Skip to content

v2026.09.02 - #354

Merged
admonstrator merged 53 commits into
mainfrom
nightly
Sep 24, 2026
Merged

admonstrator merged 53 commits into
mainfrom
nightly

Conversation

@admonstrator

Copy link
Copy Markdown
Owner

Support for new Simplify/Duplicate feature added

admonstrator and others added 30 commits September 18, 2026 17:46
Background
Paperless-ngx accumulates near-duplicate tags and correspondents
("Amazon" / "amazon", "Mueller GmbH" / "Mueller GmbH & Co. KG"). The
Duplicates page will find such groups on request, let the user pick a
survivor and merge the rest through the Paperless-ngx API, with a local
log that can undo a merge. This commit lays down everything the three
parts (matcher, merge service and routes, page) have to agree on before
they are built in parallel.

Changes
- models/document.js: migration v11 with entity_merges (one row per
  merge, JSON columns carrying everything an undo needs) and
  entity_merge_dismissals (pairs marked "not a duplicate"); methods
  addEntityMerge, getEntityMerges, getEntityMergeById,
  updateEntityMergeUndo, addEntityMergeDismissals,
  listEntityMergeDismissals, removeEntityMergeDismissal and
  replaceEntityInLocalRecords, which points history and original rows
  at another tag (by id) or correspondent (by name in history, by id in
  originals).
- services/entityNameMatcher.js: pure module declaring the kinds, match
  reasons, group warnings, sensitivity presets and the group shape;
  star-shaped clustering without chaining, target suggestion and
  warnings are implemented, the scorer is a placeholder that only
  recognises names equal after trimming and lowercasing.
- schemas.js: swagger components DuplicateGroup, DuplicateGroupMember,
  DuplicateScanResult, EntityMergeRequest, EntityMergeResult,
  EntityMergeSourceResult, EntityMergeLogEntry, EntityMergeUndoResult,
  EntityMergeDismissRequest, EntityMergeDismissal; OPENAPI/openapi.json
  regenerated.
- scripts/run-tests.js and package.json: area `duplicates` with five
  tests, three of them placeholders that the phase work replaces.

Testing
- tests/test-entity-merge-model.js: six cases for the migration, the
  log, the undo state, the dismissals and the local rewrite.
- tests/test-entity-name-matcher.js: seven cases pinning the exports,
  pairKey, the naive scorer, group shape, dismissals and warnings.
- node scripts/run-tests.js --all: 89 passed, 7 skipped offline, 0 failed.

Impact
No route, page or behaviour changes yet. The migration runs once at
startup and creates two empty tables.

Upstream Status
Not applicable; the feature is specific to this fork.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV
…essService

Adds listEntities, getEntity, findEntityByExactName, createEntity, updateEntity,
deleteEntity, getDocumentIdsByEntity, getDocumentsByIds, bulkEditDocuments and
clearEntityCaches. Unlike the existing readers these throw instead of returning
an empty result, so a scan can never report "no duplicates" for an unreachable
instance and a merge never deletes an object it could not verify. The router
harness stubs them so every other test stays offline.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV
…respondents

Background

Tags and correspondents drift over the years: "Amazon", "amazon" and
"Amazon EU S.a.r.l." end up side by side, "Rechnung" next to "Rechnungen".
Paperless-ngx has no way to fold them together, and doing it by hand means
re-tagging every document first, because an object that still has documents
cannot be deleted without losing them. Nobody does that twice, so the archive
keeps the duplicates.

This is the backend of the Duplicates page: find such groups on request, merge
a group into one survivor, and undo that merge afterwards. Nothing runs on its
own, no AI is involved in the matching, and the scan loop is untouched.

Changes

- services/duplicateMergeService.js (new singleton) with scan(), merge(),
  undo() and dismiss(). The merge order per source is: snapshot the source and
  the target's matching rule, read the source's documents, remember (for tags)
  which of them already carried the target, move them with one bulk edit, ask
  Paperless-ngx again whether the source is now empty, copy a matching rule if
  asked, delete, and rewrite the local history and original rows. A source that
  still has documents after the move is reported, never deleted; a source the
  token may not change is skipped with a reason and the merge continues.
  Everything an undo needs is written to entity_merges even for a partial
  merge, because after the DELETE it exists nowhere else.
  undo() re-creates each deleted source (adopting a same-named object that
  exists again, and retrying without `owner` when Paperless-ngx refuses it),
  hands back only the documents that still carry the target, removes the target
  only from the documents that did not carry it before the merge, reverts a
  copied matching rule when the target still has exactly that rule, and
  rewrites the local rows back.
  Refusals carry an HTTP status (MergeValidationError): 400 validation, 404
  missing object, 409 running scan or already undone, 502 Paperless-ngx.
- routes/setup.js: one contiguous block with the page route GET /duplicates
  and GET /api/duplicates/scan, POST /api/duplicates/merge, POST
  /api/duplicates/dismiss, GET /api/duplicates/dismissals, DELETE
  /api/duplicates/dismissals/:id, GET /api/duplicates/log and POST
  /api/duplicates/log/:id/undo, each with its @Swagger documentation. A partial
  merge and a failed undo answer 200 with success: false — the request worked,
  the operation did not.
- schemas.js: three optional additions to the contract components —
  DuplicateScanResult.paperlessUrl, EntityMergeDismissRequest.names and
  copiedMatchingRule on a log entry's source. Nothing renamed or removed.
- OPENAPI/openapi.json regenerated.
- tests/helpers/fake-paperless.js (new): an in-memory Paperless-ngx with
  derived document_count, case sensitive unique names, a permission flag, an
  absolute `next` link on a foreign host and bulk edits that can be told to
  skip a document. Serves both suites and a real HTTP server in front of it.

Testing

- node scripts/run-tests.js --all -> 89 passed, 7 skipped offline, 0 failed
  (unchanged against the contract commit).
- tests/test-duplicate-merge-service.js: 14 cases, from paging over the
  verification veto, the permission skip, the scan lock and the validation
  refusals to four undo variants (new id, adopted object, documents changed
  meanwhile, rule changed meanwhile).
- tests/test-duplicates-endpoints.js: 9 cases through the router harness —
  authentication, the scan shape, the merge/undo round trip, the partial merge
  answering success: false, the dismissal round trip and log paging.
- A running instance on port 3101 against an HTTP Paperless-ngx stand-in:
  scan found both groups, a merge of two tags into one moved three documents
  and copied the matching rule, the log showed the row, the undo restored both
  tags under new ids, moved the three documents back, left the target on the
  one document that already carried it, reverted the rule, and a second undo
  answered 409.

Impact

Nothing is scheduled and no existing route changes. paperlessService only gains
methods. The merge writes to Paperless-ngx and to the local tables, always
started by the user, always undoable from the log. An undo gives the restored
objects new ids: saved filters or rules in Paperless-ngx that point at the old
id do not come back with it.

Upstream Status

Not applicable — the Duplicates page does not exist upstream.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV
Background
Merging tags or correspondents means moving documents with the
Paperless-ngx bulk edit endpoint, verifying the source is empty, then
deleting it, and keeping enough locally to undo the whole thing.

Changes
- services/paperlessService.js: kind-neutral entity methods (list, get,
  find by name, create, update, delete), document ids by entity,
  documents by ids, bulk edit in batches, cache clearing.
- services/duplicateMergeService.js: scan, merge (verify before delete,
  optional matching-rule copy, local record rewrite, log row) and undo
  (re-create or adopt, re-attach only documents that still carry the
  target, revert a copied rule, rewrite local records back).
- routes/setup.js: /duplicates page route and /api/duplicates/* with
  swagger docs; OPENAPI/openapi.json regenerated.
- tests/helpers/mount-router.js: stubs for the new methods.
- tests/test-duplicate-merge-service.js, tests/test-duplicates-endpoints.js.

Testing
See the agent's suites and the fake Paperless-ngx run in its report; the
lead re-ran the whole runner after the merge.

Impact
New routes only; no existing route changed.

Upstream Status
Not applicable.
…ests

Background
The Duplicates feature needs a place to look at what the matcher found before
anything is deleted in Paperless-ngx. The phase contract fixes the wire format
(services/entityNameMatcher.js, the Duplicate*/EntityMerge* schemas); this is
the page that renders it and drives the seven /api/duplicates endpoints.

Changes
- views/duplicates.ejs: new page. Controls module (#dupControls: kind segment,
  sensitivity select built from the route's `sensitivity` local, "Include
  hidden pairs", #dupScanBtn), a stats row (#dupStats, hidden until a scan),
  the results area (#dupResults) with the pre-scan empty state, "Recent merges"
  (#dupLog) and the "Hidden pairs" drawer (#dupDismissals). Every local is
  guarded and falls back to the matcher's presets, so the view renders on its
  own.
- public/js/duplicates.js: new ES module. Scan, group cards with the confidence
  meter, reason chips, one warning alert per warning and a stacked member
  table; changing the Keep radio hands the old target back to the sources.
  Merge goes through the kernel's confirmDialog, which names the document count
  and every object that will be deleted and offers the matching-rule copy when
  the group carries has-matching-rule and the chosen target has none. Success
  collapses the card into an ok summary, a partial result lists each source's
  error and keeps the buttons. Log with "Show more" and undo, hidden pairs with
  "Show again". Everything written into innerHTML goes through escapeHtml, a
  number coercion or a helper whose name says its value is already markup.
- public/css/pages/duplicates.css: new, one @layer pages block, dup- classes
  only — the controls row, the card head, the meter width, the member column
  widths and the dialog blocks. Linked after queues.css in head-start.ejs.
- views/partials/nav.ejs: /duplicates in the first group after History. No
  `tab` key, so the phone tab bar is unchanged and the drawer reaches it.
- public/icons.svg: new i-merge symbol (two branches joining into one).
- tests/test-duplicates-ui.js: replaces the contract placeholder with 14
  checks — the view renders through the real shell partials and carries the
  agreed ids and sensitivity options, the rail lists the entry and the tab bar
  does not, the stylesheet link sits after queues.css, the stylesheet is one
  @layer pages block of dup- selectors, the icon exists, every interpolation in
  the page script's markup is escaped or a number, no inline handlers, and the
  page has a label for every match reason and group warning the matcher can
  produce.

Testing
- node scripts/run-tests.js --all -> 93 passed, 3 skipped (login-mfa-flow,
  scan-stop-flow, poppler-render-real), 0 failed.
- eslint, prettier and stylelint clean on every touched file.
- Reviewed in Chromium against a throwaway mock server with four fixture
  groups, a partial merge, a twelve-entry log and two hidden pairs: 1280x900
  and 390x844, light and dark, for the initial state, the results, the merge
  dialog, a finished merge, a partial merge, the log with the undo dialog, an
  undo that failed, the empty result and the scanning skeletons. No horizontal
  overflow at 390px in any of the 32 shots.

Impact
A new authenticated page; no existing page, route or stylesheet changes
behaviour. The nav entry appears on the rail for every user. Nothing on the
page runs without a click.

Upstream Status
Not in clusterzx/paperless-ai; next-only feature.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV
Background
The user needs a screen to start a scan, read why the page thinks two
names are the same, choose the survivor, confirm, and undo from a log.

Changes
- views/duplicates.ejs, public/js/duplicates.js,
  public/css/pages/duplicates.css: the page, its module script and its
  page-layer stylesheet.
- views/partials/nav.ejs: "Duplicates" after "History".
- views/partials/shell/head-start.ejs: stylesheet link.
- public/icons.svg: i-merge symbol.
- tests/test-duplicates-ui.js: render, nav, layer and escaping checks.

Testing
Mock server and screenshots in the agent's report; the lead ran the real
chain after the merge.

Impact
One new navigation entry; nothing else changes for existing pages.

Upstream Status
Not applicable.
Background

The Duplicates page needs a reason for every pair it offers, not a
similarity number. An archive that grew over years holds "Amazon" next to
"amazon" and "Amazon EU S.a.r.l.", "Rechnung" next to "Rechnungen",
"Müller GmbH" next to "Mueller GmbH & Co. KG" - three kinds of drift that
want three different explanations. The contract commit shipped the
vocabulary and an exact-match placeholder; this fills it in.

Changes

- services/entityNameMatcher.js: normalizeName now builds all four fields
  of NormalizedName (key, asciiKey with ae/oe/ue/ss before the remaining
  diacritics are dropped, tokens, foldedKey with legal forms removed for
  correspondents and the plural of the last word folded for tags).
- scorePair walks seven tiers and returns the strongest one: 1.00
  exact-normalized, 0.98 umlaut-variant, 0.95 legal-form, 0.92 plural,
  0.90 token-order, 0.85 prefix, 0.75-0.94 fuzzy. Fuzzy is the best of
  Jaro-Winkler, Damerau-Levenshtein, bigram Dice and a token-wise
  Jaro-Winkler that finds reordered spellings; it is capped at 0.94 so no
  fuzzy pair survives the strict preset.
- Guards: names shorter than four characters only match exactly; tiers 6
  and 7 only look at pairs that share the first three characters or a
  folded token of four; names of the same shape have to fit word by word;
  Jaro-Winkler needs a length ratio of 0.75. The file header documents
  every constant, every guard and the known trade-offs.
- Jaro, Jaro-Winkler, Damerau-Levenshtein and Dice are written out (no new
  dependency) and exported for their own tests. Scratch buffers and cheap
  bounds from the shared characters keep them out of the allocator.
- findDuplicateGroups keeps the contract semantics and stops comparing
  every pair: names are bucketed by the keys of tiers 1-5 and, for tiers 6
  and 7, by their first three characters and their folded tokens. The
  buckets use the same rule as the scorer's guard, so blocking can only
  save work, never change a result. MatchOptions grew the optional
  candidateStrategy: 'pairwise' is the reference the tests compare against.
- tests/test-entity-name-matcher.js replaces the placeholder with 48
  cases: the seven contract ones unchanged, normalisation step by step,
  every tier with the archive names it was written for, the guards, the
  presets, the metrics, the clustering, blocking against the reference and
  the timing budget.

Testing

- node scripts/run-tests.js --test entity-name-matcher -> 48 passed.
- node scripts/run-tests.js --all -> 89 passed, 7 skipped offline, 0
  failed (unchanged from the contract commit apart from 41 new cases).
- 300 generated names: blocking and pairwise scoring return identical
  groups for both kinds at all three presets.
- 5000 generated correspondents in ~0.95 s, 5000 tags in ~1.25 s.
- Looked at the groups of a hand-written drifted archive at all three
  presets and fixed what it showed: Jaro-Winkler paired "Rechnungen" with
  "Rechnungswesen" at 0.94 until the length ratio was raised to 0.75.
- npx eslint, npx prettier --check on both files: clean.

Impact

Pure module, no I/O, no dependency, no API surface. The merge service and
the page see the frozen MATCH_REASONS and GROUP_WARNINGS values they were
promised; only the scores behind them are real now.

Upstream Status

Not applicable, the Duplicates feature does not exist upstream.

Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV
Background
An undo re-creates the deleted tag or correspondent first and moves the
documents back second. When Paperless-ngx dropped the connection between
the two steps, the log entry was stamped "undone" although the documents
still sat on the target, and the page offered no way to try again.

Changes
- services/duplicateMergeService.js: an undo counts as "undone" only when
  every source is back and none of them reports an error; otherwise the
  entry stays "undo_failed" and undoable. The next attempt adopts the
  re-created entry by name and moves the remaining documents. The undo
  result now carries performedBy.
- public/js/duplicates.js: the log offers "Retry undo" on an entry whose
  undo failed.
- schemas.js, OPENAPI/openapi.json: performedBy on EntityMergeUndoResult.

Testing
- tests/test-duplicate-merge-service.js: new case 16 fails the first
  bulk edit of an undo, asserts undo_failed with the entry re-created and
  the documents untouched, then asserts the second attempt adopts the
  entry and finishes as undone.
- node scripts/run-tests.js --area duplicates: 5/5.

Impact
Only the undo status rule and one button label change.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV
… them

The character intersection of two names bounds Jaro-Winkler, the edit
distance and Dice, but computing it for a pair that none of the three can
score is wasted work. Gate it behind the three length checks and widen the
budget of the tags timing case, which is the worst bucket shape rather than
the number the scan is measured on.

Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV
Background
The Duplicates page needs to say why two names count as the same and
how sure it is. The contract shipped the group shape with a scorer that
only saw names equal after lowercasing.

Changes
- services/entityNameMatcher.js: normalisation (umlauts, diacritics,
  punctuation, legal forms, plurals), seven scoring tiers with reasons,
  candidate blocking so thousands of names score in well under a second,
  star clustering kept from the contract.
- tests/test-entity-name-matcher.js: the full suite (fixtures in German
  and English, false-positive guards, chaining refusal, blocking equals
  brute force, timing).

Testing
See the agent's suite; the lead re-ran the whole runner after the merge.

Impact
Pure module, no behaviour outside the Duplicates scan.

Upstream Status
Not applicable.
…ates page

Background
The Duplicates feature is complete on this branch: matcher, merge service
with undo, routes and page. The in-app "What's New" modal and the README
should say so.

Changes
- config/changelog.js: four entries in the current v2026.09.01 block
  (page, undo, hidden pairs, local records following a merge). No version
  bump: the block is the upcoming release, as with the other entries in it.
- README.md: a short section under "The Evolution" describing the page.

Testing
- node scripts/run-tests.js --test changelog-releases: passed.
- prettier and eslint on both files: clean.

Impact
Documentation only.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV
Background
The deterministic matcher finds names that look alike. It cannot know
that "Rechnung" and "Invoice" are the same tag in a bilingual archive, or
whether two legal entities of one company should be filed together. The
configured AI provider can judge such pairs on request. This commit fixes
the vocabulary and the seams so the judge and the page can be built in
parallel.

Changes
- config/config.js: DUPLICATES_AI_REVIEW (default yes; no hides the
  button), DUPLICATES_AI_REVIEW_BATCH_SIZE (pairs per model request,
  default 25), DUPLICATES_AI_CANDIDATE_FLOOR (lowest matcher score a pair
  needs to be shown to the model, default 0.6).
- services/entityMatchAiService.js: verdict vocabulary (same, different,
  unsure), group sources (scan, ai-candidate), typedefs, aggregateVerdict,
  isEnabled, and placeholder reviewPairs / reviewScan that answer without
  a model so the chain can be wired end to end.
- schemas.js: AiVerdict, DuplicateAiReviewRequest, DuplicateAiReviewResult,
  and the additive aiVerdict / source fields on groups and members;
  OPENAPI/openapi.json regenerated.
- scripts/run-tests.js: entity-match-ai-service registered in the
  duplicates area, with a contract placeholder test.

Testing
- tests/test-entity-match-ai-service.js: exports, settings, aggregation.
- node scripts/run-tests.js --area duplicates: 6/6.

Impact
No route, page or behaviour changes yet; three new settings with
defaults.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV
Background

The Duplicates page could only merge what a scan had proposed. Two entries
that mean the same thing but score below the threshold — a rename, an
abbreviation, a name the matcher has no rule for — stayed unmergeable, even
when the user knew perfectly well they belonged together. The scan is a
suggestion engine, not the only way in.

Changes

- duplicateMergeService.listEntities(kind): the whole list of one kind, sorted
  by name case-insensitively with the id breaking a tie, so "Amazon" and
  "amazon" arrive next to each other. Network failures are mapped the way
  scan() maps them, so the route answers 502 rather than 500.
- GET /api/duplicates/entities?kind=tags|correspondents (isAuthenticated):
  answers { success: true, data: EntityRecord[] }. Unlike the scan, kind is
  required — there is no "both" list. Swagger block added, EntityRecord added
  to schemas.js, OPENAPI/openapi.json regenerated.
- A "Merge by hand" module on the page: a closed <details> between the scan
  stats and the results, with a kind segment, a target picker, a sources
  picker that collects chips, "Reload list" and "Merge". The list is fetched
  on the first open and cached per kind, so a page that never opens the module
  costs nothing. Filtering is client-side and case-insensitive, prefix matches
  first, twelve rows and a line counting the rest; arrow keys move, Enter
  picks, Escape closes.
- The merge itself is the round-1 code: mergeGroup() was split into runMerge(),
  which both flows call with their own busy/result callbacks. Same confirm
  dialog, same request, same success and problem alerts, same log and undo. A
  merge started by hand is recorded and undoable exactly like a scanned one —
  nothing in the service can tell them apart.
- Warnings for the manual flow are computed on the client from the chosen
  records and use the round-1 texts: inbox-tag, no-permission, has-matching-
  rule, owner-differs, large-group. configured-tag is left out; only the server
  knows which tag names the settings refer to. An entry the API token may not
  change disables the merge rather than letting it fail halfway.
- Page CSS for the module and the dropdown. The dropdown has to leave the
  module: .zr-module clips its content and paints as its own stacking context,
  so .dup-manual opts out of the clipping and lifts itself above the cards
  below. On a phone the list stops short of the fixed tab bar, and a list with
  no matches lets the pointer through so one click reaches the chips under it.

Testing

- node scripts/run-tests.js --all -> 89 passed, 7 skipped offline, 0 failed
  (unchanged from before: 96 registered).
- tests/test-duplicates-endpoints.js: 9 -> 12 cases. New: the list sorted
  case-insensitively, kind required and validated (missing, empty, "all",
  unknown), 502 on an unreachable instance, and the route added to the
  authentication case.
- tests/test-duplicates-ui.js: 14 -> 17 cases. New: the module's ids, that it
  is a closed <details>, and that it sits between the scan stats and the
  results. The escaping scanner and the warning-vocabulary check cover the new
  code unchanged.
- eslint, prettier and stylelint clean on every touched file; the regenerated
  OpenAPI spec matches the JSDoc.
- Reviewed in Chromium against a throwaway mock (40 tags, 25 correspondents
  with umlauts, legal forms, a locked entry and an inbox tag): 24 screenshots
  at 1280x900 and 390x844, light and dark, 0px horizontal overflow everywhere.
  Two browser probes check what a screenshot cannot: the picker's keyboard,
  chip removal, the permission lock, the cache and the reload; and that the
  scanned-group flow behaves exactly as it did before the split.

Impact

Additive. The scan, the group cards, the log, the undo and the hidden pairs
are untouched; the only change to existing behaviour is that mergeGroup() now
delegates to runMerge(), which produces the same markup and the same requests.
Nothing runs on its own, nothing is deleted that still has documents, and the
new endpoint is read-only.

Upstream Status

Not applicable — the Duplicates page does not exist upstream.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV
Background
The scan proposes groups, but the user also wants to merge tags or
correspondents they pick themselves, with the same safety, log and undo.

Changes
- routes/setup.js, services/duplicateMergeService.js, schemas.js,
  OPENAPI/openapi.json: GET /api/duplicates/entities lists every tag or
  correspondent for the pickers.
- views/duplicates.ejs, public/js/duplicates.js,
  public/css/pages/duplicates.css: the "Merge by hand" module with a
  target picker, a sources chip field, client-side warnings, and the
  round-1 merge flow shared between both entry points.
- tests/test-duplicates-endpoints.js, tests/test-duplicates-ui.js: the
  endpoint and the module.

Testing
See the agent's report; the lead re-ran the whole runner and the browser
smoke test after the merge.

Impact
One new endpoint and one new module on the Duplicates page.

Upstream Status
Not applicable.
Background
Round 2 added the "Merge by hand" module to the Duplicates page.

Changes
- config/changelog.js: one entry in the current v2026.09.01 block.

Testing
- node scripts/run-tests.js --test changelog-releases: passed.

Impact
Documentation only.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV
The AI review needs two things the matcher already did internally: the pairs
that scored but stayed below the threshold, and the second half of a scan
that turns edges into groups.

findCandidatePairs(entities, { kind, floor, threshold, dismissedPairs, limit })
returns every pair in [floor, threshold), sorted by score and then by key and
cut to 400 by default. It shares the blocking and the memoised normalisation
of findDuplicateGroups, so it costs a scan, not a pairwise run.

buildGroupsFromEdges(kind, entities, edges, { configuredTagNames }) is the
star clustering, the target rule, the member order, the confidence, the
reasons, the id and the warnings — exactly what findDuplicateGroups produces,
only with the edges coming from outside. findDuplicateGroups now calls it
instead of keeping a second copy; nothing about its behaviour changed, which
the 48 existing cases still prove.

Tests: seven new cases. findCandidatePairs is compared against a brute-force
pairwise run over 300 generated names, for both kinds and all three
sensitivity presets; buildGroupsFromEdges is compared against
findDuplicateGroups on the same edges, likewise for both kinds and all three
presets.

Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV
…ateText

generateText(prompt) was written for one caller with one job, so everything
about the call was fixed: no system message, the configured generation
temperature, and a completion cap that was either absent (OpenAI), hardcoded
to RESPONSE_TOKENS (Azure, Ollama) or clamped to it (custom). A caller that
needs a short, deterministic answer in a fixed format had nowhere to say so.

All four provider services now take an optional second argument,
{ systemPrompt, temperature, maxTokens }, and each one spells it in its own
API: a system message for the OpenAI-compatible three, the `system` field of
the generate request for Ollama; max_tokens there, num_predict here — where
it also sizes num_ctx, so the context reservation and the limit stay the same
number. The custom service keeps its clamp against the context window and
only replaces the number it clamps.

A call without the second argument sends exactly what it sent before, which
is pinned by a test per provider.

The checks that read the options live in services/aiGenerateOptions.js rather
than four times over, because two of them are easy to get wrong: a
temperature of 0 is a value and not a missing one, and Number(null) is 0
rather than NaN.

Providers that report token usage now leave it on themselves as
`lastGenerateTextUsage` after a call. The return value of generateText stays
a plain string, so no existing caller notices.

Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV
…airs

Background

The Duplicates page finds groups with a deterministic matcher: seven scoring
tiers, every score explainable on the page. That is what makes it safe, and
it is also its limit. It cannot know that "TK" and "Techniker Krankenkasse"
are one correspondent, and it cannot know that "Deutsche Bank" and "Deutsche
Bahn" are not — it can only measure that the names look alike. An AI provider
is already configured for document analysis; asked the right question, it can
answer exactly that.

So this is stage one of using it: a judge of candidates, never the matcher
and never the one who merges. It sees pairs the matcher produced, answers
same / different / unsure with one short reason per pair, and the page shows
that next to the deterministic result. Nothing runs on its own, nothing is
merged without the user, and the deterministic scan stays untouched when the
review is off.

Changes

- services/entityMatchAiService.js: the placeholder bodies are gone.
  - reviewPairs(pairs, { kind }) asks the configured provider in batches of
    DUPLICATES_AI_REVIEW_BATCH_SIZE pairs (25) at temperature 0 with a
    completion cap of 60 tokens per pair plus 100, and returns one verdict
    per pair key — always, whatever came back. The system prompt states the
    job, the rules (case, umlaut spellings, legal forms, singular/plural,
    abbreviations, German and English names for one thing, typos; two legal
    entities of one company only count as one when a person would file them
    under one name; different companies or topics are different) and the
    output contract: a JSON array of { id, verdict, reason }, nothing else.
    The answer is read defensively: one code fence is stripped, the text from
    the first bracket to the last is parsed, an id that was not in the batch
    is dropped, an unknown verdict becomes "unsure", a reason is cut at 200
    characters, and a pair nobody answered becomes "unsure" with a reason
    that says so. A batch that fails costs only its own pairs, is counted in
    usage.failedRequests, and the batches after it still run. Only a provider
    without a client refuses the whole review (status 409).
  - reviewScan(options) runs the ordinary scan, asks the matcher for the band
    between DUPLICATES_AI_CANDIDATE_FLOOR (0.6) and the scan's threshold,
    drops what already sits inside one group and what the user dismissed,
    optionally fetches a few document titles per entity as context (four
    requests in flight, failures simply mean no context), and has the model
    judge the group members against their target and the candidates. Every
    member carries its aiVerdict, every group the aggregate; a candidate the
    model called "same" becomes a group with source "ai-candidate", built by
    the matcher from the matcher's own score and reason. Candidates called
    "different" or "unsure" are not shown.
- services/paperlessService.js: getRecentDocumentTitlesByEntity(kind, id,
  limit) — one request, newest first, titles only. Unlike its neighbours it
  never throws: a review of a few hundred pairs must not fail because one of
  a thousand context reads did.
- tests/helpers/mount-router.js: an inert stub for it, like the other entity
  readers.

Testing

node scripts/run-tests.js --all -> 90 passed, 7 skipped offline, 0 failed
(97 registered, unchanged).

tests/test-entity-match-ai-service.js replaces the contract placeholder with
21 cases, written from the angle of a model that does not do as it is told:
it fences its JSON, talks around it, invents an id, makes up a verdict,
forgets a pair, answers nothing, throws mid-run. The provider is a stand-in
that records every call; Paperless-ngx is the real store from the test
helpers and the local side is the real database on a temporary file, so
reviewScan runs the path it runs in production — including a candidate the
model confirms, one it rejects and one that was dismissed and is therefore
never sent. Two further cases pin what each of the four provider services
sends with and without the new options.

A demo run against the same stand-in printed the prompts and the result; the
judged pair of a batch reads:

  {"id":"correspondents:1-2","a":{"name":"Amazon","documents":1,
   "titles":["Amazon order 2024-11"]},"b":{"name":"amazon","documents":1,
   "titles":["amazon refund"]}}

Impact

Off by default in the sense that matters: nothing happens without the user
asking. DUPLICATES_AI_REVIEW=no hides the review, and the deterministic scan
is unchanged either way — the review adds fields, it never removes or
reorders what the scan returned. Cost is bounded by the batch size and the
candidate limit: one request per 25 pairs, at most 400 candidates per kind
plus the members of the groups the scan already found.

What only a real instance can show is whether the prompt survives the models
people actually run locally: a small quantised model that answers with prose
instead of JSON turns every batch into "unsure" — correct, but useless.

Upstream Status

Not applicable. The Duplicates page does not exist upstream.

Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV
…sults

Background
The matcher relates names by their spelling. The configured AI provider
can judge what spelling cannot: abbreviations, two languages for one
thing, and whether two legal entities belong under one name.

Changes
- services/entityMatchAiService.js: reviewPairs (batches, JSON-only
  prompt, strict parsing, every pair gets a verdict) and reviewScan (scan
  plus the wider candidate band, titles as context, verdicts attached,
  candidates the model confirms become ai-candidate groups).
- services/entityNameMatcher.js: findCandidatePairs and
  buildGroupsFromEdges, sharing the blocking with findDuplicateGroups.
- services/paperlessService.js: recent document titles per entity.
- Provider services: generateText accepts systemPrompt, temperature and
  maxTokens.
- tests/test-entity-match-ai-service.js, tests/test-entity-name-matcher.js.

Testing
See the agent's suites; the lead re-ran the whole runner and a browser
smoke test with a fake provider after the merge.

Impact
No behaviour change without the "Ask the AI" button.

Upstream Status
Not applicable.
Background
The judge counts model requests that answered nothing usable; the page
warns about them. The contract lacked the field.

Changes
- schemas.js, OPENAPI/openapi.json: failedRequests on
  DuplicateAiReviewResult.aiReview.

Testing
- node scripts/regen-openapi.js: no drift after the commit.

Impact
Documentation of an existing field.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV
Background
The Duplicates page decides with string similarity alone. The maintainer
asked whether a model could help with the matching. Stage one is a second
opinion, not a second matcher: after a scan the user can ask the configured AI
provider what it makes of the pairs, and the answer is shown next to the
deterministic result. Nothing merges by itself; a verdict is information.

Changes
- routes/setup.js: POST /api/duplicates/ai-review (isAuthenticated), body
  DuplicateAiReviewRequest — kind (default all), threshold validated like
  the scan route, includeDismissed, withTitles (default true). It calls
  entityMatchAiService.reviewScan() and answers
  { success: true, data: DuplicateAiReviewResult }; refusals of the service
  keep their status through respondDuplicatesError (409 when the review is
  switched off, 502 for an unreachable instance), validation is 400.
  The page route now also passes aiReviewEnabled.
- OPENAPI/openapi.json regenerated.
- views/duplicates.ejs: rendered only when the route offers the review —
  the "Ask the AI" button (#dupAiReviewBtn), the "Use document titles as
  context" checkbox (#dupAiTitles, checked), the hint #dupAiHint that the
  band below the threshold is widest at the strict preset, the notice line
  #dupAiNotice above the results, and two stat tiles (#dupStatAiJudgedTile,
  #dupStatAiRequestsTile) that stay hidden until a review has answered.
- public/js/duplicates.js: the review flow. The button waits for a scan and
  for anything running; while it waits the cards stay and an info line says
  how many pairs are being asked about. The answer renders through the
  existing group renderer plus a verdict chip per group, a verdict line per
  member, a muted table for a group the model called apart (buttons stay
  usable), the ai-candidate groups after a divider, and the two tiles
  (judged, near-misses, requests, tokens, model name as title). A positive
  failedRequests raises a warning above the results; a 409 reads "AI review
  is switched off (DUPLICATES_AI_REVIEW)". A new scan clears every verdict.
  Every sentence from the model is escaped and cut at 200 characters.
- public/js/duplicates.js: the manual flow gets its own inbox-tag wording.
  In a scanned group the inbox tag is the target and stays; by hand it can
  be a source, and a source is deleted — the old sentence promised the
  opposite.
- public/css/pages/duplicates.css: dup- classes for the controls row, the
  hint, the notice, the three verdict tones, the muted state, the member
  verdict line and the candidate divider.

Testing
- node scripts/run-tests.js --all: 90 passed, 7 skipped offline, 0 failed
  (unchanged from the start commit).
- duplicates-endpoints 12 -> 16 cases: authentication, kind and threshold
  validation without reaching the service, a 409 from the service, and the
  reviewed result with the options the route handed over (including the
  defaults of an empty body).
- duplicates-ui 17 -> 19 cases: the review is rendered only when the route
  offers it (button, checkbox, hint, notice, both tiles hidden), the page
  speaks all three verdicts and the ai-candidate source, and the manual
  flow keeps its own inbox-tag sentence.
- eslint, prettier and stylelint clean on every touched file; regen-openapi
  leaves no diff.
- Reviewed in a browser against a throwaway mock (1280x900 and 390x844,
  light and dark): controls, the asking state, the reviewed result with all
  four verdict shapes and two candidates, the failed-request warning, the
  409 wording and the page of an instance without the review. Horizontal
  overflow 0px everywhere.

Impact
Additive. An instance without DUPLICATES_AI_REVIEW or without a provider
renders the page exactly as before. The review is read-only, runs on
request, and merging and dismissing work unchanged on reviewed groups.

Upstream Status
Not upstream; the Duplicates page is a fork feature.
Background
The user asks the configured AI provider to judge the groups of a scan
and the near-misses below the sensitivity; the page shows the verdicts
beside the deterministic result. Nothing merges by itself.

Changes
- routes/setup.js, OPENAPI/openapi.json: POST /api/duplicates/ai-review;
  the page learns whether the review is switched on.
- views/duplicates.ejs, public/js/duplicates.js,
  public/css/pages/duplicates.css: the button, the titles checkbox, verdict
  chips per group and member, AI-suggested groups under a divider, stats.
- tests/test-duplicates-endpoints.js, tests/test-duplicates-ui.js.

Testing
See the agent's report; the lead re-ran the whole runner and the browser
smoke test after the merge.

Impact
New route and new controls on one page; hidden when DUPLICATES_AI_REVIEW
is no.

Upstream Status
Not applicable.
Background
Round 3 added "Ask the AI" to the Duplicates page.

Changes
- config/changelog.js: one entry in the current v2026.09.01 block naming
  the feature and its three settings.

Testing
- node scripts/run-tests.js --test changelog-releases: passed.

Impact
Documentation only.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV
Background
The judge is being made robust against the completion token limit: it
sizes batches by the token budget and re-asks cut-off batches in smaller
pieces. The result reports both so the page and the logs can show them.

Changes
- schemas.js, OPENAPI/openapi.json: retries and batchSize on
  DuplicateAiReviewResult.aiReview.

Testing
- node scripts/regen-openapi.js: no drift after the commit.

Impact
Documentation of two informational fields.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV
Background
On a real archive every batch of the AI review died with
"ai_response_truncated": the completion cap was 60 tokens per pair plus 100,
the batch was always 25 pairs regardless of the context window, and the custom
provider additionally clamps the cap to TOKEN_LIMIT - prompt - 64. Every pair
therefore came back "unsure" with the provider's error as its reason, and
nothing in the log said why.

Changes
- TOKENS_PER_PAIR 60 -> 120, TOKENS_OVERHEAD 100 -> 200: a verdict object with
  a long id and a twelve-word reason is 60 to 90 tokens once a model adds
  whitespace.
- Batch sizing by budget before the first request: _planBatchSize() measures
  the prompt of a batch with calculateTokens() and halves the batch (down to
  one pair) until prompt + completion cap + TOKENS_CONTEXT_MARGIN (256) fits
  into TOKEN_LIMIT. batchSize() stays the upper bound. The margin is larger
  than the custom provider's own 64-token reserve, so its clamp no longer bites.
- Retry by splitting: a request that raises ai_response_truncated (OpenAI,
  Azure, custom) is split into two halves and asked again, recursively, down to
  single pairs. A single pair that still does not fit gets "unsure" with the
  reason "the model's answer exceeded the token limit even for one pair".
  Ollama's generateText() does not raise anything - it returns the half-written
  array - so the same handling is reached through the parse failure.
- Salvage before splitting: salvageVerdictObjects() walks a cut-off answer and
  keeps every complete {...} carrying id and verdict, so only the pairs still
  missing are asked again.
- Truncation retries count in usage.requests and in the new usage.retries; they
  are not failedRequests. Every other failure keeps the previous behaviour: the
  batch's pairs are unsure with the error message, failedRequests += 1, the
  next batch runs.
- reviewPairs() reports usage.retries and usage.batchSize; reviewScan() reports
  aiReview.retries and aiReview.batchSize (the smallest size a kind had to use).
  Both are in the JSDoc typedefs; schemas.js still has to follow.
- Logging with the fixed prefix [AI-REVIEW] at info level: what a kind was
  asked to judge, the batch size and prompt estimate the plan settled on, one
  line per request (number, pairs, prompt tokens, cap, duration, completion
  tokens, verdict tally, or "splitting"/"salvaged N, re-asking M"), a warning
  per failed request with the first 200 characters of the raw answer, and the
  totals. Tag and correspondent names may appear; document titles never do.

Testing
node scripts/run-tests.js --all -> 90 passed, 7 skipped offline, 0 failed
(unchanged against the branch tip). tests/test-entity-match-ai-service.js grew
five cases: a provider that truncates above two pairs (8 -> 4+4 -> 2+2, every
pair judged, six retries, no failed request), a single pair that still
truncates, a half-written answer whose two complete objects are salvaged while
only the four missing pairs are re-asked, an answer with nothing usable in it
that stays a failed batch, and TOKEN_LIMIT=2000 which shrinks the batch to six
before the first request. Two existing assertions on the exact usage/aiReview
objects were extended by the two new fields. A demo run against the fake
Paperless-ngx store with TOKEN_LIMIT=3000 and a model that refuses more than
six pairs judges all 17 pairs in 9 requests, 6 of them retries, 0 failed.

Impact
No API, no route, no view. A review on a small context window now costs more,
smaller requests instead of failing; a review on a large one is unchanged apart
from the wider completion budget.

Upstream Status
Not applicable - the Duplicates feature does not exist upstream.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV
Background
The merge service worked silently: a scan, a merge or an undo left nothing in
the app log, so an operator watching a merge of a real archive could not tell
what had been moved, what had been deleted and what had been refused. At the
same time every single merge fired dashboardStatsService.refresh(), which reads
the counts back out of Paperless-ngx - merging a scan's worth of groups from
the page therefore rebuilt the dashboard once per group.

Changes
- Logging with the fixed prefix [DUPLICATES] at info level, the way
  [RECONCILIATION] logs: scan start and end (kinds, entities per kind, groups,
  dismissed pairs, duration), merge start (kind, target id and name, source
  ids), one line per source (documents found, moved, whether it was verified
  empty, deleted or the reason it was not, matching rule copied), merge end
  (status, documents moved, log id, duration), undo start, one line per
  restored source (new id, adopted or created, documents restored and skipped)
  and undo end (status, whether the matching rule was reverted), and dismiss.
  Tag and correspondent names are part of those lines; document titles are not,
  they are content.
- _afterWrite() replaces the two copies of "clear the caches, refresh the
  dashboard": the entity caches are still dropped immediately, the dashboard
  rebuild is debounced with a trailing timer of DASHBOARD_REFRESH_DEBOUNCE_MS
  (2000), so a burst of merges costs one rebuild. The timer is unref'd so a
  pending rebuild never holds a test or a shutdown, and it is exposed as
  _dashboardRefreshTimer; dashboardRefreshDebounceMs is overridable for tests.

Testing
node scripts/run-tests.js --all -> 90 passed, 7 skipped offline, 0 failed
(unchanged against the branch tip). tests/test-duplicate-merge-service.js grew
two cases: three merges in a row with a 40 ms debounce drop the caches after
each merge but rebuild the dashboard exactly once after the last one, and a
scan, merge, undo and dismiss write the expected log lines while no document
title appears in any of them.

Impact
No API, no route, no view. The dashboard numbers are up to two seconds older
after a merge than they were before; everything else the page reads is written
before the response.

Upstream Status
Not applicable - the Duplicates feature does not exist upstream.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV
…unce

Background
On the user's archive every review batch hit the completion token limit
and every pair came back unsure, and the logs did not say why. A burst of
merges also refreshed the dashboard once per merge.

Changes
- services/entityMatchAiService.js: batch sizing by token budget, salvage
  of complete objects from a truncated answer, split and retry on
  truncation, retries and batchSize in the result, [AI-REVIEW] log lines.
- services/duplicateMergeService.js: [DUPLICATES] log lines for scan,
  merge, undo and dismiss; one dashboard refresh per burst.
- tests/test-entity-match-ai-service.js, tests/test-duplicate-merge-service.js.

Testing
See the agent's report; the lead re-ran the whole runner and a smoke test
with a truncating fake provider after the merge.

Impact
No request shape changes; two new informational fields in the result.

Upstream Status
Not applicable.
Background
On a grown archive a scan proposes dozens of groups, and every one of them
costs its own confirm dialog. The maintainer asked for a multi-selection: every
group has to be confirmed by hand one at a time, and after each merge the tags
and correspondents are loaded again. The dialog is the bottleneck, and the log
reload after each merge makes every group feel like a page reload.

Changes
- Every group card carries a select check (.dup-select, "Select this group") in
  its head. It is unchecked by default and disabled, with a title that says why,
  while the card is busy, once it is merged, when its chosen target may not be
  changed by the API token, or when no source is ticked.
- A selection bar (#dupSelection) above the results, hidden until a card is
  ticked and sticky under the top bar while the list scrolls: "N groups selected
  · M documents", "Select all", "Select AI: same" (only once a review has judged
  something), "Clear" and "Merge selected".
- One confirm dialog for the whole batch: a line per group ("target ← source,
  source (N documents)"), both totals, the same undo sentence a single merge
  makes, and one copy-rule checkbox (#dupCopyRuleAll) where at least one group
  has a matching rule its target lacks.
- The groups are then merged one after the other through the existing
  POST /api/duplicates/merge — never in parallel, Paperless-ngx gets one bulk
  edit at a time. Each card goes busy and reports exactly what a single merge
  reports; a failure on one group does not stop the others. At the end: one
  toast "Merged N groups, M documents" (plus "K failed"), the summary in the bar
  for a moment, and one reload of the merge log. Nothing else is refetched, no
  rescan, untouched cards stay as they are.
- runMerge() takes an optional `batch` and returns how the merge ended, so the
  batch reuses the one request path instead of forking it; the single-group
  flow is unchanged, dialog and all. No new endpoint, no new request shape.
- .dup-selection, .dup-selection__count, .dup-selection__actions,
  .dup-selection__progress and .dup-select inside the existing @layer pages.

Testing
- node scripts/run-tests.js --all: 90 passed, 7 skipped offline, 0 failed
  (unchanged from the baseline of this branch).
- tests/test-duplicates-ui.js grew from 19 to 25 cases: the bar renders hidden
  with its ids above the results, view and page script agree on those ids, every
  card template carries the select check and every reason a check is disabled,
  the batch dialog asks once and has its own copy-rule id, the batch walks its
  groups one after the other through the one merge endpoint, and the stylesheet
  carries the classes and sticks the bar. The escaping scanner covers the new
  dialog markup like the rest of the file.
- Reviewed in Chromium against a mock with eight groups, two judged by a review
  and one with a target the token may not change: 1280x900 and 390x844, light
  and dark, selection / sticky bar / batch dialog / mid-batch progress /
  finished with one failed group. Horizontal overflow 0px in all twenty shots.
- Request probe: three POSTs to /api/duplicates/merge in order, then exactly one
  GET of the log. The single-group flow still sends one POST, one log reload and
  one toast, and still shows #dupCopyRule rather than #dupCopyRuleAll.

Impact
Page only. No route, service, schema or database change, so an instance that
does not update its page script behaves exactly as before. The confirmation
still names every object that will be deleted, still deletes nothing whose
document count is not verified, and every merge of a batch is its own undoable
log entry.

Upstream Status
Not applicable: the Duplicates page does not exist upstream.
Background
On a real archive the user confirmed one dialog per group. A selection
over the cards and a single confirmation for all of them removes that.

Changes
- views/duplicates.ejs, public/js/duplicates.js,
  public/css/pages/duplicates.css: a check on every group card, a sticky
  selection bar, one confirm dialog for the batch, sequential merges in
  place with one log reload at the end.
- tests/test-duplicates-ui.js.

Testing
See the agent's report; the lead re-ran the whole runner and the browser
smoke test after the merge.

Impact
The single-group flow is unchanged.

Upstream Status
Not applicable.
…ected

Background
The selection bar only appeared after the first tick, so "Select all"
and "Select AI: same" were unreachable until one group had been ticked
by hand.

Changes
- public/js/duplicates.js: the bar shows whenever a selectable card
  exists, reads "No groups selected" with the merge button disabled until
  something is ticked, and hides only when nothing can be selected.

Testing
- node scripts/run-tests.js --test duplicates-ui: 25 passed.

Impact
One visibility rule on the page.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV
admonstrator and others added 23 commits September 18, 2026 21:39
…t fix and the logs

Background
Round 4 answered the first feedback from a real archive: several groups
with one confirmation, a judge that survives the completion token limit,
and log lines that explain what the feature does.

Changes
- config/changelog.js: three entries in the current v2026.09.01 block.

Testing
- node scripts/run-tests.js --test changelog-releases: passed.

Impact
Documentation only.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV
…nks only on request (#329)

* feat(duplicates): contract for a targeted AI review

Background
With many groups at 94 to 96 percent the user wants to say "everything
from 95 percent up: ask the AI, show me its view, then merge". The
review must therefore be able to judge only chosen groups and skip the
band of near-misses.

Changes
- schemas.js, OPENAPI/openapi.json: groupIds, minConfidence and
  includeCandidates on DuplicateAiReviewRequest.

Testing
- node scripts/regen-openapi.js: no drift after the commit.

Impact
Request fields only; the implementation follows.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): targeting counters in the AI review result schema

Background
A targeted review reports which groups it judged and which it left
without a verdict; the page shows that.

Changes
- schemas.js, OPENAPI/openapi.json: targeted, groupsJudged and
  groupsSkipped on DuplicateAiReviewResult.aiReview.

Testing
- node scripts/regen-openapi.js: no drift after the commit.

Impact
Documentation of three informational fields.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): let the AI review be pointed at a few groups

Background

An archive with hundreds of correspondents produces dozens of groups at
94, 95 and 96 per cent, and asking the model about all of them costs a
lot to answer a question about a handful. The page needs to select the
groups it is about to merge, ask about those, and keep rendering the
rest of the scan while it does.

Changes

- entityMatchAiService.reviewScan() takes three options that narrow what
  is asked, never what comes back:
  - groupIds: only these scan groups are judged. Every other group is
    still in `groups`, as the scan produced it, with `aiVerdict: null` on
    the group and on every member and `source: 'scan'`. An id this scan
    does not know is ignored and logged once with the count.
  - minConfidence: only groups scoring at least this much are judged;
    together with groupIds both conditions have to hold.
  - includeCandidates (default true): false leaves the band of
    near-misses out entirely, so `candidates` is 0 — and with no band
    the entity list per kind is not read either, which is the cheap part.
- _pairsForKind() takes the set of group ids to judge. A group left out
  contributes no pairs but its member pairs still count as "inside one
  group", so it cannot reappear as a candidate.
- The result reports the targeting: aiReview.targeted, .groupsJudged and
  .groupsSkipped. The start line of the log names it as
  "judging 1 of 4 group(s) (min confidence 0.95, 3 ids), band skipped",
  the closing line adds the two counters. An untargeted review logs and
  behaves exactly as before.
- POST /api/duplicates/ai-review validates and passes the three fields
  through: groupIds an array of at most 500 non-empty strings,
  minConfidence a number in [0.5, 1], includeCandidates a real boolean
  (the string "false" is a 400). An option the request does not mention
  is left out of the service call, so an untargeted request reaches
  reviewScan() with the same object it did before.
- Swagger description of the route and the 400 reason updated,
  OPENAPI/openapi.json regenerated.

Testing

- node scripts/run-tests.js --all -> 90 passed, 7 skipped offline,
  0 failed (97 registered), unchanged against the baseline.
- entity-match-ai-service: 28 -> 34 cases. Six new ones on a fixture
  whose four groups sit exactly on the matcher tiers (1, 0.98, 0.95,
  0.9) plus one pair in the band: groupIds judges only what it names,
  minConfidence filters, includeCandidates: false skips the band and
  reads no second entity list, groupIds and minConfidence combine while
  unknown ids are ignored, an empty selection costs no request, and the
  log lines. The existing aiReview assertion gained the three new fields.
- duplicates-endpoints: 16 -> 19 cases. The three fields reach the
  stubbed reviewScan unchanged, an untargeted request still carries
  nothing extra, ten malformed targeting bodies are 400, and 500 ids are
  accepted while 501 are not.
- Manual run against the real route with a fake store and a fake
  provider: full review 5 pairs / 1 request, minConfidence 0.95 without
  the band 3 pairs, two selected ids (one unknown) 1 pair, and every
  unjudged group back with null verdicts.
- eslint, prettier and the OpenAPI drift check clean on the touched
  files.

Impact

Additive. A review that says nothing about the three options behaves and
logs as before. The page can ask about the groups it selected before a
batch merge; a dozen groups without the band are one or two model
requests instead of the whole archive. schemas.js still has to gain
targeted, groupsJudged and groupsSkipped on DuplicateAiReviewResult.

Upstream Status

Not applicable: the Duplicates feature is next-only.

* feat(duplicates): sort, select by confidence, and a guided review before merging

Background
----------
On a grown archive a scan answers with dozens of groups that all read 94, 95,
96 percent, and the page offered no way to act on that number: every group had
to be judged by eye, one tick at a time. The three presets were the only
thresholds available, so "everything above 95" was not a question the page
could be asked. And where the AI review existed it judged the whole result
list, which is the most expensive way to ask about the five groups the user
actually cares about.

The rule this follows: the AI is an addition, never a condition. Every flow
below works end to end with the review switched off; with it on, the guided
path is one more button beside the one that was already there.

Changes
-------
Results toolbar (#dupResultsBar), above the selection bar, shown once a scan
has groups:
  - "Sort by" (#dupSortSelect): confidence, documents, target name (locale
    compare), kind then confidence. It moves the DOM nodes instead of
    re-rendering, so a card keeps its target, its source ticks, its selection,
    its verdict and its busy state; the two blocks (scan groups, AI
    candidates) are sorted separately and the divider stays between them.
  - "Select >=" (#dupMinConfidence, #dupSelectMinBtn, #dupMinConfidenceCount):
    ticks every selectable group at or above a whole percent and unticks the
    rest, with a live count of what the click would do.
Custom scan threshold: a fourth sensitivity option "Custom" reveals a number
field (#dupThresholdCustom); the scan and both review paths send that percent
divided by 100. The three presets are unchanged.
Confidence breakdown under "Groups found" (#dupStatBuckets): ">=95 %: A .
90-95 %: B . <90 %: C", counted from the cards after a scan and after a review.
Guided flow (#dupReviewThenMergeBtn, rendered only where the review exists):
asks the model about exactly the ticked groups (groupIds, includeCandidates:
false), puts the verdicts on the cards as a full review does, then shows them
once in a wide dialog - one row per group with target, sources, documents, the
verdict chip and the reason, a live "N of M ticked . K documents" foot line and
the copy-rule check. Ticked rows are merged with the batch machinery; an unsure
or different verdict only comes up unticked and never blocks anything, and what
stays unticked stays selected on the page.
"Merge selected" keeps its place and its weight, first in the bar and without a
model anywhere in its path; its dialog names the guided path in one faint line,
and only where that path exists.
Sort, confidence, sensitivity and the custom threshold are remembered in
localStorage (dup.sort, dup.minConfidence, dup.sensitivity,
dup.thresholdCustom) through two try/catch helpers.

Testing
-------
node scripts/run-tests.js --all -> 90 passed, 7 skipped offline, 0 failed
  (unchanged from the branch baseline).
tests/test-duplicates-ui.js: 25 -> 38 cases. New: the toolbar ids and their
  order, the custom threshold field, the stats breakdown, the guided button
  only with the review, the whole page without the review, the toolbar ids in
  the script, sorting as a DOM move, "Select >=", the wrapped localStorage
  access, the guided request (groupIds / includeCandidates: false) and that
  "Merge selected" never touches the review endpoint, the review dialog markup,
  the tip line, the new CSS classes. Changed: the sensitivity options are read
  from #dupSensitivity alone and now end in "custom"; the undo promise and the
  confirm dialogs are counted one higher each, because the review dialog merges
  and therefore makes the same promise.
Reviewed in a browser against a throwaway mock (twelve groups over 88-100 %, a
  review that honours groupIds): 27 screenshots at 1280x900 and 390x844, light
  and dark, 0 px horizontal overflow everywhere, plus a 31-check behaviour
  probe (guided request, verdict ticks, sorting keeping picks and the divider,
  persistence, a refused review, and the whole page with the review off).

Impact
------
Page only. No route, service, schema or config was touched, so the OpenAPI
spec is unchanged. An instance without the AI review renders and behaves
exactly as before plus the toolbar and the custom threshold. The request the
guided path sends uses fields the contract already carries; a server that
ignores them reviews everything, which the page renders correctly.

Upstream Status
---------------
Not applicable - the Duplicates page does not exist upstream.

Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* docs(duplicates): changelog entries for sorting, select by confidence and the guided review

Background
Round 5 answered the second feedback from a real archive: select by a
number, let the model judge exactly those groups, read its verdicts in
one dialog, merge what stays ticked; sort the groups; a custom threshold.

Changes
- config/changelog.js: two entries in the current v2026.09.01 block.

Testing
- node scripts/run-tests.js --test changelog-releases: passed.

Impact
Documentation only.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): contract for evidence-based verdicts and the AI proposal

Background
A real archive produced "Kontoauszug" / "Kontoumzug": the matcher called
it a spelling distance, the prompt allowed "an obvious typo" as a reason
for same, and the model, seeing names and titles only, agreed. Both are
different things. The judge needs stricter rules and, for pairs linked by
spelling alone, a look at what the documents are about, at a bounded
cost.

Changes
- config/config.js: DUPLICATES_AI_EXCERPTS (default yes),
  DUPLICATES_AI_EXCERPT_CHARS (300), DUPLICATES_AI_EXCERPT_DOCUMENTS (2).
- schemas.js, OPENAPI/openapi.json: AiVerdict gains basis and confidence;
  DuplicateAiReviewRequest gains withExcerpts; aiReview reports excerpts.

Testing
- node scripts/run-tests.js --area duplicates: 6/6; regen without drift.

Impact
Settings and schema only; the implementation follows.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): judge model override and the verdict source in the contract

Background
Decisions for round 6: the matcher's hard tiers settle a pair without the
model, unsure pairs are asked once more with excerpts, and the judge may
run on a stronger model of the same provider.

Changes
- config/config.js: DUPLICATES_AI_MODEL (optional, judge only).
- schemas.js, OPENAPI/openapi.json: AiVerdict.source (model or
  spelling-rule); aiReview.escalated and aiReview.spellingRules.

Testing
- eslint and prettier on the two files; regen without drift.

Impact
Settings and schema only; the implementation follows.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(settings): make every DUPLICATES_ setting editable in its own section

Background
The AI review of the Duplicates page arrived with seven environment
variables and no way to change any of them from the interface. Editing a
container environment and recreating the container is the wrong price for
"try a stronger model for the judge" or "ask about fewer pairs per
request", and the settings page is exactly where those knobs belong.
config/config.js already reads all seven; only the front door was missing.

Changes
- views/settings.ejs: a "Duplicates" section (id="sec-duplicates") inside a
  new duplicates-tab block between the AI sections and OCR, with a nav entry
  in the desktop section nav (icon i-merge) and in the mobile one, in the
  same order as the page. Seven fields, each with a hint that says what the
  value does and what its default is: the AI review switch, the judge model,
  pairs per request, the candidate floor, the excerpt switch, excerpt length
  and documents per entry. Switches go through partials/settings-switch, so
  the hidden yes/no input the POST route reads exists as it does everywhere
  else.
- routes/setup.js: GET /settings passes the seven values (env first, the
  defaults of config/config.js as fallback) in the config object the view
  reads; POST /settings destructures the seven camelCase body keys,
  normalises them and writes them into updatedConfig, so setupService
  .saveConfig persists them with the rest. Numbers are clamped to their
  range; a value that is not a number, or a cleared field, keeps what is
  configured now instead of resetting to the default. The swagger body
  schema documents all seven, and the .env export gained a "Duplicates"
  group between "AI behaviour" and "External API".
- public/js/settings.js: the seven selector to env-key entries, so the
  "Overwritten" and "Managed by ENV" marking covers these fields too.
- OPENAPI/openapi.json regenerated.
- tests/test-settings-duplicates-section.js, registered in the
  observability area.

Testing
- node scripts/run-tests.js --all: 98 registered, 91 passed, 7 skipped
  offline (was 97/90/7). The new test covers the rendered section and its
  nav position, the seven inputs and their values, the POST round trip,
  clamping, the keep-the-previous-value case and the .env export group.
- npx eslint / npx prettier --check --ignore-unknown on every touched file.
- node scripts/regen-openapi.js leaves OPENAPI/openapi.json unchanged.
- Looked at the page in Chromium at 1440x1000 and 390x844 against a
  throwaway server outside the repository; no console errors, the section
  reads like the rest of the page and stacks on the phone.

Impact
Operators can change every DUPLICATES_ value from the settings page. The
existing restart-after-save is what makes them take effect; no new
mechanism. Values injected by the container still win and are shown as
managed, as for every other field. Nothing outside the settings page
changes: no route, service or default behaviour of the Duplicates page
itself is touched.

Upstream Status
Fork-only. The Duplicates page does not exist upstream.

Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): judge spelling-only pairs on evidence, not on distance

Background
A real archive produced "Kontoauszug" next to "Kontoumzug": the matcher
called it a spelling distance, the prompt allowed "an obvious typo" as a
reason for same, and the model, seeing two names and three titles, agreed.
Two different things. The judge needed stricter rules, evidence for the
pairs where spelling is the only link, and a way to say how sure it is and
on what grounds — all without opening a large context window on every pair.

Changes
- entityMatchAiService: the system prompt refuses a small spelling distance
  as a reason of its own ("Kontoauszug" / "Kontoumzug", "Miete" / "Mieter",
  "Bahn" / "Bank"), allows a misspelling only when one spelling is not a
  word, and answers unsure when it cannot tell. The output contract gains
  "basis" (a closed list) and "confidence" (high | low); both are parsed,
  an unknown value becomes null, and every verdict, member verdict and
  aggregate carries them. An aggregate keeps the deciding member's basis
  and takes "low" as soon as one deciding member is low.
- Evidence, graded by what the link is worth: every pair carries matched_by
  and score; every judged entity carries its titles, its matching rule and
  its neighbourhood ("filed_with": the correspondents of a tag's documents,
  the tags of a correspondent's); only the pairs linked by fuzzy, prefix or
  token-order also carry document excerpts. Excerpts are read once per
  entity per review and never for a strong tier. withExcerpts: false or
  DUPLICATES_AI_EXCERPTS=no reads nothing at all.
- A member pair a matcher rule settles (exact-normalized, umlaut-variant,
  legal-form) never reaches the provider: it gets verdict same with
  source: spelling-rule, counts in aiReview.spellingRules and costs no
  request, no read and no token.
- A pair the model calls unsure and that had no excerpts is asked once more
  with them; the second answer replaces the first (aiReview.escalated).
- paperlessService: getRecentDocumentExcerptsByEntity (one read,
  truncate_content, cut to the configured characters at a word boundary)
  and getEntityNeighbourhood (one read, the most frequent neighbour names
  through the existing caches). Both answer [] on any error and never log
  document content.
- The judge may run on its own model (DUPLICATES_AI_MODEL): generateText
  takes an optional model in all four provider services, shared through
  aiGenerateOptions.modelOverride.
- Logs: the per-kind start line names the evidence and the model, the
  request line the pairs with excerpts, the escalation its own line.
- Route POST /api/duplicates/ai-review parses withExcerpts like withTitles;
  swagger description updated and OPENAPI/openapi.json regenerated.

Testing
- node scripts/run-tests.js --all: 97 registered, 90 pass, 7 skip offline.
- tests/test-entity-match-ai-service.js: 35 -> 50 cases (the stricter
  prompt, basis and confidence parsing, excerpts only for spelling-only
  pairs and once per entity, the two switches, the configured cut, the
  Kontoauszug regression, settled pairs, the neighbourhood, escalation, the
  model override, batch sizing with excerpts, and both new client methods).
- tests/test-duplicates-endpoints.js: one case for withExcerpts; the three
  existing option assertions now expect withExcerpts: true.
- Demo run against the fake Paperless-ngx: the Kontoauszug/Kontoumzug pair
  costs 282 prompt tokens with excerpts, a strong pair without excerpts 75.
- eslint, prettier and a regen without drift on every file touched.

Impact
An AI review asks about fewer pairs and knows more about the ones it asks
about. Nothing runs on its own, nothing is merged, and document content
never reaches a log line.

Upstream Status
Not applicable — the Duplicates feature does not exist upstream.

* fix(duplicates): do not escalate an unsure pair whose documents carry no text

* feat(duplicates): one click for the AI's proposal, with the evidence behind it

Background
----------
Everything the page offered so far started from the user: scan, read every
card, tick, merge — and where the AI review existed it was a second question
asked after the first. What was missing is the path the archive's owner
actually wants for a first clean-up: one click that scans, has every group and
every near-miss judged, and then hands over a proposal to thin out rather than
a list to work through.

The rule this follows is the same as in the rounds before: the AI is an
addition, never a condition. Without the review nothing of this renders, and
"Scan Paperless-ngx", "Merge selected", the toolbar, the manual merge and the
guided path are the same as they were.

A verdict also had to say more than "same": with `basis`, `confidence` and a
`source` on the wire, the page can pre-tick exactly what is settled — a pair a
spelling rule decided, or one the model says it is sure about — and leave
everything else to the user. The member tables, finally, measured their own
content per card, so the columns of two cards below each other sat in
different places.

Changes
-------
"AI proposal" (#dupAiProposalBtn, primary, rendered only with aiReviewEnabled)
next to "Ask the AI", usable from the first paint because it scans itself:
  - status in the AI row (#dupAiProposalStatus): "Scanning…", then "Asking the
    AI about N pairs and near-misses…", with the hint line under the row
    (#dupAiProposalHint) saying what the click does;
  - it reuses runScan() (now awaited) with the kind, sensitivity and hidden-pair
    settings on the page, then the one review request with includeCandidates
    and no groupIds. Two requests, and no merge until the dialog is confirmed.
Proposal dialog (.dup-proposal-dialog): one row per group that could be merged,
  sorted same/high, same, unsure, different, unjudged (proposalRank,
  compareProposalEntries — both pure); pre-ticked are only the settled ones
  (isSureSame: verdict "same" with confidence "high", which covers the
  spelling-rule verdicts); legend, "Tick all same" (#dupProposalTickSame),
  "Untick all" (#dupProposalUntickAll), the copy-rule check (#dupCopyRuleAll)
  and a live foot line "N of M ticked · K documents · X objects will be
  deleted". Confirming sets the page selection to the ticked groups and hands
  them to the batch runner of round 4, so the selection bar reports the merge
  as it does for "Merge selected"; cancelling leaves the verdicts on the cards
  and nothing ticked.
Evidence, shared by both dialogs (one row renderer, one table):
  - a "Basis" column as a .zr-badge with a label per contract value;
  - the confidence as a suffix of the verdict chip ("AI: same · high");
  - a pair a spelling rule settled reads "Spelling rule" in the "same" tone
    (.dup-verdict--rule) instead of quoting a model that never saw it;
  - the guided dialog pre-ticks by the same rule, so a "same" the model is
    unsure about now comes up unticked there too.
Cards keep their shape: the verdict chip carries the basis in its title and the
  confidence as its suffix, no new column.
Second checkbox "Use document excerpts for spelling-only pairs"
  (#dupAiExcerpts, checked); withTitles and withExcerpts flow into every review
  request from the one place that builds it. The titles checkbox is relabelled
  "Use document titles and neighbours as context".
"AI-judged pairs" tile: its sub line now also counts "· E excerpts", "· S by
  spelling rule" and "· E escalated" when the review reports them.
Member tables line up across cards: .dup-members is table-layout: fixed with
  the name column taking what is left and truncating, and the matching rule a
  fixed share (.dup-members__name, .dup-members__rule).

Testing
-------
node scripts/run-tests.js --all -> 90 passed, 7 skipped offline, 0 failed
  (unchanged from the branch baseline of 97 registered).
tests/test-duplicates-ui.js: 38 -> 48 cases. New: the proposal ids and labels
  only with the review and the page whole without them; what the flow sends
  (runScan first, includeCandidates: true, no groupIds, both evidence flags,
  no request of its own); the pre-tick rule, evaluated as a function against
  seven verdicts; the row order, evaluated by sorting a shuffled list; a label
  for every basis the AiVerdict schema lists, parsed out of schemas.js; the
  spelling-rule chip; the dialog's parts and that it merges through the batch
  runner; the evidence counters of the stats tile; the fixed member-table
  layout; the new CSS classes. Changed: the titles checkbox label, the undo
  promise and the confirm dialogs counted one higher each (the proposal merges
  and therefore makes the same promise), and the pre-tick assertion of the
  guided row.
Reviewed in a browser against a throwaway mock (eleven scan groups plus three
  the model proposes, verdicts across same/high, same/low, unsure and
  different, some settled by a spelling rule, and a Kontoauszug / Kontoumzug
  pair that only the excerpts decide): 31 screenshots at 1280x900 and 390x844,
  light and dark — the controls, the status line mid-flow, the proposal dialog,
  after "Untick all", mid-merge, after the merge, the guided dialog, the stats
  tile, the aligned member tables and the render without the review. 0 px
  horizontal overflow everywhere; the column offsets of all eleven cards are
  identical.

Impact
------
Page only. No route, service, schema or config was touched, so the OpenAPI
spec is unchanged. An instance without the AI review renders and behaves
exactly as before. The new request field and the new verdict fields are ones
the contract already carries: a server that ignores withExcerpts reviews as it
did, and a verdict without basis, confidence or source renders as it did — it
then simply never comes up pre-ticked, which is the safe side.

Upstream Status
---------------
Not applicable - the Duplicates page does not exist upstream.

Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* chore(duplicates): changelog for the AI proposal round, room for the verdict in the Match column

Background
The sixth round of the Duplicates feature adds the AI-led proposal, the
evidence-based judge and the Duplicates settings section. The member
tables now use a fixed column layout so the columns line up across
cards, which left the Match column too narrow for a verdict such as
"AI: same - high": it wrapped into four lines.

Changes
- config/changelog.js: five entries for the round under the current
  release (AI proposal, evidence-based judge with excerpts and
  DUPLICATES_AI_EXCERPT*, DUPLICATES_AI_MODEL, aligned member tables,
  the Duplicates settings section).
- public/css/pages/duplicates.css: the Match column is 132px wide and
  the member verdict does not wrap, so the percentage and the verdict
  take one line each.

Testing
- npx eslint, prettier --check and stylelint on every file changed
  against nightly: clean.
- node scripts/run-tests.js --all: 91 passed, 7 skipped (server or
  credentials needed), 0 failed.
- node scripts/regen-openapi.js: no drift.
- Browser walkthrough against a fake Paperless-ngx and a fake judge:
  scan, merge, undo, dismiss, merge by hand, batch merge, guided review,
  AI proposal and AI review all pass. The Kontoauszug/Kontoumzug pair is
  judged "different" on its excerpts and does not appear in the
  proposal.

Impact
Visual only for the CSS; the changelog is shown in the What's New
dialog.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): contract for a watchable, stoppable AI review

Background
An AI review of a large archive is many model requests in a row. Today
it is one POST that answers when everything is done: nothing shows
while it runs, nothing can stop it, and the tokens it spends are
invisible until the end. The user wants to see what is happening, how
far it is and what it costs, and to stop it at any time. Decisions for
this round: the review runs as a server-side job the page can watch
and stop; a review nobody watches stops itself; a token budget per
review stops it on its own; a stopped review keeps the verdicts it
reached and opens no dialog; the progress lives in the AI row of the
Duplicates page.

Changes
- services/duplicateReviewJobService.js (new): the one review job at
  a time. start(), current(), get(), stop(id, reason), subscribe() for
  a server-sent stream (a late subscriber first gets the job as it is
  now), touch(), wait(), result(), toJSON(). The judge receives a
  control object (signal, onProgress, stop, tokenBudget); a partial
  result of a stopped review is kept like a complete one. The idle
  watch stops a job nobody has watched for the configured seconds. A
  finished job stays reachable for ten minutes.
- config/config.js: DUPLICATES_AI_TOKEN_BUDGET (200000, 0 = no limit)
  and DUPLICATES_AI_IDLE_STOP_SECONDS (60, 0 = never).
- schemas.js, OPENAPI/openapi.json: AiReviewProgress, AiReviewJob,
  AiReviewJobEvent; aiReview gains stopped, stopReason and
  pairsNotJudged.
- scripts/run-tests.js, tests/test-duplicate-review-job.js: the
  contract test of the job (9 cases) in the duplicates area.

Testing
- node scripts/run-tests.js --all: 99 registered, 92 pass, 7 skip
  offline, 0 fail.
- eslint and prettier on every touched file; regen without drift.

Impact
Nothing uses the job yet; the judge ignores the control object until
the implementation follows. No route or page changes.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): make the token budget and the idle stop editable in settings

Background
The two brakes of a running AI review landed as environment variables only:
DUPLICATES_AI_TOKEN_BUDGET caps what one review may spend across all its
requests, DUPLICATES_AI_IDLE_STOP_SECONDS ends a review no page has been
watching, so a closed tab cannot leave the model running. Both are exactly
the kind of setting somebody wants to try out once and then adjust, which
means editing a compose file and restarting the container for every attempt.
The other seven DUPLICATES_* variables already have a field in the Duplicates
section of the settings page; these two did not.

Changes
- views/settings.ejs: two number fields at the end of #sec-duplicates, in the
  style of the five above them — duplicatesAiTokenBudget (0-10000000, step
  1000) and duplicatesAiIdleStopSeconds (0-3600). Each hint says what the
  value does, what zero means and what the default is.
- routes/setup.js: GET /settings passes DUPLICATES_AI_TOKEN_BUDGET and
  DUPLICATES_AI_IDLE_STOP_SECONDS to the view with the defaults of
  config/config.js as the fallback; POST /settings destructures both body
  keys, clamps them to their ranges and keeps the currently configured value
  for an empty or non-numeric field, the rule the round-6 fields follow. Zero
  is a value for both and survives the clamp, because the ranges start there
  rather than at one. The @swagger body schema documents both, and the
  Duplicates group of ENV_EXPORT_GROUPS lists them after the existing keys.
- public/js/settings.js: two entries in the field mapping, so an
  operator-injected value greys the field out and carries the "Managed by ENV"
  pill like every other setting.
- OPENAPI/openapi.json regenerated.

Testing
- tests/test-settings-duplicates-section.js grew from 7 to 11 cases: the two
  fields render with their configured values, ranges and hints and close the
  section in that order; every field of the section is paired with its
  environment key in settings.js; the POST round trip persists all nine
  values; a budget of 99999999 is capped at 10000000 and an idle stop of -5
  lands on 0; zero survives for both, because it means "no limit" and "never"
  rather than an unset field; a fractional value is rounded; a cleared or
  unparsable field keeps what was stored before; the .env export carries all
  nine keys with the two brakes last.
- node scripts/run-tests.js --all: 99 registered, 92 passed, 7 skipped
  offline, 0 failed — the same numbers as before this change.
- eslint and prettier clean on every file touched; regen-openapi.js leaves no
  drift.
- Looked at the section in Chromium at 1440x1000 and 390x844 against a
  throwaway server outside the repository: both fields render like the seven
  above them, no console errors, and with the two keys in the locked-env set
  both are disabled and carry the "Managed by ENV" pill while a neighbouring
  field stays editable.

Impact
No behaviour change for anybody who never opens the section: the defaults are
unchanged (200000 tokens, 60 seconds) and nothing new runs. Operators who set
either variable in their container environment keep winning — the field is
shown greyed out rather than silently overwritten. A saved value needs a
restart to take effect, as the hints say, because config/config.js reads the
environment once at load.

Upstream Status
Not applicable — the Duplicates page is specific to this fork.

* feat(ai): let every provider take an abort signal for one call

aiGenerateOptions gains abortSignal(options); the four provider
services pass it on where their client expects it — the OpenAI SDK as
the second argument of create(body, { signal }) for OpenAI, Azure and
the custom endpoint, axios as { signal } in the request config for
Ollama. Without a signal every provider sends exactly what it sent
before: no second argument at all, and the unchanged axios config.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): the AI review reports, stops and counts its tokens

Background
"Während die AI befragt wird, könnten Millionen von Tokens im
Hintergrund verbraten werden, ohne dass man es sieht. Man muss es auch
abbrechen können." The judge answered when it was done and said
nothing while it worked, so the page had nothing to show and nothing
to stop. The job of the previous round hands it a control object; this
round makes the judge use it. A bar needs a denominator before the
first request, which the old per-kind loop could not give: it read the
archive, asked, and only then looked at the next kind.

Changes
- services/entityMatchAiService.js: reviewScan(options, control = {})
  runs in two passes. Pass one, for every kind of the review: read the
  entities and the band, build the pairs, settle the spelling-rule
  pairs, gather titles, neighbourhood and excerpts, and size the
  batches. Pass two judges kind after kind. Nothing is asked before
  the whole plan exists.
- Progress: phase scanning before the scan, phase evidence per kind
  and per read, one phase judging with requestsPlanned, pairsTotal and
  estimatedTokens for the whole review, one report per answered
  request (requestsDone, pairsJudged, the running token total,
  failedRequests, retries, kind, and the line naming the next
  request), phase escalating when an unsure pair is asked again, phase
  finishing before the groups are built. A split answer adds its
  halves to requestsPlanned in the report of the request that split,
  so the bar never goes backwards; the escalation adds its own
  requests and pairs the same way. Elapsed time and the estimate stay
  with the job, which derives them.
- Stopping: control.signal is read before every read, every request
  and the second round, and travels to the provider, so a stop lands
  on a request in flight. A request that dies on the signal is a stop,
  not a failure: no failed request, no retry, and no "unsure" — the
  pairs stay without a verdict, so they cannot become a group. A
  stopped review returns what it reached; it never throws.
  aiReview now always carries stopped, stopReason (null; the job fills
  it in) and pairsNotJudged.
- Token budget: one running total for the whole review, folded from
  the provider's usage or, for a provider that reports none, from the
  measured prompt plus the estimated answer, so the counter and the
  budget work for every provider (aiReview.tokens keeps reporting only
  what a provider stood behind). When control.tokenBudget is reached
  the review calls control.stop('token-budget') and behaves as
  stopped.
- Logs: "review stopped (user|token-budget|idle): N of M request(s)
  made, P pair(s) not judged, T token(s)." and "token budget 200000
  reached after N request(s) (T tokens)."; the start, request and
  finish lines are unchanged.
- services/duplicateReviewJobService.js: the control object gains
  stopReason(), the one seam the judge needs to name the reason in its
  own log line.
- reviewPairs(pairs, options) additionally takes plan, systemPrompt
  and tracker from reviewScan; a caller that brings none gets what it
  always got.

Testing
- node scripts/run-tests.js --all: 99 registered, 92 pass, 7 skip
  offline, 0 fail (the baseline of the branch).
- tests/test-entity-match-ai-service.js: 13 new cases (64 total) —
  the plan before the first request for one and for two kinds, the
  split and the escalation raising the plan, a failed request still
  moving the bar, a stop between requests and a stop in flight, the
  token budget, a provider without usage, an already aborted signal, a
  review without a control, the report carrying nothing the job
  derives, and the signal reaching all four providers. The one moved
  expectation is the deep-equal on aiReview, which now names the three
  new fields.
- tests/test-duplicate-review-job.js: one case for stopReason().
- A real run through the job service over a fake archive: a review
  that runs through, the same one stopped after request 2, and the
  same one against a token budget.
- eslint and prettier on every touched file.

Impact
The page can show a bar with a denominator, an estimate and a running
token count from the first request, and a stop costs at most one
request that is already in flight. A review without a control object
behaves exactly as before, so the synchronous route is untouched until
it is moved onto the job.

Upstream Status
Not applicable: the Duplicates page and its AI review do not exist
upstream.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): watch and stop the AI review from the page

Background

A review of a drifted archive is many model requests in a row. Until now
"Ask the AI" was one POST that answered when everything was over: a spinner,
no idea how many requests were still coming, no idea what it cost, and no way
out but reloading the tab — which left the model running. The job service of
the contract commit made the review watchable and stoppable on the server;
this wires the routes and the page onto it.

Changes

routes/setup.js (Duplicates block only)
- parseAiReviewRequest(body) holds the validation both entry points share, so
  the synchronous route and the job route can no longer drift apart.
- POST /api/duplicates/ai-review/jobs starts a review and answers
  202 { job }; while one runs it answers 409 with that running job, so a
  second tab attaches instead of failing.
- GET /api/duplicates/ai-review/jobs/current answers { job } or { job: null }
  and counts as watching the review.
- GET /api/duplicates/ai-review/jobs/:id answers { job, result }, 404 for an
  unknown id, and also counts as watching.
- GET /api/duplicates/ai-review/jobs/:id/events streams AiReviewJobEvents
  (text/event-stream, no-cache, X-Accel-Buffering: no, keep-alive, flush after
  every write), a ": keep-alive" comment every 15 s, and ends after done,
  stopped or failed. An unknown id is a JSON 404 before any stream header.
- POST /api/duplicates/ai-review/jobs/:id/stop answers { job }; stopping a
  finished review is a 200 no-op.
- POST /api/duplicates/ai-review now starts that same job and waits for it: a
  stopped review answers 200 with the verdicts it reached, a failed one keeps
  the judge's status, and a second request while one runs is a 409. It
  subscribes for the duration so the idle stop cannot end a review somebody is
  waiting for.
- @swagger for every new route; OPENAPI/openapi.json regenerated.

views/duplicates.ejs, public/js/duplicates.js, public/css/pages/duplicates.css
- A progress panel in the AI row (#dupAiProgress): bar (#dupAiProgressFill,
  indeterminate while the plan is unknown), message, counters
  ("Request 3 of 8 · 40 of 96 pairs · 12.4k of 200k tokens"), time
  ("about 40 s left · 1:24 elapsed") and a Stop button (#dupAiStopBtn). After
  the end it keeps one outcome line and hides on the next scan or review.
- askForVerdicts() starts the job, follows it through EventSource and falls
  back to polling the job every 2 s when the stream breaks. It resolves
  { aiReview, stopped }; all three AI paths honour `stopped` — the notice is
  shown and neither the guided dialog nor the proposal opens.
- On load the page asks for the current job and re-attaches to one that is
  still running; a finished one is left alone.
- Pure helpers formatTokens, formatEta, formatElapsed, progressPercent and
  stopNotice word the numbers; the UI test evaluates them directly.

Testing

- node scripts/run-tests.js --all: 99 registered, 92 pass, 7 skip offline
  (unchanged); duplicates-endpoints 20 -> 30 cases, duplicates-ui 48 -> 57.
- eslint, prettier, stylelint clean on every touched file; regen-openapi
  leaves no diff.
- Reviewed in a browser against a throwaway server with a judge that reports
  eight requests: mid-run, stopping, stopped and done, desktop and phone,
  light and dark, no console errors. A page loaded while a review runs
  re-attached and rendered its result; with the event stream blocked the same
  review came home through eight polls.

Impact

The Duplicates page shows what a review is doing and costing and can end it;
the verdicts already reached are kept. The synchronous route keeps its request
and response, so an API client sees no change beyond the new 409 while a
review runs.

Upstream Status

Not applicable — the Duplicates feature does not exist upstream.

* fix(duplicates): a late Stop answer no longer paints over the outcome; changelog for the review job

Background
In the browser smoke test of the round, a stop pressed after the first
answered request ended the job before the stop request itself answered.
The page then rendered that answer, a snapshot from the stopping moment,
over the outcome line and restarted the elapsed clock, so the panel read
"Stopping after the current request…" next to a finished review.

Changes
- public/js/duplicates.js: stopReview() renders the stop answer only
  while the same job is still followed and still live.
- tests/test-duplicates-ui.js: one case that pins the guard (57 -> 58).
- config/changelog.js: three entries for the round under the current
  release (the review as a job with progress and Stop, the token budget
  and the idle stop as settings, the plan before the first request).

Testing
- node scripts/run-tests.js --test duplicates-ui: 58 passed.
- Browser smoke against a fake Paperless-ngx and a slowed-down fake
  provider: Stop during request 2 leaves "Stopped after 1 of 5 requests
  · 1 of 5 pairs judged · 1.1k tokens" on the panel, the verdicts
  reached stay on the cards, no dialog opens; the proposal path stops
  the same way; a token budget of 2500 stops the review after 3
  requests with the budget named in the notice and the log; a page
  reloaded during a review re-attaches and renders the result; the
  round-6 walkthrough (scan, merge, undo, dismiss, merge by hand, batch,
  guided review, proposal, plain review) passes unchanged.
- eslint and prettier on the touched files.

Impact
Visual only; the review itself was stopped correctly before the fix.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): contract for a judge that measures the model, streams its answers and thinks only on request

Background
On a real archive with a hosted Qwen model the first review request
asked about 25 pairs, ran for 103 seconds and died at its own answer
cap: the model spent the whole budget thinking before the first
verdict, the cut-off text was thrown away, and the page showed nothing
but a ticking clock for two minutes. Three scans of 13 seconds each
came before that. Decisions for this round: the judge measures the
model on a small first request and sizes every later request to a
target duration; the providers stream the answer so the page moves
inside a request and a cut-off answer keeps its verdicts; thinking is
off for the judge unless the operator switches it on; the review
reuses a fresh scan instead of scanning again.

Changes
- config/config.js: DUPLICATES_AI_THINKING (no) and
  DUPLICATES_AI_REQUEST_SECONDS (30).
- schemas.js, OPENAPI/openapi.json: AiReviewProgress gains
  requestPairs, requestAnswers, requestTokens, thinking, batchSize and
  calibrated; the phase list gains warming-up.
- services/duplicateReviewJobService.js: the new progress fields, the
  warming-up phase, and a time estimate from the share of pairs done
  (answers streamed in count), because the batch size may change after
  the warm-up.
- services/aiGenerateOptions.js: reasoningEnabled(options) and
  progressHandler(options), the two switches the judge will send and
  the providers will read, with the GenerateTextProgress shape and the
  partialText rule for cut-off answers.
- scripts/run-tests.js, tests/test-ai-provider-streaming.js: a
  registered placeholder for the provider streaming test.

Testing
- node scripts/run-tests.js --all: 100 registered, 93 pass, 7 skip
  offline, 0 fail.
- eslint and prettier on every touched file; regen without drift.

Impact
Nothing reads the new switches yet; the implementation follows.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* test(helpers): fake OpenAI-compatible and Ollama servers on ephemeral ports

* feat(providers): stream the answer, report progress, keep the cut-off text

Background

A hosted model behind the custom provider spent 103 seconds and the whole
3200-token completion cap on one AI-review request, then threw "the answer hit
a token limit" and dropped every character it had produced. Nothing was visible
while it ran, nothing survived the throw, and the batch was split and paid for
again from the beginning. Two causes: the four provider services always sent a
non-streaming request, so there was nothing to watch; and
assertCompletionNotTruncated() threw before anyone read the content, so the
prefix was thrown away. On top of that the model thinks before it answers, and
on a server that separates thinking from answering the reasoning arrives as
reasoning_content deltas that no provider knew about.

Changes

- services/aiGenerateOptions.js: the shared streaming machinery.
  stripReasoningText() removes <think> blocks, including one a cut-off left
  open. createProgressCollector() assembles a streamed answer, splits reasoning
  from answer incrementally (a marker may be cut across two chunks), counts the
  completion tokens from a usage chunk or estimates them over everything
  produced, reasoning included, and reports at most once per 100 ms plus one
  final report that says done. consumeChatCompletionStream() and
  runChatCompletionStream() are the OpenAI-compatible half: read the stream,
  finish before any throw, and turn a cut-off or a stop into an error that
  carries what arrived. isAbortError()/abortedGenerationError() give a stopped
  request one name across the SDK, axios and fetch.
- services/serviceUtils.js: estimateTokenCount() (the same character-based
  estimate, on a length) and an optional fourth argument on
  assertCompletionNotTruncated() that puts partialText on the error.
- services/openaiService.js, services/customService.js,
  services/azureService.js: generateText() streams when the caller hands in
  onProgress, with stream_options: { include_usage: true } on OpenAI and the
  custom provider and on Azure only from API version 2024-06-01, where the API
  takes it. Without a handler the body is exactly what it was. Both paths strip
  reasoning from the answer and attach the prefix to a truncation error; an
  abort throws an AbortError with partialText.
- services/customService.js: reasoning: false adds
  chat_template_kwargs: { enable_thinking: false } and, for a model name
  matching /qwen/i, that family's soft switch on its own line at the end of the
  user message; reasoning: true sends enable_thinking: true and no soft switch;
  without the option nothing new is sent.
- services/ollamaService.js: generateText() reads NDJSON from an axios
  responseType: 'stream' response, keeps the tail of a socket read until its
  newline arrives, treats the thinking field as thinking, and stops reading the
  moment the signal aborts. reasoning: false/true sends think and overrules
  OLLAMA_THINK; without the option OLLAMA_THINK still decides. The cut-off
  check the analysis path has always run now runs here too, with partialText,
  and a failure no longer erases a token count that was already measured.
- tests/helpers/fake-openai.js, tests/helpers/fake-ollama.js: real HTTP servers
  on ephemeral ports, scripted per request (content chunks, reasoning chunks,
  finish reason, usage chunk or none, per-chunk delay, non-streaming answers
  from the same script), recording every request body and whether the client
  hung up early.
- tests/test-ai-provider-streaming.js replaces its placeholder with 22 cases.

Testing

- node tests/test-ai-provider-streaming.js: 22 passed, 0 failed; run five
  times, no flake.
- node scripts/run-tests.js --all: 93 passed, 7 skipped offline, 0 failed —
  the same numbers as before this change.
- npx eslint and npx prettier --check on every touched file: clean.
- A throwaway process reproduced the reported failure against the fake: the
  progress reports show thinking first with no text, then the answer growing,
  then one done report with the exact token count from the usage chunk, and the
  throw carries the 131 characters of JSON that had arrived.

Impact

No caller behaves differently unless it asks: without onProgress the request
body is byte for byte what it was, and the round-7 provider cases assert that.
What does change for every caller of generateText(): a <think> block no longer
reaches the returned string, a truncation error now carries partialText, an
abort now throws under the name AbortError, and Ollama's generateText() now
raises the same truncation error the analysis path raises instead of returning
a half-written answer. The document analysis path is untouched.

Upstream Status

Not upstream. Streaming, progress reporting, the partial text of a cut-off
answer and the thinking switch do not exist in clusterzx/paperless-ai.

* feat(duplicates): the progress panel moves inside a request and names the measured batch size

Background

A review of a large archive is a handful of long model requests, and the
panel only moved between them. One request took 103 seconds while the page
showed "request 1 of 4 - 0 of 82 pairs" and a ticking clock, so for minutes
at a time the only honest reading of the page was "nothing is happening".
The judge now measures the model on a small first request, sizes every later
one to a configured number of seconds, and streams the answers as they
arrive, which gives the page three things it never had: answers inside a
request, a warm-up phase, and a model that says when it is thinking.

Changes

Page (views/duplicates.ejs, public/js/duplicates.js,
public/css/pages/duplicates.css):

- progressPercent() counts pairs whenever the plan knows them, the answers
  of the running request included, and falls back to requests only while no
  pair count exists. The bar therefore moves during a request instead of
  jumping once per request.
- progressCountsText() gained the "7 of 10 answers" part, printed only while
  a request is in flight and capped at the size of that request.
- progressTimeText() says "measuring the model" in the warm-up and "the
  model is thinking" while the model writes reasoning, instead of a clock
  that cannot move; an estimate the job already made is still shown next to
  either.
- New #dupAiProgressNote line under the counts, written by the new
  progressNoteText(): "4 pairs per request while the model is measured"
  before the measurement, "9 pairs per request, sized from the model's
  answers" after it, empty while no size is known. A zero-width space holds
  its row open for as long as a review runs (.dup-progress--live), so the
  stats tiles below do not jump the moment it fills.
- .dup-progress__fill--thinking pulses while the model reasons, slower than
  the indeterminate band, and is switched off under prefers-reduced-motion.
- The outcome line and the "Model requests" tile both name the batch size the
  review settled on.
- New htmlReviewFailure(): all three AI paths report a failed review with the
  judge's own message plus one link, "Open the Duplicates settings", to
  /settings#duplicates-tab.

Settings (views/settings.ejs, public/js/settings.js, routes/setup.js):

- Two fields close the Duplicates section: the switch "Let the judge think"
  (DUPLICATES_AI_THINKING, default off) and the number "Seconds per model
  request" (DUPLICATES_AI_REQUEST_SECONDS, 5-300, default 30). GET, POST with
  the usual clamping and keep-the-previous-value behaviour, the @swagger
  request body, ENV_EXPORT_GROUPS and the two "Managed by ENV" selectors.

Route:

- GET /api/duplicates/scan passes fresh: true; a scan somebody pressed a
  button for must not be answered from a cache.

OPENAPI/openapi.json regenerated.

Testing

- node scripts/run-tests.js --all: 93 passed, 7 skipped offline, 0 failed
  (unchanged from the baseline of this round).
- duplicates-ui 58 -> 66 cases: the bar with streamed answers and without a
  pair count, the counts line with and without a running request, the three
  wordings of the time line, the note line, the outcome line with a batch
  size, the panel ids and the thinking class, the settings link of the failed
  notice, and the stylesheet's pulse with its reduced-motion rule.
- settings-duplicates-section 11 -> 15 cases: both fields render with their
  values and hints, the POST round trip, clamping (2 -> 5, 999 -> 300), the
  cleared field keeping the previous value, the switch spellings, the export
  group order and the two selectors.
- duplicates-endpoints 30 -> 31 cases: the scan route hands fresh: true to
  the service.
- eslint, prettier and stylelint clean on every touched file; regen-openapi
  leaves no drift.
- Looked at in Chromium against a throwaway server on port 3403 that walks a
  scripted review through the warm-up, a thinking stretch and a request whose
  answers climb 0 -> 10: desktop and phone, light and dark. The stats tiles
  sit at the same offset before and after the note line fills.

Impact

The panel reports inside a request rather than between requests, and names
both the warm-up and the measured batch size, so a review that takes minutes
per request looks like work rather than a hang. A failed review points at the
setting that would have prevented it. Nothing scans, judges or merges on its
own; the two new settings are read at startup like the rest of the section.

Upstream Status

Not applicable - the Duplicates page does not exist upstream.

* feat(duplicates): measure the model, size every request to it, and reuse a fresh scan

Background

Asking the AI about a scan of the user's archive did not work on their
instance. The judge sent 25 pairs with a completion cap of 3200, the hosted
model thought before it answered and spent all 3200 tokens on the thinking,
and 102 seconds later nothing had been judged. The answer was then split into
13 + 12, which buys nothing: the thinking does not get cheaper with fewer
pairs. Meanwhile the page showed "request 1 of 4 · estimating…" for two
minutes, because a request only reports when it is over. The user pressed
Stop.

The same run also scanned the archive three times inside 50 seconds — the
page's scan, the AI proposal's and the review job's — 1359 tags and 13
seconds each, with nothing changing in between.

Changes

services/entityMatchAiService.js

- Thinking off by default. Every judge request carries
  `reasoning: config.duplicatesAiThinking === true`, so a reasoning model
  answers instead of deliberating unless the operator asked for it. Nothing
  else about the prompt changed.
- A warm-up instead of a guess. The first request of a review whose model has
  not been measured asks about at most WARMUP_PAIRS (4) pairs with a
  deliberately generous cap (RESPONSE_TOKENS, the flat estimate or
  WARMUP_MIN_CAP, whichever is largest, bounded by the context window). It is
  announced under the phase `warming-up` with the message "Measuring the model
  with a small first request…", `calibrated: false` and the size it will use;
  the plan reported with it is provisional and the log says so.
- Sizing from the measurement. Every answered request yields tokens per pair
  (thinking included) and tokens per second, each smoothed by half against the
  measurement before it. From them:
  `batchSize = clamp(floor(requestSeconds × tokensPerSecond ÷ tokensPerPair), 1, batchSize())`
  and `cap = ceil(tokensPerPair × batchSize × 1.5) + TOKENS_OVERHEAD`, both
  bounded by the context window as the batch planning bounds them.
  `requestSeconds` is DUPLICATES_AI_REQUEST_SECONDS, at least 5, 30 by
  default. A batch is now taken off the front of a queue rather than chunked
  up front, because its size changes while the review runs.
- The plan settles after the warm-up. `requestsPlanned` and `estimatedTokens`
  are re-derived from the pairs nobody has asked about yet and reported with
  `batchSize` and `calibrated: true`, so the page's denominator stops moving.
- Truncation: raise before halving. A cut-off answer that salvaged nothing is
  asked again with twice the cap (the warm-up gets the whole window at once),
  and only when that bought nothing — or the cap is already at the window's
  bound — is the batch halved as before. A warm-up that does not fit even then
  ends the review as failed with a message the operator can act on, naming
  DUPLICATES_AI_THINKING and TOKEN_LIMIT. A single pair at the bound keeps the
  old "unsure" and its log line.
- The cut-off text counts. All four providers now attach `error.partialText`,
  so the salvage path runs for every one of them; a salvaged request counts
  its verdicts in `pairsJudged` and in the tracker. Two comments that still
  said only Ollama returns half-written answers were rewritten.
- Progress inside a request. With a progress sink the provider is asked to
  stream (`onProgress`). Each report, at most every 250 ms, carries
  `requestPairs`, `requestAnswers` (the complete verdict objects counted off
  the streamed text), `requestTokens`, `thinking` and the running token total:
  "The model is thinking… (640 tokens so far)" while it thinks, otherwise the
  request line with " · 7 of 10 answers" appended. The report that counts the
  request resets all four. A review nobody watches sends the plain request it
  always sent.
- Calibration memory. The last measurement per model name lives on the
  singleton; a review that finds one starts sized from it, skips the warm-up
  and says so in the log. A measurement taken with thinking on is never reused
  with thinking off. `resetCalibration()` for tests.
- Logs: the finish line says "N pair(s) planned" (the number is the plan), the
  batch-size line is marked provisional until the model is measured, and the
  split line says whether the cap was raised or the batch halved.

services/duplicateMergeService.js

- `scan()` keeps its result per set of options (kind, threshold,
  includeDismissed) for SCAN_CACHE_MS (60 s) and answers the next identical
  request from it with one log line instead of the start and finish lines.
  `fresh: true` skips and refills it; the page's Scan button sends it.
- A merge, an undo, a dismissal and `restoreDismissal()` empty the cache. A
  dismissal deleted through the route, which talks to the model directly, is
  caught by a fingerprint (row count and highest id per kind) checked on every
  hit — one local SELECT against a 13-second scan.
- `reviewScan()` calls `scan()` without `fresh`, so a proposal made right
  after the page scanned costs no second scan.

Testing

- node scripts/run-tests.js --all: 93 passed, 7 skipped offline, 0 failed
  (100 registered), unchanged from the baseline.
- tests/test-entity-match-ai-service.js: 65 -> 80 cases. New: thinking off and
  on; the warm-up's size, cap, phase and message; the sizing math on a fixed
  usage and duration; the request seconds and their floor; the context window
  bounding size and cap; smoothing; the plan and estimate recomputed after the
  warm-up; calibration reused, not reused across the thinking switch, reset; a
  warm-up that cannot fit ending the review with its message; a truncated
  answer with partialText salvaged and counted; a streamed request reporting
  thinking, then answers, then clearing itself; an unwatched review not
  streaming; a review served from the page's scan.
- tests/test-duplicate-merge-service.js: 17 -> 22 cases. New: cache hit, other
  options and `fresh` missing it, expiry, invalidation by merge, undo, dismiss
  and restore, and a dismissal removed behind the service.
- Changed expectations, all from the raise-before-halve rule: the truncation
  cases now see every size asked twice (once, once with twice the cap) before
  it is halved, the single pair is asked twice before it ends as unsure, and
  the planning cases see the `warming-up` phase where they saw `judging`.
- Two demo runs against a fake model at 30 tokens/s: thinking off, 12 pairs —
  warm-up 4 pairs in 20 s (600 tokens, 150 per pair), then requests of 5 pairs
  at 25 s, 4500 tokens, 60 s in total. Thinking on — warm-up 4 pairs in 40 s
  (1200 tokens, 300 per pair) and requests of 2 pairs at 30.04 s, the
  configured length.

Impact

The first request of a review is seconds rather than minutes, every later one
lasts about as long as the operator asked, and the page shows the model
thinking and answering while it happens instead of a still bar. A review of a
model that was measured before starts at full size. Three scans of one archive
become one. Nothing runs on its own and no verdict changed: the prompt, the
rules and the shape of an answer are what they were.

Upstream Status

Not applicable — the Duplicates feature does not exist upstream.

* fix(duplicates): a review never asks for a fresh scan of its own

reviewScan() drops a `fresh` flag its caller may carry instead of passing it on, so a route that forwards the page's scan options cannot make the review scan the archive a second time.

* fix(duplicates): the yes/no switches of the judge read 'yes', and a small batch is not starved after a thinking one

Background
The browser smoke test of the round ran the thinking scenario and the
judge kept saying "thinking off" although DUPLICATES_AI_THINKING=yes
was set. config/config.js normalises every yes/no setting to the
strings 'yes' and 'no' (parseEnvBoolean), while three readers in the
judge asked Boolean() or === true: the thinking switch could never be
turned on, and the review and excerpt switches could not be turned off
('no' is a truthy string). The second finding: a thinking model pays a
fixed price per request, so a one-pair request sized by pairs alone
after a four-pair warm-up got a cap the same thoughts did not fit; the
judge recovered by raising the cap, at the cost of one request.

Changes
- services/entityMatchAiService.js: switchedOn() accepts 'yes' and a
  boolean true; isEnabled(), excerptsEnabled() and thinkingEnabled() use
  it. The cap never drops below the largest completion the model has
  produced in this review plus a quarter (CAP_FLOOR_FACTOR), and that
  floor is remembered with the calibration.
- tests/test-entity-match-ai-service.js: one case per finding (82
  cases), the sizing case expects the remembered floor.
- config/changelog.js: three entries for the round under the current
  release.

Testing
- node scripts/run-tests.js --test entity-match-ai-service: 82 passed.
- Browser smoke against a fake Paperless-ngx and a fake provider that
  streams, thinks on request and honours max_tokens: thinking off, the
  fake never thought, warm-up 4 pairs, 59 tokens/s measured; thinking
  on, the panel showed the thinking state, no request hit the token
  limit any more; Stop, re-attach, token budget and the round-6
  walkthrough unchanged.

Impact
DUPLICATES_AI_REVIEW=no and DUPLICATES_AI_EXCERPTS=no now do what they
say; DUPLICATES_AI_THINKING=yes now reaches the model.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

---------

Co-authored-by: admonstrator <anthropic@viehl.ch>
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
… unused objects, name the survivor (#330)

* feat(duplicates): contract for a targeted AI review

Background
With many groups at 94 to 96 percent the user wants to say "everything
from 95 percent up: ask the AI, show me its view, then merge". The
review must therefore be able to judge only chosen groups and skip the
band of near-misses.

Changes
- schemas.js, OPENAPI/openapi.json: groupIds, minConfidence and
  includeCandidates on DuplicateAiReviewRequest.

Testing
- node scripts/regen-openapi.js: no drift after the commit.

Impact
Request fields only; the implementation follows.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): targeting counters in the AI review result schema

Background
A targeted review reports which groups it judged and which it left
without a verdict; the page shows that.

Changes
- schemas.js, OPENAPI/openapi.json: targeted, groupsJudged and
  groupsSkipped on DuplicateAiReviewResult.aiReview.

Testing
- node scripts/regen-openapi.js: no drift after the commit.

Impact
Documentation of three informational fields.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): let the AI review be pointed at a few groups

Background

An archive with hundreds of correspondents produces dozens of groups at
94, 95 and 96 per cent, and asking the model about all of them costs a
lot to answer a question about a handful. The page needs to select the
groups it is about to merge, ask about those, and keep rendering the
rest of the scan while it does.

Changes

- entityMatchAiService.reviewScan() takes three options that narrow what
  is asked, never what comes back:
  - groupIds: only these scan groups are judged. Every other group is
    still in `groups`, as the scan produced it, with `aiVerdict: null` on
    the group and on every member and `source: 'scan'`. An id this scan
    does not know is ignored and logged once with the count.
  - minConfidence: only groups scoring at least this much are judged;
    together with groupIds both conditions have to hold.
  - includeCandidates (default true): false leaves the band of
    near-misses out entirely, so `candidates` is 0 — and with no band
    the entity list per kind is not read either, which is the cheap part.
- _pairsForKind() takes the set of group ids to judge. A group left out
  contributes no pairs but its member pairs still count as "inside one
  group", so it cannot reappear as a candidate.
- The result reports the targeting: aiReview.targeted, .groupsJudged and
  .groupsSkipped. The start line of the log names it as
  "judging 1 of 4 group(s) (min confidence 0.95, 3 ids), band skipped",
  the closing line adds the two counters. An untargeted review logs and
  behaves exactly as before.
- POST /api/duplicates/ai-review validates and passes the three fields
  through: groupIds an array of at most 500 non-empty strings,
  minConfidence a number in [0.5, 1], includeCandidates a real boolean
  (the string "false" is a 400). An option the request does not mention
  is left out of the service call, so an untargeted request reaches
  reviewScan() with the same object it did before.
- Swagger description of the route and the 400 reason updated,
  OPENAPI/openapi.json regenerated.

Testing

- node scripts/run-tests.js --all -> 90 passed, 7 skipped offline,
  0 failed (97 registered), unchanged against the baseline.
- entity-match-ai-service: 28 -> 34 cases. Six new ones on a fixture
  whose four groups sit exactly on the matcher tiers (1, 0.98, 0.95,
  0.9) plus one pair in the band: groupIds judges only what it names,
  minConfidence filters, includeCandidates: false skips the band and
  reads no second entity list, groupIds and minConfidence combine while
  unknown ids are ignored, an empty selection costs no request, and the
  log lines. The existing aiReview assertion gained the three new fields.
- duplicates-endpoints: 16 -> 19 cases. The three fields reach the
  stubbed reviewScan unchanged, an untargeted request still carries
  nothing extra, ten malformed targeting bodies are 400, and 500 ids are
  accepted while 501 are not.
- Manual run against the real route with a fake store and a fake
  provider: full review 5 pairs / 1 request, minConfidence 0.95 without
  the band 3 pairs, two selected ids (one unknown) 1 pair, and every
  unjudged group back with null verdicts.
- eslint, prettier and the OpenAPI drift check clean on the touched
  files.

Impact

Additive. A review that says nothing about the three options behaves and
logs as before. The page can ask about the groups it selected before a
batch merge; a dozen groups without the band are one or two model
requests instead of the whole archive. schemas.js still has to gain
targeted, groupsJudged and groupsSkipped on DuplicateAiReviewResult.

Upstream Status

Not applicable: the Duplicates feature is next-only.

* feat(duplicates): sort, select by confidence, and a guided review before merging

Background
----------
On a grown archive a scan answers with dozens of groups that all read 94, 95,
96 percent, and the page offered no way to act on that number: every group had
to be judged by eye, one tick at a time. The three presets were the only
thresholds available, so "everything above 95" was not a question the page
could be asked. And where the AI review existed it judged the whole result
list, which is the most expensive way to ask about the five groups the user
actually cares about.

The rule this follows: the AI is an addition, never a condition. Every flow
below works end to end with the review switched off; with it on, the guided
path is one more button beside the one that was already there.

Changes
-------
Results toolbar (#dupResultsBar), above the selection bar, shown once a scan
has groups:
  - "Sort by" (#dupSortSelect): confidence, documents, target name (locale
    compare), kind then confidence. It moves the DOM nodes instead of
    re-rendering, so a card keeps its target, its source ticks, its selection,
    its verdict and its busy state; the two blocks (scan groups, AI
    candidates) are sorted separately and the divider stays between them.
  - "Select >=" (#dupMinConfidence, #dupSelectMinBtn, #dupMinConfidenceCount):
    ticks every selectable group at or above a whole percent and unticks the
    rest, with a live count of what the click would do.
Custom scan threshold: a fourth sensitivity option "Custom" reveals a number
field (#dupThresholdCustom); the scan and both review paths send that percent
divided by 100. The three presets are unchanged.
Confidence breakdown under "Groups found" (#dupStatBuckets): ">=95 %: A .
90-95 %: B . <90 %: C", counted from the cards after a scan and after a review.
Guided flow (#dupReviewThenMergeBtn, rendered only where the review exists):
asks the model about exactly the ticked groups (groupIds, includeCandidates:
false), puts the verdicts on the cards as a full review does, then shows them
once in a wide dialog - one row per group with target, sources, documents, the
verdict chip and the reason, a live "N of M ticked . K documents" foot line and
the copy-rule check. Ticked rows are merged with the batch machinery; an unsure
or different verdict only comes up unticked and never blocks anything, and what
stays unticked stays selected on the page.
"Merge selected" keeps its place and its weight, first in the bar and without a
model anywhere in its path; its dialog names the guided path in one faint line,
and only where that path exists.
Sort, confidence, sensitivity and the custom threshold are remembered in
localStorage (dup.sort, dup.minConfidence, dup.sensitivity,
dup.thresholdCustom) through two try/catch helpers.

Testing
-------
node scripts/run-tests.js --all -> 90 passed, 7 skipped offline, 0 failed
  (unchanged from the branch baseline).
tests/test-duplicates-ui.js: 25 -> 38 cases. New: the toolbar ids and their
  order, the custom threshold field, the stats breakdown, the guided button
  only with the review, the whole page without the review, the toolbar ids in
  the script, sorting as a DOM move, "Select >=", the wrapped localStorage
  access, the guided request (groupIds / includeCandidates: false) and that
  "Merge selected" never touches the review endpoint, the review dialog markup,
  the tip line, the new CSS classes. Changed: the sensitivity options are read
  from #dupSensitivity alone and now end in "custom"; the undo promise and the
  confirm dialogs are counted one higher each, because the review dialog merges
  and therefore makes the same promise.
Reviewed in a browser against a throwaway mock (twelve groups over 88-100 %, a
  review that honours groupIds): 27 screenshots at 1280x900 and 390x844, light
  and dark, 0 px horizontal overflow everywhere, plus a 31-check behaviour
  probe (guided request, verdict ticks, sorting keeping picks and the divider,
  persistence, a refused review, and the whole page with the review off).

Impact
------
Page only. No route, service, schema or config was touched, so the OpenAPI
spec is unchanged. An instance without the AI review renders and behaves
exactly as before plus the toolbar and the custom threshold. The request the
guided path sends uses fields the contract already carries; a server that
ignores them reviews everything, which the page renders correctly.

Upstream Status
---------------
Not applicable - the Duplicates page does not exist upstream.

Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* docs(duplicates): changelog entries for sorting, select by confidence and the guided review

Background
Round 5 answered the second feedback from a real archive: select by a
number, let the model judge exactly those groups, read its verdicts in
one dialog, merge what stays ticked; sort the groups; a custom threshold.

Changes
- config/changelog.js: two entries in the current v2026.09.01 block.

Testing
- node scripts/run-tests.js --test changelog-releases: passed.

Impact
Documentation only.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): contract for evidence-based verdicts and the AI proposal

Background
A real archive produced "Kontoauszug" / "Kontoumzug": the matcher called
it a spelling distance, the prompt allowed "an obvious typo" as a reason
for same, and the model, seeing names and titles only, agreed. Both are
different things. The judge needs stricter rules and, for pairs linked by
spelling alone, a look at what the documents are about, at a bounded
cost.

Changes
- config/config.js: DUPLICATES_AI_EXCERPTS (default yes),
  DUPLICATES_AI_EXCERPT_CHARS (300), DUPLICATES_AI_EXCERPT_DOCUMENTS (2).
- schemas.js, OPENAPI/openapi.json: AiVerdict gains basis and confidence;
  DuplicateAiReviewRequest gains withExcerpts; aiReview reports excerpts.

Testing
- node scripts/run-tests.js --area duplicates: 6/6; regen without drift.

Impact
Settings and schema only; the implementation follows.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): judge model override and the verdict source in the contract

Background
Decisions for round 6: the matcher's hard tiers settle a pair without the
model, unsure pairs are asked once more with excerpts, and the judge may
run on a stronger model of the same provider.

Changes
- config/config.js: DUPLICATES_AI_MODEL (optional, judge only).
- schemas.js, OPENAPI/openapi.json: AiVerdict.source (model or
  spelling-rule); aiReview.escalated and aiReview.spellingRules.

Testing
- eslint and prettier on the two files; regen without drift.

Impact
Settings and schema only; the implementation follows.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(settings): make every DUPLICATES_ setting editable in its own section

Background
The AI review of the Duplicates page arrived with seven environment
variables and no way to change any of them from the interface. Editing a
container environment and recreating the container is the wrong price for
"try a stronger model for the judge" or "ask about fewer pairs per
request", and the settings page is exactly where those knobs belong.
config/config.js already reads all seven; only the front door was missing.

Changes
- views/settings.ejs: a "Duplicates" section (id="sec-duplicates") inside a
  new duplicates-tab block between the AI sections and OCR, with a nav entry
  in the desktop section nav (icon i-merge) and in the mobile one, in the
  same order as the page. Seven fields, each with a hint that says what the
  value does and what its default is: the AI review switch, the judge model,
  pairs per request, the candidate floor, the excerpt switch, excerpt length
  and documents per entry. Switches go through partials/settings-switch, so
  the hidden yes/no input the POST route reads exists as it does everywhere
  else.
- routes/setup.js: GET /settings passes the seven values (env first, the
  defaults of config/config.js as fallback) in the config object the view
  reads; POST /settings destructures the seven camelCase body keys,
  normalises them and writes them into updatedConfig, so setupService
  .saveConfig persists them with the rest. Numbers are clamped to their
  range; a value that is not a number, or a cleared field, keeps what is
  configured now instead of resetting to the default. The swagger body
  schema documents all seven, and the .env export gained a "Duplicates"
  group between "AI behaviour" and "External API".
- public/js/settings.js: the seven selector to env-key entries, so the
  "Overwritten" and "Managed by ENV" marking covers these fields too.
- OPENAPI/openapi.json regenerated.
- tests/test-settings-duplicates-section.js, registered in the
  observability area.

Testing
- node scripts/run-tests.js --all: 98 registered, 91 passed, 7 skipped
  offline (was 97/90/7). The new test covers the rendered section and its
  nav position, the seven inputs and their values, the POST round trip,
  clamping, the keep-the-previous-value case and the .env export group.
- npx eslint / npx prettier --check --ignore-unknown on every touched file.
- node scripts/regen-openapi.js leaves OPENAPI/openapi.json unchanged.
- Looked at the page in Chromium at 1440x1000 and 390x844 against a
  throwaway server outside the repository; no console errors, the section
  reads like the rest of the page and stacks on the phone.

Impact
Operators can change every DUPLICATES_ value from the settings page. The
existing restart-after-save is what makes them take effect; no new
mechanism. Values injected by the container still win and are shown as
managed, as for every other field. Nothing outside the settings page
changes: no route, service or default behaviour of the Duplicates page
itself is touched.

Upstream Status
Fork-only. The Duplicates page does not exist upstream.

Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): judge spelling-only pairs on evidence, not on distance

Background
A real archive produced "Kontoauszug" next to "Kontoumzug": the matcher
called it a spelling distance, the prompt allowed "an obvious typo" as a
reason for same, and the model, seeing two names and three titles, agreed.
Two different things. The judge needed stricter rules, evidence for the
pairs where spelling is the only link, and a way to say how sure it is and
on what grounds — all without opening a large context window on every pair.

Changes
- entityMatchAiService: the system prompt refuses a small spelling distance
  as a reason of its own ("Kontoauszug" / "Kontoumzug", "Miete" / "Mieter",
  "Bahn" / "Bank"), allows a misspelling only when one spelling is not a
  word, and answers unsure when it cannot tell. The output contract gains
  "basis" (a closed list) and "confidence" (high | low); both are parsed,
  an unknown value becomes null, and every verdict, member verdict and
  aggregate carries them. An aggregate keeps the deciding member's basis
  and takes "low" as soon as one deciding member is low.
- Evidence, graded by what the link is worth: every pair carries matched_by
  and score; every judged entity carries its titles, its matching rule and
  its neighbourhood ("filed_with": the correspondents of a tag's documents,
  the tags of a correspondent's); only the pairs linked by fuzzy, prefix or
  token-order also carry document excerpts. Excerpts are read once per
  entity per review and never for a strong tier. withExcerpts: false or
  DUPLICATES_AI_EXCERPTS=no reads nothing at all.
- A member pair a matcher rule settles (exact-normalized, umlaut-variant,
  legal-form) never reaches the provider: it gets verdict same with
  source: spelling-rule, counts in aiReview.spellingRules and costs no
  request, no read and no token.
- A pair the model calls unsure and that had no excerpts is asked once more
  with them; the second answer replaces the first (aiReview.escalated).
- paperlessService: getRecentDocumentExcerptsByEntity (one read,
  truncate_content, cut to the configured characters at a word boundary)
  and getEntityNeighbourhood (one read, the most frequent neighbour names
  through the existing caches). Both answer [] on any error and never log
  document content.
- The judge may run on its own model (DUPLICATES_AI_MODEL): generateText
  takes an optional model in all four provider services, shared through
  aiGenerateOptions.modelOverride.
- Logs: the per-kind start line names the evidence and the model, the
  request line the pairs with excerpts, the escalation its own line.
- Route POST /api/duplicates/ai-review parses withExcerpts like withTitles;
  swagger description updated and OPENAPI/openapi.json regenerated.

Testing
- node scripts/run-tests.js --all: 97 registered, 90 pass, 7 skip offline.
- tests/test-entity-match-ai-service.js: 35 -> 50 cases (the stricter
  prompt, basis and confidence parsing, excerpts only for spelling-only
  pairs and once per entity, the two switches, the configured cut, the
  Kontoauszug regression, settled pairs, the neighbourhood, escalation, the
  model override, batch sizing with excerpts, and both new client methods).
- tests/test-duplicates-endpoints.js: one case for withExcerpts; the three
  existing option assertions now expect withExcerpts: true.
- Demo run against the fake Paperless-ngx: the Kontoauszug/Kontoumzug pair
  costs 282 prompt tokens with excerpts, a strong pair without excerpts 75.
- eslint, prettier and a regen without drift on every file touched.

Impact
An AI review asks about fewer pairs and knows more about the ones it asks
about. Nothing runs on its own, nothing is merged, and document content
never reaches a log line.

Upstream Status
Not applicable — the Duplicates feature does not exist upstream.

* fix(duplicates): do not escalate an unsure pair whose documents carry no text

* feat(duplicates): one click for the AI's proposal, with the evidence behind it

Background
----------
Everything the page offered so far started from the user: scan, read every
card, tick, merge — and where the AI review existed it was a second question
asked after the first. What was missing is the path the archive's owner
actually wants for a first clean-up: one click that scans, has every group and
every near-miss judged, and then hands over a proposal to thin out rather than
a list to work through.

The rule this follows is the same as in the rounds before: the AI is an
addition, never a condition. Without the review nothing of this renders, and
"Scan Paperless-ngx", "Merge selected", the toolbar, the manual merge and the
guided path are the same as they were.

A verdict also had to say more than "same": with `basis`, `confidence` and a
`source` on the wire, the page can pre-tick exactly what is settled — a pair a
spelling rule decided, or one the model says it is sure about — and leave
everything else to the user. The member tables, finally, measured their own
content per card, so the columns of two cards below each other sat in
different places.

Changes
-------
"AI proposal" (#dupAiProposalBtn, primary, rendered only with aiReviewEnabled)
next to "Ask the AI", usable from the first paint because it scans itself:
  - status in the AI row (#dupAiProposalStatus): "Scanning…", then "Asking the
    AI about N pairs and near-misses…", with the hint line under the row
    (#dupAiProposalHint) saying what the click does;
  - it reuses runScan() (now awaited) with the kind, sensitivity and hidden-pair
    settings on the page, then the one review request with includeCandidates
    and no groupIds. Two requests, and no merge until the dialog is confirmed.
Proposal dialog (.dup-proposal-dialog): one row per group that could be merged,
  sorted same/high, same, unsure, different, unjudged (proposalRank,
  compareProposalEntries — both pure); pre-ticked are only the settled ones
  (isSureSame: verdict "same" with confidence "high", which covers the
  spelling-rule verdicts); legend, "Tick all same" (#dupProposalTickSame),
  "Untick all" (#dupProposalUntickAll), the copy-rule check (#dupCopyRuleAll)
  and a live foot line "N of M ticked · K documents · X objects will be
  deleted". Confirming sets the page selection to the ticked groups and hands
  them to the batch runner of round 4, so the selection bar reports the merge
  as it does for "Merge selected"; cancelling leaves the verdicts on the cards
  and nothing ticked.
Evidence, shared by both dialogs (one row renderer, one table):
  - a "Basis" column as a .zr-badge with a label per contract value;
  - the confidence as a suffix of the verdict chip ("AI: same · high");
  - a pair a spelling rule settled reads "Spelling rule" in the "same" tone
    (.dup-verdict--rule) instead of quoting a model that never saw it;
  - the guided dialog pre-ticks by the same rule, so a "same" the model is
    unsure about now comes up unticked there too.
Cards keep their shape: the verdict chip carries the basis in its title and the
  confidence as its suffix, no new column.
Second checkbox "Use document excerpts for spelling-only pairs"
  (#dupAiExcerpts, checked); withTitles and withExcerpts flow into every review
  request from the one place that builds it. The titles checkbox is relabelled
  "Use document titles and neighbours as context".
"AI-judged pairs" tile: its sub line now also counts "· E excerpts", "· S by
  spelling rule" and "· E escalated" when the review reports them.
Member tables line up across cards: .dup-members is table-layout: fixed with
  the name column taking what is left and truncating, and the matching rule a
  fixed share (.dup-members__name, .dup-members__rule).

Testing
-------
node scripts/run-tests.js --all -> 90 passed, 7 skipped offline, 0 failed
  (unchanged from the branch baseline of 97 registered).
tests/test-duplicates-ui.js: 38 -> 48 cases. New: the proposal ids and labels
  only with the review and the page whole without them; what the flow sends
  (runScan first, includeCandidates: true, no groupIds, both evidence flags,
  no request of its own); the pre-tick rule, evaluated as a function against
  seven verdicts; the row order, evaluated by sorting a shuffled list; a label
  for every basis the AiVerdict schema lists, parsed out of schemas.js; the
  spelling-rule chip; the dialog's parts and that it merges through the batch
  runner; the evidence counters of the stats tile; the fixed member-table
  layout; the new CSS classes. Changed: the titles checkbox label, the undo
  promise and the confirm dialogs counted one higher each (the proposal merges
  and therefore makes the same promise), and the pre-tick assertion of the
  guided row.
Reviewed in a browser against a throwaway mock (eleven scan groups plus three
  the model proposes, verdicts across same/high, same/low, unsure and
  different, some settled by a spelling rule, and a Kontoauszug / Kontoumzug
  pair that only the excerpts decide): 31 screenshots at 1280x900 and 390x844,
  light and dark — the controls, the status line mid-flow, the proposal dialog,
  after "Untick all", mid-merge, after the merge, the guided dialog, the stats
  tile, the aligned member tables and the render without the review. 0 px
  horizontal overflow everywhere; the column offsets of all eleven cards are
  identical.

Impact
------
Page only. No route, service, schema or config was touched, so the OpenAPI
spec is unchanged. An instance without the AI review renders and behaves
exactly as before. The new request field and the new verdict fields are ones
the contract already carries: a server that ignores withExcerpts reviews as it
did, and a verdict without basis, confidence or source renders as it did — it
then simply never comes up pre-ticked, which is the safe side.

Upstream Status
---------------
Not applicable - the Duplicates page does not exist upstream.

Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* chore(duplicates): changelog for the AI proposal round, room for the verdict in the Match column

Background
The sixth round of the Duplicates feature adds the AI-led proposal, the
evidence-based judge and the Duplicates settings section. The member
tables now use a fixed column layout so the columns line up across
cards, which left the Match column too narrow for a verdict such as
"AI: same - high": it wrapped into four lines.

Changes
- config/changelog.js: five entries for the round under the current
  release (AI proposal, evidence-based judge with excerpts and
  DUPLICATES_AI_EXCERPT*, DUPLICATES_AI_MODEL, aligned member tables,
  the Duplicates settings section).
- public/css/pages/duplicates.css: the Match column is 132px wide and
  the member verdict does not wrap, so the percentage and the verdict
  take one line each.

Testing
- npx eslint, prettier --check and stylelint on every file changed
  against nightly: clean.
- node scripts/run-tests.js --all: 91 passed, 7 skipped (server or
  credentials needed), 0 failed.
- node scripts/regen-openapi.js: no drift.
- Browser walkthrough against a fake Paperless-ngx and a fake judge:
  scan, merge, undo, dismiss, merge by hand, batch merge, guided review,
  AI proposal and AI review all pass. The Kontoauszug/Kontoumzug pair is
  judged "different" on its excerpts and does not appear in the
  proposal.

Impact
Visual only for the CSS; the changelog is shown in the What's New
dialog.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): contract for a watchable, stoppable AI review

Background
An AI review of a large archive is many model requests in a row. Today
it is one POST that answers when everything is done: nothing shows
while it runs, nothing can stop it, and the tokens it spends are
invisible until the end. The user wants to see what is happening, how
far it is and what it costs, and to stop it at any time. Decisions for
this round: the review runs as a server-side job the page can watch
and stop; a review nobody watches stops itself; a token budget per
review stops it on its own; a stopped review keeps the verdicts it
reached and opens no dialog; the progress lives in the AI row of the
Duplicates page.

Changes
- services/duplicateReviewJobService.js (new): the one review job at
  a time. start(), current(), get(), stop(id, reason), subscribe() for
  a server-sent stream (a late subscriber first gets the job as it is
  now), touch(), wait(), result(), toJSON(). The judge receives a
  control object (signal, onProgress, stop, tokenBudget); a partial
  result of a stopped review is kept like a complete one. The idle
  watch stops a job nobody has watched for the configured seconds. A
  finished job stays reachable for ten minutes.
- config/config.js: DUPLICATES_AI_TOKEN_BUDGET (200000, 0 = no limit)
  and DUPLICATES_AI_IDLE_STOP_SECONDS (60, 0 = never).
- schemas.js, OPENAPI/openapi.json: AiReviewProgress, AiReviewJob,
  AiReviewJobEvent; aiReview gains stopped, stopReason and
  pairsNotJudged.
- scripts/run-tests.js, tests/test-duplicate-review-job.js: the
  contract test of the job (9 cases) in the duplicates area.

Testing
- node scripts/run-tests.js --all: 99 registered, 92 pass, 7 skip
  offline, 0 fail.
- eslint and prettier on every touched file; regen without drift.

Impact
Nothing uses the job yet; the judge ignores the control object until
the implementation follows. No route or page changes.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): make the token budget and the idle stop editable in settings

Background
The two brakes of a running AI review landed as environment variables only:
DUPLICATES_AI_TOKEN_BUDGET caps what one review may spend across all its
requests, DUPLICATES_AI_IDLE_STOP_SECONDS ends a review no page has been
watching, so a closed tab cannot leave the model running. Both are exactly
the kind of setting somebody wants to try out once and then adjust, which
means editing a compose file and restarting the container for every attempt.
The other seven DUPLICATES_* variables already have a field in the Duplicates
section of the settings page; these two did not.

Changes
- views/settings.ejs: two number fields at the end of #sec-duplicates, in the
  style of the five above them — duplicatesAiTokenBudget (0-10000000, step
  1000) and duplicatesAiIdleStopSeconds (0-3600). Each hint says what the
  value does, what zero means and what the default is.
- routes/setup.js: GET /settings passes DUPLICATES_AI_TOKEN_BUDGET and
  DUPLICATES_AI_IDLE_STOP_SECONDS to the view with the defaults of
  config/config.js as the fallback; POST /settings destructures both body
  keys, clamps them to their ranges and keeps the currently configured value
  for an empty or non-numeric field, the rule the round-6 fields follow. Zero
  is a value for both and survives the clamp, because the ranges start there
  rather than at one. The @swagger body schema documents both, and the
  Duplicates group of ENV_EXPORT_GROUPS lists them after the existing keys.
- public/js/settings.js: two entries in the field mapping, so an
  operator-injected value greys the field out and carries the "Managed by ENV"
  pill like every other setting.
- OPENAPI/openapi.json regenerated.

Testing
- tests/test-settings-duplicates-section.js grew from 7 to 11 cases: the two
  fields render with their configured values, ranges and hints and close the
  section in that order; every field of the section is paired with its
  environment key in settings.js; the POST round trip persists all nine
  values; a budget of 99999999 is capped at 10000000 and an idle stop of -5
  lands on 0; zero survives for both, because it means "no limit" and "never"
  rather than an unset field; a fractional value is rounded; a cleared or
  unparsable field keeps what was stored before; the .env export carries all
  nine keys with the two brakes last.
- node scripts/run-tests.js --all: 99 registered, 92 passed, 7 skipped
  offline, 0 failed — the same numbers as before this change.
- eslint and prettier clean on every file touched; regen-openapi.js leaves no
  drift.
- Looked at the section in Chromium at 1440x1000 and 390x844 against a
  throwaway server outside the repository: both fields render like the seven
  above them, no console errors, and with the two keys in the locked-env set
  both are disabled and carry the "Managed by ENV" pill while a neighbouring
  field stays editable.

Impact
No behaviour change for anybody who never opens the section: the defaults are
unchanged (200000 tokens, 60 seconds) and nothing new runs. Operators who set
either variable in their container environment keep winning — the field is
shown greyed out rather than silently overwritten. A saved value needs a
restart to take effect, as the hints say, because config/config.js reads the
environment once at load.

Upstream Status
Not applicable — the Duplicates page is specific to this fork.

* feat(ai): let every provider take an abort signal for one call

aiGenerateOptions gains abortSignal(options); the four provider
services pass it on where their client expects it — the OpenAI SDK as
the second argument of create(body, { signal }) for OpenAI, Azure and
the custom endpoint, axios as { signal } in the request config for
Ollama. Without a signal every provider sends exactly what it sent
before: no second argument at all, and the unchanged axios config.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): the AI review reports, stops and counts its tokens

Background
"Während die AI befragt wird, könnten Millionen von Tokens im
Hintergrund verbraten werden, ohne dass man es sieht. Man muss es auch
abbrechen können." The judge answered when it was done and said
nothing while it worked, so the page had nothing to show and nothing
to stop. The job of the previous round hands it a control object; this
round makes the judge use it. A bar needs a denominator before the
first request, which the old per-kind loop could not give: it read the
archive, asked, and only then looked at the next kind.

Changes
- services/entityMatchAiService.js: reviewScan(options, control = {})
  runs in two passes. Pass one, for every kind of the review: read the
  entities and the band, build the pairs, settle the spelling-rule
  pairs, gather titles, neighbourhood and excerpts, and size the
  batches. Pass two judges kind after kind. Nothing is asked before
  the whole plan exists.
- Progress: phase scanning before the scan, phase evidence per kind
  and per read, one phase judging with requestsPlanned, pairsTotal and
  estimatedTokens for the whole review, one report per answered
  request (requestsDone, pairsJudged, the running token total,
  failedRequests, retries, kind, and the line naming the next
  request), phase escalating when an unsure pair is asked again, phase
  finishing before the groups are built. A split answer adds its
  halves to requestsPlanned in the report of the request that split,
  so the bar never goes backwards; the escalation adds its own
  requests and pairs the same way. Elapsed time and the estimate stay
  with the job, which derives them.
- Stopping: control.signal is read before every read, every request
  and the second round, and travels to the provider, so a stop lands
  on a request in flight. A request that dies on the signal is a stop,
  not a failure: no failed request, no retry, and no "unsure" — the
  pairs stay without a verdict, so they cannot become a group. A
  stopped review returns what it reached; it never throws.
  aiReview now always carries stopped, stopReason (null; the job fills
  it in) and pairsNotJudged.
- Token budget: one running total for the whole review, folded from
  the provider's usage or, for a provider that reports none, from the
  measured prompt plus the estimated answer, so the counter and the
  budget work for every provider (aiReview.tokens keeps reporting only
  what a provider stood behind). When control.tokenBudget is reached
  the review calls control.stop('token-budget') and behaves as
  stopped.
- Logs: "review stopped (user|token-budget|idle): N of M request(s)
  made, P pair(s) not judged, T token(s)." and "token budget 200000
  reached after N request(s) (T tokens)."; the start, request and
  finish lines are unchanged.
- services/duplicateReviewJobService.js: the control object gains
  stopReason(), the one seam the judge needs to name the reason in its
  own log line.
- reviewPairs(pairs, options) additionally takes plan, systemPrompt
  and tracker from reviewScan; a caller that brings none gets what it
  always got.

Testing
- node scripts/run-tests.js --all: 99 registered, 92 pass, 7 skip
  offline, 0 fail (the baseline of the branch).
- tests/test-entity-match-ai-service.js: 13 new cases (64 total) —
  the plan before the first request for one and for two kinds, the
  split and the escalation raising the plan, a failed request still
  moving the bar, a stop between requests and a stop in flight, the
  token budget, a provider without usage, an already aborted signal, a
  review without a control, the report carrying nothing the job
  derives, and the signal reaching all four providers. The one moved
  expectation is the deep-equal on aiReview, which now names the three
  new fields.
- tests/test-duplicate-review-job.js: one case for stopReason().
- A real run through the job service over a fake archive: a review
  that runs through, the same one stopped after request 2, and the
  same one against a token budget.
- eslint and prettier on every touched file.

Impact
The page can show a bar with a denominator, an estimate and a running
token count from the first request, and a stop costs at most one
request that is already in flight. A review without a control object
behaves exactly as before, so the synchronous route is untouched until
it is moved onto the job.

Upstream Status
Not applicable: the Duplicates page and its AI review do not exist
upstream.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): watch and stop the AI review from the page

Background

A review of a drifted archive is many model requests in a row. Until now
"Ask the AI" was one POST that answered when everything was over: a spinner,
no idea how many requests were still coming, no idea what it cost, and no way
out but reloading the tab — which left the model running. The job service of
the contract commit made the review watchable and stoppable on the server;
this wires the routes and the page onto it.

Changes

routes/setup.js (Duplicates block only)
- parseAiReviewRequest(body) holds the validation both entry points share, so
  the synchronous route and the job route can no longer drift apart.
- POST /api/duplicates/ai-review/jobs starts a review and answers
  202 { job }; while one runs it answers 409 with that running job, so a
  second tab attaches instead of failing.
- GET /api/duplicates/ai-review/jobs/current answers { job } or { job: null }
  and counts as watching the review.
- GET /api/duplicates/ai-review/jobs/:id answers { job, result }, 404 for an
  unknown id, and also counts as watching.
- GET /api/duplicates/ai-review/jobs/:id/events streams AiReviewJobEvents
  (text/event-stream, no-cache, X-Accel-Buffering: no, keep-alive, flush after
  every write), a ": keep-alive" comment every 15 s, and ends after done,
  stopped or failed. An unknown id is a JSON 404 before any stream header.
- POST /api/duplicates/ai-review/jobs/:id/stop answers { job }; stopping a
  finished review is a 200 no-op.
- POST /api/duplicates/ai-review now starts that same job and waits for it: a
  stopped review answers 200 with the verdicts it reached, a failed one keeps
  the judge's status, and a second request while one runs is a 409. It
  subscribes for the duration so the idle stop cannot end a review somebody is
  waiting for.
- @swagger for every new route; OPENAPI/openapi.json regenerated.

views/duplicates.ejs, public/js/duplicates.js, public/css/pages/duplicates.css
- A progress panel in the AI row (#dupAiProgress): bar (#dupAiProgressFill,
  indeterminate while the plan is unknown), message, counters
  ("Request 3 of 8 · 40 of 96 pairs · 12.4k of 200k tokens"), time
  ("about 40 s left · 1:24 elapsed") and a Stop button (#dupAiStopBtn). After
  the end it keeps one outcome line and hides on the next scan or review.
- askForVerdicts() starts the job, follows it through EventSource and falls
  back to polling the job every 2 s when the stream breaks. It resolves
  { aiReview, stopped }; all three AI paths honour `stopped` — the notice is
  shown and neither the guided dialog nor the proposal opens.
- On load the page asks for the current job and re-attaches to one that is
  still running; a finished one is left alone.
- Pure helpers formatTokens, formatEta, formatElapsed, progressPercent and
  stopNotice word the numbers; the UI test evaluates them directly.

Testing

- node scripts/run-tests.js --all: 99 registered, 92 pass, 7 skip offline
  (unchanged); duplicates-endpoints 20 -> 30 cases, duplicates-ui 48 -> 57.
- eslint, prettier, stylelint clean on every touched file; regen-openapi
  leaves no diff.
- Reviewed in a browser against a throwaway server with a judge that reports
  eight requests: mid-run, stopping, stopped and done, desktop and phone,
  light and dark, no console errors. A page loaded while a review runs
  re-attached and rendered its result; with the event stream blocked the same
  review came home through eight polls.

Impact

The Duplicates page shows what a review is doing and costing and can end it;
the verdicts already reached are kept. The synchronous route keeps its request
and response, so an API client sees no change beyond the new 409 while a
review runs.

Upstream Status

Not applicable — the Duplicates feature does not exist upstream.

* fix(duplicates): a late Stop answer no longer paints over the outcome; changelog for the review job

Background
In the browser smoke test of the round, a stop pressed after the first
answered request ended the job before the stop request itself answered.
The page then rendered that answer, a snapshot from the stopping moment,
over the outcome line and restarted the elapsed clock, so the panel read
"Stopping after the current request…" next to a finished review.

Changes
- public/js/duplicates.js: stopReview() renders the stop answer only
  while the same job is still followed and still live.
- tests/test-duplicates-ui.js: one case that pins the guard (57 -> 58).
- config/changelog.js: three entries for the round under the current
  release (the review as a job with progress and Stop, the token budget
  and the idle stop as settings, the plan before the first request).

Testing
- node scripts/run-tests.js --test duplicates-ui: 58 passed.
- Browser smoke against a fake Paperless-ngx and a slowed-down fake
  provider: Stop during request 2 leaves "Stopped after 1 of 5 requests
  · 1 of 5 pairs judged · 1.1k tokens" on the panel, the verdicts
  reached stay on the cards, no dialog opens; the proposal path stops
  the same way; a token budget of 2500 stops the review after 3
  requests with the budget named in the notice and the log; a page
  reloaded during a review re-attaches and renders the result; the
  round-6 walkthrough (scan, merge, undo, dismiss, merge by hand, batch,
  guided review, proposal, plain review) passes unchanged.
- eslint and prettier on the touched files.

Impact
Visual only; the review itself was stopped correctly before the fix.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): contract for a judge that measures the model, streams its answers and thinks only on request

Background
On a real archive with a hosted Qwen model the first review request
asked about 25 pairs, ran for 103 seconds and died at its own answer
cap: the model spent the whole budget thinking before the first
verdict, the cut-off text was thrown away, and the page showed nothing
but a ticking clock for two minutes. Three scans of 13 seconds each
came before that. Decisions for this round: the judge measures the
model on a small first request and sizes every later request to a
target duration; the providers stream the answer so the page moves
inside a request and a cut-off answer keeps its verdicts; thinking is
off for the judge unless the operator switches it on; the review
reuses a fresh scan instead of scanning again.

Changes
- config/config.js: DUPLICATES_AI_THINKING (no) and
  DUPLICATES_AI_REQUEST_SECONDS (30).
- schemas.js, OPENAPI/openapi.json: AiReviewProgress gains
  requestPairs, requestAnswers, requestTokens, thinking, batchSize and
  calibrated; the phase list gains warming-up.
- services/duplicateReviewJobService.js: the new progress fields, the
  warming-up phase, and a time estimate from the share of pairs done
  (answers streamed in count), because the batch size may change after
  the warm-up.
- services/aiGenerateOptions.js: reasoningEnabled(options) and
  progressHandler(options), the two switches the judge will send and
  the providers will read, with the GenerateTextProgress shape and the
  partialText rule for cut-off answers.
- scripts/run-tests.js, tests/test-ai-provider-streaming.js: a
  registered placeholder for the provider streaming test.

Testing
- node scripts/run-tests.js --all: 100 registered, 93 pass, 7 skip
  offline, 0 fail.
- eslint and prettier on every touched file; regen without drift.

Impact
Nothing reads the new switches yet; the implementation follows.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* test(helpers): fake OpenAI-compatible and Ollama servers on ephemeral ports

* feat(providers): stream the answer, report progress, keep the cut-off text

Background

A hosted model behind the custom provider spent 103 seconds and the whole
3200-token completion cap on one AI-review request, then threw "the answer hit
a token limit" and dropped every character it had produced. Nothing was visible
while it ran, nothing survived the throw, and the batch was split and paid for
again from the beginning. Two causes: the four provider services always sent a
non-streaming request, so there was nothing to watch; and
assertCompletionNotTruncated() threw before anyone read the content, so the
prefix was thrown away. On top of that the model thinks before it answers, and
on a server that separates thinking from answering the reasoning arrives as
reasoning_content deltas that no provider knew about.

Changes

- services/aiGenerateOptions.js: the shared streaming machinery.
  stripReasoningText() removes <think> blocks, including one a cut-off left
  open. createProgressCollector() assembles a streamed answer, splits reasoning
  from answer incrementally (a marker may be cut across two chunks), counts the
  completion tokens from a usage chunk or estimates them over everything
  produced, reasoning included, and reports at most once per 100 ms plus one
  final report that says done. consumeChatCompletionStream() and
  runChatCompletionStream() are the OpenAI-compatible half: read the stream,
  finish before any throw, and turn a cut-off or a stop into an error that
  carries what arrived. isAbortError()/abortedGenerationError() give a stopped
  request one name across the SDK, axios and fetch.
- services/serviceUtils.js: estimateTokenCount() (the same character-based
  estimate, on a length) and an optional fourth argument on
  assertCompletionNotTruncated() that puts partialText on the error.
- services/openaiService.js, services/customService.js,
  services/azureService.js: generateText() streams when the caller hands in
  onProgress, with stream_options: { include_usage: true } on OpenAI and the
  custom provider and on Azure only from API version 2024-06-01, where the API
  takes it. Without a handler the body is exactly what it was. Both paths strip
  reasoning from the answer and attach the prefix to a truncation error; an
  abort throws an AbortError with partialText.
- services/customService.js: reasoning: false adds
  chat_template_kwargs: { enable_thinking: false } and, for a model name
  matching /qwen/i, that family's soft switch on its own line at the end of the
  user message; reasoning: true sends enable_thinking: true and no soft switch;
  without the option nothing new is sent.
- services/ollamaService.js: generateText() reads NDJSON from an axios
  responseType: 'stream' response, keeps the tail of a socket read until its
  newline arrives, treats the thinking field as thinking, and stops reading the
  moment the signal aborts. reasoning: false/true sends think and overrules
  OLLAMA_THINK; without the option OLLAMA_THINK still decides. The cut-off
  check the analysis path has always run now runs here too, with partialText,
  and a failure no longer erases a token count that was already measured.
- tests/helpers/fake-openai.js, tests/helpers/fake-ollama.js: real HTTP servers
  on ephemeral ports, scripted per request (content chunks, reasoning chunks,
  finish reason, usage chunk or none, per-chunk delay, non-streaming answers
  from the same script), recording every request body and whether the client
  hung up early.
- tests/test-ai-provider-streaming.js replaces its placeholder with 22 cases.

Testing

- node tests/test-ai-provider-streaming.js: 22 passed, 0 failed; run five
  times, no flake.
- node scripts/run-tests.js --all: 93 passed, 7 skipped offline, 0 failed —
  the same numbers as before this change.
- npx eslint and npx prettier --check on every touched file: clean.
- A throwaway process reproduced the reported failure against the fake: the
  progress reports show thinking first with no text, then the answer growing,
  then one done report with the exact token count from the usage chunk, and the
  throw carries the 131 characters of JSON that had arrived.

Impact

No caller behaves differently unless it asks: without onProgress the request
body is byte for byte what it was, and the round-7 provider cases assert that.
What does change for every caller of generateText(): a <think> block no longer
reaches the returned string, a truncation error now carries partialText, an
abort now throws under the name AbortError, and Ollama's generateText() now
raises the same truncation error the analysis path raises instead of returning
a half-written answer. The document analysis path is untouched.

Upstream Status

Not upstream. Streaming, progress reporting, the partial text of a cut-off
answer and the thinking switch do not exist in clusterzx/paperless-ai.

* feat(duplicates): the progress panel moves inside a request and names the measured batch size

Background

A review of a large archive is a handful of long model requests, and the
panel only moved between them. One request took 103 seconds while the page
showed "request 1 of 4 - 0 of 82 pairs" and a ticking clock, so for minutes
at a time the only honest reading of the page was "nothing is happening".
The judge now measures the model on a small first request, sizes every later
one to a configured number of seconds, and streams the answers as they
arrive, which gives the page three things it never had: answers inside a
request, a warm-up phase, and a model that says when it is thinking.

Changes

Page (views/duplicates.ejs, public/js/duplicates.js,
public/css/pages/duplicates.css):

- progressPercent() counts pairs whenever the plan knows them, the answers
  of the running request included, and falls back to requests only while no
  pair count exists. The bar therefore moves during a request instead of
  jumping once per request.
- progressCountsText() gained the "7 of 10 answers" part, printed only while
  a request is in flight and capped at the size of that request.
- progressTimeText() says "measuring the model" in the warm-up and "the
  model is thinking" while the model writes reasoning, instead of a clock
  that cannot move; an estimate the job already made is still shown next to
  either.
- New #dupAiProgressNote line under the counts, written by the new
  progressNoteText(): "4 pairs per request while the model is measured"
  before the measurement, "9 pairs per request, sized from the model's
  answers" after it, empty while no size is known. A zero-width space holds
  its row open for as long as a review runs (.dup-progress--live), so the
  stats tiles below do not jump the moment it fills.
- .dup-progress__fill--thinking pulses while the model reasons, slower than
  the indeterminate band, and is switched off under prefers-reduced-motion.
- The outcome line and the "Model requests" tile both name the batch size the
  review settled on.
- New htmlReviewFailure(): all three AI paths report a failed review with the
  judge's own message plus one link, "Open the Duplicates settings", to
  /settings#duplicates-tab.

Settings (views/settings.ejs, public/js/settings.js, routes/setup.js):

- Two fields close the Duplicates section: the switch "Let the judge think"
  (DUPLICATES_AI_THINKING, default off) and the number "Seconds per model
  request" (DUPLICATES_AI_REQUEST_SECONDS, 5-300, default 30). GET, POST with
  the usual clamping and keep-the-previous-value behaviour, the @swagger
  request body, ENV_EXPORT_GROUPS and the two "Managed by ENV" selectors.

Route:

- GET /api/duplicates/scan passes fresh: true; a scan somebody pressed a
  button for must not be answered from a cache.

OPENAPI/openapi.json regenerated.

Testing

- node scripts/run-tests.js --all: 93 passed, 7 skipped offline, 0 failed
  (unchanged from the baseline of this round).
- duplicates-ui 58 -> 66 cases: the bar with streamed answers and without a
  pair count, the counts line with and without a running request, the three
  wordings of the time line, the note line, the outcome line with a batch
  size, the panel ids and the thinking class, the settings link of the failed
  notice, and the stylesheet's pulse with its reduced-motion rule.
- settings-duplicates-section 11 -> 15 cases: both fields render with their
  values and hints, the POST round trip, clamping (2 -> 5, 999 -> 300), the
  cleared field keeping the previous value, the switch spellings, the export
  group order and the two selectors.
- duplicates-endpoints 30 -> 31 cases: the scan route hands fresh: true to
  the service.
- eslint, prettier and stylelint clean on every touched file; regen-openapi
  leaves no drift.
- Looked at in Chromium against a throwaway server on port 3403 that walks a
  scripted review through the warm-up, a thinking stretch and a request whose
  answers climb 0 -> 10: desktop and phone, light and dark. The stats tiles
  sit at the same offset before and after the note line fills.

Impact

The panel reports inside a request rather than between requests, and names
both the warm-up and the measured batch size, so a review that takes minutes
per request looks like work rather than a hang. A failed review points at the
setting that would have prevented it. Nothing scans, judges or merges on its
own; the two new settings are read at startup like the rest of the section.

Upstream Status

Not applicable - the Duplicates page does not exist upstream.

* feat(duplicates): measure the model, size every request to it, and reuse a fresh scan

Background

Asking the AI about a scan of the user's archive did not work on their
instance. The judge sent 25 pairs with a completion cap of 3200, the hosted
model thought before it answered and spent all 3200 tokens on the thinking,
and 102 seconds later nothing had been judged. The answer was then split into
13 + 12, which buys nothing: the thinking does not get cheaper with fewer
pairs. Meanwhile the page showed "request 1 of 4 · estimating…" for two
minutes, because a request only reports when it is over. The user pressed
Stop.

The same run also scanned the archive three times inside 50 seconds — the
page's scan, the AI proposal's and the review job's — 1359 tags and 13
seconds each, with nothing changing in between.

Changes

services/entityMatchAiService.js

- Thinking off by default. Every judge request carries
  `reasoning: config.duplicatesAiThinking === true`, so a reasoning model
  answers instead of deliberating unless the operator asked for it. Nothing
  else about the prompt changed.
- A warm-up instead of a guess. The first request of a review whose model has
  not been measured asks about at most WARMUP_PAIRS (4) pairs with a
  deliberately generous cap (RESPONSE_TOKENS, the flat estimate or
  WARMUP_MIN_CAP, whichever is largest, bounded by the context window). It is
  announced under the phase `warming-up` with the message "Measuring the model
  with a small first request…", `calibrated: false` and the size it will use;
  the plan reported with it is provisional and the log says so.
- Sizing from the measurement. Every answered request yields tokens per pair
  (thinking included) and tokens per second, each smoothed by half against the
  measurement before it. From them:
  `batchSize = clamp(floor(requestSeconds × tokensPerSecond ÷ tokensPerPair), 1, batchSize())`
  and `cap = ceil(tokensPerPair × batchSize × 1.5) + TOKENS_OVERHEAD`, both
  bounded by the context window as the batch planning bounds them.
  `requestSeconds` is DUPLICATES_AI_REQUEST_SECONDS, at least 5, 30 by
  default. A batch is now taken off the front of a queue rather than chunked
  up front, because its size changes while the review runs.
- The plan settles after the warm-up. `requestsPlanned` and `estimatedTokens`
  are re-derived from the pairs nobody has asked about yet and reported with
  `batchSize` and `calibrated: true`, so the page's denominator stops moving.
- Truncation: raise before halving. A cut-off answer that salvaged nothing is
  asked again with twice the cap (the warm-up gets the whole window at once),
  and only when that bought nothing — or the cap is already at the window's
  bound — is the batch halved as before. A warm-up that does not fit even then
  ends the review as failed with a message the operator can act on, naming
  DUPLICATES_AI_THINKING and TOKEN_LIMIT. A single pair at the bound keeps the
  old "unsure" and its log line.
- The cut-off text counts. All four providers now attach `error.partialText`,
  so the salvage path runs for every one of them; a salvaged request counts
  its verdicts in `pairsJudged` and in the tracker. Two comments that still
  said only Ollama returns half-written answers were rewritten.
- Progress inside a request. With a progress sink the provider is asked to
  stream (`onProgress`). Each report, at most every 250 ms, carries
  `requestPairs`, `requestAnswers` (the complete verdict objects counted off
  the streamed text), `requestTokens`, `thinking` and the running token total:
  "The model is thinking… (640 tokens so far)" while it thinks, otherwise the
  request line with " · 7 of 10 answers" appended. The report that counts the
  request resets all four. A review nobody watches sends the plain request it
  always sent.
- Calibration memory. The last measurement per model name lives on the
  singleton; a review that finds one starts sized from it, skips the warm-up
  and says so in the log. A measurement taken with thinking on is never reused
  with thinking off. `resetCalibration()` for tests.
- Logs: the finish line says "N pair(s) planned" (the number is the plan), the
  batch-size line is marked provisional until the model is measured, and the
  split line says whether the cap was raised or the batch halved.

services/duplicateMergeService.js

- `scan()` keeps its result per set of options (kind, threshold,
  includeDismissed) for SCAN_CACHE_MS (60 s) and answers the next identical
  request from it with one log line instead of the start and finish lines.
  `fresh: true` skips and refills it; the page's Scan button sends it.
- A merge, an undo, a dismissal and `restoreDismissal()` empty the cache. A
  dismissal deleted through the route, which talks to the model directly, is
  caught by a fingerprint (row count and highest id per kind) checked on every
  hit — one local SELECT against a 13-second scan.
- `reviewScan()` calls `scan()` without `fresh`, so a proposal made right
  after the page scanned costs no second scan.

Testing

- node scripts/run-tests.js --all: 93 passed, 7 skipped offline, 0 failed
  (100 registered), unchanged from the baseline.
- tests/test-entity-match-ai-service.js: 65 -> 80 cases. New: thinking off and
  on; the warm-up's size, cap, phase and message; the sizing math on a fixed
  usage and duration; the request seconds and their floor; the context window
  bounding size and cap; smoothing; the plan and estimate recomputed after the
  warm-up; calibration reused, not reused across the thinking switch, reset; a
  warm-up that cannot fit ending the review with its message; a truncated
  answer with partialText salvaged and counted; a streamed request reporting
  thinking, then answers, then clearing itself; an unwatched review not
  streaming; a review served from the page's scan.
- tests/test-duplicate-merge-service.js: 17 -> 22 cases. New: cache hit, other
  options and `fresh` missing it, expiry, invalidation by merge, undo, dismiss
  and restore, and a dismissal removed behind the service.
- Changed expectations, all from the raise-before-halve rule: the truncation
  cases now see every size asked twice (once, once with twice the cap) before
  it is halved, the single pair is asked twice before it ends as unsure, and
  the planning cases see the `warming-up` phase where they saw `judging`.
- Two demo runs against a fake model at 30 tokens/s: thinking off, 12 pairs —
  warm-up 4 pairs in 20 s (600 tokens, 150 per pair), then requests of 5 pairs
  at 25 s, 4500 tokens, 60 s in total. Thinking on — warm-up 4 pairs in 40 s
  (1200 tokens, 300 per pair) and requests of 2 pairs at 30.04 s, the
  configured length.

Impact

The first request of a review is seconds rather than minutes, every later one
lasts about as long as the operator asked, and the page shows the model
thinking and answering while it happens instead of a still bar. A review of a
model that was measured before starts at full size. Three scans of one archive
become one. Nothing runs on its own and no verdict changed: the prompt, the
rules and the shape of an answer are what they were.

Upstream Status

Not applicable — the Duplicates feature does not exist upstream.

* fix(duplicates): a review never asks for a fresh scan of its own

reviewScan() drops a `fresh` flag its caller may carry instead of passing it on, so a route that forwards the page's scan options cannot make the review scan the archive a second time.

* fix(duplicates): the yes/no switches of the judge read 'yes', and a small batch is not starved after a thinking one

Background
The browser smoke test of the round ran the thinking scenario and the
judge kept saying "thinking off" although DUPLICATES_AI_THINKING=yes
was set. config/config.js normalises every yes/no setting to the
strings 'yes' and 'no' (parseEnvBoolean), while three readers in the
judge asked Boolean() or === true: the thinking switch could never be
turned on, and the review and excerpt switches could not be turned off
('no' is a truthy string). The second finding: a thinking model pays a
fixed price per request, so a one-pair request sized by pairs alone
after a four-pair warm-up got a cap the same thoughts did not fit; the
judge recovered by raising the cap, at the cost of one request.

Changes
- services/entityMatchAiService.js: switchedOn() accepts 'yes' and a
  boolean true; isEnabled(), excerptsEnabled() and thinkingEnabled() use
  it. The cap never drops below the largest completion the model has
  produced in this review plus a quarter (CAP_FLOOR_FACTOR), and that
  floor is remembered with the calibration.
- tests/test-entity-match-ai-service.js: one case per finding (82
  cases), the sizing case expects the remembered floor.
- config/changelog.js: three entries for the round under the current
  release.

Testing
- node scripts/run-tests.js --test entity-match-ai-service: 82 passed.
- Browser smoke against a fake Paperless-ngx and a fake provider that
  streams, thinks on request and honours max_tokens: thinking off, the
  fake never thought, warm-up 4 pairs, 59 tokens/s measured; thinking
  on, the panel showed the thinking state, no request hit the token
  limit any more; Stop, re-attach, token budget and the round-6
  walkthrough unchanged.

Impact
DUPLICATES_AI_REVIEW=no and DUPLICATES_AI_EXCERPTS=no now do what they
say; DUPLICATES_AI_THINKING=yes now reaches the model.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): contract for the creation guard, the semantic sweep, unused objects, renames and a remembered calibration

Background
Round 9 of the Duplicates feature, six points the user picked: stop
the drift where it starts (document analysis creating "Rechnungen"
next to "Rechnung"), let the model find synonyms and translations the
string matcher cannot, list and delete unused objects with undo, name
the survivor of a merge, keep the judge's measurement of a model across
restarts, and scan faster. Decisions: only hard matcher tiers map a
new name onto an existing one (case, umlauts, legal form, plural, word
order), typo-like mat…
… judge that sizes around thinking, asks in lanes and remembers (#332)

* feat(duplicates): contract for a targeted AI review

Background
With many groups at 94 to 96 percent the user wants to say "everything
from 95 percent up: ask the AI, show me its view, then merge". The
review must therefore be able to judge only chosen groups and skip the
band of near-misses.

Changes
- schemas.js, OPENAPI/openapi.json: groupIds, minConfidence and
  includeCandidates on DuplicateAiReviewRequest.

Testing
- node scripts/regen-openapi.js: no drift after the commit.

Impact
Request fields only; the implementation follows.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): targeting counters in the AI review result schema

Background
A targeted review reports which groups it judged and which it left
without a verdict; the page shows that.

Changes
- schemas.js, OPENAPI/openapi.json: targeted, groupsJudged and
  groupsSkipped on DuplicateAiReviewResult.aiReview.

Testing
- node scripts/regen-openapi.js: no drift after the commit.

Impact
Documentation of three informational fields.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): let the AI review be pointed at a few groups

Background

An archive with hundreds of correspondents produces dozens of groups at
94, 95 and 96 per cent, and asking the model about all of them costs a
lot to answer a question about a handful. The page needs to select the
groups it is about to merge, ask about those, and keep rendering the
rest of the scan while it does.

Changes

- entityMatchAiService.reviewScan() takes three options that narrow what
  is asked, never what comes back:
  - groupIds: only these scan groups are judged. Every other group is
    still in `groups`, as the scan produced it, with `aiVerdict: null` on
    the group and on every member and `source: 'scan'`. An id this scan
    does not know is ignored and logged once with the count.
  - minConfidence: only groups scoring at least this much are judged;
    together with groupIds both conditions have to hold.
  - includeCandidates (default true): false leaves the band of
    near-misses out entirely, so `candidates` is 0 — and with no band
    the entity list per kind is not read either, which is the cheap part.
- _pairsForKind() takes the set of group ids to judge. A group left out
  contributes no pairs but its member pairs still count as "inside one
  group", so it cannot reappear as a candidate.
- The result reports the targeting: aiReview.targeted, .groupsJudged and
  .groupsSkipped. The start line of the log names it as
  "judging 1 of 4 group(s) (min confidence 0.95, 3 ids), band skipped",
  the closing line adds the two counters. An untargeted review logs and
  behaves exactly as before.
- POST /api/duplicates/ai-review validates and passes the three fields
  through: groupIds an array of at most 500 non-empty strings,
  minConfidence a number in [0.5, 1], includeCandidates a real boolean
  (the string "false" is a 400). An option the request does not mention
  is left out of the service call, so an untargeted request reaches
  reviewScan() with the same object it did before.
- Swagger description of the route and the 400 reason updated,
  OPENAPI/openapi.json regenerated.

Testing

- node scripts/run-tests.js --all -> 90 passed, 7 skipped offline,
  0 failed (97 registered), unchanged against the baseline.
- entity-match-ai-service: 28 -> 34 cases. Six new ones on a fixture
  whose four groups sit exactly on the matcher tiers (1, 0.98, 0.95,
  0.9) plus one pair in the band: groupIds judges only what it names,
  minConfidence filters, includeCandidates: false skips the band and
  reads no second entity list, groupIds and minConfidence combine while
  unknown ids are ignored, an empty selection costs no request, and the
  log lines. The existing aiReview assertion gained the three new fields.
- duplicates-endpoints: 16 -> 19 cases. The three fields reach the
  stubbed reviewScan unchanged, an untargeted request still carries
  nothing extra, ten malformed targeting bodies are 400, and 500 ids are
  accepted while 501 are not.
- Manual run against the real route with a fake store and a fake
  provider: full review 5 pairs / 1 request, minConfidence 0.95 without
  the band 3 pairs, two selected ids (one unknown) 1 pair, and every
  unjudged group back with null verdicts.
- eslint, prettier and the OpenAPI drift check clean on the touched
  files.

Impact

Additive. A review that says nothing about the three options behaves and
logs as before. The page can ask about the groups it selected before a
batch merge; a dozen groups without the band are one or two model
requests instead of the whole archive. schemas.js still has to gain
targeted, groupsJudged and groupsSkipped on DuplicateAiReviewResult.

Upstream Status

Not applicable: the Duplicates feature is next-only.

* feat(duplicates): sort, select by confidence, and a guided review before merging

Background
----------
On a grown archive a scan answers with dozens of groups that all read 94, 95,
96 percent, and the page offered no way to act on that number: every group had
to be judged by eye, one tick at a time. The three presets were the only
thresholds available, so "everything above 95" was not a question the page
could be asked. And where the AI review existed it judged the whole result
list, which is the most expensive way to ask about the five groups the user
actually cares about.

The rule this follows: the AI is an addition, never a condition. Every flow
below works end to end with the review switched off; with it on, the guided
path is one more button beside the one that was already there.

Changes
-------
Results toolbar (#dupResultsBar), above the selection bar, shown once a scan
has groups:
  - "Sort by" (#dupSortSelect): confidence, documents, target name (locale
    compare), kind then confidence. It moves the DOM nodes instead of
    re-rendering, so a card keeps its target, its source ticks, its selection,
    its verdict and its busy state; the two blocks (scan groups, AI
    candidates) are sorted separately and the divider stays between them.
  - "Select >=" (#dupMinConfidence, #dupSelectMinBtn, #dupMinConfidenceCount):
    ticks every selectable group at or above a whole percent and unticks the
    rest, with a live count of what the click would do.
Custom scan threshold: a fourth sensitivity option "Custom" reveals a number
field (#dupThresholdCustom); the scan and both review paths send that percent
divided by 100. The three presets are unchanged.
Confidence breakdown under "Groups found" (#dupStatBuckets): ">=95 %: A .
90-95 %: B . <90 %: C", counted from the cards after a scan and after a review.
Guided flow (#dupReviewThenMergeBtn, rendered only where the review exists):
asks the model about exactly the ticked groups (groupIds, includeCandidates:
false), puts the verdicts on the cards as a full review does, then shows them
once in a wide dialog - one row per group with target, sources, documents, the
verdict chip and the reason, a live "N of M ticked . K documents" foot line and
the copy-rule check. Ticked rows are merged with the batch machinery; an unsure
or different verdict only comes up unticked and never blocks anything, and what
stays unticked stays selected on the page.
"Merge selected" keeps its place and its weight, first in the bar and without a
model anywhere in its path; its dialog names the guided path in one faint line,
and only where that path exists.
Sort, confidence, sensitivity and the custom threshold are remembered in
localStorage (dup.sort, dup.minConfidence, dup.sensitivity,
dup.thresholdCustom) through two try/catch helpers.

Testing
-------
node scripts/run-tests.js --all -> 90 passed, 7 skipped offline, 0 failed
  (unchanged from the branch baseline).
tests/test-duplicates-ui.js: 25 -> 38 cases. New: the toolbar ids and their
  order, the custom threshold field, the stats breakdown, the guided button
  only with the review, the whole page without the review, the toolbar ids in
  the script, sorting as a DOM move, "Select >=", the wrapped localStorage
  access, the guided request (groupIds / includeCandidates: false) and that
  "Merge selected" never touches the review endpoint, the review dialog markup,
  the tip line, the new CSS classes. Changed: the sensitivity options are read
  from #dupSensitivity alone and now end in "custom"; the undo promise and the
  confirm dialogs are counted one higher each, because the review dialog merges
  and therefore makes the same promise.
Reviewed in a browser against a throwaway mock (twelve groups over 88-100 %, a
  review that honours groupIds): 27 screenshots at 1280x900 and 390x844, light
  and dark, 0 px horizontal overflow everywhere, plus a 31-check behaviour
  probe (guided request, verdict ticks, sorting keeping picks and the divider,
  persistence, a refused review, and the whole page with the review off).

Impact
------
Page only. No route, service, schema or config was touched, so the OpenAPI
spec is unchanged. An instance without the AI review renders and behaves
exactly as before plus the toolbar and the custom threshold. The request the
guided path sends uses fields the contract already carries; a server that
ignores them reviews everything, which the page renders correctly.

Upstream Status
---------------
Not applicable - the Duplicates page does not exist upstream.

Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* docs(duplicates): changelog entries for sorting, select by confidence and the guided review

Background
Round 5 answered the second feedback from a real archive: select by a
number, let the model judge exactly those groups, read its verdicts in
one dialog, merge what stays ticked; sort the groups; a custom threshold.

Changes
- config/changelog.js: two entries in the current v2026.09.01 block.

Testing
- node scripts/run-tests.js --test changelog-releases: passed.

Impact
Documentation only.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): contract for evidence-based verdicts and the AI proposal

Background
A real archive produced "Kontoauszug" / "Kontoumzug": the matcher called
it a spelling distance, the prompt allowed "an obvious typo" as a reason
for same, and the model, seeing names and titles only, agreed. Both are
different things. The judge needs stricter rules and, for pairs linked by
spelling alone, a look at what the documents are about, at a bounded
cost.

Changes
- config/config.js: DUPLICATES_AI_EXCERPTS (default yes),
  DUPLICATES_AI_EXCERPT_CHARS (300), DUPLICATES_AI_EXCERPT_DOCUMENTS (2).
- schemas.js, OPENAPI/openapi.json: AiVerdict gains basis and confidence;
  DuplicateAiReviewRequest gains withExcerpts; aiReview reports excerpts.

Testing
- node scripts/run-tests.js --area duplicates: 6/6; regen without drift.

Impact
Settings and schema only; the implementation follows.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): judge model override and the verdict source in the contract

Background
Decisions for round 6: the matcher's hard tiers settle a pair without the
model, unsure pairs are asked once more with excerpts, and the judge may
run on a stronger model of the same provider.

Changes
- config/config.js: DUPLICATES_AI_MODEL (optional, judge only).
- schemas.js, OPENAPI/openapi.json: AiVerdict.source (model or
  spelling-rule); aiReview.escalated and aiReview.spellingRules.

Testing
- eslint and prettier on the two files; regen without drift.

Impact
Settings and schema only; the implementation follows.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(settings): make every DUPLICATES_ setting editable in its own section

Background
The AI review of the Duplicates page arrived with seven environment
variables and no way to change any of them from the interface. Editing a
container environment and recreating the container is the wrong price for
"try a stronger model for the judge" or "ask about fewer pairs per
request", and the settings page is exactly where those knobs belong.
config/config.js already reads all seven; only the front door was missing.

Changes
- views/settings.ejs: a "Duplicates" section (id="sec-duplicates") inside a
  new duplicates-tab block between the AI sections and OCR, with a nav entry
  in the desktop section nav (icon i-merge) and in the mobile one, in the
  same order as the page. Seven fields, each with a hint that says what the
  value does and what its default is: the AI review switch, the judge model,
  pairs per request, the candidate floor, the excerpt switch, excerpt length
  and documents per entry. Switches go through partials/settings-switch, so
  the hidden yes/no input the POST route reads exists as it does everywhere
  else.
- routes/setup.js: GET /settings passes the seven values (env first, the
  defaults of config/config.js as fallback) in the config object the view
  reads; POST /settings destructures the seven camelCase body keys,
  normalises them and writes them into updatedConfig, so setupService
  .saveConfig persists them with the rest. Numbers are clamped to their
  range; a value that is not a number, or a cleared field, keeps what is
  configured now instead of resetting to the default. The swagger body
  schema documents all seven, and the .env export gained a "Duplicates"
  group between "AI behaviour" and "External API".
- public/js/settings.js: the seven selector to env-key entries, so the
  "Overwritten" and "Managed by ENV" marking covers these fields too.
- OPENAPI/openapi.json regenerated.
- tests/test-settings-duplicates-section.js, registered in the
  observability area.

Testing
- node scripts/run-tests.js --all: 98 registered, 91 passed, 7 skipped
  offline (was 97/90/7). The new test covers the rendered section and its
  nav position, the seven inputs and their values, the POST round trip,
  clamping, the keep-the-previous-value case and the .env export group.
- npx eslint / npx prettier --check --ignore-unknown on every touched file.
- node scripts/regen-openapi.js leaves OPENAPI/openapi.json unchanged.
- Looked at the page in Chromium at 1440x1000 and 390x844 against a
  throwaway server outside the repository; no console errors, the section
  reads like the rest of the page and stacks on the phone.

Impact
Operators can change every DUPLICATES_ value from the settings page. The
existing restart-after-save is what makes them take effect; no new
mechanism. Values injected by the container still win and are shown as
managed, as for every other field. Nothing outside the settings page
changes: no route, service or default behaviour of the Duplicates page
itself is touched.

Upstream Status
Fork-only. The Duplicates page does not exist upstream.

Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): judge spelling-only pairs on evidence, not on distance

Background
A real archive produced "Kontoauszug" next to "Kontoumzug": the matcher
called it a spelling distance, the prompt allowed "an obvious typo" as a
reason for same, and the model, seeing two names and three titles, agreed.
Two different things. The judge needed stricter rules, evidence for the
pairs where spelling is the only link, and a way to say how sure it is and
on what grounds — all without opening a large context window on every pair.

Changes
- entityMatchAiService: the system prompt refuses a small spelling distance
  as a reason of its own ("Kontoauszug" / "Kontoumzug", "Miete" / "Mieter",
  "Bahn" / "Bank"), allows a misspelling only when one spelling is not a
  word, and answers unsure when it cannot tell. The output contract gains
  "basis" (a closed list) and "confidence" (high | low); both are parsed,
  an unknown value becomes null, and every verdict, member verdict and
  aggregate carries them. An aggregate keeps the deciding member's basis
  and takes "low" as soon as one deciding member is low.
- Evidence, graded by what the link is worth: every pair carries matched_by
  and score; every judged entity carries its titles, its matching rule and
  its neighbourhood ("filed_with": the correspondents of a tag's documents,
  the tags of a correspondent's); only the pairs linked by fuzzy, prefix or
  token-order also carry document excerpts. Excerpts are read once per
  entity per review and never for a strong tier. withExcerpts: false or
  DUPLICATES_AI_EXCERPTS=no reads nothing at all.
- A member pair a matcher rule settles (exact-normalized, umlaut-variant,
  legal-form) never reaches the provider: it gets verdict same with
  source: spelling-rule, counts in aiReview.spellingRules and costs no
  request, no read and no token.
- A pair the model calls unsure and that had no excerpts is asked once more
  with them; the second answer replaces the first (aiReview.escalated).
- paperlessService: getRecentDocumentExcerptsByEntity (one read,
  truncate_content, cut to the configured characters at a word boundary)
  and getEntityNeighbourhood (one read, the most frequent neighbour names
  through the existing caches). Both answer [] on any error and never log
  document content.
- The judge may run on its own model (DUPLICATES_AI_MODEL): generateText
  takes an optional model in all four provider services, shared through
  aiGenerateOptions.modelOverride.
- Logs: the per-kind start line names the evidence and the model, the
  request line the pairs with excerpts, the escalation its own line.
- Route POST /api/duplicates/ai-review parses withExcerpts like withTitles;
  swagger description updated and OPENAPI/openapi.json regenerated.

Testing
- node scripts/run-tests.js --all: 97 registered, 90 pass, 7 skip offline.
- tests/test-entity-match-ai-service.js: 35 -> 50 cases (the stricter
  prompt, basis and confidence parsing, excerpts only for spelling-only
  pairs and once per entity, the two switches, the configured cut, the
  Kontoauszug regression, settled pairs, the neighbourhood, escalation, the
  model override, batch sizing with excerpts, and both new client methods).
- tests/test-duplicates-endpoints.js: one case for withExcerpts; the three
  existing option assertions now expect withExcerpts: true.
- Demo run against the fake Paperless-ngx: the Kontoauszug/Kontoumzug pair
  costs 282 prompt tokens with excerpts, a strong pair without excerpts 75.
- eslint, prettier and a regen without drift on every file touched.

Impact
An AI review asks about fewer pairs and knows more about the ones it asks
about. Nothing runs on its own, nothing is merged, and document content
never reaches a log line.

Upstream Status
Not applicable — the Duplicates feature does not exist upstream.

* fix(duplicates): do not escalate an unsure pair whose documents carry no text

* feat(duplicates): one click for the AI's proposal, with the evidence behind it

Background
----------
Everything the page offered so far started from the user: scan, read every
card, tick, merge — and where the AI review existed it was a second question
asked after the first. What was missing is the path the archive's owner
actually wants for a first clean-up: one click that scans, has every group and
every near-miss judged, and then hands over a proposal to thin out rather than
a list to work through.

The rule this follows is the same as in the rounds before: the AI is an
addition, never a condition. Without the review nothing of this renders, and
"Scan Paperless-ngx", "Merge selected", the toolbar, the manual merge and the
guided path are the same as they were.

A verdict also had to say more than "same": with `basis`, `confidence` and a
`source` on the wire, the page can pre-tick exactly what is settled — a pair a
spelling rule decided, or one the model says it is sure about — and leave
everything else to the user. The member tables, finally, measured their own
content per card, so the columns of two cards below each other sat in
different places.

Changes
-------
"AI proposal" (#dupAiProposalBtn, primary, rendered only with aiReviewEnabled)
next to "Ask the AI", usable from the first paint because it scans itself:
  - status in the AI row (#dupAiProposalStatus): "Scanning…", then "Asking the
    AI about N pairs and near-misses…", with the hint line under the row
    (#dupAiProposalHint) saying what the click does;
  - it reuses runScan() (now awaited) with the kind, sensitivity and hidden-pair
    settings on the page, then the one review request with includeCandidates
    and no groupIds. Two requests, and no merge until the dialog is confirmed.
Proposal dialog (.dup-proposal-dialog): one row per group that could be merged,
  sorted same/high, same, unsure, different, unjudged (proposalRank,
  compareProposalEntries — both pure); pre-ticked are only the settled ones
  (isSureSame: verdict "same" with confidence "high", which covers the
  spelling-rule verdicts); legend, "Tick all same" (#dupProposalTickSame),
  "Untick all" (#dupProposalUntickAll), the copy-rule check (#dupCopyRuleAll)
  and a live foot line "N of M ticked · K documents · X objects will be
  deleted". Confirming sets the page selection to the ticked groups and hands
  them to the batch runner of round 4, so the selection bar reports the merge
  as it does for "Merge selected"; cancelling leaves the verdicts on the cards
  and nothing ticked.
Evidence, shared by both dialogs (one row renderer, one table):
  - a "Basis" column as a .zr-badge with a label per contract value;
  - the confidence as a suffix of the verdict chip ("AI: same · high");
  - a pair a spelling rule settled reads "Spelling rule" in the "same" tone
    (.dup-verdict--rule) instead of quoting a model that never saw it;
  - the guided dialog pre-ticks by the same rule, so a "same" the model is
    unsure about now comes up unticked there too.
Cards keep their shape: the verdict chip carries the basis in its title and the
  confidence as its suffix, no new column.
Second checkbox "Use document excerpts for spelling-only pairs"
  (#dupAiExcerpts, checked); withTitles and withExcerpts flow into every review
  request from the one place that builds it. The titles checkbox is relabelled
  "Use document titles and neighbours as context".
"AI-judged pairs" tile: its sub line now also counts "· E excerpts", "· S by
  spelling rule" and "· E escalated" when the review reports them.
Member tables line up across cards: .dup-members is table-layout: fixed with
  the name column taking what is left and truncating, and the matching rule a
  fixed share (.dup-members__name, .dup-members__rule).

Testing
-------
node scripts/run-tests.js --all -> 90 passed, 7 skipped offline, 0 failed
  (unchanged from the branch baseline of 97 registered).
tests/test-duplicates-ui.js: 38 -> 48 cases. New: the proposal ids and labels
  only with the review and the page whole without them; what the flow sends
  (runScan first, includeCandidates: true, no groupIds, both evidence flags,
  no request of its own); the pre-tick rule, evaluated as a function against
  seven verdicts; the row order, evaluated by sorting a shuffled list; a label
  for every basis the AiVerdict schema lists, parsed out of schemas.js; the
  spelling-rule chip; the dialog's parts and that it merges through the batch
  runner; the evidence counters of the stats tile; the fixed member-table
  layout; the new CSS classes. Changed: the titles checkbox label, the undo
  promise and the confirm dialogs counted one higher each (the proposal merges
  and therefore makes the same promise), and the pre-tick assertion of the
  guided row.
Reviewed in a browser against a throwaway mock (eleven scan groups plus three
  the model proposes, verdicts across same/high, same/low, unsure and
  different, some settled by a spelling rule, and a Kontoauszug / Kontoumzug
  pair that only the excerpts decide): 31 screenshots at 1280x900 and 390x844,
  light and dark — the controls, the status line mid-flow, the proposal dialog,
  after "Untick all", mid-merge, after the merge, the guided dialog, the stats
  tile, the aligned member tables and the render without the review. 0 px
  horizontal overflow everywhere; the column offsets of all eleven cards are
  identical.

Impact
------
Page only. No route, service, schema or config was touched, so the OpenAPI
spec is unchanged. An instance without the AI review renders and behaves
exactly as before. The new request field and the new verdict fields are ones
the contract already carries: a server that ignores withExcerpts reviews as it
did, and a verdict without basis, confidence or source renders as it did — it
then simply never comes up pre-ticked, which is the safe side.

Upstream Status
---------------
Not applicable - the Duplicates page does not exist upstream.

Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* chore(duplicates): changelog for the AI proposal round, room for the verdict in the Match column

Background
The sixth round of the Duplicates feature adds the AI-led proposal, the
evidence-based judge and the Duplicates settings section. The member
tables now use a fixed column layout so the columns line up across
cards, which left the Match column too narrow for a verdict such as
"AI: same - high": it wrapped into four lines.

Changes
- config/changelog.js: five entries for the round under the current
  release (AI proposal, evidence-based judge with excerpts and
  DUPLICATES_AI_EXCERPT*, DUPLICATES_AI_MODEL, aligned member tables,
  the Duplicates settings section).
- public/css/pages/duplicates.css: the Match column is 132px wide and
  the member verdict does not wrap, so the percentage and the verdict
  take one line each.

Testing
- npx eslint, prettier --check and stylelint on every file changed
  against nightly: clean.
- node scripts/run-tests.js --all: 91 passed, 7 skipped (server or
  credentials needed), 0 failed.
- node scripts/regen-openapi.js: no drift.
- Browser walkthrough against a fake Paperless-ngx and a fake judge:
  scan, merge, undo, dismiss, merge by hand, batch merge, guided review,
  AI proposal and AI review all pass. The Kontoauszug/Kontoumzug pair is
  judged "different" on its excerpts and does not appear in the
  proposal.

Impact
Visual only for the CSS; the changelog is shown in the What's New
dialog.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): contract for a watchable, stoppable AI review

Background
An AI review of a large archive is many model requests in a row. Today
it is one POST that answers when everything is done: nothing shows
while it runs, nothing can stop it, and the tokens it spends are
invisible until the end. The user wants to see what is happening, how
far it is and what it costs, and to stop it at any time. Decisions for
this round: the review runs as a server-side job the page can watch
and stop; a review nobody watches stops itself; a token budget per
review stops it on its own; a stopped review keeps the verdicts it
reached and opens no dialog; the progress lives in the AI row of the
Duplicates page.

Changes
- services/duplicateReviewJobService.js (new): the one review job at
  a time. start(), current(), get(), stop(id, reason), subscribe() for
  a server-sent stream (a late subscriber first gets the job as it is
  now), touch(), wait(), result(), toJSON(). The judge receives a
  control object (signal, onProgress, stop, tokenBudget); a partial
  result of a stopped review is kept like a complete one. The idle
  watch stops a job nobody has watched for the configured seconds. A
  finished job stays reachable for ten minutes.
- config/config.js: DUPLICATES_AI_TOKEN_BUDGET (200000, 0 = no limit)
  and DUPLICATES_AI_IDLE_STOP_SECONDS (60, 0 = never).
- schemas.js, OPENAPI/openapi.json: AiReviewProgress, AiReviewJob,
  AiReviewJobEvent; aiReview gains stopped, stopReason and
  pairsNotJudged.
- scripts/run-tests.js, tests/test-duplicate-review-job.js: the
  contract test of the job (9 cases) in the duplicates area.

Testing
- node scripts/run-tests.js --all: 99 registered, 92 pass, 7 skip
  offline, 0 fail.
- eslint and prettier on every touched file; regen without drift.

Impact
Nothing uses the job yet; the judge ignores the control object until
the implementation follows. No route or page changes.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): make the token budget and the idle stop editable in settings

Background
The two brakes of a running AI review landed as environment variables only:
DUPLICATES_AI_TOKEN_BUDGET caps what one review may spend across all its
requests, DUPLICATES_AI_IDLE_STOP_SECONDS ends a review no page has been
watching, so a closed tab cannot leave the model running. Both are exactly
the kind of setting somebody wants to try out once and then adjust, which
means editing a compose file and restarting the container for every attempt.
The other seven DUPLICATES_* variables already have a field in the Duplicates
section of the settings page; these two did not.

Changes
- views/settings.ejs: two number fields at the end of #sec-duplicates, in the
  style of the five above them — duplicatesAiTokenBudget (0-10000000, step
  1000) and duplicatesAiIdleStopSeconds (0-3600). Each hint says what the
  value does, what zero means and what the default is.
- routes/setup.js: GET /settings passes DUPLICATES_AI_TOKEN_BUDGET and
  DUPLICATES_AI_IDLE_STOP_SECONDS to the view with the defaults of
  config/config.js as the fallback; POST /settings destructures both body
  keys, clamps them to their ranges and keeps the currently configured value
  for an empty or non-numeric field, the rule the round-6 fields follow. Zero
  is a value for both and survives the clamp, because the ranges start there
  rather than at one. The @swagger body schema documents both, and the
  Duplicates group of ENV_EXPORT_GROUPS lists them after the existing keys.
- public/js/settings.js: two entries in the field mapping, so an
  operator-injected value greys the field out and carries the "Managed by ENV"
  pill like every other setting.
- OPENAPI/openapi.json regenerated.

Testing
- tests/test-settings-duplicates-section.js grew from 7 to 11 cases: the two
  fields render with their configured values, ranges and hints and close the
  section in that order; every field of the section is paired with its
  environment key in settings.js; the POST round trip persists all nine
  values; a budget of 99999999 is capped at 10000000 and an idle stop of -5
  lands on 0; zero survives for both, because it means "no limit" and "never"
  rather than an unset field; a fractional value is rounded; a cleared or
  unparsable field keeps what was stored before; the .env export carries all
  nine keys with the two brakes last.
- node scripts/run-tests.js --all: 99 registered, 92 passed, 7 skipped
  offline, 0 failed — the same numbers as before this change.
- eslint and prettier clean on every file touched; regen-openapi.js leaves no
  drift.
- Looked at the section in Chromium at 1440x1000 and 390x844 against a
  throwaway server outside the repository: both fields render like the seven
  above them, no console errors, and with the two keys in the locked-env set
  both are disabled and carry the "Managed by ENV" pill while a neighbouring
  field stays editable.

Impact
No behaviour change for anybody who never opens the section: the defaults are
unchanged (200000 tokens, 60 seconds) and nothing new runs. Operators who set
either variable in their container environment keep winning — the field is
shown greyed out rather than silently overwritten. A saved value needs a
restart to take effect, as the hints say, because config/config.js reads the
environment once at load.

Upstream Status
Not applicable — the Duplicates page is specific to this fork.

* feat(ai): let every provider take an abort signal for one call

aiGenerateOptions gains abortSignal(options); the four provider
services pass it on where their client expects it — the OpenAI SDK as
the second argument of create(body, { signal }) for OpenAI, Azure and
the custom endpoint, axios as { signal } in the request config for
Ollama. Without a signal every provider sends exactly what it sent
before: no second argument at all, and the unchanged axios config.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): the AI review reports, stops and counts its tokens

Background
"Während die AI befragt wird, könnten Millionen von Tokens im
Hintergrund verbraten werden, ohne dass man es sieht. Man muss es auch
abbrechen können." The judge answered when it was done and said
nothing while it worked, so the page had nothing to show and nothing
to stop. The job of the previous round hands it a control object; this
round makes the judge use it. A bar needs a denominator before the
first request, which the old per-kind loop could not give: it read the
archive, asked, and only then looked at the next kind.

Changes
- services/entityMatchAiService.js: reviewScan(options, control = {})
  runs in two passes. Pass one, for every kind of the review: read the
  entities and the band, build the pairs, settle the spelling-rule
  pairs, gather titles, neighbourhood and excerpts, and size the
  batches. Pass two judges kind after kind. Nothing is asked before
  the whole plan exists.
- Progress: phase scanning before the scan, phase evidence per kind
  and per read, one phase judging with requestsPlanned, pairsTotal and
  estimatedTokens for the whole review, one report per answered
  request (requestsDone, pairsJudged, the running token total,
  failedRequests, retries, kind, and the line naming the next
  request), phase escalating when an unsure pair is asked again, phase
  finishing before the groups are built. A split answer adds its
  halves to requestsPlanned in the report of the request that split,
  so the bar never goes backwards; the escalation adds its own
  requests and pairs the same way. Elapsed time and the estimate stay
  with the job, which derives them.
- Stopping: control.signal is read before every read, every request
  and the second round, and travels to the provider, so a stop lands
  on a request in flight. A request that dies on the signal is a stop,
  not a failure: no failed request, no retry, and no "unsure" — the
  pairs stay without a verdict, so they cannot become a group. A
  stopped review returns what it reached; it never throws.
  aiReview now always carries stopped, stopReason (null; the job fills
  it in) and pairsNotJudged.
- Token budget: one running total for the whole review, folded from
  the provider's usage or, for a provider that reports none, from the
  measured prompt plus the estimated answer, so the counter and the
  budget work for every provider (aiReview.tokens keeps reporting only
  what a provider stood behind). When control.tokenBudget is reached
  the review calls control.stop('token-budget') and behaves as
  stopped.
- Logs: "review stopped (user|token-budget|idle): N of M request(s)
  made, P pair(s) not judged, T token(s)." and "token budget 200000
  reached after N request(s) (T tokens)."; the start, request and
  finish lines are unchanged.
- services/duplicateReviewJobService.js: the control object gains
  stopReason(), the one seam the judge needs to name the reason in its
  own log line.
- reviewPairs(pairs, options) additionally takes plan, systemPrompt
  and tracker from reviewScan; a caller that brings none gets what it
  always got.

Testing
- node scripts/run-tests.js --all: 99 registered, 92 pass, 7 skip
  offline, 0 fail (the baseline of the branch).
- tests/test-entity-match-ai-service.js: 13 new cases (64 total) —
  the plan before the first request for one and for two kinds, the
  split and the escalation raising the plan, a failed request still
  moving the bar, a stop between requests and a stop in flight, the
  token budget, a provider without usage, an already aborted signal, a
  review without a control, the report carrying nothing the job
  derives, and the signal reaching all four providers. The one moved
  expectation is the deep-equal on aiReview, which now names the three
  new fields.
- tests/test-duplicate-review-job.js: one case for stopReason().
- A real run through the job service over a fake archive: a review
  that runs through, the same one stopped after request 2, and the
  same one against a token budget.
- eslint and prettier on every touched file.

Impact
The page can show a bar with a denominator, an estimate and a running
token count from the first request, and a stop costs at most one
request that is already in flight. A review without a control object
behaves exactly as before, so the synchronous route is untouched until
it is moved onto the job.

Upstream Status
Not applicable: the Duplicates page and its AI review do not exist
upstream.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): watch and stop the AI review from the page

Background

A review of a drifted archive is many model requests in a row. Until now
"Ask the AI" was one POST that answered when everything was over: a spinner,
no idea how many requests were still coming, no idea what it cost, and no way
out but reloading the tab — which left the model running. The job service of
the contract commit made the review watchable and stoppable on the server;
this wires the routes and the page onto it.

Changes

routes/setup.js (Duplicates block only)
- parseAiReviewRequest(body) holds the validation both entry points share, so
  the synchronous route and the job route can no longer drift apart.
- POST /api/duplicates/ai-review/jobs starts a review and answers
  202 { job }; while one runs it answers 409 with that running job, so a
  second tab attaches instead of failing.
- GET /api/duplicates/ai-review/jobs/current answers { job } or { job: null }
  and counts as watching the review.
- GET /api/duplicates/ai-review/jobs/:id answers { job, result }, 404 for an
  unknown id, and also counts as watching.
- GET /api/duplicates/ai-review/jobs/:id/events streams AiReviewJobEvents
  (text/event-stream, no-cache, X-Accel-Buffering: no, keep-alive, flush after
  every write), a ": keep-alive" comment every 15 s, and ends after done,
  stopped or failed. An unknown id is a JSON 404 before any stream header.
- POST /api/duplicates/ai-review/jobs/:id/stop answers { job }; stopping a
  finished review is a 200 no-op.
- POST /api/duplicates/ai-review now starts that same job and waits for it: a
  stopped review answers 200 with the verdicts it reached, a failed one keeps
  the judge's status, and a second request while one runs is a 409. It
  subscribes for the duration so the idle stop cannot end a review somebody is
  waiting for.
- @swagger for every new route; OPENAPI/openapi.json regenerated.

views/duplicates.ejs, public/js/duplicates.js, public/css/pages/duplicates.css
- A progress panel in the AI row (#dupAiProgress): bar (#dupAiProgressFill,
  indeterminate while the plan is unknown), message, counters
  ("Request 3 of 8 · 40 of 96 pairs · 12.4k of 200k tokens"), time
  ("about 40 s left · 1:24 elapsed") and a Stop button (#dupAiStopBtn). After
  the end it keeps one outcome line and hides on the next scan or review.
- askForVerdicts() starts the job, follows it through EventSource and falls
  back to polling the job every 2 s when the stream breaks. It resolves
  { aiReview, stopped }; all three AI paths honour `stopped` — the notice is
  shown and neither the guided dialog nor the proposal opens.
- On load the page asks for the current job and re-attaches to one that is
  still running; a finished one is left alone.
- Pure helpers formatTokens, formatEta, formatElapsed, progressPercent and
  stopNotice word the numbers; the UI test evaluates them directly.

Testing

- node scripts/run-tests.js --all: 99 registered, 92 pass, 7 skip offline
  (unchanged); duplicates-endpoints 20 -> 30 cases, duplicates-ui 48 -> 57.
- eslint, prettier, stylelint clean on every touched file; regen-openapi
  leaves no diff.
- Reviewed in a browser against a throwaway server with a judge that reports
  eight requests: mid-run, stopping, stopped and done, desktop and phone,
  light and dark, no console errors. A page loaded while a review runs
  re-attached and rendered its result; with the event stream blocked the same
  review came home through eight polls.

Impact

The Duplicates page shows what a review is doing and costing and can end it;
the verdicts already reached are kept. The synchronous route keeps its request
and response, so an API client sees no change beyond the new 409 while a
review runs.

Upstream Status

Not applicable — the Duplicates feature does not exist upstream.

* fix(duplicates): a late Stop answer no longer paints over the outcome; changelog for the review job

Background
In the browser smoke test of the round, a stop pressed after the first
answered request ended the job before the stop request itself answered.
The page then rendered that answer, a snapshot from the stopping moment,
over the outcome line and restarted the elapsed clock, so the panel read
"Stopping after the current request…" next to a finished review.

Changes
- public/js/duplicates.js: stopReview() renders the stop answer only
  while the same job is still followed and still live.
- tests/test-duplicates-ui.js: one case that pins the guard (57 -> 58).
- config/changelog.js: three entries for the round under the current
  release (the review as a job with progress and Stop, the token budget
  and the idle stop as settings, the plan before the first request).

Testing
- node scripts/run-tests.js --test duplicates-ui: 58 passed.
- Browser smoke against a fake Paperless-ngx and a slowed-down fake
  provider: Stop during request 2 leaves "Stopped after 1 of 5 requests
  · 1 of 5 pairs judged · 1.1k tokens" on the panel, the verdicts
  reached stay on the cards, no dialog opens; the proposal path stops
  the same way; a token budget of 2500 stops the review after 3
  requests with the budget named in the notice and the log; a page
  reloaded during a review re-attaches and renders the result; the
  round-6 walkthrough (scan, merge, undo, dismiss, merge by hand, batch,
  guided review, proposal, plain review) passes unchanged.
- eslint and prettier on the touched files.

Impact
Visual only; the review itself was stopped correctly before the fix.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): contract for a judge that measures the model, streams its answers and thinks only on request

Background
On a real archive with a hosted Qwen model the first review request
asked about 25 pairs, ran for 103 seconds and died at its own answer
cap: the model spent the whole budget thinking before the first
verdict, the cut-off text was thrown away, and the page showed nothing
but a ticking clock for two minutes. Three scans of 13 seconds each
came before that. Decisions for this round: the judge measures the
model on a small first request and sizes every later request to a
target duration; the providers stream the answer so the page moves
inside a request and a cut-off answer keeps its verdicts; thinking is
off for the judge unless the operator switches it on; the review
reuses a fresh scan instead of scanning again.

Changes
- config/config.js: DUPLICATES_AI_THINKING (no) and
  DUPLICATES_AI_REQUEST_SECONDS (30).
- schemas.js, OPENAPI/openapi.json: AiReviewProgress gains
  requestPairs, requestAnswers, requestTokens, thinking, batchSize and
  calibrated; the phase list gains warming-up.
- services/duplicateReviewJobService.js: the new progress fields, the
  warming-up phase, and a time estimate from the share of pairs done
  (answers streamed in count), because the batch size may change after
  the warm-up.
- services/aiGenerateOptions.js: reasoningEnabled(options) and
  progressHandler(options), the two switches the judge will send and
  the providers will read, with the GenerateTextProgress shape and the
  partialText rule for cut-off answers.
- scripts/run-tests.js, tests/test-ai-provider-streaming.js: a
  registered placeholder for the provider streaming test.

Testing
- node scripts/run-tests.js --all: 100 registered, 93 pass, 7 skip
  offline, 0 fail.
- eslint and prettier on every touched file; regen without drift.

Impact
Nothing reads the new switches yet; the implementation follows.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* test(helpers): fake OpenAI-compatible and Ollama servers on ephemeral ports

* feat(providers): stream the answer, report progress, keep the cut-off text

Background

A hosted model behind the custom provider spent 103 seconds and the whole
3200-token completion cap on one AI-review request, then threw "the answer hit
a token limit" and dropped every character it had produced. Nothing was visible
while it ran, nothing survived the throw, and the batch was split and paid for
again from the beginning. Two causes: the four provider services always sent a
non-streaming request, so there was nothing to watch; and
assertCompletionNotTruncated() threw before anyone read the content, so the
prefix was thrown away. On top of that the model thinks before it answers, and
on a server that separates thinking from answering the reasoning arrives as
reasoning_content deltas that no provider knew about.

Changes

- services/aiGenerateOptions.js: the shared streaming machinery.
  stripReasoningText() removes <think> blocks, including one a cut-off left
  open. createProgressCollector() assembles a streamed answer, splits reasoning
  from answer incrementally (a marker may be cut across two chunks), counts the
  completion tokens from a usage chunk or estimates them over everything
  produced, reasoning included, and reports at most once per 100 ms plus one
  final report that says done. consumeChatCompletionStream() and
  runChatCompletionStream() are the OpenAI-compatible half: read the stream,
  finish before any throw, and turn a cut-off or a stop into an error that
  carries what arrived. isAbortError()/abortedGenerationError() give a stopped
  request one name across the SDK, axios and fetch.
- services/serviceUtils.js: estimateTokenCount() (the same character-based
  estimate, on a length) and an optional fourth argument on
  assertCompletionNotTruncated() that puts partialText on the error.
- services/openaiService.js, services/customService.js,
  services/azureService.js: generateText() streams when the caller hands in
  onProgress, with stream_options: { include_usage: true } on OpenAI and the
  custom provider and on Azure only from API version 2024-06-01, where the API
  takes it. Without a handler the body is exactly what it was. Both paths strip
  reasoning from the answer and attach the prefix to a truncation error; an
  abort throws an AbortError with partialText.
- services/customService.js: reasoning: false adds
  chat_template_kwargs: { enable_thinking: false } and, for a model name
  matching /qwen/i, that family's soft switch on its own line at the end of the
  user message; reasoning: true sends enable_thinking: true and no soft switch;
  without the option nothing new is sent.
- services/ollamaService.js: generateText() reads NDJSON from an axios
  responseType: 'stream' response, keeps the tail of a socket read until its
  newline arrives, treats the thinking field as thinking, and stops reading the
  moment the signal aborts. reasoning: false/true sends think and overrules
  OLLAMA_THINK; without the option OLLAMA_THINK still decides. The cut-off
  check the analysis path has always run now runs here too, with partialText,
  and a failure no longer erases a token count that was already measured.
- tests/helpers/fake-openai.js, tests/helpers/fake-ollama.js: real HTTP servers
  on ephemeral ports, scripted per request (content chunks, reasoning chunks,
  finish reason, usage chunk or none, per-chunk delay, non-streaming answers
  from the same script), recording every request body and whether the client
  hung up early.
- tests/test-ai-provider-streaming.js replaces its placeholder with 22 cases.

Testing

- node tests/test-ai-provider-streaming.js: 22 passed, 0 failed; run five
  times, no flake.
- node scripts/run-tests.js --all: 93 passed, 7 skipped offline, 0 failed —
  the same numbers as before this change.
- npx eslint and npx prettier --check on every touched file: clean.
- A throwaway process reproduced the reported failure against the fake: the
  progress reports show thinking first with no text, then the answer growing,
  then one done report with the exact token count from the usage chunk, and the
  throw carries the 131 characters of JSON that had arrived.

Impact

No caller behaves differently unless it asks: without onProgress the request
body is byte for byte what it was, and the round-7 provider cases assert that.
What does change for every caller of generateText(): a <think> block no longer
reaches the returned string, a truncation error now carries partialText, an
abort now throws under the name AbortError, and Ollama's generateText() now
raises the same truncation error the analysis path raises instead of returning
a half-written answer. The document analysis path is untouched.

Upstream Status

Not upstream. Streaming, progress reporting, the partial text of a cut-off
answer and the thinking switch do not exist in clusterzx/paperless-ai.

* feat(duplicates): the progress panel moves inside a request and names the measured batch size

Background

A review of a large archive is a handful of long model requests, and the
panel only moved between them. One request took 103 seconds while the page
showed "request 1 of 4 - 0 of 82 pairs" and a ticking clock, so for minutes
at a time the only honest reading of the page was "nothing is happening".
The judge now measures the model on a small first request, sizes every later
one to a configured number of seconds, and streams the answers as they
arrive, which gives the page three things it never had: answers inside a
request, a warm-up phase, and a model that says when it is thinking.

Changes

Page (views/duplicates.ejs, public/js/duplicates.js,
public/css/pages/duplicates.css):

- progressPercent() counts pairs whenever the plan knows them, the answers
  of the running request included, and falls back to requests only while no
  pair count exists. The bar therefore moves during a request instead of
  jumping once per request.
- progressCountsText() gained the "7 of 10 answers" part, printed only while
  a request is in flight and capped at the size of that request.
- progressTimeText() says "measuring the model" in the warm-up and "the
  model is thinking" while the model writes reasoning, instead of a clock
  that cannot move; an estimate the job already made is still shown next to
  either.
- New #dupAiProgressNote line under the counts, written by the new
  progressNoteText(): "4 pairs per request while the model is measured"
  before the measurement, "9 pairs per request, sized from the model's
  answers" after it, empty while no size is known. A zero-width space holds
  its row open for as long as a review runs (.dup-progress--live), so the
  stats tiles below do not jump the moment it fills.
- .dup-progress__fill--thinking pulses while the model reasons, slower than
  the indeterminate band, and is switched off under prefers-reduced-motion.
- The outcome line and the "Model requests" tile both name the batch size the
  review settled on.
- New htmlReviewFailure(): all three AI paths report a failed review with the
  judge's own message plus one link, "Open the Duplicates settings", to
  /settings#duplicates-tab.

Settings (views/settings.ejs, public/js/settings.js, routes/setup.js):

- Two fields close the Duplicates section: the switch "Let the judge think"
  (DUPLICATES_AI_THINKING, default off) and the number "Seconds per model
  request" (DUPLICATES_AI_REQUEST_SECONDS, 5-300, default 30). GET, POST with
  the usual clamping and keep-the-previous-value behaviour, the @swagger
  request body, ENV_EXPORT_GROUPS and the two "Managed by ENV" selectors.

Route:

- GET /api/duplicates/scan passes fresh: true; a scan somebody pressed a
  button for must not be answered from a cache.

OPENAPI/openapi.json regenerated.

Testing

- node scripts/run-tests.js --all: 93 passed, 7 skipped offline, 0 failed
  (unchanged from the baseline of this round).
- duplicates-ui 58 -> 66 cases: the bar with streamed answers and without a
  pair count, the counts line with and without a running request, the three
  wordings of the time line, the note line, the outcome line with a batch
  size, the panel ids and the thinking class, the settings link of the failed
  notice, and the stylesheet's pulse with its reduced-motion rule.
- settings-duplicates-section 11 -> 15 cases: both fields render with their
  values and hints, the POST round trip, clamping (2 -> 5, 999 -> 300), the
  cleared field keeping the previous value, the switch spellings, the export
  group order and the two selectors.
- duplicates-endpoints 30 -> 31 cases: the scan route hands fresh: true to
  the service.
- eslint, prettier and stylelint clean on every touched file; regen-openapi
  leaves no drift.
- Looked at in Chromium against a throwaway server on port 3403 that walks a
  scripted review through the warm-up, a thinking stretch and a request whose
  answers climb 0 -> 10: desktop and phone, light and dark. The stats tiles
  sit at the same offset before and after the note line fills.

Impact

The panel reports inside a request rather than between requests, and names
both the warm-up and the measured batch size, so a review that takes minutes
per request looks like work rather than a hang. A failed review points at the
setting that would have prevented it. Nothing scans, judges or merges on its
own; the two new settings are read at startup like the rest of the section.

Upstream Status

Not applicable - the Duplicates page does not exist upstream.

* feat(duplicates): measure the model, size every request to it, and reuse a fresh scan

Background

Asking the AI about a scan of the user's archive did not work on their
instance. The judge sent 25 pairs with a completion cap of 3200, the hosted
model thought before it answered and spent all 3200 tokens on the thinking,
and 102 seconds later nothing had been judged. The answer was then split into
13 + 12, which buys nothing: the thinking does not get cheaper with fewer
pairs. Meanwhile the page showed "request 1 of 4 · estimating…" for two
minutes, because a request only reports when it is over. The user pressed
Stop.

The same run also scanned the archive three times inside 50 seconds — the
page's scan, the AI proposal's and the review job's — 1359 tags and 13
seconds each, with nothing changing in between.

Changes

services/entityMatchAiService.js

- Thinking off by default. Every judge request carries
  `reasoning: config.duplicatesAiThinking === true`, so a reasoning model
  answers instead of deliberating unless the operator asked for it. Nothing
  else about the prompt changed.
- A warm-up instead of a guess. The first request of a review whose model has
  not been measured asks about at most WARMUP_PAIRS (4) pairs with a
  deliberately generous cap (RESPONSE_TOKENS, the flat estimate or
  WARMUP_MIN_CAP, whichever is largest, bounded by the context window). It is
  announced under the phase `warming-up` with the message "Measuring the model
  with a small first request…", `calibrated: false` and the size it will use;
  the plan reported with it is provisional and the log says so.
- Sizing from the measurement. Every answered request yields tokens per pair
  (thinking included) and tokens per second, each smoothed by half against the
  measurement before it. From them:
  `batchSize = clamp(floor(requestSeconds × tokensPerSecond ÷ tokensPerPair), 1, batchSize())`
  and `cap = ceil(tokensPerPair × batchSize × 1.5) + TOKENS_OVERHEAD`, both
  bounded by the context window as the batch planning bounds them.
  `requestSeconds` is DUPLICATES_AI_REQUEST_SECONDS, at least 5, 30 by
  default. A batch is now taken off the front of a queue rather than chunked
  up front, because its size changes while the review runs.
- The plan settles after the warm-up. `requestsPlanned` and `estimatedTokens`
  are re-derived from the pairs nobody has asked about yet and reported with
  `batchSize` and `calibrated: true`, so the page's denominator stops moving.
- Truncation: raise before halving. A cut-off answer that salvaged nothing is
  asked again with twice the cap (the warm-up gets the whole window at once),
  and only when that bought nothing — or the cap is already at the window's
  bound — is the batch halved as before. A warm-up that does not fit even then
  ends the review as failed with a message the operator can act on, naming
  DUPLICATES_AI_THINKING and TOKEN_LIMIT. A single pair at the bound keeps the
  old "unsure" and its log line.
- The cut-off text counts. All four providers now attach `error.partialText`,
  so the salvage path runs for every one of them; a salvaged request counts
  its verdicts in `pairsJudged` and in the tracker. Two comments that still
  said only Ollama returns half-written answers were rewritten.
- Progress inside a request. With a progress sink the provider is asked to
  stream (`onProgress`). Each report, at most every 250 ms, carries
  `requestPairs`, `requestAnswers` (the complete verdict objects counted off
  the streamed text), `requestTokens`, `thinking` and the running token total:
  "The model is thinking… (640 tokens so far)" while it thinks, otherwise the
  request line with " · 7 of 10 answers" appended. The report that counts the
  request resets all four. A review nobody watches sends the plain request it
  always sent.
- Calibration memory. The last measurement per model name lives on the
  singleton; a review that finds one starts sized from it, skips the warm-up
  and says so in the log. A measurement taken with thinking on is never reused
  with thinking off. `resetCalibration()` for tests.
- Logs: the finish line says "N pair(s) planned" (the number is the plan), the
  batch-size line is marked provisional until the model is measured, and the
  split line says whether the cap was raised or the batch halved.

services/duplicateMergeService.js

- `scan()` keeps its result per set of options (kind, threshold,
  includeDismissed) for SCAN_CACHE_MS (60 s) and answers the next identical
  request from it with one log line instead of the start and finish lines.
  `fresh: true` skips and refills it; the page's Scan button sends it.
- A merge, an undo, a dismissal and `restoreDismissal()` empty the cache. A
  dismissal deleted through the route, which talks to the model directly, is
  caught by a fingerprint (row count and highest id per kind) checked on every
  hit — one local SELECT against a 13-second scan.
- `reviewScan()` calls `scan()` without `fresh`, so a proposal made right
  after the page scanned costs no second scan.

Testing

- node scripts/run-tests.js --all: 93 passed, 7 skipped offline, 0 failed
  (100 registered), unchanged from the baseline.
- tests/test-entity-match-ai-service.js: 65 -> 80 cases. New: thinking off and
  on; the warm-up's size, cap, phase and message; the sizing math on a fixed
  usage and duration; the request seconds and their floor; the context window
  bounding size and cap; smoothing; the plan and estimate recomputed after the
  warm-up; calibration reused, not reused across the thinking switch, reset; a
  warm-up that cannot fit ending the review with its message; a truncated
  answer with partialText salvaged and counted; a streamed request reporting
  thinking, then answers, then clearing itself; an unwatched review not
  streaming; a review served from the page's scan.
- tests/test-duplicate-merge-service.js: 17 -> 22 cases. New: cache hit, other
  options and `fresh` missing it, expiry, invalidation by merge, undo, dismiss
  and restore, and a dismissal removed behind the service.
- Changed expectations, all from the raise-before-halve rule: the truncation
  cases now see every size asked twice (once, once with twice the cap) before
  it is halved, the single pair is asked twice before it ends as unsure, and
  the planning cases see the `warming-up` phase where they saw `judging`.
- Two demo runs against a fake model at 30 tokens/s: thinking off, 12 pairs —
  warm-up 4 pairs in 20 s (600 tokens, 150 per pair), then requests of 5 pairs
  at 25 s, 4500 tokens, 60 s in total. Thinking on — warm-up 4 pairs in 40 s
  (1200 tokens, 300 per pair) and requests of 2 pairs at 30.04 s, the
  configured length.

Impact

The first request of a review is seconds rather than minutes, every later one
lasts about as long as the operator asked, and the page shows the model
thinking and answering while it happens instead of a still bar. A review of a
model that was measured before starts at full size. Three scans of one archive
become one. Nothing runs on its own and no verdict changed: the prompt, the
rules and the shape of an answer are what they were.

Upstream Status

Not applicable — the Duplicates feature does not exist upstream.

* fix(duplicates): a review never asks for a fresh scan of its own

reviewScan() drops a `fresh` flag its caller may carry instead of passing it on, so a route that forwards the page's scan options cannot make the review scan the archive a second time.

* fix(duplicates): the yes/no switches of the judge read 'yes', and a small batch is not starved after a thinking one

Background
The browser smoke test of the round ran the thinking scenario and the
judge kept saying "thinking off" although DUPLICATES_AI_THINKING=yes
was set. config/config.js normalises every yes/no setting to the
strings 'yes' and 'no' (parseEnvBoolean), while three readers in the
judge asked Boolean() or === true: the thinking switch could never be
turned on, and the review and excerpt switches could not be turned off
('no' is a truthy string). The second finding: a thinking model pays a
fixed price per request, so a one-pair request sized by pairs alone
after a four-pair warm-up got a cap the same thoughts did not fit; the
judge recovered by raising the cap, at the cost of one request.

Changes
- services/entityMatchAiService.js: switchedOn() accepts 'yes' and a
  boolean true; isEnabled(), excerptsEnabled() and thinkingEnabled() use
  it. The cap never drops below the largest completion the model has
  produced in this review plus a quarter (CAP_FLOOR_FACTOR), and that
  floor is remembered with the calibration.
- tests/test-entity-match-ai-service.js: one case per finding (82
  cases), the sizing case expects the remembered floor.
- config/changelog.js: three entries for the round under the current
  release.

Testing
- node scripts/run-tests.js --test entity-match-ai-service: 82 passed.
- Browser smoke against a fake Paperless-ngx and a fake provider that
  streams, thinks on request and honours max_tokens: thinking off, the
  fake never thought, warm-up 4 pairs, 59 tokens/s measured; thinking
  on, the panel showed the thinking state, no request hit the token
  limit any more; Stop, re-attach, token budget and the round-6
  walkthrough unchanged.

Impact
DUPLICATES_AI_REVIEW=no and DUPLICATES_AI_EXCERPTS=no now do what they
say; DUPLICATES_AI_THINKING=yes now reaches the model.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): contract for the creation guard, the semantic sweep, unused objects, renames and a remembered calibration

Background
Round 9 of the Duplicates feature, six points the user picked: stop
the drift where it starts (document analysis creating "Rechnungen"
next to "Rechnung"), let the model find synonyms and translations the
string matcher cannot, list and delete unused objects with undo, name
the survivor of a merge, keep the judge's measurement of a model across
restarts, and scan faster. Decisions: only hard matcher tiers map a
new name onto an existing one (case, umlauts, legal form, plural…
…ss-ngx already has (#333)

* feat(duplicates): contract for a targeted AI review

Background
With many groups at 94 to 96 percent the user wants to say "everything
from 95 percent up: ask the AI, show me its view, then merge". The
review must therefore be able to judge only chosen groups and skip the
band of near-misses.

Changes
- schemas.js, OPENAPI/openapi.json: groupIds, minConfidence and
  includeCandidates on DuplicateAiReviewRequest.

Testing
- node scripts/regen-openapi.js: no drift after the commit.

Impact
Request fields only; the implementation follows.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): targeting counters in the AI review result schema

Background
A targeted review reports which groups it judged and which it left
without a verdict; the page shows that.

Changes
- schemas.js, OPENAPI/openapi.json: targeted, groupsJudged and
  groupsSkipped on DuplicateAiReviewResult.aiReview.

Testing
- node scripts/regen-openapi.js: no drift after the commit.

Impact
Documentation of three informational fields.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): let the AI review be pointed at a few groups

Background

An archive with hundreds of correspondents produces dozens of groups at
94, 95 and 96 per cent, and asking the model about all of them costs a
lot to answer a question about a handful. The page needs to select the
groups it is about to merge, ask about those, and keep rendering the
rest of the scan while it does.

Changes

- entityMatchAiService.reviewScan() takes three options that narrow what
  is asked, never what comes back:
  - groupIds: only these scan groups are judged. Every other group is
    still in `groups`, as the scan produced it, with `aiVerdict: null` on
    the group and on every member and `source: 'scan'`. An id this scan
    does not know is ignored and logged once with the count.
  - minConfidence: only groups scoring at least this much are judged;
    together with groupIds both conditions have to hold.
  - includeCandidates (default true): false leaves the band of
    near-misses out entirely, so `candidates` is 0 — and with no band
    the entity list per kind is not read either, which is the cheap part.
- _pairsForKind() takes the set of group ids to judge. A group left out
  contributes no pairs but its member pairs still count as "inside one
  group", so it cannot reappear as a candidate.
- The result reports the targeting: aiReview.targeted, .groupsJudged and
  .groupsSkipped. The start line of the log names it as
  "judging 1 of 4 group(s) (min confidence 0.95, 3 ids), band skipped",
  the closing line adds the two counters. An untargeted review logs and
  behaves exactly as before.
- POST /api/duplicates/ai-review validates and passes the three fields
  through: groupIds an array of at most 500 non-empty strings,
  minConfidence a number in [0.5, 1], includeCandidates a real boolean
  (the string "false" is a 400). An option the request does not mention
  is left out of the service call, so an untargeted request reaches
  reviewScan() with the same object it did before.
- Swagger description of the route and the 400 reason updated,
  OPENAPI/openapi.json regenerated.

Testing

- node scripts/run-tests.js --all -> 90 passed, 7 skipped offline,
  0 failed (97 registered), unchanged against the baseline.
- entity-match-ai-service: 28 -> 34 cases. Six new ones on a fixture
  whose four groups sit exactly on the matcher tiers (1, 0.98, 0.95,
  0.9) plus one pair in the band: groupIds judges only what it names,
  minConfidence filters, includeCandidates: false skips the band and
  reads no second entity list, groupIds and minConfidence combine while
  unknown ids are ignored, an empty selection costs no request, and the
  log lines. The existing aiReview assertion gained the three new fields.
- duplicates-endpoints: 16 -> 19 cases. The three fields reach the
  stubbed reviewScan unchanged, an untargeted request still carries
  nothing extra, ten malformed targeting bodies are 400, and 500 ids are
  accepted while 501 are not.
- Manual run against the real route with a fake store and a fake
  provider: full review 5 pairs / 1 request, minConfidence 0.95 without
  the band 3 pairs, two selected ids (one unknown) 1 pair, and every
  unjudged group back with null verdicts.
- eslint, prettier and the OpenAPI drift check clean on the touched
  files.

Impact

Additive. A review that says nothing about the three options behaves and
logs as before. The page can ask about the groups it selected before a
batch merge; a dozen groups without the band are one or two model
requests instead of the whole archive. schemas.js still has to gain
targeted, groupsJudged and groupsSkipped on DuplicateAiReviewResult.

Upstream Status

Not applicable: the Duplicates feature is next-only.

* feat(duplicates): sort, select by confidence, and a guided review before merging

Background
----------
On a grown archive a scan answers with dozens of groups that all read 94, 95,
96 percent, and the page offered no way to act on that number: every group had
to be judged by eye, one tick at a time. The three presets were the only
thresholds available, so "everything above 95" was not a question the page
could be asked. And where the AI review existed it judged the whole result
list, which is the most expensive way to ask about the five groups the user
actually cares about.

The rule this follows: the AI is an addition, never a condition. Every flow
below works end to end with the review switched off; with it on, the guided
path is one more button beside the one that was already there.

Changes
-------
Results toolbar (#dupResultsBar), above the selection bar, shown once a scan
has groups:
  - "Sort by" (#dupSortSelect): confidence, documents, target name (locale
    compare), kind then confidence. It moves the DOM nodes instead of
    re-rendering, so a card keeps its target, its source ticks, its selection,
    its verdict and its busy state; the two blocks (scan groups, AI
    candidates) are sorted separately and the divider stays between them.
  - "Select >=" (#dupMinConfidence, #dupSelectMinBtn, #dupMinConfidenceCount):
    ticks every selectable group at or above a whole percent and unticks the
    rest, with a live count of what the click would do.
Custom scan threshold: a fourth sensitivity option "Custom" reveals a number
field (#dupThresholdCustom); the scan and both review paths send that percent
divided by 100. The three presets are unchanged.
Confidence breakdown under "Groups found" (#dupStatBuckets): ">=95 %: A .
90-95 %: B . <90 %: C", counted from the cards after a scan and after a review.
Guided flow (#dupReviewThenMergeBtn, rendered only where the review exists):
asks the model about exactly the ticked groups (groupIds, includeCandidates:
false), puts the verdicts on the cards as a full review does, then shows them
once in a wide dialog - one row per group with target, sources, documents, the
verdict chip and the reason, a live "N of M ticked . K documents" foot line and
the copy-rule check. Ticked rows are merged with the batch machinery; an unsure
or different verdict only comes up unticked and never blocks anything, and what
stays unticked stays selected on the page.
"Merge selected" keeps its place and its weight, first in the bar and without a
model anywhere in its path; its dialog names the guided path in one faint line,
and only where that path exists.
Sort, confidence, sensitivity and the custom threshold are remembered in
localStorage (dup.sort, dup.minConfidence, dup.sensitivity,
dup.thresholdCustom) through two try/catch helpers.

Testing
-------
node scripts/run-tests.js --all -> 90 passed, 7 skipped offline, 0 failed
  (unchanged from the branch baseline).
tests/test-duplicates-ui.js: 25 -> 38 cases. New: the toolbar ids and their
  order, the custom threshold field, the stats breakdown, the guided button
  only with the review, the whole page without the review, the toolbar ids in
  the script, sorting as a DOM move, "Select >=", the wrapped localStorage
  access, the guided request (groupIds / includeCandidates: false) and that
  "Merge selected" never touches the review endpoint, the review dialog markup,
  the tip line, the new CSS classes. Changed: the sensitivity options are read
  from #dupSensitivity alone and now end in "custom"; the undo promise and the
  confirm dialogs are counted one higher each, because the review dialog merges
  and therefore makes the same promise.
Reviewed in a browser against a throwaway mock (twelve groups over 88-100 %, a
  review that honours groupIds): 27 screenshots at 1280x900 and 390x844, light
  and dark, 0 px horizontal overflow everywhere, plus a 31-check behaviour
  probe (guided request, verdict ticks, sorting keeping picks and the divider,
  persistence, a refused review, and the whole page with the review off).

Impact
------
Page only. No route, service, schema or config was touched, so the OpenAPI
spec is unchanged. An instance without the AI review renders and behaves
exactly as before plus the toolbar and the custom threshold. The request the
guided path sends uses fields the contract already carries; a server that
ignores them reviews everything, which the page renders correctly.

Upstream Status
---------------
Not applicable - the Duplicates page does not exist upstream.

Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* docs(duplicates): changelog entries for sorting, select by confidence and the guided review

Background
Round 5 answered the second feedback from a real archive: select by a
number, let the model judge exactly those groups, read its verdicts in
one dialog, merge what stays ticked; sort the groups; a custom threshold.

Changes
- config/changelog.js: two entries in the current v2026.09.01 block.

Testing
- node scripts/run-tests.js --test changelog-releases: passed.

Impact
Documentation only.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): contract for evidence-based verdicts and the AI proposal

Background
A real archive produced "Kontoauszug" / "Kontoumzug": the matcher called
it a spelling distance, the prompt allowed "an obvious typo" as a reason
for same, and the model, seeing names and titles only, agreed. Both are
different things. The judge needs stricter rules and, for pairs linked by
spelling alone, a look at what the documents are about, at a bounded
cost.

Changes
- config/config.js: DUPLICATES_AI_EXCERPTS (default yes),
  DUPLICATES_AI_EXCERPT_CHARS (300), DUPLICATES_AI_EXCERPT_DOCUMENTS (2).
- schemas.js, OPENAPI/openapi.json: AiVerdict gains basis and confidence;
  DuplicateAiReviewRequest gains withExcerpts; aiReview reports excerpts.

Testing
- node scripts/run-tests.js --area duplicates: 6/6; regen without drift.

Impact
Settings and schema only; the implementation follows.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): judge model override and the verdict source in the contract

Background
Decisions for round 6: the matcher's hard tiers settle a pair without the
model, unsure pairs are asked once more with excerpts, and the judge may
run on a stronger model of the same provider.

Changes
- config/config.js: DUPLICATES_AI_MODEL (optional, judge only).
- schemas.js, OPENAPI/openapi.json: AiVerdict.source (model or
  spelling-rule); aiReview.escalated and aiReview.spellingRules.

Testing
- eslint and prettier on the two files; regen without drift.

Impact
Settings and schema only; the implementation follows.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(settings): make every DUPLICATES_ setting editable in its own section

Background
The AI review of the Duplicates page arrived with seven environment
variables and no way to change any of them from the interface. Editing a
container environment and recreating the container is the wrong price for
"try a stronger model for the judge" or "ask about fewer pairs per
request", and the settings page is exactly where those knobs belong.
config/config.js already reads all seven; only the front door was missing.

Changes
- views/settings.ejs: a "Duplicates" section (id="sec-duplicates") inside a
  new duplicates-tab block between the AI sections and OCR, with a nav entry
  in the desktop section nav (icon i-merge) and in the mobile one, in the
  same order as the page. Seven fields, each with a hint that says what the
  value does and what its default is: the AI review switch, the judge model,
  pairs per request, the candidate floor, the excerpt switch, excerpt length
  and documents per entry. Switches go through partials/settings-switch, so
  the hidden yes/no input the POST route reads exists as it does everywhere
  else.
- routes/setup.js: GET /settings passes the seven values (env first, the
  defaults of config/config.js as fallback) in the config object the view
  reads; POST /settings destructures the seven camelCase body keys,
  normalises them and writes them into updatedConfig, so setupService
  .saveConfig persists them with the rest. Numbers are clamped to their
  range; a value that is not a number, or a cleared field, keeps what is
  configured now instead of resetting to the default. The swagger body
  schema documents all seven, and the .env export gained a "Duplicates"
  group between "AI behaviour" and "External API".
- public/js/settings.js: the seven selector to env-key entries, so the
  "Overwritten" and "Managed by ENV" marking covers these fields too.
- OPENAPI/openapi.json regenerated.
- tests/test-settings-duplicates-section.js, registered in the
  observability area.

Testing
- node scripts/run-tests.js --all: 98 registered, 91 passed, 7 skipped
  offline (was 97/90/7). The new test covers the rendered section and its
  nav position, the seven inputs and their values, the POST round trip,
  clamping, the keep-the-previous-value case and the .env export group.
- npx eslint / npx prettier --check --ignore-unknown on every touched file.
- node scripts/regen-openapi.js leaves OPENAPI/openapi.json unchanged.
- Looked at the page in Chromium at 1440x1000 and 390x844 against a
  throwaway server outside the repository; no console errors, the section
  reads like the rest of the page and stacks on the phone.

Impact
Operators can change every DUPLICATES_ value from the settings page. The
existing restart-after-save is what makes them take effect; no new
mechanism. Values injected by the container still win and are shown as
managed, as for every other field. Nothing outside the settings page
changes: no route, service or default behaviour of the Duplicates page
itself is touched.

Upstream Status
Fork-only. The Duplicates page does not exist upstream.

Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): judge spelling-only pairs on evidence, not on distance

Background
A real archive produced "Kontoauszug" next to "Kontoumzug": the matcher
called it a spelling distance, the prompt allowed "an obvious typo" as a
reason for same, and the model, seeing two names and three titles, agreed.
Two different things. The judge needed stricter rules, evidence for the
pairs where spelling is the only link, and a way to say how sure it is and
on what grounds — all without opening a large context window on every pair.

Changes
- entityMatchAiService: the system prompt refuses a small spelling distance
  as a reason of its own ("Kontoauszug" / "Kontoumzug", "Miete" / "Mieter",
  "Bahn" / "Bank"), allows a misspelling only when one spelling is not a
  word, and answers unsure when it cannot tell. The output contract gains
  "basis" (a closed list) and "confidence" (high | low); both are parsed,
  an unknown value becomes null, and every verdict, member verdict and
  aggregate carries them. An aggregate keeps the deciding member's basis
  and takes "low" as soon as one deciding member is low.
- Evidence, graded by what the link is worth: every pair carries matched_by
  and score; every judged entity carries its titles, its matching rule and
  its neighbourhood ("filed_with": the correspondents of a tag's documents,
  the tags of a correspondent's); only the pairs linked by fuzzy, prefix or
  token-order also carry document excerpts. Excerpts are read once per
  entity per review and never for a strong tier. withExcerpts: false or
  DUPLICATES_AI_EXCERPTS=no reads nothing at all.
- A member pair a matcher rule settles (exact-normalized, umlaut-variant,
  legal-form) never reaches the provider: it gets verdict same with
  source: spelling-rule, counts in aiReview.spellingRules and costs no
  request, no read and no token.
- A pair the model calls unsure and that had no excerpts is asked once more
  with them; the second answer replaces the first (aiReview.escalated).
- paperlessService: getRecentDocumentExcerptsByEntity (one read,
  truncate_content, cut to the configured characters at a word boundary)
  and getEntityNeighbourhood (one read, the most frequent neighbour names
  through the existing caches). Both answer [] on any error and never log
  document content.
- The judge may run on its own model (DUPLICATES_AI_MODEL): generateText
  takes an optional model in all four provider services, shared through
  aiGenerateOptions.modelOverride.
- Logs: the per-kind start line names the evidence and the model, the
  request line the pairs with excerpts, the escalation its own line.
- Route POST /api/duplicates/ai-review parses withExcerpts like withTitles;
  swagger description updated and OPENAPI/openapi.json regenerated.

Testing
- node scripts/run-tests.js --all: 97 registered, 90 pass, 7 skip offline.
- tests/test-entity-match-ai-service.js: 35 -> 50 cases (the stricter
  prompt, basis and confidence parsing, excerpts only for spelling-only
  pairs and once per entity, the two switches, the configured cut, the
  Kontoauszug regression, settled pairs, the neighbourhood, escalation, the
  model override, batch sizing with excerpts, and both new client methods).
- tests/test-duplicates-endpoints.js: one case for withExcerpts; the three
  existing option assertions now expect withExcerpts: true.
- Demo run against the fake Paperless-ngx: the Kontoauszug/Kontoumzug pair
  costs 282 prompt tokens with excerpts, a strong pair without excerpts 75.
- eslint, prettier and a regen without drift on every file touched.

Impact
An AI review asks about fewer pairs and knows more about the ones it asks
about. Nothing runs on its own, nothing is merged, and document content
never reaches a log line.

Upstream Status
Not applicable — the Duplicates feature does not exist upstream.

* fix(duplicates): do not escalate an unsure pair whose documents carry no text

* feat(duplicates): one click for the AI's proposal, with the evidence behind it

Background
----------
Everything the page offered so far started from the user: scan, read every
card, tick, merge — and where the AI review existed it was a second question
asked after the first. What was missing is the path the archive's owner
actually wants for a first clean-up: one click that scans, has every group and
every near-miss judged, and then hands over a proposal to thin out rather than
a list to work through.

The rule this follows is the same as in the rounds before: the AI is an
addition, never a condition. Without the review nothing of this renders, and
"Scan Paperless-ngx", "Merge selected", the toolbar, the manual merge and the
guided path are the same as they were.

A verdict also had to say more than "same": with `basis`, `confidence` and a
`source` on the wire, the page can pre-tick exactly what is settled — a pair a
spelling rule decided, or one the model says it is sure about — and leave
everything else to the user. The member tables, finally, measured their own
content per card, so the columns of two cards below each other sat in
different places.

Changes
-------
"AI proposal" (#dupAiProposalBtn, primary, rendered only with aiReviewEnabled)
next to "Ask the AI", usable from the first paint because it scans itself:
  - status in the AI row (#dupAiProposalStatus): "Scanning…", then "Asking the
    AI about N pairs and near-misses…", with the hint line under the row
    (#dupAiProposalHint) saying what the click does;
  - it reuses runScan() (now awaited) with the kind, sensitivity and hidden-pair
    settings on the page, then the one review request with includeCandidates
    and no groupIds. Two requests, and no merge until the dialog is confirmed.
Proposal dialog (.dup-proposal-dialog): one row per group that could be merged,
  sorted same/high, same, unsure, different, unjudged (proposalRank,
  compareProposalEntries — both pure); pre-ticked are only the settled ones
  (isSureSame: verdict "same" with confidence "high", which covers the
  spelling-rule verdicts); legend, "Tick all same" (#dupProposalTickSame),
  "Untick all" (#dupProposalUntickAll), the copy-rule check (#dupCopyRuleAll)
  and a live foot line "N of M ticked · K documents · X objects will be
  deleted". Confirming sets the page selection to the ticked groups and hands
  them to the batch runner of round 4, so the selection bar reports the merge
  as it does for "Merge selected"; cancelling leaves the verdicts on the cards
  and nothing ticked.
Evidence, shared by both dialogs (one row renderer, one table):
  - a "Basis" column as a .zr-badge with a label per contract value;
  - the confidence as a suffix of the verdict chip ("AI: same · high");
  - a pair a spelling rule settled reads "Spelling rule" in the "same" tone
    (.dup-verdict--rule) instead of quoting a model that never saw it;
  - the guided dialog pre-ticks by the same rule, so a "same" the model is
    unsure about now comes up unticked there too.
Cards keep their shape: the verdict chip carries the basis in its title and the
  confidence as its suffix, no new column.
Second checkbox "Use document excerpts for spelling-only pairs"
  (#dupAiExcerpts, checked); withTitles and withExcerpts flow into every review
  request from the one place that builds it. The titles checkbox is relabelled
  "Use document titles and neighbours as context".
"AI-judged pairs" tile: its sub line now also counts "· E excerpts", "· S by
  spelling rule" and "· E escalated" when the review reports them.
Member tables line up across cards: .dup-members is table-layout: fixed with
  the name column taking what is left and truncating, and the matching rule a
  fixed share (.dup-members__name, .dup-members__rule).

Testing
-------
node scripts/run-tests.js --all -> 90 passed, 7 skipped offline, 0 failed
  (unchanged from the branch baseline of 97 registered).
tests/test-duplicates-ui.js: 38 -> 48 cases. New: the proposal ids and labels
  only with the review and the page whole without them; what the flow sends
  (runScan first, includeCandidates: true, no groupIds, both evidence flags,
  no request of its own); the pre-tick rule, evaluated as a function against
  seven verdicts; the row order, evaluated by sorting a shuffled list; a label
  for every basis the AiVerdict schema lists, parsed out of schemas.js; the
  spelling-rule chip; the dialog's parts and that it merges through the batch
  runner; the evidence counters of the stats tile; the fixed member-table
  layout; the new CSS classes. Changed: the titles checkbox label, the undo
  promise and the confirm dialogs counted one higher each (the proposal merges
  and therefore makes the same promise), and the pre-tick assertion of the
  guided row.
Reviewed in a browser against a throwaway mock (eleven scan groups plus three
  the model proposes, verdicts across same/high, same/low, unsure and
  different, some settled by a spelling rule, and a Kontoauszug / Kontoumzug
  pair that only the excerpts decide): 31 screenshots at 1280x900 and 390x844,
  light and dark — the controls, the status line mid-flow, the proposal dialog,
  after "Untick all", mid-merge, after the merge, the guided dialog, the stats
  tile, the aligned member tables and the render without the review. 0 px
  horizontal overflow everywhere; the column offsets of all eleven cards are
  identical.

Impact
------
Page only. No route, service, schema or config was touched, so the OpenAPI
spec is unchanged. An instance without the AI review renders and behaves
exactly as before. The new request field and the new verdict fields are ones
the contract already carries: a server that ignores withExcerpts reviews as it
did, and a verdict without basis, confidence or source renders as it did — it
then simply never comes up pre-ticked, which is the safe side.

Upstream Status
---------------
Not applicable - the Duplicates page does not exist upstream.

Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* chore(duplicates): changelog for the AI proposal round, room for the verdict in the Match column

Background
The sixth round of the Duplicates feature adds the AI-led proposal, the
evidence-based judge and the Duplicates settings section. The member
tables now use a fixed column layout so the columns line up across
cards, which left the Match column too narrow for a verdict such as
"AI: same - high": it wrapped into four lines.

Changes
- config/changelog.js: five entries for the round under the current
  release (AI proposal, evidence-based judge with excerpts and
  DUPLICATES_AI_EXCERPT*, DUPLICATES_AI_MODEL, aligned member tables,
  the Duplicates settings section).
- public/css/pages/duplicates.css: the Match column is 132px wide and
  the member verdict does not wrap, so the percentage and the verdict
  take one line each.

Testing
- npx eslint, prettier --check and stylelint on every file changed
  against nightly: clean.
- node scripts/run-tests.js --all: 91 passed, 7 skipped (server or
  credentials needed), 0 failed.
- node scripts/regen-openapi.js: no drift.
- Browser walkthrough against a fake Paperless-ngx and a fake judge:
  scan, merge, undo, dismiss, merge by hand, batch merge, guided review,
  AI proposal and AI review all pass. The Kontoauszug/Kontoumzug pair is
  judged "different" on its excerpts and does not appear in the
  proposal.

Impact
Visual only for the CSS; the changelog is shown in the What's New
dialog.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): contract for a watchable, stoppable AI review

Background
An AI review of a large archive is many model requests in a row. Today
it is one POST that answers when everything is done: nothing shows
while it runs, nothing can stop it, and the tokens it spends are
invisible until the end. The user wants to see what is happening, how
far it is and what it costs, and to stop it at any time. Decisions for
this round: the review runs as a server-side job the page can watch
and stop; a review nobody watches stops itself; a token budget per
review stops it on its own; a stopped review keeps the verdicts it
reached and opens no dialog; the progress lives in the AI row of the
Duplicates page.

Changes
- services/duplicateReviewJobService.js (new): the one review job at
  a time. start(), current(), get(), stop(id, reason), subscribe() for
  a server-sent stream (a late subscriber first gets the job as it is
  now), touch(), wait(), result(), toJSON(). The judge receives a
  control object (signal, onProgress, stop, tokenBudget); a partial
  result of a stopped review is kept like a complete one. The idle
  watch stops a job nobody has watched for the configured seconds. A
  finished job stays reachable for ten minutes.
- config/config.js: DUPLICATES_AI_TOKEN_BUDGET (200000, 0 = no limit)
  and DUPLICATES_AI_IDLE_STOP_SECONDS (60, 0 = never).
- schemas.js, OPENAPI/openapi.json: AiReviewProgress, AiReviewJob,
  AiReviewJobEvent; aiReview gains stopped, stopReason and
  pairsNotJudged.
- scripts/run-tests.js, tests/test-duplicate-review-job.js: the
  contract test of the job (9 cases) in the duplicates area.

Testing
- node scripts/run-tests.js --all: 99 registered, 92 pass, 7 skip
  offline, 0 fail.
- eslint and prettier on every touched file; regen without drift.

Impact
Nothing uses the job yet; the judge ignores the control object until
the implementation follows. No route or page changes.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): make the token budget and the idle stop editable in settings

Background
The two brakes of a running AI review landed as environment variables only:
DUPLICATES_AI_TOKEN_BUDGET caps what one review may spend across all its
requests, DUPLICATES_AI_IDLE_STOP_SECONDS ends a review no page has been
watching, so a closed tab cannot leave the model running. Both are exactly
the kind of setting somebody wants to try out once and then adjust, which
means editing a compose file and restarting the container for every attempt.
The other seven DUPLICATES_* variables already have a field in the Duplicates
section of the settings page; these two did not.

Changes
- views/settings.ejs: two number fields at the end of #sec-duplicates, in the
  style of the five above them — duplicatesAiTokenBudget (0-10000000, step
  1000) and duplicatesAiIdleStopSeconds (0-3600). Each hint says what the
  value does, what zero means and what the default is.
- routes/setup.js: GET /settings passes DUPLICATES_AI_TOKEN_BUDGET and
  DUPLICATES_AI_IDLE_STOP_SECONDS to the view with the defaults of
  config/config.js as the fallback; POST /settings destructures both body
  keys, clamps them to their ranges and keeps the currently configured value
  for an empty or non-numeric field, the rule the round-6 fields follow. Zero
  is a value for both and survives the clamp, because the ranges start there
  rather than at one. The @swagger body schema documents both, and the
  Duplicates group of ENV_EXPORT_GROUPS lists them after the existing keys.
- public/js/settings.js: two entries in the field mapping, so an
  operator-injected value greys the field out and carries the "Managed by ENV"
  pill like every other setting.
- OPENAPI/openapi.json regenerated.

Testing
- tests/test-settings-duplicates-section.js grew from 7 to 11 cases: the two
  fields render with their configured values, ranges and hints and close the
  section in that order; every field of the section is paired with its
  environment key in settings.js; the POST round trip persists all nine
  values; a budget of 99999999 is capped at 10000000 and an idle stop of -5
  lands on 0; zero survives for both, because it means "no limit" and "never"
  rather than an unset field; a fractional value is rounded; a cleared or
  unparsable field keeps what was stored before; the .env export carries all
  nine keys with the two brakes last.
- node scripts/run-tests.js --all: 99 registered, 92 passed, 7 skipped
  offline, 0 failed — the same numbers as before this change.
- eslint and prettier clean on every file touched; regen-openapi.js leaves no
  drift.
- Looked at the section in Chromium at 1440x1000 and 390x844 against a
  throwaway server outside the repository: both fields render like the seven
  above them, no console errors, and with the two keys in the locked-env set
  both are disabled and carry the "Managed by ENV" pill while a neighbouring
  field stays editable.

Impact
No behaviour change for anybody who never opens the section: the defaults are
unchanged (200000 tokens, 60 seconds) and nothing new runs. Operators who set
either variable in their container environment keep winning — the field is
shown greyed out rather than silently overwritten. A saved value needs a
restart to take effect, as the hints say, because config/config.js reads the
environment once at load.

Upstream Status
Not applicable — the Duplicates page is specific to this fork.

* feat(ai): let every provider take an abort signal for one call

aiGenerateOptions gains abortSignal(options); the four provider
services pass it on where their client expects it — the OpenAI SDK as
the second argument of create(body, { signal }) for OpenAI, Azure and
the custom endpoint, axios as { signal } in the request config for
Ollama. Without a signal every provider sends exactly what it sent
before: no second argument at all, and the unchanged axios config.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): the AI review reports, stops and counts its tokens

Background
"Während die AI befragt wird, könnten Millionen von Tokens im
Hintergrund verbraten werden, ohne dass man es sieht. Man muss es auch
abbrechen können." The judge answered when it was done and said
nothing while it worked, so the page had nothing to show and nothing
to stop. The job of the previous round hands it a control object; this
round makes the judge use it. A bar needs a denominator before the
first request, which the old per-kind loop could not give: it read the
archive, asked, and only then looked at the next kind.

Changes
- services/entityMatchAiService.js: reviewScan(options, control = {})
  runs in two passes. Pass one, for every kind of the review: read the
  entities and the band, build the pairs, settle the spelling-rule
  pairs, gather titles, neighbourhood and excerpts, and size the
  batches. Pass two judges kind after kind. Nothing is asked before
  the whole plan exists.
- Progress: phase scanning before the scan, phase evidence per kind
  and per read, one phase judging with requestsPlanned, pairsTotal and
  estimatedTokens for the whole review, one report per answered
  request (requestsDone, pairsJudged, the running token total,
  failedRequests, retries, kind, and the line naming the next
  request), phase escalating when an unsure pair is asked again, phase
  finishing before the groups are built. A split answer adds its
  halves to requestsPlanned in the report of the request that split,
  so the bar never goes backwards; the escalation adds its own
  requests and pairs the same way. Elapsed time and the estimate stay
  with the job, which derives them.
- Stopping: control.signal is read before every read, every request
  and the second round, and travels to the provider, so a stop lands
  on a request in flight. A request that dies on the signal is a stop,
  not a failure: no failed request, no retry, and no "unsure" — the
  pairs stay without a verdict, so they cannot become a group. A
  stopped review returns what it reached; it never throws.
  aiReview now always carries stopped, stopReason (null; the job fills
  it in) and pairsNotJudged.
- Token budget: one running total for the whole review, folded from
  the provider's usage or, for a provider that reports none, from the
  measured prompt plus the estimated answer, so the counter and the
  budget work for every provider (aiReview.tokens keeps reporting only
  what a provider stood behind). When control.tokenBudget is reached
  the review calls control.stop('token-budget') and behaves as
  stopped.
- Logs: "review stopped (user|token-budget|idle): N of M request(s)
  made, P pair(s) not judged, T token(s)." and "token budget 200000
  reached after N request(s) (T tokens)."; the start, request and
  finish lines are unchanged.
- services/duplicateReviewJobService.js: the control object gains
  stopReason(), the one seam the judge needs to name the reason in its
  own log line.
- reviewPairs(pairs, options) additionally takes plan, systemPrompt
  and tracker from reviewScan; a caller that brings none gets what it
  always got.

Testing
- node scripts/run-tests.js --all: 99 registered, 92 pass, 7 skip
  offline, 0 fail (the baseline of the branch).
- tests/test-entity-match-ai-service.js: 13 new cases (64 total) —
  the plan before the first request for one and for two kinds, the
  split and the escalation raising the plan, a failed request still
  moving the bar, a stop between requests and a stop in flight, the
  token budget, a provider without usage, an already aborted signal, a
  review without a control, the report carrying nothing the job
  derives, and the signal reaching all four providers. The one moved
  expectation is the deep-equal on aiReview, which now names the three
  new fields.
- tests/test-duplicate-review-job.js: one case for stopReason().
- A real run through the job service over a fake archive: a review
  that runs through, the same one stopped after request 2, and the
  same one against a token budget.
- eslint and prettier on every touched file.

Impact
The page can show a bar with a denominator, an estimate and a running
token count from the first request, and a stop costs at most one
request that is already in flight. A review without a control object
behaves exactly as before, so the synchronous route is untouched until
it is moved onto the job.

Upstream Status
Not applicable: the Duplicates page and its AI review do not exist
upstream.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): watch and stop the AI review from the page

Background

A review of a drifted archive is many model requests in a row. Until now
"Ask the AI" was one POST that answered when everything was over: a spinner,
no idea how many requests were still coming, no idea what it cost, and no way
out but reloading the tab — which left the model running. The job service of
the contract commit made the review watchable and stoppable on the server;
this wires the routes and the page onto it.

Changes

routes/setup.js (Duplicates block only)
- parseAiReviewRequest(body) holds the validation both entry points share, so
  the synchronous route and the job route can no longer drift apart.
- POST /api/duplicates/ai-review/jobs starts a review and answers
  202 { job }; while one runs it answers 409 with that running job, so a
  second tab attaches instead of failing.
- GET /api/duplicates/ai-review/jobs/current answers { job } or { job: null }
  and counts as watching the review.
- GET /api/duplicates/ai-review/jobs/:id answers { job, result }, 404 for an
  unknown id, and also counts as watching.
- GET /api/duplicates/ai-review/jobs/:id/events streams AiReviewJobEvents
  (text/event-stream, no-cache, X-Accel-Buffering: no, keep-alive, flush after
  every write), a ": keep-alive" comment every 15 s, and ends after done,
  stopped or failed. An unknown id is a JSON 404 before any stream header.
- POST /api/duplicates/ai-review/jobs/:id/stop answers { job }; stopping a
  finished review is a 200 no-op.
- POST /api/duplicates/ai-review now starts that same job and waits for it: a
  stopped review answers 200 with the verdicts it reached, a failed one keeps
  the judge's status, and a second request while one runs is a 409. It
  subscribes for the duration so the idle stop cannot end a review somebody is
  waiting for.
- @swagger for every new route; OPENAPI/openapi.json regenerated.

views/duplicates.ejs, public/js/duplicates.js, public/css/pages/duplicates.css
- A progress panel in the AI row (#dupAiProgress): bar (#dupAiProgressFill,
  indeterminate while the plan is unknown), message, counters
  ("Request 3 of 8 · 40 of 96 pairs · 12.4k of 200k tokens"), time
  ("about 40 s left · 1:24 elapsed") and a Stop button (#dupAiStopBtn). After
  the end it keeps one outcome line and hides on the next scan or review.
- askForVerdicts() starts the job, follows it through EventSource and falls
  back to polling the job every 2 s when the stream breaks. It resolves
  { aiReview, stopped }; all three AI paths honour `stopped` — the notice is
  shown and neither the guided dialog nor the proposal opens.
- On load the page asks for the current job and re-attaches to one that is
  still running; a finished one is left alone.
- Pure helpers formatTokens, formatEta, formatElapsed, progressPercent and
  stopNotice word the numbers; the UI test evaluates them directly.

Testing

- node scripts/run-tests.js --all: 99 registered, 92 pass, 7 skip offline
  (unchanged); duplicates-endpoints 20 -> 30 cases, duplicates-ui 48 -> 57.
- eslint, prettier, stylelint clean on every touched file; regen-openapi
  leaves no diff.
- Reviewed in a browser against a throwaway server with a judge that reports
  eight requests: mid-run, stopping, stopped and done, desktop and phone,
  light and dark, no console errors. A page loaded while a review runs
  re-attached and rendered its result; with the event stream blocked the same
  review came home through eight polls.

Impact

The Duplicates page shows what a review is doing and costing and can end it;
the verdicts already reached are kept. The synchronous route keeps its request
and response, so an API client sees no change beyond the new 409 while a
review runs.

Upstream Status

Not applicable — the Duplicates feature does not exist upstream.

* fix(duplicates): a late Stop answer no longer paints over the outcome; changelog for the review job

Background
In the browser smoke test of the round, a stop pressed after the first
answered request ended the job before the stop request itself answered.
The page then rendered that answer, a snapshot from the stopping moment,
over the outcome line and restarted the elapsed clock, so the panel read
"Stopping after the current request…" next to a finished review.

Changes
- public/js/duplicates.js: stopReview() renders the stop answer only
  while the same job is still followed and still live.
- tests/test-duplicates-ui.js: one case that pins the guard (57 -> 58).
- config/changelog.js: three entries for the round under the current
  release (the review as a job with progress and Stop, the token budget
  and the idle stop as settings, the plan before the first request).

Testing
- node scripts/run-tests.js --test duplicates-ui: 58 passed.
- Browser smoke against a fake Paperless-ngx and a slowed-down fake
  provider: Stop during request 2 leaves "Stopped after 1 of 5 requests
  · 1 of 5 pairs judged · 1.1k tokens" on the panel, the verdicts
  reached stay on the cards, no dialog opens; the proposal path stops
  the same way; a token budget of 2500 stops the review after 3
  requests with the budget named in the notice and the log; a page
  reloaded during a review re-attaches and renders the result; the
  round-6 walkthrough (scan, merge, undo, dismiss, merge by hand, batch,
  guided review, proposal, plain review) passes unchanged.
- eslint and prettier on the touched files.

Impact
Visual only; the review itself was stopped correctly before the fix.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): contract for a judge that measures the model, streams its answers and thinks only on request

Background
On a real archive with a hosted Qwen model the first review request
asked about 25 pairs, ran for 103 seconds and died at its own answer
cap: the model spent the whole budget thinking before the first
verdict, the cut-off text was thrown away, and the page showed nothing
but a ticking clock for two minutes. Three scans of 13 seconds each
came before that. Decisions for this round: the judge measures the
model on a small first request and sizes every later request to a
target duration; the providers stream the answer so the page moves
inside a request and a cut-off answer keeps its verdicts; thinking is
off for the judge unless the operator switches it on; the review
reuses a fresh scan instead of scanning again.

Changes
- config/config.js: DUPLICATES_AI_THINKING (no) and
  DUPLICATES_AI_REQUEST_SECONDS (30).
- schemas.js, OPENAPI/openapi.json: AiReviewProgress gains
  requestPairs, requestAnswers, requestTokens, thinking, batchSize and
  calibrated; the phase list gains warming-up.
- services/duplicateReviewJobService.js: the new progress fields, the
  warming-up phase, and a time estimate from the share of pairs done
  (answers streamed in count), because the batch size may change after
  the warm-up.
- services/aiGenerateOptions.js: reasoningEnabled(options) and
  progressHandler(options), the two switches the judge will send and
  the providers will read, with the GenerateTextProgress shape and the
  partialText rule for cut-off answers.
- scripts/run-tests.js, tests/test-ai-provider-streaming.js: a
  registered placeholder for the provider streaming test.

Testing
- node scripts/run-tests.js --all: 100 registered, 93 pass, 7 skip
  offline, 0 fail.
- eslint and prettier on every touched file; regen without drift.

Impact
Nothing reads the new switches yet; the implementation follows.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* test(helpers): fake OpenAI-compatible and Ollama servers on ephemeral ports

* feat(providers): stream the answer, report progress, keep the cut-off text

Background

A hosted model behind the custom provider spent 103 seconds and the whole
3200-token completion cap on one AI-review request, then threw "the answer hit
a token limit" and dropped every character it had produced. Nothing was visible
while it ran, nothing survived the throw, and the batch was split and paid for
again from the beginning. Two causes: the four provider services always sent a
non-streaming request, so there was nothing to watch; and
assertCompletionNotTruncated() threw before anyone read the content, so the
prefix was thrown away. On top of that the model thinks before it answers, and
on a server that separates thinking from answering the reasoning arrives as
reasoning_content deltas that no provider knew about.

Changes

- services/aiGenerateOptions.js: the shared streaming machinery.
  stripReasoningText() removes <think> blocks, including one a cut-off left
  open. createProgressCollector() assembles a streamed answer, splits reasoning
  from answer incrementally (a marker may be cut across two chunks), counts the
  completion tokens from a usage chunk or estimates them over everything
  produced, reasoning included, and reports at most once per 100 ms plus one
  final report that says done. consumeChatCompletionStream() and
  runChatCompletionStream() are the OpenAI-compatible half: read the stream,
  finish before any throw, and turn a cut-off or a stop into an error that
  carries what arrived. isAbortError()/abortedGenerationError() give a stopped
  request one name across the SDK, axios and fetch.
- services/serviceUtils.js: estimateTokenCount() (the same character-based
  estimate, on a length) and an optional fourth argument on
  assertCompletionNotTruncated() that puts partialText on the error.
- services/openaiService.js, services/customService.js,
  services/azureService.js: generateText() streams when the caller hands in
  onProgress, with stream_options: { include_usage: true } on OpenAI and the
  custom provider and on Azure only from API version 2024-06-01, where the API
  takes it. Without a handler the body is exactly what it was. Both paths strip
  reasoning from the answer and attach the prefix to a truncation error; an
  abort throws an AbortError with partialText.
- services/customService.js: reasoning: false adds
  chat_template_kwargs: { enable_thinking: false } and, for a model name
  matching /qwen/i, that family's soft switch on its own line at the end of the
  user message; reasoning: true sends enable_thinking: true and no soft switch;
  without the option nothing new is sent.
- services/ollamaService.js: generateText() reads NDJSON from an axios
  responseType: 'stream' response, keeps the tail of a socket read until its
  newline arrives, treats the thinking field as thinking, and stops reading the
  moment the signal aborts. reasoning: false/true sends think and overrules
  OLLAMA_THINK; without the option OLLAMA_THINK still decides. The cut-off
  check the analysis path has always run now runs here too, with partialText,
  and a failure no longer erases a token count that was already measured.
- tests/helpers/fake-openai.js, tests/helpers/fake-ollama.js: real HTTP servers
  on ephemeral ports, scripted per request (content chunks, reasoning chunks,
  finish reason, usage chunk or none, per-chunk delay, non-streaming answers
  from the same script), recording every request body and whether the client
  hung up early.
- tests/test-ai-provider-streaming.js replaces its placeholder with 22 cases.

Testing

- node tests/test-ai-provider-streaming.js: 22 passed, 0 failed; run five
  times, no flake.
- node scripts/run-tests.js --all: 93 passed, 7 skipped offline, 0 failed —
  the same numbers as before this change.
- npx eslint and npx prettier --check on every touched file: clean.
- A throwaway process reproduced the reported failure against the fake: the
  progress reports show thinking first with no text, then the answer growing,
  then one done report with the exact token count from the usage chunk, and the
  throw carries the 131 characters of JSON that had arrived.

Impact

No caller behaves differently unless it asks: without onProgress the request
body is byte for byte what it was, and the round-7 provider cases assert that.
What does change for every caller of generateText(): a <think> block no longer
reaches the returned string, a truncation error now carries partialText, an
abort now throws under the name AbortError, and Ollama's generateText() now
raises the same truncation error the analysis path raises instead of returning
a half-written answer. The document analysis path is untouched.

Upstream Status

Not upstream. Streaming, progress reporting, the partial text of a cut-off
answer and the thinking switch do not exist in clusterzx/paperless-ai.

* feat(duplicates): the progress panel moves inside a request and names the measured batch size

Background

A review of a large archive is a handful of long model requests, and the
panel only moved between them. One request took 103 seconds while the page
showed "request 1 of 4 - 0 of 82 pairs" and a ticking clock, so for minutes
at a time the only honest reading of the page was "nothing is happening".
The judge now measures the model on a small first request, sizes every later
one to a configured number of seconds, and streams the answers as they
arrive, which gives the page three things it never had: answers inside a
request, a warm-up phase, and a model that says when it is thinking.

Changes

Page (views/duplicates.ejs, public/js/duplicates.js,
public/css/pages/duplicates.css):

- progressPercent() counts pairs whenever the plan knows them, the answers
  of the running request included, and falls back to requests only while no
  pair count exists. The bar therefore moves during a request instead of
  jumping once per request.
- progressCountsText() gained the "7 of 10 answers" part, printed only while
  a request is in flight and capped at the size of that request.
- progressTimeText() says "measuring the model" in the warm-up and "the
  model is thinking" while the model writes reasoning, instead of a clock
  that cannot move; an estimate the job already made is still shown next to
  either.
- New #dupAiProgressNote line under the counts, written by the new
  progressNoteText(): "4 pairs per request while the model is measured"
  before the measurement, "9 pairs per request, sized from the model's
  answers" after it, empty while no size is known. A zero-width space holds
  its row open for as long as a review runs (.dup-progress--live), so the
  stats tiles below do not jump the moment it fills.
- .dup-progress__fill--thinking pulses while the model reasons, slower than
  the indeterminate band, and is switched off under prefers-reduced-motion.
- The outcome line and the "Model requests" tile both name the batch size the
  review settled on.
- New htmlReviewFailure(): all three AI paths report a failed review with the
  judge's own message plus one link, "Open the Duplicates settings", to
  /settings#duplicates-tab.

Settings (views/settings.ejs, public/js/settings.js, routes/setup.js):

- Two fields close the Duplicates section: the switch "Let the judge think"
  (DUPLICATES_AI_THINKING, default off) and the number "Seconds per model
  request" (DUPLICATES_AI_REQUEST_SECONDS, 5-300, default 30). GET, POST with
  the usual clamping and keep-the-previous-value behaviour, the @swagger
  request body, ENV_EXPORT_GROUPS and the two "Managed by ENV" selectors.

Route:

- GET /api/duplicates/scan passes fresh: true; a scan somebody pressed a
  button for must not be answered from a cache.

OPENAPI/openapi.json regenerated.

Testing

- node scripts/run-tests.js --all: 93 passed, 7 skipped offline, 0 failed
  (unchanged from the baseline of this round).
- duplicates-ui 58 -> 66 cases: the bar with streamed answers and without a
  pair count, the counts line with and without a running request, the three
  wordings of the time line, the note line, the outcome line with a batch
  size, the panel ids and the thinking class, the settings link of the failed
  notice, and the stylesheet's pulse with its reduced-motion rule.
- settings-duplicates-section 11 -> 15 cases: both fields render with their
  values and hints, the POST round trip, clamping (2 -> 5, 999 -> 300), the
  cleared field keeping the previous value, the switch spellings, the export
  group order and the two selectors.
- duplicates-endpoints 30 -> 31 cases: the scan route hands fresh: true to
  the service.
- eslint, prettier and stylelint clean on every touched file; regen-openapi
  leaves no drift.
- Looked at in Chromium against a throwaway server on port 3403 that walks a
  scripted review through the warm-up, a thinking stretch and a request whose
  answers climb 0 -> 10: desktop and phone, light and dark. The stats tiles
  sit at the same offset before and after the note line fills.

Impact

The panel reports inside a request rather than between requests, and names
both the warm-up and the measured batch size, so a review that takes minutes
per request looks like work rather than a hang. A failed review points at the
setting that would have prevented it. Nothing scans, judges or merges on its
own; the two new settings are read at startup like the rest of the section.

Upstream Status

Not applicable - the Duplicates page does not exist upstream.

* feat(duplicates): measure the model, size every request to it, and reuse a fresh scan

Background

Asking the AI about a scan of the user's archive did not work on their
instance. The judge sent 25 pairs with a completion cap of 3200, the hosted
model thought before it answered and spent all 3200 tokens on the thinking,
and 102 seconds later nothing had been judged. The answer was then split into
13 + 12, which buys nothing: the thinking does not get cheaper with fewer
pairs. Meanwhile the page showed "request 1 of 4 · estimating…" for two
minutes, because a request only reports when it is over. The user pressed
Stop.

The same run also scanned the archive three times inside 50 seconds — the
page's scan, the AI proposal's and the review job's — 1359 tags and 13
seconds each, with nothing changing in between.

Changes

services/entityMatchAiService.js

- Thinking off by default. Every judge request carries
  `reasoning: config.duplicatesAiThinking === true`, so a reasoning model
  answers instead of deliberating unless the operator asked for it. Nothing
  else about the prompt changed.
- A warm-up instead of a guess. The first request of a review whose model has
  not been measured asks about at most WARMUP_PAIRS (4) pairs with a
  deliberately generous cap (RESPONSE_TOKENS, the flat estimate or
  WARMUP_MIN_CAP, whichever is largest, bounded by the context window). It is
  announced under the phase `warming-up` with the message "Measuring the model
  with a small first request…", `calibrated: false` and the size it will use;
  the plan reported with it is provisional and the log says so.
- Sizing from the measurement. Every answered request yields tokens per pair
  (thinking included) and tokens per second, each smoothed by half against the
  measurement before it. From them:
  `batchSize = clamp(floor(requestSeconds × tokensPerSecond ÷ tokensPerPair), 1, batchSize())`
  and `cap = ceil(tokensPerPair × batchSize × 1.5) + TOKENS_OVERHEAD`, both
  bounded by the context window as the batch planning bounds them.
  `requestSeconds` is DUPLICATES_AI_REQUEST_SECONDS, at least 5, 30 by
  default. A batch is now taken off the front of a queue rather than chunked
  up front, because its size changes while the review runs.
- The plan settles after the warm-up. `requestsPlanned` and `estimatedTokens`
  are re-derived from the pairs nobody has asked about yet and reported with
  `batchSize` and `calibrated: true`, so the page's denominator stops moving.
- Truncation: raise before halving. A cut-off answer that salvaged nothing is
  asked again with twice the cap (the warm-up gets the whole window at once),
  and only when that bought nothing — or the cap is already at the window's
  bound — is the batch halved as before. A warm-up that does not fit even then
  ends the review as failed with a message the operator can act on, naming
  DUPLICATES_AI_THINKING and TOKEN_LIMIT. A single pair at the bound keeps the
  old "unsure" and its log line.
- The cut-off text counts. All four providers now attach `error.partialText`,
  so the salvage path runs for every one of them; a salvaged request counts
  its verdicts in `pairsJudged` and in the tracker. Two comments that still
  said only Ollama returns half-written answers were rewritten.
- Progress inside a request. With a progress sink the provider is asked to
  stream (`onProgress`). Each report, at most every 250 ms, carries
  `requestPairs`, `requestAnswers` (the complete verdict objects counted off
  the streamed text), `requestTokens`, `thinking` and the running token total:
  "The model is thinking… (640 tokens so far)" while it thinks, otherwise the
  request line with " · 7 of 10 answers" appended. The report that counts the
  request resets all four. A review nobody watches sends the plain request it
  always sent.
- Calibration memory. The last measurement per model name lives on the
  singleton; a review that finds one starts sized from it, skips the warm-up
  and says so in the log. A measurement taken with thinking on is never reused
  with thinking off. `resetCalibration()` for tests.
- Logs: the finish line says "N pair(s) planned" (the number is the plan), the
  batch-size line is marked provisional until the model is measured, and the
  split line says whether the cap was raised or the batch halved.

services/duplicateMergeService.js

- `scan()` keeps its result per set of options (kind, threshold,
  includeDismissed) for SCAN_CACHE_MS (60 s) and answers the next identical
  request from it with one log line instead of the start and finish lines.
  `fresh: true` skips and refills it; the page's Scan button sends it.
- A merge, an undo, a dismissal and `restoreDismissal()` empty the cache. A
  dismissal deleted through the route, which talks to the model directly, is
  caught by a fingerprint (row count and highest id per kind) checked on every
  hit — one local SELECT against a 13-second scan.
- `reviewScan()` calls `scan()` without `fresh`, so a proposal made right
  after the page scanned costs no second scan.

Testing

- node scripts/run-tests.js --all: 93 passed, 7 skipped offline, 0 failed
  (100 registered), unchanged from the baseline.
- tests/test-entity-match-ai-service.js: 65 -> 80 cases. New: thinking off and
  on; the warm-up's size, cap, phase and message; the sizing math on a fixed
  usage and duration; the request seconds and their floor; the context window
  bounding size and cap; smoothing; the plan and estimate recomputed after the
  warm-up; calibration reused, not reused across the thinking switch, reset; a
  warm-up that cannot fit ending the review with its message; a truncated
  answer with partialText salvaged and counted; a streamed request reporting
  thinking, then answers, then clearing itself; an unwatched review not
  streaming; a review served from the page's scan.
- tests/test-duplicate-merge-service.js: 17 -> 22 cases. New: cache hit, other
  options and `fresh` missing it, expiry, invalidation by merge, undo, dismiss
  and restore, and a dismissal removed behind the service.
- Changed expectations, all from the raise-before-halve rule: the truncation
  cases now see every size asked twice (once, once with twice the cap) before
  it is halved, the single pair is asked twice before it ends as unsure, and
  the planning cases see the `warming-up` phase where they saw `judging`.
- Two demo runs against a fake model at 30 tokens/s: thinking off, 12 pairs —
  warm-up 4 pairs in 20 s (600 tokens, 150 per pair), then requests of 5 pairs
  at 25 s, 4500 tokens, 60 s in total. Thinking on — warm-up 4 pairs in 40 s
  (1200 tokens, 300 per pair) and requests of 2 pairs at 30.04 s, the
  configured length.

Impact

The first request of a review is seconds rather than minutes, every later one
lasts about as long as the operator asked, and the page shows the model
thinking and answering while it happens instead of a still bar. A review of a
model that was measured before starts at full size. Three scans of one archive
become one. Nothing runs on its own and no verdict changed: the prompt, the
rules and the shape of an answer are what they were.

Upstream Status

Not applicable — the Duplicates feature does not exist upstream.

* fix(duplicates): a review never asks for a fresh scan of its own

reviewScan() drops a `fresh` flag its caller may carry instead of passing it on, so a route that forwards the page's scan options cannot make the review scan the archive a second time.

* fix(duplicates): the yes/no switches of the judge read 'yes', and a small batch is not starved after a thinking one

Background
The browser smoke test of the round ran the thinking scenario and the
judge kept saying "thinking off" although DUPLICATES_AI_THINKING=yes
was set. config/config.js normalises every yes/no setting to the
strings 'yes' and 'no' (parseEnvBoolean), while three readers in the
judge asked Boolean() or === true: the thinking switch could never be
turned on, and the review and excerpt switches could not be turned off
('no' is a truthy string). The second finding: a thinking model pays a
fixed price per request, so a one-pair request sized by pairs alone
after a four-pair warm-up got a cap the same thoughts did not fit; the
judge recovered by raising the cap, at the cost of one request.

Changes
- services/entityMatchAiService.js: switchedOn() accepts 'yes' and a
  boolean true; isEnabled(), excerptsEnabled() and thinkingEnabled() use
  it. The cap never drops below the largest completion the model has
  produced in this review plus a quarter (CAP_FLOOR_FACTOR), and that
  floor is remembered with the calibration.
- tests/test-entity-match-ai-service.js: one case per finding (82
  cases), the sizing case expects the remembered floor.
- config/changelog.js: three entries for the round under the current
  release.

Testing
- node scripts/run-tests.js --test entity-match-ai-service: 82 passed.
- Browser smoke against a fake Paperless-ngx and a fake provider that
  streams, thinks on request and honours max_tokens: thinking off, the
  fake never thought, warm-up 4 pairs, 59 tokens/s measured; thinking
  on, the panel showed the thinking state, no request hit the token
  limit any more; Stop, re-attach, token budget and the round-6
  walkthrough unchanged.

Impact
DUPLICATES_AI_REVIEW=no and DUPLICATES_AI_EXCERPTS=no now do what they
say; DUPLICATES_AI_THINKING=yes now reaches the model.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): contract for the creation guard, the semantic sweep, unused objects, renames and a remembered calibration

Background
Round 9 of the Duplicates feature, six points the user picked: stop
the drift where it starts (document analysis creating "Rechnungen"
next to "Rechnung"), let the model find synonyms and translations the
string matcher cannot, list and delete unused objects with undo, name
the survivor of a merge, keep the judge's measurement of a model across
restarts, and scan faster. Decisions: only hard matcher tiers map a
new name onto an existing one (case, umlauts, legal form, plural, word
order), typo-like matches are logged …
…ps (#335)

* feat(duplicates): contract for a targeted AI review

Background
With many groups at 94 to 96 percent the user wants to say "everything
from 95 percent up: ask the AI, show me its view, then merge". The
review must therefore be able to judge only chosen groups and skip the
band of near-misses.

Changes
- schemas.js, OPENAPI/openapi.json: groupIds, minConfidence and
  includeCandidates on DuplicateAiReviewRequest.

Testing
- node scripts/regen-openapi.js: no drift after the commit.

Impact
Request fields only; the implementation follows.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): targeting counters in the AI review result schema

Background
A targeted review reports which groups it judged and which it left
without a verdict; the page shows that.

Changes
- schemas.js, OPENAPI/openapi.json: targeted, groupsJudged and
  groupsSkipped on DuplicateAiReviewResult.aiReview.

Testing
- node scripts/regen-openapi.js: no drift after the commit.

Impact
Documentation of three informational fields.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): let the AI review be pointed at a few groups

Background

An archive with hundreds of correspondents produces dozens of groups at
94, 95 and 96 per cent, and asking the model about all of them costs a
lot to answer a question about a handful. The page needs to select the
groups it is about to merge, ask about those, and keep rendering the
rest of the scan while it does.

Changes

- entityMatchAiService.reviewScan() takes three options that narrow what
  is asked, never what comes back:
  - groupIds: only these scan groups are judged. Every other group is
    still in `groups`, as the scan produced it, with `aiVerdict: null` on
    the group and on every member and `source: 'scan'`. An id this scan
    does not know is ignored and logged once with the count.
  - minConfidence: only groups scoring at least this much are judged;
    together with groupIds both conditions have to hold.
  - includeCandidates (default true): false leaves the band of
    near-misses out entirely, so `candidates` is 0 — and with no band
    the entity list per kind is not read either, which is the cheap part.
- _pairsForKind() takes the set of group ids to judge. A group left out
  contributes no pairs but its member pairs still count as "inside one
  group", so it cannot reappear as a candidate.
- The result reports the targeting: aiReview.targeted, .groupsJudged and
  .groupsSkipped. The start line of the log names it as
  "judging 1 of 4 group(s) (min confidence 0.95, 3 ids), band skipped",
  the closing line adds the two counters. An untargeted review logs and
  behaves exactly as before.
- POST /api/duplicates/ai-review validates and passes the three fields
  through: groupIds an array of at most 500 non-empty strings,
  minConfidence a number in [0.5, 1], includeCandidates a real boolean
  (the string "false" is a 400). An option the request does not mention
  is left out of the service call, so an untargeted request reaches
  reviewScan() with the same object it did before.
- Swagger description of the route and the 400 reason updated,
  OPENAPI/openapi.json regenerated.

Testing

- node scripts/run-tests.js --all -> 90 passed, 7 skipped offline,
  0 failed (97 registered), unchanged against the baseline.
- entity-match-ai-service: 28 -> 34 cases. Six new ones on a fixture
  whose four groups sit exactly on the matcher tiers (1, 0.98, 0.95,
  0.9) plus one pair in the band: groupIds judges only what it names,
  minConfidence filters, includeCandidates: false skips the band and
  reads no second entity list, groupIds and minConfidence combine while
  unknown ids are ignored, an empty selection costs no request, and the
  log lines. The existing aiReview assertion gained the three new fields.
- duplicates-endpoints: 16 -> 19 cases. The three fields reach the
  stubbed reviewScan unchanged, an untargeted request still carries
  nothing extra, ten malformed targeting bodies are 400, and 500 ids are
  accepted while 501 are not.
- Manual run against the real route with a fake store and a fake
  provider: full review 5 pairs / 1 request, minConfidence 0.95 without
  the band 3 pairs, two selected ids (one unknown) 1 pair, and every
  unjudged group back with null verdicts.
- eslint, prettier and the OpenAPI drift check clean on the touched
  files.

Impact

Additive. A review that says nothing about the three options behaves and
logs as before. The page can ask about the groups it selected before a
batch merge; a dozen groups without the band are one or two model
requests instead of the whole archive. schemas.js still has to gain
targeted, groupsJudged and groupsSkipped on DuplicateAiReviewResult.

Upstream Status

Not applicable: the Duplicates feature is next-only.

* feat(duplicates): sort, select by confidence, and a guided review before merging

Background
----------
On a grown archive a scan answers with dozens of groups that all read 94, 95,
96 percent, and the page offered no way to act on that number: every group had
to be judged by eye, one tick at a time. The three presets were the only
thresholds available, so "everything above 95" was not a question the page
could be asked. And where the AI review existed it judged the whole result
list, which is the most expensive way to ask about the five groups the user
actually cares about.

The rule this follows: the AI is an addition, never a condition. Every flow
below works end to end with the review switched off; with it on, the guided
path is one more button beside the one that was already there.

Changes
-------
Results toolbar (#dupResultsBar), above the selection bar, shown once a scan
has groups:
  - "Sort by" (#dupSortSelect): confidence, documents, target name (locale
    compare), kind then confidence. It moves the DOM nodes instead of
    re-rendering, so a card keeps its target, its source ticks, its selection,
    its verdict and its busy state; the two blocks (scan groups, AI
    candidates) are sorted separately and the divider stays between them.
  - "Select >=" (#dupMinConfidence, #dupSelectMinBtn, #dupMinConfidenceCount):
    ticks every selectable group at or above a whole percent and unticks the
    rest, with a live count of what the click would do.
Custom scan threshold: a fourth sensitivity option "Custom" reveals a number
field (#dupThresholdCustom); the scan and both review paths send that percent
divided by 100. The three presets are unchanged.
Confidence breakdown under "Groups found" (#dupStatBuckets): ">=95 %: A .
90-95 %: B . <90 %: C", counted from the cards after a scan and after a review.
Guided flow (#dupReviewThenMergeBtn, rendered only where the review exists):
asks the model about exactly the ticked groups (groupIds, includeCandidates:
false), puts the verdicts on the cards as a full review does, then shows them
once in a wide dialog - one row per group with target, sources, documents, the
verdict chip and the reason, a live "N of M ticked . K documents" foot line and
the copy-rule check. Ticked rows are merged with the batch machinery; an unsure
or different verdict only comes up unticked and never blocks anything, and what
stays unticked stays selected on the page.
"Merge selected" keeps its place and its weight, first in the bar and without a
model anywhere in its path; its dialog names the guided path in one faint line,
and only where that path exists.
Sort, confidence, sensitivity and the custom threshold are remembered in
localStorage (dup.sort, dup.minConfidence, dup.sensitivity,
dup.thresholdCustom) through two try/catch helpers.

Testing
-------
node scripts/run-tests.js --all -> 90 passed, 7 skipped offline, 0 failed
  (unchanged from the branch baseline).
tests/test-duplicates-ui.js: 25 -> 38 cases. New: the toolbar ids and their
  order, the custom threshold field, the stats breakdown, the guided button
  only with the review, the whole page without the review, the toolbar ids in
  the script, sorting as a DOM move, "Select >=", the wrapped localStorage
  access, the guided request (groupIds / includeCandidates: false) and that
  "Merge selected" never touches the review endpoint, the review dialog markup,
  the tip line, the new CSS classes. Changed: the sensitivity options are read
  from #dupSensitivity alone and now end in "custom"; the undo promise and the
  confirm dialogs are counted one higher each, because the review dialog merges
  and therefore makes the same promise.
Reviewed in a browser against a throwaway mock (twelve groups over 88-100 %, a
  review that honours groupIds): 27 screenshots at 1280x900 and 390x844, light
  and dark, 0 px horizontal overflow everywhere, plus a 31-check behaviour
  probe (guided request, verdict ticks, sorting keeping picks and the divider,
  persistence, a refused review, and the whole page with the review off).

Impact
------
Page only. No route, service, schema or config was touched, so the OpenAPI
spec is unchanged. An instance without the AI review renders and behaves
exactly as before plus the toolbar and the custom threshold. The request the
guided path sends uses fields the contract already carries; a server that
ignores them reviews everything, which the page renders correctly.

Upstream Status
---------------
Not applicable - the Duplicates page does not exist upstream.

Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* docs(duplicates): changelog entries for sorting, select by confidence and the guided review

Background
Round 5 answered the second feedback from a real archive: select by a
number, let the model judge exactly those groups, read its verdicts in
one dialog, merge what stays ticked; sort the groups; a custom threshold.

Changes
- config/changelog.js: two entries in the current v2026.09.01 block.

Testing
- node scripts/run-tests.js --test changelog-releases: passed.

Impact
Documentation only.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): contract for evidence-based verdicts and the AI proposal

Background
A real archive produced "Kontoauszug" / "Kontoumzug": the matcher called
it a spelling distance, the prompt allowed "an obvious typo" as a reason
for same, and the model, seeing names and titles only, agreed. Both are
different things. The judge needs stricter rules and, for pairs linked by
spelling alone, a look at what the documents are about, at a bounded
cost.

Changes
- config/config.js: DUPLICATES_AI_EXCERPTS (default yes),
  DUPLICATES_AI_EXCERPT_CHARS (300), DUPLICATES_AI_EXCERPT_DOCUMENTS (2).
- schemas.js, OPENAPI/openapi.json: AiVerdict gains basis and confidence;
  DuplicateAiReviewRequest gains withExcerpts; aiReview reports excerpts.

Testing
- node scripts/run-tests.js --area duplicates: 6/6; regen without drift.

Impact
Settings and schema only; the implementation follows.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): judge model override and the verdict source in the contract

Background
Decisions for round 6: the matcher's hard tiers settle a pair without the
model, unsure pairs are asked once more with excerpts, and the judge may
run on a stronger model of the same provider.

Changes
- config/config.js: DUPLICATES_AI_MODEL (optional, judge only).
- schemas.js, OPENAPI/openapi.json: AiVerdict.source (model or
  spelling-rule); aiReview.escalated and aiReview.spellingRules.

Testing
- eslint and prettier on the two files; regen without drift.

Impact
Settings and schema only; the implementation follows.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(settings): make every DUPLICATES_ setting editable in its own section

Background
The AI review of the Duplicates page arrived with seven environment
variables and no way to change any of them from the interface. Editing a
container environment and recreating the container is the wrong price for
"try a stronger model for the judge" or "ask about fewer pairs per
request", and the settings page is exactly where those knobs belong.
config/config.js already reads all seven; only the front door was missing.

Changes
- views/settings.ejs: a "Duplicates" section (id="sec-duplicates") inside a
  new duplicates-tab block between the AI sections and OCR, with a nav entry
  in the desktop section nav (icon i-merge) and in the mobile one, in the
  same order as the page. Seven fields, each with a hint that says what the
  value does and what its default is: the AI review switch, the judge model,
  pairs per request, the candidate floor, the excerpt switch, excerpt length
  and documents per entry. Switches go through partials/settings-switch, so
  the hidden yes/no input the POST route reads exists as it does everywhere
  else.
- routes/setup.js: GET /settings passes the seven values (env first, the
  defaults of config/config.js as fallback) in the config object the view
  reads; POST /settings destructures the seven camelCase body keys,
  normalises them and writes them into updatedConfig, so setupService
  .saveConfig persists them with the rest. Numbers are clamped to their
  range; a value that is not a number, or a cleared field, keeps what is
  configured now instead of resetting to the default. The swagger body
  schema documents all seven, and the .env export gained a "Duplicates"
  group between "AI behaviour" and "External API".
- public/js/settings.js: the seven selector to env-key entries, so the
  "Overwritten" and "Managed by ENV" marking covers these fields too.
- OPENAPI/openapi.json regenerated.
- tests/test-settings-duplicates-section.js, registered in the
  observability area.

Testing
- node scripts/run-tests.js --all: 98 registered, 91 passed, 7 skipped
  offline (was 97/90/7). The new test covers the rendered section and its
  nav position, the seven inputs and their values, the POST round trip,
  clamping, the keep-the-previous-value case and the .env export group.
- npx eslint / npx prettier --check --ignore-unknown on every touched file.
- node scripts/regen-openapi.js leaves OPENAPI/openapi.json unchanged.
- Looked at the page in Chromium at 1440x1000 and 390x844 against a
  throwaway server outside the repository; no console errors, the section
  reads like the rest of the page and stacks on the phone.

Impact
Operators can change every DUPLICATES_ value from the settings page. The
existing restart-after-save is what makes them take effect; no new
mechanism. Values injected by the container still win and are shown as
managed, as for every other field. Nothing outside the settings page
changes: no route, service or default behaviour of the Duplicates page
itself is touched.

Upstream Status
Fork-only. The Duplicates page does not exist upstream.

Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): judge spelling-only pairs on evidence, not on distance

Background
A real archive produced "Kontoauszug" next to "Kontoumzug": the matcher
called it a spelling distance, the prompt allowed "an obvious typo" as a
reason for same, and the model, seeing two names and three titles, agreed.
Two different things. The judge needed stricter rules, evidence for the
pairs where spelling is the only link, and a way to say how sure it is and
on what grounds — all without opening a large context window on every pair.

Changes
- entityMatchAiService: the system prompt refuses a small spelling distance
  as a reason of its own ("Kontoauszug" / "Kontoumzug", "Miete" / "Mieter",
  "Bahn" / "Bank"), allows a misspelling only when one spelling is not a
  word, and answers unsure when it cannot tell. The output contract gains
  "basis" (a closed list) and "confidence" (high | low); both are parsed,
  an unknown value becomes null, and every verdict, member verdict and
  aggregate carries them. An aggregate keeps the deciding member's basis
  and takes "low" as soon as one deciding member is low.
- Evidence, graded by what the link is worth: every pair carries matched_by
  and score; every judged entity carries its titles, its matching rule and
  its neighbourhood ("filed_with": the correspondents of a tag's documents,
  the tags of a correspondent's); only the pairs linked by fuzzy, prefix or
  token-order also carry document excerpts. Excerpts are read once per
  entity per review and never for a strong tier. withExcerpts: false or
  DUPLICATES_AI_EXCERPTS=no reads nothing at all.
- A member pair a matcher rule settles (exact-normalized, umlaut-variant,
  legal-form) never reaches the provider: it gets verdict same with
  source: spelling-rule, counts in aiReview.spellingRules and costs no
  request, no read and no token.
- A pair the model calls unsure and that had no excerpts is asked once more
  with them; the second answer replaces the first (aiReview.escalated).
- paperlessService: getRecentDocumentExcerptsByEntity (one read,
  truncate_content, cut to the configured characters at a word boundary)
  and getEntityNeighbourhood (one read, the most frequent neighbour names
  through the existing caches). Both answer [] on any error and never log
  document content.
- The judge may run on its own model (DUPLICATES_AI_MODEL): generateText
  takes an optional model in all four provider services, shared through
  aiGenerateOptions.modelOverride.
- Logs: the per-kind start line names the evidence and the model, the
  request line the pairs with excerpts, the escalation its own line.
- Route POST /api/duplicates/ai-review parses withExcerpts like withTitles;
  swagger description updated and OPENAPI/openapi.json regenerated.

Testing
- node scripts/run-tests.js --all: 97 registered, 90 pass, 7 skip offline.
- tests/test-entity-match-ai-service.js: 35 -> 50 cases (the stricter
  prompt, basis and confidence parsing, excerpts only for spelling-only
  pairs and once per entity, the two switches, the configured cut, the
  Kontoauszug regression, settled pairs, the neighbourhood, escalation, the
  model override, batch sizing with excerpts, and both new client methods).
- tests/test-duplicates-endpoints.js: one case for withExcerpts; the three
  existing option assertions now expect withExcerpts: true.
- Demo run against the fake Paperless-ngx: the Kontoauszug/Kontoumzug pair
  costs 282 prompt tokens with excerpts, a strong pair without excerpts 75.
- eslint, prettier and a regen without drift on every file touched.

Impact
An AI review asks about fewer pairs and knows more about the ones it asks
about. Nothing runs on its own, nothing is merged, and document content
never reaches a log line.

Upstream Status
Not applicable — the Duplicates feature does not exist upstream.

* fix(duplicates): do not escalate an unsure pair whose documents carry no text

* feat(duplicates): one click for the AI's proposal, with the evidence behind it

Background
----------
Everything the page offered so far started from the user: scan, read every
card, tick, merge — and where the AI review existed it was a second question
asked after the first. What was missing is the path the archive's owner
actually wants for a first clean-up: one click that scans, has every group and
every near-miss judged, and then hands over a proposal to thin out rather than
a list to work through.

The rule this follows is the same as in the rounds before: the AI is an
addition, never a condition. Without the review nothing of this renders, and
"Scan Paperless-ngx", "Merge selected", the toolbar, the manual merge and the
guided path are the same as they were.

A verdict also had to say more than "same": with `basis`, `confidence` and a
`source` on the wire, the page can pre-tick exactly what is settled — a pair a
spelling rule decided, or one the model says it is sure about — and leave
everything else to the user. The member tables, finally, measured their own
content per card, so the columns of two cards below each other sat in
different places.

Changes
-------
"AI proposal" (#dupAiProposalBtn, primary, rendered only with aiReviewEnabled)
next to "Ask the AI", usable from the first paint because it scans itself:
  - status in the AI row (#dupAiProposalStatus): "Scanning…", then "Asking the
    AI about N pairs and near-misses…", with the hint line under the row
    (#dupAiProposalHint) saying what the click does;
  - it reuses runScan() (now awaited) with the kind, sensitivity and hidden-pair
    settings on the page, then the one review request with includeCandidates
    and no groupIds. Two requests, and no merge until the dialog is confirmed.
Proposal dialog (.dup-proposal-dialog): one row per group that could be merged,
  sorted same/high, same, unsure, different, unjudged (proposalRank,
  compareProposalEntries — both pure); pre-ticked are only the settled ones
  (isSureSame: verdict "same" with confidence "high", which covers the
  spelling-rule verdicts); legend, "Tick all same" (#dupProposalTickSame),
  "Untick all" (#dupProposalUntickAll), the copy-rule check (#dupCopyRuleAll)
  and a live foot line "N of M ticked · K documents · X objects will be
  deleted". Confirming sets the page selection to the ticked groups and hands
  them to the batch runner of round 4, so the selection bar reports the merge
  as it does for "Merge selected"; cancelling leaves the verdicts on the cards
  and nothing ticked.
Evidence, shared by both dialogs (one row renderer, one table):
  - a "Basis" column as a .zr-badge with a label per contract value;
  - the confidence as a suffix of the verdict chip ("AI: same · high");
  - a pair a spelling rule settled reads "Spelling rule" in the "same" tone
    (.dup-verdict--rule) instead of quoting a model that never saw it;
  - the guided dialog pre-ticks by the same rule, so a "same" the model is
    unsure about now comes up unticked there too.
Cards keep their shape: the verdict chip carries the basis in its title and the
  confidence as its suffix, no new column.
Second checkbox "Use document excerpts for spelling-only pairs"
  (#dupAiExcerpts, checked); withTitles and withExcerpts flow into every review
  request from the one place that builds it. The titles checkbox is relabelled
  "Use document titles and neighbours as context".
"AI-judged pairs" tile: its sub line now also counts "· E excerpts", "· S by
  spelling rule" and "· E escalated" when the review reports them.
Member tables line up across cards: .dup-members is table-layout: fixed with
  the name column taking what is left and truncating, and the matching rule a
  fixed share (.dup-members__name, .dup-members__rule).

Testing
-------
node scripts/run-tests.js --all -> 90 passed, 7 skipped offline, 0 failed
  (unchanged from the branch baseline of 97 registered).
tests/test-duplicates-ui.js: 38 -> 48 cases. New: the proposal ids and labels
  only with the review and the page whole without them; what the flow sends
  (runScan first, includeCandidates: true, no groupIds, both evidence flags,
  no request of its own); the pre-tick rule, evaluated as a function against
  seven verdicts; the row order, evaluated by sorting a shuffled list; a label
  for every basis the AiVerdict schema lists, parsed out of schemas.js; the
  spelling-rule chip; the dialog's parts and that it merges through the batch
  runner; the evidence counters of the stats tile; the fixed member-table
  layout; the new CSS classes. Changed: the titles checkbox label, the undo
  promise and the confirm dialogs counted one higher each (the proposal merges
  and therefore makes the same promise), and the pre-tick assertion of the
  guided row.
Reviewed in a browser against a throwaway mock (eleven scan groups plus three
  the model proposes, verdicts across same/high, same/low, unsure and
  different, some settled by a spelling rule, and a Kontoauszug / Kontoumzug
  pair that only the excerpts decide): 31 screenshots at 1280x900 and 390x844,
  light and dark — the controls, the status line mid-flow, the proposal dialog,
  after "Untick all", mid-merge, after the merge, the guided dialog, the stats
  tile, the aligned member tables and the render without the review. 0 px
  horizontal overflow everywhere; the column offsets of all eleven cards are
  identical.

Impact
------
Page only. No route, service, schema or config was touched, so the OpenAPI
spec is unchanged. An instance without the AI review renders and behaves
exactly as before. The new request field and the new verdict fields are ones
the contract already carries: a server that ignores withExcerpts reviews as it
did, and a verdict without basis, confidence or source renders as it did — it
then simply never comes up pre-ticked, which is the safe side.

Upstream Status
---------------
Not applicable - the Duplicates page does not exist upstream.

Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* chore(duplicates): changelog for the AI proposal round, room for the verdict in the Match column

Background
The sixth round of the Duplicates feature adds the AI-led proposal, the
evidence-based judge and the Duplicates settings section. The member
tables now use a fixed column layout so the columns line up across
cards, which left the Match column too narrow for a verdict such as
"AI: same - high": it wrapped into four lines.

Changes
- config/changelog.js: five entries for the round under the current
  release (AI proposal, evidence-based judge with excerpts and
  DUPLICATES_AI_EXCERPT*, DUPLICATES_AI_MODEL, aligned member tables,
  the Duplicates settings section).
- public/css/pages/duplicates.css: the Match column is 132px wide and
  the member verdict does not wrap, so the percentage and the verdict
  take one line each.

Testing
- npx eslint, prettier --check and stylelint on every file changed
  against nightly: clean.
- node scripts/run-tests.js --all: 91 passed, 7 skipped (server or
  credentials needed), 0 failed.
- node scripts/regen-openapi.js: no drift.
- Browser walkthrough against a fake Paperless-ngx and a fake judge:
  scan, merge, undo, dismiss, merge by hand, batch merge, guided review,
  AI proposal and AI review all pass. The Kontoauszug/Kontoumzug pair is
  judged "different" on its excerpts and does not appear in the
  proposal.

Impact
Visual only for the CSS; the changelog is shown in the What's New
dialog.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): contract for a watchable, stoppable AI review

Background
An AI review of a large archive is many model requests in a row. Today
it is one POST that answers when everything is done: nothing shows
while it runs, nothing can stop it, and the tokens it spends are
invisible until the end. The user wants to see what is happening, how
far it is and what it costs, and to stop it at any time. Decisions for
this round: the review runs as a server-side job the page can watch
and stop; a review nobody watches stops itself; a token budget per
review stops it on its own; a stopped review keeps the verdicts it
reached and opens no dialog; the progress lives in the AI row of the
Duplicates page.

Changes
- services/duplicateReviewJobService.js (new): the one review job at
  a time. start(), current(), get(), stop(id, reason), subscribe() for
  a server-sent stream (a late subscriber first gets the job as it is
  now), touch(), wait(), result(), toJSON(). The judge receives a
  control object (signal, onProgress, stop, tokenBudget); a partial
  result of a stopped review is kept like a complete one. The idle
  watch stops a job nobody has watched for the configured seconds. A
  finished job stays reachable for ten minutes.
- config/config.js: DUPLICATES_AI_TOKEN_BUDGET (200000, 0 = no limit)
  and DUPLICATES_AI_IDLE_STOP_SECONDS (60, 0 = never).
- schemas.js, OPENAPI/openapi.json: AiReviewProgress, AiReviewJob,
  AiReviewJobEvent; aiReview gains stopped, stopReason and
  pairsNotJudged.
- scripts/run-tests.js, tests/test-duplicate-review-job.js: the
  contract test of the job (9 cases) in the duplicates area.

Testing
- node scripts/run-tests.js --all: 99 registered, 92 pass, 7 skip
  offline, 0 fail.
- eslint and prettier on every touched file; regen without drift.

Impact
Nothing uses the job yet; the judge ignores the control object until
the implementation follows. No route or page changes.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): make the token budget and the idle stop editable in settings

Background
The two brakes of a running AI review landed as environment variables only:
DUPLICATES_AI_TOKEN_BUDGET caps what one review may spend across all its
requests, DUPLICATES_AI_IDLE_STOP_SECONDS ends a review no page has been
watching, so a closed tab cannot leave the model running. Both are exactly
the kind of setting somebody wants to try out once and then adjust, which
means editing a compose file and restarting the container for every attempt.
The other seven DUPLICATES_* variables already have a field in the Duplicates
section of the settings page; these two did not.

Changes
- views/settings.ejs: two number fields at the end of #sec-duplicates, in the
  style of the five above them — duplicatesAiTokenBudget (0-10000000, step
  1000) and duplicatesAiIdleStopSeconds (0-3600). Each hint says what the
  value does, what zero means and what the default is.
- routes/setup.js: GET /settings passes DUPLICATES_AI_TOKEN_BUDGET and
  DUPLICATES_AI_IDLE_STOP_SECONDS to the view with the defaults of
  config/config.js as the fallback; POST /settings destructures both body
  keys, clamps them to their ranges and keeps the currently configured value
  for an empty or non-numeric field, the rule the round-6 fields follow. Zero
  is a value for both and survives the clamp, because the ranges start there
  rather than at one. The @swagger body schema documents both, and the
  Duplicates group of ENV_EXPORT_GROUPS lists them after the existing keys.
- public/js/settings.js: two entries in the field mapping, so an
  operator-injected value greys the field out and carries the "Managed by ENV"
  pill like every other setting.
- OPENAPI/openapi.json regenerated.

Testing
- tests/test-settings-duplicates-section.js grew from 7 to 11 cases: the two
  fields render with their configured values, ranges and hints and close the
  section in that order; every field of the section is paired with its
  environment key in settings.js; the POST round trip persists all nine
  values; a budget of 99999999 is capped at 10000000 and an idle stop of -5
  lands on 0; zero survives for both, because it means "no limit" and "never"
  rather than an unset field; a fractional value is rounded; a cleared or
  unparsable field keeps what was stored before; the .env export carries all
  nine keys with the two brakes last.
- node scripts/run-tests.js --all: 99 registered, 92 passed, 7 skipped
  offline, 0 failed — the same numbers as before this change.
- eslint and prettier clean on every file touched; regen-openapi.js leaves no
  drift.
- Looked at the section in Chromium at 1440x1000 and 390x844 against a
  throwaway server outside the repository: both fields render like the seven
  above them, no console errors, and with the two keys in the locked-env set
  both are disabled and carry the "Managed by ENV" pill while a neighbouring
  field stays editable.

Impact
No behaviour change for anybody who never opens the section: the defaults are
unchanged (200000 tokens, 60 seconds) and nothing new runs. Operators who set
either variable in their container environment keep winning — the field is
shown greyed out rather than silently overwritten. A saved value needs a
restart to take effect, as the hints say, because config/config.js reads the
environment once at load.

Upstream Status
Not applicable — the Duplicates page is specific to this fork.

* feat(ai): let every provider take an abort signal for one call

aiGenerateOptions gains abortSignal(options); the four provider
services pass it on where their client expects it — the OpenAI SDK as
the second argument of create(body, { signal }) for OpenAI, Azure and
the custom endpoint, axios as { signal } in the request config for
Ollama. Without a signal every provider sends exactly what it sent
before: no second argument at all, and the unchanged axios config.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): the AI review reports, stops and counts its tokens

Background
"Während die AI befragt wird, könnten Millionen von Tokens im
Hintergrund verbraten werden, ohne dass man es sieht. Man muss es auch
abbrechen können." The judge answered when it was done and said
nothing while it worked, so the page had nothing to show and nothing
to stop. The job of the previous round hands it a control object; this
round makes the judge use it. A bar needs a denominator before the
first request, which the old per-kind loop could not give: it read the
archive, asked, and only then looked at the next kind.

Changes
- services/entityMatchAiService.js: reviewScan(options, control = {})
  runs in two passes. Pass one, for every kind of the review: read the
  entities and the band, build the pairs, settle the spelling-rule
  pairs, gather titles, neighbourhood and excerpts, and size the
  batches. Pass two judges kind after kind. Nothing is asked before
  the whole plan exists.
- Progress: phase scanning before the scan, phase evidence per kind
  and per read, one phase judging with requestsPlanned, pairsTotal and
  estimatedTokens for the whole review, one report per answered
  request (requestsDone, pairsJudged, the running token total,
  failedRequests, retries, kind, and the line naming the next
  request), phase escalating when an unsure pair is asked again, phase
  finishing before the groups are built. A split answer adds its
  halves to requestsPlanned in the report of the request that split,
  so the bar never goes backwards; the escalation adds its own
  requests and pairs the same way. Elapsed time and the estimate stay
  with the job, which derives them.
- Stopping: control.signal is read before every read, every request
  and the second round, and travels to the provider, so a stop lands
  on a request in flight. A request that dies on the signal is a stop,
  not a failure: no failed request, no retry, and no "unsure" — the
  pairs stay without a verdict, so they cannot become a group. A
  stopped review returns what it reached; it never throws.
  aiReview now always carries stopped, stopReason (null; the job fills
  it in) and pairsNotJudged.
- Token budget: one running total for the whole review, folded from
  the provider's usage or, for a provider that reports none, from the
  measured prompt plus the estimated answer, so the counter and the
  budget work for every provider (aiReview.tokens keeps reporting only
  what a provider stood behind). When control.tokenBudget is reached
  the review calls control.stop('token-budget') and behaves as
  stopped.
- Logs: "review stopped (user|token-budget|idle): N of M request(s)
  made, P pair(s) not judged, T token(s)." and "token budget 200000
  reached after N request(s) (T tokens)."; the start, request and
  finish lines are unchanged.
- services/duplicateReviewJobService.js: the control object gains
  stopReason(), the one seam the judge needs to name the reason in its
  own log line.
- reviewPairs(pairs, options) additionally takes plan, systemPrompt
  and tracker from reviewScan; a caller that brings none gets what it
  always got.

Testing
- node scripts/run-tests.js --all: 99 registered, 92 pass, 7 skip
  offline, 0 fail (the baseline of the branch).
- tests/test-entity-match-ai-service.js: 13 new cases (64 total) —
  the plan before the first request for one and for two kinds, the
  split and the escalation raising the plan, a failed request still
  moving the bar, a stop between requests and a stop in flight, the
  token budget, a provider without usage, an already aborted signal, a
  review without a control, the report carrying nothing the job
  derives, and the signal reaching all four providers. The one moved
  expectation is the deep-equal on aiReview, which now names the three
  new fields.
- tests/test-duplicate-review-job.js: one case for stopReason().
- A real run through the job service over a fake archive: a review
  that runs through, the same one stopped after request 2, and the
  same one against a token budget.
- eslint and prettier on every touched file.

Impact
The page can show a bar with a denominator, an estimate and a running
token count from the first request, and a stop costs at most one
request that is already in flight. A review without a control object
behaves exactly as before, so the synchronous route is untouched until
it is moved onto the job.

Upstream Status
Not applicable: the Duplicates page and its AI review do not exist
upstream.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): watch and stop the AI review from the page

Background

A review of a drifted archive is many model requests in a row. Until now
"Ask the AI" was one POST that answered when everything was over: a spinner,
no idea how many requests were still coming, no idea what it cost, and no way
out but reloading the tab — which left the model running. The job service of
the contract commit made the review watchable and stoppable on the server;
this wires the routes and the page onto it.

Changes

routes/setup.js (Duplicates block only)
- parseAiReviewRequest(body) holds the validation both entry points share, so
  the synchronous route and the job route can no longer drift apart.
- POST /api/duplicates/ai-review/jobs starts a review and answers
  202 { job }; while one runs it answers 409 with that running job, so a
  second tab attaches instead of failing.
- GET /api/duplicates/ai-review/jobs/current answers { job } or { job: null }
  and counts as watching the review.
- GET /api/duplicates/ai-review/jobs/:id answers { job, result }, 404 for an
  unknown id, and also counts as watching.
- GET /api/duplicates/ai-review/jobs/:id/events streams AiReviewJobEvents
  (text/event-stream, no-cache, X-Accel-Buffering: no, keep-alive, flush after
  every write), a ": keep-alive" comment every 15 s, and ends after done,
  stopped or failed. An unknown id is a JSON 404 before any stream header.
- POST /api/duplicates/ai-review/jobs/:id/stop answers { job }; stopping a
  finished review is a 200 no-op.
- POST /api/duplicates/ai-review now starts that same job and waits for it: a
  stopped review answers 200 with the verdicts it reached, a failed one keeps
  the judge's status, and a second request while one runs is a 409. It
  subscribes for the duration so the idle stop cannot end a review somebody is
  waiting for.
- @swagger for every new route; OPENAPI/openapi.json regenerated.

views/duplicates.ejs, public/js/duplicates.js, public/css/pages/duplicates.css
- A progress panel in the AI row (#dupAiProgress): bar (#dupAiProgressFill,
  indeterminate while the plan is unknown), message, counters
  ("Request 3 of 8 · 40 of 96 pairs · 12.4k of 200k tokens"), time
  ("about 40 s left · 1:24 elapsed") and a Stop button (#dupAiStopBtn). After
  the end it keeps one outcome line and hides on the next scan or review.
- askForVerdicts() starts the job, follows it through EventSource and falls
  back to polling the job every 2 s when the stream breaks. It resolves
  { aiReview, stopped }; all three AI paths honour `stopped` — the notice is
  shown and neither the guided dialog nor the proposal opens.
- On load the page asks for the current job and re-attaches to one that is
  still running; a finished one is left alone.
- Pure helpers formatTokens, formatEta, formatElapsed, progressPercent and
  stopNotice word the numbers; the UI test evaluates them directly.

Testing

- node scripts/run-tests.js --all: 99 registered, 92 pass, 7 skip offline
  (unchanged); duplicates-endpoints 20 -> 30 cases, duplicates-ui 48 -> 57.
- eslint, prettier, stylelint clean on every touched file; regen-openapi
  leaves no diff.
- Reviewed in a browser against a throwaway server with a judge that reports
  eight requests: mid-run, stopping, stopped and done, desktop and phone,
  light and dark, no console errors. A page loaded while a review runs
  re-attached and rendered its result; with the event stream blocked the same
  review came home through eight polls.

Impact

The Duplicates page shows what a review is doing and costing and can end it;
the verdicts already reached are kept. The synchronous route keeps its request
and response, so an API client sees no change beyond the new 409 while a
review runs.

Upstream Status

Not applicable — the Duplicates feature does not exist upstream.

* fix(duplicates): a late Stop answer no longer paints over the outcome; changelog for the review job

Background
In the browser smoke test of the round, a stop pressed after the first
answered request ended the job before the stop request itself answered.
The page then rendered that answer, a snapshot from the stopping moment,
over the outcome line and restarted the elapsed clock, so the panel read
"Stopping after the current request…" next to a finished review.

Changes
- public/js/duplicates.js: stopReview() renders the stop answer only
  while the same job is still followed and still live.
- tests/test-duplicates-ui.js: one case that pins the guard (57 -> 58).
- config/changelog.js: three entries for the round under the current
  release (the review as a job with progress and Stop, the token budget
  and the idle stop as settings, the plan before the first request).

Testing
- node scripts/run-tests.js --test duplicates-ui: 58 passed.
- Browser smoke against a fake Paperless-ngx and a slowed-down fake
  provider: Stop during request 2 leaves "Stopped after 1 of 5 requests
  · 1 of 5 pairs judged · 1.1k tokens" on the panel, the verdicts
  reached stay on the cards, no dialog opens; the proposal path stops
  the same way; a token budget of 2500 stops the review after 3
  requests with the budget named in the notice and the log; a page
  reloaded during a review re-attaches and renders the result; the
  round-6 walkthrough (scan, merge, undo, dismiss, merge by hand, batch,
  guided review, proposal, plain review) passes unchanged.
- eslint and prettier on the touched files.

Impact
Visual only; the review itself was stopped correctly before the fix.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): contract for a judge that measures the model, streams its answers and thinks only on request

Background
On a real archive with a hosted Qwen model the first review request
asked about 25 pairs, ran for 103 seconds and died at its own answer
cap: the model spent the whole budget thinking before the first
verdict, the cut-off text was thrown away, and the page showed nothing
but a ticking clock for two minutes. Three scans of 13 seconds each
came before that. Decisions for this round: the judge measures the
model on a small first request and sizes every later request to a
target duration; the providers stream the answer so the page moves
inside a request and a cut-off answer keeps its verdicts; thinking is
off for the judge unless the operator switches it on; the review
reuses a fresh scan instead of scanning again.

Changes
- config/config.js: DUPLICATES_AI_THINKING (no) and
  DUPLICATES_AI_REQUEST_SECONDS (30).
- schemas.js, OPENAPI/openapi.json: AiReviewProgress gains
  requestPairs, requestAnswers, requestTokens, thinking, batchSize and
  calibrated; the phase list gains warming-up.
- services/duplicateReviewJobService.js: the new progress fields, the
  warming-up phase, and a time estimate from the share of pairs done
  (answers streamed in count), because the batch size may change after
  the warm-up.
- services/aiGenerateOptions.js: reasoningEnabled(options) and
  progressHandler(options), the two switches the judge will send and
  the providers will read, with the GenerateTextProgress shape and the
  partialText rule for cut-off answers.
- scripts/run-tests.js, tests/test-ai-provider-streaming.js: a
  registered placeholder for the provider streaming test.

Testing
- node scripts/run-tests.js --all: 100 registered, 93 pass, 7 skip
  offline, 0 fail.
- eslint and prettier on every touched file; regen without drift.

Impact
Nothing reads the new switches yet; the implementation follows.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* test(helpers): fake OpenAI-compatible and Ollama servers on ephemeral ports

* feat(providers): stream the answer, report progress, keep the cut-off text

Background

A hosted model behind the custom provider spent 103 seconds and the whole
3200-token completion cap on one AI-review request, then threw "the answer hit
a token limit" and dropped every character it had produced. Nothing was visible
while it ran, nothing survived the throw, and the batch was split and paid for
again from the beginning. Two causes: the four provider services always sent a
non-streaming request, so there was nothing to watch; and
assertCompletionNotTruncated() threw before anyone read the content, so the
prefix was thrown away. On top of that the model thinks before it answers, and
on a server that separates thinking from answering the reasoning arrives as
reasoning_content deltas that no provider knew about.

Changes

- services/aiGenerateOptions.js: the shared streaming machinery.
  stripReasoningText() removes <think> blocks, including one a cut-off left
  open. createProgressCollector() assembles a streamed answer, splits reasoning
  from answer incrementally (a marker may be cut across two chunks), counts the
  completion tokens from a usage chunk or estimates them over everything
  produced, reasoning included, and reports at most once per 100 ms plus one
  final report that says done. consumeChatCompletionStream() and
  runChatCompletionStream() are the OpenAI-compatible half: read the stream,
  finish before any throw, and turn a cut-off or a stop into an error that
  carries what arrived. isAbortError()/abortedGenerationError() give a stopped
  request one name across the SDK, axios and fetch.
- services/serviceUtils.js: estimateTokenCount() (the same character-based
  estimate, on a length) and an optional fourth argument on
  assertCompletionNotTruncated() that puts partialText on the error.
- services/openaiService.js, services/customService.js,
  services/azureService.js: generateText() streams when the caller hands in
  onProgress, with stream_options: { include_usage: true } on OpenAI and the
  custom provider and on Azure only from API version 2024-06-01, where the API
  takes it. Without a handler the body is exactly what it was. Both paths strip
  reasoning from the answer and attach the prefix to a truncation error; an
  abort throws an AbortError with partialText.
- services/customService.js: reasoning: false adds
  chat_template_kwargs: { enable_thinking: false } and, for a model name
  matching /qwen/i, that family's soft switch on its own line at the end of the
  user message; reasoning: true sends enable_thinking: true and no soft switch;
  without the option nothing new is sent.
- services/ollamaService.js: generateText() reads NDJSON from an axios
  responseType: 'stream' response, keeps the tail of a socket read until its
  newline arrives, treats the thinking field as thinking, and stops reading the
  moment the signal aborts. reasoning: false/true sends think and overrules
  OLLAMA_THINK; without the option OLLAMA_THINK still decides. The cut-off
  check the analysis path has always run now runs here too, with partialText,
  and a failure no longer erases a token count that was already measured.
- tests/helpers/fake-openai.js, tests/helpers/fake-ollama.js: real HTTP servers
  on ephemeral ports, scripted per request (content chunks, reasoning chunks,
  finish reason, usage chunk or none, per-chunk delay, non-streaming answers
  from the same script), recording every request body and whether the client
  hung up early.
- tests/test-ai-provider-streaming.js replaces its placeholder with 22 cases.

Testing

- node tests/test-ai-provider-streaming.js: 22 passed, 0 failed; run five
  times, no flake.
- node scripts/run-tests.js --all: 93 passed, 7 skipped offline, 0 failed —
  the same numbers as before this change.
- npx eslint and npx prettier --check on every touched file: clean.
- A throwaway process reproduced the reported failure against the fake: the
  progress reports show thinking first with no text, then the answer growing,
  then one done report with the exact token count from the usage chunk, and the
  throw carries the 131 characters of JSON that had arrived.

Impact

No caller behaves differently unless it asks: without onProgress the request
body is byte for byte what it was, and the round-7 provider cases assert that.
What does change for every caller of generateText(): a <think> block no longer
reaches the returned string, a truncation error now carries partialText, an
abort now throws under the name AbortError, and Ollama's generateText() now
raises the same truncation error the analysis path raises instead of returning
a half-written answer. The document analysis path is untouched.

Upstream Status

Not upstream. Streaming, progress reporting, the partial text of a cut-off
answer and the thinking switch do not exist in clusterzx/paperless-ai.

* feat(duplicates): the progress panel moves inside a request and names the measured batch size

Background

A review of a large archive is a handful of long model requests, and the
panel only moved between them. One request took 103 seconds while the page
showed "request 1 of 4 - 0 of 82 pairs" and a ticking clock, so for minutes
at a time the only honest reading of the page was "nothing is happening".
The judge now measures the model on a small first request, sizes every later
one to a configured number of seconds, and streams the answers as they
arrive, which gives the page three things it never had: answers inside a
request, a warm-up phase, and a model that says when it is thinking.

Changes

Page (views/duplicates.ejs, public/js/duplicates.js,
public/css/pages/duplicates.css):

- progressPercent() counts pairs whenever the plan knows them, the answers
  of the running request included, and falls back to requests only while no
  pair count exists. The bar therefore moves during a request instead of
  jumping once per request.
- progressCountsText() gained the "7 of 10 answers" part, printed only while
  a request is in flight and capped at the size of that request.
- progressTimeText() says "measuring the model" in the warm-up and "the
  model is thinking" while the model writes reasoning, instead of a clock
  that cannot move; an estimate the job already made is still shown next to
  either.
- New #dupAiProgressNote line under the counts, written by the new
  progressNoteText(): "4 pairs per request while the model is measured"
  before the measurement, "9 pairs per request, sized from the model's
  answers" after it, empty while no size is known. A zero-width space holds
  its row open for as long as a review runs (.dup-progress--live), so the
  stats tiles below do not jump the moment it fills.
- .dup-progress__fill--thinking pulses while the model reasons, slower than
  the indeterminate band, and is switched off under prefers-reduced-motion.
- The outcome line and the "Model requests" tile both name the batch size the
  review settled on.
- New htmlReviewFailure(): all three AI paths report a failed review with the
  judge's own message plus one link, "Open the Duplicates settings", to
  /settings#duplicates-tab.

Settings (views/settings.ejs, public/js/settings.js, routes/setup.js):

- Two fields close the Duplicates section: the switch "Let the judge think"
  (DUPLICATES_AI_THINKING, default off) and the number "Seconds per model
  request" (DUPLICATES_AI_REQUEST_SECONDS, 5-300, default 30). GET, POST with
  the usual clamping and keep-the-previous-value behaviour, the @swagger
  request body, ENV_EXPORT_GROUPS and the two "Managed by ENV" selectors.

Route:

- GET /api/duplicates/scan passes fresh: true; a scan somebody pressed a
  button for must not be answered from a cache.

OPENAPI/openapi.json regenerated.

Testing

- node scripts/run-tests.js --all: 93 passed, 7 skipped offline, 0 failed
  (unchanged from the baseline of this round).
- duplicates-ui 58 -> 66 cases: the bar with streamed answers and without a
  pair count, the counts line with and without a running request, the three
  wordings of the time line, the note line, the outcome line with a batch
  size, the panel ids and the thinking class, the settings link of the failed
  notice, and the stylesheet's pulse with its reduced-motion rule.
- settings-duplicates-section 11 -> 15 cases: both fields render with their
  values and hints, the POST round trip, clamping (2 -> 5, 999 -> 300), the
  cleared field keeping the previous value, the switch spellings, the export
  group order and the two selectors.
- duplicates-endpoints 30 -> 31 cases: the scan route hands fresh: true to
  the service.
- eslint, prettier and stylelint clean on every touched file; regen-openapi
  leaves no drift.
- Looked at in Chromium against a throwaway server on port 3403 that walks a
  scripted review through the warm-up, a thinking stretch and a request whose
  answers climb 0 -> 10: desktop and phone, light and dark. The stats tiles
  sit at the same offset before and after the note line fills.

Impact

The panel reports inside a request rather than between requests, and names
both the warm-up and the measured batch size, so a review that takes minutes
per request looks like work rather than a hang. A failed review points at the
setting that would have prevented it. Nothing scans, judges or merges on its
own; the two new settings are read at startup like the rest of the section.

Upstream Status

Not applicable - the Duplicates page does not exist upstream.

* feat(duplicates): measure the model, size every request to it, and reuse a fresh scan

Background

Asking the AI about a scan of the user's archive did not work on their
instance. The judge sent 25 pairs with a completion cap of 3200, the hosted
model thought before it answered and spent all 3200 tokens on the thinking,
and 102 seconds later nothing had been judged. The answer was then split into
13 + 12, which buys nothing: the thinking does not get cheaper with fewer
pairs. Meanwhile the page showed "request 1 of 4 · estimating…" for two
minutes, because a request only reports when it is over. The user pressed
Stop.

The same run also scanned the archive three times inside 50 seconds — the
page's scan, the AI proposal's and the review job's — 1359 tags and 13
seconds each, with nothing changing in between.

Changes

services/entityMatchAiService.js

- Thinking off by default. Every judge request carries
  `reasoning: config.duplicatesAiThinking === true`, so a reasoning model
  answers instead of deliberating unless the operator asked for it. Nothing
  else about the prompt changed.
- A warm-up instead of a guess. The first request of a review whose model has
  not been measured asks about at most WARMUP_PAIRS (4) pairs with a
  deliberately generous cap (RESPONSE_TOKENS, the flat estimate or
  WARMUP_MIN_CAP, whichever is largest, bounded by the context window). It is
  announced under the phase `warming-up` with the message "Measuring the model
  with a small first request…", `calibrated: false` and the size it will use;
  the plan reported with it is provisional and the log says so.
- Sizing from the measurement. Every answered request yields tokens per pair
  (thinking included) and tokens per second, each smoothed by half against the
  measurement before it. From them:
  `batchSize = clamp(floor(requestSeconds × tokensPerSecond ÷ tokensPerPair), 1, batchSize())`
  and `cap = ceil(tokensPerPair × batchSize × 1.5) + TOKENS_OVERHEAD`, both
  bounded by the context window as the batch planning bounds them.
  `requestSeconds` is DUPLICATES_AI_REQUEST_SECONDS, at least 5, 30 by
  default. A batch is now taken off the front of a queue rather than chunked
  up front, because its size changes while the review runs.
- The plan settles after the warm-up. `requestsPlanned` and `estimatedTokens`
  are re-derived from the pairs nobody has asked about yet and reported with
  `batchSize` and `calibrated: true`, so the page's denominator stops moving.
- Truncation: raise before halving. A cut-off answer that salvaged nothing is
  asked again with twice the cap (the warm-up gets the whole window at once),
  and only when that bought nothing — or the cap is already at the window's
  bound — is the batch halved as before. A warm-up that does not fit even then
  ends the review as failed with a message the operator can act on, naming
  DUPLICATES_AI_THINKING and TOKEN_LIMIT. A single pair at the bound keeps the
  old "unsure" and its log line.
- The cut-off text counts. All four providers now attach `error.partialText`,
  so the salvage path runs for every one of them; a salvaged request counts
  its verdicts in `pairsJudged` and in the tracker. Two comments that still
  said only Ollama returns half-written answers were rewritten.
- Progress inside a request. With a progress sink the provider is asked to
  stream (`onProgress`). Each report, at most every 250 ms, carries
  `requestPairs`, `requestAnswers` (the complete verdict objects counted off
  the streamed text), `requestTokens`, `thinking` and the running token total:
  "The model is thinking… (640 tokens so far)" while it thinks, otherwise the
  request line with " · 7 of 10 answers" appended. The report that counts the
  request resets all four. A review nobody watches sends the plain request it
  always sent.
- Calibration memory. The last measurement per model name lives on the
  singleton; a review that finds one starts sized from it, skips the warm-up
  and says so in the log. A measurement taken with thinking on is never reused
  with thinking off. `resetCalibration()` for tests.
- Logs: the finish line says "N pair(s) planned" (the number is the plan), the
  batch-size line is marked provisional until the model is measured, and the
  split line says whether the cap was raised or the batch halved.

services/duplicateMergeService.js

- `scan()` keeps its result per set of options (kind, threshold,
  includeDismissed) for SCAN_CACHE_MS (60 s) and answers the next identical
  request from it with one log line instead of the start and finish lines.
  `fresh: true` skips and refills it; the page's Scan button sends it.
- A merge, an undo, a dismissal and `restoreDismissal()` empty the cache. A
  dismissal deleted through the route, which talks to the model directly, is
  caught by a fingerprint (row count and highest id per kind) checked on every
  hit — one local SELECT against a 13-second scan.
- `reviewScan()` calls `scan()` without `fresh`, so a proposal made right
  after the page scanned costs no second scan.

Testing

- node scripts/run-tests.js --all: 93 passed, 7 skipped offline, 0 failed
  (100 registered), unchanged from the baseline.
- tests/test-entity-match-ai-service.js: 65 -> 80 cases. New: thinking off and
  on; the warm-up's size, cap, phase and message; the sizing math on a fixed
  usage and duration; the request seconds and their floor; the context window
  bounding size and cap; smoothing; the plan and estimate recomputed after the
  warm-up; calibration reused, not reused across the thinking switch, reset; a
  warm-up that cannot fit ending the review with its message; a truncated
  answer with partialText salvaged and counted; a streamed request reporting
  thinking, then answers, then clearing itself; an unwatched review not
  streaming; a review served from the page's scan.
- tests/test-duplicate-merge-service.js: 17 -> 22 cases. New: cache hit, other
  options and `fresh` missing it, expiry, invalidation by merge, undo, dismiss
  and restore, and a dismissal removed behind the service.
- Changed expectations, all from the raise-before-halve rule: the truncation
  cases now see every size asked twice (once, once with twice the cap) before
  it is halved, the single pair is asked twice before it ends as unsure, and
  the planning cases see the `warming-up` phase where they saw `judging`.
- Two demo runs against a fake model at 30 tokens/s: thinking off, 12 pairs —
  warm-up 4 pairs in 20 s (600 tokens, 150 per pair), then requests of 5 pairs
  at 25 s, 4500 tokens, 60 s in total. Thinking on — warm-up 4 pairs in 40 s
  (1200 tokens, 300 per pair) and requests of 2 pairs at 30.04 s, the
  configured length.

Impact

The first request of a review is seconds rather than minutes, every later one
lasts about as long as the operator asked, and the page shows the model
thinking and answering while it happens instead of a still bar. A review of a
model that was measured before starts at full size. Three scans of one archive
become one. Nothing runs on its own and no verdict changed: the prompt, the
rules and the shape of an answer are what they were.

Upstream Status

Not applicable — the Duplicates feature does not exist upstream.

* fix(duplicates): a review never asks for a fresh scan of its own

reviewScan() drops a `fresh` flag its caller may carry instead of passing it on, so a route that forwards the page's scan options cannot make the review scan the archive a second time.

* fix(duplicates): the yes/no switches of the judge read 'yes', and a small batch is not starved after a thinking one

Background
The browser smoke test of the round ran the thinking scenario and the
judge kept saying "thinking off" although DUPLICATES_AI_THINKING=yes
was set. config/config.js normalises every yes/no setting to the
strings 'yes' and 'no' (parseEnvBoolean), while three readers in the
judge asked Boolean() or === true: the thinking switch could never be
turned on, and the review and excerpt switches could not be turned off
('no' is a truthy string). The second finding: a thinking model pays a
fixed price per request, so a one-pair request sized by pairs alone
after a four-pair warm-up got a cap the same thoughts did not fit; the
judge recovered by raising the cap, at the cost of one request.

Changes
- services/entityMatchAiService.js: switchedOn() accepts 'yes' and a
  boolean true; isEnabled(), excerptsEnabled() and thinkingEnabled() use
  it. The cap never drops below the largest completion the model has
  produced in this review plus a quarter (CAP_FLOOR_FACTOR), and that
  floor is remembered with the calibration.
- tests/test-entity-match-ai-service.js: one case per finding (82
  cases), the sizing case expects the remembered floor.
- config/changelog.js: three entries for the round under the current
  release.

Testing
- node scripts/run-tests.js --test entity-match-ai-service: 82 passed.
- Browser smoke against a fake Paperless-ngx and a fake provider that
  streams, thinks on request and honours max_tokens: thinking off, the
  fake never thought, warm-up 4 pairs, 59 tokens/s measured; thinking
  on, the panel showed the thinking state, no request hit the token
  limit any more; Stop, re-attach, token budget and the round-6
  walkthrough unchanged.

Impact
DUPLICATES_AI_REVIEW=no and DUPLICATES_AI_EXCERPTS=no now do what they
say; DUPLICATES_AI_THINKING=yes now reaches the model.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): contract for the creation guard, the semantic sweep, unused objects, renames and a remembered calibration

Background
Round 9 of the Duplicates feature, six points the user picked: stop
the drift where it starts (document analysis creating "Rechnungen"
next to "Rechnung"), let the model find synonyms and translations the
string matcher cannot, list and delete unused objects with undo, name
the survivor of a merge, keep the judge's measurement of a model across
restarts, and scan faster. Decisions: only hard matcher tiers map a
new name onto an existing one (case, umlauts, legal form, plural, word
order), typo-like matches are logged and still create…
…order requests (#336)

* feat(duplicates): contract for a targeted AI review

Background
With many groups at 94 to 96 percent the user wants to say "everything
from 95 percent up: ask the AI, show me its view, then merge". The
review must therefore be able to judge only chosen groups and skip the
band of near-misses.

Changes
- schemas.js, OPENAPI/openapi.json: groupIds, minConfidence and
  includeCandidates on DuplicateAiReviewRequest.

Testing
- node scripts/regen-openapi.js: no drift after the commit.

Impact
Request fields only; the implementation follows.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): targeting counters in the AI review result schema

Background
A targeted review reports which groups it judged and which it left
without a verdict; the page shows that.

Changes
- schemas.js, OPENAPI/openapi.json: targeted, groupsJudged and
  groupsSkipped on DuplicateAiReviewResult.aiReview.

Testing
- node scripts/regen-openapi.js: no drift after the commit.

Impact
Documentation of three informational fields.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): let the AI review be pointed at a few groups

Background

An archive with hundreds of correspondents produces dozens of groups at
94, 95 and 96 per cent, and asking the model about all of them costs a
lot to answer a question about a handful. The page needs to select the
groups it is about to merge, ask about those, and keep rendering the
rest of the scan while it does.

Changes

- entityMatchAiService.reviewScan() takes three options that narrow what
  is asked, never what comes back:
  - groupIds: only these scan groups are judged. Every other group is
    still in `groups`, as the scan produced it, with `aiVerdict: null` on
    the group and on every member and `source: 'scan'`. An id this scan
    does not know is ignored and logged once with the count.
  - minConfidence: only groups scoring at least this much are judged;
    together with groupIds both conditions have to hold.
  - includeCandidates (default true): false leaves the band of
    near-misses out entirely, so `candidates` is 0 — and with no band
    the entity list per kind is not read either, which is the cheap part.
- _pairsForKind() takes the set of group ids to judge. A group left out
  contributes no pairs but its member pairs still count as "inside one
  group", so it cannot reappear as a candidate.
- The result reports the targeting: aiReview.targeted, .groupsJudged and
  .groupsSkipped. The start line of the log names it as
  "judging 1 of 4 group(s) (min confidence 0.95, 3 ids), band skipped",
  the closing line adds the two counters. An untargeted review logs and
  behaves exactly as before.
- POST /api/duplicates/ai-review validates and passes the three fields
  through: groupIds an array of at most 500 non-empty strings,
  minConfidence a number in [0.5, 1], includeCandidates a real boolean
  (the string "false" is a 400). An option the request does not mention
  is left out of the service call, so an untargeted request reaches
  reviewScan() with the same object it did before.
- Swagger description of the route and the 400 reason updated,
  OPENAPI/openapi.json regenerated.

Testing

- node scripts/run-tests.js --all -> 90 passed, 7 skipped offline,
  0 failed (97 registered), unchanged against the baseline.
- entity-match-ai-service: 28 -> 34 cases. Six new ones on a fixture
  whose four groups sit exactly on the matcher tiers (1, 0.98, 0.95,
  0.9) plus one pair in the band: groupIds judges only what it names,
  minConfidence filters, includeCandidates: false skips the band and
  reads no second entity list, groupIds and minConfidence combine while
  unknown ids are ignored, an empty selection costs no request, and the
  log lines. The existing aiReview assertion gained the three new fields.
- duplicates-endpoints: 16 -> 19 cases. The three fields reach the
  stubbed reviewScan unchanged, an untargeted request still carries
  nothing extra, ten malformed targeting bodies are 400, and 500 ids are
  accepted while 501 are not.
- Manual run against the real route with a fake store and a fake
  provider: full review 5 pairs / 1 request, minConfidence 0.95 without
  the band 3 pairs, two selected ids (one unknown) 1 pair, and every
  unjudged group back with null verdicts.
- eslint, prettier and the OpenAPI drift check clean on the touched
  files.

Impact

Additive. A review that says nothing about the three options behaves and
logs as before. The page can ask about the groups it selected before a
batch merge; a dozen groups without the band are one or two model
requests instead of the whole archive. schemas.js still has to gain
targeted, groupsJudged and groupsSkipped on DuplicateAiReviewResult.

Upstream Status

Not applicable: the Duplicates feature is next-only.

* feat(duplicates): sort, select by confidence, and a guided review before merging

Background
----------
On a grown archive a scan answers with dozens of groups that all read 94, 95,
96 percent, and the page offered no way to act on that number: every group had
to be judged by eye, one tick at a time. The three presets were the only
thresholds available, so "everything above 95" was not a question the page
could be asked. And where the AI review existed it judged the whole result
list, which is the most expensive way to ask about the five groups the user
actually cares about.

The rule this follows: the AI is an addition, never a condition. Every flow
below works end to end with the review switched off; with it on, the guided
path is one more button beside the one that was already there.

Changes
-------
Results toolbar (#dupResultsBar), above the selection bar, shown once a scan
has groups:
  - "Sort by" (#dupSortSelect): confidence, documents, target name (locale
    compare), kind then confidence. It moves the DOM nodes instead of
    re-rendering, so a card keeps its target, its source ticks, its selection,
    its verdict and its busy state; the two blocks (scan groups, AI
    candidates) are sorted separately and the divider stays between them.
  - "Select >=" (#dupMinConfidence, #dupSelectMinBtn, #dupMinConfidenceCount):
    ticks every selectable group at or above a whole percent and unticks the
    rest, with a live count of what the click would do.
Custom scan threshold: a fourth sensitivity option "Custom" reveals a number
field (#dupThresholdCustom); the scan and both review paths send that percent
divided by 100. The three presets are unchanged.
Confidence breakdown under "Groups found" (#dupStatBuckets): ">=95 %: A .
90-95 %: B . <90 %: C", counted from the cards after a scan and after a review.
Guided flow (#dupReviewThenMergeBtn, rendered only where the review exists):
asks the model about exactly the ticked groups (groupIds, includeCandidates:
false), puts the verdicts on the cards as a full review does, then shows them
once in a wide dialog - one row per group with target, sources, documents, the
verdict chip and the reason, a live "N of M ticked . K documents" foot line and
the copy-rule check. Ticked rows are merged with the batch machinery; an unsure
or different verdict only comes up unticked and never blocks anything, and what
stays unticked stays selected on the page.
"Merge selected" keeps its place and its weight, first in the bar and without a
model anywhere in its path; its dialog names the guided path in one faint line,
and only where that path exists.
Sort, confidence, sensitivity and the custom threshold are remembered in
localStorage (dup.sort, dup.minConfidence, dup.sensitivity,
dup.thresholdCustom) through two try/catch helpers.

Testing
-------
node scripts/run-tests.js --all -> 90 passed, 7 skipped offline, 0 failed
  (unchanged from the branch baseline).
tests/test-duplicates-ui.js: 25 -> 38 cases. New: the toolbar ids and their
  order, the custom threshold field, the stats breakdown, the guided button
  only with the review, the whole page without the review, the toolbar ids in
  the script, sorting as a DOM move, "Select >=", the wrapped localStorage
  access, the guided request (groupIds / includeCandidates: false) and that
  "Merge selected" never touches the review endpoint, the review dialog markup,
  the tip line, the new CSS classes. Changed: the sensitivity options are read
  from #dupSensitivity alone and now end in "custom"; the undo promise and the
  confirm dialogs are counted one higher each, because the review dialog merges
  and therefore makes the same promise.
Reviewed in a browser against a throwaway mock (twelve groups over 88-100 %, a
  review that honours groupIds): 27 screenshots at 1280x900 and 390x844, light
  and dark, 0 px horizontal overflow everywhere, plus a 31-check behaviour
  probe (guided request, verdict ticks, sorting keeping picks and the divider,
  persistence, a refused review, and the whole page with the review off).

Impact
------
Page only. No route, service, schema or config was touched, so the OpenAPI
spec is unchanged. An instance without the AI review renders and behaves
exactly as before plus the toolbar and the custom threshold. The request the
guided path sends uses fields the contract already carries; a server that
ignores them reviews everything, which the page renders correctly.

Upstream Status
---------------
Not applicable - the Duplicates page does not exist upstream.

Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* docs(duplicates): changelog entries for sorting, select by confidence and the guided review

Background
Round 5 answered the second feedback from a real archive: select by a
number, let the model judge exactly those groups, read its verdicts in
one dialog, merge what stays ticked; sort the groups; a custom threshold.

Changes
- config/changelog.js: two entries in the current v2026.09.01 block.

Testing
- node scripts/run-tests.js --test changelog-releases: passed.

Impact
Documentation only.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): contract for evidence-based verdicts and the AI proposal

Background
A real archive produced "Kontoauszug" / "Kontoumzug": the matcher called
it a spelling distance, the prompt allowed "an obvious typo" as a reason
for same, and the model, seeing names and titles only, agreed. Both are
different things. The judge needs stricter rules and, for pairs linked by
spelling alone, a look at what the documents are about, at a bounded
cost.

Changes
- config/config.js: DUPLICATES_AI_EXCERPTS (default yes),
  DUPLICATES_AI_EXCERPT_CHARS (300), DUPLICATES_AI_EXCERPT_DOCUMENTS (2).
- schemas.js, OPENAPI/openapi.json: AiVerdict gains basis and confidence;
  DuplicateAiReviewRequest gains withExcerpts; aiReview reports excerpts.

Testing
- node scripts/run-tests.js --area duplicates: 6/6; regen without drift.

Impact
Settings and schema only; the implementation follows.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): judge model override and the verdict source in the contract

Background
Decisions for round 6: the matcher's hard tiers settle a pair without the
model, unsure pairs are asked once more with excerpts, and the judge may
run on a stronger model of the same provider.

Changes
- config/config.js: DUPLICATES_AI_MODEL (optional, judge only).
- schemas.js, OPENAPI/openapi.json: AiVerdict.source (model or
  spelling-rule); aiReview.escalated and aiReview.spellingRules.

Testing
- eslint and prettier on the two files; regen without drift.

Impact
Settings and schema only; the implementation follows.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(settings): make every DUPLICATES_ setting editable in its own section

Background
The AI review of the Duplicates page arrived with seven environment
variables and no way to change any of them from the interface. Editing a
container environment and recreating the container is the wrong price for
"try a stronger model for the judge" or "ask about fewer pairs per
request", and the settings page is exactly where those knobs belong.
config/config.js already reads all seven; only the front door was missing.

Changes
- views/settings.ejs: a "Duplicates" section (id="sec-duplicates") inside a
  new duplicates-tab block between the AI sections and OCR, with a nav entry
  in the desktop section nav (icon i-merge) and in the mobile one, in the
  same order as the page. Seven fields, each with a hint that says what the
  value does and what its default is: the AI review switch, the judge model,
  pairs per request, the candidate floor, the excerpt switch, excerpt length
  and documents per entry. Switches go through partials/settings-switch, so
  the hidden yes/no input the POST route reads exists as it does everywhere
  else.
- routes/setup.js: GET /settings passes the seven values (env first, the
  defaults of config/config.js as fallback) in the config object the view
  reads; POST /settings destructures the seven camelCase body keys,
  normalises them and writes them into updatedConfig, so setupService
  .saveConfig persists them with the rest. Numbers are clamped to their
  range; a value that is not a number, or a cleared field, keeps what is
  configured now instead of resetting to the default. The swagger body
  schema documents all seven, and the .env export gained a "Duplicates"
  group between "AI behaviour" and "External API".
- public/js/settings.js: the seven selector to env-key entries, so the
  "Overwritten" and "Managed by ENV" marking covers these fields too.
- OPENAPI/openapi.json regenerated.
- tests/test-settings-duplicates-section.js, registered in the
  observability area.

Testing
- node scripts/run-tests.js --all: 98 registered, 91 passed, 7 skipped
  offline (was 97/90/7). The new test covers the rendered section and its
  nav position, the seven inputs and their values, the POST round trip,
  clamping, the keep-the-previous-value case and the .env export group.
- npx eslint / npx prettier --check --ignore-unknown on every touched file.
- node scripts/regen-openapi.js leaves OPENAPI/openapi.json unchanged.
- Looked at the page in Chromium at 1440x1000 and 390x844 against a
  throwaway server outside the repository; no console errors, the section
  reads like the rest of the page and stacks on the phone.

Impact
Operators can change every DUPLICATES_ value from the settings page. The
existing restart-after-save is what makes them take effect; no new
mechanism. Values injected by the container still win and are shown as
managed, as for every other field. Nothing outside the settings page
changes: no route, service or default behaviour of the Duplicates page
itself is touched.

Upstream Status
Fork-only. The Duplicates page does not exist upstream.

Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): judge spelling-only pairs on evidence, not on distance

Background
A real archive produced "Kontoauszug" next to "Kontoumzug": the matcher
called it a spelling distance, the prompt allowed "an obvious typo" as a
reason for same, and the model, seeing two names and three titles, agreed.
Two different things. The judge needed stricter rules, evidence for the
pairs where spelling is the only link, and a way to say how sure it is and
on what grounds — all without opening a large context window on every pair.

Changes
- entityMatchAiService: the system prompt refuses a small spelling distance
  as a reason of its own ("Kontoauszug" / "Kontoumzug", "Miete" / "Mieter",
  "Bahn" / "Bank"), allows a misspelling only when one spelling is not a
  word, and answers unsure when it cannot tell. The output contract gains
  "basis" (a closed list) and "confidence" (high | low); both are parsed,
  an unknown value becomes null, and every verdict, member verdict and
  aggregate carries them. An aggregate keeps the deciding member's basis
  and takes "low" as soon as one deciding member is low.
- Evidence, graded by what the link is worth: every pair carries matched_by
  and score; every judged entity carries its titles, its matching rule and
  its neighbourhood ("filed_with": the correspondents of a tag's documents,
  the tags of a correspondent's); only the pairs linked by fuzzy, prefix or
  token-order also carry document excerpts. Excerpts are read once per
  entity per review and never for a strong tier. withExcerpts: false or
  DUPLICATES_AI_EXCERPTS=no reads nothing at all.
- A member pair a matcher rule settles (exact-normalized, umlaut-variant,
  legal-form) never reaches the provider: it gets verdict same with
  source: spelling-rule, counts in aiReview.spellingRules and costs no
  request, no read and no token.
- A pair the model calls unsure and that had no excerpts is asked once more
  with them; the second answer replaces the first (aiReview.escalated).
- paperlessService: getRecentDocumentExcerptsByEntity (one read,
  truncate_content, cut to the configured characters at a word boundary)
  and getEntityNeighbourhood (one read, the most frequent neighbour names
  through the existing caches). Both answer [] on any error and never log
  document content.
- The judge may run on its own model (DUPLICATES_AI_MODEL): generateText
  takes an optional model in all four provider services, shared through
  aiGenerateOptions.modelOverride.
- Logs: the per-kind start line names the evidence and the model, the
  request line the pairs with excerpts, the escalation its own line.
- Route POST /api/duplicates/ai-review parses withExcerpts like withTitles;
  swagger description updated and OPENAPI/openapi.json regenerated.

Testing
- node scripts/run-tests.js --all: 97 registered, 90 pass, 7 skip offline.
- tests/test-entity-match-ai-service.js: 35 -> 50 cases (the stricter
  prompt, basis and confidence parsing, excerpts only for spelling-only
  pairs and once per entity, the two switches, the configured cut, the
  Kontoauszug regression, settled pairs, the neighbourhood, escalation, the
  model override, batch sizing with excerpts, and both new client methods).
- tests/test-duplicates-endpoints.js: one case for withExcerpts; the three
  existing option assertions now expect withExcerpts: true.
- Demo run against the fake Paperless-ngx: the Kontoauszug/Kontoumzug pair
  costs 282 prompt tokens with excerpts, a strong pair without excerpts 75.
- eslint, prettier and a regen without drift on every file touched.

Impact
An AI review asks about fewer pairs and knows more about the ones it asks
about. Nothing runs on its own, nothing is merged, and document content
never reaches a log line.

Upstream Status
Not applicable — the Duplicates feature does not exist upstream.

* fix(duplicates): do not escalate an unsure pair whose documents carry no text

* feat(duplicates): one click for the AI's proposal, with the evidence behind it

Background
----------
Everything the page offered so far started from the user: scan, read every
card, tick, merge — and where the AI review existed it was a second question
asked after the first. What was missing is the path the archive's owner
actually wants for a first clean-up: one click that scans, has every group and
every near-miss judged, and then hands over a proposal to thin out rather than
a list to work through.

The rule this follows is the same as in the rounds before: the AI is an
addition, never a condition. Without the review nothing of this renders, and
"Scan Paperless-ngx", "Merge selected", the toolbar, the manual merge and the
guided path are the same as they were.

A verdict also had to say more than "same": with `basis`, `confidence` and a
`source` on the wire, the page can pre-tick exactly what is settled — a pair a
spelling rule decided, or one the model says it is sure about — and leave
everything else to the user. The member tables, finally, measured their own
content per card, so the columns of two cards below each other sat in
different places.

Changes
-------
"AI proposal" (#dupAiProposalBtn, primary, rendered only with aiReviewEnabled)
next to "Ask the AI", usable from the first paint because it scans itself:
  - status in the AI row (#dupAiProposalStatus): "Scanning…", then "Asking the
    AI about N pairs and near-misses…", with the hint line under the row
    (#dupAiProposalHint) saying what the click does;
  - it reuses runScan() (now awaited) with the kind, sensitivity and hidden-pair
    settings on the page, then the one review request with includeCandidates
    and no groupIds. Two requests, and no merge until the dialog is confirmed.
Proposal dialog (.dup-proposal-dialog): one row per group that could be merged,
  sorted same/high, same, unsure, different, unjudged (proposalRank,
  compareProposalEntries — both pure); pre-ticked are only the settled ones
  (isSureSame: verdict "same" with confidence "high", which covers the
  spelling-rule verdicts); legend, "Tick all same" (#dupProposalTickSame),
  "Untick all" (#dupProposalUntickAll), the copy-rule check (#dupCopyRuleAll)
  and a live foot line "N of M ticked · K documents · X objects will be
  deleted". Confirming sets the page selection to the ticked groups and hands
  them to the batch runner of round 4, so the selection bar reports the merge
  as it does for "Merge selected"; cancelling leaves the verdicts on the cards
  and nothing ticked.
Evidence, shared by both dialogs (one row renderer, one table):
  - a "Basis" column as a .zr-badge with a label per contract value;
  - the confidence as a suffix of the verdict chip ("AI: same · high");
  - a pair a spelling rule settled reads "Spelling rule" in the "same" tone
    (.dup-verdict--rule) instead of quoting a model that never saw it;
  - the guided dialog pre-ticks by the same rule, so a "same" the model is
    unsure about now comes up unticked there too.
Cards keep their shape: the verdict chip carries the basis in its title and the
  confidence as its suffix, no new column.
Second checkbox "Use document excerpts for spelling-only pairs"
  (#dupAiExcerpts, checked); withTitles and withExcerpts flow into every review
  request from the one place that builds it. The titles checkbox is relabelled
  "Use document titles and neighbours as context".
"AI-judged pairs" tile: its sub line now also counts "· E excerpts", "· S by
  spelling rule" and "· E escalated" when the review reports them.
Member tables line up across cards: .dup-members is table-layout: fixed with
  the name column taking what is left and truncating, and the matching rule a
  fixed share (.dup-members__name, .dup-members__rule).

Testing
-------
node scripts/run-tests.js --all -> 90 passed, 7 skipped offline, 0 failed
  (unchanged from the branch baseline of 97 registered).
tests/test-duplicates-ui.js: 38 -> 48 cases. New: the proposal ids and labels
  only with the review and the page whole without them; what the flow sends
  (runScan first, includeCandidates: true, no groupIds, both evidence flags,
  no request of its own); the pre-tick rule, evaluated as a function against
  seven verdicts; the row order, evaluated by sorting a shuffled list; a label
  for every basis the AiVerdict schema lists, parsed out of schemas.js; the
  spelling-rule chip; the dialog's parts and that it merges through the batch
  runner; the evidence counters of the stats tile; the fixed member-table
  layout; the new CSS classes. Changed: the titles checkbox label, the undo
  promise and the confirm dialogs counted one higher each (the proposal merges
  and therefore makes the same promise), and the pre-tick assertion of the
  guided row.
Reviewed in a browser against a throwaway mock (eleven scan groups plus three
  the model proposes, verdicts across same/high, same/low, unsure and
  different, some settled by a spelling rule, and a Kontoauszug / Kontoumzug
  pair that only the excerpts decide): 31 screenshots at 1280x900 and 390x844,
  light and dark — the controls, the status line mid-flow, the proposal dialog,
  after "Untick all", mid-merge, after the merge, the guided dialog, the stats
  tile, the aligned member tables and the render without the review. 0 px
  horizontal overflow everywhere; the column offsets of all eleven cards are
  identical.

Impact
------
Page only. No route, service, schema or config was touched, so the OpenAPI
spec is unchanged. An instance without the AI review renders and behaves
exactly as before. The new request field and the new verdict fields are ones
the contract already carries: a server that ignores withExcerpts reviews as it
did, and a verdict without basis, confidence or source renders as it did — it
then simply never comes up pre-ticked, which is the safe side.

Upstream Status
---------------
Not applicable - the Duplicates page does not exist upstream.

Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* chore(duplicates): changelog for the AI proposal round, room for the verdict in the Match column

Background
The sixth round of the Duplicates feature adds the AI-led proposal, the
evidence-based judge and the Duplicates settings section. The member
tables now use a fixed column layout so the columns line up across
cards, which left the Match column too narrow for a verdict such as
"AI: same - high": it wrapped into four lines.

Changes
- config/changelog.js: five entries for the round under the current
  release (AI proposal, evidence-based judge with excerpts and
  DUPLICATES_AI_EXCERPT*, DUPLICATES_AI_MODEL, aligned member tables,
  the Duplicates settings section).
- public/css/pages/duplicates.css: the Match column is 132px wide and
  the member verdict does not wrap, so the percentage and the verdict
  take one line each.

Testing
- npx eslint, prettier --check and stylelint on every file changed
  against nightly: clean.
- node scripts/run-tests.js --all: 91 passed, 7 skipped (server or
  credentials needed), 0 failed.
- node scripts/regen-openapi.js: no drift.
- Browser walkthrough against a fake Paperless-ngx and a fake judge:
  scan, merge, undo, dismiss, merge by hand, batch merge, guided review,
  AI proposal and AI review all pass. The Kontoauszug/Kontoumzug pair is
  judged "different" on its excerpts and does not appear in the
  proposal.

Impact
Visual only for the CSS; the changelog is shown in the What's New
dialog.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): contract for a watchable, stoppable AI review

Background
An AI review of a large archive is many model requests in a row. Today
it is one POST that answers when everything is done: nothing shows
while it runs, nothing can stop it, and the tokens it spends are
invisible until the end. The user wants to see what is happening, how
far it is and what it costs, and to stop it at any time. Decisions for
this round: the review runs as a server-side job the page can watch
and stop; a review nobody watches stops itself; a token budget per
review stops it on its own; a stopped review keeps the verdicts it
reached and opens no dialog; the progress lives in the AI row of the
Duplicates page.

Changes
- services/duplicateReviewJobService.js (new): the one review job at
  a time. start(), current(), get(), stop(id, reason), subscribe() for
  a server-sent stream (a late subscriber first gets the job as it is
  now), touch(), wait(), result(), toJSON(). The judge receives a
  control object (signal, onProgress, stop, tokenBudget); a partial
  result of a stopped review is kept like a complete one. The idle
  watch stops a job nobody has watched for the configured seconds. A
  finished job stays reachable for ten minutes.
- config/config.js: DUPLICATES_AI_TOKEN_BUDGET (200000, 0 = no limit)
  and DUPLICATES_AI_IDLE_STOP_SECONDS (60, 0 = never).
- schemas.js, OPENAPI/openapi.json: AiReviewProgress, AiReviewJob,
  AiReviewJobEvent; aiReview gains stopped, stopReason and
  pairsNotJudged.
- scripts/run-tests.js, tests/test-duplicate-review-job.js: the
  contract test of the job (9 cases) in the duplicates area.

Testing
- node scripts/run-tests.js --all: 99 registered, 92 pass, 7 skip
  offline, 0 fail.
- eslint and prettier on every touched file; regen without drift.

Impact
Nothing uses the job yet; the judge ignores the control object until
the implementation follows. No route or page changes.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): make the token budget and the idle stop editable in settings

Background
The two brakes of a running AI review landed as environment variables only:
DUPLICATES_AI_TOKEN_BUDGET caps what one review may spend across all its
requests, DUPLICATES_AI_IDLE_STOP_SECONDS ends a review no page has been
watching, so a closed tab cannot leave the model running. Both are exactly
the kind of setting somebody wants to try out once and then adjust, which
means editing a compose file and restarting the container for every attempt.
The other seven DUPLICATES_* variables already have a field in the Duplicates
section of the settings page; these two did not.

Changes
- views/settings.ejs: two number fields at the end of #sec-duplicates, in the
  style of the five above them — duplicatesAiTokenBudget (0-10000000, step
  1000) and duplicatesAiIdleStopSeconds (0-3600). Each hint says what the
  value does, what zero means and what the default is.
- routes/setup.js: GET /settings passes DUPLICATES_AI_TOKEN_BUDGET and
  DUPLICATES_AI_IDLE_STOP_SECONDS to the view with the defaults of
  config/config.js as the fallback; POST /settings destructures both body
  keys, clamps them to their ranges and keeps the currently configured value
  for an empty or non-numeric field, the rule the round-6 fields follow. Zero
  is a value for both and survives the clamp, because the ranges start there
  rather than at one. The @swagger body schema documents both, and the
  Duplicates group of ENV_EXPORT_GROUPS lists them after the existing keys.
- public/js/settings.js: two entries in the field mapping, so an
  operator-injected value greys the field out and carries the "Managed by ENV"
  pill like every other setting.
- OPENAPI/openapi.json regenerated.

Testing
- tests/test-settings-duplicates-section.js grew from 7 to 11 cases: the two
  fields render with their configured values, ranges and hints and close the
  section in that order; every field of the section is paired with its
  environment key in settings.js; the POST round trip persists all nine
  values; a budget of 99999999 is capped at 10000000 and an idle stop of -5
  lands on 0; zero survives for both, because it means "no limit" and "never"
  rather than an unset field; a fractional value is rounded; a cleared or
  unparsable field keeps what was stored before; the .env export carries all
  nine keys with the two brakes last.
- node scripts/run-tests.js --all: 99 registered, 92 passed, 7 skipped
  offline, 0 failed — the same numbers as before this change.
- eslint and prettier clean on every file touched; regen-openapi.js leaves no
  drift.
- Looked at the section in Chromium at 1440x1000 and 390x844 against a
  throwaway server outside the repository: both fields render like the seven
  above them, no console errors, and with the two keys in the locked-env set
  both are disabled and carry the "Managed by ENV" pill while a neighbouring
  field stays editable.

Impact
No behaviour change for anybody who never opens the section: the defaults are
unchanged (200000 tokens, 60 seconds) and nothing new runs. Operators who set
either variable in their container environment keep winning — the field is
shown greyed out rather than silently overwritten. A saved value needs a
restart to take effect, as the hints say, because config/config.js reads the
environment once at load.

Upstream Status
Not applicable — the Duplicates page is specific to this fork.

* feat(ai): let every provider take an abort signal for one call

aiGenerateOptions gains abortSignal(options); the four provider
services pass it on where their client expects it — the OpenAI SDK as
the second argument of create(body, { signal }) for OpenAI, Azure and
the custom endpoint, axios as { signal } in the request config for
Ollama. Without a signal every provider sends exactly what it sent
before: no second argument at all, and the unchanged axios config.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): the AI review reports, stops and counts its tokens

Background
"Während die AI befragt wird, könnten Millionen von Tokens im
Hintergrund verbraten werden, ohne dass man es sieht. Man muss es auch
abbrechen können." The judge answered when it was done and said
nothing while it worked, so the page had nothing to show and nothing
to stop. The job of the previous round hands it a control object; this
round makes the judge use it. A bar needs a denominator before the
first request, which the old per-kind loop could not give: it read the
archive, asked, and only then looked at the next kind.

Changes
- services/entityMatchAiService.js: reviewScan(options, control = {})
  runs in two passes. Pass one, for every kind of the review: read the
  entities and the band, build the pairs, settle the spelling-rule
  pairs, gather titles, neighbourhood and excerpts, and size the
  batches. Pass two judges kind after kind. Nothing is asked before
  the whole plan exists.
- Progress: phase scanning before the scan, phase evidence per kind
  and per read, one phase judging with requestsPlanned, pairsTotal and
  estimatedTokens for the whole review, one report per answered
  request (requestsDone, pairsJudged, the running token total,
  failedRequests, retries, kind, and the line naming the next
  request), phase escalating when an unsure pair is asked again, phase
  finishing before the groups are built. A split answer adds its
  halves to requestsPlanned in the report of the request that split,
  so the bar never goes backwards; the escalation adds its own
  requests and pairs the same way. Elapsed time and the estimate stay
  with the job, which derives them.
- Stopping: control.signal is read before every read, every request
  and the second round, and travels to the provider, so a stop lands
  on a request in flight. A request that dies on the signal is a stop,
  not a failure: no failed request, no retry, and no "unsure" — the
  pairs stay without a verdict, so they cannot become a group. A
  stopped review returns what it reached; it never throws.
  aiReview now always carries stopped, stopReason (null; the job fills
  it in) and pairsNotJudged.
- Token budget: one running total for the whole review, folded from
  the provider's usage or, for a provider that reports none, from the
  measured prompt plus the estimated answer, so the counter and the
  budget work for every provider (aiReview.tokens keeps reporting only
  what a provider stood behind). When control.tokenBudget is reached
  the review calls control.stop('token-budget') and behaves as
  stopped.
- Logs: "review stopped (user|token-budget|idle): N of M request(s)
  made, P pair(s) not judged, T token(s)." and "token budget 200000
  reached after N request(s) (T tokens)."; the start, request and
  finish lines are unchanged.
- services/duplicateReviewJobService.js: the control object gains
  stopReason(), the one seam the judge needs to name the reason in its
  own log line.
- reviewPairs(pairs, options) additionally takes plan, systemPrompt
  and tracker from reviewScan; a caller that brings none gets what it
  always got.

Testing
- node scripts/run-tests.js --all: 99 registered, 92 pass, 7 skip
  offline, 0 fail (the baseline of the branch).
- tests/test-entity-match-ai-service.js: 13 new cases (64 total) —
  the plan before the first request for one and for two kinds, the
  split and the escalation raising the plan, a failed request still
  moving the bar, a stop between requests and a stop in flight, the
  token budget, a provider without usage, an already aborted signal, a
  review without a control, the report carrying nothing the job
  derives, and the signal reaching all four providers. The one moved
  expectation is the deep-equal on aiReview, which now names the three
  new fields.
- tests/test-duplicate-review-job.js: one case for stopReason().
- A real run through the job service over a fake archive: a review
  that runs through, the same one stopped after request 2, and the
  same one against a token budget.
- eslint and prettier on every touched file.

Impact
The page can show a bar with a denominator, an estimate and a running
token count from the first request, and a stop costs at most one
request that is already in flight. A review without a control object
behaves exactly as before, so the synchronous route is untouched until
it is moved onto the job.

Upstream Status
Not applicable: the Duplicates page and its AI review do not exist
upstream.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): watch and stop the AI review from the page

Background

A review of a drifted archive is many model requests in a row. Until now
"Ask the AI" was one POST that answered when everything was over: a spinner,
no idea how many requests were still coming, no idea what it cost, and no way
out but reloading the tab — which left the model running. The job service of
the contract commit made the review watchable and stoppable on the server;
this wires the routes and the page onto it.

Changes

routes/setup.js (Duplicates block only)
- parseAiReviewRequest(body) holds the validation both entry points share, so
  the synchronous route and the job route can no longer drift apart.
- POST /api/duplicates/ai-review/jobs starts a review and answers
  202 { job }; while one runs it answers 409 with that running job, so a
  second tab attaches instead of failing.
- GET /api/duplicates/ai-review/jobs/current answers { job } or { job: null }
  and counts as watching the review.
- GET /api/duplicates/ai-review/jobs/:id answers { job, result }, 404 for an
  unknown id, and also counts as watching.
- GET /api/duplicates/ai-review/jobs/:id/events streams AiReviewJobEvents
  (text/event-stream, no-cache, X-Accel-Buffering: no, keep-alive, flush after
  every write), a ": keep-alive" comment every 15 s, and ends after done,
  stopped or failed. An unknown id is a JSON 404 before any stream header.
- POST /api/duplicates/ai-review/jobs/:id/stop answers { job }; stopping a
  finished review is a 200 no-op.
- POST /api/duplicates/ai-review now starts that same job and waits for it: a
  stopped review answers 200 with the verdicts it reached, a failed one keeps
  the judge's status, and a second request while one runs is a 409. It
  subscribes for the duration so the idle stop cannot end a review somebody is
  waiting for.
- @swagger for every new route; OPENAPI/openapi.json regenerated.

views/duplicates.ejs, public/js/duplicates.js, public/css/pages/duplicates.css
- A progress panel in the AI row (#dupAiProgress): bar (#dupAiProgressFill,
  indeterminate while the plan is unknown), message, counters
  ("Request 3 of 8 · 40 of 96 pairs · 12.4k of 200k tokens"), time
  ("about 40 s left · 1:24 elapsed") and a Stop button (#dupAiStopBtn). After
  the end it keeps one outcome line and hides on the next scan or review.
- askForVerdicts() starts the job, follows it through EventSource and falls
  back to polling the job every 2 s when the stream breaks. It resolves
  { aiReview, stopped }; all three AI paths honour `stopped` — the notice is
  shown and neither the guided dialog nor the proposal opens.
- On load the page asks for the current job and re-attaches to one that is
  still running; a finished one is left alone.
- Pure helpers formatTokens, formatEta, formatElapsed, progressPercent and
  stopNotice word the numbers; the UI test evaluates them directly.

Testing

- node scripts/run-tests.js --all: 99 registered, 92 pass, 7 skip offline
  (unchanged); duplicates-endpoints 20 -> 30 cases, duplicates-ui 48 -> 57.
- eslint, prettier, stylelint clean on every touched file; regen-openapi
  leaves no diff.
- Reviewed in a browser against a throwaway server with a judge that reports
  eight requests: mid-run, stopping, stopped and done, desktop and phone,
  light and dark, no console errors. A page loaded while a review runs
  re-attached and rendered its result; with the event stream blocked the same
  review came home through eight polls.

Impact

The Duplicates page shows what a review is doing and costing and can end it;
the verdicts already reached are kept. The synchronous route keeps its request
and response, so an API client sees no change beyond the new 409 while a
review runs.

Upstream Status

Not applicable — the Duplicates feature does not exist upstream.

* fix(duplicates): a late Stop answer no longer paints over the outcome; changelog for the review job

Background
In the browser smoke test of the round, a stop pressed after the first
answered request ended the job before the stop request itself answered.
The page then rendered that answer, a snapshot from the stopping moment,
over the outcome line and restarted the elapsed clock, so the panel read
"Stopping after the current request…" next to a finished review.

Changes
- public/js/duplicates.js: stopReview() renders the stop answer only
  while the same job is still followed and still live.
- tests/test-duplicates-ui.js: one case that pins the guard (57 -> 58).
- config/changelog.js: three entries for the round under the current
  release (the review as a job with progress and Stop, the token budget
  and the idle stop as settings, the plan before the first request).

Testing
- node scripts/run-tests.js --test duplicates-ui: 58 passed.
- Browser smoke against a fake Paperless-ngx and a slowed-down fake
  provider: Stop during request 2 leaves "Stopped after 1 of 5 requests
  · 1 of 5 pairs judged · 1.1k tokens" on the panel, the verdicts
  reached stay on the cards, no dialog opens; the proposal path stops
  the same way; a token budget of 2500 stops the review after 3
  requests with the budget named in the notice and the log; a page
  reloaded during a review re-attaches and renders the result; the
  round-6 walkthrough (scan, merge, undo, dismiss, merge by hand, batch,
  guided review, proposal, plain review) passes unchanged.
- eslint and prettier on the touched files.

Impact
Visual only; the review itself was stopped correctly before the fix.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): contract for a judge that measures the model, streams its answers and thinks only on request

Background
On a real archive with a hosted Qwen model the first review request
asked about 25 pairs, ran for 103 seconds and died at its own answer
cap: the model spent the whole budget thinking before the first
verdict, the cut-off text was thrown away, and the page showed nothing
but a ticking clock for two minutes. Three scans of 13 seconds each
came before that. Decisions for this round: the judge measures the
model on a small first request and sizes every later request to a
target duration; the providers stream the answer so the page moves
inside a request and a cut-off answer keeps its verdicts; thinking is
off for the judge unless the operator switches it on; the review
reuses a fresh scan instead of scanning again.

Changes
- config/config.js: DUPLICATES_AI_THINKING (no) and
  DUPLICATES_AI_REQUEST_SECONDS (30).
- schemas.js, OPENAPI/openapi.json: AiReviewProgress gains
  requestPairs, requestAnswers, requestTokens, thinking, batchSize and
  calibrated; the phase list gains warming-up.
- services/duplicateReviewJobService.js: the new progress fields, the
  warming-up phase, and a time estimate from the share of pairs done
  (answers streamed in count), because the batch size may change after
  the warm-up.
- services/aiGenerateOptions.js: reasoningEnabled(options) and
  progressHandler(options), the two switches the judge will send and
  the providers will read, with the GenerateTextProgress shape and the
  partialText rule for cut-off answers.
- scripts/run-tests.js, tests/test-ai-provider-streaming.js: a
  registered placeholder for the provider streaming test.

Testing
- node scripts/run-tests.js --all: 100 registered, 93 pass, 7 skip
  offline, 0 fail.
- eslint and prettier on every touched file; regen without drift.

Impact
Nothing reads the new switches yet; the implementation follows.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* test(helpers): fake OpenAI-compatible and Ollama servers on ephemeral ports

* feat(providers): stream the answer, report progress, keep the cut-off text

Background

A hosted model behind the custom provider spent 103 seconds and the whole
3200-token completion cap on one AI-review request, then threw "the answer hit
a token limit" and dropped every character it had produced. Nothing was visible
while it ran, nothing survived the throw, and the batch was split and paid for
again from the beginning. Two causes: the four provider services always sent a
non-streaming request, so there was nothing to watch; and
assertCompletionNotTruncated() threw before anyone read the content, so the
prefix was thrown away. On top of that the model thinks before it answers, and
on a server that separates thinking from answering the reasoning arrives as
reasoning_content deltas that no provider knew about.

Changes

- services/aiGenerateOptions.js: the shared streaming machinery.
  stripReasoningText() removes <think> blocks, including one a cut-off left
  open. createProgressCollector() assembles a streamed answer, splits reasoning
  from answer incrementally (a marker may be cut across two chunks), counts the
  completion tokens from a usage chunk or estimates them over everything
  produced, reasoning included, and reports at most once per 100 ms plus one
  final report that says done. consumeChatCompletionStream() and
  runChatCompletionStream() are the OpenAI-compatible half: read the stream,
  finish before any throw, and turn a cut-off or a stop into an error that
  carries what arrived. isAbortError()/abortedGenerationError() give a stopped
  request one name across the SDK, axios and fetch.
- services/serviceUtils.js: estimateTokenCount() (the same character-based
  estimate, on a length) and an optional fourth argument on
  assertCompletionNotTruncated() that puts partialText on the error.
- services/openaiService.js, services/customService.js,
  services/azureService.js: generateText() streams when the caller hands in
  onProgress, with stream_options: { include_usage: true } on OpenAI and the
  custom provider and on Azure only from API version 2024-06-01, where the API
  takes it. Without a handler the body is exactly what it was. Both paths strip
  reasoning from the answer and attach the prefix to a truncation error; an
  abort throws an AbortError with partialText.
- services/customService.js: reasoning: false adds
  chat_template_kwargs: { enable_thinking: false } and, for a model name
  matching /qwen/i, that family's soft switch on its own line at the end of the
  user message; reasoning: true sends enable_thinking: true and no soft switch;
  without the option nothing new is sent.
- services/ollamaService.js: generateText() reads NDJSON from an axios
  responseType: 'stream' response, keeps the tail of a socket read until its
  newline arrives, treats the thinking field as thinking, and stops reading the
  moment the signal aborts. reasoning: false/true sends think and overrules
  OLLAMA_THINK; without the option OLLAMA_THINK still decides. The cut-off
  check the analysis path has always run now runs here too, with partialText,
  and a failure no longer erases a token count that was already measured.
- tests/helpers/fake-openai.js, tests/helpers/fake-ollama.js: real HTTP servers
  on ephemeral ports, scripted per request (content chunks, reasoning chunks,
  finish reason, usage chunk or none, per-chunk delay, non-streaming answers
  from the same script), recording every request body and whether the client
  hung up early.
- tests/test-ai-provider-streaming.js replaces its placeholder with 22 cases.

Testing

- node tests/test-ai-provider-streaming.js: 22 passed, 0 failed; run five
  times, no flake.
- node scripts/run-tests.js --all: 93 passed, 7 skipped offline, 0 failed —
  the same numbers as before this change.
- npx eslint and npx prettier --check on every touched file: clean.
- A throwaway process reproduced the reported failure against the fake: the
  progress reports show thinking first with no text, then the answer growing,
  then one done report with the exact token count from the usage chunk, and the
  throw carries the 131 characters of JSON that had arrived.

Impact

No caller behaves differently unless it asks: without onProgress the request
body is byte for byte what it was, and the round-7 provider cases assert that.
What does change for every caller of generateText(): a <think> block no longer
reaches the returned string, a truncation error now carries partialText, an
abort now throws under the name AbortError, and Ollama's generateText() now
raises the same truncation error the analysis path raises instead of returning
a half-written answer. The document analysis path is untouched.

Upstream Status

Not upstream. Streaming, progress reporting, the partial text of a cut-off
answer and the thinking switch do not exist in clusterzx/paperless-ai.

* feat(duplicates): the progress panel moves inside a request and names the measured batch size

Background

A review of a large archive is a handful of long model requests, and the
panel only moved between them. One request took 103 seconds while the page
showed "request 1 of 4 - 0 of 82 pairs" and a ticking clock, so for minutes
at a time the only honest reading of the page was "nothing is happening".
The judge now measures the model on a small first request, sizes every later
one to a configured number of seconds, and streams the answers as they
arrive, which gives the page three things it never had: answers inside a
request, a warm-up phase, and a model that says when it is thinking.

Changes

Page (views/duplicates.ejs, public/js/duplicates.js,
public/css/pages/duplicates.css):

- progressPercent() counts pairs whenever the plan knows them, the answers
  of the running request included, and falls back to requests only while no
  pair count exists. The bar therefore moves during a request instead of
  jumping once per request.
- progressCountsText() gained the "7 of 10 answers" part, printed only while
  a request is in flight and capped at the size of that request.
- progressTimeText() says "measuring the model" in the warm-up and "the
  model is thinking" while the model writes reasoning, instead of a clock
  that cannot move; an estimate the job already made is still shown next to
  either.
- New #dupAiProgressNote line under the counts, written by the new
  progressNoteText(): "4 pairs per request while the model is measured"
  before the measurement, "9 pairs per request, sized from the model's
  answers" after it, empty while no size is known. A zero-width space holds
  its row open for as long as a review runs (.dup-progress--live), so the
  stats tiles below do not jump the moment it fills.
- .dup-progress__fill--thinking pulses while the model reasons, slower than
  the indeterminate band, and is switched off under prefers-reduced-motion.
- The outcome line and the "Model requests" tile both name the batch size the
  review settled on.
- New htmlReviewFailure(): all three AI paths report a failed review with the
  judge's own message plus one link, "Open the Duplicates settings", to
  /settings#duplicates-tab.

Settings (views/settings.ejs, public/js/settings.js, routes/setup.js):

- Two fields close the Duplicates section: the switch "Let the judge think"
  (DUPLICATES_AI_THINKING, default off) and the number "Seconds per model
  request" (DUPLICATES_AI_REQUEST_SECONDS, 5-300, default 30). GET, POST with
  the usual clamping and keep-the-previous-value behaviour, the @swagger
  request body, ENV_EXPORT_GROUPS and the two "Managed by ENV" selectors.

Route:

- GET /api/duplicates/scan passes fresh: true; a scan somebody pressed a
  button for must not be answered from a cache.

OPENAPI/openapi.json regenerated.

Testing

- node scripts/run-tests.js --all: 93 passed, 7 skipped offline, 0 failed
  (unchanged from the baseline of this round).
- duplicates-ui 58 -> 66 cases: the bar with streamed answers and without a
  pair count, the counts line with and without a running request, the three
  wordings of the time line, the note line, the outcome line with a batch
  size, the panel ids and the thinking class, the settings link of the failed
  notice, and the stylesheet's pulse with its reduced-motion rule.
- settings-duplicates-section 11 -> 15 cases: both fields render with their
  values and hints, the POST round trip, clamping (2 -> 5, 999 -> 300), the
  cleared field keeping the previous value, the switch spellings, the export
  group order and the two selectors.
- duplicates-endpoints 30 -> 31 cases: the scan route hands fresh: true to
  the service.
- eslint, prettier and stylelint clean on every touched file; regen-openapi
  leaves no drift.
- Looked at in Chromium against a throwaway server on port 3403 that walks a
  scripted review through the warm-up, a thinking stretch and a request whose
  answers climb 0 -> 10: desktop and phone, light and dark. The stats tiles
  sit at the same offset before and after the note line fills.

Impact

The panel reports inside a request rather than between requests, and names
both the warm-up and the measured batch size, so a review that takes minutes
per request looks like work rather than a hang. A failed review points at the
setting that would have prevented it. Nothing scans, judges or merges on its
own; the two new settings are read at startup like the rest of the section.

Upstream Status

Not applicable - the Duplicates page does not exist upstream.

* feat(duplicates): measure the model, size every request to it, and reuse a fresh scan

Background

Asking the AI about a scan of the user's archive did not work on their
instance. The judge sent 25 pairs with a completion cap of 3200, the hosted
model thought before it answered and spent all 3200 tokens on the thinking,
and 102 seconds later nothing had been judged. The answer was then split into
13 + 12, which buys nothing: the thinking does not get cheaper with fewer
pairs. Meanwhile the page showed "request 1 of 4 · estimating…" for two
minutes, because a request only reports when it is over. The user pressed
Stop.

The same run also scanned the archive three times inside 50 seconds — the
page's scan, the AI proposal's and the review job's — 1359 tags and 13
seconds each, with nothing changing in between.

Changes

services/entityMatchAiService.js

- Thinking off by default. Every judge request carries
  `reasoning: config.duplicatesAiThinking === true`, so a reasoning model
  answers instead of deliberating unless the operator asked for it. Nothing
  else about the prompt changed.
- A warm-up instead of a guess. The first request of a review whose model has
  not been measured asks about at most WARMUP_PAIRS (4) pairs with a
  deliberately generous cap (RESPONSE_TOKENS, the flat estimate or
  WARMUP_MIN_CAP, whichever is largest, bounded by the context window). It is
  announced under the phase `warming-up` with the message "Measuring the model
  with a small first request…", `calibrated: false` and the size it will use;
  the plan reported with it is provisional and the log says so.
- Sizing from the measurement. Every answered request yields tokens per pair
  (thinking included) and tokens per second, each smoothed by half against the
  measurement before it. From them:
  `batchSize = clamp(floor(requestSeconds × tokensPerSecond ÷ tokensPerPair), 1, batchSize())`
  and `cap = ceil(tokensPerPair × batchSize × 1.5) + TOKENS_OVERHEAD`, both
  bounded by the context window as the batch planning bounds them.
  `requestSeconds` is DUPLICATES_AI_REQUEST_SECONDS, at least 5, 30 by
  default. A batch is now taken off the front of a queue rather than chunked
  up front, because its size changes while the review runs.
- The plan settles after the warm-up. `requestsPlanned` and `estimatedTokens`
  are re-derived from the pairs nobody has asked about yet and reported with
  `batchSize` and `calibrated: true`, so the page's denominator stops moving.
- Truncation: raise before halving. A cut-off answer that salvaged nothing is
  asked again with twice the cap (the warm-up gets the whole window at once),
  and only when that bought nothing — or the cap is already at the window's
  bound — is the batch halved as before. A warm-up that does not fit even then
  ends the review as failed with a message the operator can act on, naming
  DUPLICATES_AI_THINKING and TOKEN_LIMIT. A single pair at the bound keeps the
  old "unsure" and its log line.
- The cut-off text counts. All four providers now attach `error.partialText`,
  so the salvage path runs for every one of them; a salvaged request counts
  its verdicts in `pairsJudged` and in the tracker. Two comments that still
  said only Ollama returns half-written answers were rewritten.
- Progress inside a request. With a progress sink the provider is asked to
  stream (`onProgress`). Each report, at most every 250 ms, carries
  `requestPairs`, `requestAnswers` (the complete verdict objects counted off
  the streamed text), `requestTokens`, `thinking` and the running token total:
  "The model is thinking… (640 tokens so far)" while it thinks, otherwise the
  request line with " · 7 of 10 answers" appended. The report that counts the
  request resets all four. A review nobody watches sends the plain request it
  always sent.
- Calibration memory. The last measurement per model name lives on the
  singleton; a review that finds one starts sized from it, skips the warm-up
  and says so in the log. A measurement taken with thinking on is never reused
  with thinking off. `resetCalibration()` for tests.
- Logs: the finish line says "N pair(s) planned" (the number is the plan), the
  batch-size line is marked provisional until the model is measured, and the
  split line says whether the cap was raised or the batch halved.

services/duplicateMergeService.js

- `scan()` keeps its result per set of options (kind, threshold,
  includeDismissed) for SCAN_CACHE_MS (60 s) and answers the next identical
  request from it with one log line instead of the start and finish lines.
  `fresh: true` skips and refills it; the page's Scan button sends it.
- A merge, an undo, a dismissal and `restoreDismissal()` empty the cache. A
  dismissal deleted through the route, which talks to the model directly, is
  caught by a fingerprint (row count and highest id per kind) checked on every
  hit — one local SELECT against a 13-second scan.
- `reviewScan()` calls `scan()` without `fresh`, so a proposal made right
  after the page scanned costs no second scan.

Testing

- node scripts/run-tests.js --all: 93 passed, 7 skipped offline, 0 failed
  (100 registered), unchanged from the baseline.
- tests/test-entity-match-ai-service.js: 65 -> 80 cases. New: thinking off and
  on; the warm-up's size, cap, phase and message; the sizing math on a fixed
  usage and duration; the request seconds and their floor; the context window
  bounding size and cap; smoothing; the plan and estimate recomputed after the
  warm-up; calibration reused, not reused across the thinking switch, reset; a
  warm-up that cannot fit ending the review with its message; a truncated
  answer with partialText salvaged and counted; a streamed request reporting
  thinking, then answers, then clearing itself; an unwatched review not
  streaming; a review served from the page's scan.
- tests/test-duplicate-merge-service.js: 17 -> 22 cases. New: cache hit, other
  options and `fresh` missing it, expiry, invalidation by merge, undo, dismiss
  and restore, and a dismissal removed behind the service.
- Changed expectations, all from the raise-before-halve rule: the truncation
  cases now see every size asked twice (once, once with twice the cap) before
  it is halved, the single pair is asked twice before it ends as unsure, and
  the planning cases see the `warming-up` phase where they saw `judging`.
- Two demo runs against a fake model at 30 tokens/s: thinking off, 12 pairs —
  warm-up 4 pairs in 20 s (600 tokens, 150 per pair), then requests of 5 pairs
  at 25 s, 4500 tokens, 60 s in total. Thinking on — warm-up 4 pairs in 40 s
  (1200 tokens, 300 per pair) and requests of 2 pairs at 30.04 s, the
  configured length.

Impact

The first request of a review is seconds rather than minutes, every later one
lasts about as long as the operator asked, and the page shows the model
thinking and answering while it happens instead of a still bar. A review of a
model that was measured before starts at full size. Three scans of one archive
become one. Nothing runs on its own and no verdict changed: the prompt, the
rules and the shape of an answer are what they were.

Upstream Status

Not applicable — the Duplicates feature does not exist upstream.

* fix(duplicates): a review never asks for a fresh scan of its own

reviewScan() drops a `fresh` flag its caller may carry instead of passing it on, so a route that forwards the page's scan options cannot make the review scan the archive a second time.

* fix(duplicates): the yes/no switches of the judge read 'yes', and a small batch is not starved after a thinking one

Background
The browser smoke test of the round ran the thinking scenario and the
judge kept saying "thinking off" although DUPLICATES_AI_THINKING=yes
was set. config/config.js normalises every yes/no setting to the
strings 'yes' and 'no' (parseEnvBoolean), while three readers in the
judge asked Boolean() or === true: the thinking switch could never be
turned on, and the review and excerpt switches could not be turned off
('no' is a truthy string). The second finding: a thinking model pays a
fixed price per request, so a one-pair request sized by pairs alone
after a four-pair warm-up got a cap the same thoughts did not fit; the
judge recovered by raising the cap, at the cost of one request.

Changes
- services/entityMatchAiService.js: switchedOn() accepts 'yes' and a
  boolean true; isEnabled(), excerptsEnabled() and thinkingEnabled() use
  it. The cap never drops below the largest completion the model has
  produced in this review plus a quarter (CAP_FLOOR_FACTOR), and that
  floor is remembered with the calibration.
- tests/test-entity-match-ai-service.js: one case per finding (82
  cases), the sizing case expects the remembered floor.
- config/changelog.js: three entries for the round under the current
  release.

Testing
- node scripts/run-tests.js --test entity-match-ai-service: 82 passed.
- Browser smoke against a fake Paperless-ngx and a fake provider that
  streams, thinks on request and honours max_tokens: thinking off, the
  fake never thought, warm-up 4 pairs, 59 tokens/s measured; thinking
  on, the panel showed the thinking state, no request hit the token
  limit any more; Stop, re-attach, token budget and the round-6
  walkthrough unchanged.

Impact
DUPLICATES_AI_REVIEW=no and DUPLICATES_AI_EXCERPTS=no now do what they
say; DUPLICATES_AI_THINKING=yes now reaches the model.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): contract for the creation guard, the semantic sweep, unused objects, renames and a remembered calibration

Background
Round 9 of the Duplicates feature, six points the user picked: stop
the drift where it starts (document analysis creating "Rechnungen"
next to "Rechnung"), let the model find synonyms and translations the
string matcher cannot, list and delete unused objects with undo, name
the survivor of a merge, keep the judge's measurement of a model across
restarts, and scan faster. Decisions: only hard matcher tiers map a
new name onto an existing one (case, umlauts, legal form, plural, word
order), typo-like matches are logged and …
…, name an empty answer (#337)

* feat(duplicates): contract for a targeted AI review

Background
With many groups at 94 to 96 percent the user wants to say "everything
from 95 percent up: ask the AI, show me its view, then merge". The
review must therefore be able to judge only chosen groups and skip the
band of near-misses.

Changes
- schemas.js, OPENAPI/openapi.json: groupIds, minConfidence and
  includeCandidates on DuplicateAiReviewRequest.

Testing
- node scripts/regen-openapi.js: no drift after the commit.

Impact
Request fields only; the implementation follows.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): targeting counters in the AI review result schema

Background
A targeted review reports which groups it judged and which it left
without a verdict; the page shows that.

Changes
- schemas.js, OPENAPI/openapi.json: targeted, groupsJudged and
  groupsSkipped on DuplicateAiReviewResult.aiReview.

Testing
- node scripts/regen-openapi.js: no drift after the commit.

Impact
Documentation of three informational fields.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): let the AI review be pointed at a few groups

Background

An archive with hundreds of correspondents produces dozens of groups at
94, 95 and 96 per cent, and asking the model about all of them costs a
lot to answer a question about a handful. The page needs to select the
groups it is about to merge, ask about those, and keep rendering the
rest of the scan while it does.

Changes

- entityMatchAiService.reviewScan() takes three options that narrow what
  is asked, never what comes back:
  - groupIds: only these scan groups are judged. Every other group is
    still in `groups`, as the scan produced it, with `aiVerdict: null` on
    the group and on every member and `source: 'scan'`. An id this scan
    does not know is ignored and logged once with the count.
  - minConfidence: only groups scoring at least this much are judged;
    together with groupIds both conditions have to hold.
  - includeCandidates (default true): false leaves the band of
    near-misses out entirely, so `candidates` is 0 — and with no band
    the entity list per kind is not read either, which is the cheap part.
- _pairsForKind() takes the set of group ids to judge. A group left out
  contributes no pairs but its member pairs still count as "inside one
  group", so it cannot reappear as a candidate.
- The result reports the targeting: aiReview.targeted, .groupsJudged and
  .groupsSkipped. The start line of the log names it as
  "judging 1 of 4 group(s) (min confidence 0.95, 3 ids), band skipped",
  the closing line adds the two counters. An untargeted review logs and
  behaves exactly as before.
- POST /api/duplicates/ai-review validates and passes the three fields
  through: groupIds an array of at most 500 non-empty strings,
  minConfidence a number in [0.5, 1], includeCandidates a real boolean
  (the string "false" is a 400). An option the request does not mention
  is left out of the service call, so an untargeted request reaches
  reviewScan() with the same object it did before.
- Swagger description of the route and the 400 reason updated,
  OPENAPI/openapi.json regenerated.

Testing

- node scripts/run-tests.js --all -> 90 passed, 7 skipped offline,
  0 failed (97 registered), unchanged against the baseline.
- entity-match-ai-service: 28 -> 34 cases. Six new ones on a fixture
  whose four groups sit exactly on the matcher tiers (1, 0.98, 0.95,
  0.9) plus one pair in the band: groupIds judges only what it names,
  minConfidence filters, includeCandidates: false skips the band and
  reads no second entity list, groupIds and minConfidence combine while
  unknown ids are ignored, an empty selection costs no request, and the
  log lines. The existing aiReview assertion gained the three new fields.
- duplicates-endpoints: 16 -> 19 cases. The three fields reach the
  stubbed reviewScan unchanged, an untargeted request still carries
  nothing extra, ten malformed targeting bodies are 400, and 500 ids are
  accepted while 501 are not.
- Manual run against the real route with a fake store and a fake
  provider: full review 5 pairs / 1 request, minConfidence 0.95 without
  the band 3 pairs, two selected ids (one unknown) 1 pair, and every
  unjudged group back with null verdicts.
- eslint, prettier and the OpenAPI drift check clean on the touched
  files.

Impact

Additive. A review that says nothing about the three options behaves and
logs as before. The page can ask about the groups it selected before a
batch merge; a dozen groups without the band are one or two model
requests instead of the whole archive. schemas.js still has to gain
targeted, groupsJudged and groupsSkipped on DuplicateAiReviewResult.

Upstream Status

Not applicable: the Duplicates feature is next-only.

* feat(duplicates): sort, select by confidence, and a guided review before merging

Background
----------
On a grown archive a scan answers with dozens of groups that all read 94, 95,
96 percent, and the page offered no way to act on that number: every group had
to be judged by eye, one tick at a time. The three presets were the only
thresholds available, so "everything above 95" was not a question the page
could be asked. And where the AI review existed it judged the whole result
list, which is the most expensive way to ask about the five groups the user
actually cares about.

The rule this follows: the AI is an addition, never a condition. Every flow
below works end to end with the review switched off; with it on, the guided
path is one more button beside the one that was already there.

Changes
-------
Results toolbar (#dupResultsBar), above the selection bar, shown once a scan
has groups:
  - "Sort by" (#dupSortSelect): confidence, documents, target name (locale
    compare), kind then confidence. It moves the DOM nodes instead of
    re-rendering, so a card keeps its target, its source ticks, its selection,
    its verdict and its busy state; the two blocks (scan groups, AI
    candidates) are sorted separately and the divider stays between them.
  - "Select >=" (#dupMinConfidence, #dupSelectMinBtn, #dupMinConfidenceCount):
    ticks every selectable group at or above a whole percent and unticks the
    rest, with a live count of what the click would do.
Custom scan threshold: a fourth sensitivity option "Custom" reveals a number
field (#dupThresholdCustom); the scan and both review paths send that percent
divided by 100. The three presets are unchanged.
Confidence breakdown under "Groups found" (#dupStatBuckets): ">=95 %: A .
90-95 %: B . <90 %: C", counted from the cards after a scan and after a review.
Guided flow (#dupReviewThenMergeBtn, rendered only where the review exists):
asks the model about exactly the ticked groups (groupIds, includeCandidates:
false), puts the verdicts on the cards as a full review does, then shows them
once in a wide dialog - one row per group with target, sources, documents, the
verdict chip and the reason, a live "N of M ticked . K documents" foot line and
the copy-rule check. Ticked rows are merged with the batch machinery; an unsure
or different verdict only comes up unticked and never blocks anything, and what
stays unticked stays selected on the page.
"Merge selected" keeps its place and its weight, first in the bar and without a
model anywhere in its path; its dialog names the guided path in one faint line,
and only where that path exists.
Sort, confidence, sensitivity and the custom threshold are remembered in
localStorage (dup.sort, dup.minConfidence, dup.sensitivity,
dup.thresholdCustom) through two try/catch helpers.

Testing
-------
node scripts/run-tests.js --all -> 90 passed, 7 skipped offline, 0 failed
  (unchanged from the branch baseline).
tests/test-duplicates-ui.js: 25 -> 38 cases. New: the toolbar ids and their
  order, the custom threshold field, the stats breakdown, the guided button
  only with the review, the whole page without the review, the toolbar ids in
  the script, sorting as a DOM move, "Select >=", the wrapped localStorage
  access, the guided request (groupIds / includeCandidates: false) and that
  "Merge selected" never touches the review endpoint, the review dialog markup,
  the tip line, the new CSS classes. Changed: the sensitivity options are read
  from #dupSensitivity alone and now end in "custom"; the undo promise and the
  confirm dialogs are counted one higher each, because the review dialog merges
  and therefore makes the same promise.
Reviewed in a browser against a throwaway mock (twelve groups over 88-100 %, a
  review that honours groupIds): 27 screenshots at 1280x900 and 390x844, light
  and dark, 0 px horizontal overflow everywhere, plus a 31-check behaviour
  probe (guided request, verdict ticks, sorting keeping picks and the divider,
  persistence, a refused review, and the whole page with the review off).

Impact
------
Page only. No route, service, schema or config was touched, so the OpenAPI
spec is unchanged. An instance without the AI review renders and behaves
exactly as before plus the toolbar and the custom threshold. The request the
guided path sends uses fields the contract already carries; a server that
ignores them reviews everything, which the page renders correctly.

Upstream Status
---------------
Not applicable - the Duplicates page does not exist upstream.

Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* docs(duplicates): changelog entries for sorting, select by confidence and the guided review

Background
Round 5 answered the second feedback from a real archive: select by a
number, let the model judge exactly those groups, read its verdicts in
one dialog, merge what stays ticked; sort the groups; a custom threshold.

Changes
- config/changelog.js: two entries in the current v2026.09.01 block.

Testing
- node scripts/run-tests.js --test changelog-releases: passed.

Impact
Documentation only.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): contract for evidence-based verdicts and the AI proposal

Background
A real archive produced "Kontoauszug" / "Kontoumzug": the matcher called
it a spelling distance, the prompt allowed "an obvious typo" as a reason
for same, and the model, seeing names and titles only, agreed. Both are
different things. The judge needs stricter rules and, for pairs linked by
spelling alone, a look at what the documents are about, at a bounded
cost.

Changes
- config/config.js: DUPLICATES_AI_EXCERPTS (default yes),
  DUPLICATES_AI_EXCERPT_CHARS (300), DUPLICATES_AI_EXCERPT_DOCUMENTS (2).
- schemas.js, OPENAPI/openapi.json: AiVerdict gains basis and confidence;
  DuplicateAiReviewRequest gains withExcerpts; aiReview reports excerpts.

Testing
- node scripts/run-tests.js --area duplicates: 6/6; regen without drift.

Impact
Settings and schema only; the implementation follows.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): judge model override and the verdict source in the contract

Background
Decisions for round 6: the matcher's hard tiers settle a pair without the
model, unsure pairs are asked once more with excerpts, and the judge may
run on a stronger model of the same provider.

Changes
- config/config.js: DUPLICATES_AI_MODEL (optional, judge only).
- schemas.js, OPENAPI/openapi.json: AiVerdict.source (model or
  spelling-rule); aiReview.escalated and aiReview.spellingRules.

Testing
- eslint and prettier on the two files; regen without drift.

Impact
Settings and schema only; the implementation follows.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(settings): make every DUPLICATES_ setting editable in its own section

Background
The AI review of the Duplicates page arrived with seven environment
variables and no way to change any of them from the interface. Editing a
container environment and recreating the container is the wrong price for
"try a stronger model for the judge" or "ask about fewer pairs per
request", and the settings page is exactly where those knobs belong.
config/config.js already reads all seven; only the front door was missing.

Changes
- views/settings.ejs: a "Duplicates" section (id="sec-duplicates") inside a
  new duplicates-tab block between the AI sections and OCR, with a nav entry
  in the desktop section nav (icon i-merge) and in the mobile one, in the
  same order as the page. Seven fields, each with a hint that says what the
  value does and what its default is: the AI review switch, the judge model,
  pairs per request, the candidate floor, the excerpt switch, excerpt length
  and documents per entry. Switches go through partials/settings-switch, so
  the hidden yes/no input the POST route reads exists as it does everywhere
  else.
- routes/setup.js: GET /settings passes the seven values (env first, the
  defaults of config/config.js as fallback) in the config object the view
  reads; POST /settings destructures the seven camelCase body keys,
  normalises them and writes them into updatedConfig, so setupService
  .saveConfig persists them with the rest. Numbers are clamped to their
  range; a value that is not a number, or a cleared field, keeps what is
  configured now instead of resetting to the default. The swagger body
  schema documents all seven, and the .env export gained a "Duplicates"
  group between "AI behaviour" and "External API".
- public/js/settings.js: the seven selector to env-key entries, so the
  "Overwritten" and "Managed by ENV" marking covers these fields too.
- OPENAPI/openapi.json regenerated.
- tests/test-settings-duplicates-section.js, registered in the
  observability area.

Testing
- node scripts/run-tests.js --all: 98 registered, 91 passed, 7 skipped
  offline (was 97/90/7). The new test covers the rendered section and its
  nav position, the seven inputs and their values, the POST round trip,
  clamping, the keep-the-previous-value case and the .env export group.
- npx eslint / npx prettier --check --ignore-unknown on every touched file.
- node scripts/regen-openapi.js leaves OPENAPI/openapi.json unchanged.
- Looked at the page in Chromium at 1440x1000 and 390x844 against a
  throwaway server outside the repository; no console errors, the section
  reads like the rest of the page and stacks on the phone.

Impact
Operators can change every DUPLICATES_ value from the settings page. The
existing restart-after-save is what makes them take effect; no new
mechanism. Values injected by the container still win and are shown as
managed, as for every other field. Nothing outside the settings page
changes: no route, service or default behaviour of the Duplicates page
itself is touched.

Upstream Status
Fork-only. The Duplicates page does not exist upstream.

Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): judge spelling-only pairs on evidence, not on distance

Background
A real archive produced "Kontoauszug" next to "Kontoumzug": the matcher
called it a spelling distance, the prompt allowed "an obvious typo" as a
reason for same, and the model, seeing two names and three titles, agreed.
Two different things. The judge needed stricter rules, evidence for the
pairs where spelling is the only link, and a way to say how sure it is and
on what grounds — all without opening a large context window on every pair.

Changes
- entityMatchAiService: the system prompt refuses a small spelling distance
  as a reason of its own ("Kontoauszug" / "Kontoumzug", "Miete" / "Mieter",
  "Bahn" / "Bank"), allows a misspelling only when one spelling is not a
  word, and answers unsure when it cannot tell. The output contract gains
  "basis" (a closed list) and "confidence" (high | low); both are parsed,
  an unknown value becomes null, and every verdict, member verdict and
  aggregate carries them. An aggregate keeps the deciding member's basis
  and takes "low" as soon as one deciding member is low.
- Evidence, graded by what the link is worth: every pair carries matched_by
  and score; every judged entity carries its titles, its matching rule and
  its neighbourhood ("filed_with": the correspondents of a tag's documents,
  the tags of a correspondent's); only the pairs linked by fuzzy, prefix or
  token-order also carry document excerpts. Excerpts are read once per
  entity per review and never for a strong tier. withExcerpts: false or
  DUPLICATES_AI_EXCERPTS=no reads nothing at all.
- A member pair a matcher rule settles (exact-normalized, umlaut-variant,
  legal-form) never reaches the provider: it gets verdict same with
  source: spelling-rule, counts in aiReview.spellingRules and costs no
  request, no read and no token.
- A pair the model calls unsure and that had no excerpts is asked once more
  with them; the second answer replaces the first (aiReview.escalated).
- paperlessService: getRecentDocumentExcerptsByEntity (one read,
  truncate_content, cut to the configured characters at a word boundary)
  and getEntityNeighbourhood (one read, the most frequent neighbour names
  through the existing caches). Both answer [] on any error and never log
  document content.
- The judge may run on its own model (DUPLICATES_AI_MODEL): generateText
  takes an optional model in all four provider services, shared through
  aiGenerateOptions.modelOverride.
- Logs: the per-kind start line names the evidence and the model, the
  request line the pairs with excerpts, the escalation its own line.
- Route POST /api/duplicates/ai-review parses withExcerpts like withTitles;
  swagger description updated and OPENAPI/openapi.json regenerated.

Testing
- node scripts/run-tests.js --all: 97 registered, 90 pass, 7 skip offline.
- tests/test-entity-match-ai-service.js: 35 -> 50 cases (the stricter
  prompt, basis and confidence parsing, excerpts only for spelling-only
  pairs and once per entity, the two switches, the configured cut, the
  Kontoauszug regression, settled pairs, the neighbourhood, escalation, the
  model override, batch sizing with excerpts, and both new client methods).
- tests/test-duplicates-endpoints.js: one case for withExcerpts; the three
  existing option assertions now expect withExcerpts: true.
- Demo run against the fake Paperless-ngx: the Kontoauszug/Kontoumzug pair
  costs 282 prompt tokens with excerpts, a strong pair without excerpts 75.
- eslint, prettier and a regen without drift on every file touched.

Impact
An AI review asks about fewer pairs and knows more about the ones it asks
about. Nothing runs on its own, nothing is merged, and document content
never reaches a log line.

Upstream Status
Not applicable — the Duplicates feature does not exist upstream.

* fix(duplicates): do not escalate an unsure pair whose documents carry no text

* feat(duplicates): one click for the AI's proposal, with the evidence behind it

Background
----------
Everything the page offered so far started from the user: scan, read every
card, tick, merge — and where the AI review existed it was a second question
asked after the first. What was missing is the path the archive's owner
actually wants for a first clean-up: one click that scans, has every group and
every near-miss judged, and then hands over a proposal to thin out rather than
a list to work through.

The rule this follows is the same as in the rounds before: the AI is an
addition, never a condition. Without the review nothing of this renders, and
"Scan Paperless-ngx", "Merge selected", the toolbar, the manual merge and the
guided path are the same as they were.

A verdict also had to say more than "same": with `basis`, `confidence` and a
`source` on the wire, the page can pre-tick exactly what is settled — a pair a
spelling rule decided, or one the model says it is sure about — and leave
everything else to the user. The member tables, finally, measured their own
content per card, so the columns of two cards below each other sat in
different places.

Changes
-------
"AI proposal" (#dupAiProposalBtn, primary, rendered only with aiReviewEnabled)
next to "Ask the AI", usable from the first paint because it scans itself:
  - status in the AI row (#dupAiProposalStatus): "Scanning…", then "Asking the
    AI about N pairs and near-misses…", with the hint line under the row
    (#dupAiProposalHint) saying what the click does;
  - it reuses runScan() (now awaited) with the kind, sensitivity and hidden-pair
    settings on the page, then the one review request with includeCandidates
    and no groupIds. Two requests, and no merge until the dialog is confirmed.
Proposal dialog (.dup-proposal-dialog): one row per group that could be merged,
  sorted same/high, same, unsure, different, unjudged (proposalRank,
  compareProposalEntries — both pure); pre-ticked are only the settled ones
  (isSureSame: verdict "same" with confidence "high", which covers the
  spelling-rule verdicts); legend, "Tick all same" (#dupProposalTickSame),
  "Untick all" (#dupProposalUntickAll), the copy-rule check (#dupCopyRuleAll)
  and a live foot line "N of M ticked · K documents · X objects will be
  deleted". Confirming sets the page selection to the ticked groups and hands
  them to the batch runner of round 4, so the selection bar reports the merge
  as it does for "Merge selected"; cancelling leaves the verdicts on the cards
  and nothing ticked.
Evidence, shared by both dialogs (one row renderer, one table):
  - a "Basis" column as a .zr-badge with a label per contract value;
  - the confidence as a suffix of the verdict chip ("AI: same · high");
  - a pair a spelling rule settled reads "Spelling rule" in the "same" tone
    (.dup-verdict--rule) instead of quoting a model that never saw it;
  - the guided dialog pre-ticks by the same rule, so a "same" the model is
    unsure about now comes up unticked there too.
Cards keep their shape: the verdict chip carries the basis in its title and the
  confidence as its suffix, no new column.
Second checkbox "Use document excerpts for spelling-only pairs"
  (#dupAiExcerpts, checked); withTitles and withExcerpts flow into every review
  request from the one place that builds it. The titles checkbox is relabelled
  "Use document titles and neighbours as context".
"AI-judged pairs" tile: its sub line now also counts "· E excerpts", "· S by
  spelling rule" and "· E escalated" when the review reports them.
Member tables line up across cards: .dup-members is table-layout: fixed with
  the name column taking what is left and truncating, and the matching rule a
  fixed share (.dup-members__name, .dup-members__rule).

Testing
-------
node scripts/run-tests.js --all -> 90 passed, 7 skipped offline, 0 failed
  (unchanged from the branch baseline of 97 registered).
tests/test-duplicates-ui.js: 38 -> 48 cases. New: the proposal ids and labels
  only with the review and the page whole without them; what the flow sends
  (runScan first, includeCandidates: true, no groupIds, both evidence flags,
  no request of its own); the pre-tick rule, evaluated as a function against
  seven verdicts; the row order, evaluated by sorting a shuffled list; a label
  for every basis the AiVerdict schema lists, parsed out of schemas.js; the
  spelling-rule chip; the dialog's parts and that it merges through the batch
  runner; the evidence counters of the stats tile; the fixed member-table
  layout; the new CSS classes. Changed: the titles checkbox label, the undo
  promise and the confirm dialogs counted one higher each (the proposal merges
  and therefore makes the same promise), and the pre-tick assertion of the
  guided row.
Reviewed in a browser against a throwaway mock (eleven scan groups plus three
  the model proposes, verdicts across same/high, same/low, unsure and
  different, some settled by a spelling rule, and a Kontoauszug / Kontoumzug
  pair that only the excerpts decide): 31 screenshots at 1280x900 and 390x844,
  light and dark — the controls, the status line mid-flow, the proposal dialog,
  after "Untick all", mid-merge, after the merge, the guided dialog, the stats
  tile, the aligned member tables and the render without the review. 0 px
  horizontal overflow everywhere; the column offsets of all eleven cards are
  identical.

Impact
------
Page only. No route, service, schema or config was touched, so the OpenAPI
spec is unchanged. An instance without the AI review renders and behaves
exactly as before. The new request field and the new verdict fields are ones
the contract already carries: a server that ignores withExcerpts reviews as it
did, and a verdict without basis, confidence or source renders as it did — it
then simply never comes up pre-ticked, which is the safe side.

Upstream Status
---------------
Not applicable - the Duplicates page does not exist upstream.

Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* chore(duplicates): changelog for the AI proposal round, room for the verdict in the Match column

Background
The sixth round of the Duplicates feature adds the AI-led proposal, the
evidence-based judge and the Duplicates settings section. The member
tables now use a fixed column layout so the columns line up across
cards, which left the Match column too narrow for a verdict such as
"AI: same - high": it wrapped into four lines.

Changes
- config/changelog.js: five entries for the round under the current
  release (AI proposal, evidence-based judge with excerpts and
  DUPLICATES_AI_EXCERPT*, DUPLICATES_AI_MODEL, aligned member tables,
  the Duplicates settings section).
- public/css/pages/duplicates.css: the Match column is 132px wide and
  the member verdict does not wrap, so the percentage and the verdict
  take one line each.

Testing
- npx eslint, prettier --check and stylelint on every file changed
  against nightly: clean.
- node scripts/run-tests.js --all: 91 passed, 7 skipped (server or
  credentials needed), 0 failed.
- node scripts/regen-openapi.js: no drift.
- Browser walkthrough against a fake Paperless-ngx and a fake judge:
  scan, merge, undo, dismiss, merge by hand, batch merge, guided review,
  AI proposal and AI review all pass. The Kontoauszug/Kontoumzug pair is
  judged "different" on its excerpts and does not appear in the
  proposal.

Impact
Visual only for the CSS; the changelog is shown in the What's New
dialog.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): contract for a watchable, stoppable AI review

Background
An AI review of a large archive is many model requests in a row. Today
it is one POST that answers when everything is done: nothing shows
while it runs, nothing can stop it, and the tokens it spends are
invisible until the end. The user wants to see what is happening, how
far it is and what it costs, and to stop it at any time. Decisions for
this round: the review runs as a server-side job the page can watch
and stop; a review nobody watches stops itself; a token budget per
review stops it on its own; a stopped review keeps the verdicts it
reached and opens no dialog; the progress lives in the AI row of the
Duplicates page.

Changes
- services/duplicateReviewJobService.js (new): the one review job at
  a time. start(), current(), get(), stop(id, reason), subscribe() for
  a server-sent stream (a late subscriber first gets the job as it is
  now), touch(), wait(), result(), toJSON(). The judge receives a
  control object (signal, onProgress, stop, tokenBudget); a partial
  result of a stopped review is kept like a complete one. The idle
  watch stops a job nobody has watched for the configured seconds. A
  finished job stays reachable for ten minutes.
- config/config.js: DUPLICATES_AI_TOKEN_BUDGET (200000, 0 = no limit)
  and DUPLICATES_AI_IDLE_STOP_SECONDS (60, 0 = never).
- schemas.js, OPENAPI/openapi.json: AiReviewProgress, AiReviewJob,
  AiReviewJobEvent; aiReview gains stopped, stopReason and
  pairsNotJudged.
- scripts/run-tests.js, tests/test-duplicate-review-job.js: the
  contract test of the job (9 cases) in the duplicates area.

Testing
- node scripts/run-tests.js --all: 99 registered, 92 pass, 7 skip
  offline, 0 fail.
- eslint and prettier on every touched file; regen without drift.

Impact
Nothing uses the job yet; the judge ignores the control object until
the implementation follows. No route or page changes.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): make the token budget and the idle stop editable in settings

Background
The two brakes of a running AI review landed as environment variables only:
DUPLICATES_AI_TOKEN_BUDGET caps what one review may spend across all its
requests, DUPLICATES_AI_IDLE_STOP_SECONDS ends a review no page has been
watching, so a closed tab cannot leave the model running. Both are exactly
the kind of setting somebody wants to try out once and then adjust, which
means editing a compose file and restarting the container for every attempt.
The other seven DUPLICATES_* variables already have a field in the Duplicates
section of the settings page; these two did not.

Changes
- views/settings.ejs: two number fields at the end of #sec-duplicates, in the
  style of the five above them — duplicatesAiTokenBudget (0-10000000, step
  1000) and duplicatesAiIdleStopSeconds (0-3600). Each hint says what the
  value does, what zero means and what the default is.
- routes/setup.js: GET /settings passes DUPLICATES_AI_TOKEN_BUDGET and
  DUPLICATES_AI_IDLE_STOP_SECONDS to the view with the defaults of
  config/config.js as the fallback; POST /settings destructures both body
  keys, clamps them to their ranges and keeps the currently configured value
  for an empty or non-numeric field, the rule the round-6 fields follow. Zero
  is a value for both and survives the clamp, because the ranges start there
  rather than at one. The @swagger body schema documents both, and the
  Duplicates group of ENV_EXPORT_GROUPS lists them after the existing keys.
- public/js/settings.js: two entries in the field mapping, so an
  operator-injected value greys the field out and carries the "Managed by ENV"
  pill like every other setting.
- OPENAPI/openapi.json regenerated.

Testing
- tests/test-settings-duplicates-section.js grew from 7 to 11 cases: the two
  fields render with their configured values, ranges and hints and close the
  section in that order; every field of the section is paired with its
  environment key in settings.js; the POST round trip persists all nine
  values; a budget of 99999999 is capped at 10000000 and an idle stop of -5
  lands on 0; zero survives for both, because it means "no limit" and "never"
  rather than an unset field; a fractional value is rounded; a cleared or
  unparsable field keeps what was stored before; the .env export carries all
  nine keys with the two brakes last.
- node scripts/run-tests.js --all: 99 registered, 92 passed, 7 skipped
  offline, 0 failed — the same numbers as before this change.
- eslint and prettier clean on every file touched; regen-openapi.js leaves no
  drift.
- Looked at the section in Chromium at 1440x1000 and 390x844 against a
  throwaway server outside the repository: both fields render like the seven
  above them, no console errors, and with the two keys in the locked-env set
  both are disabled and carry the "Managed by ENV" pill while a neighbouring
  field stays editable.

Impact
No behaviour change for anybody who never opens the section: the defaults are
unchanged (200000 tokens, 60 seconds) and nothing new runs. Operators who set
either variable in their container environment keep winning — the field is
shown greyed out rather than silently overwritten. A saved value needs a
restart to take effect, as the hints say, because config/config.js reads the
environment once at load.

Upstream Status
Not applicable — the Duplicates page is specific to this fork.

* feat(ai): let every provider take an abort signal for one call

aiGenerateOptions gains abortSignal(options); the four provider
services pass it on where their client expects it — the OpenAI SDK as
the second argument of create(body, { signal }) for OpenAI, Azure and
the custom endpoint, axios as { signal } in the request config for
Ollama. Without a signal every provider sends exactly what it sent
before: no second argument at all, and the unchanged axios config.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): the AI review reports, stops and counts its tokens

Background
"Während die AI befragt wird, könnten Millionen von Tokens im
Hintergrund verbraten werden, ohne dass man es sieht. Man muss es auch
abbrechen können." The judge answered when it was done and said
nothing while it worked, so the page had nothing to show and nothing
to stop. The job of the previous round hands it a control object; this
round makes the judge use it. A bar needs a denominator before the
first request, which the old per-kind loop could not give: it read the
archive, asked, and only then looked at the next kind.

Changes
- services/entityMatchAiService.js: reviewScan(options, control = {})
  runs in two passes. Pass one, for every kind of the review: read the
  entities and the band, build the pairs, settle the spelling-rule
  pairs, gather titles, neighbourhood and excerpts, and size the
  batches. Pass two judges kind after kind. Nothing is asked before
  the whole plan exists.
- Progress: phase scanning before the scan, phase evidence per kind
  and per read, one phase judging with requestsPlanned, pairsTotal and
  estimatedTokens for the whole review, one report per answered
  request (requestsDone, pairsJudged, the running token total,
  failedRequests, retries, kind, and the line naming the next
  request), phase escalating when an unsure pair is asked again, phase
  finishing before the groups are built. A split answer adds its
  halves to requestsPlanned in the report of the request that split,
  so the bar never goes backwards; the escalation adds its own
  requests and pairs the same way. Elapsed time and the estimate stay
  with the job, which derives them.
- Stopping: control.signal is read before every read, every request
  and the second round, and travels to the provider, so a stop lands
  on a request in flight. A request that dies on the signal is a stop,
  not a failure: no failed request, no retry, and no "unsure" — the
  pairs stay without a verdict, so they cannot become a group. A
  stopped review returns what it reached; it never throws.
  aiReview now always carries stopped, stopReason (null; the job fills
  it in) and pairsNotJudged.
- Token budget: one running total for the whole review, folded from
  the provider's usage or, for a provider that reports none, from the
  measured prompt plus the estimated answer, so the counter and the
  budget work for every provider (aiReview.tokens keeps reporting only
  what a provider stood behind). When control.tokenBudget is reached
  the review calls control.stop('token-budget') and behaves as
  stopped.
- Logs: "review stopped (user|token-budget|idle): N of M request(s)
  made, P pair(s) not judged, T token(s)." and "token budget 200000
  reached after N request(s) (T tokens)."; the start, request and
  finish lines are unchanged.
- services/duplicateReviewJobService.js: the control object gains
  stopReason(), the one seam the judge needs to name the reason in its
  own log line.
- reviewPairs(pairs, options) additionally takes plan, systemPrompt
  and tracker from reviewScan; a caller that brings none gets what it
  always got.

Testing
- node scripts/run-tests.js --all: 99 registered, 92 pass, 7 skip
  offline, 0 fail (the baseline of the branch).
- tests/test-entity-match-ai-service.js: 13 new cases (64 total) —
  the plan before the first request for one and for two kinds, the
  split and the escalation raising the plan, a failed request still
  moving the bar, a stop between requests and a stop in flight, the
  token budget, a provider without usage, an already aborted signal, a
  review without a control, the report carrying nothing the job
  derives, and the signal reaching all four providers. The one moved
  expectation is the deep-equal on aiReview, which now names the three
  new fields.
- tests/test-duplicate-review-job.js: one case for stopReason().
- A real run through the job service over a fake archive: a review
  that runs through, the same one stopped after request 2, and the
  same one against a token budget.
- eslint and prettier on every touched file.

Impact
The page can show a bar with a denominator, an estimate and a running
token count from the first request, and a stop costs at most one
request that is already in flight. A review without a control object
behaves exactly as before, so the synchronous route is untouched until
it is moved onto the job.

Upstream Status
Not applicable: the Duplicates page and its AI review do not exist
upstream.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): watch and stop the AI review from the page

Background

A review of a drifted archive is many model requests in a row. Until now
"Ask the AI" was one POST that answered when everything was over: a spinner,
no idea how many requests were still coming, no idea what it cost, and no way
out but reloading the tab — which left the model running. The job service of
the contract commit made the review watchable and stoppable on the server;
this wires the routes and the page onto it.

Changes

routes/setup.js (Duplicates block only)
- parseAiReviewRequest(body) holds the validation both entry points share, so
  the synchronous route and the job route can no longer drift apart.
- POST /api/duplicates/ai-review/jobs starts a review and answers
  202 { job }; while one runs it answers 409 with that running job, so a
  second tab attaches instead of failing.
- GET /api/duplicates/ai-review/jobs/current answers { job } or { job: null }
  and counts as watching the review.
- GET /api/duplicates/ai-review/jobs/:id answers { job, result }, 404 for an
  unknown id, and also counts as watching.
- GET /api/duplicates/ai-review/jobs/:id/events streams AiReviewJobEvents
  (text/event-stream, no-cache, X-Accel-Buffering: no, keep-alive, flush after
  every write), a ": keep-alive" comment every 15 s, and ends after done,
  stopped or failed. An unknown id is a JSON 404 before any stream header.
- POST /api/duplicates/ai-review/jobs/:id/stop answers { job }; stopping a
  finished review is a 200 no-op.
- POST /api/duplicates/ai-review now starts that same job and waits for it: a
  stopped review answers 200 with the verdicts it reached, a failed one keeps
  the judge's status, and a second request while one runs is a 409. It
  subscribes for the duration so the idle stop cannot end a review somebody is
  waiting for.
- @swagger for every new route; OPENAPI/openapi.json regenerated.

views/duplicates.ejs, public/js/duplicates.js, public/css/pages/duplicates.css
- A progress panel in the AI row (#dupAiProgress): bar (#dupAiProgressFill,
  indeterminate while the plan is unknown), message, counters
  ("Request 3 of 8 · 40 of 96 pairs · 12.4k of 200k tokens"), time
  ("about 40 s left · 1:24 elapsed") and a Stop button (#dupAiStopBtn). After
  the end it keeps one outcome line and hides on the next scan or review.
- askForVerdicts() starts the job, follows it through EventSource and falls
  back to polling the job every 2 s when the stream breaks. It resolves
  { aiReview, stopped }; all three AI paths honour `stopped` — the notice is
  shown and neither the guided dialog nor the proposal opens.
- On load the page asks for the current job and re-attaches to one that is
  still running; a finished one is left alone.
- Pure helpers formatTokens, formatEta, formatElapsed, progressPercent and
  stopNotice word the numbers; the UI test evaluates them directly.

Testing

- node scripts/run-tests.js --all: 99 registered, 92 pass, 7 skip offline
  (unchanged); duplicates-endpoints 20 -> 30 cases, duplicates-ui 48 -> 57.
- eslint, prettier, stylelint clean on every touched file; regen-openapi
  leaves no diff.
- Reviewed in a browser against a throwaway server with a judge that reports
  eight requests: mid-run, stopping, stopped and done, desktop and phone,
  light and dark, no console errors. A page loaded while a review runs
  re-attached and rendered its result; with the event stream blocked the same
  review came home through eight polls.

Impact

The Duplicates page shows what a review is doing and costing and can end it;
the verdicts already reached are kept. The synchronous route keeps its request
and response, so an API client sees no change beyond the new 409 while a
review runs.

Upstream Status

Not applicable — the Duplicates feature does not exist upstream.

* fix(duplicates): a late Stop answer no longer paints over the outcome; changelog for the review job

Background
In the browser smoke test of the round, a stop pressed after the first
answered request ended the job before the stop request itself answered.
The page then rendered that answer, a snapshot from the stopping moment,
over the outcome line and restarted the elapsed clock, so the panel read
"Stopping after the current request…" next to a finished review.

Changes
- public/js/duplicates.js: stopReview() renders the stop answer only
  while the same job is still followed and still live.
- tests/test-duplicates-ui.js: one case that pins the guard (57 -> 58).
- config/changelog.js: three entries for the round under the current
  release (the review as a job with progress and Stop, the token budget
  and the idle stop as settings, the plan before the first request).

Testing
- node scripts/run-tests.js --test duplicates-ui: 58 passed.
- Browser smoke against a fake Paperless-ngx and a slowed-down fake
  provider: Stop during request 2 leaves "Stopped after 1 of 5 requests
  · 1 of 5 pairs judged · 1.1k tokens" on the panel, the verdicts
  reached stay on the cards, no dialog opens; the proposal path stops
  the same way; a token budget of 2500 stops the review after 3
  requests with the budget named in the notice and the log; a page
  reloaded during a review re-attaches and renders the result; the
  round-6 walkthrough (scan, merge, undo, dismiss, merge by hand, batch,
  guided review, proposal, plain review) passes unchanged.
- eslint and prettier on the touched files.

Impact
Visual only; the review itself was stopped correctly before the fix.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): contract for a judge that measures the model, streams its answers and thinks only on request

Background
On a real archive with a hosted Qwen model the first review request
asked about 25 pairs, ran for 103 seconds and died at its own answer
cap: the model spent the whole budget thinking before the first
verdict, the cut-off text was thrown away, and the page showed nothing
but a ticking clock for two minutes. Three scans of 13 seconds each
came before that. Decisions for this round: the judge measures the
model on a small first request and sizes every later request to a
target duration; the providers stream the answer so the page moves
inside a request and a cut-off answer keeps its verdicts; thinking is
off for the judge unless the operator switches it on; the review
reuses a fresh scan instead of scanning again.

Changes
- config/config.js: DUPLICATES_AI_THINKING (no) and
  DUPLICATES_AI_REQUEST_SECONDS (30).
- schemas.js, OPENAPI/openapi.json: AiReviewProgress gains
  requestPairs, requestAnswers, requestTokens, thinking, batchSize and
  calibrated; the phase list gains warming-up.
- services/duplicateReviewJobService.js: the new progress fields, the
  warming-up phase, and a time estimate from the share of pairs done
  (answers streamed in count), because the batch size may change after
  the warm-up.
- services/aiGenerateOptions.js: reasoningEnabled(options) and
  progressHandler(options), the two switches the judge will send and
  the providers will read, with the GenerateTextProgress shape and the
  partialText rule for cut-off answers.
- scripts/run-tests.js, tests/test-ai-provider-streaming.js: a
  registered placeholder for the provider streaming test.

Testing
- node scripts/run-tests.js --all: 100 registered, 93 pass, 7 skip
  offline, 0 fail.
- eslint and prettier on every touched file; regen without drift.

Impact
Nothing reads the new switches yet; the implementation follows.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* test(helpers): fake OpenAI-compatible and Ollama servers on ephemeral ports

* feat(providers): stream the answer, report progress, keep the cut-off text

Background

A hosted model behind the custom provider spent 103 seconds and the whole
3200-token completion cap on one AI-review request, then threw "the answer hit
a token limit" and dropped every character it had produced. Nothing was visible
while it ran, nothing survived the throw, and the batch was split and paid for
again from the beginning. Two causes: the four provider services always sent a
non-streaming request, so there was nothing to watch; and
assertCompletionNotTruncated() threw before anyone read the content, so the
prefix was thrown away. On top of that the model thinks before it answers, and
on a server that separates thinking from answering the reasoning arrives as
reasoning_content deltas that no provider knew about.

Changes

- services/aiGenerateOptions.js: the shared streaming machinery.
  stripReasoningText() removes <think> blocks, including one a cut-off left
  open. createProgressCollector() assembles a streamed answer, splits reasoning
  from answer incrementally (a marker may be cut across two chunks), counts the
  completion tokens from a usage chunk or estimates them over everything
  produced, reasoning included, and reports at most once per 100 ms plus one
  final report that says done. consumeChatCompletionStream() and
  runChatCompletionStream() are the OpenAI-compatible half: read the stream,
  finish before any throw, and turn a cut-off or a stop into an error that
  carries what arrived. isAbortError()/abortedGenerationError() give a stopped
  request one name across the SDK, axios and fetch.
- services/serviceUtils.js: estimateTokenCount() (the same character-based
  estimate, on a length) and an optional fourth argument on
  assertCompletionNotTruncated() that puts partialText on the error.
- services/openaiService.js, services/customService.js,
  services/azureService.js: generateText() streams when the caller hands in
  onProgress, with stream_options: { include_usage: true } on OpenAI and the
  custom provider and on Azure only from API version 2024-06-01, where the API
  takes it. Without a handler the body is exactly what it was. Both paths strip
  reasoning from the answer and attach the prefix to a truncation error; an
  abort throws an AbortError with partialText.
- services/customService.js: reasoning: false adds
  chat_template_kwargs: { enable_thinking: false } and, for a model name
  matching /qwen/i, that family's soft switch on its own line at the end of the
  user message; reasoning: true sends enable_thinking: true and no soft switch;
  without the option nothing new is sent.
- services/ollamaService.js: generateText() reads NDJSON from an axios
  responseType: 'stream' response, keeps the tail of a socket read until its
  newline arrives, treats the thinking field as thinking, and stops reading the
  moment the signal aborts. reasoning: false/true sends think and overrules
  OLLAMA_THINK; without the option OLLAMA_THINK still decides. The cut-off
  check the analysis path has always run now runs here too, with partialText,
  and a failure no longer erases a token count that was already measured.
- tests/helpers/fake-openai.js, tests/helpers/fake-ollama.js: real HTTP servers
  on ephemeral ports, scripted per request (content chunks, reasoning chunks,
  finish reason, usage chunk or none, per-chunk delay, non-streaming answers
  from the same script), recording every request body and whether the client
  hung up early.
- tests/test-ai-provider-streaming.js replaces its placeholder with 22 cases.

Testing

- node tests/test-ai-provider-streaming.js: 22 passed, 0 failed; run five
  times, no flake.
- node scripts/run-tests.js --all: 93 passed, 7 skipped offline, 0 failed —
  the same numbers as before this change.
- npx eslint and npx prettier --check on every touched file: clean.
- A throwaway process reproduced the reported failure against the fake: the
  progress reports show thinking first with no text, then the answer growing,
  then one done report with the exact token count from the usage chunk, and the
  throw carries the 131 characters of JSON that had arrived.

Impact

No caller behaves differently unless it asks: without onProgress the request
body is byte for byte what it was, and the round-7 provider cases assert that.
What does change for every caller of generateText(): a <think> block no longer
reaches the returned string, a truncation error now carries partialText, an
abort now throws under the name AbortError, and Ollama's generateText() now
raises the same truncation error the analysis path raises instead of returning
a half-written answer. The document analysis path is untouched.

Upstream Status

Not upstream. Streaming, progress reporting, the partial text of a cut-off
answer and the thinking switch do not exist in clusterzx/paperless-ai.

* feat(duplicates): the progress panel moves inside a request and names the measured batch size

Background

A review of a large archive is a handful of long model requests, and the
panel only moved between them. One request took 103 seconds while the page
showed "request 1 of 4 - 0 of 82 pairs" and a ticking clock, so for minutes
at a time the only honest reading of the page was "nothing is happening".
The judge now measures the model on a small first request, sizes every later
one to a configured number of seconds, and streams the answers as they
arrive, which gives the page three things it never had: answers inside a
request, a warm-up phase, and a model that says when it is thinking.

Changes

Page (views/duplicates.ejs, public/js/duplicates.js,
public/css/pages/duplicates.css):

- progressPercent() counts pairs whenever the plan knows them, the answers
  of the running request included, and falls back to requests only while no
  pair count exists. The bar therefore moves during a request instead of
  jumping once per request.
- progressCountsText() gained the "7 of 10 answers" part, printed only while
  a request is in flight and capped at the size of that request.
- progressTimeText() says "measuring the model" in the warm-up and "the
  model is thinking" while the model writes reasoning, instead of a clock
  that cannot move; an estimate the job already made is still shown next to
  either.
- New #dupAiProgressNote line under the counts, written by the new
  progressNoteText(): "4 pairs per request while the model is measured"
  before the measurement, "9 pairs per request, sized from the model's
  answers" after it, empty while no size is known. A zero-width space holds
  its row open for as long as a review runs (.dup-progress--live), so the
  stats tiles below do not jump the moment it fills.
- .dup-progress__fill--thinking pulses while the model reasons, slower than
  the indeterminate band, and is switched off under prefers-reduced-motion.
- The outcome line and the "Model requests" tile both name the batch size the
  review settled on.
- New htmlReviewFailure(): all three AI paths report a failed review with the
  judge's own message plus one link, "Open the Duplicates settings", to
  /settings#duplicates-tab.

Settings (views/settings.ejs, public/js/settings.js, routes/setup.js):

- Two fields close the Duplicates section: the switch "Let the judge think"
  (DUPLICATES_AI_THINKING, default off) and the number "Seconds per model
  request" (DUPLICATES_AI_REQUEST_SECONDS, 5-300, default 30). GET, POST with
  the usual clamping and keep-the-previous-value behaviour, the @swagger
  request body, ENV_EXPORT_GROUPS and the two "Managed by ENV" selectors.

Route:

- GET /api/duplicates/scan passes fresh: true; a scan somebody pressed a
  button for must not be answered from a cache.

OPENAPI/openapi.json regenerated.

Testing

- node scripts/run-tests.js --all: 93 passed, 7 skipped offline, 0 failed
  (unchanged from the baseline of this round).
- duplicates-ui 58 -> 66 cases: the bar with streamed answers and without a
  pair count, the counts line with and without a running request, the three
  wordings of the time line, the note line, the outcome line with a batch
  size, the panel ids and the thinking class, the settings link of the failed
  notice, and the stylesheet's pulse with its reduced-motion rule.
- settings-duplicates-section 11 -> 15 cases: both fields render with their
  values and hints, the POST round trip, clamping (2 -> 5, 999 -> 300), the
  cleared field keeping the previous value, the switch spellings, the export
  group order and the two selectors.
- duplicates-endpoints 30 -> 31 cases: the scan route hands fresh: true to
  the service.
- eslint, prettier and stylelint clean on every touched file; regen-openapi
  leaves no drift.
- Looked at in Chromium against a throwaway server on port 3403 that walks a
  scripted review through the warm-up, a thinking stretch and a request whose
  answers climb 0 -> 10: desktop and phone, light and dark. The stats tiles
  sit at the same offset before and after the note line fills.

Impact

The panel reports inside a request rather than between requests, and names
both the warm-up and the measured batch size, so a review that takes minutes
per request looks like work rather than a hang. A failed review points at the
setting that would have prevented it. Nothing scans, judges or merges on its
own; the two new settings are read at startup like the rest of the section.

Upstream Status

Not applicable - the Duplicates page does not exist upstream.

* feat(duplicates): measure the model, size every request to it, and reuse a fresh scan

Background

Asking the AI about a scan of the user's archive did not work on their
instance. The judge sent 25 pairs with a completion cap of 3200, the hosted
model thought before it answered and spent all 3200 tokens on the thinking,
and 102 seconds later nothing had been judged. The answer was then split into
13 + 12, which buys nothing: the thinking does not get cheaper with fewer
pairs. Meanwhile the page showed "request 1 of 4 · estimating…" for two
minutes, because a request only reports when it is over. The user pressed
Stop.

The same run also scanned the archive three times inside 50 seconds — the
page's scan, the AI proposal's and the review job's — 1359 tags and 13
seconds each, with nothing changing in between.

Changes

services/entityMatchAiService.js

- Thinking off by default. Every judge request carries
  `reasoning: config.duplicatesAiThinking === true`, so a reasoning model
  answers instead of deliberating unless the operator asked for it. Nothing
  else about the prompt changed.
- A warm-up instead of a guess. The first request of a review whose model has
  not been measured asks about at most WARMUP_PAIRS (4) pairs with a
  deliberately generous cap (RESPONSE_TOKENS, the flat estimate or
  WARMUP_MIN_CAP, whichever is largest, bounded by the context window). It is
  announced under the phase `warming-up` with the message "Measuring the model
  with a small first request…", `calibrated: false` and the size it will use;
  the plan reported with it is provisional and the log says so.
- Sizing from the measurement. Every answered request yields tokens per pair
  (thinking included) and tokens per second, each smoothed by half against the
  measurement before it. From them:
  `batchSize = clamp(floor(requestSeconds × tokensPerSecond ÷ tokensPerPair), 1, batchSize())`
  and `cap = ceil(tokensPerPair × batchSize × 1.5) + TOKENS_OVERHEAD`, both
  bounded by the context window as the batch planning bounds them.
  `requestSeconds` is DUPLICATES_AI_REQUEST_SECONDS, at least 5, 30 by
  default. A batch is now taken off the front of a queue rather than chunked
  up front, because its size changes while the review runs.
- The plan settles after the warm-up. `requestsPlanned` and `estimatedTokens`
  are re-derived from the pairs nobody has asked about yet and reported with
  `batchSize` and `calibrated: true`, so the page's denominator stops moving.
- Truncation: raise before halving. A cut-off answer that salvaged nothing is
  asked again with twice the cap (the warm-up gets the whole window at once),
  and only when that bought nothing — or the cap is already at the window's
  bound — is the batch halved as before. A warm-up that does not fit even then
  ends the review as failed with a message the operator can act on, naming
  DUPLICATES_AI_THINKING and TOKEN_LIMIT. A single pair at the bound keeps the
  old "unsure" and its log line.
- The cut-off text counts. All four providers now attach `error.partialText`,
  so the salvage path runs for every one of them; a salvaged request counts
  its verdicts in `pairsJudged` and in the tracker. Two comments that still
  said only Ollama returns half-written answers were rewritten.
- Progress inside a request. With a progress sink the provider is asked to
  stream (`onProgress`). Each report, at most every 250 ms, carries
  `requestPairs`, `requestAnswers` (the complete verdict objects counted off
  the streamed text), `requestTokens`, `thinking` and the running token total:
  "The model is thinking… (640 tokens so far)" while it thinks, otherwise the
  request line with " · 7 of 10 answers" appended. The report that counts the
  request resets all four. A review nobody watches sends the plain request it
  always sent.
- Calibration memory. The last measurement per model name lives on the
  singleton; a review that finds one starts sized from it, skips the warm-up
  and says so in the log. A measurement taken with thinking on is never reused
  with thinking off. `resetCalibration()` for tests.
- Logs: the finish line says "N pair(s) planned" (the number is the plan), the
  batch-size line is marked provisional until the model is measured, and the
  split line says whether the cap was raised or the batch halved.

services/duplicateMergeService.js

- `scan()` keeps its result per set of options (kind, threshold,
  includeDismissed) for SCAN_CACHE_MS (60 s) and answers the next identical
  request from it with one log line instead of the start and finish lines.
  `fresh: true` skips and refills it; the page's Scan button sends it.
- A merge, an undo, a dismissal and `restoreDismissal()` empty the cache. A
  dismissal deleted through the route, which talks to the model directly, is
  caught by a fingerprint (row count and highest id per kind) checked on every
  hit — one local SELECT against a 13-second scan.
- `reviewScan()` calls `scan()` without `fresh`, so a proposal made right
  after the page scanned costs no second scan.

Testing

- node scripts/run-tests.js --all: 93 passed, 7 skipped offline, 0 failed
  (100 registered), unchanged from the baseline.
- tests/test-entity-match-ai-service.js: 65 -> 80 cases. New: thinking off and
  on; the warm-up's size, cap, phase and message; the sizing math on a fixed
  usage and duration; the request seconds and their floor; the context window
  bounding size and cap; smoothing; the plan and estimate recomputed after the
  warm-up; calibration reused, not reused across the thinking switch, reset; a
  warm-up that cannot fit ending the review with its message; a truncated
  answer with partialText salvaged and counted; a streamed request reporting
  thinking, then answers, then clearing itself; an unwatched review not
  streaming; a review served from the page's scan.
- tests/test-duplicate-merge-service.js: 17 -> 22 cases. New: cache hit, other
  options and `fresh` missing it, expiry, invalidation by merge, undo, dismiss
  and restore, and a dismissal removed behind the service.
- Changed expectations, all from the raise-before-halve rule: the truncation
  cases now see every size asked twice (once, once with twice the cap) before
  it is halved, the single pair is asked twice before it ends as unsure, and
  the planning cases see the `warming-up` phase where they saw `judging`.
- Two demo runs against a fake model at 30 tokens/s: thinking off, 12 pairs —
  warm-up 4 pairs in 20 s (600 tokens, 150 per pair), then requests of 5 pairs
  at 25 s, 4500 tokens, 60 s in total. Thinking on — warm-up 4 pairs in 40 s
  (1200 tokens, 300 per pair) and requests of 2 pairs at 30.04 s, the
  configured length.

Impact

The first request of a review is seconds rather than minutes, every later one
lasts about as long as the operator asked, and the page shows the model
thinking and answering while it happens instead of a still bar. A review of a
model that was measured before starts at full size. Three scans of one archive
become one. Nothing runs on its own and no verdict changed: the prompt, the
rules and the shape of an answer are what they were.

Upstream Status

Not applicable — the Duplicates feature does not exist upstream.

* fix(duplicates): a review never asks for a fresh scan of its own

reviewScan() drops a `fresh` flag its caller may carry instead of passing it on, so a route that forwards the page's scan options cannot make the review scan the archive a second time.

* fix(duplicates): the yes/no switches of the judge read 'yes', and a small batch is not starved after a thinking one

Background
The browser smoke test of the round ran the thinking scenario and the
judge kept saying "thinking off" although DUPLICATES_AI_THINKING=yes
was set. config/config.js normalises every yes/no setting to the
strings 'yes' and 'no' (parseEnvBoolean), while three readers in the
judge asked Boolean() or === true: the thinking switch could never be
turned on, and the review and excerpt switches could not be turned off
('no' is a truthy string). The second finding: a thinking model pays a
fixed price per request, so a one-pair request sized by pairs alone
after a four-pair warm-up got a cap the same thoughts did not fit; the
judge recovered by raising the cap, at the cost of one request.

Changes
- services/entityMatchAiService.js: switchedOn() accepts 'yes' and a
  boolean true; isEnabled(), excerptsEnabled() and thinkingEnabled() use
  it. The cap never drops below the largest completion the model has
  produced in this review plus a quarter (CAP_FLOOR_FACTOR), and that
  floor is remembered with the calibration.
- tests/test-entity-match-ai-service.js: one case per finding (82
  cases), the sizing case expects the remembered floor.
- config/changelog.js: three entries for the round under the current
  release.

Testing
- node scripts/run-tests.js --test entity-match-ai-service: 82 passed.
- Browser smoke against a fake Paperless-ngx and a fake provider that
  streams, thinks on request and honours max_tokens: thinking off, the
  fake never thought, warm-up 4 pairs, 59 tokens/s measured; thinking
  on, the panel showed the thinking state, no request hit the token
  limit any more; Stop, re-attach, token budget and the round-6
  walkthrough unchanged.

Impact
DUPLICATES_AI_REVIEW=no and DUPLICATES_AI_EXCERPTS=no now do what they
say; DUPLICATES_AI_THINKING=yes now reaches the model.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): contract for the creation guard, the semantic sweep, unused objects, renames and a remembered calibration

Background
Round 9 of the Duplicates feature, six points the user picked: stop
the drift where it starts (document analysis creating "Rechnungen"
next to "Rechnung"), let the model find synonyms and translations the
string matcher cannot, list and delete unused objects with undo, name
the survivor of a merge, keep the judge's measurement of a model across
restarts, and scan faster. Decisions: only hard matcher tiers map a
new name onto an existing one (case, umlauts, legal form, plural, word
order), typo-like matches are log…
… analysis works (#338)

* feat(duplicates): contract for a targeted AI review

Background
With many groups at 94 to 96 percent the user wants to say "everything
from 95 percent up: ask the AI, show me its view, then merge". The
review must therefore be able to judge only chosen groups and skip the
band of near-misses.

Changes
- schemas.js, OPENAPI/openapi.json: groupIds, minConfidence and
  includeCandidates on DuplicateAiReviewRequest.

Testing
- node scripts/regen-openapi.js: no drift after the commit.

Impact
Request fields only; the implementation follows.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): targeting counters in the AI review result schema

Background
A targeted review reports which groups it judged and which it left
without a verdict; the page shows that.

Changes
- schemas.js, OPENAPI/openapi.json: targeted, groupsJudged and
  groupsSkipped on DuplicateAiReviewResult.aiReview.

Testing
- node scripts/regen-openapi.js: no drift after the commit.

Impact
Documentation of three informational fields.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): let the AI review be pointed at a few groups

Background

An archive with hundreds of correspondents produces dozens of groups at
94, 95 and 96 per cent, and asking the model about all of them costs a
lot to answer a question about a handful. The page needs to select the
groups it is about to merge, ask about those, and keep rendering the
rest of the scan while it does.

Changes

- entityMatchAiService.reviewScan() takes three options that narrow what
  is asked, never what comes back:
  - groupIds: only these scan groups are judged. Every other group is
    still in `groups`, as the scan produced it, with `aiVerdict: null` on
    the group and on every member and `source: 'scan'`. An id this scan
    does not know is ignored and logged once with the count.
  - minConfidence: only groups scoring at least this much are judged;
    together with groupIds both conditions have to hold.
  - includeCandidates (default true): false leaves the band of
    near-misses out entirely, so `candidates` is 0 — and with no band
    the entity list per kind is not read either, which is the cheap part.
- _pairsForKind() takes the set of group ids to judge. A group left out
  contributes no pairs but its member pairs still count as "inside one
  group", so it cannot reappear as a candidate.
- The result reports the targeting: aiReview.targeted, .groupsJudged and
  .groupsSkipped. The start line of the log names it as
  "judging 1 of 4 group(s) (min confidence 0.95, 3 ids), band skipped",
  the closing line adds the two counters. An untargeted review logs and
  behaves exactly as before.
- POST /api/duplicates/ai-review validates and passes the three fields
  through: groupIds an array of at most 500 non-empty strings,
  minConfidence a number in [0.5, 1], includeCandidates a real boolean
  (the string "false" is a 400). An option the request does not mention
  is left out of the service call, so an untargeted request reaches
  reviewScan() with the same object it did before.
- Swagger description of the route and the 400 reason updated,
  OPENAPI/openapi.json regenerated.

Testing

- node scripts/run-tests.js --all -> 90 passed, 7 skipped offline,
  0 failed (97 registered), unchanged against the baseline.
- entity-match-ai-service: 28 -> 34 cases. Six new ones on a fixture
  whose four groups sit exactly on the matcher tiers (1, 0.98, 0.95,
  0.9) plus one pair in the band: groupIds judges only what it names,
  minConfidence filters, includeCandidates: false skips the band and
  reads no second entity list, groupIds and minConfidence combine while
  unknown ids are ignored, an empty selection costs no request, and the
  log lines. The existing aiReview assertion gained the three new fields.
- duplicates-endpoints: 16 -> 19 cases. The three fields reach the
  stubbed reviewScan unchanged, an untargeted request still carries
  nothing extra, ten malformed targeting bodies are 400, and 500 ids are
  accepted while 501 are not.
- Manual run against the real route with a fake store and a fake
  provider: full review 5 pairs / 1 request, minConfidence 0.95 without
  the band 3 pairs, two selected ids (one unknown) 1 pair, and every
  unjudged group back with null verdicts.
- eslint, prettier and the OpenAPI drift check clean on the touched
  files.

Impact

Additive. A review that says nothing about the three options behaves and
logs as before. The page can ask about the groups it selected before a
batch merge; a dozen groups without the band are one or two model
requests instead of the whole archive. schemas.js still has to gain
targeted, groupsJudged and groupsSkipped on DuplicateAiReviewResult.

Upstream Status

Not applicable: the Duplicates feature is next-only.

* feat(duplicates): sort, select by confidence, and a guided review before merging

Background
----------
On a grown archive a scan answers with dozens of groups that all read 94, 95,
96 percent, and the page offered no way to act on that number: every group had
to be judged by eye, one tick at a time. The three presets were the only
thresholds available, so "everything above 95" was not a question the page
could be asked. And where the AI review existed it judged the whole result
list, which is the most expensive way to ask about the five groups the user
actually cares about.

The rule this follows: the AI is an addition, never a condition. Every flow
below works end to end with the review switched off; with it on, the guided
path is one more button beside the one that was already there.

Changes
-------
Results toolbar (#dupResultsBar), above the selection bar, shown once a scan
has groups:
  - "Sort by" (#dupSortSelect): confidence, documents, target name (locale
    compare), kind then confidence. It moves the DOM nodes instead of
    re-rendering, so a card keeps its target, its source ticks, its selection,
    its verdict and its busy state; the two blocks (scan groups, AI
    candidates) are sorted separately and the divider stays between them.
  - "Select >=" (#dupMinConfidence, #dupSelectMinBtn, #dupMinConfidenceCount):
    ticks every selectable group at or above a whole percent and unticks the
    rest, with a live count of what the click would do.
Custom scan threshold: a fourth sensitivity option "Custom" reveals a number
field (#dupThresholdCustom); the scan and both review paths send that percent
divided by 100. The three presets are unchanged.
Confidence breakdown under "Groups found" (#dupStatBuckets): ">=95 %: A .
90-95 %: B . <90 %: C", counted from the cards after a scan and after a review.
Guided flow (#dupReviewThenMergeBtn, rendered only where the review exists):
asks the model about exactly the ticked groups (groupIds, includeCandidates:
false), puts the verdicts on the cards as a full review does, then shows them
once in a wide dialog - one row per group with target, sources, documents, the
verdict chip and the reason, a live "N of M ticked . K documents" foot line and
the copy-rule check. Ticked rows are merged with the batch machinery; an unsure
or different verdict only comes up unticked and never blocks anything, and what
stays unticked stays selected on the page.
"Merge selected" keeps its place and its weight, first in the bar and without a
model anywhere in its path; its dialog names the guided path in one faint line,
and only where that path exists.
Sort, confidence, sensitivity and the custom threshold are remembered in
localStorage (dup.sort, dup.minConfidence, dup.sensitivity,
dup.thresholdCustom) through two try/catch helpers.

Testing
-------
node scripts/run-tests.js --all -> 90 passed, 7 skipped offline, 0 failed
  (unchanged from the branch baseline).
tests/test-duplicates-ui.js: 25 -> 38 cases. New: the toolbar ids and their
  order, the custom threshold field, the stats breakdown, the guided button
  only with the review, the whole page without the review, the toolbar ids in
  the script, sorting as a DOM move, "Select >=", the wrapped localStorage
  access, the guided request (groupIds / includeCandidates: false) and that
  "Merge selected" never touches the review endpoint, the review dialog markup,
  the tip line, the new CSS classes. Changed: the sensitivity options are read
  from #dupSensitivity alone and now end in "custom"; the undo promise and the
  confirm dialogs are counted one higher each, because the review dialog merges
  and therefore makes the same promise.
Reviewed in a browser against a throwaway mock (twelve groups over 88-100 %, a
  review that honours groupIds): 27 screenshots at 1280x900 and 390x844, light
  and dark, 0 px horizontal overflow everywhere, plus a 31-check behaviour
  probe (guided request, verdict ticks, sorting keeping picks and the divider,
  persistence, a refused review, and the whole page with the review off).

Impact
------
Page only. No route, service, schema or config was touched, so the OpenAPI
spec is unchanged. An instance without the AI review renders and behaves
exactly as before plus the toolbar and the custom threshold. The request the
guided path sends uses fields the contract already carries; a server that
ignores them reviews everything, which the page renders correctly.

Upstream Status
---------------
Not applicable - the Duplicates page does not exist upstream.

Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* docs(duplicates): changelog entries for sorting, select by confidence and the guided review

Background
Round 5 answered the second feedback from a real archive: select by a
number, let the model judge exactly those groups, read its verdicts in
one dialog, merge what stays ticked; sort the groups; a custom threshold.

Changes
- config/changelog.js: two entries in the current v2026.09.01 block.

Testing
- node scripts/run-tests.js --test changelog-releases: passed.

Impact
Documentation only.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): contract for evidence-based verdicts and the AI proposal

Background
A real archive produced "Kontoauszug" / "Kontoumzug": the matcher called
it a spelling distance, the prompt allowed "an obvious typo" as a reason
for same, and the model, seeing names and titles only, agreed. Both are
different things. The judge needs stricter rules and, for pairs linked by
spelling alone, a look at what the documents are about, at a bounded
cost.

Changes
- config/config.js: DUPLICATES_AI_EXCERPTS (default yes),
  DUPLICATES_AI_EXCERPT_CHARS (300), DUPLICATES_AI_EXCERPT_DOCUMENTS (2).
- schemas.js, OPENAPI/openapi.json: AiVerdict gains basis and confidence;
  DuplicateAiReviewRequest gains withExcerpts; aiReview reports excerpts.

Testing
- node scripts/run-tests.js --area duplicates: 6/6; regen without drift.

Impact
Settings and schema only; the implementation follows.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): judge model override and the verdict source in the contract

Background
Decisions for round 6: the matcher's hard tiers settle a pair without the
model, unsure pairs are asked once more with excerpts, and the judge may
run on a stronger model of the same provider.

Changes
- config/config.js: DUPLICATES_AI_MODEL (optional, judge only).
- schemas.js, OPENAPI/openapi.json: AiVerdict.source (model or
  spelling-rule); aiReview.escalated and aiReview.spellingRules.

Testing
- eslint and prettier on the two files; regen without drift.

Impact
Settings and schema only; the implementation follows.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(settings): make every DUPLICATES_ setting editable in its own section

Background
The AI review of the Duplicates page arrived with seven environment
variables and no way to change any of them from the interface. Editing a
container environment and recreating the container is the wrong price for
"try a stronger model for the judge" or "ask about fewer pairs per
request", and the settings page is exactly where those knobs belong.
config/config.js already reads all seven; only the front door was missing.

Changes
- views/settings.ejs: a "Duplicates" section (id="sec-duplicates") inside a
  new duplicates-tab block between the AI sections and OCR, with a nav entry
  in the desktop section nav (icon i-merge) and in the mobile one, in the
  same order as the page. Seven fields, each with a hint that says what the
  value does and what its default is: the AI review switch, the judge model,
  pairs per request, the candidate floor, the excerpt switch, excerpt length
  and documents per entry. Switches go through partials/settings-switch, so
  the hidden yes/no input the POST route reads exists as it does everywhere
  else.
- routes/setup.js: GET /settings passes the seven values (env first, the
  defaults of config/config.js as fallback) in the config object the view
  reads; POST /settings destructures the seven camelCase body keys,
  normalises them and writes them into updatedConfig, so setupService
  .saveConfig persists them with the rest. Numbers are clamped to their
  range; a value that is not a number, or a cleared field, keeps what is
  configured now instead of resetting to the default. The swagger body
  schema documents all seven, and the .env export gained a "Duplicates"
  group between "AI behaviour" and "External API".
- public/js/settings.js: the seven selector to env-key entries, so the
  "Overwritten" and "Managed by ENV" marking covers these fields too.
- OPENAPI/openapi.json regenerated.
- tests/test-settings-duplicates-section.js, registered in the
  observability area.

Testing
- node scripts/run-tests.js --all: 98 registered, 91 passed, 7 skipped
  offline (was 97/90/7). The new test covers the rendered section and its
  nav position, the seven inputs and their values, the POST round trip,
  clamping, the keep-the-previous-value case and the .env export group.
- npx eslint / npx prettier --check --ignore-unknown on every touched file.
- node scripts/regen-openapi.js leaves OPENAPI/openapi.json unchanged.
- Looked at the page in Chromium at 1440x1000 and 390x844 against a
  throwaway server outside the repository; no console errors, the section
  reads like the rest of the page and stacks on the phone.

Impact
Operators can change every DUPLICATES_ value from the settings page. The
existing restart-after-save is what makes them take effect; no new
mechanism. Values injected by the container still win and are shown as
managed, as for every other field. Nothing outside the settings page
changes: no route, service or default behaviour of the Duplicates page
itself is touched.

Upstream Status
Fork-only. The Duplicates page does not exist upstream.

Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): judge spelling-only pairs on evidence, not on distance

Background
A real archive produced "Kontoauszug" next to "Kontoumzug": the matcher
called it a spelling distance, the prompt allowed "an obvious typo" as a
reason for same, and the model, seeing two names and three titles, agreed.
Two different things. The judge needed stricter rules, evidence for the
pairs where spelling is the only link, and a way to say how sure it is and
on what grounds — all without opening a large context window on every pair.

Changes
- entityMatchAiService: the system prompt refuses a small spelling distance
  as a reason of its own ("Kontoauszug" / "Kontoumzug", "Miete" / "Mieter",
  "Bahn" / "Bank"), allows a misspelling only when one spelling is not a
  word, and answers unsure when it cannot tell. The output contract gains
  "basis" (a closed list) and "confidence" (high | low); both are parsed,
  an unknown value becomes null, and every verdict, member verdict and
  aggregate carries them. An aggregate keeps the deciding member's basis
  and takes "low" as soon as one deciding member is low.
- Evidence, graded by what the link is worth: every pair carries matched_by
  and score; every judged entity carries its titles, its matching rule and
  its neighbourhood ("filed_with": the correspondents of a tag's documents,
  the tags of a correspondent's); only the pairs linked by fuzzy, prefix or
  token-order also carry document excerpts. Excerpts are read once per
  entity per review and never for a strong tier. withExcerpts: false or
  DUPLICATES_AI_EXCERPTS=no reads nothing at all.
- A member pair a matcher rule settles (exact-normalized, umlaut-variant,
  legal-form) never reaches the provider: it gets verdict same with
  source: spelling-rule, counts in aiReview.spellingRules and costs no
  request, no read and no token.
- A pair the model calls unsure and that had no excerpts is asked once more
  with them; the second answer replaces the first (aiReview.escalated).
- paperlessService: getRecentDocumentExcerptsByEntity (one read,
  truncate_content, cut to the configured characters at a word boundary)
  and getEntityNeighbourhood (one read, the most frequent neighbour names
  through the existing caches). Both answer [] on any error and never log
  document content.
- The judge may run on its own model (DUPLICATES_AI_MODEL): generateText
  takes an optional model in all four provider services, shared through
  aiGenerateOptions.modelOverride.
- Logs: the per-kind start line names the evidence and the model, the
  request line the pairs with excerpts, the escalation its own line.
- Route POST /api/duplicates/ai-review parses withExcerpts like withTitles;
  swagger description updated and OPENAPI/openapi.json regenerated.

Testing
- node scripts/run-tests.js --all: 97 registered, 90 pass, 7 skip offline.
- tests/test-entity-match-ai-service.js: 35 -> 50 cases (the stricter
  prompt, basis and confidence parsing, excerpts only for spelling-only
  pairs and once per entity, the two switches, the configured cut, the
  Kontoauszug regression, settled pairs, the neighbourhood, escalation, the
  model override, batch sizing with excerpts, and both new client methods).
- tests/test-duplicates-endpoints.js: one case for withExcerpts; the three
  existing option assertions now expect withExcerpts: true.
- Demo run against the fake Paperless-ngx: the Kontoauszug/Kontoumzug pair
  costs 282 prompt tokens with excerpts, a strong pair without excerpts 75.
- eslint, prettier and a regen without drift on every file touched.

Impact
An AI review asks about fewer pairs and knows more about the ones it asks
about. Nothing runs on its own, nothing is merged, and document content
never reaches a log line.

Upstream Status
Not applicable — the Duplicates feature does not exist upstream.

* fix(duplicates): do not escalate an unsure pair whose documents carry no text

* feat(duplicates): one click for the AI's proposal, with the evidence behind it

Background
----------
Everything the page offered so far started from the user: scan, read every
card, tick, merge — and where the AI review existed it was a second question
asked after the first. What was missing is the path the archive's owner
actually wants for a first clean-up: one click that scans, has every group and
every near-miss judged, and then hands over a proposal to thin out rather than
a list to work through.

The rule this follows is the same as in the rounds before: the AI is an
addition, never a condition. Without the review nothing of this renders, and
"Scan Paperless-ngx", "Merge selected", the toolbar, the manual merge and the
guided path are the same as they were.

A verdict also had to say more than "same": with `basis`, `confidence` and a
`source` on the wire, the page can pre-tick exactly what is settled — a pair a
spelling rule decided, or one the model says it is sure about — and leave
everything else to the user. The member tables, finally, measured their own
content per card, so the columns of two cards below each other sat in
different places.

Changes
-------
"AI proposal" (#dupAiProposalBtn, primary, rendered only with aiReviewEnabled)
next to "Ask the AI", usable from the first paint because it scans itself:
  - status in the AI row (#dupAiProposalStatus): "Scanning…", then "Asking the
    AI about N pairs and near-misses…", with the hint line under the row
    (#dupAiProposalHint) saying what the click does;
  - it reuses runScan() (now awaited) with the kind, sensitivity and hidden-pair
    settings on the page, then the one review request with includeCandidates
    and no groupIds. Two requests, and no merge until the dialog is confirmed.
Proposal dialog (.dup-proposal-dialog): one row per group that could be merged,
  sorted same/high, same, unsure, different, unjudged (proposalRank,
  compareProposalEntries — both pure); pre-ticked are only the settled ones
  (isSureSame: verdict "same" with confidence "high", which covers the
  spelling-rule verdicts); legend, "Tick all same" (#dupProposalTickSame),
  "Untick all" (#dupProposalUntickAll), the copy-rule check (#dupCopyRuleAll)
  and a live foot line "N of M ticked · K documents · X objects will be
  deleted". Confirming sets the page selection to the ticked groups and hands
  them to the batch runner of round 4, so the selection bar reports the merge
  as it does for "Merge selected"; cancelling leaves the verdicts on the cards
  and nothing ticked.
Evidence, shared by both dialogs (one row renderer, one table):
  - a "Basis" column as a .zr-badge with a label per contract value;
  - the confidence as a suffix of the verdict chip ("AI: same · high");
  - a pair a spelling rule settled reads "Spelling rule" in the "same" tone
    (.dup-verdict--rule) instead of quoting a model that never saw it;
  - the guided dialog pre-ticks by the same rule, so a "same" the model is
    unsure about now comes up unticked there too.
Cards keep their shape: the verdict chip carries the basis in its title and the
  confidence as its suffix, no new column.
Second checkbox "Use document excerpts for spelling-only pairs"
  (#dupAiExcerpts, checked); withTitles and withExcerpts flow into every review
  request from the one place that builds it. The titles checkbox is relabelled
  "Use document titles and neighbours as context".
"AI-judged pairs" tile: its sub line now also counts "· E excerpts", "· S by
  spelling rule" and "· E escalated" when the review reports them.
Member tables line up across cards: .dup-members is table-layout: fixed with
  the name column taking what is left and truncating, and the matching rule a
  fixed share (.dup-members__name, .dup-members__rule).

Testing
-------
node scripts/run-tests.js --all -> 90 passed, 7 skipped offline, 0 failed
  (unchanged from the branch baseline of 97 registered).
tests/test-duplicates-ui.js: 38 -> 48 cases. New: the proposal ids and labels
  only with the review and the page whole without them; what the flow sends
  (runScan first, includeCandidates: true, no groupIds, both evidence flags,
  no request of its own); the pre-tick rule, evaluated as a function against
  seven verdicts; the row order, evaluated by sorting a shuffled list; a label
  for every basis the AiVerdict schema lists, parsed out of schemas.js; the
  spelling-rule chip; the dialog's parts and that it merges through the batch
  runner; the evidence counters of the stats tile; the fixed member-table
  layout; the new CSS classes. Changed: the titles checkbox label, the undo
  promise and the confirm dialogs counted one higher each (the proposal merges
  and therefore makes the same promise), and the pre-tick assertion of the
  guided row.
Reviewed in a browser against a throwaway mock (eleven scan groups plus three
  the model proposes, verdicts across same/high, same/low, unsure and
  different, some settled by a spelling rule, and a Kontoauszug / Kontoumzug
  pair that only the excerpts decide): 31 screenshots at 1280x900 and 390x844,
  light and dark — the controls, the status line mid-flow, the proposal dialog,
  after "Untick all", mid-merge, after the merge, the guided dialog, the stats
  tile, the aligned member tables and the render without the review. 0 px
  horizontal overflow everywhere; the column offsets of all eleven cards are
  identical.

Impact
------
Page only. No route, service, schema or config was touched, so the OpenAPI
spec is unchanged. An instance without the AI review renders and behaves
exactly as before. The new request field and the new verdict fields are ones
the contract already carries: a server that ignores withExcerpts reviews as it
did, and a verdict without basis, confidence or source renders as it did — it
then simply never comes up pre-ticked, which is the safe side.

Upstream Status
---------------
Not applicable - the Duplicates page does not exist upstream.

Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* chore(duplicates): changelog for the AI proposal round, room for the verdict in the Match column

Background
The sixth round of the Duplicates feature adds the AI-led proposal, the
evidence-based judge and the Duplicates settings section. The member
tables now use a fixed column layout so the columns line up across
cards, which left the Match column too narrow for a verdict such as
"AI: same - high": it wrapped into four lines.

Changes
- config/changelog.js: five entries for the round under the current
  release (AI proposal, evidence-based judge with excerpts and
  DUPLICATES_AI_EXCERPT*, DUPLICATES_AI_MODEL, aligned member tables,
  the Duplicates settings section).
- public/css/pages/duplicates.css: the Match column is 132px wide and
  the member verdict does not wrap, so the percentage and the verdict
  take one line each.

Testing
- npx eslint, prettier --check and stylelint on every file changed
  against nightly: clean.
- node scripts/run-tests.js --all: 91 passed, 7 skipped (server or
  credentials needed), 0 failed.
- node scripts/regen-openapi.js: no drift.
- Browser walkthrough against a fake Paperless-ngx and a fake judge:
  scan, merge, undo, dismiss, merge by hand, batch merge, guided review,
  AI proposal and AI review all pass. The Kontoauszug/Kontoumzug pair is
  judged "different" on its excerpts and does not appear in the
  proposal.

Impact
Visual only for the CSS; the changelog is shown in the What's New
dialog.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): contract for a watchable, stoppable AI review

Background
An AI review of a large archive is many model requests in a row. Today
it is one POST that answers when everything is done: nothing shows
while it runs, nothing can stop it, and the tokens it spends are
invisible until the end. The user wants to see what is happening, how
far it is and what it costs, and to stop it at any time. Decisions for
this round: the review runs as a server-side job the page can watch
and stop; a review nobody watches stops itself; a token budget per
review stops it on its own; a stopped review keeps the verdicts it
reached and opens no dialog; the progress lives in the AI row of the
Duplicates page.

Changes
- services/duplicateReviewJobService.js (new): the one review job at
  a time. start(), current(), get(), stop(id, reason), subscribe() for
  a server-sent stream (a late subscriber first gets the job as it is
  now), touch(), wait(), result(), toJSON(). The judge receives a
  control object (signal, onProgress, stop, tokenBudget); a partial
  result of a stopped review is kept like a complete one. The idle
  watch stops a job nobody has watched for the configured seconds. A
  finished job stays reachable for ten minutes.
- config/config.js: DUPLICATES_AI_TOKEN_BUDGET (200000, 0 = no limit)
  and DUPLICATES_AI_IDLE_STOP_SECONDS (60, 0 = never).
- schemas.js, OPENAPI/openapi.json: AiReviewProgress, AiReviewJob,
  AiReviewJobEvent; aiReview gains stopped, stopReason and
  pairsNotJudged.
- scripts/run-tests.js, tests/test-duplicate-review-job.js: the
  contract test of the job (9 cases) in the duplicates area.

Testing
- node scripts/run-tests.js --all: 99 registered, 92 pass, 7 skip
  offline, 0 fail.
- eslint and prettier on every touched file; regen without drift.

Impact
Nothing uses the job yet; the judge ignores the control object until
the implementation follows. No route or page changes.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): make the token budget and the idle stop editable in settings

Background
The two brakes of a running AI review landed as environment variables only:
DUPLICATES_AI_TOKEN_BUDGET caps what one review may spend across all its
requests, DUPLICATES_AI_IDLE_STOP_SECONDS ends a review no page has been
watching, so a closed tab cannot leave the model running. Both are exactly
the kind of setting somebody wants to try out once and then adjust, which
means editing a compose file and restarting the container for every attempt.
The other seven DUPLICATES_* variables already have a field in the Duplicates
section of the settings page; these two did not.

Changes
- views/settings.ejs: two number fields at the end of #sec-duplicates, in the
  style of the five above them — duplicatesAiTokenBudget (0-10000000, step
  1000) and duplicatesAiIdleStopSeconds (0-3600). Each hint says what the
  value does, what zero means and what the default is.
- routes/setup.js: GET /settings passes DUPLICATES_AI_TOKEN_BUDGET and
  DUPLICATES_AI_IDLE_STOP_SECONDS to the view with the defaults of
  config/config.js as the fallback; POST /settings destructures both body
  keys, clamps them to their ranges and keeps the currently configured value
  for an empty or non-numeric field, the rule the round-6 fields follow. Zero
  is a value for both and survives the clamp, because the ranges start there
  rather than at one. The @swagger body schema documents both, and the
  Duplicates group of ENV_EXPORT_GROUPS lists them after the existing keys.
- public/js/settings.js: two entries in the field mapping, so an
  operator-injected value greys the field out and carries the "Managed by ENV"
  pill like every other setting.
- OPENAPI/openapi.json regenerated.

Testing
- tests/test-settings-duplicates-section.js grew from 7 to 11 cases: the two
  fields render with their configured values, ranges and hints and close the
  section in that order; every field of the section is paired with its
  environment key in settings.js; the POST round trip persists all nine
  values; a budget of 99999999 is capped at 10000000 and an idle stop of -5
  lands on 0; zero survives for both, because it means "no limit" and "never"
  rather than an unset field; a fractional value is rounded; a cleared or
  unparsable field keeps what was stored before; the .env export carries all
  nine keys with the two brakes last.
- node scripts/run-tests.js --all: 99 registered, 92 passed, 7 skipped
  offline, 0 failed — the same numbers as before this change.
- eslint and prettier clean on every file touched; regen-openapi.js leaves no
  drift.
- Looked at the section in Chromium at 1440x1000 and 390x844 against a
  throwaway server outside the repository: both fields render like the seven
  above them, no console errors, and with the two keys in the locked-env set
  both are disabled and carry the "Managed by ENV" pill while a neighbouring
  field stays editable.

Impact
No behaviour change for anybody who never opens the section: the defaults are
unchanged (200000 tokens, 60 seconds) and nothing new runs. Operators who set
either variable in their container environment keep winning — the field is
shown greyed out rather than silently overwritten. A saved value needs a
restart to take effect, as the hints say, because config/config.js reads the
environment once at load.

Upstream Status
Not applicable — the Duplicates page is specific to this fork.

* feat(ai): let every provider take an abort signal for one call

aiGenerateOptions gains abortSignal(options); the four provider
services pass it on where their client expects it — the OpenAI SDK as
the second argument of create(body, { signal }) for OpenAI, Azure and
the custom endpoint, axios as { signal } in the request config for
Ollama. Without a signal every provider sends exactly what it sent
before: no second argument at all, and the unchanged axios config.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): the AI review reports, stops and counts its tokens

Background
"Während die AI befragt wird, könnten Millionen von Tokens im
Hintergrund verbraten werden, ohne dass man es sieht. Man muss es auch
abbrechen können." The judge answered when it was done and said
nothing while it worked, so the page had nothing to show and nothing
to stop. The job of the previous round hands it a control object; this
round makes the judge use it. A bar needs a denominator before the
first request, which the old per-kind loop could not give: it read the
archive, asked, and only then looked at the next kind.

Changes
- services/entityMatchAiService.js: reviewScan(options, control = {})
  runs in two passes. Pass one, for every kind of the review: read the
  entities and the band, build the pairs, settle the spelling-rule
  pairs, gather titles, neighbourhood and excerpts, and size the
  batches. Pass two judges kind after kind. Nothing is asked before
  the whole plan exists.
- Progress: phase scanning before the scan, phase evidence per kind
  and per read, one phase judging with requestsPlanned, pairsTotal and
  estimatedTokens for the whole review, one report per answered
  request (requestsDone, pairsJudged, the running token total,
  failedRequests, retries, kind, and the line naming the next
  request), phase escalating when an unsure pair is asked again, phase
  finishing before the groups are built. A split answer adds its
  halves to requestsPlanned in the report of the request that split,
  so the bar never goes backwards; the escalation adds its own
  requests and pairs the same way. Elapsed time and the estimate stay
  with the job, which derives them.
- Stopping: control.signal is read before every read, every request
  and the second round, and travels to the provider, so a stop lands
  on a request in flight. A request that dies on the signal is a stop,
  not a failure: no failed request, no retry, and no "unsure" — the
  pairs stay without a verdict, so they cannot become a group. A
  stopped review returns what it reached; it never throws.
  aiReview now always carries stopped, stopReason (null; the job fills
  it in) and pairsNotJudged.
- Token budget: one running total for the whole review, folded from
  the provider's usage or, for a provider that reports none, from the
  measured prompt plus the estimated answer, so the counter and the
  budget work for every provider (aiReview.tokens keeps reporting only
  what a provider stood behind). When control.tokenBudget is reached
  the review calls control.stop('token-budget') and behaves as
  stopped.
- Logs: "review stopped (user|token-budget|idle): N of M request(s)
  made, P pair(s) not judged, T token(s)." and "token budget 200000
  reached after N request(s) (T tokens)."; the start, request and
  finish lines are unchanged.
- services/duplicateReviewJobService.js: the control object gains
  stopReason(), the one seam the judge needs to name the reason in its
  own log line.
- reviewPairs(pairs, options) additionally takes plan, systemPrompt
  and tracker from reviewScan; a caller that brings none gets what it
  always got.

Testing
- node scripts/run-tests.js --all: 99 registered, 92 pass, 7 skip
  offline, 0 fail (the baseline of the branch).
- tests/test-entity-match-ai-service.js: 13 new cases (64 total) —
  the plan before the first request for one and for two kinds, the
  split and the escalation raising the plan, a failed request still
  moving the bar, a stop between requests and a stop in flight, the
  token budget, a provider without usage, an already aborted signal, a
  review without a control, the report carrying nothing the job
  derives, and the signal reaching all four providers. The one moved
  expectation is the deep-equal on aiReview, which now names the three
  new fields.
- tests/test-duplicate-review-job.js: one case for stopReason().
- A real run through the job service over a fake archive: a review
  that runs through, the same one stopped after request 2, and the
  same one against a token budget.
- eslint and prettier on every touched file.

Impact
The page can show a bar with a denominator, an estimate and a running
token count from the first request, and a stop costs at most one
request that is already in flight. A review without a control object
behaves exactly as before, so the synchronous route is untouched until
it is moved onto the job.

Upstream Status
Not applicable: the Duplicates page and its AI review do not exist
upstream.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): watch and stop the AI review from the page

Background

A review of a drifted archive is many model requests in a row. Until now
"Ask the AI" was one POST that answered when everything was over: a spinner,
no idea how many requests were still coming, no idea what it cost, and no way
out but reloading the tab — which left the model running. The job service of
the contract commit made the review watchable and stoppable on the server;
this wires the routes and the page onto it.

Changes

routes/setup.js (Duplicates block only)
- parseAiReviewRequest(body) holds the validation both entry points share, so
  the synchronous route and the job route can no longer drift apart.
- POST /api/duplicates/ai-review/jobs starts a review and answers
  202 { job }; while one runs it answers 409 with that running job, so a
  second tab attaches instead of failing.
- GET /api/duplicates/ai-review/jobs/current answers { job } or { job: null }
  and counts as watching the review.
- GET /api/duplicates/ai-review/jobs/:id answers { job, result }, 404 for an
  unknown id, and also counts as watching.
- GET /api/duplicates/ai-review/jobs/:id/events streams AiReviewJobEvents
  (text/event-stream, no-cache, X-Accel-Buffering: no, keep-alive, flush after
  every write), a ": keep-alive" comment every 15 s, and ends after done,
  stopped or failed. An unknown id is a JSON 404 before any stream header.
- POST /api/duplicates/ai-review/jobs/:id/stop answers { job }; stopping a
  finished review is a 200 no-op.
- POST /api/duplicates/ai-review now starts that same job and waits for it: a
  stopped review answers 200 with the verdicts it reached, a failed one keeps
  the judge's status, and a second request while one runs is a 409. It
  subscribes for the duration so the idle stop cannot end a review somebody is
  waiting for.
- @swagger for every new route; OPENAPI/openapi.json regenerated.

views/duplicates.ejs, public/js/duplicates.js, public/css/pages/duplicates.css
- A progress panel in the AI row (#dupAiProgress): bar (#dupAiProgressFill,
  indeterminate while the plan is unknown), message, counters
  ("Request 3 of 8 · 40 of 96 pairs · 12.4k of 200k tokens"), time
  ("about 40 s left · 1:24 elapsed") and a Stop button (#dupAiStopBtn). After
  the end it keeps one outcome line and hides on the next scan or review.
- askForVerdicts() starts the job, follows it through EventSource and falls
  back to polling the job every 2 s when the stream breaks. It resolves
  { aiReview, stopped }; all three AI paths honour `stopped` — the notice is
  shown and neither the guided dialog nor the proposal opens.
- On load the page asks for the current job and re-attaches to one that is
  still running; a finished one is left alone.
- Pure helpers formatTokens, formatEta, formatElapsed, progressPercent and
  stopNotice word the numbers; the UI test evaluates them directly.

Testing

- node scripts/run-tests.js --all: 99 registered, 92 pass, 7 skip offline
  (unchanged); duplicates-endpoints 20 -> 30 cases, duplicates-ui 48 -> 57.
- eslint, prettier, stylelint clean on every touched file; regen-openapi
  leaves no diff.
- Reviewed in a browser against a throwaway server with a judge that reports
  eight requests: mid-run, stopping, stopped and done, desktop and phone,
  light and dark, no console errors. A page loaded while a review runs
  re-attached and rendered its result; with the event stream blocked the same
  review came home through eight polls.

Impact

The Duplicates page shows what a review is doing and costing and can end it;
the verdicts already reached are kept. The synchronous route keeps its request
and response, so an API client sees no change beyond the new 409 while a
review runs.

Upstream Status

Not applicable — the Duplicates feature does not exist upstream.

* fix(duplicates): a late Stop answer no longer paints over the outcome; changelog for the review job

Background
In the browser smoke test of the round, a stop pressed after the first
answered request ended the job before the stop request itself answered.
The page then rendered that answer, a snapshot from the stopping moment,
over the outcome line and restarted the elapsed clock, so the panel read
"Stopping after the current request…" next to a finished review.

Changes
- public/js/duplicates.js: stopReview() renders the stop answer only
  while the same job is still followed and still live.
- tests/test-duplicates-ui.js: one case that pins the guard (57 -> 58).
- config/changelog.js: three entries for the round under the current
  release (the review as a job with progress and Stop, the token budget
  and the idle stop as settings, the plan before the first request).

Testing
- node scripts/run-tests.js --test duplicates-ui: 58 passed.
- Browser smoke against a fake Paperless-ngx and a slowed-down fake
  provider: Stop during request 2 leaves "Stopped after 1 of 5 requests
  · 1 of 5 pairs judged · 1.1k tokens" on the panel, the verdicts
  reached stay on the cards, no dialog opens; the proposal path stops
  the same way; a token budget of 2500 stops the review after 3
  requests with the budget named in the notice and the log; a page
  reloaded during a review re-attaches and renders the result; the
  round-6 walkthrough (scan, merge, undo, dismiss, merge by hand, batch,
  guided review, proposal, plain review) passes unchanged.
- eslint and prettier on the touched files.

Impact
Visual only; the review itself was stopped correctly before the fix.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): contract for a judge that measures the model, streams its answers and thinks only on request

Background
On a real archive with a hosted Qwen model the first review request
asked about 25 pairs, ran for 103 seconds and died at its own answer
cap: the model spent the whole budget thinking before the first
verdict, the cut-off text was thrown away, and the page showed nothing
but a ticking clock for two minutes. Three scans of 13 seconds each
came before that. Decisions for this round: the judge measures the
model on a small first request and sizes every later request to a
target duration; the providers stream the answer so the page moves
inside a request and a cut-off answer keeps its verdicts; thinking is
off for the judge unless the operator switches it on; the review
reuses a fresh scan instead of scanning again.

Changes
- config/config.js: DUPLICATES_AI_THINKING (no) and
  DUPLICATES_AI_REQUEST_SECONDS (30).
- schemas.js, OPENAPI/openapi.json: AiReviewProgress gains
  requestPairs, requestAnswers, requestTokens, thinking, batchSize and
  calibrated; the phase list gains warming-up.
- services/duplicateReviewJobService.js: the new progress fields, the
  warming-up phase, and a time estimate from the share of pairs done
  (answers streamed in count), because the batch size may change after
  the warm-up.
- services/aiGenerateOptions.js: reasoningEnabled(options) and
  progressHandler(options), the two switches the judge will send and
  the providers will read, with the GenerateTextProgress shape and the
  partialText rule for cut-off answers.
- scripts/run-tests.js, tests/test-ai-provider-streaming.js: a
  registered placeholder for the provider streaming test.

Testing
- node scripts/run-tests.js --all: 100 registered, 93 pass, 7 skip
  offline, 0 fail.
- eslint and prettier on every touched file; regen without drift.

Impact
Nothing reads the new switches yet; the implementation follows.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* test(helpers): fake OpenAI-compatible and Ollama servers on ephemeral ports

* feat(providers): stream the answer, report progress, keep the cut-off text

Background

A hosted model behind the custom provider spent 103 seconds and the whole
3200-token completion cap on one AI-review request, then threw "the answer hit
a token limit" and dropped every character it had produced. Nothing was visible
while it ran, nothing survived the throw, and the batch was split and paid for
again from the beginning. Two causes: the four provider services always sent a
non-streaming request, so there was nothing to watch; and
assertCompletionNotTruncated() threw before anyone read the content, so the
prefix was thrown away. On top of that the model thinks before it answers, and
on a server that separates thinking from answering the reasoning arrives as
reasoning_content deltas that no provider knew about.

Changes

- services/aiGenerateOptions.js: the shared streaming machinery.
  stripReasoningText() removes <think> blocks, including one a cut-off left
  open. createProgressCollector() assembles a streamed answer, splits reasoning
  from answer incrementally (a marker may be cut across two chunks), counts the
  completion tokens from a usage chunk or estimates them over everything
  produced, reasoning included, and reports at most once per 100 ms plus one
  final report that says done. consumeChatCompletionStream() and
  runChatCompletionStream() are the OpenAI-compatible half: read the stream,
  finish before any throw, and turn a cut-off or a stop into an error that
  carries what arrived. isAbortError()/abortedGenerationError() give a stopped
  request one name across the SDK, axios and fetch.
- services/serviceUtils.js: estimateTokenCount() (the same character-based
  estimate, on a length) and an optional fourth argument on
  assertCompletionNotTruncated() that puts partialText on the error.
- services/openaiService.js, services/customService.js,
  services/azureService.js: generateText() streams when the caller hands in
  onProgress, with stream_options: { include_usage: true } on OpenAI and the
  custom provider and on Azure only from API version 2024-06-01, where the API
  takes it. Without a handler the body is exactly what it was. Both paths strip
  reasoning from the answer and attach the prefix to a truncation error; an
  abort throws an AbortError with partialText.
- services/customService.js: reasoning: false adds
  chat_template_kwargs: { enable_thinking: false } and, for a model name
  matching /qwen/i, that family's soft switch on its own line at the end of the
  user message; reasoning: true sends enable_thinking: true and no soft switch;
  without the option nothing new is sent.
- services/ollamaService.js: generateText() reads NDJSON from an axios
  responseType: 'stream' response, keeps the tail of a socket read until its
  newline arrives, treats the thinking field as thinking, and stops reading the
  moment the signal aborts. reasoning: false/true sends think and overrules
  OLLAMA_THINK; without the option OLLAMA_THINK still decides. The cut-off
  check the analysis path has always run now runs here too, with partialText,
  and a failure no longer erases a token count that was already measured.
- tests/helpers/fake-openai.js, tests/helpers/fake-ollama.js: real HTTP servers
  on ephemeral ports, scripted per request (content chunks, reasoning chunks,
  finish reason, usage chunk or none, per-chunk delay, non-streaming answers
  from the same script), recording every request body and whether the client
  hung up early.
- tests/test-ai-provider-streaming.js replaces its placeholder with 22 cases.

Testing

- node tests/test-ai-provider-streaming.js: 22 passed, 0 failed; run five
  times, no flake.
- node scripts/run-tests.js --all: 93 passed, 7 skipped offline, 0 failed —
  the same numbers as before this change.
- npx eslint and npx prettier --check on every touched file: clean.
- A throwaway process reproduced the reported failure against the fake: the
  progress reports show thinking first with no text, then the answer growing,
  then one done report with the exact token count from the usage chunk, and the
  throw carries the 131 characters of JSON that had arrived.

Impact

No caller behaves differently unless it asks: without onProgress the request
body is byte for byte what it was, and the round-7 provider cases assert that.
What does change for every caller of generateText(): a <think> block no longer
reaches the returned string, a truncation error now carries partialText, an
abort now throws under the name AbortError, and Ollama's generateText() now
raises the same truncation error the analysis path raises instead of returning
a half-written answer. The document analysis path is untouched.

Upstream Status

Not upstream. Streaming, progress reporting, the partial text of a cut-off
answer and the thinking switch do not exist in clusterzx/paperless-ai.

* feat(duplicates): the progress panel moves inside a request and names the measured batch size

Background

A review of a large archive is a handful of long model requests, and the
panel only moved between them. One request took 103 seconds while the page
showed "request 1 of 4 - 0 of 82 pairs" and a ticking clock, so for minutes
at a time the only honest reading of the page was "nothing is happening".
The judge now measures the model on a small first request, sizes every later
one to a configured number of seconds, and streams the answers as they
arrive, which gives the page three things it never had: answers inside a
request, a warm-up phase, and a model that says when it is thinking.

Changes

Page (views/duplicates.ejs, public/js/duplicates.js,
public/css/pages/duplicates.css):

- progressPercent() counts pairs whenever the plan knows them, the answers
  of the running request included, and falls back to requests only while no
  pair count exists. The bar therefore moves during a request instead of
  jumping once per request.
- progressCountsText() gained the "7 of 10 answers" part, printed only while
  a request is in flight and capped at the size of that request.
- progressTimeText() says "measuring the model" in the warm-up and "the
  model is thinking" while the model writes reasoning, instead of a clock
  that cannot move; an estimate the job already made is still shown next to
  either.
- New #dupAiProgressNote line under the counts, written by the new
  progressNoteText(): "4 pairs per request while the model is measured"
  before the measurement, "9 pairs per request, sized from the model's
  answers" after it, empty while no size is known. A zero-width space holds
  its row open for as long as a review runs (.dup-progress--live), so the
  stats tiles below do not jump the moment it fills.
- .dup-progress__fill--thinking pulses while the model reasons, slower than
  the indeterminate band, and is switched off under prefers-reduced-motion.
- The outcome line and the "Model requests" tile both name the batch size the
  review settled on.
- New htmlReviewFailure(): all three AI paths report a failed review with the
  judge's own message plus one link, "Open the Duplicates settings", to
  /settings#duplicates-tab.

Settings (views/settings.ejs, public/js/settings.js, routes/setup.js):

- Two fields close the Duplicates section: the switch "Let the judge think"
  (DUPLICATES_AI_THINKING, default off) and the number "Seconds per model
  request" (DUPLICATES_AI_REQUEST_SECONDS, 5-300, default 30). GET, POST with
  the usual clamping and keep-the-previous-value behaviour, the @swagger
  request body, ENV_EXPORT_GROUPS and the two "Managed by ENV" selectors.

Route:

- GET /api/duplicates/scan passes fresh: true; a scan somebody pressed a
  button for must not be answered from a cache.

OPENAPI/openapi.json regenerated.

Testing

- node scripts/run-tests.js --all: 93 passed, 7 skipped offline, 0 failed
  (unchanged from the baseline of this round).
- duplicates-ui 58 -> 66 cases: the bar with streamed answers and without a
  pair count, the counts line with and without a running request, the three
  wordings of the time line, the note line, the outcome line with a batch
  size, the panel ids and the thinking class, the settings link of the failed
  notice, and the stylesheet's pulse with its reduced-motion rule.
- settings-duplicates-section 11 -> 15 cases: both fields render with their
  values and hints, the POST round trip, clamping (2 -> 5, 999 -> 300), the
  cleared field keeping the previous value, the switch spellings, the export
  group order and the two selectors.
- duplicates-endpoints 30 -> 31 cases: the scan route hands fresh: true to
  the service.
- eslint, prettier and stylelint clean on every touched file; regen-openapi
  leaves no drift.
- Looked at in Chromium against a throwaway server on port 3403 that walks a
  scripted review through the warm-up, a thinking stretch and a request whose
  answers climb 0 -> 10: desktop and phone, light and dark. The stats tiles
  sit at the same offset before and after the note line fills.

Impact

The panel reports inside a request rather than between requests, and names
both the warm-up and the measured batch size, so a review that takes minutes
per request looks like work rather than a hang. A failed review points at the
setting that would have prevented it. Nothing scans, judges or merges on its
own; the two new settings are read at startup like the rest of the section.

Upstream Status

Not applicable - the Duplicates page does not exist upstream.

* feat(duplicates): measure the model, size every request to it, and reuse a fresh scan

Background

Asking the AI about a scan of the user's archive did not work on their
instance. The judge sent 25 pairs with a completion cap of 3200, the hosted
model thought before it answered and spent all 3200 tokens on the thinking,
and 102 seconds later nothing had been judged. The answer was then split into
13 + 12, which buys nothing: the thinking does not get cheaper with fewer
pairs. Meanwhile the page showed "request 1 of 4 · estimating…" for two
minutes, because a request only reports when it is over. The user pressed
Stop.

The same run also scanned the archive three times inside 50 seconds — the
page's scan, the AI proposal's and the review job's — 1359 tags and 13
seconds each, with nothing changing in between.

Changes

services/entityMatchAiService.js

- Thinking off by default. Every judge request carries
  `reasoning: config.duplicatesAiThinking === true`, so a reasoning model
  answers instead of deliberating unless the operator asked for it. Nothing
  else about the prompt changed.
- A warm-up instead of a guess. The first request of a review whose model has
  not been measured asks about at most WARMUP_PAIRS (4) pairs with a
  deliberately generous cap (RESPONSE_TOKENS, the flat estimate or
  WARMUP_MIN_CAP, whichever is largest, bounded by the context window). It is
  announced under the phase `warming-up` with the message "Measuring the model
  with a small first request…", `calibrated: false` and the size it will use;
  the plan reported with it is provisional and the log says so.
- Sizing from the measurement. Every answered request yields tokens per pair
  (thinking included) and tokens per second, each smoothed by half against the
  measurement before it. From them:
  `batchSize = clamp(floor(requestSeconds × tokensPerSecond ÷ tokensPerPair), 1, batchSize())`
  and `cap = ceil(tokensPerPair × batchSize × 1.5) + TOKENS_OVERHEAD`, both
  bounded by the context window as the batch planning bounds them.
  `requestSeconds` is DUPLICATES_AI_REQUEST_SECONDS, at least 5, 30 by
  default. A batch is now taken off the front of a queue rather than chunked
  up front, because its size changes while the review runs.
- The plan settles after the warm-up. `requestsPlanned` and `estimatedTokens`
  are re-derived from the pairs nobody has asked about yet and reported with
  `batchSize` and `calibrated: true`, so the page's denominator stops moving.
- Truncation: raise before halving. A cut-off answer that salvaged nothing is
  asked again with twice the cap (the warm-up gets the whole window at once),
  and only when that bought nothing — or the cap is already at the window's
  bound — is the batch halved as before. A warm-up that does not fit even then
  ends the review as failed with a message the operator can act on, naming
  DUPLICATES_AI_THINKING and TOKEN_LIMIT. A single pair at the bound keeps the
  old "unsure" and its log line.
- The cut-off text counts. All four providers now attach `error.partialText`,
  so the salvage path runs for every one of them; a salvaged request counts
  its verdicts in `pairsJudged` and in the tracker. Two comments that still
  said only Ollama returns half-written answers were rewritten.
- Progress inside a request. With a progress sink the provider is asked to
  stream (`onProgress`). Each report, at most every 250 ms, carries
  `requestPairs`, `requestAnswers` (the complete verdict objects counted off
  the streamed text), `requestTokens`, `thinking` and the running token total:
  "The model is thinking… (640 tokens so far)" while it thinks, otherwise the
  request line with " · 7 of 10 answers" appended. The report that counts the
  request resets all four. A review nobody watches sends the plain request it
  always sent.
- Calibration memory. The last measurement per model name lives on the
  singleton; a review that finds one starts sized from it, skips the warm-up
  and says so in the log. A measurement taken with thinking on is never reused
  with thinking off. `resetCalibration()` for tests.
- Logs: the finish line says "N pair(s) planned" (the number is the plan), the
  batch-size line is marked provisional until the model is measured, and the
  split line says whether the cap was raised or the batch halved.

services/duplicateMergeService.js

- `scan()` keeps its result per set of options (kind, threshold,
  includeDismissed) for SCAN_CACHE_MS (60 s) and answers the next identical
  request from it with one log line instead of the start and finish lines.
  `fresh: true` skips and refills it; the page's Scan button sends it.
- A merge, an undo, a dismissal and `restoreDismissal()` empty the cache. A
  dismissal deleted through the route, which talks to the model directly, is
  caught by a fingerprint (row count and highest id per kind) checked on every
  hit — one local SELECT against a 13-second scan.
- `reviewScan()` calls `scan()` without `fresh`, so a proposal made right
  after the page scanned costs no second scan.

Testing

- node scripts/run-tests.js --all: 93 passed, 7 skipped offline, 0 failed
  (100 registered), unchanged from the baseline.
- tests/test-entity-match-ai-service.js: 65 -> 80 cases. New: thinking off and
  on; the warm-up's size, cap, phase and message; the sizing math on a fixed
  usage and duration; the request seconds and their floor; the context window
  bounding size and cap; smoothing; the plan and estimate recomputed after the
  warm-up; calibration reused, not reused across the thinking switch, reset; a
  warm-up that cannot fit ending the review with its message; a truncated
  answer with partialText salvaged and counted; a streamed request reporting
  thinking, then answers, then clearing itself; an unwatched review not
  streaming; a review served from the page's scan.
- tests/test-duplicate-merge-service.js: 17 -> 22 cases. New: cache hit, other
  options and `fresh` missing it, expiry, invalidation by merge, undo, dismiss
  and restore, and a dismissal removed behind the service.
- Changed expectations, all from the raise-before-halve rule: the truncation
  cases now see every size asked twice (once, once with twice the cap) before
  it is halved, the single pair is asked twice before it ends as unsure, and
  the planning cases see the `warming-up` phase where they saw `judging`.
- Two demo runs against a fake model at 30 tokens/s: thinking off, 12 pairs —
  warm-up 4 pairs in 20 s (600 tokens, 150 per pair), then requests of 5 pairs
  at 25 s, 4500 tokens, 60 s in total. Thinking on — warm-up 4 pairs in 40 s
  (1200 tokens, 300 per pair) and requests of 2 pairs at 30.04 s, the
  configured length.

Impact

The first request of a review is seconds rather than minutes, every later one
lasts about as long as the operator asked, and the page shows the model
thinking and answering while it happens instead of a still bar. A review of a
model that was measured before starts at full size. Three scans of one archive
become one. Nothing runs on its own and no verdict changed: the prompt, the
rules and the shape of an answer are what they were.

Upstream Status

Not applicable — the Duplicates feature does not exist upstream.

* fix(duplicates): a review never asks for a fresh scan of its own

reviewScan() drops a `fresh` flag its caller may carry instead of passing it on, so a route that forwards the page's scan options cannot make the review scan the archive a second time.

* fix(duplicates): the yes/no switches of the judge read 'yes', and a small batch is not starved after a thinking one

Background
The browser smoke test of the round ran the thinking scenario and the
judge kept saying "thinking off" although DUPLICATES_AI_THINKING=yes
was set. config/config.js normalises every yes/no setting to the
strings 'yes' and 'no' (parseEnvBoolean), while three readers in the
judge asked Boolean() or === true: the thinking switch could never be
turned on, and the review and excerpt switches could not be turned off
('no' is a truthy string). The second finding: a thinking model pays a
fixed price per request, so a one-pair request sized by pairs alone
after a four-pair warm-up got a cap the same thoughts did not fit; the
judge recovered by raising the cap, at the cost of one request.

Changes
- services/entityMatchAiService.js: switchedOn() accepts 'yes' and a
  boolean true; isEnabled(), excerptsEnabled() and thinkingEnabled() use
  it. The cap never drops below the largest completion the model has
  produced in this review plus a quarter (CAP_FLOOR_FACTOR), and that
  floor is remembered with the calibration.
- tests/test-entity-match-ai-service.js: one case per finding (82
  cases), the sizing case expects the remembered floor.
- config/changelog.js: three entries for the round under the current
  release.

Testing
- node scripts/run-tests.js --test entity-match-ai-service: 82 passed.
- Browser smoke against a fake Paperless-ngx and a fake provider that
  streams, thinks on request and honours max_tokens: thinking off, the
  fake never thought, warm-up 4 pairs, 59 tokens/s measured; thinking
  on, the panel showed the thinking state, no request hit the token
  limit any more; Stop, re-attach, token budget and the round-6
  walkthrough unchanged.

Impact
DUPLICATES_AI_REVIEW=no and DUPLICATES_AI_EXCERPTS=no now do what they
say; DUPLICATES_AI_THINKING=yes now reaches the model.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): contract for the creation guard, the semantic sweep, unused objects, renames and a remembered calibration

Background
Round 9 of the Duplicates feature, six points the user picked: stop
the drift where it starts (document analysis creating "Rechnungen"
next to "Rechnung"), let the model find synonyms and translations the
string matcher cannot, list and delete unused objects with undo, name
the survivor of a merge, keep the judge's measurement of a model across
restarts, and scan faster. Decisions: only hard matcher tiers map a
new name onto an existing one (case, umlauts, legal form, plural, word
order), typo-like matches are logged and…
…ops after thinking (#339)

* feat(duplicates): contract for a targeted AI review

Background
With many groups at 94 to 96 percent the user wants to say "everything
from 95 percent up: ask the AI, show me its view, then merge". The
review must therefore be able to judge only chosen groups and skip the
band of near-misses.

Changes
- schemas.js, OPENAPI/openapi.json: groupIds, minConfidence and
  includeCandidates on DuplicateAiReviewRequest.

Testing
- node scripts/regen-openapi.js: no drift after the commit.

Impact
Request fields only; the implementation follows.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): targeting counters in the AI review result schema

Background
A targeted review reports which groups it judged and which it left
without a verdict; the page shows that.

Changes
- schemas.js, OPENAPI/openapi.json: targeted, groupsJudged and
  groupsSkipped on DuplicateAiReviewResult.aiReview.

Testing
- node scripts/regen-openapi.js: no drift after the commit.

Impact
Documentation of three informational fields.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): let the AI review be pointed at a few groups

Background

An archive with hundreds of correspondents produces dozens of groups at
94, 95 and 96 per cent, and asking the model about all of them costs a
lot to answer a question about a handful. The page needs to select the
groups it is about to merge, ask about those, and keep rendering the
rest of the scan while it does.

Changes

- entityMatchAiService.reviewScan() takes three options that narrow what
  is asked, never what comes back:
  - groupIds: only these scan groups are judged. Every other group is
    still in `groups`, as the scan produced it, with `aiVerdict: null` on
    the group and on every member and `source: 'scan'`. An id this scan
    does not know is ignored and logged once with the count.
  - minConfidence: only groups scoring at least this much are judged;
    together with groupIds both conditions have to hold.
  - includeCandidates (default true): false leaves the band of
    near-misses out entirely, so `candidates` is 0 — and with no band
    the entity list per kind is not read either, which is the cheap part.
- _pairsForKind() takes the set of group ids to judge. A group left out
  contributes no pairs but its member pairs still count as "inside one
  group", so it cannot reappear as a candidate.
- The result reports the targeting: aiReview.targeted, .groupsJudged and
  .groupsSkipped. The start line of the log names it as
  "judging 1 of 4 group(s) (min confidence 0.95, 3 ids), band skipped",
  the closing line adds the two counters. An untargeted review logs and
  behaves exactly as before.
- POST /api/duplicates/ai-review validates and passes the three fields
  through: groupIds an array of at most 500 non-empty strings,
  minConfidence a number in [0.5, 1], includeCandidates a real boolean
  (the string "false" is a 400). An option the request does not mention
  is left out of the service call, so an untargeted request reaches
  reviewScan() with the same object it did before.
- Swagger description of the route and the 400 reason updated,
  OPENAPI/openapi.json regenerated.

Testing

- node scripts/run-tests.js --all -> 90 passed, 7 skipped offline,
  0 failed (97 registered), unchanged against the baseline.
- entity-match-ai-service: 28 -> 34 cases. Six new ones on a fixture
  whose four groups sit exactly on the matcher tiers (1, 0.98, 0.95,
  0.9) plus one pair in the band: groupIds judges only what it names,
  minConfidence filters, includeCandidates: false skips the band and
  reads no second entity list, groupIds and minConfidence combine while
  unknown ids are ignored, an empty selection costs no request, and the
  log lines. The existing aiReview assertion gained the three new fields.
- duplicates-endpoints: 16 -> 19 cases. The three fields reach the
  stubbed reviewScan unchanged, an untargeted request still carries
  nothing extra, ten malformed targeting bodies are 400, and 500 ids are
  accepted while 501 are not.
- Manual run against the real route with a fake store and a fake
  provider: full review 5 pairs / 1 request, minConfidence 0.95 without
  the band 3 pairs, two selected ids (one unknown) 1 pair, and every
  unjudged group back with null verdicts.
- eslint, prettier and the OpenAPI drift check clean on the touched
  files.

Impact

Additive. A review that says nothing about the three options behaves and
logs as before. The page can ask about the groups it selected before a
batch merge; a dozen groups without the band are one or two model
requests instead of the whole archive. schemas.js still has to gain
targeted, groupsJudged and groupsSkipped on DuplicateAiReviewResult.

Upstream Status

Not applicable: the Duplicates feature is next-only.

* feat(duplicates): sort, select by confidence, and a guided review before merging

Background
----------
On a grown archive a scan answers with dozens of groups that all read 94, 95,
96 percent, and the page offered no way to act on that number: every group had
to be judged by eye, one tick at a time. The three presets were the only
thresholds available, so "everything above 95" was not a question the page
could be asked. And where the AI review existed it judged the whole result
list, which is the most expensive way to ask about the five groups the user
actually cares about.

The rule this follows: the AI is an addition, never a condition. Every flow
below works end to end with the review switched off; with it on, the guided
path is one more button beside the one that was already there.

Changes
-------
Results toolbar (#dupResultsBar), above the selection bar, shown once a scan
has groups:
  - "Sort by" (#dupSortSelect): confidence, documents, target name (locale
    compare), kind then confidence. It moves the DOM nodes instead of
    re-rendering, so a card keeps its target, its source ticks, its selection,
    its verdict and its busy state; the two blocks (scan groups, AI
    candidates) are sorted separately and the divider stays between them.
  - "Select >=" (#dupMinConfidence, #dupSelectMinBtn, #dupMinConfidenceCount):
    ticks every selectable group at or above a whole percent and unticks the
    rest, with a live count of what the click would do.
Custom scan threshold: a fourth sensitivity option "Custom" reveals a number
field (#dupThresholdCustom); the scan and both review paths send that percent
divided by 100. The three presets are unchanged.
Confidence breakdown under "Groups found" (#dupStatBuckets): ">=95 %: A .
90-95 %: B . <90 %: C", counted from the cards after a scan and after a review.
Guided flow (#dupReviewThenMergeBtn, rendered only where the review exists):
asks the model about exactly the ticked groups (groupIds, includeCandidates:
false), puts the verdicts on the cards as a full review does, then shows them
once in a wide dialog - one row per group with target, sources, documents, the
verdict chip and the reason, a live "N of M ticked . K documents" foot line and
the copy-rule check. Ticked rows are merged with the batch machinery; an unsure
or different verdict only comes up unticked and never blocks anything, and what
stays unticked stays selected on the page.
"Merge selected" keeps its place and its weight, first in the bar and without a
model anywhere in its path; its dialog names the guided path in one faint line,
and only where that path exists.
Sort, confidence, sensitivity and the custom threshold are remembered in
localStorage (dup.sort, dup.minConfidence, dup.sensitivity,
dup.thresholdCustom) through two try/catch helpers.

Testing
-------
node scripts/run-tests.js --all -> 90 passed, 7 skipped offline, 0 failed
  (unchanged from the branch baseline).
tests/test-duplicates-ui.js: 25 -> 38 cases. New: the toolbar ids and their
  order, the custom threshold field, the stats breakdown, the guided button
  only with the review, the whole page without the review, the toolbar ids in
  the script, sorting as a DOM move, "Select >=", the wrapped localStorage
  access, the guided request (groupIds / includeCandidates: false) and that
  "Merge selected" never touches the review endpoint, the review dialog markup,
  the tip line, the new CSS classes. Changed: the sensitivity options are read
  from #dupSensitivity alone and now end in "custom"; the undo promise and the
  confirm dialogs are counted one higher each, because the review dialog merges
  and therefore makes the same promise.
Reviewed in a browser against a throwaway mock (twelve groups over 88-100 %, a
  review that honours groupIds): 27 screenshots at 1280x900 and 390x844, light
  and dark, 0 px horizontal overflow everywhere, plus a 31-check behaviour
  probe (guided request, verdict ticks, sorting keeping picks and the divider,
  persistence, a refused review, and the whole page with the review off).

Impact
------
Page only. No route, service, schema or config was touched, so the OpenAPI
spec is unchanged. An instance without the AI review renders and behaves
exactly as before plus the toolbar and the custom threshold. The request the
guided path sends uses fields the contract already carries; a server that
ignores them reviews everything, which the page renders correctly.

Upstream Status
---------------
Not applicable - the Duplicates page does not exist upstream.

Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* docs(duplicates): changelog entries for sorting, select by confidence and the guided review

Background
Round 5 answered the second feedback from a real archive: select by a
number, let the model judge exactly those groups, read its verdicts in
one dialog, merge what stays ticked; sort the groups; a custom threshold.

Changes
- config/changelog.js: two entries in the current v2026.09.01 block.

Testing
- node scripts/run-tests.js --test changelog-releases: passed.

Impact
Documentation only.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): contract for evidence-based verdicts and the AI proposal

Background
A real archive produced "Kontoauszug" / "Kontoumzug": the matcher called
it a spelling distance, the prompt allowed "an obvious typo" as a reason
for same, and the model, seeing names and titles only, agreed. Both are
different things. The judge needs stricter rules and, for pairs linked by
spelling alone, a look at what the documents are about, at a bounded
cost.

Changes
- config/config.js: DUPLICATES_AI_EXCERPTS (default yes),
  DUPLICATES_AI_EXCERPT_CHARS (300), DUPLICATES_AI_EXCERPT_DOCUMENTS (2).
- schemas.js, OPENAPI/openapi.json: AiVerdict gains basis and confidence;
  DuplicateAiReviewRequest gains withExcerpts; aiReview reports excerpts.

Testing
- node scripts/run-tests.js --area duplicates: 6/6; regen without drift.

Impact
Settings and schema only; the implementation follows.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): judge model override and the verdict source in the contract

Background
Decisions for round 6: the matcher's hard tiers settle a pair without the
model, unsure pairs are asked once more with excerpts, and the judge may
run on a stronger model of the same provider.

Changes
- config/config.js: DUPLICATES_AI_MODEL (optional, judge only).
- schemas.js, OPENAPI/openapi.json: AiVerdict.source (model or
  spelling-rule); aiReview.escalated and aiReview.spellingRules.

Testing
- eslint and prettier on the two files; regen without drift.

Impact
Settings and schema only; the implementation follows.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(settings): make every DUPLICATES_ setting editable in its own section

Background
The AI review of the Duplicates page arrived with seven environment
variables and no way to change any of them from the interface. Editing a
container environment and recreating the container is the wrong price for
"try a stronger model for the judge" or "ask about fewer pairs per
request", and the settings page is exactly where those knobs belong.
config/config.js already reads all seven; only the front door was missing.

Changes
- views/settings.ejs: a "Duplicates" section (id="sec-duplicates") inside a
  new duplicates-tab block between the AI sections and OCR, with a nav entry
  in the desktop section nav (icon i-merge) and in the mobile one, in the
  same order as the page. Seven fields, each with a hint that says what the
  value does and what its default is: the AI review switch, the judge model,
  pairs per request, the candidate floor, the excerpt switch, excerpt length
  and documents per entry. Switches go through partials/settings-switch, so
  the hidden yes/no input the POST route reads exists as it does everywhere
  else.
- routes/setup.js: GET /settings passes the seven values (env first, the
  defaults of config/config.js as fallback) in the config object the view
  reads; POST /settings destructures the seven camelCase body keys,
  normalises them and writes them into updatedConfig, so setupService
  .saveConfig persists them with the rest. Numbers are clamped to their
  range; a value that is not a number, or a cleared field, keeps what is
  configured now instead of resetting to the default. The swagger body
  schema documents all seven, and the .env export gained a "Duplicates"
  group between "AI behaviour" and "External API".
- public/js/settings.js: the seven selector to env-key entries, so the
  "Overwritten" and "Managed by ENV" marking covers these fields too.
- OPENAPI/openapi.json regenerated.
- tests/test-settings-duplicates-section.js, registered in the
  observability area.

Testing
- node scripts/run-tests.js --all: 98 registered, 91 passed, 7 skipped
  offline (was 97/90/7). The new test covers the rendered section and its
  nav position, the seven inputs and their values, the POST round trip,
  clamping, the keep-the-previous-value case and the .env export group.
- npx eslint / npx prettier --check --ignore-unknown on every touched file.
- node scripts/regen-openapi.js leaves OPENAPI/openapi.json unchanged.
- Looked at the page in Chromium at 1440x1000 and 390x844 against a
  throwaway server outside the repository; no console errors, the section
  reads like the rest of the page and stacks on the phone.

Impact
Operators can change every DUPLICATES_ value from the settings page. The
existing restart-after-save is what makes them take effect; no new
mechanism. Values injected by the container still win and are shown as
managed, as for every other field. Nothing outside the settings page
changes: no route, service or default behaviour of the Duplicates page
itself is touched.

Upstream Status
Fork-only. The Duplicates page does not exist upstream.

Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): judge spelling-only pairs on evidence, not on distance

Background
A real archive produced "Kontoauszug" next to "Kontoumzug": the matcher
called it a spelling distance, the prompt allowed "an obvious typo" as a
reason for same, and the model, seeing two names and three titles, agreed.
Two different things. The judge needed stricter rules, evidence for the
pairs where spelling is the only link, and a way to say how sure it is and
on what grounds — all without opening a large context window on every pair.

Changes
- entityMatchAiService: the system prompt refuses a small spelling distance
  as a reason of its own ("Kontoauszug" / "Kontoumzug", "Miete" / "Mieter",
  "Bahn" / "Bank"), allows a misspelling only when one spelling is not a
  word, and answers unsure when it cannot tell. The output contract gains
  "basis" (a closed list) and "confidence" (high | low); both are parsed,
  an unknown value becomes null, and every verdict, member verdict and
  aggregate carries them. An aggregate keeps the deciding member's basis
  and takes "low" as soon as one deciding member is low.
- Evidence, graded by what the link is worth: every pair carries matched_by
  and score; every judged entity carries its titles, its matching rule and
  its neighbourhood ("filed_with": the correspondents of a tag's documents,
  the tags of a correspondent's); only the pairs linked by fuzzy, prefix or
  token-order also carry document excerpts. Excerpts are read once per
  entity per review and never for a strong tier. withExcerpts: false or
  DUPLICATES_AI_EXCERPTS=no reads nothing at all.
- A member pair a matcher rule settles (exact-normalized, umlaut-variant,
  legal-form) never reaches the provider: it gets verdict same with
  source: spelling-rule, counts in aiReview.spellingRules and costs no
  request, no read and no token.
- A pair the model calls unsure and that had no excerpts is asked once more
  with them; the second answer replaces the first (aiReview.escalated).
- paperlessService: getRecentDocumentExcerptsByEntity (one read,
  truncate_content, cut to the configured characters at a word boundary)
  and getEntityNeighbourhood (one read, the most frequent neighbour names
  through the existing caches). Both answer [] on any error and never log
  document content.
- The judge may run on its own model (DUPLICATES_AI_MODEL): generateText
  takes an optional model in all four provider services, shared through
  aiGenerateOptions.modelOverride.
- Logs: the per-kind start line names the evidence and the model, the
  request line the pairs with excerpts, the escalation its own line.
- Route POST /api/duplicates/ai-review parses withExcerpts like withTitles;
  swagger description updated and OPENAPI/openapi.json regenerated.

Testing
- node scripts/run-tests.js --all: 97 registered, 90 pass, 7 skip offline.
- tests/test-entity-match-ai-service.js: 35 -> 50 cases (the stricter
  prompt, basis and confidence parsing, excerpts only for spelling-only
  pairs and once per entity, the two switches, the configured cut, the
  Kontoauszug regression, settled pairs, the neighbourhood, escalation, the
  model override, batch sizing with excerpts, and both new client methods).
- tests/test-duplicates-endpoints.js: one case for withExcerpts; the three
  existing option assertions now expect withExcerpts: true.
- Demo run against the fake Paperless-ngx: the Kontoauszug/Kontoumzug pair
  costs 282 prompt tokens with excerpts, a strong pair without excerpts 75.
- eslint, prettier and a regen without drift on every file touched.

Impact
An AI review asks about fewer pairs and knows more about the ones it asks
about. Nothing runs on its own, nothing is merged, and document content
never reaches a log line.

Upstream Status
Not applicable — the Duplicates feature does not exist upstream.

* fix(duplicates): do not escalate an unsure pair whose documents carry no text

* feat(duplicates): one click for the AI's proposal, with the evidence behind it

Background
----------
Everything the page offered so far started from the user: scan, read every
card, tick, merge — and where the AI review existed it was a second question
asked after the first. What was missing is the path the archive's owner
actually wants for a first clean-up: one click that scans, has every group and
every near-miss judged, and then hands over a proposal to thin out rather than
a list to work through.

The rule this follows is the same as in the rounds before: the AI is an
addition, never a condition. Without the review nothing of this renders, and
"Scan Paperless-ngx", "Merge selected", the toolbar, the manual merge and the
guided path are the same as they were.

A verdict also had to say more than "same": with `basis`, `confidence` and a
`source` on the wire, the page can pre-tick exactly what is settled — a pair a
spelling rule decided, or one the model says it is sure about — and leave
everything else to the user. The member tables, finally, measured their own
content per card, so the columns of two cards below each other sat in
different places.

Changes
-------
"AI proposal" (#dupAiProposalBtn, primary, rendered only with aiReviewEnabled)
next to "Ask the AI", usable from the first paint because it scans itself:
  - status in the AI row (#dupAiProposalStatus): "Scanning…", then "Asking the
    AI about N pairs and near-misses…", with the hint line under the row
    (#dupAiProposalHint) saying what the click does;
  - it reuses runScan() (now awaited) with the kind, sensitivity and hidden-pair
    settings on the page, then the one review request with includeCandidates
    and no groupIds. Two requests, and no merge until the dialog is confirmed.
Proposal dialog (.dup-proposal-dialog): one row per group that could be merged,
  sorted same/high, same, unsure, different, unjudged (proposalRank,
  compareProposalEntries — both pure); pre-ticked are only the settled ones
  (isSureSame: verdict "same" with confidence "high", which covers the
  spelling-rule verdicts); legend, "Tick all same" (#dupProposalTickSame),
  "Untick all" (#dupProposalUntickAll), the copy-rule check (#dupCopyRuleAll)
  and a live foot line "N of M ticked · K documents · X objects will be
  deleted". Confirming sets the page selection to the ticked groups and hands
  them to the batch runner of round 4, so the selection bar reports the merge
  as it does for "Merge selected"; cancelling leaves the verdicts on the cards
  and nothing ticked.
Evidence, shared by both dialogs (one row renderer, one table):
  - a "Basis" column as a .zr-badge with a label per contract value;
  - the confidence as a suffix of the verdict chip ("AI: same · high");
  - a pair a spelling rule settled reads "Spelling rule" in the "same" tone
    (.dup-verdict--rule) instead of quoting a model that never saw it;
  - the guided dialog pre-ticks by the same rule, so a "same" the model is
    unsure about now comes up unticked there too.
Cards keep their shape: the verdict chip carries the basis in its title and the
  confidence as its suffix, no new column.
Second checkbox "Use document excerpts for spelling-only pairs"
  (#dupAiExcerpts, checked); withTitles and withExcerpts flow into every review
  request from the one place that builds it. The titles checkbox is relabelled
  "Use document titles and neighbours as context".
"AI-judged pairs" tile: its sub line now also counts "· E excerpts", "· S by
  spelling rule" and "· E escalated" when the review reports them.
Member tables line up across cards: .dup-members is table-layout: fixed with
  the name column taking what is left and truncating, and the matching rule a
  fixed share (.dup-members__name, .dup-members__rule).

Testing
-------
node scripts/run-tests.js --all -> 90 passed, 7 skipped offline, 0 failed
  (unchanged from the branch baseline of 97 registered).
tests/test-duplicates-ui.js: 38 -> 48 cases. New: the proposal ids and labels
  only with the review and the page whole without them; what the flow sends
  (runScan first, includeCandidates: true, no groupIds, both evidence flags,
  no request of its own); the pre-tick rule, evaluated as a function against
  seven verdicts; the row order, evaluated by sorting a shuffled list; a label
  for every basis the AiVerdict schema lists, parsed out of schemas.js; the
  spelling-rule chip; the dialog's parts and that it merges through the batch
  runner; the evidence counters of the stats tile; the fixed member-table
  layout; the new CSS classes. Changed: the titles checkbox label, the undo
  promise and the confirm dialogs counted one higher each (the proposal merges
  and therefore makes the same promise), and the pre-tick assertion of the
  guided row.
Reviewed in a browser against a throwaway mock (eleven scan groups plus three
  the model proposes, verdicts across same/high, same/low, unsure and
  different, some settled by a spelling rule, and a Kontoauszug / Kontoumzug
  pair that only the excerpts decide): 31 screenshots at 1280x900 and 390x844,
  light and dark — the controls, the status line mid-flow, the proposal dialog,
  after "Untick all", mid-merge, after the merge, the guided dialog, the stats
  tile, the aligned member tables and the render without the review. 0 px
  horizontal overflow everywhere; the column offsets of all eleven cards are
  identical.

Impact
------
Page only. No route, service, schema or config was touched, so the OpenAPI
spec is unchanged. An instance without the AI review renders and behaves
exactly as before. The new request field and the new verdict fields are ones
the contract already carries: a server that ignores withExcerpts reviews as it
did, and a verdict without basis, confidence or source renders as it did — it
then simply never comes up pre-ticked, which is the safe side.

Upstream Status
---------------
Not applicable - the Duplicates page does not exist upstream.

Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* chore(duplicates): changelog for the AI proposal round, room for the verdict in the Match column

Background
The sixth round of the Duplicates feature adds the AI-led proposal, the
evidence-based judge and the Duplicates settings section. The member
tables now use a fixed column layout so the columns line up across
cards, which left the Match column too narrow for a verdict such as
"AI: same - high": it wrapped into four lines.

Changes
- config/changelog.js: five entries for the round under the current
  release (AI proposal, evidence-based judge with excerpts and
  DUPLICATES_AI_EXCERPT*, DUPLICATES_AI_MODEL, aligned member tables,
  the Duplicates settings section).
- public/css/pages/duplicates.css: the Match column is 132px wide and
  the member verdict does not wrap, so the percentage and the verdict
  take one line each.

Testing
- npx eslint, prettier --check and stylelint on every file changed
  against nightly: clean.
- node scripts/run-tests.js --all: 91 passed, 7 skipped (server or
  credentials needed), 0 failed.
- node scripts/regen-openapi.js: no drift.
- Browser walkthrough against a fake Paperless-ngx and a fake judge:
  scan, merge, undo, dismiss, merge by hand, batch merge, guided review,
  AI proposal and AI review all pass. The Kontoauszug/Kontoumzug pair is
  judged "different" on its excerpts and does not appear in the
  proposal.

Impact
Visual only for the CSS; the changelog is shown in the What's New
dialog.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): contract for a watchable, stoppable AI review

Background
An AI review of a large archive is many model requests in a row. Today
it is one POST that answers when everything is done: nothing shows
while it runs, nothing can stop it, and the tokens it spends are
invisible until the end. The user wants to see what is happening, how
far it is and what it costs, and to stop it at any time. Decisions for
this round: the review runs as a server-side job the page can watch
and stop; a review nobody watches stops itself; a token budget per
review stops it on its own; a stopped review keeps the verdicts it
reached and opens no dialog; the progress lives in the AI row of the
Duplicates page.

Changes
- services/duplicateReviewJobService.js (new): the one review job at
  a time. start(), current(), get(), stop(id, reason), subscribe() for
  a server-sent stream (a late subscriber first gets the job as it is
  now), touch(), wait(), result(), toJSON(). The judge receives a
  control object (signal, onProgress, stop, tokenBudget); a partial
  result of a stopped review is kept like a complete one. The idle
  watch stops a job nobody has watched for the configured seconds. A
  finished job stays reachable for ten minutes.
- config/config.js: DUPLICATES_AI_TOKEN_BUDGET (200000, 0 = no limit)
  and DUPLICATES_AI_IDLE_STOP_SECONDS (60, 0 = never).
- schemas.js, OPENAPI/openapi.json: AiReviewProgress, AiReviewJob,
  AiReviewJobEvent; aiReview gains stopped, stopReason and
  pairsNotJudged.
- scripts/run-tests.js, tests/test-duplicate-review-job.js: the
  contract test of the job (9 cases) in the duplicates area.

Testing
- node scripts/run-tests.js --all: 99 registered, 92 pass, 7 skip
  offline, 0 fail.
- eslint and prettier on every touched file; regen without drift.

Impact
Nothing uses the job yet; the judge ignores the control object until
the implementation follows. No route or page changes.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): make the token budget and the idle stop editable in settings

Background
The two brakes of a running AI review landed as environment variables only:
DUPLICATES_AI_TOKEN_BUDGET caps what one review may spend across all its
requests, DUPLICATES_AI_IDLE_STOP_SECONDS ends a review no page has been
watching, so a closed tab cannot leave the model running. Both are exactly
the kind of setting somebody wants to try out once and then adjust, which
means editing a compose file and restarting the container for every attempt.
The other seven DUPLICATES_* variables already have a field in the Duplicates
section of the settings page; these two did not.

Changes
- views/settings.ejs: two number fields at the end of #sec-duplicates, in the
  style of the five above them — duplicatesAiTokenBudget (0-10000000, step
  1000) and duplicatesAiIdleStopSeconds (0-3600). Each hint says what the
  value does, what zero means and what the default is.
- routes/setup.js: GET /settings passes DUPLICATES_AI_TOKEN_BUDGET and
  DUPLICATES_AI_IDLE_STOP_SECONDS to the view with the defaults of
  config/config.js as the fallback; POST /settings destructures both body
  keys, clamps them to their ranges and keeps the currently configured value
  for an empty or non-numeric field, the rule the round-6 fields follow. Zero
  is a value for both and survives the clamp, because the ranges start there
  rather than at one. The @swagger body schema documents both, and the
  Duplicates group of ENV_EXPORT_GROUPS lists them after the existing keys.
- public/js/settings.js: two entries in the field mapping, so an
  operator-injected value greys the field out and carries the "Managed by ENV"
  pill like every other setting.
- OPENAPI/openapi.json regenerated.

Testing
- tests/test-settings-duplicates-section.js grew from 7 to 11 cases: the two
  fields render with their configured values, ranges and hints and close the
  section in that order; every field of the section is paired with its
  environment key in settings.js; the POST round trip persists all nine
  values; a budget of 99999999 is capped at 10000000 and an idle stop of -5
  lands on 0; zero survives for both, because it means "no limit" and "never"
  rather than an unset field; a fractional value is rounded; a cleared or
  unparsable field keeps what was stored before; the .env export carries all
  nine keys with the two brakes last.
- node scripts/run-tests.js --all: 99 registered, 92 passed, 7 skipped
  offline, 0 failed — the same numbers as before this change.
- eslint and prettier clean on every file touched; regen-openapi.js leaves no
  drift.
- Looked at the section in Chromium at 1440x1000 and 390x844 against a
  throwaway server outside the repository: both fields render like the seven
  above them, no console errors, and with the two keys in the locked-env set
  both are disabled and carry the "Managed by ENV" pill while a neighbouring
  field stays editable.

Impact
No behaviour change for anybody who never opens the section: the defaults are
unchanged (200000 tokens, 60 seconds) and nothing new runs. Operators who set
either variable in their container environment keep winning — the field is
shown greyed out rather than silently overwritten. A saved value needs a
restart to take effect, as the hints say, because config/config.js reads the
environment once at load.

Upstream Status
Not applicable — the Duplicates page is specific to this fork.

* feat(ai): let every provider take an abort signal for one call

aiGenerateOptions gains abortSignal(options); the four provider
services pass it on where their client expects it — the OpenAI SDK as
the second argument of create(body, { signal }) for OpenAI, Azure and
the custom endpoint, axios as { signal } in the request config for
Ollama. Without a signal every provider sends exactly what it sent
before: no second argument at all, and the unchanged axios config.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): the AI review reports, stops and counts its tokens

Background
"Während die AI befragt wird, könnten Millionen von Tokens im
Hintergrund verbraten werden, ohne dass man es sieht. Man muss es auch
abbrechen können." The judge answered when it was done and said
nothing while it worked, so the page had nothing to show and nothing
to stop. The job of the previous round hands it a control object; this
round makes the judge use it. A bar needs a denominator before the
first request, which the old per-kind loop could not give: it read the
archive, asked, and only then looked at the next kind.

Changes
- services/entityMatchAiService.js: reviewScan(options, control = {})
  runs in two passes. Pass one, for every kind of the review: read the
  entities and the band, build the pairs, settle the spelling-rule
  pairs, gather titles, neighbourhood and excerpts, and size the
  batches. Pass two judges kind after kind. Nothing is asked before
  the whole plan exists.
- Progress: phase scanning before the scan, phase evidence per kind
  and per read, one phase judging with requestsPlanned, pairsTotal and
  estimatedTokens for the whole review, one report per answered
  request (requestsDone, pairsJudged, the running token total,
  failedRequests, retries, kind, and the line naming the next
  request), phase escalating when an unsure pair is asked again, phase
  finishing before the groups are built. A split answer adds its
  halves to requestsPlanned in the report of the request that split,
  so the bar never goes backwards; the escalation adds its own
  requests and pairs the same way. Elapsed time and the estimate stay
  with the job, which derives them.
- Stopping: control.signal is read before every read, every request
  and the second round, and travels to the provider, so a stop lands
  on a request in flight. A request that dies on the signal is a stop,
  not a failure: no failed request, no retry, and no "unsure" — the
  pairs stay without a verdict, so they cannot become a group. A
  stopped review returns what it reached; it never throws.
  aiReview now always carries stopped, stopReason (null; the job fills
  it in) and pairsNotJudged.
- Token budget: one running total for the whole review, folded from
  the provider's usage or, for a provider that reports none, from the
  measured prompt plus the estimated answer, so the counter and the
  budget work for every provider (aiReview.tokens keeps reporting only
  what a provider stood behind). When control.tokenBudget is reached
  the review calls control.stop('token-budget') and behaves as
  stopped.
- Logs: "review stopped (user|token-budget|idle): N of M request(s)
  made, P pair(s) not judged, T token(s)." and "token budget 200000
  reached after N request(s) (T tokens)."; the start, request and
  finish lines are unchanged.
- services/duplicateReviewJobService.js: the control object gains
  stopReason(), the one seam the judge needs to name the reason in its
  own log line.
- reviewPairs(pairs, options) additionally takes plan, systemPrompt
  and tracker from reviewScan; a caller that brings none gets what it
  always got.

Testing
- node scripts/run-tests.js --all: 99 registered, 92 pass, 7 skip
  offline, 0 fail (the baseline of the branch).
- tests/test-entity-match-ai-service.js: 13 new cases (64 total) —
  the plan before the first request for one and for two kinds, the
  split and the escalation raising the plan, a failed request still
  moving the bar, a stop between requests and a stop in flight, the
  token budget, a provider without usage, an already aborted signal, a
  review without a control, the report carrying nothing the job
  derives, and the signal reaching all four providers. The one moved
  expectation is the deep-equal on aiReview, which now names the three
  new fields.
- tests/test-duplicate-review-job.js: one case for stopReason().
- A real run through the job service over a fake archive: a review
  that runs through, the same one stopped after request 2, and the
  same one against a token budget.
- eslint and prettier on every touched file.

Impact
The page can show a bar with a denominator, an estimate and a running
token count from the first request, and a stop costs at most one
request that is already in flight. A review without a control object
behaves exactly as before, so the synchronous route is untouched until
it is moved onto the job.

Upstream Status
Not applicable: the Duplicates page and its AI review do not exist
upstream.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): watch and stop the AI review from the page

Background

A review of a drifted archive is many model requests in a row. Until now
"Ask the AI" was one POST that answered when everything was over: a spinner,
no idea how many requests were still coming, no idea what it cost, and no way
out but reloading the tab — which left the model running. The job service of
the contract commit made the review watchable and stoppable on the server;
this wires the routes and the page onto it.

Changes

routes/setup.js (Duplicates block only)
- parseAiReviewRequest(body) holds the validation both entry points share, so
  the synchronous route and the job route can no longer drift apart.
- POST /api/duplicates/ai-review/jobs starts a review and answers
  202 { job }; while one runs it answers 409 with that running job, so a
  second tab attaches instead of failing.
- GET /api/duplicates/ai-review/jobs/current answers { job } or { job: null }
  and counts as watching the review.
- GET /api/duplicates/ai-review/jobs/:id answers { job, result }, 404 for an
  unknown id, and also counts as watching.
- GET /api/duplicates/ai-review/jobs/:id/events streams AiReviewJobEvents
  (text/event-stream, no-cache, X-Accel-Buffering: no, keep-alive, flush after
  every write), a ": keep-alive" comment every 15 s, and ends after done,
  stopped or failed. An unknown id is a JSON 404 before any stream header.
- POST /api/duplicates/ai-review/jobs/:id/stop answers { job }; stopping a
  finished review is a 200 no-op.
- POST /api/duplicates/ai-review now starts that same job and waits for it: a
  stopped review answers 200 with the verdicts it reached, a failed one keeps
  the judge's status, and a second request while one runs is a 409. It
  subscribes for the duration so the idle stop cannot end a review somebody is
  waiting for.
- @swagger for every new route; OPENAPI/openapi.json regenerated.

views/duplicates.ejs, public/js/duplicates.js, public/css/pages/duplicates.css
- A progress panel in the AI row (#dupAiProgress): bar (#dupAiProgressFill,
  indeterminate while the plan is unknown), message, counters
  ("Request 3 of 8 · 40 of 96 pairs · 12.4k of 200k tokens"), time
  ("about 40 s left · 1:24 elapsed") and a Stop button (#dupAiStopBtn). After
  the end it keeps one outcome line and hides on the next scan or review.
- askForVerdicts() starts the job, follows it through EventSource and falls
  back to polling the job every 2 s when the stream breaks. It resolves
  { aiReview, stopped }; all three AI paths honour `stopped` — the notice is
  shown and neither the guided dialog nor the proposal opens.
- On load the page asks for the current job and re-attaches to one that is
  still running; a finished one is left alone.
- Pure helpers formatTokens, formatEta, formatElapsed, progressPercent and
  stopNotice word the numbers; the UI test evaluates them directly.

Testing

- node scripts/run-tests.js --all: 99 registered, 92 pass, 7 skip offline
  (unchanged); duplicates-endpoints 20 -> 30 cases, duplicates-ui 48 -> 57.
- eslint, prettier, stylelint clean on every touched file; regen-openapi
  leaves no diff.
- Reviewed in a browser against a throwaway server with a judge that reports
  eight requests: mid-run, stopping, stopped and done, desktop and phone,
  light and dark, no console errors. A page loaded while a review runs
  re-attached and rendered its result; with the event stream blocked the same
  review came home through eight polls.

Impact

The Duplicates page shows what a review is doing and costing and can end it;
the verdicts already reached are kept. The synchronous route keeps its request
and response, so an API client sees no change beyond the new 409 while a
review runs.

Upstream Status

Not applicable — the Duplicates feature does not exist upstream.

* fix(duplicates): a late Stop answer no longer paints over the outcome; changelog for the review job

Background
In the browser smoke test of the round, a stop pressed after the first
answered request ended the job before the stop request itself answered.
The page then rendered that answer, a snapshot from the stopping moment,
over the outcome line and restarted the elapsed clock, so the panel read
"Stopping after the current request…" next to a finished review.

Changes
- public/js/duplicates.js: stopReview() renders the stop answer only
  while the same job is still followed and still live.
- tests/test-duplicates-ui.js: one case that pins the guard (57 -> 58).
- config/changelog.js: three entries for the round under the current
  release (the review as a job with progress and Stop, the token budget
  and the idle stop as settings, the plan before the first request).

Testing
- node scripts/run-tests.js --test duplicates-ui: 58 passed.
- Browser smoke against a fake Paperless-ngx and a slowed-down fake
  provider: Stop during request 2 leaves "Stopped after 1 of 5 requests
  · 1 of 5 pairs judged · 1.1k tokens" on the panel, the verdicts
  reached stay on the cards, no dialog opens; the proposal path stops
  the same way; a token budget of 2500 stops the review after 3
  requests with the budget named in the notice and the log; a page
  reloaded during a review re-attaches and renders the result; the
  round-6 walkthrough (scan, merge, undo, dismiss, merge by hand, batch,
  guided review, proposal, plain review) passes unchanged.
- eslint and prettier on the touched files.

Impact
Visual only; the review itself was stopped correctly before the fix.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): contract for a judge that measures the model, streams its answers and thinks only on request

Background
On a real archive with a hosted Qwen model the first review request
asked about 25 pairs, ran for 103 seconds and died at its own answer
cap: the model spent the whole budget thinking before the first
verdict, the cut-off text was thrown away, and the page showed nothing
but a ticking clock for two minutes. Three scans of 13 seconds each
came before that. Decisions for this round: the judge measures the
model on a small first request and sizes every later request to a
target duration; the providers stream the answer so the page moves
inside a request and a cut-off answer keeps its verdicts; thinking is
off for the judge unless the operator switches it on; the review
reuses a fresh scan instead of scanning again.

Changes
- config/config.js: DUPLICATES_AI_THINKING (no) and
  DUPLICATES_AI_REQUEST_SECONDS (30).
- schemas.js, OPENAPI/openapi.json: AiReviewProgress gains
  requestPairs, requestAnswers, requestTokens, thinking, batchSize and
  calibrated; the phase list gains warming-up.
- services/duplicateReviewJobService.js: the new progress fields, the
  warming-up phase, and a time estimate from the share of pairs done
  (answers streamed in count), because the batch size may change after
  the warm-up.
- services/aiGenerateOptions.js: reasoningEnabled(options) and
  progressHandler(options), the two switches the judge will send and
  the providers will read, with the GenerateTextProgress shape and the
  partialText rule for cut-off answers.
- scripts/run-tests.js, tests/test-ai-provider-streaming.js: a
  registered placeholder for the provider streaming test.

Testing
- node scripts/run-tests.js --all: 100 registered, 93 pass, 7 skip
  offline, 0 fail.
- eslint and prettier on every touched file; regen without drift.

Impact
Nothing reads the new switches yet; the implementation follows.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* test(helpers): fake OpenAI-compatible and Ollama servers on ephemeral ports

* feat(providers): stream the answer, report progress, keep the cut-off text

Background

A hosted model behind the custom provider spent 103 seconds and the whole
3200-token completion cap on one AI-review request, then threw "the answer hit
a token limit" and dropped every character it had produced. Nothing was visible
while it ran, nothing survived the throw, and the batch was split and paid for
again from the beginning. Two causes: the four provider services always sent a
non-streaming request, so there was nothing to watch; and
assertCompletionNotTruncated() threw before anyone read the content, so the
prefix was thrown away. On top of that the model thinks before it answers, and
on a server that separates thinking from answering the reasoning arrives as
reasoning_content deltas that no provider knew about.

Changes

- services/aiGenerateOptions.js: the shared streaming machinery.
  stripReasoningText() removes <think> blocks, including one a cut-off left
  open. createProgressCollector() assembles a streamed answer, splits reasoning
  from answer incrementally (a marker may be cut across two chunks), counts the
  completion tokens from a usage chunk or estimates them over everything
  produced, reasoning included, and reports at most once per 100 ms plus one
  final report that says done. consumeChatCompletionStream() and
  runChatCompletionStream() are the OpenAI-compatible half: read the stream,
  finish before any throw, and turn a cut-off or a stop into an error that
  carries what arrived. isAbortError()/abortedGenerationError() give a stopped
  request one name across the SDK, axios and fetch.
- services/serviceUtils.js: estimateTokenCount() (the same character-based
  estimate, on a length) and an optional fourth argument on
  assertCompletionNotTruncated() that puts partialText on the error.
- services/openaiService.js, services/customService.js,
  services/azureService.js: generateText() streams when the caller hands in
  onProgress, with stream_options: { include_usage: true } on OpenAI and the
  custom provider and on Azure only from API version 2024-06-01, where the API
  takes it. Without a handler the body is exactly what it was. Both paths strip
  reasoning from the answer and attach the prefix to a truncation error; an
  abort throws an AbortError with partialText.
- services/customService.js: reasoning: false adds
  chat_template_kwargs: { enable_thinking: false } and, for a model name
  matching /qwen/i, that family's soft switch on its own line at the end of the
  user message; reasoning: true sends enable_thinking: true and no soft switch;
  without the option nothing new is sent.
- services/ollamaService.js: generateText() reads NDJSON from an axios
  responseType: 'stream' response, keeps the tail of a socket read until its
  newline arrives, treats the thinking field as thinking, and stops reading the
  moment the signal aborts. reasoning: false/true sends think and overrules
  OLLAMA_THINK; without the option OLLAMA_THINK still decides. The cut-off
  check the analysis path has always run now runs here too, with partialText,
  and a failure no longer erases a token count that was already measured.
- tests/helpers/fake-openai.js, tests/helpers/fake-ollama.js: real HTTP servers
  on ephemeral ports, scripted per request (content chunks, reasoning chunks,
  finish reason, usage chunk or none, per-chunk delay, non-streaming answers
  from the same script), recording every request body and whether the client
  hung up early.
- tests/test-ai-provider-streaming.js replaces its placeholder with 22 cases.

Testing

- node tests/test-ai-provider-streaming.js: 22 passed, 0 failed; run five
  times, no flake.
- node scripts/run-tests.js --all: 93 passed, 7 skipped offline, 0 failed —
  the same numbers as before this change.
- npx eslint and npx prettier --check on every touched file: clean.
- A throwaway process reproduced the reported failure against the fake: the
  progress reports show thinking first with no text, then the answer growing,
  then one done report with the exact token count from the usage chunk, and the
  throw carries the 131 characters of JSON that had arrived.

Impact

No caller behaves differently unless it asks: without onProgress the request
body is byte for byte what it was, and the round-7 provider cases assert that.
What does change for every caller of generateText(): a <think> block no longer
reaches the returned string, a truncation error now carries partialText, an
abort now throws under the name AbortError, and Ollama's generateText() now
raises the same truncation error the analysis path raises instead of returning
a half-written answer. The document analysis path is untouched.

Upstream Status

Not upstream. Streaming, progress reporting, the partial text of a cut-off
answer and the thinking switch do not exist in clusterzx/paperless-ai.

* feat(duplicates): the progress panel moves inside a request and names the measured batch size

Background

A review of a large archive is a handful of long model requests, and the
panel only moved between them. One request took 103 seconds while the page
showed "request 1 of 4 - 0 of 82 pairs" and a ticking clock, so for minutes
at a time the only honest reading of the page was "nothing is happening".
The judge now measures the model on a small first request, sizes every later
one to a configured number of seconds, and streams the answers as they
arrive, which gives the page three things it never had: answers inside a
request, a warm-up phase, and a model that says when it is thinking.

Changes

Page (views/duplicates.ejs, public/js/duplicates.js,
public/css/pages/duplicates.css):

- progressPercent() counts pairs whenever the plan knows them, the answers
  of the running request included, and falls back to requests only while no
  pair count exists. The bar therefore moves during a request instead of
  jumping once per request.
- progressCountsText() gained the "7 of 10 answers" part, printed only while
  a request is in flight and capped at the size of that request.
- progressTimeText() says "measuring the model" in the warm-up and "the
  model is thinking" while the model writes reasoning, instead of a clock
  that cannot move; an estimate the job already made is still shown next to
  either.
- New #dupAiProgressNote line under the counts, written by the new
  progressNoteText(): "4 pairs per request while the model is measured"
  before the measurement, "9 pairs per request, sized from the model's
  answers" after it, empty while no size is known. A zero-width space holds
  its row open for as long as a review runs (.dup-progress--live), so the
  stats tiles below do not jump the moment it fills.
- .dup-progress__fill--thinking pulses while the model reasons, slower than
  the indeterminate band, and is switched off under prefers-reduced-motion.
- The outcome line and the "Model requests" tile both name the batch size the
  review settled on.
- New htmlReviewFailure(): all three AI paths report a failed review with the
  judge's own message plus one link, "Open the Duplicates settings", to
  /settings#duplicates-tab.

Settings (views/settings.ejs, public/js/settings.js, routes/setup.js):

- Two fields close the Duplicates section: the switch "Let the judge think"
  (DUPLICATES_AI_THINKING, default off) and the number "Seconds per model
  request" (DUPLICATES_AI_REQUEST_SECONDS, 5-300, default 30). GET, POST with
  the usual clamping and keep-the-previous-value behaviour, the @swagger
  request body, ENV_EXPORT_GROUPS and the two "Managed by ENV" selectors.

Route:

- GET /api/duplicates/scan passes fresh: true; a scan somebody pressed a
  button for must not be answered from a cache.

OPENAPI/openapi.json regenerated.

Testing

- node scripts/run-tests.js --all: 93 passed, 7 skipped offline, 0 failed
  (unchanged from the baseline of this round).
- duplicates-ui 58 -> 66 cases: the bar with streamed answers and without a
  pair count, the counts line with and without a running request, the three
  wordings of the time line, the note line, the outcome line with a batch
  size, the panel ids and the thinking class, the settings link of the failed
  notice, and the stylesheet's pulse with its reduced-motion rule.
- settings-duplicates-section 11 -> 15 cases: both fields render with their
  values and hints, the POST round trip, clamping (2 -> 5, 999 -> 300), the
  cleared field keeping the previous value, the switch spellings, the export
  group order and the two selectors.
- duplicates-endpoints 30 -> 31 cases: the scan route hands fresh: true to
  the service.
- eslint, prettier and stylelint clean on every touched file; regen-openapi
  leaves no drift.
- Looked at in Chromium against a throwaway server on port 3403 that walks a
  scripted review through the warm-up, a thinking stretch and a request whose
  answers climb 0 -> 10: desktop and phone, light and dark. The stats tiles
  sit at the same offset before and after the note line fills.

Impact

The panel reports inside a request rather than between requests, and names
both the warm-up and the measured batch size, so a review that takes minutes
per request looks like work rather than a hang. A failed review points at the
setting that would have prevented it. Nothing scans, judges or merges on its
own; the two new settings are read at startup like the rest of the section.

Upstream Status

Not applicable - the Duplicates page does not exist upstream.

* feat(duplicates): measure the model, size every request to it, and reuse a fresh scan

Background

Asking the AI about a scan of the user's archive did not work on their
instance. The judge sent 25 pairs with a completion cap of 3200, the hosted
model thought before it answered and spent all 3200 tokens on the thinking,
and 102 seconds later nothing had been judged. The answer was then split into
13 + 12, which buys nothing: the thinking does not get cheaper with fewer
pairs. Meanwhile the page showed "request 1 of 4 · estimating…" for two
minutes, because a request only reports when it is over. The user pressed
Stop.

The same run also scanned the archive three times inside 50 seconds — the
page's scan, the AI proposal's and the review job's — 1359 tags and 13
seconds each, with nothing changing in between.

Changes

services/entityMatchAiService.js

- Thinking off by default. Every judge request carries
  `reasoning: config.duplicatesAiThinking === true`, so a reasoning model
  answers instead of deliberating unless the operator asked for it. Nothing
  else about the prompt changed.
- A warm-up instead of a guess. The first request of a review whose model has
  not been measured asks about at most WARMUP_PAIRS (4) pairs with a
  deliberately generous cap (RESPONSE_TOKENS, the flat estimate or
  WARMUP_MIN_CAP, whichever is largest, bounded by the context window). It is
  announced under the phase `warming-up` with the message "Measuring the model
  with a small first request…", `calibrated: false` and the size it will use;
  the plan reported with it is provisional and the log says so.
- Sizing from the measurement. Every answered request yields tokens per pair
  (thinking included) and tokens per second, each smoothed by half against the
  measurement before it. From them:
  `batchSize = clamp(floor(requestSeconds × tokensPerSecond ÷ tokensPerPair), 1, batchSize())`
  and `cap = ceil(tokensPerPair × batchSize × 1.5) + TOKENS_OVERHEAD`, both
  bounded by the context window as the batch planning bounds them.
  `requestSeconds` is DUPLICATES_AI_REQUEST_SECONDS, at least 5, 30 by
  default. A batch is now taken off the front of a queue rather than chunked
  up front, because its size changes while the review runs.
- The plan settles after the warm-up. `requestsPlanned` and `estimatedTokens`
  are re-derived from the pairs nobody has asked about yet and reported with
  `batchSize` and `calibrated: true`, so the page's denominator stops moving.
- Truncation: raise before halving. A cut-off answer that salvaged nothing is
  asked again with twice the cap (the warm-up gets the whole window at once),
  and only when that bought nothing — or the cap is already at the window's
  bound — is the batch halved as before. A warm-up that does not fit even then
  ends the review as failed with a message the operator can act on, naming
  DUPLICATES_AI_THINKING and TOKEN_LIMIT. A single pair at the bound keeps the
  old "unsure" and its log line.
- The cut-off text counts. All four providers now attach `error.partialText`,
  so the salvage path runs for every one of them; a salvaged request counts
  its verdicts in `pairsJudged` and in the tracker. Two comments that still
  said only Ollama returns half-written answers were rewritten.
- Progress inside a request. With a progress sink the provider is asked to
  stream (`onProgress`). Each report, at most every 250 ms, carries
  `requestPairs`, `requestAnswers` (the complete verdict objects counted off
  the streamed text), `requestTokens`, `thinking` and the running token total:
  "The model is thinking… (640 tokens so far)" while it thinks, otherwise the
  request line with " · 7 of 10 answers" appended. The report that counts the
  request resets all four. A review nobody watches sends the plain request it
  always sent.
- Calibration memory. The last measurement per model name lives on the
  singleton; a review that finds one starts sized from it, skips the warm-up
  and says so in the log. A measurement taken with thinking on is never reused
  with thinking off. `resetCalibration()` for tests.
- Logs: the finish line says "N pair(s) planned" (the number is the plan), the
  batch-size line is marked provisional until the model is measured, and the
  split line says whether the cap was raised or the batch halved.

services/duplicateMergeService.js

- `scan()` keeps its result per set of options (kind, threshold,
  includeDismissed) for SCAN_CACHE_MS (60 s) and answers the next identical
  request from it with one log line instead of the start and finish lines.
  `fresh: true` skips and refills it; the page's Scan button sends it.
- A merge, an undo, a dismissal and `restoreDismissal()` empty the cache. A
  dismissal deleted through the route, which talks to the model directly, is
  caught by a fingerprint (row count and highest id per kind) checked on every
  hit — one local SELECT against a 13-second scan.
- `reviewScan()` calls `scan()` without `fresh`, so a proposal made right
  after the page scanned costs no second scan.

Testing

- node scripts/run-tests.js --all: 93 passed, 7 skipped offline, 0 failed
  (100 registered), unchanged from the baseline.
- tests/test-entity-match-ai-service.js: 65 -> 80 cases. New: thinking off and
  on; the warm-up's size, cap, phase and message; the sizing math on a fixed
  usage and duration; the request seconds and their floor; the context window
  bounding size and cap; smoothing; the plan and estimate recomputed after the
  warm-up; calibration reused, not reused across the thinking switch, reset; a
  warm-up that cannot fit ending the review with its message; a truncated
  answer with partialText salvaged and counted; a streamed request reporting
  thinking, then answers, then clearing itself; an unwatched review not
  streaming; a review served from the page's scan.
- tests/test-duplicate-merge-service.js: 17 -> 22 cases. New: cache hit, other
  options and `fresh` missing it, expiry, invalidation by merge, undo, dismiss
  and restore, and a dismissal removed behind the service.
- Changed expectations, all from the raise-before-halve rule: the truncation
  cases now see every size asked twice (once, once with twice the cap) before
  it is halved, the single pair is asked twice before it ends as unsure, and
  the planning cases see the `warming-up` phase where they saw `judging`.
- Two demo runs against a fake model at 30 tokens/s: thinking off, 12 pairs —
  warm-up 4 pairs in 20 s (600 tokens, 150 per pair), then requests of 5 pairs
  at 25 s, 4500 tokens, 60 s in total. Thinking on — warm-up 4 pairs in 40 s
  (1200 tokens, 300 per pair) and requests of 2 pairs at 30.04 s, the
  configured length.

Impact

The first request of a review is seconds rather than minutes, every later one
lasts about as long as the operator asked, and the page shows the model
thinking and answering while it happens instead of a still bar. A review of a
model that was measured before starts at full size. Three scans of one archive
become one. Nothing runs on its own and no verdict changed: the prompt, the
rules and the shape of an answer are what they were.

Upstream Status

Not applicable — the Duplicates feature does not exist upstream.

* fix(duplicates): a review never asks for a fresh scan of its own

reviewScan() drops a `fresh` flag its caller may carry instead of passing it on, so a route that forwards the page's scan options cannot make the review scan the archive a second time.

* fix(duplicates): the yes/no switches of the judge read 'yes', and a small batch is not starved after a thinking one

Background
The browser smoke test of the round ran the thinking scenario and the
judge kept saying "thinking off" although DUPLICATES_AI_THINKING=yes
was set. config/config.js normalises every yes/no setting to the
strings 'yes' and 'no' (parseEnvBoolean), while three readers in the
judge asked Boolean() or === true: the thinking switch could never be
turned on, and the review and excerpt switches could not be turned off
('no' is a truthy string). The second finding: a thinking model pays a
fixed price per request, so a one-pair request sized by pairs alone
after a four-pair warm-up got a cap the same thoughts did not fit; the
judge recovered by raising the cap, at the cost of one request.

Changes
- services/entityMatchAiService.js: switchedOn() accepts 'yes' and a
  boolean true; isEnabled(), excerptsEnabled() and thinkingEnabled() use
  it. The cap never drops below the largest completion the model has
  produced in this review plus a quarter (CAP_FLOOR_FACTOR), and that
  floor is remembered with the calibration.
- tests/test-entity-match-ai-service.js: one case per finding (82
  cases), the sizing case expects the remembered floor.
- config/changelog.js: three entries for the round under the current
  release.

Testing
- node scripts/run-tests.js --test entity-match-ai-service: 82 passed.
- Browser smoke against a fake Paperless-ngx and a fake provider that
  streams, thinks on request and honours max_tokens: thinking off, the
  fake never thought, warm-up 4 pairs, 59 tokens/s measured; thinking
  on, the panel showed the thinking state, no request hit the token
  limit any more; Stop, re-attach, token budget and the round-6
  walkthrough unchanged.

Impact
DUPLICATES_AI_REVIEW=no and DUPLICATES_AI_EXCERPTS=no now do what they
say; DUPLICATES_AI_THINKING=yes now reaches the model.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): contract for the creation guard, the semantic sweep, unused objects, renames and a remembered calibration

Background
Round 9 of the Duplicates feature, six points the user picked: stop
the drift where it starts (document analysis creating "Rechnungen"
next to "Rechnung"), let the model find synonyms and translations the
string matcher cannot, list and delete unused objects with undo, name
the survivor of a merge, keep the judge's measurement of a model across
restarts, and scan faster. Decisions: only hard matcher tiers map a
new name onto an existing one (case, umlauts, legal form, plural, word
order), typo-like matches are logged …
* feat(duplicates): contract for a targeted AI review

Background
With many groups at 94 to 96 percent the user wants to say "everything
from 95 percent up: ask the AI, show me its view, then merge". The
review must therefore be able to judge only chosen groups and skip the
band of near-misses.

Changes
- schemas.js, OPENAPI/openapi.json: groupIds, minConfidence and
  includeCandidates on DuplicateAiReviewRequest.

Testing
- node scripts/regen-openapi.js: no drift after the commit.

Impact
Request fields only; the implementation follows.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): targeting counters in the AI review result schema

Background
A targeted review reports which groups it judged and which it left
without a verdict; the page shows that.

Changes
- schemas.js, OPENAPI/openapi.json: targeted, groupsJudged and
  groupsSkipped on DuplicateAiReviewResult.aiReview.

Testing
- node scripts/regen-openapi.js: no drift after the commit.

Impact
Documentation of three informational fields.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): let the AI review be pointed at a few groups

Background

An archive with hundreds of correspondents produces dozens of groups at
94, 95 and 96 per cent, and asking the model about all of them costs a
lot to answer a question about a handful. The page needs to select the
groups it is about to merge, ask about those, and keep rendering the
rest of the scan while it does.

Changes

- entityMatchAiService.reviewScan() takes three options that narrow what
  is asked, never what comes back:
  - groupIds: only these scan groups are judged. Every other group is
    still in `groups`, as the scan produced it, with `aiVerdict: null` on
    the group and on every member and `source: 'scan'`. An id this scan
    does not know is ignored and logged once with the count.
  - minConfidence: only groups scoring at least this much are judged;
    together with groupIds both conditions have to hold.
  - includeCandidates (default true): false leaves the band of
    near-misses out entirely, so `candidates` is 0 — and with no band
    the entity list per kind is not read either, which is the cheap part.
- _pairsForKind() takes the set of group ids to judge. A group left out
  contributes no pairs but its member pairs still count as "inside one
  group", so it cannot reappear as a candidate.
- The result reports the targeting: aiReview.targeted, .groupsJudged and
  .groupsSkipped. The start line of the log names it as
  "judging 1 of 4 group(s) (min confidence 0.95, 3 ids), band skipped",
  the closing line adds the two counters. An untargeted review logs and
  behaves exactly as before.
- POST /api/duplicates/ai-review validates and passes the three fields
  through: groupIds an array of at most 500 non-empty strings,
  minConfidence a number in [0.5, 1], includeCandidates a real boolean
  (the string "false" is a 400). An option the request does not mention
  is left out of the service call, so an untargeted request reaches
  reviewScan() with the same object it did before.
- Swagger description of the route and the 400 reason updated,
  OPENAPI/openapi.json regenerated.

Testing

- node scripts/run-tests.js --all -> 90 passed, 7 skipped offline,
  0 failed (97 registered), unchanged against the baseline.
- entity-match-ai-service: 28 -> 34 cases. Six new ones on a fixture
  whose four groups sit exactly on the matcher tiers (1, 0.98, 0.95,
  0.9) plus one pair in the band: groupIds judges only what it names,
  minConfidence filters, includeCandidates: false skips the band and
  reads no second entity list, groupIds and minConfidence combine while
  unknown ids are ignored, an empty selection costs no request, and the
  log lines. The existing aiReview assertion gained the three new fields.
- duplicates-endpoints: 16 -> 19 cases. The three fields reach the
  stubbed reviewScan unchanged, an untargeted request still carries
  nothing extra, ten malformed targeting bodies are 400, and 500 ids are
  accepted while 501 are not.
- Manual run against the real route with a fake store and a fake
  provider: full review 5 pairs / 1 request, minConfidence 0.95 without
  the band 3 pairs, two selected ids (one unknown) 1 pair, and every
  unjudged group back with null verdicts.
- eslint, prettier and the OpenAPI drift check clean on the touched
  files.

Impact

Additive. A review that says nothing about the three options behaves and
logs as before. The page can ask about the groups it selected before a
batch merge; a dozen groups without the band are one or two model
requests instead of the whole archive. schemas.js still has to gain
targeted, groupsJudged and groupsSkipped on DuplicateAiReviewResult.

Upstream Status

Not applicable: the Duplicates feature is next-only.

* feat(duplicates): sort, select by confidence, and a guided review before merging

Background
----------
On a grown archive a scan answers with dozens of groups that all read 94, 95,
96 percent, and the page offered no way to act on that number: every group had
to be judged by eye, one tick at a time. The three presets were the only
thresholds available, so "everything above 95" was not a question the page
could be asked. And where the AI review existed it judged the whole result
list, which is the most expensive way to ask about the five groups the user
actually cares about.

The rule this follows: the AI is an addition, never a condition. Every flow
below works end to end with the review switched off; with it on, the guided
path is one more button beside the one that was already there.

Changes
-------
Results toolbar (#dupResultsBar), above the selection bar, shown once a scan
has groups:
  - "Sort by" (#dupSortSelect): confidence, documents, target name (locale
    compare), kind then confidence. It moves the DOM nodes instead of
    re-rendering, so a card keeps its target, its source ticks, its selection,
    its verdict and its busy state; the two blocks (scan groups, AI
    candidates) are sorted separately and the divider stays between them.
  - "Select >=" (#dupMinConfidence, #dupSelectMinBtn, #dupMinConfidenceCount):
    ticks every selectable group at or above a whole percent and unticks the
    rest, with a live count of what the click would do.
Custom scan threshold: a fourth sensitivity option "Custom" reveals a number
field (#dupThresholdCustom); the scan and both review paths send that percent
divided by 100. The three presets are unchanged.
Confidence breakdown under "Groups found" (#dupStatBuckets): ">=95 %: A .
90-95 %: B . <90 %: C", counted from the cards after a scan and after a review.
Guided flow (#dupReviewThenMergeBtn, rendered only where the review exists):
asks the model about exactly the ticked groups (groupIds, includeCandidates:
false), puts the verdicts on the cards as a full review does, then shows them
once in a wide dialog - one row per group with target, sources, documents, the
verdict chip and the reason, a live "N of M ticked . K documents" foot line and
the copy-rule check. Ticked rows are merged with the batch machinery; an unsure
or different verdict only comes up unticked and never blocks anything, and what
stays unticked stays selected on the page.
"Merge selected" keeps its place and its weight, first in the bar and without a
model anywhere in its path; its dialog names the guided path in one faint line,
and only where that path exists.
Sort, confidence, sensitivity and the custom threshold are remembered in
localStorage (dup.sort, dup.minConfidence, dup.sensitivity,
dup.thresholdCustom) through two try/catch helpers.

Testing
-------
node scripts/run-tests.js --all -> 90 passed, 7 skipped offline, 0 failed
  (unchanged from the branch baseline).
tests/test-duplicates-ui.js: 25 -> 38 cases. New: the toolbar ids and their
  order, the custom threshold field, the stats breakdown, the guided button
  only with the review, the whole page without the review, the toolbar ids in
  the script, sorting as a DOM move, "Select >=", the wrapped localStorage
  access, the guided request (groupIds / includeCandidates: false) and that
  "Merge selected" never touches the review endpoint, the review dialog markup,
  the tip line, the new CSS classes. Changed: the sensitivity options are read
  from #dupSensitivity alone and now end in "custom"; the undo promise and the
  confirm dialogs are counted one higher each, because the review dialog merges
  and therefore makes the same promise.
Reviewed in a browser against a throwaway mock (twelve groups over 88-100 %, a
  review that honours groupIds): 27 screenshots at 1280x900 and 390x844, light
  and dark, 0 px horizontal overflow everywhere, plus a 31-check behaviour
  probe (guided request, verdict ticks, sorting keeping picks and the divider,
  persistence, a refused review, and the whole page with the review off).

Impact
------
Page only. No route, service, schema or config was touched, so the OpenAPI
spec is unchanged. An instance without the AI review renders and behaves
exactly as before plus the toolbar and the custom threshold. The request the
guided path sends uses fields the contract already carries; a server that
ignores them reviews everything, which the page renders correctly.

Upstream Status
---------------
Not applicable - the Duplicates page does not exist upstream.

Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* docs(duplicates): changelog entries for sorting, select by confidence and the guided review

Background
Round 5 answered the second feedback from a real archive: select by a
number, let the model judge exactly those groups, read its verdicts in
one dialog, merge what stays ticked; sort the groups; a custom threshold.

Changes
- config/changelog.js: two entries in the current v2026.09.01 block.

Testing
- node scripts/run-tests.js --test changelog-releases: passed.

Impact
Documentation only.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): contract for evidence-based verdicts and the AI proposal

Background
A real archive produced "Kontoauszug" / "Kontoumzug": the matcher called
it a spelling distance, the prompt allowed "an obvious typo" as a reason
for same, and the model, seeing names and titles only, agreed. Both are
different things. The judge needs stricter rules and, for pairs linked by
spelling alone, a look at what the documents are about, at a bounded
cost.

Changes
- config/config.js: DUPLICATES_AI_EXCERPTS (default yes),
  DUPLICATES_AI_EXCERPT_CHARS (300), DUPLICATES_AI_EXCERPT_DOCUMENTS (2).
- schemas.js, OPENAPI/openapi.json: AiVerdict gains basis and confidence;
  DuplicateAiReviewRequest gains withExcerpts; aiReview reports excerpts.

Testing
- node scripts/run-tests.js --area duplicates: 6/6; regen without drift.

Impact
Settings and schema only; the implementation follows.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): judge model override and the verdict source in the contract

Background
Decisions for round 6: the matcher's hard tiers settle a pair without the
model, unsure pairs are asked once more with excerpts, and the judge may
run on a stronger model of the same provider.

Changes
- config/config.js: DUPLICATES_AI_MODEL (optional, judge only).
- schemas.js, OPENAPI/openapi.json: AiVerdict.source (model or
  spelling-rule); aiReview.escalated and aiReview.spellingRules.

Testing
- eslint and prettier on the two files; regen without drift.

Impact
Settings and schema only; the implementation follows.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(settings): make every DUPLICATES_ setting editable in its own section

Background
The AI review of the Duplicates page arrived with seven environment
variables and no way to change any of them from the interface. Editing a
container environment and recreating the container is the wrong price for
"try a stronger model for the judge" or "ask about fewer pairs per
request", and the settings page is exactly where those knobs belong.
config/config.js already reads all seven; only the front door was missing.

Changes
- views/settings.ejs: a "Duplicates" section (id="sec-duplicates") inside a
  new duplicates-tab block between the AI sections and OCR, with a nav entry
  in the desktop section nav (icon i-merge) and in the mobile one, in the
  same order as the page. Seven fields, each with a hint that says what the
  value does and what its default is: the AI review switch, the judge model,
  pairs per request, the candidate floor, the excerpt switch, excerpt length
  and documents per entry. Switches go through partials/settings-switch, so
  the hidden yes/no input the POST route reads exists as it does everywhere
  else.
- routes/setup.js: GET /settings passes the seven values (env first, the
  defaults of config/config.js as fallback) in the config object the view
  reads; POST /settings destructures the seven camelCase body keys,
  normalises them and writes them into updatedConfig, so setupService
  .saveConfig persists them with the rest. Numbers are clamped to their
  range; a value that is not a number, or a cleared field, keeps what is
  configured now instead of resetting to the default. The swagger body
  schema documents all seven, and the .env export gained a "Duplicates"
  group between "AI behaviour" and "External API".
- public/js/settings.js: the seven selector to env-key entries, so the
  "Overwritten" and "Managed by ENV" marking covers these fields too.
- OPENAPI/openapi.json regenerated.
- tests/test-settings-duplicates-section.js, registered in the
  observability area.

Testing
- node scripts/run-tests.js --all: 98 registered, 91 passed, 7 skipped
  offline (was 97/90/7). The new test covers the rendered section and its
  nav position, the seven inputs and their values, the POST round trip,
  clamping, the keep-the-previous-value case and the .env export group.
- npx eslint / npx prettier --check --ignore-unknown on every touched file.
- node scripts/regen-openapi.js leaves OPENAPI/openapi.json unchanged.
- Looked at the page in Chromium at 1440x1000 and 390x844 against a
  throwaway server outside the repository; no console errors, the section
  reads like the rest of the page and stacks on the phone.

Impact
Operators can change every DUPLICATES_ value from the settings page. The
existing restart-after-save is what makes them take effect; no new
mechanism. Values injected by the container still win and are shown as
managed, as for every other field. Nothing outside the settings page
changes: no route, service or default behaviour of the Duplicates page
itself is touched.

Upstream Status
Fork-only. The Duplicates page does not exist upstream.

Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): judge spelling-only pairs on evidence, not on distance

Background
A real archive produced "Kontoauszug" next to "Kontoumzug": the matcher
called it a spelling distance, the prompt allowed "an obvious typo" as a
reason for same, and the model, seeing two names and three titles, agreed.
Two different things. The judge needed stricter rules, evidence for the
pairs where spelling is the only link, and a way to say how sure it is and
on what grounds — all without opening a large context window on every pair.

Changes
- entityMatchAiService: the system prompt refuses a small spelling distance
  as a reason of its own ("Kontoauszug" / "Kontoumzug", "Miete" / "Mieter",
  "Bahn" / "Bank"), allows a misspelling only when one spelling is not a
  word, and answers unsure when it cannot tell. The output contract gains
  "basis" (a closed list) and "confidence" (high | low); both are parsed,
  an unknown value becomes null, and every verdict, member verdict and
  aggregate carries them. An aggregate keeps the deciding member's basis
  and takes "low" as soon as one deciding member is low.
- Evidence, graded by what the link is worth: every pair carries matched_by
  and score; every judged entity carries its titles, its matching rule and
  its neighbourhood ("filed_with": the correspondents of a tag's documents,
  the tags of a correspondent's); only the pairs linked by fuzzy, prefix or
  token-order also carry document excerpts. Excerpts are read once per
  entity per review and never for a strong tier. withExcerpts: false or
  DUPLICATES_AI_EXCERPTS=no reads nothing at all.
- A member pair a matcher rule settles (exact-normalized, umlaut-variant,
  legal-form) never reaches the provider: it gets verdict same with
  source: spelling-rule, counts in aiReview.spellingRules and costs no
  request, no read and no token.
- A pair the model calls unsure and that had no excerpts is asked once more
  with them; the second answer replaces the first (aiReview.escalated).
- paperlessService: getRecentDocumentExcerptsByEntity (one read,
  truncate_content, cut to the configured characters at a word boundary)
  and getEntityNeighbourhood (one read, the most frequent neighbour names
  through the existing caches). Both answer [] on any error and never log
  document content.
- The judge may run on its own model (DUPLICATES_AI_MODEL): generateText
  takes an optional model in all four provider services, shared through
  aiGenerateOptions.modelOverride.
- Logs: the per-kind start line names the evidence and the model, the
  request line the pairs with excerpts, the escalation its own line.
- Route POST /api/duplicates/ai-review parses withExcerpts like withTitles;
  swagger description updated and OPENAPI/openapi.json regenerated.

Testing
- node scripts/run-tests.js --all: 97 registered, 90 pass, 7 skip offline.
- tests/test-entity-match-ai-service.js: 35 -> 50 cases (the stricter
  prompt, basis and confidence parsing, excerpts only for spelling-only
  pairs and once per entity, the two switches, the configured cut, the
  Kontoauszug regression, settled pairs, the neighbourhood, escalation, the
  model override, batch sizing with excerpts, and both new client methods).
- tests/test-duplicates-endpoints.js: one case for withExcerpts; the three
  existing option assertions now expect withExcerpts: true.
- Demo run against the fake Paperless-ngx: the Kontoauszug/Kontoumzug pair
  costs 282 prompt tokens with excerpts, a strong pair without excerpts 75.
- eslint, prettier and a regen without drift on every file touched.

Impact
An AI review asks about fewer pairs and knows more about the ones it asks
about. Nothing runs on its own, nothing is merged, and document content
never reaches a log line.

Upstream Status
Not applicable — the Duplicates feature does not exist upstream.

* fix(duplicates): do not escalate an unsure pair whose documents carry no text

* feat(duplicates): one click for the AI's proposal, with the evidence behind it

Background
----------
Everything the page offered so far started from the user: scan, read every
card, tick, merge — and where the AI review existed it was a second question
asked after the first. What was missing is the path the archive's owner
actually wants for a first clean-up: one click that scans, has every group and
every near-miss judged, and then hands over a proposal to thin out rather than
a list to work through.

The rule this follows is the same as in the rounds before: the AI is an
addition, never a condition. Without the review nothing of this renders, and
"Scan Paperless-ngx", "Merge selected", the toolbar, the manual merge and the
guided path are the same as they were.

A verdict also had to say more than "same": with `basis`, `confidence` and a
`source` on the wire, the page can pre-tick exactly what is settled — a pair a
spelling rule decided, or one the model says it is sure about — and leave
everything else to the user. The member tables, finally, measured their own
content per card, so the columns of two cards below each other sat in
different places.

Changes
-------
"AI proposal" (#dupAiProposalBtn, primary, rendered only with aiReviewEnabled)
next to "Ask the AI", usable from the first paint because it scans itself:
  - status in the AI row (#dupAiProposalStatus): "Scanning…", then "Asking the
    AI about N pairs and near-misses…", with the hint line under the row
    (#dupAiProposalHint) saying what the click does;
  - it reuses runScan() (now awaited) with the kind, sensitivity and hidden-pair
    settings on the page, then the one review request with includeCandidates
    and no groupIds. Two requests, and no merge until the dialog is confirmed.
Proposal dialog (.dup-proposal-dialog): one row per group that could be merged,
  sorted same/high, same, unsure, different, unjudged (proposalRank,
  compareProposalEntries — both pure); pre-ticked are only the settled ones
  (isSureSame: verdict "same" with confidence "high", which covers the
  spelling-rule verdicts); legend, "Tick all same" (#dupProposalTickSame),
  "Untick all" (#dupProposalUntickAll), the copy-rule check (#dupCopyRuleAll)
  and a live foot line "N of M ticked · K documents · X objects will be
  deleted". Confirming sets the page selection to the ticked groups and hands
  them to the batch runner of round 4, so the selection bar reports the merge
  as it does for "Merge selected"; cancelling leaves the verdicts on the cards
  and nothing ticked.
Evidence, shared by both dialogs (one row renderer, one table):
  - a "Basis" column as a .zr-badge with a label per contract value;
  - the confidence as a suffix of the verdict chip ("AI: same · high");
  - a pair a spelling rule settled reads "Spelling rule" in the "same" tone
    (.dup-verdict--rule) instead of quoting a model that never saw it;
  - the guided dialog pre-ticks by the same rule, so a "same" the model is
    unsure about now comes up unticked there too.
Cards keep their shape: the verdict chip carries the basis in its title and the
  confidence as its suffix, no new column.
Second checkbox "Use document excerpts for spelling-only pairs"
  (#dupAiExcerpts, checked); withTitles and withExcerpts flow into every review
  request from the one place that builds it. The titles checkbox is relabelled
  "Use document titles and neighbours as context".
"AI-judged pairs" tile: its sub line now also counts "· E excerpts", "· S by
  spelling rule" and "· E escalated" when the review reports them.
Member tables line up across cards: .dup-members is table-layout: fixed with
  the name column taking what is left and truncating, and the matching rule a
  fixed share (.dup-members__name, .dup-members__rule).

Testing
-------
node scripts/run-tests.js --all -> 90 passed, 7 skipped offline, 0 failed
  (unchanged from the branch baseline of 97 registered).
tests/test-duplicates-ui.js: 38 -> 48 cases. New: the proposal ids and labels
  only with the review and the page whole without them; what the flow sends
  (runScan first, includeCandidates: true, no groupIds, both evidence flags,
  no request of its own); the pre-tick rule, evaluated as a function against
  seven verdicts; the row order, evaluated by sorting a shuffled list; a label
  for every basis the AiVerdict schema lists, parsed out of schemas.js; the
  spelling-rule chip; the dialog's parts and that it merges through the batch
  runner; the evidence counters of the stats tile; the fixed member-table
  layout; the new CSS classes. Changed: the titles checkbox label, the undo
  promise and the confirm dialogs counted one higher each (the proposal merges
  and therefore makes the same promise), and the pre-tick assertion of the
  guided row.
Reviewed in a browser against a throwaway mock (eleven scan groups plus three
  the model proposes, verdicts across same/high, same/low, unsure and
  different, some settled by a spelling rule, and a Kontoauszug / Kontoumzug
  pair that only the excerpts decide): 31 screenshots at 1280x900 and 390x844,
  light and dark — the controls, the status line mid-flow, the proposal dialog,
  after "Untick all", mid-merge, after the merge, the guided dialog, the stats
  tile, the aligned member tables and the render without the review. 0 px
  horizontal overflow everywhere; the column offsets of all eleven cards are
  identical.

Impact
------
Page only. No route, service, schema or config was touched, so the OpenAPI
spec is unchanged. An instance without the AI review renders and behaves
exactly as before. The new request field and the new verdict fields are ones
the contract already carries: a server that ignores withExcerpts reviews as it
did, and a verdict without basis, confidence or source renders as it did — it
then simply never comes up pre-ticked, which is the safe side.

Upstream Status
---------------
Not applicable - the Duplicates page does not exist upstream.

Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* chore(duplicates): changelog for the AI proposal round, room for the verdict in the Match column

Background
The sixth round of the Duplicates feature adds the AI-led proposal, the
evidence-based judge and the Duplicates settings section. The member
tables now use a fixed column layout so the columns line up across
cards, which left the Match column too narrow for a verdict such as
"AI: same - high": it wrapped into four lines.

Changes
- config/changelog.js: five entries for the round under the current
  release (AI proposal, evidence-based judge with excerpts and
  DUPLICATES_AI_EXCERPT*, DUPLICATES_AI_MODEL, aligned member tables,
  the Duplicates settings section).
- public/css/pages/duplicates.css: the Match column is 132px wide and
  the member verdict does not wrap, so the percentage and the verdict
  take one line each.

Testing
- npx eslint, prettier --check and stylelint on every file changed
  against nightly: clean.
- node scripts/run-tests.js --all: 91 passed, 7 skipped (server or
  credentials needed), 0 failed.
- node scripts/regen-openapi.js: no drift.
- Browser walkthrough against a fake Paperless-ngx and a fake judge:
  scan, merge, undo, dismiss, merge by hand, batch merge, guided review,
  AI proposal and AI review all pass. The Kontoauszug/Kontoumzug pair is
  judged "different" on its excerpts and does not appear in the
  proposal.

Impact
Visual only for the CSS; the changelog is shown in the What's New
dialog.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): contract for a watchable, stoppable AI review

Background
An AI review of a large archive is many model requests in a row. Today
it is one POST that answers when everything is done: nothing shows
while it runs, nothing can stop it, and the tokens it spends are
invisible until the end. The user wants to see what is happening, how
far it is and what it costs, and to stop it at any time. Decisions for
this round: the review runs as a server-side job the page can watch
and stop; a review nobody watches stops itself; a token budget per
review stops it on its own; a stopped review keeps the verdicts it
reached and opens no dialog; the progress lives in the AI row of the
Duplicates page.

Changes
- services/duplicateReviewJobService.js (new): the one review job at
  a time. start(), current(), get(), stop(id, reason), subscribe() for
  a server-sent stream (a late subscriber first gets the job as it is
  now), touch(), wait(), result(), toJSON(). The judge receives a
  control object (signal, onProgress, stop, tokenBudget); a partial
  result of a stopped review is kept like a complete one. The idle
  watch stops a job nobody has watched for the configured seconds. A
  finished job stays reachable for ten minutes.
- config/config.js: DUPLICATES_AI_TOKEN_BUDGET (200000, 0 = no limit)
  and DUPLICATES_AI_IDLE_STOP_SECONDS (60, 0 = never).
- schemas.js, OPENAPI/openapi.json: AiReviewProgress, AiReviewJob,
  AiReviewJobEvent; aiReview gains stopped, stopReason and
  pairsNotJudged.
- scripts/run-tests.js, tests/test-duplicate-review-job.js: the
  contract test of the job (9 cases) in the duplicates area.

Testing
- node scripts/run-tests.js --all: 99 registered, 92 pass, 7 skip
  offline, 0 fail.
- eslint and prettier on every touched file; regen without drift.

Impact
Nothing uses the job yet; the judge ignores the control object until
the implementation follows. No route or page changes.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): make the token budget and the idle stop editable in settings

Background
The two brakes of a running AI review landed as environment variables only:
DUPLICATES_AI_TOKEN_BUDGET caps what one review may spend across all its
requests, DUPLICATES_AI_IDLE_STOP_SECONDS ends a review no page has been
watching, so a closed tab cannot leave the model running. Both are exactly
the kind of setting somebody wants to try out once and then adjust, which
means editing a compose file and restarting the container for every attempt.
The other seven DUPLICATES_* variables already have a field in the Duplicates
section of the settings page; these two did not.

Changes
- views/settings.ejs: two number fields at the end of #sec-duplicates, in the
  style of the five above them — duplicatesAiTokenBudget (0-10000000, step
  1000) and duplicatesAiIdleStopSeconds (0-3600). Each hint says what the
  value does, what zero means and what the default is.
- routes/setup.js: GET /settings passes DUPLICATES_AI_TOKEN_BUDGET and
  DUPLICATES_AI_IDLE_STOP_SECONDS to the view with the defaults of
  config/config.js as the fallback; POST /settings destructures both body
  keys, clamps them to their ranges and keeps the currently configured value
  for an empty or non-numeric field, the rule the round-6 fields follow. Zero
  is a value for both and survives the clamp, because the ranges start there
  rather than at one. The @swagger body schema documents both, and the
  Duplicates group of ENV_EXPORT_GROUPS lists them after the existing keys.
- public/js/settings.js: two entries in the field mapping, so an
  operator-injected value greys the field out and carries the "Managed by ENV"
  pill like every other setting.
- OPENAPI/openapi.json regenerated.

Testing
- tests/test-settings-duplicates-section.js grew from 7 to 11 cases: the two
  fields render with their configured values, ranges and hints and close the
  section in that order; every field of the section is paired with its
  environment key in settings.js; the POST round trip persists all nine
  values; a budget of 99999999 is capped at 10000000 and an idle stop of -5
  lands on 0; zero survives for both, because it means "no limit" and "never"
  rather than an unset field; a fractional value is rounded; a cleared or
  unparsable field keeps what was stored before; the .env export carries all
  nine keys with the two brakes last.
- node scripts/run-tests.js --all: 99 registered, 92 passed, 7 skipped
  offline, 0 failed — the same numbers as before this change.
- eslint and prettier clean on every file touched; regen-openapi.js leaves no
  drift.
- Looked at the section in Chromium at 1440x1000 and 390x844 against a
  throwaway server outside the repository: both fields render like the seven
  above them, no console errors, and with the two keys in the locked-env set
  both are disabled and carry the "Managed by ENV" pill while a neighbouring
  field stays editable.

Impact
No behaviour change for anybody who never opens the section: the defaults are
unchanged (200000 tokens, 60 seconds) and nothing new runs. Operators who set
either variable in their container environment keep winning — the field is
shown greyed out rather than silently overwritten. A saved value needs a
restart to take effect, as the hints say, because config/config.js reads the
environment once at load.

Upstream Status
Not applicable — the Duplicates page is specific to this fork.

* feat(ai): let every provider take an abort signal for one call

aiGenerateOptions gains abortSignal(options); the four provider
services pass it on where their client expects it — the OpenAI SDK as
the second argument of create(body, { signal }) for OpenAI, Azure and
the custom endpoint, axios as { signal } in the request config for
Ollama. Without a signal every provider sends exactly what it sent
before: no second argument at all, and the unchanged axios config.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): the AI review reports, stops and counts its tokens

Background
"Während die AI befragt wird, könnten Millionen von Tokens im
Hintergrund verbraten werden, ohne dass man es sieht. Man muss es auch
abbrechen können." The judge answered when it was done and said
nothing while it worked, so the page had nothing to show and nothing
to stop. The job of the previous round hands it a control object; this
round makes the judge use it. A bar needs a denominator before the
first request, which the old per-kind loop could not give: it read the
archive, asked, and only then looked at the next kind.

Changes
- services/entityMatchAiService.js: reviewScan(options, control = {})
  runs in two passes. Pass one, for every kind of the review: read the
  entities and the band, build the pairs, settle the spelling-rule
  pairs, gather titles, neighbourhood and excerpts, and size the
  batches. Pass two judges kind after kind. Nothing is asked before
  the whole plan exists.
- Progress: phase scanning before the scan, phase evidence per kind
  and per read, one phase judging with requestsPlanned, pairsTotal and
  estimatedTokens for the whole review, one report per answered
  request (requestsDone, pairsJudged, the running token total,
  failedRequests, retries, kind, and the line naming the next
  request), phase escalating when an unsure pair is asked again, phase
  finishing before the groups are built. A split answer adds its
  halves to requestsPlanned in the report of the request that split,
  so the bar never goes backwards; the escalation adds its own
  requests and pairs the same way. Elapsed time and the estimate stay
  with the job, which derives them.
- Stopping: control.signal is read before every read, every request
  and the second round, and travels to the provider, so a stop lands
  on a request in flight. A request that dies on the signal is a stop,
  not a failure: no failed request, no retry, and no "unsure" — the
  pairs stay without a verdict, so they cannot become a group. A
  stopped review returns what it reached; it never throws.
  aiReview now always carries stopped, stopReason (null; the job fills
  it in) and pairsNotJudged.
- Token budget: one running total for the whole review, folded from
  the provider's usage or, for a provider that reports none, from the
  measured prompt plus the estimated answer, so the counter and the
  budget work for every provider (aiReview.tokens keeps reporting only
  what a provider stood behind). When control.tokenBudget is reached
  the review calls control.stop('token-budget') and behaves as
  stopped.
- Logs: "review stopped (user|token-budget|idle): N of M request(s)
  made, P pair(s) not judged, T token(s)." and "token budget 200000
  reached after N request(s) (T tokens)."; the start, request and
  finish lines are unchanged.
- services/duplicateReviewJobService.js: the control object gains
  stopReason(), the one seam the judge needs to name the reason in its
  own log line.
- reviewPairs(pairs, options) additionally takes plan, systemPrompt
  and tracker from reviewScan; a caller that brings none gets what it
  always got.

Testing
- node scripts/run-tests.js --all: 99 registered, 92 pass, 7 skip
  offline, 0 fail (the baseline of the branch).
- tests/test-entity-match-ai-service.js: 13 new cases (64 total) —
  the plan before the first request for one and for two kinds, the
  split and the escalation raising the plan, a failed request still
  moving the bar, a stop between requests and a stop in flight, the
  token budget, a provider without usage, an already aborted signal, a
  review without a control, the report carrying nothing the job
  derives, and the signal reaching all four providers. The one moved
  expectation is the deep-equal on aiReview, which now names the three
  new fields.
- tests/test-duplicate-review-job.js: one case for stopReason().
- A real run through the job service over a fake archive: a review
  that runs through, the same one stopped after request 2, and the
  same one against a token budget.
- eslint and prettier on every touched file.

Impact
The page can show a bar with a denominator, an estimate and a running
token count from the first request, and a stop costs at most one
request that is already in flight. A review without a control object
behaves exactly as before, so the synchronous route is untouched until
it is moved onto the job.

Upstream Status
Not applicable: the Duplicates page and its AI review do not exist
upstream.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): watch and stop the AI review from the page

Background

A review of a drifted archive is many model requests in a row. Until now
"Ask the AI" was one POST that answered when everything was over: a spinner,
no idea how many requests were still coming, no idea what it cost, and no way
out but reloading the tab — which left the model running. The job service of
the contract commit made the review watchable and stoppable on the server;
this wires the routes and the page onto it.

Changes

routes/setup.js (Duplicates block only)
- parseAiReviewRequest(body) holds the validation both entry points share, so
  the synchronous route and the job route can no longer drift apart.
- POST /api/duplicates/ai-review/jobs starts a review and answers
  202 { job }; while one runs it answers 409 with that running job, so a
  second tab attaches instead of failing.
- GET /api/duplicates/ai-review/jobs/current answers { job } or { job: null }
  and counts as watching the review.
- GET /api/duplicates/ai-review/jobs/:id answers { job, result }, 404 for an
  unknown id, and also counts as watching.
- GET /api/duplicates/ai-review/jobs/:id/events streams AiReviewJobEvents
  (text/event-stream, no-cache, X-Accel-Buffering: no, keep-alive, flush after
  every write), a ": keep-alive" comment every 15 s, and ends after done,
  stopped or failed. An unknown id is a JSON 404 before any stream header.
- POST /api/duplicates/ai-review/jobs/:id/stop answers { job }; stopping a
  finished review is a 200 no-op.
- POST /api/duplicates/ai-review now starts that same job and waits for it: a
  stopped review answers 200 with the verdicts it reached, a failed one keeps
  the judge's status, and a second request while one runs is a 409. It
  subscribes for the duration so the idle stop cannot end a review somebody is
  waiting for.
- @swagger for every new route; OPENAPI/openapi.json regenerated.

views/duplicates.ejs, public/js/duplicates.js, public/css/pages/duplicates.css
- A progress panel in the AI row (#dupAiProgress): bar (#dupAiProgressFill,
  indeterminate while the plan is unknown), message, counters
  ("Request 3 of 8 · 40 of 96 pairs · 12.4k of 200k tokens"), time
  ("about 40 s left · 1:24 elapsed") and a Stop button (#dupAiStopBtn). After
  the end it keeps one outcome line and hides on the next scan or review.
- askForVerdicts() starts the job, follows it through EventSource and falls
  back to polling the job every 2 s when the stream breaks. It resolves
  { aiReview, stopped }; all three AI paths honour `stopped` — the notice is
  shown and neither the guided dialog nor the proposal opens.
- On load the page asks for the current job and re-attaches to one that is
  still running; a finished one is left alone.
- Pure helpers formatTokens, formatEta, formatElapsed, progressPercent and
  stopNotice word the numbers; the UI test evaluates them directly.

Testing

- node scripts/run-tests.js --all: 99 registered, 92 pass, 7 skip offline
  (unchanged); duplicates-endpoints 20 -> 30 cases, duplicates-ui 48 -> 57.
- eslint, prettier, stylelint clean on every touched file; regen-openapi
  leaves no diff.
- Reviewed in a browser against a throwaway server with a judge that reports
  eight requests: mid-run, stopping, stopped and done, desktop and phone,
  light and dark, no console errors. A page loaded while a review runs
  re-attached and rendered its result; with the event stream blocked the same
  review came home through eight polls.

Impact

The Duplicates page shows what a review is doing and costing and can end it;
the verdicts already reached are kept. The synchronous route keeps its request
and response, so an API client sees no change beyond the new 409 while a
review runs.

Upstream Status

Not applicable — the Duplicates feature does not exist upstream.

* fix(duplicates): a late Stop answer no longer paints over the outcome; changelog for the review job

Background
In the browser smoke test of the round, a stop pressed after the first
answered request ended the job before the stop request itself answered.
The page then rendered that answer, a snapshot from the stopping moment,
over the outcome line and restarted the elapsed clock, so the panel read
"Stopping after the current request…" next to a finished review.

Changes
- public/js/duplicates.js: stopReview() renders the stop answer only
  while the same job is still followed and still live.
- tests/test-duplicates-ui.js: one case that pins the guard (57 -> 58).
- config/changelog.js: three entries for the round under the current
  release (the review as a job with progress and Stop, the token budget
  and the idle stop as settings, the plan before the first request).

Testing
- node scripts/run-tests.js --test duplicates-ui: 58 passed.
- Browser smoke against a fake Paperless-ngx and a slowed-down fake
  provider: Stop during request 2 leaves "Stopped after 1 of 5 requests
  · 1 of 5 pairs judged · 1.1k tokens" on the panel, the verdicts
  reached stay on the cards, no dialog opens; the proposal path stops
  the same way; a token budget of 2500 stops the review after 3
  requests with the budget named in the notice and the log; a page
  reloaded during a review re-attaches and renders the result; the
  round-6 walkthrough (scan, merge, undo, dismiss, merge by hand, batch,
  guided review, proposal, plain review) passes unchanged.
- eslint and prettier on the touched files.

Impact
Visual only; the review itself was stopped correctly before the fix.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): contract for a judge that measures the model, streams its answers and thinks only on request

Background
On a real archive with a hosted Qwen model the first review request
asked about 25 pairs, ran for 103 seconds and died at its own answer
cap: the model spent the whole budget thinking before the first
verdict, the cut-off text was thrown away, and the page showed nothing
but a ticking clock for two minutes. Three scans of 13 seconds each
came before that. Decisions for this round: the judge measures the
model on a small first request and sizes every later request to a
target duration; the providers stream the answer so the page moves
inside a request and a cut-off answer keeps its verdicts; thinking is
off for the judge unless the operator switches it on; the review
reuses a fresh scan instead of scanning again.

Changes
- config/config.js: DUPLICATES_AI_THINKING (no) and
  DUPLICATES_AI_REQUEST_SECONDS (30).
- schemas.js, OPENAPI/openapi.json: AiReviewProgress gains
  requestPairs, requestAnswers, requestTokens, thinking, batchSize and
  calibrated; the phase list gains warming-up.
- services/duplicateReviewJobService.js: the new progress fields, the
  warming-up phase, and a time estimate from the share of pairs done
  (answers streamed in count), because the batch size may change after
  the warm-up.
- services/aiGenerateOptions.js: reasoningEnabled(options) and
  progressHandler(options), the two switches the judge will send and
  the providers will read, with the GenerateTextProgress shape and the
  partialText rule for cut-off answers.
- scripts/run-tests.js, tests/test-ai-provider-streaming.js: a
  registered placeholder for the provider streaming test.

Testing
- node scripts/run-tests.js --all: 100 registered, 93 pass, 7 skip
  offline, 0 fail.
- eslint and prettier on every touched file; regen without drift.

Impact
Nothing reads the new switches yet; the implementation follows.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* test(helpers): fake OpenAI-compatible and Ollama servers on ephemeral ports

* feat(providers): stream the answer, report progress, keep the cut-off text

Background

A hosted model behind the custom provider spent 103 seconds and the whole
3200-token completion cap on one AI-review request, then threw "the answer hit
a token limit" and dropped every character it had produced. Nothing was visible
while it ran, nothing survived the throw, and the batch was split and paid for
again from the beginning. Two causes: the four provider services always sent a
non-streaming request, so there was nothing to watch; and
assertCompletionNotTruncated() threw before anyone read the content, so the
prefix was thrown away. On top of that the model thinks before it answers, and
on a server that separates thinking from answering the reasoning arrives as
reasoning_content deltas that no provider knew about.

Changes

- services/aiGenerateOptions.js: the shared streaming machinery.
  stripReasoningText() removes <think> blocks, including one a cut-off left
  open. createProgressCollector() assembles a streamed answer, splits reasoning
  from answer incrementally (a marker may be cut across two chunks), counts the
  completion tokens from a usage chunk or estimates them over everything
  produced, reasoning included, and reports at most once per 100 ms plus one
  final report that says done. consumeChatCompletionStream() and
  runChatCompletionStream() are the OpenAI-compatible half: read the stream,
  finish before any throw, and turn a cut-off or a stop into an error that
  carries what arrived. isAbortError()/abortedGenerationError() give a stopped
  request one name across the SDK, axios and fetch.
- services/serviceUtils.js: estimateTokenCount() (the same character-based
  estimate, on a length) and an optional fourth argument on
  assertCompletionNotTruncated() that puts partialText on the error.
- services/openaiService.js, services/customService.js,
  services/azureService.js: generateText() streams when the caller hands in
  onProgress, with stream_options: { include_usage: true } on OpenAI and the
  custom provider and on Azure only from API version 2024-06-01, where the API
  takes it. Without a handler the body is exactly what it was. Both paths strip
  reasoning from the answer and attach the prefix to a truncation error; an
  abort throws an AbortError with partialText.
- services/customService.js: reasoning: false adds
  chat_template_kwargs: { enable_thinking: false } and, for a model name
  matching /qwen/i, that family's soft switch on its own line at the end of the
  user message; reasoning: true sends enable_thinking: true and no soft switch;
  without the option nothing new is sent.
- services/ollamaService.js: generateText() reads NDJSON from an axios
  responseType: 'stream' response, keeps the tail of a socket read until its
  newline arrives, treats the thinking field as thinking, and stops reading the
  moment the signal aborts. reasoning: false/true sends think and overrules
  OLLAMA_THINK; without the option OLLAMA_THINK still decides. The cut-off
  check the analysis path has always run now runs here too, with partialText,
  and a failure no longer erases a token count that was already measured.
- tests/helpers/fake-openai.js, tests/helpers/fake-ollama.js: real HTTP servers
  on ephemeral ports, scripted per request (content chunks, reasoning chunks,
  finish reason, usage chunk or none, per-chunk delay, non-streaming answers
  from the same script), recording every request body and whether the client
  hung up early.
- tests/test-ai-provider-streaming.js replaces its placeholder with 22 cases.

Testing

- node tests/test-ai-provider-streaming.js: 22 passed, 0 failed; run five
  times, no flake.
- node scripts/run-tests.js --all: 93 passed, 7 skipped offline, 0 failed —
  the same numbers as before this change.
- npx eslint and npx prettier --check on every touched file: clean.
- A throwaway process reproduced the reported failure against the fake: the
  progress reports show thinking first with no text, then the answer growing,
  then one done report with the exact token count from the usage chunk, and the
  throw carries the 131 characters of JSON that had arrived.

Impact

No caller behaves differently unless it asks: without onProgress the request
body is byte for byte what it was, and the round-7 provider cases assert that.
What does change for every caller of generateText(): a <think> block no longer
reaches the returned string, a truncation error now carries partialText, an
abort now throws under the name AbortError, and Ollama's generateText() now
raises the same truncation error the analysis path raises instead of returning
a half-written answer. The document analysis path is untouched.

Upstream Status

Not upstream. Streaming, progress reporting, the partial text of a cut-off
answer and the thinking switch do not exist in clusterzx/paperless-ai.

* feat(duplicates): the progress panel moves inside a request and names the measured batch size

Background

A review of a large archive is a handful of long model requests, and the
panel only moved between them. One request took 103 seconds while the page
showed "request 1 of 4 - 0 of 82 pairs" and a ticking clock, so for minutes
at a time the only honest reading of the page was "nothing is happening".
The judge now measures the model on a small first request, sizes every later
one to a configured number of seconds, and streams the answers as they
arrive, which gives the page three things it never had: answers inside a
request, a warm-up phase, and a model that says when it is thinking.

Changes

Page (views/duplicates.ejs, public/js/duplicates.js,
public/css/pages/duplicates.css):

- progressPercent() counts pairs whenever the plan knows them, the answers
  of the running request included, and falls back to requests only while no
  pair count exists. The bar therefore moves during a request instead of
  jumping once per request.
- progressCountsText() gained the "7 of 10 answers" part, printed only while
  a request is in flight and capped at the size of that request.
- progressTimeText() says "measuring the model" in the warm-up and "the
  model is thinking" while the model writes reasoning, instead of a clock
  that cannot move; an estimate the job already made is still shown next to
  either.
- New #dupAiProgressNote line under the counts, written by the new
  progressNoteText(): "4 pairs per request while the model is measured"
  before the measurement, "9 pairs per request, sized from the model's
  answers" after it, empty while no size is known. A zero-width space holds
  its row open for as long as a review runs (.dup-progress--live), so the
  stats tiles below do not jump the moment it fills.
- .dup-progress__fill--thinking pulses while the model reasons, slower than
  the indeterminate band, and is switched off under prefers-reduced-motion.
- The outcome line and the "Model requests" tile both name the batch size the
  review settled on.
- New htmlReviewFailure(): all three AI paths report a failed review with the
  judge's own message plus one link, "Open the Duplicates settings", to
  /settings#duplicates-tab.

Settings (views/settings.ejs, public/js/settings.js, routes/setup.js):

- Two fields close the Duplicates section: the switch "Let the judge think"
  (DUPLICATES_AI_THINKING, default off) and the number "Seconds per model
  request" (DUPLICATES_AI_REQUEST_SECONDS, 5-300, default 30). GET, POST with
  the usual clamping and keep-the-previous-value behaviour, the @swagger
  request body, ENV_EXPORT_GROUPS and the two "Managed by ENV" selectors.

Route:

- GET /api/duplicates/scan passes fresh: true; a scan somebody pressed a
  button for must not be answered from a cache.

OPENAPI/openapi.json regenerated.

Testing

- node scripts/run-tests.js --all: 93 passed, 7 skipped offline, 0 failed
  (unchanged from the baseline of this round).
- duplicates-ui 58 -> 66 cases: the bar with streamed answers and without a
  pair count, the counts line with and without a running request, the three
  wordings of the time line, the note line, the outcome line with a batch
  size, the panel ids and the thinking class, the settings link of the failed
  notice, and the stylesheet's pulse with its reduced-motion rule.
- settings-duplicates-section 11 -> 15 cases: both fields render with their
  values and hints, the POST round trip, clamping (2 -> 5, 999 -> 300), the
  cleared field keeping the previous value, the switch spellings, the export
  group order and the two selectors.
- duplicates-endpoints 30 -> 31 cases: the scan route hands fresh: true to
  the service.
- eslint, prettier and stylelint clean on every touched file; regen-openapi
  leaves no drift.
- Looked at in Chromium against a throwaway server on port 3403 that walks a
  scripted review through the warm-up, a thinking stretch and a request whose
  answers climb 0 -> 10: desktop and phone, light and dark. The stats tiles
  sit at the same offset before and after the note line fills.

Impact

The panel reports inside a request rather than between requests, and names
both the warm-up and the measured batch size, so a review that takes minutes
per request looks like work rather than a hang. A failed review points at the
setting that would have prevented it. Nothing scans, judges or merges on its
own; the two new settings are read at startup like the rest of the section.

Upstream Status

Not applicable - the Duplicates page does not exist upstream.

* feat(duplicates): measure the model, size every request to it, and reuse a fresh scan

Background

Asking the AI about a scan of the user's archive did not work on their
instance. The judge sent 25 pairs with a completion cap of 3200, the hosted
model thought before it answered and spent all 3200 tokens on the thinking,
and 102 seconds later nothing had been judged. The answer was then split into
13 + 12, which buys nothing: the thinking does not get cheaper with fewer
pairs. Meanwhile the page showed "request 1 of 4 · estimating…" for two
minutes, because a request only reports when it is over. The user pressed
Stop.

The same run also scanned the archive three times inside 50 seconds — the
page's scan, the AI proposal's and the review job's — 1359 tags and 13
seconds each, with nothing changing in between.

Changes

services/entityMatchAiService.js

- Thinking off by default. Every judge request carries
  `reasoning: config.duplicatesAiThinking === true`, so a reasoning model
  answers instead of deliberating unless the operator asked for it. Nothing
  else about the prompt changed.
- A warm-up instead of a guess. The first request of a review whose model has
  not been measured asks about at most WARMUP_PAIRS (4) pairs with a
  deliberately generous cap (RESPONSE_TOKENS, the flat estimate or
  WARMUP_MIN_CAP, whichever is largest, bounded by the context window). It is
  announced under the phase `warming-up` with the message "Measuring the model
  with a small first request…", `calibrated: false` and the size it will use;
  the plan reported with it is provisional and the log says so.
- Sizing from the measurement. Every answered request yields tokens per pair
  (thinking included) and tokens per second, each smoothed by half against the
  measurement before it. From them:
  `batchSize = clamp(floor(requestSeconds × tokensPerSecond ÷ tokensPerPair), 1, batchSize())`
  and `cap = ceil(tokensPerPair × batchSize × 1.5) + TOKENS_OVERHEAD`, both
  bounded by the context window as the batch planning bounds them.
  `requestSeconds` is DUPLICATES_AI_REQUEST_SECONDS, at least 5, 30 by
  default. A batch is now taken off the front of a queue rather than chunked
  up front, because its size changes while the review runs.
- The plan settles after the warm-up. `requestsPlanned` and `estimatedTokens`
  are re-derived from the pairs nobody has asked about yet and reported with
  `batchSize` and `calibrated: true`, so the page's denominator stops moving.
- Truncation: raise before halving. A cut-off answer that salvaged nothing is
  asked again with twice the cap (the warm-up gets the whole window at once),
  and only when that bought nothing — or the cap is already at the window's
  bound — is the batch halved as before. A warm-up that does not fit even then
  ends the review as failed with a message the operator can act on, naming
  DUPLICATES_AI_THINKING and TOKEN_LIMIT. A single pair at the bound keeps the
  old "unsure" and its log line.
- The cut-off text counts. All four providers now attach `error.partialText`,
  so the salvage path runs for every one of them; a salvaged request counts
  its verdicts in `pairsJudged` and in the tracker. Two comments that still
  said only Ollama returns half-written answers were rewritten.
- Progress inside a request. With a progress sink the provider is asked to
  stream (`onProgress`). Each report, at most every 250 ms, carries
  `requestPairs`, `requestAnswers` (the complete verdict objects counted off
  the streamed text), `requestTokens`, `thinking` and the running token total:
  "The model is thinking… (640 tokens so far)" while it thinks, otherwise the
  request line with " · 7 of 10 answers" appended. The report that counts the
  request resets all four. A review nobody watches sends the plain request it
  always sent.
- Calibration memory. The last measurement per model name lives on the
  singleton; a review that finds one starts sized from it, skips the warm-up
  and says so in the log. A measurement taken with thinking on is never reused
  with thinking off. `resetCalibration()` for tests.
- Logs: the finish line says "N pair(s) planned" (the number is the plan), the
  batch-size line is marked provisional until the model is measured, and the
  split line says whether the cap was raised or the batch halved.

services/duplicateMergeService.js

- `scan()` keeps its result per set of options (kind, threshold,
  includeDismissed) for SCAN_CACHE_MS (60 s) and answers the next identical
  request from it with one log line instead of the start and finish lines.
  `fresh: true` skips and refills it; the page's Scan button sends it.
- A merge, an undo, a dismissal and `restoreDismissal()` empty the cache. A
  dismissal deleted through the route, which talks to the model directly, is
  caught by a fingerprint (row count and highest id per kind) checked on every
  hit — one local SELECT against a 13-second scan.
- `reviewScan()` calls `scan()` without `fresh`, so a proposal made right
  after the page scanned costs no second scan.

Testing

- node scripts/run-tests.js --all: 93 passed, 7 skipped offline, 0 failed
  (100 registered), unchanged from the baseline.
- tests/test-entity-match-ai-service.js: 65 -> 80 cases. New: thinking off and
  on; the warm-up's size, cap, phase and message; the sizing math on a fixed
  usage and duration; the request seconds and their floor; the context window
  bounding size and cap; smoothing; the plan and estimate recomputed after the
  warm-up; calibration reused, not reused across the thinking switch, reset; a
  warm-up that cannot fit ending the review with its message; a truncated
  answer with partialText salvaged and counted; a streamed request reporting
  thinking, then answers, then clearing itself; an unwatched review not
  streaming; a review served from the page's scan.
- tests/test-duplicate-merge-service.js: 17 -> 22 cases. New: cache hit, other
  options and `fresh` missing it, expiry, invalidation by merge, undo, dismiss
  and restore, and a dismissal removed behind the service.
- Changed expectations, all from the raise-before-halve rule: the truncation
  cases now see every size asked twice (once, once with twice the cap) before
  it is halved, the single pair is asked twice before it ends as unsure, and
  the planning cases see the `warming-up` phase where they saw `judging`.
- Two demo runs against a fake model at 30 tokens/s: thinking off, 12 pairs —
  warm-up 4 pairs in 20 s (600 tokens, 150 per pair), then requests of 5 pairs
  at 25 s, 4500 tokens, 60 s in total. Thinking on — warm-up 4 pairs in 40 s
  (1200 tokens, 300 per pair) and requests of 2 pairs at 30.04 s, the
  configured length.

Impact

The first request of a review is seconds rather than minutes, every later one
lasts about as long as the operator asked, and the page shows the model
thinking and answering while it happens instead of a still bar. A review of a
model that was measured before starts at full size. Three scans of one archive
become one. Nothing runs on its own and no verdict changed: the prompt, the
rules and the shape of an answer are what they were.

Upstream Status

Not applicable — the Duplicates feature does not exist upstream.

* fix(duplicates): a review never asks for a fresh scan of its own

reviewScan() drops a `fresh` flag its caller may carry instead of passing it on, so a route that forwards the page's scan options cannot make the review scan the archive a second time.

* fix(duplicates): the yes/no switches of the judge read 'yes', and a small batch is not starved after a thinking one

Background
The browser smoke test of the round ran the thinking scenario and the
judge kept saying "thinking off" although DUPLICATES_AI_THINKING=yes
was set. config/config.js normalises every yes/no setting to the
strings 'yes' and 'no' (parseEnvBoolean), while three readers in the
judge asked Boolean() or === true: the thinking switch could never be
turned on, and the review and excerpt switches could not be turned off
('no' is a truthy string). The second finding: a thinking model pays a
fixed price per request, so a one-pair request sized by pairs alone
after a four-pair warm-up got a cap the same thoughts did not fit; the
judge recovered by raising the cap, at the cost of one request.

Changes
- services/entityMatchAiService.js: switchedOn() accepts 'yes' and a
  boolean true; isEnabled(), excerptsEnabled() and thinkingEnabled() use
  it. The cap never drops below the largest completion the model has
  produced in this review plus a quarter (CAP_FLOOR_FACTOR), and that
  floor is remembered with the calibration.
- tests/test-entity-match-ai-service.js: one case per finding (82
  cases), the sizing case expects the remembered floor.
- config/changelog.js: three entries for the round under the current
  release.

Testing
- node scripts/run-tests.js --test entity-match-ai-service: 82 passed.
- Browser smoke against a fake Paperless-ngx and a fake provider that
  streams, thinks on request and honours max_tokens: thinking off, the
  fake never thought, warm-up 4 pairs, 59 tokens/s measured; thinking
  on, the panel showed the thinking state, no request hit the token
  limit any more; Stop, re-attach, token budget and the round-6
  walkthrough unchanged.

Impact
DUPLICATES_AI_REVIEW=no and DUPLICATES_AI_EXCERPTS=no now do what they
say; DUPLICATES_AI_THINKING=yes now reaches the model.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): contract for the creation guard, the semantic sweep, unused objects, renames and a remembered calibration

Background
Round 9 of the Duplicates feature, six points the user picked: stop
the drift where it starts (document analysis creating "Rechnungen"
next to "Rechnung"), let the model find synonyms and translations the
string matcher cannot, list and delete unused objects with undo, name
the survivor of a merge, keep the judge's measurement of a model across
restarts, and scan faster. Decisions: only hard matcher tiers map a
new name onto an existing one (case, umlauts, legal form, plural, word
order), typo-like matches are logged and still created; every mapping
is recor…
…e; the order applies in lanes (#341)

* feat(duplicates): contract for a targeted AI review

Background
With many groups at 94 to 96 percent the user wants to say "everything
from 95 percent up: ask the AI, show me its view, then merge". The
review must therefore be able to judge only chosen groups and skip the
band of near-misses.

Changes
- schemas.js, OPENAPI/openapi.json: groupIds, minConfidence and
  includeCandidates on DuplicateAiReviewRequest.

Testing
- node scripts/regen-openapi.js: no drift after the commit.

Impact
Request fields only; the implementation follows.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): targeting counters in the AI review result schema

Background
A targeted review reports which groups it judged and which it left
without a verdict; the page shows that.

Changes
- schemas.js, OPENAPI/openapi.json: targeted, groupsJudged and
  groupsSkipped on DuplicateAiReviewResult.aiReview.

Testing
- node scripts/regen-openapi.js: no drift after the commit.

Impact
Documentation of three informational fields.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): let the AI review be pointed at a few groups

Background

An archive with hundreds of correspondents produces dozens of groups at
94, 95 and 96 per cent, and asking the model about all of them costs a
lot to answer a question about a handful. The page needs to select the
groups it is about to merge, ask about those, and keep rendering the
rest of the scan while it does.

Changes

- entityMatchAiService.reviewScan() takes three options that narrow what
  is asked, never what comes back:
  - groupIds: only these scan groups are judged. Every other group is
    still in `groups`, as the scan produced it, with `aiVerdict: null` on
    the group and on every member and `source: 'scan'`. An id this scan
    does not know is ignored and logged once with the count.
  - minConfidence: only groups scoring at least this much are judged;
    together with groupIds both conditions have to hold.
  - includeCandidates (default true): false leaves the band of
    near-misses out entirely, so `candidates` is 0 — and with no band
    the entity list per kind is not read either, which is the cheap part.
- _pairsForKind() takes the set of group ids to judge. A group left out
  contributes no pairs but its member pairs still count as "inside one
  group", so it cannot reappear as a candidate.
- The result reports the targeting: aiReview.targeted, .groupsJudged and
  .groupsSkipped. The start line of the log names it as
  "judging 1 of 4 group(s) (min confidence 0.95, 3 ids), band skipped",
  the closing line adds the two counters. An untargeted review logs and
  behaves exactly as before.
- POST /api/duplicates/ai-review validates and passes the three fields
  through: groupIds an array of at most 500 non-empty strings,
  minConfidence a number in [0.5, 1], includeCandidates a real boolean
  (the string "false" is a 400). An option the request does not mention
  is left out of the service call, so an untargeted request reaches
  reviewScan() with the same object it did before.
- Swagger description of the route and the 400 reason updated,
  OPENAPI/openapi.json regenerated.

Testing

- node scripts/run-tests.js --all -> 90 passed, 7 skipped offline,
  0 failed (97 registered), unchanged against the baseline.
- entity-match-ai-service: 28 -> 34 cases. Six new ones on a fixture
  whose four groups sit exactly on the matcher tiers (1, 0.98, 0.95,
  0.9) plus one pair in the band: groupIds judges only what it names,
  minConfidence filters, includeCandidates: false skips the band and
  reads no second entity list, groupIds and minConfidence combine while
  unknown ids are ignored, an empty selection costs no request, and the
  log lines. The existing aiReview assertion gained the three new fields.
- duplicates-endpoints: 16 -> 19 cases. The three fields reach the
  stubbed reviewScan unchanged, an untargeted request still carries
  nothing extra, ten malformed targeting bodies are 400, and 500 ids are
  accepted while 501 are not.
- Manual run against the real route with a fake store and a fake
  provider: full review 5 pairs / 1 request, minConfidence 0.95 without
  the band 3 pairs, two selected ids (one unknown) 1 pair, and every
  unjudged group back with null verdicts.
- eslint, prettier and the OpenAPI drift check clean on the touched
  files.

Impact

Additive. A review that says nothing about the three options behaves and
logs as before. The page can ask about the groups it selected before a
batch merge; a dozen groups without the band are one or two model
requests instead of the whole archive. schemas.js still has to gain
targeted, groupsJudged and groupsSkipped on DuplicateAiReviewResult.

Upstream Status

Not applicable: the Duplicates feature is next-only.

* feat(duplicates): sort, select by confidence, and a guided review before merging

Background
----------
On a grown archive a scan answers with dozens of groups that all read 94, 95,
96 percent, and the page offered no way to act on that number: every group had
to be judged by eye, one tick at a time. The three presets were the only
thresholds available, so "everything above 95" was not a question the page
could be asked. And where the AI review existed it judged the whole result
list, which is the most expensive way to ask about the five groups the user
actually cares about.

The rule this follows: the AI is an addition, never a condition. Every flow
below works end to end with the review switched off; with it on, the guided
path is one more button beside the one that was already there.

Changes
-------
Results toolbar (#dupResultsBar), above the selection bar, shown once a scan
has groups:
  - "Sort by" (#dupSortSelect): confidence, documents, target name (locale
    compare), kind then confidence. It moves the DOM nodes instead of
    re-rendering, so a card keeps its target, its source ticks, its selection,
    its verdict and its busy state; the two blocks (scan groups, AI
    candidates) are sorted separately and the divider stays between them.
  - "Select >=" (#dupMinConfidence, #dupSelectMinBtn, #dupMinConfidenceCount):
    ticks every selectable group at or above a whole percent and unticks the
    rest, with a live count of what the click would do.
Custom scan threshold: a fourth sensitivity option "Custom" reveals a number
field (#dupThresholdCustom); the scan and both review paths send that percent
divided by 100. The three presets are unchanged.
Confidence breakdown under "Groups found" (#dupStatBuckets): ">=95 %: A .
90-95 %: B . <90 %: C", counted from the cards after a scan and after a review.
Guided flow (#dupReviewThenMergeBtn, rendered only where the review exists):
asks the model about exactly the ticked groups (groupIds, includeCandidates:
false), puts the verdicts on the cards as a full review does, then shows them
once in a wide dialog - one row per group with target, sources, documents, the
verdict chip and the reason, a live "N of M ticked . K documents" foot line and
the copy-rule check. Ticked rows are merged with the batch machinery; an unsure
or different verdict only comes up unticked and never blocks anything, and what
stays unticked stays selected on the page.
"Merge selected" keeps its place and its weight, first in the bar and without a
model anywhere in its path; its dialog names the guided path in one faint line,
and only where that path exists.
Sort, confidence, sensitivity and the custom threshold are remembered in
localStorage (dup.sort, dup.minConfidence, dup.sensitivity,
dup.thresholdCustom) through two try/catch helpers.

Testing
-------
node scripts/run-tests.js --all -> 90 passed, 7 skipped offline, 0 failed
  (unchanged from the branch baseline).
tests/test-duplicates-ui.js: 25 -> 38 cases. New: the toolbar ids and their
  order, the custom threshold field, the stats breakdown, the guided button
  only with the review, the whole page without the review, the toolbar ids in
  the script, sorting as a DOM move, "Select >=", the wrapped localStorage
  access, the guided request (groupIds / includeCandidates: false) and that
  "Merge selected" never touches the review endpoint, the review dialog markup,
  the tip line, the new CSS classes. Changed: the sensitivity options are read
  from #dupSensitivity alone and now end in "custom"; the undo promise and the
  confirm dialogs are counted one higher each, because the review dialog merges
  and therefore makes the same promise.
Reviewed in a browser against a throwaway mock (twelve groups over 88-100 %, a
  review that honours groupIds): 27 screenshots at 1280x900 and 390x844, light
  and dark, 0 px horizontal overflow everywhere, plus a 31-check behaviour
  probe (guided request, verdict ticks, sorting keeping picks and the divider,
  persistence, a refused review, and the whole page with the review off).

Impact
------
Page only. No route, service, schema or config was touched, so the OpenAPI
spec is unchanged. An instance without the AI review renders and behaves
exactly as before plus the toolbar and the custom threshold. The request the
guided path sends uses fields the contract already carries; a server that
ignores them reviews everything, which the page renders correctly.

Upstream Status
---------------
Not applicable - the Duplicates page does not exist upstream.

Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* docs(duplicates): changelog entries for sorting, select by confidence and the guided review

Background
Round 5 answered the second feedback from a real archive: select by a
number, let the model judge exactly those groups, read its verdicts in
one dialog, merge what stays ticked; sort the groups; a custom threshold.

Changes
- config/changelog.js: two entries in the current v2026.09.01 block.

Testing
- node scripts/run-tests.js --test changelog-releases: passed.

Impact
Documentation only.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): contract for evidence-based verdicts and the AI proposal

Background
A real archive produced "Kontoauszug" / "Kontoumzug": the matcher called
it a spelling distance, the prompt allowed "an obvious typo" as a reason
for same, and the model, seeing names and titles only, agreed. Both are
different things. The judge needs stricter rules and, for pairs linked by
spelling alone, a look at what the documents are about, at a bounded
cost.

Changes
- config/config.js: DUPLICATES_AI_EXCERPTS (default yes),
  DUPLICATES_AI_EXCERPT_CHARS (300), DUPLICATES_AI_EXCERPT_DOCUMENTS (2).
- schemas.js, OPENAPI/openapi.json: AiVerdict gains basis and confidence;
  DuplicateAiReviewRequest gains withExcerpts; aiReview reports excerpts.

Testing
- node scripts/run-tests.js --area duplicates: 6/6; regen without drift.

Impact
Settings and schema only; the implementation follows.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): judge model override and the verdict source in the contract

Background
Decisions for round 6: the matcher's hard tiers settle a pair without the
model, unsure pairs are asked once more with excerpts, and the judge may
run on a stronger model of the same provider.

Changes
- config/config.js: DUPLICATES_AI_MODEL (optional, judge only).
- schemas.js, OPENAPI/openapi.json: AiVerdict.source (model or
  spelling-rule); aiReview.escalated and aiReview.spellingRules.

Testing
- eslint and prettier on the two files; regen without drift.

Impact
Settings and schema only; the implementation follows.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(settings): make every DUPLICATES_ setting editable in its own section

Background
The AI review of the Duplicates page arrived with seven environment
variables and no way to change any of them from the interface. Editing a
container environment and recreating the container is the wrong price for
"try a stronger model for the judge" or "ask about fewer pairs per
request", and the settings page is exactly where those knobs belong.
config/config.js already reads all seven; only the front door was missing.

Changes
- views/settings.ejs: a "Duplicates" section (id="sec-duplicates") inside a
  new duplicates-tab block between the AI sections and OCR, with a nav entry
  in the desktop section nav (icon i-merge) and in the mobile one, in the
  same order as the page. Seven fields, each with a hint that says what the
  value does and what its default is: the AI review switch, the judge model,
  pairs per request, the candidate floor, the excerpt switch, excerpt length
  and documents per entry. Switches go through partials/settings-switch, so
  the hidden yes/no input the POST route reads exists as it does everywhere
  else.
- routes/setup.js: GET /settings passes the seven values (env first, the
  defaults of config/config.js as fallback) in the config object the view
  reads; POST /settings destructures the seven camelCase body keys,
  normalises them and writes them into updatedConfig, so setupService
  .saveConfig persists them with the rest. Numbers are clamped to their
  range; a value that is not a number, or a cleared field, keeps what is
  configured now instead of resetting to the default. The swagger body
  schema documents all seven, and the .env export gained a "Duplicates"
  group between "AI behaviour" and "External API".
- public/js/settings.js: the seven selector to env-key entries, so the
  "Overwritten" and "Managed by ENV" marking covers these fields too.
- OPENAPI/openapi.json regenerated.
- tests/test-settings-duplicates-section.js, registered in the
  observability area.

Testing
- node scripts/run-tests.js --all: 98 registered, 91 passed, 7 skipped
  offline (was 97/90/7). The new test covers the rendered section and its
  nav position, the seven inputs and their values, the POST round trip,
  clamping, the keep-the-previous-value case and the .env export group.
- npx eslint / npx prettier --check --ignore-unknown on every touched file.
- node scripts/regen-openapi.js leaves OPENAPI/openapi.json unchanged.
- Looked at the page in Chromium at 1440x1000 and 390x844 against a
  throwaway server outside the repository; no console errors, the section
  reads like the rest of the page and stacks on the phone.

Impact
Operators can change every DUPLICATES_ value from the settings page. The
existing restart-after-save is what makes them take effect; no new
mechanism. Values injected by the container still win and are shown as
managed, as for every other field. Nothing outside the settings page
changes: no route, service or default behaviour of the Duplicates page
itself is touched.

Upstream Status
Fork-only. The Duplicates page does not exist upstream.

Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): judge spelling-only pairs on evidence, not on distance

Background
A real archive produced "Kontoauszug" next to "Kontoumzug": the matcher
called it a spelling distance, the prompt allowed "an obvious typo" as a
reason for same, and the model, seeing two names and three titles, agreed.
Two different things. The judge needed stricter rules, evidence for the
pairs where spelling is the only link, and a way to say how sure it is and
on what grounds — all without opening a large context window on every pair.

Changes
- entityMatchAiService: the system prompt refuses a small spelling distance
  as a reason of its own ("Kontoauszug" / "Kontoumzug", "Miete" / "Mieter",
  "Bahn" / "Bank"), allows a misspelling only when one spelling is not a
  word, and answers unsure when it cannot tell. The output contract gains
  "basis" (a closed list) and "confidence" (high | low); both are parsed,
  an unknown value becomes null, and every verdict, member verdict and
  aggregate carries them. An aggregate keeps the deciding member's basis
  and takes "low" as soon as one deciding member is low.
- Evidence, graded by what the link is worth: every pair carries matched_by
  and score; every judged entity carries its titles, its matching rule and
  its neighbourhood ("filed_with": the correspondents of a tag's documents,
  the tags of a correspondent's); only the pairs linked by fuzzy, prefix or
  token-order also carry document excerpts. Excerpts are read once per
  entity per review and never for a strong tier. withExcerpts: false or
  DUPLICATES_AI_EXCERPTS=no reads nothing at all.
- A member pair a matcher rule settles (exact-normalized, umlaut-variant,
  legal-form) never reaches the provider: it gets verdict same with
  source: spelling-rule, counts in aiReview.spellingRules and costs no
  request, no read and no token.
- A pair the model calls unsure and that had no excerpts is asked once more
  with them; the second answer replaces the first (aiReview.escalated).
- paperlessService: getRecentDocumentExcerptsByEntity (one read,
  truncate_content, cut to the configured characters at a word boundary)
  and getEntityNeighbourhood (one read, the most frequent neighbour names
  through the existing caches). Both answer [] on any error and never log
  document content.
- The judge may run on its own model (DUPLICATES_AI_MODEL): generateText
  takes an optional model in all four provider services, shared through
  aiGenerateOptions.modelOverride.
- Logs: the per-kind start line names the evidence and the model, the
  request line the pairs with excerpts, the escalation its own line.
- Route POST /api/duplicates/ai-review parses withExcerpts like withTitles;
  swagger description updated and OPENAPI/openapi.json regenerated.

Testing
- node scripts/run-tests.js --all: 97 registered, 90 pass, 7 skip offline.
- tests/test-entity-match-ai-service.js: 35 -> 50 cases (the stricter
  prompt, basis and confidence parsing, excerpts only for spelling-only
  pairs and once per entity, the two switches, the configured cut, the
  Kontoauszug regression, settled pairs, the neighbourhood, escalation, the
  model override, batch sizing with excerpts, and both new client methods).
- tests/test-duplicates-endpoints.js: one case for withExcerpts; the three
  existing option assertions now expect withExcerpts: true.
- Demo run against the fake Paperless-ngx: the Kontoauszug/Kontoumzug pair
  costs 282 prompt tokens with excerpts, a strong pair without excerpts 75.
- eslint, prettier and a regen without drift on every file touched.

Impact
An AI review asks about fewer pairs and knows more about the ones it asks
about. Nothing runs on its own, nothing is merged, and document content
never reaches a log line.

Upstream Status
Not applicable — the Duplicates feature does not exist upstream.

* fix(duplicates): do not escalate an unsure pair whose documents carry no text

* feat(duplicates): one click for the AI's proposal, with the evidence behind it

Background
----------
Everything the page offered so far started from the user: scan, read every
card, tick, merge — and where the AI review existed it was a second question
asked after the first. What was missing is the path the archive's owner
actually wants for a first clean-up: one click that scans, has every group and
every near-miss judged, and then hands over a proposal to thin out rather than
a list to work through.

The rule this follows is the same as in the rounds before: the AI is an
addition, never a condition. Without the review nothing of this renders, and
"Scan Paperless-ngx", "Merge selected", the toolbar, the manual merge and the
guided path are the same as they were.

A verdict also had to say more than "same": with `basis`, `confidence` and a
`source` on the wire, the page can pre-tick exactly what is settled — a pair a
spelling rule decided, or one the model says it is sure about — and leave
everything else to the user. The member tables, finally, measured their own
content per card, so the columns of two cards below each other sat in
different places.

Changes
-------
"AI proposal" (#dupAiProposalBtn, primary, rendered only with aiReviewEnabled)
next to "Ask the AI", usable from the first paint because it scans itself:
  - status in the AI row (#dupAiProposalStatus): "Scanning…", then "Asking the
    AI about N pairs and near-misses…", with the hint line under the row
    (#dupAiProposalHint) saying what the click does;
  - it reuses runScan() (now awaited) with the kind, sensitivity and hidden-pair
    settings on the page, then the one review request with includeCandidates
    and no groupIds. Two requests, and no merge until the dialog is confirmed.
Proposal dialog (.dup-proposal-dialog): one row per group that could be merged,
  sorted same/high, same, unsure, different, unjudged (proposalRank,
  compareProposalEntries — both pure); pre-ticked are only the settled ones
  (isSureSame: verdict "same" with confidence "high", which covers the
  spelling-rule verdicts); legend, "Tick all same" (#dupProposalTickSame),
  "Untick all" (#dupProposalUntickAll), the copy-rule check (#dupCopyRuleAll)
  and a live foot line "N of M ticked · K documents · X objects will be
  deleted". Confirming sets the page selection to the ticked groups and hands
  them to the batch runner of round 4, so the selection bar reports the merge
  as it does for "Merge selected"; cancelling leaves the verdicts on the cards
  and nothing ticked.
Evidence, shared by both dialogs (one row renderer, one table):
  - a "Basis" column as a .zr-badge with a label per contract value;
  - the confidence as a suffix of the verdict chip ("AI: same · high");
  - a pair a spelling rule settled reads "Spelling rule" in the "same" tone
    (.dup-verdict--rule) instead of quoting a model that never saw it;
  - the guided dialog pre-ticks by the same rule, so a "same" the model is
    unsure about now comes up unticked there too.
Cards keep their shape: the verdict chip carries the basis in its title and the
  confidence as its suffix, no new column.
Second checkbox "Use document excerpts for spelling-only pairs"
  (#dupAiExcerpts, checked); withTitles and withExcerpts flow into every review
  request from the one place that builds it. The titles checkbox is relabelled
  "Use document titles and neighbours as context".
"AI-judged pairs" tile: its sub line now also counts "· E excerpts", "· S by
  spelling rule" and "· E escalated" when the review reports them.
Member tables line up across cards: .dup-members is table-layout: fixed with
  the name column taking what is left and truncating, and the matching rule a
  fixed share (.dup-members__name, .dup-members__rule).

Testing
-------
node scripts/run-tests.js --all -> 90 passed, 7 skipped offline, 0 failed
  (unchanged from the branch baseline of 97 registered).
tests/test-duplicates-ui.js: 38 -> 48 cases. New: the proposal ids and labels
  only with the review and the page whole without them; what the flow sends
  (runScan first, includeCandidates: true, no groupIds, both evidence flags,
  no request of its own); the pre-tick rule, evaluated as a function against
  seven verdicts; the row order, evaluated by sorting a shuffled list; a label
  for every basis the AiVerdict schema lists, parsed out of schemas.js; the
  spelling-rule chip; the dialog's parts and that it merges through the batch
  runner; the evidence counters of the stats tile; the fixed member-table
  layout; the new CSS classes. Changed: the titles checkbox label, the undo
  promise and the confirm dialogs counted one higher each (the proposal merges
  and therefore makes the same promise), and the pre-tick assertion of the
  guided row.
Reviewed in a browser against a throwaway mock (eleven scan groups plus three
  the model proposes, verdicts across same/high, same/low, unsure and
  different, some settled by a spelling rule, and a Kontoauszug / Kontoumzug
  pair that only the excerpts decide): 31 screenshots at 1280x900 and 390x844,
  light and dark — the controls, the status line mid-flow, the proposal dialog,
  after "Untick all", mid-merge, after the merge, the guided dialog, the stats
  tile, the aligned member tables and the render without the review. 0 px
  horizontal overflow everywhere; the column offsets of all eleven cards are
  identical.

Impact
------
Page only. No route, service, schema or config was touched, so the OpenAPI
spec is unchanged. An instance without the AI review renders and behaves
exactly as before. The new request field and the new verdict fields are ones
the contract already carries: a server that ignores withExcerpts reviews as it
did, and a verdict without basis, confidence or source renders as it did — it
then simply never comes up pre-ticked, which is the safe side.

Upstream Status
---------------
Not applicable - the Duplicates page does not exist upstream.

Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* chore(duplicates): changelog for the AI proposal round, room for the verdict in the Match column

Background
The sixth round of the Duplicates feature adds the AI-led proposal, the
evidence-based judge and the Duplicates settings section. The member
tables now use a fixed column layout so the columns line up across
cards, which left the Match column too narrow for a verdict such as
"AI: same - high": it wrapped into four lines.

Changes
- config/changelog.js: five entries for the round under the current
  release (AI proposal, evidence-based judge with excerpts and
  DUPLICATES_AI_EXCERPT*, DUPLICATES_AI_MODEL, aligned member tables,
  the Duplicates settings section).
- public/css/pages/duplicates.css: the Match column is 132px wide and
  the member verdict does not wrap, so the percentage and the verdict
  take one line each.

Testing
- npx eslint, prettier --check and stylelint on every file changed
  against nightly: clean.
- node scripts/run-tests.js --all: 91 passed, 7 skipped (server or
  credentials needed), 0 failed.
- node scripts/regen-openapi.js: no drift.
- Browser walkthrough against a fake Paperless-ngx and a fake judge:
  scan, merge, undo, dismiss, merge by hand, batch merge, guided review,
  AI proposal and AI review all pass. The Kontoauszug/Kontoumzug pair is
  judged "different" on its excerpts and does not appear in the
  proposal.

Impact
Visual only for the CSS; the changelog is shown in the What's New
dialog.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): contract for a watchable, stoppable AI review

Background
An AI review of a large archive is many model requests in a row. Today
it is one POST that answers when everything is done: nothing shows
while it runs, nothing can stop it, and the tokens it spends are
invisible until the end. The user wants to see what is happening, how
far it is and what it costs, and to stop it at any time. Decisions for
this round: the review runs as a server-side job the page can watch
and stop; a review nobody watches stops itself; a token budget per
review stops it on its own; a stopped review keeps the verdicts it
reached and opens no dialog; the progress lives in the AI row of the
Duplicates page.

Changes
- services/duplicateReviewJobService.js (new): the one review job at
  a time. start(), current(), get(), stop(id, reason), subscribe() for
  a server-sent stream (a late subscriber first gets the job as it is
  now), touch(), wait(), result(), toJSON(). The judge receives a
  control object (signal, onProgress, stop, tokenBudget); a partial
  result of a stopped review is kept like a complete one. The idle
  watch stops a job nobody has watched for the configured seconds. A
  finished job stays reachable for ten minutes.
- config/config.js: DUPLICATES_AI_TOKEN_BUDGET (200000, 0 = no limit)
  and DUPLICATES_AI_IDLE_STOP_SECONDS (60, 0 = never).
- schemas.js, OPENAPI/openapi.json: AiReviewProgress, AiReviewJob,
  AiReviewJobEvent; aiReview gains stopped, stopReason and
  pairsNotJudged.
- scripts/run-tests.js, tests/test-duplicate-review-job.js: the
  contract test of the job (9 cases) in the duplicates area.

Testing
- node scripts/run-tests.js --all: 99 registered, 92 pass, 7 skip
  offline, 0 fail.
- eslint and prettier on every touched file; regen without drift.

Impact
Nothing uses the job yet; the judge ignores the control object until
the implementation follows. No route or page changes.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): make the token budget and the idle stop editable in settings

Background
The two brakes of a running AI review landed as environment variables only:
DUPLICATES_AI_TOKEN_BUDGET caps what one review may spend across all its
requests, DUPLICATES_AI_IDLE_STOP_SECONDS ends a review no page has been
watching, so a closed tab cannot leave the model running. Both are exactly
the kind of setting somebody wants to try out once and then adjust, which
means editing a compose file and restarting the container for every attempt.
The other seven DUPLICATES_* variables already have a field in the Duplicates
section of the settings page; these two did not.

Changes
- views/settings.ejs: two number fields at the end of #sec-duplicates, in the
  style of the five above them — duplicatesAiTokenBudget (0-10000000, step
  1000) and duplicatesAiIdleStopSeconds (0-3600). Each hint says what the
  value does, what zero means and what the default is.
- routes/setup.js: GET /settings passes DUPLICATES_AI_TOKEN_BUDGET and
  DUPLICATES_AI_IDLE_STOP_SECONDS to the view with the defaults of
  config/config.js as the fallback; POST /settings destructures both body
  keys, clamps them to their ranges and keeps the currently configured value
  for an empty or non-numeric field, the rule the round-6 fields follow. Zero
  is a value for both and survives the clamp, because the ranges start there
  rather than at one. The @swagger body schema documents both, and the
  Duplicates group of ENV_EXPORT_GROUPS lists them after the existing keys.
- public/js/settings.js: two entries in the field mapping, so an
  operator-injected value greys the field out and carries the "Managed by ENV"
  pill like every other setting.
- OPENAPI/openapi.json regenerated.

Testing
- tests/test-settings-duplicates-section.js grew from 7 to 11 cases: the two
  fields render with their configured values, ranges and hints and close the
  section in that order; every field of the section is paired with its
  environment key in settings.js; the POST round trip persists all nine
  values; a budget of 99999999 is capped at 10000000 and an idle stop of -5
  lands on 0; zero survives for both, because it means "no limit" and "never"
  rather than an unset field; a fractional value is rounded; a cleared or
  unparsable field keeps what was stored before; the .env export carries all
  nine keys with the two brakes last.
- node scripts/run-tests.js --all: 99 registered, 92 passed, 7 skipped
  offline, 0 failed — the same numbers as before this change.
- eslint and prettier clean on every file touched; regen-openapi.js leaves no
  drift.
- Looked at the section in Chromium at 1440x1000 and 390x844 against a
  throwaway server outside the repository: both fields render like the seven
  above them, no console errors, and with the two keys in the locked-env set
  both are disabled and carry the "Managed by ENV" pill while a neighbouring
  field stays editable.

Impact
No behaviour change for anybody who never opens the section: the defaults are
unchanged (200000 tokens, 60 seconds) and nothing new runs. Operators who set
either variable in their container environment keep winning — the field is
shown greyed out rather than silently overwritten. A saved value needs a
restart to take effect, as the hints say, because config/config.js reads the
environment once at load.

Upstream Status
Not applicable — the Duplicates page is specific to this fork.

* feat(ai): let every provider take an abort signal for one call

aiGenerateOptions gains abortSignal(options); the four provider
services pass it on where their client expects it — the OpenAI SDK as
the second argument of create(body, { signal }) for OpenAI, Azure and
the custom endpoint, axios as { signal } in the request config for
Ollama. Without a signal every provider sends exactly what it sent
before: no second argument at all, and the unchanged axios config.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): the AI review reports, stops and counts its tokens

Background
"Während die AI befragt wird, könnten Millionen von Tokens im
Hintergrund verbraten werden, ohne dass man es sieht. Man muss es auch
abbrechen können." The judge answered when it was done and said
nothing while it worked, so the page had nothing to show and nothing
to stop. The job of the previous round hands it a control object; this
round makes the judge use it. A bar needs a denominator before the
first request, which the old per-kind loop could not give: it read the
archive, asked, and only then looked at the next kind.

Changes
- services/entityMatchAiService.js: reviewScan(options, control = {})
  runs in two passes. Pass one, for every kind of the review: read the
  entities and the band, build the pairs, settle the spelling-rule
  pairs, gather titles, neighbourhood and excerpts, and size the
  batches. Pass two judges kind after kind. Nothing is asked before
  the whole plan exists.
- Progress: phase scanning before the scan, phase evidence per kind
  and per read, one phase judging with requestsPlanned, pairsTotal and
  estimatedTokens for the whole review, one report per answered
  request (requestsDone, pairsJudged, the running token total,
  failedRequests, retries, kind, and the line naming the next
  request), phase escalating when an unsure pair is asked again, phase
  finishing before the groups are built. A split answer adds its
  halves to requestsPlanned in the report of the request that split,
  so the bar never goes backwards; the escalation adds its own
  requests and pairs the same way. Elapsed time and the estimate stay
  with the job, which derives them.
- Stopping: control.signal is read before every read, every request
  and the second round, and travels to the provider, so a stop lands
  on a request in flight. A request that dies on the signal is a stop,
  not a failure: no failed request, no retry, and no "unsure" — the
  pairs stay without a verdict, so they cannot become a group. A
  stopped review returns what it reached; it never throws.
  aiReview now always carries stopped, stopReason (null; the job fills
  it in) and pairsNotJudged.
- Token budget: one running total for the whole review, folded from
  the provider's usage or, for a provider that reports none, from the
  measured prompt plus the estimated answer, so the counter and the
  budget work for every provider (aiReview.tokens keeps reporting only
  what a provider stood behind). When control.tokenBudget is reached
  the review calls control.stop('token-budget') and behaves as
  stopped.
- Logs: "review stopped (user|token-budget|idle): N of M request(s)
  made, P pair(s) not judged, T token(s)." and "token budget 200000
  reached after N request(s) (T tokens)."; the start, request and
  finish lines are unchanged.
- services/duplicateReviewJobService.js: the control object gains
  stopReason(), the one seam the judge needs to name the reason in its
  own log line.
- reviewPairs(pairs, options) additionally takes plan, systemPrompt
  and tracker from reviewScan; a caller that brings none gets what it
  always got.

Testing
- node scripts/run-tests.js --all: 99 registered, 92 pass, 7 skip
  offline, 0 fail (the baseline of the branch).
- tests/test-entity-match-ai-service.js: 13 new cases (64 total) —
  the plan before the first request for one and for two kinds, the
  split and the escalation raising the plan, a failed request still
  moving the bar, a stop between requests and a stop in flight, the
  token budget, a provider without usage, an already aborted signal, a
  review without a control, the report carrying nothing the job
  derives, and the signal reaching all four providers. The one moved
  expectation is the deep-equal on aiReview, which now names the three
  new fields.
- tests/test-duplicate-review-job.js: one case for stopReason().
- A real run through the job service over a fake archive: a review
  that runs through, the same one stopped after request 2, and the
  same one against a token budget.
- eslint and prettier on every touched file.

Impact
The page can show a bar with a denominator, an estimate and a running
token count from the first request, and a stop costs at most one
request that is already in flight. A review without a control object
behaves exactly as before, so the synchronous route is untouched until
it is moved onto the job.

Upstream Status
Not applicable: the Duplicates page and its AI review do not exist
upstream.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): watch and stop the AI review from the page

Background

A review of a drifted archive is many model requests in a row. Until now
"Ask the AI" was one POST that answered when everything was over: a spinner,
no idea how many requests were still coming, no idea what it cost, and no way
out but reloading the tab — which left the model running. The job service of
the contract commit made the review watchable and stoppable on the server;
this wires the routes and the page onto it.

Changes

routes/setup.js (Duplicates block only)
- parseAiReviewRequest(body) holds the validation both entry points share, so
  the synchronous route and the job route can no longer drift apart.
- POST /api/duplicates/ai-review/jobs starts a review and answers
  202 { job }; while one runs it answers 409 with that running job, so a
  second tab attaches instead of failing.
- GET /api/duplicates/ai-review/jobs/current answers { job } or { job: null }
  and counts as watching the review.
- GET /api/duplicates/ai-review/jobs/:id answers { job, result }, 404 for an
  unknown id, and also counts as watching.
- GET /api/duplicates/ai-review/jobs/:id/events streams AiReviewJobEvents
  (text/event-stream, no-cache, X-Accel-Buffering: no, keep-alive, flush after
  every write), a ": keep-alive" comment every 15 s, and ends after done,
  stopped or failed. An unknown id is a JSON 404 before any stream header.
- POST /api/duplicates/ai-review/jobs/:id/stop answers { job }; stopping a
  finished review is a 200 no-op.
- POST /api/duplicates/ai-review now starts that same job and waits for it: a
  stopped review answers 200 with the verdicts it reached, a failed one keeps
  the judge's status, and a second request while one runs is a 409. It
  subscribes for the duration so the idle stop cannot end a review somebody is
  waiting for.
- @swagger for every new route; OPENAPI/openapi.json regenerated.

views/duplicates.ejs, public/js/duplicates.js, public/css/pages/duplicates.css
- A progress panel in the AI row (#dupAiProgress): bar (#dupAiProgressFill,
  indeterminate while the plan is unknown), message, counters
  ("Request 3 of 8 · 40 of 96 pairs · 12.4k of 200k tokens"), time
  ("about 40 s left · 1:24 elapsed") and a Stop button (#dupAiStopBtn). After
  the end it keeps one outcome line and hides on the next scan or review.
- askForVerdicts() starts the job, follows it through EventSource and falls
  back to polling the job every 2 s when the stream breaks. It resolves
  { aiReview, stopped }; all three AI paths honour `stopped` — the notice is
  shown and neither the guided dialog nor the proposal opens.
- On load the page asks for the current job and re-attaches to one that is
  still running; a finished one is left alone.
- Pure helpers formatTokens, formatEta, formatElapsed, progressPercent and
  stopNotice word the numbers; the UI test evaluates them directly.

Testing

- node scripts/run-tests.js --all: 99 registered, 92 pass, 7 skip offline
  (unchanged); duplicates-endpoints 20 -> 30 cases, duplicates-ui 48 -> 57.
- eslint, prettier, stylelint clean on every touched file; regen-openapi
  leaves no diff.
- Reviewed in a browser against a throwaway server with a judge that reports
  eight requests: mid-run, stopping, stopped and done, desktop and phone,
  light and dark, no console errors. A page loaded while a review runs
  re-attached and rendered its result; with the event stream blocked the same
  review came home through eight polls.

Impact

The Duplicates page shows what a review is doing and costing and can end it;
the verdicts already reached are kept. The synchronous route keeps its request
and response, so an API client sees no change beyond the new 409 while a
review runs.

Upstream Status

Not applicable — the Duplicates feature does not exist upstream.

* fix(duplicates): a late Stop answer no longer paints over the outcome; changelog for the review job

Background
In the browser smoke test of the round, a stop pressed after the first
answered request ended the job before the stop request itself answered.
The page then rendered that answer, a snapshot from the stopping moment,
over the outcome line and restarted the elapsed clock, so the panel read
"Stopping after the current request…" next to a finished review.

Changes
- public/js/duplicates.js: stopReview() renders the stop answer only
  while the same job is still followed and still live.
- tests/test-duplicates-ui.js: one case that pins the guard (57 -> 58).
- config/changelog.js: three entries for the round under the current
  release (the review as a job with progress and Stop, the token budget
  and the idle stop as settings, the plan before the first request).

Testing
- node scripts/run-tests.js --test duplicates-ui: 58 passed.
- Browser smoke against a fake Paperless-ngx and a slowed-down fake
  provider: Stop during request 2 leaves "Stopped after 1 of 5 requests
  · 1 of 5 pairs judged · 1.1k tokens" on the panel, the verdicts
  reached stay on the cards, no dialog opens; the proposal path stops
  the same way; a token budget of 2500 stops the review after 3
  requests with the budget named in the notice and the log; a page
  reloaded during a review re-attaches and renders the result; the
  round-6 walkthrough (scan, merge, undo, dismiss, merge by hand, batch,
  guided review, proposal, plain review) passes unchanged.
- eslint and prettier on the touched files.

Impact
Visual only; the review itself was stopped correctly before the fix.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): contract for a judge that measures the model, streams its answers and thinks only on request

Background
On a real archive with a hosted Qwen model the first review request
asked about 25 pairs, ran for 103 seconds and died at its own answer
cap: the model spent the whole budget thinking before the first
verdict, the cut-off text was thrown away, and the page showed nothing
but a ticking clock for two minutes. Three scans of 13 seconds each
came before that. Decisions for this round: the judge measures the
model on a small first request and sizes every later request to a
target duration; the providers stream the answer so the page moves
inside a request and a cut-off answer keeps its verdicts; thinking is
off for the judge unless the operator switches it on; the review
reuses a fresh scan instead of scanning again.

Changes
- config/config.js: DUPLICATES_AI_THINKING (no) and
  DUPLICATES_AI_REQUEST_SECONDS (30).
- schemas.js, OPENAPI/openapi.json: AiReviewProgress gains
  requestPairs, requestAnswers, requestTokens, thinking, batchSize and
  calibrated; the phase list gains warming-up.
- services/duplicateReviewJobService.js: the new progress fields, the
  warming-up phase, and a time estimate from the share of pairs done
  (answers streamed in count), because the batch size may change after
  the warm-up.
- services/aiGenerateOptions.js: reasoningEnabled(options) and
  progressHandler(options), the two switches the judge will send and
  the providers will read, with the GenerateTextProgress shape and the
  partialText rule for cut-off answers.
- scripts/run-tests.js, tests/test-ai-provider-streaming.js: a
  registered placeholder for the provider streaming test.

Testing
- node scripts/run-tests.js --all: 100 registered, 93 pass, 7 skip
  offline, 0 fail.
- eslint and prettier on every touched file; regen without drift.

Impact
Nothing reads the new switches yet; the implementation follows.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* test(helpers): fake OpenAI-compatible and Ollama servers on ephemeral ports

* feat(providers): stream the answer, report progress, keep the cut-off text

Background

A hosted model behind the custom provider spent 103 seconds and the whole
3200-token completion cap on one AI-review request, then threw "the answer hit
a token limit" and dropped every character it had produced. Nothing was visible
while it ran, nothing survived the throw, and the batch was split and paid for
again from the beginning. Two causes: the four provider services always sent a
non-streaming request, so there was nothing to watch; and
assertCompletionNotTruncated() threw before anyone read the content, so the
prefix was thrown away. On top of that the model thinks before it answers, and
on a server that separates thinking from answering the reasoning arrives as
reasoning_content deltas that no provider knew about.

Changes

- services/aiGenerateOptions.js: the shared streaming machinery.
  stripReasoningText() removes <think> blocks, including one a cut-off left
  open. createProgressCollector() assembles a streamed answer, splits reasoning
  from answer incrementally (a marker may be cut across two chunks), counts the
  completion tokens from a usage chunk or estimates them over everything
  produced, reasoning included, and reports at most once per 100 ms plus one
  final report that says done. consumeChatCompletionStream() and
  runChatCompletionStream() are the OpenAI-compatible half: read the stream,
  finish before any throw, and turn a cut-off or a stop into an error that
  carries what arrived. isAbortError()/abortedGenerationError() give a stopped
  request one name across the SDK, axios and fetch.
- services/serviceUtils.js: estimateTokenCount() (the same character-based
  estimate, on a length) and an optional fourth argument on
  assertCompletionNotTruncated() that puts partialText on the error.
- services/openaiService.js, services/customService.js,
  services/azureService.js: generateText() streams when the caller hands in
  onProgress, with stream_options: { include_usage: true } on OpenAI and the
  custom provider and on Azure only from API version 2024-06-01, where the API
  takes it. Without a handler the body is exactly what it was. Both paths strip
  reasoning from the answer and attach the prefix to a truncation error; an
  abort throws an AbortError with partialText.
- services/customService.js: reasoning: false adds
  chat_template_kwargs: { enable_thinking: false } and, for a model name
  matching /qwen/i, that family's soft switch on its own line at the end of the
  user message; reasoning: true sends enable_thinking: true and no soft switch;
  without the option nothing new is sent.
- services/ollamaService.js: generateText() reads NDJSON from an axios
  responseType: 'stream' response, keeps the tail of a socket read until its
  newline arrives, treats the thinking field as thinking, and stops reading the
  moment the signal aborts. reasoning: false/true sends think and overrules
  OLLAMA_THINK; without the option OLLAMA_THINK still decides. The cut-off
  check the analysis path has always run now runs here too, with partialText,
  and a failure no longer erases a token count that was already measured.
- tests/helpers/fake-openai.js, tests/helpers/fake-ollama.js: real HTTP servers
  on ephemeral ports, scripted per request (content chunks, reasoning chunks,
  finish reason, usage chunk or none, per-chunk delay, non-streaming answers
  from the same script), recording every request body and whether the client
  hung up early.
- tests/test-ai-provider-streaming.js replaces its placeholder with 22 cases.

Testing

- node tests/test-ai-provider-streaming.js: 22 passed, 0 failed; run five
  times, no flake.
- node scripts/run-tests.js --all: 93 passed, 7 skipped offline, 0 failed —
  the same numbers as before this change.
- npx eslint and npx prettier --check on every touched file: clean.
- A throwaway process reproduced the reported failure against the fake: the
  progress reports show thinking first with no text, then the answer growing,
  then one done report with the exact token count from the usage chunk, and the
  throw carries the 131 characters of JSON that had arrived.

Impact

No caller behaves differently unless it asks: without onProgress the request
body is byte for byte what it was, and the round-7 provider cases assert that.
What does change for every caller of generateText(): a <think> block no longer
reaches the returned string, a truncation error now carries partialText, an
abort now throws under the name AbortError, and Ollama's generateText() now
raises the same truncation error the analysis path raises instead of returning
a half-written answer. The document analysis path is untouched.

Upstream Status

Not upstream. Streaming, progress reporting, the partial text of a cut-off
answer and the thinking switch do not exist in clusterzx/paperless-ai.

* feat(duplicates): the progress panel moves inside a request and names the measured batch size

Background

A review of a large archive is a handful of long model requests, and the
panel only moved between them. One request took 103 seconds while the page
showed "request 1 of 4 - 0 of 82 pairs" and a ticking clock, so for minutes
at a time the only honest reading of the page was "nothing is happening".
The judge now measures the model on a small first request, sizes every later
one to a configured number of seconds, and streams the answers as they
arrive, which gives the page three things it never had: answers inside a
request, a warm-up phase, and a model that says when it is thinking.

Changes

Page (views/duplicates.ejs, public/js/duplicates.js,
public/css/pages/duplicates.css):

- progressPercent() counts pairs whenever the plan knows them, the answers
  of the running request included, and falls back to requests only while no
  pair count exists. The bar therefore moves during a request instead of
  jumping once per request.
- progressCountsText() gained the "7 of 10 answers" part, printed only while
  a request is in flight and capped at the size of that request.
- progressTimeText() says "measuring the model" in the warm-up and "the
  model is thinking" while the model writes reasoning, instead of a clock
  that cannot move; an estimate the job already made is still shown next to
  either.
- New #dupAiProgressNote line under the counts, written by the new
  progressNoteText(): "4 pairs per request while the model is measured"
  before the measurement, "9 pairs per request, sized from the model's
  answers" after it, empty while no size is known. A zero-width space holds
  its row open for as long as a review runs (.dup-progress--live), so the
  stats tiles below do not jump the moment it fills.
- .dup-progress__fill--thinking pulses while the model reasons, slower than
  the indeterminate band, and is switched off under prefers-reduced-motion.
- The outcome line and the "Model requests" tile both name the batch size the
  review settled on.
- New htmlReviewFailure(): all three AI paths report a failed review with the
  judge's own message plus one link, "Open the Duplicates settings", to
  /settings#duplicates-tab.

Settings (views/settings.ejs, public/js/settings.js, routes/setup.js):

- Two fields close the Duplicates section: the switch "Let the judge think"
  (DUPLICATES_AI_THINKING, default off) and the number "Seconds per model
  request" (DUPLICATES_AI_REQUEST_SECONDS, 5-300, default 30). GET, POST with
  the usual clamping and keep-the-previous-value behaviour, the @swagger
  request body, ENV_EXPORT_GROUPS and the two "Managed by ENV" selectors.

Route:

- GET /api/duplicates/scan passes fresh: true; a scan somebody pressed a
  button for must not be answered from a cache.

OPENAPI/openapi.json regenerated.

Testing

- node scripts/run-tests.js --all: 93 passed, 7 skipped offline, 0 failed
  (unchanged from the baseline of this round).
- duplicates-ui 58 -> 66 cases: the bar with streamed answers and without a
  pair count, the counts line with and without a running request, the three
  wordings of the time line, the note line, the outcome line with a batch
  size, the panel ids and the thinking class, the settings link of the failed
  notice, and the stylesheet's pulse with its reduced-motion rule.
- settings-duplicates-section 11 -> 15 cases: both fields render with their
  values and hints, the POST round trip, clamping (2 -> 5, 999 -> 300), the
  cleared field keeping the previous value, the switch spellings, the export
  group order and the two selectors.
- duplicates-endpoints 30 -> 31 cases: the scan route hands fresh: true to
  the service.
- eslint, prettier and stylelint clean on every touched file; regen-openapi
  leaves no drift.
- Looked at in Chromium against a throwaway server on port 3403 that walks a
  scripted review through the warm-up, a thinking stretch and a request whose
  answers climb 0 -> 10: desktop and phone, light and dark. The stats tiles
  sit at the same offset before and after the note line fills.

Impact

The panel reports inside a request rather than between requests, and names
both the warm-up and the measured batch size, so a review that takes minutes
per request looks like work rather than a hang. A failed review points at the
setting that would have prevented it. Nothing scans, judges or merges on its
own; the two new settings are read at startup like the rest of the section.

Upstream Status

Not applicable - the Duplicates page does not exist upstream.

* feat(duplicates): measure the model, size every request to it, and reuse a fresh scan

Background

Asking the AI about a scan of the user's archive did not work on their
instance. The judge sent 25 pairs with a completion cap of 3200, the hosted
model thought before it answered and spent all 3200 tokens on the thinking,
and 102 seconds later nothing had been judged. The answer was then split into
13 + 12, which buys nothing: the thinking does not get cheaper with fewer
pairs. Meanwhile the page showed "request 1 of 4 · estimating…" for two
minutes, because a request only reports when it is over. The user pressed
Stop.

The same run also scanned the archive three times inside 50 seconds — the
page's scan, the AI proposal's and the review job's — 1359 tags and 13
seconds each, with nothing changing in between.

Changes

services/entityMatchAiService.js

- Thinking off by default. Every judge request carries
  `reasoning: config.duplicatesAiThinking === true`, so a reasoning model
  answers instead of deliberating unless the operator asked for it. Nothing
  else about the prompt changed.
- A warm-up instead of a guess. The first request of a review whose model has
  not been measured asks about at most WARMUP_PAIRS (4) pairs with a
  deliberately generous cap (RESPONSE_TOKENS, the flat estimate or
  WARMUP_MIN_CAP, whichever is largest, bounded by the context window). It is
  announced under the phase `warming-up` with the message "Measuring the model
  with a small first request…", `calibrated: false` and the size it will use;
  the plan reported with it is provisional and the log says so.
- Sizing from the measurement. Every answered request yields tokens per pair
  (thinking included) and tokens per second, each smoothed by half against the
  measurement before it. From them:
  `batchSize = clamp(floor(requestSeconds × tokensPerSecond ÷ tokensPerPair), 1, batchSize())`
  and `cap = ceil(tokensPerPair × batchSize × 1.5) + TOKENS_OVERHEAD`, both
  bounded by the context window as the batch planning bounds them.
  `requestSeconds` is DUPLICATES_AI_REQUEST_SECONDS, at least 5, 30 by
  default. A batch is now taken off the front of a queue rather than chunked
  up front, because its size changes while the review runs.
- The plan settles after the warm-up. `requestsPlanned` and `estimatedTokens`
  are re-derived from the pairs nobody has asked about yet and reported with
  `batchSize` and `calibrated: true`, so the page's denominator stops moving.
- Truncation: raise before halving. A cut-off answer that salvaged nothing is
  asked again with twice the cap (the warm-up gets the whole window at once),
  and only when that bought nothing — or the cap is already at the window's
  bound — is the batch halved as before. A warm-up that does not fit even then
  ends the review as failed with a message the operator can act on, naming
  DUPLICATES_AI_THINKING and TOKEN_LIMIT. A single pair at the bound keeps the
  old "unsure" and its log line.
- The cut-off text counts. All four providers now attach `error.partialText`,
  so the salvage path runs for every one of them; a salvaged request counts
  its verdicts in `pairsJudged` and in the tracker. Two comments that still
  said only Ollama returns half-written answers were rewritten.
- Progress inside a request. With a progress sink the provider is asked to
  stream (`onProgress`). Each report, at most every 250 ms, carries
  `requestPairs`, `requestAnswers` (the complete verdict objects counted off
  the streamed text), `requestTokens`, `thinking` and the running token total:
  "The model is thinking… (640 tokens so far)" while it thinks, otherwise the
  request line with " · 7 of 10 answers" appended. The report that counts the
  request resets all four. A review nobody watches sends the plain request it
  always sent.
- Calibration memory. The last measurement per model name lives on the
  singleton; a review that finds one starts sized from it, skips the warm-up
  and says so in the log. A measurement taken with thinking on is never reused
  with thinking off. `resetCalibration()` for tests.
- Logs: the finish line says "N pair(s) planned" (the number is the plan), the
  batch-size line is marked provisional until the model is measured, and the
  split line says whether the cap was raised or the batch halved.

services/duplicateMergeService.js

- `scan()` keeps its result per set of options (kind, threshold,
  includeDismissed) for SCAN_CACHE_MS (60 s) and answers the next identical
  request from it with one log line instead of the start and finish lines.
  `fresh: true` skips and refills it; the page's Scan button sends it.
- A merge, an undo, a dismissal and `restoreDismissal()` empty the cache. A
  dismissal deleted through the route, which talks to the model directly, is
  caught by a fingerprint (row count and highest id per kind) checked on every
  hit — one local SELECT against a 13-second scan.
- `reviewScan()` calls `scan()` without `fresh`, so a proposal made right
  after the page scanned costs no second scan.

Testing

- node scripts/run-tests.js --all: 93 passed, 7 skipped offline, 0 failed
  (100 registered), unchanged from the baseline.
- tests/test-entity-match-ai-service.js: 65 -> 80 cases. New: thinking off and
  on; the warm-up's size, cap, phase and message; the sizing math on a fixed
  usage and duration; the request seconds and their floor; the context window
  bounding size and cap; smoothing; the plan and estimate recomputed after the
  warm-up; calibration reused, not reused across the thinking switch, reset; a
  warm-up that cannot fit ending the review with its message; a truncated
  answer with partialText salvaged and counted; a streamed request reporting
  thinking, then answers, then clearing itself; an unwatched review not
  streaming; a review served from the page's scan.
- tests/test-duplicate-merge-service.js: 17 -> 22 cases. New: cache hit, other
  options and `fresh` missing it, expiry, invalidation by merge, undo, dismiss
  and restore, and a dismissal removed behind the service.
- Changed expectations, all from the raise-before-halve rule: the truncation
  cases now see every size asked twice (once, once with twice the cap) before
  it is halved, the single pair is asked twice before it ends as unsure, and
  the planning cases see the `warming-up` phase where they saw `judging`.
- Two demo runs against a fake model at 30 tokens/s: thinking off, 12 pairs —
  warm-up 4 pairs in 20 s (600 tokens, 150 per pair), then requests of 5 pairs
  at 25 s, 4500 tokens, 60 s in total. Thinking on — warm-up 4 pairs in 40 s
  (1200 tokens, 300 per pair) and requests of 2 pairs at 30.04 s, the
  configured length.

Impact

The first request of a review is seconds rather than minutes, every later one
lasts about as long as the operator asked, and the page shows the model
thinking and answering while it happens instead of a still bar. A review of a
model that was measured before starts at full size. Three scans of one archive
become one. Nothing runs on its own and no verdict changed: the prompt, the
rules and the shape of an answer are what they were.

Upstream Status

Not applicable — the Duplicates feature does not exist upstream.

* fix(duplicates): a review never asks for a fresh scan of its own

reviewScan() drops a `fresh` flag its caller may carry instead of passing it on, so a route that forwards the page's scan options cannot make the review scan the archive a second time.

* fix(duplicates): the yes/no switches of the judge read 'yes', and a small batch is not starved after a thinking one

Background
The browser smoke test of the round ran the thinking scenario and the
judge kept saying "thinking off" although DUPLICATES_AI_THINKING=yes
was set. config/config.js normalises every yes/no setting to the
strings 'yes' and 'no' (parseEnvBoolean), while three readers in the
judge asked Boolean() or === true: the thinking switch could never be
turned on, and the review and excerpt switches could not be turned off
('no' is a truthy string). The second finding: a thinking model pays a
fixed price per request, so a one-pair request sized by pairs alone
after a four-pair warm-up got a cap the same thoughts did not fit; the
judge recovered by raising the cap, at the cost of one request.

Changes
- services/entityMatchAiService.js: switchedOn() accepts 'yes' and a
  boolean true; isEnabled(), excerptsEnabled() and thinkingEnabled() use
  it. The cap never drops below the largest completion the model has
  produced in this review plus a quarter (CAP_FLOOR_FACTOR), and that
  floor is remembered with the calibration.
- tests/test-entity-match-ai-service.js: one case per finding (82
  cases), the sizing case expects the remembered floor.
- config/changelog.js: three entries for the round under the current
  release.

Testing
- node scripts/run-tests.js --test entity-match-ai-service: 82 passed.
- Browser smoke against a fake Paperless-ngx and a fake provider that
  streams, thinks on request and honours max_tokens: thinking off, the
  fake never thought, warm-up 4 pairs, 59 tokens/s measured; thinking
  on, the panel showed the thinking state, no request hit the token
  limit any more; Stop, re-attach, token budget and the round-6
  walkthrough unchanged.

Impact
DUPLICATES_AI_REVIEW=no and DUPLICATES_AI_EXCERPTS=no now do what they
say; DUPLICATES_AI_THINKING=yes now reaches the model.

Upstream Status
Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): contract for the creation guard, the semantic sweep, unused objects, renames and a remembered calibration

Background
Round 9 of the Duplicates feature, six points the user picked: stop
the drift where it starts (document analysis creating "Rechnungen"
next to "Rechnung"), let the model find synonyms and translations the
string matcher cannot, list and delete unused objects with undo, name
the survivor of a merge, keep the judge's measurement of a model across
restarts, and scan faster. Decisions: only hard matcher tiers map a
new name onto an existing one (case, umlauts, legal form, plural, word
order), typo-like matches …
…y what every run costs (#345)

* feat(review): the ground for assistant surfaces — run cost, baskets, decisions

Background
Duplicates and Simplify tags both grew into control panels: every module is
on screen at once, the unit of review is a row in a nine-column table, and the
only thing a run ever says about itself is that it is running. Deciding about
1,187 tags that way is archaeology, and nobody can tell before pressing a
button whether it costs six minutes of GPU or 519 writes to Paperless-ngx.

Three surfaces replace that, on both pages: the result of a run read as
baskets of sentences, one decision at a time where the model was unsure, and
the cost said out loud before, during and after a run. This commit is what
both pages need to exist before either can be built — nothing of it is
user-visible on its own except the styleguide entry.

Changes
- models/document.js: migration v15 adds ai_run_stats, one row per finished
  run of a model-backed task (requests, prompt/completion/thinking tokens,
  seconds, items the model saw against items a rule settled), with
  saveAiRunStats, getLastAiRunStats and listAiRunStats. Stopped and failed
  runs are kept and marked: half a run still measured its requests. The
  newest 50 runs per task survive, pruned inside the insert transaction.
- services/aiRunEstimate.js: what a run will cost, before it starts. Pure
  arithmetic over numbers the caller gathered, with three sources in falling
  order of trust — a finished run of the same task, the judge's measurement
  of the model, then documented constants. `basis` names which one answered,
  so a page can say "measured" or "a guess" instead of implying precision.
- services/duplicateReviewJobService.js: the progress shape carries
  promptTokens, completionTokens and a short requestLog of finished requests
  (items, answers, tokens, reasoning, duration, outcome). recordRequest keeps
  it newest-first and capped. One number for a whole run hides the request
  that thought for 25,000 tokens and answered nothing.
- public/css/review.css: the shared kit in layer components — ledger and
  token split bar, baskets including the amber one that needs an answer, the
  decision card with its two sides and the model's sentence, the consequence
  line above a button, the run bar and the request log, and a button that
  carries its price on a second line. Tokens only, both themes, and the
  decision card stacks at phone width.
- views/partials/shell/head-start.ejs links it; views/styleguide.ejs shows
  every component of it once, which is where anyone looks before inventing a
  class.
- schemas.js: AiRunEstimate and AiRunStats, with OPENAPI/openapi.json
  regenerated.
- Four tests registered in scripts/run-tests.js, two of them the contract's
  own and two the ground the page work builds on.

Testing
node scripts/run-tests.js --all -> 103 passed, 7 skipped, 0 failed (the seven
need a running server, credentials or poppler). Areas duplicates (12) and
simplify (6) green on their own. ESLint, Prettier and stylelint clean on every
file this commit touches; node scripts/regen-openapi.js leaves no drift.

Impact
No behaviour changes for anyone yet: no endpoint reads ai_run_stats, no page
renders the kit, and no run writes a row. The migration is additive, runs on
startup and leaves every existing table untouched. /styleguide gains a
"Review surfaces" section in dev builds.

Upstream Status
Fork-only; the Duplicates and Simplify features do not exist upstream.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(cost): every model-backed run writes down what it cost

Background
A run of the AI review or of the proposed order said nothing about what it
spent. The page could show "something is running" and, at the end, one token
number for the whole run — which hides exactly the request that thought for
25,000 tokens and answered nothing. There was also nothing to build an
estimate on: the `ai_run_stats` table of the contract commit had no writer.

Changes
- duplicateReviewJobService: the control object a runner gets carries two new
  channels. `noteRun()` takes what the runner knows and the progress does not
  (the items the model is asked about, the items a rule settled first, the
  model, whether it thinks); `recordRequest()` takes one finished request and
  does three things in one call — the row goes into `progress.requestLog`
  through the contract's `recordRequest`, its tokens are added to the run's
  totals, and `progress.promptTokens` / `progress.completionTokens` are put
  back on the progress. A runner without a count of its own gets the run's, so
  the rows of one run are numbered once in the order they finished.
- duplicateReviewJobService: when a job of task order, review, vocabulary or
  splits ends — done, stopped or failed — one `ai_run_stats` row is written.
  `apply` is left out: it writes tags, it never asks. The write never throws,
  so a bookkeeping failure cannot turn a finished job into a failed one. A
  token field the provider never reported stays null.
- entityMatchAiService: every finished request of the judge and of the
  semantic sweep records a row with a truthful outcome — `answered` when every
  pair came back, `partial` when some were missing, `empty` when nothing
  usable came back (the cap-raise and the single-pair give-up), `failed` for a
  provider error or an unreadable answer. A stop records nothing: it is not a
  finished request. Token counts come off `lastGenerateTextUsage`, never from
  the estimate `_countRequestTokens` makes for the budget.
- entityMatchAiService: `estimateReview()` answers what the next review would
  cost without asking anybody and without scanning — the cached scan of the
  merge service, `_pairsForKind` with an empty band, the judge's calibration
  and the last run. No cached scan for these options means `needsScan: true`,
  `items: 0` and `basis: 'guess'` rather than a number nobody measured.
- entityMatchAiService: `concurrency(override)` lets one run name its own lane
  count; out of range is clamped, absent means "as configured".
- tagSimplifyService: the rule pass of the order is `_rulePass()`, used by the
  run and by the estimate, so the two can never disagree about how many tags
  reach the model. `estimateOrder()` answers the order's cost from that pass,
  the saved vocabulary, the stored proposals and the calibration, with
  `skippable` saying what each of the two levers would save. The tag list it
  reads is cached for a minute, because a page asks on every move of a slider.
- tagSimplifyService: `proposeOrder` accepts `skipDecided`, `minDocuments` and
  `concurrency`. A tag left out for being decided keeps the proposal it was
  decided on — skipping it saves a request, it does not undo a decision — and
  a tag left out for its document count says so in its reason.
- tagSimplifyService: the order, the splits and the vocabulary record their
  requests and note their size the same way the judge does.

Testing
node scripts/run-tests.js --all — 103 passed, 7 skipped, 0 failed.
npx eslint / npx prettier --check on the three services — clean.

Impact
Nothing changes for a caller that passes the control object it always passed:
both new channels are absent then and no row is written. The two new options
of the order narrow nothing when they are absent, so an unchanged page runs
exactly the run it ran before.

Upstream Status
Not applicable — this is next-only.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(cost): two estimates, and levers on the two starts

Background
Both pages start a model-backed run without saying what it will cost. The
answer was already computable — the rule pass of the order, the cached scan of
the review, the judge's calibration, the last run — but nothing put it on the
wire. And the order had no way to be told "do not ask about the tags I already
decided on", which on a real archive is a third of its requests.

Changes
- GET /api/simplify/order/estimate: what the next run of the proposed order
  would cost, from the rule pass the run itself runs. `skippable` says what
  each of the two levers would save, counted over the tags that would
  otherwise reach the model; `lowDocument` falls back to a floor of three, so
  the page has a real number before anybody has moved anything.
  `extra.vocabularyRequests` is what proposing a new vocabulary adds on top.
- GET /api/duplicates/ai-review/estimate: the same for the review. It never
  scans — a scan is a walk over the whole archive — so it answers from the
  merge service's cached scan and says `needsScan: true` with `items: 0` and
  `basis: "guess"` when there is none. `extra` names the sweep's own requests
  and the excerpt reads, which are Paperless-ngx reads rather than model
  requests.
- Both refuse with 503 and name the reason: the review also looks at
  DUPLICATES_AI_REVIEW, which is the Duplicates page's switch and says nothing
  about Simplify tags; both look at whether a provider is configured.
- POST /api/simplify/order/propose takes `skipDecided`, `minDocuments` and
  `concurrency`; both AI review starts take `concurrency`. Out of range is
  clamped, not refused: a slider that sends 40 is the page's mistake, and
  refusing the whole run over it helps nobody. Absent means "as configured".
- The new request fields are declared inline next to the existing $ref, so
  schemas.js stays as it is and OPENAPI/openapi.json still describes them.
- tests/test-ai-run-cost.js grows from six cases to thirteen: both estimates
  over tests/helpers/fake-paperless.js, the levers moving `items`, `needsScan`
  before a scan is cached, the 503 path for both reasons, a stopped run and a
  failed run writing their rows, an apply writing none, the four outcomes
  reaching the request log, and a real order run over the fake Paperless-ngx
  and tests/helpers/fake-openai.js that writes down what it cost and is then
  read back by the estimate as `basis: "run"`.
- A token field no provider reported now reaches the table as NULL. The
  contract's `saveAiRunStats` decides with `Number.isFinite(Number(value))`,
  and `Number(null)` is 0, so a null handed in as null was stored as a
  measured zero; the same trap sat in `recordRequest`. Both are worked around
  where this code hands the value over, with the reason written next to it.

Testing
node scripts/run-tests.js --all — 103 passed, 7 skipped, 0 failed (the runner
counts files; ai-run-cost went from 6 cases to 13).
node scripts/regen-openapi.js + git diff — no drift.
npx eslint / npx prettier --check on every changed file — clean.

Impact
Both estimates are read-only and cheap: no model request, no scan, no document
read. The order's tag list is cached for a minute, because the page asks again
on every move of a lever. Nothing changes for a page that sends the bodies it
sent before.

Upstream Status
Not applicable — this is next-only.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* refactor(simplify): the order says what its own options left out

Background
The closing log of a proposed order said "no AI provider is configured" for
any run that asked the model about nothing — which, now that a run can be told
to leave tags out, is also what a fully narrowed run looks like. And the
result carried no count of what the model was actually asked about, although
that is what the next estimate divides by.

Changes
- proposeOrder logs how many tags its own options left out, separately from
  the line about a missing provider, which now only fires when there was
  something to ask and nobody to ask.
- Its result carries `items` and `itemsByRule`, the two numbers ai_run_stats
  files the run under, so a caller that does not watch the job can read them
  too.
- Its JSDoc names the three options and the two new control channels.

Testing
node scripts/run-tests.js --all — 103 passed, 7 skipped, 0 failed.
npx eslint / npx prettier --check — clean; no OpenAPI drift.

Impact
Log wording and two added fields on a return value; no behaviour changes.

Upstream Status
Not applicable — this is next-only.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): the plan, the stack and the cost of a run

Background
----------
The Duplicates page had become a control panel: two option rows, four stat
tiles, a sort bar, and then a flat list of nine-column group cards as the unit
of review. A scan of 214 objects answered with dozens of cards that all read
"94 %", "95 %", "96 %", and the one thing the page never said was what
anything costs. A review was "something is running"; a merge was a button.

The distinction that was missing runs through the whole feature: asking costs
tokens, applying costs writes. Round 13 puts three surfaces on the page that
say so.

Changes
-------
The plan (views/duplicates.ejs, public/js/duplicates.js). The default result
of a scan is now four baskets of sentences built from the kit in
public/css/review.css:

  * "The same thing, plainly" — same name, or at or above 0.95. Collapsed
    behind its own count and a "Show them".
  * "The model says it is the same" — a verdict of `same` the model is sure
    about. Expanded, one sentence per group ("rechnungen folded into Rechnung
    — 37 of 486 documents move, the same name") with a quiet "Not the same"
    that drops it.
  * "I need a word from you" — unsure, below the sensitivity, or carrying a
    warning only a person can settle. Amber, one question each with three real
    answers, and the one that writes carries what it writes.
  * "Leftovers" — the unused objects, as one basket line over the table that
    already deletes them.

  planBasketOf() is pure and the ask basket is its floor: a group nothing
  settled is a question, never a proposal that slipped past every rule. A
  verdict of `different` is an answer — the group stays as it is and is
  counted in the header sentence instead of put in a basket.

  Above the baskets a header card: one sentence of totals, a ledger of what
  the last review cost (requests, tokens, seconds, 0 writes) with the token
  split, and stacked buttons that carry their own price. The card list, the
  sort bar and the selection bar are unchanged and fold away behind "Show
  every group"; every button on the plan delegates to the card the scan built,
  so there is one merge request, one log and one undo as before.

The stack. One pair per screen for the ask basket: a run bar with the position
and a ghost offer to take the obvious ones in one go, a .zr-decision card with
the two sides, each side's documents, matching rule and up to three document
titles, the model's own sentence, the rule warning as an amber checkbox ticked
by default, a .zr-consequence naming what merging writes, three buttons and
Enter/Esc/L bound on the container and never inside a field. A group of more
than two members keeps its per-member ticks and its target stays choosable. A
footer tallies the decisions and takes the last one back — a merge through the
log route, a "keep both" through the dismissals, a "decide later" by stepping
back.

The cost layer. Both run buttons now open a preflight through the kernel
dialog: what the run actually does with a price per step, what it costs with
the ledger, the split and one honest line about `basis`, what it changes
(nothing), and the levers — sweep, excerpts, sensitivity and lanes — each
priced, each re-asking the estimate and rewriting the numbers and the primary
button's .zr-btn__sub. `needsScan` makes the dialog say so and offer to do
both. The progress panel became the run meter around the bar it already had:
position and time left, tokens spent against the estimate and the rate, the
request in flight against the token budget, the prompt/answer/thinking split,
and a .zr-reqlog of the last requests where an empty or failed one says in
words what it cost for nothing. Stop says what stopping keeps. A batch merge
became a live checklist: one row per group, the one being written, the rest
waiting, a failure with what Paperless-ngx said and a "Try it now", over the
line that this step asks no model and that the document scan would refuse it.
"Merge selected", "Merge by hand", "Delete selected" and every card's Merge
button gained a consequence line naming documents, deletions, whether a model
is asked and whether it can be undone.

The estimate endpoint is built beside this page. fetchRunEstimate() is the one
seam: it asks GET /api/duplicates/ai-review/estimate and falls back to
localRunEstimate(), the same arithmetic as services/aiRunEstimate.js with none
of its measurements, which reports `basis: 'guess'` — and the dialog says so
in words rather than dressing a guess up as a measurement.

Testing
-------
npx eslint public/js/duplicates.js tests/test-duplicates-assistant-ui.js → 0
npx prettier --check --ignore-unknown <the four files> → 0
npx stylelint public/css/pages/duplicates.css → 0
node scripts/run-tests.js --all → 103 passed, 7 skipped, 0 failed (exit 0)
node scripts/regen-openapi.js && git diff --exit-code OPENAPI/openapi.json → 0

tests/test-duplicates-assistant-ui.js grew from 3 cases to 23: which basket
every kind of group lands in, the four baskets rendered from a scan fixture
with the empty ones and a group of three, the sentence each kind of line is
built into, the decision card with its samples, its amber copy offer and its
keys, the preflight with `needsScan` both ways, a lever changing the numbers,
the run meter over a progress fixture with an empty and a failed request, and
the consequence line of every button that writes. The page was rendered end to
end through a throwaway Express server on port 3313; the browser behaviour
itself is not covered here, as the repository carries no DOM library.

Impact
------
The Duplicates page reads as an assistant rather than a control panel, and no
model-backed run or write starts without the page having said what it costs
first. Nothing was removed: the group cards, the unused table, the merge log,
the name mappings and the hidden pairs are all where they were, and
tests/test-duplicates-ui.js passes unchanged at 86 cases.

Upstream Status
---------------
Fork-only. Duplicate detection, the AI review and both of this round's
surfaces do not exist in clusterzx/paperless-ai.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(simplify): the plan, the stack and the cost of every run

Background

The Simplify tags page had become a control panel: five stat tiles, two
filter rows, a couple of dozen group cards and a nine-column table, all on
screen at once, and a model-backed run that said nothing about what it would
cost until it was over. The one distinction that matters on this page —
asking costs tokens, applying costs writes — was invisible; both showed up as
"something is running".

Round 13 replaces the default with three surfaces, built on the shared review
kit of the contract commit (public/css/review.css, layer components).

Changes

views/simplify.ejs
  - The view segment reads Plan | Table. The data name of the first position
    stays `groups`, so every route, script and test that knows it still works.
  - New: #simPlan (header card #simPlanHead plus the baskets #simBaskets) and
    #simStack (#simStackBar, #simStackCard, #simStackFoot), a section with
    tabindex="-1" so its keys can be bound on it.
  - The progress panel becomes the run meter: #simRunbar, #simRunLedger,
    #simRunTokens, #simRunLive and #simReqLog under the existing bar, and the
    Stop button gains a .zr-btn__sub (#simStopSub).
  - New #simApplyChecklist beside the apply result.
  - "Apply all accepted" becomes a stacked button with its own price line
    (#simApplyAcceptedSub).
  - Round 12's group cards, their three filters and the five counts move into
    a closed <details> (#simGroupsBlock). Every id they carried is unchanged.

public/js/simplify.js
  - The plan: planBaskets() sorts the proposals into rule / sure / ask / keep,
    htmlProposalSentence() writes one sentence per proposal with the names in
    bold and the evidence behind the dash, htmlBasket() renders a bucket —
    collapsed with "Show them" for the rule and keep baskets, capped at ten
    with "Read the other N" for the sure one, questions with their real
    answers as buttons for the ask one. htmlPlanHead() carries the totals
    sentence, the ledger of what the proposal cost with its .zr-tokenbar
    split, the ledger of what running it costs, and the stacked primary
    button that runs it.
  - The stack: htmlStackBar(), htmlDecision() and htmlStackFoot(). One card
    per proposal with the type as a select limited to the vocabulary, the
    topics as chips plus an input, the model's sentence in .zr-decision__note,
    the evidence with the overwrite choice as two radios, a .zr-consequence
    above three buttons, and Enter / Esc / L bound on the stack container and
    never while an input, select or textarea has the focus. Nothing in the
    stack reaches Paperless-ngx; it calls the existing accept endpoint and
    keeps an Undo for the last decision.
  - The cost layer, before a run: askPreflight() fills the kernel's
    confirmDialog with four numbered steps and their prices, the ledger with
    the token split and one honest line about where the numbers come from
    (basis run / model / guess), the free consequence, and the levers — skip
    the decided tags, only tags on at least three documents, and 1/3/5/8
    lanes. Every lever re-asks the estimate and redraws the numbers including
    the primary button's own second line. The levers reach the start call as
    skipDecided, minDocuments and concurrency.
  - The cost layer, while it runs: renderRunMeter() reads the progress shape
    of the contract commit — the .zr-runbar with its position and ETA, tokens
    so far against the estimate with the rate, the .zr-tokenbar split from
    promptTokens / completionTokens / thinkingTokens, the request running now
    against tokenBudget, and a .zr-reqlog of requestLog where `empty` and
    `failed` are warn rows with a sentence that says what happened.
  - The cost layer, afterwards: an apply is a checklist — done rows with
    their seconds, the ones in flight, the rest waiting, a failure in red
    with what Paperless-ngx said and a "Try it now" — headed "0 tokens — this
    step never asks the model".
  - planWrites() is the one place the page promises writes, and every button
    that writes carries a .zr-consequence or a .zr-btn__sub naming documents,
    deletions, whether a model is asked and whether it can be undone.
  - The apply route is named once; both callers go through applyTags().

public/css/pages/simplify.css
  - One @layer pages block still, extended with sim- classes that place the
    kit rather than redefining it: the header card, the stack, the preflight
    blocks, the run meter slots, the apply checklist and the group block.
    Phone rules stack the two ledgers and give every button a full row.

tests/test-simplify-assistant-ui.js
  - The four contract cases are unchanged. Thirteen more render simplify.ejs
    through the real shell and take the page's pure helpers out of the module:
    the four baskets including the empty ones, a sentence per action, the
    stack's markup and its keyboard bindings, the preflight's blocks and its
    levers moving the numbers, the run meter over a progress fixture with an
    `empty` request in the log, and the consequence of each writing button.

Testing

  npx eslint views/simplify.ejs public/js/simplify.js \
    public/css/pages/simplify.css tests/test-simplify-assistant-ui.js  -> 0
  npx prettier --check --ignore-unknown <the same four>                -> 0
  npx stylelint public/css/pages/simplify.css                          -> 0
  node scripts/run-tests.js --all       -> 0 (103 passed, 7 skipped, 0 failed)
  node scripts/regen-openapi.js && git diff --exit-code OPENAPI        -> 0

The suite counts files, not cases: test-simplify-assistant-ui grew from 4 to
17 cases inside the one file it already had, so the file count stays at 103.
test-simplify-ui.js, which asserts the ids and the wording of rounds 10 to 12,
passes unchanged with 45 cases.

Impact

No API surface moved, so OPENAPI/openapi.json is untouched. Every endpoint the
page already called is still called, on the same route, with the same body —
the order start call only gains three fields a build without them ignores.
GET /api/simplify/order/estimate does not exist on this branch yet; the page
asks for it behind one function, fetchOrderEstimate(), and falls back to
localOrderEstimate(), which does the same arithmetic as
services/aiRunEstimate.js over what the page already knows and reports
basis 'guess'. When the route lands, the fallback stops being reached.

Upstream Status

Not applicable — this is a fork-only surface. clusterzx/paperless-ai has no
Simplify tags page.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* fix(review): an unreported token is not a measured zero, and the bar shows the whole run

Background
Two seams between the three parts of round 13, found while checking them
against each other rather than against their own briefs.

The first is mine, from the contract commit: both `nullable` helpers went
through `Number(value)`, and `Number(null)` is 0. A provider that reports no
prompt tokens — Ollama on some builds, any endpoint that streams without a
usage chunk — would have been written down as a run that asked for free, and
the next estimate would have believed it.

The second is the one the pages could not see coming. `progress.thinkingTokens`
is the request being answered right now: the streaming code fills it and clears
it when the request ends. Both pages drew the third segment of their token bar
from it, so the reasoning would have collapsed to nothing every time a request
finished, and the bar would have lied about where a run's tokens went.

Changes
- models/document.js and services/duplicateReviewJobService.js: null and
  undefined survive as null in saveAiRunStats and recordRequest. A zero that
  was actually reported still counts as zero.
- services/duplicateReviewJobService.js: the progress carries thinkingTotal,
  the run's reasoning so far, set wherever the running totals are set.
  thinkingTokens keeps its meaning as the request in flight.
- public/js/simplify.js and public/js/duplicates.js draw the run's token split
  and the plan's ledger from thinkingTotal.
- tests/test-ai-run-cost.js: an unreported token stays null through both
  helpers, and two recorded requests add up to a running total that differs
  from the live field. The two page tests carry both fields in their progress
  fixtures, the way a real event does, and the duplicates one now asserts that
  the meter does not read the live field.

Testing
node scripts/run-tests.js --all -> 103 passed, 7 skipped, 0 failed. ESLint,
Prettier and stylelint clean on every file of the round; regen-openapi leaves
no drift.

Impact
No API change. A run that reports nothing now stores nulls rather than zeros,
which is what the estimate already expected to read.

Upstream Status
Fork-only; the Duplicates and Simplify features do not exist upstream.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* fix(review): a basket's note belongs under its title, and round 13 in the changelog

Background
Seen in the browser rather than in a test: the title and the note of a basket
are two spans in one cell, and without a display they ran into each other —
"Clear as day — 11 tagsCompounds a rule already covers." The note's margin did
nothing for the same reason. The styleguide had it too, so both pages
inherited it faithfully.

Changes
- public/css/review.css: .zr-basket__title and .zr-basket__note are blocks.
- config/changelog.js: six entries for round 13 in the current release block,
  next to rounds 10 to 12.

Testing
node scripts/run-tests.js --all -> 103 passed, 7 skipped, 0 failed. stylelint
and eslint clean. Checked in a browser against the real chain, light and dark:
the note now sits under its title on both pages.

Impact
Cosmetic, and it lands on both pages and the styleguide at once.

Upstream Status
Fork-only; the Duplicates and Simplify features do not exist upstream.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
…and one promise (#346)

Background
The dialog before a run explained itself to death. Four labelled sections of
prose, a four-step list with a price beside each step, a ledger, a three-line
paragraph about where the numbers came from, two options that offered to skip
zero tags, and a primary button carrying "Start — 10 requests, about 3:51 min"
over "36.9k tokens · 3 lanes · 0 writes". Everything in it was true and nobody
would read it; next to it the cancel button looked like an afterthought.

What a person wants before pressing Start is how long this takes, what it
costs and whether it breaks anything — in that order and in that many words.

Changes
- public/css/review.css: a shared .zr-preflight block. Both pages had built
  the same dialog out of their own sim-preflight/dup-preflight classes; now
  there is one of it, in layer components, and the page stylesheets lost 2 kB
  of rules that only described the old layout.
- Both preflights are now: one sentence saying what the run asks about, a hero
  with the time as the big number, the requests and tokens under it and the
  token split as the only graphic, one short line on where the numbers come
  from, one green line that nothing is written, and everything adjustable
  folded away under Options. The primary button says Start.
- The time is rounded the way an estimate deserves: "under a minute", "6 min",
  never "about 3:51 min", which reads like a promise.
- A lever that would save nothing is left out rather than offered as "skip the
  0 tags you have already decided", and a token part that cost nothing is left
  out of the legend rather than printed as "0 answer".
- An Options fold the user opened stays open when a lever inside it redraws
  the dialog underneath.
- The Duplicates preflight is no longer a wide dialog: a wide box around one
  sentence and one number only spreads it thin.

Testing
node scripts/run-tests.js --all -> 103 passed, 7 skipped, 0 failed. ESLint,
Prettier and stylelint clean on every file touched. Seen in a browser against
the real chain, light and dark, on both pages, with the fold open and closed.

Impact
No API change, no behaviour change: the same estimate, the same levers, the
same run. The changelog entry of this feature is rewritten to describe what
the dialog does now, since it has not been released yet.

Upstream Status
Fork-only; the Duplicates and Simplify features do not exist upstream.


Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
…n and the voice of software (#350)

* feat(review): the ground for two modes and the sheet before a run

Background

The review pages still speak like a chatbot and still show every tool at
once. The maintainer asked for three things: software's voice (no first
person, no reassurance, no dashes), a calm sheet before a run where one bar
shows the tokens and the levers visibly move it, and a simple mode that
trusts the model behind which the full toolset waits as an advanced mode.

This commit is the ground both pages build on; the pages themselves follow
in their own commits.

Changes

- public/js/modules/review-sheet.js: the sheet before a run as one shared
  module. formatTokens, roughTime, laneRows and shares are pure; htmlSheet
  renders the body of the dialog (facts line, big number with the time,
  the bar as a share of the token limit, the requests side by side per
  lane, the levers as framework toggles, one fact line); updateSheet moves
  the numbers in place so the widths animate; bindSheet delegates the lanes
  and the levers.
- public/js/modules/review-mode.js: the simple/advanced mode of a page,
  kept per page in localStorage, stamped on the page root as data-mode,
  with the top bar button and the gate dialog that Advanced opens.
- public/css/review.css: .zr-sheet, .zr-lanes, .zr-tokenbar--limit and
  --mini, .zr-gate, .zr-modebtn, .zr-emptycard, .zr-resulthead,
  .zr-checklist and .zr-historyline; the bar's segments animate; the mode
  rule hides [data-advanced] in simple mode and [data-simple] in advanced.
- public/css/dialogs.css: .zr-dialog--sheet and .zr-dialog--gate, wider
  and rounder, the title without a rule and the buttons without a bar.
- public/js/zr.js: confirmDialog takes a className for such variants.
- views/partials/shell/body-open.ejs: an actions slot in the top bar.
- public/icons.svg: i-sliders.
- views/styleguide.ejs: the new pieces under Review surfaces.
- tests/test-review-sheet.js: the module and the mode helper.
- tests/test-review-voice.js: the voice as a guard over listed files;
  each page joins the list when it has been brought to the voice.

Testing

node scripts/run-tests.js --all: 105 passed, 7 skipped (server, poppler),
0 failed. ESLint, Prettier and stylelint clean on every touched file.

Impact

Nothing a page renders changes yet: the pages still use their own
preflight and baskets until their own commits switch them over. The
top bar gains an empty slot, the kernel dialog an optional class.

Upstream Status

Not applicable; this is next-only UI work.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(simplify): two modes, the sheet before a run and the result as checklists

Background

The maintainer asked for three things after round 13: the page should speak
like software, the sheet before a run should be one calm bar with the
levers that move it, and a simple mode should trust the model with one list
of what will happen and one button, while the whole toolset waits behind a
deliberate switch. He approved the mockup (B-Gate, B-Preflight-Simplify,
B-Simple-Simplify, B-Wording) and added: no dashes anywhere. The contract
commit f868f1d put the shared ground in place; this commit brings the
Simplify tags page onto it.

Changes

- views/simplify.ejs: one root with data-review-page="simplify" that starts
  in simple mode. Simple: the line "Split compound tags into a document type
  and topics.", the empty card with the split icon and "Simplify tags" (with
  "No model configured" and a dead button when there is no model), the
  result head, the checklist grid and the history line. Advanced: the order
  row ("Propose a new order", "Keep vocabulary" as a .zr-toggle, the apply
  of everything accepted), the Groups and Table segment, the groups with
  their tiles and filters, the table with its filters, search, per row
  editing, "Propose splits" and the apply bar, and the vocabulary. The run
  meter, the apply checklist, the apply result and the stack carry neither
  marker and belong to both. Every hint paragraph is gone; the Stop button
  has no second line. A marked element wears no class that the pages or
  modules layer gives a display, so the kit's mode rule cannot be outranked.
- public/js/simplify.js: mountModeSwitch in the top bar with the three gate
  lines. The round 13 preflight is replaced by the shared sheet: the model
  is built from the estimate the page already fetches (facts line, tokens,
  the run budget as the limit, the time at the lanes chosen, the basis) with
  the switches "Skip N already decided", "Only tags on 3+ documents" and, in
  simple mode, "Keep vocabulary", each only when it changes something and
  priced from that same estimate. Every lever updates runLevers, fetches a
  fresh estimate and moves the sheet in place; a stale answer is dropped.
  The estimate now carries the lanes and leaves the document floor out while
  that lever is off, so the lever keeps its count. The round 13 baskets and
  plan head are replaced by the result: the headline "N tags · M changes
  proposed", the cost of the last run with the mini bar or "Cost not
  recorded", and "Apply N · W writes" whose numbers follow local ticks.
  Five checklists (Split, Merge, Delete, Unsure, Unchanged) are sorted from
  the proposals: what stays goes to Unchanged, what was not sure to Unsure
  (unticked, dimmed, with its reason and "Review one by one" into the
  stack), the rest by action with a rule, model or spelling basis chip;
  eight rows each, then "N more". Apply turns the ticks into statuses (a
  few PATCHes at a time, stopping at the first failure) and runs the apply
  job of today with its progress. The history line reads the newest applied
  proposal and leads to the merge log for the undo. The stack decides with
  "Split", "Keep", "Later" and "Accept the N clear ones" and keeps the ticks
  in step. Token counts and times come from the shared module. Every string
  of the page is brought to the voice: no first person, no reassurance,
  numbers first, no dashes.
- public/css/pages/simplify.css: places the kit (the page column, the result
  card, the two column checklist grid with Unchanged across, the checklist
  cards, the run meter card) and drops the plan, basket and preflight rules.
- tests/test-simplify-assistant-ui.js: rewritten for the modes and their
  markers, the empty card, the sheet model from an estimate fixture, the
  result head following ticks, the five checklists from a proposals
  fixture, the apply, the history line, the stack, the running screen, the
  advanced page without hints and the retired surfaces.
- tests/test-simplify-ui.js: keeps the toolset checks and loses what no
  longer exists; strings follow the voice.
- tests/test-review-voice.js: the view and the page script join FILES.

Testing

npx eslint on the changed files: exit 0. npx prettier --check
--ignore-unknown on the changed files: exit 0 (the .ejs view has no
prettier parser, as in CI). npx stylelint public/css/pages/simplify.css:
exit 0. node scripts/regen-openapi.js with git diff on the spec: exit 0, no
endpoint changed. node scripts/run-tests.js --all: 104 passed, 7 skipped,
1 failed. The failure is tests/test-simplify-endpoints.js line 247, which
asserts the retired sub line of the page; with that one string changed to
the new line the file passes 31 of 31. It is outside this change's files
and is left to the lead. The page was also reviewed in a browser against a
mock server with 1,187 proposals and against the real app on a private port
with the fake Paperless-ngx and the fake model: empty card, sheet and its
levers, the run, the result, the stack, the apply, the history line, the
gate and the advanced page, in both themes and at 390px.

Impact

The Simplify tags page opens in simple mode. The endpoints, the job
service, the estimate and order services, the apply and undo paths, the
stack's keys and the run meter's ids are unchanged.

Upstream Status

Not applicable; this is next only UI work.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* test(simplify): the endpoint test reads the page's new sub-line

Background

Agent S brought the Simplify tags page to the voice; the endpoint test
still asserted the retired head sentence.

Changes

- tests/test-simplify-endpoints.js: expects the new sub-line.

Testing

node scripts/run-tests.js --all: 105 passed, 7 skipped, 0 failed.

Impact

None on the app.

Upstream Status

Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): a simple page and an advanced page, in the voice

Background

Round 14 gives the review pages two modes on the contract of f868f1d
(review-sheet.js, review-mode.js, review.css). The Duplicates page opened
on the round 13 plan with its baskets, a preflight dialog and hint
paragraphs everywhere, and spoke in the first person. The approved mockup
wants one card with one button, the shared sheet before a run, a result
that reads as a head with one button and three checklists, and the whole
toolset behind the gate, without prose.

Changes

views/duplicates.ejs
* One root with data-review-page="duplicates"; the kit stamps data-mode.
  Simple parts carry data-simple (the sub line, the empty card, the
  result), advanced parts data-advanced (the scan row, one wrapper around
  every tool). The run meter, the stack, the apply progress and the
  notice carry neither.
* Simple: the sub line, one zr-emptycard with "Find duplicates", and the
  result: zr-resulthead (headline, cost line, "Merge 34 · 61 writes"),
  the checklists and the zr-historyline with its Undo.
* Advanced: the scan row (Look at, Sensitivity loosest first, Threshold
  always visible, Include hidden pairs as a zr-toggle, Scan, Ask the
  model), Merge by hand, Every group with its count, sort and
  "Select ≥ 95%", the selection bar ("Ask the model about 6", "Merge 6"),
  Unused, History, Names mapped while processing, Hidden pairs and
  "Clear verdict memory". The stats tiles, the option checkboxes, the
  proposal row, the plan, the baskets and every hint paragraph are gone.
* The run meter keeps its markup and ids; Stop is one word.

public/js/duplicates.js
* mountModeSwitch with the three gate lines; the simple page is drawn
  from the cards of the advanced page on every change.
* "Find duplicates": without a model a scan of both kinds at the route's
  default threshold; with one the sheet, the scan and the run over
  everything, as the round 13 proposal did.
* The sheet replaces the preflight: confirmDialog with htmlSheet, a page
  model built from the estimate (after a scan, or the last run before
  one), the switches Titles as context, Excerpts with their reads and
  Synonym sweep with its price, three lanes by default. A lever redraws
  at once and asks the estimate again; Start keeps levers and lanes for
  the run, which sends them as withTitles, withExcerpts, semanticSweep
  and concurrency.
* Pure helpers read a scan into Proposed, Unsure and Unused rows (list,
  chip, reason, documents, writes), total the ticks for the one button,
  word the headline and the cost line, and build the history line from
  the merge log.
* The stack opens on the Unsure rows; a decision ticks or unticks the
  row, Later comes round again, Undo takes the last decision back.
  Nothing in the stack writes.
* Every string in the voice: no first person, no "AI", numbers first,
  labels as nouns or a verb with a number, no dashes. formatTokens and
  roughTime come from the contract module.

public/css/pages/duplicates.css
* Rewritten around the kit: positions the empty card, the result card
  and its lists, the scan row, the tools column and the drawers. No page
  rule sets display on a marked element, so review.css alone decides
  which mode shows. The plan, basket, preflight and stats rules are gone.

tests
* test-duplicates-assistant-ui.js describes the new surfaces: the modes
  and their markers, the gate, the empty card and when it gives way, the
  sheet model from an estimate fixture, the checklists from a groups
  fixture, the head following the ticks, the history line, the stack,
  the run meter, applying, and the advanced page without prose.
* test-duplicates-ui.js loses what no longer exists and keeps the rest,
  with the new strings.
* test-review-voice.js scans views/duplicates.ejs and
  public/js/duplicates.js as well (two lines appended to FILES).

Testing

* npx eslint on the changed scripts and tests: exit 0
* npx prettier --check --ignore-unknown on the changed files: exit 0
* npx stylelint public/css/pages/duplicates.css: exit 0
* node scripts/run-tests.js --all: 105 passed, 7 skipped, 0 failed
  (duplicates-ui 79 checks, duplicates-assistant-ui 32 checks)
* node scripts/regen-openapi.js and git diff on OPENAPI/openapi.json:
  exit 0, no endpoint changed
* Looked at in headless Chromium against a mock server with fixtures:
  empty card, gate, sheet before and after a scan, running screen, result
  with ticks moving the button, stack keys and Undo, batch merge and
  apply progress, history Undo, the guided verdict dialog, the threshold
  link, the path without a model, phone width and dark mode.

Impact

The Duplicates page opens simple and keeps the advanced page one click
and one gate away. Endpoints, the job and estimate services, the merge
and undo paths, the stack keys and the run meter markup are unchanged.

Upstream Status

Not applicable; this page exists only in this fork.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* refactor(review): the seams of round 14

Background

Two builders brought the two pages to the mockup on disjoint files. What
was left for the lead: the retired kit pieces, the mode rule's place in
the cascade, and the one link that crosses the pages.

Changes

- public/css/utilities.css: the rule that hides the other mode's parts
  moves next to .hidden, with !important, so no module or page display
  can outrank it (a page had to wrap its sub-line to dodge .zr-viewhead).
- public/css/review.css: .zr-basket*, .zr-preflight*, .zr-btn--stacked
  and .zr-btn__sub are gone; nothing places them any more. The header
  names the result head and the checklist in their place.
- views/styleguide.ejs: the basket and stacked-button examples are gone;
  the intro names what is there.
- public/js/duplicates.js: a link to #dupLog (the Undo of Simplify tags)
  opens the advanced page for this visit with the log unfolded; the
  stored mode stays.
- tests: the two assistant UI tests look for the mode rule in the
  utilities layer; the kit list no longer expects the retired pieces.

Testing

node scripts/run-tests.js --all: 105 passed, 7 skipped, 0 failed. ESLint,
Prettier and stylelint clean on every file the round changed; the OpenAPI
drift check is clean.

Impact

No endpoint changed. The styleguide loses two examples of things the app
no longer draws.

Upstream Status

Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* fix(review): the one button scans first, and the seams of the cross-check

Background

The cross-check of round 14 drove both review pages through both modes
against the smoke harness and held every screen against the approved
boards. On the Duplicates page in simple mode "Find duplicates" opened the
sheet before anything was scanned, so the one screen the maintainer
described most precisely showed "0 tokens", "under a minute", an empty bar
and no lane picture, titled "Scan, then ask the model". After an apply a
correspondent that was both a merge source and unused stayed on the page
as "Deutsche Bank · 0 documents · delete" with "Merge 0 · 1 write", because
the Unused list offered objects a group row already merged. The two pages
also drew the result head, the sub line, the checklist rows and the
history line slightly differently.

Changes

- public/js/duplicates.js: in simple mode the one button scans first, on
  the run meter's scan phase ("Comparing the names", a sliding bar, no
  Stop), then opens the sheet with the scan's numbers ("17 pairs · 6
  requests", the tokens, the lane rows). The card stays behind the sheet;
  Cancel leaves the page on the card, and the next scan or answer lets the
  result show again. The sheet is always titled "Ask the model". Without a
  model the button only scans and shows the result, as before. The
  advanced "Ask the model" is unchanged.
- public/js/duplicates.js: the Unused checklist leaves out every object
  that is a member of a group on the page, merged groups included, so no
  object is offered for a merge and a deletion at once, and nothing merged
  away is left behind as unused.
- public/js/duplicates.js: the file opened with a doubled comment opener.
- views/duplicates.ejs, public/css/pages/duplicates.css: the result head
  sits on a plain card as on Simplify tags (a module added its own 12px
  and a shadow); the sub line is 13px with 16px below it; checklist rules
  run edge to edge and "N more" starts where the names start, as on
  Simplify tags and the board.
- public/js/simplify.js: the history line carries the middle dot before
  Undo, as the board and the Duplicates page have it.
- public/css/review.css, tests/test-simplify-endpoints.js: the dashes left
  in comments are gone.
- tests: the assistant UI test describes the new order (scan on the meter,
  the sheet over the card, Start lets the run show), the card's states
  while held, the title, and the Unused overlap; the Duplicates UI test
  reads the order scan, sheet, model; the Simplify history line expects
  the dot.

Testing

node scripts/run-tests.js --all: 105 passed, 7 skipped, 0 failed. ESLint,
Prettier (with --ignore-unknown, as CI runs it) and stylelint are clean on
every file the round changed; the OpenAPI drift check is clean. The
browser pass (scratchpad smoke/browser-round14.js, fake Paperless-ngx and
fake model) ran the whole chain on both pages: card, scan, sheet with real
numbers, 1 · 3 · 5 · 8 moving rows and time, Cancel, Start, run meter,
result, ticks moving the button, the stack ticking a row, "N more", the
apply and its history line, the gate, reload in advanced mode and back to
simple without a gate. A second pass with DUPLICATES_AI_REVIEW=no showed
the scan without a sheet.

Impact

No endpoint changed. The simple Duplicates page asks nothing before its
free scan and prices the model on what the scan found.

Upstream Status

Not applicable; both pages exist only in this fork.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* fix(simplify): the arrow of a checklist row is quiet, as on Duplicates

Background

Both boards draw the arrow between a name and what it becomes in the faint
colour, and the Duplicates page does. The Simplify rows escaped it as part
of the name, so it stood at full strength, the one difference left between
the checklist rows of the two pages.

Changes

- public/js/simplify.js: htmlRowWhat() draws the arrow in its own span.
- public/css/pages/simplify.css: .sim-list__arrow takes the faint colour.
- tests/test-simplify-assistant-ui.js: the row markup it expects.

Testing

node scripts/run-tests.js --all: 105 passed, 7 skipped, 0 failed. ESLint,
Prettier and stylelint clean on the three files. The browser pass shows
the arrows of both pages in the same colour, light and dark.

Impact

A colour on one page; no behaviour changes.

Upstream Status

Not applicable; this page exists only in this fork.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* fix(review): what the cross-check found, decided

Background

The reviewer drove both pages through both modes and reported what did
not follow the mockup or broke a flow. The larger findings are decided
here; the rest is listed in the pull request.

Changes

- services/entityMatchAiService.js, services/aiRunEstimate.js: the
  estimate batches per kind as the job does (one request too few before);
  it prices the two context levers (extra.titlesTokens, a guess per pair,
  and extra.excerptTokens from the excerpt size) so the sheet can move
  the bar when a lever is turned off.
- public/js/duplicates.js: Titles as context and Excerpts carry their
  price and take it out of the prompt when off; a result nobody asked a
  model about has no cost line; the stack's way out says Back on both
  pages.
- views/simplify.ejs, public/js/simplify.js: the result head has a
  "Simplify tags" button for the next run, since the result stays while a
  proposal lives and Unsure rows could otherwise lock the simple mode.
- public/js/modules/review-sheet.js: updateSheet redraws the levers, so a
  label or a price follows the estimate too.
- public/css/review.css: a lever's price sits right behind its name; the
  text buttons of a result read in the brand colour, as the boards have
  them.
- public/css/pages/*.css: the simple page is one column of 1060px.
- config/changelog.js, README.md: the round's entries and one sentence.
- The last dashes in comments and styleguide examples.

Testing

node scripts/run-tests.js --all: 105 passed, 7 skipped, 0 failed. ESLint,
Prettier, stylelint clean on every touched file; OpenAPI drift check
clean. In the browser against the fake servers: the sheet opens with the
scan's numbers, Excerpts off takes 4k to 3.1k and Titles off to 2.6k with
the bar following, one lane draws one row; the Simplify result head shows
the button for the next run.

Impact

The estimate answers two more fields in extra; no endpoint shape changes
(the fields ride the existing object). No migration.

Upstream Status

Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* style(review): review-mode.js through Prettier

Background

CI's Prettier step runs over every file a PR changed; the contract commit
had checked a list that left this module out.

Changes

- public/js/modules/review-mode.js: formatted, nothing else.

Testing

Prettier over the PR's whole changed-file list: clean. ESLint clean.
node scripts/run-tests.js --all: 105 passed, 7 skipped, 0 failed.

Impact

None.

Upstream Status

Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* style(review): every action is a bordered button

Background

The text buttons of the kit (no border, muted text) read as links: "7
more", "Review one by one", Undo, Stop, Back, Later, the mode button in
the top bar. A link is not a way to cancel or undo anything, and the
maintainer asked that every button be recognisable as one.

Changes

- views/duplicates.ejs, views/simplify.ejs, public/js/duplicates.js,
  public/js/simplify.js, public/js/modules/review-mode.js: the ghost
  variant is gone from both pages and their modules; every action is the
  bordered secondary button, the one that writes stays primary.
- public/js/simplify.js: the Undo of an applied row in the advanced table
  is a bordered button that navigates, no longer a text link; the member
  fold of a group card carries the chevron the vocabulary fold has, so it
  reads as a fold and not as a line of text.
- public/css/review.css: the rule that coloured text buttons is gone; the
  mode button keeps its weight and colour on a bordered face.
- public/css/pages/simplify.css: the fold's chevron.
- views/styleguide.ejs: the review section shows the bordered buttons.
- tests: the two assistant UI tests guard that neither page, nor the two
  modules, draws a text button, and that no action of a page is a link;
  the assertions that pinned the ghost markup follow.

Testing

node scripts/run-tests.js --all: 105 passed, 7 skipped, 0 failed. ESLint,
stylelint clean; Prettier clean over the PR's whole changed-file list.
The reviewer's full browser flow (both pages, both modes, light, dark,
phone) ran through with no finding; every screen checked by eye.

Impact

Visual only. No endpoint, no data.

Upstream Status

Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
…ges have

Background

Since #345 to #350 the Duplicates page has no "Ask the AI" and no "AI
proposal" button any more: the simple mode asks the model through Find
duplicates, the advanced mode through Ask the model. The hint under the
AI review switch in Settings still named the old buttons, and so did the
API description of the verdict confidence and a few code comments. The
release notes of v2026.09.02 had grown to 31 entries over the feature
work and still described the old buttons and the old cards.

Changes

- views/settings.ejs: the hint of "Offer the AI review on the Duplicates
  page" says what switching it off does on the page as it is now.
- schemas.js, OPENAPI/openapi.json: the AiVerdict confidence description
  names the checklist instead of the AI proposal; spec regenerated.
- config/config.js, routes/setup.js, services/entityMatchAiService.js:
  comments name Find duplicates and Ask the model.
- config/changelog.js: v2026.09.02 in six entries: Duplicates, Simplify
  tags, the two modes, the model's review, the creation guard and the
  settings sections. The notes of earlier releases are unchanged.

Testing

- node scripts/run-tests.js --all: 106 passed, 6 skipped (need a running
  server), 0 failed.
- ESLint and Prettier clean on every touched file.
- node scripts/regen-openapi.js: only the one description changed.

Impact

Text only: a settings hint, one API description, comments and the What's
New entries of the coming release. No behaviour changes.

Upstream Status

Not applicable; next-only features.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Background

Before anything was run, both simple pages drew a 520px card with a
16px icon and one button, lost on a wide screen; the maintainer's word
for it was accurate. The mockup had only drawn the result; the start
was never designed.

Changes

- public/css/review.css: .zr-start replaces .zr-emptycard. It fills the
  column: the icon in a soft brand circle, the sentence of the page as
  the title, one line of what a run does, the one button at its large
  size, and a facts line under it.
- views/duplicates.ejs, views/simplify.ejs: the start as above. The
  sentence above it is drawn only with a result, since the start carries
  it as its title. Without a model the Duplicates line names only the
  scan; the Simplify start keeps its "No model configured" as the facts
  line.
- public/js/duplicates.js: the facts line reads the last run from the
  estimate when the page opens ("Last run 23 Sep · 17 pairs · 14k tokens
  · under a minute"); startFactsText() is pure and says nothing without
  a kept run. updateSimpleSurface() shows the sentence only with a
  result.
- public/js/simplify.js: renderSimple() shows the sentence only with a
  result.
- views/styleguide.ejs: the start replaces the empty card.
- tests: the start's markup on both pages, the pure facts line, and the
  two tests appended after each file's summary last time now run and
  count (one of them had been silently failing on the shell's own icon
  buttons; it looks at the page root now).

Testing

node scripts/run-tests.js --all: 105 passed, 7 skipped, 0 failed; the
two assistant UI files count 35 and 34. ESLint, Prettier, stylelint
clean. Rendered at 2000px, 390px, light and dark, on an empty data
directory and on one with a run behind it.

Impact

Visual, plus one estimate read when the Duplicates page opens with a
model configured (the route reads the DB and the scan cache only).

Upstream Status

Not applicable.


Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

Co-authored-by: Claude <noreply@anthropic.com>
…icks that need two signs (#353)

* feat(review): the ground for one page with the assistant on top

Background

The two modes are going: one page, the assistant as the zone at the top
(start, run, result), the whole toolset under it from the first second,
dimmed until a result exists, and the proposal landing as ticks in the
tools. What two builders need in common comes first.

Changes

- public/js/modules/review-guide.js: what each page says about itself,
  as data: the start, the steps of a run, a what and a why per phase,
  the lines that say how the tools are used after, one caption per tool.
- public/js/modules/review-assist.js: pure markup for the assistant
  (stepStates, htmlSteps, htmlSentence, htmlAssistStart, htmlAssistDone,
  htmlCaption) and setWorkspaceWaiting, the one switch that dims the
  tools under it.
- public/css/review.css: .zr-assist and its parts, .zr-steps, the
  sentence under a running headline, .zr-workspace--waiting with its
  note, .zr-module__caption.
- services/duplicateReviewJobService.js: a request record keeps its kind
  (pairs, names, tags) so a page can word its row; the progress carries
  a tally; freshProgress and REQUEST_KINDS are exported.
- services/entityMatchAiService.js: the judge's rows are about pairs,
  the sweep's about names; the tracker tallies what the model answered
  and reports it with every request; a "same" about a pair only the
  model proposed is not remembered (a "different" is).
- services/tagSimplifyService.js: the vocabulary's rows are about names,
  the order's about tags.
- schemas.js, OPENAPI/openapi.json: the tally on the progress.
- views/styleguide.ejs: the assistant in its three states, the steps,
  the waiting note, a caption.
- tests: tests/test-review-assist.js (7 cases, registered), the kind and
  the fresh tally in test-ai-run-cost.js, the memory rule in
  test-entity-match-ai-service.js, both modules in the voice test.

Testing

node scripts/run-tests.js --all: 106 passed, 7 skipped, 0 failed. ESLint,
Prettier, stylelint clean; OpenAPI regenerated.

Impact

The progress gains a nullable field, the request log rows a nullable
kind. Nothing a page draws changes yet.

Upstream Status

Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(simplify): the order pass reports a tally of what the model answered

Background
The one page of Simplify tags says while a run goes what the result is
turning into. The job progress carries a tally field since the contract
commit; the judge fills it for Duplicates, the order pass did not.

Changes
The order pass counts the rows of every request that answered by action
(split, merge, delete, keep) and counts a low confidence answer as unsure
whatever its action. The count starts as null and rides on the progress
patch of every request that answered; a request that answered nothing
leaves the count the page already shows.

Testing
tests/test-simplify-groups.js runs one order against a fake Paperless-ngx
and a stand in model, six tags one per request, one unreadable answer, and
reads the tally off the progress patches.

Impact
Additive. The progress of an order job carries tally; nothing reads it
yet but the Simplify page.

Upstream Status
Not upstream; Zettelrobbe only.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(duplicates): one page with the assistant on top

Background

After round 14 the maintainer asked for one page instead of two modes: the
assistant as the zone at the top, the whole toolset under it from the first
second, dimmed until a result exists, and the proposal of a run landing as
ticks in the tools. He also asked that the page say what happens during a
run and why, and that a pair only the model proposed ("Racun" and
"Physiotherapie", model "same", high) is never one click from a merge.

Changes

- views/duplicates.ejs: one page. The root is dup-page, keeps
  data-review-page="duplicates" and starts dimmed; its first child is the
  assistant (section#dupAssist[data-assist]) with the card the script draws,
  the run meter with two places for the steps and the sentence, and the
  notice. The scan row, merge by hand, every group, unused, the log, the
  mapped names, the hidden pairs and the verdict memory follow, each with
  one caption slot. No mode marks, no start card, no result head, no
  checklists, no history line. The meter is on every instance, because a
  scan runs on it too; Stop only where a model runs.
- public/js/duplicates.js: the mode, the gate, the simple result and the
  history line are gone (initMode, renderSimple, updateSimpleSurface, the
  checklist builders, mergeTicked, loadHistory, undoLast and their state).
  The assistant is drawn in three states by renderAssist: the start
  (htmlAssistStart, the facts line of the last run), the run meter (steps
  from the guide, the sentence with the tally, the tally in the ledger,
  "read · written · thinking" in the legend) and the result (htmlAssistDone:
  "54 scanned · 13 merges proposed · 4 unsure", the cost line with the mini
  bar only when a request was made, the guide's lines, "Review N unsure one
  by one" and "Merge N · W writes"). The numbers follow the ticks through
  updateSelectionBar. setWorkspaceWaiting dims the toolset on load, during a
  scan and a run, and wakes it with a result; a visit to #dupLog wakes it for
  the log. Every tool gets its caption from DUPLICATES_GUIDE.sections via
  htmlCaption.
- The tick on a group card is the proposal: isProposed ticks a group the
  scan settled (exact name, score at or above 0.95, a spelling rule the
  server applied) or one the model called "same" with high confidence on a
  spelling match; a semantic group (reason or member matchedBy semantic) is
  never ticked, and neither is a group with a question warning or a model
  that said different or unsure. renderGroups ticks by it, the verdict
  dialog reads it, and an unticked card shows its reason in one clause (the
  model's own sentence for a semantic pair, whose chip names the model's
  basis or "Synonym").
- The stack opens over the unsure groups; a decision sets or clears the
  tick on the card (setTick) and nothing else.
- The sheet: the sweep's price ends with "never ticked alone".
- The request log words rows by record.kind: "22 pairs · 8 answered",
  "300 names read · 2 groups proposed", "22 items · 8 answered"; "the rest
  asked again" only for a cut answer that fell short. The row in flight
  follows the phase.
- "Find duplicates" scans with what the scan row shows.
- public/css/pages/duplicates.css: the mode and the simple result are gone;
  the assistant, the guide places of the meter, the captions, the reason
  line and the memory row are placed; on a phone the assistant stacks.
- public/js/modules/review-guide.js (DUPLICATES_GUIDE only, every key
  kept): the words match the tick rule and the page as it is now.
- tests/test-duplicates-assistant-ui.js: rewritten for the one page (the
  view, the three states, the waiting toolset, the tick rule with the
  semantic case, the numbers, the sheet, the stack, the request log by
  kind, the tally). tests/test-duplicates-ui.js keeps its tool checks and
  drops the mode, the gate, the checklists and the history line.

Testing

node scripts/run-tests.js --all: 106 passed, 7 skipped, 0 failed.
ESLint, Prettier and stylelint clean on every changed file; OpenAPI
regenerated without a diff. Browser pass against the real app, a fake
Paperless-ngx and a fake model: start, scan, sheet with the sweep, run,
result, untick, stack, reload during a run, Stop, no model, 390 px and
2000 px, light and dark.

Impact

The Duplicates page has no mode any more. No endpoint changed. The page no
longer imports review-mode.js and places none of the retired kit classes.

Upstream Status

Not applicable.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* feat(simplify): one page with the assistant on top and the toolset under it

Background
Round 14 gave Simplify tags two modes. The maintainer found the shape
wrong, the run unexplained and the result one click away from a merge
the model only guessed at. One page now: the assistant is the zone at
the top, the whole toolset stands under it from the first second, dimmed
until a result exists, and the proposal of a run lands as ticks in the
tools where the work goes on.

Changes
views/simplify.ejs: no mode, no marks, no gate. The root keeps
data-review-page; its first child is the assistant wrapper (data-assist,
data-provider) holding the card, the run meter with its steps and
sentence slots, the apply checklist, the apply result and the stack.
Under it the order row with the view switch in its head, the groups, the
table and the vocabulary, each with one caption placeholder. The order
row lost its own run button, its keep switch and its apply button: the
run and the apply of everything accepted are the assistant's buttons,
Keep vocabulary is a lever of the sheet only.

public/js/simplify.js: the simple mode and the mode switch are gone
(checklists, local ticks, Apply ticked, Accept the clear ones, history
line). renderAssist draws the start (review-assist htmlAssistStart, facts
line "Last apply 23 Sep · 20 tags" or "No model configured"), the run
meter, the stack or the result (headline of tags, ticked changes and
open unsure ones, the cost of a run seen in this session, the guide's
lines, Review N unsure one by one, Apply N · W writes) and switches the
waiting workspace. When an order ends, every open proposal the model was
sure of or a rule settled is accepted once: whole groups through the
group decision when every tag they would take is sure, the rest through
the status route; low confidence stays open. An order that ended while
no page watched lands the same way once, as long as nothing of it was
decided. Group cards and member rows carry the tick: ticked is
accepted, unticking reopens, and every card a tag sits in follows in
place. The run meter shows the steps of an order (the vocabulary only
when the run proposes one), the guide's sentence with the tally of the
model's answers, the tally in the ledger, the legend read, written,
thinking, request rows worded by kind, and an apply bar counting tags.
The apply result carries its Undo to the merge log.

public/css/pages/simplify.css: the simple mode rules go; the assistant
column, its phone layout, the order head with the switch, the tick
columns and the outcome width come.

public/js/modules/review-guide.js: the SIMPLIFY_GUIDE wording says what
the model reads (names and counts, never a document), that a proposed
vocabulary replaces the saved one, where an apply is undone, and how the
ticks, the stack, the table and Skip are used. Every key stays.

Testing
tests/test-simplify-assistant-ui.js describes the new page: the view,
the three states from fixtures, the waiting switch, the headline from a
proposals fixture and after a reopen, the accept on finish rule and its
plan, the missed finish, the steps, the tally sentence, the rows by kind,
the stack, the apply and its Undo, the stylesheet and the voice.
tests/test-simplify-ui.js keeps its tool checks and drops the mode, the
gate and the checklists. node scripts/run-tests.js --all: 106 passed, 7
skipped, 0 failed. Driven in a browser against the fake Paperless-ngx
and the fake model at 1750, 2000 and 390 pixels, light and dark: start,
sheet, run, stop, reload during a run, result, untick, stack, table,
apply, no model.

Impact
The Simplify tags page only. No endpoint changed; the OpenAPI spec has
no drift. review-mode.js is no longer imported by this page.

Upstream Status
Not upstream; Zettelrobbe only.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* refactor(review): the seams of round 15

Background

Two builders brought the two pages to one page each. What was left for
the lead: what both pages did alike in their own stylesheets, the mode
that nothing imports any more, two counts the service got wrong, and
the tools that must not wait for a result.

Changes

- public/css/review.css: the assistant stacks on a phone and the run
  meter spaces its strip and sentence itself, for both pages (the pages'
  own rules for that are gone); the waiting rule looks through a wrapper
  marked data-tools and leaves a tool marked data-awake at full strength;
  the gate, the mode button, the start card, the result head, the
  checklist and the history line are gone with their media rules.
- public/js/modules/review-mode.js is deleted; public/css/utilities.css
  loses the mode rule; the voice test and the sheet test no longer read
  the module.
- views/duplicates.ejs: the tools wrapper is looked through and the log
  stays awake, so an Undo needs no scan first. views/simplify.ejs: the
  vocabulary stays awake, so it can be edited before a run.
- services/entityMatchAiService.js: a sweep row counts the groups it
  proposed, so the page can say "300 names read · 2 groups proposed"
  rather than "300 answered · the rest asked again".
- services/tagSimplifyService.js: a low-confidence keep counts as a keep
  in the tally, as the headline counts it after the run.
- views/styleguide.ejs: the retired examples are gone; the done state
  carries the mini bar.
- tests: the phone rule is asserted in the kit, the awake vocabulary in
  the view, the keep rule in the tally test.

Testing

node scripts/run-tests.js --all: 106 passed, 7 skipped, 0 failed. ESLint,
Prettier, stylelint clean; OpenAPI drift check clean.

Impact

No endpoint changed. A sweep row's answers field means groups proposed
from now on.

Upstream Status

Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* docs(review): the changelog and the README say one page

Background

Round 15 replaced the two modes with one page; the entry of round 14
that announced the modes would now describe something that is not
there.

Changes

- config/changelog.js: the mode entry gives way to three entries on the
  assistant, the running screen and the two-sign rule.
- README.md: the Duplicates paragraph describes the assistant instead of
  the modes.

Testing

The changelog module loads; Prettier clean.

Impact

None on the app.

Upstream Status

Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* fix(duplicates): the assistant says what a merge wrote

Background

The reviewer of round 15 drove the page end to end against the smoke
harness. Three things on the Duplicates page were plainly wrong. After
"Merge N · W writes" the checklist closed and the toast went after a few
seconds, and the assistant then read "0 merges proposed" with nothing
saying that five groups had just been merged. On a phone the stack pushed
the page sideways: the head of a pair carries up to five badges and did
not wrap. And a member verdict with "· remembered" ran under the right
edge of its card, cut off at "rei".

Changes

public/js/duplicates.js: a batch leaves its summary ("5 merged · 15
documents", or with the failures) in the notice of the assistant, where a
stopped run already reports, until the next scan or run clears it. An
alert whose title says everything no longer carries an empty paragraph.
A request row of one token says "1 token".

public/css/pages/duplicates.css: the head of a pair in the stack wraps
(a page rule over the kit's head, scoped to the stack); a member verdict
wraps inside its cell instead of overflowing.

tests/test-duplicates-assistant-ui.js: the notice after a batch, the
alert without a body, the singular token and the wrapping head.

Testing

Driven in Chromium against the private harness (ports 3330, 3931,
3932): Find duplicates with the sweep, the stack, Merge 5 · 15 writes
through the confirmation, the notice after it; the stack at 390px scrolls
sideways no longer. node scripts/run-tests.js --all: 106 passed, 7
skipped, 0 failed. ESLint, Prettier and stylelint clean on the changed
files; OpenAPI drift check clean.

Impact

Page only. No endpoint, service or kit file changed.

Upstream Status

Not applicable.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* fix(simplify): a stopped order says so, and the meter speaks like Duplicates

Background

The reviewer of round 15 drove the page end to end against the smoke
harness. After Stop, the assistant went straight to "25 tags · 11 changes
proposed · 0 unsure" and only a toast said the run had stopped; the tags
the model was never asked about stay as they are, so the headline alone
hides them. The Duplicates page says "Stopped early" with what the run
left. Three smaller seams between the two run meters: a request row read
"0:02" here and "2 s" there, the token legend left out "0 thinking" that
the Duplicates page and the brief show, and one token read "1 tokens". The
confirmation of Apply was titled "Apply 12 accepted" while the button said
"Apply 12 · 47 writes".

Changes

public/js/simplify.js: htmlStopNotice(job) words a stopped order as the
Duplicates page does ("Stopped after 4 of 5 requests · 5 tags not
asked", the token limit and the unwatched stop in their own words) and
the assistant shows it where the apply result goes, from a run started
here and from one a reload attached to. requestTime(ms) says "2 s" under a
minute and "1:24" from one on. The token legend names all three parts,
zero included. One token is "1 token". The Apply confirmation is titled
with the button's own label.

tests/test-simplify-assistant-ui.js: the stop notice in its three
wordings and both ways into it, the request time, the legend with a zero,
the singular token and the dialog title.

Testing

Driven in Chromium against the private harness (ports 3330, 3931,
3932): an order with one lane stopped at request 4 of 5 shows the notice
under the result; the meter at 390px and at 2000px in dark mode.
node scripts/run-tests.js --all: 106 passed, 7 skipped, 0 failed.
ESLint, Prettier and stylelint clean on the changed files; OpenAPI drift
check clean.

Impact

Page only. No endpoint, service or kit file changed.

Upstream Status

Not applicable.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

* fix(review): what the cross-check found, decided

Background

The reviewer drove both pages through all three states and listed what
did not follow the mockup, the brief or the person. The findings that
break a flow and the small deviations are decided here; the rest is
listed in the pull request.

Changes

- views/duplicates.ejs: the scan row stays awake before the first run;
  Find duplicates scans with what it says, so it must be settable.
- public/js/duplicates.js: a targeted run ("Ask the model about N")
  answers only the named groups; every other group keeps the verdict it
  had, and with it its tick, and the cost line keeps the full run
  (followReviewJob carries the flag, the job's own options carry it after
  a reload). While a run goes the scan's cards do not show under the
  meter. The stack card says why a group is unsure, a warning included.
- services/entityMatchAiService.js: a spelling rule is named by its
  label where a person reads it ("settled by the spelling rule: legal
  form"); RULE_LABELS is exported.
- services/tagSimplifyService.js, public/js/simplify.js: the
  vocabulary's row counts what it proposed ("300 names read · 7
  proposed"); the tally names the keeps too, so a run that only keeps is
  not an empty run.
- public/js/modules/review-guide.js: the Simplify guide names the way to
  a new run ("Propose order again", "Propose from tags").
- public/css/review.css: on a phone the button that writes sits at the
  bottom, as the comment said; the head of a decision card wraps (the
  page rule for that is gone).
- tests follow: the rule label, the targeted flag, the decision card's
  helpers, the keep in the tally, the names row.

Testing

node scripts/run-tests.js --all: 106 passed, 7 skipped, 0 failed. ESLint,
Prettier, stylelint clean; OpenAPI drift check clean. In the browser
against the fake servers: the scan row is live before any run; after a
full run and a targeted run about one group, the headline still counts
six proposed and every other card keeps its verdict.

Impact

No endpoint changed. A vocabulary row's answers field means words
proposed from now on.

Upstream Status

Not applicable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A7nsABNdgZhMpkHpFwaXpV

---------

Co-authored-by: Claude <noreply@anthropic.com>
@admonstrator admonstrator self-assigned this Sep 24, 2026

@github-advanced-security github-advanced-security AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CodeQL found more than 20 potential problems in the proposed changes. Check the Files changed tab for more details.

@admonstrator
admonstrator merged commit d4dcf42 into main Sep 24, 2026
8 of 9 checks passed
@admonstrator
admonstrator deleted the nightly branch September 24, 2026 16:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants