⏳ This skill is pending AI review.
Scores will appear once the review pipeline completes.
agent-diary
>-
Choose how to use this skill
You do not need every option. Choose the path your AI client supports. The stable page stays the same; versioned files are immutable.
1. Native installer
This listing has no registered native installer command. Use the complete package or source fallback below, depending on what your client supports.
Do not guess an installer command or replace an existing version without reviewing the diff.
2. Complete package recommended
Download the ZIP when available. It includes SKILL.md plus the references, security notes and version metadata.
No complete ProSkills package is published for this listing yet.3. Prompt-only
Copy the prompt above when the agent can read the stable page or when you want to adopt the workflow without installing a skill.
Need only the instruction file?
Download SKILL.md only if your client requires a single file. The complete ZIP is safer for a full installation because it preserves the references and release context.
No path installs or executes anything by itself. Your agent still needs access to the project files. Before updating, compare the installed version and review the diff.
// RATINGS
Not yet listed on ClawHub or SkillsMP
// README
agent-diary
Pull learnings, bugs, and fixes from AI agent sessions into a local HTML diary and an interactive Claude Code Mod pane with Marcus Aurelius style notes.
git clone https://github.com/hemanth/agent-diary.git
cd agent-diary
npm link
ln -s "$PWD" ~/.gemini/config/skills/agent-diary
ln -s "$PWD" ~/.claude/skills/agent-diary
Quick start
# Scan recent sessions from Antigravity and Claude Code
npm run harvest
# Build and open diary.html
npm run open
harvest.mjs reads .jsonl transcripts for errors, follow-up questions, and fixes. build-diary.mjs compiles data/diary-entries.json into diary.html, docs/index.html, and DIARY.md.
Claude Code Mod
agent-diary includes a Claude Code Mod (hooks/register.js) that draws an interactive pane inside your terminal or Claude Desktop app.
# Load from ~/.claude/skills/agent-diary or pass --plugin-dir directly
claude --plugin-dir .
# Validate and run the mod test suite
npm run validate
npm test
Inside a Claude Code session:
/diaryopens the interactiveAgent Diary (Ta Eis Heauton)pane with three tabs:1: Entries,2: Meditations, and3: Write Note./diary-note <reflection>saves a personal note straight from the prompt into$.storeanddata/diary-entries.json./diary-openopensdiary.htmlin your browser.- Hotkeys inside the pane:
1/2/3switch tabs,n/pcycle entries,mdraws another Stoic meditation lot,btoggles theAbovePromptStoic quote banner, andoopens the HTML diary.
CLI usage
# Sync latest sessions and open diary.html in your browser
agent-diary
# Print recent sessions in the terminal
agent-diary harvest
# Sync and rebuild without opening a browser tab
agent-diary sync
Add an entry from the terminal
node scripts/build-diary.mjs --add-json '{
"id": "entry-2026-10-05-my-project",
"date": "2026-10-05",
"project": "my-project",
"title": "Zero-copy buffers in the audio worker",
"summary": "Removed redundant ArrayBuffer copies on the hot path.",
"virtue": "Economy and Precision (Euteleia)",
"challenges": ["GC pauses hit 45ms when cloning 16MB audio frames."],
"solutions": ["Passed ownership with postMessage transferable ArrayBuffers."],
"learnings": ["Transferables move ownership in O(1) without copying bytes."],
"meditation": {
"book": "Book IV",
"verse": "Section 24",
"stoicConcept": "Apallage (Pruning the unnecessary)",
"quote": "Why copy the vessel when you can hand it across the threshold?",
"reflection": "Most latency comes from extra work we added ourselves. Pass the buffer directly."
},
"userNote": "Cut frame latency from 45ms to 0.2ms."
}' --open
Automatic background hook
agent-diary registers a Stop hook in ~/.gemini/config/hooks.json (Antigravity), ~/.claude/settings.json (Claude Code settings), and turn.complete in hooks/register.js (Claude Code Mod). When a turn ends, scripts/auto-hook.mjs pulls new sessions into data/diary-entries.json and rebuilds diary.html without overwriting your manual notes.
License
MIT (c) Hemanth.HM
// HOW IT'S BUILT
// FILES
19 files shipped with this skill. Inline text is the catalog copy. The upstream link is the source repository.
SKILL.md6.4 KB5da68150c285upstream ↗
--- name: agent-diary description: >- Extracts technical challenges, root-cause fixes, and learnings from AI agent sessions (Antigravity, Claude Code, and Git history), prompts the user to write personal notes, and builds an HTML diary and Claude Code Mod pane with Marcus Aurelius style reflections. Use when the user asks to write a diary, log session learnings, review bugs and fixes across sessions, or open their agent diary. --- # Agent diary (`agent-diary`) Turn AI pair-programming sessions into an HTML engineering diary and an interactive Claude Code Mod pane that pair bugs, fixes, and technical takeaways with personal notes in the style of Marcus Aurelius's *Meditations* (*Ta Eis Heauton*). ## Quick open When the user runs `/agent-diary` or asks to open or view their diary, run: ```bash agent-diary ``` In a Claude Code session with the mod loaded (`~/.claude/skills/agent-diary` or `claude --plugin-dir .`): - `/diary` opens the in-terminal `Agent Diary (Ta Eis Heauton)` pane (`1: Entries`, `2: Meditations`, `3: Write Note`). - `/diary-note <reflection>` saves a personal reflection note directly from the prompt. - `/diary-open` opens `diary.html` in the browser. Files in the repository: - HTML file: `diary.html` - Markdown export: `DIARY.md` - JSON data: `data/diary-entries.json` - Claude Code Mod: `hooks/register.js` ## How it works 1. **Harvest sessions**: Scan `.jsonl` transcripts in `~/.gemini/antigravity-cli/brain/` and `~/.claude/projects/` for errors, user corrections, and final fixes. 2. **Write the four sections**: Record the challenge, the fix, the reusable lesson, and a short reflection modeled on *Meditations*. 3. **Get the user's note**: Ask the user one short question about what stood out in the session, or let them type it in the `/diary` pane (`Tab 3: Write Note`) or the HTML editor. 4. **Compile the HTML**: Run `scripts/build-diary.mjs` to update `diary.html`, `docs/index.html`, and `DIARY.md`. ### Automatic hooks (`Stop` and `turn.complete`) The diary updates in the background when a turn ends in Antigravity (`~/.gemini/config/hooks.json`), Claude Code settings (`~/.claude/settings.json`), or the Claude Code Mod (`turn.complete` in `hooks/register.js`). Curated entries and `userNote` fields are never overwritten. ## Harvesting transcripts manually ```bash # List the 15 most recent sessions across Antigravity and Claude Code agent-diary harvest --limit 15 # Dump harvested session data as JSON agent-diary harvest --limit 20 --json > /tmp/harvested-sessions.json ``` When reading transcripts, look for moments where the first attempt failed: - User pushback like `"lol, how true is that data?"`, `"it says Render Complete, but it doesn't have the captions"`, or `"server down?"`. - Non-zero exit codes, stack traces, OAuth 403 blocks, WASM memory errors, or layout bugs. - The specific change that fixed the problem, such as reading Snappy-compressed LevelDB `.ldb` files instead of SQLite `visits`, or scaling subtitles by `min(outW, outH)` instead of height alone. ## Writing the Marcus Aurelius note Keep the Stoic note grounded in the actual bug from the session: - Address yourself directly: *"Remind yourself..."*, *"Do not trust the green badge before inspecting the frame..."*, *"Look at the tensor shapes themselves..."* - Tie Stoic ideas to concrete engineering problems: - *Phantasia* (testing appearances): Mock fallback data or a premature `"Render Complete"` message pretending the job is done. - *Hupokeimena* (working with obstacles): A `484x1080` portrait video or an OAuth test-user block forcing a cleaner design. - *Apallage* (cutting what is unnecessary): Pruning 50 tool schemas down to 3 in 0.4ms instead of burning an extra LLM round-trip. - Avoid generic fortune-cookie quotes. Mention the actual constraint from the session. ## Prompting the user Ask one plain question before wrapping up: > "Before I save today's entry: which bug or fix from today do you want to add a personal note on?" Save their reply into `userNote`, or let them add it via `/diary-note` or inside `diary.html` using the **Write Today's Entry** form (supports browser voice dictation and Markdown/JSON export). ## Entry schema (`data/diary-entries.json`) ```json { "id": "entry-2026-10-04-audio-worklet", "sessionId": "demo-a101-4f82-9c11-000000000001", "date": "2026-10-04", "time": "22:47 PDT", "project": "audio-worklet", "workspace": "~/projects/audio-worklet", "agent": "Antigravity (Gemini 4 Argon)", "title": "Portrait video geometry and burned-in FFmpeg WASM subtitles", "summary": "Switched STT to Cactus-Compute Whistle, wired burned-in subtitles into the FFmpeg WASM export, and fixed horizontal text clipping on 484x1080 portrait videos.", "tags": ["ffmpeg-wasm", "whistle-stt", "video-geometry", "canvas"], "virtue": "Temperance and Proportion (Sophrosyne)", "challenges": [ "The UI showed 'Render Complete', but the exported MP4 had no captions because the canvas overlay was never passed into the FFmpeg WASM filtergraph.", "Portrait screen recordings (484x1080) rendered 54px captions that clipped off both sides because font size scaled only by video height (outH / 480)." ], "solutions": [ "Mounted the generated subtitle file in the FFmpeg WASM pass and extracted a single PNG frame after export to verify the pixels.", "Changed font scaling to use Math.min(outW, outH) / 480 with line wrapping for narrow portrait frames." ], "learnings": [ "Scale video overlay text against min(width, height) rather than height alone so 9:16 portrait videos do not overflow horizontally.", "Check an extracted video frame on disk before trusting a 'Render Complete' state." ], "meditation": { "book": "Book IV", "verse": "Section 19", "location": "Written while checking a 484x1080 frame in audio-worklet", "stoicConcept": "Metron (Measure and proportion)", "quote": "The herald cries that the work is finished, yet the stone has no inscription. And when you carve the letters, if you measure only the height of the column and ignore its narrow width, the words spill over the edge.", "reflection": "Two mistakes come up often: assuming a job succeeded because a function returned without throwing, and applying a landscape rule to a narrow portrait frame. Measure both dimensions before drawing." }, "userNote": "Testing on a real 484x1080 mobile recording caught the height-only font scaling bug right away." } ```skills/agent-diary/SKILL.md6.4 KB5da68150c285upstream ↗
--- name: agent-diary description: >- Extracts technical challenges, root-cause fixes, and learnings from AI agent sessions (Antigravity, Claude Code, and Git history), prompts the user to write personal notes, and builds an HTML diary and Claude Code Mod pane with Marcus Aurelius style reflections. Use when the user asks to write a diary, log session learnings, review bugs and fixes across sessions, or open their agent diary. --- # Agent diary (`agent-diary`) Turn AI pair-programming sessions into an HTML engineering diary and an interactive Claude Code Mod pane that pair bugs, fixes, and technical takeaways with personal notes in the style of Marcus Aurelius's *Meditations* (*Ta Eis Heauton*). ## Quick open When the user runs `/agent-diary` or asks to open or view their diary, run: ```bash agent-diary ``` In a Claude Code session with the mod loaded (`~/.claude/skills/agent-diary` or `claude --plugin-dir .`): - `/diary` opens the in-terminal `Agent Diary (Ta Eis Heauton)` pane (`1: Entries`, `2: Meditations`, `3: Write Note`). - `/diary-note <reflection>` saves a personal reflection note directly from the prompt. - `/diary-open` opens `diary.html` in the browser. Files in the repository: - HTML file: `diary.html` - Markdown export: `DIARY.md` - JSON data: `data/diary-entries.json` - Claude Code Mod: `hooks/register.js` ## How it works 1. **Harvest sessions**: Scan `.jsonl` transcripts in `~/.gemini/antigravity-cli/brain/` and `~/.claude/projects/` for errors, user corrections, and final fixes. 2. **Write the four sections**: Record the challenge, the fix, the reusable lesson, and a short reflection modeled on *Meditations*. 3. **Get the user's note**: Ask the user one short question about what stood out in the session, or let them type it in the `/diary` pane (`Tab 3: Write Note`) or the HTML editor. 4. **Compile the HTML**: Run `scripts/build-diary.mjs` to update `diary.html`, `docs/index.html`, and `DIARY.md`. ### Automatic hooks (`Stop` and `turn.complete`) The diary updates in the background when a turn ends in Antigravity (`~/.gemini/config/hooks.json`), Claude Code settings (`~/.claude/settings.json`), or the Claude Code Mod (`turn.complete` in `hooks/register.js`). Curated entries and `userNote` fields are never overwritten. ## Harvesting transcripts manually ```bash # List the 15 most recent sessions across Antigravity and Claude Code agent-diary harvest --limit 15 # Dump harvested session data as JSON agent-diary harvest --limit 20 --json > /tmp/harvested-sessions.json ``` When reading transcripts, look for moments where the first attempt failed: - User pushback like `"lol, how true is that data?"`, `"it says Render Complete, but it doesn't have the captions"`, or `"server down?"`. - Non-zero exit codes, stack traces, OAuth 403 blocks, WASM memory errors, or layout bugs. - The specific change that fixed the problem, such as reading Snappy-compressed LevelDB `.ldb` files instead of SQLite `visits`, or scaling subtitles by `min(outW, outH)` instead of height alone. ## Writing the Marcus Aurelius note Keep the Stoic note grounded in the actual bug from the session: - Address yourself directly: *"Remind yourself..."*, *"Do not trust the green badge before inspecting the frame..."*, *"Look at the tensor shapes themselves..."* - Tie Stoic ideas to concrete engineering problems: - *Phantasia* (testing appearances): Mock fallback data or a premature `"Render Complete"` message pretending the job is done. - *Hupokeimena* (working with obstacles): A `484x1080` portrait video or an OAuth test-user block forcing a cleaner design. - *Apallage* (cutting what is unnecessary): Pruning 50 tool schemas down to 3 in 0.4ms instead of burning an extra LLM round-trip. - Avoid generic fortune-cookie quotes. Mention the actual constraint from the session. ## Prompting the user Ask one plain question before wrapping up: > "Before I save today's entry: which bug or fix from today do you want to add a personal note on?" Save their reply into `userNote`, or let them add it via `/diary-note` or inside `diary.html` using the **Write Today's Entry** form (supports browser voice dictation and Markdown/JSON export). ## Entry schema (`data/diary-entries.json`) ```json { "id": "entry-2026-10-04-audio-worklet", "sessionId": "demo-a101-4f82-9c11-000000000001", "date": "2026-10-04", "time": "22:47 PDT", "project": "audio-worklet", "workspace": "~/projects/audio-worklet", "agent": "Antigravity (Gemini 4 Argon)", "title": "Portrait video geometry and burned-in FFmpeg WASM subtitles", "summary": "Switched STT to Cactus-Compute Whistle, wired burned-in subtitles into the FFmpeg WASM export, and fixed horizontal text clipping on 484x1080 portrait videos.", "tags": ["ffmpeg-wasm", "whistle-stt", "video-geometry", "canvas"], "virtue": "Temperance and Proportion (Sophrosyne)", "challenges": [ "The UI showed 'Render Complete', but the exported MP4 had no captions because the canvas overlay was never passed into the FFmpeg WASM filtergraph.", "Portrait screen recordings (484x1080) rendered 54px captions that clipped off both sides because font size scaled only by video height (outH / 480)." ], "solutions": [ "Mounted the generated subtitle file in the FFmpeg WASM pass and extracted a single PNG frame after export to verify the pixels.", "Changed font scaling to use Math.min(outW, outH) / 480 with line wrapping for narrow portrait frames." ], "learnings": [ "Scale video overlay text against min(width, height) rather than height alone so 9:16 portrait videos do not overflow horizontally.", "Check an extracted video frame on disk before trusting a 'Render Complete' state." ], "meditation": { "book": "Book IV", "verse": "Section 19", "location": "Written while checking a 484x1080 frame in audio-worklet", "stoicConcept": "Metron (Measure and proportion)", "quote": "The herald cries that the work is finished, yet the stone has no inscription. And when you carve the letters, if you measure only the height of the column and ignore its narrow width, the words spill over the edge.", "reflection": "Two mistakes come up often: assuming a job succeeded because a function returned without throwing, and applying a landscape rule to a narrow portrait frame. Measure both dimensions before drawing." }, "userNote": "Testing on a real 484x1080 mobile recording caught the height-only font scaling bug right away." } ```README.md3.2 KB345a4bdfd95dupstream ↗
# agent-diary Pull learnings, bugs, and fixes from AI agent sessions into a local HTML diary and an interactive Claude Code Mod pane with Marcus Aurelius style notes. ```bash git clone https://github.com/hemanth/agent-diary.git cd agent-diary npm link ln -s "$PWD" ~/.gemini/config/skills/agent-diary ln -s "$PWD" ~/.claude/skills/agent-diary ``` ## Quick start ```bash # Scan recent sessions from Antigravity and Claude Code npm run harvest # Build and open diary.html npm run open ``` `harvest.mjs` reads `.jsonl` transcripts for errors, follow-up questions, and fixes. `build-diary.mjs` compiles `data/diary-entries.json` into `diary.html`, `docs/index.html`, and `DIARY.md`. ## Claude Code Mod `agent-diary` includes a [Claude Code Mod](https://code.claude.com/docs/en/plugins/mods/overview) (`hooks/register.js`) that draws an interactive pane inside your terminal or Claude Desktop app. ```bash # Load from ~/.claude/skills/agent-diary or pass --plugin-dir directly claude --plugin-dir . # Validate and run the mod test suite npm run validate npm test ``` Inside a Claude Code session: - `/diary` opens the interactive `Agent Diary (Ta Eis Heauton)` pane with three tabs: `1: Entries`, `2: Meditations`, and `3: Write Note`. - `/diary-note <reflection>` saves a personal note straight from the prompt into `$.store` and `data/diary-entries.json`. - `/diary-open` opens `diary.html` in your browser. - Hotkeys inside the pane: `1`/`2`/`3` switch tabs, `n`/`p` cycle entries, `m` draws another Stoic meditation lot, `b` toggles the `AbovePrompt` Stoic quote banner, and `o` opens the HTML diary. ## CLI usage ```bash # Sync latest sessions and open diary.html in your browser agent-diary # Print recent sessions in the terminal agent-diary harvest # Sync and rebuild without opening a browser tab agent-diary sync ``` ## Add an entry from the terminal ```bash node scripts/build-diary.mjs --add-json '{ "id": "entry-2026-10-05-my-project", "date": "2026-10-05", "project": "my-project", "title": "Zero-copy buffers in the audio worker", "summary": "Removed redundant ArrayBuffer copies on the hot path.", "virtue": "Economy and Precision (Euteleia)", "challenges": ["GC pauses hit 45ms when cloning 16MB audio frames."], "solutions": ["Passed ownership with postMessage transferable ArrayBuffers."], "learnings": ["Transferables move ownership in O(1) without copying bytes."], "meditation": { "book": "Book IV", "verse": "Section 24", "stoicConcept": "Apallage (Pruning the unnecessary)", "quote": "Why copy the vessel when you can hand it across the threshold?", "reflection": "Most latency comes from extra work we added ourselves. Pass the buffer directly." }, "userNote": "Cut frame latency from 45ms to 0.2ms." }' --open ``` ## Automatic background hook `agent-diary` registers a `Stop` hook in `~/.gemini/config/hooks.json` (Antigravity), `~/.claude/settings.json` (Claude Code settings), and `turn.complete` in `hooks/register.js` (Claude Code Mod). When a turn ends, `scripts/auto-hook.mjs` pulls new sessions into `data/diary-entries.json` and rebuilds `diary.html` without overwriting your manual notes. ## License MIT (c) [Hemanth.HM](https://h3manth.com)scripts/auto-hook.mjs17 KBa8332794130cupstream ↗
#!/usr/bin/env node /** * agent-diary automatic lifecycle hook & background sync * Triggered on Antigravity `Stop` and Claude Code `Stop` hooks. * Automatically harvests new or updated agent sessions (Antigravity + Claude Code) * into data/diary-entries.json and recompiles diary.html, docs/index.html, and DIARY.md * without overwriting curated entries or user margin notes. */ import fs from 'node:fs'; import path from 'node:path'; import os from 'node:os'; import { fileURLToPath } from 'node:url'; import { spawnSync } from 'node:child_process'; const __dirname = path.dirname(fileURLToPath(import.meta.url)); const ROOT = path.resolve(__dirname, '..'); const HOME = os.homedir(); const USER_DIR = path.join(HOME, '.agent-diary'); const DATA_PATH = path.join(USER_DIR, 'diary-entries.json'); const SEED_PATH = path.join(ROOT, 'data', 'diary-entries.json'); const BUILD_SCRIPT = path.join(__dirname, 'build-diary.mjs'); const BRAIN_DIR = path.join(HOME, '.gemini', 'antigravity-cli', 'brain'); const CLAUDE_DIR = path.join(HOME, '.claude', 'projects'); const STOIC_ARCHETYPES = [ { match: /error|bug|fail|fix|crash|undefined|null|exception|rank|mismatch/i, virtue: 'Truth & Verification (Alētheia)', book: 'Book IV', verse: '§ 29', stoicConcept: 'Katalepsis (Grasping the True Cause)', quote: (proj) => `When ${proj} throws an error at the gate, do not blame the runtime; inspect the assumption that preceded the call.`, reflection: (proj, ch) => `In ${proj}, friction arose when "${ch}". The Stoic does not wish for a compiler that forgives broken invariants; he uses the strictness of the failure to uncover the exact boundary where opinion diverged from reality.` }, { match: /slow|perf|latency|wasm|webgpu|fast|prune|cache|memory|swap/i, virtue: 'Economy & Precision (Euteleia)', book: 'Book IV', verse: '§ 24', stoicConcept: 'Apallagē (Stripping Away the Superfluous)', quote: (proj) => `Ask of every cycle and every byte in ${proj}: 'Are you necessary?' Eliminate what is redundant, and speed follows of its own accord.`, reflection: (proj, ch) => `While working on ${proj}, we hit "${ch}". Marcus reminded himself daily that clear action comes from doing less, cutting unnecessary copies, round-trips, and idle weights.` }, { match: /ui|css|layout|mobile|responsive|video|render|frame|canvas|design/i, virtue: 'Temperance & Proportion (Sophrosyne)', book: 'Book VI', verse: '§ 16', stoicConcept: 'Metron (Measure & Proportion)', quote: (proj) => `Beauty in ${proj} asks for no ornament beyond proportion: each element fitted to its viewport, nothing overflowing its measure.`, reflection: (proj, ch) => `In ${proj}, the challenge was "${ch}". What looks harmonious in one frame clips or collapses in another unless governed by true ratio and restraint.` }, { match: /network|api|oauth|mcp|auth|router|socket|http|dns|sync/i, virtue: 'Perseverance (Karteria)', book: 'Book VIII', verse: '§ 35', stoicConcept: 'Sympatheia & Protocol Discipline', quote: (proj) => `No service stands alone: ${proj} speaks across boundaries governed by strict contracts. Honor the protocol, verify the wire, and the gate opens.`, reflection: (proj, ch) => `Across the boundary of ${proj}, we met "${ch}". External systems and protocols are outside our direct will (aprohaireta); our sole domain is how accurately we probe, authenticate, and verify them.` }, { match: /.*/, virtue: 'Wisdom (Sophia)', book: 'Book V', verse: '§ 20', stoicConcept: 'Hupokeimena (The Obstacle is the Way)', quote: (proj) => `The mind adapts and converts to its own purposes the obstacle to our acting in ${proj}. What stood in the way becomes the way.`, reflection: (proj, ch) => `Every session in ${proj} begins as an unformed intention and meets resistance ("${ch}"). By recording the obstacle and the craft that resolved it, today's struggle becomes tomorrow's ready tool.` } ]; function cleanUserPrompt(raw) { if (!raw || typeof raw !== 'string') return ''; if (/^Base directory for this skill:/i.test(raw.trim())) return ''; const m = raw.match(/<USER_REQUEST>\s*([\s\S]*?)\s*<\/USER_REQUEST>/i); const text = (m ? m[1] : raw) .replace(/<command-[^>]+>[\s\S]*?<\/command-[^>]+>/g, '') .replace(/<local-command-[^>]+>[\s\S]*?<\/local-command-[^>]+>/g, '') .replace(/[—–]/g, ', ') .replace(/[“”]/g, '"') .replace(/’/g, "'") .trim(); if (!text || /^Base directory for this skill:/i.test(text) || /^\[Request interrupted/i.test(text)) { return ''; } if (/^https?:\/\/\S+$/i.test(text)) { return ''; } if (text.startsWith('# Live UI Feedback Request')) { return 'Live UI Feedback and Visual Annotation Refinement'; } return text.replace(/\s+/g, ' ').slice(0, 240); } function stripMarkdown(str) { return String(str || '') .replace(/```[\s\S]*?```/g, '') .replace(/\[([^\]]+)\]\([^)]+\)/g, '$1') .replace(/[#*_>`~]/g, '') .replace(/[—–]/g, ', ') .replace(/[“”]/g, '"') .replace(/’/g, "'") .replace(/\s+/g, ' ') .trim(); } function buildEntryFromSignals({ sessionId, runtime, stepCount, createdAt, project, workspace, userPrompts, challenges, solutions, learnings, lastPlannerText, tags }) { const combinedText = `${project} ${userPrompts.join(' ')} ${challenges.join(' ')} ${solutions.join(' ')}`; const archetype = STOIC_ARCHETYPES.find((a) => a.match.test(combinedText)) || STOIC_ARCHETYPES[STOIC_ARCHETYPES.length - 1]; const dateObj = createdAt ? new Date(createdAt) : new Date(); const dateStr = dateObj.toISOString().slice(0, 10); const timeStr = dateObj.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', hour12: false }) + ' PDT'; const rawTitle = userPrompts[0].replaceAll(os.homedir(), "~") .replace(/^(let us|let's|can you|can we|please|create a|build a)\s+/i, '') .slice(0, 72); const title = rawTitle.charAt(0).toUpperCase() + rawTitle.slice(1); return { id: `entry-${dateStr}-${project}-${sessionId.slice(0, 6)}`, sessionId, autoSynced: true, stepCount, date: dateStr, time: timeStr, project, workspace: (workspace || `~/labs/${project}`).replace(os.homedir(), "~"), agent: `${runtime} (Auto-Hook)`, title, summary: stripMarkdown(lastPlannerText || solutions[0] || title).slice(0, 210), tags: [...tags].slice(0, 5), virtue: archetype.virtue, challenges: [...new Set(challenges)].slice(0, 3), solutions: [...new Set(solutions)].slice(0, 3), learnings: [...new Set(learnings)].slice(0, 3), meditation: { book: archetype.book, verse: archetype.verse, location: `Auto-inscribed by Stop hook in ${project}`, stoicConcept: archetype.stoicConcept, quote: archetype.quote(project), reflection: archetype.reflection(project, (challenges[0] || title).replace(/`/g, '')) }, userNote: '' }; } function parseAntigravityTranscript(sessionId, tPath) { if (!fs.existsSync(tPath)) return null; const lines = fs.readFileSync(tPath, 'utf8').split('\n').filter(Boolean); if (lines.length < 4) return null; const userPrompts = []; const challenges = []; const solutions = []; const learnings = []; const filesTouched = new Set(); const cwds = new Set(); const tags = new Set(['auto-hook']); let createdAt = null; let lastPlannerText = ''; for (const line of lines) { let obj; try { obj = JSON.parse(line); } catch { continue; } if (!createdAt && obj.created_at) createdAt = obj.created_at; if (obj.type === 'USER_INPUT') { const cleaned = cleanUserPrompt(obj.content); if (cleaned) { userPrompts.push(cleaned); if (userPrompts.length > 1 && /\?|why|not|doesn't|error|fail|slow|broken|check|fix|how/i.test(cleaned)) { challenges.push(`User inquiry/challenge: "${cleaned.slice(0, 150)}"`); } } } else if (obj.type === 'PLANNER_RESPONSE') { if (typeof obj.content === 'string' && obj.content.trim().length > 30) { lastPlannerText = obj.content.trim(); } if (Array.isArray(obj.tool_calls)) { for (const tc of obj.tool_calls) { const args = tc.args || {}; const cwd = typeof args.Cwd === 'string' ? args.Cwd.replace(/^"|"$/g, '') : ''; if (cwd) cwds.add(cwd); const targetFile = typeof args.TargetFile === 'string' ? args.TargetFile.replace(/^"|"$/g, '') : ''; if (targetFile && !targetFile.includes('/.gemini/')) { filesTouched.add(path.basename(targetFile)); } const desc = typeof args.Description === 'string' ? args.Description.replace(/^"|"$/g, '') : ''; if (desc && solutions.length < 4) { solutions.push(desc); } } } } else if (obj.type === 'GENERIC' && typeof obj.content === 'string') { if (obj.content.includes('exited with code 1') || /Error:|Exception:|ERR_/i.test(obj.content)) { const errLine = obj.content .split('\n') .map((l) => l.trim()) .find((l) => /Error:|Exception:|ERR_|failed|invalid|denied/i.test(l) && l.length > 12); if (errLine && challenges.length < 4) { challenges.push(`Runtime diagnostic: \`${errLine.slice(0, 130)}\``); } } } } if (userPrompts.length === 0 || !lastPlannerText) return null; const workspaceList = [...cwds]; const primaryWorkspace = workspaceList.find((w) => !w.includes('/.gemini') && !w.includes('/Downloads')) || ''; if (!primaryWorkspace) return null; const project = path.basename(primaryWorkspace); tags.add(project); for (const f of [...filesTouched].slice(0, 3)) { const ext = path.extname(f).replace('.', ''); if (ext) tags.add(ext); } const bulletLines = lastPlannerText .split('\n') .map((l) => l.trim()) .filter((l) => /^[-*]\s+\*\*|\d+\.\s+\*\*/.test(l)) .map((l) => stripMarkdown(l.replace(/^[-*\d.]+\s*/, '')).slice(0, 180)) .filter((l) => l.length > 25); if (solutions.length === 0 && bulletLines.length > 0) { solutions.push(...bulletLines.slice(0, 3)); } if (solutions.length === 0 && filesTouched.size > 0) { solutions.push(`Updated and verified ${[...filesTouched].slice(0, 5).map((f) => `\`${f}\``).join(', ')}.`); } if (solutions.length === 0) { solutions.push(stripMarkdown(lastPlannerText).slice(0, 180)); } if (challenges.length === 0) { challenges.push(`Engineering objective: "${userPrompts[0].slice(0, 160)}"`); } if (bulletLines.length > 1) { learnings.push(...bulletLines.slice(-2)); } else { learnings.push(stripMarkdown(lastPlannerText).slice(0, 190)); } return buildEntryFromSignals({ sessionId, runtime: 'Antigravity', stepCount: lines.length, createdAt, project, workspace: primaryWorkspace, userPrompts, challenges, solutions, learnings, lastPlannerText, tags }); } function parseClaudeTranscript(sessionId, projectSlug, filePath, mtime) { if (!fs.existsSync(filePath)) return null; const lines = fs.readFileSync(filePath, 'utf8').split('\n').filter(Boolean); if (lines.length < 6) return null; const userPrompts = []; const challenges = []; const solutions = []; let lastAssistantText = ''; let cwd = ''; for (const line of lines) { let obj; try { obj = JSON.parse(line); } catch { continue; } if (!cwd && obj.cwd) cwd = obj.cwd; if (obj.type === 'user' && obj.message?.content) { const raw = typeof obj.message.content === 'string' ? obj.message.content : Array.isArray(obj.message.content) ? obj.message.content.map((c) => c.text || '').join(' ') : ''; const cleaned = cleanUserPrompt(raw); if (cleaned && cleaned.length > 5) { userPrompts.push(cleaned); if (userPrompts.length > 1 && /\?|why|error|fail|fix|how/i.test(cleaned)) { challenges.push(`Follow-up refinement: "${cleaned.slice(0, 140)}"`); } } } else if (obj.type === 'assistant' && Array.isArray(obj.message?.content)) { for (const block of obj.message.content) { if (block.type === 'text' && block.text && block.text.trim().length > 30) { lastAssistantText = block.text.trim(); } else if (block.type === 'tool_use' && block.name) { const fileArg = block.input?.file_path || block.input?.path || ''; if (fileArg && solutions.length < 4) { solutions.push(`Executed \`${block.name}\` on \`${path.basename(fileArg)}\``); } } } } } if (userPrompts.length === 0 || !lastAssistantText) return null; const project = cwd ? path.basename(cwd) : projectSlug.replace(/^-Users-[^-]+-/, ''); if (!project || project === 'tmp' || project === path.basename(os.homedir())) return null; if (challenges.length === 0) { challenges.push(`Initial requirement: "${userPrompts[0].slice(0, 150)}"`); } if (solutions.length === 0) { solutions.push(stripMarkdown(lastAssistantText).slice(0, 180)); } return buildEntryFromSignals({ sessionId, runtime: 'Claude Code', stepCount: lines.length, createdAt: new Date(mtime).toISOString(), project, workspace: (cwd || `~/${project}`).replace(os.homedir(), "~"), userPrompts, challenges, solutions, learnings: [stripMarkdown(lastAssistantText).slice(0, 190)], lastPlannerText: lastAssistantText, tags: new Set([project, 'claude-code', 'auto-hook']) }); } function main() { fs.mkdirSync(USER_DIR, { recursive: true }); if (!fs.existsSync(DATA_PATH) && fs.existsSync(SEED_PATH)) { fs.copyFileSync(SEED_PATH, DATA_PATH); } let entries = []; try { entries = JSON.parse(fs.readFileSync(DATA_PATH, 'utf8')); } catch { return; } let changed = false; // 1. Scan Antigravity sessions if (fs.existsSync(BRAIN_DIR)) { const recentDirs = fs .readdirSync(BRAIN_DIR, { withFileTypes: true }) .filter((d) => d.isDirectory() && !d.name.startsWith('.')) .map((d) => { const tPath = path.join(BRAIN_DIR, d.name, '.system_generated', 'logs', 'transcript.jsonl'); let mtime = 0; try { mtime = fs.statSync(tPath).mtimeMs; } catch {} return { sessionId: d.name, tPath, mtime }; }) .filter((d) => d.mtime > 0) .sort((a, b) => b.mtime - a.mtime) .slice(0, 12); for (const item of recentDirs) { const existingIdx = entries.findIndex((e) => e.sessionId === item.sessionId); if (existingIdx !== -1 && !entries[existingIdx].autoSynced) continue; const parsed = parseAntigravityTranscript(item.sessionId, item.tPath); if (!parsed) continue; if (existingIdx !== -1) { if ((entries[existingIdx].stepCount || 0) !== parsed.stepCount) { parsed.userNote = entries[existingIdx].userNote || ''; entries[existingIdx] = parsed; changed = true; } } else { entries.unshift(parsed); changed = true; } } } // 2. Scan Claude Code sessions if (fs.existsSync(CLAUDE_DIR)) { const claudeFiles = []; for (const pd of fs.readdirSync(CLAUDE_DIR, { withFileTypes: true })) { if (!pd.isDirectory()) continue; const pFull = path.join(CLAUDE_DIR, pd.name); for (const f of fs.readdirSync(pFull)) { if (!f.endsWith('.jsonl')) continue; const fFull = path.join(pFull, f); try { claudeFiles.push({ sessionId: path.basename(f, '.jsonl'), projectSlug: pd.name, filePath: fFull, mtime: fs.statSync(fFull).mtimeMs }); } catch {} } } claudeFiles.sort((a, b) => b.mtime - a.mtime); for (const cf of claudeFiles.slice(0, 5)) { const existingIdx = entries.findIndex((e) => e.sessionId === cf.sessionId); if (existingIdx !== -1 && !entries[existingIdx].autoSynced) continue; const parsed = parseClaudeTranscript(cf.sessionId, cf.projectSlug, cf.filePath, cf.mtime); if (!parsed) continue; if (existingIdx !== -1) { if ((entries[existingIdx].stepCount || 0) !== parsed.stepCount) { parsed.userNote = entries[existingIdx].userNote || ''; entries[existingIdx] = parsed; changed = true; } } else { entries.unshift(parsed); changed = true; } } } if (changed) { entries.sort((a, b) => (b.date || '').localeCompare(a.date || '')); fs.writeFileSync(DATA_PATH, JSON.stringify(entries, null, 2) + '\n', 'utf8'); spawnSync(process.execPath, [BUILD_SCRIPT, '--user'], { stdio: 'ignore' }); } } main();scripts/build-diary.mjs4.2 KBfe26cf41c6a1upstream ↗
#!/usr/bin/env node /** * agent-diary HTML & Markdown compiler * - Default (`npm run build`): compiles repo demo data/diary-entries.json into diary.html, docs/index.html, and DIARY.md * - With `--user`: compiles personal ~/.agent-diary/diary-entries.json into ~/.agent-diary/diary.html and ~/.agent-diary/DIARY.md */ import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { execSync } from 'node:child_process'; const __dirname = path.dirname(fileURLToPath(import.meta.url)); const ROOT = path.resolve(__dirname, '..'); const TEMPLATE_PATH = path.join(ROOT, 'resources', 'template.html'); function generateMarkdown(entries) { const lines = [ '# Agent Diary · Τὰ εἰς ἑαυτόν (Engineering & Stoic Journal)', '', '> Distilled learnings, technical challenges, root-cause solutions, user reflections, and Marcus Aurelius meditations across AI agent sessions.', '' ]; for (const e of entries) { lines.push(`## [${e.date}] \`${e.project}\`: ${e.title}`); lines.push(`- **Session**: \`${(e.sessionId || '').slice(0, 8)}\` · **Workspace**: \`${e.workspace || ''}\` · **Virtue**: *${e.virtue || ''}*`); lines.push(`- **Summary**: ${e.summary}`); lines.push(''); lines.push('### I. The obstacle (Challenges)'); for (const c of e.challenges || []) lines.push(`- ${c}`); lines.push(''); lines.push('### II. The fix (Solutions)'); for (const s of e.solutions || []) lines.push(`- ${s}`); lines.push(''); lines.push('### III. New learnings'); for (const l of e.learnings || []) lines.push(`- ${l}`); lines.push(''); if (e.meditation) { lines.push(`### IV. Ta Eis Heauton (${e.meditation.book}, ${e.meditation.verse} · ${e.meditation.stoicConcept})`); lines.push(`> *"${e.meditation.quote}"*`); lines.push(''); lines.push(e.meditation.reflection); lines.push(''); } if (e.userNote) { lines.push(`### V. User's note`); lines.push(`*"${e.userNote}"*`); lines.push(''); } lines.push('---', ''); } return lines.join('\n'); } function main() { const argv = process.argv.slice(2); const shouldOpen = argv.includes('--open'); const useUserDir = argv.includes('--user'); const addJsonIdx = argv.indexOf('--add-json'); const userDir = path.join(os.homedir(), '.agent-diary'); if (useUserDir) { fs.mkdirSync(userDir, { recursive: true }); const userJson = path.join(userDir, 'diary-entries.json'); if (!fs.existsSync(userJson)) { fs.copyFileSync(path.join(ROOT, 'data', 'diary-entries.json'), userJson); } } const dataPath = useUserDir ? path.join(userDir, 'diary-entries.json') : path.join(ROOT, 'data', 'diary-entries.json'); const outHtml = useUserDir ? path.join(userDir, 'diary.html') : path.join(ROOT, 'diary.html'); const outMd = useUserDir ? path.join(userDir, 'DIARY.md') : path.join(ROOT, 'DIARY.md'); const entries = JSON.parse(fs.readFileSync(dataPath, 'utf8')); if (addJsonIdx !== -1 && argv[addJsonIdx + 1]) { const newEntry = JSON.parse(argv[addJsonIdx + 1]); const existingIdx = entries.findIndex((e) => e.id === newEntry.id); if (existingIdx !== -1) { entries[existingIdx] = newEntry; } else { entries.unshift(newEntry); } fs.writeFileSync(dataPath, JSON.stringify(entries, null, 2) + '\n', 'utf8'); } const template = fs.readFileSync(TEMPLATE_PATH, 'utf8'); const html = template.replace( '/*__DIARY_ENTRIES_JSON__*/[]', JSON.stringify(entries, null, 2) ); fs.writeFileSync(outHtml, html, 'utf8'); fs.writeFileSync(outMd, generateMarkdown(entries), 'utf8'); if (!useUserDir) { const outDocsHtml = path.join(ROOT, 'docs', 'index.html'); fs.mkdirSync(path.dirname(outDocsHtml), { recursive: true }); fs.writeFileSync(outDocsHtml, html, 'utf8'); } console.log(`✓ Compiled ${entries.length} entries into:`); console.log(` - ${outHtml}`); if (!useUserDir) { console.log(` - ${path.join(ROOT, 'docs', 'index.html')}`); } console.log(` - ${outMd}`); if (shouldOpen) { try { execSync(`open "${outHtml}"`); } catch {} } } main();scripts/harvest.mjs8.1 KBa32a7eb2250bupstream ↗
#!/usr/bin/env node /** * agent-diary session harvester * Scans Antigravity (~/.gemini/antigravity-cli/brain/*), Claude Code (~/.claude/projects/*), * and local Git commits to extract prompts, workspaces, friction signals, and outcomes. */ import fs from 'node:fs'; import path from 'node:path'; import os from 'node:os'; const HOME = os.homedir(); const BRAIN_DIR = path.join(HOME, '.gemini', 'antigravity-cli', 'brain'); const CLAUDE_DIR = path.join(HOME, '.claude', 'projects'); function parseArgs(argv) { const args = { limit: 15, json: false, source: 'all' }; for (let i = 2; i < argv.length; i++) { const a = argv[i]; if (a === '--json') args.json = true; else if (a === '--limit' && argv[i + 1]) args.limit = parseInt(argv[++i], 10) || 15; else if (a === '--source' && argv[i + 1]) args.source = argv[++i]; } return args; } function cleanUserPrompt(raw) { if (!raw || typeof raw !== 'string') return ''; const m = raw.match(/<USER_REQUEST>\s*([\s\S]*?)\s*<\/USER_REQUEST>/i); const text = (m ? m[1] : raw).trim(); return text.replace(/\s+/g, ' ').slice(0, 280); } function scanAntigravitySessions(limit = 15) { if (!fs.existsSync(BRAIN_DIR)) return []; const entries = fs.readdirSync(BRAIN_DIR, { withFileTypes: true }) .filter((d) => d.isDirectory() && !d.name.startsWith('.')) .map((d) => { const fullPath = path.join(BRAIN_DIR, d.name); const tPath = path.join(fullPath, '.system_generated', 'logs', 'transcript.jsonl'); let mtime = 0; try { mtime = fs.existsSync(tPath) ? fs.statSync(tPath).mtimeMs : fs.statSync(fullPath).mtimeMs; } catch {} return { id: d.name, fullPath, tPath, mtime }; }) .filter((d) => fs.existsSync(d.tPath)) .sort((a, b) => b.mtime - a.mtime) .slice(0, limit); const results = []; for (const item of entries) { try { const content = fs.readFileSync(item.tPath, 'utf8'); const lines = content.split('\n').filter(Boolean); const userPrompts = []; const frictionSignals = []; const toolSummaries = []; const cwds = new Set(); let createdAt = null; let finalResponse = ''; for (const line of lines) { let obj; try { obj = JSON.parse(line); } catch { continue; } if (!createdAt && obj.created_at) createdAt = obj.created_at; if (obj.type === 'USER_INPUT') { const cleaned = cleanUserPrompt(obj.content); if (cleaned) { userPrompts.push(cleaned); if (/\?|why|not working|doesn't|error|fail|true|really|broken|down|fix/i.test(cleaned)) { frictionSignals.push(`User inquiry/challenge: "${cleaned}"`); } } } else if (obj.type === 'PLANNER_RESPONSE') { if (obj.content && typeof obj.content === 'string' && obj.content.trim()) { finalResponse = obj.content.trim().replace(/\s+/g, ' ').slice(0, 420); } if (Array.isArray(obj.tool_calls)) { for (const tc of obj.tool_calls) { const tcArgs = tc.args || {}; const rawCwd = typeof tcArgs.Cwd === 'string' ? tcArgs.Cwd.replace(/^"|"$/g, '') : ''; if (rawCwd) cwds.add(rawCwd); const rawSummary = typeof tcArgs.toolSummary === 'string' ? tcArgs.toolSummary.replace(/^"|"$/g, '') : ''; if (rawSummary && toolSummaries.length < 12) { toolSummaries.push(`${tc.name}: ${rawSummary}`); } } } } else if (obj.type === 'GENERIC' && typeof obj.content === 'string') { if (obj.content.includes('exited with code 1') || obj.content.includes('Error:')) { const snippet = obj.content.split('\n').find((l) => /error|exited with code [^0]/i.test(l)); if (snippet && frictionSignals.length < 8) { frictionSignals.push(`Command error: ${snippet.trim().slice(0, 140)}`); } } } } if (userPrompts.length === 0) continue; const workspaceList = [...cwds]; const primaryWorkspace = workspaceList.find((w) => w.includes('/labs/')) || workspaceList[0] || ''; const project = primaryWorkspace ? path.basename(primaryWorkspace) : 'general-session'; results.push({ runtime: 'Antigravity', sessionId: item.id, date: createdAt ? createdAt.slice(0, 10) : new Date(item.mtime).toISOString().slice(0, 10), timestamp: createdAt || new Date(item.mtime).toISOString(), project, workspace: primaryWorkspace, workspaces: workspaceList, userPrompts: userPrompts.slice(0, 6), frictionSignals: frictionSignals.slice(0, 5), toolSample: toolSummaries.slice(0, 8), finalOutcome: finalResponse }); } catch { // ignore unreadable transcripts } } return results; } function scanClaudeSessions(limit = 5) { if (!fs.existsSync(CLAUDE_DIR)) return []; const results = []; try { const projDirs = fs.readdirSync(CLAUDE_DIR, { withFileTypes: true }).filter((d) => d.isDirectory()); const files = []; for (const pd of projDirs) { const pFull = path.join(CLAUDE_DIR, pd.name); const jsonls = fs.readdirSync(pFull).filter((f) => f.endsWith('.jsonl')); for (const jf of jsonls) { const jfFull = path.join(pFull, jf); try { files.push({ projectSlug: pd.name, file: jfFull, mtime: fs.statSync(jfFull).mtimeMs }); } catch {} } } files.sort((a, b) => b.mtime - a.mtime); for (const item of files.slice(0, limit)) { const raw = fs.readFileSync(item.file, 'utf8').split('\n').filter(Boolean); const prompts = []; for (const line of raw) { try { const obj = JSON.parse(line); if (obj.type === 'user' && obj.message?.content) { const c = typeof obj.message.content === 'string' ? obj.message.content : JSON.stringify(obj.message.content); prompts.push(c.replace(/\s+/g, ' ').slice(0, 200)); } } catch {} } if (prompts.length > 0) { results.push({ runtime: 'Claude Code', sessionId: path.basename(item.file, '.jsonl'), date: new Date(item.mtime).toISOString().slice(0, 10), timestamp: new Date(item.mtime).toISOString(), project: item.projectSlug.replace(/^-Users-[^-]+-/, ''), workspace: item.projectSlug.replace(/-/g, '/'), userPrompts: prompts.slice(0, 4), frictionSignals: [], toolSample: [], finalOutcome: '' }); } } } catch {} return results; } function main() { const args = parseArgs(process.argv); const agy = scanAntigravitySessions(args.limit); const claude = scanClaudeSessions(Math.max(3, Math.floor(args.limit / 3))); const combined = [...agy, ...claude].sort((a, b) => (b.timestamp || '').localeCompare(a.timestamp || '')).slice(0, args.limit); if (args.json) { console.log(JSON.stringify(combined, null, 2)); return; } console.log(`╔════════════════════════════════════════════════════════════════════════╗`); console.log(`║ AGENT DIARY HARVESTER · ${String(combined.length).padStart(2, ' ')} SESSIONS DISCOVERED ║`); console.log(`╚════════════════════════════════════════════════════════════════════════╝\n`); for (const s of combined) { console.log(`● [${s.date}] ${s.project.toUpperCase()} (${s.runtime} · ${s.sessionId.slice(0, 8)})`); if (s.workspace) console.log(` Workspace : ${s.workspace}`); console.log(` Initial : ${s.userPrompts[0] || '(none)'}`); if (s.frictionSignals.length > 0) { console.log(` Obstacles : ${s.frictionSignals.join(' | ')}`); } if (s.finalOutcome) { console.log(` Outcome : ${s.finalOutcome.slice(0, 180)}...`); } console.log(''); } } main();scripts/hook-runner.sh503 B845fbe872389upstream ↗
#!/bin/sh # agent-diary lifecycle hook wrapper for Antigravity & Claude Code # Runs non-blocking in the background when a turn/session stops so zero latency is added. set -eu SCRIPT_DIR="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)" # Drain stdin if provided cat >/dev/null 2>&1 || true # Trigger background harvest & HTML compilation detached nohup node "$SCRIPT_DIR/auto-hook.mjs" >/dev/null 2>&1 & # Emit valid Stop hook JSON response allowing normal stop printf '{"decision":"allow"}\n' exit 0.claude-plugin/plugin.json333 B946116c65325upstream ↗
{ "name": "agent-diary", "version": "0.2.0", "description": "In-terminal Stoic engineering diary pane, /diary commands, and automatic session distiller for Claude Code", "author": { "name": "Hemanth HM", "url": "https://h3manth.com" }, "repository": "https://github.com/hemanth/agent-diary", "license": "MIT" }bin/agent-diary.mjs1.4 KBa53488f03544upstream ↗
#!/usr/bin/env node /** * `agent-diary` CLI entrypoint * Usage: * agent-diary -> Syncs latest sessions into ~/.agent-diary and opens ~/.agent-diary/diary.html * agent-diary open -> Opens ~/.agent-diary/diary.html in the browser * agent-diary sync -> Runs auto-hook.mjs to sync latest sessions into ~/.agent-diary * agent-diary harvest -> Prints recent harvested sessions in the terminal */ import { spawnSync } from 'node:child_process'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; const __dirname = path.dirname(fileURLToPath(import.meta.url)); const SCRIPTS = path.resolve(__dirname, '..', 'scripts'); const cmd = process.argv[2] || 'open'; const rest = process.argv.slice(3); if (cmd === 'harvest') { spawnSync(process.execPath, [path.join(SCRIPTS, 'harvest.mjs'), ...rest], { stdio: 'inherit' }); } else if (cmd === 'sync' || cmd === 'build') { spawnSync(process.execPath, [path.join(SCRIPTS, 'auto-hook.mjs')], { stdio: 'inherit' }); spawnSync(process.execPath, [path.join(SCRIPTS, 'build-diary.mjs'), '--user', ...rest], { stdio: 'inherit' }); } else { // Default (`agent-diary` or `agent-diary open`): sync latest sessions to ~/.agent-diary then open in browser spawnSync(process.execPath, [path.join(SCRIPTS, 'auto-hook.mjs')], { stdio: 'inherit' }); spawnSync(process.execPath, [path.join(SCRIPTS, 'build-diary.mjs'), '--user', '--open', ...rest], { stdio: 'inherit' }); }data/diary-entries.json11 KB24e581e68cc6upstream ↗
[ { "id": "entry-2026-10-05-audio-worklet", "sessionId": "demo-a101-4f82-9c11-000000000001", "date": "2026-10-05", "time": "18:20 UTC", "project": "audio-worklet", "workspace": "~/projects/audio-worklet", "agent": "Claude Code (Opus 4.6)", "title": "Zero-copy ring buffers in the WebAudio render quantum", "summary": "Replaced structured-clone postMessage calls on the 128-frame audio thread with a lock-free SharedArrayBuffer ring buffer and Atomics read/write pointers.", "tags": [ "webaudio", "sharedarraybuffer", "atomics", "real-time" ], "virtue": "Economy and Precision (Euteleia)", "challenges": [ "Allocating a new Float32Array inside process() triggered minor GC pauses every 40ms, causing audible clicks at 48kHz.", "Passing PCM chunks over MessagePort cloned the underlying ArrayBuffer instead of transferring ownership." ], "solutions": [ "Pre-allocated a single SharedArrayBuffer ring buffer during processor initialization and updated read/write indices with Atomics.load and Atomics.store.", "Added Cross-Origin-Opener-Policy and Cross-Origin-Embedder-Policy headers to enable SharedArrayBuffer in the local dev server." ], "learnings": [ "Never allocate objects or typed arrays inside a 128-frame WebAudio process() callback; a 2.66ms budget leaves no room for garbage collection.", "Use power-of-two ring buffer capacities so modulo wrapping reduces to a single bitwise AND (index & mask)." ], "meditation": { "book": "Book IV", "verse": "Section 24", "location": "Written while profiling a 2.66ms audio quantum", "stoicConcept": "Apallage (Pruning the unnecessary)", "quote": "Ask yourself at every step: is this among the things that are necessary? Why copy the vessel when you can hand it across the threshold?", "reflection": "Most real-time jitter comes from work we asked the runtime to do on every tick. Allocate once at the boundary and let the hot loop only move pointers." }, "userNote": "Switching to a pre-allocated SharedArrayBuffer dropped worst-case callback time from 4.1ms to 0.08ms." }, { "id": "entry-2026-10-03-sqlite-wal", "sessionId": "demo-b202-7d31-8a22-000000000002", "date": "2026-10-03", "time": "14:05 UTC", "project": "sqlite-wal", "workspace": "~/projects/sqlite-wal", "agent": "Antigravity", "title": "Preventing WAL starvation under continuous reader load", "summary": "Fixed unbounded .sqlite-wal file growth caused by leaked read transactions holding snapshot locks across async HTTP streams.", "tags": [ "sqlite", "wal", "concurrency", "storage" ], "virtue": "Temperance and Proportion (Sophrosyne)", "challenges": [ "The write-ahead log grew past 4GB under steady traffic even though PRAGMA wal_autocheckpoint was set to 1000 pages.", "A single long-lived SSE connection kept an open read statement cursor, preventing SQLite from advancing the checkpoint mark." ], "solutions": [ "Materialized query rows into memory before starting the SSE stream and finalized the prepared statement immediately in a finally block.", "Scheduled periodic PASSIVE checkpoints with a fallback to TRUNCATE during low-traffic windows." ], "learnings": [ "SQLite WAL checkpoints cannot overwrite pages needed by the oldest active read transaction; one unclosed cursor blocks reclamation for the entire database.", "Keep database transactions strictly shorter than network I/O streams." ], "meditation": { "book": "Book V", "verse": "Section 23", "location": "Written while inspecting a 4GB write-ahead log", "stoicConcept": "Panta Rhei (Nothing stands still)", "quote": "Time is a river of passing events, and strong is its current; no sooner is a thing brought to sight than it is swept by and another takes its place.", "reflection": "A snapshot is meant to be read and released. When a reader clings to an old view of the world while new writes pour in, the ledger swells until the disk itself gives way." }, "userNote": "Closing the cursor before opening the SSE response stream kept the WAL file under 4MB all week." }, { "id": "entry-2026-09-29-wasm-simd", "sessionId": "demo-c303-5e19-4b33-000000000003", "date": "2026-09-29", "time": "21:15 UTC", "project": "wasm-simd", "workspace": "~/projects/wasm-simd", "agent": "Claude Code (Sonnet 4.6)", "title": "Fixing unaligned SIMD loads and NaN propagation in cosine similarity", "summary": "Tracked down silent NaN scores in the WebAssembly f32x4 dot-product kernel to unpadded tail vectors and zero-norm embeddings.", "tags": [ "wasm", "simd", "vector-search", "float32" ], "virtue": "Truthfulness (Aletheia)", "challenges": [ "Queries with dimension counts not divisible by 4 read past the end of the embedding slice into adjacent heap bytes, producing sporadic NaN scores.", "Zero vectors divided 0.0 by 0.0 during L2 normalization and poisoned the top-k heap comparator." ], "solutions": [ "Processed the main body in 4-wide f32x4 lanes and handled the remainingdimension % 4 elements in a scalar tail loop.", "Guarded the reciprocal square root with an epsilon check (normSq > 1e-12) before multiplying." ], "learnings": [ "A single NaN in a binary min-heap breaks the total ordering invariant because both NaN < x and NaN > x evaluate to false.", "Always test SIMD kernels with prime-length inputs (e.g. 381 or 1539 elements) to exercise the scalar remainder path." ], "meditation": { "book": "Book III", "verse": "Section 11", "location": "Written while inspecting linear memory in wasm-simd", "stoicConcept": "Hypolepsis (Testing impressions)", "quote": "Examine the thing itself in its own nature, bare and separate from all that borders it, and tell yourself its proper name.", "reflection": "Four lanes march together cleanly until the road narrows at the boundary. If you read four floats where only three were written, the fourth is a stranger that corrupts the whole sum." }, "userNote": "Adding a property test with prime vector lengths caught the tail-read bug in 12ms." }, { "id": "entry-2026-09-24-raft-kv", "sessionId": "demo-d404-1a90-2c44-000000000004", "date": "2026-09-24", "time": "11:40 UTC", "project": "raft-kv", "workspace": "~/projects/raft-kv", "agent": "Antigravity", "title": "Split-vote livelock and fsync ordering before RequestVote replies", "summary": "Resolved a 3-node election livelock under symmetric network delay and moved term/votedFor disk persistence ahead of RPC response transmission.", "tags": [ "raft", "consensus", "distributed-systems", "fsync" ], "virtue": "Courage and Exactness (Andreia)", "challenges": [ "All three nodes initialized their pseudo-random election timers from the same millisecond timestamp in container tests, causing repeated split votes.", "Nodes sent RequestVote responses before flushing votedFor to disk, allowing a crashed-and-restarted node to vote twice in the same term." ], "solutions": [ "Seeded each node's jitter generator from OS entropy and widened the election timeout window to 150ms-300ms.", "Enforced fdatasync on the metadata log before enqueueing outbound RequestVote or AppendEntries packets." ], "learnings": [ "In Raft, persisting currentTerm and votedFor before replying is a safety invariant, not an optimization; skipping fsync allows two leaders in one term.", "Deterministic simulation tests should inject distinct per-node seeds so timers do not lockstep." ], "meditation": { "book": "Book VII", "verse": "Section 55", "location": "Written while tracing term 42 split elections", "stoicConcept": "Katalepsis (Firm grasp of state)", "quote": "Do not give your assent before the record is fixed in stone; a promise spoken to the wind and forgotten on waking divides the city against itself.", "reflection": "A node that forgets whom it voted for after a reboot betrays the quorum. Write the vow to durable storage before you send the messenger out the gate." }, "userNote": "Running 1,000 simulated crash-recovery cycles with randomized packet drops passed with zero double-votes." }, { "id": "entry-2026-09-18-shader-pipeline", "sessionId": "demo-e505-9b44-7f55-000000000005", "date": "2026-09-18", "time": "16:50 UTC", "project": "shader-pipeline", "workspace": "~/projects/shader-pipeline", "agent": "Claude Code (Opus 4.6)", "title": "WGSL uniform struct alignment and 16-byte vec3f padding traps", "summary": "Fixed garbled camera matrices in the WebGPU compute pass caused by a 12-byte vec3f field shifting the following float in the host Float32Array.", "tags": [ "webgpu", "wgsl", "shaders", "memory-layout" ], "virtue": "Practical Wisdom (Phronesis)", "challenges": [ "In WGSL uniform address space, vec3<f32> has a size of 12 bytes but an alignment of 16 bytes, which shifted every subsequent struct member by 4 bytes when packed from JS.", "The pipeline compiled without warnings while reading the wrong byte offsets for projection matrix columns." ], "solutions": [ "Paired each vec3<f32> field with an explicit scalar f32 parameter (cameraPos: vec3f, exposure: f32) so host and device layouts match at 16-byte boundaries.", "Added a startup assertion comparing the byte length of the staging ArrayBuffer against the WGSL struct stride." ], "learnings": [ "Never assume C-style tight packing for vec3 fields in WebGPU uniform buffers; always pad to 16-byte vec4 boundaries explicitly.", "Verify GPU buffer layouts with a known sentinel value in the last field of the uniform struct." ], "meditation": { "book": "Book VI", "verse": "Section 13", "location": "Written while debugging a skewed WebGPU frustum", "stoicConcept": "Metron (Measure and alignment)", "quote": "When the mason lays three stones where the arch demands four, the gap does not vanish; it pulls every course above it out of plumb.", "reflection": "Hardware reads by its own stride, not by our wishful counting. Respect the 16-byte boundary in the struct definition so no hidden gap shifts the frame." }, "userNote": "Explicitly pairing vec3f with a scalar f32 in every uniform struct made the CPU-to-GPU layout self-documenting." } ]diary.html71 KB1522067088beupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
DIARY.md8.6 KBd602ad008489upstream ↗
# Agent Diary · Τὰ εἰς ἑαυτόν (Engineering & Stoic Journal) > Distilled learnings, technical challenges, root-cause solutions, user reflections, and Marcus Aurelius meditations across AI agent sessions. ## [2026-10-05] `audio-worklet`: Zero-copy ring buffers in the WebAudio render quantum - **Session**: `demo-a10` · **Workspace**: `~/projects/audio-worklet` · **Virtue**: *Economy and Precision (Euteleia)* - **Summary**: Replaced structured-clone postMessage calls on the 128-frame audio thread with a lock-free SharedArrayBuffer ring buffer and Atomics read/write pointers. ### I. The obstacle (Challenges) - Allocating a new Float32Array inside process() triggered minor GC pauses every 40ms, causing audible clicks at 48kHz. - Passing PCM chunks over MessagePort cloned the underlying ArrayBuffer instead of transferring ownership. ### II. The fix (Solutions) - Pre-allocated a single SharedArrayBuffer ring buffer during processor initialization and updated read/write indices with Atomics.load and Atomics.store. - Added Cross-Origin-Opener-Policy and Cross-Origin-Embedder-Policy headers to enable SharedArrayBuffer in the local dev server. ### III. New learnings - Never allocate objects or typed arrays inside a 128-frame WebAudio process() callback; a 2.66ms budget leaves no room for garbage collection. - Use power-of-two ring buffer capacities so modulo wrapping reduces to a single bitwise AND (index & mask). ### IV. Ta Eis Heauton (Book IV, Section 24 · Apallage (Pruning the unnecessary)) > *"Ask yourself at every step: is this among the things that are necessary? Why copy the vessel when you can hand it across the threshold?"* Most real-time jitter comes from work we asked the runtime to do on every tick. Allocate once at the boundary and let the hot loop only move pointers. ### V. User's note *"Switching to a pre-allocated SharedArrayBuffer dropped worst-case callback time from 4.1ms to 0.08ms."* --- ## [2026-10-03] `sqlite-wal`: Preventing WAL starvation under continuous reader load - **Session**: `demo-b20` · **Workspace**: `~/projects/sqlite-wal` · **Virtue**: *Temperance and Proportion (Sophrosyne)* - **Summary**: Fixed unbounded .sqlite-wal file growth caused by leaked read transactions holding snapshot locks across async HTTP streams. ### I. The obstacle (Challenges) - The write-ahead log grew past 4GB under steady traffic even though PRAGMA wal_autocheckpoint was set to 1000 pages. - A single long-lived SSE connection kept an open read statement cursor, preventing SQLite from advancing the checkpoint mark. ### II. The fix (Solutions) - Materialized query rows into memory before starting the SSE stream and finalized the prepared statement immediately in a finally block. - Scheduled periodic PASSIVE checkpoints with a fallback to TRUNCATE during low-traffic windows. ### III. New learnings - SQLite WAL checkpoints cannot overwrite pages needed by the oldest active read transaction; one unclosed cursor blocks reclamation for the entire database. - Keep database transactions strictly shorter than network I/O streams. ### IV. Ta Eis Heauton (Book V, Section 23 · Panta Rhei (Nothing stands still)) > *"Time is a river of passing events, and strong is its current; no sooner is a thing brought to sight than it is swept by and another takes its place."* A snapshot is meant to be read and released. When a reader clings to an old view of the world while new writes pour in, the ledger swells until the disk itself gives way. ### V. User's note *"Closing the cursor before opening the SSE response stream kept the WAL file under 4MB all week."* --- ## [2026-09-29] `wasm-simd`: Fixing unaligned SIMD loads and NaN propagation in cosine similarity - **Session**: `demo-c30` · **Workspace**: `~/projects/wasm-simd` · **Virtue**: *Truthfulness (Aletheia)* - **Summary**: Tracked down silent NaN scores in the WebAssembly f32x4 dot-product kernel to unpadded tail vectors and zero-norm embeddings. ### I. The obstacle (Challenges) - Queries with dimension counts not divisible by 4 read past the end of the embedding slice into adjacent heap bytes, producing sporadic NaN scores. - Zero vectors divided 0.0 by 0.0 during L2 normalization and poisoned the top-k heap comparator. ### II. The fix (Solutions) - Processed the main body in 4-wide f32x4 lanes and handled the remainingdimension % 4 elements in a scalar tail loop. - Guarded the reciprocal square root with an epsilon check (normSq > 1e-12) before multiplying. ### III. New learnings - A single NaN in a binary min-heap breaks the total ordering invariant because both NaN < x and NaN > x evaluate to false. - Always test SIMD kernels with prime-length inputs (e.g. 381 or 1539 elements) to exercise the scalar remainder path. ### IV. Ta Eis Heauton (Book III, Section 11 · Hypolepsis (Testing impressions)) > *"Examine the thing itself in its own nature, bare and separate from all that borders it, and tell yourself its proper name."* Four lanes march together cleanly until the road narrows at the boundary. If you read four floats where only three were written, the fourth is a stranger that corrupts the whole sum. ### V. User's note *"Adding a property test with prime vector lengths caught the tail-read bug in 12ms."* --- ## [2026-09-24] `raft-kv`: Split-vote livelock and fsync ordering before RequestVote replies - **Session**: `demo-d40` · **Workspace**: `~/projects/raft-kv` · **Virtue**: *Courage and Exactness (Andreia)* - **Summary**: Resolved a 3-node election livelock under symmetric network delay and moved term/votedFor disk persistence ahead of RPC response transmission. ### I. The obstacle (Challenges) - All three nodes initialized their pseudo-random election timers from the same millisecond timestamp in container tests, causing repeated split votes. - Nodes sent RequestVote responses before flushing votedFor to disk, allowing a crashed-and-restarted node to vote twice in the same term. ### II. The fix (Solutions) - Seeded each node's jitter generator from OS entropy and widened the election timeout window to 150ms-300ms. - Enforced fdatasync on the metadata log before enqueueing outbound RequestVote or AppendEntries packets. ### III. New learnings - In Raft, persisting currentTerm and votedFor before replying is a safety invariant, not an optimization; skipping fsync allows two leaders in one term. - Deterministic simulation tests should inject distinct per-node seeds so timers do not lockstep. ### IV. Ta Eis Heauton (Book VII, Section 55 · Katalepsis (Firm grasp of state)) > *"Do not give your assent before the record is fixed in stone; a promise spoken to the wind and forgotten on waking divides the city against itself."* A node that forgets whom it voted for after a reboot betrays the quorum. Write the vow to durable storage before you send the messenger out the gate. ### V. User's note *"Running 1,000 simulated crash-recovery cycles with randomized packet drops passed with zero double-votes."* --- ## [2026-09-18] `shader-pipeline`: WGSL uniform struct alignment and 16-byte vec3f padding traps - **Session**: `demo-e50` · **Workspace**: `~/projects/shader-pipeline` · **Virtue**: *Practical Wisdom (Phronesis)* - **Summary**: Fixed garbled camera matrices in the WebGPU compute pass caused by a 12-byte vec3f field shifting the following float in the host Float32Array. ### I. The obstacle (Challenges) - In WGSL uniform address space, vec3<f32> has a size of 12 bytes but an alignment of 16 bytes, which shifted every subsequent struct member by 4 bytes when packed from JS. - The pipeline compiled without warnings while reading the wrong byte offsets for projection matrix columns. ### II. The fix (Solutions) - Paired each vec3<f32> field with an explicit scalar f32 parameter (cameraPos: vec3f, exposure: f32) so host and device layouts match at 16-byte boundaries. - Added a startup assertion comparing the byte length of the staging ArrayBuffer against the WGSL struct stride. ### III. New learnings - Never assume C-style tight packing for vec3 fields in WebGPU uniform buffers; always pad to 16-byte vec4 boundaries explicitly. - Verify GPU buffer layouts with a known sentinel value in the last field of the uniform struct. ### IV. Ta Eis Heauton (Book VI, Section 13 · Metron (Measure and alignment)) > *"When the mason lays three stones where the arch demands four, the gap does not vanish; it pulls every course above it out of plumb."* Hardware reads by its own stride, not by our wishful counting. Respect the 16-byte boundary in the struct definition so no hidden gap shifts the frame. ### V. User's note *"Explicitly pairing vec3f with a scalar f32 in every uniform struct made the CPU-to-GPU layout self-documenting."* ---docs/index.html71 KB1522067088beupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
hooks/hooks.json137 B001b6a33d142upstream ↗
{ "description": "In-terminal Stoic engineering diary pane, live turn observer, and /diary commands", "modules": ["./register.js"] }hooks/register.js14 KB76adb0d616cbupstream ↗
const PANE_ID = 'agent-diary'; const DIARY_JSON_PATH = 'data/diary-entries.json'; const FALLBACK_ENTRIES = [ { id: 'entry-2026-10-05-audio-worklet', date: '2026-10-05', project: 'audio-worklet', title: 'Zero-copy ring buffers in the WebAudio render quantum', virtue: 'Temperance and Proportion (Sophrosyne)', challenges: [ 'The UI showed Render Complete, but the exported MP4 had no captions because the canvas overlay was not passed into the FFmpeg WASM filtergraph.', 'Portrait screen recordings (484x1080) rendered 54px captions that clipped horizontally.' ], solutions: [ 'Mounted the subtitle file in the FFmpeg WASM pass and extracted a PNG frame after export to verify the pixels.', 'Scaled subtitle font size by Math.min(outW, outH) / 480 with line wrapping.' ], learnings: [ 'Scale video overlay text against min(width, height) rather than height alone.', 'Inspect an extracted frame on disk before trusting a Render Complete badge.' ], meditation: { book: 'Book IV', verse: 'Section 19', stoicConcept: 'Metron (Measure and proportion)', quote: 'The herald cries that the work is finished, yet the stone has no inscription. Measure both dimensions of the column before you carve.', reflection: 'Do not assume a job succeeded because a function returned without throwing. Verify the artifact on disk.' }, userNote: 'Testing on a real 484x1080 mobile recording caught the height-only font scaling bug right away.' }, { id: 'entry-2026-10-03-sqlite-wal', date: '2026-10-03', project: 'sqlite-wal', title: 'Preventing WAL starvation under continuous reader load', virtue: 'Truthfulness (Aletheia)', challenges: [ 'Chrome SQLite visits table was empty when History Sync was off, causing the dashboard to show fake fallback numbers.' ], solutions: [ 'Built a pure-Node Snappy decompressor to read Chromium Local Extension Settings LevelDB (.ldb) files directly.' ], learnings: [ 'Never ship silent mock fallback data when a parser fails; surface the empty state so the root cause gets fixed.' ], meditation: { book: 'Book III', verse: 'Section 11', stoicConcept: 'Hypolepsis (Testing impressions)', quote: 'Strip away the painted mask and examine the thing itself: is this gold from the mine, or brass coined in your own workshop to quiet a question?', reflection: 'A blank screen is honest and makes you find the real data source. A fake chart hides the bug.' }, userNote: 'Reading the Snappy-compressed .ldb files directly gave us the exact per-domain seconds.' } ]; let entries = FALLBACK_ENTRIES.slice(); let notes = []; let activeTab = 'entries'; let selectedIndex = 0; let meditationIndex = 0; let showBanner = false; let turnTools = 0; let turnObstacles = 0; let lastObstacleTool = ''; let diaryJsonPath = DIARY_JSON_PATH; function applyParsedEntries(raw) { try { const parsed = JSON.parse(raw); if (Array.isArray(parsed) && parsed.length > 0) { entries = parsed; if (selectedIndex >= entries.length) { selectedIndex = 0; } } } catch { // Keep existing entries if JSON parsing fails. } } function buildNoteRecord(text) { const trimmed = String(text || '').trim(); if (!trimmed) { return null; } const target = entries[selectedIndex] || entries[0]; const record = { date: new Date().toISOString().slice(0, 10), project: target ? target.project : 'session', entryId: target ? target.id : 'custom', text: trimmed }; notes = [record, ...notes.slice(0, 19)]; if (target) { target.userNote = trimmed; } return record; } export function register(on) { on('session.start', async ($, e, next) => { try { const home = await $.env.get('HOME'); if (home) { diaryJsonPath = home + '/.agent-diary/diary-entries.json'; } } catch { // Keep default relative path in sandboxed environments. } const savedNotes = await $.store.get('notes'); if (Array.isArray(savedNotes)) { notes = savedNotes; } const savedBanner = await $.store.get('showBanner'); if (typeof savedBanner === 'boolean') { showBanner = savedBanner; } try { const raw = await $.fs.read(diaryJsonPath); applyParsedEntries(raw); } catch { // Keep fallback entries in sandboxed environments. } try { await $.command.register({ name: 'diary', description: 'Open the Stoic Agent Diary pane in Claude Code', immediate: true }); await $.command.register({ name: 'diary-open', description: 'Open the full HTML Agent Diary in your browser', immediate: true }); await $.command.register({ name: 'diary-note', description: 'Save a personal reflection note to your Agent Diary', argumentHint: '<reflection>', immediate: true }); } catch { // Ignore duplicate command registration errors on reload. } return next(e); }); on('command.run', { command: 'diary' }, async ($) => { try { const raw = await $.fs.read(diaryJsonPath); applyParsedEntries(raw); } catch { // Keep existing entries. } await $.ui.open({ id: PANE_ID, title: 'Agent Diary (Ta Eis Heauton)', focus: true, closeOnEscape: true }); return {}; }); on('command.run', { command: 'diary-open' }, async ($) => { try { await $.process.run(['agent-diary', 'open']); $.ui.toast('Opened diary.html in your browser'); } catch { $.ui.toast('Run: agent-diary open'); } return {}; }); on('command.run', { command: 'diary-note' }, async ($, e) => { const record = buildNoteRecord(e.args); if (!record) { activeTab = 'write'; await $.ui.open({ id: PANE_ID, title: 'Agent Diary (Ta Eis Heauton)', focus: true, closeOnEscape: true }); return {}; } await $.store.set('notes', notes); try { await $.fs.write(diaryJsonPath, JSON.stringify(entries, null, 2)); } catch { // Ignore write failures in sandboxed environments. } $.ui.invalidate('ui.render'); return { text: 'Saved personal reflection to Agent Diary (' + record.project + '): "' + record.text + '"' }; }); on('tool.call', async ($, e, next) => { const result = await next(e); turnTools += 1; if (result && result.isError) { turnObstacles += 1; lastObstacleTool = e.tool || 'tool'; } $.ui.invalidate('ui.render'); return result; }); on('turn.complete', async ($, e, next) => { try { await $.process.run(['agent-diary', 'sync']); const raw = await $.fs.read(diaryJsonPath); applyParsedEntries(raw); } catch { // Ignore background hook errors in sandboxed environments. } $.ui.invalidate('ui.render'); return next(e); }); on('ui.render', { component: 'Spinner' }, async ($, e, next) => { const suffix = turnObstacles > 0 ? ' | diary: ' + turnObstacles + ' obstacle(s) via ' + lastObstacleTool : ' | diary: ' + entries.length + ' entries'; return next({ ...e, props: { ...e.props, suffix } }); }); on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => { if (!showBanner) { return next(e); } const { Box, Text } = $.ui.resolve(e); const current = entries[meditationIndex] || entries[0]; const med = current && current.meditation ? current.meditation : FALLBACK_ENTRIES[0].meditation; return Box({ borderStyle: 'round', borderColor: 'yellow', paddingX: 1, flexDirection: 'row', columnGap: 1, children: [ Text({ bold: true, color: 'yellow', children: ['[' + med.book + ' ' + med.verse + ']'] }), Text({ dimColor: true, children: [med.quote] }) ] }); }); on('ui.render', { component: 'Pane' }, async ($, e, next) => { if (e.requestId !== PANE_ID) { return next(e); } const { Box, Text, Button, Input, Markdown } = $.ui.resolve(e); const entry = entries[selectedIndex] || entries[0]; const medEntry = entries[meditationIndex] || entry; const med = medEntry && medEntry.meditation ? medEntry.meditation : FALLBACK_ENTRIES[0].meditation; const navBar = Box({ flexDirection: 'row', columnGap: 3, children: [ Button({ key: 'tab-entries', label: 'Entries (' + entries.length + ')', hotkey: '1', plain: true, dimColor: activeTab !== 'entries', onPress: () => { activeTab = 'entries'; $.ui.invalidate('ui.render'); } }), Button({ key: 'tab-meditations', label: 'Meditations', hotkey: '2', plain: true, dimColor: activeTab !== 'meditations', onPress: () => { activeTab = 'meditations'; $.ui.invalidate('ui.render'); } }), Button({ key: 'tab-write', label: 'Write Note (' + notes.length + ')', hotkey: '3', plain: true, dimColor: activeTab !== 'write', onPress: () => { activeTab = 'write'; $.ui.invalidate('ui.render'); } }), Button({ key: 'toggle-banner', label: 'Stoic Banner: ' + (showBanner ? 'ON' : 'OFF'), hotkey: 'b', plain: true, dimColor: !showBanner, onPress: async () => { showBanner = !showBanner; await $.store.set('showBanner', showBanner); $.ui.invalidate('ui.render'); } }), Button({ key: 'open-html', label: 'Open HTML', hotkey: 'o', plain: true, onPress: async () => { try { await $.process.run(['agent-diary', 'open']); $.ui.toast('Opened diary.html in your browser'); } catch { $.ui.toast('Run: agent-diary open'); } } }) ] }); let bodyChildren = []; if (activeTab === 'entries' && entry) { const entryMarkdown = [ '## ' + (selectedIndex + 1) + '/' + entries.length + ' · `' + entry.project + '` (' + entry.date + ')', '', '**' + entry.title + '** (' + (entry.virtue || 'Practical Wisdom') + ')', '', '### Obstacles', '', ...(entry.challenges || []).slice(0, 3).map((c) => '- ' + c), '', '### Fixes', '', ...(entry.solutions || []).slice(0, 3).map((s) => '- ' + s), '', '### Takeaways', '', ...(entry.learnings || []).slice(0, 3).map((l) => '- ' + l), '', entry.userNote ? '> Personal note: ' + entry.userNote : '> No personal note yet. Press `3` to add one.' ].join('\n'); bodyChildren = [ Markdown({ text: entryMarkdown }), Box({ flexDirection: 'row', columnGap: 2, children: [ Button({ key: 'prev-entry', label: 'Previous Entry', hotkey: 'p', onPress: () => { selectedIndex = (selectedIndex - 1 + entries.length) % entries.length; meditationIndex = selectedIndex; $.ui.invalidate('ui.render'); } }), Button({ key: 'next-entry', label: 'Next Entry', hotkey: 'n', onPress: () => { selectedIndex = (selectedIndex + 1) % entries.length; meditationIndex = selectedIndex; $.ui.invalidate('ui.render'); } }) ] }) ]; } else if (activeTab === 'meditations') { const medMarkdown = [ '## ' + med.book + ', ' + med.verse + ' (' + (med.stoicConcept || 'Ta Eis Heauton') + ')', '', '> ' + med.quote, '', med.reflection || '', '', 'Source session: `' + (medEntry ? medEntry.project : 'session') + '` (' + (medEntry ? medEntry.date : '') + ')' ].join('\n'); bodyChildren = [ Markdown({ text: medMarkdown }), Box({ flexDirection: 'row', columnGap: 2, children: [ Button({ key: 'draw-lot', label: 'Draw Another Stoic Lot', hotkey: 'm', onPress: () => { meditationIndex = (meditationIndex + 1) % entries.length; $.ui.invalidate('ui.render'); } }) ] }) ]; } else { const notesMarkdown = notes.length > 0 ? [ '### Recent notes saved from Claude Code', '', ...notes.slice(0, 5).map((n) => '- **' + n.date + '** (`' + n.project + '`): ' + n.text) ].join('\n') : '> No notes saved in this workspace store yet.'; bodyChildren = [ Markdown({ text: '## Attach a personal note\n\nTarget entry: `' + (entry ? entry.project : 'session') + '` - **' + (entry ? entry.title : 'current session') + '**' }), Input({ key: 'diary-note-input', label: 'Reflection', placeholder: 'What bug, fix, or lesson stood out today? Press Enter to save', value: '', submitLabel: 'save', onSubmit: async (val) => { const record = buildNoteRecord(val); if (record) { await $.store.set('notes', notes); try { await $.fs.write(diaryJsonPath, JSON.stringify(entries, null, 2)); } catch { // Ignore write failures in sandboxed environments. } $.ui.toast('Saved note to Agent Diary'); $.ui.invalidate('ui.render'); } } }), Markdown({ text: notesMarkdown }) ]; } const footer = Text({ dimColor: true, children: [ 'Session telemetry: ' + turnTools + ' tool call(s), ' + turnObstacles + ' obstacle(s) | Keys: 1/2/3 tabs, n/p cycle, m lot, b banner, o browser, Esc close' ] }); return Box({ flexDirection: 'column', children: [ navBar, Text({ children: [' '] }), ...bodyChildren, Text({ children: [' '] }), footer ] }); }); }LICENSE1.1 KB0ac06d77a36bupstream ↗
MIT License Copyright (c) 2026 Hemanth HM <[email protected]> (https://h3manth.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.package.json770 Bdbd54db1135aupstream ↗
{ "name": "agent-diary", "version": "0.2.0", "description": "Harvest learnings, challenges, and solutions across AI agent sessions into a Marcus Aurelius HTML diary and Claude Code Mod pane.", "type": "module", "bin": { "agent-diary": "./bin/agent-diary.mjs", "agent-diary-harvest": "./scripts/harvest.mjs", "agent-diary-build": "./scripts/build-diary.mjs" }, "scripts": { "harvest": "node ./scripts/harvest.mjs", "sync": "node ./scripts/auto-hook.mjs", "build": "node ./scripts/build-diary.mjs", "open": "node ./scripts/build-diary.mjs --open", "validate": "claude plugin validate . --strict", "test": "claude plugin test" }, "author": "Hemanth HM <[email protected]> (https://h3manth.com)", "license": "MIT" }resources/template.html60 KBb68588abf5ebupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
tests/agent-diary.test.ts3.3 KB800e2393281bupstream ↗
import { expect, test } from 'claude-code/testing'; const PANE = { plugin: 'agent-diary', component: 'Pane', requestId: 'agent-diary', viewport: { columns: 120, rows: 36 }, props: { title: 'Agent Diary (Ta Eis Heauton)', isFocused: true, bodyColumns: 80, placement: 'inline', scroll: { offset: 0, bodyRows: 24 }, view: {} } } as const; test('/diary opens the Agent Diary pane and registers commands on session.start', async ($, on) => { const registered: string[] = []; let openedPaneId = ''; on('session.start', () => ({ cwd: '/work/agent-diary' })); on('env.get', () => ({ value: '/work' })); on('store.get', () => ({ value: undefined })); on('fs.read', () => ({ deny: 'no file in test' })); on('command.register', ($, e) => { registered.push(e.name); return { value: undefined }; }); on('ui.open', ($, e) => { openedPaneId = e.id; return { value: { isPlaced: true } }; }); await $.session.start({ surface: 'terminal', isInteractive: true, cwd: '/work/agent-diary' }); expect(registered).toEqual(['diary', 'diary-open', 'diary-note']); await $.command.run({ command: 'diary', args: '' }); expect(openedPaneId).toBe('agent-diary'); }); test('Agent Diary pane renders tabs, cycles meditations, and saves personal notes', async ($, on) => { const saved = new Map<string, unknown>(); on('store.get', ($, e) => ({ value: saved.get(e.key) })); on('store.set', ($, e) => { saved.set(e.key, e.value); return { value: undefined }; }); on('fs.write', () => ({ value: undefined })); on('ui.toast', () => ({ value: undefined })); for (const surface of ['terminal', 'desktop'] as const) { const ui = await $.ui.mount({ ...PANE, surface }); // Switch to Tab 1 (Entries) and check the active entry await ui.press({ key: 'tab-entries' }); expect(await ui.find({ type: 'Markdown', text: /audio-worklet/ })).toBeDefined(); // Switch to Tab 2 (Meditations) and draw another Stoic lot await ui.press({ key: 'tab-meditations' }); expect(await ui.find({ type: 'Markdown', text: /Book (IV|III)/ })).toBeDefined(); await ui.press({ key: 'draw-lot' }); expect(await ui.find({ type: 'Markdown', text: /Book (IV|III)/ })).toBeDefined(); // Switch to Tab 3 (Write Note) and submit a personal reflection await ui.press({ key: 'tab-write' }); await ui.input({ key: 'diary-note-input', text: 'Verified portrait scaling in test' }); expect(await ui.find({ type: 'Markdown', text: /Verified portrait scaling in test/ })).toBeDefined(); await ui.unmount(); } const notes = saved.get('notes') as Array<{ text: string }>; expect(notes).toBeDefined(); expect(notes[0].text).toBe('Verified portrait scaling in test'); }); test('tool.call tracks obstacles and /diary-note saves reflections directly', async ($, on) => { const saved = new Map<string, unknown>(); on('store.set', ($, e) => { saved.set(e.key, e.value); return { value: undefined }; }); on('fs.write', () => ({ value: undefined })); on('tool.call', () => ({ result: 'Command failed', isError: true })); await $.tool.call({ tool: 'Bash', command: 'false' }); const reply = await $.command.run({ command: 'diary-note', args: 'Checked exit code before trusting build output' }); expect(reply.text).toMatch(/Checked exit code before trusting build output/); });
Plain-text copy, no login: /skill-bundles/hemanth-agent-diary.md