Diamond Legendz

Wikidoc

The only skill you initially need. By Alex Adamczyk.

An AI agent forgets everything when the session ends. Wikidoc is the routine that writes down what a session decided, in a wiki I own, before that happens. Start with this one skill and the others grow out of it.

A skill is a short file of instructions an AI agent loads when a job comes up. This page explains this one in plain words, then prints the whole file. The other skill I have written up is Elegance, a code cleanup that proves it changed nothing.

What it does

After a stretch of work, one cheap AI model reads what was said, and writes the lasting parts into the wiki:

It never pastes a transcript, a tool's output or an agent's report. It writes conclusions. The test is whether I could read the page a year from now and know what was decided and why, without the session.

Why it comes first

So you do not need to design a set of skills up front. Run this one, work normally, and it tells you which skills you are missing.

How a pass runs

  1. A counter triggers it. Every tenth message I send, a small script gathers what is new across the AI sessions on my machine into a digest file.
  2. One cheap model does the writing. The session I am working in hands the digest to a single mid-priced model and carries on with its own work.
  3. It finds the right page. Each fact lives on one page. Other pages link to it.
  4. It logs, checks and saves. One log line per page touched, a link checker over the whole wiki, a commit and a push.
  5. It reports in one paragraph, plus its list of skill suggestions.
  6. The main session verifies the commit and the checker's result before trusting the report.
Two passes from one nightTokensTimePages touched
First475,55728 minutes22
Second422,72022 minutes18

The wiki stood at 307 pages after those two, with no broken links. A pass is not cheap: about half a million tokens of a mid-priced model. It is the reason every other session starts informed.

The rules that matter most

A lesson from the night this page was written

The rule that suggestions must reach me was already in the file. It still failed. Over many passes the report on them had shrunk to a single clause, and 118 suggestions were sitting on a page I never opened.

I noticed, and said so. The fix went into the skill itself that night: every pass now ends with a short "Skill updates" line to me, every time. It says what was applied, what is new and waiting, and what needs my word. If nothing is new it still gives the count.

That is the routine working as intended. A habit drifted, the record showed it, and the correction was written into the file the agents load.

To start your own

  1. Make a folder of plain text pages and put it under version control. That is the wiki.
  2. Write one page on what the wiki is for and how pages are named and linked.
  3. Copy the skill file below and change the paths and the names to yours.
  4. Run it by hand at the end of a working session for a week. Read what it writes.
  5. Correct it by ruling, not by editing its pages. Tell the agent what was wrong and why. The next pass records the ruling, and suggests the change to the skill.
  6. Add the counter once you trust it, so it runs without being asked. Both scripts are at the bottom of this page.
  7. Read the skill suggestions. That list is your next skill.

How often it runs, and what that costs

Every tenth message is my setting. The number is arbitrary. It is one line in the watcher, and you should set your own.

So the trade is cost against what gets missed. I have measured the cost. The limits are what I have seen in use, not a tested figure.

The skill file, whole

This is the file my AI agents load. It is dense, because it is written for them. Three things are changed for this page: the list of topics I keep out of the record is replaced by one sentence, one line about a single project's page is removed, and my local folder paths are shortened. Nothing else is changed. It refers to a second file, the list of topics, which is not published.

# /wikidoc

Turn what this session learned into wiki pages, then leave the trail the wiki's own tooling expects.
The wiki is `~/.claude/wiki/` (a private git repo), **not** the Desktop
"Personal Wiki" folder. Read `nodes/meta.md` once per session before writing if you have not.

The wiki is the last filter in the stack (see memory `context-as-filter-stack`): it gets conclusions,
rulings, method and state, never tool output, transcripts or agent reports. Alex should be able to
read a page a year from now and know what was decided and why, without the session.

## The watcher (auto-wikidoc every 10 prompts, since 2026-10-08)

