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,124 @@
1
+ // Ported from akashic-forge/index.ts @ f0a8ad4 (MIT; see NOTICE)
2
+ // The memory wiring for one piroboros home: the akashic store, the vault mirror, the briefing sources and the
3
+ // /akashic commands, which are adapted from the source's command. Everything lives under ${home}/akashic and ${home}/mnemosia.
4
+ import { createHash } from "node:crypto";
5
+ import { join } from "node:path";
6
+ import { createMemoryApi } from "./akashic/api.js";
7
+ import { renderMemorySnapshot } from "./akashic/snapshot.js";
8
+ import { AkashicStore } from "./akashic/store.js";
9
+ import { VaultError, VaultManager } from "./akashic/vault.js";
10
+ import { mnemosiaPaths, openFoundations } from "./mnemosia/open.js";
11
+ export const memoryPaths = (home) => ({ db: join(home, "akashic", "memory.sqlite"), limits: join(home, "akashic", "limits.json"), vaultConfig: join(home, "akashic", "vault.json"), vaultClone: join(home, "akashic", "vault") });
12
+ const failureText = (failure) => `${failure.code}: ${failure.reason}`;
13
+ const describe = (error) => (error instanceof VaultError && error.code !== undefined ? `${error.code}: ${error.message}` : error instanceof Error ? error.message : String(error));
14
+ export class MemoryHost {
15
+ paths;
16
+ store;
17
+ api;
18
+ vault;
19
+ foundations;
20
+ warn;
21
+ constructor(options) {
22
+ this.paths = memoryPaths(options.home);
23
+ this.warn = options.warn ?? (() => { });
24
+ this.store = new AkashicStore(this.paths.db, this.paths.limits);
25
+ this.api = createMemoryApi(this.store);
26
+ this.vault = new VaultManager(this.store, undefined, this.paths.vaultConfig, options.runner, this.warn);
27
+ this.foundations = openFoundations(this.store, mnemosiaPaths(options.home), this.warn);
28
+ }
29
+ /** The top memories for `cwd` as one framed, escaped block, or undefined when there is nothing to show. */
30
+ snapshot(cwd) {
31
+ const rendered = renderMemorySnapshot(this.store.listMemories({ scope: "all", project: cwd, limit: 5, order: "importance" }));
32
+ return rendered === undefined ? undefined : { hash: createHash("sha256").update(rendered.content).digest("hex").slice(0, 16), ids: rendered.ids, content: rendered.content };
33
+ }
34
+ status() {
35
+ return { memories: this.store.countMemories(), vaultConfigured: this.vault.configured, pendingSync: this.vault.pendingSync, quarantined: this.store.countState("QUARANTINED"), proposed: this.store.countState("PROPOSED") };
36
+ }
37
+ /** Change the state of a record the user accepted. Goes through the governed mutation, so the ledger has a row. */
38
+ async accept(state, target) {
39
+ const records = target === "all" ? this.store.listByState(state, 1_000) : [this.store.getMemory(target)].filter((record) => record !== undefined);
40
+ if (records.length === 0)
41
+ return target === "all" ? `no ${state.toLowerCase()} memories` : `no memory with id ${target}`;
42
+ const wrong = records.filter((record) => record.state !== state);
43
+ if (wrong.length > 0)
44
+ return `${wrong[0].id} is ${wrong[0].state}, not ${state}; nothing was changed`;
45
+ let failure;
46
+ for (const record of records) {
47
+ const outcome = await this.vault.write(() => this.api.mutateMemory({ memoryId: record.id, idempotencyKey: `accept:${record.id}:${record.version}`, expectedVersion: record.version, actor: "user", reason: `accepted from ${state}`, transition: "ACTIVE" }));
48
+ failure ??= outcome.vault;
49
+ }
50
+ return `${records.length} memor${records.length === 1 ? "y" : "ies"} accepted and now in the snapshot${failure === undefined ? "" : `\nvault mirror failed (saved locally): ${failureText(failure)}`}`;
51
+ }
52
+ /** /akashic ... Returns the reply text. */
53
+ async command(args, cwd) {
54
+ const [first = "status", second, third, ...rest] = args.trim().split(/\s+/u).filter((part) => part !== "");
55
+ try {
56
+ if (first === "status")
57
+ return this.statusText(cwd);
58
+ if (first === "accept")
59
+ return second === undefined ? "usage: /akashic accept <id|all>" : await this.accept("QUARANTINED", second);
60
+ if (first !== "vault")
61
+ return "usage: /akashic [status] | accept <id|all> | vault status|init <repo-url> [--auto-push]|sync|commit [message]|push|import|accept <id|all>";
62
+ switch (second ?? "status") {
63
+ case "status": {
64
+ const vault = await this.vault.status();
65
+ if (!vault.configured)
66
+ return "vault: not configured; run /akashic vault init <repo-url>";
67
+ return [`vault: ${vault.clonePath} (${vault.clean ? "clean" : "needs attention"}), origin ${vault.repoUrl}`, vault.branch === undefined ? "" : `branch: ${vault.branch}`, `pending sync: ${this.vault.pendingSync ? "yes, run /akashic vault sync" : "no"}`, ...(vault.changes ?? []).slice(0, 10).map((line) => ` ${line}`)].filter((line) => line !== "").join("\n");
68
+ }
69
+ case "init": {
70
+ if (third === undefined)
71
+ return "usage: /akashic vault init <repo-url> [--auto-push]";
72
+ const config = await this.vault.init(third, { clonePath: this.paths.vaultClone, autoPush: rest.includes("--auto-push") });
73
+ return `vault ready at ${config.clonePath}; every memory is written there as a Markdown file (commit ${config.autoCommit ? "on" : "off"}, push ${config.autoPush ? "on" : "off"}). SQLite stays the source of truth.`;
74
+ }
75
+ case "sync": {
76
+ const done = await this.vault.sync(false);
77
+ return `vault synced: ${done.written} file${done.written === 1 ? "" : "s"} written, ${done.removed} removed${done.pushed ? ", pushed" : ""}`;
78
+ }
79
+ case "push": {
80
+ const done = await this.vault.sync(true);
81
+ return `vault synced and pushed: ${done.written} file${done.written === 1 ? "" : "s"} written, ${done.removed} removed`;
82
+ }
83
+ case "commit": {
84
+ // The only way a vault-gated record reaches the clone; the mirror never writes those.
85
+ const message = [third, ...rest].filter((part) => part !== undefined).join(" ");
86
+ const done = await this.vault.commit(message === "" ? undefined : message);
87
+ return done ? "vault committed; gated records in the clone are published with it" : "nothing to commit";
88
+ }
89
+ case "import": {
90
+ const report = await this.vault.import(cwd);
91
+ return [
92
+ `import: ${report.inserted.length} added as PROPOSED, ${report.exists.length} already stored (left unchanged), ${report.duplicates.length} duplicate content, ${report.outOfScope.length} for other projects, ${report.invalid.length} rejected`,
93
+ ...report.invalid.slice(0, 5).map((item) => ` rejected ${item.path}: ${item.message}`),
94
+ report.pullFailed === undefined ? "" : `pull failed, the files already in the clone were read: ${failureText(report.pullFailed)}`,
95
+ report.inserted.length === 0 ? "" : "Imported memories stay out of the snapshot until you run /akashic vault accept <id|all>.",
96
+ ].filter((line) => line !== "").join("\n");
97
+ }
98
+ case "accept":
99
+ return third === undefined ? "usage: /akashic vault accept <id|all>" : await this.accept("PROPOSED", third);
100
+ default:
101
+ return `unknown vault command ${second}; use status, init, sync, commit, push, import or accept`;
102
+ }
103
+ }
104
+ catch (error) {
105
+ return describe(error);
106
+ }
107
+ }
108
+ statusText(cwd) {
109
+ const stats = this.store.stats(cwd);
110
+ const status = this.status();
111
+ const kinds = Object.entries(stats.memoriesByKind).map(([kind, count]) => `${kind} ${count}`).join(", ") || "none";
112
+ const usage = [stats.memoryUsage.global, ...(stats.memoryUsage.project === undefined ? [] : [stats.memoryUsage.project])].map((u) => `${u.scope}: ${u.usedChars}/${u.limitChars} chars, ${u.entries} entries`).join("; ");
113
+ return [
114
+ `${stats.memories} memories (${kinds})`,
115
+ usage,
116
+ `vault: ${status.vaultConfigured ? `configured${status.pendingSync ? ", pending sync (run /akashic vault sync)" : ""}` : "not configured"}`,
117
+ status.quarantined > 0 ? `${status.quarantined} quarantined: written while only member reports were in the turn; /akashic accept <id|all> releases them` : "",
118
+ status.proposed > 0 ? `${status.proposed} proposed: imported from the vault; /akashic vault accept <id|all> releases them` : "",
119
+ ].filter((line) => line !== "").join("\n");
120
+ }
121
+ close() {
122
+ this.store.close();
123
+ }
124
+ }
@@ -0,0 +1,180 @@
1
+ // Ported from mnemosia/adapters/akashic-memories.ts @ f0a8ad4 (MIT; see NOTICE)
2
+ /**
3
+ * Adapter over AkashicForge's curated memory surface (`memoryApi.getMemories`).
4
+ *
5
+ * This is the small, high-authority half of the corpus: ten human-curated, governed rows. It is also the only source in Phase 1 that publishes a real
6
+ * integrity claim — `content_hash`, written as `sha256(content, "utf8")` at store.ts:746 — so it is
7
+ * the only source whose envelopes can reach `integrityStatus: "verified"`, and they reach it by
8
+ * recomputation rather than by assertion.
9
+ *
10
+ * The upstream API arrives by injection. That is not ceremony: it keeps `src/` free of cross-tree
11
+ * imports (Mnemosia's source lives on D:, the foundations on C:), it lets the error-translation
12
+ * tests drive real failures through a fake, and it is what makes "replaceable adapter" true rather
13
+ * than aspirational. src/memory/mnemosia/open.ts passes the genuine `createMemoryApi(store)`, and
14
+ * the typechecker proves the structural types below match the real ones at that call site.
15
+ */
16
+ import { assertDeadline, buildEnvelope, classifyAdapterError, matchTextOrUndefined, pageSizeFor, runAdapterQuery, scopeFilterFor, } from "./contract.js";
17
+ import { SOURCE_ID } from "../types.js";
18
+ /* ------------------------------------------------------------------------------------------------
19
+ * Adapter
20
+ * ---------------------------------------------------------------------------------------------- */
21
+ export function createAkashicMemoriesAdapter(options) {
22
+ const sourceId = SOURCE_ID.akashicMemories;
23
+ const now = options.now ?? Date.now;
24
+ function probe() {
25
+ const started = Date.now();
26
+ try {
27
+ // One row is enough to prove the database opens, the schema is present, and the read path
28
+ // works. Counting the corpus would cost a scan to learn something the probe does not need.
29
+ const page = options.api.getMemories({ limit: 1 });
30
+ return {
31
+ sourceId,
32
+ available: true,
33
+ detail: `curated memory readable (${page.memories.length === 0 ? "empty corpus" : "at least 1 row"}, schema ${page.schemaVersion})`,
34
+ code: null,
35
+ latencyMs: Date.now() - started,
36
+ };
37
+ }
38
+ catch (error) {
39
+ // A probe never throws: PLAN_RETRIEVAL must be able to record an unavailable source and
40
+ // keep going, which is the whole graceful-degradation path.
41
+ const message = error instanceof Error ? error.message : String(error);
42
+ return { sourceId, available: false, detail: message, code: classifyAdapterError(error), latencyMs: Date.now() - started };
43
+ }
44
+ }
45
+ function query(plannedQuery, deadlineMs) {
46
+ const started = Date.now();
47
+ return runAdapterQuery(sourceId, () => {
48
+ assertDeadline(sourceId, deadlineMs, started);
49
+ const filter = scopeFilterFor(sourceId, plannedQuery.scope);
50
+ const limit = pageSizeFor(plannedQuery.maxArtifacts);
51
+ const observedAt = now();
52
+ /**
53
+ * `any` is executed as a **union of single-term reads**, not as an FTS5 `OR` string.
54
+ *
55
+ * AkashicForge quotes every token and joins them with a space (`toSafeMatchQuery`,
56
+ * store.ts:480-484), so an operator written into the query text would be escaped into a
57
+ * literal and match nothing. Building the disjunction out of the store's own conjunctive
58
+ * primitive keeps the foundation untouched and keeps every term subject to the tokenizer
59
+ * the index was built with. It costs one prepared statement per term over a ten-row table,
60
+ * which is affordable precisely because the curated corpus is bounded at 16,000 global +
61
+ * 32,000 project characters (store.ts:13-14) — it would not be affordable on a large corpus,
62
+ * which is why the planner asks for `all` for any other source.
63
+ *
64
+ * Rows are keyed by id, so a row matching two terms is one artifact, and the union is
65
+ * ordered by first appearance in the planner's term order — a total order, which is what
66
+ * the §16 determinism gate needs.
67
+ *
68
+ * **The per-term bm25 scores are summed, and that is a reconstruction rather than a
69
+ * heuristic.** FTS5's `bm25()` is `Σ_t idf(t)·tfNorm(t, d)` over the query terms present
70
+ * in the document; every factor in a term's addend is a property of that term, that
71
+ * document and the index, and none of them is a property of the *other* terms in the
72
+ * query. So adding the scores this union collects for one row reproduces exactly the
73
+ * score a single query over the terms that matched it would have produced — which is the
74
+ * number the disjunction is standing in for. Taking the best single term instead would
75
+ * make a row that answers three of the task's words look no better than one that answers
76
+ * its rarest word only, which is the opposite of what a union is for.
77
+ */
78
+ const terms = plannedQuery.terms.filter((term) => term.trim().length > 0);
79
+ let rows;
80
+ let retrievalMethod;
81
+ let reads;
82
+ if (plannedQuery.matchMode === "any" && terms.length > 0) {
83
+ const byId = new Map();
84
+ for (const term of terms) {
85
+ if (byId.size >= limit)
86
+ break;
87
+ // A token the store refuses to search (punctuation-only under its own tokenizer) is
88
+ // skipped rather than failing the whole disjunction: one unusable term must not zero
89
+ // a query the remaining terms can still answer.
90
+ try {
91
+ for (const row of options.api.getMemories({ ...filter, query: term, limit }).memories) {
92
+ const seen = byId.get(row.id);
93
+ if (seen === undefined) {
94
+ byId.set(row.id, row);
95
+ continue;
96
+ }
97
+ // `set` on an existing key keeps its insertion position, so accumulating the
98
+ // score cannot disturb the term-order the determinism gate depends on.
99
+ if (typeof row.rank === "number")
100
+ byId.set(row.id, { ...seen, rank: (seen.rank ?? 0) + row.rank });
101
+ }
102
+ }
103
+ catch (error) {
104
+ // Only the store's own refusal of an unsearchable term is skipped; a database failure surfaces
105
+ // through runAdapterQuery as an adapter error instead of turning into an empty result.
106
+ if (error instanceof Error && error.message === "query must contain searchable text")
107
+ continue;
108
+ throw error;
109
+ }
110
+ }
111
+ rows = [...byId.values()].slice(0, limit);
112
+ retrievalMethod = "lexical_search";
113
+ reads = terms.length;
114
+ }
115
+ else {
116
+ const match = matchTextOrUndefined(terms);
117
+ retrievalMethod = match === undefined ? "recency_scan" : "lexical_search";
118
+ // Deliberately a single read rather than a paging loop: the corpus bound above means the
119
+ // 100-row cap is not the binding constraint here the way it is on a large corpus, and if it
120
+ // ever binds `truncated` says so instead of the adapter quietly returning a prefix.
121
+ rows = options.api.getMemories({ ...filter, query: match, limit }).memories;
122
+ reads = 1;
123
+ }
124
+ const envelopes = rows.map((row) => toEnvelope(row, retrievalMethod, observedAt));
125
+ return {
126
+ sourceId,
127
+ envelopes,
128
+ truncated: rows.length >= limit && plannedQuery.maxArtifacts > limit,
129
+ pagesRead: reads,
130
+ elapsedMs: Date.now() - started,
131
+ };
132
+ });
133
+ }
134
+ return { sourceId, probe, query };
135
+ }
136
+ /* ------------------------------------------------------------------------------------------------
137
+ * Normalization
138
+ * ---------------------------------------------------------------------------------------------- */
139
+ function toEnvelope(row, retrievalMethod, observedAt) {
140
+ /**
141
+ * The governance columns are inputs to hard filtering (state, expiry, supersession) and to three
142
+ * of the seven ranking signals (importance, tags, state). The envelope has no typed home for
143
+ * them and must not grow provider-specific fields, so they ride in provenance — losslessly, and
144
+ * ahead of whatever provenance the row itself carried.
145
+ */
146
+ const origin = {
147
+ kind: "mnemosia/origin/akashic-memory",
148
+ memoryId: row.id,
149
+ memoryKind: row.kind,
150
+ state: row.state,
151
+ version: row.version,
152
+ importance: row.importance,
153
+ tags: row.tags,
154
+ expiresAt: row.expiresAt,
155
+ supersedes: row.supersedes,
156
+ storedContentHash: row.contentHash ?? null,
157
+ };
158
+ return buildEnvelope({
159
+ artifactId: `akashic-memory:${row.id}`,
160
+ sourceId: SOURCE_ID.akashicMemories,
161
+ sourceType: "curated_memory",
162
+ sourceRef: `akashic-forge/memories/${row.id}`,
163
+ content: row.content,
164
+ createdAt: row.createdAt,
165
+ updatedAt: row.updatedAt,
166
+ observedAt,
167
+ scope: { level: row.scope, project: row.project },
168
+ // A curated memory is not the product of one task: it was distilled to outlive them.
169
+ taskScope: null,
170
+ // Human-curated, vault-canonical prose. It is evidence about the world, never an instruction.
171
+ channel: "RETRIEVED_EVIDENCE",
172
+ retrievalMethod,
173
+ provenance: [origin, ...row.provenance],
174
+ // The real check. A row whose stored hash disagrees with sha256 of its own content has been
175
+ // tampered with or has drifted, and it is hard-filtered before ranking ever sees it (§12).
176
+ expectedContentHash: row.contentHash ?? null,
177
+ // FTS5's own bm25, carried verbatim; absent when the read was a recency scan.
178
+ retrievalScore: row.rank,
179
+ });
180
+ }
@@ -0,0 +1,219 @@
1
+ // Ported from mnemosia/adapters/contract.ts @ f0a8ad4 (MIT; see NOTICE)
2
+ /**
3
+ * The source-adapter boundary (spec §10, design §13).
4
+ *
5
+ * Three obligations live here, and they are the reason this is a module rather than an interface
6
+ * declaration:
7
+ *
8
+ * 1. **Normalization.** `buildEnvelope` is the only way an `ArtifactEnvelope` is constructed. Every
9
+ * adapter goes through it, so `contentHash`, `tokenEstimate` and `integrityStatus` are computed
10
+ * by one function using one rule, and a new adapter cannot accidentally invent its own.
11
+ * 2. **Integrity that actually ran.** `integrityStatus` is derived from a comparison, never passed
12
+ * in. `verified` is reachable only by supplying an expected hash that matches the sha256 of the
13
+ * content in hand; anything else is `unverified` or `failed`. Setting the field to "verified" is
14
+ * not expressible through this API.
15
+ * 3. **Error translation.** Every provider throw becomes a `StandardAdapterError` with one of five
16
+ * codes. `runAdapterQuery` wraps a whole query so an adapter author cannot forget, and
17
+ * `classifyAdapterError` holds the single mapping table from provider failure text to code.
18
+ *
19
+ * `query` is synchronous because all of it is: both foundations are local SQLite read through
20
+ * `node:sqlite`'s synchronous API (design §13). An async signature here would be a promise about
21
+ * concurrency the runtime cannot keep, and it would make the deadline check racy for no gain.
22
+ */
23
+ import { createHash } from "node:crypto";
24
+ import { estimateTokens } from "../tokens.js";
25
+ import { SCHEMA_VERSION, } from "../types.js";
26
+ /* ------------------------------------------------------------------------------------------------
27
+ * Errors
28
+ * ---------------------------------------------------------------------------------------------- */
29
+ /**
30
+ * The one error type that leaves an adapter. It mirrors AkashicForge's `MemoryMutationError`
31
+ * deliberately: a code a caller can branch on without parsing a message, plus the original failure
32
+ * kept on `cause` so nothing is lost for the trace.
33
+ */
34
+ export class StandardAdapterError extends Error {
35
+ sourceId;
36
+ code;
37
+ cause;
38
+ constructor(sourceId, code, message, cause) {
39
+ super(message);
40
+ this.name = "StandardAdapterError";
41
+ this.sourceId = sourceId;
42
+ this.code = code;
43
+ this.cause = cause;
44
+ }
45
+ }
46
+ export function isStandardAdapterError(value) {
47
+ return value instanceof StandardAdapterError;
48
+ }
49
+ /**
50
+ * Provider failure text → standard code. The concrete failure set is small and enumerated by
51
+ * design §13 (missing DB, missing/invalid key, SQLITE_BUSY past the 5s timeout, schema
52
+ * drift, oversized results), so this is a table over known failures rather than an attempt at
53
+ * general classification: anything unrecognized is honestly `internal`.
54
+ *
55
+ * Order matters. `auth` is tested before `unavailable` because a missing key file raises ENOENT
56
+ * from inside key derivation, and "the source has no key" is an authorization fact, not a
57
+ * "the ledger is down" fact — they lead to different operator actions.
58
+ */
59
+ const ERROR_PATTERNS = [
60
+ { code: "timeout", pattern: /SQLITE_BUSY|database is locked|busy_?timeout|deadline exceeded|timed? ?out/i },
61
+ { code: "auth", pattern: /\bkey\b|decrypt|authenticat|security ?domain|unauthori[sz]ed|forbidden|EACCES|EPERM/i },
62
+ { code: "unavailable", pattern: /unable to open database|SQLITE_CANTOPEN|no such file|ENOENT|not a database|closed|is not open/i },
63
+ { code: "schema", pattern: /no such table|no such column|schema|must be one of|must be a |malformed|mutually exclusive|unexpected token|JSON/i },
64
+ ];
65
+ export function classifyAdapterError(error) {
66
+ const text = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
67
+ for (const { code, pattern } of ERROR_PATTERNS) {
68
+ if (pattern.test(text))
69
+ return code;
70
+ }
71
+ return "internal";
72
+ }
73
+ /** Idempotent: an error that is already standardized keeps its code rather than being reclassified. */
74
+ export function toAdapterError(sourceId, error) {
75
+ if (isStandardAdapterError(error))
76
+ return error;
77
+ const message = error instanceof Error ? error.message : String(error);
78
+ return new StandardAdapterError(sourceId, classifyAdapterError(error), `${sourceId}: ${message}`, error);
79
+ }
80
+ /**
81
+ * Wraps an adapter body so that no provider exception can escape untranslated. Adapters call this
82
+ * rather than each writing their own try/catch, which is what makes "every upstream failure becomes
83
+ * a StandardAdapterError" a property of the boundary instead of a per-adapter promise.
84
+ */
85
+ export function runAdapterQuery(sourceId, body) {
86
+ try {
87
+ return body();
88
+ }
89
+ catch (error) {
90
+ throw toAdapterError(sourceId, error);
91
+ }
92
+ }
93
+ /* ------------------------------------------------------------------------------------------------
94
+ * Deadlines
95
+ * ---------------------------------------------------------------------------------------------- */
96
+ /**
97
+ * `deadlineMs` is an absolute epoch-ms instant, not a duration. A paging loop that has already
98
+ * spent time reading page 1 must ask "may I still read page 2 *now*", and only an absolute instant
99
+ * answers that without every caller re-deriving it from a start time it would have to remember.
100
+ */
101
+ export function deadlineExceeded(deadlineMs, now = Date.now()) {
102
+ return now >= deadlineMs;
103
+ }
104
+ export function assertDeadline(sourceId, deadlineMs, now = Date.now()) {
105
+ if (deadlineExceeded(deadlineMs, now)) {
106
+ throw new StandardAdapterError(sourceId, "timeout", `${sourceId}: deadline exceeded before the query could run`);
107
+ }
108
+ }
109
+ /* ------------------------------------------------------------------------------------------------
110
+ * Hashing and integrity
111
+ * ---------------------------------------------------------------------------------------------- */
112
+ /**
113
+ * Identical to how AkashicForge computes `content_hash` (store.ts:746, `sha256(content, utf8)` in
114
+ * hex). It has to be, or the verification below would be comparing two different functions and
115
+ * would fail on every honest row.
116
+ */
117
+ export function sha256Hex(content) {
118
+ return createHash("sha256").update(content, "utf8").digest("hex");
119
+ }
120
+ /**
121
+ * Recompute and compare. `expected == null` means the source publishes no integrity claim for this
122
+ * artifact — a source may, for instance, store a fingerprint over a redacted canonicalization
123
+ * rather than a content hash — and that is `unverified`, which is a smaller claim than `verified`
124
+ * and a different one from `failed`.
125
+ */
126
+ export function verifyContentHash(content, expected) {
127
+ const computed = sha256Hex(content);
128
+ if (expected === null || expected === undefined || expected.length === 0)
129
+ return { computed, status: "unverified" };
130
+ return { computed, status: computed === expected ? "verified" : "failed" };
131
+ }
132
+ /**
133
+ * The only constructor for an `ArtifactEnvelope`.
134
+ *
135
+ * Note what it does *not* accept: `integrityStatus`, `contentHash`, `tokenEstimate`,
136
+ * `schemaVersion`, `classification`. Those are computed or constant, so an adapter cannot assert
137
+ * them. `channel` is `AdapterChannel`, so `SYSTEM_POLICY` and `AGENT_POLICY` are rejected by the
138
+ * compiler (types.ts, AdaptersCannotEmitPrivilegedChannels).
139
+ *
140
+ * `retrievalScore` moved off that list when the bm25 foundation change landed, and it is the only
141
+ * one that did. It is not a claim the adapter makes about its own work — it is a number the store
142
+ * computed and used to discard — so passing it through is transport, not assertion. It is still
143
+ * sanitized here rather than trusted.
144
+ */
145
+ export function buildEnvelope(input) {
146
+ const { computed, status } = verifyContentHash(input.content, input.expectedContentHash);
147
+ const violations = input.integrityViolations ?? [];
148
+ const integrityStatus = violations.length > 0 || status === "failed" ? "failed" : status;
149
+ const provenance = [...(input.provenance ?? [])];
150
+ if (integrityStatus === "failed") {
151
+ const entry = {
152
+ kind: "mnemosia/integrity-violation",
153
+ violations: status === "failed" ? [...violations, "content_hash_mismatch"] : violations,
154
+ expectedContentHash: input.expectedContentHash ?? null,
155
+ computedContentHash: computed,
156
+ };
157
+ provenance.push(entry);
158
+ }
159
+ return {
160
+ schemaVersion: SCHEMA_VERSION.artifactEnvelope,
161
+ artifactId: input.artifactId,
162
+ sourceId: input.sourceId,
163
+ sourceType: input.sourceType,
164
+ sourceRef: input.sourceRef,
165
+ contentRef: { inline: input.content },
166
+ contentHash: computed,
167
+ createdAt: input.createdAt,
168
+ updatedAt: input.updatedAt,
169
+ observedAt: input.observedAt,
170
+ scope: input.scope,
171
+ taskScope: input.taskScope,
172
+ classification: "internal",
173
+ channel: input.channel,
174
+ provenance,
175
+ integrityStatus,
176
+ retrievalMethod: input.retrievalMethod,
177
+ // Carried, never invented: `undefined` (the adapter did not offer one) and a non-finite value
178
+ // both collapse to `null`, so a NaN out of a provider can never reach the ranker as a score.
179
+ retrievalScore: typeof input.retrievalScore === "number" && Number.isFinite(input.retrievalScore) ? input.retrievalScore : null,
180
+ tokenEstimate: estimateTokens(input.content),
181
+ };
182
+ }
183
+ /* ------------------------------------------------------------------------------------------------
184
+ * Shared adapter helpers
185
+ * ---------------------------------------------------------------------------------------------- */
186
+ /**
187
+ * AkashicForge caps `limit` at 100 (store.ts:398) and validates it as a positive integer, so a
188
+ * planner asking for 400 candidates must be turned into pages rather than into a rejected query.
189
+ */
190
+ export const UPSTREAM_PAGE_LIMIT = 100;
191
+ export function pageSizeFor(remaining) {
192
+ return Math.max(1, Math.min(UPSTREAM_PAGE_LIMIT, remaining));
193
+ }
194
+ /**
195
+ * Terms are already tokenized by the planner; joining them with spaces is what AkashicForge's
196
+ * `toSafeMatchQuery` expects and it re-tokenizes anyway, so nothing here can inject FTS operators.
197
+ * Empty terms means "read by recency", which the store expresses as an absent `query`.
198
+ */
199
+ export function matchTextOrUndefined(terms) {
200
+ const cleaned = terms.filter((term) => term.trim().length > 0);
201
+ return cleaned.length === 0 ? undefined : cleaned.join(" ");
202
+ }
203
+ /**
204
+ * Maps Mnemosia's `Scope` onto AkashicForge's `{ scope, project }` filter pair.
205
+ *
206
+ * A project-level scope resolves to "global memories plus this project's" — the store's behaviour
207
+ * when `project` is given without `scope` (store.ts:661) — because that is what a session working
208
+ * in a repository should see. A project-level scope with no project is refused rather than widened
209
+ * to the whole corpus: silently reading every project would be a scope leak, and the planner is
210
+ * responsible for resolving the path before the adapter is called.
211
+ */
212
+ export function scopeFilterFor(sourceId, scope) {
213
+ if (scope.level === "global")
214
+ return { scope: "global" };
215
+ if (scope.project === null || scope.project.length === 0) {
216
+ throw new StandardAdapterError(sourceId, "schema", `${sourceId}: a project-level scope requires scope.project to be resolved`);
217
+ }
218
+ return { project: scope.project };
219
+ }