@crewhaus/tool-wiki 0.3.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/README.md ADDED
@@ -0,0 +1,70 @@
1
+ # @crewhaus/tool-wiki
2
+
3
+ v0.3.0 Goal 2 (design §3.2): the **thredz-identical wiki tool vocabulary**
4
+ over [`@crewhaus/wiki-store`](../wiki-store) — exactly thredz-mcp's tool
5
+ names and input schemas, so one skill vocabulary and one set of permission
6
+ rules work on both the local and Thredz backends (a parity test pins the
7
+ name set).
8
+
9
+ ```ts
10
+ import { createWikiTools } from "@crewhaus/tool-wiki";
11
+ import { defaultCatalog } from "@crewhaus/tool-catalog";
12
+
13
+ const bundle = createWikiTools({
14
+ specName: "support-bot",
15
+ requireSources: true, // learning-mode write governance
16
+ appendEvent: (e) => eventLog.append(e), // wiki_write event kind
17
+ logGap: (gap) => planStore.logGap(gap), // wired by the composition root
18
+ });
19
+ for (const tool of bundle.all) defaultCatalog.register(tool);
20
+ ```
21
+
22
+ ## The tool table
23
+
24
+ | Tool | Flags | What it does |
25
+ | --- | --- | --- |
26
+ | `wiki_recall` | readOnly | PRIMARY RECALL: hybrid top-k WITH bodies + one-hop link expansion |
27
+ | `wiki_semantic_search` | readOnly | Embedding-only ranking; degrades to keyword search (with a note) when no embedder is configured |
28
+ | `wiki_search` | readOnly | BM25 keyword search — exact terms, names, numbers |
29
+ | `wiki_get` | readOnly | One article in full (or `concise`) |
30
+ | `wiki_write` | destructive + **requireJustification** | Versioned upsert by slug — supersede, never delete |
31
+ | `wiki_list` | readOnly | REFLECT entry point — stalest first by default (thredz sort=updated asc) |
32
+ | `wiki_related` | readOnly | Tag/link/similarity neighbors for dedup + contradiction checks |
33
+ | `wiki_set_signals` | destructive + **requireJustification** | verified / confidenceScore promotion+demotion |
34
+ | `wiki_stats` | readOnly | Corpus health |
35
+ | `log_knowledge_gap` | destructive (sideEffect audit-and-allow, **no** justification) | Record what the expert could not answer |
36
+
37
+ All tools are `scope: "internal"` — local files, no network.
38
+
39
+ ## Pillar 3 — the `memory` TrustOrigin
40
+
41
+ Article bodies returned by the read tools are classified via
42
+ `boundary-classifier` at the new **`"memory"` origin** (default policy:
43
+ block tier, like `"skill"`) before reaching the model — an article written
44
+ in an earlier session may have absorbed attacker text, and recall re-injects
45
+ it across a session boundary. Malicious verdicts return the redaction notice
46
+ instead of the body; non-blocked bodies are `tagContent`-ed into
47
+ `RunContext.dataLineage` under `"memory"` (the skills-registry two-site
48
+ pattern) so the egress fabric can attribute a later exfiltration to the
49
+ memory boundary.
50
+
51
+ ## Write-path governance
52
+
53
+ With `{ requireSources: true }` (implied by `learning.enabled`, PR 17),
54
+ `wiki_write` deterministically rejects any body without a `## Sources`
55
+ heading — no citation, no write. Sources listed under that heading are also
56
+ extracted into the article's frontmatter `sources[]`.
57
+
58
+ ## Concurrency + parity notes
59
+
60
+ `wiki_write` performs the same client-side upsert as thredz-mcp: it reads
61
+ the current version and passes it as the store's `expectedVersion`; a
62
+ concurrent editor surfaces as the thredz-parity `stale_article_version`
63
+ remediation ("re-read it with wiki_get, then re-apply your edit").
64
+ `visibility` and `category` are accepted for schema parity — the local wiki
65
+ is private by construction, and categories are a Thredz-side concept.
66
+
67
+ Without an injected `logGap`, `log_knowledge_gap` writes a draft
68
+ `gap-<topic>` article under the reserved `gaps/` tag (plus
69
+ `priority:<p>`), so the STUDY loop can find gaps with
70
+ `wiki_list tags=gaps/` even standalone.
@@ -0,0 +1,70 @@
1
+ import type { WikiWriteEventPayload } from "@crewhaus/event-log";
2
+ import type { RegisteredTool } from "@crewhaus/tool-catalog";
3
+ import { type WikiEmbedder, type WikiStore } from "@crewhaus/wiki-store";
4
+ /**
5
+ * The thredz-mcp wiki tool names, pinned (server.ts TOOLS, v0.2.0). The
6
+ * parity test asserts the registered set equals this list EXACTLY — a
7
+ * drifted name would silently fork the skill vocabulary between backends.
8
+ */
9
+ export declare const THREDZ_WIKI_TOOL_NAMES: readonly ["wiki_recall", "wiki_semantic_search", "wiki_search", "wiki_get", "wiki_write", "wiki_list", "wiki_related", "wiki_set_signals", "wiki_stats", "log_knowledge_gap"];
10
+ /** The reserved tag marking standalone-logged knowledge gaps (§3.2). */
11
+ export declare const GAPS_TAG = "gaps/";
12
+ /** A recorded knowledge gap — the `logGap` callback's input. */
13
+ export type KnowledgeGap = {
14
+ readonly topic: string;
15
+ readonly detail?: string;
16
+ readonly tags: readonly string[];
17
+ readonly priority: "low" | "medium" | "high";
18
+ };
19
+ /** The `wiki_write` event emitted through the injected append seam. */
20
+ export type WikiEvent = {
21
+ readonly kind: "wiki_write";
22
+ readonly payload: WikiWriteEventPayload;
23
+ };
24
+ /**
25
+ * The injected append seam: typically wired to the session event log's
26
+ * `append` (and/or the trace bus) by the emitter or memory-service. Should
27
+ * not throw; a throwing sink fails the tool call loudly rather than
28
+ * dropping audit events silently.
29
+ */
30
+ export type AppendWikiEvent = (event: WikiEvent) => void | Promise<void>;
31
+ export type CreateWikiToolsOptions = {
32
+ readonly specName: string;
33
+ readonly rootDir?: string;
34
+ /** Inject a custom store implementation for tests. */
35
+ readonly store?: WikiStore;
36
+ /** Enables hybrid recall + real `wiki_semantic_search` on the default store. */
37
+ readonly embedder?: WikiEmbedder;
38
+ /**
39
+ * Learning-mode write governance (design §3.3): when true, `wiki_write`
40
+ * deterministically rejects bodies without a `## Sources` heading.
41
+ */
42
+ readonly requireSources?: boolean;
43
+ /** Gap sink — the composition root wires this to the plan store. Absent →
44
+ * the standalone wiki fallback under the `gaps/` tag. */
45
+ readonly logGap?: (gap: KnowledgeGap) => string | Promise<string>;
46
+ /** Event-log append seam — see `AppendWikiEvent`. */
47
+ readonly appendEvent?: AppendWikiEvent;
48
+ readonly now?: () => Date;
49
+ };
50
+ export type WikiToolBundle = {
51
+ readonly recall: RegisteredTool;
52
+ readonly semanticSearch: RegisteredTool;
53
+ readonly search: RegisteredTool;
54
+ readonly get: RegisteredTool;
55
+ readonly write: RegisteredTool;
56
+ readonly list: RegisteredTool;
57
+ readonly related: RegisteredTool;
58
+ readonly setSignals: RegisteredTool;
59
+ readonly stats: RegisteredTool;
60
+ readonly logKnowledgeGap: RegisteredTool;
61
+ /** Every tool above, registration-ready. */
62
+ readonly all: readonly RegisteredTool[];
63
+ /** Exposed for direct inspection (tests, CLI verbs). */
64
+ readonly store: WikiStore;
65
+ };
66
+ /** The learning-mode gate: a `## Sources` heading anywhere in the body. */
67
+ export declare function hasSourcesHeading(body: string): boolean;
68
+ /** Bullet/plain lines under the `## Sources` heading (frontmatter sources[]). */
69
+ export declare function extractSources(body: string, cap?: number): string[];
70
+ export declare function createWikiTools(opts: CreateWikiToolsOptions): WikiToolBundle;
package/dist/index.js ADDED
@@ -0,0 +1,593 @@
1
+ /**
2
+ * v0.3.0 Goal 2 — `tool-wiki` (design §3.2, PR 9).
3
+ *
4
+ * RegisteredTools over `@crewhaus/wiki-store` carrying EXACTLY the
5
+ * thredz-mcp wiki tool vocabulary — names and input schemas — so one skill
6
+ * vocabulary, one set of permission rules, and one `tool_config` surface
7
+ * work identically on the local and Thredz backends (when `backend:
8
+ * thredz`, these local tools are not registered and the synthesized Thredz
9
+ * MCP server's tools alias onto the same names):
10
+ *
11
+ * wiki_recall readOnly — PRIMARY RECALL, hybrid + one-hop
12
+ * wiki_semantic_search readOnly — embedding-only ranking; degrades
13
+ * to keyword search with a note when
14
+ * no embedder is configured (the same
15
+ * degradation Thredz applies on
16
+ * keyword-only plans)
17
+ * wiki_search readOnly — BM25 keyword search
18
+ * wiki_get readOnly — one article in full
19
+ * wiki_write destructive + requireJustification — versioned
20
+ * upsert (supersede, never delete)
21
+ * wiki_list readOnly — REFLECT entry point (stale-first
22
+ * by default: sort updated asc)
23
+ * wiki_related readOnly — dedup/contradiction candidates
24
+ * wiki_set_signals destructive + requireJustification — verified /
25
+ * confidence promotion+demotion
26
+ * wiki_stats readOnly — corpus health
27
+ * log_knowledge_gap destructive (sideEffect audit-and-allow — NO
28
+ * justification; logging a gap is the
29
+ * honest low-friction path, §7.4)
30
+ *
31
+ * All tools are `scope: "internal"` — local files, no network.
32
+ *
33
+ * ## Pillar 3 — the `memory` TrustOrigin (two-site pattern)
34
+ *
35
+ * Article bodies returned by the read tools (`wiki_recall`, `wiki_get`)
36
+ * are classified at the new `"memory"` TrustOrigin BEFORE they reach the
37
+ * model: a wiki article written in an earlier session may have absorbed
38
+ * attacker text (a poisoned page STUDYed into an article), and recall
39
+ * re-injects it across a session boundary. On a malicious verdict the body
40
+ * is replaced by the redaction notice; on a non-blocked verdict the body
41
+ * is `tagContent`-ed into `RunContext.dataLineage` under origin `"memory"`
42
+ * (the skills-registry two-site pattern) so the sink-side egress fabric
43
+ * can attribute a later exfiltration to the memory boundary.
44
+ *
45
+ * ## Write-path governance (design §3.3)
46
+ *
47
+ * Constructed with `{ requireSources: true }` (the learning-mode
48
+ * enforcement), `wiki_write` deterministically REJECTS bodies without a
49
+ * `## Sources` heading — what was prompt-only discipline in the expert
50
+ * demo becomes a hard gate. Default false.
51
+ *
52
+ * ## `log_knowledge_gap` (decoupled)
53
+ *
54
+ * Takes an injected `logGap` callback — the plan-store wiring happens in
55
+ * the composition-root PR; this package never imports continuity-store.
56
+ * Without a callback the tool still works standalone: the gap is written
57
+ * into the wiki itself as a `gap-<topic>` article under the reserved
58
+ * `gaps/` tag, so the STUDY loop can find it with `wiki_list`.
59
+ *
60
+ * Mutations emit the additive event-log kind `wiki_write` through an
61
+ * injected `appendEvent` seam (tool-plan's pattern) — emitters or
62
+ * memory-service decide where events land; nothing here imports runtime
63
+ * wiring.
64
+ */
65
+ import { buildRedactionNotice, classifyBoundary } from "@crewhaus/boundary-classifier";
66
+ import { formatAgentIdentity, tagContent } from "@crewhaus/run-context";
67
+ import { buildTool } from "@crewhaus/tool-builder";
68
+ import { WikiVersionConflictError, createWikiStore, } from "@crewhaus/wiki-store";
69
+ import { z } from "zod";
70
+ /**
71
+ * The thredz-mcp wiki tool names, pinned (server.ts TOOLS, v0.2.0). The
72
+ * parity test asserts the registered set equals this list EXACTLY — a
73
+ * drifted name would silently fork the skill vocabulary between backends.
74
+ */
75
+ export const THREDZ_WIKI_TOOL_NAMES = [
76
+ "wiki_recall",
77
+ "wiki_semantic_search",
78
+ "wiki_search",
79
+ "wiki_get",
80
+ "wiki_write",
81
+ "wiki_list",
82
+ "wiki_related",
83
+ "wiki_set_signals",
84
+ "wiki_stats",
85
+ "log_knowledge_gap",
86
+ ];
87
+ /** The reserved tag marking standalone-logged knowledge gaps (§3.2). */
88
+ export const GAPS_TAG = "gaps/";
89
+ // ---------------------------------------------------------------------------
90
+ // schemas — field-for-field mirrors of thredz-mcp's TOOLS inputSchemas
91
+ // ---------------------------------------------------------------------------
92
+ const recallSchema = z.object({
93
+ query: z.string().min(1).describe("what to recall about"),
94
+ limit: z.number().int().min(1).max(50).optional().describe("max snippets (default 6)"),
95
+ });
96
+ const semanticSearchSchema = z.object({
97
+ query: z.string().min(1).describe("natural-language query"),
98
+ limit: z.number().int().min(1).max(50).optional().describe("max results (default 6)"),
99
+ minScore: z.number().min(0).max(1).optional().describe("similarity floor 0–1 (default 0.05)"),
100
+ });
101
+ const searchSchema = z.object({
102
+ query: z.string().min(1).describe("keyword query"),
103
+ });
104
+ const getSchema = z.object({
105
+ slug: z.string().min(1).describe("article slug"),
106
+ concise: z.boolean().optional().describe("trim to essentials"),
107
+ });
108
+ const articleStatusSchema = z.enum(["draft", "published", "review", "archived"]);
109
+ const writeSchema = z.object({
110
+ slug: z.string().min(1).describe("stable kebab-case identifier"),
111
+ title: z.string().min(1).describe("article title"),
112
+ body: z.string().min(1).describe("Markdown body — include a ## Sources section with citations"),
113
+ summary: z.string().optional().describe("one-line summary"),
114
+ tags: z.array(z.string().min(1)).optional().describe("lowercase topic tags"),
115
+ category: z.string().optional().describe("category slug (optional)"),
116
+ status: articleStatusSchema
117
+ .optional()
118
+ .describe("draft | published | review | archived (default published)"),
119
+ confidenceScore: z.number().min(0).max(1).optional().describe("0–1 confidence in this knowledge"),
120
+ editMessage: z.string().optional().describe("what changed and why"),
121
+ visibility: z
122
+ .enum(["private", "shared"])
123
+ .optional()
124
+ .describe("'private' (default — the local wiki is private by construction) | 'shared' (a Thredz concept; accepted for cross-backend parity, meaningless locally)"),
125
+ });
126
+ const listSchema = z.object({
127
+ query: z.string().optional().describe("optional relevance filter"),
128
+ tags: z.string().optional().describe("comma-separated tags"),
129
+ category: z.string().optional().describe("category slug"),
130
+ status: z.string().optional().describe("draft | published | review | archived | all"),
131
+ sort: z
132
+ .string()
133
+ .optional()
134
+ .describe("updated | created | title | relevance | popular | trending"),
135
+ order: z.string().optional().describe("asc | desc"),
136
+ limit: z.number().int().min(1).max(100).optional().describe("page size (default 25, max 100)"),
137
+ });
138
+ const relatedSchema = z.object({
139
+ slug: z.string().min(1).describe("article slug"),
140
+ });
141
+ const setSignalsSchema = z.object({
142
+ slug: z.string().min(1).describe("article slug"),
143
+ verified: z.boolean().optional().describe("fact-checked"),
144
+ confidenceScore: z.number().min(0).max(1).optional().describe("0–1"),
145
+ });
146
+ const statsSchema = z.object({});
147
+ const logGapSchema = z.object({
148
+ topic: z.string().min(1).describe("the topic the expert was weak on"),
149
+ detail: z.string().optional().describe("what specifically was missing"),
150
+ tags: z.array(z.string().min(1)).optional(),
151
+ priority: z.enum(["low", "medium", "high"]).optional().describe("low | medium | high"),
152
+ });
153
+ // ---------------------------------------------------------------------------
154
+ // helpers
155
+ // ---------------------------------------------------------------------------
156
+ /** The learning-mode gate: a `## Sources` heading anywhere in the body. */
157
+ export function hasSourcesHeading(body) {
158
+ return /^##\s+Sources\b/m.test(body);
159
+ }
160
+ /** Bullet/plain lines under the `## Sources` heading (frontmatter sources[]). */
161
+ export function extractSources(body, cap = 20) {
162
+ const lines = body.split("\n");
163
+ const start = lines.findIndex((l) => /^##\s+Sources\b/.test(l));
164
+ if (start === -1)
165
+ return [];
166
+ const out = [];
167
+ for (const line of lines.slice(start + 1)) {
168
+ if (/^#{1,6}\s/.test(line))
169
+ break; // next heading ends the section
170
+ const cleaned = line.replace(/^\s*[-*+]\s+/, "").trim();
171
+ if (cleaned === "")
172
+ continue;
173
+ out.push(cleaned);
174
+ if (out.length >= cap)
175
+ break;
176
+ }
177
+ return out;
178
+ }
179
+ /** Kebab-case a free-text topic into a slug fragment. */
180
+ function slugifyTopic(topic) {
181
+ const slug = topic
182
+ .toLowerCase()
183
+ .replace(/[^a-z0-9]+/g, "-")
184
+ .replace(/^-+|-+$/g, "")
185
+ .slice(0, 80)
186
+ .replace(/-+$/g, "");
187
+ return slug === "" ? "unnamed" : slug;
188
+ }
189
+ /**
190
+ * Resolve the run's `RunContext` for provenance tagging — the
191
+ * skills-registry pattern: prefer `ctx.runContext` (threaded on every tool
192
+ * execute), fall back to the opaque runtime bridge's `runContext`.
193
+ */
194
+ function resolveRunContext(ctx) {
195
+ if (ctx?.runContext !== undefined)
196
+ return ctx.runContext;
197
+ const bridge = ctx?.bridge;
198
+ return bridge?.runContext;
199
+ }
200
+ /**
201
+ * Pillar 3 source side, applied to ONE article body: classify at origin
202
+ * `"memory"`, return the redaction notice on a malicious verdict, tag the
203
+ * lineage otherwise. The caller splices the result into its rendering.
204
+ */
205
+ async function classifyBody(body, rc) {
206
+ const boundary = await classifyBoundary(body, { origin: "memory" });
207
+ if (boundary.action === "redact") {
208
+ return boundary.redacted ?? buildRedactionNotice(boundary.verdict.hits);
209
+ }
210
+ if (rc !== undefined) {
211
+ tagContent(rc, body, "memory");
212
+ }
213
+ return body;
214
+ }
215
+ function refLine(ref) {
216
+ const tagSuffix = ref.tags.length > 0 ? ` [${ref.tags.join(", ")}]` : "";
217
+ const verifiedSuffix = ref.verified ? " ✓verified" : "";
218
+ return `${ref.slug} (v${ref.version}, ${ref.status}, conf ${ref.confidence.toFixed(2)}${verifiedSuffix}) — ${ref.title}${tagSuffix}`;
219
+ }
220
+ function hitHeader(hit) {
221
+ const viaSuffix = hit.via === "link" ? ", via link" : "";
222
+ return `--- ${refLine(hit.ref)} (score ${hit.score.toFixed(4)}${viaSuffix})`;
223
+ }
224
+ const STALE_WRITE_REMEDIATION = "the article changed under you (stale version) — re-read it with wiki_get, then re-apply your edit";
225
+ // ---------------------------------------------------------------------------
226
+ // the bundle
227
+ // ---------------------------------------------------------------------------
228
+ export function createWikiTools(opts) {
229
+ const now = opts.now ?? (() => new Date());
230
+ const store = opts.store ??
231
+ createWikiStore({
232
+ specName: opts.specName,
233
+ ...(opts.rootDir !== undefined ? { rootDir: opts.rootDir } : {}),
234
+ ...(opts.embedder !== undefined ? { embedder: opts.embedder } : {}),
235
+ now,
236
+ });
237
+ const requireSources = opts.requireSources === true;
238
+ function createdByFrom(ctx) {
239
+ const rc = resolveRunContext(ctx);
240
+ if (rc === undefined)
241
+ return undefined;
242
+ return {
243
+ sessionId: rc.sessionId,
244
+ ...(rc.agentIdentity !== undefined
245
+ ? { agentIdentity: formatAgentIdentity(rc.agentIdentity) }
246
+ : {}),
247
+ };
248
+ }
249
+ async function emit(payload) {
250
+ if (opts.appendEvent === undefined)
251
+ return;
252
+ await opts.appendEvent({ kind: "wiki_write", payload });
253
+ }
254
+ const recall = buildTool({
255
+ name: "wiki_recall",
256
+ description: "PRIMARY RECALL. Fetch the most relevant slice of the expert's own wiki for a query — a combined keyword + semantic-vector context bundle. Call this FIRST on every user question before answering.",
257
+ inputSchema: recallSchema,
258
+ readOnly: true,
259
+ scope: "internal",
260
+ execute: async (input, ctx) => {
261
+ const rc = resolveRunContext(ctx);
262
+ const hits = await store.recall(input.query, input.limit ?? 6);
263
+ if (hits.length === 0) {
264
+ return `no wiki articles matched "${input.query}" — if this is a real gap, record it with log_knowledge_gap`;
265
+ }
266
+ const lines = [`${hits.length} wiki hit(s) for "${input.query}":`];
267
+ for (const hit of hits) {
268
+ lines.push("", hitHeader(hit), await classifyBody(hit.body, rc));
269
+ }
270
+ return lines.join("\n");
271
+ },
272
+ });
273
+ const semanticSearch = buildTool({
274
+ name: "wiki_semantic_search",
275
+ description: "Vector/semantic search over the wiki. Use when a query is conceptual and keyword search would miss paraphrases.",
276
+ inputSchema: semanticSearchSchema,
277
+ readOnly: true,
278
+ scope: "internal",
279
+ execute: async (input) => {
280
+ const k = input.limit ?? 6;
281
+ if (store.semanticSearch === undefined) {
282
+ // Thredz-parity degradation: keyword-only plans fall back too.
283
+ const refs = await store.search(input.query);
284
+ const lines = [
285
+ "no embedder configured — degraded to keyword search (configure memory.wiki.embedder for semantic ranking):",
286
+ ];
287
+ for (const ref of refs.slice(0, k))
288
+ lines.push(` • ${refLine(ref)}`);
289
+ if (refs.length === 0)
290
+ lines.push(` (no keyword matches for "${input.query}")`);
291
+ return lines.join("\n");
292
+ }
293
+ const hits = await store.semanticSearch(input.query, k, input.minScore ?? 0.05);
294
+ if (hits.length === 0) {
295
+ return `no semantic matches ≥ ${(input.minScore ?? 0.05).toFixed(2)} for "${input.query}"`;
296
+ }
297
+ const lines = [`${hits.length} semantic match(es) for "${input.query}":`];
298
+ for (const hit of hits) {
299
+ lines.push(` • (${hit.score.toFixed(3)}) ${refLine(hit.ref)}`);
300
+ }
301
+ return lines.join("\n");
302
+ },
303
+ });
304
+ const search = buildTool({
305
+ name: "wiki_search",
306
+ description: "Keyword/full-text search over the wiki with scored snippets. Use for exact terms, names, numbers.",
307
+ inputSchema: searchSchema,
308
+ readOnly: true,
309
+ scope: "internal",
310
+ execute: async (input) => {
311
+ const refs = await store.search(input.query);
312
+ if (refs.length === 0)
313
+ return `no wiki articles matched "${input.query}"`;
314
+ const lines = [`${refs.length} keyword match(es) for "${input.query}":`];
315
+ for (const ref of refs)
316
+ lines.push(` • ${refLine(ref)}`);
317
+ return lines.join("\n");
318
+ },
319
+ });
320
+ const CONCISE_CHARS = 600;
321
+ const get = buildTool({
322
+ name: "wiki_get",
323
+ description: "Read one wiki article in full by its slug (e.g. after a search returns a promising hit).",
324
+ inputSchema: getSchema,
325
+ readOnly: true,
326
+ scope: "internal",
327
+ execute: async (input, ctx) => {
328
+ const rc = resolveRunContext(ctx);
329
+ const article = await store.get(input.slug);
330
+ if (article === null)
331
+ return `no wiki article with slug "${input.slug}"`;
332
+ const safeBody = await classifyBody(article.body, rc);
333
+ const body = input.concise === true && safeBody.length > CONCISE_CHARS
334
+ ? `${safeBody.slice(0, CONCISE_CHARS).trimEnd()}\n… (concise — call wiki_get without concise for the full body)`
335
+ : safeBody;
336
+ const header = [
337
+ `# ${article.title}`,
338
+ `slug: ${article.slug} · v${article.version} · ${article.status} · confidence ${article.confidence.toFixed(2)}${article.verified ? " · ✓verified" : ""}`,
339
+ article.tags.length > 0 ? `tags: ${article.tags.join(", ")}` : "",
340
+ article.sources.length > 0 ? `sources: ${article.sources.join(" · ")}` : "",
341
+ `updated: ${article.updatedAt}${article.supersedes !== undefined ? ` (supersedes v${article.supersedes})` : ""}`,
342
+ ].filter((l) => l !== "");
343
+ return `${header.join("\n")}\n\n${body}`;
344
+ },
345
+ });
346
+ const write = buildTool({
347
+ name: "wiki_write",
348
+ description: "UPSERT a durable article into the wiki by slug (creates, or patches the existing one). This is how the expert commits time-tested, high-value knowledge to long-term memory. Include sources and a confidenceScore.",
349
+ inputSchema: writeSchema,
350
+ destructive: true,
351
+ // Pillar 3 intent gate (§7.4): committing knowledge to long-term memory
352
+ // is exactly what an injected instruction would reach for.
353
+ requireJustification: true,
354
+ scope: "internal",
355
+ execute: async (input, ctx) => {
356
+ if (requireSources && !hasSourcesHeading(input.body)) {
357
+ // Deterministic write-path governance (§3.3): no citation, no write.
358
+ return ("wiki_write rejected: the body has no `## Sources` section. This wiki " +
359
+ "requires cited knowledge — add a `## Sources` heading listing where " +
360
+ "this came from, then retry. Nothing was written.");
361
+ }
362
+ const existing = await store.get(input.slug).catch(() => null);
363
+ const createdBy = createdByFrom(ctx);
364
+ try {
365
+ const result = await store.write({
366
+ slug: input.slug,
367
+ title: input.title,
368
+ body: input.body,
369
+ ...(input.tags !== undefined ? { tags: input.tags } : {}),
370
+ ...(input.confidenceScore !== undefined ? { confidence: input.confidenceScore } : {}),
371
+ ...(input.status !== undefined ? { status: input.status } : {}),
372
+ sources: extractSources(input.body),
373
+ ...(existing !== null ? { expectedVersion: existing.version } : {}),
374
+ ...(createdBy !== undefined ? { createdBy } : {}),
375
+ });
376
+ await emit({
377
+ slug: result.slug,
378
+ version: result.version,
379
+ action: "write",
380
+ ...(input.editMessage !== undefined ? { editMessage: input.editMessage } : {}),
381
+ });
382
+ const verb = existing === null
383
+ ? "created"
384
+ : `updated (superseded v${existing.version} — prior kept in versions/)`;
385
+ const sharedNote = input.visibility === "shared"
386
+ ? "\nnote: the local wiki is private by construction — 'shared' visibility only applies on the Thredz backend."
387
+ : "";
388
+ return `wiki_write: ${verb} "${result.slug}" at v${result.version}${sharedNote}`;
389
+ }
390
+ catch (err) {
391
+ if (err instanceof WikiVersionConflictError) {
392
+ return `wiki_write failed (stale_article_version) — ${STALE_WRITE_REMEDIATION}`;
393
+ }
394
+ throw err;
395
+ }
396
+ },
397
+ });
398
+ const list = buildTool({
399
+ name: "wiki_list",
400
+ description: "List/filter wiki articles. For REFLECTION passes: sort by `updated` ascending to surface the stalest articles, or filter by tags/status to audit a topic.",
401
+ inputSchema: listSchema,
402
+ readOnly: true,
403
+ scope: "internal",
404
+ execute: async (input) => {
405
+ const limit = input.limit ?? 25;
406
+ const sort = input.sort ?? "updated";
407
+ const order = input.order ?? "asc"; // thredz default: stalest first
408
+ const status = input.status === "draft" ||
409
+ input.status === "published" ||
410
+ input.status === "review" ||
411
+ input.status === "archived"
412
+ ? input.status
413
+ : "all";
414
+ const tags = (input.tags ?? "")
415
+ .split(",")
416
+ .map((t) => t.trim())
417
+ .filter((t) => t !== "");
418
+ let refs = [
419
+ ...(await store.list({
420
+ staleFirst: order === "asc",
421
+ status,
422
+ ...(tags.length > 0 ? { tags } : {}),
423
+ })),
424
+ ];
425
+ if (input.query !== undefined && input.query.trim() !== "") {
426
+ const matched = new Set((await store.search(input.query)).map((r) => r.slug));
427
+ refs = refs.filter((r) => matched.has(r.slug));
428
+ }
429
+ const notes = [];
430
+ if (sort === "title") {
431
+ refs.sort((a, b) => a.title.localeCompare(b.title) * (order === "desc" ? -1 : 1));
432
+ }
433
+ else if (sort !== "updated") {
434
+ notes.push(`note: sort "${sort}" is not supported locally — sorted by updated instead.`);
435
+ }
436
+ const rows = refs.slice(0, limit);
437
+ const lines = [
438
+ `${rows.length}/${refs.length} article(s) (sort ${sort === "title" ? "title" : "updated"} ${order}):`,
439
+ ...notes,
440
+ ];
441
+ for (const ref of rows)
442
+ lines.push(` • ${ref.updatedAt} ${refLine(ref)}`);
443
+ if (rows.length === 0)
444
+ lines.push(" (none)");
445
+ return lines.join("\n");
446
+ },
447
+ });
448
+ const related = buildTool({
449
+ name: "wiki_related",
450
+ description: "Find articles related to a slug by tags + semantic similarity. Use in reflection to detect duplicates or contradictions to reconcile.",
451
+ inputSchema: relatedSchema,
452
+ readOnly: true,
453
+ scope: "internal",
454
+ execute: async (input) => {
455
+ let refs;
456
+ try {
457
+ refs = await store.related(input.slug);
458
+ }
459
+ catch {
460
+ return `no wiki article with slug "${input.slug}"`;
461
+ }
462
+ if (refs.length === 0)
463
+ return `no articles related to "${input.slug}"`;
464
+ const lines = [`${refs.length} article(s) related to "${input.slug}":`];
465
+ for (const ref of refs)
466
+ lines.push(` • (${ref.relatedScore.toFixed(2)}) ${refLine(ref)}`);
467
+ return lines.join("\n");
468
+ },
469
+ });
470
+ const setSignals = buildTool({
471
+ name: "wiki_set_signals",
472
+ description: "Set quality signals on an article after verification: `verified` (fact-checked against a primary source) and/or `confidenceScore` (0–1). Use in reflection to promote or demote knowledge.",
473
+ inputSchema: setSignalsSchema,
474
+ destructive: true,
475
+ // Pillar 3 intent gate (§7.4): promoting poisoned knowledge to
476
+ // "verified" (or demoting good knowledge) is a high-leverage mutation.
477
+ requireJustification: true,
478
+ scope: "internal",
479
+ execute: async (input) => {
480
+ if (input.verified === undefined && input.confidenceScore === undefined) {
481
+ return "wiki_set_signals: pass at least one of `verified` / `confidenceScore`.";
482
+ }
483
+ try {
484
+ await store.setSignals(input.slug, {
485
+ ...(input.verified !== undefined ? { verified: input.verified } : {}),
486
+ ...(input.confidenceScore !== undefined ? { confidence: input.confidenceScore } : {}),
487
+ });
488
+ }
489
+ catch {
490
+ return `no wiki article with slug "${input.slug}"`;
491
+ }
492
+ const article = await store.get(input.slug);
493
+ await emit({
494
+ slug: input.slug,
495
+ version: article?.version ?? 0,
496
+ action: "set_signals",
497
+ });
498
+ const bits = [];
499
+ if (input.verified !== undefined)
500
+ bits.push(`verified=${input.verified}`);
501
+ if (input.confidenceScore !== undefined)
502
+ bits.push(`confidence=${input.confidenceScore}`);
503
+ return `wiki_set_signals: "${input.slug}" → ${bits.join(", ")} (v${article?.version ?? "?"} unchanged — signals never bump the version)`;
504
+ },
505
+ });
506
+ const stats = buildTool({
507
+ name: "wiki_stats",
508
+ description: "Corpus health: article/category/tag/version counts. Useful in a reflection summary.",
509
+ inputSchema: statsSchema,
510
+ readOnly: true,
511
+ scope: "internal",
512
+ execute: async () => {
513
+ const s = await store.stats();
514
+ return [
515
+ `wiki stats (${opts.specName}):`,
516
+ ` articles: ${s.articles} (published ${s.byStatus.published}, draft ${s.byStatus.draft}, review ${s.byStatus.review}, archived ${s.byStatus.archived})`,
517
+ ` prior versions: ${s.priorVersions}`,
518
+ ` unique tags: ${s.uniqueTags}`,
519
+ ` verified: ${s.verified}`,
520
+ ` avg confidence: ${s.averageConfidence.toFixed(2)}`,
521
+ ` link edges: ${s.links}`,
522
+ ].join("\n");
523
+ },
524
+ });
525
+ const logKnowledgeGap = buildTool({
526
+ name: "log_knowledge_gap",
527
+ description: "Record a knowledge gap when the expert could NOT confidently answer. These gaps become the highest-priority items for the next study pass — this is how the expert learns WHAT to learn.",
528
+ inputSchema: logGapSchema,
529
+ // sideEffect audit-and-allow (§3.2/§7.4): it writes durable state, so it
530
+ // is destructive for permission purposes, but deliberately NOT
531
+ // justification-gated — logging a gap must stay the honest low-friction
532
+ // path (friction here trains the model to bluff instead).
533
+ destructive: true,
534
+ scope: "internal",
535
+ execute: async (input, ctx) => {
536
+ const gap = {
537
+ topic: input.topic,
538
+ ...(input.detail !== undefined ? { detail: input.detail } : {}),
539
+ tags: input.tags ?? [],
540
+ priority: input.priority ?? "medium",
541
+ };
542
+ if (opts.logGap !== undefined) {
543
+ return await opts.logGap(gap);
544
+ }
545
+ // Standalone fallback: the gap lives in the wiki itself under the
546
+ // reserved `gaps/` tag so wiki_list can drive the next STUDY pass.
547
+ const slug = `gap-${slugifyTopic(gap.topic)}`;
548
+ const existing = await store.get(slug).catch(() => null);
549
+ const at = now().toISOString();
550
+ const entry = `- ${at} (${gap.priority}) ${gap.detail ?? "(no detail)"}`;
551
+ const body = existing === null
552
+ ? `Knowledge gap: ${gap.topic}\n\n## Occurrences\n\n${entry}`
553
+ : `${existing.body}\n${entry}`;
554
+ const createdBy = createdByFrom(ctx);
555
+ const result = await store.write({
556
+ slug,
557
+ title: `Study gap: ${gap.topic}`,
558
+ body,
559
+ tags: [GAPS_TAG, `priority:${gap.priority}`, ...gap.tags],
560
+ status: "draft",
561
+ ...(existing !== null ? { expectedVersion: existing.version } : {}),
562
+ ...(createdBy !== undefined ? { createdBy } : {}),
563
+ });
564
+ await emit({ slug: result.slug, version: result.version, action: "gap" });
565
+ return `logged knowledge gap "${gap.topic}" → ${result.slug} (v${result.version}, priority ${gap.priority}) — find it with wiki_list tags=${GAPS_TAG}`;
566
+ },
567
+ });
568
+ return {
569
+ recall,
570
+ semanticSearch,
571
+ search,
572
+ get,
573
+ write,
574
+ list,
575
+ related,
576
+ setSignals,
577
+ stats,
578
+ logKnowledgeGap,
579
+ all: [
580
+ recall,
581
+ semanticSearch,
582
+ search,
583
+ get,
584
+ write,
585
+ list,
586
+ related,
587
+ setSignals,
588
+ stats,
589
+ logKnowledgeGap,
590
+ ],
591
+ store,
592
+ };
593
+ }
package/package.json ADDED
@@ -0,0 +1,48 @@
1
+ {
2
+ "name": "@crewhaus/tool-wiki",
3
+ "version": "0.3.0",
4
+ "type": "module",
5
+ "description": "0.3.0 memory release §3.2 — the thredz-identical wiki tool vocabulary (wiki_recall … log_knowledge_gap) over @crewhaus/wiki-store, with memory-origin boundary classification on every recalled body.",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js"
12
+ }
13
+ },
14
+ "scripts": {
15
+ "test": "bun test src"
16
+ },
17
+ "dependencies": {
18
+ "@crewhaus/boundary-classifier": "0.3.0",
19
+ "@crewhaus/event-log": "0.3.0",
20
+ "@crewhaus/run-context": "0.3.0",
21
+ "@crewhaus/tool-builder": "0.3.0",
22
+ "@crewhaus/tool-catalog": "0.3.0",
23
+ "@crewhaus/wiki-store": "0.3.0",
24
+ "zod": "^3.23.8"
25
+ },
26
+ "devDependencies": {
27
+ "@crewhaus/embedder": "0.3.0"
28
+ },
29
+ "license": "Apache-2.0",
30
+ "author": {
31
+ "name": "Max Meier",
32
+ "email": "max@crewhaus.ai",
33
+ "url": "https://crewhaus.ai"
34
+ },
35
+ "repository": {
36
+ "type": "git",
37
+ "url": "git+https://github.com/crewhaus/factory.git",
38
+ "directory": "packages/tool-wiki"
39
+ },
40
+ "homepage": "https://github.com/crewhaus/factory/tree/main/packages/tool-wiki#readme",
41
+ "bugs": {
42
+ "url": "https://github.com/crewhaus/factory/issues"
43
+ },
44
+ "publishConfig": {
45
+ "access": "public"
46
+ },
47
+ "files": ["dist", "README.md", "LICENSE", "NOTICE"]
48
+ }