@zosmaai/pi-llm-wiki 0.10.9 → 0.11.1

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 (82) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.de.md +35 -4
  3. package/README.es.md +260 -170
  4. package/README.fr.md +35 -4
  5. package/README.hi.md +35 -4
  6. package/README.ja.md +35 -4
  7. package/README.ko.md +35 -4
  8. package/README.md +41 -12
  9. package/README.pt.md +35 -4
  10. package/README.ru.md +35 -4
  11. package/README.zh.md +260 -170
  12. package/assets/demo.gif +0 -0
  13. package/dist/extensions/llm-wiki/lib/bootstrap.js +74 -0
  14. package/dist/extensions/llm-wiki/lib/embeddings.js +401 -0
  15. package/dist/extensions/llm-wiki/lib/guardrails.js +232 -0
  16. package/dist/extensions/llm-wiki/lib/indexing.js +78 -0
  17. package/dist/extensions/llm-wiki/lib/ingest-worker.js +410 -0
  18. package/dist/extensions/llm-wiki/lib/inject.js +65 -0
  19. package/dist/extensions/llm-wiki/lib/knowledge-document.js +442 -0
  20. package/dist/extensions/llm-wiki/lib/knowledge-links.js +206 -0
  21. package/dist/extensions/llm-wiki/lib/legacy-repair.js +443 -0
  22. package/dist/extensions/llm-wiki/lib/metadata.js +505 -0
  23. package/dist/extensions/llm-wiki/lib/model-command.js +85 -0
  24. package/dist/extensions/llm-wiki/lib/observation.js +283 -0
  25. package/dist/extensions/llm-wiki/lib/recall.js +875 -0
  26. package/dist/extensions/llm-wiki/lib/retro.js +158 -0
  27. package/dist/extensions/llm-wiki/lib/runtime.js +187 -0
  28. package/dist/extensions/llm-wiki/lib/source-extractors.js +426 -0
  29. package/dist/extensions/llm-wiki/lib/source-packet.js +229 -0
  30. package/dist/extensions/llm-wiki/lib/subagent.js +41 -0
  31. package/dist/extensions/llm-wiki/lib/task-config.js +201 -0
  32. package/dist/extensions/llm-wiki/lib/tools.js +1199 -0
  33. package/dist/extensions/llm-wiki/lib/trajectories-command.js +51 -0
  34. package/dist/extensions/llm-wiki/lib/trajectory.js +467 -0
  35. package/dist/extensions/llm-wiki/lib/utils.js +353 -0
  36. package/dist/extensions/llm-wiki/lib/vault-format.js +247 -0
  37. package/dist/extensions/llm-wiki/lib/visible-status.js +31 -0
  38. package/dist/extensions/llm-wiki/lib/wiki-service.js +128 -0
  39. package/dist/mcp/exec.js +121 -0
  40. package/dist/mcp/index.js +229 -0
  41. package/dist/mcp/operations.js +130 -0
  42. package/dist/package.json +1 -0
  43. package/docs/api.md +5 -2
  44. package/docs/architecture.md +5 -2
  45. package/docs/configuration.md +25 -0
  46. package/docs/superpowers/plans/2026-08-02-okf-foundation.md +1579 -0
  47. package/docs/superpowers/plans/2026-08-03-okf-foundation-remediation.md +3005 -0
  48. package/docs/superpowers/plans/2026-08-06-authoritative-event-history-phase-1-foundation-hardening.md +937 -0
  49. package/docs/superpowers/plans/2026-08-06-okf-foundation-release-remediation.md +1174 -0
  50. package/docs/superpowers/plans/2026-08-07-synthesis-language.md +98 -0
  51. package/docs/superpowers/specs/2026-08-02-okf-foundation-design.md +593 -0
  52. package/docs/superpowers/specs/2026-08-02-okf-v0.2-interoperability-design.md +542 -0
  53. package/docs/superpowers/specs/2026-08-07-synthesis-language-design.md +94 -0
  54. package/extensions/llm-wiki/index.ts +22 -36
  55. package/extensions/llm-wiki/lib/bootstrap.ts +87 -0
  56. package/extensions/llm-wiki/lib/embeddings.ts +9 -3
  57. package/extensions/llm-wiki/lib/guardrails.ts +26 -18
  58. package/extensions/llm-wiki/lib/indexing.ts +2 -1
  59. package/extensions/llm-wiki/lib/ingest-worker.ts +304 -28
  60. package/extensions/llm-wiki/lib/knowledge-document.ts +663 -0
  61. package/extensions/llm-wiki/lib/knowledge-links.ts +282 -0
  62. package/extensions/llm-wiki/lib/legacy-repair.ts +572 -0
  63. package/extensions/llm-wiki/lib/metadata.ts +550 -128
  64. package/extensions/llm-wiki/lib/model-command.ts +0 -1
  65. package/extensions/llm-wiki/lib/observation.ts +37 -43
  66. package/extensions/llm-wiki/lib/recall.ts +61 -33
  67. package/extensions/llm-wiki/lib/retro.ts +65 -41
  68. package/extensions/llm-wiki/lib/runtime.ts +0 -3
  69. package/extensions/llm-wiki/lib/source-extractors.ts +12 -17
  70. package/extensions/llm-wiki/lib/source-packet.ts +45 -32
  71. package/extensions/llm-wiki/lib/task-config.ts +36 -0
  72. package/extensions/llm-wiki/lib/tools.ts +413 -342
  73. package/extensions/llm-wiki/lib/trajectory.ts +15 -1
  74. package/extensions/llm-wiki/lib/utils.ts +127 -131
  75. package/extensions/llm-wiki/lib/vault-format.ts +363 -0
  76. package/extensions/llm-wiki/lib/wiki-service.ts +183 -0
  77. package/mcp/exec.ts +122 -0
  78. package/mcp/index.ts +60 -250
  79. package/mcp/operations.ts +176 -0
  80. package/package.json +8 -2
  81. package/scripts/migrate-llm-wiki.js +801 -0
  82. package/skills/llm-wiki/SKILL.md +12 -8
