piroboros 0.0.0-stage → 0.2.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 (118) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/LICENSE +21 -0
  3. package/NOTICE +39 -0
  4. package/README.md +140 -2
  5. package/agents/astrelia.md +31 -0
  6. package/agents/avaritia.md +31 -0
  7. package/agents/elaria.md +31 -0
  8. package/agents/nytheria.md +32 -0
  9. package/agents/raskreia.md +32 -0
  10. package/agents/samaela.md +40 -0
  11. package/agents/vaelia.md +35 -0
  12. package/agents/vesperia.md +45 -0
  13. package/bin/piroboros.mjs +17 -0
  14. package/dist/auth.js +105 -0
  15. package/dist/base.js +19 -0
  16. package/dist/chat/budget.js +87 -0
  17. package/dist/chat/compactloop.js +63 -0
  18. package/dist/chat/compactor.js +530 -0
  19. package/dist/chat/extension.js +36 -0
  20. package/dist/chat/hook.js +40 -0
  21. package/dist/chat/log.js +317 -0
  22. package/dist/chat/outbound.js +114 -0
  23. package/dist/chat/plan.js +64 -0
  24. package/dist/chat/prompt.js +115 -0
  25. package/dist/chat/status.js +37 -0
  26. package/dist/chat/stuck.js +83 -0
  27. package/dist/chat/tools.js +163 -0
  28. package/dist/chat/tree.js +73 -0
  29. package/dist/chat/turn.js +305 -0
  30. package/dist/chat/view.js +163 -0
  31. package/dist/conclave/agents.js +113 -0
  32. package/dist/conclave/pipeline.js +715 -0
  33. package/dist/conclave/report.js +43 -0
  34. package/dist/config.js +614 -0
  35. package/dist/durable.js +177 -0
  36. package/dist/guard.js +346 -0
  37. package/dist/lock.js +56 -0
  38. package/dist/main.js +348 -0
  39. package/dist/memory/akashic/api.js +121 -0
  40. package/dist/memory/akashic/confusables.js +41 -0
  41. package/dist/memory/akashic/scanner.js +67 -0
  42. package/dist/memory/akashic/snapshot.js +31 -0
  43. package/dist/memory/akashic/store.js +1254 -0
  44. package/dist/memory/akashic/tools.js +168 -0
  45. package/dist/memory/akashic/vault.js +984 -0
  46. package/dist/memory/host.js +124 -0
  47. package/dist/memory/mnemosia/adapters/akashic-memories.js +180 -0
  48. package/dist/memory/mnemosia/adapters/contract.js +219 -0
  49. package/dist/memory/mnemosia/agents.js +387 -0
  50. package/dist/memory/mnemosia/brief.js +890 -0
  51. package/dist/memory/mnemosia/claims.js +609 -0
  52. package/dist/memory/mnemosia/conflicts.js +769 -0
  53. package/dist/memory/mnemosia/escalation.js +257 -0
  54. package/dist/memory/mnemosia/feedback.js +108 -0
  55. package/dist/memory/mnemosia/filters.js +248 -0
  56. package/dist/memory/mnemosia/intent.js +221 -0
  57. package/dist/memory/mnemosia/open.js +34 -0
  58. package/dist/memory/mnemosia/orchestrator.js +926 -0
  59. package/dist/memory/mnemosia/plan.js +266 -0
  60. package/dist/memory/mnemosia/policy.js +426 -0
  61. package/dist/memory/mnemosia/progressive.js +550 -0
  62. package/dist/memory/mnemosia/provenance.js +458 -0
  63. package/dist/memory/mnemosia/qualifiers.js +428 -0
  64. package/dist/memory/mnemosia/rank.js +525 -0
  65. package/dist/memory/mnemosia/relations.js +156 -0
  66. package/dist/memory/mnemosia/requirements.js +138 -0
  67. package/dist/memory/mnemosia/rerank.js +253 -0
  68. package/dist/memory/mnemosia/retention.js +174 -0
  69. package/dist/memory/mnemosia/rollback.js +337 -0
  70. package/dist/memory/mnemosia/select.js +607 -0
  71. package/dist/memory/mnemosia/similarity.js +164 -0
  72. package/dist/memory/mnemosia/situation.js +251 -0
  73. package/dist/memory/mnemosia/task.js +418 -0
  74. package/dist/memory/mnemosia/temporal.js +136 -0
  75. package/dist/memory/mnemosia/tokens.js +66 -0
  76. package/dist/memory/mnemosia/tools.js +160 -0
  77. package/dist/memory/mnemosia/trace.js +306 -0
  78. package/dist/memory/mnemosia/types.js +298 -0
  79. package/dist/models.js +360 -0
  80. package/dist/paths.js +103 -0
  81. package/dist/redact.js +79 -0
  82. package/dist/runtime.js +378 -0
  83. package/dist/search-format.js +102 -0
  84. package/dist/search.js +351 -0
  85. package/dist/setup.js +366 -0
  86. package/dist/shell.js +110 -0
  87. package/dist/skills.js +311 -0
  88. package/dist/telemetry.js +84 -0
  89. package/dist/tui/app.js +1011 -0
  90. package/dist/tui/commands.js +121 -0
  91. package/dist/tui/keys.js +83 -0
  92. package/dist/tui/pane.js +387 -0
  93. package/dist/tui/panel.js +60 -0
  94. package/dist/tui/picker.js +25 -0
  95. package/dist/tui/sanitize.js +59 -0
  96. package/dist/tui/settings.js +198 -0
  97. package/dist/tui/setup.js +256 -0
  98. package/dist/tui/theme.js +26 -0
  99. package/dist/tui/thinking/parse.js +1094 -0
  100. package/dist/tui/thinking/select.js +86 -0
  101. package/dist/tui/thinking/state.js +137 -0
  102. package/dist/tui/thinking/types.js +3 -0
  103. package/dist/tui/thinking/view.js +74 -0
  104. package/dist/tui/viewport.js +208 -0
  105. package/dist/undo.js +258 -0
  106. package/dist/web.js +933 -0
  107. package/docs/conclave.md +21 -0
  108. package/docs/configuration.md +48 -0
  109. package/docs/development.md +25 -0
  110. package/docs/interface.md +33 -0
  111. package/docs/memory.md +11 -0
  112. package/docs/privacy.md +13 -0
  113. package/docs/tools.md +20 -0
  114. package/docs/web.md +38 -0
  115. package/models.json.example +34 -0
  116. package/package.json +76 -4
  117. package/settings.json.example +29 -0
  118. package/skills/conclave/SKILL.md +76 -0
