@nitpicker/crawler 0.22.0 → 0.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (136) hide show
  1. package/lib/archive/archive.d.ts +13 -5
  2. package/lib/archive/archive.js +13 -5
  3. package/lib/archive/cache/extract-archive-to-cache.d.ts +6 -1
  4. package/lib/archive/cache/extract-archive-to-cache.js +13 -6
  5. package/lib/archive/create-adjunct-tables.d.ts +0 -7
  6. package/lib/archive/create-adjunct-tables.js +0 -50
  7. package/lib/archive/create-template-tables.d.ts +30 -0
  8. package/lib/archive/create-template-tables.js +95 -0
  9. package/lib/archive/database.d.ts +1 -1
  10. package/lib/archive/database.js +1 -1
  11. package/lib/archive/db-ops/pages/read/get-crawling-state.d.ts +43 -3
  12. package/lib/archive/db-ops/pages/read/get-crawling-state.js +61 -6
  13. package/lib/archive/db-ops/pages/write/update-page.js +10 -2
  14. package/lib/archive/db-ops/templates/assign-template-labels.d.ts +60 -0
  15. package/lib/archive/db-ops/templates/assign-template-labels.js +187 -0
  16. package/lib/archive/db-ops/{analysis → templates}/replace-page-templates.d.ts +19 -3
  17. package/lib/archive/db-ops/templates/replace-page-templates.js +174 -0
  18. package/lib/archive/db-ops/{analysis → templates}/types.d.ts +38 -0
  19. package/lib/archive/init-schema.d.ts +5 -1
  20. package/lib/archive/init-schema.js +13 -2
  21. package/lib/archive/test-utils/build-full-schema-test-db.d.ts +34 -0
  22. package/lib/archive/test-utils/build-full-schema-test-db.js +74 -0
  23. package/lib/archive/transfer/attach-source-database.d.ts +31 -0
  24. package/lib/archive/transfer/attach-source-database.js +40 -0
  25. package/lib/archive/transfer/build-split-config.d.ts +30 -0
  26. package/lib/archive/transfer/build-split-config.js +42 -0
  27. package/lib/archive/transfer/clear-replaced-page-rows.d.ts +20 -0
  28. package/lib/archive/transfer/clear-replaced-page-rows.js +57 -0
  29. package/lib/archive/transfer/concat-archives.d.ts +55 -0
  30. package/lib/archive/transfer/concat-archives.js +95 -0
  31. package/lib/archive/transfer/content-item-rank-sql.d.ts +21 -0
  32. package/lib/archive/transfer/content-item-rank-sql.js +23 -0
  33. package/lib/archive/transfer/copy-analysis-violations.d.ts +19 -0
  34. package/lib/archive/transfer/copy-analysis-violations.js +43 -0
  35. package/lib/archive/transfer/copy-anchor-edges.d.ts +28 -0
  36. package/lib/archive/transfer/copy-anchor-edges.js +42 -0
  37. package/lib/archive/transfer/copy-dictionaries-for-concat.d.ts +39 -0
  38. package/lib/archive/transfer/copy-dictionaries-for-concat.js +81 -0
  39. package/lib/archive/transfer/copy-dictionaries-for-split.d.ts +29 -0
  40. package/lib/archive/transfer/copy-dictionaries-for-split.js +235 -0
  41. package/lib/archive/transfer/copy-header-set-children.d.ts +27 -0
  42. package/lib/archive/transfer/copy-header-set-children.js +51 -0
  43. package/lib/archive/transfer/copy-image-items.d.ts +21 -0
  44. package/lib/archive/transfer/copy-image-items.js +62 -0
  45. package/lib/archive/transfer/copy-inventory-source-lists.d.ts +30 -0
  46. package/lib/archive/transfer/copy-inventory-source-lists.js +61 -0
  47. package/lib/archive/transfer/copy-journal-tables.d.ts +30 -0
  48. package/lib/archive/transfer/copy-journal-tables.js +56 -0
  49. package/lib/archive/transfer/copy-page-console-logs.d.ts +16 -0
  50. package/lib/archive/transfer/copy-page-console-logs.js +27 -0
  51. package/lib/archive/transfer/copy-page-html-blobs.d.ts +31 -0
  52. package/lib/archive/transfer/copy-page-html-blobs.js +43 -0
  53. package/lib/archive/transfer/copy-page-meta.d.ts +27 -0
  54. package/lib/archive/transfer/copy-page-meta.js +68 -0
  55. package/lib/archive/transfer/copy-page-template-clusters.d.ts +31 -0
  56. package/lib/archive/transfer/copy-page-template-clusters.js +56 -0
  57. package/lib/archive/transfer/copy-page-template-labels.d.ts +34 -0
  58. package/lib/archive/transfer/copy-page-template-labels.js +88 -0
  59. package/lib/archive/transfer/copy-resource-items.d.ts +29 -0
  60. package/lib/archive/transfer/copy-resource-items.js +89 -0
  61. package/lib/archive/transfer/copy-resource-ref-edges.d.ts +20 -0
  62. package/lib/archive/transfer/copy-resource-ref-edges.js +33 -0
  63. package/lib/archive/transfer/copy-simple-page-scoped-tables.d.ts +15 -0
  64. package/lib/archive/transfer/copy-simple-page-scoped-tables.js +34 -0
  65. package/lib/archive/transfer/count-external-pages-in-scope.d.ts +26 -0
  66. package/lib/archive/transfer/count-external-pages-in-scope.js +40 -0
  67. package/lib/archive/transfer/create-transfer-temp-tables.d.ts +30 -0
  68. package/lib/archive/transfer/create-transfer-temp-tables.js +59 -0
  69. package/lib/archive/transfer/dictionary-copy-specs.d.ts +32 -0
  70. package/lib/archive/transfer/dictionary-copy-specs.js +29 -0
  71. package/lib/archive/transfer/drop-transfer-temp-tables.d.ts +9 -0
  72. package/lib/archive/transfer/drop-transfer-temp-tables.js +18 -0
  73. package/lib/archive/transfer/flatten-redirect-chains.d.ts +44 -0
  74. package/lib/archive/transfer/flatten-redirect-chains.js +74 -0
  75. package/lib/archive/transfer/insert-content-items.d.ts +35 -0
  76. package/lib/archive/transfer/insert-content-items.js +116 -0
  77. package/lib/archive/transfer/list-transfer-columns.d.ts +35 -0
  78. package/lib/archive/transfer/list-transfer-columns.js +45 -0
  79. package/lib/archive/transfer/mark-in-scope-content-items.d.ts +31 -0
  80. package/lib/archive/transfer/mark-in-scope-content-items.js +54 -0
  81. package/lib/archive/transfer/merge-archive-configs.d.ts +48 -0
  82. package/lib/archive/transfer/merge-archive-configs.js +78 -0
  83. package/lib/archive/transfer/plan-content-items-for-concat.d.ts +33 -0
  84. package/lib/archive/transfer/plan-content-items-for-concat.js +51 -0
  85. package/lib/archive/transfer/plan-content-items-for-split.d.ts +42 -0
  86. package/lib/archive/transfer/plan-content-items-for-split.js +83 -0
  87. package/lib/archive/transfer/plan-resource-items.d.ts +40 -0
  88. package/lib/archive/transfer/plan-resource-items.js +69 -0
  89. package/lib/archive/transfer/quote-transfer-identifier.d.ts +18 -0
  90. package/lib/archive/transfer/quote-transfer-identifier.js +20 -0
  91. package/lib/archive/transfer/reclassify-resource-externality.d.ts +37 -0
  92. package/lib/archive/transfer/reclassify-resource-externality.js +66 -0
  93. package/lib/archive/transfer/remap-redirect-dest-ids.d.ts +34 -0
  94. package/lib/archive/transfer/remap-redirect-dest-ids.js +51 -0
  95. package/lib/archive/transfer/replace-content-items.d.ts +39 -0
  96. package/lib/archive/transfer/replace-content-items.js +83 -0
  97. package/lib/archive/transfer/simple-page-scoped-tables.d.ts +25 -0
  98. package/lib/archive/transfer/simple-page-scoped-tables.js +38 -0
  99. package/lib/archive/transfer/split-archive.d.ts +55 -0
  100. package/lib/archive/transfer/split-archive.js +98 -0
  101. package/lib/archive/transfer/transfer-action.d.ts +34 -0
  102. package/lib/archive/transfer/transfer-action.js +32 -0
  103. package/lib/archive/transfer/transfer-archive-rows.d.ts +65 -0
  104. package/lib/archive/transfer/transfer-archive-rows.js +158 -0
  105. package/lib/archive/transfer/transfer-dictionary-tables.d.ts +12 -0
  106. package/lib/archive/transfer/transfer-dictionary-tables.js +23 -0
  107. package/lib/archive/transfer/transfer-source-alias.d.ts +9 -0
  108. package/lib/archive/transfer/transfer-source-alias.js +9 -0
  109. package/lib/archive/transfer/types.d.ts +111 -0
  110. package/lib/archive/transfer/types.js +35 -0
  111. package/lib/concat-source-transfer-phases.d.ts +10 -0
  112. package/lib/concat-source-transfer-phases.js +17 -0
  113. package/lib/crawler/build-scope-map.d.ts +21 -0
  114. package/lib/crawler/build-scope-map.js +32 -0
  115. package/lib/crawler-orchestrator.js +10 -16
  116. package/lib/crawler.d.ts +13 -1
  117. package/lib/crawler.js +22 -0
  118. package/lib/split-source-transfer-phases.d.ts +11 -0
  119. package/lib/split-source-transfer-phases.js +18 -0
  120. package/lib/template-classification/classify-archive-page-templates.d.ts +41 -0
  121. package/lib/template-classification/classify-archive-page-templates.js +79 -0
  122. package/lib/template-classification/classify-page-templates.d.ts +37 -0
  123. package/lib/template-classification/classify-page-templates.js +69 -0
  124. package/lib/template-classification/collect-page-stylesheet-urls.d.ts +32 -0
  125. package/lib/template-classification/collect-page-stylesheet-urls.js +130 -0
  126. package/lib/template-classification/create-content-root-hint.d.ts +36 -0
  127. package/lib/template-classification/create-content-root-hint.js +47 -0
  128. package/lib/template-classification/create-page-cluster-factory.d.ts +60 -0
  129. package/lib/template-classification/create-page-cluster-factory.js +98 -0
  130. package/lib/template-classification/types.d.ts +108 -0
  131. package/lib/template-classification/types.js +1 -0
  132. package/lib/transfer-post-phases.d.ts +10 -0
  133. package/lib/transfer-post-phases.js +13 -0
  134. package/package.json +3 -2
  135. package/lib/archive/db-ops/analysis/replace-page-templates.js +0 -84
  136. /package/lib/archive/db-ops/{analysis → templates}/types.js +0 -0
