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,266 @@
1
+ // Ported from mnemosia/plan.ts @ f0a8ad4 (MIT; see NOTICE)
2
+ /**
3
+ * Retrieval planning (spec §9, design §6, build-order step 8).
4
+ *
5
+ * Spec §9's demand is unambiguous and is the reason this module exists as more than a query
6
+ * builder: "It must query only the sources justified by the retrieval plan. It must not query extra
7
+ * sources merely to satisfy a quota." Spec §23 repeats it from the other side — "do not require
8
+ * every task to query three sources."
9
+ *
10
+ * So the plan records a decision for **every** source, selected or not, each with a rule id and a
11
+ * sentence of justification, and `EXECUTE_SOURCE_QUERIES` is given only the queries. A rejected
12
+ * source becomes a named `RetrievalGap` rather than a silence. A source with nothing to say is reported
13
+ * as a gap.
14
+ *
15
+ * **Why the planner narrows the term set.** AkashicForge builds its FTS5 tables with the default
16
+ * operator, which is AND (`toSafeMatchQuery`, store.ts:480-484, quotes each token and joins with a
17
+ * space). A twenty-term query therefore asks for documents containing all twenty words, and on this
18
+ * corpus that returns nothing. `TaskAnalysis.terms` stays wide because design §9's relevance signal
19
+ * measures coverage against it; `PlannedQuery.terms` is the narrow high-signal prefix that the
20
+ * store can actually answer. Conflating the two would make recall look like a ranking problem when
21
+ * it was a query-construction problem.
22
+ */
23
+ import { MODE_CONFIGS } from "./policy.js";
24
+ import { SCHEMA_VERSION, SOURCE_ID } from "./types.js";
25
+ /* ------------------------------------------------------------------------------------------------
26
+ * Mode configuration
27
+ * ---------------------------------------------------------------------------------------------- */
28
+ /**
29
+ * Design §4 assigns "ranking policies, mode configs, authority table" to `policy.ts`. In chunk B the
30
+ * table lived here because step 8 needed it and step 10 did not exist yet, with a note saying the
31
+ * move would be a re-export rather than a rewrite. Step 10 has landed and this is that re-export:
32
+ * the table is defined once, in `policy.ts`, and every existing importer of `plan.ts` is unaffected.
33
+ */
34
+ export { MODE_CONFIGS } from "./policy.js";
35
+ /**
36
+ * How many terms reach a query.
37
+ *
38
+ * Three, and the number is measured rather than chosen. Under FTS5's default AND operator every
39
+ * query term is a **hard filter**: a term the corpus does not contain zeroes the result set no
40
+ * matter how well the remaining terms match. Against a live corpus scoped to one project:
41
+ *
42
+ * ```
43
+ * ["store"] -> 100 events
44
+ * ["store","akashic-forge"] -> 100 events
45
+ * ["store","akashic-forge","under-reads"] -> 0 events
46
+ * ["akashic-forge","adapter"] -> 66 events
47
+ * ["akashic-forge","adapter","ledger"] -> 0 events
48
+ * ["review","akashic-forge","memory"] -> 54 events
49
+ * ```
50
+ *
51
+ * Design §12 says a hard-filter rejection is unrecoverable by relevance, and that is exactly the
52
+ * status a query term has here — so a *speculative* term must not be allowed to act as one. The
53
+ * seven ranking signals exist to do the fine discrimination; doing it in the query instead does it
54
+ * bluntly and irreversibly. Hence: few terms, and let ranking sort the wide result.
55
+ *
56
+ * The recall-preserving answer to a query that still comes back empty is a term ladder driven by
57
+ * spec §9's retry policy, which belongs to the orchestrator (step 15) and is measured by the §16
58
+ * gold set. It is not built here, and this constant is not tuned to hide its absence.
59
+ */
60
+ export const MAX_QUERY_TERMS = 3;
61
+ /**
62
+ * Share of the candidate budget each source may spend, before normalization over the selected set.
63
+ *
64
+ * Curated memory is the only source that ships, so its share is the whole budget after normalization.
65
+ */
66
+ export const SOURCE_CANDIDATE_SHARE = {
67
+ [SOURCE_ID.akashicMemories]: 0.1,
68
+ };
69
+ /** Priority when a mode's `maxSources` cap forces a source to be dropped. Highest authority first. */
70
+ const SOURCE_PRIORITY = [SOURCE_ID.akashicMemories];
71
+ /* ------------------------------------------------------------------------------------------------
72
+ * Plan
73
+ * ---------------------------------------------------------------------------------------------- */
74
+ export const PLAN_RULES = [
75
+ "curated_relevance",
76
+ "source_available",
77
+ "no_retrievable_signal",
78
+ "probe_unavailable",
79
+ "circuit_open",
80
+ "mode_source_cap",
81
+ "not_registered",
82
+ ];
83
+ /**
84
+ * Ranks the analysis's terms for the narrow AND-joined query.
85
+ *
86
+ * Two keys, in order: **entity-derived first**, because a path or a backticked identifier is what
87
+ * the author deliberately typed and is therefore vocabulary the corpus is likely to share; then
88
+ * **first appearance**, because the order an author writes in is their own emphasis and it is a
89
+ * total order, which is what the §16 determinism gate needs.
90
+ *
91
+ * There is deliberately no "prefer the longer/rarer token" key. It is the obvious heuristic and the
92
+ * measurement in `MAX_QUERY_TERMS` above falsifies it: `under-reads` and `millisecond` are among the
93
+ * longest tokens in that task and each on its own returns zero events, so promoting them would turn
94
+ * a good query into an empty one.
95
+ */
96
+ export function selectQueryTerms(analysis, limit = MAX_QUERY_TERMS) {
97
+ const entityTokens = new Set();
98
+ for (const entity of analysis.entities.value) {
99
+ for (const token of entity.text.toLowerCase().split(/[^\p{L}\p{N}_-]+/u)) {
100
+ if (token.length >= 3)
101
+ entityTokens.add(token);
102
+ }
103
+ }
104
+ const positions = new Map();
105
+ analysis.terms.value.forEach((term, index) => {
106
+ if (!positions.has(term.toLowerCase()))
107
+ positions.set(term.toLowerCase(), index);
108
+ });
109
+ return [...analysis.terms.value]
110
+ .sort((a, b) => {
111
+ const entityA = entityTokens.has(a.toLowerCase()) ? 0 : 1;
112
+ const entityB = entityTokens.has(b.toLowerCase()) ? 0 : 1;
113
+ if (entityA !== entityB)
114
+ return entityA - entityB;
115
+ return (positions.get(a.toLowerCase()) ?? 0) - (positions.get(b.toLowerCase()) ?? 0);
116
+ })
117
+ .slice(0, limit);
118
+ }
119
+ /**
120
+ * The scopes to actually issue queries against.
121
+ *
122
+ * AkashicForge reads a project filter as "global ∪ this project" (store.ts:661, and the note on
123
+ * `scopeFilterFor` in adapters/contract.ts), so issuing both a project query and a global query
124
+ * would read every global row twice and double its weight in every count downstream. When any
125
+ * project scope is authorized, the project queries alone cover global; the bare global query is
126
+ * issued only when nothing project-scoped was granted.
127
+ */
128
+ export function queryScopes(authorization) {
129
+ const projects = authorization.granted.filter((grant) => grant.scope.level === "project").map((grant) => grant.scope);
130
+ if (projects.length > 0)
131
+ return projects;
132
+ return authorization.granted.filter((grant) => grant.scope.level === "global").map((grant) => grant.scope);
133
+ }
134
+ function decide(analysis, sourceId, probe, circuitOpen) {
135
+ if (probe === undefined)
136
+ return { sourceId, selected: false, ruleId: "not_registered", justification: `${sourceId} was not probed at PLAN_RETRIEVAL, so it is treated as unavailable rather than assumed healthy`, probe: null };
137
+ if (circuitOpen.has(sourceId))
138
+ return { sourceId, selected: false, ruleId: "circuit_open", justification: `${sourceId} failed twice this session; the breaker stays open until session_start (design §13)`, probe };
139
+ if (!probe.available)
140
+ return { sourceId, selected: false, ruleId: "probe_unavailable", justification: `probe reported unavailable (${probe.code ?? "no code"}): ${probe.detail}`, probe };
141
+ switch (sourceId) {
142
+ case SOURCE_ID.akashicMemories: {
143
+ // **CORRECTED IN PHASE 1E.** This rule was `curated_authority`, and it selected the source
144
+ // unconditionally with an empty term list — a recency scan that returned every in-scope
145
+ // curated row on every task. Authority is a statement about a source's right to be
146
+ // believed *once it is relevant*; it is not a licence to be retrieved. Measured, the old
147
+ // rule put a mean 6.11 curated rows into every candidate pool regardless of subject, and
148
+ // with the low-amplitude relevance signal (design §10) they could not be pushed back out
149
+ // again — 0.529 irrelevant against a ≤ 0.20 gate.
150
+ //
151
+ // So curated memory is now retrieved on the same two grounds as everything else: scope,
152
+ // and sharing vocabulary with the task. What stays different is *how* the terms combine,
153
+ // and that difference is a measurement rather than a preference — see `matchMode` below
154
+ // and `QueryMatchMode` in types.ts. The authority advantage is untouched: it lives at 0.9
155
+ // in the policy table and is applied in ranking, which is where a claim about
156
+ // believability belongs.
157
+ if (analysis.terms.value.length === 0) {
158
+ return { sourceId, selected: false, ruleId: "no_retrievable_signal", justification: "the task yielded no searchable term, so there is no relevance ground on which to read curated memory; an unfiltered read would return the corpus rather than an answer", probe };
159
+ }
160
+ return { sourceId, selected: true, ruleId: "curated_relevance", justification: `the curated corpus is governed, scope-bounded and the only source reaching verified integrity; read on ${analysis.terms.value.length} task term(s) under any-match, with authority applied in ranking rather than in retrieval`, probe };
161
+ }
162
+ default:
163
+ return { sourceId, selected: true, ruleId: "source_available", justification: `${sourceId} is registered and available`, probe };
164
+ }
165
+ }
166
+ export function planRetrieval(input) {
167
+ const { analysis, authorization } = input;
168
+ const now = input.now ?? Date.now();
169
+ const mode = analysis.mode.value;
170
+ const config = MODE_CONFIGS[mode];
171
+ const circuitOpen = new Set(input.circuitOpen ?? []);
172
+ const probeIndex = new Map(input.probes.map((probe) => [probe.sourceId, probe]));
173
+ const terms = selectQueryTerms(analysis);
174
+ const extraCuratedTerms = (input.extraCuratedTerms ?? []).map((term) => term.toLowerCase()).filter((term) => term.length >= 3 && !analysis.terms.value.some((existing) => existing.toLowerCase() === term));
175
+ const curatedTerms = extraCuratedTerms.length > 0 ? [...analysis.terms.value, ...extraCuratedTerms] : analysis.terms.value;
176
+ const considered = [...SOURCE_PRIORITY, ...input.probes.map((probe) => probe.sourceId).filter((sourceId) => !SOURCE_PRIORITY.includes(sourceId))];
177
+ let decisions = considered.map((sourceId) => decide(analysis, sourceId, probeIndex.get(sourceId), circuitOpen));
178
+ // The mode cap is applied last, so a source that was rejected on its merits keeps the rule id
179
+ // that explains why rather than being relabelled as a casualty of the cap.
180
+ const selectedNow = decisions.filter((decision) => decision.selected);
181
+ if (selectedNow.length > config.maxSources) {
182
+ const keep = new Set(selectedNow.slice(0, config.maxSources).map((decision) => decision.sourceId));
183
+ decisions = decisions.map((decision) => decision.selected && !keep.has(decision.sourceId) ? { ...decision, selected: false, ruleId: "mode_source_cap", justification: `${mode} mode allows ${config.maxSources} source(s); ${decision.sourceId} was the lowest-authority selection and was dropped` } : decision);
184
+ }
185
+ const selected = decisions.filter((decision) => decision.selected).map((decision) => decision.sourceId);
186
+ const rejected = decisions.filter((decision) => !decision.selected).map((decision) => decision.sourceId);
187
+ const scopes = queryScopes(authorization);
188
+ const shareTotal = selected.reduce((sum, sourceId) => sum + (SOURCE_CANDIDATE_SHARE[sourceId] ?? 0.1), 0);
189
+ const queries = [];
190
+ const deadlines = {};
191
+ for (const sourceId of selected) {
192
+ deadlines[sourceId] = now + config.deadlineMsPerSource;
193
+ const sourceScopes = scopes;
194
+ const share = (SOURCE_CANDIDATE_SHARE[sourceId] ?? 0.1) / (shareTotal === 0 ? 1 : shareTotal);
195
+ const perQuery = Math.max(1, Math.floor((config.maxCandidates * share) / Math.max(1, sourceScopes.length)));
196
+ const decision = decisions.find((candidate) => candidate.sourceId === sourceId);
197
+ for (const scope of sourceScopes) {
198
+ const curated = sourceId === SOURCE_ID.akashicMemories;
199
+ queries.push({
200
+ schemaVersion: SCHEMA_VERSION.plannedQuery,
201
+ runId: analysis.runId,
202
+ sourceId,
203
+ /**
204
+ * Curated memory gets the **wide** term set under `any`; every other source gets the
205
+ * narrow three under `all`. Both halves are measured, not assumed.
206
+ *
207
+ * Conjunction is the filter that makes a result set readable for a large corpus and three terms is where it stops zeroing out (`MAX_QUERY_TERMS`). The
208
+ * curated corpus is ten dense rows, where the same conjunction is not a filter but an
209
+ * off switch: over the nineteen labelled retrieval tasks, three ANDed terms returned a
210
+ * curated row on six and found 6 of 23 labelled memories. Disjunction over the wide set
211
+ * finds **23 of 23** while cutting the mean rows read per task from 6.11 to 2.37.
212
+ *
213
+ * The wide set rather than the narrow one because it is already the set design §9's
214
+ * relevance signal scores coverage against (rank.ts:182); using the same vocabulary for
215
+ * "may this row be considered" and "how well does it match" keeps retrieval and ranking
216
+ * from disagreeing about what the task was about.
217
+ */
218
+ terms: curated ? curatedTerms : terms,
219
+ matchMode: curated ? "any" : "all",
220
+ scope,
221
+ taskScope: null,
222
+ since: curated ? null : analysis.since,
223
+ until: analysis.until,
224
+ maxArtifacts: perQuery,
225
+ justification: decision?.justification ?? `${sourceId} selected`,
226
+ });
227
+ }
228
+ }
229
+ const gaps = decisions
230
+ .filter((decision) => !decision.selected)
231
+ .map((decision) => ({
232
+ sourceId: decision.sourceId,
233
+ reason: decision.ruleId === "circuit_open" ? "circuit_open" : decision.ruleId === "probe_unavailable" ? "adapter_error" : "not_planned",
234
+ detail: decision.justification,
235
+ code: decision.ruleId === "probe_unavailable" ? (decision.probe?.code ?? null) : null,
236
+ }));
237
+ return {
238
+ schemaVersion: SCHEMA_VERSION.retrievalPlan,
239
+ runId: analysis.runId,
240
+ requestingAgent: analysis.requestingAgent,
241
+ taskType: analysis.taskType.value,
242
+ mode,
243
+ authorization,
244
+ considered,
245
+ selected,
246
+ rejected,
247
+ decisions,
248
+ queries,
249
+ deadlines,
250
+ gaps,
251
+ maxCandidates: config.maxCandidates,
252
+ // The caller's budget is a hard ceiling; the mode may only lower it further.
253
+ tokenBudget: Math.min(config.tokenBudget, analysis.contextBudget.value),
254
+ secondPassPermitted: config.secondPassPermitted,
255
+ retryPolicy: { attempts: config.retryAttempts, backoffMs: 0 },
256
+ graphTraversal: "none",
257
+ stopConditions: [
258
+ `candidate cap ${config.maxCandidates} reached`,
259
+ `per-source deadline ${config.deadlineMsPerSource} ms elapsed`,
260
+ `token budget ${Math.min(config.tokenBudget, analysis.contextBudget.value)} exhausted at selection`,
261
+ "every selected source returned or failed",
262
+ ],
263
+ failClosedOnUnverified: config.failClosedOnUnverified,
264
+ plannedAt: now,
265
+ };
266
+ }