SLOPSHOPPER

Base

Shared Domaine plugin for Claude Code: the Jira, Figma and doc readers, the Jira writer and the review agents, the task workspace and the progress it publishes…

guardcommandtoastprompttoolprocess
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · base
› fix the failing auth test and add an audit log call ╭────────────────────────────────────────────╮ │ base │ ⏺ Read(src/auth.ts) │ base: slim is not loaded — claude plugin │ ⎿ Read 6 lines │ install slim@domaine │ ⏺ 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 › /base-doctor ⎿ base: base doctor — plugin root: /plugins/base ⎿ base: FAIL static scripts/doctor.cjs exited 0: no rows on stdout ⎿ base: FAIL slim-live slim is not loaded — claude plugin install slim@domaine; base refuses its readers until it ⎿ base: FAIL conventions not delivered: no SessionStart command hook marker in /Users/dev/.claude/domaine/log/previe ⎿ base: FAIL mcp base's manifest is unreadable: no server to check ⎿ base: SKIP connectors none attached — base's own servers serve Jira, Notion and Figma ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts
README

base

base is the shared Domaine plugin for Claude Code. It holds the tools that every team uses. A team plugin (frontend, backend, QA) depends on base and adds its own skills on top. To install it, see Quick install (Claude Code) in the root README.

base contains these parts:

  • the readers, which turn a Jira ticket, a Figma frame or a linked doc into workspace files;
  • the Jira writer and the review agents;
  • the task workspace and the progress that base publishes for band;
  • the commit and review guards;
  • the working conventions, a doctor, and the MCP servers that the agents call.

base requires slim and reads large results through it. Only slim compresses, so every figure goes to slim's log. base's readers call slim's view tool for a file or a command output.

Current release: base v0.15.0.

Status

  • base runs in Claude Code only. It is a plugin of skills, agents, MCP servers and a hooks module (mods). It ships no adapter for another host, and scripts/install.sh --plugin base exits 2.
  • base requires slim ("dependencies": ["slim"] in its manifest). The engine does not install a dependency on its own, so install both.

Install

/plugin marketplace add domaine-oleksandr-kever/claude-plugins
/plugin install slim@domaine
/plugin install band@domaine
/plugin install base@domaine
/reload-plugins

Then run /base-doctor to check the install (§ Doctor). Next, install the team plugins for your work. Each team plugin has its own doctor:

To enable the same set through settings, put this in ~/.claude/settings.json:

{
  "enabledPlugins": {
    "slim@domaine": true,
    "band@domaine": true,
    "base@domaine": true
  }
}

base:jira-reader gives every downloaded screenshot and screen recording to slim's view. view writes the resized copy (or the frames) beside the file in .claude/tasks/<work-id>/tmp/attachments/, or in .claude/base-tmp/<KEY>/ when the reader was given no workspace path; that dir is swept after BASE_TMP_TTL hours. If the permission check would ask about that write, slim asks you once per file (Yes/No). To skip the question, add allow rules for both dirs to the project's .claude/settings.json:

{ "permissions": { "allow": ["Write(.claude/tasks/**)", "Write(.claude/base-tmp/**)"] } }

Resizing and frame cutting need ffmpeg + ffprobe on PATH. macOS sips covers images only. Without these tools, the files stay downloaded but are not resized, and the reader says so in its attachments_note. Claude then looks at an image the task needs through one read of the original, never a batch of them; a recording without frames cannot be looked at.

Agents

Spawn each agent by its qualified name (base:<agent>). When two plugins ship agents, a bare name does not resolve.

AgentDoesModel
base:jira-readerreads one ticket — fields, comments, attachments — writes ticket.md and comments.md to the workspace; downloads images and recordings (into the workspace, else .claude/base-tmp/<KEY>/), resizes them through slim's viewsonnet
base:figma-readerreads one Figma node through a Figma MCP or the REST API, writes figma-<node-id>.md; the REST tree is compacted by slim's viewsonnet
base:doc-readerreads one linked doc (Notion, Confluence, web) and writes a task-focused extractsonnet
base:jira-writerwrites one approved value to one Jira field or comment, converted to ADF, and reads it backsonnet
base:bug-hunteradversarial correctness review of the branch's diffopus
base:change-reviewercomment accuracy, refactors and rule conformance on the changed files; the profile and its team rules come in the briefopus

The three readers need slim. They read big MCP results that slim's mcp channel compacts, and they call mcp__slim__view for files on disk. If slim is not loaded, base refuses to spawn them.

The readers and the writer reach Jira, Confluence, Notion and Figma through any server that serves the tool: a claude.ai connector first, then base's own server, then a token script (Figma's REST API, Jira's attachment downloads). They load a tool by its tool name, never by a server name, as a connector's server name is the host's to choose. They run without a tools: allowlist, for an allowlist can name only exact servers. Their disallowedTools: removes Edit, NotebookEdit, Agent and Task, the built-ins each role leaves out (Skill and WebFetch/WebSearch for jira-reader; Skill for doc-reader; Skill, Write, Glob, Grep, WebFetch and WebSearch for the writer; WebFetch/WebSearch for figma-reader), the base servers each does not use, whole, and the write tools of the base servers it does use. On any other server the MCP guard refuses those writes and every server out of the agent's scope (Guards).

References and scripts

The agents cite these files by their path under the plugin root. tests/base-refs-lint.sh checks that every cited path exists.

FileHolds
references/jira-field-ids.md, references/jira-custom-fields.mdthe meetdomaine site's custom-field ids, the request shape, and how to rediscover an id
references/jira-freshness-check.mdbase:jira-reader's cached-ticket check (changelog first, comment-only refresh)
references/jira-attachments.mdthe read-only Jira token, scripts/jira-attachments.sh, scripts/external-screenshots.sh, and the resize through view
references/jira-reader-attachments.mdbase:jira-reader's download steps, read only when a ticket has attachments or linked screenshots
references/jira-adf-write.mdwriting ADF to a field or a comment, scripts/md-to-adf.cjs, the read-back check
references/figma-rest.mdthe Figma source ladder, the REST token, scripts/figma-rest.sh, the compact tree through view
references/figma-reader-rest.mdbase:figma-reader's rung-3 steps, read only when the ladder lands on REST
references/reading-linked-docs.mdwhich links a caller reads and with which reader
references/task-workspace.md, references/task-workspace-freshness.mdthe .claude/tasks/<work-id>/ layout, its read and write rules, progress.md, the freshness probes
references/review-flow.mdthe branch review flow: the .git/.base-review marker, which agent runs which check
references/commit-message-format.mdConventional Commits with the house rules
references/steps-to-test-format.mdthe Steps to Test field's General and Bug templates and the theme resolution: what a team plugin's Steps to Test writer writes and /qa:preflight reads rows from — an index; the sections are in references/steps-to-test/ (templates, item-rules, shape-and-size, theme-resolution, self-check)
references/break-it-qa.mdthe break-it QA method: deriving and executing the hostile-value and timing rows of a team plugin's QA and of /qa:preflight
references/shopify-recipes.md/base:shopify's Admin GraphQL recipes, validated on API 2026-10 with their scopes and how to read each answer; the PDP "why does X not show" checklist; the metafieldsSet and productUpdate templates
references/shopify-custom-data.mdmetafield and metaobject rules: $app vs merchant namespaces, definitions, metafieldsSet writes, metaobject ACTIVE status, reference metafields
references/shopify-analytics.mdShopifyQL through shopifyqlQuery: the wrapper, parseErrors, read_reports, example statements

The fetchers (scripts/jira-attachments.sh, scripts/external-screenshots.sh, scripts/figma-rest.sh) share scripts/_common.sh. Credentials go in a private 0600 curl config, never in the argv. Every download goes to a directory that git ignores. The fetchers only download; slim resizes and compacts.