@@ -1,4 +1,4 @@
1
- import type { TemplateClusterReason } from './db-ops/analysis/types.js';
1
+ import type { TemplateClusterReason } from './db-ops/templates/types.js';
2
2
  import type { Config, DedupeCapObservationRow, InsertDedupeCapEventParams, InsertNetworkOutageParams, ListReconcileRunMeta, PageSource } from './types.js';
3
3
  import type { OutageWindow } from '../is-within-outage-window.js';
4
4
  import type { PageData, CrawlerError, Resource } from '../utils/types/types.js';
@@ -310,13 +310,14 @@ export default class Archive extends ArchiveAccessor {
310
310
  }[]): Promise<void>;
311
311
  /**
312
312
  * Replaces the archive's DOM-structure template classification
313
- * (`--templates`) with a fresh SQL-backed set.
313
+ * with a fresh SQL-backed set.
314
314
  *
315
315
  * Thin facade over {@link Database.replacePageTemplates}; kept on
316
- * `Archive` so the analyze pipeline can persist template keys without
316
+ * `Archive` so the crawl-end classification step
317
+ * (`classifyArchivePageTemplates`) can persist template keys without
317
318
  * reaching into the low-level database class directly.
318
319
  * @param templateKeysByUrl - Page URL → template key, as produced by
319
- * `@nitpicker/core`'s `classifyPageTemplates`.
320
+ * `classifyPageTemplates`.
320
321
  * @param clusterReasonsByTemplateKey - Template key → cluster-selection
321
322
  * evidence, if the caller captured it. Omitting this always clears the
322
323
  * previously-stored reasons too — "no reason" means "not captured for
@@ -610,6 +611,13 @@ export default class Archive extends ArchiveAccessor {
610
611
  * @param namespace - Optional namespace forwarded to {@link ArchiveAccessor}.
611
612
  * @param onExtractProgress - Forwarded to {@link extractArchiveToCache} —
612
613
  * see that function's docs for the cache-hit/miss contract.
614
+ * @param onLog - Forwarded to the cache-miss migration pass (issue #294)
615
+ * — a legacy archive's self-healing schema migrations otherwise fall
616
+ * back to a bare `console.error`, which can print mid-redraw of a
617
+ * caller's `Lanes`/`TaskList` display. Omit for that fallback
618
+ * (existing callers — the viewer, MCP, query CLI — do not pass this;
619
+ * only callers driving a `TaskList` row for the extraction, like
620
+ * `concat`/`split`, need to).
613
621
  * @returns A read-only {@link ArchiveAccessor} backed by the cache directory.
614
622
  * @example
615
623
  * ```ts
@@ -618,7 +626,7 @@ export default class Archive extends ArchiveAccessor {
618
626
  * // tears down DB handle on scope exit; cacheDir persists.
619
627
  * ```
620
628
  */