A UserPromptSubmit hook (`~/.claude/scripts/wikidoc_hook.py`) counts Alex's prompts per session (the status
line shows `msgs N | wikidoc in M`). On every 10th prompt it runs `~/.claude/scripts/wikidoc_digest.py`,
which condenses what is NEW across this machine's Claude Code transcripts since the last digest (user and
assistant text only, never tool output; per-file offsets in `~/.claude/wikidoc/offsets.json`) into
`~/.claude/wikidoc/digests/<stamp>.md`, and hands the active session one line of context naming it. **When
that line arrives:** at the next natural pause, delegate this skill to ONE Sonnet subagent (effort max) with
the digest path, under the session's own permissions; it does steps 2 to 8 below with the digest as the
harvest; verify its one-paragraph report, then deal with its `Skill suggestions` as the pilot's own job (see
"Skill refinement" below; the Sonnet suggests, it never edits a skill); never paste the digest into chat. Claude Code only: Hermes runs its
own loop over its own sessions (ABS note of 2026-10-08). Manual: `python wikidoc_digest.py --dry-run` to see
what a digest would hold; `--init-offsets DAYS` to start over from DAYS back.
The hook counts only Alex's own words (fixed 2026-11-17 on his word: "fix that wiki issue so it only eats my words
not those auto things"): scheduled prompts are skipped, so a prompt the session schedules for itself must start
with `[scheduled]`. A session may hold a due pass when he needs the tokens elsewhere ("sure allow it"): the
digest stays on disk and the next pass takes every digest newer than the log's last FLAGGED line. A pass costs
about 430,000 to 570,000 tokens and 23 to 33 minutes (thirteen readings to 2026-11-24), more as the pages grow.
The hook skips a prompt only when it begins with `[scheduled]`, `stall watch`, `overnight stall watch`,
`15-minute check-in`, `half-hour check-in` or `one check on`; any other check-in wording counts as his prompt.
**One pass at a time** (Alex, 2026-11-18: "the two WikiPass lock is great"; passes from two sessions had met on
11-17 and twice on 11-18). When the hook hands a session a digest it writes `~/.claude/wikidoc/pass.lock`
(session, digest, time). While that lock is under 75 minutes old the hook hands no session another digest and
builds none; the words wait for the next one. The hook's line also lists every digest the wiki log has not
filed yet, and the delegating session names all of them in the brief. The brief takes "the last pass" from the
wiki itself (`git log -1` and the log's last digest line), never from the session's memory: a summary after a
context cut named a pass two digests old, twice on 2026-11-21. The pass deletes the lock after its push
(step 6). A session that holds a due pass instead of running it deletes the lock, so another session can take it.

## Procedure

1. **Harvest from this session only** (or from the digest the watcher named). A digest the brief names that
   the log's last FLAGGED line already holds is audited, not redone: read it against that pass's pages and the
   hold-back grep, write only what is missing, and say so in FLAGGED (2026-11-17, twice). A stretch the pilot filed itself (the brief names its commit) is done: do not edit, repeat or point at it, and report a suspected error instead of changing it (2026-11-24). List, privately, what is durable: decisions and their reasons
   (in Alex's words where he gave them), method changes, project state that a successor needs,
   numbers that changed a decision, people and their roles, open questions with the recommendation.
   Skip anything the repo, git history or an existing page already records. Skip what only mattered
   today.
   Reading a digest (mechanics added 2026-11-16 from the pass's own suggestions; Alex: "those are
   probably good mechanics improvemnts"): its message stamps are **UTC** while the file name and
   header are local time; pages use local time, so convert. A message ending `[...]` was cut at about
   1,500 characters: complete it read-only from the project's own record (CANON.md, DESIGN.md and the
   like), trust the record over the digest, and mark on the page what no record holds ("not said").
   **His own messages have no project record** (added 2026-11-19 on his word; four passes had done it by
   hand). Complete one of his that was cut, and find the ones he typed while a turn was running (no digest
   holds those), in the session's transcript, read-only: `~/.claude/projects/<folder>/<session>.jsonl`. His
   typed messages are the `user` records whose content is plain text and the records of type `attachment`
   whose `attachment.type` is `queued_command` (the text is in `attachment.prompt`; the `queue-operation`
   records around one repeat it, skip those). A time window, UTC stamps, in one line:
   `python -X utf8 -c "import json,sys;a,b=sys.argv[2:4];j=lambda t:' '.join(p.get('text','') if p.get('type')=='text' else '[IMAGE]' for p in t if p.get('type') in('text','image')) if isinstance(t,list) else t;[print(r['timestamp'][:19],t[:20000]) for r in map(json.loads,open(sys.argv[1],encoding='utf-8')) for t in [j((r.get('attachment') or {}).get('prompt') if (r.get('attachment') or {}).get('type')=='queued_command' else (r.get('message') or {}).get('content') if r.get('type')=='user' else None)] if isinstance(t,str) and t and a<=r.get('timestamp','')<=b]" <session>.jsonl 2026-11-19T07:24 2026-11-19T07:32`
   (`-X utf8` because Windows' default output encoding stops at the first character outside it; the cut is
   20,000 characters because the point is the whole message.)
   A message of his that carries a picture is a list of parts and not a string: the command joins its `text`
   parts and marks each image `[IMAGE]` (added 2026-11-19: the earlier command skipped such a message without a
   sign; a short script file reads better than the one-liner).
   The same lines that are not his words in a digest are not his words here (a task notification, a
   hand-back, the harness's summary, and a relay that begins "Another Claude session sent a message": read it
   for state; its facts are the other session's and the people it quotes are not him). His answers in a question
   form are his words, though the transcript files them as tool results and no digest holds them: scan for them. Say in the log that you read them there.
   **Not his words, though the digest files them under `user`:** a line that begins `[scheduled]` or repeats at
   intervals, even when its text differs from the last (the session's own scheduled prompt; the channel
   session's check-ins name a different Short each time), an agent-message line (a subagent's hand-back), a
   line beginning "This session is being continued from a previous conversation" (the harness's
   summary), a loaded skill's body, `[Image: ...]` lines, and `<bash-input>`/`<bash-stdout>` pairs.
   None is a ruling; read the reply under it for state. The header's session count counts working
   directories, so one session that changed directory shows as several.
   **The project's own record may run past the digest.** Take its entries newer than the digest's last
   line when they settle an open item or complete a cut text, and mark them on the page as the
   record's ("from CANON, after this digest"); leave the rest for the next digest (2026-11-18: Short 1
   went public 14 minutes after a digest's last line). Before starting, read the log's last FLAGGED
   line and `git log`: take in every digest newer than it, even one the brief does not name, and look
   for pages another pass made the same day. **Another session's pass may be writing the same tree
   right now** (2026-11-17: two sessions' passes met; one had already taken in three digests the
   other's brief named): run `git status` first; if the tree is dirty with wiki pages you did not
   touch, wait for that pass's commit, audit its pages against your digests, and write only the
   delta. A session's own memory note can run far off (45 minutes on 2026-11-17, up to three hours on 2026-11-24) the digest's UTC stamps: trust
   the digest for time. To check a page's line endings read the bytes (Python);
   `grep -c $'\r'` in this shell counts every line.
   **A very large record is read by pattern, never whole** (added 2026-11-19 from the passes' own suggestions; a
   project's record can run 300 to 450 KB): `DESIGN.md`'s Decisions list is newest first, so Grep its date pattern
   (`^- \*\*2026-11-19 1[5-8]:`) and read the newest bullets with line limits, and `CANON.md` is oldest first, so
   grep the date and time and read its tail.
   **Compare the record's clock with the commits'** (added 2026-11-19 from the passes' own suggestions; memory
   `design-record-clock`): compare the record's decision-bullet stamps with the `git log` times for the window and
   report each drift (2026-11-19: `DESIGN.md`'s 4:06 am entry said `history.py` was added "at 03:5x" where the
   commit and the digest say 3:43 am, and `CANON.md`'s 8:45 am entry ran on to 8:50). A project folder that is not
   a git repository is checked against the transcript's stamps instead.
   **A digest's trigger prompt is not in it** (added 2026-11-19 from the passes' own suggestions): the digest is
   built when his tenth prompt is submitted, and that prompt's own text is the first line of the next digest, so a
   digest's file name carries the minute of a message it does not hold (the wiki's reading: the hook builds the
   digest before the prompt is in the transcript). Do not take that message as lost and do not take it in twice:
   name it, in the FLAGGED line, as left for the next digest.
   If he typed the trigger while a turn was running, it is a queued command, which no digest holds, so the next
   digest will not hold it either: the next pass reads it from the transcript (the recipe above), and this pass
   still names it in FLAGGED as left. If the project's record quotes the trigger prompt and its entry settles an
   open item, take in the fact it gives (marked as the record's) and leave the quotation.
2. **Find the canonical page for each item** (`ls nodes/`, `grep -ril` the key noun). Facts live on
   their canonical page once; other pages link. One new page only when no page owns the noun (a new
   project, a new person, a new recurring practice). New pages take the frontmatter every node has:
   `visibility` (required; `private` unless Alex says otherwise), `aliases`, `tags` from
   `_meta/tags.md`.
3. **Write in the wiki's register:** dated subsections (`### Title (YYYY-MM-DD)`), short paragraphs,
   `[[wikilinks]]` to every page named (first mention), `{PageName}` for intentional nolinks (second
   mentions, titles), Alex's own phrasing quoted where it is the ruling. Mark who said what: his words quoted
   as typed, the pilot's statements as the pilot's, the pass's own inferences as "the wiki's reading".
   When a digest reports something done (a backup, a push, a deploy) and one read-only look settles
   it, look, and write what the look showed (a push's time and extent are in the project clone's reflog of
   the remote-tracking branch: `git reflog show origin/<branch> --date=format:"%m-%d %H:%M:%S"` prints
   "update by push"). Prefer updating a section to
   appending a diary. Numbers go in a short table when they changed a decision.
   Before writing on a hold-back topic, read the target page's `visibility`: a public page gets none
   of it, not even a pointer to what was left off (2026-11-17: a pass wrote on three public pages and
   one phrase had to be reworded).
4. **Project pages carry one "Where it stands" paragraph** at the top (called "State" on older
   pages): at most about 150 words, stamped "as of" a date and time, saying what is live, what is in
   progress, what is next in order and what waits on Alex. **Rewrite it every pass that adds a fact to the page; never stack a
   second bullet under it and never renumber a list of them** (Alex, 2026-11-15: "Every time it adds
   something, it does a little rewriting as well ... especially if the old copy is preserved
   somewhere"). Before rewriting, move the old paragraph, verbatim, to the top of the project's state
   log page (`<project>-state-log`, newest first; create it on first use and link it from the
   paragraph). The same pass also tidies what the new facts made stale on that page: a resolved Open
   item is struck and moved to the closed list, a ruling Alex reversed moves to the project's rulings
   page with what replaced it, and the dated narrative goes on the page for the current period or
   video (linked as "Main article"), not on the main page. A main project page stays an overview a
   reader can scan: lead, facts table, short sections that link out. If it passes 30,000 bytes (measure the file; a page a few hundred bytes under it is over it
   after the next pass, so split then), split
   a period out to its own page in that pass and say so in the report. Sub pages are the answer to a
   long section too (Alex, 2026-11-16: "yeah sub pages are a good idea"): a section that dominates
   its page, such as a project's doctrine, moves to its own page with a short summary and a link left
   behind. When a period page itself outgrows the size, open the next period's page and link both
   ways. Where the cut-off sits for pages every pass appends to is **not ruled yet** ("idk when we
   mark the cut off just yet"): name such pages and their size in the report, do not split them
   unasked.
   A period or concept page that carries its own "Where it stands" (a release, a candidate) follows
   the same move-and-rewrite rule, its old text going to the project's state log.
   The projects page's entry for a project follows the same rule as the paragraph, with its last dated Update as the
   unit (the entries are stacks of dated Updates, not one sentence; the practice since 2026-11-18): rewrite only the
   last Update each pass, with the old Update moved verbatim to the top of that project's state log.
5. **Log, diagnostically.** Append to `_meta/log.md` one line per page touched:
   `YYYY-MM-DD ACTION PageName — note` where ACTION is CREATE / UPDATE / RENAME / RETIRE and the note
   says what entered the wiki, not a narrative. One more line per pass, `FLAGGED`, names the digest
   taken in and anything left out or unsure. **The log is the only per-pass record** (Alex,
   2026-11-16: "that's what the log is for. We'll keep the log line ... We love the append only log"):
   do not also write a per-digest entry on the claude-code page; that page takes durable Claude Code
   knowledge only.
6. **Lint, then commit.** `cd ~/.claude/wiki/scripts && python -m lint.suite` (unlinked /
   orphans / broken_links; about a second since the 2026-11-18 speed-up, so a run that hangs is a fault); fix what it flags on the pages you
   touched. Then from the wiki root: `git add -A -- . ":(exclude)nodes/.obsidian" && git commit -m "wikidoc: <pages>" && git push` (the exclude keeps Obsidian's own settings files out of the commit), and
   delete `~/.claude/wikidoc/pass.lock` if it names one of this pass's digests.
   Grep the hold-back terms on the words this pass added, not on whole changed lines:
   `git show HEAD --word-diff=porcelain` (a line diff of a long page returns the whole page).
   Close to the weekly usage reset, land the pass in halves, each with its own commit and a
   `FLAGGED ... part N of M` line, so a cut-off loses half a pass and not all of it.
   Make edits from a script file run with `python -I` (raw-string paths, one replace helper that
   asserts exactly one match, a length check after), never an inline heredoc with a Windows path in it.
   Edit pages by exact replacement that keeps each file's own line endings (the wiki has both CRLF
   and LF pages; check before writing, never convert). Write the state log before rewriting the page
   it archives, and check each edit landed before the next, so a pass cut off by a restart can be
   resumed from `git status` without redoing or doubling anything (2026-11-16: a restart mid-pass).
7. **Report in one short paragraph:** pages created or updated, what went where, anything you chose
   not to record and why. No page content in chat.
8. **Skill refinement suggestions** (Alex, 2026-11-16: "skill refine happens on wikidoc passes seems
   efficient, if any skills can be refined they will be there"). The same harvest that feeds the wiki
   shows where a skill fell behind practice. After the paragraph, add a list headed
   `Skill suggestions`: for each skill in `~/.claude/skills/` (and project skills) that the harvest
   touches, read its SKILL.md and diff it against what the sessions actually did or what Alex ruled.
   One line per suggestion: the skill, the section, the proposed change in a sentence, and the
   evidence (his words quoted, or what happened, with the date). Kinds worth raising: a rule he
   stated that the skill lacks, a step the skill gives that practice has replaced, a correction he
   had to make twice, a trigger phrase he used that the description does not list, a recipe that
   belongs in a skill and lives only in chat. "None" is a fine answer; do not pad.
   Then read the wiki page `skill-suggestions-pending`, strike what the skill files now carry, add
   this pass's new ones, and keep the merged list on that page: duplicates joined, ordered by how much
   harm the stale text does, each marked as contradicting the skill's text or only missing from it.
   Hand back only what is new, the count still open and the numbers it extended (the pilot reads the page),
   unless the brief asks for the whole list.
   **The pass only suggests. It never edits a skill file**, whichever model runs it.

## Skill refinement (who drafts)

Alex, 2026-11-16: "i want an opus doing skill drafting not a sonnet ... the skill edit can be made by
you here with me the pilot, vs another agent, when the wikipass comes back it will have skill change
suggestions that we can go thru".

- **The skills are the pilot's tools** (Alex, 2026-11-19, 6:54 pm, answering the pilot's list with its lean: "the
  skills are your tools. If you want to do that, you're the boss on those. ... if you have any questions for me,
  let me know."). The pilot applies what it judges right, tells him in a line what it applied, and asks only what
  it is unsure of. A Sonnet may apply a numbered set whose wording is already on the pending page, with a backup
  of each file before its first edit. A change to `CLAUDE.md`, to settings or to a hook script is still named to
  him as its own item.
- The Sonnet pass finds; **the pilot decides.** When the report comes back, the pilot checks each suggestion
  against the skill file and the record, drops the wrong ones, applies the rest it judges right, and tells Alex in
  a line what went in. What it is unsure of, and anything that would undo a rule in his own words, it puts to him
  with its lean, one or two at a time. (Until 2026-11-19 every change to a flow waited for his word; his 6:54 pm
  answer above ended that.) One writer per file: other sessions edit the same skills, so check the files' times
  and the pass lock before editing.
- If drafting must be delegated (a large rewrite, the pilot's context is tight), it goes to an **Opus** agent
  with the skill file, the suggestions and the evidence. A Sonnet only applies wording that already exists (the
  numbered set above); it does not draft.
- A skill edit quotes the ruling and dates it, like a wiki page does, so the next reader knows why
  the rule is there.
- **Nothing is carried silently from pass to pass** (Alex, 2026-11-18: "skills should be changed frequently
  honestly, stale skills are more bad than good"; by that day 41 suggestions from 19 passes had piled up under the
  old "stay listed" rule). At every pass the pilot reads the pending page, applies what it judges right, and
  brings him only the items that need his ruling.
- A change to `CLAUDE.md`, to settings or to a hook script is never part of a batch: it is named to
  him as its own item.
- **Every pass ends with a `Skill updates` line to him, every time** (Alex, 2026-11-29, about 2:00 am: "The Wikidoc
  updates should be prompting me for skill updates a little more often, or updating me on them."; then, asked
  whether the skill knew: "And the wikidoc skill itself knows to be more annoying ?"). The rules above already said
  to tell him, and the pilot had let the report shrink to a clause: by that night 118 items were open and he had
  seen none. So when a pass reports, the pilot's next message to him carries, in two or three lines and not
  buried in the pass summary: **applied** (which skill, what, in a phrase each), **new and waiting** (the count
  by skill), and **needs your word** (each item as a question with the pilot's lean, one or two at a time). With
  nothing new it still says so and gives the open count ("Skill updates: none new; 114 open, 38 of them
  workervision"). A suggestion for a skill another session owns is named to him and sent to that session, not
  left on the page. If three passes in a row leave a skill's count unchanged, say that plainly and ask whether
  to clear it in one sitting.

## Rules

- Never paste tool output, agent reports, diffs or transcripts into a page. Condense.
- Never record secrets, tokens, logins, or anything from `~/.runelite`, `server\data\` or similar.
- Every pass reads `holdbacks.md` in this skill's folder first and applies it, whichever session launched the pass and whatever the digest is about. It lists the topics he has ruled out of the record.
- A fact that is derivable from a repo (code structure, commit history, test counts over time) does
  not go in the wiki; link the repo path instead. Rulings, method and why do.
- Memory (`~/.claude/projects/.../memory/`) and the wiki are different stores: memory is how Claude
  works with Alex; the wiki is Alex's record of his life and work. A method Alex named goes in both;
  a Claude-only operational detail goes in memory only.
- Protocols over subagents: run the lint script, do not spawn an agent to lint.
- If a page needs a ruling only Alex can give (which page owns a noun, a visibility change, a person's
  page), ask one question with a recommendation and record the rest.

The watcher, whole

Two small Python scripts do the triggering. They are written for my setup, the Claude Code command-line tool and the way it stores its sessions, so you will need to change the paths and perhaps the trigger. My folder paths are shortened here. Nothing else is changed.

The counter. It runs each time I send a message. It counts my messages for the session, and on every tenth it runs the second script and tells the session a digest is ready. The number is WIKIDOC_EVERY, near the top. It also keeps a lock, so two sessions never run a pass at once.

"""UserPromptSubmit hook: count Alex's prompts per session and, every WIKIDOC_EVERY prompts, build a digest of
what is new (scripts/wikidoc_digest.py) and hand the active session one line of context naming it, so that
session runs the /wikidoc skill on it with one subagent under its own permissions. No agent is launched from
here. One pass at a time: the hook writes pass.lock when it hands a digest over, and hands out no other while
the lock is fresh.

Reads the hook's stdin JSON (session_id, transcript_path, cwd). Never blocks the prompt: any error is
swallowed and logged to ~/.claude/wikidoc/hook.log. It prints only on the prompt that trips the counter (the
one line of context); otherwise nothing (the status line shows the count).
"""
import json
import os
import re
import subprocess
import sys
import time

HOME = os.path.expanduser("~")
STATE = os.path.join(HOME, ".claude", "wikidoc")
COUNTS = os.path.join(STATE, "counts.json")
STATUS_DIR = os.path.join(STATE, "status")
DIGESTER = os.path.join(HOME, ".claude", "scripts", "wikidoc_digest.py")
EVERY = int(os.environ.get("WIKIDOC_EVERY", "10"))
# 2026-11-18 (Alex: "the two WikiPass lock is great"): one wiki pass at a time. The hook writes pass.lock when it
# hands a session a digest; while the lock is fresh no session is handed another. The pass deletes it after its
# push; if a pass dies, the lock simply expires.
LOCK = os.path.join(STATE, "pass.lock")
LOCK_MINUTES = int(os.environ.get("WIKIDOC_LOCK_MINUTES", "75"))
DIGESTS = os.path.join(STATE, "digests")
WIKI_LOG = os.path.join(HOME, ".claude", "wiki", "_meta", "log.md")
STAMP = re.compile(r"\d{8}-\d{6}")


def log(msg):
    try:
        os.makedirs(STATE, exist_ok=True)
        with open(os.path.join(STATE, "hook.log"), "a", encoding="utf-8") as fh:
            fh.write("%s %s\n" % (time.strftime("%Y-%m-%d %H:%M:%S"), msg))
    except Exception:
        pass


def load_json(path, default):
    try:
        with open(path, encoding="utf-8") as fh:
            return json.load(fh)
    except Exception:
        return default


def save_json(path, data):
    tmp = path + ".tmp"
    with open(tmp, "w", encoding="utf-8") as fh:
        json.dump(data, fh)
    os.replace(tmp, path)


def lock_holder():
    """The lock's contents while it is fresh, else None."""
    held = load_json(LOCK, None)
    if not isinstance(held, dict):
        return None
    try:
        if time.time() - float(held.get("at", 0)) > LOCK_MINUTES * 60:
            return None
    except Exception:
        return None
    return held


def unfiled_digests(newest):
    """Every digest newer than the wiki log's last FLAGGED line, oldest first, always ending with `newest`."""
    last = ""
    try:
        with open(WIKI_LOG, encoding="utf-8", errors="replace") as fh:
            for ln in fh:
                if "FLAGGED" in ln:
                    stamps = STAMP.findall(ln)
                    if stamps:
                        last = max(stamps)
    except Exception:
        last = ""
    out = []
    if last:
        try:
            for name in sorted(os.listdir(DIGESTS)):
                if name.endswith(".md") and STAMP.fullmatch(name[:-3]) and name[:-3] > last:
                    out.append(os.path.join(DIGESTS, name))
        except Exception:
            out = []
    base = os.path.basename(newest)
    out = [d for d in out if os.path.basename(d) != base]
    return out + [newest]


def main():
    try:
        payload = json.load(sys.stdin)
    except Exception:
        payload = {}
    sid = str(payload.get("session_id") or "unknown")
    prompt = str(payload.get("prompt") or "").lstrip()
    # count only what Alex types: not monitor events, task notifications, hook context or ! shell input
    if prompt.startswith(("<system-reminder>", "[SYSTEM NOTIFICATION", "<task-notification>", "<bash-input>",
                          "<command-name>", "<cross-session-message", "<agent-message")):
        return
    # 2026-11-17 (Alex: "fix that wiki issue so it only eats my words not those auto things"): a session's own
    # scheduled prompts (cron check-ins, stall watches), relayed agent hand-backs and continuation summaries
    # are not his words either. New scheduled prompts should start with "[scheduled]"; the older labels are
    # matched too.
    low = prompt.lower()
    if low.startswith(("[scheduled]", "stall watch", "overnight stall watch", "15-minute check-in",
                       "one check on", "half-hour check-in", "another claude session sent a message",
                       "this session is being continued", "<local-command")):
        return
    os.makedirs(STATUS_DIR, exist_ok=True)
    counts = load_json(COUNTS, {})
    n = int(counts.get(sid, 0)) + 1
    counts[sid] = n
    save_json(COUNTS, counts)
    save_json(os.path.join(STATUS_DIR, sid + ".json"),
              {"count": n, "every": EVERY, "next_in": (EVERY - n % EVERY) % EVERY or EVERY,
               "cwd": payload.get("cwd"), "at": time.time()})
    if n % EVERY == 0 and os.path.exists(DIGESTER):
        held = lock_holder()
        if held:
            # another pass (or this session's last one) is still running: build nothing, hand over nothing; the
            # words wait for the next digest
            log("prompt %d of %s: held, pass lock by %s for %s, %d min old" % (
                n, sid[:8], str(held.get("session", "?"))[:8], os.path.basename(str(held.get("digest", "?"))),
                int((time.time() - float(held.get("at", 0))) / 60)))
            return
        # Build the digest now (fast: deltas only) and hand the active session one line of context, so its
        # pilot runs /wikidoc on it with a Sonnet subagent under the session's own permissions. No agent is
        # launched from here; each agent documents its own conversations (Hermes runs its own loop).
        try:
            out = subprocess.run([sys.executable, "-I", DIGESTER, "--trigger", "session:%s:%d" % (sid[:8], n)],
                                 capture_output=True, text=True, timeout=25, stdin=subprocess.DEVNULL)
            line = (out.stdout or "").strip().splitlines()[-1] if out.stdout else ""
            if "|" in line:
                path, n_all, n_kept, n_sess = line.split("|")
                todo = unfiled_digests(path)
                older = ""
                if len(todo) > 1:
                    older = (" Digests not yet filed in the wiki log, to be named in the same brief, oldest first: %s."
                             % ", ".join(todo[:-1]))
                ctx = ("[wikidoc watcher] Prompt %d of this session. A wikidoc digest is ready: %s (%s new messages "
                       "across %s Claude Code sessions on this machine, %s shown).%s At the next natural pause, run the "
                       "/wikidoc skill on that digest with ONE Sonnet subagent (effort max) under this session's own "
                       "permissions, verify its one-paragraph report, and keep going. Do not paste the digest into "
                       "chat. This session now holds the pass lock (%s, %d minutes): the pass deletes it after its "
                       "push, and no other session is handed a digest meanwhile."
                       % (n, path, n_all, n_sess, n_kept, older, LOCK, LOCK_MINUTES))
                try:
                    save_json(LOCK, {"session": sid, "digest": path, "at": time.time()})
                except Exception as exc:
                    log("lock not written: %r" % (exc,))
                print(json.dumps({"hookSpecificOutput": {"hookEventName": "UserPromptSubmit",
                                                         "additionalContext": ctx}}))
                log("prompt %d of %s: digest %s" % (n, sid[:8], path))
            else:
                log("prompt %d of %s: %s" % (n, sid[:8], line or (out.stderr or "").strip()[-200:]))
        except Exception as exc:
            log("digest failed: %r" % (exc,))


if __name__ == "__main__":
    try:
        main()
    except Exception as exc:
        log("hook error: %r" % (exc,))
    sys.exit(0)

The digest. It reads what is new in every session's saved conversation since the last digest, keeps only what was typed and what the AI answered, never a tool's output, and writes one file for the pass to read.

"""Build the wikidoc digest: what is NEW across this machine's Claude Code session transcripts since the
last digest. Claude Code only (each agent documents its own conversations; Hermes runs its own loop).

    python wikidoc_digest.py                 harvest since the stored offsets, write a digest, advance offsets
    python wikidoc_digest.py --dry-run       write the digest, print sizes, leave offsets alone
    python wikidoc_digest.py --init-offsets DAYS   forget offsets; the next harvest starts DAYS days back

Harvest: ~/.claude/projects/*/*.jsonl (top-level session files; subagents/ skipped), user text and
assistant text blocks only (no thinking, tool calls or tool results), each trimmed, per-file byte offsets.
State: ~/.claude/wikidoc/ (offsets.json, digests/<stamp>.md, digest.log). Prints the digest path and a
one-line summary on stdout; the UserPromptSubmit hook hands that line to the active session as context
so its pilot runs /wikidoc on the digest with a Sonnet subagent under the session's own permissions.
"""
import argparse
import datetime as dt
import glob
import json
import os
import sys
import time

HOME = os.path.expanduser("~")
STATE = os.path.join(HOME, ".claude", "wikidoc")
DIGESTS = os.path.join(STATE, "digests")
OFFSETS = os.path.join(STATE, "offsets.json")
PROJECTS = os.path.join(HOME, ".claude", "projects")

MAX_TEXT = 1500
MAX_DIGEST = 250_000
SKIP_PREFIXES = ("<task-notification>", "[Request interrupted", "<system-reminder>", "<local-command",
                 "<command-name>", "[Cross-session delivery notice]")


def load_json(path, default):
    try:
        with open(path, encoding="utf-8") as fh:
            return json.load(fh)
    except Exception:
        return default


def save_json(path, data):
    tmp = path + ".tmp"
    with open(tmp, "w", encoding="utf-8") as fh:
        json.dump(data, fh, indent=1)
    os.replace(tmp, path)


def trim(text, n=MAX_TEXT):
    text = " ".join(str(text).split())
    return text if len(text) <= n else text[:n] + " [...]"


def text_of(content):
    if isinstance(content, str):
        return content
    if isinstance(content, list):
        out = [b["text"] for b in content if isinstance(b, dict) and b.get("type") == "text" and b.get("text")]
        return "\n".join(out) if out else None
    return None


def harvest(offsets, since_ts, last_run=None):
    """last_run: epoch seconds of the previous harvest (offsets.json "_last"). A transcript never seen before
    starts at 0 when it was modified after that harvest (a session that began since: its whole text is new),
    at its end when it is older (a file that predates the watcher; nothing in it is new). Fix of 2026-10-10:
    before it, a new session's pre-digest text was skipped (the wikidoc pass of that day found the pilot
    session's own text missing from its digest)."""
    items, new_offsets = [], {}
    queued_seen = set()  # (session, text) of his mid-turn messages already taken, so none is listed twice
    for path in glob.glob(os.path.join(PROJECTS, "*", "*.jsonl")):
        try:
            size = os.path.getsize(path)
            mtime = os.path.getmtime(path)
        except OSError:
            continue
        key = os.path.relpath(path, PROJECTS).replace("\\", "/")
        start = int(offsets.get(key, -1))
        if start < 0:
            if since_ts is not None:
                start = 0
            elif last_run is not None and mtime > float(last_run):
                start = 0
            else:
                start = size
        if start > size:
            start = 0
        if start == size:
            new_offsets[key] = size
            continue
        sid = os.path.basename(path)[:8]
        with open(path, "rb") as fh:
            fh.seek(start)
            data = fh.read()
        cut = data.rfind(b"\n")
        if cut < 0:
            new_offsets[key] = start
            continue
        for line in data[:cut].split(b"\n"):
            if not line.strip():
                continue
            try:
                r = json.loads(line.decode("utf-8", "replace"))
            except Exception:
                continue
            t = r.get("type")
            if t == "attachment":
                # (2026-11-19, on Alex's word) A message he types while a turn is running is not a "user" record:
                # it reaches the session as an attachment of type queued_command, commandMode "prompt", origin kind
                # "human". Until this fix no digest held those lines (wiki: skill-suggestions, item 42). Task
                # notifications and other sessions' messages use the same attachment with another origin and stay out.
                a = r.get("attachment")
                o = a.get("origin") if isinstance(a, dict) else None
                if not (isinstance(a, dict) and a.get("type") == "queued_command" and a.get("commandMode") == "prompt"
                        and isinstance(o, dict) and o.get("kind") == "human" and isinstance(a.get("prompt"), str)):
                    continue
                ts = r.get("timestamp") or a.get("timestamp") or ""
                if since_ts is not None and ts and ts < since_ts:
                    continue
                text = a["prompt"]
                if not text.strip() or text.lstrip().startswith(SKIP_PREFIXES) or (sid, text.strip()) in queued_seen:
                    continue
                queued_seen.add((sid, text.strip()))
                items.append({"session": sid, "cwd": r.get("cwd") or "", "ts": ts, "role": "user", "text": trim(text)})
                continue
            if t not in ("user", "assistant"):
                continue
            ts = r.get("timestamp") or ""
            if since_ts is not None and ts and ts < since_ts:
                continue
            text = text_of((r.get("message") or {}).get("content"))
            if not text or (t == "user" and text.lstrip().startswith(SKIP_PREFIXES)):
                continue
            if t == "user" and (sid, text.strip()) in queued_seen:
                continue  # the same words already taken from their queued attachment
            items.append({"session": sid, "cwd": r.get("cwd") or "", "ts": ts, "role": t, "text": trim(text)})
        new_offsets[key] = start + cut + 1
    return items, new_offsets


def build(items, trigger):
    items.sort(key=lambda i: (i["ts"], i["session"]))
    kept, total = [], 0
    for it in reversed(items):
        line = "- [%s %s %s] %s" % (it["session"], it["role"], it["ts"][:16], it["text"])
        if total + len(line) > MAX_DIGEST:
            break
        kept.append((it, line))
        total += len(line)
    kept.reverse()
    dropped = len(items) - len(kept)
    sessions = {}
    for it, line in kept:
        sessions.setdefault((it["session"], it["cwd"]), []).append(line)
    out = ["# wikidoc digest %s (trigger: %s)" % (dt.datetime.now().strftime("%Y-%m-%d %H:%M"), trigger), "",
           "%d new messages across %d Claude Code sessions on this machine; %d shown, %d older dropped to fit. "
           "Each line: [session role timestamp] text. Tool calls and results are left out on purpose." % (
               len(items), len(sessions), len(kept), dropped), ""]
    for (sid, cwd), lines in sessions.items():
        out.append("## session %s (%s)" % (sid, cwd))
        out.extend(lines)
        out.append("")
    return "\n".join(out) + "\n", len(items), len(kept), len(sessions)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--trigger", default="manual")
    ap.add_argument("--dry-run", action="store_true")
    ap.add_argument("--init-offsets", type=float, metavar="DAYS")
    args = ap.parse_args()
    os.makedirs(DIGESTS, exist_ok=True)
    if args.init_offsets is not None:
        since = (dt.datetime.utcnow() - dt.timedelta(days=args.init_offsets)).strftime("%Y-%m-%dT%H:%M:%S")
        save_json(OFFSETS, {"_since": since})
        print("offsets reset; the next digest starts at %s UTC" % since)
        return 0
    offsets = load_json(OFFSETS, {})
    since_ts = offsets.pop("_since", None)
    last_run = offsets.pop("_last", None)
    items, new_offsets = harvest(offsets, since_ts, last_run)
    new_offsets["_last"] = time.time()
    if not items:
        if not args.dry_run:
            save_json(OFFSETS, new_offsets)
        print("nothing new")
        return 0
    digest, n_all, n_kept, n_sess = build(items, args.trigger)
    path = os.path.join(DIGESTS, dt.datetime.now().strftime("%Y%m%d-%H%M%S") + ".md")
    with open(path, "w", encoding="utf-8") as fh:
        fh.write(digest)
    if not args.dry_run:
        save_json(OFFSETS, new_offsets)
    with open(os.path.join(STATE, "digest.log"), "a", encoding="utf-8") as fh:
        fh.write("%s %s %d messages %d sessions %d chars%s\n" % (
            time.strftime("%Y-%m-%d %H:%M:%S"), os.path.basename(path), n_all, n_sess, len(digest),
            " (dry run)" if args.dry_run else ""))
    print("%s|%d|%d|%d" % (path, n_all, n_kept, n_sess))
    return 0


if __name__ == "__main__":
    sys.exit(main())

The counter is registered in the tool's settings file as a hook that runs when a message is sent:

"hooks": { "UserPromptSubmit": [ { "hooks": [ { "type": "command",
    "command": "python ~/.claude/scripts/wikidoc_hook.py" } ] } ] }