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,174 @@
1
+ // Ported from mnemosia/retention.ts @ f0a8ad4 (MIT; see NOTICE)
2
+ /**
3
+ * Retention: the trace-rotation policy of design §17 ambiguity 2 and §19 item 4.
4
+ *
5
+ * ─────────────────────────────────────────────────────────────────────────────────────────────────
6
+ * THE DECISION IS NOT RECORDED AS MADE, AND THAT IS THE POINT OF THIS HEADER.
7
+ * ─────────────────────────────────────────────────────────────────────────────────────────────────
8
+ *
9
+ * Design §17 ambiguity 2 reads: *"Trace retention — unbounded at ~5–20KB/run. Default: keep
10
+ * everything until Phase 2. Needs a human decision."* Two things follow.
11
+ *
12
+ * **First: the stated default has expired.** "Keep everything until Phase 2" was a default with a
13
+ * termination condition, and the condition has been met — Phase 2 is built and measured. So the
14
+ * ambiguity is no longer non-blocking in the way §17 claims for its entries; it currently has *no*
15
+ * working default at all, only a lapsed one. That is a finding about the design document rather than
16
+ * about the code, and it is recorded here rather than quietly patched.
17
+ *
18
+ * **Second: §19 item 4 makes the replacement a human approval item.** This module therefore does what
19
+ * `mutate.ts` does with §19 item 2, for the same reason and with the same shape: it builds the whole
20
+ * mechanism, states a default policy in reviewable form, computes exactly what that policy *would*
21
+ * delete against the real directory — and does not delete it. `planTraceRotation` is pure and always
22
+ * safe to call. `applyTraceRotation` requires a `RetentionGate` that only `enableRetention(named,
23
+ * justification)` can produce, and in piroboros only `open.ts` calls that, with the user's approval.
24
+ *
25
+ * Recording the decision as made would be Mnemosia approving a §19 item on a human's behalf, which is
26
+ * precisely the move this entire phase exists to refuse. Recording it as made *while also* refusing
27
+ * to activate §19 item 2 would be worse: it would mean the approval discipline holds for the item
28
+ * whose subject is somebody else's database and lapses for the item whose subject is Mnemosia's own
29
+ * audit log — which is the one an interested party would most want to shorten.
30
+ *
31
+ * What is offered instead of a decision is the number the decision needs. `scripts/phase3-live.ts`
32
+ * prints the measured trace-directory size, file count and age spread, so the choice costs the human
33
+ * a minute rather than an investigation.
34
+ *
35
+ * ─────────────────────────────────────────────────────────────────────────────────────────────────
36
+ * THE PROPOSED DEFAULT, stated so it can be approved or rejected as written
37
+ * ─────────────────────────────────────────────────────────────────────────────────────────────────
38
+ *
39
+ * Keep a trace while either of two things is true, and delete it only when neither is:
40
+ *
41
+ * - it is younger than `maxAgeDays` (proposed: **90**), or
42
+ * - it is among the `keepRuns` most recent traces (proposed: **500**).
43
+ *
44
+ * The disjunction, rather than an age cut alone, is what makes the policy safe on a quiet machine:
45
+ * an age-only rule would empty the directory entirely after a three-month gap, and `explainDecision`
46
+ * — the whole reason traces are kept — would then have nothing to answer with. The count floor is
47
+ * what guarantees that "why was this not in my briefing" is always answerable for recent work.
48
+ *
49
+ * 90 days is derived rather than picked: it is the half-life design §9 assigns to `FACT`, i.e. the
50
+ * horizon past which this system already treats its own retrieved material as substantially stale.
51
+ * A retention window shorter than the freshness horizon would discard the audit of decisions the
52
+ * ranker still considers current. 500 runs at the measured ~5–20KB/run bounds the floor at 2.5–10MB,
53
+ * which is a rounding error beside the 112MB corpus it audits.
54
+ *
55
+ * **Never deleted regardless of policy:** any trace named by a `PENDING` or `APPROVED` item in the
56
+ * approval queue. A write proposal a human has not yet decided must not lose the audit of the run
57
+ * that produced it — that is the one case where a trace is not merely derived history but the
58
+ * evidence behind a pending decision.
59
+ */
60
+ import { existsSync, readdirSync, rmSync, statSync } from "node:fs";
61
+ import { join } from "node:path";
62
+ export const RETENTION_POLICY_SCHEMA_VERSION = "mnemosia/retention-policy@1";
63
+ /** The proposal of the header. It is a *proposal*: nothing applies it. */
64
+ export const TRACE_RETENTION_DEFAULT = Object.freeze({
65
+ schemaVersion: RETENTION_POLICY_SCHEMA_VERSION,
66
+ maxAgeDays: 90,
67
+ keepRuns: 500,
68
+ });
69
+ export const DEFAULT_RETENTION_GATE = Object.freeze({
70
+ schemaVersion: "mnemosia/retention-gate@1",
71
+ rotationEnabled: false,
72
+ enabledBy: null,
73
+ justification: null,
74
+ });
75
+ export function enableRetention(enabledBy, justification) {
76
+ if (typeof enabledBy !== "string" || enabledBy.trim().length === 0)
77
+ throw new Error("enableRetention requires a named enabler; design §19 item 4 is a human decision");
78
+ if (typeof justification !== "string" || justification.trim().length === 0)
79
+ throw new Error("enableRetention requires a justification; deleting an audit trail is not a maintenance task");
80
+ return Object.freeze({ schemaVersion: "mnemosia/retention-gate@1", rotationEnabled: true, enabledBy: enabledBy.trim(), justification: justification.trim() });
81
+ }
82
+ export function readTraceDirectory(root, now = Date.now()) {
83
+ if (!existsSync(root))
84
+ return [];
85
+ const files = [];
86
+ for (const name of readdirSync(root)) {
87
+ if (!name.endsWith(".jsonl"))
88
+ continue;
89
+ const path = join(root, name);
90
+ let stat;
91
+ try {
92
+ stat = statSync(path);
93
+ }
94
+ catch {
95
+ continue;
96
+ }
97
+ if (!stat.isFile())
98
+ continue;
99
+ files.push({ runId: name.slice(0, -".jsonl".length), path, bytes: stat.size, mtimeMs: stat.mtimeMs, ageDays: (now - stat.mtimeMs) / 86_400_000 });
100
+ }
101
+ // Newest first, so "the N most recent" is a prefix and the ordering is total.
102
+ files.sort((a, b) => b.mtimeMs - a.mtimeMs || (a.runId < b.runId ? -1 : a.runId > b.runId ? 1 : 0));
103
+ return files;
104
+ }
105
+ /**
106
+ * Pure, side-effect free, and always safe to call. This is what a human reads before deciding.
107
+ */
108
+ export function planTraceRotation(options) {
109
+ const root = options.root;
110
+ const now = options.now ?? Date.now();
111
+ const policy = options.policy ?? TRACE_RETENTION_DEFAULT;
112
+ const pinnedIds = new Set(options.pinnedRunIds ?? []);
113
+ const files = readTraceDirectory(root, now);
114
+ const keep = [];
115
+ const remove = [];
116
+ const pinned = [];
117
+ files.forEach((file, index) => {
118
+ if (pinnedIds.has(file.runId)) {
119
+ pinned.push(file);
120
+ keep.push(file);
121
+ return;
122
+ }
123
+ // The disjunction: recent by age OR recent by rank. Only failing both makes a file removable.
124
+ if (file.ageDays < policy.maxAgeDays || index < policy.keepRuns)
125
+ keep.push(file);
126
+ else
127
+ remove.push(file);
128
+ });
129
+ return {
130
+ policy,
131
+ root,
132
+ now,
133
+ files: files.length,
134
+ bytes: files.reduce((sum, file) => sum + file.bytes, 0),
135
+ keep,
136
+ remove,
137
+ pinned,
138
+ bytesReclaimable: remove.reduce((sum, file) => sum + file.bytes, 0),
139
+ oldestAgeDays: files.length === 0 ? 0 : files[files.length - 1].ageDays,
140
+ newestAgeDays: files.length === 0 ? 0 : files[0].ageDays,
141
+ };
142
+ }
143
+ /**
144
+ * The only function here that deletes anything, and it refuses unless §19 item 4 has been granted.
145
+ *
146
+ * The refusal is the default and there is no configuration that changes it — same construction as
147
+ * `mutate.ts`'s gate, and for a stronger reason: an audit trail that a program may prune on its own
148
+ * initiative is an audit trail whose absences cannot be distinguished from its silences.
149
+ */
150
+ export function applyTraceRotation(plan, gate = DEFAULT_RETENTION_GATE) {
151
+ if (!gate.rotationEnabled) {
152
+ return {
153
+ applied: false,
154
+ removed: [],
155
+ failed: [],
156
+ bytesReclaimed: 0,
157
+ reason: `trace rotation is NOT ACTIVE. Design §19 item 4 makes the retention policy a human approval item and no approval is recorded. The proposed default (keep < ${plan.policy.maxAgeDays}d OR among the ${plan.policy.keepRuns} most recent) would remove ${plan.remove.length} of ${plan.files} trace file(s), reclaiming ${plan.bytesReclaimable} bytes. Nothing was deleted.`,
158
+ };
159
+ }
160
+ const removed = [];
161
+ const failed = [];
162
+ let bytesReclaimed = 0;
163
+ for (const file of plan.remove) {
164
+ try {
165
+ rmSync(file.path);
166
+ removed.push(file.runId);
167
+ bytesReclaimed += file.bytes;
168
+ }
169
+ catch (error) {
170
+ failed.push({ path: file.path, error: error instanceof Error ? error.message : String(error) });
171
+ }
172
+ }
173
+ return { applied: true, removed, failed, bytesReclaimed, reason: `rotation applied under ${gate.enabledBy}'s authorization (${gate.justification}); ${removed.length} removed, ${failed.length} failed` };
174
+ }
@@ -0,0 +1,337 @@
1
+ // Ported from mnemosia/rollback.ts @ f0a8ad4 (MIT; see NOTICE)
2
+ /**
3
+ * Safe rollback: policy-registry versions as addressable state, and spec §22's change record as a
4
+ * real artifact (Phase 5).
5
+ *
6
+ * Design §19 item 3 already made a `policy.ts` bump a human approval item, and Phase 2 and Phase 4
7
+ * each declared one — `mnemosia/policy-registry@1 → @2` and `@2 → @3`. What neither phase built is
8
+ * the other half of an approval: the ability to *un*-approve. Three things are needed for that and
9
+ * this module holds all three.
10
+ *
11
+ * 1. **Address a prior version.** `resolvePolicyAt(version, …)` answers "which policy would this
12
+ * request have resolved to under `@2`" — with the `@2` *chain*, not just the `@2` entries, because
13
+ * §19's own change list records that the resolution chain gained a link at `@3` and that link is
14
+ * the change with the widest blast radius.
15
+ * 2. **Bind a run to it.** `PolicyPin` is passed to `runBriefing` through `OrchestratorDeps` and lands
16
+ * in the `ANALYZE_TASK` trace payload, so a pinned run says in its own audit log which registry it
17
+ * was decided under. Without that, a rollback would be indistinguishable in the trace from a
18
+ * resolver bug.
19
+ * 3. **Prove the revert is exact.** A rollback that "mostly" restores prior behaviour is not a
20
+ * rollback. `replay.ts` is how that is proved: the same recorded envelopes, replayed under the
21
+ * pinned version, must reproduce the prior fingerprint *including the briefing digest*.
22
+ *
23
+ * **What a policy-registry pin does and does not roll back.** Design §21 keeps two layers apart —
24
+ * the *ranking policy* (`policy.ts`, gated by §19 item 3) and the *briefing profile* (`agents.ts`:
25
+ * lead order, addendum blocks, conflict presentation). A registry pin moves the first and leaves the
26
+ * second alone, with one deliberate exception: `SelectionPolicy.sectionShares` lives on
27
+ * `RankingPolicy`, and §19's `@2 → @3` packet lists "sectionShares became per-seat through
28
+ * `withAgentSelection`" as one of the four registry changes. So `appliesAgentSelection` is false
29
+ * below `@3` and the per-seat shares go back with the rest of the registry. Rolling the *profile*
30
+ * back as well would be a second, unversioned change riding inside the one that was asked for —
31
+ * which is exactly what §21.6 refused to let the Phase 4 agent-file build do.
32
+ */
33
+ import { AGENT_POLICY, resolveAgent } from "./agents.js";
34
+ import { DEFAULT_POLICY_ID, POLICIES, POLICY_REGISTRY_VERSION, PRIOR_POLICY_REGISTRY_VERSION } from "./policy.js";
35
+ import { SCHEMA_VERSION } from "./types.js";
36
+ /**
37
+ * The three registry versions, and the honest statement that only two of them can be run.
38
+ *
39
+ * **`@1` is not reconstructible and saying so is the point.** Phase 2's bump added three terms to
40
+ * `EvidencePolicy` and a whole `conflict` sub-policy, and it renamed every policy id from `<name>@1`
41
+ * to `<name>@2`. The `@1` objects were not kept — `POLICIES` holds the current registry only — so a
42
+ * claim that Mnemosia can roll back to `@1` would be a claim about data that does not exist. It is
43
+ * recorded here as a **limit of the rollback machinery**, which is a Phase 5 finding, rather than
44
+ * quietly reconstructed from the design document's prose. Rolling back to `@1` would additionally
45
+ * mean rolling back the Phase 2 evidence graph that `rank.ts` now computes against, i.e. reverting
46
+ * code and not only data.
47
+ */
48
+ export const POLICY_REGISTRY_HISTORY = Object.freeze([
49
+ Object.freeze({
50
+ version: "mnemosia/policy-registry@1",
51
+ phase: "Phase 1",
52
+ reconstructible: false,
53
+ chain: Object.freeze(["(agent, taskType, mode)", "(agent, *, mode)", "(*, taskType, *)", "default@1"]),
54
+ agentSelection: false,
55
+ detail: "five policies, ids `<name>@1`, `EvidencePolicy` without ungroundedCeiling/corroboration/contradictionPenalty and with no `conflict` sub-policy. The objects were replaced rather than retained at the @2 bump, so this version cannot be resolved today; reverting to it would also mean reverting rank.ts's Phase 2 evidence formula, i.e. code and not only data.",
56
+ }),
57
+ Object.freeze({
58
+ version: PRIOR_POLICY_REGISTRY_VERSION,
59
+ phase: "Phase 2 / Phase 3",
60
+ reconstructible: true,
61
+ chain: Object.freeze(["(agent, taskType, mode)", "(agent, *, mode)", "(*, taskType, *)", DEFAULT_POLICY_ID]),
62
+ agentSelection: false,
63
+ detail: "the five @2 policies, which are still present byte-identical in POLICIES (design §19: 'every @2 policy id' was left unchanged by the @3 bump). Resolvable exactly: filter the registry to the @2 ids and run the four-link chain.",
64
+ }),
65
+ Object.freeze({
66
+ version: POLICY_REGISTRY_VERSION,
67
+ phase: "Phase 4 / Phase 5",
68
+ reconstructible: true,
69
+ chain: Object.freeze(["(agent, taskType, mode)", "(agent, *, mode)", "agent binding", "(*, taskType, *)", DEFAULT_POLICY_ID]),
70
+ agentSelection: true,
71
+ detail: "adds samaela@3 and astrelia@3, the agent-binding link, ASTRELIA_AUTHORITY_TABLE, and per-seat sectionShares through withAgentSelection.",
72
+ }),
73
+ ]);
74
+ export function registryVersionRecord(version) {
75
+ return POLICY_REGISTRY_HISTORY.find((entry) => entry.version === version);
76
+ }
77
+ /** Versions a run can actually be resolved under today. */
78
+ export function reconstructibleRegistryVersions() {
79
+ return POLICY_REGISTRY_HISTORY.filter((entry) => entry.reconstructible).map((entry) => entry.version);
80
+ }
81
+ /** Whether per-seat section shares apply at this registry version (a `@3` change, see the header). */
82
+ export function appliesAgentSelection(version) {
83
+ return registryVersionRecord(version)?.agentSelection ?? false;
84
+ }
85
+ /* ------------------------------------------------------------------------------------------------
86
+ * Resolution at a version
87
+ * ---------------------------------------------------------------------------------------------- */
88
+ /**
89
+ * The suffix of a policy id that names its registry generation. `samaela@3` → `3`.
90
+ *
91
+ * `RankingPolicy.version` already holds it; this reads the id so that the partition of the registry
92
+ * and the ids a reviewer sees in a trace cannot disagree.
93
+ */
94
+ function generationOf(policy) {
95
+ const at = policy.policyId.lastIndexOf("@");
96
+ return at === -1 ? policy.version : policy.policyId.slice(at + 1);
97
+ }
98
+ /** The registry as it stood at `version`: every policy whose generation is at or below it. */
99
+ export function policiesAt(version) {
100
+ const record = registryVersionRecord(version);
101
+ if (record === undefined)
102
+ throw new Error(`unknown policy-registry version ${version}; known: ${POLICY_REGISTRY_HISTORY.map((entry) => entry.version).join(", ")}`);
103
+ if (!record.reconstructible)
104
+ throw new Error(`${version} is not reconstructible: ${record.detail}`);
105
+ const ceiling = Number(version.slice(version.lastIndexOf("@") + 1));
106
+ return POLICIES.filter((policy) => Number(generationOf(policy)) <= ceiling);
107
+ }
108
+ function matchKey(agent, taskType, mode) {
109
+ return `${agent.toLowerCase()}${taskType}${mode}`;
110
+ }
111
+ /**
112
+ * `resolvePolicy` as it behaved at `version`.
113
+ *
114
+ * The chain is rebuilt here rather than parameterized inside `policy.ts` for a reason worth stating:
115
+ * `policy.ts` is the file design §19 item 3 gates on approval, and adding a "which chain would you
116
+ * like" switch to it would make the production resolver's behaviour a caller's choice. The pinned
117
+ * resolver is a separate function in a separate module that the production path does not call, and
118
+ * `runBriefing` reaches it only when a caller has explicitly supplied a `PolicyPin`.
119
+ */
120
+ export function resolvePolicyAt(version, agent, taskType, mode) {
121
+ const record = registryVersionRecord(version);
122
+ if (record === undefined)
123
+ throw new Error(`unknown policy-registry version ${version}`);
124
+ const available = policiesAt(version);
125
+ const index = new Map(available.map((entry) => [matchKey(entry.match.agent, entry.match.taskType, entry.match.mode), entry]));
126
+ const resolved = resolveAgent(agent);
127
+ const attempted = [];
128
+ const fallbackPolicy = available.find((entry) => entry.policyId === DEFAULT_POLICY_ID);
129
+ if (fallbackPolicy === undefined)
130
+ throw new Error(`the ${version} registry has no ${DEFAULT_POLICY_ID}`);
131
+ const answer = (policy, matchedBy) => {
132
+ // The comparison is against the *current* resolver, so a pin that changes nothing says so.
133
+ // Imported lazily-by-value rather than by calling resolvePolicy here would be circular; the
134
+ // caller supplies the comparison instead when it needs one, and this cheap form uses the
135
+ // registry's own head version.
136
+ const current = currentResolution(agent, taskType, mode);
137
+ return { policy, matchedBy, attempted, resolvedAgent: resolved.agent, registryVersion: version, differsFromCurrent: current !== policy.policyId, currentPolicyId: current };
138
+ };
139
+ for (const [key, matchedBy] of [
140
+ [matchKey(agent, taskType, mode), "agent_task_mode"],
141
+ [matchKey(agent, "*", mode), "agent_mode"],
142
+ ]) {
143
+ attempted.push(key);
144
+ const found = index.get(key);
145
+ if (found !== undefined)
146
+ return answer(found, matchedBy);
147
+ }
148
+ // Link 3 exists only from `@3`. Below it, a caller naming a Conclave seat falls through to the
149
+ // task link — which is precisely the behaviour design §21.4 item 1 records as the defect Phase 4
150
+ // corrected, and precisely what a rollback to `@2` is asking to restore.
151
+ if (record.chain.includes("agent binding") && resolved.agent !== null) {
152
+ const binding = AGENT_POLICY[resolved.agent];
153
+ attempted.push(`agent:${resolved.agent}${binding.policyId}`);
154
+ const bound = available.find((entry) => entry.policyId === binding.policyId);
155
+ if (bound !== undefined)
156
+ return answer(bound, "agent");
157
+ }
158
+ attempted.push(matchKey("*", taskType, "*"));
159
+ const byTask = index.get(matchKey("*", taskType, "*"));
160
+ if (byTask !== undefined)
161
+ return answer(byTask, "task");
162
+ attempted.push(matchKey("*", "*", "*"));
163
+ return answer(fallbackPolicy, "default");
164
+ }
165
+ /** The head registry's answer, used only to report whether a pin changes anything. */
166
+ function currentResolution(agent, taskType, mode) {
167
+ const index = new Map(POLICIES.map((entry) => [matchKey(entry.match.agent, entry.match.taskType, entry.match.mode), entry]));
168
+ const resolved = resolveAgent(agent);
169
+ const direct = index.get(matchKey(agent, taskType, mode)) ?? index.get(matchKey(agent, "*", mode));
170
+ if (direct !== undefined)
171
+ return direct.policyId;
172
+ if (resolved.agent !== null)
173
+ return AGENT_POLICY[resolved.agent].policyId;
174
+ return (index.get(matchKey("*", taskType, "*")) ?? POLICIES.find((entry) => entry.policyId === DEFAULT_POLICY_ID))?.policyId ?? DEFAULT_POLICY_ID;
175
+ }
176
+ /**
177
+ * The only constructor. It refuses an unknown or unreconstructible version *at construction time*
178
+ * rather than at resolution time, so a rollback plan that names `@1` fails while it is being written
179
+ * down instead of halfway through the run it was supposed to make safe.
180
+ */
181
+ // Ported library surface: no caller under src/ uses the pin or the policy change packet yet; the ported suite covers it.
182
+ export function pinPolicyRegistry(registryVersion, pinnedBy, reason) {
183
+ const record = registryVersionRecord(registryVersion);
184
+ if (record === undefined)
185
+ throw new Error(`unknown policy-registry version ${registryVersion}; known: ${POLICY_REGISTRY_HISTORY.map((entry) => entry.version).join(", ")}`);
186
+ if (!record.reconstructible)
187
+ throw new Error(`cannot pin ${registryVersion}: ${record.detail}`);
188
+ if (typeof pinnedBy !== "string" || pinnedBy.trim().length === 0)
189
+ throw new Error("pinPolicyRegistry requires a named pinner; a rollback nobody is accountable for is not a rollback");
190
+ if (typeof reason !== "string" || reason.trim().length === 0)
191
+ throw new Error("pinPolicyRegistry requires a reason; design §19 item 3 makes a registry change a human decision and undoing one is the same decision");
192
+ return Object.freeze({ schemaVersion: SCHEMA_VERSION.policyPin, registryVersion, pinnedBy: pinnedBy.trim(), reason: reason.trim(), agentSelection: record.agentSelection });
193
+ }
194
+ const PACKET_REQUIRED = ["previousVersion", "proposedVersion", "evaluationEvidence", "expectedBenefit", "regressionResults", "securityReview", "rollbackPlan", "approvalStatus"];
195
+ export function validatePolicyChangePacket(packet) {
196
+ const missing = [];
197
+ for (const field of PACKET_REQUIRED) {
198
+ const value = packet[field];
199
+ if (typeof value === "string" && value.trim().length === 0)
200
+ missing.push(field);
201
+ else if (Array.isArray(value) && value.length === 0)
202
+ missing.push(field);
203
+ else if (value === undefined || value === null)
204
+ missing.push(field);
205
+ }
206
+ if (packet.approvalStatus !== "PROPOSED" && (packet.decidedBy === null || packet.decidedBy.trim().length === 0))
207
+ missing.push("decidedBy");
208
+ return {
209
+ complete: missing.length === 0,
210
+ missing,
211
+ detail: missing.length === 0 ? `all eight spec §22 fields are present; approval status is ${packet.approvalStatus}` : `spec §22 requires all eight; missing: ${missing.join(", ")}`,
212
+ };
213
+ }
214
+ export function renderPolicyChangePacket(packet) {
215
+ const validation = validatePolicyChangePacket(packet);
216
+ const lines = [];
217
+ lines.push(`POLICY CHANGE PACKET (spec §22) — ${packet.previousVersion} → ${packet.proposedVersion}`);
218
+ lines.push("─".repeat(110));
219
+ lines.push(`1. previous version : ${packet.previousVersion}`);
220
+ lines.push(`2. proposed version : ${packet.proposedVersion}`);
221
+ lines.push(`3. evaluation evidence:`);
222
+ for (const entry of packet.evaluationEvidence)
223
+ lines.push(` - ${entry}`);
224
+ lines.push(`4. expected benefit : ${packet.expectedBenefit}`);
225
+ lines.push(`5. regression results :`);
226
+ for (const entry of packet.regressionResults)
227
+ lines.push(` - ${entry}`);
228
+ lines.push(`6. security review : ${packet.securityReview}`);
229
+ lines.push(`7. rollback plan : ${packet.rollbackPlan}`);
230
+ lines.push(`8. approval status : ${packet.approvalStatus}${packet.decidedBy === null ? "" : ` (decided by ${packet.decidedBy})`}`);
231
+ lines.push("");
232
+ lines.push(` changed : ${packet.changes.length === 0 ? "(none)" : ""}`);
233
+ for (const entry of packet.changes)
234
+ lines.push(` - ${entry}`);
235
+ lines.push(` unchanged: ${packet.unchanged.length === 0 ? "(none)" : ""}`);
236
+ for (const entry of packet.unchanged)
237
+ lines.push(` - ${entry}`);
238
+ lines.push("");
239
+ lines.push(` validation: ${validation.detail}`);
240
+ return lines.join("\n");
241
+ }
242
+ /**
243
+ * The two packets Phases 2 and 4 declared as outstanding approval items, written down as data.
244
+ *
245
+ * Design §19 item 3 recorded both in prose. Prose cannot be validated, diffed or refused, and a
246
+ * §22 obligation that lives only in a document is one nobody can be shown to have met — which is
247
+ * why the brief for this phase asks for "a real artifact the machinery produces, not prose". The
248
+ * content is unchanged from §19; only its form is. **Both remain `PROPOSED`.** Nothing in this
249
+ * codebase constructs `APPROVED`, and `test/rollback.test.ts` asserts it over the source tree.
250
+ */
251
+ export const OUTSTANDING_POLICY_CHANGES = Object.freeze([
252
+ Object.freeze({
253
+ schemaVersion: SCHEMA_VERSION.policyChangePacket,
254
+ previousVersion: "mnemosia/policy-registry@1",
255
+ proposedVersion: "mnemosia/policy-registry@2",
256
+ evaluationEvidence: Object.freeze([
257
+ "eval/harness.ts, full design §16 table re-run under @2 on the live corpus: 10/11, unchanged from @1, same single failure (irrelevant-memory rate 0.127 against ≤ 0.20 and ≤ ½ of the lexical baseline's 0.075).",
258
+ "eval/conflicts-eval.ts over 67 labelled seeds (46 positive, 21 negative): precision 1.000, recall 0.957, SUMMARY_SOURCE_MISMATCH catch 1.000, against pre-registered 0.80 / 0.60 / 0.90.",
259
+ "On a claim with one independent group, no contradiction and graph distance ≤ 2 the new evidence formula reduces exactly to Phase 1's, so the §16 table is comparable across the bump rather than silently re-baselined.",
260
+ ]),
261
+ expectedBenefit: "evidence_strength computed from the real provenance graph rather than from a flat list: independence (distinct sourceId|taskScope groups) stops one session cited three times reading as three witnesses, contradiction is priced, and an ungrounded summary claim falls below the authority floor of an assistant turn.",
262
+ regressionResults: Object.freeze([
263
+ "Phase 1 gate: 10/11 before, 10/11 after, identical failing row.",
264
+ "PHASE 6 RE-RUN, and the number above is kept as the record of what was measured at the time: the Phase 1 gate now reads 11/11 and the Phase 2 gate 3/4 (qualifier precision 0.784 over a fresh 227-hit sample). Neither movement is attributable to this bump — the failing row was retired by a threshold amendment argued in design §16, and the qualifier number came from correcting an extractor rule. The six ranking weights are still byte-identical and this packet's own delta is still inert.",
265
+ "Six ranking weights byte-identical in all five policies; EVIDENCE_POLICY additive; CONFLICT_POLICY moves two already-fixed constants out of code into the reviewable table without changing either value.",
266
+ "Determinism 30/30; provenance completeness 1.0000; stale inclusion 0; security isolation 0/6.",
267
+ ]),
268
+ securityReview: "no change to the trust boundary, the channel enum, the hard-filter set or the quarantine path. The three new EvidencePolicy terms are multipliers on a signal that is computed only over claims that already survived filtering, and no signal can resurrect a rejected candidate (design §9). The conflict sub-policy exposes two thresholds to review that were previously literals in conflicts.ts, which widens auditability rather than authority.",
269
+ rollbackPlan: "pinPolicyRegistry('mnemosia/policy-registry@1', …) is REFUSED: the @1 objects were replaced rather than retained, so this bump is NOT reversible by pinning. Reverting it requires reverting rank.ts's Phase 2 evidence formula as well — code, not only data. This is a limitation of the change as executed and is recorded rather than papered over.",
270
+ approvalStatus: "PROPOSED",
271
+ decidedBy: null,
272
+ changes: Object.freeze([
273
+ "EvidencePolicy += ungroundedCeiling 0.25, corroborationBonus 0.1, corroborationCap 0.2, contradictionPenalty 0.15",
274
+ "ConflictPolicy is new, holding design §11's already-fixed 0.6 and 0.2",
275
+ "every policy id `<name>@1` → `<name>@2`",
276
+ ]),
277
+ unchanged: Object.freeze(["the six ranking weights of all five policies", "AUTHORITY_TABLE", "HALF_LIFE_DAYS", "CERTAINTY_CONFIDENCE", "SECTION_SHARES", "SELECTION_POLICY"]),
278
+ }),
279
+ Object.freeze({
280
+ schemaVersion: SCHEMA_VERSION.policyChangePacket,
281
+ previousVersion: "mnemosia/policy-registry@2",
282
+ proposedVersion: "mnemosia/policy-registry@3",
283
+ evaluationEvidence: Object.freeze([
284
+ "scripts/phase4-ab.ts over the 19 labelled gold retrieval tasks, control arm produced by the shipped code (an unrecognised caller resolves DEFAULT_PROFILE, which *is* the Phase 3 composition): 19/19 same outcome, 18/19 same item count, 50 → 49 factual items.",
285
+ "scripts/phase4-live.ts, one live task through eight seats: 7 of 8 distinct evidence sets (Avaritia ≡ Vaelia, reported rather than obscured).",
286
+ "Blast radius stated before it was measured: the new agent link changes the resolved policy on 13 of the 19 gold retrieval tasks.",
287
+ ]),
288
+ expectedBenefit: "spec §12 lists 'requesting agent' first among the dimensions ranking must be configurable by, and the four-link chain had no key at which 'this is how Samaela reads memory, in every mode' could be written down. The fifth link makes the first-listed dimension reachable; the two new policies use it; six of the eight seats deliberately do not.",
289
+ regressionResults: Object.freeze([
290
+ "Phase 1 gate 10/11 (same single failure), Phase 2 gate 3/4 (same single failure), Phase 3 79/79 — all re-run under @3.",
291
+ "PHASE 6 RE-RUN under @3: Phase 1 11/11, Phase 2 3/4, Phase 3 79/79, Phase 4 19/19 same outcome and 7-of-8 distinct evidence sets, Phase 5 19/19 EXACT replay. The Phase 1 row moved because design §16's irrelevant-memory clause was amended, not because this bump changed anything; scripts/phase5-experiment.ts still measures the @2 and @3 arms as indistinguishable on all eight graded rows.",
292
+ "Critical recall 1.000, stale inclusion 0, provenance completeness 1.0000, security isolation 0/6, determinism 30/30.",
293
+ "No weight, gold label, fixture, proxy or threshold moved.",
294
+ ]),
295
+ securityReview: "the new link reads a caller-declared string (`requesting_agent`) and maps it through agents.ts:resolveAgent, which is exact rather than fuzzy — `vesperia-2` and `elara` resolve to nobody and receive the shared default with the reason stated in the briefing. A fuzzy resolver would hand a caller a profile designed around somebody else's job, which is a privilege question and not a UX one. ASTRELIA_AUTHORITY_TABLE lowers curated standing for one seat and raises tool_output; it cannot admit anything the hard filters rejected, because authority is a weight over the surviving set.",
296
+ rollbackPlan: "pinPolicyRegistry('mnemosia/policy-registry@2', pinnedBy, reason) restores the four-link chain, hides samaela@3 and astrelia@3, and disables per-seat sectionShares. Proved exact by replay.ts: the same recorded envelopes replayed under the pin must reproduce the @2 briefing digest byte for byte. Measured in Phase 5.",
297
+ approvalStatus: "PROPOSED",
298
+ decidedBy: null,
299
+ changes: Object.freeze([
300
+ "POLICIES += samaela@3, astrelia@3",
301
+ "resolution chain += the `(agent)` binding link, above `(*, taskType, *)`",
302
+ "ASTRELIA_AUTHORITY_TABLE is new (tool_output 0.50 → 0.80, curated_memory 0.90 → 0.60, for one seat)",
303
+ "SelectionPolicy.sectionShares becomes per-seat through withAgentSelection",
304
+ ]),
305
+ unchanged: Object.freeze(["the six weights of default@2, debug@2, review@2, recall@2, vesperia-fast@2", "AUTHORITY_TABLE", "EVIDENCE_POLICY", "CONFLICT_POLICY", "HALF_LIFE_DAYS", "CERTAINTY_CONFIDENCE", "every @2 policy id"]),
306
+ }),
307
+ ]);
308
+ // Ported library surface: no caller under src/ uses planRollback yet; the ported suite covers it.
309
+ export function planRollback(from, to, pinnedBy, reason) {
310
+ const target = registryVersionRecord(to);
311
+ const source = registryVersionRecord(from);
312
+ if (source === undefined)
313
+ throw new Error(`unknown policy-registry version ${from}`);
314
+ if (target === undefined)
315
+ throw new Error(`unknown policy-registry version ${to}`);
316
+ const pin = pinPolicyRegistry(to, pinnedBy, reason);
317
+ const removedChain = source.chain.filter((link) => !target.chain.includes(link));
318
+ const ceiling = Number(to.slice(to.lastIndexOf("@") + 1));
319
+ const hidden = POLICIES.filter((policy) => Number(generationOf(policy)) > ceiling).map((policy) => policy.policyId);
320
+ return {
321
+ from,
322
+ to,
323
+ pin,
324
+ restores: [
325
+ `the ${target.chain.length}-link resolution chain: ${target.chain.join(" → ")}`,
326
+ removedChain.length === 0 ? "no chain link is removed" : `chain link(s) removed: ${removedChain.join(", ")}`,
327
+ hidden.length === 0 ? "no policy is hidden" : `policies hidden from resolution: ${hidden.join(", ")}`,
328
+ target.agentSelection ? "per-seat sectionShares remain in force" : "per-seat sectionShares are disabled; design §10's shares apply to every seat",
329
+ ],
330
+ doesNotRestore: [
331
+ "the agents.ts briefing profile layer — lead sections, addendum blocks, conflict presentation and the feedback template are versioned separately (design §21) and a policy-registry pin does not touch them",
332
+ "escalation routing (src/escalation.ts), which is behaviour rather than policy data",
333
+ "anything below the pinned version that is marked non-reconstructible in POLICY_REGISTRY_HISTORY",
334
+ ],
335
+ proof: "replay.ts: capture a run's envelopes, replay them under the pin, and require the resulting RunFingerprint — including the briefing digest — to equal the fingerprint the prior version produced. A rollback that reproduces the outcome but not the briefing is not a rollback.",
336
+ };
337
+ }