621
- static openCached(filePath: string, namespace?: string | null, onExtractProgress?: (readBytes: number, totalBytes: number) => void): Promise<ArchiveAccessor>;
629
+ static openCached(filePath: string, namespace?: string | null, onExtractProgress?: (readBytes: number, totalBytes: number) => void, onLog?: (message: string) => void): Promise<ArchiveAccessor>;
622
630
  /**
623
631
  * Creates a new archive at the specified file path.
624
632
  * Initializes a temporary working directory and a fresh SQLite database.
@@ -417,13 +417,14 @@ export default class Archive extends ArchiveAccessor {
417
417
  }
418
418
  /**
419
419
  * Replaces the archive's DOM-structure template classification
420
- * (`--templates`) with a fresh SQL-backed set.
420
+ * with a fresh SQL-backed set.
421
421
  *
422
422
  * Thin facade over {@link Database.replacePageTemplates}; kept on
423
- * `Archive` so the analyze pipeline can persist template keys without
423
+ * `Archive` so the crawl-end classification step
424
+ * (`classifyArchivePageTemplates`) can persist template keys without
424
425
  * reaching into the low-level database class directly.
425
426
  * @param templateKeysByUrl - Page URL → template key, as produced by
426
- * `@nitpicker/core`'s `classifyPageTemplates`.
427
+ * `classifyPageTemplates`.
427
428
  * @param clusterReasonsByTemplateKey - Template key → cluster-selection
428
429
  * evidence, if the caller captured it. Omitting this always clears the
429
430
  * previously-stored reasons too — "no reason" means "not captured for
@@ -825,6 +826,13 @@ export default class Archive extends ArchiveAccessor {
825
826
  * @param namespace - Optional namespace forwarded to {@link ArchiveAccessor}.
826
827
  * @param onExtractProgress - Forwarded to {@link extractArchiveToCache} —
827
828
  * see that function's docs for the cache-hit/miss contract.
829
+ * @param onLog - Forwarded to the cache-miss migration pass (issue #294)
830
+ * — a legacy archive's self-healing schema migrations otherwise fall
831
+ * back to a bare `console.error`, which can print mid-redraw of a
832
+ * caller's `Lanes`/`TaskList` display. Omit for that fallback
833
+ * (existing callers — the viewer, MCP, query CLI — do not pass this;
834
+ * only callers driving a `TaskList` row for the extraction, like
835
+ * `concat`/`split`, need to).
828
836
  * @returns A read-only {@link ArchiveAccessor} backed by the cache directory.
829
837
  * @example
830
838
  * ```ts
@@ -833,12 +841,12 @@ export default class Archive extends ArchiveAccessor {
833
841
  * // tears down DB handle on scope exit; cacheDir persists.
834
842
  * ```
835
843
  */
