@event4u/agent-config 14.13.0 → 14.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/.augment-plugin/marketplace.json +3 -3
  2. package/.augment-plugin/plugin.json +1 -1
  3. package/.claude-plugin/marketplace.json +1 -1
  4. package/CHANGELOG.md +116 -387
  5. package/dist/agent-src/commands/analyze/inbox.md +36 -0
  6. package/dist/agent-src/rules/code-comment-discipline.md +6 -0
  7. package/dist/agent-src/scripts/archive_completed_roadmaps.ts +6 -6
  8. package/dist/agent-src/scripts/guarded_baseline.ts +22 -7
  9. package/dist/agent-src/scripts/stubs_due.ts +118 -2
  10. package/dist/agent-src/scripts/update_roadmap_progress.ts +8 -8
  11. package/dist/agent-src/templates/agents/agent-project-settings.example.yml +1 -1
  12. package/dist/cli-delegate/cmd_conformance.js +38 -1
  13. package/dist/discovery/deprecation-report.md +1 -1
  14. package/dist/discovery/discovery-manifest.json +4 -4
  15. package/dist/discovery/discovery-manifest.json.sha256 +1 -1
  16. package/dist/discovery/discovery-manifest.summary.md +1 -1
  17. package/dist/discovery/dormancy-report.md +1 -1
  18. package/dist/discovery/orphan-report.md +1 -1
  19. package/dist/discovery/packs.json +2 -2
  20. package/dist/discovery/trust-report.md +1 -1
  21. package/dist/discovery/workspaces.json +2 -2
  22. package/dist/hooks/dispatch.js +1438 -711
  23. package/dist/mcp/registry-manifest.json +2 -2
  24. package/dist/mcp/server.json +2 -2
  25. package/dist/mcp/server.mjs +112 -17
  26. package/docs/guidelines/agent-infra/guarded-baseline.md +1 -1
  27. package/docs/guidelines/code-clarity.md +18 -0
  28. package/package.json +1 -1
  29. package/src/agent-src/scripts/archive_completed_roadmaps.ts +6 -6
  30. package/src/agent-src/scripts/guarded_baseline.ts +22 -7
  31. package/src/agent-src/scripts/stubs_due.ts +118 -2
  32. package/src/agent-src/scripts/update_roadmap_progress.ts +8 -8
  33. package/src/config/estate-count-budget.json +20 -1
  34. package/src/config/gate-coverage.yml +150 -0
  35. package/src/config/gate-violation-baselines.json +8 -3
  36. package/src/config/preamble-payload-budget.json +19 -11
  37. package/src/config/rule-stub-ceilings.json +14 -7
  38. package/src/scripts/_dispatch.bash +0 -4
  39. package/src/scripts/_lib/activation_ladder.ts +47 -3
  40. package/src/scripts/_lib/activation_receipt_producer.ts +341 -0
  41. package/src/scripts/_lib/adr_frontmatter.ts +26 -0
  42. package/src/scripts/_lib/candidate_pair_delta.ts +349 -0
  43. package/src/scripts/_lib/carrier_status.ts +118 -0
  44. package/src/scripts/_lib/cascade_stage_enumeration.ts +92 -0
  45. package/src/scripts/_lib/corpus_manifest.ts +726 -0
  46. package/src/scripts/_lib/delivery_arm_experiment.ts +18 -2
  47. package/src/scripts/_lib/estate_carrier_cases.ts +72 -0
  48. package/src/scripts/_lib/evaluation_cascade.ts +452 -0
  49. package/src/scripts/_lib/evolution_roi.ts +562 -0
  50. package/src/scripts/_lib/harness_evolution_guards.ts +10 -0
  51. package/src/scripts/_lib/lexical_shortlist.ts +215 -0
  52. package/src/scripts/_lib/llm_candidate_proposer.ts +461 -0
  53. package/src/scripts/_lib/llm_proposer_transport.ts +153 -0
  54. package/src/scripts/_lib/pathology_archive.ts +393 -0
  55. package/src/scripts/_lib/promotion_capability.ts +315 -0
  56. package/src/scripts/_lib/promotion_evidence.ts +414 -0
  57. package/src/scripts/_lib/promotion_review.ts +294 -0
  58. package/src/scripts/_lib/prompt_shape.ts +92 -0
  59. package/src/scripts/_lib/release_highlights.ts +70 -1
  60. package/src/scripts/_lib/release_material.ts +125 -2
  61. package/src/scripts/_lib/routing_corpus.ts +307 -0
  62. package/src/scripts/_lib/routing_index_input.ts +104 -0
  63. package/src/scripts/_lib/rule_injection.ts +22 -1
  64. package/src/scripts/_lib/semantic_noop.ts +167 -0
  65. package/src/scripts/activation_receipt.ts +258 -0
  66. package/src/scripts/ai_council/cross_exam.ts +128 -0
  67. package/src/scripts/ai_council/explain_route.ts +157 -0
  68. package/src/scripts/ai_council/information_gain.ts +293 -0
  69. package/src/scripts/ai_council/leakage_corpus.ts +385 -0
  70. package/src/scripts/ai_council/leakage_patterns.ts +453 -0
  71. package/src/scripts/ai_council/minority_retention.ts +171 -0
  72. package/src/scripts/ai_council/recouncil_savings.ts +299 -0
  73. package/src/scripts/ai_council/replay_route.ts +223 -0
  74. package/src/scripts/ai_council/reviewer_assignment.ts +279 -0
  75. package/src/scripts/ai_council/routing_training_row.ts +197 -0
  76. package/src/scripts/ai_council/synthesis_strategy.ts +159 -0
  77. package/src/scripts/check_adr_frontmatter.ts +4 -9
  78. package/src/scripts/check_estate_count.ts +205 -24
  79. package/src/scripts/check_release_highlights.ts +96 -13
  80. package/src/scripts/check_roadmap_trackable.ts +17 -2
  81. package/src/scripts/corpus_manifest.ts +235 -0
  82. package/src/scripts/evolution_lab.ts +181 -8
  83. package/src/scripts/hook_manifest.json +1 -1
  84. package/src/scripts/hook_manifest.yaml +28 -6
  85. package/src/scripts/hooks/comment_discipline_hook.ts +146 -0
  86. package/src/scripts/hooks/concern_registry.ts +2 -0
  87. package/src/scripts/hooks/turn_end_gate_hook.ts +9 -1
  88. package/src/scripts/language_mirror_hook.ts +14 -2
  89. package/src/scripts/lint_carrier_integrity.ts +820 -0
  90. package/src/scripts/lint_code_comments.ts +643 -0
  91. package/src/scripts/lint_plan_risk_register.ts +39 -19
  92. package/src/scripts/lint_promotion_paths.ts +779 -0
  93. package/src/scripts/llm_propose.ts +256 -0
  94. package/src/scripts/measure_delivery_sets.ts +361 -0
  95. package/src/scripts/measure_routing_signal.ts +307 -0
  96. package/src/scripts/model_rule_injection.ts +19 -3
  97. package/src/scripts/probe_council_retention.ts +495 -0
  98. package/src/scripts/release.ts +21 -37
  99. package/src/scripts/release_drill.ts +143 -0
  100. package/src/scripts/release_env.ts +35 -0
  101. package/src/scripts/release_publication.ts +84 -0
