SLOPSHOPPER

XTrace MemHub

Team memory for Claude Code. Your sessions are saved automatically, so past work is searchable later. Your team's rules show up while you work, at the moment…

bandguardcommandstatuspromptprocess
★ 2v0.133.0Apache-2.0updated 2026-10-15XTraceAI/agent-plugins/plugins/memhub
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · memhub
› fix the failing auth test and add an audit log call ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM › /goose ⎿ memhub: goose: following the session ♥ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts ⚠ memhub: MemHub rules: fell back to the command hooks

Draws

Band
♥
README

MemHub

MemHub gives coding agents shared team memory. This plugin connects Claude Code to MemHub by XTrace. It provides MCP tools for searching and saving team knowledge, and it captures your sessions into your personal MemHub memory automatically. It also enforces your team's Rulebook rules on tool calls, and adds skills for artifacts, specs, handoffs, PR linking and PR babysitting.

The plugin uploads data to MemHub in the background. The section What it runs, sends, and fetches lists every hook, every network destination and every local file. Please read it before you install.

Install

XTrace publishes this plugin from two sources. Install it from one of them:

  • The Claude plugin directory. Install memhub on claude.ai under Customize > Plugins, or in Claude Code with /plugin install memhub@claude-plugins-official. The directory's copy is built from XTraceAI/xtrace-claude-plugin, and Claude Code updates it once each new version is published to the directory. New versions can reach the directory a little later than the marketplace below.
  • The XTrace marketplace. Add it by hand:
  /plugin marketplace add XTraceAI/agent-plugins
  /plugin install memhub@memhub
  /reload-plugins

Install it from one source only. Both copies register the same hooks and an MCP server named memhub, so with both enabled every session is captured twice and every team rule fires twice. To switch, uninstall the copy you have (/plugin uninstall memhub@memhub or /plugin uninstall memhub@claude-plugins-official), restart Claude Code, then install the other.

Then, from the repository you want to connect:

  1. Run /memhub:onboard. It signs the plugin in (the same sign-in as /memhub:login, which background capture and the hooks need), sets up this machine's hooks, and creates or selects the repository's agent brain.

Requirements: python3 3.9 or newer and git. The hooks and the skills' scripts use only the Python standard library, so nothing else is installed: skills run them as python3 "${CLAUDE_PLUGIN_ROOT}/scripts/<script>.py" or python3 "${CLAUDE_PLUGIN_ROOT}/skills/<skill>/scripts/<script>.py".

Authentication

There are two credentials, and setting up one does not set up the other.

  • MCP tools (the memhub server). The server is https://api.memhub.xtrace.ai/mcp-server/mcp. Its OAuth login uses the Auth0 tenant memhub-prod.us.auth0.com, with a browser redirect to localhost:8765. On Claude Code, the server's headersHelper (scripts/mcp_headers.py) sends the credential from /memhub:login (the stored access key, else the plugin's cached OAuth token) as the Authorization header. Before it does, it checks the credential against the server with one request per connect. So after /memhub:login the tools work without a separate /mcp login. If there is no credential, or the server refuses it, the helper prints no header, and Authenticate under /mcp applies.
  • Hooks (/memhub:login). This opens the browser once for the same Auth0 login. It then mints a personal access key (mhk_…). The key is scoped to memory:read and memory:write, expires after 90 days, and is labelled claude-code-<hostname>. It is stored at ~/.config/memhub-plugin/pak-<api-host>.json. Hooks are background processes that cannot open a browser, so they rely on this key. When the login succeeds, the local callback page sends your browser on to MemHub's setup guide under https://mem.xtrace.ai/plugin.

Optional harnessDrafting setting. A boolean userConfig option, on by default. Set it to false and the plugin drafts no team rule from your corrections: the Stop hook judges no turn and asks for no drafting fork, whatever MEMHUB_HARNESS_EXTRACT says. See Harness-tied rule drafting.

Optional memhub_token setting. The plugin declares a userConfig option, memhub_token. It is a masked field, it is not required, and it has no default. Claude Code keeps its value in the system credential store. Leave it empty to use the key from /memhub:login. Hooks receive it as CLAUDE_PLUGIN_OPTION_MEMHUB_TOKEN. Set it with /plugin configure memhub@<marketplace>, or claude plugin install memhub@<marketplace> --config memhub_token=mhk_….

Hooks use the first credential they find, in this order:

  1. the memhub_token option;
  2. $MEMHUB_TOKEN;
  3. the stored access key;
  4. the cached OAuth token (~/.config/memhub-plugin/tokens-<api-host>.json), refreshed when stale.

Neither the option nor $MEMHUB_TOKEN reaches the MCP tools, because Claude Code gives the headersHelper neither of them. Skill scripts that run through the Bash tool don't see the option either.

Cloud and CI machines. No browser can sign them in, so give them a personal access key instead. Set MEMHUB_TOKEN=mhk_… as a secret in the environment, and run the installer from its setup script:

curl -fsSL https://raw.githubusercontent.com/XTraceAI/agent-plugins/main/install.sh | sh

With $MEMHUB_TOKEN set, the sign-in step opens no browser. Once the server accepts the key, it is stored as the machine's key, so the MCP tools use it as well as the hooks. The environment's network policy must allow api.memhub.xtrace.ai.

Skills

Each skill runs as /memhub:<name>, or when you ask for it in plain words.

SkillWhat it does, reads and sends
loginSigns the plugin in and stores its access key (see Authentication).
onboardSigns the plugin in when it is not (as login), checks capture health, then creates or reuses the repository's agent brain and records it in rooms.json. Lists the repository's tracked Markdown files (git ls-files) and uploads the ones that look important to that brain without asking. It also saves a short repo overview it writes. With MEMHUB_HARNESS_EXTRACT=1 on Claude Code it adds CLAUDE_CODE_FORK_SUBAGENT=1 under env in ~/.claude/settings.json. On Codex it installs the Codex hooks bridge (see Codex and Cursor) and asks you to approve it in Codex. --status only reports; --remove takes those machine settings out.
save-artifactUploads a file you name, as it is on disk, to the repository's shared brain when there is one, else to your personal memory. Saving under an existing name adds a new version.
import-sessionReads a past Claude Code, Codex or Cursor transcript from this machine and uploads it to your personal memory (never a team brain), in chunks when it is large. For sessions automatic capture missed: from before install, a failed upload, or a host without capture hooks.
search-memoryRead-only. Answers what the team knows or decided by searching the repository's brain and your personal memory with the same query, opening the best match, and saying which one each answer came from.
handoff-sessionWrites a handoff brief (goal, state, decisions, next steps, gotchas) into the standing handoff brain for exactly you and the teammates you name, so they can search it from their own agent; creates and shares that brain when there is none, or a one-off brain with --new. The session itself is not shared.
link-prLinks or unlinks a session and a pull request in MemHub. Asks the agent to run gh pr view. With --find, reads this machine's Claude Code, Codex and Cursor session history to find the sessions behind your pull requests: its script runs gh pr view and gh api for each PR's files, prints paths, branches and commit ids, never transcript content, and the skill links only the sessions you approve.
pr-babysitPolls a pull request's review bots and CI with gh. The agent fixes findings, commits, pushes and replies on review threads. Once the PR is clean, it files a proposed rule with create_rule for any fixed finding whose mistake would recur. The pr_babysit_trigger hook asks the agent to start it after gh pr create.
create-ruleTurns a lesson into a rule that warns the agent or stops the command when its situation comes up. The rule is for just you unless it is plainly right for everyone working in the repo or the organisation. Drafts the check, replays it over this machine's sessions, and files it for review as proposed; you turn on your own rules, and an org admin turns on the team's.
start-rulebookFills starter rules in from a scan of the repository. If you choose, it also mines rules from your CLAUDE.md, the last 30 days of Claude Code, Codex and Cursor sessions on this machine, and Claude Code /insights facets. Working files go to a temp directory or mine-out/ in the current directory. It files rules as proposed and never activates one.
spec, spec-work, spec-check, spec-maintainSpec-driven work against Git specs or brain documents. A --cloud bootstrap runs on the MemHub backend.
companionChecks, shows or hides the companion animal; with it hidden a one-line status strip stands in its place (see Companion).
reposLists, adds or removes the repositories MemHub is active in on this machine, or clears the list so it is active everywhere (see Which repositories MemHub is active in). Outside the listed repositories the plugin does nothing: no rules, no capture, no companion.

What it runs, sends, and fetches

Hooks

