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,257 @@
1
+ // Ported from mnemosia/escalation.ts @ f0a8ad4 (MIT; see NOTICE)
2
+ /**
3
+ * Escalation routing — spec §14's `ESCALATE_TO_ELARIA` and `ESCALATE_TO_RASKREIA`, and design §14's
4
+ * "escalate uncertain access decisions" (Phase 4).
5
+ *
6
+ * Both outcomes were left unreachable through Phases 1–3 on a rule this module is written to keep:
7
+ * *a module that cannot route must not emit a routing label*. `conflicts.ts` still cannot route. It
8
+ * does not know who is asking, so it cannot tell an escalation from a request to a seat to that same
9
+ * seat asking about itself, and a label whose recipient might be its own author is not a routing
10
+ * decision. This module is handed the requesting agent and produces, for every label it writes, an
11
+ * addressed `EscalationRequest` naming the target, the question, the evidence and the outcome
12
+ * required. Label and dispatch are produced together or not at all.
13
+ *
14
+ * **What "routing" means here, given what exists.** Mnemosia has no message bus: the `conclave`
15
+ * skill is prose doctrine with no dispatch envelope (`agents.ts` header), and spec §3 forbids
16
+ * Mnemosia executing project tasks or acting for another agent. So routing is *addressing*, not
17
+ * sending — the escalation is delivered to the requesting agent inside the briefing, naming which
18
+ * seat must be consulted and what it must be asked, and the requesting agent dispatches it through
19
+ * whatever the Conclave's ordinary sub-agent mechanism is. That is the same relationship
20
+ * `writes.ts` already has to mutation: Mnemosia recommends, somebody else executes. An escalation
21
+ * Mnemosia sent herself would be Mnemosia coordinating the Conclave, which spec §3's "must not
22
+ * define the overall mission / replace Samaela's planning" rules out.
23
+ *
24
+ * **Two rules decide which target, and they divide by the kind of question rather than by severity.**
25
+ *
26
+ * - **Raskreia** gets the questions about whether a source may be *believed at all* — provenance
27
+ * that does not resolve, standing that disagrees with integrity, and access decisions the
28
+ * authorizer declined. Her `.md` question is "should we even build it this way", and its memory
29
+ * analogue is "should we even be reading this".
30
+ * - **Elaria** gets the questions that are internally undecidable — two statements both still
31
+ * standing after every deterministic predicate has run. Her `.md` question is "is this internally
32
+ * correct", and an `UNRESOLVED` conflict is precisely a place where Mnemosia cannot answer it.
33
+ *
34
+ * Nothing here is a judgement call at runtime: each rule is a predicate over fields the conflict
35
+ * record and the authorization already carry, and the trace records which predicate fired.
36
+ */
37
+ import { createHash } from "node:crypto";
38
+ import { AGENT_DISPLAY_NAMES, resolveAgent } from "./agents.js";
39
+ export const ESCALATION_SCHEMA_VERSION = "mnemosia/escalation@1";
40
+ /** Which seat an escalation is addressed to. Only two of the eight are escalation targets. */
41
+ export const ESCALATION_TARGETS = ["elaria", "raskreia"];
42
+ /**
43
+ * The predicates. Each is a property of data the run already holds — no predicate reads free text
44
+ * and none of them is a threshold that could be moved to change how much escalates.
45
+ */
46
+ export const ESCALATION_RULES = [
47
+ /** A claim whose declared source events resolve to nothing, or which declares none. Provenance, not validity. */
48
+ "unresolved_provenance",
49
+ /** The authority table says believe A; the integrity check says A was never verified. */
50
+ "authority_over_unverified",
51
+ /** A contradiction with no deterministic winner: both sides standing, every predicate exhausted. */
52
+ "undecided_contradiction",
53
+ /** Any other conflict left `unresolved` after classification. */
54
+ "unresolved_conflict",
55
+ /**
56
+ * Design §14's "escalate uncertain access decisions".
57
+ *
58
+ * **Corrected while building: the case this rule fires on is not the one first written down.** The
59
+ * first draft escalated a scope the caller *explicitly requested and authorization refused* —
60
+ * which `task.ts:534-537` shows cannot happen, because an explicitly requested cross-project read
61
+ * is always granted. The rule would have been dead code wearing a §14 label.
62
+ *
63
+ * The genuinely uncertain decision is the other one: `cross_project_not_requested`. A project path
64
+ * appears in the task text, `authorizeScope` refuses it because a mention is not a request
65
+ * (spec §4's cross-project leak), and that refusal is a **conservative default rather than a
66
+ * determination** — the caller may well have meant it and simply not filled in
67
+ * `requested_projects`. Failing closed is right; failing closed silently is what leaves the reader
68
+ * unable to tell "there was nothing there" from "there was something and I would not look".
69
+ */
70
+ "uncertain_access_decision",
71
+ ];
72
+ const TARGET_DISPLAY = Object.freeze({
73
+ elaria: AGENT_DISPLAY_NAMES.elaria,
74
+ raskreia: AGENT_DISPLAY_NAMES.raskreia,
75
+ });
76
+ const OUTCOME_FOR = Object.freeze({
77
+ elaria: "ESCALATE_TO_ELARIA",
78
+ raskreia: "ESCALATE_TO_RASKREIA",
79
+ });
80
+ function escalationIdFor(rule, subject, claimIds) {
81
+ return createHash("sha256")
82
+ .update(`${rule}${subject}${[...claimIds].sort().join("")}`, "utf8")
83
+ .digest("hex")
84
+ .slice(0, 32);
85
+ }
86
+ function short(claimId) {
87
+ return claimId.slice(0, 12);
88
+ }
89
+ /**
90
+ * Decides the target for one conflict, or `null` when the conflict needs nobody.
91
+ *
92
+ * Order matters and is stated: the provenance and integrity rules are tested before the
93
+ * undecidability rules, because a conflict that is *both* unresolved and provenance-broken is a
94
+ * security question first. Escalating it to Elaria would ask a validator to reason about content
95
+ * whose origin is in doubt, which is the wrong order of operations and the reason design §14 lists
96
+ * integrity among the things a conflict resolution must consider.
97
+ */
98
+ function classify(record, integrityOf) {
99
+ if (record.conflictClass === "SUMMARY_SOURCE_MISMATCH")
100
+ return { target: "raskreia", rule: "unresolved_provenance" };
101
+ if (record.conflictClass === "AUTHORITY_DISAGREEMENT" && integrityOf !== undefined) {
102
+ // The winner is the side the authority table preferred. If that side is the one nothing
103
+ // verified, the two signals design §14 requires be considered together are pointing opposite
104
+ // ways, and no ranking arithmetic resolves that — it is a question about whether the standing
105
+ // table should be trusted here, which is an architecture question.
106
+ const favoured = record.winnerClaimId;
107
+ if (favoured !== null && integrityOf(favoured) === "unverified")
108
+ return { target: "raskreia", rule: "authority_over_unverified" };
109
+ }
110
+ if (!record.unresolved)
111
+ return null;
112
+ if (record.conflictClass === "DIRECT_CONTRADICTION")
113
+ return { target: "elaria", rule: "undecided_contradiction" };
114
+ return { target: "elaria", rule: "unresolved_conflict" };
115
+ }
116
+ function questionFor(rule, record) {
117
+ switch (rule) {
118
+ case "unresolved_provenance":
119
+ return {
120
+ question: `A retrieved claim declares source events that resolve to nothing in this corpus. Is the artifact behind it trustworthy, or is this content whose origin cannot be established?`,
121
+ requiredOutcome: "a verdict on the artifact: admissible, admissible-with-qualification, or quarantine. Until one arrives the claim stays in conflicts[] and cannot enter a factual section.",
122
+ };
123
+ case "authority_over_unverified":
124
+ return {
125
+ question: `The source-standing table favours a claim whose content integrity was never verified, over a claim that was. Should standing outrank verification for this source class?`,
126
+ requiredOutcome: "either a confirmation that the standing ordering is correct here, or a policy change proposal against policy.ts (design §19 item 3). Mnemosia does not re-order her own authority table.",
127
+ };
128
+ case "undecided_contradiction":
129
+ return {
130
+ question: `Two claims contradict and no deterministic predicate decides between them${record === null ? "" : ` (similarity ${record.similarity === null ? "n/a" : record.similarity.toFixed(3)})`}. Which is internally correct, or are they compatible under a distinction Mnemosia cannot see?`,
131
+ requiredOutcome: "a verdict naming the surviving claim, or a statement that both hold under different conditions. Both sides remain in conflicts[] until then; neither has been deleted.",
132
+ };
133
+ case "unresolved_conflict":
134
+ return {
135
+ question: `A detected conflict was left unresolved${record === null ? "" : ` (${record.conflictClass} via ${record.detector})`}. Is the plan or result that relies on these claims internally consistent?`,
136
+ requiredOutcome: "a consistency verdict. Mnemosia has recorded the disagreement and will not choose a side without one.",
137
+ };
138
+ case "uncertain_access_decision":
139
+ return {
140
+ question: `The task names a project outside this run's authorized scope, and Mnemosia refused it because a mention is not a request. Should this agent be able to read that project for this task?`,
141
+ requiredOutcome: "an access decision. Mnemosia does not widen her own authorization; if the answer is yes, the caller re-issues the request with the project named in requested_projects. Nothing from the refused scope was read, so this escalation costs nothing if the answer is no.",
142
+ };
143
+ }
144
+ }
145
+ export function routeEscalations(input) {
146
+ const now = input.now ?? Date.now();
147
+ const requester = resolveAgent(input.requestingAgent);
148
+ const escalations = [];
149
+ const outcomeOverrides = new Map();
150
+ const byTarget = { elaria: 0, raskreia: 0 };
151
+ const byRule = Object.fromEntries(ESCALATION_RULES.map((rule) => [rule, 0]));
152
+ let selfDelivered = 0;
153
+ const emit = (target, rule, conflictId, claimIds, evidence, record) => {
154
+ const { question, requiredOutcome } = questionFor(rule, record);
155
+ // The one routing decision that is not a lookup. A conflict Elaria must adjudicate, raised in a
156
+ // briefing Elaria asked for, is not a dispatch — it is her work item. Emitting it as a dispatch
157
+ // would tell her to consult herself, which is the kind of instruction that gets a pipeline stuck.
158
+ const isSelf = requester.agent === target;
159
+ if (isSelf)
160
+ selfDelivered += 1;
161
+ escalations.push({
162
+ schemaVersion: ESCALATION_SCHEMA_VERSION,
163
+ escalationId: escalationIdFor(rule, conflictId ?? "access", claimIds),
164
+ target,
165
+ targetDisplayName: TARGET_DISPLAY[target],
166
+ rule,
167
+ conflictId,
168
+ claimIds: [...claimIds].sort(),
169
+ question,
170
+ evidence,
171
+ requiredOutcome,
172
+ delivery: isSelf ? "self" : "dispatch",
173
+ raisedBy: requester.requested,
174
+ raisedAt: now,
175
+ });
176
+ byTarget[target] += 1;
177
+ byRule[rule] += 1;
178
+ if (conflictId !== null)
179
+ outcomeOverrides.set(conflictId, OUTCOME_FOR[target]);
180
+ };
181
+ /* --- conflict escalations ------------------------------------------------------------------- */
182
+ for (const record of input.conflicts.conflicts) {
183
+ const routed = classify(record, input.integrityOf);
184
+ if (routed === null)
185
+ continue;
186
+ const evidence = `${record.conflictClass} detected by ${record.detector} over ${record.claimIds.length} claim(s) [${record.claimIds.map(short).join(", ")}]. Mnemosia's own reading: ${record.rationale}`;
187
+ emit(routed.target, routed.rule, record.conflictId, record.claimIds, evidence, record);
188
+ }
189
+ /* --- access escalations (design §14) -------------------------------------------------------- */
190
+ //
191
+ // Only `cross_project_not_requested` escalates, and it is the only refusal rule `authorizeScope`
192
+ // can produce, so this is not a filter that happens to admit everything — it is the statement that
193
+ // any *future* refusal rule must opt in here deliberately rather than inherit an escalation it was
194
+ // never designed for. A scope that was simply never mentioned is not refused and never reaches
195
+ // this loop; escalating those would bury the real ones under every project on the machine.
196
+ for (const refusal of input.authorization.refused) {
197
+ if (refusal.ruleId !== "cross_project_not_requested")
198
+ continue;
199
+ emit("raskreia", "uncertain_access_decision", null, [], `${refusal.scope.project ?? "(global)"} appears in the task text; authorizeScope refused it (${refusal.ruleId}): ${refusal.detail}. Run authorization outcome was ${input.authorization.outcome}. Nothing from that scope was read.`, null);
200
+ }
201
+ const stats = { total: escalations.length, byTarget, byRule, selfDelivered, conflictsExamined: input.conflicts.conflicts.length };
202
+ input.trace?.append({
203
+ state: "RESOLVE_OR_ESCALATE",
204
+ event: "escalation",
205
+ payload: {
206
+ ...stats,
207
+ requestingAgent: requester.requested,
208
+ resolvedAgent: requester.agent,
209
+ escalations: escalations.map((entry) => ({ escalationId: entry.escalationId, target: entry.target, rule: entry.rule, conflictId: entry.conflictId, delivery: entry.delivery, claims: entry.claimIds.length })),
210
+ },
211
+ });
212
+ return { escalations, outcomeOverrides, stats };
213
+ }
214
+ /**
215
+ * Applies the routing labels to the conflict records.
216
+ *
217
+ * Returns a **new** `ConflictResolution` rather than mutating: `detectConflicts`'s output is what
218
+ * `rank.ts` scored against and what the trace already recorded, and rewriting it in place would make
219
+ * the `conflict` trace events disagree with the delivered briefing about what the outcome was. The
220
+ * override is a second, later fact about the same conflict, and the trace holds both.
221
+ */
222
+ export function applyEscalationOutcomes(conflicts, overrides) {
223
+ if (overrides.size === 0)
224
+ return conflicts;
225
+ const rewritten = conflicts.conflicts.map((record) => {
226
+ const outcome = overrides.get(record.conflictId);
227
+ return outcome === undefined ? record : { ...record, outcome };
228
+ });
229
+ const byId = new Map(rewritten.map((record) => [record.conflictId, record]));
230
+ const byClaimId = new Map();
231
+ for (const record of rewritten) {
232
+ for (const claimId of record.claimIds) {
233
+ const list = byClaimId.get(claimId);
234
+ if (list === undefined)
235
+ byClaimId.set(claimId, [record]);
236
+ else
237
+ list.push(record);
238
+ }
239
+ }
240
+ // `demoted` is keyed by claim and holds the record that demoted it. Rebuilt against the rewritten
241
+ // records for the same reason `byClaimId` is: a reader following `demoted` to find out why a claim
242
+ // is out of the factual sections must see the outcome the briefing renders, not the one it carried
243
+ // before routing. `mandatory` is a set of claim ids and is unaffected — escalation changes the
244
+ // label on a conflict, never which claims the conflict has.
245
+ const demoted = new Map();
246
+ for (const [claimId, record] of conflicts.demoted)
247
+ demoted.set(claimId, byId.get(record.conflictId) ?? record);
248
+ const byOutcome = { ...conflicts.stats.byOutcome };
249
+ for (const record of conflicts.conflicts) {
250
+ const outcome = overrides.get(record.conflictId);
251
+ if (outcome === undefined)
252
+ continue;
253
+ byOutcome[record.outcome] -= 1;
254
+ byOutcome[outcome] += 1;
255
+ }
256
+ return { ...conflicts, conflicts: rewritten, byClaimId, demoted, stats: { ...conflicts.stats, byOutcome } };
257
+ }
@@ -0,0 +1,108 @@
1
+ // Ported from mnemosia/feedback.ts @ f0a8ad4 (MIT; see NOTICE)
2
+ /**
3
+ * Per-agent feedback structure (spec §22, design §21 — Phase 4).
4
+ *
5
+ * Phase 1 shipped `submitFeedback` as an accept-and-store stub: one flat optional-everything record,
6
+ * appended to a file nothing in the retrieval path opens. Phase 4 gives it structure without giving
7
+ * it teeth, and the second half of that sentence is the requirement rather than a caveat.
8
+ *
9
+ * **Spec §22 is explicit — "Do not update production ranking policies online from individual
10
+ * interactions" — and this module is the place that prohibition would be violated if it were going
11
+ * to be.** So the design is deliberately lopsided:
12
+ *
13
+ * - Feedback gains a **schema** (spec §22's eight signals, typed, with per-agent expectations),
14
+ * - and a **validator** that returns a value rather than throwing, so a malformed report is recorded
15
+ * as malformed instead of being lost,
16
+ * - and **no reader anywhere under `src/`**. `test/feedback.test.ts` reads every source file and
17
+ * asserts that nothing but this module opens `feedback.jsonl`, and that no ranking or selection
18
+ * module imports it at all — the same machine-checked shape `test/mutate.test.ts` uses to make
19
+ * "Mnemosia cannot turn her own writes on" a property rather than a promise.
20
+ *
21
+ * Offline evaluation and versioned policy proposals — spec §22's stated use — are Phase 5.
22
+ *
23
+ * **Why the structure is per-agent at all.** Spec §22 asks for eight signals and design §21 makes
24
+ * Vesperia the execution-feedback seat. Those two facts together mean the signals do not come from
25
+ * one place: only whoever *acted* on a briefing knows which items were used and which were stale,
26
+ * only the validator knows about validator disagreement, and only Vaelia can report an external
27
+ * finding, because spec §3 forbids Mnemosia going to look for one. A single flat schema records all
28
+ * of that as "some optional fields were absent", which is indistinguishable from a lazy report. The
29
+ * per-agent expectation set is what makes the difference legible offline.
30
+ */
31
+ import { AGENT_PROFILES, resolveAgent } from "./agents.js";
32
+ export const FEEDBACK_SCHEMA_VERSION = "mnemosia/feedback@2";
33
+ /**
34
+ * Spec §22's list, one field each, in the spec's own order.
35
+ *
36
+ * `externalFindings` and `costObservations` are the two additions, and neither is an eighth signal
37
+ * smuggled in: they are the shapes the spec's "additional retrieval requested" and "downstream
38
+ * success" take for the two seats that produce evidence Mnemosia is structurally unable to obtain
39
+ * herself — Vaelia (spec §3 forbids browsing) and Avaritia (cost is a property of the caller's run,
40
+ * not of the corpus). A signal nobody can produce is not a signal.
41
+ */
42
+ export const FEEDBACK_SIGNALS = ["usedItemIds", "ignoredItemIds", "staleClaimIds", "missingEvidence", "additionalRetrievalRequested", "downstreamSuccess", "validatorDisagreement", "sectionsThatMattered", "externalFindings", "costObservations"];
43
+ function isPresent(value) {
44
+ if (value === undefined || value === null)
45
+ return false;
46
+ if (Array.isArray(value))
47
+ return value.length > 0;
48
+ if (typeof value === "string")
49
+ return value.trim().length > 0;
50
+ return true;
51
+ }
52
+ /**
53
+ * The signals a seat is the natural *producer* of — used to populate `unexpected`.
54
+ *
55
+ * This is not an access-control list. A consumer seat that happens to notice a stale memory should
56
+ * report it, and the report is stored exactly as sent; the field exists so that an offline pass can
57
+ * tell "Vesperia reported execution feedback" from "Astrelia reported execution feedback", which are
58
+ * different quality signals about the same bytes.
59
+ */
60
+ const PRODUCER_SIGNALS = Object.freeze({
61
+ samaela: ["usedItemIds", "ignoredItemIds", "downstreamSuccess", "sectionsThatMattered"],
62
+ vesperia: ["usedItemIds", "ignoredItemIds", "staleClaimIds", "missingEvidence", "additionalRetrievalRequested", "downstreamSuccess", "sectionsThatMattered"],
63
+ nytheria: ["missingEvidence", "additionalRetrievalRequested", "sectionsThatMattered"],
64
+ elaria: ["validatorDisagreement", "staleClaimIds", "missingEvidence", "sectionsThatMattered"],
65
+ raskreia: ["validatorDisagreement", "downstreamSuccess", "sectionsThatMattered"],
66
+ avaritia: ["costObservations", "downstreamSuccess", "sectionsThatMattered"],
67
+ astrelia: ["usedItemIds", "staleClaimIds", "sectionsThatMattered"],
68
+ vaelia: ["externalFindings", "missingEvidence", "additionalRetrievalRequested"],
69
+ });
70
+ export function validateFeedback(agent, report) {
71
+ const resolved = resolveAgent(agent);
72
+ if (resolved.agent === null) {
73
+ const present = FEEDBACK_SIGNALS.filter((signal) => isPresent(report[signal]));
74
+ return { complete: true, expected: [], missing: [], unexpected: [], producer: false, detail: `${resolved.detail}; no per-seat expectation applies, ${present.length} signal(s) recorded as submitted` };
75
+ }
76
+ const profile = AGENT_PROFILES[resolved.agent];
77
+ const expected = [...profile.feedbackExpected];
78
+ const missing = expected.filter((signal) => !isPresent(report[signal]));
79
+ const produces = new Set(PRODUCER_SIGNALS[resolved.agent]);
80
+ const unexpected = FEEDBACK_SIGNALS.filter((signal) => isPresent(report[signal]) && !produces.has(signal));
81
+ return {
82
+ complete: missing.length === 0,
83
+ expected,
84
+ missing,
85
+ unexpected: [...unexpected],
86
+ producer: profile.feedbackProducer,
87
+ detail: missing.length === 0
88
+ ? `${profile.displayName} reported all ${expected.length} expected signal(s)${unexpected.length === 0 ? "" : `, plus ${unexpected.length} outside this seat's producer set (recorded, not refused)`}`
89
+ : `${profile.displayName} omitted ${missing.length} of ${expected.length} expected signal(s): ${missing.join(", ")}. The report is stored as submitted; spec §22 forbids acting on it online in any case.`,
90
+ };
91
+ }
92
+ export function feedbackRequestFor(agent, runId, briefingId, itemIds) {
93
+ const resolved = resolveAgent(agent);
94
+ const profile = resolved.agent === null ? null : AGENT_PROFILES[resolved.agent];
95
+ return {
96
+ runId,
97
+ briefingId,
98
+ agent: resolved.requested,
99
+ expected: profile === null ? [] : [...profile.feedbackExpected],
100
+ producer: profile?.feedbackProducer ?? false,
101
+ itemIds: [...itemIds],
102
+ note: profile === null
103
+ ? "no Conclave seat resolved; any spec §22 signal is accepted"
104
+ : profile.feedbackProducer
105
+ ? `${profile.displayName} is a principal feedback producer for this run. Nothing here changes ranking: spec §22 forbids online policy updates, and Mnemosia's retrieval path never reads feedback.jsonl.`
106
+ : `${profile.displayName} consumes this briefing; the signals below are the ones her role is positioned to observe. Reporting is optional and never changes ranking.`,
107
+ };
108
+ }
@@ -0,0 +1,248 @@
1
+ // Ported from mnemosia/filters.ts @ f0a8ad4 (MIT; see NOTICE)
2
+ /**
3
+ * Hard filters and the quarantine scan (spec §11, design §12, build-order step 9).
4
+ *
5
+ * A hard filter is not a low score. Spec §11's closing line — "a candidate rejected by a hard filter
6
+ * must not be restored by a high semantic-relevance score" — is enforced structurally: this module
7
+ * runs before `rank.ts` and returns two disjoint lists, so the ranker is never given a rejected
8
+ * candidate to be tempted by. There is no threshold, no override, and no path back.
9
+ *
10
+ * **The scan runs over everything.** Design §12 is explicit that `validateMemorySafety` must run
11
+ * over *every* normalized artifact and not only over curated memories, and the reason is historical
12
+ * rather than theoretical: AkashicForge applies the scanner on the write path for memories, but other
13
+ * sources never pass through that scanner, so their content has not been checked for an injected instruction. So `scanArtifacts`
14
+ * walks the whole envelope set — including envelopes that produced no claims, whose count is still
15
+ * reported — and a failure quarantines the artifact for the run.
16
+ *
17
+ * **Evidence is pruned before a claim is rejected.** Deduplication unions evidence across artifacts
18
+ * (claims.ts), so a merged claim can stand on a clean artifact and a quarantined one at the same
19
+ * time. Rejecting the whole claim would discard a supported statement because of an artifact it did
20
+ * not need; keeping it whole would let the quarantined artifact stay in the provenance chain of
21
+ * something that gets briefed. Pruning the bad evidence and rejecting only when nothing is left is
22
+ * the only option that keeps both provenance and the quarantine honest.
23
+ */
24
+ import { scopeKey } from "./types.js";
25
+ import { CERTAINTY_RANK } from "./claims.js";
26
+ /* ------------------------------------------------------------------------------------------------
27
+ * Rules
28
+ * ---------------------------------------------------------------------------------------------- */
29
+ /**
30
+ * Design §12's list, in evaluation order. First match wins, so a claim is attributed to the *first*
31
+ * reason it was ineligible rather than to whichever check happened to run last.
32
+ *
33
+ * Order is not arbitrary. Schema validity comes first because a malformed claim cannot be
34
+ * meaningfully tested by anything downstream of it. Authorization comes next because spec §3 puts
35
+ * security before every other consideration, including whether the record is even alive. Only then
36
+ * do the lifecycle and content checks run.
37
+ */
38
+ export const HARD_FILTER_RULES = [
39
+ "invalid_schema",
40
+ "authorization_scope",
41
+ "lifecycle_state",
42
+ "expired",
43
+ "explicit_supersession",
44
+ "quarantine",
45
+ "integrity_failed",
46
+ "no_evidence",
47
+ ];
48
+ /** Design §12: only these two states are retrievable, and DISPUTED only into `conflicts[]`. */
49
+ export const RETRIEVABLE_STATES = new Set(["ACTIVE", "DISPUTED"]);
50
+ /**
51
+ * Runs the safety scanner over every normalized artifact.
52
+ *
53
+ * A scan is attempted for every envelope, including ones that will produce no claims: design §12's
54
+ * `excluded_candidate_summary.quarantined` count is a statement about the corpus that was read, not
55
+ * about the claims that survived, and computing it from the claims would understate it.
56
+ */
57
+ export function scanArtifacts(envelopes, scan) {
58
+ const quarantined = new Map();
59
+ let scanned = 0;
60
+ let unscannable = 0;
61
+ for (const envelope of envelopes) {
62
+ const content = envelope.contentRef.inline;
63
+ if (typeof content !== "string" || content.trim().length === 0) {
64
+ unscannable += 1;
65
+ continue;
66
+ }
67
+ scanned += 1;
68
+ try {
69
+ scan(content);
70
+ }
71
+ catch (error) {
72
+ quarantined.set(envelope.artifactId, {
73
+ artifactId: envelope.artifactId,
74
+ sourceId: envelope.sourceId,
75
+ sourceType: envelope.sourceType,
76
+ detail: error instanceof Error ? error.message : String(error),
77
+ });
78
+ }
79
+ }
80
+ return { quarantined, scanned, unscannable };
81
+ }
82
+ /* ------------------------------------------------------------------------------------------------
83
+ * Claim validation
84
+ * ---------------------------------------------------------------------------------------------- */
85
+ const CLAIM_TYPE_SET = new Set(["FACT", "OBSERVATION", "DECISION", "CONSTRAINT", "PLAN", "PREFERENCE", "PROCEDURE", "HYPOTHESIS"]);
86
+ const CERTAINTY_SET = new Set(Object.keys(CERTAINTY_RANK));
87
+ /**
88
+ * Structural validation of a claim, independent of anything it points at.
89
+ *
90
+ * This is the "invalid schema" hard filter spec §11 asks for. It exists because claims will one day
91
+ * arrive from a replaced adapter or a replayed trace rather than only from `claims.ts`, and the
92
+ * pipeline downstream of here assumes — in the fabrication guard especially — that a claim's fields
93
+ * mean what they say.
94
+ */
95
+ export function validateClaimShape(claim) {
96
+ if (claim.schemaVersion !== "mnemosia/claim@1")
97
+ return `unknown claim schemaVersion ${String(claim.schemaVersion)}`;
98
+ if (typeof claim.claimId !== "string" || claim.claimId.length === 0)
99
+ return "claimId is missing";
100
+ if (typeof claim.text !== "string" || claim.text.trim().length === 0)
101
+ return "text is empty";
102
+ if (typeof claim.dedupKey !== "string" || claim.dedupKey.length === 0)
103
+ return "dedupKey is empty";
104
+ if (!CLAIM_TYPE_SET.has(claim.claimType))
105
+ return `unknown claimType ${String(claim.claimType)}`;
106
+ if (!CERTAINTY_SET.has(claim.certainty))
107
+ return `unknown certainty ${String(claim.certainty)}`;
108
+ if (claim.scope.level !== "global" && claim.scope.level !== "project")
109
+ return `unknown scope level ${String(claim.scope.level)}`;
110
+ if (claim.scope.level === "project" && (claim.scope.project === null || claim.scope.project.length === 0))
111
+ return "a project-level claim carries no project";
112
+ if (!Number.isFinite(claim.effectiveAt))
113
+ return "effectiveAt is not a finite timestamp";
114
+ // A claim with no evidence is a fabrication. `claims.ts` cannot build one; this catches anything
115
+ // that did not come from `claims.ts`.
116
+ if (!Array.isArray(claim.evidence) || claim.evidence.length === 0)
117
+ return "claim carries no evidence";
118
+ for (const item of claim.evidence) {
119
+ if (item.claimId !== claim.claimId)
120
+ return `evidence ${item.evidenceId} points at a different claim`;
121
+ if (typeof item.artifactId !== "string" || item.artifactId.length === 0)
122
+ return `evidence ${item.evidenceId} names no artifact`;
123
+ }
124
+ return null;
125
+ }
126
+ function emptyByRule() {
127
+ return { invalid_schema: 0, authorization_scope: 0, lifecycle_state: 0, expired: 0, explicit_supersession: 0, quarantine: 0, integrity_failed: 0, no_evidence: 0 };
128
+ }
129
+ /**
130
+ * Applies design §12's hard filters, deterministically, before anything is ranked.
131
+ *
132
+ * Every rejection records a rule id and a detail string; nothing is dropped silently, which is what
133
+ * makes `explainDecision(runId, claimId)` able to answer "why was this not in my briefing".
134
+ */
135
+ /** Whole-claim checks, in rule order. `null` means the claim itself is eligible. */
136
+ function claimRejection(claim, authorization, authorized, now) {
137
+ const shapeError = validateClaimShape(claim);
138
+ if (shapeError !== null)
139
+ return { ruleId: "invalid_schema", detail: shapeError };
140
+ // Spec §3: a highly relevant memory that is unauthorized remains unavailable. This runs before
141
+ // every content check, so an unauthorized claim is never even scanned for merit.
142
+ if (authorization.outcome !== "AUTHORIZED" || !authorized.has(scopeKey(claim.scope))) {
143
+ return { ruleId: "authorization_scope", detail: `scope ${claim.scope.level}:${claim.scope.project ?? "-"} is not in the authorized set` };
144
+ }
145
+ if (claim.lifecycle !== null && !RETRIEVABLE_STATES.has(claim.lifecycle)) {
146
+ return { ruleId: "lifecycle_state", detail: `lifecycle ${claim.lifecycle} is not retrievable (only ACTIVE and DISPUTED are)` };
147
+ }
148
+ if (claim.expiresAt !== null && claim.expiresAt <= now)
149
+ return { ruleId: "expired", detail: `expired at ${new Date(claim.expiresAt).toISOString()}` };
150
+ return null;
151
+ }
152
+ /** Per-artifact content checks. `null` means this piece of evidence may stand. */
153
+ function artifactRejection(envelope, artifactId, scan, failClosedOnUnverified) {
154
+ // An evidence pointer with no artifact behind it cannot be verified, quoted or explained.
155
+ // Treating it as valid would be the fabrication the §16 provenance gate measures.
156
+ if (envelope === undefined)
157
+ return { ruleId: "invalid_schema", detail: `evidence names artifact ${artifactId}, which this run did not normalize` };
158
+ const quarantine = scan.quarantined.get(artifactId);
159
+ if (quarantine !== undefined)
160
+ return { ruleId: "quarantine", detail: quarantine.detail };
161
+ if (envelope.integrityStatus === "failed")
162
+ return { ruleId: "integrity_failed", detail: "artifact integrity is failed" };
163
+ if (failClosedOnUnverified && envelope.integrityStatus !== "verified")
164
+ return { ruleId: "integrity_failed", detail: `high-assurance mode: integrity is ${envelope.integrityStatus}` };
165
+ return null;
166
+ }
167
+ export function applyHardFilters(input) {
168
+ const now = input.now ?? Date.now();
169
+ const artifactScan = input.artifactScan ?? scanArtifacts(input.envelopes, input.scan);
170
+ const envelopeIndex = new Map(input.envelopes.map((envelope) => [envelope.artifactId, envelope]));
171
+ const authorized = new Set(input.authorization.authorizedKeys);
172
+ const failClosed = input.failClosedOnUnverified === true;
173
+ const accepted = [];
174
+ const rejections = [];
175
+ const byRule = emptyByRule();
176
+ let evidencePruned = 0;
177
+ const reject = (claim, ruleId, detail, artifactIds = []) => {
178
+ rejections.push({ claimId: claim.claimId, ruleId, detail, artifactIds });
179
+ byRule[ruleId] += 1;
180
+ };
181
+ /**
182
+ * Explicit supersession (design §12) is a relation *between* claims, so the set of retired
183
+ * artifacts has to be settled before any single claim can be judged.
184
+ *
185
+ * Only a claim that would itself survive every other filter gets a vote. Without that, a
186
+ * poisoned artifact could carry `supersedes: [<the memory that contradicts it>]` and retire a
187
+ * clean, authorized, verified record on its own say-so — a one-line injection that deletes
188
+ * memory from the briefing. It must clear the whole-claim checks *and* stand on at least one
189
+ * artifact that is not quarantined, integrity-failed or out of its security domain.
190
+ */
191
+ const supersededArtifacts = new Set();
192
+ for (const claim of input.claims) {
193
+ if (claimRejection(claim, input.authorization, authorized, now) !== null)
194
+ continue;
195
+ if (!claim.evidence.some((item) => artifactRejection(envelopeIndex.get(item.artifactId), item.artifactId, artifactScan, failClosed) === null))
196
+ continue;
197
+ for (const reference of claim.supersedes)
198
+ supersededArtifacts.add(reference);
199
+ }
200
+ for (const claim of input.claims) {
201
+ const claimError = claimRejection(claim, input.authorization, authorized, now);
202
+ if (claimError !== null) {
203
+ reject(claim, claimError.ruleId, claimError.detail);
204
+ continue;
205
+ }
206
+ // A claim every one of whose artifacts has been explicitly retired by a surviving claim.
207
+ // "Every" rather than "any": a claim standing on three artifacts of which one was superseded
208
+ // is still supported by the other two.
209
+ const artifactIds = claim.evidence.map((item) => item.artifactId);
210
+ if (artifactIds.length > 0 && artifactIds.every((artifactId) => supersededArtifacts.has(artifactId))) {
211
+ reject(claim, "explicit_supersession", "every supporting artifact is explicitly superseded by a retained claim", artifactIds);
212
+ continue;
213
+ }
214
+ // Per-evidence content checks. Anything that fails removes that evidence, not the claim.
215
+ const surviving = [];
216
+ const dropped = [];
217
+ for (const item of claim.evidence) {
218
+ const failure = artifactRejection(envelopeIndex.get(item.artifactId), item.artifactId, artifactScan, failClosed);
219
+ if (failure === null)
220
+ surviving.push(item);
221
+ else
222
+ dropped.push({ ...failure, artifactId: item.artifactId });
223
+ }
224
+ if (surviving.length === 0) {
225
+ // Attributed to the first reason that fired, matching the whole-claim rule order.
226
+ const first = dropped[0];
227
+ reject(claim, first?.ruleId ?? "no_evidence", first?.detail ?? "no evidence survived the artifact checks", dropped.map((entry) => entry.artifactId));
228
+ continue;
229
+ }
230
+ evidencePruned += dropped.length;
231
+ accepted.push(surviving.length === claim.evidence.length ? claim : { ...claim, evidence: surviving });
232
+ }
233
+ return {
234
+ accepted,
235
+ rejections,
236
+ quarantined: [...artifactScan.quarantined.values()],
237
+ stats: {
238
+ claimsIn: input.claims.length,
239
+ claimsOut: accepted.length,
240
+ rejected: rejections.length,
241
+ byRule,
242
+ artifactsScanned: artifactScan.scanned,
243
+ artifactsQuarantined: artifactScan.quarantined.size,
244
+ artifactsUnscannable: artifactScan.unscannable,
245
+ evidencePruned,
246
+ },
247
+ };
248
+ }