Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
refactor([issue-2800]): extract shared taxonomy-tally/render engine for LI leaves
[._.]/ Adam Eivyc7f441b1c538
diff --git a/server/lib/README.md b/server/lib/README.mdindex 73ef17f0c2..c42a1e90d9 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -202,6 +202,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `htmlToText.js` | Shared HTML → plain-text converter. `htmlToText(html, { extraEntities?, paragraphBreak?, collapseSpaces? })` — strips script/style/head/noscript blocks, converts `<br>`/block closes to newlines, strips remaining tags, decodes entities via `decodeXmlEntities`, collapses 3+ newlines, trims. Options preserve caller-specific output (Gmail: `paragraphBreak: '\n\n'` + `collapseSpaces`; SongBook import: defaults — space runs preserved for tab alignment). || `jsonExtract.js` | Pull JSON blocks out of LLM responses. || `taskParser.js` | Parse `TASKS.md` format. |+| `taxonomyTally.js` | Generic taxonomy tally + top-N-line render engine shared by the two Layered Intelligence leaf taxonomies (`services/layeredIntelligenceRejections.js`, `layeredIntelligenceExecutionFailures.js`). `normalizeToken(value)` (lowercase + separator-collapse for label/category matching); `formatTaxonomyToken(token, labels)` (gloss-map render, nullish→'', unglossed passthrough); `tallyTaxonomy(records, {predicate, select, vocabulary, sentinel, field})` → three-bucket `{entries, unknown, unclassified, diagnosed, total}` with commonest-first + taxonomy-order tie-break; `renderTallyLine(summary, {field, glossFn, limit, gapWording})` → one prompt line; `createTaxonomyTally(config)` binds a full config into `{summarize, format}`. Pure leaf — imports nothing from the LI graph. || `xmlEntities.js` | Shared dependency-free XML/HTML entity decoder. `decodeXmlEntities(str, extraEntities?)` — single-pass (double-decode-safe) decode of the five predefined named entities + decimal/hex numeric refs, with an optional caller-supplied extra-entity map (e.g. `{ nbsp: ' ', zwnj: '' }`). Unknown/out-of-range refs left untouched. Used by the Apple Health XML parser, Claude changelog feed, Pinterest RSS, generic feeds, and Gmail HTML-to-text. |## Curated static datadiff --git a/server/lib/index.js b/server/lib/index.jsindex 49a1a1e98b..322a50386b 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -183,6 +183,7 @@ export * from './vectorMath.js';export * from './htmlToText.js';export * from './jsonExtract.js';export * from './taskParser.js';+export * from './taxonomyTally.js';export * from './xmlEntities.js';// === Curated static data ===diff --git a/server/lib/taxonomyTally.js b/server/lib/taxonomyTally.jsnew file mode 100644index 0000000000..a4835cc185--- /dev/null+++ b/server/lib/taxonomyTally.js@@ -0,0 +1,134 @@+/**+ * Generic taxonomy tally + top-N-line renderer (extracted for #2800).+ *+ * Two Layered Intelligence leaf modules —+ * `services/layeredIntelligenceRejections.js` (proposal-REJECTION taxonomy, #2689)+ * and `services/layeredIntelligenceExecutionFailures.js` (execution-FAILURE+ * taxonomy, #2764 §1) — carried near-verbatim copies of the same counting ++ * rendering engine: a Map-counting `summarize*` with commonest-first sort and a+ * taxonomy-order tie-break over the three-bucket `{entries, unknown, unclassified,+ * diagnosed, total}` discipline, a `format*` top-N-line renderer, and a private+ * `normalizeToken`. The two would drift (a tie-break or gap-wording fix landing in+ * only one). This module owns that shared engine; each taxonomy module now keeps+ * only its vocabulary, gloss map, and classifier.+ *+ * A LEAF module by design: it imports nothing from the LI graph, so it does not+ * turn either taxonomy leaf into a cross-import of the other — both keep importing+ * only this small standalone helper. Pure, no I/O, no LLM call.+ */++/**+ * Normalize a raw token (a tracker label, stateReason, or error category) for+ * matching: lowercased, with separators collapsed so `not_planned`, `not-planned`,+ * `Not Planned`, and `test_failure` / `test-failure` / `Test Failure` all land on+ * the same key. A non-string yields '' (never matches a real key).+ */+export function normalizeToken(value) {+ return typeof value === 'string' ? value.trim().toLowerCase().replace(/[\s_-]+/g, '-') : '';+}++/**+ * Render one taxonomy token as prose via a gloss map. An unglossed token passes+ * through unchanged; a nullish (unclassified) input renders as '' — mapping it onto+ * a sentinel would invert the taxonomy's central rule by dressing "not classified"+ * up as "classified, and we found nothing".+ */+export function formatTaxonomyToken(token, labels) {+ if (!token) return '';+ return labels[token] || token;+}++/**+ * Tally a taxonomy across a record set, applying the three-bucket discipline the two+ * LI taxonomies share.+ *+ * Config:+ * - `predicate(record)` — is this record part of the population being diagnosed?+ * (a non-merged resolved proposal; a failed execution). Records that fail it, and+ * nullish records, are skipped.+ * - `select(record)` — reads the stored classification token off a population record.+ * - `vocabulary` — the REAL-diagnosis tokens; its order is also the tie-break order.+ * - `sentinel` — the "we looked and found nothing" token (counted as `unknown`, a+ * MEASURED gap — never a finding).+ * - `field` — the key name each entry carries the token under (`reason` / `category`).+ *+ * Returns `{ entries, unknown, unclassified, diagnosed, total }`:+ * - `entries` — `[{ [field], count }]` of REAL diagnoses only, commonest first,+ * ties broken by `vocabulary` order (stable regardless of record+ * ordering).+ * - `unknown` — records holding the sentinel: a MEASURED gap.+ * - `unclassified` — records whose stored token is absent OR not in `vocabulary`+ * (pre-field, or a token from a newer version): an UNMEASURED gap.+ * - `diagnosed` — sum of `entries`.+ * - `total` — the full population (`diagnosed + unknown + unclassified`).+ *+ * `unknown`/`unclassified` stay OUT of `entries` so they can't crowd real diagnoses+ * out of a caller's top-N list — they measure missing data, they are not findings.+ */+export function tallyTaxonomy(records, { predicate, select, vocabulary, sentinel, field }) {+ const counts = new Map();+ let unknown = 0;+ let unclassified = 0;+ for (const record of Array.isArray(records) ? records : []) {+ if (!record || !predicate(record)) continue;+ const token = select(record);+ if (token === sentinel) { unknown += 1; continue; }+ // Absent OR unrecognized: both mean we hold no valid diagnosis for a record that+ // demonstrably belongs to the population.+ if (!vocabulary.includes(token)) { unclassified += 1; continue; }+ counts.set(token, (counts.get(token) || 0) + 1);+ }+ const entries = [...counts.entries()]+ // Commonest first; ties broken by taxonomy order so the output is stable rather+ // than dependent on Map insertion (i.e. on record ordering).+ .sort((a, b) => b[1] - a[1] || vocabulary.indexOf(a[0]) - vocabulary.indexOf(b[0]))+ .map(([token, count]) => ({ [field]: token, count }));+ const diagnosed = entries.reduce((n, e) => n + e.count, 0);+ return { entries, unknown, unclassified, diagnosed, total: diagnosed + unknown + unclassified };+}++/**+ * Render a tally (the output of `tallyTaxonomy`) as one prompt line: the commonest+ * `limit` diagnoses, glossed, followed by whichever gaps are non-zero.+ *+ * Returns '' ONLY when the population is empty (`total === 0`), so a caller may safely+ * read '' as "there is nothing to explain". It must never fall silent merely because+ * the population is undiagnosed: a report that names a non-zero count and then stays+ * quiet about why is exactly the blindness these taxonomies exist to remove.+ *+ * Config:+ * - `field` — the entry key holding the token (must match `tallyTaxonomy`'s `field`).+ * - `glossFn(token)` — renders a token as prose.+ * - `gapWording` — `{ unknown(n, total), unclassified(n, total) }`, each returning the+ * gap clause for that bucket. Both taxonomies phrase `unclassified` the same but+ * `unknown` differently ("no recorded reason" vs "no recognized cause").+ */+export function renderTallyLine(summary, { field, glossFn, limit = 3, gapWording }) {+ const { entries, unknown, unclassified, total } = summary;+ if (total === 0) return '';+ const listed = entries+ .slice(0, limit)+ .map((entry) => `${glossFn(entry[field])} (${entry.count})`)+ .join('; ');+ // Name every non-zero gap: an undiagnosed share is a real, actionable fact about+ // the loop's own blind spot, and the honest line when it's all we have.+ const gaps = [+ unknown ? gapWording.unknown(unknown, total) : '',+ unclassified ? gapWording.unclassified(unclassified, total) : ''+ ];+ return [listed, ...gaps].filter(Boolean).join(' — ');+}++/**+ * Bind a full taxonomy config into the `{ summarize, format }` pair each taxonomy+ * module re-exports under its own domain names. `summarize(records)` returns the+ * three-bucket tally; `format(records, limit)` renders the top-N prompt line.+ *+ * Config keys are the union of `tallyTaxonomy`'s and `renderTallyLine`'s:+ * `{ predicate, select, field, vocabulary, sentinel, glossFn, gapWording }`.+ */+export function createTaxonomyTally({ predicate, select, field, vocabulary, sentinel, glossFn, gapWording }) {+ const summarize = (records = []) => tallyTaxonomy(records, { predicate, select, vocabulary, sentinel, field });+ const format = (records = [], limit = 3) => renderTallyLine(summarize(records), { field, glossFn, limit, gapWording });+ return { summarize, format };+}diff --git a/server/lib/taxonomyTally.test.js b/server/lib/taxonomyTally.test.jsnew file mode 100644index 0000000000..3c3c449a59--- /dev/null+++ b/server/lib/taxonomyTally.test.js@@ -0,0 +1,130 @@+import { describe, it, expect } from 'vitest';+import {+ normalizeToken,+ formatTaxonomyToken,+ tallyTaxonomy,+ renderTallyLine,+ createTaxonomyTally+} from './taxonomyTally.js';++// A tiny fixture taxonomy exercising the engine directly (independent of the two LI+// consumers, whose own suites pin the domain-facing contracts).+const VOCAB = ['alpha', 'beta', 'gamma'];+const SENTINEL = 'unknown-x';+const LABELS = { alpha: 'the alpha cause', beta: 'the beta cause', gamma: 'the gamma cause', [SENTINEL]: 'no known cause' };+const gloss = (t) => formatTaxonomyToken(t, LABELS);+const config = {+ predicate: (r) => r.kind === 'counted',+ select: (r) => r.token,+ field: 'token',+ vocabulary: VOCAB,+ sentinel: SENTINEL,+ glossFn: gloss,+ gapWording: {+ unknown: (n, total) => `${n} of ${total} with no known cause`,+ unclassified: (n, total) => `${n} of ${total} not yet classified`+ }+};+const rec = (token) => ({ kind: 'counted', token });++describe('normalizeToken', () => {+ it('lowercases and collapses separators', () => {+ expect(normalizeToken('Not_Planned')).toBe('not-planned');+ expect(normalizeToken('Test Failure')).toBe('test-failure');+ expect(normalizeToken(' git---conflict ')).toBe('git-conflict');+ });++ it('returns empty string for a non-string', () => {+ expect(normalizeToken(null)).toBe('');+ expect(normalizeToken(undefined)).toBe('');+ expect(normalizeToken(42)).toBe('');+ });+});++describe('formatTaxonomyToken', () => {+ it('glosses a known token and passes an unglossed token through', () => {+ expect(formatTaxonomyToken('alpha', LABELS)).toBe('the alpha cause');+ expect(formatTaxonomyToken('future-token', LABELS)).toBe('future-token');+ });++ it('renders a nullish input as empty, never a sentinel', () => {+ expect(formatTaxonomyToken(null, LABELS)).toBe('');+ expect(formatTaxonomyToken(undefined, LABELS)).toBe('');+ expect(formatTaxonomyToken('', LABELS)).toBe('');+ });+});++describe('tallyTaxonomy', () => {+ it('counts only population records, commonest first, and keys entries by field', () => {+ const { entries, diagnosed, total } = tallyTaxonomy(+ [rec('beta'), rec('beta'), rec('alpha'), { kind: 'ignored', token: 'beta' }],+ config+ );+ expect(entries).toEqual([{ token: 'beta', count: 2 }, { token: 'alpha', count: 1 }]);+ expect(diagnosed).toBe(2 + 1);+ expect(total).toBe(3);+ });++ it('breaks count ties by vocabulary order, independent of record order', () => {+ const forward = tallyTaxonomy([rec('gamma'), rec('alpha')], config);+ const reverse = tallyTaxonomy([rec('alpha'), rec('gamma')], config);+ expect(forward.entries.map((e) => e.token)).toEqual(['alpha', 'gamma']);+ expect(forward.entries).toEqual(reverse.entries);+ });++ it('separates the sentinel (unknown) from absent/unrecognized (unclassified)', () => {+ const { entries, unknown, unclassified, diagnosed, total } = tallyTaxonomy(+ [rec('alpha'), rec(SENTINEL), rec(null), rec('not-in-vocab')],+ config+ );+ expect(entries).toEqual([{ token: 'alpha', count: 1 }]);+ expect(unknown).toBe(1);+ expect(unclassified).toBe(2);+ expect(diagnosed).toBe(1);+ expect(total).toBe(4);+ });++ it('tolerates junk input and nullish records', () => {+ expect(tallyTaxonomy(null, config).total).toBe(0);+ expect(tallyTaxonomy([null, undefined, 'x'], config).total).toBe(0);+ });+});++describe('renderTallyLine', () => {+ it('returns empty ONLY when the population is empty', () => {+ expect(renderTallyLine(tallyTaxonomy([], config), config)).toBe('');+ });++ it('lists glossed diagnoses with counts, then names every non-zero gap', () => {+ const summary = tallyTaxonomy([rec('alpha'), rec('alpha'), rec(SENTINEL), rec(null)], config);+ const line = renderTallyLine(summary, config);+ expect(line).toBe('the alpha cause (2) — 1 of 4 with no known cause — 1 of 4 not yet classified');+ });++ it('caps listed diagnoses at the limit but still counts the gap over everything', () => {+ const summary = tallyTaxonomy([rec('alpha'), rec('beta'), rec('gamma'), rec(SENTINEL)], config);+ const line = renderTallyLine(summary, { ...config, limit: 2 });+ expect(line.split(' — ')[0].split(';').length).toBe(2);+ expect(line).toContain('1 of 4 with no known cause');+ });++ it('never falls silent on an all-undiagnosed population', () => {+ const summary = tallyTaxonomy([rec(null), rec(null)], config);+ expect(renderTallyLine(summary, config)).toBe('2 of 2 not yet classified');+ });+});++describe('createTaxonomyTally', () => {+ it('binds a config into a { summarize, format } pair', () => {+ const { summarize, format } = createTaxonomyTally(config);+ expect(summarize([rec('beta'), rec('beta')]).entries).toEqual([{ token: 'beta', count: 2 }]);+ expect(format([rec('alpha')])).toBe('the alpha cause (1)');+ expect(format([])).toBe('');+ });++ it('threads the limit through format', () => {+ const { format } = createTaxonomyTally(config);+ const line = format([rec('alpha'), rec('beta'), rec('gamma')], 1);+ expect(line.split(';').length).toBe(1);+ });+});diff --git a/server/services/layeredIntelligenceExecutionFailures.js b/server/services/layeredIntelligenceExecutionFailures.jsindex 1fff799c32..0ccd0d9516 100644--- a/server/services/layeredIntelligenceExecutionFailures.js+++ b/server/services/layeredIntelligenceExecutionFailures.js@@ -32,8 +32,20 @@* provider-outage category never lands here and never dents a domain's failure* shape. The remaining raw categories describe how LI's OWN implementation attempt* went wrong — which is what this taxonomy classifies.+ *+ * The tally + top-N-line render engine (the commonest-first sort with a+ * taxonomy-order tie-break, the three-bucket `{entries, unknown, unclassified,+ * diagnosed, total}` discipline, and `normalizeToken`) lives in the shared leaf+ * `lib/taxonomyTally.js` (#2800); this module supplies only the vocabulary, gloss+ * map, and classifier.*/+import {+ normalizeToken,+ formatTaxonomyToken,+ createTaxonomyTally+} from '../lib/taxonomyTally.js';+// The execution-failure vocabulary (#2764 §1). Stored on the outcome record and// rendered into the reasoner's prompt, so these tokens are a persisted contract:// rename one and old records fail the sanitizer's membership check and coerce to@@ -93,15 +105,7 @@ const EXECUTION_FAILURE_LABELS = {* "classified, and we found nothing".*/export function formatExecutionFailure(category) {- if (!category) return '';- return EXECUTION_FAILURE_LABELS[category] || category;-}--// Normalize a raw error-category token for matching: lowercased, with separators-// collapsed so `test_failure`, `test-failure`, and `Test Failure` all land on the-// same key.-function normalizeToken(value) {- return typeof value === 'string' ? value.trim().toLowerCase().replace(/[\s_-]+/g, '-') : '';+ return formatTaxonomyToken(category, EXECUTION_FAILURE_LABELS);}// Raw agentErrorAnalysis category → execution-failure taxonomy. Every key is one of@@ -226,26 +230,49 @@ export function classifyExecutionFailure({ success, errorCategory = null, valida* `unknown`/`unclassified` stay OUT of `entries` so they can't crowd real diagnoses* out of a caller's top-N list — they measure missing data, they are not findings.*/-export function summarizeExecutionFailures(outcomes = []) {- const counts = new Map();- let unknown = 0;- let unclassified = 0;- for (const o of Array.isArray(outcomes) ? outcomes : []) {- if (!o || o.executionOutcome !== 'failure') continue;- const category = o.failureCategory;- if (category === UNKNOWN_EXECUTION_FAILURE) { unknown += 1; continue; }- // Absent OR unrecognized (hand-edited, or a token from a newer version): both- // mean we hold no valid diagnosis for an execution that demonstrably failed.- if (!EXECUTION_FAILURE_CATEGORIES.includes(category)) { unclassified += 1; continue; }- counts.set(category, (counts.get(category) || 0) + 1);+// The shared tally + render engine, bound to the execution-failure taxonomy. The+// counting rules, commonest-first sort, taxonomy-order tie-break, three-bucket+// discipline, and top-N-line render live in `lib/taxonomyTally.js` (#2800); this+// module supplies only the population predicate, the stored-token accessor, the+// vocabulary/sentinel, the gloss, and the gap wording.+const executionFailureTally = createTaxonomyTally({+ predicate: (o) => o.executionOutcome === 'failure',+ select: (o) => o.failureCategory,+ field: 'category',+ vocabulary: EXECUTION_FAILURE_CATEGORIES,+ sentinel: UNKNOWN_EXECUTION_FAILURE,+ glossFn: formatExecutionFailure,+ gapWording: {+ // "2 of 3 failed with no recognized cause" is a real, actionable fact about LI's+ // own blind spot, and the honest line when it's all we have.+ unknown: (n, total) => `${n} of ${total} failed with no recognized cause`,+ unclassified: (n, total) => `${n} of ${total} not yet classified`}- const entries = [...counts.entries()]- // Commonest first; ties broken by taxonomy order so the output is stable rather- // than dependent on Map insertion (i.e. on record ordering).- .sort((a, b) => b[1] - a[1] || EXECUTION_FAILURE_CATEGORIES.indexOf(a[0]) - EXECUTION_FAILURE_CATEGORIES.indexOf(b[0]))- .map(([category, count]) => ({ category, count }));- const diagnosed = entries.reduce((n, e) => n + e.count, 0);- return { entries, unknown, unclassified, diagnosed, total: diagnosed + unknown + unclassified };+});++/**+ * Tally execution-failure categories across every FAILED-execution record. A+ * successful execution has nothing to explain, and a record that was never handed+ * off (executionOutcome null) never executed — neither is counted.+ *+ * Returns `{ entries, unknown, unclassified, diagnosed, total }` — the same shape,+ * and the same three-bucket discipline, as summarizeRejectionReasons:+ * - `entries` — `[{ category, count }]` of REAL diagnoses only, commonest first.+ * - `unknown` — classified `unknown-failure`: we looked, no signal explained+ * it. A MEASURED gap.+ * - `unclassified` — a failed execution with no valid category stored at all:+ * recorded before this field existed, or by a path that passed+ * no failure signal. An UNMEASURED gap — a different fact from+ * `unknown`, with a different remedy.+ * - `diagnosed` — records carrying a real diagnosis (sum of `entries`).+ * - `total` — every failed-execution record: the population being diagnosed.+ * `total === 0` means, and only means, "no hand-off has failed".+ *+ * `unknown`/`unclassified` stay OUT of `entries` so they can't crowd real diagnoses+ * out of a caller's top-N list — they measure missing data, they are not findings.+ */+export function summarizeExecutionFailures(outcomes = []) {+ return executionFailureTally.summarize(outcomes);}/**@@ -258,17 +285,5 @@ export function summarizeExecutionFailures(outcomes = []) {* about why is exactly the blindness this taxonomy exists to remove.*/export function formatExecutionFailures(outcomes = [], limit = 3) {- const { entries, unknown, unclassified, total } = summarizeExecutionFailures(outcomes);- if (total === 0) return '';- const listed = entries- .slice(0, limit)- .map(({ category, count }) => `${formatExecutionFailure(category)} (${count})`)- .join('; ');- // Name every gap: "2 of 3 failed with no recognized cause" is a real, actionable- // fact about LI's own blind spot, and the honest line when it's all we have.- const gaps = [- unknown ? `${unknown} of ${total} failed with no recognized cause` : '',- unclassified ? `${unclassified} of ${total} not yet classified` : ''- ];- return [listed, ...gaps].filter(Boolean).join(' — ');+ return executionFailureTally.format(outcomes, limit);}diff --git a/server/services/layeredIntelligenceRejections.js b/server/services/layeredIntelligenceRejections.jsindex 9a6e5fd4e6..ab9306faaa 100644--- a/server/services/layeredIntelligenceRejections.js+++ b/server/services/layeredIntelligenceRejections.js@@ -36,8 +36,20 @@* gap it closes. The fix therefore needs a disposition/state split here plus a* change to `deriveOutcome`'s merge-rate semantics (#2620's territory), so it is* deliberately left to a follow-up rather than bolted on. Tracked on #2689.+ *+ * The tally + top-N-line render engine (the commonest-first sort with a+ * taxonomy-order tie-break, the three-bucket `{entries, unknown, unclassified,+ * diagnosed, total}` discipline, and `normalizeToken`) lives in the shared leaf+ * `lib/taxonomyTally.js` (#2800); this module supplies only the vocabulary, gloss+ * maps, and classifiers.*/+import {+ normalizeToken,+ formatTaxonomyToken,+ createTaxonomyTally+} from '../lib/taxonomyTally.js';+// The rejection-reason vocabulary. Stored on the outcome record and rendered into// the reasoner's prompt, so these tokens are a persisted contract: rename one and// old records fail the sanitizer's membership check and re-classify (which is the@@ -101,15 +113,7 @@ const REJECTION_REASON_LABELS = {* "classified, and we found nothing".*/export function formatRejectionReason(reason) {- if (!reason) return '';- return REJECTION_REASON_LABELS[reason] || reason;-}--// Normalize a tracker token (label name or stateReason) for matching: lowercased,-// with separators collapsed so `not_planned`, `not-planned` and `Not Planned` all-// land on the same key.-function normalizeToken(value) {- return typeof value === 'string' ? value.trim().toLowerCase().replace(/[\s_-]+/g, '-') : '';+ return formatTaxonomyToken(reason, REJECTION_REASON_LABELS);}// Label → reason. Every key here must be a label that states a JUDGEMENT ABOUT THE@@ -325,26 +329,52 @@ export function classifyRejection({ outcome = null, stateReason = null, labels =* can't crowd real diagnoses out of a caller's top-N list — they measure missing* data, they are not findings.*/-export function summarizeRejectionReasons(outcomes = []) {- const counts = new Map();- let unknown = 0;- let unclassified = 0;- for (const o of Array.isArray(outcomes) ? outcomes : []) {- if (!o || (o.outcome !== 'rejected' && o.outcome !== 'abandoned')) continue;- const reason = o.rejectionReason;- if (reason === UNKNOWN_REJECTION_REASON) { unknown += 1; continue; }- // Absent OR unrecognized (hand-edited, or a token from a newer version): both- // mean we hold no valid diagnosis for a proposal that demonstrably didn't merge.- if (!REJECTION_REASONS.includes(reason)) { unclassified += 1; continue; }- counts.set(reason, (counts.get(reason) || 0) + 1);+// The shared tally + render engine, bound to the rejection taxonomy. The counting+// rules, commonest-first sort, taxonomy-order tie-break, three-bucket discipline,+// and top-N-line render live in `lib/taxonomyTally.js` (#2800); this module supplies+// only the population predicate, the stored-token accessor, the vocabulary/sentinel,+// the gloss, and the gap wording.+const rejectionTally = createTaxonomyTally({+ predicate: (o) => o.outcome === 'rejected' || o.outcome === 'abandoned',+ select: (o) => o.rejectionReason,+ field: 'reason',+ vocabulary: REJECTION_REASONS,+ sentinel: UNKNOWN_REJECTION_REASON,+ glossFn: formatRejectionReason,+ gapWording: {+ // "3 of 3 closed with no recorded reason" is a real, actionable fact about the+ // loop's own blind spot, and the honest line when it's all we have.+ unknown: (n, total) => `${n} of ${total} closed with no recorded reason`,+ unclassified: (n, total) => `${n} of ${total} not yet classified`}- const entries = [...counts.entries()]- // Commonest first; ties broken by taxonomy order so the output is stable- // rather than dependent on Map insertion (i.e. on record ordering).- .sort((a, b) => b[1] - a[1] || REJECTION_REASONS.indexOf(a[0]) - REJECTION_REASONS.indexOf(b[0]))- .map(([reason, count]) => ({ reason, count }));- const diagnosed = entries.reduce((n, e) => n + e.count, 0);- return { entries, unknown, unclassified, diagnosed, total: diagnosed + unknown + unclassified };+});++/**+ * Tally rejection reasons across every non-merged RESOLVED proposal. A pending+ * proposal is awaiting triage, not rejected, and a merged one has nothing to+ * explain — neither is counted.+ *+ * Returns `{ entries, unknown, unclassified, diagnosed, total }`:+ * - `entries` — `[{ reason, count }]` of REAL diagnoses only, commonest first.+ * - `unknown` — classified as `unknown-reason`: we looked and no signal+ * explained it. A MEASURED gap.+ * - `unclassified` — no valid diagnosis stored at all: written before the taxonomy+ * existed, or reconcile hasn't reached it yet. An UNMEASURED+ * gap — a different fact from `unknown`, with a different+ * remedy (reconcile it vs. enrich the signals).+ * - `diagnosed` — records carrying a real diagnosis (sum of `entries`).+ * - `total` — every non-merged resolved proposal: the full population being+ * diagnosed. `total === 0` means, and only means, "nothing has+ * been closed unmerged".+ *+ * The three buckets stay apart for the same reason the record field is three-valued:+ * collapsing them would either fabricate a diagnosis or hide the data gap this+ * metric exists to track. `unknown`/`unclassified` stay OUT of `entries` so they+ * can't crowd real diagnoses out of a caller's top-N list — they measure missing+ * data, they are not findings.+ */+export function summarizeRejectionReasons(outcomes = []) {+ return rejectionTally.summarize(outcomes);}/**@@ -358,17 +388,5 @@ export function summarizeRejectionReasons(outcomes = []) {* is exactly the blindness this taxonomy exists to remove.*/export function formatRejectionReasons(outcomes = [], limit = 3) {- const { entries, unknown, unclassified, total } = summarizeRejectionReasons(outcomes);- if (total === 0) return '';- const listed = entries- .slice(0, limit)- .map(({ reason, count }) => `${formatRejectionReason(reason)} (${count})`)- .join('; ');- // Name every gap: "3 of 3 closed with no recorded reason" is a real, actionable- // fact about the loop's own blind spot, and the honest line when it's all we have.- const gaps = [- unknown ? `${unknown} of ${total} closed with no recorded reason` : '',- unclassified ? `${unclassified} of ${total} not yet classified` : ''- ];- return [listed, ...gaps].filter(Boolean).join(' — ');+ return rejectionTally.format(outcomes, limit);}