SLOPSHOPPER

agent-kevin

Test harness for this plugin's mods: `claude plugin test mods`. Never installed; the plugin loads mods/hooks/register.ts through hooks/claude.json.

bandguardcommandtoastprompttool
★ 2v0.0.0Apache-2.0updated 2026-10-26AgentLayer1/agent-kevin/mods
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · agent-kevin
› fix the failing auth test and add an audit log call ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM › /manuals ⎿ agent-kevin: No repo instructions attached yet. Session preview-session [ Copy ] [ Dismiss ] ⟨Claude Code's own drawing⟩ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
Session preview-session [ Copy ] [ Dismiss ] ⟨Claude Code's own drawing⟩
README

<img src="assets/kevin-avatar.jpg" alt="Kevin" width="180" />

Agent Kevin 🍌

Your personal AI assistant, as a Claude Code or Codex plugin. One markdown folder, one plugin, a brain that learns who you are session after session.

<a href="https://agentlayer.one/docs"><img src="https://img.shields.io/badge/Docs-agentlayer.one-5EFFA1.svg" alt="Documentation"/></a>&nbsp; <a href="./LICENSE"><img src="https://img.shields.io/badge/License-Apache_2.0-blue.svg" alt="License"/></a>&nbsp; <a href="https://docs.claude.com/en/docs/claude-code"><img src="https://img.shields.io/badge/Claude_Code-plugin-orange.svg" alt="Claude Code plugin"/></a>&nbsp; <a href="https://developers.openai.com/codex"><img src="https://img.shields.io/badge/Codex-plugin-black.svg" alt="Codex plugin"/></a>&nbsp; <a href="https://agentlayer.one/docs/about/platforms"><img src="https://img.shields.io/badge/macOS-tested-success.svg" alt="macOS tested"/></a>&nbsp; <a href="https://agentlayer.one"><img src="https://img.shields.io/badge/Made_by-AgentLayer-blueviolet.svg" alt="Made by AgentLayer"/></a>

Read the docs →


What is Kevin?

Kevin is a portable, file-based personal AI assistant that plugs into the agent CLI you already use, Claude Code or OpenAI Codex. Everything that makes Kevin Kevin (personality, memory, knowledge, projects, tasks) lives in your own directory as plain markdown. Any AI can read it. You can browse it in Obsidian or Finder. If you ever want to leave, you take the folder and go.

It is not a chat wrapper. It is an operating system for personal AI:

  • A 59-tool MCP server for tasks, knowledge compilation, reports, home history, worktrees, database queries, GitHub review, search, page speed, a bundled browser, and Google Search Console.
  • A 33-skill library, related work grouped into one skill with playbooks (briefing, goals, SEO, focus, engineering), covering onboarding, version history, project lifecycle, a daily focus view with standup and a session radar, goals from the day to the year, morning and evening briefings, tax deadlines and bookkeeping, a support queue pulse and reply drafts, trip planning, worktree setup, API-request drafting, read-only SEO auditing, and audio and video transcripts and summaries.
  • A knowledge pipeline that turns every conversation into structured, queryable memory.
  • Opt-in packs (SEO, Browser, Database, GitHub, API, Xcode, Helpdesk, App Store) and a bridge to community skill libraries via skills.sh.
  • You drive. Ask in plain words and Kevin picks the skill and playbook; nothing runs unasked, and you never have to remember a command.
graph LR
    A[Sessions] -->|capture| B[Knowledge]
    B -->|informs| C[Projects]
    C -->|generate| D[Results]
    D -->|feed back into| A

Every session is captured on exit. Captured sessions compile into a wiki. The wiki loads before you type a word in the next session. That loop is the whole product.

Kevin is named after the loyal minion. Helpful, enthusiastic, a little nerdy.


Quick start

You need Bun ≥ 1.1, Git, and a host: Claude Code or Codex. Full prerequisites, the local clone install, and Windows notes are in Install.

Pick a home for the brain, then install the plugin from it:

mkdir -p ~/Documents/Agents/Kevin && cd ~/Documents/Agents/Kevin
Claude CodeCodex
claude, then /plugin install agent-kevin --marketplace AgentLayer1/agentlayer-agent-marketplacecodex plugin marketplace add AgentLayer1/agentlayer-agent-marketplace then codex plugin add agent-kevin@agentlayer
Relaunch and run /agent-kevin:initCreate the home from Claude Code, then open it with codex and run $upgrade once
Skills: /agent-kevin:<skill>Skills: $<skill>

Five minutes of questions later you have a home. See Onboarding and Hosts.

Want a head start? The wizard turns eleven prompts about your company into a seed bundle; hand the zip to init and the agent wakes up named, characterised, and briefed. A teammate's seed export does the same from an existing agent. → Seed bundles

Always launch from the agent home. The plugin loads only for sessions started there, and that is also what keeps several agents on one machine apart. Reach your code through permissions.additionalDirectories in the home's .claude/settings.local.json (init writes it there, since the path is this machine's), not by launching from a repo.


Documentation

This README is the short version. Everything lives at agentlayer.one/docs, also served as llms-full.txt for models.

SectionStart with
Getting startedInstall · Onboarding · Your first session · Updating
DashboardToday · Tasks and projects · Sessions · Brain · Reports and scheduler · Capabilities · Persona and system
PlatformThe agent home · The brain · Capture · Sync · History · Self-evolution · Seed bundles · Multiple agents
AgentHosts · Claude Code · Codex · Hooks · Configuration · Tasks · Daily rhythm · Architecture
ModulesPlan and run · Build and ship · Reach and see · Brain and memory · Skills · MCP tools · Second-model review · Browser · SEO · Accounts
EngineeringThe engineer skill · Principles · Design and review · Pull requests · Worktrees · Specs and plans · Coding rules · Verification · API collections · Releases
ReferenceCLI · Upgrades · Naming · Changelog
WorkstationThe rig: Ghostty · cmux · editor and tools
AboutPrivacy · Platforms · FAQ · History · Contributing

Highlights

<img src="assets/dashboard.png" alt="Kevin Agent OS dashboard" width="720" />

  • Memory that compounds. Hooks capture every session; the knowledge-compile skill distils them into user facets, concept articles, and active memory that load next launch. → The brain
  • Projects, not just chats. One markdown file per task with frontmatter, threads, and a generated dashboard. → Tasks
  • A focus page for the day. The focus skill keeps today to three, shows what carried over and what the roadmap has in flight, and the goals skill sets the day, week, month and year with you; one page for all your work and one per project. → Daily rhythm
  • One pass to bring everything current. The sync skill runs compile → lint → flywheel → dashboards and ends with a next move. → Sync
  • Every change can be undone. The history skill turns on local version history for the home in one question, no git knowledge needed; sync saves a snapshot each run. A home in iCloud, Dropbox or OneDrive keeps its history in ~/.local/state (%LOCALAPPDATA% on Windows), where syncing can't damage it. → History
  • A mission-control page regenerated on every sync, self-contained, zero external requests. → Dashboard
  • Engineering by playbook. The engineer skill routes code work to a playbook (bug fix, feature, refactor, performance, forensics, prototype, and more) backed by 23 named principles, proves the result on the running artifact, and strips comments before you see the diff. → Engineering
  • Pull requests, three ways. Review a teammate's PR with verified findings and paste-ready comments, prep to present your own, or brief a second model on your branch and have its findings verified, fixed, and committed on one dossier. → Pull requests
  • Multiple homes, multiple personas. One plugin install, separate brains, told apart by the launch folder. → Multiple agents
  • Hand an agent to a teammate. A seed bundle carries persona, curated knowledge, and setup with fork semantics; credentials travel as names only. → Seed bundles
  • Subscription-billed. The MCP server returns prompts; your session does the thinking on your host's plan. → Hosts
  • Private by construction. Secrets in a deny-gated store Kevin cannot read, transcripts redacted before they persist. → Privacy

Updating

Pull the new plugin version on your host (/plugin update agent-kevin@agentlayer in Claude Code; remove and re-add in Codex), then run the upgrade skill. The plugin update refreshes code; upgrade reconciles your home from the CHANGELOG's Upgrade blocks, backing up first. → Updating · Upgrades and releases


Contributing

Pull requests welcome: new opt-in packs, read-mostly MCP tools, platform hardening, docs. Open an issue first for architectural changes; Kevin's contract with the markdown home is intentional. See CONTRIBUTING.md.

License

Licensed under the Apache License, Version 2.0. agent-kevin is © AgentLayer · agentlayer.one. See NOTICE for the attribution stanza. Third-party skill libraries installed via the configure-skills skill are not bundled and carry their own licenses.


<a href="https://agentlayer.one"><img src="assets/agentlayer-logo.png" alt="AgentLayer" height="40" /></a>

Built by AgentLayer · agentic infrastructure for AI-native operations

