ai-advisory-board 0.11.1 → 0.12.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,22 @@
1
1
  # CHANGELOG — AI Advisory Board CLI
2
2
 
3
+ ## 0.12.1
4
+
5
+ ### Patch Changes
6
+
7
+ - 80562ca: Fix wiki **Ask** failing with `Query LLM call failed: … "Prompt is too long"` on large wikis.
8
+
9
+ The query prompt inlined the wiki's `catalog.json` (and index). On a wiki with hundreds of pages (e.g. from email/Slack ingestion) that's ~700 KB+ → 170k+ tokens, overflowing the model's context window before the question is even answered. The query agent now **walks the wiki natively with Read/Grep/Glob** — exactly the approach documented in `KNOWLEDGE_WIKI.md` §15.2: `Grep wiki/` for the question's terms, resolve slugs via the compact catalog without reading it whole, and `Read` only the 1–3 relevant pages. Nothing from the wiki is inlined into the prompt, so it stays a fixed small size no matter how large the wiki grows. Answers are unchanged on small wikis; large wikis now work instead of erroring.
10
+
11
+ ## 0.12.0
12
+
13
+ ### Minor Changes
14
+
15
+ - f1b1edc: Decision Coach × Business Wiki: the **📚 wiki badge now explains itself**.
16
+
17
+ - **Sources used** — the badge expands ("📚 wiki · N sources ▸") to list exactly which wiki pages the coach read for that reply (each links to the Knowledge view), plus what it searched for. Captured per turn as `DecisionMessage.wikiUsage`.
18
+ - **Added to your wiki** — when your message is ingested back into the wiki, the user turn shows a **📥 Added to your wiki (N)** note listing the new/updated pages (or "nothing new to add"). Captured as `DecisionMessage.wikiIngest` and streamed live via a new `coach_wiki_ingested` event.
19
+
3
20
  ## 0.11.1
4
21
 
5
22
  ### Patch Changes
