Your team of AI agents, on your Mac, Windows or Linux. Agents that talk in channels, write code, review each other and use your tools, on the Claude Code, Codex, OpenCode or Pi you already have. Anything that touches the real world waits for your yes.
TypeScript agent-teamagentic-aiai-agentsai-assistantclaude-codecodexcursorelectrongrokgrok-bot-alternativelinuxlocal-firstmacosmcpmulti-agentopenclaw-alternativeopencodewindows
Wiki keeps knowledge, not records of the task (#95)
Eduardo Machado399dd0ee65fc
diff --git a/src/core/wiki-curator.ts b/src/core/wiki-curator.tsindex bcaa9e9..a2ad086 100644--- a/src/core/wiki-curator.ts+++ b/src/core/wiki-curator.ts@@ -26,40 +26,46 @@ export interface CuratorDeps {export const curatorSystem = (): string =>L(- `Você é o curador da wiki de um time. A wiki guarda o que vale lembrar por muito tempo, em páginas ligadas por [[Título]]: pessoas, clientes, projetos, assuntos e decisões.+ `Você é o curador da wiki de um time. A wiki guarda o que vale lembrar por muito tempo, em páginas ligadas por [[Título]]: pessoas, clientes, projetos, assuntos e decisões. Ela é um retrato de como as coisas estão, não um diário do que foi feito.-Você recebe as regras da wiki (o esquema), o índice das páginas, algumas páginas que podem ter a ver, e um trecho novo (uma conversa ou uma mensagem). Decida se o trecho traz algo durável:+Você recebe as regras da wiki (o esquema), o índice das páginas, algumas páginas que podem ter a ver, e um trecho novo (uma conversa ou uma mensagem). Decida se o trecho traz conhecimento durável:- uma decisão ("vamos fechar com a Construtora Alpha");- um fato que continua valendo sobre uma pessoa, um cliente ou um projeto (contato, preferência, prazo, valor, situação);-- o resultado de um trabalho ou de uma pesquisa (um roteiro, uma comparação, um orçamento);+- o resultado de um trabalho ou de uma pesquisa, o próprio resultado (um roteiro, uma comparação, um orçamento);- algo que a pessoa pediu pra guardar ("guarda isso", "anota na wiki").-Não guarde: conversa fiada, perguntas sem resposta, o que só importa nesta conversa, tarefas em andamento sem conclusão.++Conhecimento, não registro. Os agentes contam o que fizeram ("enviei o e-mail", "procurei na agenda", "rodei os testes", "criei o rascunho", "não achei o arquivo"). Isso é o registro da tarefa, não conhecimento: não guarde as ações, os passos, as tentativas, os erros nem as ferramentas usadas. Quando uma ação mudou algo que continua valendo, guarde o que mudou, não a ação: "marquei a reunião com o Marcos dia 12" vira "Reunião com [[Marcos Lima]] em 12/01" na página certa; "mandei o orçamento pro Marcos" vira "Orçamento enviado em 03/11" na situação do projeto.+Não guarde também: conversa fiada, perguntas sem resposta, o que só importa nesta conversa, tarefas em andamento sem conclusão.Se valer, escreva as mudanças:- "create": uma página nova, inteira, no formato do esquema (uma frase de resumo no começo; seções com ##; [[links]] pras outras páginas). Só crie se não houver página sobre isso no índice.-- "append": acrescente um trecho curto numa seção de uma página que existe (a seção é criada se faltar). Prefira isso a reescrever.-- "replace": troque um trecho exato que ficou errado ou velho. "old" tem que estar na página, letra por letra.+- "replace": troque um trecho exato que ficou errado ou velho. "old" tem que estar na página, letra por letra. Quando um fato mudou (a situação, um prazo, um valor), atualize o que a página diz em vez de acrescentar mais uma linha.+- "append": acrescente um trecho curto numa seção de uma página que existe (a seção é criada se faltar), pra um fato novo. Um histórico só leva marcos (contrato assinado, obra começou), não cada conversa.Escreva só o que é novo: o que já está numa página (inclusive em outra) não se repete; ligue com [[link]]. Não invente nem complete. Datas no formato dd/mm. Pouco e certo é melhor que muito.+Em cada mudança, diga em "lasting" se ela ainda vai importar daqui a três meses, pra alguém que nunca viu esta conversa. Se não, "lasting": false, e ela não entra.Responda só com JSON:-{"guardar": true|false, "motivo": "uma frase", "titulo_fonte": "título curto do trecho", "mudancas": [{"op": "create"|"append"|"replace", "pagina": "Título", "tipo": "Pessoa|Projeto|Assunto|Decisão", "secao": "Histórico", "texto": "markdown", "old": "trecho exato", "new": "trecho novo"}]}`,- `You curate a team's wiki. The wiki keeps what's worth remembering for a long time, as pages linked with [[Title]]: people, clients, projects, topics and decisions.+{"worth": true|false, "reason": "uma frase", "source_title": "título curto do trecho", "changes": [{"op": "create"|"append"|"replace", "page": "Título", "kind": "Pessoa|Projeto|Assunto|Decisão", "section": "Situação", "text": "markdown", "old": "trecho exato", "new": "trecho novo", "lasting": true|false}]}`,+ `You curate a team's wiki. The wiki keeps what's worth remembering for a long time, as pages linked with [[Title]]: people, clients, projects, topics and decisions. It's a picture of how things stand, not a diary of what was done.-You get the wiki's rules (the schema), the page index, a few pages that may be related, and a new stretch (a conversation or a message). Decide if the stretch brings something lasting:+You get the wiki's rules (the schema), the page index, a few pages that may be related, and a new stretch (a conversation or a message). Decide if the stretch brings lasting knowledge:- a decision ("we're going with Alpha Builders");- a fact that keeps holding about a person, a client or a project (contact, preference, deadline, price, status);-- the result of a piece of work or research (a plan, a comparison, a quote);+- the result of a piece of work or research, the result itself (a plan, a comparison, a quote);- something the person asked to keep ("save this", "put it in the wiki").-Don't keep: small talk, unanswered questions, what matters only in this conversation, tasks in progress with no outcome.++Knowledge, not a record. Agents tell what they did ("I sent the email", "I checked the calendar", "I ran the tests", "I made the draft", "I couldn't find the file"). That's the record of the task, not knowledge: don't keep the actions, the steps, the attempts, the errors or the tools used. When an action changed something that keeps holding, keep what changed, not the action: "I booked the meeting with Mark on the 12th" becomes "Meeting with [[Mark Lee]] on Jan 12" on the right page; "I sent Mark the quote" becomes "Quote sent on Nov 3" in the project's status.+Don't keep either: small talk, unanswered questions, what matters only in this conversation, tasks in progress with no outcome.If it's worth it, write the changes:- "create": a new page, whole, in the schema's format (a summary sentence first; ## sections; [[links]] to other pages). Only create it if no page in the index is about it.-- "append": add a short passage under a section of an existing page (the section is made if missing). Prefer this to rewriting.-- "replace": swap an exact passage that became wrong or old. "old" must be on the page, letter by letter.+- "replace": swap an exact passage that became wrong or old. "old" must be on the page, letter by letter. When a fact changed (the status, a deadline, a price), update what the page says instead of adding one more line.+- "append": add a short passage under a section of an existing page (the section is made if missing), for a new fact. A history only takes milestones (contract signed, work started), not every conversation.Write only what is new: what a page already says (even another page) isn't repeated; link to it with [[link]]. Don't make things up or fill gaps. Dates written out, like Jan 12 or Nov 3 (never 12/01). Little and right beats a lot.+For each change, say in "lasting" whether it will still matter three months from now, to someone who never saw this conversation. If not, "lasting": false, and it stays out.Reply with JSON only:-{"guardar": true|false, "motivo": "one sentence", "titulo_fonte": "short title of the stretch", "mudancas": [{"op": "create"|"append"|"replace", "pagina": "Title", "tipo": "Person|Project|Topic|Decision", "secao": "History", "texto": "markdown", "old": "exact passage", "new": "new passage"}]}`+{"worth": true|false, "reason": "one sentence", "source_title": "short title of the stretch", "changes": [{"op": "create"|"append"|"replace", "page": "Title", "kind": "Person|Project|Topic|Decision", "section": "Status", "text": "markdown", "old": "exact passage", "new": "new passage", "lasting": true|false}]}`)// Lenient: models sometimes wrap the JSON in a fence or add a word around it.@@ -89,6 +95,8 @@ export function parseOps(list: unknown): WikiOp[] {if (!page || !['create', 'append', 'replace'].includes(op)) continueif (op === 'replace' && !str(o['old'])) continueif (op !== 'replace' && !str(o['texto'] ?? o['text'])) continue+ // the model's own word that this won't matter in three months: a record of the task, not knowledge+ if (o['lasting'] === false) continueops.push({op: op as WikiOp['op'],page,@@ -228,9 +236,13 @@ export class WikiCurator {const text = p.text ?? this.excerpt(p.messages)const plain = p.plain ?? p.messages.map((m) => m.text).join(' ')// The pages it may touch: the ones the words of the stretch find.+ // The pages it may touch: first the ones the stretch names ("o Rogério mudou de telefone"),+ // then what a search finds in its end, the newest part; a long reply up front can't crowd them out.const words = ftsQuery(plain, true)- const related = words ? wiki.search(plain.slice(0, 600), 4) : []- const pages = related.map((h) => wiki.page(h.title)).filter((x): x is NonNullable<typeof x> => !!x)+ const low = plain.toLowerCase()+ const named = wiki.list().filter((p) => p.title.length >= 3 && new RegExp(`(^|[^\\p{L}\\p{N}])${p.title.toLowerCase().replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}($|[^\\p{L}\\p{N}])`, 'u').test(low)).map((p) => p.title)+ const found = words ? wiki.search(plain.slice(-600), 4).map((h) => h.title) : []+ const pages = [...new Set([...named, ...found])].slice(0, 6).map((t) => wiki.page(t)).filter((x): x is NonNullable<typeof x> => !!x)// What already waits for approval on those pages, so it isn't proposed twice or fought over.const titles = new Set(pages.map((pg) => pg.title))const waiting = wiki.changes('pending').flatMap((c) => c.ops.filter((o) => titles.has(o.page)).map((o) => `- [[${o.page}]] ${o.op}${o.section ? ` (${o.section})` : ''}: ${o.op === 'replace' ? `"${o.old}" → "${o.new}"` : (o.text ?? '').slice(0, 300)}`))@@ -255,7 +267,16 @@ export class WikiCurator {if (!out || (!out.worth && !p.force) || !out.ops.length) return []const source = p.source ?? wiki.addSource({ title: out.title, text, kind: p.kind === 'document' ? 'file' : p.kind, origin: { conversationId: p.conversationId, messageIds: p.messages.map((m) => m.id) }, by: 'auto' })const cite = ` ([[${source.file}|${L('fonte', 'source')}]])`- const ops = out.ops.map((o): WikiOp => (o.op === 'append' ? { ...o, text: `${o.text}${cite}` } : o.op === 'create' ? { ...o, text: `${o.text}\n\n${L('Fontes', 'Sources')}: [[${source.file}|${source.title}]]` } : o.op === 'replace' && o.new ? { ...o, new: `${o.new}${cite}` } : o))+ // A swap whose passage isn't on that page: on the one page that has it, it goes there; on none, it+ // becomes an addition to the page named, so approving it can't fail.+ const fitted = out.ops.map((o): WikiOp => {+ if (o.op !== 'replace' || wiki.page(o.page)?.body.includes(o.old!)) return o+ const holders = wiki.list().filter((p) => wiki.page(p.title)?.body.includes(o.old!))+ if (holders.length === 1) return { ...o, page: holders[0]!.title }+ const { old: _old, new: text = '', ...rest } = o+ return { ...rest, op: 'append', text }+ })+ const ops = fitted.filter((o) => o.op !== 'append' || o.text).map((o): WikiOp => (o.op === 'append' ? { ...o, text: `${o.text}${cite}` } : o.op === 'create' ? { ...o, text: `${o.text}\n\n${L('Fontes', 'Sources')}: [[${source.file}|${source.title}]]` } : o.op === 'replace' && o.new ? { ...o, new: `${o.new}${cite}` } : o))// New pages go in now; changes to existing ones go in or wait, as the settings say.const exists = (t: string): boolean => !!wiki.page(t)const creates = ops.filter((o) => o.op === 'create' && !exists(o.page))diff --git a/src/core/wiki-review.ts b/src/core/wiki-review.tsindex 9037a28..3d589ec 100644--- a/src/core/wiki-review.ts+++ b/src/core/wiki-review.ts@@ -36,6 +36,22 @@ function namesIn(body: string): Set<string> {return out}+// A history that grew into a log: the sections named like one, and how many entries each has.+const LOG_HEADING = /^#{2,4}\s*(hist[óo]rico|history|registro|log|atualiza[çc][õo]es|updates|andamento|progress)\b/i+export const LOG_ITEMS = 8+export function logSections(body: string): { section: string; items: number }[] {+ const out: { section: string; items: number }[] = []+ let current: { section: string; items: number } | null = null+ for (const line of body.split('\n')) {+ if (/^#{1,4}\s/.test(line)) {+ current = LOG_HEADING.test(line) ? { section: line.replace(/^#+\s*/, '').trim(), items: 0 } : null+ if (current) out.push(current)+ } else if (current && /^\s*[-*]\s+\S/.test(line)) current.items+++ }+ return out+}+const readsLikeLog = (body: string): number => Math.max(0, ...logSections(body).map((s) => s.items))+// What can be found without a model.export function lint(wiki: Wiki, owner?: string): Found[] {const pages = wiki@@ -69,38 +85,45 @@ export function lint(wiki: Wiki, owner?: string): Found[] {seen.set(k, s)}for (const [k, s] of seen) if (s.pages.length >= 3) out.push({ key: `missing:${k}`, kind: 'missing', name: s.name, pages: s.pages, text: L(`**${s.name}** aparece em ${list(s.pages)}, e não tem página.`, `**${s.name}** shows up in ${list(s.pages)}, and has no page.`) })+ // a history that grew into a diary of what was done+ for (const p of pages) {+ const n = readsLikeLog(p.body)+ if (n >= LOG_ITEMS) out.push({ key: `log:${p.title.toLowerCase()}`, kind: 'log', pages: [p.title], text: L(`${link(p.title)} tem ${n} entradas no histórico: parece um registro do que foi feito. Vale resumir no que vale hoje.`, `${link(p.title)} has ${n} history entries: it reads like a record of what was done. Worth condensing into what holds today.`) })+ }return out}export const reviewSystem = (): string =>L(`Você revisa a wiki de um time: páginas em Markdown ligadas por [[Título]]. Leia as páginas e procure só problemas reais:-- "contradicao": duas páginas (ou uma página consigo mesma) dizem coisas diferentes sobre o mesmo fato (um valor, uma data, um contato, uma situação);-- "desatualizada": uma página diz algo que outra, mais nova, mostra que já mudou (ex.: "aguardando resposta" numa página, "contrato assinado" em outra);-- "duplicada": duas páginas sobre a mesma coisa (mesma pessoa, mesmo projeto) com títulos diferentes;-- "ligacao": uma página sem ninguém ligando pra ela, que deveria ser citada em outra (diga onde).+- "contradiction": duas páginas (ou uma página consigo mesma) dizem coisas diferentes sobre o mesmo fato (um valor, uma data, um contato, uma situação);+- "stale": uma página diz algo que outra, mais nova, mostra que já mudou (ex.: "aguardando resposta" numa página, "contrato assinado" em outra);+- "duplicate": duas páginas sobre a mesma coisa (mesma pessoa, mesmo projeto) com títulos diferentes;+- "link": uma página sem ninguém ligando pra ela, que deveria ser citada em outra (diga onde);+- "log": uma página que virou um diário do que foi feito (um histórico longo de ações, passos, tentativas e conversas) em vez de dizer como as coisas estão. A correção é um "replace" que troca a seção inteira por poucas linhas com o estado atual, mantendo só os marcos e todo fato que ainda vale, sem perder nenhum.Para cada problema, proponha a correção como mudanças:- "replace": troque um trecho exato ("old" tem que estar na página, letra por letra) pelo certo ("new");- "append": acrescente um trecho numa seção de uma página.Corrija pelo que é mais novo ou tem fonte; na dúvida, não troque: só aponte, sem mudanças. Pra duplicadas, fique com a página que mais páginas ligam (ou a mais completa), leve pra ela todo fato que só a outra tem, sem perder nenhum, e na outra deixe só "Ver [[Título]]". Não invente nada que não esteja nas páginas. Pouco e certo: se nada estiver errado, a lista vem vazia.Responda só com JSON:-{"achados": [{"tipo": "contradicao"|"desatualizada"|"duplicada"|"ligacao", "paginas": ["Título"], "explicacao": "uma frase, com [[links]]", "mudancas": [{"op": "replace"|"append", "pagina": "Título", "secao": "Seção", "texto": "markdown", "old": "trecho exato", "new": "trecho novo"}]}]}`,+{"findings": [{"kind": "contradiction"|"stale"|"duplicate"|"link"|"log", "pages": ["Título"], "explanation": "uma frase, com [[links]]", "changes": [{"op": "replace"|"append", "page": "Título", "section": "Seção", "text": "markdown", "old": "trecho exato", "new": "trecho novo"}]}]}`,`You review a team's wiki: Markdown pages linked with [[Title]]. Read the pages and look only for real problems:-- "contradicao": two pages (or a page and itself) say different things about the same fact (an amount, a date, a contact, a status);-- "desatualizada": a page says something another, newer one shows has changed (e.g. "waiting for an answer" on one page, "contract signed" on another);-- "duplicada": two pages about the same thing (same person, same project) under different titles;-- "ligacao": a page nothing links to, that another one should mention (say where).+- "contradiction": two pages (or a page and itself) say different things about the same fact (an amount, a date, a contact, a status);+- "stale": a page says something another, newer one shows has changed (e.g. "waiting for an answer" on one page, "contract signed" on another);+- "duplicate": two pages about the same thing (same person, same project) under different titles;+- "link": a page nothing links to, that another one should mention (say where);+- "log": a page that turned into a diary of what was done (a long history of actions, steps, attempts and conversations) instead of saying how things stand. The fix is a "replace" that swaps the whole section for a few lines with the current state, keeping only the milestones and every fact that still holds, losing none.For each problem, write the fix as changes:- "replace": swap an exact passage ("old" must be on the page, letter by letter) for the right one ("new");- "append": add a passage under a section of a page.Fix toward what's newer or has a source; when unsure, don't swap: just point it out, with no changes. For duplicates, keep the page more pages link to (or the fuller one), bring into it every fact only the other has, losing none, and leave just "See [[Title]]" in the other. Don't make up anything the pages don't say. Little and right: if nothing is wrong, the list is empty.Reply with JSON only:-{"achados": [{"tipo": "contradicao"|"desatualizada"|"duplicada"|"ligacao", "paginas": ["Title"], "explicacao": "one sentence, with [[links]]", "mudancas": [{"op": "replace"|"append", "pagina": "Title", "secao": "Section", "texto": "markdown", "old": "exact passage", "new": "new passage"}]}]}`+{"findings": [{"kind": "contradiction"|"stale"|"duplicate"|"link"|"log", "pages": ["Title"], "explanation": "one sentence, with [[links]]", "changes": [{"op": "replace"|"append", "page": "Title", "section": "Section", "text": "markdown", "old": "exact passage", "new": "new passage"}]}]}`)-const KINDS: Record<string, WikiFinding['kind']> = { contradicao: 'contradiction', contradiction: 'contradiction', desatualizada: 'stale', stale: 'stale', duplicada: 'duplicate', duplicate: 'duplicate', ligacao: 'link', link: 'link' }+const KINDS: Record<string, WikiFinding['kind']> = { contradicao: 'contradiction', contradiction: 'contradiction', desatualizada: 'stale', stale: 'stale', duplicada: 'duplicate', duplicate: 'duplicate', ligacao: 'link', link: 'link', registro: 'log', log: 'log' }export function parseReview(text: string, wiki: Wiki): Found[] {const json = text.slice(text.indexOf('{'), text.lastIndexOf('}') + 1)@@ -175,6 +198,9 @@ export class WikiReviewer {if (!orphan.pages.length) this.found = this.found.filter((f) => f !== orphan)else if (linked.size) Object.assign(orphan, { key: `orphan:${[...orphan.pages].sort().join('|').toLowerCase()}`, text: L(`Nenhuma página liga pra ${orphan.pages.map(link).join(', ')}.`, `No page links to ${orphan.pages.map(link).join(', ')}.`) })}+ // a page the model already proposed condensing isn't also listed by the count of its entries+ const condensed = new Set(asked.filter((f) => f.kind === 'log').flatMap((f) => f.pages.map((t) => t.toLowerCase())))+ this.found = this.found.filter((f) => f.kind !== 'log' || !condensed.has(f.pages[0]!.toLowerCase()))this.found.push(...asked)} catch (e) {this.error = e instanceof Error ? e.message : String(e)@@ -187,8 +213,10 @@ export class WikiReviewer {const since = Number(wiki.getMeta('reviewed_at') ?? 0)const all = wiki.list()const changed = all.filter((p) => p.updatedAt > since).sort((a, b) => b.updatedAt - a.updatedAt)- if (!changed.length) return []- const picked = new Map<string, WikiPage>()+ // pages that read like a log go in even if nothing changed: the model proposes condensing them+ const logs = all.map((p) => wiki.page(p.title)).filter((pg): pg is WikiPage => !!pg && readsLikeLog(pg.body) >= LOG_ITEMS)+ if (!changed.length && !logs.length) return []+ const picked = new Map<string, WikiPage>(logs.map((pg) => [pg.title.toLowerCase(), pg]))const add = (t: string): void => {if (picked.has(t.toLowerCase())) returnconst pg = wiki.page(t)@@ -212,6 +240,7 @@ export class WikiReviewer {L('## Páginas', '## Pages'),...shown.map((p) => `### [[${p.title}]] (${p.kind}, ${L('atualizada em', 'updated')} ${date(p.updatedAt)})\n${p.body.slice(0, PAGE_CHARS)}`),...(orphans.length ? [L('## Páginas sem ninguém ligando pra elas', '## Pages nothing links to'), orphans.join(', ')] : []),+ ...(logs.length ? [L('## Páginas com cara de registro (veja se é o caso de condensar)', '## Pages that read like a log (see whether to condense them)'), logs.map((p) => link(p.title)).join(', ')] : []),L('Responda só com o JSON.', 'Reply with the JSON only.')].join('\n\n')return parseReview(await this.deps.llm(reviewSystem(), prompt), wiki)diff --git a/src/renderer/src/components/Wiki.tsx b/src/renderer/src/components/Wiki.tsxindex 1a752e4..bcb6164 100644--- a/src/renderer/src/components/Wiki.tsx+++ b/src/renderer/src/components/Wiki.tsx@@ -1186,10 +1186,11 @@ const FINDING_LABEL: Record<WikiFinding['kind'], () => string> = {link: () => L('Falta ligar', 'Missing link'),broken: () => L('Página por escrever', 'Page to write'),missing: () => L('Sem página', 'No page'),- orphan: () => L('Ninguém liga pra elas', 'Nothing links to them')+ orphan: () => L('Ninguém liga pra elas', 'Nothing links to them'),+ log: () => L('Parece um registro', 'Reads like a log')}-const FINDING_TONE: Record<WikiFinding['kind'], 'danger' | 'warn' | 'calm'> = { contradiction: 'danger', stale: 'warn', duplicate: 'warn', link: 'calm', broken: 'calm', missing: 'calm', orphan: 'calm' }-const FINDING_ORDER: WikiFinding['kind'][] = ['contradiction', 'stale', 'duplicate', 'link', 'broken', 'missing', 'orphan']+const FINDING_TONE: Record<WikiFinding['kind'], 'danger' | 'warn' | 'calm'> = { contradiction: 'danger', stale: 'warn', duplicate: 'warn', link: 'calm', broken: 'calm', missing: 'calm', orphan: 'calm', log: 'warn' }+const FINDING_ORDER: WikiFinding['kind'][] = ['contradiction', 'stale', 'duplicate', 'log', 'link', 'broken', 'missing', 'orphan']function WikiReviewPane(): ReactNode {const rev = useStore((s) => s.wikiRev)@@ -1225,6 +1226,7 @@ function WikiReviewPane(): ReactNode {['danger', L('Não batem', "Don't agree"), L('Duas páginas dizendo coisas diferentes sobre o mesmo valor, data ou prazo.', 'Two pages saying different things about the same amount, date or deadline.')],['warn', L('Desatualizada', 'Out of date'), L('"Aguardando resposta" numa página, "contrato assinado" em outra.', '"Waiting for an answer" on one page, "contract signed" on another.')],['warn', L('Repetida', 'Duplicate'), L('Duas páginas sobre a mesma pessoa ou o mesmo projeto. Ela junta, sem perder nada.', 'Two pages about the same person or project. It merges them, losing nothing.')],+ ['warn', L('Parece um registro', 'Reads like a log'), L('Um histórico que virou diário do que foi feito. Ela resume no que vale hoje.', 'A history that turned into a diary of what was done. It condenses it into what holds today.')],['calm', L('Solta', 'Loose'), L('Links pra páginas que não existem, nomes sem página, páginas que ninguém cita.', 'Links to missing pages, names with no page, pages nothing cites.')]] as const).map(([tone, t, d]) => (diff --git a/src/shared/types.ts b/src/shared/types.tsindex 3347b5a..49e85f4 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -881,7 +881,7 @@ export interface WikiChange {export interface WikiFinding {id: stringat: number- kind: 'broken' | 'missing' | 'orphan' | 'contradiction' | 'stale' | 'duplicate' | 'link'+ kind: 'broken' | 'missing' | 'orphan' | 'contradiction' | 'stale' | 'duplicate' | 'link' | 'log' // log: a page that reads like a record of what was donepages: string[] // the pages it is abouttext: string // what's wrong, in a sentence (Markdown, with [[links]])name?: string // broken, missing: the page it would takediff --git a/test/wiki-curator.test.ts b/test/wiki-curator.test.tsindex 3b3f7a3..cb79525 100644--- a/test/wiki-curator.test.ts+++ b/test/wiki-curator.test.ts@@ -4,7 +4,7 @@ import { join } from 'node:path'import { describe, expect, it } from 'vitest'import type { Agent, Message, Settings } from '../src/shared/types'import { applyOp, Wiki } from '../src/core/wiki'-import { parseCuration, WikiCurator } from '../src/core/wiki-curator'+import { curatorSystem, parseCuration, WikiCurator } from '../src/core/wiki-curator'const fresh = (): Wiki => {const root = mkdtempSync(join(tmpdir(), 'tucano-wiki-'))@@ -157,6 +157,47 @@ describe('the curator', () => {expect(calls[1]).not.toContain('Começa dia 12')})+ it("drops a change the model itself says won't matter in three months", () => {+ const out = parseCuration(JSON.stringify({ guardar: true, mudancas: [+ { op: 'append', pagina: 'Reforma do apto 302', secao: 'Situação', texto: 'Contrato assinado em 05/11.', lasting: true },+ { op: 'append', pagina: 'Marcos Lima', secao: 'Histórico', texto: '- 03/11: a Lia mandou o e-mail de confirmação.', lasting: false },+ { op: 'append', pagina: 'Marcos Lima', secao: 'Contato', texto: '- Prefere WhatsApp.' }+ ] }))!+ expect(out.ops.map((o) => o.text)).toEqual(['Contrato assinado em 05/11.', '- Prefere WhatsApp.'])+ })++ it('shows the model the pages the stretch names, even after a long reply', async () => {+ const { w, curator, say, calls } = setup(() => JSON.stringify({ guardar: false, mudancas: [] }))+ w.save({ title: 'Rogério', kind: 'Pessoa', body: 'Engenheiro da construtora. Telefone (41) 3333-2222.', ...by })+ say('m1', 'me', 'Rascunha um e-mail pedindo a visita técnica.', 1)+ say('m2', 'lia', `Rascunho: ${'Bom dia, preciso marcar a visita técnica no apartamento. '.repeat(20)}`, 2)+ say('m3', 'me', 'Anota aí: o Rogério mudou de telefone, agora é (41) 98888-7777.', 3)+ say('m4', 'lia', 'Anotado.', 4)+ await curator.read('c')+ expect(calls[0]).toContain('### [[Rogério]]')+ })++ it('a swap aimed at the wrong page goes to the one that has the passage, or becomes an addition', async () => {+ const reply = JSON.stringify({ guardar: true, titulo_fonte: 'Telefone novo', mudancas: [+ { op: 'replace', pagina: 'Rogério', old: '(41) 3333-2222', new: '(41) 98888-7777' },+ { op: 'replace', pagina: 'Rogério', secao: 'Contato', old: 'texto que não existe', new: 'Responde de manhã.' }+ ] })+ const { w, curator, say } = setup(() => reply, { wikiEdits: 'auto' })+ w.save({ title: 'Rogério', kind: 'Pessoa', body: 'Engenheiro da [[Construtora Alpha]].', ...by })+ w.save({ title: 'Construtora Alpha', kind: 'Assunto', body: 'Contato: [[Rogério]], (41) 3333-2222.', ...by })+ say('m1', 'me', 'O Rogério mudou de telefone, agora é (41) 98888-7777, e ele prefere ser chamado de manhã cedo.', 1)+ say('m2', 'lia', 'Anotado o telefone novo do Rogério, e que ele responde melhor de manhã.', 2)+ await curator.read('c')+ expect(w.page('Construtora Alpha')!.body).toContain('(41) 98888-7777')+ expect(w.page('Rogério')!.body).toContain('Responde de manhã.')+ expect(w.changes('conflict')).toHaveLength(0)+ })++ it('tells the model the wiki is knowledge, not a record of tasks', () => {+ expect(curatorSystem()).toMatch(/registro da tarefa|record of the task/)+ expect(curatorSystem()).toMatch(/"lasting"/)+ })+it('reads the model leniently', () => {expect(parseCuration('nada')).toBeNull()expect(parseCuration('{"guardar": true, "mudancas": [{"op": "append", "pagina": "[[X]]", "texto": "y"}, {"op": "replace", "pagina": "X"}, {"op": "voar", "pagina": "X"}]}')).toMatchObject({ worth: true, ops: [{ op: 'append', page: 'X', text: 'y' }] })diff --git a/test/wiki-review.test.ts b/test/wiki-review.test.tsindex 970b37c..441f301 100644--- a/test/wiki-review.test.ts+++ b/test/wiki-review.test.ts@@ -4,7 +4,7 @@ import { join } from 'node:path'import { describe, expect, it } from 'vitest'import type { Settings } from '../src/shared/types'import { Wiki } from '../src/core/wiki'-import { lint, parseReview, WikiReviewer } from '../src/core/wiki-review'+import { lint, logSections, parseReview, WikiReviewer } from '../src/core/wiki-review'function wiki(): Wiki {const root = mkdtempSync(join(tmpdir(), 'tucano-wiki-'))@@ -99,4 +99,24 @@ describe('a review of the wiki', () => {expect(r.status().at).toBeUndefined()expect(r.status().findings.some((f) => f.kind === 'broken')).toBe(true)})++ it('a history that grew into a log is pointed out, and the model is asked to condense it', async () => {+ const w = wiki()+ const diary = Array.from({ length: 9 }, (_, i) => `- ${i + 1}/11: a Lia conferiu a agenda e mandou um lembrete.`).join('\n')+ w.save({ title: 'Marcos Lima', body: `Cliente.\n\n## Histórico\n${diary}\n\n## Contato\n- (41) 99999-0000`, by: 'me', byName: 'Ana' })+ expect(logSections(w.page('Marcos Lima')!.body)).toEqual([{ section: 'Histórico', items: 9 }])+ expect(lint(w).find((f) => f.kind === 'log')).toMatchObject({ pages: ['Marcos Lima'] })+ // reviewed once: it still goes to the model next time, though it didn't change+ const prompts: string[] = []+ const answer = { achados: [{ tipo: 'registro', paginas: ['Marcos Lima'], explicacao: 'O histórico virou um diário.', mudancas: [{ op: 'replace', pagina: 'Marcos Lima', old: diary, new: '- Lembretes de agenda em novembro.' }] }] }+ const r = new WikiReviewer({ wiki: w, settings: () => ({}) as Settings, llm: async (_s, p) => (prompts.push(p), JSON.stringify(answer)) })+ w.setMeta('reviewed_at', String(Date.now() + 1000))+ await r.review()+ expect(prompts[0]).toContain('cara de registro')+ expect(prompts[0]).toContain('### [[Marcos Lima]]')+ const found = r.status().findings.filter((f) => f.kind === 'log')+ // the model's proposal, with its fix, takes the place of the count+ expect(found).toHaveLength(1)+ expect(found[0]!.change).toMatchObject({ state: 'pending', ops: [{ op: 'replace', new: '- Lembretes de agenda em novembro.' }] })+ })})