Source 17 files
hooks/register.ts 20 lines
1import type { Register } from 'claude-code';
2
3import { registerCommands } from '../commands/commands';
4import { registerManuals } from '../manuals/manuals';
5import { registerNotices } from '../notices/notices';
6import { registerQueue } from '../queue/queue';
7import { registerReports } from '../reports/reports';
8import { registerSetup } from '../setup/setup';
9import { registerSync } from '../sync/tracker';
10
11export const register: Register = (on) => {
12  registerManuals(on);
13  registerReports(on);
14  registerSync(on);
15  registerCommands(on);
16  registerNotices(on);
17  registerQueue(on);
18  registerSetup(on);
19};
20
commands/commands.tsx 207 lines
1import { atom, read, update } from 'claude-code';
2import type { EngineInterface, On } from 'claude-code';
3
4import type { AgendaItem, TodayView } from '../types';
5
6import { COMMANDS_FEATURE } from '../shared/catalog';
7import { cliArgv, cliError } from '../shared/cli';
8import { doneSuggestions, isDoneArgument } from './done';
9import type { TaskFrontmatter } from './today';
10import { STALE_SYNC_HOURS, buildToday, formatAge, parseEmoji, summarize } from './today';
11
12const todayBand = atom({ plugin: 'agent-kevin', key: 'todayBand' } as const, null);
13const sessionBand = atom({ plugin: 'agent-kevin', key: 'sessionBand' } as const, null);
14const TASKS_FRESH_MS = 60_000;
15const PRIORITY_COLORS: Record<string, string> = { P0: 'red', P1: 'yellow' };
16
17// The read itself is cached, so keystrokes that land before it finishes share it.
18let doneTasks: { readAt: number; tasks: Promise<TaskFrontmatter[]> } | undefined;
19
20// The session root, not its cwd: a shell `cd` in a turn moves the cwd out of the home.
21async function runCli($: EngineInterface, args: readonly string[]): Promise<string> {
22  const { exitCode, stdout, stderr } = await $.process.run(cliArgv($.plugin.root, $.plugin.name, args), {
23    cwd: await $.session.root()
24  });
25  if (exitCode !== 0) {
26    throw cliError(stderr, args, exitCode);
27  }
28  return stdout;
29}
30
31async function readTasks($: EngineInterface): Promise<TaskFrontmatter[]> {
32  return JSON.parse(await runCli($, ['task', 'query'])) as TaskFrontmatter[];
33}
34
35async function captureAs($: EngineInterface, kind: 'inbox' | 'feedback', text: string) {
36  if (!text.trim()) {
37    return { text: `Usage: /${kind === 'inbox' ? 'capture' : 'lesson'} <text>` };
38  }
39  const result = JSON.parse(await runCli($, ['capture', text, `--kind=${kind}`])) as {
40    relPath: string;
41    duplicate: boolean;
42  };
43  return { text: result.duplicate ? `Already captured: ${result.relPath}` : `Saved to ${result.relPath}` };
44}
45
46async function todayView($: EngineInterface): Promise<TodayView> {
47  const { home, data, timezone } = JSON.parse(await runCli($, ['ping'])) as {
48    home: string;
49    data: string;
50    timezone: string;
51  };
52  const [tasks, syncedAt, identityText, now] = await Promise.all([
53    readTasks($),
54    $.fs
55      .read(`${data}/cadence.json`)
56      .then((text) => (JSON.parse(text) as { sync?: string }).sync)
57      .catch(() => undefined),
58    $.fs.read(`${home}/IDENTITY.md`).catch(() => ''),
59    $.clock.now()
60  ]);
61  return buildToday({ emoji: parseEmoji(identityText), timezone, tasks, syncedAt, now });
62}
63
64export const registerCommands = (on: On): void => {
65  on('session.start', async ($, e, next) => {
66    await Promise.all(COMMANDS_FEATURE.commands.map((command) => $.command.register(command)));
67    return next(e);
68  });
69
70  on('command.run', { command: 'capture' }, ($, e) => captureAs($, 'inbox', e.args));
71
72  on('command.run', { command: 'lesson' }, ($, e) => captureAs($, 'feedback', e.args));
73
74  on('command.run', { command: 'done' }, async ($, e) => {
75    const id = e.args.trim();
76    if (!id) {
77      return { text: 'Usage: /done <task-id>' };
78    }
79    await runCli($, ['task', 'close', id]);
80    doneTasks = undefined;
81    return { text: `Closed ${id}` };
82  });
83
84  on('prompt.autocomplete', async ($, e, next) => {
85    if (!isDoneArgument(e.text.slice(0, e.start))) {
86      return next(e);
87    }
88    const [result, now] = await Promise.all([next(e), $.clock.now()]);
89    if (doneTasks === undefined || now - doneTasks.readAt > TASKS_FRESH_MS) {
90      doneTasks = { readAt: now, tasks: readTasks($).catch((): TaskFrontmatter[] => []) };
91    }
92    return { suggestions: [...result.suggestions, ...doneSuggestions(await doneTasks.tasks, e.token)] };
93  });
94
95  // Claude reads the one-line summary; the person sees the agenda in the band until they dismiss it.
96  on('command.run', { command: 'today' }, async ($) => {
97    const view = await todayView($).catch((error: unknown) => (error instanceof Error ? error.message : String(error)));
98    if (typeof view === 'string') {
99      return { text: `Couldn't read today's state: ${view}` };
100    }
101    await update($, todayBand, () => view);
102    return { context: [summarize(view)] };
103  });
104
105  on('command.run', { command: 'session' }, async ($) => {
106    const id = await $.session.id();
107    await update($, sessionBand, () => id);
108    return { context: [`Session id: ${id}`] };
109  });
110
111  // A /clear or a resume starts another conversation in the same process.
112  on('session.end', { reason: ['clear', 'resume'] }, async ($, e, next) => {
113    await Promise.all([update($, todayBand, () => null), update($, sessionBand, () => null)]);
114    return next(e);
115  });
116
117  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
118    const below = await next(e);
119    const id = await read($, sessionBand);
120    if (id === null || e.props.hasSurvey) {
121      return below;
122    }
123    const { Box, Button, Text } = $.ui.resolve(e);
124    return (
125      <Box flexDirection="column">
126        <Box gap={1}>
127          <Text bold>Session</Text>
128          <Text>{id}</Text>
129          <Box marginLeft={2} gap={2}>
130            <Button
131              key="session:copy"
132              label="Copy"
133              onPress={async (press) => {
134                const copied = await $.ui.copy({ text: id, surface: press.surface });
135                $.ui.toast(copied.isCopied ? 'Session id copied' : `Couldn't copy the session id (${copied.reason})`);
136              }}
137            />
138            <Button key="session:dismiss" dimColor label="Dismiss" onPress={() => update($, sessionBand, () => null)} />
139          </Box>
140        </Box>
141        {below}
142      </Box>
143    );
144  });
145
146  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
147    const below = await next(e);
148    const view = await read($, todayBand);
149    if (view === null || e.props.hasSurvey) {
150      return below;
151    }
152    const { Box, Button, Text } = $.ui.resolve(e);
153    const isStale = view.syncAgeHours === null || view.syncAgeHours >= STALE_SYNC_HOURS;
154    const idWidth = Math.max(0, ...[...view.overdue, ...view.dueToday].map((item) => item.id.length));
155    const row = (item: AgendaItem, isLate: boolean) => (
156      <Box key={item.id} paddingLeft={3}>
157        <Text dimColor>▸ </Text>
158        <Text color={PRIORITY_COLORS[item.priority]} dimColor={!PRIORITY_COLORS[item.priority]}>
159          {item.priority.padEnd(4)}
160        </Text>
161        <Text dimColor>{item.id.padEnd(idWidth + 2)}</Text>
162        <Box flexGrow={1} flexShrink={1}>
163          <Text wrap="truncate-end">{item.title}</Text>
164        </Box>
165        {isLate ? <Text color="red">{`  ${item.daysLate}d late`}</Text> : null}
166      </Box>
167    );
168    const section = (title: string, items: readonly AgendaItem[], isLate: boolean) =>
169      items.length ? (
170        <Box key={title} flexDirection="column" marginTop={1}>
171          <Box paddingLeft={2}>
172            <Text bold>{title}</Text>
173            <Text dimColor>{`  ${items.length}`}</Text>
174          </Box>
175          {items.map((item) => row(item, isLate))}
176        </Box>
177      ) : null;
178    return (
179      <Box flexDirection="column">
180        <Box gap={1}>
181          <Text>{view.emoji}</Text>
182          <Text bold>Today</Text>
183          <Text dimColor>
184            · {view.dateLabel} · {view.hijriLabel}
185          </Text>
186          <Box marginLeft={2}>
187            <Button key="today:dismiss" dimColor label="Dismiss" onPress={() => update($, todayBand, () => null)} />
188          </Box>
189        </Box>
190        {section('Overdue', view.overdue, true)}
191        {section('Due today', view.dueToday, false)}
192        {view.overdue.length + view.dueToday.length === 0 ? (
193          <Box marginTop={1} paddingLeft={2}>
194            <Text color="green">✓ nothing overdue or due today</Text>
195          </Box>
196        ) : null}
197        <Box marginTop={1} paddingLeft={2}>
198          <Text color={isStale ? 'yellow' : undefined} dimColor={!isStale}>
199            ⟳ {view.syncAgeHours === null ? 'never synced' : `last sync ${formatAge(view.syncAgeHours)}`}
200          </Text>
201        </Box>
202        {below}
203      </Box>
204    );
205  });
206};
207
manuals/manuals.tsx 288 lines
1import { atom, read, update } from 'claude-code';
2import type { EngineInterface, On, ToolCallResult } from 'claude-code';
3
4import { MANUALS_FEATURE } from '../shared/catalog';
5import { cliArgv } from '../shared/cli';
6import { TURN_REASONS } from '../shared/turns';
7import {
8  CLAUDE_FILES,
9  HOME_MARKERS,
10  MAX_IMPORT_HOPS,
11  dataDirNameIn,
12  expandHome,
13  foldersUpTo,
14  grantFor,
15  hasOwnContent,
16  importsIn,
17  isUnder,
18  manualContext,
19  normalize,
20  parentOf,
21  pathsInCommand,
22  resolveImport,
23  shortName
24} from './repo';
25
26// `${loop}:${path}` for each file attached and `${loop}:${folder}/` for each folder already read.
27const delivered = atom({ plugin: 'agent-kevin', key: 'delivered' } as const, []);
28// Files the current turn attached, shown in the band until the turn ends.
29const thisTurn = atom({ plugin: 'agent-kevin', key: 'manualsThisTurn' } as const, []);
30
31const MAIN = 'main';
32
33// Read once per module load; a reload picks up changed grants.
34let grantsCache: string[] | undefined;
35let dataDirCache: string | undefined;
36
37interface Manual {
38  path: string;
39  text: string;
40}
41
42const loopOf = (agentId: string | undefined): string => agentId ?? MAIN;
43
44const asPaths = (field: unknown): string[] => (typeof field === 'string' ? [field] : []);
45
46async function exists($: EngineInterface, path: string): Promise<boolean> {
47  return $.fs.stat(path).then(
48    () => true,
49    () => false
50  );
51}
52
53async function grants($: EngineInterface): Promise<string[]> {
54  if (grantsCache) {
55    return grantsCache;
56  }
57  const permissions = (await $.settings.read()).permissions;
58  const listed =
59    typeof permissions === 'object' && permissions !== null && 'additionalDirectories' in permissions
60      ? permissions.additionalDirectories
61      : [];
62  const home = await $.env.get('HOME');
63  grantsCache = (Array.isArray(listed) ? listed : [])
64    .filter((entry): entry is string => typeof entry === 'string')
65    .map((entry) => expandHome(entry, home));
66  return grantsCache;
67}
68
69/**
70 * The plugin's data dir name (`.state`), from the CLI that owns it; '' when it can't be read.
71 */
72async function dataDirName($: EngineInterface): Promise<string> {
73  if (dataDirCache === undefined) {
74    const { exitCode, stdout } = await $.process.run(cliArgv($.plugin.root, $.plugin.name, ['ping']), {
75      cwd: await $.session.root()
76    });
77    dataDirCache = exitCode === 0 ? dataDirNameIn(stdout) : '';
78  }
79  return dataDirCache;
80}
81
82/**
83 * An agent home loads its own instructions through its bridge; it is marked, as the runtime marks
84 * one, by a data dir holding a marker file.
85 */
86async function isAgentHome($: EngineInterface, folder: string): Promise<boolean> {
87  const name = await dataDirName($);
88  if (!name) {
89    return false;
90  }
91  const marked = await Promise.all(HOME_MARKERS.map((marker) => exists($, `${folder}/${name}/${marker}`)));
92  return marked.includes(true);
93}
94
95async function findRepoRoot($: EngineInterface, folders: readonly string[]): Promise<string | undefined> {
96  const [first, ...rest] = folders;
97  if (first === undefined) {
98    return undefined;
99  }
100  return (await exists($, `${first}/.git`)) ? first : findRepoRoot($, rest);
101}
102
103/**
104 * The repo folders from the root down to `path`'s folder that this loop hasn't read yet, or none
105 * outside a granted repo and inside an agent home.
106 */
107async function foldersFor(
108  $: EngineInterface,
109  path: string,
110  mayBeFolder: boolean,
111  done: ReadonlySet<string>
112): Promise<string[]> {
113  const grant = grantFor(path, await grants($), await $.session.root());
114  if (grant === undefined) {
115    return [];
116  }
117  const isFolder =
118    mayBeFolder &&
119    (await $.fs.stat(path).then(
120      (stat) => stat.kind === 'dir',
121      () => false
122    ));
123  const folder = isFolder ? path : parentOf(path);
124  // Handling a folder marks every folder from its repo root down, so a repeat touch stops here.
125  if (done.has(`${folder}/`)) {
126    return [];
127  }
128  const upward = foldersUpTo(folder, grant);
129  const repoRoot = await findRepoRoot($, upward);
130  if (repoRoot === undefined || (await isAgentHome($, repoRoot))) {
131    return [];
132  }
133  return upward.slice(0, upward.indexOf(repoRoot) + 1).reverse();
134}
135
136/**
137 * A folder's Claude files, or its AGENTS.md when it has none: Claude Code's default rule.
138 */
139async function instructionFiles($: EngineInterface, folder: string): Promise<string[]> {
140  const present = async (paths: readonly string[]) =>
141    (await Promise.all(paths.map(async (path) => ((await exists($, path)) ? [path] : [])))).flat();
142  const claude = await present(CLAUDE_FILES.map((name) => `${folder}/${name}`));
143  return claude.length ? claude : present([`${folder}/AGENTS.md`]);
144}
145
146/**
147 * Each file then its imports, depth-first, skipping anything already seen and any import
148 * outside the grants (the mod reads files the Read tool's sandbox would refuse).
149 */
150async function expand(
151  $: EngineInterface,
152  files: readonly string[],
153  hops: number,
154  walk: { allowed: readonly string[]; home: string | undefined; seen: Set<string> }
155): Promise<Manual[]> {
156  const [file, ...rest] = files;
157  if (file === undefined) {
158    return [];
159  }
160  if (walk.seen.has(file)) {
161    return expand($, rest, hops, walk);
162  }
163  walk.seen.add(file);
164  const text = await $.fs.read(file).catch(() => undefined);
165  if (typeof text !== 'string') {
166    return expand($, rest, hops, walk);
167  }
168  const imports =
169    hops >= MAX_IMPORT_HOPS
170      ? []
171      : importsIn(text)
172          .map((ref) => resolveImport(file, ref, walk.home))
173          .filter((path) => walk.allowed.some((grant) => isUnder(path, grant)));
174  const nested = await expand($, imports, hops + 1, walk);
175  return [{ path: file, text }, ...nested, ...(await expand($, rest, hops, walk))];
176}
177
178async function withManuals(
179  $: EngineInterface,
180  result: ToolCallResult,
181  spelled: readonly string[],
182  mayBeFolder: boolean,
183  agentId: string | undefined
184): Promise<ToolCallResult> {
185  const touched = spelled.map(normalize);
186  if (result.deny !== undefined || touched.length === 0) {
187    return result;
188  }
189  const loop = loopOf(agentId);
190  const done = new Set(
191    (await read($, delivered)).filter((key) => key.startsWith(`${loop}:`)).map((key) => key.slice(loop.length + 1))
192  );
193  const folders = [
194    ...new Set((await Promise.all(touched.map((path) => foldersFor($, path, mayBeFolder, done)))).flat())
195  ].filter((folder) => !done.has(`${folder}/`));
196  if (folders.length === 0) {
197    return result;
198  }
199  const files = (await Promise.all(folders.map((folder) => instructionFiles($, folder)))).flat();
200  const manuals = await expand($, files, 0, {
201    allowed: await grants($),
202    home: await $.env.get('HOME'),
203    seen: new Set([...done, ...touched])
204  });
205  const shown = manuals.filter((manual) => hasOwnContent(manual.text));
206  await update($, delivered, (list) => [
207    ...list,
208    ...folders.map((folder) => `${loop}:${folder}/`),
209    ...shown.map((manual) => `${loop}:${manual.path}`)
210  ]);
211  if (loop === MAIN && shown.length) {
212    await update($, thisTurn, (list) => [...list, ...shown.map((manual) => manual.path)]);
213  }
214  return shown.length
215    ? {
216        ...result,
217        context: [...(result.context ?? []), ...shown.map((manual) => manualContext(manual.path, manual.text))]
218      }
219    : result;
220}
221
222export const registerManuals = (on: On): void => {
223  // Edit refuses a file the conversation hasn't Read, so the Read already attached its manual.
224  on('tool.call', { tool: ['Read', 'Write'] }, async ($, e, next) =>
225    withManuals($, await next(e), asPaths(e.file_path), false, e.agentId)
226  );
227
228  on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
229    const result = await next(e);
230    return withManuals($, result, pathsInCommand(asPaths(e.command)[0] ?? '', await grants($)), true, e.agentId);
231  });
232
233  // A precompute only prepares a summary and a vetoed one changes nothing: the manuals stay in context.
234  on('session.compact', { trigger: ['manual', 'auto', 'plugin'] }, async ($, e, next) => {
235    const result = await next(e);
236    if (result.skip === undefined) {
237      const prefix = `${loopOf(e.agentId)}:`;
238      await update($, delivered, (list) => list.filter((key) => !key.startsWith(prefix)));
239    }
240    return result;
241  });
242
243  // A /clear or a resume starts another conversation in the same process.
244  on('session.end', { reason: ['clear', 'resume'] }, async ($, e, next) => {
245    await update($, delivered, () => []);
246    return next(e);
247  });
248
249  // Sync owns the unmatched turn.complete; every reason is listed so this one sees each turn too.
250  on('turn.complete', { reason: TURN_REASONS }, async ($, e, next) => {
251    if (e.agentId === undefined) {
252      await update($, thisTurn, () => []);
253    }
254    return next(e);
255  });
256
257  on('session.start', { isInteractive: true }, async ($, e, next) => {
258    await Promise.all(MANUALS_FEATURE.commands.map((command) => $.command.register(command)));
259    return next(e);
260  });
261
262  on('command.run', { command: 'manuals' }, async ($) => {
263    const allowed = await grants($);
264    const files = (await read($, delivered))
265      .filter((key) => key.startsWith(`${MAIN}:`) && !key.endsWith('/'))
266      .map((key) => shortName(key.slice(MAIN.length + 1), allowed));
267    return { text: files.length ? `In context: ${files.join(', ')}` : 'No repo instructions attached yet.' };
268  });
269
270  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
271    const below = await next(e);
272    const attached = await read($, thisTurn);
273    if (attached.length === 0 || e.props.hasSurvey) {
274      return below;
275    }
276    const allowed = await grants($);
277    const { Box, Text } = $.ui.resolve(e);
278    return (
279      <Box flexDirection="column">
280        <Text dimColor wrap="truncate-end">
281          📎 {attached.map((path) => shortName(path, allowed)).join(' · ')} attached
282        </Text>
283        {below}
284      </Box>
285    );
286  });
287};
288
notices/notices.tsx 205 lines
1import { atom, read, update } from 'claude-code';
2import type { EngineInterface, On, Timer } from 'claude-code';
3
4import { cliArgv, cliError } from '../shared/cli';
5import { TURN_REASONS } from '../shared/turns';
6import { SYNC_HISTORY_KEY, formatDuration, parseHistory, typicalMs } from '../sync/stats';
7import type { Notice, NoticeActing } from '../types';
8
9const notices = atom({ plugin: 'agent-kevin', key: 'notices' } as const, []);
10// The notice whose command was pressed or started; the row steps aside until that command's turn ends.
11const acting = atom({ plugin: 'agent-kevin', key: 'noticeActing' } as const, null);
12
13const REFRESH_MS = 30 * 60_000;
14const TOAST_MS = 8000;
15
16const LEVEL_COLORS = { hint: 'cyan', nudge: 'yellow', alert: 'red' } as const;
17const TONE_COLORS = { accent: 'cyan', warn: 'yellow' } as const;
18
19// Module state: a reload drops the timer and the next session start makes a new one.
20let refresher: Timer | undefined;
21// Claimed before the press's first await, so a second press in the same tick finds it.
22let isPressing = false;
23
24const actsOn = (notice: Notice, skill: string): boolean =>
25  notice.command === skill || notice.command.endsWith(`:${skill}`);
26
27const isString = (data: unknown): data is string => typeof data === 'string';
28
29const isNotice = (data: unknown): data is Notice => {
30  if (typeof data !== 'object' || data === null) {
31    return false;
32  }
33  const item = data as Record<string, unknown>;
34  return (
35    [item.id, item.icon, item.title, item.command, item.actionLabel].every(isString) &&
36    ['hint', 'nudge', 'alert'].includes(String(item.level)) &&
37    Array.isArray(item.facts) &&
38    item.facts.every(
39      (fact: unknown) => typeof fact === 'object' && fact !== null && isString((fact as { text?: unknown }).text)
40    )
41  );
42};
43
44// The CLI is this plugin's own, but a list that isn't one keeps the last good list rather than breaking the band.
45const parseNotices = (text: string): Notice[] | null => {
46  const data: unknown = JSON.parse(text);
47  return Array.isArray(data) && data.every(isNotice) ? data : null;
48};
49
50// The session root, not its cwd: a shell `cd` in a turn moves the cwd out of the home.
51async function runCli($: EngineInterface, args: readonly string[]): Promise<string> {
52  const { exitCode, stdout, stderr } = await $.process.run(cliArgv($.plugin.root, $.plugin.name, args), {
53    cwd: await $.session.root()
54  });
55  if (exitCode !== 0) {
56    throw cliError(stderr, args, exitCode);
57  }
58  return stdout;
59}
60
61/**
62 * Stores the list a `notices` call prints, the sync notice carrying this machine's typical run time.
63 */
64async function load($: EngineInterface, args: readonly string[]): Promise<Notice[]> {
65  const fresh = await runCli($, args)
66    .then(parseNotices)
67    .catch(() => null);
68  if (fresh === null) {
69    return read($, notices);
70  }
71  const typical = typicalMs(parseHistory(await $.store.get(SYNC_HISTORY_KEY)));
72  const shown =
73    typical === null
74      ? fresh
75      : fresh.map((notice) =>
76          notice.id === 'sync'
77            ? { ...notice, facts: [...notice.facts, { text: `~${formatDuration(typical)}` }] }
78            : notice
79        );
80  await update($, notices, () => shown);
81  return shown;
82}
83
84async function announce($: EngineInterface): Promise<void> {
85  const [lead] = await load($, ['notices', '--row']);
86  if (lead === undefined) {
87    return;
88  }
89  void $.prompt.suggest({ text: `/${lead.command}` });
90  if (lead.level === 'alert') {
91    $.ui.toast(`${lead.icon}  ${lead.title}. Tab to ${lead.actionLabel.toLowerCase()}.`, { timeoutMs: TOAST_MS });
92  }
93}
94
95async function act($: EngineInterface, notice: Notice): Promise<void> {
96  if (isPressing) {
97    return;
98  }
99  isPressing = true;
100  try {
101    if ((await read($, acting)) !== null) {
102      return;
103    }
104    const at = await $.clock.now();
105    await update($, acting, () => ({ id: notice.id, isStarted: false, at }));
106  } finally {
107    isPressing = false;
108  }
109  // Queued, not awaited: the run outlives the press. Should a host refuse the name, the typed form does the same.
110  void $.command
111    .run({ command: notice.command })
112    .catch(() => $.prompt.submit({ text: `/${notice.command}` }))
113    .catch(() => update($, acting, (current) => (current?.isStarted ? current : null)));
114}
115
116async function snooze($: EngineInterface, notice: Notice): Promise<void> {
117  await load($, ['notices', 'record', notice.id, '--outcome=snoozed']);
118}
119
120async function settle($: EngineInterface): Promise<void> {
121  await load($, ['notices']);
122  await update($, acting, () => null);
123}
124
125// A press whose command never started (the queue dropped it) stops hiding the row once it is a refresh old.
126async function refresh($: EngineInterface): Promise<void> {
127  await load($, ['notices']);
128  const now = await $.clock.now();
129  await update($, acting, (current: NoticeActing | null) =>
130    current && !current.isStarted && now - current.at >= REFRESH_MS ? null : current
131  );
132}
133
134export const registerNotices = (on: On): void => {
135  on('session.start', { isInteractive: true }, async ($, e, next) => {
136    const result = await next(e);
137    // After the session is up: the CLI call is a process spawn the prompt shouldn't wait on.
138    $.clock.after(0, () => void announce($));
139    refresher?.cancel();
140    refresher = $.clock.every(REFRESH_MS, () => void refresh($));
141    return result;
142  });
143
144  // Typing the command by hand counts as acting on it, the same as the button.
145  on('skill.prompt', { skill: /./ }, async ($, e, next) => {
146    const notice = (await read($, notices)).find((item) => actsOn(item, e.skill));
147    if (notice) {
148      const at = await $.clock.now();
149      await update($, acting, () => ({ id: notice.id, isStarted: true, at }));
150      void runCli($, ['notices', 'record', notice.id, '--outcome=acted']).catch(() => undefined);
151    }
152    return next(e);
153  });
154
155  // The command's skill started inside the running turn, so the next main turn to end is the command's own, however it ended.
156  on('turn.complete', { reason: TURN_REASONS }, async ($, e, next) => {
157    const result = await next(e);
158    if (e.agentId === undefined && (await read($, acting))?.isStarted) {
159      $.clock.after(0, () => void settle($));
160    }
161    return result;
162  });
163
164  // Stacks above whatever renders beneath, so other features' rows share the band.
165  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
166    const below = await next(e);
167    if (e.props.hasSurvey || (await read($, acting)) !== null) {
168      return below;
169    }
170    const [top, ...waiting] = await read($, notices);
171    if (top === undefined || top.level === 'hint') {
172      return below;
173    }
174    const { Box, Button, Text } = $.ui.resolve(e);
175    return (
176      <Box flexDirection="column">
177        <Box gap={1}>
178          {/* The trailing space survives a font that draws the glyph wider than its one cell. */}
179          <Text bold color={LEVEL_COLORS[top.level]}>{`${top.icon} `}</Text>
180          <Text bold>{top.title}</Text>
181          {top.facts.map((fact) => (
182            <Box key={fact.text} gap={1}>
183              <Text dimColor>·</Text>
184              <Text color={fact.tone ? TONE_COLORS[fact.tone] : undefined} dimColor={!fact.tone}>
185                {fact.text}
186              </Text>
187            </Box>
188          ))}
189          <Box gap={1} marginLeft={2}>
190            <Button
191              key={`notice:${top.id}:act`}
192              variant="primary"
193              label={top.actionLabel}
194              onPress={() => act($, top)}
195            />
196            <Button key={`notice:${top.id}:snooze`} dimColor label="Tomorrow" onPress={() => snooze($, top)} />
197          </Box>
198          {waiting.length ? <Text dimColor>{`+${waiting.length} more`}</Text> : null}
199        </Box>
200        {below}
201      </Box>
202    );
203  });
204};
205
queue/queue.tsx 87 lines
1import { atom, read, update } from 'claude-code';
2import type { EngineInterface, On } from 'claude-code';
3
4import { QUEUE_FEATURE } from '../shared/catalog';
5import { TURN_REASONS } from '../shared/turns';
6import type { Queue } from '../types';
7
8const EMPTY: Queue = { pending: [], isBusy: false, isPaused: false };
9const queue = atom({ plugin: 'agent-kevin', key: 'queue' } as const, EMPTY);
10
11const drain = async ($: EngineInterface): Promise<void> => {
12  // update() may rerun the change on a conflict; only the committed run's pick is sent.
13  let text: string | undefined;
14  await update($, queue, (current) => {
15    text = current.isBusy || current.isPaused ? undefined : current.pending[0];
16    return text === undefined ? current : { ...current, pending: current.pending.slice(1), isBusy: true };
17  });
18
19  if (text !== undefined) {
20    const prompt = text;
21    // A submit from inside a hook would wait on the turn the hook holds; a timer runs it after.
22    $.clock.after(0, () => void $.prompt.submit({ text: prompt, asUser: true }));
23  }
24};
25
26export const registerQueue = (on: On): void => {
27  on('session.start', { isInteractive: true }, async ($, e, next) => {
28    await Promise.all(QUEUE_FEATURE.commands.map((command) => $.command.register(command)));
29    return next(e);
30  });
31
32  on('command.run', { command: 'queue' }, async ($, e) => {
33    const text = e.args.trim();
34    if (!text) {
35      return { text: 'Usage: /queue <prompt>, or /queue clear' };
36    }
37
38    if (text === 'clear') {
39      let cleared = 0;
40      await update($, queue, (current) => {
41        cleared = current.pending.length;
42        return { ...current, pending: [], isPaused: false };
43      });
44      return { text: `Cleared ${cleared} queued prompt${cleared === 1 ? '' : 's'}.` };
45    }
46
47    await update($, queue, (current) => ({ ...current, pending: [...current.pending, text] }));
48    await drain($);
49    return {};
50  });
51
52  on('turn.start', async ($, e, next) => {
53    if (e.agentId === undefined) {
54      await update($, queue, (current) => ({ ...current, isBusy: true }));
55    }
56    return next(e);
57  });
58
59  // Esc on a runaway task, or an error such as a rate limit, holds what waits instead of sending it into the same trouble.
60  on('turn.complete', { reason: TURN_REASONS }, async ($, e, next) => {
61    if (e.agentId === undefined) {
62      const isPaused = e.reason === 'aborted' || e.reason === 'error';
63      await update($, queue, (current) => ({ ...current, isBusy: false, isPaused: isPaused && current.pending.length > 0 }));
64      await drain($);
65    }
66    return next(e);
67  });
68
69  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
70    const below = await next(e);
71    const { pending, isPaused } = await read($, queue);
72    if (!pending.length || e.props.hasSurvey) {
73      return below;
74    }
75    const { Box, Text } = $.ui.resolve(e);
76    const line = isPaused
77      ? `⏸ ${pending.length} queued (paused) · send a prompt to resume, /queue clear to drop`
78      : `⏳ ${pending.length} queued · /queue clear to drop`;
79    return (
80      <Box flexDirection="column">
81        <Text dimColor>{line}</Text>
82        {below}
83      </Box>
84    );
85  });
86};
87
reports/reports.tsx 333 lines
1import { atom, read, update } from 'claude-code';
2import type { EngineInterface, On } from 'claude-code';
3
4import type { ReportRow, SessionReport } from '../types';
5
6import { REPORTS_FEATURE } from '../shared/catalog';
7import { cliArgv } from '../shared/cli';
8import { bareToolName } from '../sync/phases';
9
10const reportsBand = atom({ plugin: 'agent-kevin', key: 'reportsBand' } as const, null);
11
12const KEY_PREFIX = 'reports:';
13const SESSIONS_KEPT = 50;
14const USAGE = 'Usage: /reports, or /reports attach <path> [<path> …] (quote a path with spaces)';
15// A subset of shell word rules: whitespace splits, "…" and '…' keep spaces, and a backslash escapes one character.
16const WORD = /(?:"[^"]*"|'[^']*'|\\.|[^\s"'\\])+/g;
17const QUOTED = /"([^"]*)"|'([^']*)'|\\(.)/g;
18const INDEXES = ['reports/index.md', 'reports/pinned.md'];
19const HOME_RECHECK_MS = 60_000;
20
21// Subagents can finish report_write together; one store write at a time keeps both rows.
22let writes: Promise<void> = Promise.resolve();
23let homeCache: { home: Promise<string | undefined>; at: number } | undefined;
24
25const isSessionReport = (item: unknown): item is SessionReport =>
26  typeof item === 'object' &&
27  item !== null &&
28  'title' in item &&
29  'path' in item &&
30  typeof item.title === 'string' &&
31  typeof item.path === 'string';
32
33const writtenPath = (text: string | undefined): string | undefined => {
34  try {
35    const parsed: unknown = JSON.parse(text ?? '');
36    return typeof parsed === 'object' && parsed !== null && 'path' in parsed && typeof parsed.path === 'string'
37      ? parsed.path
38      : undefined;
39  } catch {
40    return undefined;
41  }
42};
43
44async function sessionKey($: EngineInterface): Promise<string> {
45  return `${KEY_PREFIX}${await $.session.id()}`;
46}
47
48async function storedReports($: EngineInterface, key: string): Promise<SessionReport[]> {
49  const stored = await $.store.get(key);
50  return Array.isArray(stored) ? stored.filter(isSessionReport) : [];
51}
52
53const fileName = (path: string): string => path.slice(path.lastIndexOf('/') + 1);
54
55const stem = (path: string): string => fileName(path).replace(/\.[^.]+$/, '');
56
57const isDocument = (path: string): boolean => path.endsWith('.md') || path.endsWith('.html');
58
59const namesDeliverableFolder = (text: string): boolean =>
60  text.includes('/reports/') || text.includes('/projects/') || text.includes('/roadmap.html');
61
62const mayBeReport = (path: string): boolean => isDocument(path) && namesDeliverableFolder(path);
63
64// A miss is asked again after a minute, so a folder set up as a home mid-session is picked up.
65async function home($: EngineInterface): Promise<string | undefined> {
66  const now = await $.clock.now();
67  if (homeCache !== undefined && ((await homeCache.home) !== undefined || now - homeCache.at < HOME_RECHECK_MS)) {
68    return homeCache.home;
69  }
70  const lookup = $.process
71    .run(cliArgv($.plugin.root, $.plugin.name, ['ping']), { cwd: await $.session.root() })
72    .then(({ exitCode, stdout }) => {
73      const parsed: unknown = exitCode === 0 ? JSON.parse(stdout) : undefined;
74      // Outside a home the CLI still names a folder, but says it isn't one.
75      return typeof parsed === 'object' &&
76        parsed !== null &&
77        'ok' in parsed &&
78        parsed.ok === true &&
79        'home' in parsed &&
80        typeof parsed.home === 'string'
81        ? parsed.home
82        : undefined;
83    })
84    .catch(() => undefined);
85  homeCache = { home: lookup, at: now };
86  return lookup;
87}
88
89async function isDeliverable($: EngineInterface, path: string): Promise<boolean> {
90  const root = await home($);
91  if (root === undefined || !path.startsWith(`${root}/`)) {
92    return false;
93  }
94  const inHome = path.slice(root.length + 1);
95  const isReport = inHome.startsWith('reports/') && !INDEXES.includes(inHome);
96  const isProjectDocument =
97    /^projects\/[^/]+\//.test(inHome) &&
98    (path.endsWith('.html') || (fileName(path) !== 'README.md' && !inHome.includes('/tasks/')));
99  return isReport || isProjectDocument || inHome === 'roadmap.html';
100}
101
102async function rowFor($: EngineInterface, report: SessionReport, root: string): Promise<ReportRow> {
103  const page = report.path.replace(/\.md$/, '.html');
104  const hasPage =
105    page !== report.path &&
106    (await $.fs.stat(page).then(
107      () => true,
108      () => false
109    ));
110  const shown = hasPage ? page : report.path;
111  return { title: report.title, shownPath: shown.startsWith(`${root}/`) ? shown.slice(root.length + 1) : shown };
112}
113
114async function rowsFor($: EngineInterface, key: string): Promise<ReportRow[]> {
115  const [reports, root] = await Promise.all([storedReports($, key), $.session.root()]);
116  const drawn = await Promise.all(reports.map(async (report) => ({ report, row: await rowFor($, report, root) })));
117  const latestFirst = [...drawn].reverse();
118  // A page and its card share one row, placed by the latest save, titled by the card report_write named.
119  return latestFirst
120    .filter((item, index) => latestFirst.findIndex((other) => other.row.shownPath === item.row.shownPath) === index)
121    .map((item) => {
122      const card = drawn.find(
123        (other) => other.row.shownPath === item.row.shownPath && other.report.path.endsWith('.md')
124      );
125      const title = (card ?? item).row.title ?? '';
126      return stem(title) === stem(item.row.shownPath) ? { shownPath: item.row.shownPath } : { ...item.row, title };
127    })
128    .reverse();
129}
130
131const inQueue = <T,>(task: () => Promise<T>): Promise<T> => {
132  const run = writes.then(task);
133  writes = run.then(
134    () => undefined,
135    () => undefined
136  );
137  return run;
138};
139
140const queue = (task: () => Promise<void>): void => {
141  inQueue(task).catch(() => undefined);
142};
143
144async function record($: EngineInterface, key: string, path: string, title?: string): Promise<void> {
145  const reports = await storedReports($, key);
146  const report = { path, title: title ?? reports.find((item) => item.path === path)?.title ?? fileName(path) };
147  // The store lists keys in insertion order and a set keeps a key's place, so a save moves it to the end.
148  await $.store.delete(key);
149  await $.store.set(key, [...reports.filter((item) => item.path !== path), report]);
150  const sessions = (await $.store.keys()).filter((stored) => stored.startsWith(KEY_PREFIX));
151  await Promise.all(sessions.slice(0, -SESSIONS_KEPT).map((stored) => $.store.delete(stored)));
152  if ((await read($, reportsBand)) !== null && key === (await sessionKey($))) {
153    const rows = await rowsFor($, key);
154    await update($, reportsBand, (band) => (band === null ? band : rows));
155  }
156}
157
158// A redirect, an assignment or a following operator can sit against a path: `>/x.md`, `P=~/x.md`, `/x.md;ls`.
159const pathIn = (word: string, userHome: string | undefined): string | undefined => {
160  const start = word.search(/~\/|\//);
161  const path = start === -1 ? undefined : word.slice(start).split(/[;|&<>()]/)[0];
162  return path?.startsWith('~/') && userHome ? `${userHome}${path.slice(1)}` : path;
163};
164
165const shellWords = (text: string): string[] =>
166  (text.match(WORD) ?? []).map((word) =>
167    word.replace(
168      QUOTED,
169      (_match, double?: string, single?: string, escaped?: string) => double ?? single ?? escaped ?? ''
170    )
171  );
172
173async function attach($: EngineInterface, spelled: readonly string[]): Promise<string[]> {
174  const [root, userHome, key] = await Promise.all([$.session.root(), $.env.get('HOME'), sessionKey($)]);
175  const resolve = (path: string) =>
176    path.startsWith('/')
177      ? path
178      : path.startsWith('~/') && userHome
179        ? `${userHome}/${path.slice(2)}`
180        : `${root}/${path.replace(/^\.\//, '')}`;
181  const paths = spelled.map(resolve);
182  const found = await Promise.all(
183    paths.map((path) =>
184      $.fs.stat(path).then(
185        (stat) => stat.kind === 'file',
186        () => false
187      )
188    )
189  );
190  paths.filter((_path, index) => found[index]).forEach((path) => queue(() => record($, key, path)));
191  return spelled.filter((_path, index) => !found[index]);
192}
193
194export const registerReports = (on: On): void => {
195  on('tool.call', { tool: /__report_write$/ }, async ($, e, next) => {
196    const result = await next(e);
197    const path = writtenPath(result.text);
198    if (bareToolName(e.tool, $.plugin.name) !== 'report_write' || result.isError === true || path === undefined) {
199      return result;
200    }
201    const title = 'title' in e && typeof e.title === 'string' ? e.title : undefined;
202    const key = await sessionKey($);
203    queue(() => record($, key, path, title));
204    return result;
205  });
206
207  on('tool.call', { tool: ['Write', 'Edit'] }, async ($, e, next) => {
208    const result = await next(e);
209    if (result.deny === undefined && result.isError !== true && mayBeReport(e.file_path)) {
210      const key = await sessionKey($);
211      queue(async () => {
212        if (await isDeliverable($, e.file_path)) {
213          await record($, key, e.file_path);
214        }
215      });
216    }
217    return result;
218  });
219
220  // A shell write leaves no structured trace, so a named path counts once its modified time follows the call's start.
221  on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
222    if (!namesDeliverableFolder(e.command)) {
223      return next(e);
224    }
225    const startedAt = await $.clock.now();
226    const result = await next(e);
227    if (result.deny === undefined) {
228      const key = await sessionKey($);
229      queue(async () => {
230        const [root, userHome] = await Promise.all([home($), $.env.get('HOME')]);
231        const named = [...new Set(shellWords(e.command).flatMap((word) => pathIn(word, userHome) ?? []))].filter(
232          (path) => root !== undefined && path.startsWith(`${root}/`) && isDocument(path)
233        );
234        const written = await Promise.all(
235          named.map(async (path) => {
236            const isWritten =
237              (await isDeliverable($, path)) &&
238              (await $.fs.stat(path).then(
239                (stat) => stat.kind === 'file' && stat.mtimeMs >= startedAt,
240                () => false
241              ));
242            return isWritten ? [path] : [];
243          })
244        );
245        await written.flat().reduce((previous, path) => previous.then(() => record($, key, path)), Promise.resolve());
246      });
247    }
248    return result;
249  });
250
251  on('session.start', { isInteractive: true }, async ($, e, next) => {
252    await Promise.all(REPORTS_FEATURE.commands.map((command) => $.command.register(command)));
253    return next(e);
254  });
255
256  // Claude reads the full list; the person sees the latest rows in the band until they dismiss it.
257  on('command.run', { command: 'reports' }, async ($, e) => {
258    if (e.args.replace(WORD, '').trim()) {
259      return { text: `A quote isn't closed in: ${e.args.trim()}` };
260    }
261    const [verb = '', ...words] = shellWords(e.args);
262    const paths = words.filter(Boolean);
263    if ((verb && verb !== 'attach') || (verb === 'attach' && paths.length === 0)) {
264      return { text: USAGE };
265    }
266    const missing = verb === 'attach' ? await attach($, paths) : [];
267    const notice = missing.length ? `No file at ${missing.join(', ')}` : undefined;
268    const key = await sessionKey($);
269    // Read in the queue, so a save landing meanwhile either comes first or finds the band open.
270    const rows = await inQueue(async () => {
271      const found = await rowsFor($, key);
272      if (found.length) {
273        await update($, reportsBand, () => found);
274      }
275      return found;
276    });
277    if (rows.length === 0) {
278      return { text: notice ?? 'No reports in this conversation yet.' };
279    }
280    return {
281      ...(notice === undefined ? {} : { text: notice }),
282      context: [
283        [
284          'Reports in this conversation:',
285          ...rows.map((row) => (row.title ? `- ${row.shownPath} · ${row.title}` : `- ${row.shownPath}`))
286        ].join('\n')
287      ]
288    };
289  });
290
291  // A /clear or a resume starts another conversation in the same process.
292  on('session.end', { reason: ['clear', 'resume'] }, async ($, e, next) => {
293    await update($, reportsBand, () => null);
294    return next(e);
295  });
296
297  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
298    const below = await next(e);
299    const rows = await read($, reportsBand);
300    if (rows === null || e.props.hasSurvey) {
301      return below;
302    }
303    const { Box, Button, Text } = $.ui.resolve(e);
304    return (
305      <Box flexDirection="column">
306        <Box gap={1}>
307          <Text bold>📎 Reports</Text>
308          <Text dimColor>{`· ${rows.length} in this conversation`}</Text>
309          <Box marginLeft={2}>
310            <Button key="reports:dismiss" dimColor label="Dismiss" onPress={() => update($, reportsBand, () => null)} />
311          </Box>
312        </Box>
313        {/* Newest first: past the band's height the engine scrolls the rest. */}
314        {[...rows].reverse().map((row) => (
315          <Box key={row.shownPath} paddingLeft={3}>
316            <Box flexShrink={0}>
317              <Text>{row.shownPath}</Text>
318            </Box>
319            {row.title ? (
320              <Box flexGrow={1} flexShrink={1} marginLeft={2}>
321                <Text dimColor wrap="truncate-end">
322                  {row.title}
323                </Text>
324              </Box>
325            ) : null}
326          </Box>
327        ))}
328        {below}
329      </Box>
330    );
331  });
332};
333
setup/setup.tsx 81 lines
1import { atom, read, update } from 'claude-code';
2import type { EngineInterface, On } from 'claude-code';
3
4import { DATA_DIR, HOME_MARKERS, parentOf } from '../manuals/repo';
5
6const needsSetup = atom({ plugin: 'agent-kevin', key: 'needsSetup' } as const, false);
7
8const selfAndAncestors = (dir: string): string[] => (dir === '/' ? [] : [dir, ...selfAndAncestors(parentOf(dir))]);
9
10const exists = ($: EngineInterface, path: string): Promise<boolean> =>
11  $.fs.stat(path).then(
12    () => true,
13    () => false
14  );
15
16/**
17 * No data dir at the root or above it holds a home marker and no SOUL.md sits at the root, so init has nothing
18 * to overwrite and won't nest a home inside one. Read from disk rather than the CLI, which refuses to run
19 * outside a home and needs the plugin's packages installed.
20 */
21async function isFresh($: EngineInterface): Promise<boolean> {
22  const root = await $.session.root();
23  const paths = [
24    `${root}/SOUL.md`,
25    ...selfAndAncestors(root).flatMap((folder) => HOME_MARKERS.map((marker) => `${folder}/${DATA_DIR}/${marker}`))
26  ];
27  return !(await Promise.all(paths.map((path) => exists($, path)))).includes(true);
28}
29
30async function check($: EngineInterface): Promise<void> {
31  const isNew = await isFresh($);
32  await update($, needsSetup, () => isNew);
33  if (isNew) {
34    void $.prompt.suggest({ text: `/${$.plugin.name}:init` });
35  }
36}
37
38async function runInit($: EngineInterface): Promise<void> {
39  const command = `${$.plugin.name}:init`;
40  await update($, needsSetup, () => false);
41  void $.command.run({ command }).catch(() => $.prompt.submit({ text: `/${command}` }));
42}
43
44const agentName = (pluginName: string): string => {
45  const slug = pluginName.replace(/^agent-/, '');
46  return `${slug.charAt(0).toUpperCase()}${slug.slice(1)}`;
47};
48
49export const registerSetup = (on: On): void => {
50  on('session.start', { isInteractive: true }, async ($, e, next) => {
51    const result = await next(e);
52    $.clock.after(0, () => void check($));
53    return result;
54  });
55
56  // Once init starts it owns the rest of the session: it either sets the folder up or stops to ask for a relaunch.
57  on('skill.prompt', { skill: /(^|:)init$/ }, async ($, e, next) => {
58    await update($, needsSetup, () => false);
59    return next(e);
60  });
61
62  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
63    const below = await next(e);
64    if (e.props.hasSurvey || !(await read($, needsSetup))) {
65      return below;
66    }
67    const { Box, Button, Text } = $.ui.resolve(e);
68    return (
69      <Box flexDirection="column">
70        <Box gap={1}>
71          <Text bold>{`${agentName($.plugin.name)} isn't set up in this folder yet`}</Text>
72          <Box marginLeft={2}>
73            <Button key="setup:init" variant="primary" label="Set up" onPress={() => runInit($)} />
74          </Box>
75        </Box>
76        {below}
77      </Box>
78    );
79  });
80};
81
sync/tracker.tsx 319 lines
1import { atom, read, update } from 'claude-code';
2import type { AgentStatus, EngineInterface, On, Timer } from 'claude-code';
3
4import { SYNC_FEATURE } from '../shared/catalog';
5import { cliArgv } from '../shared/cli';
6import type { SyncRun, SyncSnapshot } from '../types';
7import { PHASES, bareToolName, classify } from './phases';
8import {
9  actionNotes,
10  appendHistory,
11  finish,
12  isOver,
13  formatDuration,
14  joined,
15  markWaiting,
16  parseBrain,
17  parseCompile,
18  parseHistory,
19  parseTasks,
20  progressOf,
21  recordCall,
22  remeasured,
23  startRun,
24  statsInstruction,
25  statsPayload,
26  SYNC_HISTORY_KEY,
27  toHistory,
28  typicalMs
29} from './stats';
30
31const syncRun = atom({ plugin: 'agent-kevin', key: 'syncRun' } as const, null);
32// Bumped every second while a run is live; only the band reads it, so only the band redraws.
33const syncTick = atom({ plugin: 'agent-kevin', key: 'syncTick' } as const, 0);
34
35const [STATS_TOOL] = SYNC_FEATURE.tools;
36const SYNC_SKILL = /(^|:)sync$/;
37const TICK_MS = 1000;
38const MAIN = 'main';
39
40const loopOf = (agentId: string | undefined): string => agentId ?? MAIN;
41const ENDED: readonly AgentStatus[] = ['completed', 'failed', 'killed'];
42
43const LOOKS = {
44  running: { icon: '⟳', color: 'cyan', status: 'running' },
45  waiting: { icon: '⏸', color: 'yellow', status: 'waiting on you' },
46  done: { icon: '✓', color: 'green', status: 'done' },
47  stopped: { icon: '■', color: 'red', status: 'stopped' }
48} as const;
49
50// Module state: a reload drops the timer and the next run starts a new one.
51let ticker: Timer | undefined;
52// skill.prompt carries no agentId, so the Skill call that loads sync names its loop here.
53let loadingLoop: string | undefined;
54
55async function runQuiet($: EngineInterface, argv: readonly string[]): Promise<string> {
56  const { exitCode, stdout } = await $.process.run(argv, { cwd: await $.session.root() });
57  return exitCode === 0 ? stdout : '';
58}
59
60async function measureCompile($: EngineInterface) {
61  return parseCompile(await runQuiet($, cliArgv($.plugin.root, $.plugin.name, ['compile', 'status'])));
62}
63
64async function snapshot($: EngineInterface): Promise<SyncSnapshot> {
65  const [compile, tasks, brain] = await Promise.all([
66    measureCompile($),
67    runQuiet($, cliArgv($.plugin.root, $.plugin.name, ['task', 'scan'])),
68    runQuiet($, ['bun', `${$.plugin.root}/skills/self-review/scripts/brain-audit.ts`])
69  ]);
70  return { compile, tasks: parseTasks(tasks), brain: parseBrain(brain) };
71}
72
73/**
74 * Re-measures in the background so the counters move during the run; a late answer after the
75 * run ended is dropped.
76 */
77async function refresh($: EngineInterface, fresh: Promise<Partial<SyncSnapshot>>): Promise<void> {
78  const measured = await fresh.catch(() => ({}));
79  await update($, syncRun, (run) => (run && !isOver(run) ? remeasured(run, measured) : run));
80}
81
82/**
83 * Whether an agent the run spawned is still working, as the host lists it; a killed one counts as ended.
84 */
85async function isHelperWorking($: EngineInterface, run: SyncRun): Promise<boolean> {
86  const agents = await $.agent.list().catch(() => []);
87  return agents.some(
88    (agent) => agent.id !== run.owner && run.loops.includes(agent.id) && !ENDED.includes(agent.status)
89  );
90}
91
92async function history($: EngineInterface) {
93  return parseHistory(await $.store.get(SYNC_HISTORY_KEY));
94}
95
96export const registerSync = (on: On): void => {
97  on('session.start', { isInteractive: true }, async ($, e, next) => {
98    await $.tool.register({
99      name: STATS_TOOL,
100      description:
101        "Counted numbers for the sync that is running: compile backlog, task health and brain counts measured at the run's start and now, actions tallied from tool results, and phase timings. Call once before writing sync's output block.",
102      inputSchema: { type: 'object', properties: {} },
103      isDeferred: false
104    });
105    return next(e);
106  });
107
108  on('tool.call', { tool: 'Skill' }, async ($, e, next) => {
109    if (!SYNC_SKILL.test(e.skill)) {
110      return next(e);
111    }
112    loadingLoop = loopOf(e.agentId);
113    try {
114      return await next(e);
115    } finally {
116      loadingLoop = undefined;
117    }
118  });
119
120  on('skill.prompt', { skill: SYNC_SKILL }, async ($, e, next) => {
121    const result = await next(e);
122    const loop = loadingLoop ?? MAIN;
123    const current = await read($, syncRun);
124    // An agent the run spawned (the one sync was handed to) is continuing it, not starting over.
125    const isHandedOn = current !== null && !isOver(current) && loop !== current.owner && current.loops.includes(loop);
126    if (!isHandedOn) {
127      const now = await $.clock.now();
128      const before = await snapshot($).catch(() => null);
129      await update($, syncRun, () => startRun(now, before, loop));
130      ticker?.cancel();
131      ticker = $.clock.every(TICK_MS, () => void update($, syncTick, (tick) => tick + 1));
132    }
133    const tools = await $.tool.list();
134    const statsTool = tools.find((tool) => tool.name.endsWith(`__${STATS_TOOL}`));
135    return statsTool ? { text: result.text + statsInstruction(statsTool.name) } : result;
136  });
137
138  on('tool.call', async ($, e, next) => {
139    const before = await read($, syncRun);
140    if (before === null || isOver(before) || !before.loops.includes(loopOf(e.agentId))) {
141      return next(e);
142    }
143    const phase = classify({ tool: e.tool, input: e }, $.plugin.name);
144    if (e.tool === 'AskUserQuestion') {
145      const asked = await $.clock.now();
146      await update($, syncRun, (run) => (run ? markWaiting(run, phase, asked) : run));
147    }
148    const result = await next(e);
149    const now = await $.clock.now();
150    const call = {
151      phase,
152      name: bareToolName(e.tool, $.plugin.name),
153      resultText: result.text ?? '',
154      isError: result.isError === true
155    };
156    await update($, syncRun, (run) => (run ? recordCall(run, call, now) : run));
157    if (call.phase !== undefined && call.phase > before.phase) {
158      $.clock.after(0, () => void refresh($, snapshot($)));
159    } else if (call.name === 'compile_write') {
160      $.clock.after(
161        0,
162        () =>
163          void refresh(
164            $,
165            measureCompile($).then((compile) => ({ compile }))
166          )
167      );
168    }
169    return result;
170  });
171
172  on('tool.call', { tool: /__sync_stats$/ }, async ($) => {
173    const run = await read($, syncRun);
174    if (run === null) {
175      return { result: 'No sync is running in this session.' };
176    }
177    const after = await snapshot($).catch(() => null);
178    await update($, syncRun, (current) => (current ? { ...current, after } : current));
179    const now = await $.clock.now();
180    // A tool result is text or content blocks, never an object.
181    return { result: JSON.stringify(statsPayload({ ...run, after }, now, await history($))) };
182  });
183
184  on('agent.spawn', async ($, e, next) => {
185    const result = await next(e);
186    const child = result.agentId;
187    if (child !== undefined) {
188      await update($, syncRun, (run) => (run && !isOver(run) ? joined(run, loopOf(e.parentAgentId), child) : run));
189    }
190    return result;
191  });
192
193  on('turn.complete', async ($, e, next) => {
194    const result = await next(e);
195    const run = await read($, syncRun);
196    if (run === null || isOver(run) || loopOf(e.agentId) !== run.owner) {
197      return result;
198    }
199    // The owner waits on its agents; their hand-back comes as its next turn, and the run ends there.
200    if (await isHelperWorking($, run)) {
201      return result;
202    }
203    ticker?.cancel();
204    ticker = undefined;
205    const now = await $.clock.now();
206    const ended = finish(run, now, await snapshot($).catch(() => null), e.isAborted);
207    await update($, syncRun, () => ended);
208    // A stopped run would drag the average down.
209    if (!e.isAborted) {
210      await $.store.set(SYNC_HISTORY_KEY, appendHistory(await history($), toHistory(ended)));
211    }
212    return result;
213  });
214
215  on('prompt.submit', async ($, e, next) => {
216    const run = await read($, syncRun);
217    if (run && isOver(run)) {
218      await update($, syncRun, () => null);
219    }
220    return next(e);
221  });
222
223  // Stacks above whatever renders beneath, so other features' rows share the band.
224  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
225    const below = await next(e);
226    const run = await read($, syncRun);
227    if (run === null || e.props.hasSurvey) {
228      return below;
229    }
230    const { Box, Text } = $.ui.resolve(e);
231    const now = await $.clock.now();
232    const look = LOOKS[run.status];
233    const isEnded = isOver(run);
234    const isComplete = run.status === 'done';
235    await read($, syncTick);
236    const past = isComplete ? await history($) : [];
237    const average = typicalMs(past);
238    const elapsed = formatDuration((run.endedAt ?? now) - run.startedAt);
239    const notes = actionNotes(run.actions);
240
241    const header = (
242      <Box>
243        <Text color={look.color}>{look.icon} </Text>
244        <Text bold>sync</Text>
245        <Text dimColor>
246          {' '}
247          · {look.status} · {elapsed}
248          {average === null ? '' : ` (avg ${formatDuration(average)})`}
249        </Text>
250      </Box>
251    );
252
253    const rail = (
254      <Box>
255        {PHASES.map((phase, index) => (
256          <Box key={phase.id}>
257            {index > 0 ? <Text dimColor>─</Text> : null}
258            {isComplete || index < run.phase ? (
259              <Text color="green">●</Text>
260            ) : index === run.phase ? (
261              <Text color={look.color}>◉</Text>
262            ) : (
263              <Text dimColor>○</Text>
264            )}
265          </Box>
266        ))}
267        {!isComplete && PHASES[run.phase] ? (
268          <Box>
269            <Text>
270              {'  '}
271              {PHASES[run.phase]?.id}{' '}
272            </Text>
273            <Text dimColor>{`${run.phase + 1}/${PHASES.length}`}</Text>
274          </Box>
275        ) : null}
276      </Box>
277    );
278
279    const counters = (
280      <Box flexWrap="wrap" columnGap={3}>
281        {progressOf(run).map((item) => (
282          <Box key={item.label} flexShrink={0}>
283            <Text dimColor>{item.label} </Text>
284            <Text color={item.cleared && item.cleared === item.total ? 'green' : undefined}>
285              {item.cleared}/{item.total}
286            </Text>
287            {item.grew ? <Text color="red"> +{item.grew}</Text> : null}
288          </Box>
289        ))}
290        {notes.map((note) => (
291          <Box key={note.label} flexShrink={0}>
292            <Text dimColor>{note.label} </Text>
293            <Text>{note.count}</Text>
294          </Box>
295        ))}
296      </Box>
297    );
298
299    return isEnded ? (
300      <Box flexDirection="column">
301        {/* A narrow pane wraps whole pieces onto the next line instead of breaking words. */}
302        <Box flexWrap="wrap" columnGap={2}>
303          <Box flexShrink={0}>{header}</Box>
304          <Box flexShrink={0}>{rail}</Box>
305          {counters}
306        </Box>
307        {below}
308      </Box>
309    ) : (
310      <Box flexDirection="column">
311        {header}
312        <Box paddingLeft={2}>{rail}</Box>
313        <Box paddingLeft={2}>{counters}</Box>
314        {below}
315      </Box>
316    );
317  });
318};
319
shared/catalog.ts 128 lines
1// Pure data, no 'claude-code' import: the features register their commands from here, and the
2// dashboard's Capabilities page reads the same list, so the two can't drift.
3
4export interface ModCommand {
5  name: string;
6  description: string;
7  argumentHint?: string;
8  immediate?: boolean;
9}
10
11export interface ModFeature {
12  /** The feature's folder under mods/, which register.ts imports. */
13  id: string;
14  title: string;
15  summary: string;
16  where: string;
17  commands: readonly ModCommand[];
18  tools: readonly string[];
19}
20
21export const COMMANDS_FEATURE = {
22  id: 'commands',
23  title: 'Instant commands',
24  summary:
25    "Capture a thought, log a lesson, close a task, see today or copy this conversation's session id, answered at once without a model turn.",
26  where: 'slash commands · the Today and Session rows above the prompt',
27  commands: [
28    {
29      name: 'capture',
30      description: 'Drop a thought into the knowledge inbox (no Claude turn)',
31      argumentHint: '<text>',
32      immediate: true
33    },
34    {
35      name: 'lesson',
36      description: 'Log a correction to the feedback log (no Claude turn)',
37      argumentHint: '<text>',
38      immediate: true
39    },
40    { name: 'done', description: 'Close a task by id (no Claude turn)', argumentHint: '<task-id>', immediate: true },
41    { name: 'today', description: "Overdue work, what's due today and the last sync (no Claude turn)" },
42    { name: 'session', description: "This conversation's session id, with a Copy button (no Claude turn)" }
43  ],
44  tools: []
45} as const satisfies ModFeature;
46
47export const MANUALS_FEATURE = {
48  id: 'manuals',
49  title: 'Repo manuals',
50  summary:
51    "The first file read or written in a granted code repo, or named by absolute path in a shell command, attaches that repo's CLAUDE.md or AGENTS.md, once, and again after a compaction or /clear.",
52  where: 'tool results · a 📎 line above the prompt',
53  commands: [{ name: 'manuals', description: 'Repo instructions attached to this conversation (no Claude turn)' }],
54  tools: []
55} as const satisfies ModFeature;
56
57export const REPORTS_FEATURE = {
58  id: 'reports',
59  title: 'Session reports',
60  summary:
61    "The reports this conversation wrote or edited, its own and its subagents', its project documents and anything attached by hand, until dismissed; a report with an HTML page shows the page.",
62  where: 'slash command · a 📎 row above the prompt',
63  commands: [
64    {
65      name: 'reports',
66      description: 'Reports this conversation wrote or attached (no Claude turn)',
67      argumentHint: '[attach <path>…]'
68    }
69  ],
70  tools: []
71} as const satisfies ModFeature;
72
73export const SYNC_FEATURE = {
74  id: 'sync',
75  title: 'Sync progress',
76  summary:
77    "Sync's step, elapsed time and what it is clearing, live while it runs; its report quotes counted numbers instead of a tally.",
78  where: 'above the prompt',
79  commands: [],
80  tools: ['sync_stats']
81} as const satisfies ModFeature;
82
83export const NOTICES_FEATURE = {
84  id: 'notices',
85  title: 'Notices',
86  summary:
87    'The top upgrade or sync nudge, with a button that runs it and one that snoozes it until tomorrow; also the Tab suggestion.',
88  where: 'above the prompt · toast for an alert',
89  commands: [],
90  tools: []
91} as const satisfies ModFeature;
92
93export const QUEUE_FEATURE = {
94  id: 'queue',
95  title: 'Queue a prompt',
96  summary:
97    'Line up prompts while a task runs; each goes out as its own turn once the one before it ends, never mid-task.',
98  where: 'slash command · a ⏳ count above the prompt',
99  commands: [
100    {
101      name: 'queue',
102      description: 'Send a prompt after the current task ends, one per turn',
103      argumentHint: '<prompt> | clear',
104      immediate: true
105    }
106  ],
107  tools: []
108} as const satisfies ModFeature;
109
110export const SETUP_FEATURE = {
111  id: 'setup',
112  title: 'Setup prompt',
113  summary: "In a folder that isn't an agent home yet, a row with a button that runs init; also the Tab suggestion.",
114  where: 'above the prompt',
115  commands: [],
116  tools: []
117} as const satisfies ModFeature;
118
119export const MOD_FEATURES: readonly ModFeature[] = [
120  COMMANDS_FEATURE,
121  MANUALS_FEATURE,
122  REPORTS_FEATURE,
123  SYNC_FEATURE,
124  NOTICES_FEATURE,
125  QUEUE_FEATURE,
126  SETUP_FEATURE
127];
128
shared/cli.ts 22 lines
1// Pure helpers only: the engine follows `$` into functions of the calling file, never across
2// an import, so each feature file makes its own `$` calls and shares just these.
3
4const LOG_LINE = /^\d{4}-\d{2}-\d{2}T/;
5
6/**
7 * The plugin's CLI is `bin/<plugin name minus "agent-">`, the same rule its manifests pin.
8 */
9export const cliArgv = (pluginRoot: string, pluginName: string, args: readonly string[]): string[] => [
10  'bun',
11  `${pluginRoot}/bin/${pluginName.replace(/^agent-/, '')}`,
12  ...args
13];
14
15/**
16 * The CLI's first stderr line that isn't a timestamped log line, else a generic exit message.
17 */
18export const cliError = (stderr: string, args: readonly string[], exitCode: number): Error =>
19  new Error(
20    stderr.split('\n').find((line) => line.trim() && !LOG_LINE.test(line)) ?? `${args.join(' ')} exited ${exitCode}`
21  );
22
commands/done.ts 24 lines
1import type { PromptAutocompleteSuggestion } from 'claude-code';
2
3import type { TaskFrontmatter } from './today';
4import { OPEN_STATUSES } from './today';
5
6const MAX_ROWS = 8;
7
8export const isDoneArgument = (beforeToken: string): boolean => /^\/(?:[\w-]+:)?done\s+$/.test(beforeToken);
9
10/**
11 * Open tasks whose id starts with the token, then those whose title holds it, each in the task list's order.
12 */
13export const doneSuggestions = (tasks: readonly TaskFrontmatter[], token: string): PromptAutocompleteSuggestion[] => {
14  const needle = token.toLowerCase();
15  const open = tasks.filter((task) => OPEN_STATUSES.includes(task.status));
16  const isIdMatch = (task: TaskFrontmatter) => task.id.toLowerCase().startsWith(needle);
17  return [
18    ...open.filter(isIdMatch),
19    ...open.filter((task) => !isIdMatch(task) && task.title.toLowerCase().includes(needle))
20  ]
21    .slice(0, MAX_ROWS)
22    .map((task) => ({ text: task.id, description: task.title }));
23};
24
commands/today.ts 99 lines
1import type { AgendaItem, TodayView } from '../types';
2
3export const OPEN_STATUSES = ['open', 'active'];
4const PRIORITIES = ['P0', 'P1', 'P2', 'P3'];
5const DAY_MS = 86_400_000;
6const HOUR_MS = 3_600_000;
7
8export interface TaskFrontmatter {
9  id: string;
10  title: string;
11  status: string;
12  priority?: string;
13  due?: string;
14}
15
16interface TodayInputs {
17  emoji: string;
18  timezone: string;
19  tasks: readonly TaskFrontmatter[];
20  syncedAt: string | undefined;
21  now: number;
22}
23
24export const STALE_SYNC_HOURS = 72;
25
26export const parseEmoji = (identity: string): string => /\*\*Emoji:\*\*\s*(\S+)/.exec(identity)?.[1] ?? '🤖';
27
28const isoDate = (now: number, timeZone: string): string =>
29  new Intl.DateTimeFormat('en-CA', { timeZone, year: 'numeric', month: '2-digit', day: '2-digit' }).format(now);
30
31const hijriDate = (now: number, timeZone: string): string => {
32  const parts = new Intl.DateTimeFormat('en-u-ca-islamic-umalqura', {
33    timeZone,
34    day: 'numeric',
35    month: 'long',
36    year: 'numeric'
37  }).formatToParts(now);
38  const part = (type: Intl.DateTimeFormatPartTypes) => parts.find((item) => item.type === type)?.value ?? '';
39  return `${part('day')} ${part('month')} ${part('year')}`;
40};
41
42const priorityRank = (priority: string): number => {
43  const rank = PRIORITIES.indexOf(priority);
44  return rank === -1 ? PRIORITIES.length : rank;
45};
46
47/**
48 * Most urgent first: priority, then the latest.
49 */
50const byUrgency = (left: AgendaItem, right: AgendaItem): number =>
51  priorityRank(left.priority) - priorityRank(right.priority) || right.daysLate - left.daysLate;
52
53const toItem = (task: TaskFrontmatter, date: string): AgendaItem => ({
54  id: task.id,
55  priority: task.priority ?? '',
56  title: task.title,
57  daysLate: Math.round((Date.parse(date) - Date.parse(task.due ?? date)) / DAY_MS)
58});
59
60export const buildToday = ({ emoji, timezone, tasks, syncedAt, now }: TodayInputs): TodayView => {
61  const date = isoDate(now, timezone);
62  const open = tasks.filter((task) => OPEN_STATUSES.includes(task.status) && task.due);
63  const syncedMs = syncedAt === undefined ? Number.NaN : Date.parse(syncedAt);
64  return {
65    emoji,
66    dateLabel: new Intl.DateTimeFormat('en-GB', {
67      timeZone: timezone,
68      weekday: 'short',
69      day: 'numeric',
70      month: 'short'
71    }).format(now),
72    hijriLabel: hijriDate(now, timezone),
73    overdue: open
74      .filter((task) => (task.due ?? '') < date)
75      .map((task) => toItem(task, date))
76      .sort(byUrgency),
77    dueToday: open
78      .filter((task) => task.due === date)
79      .map((task) => toItem(task, date))
80      .sort(byUrgency),
81    syncAgeHours: Number.isNaN(syncedMs) ? null : Math.floor((now - syncedMs) / HOUR_MS)
82  };
83};
84
85export const formatAge = (hours: number): string =>
86  hours < 1 ? 'just now' : hours < 48 ? `${hours}h ago` : `${Math.floor(hours / 24)}d ago`;
87
88/**
89 * The one line Claude reads; the transcript draws the agenda from the stored view.
90 */
91export const summarize = (view: TodayView): string => {
92  const ids = (list: readonly AgendaItem[]) => (list.length ? ` (${list.map((item) => item.id).join(', ')})` : '');
93  return [
94    `${view.emoji} ${view.overdue.length} overdue${ids(view.overdue)}`,
95    `${view.dueToday.length} due today${ids(view.dueToday)}`,
96    view.syncAgeHours === null ? 'never synced' : `synced ${formatAge(view.syncAgeHours)}`
97  ].join(' · ');
98};
99