@@ -0,0 +1,156 @@
1
+ // Ported from mnemosia/relations.ts @ f0a8ad4 (MIT; see NOTICE)
2
+ /**
3
+ * Deterministic pairwise relation predicates (design §11's Phase 2 detectors; spec §14).
4
+ *
5
+ * These are the tests that decide whether two near-duplicate claims are *related* and how. They live
6
+ * apart from `conflicts.ts` because they are pure functions of two claims and nothing else — no
7
+ * policy, no graph, no clock — which makes them the part of the taxonomy that can be unit-tested
8
+ * exhaustively and, more importantly, the part whose false-positive behaviour can be inspected
9
+ * without standing up a run.
10
+ *
11
+ * **Every predicate here is deterministic and none of them is semantic.** Design §11 splits
12
+ * `DIRECT_CONTRADICTION` for exactly this reason: the deterministic subset is "a near-dup pair where
13
+ * exactly one side carries a negation marker or a differing `key: value`", and the general case
14
+ * "needs semantics → `OPTIONAL_EXPERIMENT` LLM (Phase 5) with MARK_DISPUTED fallback". Nothing in
15
+ * this file attempts the general case. A pair that is in the neighbourhood, is not explained by any
16
+ * predicate here, and is not otherwise resolvable stays `UNRESOLVED` with `MARK_DISPUTED` — which
17
+ * spec §14's closing line requires and which is a smaller claim than a guess would be.
18
+ */
19
+ import { qualifiersDiverge } from "./qualifiers.js";
20
+ /* ------------------------------------------------------------------------------------------------
21
+ * Negation
22
+ * ---------------------------------------------------------------------------------------------- */
23
+ /**
24
+ * Design §11's negation markers, verbatim: `not | never | no longer | don't | stopped | instead of`.
25
+ *
26
+ * The apostrophe variants of `don't` and the inflections of `stopped` are the same marker written
27
+ * differently, not extra markers — `doesn't` and `do not` are `don't`, and a rule that fired on one
28
+ * spelling and not another would make the detector depend on the author's contractions. Nothing
29
+ * beyond the design's six is added: each extra marker is a knob, and the Phase 2 brief forbids
30
+ * tuning the detector to make the precision number come out.
31
+ */
32
+ export const NEGATION_MARKERS = /\b(?:not|never|no longer|do\s?n[o']?t|does\s?n[o']?t|did\s?n[o']?t|stop(?:s|ped|ping)?|instead of)\b/iu;
33
+ export function hasNegationMarker(text) {
34
+ return NEGATION_MARKERS.test(text);
35
+ }
36
+ /**
37
+ * True when exactly one of the two near-duplicate texts is negated.
38
+ *
39
+ * "Exactly one" is the whole test. Two texts that both say `not` are two statements of the same
40
+ * restriction; two that both omit it are two statements of the same permission. The asymmetry is
41
+ * what carries the information, and it is the only thing about negation a non-semantic detector can
42
+ * honestly read.
43
+ */
44
+ export function negationDivergence(a, b) {
45
+ const left = hasNegationMarker(a);
46
+ const right = hasNegationMarker(b);
47
+ if (left === right)
48
+ return { diverges: false, negatedSide: null };
49
+ return { diverges: true, negatedSide: left ? "a" : "b" };
50
+ }
51
+ /* ------------------------------------------------------------------------------------------------
52
+ * `key: value` divergence
53
+ * ---------------------------------------------------------------------------------------------- */
54
+ /**
55
+ * `retries: 3`, `NODE_ENV=production`, `Pi 0.82.1`… no: only the first two shapes.
56
+ *
57
+ * The pattern requires an explicit `:` or `=` separator and a key made of word characters, because
58
+ * those are the two shapes in which this corpus writes a *setting*. Admitting bare `name value`
59
+ * juxtaposition would turn every noun-phrase pair into a key/value disagreement.
60
+ *
61
+ * The value is captured up to the first separator that ends a field — comma, semicolon, newline, or
62
+ * a closing bracket — and trimmed of trailing sentence punctuation, so `retries: 3.` and
63
+ * `retries: 3` are the same value.
64
+ */
65
+ const KEY_VALUE = /(?:^|[\s(\[{,;])([A-Za-z][A-Za-z0-9_. -]{0,38}[A-Za-z0-9_])\s*[:=]\s*([^\n,;)\]}]{1,60})/gu;
66
+ export function extractKeyValues(text) {
67
+ const found = new Map();
68
+ KEY_VALUE.lastIndex = 0;
69
+ for (const match of text.matchAll(KEY_VALUE)) {
70
+ const key = (match[1] ?? "").trim().toLowerCase().replace(/\s+/gu, " ");
71
+ const value = (match[2] ?? "").trim().replace(/[.\s"'`]+$/u, "").toLowerCase();
72
+ if (key.length === 0 || value.length === 0)
73
+ continue;
74
+ // First occurrence wins, matching the first-match-wins rule the rest of the pipeline uses:
75
+ // a text that sets the same key twice is attributed to what it said first.
76
+ if (!found.has(key))
77
+ found.set(key, value);
78
+ }
79
+ return [...found.entries()].map(([key, value]) => ({ key, value })).sort((x, y) => (x.key < y.key ? -1 : x.key > y.key ? 1 : 0));
80
+ }
81
+ /**
82
+ * The part of a captured value that actually is the value.
83
+ *
84
+ * **CORRECTED AFTER THE FIRST SEEDED MEASUREMENT — the capture was greedy and it produced a false
85
+ * positive.** `extractKeyValues` runs to the end of the clause, so `retries: 3 in the config` and
86
+ * `retries: 3 in the configuration` captured `3 in the config` and `3 in the configuration`, which
87
+ * are unequal strings and were reported as a `DIRECT_CONTRADICTION` between two statements that say
88
+ * the same thing. Seed `N04` in `eval/conflict-seeds.ts` is that case, written as a labelled negative
89
+ * before any measurement was run, and it is what caught it.
90
+ *
91
+ * A setting's value is the token immediately after the separator; the rest of the clause is prose
92
+ * about it. Comparing only the leading token is a **narrowing** — it can only remove detections,
93
+ * never add them — which is the right direction for a rule whose output is the sentence "these two
94
+ * statements contradict each other" in front of a reader. The cost is real and is stated rather than
95
+ * hidden: `strategy: exponential backoff` and `strategy: exponential decay` now agree on `exponential`
96
+ * and the divergence is missed, which is the conservative failure for a deterministic subset that
97
+ * design §11 already says does not cover the semantic case.
98
+ */
99
+ function leadingToken(value) {
100
+ return value.split(/\s+/u)[0] ?? value;
101
+ }
102
+ /** Keys present in both texts with different values. Empty when the two agree or do not overlap. */
103
+ export function keyValueDivergence(a, b) {
104
+ const left = new Map(extractKeyValues(a).map((entry) => [entry.key, entry.value]));
105
+ const right = new Map(extractKeyValues(b).map((entry) => [entry.key, entry.value]));
106
+ const diverging = [];
107
+ for (const [key, value] of [...left.entries()].sort((x, y) => (x[0] < y[0] ? -1 : 1))) {
108
+ const other = right.get(key);
109
+ if (other === undefined)
110
+ continue;
111
+ if (leadingToken(value) === leadingToken(other))
112
+ continue;
113
+ diverging.push({ key, left: leadingToken(value), right: leadingToken(other) });
114
+ }
115
+ return diverging;
116
+ }
117
+ /* ------------------------------------------------------------------------------------------------
118
+ * Claim-shape predicates
119
+ * ---------------------------------------------------------------------------------------------- */
120
+ /** Claim types that assert something *happened or is true*, as opposed to something intended. */
121
+ const FACTUAL_TYPES = new Set(["FACT", "OBSERVATION"]);
122
+ /**
123
+ * Design §11: "`{PLAN, FACT/OBSERVATION}` pair within jaccard₃ ≥ 0.6 neighborhood".
124
+ *
125
+ * The neighbourhood test is the caller's; this decides only whether the *pair of types* is the one
126
+ * §14's `PLAN_VERSUS_FACT` names. Note the direction is recorded rather than discarded: which side
127
+ * is the plan decides the qualification sentence ("this was intended; that is what was observed"),
128
+ * and a symmetric boolean would lose it.
129
+ */
130
+ export function planVersusFact(a, b) {
131
+ if (a.claimType === "PLAN" && FACTUAL_TYPES.has(b.claimType))
132
+ return { matches: true, planSide: "a" };
133
+ if (b.claimType === "PLAN" && FACTUAL_TYPES.has(a.claimType))
134
+ return { matches: true, planSide: "b" };
135
+ return { matches: false, planSide: null };
136
+ }
137
+ /**
138
+ * Design §11: "two PREFERENCE claims, neighborhood match, different hashes".
139
+ *
140
+ * "Different hashes" is `claimId` inequality, which after the Phase 1B identity correction
141
+ * (claims.ts:120-135) also means *not the same statement in the same scope* — two identical
142
+ * preferences in one scope collapsed at deduplication and never reach here.
143
+ */
144
+ export function preferenceChange(a, b) {
145
+ return a.claimType === "PREFERENCE" && b.claimType === "PREFERENCE" && a.claimId !== b.claimId;
146
+ }
147
+ /** Design §11: "same core, different `scope.project`." The scope *level* counts too: global ≠ project. */
148
+ export function scopeDifference(a, b) {
149
+ return a.scope.level !== b.scope.level || (a.scope.project ?? null) !== (b.scope.project ?? null);
150
+ }
151
+ export function branchDifference(a, b) {
152
+ return qualifiersDiverge(a, b, "branch");
153
+ }
154
+ export function environmentDifference(a, b) {
155
+ return qualifiersDiverge(a, b, "environment");
156
+ }
@@ -0,0 +1,138 @@
1
+ // Ported from mnemosia/requirements.ts @ f0a8ad4 (MIT; see NOTICE)
2
+ /**
3
+ * Phase B stage 3 — knowledge-requirement generation (spec Stage 2/3: "treating [situation items]
4
+ * as candidate knowledge requirements and selecting only those justified by the task").
5
+ *
6
+ * A requirement is a named hole in what Mnemosia knows, with a priority and a source preference —
7
+ * not a query, and not a promise to retrieve. Phase B only *derives* them; consuming them into
8
+ * retrieval rounds is Phase C's progressive-retrieval work. What Phase C will need that this module
9
+ * already provides: stable ids (so coverage can be tracked per requirement), `satisfiedBy` left
10
+ * open (the claim id that satisfied it gets written there later), and `queryHints` — deterministic
11
+ * vocabulary the orchestrator feeds into the curated wide-term set so inferred context influences
12
+ * retrieval planning without redefining the caller's task.
13
+ *
14
+ * Derivation is deterministic: situation items map through a category table weighted by tier and
15
+ * confidence; intent hypotheses contribute discriminating-evidence requirements so the cheapest
16
+ * high-value distinguishing evidence is named before any query runs.
17
+ */
18
+ import { SOURCE_ID } from "./types.js";
19
+ /* ------------------------------------------------------------------------------------------------
20
+ * Types
21
+ * ---------------------------------------------------------------------------------------------- */
22
+ export const KNOWLEDGE_REQUIREMENT_PRIORITIES = ["high", "medium", "low"];
23
+ /** Hard bound per derivation; beyond this the tail is unfetchable noise. */
24
+ export const MAX_KNOWLEDGE_REQUIREMENTS = 12;
25
+ const CATEGORY_BY_SITUATION_ITEM = {
26
+ "explicit-project": { category: "project-identity", sourcePreference: [SOURCE_ID.akashicMemories] },
27
+ "explicit-requested-projects": { category: "project-identity", sourcePreference: [SOURCE_ID.akashicMemories] },
28
+ "resume-open-work": { category: "open-work-state", sourcePreference: [SOURCE_ID.akashicMemories], queryHints: ["todo"] },
29
+ "active-milestone-definition": { category: "milestone-definition", sourcePreference: [SOURCE_ID.akashicMemories], queryHints: ["phase"] },
30
+ "previous-phase-outcome": { category: "previous-outcome", sourcePreference: [SOURCE_ID.akashicMemories], queryHints: ["outcome"] },
31
+ "known-failures": { category: "known-failures", sourcePreference: [SOURCE_ID.akashicMemories], queryHints: ["failure"] },
32
+ "coding-conventions": { category: "conventions", sourcePreference: [SOURCE_ID.akashicMemories], queryHints: ["convention"] },
33
+ "vague-referent": { category: "subject-identification", sourcePreference: [] },
34
+ };
35
+ /**
36
+ * Priority from tier + confidence: believed-and-load-bearing is high, plausible is medium,
37
+ * unknown-or-needing-clarification is low (recorded, not pursued).
38
+ */
39
+ function priorityFor(tier, confidence) {
40
+ if (tier === "unknown" || tier === "needs_clarification")
41
+ return "low";
42
+ if (confidence >= 0.7)
43
+ return "high";
44
+ if (confidence >= 0.4)
45
+ return "medium";
46
+ return "low";
47
+ }
48
+ /* ------------------------------------------------------------------------------------------------
49
+ * Derivation
50
+ * ---------------------------------------------------------------------------------------------- */
51
+ /**
52
+ * Derives knowledge requirements from situation context items and intent hypotheses. Pure and
53
+ * deterministic; bounded by MAX_KNOWLEDGE_REQUIREMENTS; duplicate categories collapse onto the
54
+ * first (highest-belief) occurrence.
55
+ */
56
+ export function deriveKnowledgeRequirements(task, situation, intentHypotheses, requestingAgent) {
57
+ void task; // reserved: task-conditioned requirement wording arrives with model-assisted generation
58
+ const requirements = [];
59
+ const seenCategories = new Set();
60
+ for (const item of situation.items) {
61
+ if (requirements.length >= MAX_KNOWLEDGE_REQUIREMENTS)
62
+ break;
63
+ if (item.tier === "needs_clarification")
64
+ continue; // clarification is the intent layer's decision, not a retrieval target
65
+ const mapping = CATEGORY_BY_SITUATION_ITEM[item.id];
66
+ if (mapping === undefined)
67
+ continue;
68
+ if (mapping.sourcePreference.length === 0)
69
+ continue;
70
+ if (seenCategories.has(mapping.category))
71
+ continue;
72
+ seenCategories.add(mapping.category);
73
+ let priority = priorityFor(item.tier, item.confidence);
74
+ // Vaelia researches current documentation for a living; documentation-shaped requirements
75
+ // are her high-priority business even at medium belief.
76
+ if (requestingAgent === "vaelia" && mapping.category === "conventions")
77
+ priority = "high";
78
+ requirements.push({
79
+ requirementId: `req-${mapping.category}`,
80
+ category: mapping.category,
81
+ priority,
82
+ sourcePreference: [...mapping.sourcePreference],
83
+ satisfiedBy: null,
84
+ queryHints: [...(mapping.queryHints ?? [])],
85
+ });
86
+ }
87
+ for (const hypothesis of intentHypotheses.hypotheses) {
88
+ if (requirements.length >= MAX_KNOWLEDGE_REQUIREMENTS)
89
+ break;
90
+ const category = `discriminating-evidence:${hypothesis.hypothesisId}`;
91
+ if (seenCategories.has(category))
92
+ continue;
93
+ seenCategories.add(category);
94
+ requirements.push({
95
+ requirementId: `req-discriminating-${hypothesis.hypothesisId}`,
96
+ category,
97
+ priority: hypothesis.status === "alternative" ? "medium" : "high",
98
+ sourcePreference: [SOURCE_ID.akashicMemories],
99
+ satisfiedBy: null,
100
+ queryHints: [],
101
+ });
102
+ }
103
+ return validateKnowledgeRequirements(requirements);
104
+ }
105
+ /* ------------------------------------------------------------------------------------------------
106
+ * Validation
107
+ * ---------------------------------------------------------------------------------------------- */
108
+ const KNOWN_SOURCES = new Set(Object.values(SOURCE_ID));
109
+ /**
110
+ * Schema-validates and bounds a requirement list: drops malformed entries, unknown sources and
111
+ * duplicates, caps at MAX_KNOWLEDGE_REQUIREMENTS. Invalid input degrades the list; it never throws.
112
+ */
113
+ export function validateKnowledgeRequirements(value) {
114
+ const seen = new Set();
115
+ const requirements = [];
116
+ for (const requirement of value) {
117
+ if (requirements.length >= MAX_KNOWLEDGE_REQUIREMENTS)
118
+ break;
119
+ if (typeof requirement.requirementId !== "string" || requirement.requirementId.length === 0 || seen.has(requirement.requirementId))
120
+ continue;
121
+ if (typeof requirement.category !== "string" || requirement.category.length === 0)
122
+ continue;
123
+ if (!KNOWLEDGE_REQUIREMENT_PRIORITIES.includes(requirement.priority))
124
+ continue;
125
+ const sources = Array.isArray(requirement.sourcePreference) ? requirement.sourcePreference.filter((source) => typeof source === "string" && KNOWN_SOURCES.has(source)) : [];
126
+ if (sources.length === 0)
127
+ continue; // a requirement no registered source could ever satisfy is noise
128
+ seen.add(requirement.requirementId);
129
+ requirements.push({
130
+ ...requirement,
131
+ requirementId: requirement.requirementId.slice(0, 120),
132
+ sourcePreference: sources.slice(0, 3),
133
+ satisfiedBy: typeof requirement.satisfiedBy === "string" ? requirement.satisfiedBy : null,
134
+ queryHints: Array.isArray(requirement.queryHints) ? requirement.queryHints.filter((hint) => typeof hint === "string").slice(0, 3) : [],
135
+ });
136
+ }
137
+ return requirements;
138
+ }
@@ -0,0 +1,253 @@
1
+ // Ported from mnemosia/rerank.ts @ f0a8ad4 (MIT; see NOTICE)
2
+ /**
3
+ * Versioned model-assisted reranking (spec §12, design §3 `OPTIONAL_EXPERIMENT`, Phase 5).
4
+ *
5
+ * **This is the only module in Mnemosia that can talk to a model, and it is off.** Design §3 lists
6
+ * "any LLM call in the Phase 1 path" as `PROHIBITED` and marks LLM-assisted reranking
7
+ * `OPTIONAL_EXPERIMENT` from Phase 5 onward; spec §25 admits Phase 5's items "only after strong
8
+ * offline evaluation", and the evaluation has not passed (Phase 1 is 10/11, Phase 2 is 3/4). So the
9
+ * capability is built, wired, tested and **disabled by default**, exactly as `mutate.ts` built the
10
+ * write path in Phase 3 — and, as there, it refuses to enable itself.
11
+ *
12
+ * Spec §12's sentence is the whole specification of this file:
13
+ *
14
+ * > LLM-assisted reranking may be used only after deterministic filtering and must have a
15
+ * > deterministic fallback.
16
+ *
17
+ * Six properties deliver it, each one structural rather than promised, and each one separately
18
+ * asserted in `test/rerank.test.ts`:
19
+ *
20
+ * 1. **Off by default.** `deps.gate ?? DEFAULT_RERANK_GATE` and the default is frozen with
21
+ * `rerankEnabled: false`. A disabled call returns the input array *by identity* and never touches
22
+ * `deps.model` — measured by a model that counts its own calls. The only constructor of an
23
+ * enabled gate is `enableReranking(enabledBy, justification, rerankerVersion)`, all three
24
+ * required and non-empty, and `test/mutate.test.ts`'s source sweep asserts that nothing under
25
+ * `src/` calls it or builds the enabled literal by hand.
26
+ * 2. **Strictly after deterministic filtering.** The input is `RankedCandidate[]`, which `rank.ts`
27
+ * produces from `filters.accepted` — a rejected claim is never scored, so it is never in the
28
+ * array this function receives. The orchestrator calls it *after* the mode's candidate cap for
29
+ * the same reason: the cap is the last deterministic narrowing, and a reranker placed before it
30
+ * would be choosing what gets weighed rather than reordering what was.
31
+ * 3. **It cannot resurrect a hard-filtered candidate.** The output is assembled by looking every id
32
+ * the model returned up in an index built from the *input*; an id that is not there is discarded
33
+ * into `dropped` and recorded in the trace. There is no code path in this file that constructs a
34
+ * `RankedCandidate`, so an id the deterministic stage rejected has nothing to become.
35
+ * 4. **The deterministic fallback is the current ranking, verbatim.** Every failure mode — a throw,
36
+ * a null, a wrong version, a non-array, an empty order, an order that is not a permutation of the
37
+ * input — returns the input array unchanged, with a status naming which one occurred.
38
+ * 5. **Bounded retry.** `MAX_RERANK_ATTEMPTS = 2`, i.e. one retry, following `mutate.ts`'s
39
+ * rebase-and-retry-**once**: contention or flakiness past one retry is a fact about the
40
+ * dependency, and a loop replaces a visible failure with an invisible one.
41
+ * 6. **Every invocation is versioned and traced.** One `rerank` trace event per call, including the
42
+ * calls that did nothing, carrying the gate, the reranker version, the attempt count, the status,
43
+ * the dropped ids and the resulting displacement.
44
+ *
45
+ * > **THE MODEL PATH IS UNTESTED AND IS DECLARED SO.** No model is reachable from this environment
46
+ * > and Mnemosia has no HTTP client, no API key and no runtime dependency that could acquire one
47
+ * > (`package.json` has zero dependencies, deliberately). `RerankModel` is therefore a *seam*: the
48
+ * > fallback path, the permutation guard, the retry bound and the trace record are exercised against
49
+ * > fakes, and the sentence "a real model was asked to reorder real candidates and the result was
50
+ * > better" is **not** claimed anywhere. `REGISTERED_RERANKERS` holds exactly one entry, and its
51
+ * > version string says what it is.
52
+ */
53
+ import { compareCandidates } from "./rank.js";
54
+ import { SCHEMA_VERSION } from "./types.js";
55
+ /** The gate every production wiring uses. `extension.ts` names no other. */
56
+ export const DEFAULT_RERANK_GATE = Object.freeze({
57
+ schemaVersion: SCHEMA_VERSION.rerankGate,
58
+ rerankEnabled: false,
59
+ enabledBy: null,
60
+ justification: null,
61
+ rerankerVersion: null,
62
+ });
63
+ /**
64
+ * The single constructor of an enabled gate. Nothing under `src/` calls it; `test/mutate.test.ts`
65
+ * proves that by reading the source tree, and `test/rerank.test.ts` extends the same sweep here.
66
+ */
67
+ export function enableReranking(enabledBy, justification, rerankerVersion) {
68
+ if (typeof enabledBy !== "string" || enabledBy.trim().length === 0)
69
+ throw new Error("enableReranking requires a named enabler; spec §25 admits model-assisted reranking only after strong offline evaluation, and an anonymous activation is not an approval");
70
+ if (typeof justification !== "string" || justification.trim().length === 0)
71
+ throw new Error("enableReranking requires a justification; the Phase 1 gate is 10/11 and the Phase 2 gate is 3/4, so any activation has to say what it is for");
72
+ if (typeof rerankerVersion !== "string" || rerankerVersion.trim().length === 0)
73
+ throw new Error("enableReranking requires a reranker version; an approval that does not name one authorizes whatever the provider ships next");
74
+ return Object.freeze({ schemaVersion: SCHEMA_VERSION.rerankGate, rerankEnabled: true, enabledBy: enabledBy.trim(), justification: justification.trim(), rerankerVersion: rerankerVersion.trim() });
75
+ }
76
+ /**
77
+ * The reranker registry. One entry, and its version string is the honest description of it.
78
+ *
79
+ * A registry with one unbuilt member looks like ceremony until you ask what the alternative is: the
80
+ * gate names a version, `applyReranking` refuses a response whose version is not the gate's, and a
81
+ * version nobody wrote down cannot be approved. An empty registry would make the version field
82
+ * unverifiable; a registry with a plausible-looking `mnemosia/reranker@1` in it would be design §26's
83
+ * placeholder abstraction, claiming a model that does not exist.
84
+ */
85
+ export const REGISTERED_RERANKERS = Object.freeze(["mnemosia/reranker@0-unbuilt"]);
86
+ /** One retry, following `mutate.ts`'s rebase-and-retry-once. See property 5 in the header. */
87
+ export const MAX_RERANK_ATTEMPTS = 2;
88
+ /* ------------------------------------------------------------------------------------------------
89
+ * Application
90
+ * ---------------------------------------------------------------------------------------------- */
91
+ export const RERANK_STATUSES = [
92
+ /** The gate is closed. The model was not called. This is production. */
93
+ "disabled",
94
+ /** The gate is open but no model was supplied — an activation without an implementation. */
95
+ "no_model",
96
+ /** The model answered and its answer was applied. */
97
+ "applied",
98
+ /** Every attempt threw. Deterministic order returned. */
99
+ "fallback_error",
100
+ /** The model answered with something that is not a usable order. Deterministic order returned. */
101
+ "fallback_invalid",
102
+ /** The model's version is not the version the gate approved. Deterministic order returned. */
103
+ "fallback_version_mismatch",
104
+ /** There was nothing to rerank. */
105
+ "empty",
106
+ ];
107
+ /**
108
+ * Reorders `candidates` with the model, or returns them exactly as they arrived.
109
+ *
110
+ * The order of the checks is load-bearing and mirrors `executeMutation`: the **gate is read first**,
111
+ * before the model is looked at and before a request is built, so a disabled run performs no work
112
+ * that an enabled one would and the "0 model calls" measurement is about the code path rather than
113
+ * about the fake.
114
+ */
115
+ // Ported library surface: no caller under src/ uses the rerank model path yet; the ported suite covers it.
116
+ export function applyReranking(candidates, deps) {
117
+ const gate = deps.gate ?? DEFAULT_RERANK_GATE;
118
+ const at = deps.now?.() ?? Date.now();
119
+ const input = candidates;
120
+ const emit = (outcome) => {
121
+ deps.trace?.append({
122
+ state: "SCORE_CANDIDATES",
123
+ event: "rerank",
124
+ at,
125
+ payload: {
126
+ status: outcome.status,
127
+ reason: outcome.reason,
128
+ gate: { rerankEnabled: gate.rerankEnabled, enabledBy: gate.enabledBy, justification: gate.justification, approvedVersion: gate.rerankerVersion },
129
+ rerankerVersion: outcome.rerankerVersion,
130
+ attempts: outcome.attempts,
131
+ candidatesIn: input.length,
132
+ candidatesOut: outcome.candidates.length,
133
+ dropped: outcome.dropped,
134
+ restored: outcome.restored,
135
+ moved: outcome.moved,
136
+ maxDisplacement: outcome.maxDisplacement,
137
+ errors: outcome.errors,
138
+ deterministicFallback: outcome.status !== "applied",
139
+ note: "spec §12: LLM-assisted reranking runs only after deterministic filtering and must have a deterministic fallback. No id outside the deterministically-ranked input can appear in the output; `dropped` lists every id the model returned that was not admitted.",
140
+ },
141
+ });
142
+ return outcome;
143
+ };
144
+ const fallback = (status, reason, extra = {}) => emit({ status, candidates: input, rerankerVersion: gate.rerankerVersion, attempts: 0, dropped: [], restored: [], moved: 0, maxDisplacement: 0, reason, errors: [], ...extra });
145
+ // 1. The gate, first.
146
+ if (!gate.rerankEnabled) {
147
+ return fallback("disabled", "spec §25 admits model-assisted reranking only after strong offline evaluation; the Phase 1 gate is 10/11 and the Phase 2 gate is 3/4, so DEFAULT_RERANK_GATE is in force and no model was called");
148
+ }
149
+ if (deps.model === undefined) {
150
+ return fallback("no_model", "the rerank gate is open but no model was supplied; the deterministic ranking stands");
151
+ }
152
+ if (input.length === 0) {
153
+ return fallback("empty", "no candidate survived deterministic ranking, so there is nothing to rerank");
154
+ }
155
+ const request = {
156
+ runId: deps.runId,
157
+ objective: deps.objective,
158
+ policyId: deps.policyId,
159
+ candidates: input.map((candidate, index) => ({
160
+ claimId: candidate.claim.claimId,
161
+ claimType: candidate.claim.claimType,
162
+ text: candidate.claim.text,
163
+ deterministicRank: index + 1,
164
+ utility: candidate.score.utility,
165
+ })),
166
+ };
167
+ const errors = [];
168
+ let attempts = 0;
169
+ let response = null;
170
+ while (attempts < MAX_RERANK_ATTEMPTS) {
171
+ attempts += 1;
172
+ try {
173
+ response = deps.model.rerank(request, attempts);
174
+ }
175
+ catch (error) {
176
+ errors.push(error instanceof Error ? error.message : String(error));
177
+ response = null;
178
+ continue;
179
+ }
180
+ if (response !== null && typeof response === "object")
181
+ break;
182
+ errors.push(`attempt ${attempts} returned no response`);
183
+ response = null;
184
+ }
185
+ if (response === null) {
186
+ return emit({ status: "fallback_error", candidates: input, rerankerVersion: gate.rerankerVersion, attempts, dropped: [], restored: [], moved: 0, maxDisplacement: 0, reason: `the reranker failed on all ${attempts} attempt(s); the deterministic ranking is returned unchanged`, errors });
187
+ }
188
+ if (response.rerankerVersion !== gate.rerankerVersion) {
189
+ return emit({ status: "fallback_version_mismatch", candidates: input, rerankerVersion: gate.rerankerVersion, attempts, dropped: [], restored: [], moved: 0, maxDisplacement: 0, reason: `the reranker identified itself as ${String(response.rerankerVersion)} but the gate approved ${String(gate.rerankerVersion)}; an unapproved version is a fallback, not a warning`, errors });
190
+ }
191
+ if (!Array.isArray(response.order) || response.order.length === 0) {
192
+ return emit({ status: "fallback_invalid", candidates: input, rerankerVersion: gate.rerankerVersion, attempts, dropped: [], restored: [], moved: 0, maxDisplacement: 0, reason: "the reranker returned no usable order; the deterministic ranking is returned unchanged", errors });
193
+ }
194
+ /* --- the permutation guard (properties 3 and 4) --------------------------------------------- */
195
+ //
196
+ // Everything below reads *only* from `byClaimId`, which is built from the input. That is what
197
+ // makes "no hard-filtered candidate can be resurrected" a property of the code's shape rather
198
+ // than of a validation step somebody could forget to run: there is no expression in this function
199
+ // that produces a `RankedCandidate` from anything but the input array.
200
+ const byClaimId = new Map(input.map((candidate) => [candidate.claim.claimId, candidate]));
201
+ const positionByClaimId = new Map(input.map((candidate, index) => [candidate.claim.claimId, index]));
202
+ const ordered = [];
203
+ const placed = new Set();
204
+ const dropped = [];
205
+ for (const claimId of response.order) {
206
+ if (typeof claimId !== "string") {
207
+ dropped.push(String(claimId));
208
+ continue;
209
+ }
210
+ if (placed.has(claimId))
211
+ continue; // a duplicate is not a second placement
212
+ const candidate = byClaimId.get(claimId);
213
+ if (candidate === undefined) {
214
+ dropped.push(claimId);
215
+ continue;
216
+ }
217
+ ordered.push(candidate);
218
+ placed.add(claimId);
219
+ }
220
+ // Anything the model omitted is re-appended in the deterministic total order. Dropping it would
221
+ // let a model *remove* evidence, which is a filtering decision, and §12 puts reranking strictly
222
+ // after filtering rather than partly inside it.
223
+ const restoredCandidates = input.filter((candidate) => !placed.has(candidate.claim.claimId)).sort(compareCandidates);
224
+ const restored = restoredCandidates.map((candidate) => candidate.claim.claimId);
225
+ ordered.push(...restoredCandidates);
226
+ if (ordered.length !== input.length) {
227
+ // Unreachable: `ordered` holds each input exactly once by construction. Kept as a hard stop
228
+ // rather than an assertion, because a reranker that silently changed the candidate count would
229
+ // be the one defect that invalidates every downstream token and provenance guarantee.
230
+ return emit({ status: "fallback_invalid", candidates: input, rerankerVersion: gate.rerankerVersion, attempts, dropped, restored, moved: 0, maxDisplacement: 0, reason: `the reranked order held ${ordered.length} candidates against ${input.length} in; the deterministic ranking is returned unchanged`, errors });
231
+ }
232
+ let moved = 0;
233
+ let maxDisplacement = 0;
234
+ for (const [index, candidate] of ordered.entries()) {
235
+ const was = positionByClaimId.get(candidate.claim.claimId) ?? index;
236
+ if (was !== index) {
237
+ moved += 1;
238
+ maxDisplacement = Math.max(maxDisplacement, Math.abs(was - index));
239
+ }
240
+ }
241
+ return emit({
242
+ status: "applied",
243
+ candidates: ordered,
244
+ rerankerVersion: gate.rerankerVersion,
245
+ attempts,
246
+ dropped,
247
+ restored,
248
+ moved,
249
+ maxDisplacement,
250
+ reason: `${gate.rerankerVersion} reordered ${moved} of ${input.length} candidate(s) after deterministic ranking; ${dropped.length} returned id(s) were not in the deterministic set and were discarded, ${restored.length} omitted id(s) were restored in deterministic order`,
251
+ errors,
252
+ });
253
+ }