836
- static async openCached(filePath, namespace = null, onExtractProgress) {
844
+ static async openCached(filePath, namespace = null, onExtractProgress, onLog) {
837
845
  const cacheRoot = getArchiveCacheRoot();
838
846
  const cacheKey = await computeArchiveCacheKey(filePath);
839
847
  const cacheDir = resolveArchiveCacheDir(cacheRoot, cacheKey, filePath);
840
848
  log('Open cached: %s (cacheDir=%s)', filePath, cacheDir);
841
- await extractArchiveToCache(filePath, cacheRoot, cacheDir, cacheKey, onExtractProgress);
849
+ await extractArchiveToCache(filePath, cacheRoot, cacheDir, cacheKey, onExtractProgress, onLog);
842
850
  return await Archive.connect(cacheDir, namespace);
843
851
  }
844
852
  /**
@@ -47,6 +47,11 @@
47
47
  * first call actually arrives. Only the first concurrent caller for a
48
48
  * given `cacheDir` sees callbacks; same-`cacheDir` callers deduped
49
49
  * through {@link inFlightByCacheDir} just await the shared promise.
50
+ * @param onLog - Forwarded to the cache-miss writer connection
51
+ * (`runMigrationsOnCacheDir`'s `Database.connect`) so a legacy archive's
52
+ * self-healing schema migrations do not fall back to a bare
53
+ * `console.error` mid-redraw of a caller's display (issue #294). Omit for
54
+ * that fallback — see `Archive.openCached`'s own `onLog` doc.
50
55
  * @returns Resolves once `cacheDir` is ready to be opened read-only.
51
56
  */
52
- export declare function extractArchiveToCache(archivePath: string, cacheRoot: string, cacheDir: string, cacheKey: string, onExtractProgress?: (readBytes: number, totalBytes: number) => void): Promise<void>;
57
+ export declare function extractArchiveToCache(archivePath: string, cacheRoot: string, cacheDir: string, cacheKey: string, onExtractProgress?: (readBytes: number, totalBytes: number) => void, onLog?: (message: string) => void): Promise<void>;
@@ -95,9 +95,14 @@ const inFlightByCacheDir = new Map();
95
95
  * first call actually arrives. Only the first concurrent caller for a
96
96
  * given `cacheDir` sees callbacks; same-`cacheDir` callers deduped
97
97
  * through {@link inFlightByCacheDir} just await the shared promise.
98
+ * @param onLog - Forwarded to the cache-miss writer connection
99
+ * (`runMigrationsOnCacheDir`'s `Database.connect`) so a legacy archive's
100
+ * self-healing schema migrations do not fall back to a bare
101
+ * `console.error` mid-redraw of a caller's display (issue #294). Omit for
102
+ * that fallback — see `Archive.openCached`'s own `onLog` doc.
98
103
  * @returns Resolves once `cacheDir` is ready to be opened read-only.
99
104
  */
100
- export async function extractArchiveToCache(archivePath, cacheRoot, cacheDir, cacheKey, onExtractProgress) {
105
+ export async function extractArchiveToCache(archivePath, cacheRoot, cacheDir, cacheKey, onExtractProgress, onLog) {
101
106
  if (await isCacheDirReady(cacheDir)) {
102
107
  return;
103
108
  }
@@ -105,7 +110,7 @@ export async function extractArchiveToCache(archivePath, cacheRoot, cacheDir, ca
105
110
  if (existing) {
106
111
  return existing;
107
112
  }
108
- const promise = runExtraction(archivePath, cacheRoot, cacheDir, cacheKey, onExtractProgress).finally(() => {
113
+ const promise = runExtraction(archivePath, cacheRoot, cacheDir, cacheKey, onExtractProgress, onLog).finally(() => {
109
114
  inFlightByCacheDir.delete(cacheDir);
110
115
  });
111
116
  inFlightByCacheDir.set(cacheDir, promise);
@@ -120,8 +125,9 @@ export async function extractArchiveToCache(archivePath, cacheRoot, cacheDir, ca
120
125
  * @param cacheDir - Absolute path the extracted contents should end up at.
121
126
  * @param cacheKey - Pre-extraction cache key, re-verified post-extraction.
122
127
  * @param onExtractProgress - See {@link extractArchiveToCache}.
128
+ * @param onLog - See {@link extractArchiveToCache}.
123
129
  */
124
- async function runExtraction(archivePath, cacheRoot, cacheDir, cacheKey, onExtractProgress) {
130
+ async function runExtraction(archivePath, cacheRoot, cacheDir, cacheKey, onExtractProgress, onLog) {
125
131
  await fs.mkdir(cacheRoot, { recursive: true });
126
132
  const releaseLock = await acquireLockWithPeerWait(cacheDir);
127
133
  try {
@@ -167,7 +173,7 @@ async function runExtraction(archivePath, cacheRoot, cacheDir, cacheKey, onExtra
167
173
  // cache entry so the next caller does not get stuck on a
168
174
  // "ready"-marked but broken cache.
169
175
  try {
170
- await runMigrationsOnCacheDir(cacheDir);
176
+ await runMigrationsOnCacheDir(cacheDir, onLog);
171
177
  }
172
178
  catch (error) {
173
179
  await fs.rm(cacheDir, { recursive: true, force: true });
@@ -214,13 +220,14 @@ async function acquireLockWithPeerWait(cacheDir) {
214
220
  * `Archive.connect` read-only open never needs to mutate the cache dir
215
221
  * (and never silently misses a newly-added column).
216
222
  * @param cacheDir - Absolute path to the freshly-extracted cache dir.
223
+ * @param onLog - See {@link extractArchiveToCache}.
217
224
  */
218
- async function runMigrationsOnCacheDir(cacheDir) {
225
+ async function runMigrationsOnCacheDir(cacheDir, onLog) {
219
226
  const dbPath = path.join(cacheDir, 'db.sqlite');
220
227
  if (!(await fileExists(dbPath))) {
221
228
  throw new Error(`Cache directory does not contain db.sqlite: ${cacheDir}`);
222
229
  }
223
- const db = await Database.connect({ filename: dbPath, readOnly: false });
230
+ const db = await Database.connect({ filename: dbPath, readOnly: false, onLog });
224
231
  try {
225
232
  // `Database.connect` ran migrations during init. Closing here
226
233
  // flushes WAL + drops the handle so the read-only re-open in
@@ -32,13 +32,6 @@ import type { Knex } from 'knex';
32
32
  * `crawlEnd`)
33
33
  * - `analysis_text_refs` + `analysis_violations` — analyze-phase findings,
34
34
  * FK → `content_items(id)`
35
- * - `page_templates` — DOM-structure template classification (`--templates`,
36
- * `@nitpicker/core`'s `template-classification/`), one row per classified
37
- * page, FK → `content_items(id)`
38
- * - `page_template_clusters` — one row per distinct `page_templates.template_key`,
39
- * holding `@d-zero/page-cluster`'s cluster-selection evidence (no FK;
40
- * `template_key` is not a `page_templates` FK target, so consistency is
41
- * maintained by replacing both tables together, not by a foreign key)
42
35
  * - `page_html_blobs` + `page_html_ref` — content-addressable HTML
43
36
  * snapshots, FK → `content_items(id)`
44
37
  * - `console_log_items` — content-addressable dictionary of distinct
@@ -31,13 +31,6 @@
31
31
  * `crawlEnd`)
32
32
  * - `analysis_text_refs` + `analysis_violations` — analyze-phase findings,
33
33
  * FK → `content_items(id)`
34
- * - `page_templates` — DOM-structure template classification (`--templates`,
35
- * `@nitpicker/core`'s `template-classification/`), one row per classified
36
- * page, FK → `content_items(id)`
37
- * - `page_template_clusters` — one row per distinct `page_templates.template_key`,
38
- * holding `@d-zero/page-cluster`'s cluster-selection evidence (no FK;
39
- * `template_key` is not a `page_templates` FK target, so consistency is
40
- * maintained by replacing both tables together, not by a foreign key)
41
34
  * - `page_html_blobs` + `page_html_ref` — content-addressable HTML
42
35
  * snapshots, FK → `content_items(id)`
43
36
  * - `console_log_items` — content-addressable dictionary of distinct
@@ -470,49 +463,6 @@ export async function createAdjunctTables(instance) {
470
463
  await instance.raw('CREATE INDEX av_code_order ON analysis_violations(code_sort_key, id)');
471
464
  await instance.raw('CREATE INDEX av_page ON analysis_violations(page_id, id)');
472
465
  }
473
- // DOM-structure template classification (`--templates`). One row per
474
- // internal HTML page that was classified; `page_id` is both the PK and
475
- // the natural key (1:1 with `content_items`), so — unlike
476
- // `analysis_violations`, which is 1:many and needs a surrogate `id` —
477
- // there's nothing to index beyond the PK itself. `WITHOUT ROWID` packs
478
- // rows directly in the PK b-tree, matching `page_html_ref`'s shape
479
- // (small fixed-width row, PK-only lookups).
480
- if (!(await instance.schema.hasTable('page_templates'))) {
481
- await instance.raw(`
482
- CREATE TABLE page_templates (
483
- page_id INTEGER PRIMARY KEY REFERENCES content_items(id),
484
- template_key TEXT NOT NULL
485
- ) WITHOUT ROWID
486
- `);
487
- }
488
- // One row per distinct `template_key` produced by the same `--templates`
489
- // classification run, holding `@d-zero/page-cluster`'s cluster-selection
490
- // evidence (`ClusterReason`, renamed `TemplateClusterReason` on this side)
491
- // as a zstd-compressed JSON blob — same BLOB+codec+size shape as
492
- // `page_html_blobs` below. A column on `page_templates` was rejected: that
493
- // table is one row per *page*, so the same cluster's reason would be
494
- // duplicated across every member page (multi-GB on a large archive with a
495
- // few-hundred-member cluster). A `json_refs` row was also rejected: reason
496
- // payloads differ per cluster (distinct `memberCount`/token sets), so
497
- // content-address dedup would not pay for itself, and `json_refs` is a
498
- // shared dictionary that other tables reference — this table's full
499
- // replace-on-every-run write pattern (see `replacePageTemplates`) would
500
- // otherwise leave orphaned rows behind with no owner able to delete them.
501
- // No FK to `page_templates`: `template_key` is not that table's primary
502
- // key (`page_id` is), so there is nothing to reference — consistency is
503
- // instead maintained by replacing both tables in the same transaction.
504
- if (!(await instance.schema.hasTable('page_template_clusters'))) {
505
- await instance.raw(`
506
- CREATE TABLE page_template_clusters (
507
- template_key TEXT PRIMARY KEY,
508
- member_count INTEGER NOT NULL,
509
- reason_json BLOB NOT NULL,
510
- codec TEXT NOT NULL CHECK(codec IN ('zstd', 'none')),
511
- size_raw INTEGER NOT NULL,
512
- size_stored INTEGER NOT NULL
513
- ) WITHOUT ROWID
514
- `);
515
- }
516
466
  // Content-addressable HTML blob storage. Knex's schema builder doesn't
517
467
  // expose a WITHOUT ROWID toggle, so the BLOB tables are created via raw
518
468
  // SQL. WITHOUT ROWID keeps the rows packed inside the b-tree leaves
@@ -0,0 +1,30 @@
1
+ import type { Knex } from 'knex';
2
+ /**
3
+ * Creates the DOM-structure template classification tables. Kept apart from
4
+ * `createAdjunctTables` because the classification is a derived,
5
+ * archive-wide computation produced by its own crawl-end step
6
+ * (`classifyArchivePageTemplates`), not an observation the crawler writes per
7
+ * page and not an analyze-plugin output (`analysis_violations`) — the two
8
+ * lifecycles and their write paths (`db-ops/templates/` vs `db-ops/analysis/`)
9
+ * share nothing.
10
+ *
11
+ * - `page_templates` — one row per classified page, FK → `content_items(id)`
12
+ * - `page_template_clusters` — one row per distinct `page_templates.template_key`,
13
+ * holding `@d-zero/page-cluster`'s cluster-selection evidence (no FK;
14
+ * `template_key` is not a `page_templates` FK target, so consistency is
15
+ * maintained by replacing both tables together, not by a foreign key)
16
+ * - `page_template_labels` — one row per template key: the stable
17
+ * human-facing name (`events template A`) carried forward across
18
+ * re-classifications (no FK, same reason)
19
+ *
20
+ * Each table is guarded individually (same convergence rule as
21
+ * `createAdjunctTables`) and `initSchema` runs this on every open, so
22
+ * archives created before these tables existed gain them on their next
23
+ * writer open. MUST run after `createEntityTables` because `page_templates`
24
+ * references `content_items(id)`.
25
+ * @param instance - The Knex query builder instance connected to the database.
26
+ * @example
27
+ * await createEntityTables(db);
28
+ * await createTemplateTables(db);
29
+ */
30
+ export declare function createTemplateTables(instance: Knex): Promise<void>;
@@ -0,0 +1,95 @@
1
+ /**
2
+ * Creates the DOM-structure template classification tables. Kept apart from
3
+ * `createAdjunctTables` because the classification is a derived,
4
+ * archive-wide computation produced by its own crawl-end step
5
+ * (`classifyArchivePageTemplates`), not an observation the crawler writes per
6
+ * page and not an analyze-plugin output (`analysis_violations`) — the two
7
+ * lifecycles and their write paths (`db-ops/templates/` vs `db-ops/analysis/`)
8
+ * share nothing.
9
+ *
10
+ * - `page_templates` — one row per classified page, FK → `content_items(id)`
11
+ * - `page_template_clusters` — one row per distinct `page_templates.template_key`,
12
+ * holding `@d-zero/page-cluster`'s cluster-selection evidence (no FK;
13
+ * `template_key` is not a `page_templates` FK target, so consistency is
14
+ * maintained by replacing both tables together, not by a foreign key)
15
+ * - `page_template_labels` — one row per template key: the stable
16
+ * human-facing name (`events template A`) carried forward across
17
+ * re-classifications (no FK, same reason)
18
+ *
19
+ * Each table is guarded individually (same convergence rule as
20
+ * `createAdjunctTables`) and `initSchema` runs this on every open, so
21
+ * archives created before these tables existed gain them on their next
22
+ * writer open. MUST run after `createEntityTables` because `page_templates`
23
+ * references `content_items(id)`.
24
+ * @param instance - The Knex query builder instance connected to the database.
25
+ * @example
26
+ * await createEntityTables(db);
27
+ * await createTemplateTables(db);
28
+ */
29
+ export async function createTemplateTables(instance) {
30
+ // One row per internal HTML page that was classified; `page_id` is both
31
+ // the PK and the natural key (1:1 with `content_items`), so — unlike
32
+ // `analysis_violations`, which is 1:many and needs a surrogate `id` —
33
+ // there's nothing to index beyond the PK itself. `WITHOUT ROWID` packs
34
+ // rows directly in the PK b-tree, matching `page_html_ref`'s shape
35
+ // (small fixed-width row, PK-only lookups).
36
+ if (!(await instance.schema.hasTable('page_templates'))) {
37
+ await instance.raw(`
38
+ CREATE TABLE page_templates (
39
+ page_id INTEGER PRIMARY KEY REFERENCES content_items(id),
40
+ template_key TEXT NOT NULL
41
+ ) WITHOUT ROWID
42
+ `);
43
+ }
44
+ // One row per distinct `template_key` produced by the same classification
45
+ // run, holding `@d-zero/page-cluster`'s cluster-selection evidence
46
+ // (`ClusterReason`, renamed `TemplateClusterReason` on this side) as a
47
+ // zstd-compressed JSON blob — same BLOB+codec+size shape as
48
+ // `page_html_blobs`. A column on `page_templates` was rejected: that
49
+ // table is one row per *page*, so the same cluster's reason would be
50
+ // duplicated across every member page (multi-GB on a large archive with a
51
+ // few-hundred-member cluster). A `json_refs` row was also rejected: reason
52
+ // payloads differ per cluster (distinct `memberCount`/token sets), so
53
+ // content-address dedup would not pay for itself, and `json_refs` is a
54
+ // shared dictionary that other tables reference — this table's full
55
+ // replace-on-every-run write pattern (see `replacePageTemplates`) would
56
+ // otherwise leave orphaned rows behind with no owner able to delete them.
57
+ // No FK to `page_templates`: `template_key` is not that table's primary
58
+ // key (`page_id` is), so there is nothing to reference — consistency is
59
+ // instead maintained by replacing both tables in the same transaction.
60
+ if (!(await instance.schema.hasTable('page_template_clusters'))) {
61
+ await instance.raw(`
62
+ CREATE TABLE page_template_clusters (
63
+ template_key TEXT PRIMARY KEY,
64
+ member_count INTEGER NOT NULL,
65
+ reason_json BLOB NOT NULL,
66
+ codec TEXT NOT NULL CHECK(codec IN ('zstd', 'none')),
67
+ size_raw INTEGER NOT NULL,
68
+ size_stored INTEGER NOT NULL
69
+ ) WITHOUT ROWID
70
+ `);
71
+ }
72
+ // One row per distinct `page_templates.template_key`: the human-facing
73
+ // label (`<section> template <letter>`) assigned to that cluster by
74
+ // `assignTemplateLabels` when `replacePageTemplates` wrote it. Stored
75
+ // rather than derived at read time because a label's whole point is to
76
+ // stay attached to the same template across re-classifications, and
77
+ // nothing derivable from the key alone survives one — `cluster:<n>` is
78
+ // the library's per-run index and `css:<hash>` changes with the
79
+ // stylesheet set. `replacePageTemplates` carries labels forward by member
80
+ // overlap against the previous run's `page_templates` before replacing
81
+ // it. Kept apart from `page_template_clusters` because that table's rows
82
+ // are best-effort (a cluster may have no captured reason) while every
83
+ // cluster gets a label. `section` is NULL for a site-wide label (members
84
+ // span several top-level directories). No FK, same reasoning as
85
+ // `page_template_clusters`.
86
+ if (!(await instance.schema.hasTable('page_template_labels'))) {
87
+ await instance.raw(`
88
+ CREATE TABLE page_template_labels (
89
+ template_key TEXT PRIMARY KEY,
90
+ section TEXT,
91
+ ordinal INTEGER NOT NULL
92
+ ) WITHOUT ROWID
93
+ `);
94
+ }
95
+ }
@@ -1,4 +1,4 @@
1
- import type { TemplateClusterReason } from './db-ops/analysis/types.js';
1
+ import type { TemplateClusterReason } from './db-ops/templates/types.js';
2
2
  import type { JsonLdRow, MainContentAudioRow, MainContentButtonRow, MainContentCanvasRow, MainContentCustomElementRow, MainContentHeadingRow, MainContentIframeRow, MainContentImageRow, MainContentTableRow, MainContentVideoRow, PageTechnologyRow, TechnologySignalRow } from './meta/types.js';
3
3
  import type { Config, DatabaseOption, DB_Redirect, DB_Resource, DatabaseEvent, DedupeCapObservationRow, InsertDedupeCapEventParams, InsertNetworkOutageParams, ListReconcileRunMeta, PageFilter, PageSource, ResetPagesByUrlsResult } from './types.js';
4
4
  import type { OutageWindow } from '../is-within-outage-window.js';
@@ -8,7 +8,6 @@ import { emitError } from '../utils/error/emit-error.js';
8
8
  import { createWriteRefCaches } from './db-ops/_shared/create-write-ref-caches.js';
9
9
  import { retrySetting } from './db-ops/_shared/retry-setting.js';
10
10
  import { replaceAnalysisViolations as replaceAnalysisViolationsOp } from './db-ops/analysis/replace-analysis-violations.js';
11
- import { replacePageTemplates as replacePageTemplatesOp } from './db-ops/analysis/replace-page-templates.js';
12
11
  import { getAnchorsOnPage as getAnchorsOnPageOp } from './db-ops/anchors/get-anchors-on-page.js';
13
12
  import { getBaseUrl as getBaseUrlOp } from './db-ops/config/get-base-url.js';
14
13
  import { getConfig as getConfigOp } from './db-ops/config/get-config.js';
@@ -71,6 +70,7 @@ import { getResources as getResourcesOp } from './db-ops/resources/get-resources
71
70
  import { insertInventoryResources as insertInventoryResourcesOp } from './db-ops/resources/insert-inventory-resources.js';
72
71
  import { insertResourceReferrers as insertResourceReferrersOp } from './db-ops/resources/insert-resource-referrers.js';
73
72
  import { insertResource as insertResourceOp } from './db-ops/resources/insert-resource.js';
73
+ import { replacePageTemplates as replacePageTemplatesOp } from './db-ops/templates/replace-page-templates.js';
74
74
  import { mkdir } from './filesystem/mkdir.js';
75
75
  import { LibsqlDialect } from './libsql-dialect.js';
76
76
  /**
@@ -7,7 +7,7 @@ import type { Knex } from 'knex';
7
7
  * setSkippedPage / setExternalPage / outright setPage success or failure.
8
8
  *
9
9
  * `pending` is intentionally STRICT — not "every `scraped = 0` row".
10
- * Three filters apply:
10
+ * Four filters apply:
11
11
  *
12
12
  * 1. `scraped = 0` — work still incomplete.
13
13
  * 2. `is_external = 0` — only in-scope work. External URLs go through a
@@ -36,6 +36,46 @@ import type { Knex } from 'knex';
36
36
  * URL came from the operator's URL list (no anchor referrer) and
37
37
  * `resetFailedPages` puts it back at `scraped = 0`. Without this
38
38
  * clause those legitimate retries would be dropped on resume.
39
+ * 4. **Confirmed same-cluster trap exclusion** (issue #350): a row whose
40
+ * URL shape (`computeShapeKey`) matches a `dedupe_cap_events.shape_key`
41
+ * already recorded in this archive is dropped, UNLESS its `source` is
42
+ * `'inventory-seed'` (an operator-listed URL, not an anchor-discovered
43
+ * one — the same "explicit URL survives cap" carve-out `resetPagesByUrls`
44
+ * gives `--recrawl`). NOT the same as `resetFailedPages`'s own
45
+ * same-shape exclusion, which drops a matching candidate regardless of
46
+ * `source` — a `scraped=1, status=-1` inventory-seed row of a
47
+ * confirmed-capped shape is therefore excluded there too and never
48
+ * resets to `scraped=0` for `--retry-failed` to pick back up. That
49
+ * asymmetry pre-dates this filter and is unrelated to it (out of scope
50
+ * here): this filter only decides what `getCrawlingState` reports as
51
+ * `pending`, never whether a `scraped=1` row gets reset in the first
52
+ * place.
53
+ *
54
+ * Why this is needed: `--dedupe-cap`'s enqueue gate (`crawler.ts`'s
55
+ * `addUrl` closure) only stops a capped shape's anchor from being
56
+ * ADDED TO THE QUEUE in memory — it does not stop `replaceAnchorEdges`
57
+ * (`update-page.ts`) from writing a `scraped = 0` row for that same
58
+ * anchor (post-hoc marking, `content_items.dedupe_cap_event_id`,
59
+ * deliberately needs that row to exist). Before this filter, such a
60
+ * row still satisfied filter 3 (it has an anchor referrer) and entered
61
+ * `pending`, so `CrawlerOrchestrator#crawlUntilPendingClears`'s
62
+ * auto-retry loop (and any `--resume`/`--retry-failed`/`--append`) would
63
+ * requeue it — `Crawler#resume`'s `LinkList#resume` has no cap gate of
64
+ * its own — actually fetch the trap page, and its anchors would create
65
+ * a fresh batch of same-shape `scraped = 0` rows. Pending never shrank,
66
+ * so the loop ended in `PendingUrlsRemainError('no-progress')` even
67
+ * though nothing was actually wrong with the target site.
68
+ *
69
+ * Why not skip the row instead of merely omitting it from `pending`:
70
+ * this function is read-only — leaving `is_skipped`/`skip_reason`
71
+ * unset keeps `dedupe_cap_event_id` backfill (`viewer-build`) as the
72
+ * single place that judges a row "capped", matching the archive's
73
+ * existing dedupe-cap post-hoc-marking pattern rather than adding a
74
+ * second one here.
75
+ *
76
+ * A row whose shape cannot be computed (`computeShapeKey` returns
77
+ * `null`) stays in `pending` — no signal either way, same
78
+ * err-on-the-side-of-retrying choice `resetFailedPages` makes.
39
79
  *
40
80
  * The defensive shape is on purpose: the data source can drift into
41
81
  * anomalous states under interruption, but the reader must never throw
@@ -62,8 +102,8 @@ import type { Knex } from 'knex';
62
102
  * methods carry.
63
103
  * @param knex - Knex query builder connected to the archive DB.
64
104
  * @returns An object with `scraped` (completed URLs), `pending` (the
65
- * strict set of in-scope, anchor-referenced, unfinished URLs), and
66
- * `pendingMetadataOnly` (the subset of `pending` whose
105
+ * strict set of in-scope, anchor-referenced, unfinished, non-capped
106
+ * URLs), and `pendingMetadataOnly` (the subset of `pending` whose
67
107
  * `content_items.is_metadata_only` was persisted as `1` — see
68
108
  * `replaceAnchorEdges`/`resolveContentItemId`). Callers that resume a
69
109
  * crawl (`Crawler#resume` → `LinkList#resume`) pass this subset through
@@ -1,3 +1,5 @@
1
+ import { computeShapeKey } from '../../../../crawler/dedupe/compute-shape-key.js';
2
+ import { listDedupeCapShapeKeys } from '../../dedupe-cap/list-dedupe-cap-shape-keys.js';
1
3
  /**
2
4
  * Retrieves the current crawling state by listing scraped and pending URLs.
3
5
  *
@@ -6,7 +8,7 @@
6
8
  * setSkippedPage / setExternalPage / outright setPage success or failure.
7
9
  *
8
10
  * `pending` is intentionally STRICT — not "every `scraped = 0` row".
9
- * Three filters apply:
11
+ * Four filters apply:
10
12
  *
11
13
  * 1. `scraped = 0` — work still incomplete.
12
14
  * 2. `is_external = 0` — only in-scope work. External URLs go through a
@@ -35,6 +37,46 @@
35
37
  * URL came from the operator's URL list (no anchor referrer) and
36
38
  * `resetFailedPages` puts it back at `scraped = 0`. Without this
37
39
  * clause those legitimate retries would be dropped on resume.
40
+ * 4. **Confirmed same-cluster trap exclusion** (issue #350): a row whose
41
+ * URL shape (`computeShapeKey`) matches a `dedupe_cap_events.shape_key`
42
+ * already recorded in this archive is dropped, UNLESS its `source` is
43
+ * `'inventory-seed'` (an operator-listed URL, not an anchor-discovered
44
+ * one — the same "explicit URL survives cap" carve-out `resetPagesByUrls`
45
+ * gives `--recrawl`). NOT the same as `resetFailedPages`'s own
46
+ * same-shape exclusion, which drops a matching candidate regardless of
47
+ * `source` — a `scraped=1, status=-1` inventory-seed row of a
48
+ * confirmed-capped shape is therefore excluded there too and never
49
+ * resets to `scraped=0` for `--retry-failed` to pick back up. That
50
+ * asymmetry pre-dates this filter and is unrelated to it (out of scope
51
+ * here): this filter only decides what `getCrawlingState` reports as
52
+ * `pending`, never whether a `scraped=1` row gets reset in the first
53
+ * place.
54
+ *
55
+ * Why this is needed: `--dedupe-cap`'s enqueue gate (`crawler.ts`'s
56
+ * `addUrl` closure) only stops a capped shape's anchor from being
57
+ * ADDED TO THE QUEUE in memory — it does not stop `replaceAnchorEdges`
58
+ * (`update-page.ts`) from writing a `scraped = 0` row for that same
59
+ * anchor (post-hoc marking, `content_items.dedupe_cap_event_id`,
60
+ * deliberately needs that row to exist). Before this filter, such a
61
+ * row still satisfied filter 3 (it has an anchor referrer) and entered
62
+ * `pending`, so `CrawlerOrchestrator#crawlUntilPendingClears`'s
63
+ * auto-retry loop (and any `--resume`/`--retry-failed`/`--append`) would
64
+ * requeue it — `Crawler#resume`'s `LinkList#resume` has no cap gate of
65
+ * its own — actually fetch the trap page, and its anchors would create
66
+ * a fresh batch of same-shape `scraped = 0` rows. Pending never shrank,
67
+ * so the loop ended in `PendingUrlsRemainError('no-progress')` even
68
+ * though nothing was actually wrong with the target site.
69
+ *
70
+ * Why not skip the row instead of merely omitting it from `pending`:
71
+ * this function is read-only — leaving `is_skipped`/`skip_reason`
72
+ * unset keeps `dedupe_cap_event_id` backfill (`viewer-build`) as the
73
+ * single place that judges a row "capped", matching the archive's
74
+ * existing dedupe-cap post-hoc-marking pattern rather than adding a
75
+ * second one here.
76
+ *
77
+ * A row whose shape cannot be computed (`computeShapeKey` returns
78
+ * `null`) stays in `pending` — no signal either way, same
79
+ * err-on-the-side-of-retrying choice `resetFailedPages` makes.
38
80
  *
39
81
  * The defensive shape is on purpose: the data source can drift into
40
82
  * anomalous states under interruption, but the reader must never throw
@@ -61,8 +103,8 @@
61
103
  * methods carry.
62
104
  * @param knex - Knex query builder connected to the archive DB.
63
105
  * @returns An object with `scraped` (completed URLs), `pending` (the
64
- * strict set of in-scope, anchor-referenced, unfinished URLs), and
65
- * `pendingMetadataOnly` (the subset of `pending` whose
106
+ * strict set of in-scope, anchor-referenced, unfinished, non-capped
107
+ * URLs), and `pendingMetadataOnly` (the subset of `pending` whose
66
108
  * `content_items.is_metadata_only` was persisted as `1` — see
67
109
  * `replaceAnchorEdges`/`resolveContentItemId`). Callers that resume a
68
110
  * crawl (`Crawler#resume` → `LinkList#resume`) pass this subset through
@@ -77,7 +119,7 @@ export async function getCrawlingState(knex) {
77
119
  .where('content_items.scraped', 1);
78
120
  const scraped = $scraped.map(ex);
79
121
  const $pending = await knex
80
- .select('ur.url as url', 'ci.is_metadata_only as isMetadataOnly')
122
+ .select('ur.url as url', 'ci.is_metadata_only as isMetadataOnly', 'ci.source as source')
81
123
  .from({ ci: 'content_items' })
82
124
  .join({ ur: 'url_refs' }, 'ur.id', 'ci.url_id')
83
125
  .where('ci.scraped', 0)
@@ -96,8 +138,21 @@ export async function getCrawlingState(knex) {
96
138
  .whereRaw('anchor_edges.href_page_id = ci.id');
97
139
  }).orWhereNot('ci.source', 'crawled');
98
140
  });
99
- const pending = $pending.map(ex);
100
- const pendingMetadataOnly = $pending.filter((r) => r.isMetadataOnly === 1).map(ex);
141
+ // Confirmed same-cluster trap exclusion (filter 4, see this function's
142
+ // JSDoc) — an archive with no recorded cap events behaves exactly as
143
+ // before this filter existed (`cappedShapeKeys.size === 0` short-circuits
144
+ // to a no-op, same guard `resetFailedPages` uses).
145
+ const cappedShapeKeys = new Set(await listDedupeCapShapeKeys(knex));
146
+ const $notCapped = cappedShapeKeys.size === 0
147
+ ? $pending
148
+ : $pending.filter((row) => {
149
+ if (row.source === 'inventory-seed')
150
+ return true;
151
+ const shapeKey = computeShapeKey(row.url);
152
+ return shapeKey === null || !cappedShapeKeys.has(shapeKey);
153
+ });
154
+ const pending = $notCapped.map(ex);
155
+ const pendingMetadataOnly = $notCapped.filter((r) => r.isMetadataOnly === 1).map(ex);
101
156
  return {
102
157
  scraped,
103
158
  pending,
@@ -294,8 +294,16 @@ async function readSourceByUrl(trx, caches, url) {
294
294
  * `processAnchors` (`handle-scrape-end.ts`) decides whether to queue the
295
295
  * anchor for a full or metadata-only scrape: `!recursive || isExternal`.
296
296
  * Both `recursive` and a given URL's `isExternal` are constant for the
297
- * whole crawl session, so this is a pure recomputation, not a second
298
- * source of truth (#369).
297
+ * duration of one `CrawlerOrchestrator#crawling()` invocation (this is a
298
+ * pure recomputation of that call's own decision, not a second source of
299
+ * truth, #369) — NOT necessarily across the whole session:
300
+ * `#crawlUntilPendingClears`'s auto-retry loop (issue #350) always
301
+ * re-invokes `crawling([], { recursive: false, isRetryContinuation: true })`
302
+ * for a retry round regardless of the session's original `recursive`
303
+ * value, so the SAME URL anchored again during a retry round can compute
304
+ * a different `is_metadata_only` verdict than it did on the original
305
+ * pass. `resolveContentItemId`'s ratchet lets the later call's opinion
306
+ * win, same as it does for any other repeat discovery.
299
307
  */
300
308
  async function replaceAnchorEdges(trx, caches, pageId, page, anchorLineageSource, recursive) {
301
309
  if (page.anchorList.length === 0) {