@nitpicker/crawler 0.21.0 → 0.22.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.
Files changed (113) hide show
  1. package/lib/append-retry-failed-common-setup-phases.d.ts +1 -1
  2. package/lib/append-retry-failed-common-setup-phases.js +5 -1
  3. package/lib/append-setup-phases.d.ts +1 -1
  4. package/lib/archive/archive.d.ts +57 -8
  5. package/lib/archive/archive.js +83 -12
  6. package/lib/archive/create-adjunct-tables.d.ts +3 -2
  7. package/lib/archive/create-adjunct-tables.js +12 -9
  8. package/lib/archive/create-entity-tables.js +3 -0
  9. package/lib/archive/database.d.ts +39 -7
  10. package/lib/archive/database.js +49 -9
  11. package/lib/archive/db-ops/_shared/keyset-paginate-by-id.d.ts +49 -0
  12. package/lib/archive/db-ops/_shared/keyset-paginate-by-id.js +69 -0
  13. package/lib/archive/db-ops/_shared/resolve-content-item-id.d.ts +13 -12
  14. package/lib/archive/db-ops/_shared/resolve-content-item-id.js +63 -31
  15. package/lib/archive/db-ops/_shared/types.d.ts +39 -0
  16. package/lib/archive/db-ops/analysis/replace-analysis-violations.js +7 -4
  17. package/lib/archive/db-ops/config/get-created-cwd.d.ts +11 -0
  18. package/lib/archive/db-ops/config/get-created-cwd.js +13 -0
  19. package/lib/archive/db-ops/config/info-column-allowlist.js +1 -0
  20. package/lib/archive/db-ops/dedupe-cap/list-dedupe-cap-observations.d.ts +57 -0
  21. package/lib/archive/db-ops/dedupe-cap/list-dedupe-cap-observations.js +87 -0
  22. package/lib/archive/db-ops/errors/insert-page-error.js +3 -1
  23. package/lib/archive/db-ops/lifecycle/init.d.ts +13 -6
  24. package/lib/archive/db-ops/lifecycle/init.js +30 -10
  25. package/lib/archive/db-ops/list-reconcile/record-list-reconcile-run.d.ts +22 -0
  26. package/lib/archive/db-ops/{inventory/record-inventory-run.js → list-reconcile/record-list-reconcile-run.js} +11 -10
  27. package/lib/archive/db-ops/pages/read/build-page-query.js +1 -1
  28. package/lib/archive/db-ops/pages/read/get-crawling-state.d.ts +50 -3
  29. package/lib/archive/db-ops/pages/read/get-crawling-state.js +68 -5
  30. package/lib/archive/db-ops/pages/reset/clear-page-derived-rows.d.ts +20 -0
  31. package/lib/archive/db-ops/pages/reset/clear-page-derived-rows.js +37 -0
  32. package/lib/archive/db-ops/pages/reset/repromote-external-pages.d.ts +3 -2
  33. package/lib/archive/db-ops/pages/reset/repromote-external-pages.js +17 -37
  34. package/lib/archive/db-ops/pages/reset/reset-failed-pages.d.ts +22 -1
  35. package/lib/archive/db-ops/pages/reset/reset-failed-pages.js +79 -33
  36. package/lib/archive/db-ops/pages/reset/reset-pages-by-urls.d.ts +78 -0
  37. package/lib/archive/db-ops/pages/reset/reset-pages-by-urls.js +146 -0
  38. package/lib/archive/db-ops/pages/reset/retryable-image-scan-codes.d.ts +24 -0
  39. package/lib/archive/db-ops/pages/reset/retryable-image-scan-codes.js +24 -0
  40. package/lib/archive/db-ops/pages/write/insert-inventory-content-items.js +2 -1
  41. package/lib/archive/db-ops/pages/write/insert-page.js +4 -2
  42. package/lib/archive/db-ops/pages/write/link-redirect-sources.js +3 -1
  43. package/lib/archive/db-ops/pages/write/record-redirect.js +1 -1
  44. package/lib/archive/db-ops/pages/write/set-skipped-page.js +3 -1
  45. package/lib/archive/db-ops/pages/write/update-page.d.ts +9 -1
  46. package/lib/archive/db-ops/pages/write/update-page.js +36 -6
  47. package/lib/archive/db-ops/resources/get-resource-url-list.d.ts +3 -6
  48. package/lib/archive/db-ops/resources/get-resource-url-list.js +10 -35
  49. package/lib/archive/init-schema.d.ts +1 -1
  50. package/lib/archive/init-schema.js +3 -2
  51. package/lib/archive/meta/compute-main-contents-denormalized.d.ts +11 -3
  52. package/lib/archive/meta/compute-main-contents-denormalized.js +14 -2
  53. package/lib/archive/meta/types.d.ts +24 -0
  54. package/lib/archive/migrate-content-items-is-metadata-only.d.ts +44 -0
  55. package/lib/archive/migrate-content-items-is-metadata-only.js +60 -0
  56. package/lib/archive/migrate-info-created-cwd.d.ts +17 -0
  57. package/lib/archive/migrate-info-created-cwd.js +36 -0
  58. package/lib/archive/migrate-inventory-runs-to-list-reconcile-runs.d.ts +34 -0
  59. package/lib/archive/migrate-inventory-runs-to-list-reconcile-runs.js +51 -0
  60. package/lib/archive/{migrate-inventory-runs-exclude-skipped.d.ts → migrate-list-reconcile-runs-exclude-skipped.d.ts} +8 -8
  61. package/lib/archive/{migrate-inventory-runs-exclude-skipped.js → migrate-list-reconcile-runs-exclude-skipped.js} +12 -12
  62. package/lib/archive/migrate-list-reconcile-runs-invalid-skipped.d.ts +16 -0
  63. package/lib/archive/migrate-list-reconcile-runs-invalid-skipped.js +35 -0
  64. package/lib/archive/migrate-page-meta-image-scan.d.ts +27 -0
  65. package/lib/archive/migrate-page-meta-image-scan.js +52 -0
  66. package/lib/archive/page.d.ts +12 -0
  67. package/lib/archive/page.js +16 -0
  68. package/lib/archive/types.d.ts +97 -10
  69. package/lib/compute-auto-retry-backoff-delay.d.ts +30 -0
  70. package/lib/compute-auto-retry-backoff-delay.js +36 -0
  71. package/lib/crawler/apply-crawl-runtime-options-patch.d.ts +32 -0
  72. package/lib/crawler/apply-crawl-runtime-options-patch.js +129 -0
  73. package/lib/crawler/crawler.d.ts +35 -3
  74. package/lib/crawler/crawler.js +486 -338
  75. package/lib/crawler/dedupe/build-dedupe-cap-observation.d.ts +74 -0
  76. package/lib/crawler/dedupe/build-dedupe-cap-observation.js +97 -0
  77. package/lib/crawler/dedupe/compute-meta-signature.d.ts +7 -5
  78. package/lib/crawler/dedupe/compute-meta-signature.js +0 -0
  79. package/lib/crawler/dedupe/compute-shape-key.d.ts +20 -0
  80. package/lib/crawler/dedupe/compute-shape-key.js +73 -1
  81. package/lib/crawler/dedupe/dedupe-cap-tracker.d.ts +6 -1
  82. package/lib/crawler/dedupe/dedupe-cap-tracker.js +6 -1
  83. package/lib/crawler/dedupe/resolve-og-url-mismatch.d.ts +7 -5
  84. package/lib/crawler/dedupe/resolve-og-url-mismatch.js +5 -3
  85. package/lib/crawler/dedupe/types.d.ts +18 -0
  86. package/lib/crawler/fetch-destination.js +1 -0
  87. package/lib/crawler/link-list.d.ts +9 -1
  88. package/lib/crawler/link-list.js +12 -2
  89. package/lib/crawler/link-to-page-data.js +1 -0
  90. package/lib/crawler/resource-to-page-data.js +1 -0
  91. package/lib/crawler/types.d.ts +75 -0
  92. package/lib/crawler-orchestrator.d.ts +171 -8
  93. package/lib/crawler-orchestrator.js +1184 -234
  94. package/lib/crawler.d.ts +3 -0
  95. package/lib/crawler.js +3 -0
  96. package/lib/delay-or-abort.d.ts +20 -0
  97. package/lib/delay-or-abort.js +35 -0
  98. package/lib/pending-urls-remain-error.d.ts +35 -0
  99. package/lib/pending-urls-remain-error.js +43 -0
  100. package/lib/recrawl-setup-phases.d.ts +38 -0
  101. package/lib/recrawl-setup-phases.js +52 -0
  102. package/lib/resume-setup-phases.d.ts +1 -1
  103. package/lib/resume-setup-phases.js +5 -1
  104. package/lib/retry-failed-setup-phases.d.ts +1 -1
  105. package/lib/setup-recovery-phase-labels.d.ts +17 -8
  106. package/lib/setup-recovery-phase-labels.js +17 -8
  107. package/lib/types.d.ts +62 -12
  108. package/lib/utils/compute-file-sha256.d.ts +1 -1
  109. package/lib/utils/compute-file-sha256.js +1 -1
  110. package/package.json +4 -4
  111. package/lib/archive/db-ops/inventory/record-inventory-run.d.ts +0 -21
  112. package/lib/archive/migrate-inventory-runs-invalid-skipped.d.ts +0 -16
  113. package/lib/archive/migrate-inventory-runs-invalid-skipped.js +0 -35
@@ -8,9 +8,11 @@ import { APPEND_SETUP_PHASES } from './append-setup-phases.js';
8
8
  import Archive from './archive/archive.js';
9
9
  import { copyFileWithProgress } from './archive/filesystem/copy-file-with-progress.js';
10
10
  import { REQUIRED_FORMAT_VERSION } from './archive/meta/assert-compatible-version.js';
11
+ import { computeAutoRetryBackoffDelayMs } from './compute-auto-retry-backoff-delay.js';
11
12
  import { clearDestinationCache } from './crawler/clear-destination-cache.js';
12
13
  import { clearDnsBurnedHostCache } from './crawler/clear-dns-burned-host-cache.js';
13
14
  import Crawler from './crawler/crawler.js';
15
+ import { buildDedupeCapObservation } from './crawler/dedupe/build-dedupe-cap-observation.js';
14
16
  import { dnsBurnedHostCache } from './crawler/dns-burned-host-cache.js';
15
17
  import { dnsBurnedHostShortCircuitCounter } from './crawler/dns-burned-host-short-circuit-counter.js';
16
18
  import { findScopeEntry } from './crawler/find-scope-entry.js';
@@ -20,8 +22,11 @@ import { PreloadShortCircuitError } from './crawler/preload-short-circuit-error.
20
22
  import { protocolAgnosticKey } from './crawler/protocol-agnostic-key.js';
21
23
  import { shouldSkipUrl } from './crawler/should-skip-url.js';
22
24
  import { crawlerLog, log } from './debug.js';
25
+ import { delayOrAbort } from './delay-or-abort.js';
23
26
  import { INVENTORY_SETUP_PHASES } from './inventory-setup-phases.js';
24
27
  import { normalizeToArray } from './normalize-to-array.js';
28
+ import { PendingUrlsRemainError } from './pending-urls-remain-error.js';
29
+ import { RECRAWL_SETUP_PHASES } from './recrawl-setup-phases.js';
25
30
  import { resolveOutputPath } from './resolve-output-path.js';
26
31
  import { resourceRowToLookupResult } from './resource-row-to-lookup-result.js';
27
32
  import { RESUME_SETUP_PHASES } from './resume-setup-phases.js';
@@ -29,7 +34,7 @@ import { RETRY_FAILED_SETUP_PHASES } from './retry-failed-setup-phases.js';
29
34
  import { SETUP_RECOVERY_PHASE_LABELS } from './setup-recovery-phase-labels.js';
30
35
  import { cleanObject } from './utils/object/clean-object.js';
31
36
  import { WriteQueue } from './write-queue.js';
32
- const [RECOVERY_RESTORE_FROM_BACKUP, RECOVERY_PERSIST_INGESTED_STATE] = SETUP_RECOVERY_PHASE_LABELS;
37
+ const [RECOVERY_RESTORE_FROM_BACKUP, RECOVERY_LEAVE_STATE_FOR_RESUME] = SETUP_RECOVERY_PHASE_LABELS;
33
38
  /**
34
39
  * Default list of external URL prefixes excluded from crawling.
35
40
  * Includes social media sharing endpoints that are commonly linked
@@ -73,8 +78,27 @@ export const DEFAULT_EXCLUDED_EXTERNAL_URLS = [
73
78
  export class CrawlerOrchestrator extends EventEmitter {
74
79
  /** The archive instance for persisting crawl results to SQLite + tar. */
75
80
  #archive;
81
+ /**
82
+ * Set when the archive's own `'error'` event fires (a DB/storage-level
83
+ * failure — see the constructor's listener), so
84
+ * `#crawlUntilPendingClears` can tell "the session ended because pages
85
+ * are still pending" apart from "the underlying storage broke" (issue
86
+ * #350). Retrying scrape work cannot fix the latter, so the auto-retry
87
+ * loop re-throws it immediately instead of burning retry attempts
88
+ * against it — `crawling()`'s own promise resolves normally either way
89
+ * (the constructor's listener only aborts the crawler; it does not
90
+ * reject anything), so this flag is the only way to distinguish the
91
+ * two after the fact.
92
+ */
93
+ #archiveFailure = null;
76
94
  /** The crawler engine that discovers and scrapes pages. */
77
95
  #crawler;
96
+ /**
97
+ * Monotonic counter bumped on every `crawling()` call — see that
98
+ * method's JSDoc for why its listeners key off this instead of relying
99
+ * on listener removal.
100
+ */
101
+ #crawlGeneration = 0;
78
102
  /**
79
103
  * `dedupe_cap_events.id` for each shape confirmed capped this session, so
80
104
  * `crawlEnd` can look up the right row to finalize with
@@ -86,6 +110,18 @@ export class CrawlerOrchestrator extends EventEmitter {
86
110
  #dedupeCapEventIds = new Map();
87
111
  /** Whether the crawl was started from a pre-defined URL list (non-recursive mode). */
88
112
  #fromList;
113
+ /**
114
+ * The caller-owned `Lanes` instance, if any — see `CrawlConfig.lanes`'s
115
+ * JSDoc. Used by `#crawlUntilPendingClears`'s auto-retry wait to render
116
+ * through `Lanes#header` instead of `console.error` when present (and
117
+ * {@link #verbose} is `false` — see that field's JSDoc for why verbose
118
+ * excludes this path), since an injected `Lanes` stays alive across
119
+ * auto-retry rounds (unlike `deal()`'s own `Lanes`, which closes each
120
+ * round) and a bare `console.error` would corrupt its live frame.
121
+ */
122
+ #lanes;
123
+ /** See `CrawlConfig.maxAutoRetry`'s JSDoc. */
124
+ #maxAutoRetry;
89
125
  /**
90
126
  * The `network_outages` row id for the currently-open outage, or `null`
91
127
  * when none is open. Set by the `networkOutageConfirmed` handler (once
@@ -97,6 +133,41 @@ export class CrawlerOrchestrator extends EventEmitter {
97
133
  #openNetworkOutageId = null;
98
134
  /** `startedAt` of the currently-open outage, tracked alongside {@link #openNetworkOutageId} so `networkOutageRecovered` can compute a duration for {@link networkOutageSummaryCounter}. */
99
135
  #openNetworkOutageStartedAt = null;
