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,426 @@
1
+ // Ported from mnemosia/policy.ts @ f0a8ad4 (MIT; see NOTICE)
2
+ /**
3
+ * Ranking policies, mode configs and the authority table (design §4, §9, build-order step 10).
4
+ *
5
+ * Spec §12 opens with a prohibition: "Do not implement a universal static scoring formula." So this
6
+ * file holds **data**, not code. Every number a ranking decision depends on — weights, the authority
7
+ * table, half-lives, the certainty map, the selection constants — lives in a frozen policy object
8
+ * with an id, a version and a written rationale, and `rank.ts` / `select.ts` contain only the
9
+ * arithmetic that reads them. A policy change is therefore a diff to a table, reviewable on its own,
10
+ * which is what design §19 item 3 means when it makes a `policy.ts` bump a decision requiring human
11
+ * approval: there has to be something small enough to approve.
12
+ *
13
+ * **The lookup chain is four links** (design §9):
14
+ * `(agent, taskType, mode)` → `(agent, *, mode)` → `(*, taskType, *)` → `default@1`.
15
+ * Spec §12 lists more configurable dimensions than that — project, memory type, source, security
16
+ * level, context budget, freshness requirements. Phase 1 keys on three of them and leaves the rest
17
+ * *reachable* rather than pretending to support them: memory type, source and freshness are already
18
+ * per-policy tables (`authority`, `halfLifeDays`), so specialising them means adding a named policy,
19
+ * not changing the resolver. Security level is expressed by mode (`high_assurance`), and context
20
+ * budget is a selection constraint rather than a ranking input. Adding an unused `project` key to
21
+ * the resolver would be a field that reads as a capability, which design §7 forbids elsewhere and
22
+ * would be no less dishonest here.
23
+ *
24
+ * **`utility` is not in `RANK_SIGNALS`.** It is the composed output `Σ wᵢ·signalᵢ`. Design §9 is
25
+ * explicit about why: give utility a weight and it becomes a circular eighth input, and the six
26
+ * concepts spec §12 requires be kept separate start collapsing into it.
27
+ */
28
+ import { AGENT_POLICY, resolveAgent } from "./agents.js";
29
+ /**
30
+ * Design §16's mode table. `plan.ts` re-exports it so step 8's consumers are unaffected by the move.
31
+ */
32
+ export const MODE_CONFIGS = Object.freeze({
33
+ fast: { maxSources: 2, maxCandidates: 100, tokenBudget: 2_000, deadlineMsPerSource: 500, secondPassPermitted: false, failClosedOnUnverified: false, retryAttempts: 0 },
34
+ standard: { maxSources: 3, maxCandidates: 400, tokenBudget: 6_000, deadlineMsPerSource: 2_000, secondPassPermitted: false, failClosedOnUnverified: false, retryAttempts: 1 },
35
+ deep: { maxSources: 3, maxCandidates: 1_500, tokenBudget: 12_000, deadlineMsPerSource: 10_000, secondPassPermitted: true, failClosedOnUnverified: false, retryAttempts: 1 },
36
+ high_assurance: { maxSources: 3, maxCandidates: 400, tokenBudget: 6_000, deadlineMsPerSource: 2_000, secondPassPermitted: false, failClosedOnUnverified: true, retryAttempts: 1 },
37
+ });
38
+ /* ------------------------------------------------------------------------------------------------
39
+ * Signals
40
+ * ---------------------------------------------------------------------------------------------- */
41
+ /**
42
+ * The six **inputs**. Spec §12: "Keep these concepts separate" — authority, evidence_strength,
43
+ * confidence, integrity, freshness, relevance. `utility` is the seventh concept and the composed
44
+ * output; it appears in `ScoreVector` because the trace must record it, never in this list.
45
+ */
46
+ export const RANK_SIGNALS = ["authority", "evidenceStrength", "confidence", "integrity", "freshness", "relevance"];
47
+ /**
48
+ * The standing of a *source*, at the granularity the design's table actually distinguishes.
49
+ *
50
+ * Design §9's authority row reads "curated 0.9 · summary 0.7 · user 0.6 · tool 0.5 ·
51
+ * assistant 0.35", which mixes two vocabularies: three of those are `SourceType` values and three
52
+ * are conversation *event kinds* living inside the single `conversation_message` source type. Keying the
53
+ * table on `SourceType` alone would give a user turn and an assistant turn the same standing and
54
+ * silently delete the 0.25 gap the design put between them — the single largest spread in the table.
55
+ * So the class is derived from both fields, in `rank.ts:authorityClassOf`.
56
+ */
57
+ export const AUTHORITY_CLASSES = ["curated_memory", "compaction_summary", "user_message", "tool_output", "assistant_message", "unknown"];
58
+ /* ------------------------------------------------------------------------------------------------
59
+ * The shared tables
60
+ * ---------------------------------------------------------------------------------------------- */
61
+ /** Design §9's authority row. `unknown` sits below `assistant_message` on purpose: an event kind */
62
+ /** nobody has classified must not inherit the standing of one that was (claims.ts:499-515). */
63
+ export const AUTHORITY_TABLE = Object.freeze({
64
+ curated_memory: 0.9,
65
+ compaction_summary: 0.7,
66
+ user_message: 0.6,
67
+ tool_output: 0.5,
68
+ assistant_message: 0.35,
69
+ unknown: 0.3,
70
+ });
71
+ /**
72
+ * Design §9's half-lives, in days. Two of the eight claim types are not in the design's list and are
73
+ * filled in here with the reason rather than defaulted:
74
+ *
75
+ * - `CONSTRAINT` → 365, matching `PREFERENCE`. A constraint is a standing rule; decaying it on a
76
+ * 90-day fact clock would push it out of the mandatory reservation design §10 gives it, which is
77
+ * the one place freshness must never be able to reach.
78
+ * - `HYPOTHESIS` → 14, matching `PLAN`. A working guess ages exactly like a plan: it is about what
79
+ * might be done next, and next moves stale fastest.
80
+ */
81
+ export const HALF_LIFE_DAYS = Object.freeze({
82
+ PREFERENCE: 365,
83
+ CONSTRAINT: 365,
84
+ DECISION: 180,
85
+ PROCEDURE: 180,
86
+ FACT: 90,
87
+ PLAN: 14,
88
+ HYPOTHESIS: 14,
89
+ OBSERVATION: 7,
90
+ });
91
+ /** Design §9's "project-state/plans 14d". See `halfLifeDaysByMemoryKind`. */
92
+ export const HALF_LIFE_DAYS_BY_MEMORY_KIND = Object.freeze({
93
+ "project-state": 14,
94
+ "open-loops": 14,
95
+ });
96
+ /** Design §9's certainty map. */
97
+ export const CERTAINTY_CONFIDENCE = Object.freeze({
98
+ CONFIRMED: 1.0,
99
+ PROBABLE: 0.7,
100
+ SPECULATIVE: 0.4,
101
+ UNKNOWN: 0.2,
102
+ });
103
+ export const INTEGRITY_SCORE = Object.freeze({
104
+ verified: 1.0,
105
+ unverified: 0.6,
106
+ // Unreachable by construction: filters.ts rejects a failed artifact before ranking runs. Present
107
+ // so the map is total and a future caller that skips filtering does not silently get `undefined`.
108
+ failed: 0.0,
109
+ });
110
+ /**
111
+ * The Phase 2 constants.
112
+ *
113
+ * `directBase`, `supportCoefficient` and `derivedCeiling` are design §9's, unchanged. The three new
114
+ * numbers are set from the shape of the corpus rather than from a sweep, and each is stated with the
115
+ * reasoning so a reviewer can disagree with the reasoning rather than with the number:
116
+ *
117
+ * - `ungroundedCeiling` **0.25**. Design §9 gives an assistant turn 0.35 authority as the floor of
118
+ * the standing table. A confident sentence in a summary whose underlying events nobody can reach
119
+ * is a weaker evidentiary object than an assistant turn — the turn at least *is* the thing that
120
+ * was said — so its evidence ceiling sits below that floor. It is not zero, because the summary
121
+ * is a real artifact that really says this.
122
+ * - `corroborationBonus` **0.1**, `corroborationCap` **0.2**. One extra independent group is worth
123
+ * about half of what the first `log2` step is worth (`0.2·log2(2) = 0.2`), and the cap stops the
124
+ * term at two extra groups. Beyond three independent witnesses the marginal information is small
125
+ * and the risk — one statement echoed across many sessions — is not.
126
+ * - `contradictionPenalty` **0.15**. Enough that a contradicted direct claim (0.4 + 0.2 − 0.15 =
127
+ * 0.45) falls below an uncontradicted one (0.6) without falling below the derived band, because a
128
+ * contradicted first-hand observation is still first-hand.
129
+ *
130
+ * None of these was chosen after seeing a metric. `eval/harness.ts` re-runs the full Phase 1 table
131
+ * with them in place and the result is reported whatever it is.
132
+ */
133
+ export const EVIDENCE_POLICY = Object.freeze({
134
+ directBase: 0.4,
135
+ supportCoefficient: 0.2,
136
+ derivedCeiling: 0.4,
137
+ ungroundedCeiling: 0.25,
138
+ corroborationBonus: 0.1,
139
+ corroborationCap: 0.2,
140
+ contradictionPenalty: 0.15,
141
+ });
142
+ export const RELEVANCE_BONUS = Object.freeze({ tag: 0.1, entity: 0.1, exactScope: 0.05 });
143
+ /** Design §10's soft shares. They sum to 1.00; `assertSharesSumToOne` below proves it at load. */
144
+ export const SECTION_SHARES = Object.freeze({
145
+ confirmed_facts: 0.3,
146
+ previous_decisions: 0.15,
147
+ current_state: 0.15,
148
+ constraints: 0.1,
149
+ known_failures_or_rejected: 0.1,
150
+ preferences: 0.05,
151
+ conflicts: 0.05,
152
+ open_tasks: 0.05,
153
+ uncertainties_or_gaps: 0.05,
154
+ });
155
+ /** Design §11's neighbourhood and authority-gap thresholds, verbatim. */
156
+ export const CONFLICT_POLICY = Object.freeze({ neighbourhoodThreshold: 0.6, authorityGap: 0.2 });
157
+ export const SELECTION_POLICY = Object.freeze({
158
+ lambda: 0.5,
159
+ marginalFloor: 0.15,
160
+ reserveRatio: 0.1,
161
+ sectionShares: SECTION_SHARES,
162
+ quotaOverFactor: 1.5,
163
+ quotaFloor: 0.5,
164
+ shingleSize: 3,
165
+ });
166
+ /* ------------------------------------------------------------------------------------------------
167
+ * The registry
168
+ * ---------------------------------------------------------------------------------------------- */
169
+ export const DEFAULT_POLICY_ID = "default@2";
170
+ /**
171
+ * Bumped whenever any policy in the registry changes. Design §19 item 3 gates that on approval.
172
+ *
173
+ * **@1 → @2 in Phase 2, and this is an approval item, declared as one.** Design §19 item 3 makes a
174
+ * `policy.ts` bump a decision requiring human approval, with the §22 change packet. What changed and
175
+ * what did not:
176
+ *
177
+ * - **The six ranking weights are byte-identical in all five policies.** They were measured in Phase
178
+ * 1 and the Phase 2 brief forbids tuning them; nothing here re-balances relevance against
179
+ * authority.
180
+ * - **`evidence` gained three terms** (`ungroundedCeiling`, `corroborationBonus`/`corroborationCap`,
181
+ * `contradictionPenalty`) because Phase 2's remit is evidence-strength scoring over the real
182
+ * provenance graph. On a claim with one independent group and no contradiction at distance ≤ 2 the
183
+ * formula reduces exactly to Phase 1's, so the change is additive rather than a re-baseline.
184
+ * - **`conflict` is new**, holding design §11's two already-fixed thresholds (0.6, 0.2). No number
185
+ * in it is new; it moves them out of code and into the reviewable table.
186
+ *
187
+ * The version string lands in every trace event and in the briefing's `policy_version`, so a replay
188
+ * can tell a Phase 1 score from a Phase 2 one rather than having to infer it.
189
+ */
190
+ export const POLICY_REGISTRY_VERSION = "mnemosia/policy-registry@3";
191
+ /**
192
+ * **@2 → @3 in Phase 4, and this is an approval item, declared as one** (design §19 item 3, with the
193
+ * spec §22 change packet). What changed:
194
+ *
195
+ * - **Two policies added**, `samaela@3` and `astrelia@3`, reached through the new agent link. Six of
196
+ * the eight Conclave seats are bound to policies that already existed and are byte-identical to
197
+ * what Phase 2 measured (`agents.ts:AGENT_POLICY`).
198
+ * - **One authority table added**, `ASTRELIA_AUTHORITY_TABLE`. `AUTHORITY_TABLE` itself is untouched
199
+ * and still backs the other six policies.
200
+ * - **The resolution chain gained a link.** `(agent)` now sits between `(agent, *, mode)` and
201
+ * `(*, taskType, *)`. This is the only change with a blast radius beyond the two new policies: a
202
+ * caller naming a Conclave seat can now resolve to a different policy than it did under @2, on
203
+ * every task where the inferred task type previously won.
204
+ * - **`SelectionPolicy.sectionShares` became per-agent** through `withAgentSelection`. The nine
205
+ * shares still sum to 1.00 for every seat, checked at load in `agents.ts`.
206
+ *
207
+ * What did **not** change: the six ranking weights of `default@2`, `debug@2`, `review@2`, `recall@2`
208
+ * and `vesperia-fast@2`; `EVIDENCE_POLICY`; `CONFLICT_POLICY`; `HALF_LIFE_DAYS`; the certainty map;
209
+ * and every `@2` policy id, so a replay can still tell a Phase 2 score from a Phase 4 one.
210
+ */
211
+ export const PRIOR_POLICY_REGISTRY_VERSION = "mnemosia/policy-registry@2";
212
+ /**
213
+ * Astrelia's authority table (Phase 4).
214
+ *
215
+ * The only table in the registry that is not `AUTHORITY_TABLE`, and the deviation is confined to
216
+ * one field's worth of reasoning. Design §9's shared ordering — curated 0.9 above summary 0.7 above
217
+ * tool 0.5 — encodes "a human wrote this down on purpose, so believe it". That is right for seven
218
+ * seats. It is wrong for the one whose question is *where is the implementation*: a tool transcript
219
+ * that read the file is a direct observation of the code, while a curated decision memo is a claim
220
+ * about intent that the code may since have diverged from. So `tool_output` rises to 0.80 and
221
+ * `curated_memory` falls to 0.60 — they swap sides of `compaction_summary` — and nothing else moves.
222
+ *
223
+ * `assistant_message` (0.35) and `unknown` (0.30) are untouched: a model's paraphrase of a file is
224
+ * not an observation of it however useful the file listing was, and design §9's reason for putting
225
+ * `unknown` at the bottom (an unclassified event kind must not inherit a classified one's standing)
226
+ * is a statement about classification rather than about this seat.
227
+ */
228
+ export const ASTRELIA_AUTHORITY_TABLE = Object.freeze({
229
+ curated_memory: 0.6,
230
+ compaction_summary: 0.55,
231
+ user_message: 0.6,
232
+ tool_output: 0.8,
233
+ assistant_message: 0.35,
234
+ unknown: 0.3,
235
+ });
236
+ /** Everything a policy shares with `default@1`, so a named policy is a weight diff and nothing else. */
237
+ function policy(name, version, match, weights, rationale, overrides = {}) {
238
+ return Object.freeze({
239
+ policyId: `${name}@${version}`,
240
+ name,
241
+ version,
242
+ match,
243
+ weights: Object.freeze(weights),
244
+ authority: overrides.authority ?? AUTHORITY_TABLE,
245
+ halfLifeDays: HALF_LIFE_DAYS,
246
+ halfLifeDaysByMemoryKind: HALF_LIFE_DAYS_BY_MEMORY_KIND,
247
+ certaintyConfidence: CERTAINTY_CONFIDENCE,
248
+ curatedImportanceWeight: 0.3,
249
+ integrityScore: INTEGRITY_SCORE,
250
+ evidence: EVIDENCE_POLICY,
251
+ relevanceBonus: RELEVANCE_BONUS,
252
+ selection: SELECTION_POLICY,
253
+ conflict: CONFLICT_POLICY,
254
+ rationale,
255
+ });
256
+ }
257
+ /**
258
+ * The Phase 1 registry.
259
+ *
260
+ * Five policies, and each one exists because a *measurable* task type wants different evidence, not
261
+ * to populate a table. They differ in weights only: the tables above are shared, so a change to the
262
+ * authority of a source is one edit rather than five.
263
+ *
264
+ * Every weight vector sums to 1.0 — checked at module load by `assertWeightsSumToOne`, because a
265
+ * vector that sums to 0.95 would silently shrink every utility in that policy and make cross-policy
266
+ * comparison of `utility` meaningless.
267
+ */
268
+ export const POLICIES = Object.freeze([
269
+ policy("default", "2", { agent: "*", taskType: "*", mode: "*" }, { relevance: 0.3, authority: 0.18, freshness: 0.16, confidence: 0.14, evidenceStrength: 0.12, integrity: 0.1 }, "relevance leads because an unrelated memory is worse than a missing one; authority and freshness follow because this corpus is a week of dense sessions in which the same subject was revisited under changing conclusions"),
270
+ policy("debug", "2", { agent: "*", taskType: "debug", mode: "*" }, { relevance: 0.32, freshness: 0.24, evidenceStrength: 0.12, confidence: 0.12, authority: 0.12, integrity: 0.08 }, "a debugger needs what broke most recently and what was actually observed; freshness is nearly doubled and authority halved, because a tool transcript from an hour ago beats a curated decision from last month for this task and only for this task"),
271
+ policy("review", "2", { agent: "*", taskType: "review", mode: "*" }, { relevance: 0.22, authority: 0.22, integrity: 0.2, evidenceStrength: 0.18, confidence: 0.12, freshness: 0.06 }, "a reviewer is judging whether something is right, so provenance quality outranks recency; integrity doubles and freshness drops to the floor"),
272
+ policy("recall", "2", { agent: "*", taskType: "recall", mode: "*" }, { relevance: 0.3, authority: 0.2, evidenceStrength: 0.16, confidence: 0.14, integrity: 0.12, freshness: 0.08 }, "an explicit recall request is usually about older material by definition; freshness is halved so that asking about history does not return this morning"),
273
+ policy("vesperia-fast", "2", { agent: "vesperia", taskType: "*", mode: "fast" }, { relevance: 0.4, freshness: 0.2, authority: 0.14, confidence: 0.1, evidenceStrength: 0.09, integrity: 0.07 }, "fast mode gives Vesperia a 2,000-token budget and ≤2 sources; with that little room the only signal that reliably pays for a token is topical fit, so relevance takes 0.40 and the corroboration signals give way"),
274
+ /* --- Phase 4: the two agent-keyed policies, and only two ------------------------------------ */
275
+ //
276
+ // `match` on both is `{agent, *, *}` so they are reached through the new agent link rather than
277
+ // through links 1 or 2. Six of the eight Conclave seats are *not* here, because they share an
278
+ // existing policy — `agents.ts:AGENT_POLICY` records which and why. Eight near-identical weight
279
+ // vectors would have been the placeholder abstraction design §26 forbids; the finding that six
280
+ // roles imply no distinct ordering is worth more than six tables a reader would have to diff.
281
+ policy("samaela", "3", { agent: "samaela", taskType: "*", mode: "*" }, { relevance: 0.28, authority: 0.24, confidence: 0.14, evidenceStrength: 0.14, freshness: 0.1, integrity: 0.1 }, "a planner reconstructs what was settled and why. Authority takes 0.24 — the highest in the registry — because a recorded decision's standing is exactly what makes it binding on a new plan, and freshness falls to 0.10 because a decision does not stop being the decision by ageing: supersession retires it, and supersession is a conflict class rather than a decay curve. Relevance still leads, at 0.28, because an unrelated decision is worse than a missing one"),
282
+ policy("astrelia", "3", { agent: "astrelia", taskType: "*", mode: "*" }, { relevance: 0.3, authority: 0.18, freshness: 0.16, confidence: 0.14, evidenceStrength: 0.12, integrity: 0.1 }, "**the six weights are byte-identical to default@2 and that is deliberate** — nothing about how the code scout trades relevance against authority differs. What differs is the authority *table*: for the question 'where is the implementation', a tool transcript that read the file is direct evidence and a curated memo is a claim about intent, so tool_output rises to 0.80 and curated_memory falls to 0.60 (see ASTRELIA_AUTHORITY_TABLE). Recording the difference where source standing is configured, rather than as a re-weighting, keeps the two kinds of change separable in a diff", { authority: ASTRELIA_AUTHORITY_TABLE }),
283
+ ]);
284
+ /* ------------------------------------------------------------------------------------------------
285
+ * Load-time invariants
286
+ * ---------------------------------------------------------------------------------------------- */
287
+ function assertWeightsSumToOne(candidate) {
288
+ let total = 0;
289
+ for (const signal of RANK_SIGNALS)
290
+ total += candidate.weights[signal];
291
+ if (Math.abs(total - 1) > 1e-9)
292
+ throw new Error(`policy ${candidate.policyId}: weights sum to ${total}, expected 1`);
293
+ }
294
+ function assertSharesSumToOne() {
295
+ let total = 0;
296
+ for (const share of Object.values(SECTION_SHARES))
297
+ total += share;
298
+ if (Math.abs(total - 1) > 1e-9)
299
+ throw new Error(`section shares sum to ${total}, expected 1`);
300
+ }
301
+ /**
302
+ * Every `AGENT_POLICY` binding names a policy the registry actually holds.
303
+ *
304
+ * Without this, a typo in a binding would demote that seat to the task link at runtime — the
305
+ * per-agent layer reading as configured while doing nothing — and the symptom would be a subtly
306
+ * different briefing rather than an error. Checked at load, so the failure is a startup crash with
307
+ * the offending name in it.
308
+ */
309
+ function assertAgentBindingsResolve() {
310
+ const known = new Set(POLICIES.map((entry) => entry.policyId));
311
+ for (const [agent, binding] of Object.entries(AGENT_POLICY)) {
312
+ if (!known.has(binding.policyId))
313
+ throw new Error(`agent ${agent} is bound to ${binding.policyId}, which the registry does not hold`);
314
+ }
315
+ }
316
+ for (const candidate of POLICIES)
317
+ assertWeightsSumToOne(candidate);
318
+ assertSharesSumToOne();
319
+ assertAgentBindingsResolve();
320
+ /* ------------------------------------------------------------------------------------------------
321
+ * Lookup
322
+ * ---------------------------------------------------------------------------------------------- */
323
+ function matchKey(agent, taskType, mode) {
324
+ return `${agent.toLowerCase()}${taskType}${mode}`;
325
+ }
326
+ const POLICY_INDEX = new Map(POLICIES.map((entry) => [matchKey(entry.match.agent, entry.match.taskType, entry.match.mode), entry]));
327
+ export const DEFAULT_POLICY = (() => {
328
+ const found = POLICIES.find((entry) => entry.policyId === DEFAULT_POLICY_ID);
329
+ if (found === undefined)
330
+ throw new Error(`the registry has no ${DEFAULT_POLICY_ID}`);
331
+ return found;
332
+ })();
333
+ /**
334
+ * The chain, **five links after Phase 4**:
335
+ * `(agent, taskType, mode)` → `(agent, *, mode)` → **agent binding** → `(*, taskType, *)` → `default@2`.
336
+ *
337
+ * **The third link is new, and it is the link design §9's chain was missing.** Spec §12 lists
338
+ * "Requesting agent" first among the dimensions ranking policy must be configurable by, but the
339
+ * four-link chain could only express an agent policy *jointly with a mode*: the only agent-keyed
340
+ * entry in the Phase 1 registry, `vesperia-fast@2`, is pinned to `fast`, and there was no key at
341
+ * which "this is how Samaela reads memory, in every mode" could be written down. Adding the link is
342
+ * therefore a correction to the chain rather than a new feature on top of it.
343
+ *
344
+ * **Why it sits above `(*, taskType, *)` rather than below.** Both links bind exactly one dimension,
345
+ * so specificity does not order them and something else has to. Two things do, and they agree. The
346
+ * existing chain already prefers the agent dimension at the two-dimension level — `(agent, *, mode)`
347
+ * is tried before `(*, taskType, *)` — so putting the agent binding below the task link would make
348
+ * the chain prefer agent over task at two dimensions and task over agent at one. And the requesting
349
+ * agent is **declared by the caller** while the task type is **inferred by `analyzeTask` from the
350
+ * text**; a resolver that let an inference override a declaration would be backwards on exactly the
351
+ * dimension Phase 4 exists to make real.
352
+ *
353
+ * The consequence is stated rather than discovered: this changes which policy resolves for a caller
354
+ * that names a Conclave seat, on every task where the inferred task type would previously have won.
355
+ * The full Phase 1, 2 and 3 threshold tables are re-run under it and reported whatever they say.
356
+ *
357
+ * It terminates: the last link is a constant that the load-time check above proves exists. There is
358
+ * deliberately no "closest match" scoring — a resolver that could return a policy nobody wrote down
359
+ * would make `policy_version` in the briefing a guess rather than a fact.
360
+ */
361
+ export function resolvePolicy(agent, taskType, mode) {
362
+ const resolved = resolveAgent(agent);
363
+ const attempts = [
364
+ { key: matchKey(agent, taskType, mode), matchedBy: "agent_task_mode" },
365
+ { key: matchKey(agent, "*", mode), matchedBy: "agent_mode" },
366
+ ];
367
+ const attempted = [];
368
+ for (const attempt of attempts) {
369
+ attempted.push(attempt.key);
370
+ const found = POLICY_INDEX.get(attempt.key);
371
+ if (found !== undefined)
372
+ return { policy: found, matchedBy: attempt.matchedBy, attempted, resolvedAgent: resolved.agent };
373
+ }
374
+ // Link 3. The binding names a policyId rather than a match key, so two seats can share one policy
375
+ // visibly (`agents.ts:AGENT_POLICY`) instead of each carrying a private copy of the same weights.
376
+ if (resolved.agent !== null) {
377
+ const binding = AGENT_POLICY[resolved.agent];
378
+ attempted.push(`agent:${resolved.agent}${binding.policyId}`);
379
+ const bound = POLICIES.find((entry) => entry.policyId === binding.policyId);
380
+ // A binding naming a policy the registry does not hold is a programming error, not a runtime
381
+ // condition to absorb: it would silently demote the seat to the task link and make the
382
+ // per-agent layer look configured when it was not. The load-time check below makes it
383
+ // unreachable, and this branch simply never runs.
384
+ if (bound !== undefined)
385
+ return { policy: bound, matchedBy: "agent", attempted, resolvedAgent: resolved.agent };
386
+ }
387
+ attempted.push(matchKey("*", taskType, "*"));
388
+ const byTask = POLICY_INDEX.get(matchKey("*", taskType, "*"));
389
+ if (byTask !== undefined)
390
+ return { policy: byTask, matchedBy: "task", attempted, resolvedAgent: resolved.agent };
391
+ attempted.push(matchKey("*", "*", "*"));
392
+ return { policy: DEFAULT_POLICY, matchedBy: "default", attempted, resolvedAgent: resolved.agent };
393
+ }
394
+ /**
395
+ * The resolved policy with this agent's section shares in place of design §10's.
396
+ *
397
+ * Section shares live on `SelectionPolicy`, which lives on `RankingPolicy`, so they are already part
398
+ * of the surface design §19 item 3 gates on approval — this does not open a new one. What it does is
399
+ * let the *composition* layer vary without touching the six ranking weights: `astrelia@3` and
400
+ * `samaela@3` are the only weight changes Phase 4 makes, and every other per-agent difference in the
401
+ * delivered briefing comes through this function.
402
+ *
403
+ * The returned object is a fresh frozen clone. Mutating the registry entry in place would make the
404
+ * policy a caller sees depend on which agent asked last, and the §16 determinism gate compares
405
+ * briefings across three runs.
406
+ */
407
+ export function withAgentSelection(base, profile) {
408
+ // Compared **by value**, not by reference. `agents.ts` cannot import `SECTION_SHARES` from here
409
+ // without a module cycle (this file imports `AGENT_POLICY` from there), so the three seats that
410
+ // keep design §10's shares hold an equal-but-distinct object. A reference check would have cloned
411
+ // the policy for them anyway and quietly broken the property this function exists to guarantee:
412
+ // that a seat with no composition requirement is scored against the object Phases 1–3 measured.
413
+ let identical = true;
414
+ for (const section of Object.keys(base.selection.sectionShares)) {
415
+ if (base.selection.sectionShares[section] !== profile.sectionShares[section]) {
416
+ identical = false;
417
+ break;
418
+ }
419
+ }
420
+ if (identical)
421
+ return base;
422
+ return Object.freeze({ ...base, selection: Object.freeze({ ...base.selection, sectionShares: profile.sectionShares }) });
423
+ }
424
+ export function policyById(policyId) {
425
+ return POLICIES.find((entry) => entry.policyId === policyId);
426
+ }