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.
- package/CHANGELOG.md +43 -0
- package/LICENSE +21 -0
- package/NOTICE +39 -0
- package/README.md +140 -2
- package/agents/astrelia.md +31 -0
- package/agents/avaritia.md +31 -0
- package/agents/elaria.md +31 -0
- package/agents/nytheria.md +32 -0
- package/agents/raskreia.md +32 -0
- package/agents/samaela.md +40 -0
- package/agents/vaelia.md +35 -0
- package/agents/vesperia.md +45 -0
- package/bin/piroboros.mjs +17 -0
- package/dist/auth.js +105 -0
- package/dist/base.js +19 -0
- package/dist/chat/budget.js +87 -0
- package/dist/chat/compactloop.js +63 -0
- package/dist/chat/compactor.js +530 -0
- package/dist/chat/extension.js +36 -0
- package/dist/chat/hook.js +40 -0
- package/dist/chat/log.js +317 -0
- package/dist/chat/outbound.js +114 -0
- package/dist/chat/plan.js +64 -0
- package/dist/chat/prompt.js +115 -0
- package/dist/chat/status.js +37 -0
- package/dist/chat/stuck.js +83 -0
- package/dist/chat/tools.js +163 -0
- package/dist/chat/tree.js +73 -0
- package/dist/chat/turn.js +305 -0
- package/dist/chat/view.js +163 -0
- package/dist/conclave/agents.js +113 -0
- package/dist/conclave/pipeline.js +715 -0
- package/dist/conclave/report.js +43 -0
- package/dist/config.js +614 -0
- package/dist/durable.js +177 -0
- package/dist/guard.js +346 -0
- package/dist/lock.js +56 -0
- package/dist/main.js +348 -0
- package/dist/memory/akashic/api.js +121 -0
- package/dist/memory/akashic/confusables.js +41 -0
- package/dist/memory/akashic/scanner.js +67 -0
- package/dist/memory/akashic/snapshot.js +31 -0
- package/dist/memory/akashic/store.js +1254 -0
- package/dist/memory/akashic/tools.js +168 -0
- package/dist/memory/akashic/vault.js +984 -0
- package/dist/memory/host.js +124 -0
- package/dist/memory/mnemosia/adapters/akashic-memories.js +180 -0
- package/dist/memory/mnemosia/adapters/contract.js +219 -0
- package/dist/memory/mnemosia/agents.js +387 -0
- package/dist/memory/mnemosia/brief.js +890 -0
- package/dist/memory/mnemosia/claims.js +609 -0
- package/dist/memory/mnemosia/conflicts.js +769 -0
- package/dist/memory/mnemosia/escalation.js +257 -0
- package/dist/memory/mnemosia/feedback.js +108 -0
- package/dist/memory/mnemosia/filters.js +248 -0
- package/dist/memory/mnemosia/intent.js +221 -0
- package/dist/memory/mnemosia/open.js +34 -0
- package/dist/memory/mnemosia/orchestrator.js +926 -0
- package/dist/memory/mnemosia/plan.js +266 -0
- package/dist/memory/mnemosia/policy.js +426 -0
- package/dist/memory/mnemosia/progressive.js +550 -0
- package/dist/memory/mnemosia/provenance.js +458 -0
- package/dist/memory/mnemosia/qualifiers.js +428 -0
- package/dist/memory/mnemosia/rank.js +525 -0
- package/dist/memory/mnemosia/relations.js +156 -0
- package/dist/memory/mnemosia/requirements.js +138 -0
- package/dist/memory/mnemosia/rerank.js +253 -0
- package/dist/memory/mnemosia/retention.js +174 -0
- package/dist/memory/mnemosia/rollback.js +337 -0
- package/dist/memory/mnemosia/select.js +607 -0
- package/dist/memory/mnemosia/similarity.js +164 -0
- package/dist/memory/mnemosia/situation.js +251 -0
- package/dist/memory/mnemosia/task.js +418 -0
- package/dist/memory/mnemosia/temporal.js +136 -0
- package/dist/memory/mnemosia/tokens.js +66 -0
- package/dist/memory/mnemosia/tools.js +160 -0
- package/dist/memory/mnemosia/trace.js +306 -0
- package/dist/memory/mnemosia/types.js +298 -0
- package/dist/models.js +360 -0
- package/dist/paths.js +103 -0
- package/dist/redact.js +79 -0
- package/dist/runtime.js +378 -0
- package/dist/search-format.js +102 -0
- package/dist/search.js +351 -0
- package/dist/setup.js +366 -0
- package/dist/shell.js +110 -0
- package/dist/skills.js +311 -0
- package/dist/telemetry.js +84 -0
- package/dist/tui/app.js +1011 -0
- package/dist/tui/commands.js +121 -0
- package/dist/tui/keys.js +83 -0
- package/dist/tui/pane.js +387 -0
- package/dist/tui/panel.js +60 -0
- package/dist/tui/picker.js +25 -0
- package/dist/tui/sanitize.js +59 -0
- package/dist/tui/settings.js +198 -0
- package/dist/tui/setup.js +256 -0
- package/dist/tui/theme.js +26 -0
- package/dist/tui/thinking/parse.js +1094 -0
- package/dist/tui/thinking/select.js +86 -0
- package/dist/tui/thinking/state.js +137 -0
- package/dist/tui/thinking/types.js +3 -0
- package/dist/tui/thinking/view.js +74 -0
- package/dist/tui/viewport.js +208 -0
- package/dist/undo.js +258 -0
- package/dist/web.js +933 -0
- package/docs/conclave.md +21 -0
- package/docs/configuration.md +48 -0
- package/docs/development.md +25 -0
- package/docs/interface.md +33 -0
- package/docs/memory.md +11 -0
- package/docs/privacy.md +13 -0
- package/docs/tools.md +20 -0
- package/docs/web.md +38 -0
- package/models.json.example +34 -0
- package/package.json +76 -4
- package/settings.json.example +29 -0
- package/skills/conclave/SKILL.md +76 -0
|
@@ -0,0 +1,609 @@
|
|
|
1
|
+
// Ported from mnemosia/claims.ts @ f0a8ad4 (MIT; see NOTICE)
|
|
2
|
+
/**
|
|
3
|
+
* Deterministic claim extraction, normalization and deduplication (design §8, build-order step 6).
|
|
4
|
+
*
|
|
5
|
+
* This is the linchpin: it is the module that decides what "the corpus says X" means without an LLM
|
|
6
|
+
* anywhere in the path. Three extraction paths exist, one per artifact shape, and no fifth is
|
|
7
|
+
* synthesized to make the corpus look richer than it is:
|
|
8
|
+
*
|
|
9
|
+
* 1. curated memory → one claim, CONFIRMED, governance columns carried across.
|
|
10
|
+
* 2. compaction summary → N claims via the heading grammar, capped at PROBABLE.
|
|
11
|
+
* 3. raw event → one degenerate whole-artifact OBSERVATION with an excerpt window.
|
|
12
|
+
*
|
|
13
|
+
* Path 3 is the one that would be most tempting to make clever. Splitting a 4KB tool transcript
|
|
14
|
+
* into sentence-level "claims" would produce a large number of grammatically well-formed objects
|
|
15
|
+
* that are not claims about anything, and every downstream signal (evidence strength, freshness,
|
|
16
|
+
* conflict detection) would then be computed over noise while reporting the confidence of signal.
|
|
17
|
+
* Mnemosia.txt §26 forbids exactly that kind of placeholder sophistication, so a raw event stays one
|
|
18
|
+
* honest OBSERVATION that says "this artifact contains this passage", and its excerpt is the ±240
|
|
19
|
+
* character window design §18 prices at roughly 120 tokens.
|
|
20
|
+
*
|
|
21
|
+
* **The summary certainty cap is the mechanism, not the aspiration.** Spec §4 requires that a
|
|
22
|
+
* polished summary not outrank its raw evidence. That is enforced here by construction: every
|
|
23
|
+
* summary-derived claim is capped at PROBABLE and every piece of its evidence is `derived`, so no
|
|
24
|
+
* amount of downstream scoring can lift it to the CONFIRMED band that curated memory occupies.
|
|
25
|
+
*
|
|
26
|
+
* Nothing in this module imports from the foundations. It reads `ArtifactEnvelope` and writes
|
|
27
|
+
* `Claim`, both of which are Mnemosia's own vocabulary.
|
|
28
|
+
*/
|
|
29
|
+
import { createHash } from "node:crypto";
|
|
30
|
+
import { SCHEMA_VERSION, scopeKey, } from "./types.js";
|
|
31
|
+
/* ------------------------------------------------------------------------------------------------
|
|
32
|
+
* Certainty algebra
|
|
33
|
+
* ---------------------------------------------------------------------------------------------- */
|
|
34
|
+
/** A total order, so "certainty = max" in dedup and "capped at PROBABLE" are both arithmetic. */
|
|
35
|
+
export const CERTAINTY_RANK = { CONFIRMED: 3, PROBABLE: 2, SPECULATIVE: 1, UNKNOWN: 0 };
|
|
36
|
+
export function maxCertainty(a, b) {
|
|
37
|
+
return CERTAINTY_RANK[a] >= CERTAINTY_RANK[b] ? a : b;
|
|
38
|
+
}
|
|
39
|
+
/** Never raises; only lowers. Used to make the summary cap unbypassable rather than remembered. */
|
|
40
|
+
export function capCertainty(value, ceiling) {
|
|
41
|
+
return CERTAINTY_RANK[value] <= CERTAINTY_RANK[ceiling] ? value : ceiling;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* The ceiling on anything read out of a compaction summary (design §8.2). A summary is a derivative
|
|
45
|
+
* account written by a model; treating it as CONFIRMED would let a paraphrase outrank the events it
|
|
46
|
+
* paraphrases, which is the invariant this constant exists to make impossible.
|
|
47
|
+
*/
|
|
48
|
+
export const SUMMARY_CERTAINTY_CEILING = "PROBABLE";
|
|
49
|
+
/**
|
|
50
|
+
* Precedence used when deduplication merges two claims that carry different types. The governing
|
|
51
|
+
* types win: a sentence that appears once as a CONSTRAINT and once as an ordinary OBSERVATION is a
|
|
52
|
+
* constraint that was also observed, and demoting it would drop it out of the mandatory set that
|
|
53
|
+
* §10 reserves budget for. Merging in the other direction can only ever lose a restriction.
|
|
54
|
+
*/
|
|
55
|
+
const CLAIM_TYPE_PRECEDENCE = ["CONSTRAINT", "DECISION", "PREFERENCE", "PROCEDURE", "FACT", "PLAN", "HYPOTHESIS", "OBSERVATION"];
|
|
56
|
+
/**
|
|
57
|
+
* Precedence used when deduplication merges two claims carrying different lifecycle states. A
|
|
58
|
+
* governed state that restricts retrieval wins over one that permits it, for the same reason:
|
|
59
|
+
* merging must never launder a DISPUTED or SUPERSEDED reading into an ACTIVE one.
|
|
60
|
+
*/
|
|
61
|
+
const LIFECYCLE_PRECEDENCE = ["DELETED", "REVOKED", "QUARANTINED", "EXPIRED", "SUPERSEDED", "DISPUTED", "PROPOSED", "ACTIVE"];
|
|
62
|
+
/* ------------------------------------------------------------------------------------------------
|
|
63
|
+
* Normalization and identity
|
|
64
|
+
* ---------------------------------------------------------------------------------------------- */
|
|
65
|
+
/** List markers stripped before normalization, so `1. x`, `- x` and `- [x] x` share a dedup key. */
|
|
66
|
+
const LIST_MARKER = /^\s*(?:[-*+•]|\d{1,3}[.)])\s+/;
|
|
67
|
+
const TASK_MARKER = /^\s*\[[ xX]\]\s+/;
|
|
68
|
+
/**
|
|
69
|
+
* `NFKC → lowercase → collapse whitespace → strip list markers and punctuation` (design §7).
|
|
70
|
+
*
|
|
71
|
+
* Punctuation is replaced with a space rather than deleted. Deleting it would fold `a.b` into `ab`
|
|
72
|
+
* and `run-time` into `runtime`, quietly merging identifiers that a technical corpus keeps apart;
|
|
73
|
+
* replacing it keeps the token boundary that made them different in the first place.
|
|
74
|
+
*/
|
|
75
|
+
export function normalizeClaimText(text) {
|
|
76
|
+
let value = text.normalize("NFKC").toLowerCase();
|
|
77
|
+
// Repeated because a Markdown task item carries two markers: `- ` and then `[x] `.
|
|
78
|
+
for (let i = 0; i < 4; i += 1) {
|
|
79
|
+
const stripped = value.replace(LIST_MARKER, "").replace(TASK_MARKER, "");
|
|
80
|
+
if (stripped === value)
|
|
81
|
+
break;
|
|
82
|
+
value = stripped;
|
|
83
|
+
}
|
|
84
|
+
// Comparison operators become words first, so "attempts < 5" and "attempts > 5" stay two claims.
|
|
85
|
+
// An arrow (`->`, `=>`, `<-`) is not a comparison and still folds away with the other punctuation.
|
|
86
|
+
return value
|
|
87
|
+
.replace(/>=/gu, " ge ")
|
|
88
|
+
.replace(/<=/gu, " le ")
|
|
89
|
+
.replace(/!=/gu, " ne ")
|
|
90
|
+
.replace(/(?<![-=])>/gu, " gt ")
|
|
91
|
+
.replace(/<(?!-)/gu, " lt ")
|
|
92
|
+
.replace(/[\p{P}\p{S}]/gu, " ")
|
|
93
|
+
.replace(/\s+/gu, " ")
|
|
94
|
+
.trim();
|
|
95
|
+
}
|
|
96
|
+
export function sha256Hex(value) {
|
|
97
|
+
return createHash("sha256").update(value, "utf8").digest("hex");
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Claim identity.
|
|
101
|
+
*
|
|
102
|
+
* Design §7 writes this as `sha256(dedupKey)`, and design §8 writes the dedup rule as "identical
|
|
103
|
+
* `dedupKey` **in compatible scope** ⇒ one claim". Those two sentences cannot both hold: the second
|
|
104
|
+
* says the same sentence in two different projects is two claims, and two claims cannot share an
|
|
105
|
+
* identifier — the fabrication guard in `VALIDATE_BRIEFING` indexes the run's claims by `claimId`,
|
|
106
|
+
* and a collision there would let one project's claim vouch for another's.
|
|
107
|
+
*
|
|
108
|
+
* Resolved in favour of the isolation invariant (spec §4): identity is the dedup key **plus the
|
|
109
|
+
* scope**. `dedupKey` stays on the claim verbatim, so the design's rule is still directly
|
|
110
|
+
* inspectable, and scope is the only thing added.
|
|
111
|
+
*/
|
|
112
|
+
export function claimIdFor(dedupKey, scope) {
|
|
113
|
+
return sha256Hex(`${dedupKey}\u001f${scopeKey(scope)}`);
|
|
114
|
+
}
|
|
115
|
+
/** sha256(artifactId + claimId + relation): the same link never gets two ids (design §7). */
|
|
116
|
+
export function evidenceIdFor(artifactId, claimId, relation) {
|
|
117
|
+
return sha256Hex(`${artifactId}\u001f${claimId}\u001f${relation}`);
|
|
118
|
+
}
|
|
119
|
+
function buildEvidence(artifactId, claimId, relation, directness, locator, observedAt) {
|
|
120
|
+
return {
|
|
121
|
+
schemaVersion: SCHEMA_VERSION.evidence,
|
|
122
|
+
evidenceId: evidenceIdFor(artifactId, claimId, relation),
|
|
123
|
+
artifactId,
|
|
124
|
+
claimId,
|
|
125
|
+
relation,
|
|
126
|
+
directness,
|
|
127
|
+
locator,
|
|
128
|
+
observedAt,
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
function materialize(envelope, draft) {
|
|
132
|
+
const text = draft.text.trim();
|
|
133
|
+
if (text.length === 0)
|
|
134
|
+
return null;
|
|
135
|
+
const dedupKey = normalizeClaimText(text);
|
|
136
|
+
// A block that normalizes to nothing (a bare `---`, a lone bullet marker) carried no assertion.
|
|
137
|
+
// Emitting it would create a claim whose identity is the hash of the empty string, shared by
|
|
138
|
+
// every other such block in the corpus.
|
|
139
|
+
if (dedupKey.length === 0)
|
|
140
|
+
return null;
|
|
141
|
+
const scope = draft.scope ?? envelope.scope;
|
|
142
|
+
const claimId = claimIdFor(dedupKey, scope);
|
|
143
|
+
return {
|
|
144
|
+
schemaVersion: SCHEMA_VERSION.claim,
|
|
145
|
+
claimId,
|
|
146
|
+
dedupKey,
|
|
147
|
+
text,
|
|
148
|
+
claimType: draft.claimType,
|
|
149
|
+
certainty: draft.certainty,
|
|
150
|
+
scope,
|
|
151
|
+
effectiveAt: draft.effectiveAt ?? envelope.createdAt,
|
|
152
|
+
expiresAt: draft.expiresAt ?? null,
|
|
153
|
+
supersedes: draft.supersedes ?? [],
|
|
154
|
+
lifecycle: draft.lifecycle ?? null,
|
|
155
|
+
// Phase 1 emits SUPPORTS here; conflicts.ts (step 11) is what adds SUPERSEDES links.
|
|
156
|
+
evidence: [buildEvidence(envelope.artifactId, claimId, "SUPPORTS", draft.directness, draft.locator, envelope.observedAt)],
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* The grammar, in the order the headings appear in a live summary.
|
|
161
|
+
*
|
|
162
|
+
* `Progress` is a container: the `###` subsections that follow it are split out as sections of
|
|
163
|
+
* their own, so its own body is always empty. It is listed anyway, because a known heading with an
|
|
164
|
+
* empty body must count as *known* — dropping it into the unknown bucket would be the same false
|
|
165
|
+
* drift signal described above.
|
|
166
|
+
*/
|
|
167
|
+
export const SUMMARY_SECTION_GRAMMAR = [
|
|
168
|
+
{ heading: "Goal", claimType: "PLAN", provenance: "design" },
|
|
169
|
+
{ heading: "Constraints & Preferences", claimType: "CONSTRAINT", provenance: "design" },
|
|
170
|
+
{ heading: "Progress", claimType: "PLAN", provenance: "design" },
|
|
171
|
+
{ heading: "Done", claimType: "OBSERVATION", provenance: "design" },
|
|
172
|
+
{ heading: "In Progress", claimType: "PLAN", provenance: "design" },
|
|
173
|
+
{ heading: "Blocked", claimType: "PLAN", provenance: "design" },
|
|
174
|
+
{ heading: "Key Decisions", claimType: "DECISION", provenance: "design" },
|
|
175
|
+
{ heading: "Next Steps", claimType: "PLAN", provenance: "design" },
|
|
176
|
+
{ heading: "Critical Context", claimType: "FACT", provenance: "design" },
|
|
177
|
+
// The split-turn tail. `Original Request` restates the objective (PLAN), `Early Progress`
|
|
178
|
+
// reports what already happened (OBSERVATION, exactly like `Done`), and `Context for Suffix`
|
|
179
|
+
// carries the facts the next turn needs (FACT, exactly like `Critical Context`).
|
|
180
|
+
{ heading: "Original Request", claimType: "PLAN", provenance: "measured" },
|
|
181
|
+
{ heading: "Early Progress", claimType: "OBSERVATION", provenance: "measured" },
|
|
182
|
+
{ heading: "Context for Suffix", claimType: "FACT", provenance: "measured" },
|
|
183
|
+
];
|
|
184
|
+
/** Lookup key for a heading: NFKC, unbolded, uncoloned, case- and whitespace-insensitive. */
|
|
185
|
+
export function headingKey(heading) {
|
|
186
|
+
return heading
|
|
187
|
+
.normalize("NFKC")
|
|
188
|
+
.replace(/\*\*/g, "")
|
|
189
|
+
.replace(/\s+/gu, " ")
|
|
190
|
+
.trim()
|
|
191
|
+
// After trimming, not before: `**Key Decisions:** ` only ends in a colon once the bold
|
|
192
|
+
// markers and the trailing space are gone.
|
|
193
|
+
.replace(/:$/, "")
|
|
194
|
+
.trim()
|
|
195
|
+
.toLowerCase();
|
|
196
|
+
}
|
|
197
|
+
export const SUMMARY_SECTION_RULES = new Map(SUMMARY_SECTION_GRAMMAR.map((rule) => [headingKey(rule.heading), rule]));
|
|
198
|
+
/** Design §8.2 splits on `^##+ `; an `#` heading is therefore ordinary body text, not a section. */
|
|
199
|
+
const HEADING_LINE = /^(#{2,6})\s+(.*)$/;
|
|
200
|
+
const TOP_LEVEL_ITEM = /^(?:[-*+•]|\d{1,3}[.)])\s+/;
|
|
201
|
+
/**
|
|
202
|
+
* Splits a compaction summary into sections and each section into blocks.
|
|
203
|
+
*
|
|
204
|
+
* A block is either a top-level list item — its own line plus any *indented* continuation, which is
|
|
205
|
+
* how nested bullets stay attached to the bullet they qualify — or a run of unindented prose. The
|
|
206
|
+
* distinction matters because the live corpus contains all three shapes: sections that are pure
|
|
207
|
+
* bullets, sections that are pure prose (`## Goal` is prose in 7 of 14 summaries), and sections
|
|
208
|
+
* whose bullets are followed by a trailing `---` / `**Turn Context (split turn):**` separator or a
|
|
209
|
+
* `<read-files>` path dump. Absorbing that trailing material into the last bullet would corrupt the
|
|
210
|
+
* final claim of nearly every section; treating it as a claim of its own would file a directory
|
|
211
|
+
* listing as a statement about the world.
|
|
212
|
+
*
|
|
213
|
+
* Anything above the first heading is returned under the empty heading, so a summary that has lost
|
|
214
|
+
* its grammar still yields something rather than nothing.
|
|
215
|
+
*/
|
|
216
|
+
export function parseSummarySections(content) {
|
|
217
|
+
const lines = content.split(/\r?\n/);
|
|
218
|
+
const sections = [];
|
|
219
|
+
let current = { heading: "", level: 0, line: 0, blocks: [], rule: null };
|
|
220
|
+
let block = null;
|
|
221
|
+
let pending = [];
|
|
222
|
+
const closeBlock = () => {
|
|
223
|
+
if (block === null)
|
|
224
|
+
return;
|
|
225
|
+
const text = block.text.replace(/\s+$/u, "");
|
|
226
|
+
if (text.trim().length > 0)
|
|
227
|
+
current.blocks.push({ ...block, text });
|
|
228
|
+
block = null;
|
|
229
|
+
pending = [];
|
|
230
|
+
};
|
|
231
|
+
const closeSection = () => {
|
|
232
|
+
closeBlock();
|
|
233
|
+
if (current.heading.length > 0 || current.blocks.length > 0)
|
|
234
|
+
sections.push(current);
|
|
235
|
+
};
|
|
236
|
+
lines.forEach((line, index) => {
|
|
237
|
+
const heading = HEADING_LINE.exec(line);
|
|
238
|
+
if (heading !== null) {
|
|
239
|
+
closeSection();
|
|
240
|
+
const title = (heading[2] ?? "").trim();
|
|
241
|
+
current = { heading: title, level: (heading[1] ?? "##").length, line: index, blocks: [], rule: SUMMARY_SECTION_RULES.get(headingKey(title)) ?? null };
|
|
242
|
+
return;
|
|
243
|
+
}
|
|
244
|
+
if (TOP_LEVEL_ITEM.test(line)) {
|
|
245
|
+
closeBlock();
|
|
246
|
+
block = { kind: "item", text: line, line: index };
|
|
247
|
+
return;
|
|
248
|
+
}
|
|
249
|
+
const blank = line.trim().length === 0;
|
|
250
|
+
if (block !== null && (blank || /^\s/u.test(line))) {
|
|
251
|
+
// Blank lines are held back: they only belong to the block if indented content follows,
|
|
252
|
+
// otherwise they are the gap before the next block and must not pad this one.
|
|
253
|
+
if (blank)
|
|
254
|
+
pending.push(line);
|
|
255
|
+
else {
|
|
256
|
+
block.text += `\n${[...pending, line].join("\n")}`;
|
|
257
|
+
pending = [];
|
|
258
|
+
}
|
|
259
|
+
return;
|
|
260
|
+
}
|
|
261
|
+
if (block !== null && block.kind === "prose" && blank) {
|
|
262
|
+
pending.push(line);
|
|
263
|
+
return;
|
|
264
|
+
}
|
|
265
|
+
if (blank) {
|
|
266
|
+
closeBlock();
|
|
267
|
+
return;
|
|
268
|
+
}
|
|
269
|
+
if (block === null || block.kind === "item") {
|
|
270
|
+
closeBlock();
|
|
271
|
+
block = { kind: "prose", text: line, line: index };
|
|
272
|
+
return;
|
|
273
|
+
}
|
|
274
|
+
block.text += `\n${[...pending, line].join("\n")}`;
|
|
275
|
+
pending = [];
|
|
276
|
+
});
|
|
277
|
+
closeSection();
|
|
278
|
+
return sections;
|
|
279
|
+
}
|
|
280
|
+
/** Strips the Markdown list syntax from a block's first line; the rest is the author's own text. */
|
|
281
|
+
function stripMarker(text) {
|
|
282
|
+
const lines = text.split("\n");
|
|
283
|
+
const first = (lines[0] ?? "").replace(TOP_LEVEL_ITEM, "").replace(TASK_MARKER, "");
|
|
284
|
+
return [first, ...lines.slice(1)].join("\n").trim();
|
|
285
|
+
}
|
|
286
|
+
/**
|
|
287
|
+
* Which blocks of a known section become claims.
|
|
288
|
+
*
|
|
289
|
+
* Every top-level list item does. Prose does only when it is the section's whole content or when it
|
|
290
|
+
* precedes the first list item — the shapes the corpus actually uses for a written-out `## Goal` or
|
|
291
|
+
* `## Original Request`. Prose *after* the last item is the split-turn separator and the
|
|
292
|
+
* `<read-files>` dump; it is counted (`droppedTrailingBlocks`) rather than either claimed or
|
|
293
|
+
* silently discarded, so a grammar change that starts putting real content there is visible.
|
|
294
|
+
*/
|
|
295
|
+
function claimBlocks(section) {
|
|
296
|
+
const firstItem = section.blocks.findIndex((candidate) => candidate.kind === "item");
|
|
297
|
+
if (firstItem < 0)
|
|
298
|
+
return { claimed: section.blocks, dropped: 0 };
|
|
299
|
+
const claimed = section.blocks.filter((candidate, index) => candidate.kind === "item" || index < firstItem);
|
|
300
|
+
return { claimed, dropped: section.blocks.length - claimed.length };
|
|
301
|
+
}
|
|
302
|
+
/* ------------------------------------------------------------------------------------------------
|
|
303
|
+
* Path 4 — excerpt windows over raw events
|
|
304
|
+
* ---------------------------------------------------------------------------------------------- */
|
|
305
|
+
/** ±240 characters, the window design §18 prices at roughly 120 tokens against 1K for a whole event. */
|
|
306
|
+
export const EXCERPT_RADIUS = 240;
|
|
307
|
+
/**
|
|
308
|
+
* A deterministic window over an artifact.
|
|
309
|
+
*
|
|
310
|
+
* The anchor is the *first* occurrence of the *first* term that occurs at all — first by term
|
|
311
|
+
* order, not by position — so the same terms over the same content always produce the same window
|
|
312
|
+
* regardless of how the terms were collected. A recency retrieval, or a term set that matches
|
|
313
|
+
* nothing, takes the head instead, which is honest about the fact that nothing in the artifact was
|
|
314
|
+
* selected for.
|
|
315
|
+
*/
|
|
316
|
+
export function excerptFor(content, terms, mode = "match") {
|
|
317
|
+
const width = EXCERPT_RADIUS * 2 + 1;
|
|
318
|
+
if (mode === "head" || terms.length === 0) {
|
|
319
|
+
const end = Math.min(content.length, width);
|
|
320
|
+
return { text: withEllipses(content, 0, end), start: 0, end, anchor: "head" };
|
|
321
|
+
}
|
|
322
|
+
const haystack = content.toLowerCase();
|
|
323
|
+
for (const term of terms) {
|
|
324
|
+
const needle = term.toLowerCase();
|
|
325
|
+
if (needle.length === 0)
|
|
326
|
+
continue;
|
|
327
|
+
const at = haystack.indexOf(needle);
|
|
328
|
+
if (at < 0)
|
|
329
|
+
continue;
|
|
330
|
+
const start = Math.max(0, at - EXCERPT_RADIUS);
|
|
331
|
+
const end = Math.min(content.length, at + needle.length + EXCERPT_RADIUS);
|
|
332
|
+
return { text: withEllipses(content, start, end), start, end, anchor: "match" };
|
|
333
|
+
}
|
|
334
|
+
const end = Math.min(content.length, width);
|
|
335
|
+
return { text: withEllipses(content, 0, end), start: 0, end, anchor: "head" };
|
|
336
|
+
}
|
|
337
|
+
/**
|
|
338
|
+
* The ellipsis is a claim about the text: it says "this is a window, not the artifact". It cannot
|
|
339
|
+
* affect identity — `normalizeClaimText` maps punctuation to whitespace and collapses it — so the
|
|
340
|
+
* same passage reached from two different query terms still deduplicates.
|
|
341
|
+
*/
|
|
342
|
+
function withEllipses(content, start, end) {
|
|
343
|
+
return `${start > 0 ? "…" : ""}${content.slice(start, end)}${end < content.length ? "…" : ""}`;
|
|
344
|
+
}
|
|
345
|
+
/* ------------------------------------------------------------------------------------------------
|
|
346
|
+
* Extraction
|
|
347
|
+
* ---------------------------------------------------------------------------------------------- */
|
|
348
|
+
export const EXTRACTION_PATHS = ["curated_memory", "compaction_summary", "raw_event"];
|
|
349
|
+
function emptyStats() {
|
|
350
|
+
return {
|
|
351
|
+
envelopes: 0,
|
|
352
|
+
claims: 0,
|
|
353
|
+
byPath: { curated_memory: 0, compaction_summary: 0, raw_event: 0 },
|
|
354
|
+
knownSections: 0,
|
|
355
|
+
unknownSections: 0,
|
|
356
|
+
unknownHeadings: {},
|
|
357
|
+
droppedTrailingBlocks: 0,
|
|
358
|
+
unhandledEnvelopes: 0,
|
|
359
|
+
};
|
|
360
|
+
}
|
|
361
|
+
function findOrigin(envelope, kind) {
|
|
362
|
+
for (const entry of envelope.provenance) {
|
|
363
|
+
if (entry !== null && typeof entry === "object" && entry.kind === kind)
|
|
364
|
+
return entry;
|
|
365
|
+
}
|
|
366
|
+
return null;
|
|
367
|
+
}
|
|
368
|
+
/**
|
|
369
|
+
* AkashicForge's `kind` column → Mnemosia's `claimType` (design §8.1).
|
|
370
|
+
*
|
|
371
|
+
* An unrecognized kind becomes an OBSERVATION rather than defaulting to FACT: a memory kind nobody
|
|
372
|
+
* has reviewed must not inherit the authority of one that was, which is the same rule an
|
|
373
|
+
* adapter applies when it routes an unknown event kind to the least-trusted channel. The certainty
|
|
374
|
+
* still reads CONFIRMED, because certainty here is a statement about *who wrote it* — a human
|
|
375
|
+
* curating the vault — and that is true whatever the kind column says.
|
|
376
|
+
*/
|
|
377
|
+
export function claimTypeForMemoryKind(kind) {
|
|
378
|
+
switch (kind) {
|
|
379
|
+
case "decisions":
|
|
380
|
+
return "DECISION";
|
|
381
|
+
case "preferences":
|
|
382
|
+
return "PREFERENCE";
|
|
383
|
+
case "procedures":
|
|
384
|
+
return "PROCEDURE";
|
|
385
|
+
case "project-state":
|
|
386
|
+
return "FACT";
|
|
387
|
+
case "open-loops":
|
|
388
|
+
return "PLAN";
|
|
389
|
+
case "people":
|
|
390
|
+
return "FACT";
|
|
391
|
+
default:
|
|
392
|
+
return "OBSERVATION";
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
const LIFECYCLE_LOOKUP = new Set(LIFECYCLE_PRECEDENCE);
|
|
396
|
+
export function toLifecycle(state) {
|
|
397
|
+
return LIFECYCLE_LOOKUP.has(state) ? state : null;
|
|
398
|
+
}
|
|
399
|
+
/**
|
|
400
|
+
* Certainty of a whole-artifact OBSERVATION, by the event kind that produced it (design §8.4).
|
|
401
|
+
*
|
|
402
|
+
* Tools observe and users assert, so both are PROBABLE; assistants speculate, so they are
|
|
403
|
+
* SPECULATIVE. An unrecognized kind is UNKNOWN rather than being folded into the nearest neighbour.
|
|
404
|
+
*/
|
|
405
|
+
export function certaintyForEventKind(kind) {
|
|
406
|
+
switch (kind) {
|
|
407
|
+
case "user":
|
|
408
|
+
case "tool":
|
|
409
|
+
return "PROBABLE";
|
|
410
|
+
case "assistant":
|
|
411
|
+
return "SPECULATIVE";
|
|
412
|
+
default:
|
|
413
|
+
return "UNKNOWN";
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
/** Extraction for a single envelope. Exported so tests and the trace can attribute per-artifact. */
|
|
417
|
+
export function extractFromEnvelope(envelope, options = {}) {
|
|
418
|
+
const stats = emptyStats();
|
|
419
|
+
stats.envelopes = 1;
|
|
420
|
+
const claims = [];
|
|
421
|
+
const push = (path, claim) => {
|
|
422
|
+
if (claim === null)
|
|
423
|
+
return;
|
|
424
|
+
claims.push(claim);
|
|
425
|
+
stats.byPath[path] += 1;
|
|
426
|
+
};
|
|
427
|
+
switch (envelope.sourceType) {
|
|
428
|
+
case "curated_memory": {
|
|
429
|
+
const origin = findOrigin(envelope, "mnemosia/origin/akashic-memory");
|
|
430
|
+
push("curated_memory", materialize(envelope, {
|
|
431
|
+
text: envelope.contentRef.inline,
|
|
432
|
+
claimType: claimTypeForMemoryKind(origin?.memoryKind ?? ""),
|
|
433
|
+
certainty: "CONFIRMED",
|
|
434
|
+
locator: "whole",
|
|
435
|
+
directness: "direct",
|
|
436
|
+
// A curated memory's claim became effective when the row was last edited, not when
|
|
437
|
+
// it was first written: freshness must reward the edit, or a maintained memory
|
|
438
|
+
// would decay at the same rate as an abandoned one.
|
|
439
|
+
effectiveAt: envelope.updatedAt,
|
|
440
|
+
expiresAt: origin?.expiresAt ?? null,
|
|
441
|
+
lifecycle: origin === null ? null : toLifecycle(origin.state),
|
|
442
|
+
// Stored in artifact-id form. The column holds a bare memory id, which is an
|
|
443
|
+
// AkashicForge identifier; converting it here means conflicts.ts (step 11) resolves
|
|
444
|
+
// supersession against the same namespace every Evidence already points into.
|
|
445
|
+
supersedes: origin?.supersedes ? [`akashic-memory:${origin.supersedes}`] : [],
|
|
446
|
+
}));
|
|
447
|
+
break;
|
|
448
|
+
}
|
|
449
|
+
case "compaction_summary": {
|
|
450
|
+
for (const section of parseSummarySections(envelope.contentRef.inline)) {
|
|
451
|
+
if (section.rule === null) {
|
|
452
|
+
stats.unknownSections += 1;
|
|
453
|
+
const label = section.heading.length === 0 ? "(preamble)" : section.heading;
|
|
454
|
+
stats.unknownHeadings[label] = (stats.unknownHeadings[label] ?? 0) + 1;
|
|
455
|
+
// The whole section, honestly labelled. UNKNOWN certainty is the point: Mnemosia
|
|
456
|
+
// does not know what this heading means, and says so instead of guessing a type.
|
|
457
|
+
push("compaction_summary", materialize(envelope, {
|
|
458
|
+
text: section.blocks.map((entry) => entry.text).join("\n"),
|
|
459
|
+
claimType: "OBSERVATION",
|
|
460
|
+
certainty: "UNKNOWN",
|
|
461
|
+
locator: `#${label}`,
|
|
462
|
+
directness: "derived",
|
|
463
|
+
}));
|
|
464
|
+
continue;
|
|
465
|
+
}
|
|
466
|
+
stats.knownSections += 1;
|
|
467
|
+
const { claimed, dropped } = claimBlocks(section);
|
|
468
|
+
stats.droppedTrailingBlocks += dropped;
|
|
469
|
+
claimed.forEach((entry, index) => {
|
|
470
|
+
push("compaction_summary", materialize(envelope, {
|
|
471
|
+
text: stripMarker(entry.text),
|
|
472
|
+
claimType: section.rule?.claimType ?? "OBSERVATION",
|
|
473
|
+
certainty: capCertainty("PROBABLE", SUMMARY_CERTAINTY_CEILING),
|
|
474
|
+
locator: `#${section.heading}[${index}]`,
|
|
475
|
+
// `derived` is what caps evidence strength at 0.4 in design §9. Every route
|
|
476
|
+
// out of a summary takes it.
|
|
477
|
+
directness: "derived",
|
|
478
|
+
}));
|
|
479
|
+
});
|
|
480
|
+
}
|
|
481
|
+
break;
|
|
482
|
+
}
|
|
483
|
+
case "conversation_message":
|
|
484
|
+
case "tool_output": {
|
|
485
|
+
const origin = findOrigin(envelope, "mnemosia/origin/conversation");
|
|
486
|
+
const eventKind = origin?.eventKind ?? (envelope.sourceType === "tool_output" ? "tool" : "");
|
|
487
|
+
const terms = options.terms ?? [];
|
|
488
|
+
const excerpt = excerptFor(envelope.contentRef.inline, terms, envelope.retrievalMethod === "recency_scan" ? "head" : "match");
|
|
489
|
+
push("raw_event", materialize(envelope, {
|
|
490
|
+
text: excerpt.text,
|
|
491
|
+
// One claim per artifact. See the file header on why this is not atomized.
|
|
492
|
+
claimType: "OBSERVATION",
|
|
493
|
+
certainty: certaintyForEventKind(eventKind),
|
|
494
|
+
locator: `chars ${excerpt.start}-${excerpt.end}`,
|
|
495
|
+
directness: "direct",
|
|
496
|
+
}));
|
|
497
|
+
break;
|
|
498
|
+
}
|
|
499
|
+
default:
|
|
500
|
+
stats.unhandledEnvelopes += 1;
|
|
501
|
+
break;
|
|
502
|
+
}
|
|
503
|
+
stats.claims = claims.length;
|
|
504
|
+
return { claims, stats };
|
|
505
|
+
}
|
|
506
|
+
function mergeStats(into, from) {
|
|
507
|
+
into.envelopes += from.envelopes;
|
|
508
|
+
into.claims += from.claims;
|
|
509
|
+
for (const path of EXTRACTION_PATHS)
|
|
510
|
+
into.byPath[path] += from.byPath[path];
|
|
511
|
+
into.knownSections += from.knownSections;
|
|
512
|
+
into.unknownSections += from.unknownSections;
|
|
513
|
+
for (const [heading, count] of Object.entries(from.unknownHeadings))
|
|
514
|
+
into.unknownHeadings[heading] = (into.unknownHeadings[heading] ?? 0) + count;
|
|
515
|
+
into.droppedTrailingBlocks += from.droppedTrailingBlocks;
|
|
516
|
+
into.unhandledEnvelopes += from.unhandledEnvelopes;
|
|
517
|
+
}
|
|
518
|
+
/** Extraction over a whole retrieval result. Order follows the envelopes, which the adapters sorted. */
|
|
519
|
+
export function extractClaims(envelopes, options = {}) {
|
|
520
|
+
const stats = emptyStats();
|
|
521
|
+
const claims = [];
|
|
522
|
+
for (const envelope of envelopes) {
|
|
523
|
+
const one = extractFromEnvelope(envelope, options);
|
|
524
|
+
claims.push(...one.claims);
|
|
525
|
+
mergeStats(stats, one.stats);
|
|
526
|
+
}
|
|
527
|
+
return { claims, stats };
|
|
528
|
+
}
|
|
529
|
+
function bestByPrecedence(values, order) {
|
|
530
|
+
let best;
|
|
531
|
+
let bestRank = Number.POSITIVE_INFINITY;
|
|
532
|
+
for (const value of values) {
|
|
533
|
+
const rank = order.indexOf(value);
|
|
534
|
+
const effective = rank < 0 ? order.length : rank;
|
|
535
|
+
if (effective < bestRank) {
|
|
536
|
+
bestRank = effective;
|
|
537
|
+
best = value;
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
return best;
|
|
541
|
+
}
|
|
542
|
+
/**
|
|
543
|
+
* "Identical `dedupKey` in compatible scope ⇒ one claim, evidence unioned, `certainty` = max,
|
|
544
|
+
* earliest `effectiveAt`, all provenance kept" (design §8).
|
|
545
|
+
*
|
|
546
|
+
* The last clause is the one with teeth. Spec §23 requires deduplication that does not destroy
|
|
547
|
+
* provenance, so a merged claim carries **every** contributing artifact's evidence — the union is
|
|
548
|
+
* what makes `evidence_strength` (§9: `0.4·direct + 0.2·log2(1+supports)`) mean "how many
|
|
549
|
+
* independent artifacts said this" instead of "which artifact happened to be read first".
|
|
550
|
+
*
|
|
551
|
+
* Scope compatibility is exact equality, and it is already folded into `claimId` (see `claimIdFor`),
|
|
552
|
+
* so grouping by `claimId` *is* the scope check rather than a second one that could disagree with it.
|
|
553
|
+
*
|
|
554
|
+
* Output order is first appearance. The envelopes arrived in a total order the adapters imposed
|
|
555
|
+
* (§16 determinism), so preserving it keeps the pipeline reproducible while staying readable.
|
|
556
|
+
*/
|
|
557
|
+
export function dedupeClaims(claims) {
|
|
558
|
+
const groups = new Map();
|
|
559
|
+
const order = [];
|
|
560
|
+
for (const claim of claims) {
|
|
561
|
+
const existing = groups.get(claim.claimId);
|
|
562
|
+
if (existing === undefined) {
|
|
563
|
+
groups.set(claim.claimId, [claim]);
|
|
564
|
+
order.push(claim.claimId);
|
|
565
|
+
}
|
|
566
|
+
else
|
|
567
|
+
existing.push(claim);
|
|
568
|
+
}
|
|
569
|
+
const merged = [];
|
|
570
|
+
for (const claimId of order) {
|
|
571
|
+
const group = groups.get(claimId) ?? [];
|
|
572
|
+
const base = group[0];
|
|
573
|
+
if (base === undefined)
|
|
574
|
+
continue;
|
|
575
|
+
if (group.length === 1) {
|
|
576
|
+
merged.push(base);
|
|
577
|
+
continue;
|
|
578
|
+
}
|
|
579
|
+
const evidence = new Map();
|
|
580
|
+
for (const member of group)
|
|
581
|
+
for (const item of member.evidence)
|
|
582
|
+
evidence.set(item.evidenceId, item);
|
|
583
|
+
// A total order over the union, so two runs that read the same artifacts in different orders
|
|
584
|
+
// still serialize byte-identically (§16).
|
|
585
|
+
const evidenceList = [...evidence.values()].sort((a, b) => (a.artifactId < b.artifactId ? -1 : a.artifactId > b.artifactId ? 1 : a.relation < b.relation ? -1 : a.relation > b.relation ? 1 : 0));
|
|
586
|
+
const supersedes = [...new Set(group.flatMap((member) => member.supersedes))].sort();
|
|
587
|
+
const expiries = group.map((member) => member.expiresAt).filter((value) => value !== null);
|
|
588
|
+
const lifecycles = group.map((member) => member.lifecycle).filter((value) => value !== null);
|
|
589
|
+
merged.push({
|
|
590
|
+
...base,
|
|
591
|
+
// The longest surviving text: two renderings of the same normalized sentence differ only
|
|
592
|
+
// in the material normalization threw away, and the fuller one is the better quotation.
|
|
593
|
+
text: group.reduce((longest, member) => (member.text.length > longest.length ? member.text : longest), base.text),
|
|
594
|
+
claimType: bestByPrecedence(group.map((member) => member.claimType), CLAIM_TYPE_PRECEDENCE) ?? base.claimType,
|
|
595
|
+
certainty: group.reduce((best, member) => maxCertainty(best, member.certainty), "UNKNOWN"),
|
|
596
|
+
effectiveAt: Math.min(...group.map((member) => member.effectiveAt)),
|
|
597
|
+
// The earliest expiry wins: a claim that two sources bound differently stops being
|
|
598
|
+
// retrievable at the first of those bounds, never the last.
|
|
599
|
+
expiresAt: expiries.length === 0 ? null : Math.min(...expiries),
|
|
600
|
+
lifecycle: bestByPrecedence(lifecycles, LIFECYCLE_PRECEDENCE) ?? null,
|
|
601
|
+
supersedes,
|
|
602
|
+
evidence: evidenceList,
|
|
603
|
+
});
|
|
604
|
+
}
|
|
605
|
+
// "All provenance kept" is only a real property if it is measurable, so this counts the claims
|
|
606
|
+
// that actually ended up standing on more than one artifact.
|
|
607
|
+
const multiSourced = merged.filter((claim) => new Set(claim.evidence.map((item) => item.artifactId)).size > 1).length;
|
|
608
|
+
return { claims: merged, before: claims.length, after: merged.length, merged: claims.length - merged.length, multiSourced };
|
|
609
|
+
}
|