136
+ /**
137
+ * Set for the duration of {@link updateRuntimeOptions}'s enqueued
138
+ * `archive.updateConfig()` call — the constructor's `Archive` `'error'`
139
+ * listener checks this to skip its normal fatal handling (setting
140
+ * {@link #archiveFailure}, aborting the crawler, emitting `'error'`) for
141
+ * that one write. A failure there means only that the new
142
+ * `parallels`/`interval`/exclude values won't survive a later
143
+ * `--resume`/`--append`/`--retry-failed` — the in-memory change already
144
+ * took effect (`Crawler#updateRuntimeOptions` runs synchronously, before
145
+ * this write is even enqueued) and the crawl itself is otherwise
146
+ * unaffected, so treating it as crawl-fatal (like a real page/resource
147
+ * write failure, which DOES indicate DB corruption) would let a
148
+ * transient DB conflict on an optional persistence write cut short a
149
+ * multi-hour crawl over nothing worse than "an exclude pattern won't be
150
+ * remembered on resume." Safe without additional locking: every write
151
+ * this class issues — this one included — is serialized through the same
152
+ * {@link #writeQueue}, so at most one write (and therefore at most one
153
+ * meaning for this flag) is ever in flight at a time.
154
+ */
155
+ #persistingRuntimeOptionsPatch = false;
156
+ /**
157
+ * Mirrors `CrawlerOptions.verbose` (forwarded to `Crawler` at
158
+ * construction). `#crawlUntilPendingClears`'s auto-retry wait reads this
159
+ * alongside {@link #lanes}: `Lanes#header()` only queues its text in
160
+ * verbose mode (prefixed onto the *next* `update()` call) rather than
161
+ * writing immediately, so routing the auto-retry wait message through it
162
+ * while verbose would leave that message effectively invisible for the
163
+ * whole backoff wait — a regression from the unconditional
164
+ * `console.error` this replaced, which always printed immediately. Verbose
165
+ * mode falls back to `console.error` instead, matching its pre-`#lanes`
166
+ * behavior exactly (verbose output is append-only lines anyway, so an
167
+ * interleaved `console.error` line is harmless there, unlike in
168
+ * non-verbose mode where it would corrupt the live frame).
169
+ */
170
+ #verbose;
100
171
  /** Serializes archive writes from crawler event handlers (FIFO). */
101
172
  #writeQueue = new WriteQueue();
102
173
  /**
@@ -109,15 +180,26 @@ export class CrawlerOrchestrator extends EventEmitter {
109
180
  constructor(archive, options) {
110
181
  super();
111
182
  this.#fromList = !!options?.list;
183
+ this.#maxAutoRetry = options?.maxAutoRetry ?? 3;
112
184
  this.#archive = archive;
113
185
  this.#archive.on('error', (e) => {
186
+ const error = e instanceof Error ? e : new Error(String(e));
187
+ if (this.#persistingRuntimeOptionsPatch) {
188
+ // See `#persistingRuntimeOptionsPatch`'s JSDoc for why this one
189
+ // write's failure does not escalate to `#archiveFailure`/abort/
190
+ // `'error'` — only debug-logged (`DEBUG=Nitpicker:*`), matching
191
+ // this class's other best-effort-write logging.
192
+ log('updateRuntimeOptions: archive.updateConfig failed (non-fatal): %O', error);
193
+ return;
194
+ }
195
+ this.#archiveFailure = error;
114
196
  this.#crawler.abort();
115
197
  void this.emit('error', {
116
198
  pid: process.pid,
117
199
  isMainProcess: true,
118
200
  url: null,
119
201
  isExternal: false,
120
- error: e instanceof Error ? e : new Error(String(e)),
202
+ error: this.#archiveFailure,
121
203
  });
122
204
  });
123
205
  const defaultUserAgent = `Nitpicker/${pkg.version}`;
@@ -180,12 +262,18 @@ export class CrawlerOrchestrator extends EventEmitter {
180
262
  networkProbe: options?.networkProbe ?? null,
181
263
  dedupeCap: options?.dedupeCap ?? null,
182
264
  dedupeMapCap: options?.dedupeMapCap,
183
- // Only the four resuming-session static methods
184
- // (`append`/`inventory`/`retryFailed`/`resume`) pass this — a
185
- // fresh `crawling()` has no archive history to seed from (see
186
- // `CrawlConfig.preloadedStickyShapeKeys`'s JSDoc).
265
+ // Only the five resuming-session static methods
266
+ // (`append`/`inventory`/`recrawl`/`retryFailed`/`resume`) pass
267
+ // this — a fresh `crawling()` has no archive history to seed from
268
+ // (see `CrawlConfig.preloadedStickyShapeKeys`'s JSDoc).
187
269
  preloadedStickyShapeKeys: options?.preloadedStickyShapeKeys ?? [],
270
+ // Same five methods, same rationale (see
271
+ // `CrawlConfig.preloadedDedupeObservations`'s JSDoc).
272
+ preloadedDedupeObservations: options?.preloadedDedupeObservations ?? [],
273
+ lanes: options?.lanes,
188
274
  });
275
+ this.#lanes = options?.lanes;
276
+ this.#verbose = options?.verbose ?? false;
189
277
  }
190
278
  /**
191
279
  * Enables `await using orchestrator = ...`. Closes the archive (write
@@ -233,23 +321,74 @@ export class CrawlerOrchestrator extends EventEmitter {
233
321
  * Sets up event listeners on the crawler, starts crawling, and resolves
234
322
  * when the crawl completes. Discovered pages, external pages, skipped pages,
235
323
  * and resources are forwarded to the archive for storage.
324
+ *
325
+ * Safe to call more than once on the same instance —
326
+ * `#crawlUntilPendingClears` (issue #350) re-invokes this for each
327
+ * auto-retry attempt against the same long-lived `#crawler`. `Crawler`
328
+ * (`TypedAwaitEventEmitter`) has no listener-removal API, so a second
329
+ * call cannot replace the first call's listeners — it can only stack
330
+ * another set alongside them. Every listener this method attaches is
331
+ * instead guarded by a monotonic generation counter (`isCurrent()`,
332
+ * defined below): once a later call bumps it, every earlier call's
333
+ * listeners permanently fail the check and become inert no-ops, leaving
334
+ * exactly the latest call's listeners actually writing anything.
236
335
  * @param list - The list of parsed URLs to crawl. May be empty when a resumed
237
336
  * session already has pending pages queued (for example `--retry-failed`).
238
337
  * @param opts - Optional crawl overrides.
239
338
  * @param opts.recursive - Whether discovered URLs are followed. Defaults to
240
339
  * `!fromList` (recursive unless the archive was created from a URL list), so
241
340
  * existing callers keep their behaviour; the retry flow passes it explicitly.
341
+ * @param opts.suppressFlushNotice - Skip emitting `flushingPendingWrites`
342
+ * (issue #350). Set by `#crawlUntilPendingClears` for every auto-retry
343
+ * attempt after the first: that event starts the CLI's crawl-tail
344
+ * `TaskList` (`attach-crawl-display.ts`), which must stay closed until
345
+ * the whole retry loop is done — a second `deal()`/`Lanes` cycle
346
+ * starting while that `TaskList` is still open would corrupt the
347
+ * display (see ARCHITECTURE.md's `Lanes`/`Display` single-instance
348
+ * invariant). The write-queue drain itself is unaffected; only the
349
+ * CLI-facing progress event is skipped.
350
+ * @param opts.isRetryContinuation - Forwarded to `Crawler#start()`
351
+ * (issue #350). Set by `#crawlUntilPendingClears` for every auto-retry
352
+ * attempt after the first, so `#runDeal` preserves cross-attempt
353
+ * learned state (known-good hosts, outage-detector window) instead of
354
+ * discarding it as if this were an unrelated fresh session.
242
355
  * @returns A promise that resolves when crawling is complete.
243
356
  */