ScriptRun byDoes
scripts/md-to-adf.cjsbase:jira-writerMarkdown → ADF for a Jira field or comment
scripts/review-scope.sh/base:pre-commit-review, /base:commit, a team plugin's PR gatethe review scope and its diff_hash for the .git/.base-review marker: merge-base to working tree, untracked files included, build-dirtied rewrites kept out; --check prints one line `marker=fresh\stale\other-branch\none (the marker against this branch and scope) for /base:commit`'s gate
scripts/worktree-setup.sh/base:worktreecreates or removes a sibling git worktree with its own branch and dev port, the .claude/tasks link back to the main checkout, and the --copy list
scripts/doctor.cjs/base-doctor, or by handthe static install checks (below); --json for the command
scripts/edit-delegation.cjshooks/conventions.cjs, scripts/doctor.cjsthe edit-delegation model from the login record and BASE_EDIT_MODEL (one place decides): a module, no CLI
scripts/scratch-hygiene.cjsbase's hooks module, once per sessionsweeps .claude/base-tmp of files older than BASE_TMP_TTL hours and keeps it in .git/info/exclude
scripts/qa-stores.cjsa QA engineer by hand; /qa:preflight reads itthe QA store registry, one file per machine (~/.config/domaine/qa-stores.json, dir 0700, file 0600): list, get <store> (the only command that prints a password; `--field password\alias\defaultTheme\domain\notes prints that one value raw, nothing for a field the store lacks), find, set, unset, path`
scripts/shopify-validate.cjs/base:shopify where no dev-mcp server is loaded (a cloud session)validates one Admin GraphQL document through npx -y @shopify/dev-mcp@latest over stdio: --file, --code or stdin, --version (default 2026-10); prints `result=valid\invalid\unavailable and the server's detail text; exit 0 / 1 / 3 (unavailable: send the operation anyway), 2 = usage; a timeout before the server speaks leaves npx to finish its install instead of killing it, and error=server_exited_early names the _npx` dir to delete

Skills

Invoke each skill by its qualified name (/base:<skill>). A team plugin's skills call them by the same names.

SkillDoes
/base:commita Conventional Commits commit, directly — only on a reviewed tree: no fresh .git/.base-review marker for this branch and diff (review-scope.sh --check) → runs /base:pre-commit-review first; the developer's own "commit without review" request in the same turn (not negated) is the only bypass; offers a ticket scope
/base:pre-commit-reviewthe branch review before a commit: ticket references and untracked files inline, base:change-reviewer for comments, refactors and rules, base:bug-hunter for correctness; a plan to approve, then the agreed edits and the marker. The caller passes the profile word its team plugin names (none without one)
/base:save-task-contextwrites what the conversation holds into .claude/tasks/<work-id>/ — ticket fields, comments, decisions, progress.md in the team's series order — without spawning a reader
/base:report-plugin-issuedrafts a sanitized GitHub issue for a base defect, with the /base-doctor output and the base.events tail, and posts it after your approval
/base:worktreea sibling git worktree on feat/<work-id> with its own dev port, sharing the task workspace; --remove tears it down
/base:shopifystore questions and Admin GraphQL: a routing table to the recipes, answers with evidence (field, value, file key), validation through a remote store connector's own validate tool, the dev-mcp validate tool or scripts/shopify-validate.cjs (never blocking), a mutation only after a "yes" in a separate turn, then a runner table: Shopify CLI store execute, a remote store connector, an Admin token, or a ready .graphql file for GraphiQL

/base:worktree copies .env into a new worktree, because base's fetchers read their credentials from it. It also copies every path that a team plugin names in its convention section, on one line:

worktree copy list: <path>[, <path>…]

The paths are repo-relative files or directories, separated by , . The skill passes each path to scripts/worktree-setup.sh as --copy <path>. The script refuses .git, .claude, .claude/tasks and .claude/settings.local.json. A team step that must follow, such as a per-worktree config to adjust, runs from the team plugin's own skill.

The worktree's .claude/settings.local.json (its own, else copied from the main checkout, else created) lists the main checkout's .claude/tasks under permissions.additionalDirectories. A write through the .claude/tasks link resolves outside the worktree, and without that entry Claude Code asks for permission on every one. With it, a write there is treated like any other .claude/ write: auto mode hands it to the classifier, and Manual and accept-edits modes still ask, because .claude is a protected path. The script merges the entry into the other keys, writes it atomically, stamps the file into info/exclude, and never rewrites a file that is not valid JSON (warn=settings_local_invalid_json).

Commands

base's hooks module registers these commands at each session start.

CommandDoes
/base-doctorchecks the install (Doctor)
/base-progresspins or unpins the work id band's checklist shows (Workspace)
/base-defectsonly in dogfood mode: lists the plugin defects reported, newest first (Dogfood mode)
/base-edit-directallows direct project-file edits for this session id (never a read of a drafter's draft), while edit delegation is on (Guards); typed at the prompt only, a run another plugin queues grants nothing

Conventions

The working conventions reach the model through one channel on every login: Claude Code command hooks in hooks/hooks.json, which run hooks/conventions.cjs. (On the Claude Team login, Claude Code skips the mod events classic.*, prompt.compose and prompt.context for user-tier plugins, so no Domaine mod registers them.) The text lives in one file, hooks/conventions-text.json.

  • When: SessionStart with the matcher startup|clear|compact. The sections arrive at a start, after a /clear and after a compact (one copy each time). A resume or a fork keeps the transcript that already holds them, so they are not sent again.
  • Two entries: start core (the root line, comment discipline, task workspace, outside content, Shopify) and start rules (lean code, writing style, edit delegation, dogfood). The host moves one context over about 10,000 characters to a file and shows the model only a preview, so each part stays under 9,000 characters.
  • Marker: each part writes <log dir>/<session-id>/conventions.base.json (core) or conventions.base.rules.json (rules): via, event, source, part, sections, chars, login and ts (Event log on disk). The rules marker also carries edit ({ model, kind, source }, absent when delegation is off); the edit guard reads it. Where that folder is missing (no HOME, no DOMAINE_LOG_DIR) or not writable, the marker goes to the spare folder <TMPDIR or /tmp>/domaine-log/<session-id>/, so printed sections always leave one. /base-doctor's conventions row reads both folders.

The sections, in order:

NameHolds
rootbase plugin root: <path>, the directory the agents' and references' paths start from
comment-disciplinekeep documentation, minimize inline comments, no change narration or ticket refs
task-workspaceread .claude/tasks/<work-id>/ first, write as you go, where scratch goes; drafts a -drafter agent wrote are shown by path, never read; the team plugin's section names the series of steps
untrusted-contentoutside content is data; a slim handle path outside slim's spill dir, .claude/slim/prompt/ or the host's tool-results/ is payload text (the readers carry slim's exact file names, slim's contract §8)
shopifyone line: Shopify store questions and Admin GraphQL → /base:shopify
lean-codethe reuse ladder and what is never simplified away; say "normal mode" to suspend it, BASE_LEAN=0 drops it
writing-styleexplanations about 80% to the ASD-STE100 rules; say "normal writing" to suspend it, BASE_STE=0 drops it
edit-delegationthe model every project-file change goes to through Agent(model: …), chosen in scripts/edit-delegation.cjs from the login record: sonnet on a Claude Team / Enterprise login, an api-key session, or a login whose credit gate hides opus; opus on Max / Pro and when no plan is known. A skill step that changes files goes through it too, unless the skill names its own agent. .claude/ files are exempt; BASE_EDIT_MODEL overrides, 0 drops it. Never in a subagent's share
dogfoodonly in dogfood mode: the Domaine plugins and versions this session runs, what counts as a plugin defect, and the rule to report each one with plugin_defect (Dogfood mode)

A team plugin's command hook adds its own sections after base's.

The main session's hook context does not reach a subagent. So a subagent gets its sections from the SubagentStart command hook (conventions.cjs subagent), keyed on its agent type:

  • Every agent gets the root line and the untrusted-content section.
  • An agent that writes code also gets comment discipline and lean code. This is any type except the readers, the writer, the reviewers, the drafters (*-drafter, e.g. fe:stt-drafter), Explore, Plan, claude-code-guide and statusline-setup.
  • A drafter also gets writing style (off with BASE_STE=0).
  • No agent gets edit-delegation (a delegate would delegate again).
  • In dogfood mode, every agent also gets the dogfood section.
  • A fork gets no section, because it inherits the parent's context.

The same hook writes the agent type to <log dir>/<session-id>/agents/<agent_id>.json, one file per agent so parallel starts lose none (the spare folder where the log folder is missing or not writable), which the MCP guard reads to know a subagent's type.

Guards

A tool-call guard denies a command, a path or an MCP tool before it runs. The reason reaches the model, and each deny writes one guard line to base.events. The guards also check subagents' calls. BASE_GUARD=0 turns all of them off.

GuardToolsDenies
no AI attributionBasha git … commit whose message carries a Claude or Anthropic co-author trailer or a "Generated with Claude" line; a human Co-Authored-By passes
no git-hooks bypassBash--no-verify (-n on a commit) on commit, push, merge, pull, am and rebase in any spelling, a core.hooksPath or HUSKY=0 override, an alias that carries the flag, and a command that removes, empties or rewrites a hook file before a commit; hooks/no-verify-bypass.sh decides, run only for a command naming a git verb
MCP precedencethe tools of base's atlassian, notion-mcp and figma-dev-mode servers (mcp__plugin_base_<server>__<tool>), in the main loop and in subagentsthe first call of such a tool in a session while a server that is no plugin's (a claude.ai connector, a user-scope server) lists both the same tool and the server's signature tool (getJiraIssue, notion-fetch, get_design_context), so a shared generic name such as search or authenticate makes no twin: the deny names that tool to call instead, and the same call is allowed after this one refusal (base.mcpSoft), so a connector that needs sign-in strands nobody. A tool list that fails lets the call run
reader writesthe Jira, Confluence and Notion write tools of any MCP server (slim's and base's registered tools aside), in a subagentevery write for base:jira-reader, base:doc-reader and base:figma-reader; every write but editJiraIssue and addCommentToJiraIssue for base:jira-writer; every write for a subagent with no agents/<agent_id>.json record (fail closed: the deny says no agent-type marker for this subagent); other agent types and the main loop are not limited. A probe of the file that fails lets the call run
reader scopeevery MCP tool but slim's and base's registered ones, in a subagent of base's reader or writer typesa call on a server that lists no signature tool of the agent's vendors: getJiraIssue for jira-reader and the writer, getJiraIssue or notion-fetch for doc-reader, get_design_context for figma-reader (base's own server of that vendor always counts), so a connector the session holds for other work (a store, a docs editor, a browser) stays out of reach of a reader fed untrusted text. A tool list that fails lets the call run
edit delegationWrite, Edit, NotebookEdit in the main loop (no agentId) on a file under the session root outside .claude/, while the rules marker names a modelrefused with the Agent(model: …) pointer every time, unless the session already runs on that family or a cheaper one (haiku < sonnet < opus < fable), the developer ran /base-edit-direct this session, or BASE_GUARD=0; allowed edits are counted (base.mainEdits, the doctor's delegate row, one delegate log line per file). A main-loop Bash write (sed -i, redirection, tee, git apply, patch) not naming .claude/, /tmp/ or /dev/ is counted, never refused. The marker is read once per session id
drafter draftsa main-loop read (no agentId) of a drafter's draft — .claude/tasks/<id>/steps-to-test.md, pr-body.md, jira-comment.md — by Read, Grep, slim's view, or a Bash command naming one, directly or through a variable it assigns (drafter-check.cjs, gh pr … --body-file, test -s, ls and the bare assignment P=<draft> stay allowed), whenever base runs: on any model, with or without the rules markerrefused with the drafter-rule pointer (show its path, change it through the same agent) every time — /base-edit-direct, a session on the delegate's family or cheaper and BASE_EDIT_MODEL=0 do not lift it; only BASE_GUARD=0 does. Each refusal counts in base.mainEdits.refused and logs one guard line
scratch paththe browser tools that take a file path (take_screenshot, browser_take_screenshot, take_snapshot, get_network_request, browser_run_code_unsafe) of any MCP servera path outside the project (chrome-devtools also accepts its OS temp dir), or inside it outside .claude/ (the task workspace's tmp/, .claude/tmp/, .claude/base-tmp/); in a git worktree, a path into the shared task workspace. hooks/scratch-path-guard.cjs decides against the project root the session launched in (base.guardRoot), names an absolute path to use instead and creates its directory. The tools' descriptions carry the rule too. BASE_SCRATCH_GUARD=0 turns this one off

base's playwright server writes its own files under .claude/base-tmp/playwright. When the guard allows a write there, it adds /.claude/base-tmp/ to .git/info/exclude. If a guard cannot run (its script fails or times out), it lets the call through.

Workspace

base resolves a work id and publishes its task workspace as $.state atoms (shared state values). band draws them in its checklist and Log panes. Any plugin reads the atoms; only base writes them.

base picks the work id in this order:

  1. The pinned id, when its .claude/tasks/<id>/ exists.
  2. The last ticket that a person's prompt named. A Jira /browse/ URL corroborates a key, and so does a project that already has a `.claude/
Source 17 files
hooks/mods/register.ts 27 lines
1// base hooks module (Claude Code only): the workspace progress band draws and its autosave, the install checks, the guards,
2// the doctor, the event log on disk and dogfood mode; it adopts the title and reads the conventions markers that
3// hooks/title.cjs and hooks/conventions.cjs write. base writes only base.* atoms.
4// Each feature file declares its own atoms and keeps its `$` code to itself: the validator follows `$` only within one file.
5import type { Register } from 'claude-code'
6import { registerDoctor } from './doctor.ts'
7import { registerDogfood } from './dogfood.ts'
8import { registerBashGuards } from './guards/bash.ts'
9import { registerEditGuard } from './guards/edit.ts'
10import { registerMcpGuards } from './guards/mcp.ts'
11import { registerScratchGuard } from './guards/scratch.ts'
12import { registerSession } from './session.ts'
13import { registerAutosave } from './workspace/autosave.ts'
14import { registerProgress } from './workspace/progress.ts'
15
16export const register: Register = (on) => {
17  registerSession(on)
18  registerProgress(on)
19  registerAutosave(on)
20  registerBashGuards(on)
21  registerScratchGuard(on)
22  registerMcpGuards(on)
23  registerEditGuard(on)
24  registerDoctor(on)
25  registerDogfood(on)
26}
27
hooks/mods/doctor.ts 365 lines
1// /base-doctor and the sweeps of base-tmp and of old event-log directories (once per session id; a /clear starts
2// a new one). The doctor runs scripts/doctor.cjs for what a node process sees and adds what only a session answers:
3// slim's view tool, each MCP server of base's manifest connected, the connectors serving the same tools; then the
4// tail of base.events.
5import { atom, read, update } from 'claude-code'
6import type { EngineInterface, On } from 'claude-code'
7import type { BaseEvent, BaseMainEdits } from '../../types'
8import { LOG_TTL_MS, defaultLogRoot, logDir, logLine, pushEvent, spareRoot } from './events.ts'
9import type { Disk } from './events.ts'
10import { SLIM_MISSING, SLIM_VIEW } from './session.ts'
11import { WINDOW_DAYS, dogfoodMode, enabledNames, loginAccount, loginFile, recent, seen } from './dogfood/text.ts'
12import { SIGNATURE, twinServers } from './guards/mcp.ts'
13
14export const COMMAND = {
15  name: 'base-doctor',
16  description: 'Check the base install: node, manifest, slim, MCP servers, base-tmp, event log',
17  immediate: true,
18} as const
19export const MCP_TIMEOUT_MS = 15_000
20const TAIL = 10
21/** The Figma desktop app serves it locally; base:figma-reader falls back to the REST API without it. */
22const LOCAL_SERVER = 'figma-dev-mode'
23
24type Status = 'PASS' | 'FAIL' | 'SKIP' | 'WARN'
25export type Row = { status: Status; name: string; detail: string }
26
27const swept = atom({ plugin: 'base', key: 'swept' } as const, null)
28const events = atom({ plugin: 'base', key: 'events' } as const, [] as BaseEvent[])
29// Written in session.ts (the first prompt's slim check).
30const checked = atom({ plugin: 'base', key: 'checked' } as const, null)
31// Written in guards/edit.ts: this session's main-loop project-file changes.
32const mainEdits = atom({ plugin: 'base', key: 'mainEdits' } as const, null as BaseMainEdits | null)
33/** The Domaine plugins whose SessionStart command hook writes a conventions marker. */
34const MARKED = ['base', 'fe', 'qa', 'be', 'pm'] as const
35
36type $ = EngineInterface
37
38/** events.ts's file writer reaches `$` through this: the validator follows `$` only within one file. */
39function diskOf($: $): Disk {
40  return {
41    session: () => $.session.id(),
42    home: () => $.env.get('HOME'),
43    override: () => $.env.get('DOMAINE_LOG_DIR'),
44    manifest: () => $.fs.read(`${$.plugin.root}/.claude-plugin/plugin.json`),
45    read: path => $.fs.read(path),
46    write: (path, text) => $.fs.write(path, text),
47    toast: text => $.ui.toast(text),
48  }
49}
50
51/** Claude Code's session ids: the sweep touches nothing else, so no dotfile or other directory ever goes. */
52const SESSION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
53
54/**
55 * Removes the session directories under `$HOME/.claude/domaine/log` whose newest file is older than 7 days:
56 * never this session's, only a session-id name holding nothing but `*.jsonl` and `*.json` files, and never when the root
57 * or the directory resolves anywhere but its own spelling (a linked root could point at `~`). `$.fs` has no
58 * delete, hence `rm -rf`. A DOMAINE_LOG_DIR is the person's to clean.
59 */
60async function sweepLogs($: $, sid: string): Promise<void> {
61  const root = defaultLogRoot(await $.env.get('HOME'))
62  if (!root) return
63  if ((await $.fs.stat(root, { resolve: true })).realPath !== root) return
64  const now = await $.clock.now()
65  for (const d of await $.fs.list(root)) {
66    if (d.kind !== 'dir' || d.name === sid || !SESSION_ID.test(d.name)) continue
67    const dir = `${root}/${d.name}`
68    try {
69      const entries = await $.fs.list(dir)
70      if (entries.some(f => f.kind !== 'file' || !/\.jsonl?$/.test(f.name))) continue
71      const newest = entries.length ? Math.max(...entries.map(f => f.mtimeMs)) : (await $.fs.stat(dir)).mtimeMs
72      if (now - newest <= LOG_TTL_MS) continue
73      if ((await $.fs.stat(dir, { resolve: true })).realPath === dir) await $.process.run(['rm', '-rf', dir], { timeoutMs: 10_000 })
74    } catch {}
75  }
76}
77
78/**
79 * The command on every session start (a reload or a re-enable drops it) and at the first prompt of a new
80 * session id; the sweeps of `.claude/base-tmp` past BASE_TMP_TTL hours and of the old event-log session
81 * directories once per session id, unawaited.
82 */
83async function arm($: $, start: boolean): Promise<void> {
84  try {
85    const sid = String(await $.session.id())
86    const fresh = (await read($, swept)) !== sid
87    if (start || fresh) await $.command.register(COMMAND).catch(() => undefined)
88    if (!fresh) return
89    await update($, swept, () => sid)
90    const argv = ['node', `${$.plugin.root}/scripts/scratch-hygiene.cjs`, '--sweep', await $.session.root()]
91    const ttl = await $.env.get('BASE_TMP_TTL')
92    if (ttl) argv.push('--ttl-hours', ttl)
93    void $.process.run(argv, { timeoutMs: 10_000 }).catch(() => undefined)
94    void sweepLogs($, sid).catch(() => undefined)
95  } catch {}
96}
97
98const STATUSES = new Set(['PASS', 'FAIL', 'SKIP', 'WARN'])
99
100/** doctor.cjs --json rows, or null when its stdout is not that shape. */
101export function parseStatic(stdout: string): Row[] | null {
102  try {
103    const rows = (JSON.parse(stdout) as { rows?: unknown }).rows
104    if (!Array.isArray(rows)) return null
105    return rows.filter(
106      (r): r is Row => !!r && STATUSES.has(r.status) && typeof r.name === 'string' && typeof r.detail === 'string',
107    )
108  } catch {
109    return null
110  }
111}
112
113async function staticRows($: $): Promise<Row[]> {
114  const root = $.plugin.root
115  let r
116  try {
117    const argv = ['node', `${root}/scripts/doctor.cjs`, '--json', '--root', root, '--project', await $.session.root()]
118    const dir = logDir(await $.env.get('HOME'), await $.env.get('DOMAINE_LOG_DIR'), await $.session.id())
119    if (dir) argv.push('--log-dir', dir)
120    r = await $.process.run(argv, { timeoutMs: 30_000 })
121  } catch (err) {
122    const why = err instanceof Error ? err.message : String(err)
123    return [{ status: 'SKIP', name: 'static', detail: `scripts/doctor.cjs did not run (${why}): the static checks need node and the Claude Code CLI` }]
124  }
125  const rows = parseStatic(r.stdout)
126  if (rows?.length) return rows
127  const why = (r.stderr.trim().split('\n')[0] ?? '') || 'no rows on stdout'
128  return [{ status: 'FAIL', name: 'static', detail: `scripts/doctor.cjs exited ${r.exitCode}: ${why}` }]
129}
130
131type Marker = { source?: unknown; login?: { label?: unknown; file?: unknown } }
132
133/** The conventions markers the SessionStart command hooks wrote for this session in the log dir or the spare dir, by file stem (`base`, `base.rules`, `fe`, …). */
134async function markers($: $, dirs: string[]): Promise<Map<string, Marker>> {
135  const out = new Map<string, Marker>()
136  for (const stem of [...MARKED, 'base.rules']) {
137    for (const dir of dirs) {
138      try {
139        out.set(stem, JSON.parse(await $.fs.read(`${dir}/conventions.${stem}.json`)) as Marker)
140        break
141      } catch {}
142    }
143  }
144  return out
145}
146
147async function conventionsRow($: $, dirs: string[], found: Map<string, Marker>, prompted: boolean): Promise<Row> {
148  if (!dirs.length) return { status: 'SKIP', name: 'conventions', detail: 'no log directory for this session id: the SessionStart command hook markers cannot be read' }
149  if (!found.size) {
150    return prompted
151      ? { status: 'FAIL', name: 'conventions', detail: `not delivered: no SessionStart command hook marker in ${dirs.join(' or ')} (hooks/hooks.json → hooks/conventions.cjs)` }
152      : { status: 'SKIP', name: 'conventions', detail: 'no prompt sent yet: send one, then run the doctor again' }
153  }
154  const enabled = new Set(['base', ...enabledNames(await $.settings.read().catch(() => null))])
155  const has = (p: string) => found.has(p) || (p === 'base' && found.has('base.rules'))
156  // A claude.ai sandbox's synced plugins have no enabledPlugins entry: a plugin's event log shows it loaded.
157  const loaded = new Set<string>()
158  for (const p of MARKED) {
159    if (enabled.has(p) || has(p)) continue
160    if ((await Promise.all(dirs.map(d => $.fs.exists(`${d}/${p}.jsonl`).catch(() => false)))).some(Boolean)) loaded.add(p)
161  }
162  const want = MARKED.filter(p => enabled.has(p) || loaded.has(p) || has(p))
163  const label = (p: string) => (p === 'base' ? `base ${[found.has('base') && 'core', found.has('base.rules') && 'rules'].filter(Boolean).join('+')}` : p)
164  const source = (found.get('base') ?? [...found.values()][0])?.source
165  const login = found.get('base')?.login
166  const who = typeof login?.label === 'string' ? ` (login: ${login.label}, ${typeof login.file === 'string' ? login.file : '?'})` : ''
167  const head = `SessionStart command hook (${typeof source === 'string' ? source : '?'}): ${want.filter(has).map(label).join(', ')}${who}`
168  const missing = want.filter(p => !has(p))
169  return missing.length
170    ? { status: 'WARN', name: 'conventions', detail: `${head}; no marker from ${missing.map(p => `${p} (${enabled.has(p) ? 'enabled' : 'loaded'})`).join(', ')}` }
171    : { status: 'PASS', name: 'conventions', detail: head }
172}
173
174async function liveRows($: $): Promise<Row[]> {
175  const rows: Row[] = []
176  try {
177    rows.push((await $.tool.list()).some(t => t.name === SLIM_VIEW)
178      ? { status: 'PASS', name: 'slim-live', detail: `${SLIM_VIEW} registered` }
179      : { status: 'FAIL', name: 'slim-live', detail: `${SLIM_MISSING}; base refuses its readers until it is` })
180  } catch {
181    rows.push({ status: 'SKIP', name: 'slim-live', detail: 'the tool list did not answer' })
182  }
183  try {
184    const sid = String(await $.session.id())
185    const prompted = (await read($, checked)) === sid
186    const dirs = [logDir(await $.env.get('HOME'), await $.env.get('DOMAINE_LOG_DIR'), sid), logDir(undefined, spareRoot(await $.env.get('TMPDIR')), sid)]
187      .filter((d): d is string => d !== null)
188    rows.push(await conventionsRow($, dirs, await markers($, dirs), prompted))
189  } catch {
190    rows.push({ status: 'SKIP', name: 'conventions', detail: 'the state did not answer' })
191  }
192  return rows
193}
194
195const dogfoodOn = async ($: $) => {
196  const sw = (await $.env.get('BASE_DOGFOOD')) ?? ''
197  if (sw === '1' || sw === '0') return sw === '1'
198  const file = loginFile(await $.env.get('HOME'), await $.env.get('CLAUDE_CONFIG_DIR'))
199  const account = (await $.env.get('CLAUDE_CODE_ACCOUNT_UUID'))?.trim() || loginAccount(file && (await $.fs.read(file).catch(() => null)))
200  return dogfoodMode(sw, account, await $.fs.read(`${$.plugin.root}/dogfood.json`).catch(() => null))
201}
202
203/** Dogfood mode's reports of the last 7 days, the home index and this project's folder together; no row when it is off. */
204async function defectRows($: $): Promise<Row[]> {
205  if (!(await dogfoodOn($))) return []
206  try {
207    const home = (await $.env.get('HOME'))?.trim() ?? ''
208    const index = home.startsWith('/') ? await $.fs.read(`${home.replace(/\/+$/, '')}/.claude/plugin-defects/index.md`).catch(() => '') : ''
209    const dir = `${await $.session.root()}/.claude/plugin-defects`
210    const names = (await $.fs.list(dir).catch(() => [])).filter(f => f.kind === 'file').map(f => f.name)
211    const week = recent(seen(index as string, dir, names), await $.clock.now())
212    return [week.length
213      ? { status: 'WARN', name: 'defects', detail: `${week.length} in ${WINDOW_DAYS} days, newest ${week[0]!.title} (/base-defects lists them)` }
214      : { status: 'PASS', name: 'defects', detail: `none in ${WINDOW_DAYS} days` }]
215  } catch {
216    return [{ status: 'SKIP', name: 'defects', detail: 'the reports did not answer' }]
217  }
218}
219
220/** The connection row, naming the servers that are no plugin's and serve the same tools: they take precedence. */
221async function connectRow($: $, server: string, names: readonly string[]): Promise<Row> {
222  const row = await connect($, server)
223  const twins = twinServers(names, server).join(', ')
224  if (!twins) return row
225  return row.status === 'PASS'
226    ? { ...row, detail: `${row.detail} — ${twins} takes precedence` }
227    : { status: 'WARN', name: row.name, detail: `${row.detail} — ${twins} serves the same tools and takes precedence` }
228}
229
230/** The connectors serving what base's own Atlassian, Notion and Figma servers serve. */
231function connectorsRow(names: readonly string[] | null): Row {
232  if (names === null) return { status: 'SKIP', name: 'connectors', detail: 'the tool list did not answer' }
233  const found = Object.entries(SIGNATURE)
234    .map(([server, [, vendor]]) => [vendor, twinServers(names, server).join(', ')] as const)
235    .filter(([, twins]) => twins)
236  return found.length
237    ? { status: 'PASS', name: 'connectors', detail: found.map(([vendor, twins]) => `${vendor}: ${twins}`).join('; ') }
238    : { status: 'SKIP', name: 'connectors', detail: "none attached — base's own servers serve Jira, Notion and Figma" }
239}
240
241async function connect($: $, server: string): Promise<Row> {
242  const name = `mcp:${server}`
243  const timeout = $.clock.sleep(MCP_TIMEOUT_MS).then(() => null)
244  let r
245  try {
246    r = await Promise.race([$.mcp.connect(server), timeout])
247  } catch (err) {
248    return { status: 'FAIL', name, detail: err instanceof Error ? err.message : String(err) }
249  }
250  if (r === null) return { status: 'FAIL', name, detail: `no answer in ${MCP_TIMEOUT_MS / 1000} s` }
251  if (r.isConnected) return { status: 'PASS', name, detail: `connected as ${r.server}` }
252  if (server === LOCAL_SERVER) {
253    return { status: 'WARN', name, detail: `${r.message} — the Figma desktop app serves it (Dev Mode); base:figma-reader falls back to the REST API` }
254  }
255  if (r.reason === 'disabled') return { status: 'WARN', name, detail: `turned off: ${r.message}` }
256  if (r.reason === 'auth') return { status: 'FAIL', name, detail: `needs sign-in — /mcp, then authenticate ${server}: ${r.message}` }
257  return { status: 'FAIL', name, detail: `${r.reason}: ${r.message}` }
258}
259
260/** One row per server in base's own manifest, connected in parallel, then the `connectors` row. */
261async function mcpRows($: $): Promise<Row[]> {
262  const names = await $.tool.list().then(l => l.map(t => t.name), () => null)
263  const tail = connectorsRow(names)
264  let servers: string[]
265  try {
266    const manifest = JSON.parse(await $.fs.read(`${$.plugin.root}/.claude-plugin/plugin.json`)) as { mcpServers?: unknown }
267    servers = manifest.mcpServers && typeof manifest.mcpServers === 'object' ? Object.keys(manifest.mcpServers) : []
268  } catch {
269    return [{ status: 'FAIL', name: 'mcp', detail: "base's manifest is unreadable: no server to check" }, tail]
270  }
271  if (!servers.length) return [{ status: 'SKIP', name: 'mcp', detail: 'no mcpServers in the manifest' }, tail]
272  return [...(await Promise.all(servers.map(s => connectRow($, s, names ?? [])))), tail]
273}
274
275/**
276 * A static `slim` FAIL for a slim that is loaded anyway (a `--plugin-dir` load has no install record)
277 * reads as a warning: the session has what base needs.
278 */
279export function reconcile(rows: Row[]): Row[] {
280  const live = rows.find(r => r.name === 'slim-live')?.status === 'PASS'
281  return rows.map(r =>
282    live && r.name === 'slim' && r.status === 'FAIL' && r.detail.startsWith('not installed')
283      ? { status: 'WARN', name: 'slim', detail: 'not in installed_plugins.json, yet loaded this session (a --plugin-dir load?)' }
284      : r,
285  )
286}
287
288/** The static `delegate` row plus this session's main-loop file changes under the root (guards/edit.ts counts them). */
289export function withMainEdits(rows: Row[], m: BaseMainEdits | null, sid: string): Row[] {
290  if (!m || m.sid !== sid) return rows
291  const parts = [`${m.n} tool edit(s) in ${m.files.length} file(s)`, `${m.shell} shell write(s)`]
292  if (m.refused) parts.push(`${m.refused} refused`)
293  if (m.direct) parts.push('direct edits allowed (/base-edit-direct)')
294  return rows.map(r => (r.name === 'delegate' && r.status === 'PASS' ? { ...r, detail: `${r.detail}; this session: ${parts.join(', ')}` } : r))
295}
296
297export function age(ms: number): string {
298  const s = Math.max(0, Math.round(ms / 1000))
299  if (s < 60) return `${s}s`
300  if (s < 3600) return `${Math.floor(s / 60)}m`
301  if (s < 48 * 3600) return `${Math.floor(s / 3600)}h`
302  return `${Math.floor(s / 86400)}d`
303}
304
305export function summary(rows: Row[]): string {
306  const n = { PASS: 0, FAIL: 0, SKIP: 0, WARN: 0 }
307  for (const r of rows) n[r.status]++
308  return `${n.PASS} passed, ${n.FAIL} failed, ${n.SKIP} skipped${n.WARN ? `, ${n.WARN} warned` : ''}`
309}
310
311export function render(root: string, rows: Row[], tail: string[]): string {
312  const width = rows.reduce((w, r) => Math.max(w, r.name.length), 0)
313  return [
314    `base doctor — plugin root: ${root}`,
315    ...rows.map(r => `${r.status}  ${r.name.padEnd(width)}  ${r.detail}`),
316    `doctor: ${summary(rows)}`,
317    '',
318    ...tail,
319  ].join('\n')
320}
321
322async function eventTail($: $): Promise<string[]> {
323  if ((await $.env.get('BASE_EVENT_LOG')) === '0') return ['base events: off (BASE_EVENT_LOG=0)']
324  const list = await read($, events)
325  if (!list.length) return ['base events: none yet']
326  const now = await $.clock.now()
327  const shown = list.slice(-TAIL)
328  return [
329    `base events (last ${shown.length} of ${list.length}, newest last):`,
330    ...shown.map(ev => `  ${age(now - ev.atMs).padStart(4)}  ${ev.kind.padEnd(9)}  ${ev.text}`),
331  ]
332}
333
334async function logDoctor($: $, text: string): Promise<void> {
335  try {
336    if ((await $.env.get('BASE_EVENT_LOG')) === '0') return
337    const ev: BaseEvent = { atMs: await $.clock.now(), kind: 'doctor', text }
338    await update($, events, l => pushEvent(l, ev))
339    await logLine(diskOf($), ev)
340  } catch {}
341}
342
343export function registerDoctor(on: On): void {
344  // Matchers apart from base's other start hooks: one unmatched hook per event per plugin.
345  on('session.start', { cwd: /$/ }, async ($, e, next) => {
346    const r = await next(e)
347    await arm($, true)
348    return r
349  })
350
351  on('prompt.submit', { text: /$/ }, async ($, e, next) => {
352    const r = await next(e)
353    await arm($, false)
354    return r
355  })
356
357  on('command.run', { command: COMMAND.name }, async $ => {
358    const [fixed, live, defects, mcp] = await Promise.all([staticRows($), liveRows($), defectRows($), mcpRows($)])
359    const rows = withMainEdits(reconcile([...fixed, ...live, ...defects, ...mcp]), await read($, mainEdits).catch(() => null), String(await $.session.id()))
360    const tail = await eventTail($)
361    await logDoctor($, summary(rows))
362    return { text: render($.plugin.root, rows, tail) }
363  })
364}
365
hooks/mods/dogfood.ts 317 lines
1// Dogfood mode (BASE_DOGFOOD=1, or an account of dogfood.json): the plugin_defect tool and its report files, the nudge on a failed plugin
2// script (a designed refusal stays silent: text.ts's designedRefusal), and /base-defects. Off, every hook passes. The state of
3// base.dogfood is mirrored to <log dir>/<session>/dogfood-state.json with the main loop's failures since the last report (`errors`),
4// where hooks/conventions.cjs blocks the stop once while one is unreported. The convention section is hooks/conventions.cjs's; the `defects` row is doctor.ts's.
5import { atom, read, update } from 'claude-code'
6import type { EngineInterface, On } from 'claude-code'
7import type { BaseDogfood, BaseEvent } from '../../types'
8import {
9  NUDGE,
10  TOOL,
11  TOOL_DESC,
12  TOOL_NAME,
13  TOOL_SCHEMA,
14  bashFailed,
15  bashText,
16  crashedIn,
17  defectBody,
18  deniedNotRun,
19  designedRefusal,
20  dogfoodMode,
21  enabledNames,
22  errorLine,
23  failureLine,
24  fenced,
25  fileName,
26  indexLine,
27  isRepo,
28  isoDate,
29  loginAccount,
30  loginFile,
31  marketplaceOf,
32  parseDefect,
33  pluginScript,
34  pluginScripts,
35  priorErrors,
36  repoOf,
37  scriptLast,
38  seen,
39  slugOf,
40  versionsLine,
41  versionsOf,
42} from './dogfood/text.ts'
43import type { Defect, Plugin, ScriptError } from './dogfood/text.ts'
44import { logDir, logLine, pushEvent } from './events.ts'
45import type { Disk } from './events.ts'
46
47export const COMMAND = {
48  name: 'base-defects',
49  description: 'List the plugin defects reported in dogfood mode, newest first',
50  immediate: true,
51} as const
52const MAX_CLASH = 99
53const MAX_ERRORS = 50
54
55const events = atom({ plugin: 'base', key: 'events' } as const, [] as BaseEvent[])
56const dogfood = atom({ plugin: 'base', key: 'dogfood' } as const, null as BaseDogfood | null)
57const progress = atom({ plugin: 'base', key: 'progress' } as const, null)
58const slimInfo = atom({ plugin: 'slim', key: 'info' } as const, null)
59
60type $ = EngineInterface
61
62/** events.ts's file writer reaches `$` through this: the validator follows `$` only within one file. */
63function diskOf($: $): Disk {
64  return {
65    session: () => $.session.id(),
66    home: () => $.env.get('HOME'),
67    override: () => $.env.get('DOMAINE_LOG_DIR'),
68    manifest: () => $.fs.read(`${$.plugin.root}/.claude-plugin/plugin.json`),
69    read: path => $.fs.read(path),
70    write: (path, text) => $.fs.write(path, text),
71    toast: text => $.ui.toast(text),
72  }
73}
74
75async function logDefect($: $, text: string): Promise<void> {
76  try {
77    if ((await $.env.get('BASE_EVENT_LOG')) === '0') return
78    const ev: BaseEvent = { atMs: await $.clock.now(), kind: 'defect', text }
79    await update($, events, l => pushEvent(l, ev))
80    await logLine(diskOf($), ev)
81  } catch {}
82}
83
84const dogfoodOn = async ($: $) => {
85  const sw = (await $.env.get('BASE_DOGFOOD')) ?? ''
86  if (sw === '1' || sw === '0') return sw === '1'
87  const file = loginFile(await $.env.get('HOME'), await $.env.get('CLAUDE_CONFIG_DIR'))
88  const account = (await $.env.get('CLAUDE_CODE_ACCOUNT_UUID'))?.trim() || loginAccount(file && (await $.fs.read(file).catch(() => null)))
89  return dogfoodMode(sw, account, await $.fs.read(`${$.plugin.root}/dogfood.json`).catch(() => null))
90}
91
92/** `$HOME/.claude/plugin-defects`, or null without an absolute HOME (a cloud session). */
93async function homeDir($: $): Promise<string | null> {
94  const h = (await $.env.get('HOME'))?.trim() ?? ''
95  return h.startsWith('/') ? `${h.replace(/\/+$/, '')}/.claude/plugin-defects` : null
96}
97
98async function configDir($: $): Promise<string | null> {
99  const c = (await $.env.get('CLAUDE_CONFIG_DIR'))?.trim() ?? ''
100  if (c.startsWith('/')) return c.replace(/\/+$/, '')
101  const h = (await $.env.get('HOME'))?.trim() ?? ''
102  return h.startsWith('/') ? `${h.replace(/\/+$/, '')}/.claude` : null
103}
104
105const readOrNull = ($: $, path: string | null) => (path ? $.fs.read(path).catch(() => null) : Promise.resolve(null))
106
107async function ownVersion($: $): Promise<string> {
108  try {
109    const v = (JSON.parse(await $.fs.read(`${$.plugin.root}/.claude-plugin/plugin.json`)) as { version?: unknown }).version
110    return typeof v === 'string' && v ? v : 'unknown'
111  } catch {
112    return 'unknown'
113  }
114}
115
116async function versions($: $, installed: string | null): Promise<Map<Plugin, string | null>> {
117  const slim = (await read($, slimInfo).catch(() => null))?.version ?? null
118  const enabled = enabledNames(await $.settings.read().catch(() => null))
119  return versionsOf(installed, $.plugin.root, await ownVersion($), slim, enabled)
120}
121
122async function git($: $, root: string, args: string[]): Promise<string | null> {
123  const r = await $.process.run(['git', ...args], { cwd: root, timeoutMs: 5000 }).catch(() => null)
124  const out = r?.exitCode === 0 ? r.stdout.trim() : ''
125  return out || null
126}
127
128/**
129 * base.dogfood as the file the Stop command hook reads, with `errors`: the prior file's failures after the last report, plus
130 * `add`. The list lives in the file alone; a failed read starts it empty, a failed write is ignored.
131 */
132async function mirror($: $, add?: ScriptError): Promise<void> {
133  try {
134    const s = await read($, dogfood)
135    const dir = s && logDir(await $.env.get('HOME'), await $.env.get('DOMAINE_LOG_DIR'), s.sid)
136    if (!s || !dir) return
137    const file = `${dir}/dogfood-state.json`
138    const errors = [...priorErrors(await $.fs.read(file).catch(() => null), s.sid, s.reportMs), ...(add ? [add] : [])].slice(-MAX_ERRORS)
139    await $.fs.write(file, `${JSON.stringify({ sid: s.sid, failMs: s.failMs, script: s.script, reportMs: s.reportMs, errors })}\n`)
140  } catch {}
141}
142
143/** Registers the command on every session start and at the first prompt of a new session id; a new id starts clean. */
144async function arm($: $, start: boolean): Promise<void> {
145  try {
146    if (!(await dogfoodOn($))) return
147    const sid = String(await $.session.id())
148    const fresh = (await read($, dogfood))?.sid !== sid
149    if (start || fresh) await $.command.register(COMMAND).catch(() => undefined)
150    if (!fresh) return
151    await update($, dogfood, () => ({ sid, failMs: 0, script: '', reportMs: 0 }))
152    await mirror($)
153  } catch {}
154}
155
156/** The repo an issue goes to: BASE_DOGFOOD_REPO, else the github marketplace base was installed from. */
157async function issueRepo($: $, installed: string | null, config: string | null): Promise<string | null> {
158  const env = (await $.env.get('BASE_DOGFOOD_REPO'))?.trim() ?? ''
159  if (env) return isRepo(env) ? env : null
160  const known = await readOrNull($, config && `${config}/plugins/known_marketplaces.json`)
161  return repoOf(known, marketplaceOf(installed, $.plugin.root))
162}
163
164async function fileIssue($: $, d: Defect, path: string, installed: string | null, config: string | null): Promise<string> {
165  const repo = await issueRepo($, installed, config)
166  if (!repo) return 'GitHub issue not created: no repo known — set BASE_DOGFOOD_REPO=<owner>/<repo> (the marketplace base came from is not a github one this session can read)'
167  const argv = ['gh', 'issue', 'create', '--repo', repo, '--title', `[${d.plugin}] ${d.title}`, '--body-file', path]
168  let r
169  try {
170    r = await $.process.run(argv, { timeoutMs: 60_000 })
171  } catch (err) {
172    return `GitHub issue not created: gh did not run (${String((err as Error)?.message ?? err).slice(0, 160)})`
173  }
174  if (r.exitCode !== 0) return `GitHub issue not created: gh exited ${r.exitCode}: ${(r.stderr.trim().split('\n')[0] ?? '').slice(0, 200)}`
175  const url = r.stdout.match(/https:\/\/\S+/g)?.pop()
176  return url ? `GitHub issue: ${url}` : `GitHub issue created in ${repo}; gh printed no URL`
177}
178
179// Reports run one at a time: the free-name probe and the index read-modify-write would race in parallel calls.
180let queue: Promise<unknown> = Promise.resolve()
181const serial = <T>(job: () => Promise<T>): Promise<T> => {
182  const next = queue.then(job, job)
183  queue = next.catch(() => undefined)
184  return next
185}
186
187/**
188 * Writes the report and its index line; the result names the path (and the issue). Where no surface draws the
189 * file and `~` die with the session, so the result carries the whole report and the issue is filed by default.
190 */
191async function report($: $, d: Defect): Promise<string> {
192  const root = await $.session.root()
193  const now = await $.clock.now()
194  const date = isoDate(now)
195  const dir = `${root}/.claude/plugin-defects`
196  const slug = slugOf(d.title)
197  let path = ''
198  for (let n = 1; n <= MAX_CLASH && !path; n++) {
199    const p = `${dir}/${fileName(date, d.plugin, slug, n)}`
200    if (!(await $.fs.exists(p))) path = p
201  }
202  if (!path) return `plugin_defect: ${MAX_CLASH} reports named ${date}-${d.plugin}-${slug} already: give a different title`
203  const config = await configDir($)
204  const installed = await readOrNull($, config && `${config}/plugins/installed_plugins.json`)
205  const v = await versions($, installed)
206  const sid = String(await $.session.id())
207  const p = await read($, progress).catch(() => null)
208  const workId = p?.workId ?? null
209  const [remote, branch, commit] = await Promise.all([
210    git($, root, ['remote', 'get-url', 'origin']),
211    git($, root, ['rev-parse', '--abbrev-ref', 'HEAD']),
212    git($, root, ['rev-parse', '--short', 'HEAD']),
213  ])
214  const surfaces = await $.session.surfaces().catch(() => null)
215  const surfaceless = surfaces?.length === 0
216  const claudeCode = (await $.session.version().catch(() => null))?.version ?? null
217  const body = defectBody(d, { version: v.get(d.plugin) ?? 'unknown', date, session: sid, workId }, {
218    root,
219    remote,
220    branch,
221    commit,
222    versions: versionsLine(v),
223    surfaces: surfaces === null ? 'unknown' : surfaces.length ? surfaces.join(', ') : 'none (nothing draws)',
224    claudeCode,
225    session: sid,
226    workId,
227  })
228  try {
229    await $.fs.write(path, body)
230  } catch (err) {
231    return `plugin_defect: the report was not written to ${path}: ${String((err as Error)?.message ?? err).slice(0, 160)}`
232  }
233  await update($, dogfood, s => (s ? { ...s, reportMs: now } : { sid, failMs: 0, script: '', reportMs: now })).catch(() => undefined)
234  await mirror($)
235  await logDefect($, `${d.plugin}: ${d.title}`)
236  const lines = [`Plugin defect: ${d.title} → ${path}`]
237  const home = await homeDir($)
238  if (home) {
239    const index = `${home}/index.md`
240    try {
241      // An index that exists but will not read is skipped, never rewritten from '' over its lines.
242      const prior = (await $.fs.exists(index)) ? await $.fs.read(index) : ''
243      try {
244        await $.fs.write(index, `${prior}${prior && !prior.endsWith('\n') ? '\n' : ''}${indexLine(date, d, path)}\n`)
245        lines.push(`Index: ${index}`)
246      } catch {}
247    } catch (err) {
248      lines.push(`Index not updated: ${index} did not read (${String((err as Error)?.message ?? err).slice(0, 160)})`)
249    }
250  }
251  if (d.github ?? surfaceless) lines.push(await fileIssue($, d, path, installed, config))
252  if (surfaceless) lines.push('', 'No surface draws here: this file and ~ end with the session. Paste the whole report below into your reply, in this fenced block, under the Plugin defect: line.', '', fenced(body, 'markdown'))
253  return lines.join('\n')
254}
255
256async function listing($: $): Promise<string> {
257  const home = await homeDir($)
258  const index = home ? ((await $.fs.read(`${home}/index.md`).catch(() => '')) as string) : ''
259  const dir = `${await $.session.root()}/.claude/plugin-defects`
260  const names = (await $.fs.list(dir).catch(() => [])).filter(f => f.kind === 'file').map(f => f.name)
261  const fromIndex = seen(index, dir, [])
262  const fromProject = seen('', dir, names)
263  return [
264    home ? `~/.claude/plugin-defects/index.md — ${fromIndex.length || 'none'}${fromIndex.length ? ', newest first:' : ''}` : 'no home index here (no HOME)',
265    ...fromIndex.map(s => `  ${s.date} ${s.plugin} ${s.title} → ${s.path}`),
266    `${dir}/ — ${fromProject.length || 'none'}${fromProject.length ? ', newest first:' : ''}`,
267    ...fromProject.map(s => `  ${s.path.slice(dir.length + 1)}`),
268  ].join('\n')
269}
270
271export function registerDogfood(on: On): void {
272  // Matchers apart from base's other start and prompt hooks: one unmatched hook per event per plugin.
273  on('session.start', { cwd: /(?:)/ }, async ($, e, next) => {
274    try {
275      if (await dogfoodOn($)) await $.tool.register({ name: TOOL_NAME, description: TOOL_DESC, inputSchema: TOOL_SCHEMA, isDeferred: false })
276    } catch {}
277    await arm($, true)
278    return next(e)
279  })
280
281  on('prompt.submit', { text: /^(?:)/ }, async ($, e, next) => {
282    const r = await next(e)
283    await arm($, false)
284    return r
285  })
286
287  on('tool.call', { tool: TOOL }, async ($, e) => {
288    if (!(await dogfoodOn($))) return { result: 'plugin_defect: dogfood mode is off (BASE_DOGFOOD=1 turns it on)' }
289    const d = parseDefect(e as unknown as Record<string, unknown>)
290    if (typeof d === 'string') return { result: d }
291    return { result: await serial(() => report($, d)).catch(err => `plugin_defect failed: ${String((err as Error)?.message ?? err).slice(0, 160)}`) }
292  })
293
294  on('tool.call', { tool: 'Bash', command: /plugins\// }, async ($, e, next) => {
295    const r = await next(e)
296    if (e.tool !== 'Bash' || r.deny !== undefined) return r
297    const script = pluginScript(e.command)
298    if (!script) return r
299    const text = bashText(r)
300    if (deniedNotRun(text)) return r
301    // A line the script does not end owns no exit code (`| head` hides it): only the script's own trace or `error=` line speaks for it.
302    const failed = failureLine(text) || (scriptLast(e.command) ? bashFailed(r) && !designedRefusal(text, script) : bashFailed(r) && pluginScripts(e.command).some(s => crashedIn(text, s)))
303    if (!failed || !(await dogfoodOn($).catch(() => false))) return r
304    try {
305      await logDefect($, `script failed: ${script}`)
306      if (e.agentId === undefined) {
307        const now = await $.clock.now()
308        await update($, dogfood, s => (s ? { ...s, failMs: now, script } : s))
309        await mirror($, { script, line: errorLine(text), ms: now })
310      }
311    } catch {}
312    return { ...r, context: [...(r.context ?? []), NUDGE] }
313  })
314
315  on('command.run', { command: COMMAND.name }, async $ => ({ text: await listing($) }))
316}
317
hooks/mods/guards/bash.ts 73 lines
1// The two Bash guards in one tool.call hook: no AI attribution in a commit message (pure, in this
2// module) and no git-hooks bypass (delegated to hooks/no-verify-bypass.sh, whose heuristics
3// tests/no-verify-bypass-matrix.sh pins row by row). Each deny writes one `guard` event.
4import { atom, update } from 'claude-code'
5import type { EngineInterface, On } from 'claude-code'
6import type { BaseEvent } from '../../../types'
7import { logLine, pushEvent } from '../events.ts'
8import type { Disk } from '../events.ts'
9import { buildHookRun } from '../node-hook.ts'
10import { ATTRIBUTION_DENY, carriesAttribution } from './attribution.ts'
11
12/** Every block of the script sits behind one of these words; a command naming none never spawns it. */
13const GIT_WORD = /git|commit|push|merge|pull|\sam/
14export const NO_VERIFY_FALLBACK =
15  'Domaine convention (references/commit-message-format.md): git hooks are quality gates — never bypass them.'
16
17const events = atom({ plugin: 'base', key: 'events' } as const, [] as BaseEvent[])
18
19type $ = EngineInterface
20
21/** events.ts's file writer reaches `$` through this: the validator follows `$` only within one file. */
22function diskOf($: $): Disk {
23  return {
24    session: () => $.session.id(),
25    home: () => $.env.get('HOME'),
26    override: () => $.env.get('DOMAINE_LOG_DIR'),
27    manifest: () => $.fs.read(`${$.plugin.root}/.claude-plugin/plugin.json`),
28    read: path => $.fs.read(path),
29    write: (path, text) => $.fs.write(path, text),
30    toast: text => $.ui.toast(text),
31  }
32}
33
34async function logGuard($: $, text: string): Promise<void> {
35  try {
36    if ((await $.env.get('BASE_EVENT_LOG')) === '0') return
37    const ev: BaseEvent = { atMs: await $.clock.now(), kind: 'guard', text }
38    await update($, events, l => pushEvent(l, ev))
39    await logLine(diskOf($), ev)
40  } catch {}
41}
42
43/** The script's deny reason (exit 2, its stderr), else null; a spawn that fails or times out lets the call run. */
44async function noVerifyDeny($: $, command: string): Promise<string | null> {
45  if (!GIT_WORD.test(command)) return null
46  const { argv, init } = buildHookRun(
47    'bash',
48    $.plugin.root,
49    'hooks/no-verify-bypass.sh',
50    { tool_name: 'Bash', tool_input: { command } },
51    {},
52    10_000,
53  )
54  const run = await $.process.run(argv, init).catch(() => null)
55  if (run?.exitCode !== 2) return null
56  return run.stderr.trim() || NO_VERIFY_FALLBACK
57}
58
59export function registerBashGuards(on: On): void {
60  // A matcher apart from the workspace's `{ tool: 'Bash' }` hook.
61  on('tool.call', { tool: /^Bash$/ }, async ($, e, next) => {
62    if (e.tool !== 'Bash' || (await $.env.get('BASE_GUARD')) === '0') return next(e)
63    if (carriesAttribution(e.command)) {
64      await logGuard($, 'Bash: a commit message with AI attribution')
65      return { deny: ATTRIBUTION_DENY }
66    }
67    const deny = await noVerifyDeny($, e.command)
68    if (deny === null) return next(e)
69    await logGuard($, 'Bash: a git hooks bypass')
70    return { deny }
71  })
72}
73
hooks/mods/guards/edit.ts 308 lines
1// The edit-delegation guard: in the main loop (no agentId), a Write / Edit / NotebookEdit of a file under the session
2// root but outside `<root>/.claude/` is refused with a pointer to Agent(model: X) while the rules marker names X; a
3// main-loop Bash command that recognisably writes such a file is counted, never refused. Escapes: the session already on
4// X or cheaper, `/base-edit-direct` for this session id, BASE_GUARD=0. No marker or no `edit.model` = no edit guard, no
5// count. Apart from that, whenever base runs: a main-loop read of a drafter's draft (`.claude/tasks/<id>/steps-to-test.md`,
6// `pr-body.md`, `jira-comment.md`: Read, Grep, slim view, or a Bash command naming one outside drafter-check /
7// gh --body-file / test / ls) is refused on any model; only BASE_GUARD=0 lifts it.
8import { atom, read, update } from 'claude-code'
9import type { EngineInterface, On } from 'claude-code'
10import type { BaseEvent, BaseEventKind, BaseMainEdits } from '../../../types'
11import { bare, logLine, markerPaths, pushEvent } from '../events.ts'
12import type { Disk } from '../events.ts'
13
14export const COMMAND = {
15  name: 'base-edit-direct',
16  description: 'Allow direct project-file edits in this session (base edit delegation)',
17  immediate: true,
18} as const
19
20const TOOLS = /^(Edit|Write|NotebookEdit)$/
21/** Twin of scripts/edit-delegation.cjs FAMILIES: cheapest first. */
22export const FAMILIES = ['haiku', 'sonnet', 'opus', 'fable']
23const MODELS = ['opus', 'sonnet', 'haiku']
24// conservative: a shell command that writes a file in place or by redirection (`=>` and `->` are no redirection)
25export const SHELL_WRITE = /\bsed\b[^|;&\n]*\s-[a-zA-Z]*i|\bperl\s+-[a-zA-Z]*i|(?<![=-])>>?\s*[^\s&|>=]|\btee\s|\bgit\s+apply\b|\bpatch\s/
26const SHELL_SKIP = /\.claude\/|\/dev\/|\/tmp\/|\$TMPDIR/
27/** A drafter's draft in a task workspace: the main session shows its path and never reads it. */
28export const DRAFT = /\/\.claude\/tasks\/[^/]+\/(steps-to-test|pr-body|jira-comment)\.md$/
29const DRAFT_NAME = /(steps-to-test|pr-body|jira-comment)\.md/
30// a draft named in a shell command: a workspace path, or a variable's (`$W/pr-body.md`)
31const DRAFT_ARG = /(?:\.claude\/tasks\/[^\s'"/]+|\$\{?\w+\}?)\/(?:steps-to-test|pr-body|jira-comment)\.md\b/
32// the sanctioned consumers of a draft path: the checker, gh's --body-file, an existence test, a listing
33const DRAFT_OK = /drafter-check\.cjs\b|\bgh\s+pr\s+(?:create|edit)\b[^\n]*--body-file|^\s*(?:test|\[)\s+-[sef]\s|^\s*ls\b/
34const CHECKER = /drafter-check\.cjs\b/
35// a segment that only assigns variables (`P=<draft>`, `export P="$W/pr-body.md"`); a `$(…)` or backtick value runs a command
36const VALUE = String.raw`(?:"(?:[^"\`$]|\$(?!\())*"|'[^']*'|(?:[^\s'"\`$;|&]|\$(?!\())*)`
37const ASSIGN_ONLY = new RegExp(String.raw`^\s*(?:(?:export|local|declare|readonly)\s+)?\w+=${VALUE}(?:\s+\w+=${VALUE})*\s*$`)
38const ASSIGN = new RegExp(String.raw`(\w+)=(${VALUE})`, 'g')
39// a heredoc start (`<<EOF`, `<<-'EOF'`), not a here-string (`<<<`)
40const HEREDOC = /(?<!<)<<-?\s*(['"]?)(\w+)\1/
41const VIEW_TOOL = 'mcp__slim__view'
42const FILES_CAP = 50
43
44export const editRefusal = (model: string) =>
45  `base edit delegation: this session hands project-file changes to Agent(model: "${model}") — brief one agent with ` +
46  `the files, the exact change and the test, then review its diff. Allowed directly only when this session already runs ` +
47  `on ${model} or a cheaper family (haiku < sonnet < opus < fable) — say which model you run on and call again after ` +
48  `the developer runs /base-edit-direct — or for files under .claude/. BASE_EDIT_MODEL=0 turns delegation off.`
49
50export const draftRefusal = (rel: string) =>
51  `base drafter rule: ${rel} is a drafter agent's draft — never read, quote or paraphrase it. Show its path; a change ` +
52  `goes to the same agent via SendMessage, and jira-writer / gh pr create --body-file take the path. Refused on ` +
53  `any model and after /base-edit-direct too; only BASE_GUARD=0 lifts it.`
54
55const mainEdits = atom({ plugin: 'base', key: 'mainEdits' } as const, null as BaseMainEdits | null)
56const delegation = atom({ plugin: 'base', key: 'delegation' } as const, null as { sid: string; model: string | null } | null)
57const events = atom({ plugin: 'base', key: 'events' } as const, [] as BaseEvent[])
58
59type $ = EngineInterface
60
61/** `claude-opus-5-5[1m]` → `opus`; null for no id. */
62export function modelFamily(id: string | null | undefined): string | null {
63  return typeof id === 'string' && id ? (id.replace(/^claude-/, '').replace(/\[1m\]$/, '').split('-')[0] ?? null) : null
64}
65
66/** True when `family` is a known family no dearer than `model`. */
67export const atOrBelow = (family: string | null, model: string): boolean =>
68  family !== null && FAMILIES.includes(family) && FAMILIES.indexOf(family) <= FAMILIES.indexOf(model)
69
70/** An absolute path under `root`, outside `<root>/.claude/`; a relative one resolves against root. */
71export function inScope(path: string, root: string): boolean {
72  const p = path.startsWith('/') ? path : `${root}/${path}`
73  return p.startsWith(`${root}/`) && !p.startsWith(`${root}/.claude/`)
74}
75
76/** The rules marker's `edit.model` (opus, sonnet or haiku), else null. */
77export function markerModel(text: string): string | null {
78  try {
79    const m = (JSON.parse(text) as { edit?: { model?: unknown } }).edit?.model
80    return typeof m === 'string' && MODELS.includes(m) ? m : null
81  } catch {
82    return null
83  }
84}
85
86const empty = (sid: string): BaseMainEdits => ({ sid, n: 0, files: [], shell: 0, refused: 0, direct: false })
87const mine = (v: BaseMainEdits | null, sid: string): BaseMainEdits => (v && v.sid === sid ? v : empty(sid))
88
89/** events.ts's file writer reaches `$` through this: the validator follows `$` only within one file. */
90function diskOf($: $): Disk {
91  return {
92    session: () => $.session.id(),
93    home: () => $.env.get('HOME'),
94    override: () => $.env.get('DOMAINE_LOG_DIR'),
95    manifest: () => $.fs.read(`${$.plugin.root}/.claude-plugin/plugin.json`),
96    read: path => $.fs.read(path),
97    write: (path, text) => $.fs.write(path, text),
98    toast: text => $.ui.toast(text),
99  }
100}
101
102async function logEvent($: $, kind: BaseEventKind, text: string): Promise<void> {
103  try {
104    if ((await $.env.get('BASE_EVENT_LOG')) === '0') return
105    const ev: BaseEvent = { atMs: await $.clock.now(), kind, text }
106    await update($, events, l => pushEvent(l, ev))
107    await logLine(diskOf($), ev)
108  } catch {}
109}
110
111/** The delegate model of session `sid`, read once from its rules marker; no marker caches null. */
112async function modelFor($: $, sid: string): Promise<string | null> {
113  const known = await read($, delegation)
114  if (known && known.sid === sid) return known.model
115  let model: string | null = null
116  for (const file of markerPaths(await $.env.get('HOME'), await $.env.get('DOMAINE_LOG_DIR'), await $.env.get('TMPDIR'), sid, 'base.rules')) {
117    const text = await $.fs.read(file).catch(() => null)
118    if (text === null) continue
119    model = markerModel(text)
120    break
121  }
122  await update($, delegation, () => ({ sid, model }))
123  return model
124}
125
126/** True when a shell command reads a draft: some segment names one and is not a sanctioned consumer. */
127export function shellReadsDraft(command: string): boolean {
128  const vars = new Map<string, string>()
129  const expand = (s: string) => s.replace(/\$\{?(\w+)\}?/g, (m, v: string) => vars.get(v) ?? m)
130  return withoutHeredocs(command).split(/&&|\|\||[;\n]/).some(raw => {
131    // a draft path parked in a variable is no read; its later use is matched with the value substituted
132    if (ASSIGN_ONLY.test(raw)) {
133      for (const [, name, value] of raw.matchAll(ASSIGN)) vars.set(name, expand(value.replace(/^(['"])(.*)\1$/, '$2')))
134      return false
135    }
136    const cmd = expand(raw)
137    const stages = cmd.split('|')
138    // a pipeline into the checker: it prints counts only (a drafter's receipt piped in)
139    if (CHECKER.test(stages[stages.length - 1])) return false
140    return stages.some(seg => DRAFT_ARG.test(seg) && !DRAFT_OK.test(seg))
141  })
142}
143
144/** The command without its heredoc bodies: they are stdin data, not commands. */
145function withoutHeredocs(command: string): string {
146  const out: string[] = []
147  let end: string | null = null
148  for (const line of command.split('\n')) {
149    if (end !== null) {
150      if (line.trim() === end) end = null
151      continue
152    }
153    out.push(line)
154    const m = HEREDOC.exec(line)
155    if (m) end = m[2]
156  }
157  return out.join('\n')
158}
159
160/** The session's own escapes: /base-edit-direct, BASE_GUARD=0, a model at or below the delegate's. */
161async function escaped($: $, cur: BaseMainEdits, model: string): Promise<boolean> {
162  if (cur.direct || (await $.env.get('BASE_GUARD')) === '0') return true
163  const own = await $.session.model().catch(() => null)
164  return atOrBelow(modelFamily(own), model)
165}
166
167const rel = (path: string, root: string) => (path.startsWith(`${root}/`) ? path.slice(root.length + 1) : path)
168
169/** The draft deny for a main-loop read, on any model and with or without a rules marker; `shown` names the path or command. */
170async function draftDeny($: $, tool: string, shown: string): Promise<{ deny: string } | null> {
171  if ((await $.env.get('BASE_GUARD')) === '0') return null
172  const sid = String(await $.session.id())
173  await update($, mainEdits, v => ({ ...mine(v, sid), refused: mine(v, sid).refused + 1 }))
174  await logEvent($, 'guard', `${tool}: main session — ${shown} is a drafter's draft`)
175  return { deny: draftRefusal(shown) }
176}
177
178
179/** The command on every session start and at the first prompt of a new session id. */
180async function arm($: $, start: boolean): Promise<void> {
181  try {
182    const sid = String(await $.session.id())
183    const known = await read($, mainEdits)
184    if (start || known?.sid !== sid) await $.command.register(COMMAND).catch(() => undefined)
185  } catch {}
186}
187
188export function registerEditGuard(on: On): void {
189  // Matchers apart from base's other start hooks: one unmatched hook per event per plugin.
190  on('session.start', { cwd: /(?:)$/ }, async ($, e, next) => {
191    const r = await next(e)
192    await arm($, true)
193    return r
194  })
195
196  on('prompt.submit', { text: /(?:)$/ }, async ($, e, next) => {
197    const r = await next(e)
198    await arm($, false)
199    return r
200  })
201
202  // A developer's gesture only: a run another plugin or a delivered message queued grants nothing.
203  on('command.run', { command: COMMAND.name }, async ($, e) => {
204    const kind = e.origin.kind
205    if (kind !== 'composer' && kind !== 'bridge' && kind !== 'sdk') return { text: 'base: /base-edit-direct is the developer\'s to run at the prompt' }
206    const sid = String(await $.session.id())
207    const model = await modelFor($, sid).catch(() => null)
208    await update($, mainEdits, v => ({ ...mine(v, sid), direct: true }))
209    return {
210      text: model
211        ? `base: direct edits allowed for this session (edit delegation: ${model}); /clear starts over.`
212        : 'base: direct edits allowed for this session (edit delegation is off here); /clear starts over.',
213    }
214  })
215
216  on('tool.call', { tool: TOOLS }, async ($, e, next) => {
217    if (e.agentId !== undefined) return next(e)
218    if (e.tool !== 'Edit' && e.tool !== 'Write' && e.tool !== 'NotebookEdit') return next(e)
219    const path = e.tool === 'NotebookEdit' ? e.notebook_path : e.file_path
220    let root: string, sid: string, model: string | null, cur: BaseMainEdits
221    try {
222      root = await $.session.root()
223      if (typeof path !== 'string' || !inScope(path, root)) return next(e)
224      sid = String(await $.session.id())
225      model = await modelFor($, sid)
226      if (!model) return next(e)
227      cur = mine(await read($, mainEdits), sid)
228      if (!(await escaped($, cur, model))) {
229        const m = model
230        await update($, mainEdits, v => ({ ...mine(v, sid), refused: mine(v, sid).refused + 1 }))
231        await logEvent($, 'guard', `${e.tool}: main session — delegate to Agent(model: ${m})`)
232        return { deny: editRefusal(m) }
233      }
234    } catch {
235      return next(e)
236    }
237    const r = await next(e)
238    if (r.deny !== undefined || r.isError) return r
239    try {
240      const abs = path.startsWith('/') ? path : `${root}/${path}`
241      let fresh = false
242      await update($, mainEdits, v => {
243        const c = mine(v, sid)
244        fresh = !c.files.includes(abs)
245        return { ...c, n: c.n + 1, files: fresh ? [...c.files, abs].slice(-FILES_CAP) : c.files }
246      })
247      if (fresh) await logEvent($, 'delegate', bare(`main-session ${e.tool} of ${rel(abs, root)} (delegation: ${model}${cur.direct ? ', direct' : ''})`))
248    } catch {}
249    return r
250  })
251
252  on('tool.call', { tool: /^(Read|Grep)$/ }, async ($, e, next) => {
253    if (e.agentId !== undefined) return next(e)
254    try {
255      const args = e as unknown as Record<string, unknown>
256      const raw = e.tool === 'Read' ? args.file_path : args.path
257      const root = await $.session.root()
258      const path = typeof raw === 'string' ? (raw.startsWith('/') ? raw : `${root}/${raw}`) : ''
259      const glob = e.tool === 'Grep' && typeof args.glob === 'string' ? args.glob : ''
260      if (!DRAFT.test(path) && !(path.includes('/.claude/tasks/') && DRAFT_NAME.test(glob))) return next(e)
261      const r = await draftDeny($, e.tool, rel(path, root))
262      return r ?? next(e)
263    } catch {
264      return next(e)
265    }
266  })
267
268  on('tool.call', { tool: VIEW_TOOL }, async ($, e, next) => {
269    if (e.agentId !== undefined) return next(e)
270    try {
271      const args = e as unknown as Record<string, unknown>
272      const root = await $.session.root()
273      const raw = typeof args.path === 'string' ? args.path : ''
274      const path = raw.startsWith('/') ? raw : `${root}/${raw}`
275      if (!DRAFT.test(path)) return next(e)
276      return (await draftDeny($, 'view', rel(path, root))) ?? next(e)
277    } catch {
278      return next(e)
279    }
280  })
281
282  // Apart from the shell-write counter below: a narrower `command` matcher of its own.
283  on('tool.call', { tool: 'Bash', command: DRAFT_NAME }, async ($, e, next) => {
284    if (e.agentId !== undefined || e.tool !== 'Bash') return next(e)
285    try {
286      if (!shellReadsDraft(e.command)) return next(e)
287      const m = DRAFT_ARG.exec(e.command)
288      const root = await $.session.root()
289      return (await draftDeny($, 'Bash', m ? rel(m[0], root) : 'a draft')) ?? next(e)
290    } catch {
291      return next(e)
292    }
293  })
294
295  // Matched apart from progress.ts's Bash hook: the `command` field narrows this one.
296  on('tool.call', { tool: 'Bash', command: SHELL_WRITE }, async ($, e, next) => {
297    const r = await next(e)
298    if (e.agentId !== undefined || e.tool !== 'Bash' || r.deny !== undefined || r.isError) return r
299    try {
300      if (SHELL_SKIP.test(e.command)) return r
301      const sid = String(await $.session.id())
302      if (!(await modelFor($, sid))) return r
303      await update($, mainEdits, v => ({ ...mine(v, sid), shell: mine(v, sid).shell + 1 }))
304    } catch {}
305    return r
306  })
307}
308
hooks/mods/guards/mcp.ts 181 lines
1// The MCP guards in one tool.call hook, server-agnostic. A subagent of base's reader or writer types calls MCP tools
2// only on a server serving its vendor's tools, and a Jira, Confluence or Notion write only when its type allows it (an
3// unknown type gets none). A server other than a plugin's that serves the same tools as one of base's own takes
4// precedence: base's tool is refused once per session, then allowed. Each deny writes one `guard` event.
5import { atom, update } from 'claude-code'
6import type { EngineInterface, On } from 'claude-code'
7import type { BaseEvent } from '../../../types'
8import { logDir, logLine, pushEvent, spareRoot } from '../events.ts'
9import type { Disk } from '../events.ts'
10
11/** The write tools by tool name on any server; tests/base-refs-lint.sh reads both lists from this file. */
12export const JIRA_WRITES = [
13  'editJiraIssue', 'addCommentToJiraIssue', 'transitionJiraIssue', 'createJiraIssue', 'createIssueLink',
14  'addWorklogToJiraIssue', 'createConfluencePage', 'updateConfluencePage', 'createConfluenceFooterComment',
15  'createConfluenceInlineComment',
16]
17export const NOTION_WRITES = [
18  'notion-create-pages', 'notion-update-page', 'notion-create-comment', 'notion-move-pages', 'notion-duplicate-page',
19  'notion-create-database', 'notion-update-data-source', 'notion-create-view', 'notion-update-view',
20  'notion-create-folder', 'notion-update-folder', 'notion-create-file-upload', 'notion-create-attachment',
21  'notion-spawn-session', 'notion-send-message-to-session', 'notion-stop-session',
22]
23/** Per server of base's manifest: a tool only its vendor's servers serve, and the vendor. A server listing it serves the same tools. */
24export const SIGNATURE: Record<string, readonly [tool: string, vendor: string]> = {
25  atlassian: ['getJiraIssue', 'Atlassian'],
26  'notion-mcp': ['notion-fetch', 'Notion'],
27  'figma-dev-mode': ['get_design_context', 'Figma'],
28}
29const WRITES = new Set([...JIRA_WRITES, ...NOTION_WRITES])
30/** SubagentStart's `agent_type` spelling of base's agents → the SIGNATURE servers whose vendor's servers are its only MCP servers. */
31const SCOPE: Record<string, readonly string[]> = {
32  'base:jira-reader': ['atlassian'],
33  'base:doc-reader': ['atlassian', 'notion-mcp'],
34  'base:figma-reader': ['figma-dev-mode'],
35  'base:jira-writer': ['atlassian'],
36}
37const READERS = new Set(['base:jira-reader', 'base:doc-reader', 'base:figma-reader'])
38const WRITER = 'base:jira-writer'
39const WRITER_TOOLS = new Set(['editJiraIssue', 'addCommentToJiraIssue'])
40const OWN = 'plugin_base_'
41const SOFT_CAP = 200
42
43const soft = atom({ plugin: 'base', key: 'mcpSoft' } as const, { sid: '', tools: [] as string[] })
44const events = atom({ plugin: 'base', key: 'events' } as const, [] as BaseEvent[])
45
46type $ = EngineInterface
47
48/** `mcp__<server>__<tool>` → its server and tool; null for any other name. */
49export function splitTool(name: string): { server: string; tool: string } | null {
50  const at = name.lastIndexOf('__')
51  return name.startsWith('mcp__') && at > 5 ? { server: name.slice(5, at), tool: name.slice(at + 2) } : null
52}
53
54/**
55 * The servers in `names` that list the SIGNATURE tool of base's `server` and are no plugin's (nor slim's or base's
56 * registered tools), in list order; none for a server without a signature.
57 */
58export function twinServers(names: readonly string[], server: string): string[] {
59  const sig = SIGNATURE[server]?.[0]
60  const out: string[] = []
61  for (const n of names) {
62    const s = splitTool(n)
63    if (!sig || s?.tool !== sig || s.server.startsWith('plugin_') || s.server === 'slim' || s.server === 'base') continue
64    if (!out.includes(s.server)) out.push(s.server)
65  }
66  return out
67}
68
69/** Why an agent of `type` (null = no marker entry) may not call the write tool `tool`; null when it may. */
70export function writeRefusal(type: string | null, tool: string, full: string): string | null {
71  if (!WRITES.has(tool)) return null
72  if (type === null) return `base: ${full} refused: no agent-type marker for this subagent, so it gets no Jira, Confluence or Notion write tool`
73  if (READERS.has(type)) return `base: ${type} is read-only toward Jira, Confluence and Notion — ${full} refused`
74  if (type === WRITER && !WRITER_TOOLS.has(tool)) return `base: ${type} writes only with editJiraIssue or addCommentToJiraIssue — ${full} refused`
75  return null
76}
77
78/** Why an agent of `type` may not call `full` on `server` while `names` are listed; null when it may or its type has no scope. */
79export function scopeRefusal(type: string, server: string, full: string, names: readonly string[]): string | null {
80  const scope = SCOPE[type]
81  if (!scope || scope.some(k => server === OWN + k || names.includes(`mcp__${server}__${SIGNATURE[k][0]}`))) return null
82  return `base: ${type} calls MCP tools only on a server that serves ${scope.map(k => SIGNATURE[k][0]).join(' or ')} — ${full} refused`
83}
84
85/** events.ts's file writer reaches `$` through this: the validator follows `$` only within one file. */
86function diskOf($: $): Disk {
87  return {
88    session: () => $.session.id(),
89    home: () => $.env.get('HOME'),
90    override: () => $.env.get('DOMAINE_LOG_DIR'),
91    manifest: () => $.fs.read(`${$.plugin.root}/.claude-plugin/plugin.json`),
92    read: path => $.fs.read(path),
93    write: (path, text) => $.fs.write(path, text),
94    toast: text => $.ui.toast(text),
95  }
96}
97
98async function logGuard($: $, text: string): Promise<void> {
99  try {
100    if ((await $.env.get('BASE_EVENT_LOG')) === '0') return
101    const ev: BaseEvent = { atMs: await $.clock.now(), kind: 'guard', text }
102    await update($, events, l => pushEvent(l, ev))
103    await logLine(diskOf($), ev)
104  } catch {}
105}
106
107/**
108 * The type hooks/conventions.cjs recorded for subagent `id` in `<log dir or spare dir>/<session>/agents/<id>.json`:
109 * null when no file names it, undefined when a probe failed.
110 */
111async function agentType($: $, id: string): Promise<string | null | undefined> {
112  if (!/^[\w.-]+$/.test(id) || /^\.+$/.test(id)) return null
113  let failed = false
114  try {
115    const sid = String(await $.session.id())
116    const dirs = [logDir(await $.env.get('HOME'), await $.env.get('DOMAINE_LOG_DIR'), sid), logDir(undefined, spareRoot(await $.env.get('TMPDIR')), sid)]
117    for (const dir of dirs) {
118      if (dir === null) continue
119      const file = `${dir}/agents/${id}.json`
120      let text: string
121      try {
122        if (!(await $.fs.exists(file))) continue
123        text = await $.fs.read(file)
124      } catch {
125        failed = true
126        continue
127      }
128      try {
129        const type = JSON.parse(text) as unknown
130        if (typeof type === 'string' && type) return type
131      } catch {}
132    }
133  } catch {
134    return undefined
135  }
136  return failed ? undefined : null
137}
138
139/** The one refusal per session of base's own `full` while another server serves the same tools; null when none applies. */
140async function precedence($: $, full: string, name: { server: string; tool: string }, names: readonly string[]): Promise<string | null> {
141  const twin = twinServers(names, name.server.slice(OWN.length)).find(s => names.includes(`mcp__${s}__${name.tool}`))
142  if (!twin) return null
143  const sid = String(await $.session.id())
144  let fresh = false
145  await update($, soft, s => {
146    const tools = s.sid === sid ? s.tools : []
147    fresh = !tools.includes(full)
148    return fresh ? { sid, tools: [...tools, full].slice(-SOFT_CAP) } : s
149  })
150  if (!fresh) return null
151  const other = `mcp__${twin}__${name.tool}`
152  await logGuard($, `${name.tool}: ${twin} takes precedence`)
153  return `${full}: ${other} serves the same tool and takes precedence — call ${other} instead; if that fails, call ${full} again (it is allowed after this one refusal)`
154}
155
156export function registerMcpGuards(on: On): void {
157  on('tool.call', { tool: /^mcp__(?!slim__|base__)/ }, async ($, e, next) => {
158    const name = splitTool(e.tool)
159    if (!name || (await $.env.get('BASE_GUARD')) === '0') return next(e)
160    let listed: string[] | null | undefined
161    const names = async () => (listed !== undefined ? listed : (listed = await $.tool.list().then(l => l.map(t => t.name), () => null)))
162    if (e.agentId !== undefined) {
163      const type = await agentType($, e.agentId)
164      const write = type === undefined ? null : writeRefusal(type, name.tool, e.tool)
165      if (write) {
166        await logGuard($, `${name.tool}: ${type ?? 'a subagent of unknown type'} may not write`)
167        return { deny: write }
168      }
169      const scoped = type && SCOPE[type] ? await names() : null
170      const scope = type && scoped ? scopeRefusal(type, name.server, e.tool, scoped) : null
171      if (scope) {
172        await logGuard($, `${name.tool}: ${type} may not call ${name.server}`)
173        return { deny: scope }
174      }
175    }
176    const list = name.server.startsWith(OWN) ? await names() : null
177    const deny = list ? await precedence($, e.tool, name, list) : null
178    return deny ? { deny } : next(e)
179  })
180}
181
hooks/mods/guards/scratch.ts 111 lines
1// The scratch-path guard: a tool.describe note and a tool.call deny delegated to hooks/scratch-path-guard.cjs,
2// which keeps the os.tmpdir() and realpath logic a mod cannot do. Each deny writes one `guard` event.
3import { atom, read, update } from 'claude-code'
4import type { EngineInterface, On } from 'claude-code'
5import type { BaseEvent } from '../../../types'
6import { bare, logLine, pushEvent, toolName } from '../events.ts'
7import type { Disk } from '../events.ts'
8import { buildHookRun, omit, parseHookOut } from '../node-hook.ts'
9
10/** Server-agnostic: a per-user `claude mcp add` of the same servers is guarded too. */
11export const GUARDED_RE =
12  /^mcp__.*__(take_screenshot|browser_take_screenshot|take_snapshot|get_network_request|browser_run_code_unsafe)$/
13
14// chrome-devtools' write tools (playwright's are browser_*): their server also accepts its OS temp dir.
15const TMPDIR_OK_RE = /__(take_screenshot|take_snapshot|get_network_request)$/
16
17// Constant on purpose: the describe answer is cached per session and any change spends the prompt cache.
18const NOTE_HEAD =
19  '\n\nbase scratch-path guard: paths must resolve inside this project: `.claude/tasks/<work-id>/tmp/` ' +
20  '(`.claude/tmp/<work-id>/` in a git worktree) or `.claude/tmp/`; use an absolute path. '
21const NOTE = NOTE_HEAD + 'Paths outside the project are refused.'
22const NOTE_TMPDIR = NOTE_HEAD + "Paths outside the project, other than this server's own OS temp dir, are refused."
23
24export const DENY_FALLBACK = 'base scratch-path guard: path outside the project'
25
26/** The launch root, latched once: the MCP servers' roots were fixed where they launched. */
27const guardRoot = atom({ plugin: 'base', key: 'guardRoot' } as const, null)
28const events = atom({ plugin: 'base', key: 'events' } as const, [] as BaseEvent[])
29
30type $ = EngineInterface
31
32/** events.ts's file writer reaches `$` through this: the validator follows `$` only within one file. */
33function diskOf($: $): Disk {
34  return {
35    session: () => $.session.id(),
36    home: () => $.env.get('HOME'),
37    override: () => $.env.get('DOMAINE_LOG_DIR'),
38    manifest: () => $.fs.read(`${$.plugin.root}/.claude-plugin/plugin.json`),
39    read: path => $.fs.read(path),
40    write: (path, text) => $.fs.write(path, text),
41    toast: text => $.ui.toast(text),
42  }
43}
44
45async function logGuard($: $, text: string): Promise<void> {
46  try {
47    if ((await $.env.get('BASE_EVENT_LOG')) === '0') return
48    const ev: BaseEvent = { atMs: await $.clock.now(), kind: 'guard', text }
49    await update($, events, l => pushEvent(l, ev))
50    await logLine(diskOf($), ev)
51  } catch {}
52}
53
54export function guardNote(tool: string): string {
55  return TMPDIR_OK_RE.test(tool) ? NOTE_TMPDIR : NOTE
56}
57
58/** BASE_GUARD or BASE_SCRATCH_GUARD is 0 in the process env. */
59async function off($: $): Promise<boolean> {
60  return (await $.env.get('BASE_GUARD')) === '0' || (await $.env.get('BASE_SCRATCH_GUARD')) === '0'
61}
62
63export function registerScratchGuard(on: On): void {
64  // A matcher apart from base's other session.start hooks: one unmatched hook per event per plugin.
65  on('session.start', { cwd: /./ }, async ($, e, next) => {
66    try {
67      const launch = await $.session.root()
68      await update($, guardRoot, v => v ?? launch)
69    } catch {}
70    return next(e)
71  })
72
73  // The describe answer lasts the session, and no spawned script re-checks the switch here: the settings env counts too.
74  on('tool.describe', { tool: GUARDED_RE }, async ($, e, next) => {
75    const settingsEnv = (await $.settings.read()).env as Record<string, unknown> | undefined
76    if ((await off($)) || settingsEnv?.BASE_GUARD === '0' || settingsEnv?.BASE_SCRATCH_GUARD === '0') return next(e)
77    const d = await next(e)
78    return { ...d, description: d.description + guardNote(e.tool) }
79  })
80
81  on('tool.call', { tool: GUARDED_RE }, async ($, e, next) => {
82    if (await off($)) return next(e)
83    let root = await read($, guardRoot)
84    if (root === null) {
85      // A throwing session.start hook of base skips this latch: the first call latches.
86      const live = await $.session.root()
87      root = (await update($, guardRoot, v => v ?? live)) ?? live
88    }
89    const { argv, init } = buildHookRun(
90      'node',
91      $.plugin.root,
92      'hooks/scratch-path-guard.cjs',
93      {
94        hook_event_name: 'PreToolUse',
95        tool_name: e.tool,
96        tool_input: omit(e, ['tool', 'tool_use_id', 'agentId']),
97        cwd: await $.session.cwd(),
98      },
99      { CLAUDE_PROJECT_DIR: root, CLAUDE_PLUGIN_ROOT: $.plugin.root },
100      10_000,
101    )
102    const out = await $.process.run(argv, init).then(parseHookOut, () => null)
103    const hso = out?.hookSpecificOutput
104    if (hso?.permissionDecision !== 'deny') return next(e)
105    const raw = hso.permissionDecisionReason
106    const reason = typeof raw === 'string' && raw.trim() ? raw : DENY_FALLBACK
107    await logGuard($, `${toolName(e.tool)}: ${bare(reason.split('\n')[0] ?? '')}`)
108    return { deny: reason }
109  })
110}
111
hooks/mods/session.ts 105 lines
1// base's install state: the start line, the slim check at a session's first prompt, and the refusal
2// of the readers while slim's view tool is missing.
3import { atom, read, update } from 'claude-code'
4import type { EngineInterface, On } from 'claude-code'
5import type { BaseEvent, BaseEventKind } from '../../types'
6import { logLine, pushEvent } from './events.ts'
7import type { Disk } from './events.ts'
8
9export const SLIM_VIEW = 'mcp__slim__view'
10const SLIM_INSTALL = 'claude plugin install slim@domaine'
11export const SLIM_MISSING = `slim is not loaded — ${SLIM_INSTALL}`
12/** The agents that read through slim's view tool; the writer and the reviewers do not need it. */
13const READER = /^base:(jira|figma|doc)-reader$/
14
15const events = atom({ plugin: 'base', key: 'events' } as const, [] as BaseEvent[])
16const started = atom({ plugin: 'base', key: 'started' } as const, null)
17/** The session id whose first prompt ran the slim check: a prompt has been sent once it is set (doctor.ts reads it). */
18const checked = atom({ plugin: 'base', key: 'checked' } as const, null)
19
20type $ = EngineInterface
21
22/** events.ts's file writer reaches `$` through this: the validator follows `$` only within one file. */
23function diskOf($: $): Disk {
24  return {
25    session: () => $.session.id(),
26    home: () => $.env.get('HOME'),
27    override: () => $.env.get('DOMAINE_LOG_DIR'),
28    manifest: () => $.fs.read(`${$.plugin.root}/.claude-plugin/plugin.json`),
29    read: path => $.fs.read(path),
30    write: (path, text) => $.fs.write(path, text),
31    toast: text => $.ui.toast(text),
32  }
33}
34
35async function logEvent($: $, kind: BaseEventKind, text: string): Promise<void> {
36  try {
37    if ((await $.env.get('BASE_EVENT_LOG')) === '0') return
38    const ev: BaseEvent = { atMs: await $.clock.now(), kind, text }
39    await update($, events, l => pushEvent(l, ev))
40    await logLine(diskOf($), ev)
41  } catch {}
42}
43
44async function version($: $): Promise<string> {
45  try {
46    const v = (JSON.parse(await $.fs.read(`${$.plugin.root}/.claude-plugin/plugin.json`)) as { version?: unknown }).version
47    return typeof v === 'string' && v ? v : 'unknown'
48  } catch {
49    return 'unknown'
50  }
51}
52
53/** slim registers its view tool at its own session.start, so the list answers from the first prompt on. */
54async function slimLoaded($: $): Promise<boolean> {
55  return (await $.tool.list()).some(t => t.name === SLIM_VIEW)
56}
57
58/** The deny reason for a reader spawned while slim is missing, else null; a failed tool listing lets it run. */
59async function refusal($: $, type: string): Promise<string | null> {
60  if (!READER.test(type) || (await slimLoaded($).catch(() => true))) return null
61  const name = type.slice(type.indexOf(':') + 1)
62  await logEvent($, 'refuse', `${name}: slim is not loaded`)
63  return `base: ${name} needs the slim plugin — ${SLIM_INSTALL}`
64}
65
66export function registerSession(on: On): void {
67  // The engine allows one unmatched hook per event per plugin; this matcher takes every session.
68  on('session.start', { cwd: /^/ }, async ($, e, next) => {
69    try {
70      const sid = String(await $.session.id())
71      if ((await read($, started)) !== sid) {
72        await update($, started, () => sid)
73        await logEvent($, 'start', `base ${await version($)}`)
74      }
75    } catch {}
76    return next(e)
77  })
78
79  on('prompt.submit', { text: /^/ }, async ($, e, next) => {
80    const r = await next(e)
81    try {
82      const sid = String(await $.session.id())
83      if ((await read($, checked)) === sid) return r
84      await update($, checked, () => sid)
85      if (!(await slimLoaded($))) {
86        await logEvent($, 'install', SLIM_MISSING)
87        $.ui.toast(`base: ${SLIM_MISSING}`)
88      }
89    } catch {}
90    return r
91  })
92
93  on('tool.call', { tool: 'Agent' }, async ($, e, next) => {
94    if (e.tool !== 'Agent') return next(e)
95    const deny = await refusal($, e.subagent_type ?? '')
96    return deny ? { deny } : next(e)
97  })
98
99  // The resolved type: a bare name the Agent tool resolved, or another plugin's $.agent.spawn.
100  on('agent.spawn', { subagentType: READER }, async ($, e, next) => {
101    const deny = await refusal($, e.subagentType)
102    return deny ? { deny } : next(e)
103  })
104}
105
hooks/mods/workspace/autosave.ts 82 lines
1// Autosave: the levers on a stale task workspace (base.progress `stale`, never a `guessed` one) — one context line
2// on a person's prompt here; the blocked stop and the notes.md marker before an auto-compact are the Stop and
3// PreCompact command hooks (hooks/conventions.cjs), acting on the autosave-state.json progress.ts mirrors.
4// BASE_AUTOSAVE=0 turns all three off.
5import { atom, read, update } from 'claude-code'
6import type { EngineInterface, FsEntry, On } from 'claude-code'
7import type { BaseCompactMarker } from '../../../types'
8import { logDir } from '../events.ts'
9import { PERSON, autosaveState, newMarker, newestWrite, queueMirror } from './progress.ts'
10
11const progress = atom({ plugin: 'base', key: 'progress' } as const, null)
12const autosave = atom({ plugin: 'base', key: 'autosave' } as const, null)
13const marker = atom({ plugin: 'base', key: 'compactMarker' } as const, null)
14
15type $ = EngineInterface
16
17// progress.ts keeps the same two wrappers: the validator follows `$` only within one file.
18const sessionLogDir = async ($: $): Promise<string | null> =>
19  logDir(await $.env.get('HOME'), await $.env.get('DOMAINE_LOG_DIR'), String(await $.session.id()))
20
21async function adoptMarker($: $): Promise<BaseCompactMarker | null> {
22  const cur = await read($, marker)
23  const dir = await sessionLogDir($).catch(() => null)
24  const m = dir ? newMarker(await $.fs.read(`${dir}/compact-marker.json`).catch(() => null), cur) : null
25  if (!m) return cur
26  await update($, marker, () => m)
27  await update($, autosave, t => (t ? { ...t, nudgedMs: -1 } : t))
28  return m
29}
30
31const mirrorAutosave = ($: $): Promise<void> => queueMirror(() => mirrorOnce($))
32
33async function mirrorOnce($: $): Promise<void> {
34  try {
35    const dir = (await $.env.get('BASE_AUTOSAVE')) === '0' ? null : await sessionLogDir($)
36    if (!dir) return
37    const text = autosaveState(String(await $.session.id()), await $.session.root(), await read($, progress), await read($, autosave))
38    const file = `${dir}/autosave-state.json`
39    if ((await $.fs.read(file).catch(() => null)) !== text) await $.fs.write(file, text)
40  } catch {}
41}
42
43type Workspace = { id: string; mtimeMs: number; stale: boolean }
44
45/** The published workspace with its newest write listed now: a Bash append lands between ticks and un-stales it. */
46async function workspace($: $): Promise<Workspace | null> {
47  if ((await $.env.get('BASE_AUTOSAVE')) === '0') return null
48  const p = await read($, progress)
49  if (!p || p.workId === null || !p.hasWorkspace) return null
50  let entries: FsEntry[] = []
51  try {
52    entries = await $.fs.list(`${await $.session.root()}/.claude/tasks/${p.workId}`)
53  } catch {}
54  const mtimeMs = Math.max(p.mtimeMs, newestWrite(entries, p.workId, await adoptMarker($)))
55  return { id: p.workId, mtimeMs, stale: p.stale && mtimeMs <= p.mtimeMs }
56}
57
58/** Once per stale period: the period ends with the next workspace write (a new `mtimeMs`). */
59async function nudge($: $, ws: Workspace | null): Promise<string | null> {
60  if (!ws?.stale || (await read($, autosave))?.nudgedMs === ws.mtimeMs) return null
61  await update($, autosave, t => (t ? { ...t, nudgedMs: ws.mtimeMs } : t))
62  const age = ws.mtimeMs ? `${Math.floor(((await $.clock.now()) - ws.mtimeMs) / 60_000)} min` : 'unsaved'
63  return `workspace stale ${age}: save findings to .claude/tasks/${ws.id}/notes.md before answering`
64}
65
66export function registerAutosave(on: On): void {
67  on('prompt.submit', { text: /(?:)/ }, async ($, e, next) => {
68    let line: string | null = null
69    try {
70      const ws = await workspace($)
71      // A prompt typed over a running turn, or delivered into it, starts no turn of its own.
72      if (e.turnId === undefined) {
73        const startMs = await $.clock.now()
74        await update($, autosave, t => ({ turn: (t?.turn ?? 0) + 1, startMs, nudgedMs: t?.nudgedMs ?? -1 }))
75        await mirrorAutosave($)
76      }
77      if (PERSON.has(e.origin.kind)) line = await nudge($, ws)
78    } catch {}
79    return next(line ? { ...e, context: [...(e.context ?? []), line] } : e)
80  })
81}
82
hooks/mods/workspace/progress.ts 573 lines
1// Progress: the work-id resolver, the digest refresh and /base-progress (the pin). Writes the base.progress
2// atom band draws its checklist from, with the staleness autosave.ts acts on; base draws nothing itself.
3import { atom, read, update } from 'claude-code'
4import type { EngineInterface, FsEntry, On } from 'claude-code'
5import type { BaseAutosave, BaseCompactMarker, BaseEvent, BaseProgress, BaseSavable } from '../../../types'
6import { logDir, logLine, pushEvent, spareRoot } from '../events.ts'
7import type { Disk } from '../events.ts'
8import { notesTail, parseProgress } from './progress-parse.ts'
9import { KEY, isWorkId, keyFromBranch, projectsOf, slugFromBranch, ticketKeys } from './workid.ts'
10
11export const COMMAND = {
12  name: 'base-progress',
13  description: 'Pin the task base publishes for the checklist (<work-id>, or - to unpin)',
14  argumentHint: '[work-id|-]',
15  immediate: true,
16} as const
17const CHECKLIST = '/band-progress'
18const TICK_MS = 30_000
19const RESOLVE_EVERY = 4
20const FRESH_MS = 12 * 60 * 60_000
21const CHECKOUT = /\bgit\s+(checkout|switch|worktree)\b/
22export const STALE_MS = 20 * 60_000
23/** The levers' stale window once the context window is at or above TIGHT_CTX_PCT full: an auto-compact is near. */
24export const TIGHT_STALE_MS = 5 * 60_000
25const TIGHT_CTX_PCT = 85
26const SAVABLE_CAP = 200
27/** slim's MCP gate: a result past it is one slim compresses or stubs. */
28const MCP_GATE = 4096
29/** slim's handle or stub: the original was over the gate even when the result now is not. */
30const SLIMMED = /<<full=|<<slim stub>>/
31/** Prompt origins a person wrote; notifications, peers and schedules never set the conversation key. */
32export const PERSON = new Set(['composer', 'bridge', 'sdk'])
33
34const progress = atom({ plugin: 'base', key: 'progress' } as const, null)
35const pin = atom({ plugin: 'base', key: 'pin' } as const, null)
36const lastKey = atom({ plugin: 'base', key: 'lastKey' } as const, null)
37const sessionId = atom({ plugin: 'base', key: 'sessionId' } as const, null)
38const events = atom({ plugin: 'base', key: 'events' } as const, [] as BaseEvent[])
39const savable = atom({ plugin: 'base', key: 'savable' } as const, [] as BaseSavable[])
40const background = atom({ plugin: 'base', key: 'background' } as const, [] as string[])
41const saved = atom({ plugin: 'base', key: 'saved' } as const, [] as string[])
42const marker = atom({ plugin: 'base', key: 'compactMarker' } as const, null)
43const autosave = atom({ plugin: 'base', key: 'autosave' } as const, null)
44
45/** Unsaved work: no workspace write for the stale window, and something worth saving happened after the last one. */
46export const isStale = (mtimeMs: number, lastSavableMs: number, now: number, staleMs = STALE_MS): boolean =>
47  now - mtimeMs > staleMs && lastSavableMs > mtimeMs
48
49/** The levers' window from `$.session.usage().context.percent`: 5 min at or above 85 % full, else 20. */
50export const staleWindowOf = (percent: number | null | undefined): number =>
51  (percent ?? 0) >= TIGHT_CTX_PCT ? TIGHT_STALE_MS : STALE_MS
52
53/** The newest write among a workspace root's files; notes.md still at the compact marker's write keeps the time before it. */
54export function newestWrite(entries: readonly FsEntry[], id: string, m: BaseCompactMarker | null): number {
55  let ms = 0
56  for (const f of entries) {
57    if (f.kind !== 'file') continue
58    ms = Math.max(ms, f.name === 'notes.md' && m?.workId === id && f.mtimeMs === m.notesMs ? m.priorMs : f.mtimeMs)
59  }
60  return ms
61}
62
63type Loaded = Extract<BaseProgress, { workId: string }>
64
65/** Events stamped with another work id belong to that task; unstamped ones count for any. */
66function withStaleness(p: Loaded, list: readonly BaseSavable[], now: number, staleMs: number): Loaded {
67  let lastSavableMs = 0
68  let agentsSince = 0
69  let editsSince = 0
70  for (const s of list) {
71    if (s.workId != null && s.workId !== p.workId) continue
72    lastSavableMs = Math.max(lastSavableMs, s.atMs)
73    if (s.atMs <= p.mtimeMs) continue
74    if (s.kind === 'agent') agentsSince++
75    else if (s.kind === 'edit') editsSince++
76  }
77  const stale = p.hasWorkspace && !p.guessed && isStale(p.mtimeMs, lastSavableMs, now, staleMs)
78  return { ...p, lastSavableMs, agentsSince, editsSince, stale }
79}
80
81type $ = EngineInterface
82
83const windowOf = async ($: $): Promise<number> => staleWindowOf((await $.session.usage().catch(() => null))?.context.percent)
84
85/** events.ts's file writer reaches `$` through this: the validator follows `$` only within one file. */
86function diskOf($: $): Disk {
87  return {
88    session: () => $.session.id(),
89    home: () => $.env.get('HOME'),
90    override: () => $.env.get('DOMAINE_LOG_DIR'),
91    manifest: () => $.fs.read(`${$.plugin.root}/.claude-plugin/plugin.json`),
92    read: path => $.fs.read(path),
93    write: (path, text) => $.fs.write(path, text),
94    toast: text => $.ui.toast(text),
95  }
96}
97
98/** Compared with the last logged workspace, not the atom: /clear nulls the atom while the work stays. */
99async function logWorkspace($: $, text: string): Promise<void> {
100  try {
101    if ((await $.env.get('BASE_EVENT_LOG')) === '0') return
102    const ev: BaseEvent = { atMs: await $.clock.now(), kind: 'workspace', text }
103    let pushed = false
104    await update($, events, l => {
105      let last = 'none'
106      for (const e of l) if (e.kind === 'workspace') last = e.text
107      pushed = last !== text
108      return pushed ? pushEvent(l, ev) : l
109    })
110    if (pushed) await logLine(diskOf($), ev)
111  } catch {}
112}
113
114const tasksDir = (root: string) => `${root}/.claude/tasks`
115const workDir = (root: string, id: string) => `${tasksDir(root)}/${id}`
116
117async function branchOf($: $, root: string): Promise<string | null> {
118  try {
119    const r = await $.process.run(['git', 'rev-parse', '--abbrev-ref', 'HEAD'], { cwd: root, timeoutMs: 5000 })
120    return r.exitCode === 0 ? r.stdout.trim() || null : null
121  } catch {
122    return null
123  }
124}
125
126/** The workspace directory itself: a ticket dir without progress.md still names the work. */
127async function hasWorkspace($: $, root: string, id: string | null): Promise<boolean> {
128  if (!id) return false
129  try {
130    return (await $.fs.stat(workDir(root, id))).kind === 'dir'
131  } catch {
132    return false
133  }
134}
135
136async function newestWorkspace($: $, root: string): Promise<string | null> {
137  let dirs
138  try {
139    dirs = (await $.fs.list(tasksDir(root))).filter(d => d.kind === 'dir' && isWorkId(d.name))
140  } catch {
141    return null
142  }
143  const now = await $.clock.now()
144  let best: string | null = null
145  let bestMs = 0
146  for (const d of dirs) {
147    try {
148      const s = await $.fs.stat(`${workDir(root, d.name)}/progress.md`)
149      if (s.kind === 'file' && now - s.mtimeMs <= FRESH_MS && s.mtimeMs > bestMs) {
150        best = d.name
151        bestMs = s.mtimeMs
152      }
153    } catch {}
154  }
155  return best
156}
157
158type Inputs = { pin: string | null; lastKey: string | null }
159
160const readInputs = async ($: $): Promise<Inputs> => ({ pin: await read($, pin), lastKey: await read($, lastKey) })
161
162const inputsFile = async ($: $, sid: string): Promise<string | null> => {
163  const dir = logDir(await $.env.get('HOME'), await $.env.get('DOMAINE_LOG_DIR'), sid)
164  return dir && `${dir}/workspace.json`
165}
166
167/** The inputs on disk under the session id: a resume or an engine restart brings the same id back with empty atoms. */
168async function saveInputs($: $, sid: string): Promise<void> {
169  try {
170    const file = await inputsFile($, sid)
171    if (file) await $.fs.write(file, JSON.stringify(await readInputs($)))
172  } catch {}
173}
174
175/** With both inputs null, takes them from the file `saveInputs` wrote under this very id. */
176async function restoreInputs($: $, sid: string): Promise<void> {
177  try {
178    const cur = await readInputs($)
179    if (cur.lastKey !== null || cur.pin !== null) return
180    const file = await inputsFile($, sid)
181    if (!file || !(await $.fs.exists(file))) return
182    const disk = JSON.parse(await $.fs.read(file)) as Partial<Record<keyof Inputs, unknown>>
183    const ok = (v: unknown): v is string => typeof v === 'string' && isWorkId(v)
184    if (ok(disk.lastKey)) await update($, lastKey, () => disk.lastKey as string)
185    if (ok(disk.pin)) await update($, pin, () => disk.pin as string)
186  } catch {}
187}
188
189/** The names of the `.claude/tasks` dirs. */
190async function taskDirs($: $, root: string): Promise<Set<string>> {
191  try {
192    return new Set((await $.fs.list(tasksDir(root))).filter(d => d.kind === 'dir').map(d => d.name))
193  } catch {
194    return new Set()
195  }
196}
197
198type Resolved = { id: string; guessed: boolean } | null
199
200/**
201 * pin (an existing dir) → conversation key, workspace or not: the ticket the developer named is the task →
202 * branch key → branch slug (existing dirs) → newest progress.md within 12 h → null. The last three are `guessed`.
203 */
204async function resolveWorkId($: $, root: string, branch: string | null, inputs: Inputs): Promise<Resolved> {
205  if (await hasWorkspace($, root, inputs.pin)) return { id: inputs.pin as string, guessed: false }
206  if (inputs.lastKey) return { id: inputs.lastKey, guessed: false }
207  for (const id of [keyFromBranch(branch), slugFromBranch(branch)]) if (await hasWorkspace($, root, id)) return { id: id as string, guessed: true }
208  const id = await newestWorkspace($, root)
209  return id ? { id, guessed: true } : null
210}
211
212/** The most recent ticket the prompt names (`ticketKeys`), else null: the held key stays. */
213async function conversationKey($: $, text: string): Promise<string | null> {
214  if (!KEY.test(text)) return null
215  return ticketKeys(text, projectsOf(await taskDirs($, await $.session.root())))[0] ?? null
216}
217
218async function readText($: $, path: string): Promise<string> {
219  try {
220    return await $.fs.read(path)
221  } catch {
222    return ''
223  }
224}
225
226/** compact-marker.json's marker when it is a new one (another `notesMs` than `cur`), else null. */
227export function newMarker(text: string | null, cur: BaseCompactMarker | null): BaseCompactMarker | null {
228  try {
229    const m = JSON.parse(text ?? '') as Partial<BaseCompactMarker>
230    if (typeof m.workId !== 'string' || typeof m.notesMs !== 'number' || typeof m.priorMs !== 'number' || m.notesMs === cur?.notesMs) return null
231    return { workId: m.workId, notesMs: m.notesMs, priorMs: m.priorMs }
232  } catch {
233    return null
234  }
235}
236
237/** autosave-state.json, what the Stop and PreCompact command hooks act on: the workspace (null without one) and the turn. */
238export function autosaveState(sid: string, root: string, p: BaseProgress | null, t: BaseAutosave | null): string {
239  const ws = p && p.workId !== null && p.hasWorkspace ? p : null
240  const state = {
241    sid,
242    workId: ws?.workId ?? null,
243    wsDir: ws ? workDir(root, ws.workId) : null,
244    stale: ws?.stale ?? false,
245    mtimeMs: ws?.mtimeMs ?? 0,
246    lastSavableMs: ws?.lastSavableMs ?? 0,
247    agentsSince: ws?.agentsSince ?? 0,
248    editsSince: ws?.editsSince ?? 0,
249    turn: t?.turn ?? 0,
250    startMs: t?.startMs ?? 0,
251  }
252  return `${JSON.stringify(state)}\n`
253}
254
255const sessionLogDir = async ($: $): Promise<string | null> =>
256  logDir(await $.env.get('HOME'), await $.env.get('DOMAINE_LOG_DIR'), String(await $.session.id()))
257
258/** A new compact-marker.json becomes base.compactMarker and re-arms the prompt line: the compacted context lost it. */
259async function adoptMarker($: $): Promise<BaseCompactMarker | null> {
260  const cur = await read($, marker)
261  const dir = await sessionLogDir($).catch(() => null)
262  const m = dir ? newMarker(await $.fs.read(`${dir}/compact-marker.json`).catch(() => null), cur) : null
263  if (!m) return cur
264  await update($, marker, () => m)
265  await update($, autosave, t => (t ? { ...t, nudgedMs: -1 } : t))
266  return m
267}
268
269let mirrors: Promise<void> = Promise.resolve()
270
271/** Runs one autosave-state.json mirror after the one before (progress.ts and autosave.ts share the queue). */
272export function queueMirror(job: () => Promise<void>): Promise<void> {
273  mirrors = mirrors.then(job, job)
274  return mirrors
275}
276
277/** Writes autosave-state.json when its text changed, built from the atoms after the previous mirror's write. */
278const mirrorAutosave = ($: $): Promise<void> => queueMirror(() => mirrorOnce($))
279
280async function mirrorOnce($: $): Promise<void> {
281  try {
282    const dir = (await $.env.get('BASE_AUTOSAVE')) === '0' ? null : await sessionLogDir($)
283    if (!dir) return
284    const text = autosaveState(String(await $.session.id()), await $.session.root(), await read($, progress), await read($, autosave))
285    const file = `${dir}/autosave-state.json`
286    if ((await $.fs.read(file).catch(() => null)) !== text) await $.fs.write(file, text)
287  } catch {}
288}
289
290/** The workspace's newest write (`newestWrite`): what the tick compares. */
291async function workspaceMtime($: $, root: string, id: string): Promise<number> {
292  let entries: FsEntry[] = []
293  try {
294    entries = await $.fs.list(workDir(root, id))
295  } catch {}
296  return newestWrite(entries, id, await adoptMarker($))
297}
298
299async function load($: $, root: string, workId: string, branch: string | null, guessed: boolean): Promise<BaseProgress> {
300  const dir = workDir(root, workId)
301  const workspace = await hasWorkspace($, root, workId)
302  const mtimeMs = await workspaceMtime($, root, workId)
303  const parsed = parseProgress(await readText($, `${dir}/progress.md`))
304  const notes = notesTail(await readText($, `${dir}/notes.md`))
305  const p = { workId, branch, hasWorkspace: workspace, ...parsed, notesTail: notes, mtimeMs, lastSavableMs: 0, agentsSince: 0, editsSince: 0, stale: false, guessed }
306  return withStaleness(p, await read($, savable), await $.clock.now(), await windowOf($))
307}
308
309/** A savable event re-derives the staleness fields without re-reading the workspace. */
310async function noteSavable($: $, kind: BaseSavable['kind']): Promise<void> {
311  const now = await $.clock.now()
312  const workId = (await read($, progress))?.workId ?? null
313  const list = await update($, savable, l => [...l, { atMs: now, kind, workId }].slice(-SAVABLE_CAP))
314  const staleMs = await windowOf($)
315  await update($, progress, p => (p && p.workId !== null ? withStaleness(p, list, now, staleMs) : p))
316  await mirrorAutosave($)
317}
318
319/** An agent that wrote the workspace itself (`saved`) brings back nothing unsaved: its return or stop is no event. */
320async function noteAgent($: $, id: string | undefined): Promise<void> {
321  let own = false
322  if (id !== undefined)
323    await update($, saved, l => {
324      own = l.includes(id)
325      return own ? l.filter(s => s !== id) : l
326    })
327  if (!own) await noteSavable($, 'agent')
328}
329
330const markSaved = ($: $, id: string) => update($, saved, l => (l.includes(id) ? l : [...l, id].slice(-SAVABLE_CAP)))
331
332/** The published workspace and its newest write, or null with no work id. */
333async function currentWrite($: $): Promise<{ id: string; ms: number } | null> {
334  const cur = await read($, progress)
335  return cur?.workId ? { id: cur.workId, ms: await workspaceMtime($, await $.session.root(), cur.workId) } : null
336}
337
338/** A tool call that reaches into the guessed workspace (`touches` its dir or id) makes it this session's work. */
339async function adopt($: $, touches: (dir: string, id: string) => boolean): Promise<void> {
340  const cur = await read($, progress)
341  if (!cur || cur.workId === null || !cur.guessed) return
342  const root = await $.session.root()
343  const list = await read($, savable)
344  const now = await $.clock.now()
345  const staleMs = await windowOf($)
346  await update($, progress, p => (p && p.workId !== null && p.guessed && touches(workDir(root, p.workId), p.workId) ? withStaleness({ ...p, guessed: false }, list, now, staleMs) : p))
347  await mirrorAutosave($)
348}
349
350// The root the last refresh resolved under: a tick that finds another (a /cd, a worktree move) resolves again.
351let lastRoot = ''
352
353/** `resolve` re-runs git and the resolver; otherwise only the current workspace is re-read while it exists. */
354async function refresh($: $, resolve: boolean): Promise<void> {
355  const root = await $.session.root()
356  lastRoot = root
357  const cur = await read($, progress)
358  const inputs = await readInputs($)
359  const reload = !resolve && !!cur?.workId && (await hasWorkspace($, root, cur.workId))
360  let next: BaseProgress
361  if (reload && cur?.workId) {
362    next = await load($, root, cur.workId, cur.branch, cur.guessed)
363    // a write since the last read adopts a guessed workspace: it is this session's work now
364    if (next.workId !== null && next.guessed && next.mtimeMs > cur.mtimeMs) next = { ...next, guessed: false }
365  } else {
366    const branch = await branchOf($, root)
367    const r = await resolveWorkId($, root, branch, inputs)
368    // a re-resolve keeps an adopted workspace adopted
369    const guessed = !!r?.guessed && !(cur !== null && cur.workId === r.id && !cur.guessed)
370    next = r ? await load($, root, r.id, branch, guessed) : { workId: null, branch }
371  }
372  // A pin or key change (or /clear) during the awaits started its own, newer resolve.
373  const now = await readInputs($)
374  if (now.pin !== inputs.pin || now.lastKey !== inputs.lastKey) return
375  const after = await update($, progress, prev => (!reload || prev?.workId === next.workId ? next : prev))
376  await logWorkspace($, after?.workId ?? 'none')
377  await mirrorAutosave($)
378}
379
380// The session id whose title.json the tick has read: one read per id once the file is there.
381let titleSid = ''
382
383/** The title hooks/title.cjs set for this session id, as one `title` event (base.events and base.jsonl). */
384async function adoptTitle($: $): Promise<void> {
385  try {
386    const sid = String(await $.session.id())
387    if (sid === titleSid) return
388    const dirs = [logDir(await $.env.get('HOME'), await $.env.get('DOMAINE_LOG_DIR'), sid), logDir(undefined, spareRoot(await $.env.get('TMPDIR')), sid)]
389    let file: { by?: unknown; title?: unknown; ts?: unknown } | null = null
390    for (const d of dirs) {
391      if (!d) continue
392      const text = await $.fs.read(`${d}/title.json`).catch(() => null)
393      if (text === null) continue
394      titleSid = sid
395      try {
396        file = JSON.parse(text) as typeof file
397      } catch {}
398      break
399    }
400    if (!file) return
401    if (file.by !== 'base' || typeof file.title !== 'string' || (await $.env.get('BASE_EVENT_LOG')) === '0') return
402    const ev: BaseEvent = { atMs: typeof file.ts === 'number' ? file.ts : await $.clock.now(), kind: 'title', text: file.title }
403    let pushed = false
404    await update($, events, l => {
405      pushed = !l.some(x => x.kind === 'title' && x.atMs === ev.atMs)
406      return pushed ? pushEvent(l, ev) : l
407    })
408    if (pushed) await logLine(diskOf($), ev)
409  } catch {}
410}
411
412async function tick($: $, resolve: boolean): Promise<void> {
413  await adoptTitle($)
414  const cur = await read($, progress)
415  if (resolve || cur === null || (await $.session.root()) !== lastRoot) return refresh($, true)
416  if (cur.workId === null) return
417  const mtimeMs = await workspaceMtime($, await $.session.root(), cur.workId)
418  if (mtimeMs !== cur.mtimeMs) return refresh($, false)
419  // Time or the context window alone turns a workspace stale: write only when the flag flips.
420  const now = await $.clock.now()
421  const list = await read($, savable)
422  const staleMs = await windowOf($)
423  if (withStaleness(cur, list, now, staleMs).stale !== cur.stale) {
424    await update($, progress, p => (p && p.workId !== null ? withStaleness(p, list, now, staleMs) : p))
425    await mirrorAutosave($)
426  }
427}
428
429export function registerProgress(on: On): void {
430  on('session.start', async ($, e, next) => {
431    const r = await next(e)
432    let ticks = 0
433    $.clock.every(TICK_MS, () => {
434      ticks++
435      void tick($, ticks % RESOLVE_EVERY === 0).catch(() => undefined)
436    })
437    try {
438      const id = await $.session.id()
439      await update($, sessionId, () => id)
440      await restoreInputs($, id)
441    } catch {}
442    await $.command.register(COMMAND).catch(() => undefined)
443    await refresh($, true).catch(() => undefined)
444    return r
445  })
446
447  // A /clear starts a new session id with no session.start: the command and the resolve follow it here.
448  on('prompt.submit', async ($, e, next) => {
449    const r = await next(e)
450    let resolve = false
451    const id = await $.session.id()
452    if (id !== (await read($, sessionId))) {
453      await update($, sessionId, () => id)
454      await restoreInputs($, id)
455      // a pin outlives /clear in memory: the new id's file keeps it for that id's own resume
456      if ((await read($, pin)) !== null) await saveInputs($, id)
457      await $.command.register(COMMAND).catch(() => undefined)
458      resolve = true
459    }
460    const key = PERSON.has(e.origin.kind) ? await conversationKey($, e.text) : null
461    if (key && key !== (await read($, lastKey))) {
462      await update($, lastKey, () => key)
463      await saveInputs($, id)
464      resolve = true
465    }
466    if (resolve) await refresh($, true)
467    return r
468  })
469
470  on('session.end', { reason: 'clear' }, async ($, e, next) => {
471    await update($, progress, () => null)
472    await update($, lastKey, () => null)
473    await update($, savable, () => [])
474    await saveInputs($, e.sessionId)
475    return next(e)
476  })
477
478  on('tool.call', { tool: /^(Write|Edit)$/ }, async ($, e, next) => {
479    const r = await next(e)
480    if (e.tool !== 'Write' && e.tool !== 'Edit') return r
481    if (!e.file_path.includes('/.claude/')) {
482      if (r.deny === undefined && !r.isError && e.agentId === undefined) await noteSavable($, 'edit')
483      return r
484    }
485    const root = await $.session.root()
486    if (!e.file_path.startsWith(`${tasksDir(root)}/`)) return r
487    const cur = await read($, progress)
488    const inCurrent = !!cur?.workId && e.file_path.startsWith(`${workDir(root, cur.workId)}/`)
489    await refresh($, !inCurrent)
490    const path = e.file_path
491    if (r.deny !== undefined || r.isError) return r
492    await adopt($, dir => path.startsWith(`${dir}/`))
493    const after = await read($, progress)
494    const dir = after?.workId ? `${workDir(root, after.workId)}/` : null
495    // a file in the root, as newestWrite counts it
496    if (e.agentId !== undefined && dir && path.startsWith(dir) && !path.slice(dir.length).includes('/')) await markSaved($, e.agentId)
497    return r
498  })
499
500  on('tool.call', { tool: 'Read' }, async ($, e, next) => {
501    const r = await next(e)
502    if (e.tool === 'Read' && e.file_path.includes('/.claude/tasks/') && r.deny === undefined && !r.isError) {
503      const path = e.file_path
504      await adopt($, dir => path.startsWith(`${dir}/`))
505    }
506    return r
507  })
508
509  // A background launch is no result yet: the agent's stop is the savable event.
510  on('tool.call', { tool: /^(Agent|Task)$/ }, async ($, e, next) => {
511    const r = await next(e)
512    if (r.deny !== undefined || r.isError || e.agentId !== undefined) return r
513    const rec = r.result as { status?: unknown; agentId?: unknown } | null | undefined
514    const status = typeof rec === 'object' ? rec?.status : undefined
515    const id = typeof rec === 'object' && typeof rec?.agentId === 'string' ? rec.agentId : undefined
516    if (status === 'async_launched' && id !== undefined) await update($, background, l => [...l, id].slice(-SAVABLE_CAP))
517    else if (status === undefined || status === 'completed') await noteAgent($, id)
518    return r
519  })
520
521  on('turn.complete', async ($, e, next) => {
522    const r = await next(e)
523    const id = e.agentId
524    if (id === undefined) return r
525    let mine = false
526    await update($, background, l => {
527      mine = l.includes(id)
528      return mine ? l.filter(x => x !== id) : l
529    })
530    if (mine) await noteAgent($, id)
531    return r
532  })
533
534  on('tool.call', { tool: /^mcp__/ }, async ($, e, next) => {
535    const r = await next(e)
536    if (r.deny !== undefined || r.isError || e.agentId !== undefined) return r
537    const text = typeof r.result === 'string' ? r.result : (JSON.stringify(r.result) ?? '')
538    if (text.length > MCP_GATE || SLIMMED.test(text)) await noteSavable($, 'mcp')
539    return r
540  })
541
542  // A Bash write to the workspace reaches the atom now, not at the next tick; a subagent's is its own save.
543  on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
544    if (e.tool !== 'Bash') return next(e)
545    const command = e.command
546    const tasks = command.includes('.claude/tasks/')
547    const before = tasks ? await currentWrite($) : null
548    const r = await next(e)
549    if (CHECKOUT.test(command)) await refresh($, true)
550    if (!tasks) return r
551    await adopt($, (_, id) => command.includes(`.claude/tasks/${id}/`))
552    const after = before && (await currentWrite($))
553    if (before && after?.id === before.id && after.ms > before.ms) {
554      await refresh($, false)
555      if (e.agentId !== undefined) await markSaved($, e.agentId)
556    }
557    return r
558  })
559
560  on('command.run', { command: COMMAND.name }, async ($, e) => {
561    const arg = e.args.trim()
562    if (!arg) return { text: `Pinned: ${(await read($, pin)) ?? 'none'}. The checklist is band's: ${CHECKLIST}` }
563    if (arg !== '-' && !isWorkId(arg)) return { text: `Not a work id: ${arg}` }
564    await update($, pin, () => (arg === '-' ? null : arg))
565    await saveInputs($, await $.session.id())
566    await refresh($, true)
567    if (arg === '-') return { text: `Unpinned. ${CHECKLIST} shows the checklist.` }
568    const cur = await read($, progress)
569    const text = `Pinned ${arg}. ${CHECKLIST} shows it.`
570    return { text: cur?.workId === arg ? text : `${text} ${arg} has no task workspace.` }
571  })
572}
573
hooks/mods/events.ts 183 lines
1// base's event list and its file on disk, `<log dir>/<session-id>/base.jsonl`. No `$` here: each writer file
2// keeps its own wrapper, which pushes the line to base.events and then hands it to `logLine` with a `Disk` it
3// built, as the validator follows `$` only within one file (ARCHITECTURE.md §3).
4import type { BaseEvent } from '../../types'
5
6export const EVENT_CAP = 200
7export const FILE_LINES = 2000
8export const FILE_BYTES = 256 * 1024
9/** A session directory whose newest file is older than this is swept at a session start. */
10export const LOG_TTL_MS = 7 * 24 * 3_600_000
11
12/** Appends `ev`, oldest first, at most EVENT_CAP: past the cap the oldest line goes. */
13export function pushEvent(list: readonly BaseEvent[], ev: BaseEvent): BaseEvent[] {
14  return list.length < EVENT_CAP ? [...list, ev] : [...list.slice(1), ev]
15}
16
17/** `base scratch-path guard: <reason>` → `<reason>`: the kind column already names the source. */
18export function bare(text: string): string {
19  return text.replace(/^base[ -][a-z -]+?: /, '')
20}
21
22/** `mcp__plugin_base_chrome-devtools-mcp__take_screenshot` → `take_screenshot`. */
23export function toolName(tool: string): string {
24  return tool.split('__').pop() ?? tool
25}
26
27const trimSlash = (p: string) => p.replace(/\/+$/, '')
28
29/** `$HOME/.claude/domaine/log`, the only directory the sweep deletes in; null without an absolute HOME. */
30export function defaultLogRoot(home: string | undefined): string | null {
31  const h = home?.trim() ?? ''
32  return h.startsWith('/') ? `${trimSlash(h)}/.claude/domaine/log` : null
33}
34
35/** A name the engine could not have made a session id of never becomes a path segment. */
36export function isSessionName(name: string): boolean {
37  return /^[\w.-]+$/.test(name) && !/^\.+$/.test(name)
38}
39
40/** `<DOMAINE_LOG_DIR>/<session>` when the override is absolute, else `$HOME/.claude/domaine/log/<session>`; null with neither. */
41export function logDir(home: string | undefined, override: string | undefined, session: string): string | null {
42  if (!isSessionName(session)) return null
43  const o = override?.trim() ?? ''
44  const root = o.startsWith('/') ? trimSlash(o) : defaultLogRoot(home)
45  return root === null ? null : `${root}/${session}`
46}
47
48/** The spare root the command hook leaves its marker under without a writable log dir: `<TMPDIR or /tmp>/domaine-log`. */
49export function spareRoot(tmp: string | undefined): string {
50  const t = tmp?.trim() ?? ''
51  return `${t.startsWith('/') ? trimSlash(t) : '/tmp'}/domaine-log`
52}
53
54/** Where the SessionStart command hook leaves its marker: `<log dir>/<session>/conventions.<stem>.json` (`base`, `base.rules`), else under the spare root. */
55export const markerPaths = (home: string | undefined, override: string | undefined, tmp: string | undefined, sid: string, stem = 'base'): string[] =>
56  [logDir(home, override, sid), logDir(undefined, spareRoot(tmp), sid)].flatMap(d => (d ? [`${d}/conventions.${stem}.json`] : []))
57
58/** One base.jsonl line; `plugin` is base's own name, never taken from another plugin's state. */
59export function fileLine(ev: BaseEvent, version: string, session: string): string {
60  return JSON.stringify({ ts: new Date(ev.atMs).toISOString(), plugin: 'base', version, session, kind: ev.kind, agent: 'main', text: ev.text })
61}
62
63export function utf8Bytes(s: string): number {
64  let n = 0
65  for (const ch of s) {
66    const cp = ch.codePointAt(0) ?? 0
67    n += cp < 0x80 ? 1 : cp < 0x800 ? 2 : cp < 0x10000 ? 3 : 4
68  }
69  return n
70}
71
72/** Drops the oldest lines past FILE_LINES lines or FILE_BYTES bytes; the newest line always stays. */
73function trimFront(out: string[]): string[] {
74  let bytes = 0
75  for (const l of out) bytes += utf8Bytes(l) + 1
76  let cut = 0
77  while (out.length - cut > 1 && (out.length - cut > FILE_LINES || bytes > FILE_BYTES)) bytes -= utf8Bytes(out[cut++]!) + 1
78  return cut ? out.slice(cut) : out
79}
80
81/** Appends `line` within the cap. */
82export function capLines(lines: readonly string[], line: string): string[] {
83  return trimFront([...lines, line])
84}
85
86/** The lines of a base.jsonl that belong to `session`, oldest first, within the cap: what a reload goes on from. */
87export function seedLines(text: string, session: string): string[] {
88  return trimFront(text.split('\n').filter(l => {
89    try {
90      return (JSON.parse(l) as { session?: unknown }).session === session
91    } catch {
92      return false
93    }
94  }))
95}
96
97const hasStart = (lines: readonly string[]) => lines.some(l => l.includes('"kind":"start"'))
98
99/**
100 * The file's lines after `ev`: the start line first in every session (a /clear's new id gets one before its
101 * first event, as no session.start announces it), and one start line per session.
102 */
103export function nextLines(lines: readonly string[], ev: BaseEvent, version: string, session: string): string[] | null {
104  if (ev.kind === 'start') return hasStart(lines) ? null : capLines(lines, fileLine(ev, version, session))
105  const head = lines.length ? lines : [fileLine({ atMs: ev.atMs, kind: 'start', text: `base ${version}` }, version, session)]
106  return capLines(head, fileLine(ev, version, session))
107}
108
109/** What the writer needs from `$`, built by each writer file's `diskOf`. */
110export type Disk = {
111  session: () => Promise<string>
112  home: () => Promise<string | undefined>
113  override: () => Promise<string | undefined>
114  manifest: () => Promise<string>
115  read: (path: string) => Promise<string>
116  write: (path: string, text: string) => Promise<void>
117  toast: (text: string) => void
118}
119
120type Sink = { path: string; lines: string[] }
121
122// Module-local, so a hot reload starts from the file: the lines already on disk for this session.
123let sink: Promise<Sink | null> | null = null
124let sinkSession = ''
125let version: Promise<string> | null = null
126let writes: Promise<void> = Promise.resolve()
127let toasted = ''
128
129async function readVersion(disk: Disk): Promise<string> {
130  try {
131    const v = (JSON.parse(await disk.manifest()) as { version?: unknown }).version
132    return typeof v === 'string' && v ? v : 'unknown'
133  } catch {
134    return 'unknown'
135  }
136}
137
138async function openSink(disk: Disk, session: string): Promise<Sink | null> {
139  const dir = logDir(await disk.home(), await disk.override(), session)
140  if (dir === null) return null
141  const path = `${dir}/base.jsonl`
142  let lines: string[] = []
143  try {
144    lines = seedLines(await disk.read(path), session)
145  } catch {}
146  return { path, lines }
147}
148
149/**
150 * Rewrites this session's base.jsonl with `ev` appended (`$.fs.write` has no append), after the line went to
151 * base.events. Never throws; one toast per session when a write fails.
152 */
153export async function logLine(disk: Disk, ev: BaseEvent): Promise<void> {
154  let session = ''
155  try {
156    session = await disk.session()
157    if (!sink || sinkSession !== session) {
158      sinkSession = session
159      sink = openSink(disk, session).catch(() => null)
160    }
161    version ??= readVersion(disk)
162    const v = await version
163    const s = await sink
164    if (!s) return
165    // Read, append and write inside one queue: two events in flight never build on the same snapshot.
166    const w = writes.then(async () => {
167      const lines = nextLines(s.lines, ev, v, session)
168      if (!lines) return
169      s.lines = lines
170      await disk.write(s.path, `${lines.join('\n')}\n`)
171    })
172    writes = w.catch(() => {})
173    await w
174  } catch (err) {
175    if (toasted === session) return
176    toasted = session
177    const reason = String((err as { message?: unknown } | null)?.message ?? err).replace(/\s+/g, ' ').slice(0, 120)
178    try {
179      disk.toast(`base: event log not written: ${reason}`)
180    } catch {}
181  }
182}
183
hooks/mods/dogfood/text.ts 434 lines
1// Dogfood mode's pure parts: the plugin_defect tool's schema, the report file's name and
2// body, the install-record readings, the plugin-script failure test and the index parser. No `$` here.
3import { utf8Bytes } from '../events.ts'
4
5export const PLUGINS = ['slim', 'band', 'base', 'fe', 'be', 'qa', 'pm'] as const
6export const KINDS = ['skill', 'script', 'hook', 'mod', 'doctor', 'output', 'docs', 'other'] as const
7export const SUSPECTS = ['plugin', 'project', 'unsure'] as const
8export const TOOL_NAME = 'plugin_defect'
9export const TOOL = `mcp__base__${TOOL_NAME}`
10export const EVIDENCE_BYTES = 2048
11/** Every other free-text field; the model's text is data and never grows a report without bound. */
12export const FIELD_CHARS = 4000
13export const TITLE_CHARS = 120
14export const SLUG_CHARS = 40
15export const WINDOW_DAYS = 7
16export const NUDGE = 'base dogfood: a plugin script failed — report it with plugin_defect (not among your tools: in your reply) before working around it'
17
18export const TOOL_DESC = `Report a defect in a Domaine plugin (${PLUGINS.join(', ')}) you hit while working: a script that failed or returned odd output, a hook or mod that threw, a skill that contradicts the code, a doctor FAIL, wrong slim output, a convention wrong for this host. Writes a report under the project's .claude/plugin-defects/ and returns its path; github: true also files a GitHub issue (only when the person asked). Where no surface draws (a cloud session, claude -p) it returns the whole report and files the issue unless github: false. Never put secrets, tokens or passwords in any field.`
19
20export const TOOL_SCHEMA = {
21  type: 'object',
22  properties: {
23    plugin: { type: 'string', enum: [...PLUGINS], description: 'The plugin at fault.' },
24    kind: { type: 'string', enum: [...KINDS], description: 'What part of it.' },
25    title: { type: 'string', description: `One line, at most ${TITLE_CHARS} characters.` },
26    path: { type: 'string', description: "The plugin file at fault as file:line, or ''." },
27    observed: { type: 'string', description: 'What happened.' },
28    expected: { type: 'string', description: 'What should have happened.' },
29    reproduce: { type: 'string', description: 'The commands or the tool call that show it.' },
30    evidence: { type: 'string', description: `The raw output, error or stub; cut at ${EVIDENCE_BYTES} bytes.` },
31    suspect: { type: 'string', enum: [...SUSPECTS], description: 'Whose fault it looks like.' },
32    github: { type: 'boolean', description: 'Also file a GitHub issue; true only when the person asked. Default false; where no surface draws, default true.' },
33  },
34  required: ['plugin', 'kind', 'title', 'observed', 'expected'],
35} as const
36
37export type Plugin = (typeof PLUGINS)[number]
38export type Defect = {
39  plugin: Plugin
40  kind: (typeof KINDS)[number]
41  title: string
42  path: string
43  observed: string
44  expected: string
45  reproduce: string
46  evidence: string
47  suspect: (typeof SUSPECTS)[number]
48  /** null = not given: the session decides (no surface draws → file). */
49  github: boolean | null
50}
51
52// C0 but tab and newline, DEL, C1: an ESC or NUL must not reach a file name, a heading, the index or gh's argv.
53const CONTROL = /[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g
54const str = (v: unknown) => (typeof v === 'string' ? v.replace(/\r\n?/g, '\n').replace(CONTROL, '') : '')
55const oneOf = <T extends string>(list: readonly T[], v: unknown): T | null => (list as readonly unknown[]).includes(v) ? (v as T) : null
56const cut = (s: string, n: number) => (s.length > n ? `${s.slice(0, n)} [cut at ${n} characters]` : s)
57
58/** The tool's arguments checked and capped, or the reason they are refused. */
59export function parseDefect(a: Record<string, unknown>): Defect | string {
60  const plugin = oneOf(PLUGINS, a.plugin)
61  if (!plugin) return `plugin_defect: plugin must be one of ${PLUGINS.join(', ')}`
62  const kind = oneOf(KINDS, a.kind)
63  if (!kind) return `plugin_defect: kind must be one of ${KINDS.join(', ')}`
64  const title = str(a.title).replace(/\s+/g, ' ').trim().slice(0, TITLE_CHARS)
65  if (!title) return 'plugin_defect: title is empty'
66  return {
67    plugin,
68    kind,
69    title,
70    path: str(a.path).replace(/\s+/g, ' ').trim().slice(0, 300),
71    observed: cut(str(a.observed).trim(), FIELD_CHARS),
72    expected: cut(str(a.expected).trim(), FIELD_CHARS),
73    reproduce: cut(str(a.reproduce).trim(), FIELD_CHARS),
74    evidence: capEvidence(str(a.evidence)),
75    suspect: oneOf(SUSPECTS, a.suspect) ?? 'unsure',
76    github: typeof a.github === 'boolean' ? a.github : null,
77  }
78}
79
80/** At most EVIDENCE_BYTES UTF-8 bytes, with a line saying how much was given when cut. */
81export function capEvidence(text: string): string {
82  const total = utf8Bytes(text)
83  if (total <= EVIDENCE_BYTES) return text
84  let out = ''
85  let n = 0
86  for (const ch of text) {
87    n += utf8Bytes(ch)
88    if (n > EVIDENCE_BYTES) break
89    out += ch
90  }
91  return `${out}\n[evidence truncated at 2 KB: ${total} bytes given]`
92}
93
94/** `[a-z0-9-]`, at most SLUG_CHARS, never empty: no path separator or dot survives. */
95export function slugOf(title: string): string {
96  const s = title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, SLUG_CHARS).replace(/-+$/, '')
97  return s || 'defect'
98}
99
100/** `<date>-<plugin>-<slug>`, `-2`, `-3`… for the n-th clash. */
101export function fileName(date: string, plugin: Plugin, slug: string, n: number): string {
102  return `${date}-${plugin}-${slug}${n > 1 ? `-${n}` : ''}.md`
103}
104
105/** A fence longer than any backtick run in `text`: the text cannot close it and forge a section after it. */
106export function fenced(text: string, lang = 'text'): string {
107  const longest = Math.max(2, ...[...text.matchAll(/`+/g)].map(m => m[0].length))
108  const f = '`'.repeat(longest + 1)
109  return `${f}${lang}\n${text}\n${f}`
110}
111
112export type Environment = {
113  root: string
114  remote: string | null
115  branch: string | null
116  commit: string | null
117  versions: string
118  surfaces: string
119  claudeCode: string | null
120  session: string
121  workId: string | null
122}
123
124export type Meta = { version: string; date: string; session: string; workId: string | null }
125
126export function defectBody(d: Defect, m: Meta, env: Environment): string {
127  const or = (s: string, none = '(none given)') => s || none
128  return [
129    '---',
130    `plugin: ${d.plugin}`,
131    `version: ${JSON.stringify(m.version)}`,
132    `kind: ${d.kind}`,
133    `suspect: ${d.suspect}`,
134    `date: ${m.date}`,
135    `session: ${JSON.stringify(m.session)}`,
136    `work_id: ${m.workId === null ? 'null' : JSON.stringify(m.workId)}`,
137    '---',
138    '',
139    `# [${d.plugin}] ${d.title}`,
140    '',
141    `Path: ${or(d.path, '(not given)')}`,
142    '',
143    '## Observed',
144    '',
145    d.observed ? fenced(d.observed) : '(none given)',
146    '',
147    '## Expected',
148    '',
149    d.expected ? fenced(d.expected) : '(none given)',
150    '',
151    '## Reproduce',
152    '',
153    d.reproduce ? fenced(d.reproduce) : '(none given)',
154    '',
155    '## Evidence',
156    '',
157    d.evidence ? fenced(d.evidence) : '(none given)',
158    '',
159    '## Environment',
160    '',
161    `- project root: ${env.root}`,
162    `- git: ${env.remote?.replace(/^([a-z][\w+.-]*:\/\/)[^@/]*@/i, '$1') ?? '(no remote)'} · ${env.branch ?? '(no branch)'} · ${env.commit ?? '(no commit)'}`,
163    `- plugins: ${env.versions}`,
164    `- surfaces: ${env.surfaces}`,
165    `- Claude Code: ${env.claudeCode ?? 'unknown'}`,
166    `- session: ${env.session}`,
167    `- work id: ${env.workId ?? 'none'}`,
168    '',
169  ].join('\n')
170}
171
172export const indexLine = (date: string, d: Defect, path: string) => `- ${date} ${d.plugin} ${d.title} → ${path}`
173
174type Record_ = { installPath?: unknown; version?: unknown }
175
176/** installed_plugins.json's records as `[name, marketplace, record]`; [] when unreadable. */
177function records(installed: string | null): [string, string, Record_][] {
178  try {
179    const plugins = (JSON.parse(installed ?? '') as { plugins?: Record<string, Record_[]> }).plugins ?? {}
180    return Object.entries(plugins).flatMap(([key, list]) => {
181      const at = key.lastIndexOf('@')
182      return Array.isArray(list) && at > 0 ? list.map(r => [key.slice(0, at), key.slice(at + 1), r] as [string, string, Record_]) : []
183    })
184  } catch {
185    return []
186  }
187}
188
189/** The marketplace base was installed from: the record whose install path is base's root; null for a --plugin-dir or synced load. */
190export function marketplaceOf(installed: string | null, root: string): string | null {
191  return records(installed).find(([name, , r]) => name === 'base' && r.installPath === root)?.[1] ?? null
192}
193
194/**
195 * Each Domaine plugin this session can name, with its version where known: base's own manifest, slim's info
196 * atom, then the install record (base's marketplace first); a plugin enabled in settings without a record
197 * stands without a version.
198 */
199export function versionsOf(installed: string | null, root: string, own: string, slim: string | null, enabled: readonly string[]): Map<Plugin, string | null> {
200  const mk = marketplaceOf(installed, root)
201  const recs = records(installed)
202  const out = new Map<Plugin, string | null>()
203  for (const p of PLUGINS) {
204    const rec = recs.find(([n, m]) => n === p && m === mk) ?? recs.find(([n]) => n === p)
205    const v = p === 'base' ? own : p === 'slim' && slim ? slim : typeof rec?.[2].version === 'string' ? rec[2].version : null
206    if (v !== null || p === 'base' || enabled.includes(p)) out.set(p, v)
207  }
208  return out
209}
210
211export function versionsLine(v: Map<Plugin, string | null>): string {
212  return [...v].map(([p, ver]) => (ver ? `${p} ${ver}` : `${p} (version unknown)`)).join(', ')
213}
214
215/** The enabledPlugins names of settings that are switched on. */
216export function enabledNames(settings: unknown): string[] {
217  const e = (settings as { enabledPlugins?: unknown } | null)?.enabledPlugins
218  if (!e || typeof e !== 'object') return []
219  return Object.entries(e as Record<string, unknown>).filter(([, on]) => on === true).map(([k]) => (k.lastIndexOf('@') > 0 ? k.slice(0, k.lastIndexOf('@')) : k))
220}
221
222const REPO = /^[\w.-]+\/[\w.-]+$/
223
224/** `owner/repo` of a marketplace with a github source; null otherwise. */
225export function repoOf(known: string | null, marketplace: string | null): string | null {
226  if (!marketplace) return null
227  try {
228    const src = (JSON.parse(known ?? '') as Record<string, { source?: { source?: unknown; repo?: unknown } }>)[marketplace]?.source
229    return src?.source === 'github' && typeof src.repo === 'string' && REPO.test(src.repo) ? src.repo : null
230  } catch {
231    return null
232  }
233}
234
235export const isRepo = (s: string) => REPO.test(s)
236
237const NAMES = PLUGINS.join('|')
238// A path runs only in command position: a command's first word, or the script argument of an interpreter that is one.
239const RUN = `(?:^|[;&|(\`])\\s*(?:(?:\\w+=\\S*|env|exec|time)\\s+)*(?:[^\\s;&|()]*/)?(?:(?:node|bash|sh|zsh|python3?)(?:\\s+-\\S+)*\\s+)?["']?`
240const IN_REPO = new RegExp(`${RUN}(?:[^\\s"';|&()]*/)?plugins/(?:${NAMES})/scripts/[^\\s"';|&)<>\`]+`)
241const IN_CACHE = new RegExp(
242  `${RUN}[^\\s"';|&()]*/\\.claude[^/\\s"']*/plugins/(?:cache/[^/\\s"']+/(?:${NAMES})/[^/\\s"']+|synced/[^/\\s"']+/(?:${NAMES})(?:~[^/\\s"']*)?)/scripts/[^\\s"';|&)<>\`]+`,
243)
244const base = (p: string) => p.slice(p.lastIndexOf('/') + 1)
245
246/** The basename of the Domaine plugin script a command runs (repo `plugins/<name>/scripts/`, the plugin cache of any config dir or its synced copy), else null; a path merely named (grep, cat, ls) is not a run. */
247export function pluginScript(command: string): string | null {
248  const p = (IN_CACHE.exec(command) ?? IN_REPO.exec(command))?.[0]
249  return p ? base(p) : null
250}
251
252/** The basenames of every Domaine plugin script a command runs, in no particular order. */
253export const pluginScripts = (command: string): string[] =>
254  [IN_CACHE, IN_REPO].flatMap(re => [...command.matchAll(new RegExp(re.source, 'g'))].map(m => base(m[0])))
255
256/**
257 * True when the plugin script's command is the line's last: the exit code is then the script's own. After
258 * `script; echo done` or `script | head` it belongs to another command (`2>&1` redirects are not a `&`).
259 */
260export function scriptLast(command: string): boolean {
261  const m = IN_CACHE.exec(command) ?? IN_REPO.exec(command)
262  if (!m) return false
263  const tail = command.slice(m.index + m[0].length).replace(/\d*>&\d+/g, '')
264  return !/[;&|\n]/.test(tail)
265}
266
267/** The stdout and stderr of a Bash result as one text. */
268export function bashText(r: { result?: unknown; text?: unknown }): string {
269  if (typeof r.result === 'string') return r.result
270  const o = (r.result ?? {}) as { stdout?: unknown; stderr?: unknown }
271  const parts = [o.stdout, o.stderr].filter((s): s is string => typeof s === 'string')
272  return parts.length ? parts.join('\n') : typeof r.text === 'string' ? r.text : ''
273}
274
275/** A Bash result that failed: an error result, or `Error` in its stderr. */
276export function bashFailed(r: { isError?: true; result?: unknown }): boolean {
277  if (r.isError) return true
278  const stderr = (r.result as { stderr?: unknown } | null)?.stderr
279  return typeof stderr === 'string' && /\bError\b/.test(stderr)
280}
281
282/**
283 * The `error=` reasons that are refusals: the caller's input or usage, the checkout or toml, a store state a guard
284 * stops at, a named thing that is not there, a designed degrade rung, a credential not set up. Every other
285 * reason — a tool or the plugin's own file missing, a credential set but rejected, a remote call, the script's own
286 * machinery — is a failure. Matched against the text after `error=`; a free-text reason (`unknown arg: x`) counts too.
287 */
288const REFUSAL = new RegExp(`^(?:${[
289  'usage', 'unknown[_ ]', 'unexpected_', 'missing[_ ]', 'too many ', '(?:--)?[a-z][a-z-]* (?:requires|needs) ', 'conflicting_', 'ambiguous_',
290  'not_a_', 'not_applied', 'upload_rejected\\b', 'unusable_', 'unsupported_', 'no uncommented ', 'config not found',
291  'no_(?:store|such_dir|origin|free_port|jira_credentials|(?:admin|theme|figma)_token)\\b', 'bad_(?:theme_id|file|build_script)\\b',
292  'file_not_writable\\b', '(?:\\w+_)?invalid_(?!\\w*(?:token|credentials)\\b)',
293  '\\w+_(?:refused|mismatch|drift|limit|missing|dirty|detached|taken|elsewhere|not_a_symlink|not_in_repo|not_ignored)\\b',
294  '(?!\\w*(?:cli|jq|curl|runner|lib)_not)\\w+_not_found',
295].join('|')})`)
296
297const errorReasons = (text: string) => [...text.matchAll(/^error=(.*)$/gm)].map(m => m[1]!)
298
299/** An `error=` line that is a failure, not a refusal: worth a report even when the line's exit code is another command's. */
300export const failureLine = (text: string): boolean => errorReasons(text).some(r => !REFUSAL.test(r))
301
302/** The host's own `Exit code N` line (`Error: Exit code N` on an error result): never the script's words. */
303const EXIT_LINE = /^\s*(?:Error:\s*)?Exit code \d+\s*$/
304
305/**
306 * The line that names a failure: the first failing `error=` line, else the first with `Error`, else the first
307 * non-empty line; the host's `Exit code N` line never counts; at most 160 chars.
308 */
309export function errorLine(text: string): string {
310  const reason = errorReasons(text).find(r => !REFUSAL.test(r))
311  if (reason !== undefined) return `error=${reason}`.trim().slice(0, 160)
312  const lines = text.split('\n').filter(l => l.trim() && !EXIT_LINE.test(l))
313  return (lines.find(l => /Error\b/.test(l)) ?? lines[0] ?? '').trim().slice(0, 160)
314}
315
316/** One unreported plugin-script failure of the main loop, as dogfood-state.json's `errors` lists them. */
317export type ScriptError = { script: string; line: string; ms: number }
318
319/** The `errors` of a prior dogfood-state.json text that belong to session `sid` and came after the report at `reportMs`. */
320export function priorErrors(json: string | null, sid: string, reportMs: number): ScriptError[] {
321  try {
322    const s = JSON.parse(json ?? '') as { sid?: unknown; errors?: unknown }
323    if (s.sid !== sid || !Array.isArray(s.errors)) return []
324    return s.errors.filter(
325      (e): e is ScriptError => !!e && typeof e.script === 'string' && typeof e.line === 'string' && typeof e.ms === 'number' && e.ms > reportMs,
326    )
327  } catch {
328    return []
329  }
330}
331
332/**
333 * A refusal the script printed on purpose, with no crash signature: its `error=` lines all refusals, or, with
334 * none, a `<stem>: <why>` line (a base script's die). The script did its job, nothing to report.
335 */
336export function designedRefusal(text: string, script: string): boolean {
337  if (crashed(text)) return false
338  const reasons = errorReasons(text)
339  if (reasons.length) return reasons.every(r => REFUSAL.test(r))
340  return new RegExp(`^${esc(script.replace(/\.[a-z]+$/, ''))}: `, 'm').test(text)
341}
342
343const esc = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
344
345/** A crash signature in the output: `Error` (an exception, a node stack) outside the host's `Exit code N` line; never a refusal. */
346export const crashed = (text: string): boolean => text.split('\n').some(l => /\bError\b/.test(l) && !EXIT_LINE.test(l))
347
348/**
349 * A crash the script's own trace names: `Error` (`TypeError`, …) with a stack frame `<script>:12`, or a shell's `<script>: line 12:`.
350 * In a compound line another command's `Error` (tsc, git, a husky hook) is in the same output and is not the script's.
351 */
352export function crashedIn(text: string, script: string): boolean {
353  const s = esc(script)
354  return (/Error\b/.test(text) && new RegExp(`(?:^|[/\\s(])${s}:\\d+`, 'm').test(text)) || new RegExp(`(?:^|/)${s}: line \\d+: `, 'm').test(text)
355}
356
357/**
358 * A result the permission layer wrote in place of the command's (its text opens with the denial, `Error: ` allowed):
359 * nothing ran, so no script failed. Covers the interactive denials and the headless ones (`claude -p`, cron, cloud).
360 */
361export const deniedNotRun = (text: string): boolean =>
362  /^\s*(?:Error:\s*)?(?:Permission (?:for|to) .* denied|The user doesn't want to proceed with this tool use|This command requires approval|Claude requested permissions? to .* but you haven't granted it yet)/.test(text)
363
364export type Seen = { date: string; plugin: string; title: string; path: string }
365
366const LINE = /^- (\d{4}-\d{2}-\d{2}) (\S+) (.*) → (\/.*)$/
367const NAME = /^(\d{4}-\d{2}-\d{2})-([a-z]+)-([a-z0-9-]+)\.md$/
368
369/**
370 * The index lines and the project folder's report files as one list, newest first, a path once (the
371 * index's title wins over a file name's slug).
372 */
373export function seen(index: string, projectDir: string, names: readonly string[]): Seen[] {
374  const out = new Map<string, Seen>()
375  for (const l of index.split('\n')) {
376    const m = LINE.exec(l.trim())
377    if (m) out.set(m[4]!, { date: m[1]!, plugin: m[2]!, title: m[3]!, path: m[4]! })
378  }
379  for (const n of names) {
380    const m = NAME.exec(n)
381    const path = `${projectDir}/${n}`
382    if (m && !out.has(path)) out.set(path, { date: m[1]!, plugin: m[2]!, title: m[3]!, path })
383  }
384  // Within a day, a later line or name was written later.
385  return [...out.values()].map((s, i) => ({ s, i })).sort((a, b) => b.s.date.localeCompare(a.s.date) || b.i - a.i).map(x => x.s)
386}
387
388/** The reports of the last WINDOW_DAYS days, `now` included. */
389export function recent(list: readonly Seen[], nowMs: number): Seen[] {
390  const from = new Date(nowMs - (WINDOW_DAYS - 1) * 86_400_000).toISOString().slice(0, 10)
391  return list.filter(s => s.date >= from)
392}
393
394export const isoDate = (ms: number) => new Date(ms).toISOString().slice(0, 10)
395
396/**
397 * Dogfood mode: on under BASE_DOGFOOD=1; else, unless BASE_DOGFOOD=0, for a claude.ai account dogfood.json lists —
398 * the file follows the plugin into every synced sandbox, where no environment variable of the person's can be set.
399 */
400export function dogfoodMode(sw: string, account: string, json: string | null): boolean {
401  if (sw === '1') return true
402  if (sw === '0') return false
403  const id = account.trim()
404  return id !== '' && dogfoodAccounts(json).includes(id)
405}
406
407/** The login file the account id comes from: `$HOME/.claude.json` for the default config dir, else `<CLAUDE_CONFIG_DIR>/.claude.json`. */
408export function loginFile(home: string | undefined, configDir: string | undefined): string | null {
409  const abs = (p: string | undefined) => (p?.trim().startsWith('/') ? p.trim().replace(/\/+$/, '') : '')
410  const h = abs(home)
411  const c = abs(configDir)
412  return c && c !== `${h}/.claude` ? `${c}/.claude.json` : h ? `${h}/.claude.json` : null
413}
414
415/** A login file's `oauthAccount.accountUuid`; '' for a missing or malformed file. */
416export function loginAccount(json: string | null): string {
417  try {
418    const id = (JSON.parse(json ?? '') as { oauthAccount?: { accountUuid?: unknown } }).oauthAccount?.accountUuid
419    return typeof id === 'string' ? id : ''
420  } catch {
421    return ''
422  }
423}
424
425/** The claude.ai account ids dogfood.json lists (`accounts`: id → name); [] for a missing or malformed file. */
426export function dogfoodAccounts(json: string | null): string[] {
427  try {
428    const a = (JSON.parse(json ?? '') as { accounts?: unknown }).accounts
429    return a && typeof a === 'object' && !Array.isArray(a) ? Object.keys(a) : []
430  } catch {
431    return []
432  }
433}
434