@a-t-h-i/bot-lobby 0.6.66 → 0.6.68

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@a-t-h-i/bot-lobby",
3
- "version": "0.6.66",
3
+ "version": "0.6.68",
4
4
  "description": "Structured multi-agent software engineering orchestrator for Pi",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
package/src/desk/lock.ts CHANGED
@@ -7,8 +7,8 @@
7
7
  * holder and losing changes. Temp names carry the pid and a random suffix,
8
8
  * so concurrent writers never collide.
9
9
  */
10
- import { mkdirSync, rmSync, statSync } from "node:fs";
11
- import { dirname } from "node:path";
10
+ import { mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
11
+ import { dirname, join } from "node:path";
12
12
  import { randomUUID } from "node:crypto";
13
13
 
14
14
  /** How long a writer waits for another process's write, and when a lock is taken to be left behind. */
@@ -21,10 +21,21 @@ function sleep(ms: number): void {
21
21
  Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
22
22
  }
23
23
 
24
- /** A lock's identity: the inode of the directory currently holding it. */
24
+ /** A lock's identity: the token its taker wrote inside it (an inode can be reused at once by a breaker's new lock). */
25
25
  function lockIdentity(lock: string): string | undefined {
26
26
  try {
27
- return String(statSync(lock).ino);
27
+ return readFileSync(join(lock, "owner"), "utf8");
28
+ } catch {
29
+ return undefined;
30
+ }
31
+ }
32
+
33
+ /** Mark a just-made lock as ours; undefined when it was broken before the mark landed. */
34
+ function claim(lock: string): string | undefined {
35
+ const token = `${process.pid}.${randomUUID()}`;
36
+ try {
37
+ writeFileSync(join(lock, "owner"), token, { flag: "wx" });
38
+ return token;
28
39
  } catch {
29
40
  return undefined;
30
41
  }
@@ -60,7 +71,7 @@ export function withFileLock<T>(path: string, write: () => T): T {
60
71
  sleep(5);
61
72
  continue;
62
73
  }
63
- const identity = lockIdentity(lock);
74
+ const identity = claim(lock);
64
75
  if (!stillOurs(lock, identity)) {
65
76
  // Broken from under us before the write: take it again rather than write beside the breaker.
66
77
  if (Date.now() > until) throw new Error(LOCK_BUSY);
@@ -288,7 +288,9 @@ export class DeskSession {
288
288
  const queue = undeliveredFor(readBoard(board), readDelivery(path).recipients[peer], this.scopeFor(peer));
289
289
  const batch = queue.slice(0, REPLAY_LIMIT);
290
290
  const extra = queue.filter((entry) => !batch.includes(entry));
291
- const shown = extra.includes(post) ? [...batch, post] : batch;
291
+ // The board is read afresh, so the fresh post is matched by its number, not by identity.
292
+ const beyond = extra.some((entry) => entry.seq === post.seq);
293
+ const shown = beyond ? [...batch, post] : batch;
292
294
  const waiting = queue.length - shown.length;
293
295
  try {
294
296
  this.steer(peer, `bot-lobby board: ${formatPosts(shown)}${waiting > 0 ? `\n(+${waiting} older board posts waiting; read_board shows them.)` : ""}`);
@@ -297,7 +299,7 @@ export class DeskSession {
297
299
  }
298
300
  markDelivered(path, peer, batch.at(-1)?.seq ?? post.seq);
299
301
  // Only the batch and the fresh post were shown; the backlog beyond them stays pending for the next catch-up.
300
- if (extra.includes(post)) markSeen(path, peer, post.seq);
302
+ if (beyond) markSeen(path, peer, post.seq);
301
303
  return true;
302
304
  }
303
305
 
@@ -0,0 +1,194 @@
1
+ /**
2
+ * What the Knowledge page shows beside the files themselves: which notes are
3
+ * pinned, where each note came from and how it changed (with the text before
4
+ * each edit, so an earlier version can be restored), and the Inbox of notes
5
+ * finished work proposed and nobody has accepted yet. One JSON file per
6
+ * project, next to the knowledge directories; the knowledge files stay plain
7
+ * Markdown that agents read and rewrite.
8
+ *
9
+ * Notes are tied to their entry by its text, like the user's comments: an
10
+ * edit from the Knowledge page carries its pins and history to the new text.
11
+ */
12
+ import { randomUUID } from "node:crypto";
13
+ import { existsSync, readFileSync, renameSync, writeFileSync } from "node:fs";
14
+ import { join } from "node:path";
15
+ import { tempName, withFileLock } from "../desk/lock.ts";
16
+ import type { KnowledgeAgent } from "./paths.ts";
17
+
18
+ export interface LedgerPin {
19
+ agent: KnowledgeAgent;
20
+ file: string;
21
+ entry: string;
22
+ at: string;
23
+ }
24
+
25
+ /** One thing that happened to a note: who did it, in words, and the text before when it changed. */
26
+ export interface LedgerEvent {
27
+ id: string;
28
+ agent: KnowledgeAgent;
29
+ file: string;
30
+ /** The note's text after the event. */
31
+ entry: string;
32
+ /** "you", or the agent that wrote it. */
33
+ by: string;
34
+ /** What happened, as a sentence without its subject ("wrote this while working on task 8f3a21"). */
35
+ what: string;
36
+ /** Where it came from, short ("Task 8f3a21", "Chat with you", "Compaction"). */
37
+ source?: string;
38
+ /** The text before an edit: restoring the event puts it back. */
39
+ before?: string;
40
+ at: string;
41
+ }
42
+
43
+ /** A note finished work proposed, waiting in the Inbox. */
44
+ export interface LedgerProposal {
45
+ id: string;
46
+ agent: KnowledgeAgent;
47
+ kind: "knowledge" | "standard" | "decision";
48
+ text: string;
49
+ source: string;
50
+ /** 0–100, when the proposer said how sure it is. */
51
+ confidence?: number;
52
+ /** The note it would replace, by its text. */
53
+ replaces?: string;
54
+ taskId?: string;
55
+ at: string;
56
+ }
57
+
58
+ interface LedgerFile {
59
+ version: 1;
60
+ pins: LedgerPin[];
61
+ events: LedgerEvent[];
62
+ proposals: LedgerProposal[];
63
+ }
64
+
65
+ const MAX_EVENTS = 3000;
66
+ const MAX_PROPOSALS = 200;
67
+
68
+ export function ledgerPath(dataRoot: string): string {
69
+ return join(dataRoot, "knowledge-ledger.json");
70
+ }
71
+
72
+ /** A note's text without its list marker, for matching across bullets and plain lines. */
73
+ export function plainEntry(text: string): string {
74
+ return text.replace(/^\s*(?:[-*+]|\d+[.)])\s+(?:\[[ x]\]\s+)?/i, "").trim().toLowerCase();
75
+ }
76
+
77
+ function empty(): LedgerFile {
78
+ return { version: 1, pins: [], events: [], proposals: [] };
79
+ }
80
+
81
+ export function readLedger(dataRoot: string | undefined): LedgerFile {
82
+ if (!dataRoot) return empty();
83
+ const path = ledgerPath(dataRoot);
84
+ if (!existsSync(path)) return empty();
85
+ try {
86
+ const parsed = JSON.parse(readFileSync(path, "utf8")) as Partial<LedgerFile>;
87
+ return {
88
+ version: 1,
89
+ pins: Array.isArray(parsed.pins) ? parsed.pins : [],
90
+ events: Array.isArray(parsed.events) ? parsed.events : [],
91
+ proposals: Array.isArray(parsed.proposals) ? parsed.proposals : [],
92
+ };
93
+ } catch {
94
+ return empty();
95
+ }
96
+ }
97
+
98
+ function update<T>(dataRoot: string, change: (ledger: LedgerFile) => T): T {
99
+ const path = ledgerPath(dataRoot);
100
+ return withFileLock(path, () => {
101
+ const ledger = readLedger(dataRoot);
102
+ const result = change(ledger);
103
+ ledger.events = ledger.events.slice(-MAX_EVENTS);
104
+ ledger.proposals = ledger.proposals.slice(-MAX_PROPOSALS);
105
+ const temp = tempName(path);
106
+ writeFileSync(temp, `${JSON.stringify(ledger, null, 1)}\n`, "utf8");
107
+ renameSync(temp, path);
108
+ return result;
109
+ });
110
+ }
111
+
112
+ const same = (a: { agent: string; file: string; entry: string }, agent: string, file: string, entry: string) =>
113
+ a.agent === agent && a.file === file && plainEntry(a.entry) === plainEntry(entry);
114
+
115
+ /** Note what happened to an entry. */
116
+ export function recordEvent(dataRoot: string, event: Omit<LedgerEvent, "id" | "at">, now = new Date()): void {
117
+ update(dataRoot, (ledger) => {
118
+ ledger.events.push({ ...event, id: randomUUID().slice(0, 8), at: now.toISOString() });
119
+ });
120
+ }
121
+
122
+ /** Pin a note to the top, or unpin it. */
123
+ export function setPin(dataRoot: string, agent: KnowledgeAgent, file: string, entry: string, on: boolean, now = new Date()): void {
124
+ update(dataRoot, (ledger) => {
125
+ ledger.pins = ledger.pins.filter((pin) => !same(pin, agent, file, entry));
126
+ if (on) ledger.pins.push({ agent, file, entry, at: now.toISOString() });
127
+ });
128
+ }
129
+
130
+ /** An entry changed text (or moved file): its pins and history follow it. */
131
+ export function moveEntry(dataRoot: string, from: { agent: KnowledgeAgent; file: string; entry: string }, to: { agent: KnowledgeAgent; file: string; entry: string }): void {
132
+ update(dataRoot, (ledger) => {
133
+ for (const pin of ledger.pins) if (same(pin, from.agent, from.file, from.entry)) Object.assign(pin, to);
134
+ for (const event of ledger.events) if (same(event, from.agent, from.file, from.entry)) Object.assign(event, to);
135
+ });
136
+ }
137
+
138
+ /** An entry was deleted: its pin goes (its history stays, unseen). */
139
+ export function dropEntry(dataRoot: string, agent: KnowledgeAgent, file: string, entry: string): void {
140
+ update(dataRoot, (ledger) => {
141
+ ledger.pins = ledger.pins.filter((pin) => !same(pin, agent, file, entry));
142
+ });
143
+ }
144
+
145
+ /** Add a note to the Inbox; one already waiting with the same text is kept instead. */
146
+ export function propose(dataRoot: string, proposal: Omit<LedgerProposal, "id" | "at">, now = new Date()): boolean {
147
+ return update(dataRoot, (ledger) => {
148
+ const key = plainEntry(proposal.text);
149
+ if (!key || ledger.proposals.some((one) => one.agent === proposal.agent && plainEntry(one.text) === key)) return false;
150
+ ledger.proposals.push({ ...proposal, id: randomUUID().slice(0, 8), at: now.toISOString() });
151
+ return true;
152
+ });
153
+ }
154
+
155
+ /** Take a proposal out of the Inbox (accepted or dismissed); the one taken, when it was there. */
156
+ export function takeProposal(dataRoot: string, id: string): LedgerProposal | undefined {
157
+ return update(dataRoot, (ledger) => {
158
+ const found = ledger.proposals.find((one) => one.id === id);
159
+ ledger.proposals = ledger.proposals.filter((one) => one.id !== id);
160
+ return found;
161
+ });
162
+ }
163
+
164
+ /** Proposals a write made moot: the same text, now saved for that agent. */
165
+ export function settleProposals(dataRoot: string, agent: KnowledgeAgent, text: string): void {
166
+ const key = plainEntry(text);
167
+ if (!key || !existsSync(ledgerPath(dataRoot))) return;
168
+ update(dataRoot, (ledger) => {
169
+ ledger.proposals = ledger.proposals.filter((one) => !(one.agent === agent && plainEntry(one.text) === key));
170
+ });
171
+ }
172
+
173
+ /** The pinned entries of one agent's file, in pin order, for the prompt. */
174
+ export function pinnedEntries(dataRoot: string | undefined, agent: KnowledgeAgent, file: string): string[] {
175
+ return readLedger(dataRoot).pins.filter((pin) => pin.agent === agent && pin.file === file).map((pin) => pin.entry);
176
+ }
177
+
178
+ /** `- [kind] text — 90%` or `… (replaces: old text)`: a proposal's confidence and what it replaces, read off its line. */
179
+ export function proposalParts(text: string): { text: string; confidence?: number; replaces?: string } {
180
+ let rest = text.trim();
181
+ let replaces: string | undefined;
182
+ const replacing = /\s*\((?:replaces|supersedes):\s*(.+)\)\s*$/i.exec(rest);
183
+ if (replacing) {
184
+ replaces = replacing[1]!.replace(/^["“]|["”]$/g, "").trim();
185
+ rest = rest.slice(0, replacing.index).trim();
186
+ }
187
+ let confidence: number | undefined;
188
+ const sure = /\s*(?:[—–-]|\()\s*(\d{1,3})\s*%\s*(?:confident|confidence)?\)?\s*$/i.exec(rest);
189
+ if (sure) {
190
+ confidence = Math.min(100, Number(sure[1]));
191
+ rest = rest.slice(0, sure.index).trim();
192
+ }
193
+ return { text: rest, ...(confidence !== undefined ? { confidence } : {}), ...(replaces ? { replaces } : {}) };
194
+ }
@@ -54,7 +54,7 @@ export function shareDigest(dataRoot: string, items: readonly DigestItem[], now
54
54
  const added: Partial<Record<KnowledgeAgent, number>> = {};
55
55
  for (const item of items) {
56
56
  const text = item.kind === "decision" ? item.text : `- ${item.text}`;
57
- if (applyKnowledge({ dataRoot, agent: item.agent, kind: item.kind, text, now }).result === "added") added[item.agent] = (added[item.agent] ?? 0) + 1;
57
+ if (applyKnowledge({ dataRoot, agent: item.agent, kind: item.kind, text, now, by: "Oracle", what: "filed this when it compacted its context", source: "Compaction" }).result === "added") added[item.agent] = (added[item.agent] ?? 0) + 1;
58
58
  }
59
59
  return added;
60
60
  }
@@ -1,7 +1,11 @@
1
1
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
- import { dirname, join } from "node:path";
2
+ import { basename, dirname, join } from "node:path";
3
3
  import { knowledgeDir, STANDARDS_FILE, type KnowledgeAgent } from "./paths.ts";
4
4
  import { annotate, readNotes } from "./notes.ts";
5
+ import { pinnedEntries, recordEvent, settleProposals } from "./ledger.ts";
6
+
7
+ /** The agent's name as the Knowledge page shows it. */
8
+ const AGENT_NAMES: Record<KnowledgeAgent, string> = { master: "Oracle", designer: "Designer", backend: "Backend", qa: "QA" };
5
9
 
6
10
  export function readFileOr(path: string, fallback = ""): string {
7
11
  try {
@@ -73,6 +77,10 @@ export interface KnowledgeEntry {
73
77
  kind: KnowledgeKind;
74
78
  text: string;
75
79
  now?: Date;
80
+ /** Who wrote it and how, for the note's history on the Knowledge page ("Backend", "wrote this while working on task 8f3a21"). */
81
+ by?: string;
82
+ what?: string;
83
+ source?: string;
76
84
  }
77
85
 
78
86
  /**
@@ -89,6 +97,16 @@ export function applyKnowledge(entry: KnowledgeEntry): { path: string; result: "
89
97
  if (entry.kind === "decision") appendDecision(dirname(path), text, now);
90
98
  else if (entry.kind === "completed") appendCompletedTask(dirname(path), text, now);
91
99
  else writeFileEnsured(path, `${existing.trimEnd()}\n\n${text}\n`);
100
+ if (entry.kind !== "completed") {
101
+ const file = basename(path);
102
+ const by = entry.by ?? AGENT_NAMES[entry.agent];
103
+ try {
104
+ recordEvent(entry.dataRoot, { agent: entry.agent, file, entry: text, by, what: entry.what ?? "wrote this", ...(entry.source ? { source: entry.source } : {}) }, now);
105
+ settleProposals(entry.dataRoot, entry.agent, text);
106
+ } catch {
107
+ // The history is a nicety; the knowledge itself is saved.
108
+ }
109
+ }
92
110
  return { path, result: "added" };
93
111
  }
94
112
 
@@ -114,12 +132,21 @@ export function readKnowledgeSlices(
114
132
  export function readAgentKnowledge(roots: readonly string[], agent: KnowledgeAgent) {
115
133
  const slices = readKnowledgeSlices(roots.map((root) => knowledgeDir(root, agent)), STANDARDS_FILE[agent]);
116
134
  const notes = readNotes(roots[0]).filter((note) => note.agent === agent);
117
- if (notes.length === 0) return slices;
118
135
  const about = (file: string) => notes.filter((note) => note.file === file);
136
+ // Pinned notes load first: repeated at the top of their file, so a trimmed slice still carries them.
137
+ const shaped = (content: string, file: string) => pinFirst(notes.length ? annotate(content, about(file)) : content, pinnedEntries(roots[0], agent, file));
119
138
  return {
120
- knowledge: annotate(slices.knowledge, about("knowledge.md")),
121
- standards: annotate(slices.standards, about(STANDARDS_FILE[agent])),
122
- decisions: annotate(slices.decisions, about("decisions.md")),
123
- completed: annotate(slices.completed, about("completed-tasks.md")),
139
+ knowledge: shaped(slices.knowledge, "knowledge.md"),
140
+ standards: shaped(slices.standards, STANDARDS_FILE[agent]),
141
+ decisions: shaped(slices.decisions, "decisions.md"),
142
+ completed: shaped(slices.completed, "completed-tasks.md"),
124
143
  };
125
144
  }
145
+
146
+ /** The pins still in the file, as a "Pinned" list above it. */
147
+ function pinFirst(content: string, pins: readonly string[]): string {
148
+ const lines = content.split("\n").map((line) => line.trim());
149
+ const kept = pins.filter((pin) => lines.includes(pin.trim()));
150
+ if (kept.length === 0) return content;
151
+ return `## Pinned (always loaded first)\n\n${kept.map((pin) => (/^[-*+]\s/.test(pin.trim()) ? pin.trim() : `- ${pin.trim()}`)).join("\n")}\n\n${content}`;
152
+ }
@@ -12,7 +12,9 @@ import { compactKnowledgeFile } from "../knowledge/compactor.ts";
12
12
  import { findEntry, insertAfter, parseEntries, removeEntry, replaceEntry, type KnowledgeEntry } from "../knowledge/edit.ts";
13
13
  import { addNote, moveNotes, readNotes, removeNote, removeNotesOn, type KnowledgeNote } from "../knowledge/notes.ts";
14
14
  import { AGENT_DIR_NAMES, KNOWLEDGE_FILES, knowledgeDir, type KnowledgeAgent } from "../knowledge/paths.ts";
15
- import { readFirstExisting } from "../knowledge/store.ts";
15
+ import { applyKnowledge, readFirstExisting } from "../knowledge/store.ts";
16
+ import { dropEntry, moveEntry, readLedger, recordEvent, setPin, takeProposal, type LedgerEvent, type LedgerPin, type LedgerProposal } from "../knowledge/ledger.ts";
17
+ import { readMetrics } from "../state/metrics.ts";
16
18
  import { dataRoot, readDataRoots } from "../state/project.ts";
17
19
 
18
20
  /** What each knowledge file is, in words. */
@@ -84,6 +86,34 @@ export interface KnowledgeDeps {
84
86
 
85
87
  const CHANGED = "that entry changed on disk since it was drawn — r reloads the file";
86
88
 
89
+ /** One run that loaded an agent's knowledge: when, and for which task. */
90
+ export interface KnowledgeRun {
91
+ at: string;
92
+ taskId?: string;
93
+ }
94
+
95
+ /** What the Knowledge page shows beside the files: pins, each note's history, the Inbox and how often each agent ran. */
96
+ export interface KnowledgeLedgerView {
97
+ pins: LedgerPin[];
98
+ events: LedgerEvent[];
99
+ proposals: LedgerProposal[];
100
+ /** Each agent's runs in the last 30 days (every run loads its knowledge), newest first, and its last run ever. */
101
+ runs: Partial<Record<KnowledgeAgent, { recent: KnowledgeRun[]; lastAt?: string }>>;
102
+ }
103
+
104
+ /** The metrics' agent names (`DEV`, `DESIGN`, `MASTER`, …) as knowledge agents. */
105
+ function runAgent(name: string): KnowledgeAgent | undefined {
106
+ const key = name.toUpperCase();
107
+ if (key === "MASTER" || key === "ORACLE") return "master";
108
+ if (key === "DEV" || key === "BACKEND") return "backend";
109
+ if (key === "DESIGN" || key === "DESIGNER" || key === "FRONTEND") return "designer";
110
+ if (key === "QA") return "qa";
111
+ return undefined;
112
+ }
113
+
114
+ /** Short names, as the page's history lines use them. */
115
+ const SHORT_NAMES: Record<KnowledgeAgent, string> = { master: "Oracle", designer: "Designer", backend: "Backend", qa: "QA" };
116
+
87
117
  export class KnowledgeBook {
88
118
  private readonly deps: KnowledgeDeps;
89
119
 
@@ -146,6 +176,10 @@ export class KnowledgeBook {
146
176
  if (next.trim() === content.trim()) return "nothing changed";
147
177
  const notice = this.write(agent, file, next);
148
178
  const moved = moveNotes(this.data, agent, file, entry.text, text.replace(/\s+$/, ""), this.deps.now?.());
179
+ this.note(() => {
180
+ moveEntry(this.data, { agent, file, entry: entry.text }, { agent, file, entry: text.trim() });
181
+ recordEvent(this.data, { agent, file, entry: text.trim(), by: "you", what: "edited it", before: entry.text }, this.deps.now?.());
182
+ });
149
183
  return `${notice}${moved > 0 ? `; ${moved} note${moved === 1 ? "" : "s"} stayed with it` : ""}`;
150
184
  }
151
185
 
@@ -156,7 +190,9 @@ export class KnowledgeBook {
156
190
  if (after && !entry) return CHANGED;
157
191
  const next = insertAfter(content, entry, text);
158
192
  if (next === content) return "nothing to add";
159
- return this.write(agent, file, next);
193
+ const notice = this.write(agent, file, next);
194
+ this.note(() => recordEvent(this.data, { agent, file, entry: text.trim(), by: "you", what: "wrote this", source: "You" }, this.deps.now?.()));
195
+ return notice;
160
196
  }
161
197
 
162
198
  /** Delete an entry, and the notes on it. */
@@ -166,6 +202,7 @@ export class KnowledgeBook {
166
202
  if (!entry) return CHANGED;
167
203
  const notice = this.write(agent, file, removeEntry(content, entry));
168
204
  const gone = removeNotesOn(this.data, agent, file, entry.text, this.deps.now?.());
205
+ this.note(() => dropEntry(this.data, agent, file, entry.text));
169
206
  return `${notice}${gone > 0 ? `; its ${gone} note${gone === 1 ? "" : "s"} went with it` : ""}`;
170
207
  }
171
208
 
@@ -188,6 +225,107 @@ export class KnowledgeBook {
188
225
  return "note saved — every agent reads it under this entry";
189
226
  }
190
227
 
228
+ /** History and pins never stop a write: they are the page's record, not the knowledge. */
229
+ private note(write: () => void): void {
230
+ try {
231
+ write();
232
+ } catch {
233
+ // Left out of the history.
234
+ }
235
+ }
236
+
237
+ /** Characters past which a file is over its compaction threshold. */
238
+ threshold(): number {
239
+ return this.deps.threshold();
240
+ }
241
+
242
+ /** Pins, history, the Inbox and the agents' recent runs. */
243
+ ledger(): KnowledgeLedgerView {
244
+ const ledger = readLedger(this.data);
245
+ const now = (this.deps.now?.() ?? new Date()).getTime();
246
+ const since = now - 30 * 24 * 3600 * 1000;
247
+ const runs: KnowledgeLedgerView["runs"] = {};
248
+ let records: ReturnType<typeof readMetrics> = [];
249
+ try {
250
+ records = readMetrics(this.deps.root, this.deps.configDir);
251
+ } catch {
252
+ records = [];
253
+ }
254
+ for (const record of records) {
255
+ const agent = runAgent(record.agent);
256
+ const at = Date.parse(record.startedAt);
257
+ if (!agent || Number.isNaN(at)) continue;
258
+ const mine = (runs[agent] ??= { recent: [] });
259
+ if (!mine.lastAt || at > Date.parse(mine.lastAt)) mine.lastAt = record.startedAt;
260
+ if (at >= since) mine.recent.push({ at: record.startedAt, ...(record.taskId ? { taskId: record.taskId } : {}) });
261
+ }
262
+ for (const mine of Object.values(runs)) mine?.recent.sort((a, b) => Date.parse(b.at) - Date.parse(a.at)).splice(500);
263
+ return { pins: ledger.pins, events: ledger.events, proposals: ledger.proposals, runs };
264
+ }
265
+
266
+ /** Pin a note to the top of its file (it loads first), or unpin it. */
267
+ pin(agent: KnowledgeAgent, file: string, ref: EntryRef, on: boolean): string {
268
+ const entry = findEntry(this.read(agent, file), ref.text, ref.occurrence);
269
+ if (!entry) return CHANGED;
270
+ setPin(this.data, agent, file, entry.text, on, this.deps.now?.());
271
+ return on ? "pinned — it loads first for this agent" : "unpinned";
272
+ }
273
+
274
+ /** Put back the text an edit replaced. */
275
+ restore(agent: KnowledgeAgent, file: string, ref: EntryRef, eventId: string): string {
276
+ const event = readLedger(this.data).events.find((one) => one.id === eventId);
277
+ if (!event?.before) return "that version is no longer in the history";
278
+ const notice = this.edit(agent, file, ref, event.before);
279
+ return notice.startsWith("saved") ? `restored the earlier version — ${notice}` : notice;
280
+ }
281
+
282
+ /** Move a note to another agent's file: added there, then removed here, its comments, pin and history with it. */
283
+ move(agent: KnowledgeAgent, file: string, ref: EntryRef, to: KnowledgeAgent, toFile: string): string {
284
+ if (agent === to && file === toFile) return "it is already there";
285
+ const content = this.read(agent, file);
286
+ const entry = findEntry(content, ref.text, ref.occurrence);
287
+ if (!entry) return CHANGED;
288
+ const target = this.read(to, toFile);
289
+ this.write(to, toFile, insertAfter(target, undefined, entry.text));
290
+ const notice = this.write(agent, file, removeEntry(content, entry));
291
+ const notes = readNotes(this.data).filter((note) => note.agent === agent && note.file === file && note.entry === entry.text);
292
+ for (const note of notes) {
293
+ addNote(this.data, { agent: to, file: toFile, entry: entry.text, text: note.text, ...(note.by ? { by: note.by } : {}) }, this.deps.now?.());
294
+ removeNote(this.data, note.id, this.deps.now?.());
295
+ }
296
+ this.note(() => {
297
+ moveEntry(this.data, { agent, file, entry: entry.text }, { agent: to, file: toFile, entry: entry.text });
298
+ recordEvent(this.data, { agent: to, file: toFile, entry: entry.text, by: "you", what: `moved it from ${SHORT_NAMES[agent]}` }, this.deps.now?.());
299
+ });
300
+ return `moved to ${AGENT_LABELS[to]}'s ${toFile} — ${notice}`;
301
+ }
302
+
303
+ /** Accept a note from the Inbox (as written, or with the user's edit): saved, and the note it replaces updated. */
304
+ accept(id: string, text?: string): string {
305
+ const proposal = takeProposal(this.data, id);
306
+ if (!proposal) return "that proposal was already handled";
307
+ const body = (text ?? proposal.text).trim();
308
+ if (proposal.replaces) {
309
+ for (const file of KNOWLEDGE_FILES[proposal.agent]) {
310
+ const entry = findEntry(this.read(proposal.agent, file), proposal.replaces, 0) ?? parseEntries(this.read(proposal.agent, file)).find((one) => one.text.replace(/^[-*+]\s+/, "").trim() === proposal.replaces!.trim());
311
+ if (entry) {
312
+ const notice = this.edit(proposal.agent, file, { text: entry.text, occurrence: 0 }, entry.kind === "bullet" ? `- ${body.replace(/^[-*+]\s+/, "")}` : body);
313
+ this.note(() => recordEvent(this.data, { agent: proposal.agent, file, entry: entry.kind === "bullet" ? `- ${body.replace(/^[-*+]\s+/, "")}` : body, by: "you", what: `accepted it from the Inbox (${proposal.source})` }, this.deps.now?.()));
314
+ return `accepted — ${notice}`;
315
+ }
316
+ }
317
+ }
318
+ const kind = proposal.kind;
319
+ const line = kind === "decision" ? body : body.startsWith("-") ? body : `- ${body}`;
320
+ const outcome = applyKnowledge({ dataRoot: this.data, agent: proposal.agent, kind, text: line, by: SHORT_NAMES[proposal.agent], what: `proposed this after ${proposal.source.toLowerCase()}; you accepted it`, source: `Inbox · from ${proposal.source}`, ...(this.deps.now ? { now: this.deps.now() } : {}) });
321
+ return outcome.result === "duplicate" ? "already saved — nothing changed" : `accepted — saved for ${AGENT_LABELS[proposal.agent]}`;
322
+ }
323
+
324
+ /** Dismiss a note from the Inbox. */
325
+ dismiss(id: string): string {
326
+ return takeProposal(this.data, id) ? "dismissed" : "that proposal was already handled";
327
+ }
328
+
191
329
  /** Take a note back. */
192
330
  unnote(id: string): string {
193
331
  removeNote(this.data, id, this.deps.now?.());
@@ -18,7 +18,7 @@ export const workerSpec: RoleSpec = {
18
18
  "### Output contract",
19
19
  "Respond with exactly these sections and nothing else: `## Completed`, `## Files Changed`,",
20
20
  "`## Verification`, `## Brief Check` (one `- criterion — met|not met — evidence` line per \"Done when\" item of your brief), `## Notes`, `## Blockers`, `## Dependencies Needed`, `## Architecture Changes`,",
21
- "`## Knowledge Proposals` (`- knowledge: ...`, `- standard: ...`, or `- decision: ...`).",
21
+ "`## Knowledge Proposals` (`- knowledge: ...`, `- standard: ...`, or `- decision: ...`; end a line with `— NN%` for how sure you are, and `(replaces: old text)` when it corrects a saved note).",
22
22
  "An optional `## Script Proposals` (`- \\`name.ext\\` — what it does — draft: \\`path\\``) proposes a script you wrote for a job that will come back, for the shared library.",
23
23
  "`## Files Changed` entries are `- \\`path\\` — change`.",
24
24
  "`## Verification` entries are `- command — result`.",
@@ -15,7 +15,7 @@ import { lobbyAbort, lobbyHistory, lobbySend, lobbySnapshot } from "./lobby.ts";
15
15
  import { promptsAnswer, promptsDismiss, promptsList } from "./prompts.ts";
16
16
  import { plannerAnswer, plannerCommentLine, plannerGet, plannerNew, plannerRetry, plannerSend, plannerEditMessage, plannerToggleSeat, plannerSave, plannerPrevious, plannerPreviousArchive, plannerPreviousDelete, plannerPreviousGet, plannerPreviousOpen } from "./planner.ts";
17
17
  import { tasksArchive, tasksArchived, tasksAuto, tasksComment, tasksComments, tasksDelete, tasksEditComment, tasksGet, tasksList, tasksMessage, tasksRestore, tasksOpen, tasksResume, tasksDeliveryReview, tasksDeliveryDefer, tasksDeliver, tasksAccept, tasksSkipStep, tasksForceClose, tasksResolveApproval } from "./tasks.ts";
18
- import { knowledgeAdd, knowledgeAsk, knowledgeComment, knowledgeEdit, knowledgeFiles, knowledgeOpen, knowledgeRemove, knowledgeReplaceFile, knowledgeUnnote } from "./knowledge.ts";
18
+ import { knowledgeAccept, knowledgeAdd, knowledgeAsk, knowledgeComment, knowledgeDismiss, knowledgeEdit, knowledgeFiles, knowledgeLedger, knowledgeMove, knowledgeOpen, knowledgePin, knowledgeRemove, knowledgeReplaceFile, knowledgeRestore, knowledgeUnnote } from "./knowledge.ts";
19
19
  import { plansDiscard, plansGet, plansStart } from "./plans.ts";
20
20
  import { sessionsAnswer, sessionsArchive, sessionsChat, sessionsList, sessionsMessage, sessionsRename, sessionsStart, sessionsStop, sessionsSwitch } from "./sessions.ts";
21
21
  import { settingsGet, settingsGrants, settingsHarnesses, settingsLinters, settingsSet } from "./settings.ts";
@@ -328,6 +328,29 @@ function buildRoutes(): Record<string, Route> {
328
328
  schema: Type.Object({ agent: KnowledgeAgent, file: KnowledgeFile, ref: EntryRef, text: Type.String({ minLength: 1, maxLength: 2000 }) }, { additionalProperties: false }),
329
329
  run: (body, ctx) => knowledgeComment(body as { agent: "master" | "designer" | "backend" | "qa"; file: string; ref: { text: string; occurrence: number }; text: string }, ctx),
330
330
  };
331
+ type Agent = "master" | "designer" | "backend" | "qa";
332
+ type Ref = { text: string; occurrence: number };
333
+ routes["knowledge.ledger"] = { schema: Empty, run: (_body, ctx) => knowledgeLedger(ctx) };
334
+ routes["knowledge.pin"] = {
335
+ schema: Type.Object({ agent: KnowledgeAgent, file: KnowledgeFile, ref: EntryRef, on: Type.Boolean() }, { additionalProperties: false }),
336
+ run: (body, ctx) => knowledgePin(body as { agent: Agent; file: string; ref: Ref; on: boolean }, ctx),
337
+ };
338
+ routes["knowledge.restore"] = {
339
+ schema: Type.Object({ agent: KnowledgeAgent, file: KnowledgeFile, ref: EntryRef, event: Type.String({ minLength: 1, maxLength: 64 }) }, { additionalProperties: false }),
340
+ run: (body, ctx) => knowledgeRestore(body as { agent: Agent; file: string; ref: Ref; event: string }, ctx),
341
+ };
342
+ routes["knowledge.move"] = {
343
+ schema: Type.Object({ agent: KnowledgeAgent, file: KnowledgeFile, ref: EntryRef, to: KnowledgeAgent, toFile: KnowledgeFile }, { additionalProperties: false }),
344
+ run: (body, ctx) => knowledgeMove(body as { agent: Agent; file: string; ref: Ref; to: Agent; toFile: string }, ctx),
345
+ };
346
+ routes["knowledge.accept"] = {
347
+ schema: Type.Object({ id: Type.String({ minLength: 1, maxLength: 64 }), text: Type.Optional(KnowledgeText) }, { additionalProperties: false }),
348
+ run: (body, ctx) => knowledgeAccept(body as { id: string; text?: string }, ctx),
349
+ };
350
+ routes["knowledge.dismiss"] = {
351
+ schema: Type.Object({ id: Type.String({ minLength: 1, maxLength: 64 }) }, { additionalProperties: false }),
352
+ run: (body, ctx) => knowledgeDismiss(body as { id: string }, ctx),
353
+ };
331
354
  routes["knowledge.unnote"] = {
332
355
  schema: Type.Object({ id: TaskId }, { additionalProperties: false }),
333
356
  run: (body, ctx) => knowledgeUnnote(body as { id: string }, ctx),
@@ -42,8 +42,9 @@ interface RefBody extends FileBody {
42
42
  }
43
43
 
44
44
  /** Every agent's files with their size and note counts, in tab order. */
45
- export function knowledgeFiles(ctx: ApiContext): { files: KnowledgeFileInfo[]; models: Record<KnowledgeAgentName, string> } {
46
- return { files: ctx.service.knowledge.files(), models: agentModels(ctx.service.config?.() ?? loadConfig()) };
45
+ export function knowledgeFiles(ctx: ApiContext): { files: KnowledgeFileInfo[]; models: Record<KnowledgeAgentName, string>; threshold?: number } {
46
+ const threshold = ctx.service.knowledge.threshold?.();
47
+ return { files: ctx.service.knowledge.files(), models: agentModels(ctx.service.config?.() ?? loadConfig()), ...(threshold ? { threshold } : {}) };
47
48
  }
48
49
 
49
50
  /** The model each knowledge-keeping agent runs on, as the tree names it ("session model" when none is pinned). */
@@ -94,3 +95,39 @@ export function knowledgeComment(body: RefBody & { text: string }, ctx: ApiConte
94
95
  export function knowledgeUnnote(body: { id: string }, ctx: ApiContext): { notice: string } {
95
96
  return { notice: ctx.service.knowledge.unnote(body.id) };
96
97
  }
98
+
99
+ /** Pins, history, the Inbox and the agents' recent runs. */
100
+ export function knowledgeLedger(ctx: ApiContext): ReturnType<ApiContext["service"]["knowledge"]["ledger"]> {
101
+ return ctx.service.knowledge.ledger();
102
+ }
103
+
104
+ /** Pin a note (it loads first), or unpin it. */
105
+ export function knowledgePin(body: RefBody & { on: boolean }, ctx: ApiContext): { notice: string } {
106
+ const notice = ctx.service.knowledge.pin(body.agent, body.file, body.ref, body.on);
107
+ if (isStale(notice)) stale(notice);
108
+ return { notice };
109
+ }
110
+
111
+ /** Put back the text an edit replaced. */
112
+ export function knowledgeRestore(body: RefBody & { event: string }, ctx: ApiContext): { notice: string } {
113
+ const notice = ctx.service.knowledge.restore(body.agent, body.file, body.ref, body.event);
114
+ if (isStale(notice)) stale(notice);
115
+ return { notice };
116
+ }
117
+
118
+ /** Move a note to another agent's file. */
119
+ export function knowledgeMove(body: RefBody & { to: KnowledgeAgent; toFile: string }, ctx: ApiContext): { notice: string } {
120
+ const notice = ctx.service.knowledge.move(body.agent, body.file, body.ref, body.to, body.toFile);
121
+ if (isStale(notice)) stale(notice);
122
+ return { notice };
123
+ }
124
+
125
+ /** Accept an Inbox note, as proposed or edited. */
126
+ export function knowledgeAccept(body: { id: string; text?: string }, ctx: ApiContext): { notice: string } {
127
+ return { notice: ctx.service.knowledge.accept(body.id, body.text) };
128
+ }
129
+
130
+ /** Dismiss an Inbox note. */
131
+ export function knowledgeDismiss(body: { id: string }, ctx: ApiContext): { notice: string } {
132
+ return { notice: ctx.service.knowledge.dismiss(body.id) };
133
+ }