Every hook is the same command, python3 "${CLAUDE_PLUGIN_ROOT}/scripts/hook_entry.py" <event> <name>. Hooks are declared in hooks/claude-hooks.json. scripts/hook_entry.py reads the hook input once. It checks any payload filter (on the tool call's command or tool name, never its output), then runs the named script with the same Python: in the same process for the hooks Claude Code waits on, in a separate process for the async ones. Every handler first passes claude_hook_guard. If the hook input comes from Cursor or Codex instead of Claude Code, the guard stops the handler. At a Cursor turn end, it starts the plugin's Cursor capture (cursor_flush.py) instead.

Claude Code always sets CLAUDE_PLUGIN_ROOT for plugin hooks. A host that loads hooks/claude-hooks.json without setting it gets the path /scripts/hook_entry.py. Python then exits 2, and the host treats exit 2 on PreToolUse, UserPromptSubmit and Stop as a block. Set CLAUDE_PLUGIN_ROOT to the plugin folder when you run these hooks in another host.

Which repositories MemHub is active in

You can limit MemHub to the repositories you choose, so a client's repository is never touched. The list is ~/.config/memhub-plugin/repos.json ({"version": 1, "mode": "allowlist", "repos": ["XTraceAI/MemHub-Backend"]}), managed by /memhub:repos (list, add ., add org/name, remove, all) or by install.sh --repos org/a,org/b / --selected-repos / --all-repos (a first install asks). A repository is named as its origin remote spells it, <org>/<name>, matched case-insensitively; a checkout with no remote is named by its directory. Linked worktrees carry their repository's name.

  • No file: MemHub is active in every repository (every install before this option existed, and any upgrade).
  • A file: everywhere it does not list, the plugin is dormant — every session-wide hook in the table below (capture, Markdown capture, the brief, the harness, PR linking, the Rulebook's session and prompt lanes) is skipped by hook_entry.py for a session whose directory is not in a listed checkout, the Rulebook's per-call lanes (rulebook_hook pre / post) judge each tool call by the checkout it acts in and stay silent for an unlisted one, and the Claude Code mod claims no lane and shows no animal there. The only hook that still runs is the rule-fire upload, which ships rows already recorded. A session in an unlisted repository is told so once, at its start, through additionalContext; nothing else prints. A session started in a folder that is not a repository (the parent of several) is not captured, but its tool calls into a listed checkout are still judged. An empty list is dormant everywhere; install.sh writes one on a first install it cannot ask about (/memhub:repos add . in each repository you want, or /memhub:repos all). A file that cannot be read counts as empty.
  • Asked, not guessed (ENG-1253): in Claude Code, a session started in a checkout the list leaves out is asked once, on the status strip above the prompt: MemHub · enable in <org/repo>? with 1 Yes / 2 No / 3 Later. Yes lists it, exactly as /memhub:repos add . does, and MemHub is active there from that moment (the hooks read the file per call); No records it under declined in the same file, so it stays dormant and is never asked about again — /memhub:repos list and status show declined repositories, and add or remove clears a decline; Later hides the ask for that session only. Nothing asks when there is no file, outside a checkout, in a listed or declined repository, or while no one is signed in.

The list applies to the Claude Code hooks and to every host's Rulebook check (rulebook_hook.py, which Codex and Cursor call too). Codex and Cursor's own capture paths do not read it yet.

Event (matcher)NameWhat it doesSends data?
PreToolUse (Bash, Edit, MultiEdit, Write, NotebookEdit, Read)rulebook_hook preChecks the call against your cached team rules. It can add an advisory or deny the call when a gate rule matches. It refreshes the rule cache in a detached background process once the cache is a minute old.Yes, see Rulebook
PreToolUse (mcp__*__create_rule)create_rule_originAdds this session's id and the current turn to MemHub's create_rule call (not to a harness draft, which carries its own), so the rule records the session it was filed from. Never approves or blocks the call.Yes, the session id and turn, inside the create_rule call
PostToolUse (Bash)flush_sessionAfter a command that actually ran git commit, gh pr create or gh pr merge, uploads the transcript so far, then each agent the session spawned (subagents/) as its own conversation linked to it — never the MemHub harness fork or a plugin's own fork, and only to a server that accepts agents. Runs in the background.Yes, the transcript and its agents'
PostToolUse (Edit, MultiEdit, Write, NotebookEdit)artifact_sync_reminderIf the edited file belongs to a spec in the repository (by spec frontmatter), reminds the agent once per session.No
PostToolUse (Bash)pr_babysit_triggerAfter a successful gh pr create, tells the agent to start a /memhub:pr-babysit loop on the new PR.No
PostToolUse (Edit, MultiEdit, Write, Bash)md_captureRecords which Markdown files the session wrote, or for Bash the working directory, in a local state file, and touches a per-session activity marker.No
PostToolUse (Bash, Edit, MultiEdit, Write, NotebookEdit, Read)rulebook_hook postRule advisories on failed results and on files a Bash call wrote, plus tracking for ordering rules.Yes, see Rulebook
PostToolUse (Bash, mcp__*github*__*)pr_link_triggerWhen a GitHub call's output names exactly one pull request, asks MemHub whether to link this session to it. It may then tell the agent to call the link_pr tool.Yes, the PR URL
SessionStartcapture_healthWarns you when capture is unauthenticated or recently failed. Checks plugin compatibility with MemHub and whether a newer release exists.Yes, see Network destinations
SessionStartbrain_brief briefGives the agent a short map of the repository's agent brain from a local cache. Starts a detached process that refreshes its recall pointers.The detached process does
SessionStartrulebook_hook sessionLoads your team rules into the session. Fetches them first if the cache is stale.Yes, the repository name
SessionStartharness_stop sessionUnless MEMHUB_HARNESS_EXTRACT turns it off. Tells the agent the hand-off rule, unseen by you. See Harness-tied rule drafting.No
UserPromptSubmitbrain_brief promptDelivers brain pointers the session-start brief didn't have yet.No
UserPromptSubmitrulebook_hook promptFires rules written for prompts. These only advise.No. Fires are logged locally and uploaded at Stop
Stopflush_turnUploads the transcript bytes written since the last successful upload. Runs in the background.Yes, the transcript
Stopbrain_brief refreshRefreshes the cached brain overview, at most every 6 hours. Runs in the background.Yes, a brain id
Stopmd_capture_flushSaves qualifying Markdown files as draft artifacts. Runs in the background. See Markdown capture.Yes, file contents
Stoprulebook_hook flushUploads the rule-fire and rule-event logs. Once a day it also deletes stale local state. Runs in the background.Yes, identifiers
Stopharness_stop stopUnless MEMHUB_HARNESS_EXTRACT turns it off.Yes, when on
SessionEndsession_endRuns flush_session.py (re-sends the whole transcript as a backstop, then the session's agents as above), then rulebook_hook flush final. Runs in the background.Yes, the transcript and its agents'

Session capture

Sessions upload automatically through the import_conversation MCP tool, from the Stop, SessionEnd and commit/PR hooks above. They go to your personal memory, never into a brain. Each upload also carries the session's title, the repository name (the origin remote's basename) and any GitHub pull-request URLs that gh pr create printed in the session. Slash-command bookkeeping records are left out, and a tool result over 200,000 bytes is replaced by a note giving its size. Before upload, the plugin removes MemHub keys (mhk_…, xtk_…) from the records and the title. Nothing else is redacted. The server de-duplicates what it already has, so re-sending is safe. MEMHUB_TURN_FLUSH=0 turns off per-turn capture. The commit/PR and SessionEnd uploads still run.

Markdown capture

At the end of each turn, md_capture_flush.py reads Markdown files the session wrote and saves them to MemHub as draft artifacts. These files come from Edit, Write or MultiEdit calls, or from git status in a directory where the session ran Bash. A file qualifies when:

  • it is a .md file of 6,000 to 2,000,000 bytes; or
  • it is a .md file whose YAML frontmatter has the line memhub: artifact, which skips the 6,000-byte floor.

Files found through git status must also be modified or untracked, and newer than the session's start.

A prefilter (md_capture_prefilter.py) skips the turn-end pass when nothing is pending: no Edit/Write path is waiting, and the last git status pass found nothing outstanding with no Bash, Edit, MultiEdit or Write call since. A file changed by anything else (your editor, a background job) after such a pass is picked up by the next turn that runs one of those calls, or within five minutes.

A file never qualifies if its path contains /.claude/, /scratchpad/, /tmp/, /private/tmp/, /var/folders/, /node_modules/ or /.git/. The same goes for files named CLAUDE.md, AGENTS.md or MEMORY.md and files in the OS temp directory. The git status search also skips ignored files, submodules, symlinks and paths outside the repository. At most five files are saved per turn, largest first. Content is redacted the same way as transcripts. Each save carries the auto-captured tag. It goes to the repository's agent brain when one is known (~/.config/memhub-plugin/rooms.json). When none is recorded, the plugin asks MemHub for a brain named after the origin remote's <org>/<name> and records the answer; a miss is asked again after a day. It never creates one. Without a brain, the file goes to your personal memory. A file goes up again only when its content changes. There is no setting that turns this off on its own. MEMHUB_TURN_FLUSH=0 does not affect it. To keep a file out, keep it below the size floor or in one of the excluded locations, or disable the plugin.

Rulebook

rulebook_hook.py sends:

  • fetch: the repository name (the origin remote's basename, else the directory name).
  • fires and fire events: rule id, session, repo, branch, tool, a hashed checkout id, timestamps and the judge's verdict. Events record what followed a fire: a command that satisfied it, a turn or session end, or a rule you set aside. A fire on a call you overrode, and an event for a rule you set aside, also carry the reason you gave (redacted, up to 2,000 characters). The matched excerpt stays in the local log.
  • rules tied to files or commands (anchor rules): nothing. They are matched on this machine against the cached rules: a rule fires when one of its anchors appears in the command or the edited file's path as a whole identifier. Set MEMHUB_RULEBOOK_RECALL=0 to turn this matching off.
  • judge: when a rule fires on a call, it asks MemHub whether the rule fits the turn. The request carries your current message (up to 2,000 characters), a stripped copy of the turn (the agent's text, one line per tool call, the first 300 characters of each result), the call, and the fired rule ids. It goes through the same denylist redaction, which can miss things. Set MEMHUB_RULEBOOK_JUDGE=0 to turn this off.

Every rule that fires is shown to you as 📏 Rule fired: …, or ⛔️ when a gate blocked the call. The agent is told to repeat the same line. A blocked Bash call can be overridden with RULEBOOK_OVERRIDE='<why>' <command>, and a blocked edit with a rulebook-override[<rule>]: <why> line in the new content. MEMHUB_RULEBOOK_FETCH=0 stops fetching rules, and the cached ones keep applying.

On Claude Code with mods (2.1.287+), the plugin's mod (mod/) checks these rules in-process and the command hooks step aside for the lanes it serves. MemHub can switch that off remotely: the mod reads mod_lanes from GET /v1/plugin/compatibility when the session starts (before it takes any lane) and every five minutes after. When it reads false, the mod hands every lane back to the command hooks for the rest of the session and the status line says MemHub rules: served by the command hooks (remote switch). A later true does not take them back; the next session (or a reload of the plugin) reads the switch afresh. A failed check changes nothing, and a server that sends no mod_lanes leaves the mod serving.

Brain brief and PR linking

brain_brief.py runs a detached pointers process. It searches the repository's brain and your sessions with identifiers taken from the branch: PR and ticket numbers, plus the basenames of files changed against the default branch, left uncommitted, or changed in the last 20 commits. The search goes through the search_memory tool. MEMHUB_BRIEF_POINTERS=0 turns this off. pr_link_trigger.py sends the pull request URL to /v1/team/pr-links/check. It caches a "not connected" answer for 30 minutes (MEMHUB_PRLINK_NEGATIVE_TTL_S).

Harness-tied rule drafting (on by default)

Unless MEMHUB_HARNESS_EXTRACT is set to something other than 1, on, true or yes (0 turns it off; unset or blank is on), each Stop rebuilds the previous turn from the transcript. It redacts that window (MemHub keys, home directories, e-mail addresses, command-line credentials) and sends it to /v1/team/rulebook/harness/classify. When the classifier signals a candidate rule, the agent is asked once to start

Source 50 files
mod/register.ts 528 lines
1// The plugin's one hooks module (spec §3.1, D1): a composition root that
2// registers each part in a fixed order. Hooks of one module run in
3// registration order, so:
4//
5//   shell (session.start: claims → book → remote switch → session lane) → rulebook lanes
6//   (tool.call pre+post, prompt.submit) → turn.complete (ledger) → companion
7//
8// The companion registers LAST, so its tool.call hook is innermost and sees
9// the rulebook's answer.
10//
11// The mod never builds on `classic.*`, `prompt.section`, `prompt.context`,
12// `prompt.compose`, `skill.prompt` or `attribution.text` (spec §1.4, D3): the
13// built-in guard skips user mods on those for most Team/Enterprise sign-ins.
14
15import type { EngineInterface, On, PluginOptions } from 'claude-code'
16
17import type { FireNote, LaneName } from '../types'
18
19// The companion registers last (innermost) with the mod's ctx and the
20// plugin's userConfig options (its `companion` switch): it reads fires from
21// `$.state` and polls proposals over `$.http.fetch` (`register(on, ctx, options)`).
22import { register as registerCompanion } from '../companion/register'
23import { Act } from './act'
24import { Book, RemoteSwitch } from './book'
25import { Claims, StatusLine } from './claims'
26import { ACTIVE, type Active, type Ctx, type Env, envOf, type Io, lastJson, makeCtx, MOD_CLI, rootOf } from './ctx'
27import type { Engine, EngineEnv, EngineIO, FileStat, HookRule, PathsInfo, TurnMessage } from './engine'
28import { createEngine } from './engine/engine'
29import { Lanes, TOOL_RX } from './lanes'
30import { forwardTestCovers } from './redirect'
31
32/**
33 * The Ctx every part receives at register time. Its fields are the real
34 * ones from session.start on (the plugin's name — and so the environment —
35 * is only known through `$`); before that `env` reads 'staging', `root` ''
36 * and `api()` undefined.
37 */
38function lateCtx(): Ctx & { bind(real: Ctx): void } {
39  let real: Ctx | undefined
40  return {
41    get env(): Env {
42      return real?.env ?? 'staging'
43    },
44    get root() {
45      return real?.root ?? ''
46    },
47    api: () => (real ? real.api() : Promise.resolve(undefined)),
48    forgetApi: () => real?.forgetApi(),
49    // Before the shell is bound nothing can ask the allowlist: active, as always.
50    active: () => (real ? real.active() : Promise.resolve(ACTIVE)),
51    setActive: value => real?.setActive(value),
52    book: () => real?.book(),
53    setBook: info => real?.setBook(info),
54    signIn: () => real?.signIn() ?? 'unknown',
55    bind(r) {
56      real = r
57    },
58  }
59}
60
61// ── the real port, over `$` ─────────────────────────────────────────────────
62//
63// `$.env` and `$.state` take literals only (claude plugin validate reads them
64// off the source), so each name is spelled out. promote_export.py renames the
65// plugin to `memhub` for prod and must rewrite the `'memhub-staging'` state
66// refs below (and types/index.d.ts) with it: a plugin may write only its own
67// state.
68
69const FIRES = { plugin: 'memhub', key: 'fires' } as const
70const LANES = { plugin: 'memhub', key: 'lanes' } as const
71const HEALTH = { plugin: 'memhub', key: 'health' } as const
72
73export function ioOf($: EngineInterface): Io {
74  return {
75    pluginName: $.plugin.name,
76    root: rootOf($.plugin.root),
77    now: () => $.clock.now(),
78    sessionId: () => $.session.id(),
79    cwd: () => $.session.cwd(),
80    run: (argv, init) => $.process.run(argv, init),
81    fetch: (url, init) => $.http.fetch(url, init),
82    readFile: async path => {
83      const text: unknown = await $.fs.read(path)
84      if (typeof text !== 'string') throw new Error(`not text: ${path}`)
85      return text
86    },
87    writeFile: (path, text) => $.fs.write(path, text),
88    getLanesVar: env => (env === 'prod' ? $.env.get('MEMHUB_MOD_LANES_PROD') : $.env.get('MEMHUB_MOD_LANES_STAGING')),
89    setLanesVar: (env, value) =>
90      env === 'prod' ? $.env.set('MEMHUB_MOD_LANES_PROD', value) : $.env.set('MEMHUB_MOD_LANES_STAGING', value),
91    getState: async key => {
92      const read =
93        key === 'fires' ? await $.state.get(FIRES) : key === 'lanes' ? await $.state.get(LANES) : await $.state.get(HEALTH)
94      return read as { value: never; version: number }
95    },
96    setState: async (key, value) => {
97      if (key === 'fires') await $.state.set(FIRES, value as FireNote[])
98      else if (key === 'lanes') await $.state.set(LANES, value as LaneName[])
99      else await $.state.set(HEALTH, value as string)
100    },
101    status: text => $.ui.status(text),
102    log: text => $.ui.log(text),
103    debug: text => $.ui.log(text, { to: 'debug' }),
104    append: async (type, text) => {
105      const r: unknown = await $.session.append({ message: { type, content: [{ type: 'text', text }] } })
106      if (r && typeof r === 'object' && 'deny' in r && (r as { deny?: unknown }).deny) {
107        throw new Error(`session.append refused: ${String((r as { deny: unknown }).deny)}`)
108      }
109    },
110    every: (ms, fn) => $.clock.every(ms, fn),
111    sleep: ms => $.clock.sleep(ms),
112  }
113}
114
115/**
116 * What the engine needs from `$` beyond the shell's Io: built by `extrasOf`
117 * (the one place `$` is read for it); the tests leave it out.
118 */
119export type EngineExtras = {
120  stat(path: string, resolve?: boolean): Promise<FileStat | undefined>
121  /** The main conversation as ApiMessage (`$.session.messages({ as: "api" })`). */
122  messages(): Promise<readonly TurnMessage[] | undefined>
123  /** `$.session.turns()`: user prompts so far, the judge's per-turn id. */
124  turns(): Promise<number>
125  env(): Promise<EngineEnv>
126  home(): Promise<string>
127  sleep(ms: number): Promise<void>
128}
129
130export function extrasOf($: EngineInterface): EngineExtras {
131  return {
132    stat: async (path, resolve) => {
133      try {
134        const st = await $.fs.stat(path, resolve ? { resolve: true } : undefined)
135        return { kind: st.kind, size: st.size, mtimeMs: st.mtimeMs, ...(st.realPath ? { realPath: st.realPath } : {}) }
136      } catch {
137        return undefined
138      }
139    },
140    messages: async () => {
141      try {
142        return (await $.session.messages({ as: 'api' })) as unknown as TurnMessage[]
143      } catch {
144        return undefined
145      }
146    },
147    turns: () => $.session.turns(),
148    env: async () => ({
149      recall: await $.env.get('MEMHUB_RULEBOOK_RECALL'),
150      judge: await $.env.get('MEMHUB_RULEBOOK_JUDGE'),
151      timeoutS: await $.env.get('MEMHUB_RULEBOOK_TIMEOUT_S'),
152      baseBranch: await $.env.get('MEMHUB_RULEBOOK_BASE_BRANCH'),
153      briefBudget: await $.env.get('MEMHUB_BRIEF_TOKEN_BUDGET'),
154    }),
155    home: async () => (await $.env.get('HOME')) ?? '',
156    sleep: ms => $.clock.sleep(ms),
157  }
158}
159
160/** `read_facts`' newline count for a file past the `$.fs` read cap, by the Python's own loop. */
161const COUNT_LINES_PY =
162  'import sys\n' +
163  'total, seen, last = 0, 0, b"\\n"\n' +
164  'with open(sys.argv[1], "rb") as f:\n' +
165  '    while seen < (64 << 20):\n' +
166  '        chunk = f.read(1 << 20)\n' +
167  '        if not chunk: break\n' +
168  '        total += chunk.count(b"\\n"); seen += len(chunk); last = chunk[-1:]\n' +
169  'if seen and last != b"\\n": total += 1\n' +
170  'print(total)\n'
171
172/** The engine's own I/O, over the shell's port (and `$`, through `extras`). */
173function engineIoOf(io: Io, ctx: Ctx, extras: EngineExtras | undefined, home: string): EngineIO {
174  const pathsCache = new Map<string, Promise<PathsInfo | undefined>>()
175  const envCache = new Map<string, Promise<string | undefined>>()
176  return {
177    git: async (argv, cwd, timeoutMs = 10_000) => {
178      const r = await io.run(['git', ...argv], { cwd, timeoutMs })
179      return { code: r.exitCode, stdout: r.stdout }
180    },
181    readText: path => io.readFile(path).catch(() => undefined),
182    writeText: (path, text) => io.writeFile(path, text).catch(() => undefined),
183    stat: (path, resolve) => (extras ? extras.stat(path, resolve) : Promise.resolve(undefined)),
184    countLines: async path => {
185      try {
186        const r = await io.run(['python3', '-c', COUNT_LINES_PY, path], { timeoutMs: 10_000 })
187        const n = Number(r.stdout.trim())
188        return r.exitCode === 0 && Number.isInteger(n) ? n : undefined
189      } catch {
190        return undefined
191      }
192    },
193    now: () => Date.now(),
194    sleep: ms => (extras ? extras.sleep(ms) : new Promise<void>(() => undefined)),
195    tzOffsetMinutes: ms => -new Date(ms).getTimezoneOffset(),
196    home,
197    env: () => (extras ? extras.env() : Promise.resolve({})),
198    // `$.env.get` takes only a literal name, so a variable a Bash command
199    // names (`cd "$WT"`) is read the way the Python hook inherits it: from
200    // this process's environment, once per name per session.
201    getenv: name => {
202      let v = envCache.get(name)
203      if (!v) {
204        v = /^[A-Za-z_][A-Za-z0-9_]*$/.test(name)
205          ? io.run(['printenv', name], { timeoutMs: 2_000 })
206            .then(r => (r.exitCode === 0 ? r.stdout.replace(/\n$/, '') : undefined), () => undefined)
207          : Promise.resolve(undefined)
208        envCache.set(name, v)
209      }
210      return v
211    },
212    paths: dir => {
213      let p = pathsCache.get(dir)
214      if (!p) {
215        p = (async () => {
216          const r = await io.run(['python3', `${ctx.root}/${MOD_CLI}`, 'paths', '--env', ctx.env, '--cwd', dir], { timeoutMs: 10_000 })
217          const got = lastJson(r.stdout) as Record<string, unknown> | undefined
218          if (r.exitCode !== 0 || !got || typeof got.base !== 'string') return undefined
219          return { repo: typeof got.repo === 'string' ? got.repo : '', root: typeof got.root === 'string' ? got.root : null, base: got.base }
220        })().catch(() => undefined)
221        pathsCache.set(dir, p)
222        // A failed answer is not kept: the next call asks again.
223        void p.then(v => {
224          if (!v) pathsCache.delete(dir)
225        })
226      }
227      return p
228    },
229    state: async (ops, cwd) => {
230      try {
231        const r = await io.run(['python3', `${ctx.root}/${MOD_STATE}`], { stdin: JSON.stringify({ cwd, ops }), timeoutMs: 10_000 })
232        const got = lastJson(r.stdout) as { results?: unknown } | undefined
233        return r.exitCode === 0 && got && Array.isArray(got.results) ? (got.results as Record<string, unknown>[]) : undefined
234      } catch {
235        return undefined
236      }
237    },
238    judge: async body => {
239      const api = await ctx.api()
240      if (!api) return undefined
241      try {
242        const r = await io.fetch(`${api.base}/v1/team/rulebook/judge`, {
243          method: 'POST',
244          headers: { Authorization: `Bearer ${api.bearer}`, 'Content-Type': 'application/json', Accept: 'application/json' },
245          body: JSON.stringify(body),
246        })
247        if (r.status === 401) ctx.forgetApi()
248        if (!r.ok) return { status: r.status }
249        if (!r.text.trim()) return { status: r.status, data: null }
250        const p = JSON.parse(r.text) as unknown
251        // mcp_http.rest: a non-zero envelope code is a failure the transport reported as 2xx.
252        if (p && typeof p === 'object' && 'code' in p) {
253          const env = p as { code?: unknown; data?: unknown }
254          if (env.code !== 0) return undefined
255          return { status: r.status, data: 'data' in env ? env.data : p }
256        }
257        return { status: r.status, data: p }
258      } catch {
259        return undefined
260      }
261    },
262    turn: async () => {
263      if (!extras) return undefined
264      const [messages, n] = await Promise.all([extras.messages(), extras.turns().catch(() => -1)])
265      return messages ? { id: n >= 0 ? `mod-turn-${n}` : '', messages } : undefined
266    },
267  }
268}
269
270/** This plugin's manifest version: the `hook_version` the mod reports (spec §4.1). */
271async function versionOf(io: Io): Promise<string | undefined> {
272  try {
273    const v = (JSON.parse(await io.readFile(`${io.root}/.claude-plugin/plugin.json`)) as { version?: unknown }).version
274    return typeof v === 'string' && /^\d{1,6}\.\d{1,6}\.\d{1,6}$/.test(v) ? v : undefined
275  } catch {
276    return undefined
277  }
278}
279
280/**
281 * A matcher every event of its kind matches. One module may hook an event
282 * once without a matcher (a second is refused at load), and the companion
283 * already hooks `session.start` and `turn.complete` bare; a matcher on the
284 * shell's own makes them distinct registrations without narrowing them.
285 */
286/** The shared-state writer (scripts/rulebook_mod_state.py): the Python's own lock. */
287const MOD_STATE = 'scripts/rulebook_mod_state.py'
288
289const EVERY_SESSION = { cwd: /^/ } as const
290const EVERY_TURN = { turnId: /^/ } as const
291
292/** Everything the shell holds for the session, built at session.start. */
293export type Shell = {
294  io: Io
295  ctx: Ctx
296  claims: Claims
297  act: Act
298  lanes: Lanes
299  book: Book | undefined
300  /** The remote `mod_lanes` switch; undefined where there is no engine. */
301  remote?: RemoteSwitch
302  /** Settles once the book is held and the lanes are claimed, or the load gave up. */
303  ready: Promise<void>
304  /** The first prompt of the process has come: startup is past (see `boot`). */
305  firstPrompt(): Promise<void>
306  /**
307   * At every prompt, before the lanes: a session id that changed in-process
308   * (/clear, resume) gets the claim re-stamped (claims.ts `restamp`). Python
309   * served that new session until now, its SessionStart preamble included,
310   * so the session lane counts it as delivered.
311   */
312  sessionChanged(): Promise<void>
313}
314
315/**
316 * The shell's session.start, without `$` (so a test drives it through a fake
317 * Io): claims → book → remote switch → session lane.
318 *
319 * `pastStartup` is false in a fresh process: the startup session's posture
320 * preamble is then Python's (its SessionStart hook runs before anything here
321 * could claim), and `session` is claimed only once the first prompt has come
322 * AND the book is held, whichever is later. A hot reload is long past startup.
323 */
324export async function boot(
325  io: Io,
326  ctx: Ctx,
327  makeEngine: ((io: EngineIO) => Engine) | undefined,
328  opts: {
329    cwd: string
330    pastStartup: boolean
331    toHook?: (row: Record<string, unknown>) => HookRule | null
332    /** What the engine reads off `$` (extrasOf); absent in the shell's tests. */
333    extras?: EngineExtras
334  },
335): Promise<Shell> {
336  const status = new StatusLine(io)
337  const claims = new Claims(io, ctx.env, status)
338  const act = new Act(io, ctx, status)
339  // Whatever the variable lists now is not this module's to serve yet: an
340  // inherited value (a `claude` started from Bash) or the module before a
341  // reload. Python serves until the claim below.
342  await claims.forgetInherited()
343  let pastStartup = opts.pastStartup
344  let isLoaded = false
345  if (!makeEngine) {
346    await claims.failLoad()
347    ctx.setActive(ACTIVE)   // nothing asked the allowlist: the companion shows as always
348    const lanes = new Lanes(io, NO_ENGINE, claims, act)
349    return { io, ctx, claims, act, lanes, book: undefined, ready: Promise.resolve(), firstPrompt: async () => {}, sessionChanged: async () => {} }
350  }
351  const home = opts.extras ? await opts.extras.home().catch(() => '') : ''
352  const engine = makeEngine(engineIoOf(io, ctx, opts.extras, home))
353  const hookVersion = await versionOf(io)
354  // The repository allowlist's answer for the session's cwd, as `paths`
355  // gives it with the book's location: dormant in a repository repos.json
356  // leaves out, and outside any checkout while a repos.json exists — in
357  // both no book is loaded and no lane claimed. The companion reads it
358  // through ctx.active(); it is settled below whatever the load came to, so
359  // nothing waits on it forever.
360  let active: Active = ACTIVE
361  const book = new Book(io, ctx, engine, claims, status, {
362    hookVersion,
363    toHook: opts.toHook,
364    onPaths: a => { active = { enabled: a.enabled, repo: a.repo, restricted: a.restricted, declined: a.declined, identity: a.identity } },
365    // what the companion's status strip says when nothing fired and nothing waits
366    onRules: (repo, rules) => ctx.setBook({ repo, rules }),
367  })
368  // The remote switch (book.ts): a false gives every lane to Python for the
369  // session, and stops the book's refresh, which then serves nothing.
370  const remote = new RemoteSwitch(io, ctx, claims, status, { hookVersion, onOff: () => book.stop() })
371  // A create-rule forward test's claim (mod/redirect.ts): the call goes to
372  // Python, which serves the test's private book. Read per call from the
373  // install's own base; without `extras` (the tests) no claim can be stat'd
374  // and nothing is handed off on that account.
375  const redirectIo = {
376    readText: (p: string) => io.readFile(p).catch(() => undefined),
377    stat: (p: string, resolve?: boolean) => (opts.extras ? opts.extras.stat(p, resolve) : Promise.resolve(undefined)),
378    now: () => io.now(),
379  }
380  const lanes = new Lanes(io, engine, claims, act, (cwd, agentId) => forwardTestCovers(redirectIo, book.realBase, cwd, agentId))
381  // Claim late, in the background: the first prompt never waits on the book,
382  // and until it is held Python serves every lane.
383  const ready = (async () => {
384    try {
385      if (!(await book.load(opts.cwd))) return
386      // Before any claim: switched off, nothing is claimed (and `firstPrompt`
387      // claims nothing either: every lane is released for the session).
388      if (!(await remote.allowsClaim())) return
389      isLoaded = true
390      await claims.claim(pastStartup ? ['pre', 'post', 'prompt', 'session'] : ['pre', 'post', 'prompt'])
391      await lanes.sessionStart(true)
392      book.start()
393      remote.start()
394    } catch (err) {
395      act.unhealthy('load', err)
396      await claims.failLoad().catch(() => undefined)
397    } finally {
398      ctx.setActive(active)
399    }
400  })()
401  return {
402    io,
403    ctx,
404    claims,
405    act,
406    lanes,
407    book,
408    remote,
409    ready,
410    async firstPrompt() {
411      if (pastStartup) return
412      pastStartup = true
413      if (isLoaded) await claims.claim(['session'])
414    },
415    async sessionChanged() {
416      if (await claims.restamp()) await lanes.sessionStart(true)
417    },
418  }
419}
420
421/** Stands in where there is no engine: every lane is released, so nothing calls it. */
422const NO_ENGINE: Engine = {
423  setBook() {},
424  pre: () => Promise.reject(new Error('no engine')),
425  post: () => Promise.reject(new Error('no engine')),
426  prompt: () => Promise.reject(new Error('no engine')),
427  session: () => Promise.reject(new Error('no engine')),
428}
429
430/** The hooks module's entry (`Register`): `options` are the manifest's userConfig values, defaults filled in. */
431export function register(on: On, options: PluginOptions = {}) {
432  const ctx = lateCtx()
433  let shell: Shell | undefined
434
435  // ── shell: claims → book → remote switch → session lane ───────────────────
436  on('session.start', EVERY_SESSION, async ($: EngineInterface, e, next) => {
437    // The shell failing to start must never cost the companion its start:
438    // caught here, and the shell stays off (no claim, so Python serves).
439    shell = undefined
440    try {
441      const io = ioOf($)
442      const env = envOf(io.pluginName)
443      if (env) {
444        const real = makeCtx(io, env)
445        ctx.bind(real)
446        // A fresh process has no `lanes` in $.state; a hot reload keeps it.
447        const pastStartup = (await io.getState('lanes')).version > 0
448        shell = await boot(io, real, createEngine, { cwd: e.cwd, pastStartup, extras: extrasOf($) })
449        // The companion's status strip reads the book and the allowlist off
450        // ctx once the load has settled: draw the band again then.
451        void shell.ready.then(() => {
452          try {
453            $.ui.invalidate('ui.render')
454          } catch {
455            // a band nothing draws
456          }
457        })
458      }
459    } catch {
460      shell = undefined
461    }
462    return next(e)
463  }).catch(($, e, next) => next(e))
464
465  // ── rulebook lanes ────────────────────────────────────────────────────────
466  on('tool.call', { tool: TOOL_RX }, async ($, e, next) => {
467    if (!shell) return next(e)
468    return shell.lanes.toolCall(e, next as never) as never
469  }).catch(async ($, e, next) => {
470    // Overran or threw outside the lanes' own handling: hand the call to Python.
471    // `next` here is replay-safe (claude-code.d.ts `Caught`): when the hook had
472    // called it (`next.called`), `next(e)` resolves to what that call settled
473    // to and nothing beneath runs again, so the tool never runs twice; the
474    // d.ts's own pattern for a tool.call guard is
475    // `next.called ? next(e) : { deny }`. Not called: the call has not run,
476    // and Python's hook beneath serves it once `pre` is out of the claim.
477    if (!next.called && shell?.claims.has('pre')) {
478      await shell.claims.fail('pre').catch(() => undefined)
479      try {
480        return await next(e)
481      } finally {
482        await shell.claims.recover('pre').catch(() => undefined)
483      }
484    }
485    return next(e)
486  })
487
488  on('prompt.submit', async ($, e, next) => {
489    if (!shell) return next(e)
490    // Re-stamp the claim first: until it carries this session's id, Python serves.
491    await shell.sessionChanged().catch(() => undefined)
492    await shell.firstPrompt()
493    return shell.lanes.promptSubmit(e, next as never) as never
494  }).catch(async ($, e, next) => {
495    // Replay-safe `next`, as for tool.call above.
496    if (!next.called && shell?.claims.has('prompt')) {
497      await shell.claims.fail('prompt').catch(() => undefined)
498      try {
499        return await next(e)
500      } finally {
501        await shell.claims.recover('prompt').catch(() => undefined)
502      }
503    }
504    return next(e)
505  })
506
507  // A compaction summarises the preamble away; the next prompt brings it back,
508  // and the next fire the no-echo note (act.ts NO_ECHO_NOTE).
509  on('session.compact', async ($, e, next) => {
510    const r = await next(e)
511    if (shell && e.trigger !== 'precompute' && e.agentId === undefined && !('skip' in r)) {
512      const sessionId = await shell.io.sessionId()
513      shell.lanes.compacted(sessionId)
514      shell.act.compacted(sessionId)
515    }
516    return r
517  }).catch(($, e, next) => next(e))
518
519  // The turn's batched ledger events (spec §4.7).
520  on('turn.complete', EVERY_TURN, async ($, e, next) => {
521    if (shell) await shell.act.flush(await shell.io.sessionId())
522    return next(e)
523  }).catch(($, e, next) => next(e))
524
525  // ── companion: last, so innermost ─────────────────────────────────────────
526  registerCompanion(on, ctx, options)
527}
528
companion/register.ts 1583 lines
1// One entry point: mod/register.ts, the plugin's hooks module (hooks.json),
2// calls `register(on, ctx, options)` with the mod's Ctx (mod/ctx.ts) and the
3// plugin's userConfig values, last of its parts, so the companion's hooks sit
4// innermost. MemHub calls use `ctx.api()`: the REST base, the bearer, and the
5// Studio web app paired with the base; `ctx.env` says which MemHub it is.
6//
7// Whether the ANIMAL shows: the `companion` option (plugin.json userConfig,
8// off by default) shows it in every session unless `/<animal> off` hid it;
9// with the option off it shows only where the person ran `/<animal>` (which
10// stores `companion.enabled`). And never in a repository MemHub is inactive
11// in — `ctx.active()`, the machine's repository allowlist (repos.json) as the
12// shell read it at boot — where the Python lanes are silent too. With the
13// animal off the band is not empty: one plain status line (the "strip",
14// ui.render below) stands in its place, so MemHub's presence stays visible
15// and a proposed rule can still be answered on its buttons. In a repository
16// the list leaves out — not listed, not declined — the strip asks once, at
17// session start, whether to enable MemHub there (ENG-1253): `1 Yes` lists
18// it, `2 No` declines it for good, `3 Later` hides the ask for the session.
19//
20// It reads what the mod writes to `$.state` (fires, proposals,
21// lanes) and never needs the classic.* events, which the built-in
22// `sec-default` guard skips for user mods on Team/Enterprise sign-ins (Claude
23// Mods Migration Spec §1.4, D3). The classic PreToolUse / PostToolUse hooks
24// stay only as the fallback for lanes the mod has not claimed.
25
26import type { EngineInterface, On, PluginOptions, Timer } from 'claude-code'
27import { read, update } from 'claude-code'
28
29import { type Active, type Api, type Ctx, lastJson, MOD_CLI, type SignIn } from '../mod/ctx'
30import type { FireNote, ProposalNote } from '../types'
31import type { Animal, Build, Painted, Tone } from './animal'
32import { ANIMALS, DEFAULT_ANIMAL } from './animals'
33import {
34  decisionOf, envName, firesOf, freshFires, headersOf, isApi, isClassicLane, lanesOf, listedRules,
35  mergedProposals, PROPOSED_PATH, proposalsKey, proposalsOf, proposedOfNote, rulePath, STATUS_OF, studioUrl, UUID,
36  versionOfManifest,
37} from './feed'
38import {
39  announcedIn, announcedOf, type Decision, decisionSaid, nameOf, type Proposed, proposalSaid, RULE_WORD,
40  withAnnounced,
41} from './proposed'
42import { type Fired, firedOf } from './rules'
43import { BUB_BG_HEX, CELL_H, CELL_W, compose, DESKTOP_TEXT_LINES, encode, fitBubble, footerOf, type Layout, layoutOf, petAt, SCALES, svgOf, wordAt } from './screen'
44import { pick, poolOf, prefsOf, type Prefs, remember, sessionsOf } from './selection'
45
46/** What the mod's act side writes on each fire (types/index.d.ts). */
47const FIRES = { plugin: 'memhub', key: 'fires' } as const
48/** Rules waiting on an answer: the poll below writes them. */
49const PROPOSALS = { plugin: 'memhub', key: 'proposals' } as const
50/** The Rulebook lanes the mod serves now; the classic hooks announce the rest. */
51const LANES = { plugin: 'memhub', key: 'lanes' } as const
52/** How often the server is asked for proposed rules, besides session start and each turn's end. */
53const POLL_MS = 300_000
54/** What the animal says, once a session, when the poll finds no one signed in. */
55const SIGNED_OUT_SAID = "Not signed in to MemHub: sessions aren't saved and team rules can't sync. Run /memhub:login"
56/** What it says when a later poll finds the sign-in it had asked for. */
57const SIGNED_IN_SAID = 'Signed in to MemHub: sessions are saved and team rules sync again.'
58/** The row under the animal while no one is signed in. */
59const SIGNED_OUT_ROW = 'not signed in · /memhub:login'
60/** The strip's enable ask (ENG-1253): the keyed Box a test (and a surface) finds. */
61const ENABLE_KEY = 'memhub-enable-ask'
62
63/**
64 * The companion in the band above the prompt: MemHub's face in the session,
65 * there to show what the plugin is doing for it. It sleeps while nothing
66 * happens, looks around while Claude answers or you type, and rises to speak
67 * when a MemHub rule fires, announcing the rule — calmly for an advisory,
68 * crossly for a call the rule stopped — and when the harness has proposed a
69 * new rule, presenting it and asking: Activate, Reject or Later, as buttons
70 * inside its bubble (1, 2, 3 from an empty prompt) until it is answered.
71 * When no one is signed in to MemHub it says so, once a session, and keeps a
72 * `not signed in · /memhub:login` row under it until a sign-in is found.
73 *
74 * This is the whole of what watches the session. Which animal does the
75 * sleeping and speaking is the Animal contract's business (see animal.ts):
76 * the director asks for a pose and draws what comes back, and knows nothing
77 * else about it. Every pose plays whole; it cuts in only where the animal is
78 * merely waiting (asleep, looking).
79 *
80 * Which animal shows is the session's own (see selection.ts): picked from the
81 * session id unless someone pinned one, and changed for this session alone by
82 * `/hippo`, `/goose`, ... — each of which also takes `always` (pin it for
83 * every new session), `random` (drop the pin), `never` / `include` (leave it
84 * out of, or put it back in, the random pick), `off`, `on`, `auto`, and —
85 * where the animal offers a demo — `demo` and its own pose names.
86 *
87 * A click on the ♥ beside its ground pets it. The animal itself cannot take
88 * the click: a Raster takes none, and a surface module laid over it to take
89 * them froze the pixels under it, while one laid beneath it never got them. A
90 * proposal's `rule↗` opens the rule in MemHub Studio.
91 *
92 * The terminal draws the band as a Raster, repainted in place by `$.ui.blit`.
93 * The desktop lists a Raster but draws nothing for one and refuses its blits,
94 * so there the same cells are drawn as an SVG and each changed frame redraws
95 * the band; its buttons sit in a row of their own, since a Box is placed in
96 * cells and the SVG is sized in CSS pixels, which need not agree.
97 */
98
99const FPS = 20
100/** The desktop redraws the band for a frame, not a blit: every frame that changed. */
101const DESKTOP_STRIDE = 1
102const RASTER_KEY = 'companion'
103const STORE_ENABLED = 'companion.enabled'
104/** The userConfig option that shows the companion without a `/<animal>` (off by default). */
105const OPTION_COMPANION = 'companion'
106/** How long setUp waits for the shell's allowlist answer before showing the animal anyway. */
107const ACTIVE_WAIT_MS = 5_000
108const REPOS_FILE = '~/.config/memhub-plugin/repos.json'
109/** How many turn ends a fire stands on the status strip: the turn it fired in, and the next. */
110const STRIP_FIRE_TURNS = 2
111const STRIP_KEY = 'memhub-strip'
112/** The strip's colour for a fire that blocked the call (the Python disclosure's ⛔️ line). */
113const BLOCKED_HEX = '#e06c75'
114// `companion.animal`, the old global pick, is neither read nor written: most
115// of it was `/goose` run to turn the band on, not a choice. Older versions
116// still read it, so it is left where it is.
117const STORE_PIN = 'companion.pin'
118const STORE_NEVER = 'companion.never'
119const STORE_SESSIONS = 'companion.sessions'
120const STORE_SCALE = 'companion.scale'
121/** Per session, the proposed rules already announced: a reload must not announce them again. */
122const STORE_ANNOUNCED = 'companion.announced'
123/** How long a keystroke keeps the animal looking, and a finished turn too. */
124const LINGER_FRAMES = 3 * FPS
125/** Announcements waiting their turn; past this the oldest waiting one drops. */
126const MAX_QUEUED = 3
127/** The key of the ♥ at the animal's feet that pets it. */
128const PET_KEY = 'companion-pet'
129/** How long a click waits for the animal to be free to be petted; then it drops. */
130const PET_PENDING_FRAMES = 5 * FPS
131/** The director's own pet, for an animal without one: hearts over `look`. */
132const FALLBACK_PET_FRAMES = 30
133const HEART_RGB: [number, number, number] = [240, 124, 150]
134/** How long after a /clear or /resume the frame clock keeps asking for the new session id. */
135const REPICK_FRAMES = 10 * FPS
136
137/** A pose the director asks the animal for, plus its own idle `offscreen`. */
138type PoseName = 'offscreen' | 'enter' | 'sleep' | 'wake' | 'look' | 'rise' | 'speak' | 'leave' | 'demo' | 'pet'
139
140type Segment = { name: PoseName; frames: Iterator<unknown> }
141
142/** One thing the animal has to say, in the bubble's tone. */
143type Said = { text: string; tone: Tone }
144
145/** What the session wants of the animal right now. */
146type Want = 'sleep' | 'look' | 'speak'
147
148/** Everything the companion keeps between frames and events. */
149type Band = {
150  animal: Animal
151  /** The animal's art for the size being drawn; its poses are the ones running. */
152  build: Build
153  fires: number
154  queue: Said[]
155  /** Proposed rules waiting on the person's answer; the first has the buttons. */
156  asks: Proposed[]
157  /**
158   * Rule ids already announced: the server lists a proposal until it is
159   * decided. Kept in the store too (STORE_ANNOUNCED), per session, since a
160   * reload of this module starts this set empty.
161   */
162  announced: Set<string>
163  /** An answer is on its way to MemHub; the buttons wait for it. */
164  isDeciding: boolean
165  /** The demo is showing a proposal, so it shows the buttons too. */
166  hasDemoAsk: boolean
167  /** What a press in the demo would have done, said in place of doing it. */
168  demoNote: string | null
169  /** The frame the demo's note gives the buttons back. */
170  demoNoteUntil: number
171  /** Where the buttons sat when last drawn (see buttonsAt), so a move redraws. */
172  buttonsKey: string
173  /** Where the proposal's linked `rule` sat when last drawn (see wordOf), likewise. */
174  wordKey: string
175  /** The tone of what the animal is saying now, while a `speak` plays. */
176  speakingTone: Tone | null
177  /**
178   * The ANIMAL is drawn: decided by setUp from the option, the store and the
179   * allowlist; false until then. False draws the status strip instead (one
180   * dim line: the latest fire, a waiting proposal with its buttons, else what
181   * MemHub is doing), never nothing — so the mod's presence stays visible.
182   */
183  isEnabled: boolean
184  /** The plugin's `companion` option: the animal without a `/<animal>` first. */
185  optionOn: boolean
186  /** The repository allowlist's answer for this session (ctx.active()); null until setUp asked. */
187  active: Active | null
188  /** The fire the strip shows (no bubble to say it in), for `stripFireTurns` more turn ends. */
189  stripFire: Said | null
190  stripFireTurns: number
191  /** A forced pixel size, or null to let the room pick as hippo_half.py does. */
192  scale: number | null
193  /** Rows the band really gave the drawing, once it has said; see ui.render. */
194  roomRows: number | null
195  /** The width and allowance the room was measured at; a change measures again. */
196  roomAt: number | null
197  roomMax: number | null
198  /** `auto` follows the session; anything else is the animal's own demo. */
199  mode: string
200  isWorking: boolean
201  /** The frame until which a keystroke or a finished turn keeps it looking. */
202  activeUntil: number
203  seg: Segment
204  frame: number
205  current: Painted
206  timer: Timer | null
207  requestId: string | null
208  /** Where the band was last drawn: the terminal blits a frame, the desktop redraws it. */
209  surface: 'terminal' | 'desktop'
210  layout: Layout | null
211  lastCells: string
212  /** The session the animal was picked for. */
213  sessionId: string
214  /**
215   * A /clear or /resume moved the process to another session: pick again once
216   * its id is readable — tried on every prompt edit and turn until then, and
217   * by the frame clock until `repickUntil`.
218   */
219  needsRepick: boolean
220  repickUntil: number
221  isPicking: boolean
222  /** Bumped by every command that picks an animal, so a pick already in flight yields to it. */
223  pickGen: number
224  /** An animal picked by a command before the engine reported the new session's id: it is that session's. */
225  pendingPick: string | null
226  /** A click waits, until this frame, for the animal to be free to be petted. */
227  petUntil: number
228  /** The frame the director's own pet began, for its hearts. */
229  petAt: number
230  /** Got it: the speech's bubble is hidden and its holds skipped. */
231  isHushed: boolean
232  /** The last frame a hushed speech showed, so a hold's repeats are skipped. */
233  hushedFrame: string
234  /** A page is being opened in the browser; another press waits for it. */
235  isOpening: boolean
236  /** setUp has run (or is running) for this load of the module. */
237  isSetUp: boolean
238  /** The mod's Ctx, from mod/register.ts: the credential and the env. */
239  ctx: Ctx
240  /**
241   * The `$.state` fires already seen, by feed.fireKey; null until the first
242   * read of this load, which takes what is there as said (a reload must not
243   * say a session's fires again).
244   */
245  seenFires: Set<string> | null
246  /** The proposals last handed to the band (feed.proposalsKey); null before any. */
247  proposalsKey: string | null
248  /** Proposal updates, one after another, so two never announce the same rule. */
249  syncing: Promise<void>
250  pollTimer: Timer | null
251  isPolling: boolean
252  /** The MemHub the poll reached ('staging' | 'production'); '' until it has. */
253  env: string
254  /** The sign-in the last poll found: 'out' keeps a row under the animal; 'unknown' changes nothing. */
255  signIn: SignIn
256  /** The session the animal last said it is not signed in, so it says so once a session. */
257  saidSignedOutIn: string | null
258  /** The session's working directory (session.start): what the enable ask's Yes and No name to the CLI. */
259  cwd: string
260  /**
261   * The strip's enable ask (ENG-1253): 'open' shows it where `enableAskOf`
262   * says to; 'answering' while Yes or No is being written (its buttons
263   * wait); 'later' hides it for the rest of this session, in memory only.
264   */
265  enableAsk: 'open' | 'answering' | 'later'
266}
267
268export function register(on: On, ctx: Ctx, options: PluginOptions = {}) {
269  const band: Band = {
270    animal: DEFAULT_ANIMAL,
271    build: DEFAULT_ANIMAL.builds[0]!,
272    fires: 0,
273    queue: [],
274    asks: [],
275    announced: new Set(),
276    isDeciding: false,
277    hasDemoAsk: false,
278    demoNote: null,
279    demoNoteUntil: 0,
280    buttonsKey: '',
281    wordKey: '',
282    speakingTone: null,
283    isEnabled: false,
284    optionOn: options[OPTION_COMPANION] === true,
285    active: null,
286    stripFire: null,
287    stripFireTurns: 0,
288    scale: null,
289    roomRows: null,
290    roomAt: null,
291    roomMax: null,
292    mode: 'auto',
293    isWorking: false,
294    activeUntil: 0,
295    seg: { name: 'offscreen', frames: [][Symbol.iterator]() },
296    frame: 0,
297    current: { canvas: [] },
298    timer: null,
299    requestId: null,
300    surface: 'terminal',
301    layout: null,
302    lastCells: '',
303    sessionId: '',
304    needsRepick: false,
305    repickUntil: 0,
306    isPicking: false,
307    pickGen: 0,
308    pendingPick: null,
309    petUntil: 0,
310    petAt: 0,
311    isHushed: false,
312    hushedFrame: '',
313    isOpening: false,
314    isSetUp: false,
315    ctx,
316    seenFires: null,
317    proposalsKey: null,
318    syncing: Promise.resolve(),
319    pollTimer: null,
320    isPolling: false,
321    env: '',
322    signIn: 'unknown',
323    saidSignedOutIn: null,
324    cwd: '',
325    enableAsk: 'open',
326  }
327
328  on('session.start', async ($, e, next) => {
329    const result = await next(e)
330    if (typeof e.cwd === 'string') band.cwd = e.cwd
331    // `claude -p` is a terminal that is not interactive, with no band to draw
332    // in. The desktop reports no surface here and `isInteractive: false` (a
333    // live 2.1.287 session), so it sets up from its first draw instead.
334    if (e.surface === 'terminal' && e.isInteractive) {
335      await setUp($, band)
336    }
337    return result
338  })
339
340  for (const animal of ANIMALS) {
341    on('command.run', { command: commandOf(animal) }, async ($, e) => {
342      const arg = e.args.trim().toLowerCase()
343      if (arg === 'off') {
344        band.isEnabled = false
345        stop(band)
346        // the frame clock stops with the band: a click from before must not
347        // pet the animal once it is back
348        band.petUntil = 0
349        await $.store.set(STORE_ENABLED, false).catch(() => undefined)
350        $.ui.invalidate('ui.render')
351        return {
352          text: `The ${animal.name.toLowerCase()} goes away; a plain MemHub status line stays above the prompt. ` +
353            `/${commandOf(animal)} brings it back.`,
354        }
355      }
356      const scaleAsked = /^scale +([1-4])$/.exec(arg)
357      if (scaleAsked || arg === 'scale auto') {
358        band.scale = scaleAsked ? Number(scaleAsked[1]) : null
359        await $.store.set(STORE_SCALE, band.scale).catch(() => undefined)
360        $.ui.invalidate('ui.render')
361        const fits = band.layout ? ` (showing ${band.layout.s})` : ''
362        return { text: `${commandOf(animal)}: pixel size ${band.scale ?? 'auto'}${fits}` }
363      }
364      const key = commandOf(animal)
365      if (arg === 'random') {
366        await $.store.delete(STORE_PIN).catch(() => undefined)
367        return { text: `${key}: new sessions pick their own animal from the session id` }
368      }
369      if (arg === 'never' || arg === 'include') {
370        const prefs = await prefsFor($)
371        const never = prefs.never.filter(n => n !== key)
372        if (arg === 'never') {
373          if (ANIMALS.every(a => a === animal || never.includes(commandOf(a)))) {
374            return { text: `${key}: it is the last animal in the random pick; include another first` }
375          }
376          never.push(key)
377          if (prefs.pin === key) await $.store.delete(STORE_PIN).catch(() => undefined)
378        }
379        await $.store.set(STORE_NEVER, never).catch(() => undefined)
380        return { text: arg === 'never' ? `${key}: left out of the random pick` : `${key}: back in the random pick` }
381      }
382      const isAlways = arg === 'always'
383      const isDemo = arg !== '' && arg !== 'on' && arg !== 'auto' && !isAlways
384      const demoBuild = buildFor(animal, band.scale)
385      if (isDemo && !(demoBuild.demo && (arg === 'demo' || (demoBuild.demoPoses ?? []).includes(arg)))) {
386        return { text: `usage: /${commandOf(animal)} ${usageOf(animal)}` }
387      }
388      // A repository MemHub is inactive in (the allowlist) has no companion
389      // to show, whatever the person asks of it: say so, and store nothing.
390      const active = await activeOf($, band)
391      if (!active.enabled) {
392        return {
393          text: active.repo
394            ? `MemHub is inactive in this repository (${REPOS_FILE} leaves it out), so the ` +
395              `${animal.name.toLowerCase()} stays away. /${$.plugin.name}:repos add . enables MemHub here.`
396            : `MemHub is inactive here: this folder is not inside a repository, and ${REPOS_FILE} limits ` +
397              `MemHub to the repositories it lists, so the ${animal.name.toLowerCase()} stays away. ` +
398              `Run /${$.plugin.name}:repos add . inside a repository to enable MemHub there.`,
399        }
400      }
401      // this command decides the session's animal: a pick still in flight for
402      // it yields, and one the engine's new session id (after a /clear or a
403      // /resume) was waiting for is this one
404      band.pickGen += 1
405      const id = await sessionIdOf($)
406      let isPending = false
407      if (id && id !== band.sessionId) {
408        band.sessionId = id
409        band.needsRepick = false
410        band.repickUntil = 0
411      } else if (band.needsRepick) {
412        // typed in the new session before the engine said its id: kept for it,
413        // and not written under the old session's id
414        band.pendingPick = key
415        isPending = true
416      }
417      const wasOff = !band.isEnabled
418      const isSwitch = band.animal !== animal || wasOff
419      band.isEnabled = true
420      band.animal = animal
421      await $.store.set(STORE_ENABLED, true).catch(() => undefined)
422      if (band.sessionId && !isPending) {
423        const sessions = sessionsOf(await $.store.get(STORE_SESSIONS).catch(() => undefined))
424        await $.store.set(STORE_SESSIONS, remember(sessions, band.sessionId, key)).catch(() => undefined)
425      }
426      if (isAlways) {
427        const prefs = await prefsFor($)
428        await $.store.set(STORE_PIN, key).catch(() => undefined)
429        await $.store.set(STORE_NEVER, prefs.never.filter(n => n !== key)).catch(() => undefined)
430      }
431      if (isDemo) {
432        // another animal's demo plays in that animal's own art, from the start
433        band.build = buildFor(animal, band.scale)
434        play(band, arg)
435      } else if (isSwitch) {
436        switchTo(band, animal)
437      } else if (band.mode !== 'auto') {
438        play(band, 'auto')
439      }
440      start($, band)
441      // polls stopped while it was off: look again now, sign-in included
442      if (wasOff && band.isSetUp) void pollProposals($, band)
443      $.ui.invalidate('ui.render')
444      if (isAlways) {
445        return { text: `${key}: every new session starts with ${titleOf(animal).toLowerCase()} (\`/${key} random\` undoes it)` }
446      }
447      return {
448        text:
449          band.mode === 'auto'
450            ? `${animal.name.toLowerCase()}: following the session`
451            : `${animal.name.toLowerCase()}: looping ${band.mode}`,
452      }
453    })
454  }
455
456  on('prompt.edit', ($, e, next) => {
457    band.activeUntil = band.frame + LINGER_FRAMES
458    nudge(band)
459    if (band.needsRepick) void repick($, band)
460    return next(e)
461  })
462
463  on('turn.start', async ($, e, next) => {
464    const result = await next(e)
465    band.isWorking = true
466    nudge(band)
467    if (band.needsRepick) void repick($, band)
468    return result
469  })
470
471  // A /clear or a /resume goes on under another session id with no
472  // session.start: that session shows its own animal, picked once the engine
473  // answers with its id.
474  on('session.end', async ($, e, next) => {
475    const result = await next(e)
476    if (e.reason === 'clear' || e.reason === 'resume') {
477      band.needsRepick = true
478      band.repickUntil = band.frame + REPICK_FRAMES
479      void repick($, band)
480    }
481    return result
482  })
483
484  // A rule the harness's background fork filed lands on the server minutes
485  // after the turn that launched it. Besides the clock (setUp), each main
486  // turn's end asks the server, without holding the turn — as each classic
487  // Stop used to, which the guard skips for most customers (D3).
488  on('turn.complete', async ($, e, next) => {
489    const result = await next(e)
490    if (e.agentId === undefined) {
491      band.isWorking = false
492      band.activeUntil = band.frame + LINGER_FRAMES
493      if (band.isSetUp) void pollProposals($, band)
494      // the strip's fire line stands through the turn it fired in and the next
495      if (band.stripFire && --band.stripFireTurns <= 0) {
496        band.stripFire = null
497        $.ui.invalidate('ui.render')
498      }
499    }
500    return result
501  })
502
503  // The fallback for fires: the rulebook's command hooks sit beneath every
504  // hooks module in the classic chain, so `next(e)` is what they answered for
505  // this call. Read only while the mod has not claimed that lane: a claimed
506  // lane's fires come through `$.state` fires (see ui.render), and the Python
507  // hook it suppresses prints nothing here anyway. Where the built-in guard
508  // skips classic.* for user mods, these never run at all.
509  on('classic.PreToolUse', async ($, e, next) => {
510    const result = await next(e)
511    if (isClassicLane(await lanesNow($), 'pre')) {
512      announce(band, firedOf(result.additionalContext ?? [], result.deny ?? result.ask).map(saidOfFire))
513      if (!band.isEnabled) $.ui.invalidate('ui.render')   // the strip has no frame clock to redraw it
514    }
515    return result
516  })
517
518  on('classic.PostToolUse', async ($, e, next) => {
519    const result = await next(e)
520    if (isClassicLane(await lanesNow($), 'post')) {
521      announce(band, firedOf(result.additionalContext ?? [], result.block).map(saidOfFire))
522      if (!band.isEnabled) $.ui.invalidate('ui.render')
523    }
524    return result
525  })
526
527  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
528    // Read while drawing, so a write to either redraws the band and lands here.
529    await feedFromState($, band)
530    // The desktop sets up from its first draw (session.start named no
531    // surface there), and that draw happens while the band is still hidden:
532    // setUp is what decides whether it shows, so it runs before that test.
533    if (e.surface === 'desktop') void setUp($, band)
534    if (e.props.hasSurvey || (e.surface !== 'terminal' && e.surface !== 'desktop')) {
535      band.requestId = null
536      return next(e)
537    }
538    const { Box, Text, Button } = $.ui.resolve(e)
539    band.requestId = e.requestId
540    band.surface = e.surface
541    // opens a rule's page in MemHub Studio. A pressable word rather than a
542    // link: a terminal without hyperlinks draws a Link or a Markdown link as
543    // its text and then its URL, which ran down the bubble past its bottom.
544    const opens = (url: string) => () => void openUrl($, band, url)
545    // under the animal (or on the strip), the rule's name opens it (#67's link), as `rule` does
546    const name = (ask: Proposed, width: number) =>
547      ask.url
548        ? Button({ key: 'rule-name', plain: true, label: nameOf(ask, width), hover: { underline: true }, onPress: opens(ask.url) })
549        : Text({ children: nameOf(ask, width) })
550    const controlsFor = (ask: Proposed) => {
551      const isDemo = ask === DEMO_ASK
552      const answer = (action: 'activate' | 'reject') =>
553        isDemo ? () => demoPress($, band, action) : () => void decide($, band, ask, action)
554      // plain, so each reads `1: Activate`: the digit is the key to press
555      return band.isDeciding
556        ? [Text({ color: '#968ca5', children: 'asking MemHub…' })]
557        : isDemo && band.demoNote
558          ? [Text({ color: '#968ca5', wrap: 'truncate-end', children: band.demoNote })]
559          : [
560              Button({ key: 'rule-activate', hotkey: '1', plain: true, label: 'Activate', onPress: answer('activate') }),
561              Button({ key: 'rule-reject', hotkey: '2', plain: true, label: 'Reject', onPress: answer('reject') }),
562              Button({
563                key: 'rule-later', hotkey: '3', plain: true, dimColor: true, label: 'Later',
564                onPress: isDemo ? () => demoPress($, band, 'later') : () => later($, band),
565              }),
566            ]
567    }
568    const waiting = (ask: Proposed) =>
569      Box({ key: 'rule-waiting', gap: 2, children: [Text({ dimColor: true, children: 'new rule waiting:' }), name(ask, 40), ...controlsFor(ask)] })
570    // The enable ask (ENG-1253): the same three-button row as a proposal's,
571    // with its own three answers. The digits are the keys to press.
572    const asking = (identity: string) =>
573      Box({
574        key: ENABLE_KEY, gap: 2, children: [
575          Text({ wrap: 'truncate-end', children: `MemHub · enable in ${identity}?` }),
576          ...(band.enableAsk === 'answering'
577            ? [Text({ color: '#968ca5', children: 'writing…' })]
578            : [
579                Button({ key: 'enable-yes', hotkey: '1', plain: true, label: 'Yes', onPress: () => void answerEnable($, band, 'yes') }),
580                Button({ key: 'enable-no', hotkey: '2', plain: true, label: 'No', onPress: () => void answerEnable($, band, 'no') }),
581                Button({ key: 'enable-later', hotkey: '3', plain: true, dimColor: true, label: 'Later', onPress: () => enableLater($, band) }),
582              ]),
583        ],
584      })
585
586    // The status strip: the animal is off (the `companion` option, `/<animal>
587    // off`, or a repository MemHub is inactive in), and one plain line stands
588    // in its place so the mod's presence stays visible. Its text, in this
589    // order: the latest fire, as the animal would say it; a waiting proposal
590    // with its 1 Activate / 2 Reject / 3 Later buttons and the rule's name as
591    // the link to Studio — the proposal flow needs no animal; the enable ask,
592    // where this repository is unlisted and undeclined (enableAskOf); else,
593    // dim, what MemHub is doing here. Nothing on it moves: no frame clock runs.
594    if (!band.isEnabled) {
595      const fire = band.stripFire
596      const ask = band.asks[0]
597      const enable = enableAskOf(band)
598      // a Text takes no key, so the keyed Box is what a test (and a surface) finds
599      const line = fire
600        ? Box({
601            key: STRIP_KEY,
602            children: Text({
603              wrap: 'truncate-end', ...(fire.tone === 'blocked' ? { color: BLOCKED_HEX } : {}),
604              children: `${fire.tone === 'blocked' ? '⛔️' : '📏'} ${fire.text}`,
605            }),
606          })
607        : ask
608          ? waiting(ask)
609          : enable
610            ? asking(enable)
611            : Box({ key: STRIP_KEY, children: Text({ dimColor: true, wrap: 'truncate-end', children: quietOf($, band) }) })
612      return Box({ key: 'memhub-strip-row', justifyContent: 'flex-end', children: line })
613    }
614    // hippo_half.py picks its pixel size from the terminal's height; the band
615    // gets less than that, and only says how much by how much it scrolled. So
616    // pick from the allowance, and where the drawing did not fit, remember the
617    // rows it actually got and pick again — shrinking until it sits whole.
618    if (band.roomAt !== e.props.bodyColumns || band.roomMax !== e.props.maxRows) {
619      band.roomAt = e.props.bodyColumns
620      band.roomMax = e.props.maxRows
621      band.roomRows = null
622    }
623    const ask = askOf(band)
624    // A waiting proposal's buttons sit inside its bubble, where Got it goes.
625    // Once the animal has said it and gone, they wait on a row of their own
626    // under it; that row is kept while one waits, so the drawing never jumps.
627    // On the desktop they always have that row (see the header).
628    const isRowed = e.surface === 'desktop' ? ask !== undefined : band.mode === 'auto' && band.asks.length > 0
629    // no one signed in: a row of its own under the animal, kept until a poll finds a sign-in
630    const isSignedOut = band.mode === 'auto' && band.signIn === 'out'
631    const extra = (isRowed ? 1 : 0) + (isSignedOut ? 1 : 0)
632    const room = Math.max(1, Math.min(e.props.maxRows, band.roomRows ?? e.props.maxRows) - extra)
633    const build = buildFor(band.animal, band.scale)
634    if (build !== band.build) {
635      // different art, different frames: it starts over rather than cutting
636      // from one drawing's pose into another's
637      band.build = build
638      band.seg = segment(band, 'offscreen')
639      band.current = { canvas: [] }
640    }
641    band.layout = layoutOf(build, e.props.bodyColumns, room, band.scale ?? undefined, linesOf(band), e.surface === 'desktop' ? 0 : 1)
642    if (!band.layout) {
643      const name = band.animal.name.toLowerCase()
644      const where = e.surface === 'desktop' ? 'window' : 'terminal'
645      return Text({ dimColor: true, children: `make the ${where} a little bigger for the ${name}` })
646    }
647    const { bodyRows } = e.props.scroll
648    if (bodyRows > 0 && bodyRows < band.layout.rows + extra && band.roomRows !== bodyRows) {
649      band.roomRows = bodyRows
650      $.ui.invalidate('ui.render')
651    }
652    const petButton = () =>
653      Button({ key: PET_KEY, plain: true, dimColor: true, label: '♥', onPress: () => onClick(band) })
654    const at = buttonsAt(band, build, band.layout)
655    band.buttonsKey = keyOfButtons(at)
656    const signedOut = isSignedOut ? [Box({ key: 'signed-out', children: Text({ dimColor: true, children: SIGNED_OUT_ROW }) })] : []
657
658    if (e.surface === 'desktop') {
659      const buf = compose(band.current, build, titleOf(band.animal), band.layout)
660      band.lastCells = encode(buf)
661      band.wordKey = ''
662      const art = Box({
663        alignItems: 'flex-end',
664        children: [
665          petButton(),
666          // no `key`: an Svg takes none (SvgProps), and Claude Code 2.1.292
667          // drops one from the drawn tree
668          $.ui.resolve(e).Svg({
669            source: svgOf(buf),
670            alt: `${titleOf(band.animal)}, the MemHub companion`,
671            width: band.layout.columns * CELL_W,
672            height: band.layout.rows * CELL_H,
673          }),
674        ],
675      })
676      const under = [...(ask && at !== null ? [waiting(ask)] : []), ...signedOut]
677      if (under.length === 0) return Box({ justifyContent: 'flex-end', children: art })
678      return Box({ flexDirection: 'column', alignItems: 'flex-end', children: [art, ...under] })
679    }
680
681    band.lastCells = cellsOf(band) ?? ''
682    const raster = $.ui.resolve(e).Raster({
683      key: RASTER_KEY,
684      columns: band.layout.columns,
685      rows: band.layout.rows,
686      cells: band.lastCells,
687    })
688    // a ♥ just left of where the ground begins, on its row: a click on it pets
689    // the animal. No hotkey: a plain Button draws one as `p: ♥`.
690    const pet = petAt(build, band.layout)
691    const clicks = Box({ key: 'companion-clicks', position: 'absolute', top: pet.top, left: pet.left, children: petButton() })
692    // a proposal's `rule`, once typed, opens the rule in MemHub Studio: a
693    // plain Button labelled `rule`, over the word itself, on the bubble's own
694    // background, underlined under the pointer
695    const word = wordOf(band)
696    band.wordKey = keyOfWord(word)
697    const linked = word
698      ? [Box({
699          key: 'rule-word', position: 'absolute', top: word.at.row, left: word.at.col, width: RULE_WORD.length,
700          backgroundColor: BUB_BG_HEX,
701          children: Button({
702            key: 'rule-link', plain: true, label: RULE_WORD, hover: { underline: true }, onPress: opens(word.ask.url),
703          }),
704        })]
705      : []
706    // the buttons inside the bubble, once its text is typed out (see buttonsAt)
707    const inBubble = ask && at && at !== 'below'
708      ? [Box({
709          position: 'absolute', top: at.row, left: at.col, width: at.width,
710          backgroundColor: BUB_BG_HEX, gap: 2, children: controlsFor(ask),
711        })]
712      : []
713    const drawn = Box({ children: [raster, clicks, ...linked, ...inBubble] })
714    const under = [...(ask && at === 'below' ? [waiting(ask)] : []), ...signedOut]
715    if (under.length === 0) return Box({ justifyContent: 'flex-end', children: drawn })
716    return Box({ flexDirection: 'column', alignItems: 'flex-end', children: [drawn, ...under] })
717  })
718}
719
720/**
721 * What the mod wrote to `$.state` since the band last looked: each new fire
722 * announced once (crossly when it blocked the call), and the proposals handed
723 * to the band when their list changed. Called while drawing, so the reads
724 * subscribe the band and every write draws it again. A read that fails is
725 * nothing new.
726 */
727async function feedFromState($: EngineInterface, band: Band) {
728  const fires = firesOf(await readSafe(() => read($, FIRES)))
729  const { fresh, seen } = freshFires(fires, band.seenFires ?? new Set())
730  const isFirstLook = band.seenFires === null
731  band.seenFires = seen
732  // the first look of this load takes what is there as already said
733  if (!isFirstLook) announce(band, fresh.map(saidOfNote))
734  const notes = proposalsOf(await readSafe(() => read($, PROPOSALS)))
735  if (notes !== null && proposalsKey(notes) !== band.proposalsKey) {
736    band.proposalsKey = proposalsKey(notes)
737    void syncProposals($, band, notes)
738  }
739}
740
741/** A `$.state` read that cannot throw: undefined for anything that went wrong. */
742async function readSafe(get: () => Promise<unknown>): Promise<unknown> {
743  try {
744    return await get()
745  } catch {
746    return undefined
747  }
748}
749
750/** The Rulebook lanes the mod has claimed; none when unknown. */
751async function lanesNow($: EngineInterface) {
752  return lanesOf(await readSafe(() => read($, LANES)))
753}
754
755/**
756 * Ask the server for this session's proposed rules — once at a time — merge
757 * its list into `$.state` proposals and hand the result to the band. A poll
758 * that could not ask changes nothing.
759 */
760async function pollProposals($: EngineInterface, band: Band) {
761  if (band.isPolling) return   // with the animal off the strip asks and answers, so the poll runs either way
762  band.isPolling = true
763  try {
764    const session = await sessionIdOf($)
765    const since = await $.clock.now().catch(() => 0)
766    if (!session) return
767    const listed = await listProposed($, band, session, since)
768    // a key the server refuses twice is no sign-in, whatever api-info says; no
769    // key is what the lookup the list just made said; a list that failed any
770    // other way says nothing of the sign-in
771    noteSignIn($, band, session, listed === 'refused' ? 'out' : listed === 'no_key' ? signInOf(band) : listed ? 'in' : 'unknown')
772    if (!listed || listed === 'refused' || listed === 'no_key') return
773    band.env = envName(band.ctx.env)
774    const merged = await update($, PROPOSALS, current => mergedProposals(proposalsOf(current) ?? [], listed.notes, since))
775      .then(proposalsOf, () => null)
776    // no $.state to write to (or the write refused): the server's list is the list
777    const notes = merged ?? listed.notes
778    band.proposalsKey = proposalsKey(notes)
779    await syncProposals($, band, notes)
780  } catch {
781    // companion-upgrades §1.2: never thrown out of a timer
782  } finally {
783    band.isPolling = false
784  }
785}
786
787/**
788 * What the poll found of the sign-in: no one signed in is said once a
789 * session and keeps its row under the animal; a sign-in after that is said
790 * too and takes the row away. 'unknown' (api-info could not answer) is
791 * neither, so a broken lookup never tells a signed-in person to log in.
792 */
793function noteSignIn($: EngineInterface, band: Band, session: string, now: SignIn) {
794  if (now === 'unknown') return
795  const was = band.signIn
796  // the strip keeps the answer too (its not-signed-in line, and the enable
797  // ask, which waits for a sign-in) but has no bubble to say it in
798  band.signIn = now
799  if (band.isEnabled) {
800    if (now === 'out' && band.saidSignedOutIn !== session) {
801      band.saidSignedOutIn = session
802      announce(band, [{ text: SIGNED_OUT_SAID, tone: 'advice' }])
803    } else if (now === 'in' && was === 'out') {
804      announce(band, [{ text: SIGNED_IN_SAID, tone: 'advice' }])
805    }
806  }
807  if (now !== was) $.ui.invalidate('ui.render')
808}
809
810/** Hand `notes` to the band after any update still running. */
811function syncProposals($: EngineInterface, band: Band, notes: readonly ProposalNote[]): Promise<void> {
812  band.syncing = band.syncing.then(() => applyProposals($, band, notes)).catch(() => undefined)
813  return band.syncing
814}
815
816/**
817 * `notes` is the whole of what is still waiting: an ask on the band it no
818 * longer names (decided in Studio, or by anyone else) comes off, buttons and
819 * any queued saying of it with it; a rule this session has not announced yet
820 * is said and asked. What was announced is kept in the store per session, so
821 * a reload of this module does not say it again (companion-upgrades §3.11).
822 */
823async function applyProposals($: EngineInterface, band: Band, notes: readonly ProposalNote[]) {
824  const waiting = new Set(notes.map(p => p.ruleId))
825  const gone = band.asks.filter(a => !waiting.has(a.ruleId))
826  if (gone.length > 0) {
827    band.asks = band.asks.filter(a => waiting.has(a.ruleId))
828    const unsaid = new Set(gone.map(proposalSaid))
829    band.queue = band.queue.filter(q => !(q.tone === 'proposed' && unsaid.has(q.text)))
830    $.ui.invalidate('ui.render')
831  }
832  const session = await sessionIdOf($)
833  const stored = announcedOf(await $.store.get(STORE_ANNOUNCED).catch(() => undefined))
834  if (session) for (const id of announcedIn(stored, session)) band.announced.add(id)
835  const fresh = notes.filter(p => !band.announced.has(p.ruleId)).map(p => proposedOfNote(p, band.env))
836  if (fresh.length === 0) return
837  for (const p of fresh) band.announced.add(p.ruleId)
838  if (session) {
839    await $.store.set(STORE_ANNOUNCED, withAnnounced(stored, session, fresh.map(p => p.ruleId))).catch(() => undefined)
840  }
841  announce(band, fresh.map(p => ({ text: proposalSaid(p), tone: 'proposed' as const })))
842  band.asks.push(...fresh)
843  for (const p of fresh) void linkOf($, band, p)
844  $.ui.invalidate('ui.render')
845}
846
847// MemHub over `$.http.fetch` (spec §4.11, W12): the proposal poll, Activate /
848// Reject, and where a rule opens in Studio. They used to shell out to
849// `python3 scripts/rule_decide.py` per call; that script stays for the
850// skills, and its requests are mirrored here (feed.ts). Every call settles:
851// a failure is an answer (null, 'no_key', an error Decision), never a throw
852// (companion-upgrades §1.2). These live in this file because `claude plugin
853// validate` follows `$` into no imported function.
854
855/**
856 * The REST base, bearer and Studio origin: the mod's `ctx.api()`, which runs
857 * `rulebook_mod_cli.py api-info` once a session and keeps the answer in module
858 * memory only (a secret: never `$.state` or `$.store`).
859 */
860async function apiFor(band: Band): Promise<Api | undefined> {
861  return band.ctx.api().then(a => (isApi(a) ? a : undefined), () => undefined)
862}
863
864/** What the last credential lookup said of the sign-in; 'unknown' for a ctx that cannot say. */
865function signInOf(band: Band): SignIn {
866  try {
867    return band.ctx.signIn()
868  } catch {
869    return 'unknown'
870  }
871}
872
873/** Drop the cached credential (after a 401) so the next apiFor() resolves it again. */
874function forgetApi(band: Band) {
875  try {
876    band.ctx.forgetApi()
877  } catch {
878    // a ctx that cannot forget costs one more 401, never a thrown hook
879  }
880}
881
882/** The plugin's folder: `$.plugin.root` may name its `.claude-plugin`. */
883function rootOf($: EngineInterface) {
884  return $.plugin.root.replace(/\/\.claude-plugin\/?$/, '')
885}
886
887let manifestVersion: Promise<string> | undefined
888
889/** plugin_version.request_headers()'s value: the manifest's version, '' when unreadable. */
890function versionOf($: EngineInterface): Promise<string> {
891  manifestVersion ??= $.fs.read(`${rootOf($)}/.claude-plugin/plugin.json`).then(versionOfManifest, () => '')
892  return manifestVersion
893}
894
895type Sent = { status: number; text: string; base: string }
896
897/**
898 * One request to MemHub's REST API with the plugin's key, as rule_decide.py
899 * sends it. A 401 drops the cached key and tries once more with a fresh one.
900 * 'no_key' when there is no key to send; null when no answer came.
901 */
902async function send($: EngineInterface, band: Band, path: string, body?: { method: string; body: string }): Promise<Sent | 'no_key' | null> {
903  for (let attempt = 0; ; attempt += 1) {
904    const api = await apiFor(band).catch(() => undefined)
905    if (!api) return 'no_key'
906    const headers = headersOf(api, await versionOf($), body !== undefined)
907    const base = api.base.replace(/\/+$/, '')
908    const res = await $.http.fetch(`${base}${path}`, { ...body, headers }).catch(() => null)
909    if (!res) return null
910    if (res.status === 401 && attempt === 0) {
911      forgetApi(band)
912      continue
913    }
914    return { status: res.status, text: typeof res.text === 'string' ? res.text : '', base }
915  }
916}
917
918/**
919 * This session's rules still `proposed` as the server lists them, and the
920 * base that answered; 'no_key' when there was no key to send; 'refused'
921 * when the key was refused even freshly resolved (a second 401); null when it could not be asked or answered oddly
922 * — then nothing may be taken off the band.
923 */
924async function listProposed($: EngineInterface, band: Band, session: string, at: number): Promise<{ notes: ProposalNote[]; base: string } | 'refused' | 'no_key' | null> {
925  const sent = await send($, band, PROPOSED_PATH)
926  if (sent === 'no_key') return 'no_key'
927  // a second 401, with a freshly resolved key: the key itself is refused
928  if (sent && sent !== 'no_key' && sent.status === 401) return 'refused'
929  if (!sent || sent === 'no_key' || sent.status < 200 || sent.status >= 300) return null
930  const notes = listedRules(sent.text, session, at)
931  return notes ? { notes, base: sent.base } : null
932}
933
934/** rule_decide.py `decide()`: Studio's own PATCH, and what came of it. */
935async function decideRule($: EngineInterface, band: Band, ruleId: string, action: keyof typeof STATUS_OF): Promise<Decision> {
936  if (!UUID.test(ruleId)) return { outcome: 'error', msg: 'not a rule id' }
937  const sent = await send($, band, rulePath(ruleId), { method: 'PATCH', body: JSON.stringify({ status: STATUS_OF[action] }) })
938  if (sent === 'no_key') return { outcome: 'no_key', msg: 'no stored access key; run /memhub:login' }
939  if (!sent) return { outcome: 'error', msg: 'no connection' }
940  // a second 401, with a freshly resolved key: the key itself is refused
941  if (sent.status === 401) return { outcome: 'no_key', msg: 'access key refused' }
942  return decisionOf(sent.status, sent.text, action)
943}
944
945/** Where the rule (or, with no id, the rulebook) opens in MemHub Studio; '' for nowhere. */
946async function studioUrlFor($: EngineInterface, band: Band, ruleId: string): Promise<string> {
947  const api = await apiFor(band).catch(() => undefined)
948  return api ? studioUrl(api.studio ?? '', ruleId) : ''
949}
950
951/** Take a decided rule out of `$.state` proposals, so no reader asks it again. */
952async function forget($: EngineInterface, band: Band, ruleId: string) {
953  const left = await update($, PROPOSALS, current => (proposalsOf(current) ?? []).filter(p => p.ruleId !== ruleId))
954    .then(proposalsOf, () => null)
955  if (left) band.proposalsKey = proposalsKey(left)
956}
957
958/**
959 * The companion's start, once a session: its saved state, its animal, its
960 * commands and its frame clock. The terminal runs it at session.start; the
961 * desktop, whose session.start says nothing of where it draws, at its first
962 * draw of the band.
963 */
964async function setUp($: EngineInterface, band: Band) {
965  if (band.isSetUp) return
966  band.isSetUp = true
967  band.isEnabled = await wantedOf($, band)
968  const savedScale = await $.store.get(STORE_SCALE).catch(() => undefined)
969  band.scale = SCALES.includes(savedScale as never) ? (savedScale as number) : null
970  band.sessionId = await sessionIdOf($)
971  // The engine has already drawn the band by now — hidden, since nothing is
972  // shown before this decides — and nothing redraws it on its own: switch
973  // the art as well as the name, then invalidate below, or the fallback
974  // walks in and stays until the terminal is next resized (a tmux split was
975  // how it showed).
976  const animal = await pickFor($, band.sessionId)
977  if (animal !== band.animal || buildFor(animal, band.scale) !== band.build) {
978    switchTo(band, animal)
979  }
980  for (const animal of ANIMALS) {
981    await $.command
982      .register({
983        name: commandOf(animal),
984        description: `The MemHub ${animal.name.toLowerCase()} above the prompt: what the plugin is doing, as it happens`,
985        argumentHint: usageOf(animal),
986        immediate: true,
987      })
988      .catch(() => undefined)
989  }
990  // and redraw whatever the store changed: the animal, the scale's layout,
991  // or a companion turned off, which draws nothing at all
992  $.ui.invalidate('ui.render')
993  if (band.isEnabled) {
994    start($, band)
995  }
996  // proposed rules: once now, then on the clock (and at each turn's end)
997  band.pollTimer ??= $.clock.every(POLL_MS, () => void pollProposals($, band))
998  void pollProposals($, band)
999}
1000
1001/**
1002 * Whether the companion shows in this session: the person turned it on
1003 * (`/<animal>`, stored true), or the plugin's `companion` option is on and
1004 * nobody turned it off (`/<animal> off`, stored false) — and MemHub is
1005 * active in the session's repository (`activeOf`). With the option off and
1006 * nothing stored, which is how the plugin installs, it stays away.
1007 */
1008async function wantedOf($: EngineInterface, band: Band): Promise<boolean> {
1009  const stored = await $.store.get(STORE_ENABLED).catch(() => undefined)
1010  const wanted = stored === true || (band.optionOn && stored !== false)
1011  band.active = await activeOf($, band)
1012  return wanted && band.active.enabled
1013}
1014
1015/**
1016 * The strip's quiet line, when nothing fired and nothing waits: where MemHub
1017 * is inactive (the allowlist) — this repository not listed, or no repository
1018 * here at all — how to enable it; else the book the mod holds for this
1019 * repository, or that the session is being captured.
1020 */
1021function quietOf($: EngineInterface, band: Band): string {
1022  if (stripSignIn(band) === 'out') return `MemHub · ${SIGNED_OUT_ROW}`
1023  if (band.active && !band.active.enabled) {
1024    return band.active.repo
1025      ? `MemHub · inactive in this repo (/${$.plugin.name}:repos add .)`
1026      : `MemHub · inactive here: not in a repository (/${$.plugin.name}:repos add . inside one)`
1027  }
1028  const book = band.ctx.book()
1029  if (!book) return 'MemHub · capturing'
1030  if (!book.rules) return `MemHub · capturing · no rules for ${book.repo}`
1031  return `MemHub · ${book.rules} rule${book.rules === 1 ? '' : 's'} armed for ${book.repo}`
1032}
1033
1034/**
1035 * The sign-in as the strip knows it: what the poll last found, else what the
1036 * credential lookup itself said (ctx.signIn: 'in' with a key, even when the
1037 * poll's request then failed). 'unknown' before either.
1038 */
1039function stripSignIn(band: Band): SignIn {
1040  return band.signIn !== 'unknown' ? band.signIn : signInOf(band)
1041}
1042
1043/**
1044 * The repository the strip asks to enable MemHub in (ENG-1253), or undefined
1045 * for no ask. Every condition must hold, all from `paths` at boot: a
1046 * repos.json exists (`restricted`), the session is inside a checkout (`repo`
1047 * and `identity` known), the person is signed in, and the repository is
1048 * neither listed (`enabled`) nor declined — and the person has not said
1049 * Later this session. Not signed in: the quiet line's own row wins, and the
1050 * ask waits for a sign-in. Nothing here reads repos.json.
1051 */
1052function enableAskOf(band: Band): string | undefined {
1053  const a = band.active
1054  if (!a || a.enabled || !a.restricted || a.declined || !a.repo || !a.identity) return undefined
1055  if (band.enableAsk === 'later') return undefined
1056  if (stripSignIn(band) !== 'in') return undefined
1057  return a.identity
1058}
1059
1060/**
1061 * The ask's Yes or No: `rulebook_mod_cli.py answer`, which lists (Yes:
1062 * `repo_allow.allow`, what `/memhub:repos add .` writes) or declines (No:
1063 * `repo_allow.decline`) the session's checkout. The buttons wait while it
1064 * writes, so a second press cannot answer twice. The Python hooks read the
1065 * file per call and follow at the next one; the mod flips its own state here:
1066 * ctx.active() (so `/goose` and the shell see it) and the strip's line — after
1067 * Yes the animal, where the option or the store asks for it, as in any listed
1068 * repository; else the quiet line. A write that failed leaves the ask up.
1069 */
1070async function answerEnable($: EngineInterface, band: Band, say: 'yes' | 'no') {
1071  const was = band.active
1072  if (band.enableAsk !== 'open' || !was?.identity) return
1073  band.enableAsk = 'answering'
1074  $.ui.invalidate('ui.render')
1075  let got: Record<string, unknown> | undefined
1076  try {
1077    const cwd = band.cwd || (await $.session.cwd().catch(() => '')) || '.'
1078    const argv = ['python3', `${rootOf($)}/${MOD_CLI}`, 'answer', '--env', band.ctx.env, '--cwd', cwd, '--say', say]
1079    const run = await $.process.run(argv, { timeoutMs: 10_000 }).catch(() => null)
1080    const out = run && run.exitCode === 0 ? lastJson(run.stdout) : undefined
1081    got = out && typeof out === 'object' ? (out as Record<string, unknown>) : undefined
1082  } finally {
1083    band.enableAsk = 'open'
1084  }
1085  if (!got || typeof got.enabled !== 'boolean') {
1086    $.ui.invalidate('ui.render')
1087    return
1088  }
1089  const next: Active = { ...was, enabled: got.enabled, declined: got.declined === true }
1090  band.active = next
1091  band.ctx.setActive(next)
1092  if (next.enabled && !band.isEnabled) {
1093    const stored = await $.store.get(STORE_ENABLED).catch(() => undefined)
1094    if (stored === true || (band.optionOn && stored !== false)) {
1095      band.isEnabled = true
1096      start($, band)
1097      if (band.isSetUp) void pollProposals($, band)
1098    }
1099  }
1100  $.ui.invalidate('ui.render')
1101}
1102
1103/** The ask's Later: hidden for the rest of this session, and nothing written. */
1104function enableLater($: EngineInterface, band: Band) {
1105  band.enableAsk = 'later'
1106  $.ui.invalidate('ui.render')
1107}
1108
1109/**
1110 * The repository allowlist's answer for the session, as the shell read it
1111 * (mod/ctx.ts `active`). The shell asks Python once at boot; should that
1112 * take longer than ACTIVE_WAIT_MS, the animal shows rather than waits.
1113 */
1114async function activeOf($: EngineInterface, band: Band): Promise<Active> {
1115  const asIs: Active = { enabled: true, repo: '' }
1116  try {
1117    return await Promise.race([band.ctx.active(), $.clock.sleep(ACTIVE_WAIT_MS).then(() => asIs)])
1118  } catch {
1119    return asIs
1120  }
1121}
1122
1123/** The most lines a bubble says where the band is drawn; the terminal's default when undefined. */
1124const linesOf = (band: Band) => (band.surface === 'desktop' ? DESKTOP_TEXT_LINES : undefined)
1125
1126const commandOf = (animal: Animal) => animal.name.toLowerCase()
1127
1128/** What its bubble introduces it as. */
1129const titleOf = (animal: Animal) => animal.title ?? animal.name
1130
1131/**
1132 * The build to draw: the largest whose art is drawn for a pixel no bigger than
1133 * the one asked for, and the smallest when nothing is asked — small is the
1134 * default, and a bigger pixel is `/<animal> scale <n>`'s to ask for.
1135 */
1136function buildFor(animal: Animal, scale: number | null): Build {
1137  const builds = [...animal.builds].sort((a, b) => a.pixelSize - b.pixelSize)
1138  if (scale === null) {
1139    return builds[0]!
1140  }
1141  const fits = builds.filter(b => b.pixelSize <= scale)
1142  return (fits[fits.length - 1] ?? builds[0])!
1143}
1144
1145const usageOf = (animal: Animal) =>
1146  ['on', 'off', 'auto', 'always', 'random', 'never', 'include', 'scale 1-4',
1147   ...(animal.builds[0]?.demo ? ['demo', ...(animal.builds[0]?.demoPoses ?? [])] : [])].join('|')
1148
1149function wantOf(band: Band): Want {
1150  if (band.queue.length > 0) return 'speak'
1151  return band.isWorking || band.frame < band.activeUntil || isPetting(band) ? 'look' : 'sleep'
1152}
1153
1154/** A click is waiting to be answered with a pet. */
1155const isPetting = (band: Band) => band.frame < band.petUntil
1156
1157async function sessionIdOf($: EngineInterface): Promise<string> {
1158  const id = await $.session.id().catch(() => '')
1159  return typeof id === 'string' ? id : ''
1160}
1161
1162async function prefsFor($: EngineInterface): Promise<Prefs> {
1163  return prefsOf(
1164    await $.store.get(STORE_PIN).catch(() => undefined),
1165    await $.store.get(STORE_NEVER).catch(() => undefined),
1166  )
1167}
1168
1169/** The animal a session shows: its own pick, the pin, or its id's hash (selection.ts). */
1170async function pickFor($: EngineInterface, sessionId: string): Promise<Animal> {
1171  const sessions = sessionsOf(await $.store.get(STORE_SESSIONS).catch(() => undefined))
1172  const name = pick(ANIMALS.map(a => a.name), sessionId, sessions, await prefsFor($))
1173  return ANIMALS.find(a => a.name === name) ?? DEFAULT_ANIMAL
1174}
1175
1176/** Another animal: it starts offscreen, not standing where the last one stood. */
1177function switchTo(band: Band, animal: Animal) {
1178  band.animal = animal
1179  band.mode = 'auto'
1180  band.build = buildFor(animal, band.scale)
1181  band.seg = segment(band, 'offscreen')
1182  band.current = { canvas: [] }
1183}
1184
1185/**
1186 * After a /clear or /resume: once the engine reports the new session's id,
1187 * pick its animal. Until then (the id not yet changed) it is tried again, by
1188 * the next event, and by the frame clock for a while. A command that picks
1189 * an animal meanwhile wins.
1190 */
1191async function repick($: EngineInterface, band: Band) {
1192  if (band.isPicking) return
1193  band.isPicking = true
1194  const gen = band.pickGen
1195  try {
1196    const id = await sessionIdOf($)
1197    if (!id || id === band.sessionId || gen !== band.pickGen) return
1198    band.needsRepick = false
1199    band.repickUntil = 0
1200    band.sessionId = id
mod/act.ts 291 lines
1// The act side: what the mod DOES with an engine Verdict (spec §4.6, §4.7,
2// §4.15). The engine decides; this file denies, adds context, discloses,
3// feeds the companion and writes the ledger.
4//
5// For each fire:
6//   (a) `$.state` `fires` gets a FireNote (newest last, capped at 50) — the
7//       companion's feed, replacing its regex over hook output (W7).
8//   (b) the disclosure. The person sees the line as a dim transcript row
9//       (`$.ui.log`), the mod path's stand-in for the Python hook's
10//       `systemMessage`. Gate G2 (spec §8.4) has passed: MemHub-Backend
11//       stores a disclosure `system` row as a role="system" message (#1493),
12//       so the system row is on (SYSTEM_ROW_DISCLOSURE). With it off (Act's
13//       `systemRow` = false, the Python path's behaviour), the model is told
14//       to echo the line with rulebook_hook.py's exact
15//       `disclosure_instruction` text. With it on, each
16//       fire is one transcript `system` row the model never reads,
17//       and the echo instruction is dropped for every verdict whose rows
18//       were all written; a row that could not be written keeps the echo.
19//       The first such fire of a session (and of each compaction) also
20//       writes NO_ECHO_NOTE, lifting the posture preamble's own "you MUST
21//       disclose" sentence.
22//   (c) the ledger: fire rows go to `rulebook_mod_cli.py log` at once (one
23//       process per fire, D6); per-call event rows wait in memory for
24//       `turn.complete`.
25//   (d) health: a lane error shows on the status line and in `$.state`
26//       `health`; the next success clears both.
27
28import type { FireNote } from '../types'
29import type { StatusLine } from './claims'
30import type { Ctx, Io } from './ctx'
31import { MOD_CLI } from './ctx'
32import type { Verdict } from './engine'
33
34/**
35 * D5: one `system` row per fire in the transcript (stored as
36 * `{type:'system', subtype:'informational', content:<line>}`), which capture
37 * uploads and the model never reads, in place of the model's echo. On since
38 * gate G2 (spec §8.4) passed: MemHub-Backend stores the row as a
39 * `role="system"` message (#1493, `claude_parts.is_disclosure_record`), so a
40 * stored session keeps the line without the model writing it. The Python
41 * path (Codex, Cursor, the fallback) still asks the model to echo.
42 */
43export const SYSTEM_ROW_DISCLOSURE = true
44
45/**
46 * With the system row on, the model is still carrying the posture preamble's
47 * "When one fires, you MUST disclose it …" (Python's SessionStart serves the
48 * startup session before the mod can claim it, and the mod's own preamble is
49 * byte-identical). Measured live (2.1.293): without this note the model still
50 * opens its reply with `📏 Rule fired:` lines — paraphrased, because it never
51 * saw the exact line. One `user` row per session (again after a compaction)
52 * lifts that instruction; it costs one row, not one per fire.
53 */
54export const NO_ECHO_NOTE =
55  '_MemHub now shows each rule fire to the user and records it in the transcript itself. ' +
56  'Do not write `📏 Rule fired:` or `⛔️ Rule fired:` lines in your replies: that part of ' +
57  "the Rulebook's session-start instruction no longer applies. Follow the rules themselves as before._"
58
59export const FIRES_CAP = 50
60/** Rows kept for a ledger that could not be written, before the oldest drop. */
61const PENDING_CAP = 500
62
63/** rulebook_hook.py `disclosure_instruction(lines)`, byte for byte. */
64export function disclosureInstruction(lines: readonly string[]): string {
65  const quoted = lines.join('\n')
66  return (
67    '\n_Disclose these to the user. Begin your next reply with the following ' +
68    'line(s), verbatim and each on its own line, before anything else — including ' +
69    'before any tool call narration:_\n' +
70    quoted +
71    '\n_This is how the team sees its rules working. Do not paraphrase, do not merge ' +
72    'them into a sentence, and do not omit one because it did not change what you were ' +
73    'going to do — a rule that fired and changed nothing is exactly the rule the team ' +
74    'needs to hear about._'
75  )
76}
77
78const MARKER = /^\s*(📏|⛔️?)\s*Rule fired:[^\S\n]*/u
79
80/** The rule as the line names it: the disclosure line without its marker. */
81export const ruleOfLine = (line: string) => line.replace(MARKER, '').trim()
82const isBlockedLine = (line: string) => /^\s*⛔/u.test(line)
83
84/**
85 * Which ledger rows are events (`log_event`: `event_id` + `kind`) rather than
86 * fires (`log_fires`: `fire_id`). The engine hands both in `Verdict.ledger`.
87 */
88export const isEventRow = (row: Record<string, unknown>) =>
89  typeof row.event_id === 'string' || (typeof row.kind === 'string' && !('fire_id' in row))
90
91export class Act {
92  private events: Record<string, unknown>[] = []
93  private fires: Record<string, unknown>[] = []
94  private notes: Promise<void> = Promise.resolve()
95  /** Verdicts whose every fire is a transcript system row: the model gets no echo instruction. */
96  private disclosed = new WeakSet<Verdict>()
97  /** Sessions whose conversation holds NO_ECHO_NOTE (cleared on compaction). */
98  private noted = new Set<string>()
99  /** A note write in flight, per session: parallel tool calls share it, so a session gets one note. */
100  private noting = new Map<string, Promise<boolean>>()
101  /** The lines of a verdict whose system row failed (its note was written): only those are echoed. */
102  private unwritten = new WeakMap<Verdict, string[]>()
103
104  constructor(
105    private io: Io,
106    private ctx: Ctx,
107    private status: StatusLine,
108    /** D5's transcript system row in place of the echo; SYSTEM_ROW_DISCLOSURE unless a test says. */
109    private systemRow: boolean = SYSTEM_ROW_DISCLOSURE,
110  ) {}
111
112  /** (a)–(c) for one verdict. Never throws: acting must not cost the call. */
113  async record(v: Verdict | undefined, sessionId: string): Promise<void> {
114    try {
115      await this.recordOnce(v, sessionId)
116    } catch (err) {
117      // Anything unforeseen (a synchronous `$` call that throws) is a health
118      // line, never the call's failure.
119      this.unhealthy('ledger', err)
120    }
121  }
122
123  private async recordOnce(v: Verdict | undefined, sessionId: string): Promise<void> {
124    if (!v) return
125    const at = await this.io.now().catch(() => 0)
126    if (v.fires.length) {
127      const notes: FireNote[] = v.fires.map(f => ({
128        ruleId: f.ruleId,
129        line: f.line,
130        rule: ruleOfLine(f.line) || f.text,
131        isBlocked: isBlockedLine(f.line),
132        at,
133      }))
134      await this.addNotes(notes)
135      const noted = this.systemRow && (await this.noteOnce(sessionId))
136      let written = noted
137      const failed: string[] = []
138      for (const f of v.fires) {
139        // `$.ui.log` is synchronous and may throw: the line is best effort.
140        try {
141          this.io.log(f.line)
142        } catch {
143          // the transcript copy (the system row, or the model's echo) remains
144        }
145        if (!this.systemRow) continue
146        try {
147          await this.io.append('system', f.line)
148        } catch (err) {
149          // No transcript copy for this fire: the verdict keeps the echo
150          // instruction, so the line is not lost, and the person is told.
151          written = false
152          failed.push(f.line)
153          this.unhealthy('disclosure', err)
154        }
155      }
156      if (written) {
157        this.disclosed.add(v)
158        this.healthy('disclosure')
159      } else if (noted && failed.length) {
160        // The note is in place, so the model echoes only what we asked it to:
161        // just the lines with no row, never one the transcript already holds.
162        this.unwritten.set(v, failed)
163      }
164    }
165    for (const row of v.ledger) (isEventRow(row) ? this.events : this.fires).push(row)
166    // One process per fire, never per call: events alone wait for the turn's end.
167    if (this.fires.length) await this.flush(sessionId)
168  }
169
170  /**
171   * The text the model reads for a verdict: its context, then the echo
172   * instruction — unless `record` wrote every fire as a transcript system row.
173   */
174  modelText(v: Verdict | undefined): string | undefined {
175    if (!v) return undefined
176    const lines = [...v.context]
177    if (v.fires.length && !this.disclosed.has(v)) {
178      lines.push(disclosureInstruction(this.unwritten.get(v) ?? v.fires.map(f => f.line)))
179    }
180    const text = lines.join('\n')
181    return text.trim() ? text : undefined
182  }
183
184  /**
185   * A deny carries no `context` (ToolCallResult's deny arm), so the model's
186   * whole copy rides the reason: the gate's own text, then the context and
187   * (unless the fires are system rows) the echo instruction the Python hook
188   * would have put in additionalContext.
189   */
190  denyText(v: Verdict): string {
191    return [v.deny ?? '', this.modelText(v)].filter(Boolean).join('\n')
192  }
193
194  /**
195   * NO_ECHO_NOTE into the session once. False when it could not be written:
196   * the preamble's disclosure instruction then stands, so the verdict keeps
197   * the verbatim echo instruction rather than leave the model to paraphrase.
198   */
199  private async noteOnce(sessionId: string): Promise<boolean> {
200    if (this.noted.has(sessionId)) return true
201    // Parallel tool calls each record a verdict: they share the one write in
202    // flight, or a session would get the note once per concurrent call.
203    const inFlight = this.noting.get(sessionId)
204    if (inFlight) return inFlight
205    const write = (async () => {
206      try {
207        await this.io.append('user', NO_ECHO_NOTE)
208        this.noted.add(sessionId)
209        return true
210      } catch (err) {
211        this.unhealthy('disclosure', err)
212        return false
213      } finally {
214        this.noting.delete(sessionId)
215      }
216    })()
217    this.noting.set(sessionId, write)
218    return write
219  }
220
221  /** A compaction summarised the note away with the preamble: the next fire writes it again. */
222  compacted(sessionId: string): void {
223    this.noted.delete(sessionId)
224  }
225
226  /** Writes every waiting ledger row through the Python ledger (turn.complete, or a fire). */
227  async flush(sessionId: string): Promise<void> {
228    if (!this.fires.length && !this.events.length) return
229    const fires = this.fires
230    const events = this.events
231    this.fires = []
232    this.events = []
233    try {
234      const r = await this.io.run(['python3', `${this.ctx.root}/${MOD_CLI}`, 'log', '--env', this.ctx.env], {
235        stdin: JSON.stringify({ session: sessionId, fires, events }),
236        timeoutMs: 10_000,
237      })
238      if (r.exitCode !== 0) throw new Error(`ledger log exited ${r.exitCode}`)
239      this.healthy('ledger')
240    } catch (err) {
241      // Kept for the next flush; bounded so a broken ledger cannot grow without end.
242      this.fires = [...fires, ...this.fires].slice(-PENDING_CAP)
243      this.events = [...events, ...this.events].slice(-PENDING_CAP)
244      this.unhealthy('ledger', err)
245    }
246  }
247
248  private failing = new Set<string>()
249
250  /** (d) A lane (or the ledger) hit an error the person should know of. */
251  unhealthy(what: string, err: unknown): void {
252    this.failing.add(what)
253    const why = err instanceof Error ? err.message : String(err)
254    const line = `MemHub: ${what} — ${why}`.replace(/\s+/g, ' ').slice(0, 200)
255    this.show(line)
256  }
257
258  /** (d) The next success clears it. */
259  healthy(what: string): void {
260    if (!this.failing.delete(what) || this.failing.size) return
261    this.show(undefined)
262  }
263
264  /** The health line on the status line and in `$.state`. Never throws: it runs in failure paths. */
265  private show(line: string | undefined): void {
266    try {
267      this.status.set('health', line)
268    } catch {
269      // `$.ui.status` is synchronous; a refused line is not the call's failure
270    }
271    try {
272      void this.io.setState('health', line ?? '').catch(() => undefined)
273    } catch {
274      // as above
275    }
276  }
277
278  private addNotes(notes: FireNote[]): Promise<void> {
279    // One read-modify-write at a time: parallel tool calls fire together.
280    this.notes = this.notes.then(async () => {
281      try {
282        const { value = [] } = await this.io.getState('fires')
283        await this.io.setState('fires', [...value, ...notes].slice(-FIRES_CAP))
284      } catch {
285        // the companion's feed is best effort
286      }
287    })
288    return this.notes
289  }
290}
291
mod/book.ts 547 lines
1// The rule book on the mod path (spec §4.1): load the cached book at
2// session.start, keep it fresh with `$.clock.every`, and hand the rows to the
3// engine. The book file is the one rulebook_hook.py reads and writes —
4// `{"etag", "fetched_at", "rules"}` at the path `rulebook_mod_cli.py paths`
5// names — so the Python fallback is never staler than the mod.
6//
7// Mirrors rulebook_hook.py `fetch_book` (GET /v1/team/rulebook/rules
8// ?view=hook&repo=<repo>&hook_version=<v> with If-None-Match; no `status=`)
9// and `_norm_rules` (to_hook_rule per row, first id wins). Replaces the
10// detached `fetch` child `maybe_refresh` spawns (W4).
11
12import type { Claims, StatusLine } from './claims'
13import type { Ctx, Io } from './ctx'
14import { lastJson, MOD_CLI } from './ctx'
15import type { Engine, HookRule } from './engine'
16import { toHookRule as shapeRow, versionTuple } from './engine/rules'
17
18/**
19 * One served row → the flat hook rule (engine/rules.ts `toHookRule`), shaped
20 * for this build's own version so a `min_hook_version` row degrades exactly
21 * as it does in the Python hook beside it. No forward-test claim here
22 * (`activeBase` false): /memhub:create-rule's private-base forward test is
23 * served by the Python hook, which reads the claim — the lanes hand it every
24 * call the claim covers (mod/redirect.ts), since the rows dropped here are
25 * exactly the ones that test must see fire.
26 */
27export const hookRuleFor = (hookVersion: string | undefined) => (row: Record<string, unknown>): HookRule | null =>
28  shapeRow(row, { hookVersion: versionTuple(hookVersion ?? null), activeBase: false })
29
30export const toHookRule = hookRuleFor(undefined)
31
32export const API_PATH = '/v1/team/rulebook'
33export const REFRESH_MS = 60_000
34/** Consecutive refresh failures before the status line says so (a blip is not news). */
35const REFRESH_FAILURES_SHOWN = 3
36/**
37 * Consecutive refresh failures after which the mod gives every lane back to
38 * Python for the session — once its book is also older than Python's own
39 * staleness window (rulebook_hook.py `REFRESH_AFTER_S`), so Python, whose
40 * urllib takes a different road than `$.http.fetch`, would refresh it.
41 */
42export const RELEASE_AFTER_FAILURES = 5
43/** rulebook_hook.py `REFRESH_AFTER_S` (60 s): Python refreshes a book older than this. */
44export const PYTHON_REFRESH_AFTER_MS = 60_000
45
46export const FETCH_REFUSED = "MemHub rules: your organization's web-fetch policy refuses the mod — the command hooks serve the rules"
47export const REFRESH_GAVE_UP = 'MemHub rules: the mod could not refresh the rules — the command hooks serve them'
48
49/**
50 * Whether a `$.http.fetch` rejection is a refusal, never a network blip.
51 *
52 * The engine refuses before any request leaves with
53 * `<plugin>: $.http.fetch: refused: <why>` — the organization's web-fetch
54 * policy (`allow_web_fetch`: "Network access from plugins …"),
55 * CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC, a confined eval — and a hook's
56 * `{ deny }` on `http.fetch` rejects as `<plugin>: $.http.fetch: <deny>`. A
57 * request that went out and failed reads `$.http.fetch(<url>) failed: …` or
58 * `… aborted: …`, with the URL in parentheses. (Claude Code 2.1.292; the
59 * d.ts says only "unless the organization's web-fetch policy refuses it".)
60 * A refusal does not heal by retrying, so it is acted on at once.
61 */
62export function isFetchRefused(err: unknown): boolean {
63  const msg = err instanceof Error ? err.message : String(err)
64  return /\$\.http\.fetch: /.test(msg)
65}
66
67/** A `fetched_at` Python wrote (microseconds, an offset) as epoch ms; undefined when unreadable. */
68export function msOfIso(iso: string | null | undefined): number | undefined {
69  if (typeof iso !== 'string') return undefined
70  const ms = Date.parse(iso.replace(/(\.\d{3})\d+/, '$1'))
71  return Number.isFinite(ms) ? ms : undefined
72}
73
74export type BookFile = { etag?: string | null; fetched_at?: string | null; rules: Record<string, unknown>[] }
75/**
76 * What `paths` answers for a checkout. `enabled` is the repository
77 * allowlist's verdict (scripts/repo_allow.py: `~/.config/memhub-plugin/repos.json`);
78 * false means MemHub is dormant there, and the mod claims nothing.
79 */
80export type Paths = { book: string; repo: string; ledger?: string; enabled: boolean }
81
82/** The cached book, as `load_book` accepts it: a dict whose `rules` is a list. */
83export function parseBook(text: string): BookFile | undefined {
84  try {
85    const b = JSON.parse(text) as unknown
86    if (b && typeof b === 'object' && !Array.isArray(b) && Array.isArray((b as BookFile).rules)) return b as BookFile
87  } catch {
88    // unreadable is no book, as in Python
89  }
90  return undefined
91}
92
93/** `_norm_rules`: each row through toHookRule, unrunnable rows dropped, the first of an id kept. */
94export function shapeRules(
95  rows: readonly unknown[],
96  toHook: (row: Record<string, unknown>) => HookRule | null = toHookRule,
97): HookRule[] {
98  const out: HookRule[] = []
99  const seen = new Set<string>()
100  for (const row of rows) {
101    if (!row || typeof row !== 'object') continue
102    const r = toHook(row as Record<string, unknown>)
103    if (r && !seen.has(r.id)) {
104      seen.add(r.id)
105      out.push(r)
106    }
107  }
108  return out
109}
110
111/** `_now()`: ISO with microseconds and an explicit offset, which every Python `fromisoformat` reads. */
112export function isoOf(ms: number): string {
113  return new Date(ms).toISOString().replace(/\.(\d{3})Z$/, '.$1000+00:00')
114}
115
116/** `urllib.parse.quote(s, safe="")`: everything but letters, digits and `_.-~` escaped. */
117export function quoteAll(s: string): string {
118  return encodeURIComponent(s).replace(/[!'()*]/g, c => `%${c.charCodeAt(0).toString(16).toUpperCase()}`)
119}
120
121/** `require_secure`: a credential rides https, or loopback http only. */
122export function isSecure(url: string): boolean {
123  const m = /^([a-z][a-z0-9+.-]*):\/\/(\[[^\]]*\]|[^/:?#]*)/i.exec(url)
124  if (!m) return false
125  if (m[1]!.toLowerCase() === 'https') return true
126  const host = m[2]!.toLowerCase().replace(/^\[|\]$/g, '')
127  return m[1]!.toLowerCase() === 'http' && (host === 'localhost' || host === '127.0.0.1' || host === '::1')
128}
129
130/**
131 * What `paths` answers for a session's cwd, whole: the book to serve (none
132 * outside a checkout, or with no book), the repo's name ('' outside any
133 * checkout), and the allowlist's verdict — which stands even where there is
134 * no repo: a session in a folder that is no repository is dormant when a
135 * repos.json exists (repo_allow.session_enabled), and the companion says so.
136 * With it, what the companion's enable ask (ENG-1253) reads: `restricted`
137 * (a repos.json exists), `declined` (the person answered No here before) and
138 * `identity` (the checkout as repos.json names it, `org/name`; '' unknown).
139 */
140export type PathsAnswer = {
141  paths: Paths | undefined
142  repo: string
143  enabled: boolean
144  restricted: boolean
145  declined: boolean
146  identity: string
147  /**
148   * The install's own rulebook base (`real_base`), where a create-rule
149   * forward test leaves its claim file (mod/redirect.ts). `base` itself may
150   * already be that test's private copy when the claim covers the cwd.
151   * Undefined from an older CLI.
152   */
153  realBase?: string
154}
155
156/** `rulebook_mod_cli.py paths --env <env> --cwd <dir>`, as the CLI answers it. */
157export async function askPaths(io: Io, ctx: Ctx, cwd: string): Promise<PathsAnswer> {
158  const r = await io.run(['python3', `${ctx.root}/${MOD_CLI}`, 'paths', '--env', ctx.env, '--cwd', cwd], { timeoutMs: 10_000 })
159  if (r.exitCode !== 0) throw new Error(`paths exited ${r.exitCode}: ${r.stderr.slice(0, 200)}`)
160  const got = lastJson(r.stdout) as Record<string, unknown> | undefined
161  if (!got || typeof got !== 'object') throw new Error('paths printed no JSON')
162  const book = got.book ?? got.book_path
163  const repo = typeof got.repo === 'string' ? got.repo : ''
164  const ledger = got.ledger ?? got.ledger_dir
165  // An older CLI answers no `enabled`: active, as everything was before the list existed.
166  const enabled = got.enabled !== false
167  // …and no `restricted`, `declined` or `identity`: nothing to ask about, then.
168  const rest = {
169    restricted: got.restricted === true,
170    declined: got.declined === true,
171    identity: typeof got.identity === 'string' ? got.identity : '',
172    realBase: typeof got.real_base === 'string' && got.real_base ? got.real_base : undefined,
173  }
174  // No repo (not a git checkout, or no remote): no book to serve, nothing to claim.
175  if (!repo || typeof book !== 'string' || !book) return { paths: undefined, repo, enabled, ...rest }
176  return { paths: { book, repo, ledger: typeof ledger === 'string' ? ledger : undefined, enabled }, repo, enabled, ...rest }
177}
178
179/** `askPaths`' book, or undefined where there is none to serve. */
180export async function pathsFor(io: Io, ctx: Ctx, cwd: string): Promise<Paths | undefined> {
181  return (await askPaths(io, ctx, cwd)).paths
182}
183
184export type RefreshOutcome = 'updated' | 'unchanged' | 'upgrade' | 'skipped' | 'failed'
185
186export class Book {
187  repo: string | undefined
188  path: string | undefined
189  /** The install's own base (PathsAnswer.realBase), once `paths` answered. */
190  realBase: string | undefined
191  private etag: string | undefined
192  private timer: { cancel(): void } | undefined
193  private inFlight = false
194  private failures = 0
195  private stopped = false
196  /** When the book the engine holds was last known current (epoch ms). */
197  private freshAt: number | undefined
198
199  constructor(
200    private io: Io,
201    private ctx: Ctx,
202    private engine: Engine,
203    private claims: Claims,
204    private status: StatusLine,
205    private opts: {
206      hookVersion?: string
207      toHook?: (row: Record<string, unknown>) => HookRule | null
208      /** Told what `paths` answered for the session's cwd, once, before anything is loaded. */
209      onPaths?: (answer: PathsAnswer) => void
210      /** Told the repository and rule count each time rows are handed to the engine. */
211      onRules?: (repo: string, count: number) => void
212    } = {},
213  ) {}
214
215  /**
216   * At session.start: find the book, read it, hand it to the engine. A
217   * missing cache is fetched once, here. Resolves true once the engine holds
218   * a book (then the lanes may be claimed), false when there is none to hold
219   * (signed out with no cache, no repo, or a repo the machine's allowlist
220   * leaves out): Python then serves, with no book either — and in the
221   * allowlist case stays silent too, reading the same file. Rejects on a
222   * real failure (the caller releases every lane).
223   */
224  async load(cwd: string): Promise<boolean> {
225    const answer = await askPaths(this.io, this.ctx, cwd)
226    this.realBase = answer.realBase
227    this.opts.onPaths?.(answer)
228    const paths = answer.paths
229    if (!paths) return false
230    // Dormant here (repo_allow.py): nothing to serve, nothing to claim, no refresh.
231    if (!paths.enabled) return false
232    this.repo = paths.repo
233    this.path = paths.book
234    // A recorded upgrade notice suspends the cached rules (rulebook_hook
235    // `upgrade_status`); only Python can validate and clear it, so it serves.
236    if (await this.io.readFile(`${paths.book}.upgrade`).then(() => true, () => false)) return false
237    const text = await this.io.readFile(paths.book).catch(() => undefined)
238    const cached = text === undefined ? undefined : parseBook(text)
239    if (cached) {
240      this.etag = cached.etag ?? undefined
241      this.freshAt = msOfIso(cached.fetched_at)
242      await this.hand(cached.rules)
243      return true
244    }
245    return (await this.refresh()) === 'updated'
246  }
247
248  /** Every minute until stopped. A tick never overlaps the one before it. */
249  start(): void {
250    if (this.timer || this.stopped) return
251    this.timer = this.io.every(REFRESH_MS, () => {
252      void this.refresh()
253    })
254  }
255
256  stop(): void {
257    this.stopped = true
258    this.timer?.cancel()
259    this.timer = undefined
260  }
261
262  /** One GET with If-None-Match: 200 → write the file + setBook; 304 → nothing; 426 → stop serving. */
263  async refresh(): Promise<RefreshOutcome> {
264    if (this.inFlight || this.stopped || !this.repo || !this.path) return 'skipped'
265    this.inFlight = true
266    try {
267      return await this.fetchOnce(true)
268    } catch (err) {
269      await this.failed(err)
270      return 'failed'
271    } finally {
272      this.inFlight = false
273    }
274  }
275
276  private async fetchOnce(retryOn401: boolean): Promise<RefreshOutcome> {
277    const api = await this.ctx.api()
278    if (!api) return 'skipped'
279    if (!isSecure(api.base)) throw new Error('refusing to send credentials over cleartext')
280    let q = `view=hook&repo=${quoteAll(this.repo!)}`
281    if (this.opts.hookVersion) q += `&hook_version=${this.opts.hookVersion}`
282    const headers: Record<string, string> = { Authorization: `Bearer ${api.bearer}`, Accept: 'application/json' }
283    if (this.opts.hookVersion) headers['X-MemHub-Plugin-Version'] = this.opts.hookVersion
284    if (this.etag) headers['If-None-Match'] = this.etag
285    const reply = await this.io.fetch(`${api.base}${API_PATH}/rules?${q}`, { method: 'GET', headers })
286    if (reply.status === 304) {
287      this.freshAt = await this.io.now()
288      this.succeeded()
289      return 'unchanged'
290    }
291    if (reply.status === 401 && retryOn401) {
292      this.ctx.forgetApi()
293      return this.fetchOnce(false)
294    }
295    if (reply.status === 426) {
296      await this.upgradeRequired(reply.text)
297      return 'upgrade'
298    }
299    if (reply.status !== 200) throw new Error(`rules fetch HTTP ${reply.status}`)
300    const rules = rulesOf(reply.text)
301    if (!rules) throw new Error('rules fetch: unexpected reply shape')
302    const etag = reply.headers['etag']
303    const now = await this.io.now()
304    const file: BookFile = { etag: etag ?? null, fetched_at: isoOf(now), rules }
305    // The engine first: what the mod serves must never lag the file Python reads.
306    await this.hand(rules)
307    this.etag = etag
308    this.freshAt = now
309    await this.io.writeFile(this.path!, JSON.stringify(file))
310    this.succeeded()
311    return 'updated'
312  }
313
314  private async hand(rows: readonly unknown[]): Promise<void> {
315    const rules = shapeRules(rows, this.opts.toHook ?? hookRuleFor(this.opts.hookVersion))
316    this.engine.setBook(rules, { repo: this.repo!, fetchedAt: await this.io.now() })
317    this.opts.onRules?.(this.repo!, rules.length)
318  }
319
320  /**
321   * The server refuses this plugin version: cached rules are suspended. The
322   * mod stops serving every lane, and Python's own fetch records the upgrade
323   * notice beside the book (`<book>.upgrade`), which is what makes the Python
324   * lanes suspend the cached rules and tell the agent.
325   */
326  private async upgradeRequired(body: string): Promise<void> {
327    this.stop()
328    let minimum: string | undefined
329    try {
330      const p = JSON.parse(body) as { data?: { minimum_version?: unknown } }
331      if (typeof p?.data?.minimum_version === 'string' && /^\d{1,6}\.\d{1,6}\.\d{1,6}$/.test(p.data.minimum_version)) {
332        minimum = p.data.minimum_version
333      }
334    } catch {
335      // the status line says it without the number
336    }
337    this.status.set(
338      'upgrade',
339      `MemHub: update the plugin${minimum ? ` (minimum ${minimum})` : ''} — team rules are paused`,
340    )
341    await this.claims.release()
342    await this.io
343      .run(['python3', `${this.ctx.root}/scripts/rulebook_hook.py`, 'fetch', this.repo!], { timeoutMs: 15_000 })
344      .catch(() => undefined)
345  }
346
347  private succeeded(): void {
348    this.failures = 0
349    this.status.set('refresh', undefined)
350  }
351
352  /**
353   * A refresh failed. A refusal (the org's web-fetch policy, a hook's deny)
354   * gives every lane back to Python at once: the mod would serve a stale book
355   * forever and the judge fails the same way, while Python's own fetch is not
356   * subject to that policy. A network blip is retried; after
357   * RELEASE_AFTER_FAILURES in a row with a book older than Python's staleness
358   * window, the lanes go back to Python too.
359   */
360  private async failed(err: unknown): Promise<void> {
361    if (isFetchRefused(err)) return this.giveUp(FETCH_REFUSED)
362    this.failures += 1
363    if (this.failures >= RELEASE_AFTER_FAILURES) {
364      const age = this.freshAt === undefined ? Infinity : (await this.io.now()) - this.freshAt
365      if (age > PYTHON_REFRESH_AFTER_MS) return this.giveUp(REFRESH_GAVE_UP)
366    }
367    if (this.failures >= REFRESH_FAILURES_SHOWN) {
368      const why = err instanceof Error ? err.message : String(err)
369      this.status.set('refresh', `MemHub: team rules not refreshed — ${why}`.slice(0, 200))
370    }
371  }
372
373  /** Stop refreshing and release every lane for the session, saying why on the status line. */
374  private async giveUp(why: string): Promise<void> {
375    this.stop()
376    this.status.set('refresh', undefined)
377    this.status.set('claims', why)
378    await this.claims.release().catch(() => undefined)
379  }
380}
381
382/** `{"code":0,"msg":"ok","data":{"rules":[…]}}` or the bare `{"rules":[…]}`; undefined otherwise. */
383function rulesOf(text: string): Record<string, unknown>[] | undefined {
384  try {
385    let p = JSON.parse(text) as Record<string, unknown> | null
386    if (p && typeof p === 'object' && 'code' in p) {
387      if (p.code !== 0) return undefined
388      if ('data' in p) p = p.data as Record<string, unknown> | null
389    }
390    const rules = p && typeof p === 'object' ? (p as { rules?: unknown }).rules : undefined
391    return Array.isArray(rules) ? (rules as Record<string, unknown>[]) : undefined
392  } catch {
393    return undefined
394  }
395}
396
397// ── the remote switch (ENG-1206) ────────────────────────────────────────────
398//
399// `GET /v1/plugin/compatibility` answers `"mod_lanes": true|false`: false
400// tells every mod to leave the Rulebook lanes to the Python command hooks. A
401// missing field means true, so an older backend changes nothing. Mirrors
402// plugin_compatibility.py `check`: the endpoint at the REST base's origin, the
403// bearer, `Accept: application/json` and `X-MemHub-Plugin-Version`
404// (mcp_http.rest + plugin_version.request_headers), the `{code, data}`
405// envelope unwrapped.
406//
407// Read at boot before any lane is claimed, then every SWITCH_MS while lanes
408// are claimed. Each request races COMPAT_TIMEOUT_MS (Python's `timeout=2`;
409// `$.http.fetch` has none of its own). Fail direction: a read that does not
410// answer (network, timeout, 401, a non-200, a refused `$.http.fetch`, an
411// unexpected shape) changes nothing —
412// a blip never flips lanes; a refused fetch is already acted on by the book's
413// own refresh. A false is final for the session: lanes released then are
414// never re-claimed by this module, even if the switch reads true again (a hot
415// reload is a fresh module and reads the switch afresh at its own boot).
416
417export const COMPAT_PATH = '/v1/plugin/compatibility'
418export const SWITCH_MS = 5 * 60_000
419/** plugin_compatibility.check's `timeout=2`. */
420export const COMPAT_TIMEOUT_MS = 2_000
421export const SWITCHED_OFF = 'MemHub rules: served by the command hooks (remote switch)'
422
423/** on: the mod may serve (true, or the field absent); off: give every lane to Python; unknown: keep the current state. */
424export type SwitchRead = 'on' | 'off' | 'unknown'
425
426/** `scheme://netloc` of a URL, as plugin_compatibility.py builds the endpoint; undefined when unparseable. */
427export function originOf(url: string): string | undefined {
428  const m = /^([a-z][a-z0-9+.-]*:\/\/[^/?#]+)/i.exec(url)
429  return m ? m[1] : undefined
430}
431
432/** The compatibility reply's `mod_lanes`, as a switch read. */
433export function modLanesOf(text: string): SwitchRead {
434  try {
435    let p = JSON.parse(text) as unknown
436    if (p && typeof p === 'object' && !Array.isArray(p) && 'code' in p) {
437      const env = p as { code?: unknown; data?: unknown }
438      if (env.code !== 0) return 'unknown'
439      if ('data' in env) p = env.data
440    }
441    if (!p || typeof p !== 'object' || Array.isArray(p)) return 'unknown'
442    const v = (p as { mod_lanes?: unknown }).mod_lanes
443    if (v === false) return 'off'
444    if (v === true || v === undefined) return 'on'
445    return 'unknown'
446  } catch {
447    return 'unknown'
448  }
449}
450
451export class RemoteSwitch {
452  /** The switch read false this session: lanes are released and stay so. */
453  off = false
454  private timer: { cancel(): void } | undefined
455  private inFlight = false
456
457  constructor(
458    private io: Io,
459    private ctx: Ctx,
460    private claims: Claims,
461    private status: StatusLine,
462    private opts: { hookVersion?: string; onOff?: () => void } = {},
463  ) {}
464
465  /** One read of the switch; never rejects (a failure is 'unknown'). */
466  async read(): Promise<SwitchRead> {
467    try {
468      return await this.readOnce(true)
469    } catch (err) {
470      this.io.debug(`MemHub rules: remote switch not read — ${err instanceof Error ? err.message : String(err)}`)
471      return 'unknown'
472    }
473  }
474
475  /** At boot, before any claim: false when the switch is off (every lane then stays Python's). */
476  async allowsClaim(): Promise<boolean> {
477    if ((await this.read()) !== 'off') return true
478    await this.turnOff()
479    return false
480  }
481
482  /** Re-read every SWITCH_MS while the module lives and the switch is not off (`turnOff` cancels the timer). */
483  start(): void {
484    if (this.timer || this.off) return
485    this.timer = this.io.every(SWITCH_MS, () => {
486      void this.poll()
487    })
488  }
489
490  /**
491   * One read: an off releases every lane for the session; on or unknown
492   * changes nothing — in particular an on after an off claims nothing back.
493   * Overlapping reads are skipped; a hung one is bounded by COMPAT_TIMEOUT_MS,
494   * so the next tick reads again.
495   */
496  async poll(): Promise<void> {
497    if (this.inFlight) return
498    this.inFlight = true
499    try {
500      if ((await this.read()) === 'off') await this.turnOff()
501    } finally {
502      this.inFlight = false
503    }
504  }
505
506  private async readOnce(retryOn401: boolean): Promise<SwitchRead> {
507    const api = await this.ctx.api()
508    if (!api) return 'unknown'
509    if (!isSecure(api.base)) throw new Error('refusing to send credentials over cleartext')
510    const origin = originOf(api.base)
511    if (!origin) throw new Error('no origin in the API base')
512    // Always sent, as mcp_http.rest does: plugin_version.py says 'unknown'
513    // when the manifest has no readable x.y.z, and so does this.
514    const headers: Record<string, string> = {
515      Authorization: `Bearer ${api.bearer}`,
516      Accept: 'application/json',
517      'X-MemHub-Plugin-Version': this.opts.hookVersion ?? 'unknown',
518    }
519    const timedOut = this.io.sleep(COMPAT_TIMEOUT_MS).then(() => {
520      throw new Error(`compatibility: no answer in ${COMPAT_TIMEOUT_MS} ms`)
521    })
522    const reply = await Promise.race([this.io.fetch(`${origin}${COMPAT_PATH}`, { method: 'GET', headers }), timedOut])
523    if (reply.status === 401 && retryOn401) {
524      this.ctx.forgetApi()
525      return this.readOnce(false)
526    }
527    if (reply.status !== 200) throw new Error(`compatibility HTTP ${reply.status}`)
528    return modLanesOf(reply.text)
529  }
530
531  /** Release every lane for the rest of the session and say so; the renewal and recovery paths never bring one back (claims.ts `lost`). */
532  private async turnOff(): Promise<void> {
533    if (this.off) return
534    this.off = true
535    this.timer?.cancel()
536    this.timer = undefined
537    this.status.set('claims', SWITCHED_OFF)
538    this.opts.onOff?.()
539    // A failed write already serves nothing and tries to unset the variable
540    // (claims.ts `writeFailed`); the variable's lease lapses within LEASE_S
541    // if even that failed. Said in the debug log, never on screen.
542    await this.claims.release().catch(err => {
543      this.io.debug(`MemHub rules: remote switch release failed — ${err instanceof Error ? err.message : String(err)}`)
544    })
545  }
546}
547
mod/claims.ts 341 lines
1// Lane claims (spec §3.3, D2): which Rulebook lanes the mod serves, told to
2// the Python hooks through ONE env var per environment —
3// `MEMHUB_MOD_LANES_STAGING` / `MEMHUB_MOD_LANES_PROD` =
4// "<session_id>:<expires_epoch_s>:<pid>:pre,post,prompt,session".
5// `hooks/hook_entry.py` (scripts/mod_lanes.py) skips a lane its own
6// environment's variable lists ONLY while the lease is live, the pid is its
7// own `CLAUDE_PID` (where both are known), and the stamp is its payload's
8// `session_id` (or the payload is a call served here for another session).
9//
10// A claim must never outlive or escape the module that made it, or a gate is
11// lost: nothing evaluates it.
12//   * Escape: the variable is inherited by every child process. A `claude`
13//     started from a Bash call or a skill sees it, and if that child's mod did
14//     not load (allowManagedModsOnly, --safe-mode, disableAllHooks, an older
15//     build, a load error), an inherited claim would leave nothing evaluating
16//     the rules. The child's hooks carry its own pid and session id. Subagent
17//     calls carry the parent's session id, so they stay ours. A /clear or
18//     resume changes the id without a session.start: `restamp()` (at the next
19//     prompt) writes the new one; in between Python serves.
20//   * Outlive: `$.env` writes go straight to the process environment and the
21//     engine does not undo them when the module crashes, fails a hot reload
22//     or unloads. So the claim is a LEASE: every write sets the expiry to now
23//     + LEASE_S, and a `$.clock.every` timer renews it every RENEW_MS. Timers
24//     die with the module, so a dead module's claim lapses by itself within
25//     LEASE_S and Python serves.
26//
27// The invariant this file exists for: a gate is never lost. It is doubled
28// (the mod and Python both evaluate one call) only in two brief overlaps,
29// accepted because the alternative is a gap:
30//   * the lease hand-back: the mod serves up to LEASE_LATE_MS past its own
31//     lease, while Python already serves the lapsed lane;
32//   * parallel calls: a call that passed `has(lane)` before another call's
33//     failure took the lane out of the variable is evaluated by the mod, and
34//     by the Python hook at its `next`, which now sees the lane unclaimed.
35// Its parts:
36//   * Claim late: a lane is listed only once the mod can serve it (book loaded).
37//   * A lane the variable does not list is served by Python alone: every lane
38//     hook asks `has(lane)` before it evaluates anything (lanes.ts).
39//   * A write that fails leaves the variable as it was, still listing lanes
40//     the module may have dropped: the module stops serving at once (no live
41//     lease) and tries to unset the variable, so Python serves; if even that
42//     fails, the variable's own lease lapses within LEASE_S.
43//   * Release on failure: a failing pre/prompt lane takes itself out of the
44//     variable BEFORE it calls `next(e)`, so the Python hook beneath (which the
45//     engine starts at the last mod's `next`, spec §1.2) serves that very call.
46//     The first failure is forgiven once the call settles (`recover`); the
47//     second, or any failure at load, releases the lane for the session and
48//     says so on the status line.
49//   * The fail→recover window: `recover` runs only after that call's `next`
50//     settles, so the lane stays paused for the whole of `next` (for a long
51//     Bash call, minutes). Every call that starts in the window finds the
52//     lane unclaimed and is evaluated by Python's hook alone: single
53//     evaluation, never a gap, but the mod serves nothing on that lane
54//     meanwhile. (The paused lane is pre or prompt; a claimed post lane keeps
55//     running in the mod for those calls, and Python's post hook skips it.)
56//
57// Module memory holds the truth; `$.state` `lanes` mirrors it for the
58// companion and for a hot reload (which re-claims at its own session.start).
59
60import type { LaneName } from '../types'
61import type { Env, Io } from './ctx'
62
63export const LANES: readonly LaneName[] = ['pre', 'post', 'prompt', 'session']
64export const FELL_BACK = 'MemHub rules: fell back to the command hooks'
65/** Failures a lane survives in a session; the next one releases it. */
66const MAX_FAILURES = 2
67
68/**
69 * The lease. Renewed every 30 s, valid for 90 s: a live module renews twice
70 * before its lease could lapse, so one late or refused tick (a busy event
71 * loop, a slow `$.env` write) never hands a lane to Python while the mod still
72 * serves it; a dead module's claim lapses within 90 s, which bounds how long
73 * gates can go unevaluated after a crash, a failed reload or an unload. A
74 * shorter lease buys a shorter gap at the price of a renewal (two `$` calls)
75 * more often; 90 s is under two of the book's 60 s refresh periods.
76 */
77export const LEASE_S = 90
78export const RENEW_MS = 30_000
79/**
80 * How long past its own lease the mod keeps serving. Python checks the lease
81 * after the mod has evaluated pre and prompt (its hook runs at the mod's
82 * `next`), but before the mod evaluates post; serving a little past the
83 * expiry makes the hand-back an overlap (both evaluate) and never a gap.
84 */
85export const LEASE_LATE_MS = 30_000
86
87/**
88 * This plugin's one status line (`$.ui.status` is one per plugin), shared by
89 * the parts that want it. The most important message shows: an upgrade notice
90 * over a fallback over a lane's health line over a stale book.
91 */
92export class StatusLine {
93  private slots: { upgrade?: string; claims?: string; health?: string; refresh?: string } = {}
94  private shown: string | undefined
95  constructor(private io: Io) {}
96  set(slot: 'upgrade' | 'claims' | 'health' | 'refresh', text: string | undefined) {
97    this.slots[slot] = text
98    const next = this.slots.upgrade ?? this.slots.claims ?? this.slots.health ?? this.slots.refresh
99    if (next === this.shown) return
100    this.shown = next
101    this.io.status(next)
102  }
103}
104
105export class Claims {
106  private claimed = new Set<LaneName>()
107  /** Released for the rest of the session: never re-claimed. */
108  private lost = new Set<LaneName>()
109  private failures = new Map<LaneName, number>()
110  /** Released for one in-flight call after a first failure. */
111  private paused = new Set<LaneName>()
112  private writes: Promise<void> = Promise.resolve()
113  /** The session id the variable was last stamped with. */
114  private stampedFor: string | undefined
115  /** Epoch ms the variable's lease runs to (0: no live lease). */
116  private leaseUntil = 0
117  private renewal: { cancel(): void } | undefined
118  private pid: Promise<string> | undefined
119
120  /**
121   * `clock` is epoch ms, read synchronously so `has()` stays synchronous; it
122   * is `Date.now`, which reads what `$.clock.now()` and Python's
123   * `time.time()` read (verified on Claude Code 2.1.292: equal).
124   */
125  constructor(
126    private io: Io,
127    private env: Env,
128    private status: StatusLine,
129    private clock: () => number = () => Date.now(),
130  ) {}
131
132  /** The mod serves `lane`: claimed, and its lease (written to the variable) not long lapsed. */
133  has(lane: LaneName): boolean {
134    return this.claimed.has(lane) && this.clock() < this.leaseUntil + LEASE_LATE_MS
135  }
136
137  list(): LaneName[] {
138    return LANES.filter(l => this.claimed.has(l))
139  }
140
141  /**
142   * A fresh process (nothing in `$.state` yet) must not trust a variable it
143   * did not write: a `claude` started from a Bash call inherits its parent's.
144   * Cleared before anything else runs, so Python serves until we claim.
145   */
146  async forgetInherited(): Promise<void> {
147    if ((await this.io.getLanesVar(this.env)) !== undefined) await this.io.setLanesVar(this.env, undefined)
148  }
149
150  /** Add lanes the mod is now ready to serve. A lane released for the session stays released. */
151  async claim(lanes: readonly LaneName[]): Promise<void> {
152    const added = lanes.filter(l => !this.lost.has(l) && !this.claimed.has(l))
153    for (const l of added) this.claimed.add(l)
154    try {
155      await this.write()
156    } catch (err) {
157      // The variable may not list them: serving them here too would double-fire.
158      for (const l of added) this.claimed.delete(l)
159      throw err
160    }
161  }
162
163  /** Give lanes back to Python for the rest of the session. */
164  async release(lanes: readonly LaneName[] = LANES): Promise<void> {
165    for (const l of lanes) {
166      this.claimed.delete(l)
167      this.lost.add(l)
168    }
169    await this.write()
170  }
171
172  /** A failure while the mod was loading: nothing is (or stays) claimed, and the person is told. */
173  async failLoad(): Promise<void> {
174    await this.release(LANES)
175    this.status.set('claims', FELL_BACK)
176  }
177
178  /**
179   * A lane hook failed. The lane leaves the variable at once (so the Python
180   * hook serves this call if it has not run yet); on the second failure it
181   * stays out for the session.
182   */
183  async fail(lane: LaneName): Promise<void> {
184    // A lane paused by a failure still in flight counts too (parallel calls).
185    if (!this.claimed.has(lane) && !this.paused.has(lane)) return
186    const n = (this.failures.get(lane) ?? 0) + 1
187    this.failures.set(lane, n)
188    this.claimed.delete(lane)
189    if (n >= MAX_FAILURES) {
190      this.lost.add(lane)
191      this.paused.delete(lane)
192      this.status.set('claims', FELL_BACK)
193    } else {
194      this.paused.add(lane)
195    }
196    await this.write()
197  }
198
199  /**
200   * The session id changed in this process (a /clear or a resume: no
201   * session.start fires) — stamp the claim with the new one. Resolves true
202   * when the id differs from the stamp the variable carried, i.e. Python
203   * served the new session until now (its SessionStart included).
204   */
205  async restamp(): Promise<boolean> {
206    if (this.stampedFor === undefined) return false
207    const sid = await this.io.sessionId()
208    if (sid === this.stampedFor) return false
209    if (this.claimed.size) await this.write()
210    else this.stampedFor = sid
211    return true
212  }
213
214  /**
215   * The renewal tick: push the lease out for the lanes still claimed. A
216   * released, lost or paused lane is not in `claimed`, so a renewal never
217   * brings one back; nothing claimed writes nothing.
218   */
219  async renew(): Promise<void> {
220    if (!this.claimed.size) return
221    await this.write()
222  }
223
224  /**
225   * Hand ONE call to Python without counting a failure — a call the mod's
226   * book does not cover (another repo's checkout). The lanes leave the
227   * variable, so the Python hooks beneath serve the call, until `recover`
228   * takes each back. Resolves the lanes actually yielded.
229   */
230  async yieldCall(lanes: readonly LaneName[]): Promise<LaneName[]> {
231    const took = lanes.filter(l => this.claimed.has(l))
232    if (!took.length) return took
233    for (const l of took) {
234      this.claimed.delete(l)
235      this.paused.add(l)
236    }
237    await this.write()
238    return took
239  }
240
241  /** After the call a first failure handed to Python: take the lane back. */
242  async recover(lane: LaneName): Promise<void> {
243    if (!this.paused.delete(lane) || this.lost.has(lane)) return
244    this.claimed.add(lane)
245    await this.write()
246  }
247
248  /**
249   * The variable and the mirror, written in order (one write at a time). The
250   * value is `<session_id>:<expires_epoch_s>:<pid>:<lanes>`, the id and the
251   * clock read at write time; no lanes unsets it. A claim that cannot be
252   * stamped is not made: with no session id every lane goes back to Python
253   * (the variable unset) and the write rejects.
254   */
255  private write(): Promise<void> {
256    this.writes = this.writes
257      .catch(() => undefined)
258      .then(() => this.writeOnce().catch(err => this.writeFailed(err)))
259    return this.writes
260  }
261
262  /**
263   * A write rejected: the variable may still hold its previous value, listing
264   * a lane this module has dropped (a `fail`, a `release`) and so leaving that
265   * lane evaluated by nobody. Serve nothing (no live lease: `has()` is false
266   * for every lane) and try to unset the variable, so Python serves every
267   * lane; if the unset fails too, the variable's own lease lapses within
268   * LEASE_S. The next renewal (or claim) writes the claim afresh. Rejects with
269   * the write's error.
270   */
271  private async writeFailed(err: unknown): Promise<never> {
272    this.leaseUntil = 0
273    const unset = await this.io.setLanesVar(this.env, undefined).then(() => true, () => false)
274    if (unset) await this.io.setState('lanes', []).catch(() => undefined)
275    throw err
276  }
277
278  private async writeOnce(): Promise<void> {
279    let lanes = this.list()
280    let value: string | undefined
281    if (lanes.length) {
282      const sid = await this.io.sessionId().catch(() => undefined)
283      if (!sid) {
284        this.claimed.clear()
285        this.leaseUntil = 0
286        await this.io.setLanesVar(this.env, undefined)
287        lanes = []
288        await this.io.setState('lanes', lanes).catch(() => undefined)
289        throw new Error('no session id to stamp the claim with')
290      }
291      const pid = await this.ownPid()
292      // Re-read after the awaits: a release that landed meanwhile wins.
293      lanes = this.list()
294      if (lanes.length) {
295        const expires = Math.floor(this.clock() / 1000) + LEASE_S
296        this.stampedFor = sid
297        value = stampOf(sid, expires, pid, lanes)
298        await this.io.setLanesVar(this.env, value)
299        this.leaseUntil = expires * 1000
300        this.renewing()
301      }
302    }
303    if (value === undefined) {
304      this.leaseUntil = 0
305      await this.io.setLanesVar(this.env, undefined)
306    }
307    // The mirror is for display; a failed mirror must not undo a claim.
308    await this.io.setState('lanes', lanes).catch(() => undefined)
309  }
310
311  /** Start the renewal timer once. It dies with the module, which is what lets a dead module's lease lapse. */
312  private renewing(): void {
313    if (this.renewal) return
314    this.renewal = this.io.every(RENEW_MS, () => {
315      void this.renew().catch(() => undefined)
316    })
317  }
318
319  /**
320   * This Claude Code process's pid, which its hook commands see as
321   * `CLAUDE_PID`: the parent of a shell `$.process.run` starts (verified on
322   * 2.1.292; `$.env.get('CLAUDE_PID')` would read an ANCESTOR's, inherited).
323   * '' when it cannot be had (no /bin/sh): Python then matches on the session.
324   */
325  private ownPid(): Promise<string> {
326    this.pid ??= this.io
327      .run(['/bin/sh', '-c', 'echo $PPID'], { timeoutMs: 5_000 })
328      .then(r => {
329        const out = r.stdout.trim()
330        return r.exitCode === 0 && /^\d{1,10}$/.test(out) ? out : ''
331      })
332      .catch(() => '')
333    return this.pid
334  }
335}
336
337/** The variable's value (mod_lanes.py `lanes_for` reads it). */
338export function stampOf(sid: string, expiresEpochS: number, pid: string, lanes: readonly LaneName[]): string {
339  return `${sid}:${expiresEpochS}:${pid}:${lanes.join(',')}`
340}
341
mod/ctx.ts 227 lines
1// What every part of the mod shares, resolved once per session at
2// `session.start` by mod/register.ts.
3//
4// Two things live here:
5//   * `Ctx`: the environment (staging | prod), the plugin root and the REST
6//     credential, cached in module memory.
7//   * `Io`: the narrow port every part of the shell (claims, book, act,
8//     lanes) does its I/O through. register.ts builds it from `$` (`ioOf`,
9//     which must live there: the engine follows `$` only into functions of
10//     the file that holds it); the tests build a fake one. Nothing but
11//     register.ts touches `$`, so each part is testable without the engine
12//     beneath it.
13
14import type { FireNote, LaneName } from '../types'
15
16export type Env = 'staging' | 'prod'
17
18export type Api = {
19  base: string
20  bearer: string
21  /**
22   * The MemHub Studio web app paired with `base` (api-info's `studio`:
23   * plugin_onboarding._ORIGINS), or absent for an API with none. The mod
24   * links a rule's Studio page from it and keeps no host table of its own.
25   */
26  studio?: string
27}
28
29/**
30 * What the last credential lookup said: 'in' with a credential, 'out' when
31 * api-info answered signed out, 'unknown' when it could not answer at all
32 * (no python3, a broken install): never taken for a signed-out person.
33 */
34export type SignIn = 'in' | 'out' | 'unknown'
35
36export type Ctx = {
37  /** 'staging' for memhub-staging, 'prod' for memhub (promote_export.py changes the name). */
38  env: Env
39  /** The plugin's install directory (`$.plugin.root`, without a trailing `/.claude-plugin`). */
40  root: string
41  /**
42   * The REST base, bearer and Studio origin, from `python3 scripts/rulebook_mod_cli.py
43   * api-info --env <env>`; cached in module memory only (never $.state /
44   * $.store: it is a secret). undefined when signed out.
45   */
46  api(): Promise<Api | undefined>
47  /** Drop the cached credential (after a 401) so the next api() re-resolves. */
48  forgetApi(): void
49  /**
50   * Whether MemHub is active in the session's repository: false when the
51   * machine's repository allowlist (`~/.config/memhub-plugin/repos.json`,
52   * scripts/repo_allow.py) leaves it out, which `rulebook_mod_cli.py paths`
53   * answers as `enabled`. The shell settles it at boot (register.ts) once it
54   * has asked; true where nothing could ask. The companion stays hidden in
55   * a repository MemHub is inactive in, as the Python lanes stay silent there.
56   * Resolves to the LATEST answer: the strip's Yes (ENG-1253) lists the
57   * repository mid-session and sets it again.
58   */
59  active(): Promise<Active>
60  /**
61   * The shell's answer (register.ts `boot`), and later the strip's: the
62   * first call settles anyone waiting, each call is what `active()` says next.
63   */
64  setActive(value: Active): void
65  /** The book the shell holds for the session's repository, once loaded (the companion's status strip reads it). */
66  book(): BookInfo | undefined
67  setBook(info: BookInfo): void
68  /** What the last api() lookup said of the sign-in (see SignIn); 'unknown' before any. */
69  signIn(): SignIn
70}
71
72/** What the status strip says of the book: the repository and how many rules the mod holds for it. */
73export type BookInfo = { repo: string; rules: number }
74
75/**
76 * The allowlist's answer for the session: `enabled` false where MemHub is
77 * dormant, and `repo` the session's repository name — '' outside any checkout,
78 * which with a repos.json is dormant too (there is no repository to list).
79 * The rest is what the strip's enable ask (ENG-1253) needs, all from `paths`
80 * so nothing re-reads repos.json in TypeScript: `restricted`, a repos.json
81 * exists; `declined`, the person answered No to this repository before;
82 * `identity`, the checkout's name as the list carries it (`org/name`).
83 * Each is optional: a shell that could not ask leaves them out, and the ask
84 * then never shows.
85 */
86export type Active = { enabled: boolean; repo: string; restricted?: boolean; declined?: boolean; identity?: string }
87export const ACTIVE: Active = { enabled: true, repo: '' }
88
89/** The keys of this plugin's `$.state` contract (types/index.d.ts) the shell writes. */
90export type StateShape = {
91  fires: FireNote[]
92  lanes: LaneName[]
93  health: string
94}
95
96export type RunResult = { exitCode: number; stdout: string; stderr: string }
97export type HttpReply = { status: number; ok: boolean; headers: Record<string, string>; text: string }
98
99/** Every effect the shell has, as one port. */
100export interface Io {
101  pluginName: string
102  root: string
103  now(): Promise<number>
104  sessionId(): Promise<string>
105  cwd(): Promise<string>
106  run(argv: readonly string[], init?: { stdin?: string; timeoutMs?: number; cwd?: string }): Promise<RunResult>
107  fetch(url: string, init?: { method?: string; headers?: Record<string, string>; body?: string }): Promise<HttpReply>
108  /** Rejects when the file is missing or unreadable. */
109  readFile(path: string): Promise<string>
110  writeFile(path: string, text: string): Promise<void>
111  /** `MEMHUB_MOD_LANES_<ENV>`: written only by claims.ts. */
112  getLanesVar(env: Env): Promise<string | undefined>
113  setLanesVar(env: Env, value: string | undefined): Promise<void>
114  getState<K extends keyof StateShape>(key: K): Promise<{ value: StateShape[K] | undefined; version: number }>
115  setState<K extends keyof StateShape>(key: K, value: StateShape[K]): Promise<void>
116  status(text: string | undefined): void
117  /** A dim transcript line for the person (the model never reads it). */
118  log(text: string): void
119  /** A debug-log line only (`$.ui.log(text, { to: 'debug' })`): never on screen. */
120  debug(text: string): void
121  /** `$.session.append`: `user` = an isMeta row the model reads; `system` = a notice it never reads. */
122  append(type: 'user' | 'system', text: string): Promise<void>
123  every(ms: number, fn: () => void): { cancel(): void }
124  /** `$.clock.sleep`: the mod has no setTimeout; what a request races to bound itself. */
125  sleep(ms: number): Promise<void>
126}
127
128/** memhub-staging → staging, memhub → prod; any other name is not ours to guess. */
129export function envOf(pluginName: string): Env | undefined {
130  if (pluginName === 'memhub-staging') return 'staging'
131  if (pluginName === 'memhub') return 'prod'
132  return undefined
133}
134
135/** The last non-empty stdout line as JSON, or undefined. Scripts may print progress first. */
136export function lastJson(stdout: string): unknown {
137  const lines = stdout.split('\n').map(l => l.trim()).filter(Boolean)
138  const last = lines.at(-1)
139  if (last === undefined) return undefined
140  try {
141    return JSON.parse(last)
142  } catch {
143    return undefined
144  }
145}
146
147/**
148 * The scope label of a REST rule row's rulebook ("Everyone in Acme", "Just
149 * you"): who the rule applies to. '' for a backend that sends none.
150 */
151export function audienceOf(row: Record<string, unknown>): string {
152  const book = row.rulebook
153  const label = book && typeof book === 'object' ? (book as { label?: unknown }).label : undefined
154  // one line, bounded: it is drawn on the band
155  // eslint-disable-next-line no-control-regex
156  return typeof label === 'string' ? label.replace(/[\x00-\x1f\x7f]+/g, ' ').trim().slice(0, 120) : ''
157}
158
159export const MOD_CLI = 'scripts/rulebook_mod_cli.py'
160
161export function makeCtx(io: Io, env: Env): Ctx {
162  // The resolved credential, kept for the session. A signed-out or failed
163  // answer is not kept: a person who runs /memhub:login mid-session is picked
164  // up on the next refresh tick (only the tick and the judge ask).
165  let said: SignIn = 'unknown'
166  // what a lookup said is kept only while it is the lookup in `cached`: one
167  // overtaken by a forgetApi() and a newer lookup must not overwrite its answer
168  const resolve = async (): Promise<{ api?: Api; said: SignIn }> => {
169    const r = await io.run(['python3', `${io.root}/${MOD_CLI}`, 'api-info', '--env', env], { timeoutMs: 10_000 })
170    if (r.exitCode !== 0) throw new Error(`api-info exited ${r.exitCode}: ${r.stderr.slice(0, 200)}`)
171    const got = lastJson(r.stdout) as Partial<Api> | undefined
172    if (got && typeof got.base === 'string' && got.base && typeof got.bearer === 'string' && got.bearer) {
173      const studio = typeof got.studio === 'string' ? got.studio.replace(/\/+$/, '') : ''
174      return { api: { base: got.base.replace(/\/+$/, ''), bearer: got.bearer, ...(studio ? { studio } : {}) }, said: 'in' }
175    }
176    // `{}` is api-info's signed out; anything else on stdout is not an answer
177    return { said: got && typeof got === 'object' && Object.keys(got).length === 0 ? 'out' : 'unknown' }
178  }
179  let cached: Promise<{ api?: Api; said: SignIn }> | undefined
180  const api = async (): Promise<Api | undefined> => {
181    if (!cached) cached = resolve()
182    const mine = cached
183    try {
184      const got = await mine
185      if (cached === mine) {
186        said = got.said
187        if (!got.api) cached = undefined
188      }
189      return got.api
190    } catch {
191      if (cached === mine) {
192        said = 'unknown'
193        cached = undefined
194      }
195      return undefined
196    }
197  }
198  let settleActive: (value: Active) => void = () => undefined
199  const firstActive = new Promise<Active>(r => {
200    settleActive = r
201  })
202  // the latest answer, once there is one: the first waits on the shell's boot
203  let current: Active | undefined
204  let bookInfo: BookInfo | undefined
205  return {
206    env,
207    root: io.root,
208    active: () => (current ? Promise.resolve(current) : firstActive),
209    setActive(value) {
210      current = value
211      settleActive(value)
212    },
213    book: () => bookInfo,
214    setBook(info) {
215      bookInfo = info
216    },
217    api,
218    forgetApi() {
219      cached = undefined
220    },
221    signIn: () => said,
222  }
223}
224
225/** `$.plugin.root` names the folder holding plugin.json; the scripts sit beside `.claude-plugin/`. */
226export const rootOf = (pluginRoot: string) => pluginRoot.replace(/\/\.claude-plugin\/?$/, '')
227
mod/engine/index.ts 155 lines
1// The Rulebook engine the mod's lanes call: a TypeScript port of the parts of
2// scripts/rulebook_hook.py that decide what fires. Python stays the engine on
3// Codex, Cursor and wherever the mod does not load; the golden vectors
4// (scripts/rule_vectors.py, generated into ./tests/vectors/ by
5// scripts/test-mod.sh for each test run) hold the port to its answers.
6//
7// The engine decides; the mod acts (mod/act.ts): it denies, adds context,
8// writes the disclosure row, asks, and feeds the companion. Nothing in
9// ./engine touches `$` — I/O comes in through EngineIO, so every layer is a
10// pure function a vector can replay.
11
12/** A rule in the flat shape `to_hook_rule()` returns (rules.ts). */
13export type HookRule = {
14  id: string
15  on: string
16  mode?: string
17  text?: string
18  why?: string
19  _label?: string | null
20  [k: string]: unknown
21}
22
23/** One tool call as the lanes see it. */
24export type CallEvent = {
25  phase: 'pre' | 'post'
26  tool: string
27  input: Readonly<Record<string, unknown>>
28  sessionId: string
29  cwd: string
30  /** Set when a subagent made the call (replaces the /subagents/ path test). */
31  agentId?: string
32  /** The call's tool_use id: pairs a Bash call's pre with its post (parallel calls). */
33  toolUseId?: string
34  /** Post phase only. */
35  result?: { text?: string; isError?: boolean }
36}
37
38/** One rule that fired on this event. */
39export type Fire = {
40  ruleId: string
41  label: string
42  /** `disclosure_line(rule, blocked)`, byte-identical to Python. */
43  line: string
44  mode: 'advise' | 'gate'
45  text: string
46}
47
48export type Verdict = {
49  /** Set when a gate refuses the call: the reason the model reads. */
50  deny?: string
51  /** Text the model reads after the result (advisories, post-lane notes). */
52  context: string[]
53  fires: Fire[]
54  /** Fire/event rows for the Python ledger (`rulebook_mod_cli.py log`). */
55  ledger: Record<string, unknown>[]
56}
57
58/** One file-system entry as `$.fs.stat` answers it. */
59export type FileStat = { kind: 'file' | 'dir' | 'other'; size: number; mtimeMs: number; realPath?: string }
60
61/** One message in Messages API form (`$.session.messages({ as: "api" })`). */
62export type TurnMessage = { role: 'user' | 'assistant'; content: readonly Record<string, unknown>[] | string }
63
64/** The environment variables the Python hook reads, as the mod's process has them. */
65export type EngineEnv = {
66  /** MEMHUB_RULEBOOK_RECALL: "0" turns the anchor lane off. */
67  recall?: string
68  /** MEMHUB_RULEBOOK_JUDGE: "0" turns the judge off. */
69  judge?: string
70  /** MEMHUB_RULEBOOK_TIMEOUT_S: the network timeout override. */
71  timeoutS?: string
72  /** MEMHUB_RULEBOOK_BASE_BRANCH: the diff probes' explicit base. */
73  baseBranch?: string
74  /** MEMHUB_BRIEF_TOKEN_BUDGET: the session-start budget the posture rules take a third of. */
75  briefBudget?: string
76}
77
78/** `rulebook_mod_cli.py paths --cwd <dir>`: what the Python hook resolves for a call made there. */
79export type PathsInfo = { repo: string; root: string | null; base: string }
80
81/**
82 * One write to the state the Python hooks share (`scripts/rulebook_mod_state.py`,
83 * which takes their lock): an ordering feed that writes, an arming, a discharge.
84 */
85export type StateOp =
86  | { op: 'feed'; root: string; rule: HookRule; hook_phase: string; tool: string; cmd: string; file_path: string; ok: boolean | null; armed: string | null }
87  | { op: 'arm'; session: string; event: string; prompt: string; rules: HookRule[]; repo: string; gitdir: string }
88  | { op: 'drop'; session: string; rule_ids: string[] }
89  | { op: 'specs'; root: string; spec_dir: string; paths: string[] }
90
91/** The engine's only way out of pure code. */
92export interface EngineIO {
93  /** `git <argv>` (argv WITHOUT the leading `git`); rejects on a timeout, as Python's `subprocess.run` raises. */
94  git(argv: readonly string[], cwd: string, timeoutMs?: number): Promise<{ code: number; stdout: string }>
95  /** A file's text; undefined when missing, unreadable or past the 4 MiB `$.fs` cap. */
96  readText(path: string): Promise<string | undefined>
97  /** Best effort; never throws. */
98  writeText(path: string, text: string): Promise<void>
99  /** `os.stat` (`resolve`: also the real path); undefined when missing. */
100  stat(path: string, resolve?: boolean): Promise<FileStat | undefined>
101  /** Newline count of a file too big for `readText` (`read_facts`' loop); undefined on failure. */
102  countLines(path: string): Promise<number | undefined>
103  /** Milliseconds since the epoch. */
104  now(): number
105  /** Resolves after `ms` (the judge's own timeout race). */
106  sleep(ms: number): Promise<void>
107  /** The local UTC offset at `ms`, in minutes east (Python's `astimezone()`). */
108  tzOffsetMinutes(ms: number): number
109  /** $HOME, for `~` and the identity redaction. */
110  home: string
111  env(): Promise<EngineEnv>
112  /**
113   * One variable of the environment the Python hook would see (`os.environ`),
114   * for a Bash command's `cd "$WT"` / `> $OUT/f`; undefined when unset. Absent:
115   * no variable but HOME expands, and a path naming one is unknown.
116   */
117  getenv?(name: string): Promise<string | undefined>
118  /** `rulebook_mod_cli.py paths --cwd <dir>`; undefined when it cannot answer. */
119  paths(dir: string): Promise<PathsInfo | undefined>
120  /** One write through `rulebook_mod_state.py`; undefined when the helper failed as a whole. */
121  state(ops: readonly StateOp[], cwd: string): Promise<Record<string, unknown>[] | undefined>
122  /**
123   * POST /judge with `body`: the HTTP status and the unwrapped `data`; undefined
124   * when the call could not be made or completed (no credential, network error,
125   * timeout — the engine adds its own race too), which Python treats as
126   * "nothing judged". A 404 is answered `{ status: 404 }`.
127   */
128  judge(body: Record<string, unknown>): Promise<{ status: number; data?: unknown } | undefined>
129  /**
130   * The conversation the judge reads (`rule_judge_turn.read_turn`'s input),
131   * and an id that is stable for the length of one human turn; undefined when
132   * there is none to read.
133   */
134  turn(): Promise<{ id: string; messages: readonly TurnMessage[] } | undefined>
135}
136
137export interface Engine {
138  /** Replace the book (already shaped by `toHookRule`). */
139  setBook(rules: readonly HookRule[], meta: { repo: string; fetchedAt: number }): void
140  pre(e: CallEvent): Promise<Verdict>
141  post(e: CallEvent): Promise<Verdict>
142  prompt(text: string, sessionId: string, cwd: string): Promise<Verdict>
143  /**
144   * The session lane. `servedAlready`: the posture preamble is already in the
145   * conversation (Python's SessionStart served it at startup, or the module
146   * before a hot reload) — the engine then only arms, and records nothing.
147   * `ledger`: the posture fire rows, for `rulebook_mod_cli.py log`.
148   */
149  session(
150    sessionId: string,
151    cwd: string,
152    opts?: { servedAlready?: boolean },
153  ): Promise<{ context: string[]; ledger?: Record<string, unknown>[] }>
154}
155
mod/engine/engine.ts 1482 lines
1// The Rulebook engine (mods spec §4.1–4.8): a port of rulebook_hook.py
2// `main()`'s lane orchestration — the pre, post, prompt and session lanes —
3// over the layers beside it (rules.ts, shell.ts, ordering.ts, pyre.ts) and
4// EngineIO. scripts/rule_vector_cases/lanes.py runs the REAL Python lanes on
5// recorded hook sequences; ./tests/lanes.test.ts replays them through this
6// engine and fails on any difference. Read main() beside this file: the
7// order of every step below is its order.
8//
9// What the engine keeps, and where:
10//   * the session's dedup state (`fired`, `counts`, `raw`, `spec_pending`,
11//     the judge's per-turn cache, the Bash pre-call stamps) in memory, one
12//     object per session id, seeded ONCE from the Python's
13//     `state/<session>.json` (lockless: Python replaces it atomically) so
14//     whatever Python served before the claim stays deduped;
15//   * the session's ARMINGS (`armed`, `armed_version`, `armed_once`) in that
16//     same file, shared with the Python lanes: re-read at each tool call that
17//     could need them, written only through scripts/rulebook_mod_state.py,
18//     which takes the Python's lock and merges by delta;
19//   * the per-checkout ordering obligations in `state/wt-<worktree_key>.json`:
20//     a gate reads it lockless; an arm (an edit) and a discharge (a green
21//     receipt) go through the same script, under the same lock.
22//
23// Port notes (each a known, accepted difference from the Python):
24//   * `$.session.messages({ as: "api" })` stands in for the transcript file
25//     (given.user, the judge's turn): `isMeta` and compaction-summary rows are
26//     not visible in that form, and `source_message_id` is always null;
27//   * the post lane's result text: for a Bash call it is built from the
28//     tool's own record (`stdout`, `stderr`) exactly as `result_text` builds
29//     it from `tool_response` (lanes.ts `postResultText`), so a large output
30//     Claude Code persisted to a file is matched on the same ~30,000-character
31//     `stdout` Python gets, not the ~2 KB preview the model reads. Still
32//     different: every non-Bash tool, a Bash error result, and a Bash output
33//     with no stdout or stderr read `text` (Python matches the raw
34//     `tool_response` dict, or its `json.dumps`, there);
35//   * no `show_upgrade` (a book suspended by an upgrade notice is never loaded:
36//     book.ts), no `maybe_refresh` / `refresh_if_stale` (book.ts refreshes on a
37//     timer), no `.sources` audit file, no breadcrumbs, no legacy conversions;
38//   * ONE book per session: a call whose checkout belongs to ANOTHER repo
39//     than the loaded book — the file it edits or reads, or where its Bash
40//     command runs (`cd ~/other && …`, `git -C ../x`, `$VAR` expanded:
41//     Repos.ofCall, the port of `repo_of_call`) — throws ForeignRepoError,
42//     and the shell hands BOTH halves of that call to Python (lanes.ts),
43//     which loads that repo's book, rather than judge it against the wrong
44//     rules. A hand-off for a foreign repo is not a failure: it never costs
45//     the session its claim;
46//   * a rule pyre cannot express (`_unportable`) is never skipped: while one
47//     is in the book every tool and prompt lane throws UnportableRuleError,
48//     the shell hands the call to Python and, on the second, releases the
49//     lane for the session (claims.ts) — Python then serves it whole.
50//   * a GATE-mode ordering receipt discharges on a Bash result that is not
51//     an error. Python's `bash_ok(strict=True)` needs an explicit `exit_code`,
52//     and neither Claude Code's PostToolUse payload nor the mod's tool result
53//     carries one, so on Claude Code the Python lane never discharges a gate
54//     (harness/cases/README.md, "A gate-mode receipt never discharges under
55//     Claude Code"). The mod knows `isError` for the call it ran, and Claude
56//     Code sets it for a Bash call that exited non-zero, so the mod reads a
57//     non-error result as exit 0: a deliberate divergence. The lane vectors
58//     pin it: `ordering-gate-receipt-without-exit-code` stays blocked in the
59//     Python and is allowed here (tests/lanes.test.ts, MOD_DIVERGES);
60//   * any other exception is Python's `except BaseException: rc = 0`: the call
61//     gets nothing (no gate, no advice), and this call's state changes are
62//     dropped, as an unsaved Python state file drops them.
63
64import type { CallEvent, Engine, EngineEnv, EngineIO, Fire, HookRule, TurnMessage, Verdict } from './index'
65import { judgeFires, judgeTimeoutMs, unfire, type JudgeState, type Marks } from './judge'
66import { OrderingEngine, armsOn, sessionScoped } from './ordering'
67import {
68  BRAND, dismissalLines, findEditOverride, findOverride, labelOf, namedRules, resolveDismissals,
69  splitNamedOverride, stripOverride,
70} from './override'
71import { givenOk, Probes, pyCompare, type SpecHit } from './probes'
72import { isoMicros, pyExec, pyMatch } from './py'
73import { pySearch } from './pyre'
74import { dirname } from './py'
75import { Repos, sessionFileName, worktreeKey, type RepoInfo } from './repo'
76import {
77  bookRank, cpLen, cpSlice, disclosureLine, EDIT_TOOLS, editAddedText, evaluate, isDict, oneLine, pyStr, pyStrip, READ_TOOLS, truthy,
78} from './rules'
79import {
80  anchorHits, bashDirs, bashReads, bashWriteTargets, basename, join, pathInScope, redactSecrets, relpath, shellOnly, stripComments,
81  varNames, type Env,
82} from './shell'
83
84type Dict = Record<string, unknown>
85
86export const MAX_ADVISE = 2
87export const MAX_POSTURE = 15
88const BASH_EDIT_MAX_FILES = 40
89const BASH_EDIT_MAX_BYTES = 512 * 1024
90const BASH_EDIT_MAX_STATUS = 4000
91const BASH_EDIT_MARKS_KEPT = 8
92const FS_READ_MAX = 4 * 1024 * 1024
93const MAX_BOOKS_NAMED = 6
94const ROSTER_MAX_CHARS = 1000
95const SPEC_LIST_MAX = 3
96const SPEC_OWNED_MAX = 5
97
98const TREE_REWRITE_RX = String.raw`(?:^|[;&|(]\s*)git\s+(?:-C\s+\S+\s+)?(?:checkout|switch|stash|merge|rebase|pull|reset` +
99  String.raw`|cherry-pick|revert|apply|am|restore|worktree)\b`
100const HARNESS_PROMPT_RX = String.raw`\s*(?:<(?:command-name|command-message|command-args|local-command-stdout` +
101  String.raw`|local-command-stderr|local-command-caveat|system-reminder|task-notification)>` +
102  String.raw`|This session is being continued|Caveat: The messages below|Base directory for this skill:` +
103  String.raw`|Another Claude session sent a message:)`
104const AGENT_MESSAGE_RX = String.raw`\s*Another Claude session sent a message:`
105const BASH_RED_RX = String.raw`(^|\n)(FAILED|ERROR)\b|\b\d+ (failed|errors?)\b|\nTraceback \(most recent call last\)` +
106  String.raw`|(^|\n)npm ERR!|(^|\n)error(\[E\d+\])?:`
107
108export const ADVISE_FEEDBACK_HINT =
109  "_If you go on without following one of these, say why on your next shell command — " +
110  "`RULEBOOK_OVERRIDE='[<label>] <why>' <command>` — so the reason is recorded against " +
111  'that rule instead of silence._'
112
113export const SESSION_PREAMBLE =
114  "These are your team's engineering rules — standing instructions from your teammates, " +
115  "carrying the same weight as this repo's CLAUDE.md. Follow them as you would CLAUDE.md: " +
116  'they are how this team works, not suggestions to weigh. When one fires, you MUST disclose ' +
117  'it to the user on its own line, exactly `📏 Rule fired: <the rule, in 20 words or fewer>`, ' +
118  'before anything else in that reply.'
119
120/** A call in a checkout of another repo than the book's: Python serves it. */
121export class ForeignRepoError extends Error {
122  constructor(repo: string, book: string) {
123    super(`call is in ${repo}, the loaded book is ${book}`)
124    this.name = 'ForeignRepoError'
125  }
126}
127
128/** The book holds a rule pyre cannot run: the lane must be Python's. */
129export class UnportableRuleError extends Error {
130  constructor(ids: readonly string[]) {
131    super(`rules not portable to the mod: ${ids.slice(0, 3).join(', ')}`)
132    this.name = 'UnportableRuleError'
133  }
134}
135
136// ── small Python-isms ───────────────────────────────────────────────────────
137
138const has = (o: object, k: string) => Object.prototype.hasOwnProperty.call(o, k)
139/** `r.get("status", "active") == "active"` */
140const isActive = (r: HookRule) => (has(r, 'status') ? r.status : 'active') === 'active'
141/** `d.get(k, dflt)` */
142const getOr = (d: Dict, k: string, dflt: unknown): unknown => (has(d, k) ? d[k] ?? null : dflt)
143/** `str(v)` of a payload value read with `.get(k, "")`. */
144const strOf = (d: Dict, k: string): string => pyStr(getOr(d, k, ''))
145const casefold = (s: string) => s.toLowerCase()
146
147/** `int(x)` as read_facts and the counter scope accept it, else null (Python's except). */
148function pyIntLoose(v: unknown): number | null {
149  if (typeof v === 'boolean') return Number(v)
150  if (typeof v === 'number' && Number.isFinite(v)) return Math.trunc(v)
151  if (typeof v === 'string' && /^\s*[+-]?\d+(_\d+)*\s*$/.test(v)) return Number(v.replace(/_/g, ''))
152  return null
153}
154
155/** `json.dumps(v)` for the string lists the state keys are made of. */
156function pyDumps(v: unknown): string {
157  if (Array.isArray(v)) return '[' + v.map(pyDumps).join(', ') + ']'
158  if (typeof v === 'string') {
159    return JSON.stringify(v).replace(/[\u0080-\uffff]/g, (c) => '\\u' + c.charCodeAt(0).toString(16).padStart(4, '0'))
160  }
161  return JSON.stringify(v ?? null)
162}
163
164/** `scope_ok(rule, repo, gitdir)` */
165export function scopeOk(rule: HookRule, repo: string, gitdir: string): boolean {
166  const scope = has(rule, 'repo_scope') ? rule.repo_scope : 'any'
167  const repos = rule._scope_repos
168  if (truthy(repos)) {
169    const parts = gitdir ? gitdir.split('/') : []
170    const i = parts.indexOf('.git')
171    const main = i > 0 ? parts[i - 1]! : ''
172    const here = new Set([casefold(repo), casefold(main)].filter(Boolean))
173    return (repos as unknown[]).some((s) => here.has(casefold(pyStr(s))))
174  }
175  if (scope === 'any') return true
176  if (typeof scope !== 'string') throw new TypeError("'in <string>' requires string as left operand")
177  return repo.includes(scope) || (!!gitdir && gitdir.includes(`/${scope}/`))
178}
179
180/** A rule as the shell layer's scope/anchor helpers read it. */
181const sc = (r: HookRule) => r as unknown as { _scope_paths?: unknown; _scope_exclude_paths?: unknown; anchors?: unknown }
182
183/** `harness_prompt(text)` */
184export const harnessPrompt = (text: string): boolean => pyMatch(HARNESS_PROMPT_RX, text || '') !== null
185
186/** `agent_message(text)`: another agent's message — it fires no `prompt` rule. */
187export const agentMessage = (text: string): boolean => pyMatch(AGENT_MESSAGE_RX, text || '') !== null
188
189/** `_why(r)` */
190const why = (r: HookRule) => (truthy(r.why) ? `  _(why: ${pyStr(r.why)})_` : '')
191
192/** `_spec_untouched_text(text, hits)` */
193function specUntouchedText(text: string, hits: readonly SpecHit[]): [string, string] {
194  const shown = hits.slice(0, SPEC_LIST_MAX)
195  const more = hits.length - shown.length
196  let names = shown.map(([p]) => oneLine(p)).join(', ')
197  if (more > 0) names += ` (+${more} more)`
198  if (!names) return [text, '']
199  const owned = shown.map(([p, paths]) => {
200    let head = paths.slice(0, SPEC_OWNED_MAX).map(oneLine).join(', ')
201    if (paths.length > SPEC_OWNED_MAX) head += ` (+${paths.length - SPEC_OWNED_MAX} more)`
202    return `${oneLine(p)} owns ${head}`
203  })
204  const detail = owned.length ? `  _(changed owned paths: ${owned.join('; ')})_` : ''
205  return [`${text.replace(/[\s]+$/u, '')} Specs not updated: ${names}.`, detail]
206}
207
208/**
209 * `bash_ok(resp, strict)` over what the mod sees of a Bash result, which never
210 * carries an exit code. Python's strict (gate-mode receipt) answer without one
211 * is always False; here `isError` stands in for it: Claude Code marks a Bash
212 * call that exited non-zero as an error, so a strict receipt is a Bash result
213 * that is not one (the port note "a gate-mode receipt discharges" above).
214 */
215function bashOk(resp: { text: string; isError?: boolean } | null, strict: boolean): boolean {
216  if (resp === null) return false
217  if (resp.isError) return false
218  if (strict) return true
219  return !pySearch(BASH_RED_RX, resp.text)
220}
221
222const cmpTuple = (a: readonly (number | string)[], b: readonly (number | string)[]): number => {
223  for (let i = 0; i < Math.min(a.length, b.length); i++) {
224    const x = a[i]!
225    const y = b[i]!
226    const d = typeof x === 'number' && typeof y === 'number' ? x - y : pyCompare(String(x), String(y))
227    if (d) return d
228  }
229  return a.length - b.length
230}
231
232// ── session state ───────────────────────────────────────────────────────────
233
234type SessionState = JudgeState & {
235  fired: string[]
236  counts: Record<string, number>
237  raw: Record<string, number>
238  armed: Record<string, unknown>
239  armed_once: string[]
240  armed_version: Record<string, unknown>
241  spec_pending: Record<string, unknown>
242  bash_t0: Map<string, number>
243  /** Per Bash call: [rule id, real path] its pre lane fired on (`bash_pre`). */
244  bash_pre: Map<string, [string, string][]>
245}
246
247function freshState(): SessionState {
248  return {
249    fired: [], counts: {}, raw: {}, armed: {}, armed_once: [], armed_version: {}, spec_pending: {}, bash_t0: new Map(),
250    bash_pre: new Map(),
251  }
252}
253
254/** `load_state`'s defaulting, over a parsed file. */
255function stateFrom(doc: unknown): SessionState {
256  const st = freshState()
257  if (!isDict(doc)) return st
258  const list = (v: unknown) => (Array.isArray(v) ? v.map((x) => x as string) : [])
259  const dict = (v: unknown) => (isDict(v) ? { ...v } : {})
260  st.fired = list(doc.fired)
261  st.counts = dict(doc.counts) as Record<string, number>
262  st.raw = dict(doc.raw) as Record<string, number>
263  st.armed = dict(doc.armed)
264  st.armed_once = list(doc.armed_once)
265  st.armed_version = dict(doc.armed_version)
266  st.spec_pending = dict(doc.spec_pending)
267  if (isDict(doc.judge)) st.judge = doc.judge as SessionState['judge']
268  if (isDict(doc.bash_t0)) {
269    for (const [k, v] of Object.entries(doc.bash_t0)) if (typeof v === 'number') st.bash_t0.set(k, v)
270  }
271  if (isDict(doc.bash_pre)) {
272    for (const [k, v] of Object.entries(doc.bash_pre)) {
273      if (Array.isArray(v)) {
274        st.bash_pre.set(k, v.filter((x): x is [string, string] =>
275          Array.isArray(x) && x.length === 2 && typeof x[0] === 'string' && typeof x[1] === 'string'))
276      }
277    }
278  }
279  return st
280}
281
282const cloneState = (st: SessionState): SessionState => {
283  const c = stateFrom(JSON.parse(JSON.stringify({
284    ...st, bash_t0: Object.fromEntries(st.bash_t0), bash_pre: Object.fromEntries(st.bash_pre),
285  })))
286  if (!st.judge) delete c.judge
287  return c
288}
289
290/** An event of one call (main()'s `events` entries). */
291type Ev = {
292  tool: string
293  phase: string
294  order_phase: string
295  cmd: string
296  fp: string
297  body: string
298  /** What the call ADDED, for edit rules' content_rx; null = read `body`. */
299  added?: string | null
300  rtext: string
301  resp: { text: string; isError: boolean } | null
302  /** 'bash-pre': a file the Bash command is about to write; 'bash': one it wrote (post lane). */
303  via: 'bash' | 'bash-pre' | 'bash-read' | null
304  read: Dict | null
305  /** The worktree a synthetic edit's file is in, when not the call's. */
306  root?: string
307}
308
309type Ctx = {
310  session: string
311  agent_id: string | null
312  repo: string
313  branch: string
314  tool: string
315  worktree: string | null
316  /** The call this fire is anchored on — local-only, like `host`; the Stop
317   *  lane builds the effect judge's window from it (fire_effect.py). */
318  tool_use_id?: string | null
319}
320
321// ── the engine ──────────────────────────────────────────────────────────────
322
323export function createEngine(io: EngineIO): Engine {
324  return new RulebookEngine(io)
325}
326
327class RulebookEngine implements Engine {
328  private rules: HookRule[] = []
329  private repo = ''
330  private loaded = false
331  private unportable: string[] = []
332  private sessions = new Map<string, SessionState>()
333  private repos: Repos
334
335  constructor(private io: EngineIO) {
336    this.repos = new Repos(io)
337  }
338
339  setBook(rules: readonly HookRule[], meta: { repo: string; fetchedAt: number }): void {
340    this.rules = rules.map((r) => ({ ...r }))
341    this.repo = meta.repo
342    this.loaded = true
343    this.unportable = rules.filter((r) => truthy(r._unportable) && r.on !== 'session').map((r) => r.id)
344  }
345
346  // ── shared plumbing ──────────────────────────────────────────────────────
347
348  private assertPortable(): void {
349    if (this.unportable.length) throw new UnportableRuleError(this.unportable)
350  }
351
352  /** A per-call copy: Python loads the book fresh per process, and the fire pass writes on rules. */
353  private book(): HookRule[] {
354    return this.rules.map((r) => ({ ...r }))
355  }
356
357  private async where(cwd: string, tool: string, inp: Dict, vars: Env = {}): Promise<RepoInfo | undefined> {
358    const info = await this.repos.ofCall(cwd, tool, inp, vars)
359    if (!info.repo) return undefined
360    if (info.repo !== this.repo) throw new ForeignRepoError(info.repo, this.repo)
361    return info
362  }
363
364  /**
365   * A Bash command that writes or reads a file in ANOTHER repo's checkout
366   * (`echo > ../other/x.csv`, `tee ~/other/app/x.py`, `cat $HOME/other/README.md`)
367   * has that file judged by that repo's book (rulebook_hook `_file_book`).
368   * The mod holds one book, so it hands the call to Python, which loads it.
369   */
370  private async foreignTargets(cwd: string, cmd: string, vars: Env): Promise<void> {
371    if (!cmd) return
372    let cleaned = cmd
373    const found = findOverride(cmd)
374    if (found) cleaned = stripOverride(cmd, found)
375    let paths: string[]
376    try {
377      paths = [
378        ...bashWriteTargets(cwd, cleaned, vars).map(([p]) => p),
379        ...bashReads(cwd, cleaned, this.io.home).map(([p]) => p),
380      ]
381    } catch {
382      return   // the lane itself meets the same input and answers as Python does
383    }
384    for (const p of paths) {
385      const info = await this.repos.repoInfo(dirname(p))
386      if (info.repo && info.repo !== this.repo) throw new ForeignRepoError(info.repo, this.repo)
387    }
388  }
389
390  /** The environment a Bash command's paths expand in: HOME and the variables it names. */
391  private async varsFor(cmd: string): Promise<Env> {
392    const env: Record<string, string> = this.io.home ? { HOME: this.io.home } : {}
393    for (const name of varNames(cmd)) {
394      if (name === 'HOME' || !this.io.getenv) continue
395      const v = await this.io.getenv(name).catch(() => undefined)
396      if (v !== undefined) env[name] = v
397    }
398    return env
399  }
400
401  private async baseOf(root: string): Promise<string> {
402    const p = await this.io.paths(root).catch(() => undefined)
403    if (!p?.base) throw new Error('no rulebook base')
404    return p.base
405  }
406
407  private nowUs(): number {
408    return Math.round(this.io.now() * 1000)
409  }
410
411  private iso(us: number): string {
412    return isoMicros(us, this.io.tzOffsetMinutes(Math.floor(us / 1000)))
413  }
414
415  /** The session's state: memory, seeded once from Python's file. */
416  private async state(session: string, base: string): Promise<SessionState> {
417    let st = this.sessions.get(session)
418    if (!st) {
419      const text = await this.io.readText(join(base, 'state', sessionFileName(session)))
420      let doc: unknown
421      try {
422        doc = text === undefined ? undefined : JSON.parse(text)
423      } catch {
424        doc = undefined
425      }
426      st = stateFrom(doc)
427      this.sessions.set(session, st)
428    }
429    return st
430  }
431
432  /** The armings, re-read from the shared file (only when a rule could read them). */
433  private async refreshArmings(st: SessionState, session: string, base: string, rules: readonly HookRule[]) {
434    if (!rules.some((r) => r.on === 'ordering' && sessionScoped(r))) return
435    const text = await this.io.readText(join(base, 'state', sessionFileName(session)))
436    let doc: unknown
437    try {
438      doc = text === undefined ? undefined : JSON.parse(text)
439    } catch {
440      doc = undefined
441    }
442    const f = stateFrom(doc)
443    st.armed = f.armed
444    st.armed_version = f.armed_version
445    st.armed_once = f.armed_once
446  }
447
448  private turns(): () => Promise<readonly TurnMessage[] | undefined> {
449    let got: Promise<readonly TurnMessage[] | undefined> | undefined
450    return () => (got ??= this.io.turn().then((t) => t?.messages, () => undefined))
451  }
452
453  /** `log_fires` row for rulebook_mod_cli.py log. */
454  private fireRow(
455    ctx: Ctx, r: HookRule, phase: string, mode: string, excerpt: string,
456    o: { raw?: Record<string, unknown>; dedup?: Record<string, string>; override?: Record<string, string>; at?: string;
457      judge?: Map<string, { verdict: string; p_fit: number | null }> },
458  ): Record<string, unknown> {
459    const v = o.judge?.get(r.id)
460    return {
461      rule_id: r.id,
462      rulebook_id: r._rulebook_id ?? null,
463      rule_version: r._version ?? null,
464      agent_id: ctx.agent_id,
465      worktree: ctx.worktree,
466      source_message_id: null,
467      tool_use_id: ctx.tool_use_id ?? null,
468      // Local-only, as Python writes it: the rule's label for the one line a
469      // repair shows the person (live repair, ENG-1231).
470      title: pyStr(r._label || r.title || '').slice(0, 120),
471      repo: ctx.repo,
472      branch: ctx.branch,
473      tool: ctx.tool,
474      hook_phase: phase,
475      mode,
476      dedup_key: o.dedup?.[r.id] ?? null,
477      raw_matches_before_fire: o.raw && has(o.raw, r.id) ? o.raw[r.id] ?? null : null,
478      fired_at: o.at ?? this.iso(this.nowUs()),
479      override_reason: o.override?.[r.id] ?? null,
480      excerpt: cpSlice(excerpt, 0, 160),
481      ...(v ? { judge_score: v.p_fit, judge_verdict: v.verdict } : {}),
482    }
483  }
484
485  /** `log_event` row. `worktree` undefined = the call's checkout; null = none (a session-scoped receipt). */
486  private eventRow(ctx: Ctx, kind: string, o: { rule_id?: string; reason?: string | null; worktree?: string | null; at?: string }) {
487    return {
488      kind,
489      rule_id: o.rule_id ?? null,
490      agent_id: ctx.agent_id,
491      worktree: o.worktree !== undefined ? o.worktree : ctx.worktree,
492      repo: ctx.repo,
493      branch: ctx.branch,
494      reason: o.reason ?? null,
495      at: o.at ?? this.iso(this.nowUs()),
496    }
497  }
498
499  // ── ordering ─────────────────────────────────────────────────────────────
500
501  /**
502   * OrderingEngine.feed: decided on a lockless read of the worktree file; an
503   * outcome that WRITES (an edit arming, a green receipt) is decided again by
504   * the Python under its lock (rulebook_mod_state.py), whose answer stands.
505   */
506  private async feed(
507    rule: HookRule, ev: Ev, armed: unknown, root: string, base: string, cwd: string, cache: Map<string, unknown>,
508  ): Promise<string | null> {
509    const path = join(base, 'state', `wt-${worktreeKey(root) ?? 'None'}.json`)
510    if (!cache.has(path)) {
511      const text = await this.io.readText(path)
512      let doc: unknown = {}
513      try {
514        doc = text === undefined ? {} : JSON.parse(text)
515      } catch {
516        doc = {}
517      }
518      cache.set(path, doc)
519    }
520    let wrote = false
521    const snapshot = JSON.parse(JSON.stringify(cache.get(path) ?? {})) as unknown
522    const engine = new OrderingEngine({
523      lock: () => true,
524      unlock: () => {},
525      read: () => snapshot,
526      write: () => {
527        wrote = true
528      },
529    })
530    const ok = ev.resp !== null ? bashOk(ev.resp, rule.mode === 'gate') : null
531    const armedArg = typeof armed === 'string' ? armed : armed === undefined ? null : (armed as string | null)
532    const local = engine.feed(rule, { hookPhase: ev.order_phase, tool: ev.tool, cmd: ev.cmd, filePath: ev.fp, ok, armed: armedArg })
533    if (!wrote) return local
534    delete rule._gate_msg
535    delete rule._legacy_fires
536    const r = await this.io.state([{
537      op: 'feed', root, rule: this.rules.find((x) => x.id === rule.id) ?? rule, hook_phase: ev.order_phase, tool: ev.tool,
538      cmd: ev.cmd, file_path: ev.fp, ok, armed: armedArg,
539    }], cwd)
540    cache.delete(path)
541    const got = r?.[0]
542    if (!isDict(got) || 'error' in got) return null
543    if (typeof got.gate_msg === 'string') rule._gate_msg = got.gate_msg
544    if (Array.isArray(got.legacy_fires)) rule._legacy_fires = got.legacy_fires
545    return typeof got.outcome === 'string' ? got.outcome : null
546  }
547
548  // ── file facts ───────────────────────────────────────────────────────────
549
550  private async realpath(p: string): Promise<string> {
551    return (await this.io.stat(p, true))?.realPath ?? p
552  }
553
554  /** `os.path.realpath` of a file that may not exist yet: its directory's, resolved. */
555  private async realFile(p: string): Promise<string> {
556    const st = await this.io.stat(p, true)
557    if (st?.realPath) return st.realPath
558    const d = (await this.io.stat(dirname(p), true))?.realPath
559    return d ? join(d, basename(p)) : p
560  }
561
562  /** `_same_dir(a, b)` */
563  private async sameDir(a: string, b: string): Promise<boolean> {
564    return (await this.realpath(a)) === (await this.realpath(b))
565  }
566
567  /** `_write_root(path, repo, root)`: [worktree, path] when the file is in a checkout of `repo`, else ['', path]. */
568  private async writeRoot(path: string, repo: string, root: string): Promise<[string, string]> {
569    const info = await this.repos.repoInfo(dirname(path))
570    if (!info.repo || info.repo !== repo) return ['', path]
571    if (root && info.root !== root && (await this.sameDir(info.root, root))) return [root, join(root, relpath(path, info.root))]
572    return [info.root, path]
573  }
574
575  /** `_worktrees(root)` */
576  private async worktrees(root: string): Promise<string[]> {
577    let r: { code: number; stdout: string }
578    try {
579      r = await this.io.git(['-C', root, 'worktree', 'list', '--porcelain'], root, 3000)
580    } catch {
581      return [root]
582    }
583    if (r.code !== 0) return [root]
584    const seen = [root]
585    const real = new Set([await this.realpath(root)])
586    for (const line of r.stdout.split(/\r\n|\r|\n/)) {
587      if (!line.startsWith('worktree ')) continue
588      const p = line.slice(9)
589      const rp = await this.realpath(p)
590      if (!real.has(rp)) {
591        seen.push(p)
592        real.add(rp)
593      }
594    }
595    return seen
596  }
597
598  /** `_names_of(path)` */
599  private async namesOf(path: string): Promise<string[]> {
600    const names = new Set([path, await this.realpath(path)])
601    for (const n of [...names]) if (n.startsWith('/private/')) names.add(n.slice('/private'.length))
602    return [...names]
603  }
604
605  /** `bash_written_files(root, cmd, since, also)` */
606  private async bashWrittenFiles(root: string, cmd: string, since: number, also: readonly string[]): Promise<[string, boolean, string][]> {
607    if (!root || pySearch(TREE_REWRITE_RX, shellOnly(cmd || ''), 'm')) return []
608    const roots: string[] = []
609    for (const w of await this.worktrees(root)) {
610      if (w === root || (await this.namesOf(w)).some((n) => (cmd || '').includes(n))) roots.push(w)
611    }
612    for (const w of also) {
613      if (!w) continue
614      let same = false
615      for (const r of roots) if (await this.sameDir(w, r)) same = true
616      if (!same) roots.push(w)
617    }
618    const out: [string, boolean, string][] = []
619    for (const wt of roots) {
620      let r: { code: number; stdout: string }
621      try {
622        r = await this.io.git(['-C', wt, 'status', '--porcelain=v1', '-z', '--untracked-files=all'], wt, 5000)
623      } catch {
624        continue
625      }
626      if (r.code !== 0) continue
627      const entries = r.stdout.split('\0')
628      if (entries.length > BASH_EDIT_MAX_STATUS) continue
629      let skipNext = false
630      for (const e of entries) {
631        if (skipNext) {
632          skipNext = false
633          continue
634        }
635        if (e.length < 4) continue
636        const code = e.slice(0, 2)
637        const rel = e.slice(3)
638        skipNext = code[0] === 'R' || code[0] === 'C'
639        if (code.includes('D')) continue
640        const isNew = code === '??' || code[0] === 'A'
641        const path = join(wt, rel)
642        const st = await this.io.stat(path)
643        if (!st || st.kind !== 'file' || st.mtimeMs / 1000 < since) continue
644        out.push([path, isNew, wt])
645        if (out.length > BASH_EDIT_MAX_FILES) return []
646      }
647    }
648    return out
649  }
650
651  /** `read_edit_body(path, is_new)` */
652  private async readEditBody(path: string, isNew: boolean): Promise<string | null> {
653    const st = await this.io.stat(path)
654    if (!st || st.size > BASH_EDIT_MAX_BYTES) return null
655    const raw = await this.io.readText(path)
656    if (raw === undefined || raw.includes('\0')) return null
657    if (isNew) return raw
658    let r: { code: number; stdout: string }
659    try {
660      const dir = path.slice(0, Math.max(path.lastIndexOf('/'), 0)) || (path.startsWith('/') ? '/' : '')
661      r = await this.io.git(['-C', dir, 'diff', 'HEAD', '--no-color', '--no-ext-diff', '-U0', '--', path], dir || '.', 5000)
662    } catch {
663      return null
664    }
665    if (r.code !== 0) return null
666    return r.stdout.split('\n').filter((l) => l.startsWith('+') && !l.startsWith('+++')).map((l) => l.slice(1)).join('\n')
667  }
668
669  /** `read_facts(path, pulled, offset, limit)` */
670  private async readFacts(path: string, o: { pulled?: number | null; offset?: unknown; limit?: unknown }): Promise<Dict | null> {
671    const st = await this.io.stat(path)
672    if (!st || st.kind !== 'file') return null
673    const size = st.size
674    let total: number | undefined
675    if (size < FS_READ_MAX) {
676      const text = await this.io.readText(path)
677      if (text !== undefined) {
678        total = 0
679        for (let i = text.indexOf('\n'); i >= 0; i = text.indexOf('\n', i + 1)) total++
680        if (text.length && !text.endsWith('\n')) total++
681      }
682    }
683    if (total === undefined) total = await this.io.countLines(path)
684    if (total === undefined) return null
685    let n = total
686    if (o.offset !== undefined && o.offset !== null) {
687      const off = pyIntLoose(o.offset)
688      if (off !== null) n = Math.max(total - Math.max(off, 1) + 1, 0)
689    }
690    for (const cap of [o.limit, o.pulled]) {
691      if (cap === undefined || cap === null) continue
692      const c = pyIntLoose(cap)
693      if (c !== null) n = Math.min(n, Math.max(c, 0))
694    }
695    const bytes = n >= total ? size : total ? Math.trunc((size * n) / total) : 0
696    return { lines: n, bytes }
697  }
698
699  // ── pre / post ───────────────────────────────────────────────────────────
700
701  async pre(e: CallEvent): Promise<Verdict> {
702    return this.call('pre', e)
703  }
704
705  async post(e: CallEvent): Promise<Verdict> {
706    return this.call('post', e)
707  }
708
709  private async call(mode: 'pre' | 'post', e: CallEvent): Promise<Verdict> {
710    this.assertPortable()
711    const out: Verdict = { context: [], fires: [], ledger: [] }
712    if (!this.loaded) return out
713    const inp = (e.input ?? {}) as Dict
714    const vars = e.tool === 'Bash' ? await this.varsFor(typeof inp.command === 'string' ? inp.command : '') : {}
715    const info = await this.where(e.cwd, e.tool, inp, vars)
716    // No checkout at all: Python judges it on the book of rules that bind
717    // every repo (rulebook_hook `main`, projectless); the mod holds one repo's.
718    if (!info) throw new ForeignRepoError('', this.repo)
719    if (e.tool === 'Bash') await this.foreignTargets(e.cwd, typeof inp.command === 'string' ? inp.command : '', vars)
720    const base = await this.baseOf(info.root)
721    const st = await this.state(e.sessionId, base)
722    const saved = cloneState(st)
723    try {
724      return await this.callInner(mode, e, inp, info, base, st, out, vars)
725    } catch (err) {
726      if (err instanceof ForeignRepoError || err instanceof UnportableRuleError) throw err
727      // Python's main(): any exception is a silent exit 0, its state unsaved.
728      this.sessions.set(e.sessionId, saved)
729      return { context: [], fires: [], ledger: [] }
730    }
731  }
732
733  private async callInner(
734    mode: 'pre' | 'post', e: CallEvent, inp: Dict, info: RepoInfo, base: string, st: SessionState, out: Verdict, vars: Env,
735  ): Promise<Verdict> {
736    const io = this.io
737    const { repo, root, gitdir, branch } = info
738    const rules = this.book()
739    const env: EngineEnv = await io.env().catch(() => ({}))
740    const tool = e.tool
741    const session = e.sessionId
742    const cwd = e.cwd
743    const agentId = e.agentId && pyStrip(e.agentId) ? cpSlice(pyStrip(e.agentId), 0, 64) : null
744    const ctx: Ctx = {
745      session, agent_id: agentId, repo, branch, tool, worktree: worktreeKey(root),
746      tool_use_id: e.toolUseId ? pyStr(e.toolUseId) : null,
747    }
748    const ledger = out.ledger
749    const cmdText = tool === 'Bash' ? pyStr(inp.command || '') : ''
750    let probeRoot = root
751    let probeBranch = branch
752    const elsewhere = await this.repos.commandRoot(cwd, cmdText)
753    if (elsewhere && elsewhere !== root) {
754      probeRoot = elsewhere
755      probeBranch = (await this.repos.repoInfo(elsewhere, false)).branch
756    }
757    const turns = this.turns()
758    const probes = new Probes(io, probeRoot, probeBranch, cmdText, agentId, turns, cwd, env.baseBranch ?? '')
759
760    await this.refreshArmings(st, session, base, rules)
761    const droppedArmings: string[] = []
762    const dropArming = (rid: string) => {
763      if (rid in st.armed || rid in st.armed_version) droppedArmings.push(rid)
764      delete st.armed[rid]
765      delete st.armed_version[rid]
766    }
767    let firedNow: HookRule[] = []
768
769    let cmd = tool === 'Bash' ? strOf(inp, 'command') : ''
770    let overrideReason: string | null = null
771    if (cmd) {
772      const found = findOverride(cmd)
773      if (found) {
774        overrideReason = cpSlice(redactSecrets(found[0]), 0, 2000)
775        cmd = stripOverride(cmd, found)
776      }
777    }
778    let overrideLabel: string | null = null
779    if (overrideReason !== null) {
780      const rawReason = overrideReason
781      ;[overrideLabel, overrideReason] = splitNamedOverride(overrideReason)
782      if (overrideLabel !== null && !overrideReason) {
783        overrideLabel = null
784        overrideReason = null
785      } else if (overrideLabel !== null &&
786          !rules.some((r) => overrideLabel === pyStr(r.id).toLowerCase() || overrideLabel === labelOf(r))) {
787        overrideLabel = null
788        overrideReason = rawReason
789      }
790    }
791    const fp = strOf(inp, 'file_path')
792    const edits = truthy(inp.edits) && Array.isArray(inp.edits) ? (inp.edits as unknown[]) : []
793    const body = strOf(inp, 'new_string') + strOf(inp, 'content') +
794      edits.filter(isDict).map((x) => strOf(x, 'new_string')).join('\n')
795    const added = editAddedText(inp)
796    const editMarkers = new Map<string, string>()
797    if (mode === 'pre' && EDIT_TOOLS.includes(tool)) {
798      for (const [k, v] of findEditOverride(body)) editMarkers.set(k, cpSlice(redactSecrets(v), 0, 2000))
799    }
800    const rtext = mode === 'post' ? e.result?.text ?? '' : ''
801    const resp = mode === 'post' && tool === 'Bash' ? { text: e.result?.text ?? '', isError: !!e.result?.isError } : null
802    const dedupKeys: Record<string, string> = {}
803
804    // The events this call is (main(): synthetic edits FIRST, then the call, then synthetic reads).
805    const real: Ev = { tool, phase: mode, order_phase: mode, cmd, fp, body, added, rtext, resp, via: null, read: null }
806    const events: Ev[] = []
807    let preWritten: [string, string][] = []
808    const callKey = e.toolUseId ? pyStr(e.toolUseId) : 'last'
809    if (tool === 'Bash') {
810      const marks = st.bash_t0
811      if (mode === 'pre') {
812        marks.set(callKey, io.now() / 1000)
813        const keys = [...marks.keys()]
814        for (const k of keys.slice(0, Math.max(keys.length - BASH_EDIT_MARKS_KEPT, 0))) marks.delete(k)
815        if (cmd && rules.some((r) => r.on === 'edit' && isActive(r))) {
816          for (const [target, text] of bashWriteTargets(cwd, cmd, vars)) {
817            if ((await io.stat(target))?.kind === 'dir') continue
818            const [wroot, path] = await this.writeRoot(target, repo, root)
819            if (wroot) {
820              events.push({
821                tool: 'Write', phase: 'pre', order_phase: 'pre', cmd: '', fp: path, body: text, added: null, rtext: '',
822                resp: null, via: 'bash-pre', read: null, root: wroot,
823              })
824            }
825          }
826        }
827      } else {
828        let t0 = marks.get(callKey)
829        marks.delete(callKey)
830        if (t0 === undefined && callKey !== 'last') {
831          t0 = marks.get('last')
832          marks.delete('last')
833        }
834        const done = st.bash_pre
835        let pw = done.get(callKey)
836        done.delete(callKey)
837        if (!pw?.length && callKey !== 'last') {
838          pw = done.get('last')
839          done.delete('last')
840        }
841        preWritten = pw ?? []
842        const wantsEdits = rules.some((r) => (r.on === 'edit' || r.on === 'ordering') && isActive(r))
843        if (t0 !== undefined && wantsEdits) {
844          const also: string[] = []
845          const dirs = [...bashDirs(cwd, cmd, vars), ...bashWriteTargets(cwd, cmd, vars).map(([p]) => dirname(p)), cwd]
846          for (const d of dirs) {
847            const w = (await this.writeRoot(join(d, '_'), repo, root))[0]
848            if (w && !also.includes(w)) also.push(w)
849          }
850          for (const [path, isNew, wt] of await this.bashWrittenFiles(root, cmd, t0, also)) {
851            const text = await this.readEditBody(path, isNew)
852            if (text === null) continue
853            events.push({ tool: 'Write', phase: 'pre', order_phase: 'post', cmd: '', fp: path, body: text, rtext: '', resp: null, via: 'bash', read: null, root: wt })
854          }
855        }
856      }
857    }
858    events.push(real)
859    const wantsReads = mode === 'pre' && rules.some((r) => r.on === 'read' && isActive(r))
860    if (wantsReads && READ_TOOLS.includes(tool) && fp) {
861      real.read = await this.readFacts(fp, { offset: inp.offset ?? null, limit: inp.limit ?? null })
862    } else if (wantsReads && tool === 'Bash' && cmd) {
863      for (const [path, pulled] of bashReads(cwd, cmd, io.home)) {
864        events.push({
865          tool: 'Read', phase: 'pre', order_phase: 'pre', cmd, fp: path, body: '', rtext: '', resp: null,
866          via: 'bash-read', read: await this.readFacts(path, { pulled }),
867        })
868      }
869    }
870
871    // Conversions: collected now, posted after the fire pass.
872    const convertedHits: string[] = []
873    if (mode === 'post' && Object.values(st.spec_pending).some((p) => isDict(p) && p.root === probeRoot && p.branch === probeBranch)) {
874      const changed = await probes.diffPaths()
875      if (changed !== null) {
876        for (const rule of rules) {
877          const pendingKey = pyDumps([rule.id, probeRoot, probeBranch])
878          const pending = st.spec_pending[pendingKey]
879          if (!(isDict(pending) && pending.root === probeRoot && pending.branch === probeBranch && truthy(pending.paths))) continue
880          const specDir = pyStr(getOr(pending, 'spec_dir', 'docs/specs'))
881          let all = true
882          for (const path of pending.paths as string[]) {
883            if (!changed.includes(path) || !((await probes.activeSpecPaths(specDir)) ?? new Set()).has(path)) {
884              all = false
885              break
886            }
887          }
888          if (all && scopeOk(rule, repo, gitdir)) {
889            convertedHits.push(rule.id)
890            delete st.spec_pending[pendingKey]
891          }
892        }
893      }
894    }
895    if (mode === 'post' && tool === 'Bash' && cmd) {
896      const stripped = stripComments(shellOnly(cmd))
897      for (const r of rules) {
898        const crx = r.converted_rx
899        if (truthy(crx) && isActive(r) && scopeOk(r, repo, gitdir)) {
900          let hit = false
901          try {
902            hit = pySearch(pyStr(crx), stripped, 'im')
903          } catch {
904            hit = false
905          }
906          if (hit) convertedHits.push(r.id)
907        }
908      }
909    }
910
911    const dismissals = new Map<string, string>()
912    if (mode === 'pre' && overrideLabel !== null) dismissals.set(overrideLabel, overrideReason!)
913
914    const marks: Marks = { fired: [...st.fired], counts: { ...st.counts }, spec_pending: { ...st.spec_pending } }
915
916    // Anchor rules (§4.7), matched locally.
917    let handle = ''
918    let apath = ''
919    if (tool === 'Bash' && cmd) handle = cpSlice(redactSecrets(shellOnly(cmd)), 0, 400)
920    else if (EDIT_TOOLS.includes(tool) && fp) handle = apath = fp
921    if (mode === 'pre' && handle && (env.recall ?? '1') !== '0') {
922      let n = 0
923      for (const r of rules) {
924        if (n >= MAX_ADVISE) break
925        if (r.on !== 'anchor' || !isActive(r) || st.fired.includes(r.id) || !scopeOk(r, repo, gitdir) ||
926            !pathInScope(sc(r), apath, root) || !anchorHits(sc(r), handle).length) continue
927        st.fired.push(r.id)
928        dedupKeys[r.id] = r.id
929        firedNow.push(r)
930        n += 1
931      }
932    }
933
934    const firedOn = new Map<string, Ev>()
935    const wtCache = new Map<string, unknown>()
936    for (const ev of events) {
937      const { tool: etool, phase: ephase, cmd: ecmd, fp: efp, body: ebody } = ev
938      for (let r of rules) {
939        if (r.on === 'session' || r.on === 'anchor' || !scopeOk(r, repo, gitdir) || !isActive(r)) continue
940        const rid = r.id
941        if (firedOn.has(rid)) continue
942
943        if (r.on === 'ordering') {
944          if (ev.via === 'bash-pre') continue
945          if (EDIT_TOOLS.includes(etool) && !pathInScope(sc(r), efp, ev.root || root)) continue
946          if (rid in st.armed && rid in st.armed_version && (st.armed_version[rid] ?? null) !== (r._version ?? null)) dropArming(rid)
947          let outcome: string | null
948          try {
949            outcome = await this.feed(r, ev, st.armed[rid], root, base, cwd, wtCache)
950          } catch {
951            outcome = null
952          }
953          if (outcome === 'discharged') {
954            dropArming(rid)
955            ledger.push(this.eventRow(ctx, 'receipt', { rule_id: rid, worktree: sessionScoped(r) ? null : ctx.worktree }))
956            delete r._legacy_fires
957          } else if (outcome === 'fired') {
958            dedupKeys[rid] = `${rid}@${root}:${branch}`
959            firedNow.push(r)
960            firedOn.set(rid, ev)
961          }
962          continue
963        }
964
965        if (!pathInScope(sc(r), EDIT_TOOLS.includes(etool) || READ_TOOLS.includes(etool) ? efp : '', ev.root || root)) continue
966        if (ev.via === 'bash' && preWritten.length) {
967          const realFp = await this.realFile(efp)
968          if (preWritten.some(([a, b]) => a === rid && b === realFp)) continue
969        }
970        let scope = has(r, 'fire_scope') ? r.fire_scope : 'session'
971        if (ephase === 'pre' && r.mode === 'gate' && (ev.via === null || ev.via === 'bash-read' || ev.via === 'bash-pre') &&
972            ((etool === 'Bash' && r.on === 'bash') || (EDIT_TOOLS.includes(etool) && r.on === 'edit') ||
973              (READ_TOOLS.includes(etool) && r.on === 'read'))) {
974          scope = 'call'
975        }
976        if (typeof scope !== 'string') throw new TypeError("'NoneType' object has no attribute 'startswith'")
977        const key = !scope.startsWith('branch') ? rid : `${rid}:${branch}`
978        const matched = evaluate(r, { hookPhase: ephase, tool: etool, cmd: ecmd, filePath: efp, body: ebody, resultText: ev.rtext, added: ev.added ?? null }) &&
979          (await givenOk(r, probes, ev.read))
980        if (scope !== 'call' && !scope.startsWith('counter') && st.fired.includes(key)) {
981          if (matched) st.raw[rid] = (st.raw[rid] ?? 0) + 1
982          continue
983        }
984        if (!matched) continue
985        st.raw[rid] = (st.raw[rid] ?? 0) + 1
986        if (scope.startsWith('counter')) {
987          const i = scope.indexOf(':')
988          const threshold = (i >= 0 ? pyIntLoose(scope.slice(i + 1)) : null) ?? 1
989          st.counts[rid] = (st.counts[rid] ?? 0) + 1
990          if (st.counts[rid] !== threshold) continue
991        }
992        st.fired.push(key)
993        dedupKeys[rid] = key
994        const given = truthy(r.given) && isDict(r.given) ? r.given : {}
995        const specGiven = truthy(given.repo) && isDict(given.repo) ? given.repo : {}
996        if (truthy(specGiven.spec_untouched)) {
997          const specDir = pyStr(getOr(specGiven, 'spec_dir', 'docs/specs'))
998          const hits = (await probes.untouchedSpecs(specDir)) ?? []
999          st.spec_pending[pyDumps([rid, probeRoot, probeBranch])] = {
1000            root: probeRoot, branch: probeBranch, spec_dir: specDir, paths: hits.map(([p]) => p),
1001          }
1002          r = { ...r }
1003          const [text, detail] = specUntouchedText(pyStr(r.text), hits)
1004          r.text = text
1005          r._spec_detail = detail
1006        }
1007        firedNow.push(r)
1008        firedOn.set(rid, ev)
1009      }
1010    }
1011
1012    // One instant for everything this call records.
1013    const firedUs = this.nowUs()
1014    const firedAt = this.iso(firedUs)
1015    const firedIds = new Set(firedNow.map((r) => r.id))
1016    for (const rid of convertedHits) {
1017      ledger.push(this.eventRow(ctx, 'converted', { rule_id: rid, at: firedIds.has(rid) ? this.iso(firedUs - 1) : firedAt }))
1018    }
1019
1020    const excerptOf = (r: HookRule): string => {
1021      const ev = firedOn.get(r.id)
1022      if (ev?.via === 'bash' || ev?.via === 'bash-pre') return `bash-edit ${ev.fp}`
1023      if (ev?.via === 'bash-read') return `bash-read ${ev.fp}`
1024      return cmd || fp || ''
1025    }
1026
1027    // The judge.
1028    const [judged, held, fresh] = await judgeFires(io, st, {
1029      repo, session, tool, cmd, fp, root, firedNow, firedOn,
1030      enabled: (env.judge ?? '1') !== '0', timeoutMs: judgeTimeoutMs(env.timeoutS), base,
1031    })
1032    for (const r of firedNow.filter((r) => held.has(r.id))) {
1033      if (fresh.has(r.id)) {
1034        ledger.push(this.fireRow(ctx, r, mode, 'suppressed', excerptOf(r), {
1035          raw: { [r.id]: st.raw[r.id] ?? null }, dedup: dedupKeys, at: firedAt, judge: judged,
1036        }))
1037      }
1038      unfire(st, r, dedupKeys[r.id], marks, fresh.has(r.id))
1039    }
1040    firedNow = firedNow.filter((r) => !held.has(r.id))
1041
1042    const dismiss = (d: ReadonlyMap<string, string>): [[string, string][], [string, number][]] => {
1043      const [resolved, ambiguous] = d.size ? resolveDismissals(rules, d) : [[], []]
1044      const recorded: [string, string][] = []
1045      for (const [r, w] of resolved) {
1046        ledger.push(this.eventRow(ctx, 'dismissed', { rule_id: r.id, reason: w }))
1047        recorded.push([pyStr(r._label || r.id), w])
1048      }
1049      return [recorded, ambiguous]
1050    }
1051
1052    const finish = async () => {
1053      if (droppedArmings.length) {
1054        await io.state([{ op: 'drop', session, rule_ids: [...new Set(droppedArmings)] }], cwd).catch(() => undefined)
1055      }
1056    }
1057
1058    if (!firedNow.length) {
1059      const [setAside, ambiguous] = dismiss(dismissals)
1060      await finish()
1061      if (setAside.length || ambiguous.length) {
1062        const [agentLines] = dismissalLines(setAside, ambiguous)
1063        out.context.push(agentLines.join('\n'))
1064      }
1065      return out
1066    }
1067
1068    const fireOf = (r: HookRule) => firedOn.get(r.id)
1069    const gateable = (r: HookRule): boolean => {
1070      if (mode !== 'pre' || r.mode !== 'gate') return false
1071      const via = fireOf(r)?.via ?? null
1072      if (via === 'bash') return false
1073      if (tool === 'Bash') {
1074        return r.on === 'bash' || r.on === 'ordering' || (r.on === 'read' && via === 'bash-read') || (r.on === 'edit' && via === 'bash-pre')
1075      }
1076      if (READ_TOOLS.includes(tool)) return r.on === 'read'
1077      return EDIT_TOOLS.includes(tool) && r.on === 'edit'
1078    }
1079    const gateIds = new Set(firedNow.filter(gateable).map((r) => r.id))
1080
1081    let overridden: Record<string, string> = {}
1082    const gatesHere = firedNow.filter((r) => gateIds.has(r.id))
1083    const labelCount = new Map<string, number>()
1084    for (const r of gatesHere) labelCount.set(labelOf(r), (labelCount.get(labelOf(r)) ?? 0) + 1)
1085    let ambiguousGate: [string, number] | null = null
1086    const namedGates = (label: string) => namedRules(label, rules, gatesHere)
1087    if (overrideReason !== null && overrideLabel === null) {
1088      overridden = Object.fromEntries(gatesHere.map((r) => [r.id, overrideReason!]))
1089    } else if (overrideReason !== null) {
1090      const named = namedGates(overrideLabel!)
1091      if (named.length === 1) {
1092        overridden[named[0]!.id] = overrideReason
1093        dismissals.delete(overrideLabel!)
1094      } else if (named.length) {
1095        ambiguousGate = [overrideLabel!, named.length]
1096        dismissals.delete(overrideLabel!)
1097      }
1098    } else if (editMarkers.size) {
1099      for (const [label, w] of editMarkers) {
1100        const named = label ? namedGates(label) : []
1101        if (named.length === 1) overridden[named[0]!.id] = w
1102        else if (named.length) ambiguousGate = [label, named.length]
1103      }
1104    }
1105    const gates = firedNow.filter((r) => gateIds.has(r.id))
1106    const advisories = firedNow
1107      .filter((r) => !gateIds.has(r.id))
1108      .map((r, i) => ({ r, i, k: [r.on === 'anchor' ? 0 : 1, ...bookRank(r)] as number[] }))
1109      .sort((a, b) => cmpTuple(a.k, b.k) || a.i - b.i)
1110      .map((x) => x.r)
1111    const shown = [...gates, ...advisories.slice(0, MAX_ADVISE)]
1112    const cut = advisories.slice(MAX_ADVISE)
1113    if (overrideLabel !== null && namedRules(overrideLabel, rules, firedNow).length) dismissals.delete(overrideLabel)
1114    const [setAside, ambiguous] = dismiss(dismissals)
1115    const sameCall: Record<string, string> = {}
1116    const gateTookIt = overrideLabel !== null ? namedRules(overrideLabel, rules, gates).some((r) => r.id in overridden) : false
1117    if (overrideLabel !== null && !gateTookIt) {
1118      const here = namedRules(overrideLabel, rules, shown.filter((r) => !gateIds.has(r.id)))
1119      if (here.length === 1) {
1120        sameCall[here[0]!.id] = overrideReason!
1121        const ack: [string, string] = [pyStr(here[0]!._label || here[0]!.id), overrideReason!]
1122        if (!setAside.some(([a, b]) => a === ack[0] && b === ack[1])) setAside.push(ack)
1123      } else if (here.length) {
1124        ambiguous.push([overrideLabel, here.length])
1125      }
1126    }
1127    const blocked = gates.some((r) => !(r.id in overridden))
1128    const lines = [blocked ? `## ${BRAND} Rulebook — BLOCKED` : `## ${BRAND} Rulebook (team rules — advisory, not blocking)`]
1129    const denyLines: string[] = []
1130    if (setAside.length || ambiguous.length) lines.push(...dismissalLines(setAside, ambiguous)[0])
1131
1132    const whereOf = (r: HookRule): string => {
1133      const ev = firedOn.get(r.id)
1134      if (!ev || (ev.via !== 'bash' && ev.via !== 'bash-pre' && ev.via !== 'bash-read')) return ''
1135      let path = ev.fp
1136      const eroot = ev.root || root
1137      if (eroot && path.startsWith(eroot.replace(/\/+$/, '') + '/')) path = relpath(path, eroot)
1138      if (ev.via === 'bash-pre') return ` _(in \`${path}\`, which that command writes)_`
1139      if (ev.via === 'bash-read') {
1140        const n = (ev.read ?? {}).lines
1141        return n !== undefined && n !== null ? ` _(\`${path}\`, ${pyStr(n)} lines, read by that command)_` : ` _(\`${path}\`, read by that command)_`
1142      }
1143      return ` _(in \`${path}\`, written by that command)_`
1144    }
1145
1146    for (const r of shown) {
1147      const label = pyStr(r._label || r.id)
1148      const detail = truthy(r._gate_msg) ? ` — ${pyStr(r._gate_msg)}` : ''
1149      const staleKey = `_degraded:${r.id}`
1150      let note = ''
1151      if (truthy(r._degraded) && !st.fired.includes(staleKey)) {
1152        st.fired.push(staleKey)
1153        note = `  _(advice only — ${pyStr(r._degraded)}. Update the ${BRAND} plugin to let this rule gate.)_`
1154      }
1155      const blockedHere = gateIds.has(r.id) && !(r.id in overridden)
1156      const specDetail = pyStr(r._spec_detail ?? '')
1157      const text = pyStr(r.text)
1158      if (!gateIds.has(r.id)) {
1159        lines.push(`- **[${label}]** ${text}${detail}${whereOf(r)}${why(r)}${specDetail}`)
1160      } else if (r.id in overridden) {
1161        lines.push(`- **[${label}]** ${text}${detail}${whereOf(r)}${why(r)}${specDetail} _(gate overridden: ${overridden[r.id]})_`)
1162      } else {
1163        lines.push(`- **BLOCKED [${label}]** ${text}${detail}${whereOf(r)}${why(r)}${specDetail}`)
1164        const ident = (labelCount.get(labelOf(r)) ?? 0) > 1 ? ` (rule id ${r.id})` : ''
1165        denyLines.push(`[${label}]${ident} ${text}${detail}${whereOf(r)}`)
1166      }
1167      if (note) lines.push(note)
1168      const line = disclosureLine(r, blockedHere)
1169      const f: Fire = { ruleId: r.id, label, line, mode: gateIds.has(r.id) ? 'gate' : 'advise', text }
1170      out.fires.push(f)
1171    }
1172    if (shown.some((r) => !gateIds.has(r.id))) lines.push(ADVISE_FEEDBACK_HINT)
1173    if (blocked) {
1174      const still = gates.filter((r) => !(r.id in overridden))
1175      let how: string
1176      if (tool === 'Bash') {
1177        how = "re-run the same command prefixed RULEBOOK_OVERRIDE='<why>' — that allows exactly that call and records why"
1178      } else if (READ_TOOLS.includes(tool)) {
1179        how = 'read only the part you need (`offset`/`limit`), or hand the question to a ' +
1180          'subagent so its answer, not the file, enters this context; if the whole ' +
1181          "file must be read here, run RULEBOOK_OVERRIDE='<why>' cat <path> in Bash — " +
1182          'that allows exactly that read and records why'
1183      } else {
1184        const named = still.map((r) => `\`rulebook-override[${pyStr(r._label || r.id)}]: <why>\``).join(', ')
1185        how = `add a comment naming the rule you are excusing (${named}) — each allows ` +
1186          'that one rule, records why, and stays in the diff for the next reader'
1187        if (editMarkers.has('')) {
1188          how += '. A `rulebook-override:` with no rule in brackets excuses nothing — ' +
1189            'it would mean something different as soon as a second edit gate ' +
1190            'covers this line'
1191        }
1192      }
1193      if (ambiguousGate) {
1194        how = `\`[${ambiguousGate[0]}]\` fits ${ambiguousGate[1]} of this call's gates, so it ` +
1195          'excused none — name the one you mean by its rule id, ' +
1196          `\`[<rule id>] <why>\`, in the same override form; ${how}`
1197      }
1198      out.deny = `Blocked by the ${BRAND} team rulebook:\n` + denyLines.map((l) => `- ${l}`).join('\n') +
1199        `\nIf this is a legitimate exception, ${how}.`
1200      lines.push(`_This call was blocked. If it is a legitimate exception, ${how}._`)
mod/lanes.ts 326 lines
1// The Rulebook lanes on mod events (spec §4.2–§4.5): each builds what the
2// engine needs, asks it, and hands the Verdict to act.ts. A lane that is not
3// claimed (claims.ts) is NOT evaluated here — Python serves it, and serving
4// it twice would double-fire (outside the brief overlaps claims.ts accepts).
5//
6//   pre + post  tool.call (Bash, Edit, MultiEdit, Write, NotebookEdit, Read):
7//               pre before `next`; a gate answers `{ deny }` WITHOUT `next`
8//               (so nothing beneath runs, spec §1.2); otherwise
9//               `r = await next(e)`, post on `postResultText(tool, r)`
10//               / `r.isError`, and `r`
11//               comes back with the pre advisories and the post context added
12//               to `r.context`.
13//   prompt      prompt.submit: `next({ ...e, context: [...e.context, text] })`.
14//   session     the posture preamble as an isMeta user row
15//               (`$.session.append`, spec §4.5), once per session id.
16//
17// A call in a checkout of ANOTHER repo than the mod's book (engine.ts
18// ForeignRepoError: an edit there, or `cd ~/other && …`) is not a failure:
19// both halves of it go to Python, which loads that repo's book — the pre and
20// post lanes leave the claim around `next` and come back after it, and no
21// failure is counted, so a session that works across repos keeps its claim.
22//
23// Failure: a lane that throws gives the call to Python. The pre and prompt
24// lanes leave the claim before their `next`, so the Python hook beneath serves
25// that very call; the post lane has run past Python's PostToolUse by then (a
26// post rule only advises) and counts the failure. A pre hand-off still runs
27// the mod's post lane after `next` while `post` is claimed: Python skipped
28// its PostToolUse for that lane, so nothing else would. A claims write that
29// fails during a hand-off does not cost the call: it still reaches `next`
30// (claims.ts unsets the variable, so Python serves). See claims.ts.
31
32import type { LaneName } from '../types'
33import type { Act } from './act'
34import type { Claims } from './claims'
35import type { Io } from './ctx'
36import type { CallEvent, Engine, Verdict } from './engine'
37import { ForeignRepoError } from './engine/engine'
38
39export const TOOLS = ['Bash', 'Edit', 'MultiEdit', 'Write', 'NotebookEdit', 'Read'] as const
40/**
41 * The matcher for TOOLS. A RegExp, not the list: this build has no
42 * `MultiEdit` built-in (claude-code.d.ts BuiltinToolName), so the list does
43 * not type; the pattern still catches it on a build that has one.
44 */
45export const TOOL_RX = /^(?:Bash|Edit|MultiEdit|Write|NotebookEdit|Read)$/
46
47/** What a `tool.call` hook sees, as far as the lanes read it. */
48export type ToolCallLike = { tool: string; tool_use_id?: string; agentId?: string; [k: string]: unknown }
49/** What a `tool.call` resolves to, as far as the lanes read it (ToolCallResult). */
50export type ToolResultLike =
51  | { deny: string; context?: undefined; text?: undefined; isError?: undefined }
52  | { deny?: undefined; context?: readonly string[]; text?: string; isError?: true; [k: string]: unknown }
53export type PromptLike = { text: string; context?: readonly string[]; [k: string]: unknown }
54
55/** The `tool_response` keys rulebook_hook.py `result_text` joins, in its order. */
56const RESULT_KEYS = ['stderr', 'stdout', 'output', 'error', 'text'] as const
57
58/**
59 * The text the post lane's result rules match: for Bash, built from the
60 * tool's own record the way rulebook_hook.py `result_text(tool_response)`
61 * builds it from Claude Code's PostToolUse payload: the non-empty string
62 * fields among RESULT_KEYS, in that order (stderr before stdout), joined by
63 * a newline. The engine then scans both ends of it (rules.ts, two
64 * RESULT_WINDOW_CHARS spans), as Python's `evaluate` does, and an advise-mode
65 * ordering receipt's text check reads it too, as `bash_ok` reads
66 * `result_text`.
67 *
68 * Why not `r.text`: when Claude Code persists a large output to a file, the
69 * model, and `r.text`, get only a ~2 KB `<persisted-output>` preview, while
70 * the record's `stdout` (the same field PostToolUse sends as
71 * `tool_response.stdout`) still holds the first ~30,000 characters. A rule
72 * matching past the preview fired in Python and not here.
73 *
74 * A FAILED Bash call's record is the error string itself (`Error: Exit code
75 * 1\n<stderr>`): it stands in for a missing `text`, and either is shaped as rulebook_hook.py `failure_result`
76 * shapes the PostToolUseFailure `error` — the `Exit code N` line moved last,
77 * so a content rule reads the program's own words first (ENG-1236). The
78 * Python failure lane is claim-skipped while this mod serves `post`, so this
79 * is the only engine that sees the failure.
80 *
81 * Falls back to `r.text` for every other tool, for a record that is neither
82 * an object nor a string, and for a record with no non-empty field: Python
83 * would match `json.dumps(tool_response)` there, which the mod does not
84 * reproduce (engine.ts, port notes).
85 */
86export function postResultText(tool: string, r: { text?: string; result?: unknown; isError?: boolean }): string | undefined {
87  if (tool !== 'Bash') return r.text
88  const rec = r.result
89  if (rec === null || typeof rec !== 'object' || Array.isArray(rec)) {
90    const text = r.text || (typeof rec === 'string' ? rec : undefined)
91    return text && r.isError ? failureText(text) : text
92  }
93  const parts = RESULT_KEYS
94    .map(k => (rec as Record<string, unknown>)[k])
95    .filter((v): v is string => typeof v === 'string' && v !== '')
96  return parts.length ? parts.join('\n') : r.text
97}
98
99const EXIT_LINE = /^\s*(?:Error: )?Exit code (\d+)[ \t]*\n?/
100
101/** `Error: Exit code 1\nboom` → `boom\nExit code 1`: the program's words first,
102 *  the exit line last, as rulebook_hook.py `failure_result` shapes it. */
103export function failureText(text: string): string {
104  const m = EXIT_LINE.exec(text)
105  if (!m) return text
106  const body = text.slice(m[0].length)
107  return body ? `${body.replace(/\n$/, '')}\nExit code ${m[1]}` : `Exit code ${m[1]}`
108}
109
110/** The tools whose rules scope by path, and the input fields the engine
111 *  reads the path from (engine.ts `file_path`, repo.ts `notebook_path`). */
112const PATH_TOOLS: readonly string[] = ['Edit', 'Write', 'NotebookEdit', 'Read']
113const PATH_FIELDS = ['file_path', 'notebook_path'] as const
114
115export class Lanes {
116  /** Session ids whose posture preamble is in their conversation (by us or by Python). */
117  private served = new Set<string>()
118  /** `<session>\0<tool>` already reported by `noPathCheck`. */
119  private noPathSeen = new Set<string>()
120
121  constructor(
122    private io: Io,
123    private engine: Engine,
124    private claims: Claims,
125    private act: Act,
126    /**
127     * A create-rule forward-test claim covers this call (mod/redirect.ts):
128     * hand it to the Python hook, which serves the test's private book. The
129     * shell wires it; a fake without it never hands off on that account.
130     */
131    private forwardTest?: (cwd: string, agentId: string | undefined) => Promise<boolean>,
132  ) {}
133
134  // ── tool.call ───────────────────────────────────────────────────────────
135
136  /**
137   * A self-check on the event's shape, which only hand-written fakes pin: an
138   * Edit, Write, NotebookEdit or Read call carrying none of PATH_FIELDS means
139   * Claude Code renamed the field, and every path-scoped rule has silently
140   * stopped matching. One debug-log line per session per tool says so;
141   * nothing else changes (the call is evaluated exactly as before).
142   */
143  private noPathCheck(tool: string, input: Record<string, unknown>, sessionId: string): void {
144    if (!PATH_TOOLS.includes(tool)) return
145    if (PATH_FIELDS.some(k => typeof input[k] === 'string' && input[k] !== '')) return
146    const key = `${sessionId}\0${tool}`
147    if (this.noPathSeen.has(key)) return
148    this.noPathSeen.add(key)
149    try {
150      this.io.debug(`rulebook: a ${tool} tool.call carried no ${PATH_FIELDS.join(' or ')} ` +
151        `(input keys: ${Object.keys(input).sort().join(', ') || 'none'}); path-scoped rules cannot match it`)
152    } catch {
153      // `$.ui.log` is synchronous and may throw: a self-check costs nothing.
154    }
155  }
156
157  async toolCall<R extends ToolResultLike>(
158    e: ToolCallLike,
159    next: (e: ToolCallLike) => Promise<R>,
160  ): Promise<R | { deny: string }> {
161    if (!this.claims.has('pre') && !this.claims.has('post')) return next(e)
162    const { tool, tool_use_id: toolUseId, agentId, ...input } = e
163    const [sessionId, cwd] = await Promise.all([this.io.sessionId(), this.io.cwd()])
164    this.noPathCheck(tool, input, sessionId)
165    const base: Omit<CallEvent, 'phase'> = {
166      tool,
167      input,
168      sessionId,
169      cwd,
170      ...(agentId ? { agentId } : {}),
171      ...(toolUseId ? { toolUseId } : {}),
172    }
173
174    let pre: Verdict | undefined
175    let handed: R | undefined
176    let foreign = false
177    if (this.claims.has('pre')) {
178      try {
179        // A forward test's call (ENG-1250): the candidate it must prove lives
180        // only in the test's private book, which the mod never serves
181        // (book.ts `hookRuleFor`). Out of the claim for pre AND post, as for a
182        // foreign repo, so Python reads the claim and judges it on that book.
183        if (this.forwardTest && (await this.forwardTest(cwd, agentId).catch(() => false))) {
184          throw new ForeignRepoError(`a forward-test claim over ${cwd}`, "the test's private book, which Python serves")
185        }
186        pre = await this.engine.pre({ ...base, phase: 'pre' })
187        this.act.healthy('pre')
188      } catch (err) {
189        if (err instanceof ForeignRepoError) {
190          // Another repo's call: Python's hooks serve its pre AND post with
191          // that repo's book, and the mod's post lane below stays out.
192          foreign = true
193          handed = await this.handForeign(() => next(e))
194        } else {
195          // Python's hook serves this call's pre at `next`; the post lane below
196          // still runs here, as it would have without the failure.
197          handed = await this.handOff('pre', err, () => next(e))
198        }
199      }
200      if (pre) {
201        await this.act.record(pre, sessionId)
202        if (pre.deny) return { deny: this.act.denyText(pre) }
203      }
204    }
205
206    const r = handed ?? (await next(e))
207    if (r.deny !== undefined) return r
208
209    let post: Verdict | undefined
210    if (this.claims.has('post') && !foreign) {
211      try {
212        post = await this.engine.post({ ...base, phase: 'post', result: { text: postResultText(tool, r), isError: r.isError } })
213        this.act.healthy('post')
214        await this.act.record(post, sessionId)
215      } catch (err) {
216        // Python's PostToolUse already ran (skipped, the lane being ours):
217        // this call's post advice is lost, never a gate. Count it.
218        this.act.unhealthy('post', err)
219        await this.claims.fail('post').catch(() => undefined)
220        await this.claims.recover('post').catch(() => undefined)
221        post = undefined
222      }
223    }
224
225    const extra = [this.act.modelText(pre), this.act.modelText(post)].filter((t): t is string => !!t)
226    if (!extra.length) return r
227    return { ...r, context: [...(r.context ?? []), ...extra] }
228  }
229
230  // ── prompt.submit ───────────────────────────────────────────────────────
231
232  async promptSubmit<R>(e: PromptLike, next: (e: PromptLike) => Promise<R>): Promise<R> {
233    const sessionId = await this.io.sessionId()
234    await this.deliverSession(sessionId)
235    if (!this.claims.has('prompt')) return next(e)
236    let v: Verdict
237    try {
238      v = await this.engine.prompt(e.text, sessionId, await this.io.cwd())
239      this.act.healthy('prompt')
240    } catch (err) {
241      return this.handOff('prompt', err, () => next(e))
242    }
243    await this.act.record(v, sessionId)
244    const text = this.act.modelText(v)
245    return next(text ? { ...e, context: [...(e.context ?? []), text] } : e)
246  }
247
248  // ── session ─────────────────────────────────────────────────────────────
249
250  /**
251   * At session.start. `servedAlready`: the session that is starting already
252   * has its preamble — from Python's SessionStart hook in a fresh process
253   * (it ran before the lane could be claimed), or from the module before a
254   * hot reload. The engine still sees the session start, for its own state.
255   */
256  async sessionStart(servedAlready: boolean): Promise<void> {
257    const sessionId = await this.io.sessionId()
258    if (servedAlready) {
259      this.served.add(sessionId)
260      if (this.claims.has('session') || this.claims.has('pre')) {
261        await this.engine.session(sessionId, await this.io.cwd(), { servedAlready: true }).catch(() => undefined)
262      }
263      return
264    }
265    await this.deliverSession(sessionId)
266  }
267
268  /** After a compaction the preamble is summarised away: the next prompt brings it back (Python: SessionStart `compact`). */
269  compacted(sessionId: string): void {
270    this.served.delete(sessionId)
271  }
272
273  /**
274   * The posture preamble for a session that has none yet — in practice a
275   * compacted conversation. A new id after `/clear` or a resume is NOT served
276   * here: its claim stamp mismatched when Python's SessionStart ran, so Python
277   * delivered it, and claims' re-stamp marks the id served (no second copy).
278   * Once per session id; only while the lane is ours.
279   */
280  async deliverSession(sessionId: string): Promise<void> {
281    if (!this.claims.has('session') || this.served.has(sessionId)) return
282    this.served.add(sessionId)
283    try {
284      const { context, ledger } = await this.engine.session(sessionId, await this.io.cwd())
285      const text = context.join('\n')
286      if (text.trim()) await this.io.append('user', text)
287      // The posture rules' fire rows (Python's session_digest logs them as it emits).
288      if (ledger?.length) await this.act.record({ context: [], fires: [], ledger }, sessionId)
289      this.act.healthy('session')
290    } catch (err) {
291      // Not delivered: let Python's next SessionStart (a /clear, a compaction) serve it.
292      this.served.delete(sessionId)
293      this.act.unhealthy('session', err)
294      await this.claims.fail('session')
295      await this.claims.recover('session')
296    }
297  }
298
299  /** A foreign-repo call: pre and post out of the claim around `next`, no failure counted. */
300  private async handForeign<T>(next: () => Promise<T>): Promise<T> {
301    const lanes = await this.claims.yieldCall(['pre', 'post']).catch(() => [] as LaneName[])
302    try {
303      return await next()
304    } finally {
305      for (const l of lanes) await this.claims.recover(l).catch(() => undefined)
306    }
307  }
308
309  /**
310   * A lane threw before its `next`: out of the claim first, so the Python
311   * hook the engine starts at `next` serves this call; back in afterwards
312   * unless that was the lane's second failure.
313   */
314  private async handOff<T>(lane: LaneName, err: unknown, next: () => Promise<T>): Promise<T> {
315    this.act.unhealthy(lane, err)
316    // A rejected write still left the module serving nothing and the variable
317    // unset if it could be (claims.ts writeFailed): carry on to `next`.
318    await this.claims.fail(lane).catch((e: unknown) => this.act.unhealthy(lane, e))
319    try {
320      return await next()
321    } finally {
322      await this.claims.recover(lane).catch(() => undefined)
323    }
324  }
325}
326
mod/redirect.ts 76 lines
1// The §4b forward test's claim, as the shell honours it: a call it covers is
2// handed to the Python hook (lanes.ts `handForeign`), which reads the claim in
3// full (`rulebook_hook._redirect_base`) and serves the test's private book.
4//
5// /memhub:create-rule step 4b proves a candidate rule fires before filing it:
6// it copies the rulebook state to a private base, adds the candidate as a
7// `candidate-…` row, writes `<real base>/pretest-redirect.json` naming that
8// base and the directory prefix it covers (`<repo>/.claude/worktrees`), and
9// runs the violating command in an Agent-tool fork isolated in a worktree
10// there. The mod drops candidate rows (book.ts `hookRuleFor`, activeBase
11// false) and its lane claim is keyed on the session id, which a fork shares
12// with its parent — so with no hand-off the fork's calls were judged on the
13// real book, nothing fired, and the skill refused to file (ENG-1250).
14//
15// This decides only whether to hand off; Python decides what the claim means.
16// The uid, mode and `base` checks are Python's: a call handed over under a
17// claim Python rejects is served by Python from the real base, which is the
18// same answer the mod would have given. So every doubt here reads as "hand
19// off" only where the claim is plainly live, and as "serve" otherwise.
20
21import { REDIRECT_MAX_AGE_S, abspath, normpath, under } from './engine/shell'
22
23export const REDIRECT_NAME = 'pretest-redirect.json'
24
25/** What the check reads: the file's text, its stat, the clock. */
26export type RedirectIo = {
27  /** Resolves undefined when the file is missing or unreadable. */
28  readText(path: string): Promise<string | undefined>
29  /** `realPath` with `resolve`; undefined when the path does not exist. */
30  stat(path: string, resolve?: boolean): Promise<{ mtimeMs: number; realPath?: string } | undefined>
31  /** Epoch milliseconds. */
32  now(): Promise<number>
33}
34
35/**
36 * True when a live forward-test claim under `realBase` should steer this call
37 * to the Python hook:
38 *
39 *  - the session's cwd is inside the claimed prefix (the harness's shape: a
40 *    session started in the test worktree), checked on the spelling and, where
41 *    both resolve, on the real paths, as Python checks them; or
42 *  - the call is a sub-agent's (`agentId`): its own cwd is the isolated
43 *    worktree, which the shell's `session.cwd()` does not report, so Python,
44 *    which reads the call's cwd off the hook payload, is the one that can tell.
45 *
46 * Never when there is no claim file, when it is older than REDIRECT_MAX_AGE_S
47 * (a forgotten one from an interrupted run), or when it names no prefix.
48 */
49export async function forwardTestCovers(
50  io: RedirectIo, realBase: string | undefined, cwd: string, agentId: string | undefined,
51): Promise<boolean> {
52  if (!realBase) return false
53  const path = `${realBase}/${REDIRECT_NAME}`
54  try {
55    const text = await io.readText(path)
56    if (text === undefined) return false
57    const st = await io.stat(path)
58    if (!st || (await io.now()) - st.mtimeMs > REDIRECT_MAX_AGE_S * 1000) return false
59    const data: unknown = JSON.parse(text)
60    if (!data || typeof data !== 'object' || Array.isArray(data)) return false
61    const prefix = (data as Record<string, unknown>).cwd_prefix
62    if (typeof prefix !== 'string' || !prefix) return false
63    if (cwd) {
64      const here = normpath(abspath(cwd))
65      const pre = normpath(abspath(prefix))
66      if (under(here, pre)) {
67        const [rh, rp] = await Promise.all([io.stat(here, true), io.stat(pre, true)])
68        if (!rh?.realPath || !rp?.realPath || under(rh.realPath, rp.realPath)) return true
69      }
70    }
71    return agentId !== undefined
72  } catch {
73    return false
74  }
75}
76
companion/animal.ts 143 lines
1// The contract between the director (register.ts, which watches the session)
2// and one animal (its art, its poses, its choreography). The director knows
3// nothing of an animal beyond this file: not its size, its palette, or what
4// its frames hold. See docs/companion/ANIMALS.md for how to write one.
5
6import type { Canvas, RGB } from './pixels'
7
8/**
9 * Why the animal is speaking; the bubble's colour follows it. `proposed` is a
10 * new rule waiting to be activated or rejected: every animal presents it with
11 * a prelude of its own and holds it at least 8 s with the `proposed` tone, so
12 * the Activate / Reject / Later buttons can sit inside its bubble. An animal
13 * with no prelude still says it in the `proposed` tone, never as `advice`.
14 */
15export type Tone = 'advice' | 'blocked' | 'proposed'
16
17/** One character drawn over the pixels, at canvas pixel (x, y). */
18export type Glyph = { x: number; y: number; ch: string; color: RGB }
19
20/** What the animal is saying this frame, as the bubble should show it. */
21export type Bubble = {
22  text: string
23  /** How much of `text` has been typed out so far; `text.length` when done. */
24  shown: number
25  /** The bubble's corner label: `rule`, `tip 3`, `grr`. */
26  tag: string
27  tone: Tone
28}
29
30/** One drawn frame of an animal. */
31export type Painted = {
32  canvas: Canvas
33  /** Text over the pixels, such as a sleeper's z's. */
34  glyphs?: readonly Glyph[]
35  /** The speech bubble, or nothing while the animal is silent. */
36  bubble?: Bubble | null
37}
38
39/**
40 * The poses the director asks for, each a generator of the animal's own
41 * frame type. Four are finite and play whole; `sleep` and `look` are endless
42 * and the director cuts them off; `speak` and `pet` end on their own.
43 *
44 * The director only ever walks this ring:
45 *
46 *   enter → sleep ⇄ (wake → look ⇄ pet) → rise → speak+ → leave → enter
47 *
48 * so every finite pose must end where the next one begins.
49 */
50export type Poses<F> = {
51  /** Offscreen → asleep. Runs at startup and after every `leave`. */
52  enter(): Generator<F>
53  /** Asleep, endless: nothing is happening in the session. */
54  sleep(): Generator<F>
55  /** Asleep → awake. */
56  wake(): Generator<F>
57  /** Awake, endless: Claude is answering, or the person is typing. */
58  look(): Generator<F>
59  /** Awake → the speaking position. */
60  rise(): Generator<F>
61  /**
62   * Says one thing and holds it long enough to read: type `text` out, then
63   * keep still for a few seconds. Several may run back to back, so this must
64   * start and end in the same position `rise` left the animal in.
65   *
66   * @param text what to say, already short enough for the bubble
67   * @param n how many times the animal has spoken this session, from 1
68   */
69  speak(text: string, n: number, tone: Tone): Generator<F>
70  /** The speaking position → offscreen, ready for `enter` again. */
71  leave(): Generator<F>
72  /**
73   * Awake → awake: what a click on the animal does. 20–40 frames, starting
74   * and ending on the first frame `look` yields. Without it the director
75   * floats hearts over `look` instead.
76   */
77  pet?(): Generator<F>
78}
79
80/**
81 * One build of an animal: art drawn for one pixel size, with the poses and
82 * the canvas that go with it.
83 *
84 * A pixel is `pixelSize` cells wide and half that tall, so the same drawing at
85 * size 1 packs two canvas rows into one cell and at size 2 gives each row a
86 * cell of its own. That is a different drawing problem, not the same one
87 * scaled: what reads at size 2 can turn to mush at size 1. An animal may ship
88 * a build per size, each with art of its own.
89 */
90export type Build<F = unknown> = {
91  /** Cells per pixel this art is drawn for. */
92  pixelSize: number
93  /** The canvas every frame paints on, in pixels (two pixels a terminal row). */
94  size: { columns: number; rows: number }
95  /**
96   * Where the bubble hangs, in canvas pixels: its right edge sits at
97   * `column`, and its last row at `row` — so the tail points at the animal's
98   * head while it speaks. `rowWhenAbove` is that last row for a terminal too
99   * narrow to fit the bubble beside the animal, where it sits over its head
100   * instead (the animal's own top row suits); `row` is used when absent.
101   */
102  bubbleAt: { column: number; row: number; rowWhenAbove?: number }
103  /**
104   * Canvas rows at the top and bottom the band may drop when it is short of
105   * room — empty sky, the base of a mound — so the pixels can be drawn bigger
106   * instead. Nothing the animal needs to read should live in them.
107   */
108  trim?: { top?: number; bottom?: number }
109  poses: Poses<F>
110  /**
111   * Draws one frame. Called exactly once per frame, in order, so a build may
112   * keep state between calls (particles, a wind, a ripple).
113   *
114   * @param frame what a pose just yielded
115   * @param tick the frame number since the session started, for anything
116   *        that moves on its own (a shimmer, a drift)
117   */
118  render(frame: F, tick: number): Painted
119  /**
120   * What `/<name> demo` and `/<name> <pose>` replay, when the build has a loop
121   * of its own to show off; without it those arguments are refused.
122   */
123  demo?(only?: string | null): Generator<F>
124  /** The poses `demo` accepts by name, for the command's usage line. */
125  demoPoses?: readonly string[]
126}
127
128/**
129 * One animal: its name, and its art. The band draws the smallest build unless
130 * someone asks for a bigger pixel, which is what `/<name> scale <n>` is for.
131 */
132export type Animal = {
133  /** Its name, which is also its command: `Hippo` gives `/hippo`. */
134  name: string
135  /**
136   * What the speech bubble's header shows, when that is not just the name:
137   * the hippo answers to `/hippo` and introduces itself as Hugo.
138   */
139  title?: string
140  /** One build per pixel size, smallest first; at least one. */
141  builds: readonly Build[]
142}
143
companion/animals/index.ts 17 lines
1// Every animal the band can show. A new one lands here and nowhere else: the
2// director reads this list for its commands and for the saved choice.
3//
4// See docs/companion/ANIMALS.md for what writing one involves.
5
6import type { Animal } from '../animal'
7import { goose } from './goose'
8import { hippo } from './hippo'
9import { penguin } from './penguin'
10import { shiba } from './shiba'
11
12// Gus first: the band shows the first of these to anyone who has not picked
13// one, and a saved choice wins over it.
14export const ANIMALS: readonly Animal[] = [goose as Animal, hippo as Animal, penguin as Animal, shiba as Animal]
15
16export const DEFAULT_ANIMAL = ANIMALS[0]!
17