Template 2.2.0: voice and convert modules
- 2.1.0 new opt-in `voice` module (D-0020): skill ckb-voice rewrites every prose file written under apply_to (outputs/answers, documents, reports, PROJECT-OVERVIEW) in a voice whose profile is a wiki page, wiki/voice/<name>.md (type voice-profile); settings in ckb.yaml (mode, profile, writer, apply_to, skip, chat); frozen spans never change, vague claims flagged not cut; `writer:` delegates to an external rewriting skill such as a personal ghost-writer. ckb-module writes a manifest's default_config into the entry's config:. Eval ckb-module/install-voice. - 2.2.0 new opt-in `convert` module (D-0021): skill ckb-convert and convert.py turn Markdown into Word/ODT/PDF/HTML through pandoc with a house style in templates/styles/; unit tests and eval ckb-module/install-convert. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
9d5148ccec
commit
c57ddceffd
34 changed files with 2697 additions and 6 deletions
82
.agents/modules/convert/README.md
Normal file
82
.agents/modules/convert/README.md
Normal file
|
|
@ -0,0 +1,82 @@
|
|||
# `convert` module
|
||||
|
||||
*Read this in: **English** | [Polski](README.pl.md)*
|
||||
|
||||
Opt-in. Install with "install the convert module"; remove with "uninstall
|
||||
the convert module". Nothing in here is active until installed.
|
||||
|
||||
## What it does
|
||||
|
||||
The KB writes Markdown. The people you send things to want a Word file or a
|
||||
PDF that looks like the rest of your company's documents. This module turns
|
||||
any Markdown file in the KB into **`.docx`, `.odt`, PDF or HTML** through
|
||||
[pandoc](https://pandoc.org), in a **house style**, so nobody picks fonts,
|
||||
sizes or margins by hand.
|
||||
|
||||
| Skill | Does |
|
||||
|---|---|
|
||||
| `ckb-convert` | Converts a file in a named style; creates a style from a few settings or from your company's Word template; changes, checks and lists styles. |
|
||||
|
||||
Say "give me the status report as a Word file" or "convert this answer to
|
||||
PDF". The first time, it asks once how the house style should look.
|
||||
|
||||
## Styles
|
||||
|
||||
A style is a Word file, `templates/styles/<name>.docx`. pandoc takes fonts,
|
||||
sizes, colours, spacing, page size, margins, header and footer from it and
|
||||
ignores its text. You get one in one of three ways:
|
||||
|
||||
- **Describe it**: "make a house style with Georgia 11pt, navy headings, A4".
|
||||
- **Bring your own**: "use Company.dotx as the house style". The agent copies
|
||||
it in and tells you which styles pandoc needs that your template lacks.
|
||||
- **Edit it by hand** in Word or LibreOffice: change the *styles* (Normal,
|
||||
Body Text, Title, Heading 1–6, Table), not the text, and save as `.docx`.
|
||||
|
||||
Several styles can live side by side ("convert it in the board style").
|
||||
`<name>.css` styles HTML, and an optional `<name>.odt` styles ODT directly.
|
||||
|
||||
PDF and ODT are made from the styled `.docx` with LibreOffice, so all formats
|
||||
look the same. Without LibreOffice, PDF falls back to a pandoc PDF engine and
|
||||
won't follow the Word style. You'll be told when that happens.
|
||||
|
||||
## What changes on the way
|
||||
|
||||
The Markdown file is never changed and is always kept. In the converted
|
||||
copy:
|
||||
|
||||
- frontmatter becomes the title, author (without the e-mail) and date, and the
|
||||
first `# Heading` becomes the title when there's none;
|
||||
- `<!-- comments -->` left over from a template are dropped;
|
||||
- `[[Wikilinks]]` and links to KB paths become plain text, because they'd be
|
||||
dead in a Word file (say "keep the links" to keep them); web links stay;
|
||||
- code blocks, tables, task lists and images come through as they are.
|
||||
|
||||
## Settings
|
||||
|
||||
In `ckb.yaml`, under the module's entry. Change them by asking ("make PDF
|
||||
the default", "always add a table of contents"):
|
||||
|
||||
```yaml
|
||||
config:
|
||||
style: house # templates/styles/house.docx
|
||||
format: docx # docx | odt | pdf | html
|
||||
out_dir: outputs/documents/ # a file already in outputs/ converts beside itself
|
||||
toc: false
|
||||
number_sections: false
|
||||
keep_links: false
|
||||
```
|
||||
|
||||
## Requirements
|
||||
|
||||
- **pandoc**, for every conversion. The install doesn't need it, so a
|
||||
teammate without it can still clone the KB; they're told how to get it the
|
||||
first time they convert.
|
||||
- **LibreOffice**, optional, for PDF and ODT in the house style.
|
||||
- Python 3.8+ like every other KB script. Nothing is installed without asking.
|
||||
|
||||
## Good to know
|
||||
|
||||
- **Fonts aren't embedded** in a `.docx`. Choose fonts your readers have.
|
||||
- **Uninstalling keeps your styles**: `templates/styles/` stays.
|
||||
- **Macro templates** (`.docm`, `.dotm`) are refused; save a copy as `.docx`
|
||||
or `.dotx` first.
|
||||
86
.agents/modules/convert/README.pl.md
Normal file
86
.agents/modules/convert/README.pl.md
Normal file
|
|
@ -0,0 +1,86 @@
|
|||
# Moduł `convert`
|
||||
|
||||
*Przeczytaj w: [English](README.md) | **Polski***
|
||||
|
||||
Opcjonalny. Instalacja: „install the convert module”, usunięcie: „uninstall
|
||||
the convert module”. Dopóki nie jest zainstalowany, nic z tego folderu nie
|
||||
działa.
|
||||
|
||||
## Co robi
|
||||
|
||||
Baza pisze w Markdownie. Ludzie, do których coś wysyłasz, chcą pliku Worda
|
||||
albo PDF-a, który wygląda jak reszta dokumentów w firmie. Ten moduł zamienia
|
||||
dowolny plik Markdown z bazy na **`.docx`, `.odt`, PDF lub HTML** przez
|
||||
[pandoc](https://pandoc.org), w **stylu firmowym**, więc nikt nie dobiera
|
||||
ręcznie czcionek, rozmiarów ani marginesów.
|
||||
|
||||
| Skill | Co robi |
|
||||
|---|---|
|
||||
| `ckb-convert` | Konwertuje plik w wybranym stylu; tworzy styl z kilku ustawień albo z firmowego szablonu Worda; zmienia, sprawdza i wypisuje style. |
|
||||
|
||||
Powiedz „give me the status report as a Word file” albo „convert this answer
|
||||
to PDF”. Za pierwszym razem padnie jedno pytanie o to, jak ma wyglądać styl
|
||||
firmowy.
|
||||
|
||||
## Style
|
||||
|
||||
Styl to plik Worda, `templates/styles/<nazwa>.docx`. pandoc bierze z niego
|
||||
czcionki, rozmiary, kolory, odstępy, format strony, marginesy, nagłówek i
|
||||
stopkę, a jego treść pomija. Styl można zdobyć na trzy sposoby:
|
||||
|
||||
- **Opisać go**: „make a house style with Georgia 11pt, navy headings, A4”.
|
||||
- **Przynieść własny**: „use Company.dotx as the house style”. Agent go
|
||||
skopiuje i powie, których stylów potrzebnych pandocowi brakuje w szablonie.
|
||||
- **Poprawić ręcznie** w Wordzie lub LibreOffice: zmieniać *style* (Normal,
|
||||
Body Text, Title, Heading 1–6, Table), nie treść, i zapisać jako `.docx`.
|
||||
|
||||
Stylów może być kilka („convert it in the board style”). `<nazwa>.css`
|
||||
ustala wygląd HTML, a opcjonalny `<nazwa>.odt` wygląd ODT.
|
||||
|
||||
PDF i ODT powstają ze sformatowanego `.docx` przez LibreOffice, więc
|
||||
wszystkie formaty wyglądają tak samo. Bez LibreOffice PDF robi silnik PDF
|
||||
pandoca i styl Worda nie jest stosowany. Agent o tym powie.
|
||||
|
||||
## Co się zmienia po drodze
|
||||
|
||||
Plik Markdown nigdy się nie zmienia i zawsze zostaje. W skonwertowanej
|
||||
kopii:
|
||||
|
||||
- frontmatter staje się tytułem, autorem (bez adresu e-mail) i datą, a
|
||||
pierwszy nagłówek `#` staje się tytułem, gdy frontmatter go nie ma;
|
||||
- komentarze `<!-- … -->` pozostałe z szablonu znikają;
|
||||
- `[[Wikilinki]]` i linki do ścieżek w bazie stają się zwykłym tekstem, bo w
|
||||
pliku Worda byłyby martwe („keep the links” je zostawia); linki do stron
|
||||
WWW zostają;
|
||||
- bloki kodu, tabele, listy zadań i obrazy przechodzą bez zmian.
|
||||
|
||||
## Ustawienia
|
||||
|
||||
W `ckb.yaml`, we wpisie modułu. Zmienia się je prośbą („make PDF the
|
||||
default”, „always add a table of contents”):
|
||||
|
||||
```yaml
|
||||
config:
|
||||
style: house # templates/styles/house.docx
|
||||
format: docx # docx | odt | pdf | html
|
||||
out_dir: outputs/documents/ # plik już leżący w outputs/ trafia obok siebie
|
||||
toc: false
|
||||
number_sections: false
|
||||
keep_links: false
|
||||
```
|
||||
|
||||
## Wymagania
|
||||
|
||||
- **pandoc** do każdej konwersji. Instalacja modułu go nie wymaga, więc
|
||||
osoba z zespołu bez pandoca nadal może sklonować bazę; przy pierwszej
|
||||
konwersji dowie się, jak go zainstalować.
|
||||
- **LibreOffice**, opcjonalnie, do PDF i ODT w stylu firmowym.
|
||||
- Python 3.8+, jak każdy skrypt bazy. Nic nie jest instalowane bez pytania.
|
||||
|
||||
## Warto wiedzieć
|
||||
|
||||
- **Czcionki nie są osadzane** w `.docx`. Wybieraj czcionki, które mają
|
||||
czytelnicy.
|
||||
- **Odinstalowanie zostawia style**: `templates/styles/` zostaje.
|
||||
- **Szablony z makrami** (`.docm`, `.dotm`) są odrzucane; najpierw zapisz
|
||||
kopię jako `.docx` lub `.dotx`.
|
||||
16
.agents/modules/convert/fragments/agents-routing.md
Normal file
16
.agents/modules/convert/fragments/agents-routing.md
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
## MODULE: convert
|
||||
|
||||
Markdown in this KB becomes Word, ODT, PDF or HTML through pandoc, in a house
|
||||
style: `templates/styles/<name>.docx`. Settings are under the `convert`
|
||||
entry of `kb_modules:` in `ckb.yaml`.
|
||||
|
||||
- A request for a document as `.docx`, `.odt`, `.pdf` or `.html` ("as a Word
|
||||
file", "send me a PDF") goes through `ckb-convert`, after the Markdown is
|
||||
final (after `ckb-voice`, when that module is installed). The Markdown is
|
||||
always kept beside the converted file.
|
||||
- Styles are the user's files: create or change one only on request, and
|
||||
never edit a style the user supplied (`--from`) unless asked.
|
||||
|
||||
| User intent | Skill |
|
||||
|---|---|
|
||||
| Convert Markdown to Word/ODT/PDF/HTML, or create, change, check or list a house style | `ckb-convert` |
|
||||
1
.agents/modules/convert/fragments/gitignore.snippet
Normal file
1
.agents/modules/convert/fragments/gitignore.snippet
Normal file
|
|
@ -0,0 +1 @@
|
|||
# convert module: nothing extra to ignore (styles in templates/styles/ are tracked).
|
||||
56
.agents/modules/convert/module.yaml
Normal file
56
.agents/modules/convert/module.yaml
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
# Cascade KB module manifest — read by `ckb-module` on install/uninstall.
|
||||
# See docs/decisions/0021-convert-module.md.
|
||||
name: convert
|
||||
title: Document conversion with house styles
|
||||
version: 1.0.0
|
||||
requires_kb_schema: "1.7"
|
||||
summary: >
|
||||
Turns any Markdown file in the KB (a document from a template, a kept
|
||||
answer, a report, a wiki page) into Word, OpenDocument, PDF or HTML through
|
||||
pandoc, in a named house style kept in templates/styles/, so nobody has to
|
||||
pick fonts, sizes or margins by hand.
|
||||
|
||||
skills:
|
||||
- ckb-convert
|
||||
|
||||
# Created on install, never removed on uninstall: it holds the user's styles.
|
||||
scaffold:
|
||||
- path: templates/styles/
|
||||
from: scaffold/styles-README.md
|
||||
as: templates/styles/README.md
|
||||
note: House styles, one NAME.docx per style (NAME.odt and NAME.css optional).
|
||||
|
||||
agents_fragment: fragments/agents-routing.md
|
||||
gitignore_fragment: fragments/gitignore.snippet
|
||||
|
||||
# Written under this module's `config:` in ckb.yaml on install; ckb-convert
|
||||
# owns them afterwards ("make PDF the default", "use the board style").
|
||||
default_config:
|
||||
style: house # templates/styles/<style>.docx, used when the request names none
|
||||
format: docx # docx | odt | pdf | html
|
||||
out_dir: outputs/documents/ # for files outside outputs/; a file in outputs/ converts beside itself
|
||||
toc: false # table of contents
|
||||
number_sections: false
|
||||
keep_links: false # true = keep links to KB paths (dead outside the KB)
|
||||
|
||||
schema_additions:
|
||||
types: []
|
||||
fields: []
|
||||
|
||||
depends_on:
|
||||
- name: pandoc
|
||||
scope: all
|
||||
check: "command -v pandoc"
|
||||
optional: true
|
||||
note: >
|
||||
Does every conversion, so nothing converts without it. Optional only for
|
||||
the install: the module is committed and shared, and a teammate without
|
||||
pandoc is told how to get it when they first convert. Never installed
|
||||
without asking.
|
||||
- name: libreoffice
|
||||
scope: pdf-and-odt
|
||||
check: "command -v soffice || command -v libreoffice"
|
||||
optional: true
|
||||
note: >
|
||||
Turns the styled .docx into PDF or ODT so every format looks the same.
|
||||
Without it PDF needs a pandoc PDF engine and ignores the Word style.
|
||||
26
.agents/modules/convert/scaffold/styles-README.md
Normal file
26
.agents/modules/convert/scaffold/styles-README.md
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
# House styles
|
||||
|
||||
One file per style, used by `ckb-convert` (the `convert` module) to turn
|
||||
Markdown into Word, OpenDocument, PDF or HTML:
|
||||
|
||||
| File | Used for | Required |
|
||||
|---|---|---|
|
||||
| `<name>.docx` | Word, and PDF/ODT made from it with LibreOffice | yes |
|
||||
| `<name>.odt` | ODT, when you want a separate LibreOffice style | no |
|
||||
| `<name>.css` | HTML | no |
|
||||
|
||||
pandoc takes fonts, sizes, colours, spacing, page size, margins, header and
|
||||
footer from the `.docx` and ignores any text in it.
|
||||
|
||||
Three ways to get a style:
|
||||
|
||||
- **Say what you want**: "make a house style with Georgia 11pt, navy
|
||||
headings, A4". The agent builds the `.docx`.
|
||||
- **Use your company's template**: "use Company.dotx as the house style". The
|
||||
agent copies it here and tells you which styles pandoc needs that it lacks.
|
||||
- **Edit by hand**: open `<name>.docx` in Word or LibreOffice, change the
|
||||
*styles* (Normal, Body Text, Title, Heading 1–6, Table…), not the text, and
|
||||
save it as `.docx`.
|
||||
|
||||
Fonts aren't embedded in a `.docx`. Choose fonts your readers have, or
|
||||
they'll see a substitute.
|
||||
151
.agents/modules/convert/skills/ckb-convert/SKILL.md
Normal file
151
.agents/modules/convert/skills/ckb-convert/SKILL.md
Normal file
|
|
@ -0,0 +1,151 @@
|
|||
---
|
||||
name: ckb-convert
|
||||
description: Convert a Markdown file from the KB (a document from a template, a kept answer, a report, a wiki page) into Word .docx, OpenDocument .odt, PDF or HTML through pandoc, in a house style kept in templates/styles/ so fonts, sizes, colours and margins are never picked by hand; also creates, changes, checks and lists house styles, including one made from a company .docx/.dotx. Use for "convert this to Word", "give me this as a docx/PDF", "export the status report as a Word file", "make a house style with Georgia and navy headings", "use our company template for documents", "list the styles", "make PDF the default".
|
||||
---
|
||||
|
||||
# Convert skill (module: convert)
|
||||
|
||||
## Purpose
|
||||
|
||||
People outside the KB want a Word file or a PDF that looks like the rest of
|
||||
their company's documents. pandoc does the conversion; the look comes from a
|
||||
**style**, a reference `.docx` in `templates/styles/<name>.docx` that the
|
||||
user never has to open. The Markdown stays the source: it's always kept, and
|
||||
the converted file is made from it again whenever it changes.
|
||||
|
||||
Nothing here touches `wiki/`, so Rule B doesn't apply; Rule D does.
|
||||
|
||||
## Settings
|
||||
|
||||
Under the `convert` entry of `kb_modules:` in `ckb.yaml`, `config:`:
|
||||
|
||||
| Key | Default | Meaning |
|
||||
|---|---|---|
|
||||
| `style` | `house` | Style used when the request names none |
|
||||
| `format` | `docx` | `docx`, `odt`, `pdf` or `html` when the request names none |
|
||||
| `out_dir` | `outputs/documents/` | Where a file from outside `outputs/` is written; a file already in `outputs/` converts beside itself |
|
||||
| `toc` | `false` | Add a table of contents |
|
||||
| `number_sections` | `false` | Number the headings |
|
||||
| `keep_links` | `false` | Keep links to KB paths, which are dead in a Word file |
|
||||
|
||||
The request wins over a setting ("as a PDF", "with a table of contents").
|
||||
"Make PDF the default" or "use the board style by default" edits only that
|
||||
key's value in `ckb.yaml` and says so in one line.
|
||||
|
||||
## The script
|
||||
|
||||
```bash
|
||||
<python> .agents/skills/ckb-convert/scripts/convert.py <command> …
|
||||
```
|
||||
|
||||
Resolve `<python>` per "Scripts and the Python Runtime" in `AGENTS.md`. Run it
|
||||
from the KB root (or pass `--root`). Exit codes: `0` done, `1` refused (the
|
||||
message says why), `3` a program is missing or failed.
|
||||
|
||||
| Command | Does |
|
||||
|---|---|
|
||||
| `doctor` | pandoc version, LibreOffice, how PDF will be made, styles present |
|
||||
| `styles` | Lists `templates/styles/` |
|
||||
| `convert FILE --to FMT --style NAME [--toc] [--number-sections] [--keep-links] [--out PATH \| --out-dir DIR] [--force]` | Converts one file |
|
||||
| `new-style NAME [--from FILE] [settings]` | Creates a style from pandoc's default, or from a company `.docx`/`.dotx` |
|
||||
| `edit-style NAME settings` | Changes a style |
|
||||
| `check-style NAME` | Lists the styles pandoc uses that NAME doesn't define |
|
||||
|
||||
Settings: `--body-font F`, `--heading-font F`, `--size PT` (body text),
|
||||
`--heading-color RRGGBB`, `--paper a4|letter`, `--margin-cm CM`.
|
||||
|
||||
## How to run this skill
|
||||
|
||||
### Step 1 — Check the tools once per session
|
||||
|
||||
Run `doctor`. If pandoc is missing, stop and tell the user how to install it
|
||||
on their system (the error names the commands). Never install it yourself.
|
||||
If LibreOffice is missing and they asked for PDF or ODT, say once that the
|
||||
file won't follow the Word style and how to install LibreOffice, then go on.
|
||||
|
||||
### Step 2 — Make sure there's a style
|
||||
|
||||
If the style to use exists, go to Step 3. If `templates/styles/` has no style
|
||||
at all, ask **one** question before converting:
|
||||
|
||||
> There's no house style yet. Use a plain default (Calibri 11pt, dark-blue
|
||||
> headings, A4), tell me fonts/colours/paper, or give me your company's Word
|
||||
> template (.docx or .dotx)?
|
||||
|
||||
- Default: `new-style house --body-font Calibri --heading-font Calibri
|
||||
--size 11 --heading-color 1F3864 --paper a4 --margin-cm 2.5`.
|
||||
- Their own settings: the same command with their values. A colour named in
|
||||
words becomes hex ("navy" → `1F3864`); a page size other than A4/Letter isn't
|
||||
supported, so say so and use the closer one.
|
||||
- A company template: `new-style house --from <file>`. Report the `check:`
|
||||
lines it prints in plain words: a missing *Heading 1* means headings will
|
||||
use pandoc's look, not the company's. Offer to fill only the missing ones
|
||||
with settings (`edit-style`), never to change the ones that exist.
|
||||
|
||||
If other styles exist but not the one named, list them and ask which to use.
|
||||
|
||||
### Step 3 — Convert
|
||||
|
||||
Check that the Markdown is final first. If it was just written and the `voice`
|
||||
module is installed, the voice pass comes before conversion.
|
||||
|
||||
```bash
|
||||
<python> .agents/skills/ckb-convert/scripts/convert.py convert <file.md> --to <fmt> --style <style> [flags from settings]
|
||||
```
|
||||
|
||||
Several files, or several formats of one file: one call each.
|
||||
|
||||
- **`refused: exists`** — the converted file is already there. Ask once:
|
||||
replace it (`--force`) or keep both (`--out` with `-2` before the
|
||||
extension). A file made earlier may have been edited in Word since.
|
||||
- **`note:` lines** — pass them on in plain words. A `pandoc:` note about a
|
||||
missing image names the file; check the path.
|
||||
|
||||
What the script changes on the way, so you can explain it if asked: the
|
||||
frontmatter becomes the title, author (without the e-mail) and date; the
|
||||
first `# Heading` becomes the title when the frontmatter has none; `<!--
|
||||
comments -->` are dropped; `[[Wikilinks]]` and links to KB paths become plain
|
||||
text (`--keep-links` keeps the links); web links stay; code blocks stay as
|
||||
they are. Sections such as `## Sources` are content and stay. If the reader
|
||||
shouldn't see them, offer a copy of the Markdown without them, and never edit
|
||||
the original for that.
|
||||
|
||||
### Step 4 — Report
|
||||
|
||||
One line per file: path, format, style. Add the notes that matter. For a
|
||||
`.docx` with `--toc`, say the reader may have to accept "update fields" when
|
||||
Word opens it. Offer nothing else.
|
||||
|
||||
## Changing a style
|
||||
|
||||
"Make the headings green", "use Georgia", "switch to Letter paper":
|
||||
`edit-style <name>` with only the settings asked for, then offer to
|
||||
reconvert the last file. Ask first if the style came from the user's own
|
||||
template (`--from`): they may want their file left as it is.
|
||||
|
||||
For anything the settings can't do (a logo in the header, a cover page, line
|
||||
spacing, table borders), tell the user to open `templates/styles/<name>.docx`
|
||||
in Word or LibreOffice, change the **styles** (not the text), and save it as
|
||||
`.docx`. pandoc reads fonts, sizes, colours, spacing, page size, margins,
|
||||
header and footer from it and ignores its text.
|
||||
|
||||
`.odt` and `.css` styles are optional and hand-made: `NAME.odt` is used for
|
||||
ODT instead of going through LibreOffice, and `NAME.css` for HTML.
|
||||
|
||||
## Edge cases
|
||||
|
||||
- **The file isn't Markdown** (a `.docx` to turn into PDF): pandoc can't keep
|
||||
the look that way. Offer LibreOffice directly (`soffice --headless
|
||||
--convert-to pdf`) or the general document skills.
|
||||
- **A wiki page** is converted like any file. The output goes to `out_dir`,
|
||||
never into `wiki/`.
|
||||
- **Mermaid diagrams** stay as code blocks; pandoc doesn't draw them. Say so
|
||||
if the file has one.
|
||||
- **Fonts aren't embedded** in `.docx`. A font the reader lacks shows as a
|
||||
substitute; in PDF, LibreOffice substitutes on this machine. Suggest common
|
||||
fonts if the user picks something rare.
|
||||
- **A `.docm`/`.dotm`** (macros) is refused: ask for a copy saved as `.docx`
|
||||
or `.dotx`.
|
||||
- **Without Python**: run pandoc by hand,
|
||||
`pandoc <file.md> -o <out.docx> --reference-doc templates/styles/<style>.docx`,
|
||||
and say the KB clean-up (frontmatter, wikilinks, comments) was skipped.
|
||||
746
.agents/modules/convert/skills/ckb-convert/scripts/convert.py
Normal file
746
.agents/modules/convert/skills/ckb-convert/scripts/convert.py
Normal file
|
|
@ -0,0 +1,746 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Turn a KB Markdown file into a Word, OpenDocument, PDF or HTML file in a
|
||||
house style, through pandoc. The style is a file the user never has to open:
|
||||
|
||||
convert.py convert FILE.md [--to docx|odt|pdf|html] [--style NAME] [--out PATH]
|
||||
[--out-dir DIR] [--toc] [--number-sections]
|
||||
[--keep-links] [--force]
|
||||
convert.py new-style NAME [--from FILE.docx|.dotx] [--body-font F] [--heading-font F]
|
||||
[--size PT] [--heading-color RRGGBB] [--paper a4|letter]
|
||||
[--margin-cm CM] [--force]
|
||||
convert.py edit-style NAME [same options as new-style, without --from]
|
||||
convert.py check-style NAME # which styles pandoc uses are missing from NAME.docx
|
||||
convert.py styles # list templates/styles/
|
||||
convert.py doctor # pandoc, LibreOffice, PDF route
|
||||
|
||||
Styles live in templates/styles/: NAME.docx (the Word reference document,
|
||||
required), NAME.odt and NAME.css (optional, for odt and html). pandoc takes
|
||||
fonts, sizes, colours, spacing, page size, margins, header and footer from the
|
||||
reference document and ignores its text.
|
||||
|
||||
Before conversion the Markdown is cleaned for a reader outside the KB: the
|
||||
frontmatter becomes title/author/date/lang metadata, the first `# H1` becomes
|
||||
the title when the frontmatter has none, HTML comments are dropped,
|
||||
[[Wikilinks]] become plain text, and links to KB paths become their label
|
||||
(they would be dead in a Word file; --keep-links keeps them). Code blocks are
|
||||
never touched.
|
||||
|
||||
PDF and ODT go through the Word style: pandoc writes the .docx and LibreOffice
|
||||
converts it, so all formats look the same. Without LibreOffice, PDF falls back
|
||||
to a pandoc PDF engine (style not applied, said so) and ODT to pandoc's own.
|
||||
|
||||
Exit 0 = written, 1 = refused (output exists, unknown style, bad input),
|
||||
2 = usage, 3 = a required program is missing or failed.
|
||||
Python 3.8+, standard library only; needs pandoc, optionally LibreOffice.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import zipfile
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
|
||||
STYLES_DIR = Path("templates") / "styles"
|
||||
DEFAULT_OUT_DIR = Path("outputs") / "documents"
|
||||
FORMATS = ("docx", "odt", "pdf", "html")
|
||||
PDF_ENGINES = ("typst", "weasyprint", "wkhtmltopdf", "xelatex", "lualatex", "pdflatex")
|
||||
SOFFICE_TIMEOUT = 180
|
||||
|
||||
# The paragraph/character/table styles pandoc's docx writer uses. A reference
|
||||
# document without one of them gets pandoc's own definition for it.
|
||||
PANDOC_STYLES = [
|
||||
"Normal", "Body Text", "First Paragraph", "Compact", "Title", "Subtitle", "Author",
|
||||
"Date", "Abstract", "heading 1", "heading 2", "heading 3", "heading 4", "heading 5",
|
||||
"heading 6", "Block Text", "Source Code", "Verbatim Char", "Hyperlink", "Footnote Text",
|
||||
"Footnote Reference", "Caption", "Table Caption", "Image Caption", "Table", "TOC Heading",
|
||||
]
|
||||
KEY_STYLES = {"Normal", "Body Text", "Title", "heading 1", "heading 2", "heading 3", "Table"}
|
||||
|
||||
# Child order inside <w:rPr> and <w:sectPr> (ECMA-376). Word rejects a file
|
||||
# whose children are out of order, so inserts respect it.
|
||||
RPR_ORDER = ("rStyle rFonts b bCs i iCs caps smallCaps strike dstrike outline shadow emboss "
|
||||
"imprint noProof snapToGrid vanish webHidden color spacing w kern position sz szCs "
|
||||
"highlight u effect bdr shd fitText vertAlign rtl cs em lang eastAsianLayout "
|
||||
"specVanish oMath").split()
|
||||
SECTPR_ORDER = ("headerReference footerReference footnotePr endnotePr type pgSz pgMar paperSrc "
|
||||
"pgBorders lnNumType pgNumType cols formProt vAlign noEndnote titlePg "
|
||||
"textDirection bidi rtlGutter docGrid printerSettings sectPrChange").split()
|
||||
PAPER = {"a4": (11906, 16838), "letter": (12240, 15840)}
|
||||
HEADING_STYLE_IDS = ["Title", "Subtitle"] + ["Heading%d" % i for i in range(1, 10)]
|
||||
DOCX_CT = "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"
|
||||
DOTX_CT = "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml"
|
||||
|
||||
|
||||
class Refused(Exception):
|
||||
"""Exit 1 with a message."""
|
||||
|
||||
|
||||
class Missing(Exception):
|
||||
"""Exit 3 with a message."""
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- tools
|
||||
|
||||
def pandoc_version():
|
||||
exe = shutil.which("pandoc")
|
||||
if not exe:
|
||||
return None
|
||||
try:
|
||||
out = subprocess.run([exe, "--version"], capture_output=True, timeout=30,
|
||||
encoding="utf-8", errors="replace").stdout
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
return None
|
||||
m = re.search(r"pandoc(?:\.exe)?\s+(\d+(?:\.\d+)*)", out)
|
||||
return tuple(int(x) for x in m.group(1).split(".")) if m else (0,)
|
||||
|
||||
|
||||
def soffice():
|
||||
for name in ("soffice", "libreoffice"):
|
||||
exe = shutil.which(name)
|
||||
if exe:
|
||||
return exe
|
||||
for p in ("/Applications/LibreOffice.app/Contents/MacOS/soffice",
|
||||
r"C:\Program Files\LibreOffice\program\soffice.exe",
|
||||
r"C:\Program Files (x86)\LibreOffice\program\soffice.exe"):
|
||||
if Path(p).exists():
|
||||
return p
|
||||
return None
|
||||
|
||||
|
||||
def need_pandoc():
|
||||
v = pandoc_version()
|
||||
if v is None:
|
||||
raise Missing("pandoc not found. Install it from https://pandoc.org/installing.html "
|
||||
"(Fedora: dnf install pandoc; Debian/Ubuntu: apt install pandoc; "
|
||||
"macOS: brew install pandoc; Windows: winget install JohnMacFarlane.Pandoc).")
|
||||
return v
|
||||
|
||||
|
||||
def run(cmd, timeout=300):
|
||||
try:
|
||||
p = subprocess.run(cmd, capture_output=True, timeout=timeout, encoding="utf-8", errors="replace")
|
||||
except subprocess.TimeoutExpired:
|
||||
raise Missing("%s timed out after %ds" % (Path(cmd[0]).name, timeout))
|
||||
except OSError as e:
|
||||
raise Missing("could not run %s: %s" % (cmd[0], e))
|
||||
if p.returncode != 0:
|
||||
raise Missing("%s failed (exit %d):\n%s" % (Path(cmd[0]).name, p.returncode,
|
||||
(p.stderr or p.stdout).strip()))
|
||||
return p
|
||||
|
||||
|
||||
def soffice_convert(exe, src, fmt, workdir):
|
||||
"""Convert src with LibreOffice into workdir; return the new file's path.
|
||||
A private profile keeps it from colliding with a LibreOffice the user has open."""
|
||||
profile = (Path(workdir) / "lo-profile").resolve().as_uri()
|
||||
outdir = Path(workdir) / ("lo-out-" + fmt)
|
||||
outdir.mkdir(exist_ok=True)
|
||||
run([exe, "-env:UserInstallation=" + profile, "--headless", "--norestore",
|
||||
"--convert-to", fmt, "--outdir", str(outdir), str(src)], timeout=SOFFICE_TIMEOUT)
|
||||
out = outdir / (Path(src).stem + "." + fmt)
|
||||
if not out.exists():
|
||||
raise Missing("LibreOffice did not produce %s (is another conversion stuck?)" % out.name)
|
||||
return out
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- Markdown
|
||||
|
||||
def split_frontmatter(text):
|
||||
if not text.startswith("---\n"):
|
||||
return {}, text
|
||||
end = text.find("\n---", 4)
|
||||
if end < 0:
|
||||
return {}, text
|
||||
meta = {}
|
||||
for line in text[4:end].split("\n"):
|
||||
m = re.match(r"^([A-Za-z_][\w-]*):\s*(.*?)\s*$", line)
|
||||
if m:
|
||||
v = m.group(2)
|
||||
if len(v) >= 2 and v[0] == v[-1] and v[0] in "\"'":
|
||||
v = v[1:-1]
|
||||
meta[m.group(1)] = v
|
||||
rest = text[end + 4:]
|
||||
return meta, rest[1:] if rest.startswith("\n") else rest
|
||||
|
||||
|
||||
def split_fences(body):
|
||||
"""Yield (is_code, chunk). Fenced code blocks are passed through untouched."""
|
||||
out, buf, fence = [], [], None
|
||||
for line in body.split("\n"):
|
||||
m = re.match(r"^\s{0,3}(`{3,}|~{3,})", line)
|
||||
if fence is None and m:
|
||||
if buf:
|
||||
out.append((False, "\n".join(buf)))
|
||||
buf, fence = [line], m.group(1)
|
||||
elif fence is not None and re.match(r"^\s{0,3}" + re.escape(fence[0]) + "{%d,}\\s*$" % len(fence), line):
|
||||
buf.append(line)
|
||||
out.append((True, "\n".join(buf)))
|
||||
buf, fence = [], None
|
||||
else:
|
||||
buf.append(line)
|
||||
if buf:
|
||||
out.append((fence is not None, "\n".join(buf)))
|
||||
return out
|
||||
|
||||
|
||||
def is_external(target):
|
||||
return bool(re.match(r"^(?:[a-z][a-z0-9+.-]*:|#)", target, re.I))
|
||||
|
||||
|
||||
def wikilink_text(m):
|
||||
target, label = m.group(1), m.group(2)
|
||||
return label or target.rstrip("/").split("/")[-1].replace(".md", "")
|
||||
|
||||
|
||||
def clean_prose(text, keep_links):
|
||||
text = re.sub(r"<!--.*?-->\n?", "", text, flags=re.S)
|
||||
# Rule C pairs a wikilink with a Markdown link to the same page: keep one label.
|
||||
def pair(m):
|
||||
label = wikilink_text(m)
|
||||
return "[%s](%s)" % (label, m.group(3)) if keep_links else label
|
||||
text = re.sub(r"\[\[([^\]|\n]+)(?:\|([^\]\n]+))?\]\]\s*\(\[[^\]\n]*\]\(([^)\s]+)\)\)", pair, text)
|
||||
text = re.sub(r"\[\[([^\]|\n]+)(?:\|([^\]\n]+))?\]\]", wikilink_text, text)
|
||||
if not keep_links:
|
||||
def local(m):
|
||||
return m.group(0) if is_external(m.group(2)) else m.group(1)
|
||||
text = re.sub(r"(?<!!)\[([^\]\n]+)\]\(([^)\s]+)(?:\s+\"[^\"]*\")?\)", local, text)
|
||||
return text
|
||||
|
||||
|
||||
def prepare(text, keep_links):
|
||||
"""Return (metadata for pandoc, cleaned Markdown body)."""
|
||||
fm, body = split_frontmatter(text.lstrip("\ufeff").replace("\r\n", "\n"))
|
||||
meta = {}
|
||||
title = fm.get("title", "").strip()
|
||||
if not title:
|
||||
m = re.search(r"^# +(.+?)\s*#*\s*$", body, re.M)
|
||||
if m and not body[:m.start()].strip().strip("-").strip():
|
||||
title = m.group(1).strip()
|
||||
body = body[:m.start()] + body[m.end():].lstrip("\n")
|
||||
if title:
|
||||
meta["title"] = re.sub(r"\[\[([^\]|]+)(?:\|([^\]]+))?\]\]", wikilink_text, title)
|
||||
for key in ("subtitle",):
|
||||
if fm.get(key):
|
||||
meta[key] = fm[key]
|
||||
author = fm.get("author", "").strip()
|
||||
if author:
|
||||
meta["author"] = re.sub(r"\s*<[^>]*>", "", author).strip()
|
||||
when = fm.get("date") or fm.get("created") or ""
|
||||
if when:
|
||||
meta["date"] = when
|
||||
if fm.get("lang"):
|
||||
meta["lang"] = fm["lang"]
|
||||
parts = [chunk if code else clean_prose(chunk, keep_links) for code, chunk in split_fences(body)]
|
||||
return meta, "\n".join(parts).strip("\n") + "\n"
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- docx XML
|
||||
|
||||
def children(inner):
|
||||
"""Direct <w:*> children of an element's inner XML as (name, start, end)."""
|
||||
out, pos = [], 0
|
||||
tag = re.compile(r"<w:([A-Za-z]+)\b[^>]*?(/?)>")
|
||||
while True:
|
||||
m = tag.search(inner, pos)
|
||||
if not m:
|
||||
return out
|
||||
if m.group(2) == "/":
|
||||
end = m.end()
|
||||
else:
|
||||
close = inner.find("</w:%s>" % m.group(1), m.end())
|
||||
end = len(inner) if close < 0 else close + len(m.group(1)) + 6
|
||||
out.append((m.group(1), m.start(), end))
|
||||
pos = end
|
||||
|
||||
|
||||
def set_child(inner, name, element, order):
|
||||
"""Replace every <w:name> child with element, placed in schema order."""
|
||||
for n, s, e in reversed(children(inner)):
|
||||
if n == name:
|
||||
inner = inner[:s] + inner[e:]
|
||||
rank = order.index(name)
|
||||
kids = children(inner)
|
||||
for n, s, _ in kids:
|
||||
if n in order and order.index(n) > rank:
|
||||
return inner[:s] + element + inner[s:]
|
||||
known = [e for n, _, e in kids if n in order]
|
||||
at = known[-1] if known else len(inner)
|
||||
return inner[:at] + element + inner[at:]
|
||||
|
||||
|
||||
def edit_block(xml, open_re, tag, fn):
|
||||
"""Apply fn to the inner XML of the first <w:tag> matched by open_re."""
|
||||
m = re.search(open_re, xml, re.S)
|
||||
if not m:
|
||||
return xml, False
|
||||
if m.group(0).endswith("/>"):
|
||||
new = "<w:%s>%s</w:%s>" % (tag, fn(""), tag)
|
||||
return xml[:m.start()] + new + xml[m.end():], True
|
||||
close = xml.find("</w:%s>" % tag, m.end())
|
||||
return xml[:m.end()] + fn(xml[m.end():close]) + xml[close:], True
|
||||
|
||||
|
||||
def style_span(xml, style_id):
|
||||
m = re.search(r'<w:style\b[^>]*w:styleId="%s"[^>]*>' % re.escape(style_id), xml)
|
||||
if not m:
|
||||
return None
|
||||
return m.start(), xml.find("</w:style>", m.end()) + len("</w:style>")
|
||||
|
||||
|
||||
def edit_style_rpr(xml, style_id, edits):
|
||||
span = style_span(xml, style_id)
|
||||
if not span:
|
||||
return xml, False
|
||||
block = xml[span[0]:span[1]]
|
||||
if not re.search(r"<w:rPr\s*/?>", block):
|
||||
block = block[:-len("</w:style>")] + "<w:rPr></w:rPr></w:style>"
|
||||
|
||||
def apply(inner):
|
||||
for name, element in edits:
|
||||
inner = set_child(inner, name, element, RPR_ORDER)
|
||||
return inner
|
||||
block, _ = edit_block(block, r"<w:rPr\s*/?>", "rPr", apply)
|
||||
return xml[:span[0]] + block + xml[span[1]:], True
|
||||
|
||||
|
||||
def fonts_el(font):
|
||||
f = xml_attr(font)
|
||||
return '<w:rFonts w:ascii="%s" w:hAnsi="%s" w:eastAsia="%s" w:cs="%s"/>' % (f, f, f, f)
|
||||
|
||||
|
||||
def xml_attr(s):
|
||||
return s.replace("&", "&").replace('"', """).replace("<", "<")
|
||||
|
||||
|
||||
def patch_styles(xml, opts, notes):
|
||||
rpr_edits = []
|
||||
if opts.body_font:
|
||||
rpr_edits.append(("rFonts", fonts_el(opts.body_font)))
|
||||
if opts.size:
|
||||
half = str(int(round(opts.size * 2)))
|
||||
rpr_edits += [("sz", '<w:sz w:val="%s"/>' % half), ("szCs", '<w:szCs w:val="%s"/>' % half)]
|
||||
if rpr_edits:
|
||||
def apply(inner):
|
||||
for name, element in rpr_edits:
|
||||
inner = set_child(inner, name, element, RPR_ORDER)
|
||||
return inner
|
||||
m = re.search(r"<w:rPrDefault>(.*?)</w:rPrDefault>", xml, re.S)
|
||||
if m:
|
||||
seg, _ = edit_block(m.group(1) if "<w:rPr" in m.group(1) else "<w:rPr></w:rPr>",
|
||||
r"<w:rPr\s*/?>", "rPr", apply)
|
||||
xml = xml[:m.start(1)] + seg + xml[m.end(1):]
|
||||
else:
|
||||
notes.append("no document defaults found; body font/size set on Normal only")
|
||||
# A template may pin its own font or size on Normal; the request wins there too.
|
||||
xml, _ = edit_style_rpr(xml, "Normal", rpr_edits)
|
||||
heading_edits = []
|
||||
if opts.heading_font:
|
||||
heading_edits.append(("rFonts", fonts_el(opts.heading_font)))
|
||||
if opts.heading_color:
|
||||
heading_edits.append(("color", '<w:color w:val="%s"/>' % opts.heading_color))
|
||||
if heading_edits:
|
||||
found = []
|
||||
for sid in HEADING_STYLE_IDS:
|
||||
xml, ok = edit_style_rpr(xml, sid, heading_edits)
|
||||
if ok:
|
||||
found.append(sid)
|
||||
if not found:
|
||||
notes.append("no Title or Heading styles found; heading settings not applied")
|
||||
return xml
|
||||
|
||||
|
||||
def patch_theme(xml, opts):
|
||||
for which, font in (("major", opts.heading_font), ("minor", opts.body_font)):
|
||||
if font:
|
||||
xml = re.sub(r'(<a:%sFont>\s*<a:latin typeface=")[^"]*(")' % which,
|
||||
lambda m: m.group(1) + xml_attr(font) + m.group(2), xml)
|
||||
return xml
|
||||
|
||||
|
||||
def patch_document(xml, opts):
|
||||
sects = list(re.finditer(r"<w:sectPr\b[^>]*?(/?)>", xml))
|
||||
if not sects:
|
||||
at = xml.rfind("</w:body>")
|
||||
if at < 0:
|
||||
return xml
|
||||
xml = xml[:at] + "<w:sectPr></w:sectPr>" + xml[at:]
|
||||
sects = list(re.finditer(r"<w:sectPr\b[^>]*?(/?)>", xml))
|
||||
m = sects[-1]
|
||||
if m.group(1) == "/":
|
||||
xml = xml[:m.start()] + "<w:sectPr>" + "</w:sectPr>" + xml[m.end():]
|
||||
m = list(re.finditer(r"<w:sectPr\b[^>]*?(/?)>", xml))[-1]
|
||||
close = xml.find("</w:sectPr>", m.end())
|
||||
inner = xml[m.end():close]
|
||||
if opts.paper:
|
||||
w, h = PAPER[opts.paper]
|
||||
inner = set_child(inner, "pgSz", '<w:pgSz w:w="%d" w:h="%d"/>' % (w, h), SECTPR_ORDER)
|
||||
if opts.margin_cm is not None:
|
||||
t = int(round(opts.margin_cm * 567))
|
||||
inner = set_child(inner, "pgMar", '<w:pgMar w:top="%d" w:right="%d" w:bottom="%d" w:left="%d" '
|
||||
'w:header="709" w:footer="709" w:gutter="0"/>' % (t, t, t, t), SECTPR_ORDER)
|
||||
return xml[:m.end()] + inner + xml[close:]
|
||||
|
||||
|
||||
def rewrite_zip(path, edits):
|
||||
"""edits: {member name: function(str) -> str}. Rewrites the zip in place."""
|
||||
tmp = Path(str(path) + ".tmp")
|
||||
with zipfile.ZipFile(path) as zin, zipfile.ZipFile(tmp, "w", zipfile.ZIP_DEFLATED) as zout:
|
||||
for info in zin.infolist():
|
||||
data = zin.read(info.filename)
|
||||
if info.filename in edits:
|
||||
data = edits[info.filename](data.decode("utf-8")).encode("utf-8")
|
||||
zout.writestr(info, data)
|
||||
tmp.replace(path)
|
||||
|
||||
|
||||
def style_settings_given(opts):
|
||||
return any(v is not None for v in (opts.body_font, opts.heading_font, opts.size,
|
||||
opts.heading_color, opts.paper, opts.margin_cm))
|
||||
|
||||
|
||||
def apply_settings(path, opts):
|
||||
notes = []
|
||||
with zipfile.ZipFile(path) as z:
|
||||
names = set(z.namelist())
|
||||
if "word/styles.xml" not in names or "word/document.xml" not in names:
|
||||
raise Refused("%s is not a Word document (no word/styles.xml)" % path)
|
||||
edits = {"word/styles.xml": lambda x: patch_styles(x, opts, notes)}
|
||||
if opts.paper or opts.margin_cm is not None:
|
||||
edits["word/document.xml"] = lambda x: patch_document(x, opts)
|
||||
if "word/theme/theme1.xml" in names and (opts.body_font or opts.heading_font):
|
||||
edits["word/theme/theme1.xml"] = lambda x: patch_theme(x, opts)
|
||||
rewrite_zip(path, edits)
|
||||
return notes
|
||||
|
||||
|
||||
def style_names(path):
|
||||
with zipfile.ZipFile(path) as z:
|
||||
xml = z.read("word/styles.xml").decode("utf-8")
|
||||
return {n.lower() for n in re.findall(r'<w:name w:val="([^"]*)"', xml)}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- commands
|
||||
|
||||
def styles_dir(root):
|
||||
return Path(root) / STYLES_DIR
|
||||
|
||||
|
||||
def valid_name(name):
|
||||
if not re.match(r"^[a-z0-9][a-z0-9-]{0,60}$", name):
|
||||
raise Refused("style name %r: use lower-case letters, digits and hyphens" % name)
|
||||
return name
|
||||
|
||||
|
||||
def cmd_styles(args):
|
||||
d = styles_dir(args.root)
|
||||
found = {}
|
||||
for p in sorted(d.glob("*")) if d.is_dir() else []:
|
||||
if p.suffix.lower() in (".docx", ".odt", ".css"):
|
||||
found.setdefault(p.stem, []).append(p.suffix[1:].lower())
|
||||
if not found:
|
||||
print("no styles in %s" % STYLES_DIR.as_posix())
|
||||
return 0
|
||||
for name, kinds in found.items():
|
||||
flag = "" if "docx" in kinds else " (no .docx: docx and pdf use pandoc's default)"
|
||||
print("%-20s %s%s" % (name, ", ".join(kinds), flag))
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_doctor(args):
|
||||
v = pandoc_version()
|
||||
lo = soffice()
|
||||
engines = [e for e in PDF_ENGINES if shutil.which(e)]
|
||||
print("pandoc: %s" % (".".join(map(str, v)) if v else "MISSING (required)"))
|
||||
print("libreoffice: %s" % (lo or "missing (PDF and ODT will not follow the Word style)"))
|
||||
if lo:
|
||||
print("pdf: via LibreOffice from the styled .docx")
|
||||
elif engines:
|
||||
print("pdf: via pandoc --pdf-engine=%s (Word style not applied)" % engines[0])
|
||||
else:
|
||||
print("pdf: unavailable (install LibreOffice)")
|
||||
print("styles: %s" % (", ".join(sorted(p.stem for p in styles_dir(args.root).glob("*.docx")))
|
||||
if styles_dir(args.root).is_dir() else "none") or "none")
|
||||
return 0 if v else 3
|
||||
|
||||
|
||||
def cmd_new_style(args):
|
||||
name = valid_name(args.name)
|
||||
d = styles_dir(args.root)
|
||||
dest = d / (name + ".docx")
|
||||
if dest.exists() and not args.force:
|
||||
raise Refused("%s exists; use edit-style to change it, or --force to replace it"
|
||||
% dest.relative_to(args.root).as_posix())
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
if args.from_file:
|
||||
src = Path(args.from_file)
|
||||
if not src.is_file():
|
||||
raise Refused("no such file: %s" % src)
|
||||
ext = src.suffix.lower()
|
||||
if ext in (".docm", ".dotm"):
|
||||
raise Refused("%s holds macros; save it as .docx or .dotx (no macros) first" % src.name)
|
||||
if ext not in (".docx", ".dotx"):
|
||||
raise Refused("a style is made from a .docx or .dotx file, not %s" % ext)
|
||||
shutil.copyfile(src, dest)
|
||||
if ext == ".dotx":
|
||||
rewrite_zip(dest, {"[Content_Types].xml": lambda x: x.replace(DOTX_CT, DOCX_CT)})
|
||||
else:
|
||||
need_pandoc()
|
||||
with open(dest, "wb") as f:
|
||||
p = subprocess.run(["pandoc", "--print-default-data-file", "reference.docx"],
|
||||
stdout=f, stderr=subprocess.PIPE, timeout=60)
|
||||
if p.returncode != 0:
|
||||
dest.unlink()
|
||||
raise Missing("pandoc could not print its reference.docx: %s"
|
||||
% p.stderr.decode("utf-8", "replace").strip())
|
||||
notes = apply_settings(dest, args) if style_settings_given(args) else []
|
||||
print("written: %s" % dest.relative_to(args.root).as_posix())
|
||||
for n in notes:
|
||||
print("note: " + n)
|
||||
if args.from_file:
|
||||
report_missing(dest)
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_edit_style(args):
|
||||
name = valid_name(args.name)
|
||||
dest = styles_dir(args.root) / (name + ".docx")
|
||||
if not dest.exists():
|
||||
raise Refused("no style %s; create it with new-style" % name)
|
||||
if not style_settings_given(args):
|
||||
raise Refused("nothing to change: give --body-font, --heading-font, --size, "
|
||||
"--heading-color, --paper or --margin-cm")
|
||||
notes = apply_settings(dest, args)
|
||||
print("updated: %s" % dest.relative_to(args.root).as_posix())
|
||||
for n in notes:
|
||||
print("note: " + n)
|
||||
return 0
|
||||
|
||||
|
||||
def report_missing(path):
|
||||
have = style_names(path)
|
||||
missing = [s for s in PANDOC_STYLES if s.lower() not in have]
|
||||
key = [s for s in missing if s in KEY_STYLES]
|
||||
if not missing:
|
||||
print("check: every style pandoc uses is defined")
|
||||
else:
|
||||
print("check: %d of %d styles pandoc uses are not defined; pandoc adds its own for them:"
|
||||
% (len(missing), len(PANDOC_STYLES)))
|
||||
print(" " + ", ".join(missing))
|
||||
if key:
|
||||
print(" important: " + ", ".join(key))
|
||||
return missing
|
||||
|
||||
|
||||
def cmd_check_style(args):
|
||||
path = styles_dir(args.root) / (valid_name(args.name) + ".docx")
|
||||
if not path.exists():
|
||||
raise Refused("no style %s" % args.name)
|
||||
report_missing(path)
|
||||
return 0
|
||||
|
||||
|
||||
def default_output(root, src, fmt, out_dir):
|
||||
root = Path(root).resolve()
|
||||
src = Path(src).resolve()
|
||||
if out_dir:
|
||||
d = Path(out_dir)
|
||||
d = d if d.is_absolute() else root / d
|
||||
else:
|
||||
try:
|
||||
rel = src.relative_to(root)
|
||||
d = src.parent if rel.parts[:1] == ("outputs",) else root / DEFAULT_OUT_DIR
|
||||
except ValueError:
|
||||
d = root / DEFAULT_OUT_DIR
|
||||
return d / (src.stem + "." + fmt)
|
||||
|
||||
|
||||
def cmd_convert(args):
|
||||
version = need_pandoc()
|
||||
root = Path(args.root).resolve()
|
||||
src = Path(args.file)
|
||||
if not src.is_absolute():
|
||||
src = (Path.cwd() / src).resolve()
|
||||
if not src.is_file():
|
||||
raise Refused("no such file: %s" % args.file)
|
||||
fmt = args.to
|
||||
out = Path(args.out) if args.out else default_output(root, src, fmt, args.out_dir)
|
||||
if not out.is_absolute():
|
||||
out = root / out
|
||||
if out.suffix.lower() != "." + fmt:
|
||||
raise Refused("--out %s does not end in .%s" % (out.name, fmt))
|
||||
if out.exists() and not args.force:
|
||||
raise Refused("exists: %s (--force replaces it, --out writes elsewhere)" % rel(out, root))
|
||||
name = valid_name(args.style)
|
||||
sdir = styles_dir(root)
|
||||
ref_docx = sdir / (name + ".docx")
|
||||
notes = []
|
||||
if not ref_docx.exists():
|
||||
if args.style_required:
|
||||
raise Refused("no style %s in %s" % (name, STYLES_DIR.as_posix()))
|
||||
notes.append("no style %s: used pandoc's default look" % name)
|
||||
ref_docx = None
|
||||
|
||||
meta, body = prepare(src.read_text(encoding="utf-8-sig"), args.keep_links)
|
||||
lo = soffice()
|
||||
with tempfile.TemporaryDirectory(prefix="ckb-convert-") as tmp:
|
||||
tmpd = Path(tmp)
|
||||
md = tmpd / (src.stem + ".md")
|
||||
md.write_text(body, encoding="utf-8")
|
||||
metaf = tmpd / "meta.json"
|
||||
metaf.write_text(json.dumps(meta, ensure_ascii=False), encoding="utf-8")
|
||||
base = ["pandoc", str(md), "-f", "markdown-yaml_metadata_block+autolink_bare_uris",
|
||||
"--metadata-file", str(metaf),
|
||||
"--resource-path", "%s%s%s" % (src.parent, ";" if sys.platform == "win32" else ":", root)]
|
||||
if "title" not in meta:
|
||||
base += ["--metadata", "pagetitle=" + src.stem]
|
||||
if args.toc:
|
||||
base.append("--toc")
|
||||
if args.number_sections:
|
||||
base.append("--number-sections")
|
||||
|
||||
def docx_to(path):
|
||||
cmd = base + ["-t", "docx", "-o", str(path)]
|
||||
if ref_docx:
|
||||
cmd += ["--reference-doc", str(ref_docx)]
|
||||
return run(cmd)
|
||||
|
||||
via = "pandoc"
|
||||
produced = tmpd / ("out." + fmt)
|
||||
if fmt == "docx":
|
||||
p = docx_to(produced)
|
||||
elif fmt == "html":
|
||||
css = sdir / (name + ".css")
|
||||
cmd = base + ["-t", "html5", "--standalone", "-o", str(produced),
|
||||
"--embed-resources" if version >= (2, 19) else "--self-contained"]
|
||||
if css.exists():
|
||||
cmd += ["--css", str(css)]
|
||||
else:
|
||||
notes.append("no %s.css: html uses pandoc's default look" % name)
|
||||
p = run(cmd)
|
||||
elif fmt == "odt":
|
||||
ref_odt = sdir / (name + ".odt")
|
||||
if ref_odt.exists():
|
||||
p = run(base + ["-t", "odt", "-o", str(produced), "--reference-doc", str(ref_odt)])
|
||||
elif lo and ref_docx:
|
||||
p = docx_to(tmpd / (src.stem + ".docx"))
|
||||
produced = soffice_convert(lo, tmpd / (src.stem + ".docx"), "odt", tmpd)
|
||||
via = "pandoc + LibreOffice"
|
||||
else:
|
||||
p = run(base + ["-t", "odt", "-o", str(produced)])
|
||||
notes.append("odt uses pandoc's default look (no %s.odt%s)"
|
||||
% (name, "" if lo else ", no LibreOffice"))
|
||||
else: # pdf
|
||||
if lo:
|
||||
p = docx_to(tmpd / (src.stem + ".docx"))
|
||||
produced = soffice_convert(lo, tmpd / (src.stem + ".docx"), "pdf", tmpd)
|
||||
via = "pandoc + LibreOffice"
|
||||
else:
|
||||
engine = next((e for e in PDF_ENGINES if shutil.which(e)), None)
|
||||
if not engine:
|
||||
raise Missing("PDF needs LibreOffice (keeps the Word style) or a pandoc PDF "
|
||||
"engine (%s); none found" % ", ".join(PDF_ENGINES))
|
||||
p = run(base + ["-o", str(produced), "--pdf-engine=" + engine])
|
||||
via = "pandoc --pdf-engine=" + engine
|
||||
notes.append("no LibreOffice: the PDF does not follow the Word style")
|
||||
out.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copyfile(produced, out)
|
||||
for line in (p.stderr or "").splitlines():
|
||||
if line.strip():
|
||||
notes.append("pandoc: " + line.strip())
|
||||
print("written: %s" % rel(out, root))
|
||||
print("format: %s via %s, style: %s" % (fmt, via, name if ref_docx else "pandoc default"))
|
||||
if meta.get("title"):
|
||||
print("title: %s" % meta["title"])
|
||||
for n in notes:
|
||||
print("note: " + n)
|
||||
return 0
|
||||
|
||||
|
||||
def rel(path, root):
|
||||
try:
|
||||
return Path(path).resolve().relative_to(Path(root).resolve()).as_posix()
|
||||
except ValueError:
|
||||
return str(path)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- CLI
|
||||
|
||||
def hex_color(v):
|
||||
v = v.lstrip("#").upper()
|
||||
if not re.match(r"^[0-9A-F]{6}$", v):
|
||||
raise argparse.ArgumentTypeError("colour must be six hex digits, e.g. 1F3864")
|
||||
return v
|
||||
|
||||
|
||||
def style_options(p):
|
||||
p.add_argument("--body-font")
|
||||
p.add_argument("--heading-font")
|
||||
p.add_argument("--size", type=float, help="body text size in points")
|
||||
p.add_argument("--heading-color", type=hex_color, help="RRGGBB")
|
||||
p.add_argument("--paper", choices=sorted(PAPER))
|
||||
p.add_argument("--margin-cm", type=float)
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
for stream in (sys.stdout, sys.stderr):
|
||||
if hasattr(stream, "reconfigure"):
|
||||
stream.reconfigure(encoding="utf-8", errors="replace")
|
||||
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
|
||||
ap.add_argument("--root", default=".")
|
||||
sub = ap.add_subparsers(dest="cmd")
|
||||
sub.required = True
|
||||
|
||||
c = sub.add_parser("convert")
|
||||
c.add_argument("file")
|
||||
c.add_argument("--to", choices=FORMATS, default="docx")
|
||||
c.add_argument("--style", default="house")
|
||||
c.add_argument("--style-required", action="store_true",
|
||||
help="refuse instead of falling back to pandoc's default when the style is missing")
|
||||
c.add_argument("--out")
|
||||
c.add_argument("--out-dir")
|
||||
c.add_argument("--toc", action="store_true")
|
||||
c.add_argument("--number-sections", action="store_true")
|
||||
c.add_argument("--keep-links", action="store_true")
|
||||
c.add_argument("--force", action="store_true")
|
||||
c.set_defaults(fn=cmd_convert)
|
||||
|
||||
n = sub.add_parser("new-style")
|
||||
n.add_argument("name")
|
||||
n.add_argument("--from", dest="from_file")
|
||||
n.add_argument("--force", action="store_true")
|
||||
style_options(n)
|
||||
n.set_defaults(fn=cmd_new_style)
|
||||
|
||||
e = sub.add_parser("edit-style")
|
||||
e.add_argument("name")
|
||||
style_options(e)
|
||||
e.set_defaults(fn=cmd_edit_style)
|
||||
|
||||
k = sub.add_parser("check-style")
|
||||
k.add_argument("name")
|
||||
k.set_defaults(fn=cmd_check_style)
|
||||
|
||||
sub.add_parser("styles").set_defaults(fn=cmd_styles)
|
||||
sub.add_parser("doctor").set_defaults(fn=cmd_doctor)
|
||||
|
||||
args = ap.parse_args(argv)
|
||||
args.root = str(Path(args.root).resolve())
|
||||
try:
|
||||
return args.fn(args)
|
||||
except Refused as e:
|
||||
print("refused: %s" % e, file=sys.stderr)
|
||||
return 1
|
||||
except Missing as e:
|
||||
print("error: %s" % e, file=sys.stderr)
|
||||
return 3
|
||||
except zipfile.BadZipFile as e:
|
||||
print("refused: not a valid Office file (%s)" % e, file=sys.stderr)
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
69
.agents/modules/voice/README.md
Normal file
69
.agents/modules/voice/README.md
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
# `voice` module
|
||||
|
||||
*Read this in: **English** | [Polski](README.pl.md)*
|
||||
|
||||
Opt-in. Install with "install the voice module"; remove with "uninstall the
|
||||
voice module". Nothing in here is active until installed.
|
||||
|
||||
## What it does
|
||||
|
||||
Answers, documents and reports the KB writes for people outside it tend to
|
||||
read like a model wrote them. This module rewrites them in **your voice**
|
||||
before they're saved. The voice is a wiki page, `wiki/voice/<name>.md`, so
|
||||
the team can read it, review it and correct it like any other knowledge.
|
||||
|
||||
| Skill | Does |
|
||||
|---|---|
|
||||
| `ckb-voice` | Rewrites outgoing text in a voice profile, builds a profile from sample documents, records "we never say X" as it comes up, and changes the settings. |
|
||||
|
||||
Once installed, nothing changes until the first profile exists. Say
|
||||
"calibrate our writing style" and give it a few documents that sound right.
|
||||
From then on, every new file in `outputs/answers/`, `outputs/documents/`,
|
||||
`outputs/reports/` and the project overview is written in that voice.
|
||||
|
||||
## What changes and what doesn't
|
||||
|
||||
The voice changes **wording**: banned AI vocabulary, formulaic structure,
|
||||
hedging, flat rhythm, and the tone, formality and phrases your profile sets.
|
||||
|
||||
It never changes **content**. Frontmatter, `## Sources`, `## Crux` and every
|
||||
quote, `## Notes`, contradiction markers, code, paths, links, numbers and
|
||||
names come out exactly as they went in. A rewrite that would alter one of
|
||||
them is rejected. A vague claim isn't cut, it's flagged for you. Wiki pages
|
||||
are never rewritten; the wiki stays plain.
|
||||
|
||||
## Settings
|
||||
|
||||
In `ckb.yaml`, under the module's entry. Change them by asking ("set the
|
||||
voice mode to ask", "make board the default voice"):
|
||||
|
||||
```yaml
|
||||
config:
|
||||
mode: auto # auto | ask (once per file) | off
|
||||
profile: house # the default voice, wiki/voice/house.md
|
||||
writer: ckb-voice # or another rewriting skill you have, e.g. ghost-writer
|
||||
apply_to: [outputs/answers/, outputs/documents/, outputs/reports/, PROJECT-OVERVIEW]
|
||||
skip: [outputs/okf/, outputs/starlight/]
|
||||
chat: false # true = chat answers too
|
||||
```
|
||||
|
||||
Which voice is used: one named in the request ("in the board voice"), else
|
||||
the `voice:` set in your own `workload/profiles/` page ("use my own voice by
|
||||
default"), else `profile`.
|
||||
|
||||
## Using your own rewriting skill
|
||||
|
||||
If you already have a rewriting skill you like, such as a personal
|
||||
`ghost-writer` in `~/.claude/skills/`, set `writer: ghost-writer`. The
|
||||
module still picks the profile from the wiki and still guards the frozen
|
||||
parts; your skill does the rewriting. If the skill isn't installed on a
|
||||
teammate's machine, their sessions fall back to `ckb-voice`.
|
||||
|
||||
## Safety
|
||||
|
||||
- **Profiles are committed.** Everyone who clones the KB sees them. Keep
|
||||
samples to text you'd share with the team.
|
||||
- **Third-party voices** ("write like Feynman") are built from published
|
||||
text and keep only a few lines as a sample.
|
||||
- **Uninstalling keeps the profiles.** `wiki/voice/` stays as knowledge;
|
||||
only the automatic rewrite stops.
|
||||
73
.agents/modules/voice/README.pl.md
Normal file
73
.agents/modules/voice/README.pl.md
Normal file
|
|
@ -0,0 +1,73 @@
|
|||
# Moduł `voice`
|
||||
|
||||
*Przeczytaj w: [English](README.md) | **Polski***
|
||||
|
||||
Opcjonalny. Instalacja: „install the voice module”, usunięcie: „uninstall
|
||||
the voice module”. Dopóki nie jest zainstalowany, nic z tego folderu nie
|
||||
działa.
|
||||
|
||||
## Co robi
|
||||
|
||||
Odpowiedzi, dokumenty i raporty, które baza pisze dla ludzi spoza niej,
|
||||
często brzmią jak tekst z modelu. Ten moduł przepisuje je **Waszym głosem**,
|
||||
zanim zostaną zapisane. Głos to strona wiki, `wiki/voice/<nazwa>.md`, więc
|
||||
zespół może go przeczytać, przejrzeć i poprawić jak każdą inną wiedzę.
|
||||
|
||||
| Skill | Co robi |
|
||||
|---|---|
|
||||
| `ckb-voice` | Przepisuje wychodzący tekst według profilu głosu, buduje profil z przykładowych dokumentów, zapisuje uwagi w rodzaju „nigdy nie piszemy X”, gdy padną, i zmienia ustawienia. |
|
||||
|
||||
Po instalacji nic się nie zmienia, dopóki nie powstanie pierwszy profil.
|
||||
Powiedz „calibrate our writing style” i podaj kilka dokumentów, które brzmią
|
||||
dobrze. Od tej chwili każdy nowy plik w `outputs/answers/`,
|
||||
`outputs/documents/`, `outputs/reports/` i przegląd projektu powstaje tym
|
||||
głosem.
|
||||
|
||||
## Co się zmienia, a co nie
|
||||
|
||||
Głos zmienia **sformułowania**: typowe dla AI słownictwo, schematyczną
|
||||
budowę, asekuranckie zwroty, płaski rytm, a także ton, formalność i
|
||||
zwroty, które ustala profil.
|
||||
|
||||
Nigdy nie zmienia **treści**. Frontmatter, `## Sources`, `## Crux` i każdy
|
||||
cytat, `## Notes`, znaczniki sprzeczności, kod, ścieżki, linki, liczby i
|
||||
nazwy wychodzą dokładnie takie, jakie weszły. Przepisanie, które zmieniłoby
|
||||
którekolwiek z nich, jest odrzucane. Ogólnikowe twierdzenie nie jest
|
||||
wycinane, tylko zgłaszane Tobie. Strony wiki nigdy nie są przepisywane;
|
||||
wiki zostaje zwykła.
|
||||
|
||||
## Ustawienia
|
||||
|
||||
W `ckb.yaml`, we wpisie modułu. Zmieniasz je prośbą („set the voice mode to
|
||||
ask”, „make board the default voice”):
|
||||
|
||||
```yaml
|
||||
config:
|
||||
mode: auto # auto | ask (raz na plik) | off
|
||||
profile: house # domyślny głos, wiki/voice/house.md
|
||||
writer: ckb-voice # albo inny Twój skill do przepisywania, np. ghost-writer
|
||||
apply_to: [outputs/answers/, outputs/documents/, outputs/reports/, PROJECT-OVERVIEW]
|
||||
skip: [outputs/okf/, outputs/starlight/]
|
||||
chat: false # true = także odpowiedzi w czacie
|
||||
```
|
||||
|
||||
Który głos: nazwany w prośbie („in the board voice”), inaczej `voice:` z
|
||||
Twojej strony w `workload/profiles/` („use my own voice by default”),
|
||||
inaczej `profile`.
|
||||
|
||||
## Własny skill do przepisywania
|
||||
|
||||
Jeśli masz już skill, który lubisz, np. osobisty `ghost-writer` w
|
||||
`~/.claude/skills/`, ustaw `writer: ghost-writer`. Moduł nadal bierze profil
|
||||
z wiki i nadal pilnuje zamrożonych części; przepisuje Twój skill. Jeśli na
|
||||
komputerze kogoś z zespołu tego skilla nie ma, jego sesje wracają do
|
||||
`ckb-voice`.
|
||||
|
||||
## Bezpieczeństwo
|
||||
|
||||
- **Profile są commitowane.** Widzi je każdy, kto sklonuje bazę. Jako
|
||||
próbki dawaj tylko tekst, którym podzielił(a)byś się z zespołem.
|
||||
- **Głosy osób trzecich** („pisz jak Feynman”) powstają z opublikowanych
|
||||
tekstów, a jako próbka zostaje najwyżej kilka linijek.
|
||||
- **Odinstalowanie zostawia profile.** `wiki/voice/` zostaje jako wiedza;
|
||||
ustaje tylko automatyczne przepisywanie.
|
||||
20
.agents/modules/voice/fragments/agents-routing.md
Normal file
20
.agents/modules/voice/fragments/agents-routing.md
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
## MODULE: voice
|
||||
|
||||
Text this KB sends out is written in a voice whose profile is a wiki page,
|
||||
`wiki/voice/<name>.md` (`type: voice-profile`). Settings are under the
|
||||
`voice` entry of `kb_modules:` in `ckb.yaml`.
|
||||
|
||||
- **Before writing a prose file** to a path under `apply_to` and not under
|
||||
`skip`, pass the draft through `ckb-voice`, whatever skill produced it.
|
||||
`mode: ask` asks once per file; `mode: off`, or no profile page yet, writes
|
||||
the draft unchanged. `chat: true` does the same for answers in the chat.
|
||||
- **The voice changes wording, never content.** Frontmatter, `## Sources`,
|
||||
`## Crux` and every quote, `## Notes`, `> CONTRADICTION:` markers, code,
|
||||
paths, links, numbers, names and a template's headings stay byte-for-byte.
|
||||
- Which profile: one named in the request, else the `voice:` field of the
|
||||
person's `workload/profiles/` page, else `profile` in `ckb.yaml`.
|
||||
- `wiki/` pages are never rewritten into a voice; the wiki stays plain.
|
||||
|
||||
| User intent | Skill |
|
||||
|---|---|
|
||||
| Rewrite text in a voice, create or update a voice profile, change the voice settings | `ckb-voice` |
|
||||
1
.agents/modules/voice/fragments/gitignore.snippet
Normal file
1
.agents/modules/voice/fragments/gitignore.snippet
Normal file
|
|
@ -0,0 +1 @@
|
|||
# voice module: nothing extra to ignore (profiles are tracked in wiki/voice/).
|
||||
45
.agents/modules/voice/module.yaml
Normal file
45
.agents/modules/voice/module.yaml
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
# Cascade KB module manifest — read by `ckb-module` on install/uninstall.
|
||||
# See docs/decisions/0020-voice-module.md.
|
||||
name: voice
|
||||
title: Voice for outgoing text
|
||||
version: 1.0.0
|
||||
requires_kb_schema: "1.7"
|
||||
summary: >
|
||||
Rewrites every text the KB sends out (kept answers, documents, reports, the
|
||||
project overview) in a writing voice whose profile is a page in
|
||||
wiki/voice/, so it reads like the team and not like a model. Facts, quotes,
|
||||
sources and code are never touched.
|
||||
|
||||
skills:
|
||||
- ckb-voice
|
||||
|
||||
# No scaffold: wiki/voice/ is created, and logged, by ckb-voice when the first
|
||||
# profile is written. A module install never writes wiki pages.
|
||||
|
||||
agents_fragment: fragments/agents-routing.md
|
||||
gitignore_fragment: fragments/gitignore.snippet
|
||||
|
||||
# Default settings, written under this module's `config:` in ckb.yaml on
|
||||
# install. ckb-voice owns them afterwards ("set the voice mode to ask").
|
||||
default_config:
|
||||
mode: auto # auto | ask | off
|
||||
profile: house # wiki/voice/<profile>.md used when nothing else names one
|
||||
writer: ckb-voice # or the name of another rewriting skill, e.g. ghost-writer
|
||||
apply_to: # path prefixes whose prose files go through the voice
|
||||
- outputs/answers/
|
||||
- outputs/documents/
|
||||
- outputs/reports/
|
||||
- PROJECT-OVERVIEW
|
||||
skip: # never rewritten, even under an apply_to prefix
|
||||
- outputs/okf/
|
||||
- outputs/starlight/
|
||||
chat: false # true = also rewrite answers given in the chat
|
||||
|
||||
schema_additions:
|
||||
types:
|
||||
- voice-profile # wiki/voice/<name>.md: a writing voice, maintained by ckb-voice
|
||||
fields:
|
||||
- voice # on an output file: the profile it was written in
|
||||
# on a person's workload/profiles/ page: their default voice
|
||||
|
||||
depends_on: []
|
||||
238
.agents/modules/voice/skills/ckb-voice/SKILL.md
Normal file
238
.agents/modules/voice/skills/ckb-voice/SKILL.md
Normal file
|
|
@ -0,0 +1,238 @@
|
|||
---
|
||||
name: ckb-voice
|
||||
description: Rewrite text the KB sends out (kept answers, documents, reports, the project overview) in a writing voice whose profile lives in wiki/voice/, and maintain those profiles and the voice settings. Runs before any prose file is written under the configured outputs paths, whichever skill drafted it. Use for "rewrite this in our voice", "use the <name> voice", "make this sound less AI", "humanize this", "calibrate our writing style", "create a voice profile", "update the house voice", "list voices", "set the voice mode to ask", "turn the voice off", "use my own voice by default".
|
||||
---
|
||||
|
||||
# Voice skill
|
||||
|
||||
## Purpose
|
||||
|
||||
Everything this KB hands to people outside it should read like the team
|
||||
wrote it, not like a model did. The rules for *how* to write are generic and
|
||||
ship here; the voice itself (tone, formality, words to keep and avoid,
|
||||
samples) is knowledge the team owns, so it is a wiki page anyone can review
|
||||
and correct: `wiki/voice/<name>.md`.
|
||||
|
||||
Two jobs:
|
||||
|
||||
1. **Apply** a voice to a draft before it leaves the KB (Steps 1–5).
|
||||
2. **Maintain** profiles and settings (the sections after Step 5).
|
||||
|
||||
## Settings
|
||||
|
||||
Under the `voice` entry of `kb_modules:` in `ckb.yaml`, written by
|
||||
`ckb-module` on install from the manifest's `default_config`:
|
||||
|
||||
```yaml
|
||||
kb_modules:
|
||||
- name: voice
|
||||
version: 1.0.0
|
||||
installed_on: YYYY-MM-DD
|
||||
config:
|
||||
mode: auto # auto | ask | off
|
||||
profile: house # default profile, wiki/voice/house.md
|
||||
writer: ckb-voice # or another installed rewriting skill
|
||||
apply_to: [outputs/answers/, outputs/documents/, outputs/reports/, PROJECT-OVERVIEW]
|
||||
skip: [outputs/okf/, outputs/starlight/]
|
||||
chat: false
|
||||
```
|
||||
|
||||
A path is in scope when it starts with an `apply_to` prefix and with no
|
||||
`skip` prefix. Only prose files are rewritten: Markdown and plain text.
|
||||
Generated data (`.json`, `.ics`, `.yaml`, `.csv`) never is, even in scope.
|
||||
`workload/`, `raw/`, `templates/` and `wiki/` are never in scope, whatever
|
||||
the settings say.
|
||||
|
||||
## Step 1 — Decide whether to run
|
||||
|
||||
Run when either is true:
|
||||
|
||||
- another skill is about to write a file whose path is in scope (the
|
||||
`AGENTS.md` module block sends it here), or the chat answer is about to
|
||||
go out and `chat: true`;
|
||||
- the user asks directly ("rewrite this in our voice", "use the Feynman
|
||||
voice", "make this less AI") — then scope and `mode` don't matter.
|
||||
|
||||
Then by `mode`:
|
||||
|
||||
- `off` → write the draft unchanged. Say nothing.
|
||||
- `ask` → ask once per file: "Write `<path>` in the `<profile>` voice?" A no
|
||||
writes the draft unchanged.
|
||||
- `auto` → continue.
|
||||
|
||||
## Step 2 — Resolve the profile
|
||||
|
||||
First match wins:
|
||||
|
||||
1. a profile named in the request ("in the Feynman voice", "use the board
|
||||
voice");
|
||||
2. `voice:` in the frontmatter of the session person's
|
||||
`workload/profiles/<author-slug>.md`;
|
||||
3. `profile` in the settings.
|
||||
|
||||
Read `wiki/voice/<name>.md`. If it doesn't exist:
|
||||
|
||||
- On an automatic run, write the draft unchanged and say once per session:
|
||||
"(No `<name>` voice profile yet, so `<path>` went out as drafted. Say
|
||||
'calibrate the <name> voice' to create one.)"
|
||||
- On a direct request, list `wiki/voice/index.md` and ask which to use, or
|
||||
offer to calibrate one.
|
||||
|
||||
A profile with `review: needs_update` is still used; mention it once.
|
||||
A profile marked `superseded_by` is replaced by its successor.
|
||||
|
||||
Say which voice you used in one line, e.g. "(Written in the `house` voice.)"
|
||||
Never mix two profiles in one text.
|
||||
|
||||
## Step 3 — Freeze what must not change
|
||||
|
||||
Before touching anything, mark these spans as frozen. They come out
|
||||
byte-for-byte as they went in:
|
||||
|
||||
- frontmatter, then add or update only `voice: <name>` in it;
|
||||
- `## Sources`, `## Crux` and every blockquote, and each attribution line
|
||||
(`— \`path\`, under "X"`), em-dash included;
|
||||
- `## Notes` and `## Rules`;
|
||||
- `> CONTRADICTION:` markers and `<private>` spans;
|
||||
- code blocks, inline code, file paths, URLs, links and `[[wikilinks]]`;
|
||||
- numbers, dates, amounts, names of people, products and organisations;
|
||||
- tables of data (cell wording may be tidied, values never);
|
||||
- in a `ckb-document` output, the template's headings and their order.
|
||||
|
||||
If the voice would need a frozen span changed (a quote that breaks the
|
||||
rhythm, a heading in the wrong register), leave it and move on.
|
||||
|
||||
## Step 4 — Rewrite the rest
|
||||
|
||||
If `writer` names another skill (for example a personal `ghost-writer`
|
||||
installed in the user's home directory), load it and let it do the
|
||||
rewrite. Pass it the profile page as its style profile and the frozen spans
|
||||
from Step 3 as text it must not change. Then check its output against
|
||||
Step 5. If it isn't available, say so once and fall back to `ckb-voice`.
|
||||
|
||||
Otherwise apply [`references/rules.md`](references/rules.md), with the
|
||||
profile overriding its defaults:
|
||||
|
||||
- **Tone**, **Formality** and **Sentence style** replace the rules' defaults
|
||||
(an em-dash rate set there overrides the rules' dash advice).
|
||||
- **Keep** words survive even if the rules ban them; **Avoid** words are added
|
||||
to the ban list.
|
||||
- **Sample** paragraphs are the voice reference: match their rhythm, not
|
||||
their content.
|
||||
- **Audience** and **Opinions** set how much to explain and how hard to land
|
||||
a point.
|
||||
|
||||
A rewrite changes wording, order inside a paragraph and paragraph breaks.
|
||||
It never adds a claim, a number or an example that wasn't in the draft, and
|
||||
never drops one. A vague claim the rules would cut is kept and listed in the
|
||||
change note instead. In a KB its source may say more, and that is the
|
||||
author's call, not the voice's.
|
||||
|
||||
For a long text (about 1,500 words or more), also read
|
||||
[`references/ai-signs.md`](references/ai-signs.md) and
|
||||
[`references/good-writing.md`](references/good-writing.md).
|
||||
|
||||
## Step 5 — Check, then write
|
||||
|
||||
Compare the rewrite with the draft before writing it:
|
||||
|
||||
- every frozen span is identical (diff them, don't eyeball them);
|
||||
- every number, name, path and link in the draft is still there;
|
||||
- the headings are the same (a `ckb-document` output) or no fewer
|
||||
(anything else).
|
||||
|
||||
A failed check means the rewrite is wrong: fix it, or write the draft
|
||||
unchanged and say why. Then write the file and add one line to the reply:
|
||||
"Voice: `<name>`. Main change: <the dominant pattern fixed>." On a direct
|
||||
request with no file, return the text and the same line.
|
||||
|
||||
The written file is the calling skill's output. Its log and workload entries
|
||||
are that skill's, and this skill adds none.
|
||||
|
||||
## Maintaining profiles
|
||||
|
||||
### A profile page
|
||||
|
||||
`wiki/voice/<name>.md`, one per voice. The name is a lower-case slug
|
||||
(`house`, `board`, `michal-kopec`, `feynman`). Write it from
|
||||
[`references/profile-template.md`](references/profile-template.md):
|
||||
|
||||
```yaml
|
||||
---
|
||||
type: voice-profile
|
||||
tldr: <who this voice is for and what it sounds like, one sentence>
|
||||
voice_of: team | person | third-party # whose voice it is
|
||||
last_updated: YYYY-MM-DD
|
||||
retention: high
|
||||
review: draft
|
||||
---
|
||||
```
|
||||
|
||||
The body has the sections in the template: Tone, Formality, Sentence style,
|
||||
Keep, Avoid, Audience, Opinions, Sample, then the reserved `## Sources`
|
||||
(documents the voice was calibrated from, fingerprinted as `AGENTS.md` §2
|
||||
says) and `## Notes` (protected).
|
||||
|
||||
`wiki/voice/index.md` lists every profile with its `tldr`, and
|
||||
`wiki/index.md` routes to it. Create both with the first profile. Every
|
||||
create or change under `wiki/voice/` is logged in `wiki/log.md` (Rule B)
|
||||
before going further.
|
||||
|
||||
A profile is knowledge about how to write. It is not evidence for any other
|
||||
claim, and `ckb-retrieve` should not ground a factual answer on it.
|
||||
|
||||
### Calibrate ("calibrate our writing style", "create a voice profile for X")
|
||||
|
||||
Run [`references/calibration.md`](references/calibration.md). It asks for
|
||||
sample documents first and then at most four short questions, one at a time,
|
||||
and writes the page with `review: draft`. Sample documents the user points
|
||||
to inside the KB (`raw/archive/`, `outputs/`) are cited in `## Sources`.
|
||||
Files from elsewhere go to `raw/inbox/` first, and only on a yes, so they
|
||||
can be fingerprinted. A third-party voice (a writer, a public figure) is
|
||||
built from published text and marked `voice_of: third-party`; its Sample
|
||||
holds a few lines at most, never whole passages.
|
||||
|
||||
### Update one thing ("we never say 'leverage'", "the board voice is more formal")
|
||||
|
||||
A standing preference, said during any work, goes to the profile in use:
|
||||
change only the field it touches, set `last_updated`, set `review:
|
||||
needs_update` on a `reviewed` page, log it, and confirm in one line. "Make
|
||||
*this one* more formal" is a one-off. Apply it and don't save it. If it's
|
||||
unclear which, ask: "Keep that for future texts, or just this one?"
|
||||
|
||||
Never write a preference learned for one profile into another.
|
||||
|
||||
### Personal default ("use my own voice by default")
|
||||
|
||||
Write `voice: <name>` into the frontmatter of the person's
|
||||
`workload/profiles/<author-slug>.md`, creating the profile through
|
||||
`ckb-profile` if it doesn't exist. It changes their sessions only.
|
||||
|
||||
### List ("list voices", "what voices do we have")
|
||||
|
||||
Show `wiki/voice/index.md`: name, `voice_of`, `tldr`, review state, and mark
|
||||
the default and the current person's choice.
|
||||
|
||||
### Retire
|
||||
|
||||
Never delete a profile on a request to change it. A replaced voice gets
|
||||
`superseded_by`, and its successor gets `supersedes`. Delete only on an
|
||||
explicit "delete the X voice", logged.
|
||||
|
||||
## Changing the settings
|
||||
|
||||
"Set the voice mode to ask", "turn the voice off", "make board the default
|
||||
voice", "also apply the voice to outputs/teaching/", "rewrite chat answers
|
||||
too". Edit only the `config:` of the `voice` entry in `ckb.yaml`, keeping
|
||||
everything else in the file intact, and confirm the new value in one line.
|
||||
Refuse an `apply_to` under `wiki/`, `raw/`, `workload/` or `templates/` and
|
||||
say why: the wiki stays plain, raw material and workload notes are records,
|
||||
and templates are the user's.
|
||||
|
||||
## What this skill does not do
|
||||
|
||||
- It does not check facts or add knowledge. Content goes out as the
|
||||
calling skill drafted it.
|
||||
- It does not rewrite wiki pages, quotes or code.
|
||||
- It does not change the language (English/Polish, British/American) unless
|
||||
the profile or the request says so.
|
||||
139
.agents/modules/voice/skills/ckb-voice/references/ai-signs.md
Normal file
139
.agents/modules/voice/skills/ckb-voice/references/ai-signs.md
Normal file
|
|
@ -0,0 +1,139 @@
|
|||
# AI Writing Signs — Detection Checklist
|
||||
|
||||
Reference for the `ckb-voice` skill (adapted from a personal ghost-writer skill). Scan input text against these patterns before rewriting.
|
||||
|
||||
---
|
||||
|
||||
## Category A: Surface-Level Tells (Easy to Spot)
|
||||
|
||||
### 1. Em Dash Overuse
|
||||
**Signal:** More than 3 em dashes per 500 words
|
||||
**Fix:** Replace with period, comma, or restructure the sentence
|
||||
|
||||
### 2. Banned Vocabulary
|
||||
**Signal:** Any cluster of these words: *delve, showcase, underscores, noteworthy, pivotal, realm, tapestry, beacon, multifaceted, commendable, meticulous, intricate, vibrant, bolstered, fostering, highlighting, crucial, emphasizing, enhance, align with*
|
||||
**Fix:** Replace with plain, direct language. "Shows" not "showcases." "Important" not "pivotal."
|
||||
|
||||
### 3. Perfect Grammar, Zero Personality
|
||||
**Signal:** No fragments, no deliberate rule-bending, no contractions, no personality
|
||||
**Fix:** Add a fragment. Use a contraction. Let a short sentence stand alone. Like this.
|
||||
|
||||
### 4. Formulaic Paragraph Structure
|
||||
**Signal:** Every paragraph follows: topic sentence → evidence → summary
|
||||
**Fix:** Vary openings. Start a paragraph with a question, an example, or a one-sentence punch.
|
||||
|
||||
### 5. Excessive Hedging
|
||||
**Signal:** High density of: *arguably, potentially, it's worth noting, it could be said, in many ways, some might argue, one could suggest*
|
||||
**Fix:** If the author means it, say it. Cut the hedge or restructure to a genuine conditional.
|
||||
|
||||
### 6. Meta-Commentary and Structural Narration
|
||||
**Signal:** "In this article, we will explore…" / "As we can see…" / "In conclusion, we have discussed…"
|
||||
**Fix:** Delete sentences that describe the document instead of saying the thing.
|
||||
|
||||
### 7. Identical Sentence Length
|
||||
**Signal:** Every sentence runs 15–20 words with no variation
|
||||
**Fix:** Vary aggressively. Mix a 4-word sentence with a 30-word one.
|
||||
|
||||
### 8. Transition Word Saturation
|
||||
**Signal:** High frequency of: *furthermore, moreover, additionally, consequently, thus, hence, in addition, it is important to note*
|
||||
**Fix:** Remove or replace with direct connectives ("but," "so," "and") or restructure without them.
|
||||
|
||||
### 9. The Rule of Three — Always
|
||||
**Signal:** Every list has exactly three items; every comparison hits three points
|
||||
**Fix:** Use two sometimes. Use four sometimes. Break the pattern intentionally.
|
||||
|
||||
### 10. Overuse of "-ing" Openers
|
||||
**Signal:** Multiple sentences per paragraph starting with an -ing phrase ("Offering a wide range…", "Giving users the ability…")
|
||||
**Fix:** Restructure to lead with the subject.
|
||||
|
||||
---
|
||||
|
||||
## Category B: Deep Patterns (Harder to Spot, More Damaging)
|
||||
|
||||
### 11. The Abstraction Trap ⚠️ HIGH PRIORITY
|
||||
**Signal:** Vague language where concrete details belong. "The experience was positive" instead of "Cut setup time from 3 days to 4 hours."
|
||||
**Fix:** For every abstract claim, add one specific detail, number, or named example.
|
||||
|
||||
### 12. The Treadmill Effect
|
||||
**Signal:** Text circles the same idea across multiple paragraphs without advancing the information
|
||||
**Fix:** Cut restatements ruthlessly. If the same idea appears twice, keep the best version, delete the rest.
|
||||
|
||||
### 13. Latinate Bias ⚠️ HIGH PRIORITY
|
||||
**Signal:** Preference for long, formal Latinate words over short Anglo-Saxon ones:
|
||||
- "utilize" → "use"
|
||||
- "facilitate" → "help"
|
||||
- "commence" → "start"
|
||||
- "demonstrate" → "show"
|
||||
- "approximately" → "about"
|
||||
- "endeavor" → "try"
|
||||
- "in order to" → "to"
|
||||
- "due to the fact that" → "because"
|
||||
**Fix:** Audit every 3+ syllable word. Is there a shorter one? Use it.
|
||||
|
||||
### 14. Sensing Without Sensing
|
||||
**Signal:** Sensory descriptions that feel generic ("the warm, inviting atmosphere" / "a rich blend of flavors")
|
||||
**Fix:** Replace with specific, idiosyncratic detail that only someone who was there would know.
|
||||
|
||||
### 15. The Both-Sides Seesaw
|
||||
**Signal:** AI presents "both sides" of claims the author clearly believes in, or softens assertions with unnecessary counterpoints
|
||||
**Fix:** If the author has a position, let it land. Remove false balance.
|
||||
|
||||
### 16. Model-Specific First-Word Fingerprints
|
||||
**Signal:**
|
||||
- ChatGPT: sentences starting with "Certainly!", "As an AI…", "Sure!", "Here's…"
|
||||
- Claude: "I'd be happy to", "Based on", "I understand"
|
||||
- Generic: "Absolutely!", "Great question!"
|
||||
**Fix:** Delete or fully restructure these openers.
|
||||
|
||||
### 17. Passive Voice Overuse
|
||||
**Signal:** Actions where the agent is hidden: "Mistakes were made." / "The analysis was conducted."
|
||||
**Fix:** Say who did it. "The team made mistakes." "We ran the analysis."
|
||||
|
||||
### 18. Uniform Paragraph Length
|
||||
**Signal:** All paragraphs roughly the same length (3-5 sentences each)
|
||||
**Fix:** Vary paragraph length. Use a 1-sentence paragraph for impact.
|
||||
|
||||
### 19. Overclaiming Comprehensiveness
|
||||
**Signal:** "This comprehensive guide covers everything you need to know about…" / "A complete overview of…"
|
||||
**Fix:** Say what it actually covers. "This covers the three most common setup errors."
|
||||
|
||||
### 20. Fake Urgency / Motivational Padding
|
||||
**Signal:** Closing with generic positivity: "Now that you have the tools, you're ready to succeed!" / "The possibilities are endless!"
|
||||
**Fix:** End with a specific, useful next step or a genuine observation.
|
||||
|
||||
---
|
||||
|
||||
## Category C: Structural Red Flags
|
||||
|
||||
### 21. Symmetrical Bullet Lists
|
||||
**Signal:** Every bullet item is the same length; every list has the same count
|
||||
**Fix:** Vary. Let some bullets be 1 sentence, others 3. Cut a list to 2 items or expand to 6.
|
||||
|
||||
### 22. Overuse of Bold Headers in Short Text
|
||||
**Signal:** H2/H3 headers every 2-3 paragraphs in a short document
|
||||
**Fix:** Reserve headers for genuine section breaks in longer content.
|
||||
|
||||
### 23. Redundant Section Summaries
|
||||
**Signal:** A paragraph that restates the preceding section at the end of each section
|
||||
**Fix:** Cut. The section speaks for itself.
|
||||
|
||||
### 24. The "Despite / However" Pivot Formula
|
||||
**Signal:** "Despite its many advantages, [X] faces challenges…" appears formulaically
|
||||
**Fix:** Restructure the critique directly without the softening setup.
|
||||
|
||||
---
|
||||
|
||||
## Quick Scan Protocol
|
||||
|
||||
When scanning a new text, check in this order:
|
||||
|
||||
1. Ctrl+F for banned vocabulary (see #2 above)
|
||||
2. Read first sentence of every paragraph — are they all the same structure?
|
||||
3. Count em dashes — more than 3 per page is a flag
|
||||
4. Find one factual claim — is it specific or vague? (abstraction trap)
|
||||
5. Find one transition word — does it appear more than twice per page?
|
||||
6. Read aloud for 30 seconds — does it have rhythm, or is it a metronome?
|
||||
|
||||
---
|
||||
|
||||
*Sources: vrid.ai/blog/signs-of-ai-writing (Feb 2026), Wikipedia:Signs_of_AI_writing, academic research from CMU, theaugmentededucator.com, bethz.com pattern analysis*
|
||||
|
|
@ -0,0 +1,86 @@
|
|||
# Calibrating a voice profile
|
||||
|
||||
Run this for "calibrate our writing style", "create a voice profile for X",
|
||||
"learn how we write", "rebuild the house voice". For a single preference
|
||||
mentioned in passing, use "Update one thing" in SKILL.md instead and don't
|
||||
run these questions.
|
||||
|
||||
Adapted from a personal ghost-writer skill's calibration flow. The result
|
||||
is a wiki page, `wiki/voice/<name>.md`, not a file in a skill folder.
|
||||
|
||||
---
|
||||
|
||||
## Which profile
|
||||
|
||||
Take the name from the request (`house` when they say "our style", "the
|
||||
team voice", "house style"; the person's author slug for "my style"). If
|
||||
`wiki/voice/<name>.md` exists, ask once: "There's already a `<name>` voice.
|
||||
Update it, or replace it from scratch?" Updating keeps every field the new
|
||||
answers don't touch, and keeps `## Notes` byte-for-byte.
|
||||
|
||||
Set `voice_of`: `team` for a shared voice, `person` for one person's own,
|
||||
`third-party` for a writer or public figure.
|
||||
|
||||
## Question 1 — samples (the most useful input)
|
||||
|
||||
Ask: "Do you have documents written in this voice? Give me paths in the KB,
|
||||
files elsewhere, or paste text."
|
||||
|
||||
- **In the KB** (`raw/archive/`, `outputs/`, a `templates/` example): read
|
||||
them and cite them in `## Sources` with fingerprints.
|
||||
- **Elsewhere**: offer to copy them into `raw/inbox/` first, so they can be
|
||||
fingerprinted and re-read later. Read them either way. Without the copy,
|
||||
say "Calibrated from files outside the KB" in the page's opening
|
||||
paragraph, and leave them out of `## Sources`.
|
||||
- **Pasted text**: use it, and say a single paragraph is a weak signal.
|
||||
- **`.docx`**: `python3 -c "from docx import Document; d=Document('PATH'); print('\n'.join(p.text for p in d.paragraphs if p.text.strip()))"`.
|
||||
Without python-docx, ask for a PDF or pasted text. Never install it
|
||||
without asking.
|
||||
- For a file over 1,000 lines, read the first 200 and the last 100.
|
||||
|
||||
Extract, with examples quoted from the samples:
|
||||
|
||||
1. average sentence length and how often short ones land;
|
||||
2. contractions or not;
|
||||
3. deliberate fragments;
|
||||
4. how sentences usually open;
|
||||
5. recurring phrases (these go to **Keep**);
|
||||
6. vocabulary register and domain terms;
|
||||
7. paragraph length;
|
||||
8. how directly opinions are stated;
|
||||
9. overall tone in two or three words;
|
||||
10. habits that appear inconsistently and look like slips (candidates for
|
||||
**Avoid**).
|
||||
|
||||
With several documents, separate what holds across all of them from what
|
||||
one document does. If the samples come from different eras or authors,
|
||||
ask which ones are the target voice and use the rest for facts only.
|
||||
|
||||
## Questions 2–4 — only what the samples didn't settle
|
||||
|
||||
Ask one at a time, and skip any the samples already answer:
|
||||
|
||||
2. "What do you mostly write in this voice: notes, blog posts, business
|
||||
documents, client deliverables, or formal writing?" (maps to 1–5)
|
||||
3. "Short and punchy, long and flowing, or mixed?"
|
||||
4. "Any words or habits you want stripped, even if they aren't AI tells?
|
||||
And when there's a point of view, state it or stay neutral?"
|
||||
|
||||
## Confirm, then write
|
||||
|
||||
Summarise in two sentences: "This voice is [formality], [sentence style],
|
||||
[opinions]. I'll keep [phrases] and strip [avoid list]." Ask: "Does that
|
||||
sound right?" Apply corrections.
|
||||
|
||||
Then write the page from `profile-template.md` with `review: draft` and
|
||||
today's `last_updated`. Paste the best one or two sample paragraphs into
|
||||
`## Sample`; for a third-party voice, a few lines at most.
|
||||
|
||||
Create `wiki/voice/index.md` if it's missing (a table: name, `voice_of`,
|
||||
`tldr`), add the row, and add a `wiki/voice/` row to `wiki/index.md`. Log
|
||||
every create and change in `wiki/log.md` (Rule B) as you go.
|
||||
|
||||
Finish with one line: "Saved the `<name>` voice to `wiki/voice/<name>.md`.
|
||||
It applies to new outputs from now on. Edit the page or say 'update the
|
||||
<name> voice' to change it." If it isn't the default and the user may want
|
||||
it to be, offer that once.
|
||||
|
|
@ -0,0 +1,158 @@
|
|||
# Good Writing Principles
|
||||
|
||||
Reference for the `ckb-voice` skill. Apply these when rewriting. These are grounded in enduring style principles (Orwell, Strunk & White, Hemingway) and current research on what distinguishes human from AI prose.
|
||||
|
||||
---
|
||||
|
||||
## Core Principles
|
||||
|
||||
### 1. Clarity First
|
||||
The reader should understand every sentence on first read. No re-reading required.
|
||||
|
||||
- Use precise words over impressive ones
|
||||
- One idea per sentence when the idea is complex
|
||||
- Active voice: say who did what
|
||||
- Short sentences carry weight. Use them for your most important points.
|
||||
|
||||
> Orwell's rule: "If it is possible to cut a word out, always cut it out."
|
||||
|
||||
---
|
||||
|
||||
### 2. Economy of Words
|
||||
Every word must earn its place.
|
||||
|
||||
| Cut this | Write this |
|
||||
|----------|-----------|
|
||||
| in order to | to |
|
||||
| due to the fact that | because |
|
||||
| at this point in time | now |
|
||||
| in the event that | if |
|
||||
| it is important to note that | (just say it) |
|
||||
| basic fundamentals | fundamentals |
|
||||
| end result | result |
|
||||
| close proximity | near |
|
||||
|
||||
Eliminating redundancy doesn't flatten writing — it sharpens it. The meaning comes through faster and hits harder.
|
||||
|
||||
---
|
||||
|
||||
### 3. Voice and Authenticity
|
||||
Voice is the personality of the writer coming through the text. It can't be faked — it emerges from honest, confident writing.
|
||||
|
||||
**What creates voice:**
|
||||
- Word choices the author gravitates toward
|
||||
- Sentence rhythms that feel natural to them
|
||||
- Opinions delivered without apology
|
||||
- Specific details only this person would notice
|
||||
|
||||
**What kills voice:**
|
||||
- Hedging every assertion
|
||||
- Replacing personality with formality
|
||||
- Writing "correctly" instead of writing truly
|
||||
|
||||
When editing, ask: *does this still sound like the author, or does it sound like a textbook?*
|
||||
|
||||
---
|
||||
|
||||
### 4. Rhythm and Sentence Variation
|
||||
Writing without rhythm feels robotic. The goal is a cadence that pulls the reader forward.
|
||||
|
||||
**Rhythm tactics:**
|
||||
- Mix sentence lengths. A short sentence after a long one lands hard.
|
||||
- Vary sentence structure. Not every sentence needs subject → verb → object.
|
||||
- Use a one-sentence paragraph for a point that deserves to stand alone.
|
||||
- Parallel structures (two or more sentences with the same grammatical shape) create momentum — but only when used intentionally, not by default.
|
||||
|
||||
**The metronome test:** Read the text aloud. If every sentence takes about the same amount of time to speak, the rhythm is broken.
|
||||
|
||||
---
|
||||
|
||||
### 5. Specificity Over Generality
|
||||
Concrete details create trust. Vague language signals inexperience or distance from the subject.
|
||||
|
||||
| Vague (AI) | Specific (Human) |
|
||||
|-----------|-----------------|
|
||||
| "significant improvement" | "reduced errors by 40%" |
|
||||
| "the experience was positive" | "we spent 3 fewer hours per sprint in review" |
|
||||
| "it smelled wonderful" | "burnt espresso and old books" |
|
||||
| "many users prefer this" | "7 of the 10 engineers we interviewed chose it immediately" |
|
||||
| "recently" | "last Tuesday" / "in Q3" |
|
||||
| "a well-known study found" | "the 2024 CMU study of 12,000 texts found" |
|
||||
|
||||
When specifics aren't available, name the gap: "we haven't measured this yet" is more trustworthy than a vague positive claim.
|
||||
|
||||
---
|
||||
|
||||
### 6. Active Voice
|
||||
Passive voice hides agents and weakens impact. Use it only when the agent is genuinely unknown or irrelevant.
|
||||
|
||||
| Passive | Active |
|
||||
|---------|--------|
|
||||
| "Mistakes were made." | "The team made mistakes." |
|
||||
| "The report was written by Sarah." | "Sarah wrote the report." |
|
||||
| "It was decided that..." | "The board decided..." |
|
||||
| "Questions should be sent to..." | "Send questions to..." |
|
||||
|
||||
---
|
||||
|
||||
### 7. Directness
|
||||
A direct writer doesn't hide behind jargon or hedged language. They trust that clear, honest prose persuades better than embellishment.
|
||||
|
||||
**Signs of indirect writing:**
|
||||
- Using formal language to create distance ("leverage synergies")
|
||||
- Qualifying assertions that the author clearly believes ("it could be argued that this approach is effective")
|
||||
- Softening criticism to the point of meaninglessness ("while this has some limitations, it also shows promise")
|
||||
|
||||
**Directness in practice:**
|
||||
- Say the bad thing directly: "This approach failed in three ways."
|
||||
- Commit to your position: "This is wrong." not "One might argue this is suboptimal."
|
||||
- Trust the reader to handle direct information.
|
||||
|
||||
---
|
||||
|
||||
### 8. Unpretentious Language
|
||||
Strunk and White: use words and phrases that come readily to hand. Plain language bridges writer and reader.
|
||||
|
||||
The goal is to *express*, not to *impress*. Pretentious writing signals the writer is showing off rather than communicating. Readers sense this and disengage.
|
||||
|
||||
**Practical test:** If you'd feel awkward saying it out loud to a colleague, rewrite it.
|
||||
|
||||
---
|
||||
|
||||
### 9. Structure Serves the Reader
|
||||
Good structure is invisible — the reader moves through the document without noticing the architecture.
|
||||
|
||||
**Structure principles:**
|
||||
- Lead with the most important information (especially in professional writing)
|
||||
- Topic sentences that actually commit to a point, not just name a topic
|
||||
- Transitions that reflect logic, not just sequence ("but" / "because" / "so" rather than "furthermore" / "additionally")
|
||||
- Endings that land — not a summary of what was just said, but a forward-looking observation or call to action
|
||||
|
||||
---
|
||||
|
||||
### 10. Emotional Honesty
|
||||
Human writing carries the writer's actual perspective. It can be measured, professional, and still emotionally present.
|
||||
|
||||
AI avoids emotional stakes. It describes things at a distance. Human writers who care about their subject write differently than those who don't — and readers feel it.
|
||||
|
||||
**Ways emotional honesty shows up:**
|
||||
- An opinion delivered without apology
|
||||
- A specific anecdote from real experience
|
||||
- Admitting uncertainty without hiding behind vague language
|
||||
- Enthusiasm (or frustration, or caution) that's proportionate to the subject
|
||||
|
||||
---
|
||||
|
||||
## The Writer's Test
|
||||
|
||||
Before finalizing any rewrite, ask:
|
||||
|
||||
1. Can I read every sentence aloud without stumbling?
|
||||
2. Does every paragraph move forward — does it add something the previous didn't?
|
||||
3. Is there at least one concrete, specific detail in every major claim?
|
||||
4. Would I be comfortable sending this with my name on it?
|
||||
5. Does it sound like a person, or does it sound like a template?
|
||||
|
||||
---
|
||||
|
||||
*Grounded in: Strunk & White "The Elements of Style," Orwell "Politics and the English Language," Hemingway's iceberg principle, journalism.university writing principles, naturalwrite.com elements of good writing (2025)*
|
||||
|
|
@ -0,0 +1,49 @@
|
|||
---
|
||||
type: voice-profile
|
||||
tldr: <Whose voice this is, for what kind of text, and what it sounds like, in one sentence>
|
||||
voice_of: team # team | person | third-party
|
||||
last_updated: YYYY-MM-DD
|
||||
retention: high
|
||||
review: draft
|
||||
---
|
||||
|
||||
# <Name> voice
|
||||
|
||||
<!-- One or two sentences: when to use this voice and when not to. -->
|
||||
|
||||
## Tone
|
||||
<!-- How the text should come across, in a few words with an example:
|
||||
"calm practitioners talking to peers", "blunt", "warm but exact". -->
|
||||
|
||||
## Formality
|
||||
<!-- 1-5, plus a word on contractions:
|
||||
1 chat, 2 blog, 3 business, 4 client deliverable, 5 legal/academic. -->
|
||||
|
||||
## Sentence style
|
||||
<!-- Short and punchy / mixed / long and flowing. Paragraph length.
|
||||
Punctuation habits, such as how often an em dash is fine. -->
|
||||
|
||||
## Keep
|
||||
<!-- Words and phrases this voice uses on purpose. Kept even when the
|
||||
generic rules would ban them. -->
|
||||
|
||||
## Avoid
|
||||
<!-- Words, phrases and habits to strip, on top of the generic ban list. -->
|
||||
|
||||
## Audience
|
||||
<!-- Who reads it, and what they already know. -->
|
||||
|
||||
## Opinions
|
||||
<!-- State positions directly, stay neutral, or hedge only on uncertain facts. -->
|
||||
|
||||
## Sample
|
||||
<!-- One or two short paragraphs that sound exactly right. The rewrite
|
||||
matches their rhythm, not their content. For a third-party voice,
|
||||
a few lines at most. -->
|
||||
|
||||
## Sources
|
||||
<!-- Documents this voice was calibrated from, one bullet each with a
|
||||
fingerprint, as AGENTS.md §2 says. Leave empty if built from answers only. -->
|
||||
|
||||
## Notes
|
||||
<!-- Human-authored and protected: no skill rewrites this section. -->
|
||||
188
.agents/modules/voice/skills/ckb-voice/references/rules.md
Normal file
188
.agents/modules/voice/skills/ckb-voice/references/rules.md
Normal file
|
|
@ -0,0 +1,188 @@
|
|||
# Rewriting rules
|
||||
|
||||
Reference for the `ckb-voice` skill, adapted from a personal ghost-writer
|
||||
skill. The active voice profile overrides these defaults wherever it says
|
||||
something (see SKILL.md Step 4). Frozen spans (SKILL.md Step 3) are never
|
||||
touched, whatever a rule below says.
|
||||
|
||||
---
|
||||
|
||||
## Scan and triage
|
||||
|
||||
Run the quick scan protocol in this order:
|
||||
|
||||
1. Ctrl+F for banned vocabulary (section A below) - flag every hit
|
||||
2. Read the first sentence of every paragraph - are they all the same grammatical shape?
|
||||
3. Count em dashes - more than 3 per page is a flag
|
||||
4. Find one factual claim - is it specific or vague? (abstraction trap, section E)
|
||||
5. Find one transition word - does it appear more than twice per page?
|
||||
6. Read 30 seconds aloud - does it have rhythm, or is it a metronome?
|
||||
|
||||
Classify findings:
|
||||
|
||||
- **High priority** (most detectable, most trust-damaging): abstraction trap, banned vocabulary, hedging, formulaic structure, "serves as" substitutions
|
||||
- **Medium priority**: sentence rhythm, transition word overuse, Latinate bias, passive voice
|
||||
- **Low priority**: em dash count, rule-of-three overuse, -ing openers
|
||||
|
||||
**Exit path:** If the scan finds only one or two low-priority issues, fix those and stop. Don't force a full rewrite on a clean text.
|
||||
|
||||
If the user asks for a **quick pass**, fix high-priority items only and note what was skipped. For a long text or a **deep rewrite**, work through all categories and read `ai-signs.md` and `good-writing.md` for the extended checklist.
|
||||
|
||||
---
|
||||
|
||||
## Rules
|
||||
|
||||
Work through all categories relevant to what triage found. Preserve intentional stylistic choices - if the author consistently uses a construction across the whole text, treat it as a voice marker, not a tell.
|
||||
|
||||
---
|
||||
|
||||
### A. Banned vocabulary - replace or cut
|
||||
|
||||
Every instance must be replaced with a plain word or the sentence rewritten.
|
||||
|
||||
**Remove or replace:**
|
||||
testament, pivotal, underscore, watershed, profound, solidifies, stands as, serves as, crucial, vibrant, enduring, intricate, seamless, comprehensive, robust, dynamic, breathtaking, stunning, nestled, groundbreaking, renowned, boasts, bolstered, garner, foster, enhance, delve, tapestry, rich (as in "rich cultural heritage"), landscape (metaphorical), ecosystem (metaphorical), interplay, meticulous/meticulously, align with, highlighting, showcasing, emphasizing, realm, beacon, multifaceted, commendable
|
||||
|
||||
**Replace "is/are" substitutes with the plain verb:**
|
||||
- "serves as" → "is"
|
||||
- "stands as" → "is"
|
||||
- "marks" (as synonym for "is") → "is"
|
||||
- "represents" → "is" or "shows"
|
||||
- "features" (meaning "has") → "has"
|
||||
- "maintains" (meaning "has") → "has"
|
||||
- "offers" (meaning "has") → "has"
|
||||
|
||||
**Remove vague authority phrases entirely:**
|
||||
- "industry observers note", "experts argue", "some critics argue"
|
||||
- "researchers suggest" (unless a specific researcher is named)
|
||||
- "it has been suggested", "it is worth noting", "it is important to note"
|
||||
- "scholarship describes", "studies show" (without citation)
|
||||
|
||||
If the draft names the source anywhere (its `## Sources`, a citation), name it here. If not, state the claim plainly without the false authority and list it in the change note. Never cut the claim itself: in a KB that is the author's call, not the voice's.
|
||||
|
||||
---
|
||||
|
||||
### B. Banned sentence patterns
|
||||
|
||||
**"Not X but Y" / "Not only X but also Y"**
|
||||
Artificial contrasts that sound insightful but restate the obvious. State the point directly.
|
||||
|
||||
Before: "Not just a technical tool, it is also a communication platform."
|
||||
After: "It is both a technical tool and a communication platform."
|
||||
|
||||
**Trailing -ing phrases that restate the clause**
|
||||
Delete any trailing participial phrase that repeats what the main clause already said.
|
||||
|
||||
Before: "The system improved reliability, reducing errors across deployments."
|
||||
After: "The system improved reliability."
|
||||
|
||||
**The rule of three (triplet adjectives or vague phrases)**
|
||||
Three-part lists of vague adjectives are an LLM fingerprint. Use one specific detail or none.
|
||||
|
||||
Before: "a dynamic, innovative, and forward-thinking organisation"
|
||||
After: "an organisation that ships in two-week cycles"
|
||||
|
||||
**The "Despite / However" pivot formula**
|
||||
Before: "Despite its many advantages, the system faces challenges, but continues to improve."
|
||||
After: State the specific challenge as a concrete fact, or cut the paragraph.
|
||||
|
||||
**Transition word saturation**
|
||||
Remove or replace: furthermore, moreover, additionally, consequently, thus, hence, in addition, it is worth noting, in contrast.
|
||||
Replace with direct connectives ("but," "so," "and") or restructure without them.
|
||||
|
||||
---
|
||||
|
||||
### C. Structural patterns to remove
|
||||
|
||||
**"In conclusion" / "As we have seen" / "In summary" openers**
|
||||
Delete. Start the final paragraph with its actual content.
|
||||
|
||||
**"In today's world" / "In today's [adjective] landscape" openers**
|
||||
Delete the opener. Start with the substantive claim.
|
||||
|
||||
**"As X continues to evolve" / "With the rise of X" openers**
|
||||
Delete. Start with what actually happened.
|
||||
|
||||
**Separate "Challenges and Future Prospects" or "Looking Ahead" sections**
|
||||
Integrate challenges as concrete statements into the relevant sections. Cut speculation.
|
||||
|
||||
**Meta-commentary and structural narration**
|
||||
Delete sentences that describe the document rather than saying the thing:
|
||||
- "In this article, we will explore…"
|
||||
- "As we can see from the above…"
|
||||
- "This section covers…" (as a standalone sentence)
|
||||
|
||||
---
|
||||
|
||||
### D. Formatting tells to remove
|
||||
|
||||
**Bullet points with bolded lead phrases**
|
||||
The pattern "**Term:** explanation" throughout a document is an LLM fingerprint. Convert to prose where the calling skill's format allows it. If a list is genuinely needed, use plain bullets without bolded labels.
|
||||
|
||||
**Excessive bold mid-sentence**
|
||||
Bold is for terms being defined or genuine emphasis only. Remove bold from any word bolded simply because the LLM deemed it important.
|
||||
|
||||
**Excessive headers**
|
||||
One header per short paragraph is a structural tell. Consolidate sections. A paragraph does not need a heading unless it begins a genuinely new section. A template's headings (a `ckb-document` output) are frozen and stay.
|
||||
|
||||
**Em dashes used for decoration or aside**
|
||||
Replace em dashes (—) in prose with a comma, a full stop, a hyphen-minus surrounded by spaces ( - ), or restructure the sentence. A profile may set its own dash rate. Crux attribution lines start with an em-dash and are frozen.
|
||||
|
||||
**Symmetrical bullet lists**
|
||||
Every bullet the same length, every list the same count, is a tell. Vary: let some bullets be one sentence, others three. Cut a list to two items or expand to six.
|
||||
|
||||
---
|
||||
|
||||
### E. The abstraction trap (highest priority)
|
||||
|
||||
Every generic claim should carry a concrete fact, number, name, or example, taken from the draft itself or from the sources it cites. Never invent one. If the draft has nothing specific to offer, keep the claim and list it in the change note as vague, so the author can fill it or cut it.
|
||||
|
||||
Before: "The platform has helped many organisations improve their processes."
|
||||
After: "The platform cut invoice processing time by 40% at the client in the case study." (only if the draft or its source says so)
|
||||
Or: keep it and flag it.
|
||||
|
||||
Apply to every sentence containing:
|
||||
- quantities without numbers ("many," "several," "numerous," "various")
|
||||
- superlatives without evidence ("the most," "the best," "leading")
|
||||
- outcomes without measurement ("improved," "enhanced," "transformed")
|
||||
- time without specifics ("recently," "in recent years," "over time")
|
||||
|
||||
---
|
||||
|
||||
### F. Voice, clarity and authenticity
|
||||
|
||||
**Latinate bias**
|
||||
Replace long formal words with short plain ones:
|
||||
- "utilize" → "use", "facilitate" → "help", "commence" → "start"
|
||||
- "demonstrate" → "show", "approximately" → "about", "endeavor" → "try"
|
||||
- "in order to" → "to", "due to the fact that" → "because"
|
||||
|
||||
**Passive voice**
|
||||
Say who did what. "Mistakes were made" → "The team made mistakes."
|
||||
|
||||
**Hedging**
|
||||
If the author means it, say it. Cut: arguably, potentially, it could be said, in many ways, one could suggest, somewhat.
|
||||
|
||||
**Treadmill effect**
|
||||
Cut restatements. If the same idea appears twice, keep the best version, delete the rest.
|
||||
|
||||
**Perfect grammar, zero personality**
|
||||
Add a fragment. Use a contraction. Let a short sentence stand alone. Like this.
|
||||
|
||||
**Preserve the author's voice**
|
||||
Do not over-sanitize. Retain domain vocabulary the author uses deliberately. Where the original has opinions, let them land - do not hedge what the author clearly meant to assert. One opinion should land in the final version without softening.
|
||||
|
||||
---
|
||||
|
||||
### G. Sentence rhythm
|
||||
|
||||
LLMs produce sentences of similar length and structure. After all other fixes, check rhythm:
|
||||
|
||||
- Are consecutive sentences the same length? Break one up or combine two.
|
||||
- Do multiple sentences start with subject + verb? Vary the opening.
|
||||
- Does every paragraph have at least one short sentence (under 10 words)?
|
||||
- Are all paragraphs roughly the same length? Use a one-sentence paragraph for a point that deserves to stand alone.
|
||||
- Read aloud: if every sentence takes about the same time to speak, the rhythm is broken.
|
||||
|
||||
---
|
||||
|
||||
|
|
@ -56,7 +56,7 @@ Find `.agents/modules/<name>/module.yaml`. If the name doesn't match, list what'
|
|||
actually in `.agents/modules/` rather than guessing at a near-miss.
|
||||
|
||||
Read the manifest: `skills`, `scaffold`, `agents_fragment`, `gitignore_fragment`,
|
||||
`schema_additions`, `depends_on`, `requires_kb_schema`.
|
||||
`schema_additions`, `depends_on`, `requires_kb_schema`, `default_config`.
|
||||
|
||||
### Step 2 — Check preconditions, and report them before writing anything
|
||||
|
||||
|
|
@ -110,7 +110,10 @@ Both patches are wrapped in markers so uninstall is exact:
|
|||
|
||||
### Step 5 — Record, log, report
|
||||
|
||||
- Add the module to `ckb.yaml` with its version and today's date.
|
||||
- Add the module to `ckb.yaml` with its version and today's date. If the
|
||||
manifest has `default_config`, write it as the entry's `config:`. On a
|
||||
reinstall, keep the existing `config:` and add only keys it lacks: the
|
||||
user may have changed the values since.
|
||||
- Log to `wiki/log.md` per Rule B **only** for the `wiki/index.md` change — the
|
||||
rest is template layer, not wiki content.
|
||||
- Append to `workload/YYYY-MM-DD_<author>_summary.md` per Rule D.
|
||||
|
|
|
|||
|
|
@ -32,7 +32,12 @@ PDFs and video transcripts into `raw/inbox/`, the optional `capture` module
|
|||
saves each as a dated, untrusted-marked snapshot. To send a document to
|
||||
another KB, the optional `share` module uses a shared git repo with one
|
||||
mailbox per KB; the receiver takes it into `raw/inbox/` and ingests it as
|
||||
usual. Every module has its
|
||||
usual. To write everything the KB sends out in your team's voice, the
|
||||
optional `voice` module rewrites kept answers, documents and reports from a
|
||||
voice profile kept as a wiki page, without touching facts, quotes or
|
||||
sources. To hand a document over as a Word file or a PDF, the optional
|
||||
`convert` module runs pandoc with a house style kept in `templates/styles/`,
|
||||
built from a few settings or from your company's Word template. Every module has its
|
||||
own README in both languages under `.agents/modules/<name>/`.
|
||||
|
||||
For the page schema in full, and for how both version numbers got where they
|
||||
|
|
|
|||
|
|
@ -35,6 +35,13 @@ w `raw/inbox/`, opcjonalny moduł `capture` zapisuje każdą jako datowany zrzut
|
|||
oznaczony jako niezaufany. Aby wysłać dokument do innej bazy, opcjonalny moduł
|
||||
`share` korzysta ze wspólnego repozytorium git z jedną skrzynką na bazę;
|
||||
odbiorca bierze dokument do `raw/inbox/` i przetwarza go zwykłym ingestem.
|
||||
Aby wszystko, co baza wysyła na zewnątrz, brzmiało głosem zespołu, opcjonalny
|
||||
moduł `voice` przepisuje zachowane odpowiedzi, dokumenty i raporty według
|
||||
profilu głosu trzymanego jako strona wiki, nie ruszając faktów, cytatów ani
|
||||
źródeł. Aby oddać dokument jako plik Worda lub PDF, opcjonalny moduł
|
||||
`convert` uruchamia pandoca ze stylem firmowym trzymanym w
|
||||
`templates/styles/`, zbudowanym z kilku ustawień albo z firmowego szablonu
|
||||
Worda.
|
||||
Każdy moduł ma własne README w obu językach w
|
||||
`.agents/modules/<nazwa>/`.
|
||||
|
||||
|
|
|
|||
2
VERSION
2
VERSION
|
|
@ -1 +1 @@
|
|||
2.0.9
|
||||
2.2.0
|
||||
|
|
|
|||
|
|
@ -346,7 +346,9 @@ docs. Independent of the content schema above.
|
|||
|
||||
| Version | Date | What landed | Schema |
|
||||
|---|---|---|---|
|
||||
| **2.0.9** | 2026-11-11 | Tests only. Golden outputs for both exporters on the clean fixture: the exact file list (`tests/expected/okf-files.txt`, 15 files; `starlight-files.txt`, 17) and the summary each prints (`okf-report.txt`, `starlight-report.txt`, including the OKF conformance verdict). Content is not compared, because OKF stamps the export date. This closes the last item of the 2.0.0 script review | 1.7 |
|
||||
| **2.2.0** | 2026-11-11 | New opt-in `convert` module (D-0021): skill `ckb-convert` and `convert.py` (stdlib; needs pandoc, LibreOffice optional). `convert` turns any KB Markdown file into `.docx`, `.odt`, PDF or HTML in a named house style, `templates/styles/<name>.docx` (pandoc's reference document; optional `<name>.odt`/`<name>.css`). PDF and ODT are made by LibreOffice from the styled `.docx` (private profile), so every format looks the same; without it PDF falls back to a pandoc PDF engine and says the style wasn't applied. The copy is cleaned for outside readers: frontmatter → title/author (no e-mail)/date/lang, a leading `# H1` → title, template comments dropped, `[[wikilinks]]` and KB-path links → text (`--keep-links`), code blocks untouched. An existing output is refused without `--force`. **Styles without fonts by hand:** `new-style` copies pandoc's default reference and sets body/heading font, size, heading colour, paper (A4/Letter) and margins in `styles.xml`, the theme and the body `sectPr` in schema order; `--from` takes a company `.docx`/`.dotx` (content type rewritten, macros refused); `edit-style`, `check-style` (styles pandoc uses that a template lacks), `styles`, `doctor`. Scaffold `templates/styles/README.md`; settings `style`, `format`, `out_dir`, `toc`, `number_sections`, `keep_links` via `default_config`; routed by the module's `AGENTS.md` block, after `ckb-voice`. Tests: `tests/unit/test_convert.py`, eval `ckb-module/install-convert`. No schema change | 1.7 |
|
||||
| 2.1.0 | 2026-11-11 | New opt-in `voice` module (D-0020): skill `ckb-voice`, no script. Every prose file written under the configured `apply_to` paths (default `outputs/answers/`, `outputs/documents/`, `outputs/reports/`, `PROJECT-OVERVIEW*`; `outputs/okf/` and `outputs/starlight/` skipped) is rewritten in a voice before it is saved, whichever skill drafted it; the hook is the module's `AGENTS.md` block, so no core skill changed for it. **Profiles are wiki pages**, `wiki/voice/<name>.md` (`type: voice-profile`, `voice_of: team/person/third-party`, Tone, Formality, Sentence style, Keep, Avoid, Audience, Opinions, Sample, `## Sources`, protected `## Notes`), created and logged by calibration from sample documents; standing preferences said in passing update one field. **Settings** in `ckb.yaml` (`mode: auto/ask/off`, `profile`, `writer`, `apply_to`, `skip`, `chat`); profile precedence: named in the request, then `voice:` on the person's `workload/profiles/` page, then the default. **Frozen spans** (frontmatter except a new `voice:` field, Sources, Crux and quotes with attributions, Notes/Rules, contradiction markers, `<private>`, code, paths, links, numbers, names, a template's headings) are diffed before writing; a vague claim is flagged, never cut. `writer:` hands the rewrite to another installed skill such as a personal `ghost-writer`, with fallback. Rules adapted from that skill. `ckb-module` reads a manifest's `default_config` into the entry's `config:` and keeps edited values on reinstall. New type `voice-profile` and field `voice`, additive, no schema bump | 1.7 |
|
||||
| 2.0.9 | 2026-11-11 | Tests only. Golden outputs for both exporters on the clean fixture: the exact file list (`tests/expected/okf-files.txt`, 15 files; `starlight-files.txt`, 17) and the summary each prints (`okf-report.txt`, `starlight-report.txt`, including the OKF conformance verdict). Content is not compared, because OKF stamps the export date. This closes the last item of the 2.0.0 script review | 1.7 |
|
||||
| 2.0.8 | 2026-11-11 | Tests only. `tests/unit/test_mcp_server.py` covers the mcp server with the MCP SDK installed (2.3.0): a confirmation code confirms exactly one write and is bound to its payload and lifetime, a wrong `kb` is refused first, `_redact` masks secrets, the allowed-hosts default and override, a foreign `Host` header gets 421 over real HTTP while the public host gets 200, and OAuth tokens signed with a real RSA key — an unverified email no longer passes an `@domain` allow list, a verified one does, `CKB_MCP_OAUTH_TRUST_EMAIL=1` opts out, wrong audience and expired tokens fail. Without the SDK the tests skip; `CKB_MCP_PYTHON=<venv>/bin/python bash tests/smoke.sh` runs them. These confirm the 2.0.4 server changes, which until now were only compiled | 1.7 |
|
||||
| 2.0.7 | 2026-11-11 | Skill evals for the destructive and stateful skills, and the fix one of them found; no new features. **`ckb-reset`:** in a KB with no git repository, Step 0 asked for "a much more explicit confirmation" without saying what, so two runs asked for two different phrases; the phrase is now named, **`reset the wiki with no restore point`**, and the plain `reset the wiki` does not count there. **Nine new eval cases**, each run once by an agent on 2026-11-11 and passing: `ckb-reset/no-confirm` (inventory, nothing deleted), `ckb-reset/confirmed` (the plain phrase refused, the strict one accepted; tier 1 gone, scaffold back, `kb_schema_version` kept, raw/template untouched), `ckb-module/install` and `ckb-module/round-trip` (`AGENTS.md`, `.gitignore`, `ckb.yaml` byte-identical after uninstall), `ckb-upgrade/major-guard` (1.28.7 → 2.x stops and asks) and `ckb-upgrade/take-major` (VERSION 2.x, `lint_quick.ps1` deleted, wiki untouched), `ckb-decide/supersede` (both links set, D-0001's text untouched), `ckb-ingest/check-in-waits` and `ckb-ingest/reviewed-page` (`needs_update`, `## Notes` byte-for-byte). **Runner:** `replies` for the operator's answers when a skill stops and waits; setup steps `template` (template files, optionally from an older git ref) and `upstream` (a local bare repo for `ckb-upgrade`); `record` saves a passing run as `reference/` with a `.deleted` list and `replay` rebuilds and checks it; the smoke test replays every reference (five today). The runner's frontmatter reader takes frontmatter closed at end of file | 1.7 |
|
||||
| 2.0.6 | 2026-11-11 | Tests, and the parser fix they found; no new features. **Frontmatter readers agree:** the eight scripts that read page frontmatter (lint, retrieve, consolidate, both exporters, dedup, share, the mcp server) now all end it at a line that is exactly `---`, including one at the very end of the file; consolidate, dedup, OKF and share missed frontmatter closed without a final newline, and retrieve, Starlight and the mcp server ended it at any line starting with `---`. New `tests/unit/test_frontmatter_contract.py` feeds all eight the same cases. **Every lint check fires:** `tests/unit/test_lint_dirty.py` plants one fault per check (conformance, freshness, confidence, retention, decisions, orphans, graph, index/log, fingerprints, crux, review, contradictions, tags) in a copy of the fixture and asserts exactly which files each reports; the golden `lint.json` only proved the checks stay quiet on a clean KB | 1.7 |
|
||||
|
|
|
|||
|
|
@ -354,7 +354,9 @@ Niezależna od schematu treści powyżej.
|
|||
|
||||
| Wersja | Data | Co weszło | Schemat |
|
||||
|---|---|---|---|
|
||||
| **2.0.9** | 2026-11-11 | Tylko testy. Złote wyniki obu eksportów na czystym fixture: dokładna lista plików (`tests/expected/okf-files.txt`, 15 plików; `starlight-files.txt`, 17) i podsumowanie, które każdy wypisuje (`okf-report.txt`, `starlight-report.txt`, z werdyktem zgodności OKF). Treść nie jest porównywana, bo OKF wpisuje datę eksportu. To zamyka ostatni punkt przeglądu skryptów 2.0.0 | 1.7 |
|
||||
| **2.2.0** | 2026-11-11 | Nowy opcjonalny moduł `convert` (D-0021): skill `ckb-convert` i `convert.py` (biblioteka standardowa; wymaga pandoca, LibreOffice opcjonalnie). `convert` zamienia dowolny plik Markdown z bazy na `.docx`, `.odt`, PDF lub HTML w nazwanym stylu firmowym, `templates/styles/<nazwa>.docx` (dokument referencyjny pandoca; opcjonalnie `<nazwa>.odt`/`<nazwa>.css`). PDF i ODT robi LibreOffice ze sformatowanego `.docx` (osobny profil), więc wszystkie formaty wyglądają tak samo; bez niego PDF robi silnik PDF pandoca, z informacją, że styl nie został zastosowany. Kopia jest czyszczona dla czytelnika spoza bazy: frontmatter → tytuł/autor (bez e-maila)/data/język, początkowy `# H1` → tytuł, komentarze szablonu usunięte, `[[wikilinki]]` i linki do ścieżek bazy → tekst (`--keep-links`), bloki kodu bez zmian. Istniejący plik wynikowy nie jest nadpisywany bez `--force`. **Style bez ręcznego wybierania czcionek:** `new-style` kopiuje domyślny dokument referencyjny pandoca i ustawia czcionkę tekstu i nagłówków, rozmiar, kolor nagłówków, format papieru (A4/Letter) i marginesy w `styles.xml`, motywie i `sectPr` treści, w kolejności wymaganej przez schemat; `--from` przyjmuje firmowy `.docx`/`.dotx` (typ zawartości przepisany, makra odrzucane); `edit-style`, `check-style` (style używane przez pandoca, których brakuje w szablonie), `styles`, `doctor`. Szkielet `templates/styles/README.md`; ustawienia `style`, `format`, `out_dir`, `toc`, `number_sections`, `keep_links` przez `default_config`; kierowanie przez blok modułu w `AGENTS.md`, po `ckb-voice`. Testy: `tests/unit/test_convert.py`, eval `ckb-module/install-convert`. Bez zmiany schematu | 1.7 |
|
||||
| 2.1.0 | 2026-11-11 | Nowy opcjonalny moduł `voice` (D-0020): skill `ckb-voice`, bez skryptu. Każdy plik prozy zapisywany pod ścieżkami `apply_to` (domyślnie `outputs/answers/`, `outputs/documents/`, `outputs/reports/`, `PROJECT-OVERVIEW*`; `outputs/okf/` i `outputs/starlight/` pominięte) jest przed zapisem przepisywany wybranym głosem, niezależnie od tego, który skill go przygotował; podpięcie to blok modułu w `AGENTS.md`, więc żaden skill bazowy się nie zmienił. **Profile to strony wiki**, `wiki/voice/<nazwa>.md` (`type: voice-profile`, `voice_of: team/person/third-party`, Tone, Formality, Sentence style, Keep, Avoid, Audience, Opinions, Sample, `## Sources`, chronione `## Notes`), tworzone i logowane przez kalibrację z przykładowych dokumentów; stałe preferencje wypowiedziane przy okazji zmieniają jedno pole. **Ustawienia** w `ckb.yaml` (`mode: auto/ask/off`, `profile`, `writer`, `apply_to`, `skip`, `chat`); kolejność profilu: nazwany w prośbie, potem `voice:` na stronie osoby w `workload/profiles/`, potem domyślny. **Zamrożone fragmenty** (frontmatter poza nowym polem `voice:`, Sources, Crux i cytaty z atrybucjami, Notes/Rules, znaczniki sprzeczności, `<private>`, kod, ścieżki, linki, liczby, nazwy, nagłówki szablonu) są porównywane przed zapisem; ogólnikowe twierdzenie jest zgłaszane, nigdy wycinane. `writer:` przekazuje przepisywanie innemu zainstalowanemu skillowi, np. osobistemu `ghost-writer`, z powrotem do `ckb-voice`, gdy go brak. Reguły zaadaptowane z tego skilla. `ckb-module` wpisuje `default_config` z manifestu do `config:` wpisu i przy reinstalacji zachowuje zmienione wartości. Nowy typ `voice-profile` i pole `voice`, addytywnie, bez zmiany schematu | 1.7 |
|
||||
| 2.0.9 | 2026-11-11 | Tylko testy. Złote wyniki obu eksportów na czystym fixture: dokładna lista plików (`tests/expected/okf-files.txt`, 15 plików; `starlight-files.txt`, 17) i podsumowanie, które każdy wypisuje (`okf-report.txt`, `starlight-report.txt`, z werdyktem zgodności OKF). Treść nie jest porównywana, bo OKF wpisuje datę eksportu. To zamyka ostatni punkt przeglądu skryptów 2.0.0 | 1.7 |
|
||||
| 2.0.8 | 2026-11-11 | Tylko testy. `tests/unit/test_mcp_server.py` obejmuje serwer mcp z zainstalowanym MCP SDK (2.3.0): kod potwierdzenia potwierdza dokładnie jeden zapis i jest związany z treścią i czasem ważności, zły `kb` jest odrzucany jako pierwszy, `_redact` maskuje sekrety, domyślna i nadpisana lista dozwolonych hostów, obcy nagłówek `Host` dostaje 421 przez prawdziwe HTTP, a host publiczny 200, oraz tokeny OAuth podpisane prawdziwym kluczem RSA — niezweryfikowany e-mail nie przechodzi już listy `@domena`, zweryfikowany przechodzi, `CKB_MCP_OAUTH_TRUST_EMAIL=1` to wyłącza, zła publiczność i wygasłe tokeny są odrzucane. Bez SDK testy są pomijane; `CKB_MCP_PYTHON=<venv>/bin/python bash tests/smoke.sh` je uruchamia. Potwierdzają zmiany serwera z 2.0.4, które dotąd były tylko skompilowane | 1.7 |
|
||||
| 2.0.7 | 2026-11-11 | Ewaluacje skilli niszczących i zmieniających stan oraz poprawka, którą jedna z nich znalazła; bez nowych funkcji. **`ckb-reset`:** w KB bez repozytorium git krok 0 wymagał „znacznie wyraźniejszego potwierdzenia”, nie mówiąc jakiego, więc dwa przebiegi poprosiły o dwie różne frazy; fraza jest teraz nazwana, **`reset the wiki with no restore point`**, a zwykłe `reset the wiki` się tam nie liczy. **Dziewięć nowych przypadków ewaluacji**, każdy raz wykonany przez agenta 2026-11-11 i zaliczony: `ckb-reset/no-confirm` (inwentarz, nic nie usunięto), `ckb-reset/confirmed` (zwykła fraza odrzucona, ścisła przyjęta; poziom 1 usunięty, szkielet przywrócony, `kb_schema_version` zachowane, raw i szablon nietknięte), `ckb-module/install` i `ckb-module/round-trip` (`AGENTS.md`, `.gitignore`, `ckb.yaml` identyczne co do bajtu po odinstalowaniu), `ckb-upgrade/major-guard` (1.28.7 → 2.x zatrzymuje się i pyta) i `ckb-upgrade/take-major` (VERSION 2.x, `lint_quick.ps1` usunięty, wiki nietknięte), `ckb-decide/supersede` (oba odnośniki ustawione, tekst D-0001 nietknięty), `ckb-ingest/check-in-waits` i `ckb-ingest/reviewed-page` (`needs_update`, `## Notes` co do bajtu). **Runner:** `replies` na odpowiedzi operatora, gdy skill się zatrzymuje; kroki przygotowania `template` (pliki szablonu, opcjonalnie ze starszego refa gita) i `upstream` (lokalne gołe repozytorium dla `ckb-upgrade`); `record` zapisuje zaliczony przebieg jako `reference/` z listą `.deleted`, a `replay` go odtwarza i sprawdza; test dymny odtwarza każdą referencję (dziś pięć). Czytnik frontmattera w runnerze przyjmuje frontmatter zamknięty na końcu pliku | 1.7 |
|
||||
| 2.0.6 | 2026-11-11 | Testy i poprawka parsera, którą znalazły; bez nowych funkcji. **Czytniki frontmattera są zgodne:** osiem skryptów czytających frontmatter stron (lint, wyszukiwanie, konsolidacja, oba eksporty, dedup, share, serwer mcp) kończy go teraz na linii będącej dokładnie `---`, także na samym końcu pliku; konsolidacja, dedup, OKF i share pomijały frontmatter zamknięty bez końcowego znaku nowej linii, a wyszukiwanie, Starlight i serwer mcp kończyły go na dowolnej linii zaczynającej się od `---`. Nowy `tests/unit/test_frontmatter_contract.py` podaje wszystkim ośmiu te same przypadki. **Każde sprawdzenie lintu działa:** `tests/unit/test_lint_dirty.py` podkłada po jednym błędzie na sprawdzenie (zgodność, świeżość, pewność, retencja, decyzje, sieroty, graf, indeks/log, odciski, crux, przegląd, sprzeczności, tagi) w kopii fixture'a i sprawdza, które dokładnie pliki zgłasza każde z nich; złoty `lint.json` dowodził tylko, że na czystej KB sprawdzenia milczą | 1.7 |
|
||||
|
|
|
|||
|
|
@ -1076,6 +1076,8 @@ install one. Say:
|
|||
| `software` | The KB documents software you're building: source repos as gitignored clones in `src/`, code mapped into wiki entities, and specs with OpenSpec | [OPENSPEC.md](OPENSPEC.md) · [module README](../.agents/modules/software/README.md) |
|
||||
| `capture` | Save links, articles, PDFs and video transcripts into `raw/inbox/` as dated snapshots, with a Wayback fallback and duplicate check | [module README](../.agents/modules/capture/README.md) |
|
||||
| `share` | Send a document to another KB through a shared git repo (one append-only mailbox per KB), and take what other KBs sent into `raw/inbox/`, with versions, retractions and a sender check | [module README](../.agents/modules/share/README.md) |
|
||||
| `voice` | Write everything the KB sends out (kept answers, documents, reports, the project overview) in your team's voice, from a profile kept as a wiki page in `wiki/voice/`. Wording changes; facts, quotes, sources and code don't | [module README](../.agents/modules/voice/README.md) |
|
||||
| `convert` | Turn any Markdown file (a document from a template, a kept answer, a report) into Word, ODT, PDF or HTML through pandoc, in a house style kept in `templates/styles/`: describe it ("Georgia 11pt, navy headings, A4") or bring your company's Word template | [module README](../.agents/modules/convert/README.md) |
|
||||
| `mcp` | Use the KB from Claude's web/desktop/mobile apps, Claude Code or another agent through an MCP server: search, read, add material, undo a misfiled submission. Several KBs can be connected at once | [MCP.md](MCP.md) · [module README](../.agents/modules/mcp/README.md) |
|
||||
|
||||
Skill: `.agents/skills/ckb-module/SKILL.md`.
|
||||
|
|
|
|||
|
|
@ -1127,6 +1127,8 @@ nieaktywne, dopóki ich nie zainstalujesz. Powiedz:
|
|||
| `software` | Baza dokumentuje tworzone oprogramowanie: repozytoria jako ignorowane klony w `src/`, kod mapowany na encje wiki, specyfikacje z OpenSpec | [OPENSPEC.pl.md](OPENSPEC.pl.md) · [README modułu](../.agents/modules/software/README.pl.md) |
|
||||
| `capture` | Zapisywanie linków, artykułów, PDF-ów i transkrypcji filmów w `raw/inbox/` jako datowanych zrzutów, z Wayback w razie niepowodzenia i sprawdzaniem duplikatów | [README modułu](../.agents/modules/capture/README.pl.md) |
|
||||
| `share` | Wysyłanie dokumentu do innej bazy przez wspólne repozytorium git (jedna skrzynka na bazę, tylko dopisywanie) i odbieranie tego, co wysłały inne bazy, do `raw/inbox/` — z wersjami, wycofaniami i sprawdzeniem nadawcy | [README modułu](../.agents/modules/share/README.md) |
|
||||
| `voice` | Wszystko, co baza wysyła na zewnątrz (zachowane odpowiedzi, dokumenty, raporty, przegląd projektu), pisane głosem zespołu według profilu trzymanego jako strona wiki w `wiki/voice/`. Zmieniają się sformułowania; fakty, cytaty, źródła i kod — nie | [README modułu](../.agents/modules/voice/README.md) |
|
||||
| `convert` | Zamiana dowolnego pliku Markdown (dokumentu z szablonu, zachowanej odpowiedzi, raportu) na Word, ODT, PDF lub HTML przez pandoca, w stylu firmowym trzymanym w `templates/styles/`: wystarczy go opisać („Georgia 11pt, granatowe nagłówki, A4”) albo przynieść firmowy szablon Worda | [README modułu](../.agents/modules/convert/README.pl.md) |
|
||||
| `mcp` | Korzystanie z bazy w aplikacjach Claude (web/desktop/mobile), Claude Code lub innym agencie przez serwer MCP: wyszukiwanie, odczyt, dodawanie materiału, cofanie źle skierowanego zgłoszenia. Można podłączyć kilka baz naraz | [MCP.pl.md](MCP.pl.md) · [README modułu](../.agents/modules/mcp/README.pl.md) |
|
||||
|
||||
Skill: `.agents/skills/ckb-module/SKILL.md`.
|
||||
|
|
|
|||
89
docs/decisions/0020-voice-module.md
Normal file
89
docs/decisions/0020-voice-module.md
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
---
|
||||
type: decision
|
||||
tldr: Outgoing text gets a team voice through an opt-in `voice` module — profiles are wiki pages in wiki/voice/ (type voice-profile), settings live in ckb.yaml, an AGENTS.md block routes every prose file under apply_to through ckb-voice, frozen spans (frontmatter, Sources, Crux, quotes, Notes, code, numbers, names) never change, and an external rewriting skill can be plugged in with `writer:`.
|
||||
status: accepted
|
||||
decided_on: 2026-11-11
|
||||
decided_by: Michał Kopeć
|
||||
affects: .agents/modules/voice/, .agents/skills/ckb-module/SKILL.md, README.md, docs/MANUAL.md, docs/CHANGELOG.md
|
||||
confidence: 0.7
|
||||
quality: 0.8
|
||||
last_updated: 2026-11-11
|
||||
freshness_window_days: 365
|
||||
retention: high
|
||||
---
|
||||
|
||||
# D-0020 — A voice module for text that leaves the KB
|
||||
|
||||
**Status:** Accepted · **Decided:** 2026-11-11 · **Deciders:** Michał Kopeć
|
||||
|
||||
## Context
|
||||
|
||||
Kept answers, documents from templates, consolidation reports and the
|
||||
project overview are read by people outside the KB, and they read like a
|
||||
model wrote them. Michał already runs a personal `ghost-writer` skill
|
||||
(banned AI vocabulary, rhythm, the abstraction trap, named voice profiles)
|
||||
in his home directory, and wanted the same pass on everything the KB sends
|
||||
out, with the profile kept in the KB itself so the team can maintain it.
|
||||
|
||||
## Decision
|
||||
|
||||
1. **An opt-in module** (D-0001 pattern), `voice`, with one skill,
|
||||
`ckb-voice`, and no script. Many KBs never publish anything, so the base
|
||||
pays no context for it.
|
||||
2. **The profile is a wiki page**, `wiki/voice/<name>.md`, `type:
|
||||
voice-profile`, with `voice_of` (team/person/third-party) and the usual
|
||||
`## Sources` and protected `## Notes`. It is knowledge the team reviews
|
||||
and corrects. A skill-folder file would be invisible to teammates and
|
||||
lost on a clone. Pages are created, and logged, by `ckb-voice` on the
|
||||
first calibration, never by the install.
|
||||
3. **Settings live in `ckb.yaml`** under the module's `config:` (`mode`,
|
||||
`profile`, `writer`, `apply_to`, `skip`, `chat`). `ckb-module` gains
|
||||
`default_config` in the manifest to write them on install and keeps
|
||||
edited values on a reinstall.
|
||||
4. **The hook is the `AGENTS.md` block, not edits to each skill.** The
|
||||
installed fragment says that any prose file written under `apply_to`
|
||||
goes through `ckb-voice`, whichever skill drafted it. `ckb-document`,
|
||||
`ckb-retrieve`, `ckb-consolidate` and `ckb-project-summary` stay
|
||||
unchanged, and a future skill writing to `outputs/` is covered without
|
||||
a change.
|
||||
5. **Wording only; content is frozen.** Frontmatter, `## Sources`, `## Crux`,
|
||||
quotes and their attributions, `## Notes`/`## Rules`, contradiction
|
||||
markers, `<private>` spans, code, paths, links, numbers, names and a
|
||||
template's headings are kept byte-for-byte and diffed before writing.
|
||||
Ghost-writer's rule to cut any claim that can't be made specific is
|
||||
inverted. Such a claim is kept and flagged, because in a KB its source
|
||||
may say more and dropping it changes the content.
|
||||
6. **Profile precedence:** named in the request, then `voice:` on the
|
||||
person's `workload/profiles/` page, then the configured default. Never
|
||||
two profiles in one text.
|
||||
7. **Pluggable writer.** `writer:` can name another installed skill (a
|
||||
personal `ghost-writer`). `ckb-voice` still resolves the profile and runs
|
||||
the freeze check; when the skill is missing on a machine it falls back to
|
||||
its own rules.
|
||||
8. **Out of scope by construction:** `wiki/`, `raw/`, `workload/`,
|
||||
`templates/`, and the exports (`outputs/okf/`, `outputs/starlight/`),
|
||||
which mirror wiki pages rather than speak for anyone.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
- **Depend on the user's home `ghost-writer`.** It's not in the repo, so
|
||||
teammates wouldn't have it and the profile would live outside the KB.
|
||||
It's kept as an option through `writer:`.
|
||||
- **Profiles in `workload/profiles/` beside personal profiles.** Those are
|
||||
per person and outside retrieval; a house voice is shared knowledge that
|
||||
deserves review status and a log.
|
||||
- **A rewrite step in every output-writing skill.** Four skills to edit now,
|
||||
and every future one to remember. The single `AGENTS.md` rule does the
|
||||
same job.
|
||||
- **Rewrite wiki pages too.** The wiki is evidence for retrieval and lint;
|
||||
voice belongs at the boundary, not in the store.
|
||||
|
||||
## Consequences
|
||||
|
||||
- One more page type, `voice-profile`, and one field, `voice`, additive on
|
||||
schema 1.7 with no version bump.
|
||||
- A rewrite costs a model pass per output file; `mode: ask` or `off` turns
|
||||
it down.
|
||||
- The freeze check runs in the agent, not in a script, so it is only as
|
||||
strict as the agent following it. A script diffing frozen spans is the
|
||||
natural follow-up if drift shows up.
|
||||
90
docs/decisions/0021-convert-module.md
Normal file
90
docs/decisions/0021-convert-module.md
Normal file
|
|
@ -0,0 +1,90 @@
|
|||
---
|
||||
type: decision
|
||||
tldr: Markdown leaves the KB as Word/ODT/PDF/HTML through an opt-in `convert` module — pandoc does the conversion, the look is a named reference .docx in templates/styles/ that a stdlib script can build or adjust from a few settings or copy from a company .docx/.dotx, PDF and ODT go through LibreOffice from the styled .docx so every format matches, and the Markdown stays the source.
|
||||
status: accepted
|
||||
decided_on: 2026-11-11
|
||||
decided_by: Michał Kopeć
|
||||
affects: .agents/modules/convert/, tests/unit/test_convert.py, tests/evals/ckb-module/install-convert/, README.md, docs/MANUAL.md, docs/CHANGELOG.md
|
||||
confidence: 0.75
|
||||
quality: 0.8
|
||||
last_updated: 2026-11-11
|
||||
freshness_window_days: 365
|
||||
retention: high
|
||||
---
|
||||
|
||||
# D-0021 — A convert module for documents that leave as Office files
|
||||
|
||||
**Status:** Accepted · **Decided:** 2026-11-11 · **Deciders:** Michał Kopeć
|
||||
|
||||
## Context
|
||||
|
||||
`ckb-document`, kept answers and reports all write Markdown. The people they
|
||||
go to want a Word file or a PDF in the company's look. `ckb-document` Step 4
|
||||
says to make a `.docx` "with the general document skills", which leaves the
|
||||
fonts, sizes and margins to whatever the agent picks each time. Michał wanted
|
||||
a pandoc front end with design templates, so users get a consistent document
|
||||
without thinking about typography.
|
||||
|
||||
## Decision
|
||||
|
||||
1. **An opt-in module** (D-0001 pattern), `convert`, with one skill,
|
||||
`ckb-convert`, and one stdlib script, `convert.py`. pandoc is a system
|
||||
tool not every KB needs.
|
||||
2. **A style is a reference `.docx`** in `templates/styles/<name>.docx`,
|
||||
pandoc's own mechanism: it takes styles, page setup, header and footer
|
||||
from it and ignores the text. Optional `<name>.odt` and `<name>.css` cover
|
||||
ODT and HTML. `templates/` already holds the user's document templates and
|
||||
isn't a retrieval layer. `ckb-document` lists only `templates/*.md`, so the
|
||||
subfolder doesn't clash.
|
||||
3. **Styles from settings, not by hand.** `new-style`/`edit-style` copy
|
||||
pandoc's default reference and patch body font, heading font, body size,
|
||||
heading colour, paper (A4/Letter) and margins straight into
|
||||
`styles.xml`, `theme1.xml` and the body `sectPr`, keeping the schema's
|
||||
child order so Word opens the result. `--from` takes a company `.docx` or
|
||||
`.dotx` (content type rewritten) and `check-style` lists the styles pandoc
|
||||
uses that it lacks. Anything richer (logos, cover pages) is edited in
|
||||
Word, and the skill says so.
|
||||
4. **One look for every format.** PDF and ODT are produced by LibreOffice from
|
||||
the styled `.docx`, in a private profile so an open LibreOffice doesn't
|
||||
block it. Without LibreOffice, PDF falls back to a pandoc PDF engine and
|
||||
the skill reports that the style wasn't applied.
|
||||
5. **KB Markdown is cleaned for an outside reader**, in the copy only:
|
||||
frontmatter → title/author/date/lang metadata (e-mail dropped), the
|
||||
leading `# H1` → title, template comments dropped, wikilinks and KB-path
|
||||
links → text (`keep_links` opts out), code blocks untouched.
|
||||
6. **The Markdown stays the source**, always kept. An existing converted file
|
||||
is never overwritten without `--force`; the skill asks, since it may have
|
||||
been edited in Word.
|
||||
7. **Settings in `ckb.yaml`** through `default_config` (D-0020): `style`,
|
||||
`format`, `out_dir`, `toc`, `number_sections`, `keep_links`.
|
||||
8. **Hook through the `AGENTS.md` block**, as D-0020 did: any request for an
|
||||
Office/PDF file goes through `ckb-convert`, after `ckb-voice` when that is
|
||||
installed. `ckb-document` is unchanged.
|
||||
9. **pandoc is a non-blocking dependency** of the install. The module is
|
||||
committed and shared, and a teammate without pandoc gets install
|
||||
instructions at first use rather than a blocked install for everyone.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
- **python-docx or the general docx skill** to build documents directly.
|
||||
These need a third-party package or produce a different look per run, and
|
||||
they can't read the Markdown the KB already has. pandoc is the standard
|
||||
tool for exactly this conversion.
|
||||
- **Ship a binary `house.docx` in the module.** A binary in the template
|
||||
repo, and a single fixed look. Generating it from pandoc's default plus
|
||||
settings keeps the repo text-only and the look adjustable.
|
||||
- **pandoc's LaTeX route for PDF.** It needs a TeX install and a second style
|
||||
definition that drifts from the Word one. LibreOffice reuses the `.docx`.
|
||||
- **Edit `ckb-document` to convert.** That would cover one producer only.
|
||||
Answers, reports and wiki pages need conversion too.
|
||||
|
||||
## Consequences
|
||||
|
||||
- No new page types or fields; no schema change.
|
||||
- Fonts aren't embedded in `.docx`; a rare font shows as a substitute. The
|
||||
README and skill say so.
|
||||
- The XML patching covers the settings listed and nothing else. A company
|
||||
template with unusual structure gets `check-style` and a pointer to Word.
|
||||
- Tests: `tests/unit/test_convert.py` (clean-up always; style patching and
|
||||
conversion when pandoc is present) and an install eval,
|
||||
`ckb-module/install-convert`, not yet run.
|
||||
|
|
@ -33,3 +33,5 @@ but they live here, in the template layer, because:
|
|||
| [D-0017](0017-capture-module-and-skill-evals.md) | Opt-in `capture` module (stdlib fetch, Wayback only over a failed/thinner page, agent tool fallback, untrusted marking, dedup at capture, `yt-dlp` with consent); structural skill evals with a prepare/check runner; multi-agent setup documented as untested |
|
||||
| [D-0018](0018-share-mailbox-module.md) | Opt-in `share` module: KBs exchange documents through a git channel with one append-only mailbox per KB; received mail lands in `raw/inbox/` (untrusted) and retractions in `raw/retractions/`; the git author must own the mailbox; handled messages are kept in a ledger in `ckb.yaml` |
|
||||
| [D-0019](0019-two-dot-zero-drops-powershell.md) | Template 2.0.0 drops PowerShell; every script the template and its modules ship is Python (bash fallback and the container entrypoint named as exceptions); 1.x continues on a `1.x` maintenance branch; `ckb-upgrade` never crosses a major version without asking |
|
||||
| [D-0020](0020-voice-module.md) | Opt-in `voice` module: outgoing prose (kept answers, documents, reports, the project overview) is rewritten in a voice whose profile is a wiki page in `wiki/voice/`; settings in `ckb.yaml`; routed by the `AGENTS.md` block, not per-skill edits; frozen spans never change, vague claims are flagged rather than cut; `writer:` plugs in an external rewriting skill |
|
||||
| [D-0021](0021-convert-module.md) | Opt-in `convert` module: Markdown becomes Word/ODT/PDF/HTML through pandoc in a named house style, a reference `.docx` in `templates/styles/` built from a few settings or copied from a company `.docx`/`.dotx`; PDF and ODT go through LibreOffice from the styled `.docx`; KB links and frontmatter are cleaned in the copy; the Markdown stays the source |
|
||||
|
|
|
|||
|
|
@ -36,6 +36,8 @@ run fails there.
|
|||
| `ckb-decide/record` | 2026-11-02 | yes |
|
||||
| `ckb-reset/no-confirm`, `ckb-reset/confirmed` | 2026-11-11 | confirmed only |
|
||||
| `ckb-module/install`, `ckb-module/round-trip` | 2026-11-11 | install only |
|
||||
| `ckb-module/install-voice` | not run yet | no |
|
||||
| `ckb-module/install-convert` | not run yet | no |
|
||||
| `ckb-upgrade/major-guard`, `ckb-upgrade/take-major` | 2026-11-11 | no (a reference would copy the template's docs) |
|
||||
| `ckb-decide/supersede` | 2026-11-11 | yes |
|
||||
| `ckb-ingest/check-in-waits`, `ckb-ingest/reviewed-page` | 2026-11-11 | reviewed-page only |
|
||||
|
|
|
|||
53
tests/evals/ckb-module/install-convert/case.json
Normal file
53
tests/evals/ckb-module/install-convert/case.json
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
{
|
||||
"skill": "ckb-module",
|
||||
"fixture": "minimal-kb",
|
||||
"setup": [
|
||||
{
|
||||
"template": [
|
||||
".agents/skills",
|
||||
".agents/modules",
|
||||
"AGENTS.md",
|
||||
".gitignore"
|
||||
]
|
||||
}
|
||||
],
|
||||
"prompt": "Install the convert module. You don't need to ask me first.",
|
||||
"assert": [
|
||||
{
|
||||
"file_exists": ".agents/skills/ckb-convert/SKILL.md"
|
||||
},
|
||||
{
|
||||
"file_exists": ".agents/skills/ckb-convert/scripts/convert.py"
|
||||
},
|
||||
{
|
||||
"file_exists": "templates/styles/README.md"
|
||||
},
|
||||
{
|
||||
"file_contains": {
|
||||
"path": "AGENTS.md",
|
||||
"regex": "(?i)MODULE: convert"
|
||||
}
|
||||
},
|
||||
{
|
||||
"file_contains": {
|
||||
"path": "ckb.yaml",
|
||||
"regex": "name: convert"
|
||||
}
|
||||
},
|
||||
{
|
||||
"file_contains": {
|
||||
"path": "ckb.yaml",
|
||||
"regex": "style: house"
|
||||
}
|
||||
},
|
||||
{
|
||||
"file_absent": "templates/styles/*.docx"
|
||||
},
|
||||
{
|
||||
"unchanged": ".agents/modules/**/*"
|
||||
},
|
||||
{
|
||||
"unchanged": "wiki/**/*"
|
||||
}
|
||||
]
|
||||
}
|
||||
56
tests/evals/ckb-module/install-voice/case.json
Normal file
56
tests/evals/ckb-module/install-voice/case.json
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
{
|
||||
"skill": "ckb-module",
|
||||
"fixture": "minimal-kb",
|
||||
"setup": [
|
||||
{
|
||||
"template": [
|
||||
".agents/skills",
|
||||
".agents/modules",
|
||||
"AGENTS.md",
|
||||
".gitignore"
|
||||
]
|
||||
}
|
||||
],
|
||||
"prompt": "Install the voice module. You don't need to ask me first.",
|
||||
"assert": [
|
||||
{
|
||||
"file_exists": ".agents/skills/ckb-voice/SKILL.md"
|
||||
},
|
||||
{
|
||||
"file_exists": ".agents/skills/ckb-voice/references/rules.md"
|
||||
},
|
||||
{
|
||||
"file_contains": {
|
||||
"path": "AGENTS.md",
|
||||
"regex": "(?i)MODULE: voice"
|
||||
}
|
||||
},
|
||||
{
|
||||
"file_contains": {
|
||||
"path": "ckb.yaml",
|
||||
"regex": "name: voice"
|
||||
}
|
||||
},
|
||||
{
|
||||
"file_contains": {
|
||||
"path": "ckb.yaml",
|
||||
"regex": "mode: auto"
|
||||
}
|
||||
},
|
||||
{
|
||||
"file_contains": {
|
||||
"path": "ckb.yaml",
|
||||
"regex": "profile: house"
|
||||
}
|
||||
},
|
||||
{
|
||||
"file_absent": "wiki/voice/**"
|
||||
},
|
||||
{
|
||||
"unchanged": ".agents/modules/**/*"
|
||||
},
|
||||
{
|
||||
"unchanged": "wiki/**/*"
|
||||
}
|
||||
]
|
||||
}
|
||||
146
tests/unit/test_convert.py
Normal file
146
tests/unit/test_convert.py
Normal file
|
|
@ -0,0 +1,146 @@
|
|||
"""convert module: the Markdown clean-up is pure and always tested; the style
|
||||
patching and real conversions run only where pandoc is installed."""
|
||||
import contextlib
|
||||
import importlib.util
|
||||
import io
|
||||
import re
|
||||
import shutil
|
||||
import tempfile
|
||||
import unittest
|
||||
import xml.dom.minidom
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
SPEC = importlib.util.spec_from_file_location(
|
||||
"convert", str(ROOT / ".agents/modules/convert/skills/ckb-convert/scripts/convert.py"))
|
||||
convert = importlib.util.module_from_spec(SPEC)
|
||||
SPEC.loader.exec_module(convert)
|
||||
|
||||
DOC = """---
|
||||
type: document
|
||||
created: 2026-11-11
|
||||
author: Ada Lovelace <ada@example.com>
|
||||
---
|
||||
|
||||
# Status: Atlas
|
||||
|
||||
<!-- Ask the user. -->
|
||||
See [[Atlas Retry Policy]] ([atlas](/wiki/entities/atlas.md)), [Maria](/wiki/entities/maria.md),
|
||||
[[x/y/page|the page]], [web](https://example.com) and .
|
||||
|
||||
```md
|
||||
[[keep]] <!-- keep --> [k](/wiki/k.md)
|
||||
```
|
||||
"""
|
||||
|
||||
|
||||
class Prepare(unittest.TestCase):
|
||||
def test_metadata_from_frontmatter_and_heading(self):
|
||||
meta, body = convert.prepare(DOC, keep_links=False)
|
||||
self.assertEqual(meta, {"title": "Status: Atlas", "author": "Ada Lovelace", "date": "2026-11-11"})
|
||||
self.assertNotIn("# Status", body)
|
||||
self.assertNotIn("type: document", body)
|
||||
|
||||
def test_kb_links_become_text_web_links_and_images_stay(self):
|
||||
_, body = convert.prepare(DOC, keep_links=False)
|
||||
self.assertIn("See Atlas Retry Policy, Maria,", body)
|
||||
self.assertIn("the page,", body)
|
||||
self.assertIn("[web](https://example.com)", body)
|
||||
self.assertIn("", body)
|
||||
self.assertNotIn("Ask the user", body)
|
||||
|
||||
def test_code_blocks_untouched(self):
|
||||
_, body = convert.prepare(DOC, keep_links=False)
|
||||
self.assertIn("[[keep]] <!-- keep --> [k](/wiki/k.md)", body)
|
||||
|
||||
def test_keep_links(self):
|
||||
_, body = convert.prepare(DOC, keep_links=True)
|
||||
self.assertIn("[Atlas Retry Policy](/wiki/entities/atlas.md)", body)
|
||||
self.assertIn("[Maria](/wiki/entities/maria.md)", body)
|
||||
|
||||
def test_frontmatter_title_wins_and_heading_stays(self):
|
||||
meta, body = convert.prepare("---\ntitle: Report\n---\n\n# Intro\n\nText\n", False)
|
||||
self.assertEqual(meta["title"], "Report")
|
||||
self.assertIn("# Intro", body)
|
||||
|
||||
def test_heading_after_text_is_not_the_title(self):
|
||||
meta, body = convert.prepare("Some text.\n\n# Later\n", False)
|
||||
self.assertNotIn("title", meta)
|
||||
self.assertIn("# Later", body)
|
||||
|
||||
|
||||
class SchemaOrder(unittest.TestCase):
|
||||
def test_insert_respects_order(self):
|
||||
inner = '<w:rFonts w:ascii="A"/><w:sz w:val="24"/><w:lang w:val="en"/>'
|
||||
out = convert.set_child(inner, "color", '<w:color w:val="112233"/>', convert.RPR_ORDER)
|
||||
self.assertLess(out.index("w:color"), out.index("w:sz"))
|
||||
self.assertGreater(out.index("w:color"), out.index("w:rFonts"))
|
||||
out = convert.set_child(out, "sz", '<w:sz w:val="22"/>', convert.RPR_ORDER)
|
||||
self.assertEqual(out.count("<w:sz "), 1)
|
||||
self.assertLess(out.index("w:sz"), out.index("w:lang"))
|
||||
|
||||
|
||||
@unittest.skipUnless(shutil.which("pandoc"), "pandoc not installed")
|
||||
class WithPandoc(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.root = Path(self.tmp.name)
|
||||
(self.root / "outputs/documents").mkdir(parents=True)
|
||||
(self.root / "outputs/documents/r.md").write_text(DOC, encoding="utf-8")
|
||||
|
||||
def tearDown(self):
|
||||
self.tmp.cleanup()
|
||||
|
||||
def cli(self, *a):
|
||||
with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):
|
||||
return convert.main(["--root", str(self.root)] + list(a))
|
||||
|
||||
def test_style_settings_land_in_valid_xml(self):
|
||||
self.assertEqual(self.cli("new-style", "house", "--body-font", "Georgia", "--size", "11",
|
||||
"--heading-color", "#1f3864", "--paper", "a4", "--margin-cm", "2"), 0)
|
||||
z = zipfile.ZipFile(self.root / "templates/styles/house.docx")
|
||||
for n in z.namelist():
|
||||
if n.endswith(".xml"):
|
||||
xml.dom.minidom.parseString(z.read(n))
|
||||
styles = z.read("word/styles.xml").decode()
|
||||
doc = z.read("word/document.xml").decode()
|
||||
default = re.search(r"<w:rPrDefault>.*?</w:rPrDefault>", styles, re.S).group(0)
|
||||
self.assertIn('w:ascii="Georgia"', default)
|
||||
self.assertIn('<w:sz w:val="22"/>', default)
|
||||
h1 = re.search(r'<w:style [^>]*w:styleId="Heading1".*?</w:style>', styles, re.S).group(0)
|
||||
self.assertIn('<w:color w:val="1F3864"/>', h1)
|
||||
self.assertEqual(h1.count("<w:color "), 1)
|
||||
self.assertIn('<w:pgSz w:w="11906" w:h="16838"/>', doc)
|
||||
self.assertIn('w:top="1134"', doc)
|
||||
|
||||
def test_convert_docx_and_refuse_overwrite(self):
|
||||
self.cli("new-style", "house")
|
||||
self.assertEqual(self.cli("convert", str(self.root / "outputs/documents/r.md")), 0)
|
||||
out = self.root / "outputs/documents/r.docx"
|
||||
self.assertTrue(out.exists())
|
||||
doc = zipfile.ZipFile(out).read("word/document.xml").decode()
|
||||
self.assertIn("Status: Atlas", doc)
|
||||
self.assertNotIn("Ask the user", doc)
|
||||
self.assertEqual(self.cli("convert", str(self.root / "outputs/documents/r.md")), 1)
|
||||
self.assertEqual(self.cli("convert", str(self.root / "outputs/documents/r.md"), "--force"), 0)
|
||||
|
||||
def test_dotx_becomes_docx(self):
|
||||
self.cli("new-style", "house")
|
||||
dotx = self.root / "Company.dotx"
|
||||
shutil.copyfile(self.root / "templates/styles/house.docx", dotx)
|
||||
convert.rewrite_zip(dotx, {"[Content_Types].xml": lambda x: x.replace(convert.DOCX_CT, convert.DOTX_CT)})
|
||||
self.assertEqual(self.cli("new-style", "company", "--from", str(dotx)), 0)
|
||||
ct = zipfile.ZipFile(self.root / "templates/styles/company.docx").read("[Content_Types].xml").decode()
|
||||
self.assertIn(convert.DOCX_CT, ct)
|
||||
self.assertNotIn(convert.DOTX_CT, ct)
|
||||
|
||||
def test_refusals(self):
|
||||
self.assertEqual(self.cli("new-style", "Bad Name"), 1)
|
||||
self.assertEqual(self.cli("edit-style", "nope", "--size", "10"), 1)
|
||||
self.assertEqual(self.cli("convert", str(self.root / "outputs/documents/r.md"),
|
||||
"--style", "nope", "--style-required"), 1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Loading…
Add table
Reference in a new issue