@@ -0,0 +1,153 @@
1
+ /**
2
+ * The metered transport for the LLM proposer arm — one provider, one call shape.
3
+ *
4
+ * `road-to-governed-evidence-production` step 2.1. Deliberately a SEPARATE file
5
+ * from `_lib/llm_candidate_proposer.ts`: the arm holds the role constraint and
6
+ * must stay transport-free so it can be exercised with a stub, and the transport
7
+ * holds the one thing a reviewer has to read whole before money moves.
8
+ *
9
+ * ## What this file may and may not do
10
+ *
11
+ * It may send a prompt and return the text that came back. It may not score,
12
+ * rank, filter, or select — and structurally it cannot: {@link GenerationResult}
13
+ * has no field that could carry a judgement, and this module never sees more
14
+ * than one request at a time. The narrowed park admits exactly this role; see
15
+ * `docs/contracts/metered-proposer-protocol.md`.
16
+ *
17
+ * ## The model per tier is PINNED TO A DATED ID, or refused
18
+ *
19
+ * A frozen execution protocol whose model is a floating alias is not frozen: the
20
+ * alias moves and a later run answers a different question. So {@link TIER_MODEL}
21
+ * carries dated ids only, and the `high` tier is deliberately `null` because no
22
+ * dated `claude-opus-4-1-*` id exists anywhere in this tree to pin it to.
23
+ * Requesting `high` therefore REFUSES with a message naming what has to be
24
+ * pinned first, rather than resolving an alias and calling the protocol frozen.
25
+ *
26
+ * `high` is reachable only through an `execution_failed` escalation
27
+ * (`_lib/evolution_roi.ts:128`), so a run that never hits a transport error
28
+ * never touches it.
29
+ *
30
+ * ## Nothing here has been executed
31
+ *
32
+ * As of the commit that adds it, this module has made zero live calls. Its
33
+ * request shape is proven by {@link describeRequest}, which returns exactly what
34
+ * would be sent without sending it, and by a unit test over that description.
35
+ * The live path is unexercised, and saying so is cheaper than implying a probe
36
+ * that the park forbids.
37
+ */
38
+
39
+ import { load_anthropic_key } from '../ai_council/clients.js';
40
+ import type {
41
+ GenerationRequest,
42
+ GenerationResult,
43
+ TextGenerator,
44
+ } from './llm_candidate_proposer.js';
45
+ import type { ModelTier } from './evolution_roi.js';
46
+
47
+ export const ANTHROPIC_URL = 'https://api.anthropic.com/v1/messages';
48
+ export const ANTHROPIC_VERSION = '2023-06-01';
49
+
50
+ /**
51
+ * Dated model id per tier, or `null` where this tree pins none.
52
+ *
53
+ * The two dated ids are the ones already used elsewhere in this repository
54
+ * (`src/scripts/rdp_gate_classify.ts:66`, `src/scripts/bench_ab_v2_run.ts`), so
55
+ * they are not invented here.
56
+ */
57
+ export const TIER_MODEL: Readonly<Record<ModelTier, string | null>> = {
58
+ lite: 'claude-haiku-4-5-20251001',
59
+ medium: 'claude-sonnet-4-5-20250929',
60
+ high: null,
61
+ };
62
+
63
+ /** Sampling parameters. Frozen with the protocol; not tuned per run. */
64
+ export const MAX_TOKENS = 8192;
65
+ export const TEMPERATURE = 0;
66
+
67
+ export class TransportRefusedError extends Error {
68
+ constructor(message: string) {
69
+ super(message);
70
+ this.name = 'TransportRefusedError';
71
+ }
72
+ }
73
+
74
+ /** The model id for a tier, or a refusal naming what must be pinned. */
75
+ export function modelForTier(tier: ModelTier): string {
76
+ const model = TIER_MODEL[tier];
77
+ if (model === null) {
78
+ throw new TransportRefusedError(
79
+ `tier '${tier}' has no dated model id pinned in TIER_MODEL, so it cannot be sent: a ` +
80
+ 'floating alias would make the frozen execution protocol answer a different ' +
81
+ 'question on a later run. Pin a dated id and record it in ' +
82
+ 'docs/contracts/metered-proposer-protocol.md before using this tier',
83
+ );
84
+ }
85
+ return model;
86
+ }
87
+
88
+ /** The exact HTTP request body a call would carry. Sends nothing. */
89
+ export function describeRequest(req: GenerationRequest): {
90
+ url: string;
91
+ model: string;
92
+ body: Record<string, unknown>;
93
+ } {
94
+ const model = modelForTier(req.tier);
95
+ return {
96
+ url: ANTHROPIC_URL,
97
+ model,
98
+ body: {
99
+ model,
100
+ max_tokens: MAX_TOKENS,
101
+ temperature: TEMPERATURE,
102
+ system: req.system,
103
+ messages: [{ role: 'user', content: req.prompt }],
104
+ },
105
+ };
106
+ }
107
+
108
+ /** Rough token estimate for a dry-run cost line. Characters over four. */
109
+ export function estimateTokens(text: string): number {
110
+ return Math.ceil(text.length / 4);
111
+ }
112
+
113
+ interface AnthropicResponse {
114
+ content?: Array<{ type?: string; text?: string }>;
115
+ }
116
+
117
+ /**
118
+ * Bind the metered port to the Anthropic messages API.
119
+ *
120
+ * The key is read at CALL time rather than at module load, so importing this
121
+ * module — which the tests do — never touches the filesystem for a credential
122
+ * and never fails on a machine that has none.
123
+ */
124
+ export function anthropicGenerator(keyPath: string | null = null): TextGenerator {
125
+ return async (req: GenerationRequest): Promise<GenerationResult> => {
126
+ const described = describeRequest(req);
127
+ const key = load_anthropic_key(keyPath);
128
+ const resp = await fetch(described.url, {
129
+ method: 'POST',
130
+ headers: {
131
+ 'x-api-key': key,
132
+ 'anthropic-version': ANTHROPIC_VERSION,
133
+ 'content-type': 'application/json',
134
+ },
135
+ body: JSON.stringify(described.body),
136
+ });
137
+ if (!resp.ok) {
138
+ throw new TransportRefusedError(
139
+ `${described.model} returned HTTP ${String(resp.status)}: ${(await resp.text()).slice(0, 300)}`,
140
+ );
141
+ }
142
+ const data = (await resp.json()) as AnthropicResponse;
143
+ const text = (data.content ?? [])
144
+ .filter((b) => b.type === 'text')
145
+ .map((b) => b.text ?? '')
146
+ .join('');
147
+ // An empty body is returned AS an empty body rather than repaired here.
148
+ // The arm's own output contract refuses it and classifies the refusal;
149
+ // repairing it in the transport would move a decision into the layer
150
+ // that is supposed to have none.
151
+ return { text, model: described.model };
152
+ };
153
+ }
@@ -0,0 +1,393 @@
1
+ /**
2
+ * The pathology archive — best-known intervention per `WHERE x WHY` failure
3
+ * cell, over closed vocabularies, backed by append-only attempt history.
4
+ *
5
+ * `road-to-governed-harness-evolution` step 4.4. A pure Pareto frontier orders
6
+ * candidates by their metric vectors and throws away the reason each candidate
7
+ * exists, so two candidates that fail for completely different reasons compete
8
+ * as if they were interchangeable. This module keeps the reason.
9
+ *
10
+ * ## What this is NOT
11
+ *
12
+ * It is not a second verdict beside `_lib/paired_verdict.ts`. Nothing here
13
+ * decides whether a candidate is better; the archive records WHY attempts
14
+ * failed and which intervention is currently RETAINED per cell. Promotion stays
15
+ * with `_lib/evaluation_vector.ts`'s `promotionVerdict`, which this module never
16
+ * calls and never reimplements.
17
+ *
18
+ * ## "Best" is a retained representative, not a quality claim
19
+ *
20
+ * The AI council of 2026-08-31 was explicit that "archive the best intervention
21
+ * per cell" names no operation until ranking, tie-break and replacement are all
22
+ * total. Two of the three candidate rules it enumerated need evidence systems
23
+ * that do not exist — lowest edit distance to a human gold standard (there is no
24
+ * gold standard) and highest measured failure-class coverage (there is no
25
+ * coverage metric). The third, recency, is trivially deterministic and is what
26
+ * ships. So the retained entry is a REPRESENTATIVE selected by recency, and this
27
+ * module says so in its type names rather than calling it "best" and implying a
28
+ * measurement nobody took.
29
+ *
30
+ * Because recency says nothing about quality, the attempt history is append-only
31
+ * and every ranking decision is stamped with `ranking_rule_version`. When a real
32
+ * quality metric arrives, representatives are RECOMPUTED from history rather
33
+ * than lost.
34
+ *
35
+ * ## Ordering is by sequence, never by timestamp
36
+ *
37
+ * `attempt_sequence` is assigned by the ingester, monotonically. Timestamps come
38
+ * from producer clocks: they collide, they arrive out of order, and they make a
39
+ * replacement rule that is not total. `observed_at` is retained for reporting
40
+ * and is never consulted for ordering.
41
+ */
42
+
43
+ import { LADDER_RUNGS, type LadderRung } from './activation_ladder.js';
44
+
45
+ /** `WHERE` — reused from the activation ladder, never re-invented. */
46
+ export const PATHOLOGY_WHERE = LADDER_RUNGS;
47
+ export type PathologyWhere = LadderRung;
48
+
49
+ /**
50
+ * `WHY` — the closed failure-REASON vocabulary.
51
+ *
52
+ * Closed means: a versioned enum, exactly one value per attempt, and an addition
53
+ * requires a `classification_rule_version` bump plus migration. Free-form
54
+ * explanation belongs in `reason_detail` and never in this axis.
55
+ *
56
+ * The order IS the precedence order. When several reasons could apply, the
57
+ * earliest applicable value wins, so classification is deterministic rather than
58
+ * dependent on evaluation order. `reason_unknown` applies only when none of the
59
+ * first seven can be established — it is a real state, not a default.
60
+ *
61
+ * These are REASONS, deliberately not places. An earlier draft of this
62
+ * vocabulary used names like `projection_failed` and `delivery_failed`, which
63
+ * restate `WHERE` and collapse the very distinction the two axes exist to draw.
64
+ */
65
+ export const PATHOLOGY_WHY = [
66
+ 'precondition_unsatisfied',
67
+ 'policy_blocked',
68
+ 'dependency_unavailable',
69
+ 'execution_failed',
70
+ 'output_contract_violated',
71
+ 'evidence_missing',
72
+ 'human_rejected',
73
+ 'reason_unknown',
74
+ ] as const;
75
+ export type PathologyWhy = (typeof PATHOLOGY_WHY)[number];
76
+
77
+ /** Bumped when the cell/query shape changes. */
78
+ export const ARCHIVE_SCHEMA_VERSION = 1;
79
+ /** Bumped when `PATHOLOGY_WHY` or its precedence changes. */
80
+ export const CLASSIFICATION_RULE_VERSION = 1;
81
+ /** Bumped when the ranking/tie-break/replacement rule changes. */
82
+ export const RANKING_RULE_VERSION = 1;
83
+
84
+ /**
85
+ * Dominance threshold for the search-collapse guard.
86
+ *
87
+ * STATED POLICY DEFAULT, not a measured optimum — and deliberately a NEW
88
+ * constant rather than a reuse.
89
+ *
90
+ * The step's own verify line carries a bare `0.6`, and the prior council warned
91
+ * that reusing it would be "a semantic change wearing a constant's clothes" IF
92
+ * it already meant textual similarity. Checked against the tree on 2026-08-31:
93
+ * it does not, because no such constant exists. `diversityCollapsed`
94
+ * (`_lib/harness_evolution_guards.ts:215`) is a DISTINCT-COUNT check with
95
+ * `minDistinct = 2` and no ratio at all, and the only near-duplicate constant is
96
+ * `NEAR_DUPLICATE_THRESHOLD = 70` in `_lib/curator_ops.ts:106` — an integer
97
+ * percentage on a different scale. So the collision the objection feared is not
98
+ * present, and the number below is free to be given its own meaning.
99
+ *
100
+ * Revisit-if: a run records a collapse the guard did not catch, or a warm-up
101
+ * period in which the floor below suppressed a real signal.
102
+ */
103
+ export const PATHOLOGY_DOMINANCE_THRESHOLD = 0.6;
104
+ /** Observation window: the latest N classifiable failed attempts. */
105
+ export const PATHOLOGY_WINDOW_SIZE = 50;
106
+ /** No verdict below this many classifiable attempts in the window. */
107
+ export const PATHOLOGY_MIN_CLASSIFIABLE_ATTEMPTS = 20;
108
+
109
+ export type ClassificationStatus = 'classified' | 'unclassifiable';
110
+ export type ValidationStatus = 'valid' | 'invalid';
111
+
112
+ /** One append-only attempt observation. Never mutated, never deleted. */
113
+ export interface PathologyAttempt {
114
+ readonly attempt_id: string;
115
+ /** Monotonic, ingester-assigned. The ONLY ordering key. */
116
+ readonly attempt_sequence: number;
117
+ readonly candidate_id: string;
118
+ readonly intervention_ref: string;
119
+ readonly where: PathologyWhere;
120
+ readonly why: PathologyWhy;
121
+ readonly reason_detail: string;
122
+ readonly classification_status: ClassificationStatus;
123
+ readonly validation_status: ValidationStatus;
124
+ /** Reporting only. Never consulted for ordering. */
125
+ readonly observed_at: string;
126
+ readonly archive_schema_version: number;
127
+ readonly classification_rule_version: number;
128
+ readonly ranking_rule_version: number;
129
+ readonly cohort_id: string;
130
+ readonly cohort_version: number;
131
+ }
132
+
133
+ /** A versioned cell query result. The guard consumes THIS, never storage internals. */
134
+ export interface PathologyCell {
135
+ readonly where: PathologyWhere;
136
+ readonly why: PathologyWhy;
137
+ readonly archive_schema_version: number;
138
+ readonly classification_rule_version: number;
139
+ readonly ranking_rule_version: number;
140
+ readonly cohort_id: string;
141
+ readonly cohort_version: number;
142
+ readonly attempt_count: number;
143
+ readonly classifiable_count: number;
144
+ readonly unclassifiable_count: number;
145
+ readonly first_observed_attempt_sequence: number;
146
+ readonly first_observed_at: string;
147
+ readonly last_observed_attempt_sequence: number;
148
+ readonly last_observed_at: string;
149
+ readonly retained_candidate_id: string | null;
150
+ readonly retained_intervention_ref: string | null;
151
+ readonly retained_attempt_id: string | null;
152
+ readonly retained_attempt_sequence: number | null;
153
+ readonly retained_observed_at: string | null;
154
+ readonly retained_ranking_rule: string;
155
+ readonly retained_ranking_key: string | null;
156
+ readonly retained_validation_status: ValidationStatus | null;
157
+ }
158
+
159
+ /** A versioned window query result. The guard's only legal input. */
160
+ export interface PathologyWindowQuery {
161
+ readonly archive_schema_version: number;
162
+ readonly classification_rule_version: number;
163
+ readonly ranking_rule_version: number;
164
+ readonly window_size: number;
165
+ readonly unclassifiable_excluded: number;
166
+ readonly rows: readonly PathologyAttempt[];
167
+ }
168
+
169
+ export interface DominanceOptions {
170
+ readonly threshold?: number;
171
+ readonly windowSize?: number;
172
+ readonly minClassifiable?: number;
173
+ }
174
+
175
+ export const RETAINED_RANKING_RULE = 'recency-v1: attempt_sequence DESC, candidate_id ASC, attempt_id ASC';
176
+
177
+ export function cellKey(where: PathologyWhere, why: PathologyWhy): string {
178
+ return `${where} ${why}`;
179
+ }
180
+
181
+ export class PathologyArchiveError extends Error {}
182
+
183
+ /**
184
+ * Is `incoming` a better representative than `retained`?
185
+ *
186
+ * Total by construction: the tuple `(attempt_sequence DESC, candidate_id ASC,
187
+ * attempt_id ASC)` orders any two distinct attempts, and `attempt_id` is unique,
188
+ * so the comparison never falls through to "equal" for two different attempts.
189
+ * A rule whose tie-break is declared but unreachable is not total, which is the
190
+ * defect the council named in the timestamp-ordered alternative.
191
+ */
192
+ export function replacesRetained(incoming: PathologyAttempt, retained: PathologyAttempt): boolean {
193
+ if (incoming.attempt_sequence !== retained.attempt_sequence) {
194
+ return incoming.attempt_sequence > retained.attempt_sequence;
195
+ }
196
+ if (incoming.candidate_id !== retained.candidate_id) {
197
+ return incoming.candidate_id < retained.candidate_id;
198
+ }
199
+ return incoming.attempt_id < retained.attempt_id;
200
+ }
201
+
202
+ /** Only a validated, classified attempt may become a representative. */
203
+ function eligibleAsRepresentative(a: PathologyAttempt): boolean {
204
+ return a.classification_status === 'classified' && a.validation_status === 'valid';
205
+ }
206
+
207
+ /**
208
+ * Append-only, idempotent attempt store.
209
+ *
210
+ * Re-ingesting an existing `attempt_id` is a no-op: it cannot alter counts and
211
+ * cannot change a representative. Without that, a retry loop silently inflates
212
+ * the very frequency evidence the dominance guard reads.
213
+ */
214
+ export class PathologyArchive {
215
+ private readonly byId = new Map<string, PathologyAttempt>();
216
+ private readonly order: PathologyAttempt[] = [];
217
+
218
+ /** @returns true when the attempt was new, false when it was a duplicate. */
219
+ ingest(a: PathologyAttempt): boolean {
220
+ if (!PATHOLOGY_WHERE.includes(a.where)) {
221
+ throw new PathologyArchiveError(`unknown WHERE '${a.where}'`);
222
+ }
223
+ if (!PATHOLOGY_WHY.includes(a.why)) {
224
+ throw new PathologyArchiveError(`unknown WHY '${a.why}'`);
225
+ }
226
+ if (this.byId.has(a.attempt_id)) return false;
227
+ this.byId.set(a.attempt_id, a);
228
+ this.order.push(a);
229
+ return true;
230
+ }
231
+
232
+ /** Every attempt, in ingest order. Callers must not mutate. */
233
+ attempts(): readonly PathologyAttempt[] {
234
+ return this.order;
235
+ }
236
+
237
+ /**
238
+ * The versioned window query the collapse guard consumes.
239
+ *
240
+ * The guard may not read `attempts()` directly: the council required it to
241
+ * consume "a versioned archive query rather than storage internals", so the
242
+ * version/cohort quad travels WITH the rows and a guard cannot silently mix
243
+ * two classification vocabularies. It returns attempts rather than cells
244
+ * because a last-N window is not reconstructible from aggregates — which is
245
+ * the same reason `cells()` alone is not the guard's input.
246
+ */
247
+ dominanceWindow(windowSize: number = PATHOLOGY_WINDOW_SIZE): PathologyWindowQuery {
248
+ const classifiable = this.order
249
+ .filter((a) => a.classification_status === 'classified')
250
+ .sort((a, b) => a.attempt_sequence - b.attempt_sequence);
251
+ const rows = classifiable.slice(-windowSize);
252
+ const head = rows[0] ?? this.order[0];
253
+ return {
254
+ archive_schema_version: head?.archive_schema_version ?? ARCHIVE_SCHEMA_VERSION,
255
+ classification_rule_version: head?.classification_rule_version ?? CLASSIFICATION_RULE_VERSION,
256
+ ranking_rule_version: head?.ranking_rule_version ?? RANKING_RULE_VERSION,
257
+ window_size: windowSize,
258
+ unclassifiable_excluded: this.order.length - classifiable.length,
259
+ rows,
260
+ };
261
+ }
262
+
263
+ /** The collapse verdict, read through the versioned query above. */
264
+ collapseVerdict(opts: DominanceOptions = {}): DominanceVerdict {
265
+ return dominanceVerdict(this.dominanceWindow(opts.windowSize ?? PATHOLOGY_WINDOW_SIZE), opts);
266
+ }
267
+
268
+ /**
269
+ * The versioned cell query. Cells are keyed on `WHERE x WHY` AND on the
270
+ * version/cohort quad — attempts recorded under a different classification
271
+ * rule describe a different vocabulary and must not be summed with these.
272
+ */
273
+ cells(): readonly PathologyCell[] {
274
+ const groups = new Map<string, PathologyAttempt[]>();
275
+ for (const a of this.order) {
276
+ const k = [
277
+ a.where,
278
+ a.why,
279
+ a.archive_schema_version,
280
+ a.classification_rule_version,
281
+ a.ranking_rule_version,
282
+ a.cohort_id,
283
+ a.cohort_version,
284
+ ].join(' ');
285
+ const bucket = groups.get(k);
286
+ if (bucket) bucket.push(a);
287
+ else groups.set(k, [a]);
288
+ }
289
+
290
+ const out: PathologyCell[] = [];
291
+ for (const bucket of groups.values()) {
292
+ const first = bucket.reduce((m, a) => (a.attempt_sequence < m.attempt_sequence ? a : m));
293
+ const last = bucket.reduce((m, a) => (a.attempt_sequence > m.attempt_sequence ? a : m));
294
+ let rep: PathologyAttempt | null = null;
295
+ for (const a of bucket) {
296
+ if (!eligibleAsRepresentative(a)) continue;
297
+ if (rep === null || replacesRetained(a, rep)) rep = a;
298
+ }
299
+ const head = bucket[0]!;
300
+ out.push({
301
+ where: head.where,
302
+ why: head.why,
303
+ archive_schema_version: head.archive_schema_version,
304
+ classification_rule_version: head.classification_rule_version,
305
+ ranking_rule_version: head.ranking_rule_version,
306
+ cohort_id: head.cohort_id,
307
+ cohort_version: head.cohort_version,
308
+ attempt_count: bucket.length,
309
+ classifiable_count: bucket.filter((a) => a.classification_status === 'classified').length,
310
+ unclassifiable_count: bucket.filter((a) => a.classification_status === 'unclassifiable').length,
311
+ first_observed_attempt_sequence: first.attempt_sequence,
312
+ first_observed_at: first.observed_at,
313
+ last_observed_attempt_sequence: last.attempt_sequence,
314
+ last_observed_at: last.observed_at,
315
+ retained_candidate_id: rep?.candidate_id ?? null,
316
+ retained_intervention_ref: rep?.intervention_ref ?? null,
317
+ retained_attempt_id: rep?.attempt_id ?? null,
318
+ retained_attempt_sequence: rep?.attempt_sequence ?? null,
319
+ retained_observed_at: rep?.observed_at ?? null,
320
+ retained_ranking_rule: RETAINED_RANKING_RULE,
321
+ retained_ranking_key: rep
322
+ ? `${rep.attempt_sequence}|${rep.candidate_id}|${rep.attempt_id}`
323
+ : null,
324
+ retained_validation_status: rep?.validation_status ?? null,
325
+ });
326
+ }
327
+ return out.sort((a, b) => (cellKey(a.where, a.why) < cellKey(b.where, b.why) ? -1 : 1));
328
+ }
329
+ }
330
+
331
+ export type DominanceVerdict =
332
+ | { readonly status: 'warming-up'; readonly classifiable_in_window: number; readonly floor: number }
333
+ | {
334
+ readonly status: 'ok' | 'collapsed';
335
+ readonly dominant_share: number;
336
+ readonly dominant_cell: string;
337
+ readonly classifiable_in_window: number;
338
+ readonly window_size: number;
339
+ readonly threshold: number;
340
+ };
341
+
342
+ /**
343
+ * The search-collapse guard, reading the archive through `cells()`-shaped data.
344
+ *
345
+ * Why a share and not the occupancy the frontier already gives: retaining one
346
+ * winner per cell erases whether attempts were distributed 50/50 or 99.9/0.1 —
347
+ * identical occupancy, radically different evidence of collapse. The denominator
348
+ * is therefore CLASSIFIABLE ATTEMPTS in the window, not distinct cells.
349
+ *
350
+ * `warming-up` is a real state and NOT a pass. A guard that returned "ok" on
351
+ * three observations would be reporting a confidence it does not have; the floor
352
+ * exists so an empty archive cannot look healthy.
353
+ */
354
+ export function dominanceVerdict(
355
+ query: PathologyWindowQuery,
356
+ opts: DominanceOptions = {},
357
+ ): DominanceVerdict {
358
+ const threshold = opts.threshold ?? PATHOLOGY_DOMINANCE_THRESHOLD;
359
+ const windowSize = query.window_size;
360
+ const floor = opts.minClassifiable ?? PATHOLOGY_MIN_CLASSIFIABLE_ATTEMPTS;
361
+
362
+ // The query has already excluded unclassifiable rows and applied the
363
+ // window; re-filtering here would let a caller pass raw storage and get a
364
+ // verdict, which is the coupling this signature exists to prevent.
365
+ const window = query.rows;
366
+
367
+ if (window.length < floor) {
368
+ return { status: 'warming-up', classifiable_in_window: window.length, floor };
369
+ }
370
+
371
+ const counts = new Map<string, number>();
372
+ for (const a of window) {
373
+ const k = cellKey(a.where, a.why);
374
+ counts.set(k, (counts.get(k) ?? 0) + 1);
375
+ }
376
+ let dominantCell = '';
377
+ let dominantCount = 0;
378
+ for (const [k, n] of [...counts.entries()].sort((x, y) => (x[0] < y[0] ? -1 : 1))) {
379
+ if (n > dominantCount) {
380
+ dominantCount = n;
381
+ dominantCell = k;
382
+ }
383
+ }
384
+ const share = dominantCount / window.length;
385
+ return {
386
+ status: share >= threshold ? 'collapsed' : 'ok',
387
+ dominant_share: share,
388
+ dominant_cell: dominantCell.replace(' ', ' x '),
389
+ classifiable_in_window: window.length,
390
+ window_size: windowSize,
391
+ threshold,
392
+ };
393
+ }