@@ -0,0 +1,542 @@
1
+ # OKF v0.2 Interoperability Design
2
+
3
+ **Status:** Approved umbrella design; non-normative
4
+
5
+ **Date:** 2026-08-02
6
+
7
+ **Package:** `@zosmaai/pi-llm-wiki`
8
+
9
+ > This document records program-level goals and approved direction. Child specs own normative implementation requirements. If this document conflicts with a child spec, the child spec wins.
10
+
11
+ ## Specification Map
12
+
13
+ 1. [OKF Foundation](./2026-08-02-okf-foundation-design.md) — shared document model, dual-read behavior, OKF-canonical writes, vault mode, indexes, logs, and metadata integration. This is the only child currently ready for implementation planning.
14
+ 2. **OKF Interchange** — import, review, transactions, export, and explicit migration. Write and review this child spec after Foundation is planned.
15
+ 3. **OKF Intelligence** — trust-aware recall and expanded linting. Write and review this child spec after Interchange boundaries are stable.
16
+
17
+ MCP and Pi tools must call the same shared service operations defined by each child spec; no interface may implement separate business rules.
18
+
19
+ ## Summary
20
+
21
+ pi-llm-wiki will become an Open Knowledge Format (OKF) v0.2 producer and consumer without forcing existing users to migrate their vaults. The extension will read both legacy pi-llm-wiki pages and OKF pages, write new pages in an OKF-canonical form, import external bundles through a review gate, export portable bundles, and offer an explicit migration command.
22
+
23
+ The first release focuses on interoperability, provenance, trust, freshness, stronger linting, and trust-aware recall. Graph visualization, git-backed snapshots, frozen reads, advanced removal/versioning, broader document extraction, and execution of attested computations remain future work.
24
+
25
+ ## Goals
26
+
27
+ 1. Make `.llm-wiki/wiki/` a conformant OKF v0.2 knowledge bundle for new and migrated vaults.
28
+ 2. Preserve existing vault behavior without automatic migration.
29
+ 3. Safely import, review, approve, and export external OKF bundles.
30
+ 4. Preserve unknown types, producer fields, document bodies, and safe concept paths during round trips.
31
+ 5. Make provenance, verification, lifecycle, and freshness visible during recall.
32
+ 6. Extend `wiki_lint` into a deterministic OKF and wiki-health validator.
33
+ 7. Keep extension and MCP behavior equivalent.
34
+
35
+ ## Non-goals for the First Release
36
+
37
+ - Executing code referenced by an `Attested Computation` document.
38
+ - Defining a universal category taxonomy or registered type vocabulary.
39
+ - Automatically resolving semantic contradictions.
40
+ - Automatically committing wiki changes to git.
41
+ - Importing zip or tar archives. First-release imports accept directories; archive transport can be added later without changing the bundle model.
42
+ - Building a graph viewer or hosted service.
43
+ - Replacing the existing recall system with a new retrieval engine.
44
+
45
+ ## Research and Competitive Findings
46
+
47
+ ### OKF v0.2
48
+
49
+ OKF is a format, not a runtime or platform. A bundle is a directory tree of Markdown concept documents with YAML frontmatter. A document's path without `.md` is its concept ID. `index.md` and `log.md` are reserved. The only always-required concept field is `type`; consumers must tolerate unknown types and unknown producer fields.
50
+
51
+ Version 0.2 adds optional first-class metadata for:
52
+
53
+ - provenance through `sources`
54
+ - authorship through `generated`
55
+ - verification through `verified`
56
+ - lifecycle through `status`
57
+ - freshness through `stale_after`
58
+ - sanctioned, verifiable calculations through `Attested Computation`
59
+
60
+ OKF relationships use ordinary Markdown links. Directories provide hierarchy; links provide graph edges. Index files provide progressive disclosure.
61
+
62
+ ### Pi package competitors
63
+
64
+ | Package | Strong points | Main limitations relative to this design |
65
+ |---|---|---|
66
+ | `pi-okf-wiki` | Deterministic intake of conformant Markdown, broad extraction support, TF-IDF query injection, generated hierarchical indexes, collision-safe archive, deterministic removal | Targets OKF v0.1, has no layered personal/project recall, no MCP, limited YAML subset, no v0.2 trust model |
67
+ | `llm-wiki-okf` | Query-first discipline, immutable raw sources, git-native workflow, strict linting, global/project tiers, source tracing | Skill and Python-script workflow rather than a Pi-native extension; no semantic retrieval; strict custom schema exceeds base OKF requirements |
68
+ | `@d1g1tlprim8/pi-okf-wiki` | Atomic single-file writes, git commits, graph checks, tag harmonization | Small skill utility set, custom required schema, no advanced retrieval, no safe bundle exchange workflow |
69
+
70
+ ### Broader projects
71
+
72
+ - Google's reference implementation demonstrates two-pass enrichment, hierarchical indexes, sample bundles, and a self-contained graph viewer.
73
+ - `llm-wiki-compiler` demonstrates review-gated import, trusted import, preservation of foreign fields and paths, and OKF export.
74
+ - OKF Harness demonstrates bounded evidence retrieval, deterministic JSON tool output, workspace checks, and a local graph report.
75
+ - `wiki-as-an-mcp` demonstrates separate read/manage capabilities, frozen git-backed reads, snapshots, and multi-topic isolation.
76
+
77
+ The competitive advantage for pi-llm-wiki is combining OKF interoperability with its existing immutable source packets, layered personal/project recall, background ingestion, hybrid lexical/semantic retrieval, guardrails, observations, retrospectives, trajectories, and MCP access.
78
+
79
+ ## Design Decisions
80
+
81
+ - Deliver both OKF interoperability and Pi-native wiki advantages in phases.
82
+ - Use dual-read, OKF-canonical write behavior.
83
+ - Never force automatic migration.
84
+ - Stage untrusted imports by default; support dry-run and explicit trusted mode.
85
+ - Keep recall relevance-first. Trust and freshness may rerank relevant candidates and add warnings, but never silently hide knowledge.
86
+ - Keep `category`, `domain`, `aliases`, and `recall_triggers` as optional producer extensions.
87
+ - Preserve and validate Attested Computation metadata but do not execute it.
88
+ - Restrict automatic lint fixes to deterministic repairs; never fabricate knowledge pages.
89
+
90
+ ## Vault Architecture
91
+
92
+ ```text
93
+ .llm-wiki/
94
+ ├── config.json
95
+ ├── WIKI_SCHEMA.md
96
+ ├── wiki/ # canonical OKF bundle
97
+ │ ├── index.md # okf_version: "0.2"
98
+ │ ├── log.md
99
+ │ ├── sources/
100
+ │ ├── concepts/
101
+ │ ├── entities/
102
+ │ ├── syntheses/
103
+ │ ├── analyses/
104
+ │ └── ... # requirements, skills, cases, foreign paths
105
+ ├── raw/ # immutable pi-llm-wiki source packets
106
+ ├── imports/ # extension-owned import staging and audit records
107
+ │ ├── pending/<import-id>/
108
+ │ └── applied/<import-id>/manifest.json
109
+ ├── meta/ # durable local events + generated internal projections
110
+ └── outputs/ # reports and explicit exports
111
+ ```
112
+
113
+ `.llm-wiki/wiki/` is the distributable OKF bundle. Product-specific raw packets, staging state, and generated search metadata remain outside it.
114
+
115
+ `meta/events.jsonl` is durable local pi-llm-wiki state but is not part of the base OKF bundle. A full-vault backup preserves it; an OKF-only export does not. The exported `wiki/log.md` is therefore a readable history snapshot, not a lossless or resumable event source.
116
+
117
+ Source pages inside the bundle provide stable provenance targets for canonical pages. Raw packet paths may remain pi-llm-wiki extension metadata on source pages, but portable provenance references should resolve to source pages or external resources rather than escaping the bundle.
118
+
119
+ `imports/**` is extension-owned and protected by the same tool-call guardrail model as `raw/**` and `meta/**`. Pending imports never participate in recall or metadata indexing.
120
+
121
+ ## Knowledge Model
122
+
123
+ ### Terminology
124
+
125
+ In OKF, every non-reserved Markdown knowledge document is a concept. In the pi-llm-wiki profile, `type: concept` remains one specific page class beside `entity`, `source`, `analysis`, and other existing classes.
126
+
127
+ ### Standard and profile fields
128
+
129
+ | Field | Role |
130
+ |---|---|
131
+ | `type` | Primary semantic kind; only always-required OKF field |
132
+ | File path | Stable concept identity and broad hierarchy |
133
+ | `title` | Human-readable display name |
134
+ | `description` | One-sentence search and index summary |
135
+ | `resource` | Canonical URI for the described asset, when applicable |
136
+ | `tags` | Cross-cutting labels |
137
+ | `sources` | Structured provenance and source credibility signals |
138
+ | `generated` | Who or what produced the current content and when |
139
+ | `verified` | Independent verification events |
140
+ | `status` | `draft`, `stable`, or `deprecated`; absent means stable |
141
+ | `stale_after` | Absolute date after which content is stale |
142
+ | `category` | Optional pi-llm-wiki subtype such as `architecture`, `person`, or `library` |
143
+ | `domain` | Optional knowledge area such as `security` or `ai-engineering` |
144
+ | `aliases` | Optional alternate names |
145
+ | `recall_triggers` | Optional phrases likely to be used when retrieving the page |
146
+
147
+ `category`, `domain`, `aliases`, and `recall_triggers` remain top-level producer extensions. They are optional, have no central vocabulary, and must be preserved by round-tripping consumers. The profile does not add subjective credibility or confidence scores; trust is derived from objective OKF signals.
148
+
149
+ Existing type values remain valid:
150
+
151
+ - `source`
152
+ - `entity`
153
+ - `concept`
154
+ - `synthesis`
155
+ - `analysis`
156
+ - `requirement`
157
+ - `trajectory`
158
+ - `case`
159
+ - `skill`
160
+
161
+ Unknown imported types remain valid and are treated as generic concepts by code that lacks type-specific behavior.
162
+
163
+ ### Profile conventions
164
+
165
+ The root index declares only the base format:
166
+
167
+ ```yaml
168
+ ---
169
+ okf_version: "0.2"
170
+ ---
171
+ ```
172
+
173
+ OKF v0.2 is ambiguous about additional root-index frontmatter keys, so the bundle does not claim `profile: pi-llm-wiki/1` there. The package documentation still defines pi-llm-wiki extension fields and page-type conventions, but plain OKF bundles do not need them and imported documents never require them. A portable profile-discovery mechanism is deferred until OKF specifies one or a later child spec defines a conformant approach.
174
+
175
+ ### Example
176
+
177
+ ```markdown
178
+ ---
179
+ type: concept
180
+ title: Retrieval-Augmented Generation
181
+ description: Grounds generation using retrieved evidence.
182
+ category: architecture
183
+ domain: ai-engineering
184
+ tags: [rag, retrieval]
185
+ aliases: [RAG]
186
+ recall_triggers: [grounded generation, document retrieval]
187
+ status: stable
188
+ generated:
189
+ by: pi-llm-wiki/model
190
+ at: 2026-08-02T10:00:00Z
191
+ sources:
192
+ - id: SRC-2026-08-02-001
193
+ resource: /sources/SRC-2026-08-02-001.md
194
+ ---
195
+
196
+ # Retrieval-Augmented Generation
197
+
198
+ RAG retrieves evidence before generation.[^SRC-2026-08-02-001]
199
+
200
+ [^SRC-2026-08-02-001]: Source summary
201
+ ```
202
+
203
+ ## Shared Document Layer
204
+
205
+ A small shared format module becomes the only parser and serializer used by ingestion, metadata generation, recall, lint, migration, import, and export.
206
+
207
+ Conceptual API:
208
+
209
+ - `parseKnowledgeDocument(content, path)`
210
+ - `serializeKnowledgeDocument(document)`
211
+ - `parseBundleIndex(content)`
212
+ - `validateKnowledgeDocument(document)`
213
+ - `validateOkfBundle(bundle)`
214
+ - `resolveKnowledgeLinks(document, bundle)`
215
+ - `convertLegacyDocument(document)`
216
+
217
+ The internal model separates standard OKF fields, pi-llm-wiki extension fields, unknown producer fields, and the Markdown body. Unknown fields must survive semantic round trips. Exact YAML formatting, comments, quoting style, and key order are not guaranteed to survive migration or serialization.
218
+
219
+ ### YAML handling
220
+
221
+ The current dependency-free parser cannot represent OKF v0.2 nested mappings and lists. The implementation will use a maintained YAML parser rather than grow a bespoke general YAML implementation.
222
+
223
+ Security requirements:
224
+
225
+ - disable aliases and alias expansion
226
+ - disable custom executable tags
227
+ - reject multiple YAML documents
228
+ - cap frontmatter bytes and nesting depth
229
+ - return structured parse errors rather than throwing through tool boundaries
230
+ - preserve unknown ordinary mappings, lists, and scalar values
231
+
232
+ Parsing is permissive; conformance validation is separate. A parseable document with unknown fields or type is accepted. A malformed document produces a file- and field-specific validation result.
233
+
234
+ ## Link Model
235
+
236
+ New pages use ordinary Markdown links, preferably bundle-root-relative links such as `/concepts/retrieval.md`. Legacy `[[wikilinks]]` remain readable during the compatibility period.
237
+
238
+ Metadata and linting resolve both forms:
239
+
240
+ - standard Markdown links between concept documents
241
+ - bundle-root-relative and relative paths
242
+ - legacy folder-qualified wikilinks
243
+ - body footnotes whose labels join to `sources[].id`
244
+
245
+ Migration converts resolvable wikilinks into Markdown links while preserving display labels. Unresolvable links remain unchanged and are reported; migration must not guess a target.
246
+
247
+ ## Generated Indexes and Logs
248
+
249
+ The metadata rebuild writes:
250
+
251
+ - a root `wiki/index.md`
252
+ - one `index.md` in each directory containing concepts directly or transitively
253
+ - a root `wiki/log.md`
254
+ - existing machine-oriented files under `meta/`
255
+
256
+ Each directory index lists only direct concepts and immediate child directories. This preserves progressive disclosure and avoids loading a recursive catalog into context.
257
+
258
+ Reserved `index.md` and `log.md` files are not concept documents and are excluded from ordinary concept recall. Imported reserved files are validated and recorded in the import manifest, but the live bundle regenerates its own indexes and log. Foreign concept paths and document-level metadata are preserved; arbitrary foreign index prose is not merged into the live generated index. Before Interchange implementation, its normative child spec must define whether an imported `log.md` is archived, retained as a separate historical baseline, or replaced when a new local event stream begins. It must not imply that Markdown prose can reconstruct the originating JSONL stream.
259
+
260
+ ## Import Design
261
+
262
+ ### Tool
263
+
264
+ `wiki_okf_import` accepts:
265
+
266
+ - a local directory path
267
+ - `dry_run`, defaulting to `true`
268
+ - `trusted`, defaulting to `false`
269
+ - collision policy, defaulting to `error`
270
+
271
+ First-release directory imports avoid archive extraction and decompression risks. A future archive adapter can feed the same validated staging pipeline.
272
+
273
+ ### Flow
274
+
275
+ ```text
276
+ external directory
277
+ → bounded path and filesystem scan
278
+ → parse all concept and reserved documents
279
+ → validate OKF version and conformance
280
+ → calculate content hashes and collision report
281
+ → dry-run report OR immutable staged copy
282
+ → explicit review
283
+ → recoverable live-wiki transaction
284
+ → metadata rebuild
285
+ ```
286
+
287
+ ### Safety constraints
288
+
289
+ - Reject paths that escape the selected bundle root.
290
+ - Reject symlinks and non-regular files in the first release.
291
+ - Cap document count, individual file size, total bytes, frontmatter bytes, and nesting depth with conservative defaults.
292
+ - Ignore non-Markdown files unless a future adapter explicitly supports them.
293
+ - Never overwrite a live concept silently.
294
+ - Treat identical path and content hash as a no-op.
295
+ - Treat same path with different content as a conflict.
296
+ - Validate trusted imports and enforce collision rules; trusted means bypassing review, not bypassing safety.
297
+ - Copy staged bytes and hashes so approval applies to the reviewed content even if the source directory later changes.
298
+
299
+ ### Review
300
+
301
+ `wiki_okf_review` supports listing imports, showing a manifest and candidate diff, approving selected or all non-conflicting documents, rejecting an import, and explicitly resolving collisions as `skip` or `replace`.
302
+
303
+ `replace` requires an explicit choice and records the replaced content in the transaction backup. Rejected imports are removed only through this tool.
304
+
305
+ Applied import manifests retain source bundle metadata, file hashes, decisions, and timestamps under `imports/applied/`. They provide auditability but do not enter recall.
306
+
307
+ ### Transaction behavior
308
+
309
+ Cross-file filesystem writes cannot be truly atomic. The implementation therefore uses:
310
+
311
+ 1. validation before mutation
312
+ 2. temporary files for each changed document
313
+ 3. a transaction journal listing old and new hashes
314
+ 4. backups of replaced files
315
+ 5. atomic rename for each individual file
316
+ 6. startup/tool-entry recovery when an incomplete journal exists
317
+ 7. metadata rebuild only after the transaction commits
318
+
319
+ Any normal error rolls back changed files. An interrupted process leaves a journal that can deterministically finish or roll back on the next operation.
320
+
321
+ ## Export Design
322
+
323
+ `wiki_okf_export` writes to a new or empty output directory and refuses to overwrite an existing non-empty destination.
324
+
325
+ Flow:
326
+
327
+ ```text
328
+ live legacy + OKF pages
329
+ → shared parser
330
+ → in-memory legacy conversion
331
+ → full bundle validation
332
+ → deterministic hierarchical indexes and log
333
+ → portable OKF v0.2 output
334
+ → export report
335
+ ```
336
+
337
+ Export never mutates the live vault. It preserves safe concept paths, bodies, unknown document fields, standard metadata, and pi-llm-wiki extension fields. Legacy pages are converted in memory. Generated `meta/**`, pending imports, source packet internals, and embeddings are not exported.
338
+
339
+ Because `meta/events.jsonl` is excluded, exported `log.md` is a deterministic snapshot rather than a resumable event ledger. Export must use only bundle-safe projected fields. Portable event continuity or a machine-readable event sidecar requires a separately reviewed Interchange decision and is not implied by Foundation.
340
+
341
+ Raw evidence remains represented through portable source concept pages and their provenance links. A later option may package selected original artifacts under an OKF `references/` convention.
342
+
343
+ ## Migration Design
344
+
345
+ `wiki_okf_migrate` defaults to dry-run. Applying migration requires an explicit `apply` flag.
346
+
347
+ Migration performs these deterministic conversions:
348
+
349
+ - add or update root OKF version metadata
350
+ - generate hierarchical indexes and root log
351
+ - convert resolvable wikilinks to Markdown links
352
+ - convert scalar legacy source references into structured `sources` entries
353
+ - preserve existing `type`, `category`, `domain`, aliases, recall triggers, timestamps, bodies, and unknown fields
354
+ - derive `description` from an existing concise summary only when no description exists; preserve the original summary field
355
+ - leave optional `generated` and `verified` absent when authorship or verification is unknown rather than inventing trust
356
+
357
+ Dry-run reports every changed file, unresolved link, invalid source reference, and conformance issue. Apply creates a dated backup of changed files, writes through the transaction journal, validates the result, and rebuilds metadata. Re-running migration after success is a no-op.
358
+
359
+ ## Recall and Trust
360
+
361
+ Existing lexical, chunk-level, pseudo-relevance-feedback, and optional semantic retrieval remain the candidate generators. Trust metadata does not create candidates.
362
+
363
+ For relevant candidates, recall computes and displays:
364
+
365
+ - human-reviewed
366
+ - machine-confirmed
367
+ - unverified
368
+ - verification-outdated when the latest verification predates the current generation timestamp
369
+ - stale when `today >= stale_after`
370
+ - deprecated when `status: deprecated`
371
+
372
+ A bounded trust factor may adjust a relevant candidate's base score within `0.90` to `1.10`:
373
+
374
+ - human-reviewed: positive adjustment
375
+ - machine-confirmed: smaller positive adjustment
376
+ - unverified: neutral
377
+ - stale: negative adjustment
378
+ - deprecated: larger negative adjustment
379
+ - verification-outdated: no verification boost and a warning
380
+
381
+ The final combined factor is clamped to the stated range. Tests must prove that trust cannot introduce a zero-relevance candidate or remove a relevant candidate from the result set solely because it is unverified, stale, or deprecated.
382
+
383
+ Recall output includes trust state, lifecycle warnings, and source links. Two-stage links-first behavior remains unchanged.
384
+
385
+ ## Lint Design
386
+
387
+ `wiki_lint` becomes the single health and conformance entry point. It reports machine-readable findings with severity, stable code, file path, field or line where available, and human guidance.
388
+
389
+ Checks include:
390
+
391
+ - OKF v0.2 document and bundle conformance
392
+ - missing or empty `type`
393
+ - invalid nested `sources`, `generated`, `verified`, lifecycle, or computation fields
394
+ - invalid actor and timestamp shapes
395
+ - stale content and outdated verification
396
+ - body footnote IDs missing from `sources[].id`
397
+ - duplicate source IDs within a document
398
+ - escaping or unsafe path-valued fields
399
+ - broken Markdown links and legacy wikilinks
400
+ - missing or stale directory indexes
401
+ - malformed logs
402
+ - duplicate concept paths and import collisions
403
+ - existing orphan, gap, and explicit contradiction-marker checks
404
+
405
+ Unknown types, absent optional trust metadata, and unknown extension fields are not errors.
406
+
407
+ Automatic fixes are limited to deterministic operations:
408
+
409
+ - regenerate indexes and log
410
+ - rebuild registry and backlinks
411
+ - normalize metadata shapes when conversion is unambiguous
412
+
413
+ Lint no longer auto-creates stub concept pages. Missing knowledge remains a reported gap until a human or ingestion flow supplies evidence.
414
+
415
+ ## Error Model
416
+
417
+ New OKF operations return stable result codes rather than relying on prose. Representative groups:
418
+
419
+ - `parse_invalid_frontmatter`
420
+ - `conformance_missing_type`
421
+ - `conformance_invalid_reserved_file`
422
+ - `path_escape`
423
+ - `path_symlink`
424
+ - `limit_file_count`
425
+ - `limit_file_size`
426
+ - `limit_total_bytes`
427
+ - `collision_changed`
428
+ - `transaction_incomplete`
429
+ - `transaction_rollback_failed`
430
+ - `migration_unresolved_link`
431
+
432
+ Tool responses provide a concise summary and store full reports under `outputs/` or import manifests. A failed validation, import, export, or migration does not leave partially indexed knowledge.
433
+
434
+ ## Tool and MCP Surface
435
+
436
+ New Pi tools:
437
+
438
+ - `wiki_okf_import`
439
+ - `wiki_okf_review`
440
+ - `wiki_okf_export`
441
+ - `wiki_okf_migrate`
442
+
443
+ Existing tools updated:
444
+
445
+ - `wiki_lint`
446
+ - `wiki_recall`
447
+ - `wiki_search`
448
+ - `wiki_status`
449
+ - `wiki_rebuild_meta`
450
+ - all page-producing ingestion, observation, retro, requirement, and trajectory flows
451
+
452
+ The MCP server exposes equivalent OKF operations and structured result codes. Slash commands may wrap tools for interactive use, but business logic remains in shared library functions rather than command handlers.
453
+
454
+ ## Testing Strategy
455
+
456
+ ### Unit tests
457
+
458
+ - nested OKF v0.2 frontmatter parsing and serialization
459
+ - alias/custom-tag/multiple-document rejection
460
+ - preservation of unknown mappings, lists, and scalar fields
461
+ - Markdown and legacy link extraction/resolution
462
+ - trust-tier and freshness derivation
463
+ - deterministic index and log generation
464
+ - legacy source and link conversion
465
+
466
+ ### Fixture tests
467
+
468
+ - conformant Google/reference-style v0.2 bundles
469
+ - current pi-llm-wiki legacy vaults
470
+ - unknown foreign types and producer extensions
471
+ - Attested Computation documents
472
+ - malformed frontmatter and reserved files
473
+ - path traversal, symlink, oversized file, excessive file count, deep nesting, and collision cases
474
+
475
+ ### Integration tests
476
+
477
+ - dry-run import makes no writes
478
+ - staged content is independent of later source-directory changes
479
+ - approval indexes content only after commit
480
+ - rejection removes staged content and never affects live recall
481
+ - trusted import still validates and detects collisions
482
+ - export converts legacy pages without modifying them
483
+ - migration apply is idempotent and recoverable
484
+ - simulated interruption recovers or rolls back through the journal
485
+ - extension and MCP produce equivalent structured outcomes
486
+
487
+ ### Recall tests
488
+
489
+ - existing lexical, chunk, and semantic tests remain green
490
+ - human-reviewed relevant pages receive only a bounded boost
491
+ - stale/deprecated relevant pages remain returned with warnings
492
+ - unverified pages are never silently hidden
493
+ - outdated verification is detected from timestamps
494
+ - pending imports never appear in recall
495
+
496
+ ### Release gates
497
+
498
+ - Reference/sample OKF v0.2 bundles validate.
499
+ - Parse/serialize preserves document bodies, paths, unknown field values, and nested metadata semantically.
500
+ - Existing vaults work without migration.
501
+ - Migration dry-run is deterministic and apply is idempotent.
502
+ - Invalid imports leave live concept files unchanged.
503
+ - Security fixtures fail with expected stable codes.
504
+ - Existing package tests, typecheck, lint, and coverage gates pass.
505
+ - Pi extension and MCP operations remain behaviorally aligned.
506
+
507
+ ## Rollout
508
+
509
+ 1. Introduce shared document model and hardened YAML parsing without changing writes.
510
+ 2. Switch all readers to dual legacy/OKF support.
511
+ 3. Switch new page producers to OKF-canonical output.
512
+ 4. Generate hierarchical bundle indexes and expand lint.
513
+ 5. Add safe import, review staging, and export.
514
+ 6. Add explicit migration.
515
+ 7. Add trust/freshness-aware recall.
516
+ 8. Publish profile documentation, migration guidance, and a competitor feature matrix.
517
+
518
+ Each stage is independently releasable. No stage forces migration.
519
+
520
+ ## Future Roadmap
521
+
522
+ 1. Self-contained graph viewer with backlinks and filters.
523
+ 2. Git snapshots, frozen read versions, rollback, and separate read/manage capabilities.
524
+ 3. Safe concept removal, deprecation workflows, and version history.
525
+ 4. DOCX, PPTX, XLSX, EPUB, image, and other broader extraction adapters.
526
+ 5. Archive import/export adapters with decompression-bomb protections.
527
+ 6. Bundle registry and multi-topic isolation.
528
+ 7. Optional Attested Computation executors and deterministic attesters behind explicit security boundaries.
529
+ 8. Retrieval benchmark suite, competitive evaluations, and larger-scale indexing.
530
+ 9. Versioned evolution of the `pi-llm-wiki/1` profile.
531
+
532
+ ## Sources
533
+
534
+ - [Google Cloud: How the Open Knowledge Format can improve data sharing](https://cloud.google.com/blog/products/data-analytics/how-the-open-knowledge-format-can-improve-data-sharing)
535
+ - [Open Knowledge Format v0.2 specification](https://github.com/GoogleCloudPlatform/knowledge-catalog/blob/main/okf/SPEC.md)
536
+ - [Google knowledge-catalog OKF reference implementation](https://github.com/GoogleCloudPlatform/knowledge-catalog/tree/main/okf)
537
+ - [Pi package: pi-okf-wiki](https://pi.dev/packages/pi-okf-wiki)
538
+ - [Pi package: llm-wiki-okf](https://pi.dev/packages/llm-wiki-okf)
539
+ - [Pi package: @d1g1tlprim8/pi-okf-wiki](https://pi.dev/packages/@d1g1tlprim8/pi-okf-wiki)
540
+ - [llm-wiki-compiler OKF round-trip guide](https://github.com/atomicstrata/llm-wiki-compiler/blob/main/docs/guides/open-knowledge-format.mdx)
541
+ - [OKF Harness](https://github.com/pumblus/okf-harness)
542
+ - [wiki-as-an-mcp](https://github.com/taikunudel/wiki-as-an-mcp)
@@ -0,0 +1,94 @@
1
+ # Configurable Language for Background Ingest Synthesis
2
+
3
+ **Issue:** [#124](https://github.com/zosmaai/pi-llm-wiki/issues/124)
4
+ **Date:** 2026-08-07
5
+ **Status:** Approved
6
+
7
+ ## Problem
8
+
9
+ Background ingest synthesis (`wiki_ingest(background=true)`) always produces English narrative content, regardless of the vault's authoring language. The background sub-agent does not inherit language instructions from `AGENTS.md`, `APPEND_SYSTEM.md`, `WIKI_SCHEMA.md`, or the main session prompt.
10
+
11
+ Workarounds are inadequate:
12
+ - `background=false` returns extracted content to the main session, consuming context window.
13
+ - Manual translation after ingest is error-prone and defeats the purpose of background synthesis.
14
+
15
+ ## Goal
16
+
17
+ Allow vault owners to configure the narrative language used by background ingest synthesis, without copying the main conversation context into the background worker.
18
+
19
+ ## Design
20
+
21
+ ### Configuration
22
+
23
+ - **Field:** `synthesisLanguage`
24
+ - **Type:** BCP 47 language tag (e.g., `"ru"`, `"fr"`, `"en"`)
25
+ - **Location:** `.pi/settings.json` under the `llm-wiki` namespace
26
+ - **Default:** undefined (no change to current behavior)
27
+
28
+ Example:
29
+ ```json
30
+ {
31
+ "llm-wiki": {
32
+ "synthesisLanguage": "ru"
33
+ }
34
+ }
35
+ ```
36
+
37
+ This matches the existing pattern used by `taskModel`, `trajectories`, `notices`, etc.
38
+
39
+ ### System Prompt Modification
40
+
41
+ When `synthesisLanguage` is configured, the background ingest worker appends a fixed instruction block to its system prompt (`INGEST_SYSTEM` in `ingest-worker.ts`):
42
+
43
+ > Write all generated content in {language}, including titles, headings, summaries, descriptions, and concept/entity names. Only preserve code, API names, file paths, commands, exact technical identifiers, and verbatim quotations in their original form.
44
+
45
+ The BCP 47 tag is validated using `Intl.getCanonicalLocales()` and canonicalized before use. Invalid or suspicious tags (containing newlines, quotes, or instruction-like words) are rejected.
46
+
47
+ Additionally, the page renderer translates fixed headings (Summary, Key Takeaways, etc.) into the configured language for supported languages (Russian, French, German, Japanese). Unsupported languages fall back to English headings.
48
+
49
+ ### Scope
50
+
51
+ The language setting applies to LLM-generated narrative fields:
52
+ - Page titles
53
+ - Headings
54
+ - Summaries
55
+ - Descriptions
56
+ - Key takeaways
57
+ - Conclusions
58
+ - Entity and concept descriptions
59
+ - Synthesis and analysis text
60
+
61
+ It does NOT apply to:
62
+ - Raw captured source content (`extracted.md`)
63
+ - Code blocks
64
+ - Technical identifiers (API names, paths, commands, field names)
65
+ - Source quotations
66
+
67
+ ### Implementation Changes
68
+
69
+ 1. **`lib/task-config.ts`**
70
+ - Add `synthesisLanguage?: string` to `TaskConfig` interface
71
+ - Parse in `readNamespacedConfig` as a non-empty trimmed string
72
+
73
+ 2. **`lib/ingest-worker.ts`**
74
+ - Add `synthesisLanguage?: string` to `RunIngestSynthesisArgs`
75
+ - In `runIngestSynthesis`, conditionally append the language instruction to `INGEST_SYSTEM` when `synthesisLanguage` is set
76
+
77
+ 3. **`lib/tools.ts`** (wiki_ingest tool)
78
+ - Pass `runtime.config.synthesisLanguage` into `runIngestSynthesis` args
79
+
80
+ ### Acceptance Criteria
81
+
82
+ - [ ] Background ingest generates synthesis in the configured language
83
+ - [ ] Configuration works with `wiki_ingest(background=true)`
84
+ - [ ] Main conversation context is NOT copied into the background worker
85
+ - [ ] Existing behavior unchanged when no language is configured
86
+ - [ ] Technical identifiers and source quotations remain in their original language
87
+ - [ ] Generated titles, headings, summaries, and conclusions consistently follow the configured language
88
+
89
+ ## Out of Scope
90
+
91
+ - Per-source language override
92
+ - Automatic language detection from source content
93
+ - User-editable prompt template (fixed wording for now)
94
+ - Language setting for other background tasks (embeddings, topic inference) — can be added later if needed