244
357
  async crawling(list, opts) {
245
358
  const writeQueue = this.#writeQueue;
359
+ // Same value passed to `Crawler#start()` below (line ~822) — computed
360
+ // once here so the `setPage`/`setExternalPage` listeners can forward
361
+ // it for `is_metadata_only` (#369) without recomputing the default.
362
+ const recursive = opts?.recursive ?? !this.#fromList;
246
363
  // Per-session state, like `Crawler`'s own `#successfulHosts.clear()` /
247
364
  // `#networkGate.open()` reset at the start of `#runDeal` — a fresh
248
365
  // session must not inherit a dangling outage id from a prior one.
249
366
  this.#openNetworkOutageId = null;
250
367
  this.#openNetworkOutageStartedAt = null;
368
+ // `Crawler` (`TypedAwaitEventEmitter`) has no listener-removal API, so
369
+ // a second call on the same instance (an auto-retry attempt, issue
370
+ // #350) cannot replace the first call's listeners — it can only add
371
+ // another set alongside them. Every listener below is instead guarded
372
+ // by `isCurrent()`, keyed off a monotonic generation counter bumped
373
+ // here: once a later call starts, every earlier call's listeners
374
+ // permanently fail this check and become inert no-ops (their
375
+ // `writeQueue`/`#archive` side effects never run), leaving exactly
376
+ // one "live" set — this call's — actually writing anything.
377
+ const generation = ++this.#crawlGeneration;
378
+ const isCurrent = () => generation === this.#crawlGeneration;
379
+ // The ONLY way any listener below reaches `this.#crawler.on()` — a
380
+ // structural guarantee (not a per-listener discipline a future edit
381
+ // could forget) that no handler can run without the `isCurrent()`
382
+ // check, however many are added here in the future.
383
+ const registerGuarded = (event, handler) => {
384
+ this.#crawler.on(event, (payload) => {
385
+ if (!isCurrent())
386
+ return;
387
+ handler(payload);
388
+ });
389
+ };
251
390
  return new Promise((resolve, reject) => {
252
- this.#crawler.on('error', (error) => {
391
+ registerGuarded('error', (error) => {
253
392
  if (error.error instanceof PreloadShortCircuitError) {
254
393
  // DNS-burned host short-circuit: the underlying cause already
255
394
  // lives in `crawl_errors` from the original DNS failure.
@@ -268,33 +407,33 @@ export class CrawlerOrchestrator extends EventEmitter {
268
407
  .catch((writeError) => reject(writeError));
269
408
  void this.emit('error', error);
270
409
  });
271
- this.#crawler.on('page', ({ result, source, bodyHash }) => {
410
+ registerGuarded('page', ({ result, source, bodyHash }) => {
272
411
  writeQueue
273
- .enqueue(() => this.#archive.setPage(result, source, bodyHash))
412
+ .enqueue(() => this.#archive.setPage(result, source, bodyHash, recursive))
274
413
  .catch((error) => reject(error));
275
414
  });
276
- this.#crawler.on('externalPage', ({ result, source }) => {
415
+ registerGuarded('externalPage', ({ result, source }) => {
277
416
  writeQueue
278
- .enqueue(() => this.#archive.setExternalPage(result, source))
417
+ .enqueue(() => this.#archive.setExternalPage(result, source, recursive))
279
418
  .catch((error) => reject(error));
280
419
  });
281
- this.#crawler.on('skip', ({ url, reason, isExternal }) => {
420
+ registerGuarded('skip', ({ url, reason, isExternal }) => {
282
421
  writeQueue
283
422
  .enqueue(() => this.#archive.setSkippedPage(url, reason, isExternal))
284
423
  .catch((error) => reject(error));
285
424
  });
286
- this.#crawler.on('pageError', ({ url, phase, message, isExternal }) => {
425
+ registerGuarded('pageError', ({ url, phase, message, isExternal }) => {
287
426
  writeQueue
288
427
  .enqueue(() => this.#archive.addPageError(url, phase, message, isExternal))
289
428
  .catch((error) => reject(error));
290
429
  });
291
- this.#crawler.on('redirect', ({ result, source }) => {
430
+ registerGuarded('redirect', ({ result, source }) => {
292
431
  writeQueue
293
432
  .enqueue(() => this.#archive.setRedirect(result, source))
294
433
  .catch((error) => reject(error));
295
434
  void this.emit('redirect', { result });
296
435
  });
297
- this.#crawler.on('networkOutageConfirmed', ({ startedAt, detectedAt, probeHost, triggerErrorCount, triggerHostCount }) => {
436
+ registerGuarded('networkOutageConfirmed', ({ startedAt, detectedAt, probeHost, triggerErrorCount, triggerHostCount }) => {
298
437
  crawlerLog('Network outage confirmed: probeHost=%s triggerErrorCount=%d triggerHostCount=%d', probeHost, triggerErrorCount, triggerHostCount);
299
438
  // Rare anomaly notice, printed unconditionally even though this
300
439
  // fires while `deal()`'s own crawl-time `Lanes` is actively
@@ -324,7 +463,7 @@ export class CrawlerOrchestrator extends EventEmitter {
324
463
  })
325
464
  .catch((error) => reject(error));
326
465
  });
327
- this.#crawler.on('networkOutageRecovered', ({ endedAt }) => {
466
+ registerGuarded('networkOutageRecovered', ({ endedAt }) => {
328
467
  // The `id` read is deferred to INSIDE the queued closure, not
329
468
  // read synchronously here, because `networkOutageConfirmed`'s
330
469
  // INSERT is itself only queued (not awaited) when that event
@@ -360,7 +499,7 @@ export class CrawlerOrchestrator extends EventEmitter {
360
499
  })
361
500
  .catch((error) => reject(error));
362
501
  });
363
- this.#crawler.on('dedupeCap', ({ shapeKey, sampleUrl, bodyHash, effectiveThreshold, observedCount }) => {
502
+ registerGuarded('dedupeCap', ({ shapeKey, sampleUrl, bodyHash, effectiveThreshold, observedCount }) => {
364
503
  crawlerLog('Dedupe cap reached: shapeKey=%s effectiveThreshold=%d observedCount=%d', shapeKey, effectiveThreshold, observedCount);
365
504
  console.error(`[dedupe-cap] same-cluster trap confirmed: ${shapeKey} (sample: ${sampleUrl})`);
366
505
  writeQueue
@@ -377,27 +516,27 @@ export class CrawlerOrchestrator extends EventEmitter {
377
516
  })
378
517
  .catch((error) => reject(error));
379
518
  });
380
- this.#crawler.on('response', ({ resource, source }) => {
519
+ registerGuarded('response', ({ resource, source }) => {
381
520
  writeQueue
382
521
  .enqueue(() => this.#archive.setResources(resource, source))
383
522
  .catch((error) => reject(error));
384
523
  });
385
- this.#crawler.on('responseReferrers', (resource) => {
524
+ registerGuarded('responseReferrers', (resource) => {
386
525
  writeQueue
387
526
  .enqueue(() => this.#archive.setResourcesReferrers(resource))
388
527
  .catch((error) => reject(error));
389
528
  });
390
- this.#crawler.on('consoleLogs', ({ pageUrl, redirectPaths, entries }) => {
529
+ registerGuarded('consoleLogs', ({ pageUrl, redirectPaths, entries }) => {
391
530
  writeQueue
392
531
  .enqueue(() => this.#archive.setConsoleLogs(pageUrl, redirectPaths, entries))
393
532
  .catch((error) => reject(error));
394
533
  });
395
- this.#crawler.on('crawlEnd', () => {
534
+ registerGuarded('crawlEnd', () => {
396
535
  // Read BEFORE enqueuing the dedupeCap-finalize closure below
397
536
  // (issue #294) so this reflects genuine backlog from the
398
537
  // crawl's own page/resource writes, not the finalize
399
538
  // closure's own, always-present entry.
400
- if (writeQueue.pending > 0) {
539
+ if (writeQueue.pending > 0 && !opts?.suppressFlushNotice) {
401
540
  void this.emit('flushingPendingWrites', { pending: writeQueue.pending });
402
541
  }
403
542
  // Deferred to INSIDE a queued closure, not read synchronously
@@ -450,7 +589,10 @@ export class CrawlerOrchestrator extends EventEmitter {
450
589
  .then(() => resolve())
451
590
  .catch((error) => reject(error));
452
591
  });
453
- this.#crawler.start(list, { recursive: opts?.recursive ?? !this.#fromList });
592
+ this.#crawler.start(list, {
593
+ recursive,
594
+ isRetryContinuation: opts?.isRetryContinuation,
595
+ });
454
596
  });
455
597
  }
456
598
  /**
@@ -482,6 +624,58 @@ export class CrawlerOrchestrator extends EventEmitter {
482
624
  getUndeadPid() {
483
625
  return this.#crawler.getUndeadPid();
484
626
  }
627
+ /**
628
+ * Applies a runtime change to the in-progress crawl's tunable options
629
+ * (`parallels`/`interval`/the three exclude arrays — see
630
+ * {@link Crawler.updateRuntimeOptions}) and persists the resulting
631
+ * values to the archive's `info` row so a later `--resume` / `--append`
632
+ * / `--retry-failed` reuses them (`Archive#updateConfig`).
633
+ *
634
+ * The in-memory change takes effect immediately, before this method
635
+ * returns. The archive write is enqueued on {@link #writeQueue} — so it
636
+ * is ordered relative to the crawl's own page/resource writes — but not
637
+ * awaited: this method is synchronous so a caller (e.g. the CLI reading
638
+ * a console command) can report the new value back without waiting on
639
+ * disk I/O. A failure in that write does NOT abort the crawl or set
640
+ * {@link #archiveFailure} — see {@link #persistingRuntimeOptionsPatch}'s
641
+ * JSDoc for why this one write is deliberately exempted from the fatal
642
+ * handling every other archive write gets; it is only debug-logged
643
+ * (`DEBUG=Nitpicker:*`).
644
+ * @param patch - The runtime change to apply.
645
+ * @returns A snapshot of the tunable options after applying `patch`.
646
+ * @throws {RangeError} If `parallels` is present and not an integer `>= 1`, or `interval` is present and not an integer `>= 0`.
647
+ * @throws {TypeError} If any exclude entry is present and not a non-empty string.
648
+ * @example
649
+ * ```ts
650
+ * const snapshot = orchestrator.updateRuntimeOptions({ parallels: 4 });
651
+ * console.log(snapshot.parallels); // 4
652
+ * ```
653
+ */
654
+ updateRuntimeOptions(patch) {
655
+ const snapshot = this.#crawler.updateRuntimeOptions(patch);
656
+ this.#writeQueue
657
+ .enqueue(async () => {
658
+ this.#persistingRuntimeOptionsPatch = true;
659
+ try {
660
+ await this.#archive.updateConfig({
661
+ parallels: snapshot.parallels,
662
+ interval: snapshot.interval,
663
+ excludes: [...snapshot.excludes],
664
+ excludeUrls: [...snapshot.excludeUrls],
665
+ excludeKeywords: [...snapshot.excludeKeywords],
666
+ });
667
+ }
668
+ finally {
669
+ this.#persistingRuntimeOptionsPatch = false;
670
+ }
671
+ })
672
+ // The `Archive` `'error'` listener above already logs a failure
673
+ // here (non-fatal, see `#persistingRuntimeOptionsPatch`) — this
674
+ // catch exists only to prevent an unhandled rejection from this
675
+ // fire-and-forget enqueue.
676
+ .catch(() => { });
677
+ return snapshot;
678
+ }
485
679
  /**
486
680
  * Write the archive to its configured file path.
487
681
  *
@@ -509,6 +703,202 @@ export class CrawlerOrchestrator extends EventEmitter {
509
703
  });
510
704
  void this.emit('writeFileEnd', { filePath: this.#archive.filePath });
511
705
  }
706
+ /**
707
+ * Releases the archive handle (lock dropped, tmpDir left intact — see
708
+ * {@link Archive.releaseHandle}) and throws a {@link PendingUrlsRemainError}
709
+ * (issue #350) describing why `#crawlUntilPendingClears` gave up. Typed
710
+ * to return `never` so callers can `return this.#abandonPendingRetryLoop(...)`
711
+ * and satisfy control-flow analysis without an unreachable trailing
712
+ * `throw`.
713
+ * @param params - See the matching {@link PendingUrlsRemainError} field for each property's meaning.
714
+ * @param params.pendingCount - Pending URL count at the moment of giving up.
715
+ * @param params.attemptsMade - Auto-retry attempts actually run before giving up.
716
+ * @param params.reason - See {@link PendingUrlsRemainError}'s `reason` field.
717
+ */
718
+ async #abandonPendingRetryLoop(params) {
719
+ const { pendingCount, attemptsMade, reason } = params;
720
+ await this.#archive.releaseHandle();
721
+ throw new PendingUrlsRemainError({
722
+ pendingCount,
723
+ attemptsMade,
724
+ maxAutoRetry: this.#maxAutoRetry,
725
+ reason,
726
+ stubPath: this.#archive.tmpDir,
727
+ });
728
+ }
729
+ /**
730
+ * Runs `crawling()` and, if the session ends with pages still pending
731
+ * (issue #350), automatically re-queues them and re-runs the crawl loop
732
+ * up to `#maxAutoRetry` times with an exponential backoff between
733
+ * attempts ({@link computeAutoRetryBackoffDelayMs}) before giving up.
734
+ *
735
+ * Every one of the six session-starting static factories
736
+ * (`crawling`/`append`/`inventory`/`recrawl`/`retryFailed`/`resume`)
737
+ * routes its first `crawling()` call through here instead of calling it
738
+ * directly, so that **a `.nitpicker` file existing on disk always
739
+ * implies `pending === 0`**: this method never lets a factory reach
740
+ * `orchestrator.write()` (called later by the CLI's post-crawl step)
741
+ * while pages remain unscraped. When retrying cannot (or should not)
742
+ * continue, it releases the archive handle — leaving the stub (tmpDir)
743
+ * on disk, un-packaged, lock released — and throws
744
+ * {@link PendingUrlsRemainError} so the operator can recover via
745
+ * `crawl --resume` or `--retry-failed`.
746
+ *
747
+ * Three conditions end the loop early, before `#maxAutoRetry` is reached:
748
+ * - The archive itself failed (`#archiveFailure` set by the constructor's
749
+ * `Archive` `'error'` listener — a DB/storage-level failure). Retrying
750
+ * scrape work cannot fix a broken database, so this re-throws the
751
+ * original failure immediately without releasing-and-wrapping it in a
752
+ * `PendingUrlsRemainError` — there is nothing "pending-remains"-shaped
753
+ * about a storage failure.
754
+ * - The crawl was explicitly aborted (`#crawler.signal.aborted` — the
755
+ * public `abort()` method, e.g. a caller-driven cancellation or a
756
+ * Ctrl+C proxy in tests). `AbortController.signal` cannot be
757
+ * un-aborted, so every subsequent `crawling()` call on this same
758
+ * `#crawler` would deal zero work forever — retrying would just waste
759
+ * one full backoff wait before "no progress" gives up anyway. This
760
+ * returns immediately instead, matching this method's pre-#350
761
+ * behaviour for an explicit abort: the caller gets the orchestrator
762
+ * back with pending possibly `> 0` and decides for itself (the CLI's
763
+ * own SIGINT handler never reaches this far — see `crawl.ts` — so the
764
+ * `.nitpicker` ⟹ pending = 0 invariant still holds for that path). The
765
+ * backoff wait itself is also abort-interruptible ({@link delayOrAbort}
766
+ * rather than a bare `delay()`, issue #350 code review): a library
767
+ * consumer calling `abort()` mid-wait (unlike the CLI's SIGINT path)
768
+ * must not be stuck waiting up to 5 minutes for nothing.
769
+ * - An attempt makes no dent in the pending count (unchanged or grown):
770
+ * burning the remaining budget against a cause retrying will not fix
771
+ * (e.g. a wholesale host outage) just delays the operator finding out.
772
+ * Checked AFTER the exhaustion check below it in the loop body so
773
+ * that a final attempt which is both exhausted AND made no progress
774
+ * reports as `'exhausted'` — the more actionable of the two (it tells
775
+ * the operator the budget, not just that this one attempt stalled).
776
+ * `getCrawlingState()`'s "Confirmed same-cluster trap exclusion"
777
+ * filter (issue #350) keeps a `--dedupe-cap`-confirmed shape's own
778
+ * never-scraped descendants out of `pending` in the first place, so
779
+ * `pending` genuinely converging to 0 is no longer blocked by that
780
+ * shape — a `'no-progress'` or `'exhausted'` result here now points
781
+ * at a real, currently-unresolvable fetch failure (network/host),
782
+ * not at a same-cluster trap the cap already confirmed.
783
+ *
784
+ * Each retry attempt re-reads `getCrawlingState()` and
785
+ * `getResourceUrlList()` in full — the same cost `retryFailed`/`resume`/
786
+ * `append`/`inventory` already pay once per invocation, now paid up to
787
+ * `#maxAutoRetry` additional times (bounded, default 3). Retry attempts
788
+ * pass `isRetryContinuation: true` through to `Crawler#start()` so
789
+ * `#runDeal` preserves cross-attempt learned state (known-good hosts,
790
+ * network-outage detector window) instead of discarding it as if this
791
+ * were an unrelated fresh session (issue #350 code review) — the whole
792
+ * point of retrying is to avoid re-paying that detection cost.
793
+ * @param list - Forwarded to the first `crawling()` call.
794
+ * @param opts - Forwarded to the first `crawling()` call.
795
+ * @param opts.recursive
796
+ */
797
+ async #crawlUntilPendingClears(list, opts) {
798
+ await this.crawling(list, opts);
799
+ if (this.#archiveFailure) {
800
+ throw this.#archiveFailure;
801
+ }
802
+ if (this.#crawler.signal.aborted) {
803
+ return;
804
+ }
805
+ // `list` is this call's own root/seed URLs — always a full-scrape
806
+ // target regardless of `is_metadata_only` (a root added via
807
+ // `crawler.ts`'s direct seeding path never goes through
808
+ // `processAnchors`, so the anchor-derived flag on its row, if any,
809
+ // reflects some OTHER page's anchor to the same URL, not this URL's
810
+ // own root status). Excluded here rather than never written in the
811
+ // first place — see `replaceAnchorEdges`'s `recursive` doc for why a
812
+ // root's `is_metadata_only` can be wrongly set to `1` by a
813
+ // same-crawl page that happens to link to it before it is scraped
814
+ // itself (#369).
815
+ const rootKeys = new Set(list.map((u) => u.withoutHashAndAuth));
816
+ // Fetched at most once across the whole retry loop (issue #350 code
817
+ // review), not per attempt: `getResourceUrlList()` is a full scan of
818
+ // every known resource URL, but `Crawler#resume()`'s use of it is
819
+ // just seeding the in-memory `#resources` Set — idempotent, and
820
+ // already kept current independently as the live crawl writes new
821
+ // resources during each attempt. Re-fetching the full list on every
822
+ // attempt would re-pay that scan cost for no benefit on a large
823
+ // archive. `undefined` until the first retry actually needs it, so
824
+ // the common case (pending clears without ever retrying) never
825
+ // fetches it at all.
826
+ let cachedResources;
827
+ let previousPendingCount = null;
828
+ for (let attempt = 1;; attempt++) {
829
+ // `pendingMetadataOnly` defaults to `[]`: `.filter()` runs on it a
830
+ // few lines below, and a test-mocked `Archive` may return
831
+ // `{ scraped, pending }` without the field (production's real
832
+ // `getCrawlingState()` always includes it).
833
+ const { scraped, pending, pendingMetadataOnly = [], } = await this.#archive.getCrawlingState();
834
+ if (pending.length === 0) {
835
+ return;
836
+ }
837
+ if (attempt > this.#maxAutoRetry) {
838
+ return this.#abandonPendingRetryLoop({
839
+ pendingCount: pending.length,
840
+ attemptsMade: attempt - 1,
841
+ reason: 'exhausted',
842
+ });
843
+ }
844
+ if (previousPendingCount !== null && pending.length >= previousPendingCount) {
845
+ return this.#abandonPendingRetryLoop({
846
+ pendingCount: pending.length,
847
+ attemptsMade: attempt - 1,
848
+ reason: 'no-progress',
849
+ });
850
+ }
851
+ previousPendingCount = pending.length;
852
+ const delayMs = computeAutoRetryBackoffDelayMs(attempt);
853
+ void this.emit('autoRetryWaiting', {
854
+ attempt,
855
+ maxAttempts: this.#maxAutoRetry,
856
+ pendingCount: pending.length,
857
+ delayMs,
858
+ });
859
+ // A caller-injected `#lanes` (see `CrawlConfig.lanes`'s JSDoc)
860
+ // stays alive across auto-retry rounds — unlike `deal()`'s own
861
+ // Lanes, which closes each round — so a bare `console.error`
862
+ // here would corrupt its still-live frame. Route through
863
+ // `header()` instead; its `%countdown(...)%` placeholder
864
+ // animates via the Lanes' own redraw loop, same as the
865
+ // per-URL interval wait in `crawler.ts`. `#verbose` excludes
866
+ // this path (see that field's JSDoc: `header()` only queues its
867
+ // text for the next `update()` call in verbose mode, so it would
868
+ // go effectively unseen for the whole wait). Without an injected
869
+ // `#lanes` (or while verbose), this always fires in the gap
870
+ // after `deal()`'s own Lanes has closed and before the next
871
+ // round's opens (the retry's own `crawling()` call hasn't run
872
+ // yet), so there is no active display to corrupt and
873
+ // `console.error` is safe.
874
+ if (this.#lanes && !this.#verbose) {
875
+ this.#lanes.header(`[auto-retry] ${pending.length} pending page(s) remain — retry ${attempt}/${this.#maxAutoRetry} in %countdown(${delayMs},autoRetry,s)%s`);
876
+ }
877
+ else {
878
+ // eslint-disable-next-line no-console -- see comment above
879
+ console.error(`[auto-retry] ${pending.length} pending page(s) remain — waiting ${Math.round(delayMs / 1000)}s before retry ${attempt}/${this.#maxAutoRetry}`);
880
+ }
881
+ await delayOrAbort(delayMs, this.#crawler.signal);
882
+ if (this.#crawler.signal.aborted) {
883
+ return;
884
+ }
885
+ cachedResources ??= await this.#archive.getResourceUrlList();
886
+ const pagesScrapedOffset = await this.#archive.getScrapedHtmlPageCount();
887
+ const metadataOnlyUrls = pendingMetadataOnly.filter((url) => !rootKeys.has(url));
888
+ this.#crawler.resume(pending, scraped, cachedResources, pagesScrapedOffset, metadataOnlyUrls);
889
+ await this.crawling([], {
890
+ recursive: false,
891
+ suppressFlushNotice: true,
892
+ isRetryContinuation: true,
893
+ });
894
+ if (this.#archiveFailure) {
895
+ throw this.#archiveFailure;
896
+ }
897
+ if (this.#crawler.signal.aborted) {
898
+ return;
899
+ }
900
+ }
901
+ }
512
902
  /**
513
903
  * Assign natural URL sort order to every internal page, relaying chunk
514
904
  * progress through the `sortingUrls` event (issue #294). Always runs
@@ -538,6 +928,7 @@ export class CrawlerOrchestrator extends EventEmitter {
538
928
  * @param initializedCallback - Optional callback invoked after initialization but before crawling starts.
539
929
  * @returns A promise that resolves to the CrawlerOrchestrator instance after crawling completes.
540
930
  * @throws {Error} If the URL list is empty or contains no valid URLs.
931
+ * @throws {PendingUrlsRemainError} When the crawl session ends with pages still pending after exhausting auto-retry.
541
932
  */
542
933
  static async crawling(url, options, initializedCallback) {
543
934
  const list = sortUrl(url, options);
@@ -585,6 +976,7 @@ export class CrawlerOrchestrator extends EventEmitter {
585
976
  userAgent: options?.userAgent || defaultUserAgent,
586
977
  ignoreRobots: options?.ignoreRobots ?? false,
587
978
  mainContentSelector: options?.mainContentSelector ?? null,
979
+ ...buildCreatedCwdPatch(cwd),
588
980
  });
589
981
  const orchestrator = new CrawlerOrchestrator(archive, {
590
982
  ...options,
@@ -597,7 +989,7 @@ export class CrawlerOrchestrator extends EventEmitter {
597
989
  log('Start crawling');
598
990
  log('URL %O', list.map((url) => url.href));
599
991
  log('Config %O', config);
600
- await orchestrator.crawling(list);
992
+ await orchestrator.#crawlUntilPendingClears(list);
601
993
  log('Crawling completed');
602
994
  CrawlerOrchestrator.#finalizeCrawlSession(orchestrator);
603
995
  log('Set order natural URL sort');
@@ -614,7 +1006,11 @@ export class CrawlerOrchestrator extends EventEmitter {
614
1006
  * the expanded scope are demoted back to "needs scraping" so the next pass
615
1007
  * re-fetches them as full internal pages. A `<archive>.bak` is created
616
1008
  * before the crawl and removed on success; if the crawl throws, the backup
617
- * is restored to keep the original archive intact.
1009
+ * is restored to keep the original archive intact — except when the crawl
1010
+ * ends with {@link PendingUrlsRemainError} (issue #350), where the
1011
+ * un-packaged stub itself is the recovery path and the backup is instead
1012
+ * left untouched (deleted, not restored — see
1013
+ * {@link CrawlerOrchestrator.#abandonBackupOnPendingRemains}).
618
1014
  *
619
1015
  * List-mode archives (`info.fromList === true`) are rejected because their
620
1016
  * pages are all metadata-only and cannot host a recursive append.
@@ -628,6 +1024,7 @@ export class CrawlerOrchestrator extends EventEmitter {
628
1024
  * this can't go through the orchestrator's event emitter (issue #294).
629
1025
  * @returns The orchestrator instance after the append crawl completes.
630
1026
  * @throws {Error} When `newUrls` is empty, the archive is in list mode, or it cannot be parsed.
1027
+ * @throws {PendingUrlsRemainError} When the crawl session ends with pages still pending after exhausting auto-retry.
631
1028
  */
632
1029
  static async append(archivePath, newUrls, options, initializedCallback, setupProgress) {
633
1030
  const [PHASE_EXTRACTING, PHASE_LOADING_CONFIG, PHASE_BACKING_UP, PHASE_REPROMOTING, PHASE_LOADING_DEDUPE_KEYS, PHASE_LOADING_CRAWL_STATE, PHASE_LOADING_RESOURCES, PHASE_LOADING_SCRAPED_COUNT, PHASE_RESTORING_CRAWL_STATE,] = APPEND_SETUP_PHASES;
@@ -671,6 +1068,12 @@ export class CrawlerOrchestrator extends EventEmitter {
671
1068
  fromList: false,
672
1069
  recursive: true,
673
1070
  baseUrl: mergedRoots[0],
1071
+ // Stamped for `Archive.resume` (issue #350) — this session's
1072
+ // cwd, not `options.cwd` (already spread above and dropped by
1073
+ // `updateConfig`'s allowlist): a stub left behind by THIS
1074
+ // append should resume back to where THIS command ran, not
1075
+ // wherever the original crawl happened to run from.
1076
+ ...buildCreatedCwdPatch(cwd),
674
1077
  };
675
1078
  const backupPath = absFilePath + '.bak';
676
1079
  setupProgress?.onPhase?.(PHASE_BACKING_UP);
@@ -689,22 +1092,52 @@ export class CrawlerOrchestrator extends EventEmitter {
689
1092
  await archive.repromoteExternalPages(scopeMap, archived, setupProgress?.onChunkProgress);
690
1093
  // Seed the sticky set from prior sessions' confirmed traps so
691
1094
  // `--append` does not pay the cost of re-discovering them (see
692
- // `DedupeCapTracker`'s constructor JSDoc).
1095
+ // `DedupeCapTracker`'s constructor JSDoc), and replay every
1096
+ // not-yet-capped shape's prior observations so its counter
1097
+ // does not restart at 0 (see `#preloadDedupeCapObservations`).
693
1098
  setupProgress?.onPhase?.(PHASE_LOADING_DEDUPE_KEYS);
694
- const preloadedStickyShapeKeys = await archive.listDedupeCapShapeKeys();
1099
+ // Independent reads (no data dependency) — run concurrently
1100
+ // rather than paying two sequential round-trips, the same
1101
+ // reasoning `resetFailedPages` already applies to its own
1102
+ // unrelated reads.
1103
+ const [preloadedStickyShapeKeys, preloadedDedupeObservations] = await Promise.all([
1104
+ archive.listDedupeCapShapeKeys(),
1105
+ CrawlerOrchestrator.#preloadDedupeCapObservations(archive, options?.dedupeCap ?? null, setupProgress?.onChunkProgress),
1106
+ ]);
695
1107
  const orchestrator = new CrawlerOrchestrator(archive, {
696
1108
  ...mergedConfig,
697
1109
  roots: mergedRoots,
698
1110
  preloadedStickyShapeKeys,
1111
+ preloadedDedupeObservations,
699
1112
  });
700
1113
  setupProgress?.onPhase?.(PHASE_LOADING_CRAWL_STATE);
701
- const { scraped, pending } = await archive.getCrawlingState();
1114
+ // `mergedConfig.recursive` is forced `true` above, so THIS
1115
+ // session's own anchor discovery can only mark an EXTERNAL
1116
+ // anchor as metadata-only. But `pendingMetadataOnly` can also
1117
+ // carry a STALE flag from a PRIOR session — e.g. a URL that
1118
+ // was external (or discovered under a then-non-recursive
1119
+ // config) before this `--append` call promotes it into
1120
+ // `mergedRoots`. `crawler.resume()` below runs BEFORE the new
1121
+ // roots are added via `#crawlUntilPendingClears(newParsed)`
1122
+ // (→ `LinkList#add()`), so `LinkList#add()`'s dedup would
1123
+ // silently let the stale metadataOnly flag win over the
1124
+ // root's full-scrape intent without this exclusion (issue
1125
+ // #369 code review — same class of bug the fix itself
1126
+ // targets). Re-parse `mergedRoots` (`ExURL#withoutHash` form)
1127
+ // to `withoutHashAndAuth` before comparing, matching how
1128
+ // `pendingMetadataOnly` entries are normalised (see the
1129
+ // list-mode `resume`'s identical comment).
1130
+ const { scraped, pending, pendingMetadataOnly = [], } = await archive.getCrawlingState();
1131
+ const mergedRootKeys = new Set(mergedRoots
1132
+ .map((root) => parseUrl(root, mergedConfig)?.withoutHashAndAuth)
1133
+ .filter((root) => root !== undefined));
1134
+ const metadataOnlyUrls = pendingMetadataOnly.filter((url) => !mergedRootKeys.has(url));
702
1135
  setupProgress?.onPhase?.(PHASE_LOADING_RESOURCES);
703
1136
  const resources = await archive.getResourceUrlList(setupProgress?.onChunkProgress);
704
1137
  setupProgress?.onPhase?.(PHASE_LOADING_SCRAPED_COUNT);
705
1138
  const pagesScrapedOffset = await archive.getScrapedHtmlPageCount();
706
1139
  setupProgress?.onPhase?.(PHASE_RESTORING_CRAWL_STATE);
707
- orchestrator.#crawler.resume(pending, scraped, resources, pagesScrapedOffset);
1140
+ orchestrator.#crawler.resume(pending, scraped, resources, pagesScrapedOffset, metadataOnlyUrls);
708
1141
  if (initializedCallback) {
709
1142
  await initializedCallback(orchestrator, mergedConfig);
710
1143
  }
@@ -713,13 +1146,17 @@ export class CrawlerOrchestrator extends EventEmitter {
713
1146
  log('New roots %O', newRoots);
714
1147
  log('Merged roots %O', mergedRoots);
715
1148
  await CrawlerOrchestrator.#preloadDnsBurnedHostCache(archive);
716
- await orchestrator.crawling(newParsed);
1149
+ await orchestrator.#crawlUntilPendingClears(newParsed);
717
1150
  CrawlerOrchestrator.#finalizeCrawlSession(orchestrator);
718
1151
  await orchestrator.#setUrlOrder();
719
1152
  await ignoreEnoent(unlinkFile(backupPath));
720
1153
  return orchestrator;
721
1154
  }
722
1155
  catch (error) {
1156
+ if (error instanceof PendingUrlsRemainError) {
1157
+ await CrawlerOrchestrator.#abandonBackupOnPendingRemains(setupProgress, backupPath);
1158
+ throw error;
1159
+ }
723
1160
  try {
724
1161
  setupProgress?.onPhase?.(RECOVERY_RESTORE_FROM_BACKUP);
725
1162
  await copyFileWithProgress(backupPath, absFilePath, setupProgress?.onCopyProgress);
@@ -823,6 +1260,7 @@ export class CrawlerOrchestrator extends EventEmitter {
823
1260
  * #294).
824
1261
  * @returns The orchestrator instance after a successful inventory pass.
825
1262
  * @throws {Error} When `inventoryUrls` is empty or the archive is in list mode. Unresolved pending URLs from a previous crawl do NOT throw — see step 3.
1263
+ * @throws {PendingUrlsRemainError} When the crawl session ends with pages still pending after exhausting auto-retry.
826
1264
  */
827
1265
  static async inventory(archivePath, inventoryUrls, options, initializedCallback, source = null, setupProgress) {
828
1266
  const [PHASE_EXTRACTING, PHASE_LOADING_CONFIG, PHASE_LOADING_CRAWL_STATE_PRE, PHASE_CHECKING_KNOWN_URLS, PHASE_BACKING_UP, PHASE_RECORDING_NON_HTML, PHASE_RECORDING_HTML_SEEDS, PHASE_RECORDING_EXCLUDED, PHASE_LOADING_CRAWL_STATE_POST, PHASE_LOADING_RESOURCES, PHASE_LOADING_SCRAPED_COUNT, PHASE_RESTORING_CRAWL_STATE,] = INVENTORY_SETUP_PHASES;
@@ -849,6 +1287,10 @@ export class CrawlerOrchestrator extends EventEmitter {
849
1287
  if (archived.fromList) {
850
1288
  throw new Error('Cannot run inventory on a list-mode archive: this archive was created with --list/--list-file and contains metadata-only pages. Create a fresh archive instead.');
851
1289
  }
1290
+ // Stamped for `Archive.resume` (issue #350) — a stub left behind
1291
+ // by THIS inventory run should resume back to where THIS command
1292
+ // ran, independent of `--resume`'s own invocation directory.
1293
+ await archive.updateConfig(buildCreatedCwdPatch(cwd));
852
1294
  setupProgress?.onPhase?.(PHASE_LOADING_CRAWL_STATE_PRE);
853
1295
  const { pending } = await archive.getCrawlingState();
854
1296
  if (pending.length > 0) {
@@ -894,84 +1336,16 @@ export class CrawlerOrchestrator extends EventEmitter {
894
1336
  if (source) {
895
1337
  await archive.saveInventorySourceList(source.sha256, source.bytes);
896
1338
  }
897
- // Parse + scope-classify the candidate URLs. sortUrl drops
898
- // unparseable strings; findScopeEntry separates in-scope from
899
- // out-of-scope.
900
- const parsedAll = sortUrl(inventoryUrls, archived);
901
- const scopeMap = new Map();
902
- for (const raw of archived.roots) {
903
- const parsed = parseUrl(raw, archived);
904
- if (!parsed)
905
- continue;
906
- const existing = scopeMap.get(parsed.hostname) ?? [];
907
- scopeMap.set(parsed.hostname, [...existing, parsed]);
908
- }
909
- const inScope = [];
910
- let outOfScope = 0;
911
- for (const url of parsedAll) {
912
- if (findScopeEntry(url, scopeMap, archived) === null) {
913
- outOfScope++;
914
- }
915
- else {
916
- inScope.push(url);
917
- }
918
- }
919
- if (outOfScope > 0) {
920
- log('[inventory] %d URL(s) skipped (outside archived scope: %O)', outOfScope, archived.roots);
921
- }
922
- // Drop URLs that are already represented in the archive (either
923
- // as pages or resources). Comparison key is `withoutHashAndAuth`
924
- // to mirror what `resolveContentItemId` / `insertResource` actually store.
925
- // Two independent reads — Promise.all halves the wait on large
926
- // archives where each `WHERE url IN (?)` chunk costs real I/O.
1339
+ // Parse, scope-classify, and split the candidate URLs into
1340
+ // already-known vs. novel — shared with `recrawl`, see
1341
+ // `#classifyInventoryCandidateUrls`.
927
1342
  setupProgress?.onPhase?.(PHASE_CHECKING_KNOWN_URLS);
928
- const candidateUrls = inScope.map((u) => u.withoutHashAndAuth);
929
- const [existingPageUrlList, existingResourceUrlList] = await Promise.all([
930
- archive.getExistingPageUrls(candidateUrls),
931
- archive.getExistingResourceUrls(candidateUrls),
932
- ]);
933
- const existingPageUrls = new Set(existingPageUrlList);
934
- const existingResourceUrls = new Set(existingResourceUrlList);
935
- const novelUrls = inScope.filter((u) => {
936
- const key = u.withoutHashAndAuth;
937
- return !existingPageUrls.has(key) && !existingResourceUrls.has(key);
938
- });
939
- const knownCount = existingPageUrls.size + existingResourceUrls.size;
940
- log('[inventory] %d in-scope, %d already in archive, %d new', inScope.length, knownCount, novelUrls.length);
941
- // Split the novel URLs on the exclusion config BEFORE the
942
- // HTML/non-HTML classification, so an exclude-matched URL is
943
- // recorded as a terminal skipped page instead of being imported
944
- // (issue #260). The inputs mirror the scrape phase's fetch-time
945
- // gate (`shouldSkipUrl` in `crawler.ts` fed by the constructor's
946
- // merge): archived config overlaid with this run's overrides,
947
- // and `DEFAULT_EXCLUDED_EXTERNAL_URLS` merged ahead of the
948
- // user's prefixes — classification and gate must never disagree
949
- // about the same URL. Running this AFTER the known-URL filter is
950
- // deliberate: a previously crawled row that newly matches the
951
- // exclusion config stays untouched (crawled-wins), matching how
952
- // `getExistingPageUrls` shields known rows from re-labelling.
953
- // `excludeKeywords` is deliberately absent: it matches rendered
954
- // page content, which a URL list does not have — HTML seeds
955
- // still get it at render time via the browser verdict.
1343
+ const { outOfScope, novelUrls } = await CrawlerOrchestrator.#classifyInventoryCandidateUrls(inventoryUrls, archived, archive);
1344
+ // Split the novel URLs on the exclusion config — shared with
1345
+ // `recrawl`, see `#classifyExcludedNovelUrls`. `effectiveConfig`
1346
+ // is also used below to build `baseConfig`.
956
1347
  const effectiveConfig = { ...archived, ...cleanObject(options) };
957
- const excludes = normalizeToArray(effectiveConfig.excludes);
958
- const excludeUrls = [
959
- ...DEFAULT_EXCLUDED_EXTERNAL_URLS,
960
- ...normalizeToArray(effectiveConfig.excludeUrls),
961
- ];
962
- const excludedNovelUrls = [];
963
- const importableNovelUrls = [];
964
- for (const url of novelUrls) {
965
- if (shouldSkipUrl({ url, excludes, excludeUrls, options: effectiveConfig })) {
966
- excludedNovelUrls.push(url);
967
- }
968
- else {
969
- importableNovelUrls.push(url);
970
- }
971
- }
972
- if (excludedNovelUrls.length > 0) {
973
- log('[inventory] %d URL(s) recorded as skipped (matched excludes / excludeUrls)', excludedNovelUrls.length);
974
- }
1348
+ const { excludedNovelUrls, importableNovelUrls } = CrawlerOrchestrator.#classifyExcludedNovelUrls(novelUrls, effectiveConfig);
975
1349
  if (novelUrls.length === 0) {
976
1350
  // Nothing to do — release the archive cleanly without taking a
977
1351
  // backup. The orchestrator returned here is empty; the caller
@@ -997,89 +1371,17 @@ export class CrawlerOrchestrator extends EventEmitter {
997
1371
  // clause). This flag steers the catch below.
998
1372
  let ingestionComplete = false;
999
1373
  try {
1000
- // Classify importable novel URLs by URL-extension heuristic (no I/O).
1001
- // Source file lists come from `ls` on the doc-root, so the
1002
- // extension reflects the real file type — a HEAD pre-flight
1003
- // here would be pure wasted I/O. Edge cases:
1004
- //
1005
- // - `.html` returning 404 / 200: the normal crawler HEAD/GET
1006
- // path absorbs this because every HTML-classified URL is
1007
- // fed through the dealer and gets its real HEAD/GET there.
1008
- //
1009
- // - Extensionless API endpoints (e.g. `/api/foo`) that the
1010
- // server returns as `text/html`: `isLikelyHtmlUrl` accepts
1011
- // them as HTML so the dealer's render path runs — the
1012
- // real content-type wins downstream.
1013
- //
1014
- // - `.aspx` / `.do` / `.jsp` / other server-handler
1015
- // extensions that the heuristic does NOT recognise as
1016
- // HTML: these are classified as non-HTML here, recorded
1017
- // as `resources` rows with all-null metadata, and never
1018
- // get a HEAD/GET probe. The accepted trade-off for
1019
- // `--inventory`'s "list of static-looking server files"
1020
- // contract; sites that mix server-handlers into the
1021
- // inventory list will need a follow-up `--retry-failed`
1022
- // pass (or a re-`--inventory` with the corrected list)
1023
- // to populate metadata.
1024
- //
1025
- // non-HTML rows are recorded with null status/content-type
1026
- // which is sufficient for `listUnusedResources` (referrer
1027
- // count = 0) but means downstream consumers must treat
1028
- // null as "not probed" rather than "failed".
1029
- const rawHtmlSeeds = [];
1030
- const nonHtmlSeeds = [];
1031
- for (const url of importableNovelUrls) {
1032
- if (isLikelyHtmlUrl(url)) {
1033
- rawHtmlSeeds.push(url);
1034
- }
1035
- else {
1036
- nonHtmlSeeds.push(url);
1037
- }
1038
- }
1039
- // Dedup HTML seeds by `protocolAgnosticKey` so an inventory
1040
- // list that mixes `http://` and `https://` for the same
1041
- // origin does not produce two `pages` rows that the dealer
1042
- // later collapses to one — the loser would otherwise stay
1043
- // `scraped=0, source='inventory-seed'` forever and look like
1044
- // a real recovery candidate on `--resume`. `getExistingPageUrls`
1045
- // keys on the full URL (with protocol), so it cannot catch
1046
- // the cross-scheme duplicate; this is the dedup boundary.
1047
- const seenKeys = new Set();
1048
- const htmlSeeds = [];
1049
- for (const url of rawHtmlSeeds) {
1050
- const key = protocolAgnosticKey(url.withoutHashAndAuth);
1051
- if (seenKeys.has(key)) {
1052
- continue;
1053
- }
1054
- seenKeys.add(key);
1055
- htmlSeeds.push(url);
1056
- }
1057
- // Bulk-record non-HTML novel URLs in `resources` as
1058
- // `source='inventory-seed'` placeholders. A
1059
- // per-URL `await setResources(...)` loop would spend minutes
1060
- // inside the `.bak`-protected window on large inventory
1061
- // lists; the chunked bulk path collapses N round-trips
1062
- // to N/500.
1063
- setupProgress?.onPhase?.(PHASE_RECORDING_NON_HTML);
1064
- await archive.insertInventoryResources(nonHtmlSeeds);
1065
- // Pre-insert HTML seeds as `scraped = 0`,
1066
- // `source = 'inventory-seed'` placeholders *before* the
1067
- // scrape phase, so a Ctrl+C between here and `setPage`
1068
- // cannot lose the URL. The strict-pending set picks
1069
- // these rows up on the next `--resume` via the
1070
- // `OR p.source != 'crawled'` clause.
1071
- setupProgress?.onPhase?.(PHASE_RECORDING_HTML_SEEDS);
1072
- await archive.insertInventorySeeds(htmlSeeds);
1073
- // Record exclude-matched novel URLs as terminal skipped pages
1074
- // (`is_skipped=1`, `skip_reason='excluded'`,
1075
- // `source='inventory-seed'`) — the same end state the normal
1076
- // crawl's fetch-time gate produces for link-discovered
1077
- // excluded URLs, so the archive looks identical no matter
1078
- // how the URL was discovered. Inside the `.bak` window for
1079
- // the same all-or-nothing reason as the seed inserts above.
1080
- setupProgress?.onPhase?.(PHASE_RECORDING_EXCLUDED);
1081
- await archive.insertInventorySkippedPages(excludedNovelUrls);
1082
- log('[inventory] %d HTML seed(s), %d non-HTML resource(s), %d skipped page(s) recorded', htmlSeeds.length, nonHtmlSeeds.length, excludedNovelUrls.length);
1374
+ // Classify, dedup, and bulk-record the novel URLs — shared
1375
+ // with `recrawl`, see `#ingestNovelSeeds`.
1376
+ const { htmlSeeds, nonHtmlSeeds } = await CrawlerOrchestrator.#ingestNovelSeeds({
1377
+ archive,
1378
+ importableNovelUrls,
1379
+ excludedNovelUrls,
1380
+ setupProgress,
1381
+ phaseRecordingNonHtml: PHASE_RECORDING_NON_HTML,
1382
+ phaseRecordingHtmlSeeds: PHASE_RECORDING_HTML_SEEDS,
1383
+ phaseRecordingExcluded: PHASE_RECORDING_EXCLUDED,
1384
+ });
1083
1385
  // Audit row is written *inside* the `.bak` window: a libsql
1084
1386
  // hiccup or transient lock on the INSERT aborts the ingestion
1085
1387
  // and the `.bak` restore wipes the pre-inserted seeds too,
@@ -1087,8 +1389,8 @@ export class CrawlerOrchestrator extends EventEmitter {
1087
1389
  // the ingestion boundary. Audit failures are deliberately
1088
1390
  // NOT swallowed — inside the `.bak` window a restore is
1089
1391
  // safe and useful (see
1090
- // {@link CrawlerOrchestrator.#writeInventoryRunRow}).
1091
- await CrawlerOrchestrator.#writeInventoryRunRow(archive, {
1392
+ // {@link CrawlerOrchestrator.#writeListReconcileRunRow}).
1393
+ await CrawlerOrchestrator.#writeListReconcileRunRow(archive, {
1092
1394
  inventoryUrlsCount: inventoryUrls.length,
1093
1395
  htmlSeedsCount: htmlSeeds.length,
1094
1396
  nonHtmlCount: nonHtmlSeeds.length,
@@ -1129,13 +1431,25 @@ export class CrawlerOrchestrator extends EventEmitter {
1129
1431
  // Seed the sticky set from prior sessions' confirmed traps
1130
1432
  // so `--inventory` does not pay the cost of
1131
1433
  // re-discovering them (see `DedupeCapTracker`'s
1132
- // constructor JSDoc). Scoped to this branch only,
1133
- // matching `#preloadDnsBurnedHostCache`'s scoping below —
1134
- // the fallback (non-HTML-only) branch never calls
1434
+ // constructor JSDoc), and replay every not-yet-capped
1435
+ // shape's prior observations so its counter does not
1436
+ // restart at 0 (see `#preloadDedupeCapObservations`).
1437
+ // Scoped to this branch only, matching
1438
+ // `#preloadDnsBurnedHostCache`'s scoping below — the
1439
+ // fallback (non-HTML-only) branch never calls
1135
1440
  // `orchestrator.crawling(...)`, so the tracker is never
1136
- // consulted there.
1137
- orchestratorOptions.preloadedStickyShapeKeys =
1138
- await archive.listDedupeCapShapeKeys();
1441
+ // consulted there. Silent (no `onPhase`/`onProgress`) —
1442
+ // matching the shape-key read's existing silent
1443
+ // behaviour here, unlike `append`/`retryFailed`/`resume`,
1444
+ // which already dedicate a phase to it. Independent reads
1445
+ // — run concurrently (see `append`'s identical pair).
1446
+ [
1447
+ orchestratorOptions.preloadedStickyShapeKeys,
1448
+ orchestratorOptions.preloadedDedupeObservations,
1449
+ ] = await Promise.all([
1450
+ archive.listDedupeCapShapeKeys(),
1451
+ CrawlerOrchestrator.#preloadDedupeCapObservations(archive, orchestratorOptions.dedupeCap ?? null),
1452
+ ]);
1139
1453
  const orchestrator = new CrawlerOrchestrator(archive, orchestratorOptions);
1140
1454
  // Re-read pending *after* the pre-insert so the strict-
1141
1455
  // pending set includes the freshly inserted
@@ -1145,7 +1459,14 @@ export class CrawlerOrchestrator extends EventEmitter {
1145
1459
  // pending set alone (see retryFailed's
1146
1460
  // `crawling([], { recursive })` invocation).
1147
1461
  setupProgress?.onPhase?.(PHASE_LOADING_CRAWL_STATE_POST);
1148
- const { scraped: scrapedAfter, pending: pendingAfter } = await archive.getCrawlingState();
1462
+ // `archived.fromList` is rejected above, so no
1463
+ // root-exclusion is needed here (see the list-mode
1464
+ // `resume`/auto-retry paths' comments for why it matters
1465
+ // there). No `= []` default needed: `pendingMetadataOnlyAfter`
1466
+ // is only ever passed straight through to `Crawler#resume()`,
1467
+ // whose own `metadataOnlyUrls` parameter already defaults
1468
+ // `undefined` to `[]`.
1469
+ const { scraped: scrapedAfter, pending: pendingAfter, pendingMetadataOnly: pendingMetadataOnlyAfter, } = await archive.getCrawlingState();
1149
1470
  setupProgress?.onPhase?.(PHASE_LOADING_RESOURCES);
1150
1471
  const resources = await archive.getResourceUrlList(setupProgress?.onChunkProgress);
1151
1472
  // Pre-existing rendered HTML page count seeds the
@@ -1157,7 +1478,7 @@ export class CrawlerOrchestrator extends EventEmitter {
1157
1478
  setupProgress?.onPhase?.(PHASE_LOADING_SCRAPED_COUNT);
1158
1479
  const pagesScrapedOffset = await archive.getScrapedHtmlPageCount();
1159
1480
  setupProgress?.onPhase?.(PHASE_RESTORING_CRAWL_STATE);
1160
- orchestrator.#crawler.resume(pendingAfter, scrapedAfter, resources, pagesScrapedOffset);
1481
+ orchestrator.#crawler.resume(pendingAfter, scrapedAfter, resources, pagesScrapedOffset, pendingMetadataOnlyAfter);
1161
1482
  if (initializedCallback) {
1162
1483
  await initializedCallback(orchestrator, baseConfig);
1163
1484
  }
@@ -1165,7 +1486,7 @@ export class CrawlerOrchestrator extends EventEmitter {
1165
1486
  log('Archive %s', absFilePath);
1166
1487
  log('HTML seeds %O', htmlSeeds.map((u) => u.href));
1167
1488
  await CrawlerOrchestrator.#preloadDnsBurnedHostCache(archive);
1168
- await orchestrator.crawling([], { recursive: true });
1489
+ await orchestrator.#crawlUntilPendingClears([], { recursive: true });
1169
1490
  CrawlerOrchestrator.#finalizeCrawlSession(orchestrator);
1170
1491
  await orchestrator.#setUrlOrder();
1171
1492
  return orchestrator;
@@ -1181,28 +1502,33 @@ export class CrawlerOrchestrator extends EventEmitter {
1181
1502
  }
1182
1503
  catch (error) {
1183
1504
  if (ingestionComplete) {
1184
- // Scrape phase failed; the pre-inserted seeds + audit
1185
- // row are durable inside `tmpDir/db.sqlite` but not yet
1186
- // on disk as a `.nitpicker` tar. The outer catch below
1187
- // runs `archive.close()`, which sees the original
1505
+ // Scrape phase failed — either the auto-retry loop
1506
+ // (`#crawlUntilPendingClears`, issue #350) gave up with
1507
+ // pages still pending, or some other exception. Either
1508
+ // way the pre-inserted seeds + audit row are durable
1509
+ // inside `tmpDir/db.sqlite` but must NOT be packaged: a
1510
+ // `.nitpicker` on disk must imply `pending === 0` (see
1511
+ // that method's JSDoc). The outer catch below runs
1512
+ // `archive.close()`, which sees the original
1188
1513
  // (pre-inventory) `.nitpicker` already on disk and
1189
1514
  // would just `remove(tmpDir)` — silently wiping every
1190
1515
  // `inventory-seed` row and the audit row.
1191
1516
  //
1192
- // Persist the ingested state ourselves before letting
1193
- // the outer catch unwind, then re-throw so the operator
1194
- // learns about the scrape failure (and can recover via
1195
- // `crawl --resume <archive>`). `releaseHandle` shares
1196
- // the orchestrator's `#closeOnce` guard, so the outer
1197
- // catch's `close()` becomes a no-op for the destructive
1198
- // step and only runs `releaseLock` cleanup.
1517
+ // Release the handle ourselves (leaving tmpDir intact)
1518
+ // before letting the outer catch unwind, then re-throw
1519
+ // so the operator learns about the scrape failure and
1520
+ // can recover via `crawl --resume <stub>`. `releaseHandle`
1521
+ // shares the orchestrator's `#closeOnce` guard, so the
1522
+ // outer catch's `close()` becomes a no-op for the
1523
+ // destructive step and only runs `releaseLock` cleanup
1524
+ // — a no-op too when `#crawlUntilPendingClears` already
1525
+ // released it itself before throwing.
1199
1526
  try {
1200
- setupProgress?.onPhase?.(RECOVERY_PERSIST_INGESTED_STATE);
1201
- await archive.write();
1527
+ setupProgress?.onPhase?.(RECOVERY_LEAVE_STATE_FOR_RESUME);
1202
1528
  await archive.releaseHandle();
1203
1529
  }
1204
1530
  catch (persistError) {
1205
- throw new AggregateError([error, persistError], 'inventory scrape phase failed AND persisting the ingested state to disk also failed. The archive may be in an inconsistent state — check tmpDir.');
1531
+ throw new AggregateError([error, persistError], 'inventory scrape phase failed AND releasing the archive handle also failed. The archive may be in an inconsistent state — check tmpDir.');
1206
1532
  }
1207
1533
  throw error;
1208
1534
  }
@@ -1222,6 +1548,481 @@ export class CrawlerOrchestrator extends EventEmitter {
1222
1548
  throw error;
1223
1549
  }
1224
1550
  }
1551
+ /**
1552
+ * Re-fetch pages named by an operator-supplied URL list, importing any
1553
+ * URL the archive does not yet track as a new inventory seed.
1554
+ *
1555
+ * `recrawl` is `retryFailed`'s un-scrape combined with `inventory`'s
1556
+ * novel-URL ingestion, run inside one `.bak`-protected window: URLs in
1557
+ * `recrawlUrls` that already exist as `content_items` rows are reset back
1558
+ * to pending via {@link Archive.resetPagesByUrls} (see that method for the
1559
+ * conservative exclusion rules — redirect sources, intentionally-skipped
1560
+ * pages, and external pages are matched but never reset), while URLs the
1561
+ * archive has never seen are ingested exactly as `inventory` does (see
1562
+ * {@link CrawlerOrchestrator.inventory}'s JSDoc for that half's contract).
1563
+ * Existing *resources* matched by the list are neither resettable nor
1564
+ * novel — `resource_items` is first-write-wins (a known deviation, see
1565
+ * ARCHITECTURE.md), so a resource re-fetch would not update anything; the
1566
+ * function reports how many list entries fell into this bucket via
1567
+ * `setupProgress.onLog` without acting on them.
1568
+ *
1569
+ * Unlike `inventory`, whose sole early-return condition is "no novel
1570
+ * URLs", `recrawl` also has existing pages to act on — the `.bak` is
1571
+ * skipped only when BOTH `existingPageUrls` (reset candidates) AND
1572
+ * `novelUrls` (ingestion candidates) are empty.
1573
+ *
1574
+ * **Strict-pending gap**: `getCrawlingState()`'s pending set only includes
1575
+ * a `scraped = 0` row that is either anchor-referenced or explicitly
1576
+ * labelled (see that function's JSDoc). When `recrawlUrls` contains pages
1577
+ * that link to each other, resetting one page also deletes its outgoing
1578
+ * `anchor_edges` — so a `source = 'crawled'` sibling that was reset in the
1579
+ * same pass can lose its only anchor referrer and fall out of the strict
1580
+ * pending set, silently skipping its re-fetch. `retryFailed` never hits
1581
+ * this because a failed page's referrers are not themselves reset. The
1582
+ * fix: every URL `Archive.resetPagesByUrls` actually reset is merged into
1583
+ * the pending list handed to `Crawler#resume` regardless of what the
1584
+ * strict scan finds, deduplicated by `LinkList.add`'s `protocolAgnosticKey`
1585
+ * check. A Ctrl+C between the reset and the scrape phase loses this
1586
+ * synthetic merge (it lives only in memory) — `crawl --resume` recovers
1587
+ * whatever the strict-pending scan finds on its own, and re-running
1588
+ * `--recrawl` with the same list recovers the rest, matching the
1589
+ * "un-picked seeds" recovery contract `getCrawlingState`'s JSDoc already
1590
+ * documents for `inventory`.
1591
+ *
1592
+ * **Stale analyze findings**: resetting a page deletes its
1593
+ * `analysis_violations` rows (see {@link resetPagesByUrls}'s JSDoc) so a
1594
+ * re-fetched page never shows findings from HTML that no longer exists,
1595
+ * but other `analyze` outputs (e.g. Discrepancies plugin reports) are not
1596
+ * page-scoped and cannot be selectively invalidated. When at least one
1597
+ * page was reset, a `crawlSessionNotice` is emitted after the crawl
1598
+ * completes recommending `analyze` be re-run before the next `report`.
1599
+ * @param archivePath - Absolute or relative path to the existing `.nitpicker`.
1600
+ * @param recrawlUrls - URLs to match against the archive (existing pages
1601
+ * are reset; unknown URLs are ingested as new inventory seeds).
1602
+ * @param options - Optional config overrides applied on top of the archived config.
1603
+ * @param initializedCallback - Optional callback invoked after initialization but before crawling resumes.
1604
+ * @param source - The CLI's already-read URL list source bytes, archived
1605
+ * for audit purposes — see {@link InventorySource}. `null` for
1606
+ * programmatic callers with no source file.
1607
+ * @param setupProgress - Optional progress callbacks for the setup phase
1608
+ * (untar, `.bak` copy, URL classification, reset, seed ingestion, state
1609
+ * rebuild) that runs before `initializedCallback` — see
1610
+ * {@link SetupProgressCallbacks} for why this can't go through the
1611
+ * orchestrator's event emitter (issue #294).
1612
+ * @returns The orchestrator instance after the recrawl completes.
1613
+ * @throws {Error} When `recrawlUrls` is empty or the archive is in list mode.
1614
+ * @throws {PendingUrlsRemainError} When the crawl session ends with pages still pending after exhausting auto-retry.
1615
+ */
1616
+ static async recrawl(archivePath, recrawlUrls, options, initializedCallback, source = null, setupProgress) {
1617
+ const [PHASE_EXTRACTING, PHASE_LOADING_CONFIG, PHASE_LOADING_CRAWL_STATE_PRE, PHASE_CHECKING_KNOWN_URLS, PHASE_BACKING_UP, PHASE_RESETTING_MATCHED, PHASE_RECORDING_NON_HTML, PHASE_RECORDING_HTML_SEEDS, PHASE_RECORDING_EXCLUDED, PHASE_LOADING_CRAWL_STATE_POST, PHASE_LOADING_RESOURCES, PHASE_LOADING_SCRAPED_COUNT, PHASE_RESTORING_CRAWL_STATE,] = RECRAWL_SETUP_PHASES;
1618
+ if (recrawlUrls.length === 0) {
1619
+ throw new Error('recrawl: URL list is empty');
1620
+ }
1621
+ const cwd = options?.cwd ?? process.cwd();
1622
+ const absFilePath = path.isAbsolute(archivePath)
1623
+ ? archivePath
1624
+ : path.resolve(cwd, archivePath);
1625
+ // See `ArchiveOpenOptions.openPluginData` for why this must be `true`
1626
+ // on every writer path that calls `write()`.
1627
+ setupProgress?.onPhase?.(PHASE_EXTRACTING);
1628
+ const archive = await Archive.open({
1629
+ filePath: absFilePath,
1630
+ cwd,
1631
+ openPluginData: true,
1632
+ onExtractProgress: setupProgress?.onExtractProgress,
1633
+ onLog: setupProgress?.onLog,
1634
+ });
1635
+ try {
1636
+ setupProgress?.onPhase?.(PHASE_LOADING_CONFIG);
1637
+ const archived = await archive.getConfig();
1638
+ if (archived.fromList) {
1639
+ throw new Error('Cannot recrawl a list-mode archive: this archive was created with --list/--list-file and contains metadata-only pages. Create a fresh archive instead.');
1640
+ }
1641
+ // Stamped for `Archive.resume` (issue #350) — same rationale as
1642
+ // `inventory`'s identical call.
1643
+ await archive.updateConfig(buildCreatedCwdPatch(cwd));
1644
+ setupProgress?.onPhase?.(PHASE_LOADING_CRAWL_STATE_PRE);
1645
+ const { pending } = await archive.getCrawlingState();
1646
+ if (pending.length > 0) {
1647
+ // Same rationale as `inventory`'s identical warning — routed
1648
+ // through `setupProgress.onLog`, not a bare `console.warn`,
1649
+ // since the `'Loading crawl state'` row is active here.
1650
+ const message = `recrawl: archive has ${pending.length} pending URLs from a previous crawl. Proceeding — crawled-wins priority keeps their labels stable. Consider \`--resume\` first if you want the prior work finalized.`;
1651
+ if (setupProgress?.onLog) {
1652
+ setupProgress.onLog(message);
1653
+ }
1654
+ else {
1655
+ // eslint-disable-next-line no-console -- --silent has no TaskList row to report through
1656
+ console.warn(message);
1657
+ }
1658
+ }
1659
+ // Archive the exact source bytes before scope classification —
1660
+ // same rationale as `inventory`'s identical call.
1661
+ if (source) {
1662
+ await archive.saveInventorySourceList(source.sha256, source.bytes);
1663
+ }
1664
+ setupProgress?.onPhase?.(PHASE_CHECKING_KNOWN_URLS);
1665
+ const { outOfScope, existingPageUrls, existingResourceUrls, novelUrls } = await CrawlerOrchestrator.#classifyInventoryCandidateUrls(recrawlUrls, archived, archive);
1666
+ if (existingResourceUrls.length > 0) {
1667
+ const message = `recrawl: ${existingResourceUrls.length} URL(s) matched existing resources — not re-fetched (resource rows are first-write-wins; re-fetching would not update them).`;
1668
+ if (setupProgress?.onLog) {
1669
+ setupProgress.onLog(message);
1670
+ }
1671
+ else {
1672
+ // eslint-disable-next-line no-console -- --silent has no TaskList row to report through
1673
+ console.warn(message);
1674
+ }
1675
+ }
1676
+ const effectiveConfig = { ...archived, ...cleanObject(options) };
1677
+ const { excludedNovelUrls, importableNovelUrls } = CrawlerOrchestrator.#classifyExcludedNovelUrls(novelUrls, effectiveConfig);
1678
+ if (existingPageUrls.length === 0 && novelUrls.length === 0) {
1679
+ // Nothing to do — release the archive cleanly without taking a
1680
+ // backup, mirroring `inventory`'s zero-novel early return.
1681
+ const orchestrator = new CrawlerOrchestrator(archive, effectiveConfig);
1682
+ if (initializedCallback) {
1683
+ await initializedCallback(orchestrator, effectiveConfig);
1684
+ }
1685
+ return orchestrator;
1686
+ }
1687
+ const backupPath = absFilePath + '.bak';
1688
+ setupProgress?.onPhase?.(PHASE_BACKING_UP);
1689
+ await copyFileWithProgress(absFilePath, backupPath, setupProgress?.onCopyProgress);
1690
+ let ingestionComplete = false;
1691
+ try {
1692
+ setupProgress?.onPhase?.(PHASE_RESETTING_MATCHED);
1693
+ const resetResult = await archive.resetPagesByUrls(existingPageUrls, setupProgress?.onChunkProgress);
1694
+ const excludedTotal = resetResult.excludedRedirects.length +
1695
+ resetResult.excludedSkipped.length +
1696
+ resetResult.excludedExternal.length;
1697
+ // `existingPageUrls` (from `getExistingPageUrls`) matches by URL
1698
+ // alone, regardless of `scraped` — it can include rows still
1699
+ // pending from an interrupted previous session. Those rows are
1700
+ // absent from every `resetPagesByUrls` array (see that
1701
+ // function's JSDoc: "already pending, nothing to reset"), so
1702
+ // the three counts below alone would not sum back to
1703
+ // `existingPageUrls.length` and the message would look like
1704
+ // pages vanished unexplained. Naming this remainder keeps the
1705
+ // arithmetic honest for an operator auditing the summary.
1706
+ const alreadyPendingCount = existingPageUrls.length - resetResult.resetUrls.length - excludedTotal;
1707
+ const summaryMessage = `recrawl: matched ${existingPageUrls.length} existing page(s) — reset ${resetResult.resetUrls.length}, excluded ${excludedTotal} (${resetResult.excludedRedirects.length} redirect source(s), ${resetResult.excludedSkipped.length} intentionally-skipped, ${resetResult.excludedExternal.length} external), already pending ${alreadyPendingCount}.`;
1708
+ if (setupProgress?.onLog) {
1709
+ setupProgress.onLog(summaryMessage);
1710
+ }
1711
+ else {
1712
+ // eslint-disable-next-line no-console -- --silent has no TaskList row to report through
1713
+ console.warn(summaryMessage);
1714
+ }
1715
+ const { htmlSeeds, nonHtmlSeeds } = await CrawlerOrchestrator.#ingestNovelSeeds({
1716
+ archive,
1717
+ importableNovelUrls,
1718
+ excludedNovelUrls,
1719
+ setupProgress,
1720
+ phaseRecordingNonHtml: PHASE_RECORDING_NON_HTML,
1721
+ phaseRecordingHtmlSeeds: PHASE_RECORDING_HTML_SEEDS,
1722
+ phaseRecordingExcluded: PHASE_RECORDING_EXCLUDED,
1723
+ });
1724
+ // Audit row is written *inside* the `.bak` window — same
1725
+ // all-or-nothing rationale as `inventory`'s identical write.
1726
+ await CrawlerOrchestrator.#writeListReconcileRunRow(archive, {
1727
+ inventoryUrlsCount: recrawlUrls.length,
1728
+ htmlSeedsCount: htmlSeeds.length,
1729
+ nonHtmlCount: nonHtmlSeeds.length,
1730
+ outOfScope,
1731
+ excludeSkipped: excludedNovelUrls.length,
1732
+ sourceFileSha256: source?.sha256 ?? null,
1733
+ invalidSkipped: source?.invalidLineCount ?? null,
1734
+ listLabelPrefix: 'recrawl',
1735
+ notes: `Reset ${resetResult.resetUrls.length} existing page(s) for re-fetch`,
1736
+ });
1737
+ ingestionComplete = true;
1738
+ await ignoreEnoent(unlinkFile(backupPath));
1739
+ const baseConfig = {
1740
+ ...effectiveConfig,
1741
+ recursive: true,
1742
+ fromList: false,
1743
+ };
1744
+ const seedSet = new Set(htmlSeeds.map((u) => u.withoutHashAndAuth));
1745
+ const orchestratorOptions = {
1746
+ ...baseConfig,
1747
+ inventoryMode: { seedUrls: seedSet },
1748
+ };
1749
+ if (resetResult.resetUrls.length > 0 || htmlSeeds.length > 0) {
1750
+ // Same rationale as `inventory`'s identical pair of
1751
+ // preload calls (sticky shapes + prior observation
1752
+ // replay, run concurrently), silent for the same reason
1753
+ // — see that method's comment.
1754
+ [
1755
+ orchestratorOptions.preloadedStickyShapeKeys,
1756
+ orchestratorOptions.preloadedDedupeObservations,
1757
+ ] = await Promise.all([
1758
+ archive.listDedupeCapShapeKeys(),
1759
+ CrawlerOrchestrator.#preloadDedupeCapObservations(archive, orchestratorOptions.dedupeCap ?? null),
1760
+ ]);
1761
+ const orchestrator = new CrawlerOrchestrator(archive, orchestratorOptions);
1762
+ setupProgress?.onPhase?.(PHASE_LOADING_CRAWL_STATE_POST);
1763
+ // `archived.fromList` is rejected above, so no
1764
+ // root-exclusion is needed here (see the list-mode
1765
+ // `resume`/auto-retry paths' comments for why it matters
1766
+ // there). `pendingMetadataOnlyAfter` is not merged with
1767
+ // `resetResult.resetUrls` the way `pending` is below — a
1768
+ // reset row absent from the strict-pending set defaults
1769
+ // to a full re-scrape, the safe direction for a
1770
+ // user-requested recrawl. No `= []` default needed: it is
1771
+ // only ever passed straight through to `Crawler#resume()`,
1772
+ // whose own `metadataOnlyUrls` parameter already defaults
1773
+ // `undefined` to `[]`.
1774
+ const { scraped: scrapedAfter, pending: pendingAfter, pendingMetadataOnly: pendingMetadataOnlyAfter, } = await archive.getCrawlingState();
1775
+ // Merge the reset URLs into the pending set explicitly —
1776
+ // see this method's "Strict-pending gap" JSDoc section.
1777
+ // Deduped by `LinkList.add`'s own key check, so a URL the
1778
+ // strict scan already found is harmless to repeat here.
1779
+ const pendingWithReset = [
1780
+ ...new Set([...pendingAfter, ...resetResult.resetUrls]),
1781
+ ];
1782
+ setupProgress?.onPhase?.(PHASE_LOADING_RESOURCES);
1783
+ const resources = await archive.getResourceUrlList(setupProgress?.onChunkProgress);
1784
+ setupProgress?.onPhase?.(PHASE_LOADING_SCRAPED_COUNT);
1785
+ const pagesScrapedOffset = await archive.getScrapedHtmlPageCount();
1786
+ setupProgress?.onPhase?.(PHASE_RESTORING_CRAWL_STATE);
1787
+ orchestrator.#crawler.resume(pendingWithReset, scrapedAfter, resources, pagesScrapedOffset, pendingMetadataOnlyAfter);
1788
+ if (initializedCallback) {
1789
+ await initializedCallback(orchestrator, baseConfig);
1790
+ }
1791
+ log('Start recrawl');
1792
+ log('Archive %s', absFilePath);
1793
+ log('Reset %d page(s), %d new HTML seed(s)', resetResult.resetUrls.length, htmlSeeds.length);
1794
+ await CrawlerOrchestrator.#preloadDnsBurnedHostCache(archive);
1795
+ await orchestrator.#crawlUntilPendingClears([], { recursive: true });
1796
+ CrawlerOrchestrator.#finalizeCrawlSession(orchestrator);
1797
+ if (resetResult.resetUrls.length > 0) {
1798
+ void orchestrator.emit('crawlSessionNotice', {
1799
+ message: `[recrawl] Reset ${resetResult.resetUrls.length} page(s) — run \`analyze\` before \`report\` to refresh their findings.`,
1800
+ });
1801
+ }
1802
+ await orchestrator.#setUrlOrder();
1803
+ return orchestrator;
1804
+ }
1805
+ // Only non-HTML URLs were imported and nothing was reset —
1806
+ // nothing left to render, but still update sort order.
1807
+ const orchestrator = new CrawlerOrchestrator(archive, orchestratorOptions);
1808
+ if (initializedCallback) {
1809
+ await initializedCallback(orchestrator, baseConfig);
1810
+ }
1811
+ await orchestrator.#setUrlOrder();
1812
+ return orchestrator;
1813
+ }
1814
+ catch (error) {
1815
+ if (ingestionComplete) {
1816
+ // Same rationale as `inventory`'s identical catch — see
1817
+ // that method's comment. Scrape failure here can equally
1818
+ // be the auto-retry loop (issue #350) giving up.
1819
+ try {
1820
+ setupProgress?.onPhase?.(RECOVERY_LEAVE_STATE_FOR_RESUME);
1821
+ await archive.releaseHandle();
1822
+ }
1823
+ catch (persistError) {
1824
+ throw new AggregateError([error, persistError], 'recrawl scrape phase failed AND releasing the archive handle also failed. The archive may be in an inconsistent state — check tmpDir.');
1825
+ }
1826
+ throw error;
1827
+ }
1828
+ try {
1829
+ setupProgress?.onPhase?.(RECOVERY_RESTORE_FROM_BACKUP);
1830
+ await copyFileWithProgress(backupPath, absFilePath, setupProgress?.onCopyProgress);
1831
+ await ignoreEnoent(unlinkFile(backupPath));
1832
+ }
1833
+ catch (restoreError) {
1834
+ throw new AggregateError([error, restoreError], `recrawl failed AND restore from backup failed. Original archive backup is left at: ${backupPath}`);
1835
+ }
1836
+ throw error;
1837
+ }
1838
+ }
1839
+ catch (error) {
1840
+ await archive.close().catch(() => { });
1841
+ throw error;
1842
+ }
1843
+ }
1844
+ /**
1845
+ * Shared first-stage classification for `inventory` and `recrawl`: parse
1846
+ * the candidate URLs, split them by the archived scope map into
1847
+ * in-scope/out-of-scope, then split the in-scope set into URLs already
1848
+ * represented in the archive (as a page or a resource) vs. novel URLs the
1849
+ * archive has never seen. Comparison key is `withoutHashAndAuth` to
1850
+ * mirror what `resolveContentItemId` / `insertResource` actually store.
1851
+ *
1852
+ * The two existing-URL reads run concurrently via `Promise.all` — halves
1853
+ * the wait on large archives where each `WHERE url IN (?)` chunk costs
1854
+ * real I/O.
1855
+ * @param rawUrls - The operator-supplied URL list, unparsed.
1856
+ * @param archived - The archive's persisted config (`roots` defines scope).
1857
+ * @param archive - The opened archive to query for existing URLs.
1858
+ * @returns `outOfScope` (count dropped by the scope filter),
1859
+ * `existingPageUrls` / `existingResourceUrls` (URLs already known, by
1860
+ * kind), and `novelUrls` (parsed, in-scope URLs matching neither).
1861
+ */
1862
+ static async #classifyInventoryCandidateUrls(rawUrls, archived, archive) {
1863
+ const parsedAll = sortUrl(rawUrls, archived);
1864
+ const scopeMap = new Map();
1865
+ for (const raw of archived.roots) {
1866
+ const parsed = parseUrl(raw, archived);
1867
+ if (!parsed)
1868
+ continue;
1869
+ const existing = scopeMap.get(parsed.hostname) ?? [];
1870
+ scopeMap.set(parsed.hostname, [...existing, parsed]);
1871
+ }
1872
+ const inScope = [];
1873
+ let outOfScope = 0;
1874
+ for (const url of parsedAll) {
1875
+ if (findScopeEntry(url, scopeMap, archived) === null) {
1876
+ outOfScope++;
1877
+ }
1878
+ else {
1879
+ inScope.push(url);
1880
+ }
1881
+ }
1882
+ if (outOfScope > 0) {
1883
+ log('[ingest] %d URL(s) skipped (outside archived scope: %O)', outOfScope, archived.roots);
1884
+ }
1885
+ const candidateUrls = inScope.map((u) => u.withoutHashAndAuth);
1886
+ const [existingPageUrls, existingResourceUrls] = await Promise.all([
1887
+ archive.getExistingPageUrls(candidateUrls),
1888
+ archive.getExistingResourceUrls(candidateUrls),
1889
+ ]);
1890
+ const existingPageUrlSet = new Set(existingPageUrls);
1891
+ const existingResourceUrlSet = new Set(existingResourceUrls);
1892
+ const novelUrls = inScope.filter((u) => {
1893
+ const key = u.withoutHashAndAuth;
1894
+ return !existingPageUrlSet.has(key) && !existingResourceUrlSet.has(key);
1895
+ });
1896
+ log('[ingest] %d in-scope, %d already in archive, %d new', inScope.length, existingPageUrlSet.size + existingResourceUrlSet.size, novelUrls.length);
1897
+ return { outOfScope, existingPageUrls, existingResourceUrls, novelUrls };
1898
+ }
1899
+ /**
1900
+ * Shared second-stage classification for `inventory` and `recrawl`:
1901
+ * splits novel URLs on the exclusion config BEFORE the HTML/non-HTML
1902
+ * classification, so an exclude-matched URL is recorded as a terminal
1903
+ * skipped page instead of being imported (issue #260).
1904
+ *
1905
+ * The inputs mirror the scrape phase's fetch-time gate (`shouldSkipUrl`
1906
+ * in `crawler.ts` fed by the constructor's merge): archived config
1907
+ * overlaid with this run's overrides, and `DEFAULT_EXCLUDED_EXTERNAL_URLS`
1908
+ * merged ahead of the user's prefixes — classification and gate must
1909
+ * never disagree about the same URL. Running this AFTER the known-URL
1910
+ * filter (`#classifyInventoryCandidateUrls`) is deliberate: a previously
1911
+ * crawled row that newly matches the exclusion config stays untouched
1912
+ * (crawled-wins), matching how `getExistingPageUrls` shields known rows
1913
+ * from re-labelling. `excludeKeywords` is deliberately absent: it matches
1914
+ * rendered page content, which a URL list does not have — HTML seeds
1915
+ * still get it at render time via the browser verdict.
1916
+ * @param novelUrls - URLs not yet represented in the archive, from
1917
+ * `#classifyInventoryCandidateUrls`.
1918
+ * @param effectiveConfig - The archived config overlaid with this run's
1919
+ * overrides (the same merge the caller uses to build its own config).
1920
+ * @returns `excludedNovelUrls` (matched `excludes`/`excludeUrls`, to be
1921
+ * recorded as terminal skipped pages) and `importableNovelUrls` (the rest).
1922
+ */
1923
+ static #classifyExcludedNovelUrls(novelUrls, effectiveConfig) {
1924
+ const excludes = normalizeToArray(effectiveConfig.excludes);
1925
+ const excludeUrls = [
1926
+ ...DEFAULT_EXCLUDED_EXTERNAL_URLS,
1927
+ ...normalizeToArray(effectiveConfig.excludeUrls),
1928
+ ];
1929
+ const excludedNovelUrls = [];
1930
+ const importableNovelUrls = [];
1931
+ for (const url of novelUrls) {
1932
+ if (shouldSkipUrl({ url, excludes, excludeUrls, options: effectiveConfig })) {
1933
+ excludedNovelUrls.push(url);
1934
+ }
1935
+ else {
1936
+ importableNovelUrls.push(url);
1937
+ }
1938
+ }
1939
+ if (excludedNovelUrls.length > 0) {
1940
+ log('[ingest] %d URL(s) recorded as skipped (matched excludes / excludeUrls)', excludedNovelUrls.length);
1941
+ }
1942
+ return { excludedNovelUrls, importableNovelUrls };
1943
+ }
1944
+ /**
1945
+ * Shared third-stage ingestion for `inventory` and `recrawl`: classifies
1946
+ * importable novel URLs by URL-extension heuristic (no I/O), dedups HTML
1947
+ * seeds, and bulk-records both kinds into the archive.
1948
+ *
1949
+ * Source file lists come from `ls` on the doc-root, so the extension
1950
+ * reflects the real file type — a HEAD pre-flight here would be pure
1951
+ * wasted I/O. Edge cases:
1952
+ *
1953
+ * - `.html` returning 404 / 200: the normal crawler HEAD/GET path absorbs
1954
+ * this because every HTML-classified URL is fed through the dealer and
1955
+ * gets its real HEAD/GET there.
1956
+ * - Extensionless API endpoints (e.g. `/api/foo`) that the server returns
1957
+ * as `text/html`: `isLikelyHtmlUrl` accepts them as HTML so the
1958
+ * dealer's render path runs — the real content-type wins downstream.
1959
+ * - `.aspx` / `.do` / `.jsp` / other server-handler extensions the
1960
+ * heuristic does NOT recognise as HTML: classified as non-HTML,
1961
+ * recorded as `resources` rows with all-null metadata, never get a
1962
+ * HEAD/GET probe. Sites that mix server-handlers into the list need a
1963
+ * follow-up `--retry-failed` pass (or a re-run with the corrected list)
1964
+ * to populate metadata.
1965
+ *
1966
+ * HTML seeds are deduped by `protocolAgnosticKey` so a list mixing
1967
+ * `http://` and `https://` for the same origin does not produce two rows
1968
+ * that the dealer later collapses to one — the loser would otherwise stay
1969
+ * `scraped=0, source='inventory-seed'` forever and look like a real
1970
+ * recovery candidate on `--resume`. `getExistingPageUrls` keys on the
1971
+ * full URL (with protocol), so it cannot catch the cross-scheme
1972
+ * duplicate; this is the dedup boundary.
1973
+ *
1974
+ * Non-HTML URLs are bulk-recorded via `insertInventoryResources` — a
1975
+ * per-URL loop would spend minutes inside the `.bak`-protected window on
1976
+ * a large list; the chunked bulk path collapses N round-trips to N/500.
1977
+ * HTML seeds are pre-inserted as `scraped = 0`, `source =
1978
+ * 'inventory-seed'` placeholders *before* the scrape phase, so a Ctrl+C
1979
+ * between here and `setPage` cannot lose the URL — the strict-pending set
1980
+ * picks these rows up on the next `--resume` via the `OR p.source !=
1981
+ * 'crawled'` clause. Exclude-matched novel URLs are recorded as terminal
1982
+ * skipped pages (`is_skipped=1`, `skip_reason='excluded'`,
1983
+ * `source='inventory-seed'`) — the same end state the normal crawl's
1984
+ * fetch-time gate produces for link-discovered excluded URLs.
1985
+ * @param options - Named parameters (4+ values).
1986
+ * @param options.archive - The opened archive to write into.
1987
+ * @param options.importableNovelUrls - Novel URLs not matched by excludes.
1988
+ * @param options.excludedNovelUrls - Novel URLs matched by excludes, from `#classifyExcludedNovelUrls`.
1989
+ * @param options.setupProgress - Optional setup progress callbacks.
1990
+ * @param options.phaseRecordingNonHtml - The `onPhase` label to announce before recording non-HTML resources.
1991
+ * @param options.phaseRecordingHtmlSeeds - The `onPhase` label to announce before recording HTML seed pages.
1992
+ * @param options.phaseRecordingExcluded - The `onPhase` label to announce before recording excluded pages.
1993
+ * @returns `htmlSeeds` and `nonHtmlSeeds` — the deduped, classified novel URLs actually recorded.
1994
+ */
1995
+ static async #ingestNovelSeeds(options) {
1996
+ const { archive, importableNovelUrls, excludedNovelUrls, setupProgress, phaseRecordingNonHtml, phaseRecordingHtmlSeeds, phaseRecordingExcluded, } = options;
1997
+ const rawHtmlSeeds = [];
1998
+ const nonHtmlSeeds = [];
1999
+ for (const url of importableNovelUrls) {
2000
+ if (isLikelyHtmlUrl(url)) {
2001
+ rawHtmlSeeds.push(url);
2002
+ }
2003
+ else {
2004
+ nonHtmlSeeds.push(url);
2005
+ }
2006
+ }
2007
+ const seenKeys = new Set();
2008
+ const htmlSeeds = [];
2009
+ for (const url of rawHtmlSeeds) {
2010
+ const key = protocolAgnosticKey(url.withoutHashAndAuth);
2011
+ if (seenKeys.has(key)) {
2012
+ continue;
2013
+ }
2014
+ seenKeys.add(key);
2015
+ htmlSeeds.push(url);
2016
+ }
2017
+ setupProgress?.onPhase?.(phaseRecordingNonHtml);
2018
+ await archive.insertInventoryResources(nonHtmlSeeds);
2019
+ setupProgress?.onPhase?.(phaseRecordingHtmlSeeds);
2020
+ await archive.insertInventorySeeds(htmlSeeds);
2021
+ setupProgress?.onPhase?.(phaseRecordingExcluded);
2022
+ await archive.insertInventorySkippedPages(excludedNovelUrls);
2023
+ log('[ingest] %d HTML seed(s), %d non-HTML resource(s), %d skipped page(s) recorded', htmlSeeds.length, nonHtmlSeeds.length, excludedNovelUrls.length);
2024
+ return { htmlSeeds, nonHtmlSeeds };
2025
+ }
1225
2026
  /**
1226
2027
  * Re-fetch previously-failed pages in an existing `.nitpicker` archive.
1227
2028
  *
@@ -1245,7 +2046,10 @@ export class CrawlerOrchestrator extends EventEmitter {
1245
2046
  *
1246
2047
  * A `<archive>.bak` is created before any DB mutation and removed on success;
1247
2048
  * if the crawl throws, the backup is restored to keep the original archive
1248
- * intact.
2049
+ * intact — except when the crawl ends with {@link PendingUrlsRemainError}
2050
+ * (issue #350), where the un-packaged stub itself is the recovery path and
2051
+ * the backup is instead left untouched (deleted, not restored — see
2052
+ * {@link CrawlerOrchestrator.#abandonBackupOnPendingRemains}).
1249
2053
  *
1250
2054
  * List-mode archives (`info.fromList === true`) are rejected for the same
1251
2055
  * reason as {@link CrawlerOrchestrator.append}: their pages are metadata-only.
@@ -1258,6 +2062,7 @@ export class CrawlerOrchestrator extends EventEmitter {
1258
2062
  * this can't go through the orchestrator's event emitter (issue #294).
1259
2063
  * @returns The orchestrator instance after the retry crawl completes.
1260
2064
  * @throws {Error} When the archive is in list mode or has no parseable roots.
2065
+ * @throws {PendingUrlsRemainError} When the crawl session ends with pages still pending after exhausting auto-retry.
1261
2066
  */
1262
2067
  static async retryFailed(archivePath, options, initializedCallback, setupProgress) {
1263
2068
  const [PHASE_EXTRACTING, PHASE_LOADING_CONFIG, PHASE_BACKING_UP, PHASE_RESETTING_FAILED, PHASE_LOADING_DEDUPE_KEYS, PHASE_LOADING_CRAWL_STATE, PHASE_LOADING_RESOURCES, PHASE_LOADING_SCRAPED_COUNT, PHASE_RESTORING_CRAWL_STATE,] = RETRY_FAILED_SETUP_PHASES;
@@ -1284,6 +2089,9 @@ export class CrawlerOrchestrator extends EventEmitter {
1284
2089
  if (archived.fromList) {
1285
2090
  throw new Error('Cannot retry a list-mode archive: this archive was created with --list/--list-file and contains metadata-only pages. Create a fresh archive instead.');
1286
2091
  }
2092
+ // Stamped for `Archive.resume` (issue #350) — same rationale as
2093
+ // `inventory`'s identical call.
2094
+ await archive.updateConfig(buildCreatedCwdPatch(cwd));
1287
2095
  const rootsParsed = sortUrl(archived.roots, archived);
1288
2096
  if (rootsParsed.length === 0) {
1289
2097
  throw new Error('retry: archive has no parseable root URLs');
@@ -1306,32 +2114,60 @@ export class CrawlerOrchestrator extends EventEmitter {
1306
2114
  log('Reset %d failed page(s)', resetUrls.length);
1307
2115
  // Seed the sticky set from prior sessions' confirmed traps so
1308
2116
  // `--retry-failed` does not pay the cost of re-discovering
1309
- // them (see `DedupeCapTracker`'s constructor JSDoc).
2117
+ // them (see `DedupeCapTracker`'s constructor JSDoc), and
2118
+ // replay every not-yet-capped shape's prior observations so
2119
+ // its counter does not restart at 0 (see
2120
+ // `#preloadDedupeCapObservations`). Runs *after*
2121
+ // `resetFailedPages` above, which already excludes
2122
+ // confirmed-capped-shape failures from the reset — so the
2123
+ // still-`scraped=1` rows this reads back never include a page
2124
+ // this same call is about to re-queue, and a page this call
2125
+ // does reset is correctly absent from the replay (its
2126
+ // `page_meta` row — and therefore its `body_hash` — was just
2127
+ // deleted).
1310
2128
  setupProgress?.onPhase?.(PHASE_LOADING_DEDUPE_KEYS);
1311
- const preloadedStickyShapeKeys = await archive.listDedupeCapShapeKeys();
2129
+ // Independent reads — run concurrently (see `append`'s
2130
+ // identical pair).
2131
+ const [preloadedStickyShapeKeys, preloadedDedupeObservations] = await Promise.all([
2132
+ archive.listDedupeCapShapeKeys(),
2133
+ CrawlerOrchestrator.#preloadDedupeCapObservations(archive, options?.dedupeCap ?? null, setupProgress?.onChunkProgress),
2134
+ ]);
1312
2135
  const orchestrator = new CrawlerOrchestrator(archive, {
1313
2136
  ...config,
1314
2137
  preloadedStickyShapeKeys,
2138
+ preloadedDedupeObservations,
1315
2139
  });
1316
2140
  setupProgress?.onPhase?.(PHASE_LOADING_CRAWL_STATE);
1317
- const { scraped, pending } = await archive.getCrawlingState();
2141
+ // `archived.fromList` is rejected above, so this archive's
2142
+ // `recursive` was never `false` for a list-mode reason — no
2143
+ // root-exclusion needed (see the list-mode `resume`/
2144
+ // auto-retry paths' comments for why it matters there). No
2145
+ // `= []` default needed: `pendingMetadataOnly` is only ever
2146
+ // passed straight through to `Crawler#resume()`, whose own
2147
+ // `metadataOnlyUrls` parameter already defaults `undefined`
2148
+ // to `[]`.
2149
+ const { scraped, pending, pendingMetadataOnly } = await archive.getCrawlingState();
1318
2150
  setupProgress?.onPhase?.(PHASE_LOADING_RESOURCES);
1319
2151
  const resources = await archive.getResourceUrlList(setupProgress?.onChunkProgress);
1320
2152
  setupProgress?.onPhase?.(PHASE_LOADING_SCRAPED_COUNT);
1321
2153
  const pagesScrapedOffset = await archive.getScrapedHtmlPageCount();
1322
2154
  setupProgress?.onPhase?.(PHASE_RESTORING_CRAWL_STATE);
1323
- orchestrator.#crawler.resume(pending, scraped, resources, pagesScrapedOffset);
2155
+ orchestrator.#crawler.resume(pending, scraped, resources, pagesScrapedOffset, pendingMetadataOnly);
1324
2156
  if (initializedCallback) {
1325
2157
  await initializedCallback(orchestrator, config);
1326
2158
  }
1327
2159
  await CrawlerOrchestrator.#preloadDnsBurnedHostCache(archive);
1328
- await orchestrator.crawling([], { recursive: config.recursive });
2160
+ await orchestrator.#crawlUntilPendingClears([], { recursive: config.recursive });
1329
2161
  CrawlerOrchestrator.#finalizeCrawlSession(orchestrator);
1330
2162
  await orchestrator.#setUrlOrder();
1331
2163
  await ignoreEnoent(unlinkFile(backupPath));
1332
2164
  return orchestrator;
1333
2165
  }
1334
2166
  catch (error) {
2167
+ if (error instanceof PendingUrlsRemainError) {
2168
+ await CrawlerOrchestrator.#abandonBackupOnPendingRemains(setupProgress, backupPath);
2169
+ throw error;
2170
+ }
1335
2171
  try {
1336
2172
  setupProgress?.onPhase?.(RECOVERY_RESTORE_FROM_BACKUP);
1337
2173
  await copyFileWithProgress(backupPath, absFilePath, setupProgress?.onCopyProgress);
@@ -1370,6 +2206,7 @@ export class CrawlerOrchestrator extends EventEmitter {
1370
2206
  * tmpDir IS the source of truth).
1371
2207
  * @returns A promise that resolves to the CrawlerOrchestrator instance after crawling completes.
1372
2208
  * @throws {Error} If the archived URL is invalid.
2209
+ * @throws {PendingUrlsRemainError} When the crawl session ends with pages still pending after exhausting auto-retry.
1373
2210
  */
1374
2211
  static async resume(stubPath, options, initializedCallback, setupProgress) {
1375
2212
  const [PHASE_RECONNECTING, PHASE_LOADING_CONFIG, PHASE_LOADING_DEDUPE_KEYS, PHASE_LOADING_CRAWL_STATE, PHASE_LOADING_RESOURCES, PHASE_LOADING_SCRAPED_COUNT, PHASE_RESTORING_CRAWL_STATE,] = RESUME_SETUP_PHASES;
@@ -1379,13 +2216,21 @@ export class CrawlerOrchestrator extends EventEmitter {
1379
2216
  const archivedConfig = await archive.getConfig();
1380
2217
  // Seed the sticky set from prior sessions' confirmed traps so
1381
2218
  // `--resume` does not pay the cost of re-discovering them (see
1382
- // `DedupeCapTracker`'s constructor JSDoc).
2219
+ // `DedupeCapTracker`'s constructor JSDoc), and replay every
2220
+ // not-yet-capped shape's prior observations so its counter does not
2221
+ // restart at 0 (see `#preloadDedupeCapObservations`).
1383
2222
  setupProgress?.onPhase?.(PHASE_LOADING_DEDUPE_KEYS);
1384
- const preloadedStickyShapeKeys = await archive.listDedupeCapShapeKeys();
2223
+ // Independent reads — run concurrently (see `append`'s identical
2224
+ // pair).
2225
+ const [preloadedStickyShapeKeys, preloadedDedupeObservations] = await Promise.all([
2226
+ archive.listDedupeCapShapeKeys(),
2227
+ CrawlerOrchestrator.#preloadDedupeCapObservations(archive, options?.dedupeCap ?? null, setupProgress?.onChunkProgress),
2228
+ ]);
1385
2229
  const config = {
1386
2230
  ...archivedConfig,
1387
2231
  ...cleanObject(options),
1388
2232
  preloadedStickyShapeKeys,
2233
+ preloadedDedupeObservations,
1389
2234
  };
1390
2235
  const orchestrator = new CrawlerOrchestrator(archive, config);
1391
2236
  const _url = await archive.getUrl();
@@ -1394,13 +2239,31 @@ export class CrawlerOrchestrator extends EventEmitter {
1394
2239
  throw new Error(`URL (${_url}) is invalid`);
1395
2240
  }
1396
2241
  setupProgress?.onPhase?.(PHASE_LOADING_CRAWL_STATE);
1397
- const { scraped, pending } = await archive.getCrawlingState();
2242
+ const { scraped, pending, pendingMetadataOnly = [], } = await archive.getCrawlingState();
2243
+ // Unlike `append`/`inventory`/`recrawl`/`retryFailed`, this path
2244
+ // resumes ANY archive including list-mode ones (`fromList: true`,
2245
+ // `recursive: false`) — exactly the #369 scenario. `config.roots`
2246
+ // are always full-scrape targets regardless of `is_metadata_only`
2247
+ // (see `#crawlUntilPendingClears`'s identical root-exclusion
2248
+ // comment for why a root's row can be wrongly flagged by another
2249
+ // page's anchor). `config.roots` is `ExURL#withoutHash` form (may
2250
+ // keep basic-auth userinfo), but `pendingMetadataOnly` entries are
2251
+ // always `url_refs.url` (`withoutHashAndAuth`, auth stripped —
2252
+ // see `insert-page.ts`/`resolve-content-item-id.ts`) — re-parse
2253
+ // each root through the same normalization before comparing, or a
2254
+ // root URL carrying credentials would never match `rootKeys` and
2255
+ // would wrongly stay in `metadataOnlyUrls` below (issue #369 code
2256
+ // review).
2257
+ const rootKeys = new Set(config.roots
2258
+ .map((root) => parseUrl(root, config)?.withoutHashAndAuth)
2259
+ .filter((root) => root !== undefined));
2260
+ const metadataOnlyUrls = pendingMetadataOnly.filter((u) => !rootKeys.has(u));
1398
2261
  setupProgress?.onPhase?.(PHASE_LOADING_RESOURCES);
1399
2262
  const resources = await archive.getResourceUrlList(setupProgress?.onChunkProgress);
1400
2263
  setupProgress?.onPhase?.(PHASE_LOADING_SCRAPED_COUNT);
1401
2264
  const pagesScrapedOffset = await archive.getScrapedHtmlPageCount();
1402
2265
  setupProgress?.onPhase?.(PHASE_RESTORING_CRAWL_STATE);
1403
- orchestrator.#crawler.resume(pending, scraped, resources, pagesScrapedOffset);
2266
+ orchestrator.#crawler.resume(pending, scraped, resources, pagesScrapedOffset, metadataOnlyUrls);
1404
2267
  if (initializedCallback) {
1405
2268
  await initializedCallback(orchestrator, config);
1406
2269
  }
@@ -1409,10 +2272,33 @@ export class CrawlerOrchestrator extends EventEmitter {
1409
2272
  log('URL %s', url.href);
1410
2273
  log('Config %O', config);
1411
2274
  await CrawlerOrchestrator.#preloadDnsBurnedHostCache(archive);
1412
- await orchestrator.crawling([url]);
2275
+ await orchestrator.#crawlUntilPendingClears([url]);
1413
2276
  CrawlerOrchestrator.#finalizeCrawlSession(orchestrator);
1414
2277
  return orchestrator;
1415
2278
  }
2279
+ /**
2280
+ * Shared `PendingUrlsRemainError` recovery step for `append` and
2281
+ * `retryFailed`'s catch blocks (issue #350 code review — `inventory` /
2282
+ * `recrawl` reach the same outcome through their own `ingestionComplete`
2283
+ * branch instead, which has no `.bak` left to clean up by the time it
2284
+ * runs, so this helper is specific to the two `.bak`-restore-by-default
2285
+ * catch shapes).
2286
+ *
2287
+ * `#crawlUntilPendingClears` has already released the archive handle
2288
+ * and left the stub intact for `--resume`/`--retry-failed` by the time
2289
+ * this runs; `write()` never ran, so the original archive file was
2290
+ * never touched. Restoring `.bak` over it would be a wasted
2291
+ * full-archive copy (and show a misleading "Restoring from backup"
2292
+ * phase label) — only the now-unnecessary `.bak` needs cleaning up.
2293
+ * @param setupProgress - Forwarded so the recovery phase label still
2294
+ * reaches the caller's setup `TaskList`.
2295
+ * @param backupPath - The `.bak` path to delete (`unlinkFile`, ENOENT
2296
+ * ignored).
2297
+ */
2298
+ static async #abandonBackupOnPendingRemains(setupProgress, backupPath) {
2299
+ setupProgress?.onPhase?.(RECOVERY_LEAVE_STATE_FOR_RESUME);
2300
+ await ignoreEnoent(unlinkFile(backupPath));
2301
+ }
1416
2302
  /**
1417
2303
  * Seeds {@link dnsBurnedHostCache} from `crawl_errors` history at re-open
1418
2304
  * (append / inventory / retryFailed / resume). Called after Archive.open
@@ -1435,8 +2321,40 @@ export class CrawlerOrchestrator extends EventEmitter {
1435
2321
  }
1436
2322
  }
1437
2323
  /**
1438
- * Persist one `inventory_runs` audit row inside the ingestion phase of a
1439
- * `--inventory` invocation, before the `.bak` is released. Lives as a
2324
+ * Reads back this archive's prior `DedupeCapTracker` observations (see
2325
+ * `Archive.listDedupeCapObservations`) and reconstructs them via
2326
+ * `buildDedupeCapObservation`, for the same five resuming-session static
2327
+ * methods that already call `archive.listDedupeCapShapeKeys()` to seed
2328
+ * `CrawlConfig.preloadedStickyShapeKeys`. Unlike that sticky-shape
2329
+ * preload, this read is skipped entirely when `dedupeCap` is `null` — a
2330
+ * full per-page table scan is not worth paying on every resuming session
2331
+ * that has `--dedupe-cap` disabled, whereas the shape-key `DISTINCT`
2332
+ * query stays cheap enough to always run.
2333
+ * @param archive - The opened archive whose scraped pages are read.
2334
+ * @param dedupeCap - The resolved `CrawlConfig.dedupeCap` for this
2335
+ * session. `null` short-circuits to `[]` without touching the archive.
2336
+ * @param onProgress - Forwarded to `archive.listDedupeCapObservations` —
2337
+ * see that method's docs.
2338
+ * @returns Every qualifying page's reconstructed observation (rows with
2339
+ * no usable shape/meta signal are silently dropped — see
2340
+ * `buildDedupeCapObservation`).
2341
+ */
2342
+ static async #preloadDedupeCapObservations(archive, dedupeCap, onProgress) {
2343
+ if (dedupeCap === null)
2344
+ return [];
2345
+ const rows = await archive.listDedupeCapObservations(onProgress);
2346
+ const observations = [];
2347
+ for (const row of rows) {
2348
+ const observation = buildDedupeCapObservation(row);
2349
+ if (observation) {
2350
+ observations.push(observation);
2351
+ }
2352
+ }
2353
+ return observations;
2354
+ }
2355
+ /**
2356
+ * Persist one `list_reconcile_runs` audit row inside the ingestion phase
2357
+ * of a `--inventory` invocation, before the `.bak` is released. Lives as a
1440
2358
  * static helper because the audit-row shape (timestamp stamping + label
1441
2359
  * auto-gen + the privacy-driven path elision documented below) is a
1442
2360
  * cohesive concern that benefits from staying outside the long
@@ -1451,7 +2369,7 @@ export class CrawlerOrchestrator extends EventEmitter {
1451
2369
  * `computeFileSha256` against the bytes it read from the input txt,
1452
2370
  * before the orchestrator was even invoked). The orchestrator boundary
1453
2371
  * deliberately never sees the absolute path — see
1454
- * {@link InventoryRunAggregates} for the privacy rationale.
2372
+ * {@link ListReconcileRunAggregates} for the privacy rationale.
1455
2373
  *
1456
2374
  * **Audit-write failures abort the ingestion phase.** Swallowing them
1457
2375
  * would only be justified if the audit were the last write after the
@@ -1459,20 +2377,20 @@ export class CrawlerOrchestrator extends EventEmitter {
1459
2377
  * `.bak`-protected ingestion phase the
1460
2378
  * trade-off flips. A failed audit row is restorable: the outer catch
1461
2379
  * copies `.bak` back over the archive and the operator reruns the
1462
- * (short) ingestion from scratch. That keeps `inventory_runs` honest
1463
- * (no "ran but unrecorded" rows) at the cost of one rerun.
2380
+ * (short) ingestion from scratch. That keeps `list_reconcile_runs`
2381
+ * honest (no "ran but unrecorded" rows) at the cost of one rerun.
1464
2382
  *
1465
2383
  * Forward-compat: if an explicit `--label` flag is ever added, thread
1466
2384
  * `labelOverride` through {@link inventory} into the `aggregates`
1467
2385
  * shape so the auto-name can be overridden.
1468
2386
  * @param archive - The opened archive to write the audit row into.
1469
- * @param aggregates - The counts captured during the inventory pass; see {@link InventoryRunAggregates}.
2387
+ * @param aggregates - The counts captured during the inventory pass; see {@link ListReconcileRunAggregates}.
1470
2388
  */
1471
- static async #writeInventoryRunRow(archive, aggregates) {
2389
+ static async #writeListReconcileRunRow(archive, aggregates) {
1472
2390
  const ranAt = new Date().toISOString();
1473
- await archive.recordInventoryRun({
2391
+ await archive.recordListReconcileRun({
1474
2392
  ran_at: ranAt,
1475
- list_label: `inventory-${ranAt}`,
2393
+ list_label: `${aggregates.listLabelPrefix ?? 'inventory'}-${ranAt}`,
1476
2394
  source_file_sha256: aggregates.sourceFileSha256,
1477
2395
  total_lines: aggregates.inventoryUrlsCount,
1478
2396
  new_pages: aggregates.htmlSeedsCount,
@@ -1480,6 +2398,7 @@ export class CrawlerOrchestrator extends EventEmitter {
1480
2398
  scope_skipped: aggregates.outOfScope,
1481
2399
  exclude_skipped: aggregates.excludeSkipped,
1482
2400
  invalid_skipped: aggregates.invalidSkipped,
2401
+ notes: aggregates.notes ?? null,
1483
2402
  });
1484
2403
  }
1485
2404
  /**
@@ -1514,6 +2433,37 @@ export class CrawlerOrchestrator extends EventEmitter {
1514
2433
  clearDnsBurnedHostCache();
1515
2434
  }
1516
2435
  }
2436
+ /**
2437
+ * Resolves a `CrawlConfig.cwd` value to an absolute path before it is
2438
+ * stamped as `Config.createdCwd` (issue #350). `cwd` is trusted as an
2439
+ * absolute base everywhere else in this file (`path.resolve(cwd, ...)` for
2440
+ * `absFilePath`/tmpDir), so a caller-supplied relative `cwd` already
2441
+ * resolves against `process.cwd()` implicitly for archive placement — this
2442
+ * makes that same resolution explicit for the value `Archive.resume` will
2443
+ * later read back, so a relative `createdCwd` can never silently
2444
+ * reintroduce the cwd-dependent resume path this column exists to fix.
2445
+ * `path.resolve` is a no-op when `cwd` is already absolute.
2446
+ * @param cwd - The `CrawlConfig.cwd` value (defaults to `process.cwd()` at each call site).
2447
+ * @returns An absolute path.
2448
+ */
2449
+ function resolveAbsoluteCwd(cwd) {
2450
+ return path.resolve(process.cwd(), cwd);
2451
+ }
2452
+ /**
2453
+ * Builds the `Config` patch that stamps `createdCwd` (issue #350) — the one
2454
+ * field every stub-creating static factory (`crawling`/`append`/`inventory`/
2455
+ * `recrawl`/`retryFailed`; `resume` deliberately excluded, it only reads
2456
+ * this value) must set. Centralised so a future stub-creating mode spreads
2457
+ * this into its `setConfig`/`updateConfig` call instead of hand-rolling
2458
+ * `{ createdCwd: resolveAbsoluteCwd(cwd) }` and risking a forgotten
2459
+ * `resolveAbsoluteCwd` wrap (see that function's JSDoc for why the
2460
+ * resolution itself matters).
2461
+ * @param cwd - The `CrawlConfig.cwd` value for this session.
2462
+ * @returns A one-field `Partial<Config>` patch.
2463
+ */
2464
+ function buildCreatedCwdPatch(cwd) {
2465
+ return { createdCwd: resolveAbsoluteCwd(cwd) };
2466
+ }
1517
2467
  /**
1518
2468
  * Await a filesystem promise but silently swallow only `ENOENT` errors. Any
1519
2469
  * other failure (permissions, disk full, etc.) propagates so the caller can