package/dist/bin/aab.js CHANGED
@@ -4250,7 +4250,7 @@ function createIngestQueue(runner = ingestUserFacts) {
4250
4250
  const batch = state.pending.splice(0, state.pending.length);
4251
4251
  for (const group of coalesce(batch)) {
4252
4252
  try {
4253
- await runner({
4253
+ const result = await runner({
4254
4254
  text: group.text,
4255
4255
  kind: group.kind,
4256
4256
  workspace: group.workspace,
@@ -4259,8 +4259,20 @@ function createIngestQueue(runner = ingestUserFacts) {
4259
4259
  sparringSessionId: group.sparringSessionId,
4260
4260
  coachSessionId: group.coachSessionId
4261
4261
  });
4262
+ if (group.onResult) {
4263
+ try {
4264
+ await group.onResult(result);
4265
+ } catch {
4266
+ }
4267
+ }
4262
4268
  } catch (error) {
4263
4269
  logger.warn("[ingest-queue] user-fact ingest failed (non-blocking):", error);
4270
+ if (group.onResult) {
4271
+ try {
4272
+ await group.onResult(null);
4273
+ } catch {
4274
+ }
4275
+ }
4264
4276
  }
4265
4277
  }
4266
4278
  }
@@ -4328,7 +4340,8 @@ function maybeEnqueueUserInput(opts) {
4328
4340
  discussionId: opts.discussionId,
4329
4341
  sparringSessionId: opts.sparringSessionId,
4330
4342
  coachSessionId: opts.coachSessionId,
4331
- eventId: opts.eventId
4343
+ eventId: opts.eventId,
4344
+ onResult: opts.onResult
4332
4345
  });
4333
4346
  } catch (error) {
4334
4347
  logger.debug("[ingest-queue] enqueue failed (non-blocking):", error);
@@ -9941,6 +9954,7 @@ init_errors();
9941
9954
 
9942
9955
  // src/core/prompts/skill-query.ts
9943
9956
  function buildQueryPrompt(input) {
9957
+ const dir = input.wikiDir.replace(/\\/g, "/").replace(/\/+$/, "") || "wiki";
9944
9958
  const lines = [];
9945
9959
  lines.push("You are the wiki query agent for an AI advisory-board CLI.");
9946
9960
  lines.push("Your job: answer ONE question using the user's knowledge wiki, citing the pages you used.");
@@ -9951,34 +9965,21 @@ function buildQueryPrompt(input) {
9951
9965
  lines.push("## Wiki schema (`wiki/KNOWLEDGE.md`)");
9952
9966
  lines.push(input.wikiKnowledgeMd);
9953
9967
  lines.push("");
9954
- if (input.wikiCatalogJson) {
9955
- lines.push("## Wiki catalog (`wiki/.aab/catalog.json`)");
9956
- lines.push("");
9957
- lines.push("This compact catalog lists every page (slug, type, title, summary, tags, path). Use it to pick pages and resolve slugs \u2014 do NOT `Read wiki/index.md` in full (it can exceed 256 KB).");
9958
- lines.push("");
9959
- lines.push("```json");
9960
- lines.push(input.wikiCatalogJson.trim());
9961
- lines.push("```");
9962
- } else {
9963
- lines.push("## Wiki index (`wiki/index.md`, possibly truncated)");
9964
- lines.push("");
9965
- lines.push("The `<!-- AAB:SLUG-MAP -->` section is your `[[wikilink]]` resolver. Do NOT re-`Read` the full index.md (it can exceed 256 KB) \u2014 `Grep` it or `Read` with `limit: 150` if you need more.");
9966
- lines.push("");
9967
- lines.push(input.wikiIndexMd);
9968
- }
9969
- lines.push("");
9970
- lines.push("## Your procedure");
9971
- lines.push(`1. From the catalog/index above, identify the most relevant \u2264${input.maxPages} pages \u2014 do NOT read the full index.md.`);
9972
- lines.push("2. `Grep wiki/` for keywords from the question (target `summary:` and `tags:` first).");
9973
- lines.push("3. `Read` only the relevant pages. Follow `[[wikilinks]]` only when useful.");
9974
- lines.push("4. Synthesize a focused answer.");
9968
+ lines.push("## How to retrieve - the wiki lives at `" + dir + "/`; walk it with your tools");
9969
+ lines.push(
9970
+ "The wiki can hold hundreds of pages - do NOT try to read it all, and do NOT expect it inlined here. Retrieve on-demand, within your tool budget:"
9971
+ );
9972
+ lines.push("1. **`Grep " + dir + "/` for the key terms in the question first** (entity names, topics). Target `summary:` and `tags:` frontmatter. Try both English and the user's own language (e.g. Danish) where relevant.");
9973
+ lines.push("2. To resolve a slug to a file path, the compact catalog is at `" + dir + "/.aab/catalog.json` - but it can be large, so `Grep` it for the term rather than `Read`-ing it whole. **Never `Read " + dir + "/index.md` in full** (it can exceed 256 KB) - `Grep` it or `Read` with `limit: 150`.");
9974
+ lines.push("3. `Read` only the " + input.maxPages + " or fewer most relevant pages (usually 1-3). Follow `[[wikilinks]]` only when they help answer the question.");
9975
+ lines.push("4. Synthesize a focused answer grounded in what you actually read. If the wiki has nothing on the topic, say so plainly in `notes`.");
9975
9976
  lines.push("5. Mark any claims you inferred (rather than read directly from a page) with `^[inferred]`.");
9976
- lines.push("6. NEVER fabricate page slugs in citations \u2014 only cite slugs you actually opened.");
9977
+ lines.push("6. NEVER fabricate page slugs in citations - only cite slugs you actually opened.");
9977
9978
  lines.push("");
9978
- lines.push("## Output (return ONLY this raw JSON object \u2014 no fences, no commentary)");
9979
+ lines.push("## Output (return ONLY this raw JSON object - no fences, no commentary)");
9979
9980
  lines.push("");
9980
9981
  lines.push("{");
9981
- lines.push(` "answer": "<markdown \u2014 the answer to the user's question, terse and grounded in the wiki>",`);
9982
+ lines.push(` "answer": "<markdown - the answer to the user's question, terse and grounded in the wiki>",`);
9982
9983
  lines.push(' "citations": ["slug-a", "slug-b", ...], // wiki slugs you actually used');
9983
9984
  lines.push(' "notes": "Optional 1-line caveat (e.g., \\"wiki contained no info on X\\")."');
9984
9985
  lines.push("}");
@@ -9993,14 +9994,14 @@ async function queryWiki(opts) {
9993
9994
  }
9994
9995
  const maxPages = opts.maxPages ?? opts.settings.knowledgeWiki?.maxAgentPagesPerCall ?? 10;
9995
9996
  const model = pickQueryModel(opts.settings, opts.modelOverride);
9996
- const wikiKnowledgeMd = existsSync25(p.wikiKnowledge) ? readFileSync18(p.wikiKnowledge, "utf8") : "";
9997
- const wikiCatalogJson = existsSync25(p.wikiCatalog) ? readFileSync18(p.wikiCatalog, "utf8") : "";
9998
- const wikiIndexMd = wikiCatalogJson ? "" : existsSync25(p.wikiIndex) ? capText(readFileSync18(p.wikiIndex, "utf8"), 12e3) : "";
9997
+ const wikiKnowledgeMd = capText(
9998
+ existsSync25(p.wikiKnowledge) ? readFileSync18(p.wikiKnowledge, "utf8") : "",
9999
+ KNOWLEDGE_CHAR_BUDGET
10000
+ );
9999
10001
  const prompt2 = buildQueryPrompt({
10000
10002
  question: opts.question,
10001
10003
  wikiKnowledgeMd,
10002
- wikiIndexMd,
10003
- wikiCatalogJson,
10004
+ wikiDir: "wiki",
10004
10005
  maxPages
10005
10006
  });
10006
10007
  logger.debug("[query] starting", { question: opts.question.slice(0, 80), model, maxPages });
@@ -10075,8 +10076,9 @@ function pickQueryModel(settings, override) {
10075
10076
  }
10076
10077
  function capText(text, max) {
10077
10078
  if (text.length <= max) return text;
10078
- return text.slice(0, max) + "\n\u2026[truncated \u2014 use the compact catalog / Grep instead of reading this in full]";
10079
+ return text.slice(0, max) + "\n\u2026[truncated \u2014 Grep the wiki instead of reading this in full]";
10079
10080
  }
10081
+ var KNOWLEDGE_CHAR_BUDGET = 16e3;
10080
10082
 
10081
10083
  // src/core/knowledge/lint.ts
10082
10084
  import {
@@ -11288,13 +11290,25 @@ function makeCoachEventForwarder(passthrough, onTool) {
11288
11290
  if (event.type === "assistant" && event.message?.content) {
11289
11291
  for (const block of event.message.content) {
11290
11292
  if (block.type === "tool_use" && typeof block.name === "string") {
11291
- onTool(block.name.toLowerCase());
11293
+ onTool(block.name.toLowerCase(), block.input);
11292
11294
  }
11293
11295
  }
11294
11296
  }
11295
11297
  passthrough?.(event);
11296
11298
  };
11297
11299
  }
11300
+ function toWikiRelPath(input) {
11301
+ if (typeof input !== "string" || !input) return void 0;
11302
+ const posix = input.replace(/\\/g, "/");
11303
+ const idx = posix.toLowerCase().lastIndexOf("/wiki/");
11304
+ let rel = idx >= 0 ? posix.slice(idx + 1) : posix.startsWith("wiki/") ? posix : void 0;
11305
+ if (!rel) return void 0;
11306
+ const tail = rel.replace(/^wiki\//, "");
11307
+ if (tail === "index.md" || tail === "log.md" || tail === "KNOWLEDGE.md" || tail.startsWith(".aab/") || !tail.endsWith(".md")) {
11308
+ return void 0;
11309
+ }
11310
+ return rel;
11311
+ }
11298
11312
  function renderPrincipleForPrompt(p) {
11299
11313
  const lines = [`**${p.title}** (priority ${p.priority}/10, ${p.category})`];
11300
11314
  lines.push(`Description: ${p.description}`);
@@ -11351,8 +11365,18 @@ ${transcript}
11351
11365
  Respond now as the Decision Coach. Use markdown. Reference principles by their **Title**. Always end with a question or call to reflection.`;
11352
11366
  const model = opts.model ?? settings.primaryModel ?? "sonnet";
11353
11367
  let usedWiki = false;
11354
- const onEvent = makeCoachEventForwarder(opts.onEvent, (tool) => {
11355
- if (tool === "read" || tool === "grep" || tool === "glob") usedWiki = true;
11368
+ const sourcesRead = [];
11369
+ const queries = [];
11370
+ const onEvent = makeCoachEventForwarder(opts.onEvent, (tool, input) => {
11371
+ if (tool !== "read" && tool !== "grep" && tool !== "glob") return;
11372
+ usedWiki = true;
11373
+ if (tool === "read") {
11374
+ const rel = toWikiRelPath(input?.file_path);
11375
+ if (rel && !sourcesRead.includes(rel)) sourcesRead.push(rel);
11376
+ } else {
11377
+ const q = typeof input?.pattern === "string" ? input.pattern : void 0;
11378
+ if (q && !queries.includes(q)) queries.push(q);
11379
+ }
11356
11380
  });
11357
11381
  const allowedTools = useWiki ? ["WebSearch", "WebFetch", "Read", "Grep", "Glob"] : ["WebSearch", "WebFetch"];
11358
11382
  const addDirs = useWiki && opts.workspaceRoot ? [opts.workspaceRoot] : void 0;
@@ -11398,6 +11422,7 @@ Respond now as the Decision Coach. Use markdown. Reference principles by their *
11398
11422
  content: cleaned,
11399
11423
  principlesReferenced: referenced.length > 0 ? referenced : void 0,
11400
11424
  usedWiki: usedWiki || void 0,
11425
+ wikiUsage: sourcesRead.length > 0 || queries.length > 0 ? { sourcesRead, queries } : void 0,
11401
11426
  createdAt: nowIso()
11402
11427
  };
11403
11428
  const newMessages = [...session.messages];
@@ -14798,6 +14823,22 @@ async function startUiServer(opts) {
14798
14823
  const root = opts.storage.getWorkspaceRoot();
14799
14824
  return { useWiki: !!session.useBusinessWiki, workspaceRoot: root, wikiDir: paths(root).wiki };
14800
14825
  };
14826
+ const recordCoachWikiIngest = async (storage, sessionId, messageId, result) => {
14827
+ if (!messageId) return null;
14828
+ const r = result ?? {};
14829
+ const ingest = {
14830
+ producedPages: Array.isArray(r.producedPages) ? r.producedPages : [],
14831
+ updatedPages: Array.isArray(r.updatedPages) ? r.updatedPages : [],
14832
+ notes: typeof r.notes === "string" ? r.notes : void 0
14833
+ };
14834
+ const session = await storage.loadDecisionSessionById(sessionId);
14835
+ if (!session) return null;
14836
+ const msg = session.messages.find((m) => m.id === messageId);
14837
+ if (!msg) return null;
14838
+ msg.wikiIngest = ingest;
14839
+ await storage.updateDecisionSession({ ...session, updatedAt: nowIso() });
14840
+ return ingest;
14841
+ };
14801
14842
  app.get("/api/coach/sessions", async (_req, res) => {
14802
14843
  try {
14803
14844
  const sessions = await opts.storage.loadDecisionSessions();
@@ -14917,12 +14958,23 @@ async function startUiServer(opts) {
14917
14958
  await opts.storage.updateDecisionSession(updated);
14918
14959
  broadcast({ type: "coach_message", sessionId: updated.id, message: reply, session: updated });
14919
14960
  if (updated.useBusinessWiki) {
14961
+ const userMsg = [...updated.messages].reverse().find((m) => m.role === "user");
14920
14962
  maybeEnqueueUserInput({
14921
14963
  text: content,
14922
14964
  kind: "coach_message",
14923
14965
  settings,
14924
14966
  storage: opts.storage,
14925
- coachSessionId: updated.id
14967
+ coachSessionId: updated.id,
14968
+ onResult: async (result) => {
14969
+ try {
14970
+ const ingest = await recordCoachWikiIngest(opts.storage, updated.id, userMsg?.id, result);
14971
+ if (ingest) {
14972
+ broadcast({ type: "coach_wiki_ingested", sessionId: updated.id, messageId: userMsg?.id, wikiIngest: ingest });
14973
+ }
14974
+ } catch (err) {
14975
+ logger.debug("[coach] record wiki ingest failed (non-blocking):", err);
14976
+ }
14977
+ }
14926
14978
  });
14927
14979
  }
14928
14980
  } catch (error) {
@@ -18844,15 +18896,28 @@ function coachWikiRunOpts(session, root) {
18844
18896
  return { useWiki: !!session.useBusinessWiki, workspaceRoot: root, wikiDir: paths(root).wiki };
18845
18897
  }
18846
18898
  function fireCoachIngest(session, settings, storage, text) {
18847
- if (session.useBusinessWiki) {
18848
- maybeEnqueueUserInput({
18849
- text,
18850
- kind: "coach_message",
18851
- settings,
18852
- storage,
18853
- coachSessionId: session.id
18854
- });
18855
- }
18899
+ if (!session.useBusinessWiki) return;
18900
+ const userMsg = [...session.messages].reverse().find((m) => m.role === "user");
18901
+ maybeEnqueueUserInput({
18902
+ text,
18903
+ kind: "coach_message",
18904
+ settings,
18905
+ storage,
18906
+ coachSessionId: session.id,
18907
+ onResult: async (result) => {
18908
+ if (!userMsg) return;
18909
+ const r = result ?? {};
18910
+ const fresh = await storage.loadDecisionSessionById(session.id);
18911
+ const msg = fresh?.messages.find((m) => m.id === userMsg.id);
18912
+ if (!fresh || !msg) return;
18913
+ msg.wikiIngest = {
18914
+ producedPages: Array.isArray(r.producedPages) ? r.producedPages : [],
18915
+ updatedPages: Array.isArray(r.updatedPages) ? r.updatedPages : [],
18916
+ notes: typeof r.notes === "string" ? r.notes : void 0
18917
+ };
18918
+ await storage.updateDecisionSession({ ...fresh, updatedAt: nowIso() });
18919
+ }
18920
+ });
18856
18921
  }
18857
18922
  function renderMessage(role, content) {
18858
18923
  if (role === "user") {