SLOPSHOPPER

kodflow-hooks

The lifecycle machinery the other plugins assume: shell-output compression that never rewrites a read whose bytes matter, a git guard, a delegation gate (code…

guardcommandtoastprompttoolprocess
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · kodflow-hooks
› 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(rm -rf build && git push --force origin main) ⎿ Denied by kodflow-hooks: ═══════════════════════════════════════════════ ❌ BLOCKED — code production in ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM › /lint-setup ⎿ kodflow-hooks: No go.mod at or above /work/app inside /work/app: not a Go project, so the hooks do not run ⎿ kodflow-hooks: ktn-linter here, and there is nothing to set up. ⎿ kodflow-hooks: Name a file or a directory of a Go module to check it: /lint-setup <path>. ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts
README

kodflow-hooks

The lifecycle machinery the other kodflow plugins assume: a git and forge guard that reads a Bash line as the shell would and never rewrites it, the delegation gate (code in a git repository is produced by subagents), session context, a formatter, a turn-end quality gate, one structured log, and the session task list.

Two halves. The shell scripts (hooks/scripts/) hold every hard guard and run on any Claude Code. The function hooks (hooks/mod/, a mod: TypeScript the engine loads from hooks/hooks.json → modules) serve the task tools, blank the attribution text, double the Bash guards, compress Bash output and mask secrets in every tool's result; they need Claude Code 2.1.293 or later.

The mod and what is lost without it

hooks/mod/register.ts is wiring only, one on(...) per event; the logic sits in pure modules beside it (tasks.ts, store.ts, calls.ts, paths.ts, lint.ts, shell.ts, patterns.ts, guards.ts, filter.ts, veil.ts, mcp-probe.ts, pipeline.ts, fable.ts, cleanup.ts, and for the three machine guards machine-guards.ts over a port, with modwall.ts, collision.ts, zsh.ts), which never touch $: the engine follows $ and on only inside register.ts.

EventWhat the mod does
session.startregisters task_create, task_update, task_epic, task_focus, task_list, task_assign_human (isDeferred: false), listed as mcp__kodflow-hooks__task_*, and the /lint-setup command
classic.SessionStart with source: compactadds to the context the tasks still waiting on the user (task_assign_human), read fresh from tasks.json, so a summary cannot drop a pending "go"
command.run on lint-setupchecks ktn-linter for a Go module (below)
classic.SessionStart, prompt.submit, every tool.callwrites the beat, <config>/kodflow/sessions/<session>/mod-beat (time in seconds), before the shell hook of the same event runs, once the tools are registered
tool.call on a task toolanswers it (below); a refusal is { deny } with the text the model reads, an internal failure a text error, never a crash
tool.call on Bashone pipeline of ordered policies (pipeline.ts), below
every tool.call, after the tool ransecrets masked in the result (veil.ts), below
tool.call on an mcp__* tool, after the veilone line of shape and size in mcp-shapes.jsonl (mcp-probe.ts), below
prompt.submitremembers when the user last pressed Enter (origin.kind composer, notePrompt of machine-guards.ts, read through lastComposerAt()): the collision and gated-model questions are put only to someone who typed in the last 10 minutes
attribution.text"" for commit and pr; exemption and remedy untouched
plugin.registermodwall: refuses every user-tier hooks module whose provenance is not *@kodflow (the list is in modwall.ts, nothing the model writes widens it); built-in and managed tiers are not judged. Each decision goes to $.store (modwall, last 100) and the debug log; a refusal is toasted once the session binds
command.run · /kodflow-modsthe modules judged at this load, and the refusals on record
session.startzsh-safe: ZDOTDIR → hooks/zsh, the user's own in KODFLOW_USER_ZDOTDIR ("" when unset); hooks/zsh/.zshenv gives ZDOTDIR back, sources the user's .zshenv, then setopt nonomatch noequals: echo .none prints .none instead of failing
tool.call on Edit, Write, MultiEdit, NotebookEditcollision-guard: when another session of this machine, beating within 30 min, wrote the same file within 30 min (its edits.tsv), asks Continue / Move to a worktree (the model is told to call EnterWorktree) / Cancel, but only when the user typed a prompt at the terminal (origin.kind composer, noted by prompt.submit) in the last 10 minutes (the presence rule): otherwise it journals the collision to the debug log and lets the edit through, so a night run never waits on a question; once written, notes <seconds>\t<path> in <config>/kodflow/sessions/<session>/edits.tsv (no prompt, no content); <config>/projects is never checked
session.endempties this session's edits.tsv
agent.spawngated models: passes or refuses a spawn on the model it would run on, never writes one (below)
tool.call on Skillgated models: a skill whose frontmatter names one passes only with the session's grant, asked once like a spawn
classic.PreModelSwitcha /model the user typed or picked grants the session a gated model; a switch from the SDK asks, and is refused with nobody at the prompt
tool.call on Bash, Edit, Write, MultiEdit, NotebookEdit from a subagentcleanup on close: notes the absolute .worktrees/<name> roots its arguments name (~ and $HOME expanded) under its id in <config>/kodflow/sessions/<session>/worktrees.json, once per path, without waiting
tool.call on task_update completing a main-agent taskcleanup on close: once the answer is settled, starts hooks/scripts/cleanup.sh on the worktrees of the task's worker, and when the completion closes the epic, of every worker of the epic and every subagent started on it; never awaited (below)
prompt.submit from the composerwrites <config>/kodflow/sessions/<session>/composer-at (seconds), the presence on-stop.sh reads before proposing agent feedback

The Bash pipeline

One on("tool.call", { tool: "Bash" }), its policies in a fixed order, each with its own failure rule. No policy ever answers allow, and none answers { result } but the filter (and the veil, on every tool).

#PolicyWhat it doesA failure
1guards (guards.ts)the shell's Bash guards doubled, refusal only: same reader (shell.ts, a port of on-tool.sh's), same order of blocks, same motifs; the bash-guard corpus is replayed against both. The staged-secret scan stays the shell's alone; the mcp.json refusal is doubled (the index read by name only), and the generic tool.call hook holds the forge tools to itis logged, the call goes on
2the callthe shell's PreToolUse runs beneath, as ever—
3output filter (filter.ts, L3)a line that is exactly one git status, git log, git diff, ls -l, find or grep -rn gets its stdout shortened (hints, index lines, columns, repeated prefixes); never a read whose bytes count (cat, head, tail, sed, diff, git show, git cat-file, …), never a failed, interrupted, persisted, image, background or structured result, only when the result has the shape a Bash call gives, an object whose stdout is a string, checked on every call and on any engine version (no version window to go stale). Every other key of the result is keptreturns the result untouched

Each decision and failure is one ModPolicy line in the session log.

A merge asks nothing and waits on no one: from the main thread it is journaled (root_guard: merge), from a subagent it is refused. No command is put to the user for being irreversible (rm -rf included); the guards above still refuse what they refuse (a forced push, the delegation gate's writes).

The secret veil

After every tool ran, never on its input: the value of a known credential variable of the session (SECRET_VARS), a credential by its shape (provider prefixes, Bearer, private key blocks, user:password@, password=…), and a token of 20 characters or more, letters and digits mixed, above 4.3 bits per character, unless it is a hash, a UUID, a path, an integrity digest or base64 of plain text. A masked value is gone, nothing keeps it. An errored result with a secret is withheld with the masked text. Past 2 000 000 characters or 1.5 s, the result comes back as it was (fail open). A {type:"image"} block is left whole, not read as text: its data is base64 pixels, which the entropy rule would take for a token. The text blocks of the same result are still masked.

The MCP shape probe: mcp-shapes.jsonl

<config>/kodflow/sessions/<session>/mcp-shapes.jsonl (mcp-probe.ts): after an mcp__* tool ran and its result was veiled, one JSON line. It measures how large MCP results are, and what shape, before anything is built on them; the result itself is never changed, cut or cached.

FieldContent
attime, whole seconds
toolthe tool's name
keysthe keys of the answer (result, isError, deny, …)
formwhat result is: string, array, object, null, …
resultKeysthe keys of result when it is an object
blocksthe type of each content block (result or result.content), in order
charsthe length of the result serialised, in characters

No value of the result is read into the line: a key or a block type is kept only when it reads like an identifier (letters, digits, _, -, 32 at most), else it is written ?; lists stop at 20. The file is created 0600 (umask 077, then chmod 600, in one sh run with the line on stdin), one append per call, no rotation: it is read, then deleted, by the user. KODFLOW_MCP_PROBE=off turns it off; a failed append is swallowed and the result goes to the model as it is.

Every hook fails open. KODFLOW_MOD=off (environment or the env block of the settings) makes the module pass-through: no tool, no beat, no marker. A modwall judge that throws lets the module load; with no one to answer (-p) or the dialog dismissed, collision-guard lets the edit through.

modwall judges only the modules that register after kodflow-hooks: one loaded before it (load order is the engine's) is admitted by core alone, and /kodflow-mods says so. This limit is accepted: closing it would take kodflow-hooks into the managed prepend tier, which managed settings alone can do, and they are not used. on-session.sh stays the net: it warns about any plugin outside the kodflow marketplace that declares modules.

The shell reads the beat (lib/beat.sh): younger than 5 s, the task tools answer; older, the mod was loaded and is gone; absent, it never loaded.

Without the mod (Claude Code < 2.1.293, KODFLOW_MOD=off, a failed reload)
task toolsabsent: tasks are not tracked, the status line shows no epic
triage gate, triage directive, epic state in the prompt, session-start reviewoff: nothing could lift a gate the tools cannot answer
built-in TaskCreate/TodoWriteallowed again: they are the only list left
attribution textClaude Code's own (the shell guard still refuses AI attribution in a commit)
what the user is toldonce per session that the task tools did not load (not with KODFLOW_MOD=off); after an unload, /reload-plugins

| output filter, secret veil, doubled guards | absent |

Every hard guard (git, delegation, protected paths, secrets) is shell and does not depend on the mod.

One script per event

Hooks registered on the same event run in parallel — the Claude Code hooks reference says so in one line, and it decides the design. A chain of small scripts on PreToolUse has no order: the guard may inspect a command the rewriter has already changed. The only way to get a sequence is to have one script per event and put the sequence inside it.

Every script runs the same four stages, in this order, and leaves at the first stage that has nothing more to do:

StageMeaningExit
1 · gatethe cheapest test that lets most calls leave at once0
2 · blockwhat must stop the call2, reason on stderr
3 · transformwhat Claude reads (context, the task identity of a task_* call), emitted as one JSON document; a Bash command is never rewritten0
4 · observelogging and advice, off the critical path0

Every path that is not a deliberate block exits 0. A PreToolUse hook that fails by accident blocks every shell call of the session.

Events → scripts

EventScriptGateBlockTransformObserve
PreToolUse · Bashon-tool.shno git/gh/glab/curl/wget/http on the line once unquoted (and no $'…')read by the shell reader below: the main thread producing into a repository (delegation gate) · --no-verify, -n on a commit, -c core.hooksPath · AI attribution or workflow leak in a commit message, AI attribution in a PR/MR title or body · credential shapes in the staged blobs · a forced push (--force, -f, +refspec), with the command to run instead · from a subagent: any merge, any push to the default branchnone: the input is never rewrittenlog; a main-thread merge is tagged root_guard: merge
PreToolUse · task toolson-tool.shthe mod's task tools never reach it (a call a function hook answers fires no PreToolUse); the old MCP names are logged and passedbuilt-in TaskCreate/TodoWrite while the mod beats: their chat panel duplicates the status line, the refusal points at the kodflow task tools—log
PreToolUse · Write/Editon-tool.shmain thread writing inside a git work tree (memory and Claude configuration excepted) · no file paththe main thread producing into a repository (delegation gate) · protected path (defaults or .claude/protected-paths)—log (no linter call: ktn-linter reports through its own command hooks)
PreToolUse · forge MCP (mcp__github__*, mcp__gitlab__*, mcp__GitKraken__*)on-tool.shno message, title, body, description, branch or merge field, and a subagent or a read/merge/review/issue tool (decided without jq)a forge write from the main thread (files, branches, pull requests) · AI attribution or workflow leak in a commit field (message, commit_message, commit_title, squash_commit_message, merge_commit_message) · AI attribution in the title, body or description of a PR/MR tool · from a subagent: a merge (merge_pull_request, merge_merge_request, merge_when_pipeline_succeeds, auto_merge), a file write to main/master—log; a main-thread merge is tagged root_guard: merge
PostToolUse · Write/Editon-tool.shfile absent; then markdown, .claude/—docs.json rebuilt after a write under docs/ (markdown included), at most every 30 s otherwise · document concerné for each document the file concerns, once per session (below) · format (Makefile fmt/format first, then the formatter for the extension) and say so when the bytes changed · then, for a Go file (Write/Edit/MultiEdit), the ktn-linter findings of that file with the instruction to fix them now, unless ktn-linter's own PostToolUse hook is installed or KODFLOW_LINT=off (below)edited-file tracker · risky construct warning once per session · log
PreToolUse · Agent/Taskon-tool.shgated-model fallback first, every caller, no jq; then the main thread onlya gated model when the mod does not beat · from the main thread, a general-purpose dispatch whose description names an installed specialist's technology (routing gate, below) · from the main thread, isolation: "worktree" on work in another repository (isolation gate, below)—log, root_guard: route-deny, route-override, route-noindex, isolation-deny or isolation-override
PreToolUse · Skillon-tool.shthe mod does not beata skill whose frontmatter names a gated model——
PostToolUse · Task/Agenton-tool.sh———agent-models.tsv (agent id, resolved model, per-call effort) · log tagged root_guard: dispatch
PostToolUse · SubagentHandbackon-tool.sh———the report's agent feedback, as at SubagentStop
PostToolUse · Readon-tool.sh——docs.json at most every 30 s · document concerné for each document the file concerns, once per sessionlog
PostToolUse · Bashon-tool.sh——docs.json at most every 30 slog
PostToolUse · otheron-tool.sh———log
PostToolUseFailureon-tool.sh———remediation hint · a failure carrying auto mode's refusal text goes to blocks.jsonl · log (error redacted)
PermissionDeniedon-tool.sh———auto mode's refusal in blocks.jsonl (kind classifier, the verdict, the rule that would allow the call) · log
SessionStarton-session.sh——docs.json and the index of the project's documents (below) · routing-installed.tsv for the routing gate · a notice when the session starts on a gated model · the open tasks to reconcile, while the mod beats · post-compaction rules on compact · a warning when rtk is absent · a warning to the user (systemMessage) and to Claude when disableAllHooks is set, when CLAUDE_CODE_PLUGIN_DIRS is set, or when an enabled plugin, a skills directory or a plugin dir outside the kodflow marketplace declares modules · the same warning when an installed guard (on-tool.sh, scripts/lib/agents.sh, scripts/lib/identity.sh, gated-models.txt, hooks/patterns/*.txt) differs from hooks/fingerprints.sha256, when that file is missing, or when it differs from the marketplace clone's (D8: nothing is blocked; the file is generated by scripts/hooks-fingerprints.sh and checked by CI)log
SessionEndon-session.sh———one log line with the session's event count (1.5 s budget)
PreCompacton-session.sh———log
ConfigChangeon-session.sh———log · bypassPermissions flagged in security-events.jsonl
UserPromptSubmiton-user.sh——branch, latest plan, latest goal · the cleanup notices (cleanup-notices, consumed) · while the mod beats: the main agent's epics (active one with its task in progress, other open ones with done/total) when tasks.json exists, and the triage directive with the epic mandatory on task_create · the delegation line (code in a repository: dispatch or message the epic's subagent) unless KODFLOW_ROOT=off · no triage directive on a turn the user did not type · a systemMessage when the mod is goneraise the triage gate (mod beating) and reset the Stop loop counter, except on a turn the user did not type · log
Notificationon-user.sh——bell (terminalSequence) on idle, permission and elicitation promptslog
SubagentStarton-agent.sh——the standing rules, injected into the subagent (own worktree, deliver through a PR, and rule 6: end with ## Agent feedback)running-agents registry, with the main agent's active epic at start · log
SubagentStopon-agent.shstop_hook_active——running-agents registry · its agent feedback in agent-feedback.jsonl · log
TaskCreated · TaskCompleted · TeammateIdleon-agent.sh———log
Stopon-stop.shstop_hook_active · 3 feedbacks without a new prompt—feedback in one document, one line per cause, each task named once, each cause said once per state (below, « The Stop feedback ») · the CLAUDE.md of each directory changed this session, once per directory · a triage cause left unsettled (triage-pending), not on a system turn · the subagents' new agent feedback, once, to a user present in the last 10 minutes, never for an agent with no definition filebell · log

Main thread = reviewer, code is delegated

The user's rule: the main thread triages, manages epics and tasks, dispatches, reviews, merges, and informs. Code production in a git repository is delegated: every epic is carried by at least one subagent working in its own git worktree beside the repository (<repo parent>/.worktrees/<repo>-<epic-slug>; when that parent is or sits under ~/Documents, ~/Desktop or ~/Downloads, which macOS TCC protects, ~/Projects/.worktrees/<repo>-<epic-slug> instead) that delivers through a PR. The main thread keeps every other permission — it is also the workstation's sysadmin (sudo, apt, systemctl, nmcli, installs, files outside repositories, configuration).

The gate is mechanical. A PreToolUse payload carries agent_id only when the call comes from inside a subagent (measured on 855 real events: every one carrying it came from a subagent, no main-thread one did), so a call without it is the main thread's own hand. Subagents are never gated. The main thread is refused exactly three things:

ToolRefusedStill allowed
Write/Edit/MultiEdit/NotebookEdita file inside a git work tree: its directory and parents are walked up looking for .git (a directory, or a worktree's gitdir file), no exec, after the path is normalised lexicallyeverything outside a repository; <config>/projects/*/memory/*, <config>/settings.json, settings.local.json, <config>/CLAUDE.md and ~/CLAUDE.md even inside one
Bashgit commit, push, rebase, cherry-pick, merge, am, apply, revert, reset --hard, worktree add; gh pr create, glab mr create — wherever the shell reader finds them (below)everything else: no allow-list, no redirection rule, unknown commands pass; gh pr merge and glab mr merge pass the delegation gate, and the merge gate then asks for the mod's token (above)
forge MCP (mcp__github__*, mcp__gitlab__*, mcp__GitKraken__*)file, branch, push and pull-request writes, and any tool not classifiedreads, merges, reviews, comments, issues (decided in the jq-free fast path)

Commit identity

A commit carries a name and an address to wherever its repository is pushed. Before every git commit the shell reader finds, on-tool.sh (BLOCK 2b, lib/identity.sh) holds that identity to the one the user's rules give the forge of origin, so an address meant for one host never lands on another. The rules are the user's and stay out of this repository: ${CLAUDE_CONFIG_DIR:-~/.claude}/kodflow/commit-identity.conf (commit-identity.example.conf beside this README shows the format with example values).

  • The forge is origin as git remote get-url gives it (insteadOf applied): https, ssh://user@host:port/…, git@host:path, CodeCommit with a key id and codecommit::<region>://. No origin, a local path, or a host no rule names: refused.
  • The identity is the one git will write, author and committer, name and address: git var GIT_AUTHOR_IDENT and GIT_COMMITTER_IDENT run in the commit's directory (-C, cd … &&), with the line's -c, --config-env, --git-dir, and the GIT_*, EMAIL, HOME it sets (X=v git, env [-i] [-u X] X=v git, export X=v; …), so local, global and includeIf configuration all count; then --author, or the reused commit's author for --amend, -C, -c unless --reset-author. The address is compared without case, the name exactly.
  • An empty address (<> in a rule) is what git writes for user.email="", with or without user.useConfigOnly (tests/test_identity.sh asks git each run). A rule with an address refuses an empty one, and a rule without refuses any.
  • A refusal ([motif:commit-identity]) names the rule, the expected identity, the author and committer found, and the two git -C <dir> config commands to run. The hook never changes a configuration.
  • Fail open: no rules file, the check is off and says so once a session (systemMessage); a malformed or unreadable one voids the whole file the same way rather than enforce half a policy; git missing, not a repository, or a value the reader cannot know (a $ or a backtick in it) leaves the commit alone. KODFLOW_COMMIT_IDENTITY=off turns it off.
  • Not covered: a commit made by merge, rebase, cherry-pick, revert, am or pull (their committer), a commit through a for
Source 20 files
hooks/mod/register.ts 828 lines
1// register.ts — kodflow-hooks' function hooks: wiring only.
2//
3// One `on` per event, each a few lines that read `$` and hand the work to the
4// pure modules beside this file (tasks.ts, store.ts, calls.ts, paths.ts).
5// The shell scripts keep every hard guard; this module serves the session
6// task list as six tools, blanks the attribution text, and beats: it writes
7// <config>/kodflow/sessions/<session>/mod-beat before each event it sees, so
8// the shell hooks know the task tools exist before they gate on them. After a
9// compaction it tells the model again which tasks wait on the user, and it
10// serves /lint-setup (lint.ts).
11//
12// Bash goes through one ordered pipeline (pipeline.ts): the shell's guards
13// doubled (guards.ts), the call, then its output compressed (filter.ts).
14// Every tool's result then has its secrets masked (veil.ts) before the model
15// reads it, and an MCP tool's leaves one line of shape and size, no value, in
16// the session directory (mcp-probe.ts).
17//
18// Gated models (fable.ts): an agent.spawn that would run on one passes only
19// with the session's grant in $.store, asked once while the user is at the
20// prompt; a /model the user types grants it (classic.PreModelSwitch). The
21// hook never writes the model it judged.
22//
23// Every hook fails open: a throw is caught and the event goes on, except a
24// task tool's own call, which answers the failure as text, and a spawn whose
25// raw input names a gated model. KODFLOW_MOD=off turns the whole module into
26// pass-through, with no marker written.
27//
28// Cleanup on close (cleanup.ts): the worktrees a subagent writes into are
29// noted; a task_update that completes a worker's task, or closes an epic,
30// hands them to hooks/scripts/cleanup.sh, started without waiting for it.
31import type { Register } from "claude-code";
32import {
33  TOOLS,
34  MAIN,
35  humanContext,
36  isTaskError,
37  plan,
38  resolveWorkers,
39  type ToolName,
40} from "./tasks.ts";
41import { load, lock, mutate, unique, type Port } from "./store.ts";
42import { LINT_SETUP, lintSetup, type LintPort } from "./lint.ts";
43import {
44  argsOf,
45  attributionText,
46  isMcpTool,
47  isOff,
48  logPayload,
49  mainLoop,
50  settleCauses,
51  taskTool,
52  triageCauses,
53} from "./calls.ts";
54import {
55  agentsFile,
56  beatFile,
57  beatText,
58  composerFile,
59  configDir,
60  safe,
61  sessionDir,
62  triageFile,
63} from "./paths.ts";
64import {
65  admit,
66  endGuards,
67  guardWrite,
68  lastComposerAt,
69  notePrompt,
70  modsReport,
71  startGuards,
72  type GuardPort,
73} from "./machine-guards.ts";
74import {
75  forgeMcpJson,
76  inspect,
77  refusalText,
78  verdict,
79  type GuardCtx,
80} from "./guards.ts";
81import { loadRules, type Rules } from "./patterns.ts";
82import { filterResult } from "./filter.ts";
83import { veilResult } from "./veil.ts";
84import { appendArgv, shapeLine, shapeOf, shapesFile } from "./mcp-probe.ts";
85import { blockOf, type Block } from "./blocks.ts";
86import { runBash } from "./pipeline.ts";
87import {
88  WRITING_TOOLS,
89  claim,
90  closingOf,
91  note,
92  worktreePaths,
93  type Closing,
94} from "./cleanup.ts";
95import {
96  anyGated,
97  gateMode,
98  grantKey,
99  failClosedTokens,
100  forced,
101  judgeSkill,
102  judgeSpawn,
103  skillPaths,
104  judgeSwitch,
105  isGated,
106  parseGated,
107  refusal as fableRefusal,
108  definitionPaths,
109  type SpawnPort,
110} from "./fable.ts";
111
112// Set once every tool registered; the beat is a promise that they did.
113let toolsReady = false;
114
115// The gated-model question is only put to someone who is there: a message
116// typed at the prompt in the last 10 minutes, as machine-guards.ts records it
117// (notePrompt, in prompt.submit).
118const PRESENCE_MS = 10 * 60_000;
119const present = () => {
120  const at = lastComposerAt();
121  return at !== undefined && Date.now() - at <= PRESENCE_MS;
122};
123
124// Read once a session: the credential variables' values.
125let secrets: Promise<string[]> | undefined;
126// The vendored §5 rules; a failed read stays undefined and is tried again.
127let rules: Rules | undefined;
128
129const off = async ($: any): Promise<boolean> =>
130  isOff(await $.env.get("KODFLOW_MOD"));
131
132async function config($: any): Promise<string | undefined> {
133  return configDir(
134    await $.env.get("CLAUDE_CONFIG_DIR"),
135    await $.env.get("HOME"),
136  );
137}
138
139async function ensureTools($: any): Promise<void> {
140  if (toolsReady) return;
141  for (const tool of TOOLS)
142    await $.tool.register({ ...tool, isDeferred: false });
143  toolsReady = true;
144}
145
146// `early`: the settings hooks' SessionStart runs before the session binds,
147// when `$.tool.register` still rejects; session.start registers the tools
148// before the first prompt. The beat there says the mod is loaded. Should the
149// registration then fail, no beat follows, and the first prompt finds it
150// stale and lifts whatever the SessionStart hook raised.
151async function beat($: any, session?: string, early = false): Promise<void> {
152  if (!toolsReady && !early) return;
153  const cfg = await config($);
154  if (!cfg) return;
155  const dir = sessionDir(cfg, session || (await $.session.id()));
156  await $.fs.write(beatFile(dir), beatText(Date.now()));
157}
158
159// The user's open tasks, read fresh, for the context a compaction lost
160async function humanAfterCompact(
161  $: any,
162  session: string,
163): Promise<string | undefined> {
164  const cfg = await config($);
165  if (!cfg) return undefined;
166  return humanContext(
167    await load(port($), sessionDir(cfg, session), Math.floor(Date.now() / 1000)),
168  );
169}
170
171async function lintPort($: any): Promise<LintPort> {
172  return {
173    exists: (path) => $.fs.exists(path).catch(() => false),
174    isDir: (path) =>
175      $.fs.stat(path).then(
176        (s: { kind: string }) => s.kind === "directory",
177        () => false,
178      ),
179    read: (path) =>
180      $.fs.read(path).then(
181        (t: string) => t,
182        () => undefined,
183      ),
184    run: (argv, timeoutMs) =>
185      $.process.run(argv, { timeoutMs }).catch(() => undefined),
186    ask: (question, options) =>
187      $.ui.ask(question, options).catch(() => undefined),
188    vars: {
189      KTN_USER_DAEMON: await $.env.get("KTN_USER_DAEMON"),
190    },
191    sleep: (ms) => $.clock.sleep(ms),
192    root: await $.session.root(),
193  };
194}
195
196function port($: any): Port {
197  return {
198    read: (path) =>
199      $.fs.read(path).then(
200        (t: string) => t,
201        () => undefined,
202      ),
203    write: (path, text) => $.fs.write(path, text),
204    run: (argv) => $.process.run(argv, { timeoutMs: 5000 }),
205    mtime: (path) =>
206      $.fs.stat(path).then(
207        (s: { mtimeMs: number }) => s.mtimeMs,
208        () => undefined,
209      ),
210    sleep: (ms) => $.clock.sleep(ms),
211    now: () => Date.now(),
212  };
213}
214
215async function serve(
216  $: any,
217  tool: ToolName,
218  e: any,
219): Promise<{ result: string } | { deny: string }> {
220  const cfg = await config($);
221  if (!cfg)
222    return {
223      deny: "kodflow task tools: no absolute CLAUDE_CONFIG_DIR or HOME to keep the list in",
224    };
225  const session = await $.session.id();
226  const dir = sessionDir(cfg, session);
227  const io = port($);
228  const agent = e.agentId ? safe(e.agentId) : MAIN;
229  const nowSec = () => Math.floor(Date.now() / 1000);
230  let answer: { result: string } | { deny: string };
231  let closing: Closing | undefined;
232  try {
233    const step = plan(tool, agent, argsOf(e));
234    // The main agent completing a task: the list before the update is kept,
235    // since the update drops the task's worker link
236    const completing =
237      tool === "task_update" &&
238      agent === MAIN &&
239      argsOf(e).status === "completed";
240    let workers: ReturnType<typeof resolveWorkers> = [];
241    if (tool === "task_update") {
242      const listed = await $.agent.list().catch(() => undefined);
243      workers = resolveWorkers(
244        listed,
245        await io.read(agentsFile(dir)),
246        nowSec(),
247      );
248    }
249    const text = step.mutates
250      ? await mutate(io, dir, (data) => {
251          const before = completing ? JSON.parse(JSON.stringify(data)) : undefined;
252          const out = step.run(data, { now: nowSec(), workers });
253          if (before) closing = closingOf(before, data, argsOf(e).id);
254          return out;
255        })
256      : step.run(await load(io, dir, nowSec()), { now: nowSec(), workers });
257    answer = { result: text };
258  } catch (err) {
259    if (!isTaskError(err)) {
260      // Fail open: the store or the host failed, and a gate the task tools
261      // cannot settle would stop the session
262      if (mainLoop(e.agentId))
263        await io.run(["rm", "-f", triageFile(dir)]).catch(() => undefined);
264      throw err;
265    }
266    answer = { deny: err.message };
267  }
268  // A refusal leaves the gate as it was; a call that succeeded settles the
269  // causes it answers. Never at the cost of the answer of an applied change.
270  if ("result" in answer)
271    await settleTriage(io, dir, tool, argsOf(e), e.agentId).catch(
272      () => undefined,
273    );
274  // Started, never awaited: gh and git push reach the network, and the
275  // answer to the task call does not wait on them
276  if ("result" in answer && closing) void cleanupAfter($, dir, closing);
277  // One line in .claude/logs/<branch>/session.jsonl, through lib/event.jq
278  const payload = logPayload(session, await $.session.root(), e, answer);
279  await $.process
280    .run(["bash", `${$.plugin.root}/hooks/scripts/on-mod.sh`], {
281      stdin: JSON.stringify(payload),
282      timeoutMs: 3000,
283    })
284    .catch(() => undefined);
285  return answer;
286}
287
288// One line of structure and size for an MCP tool's result, in the session's
289// mcp-shapes.jsonl (mcp-probe.ts); KODFLOW_MCP_PROBE=off: nothing. The line
290// is built from the answer's shape only, and every failure is swallowed:
291// the result goes to the model as it is.
292async function probeMcp($: any, tool: string, answer: unknown): Promise<void> {
293  try {
294    if (isOff(await $.env.get("KODFLOW_MCP_PROBE"))) return;
295    const cfg = await config($);
296    if (!cfg) return;
297    const dir = sessionDir(cfg, await $.session.id());
298    await $.process.run(appendArgv(shapesFile(dir)), {
299      stdin: shapeLine(shapeOf(tool, answer, Date.now())),
300      timeoutMs: 3000,
301    });
302  } catch {
303    // fail open
304  }
305}
306
307// The worktrees of the workers a completion closes, to cleanup.sh, which
308// removes only what is merged, published and clean (KODFLOW_CLEANUP=off:
309// nothing). Every failure is swallowed: the task call has already answered.
310async function cleanupAfter($: any, dir: string, closing: Closing): Promise<void> {
311  try {
312    if (isOff(await $.env.get("KODFLOW_CLEANUP"))) return;
313    const io = port($);
314    const paths = await claim(io, dir, closing, await io.read(agentsFile(dir)));
315    if (!paths.length) return;
316    await $.process.run(
317      ["bash", `${$.plugin.root}/hooks/scripts/cleanup.sh`, dir, ...paths],
318      { timeoutMs: 300_000 },
319    );
320  } catch {
321    // fail open
322  }
323}
324
325// The worktrees a subagent writes into, noted once per path and session
326const noted = new Set<string>();
327async function noteWorktrees($: any, e: any): Promise<void> {
328  try {
329    const text =
330      typeof e.command === "string" ? e.command : JSON.stringify(argsOf(e));
331    const paths = worktreePaths(text.slice(0, 20_000), await $.env.get("HOME"));
332    if (!paths.length) return;
333    const cfg = await config($);
334    if (!cfg) return;
335    const dir = sessionDir(cfg, await $.session.id());
336    const fresh = paths.filter((p) => !noted.has(`${dir}\t${e.agentId}\t${p}`));
337    if (!fresh.length) return;
338    await note(port($), dir, String(e.agentId), fresh);
339    for (const p of fresh) noted.add(`${dir}\t${e.agentId}\t${p}`);
340  } catch {
341    // fail open
342  }
343}
344
345// Drop from triage-pending the causes this call settled: the file goes with
346// the last one, the others stay for their own gesture. Under the lock the
347// shell takes to append a cause (on-user.sh, on-session.sh), so a message
348// that arrives meanwhile is never lost; replaced through a temporary file
349// and `mv`, so the gate never reads half a list. A lock not obtained in time
350// is written through, as lib/lock.sh's callers do.
351async function settleTriage(
352  io: Port,
353  dir: string,
354  tool: ToolName,
355  args: Record<string, unknown>,
356  agentId: unknown,
357): Promise<void> {
358  if (!mainLoop(agentId)) return;
359  const file = triageFile(dir);
360  // Most calls find no gate, or answer none of its causes: no lock for them
361  const seen = await io.read(file);
362  if (seen === undefined) return;
363  const before = triageCauses(seen);
364  if (settleCauses(before, tool, args, agentId).length === before.length) return;
365  const lockDir = `${dir}/.triage.lock.d`;
366  const held = await lock(io, lockDir);
367  try {
368    const text = await io.read(file);
369    if (text === undefined) return;
370    const causes = triageCauses(text);
371    const left = settleCauses(causes, tool, args, agentId);
372    if (left.length === causes.length) return;
373    if (left.length === 0) {
374      await io.run(["rm", "-f", file]);
375      return;
376    }
377    const tmp = `${dir}/.triage.${unique()}.tmp`;
378    await io.write(tmp, `${left.join("\n")}\n`);
379    if ((await io.run(["mv", "-f", tmp, file])).exitCode !== 0)
380      await io.run(["rm", "-f", tmp]);
381  } finally {
382    if (held) await io.run(["rmdir", lockDir]);
383  }
384}
385
386// modwall, collision-guard and zsh-safe (machine-guards.ts) reach `$` through this
387function guardPort($: any): GuardPort {
388  return {
389    off: () => off($),
390    config: () => config($),
391    read: (path) =>
392      $.fs.read(path).then(
393        (t: string) => t,
394        () => undefined,
395      ),
396    write: (path, text) => $.fs.write(path, text),
397    list: (path) => $.fs.list(path),
398    session: () => $.session.id(),
399    cwd: () => $.session.cwd(),
400    ask: (question, options) =>
401      $.ui.ask(question, { options, header: "Collision" }),
402    storeGet: (key) => $.store.get(key),
403    storeSet: (key, value) => $.store.set(key, value),
404    log: (text) => $.ui.log(text, { to: "debug" }),
405    toast: (text) => $.ui.toast(text, { timeoutMs: 8000 }),
406    registerMods: (description) =>
407      $.command.register({ name: "kodflow-mods", description }),
408    zdotdir: () => $.env.get("ZDOTDIR"),
409    userZdotdir: () => $.env.get("KODFLOW_USER_ZDOTDIR"),
410    setZdotdir: (value) => $.env.set("ZDOTDIR", value),
411    setUserZdotdir: (value) => $.env.set("KODFLOW_USER_ZDOTDIR", value),
412    pluginRoot: $.plugin.root,
413    now: () => Date.now(),
414  };
415}
416
417// One line in .claude/logs/<branch>/session.jsonl for a policy's decision;
418// with `block` (a refusal), one more in the session's blocks.jsonl.
419function journal(
420  $: any,
421  e: any,
422  policy: string,
423  decision: string,
424  error?: unknown,
425  block?: Block,
426): void {
427  void (async () => {
428    const payload: Record<string, unknown> = {
429      hook_event_name: "ModPolicy",
430      session_id: await $.session.id(),
431      cwd: await $.session.cwd(),
432      tool_use_id: e.tool_use_id,
433      tool_name: e.tool,
434      tool_input: typeof e.command === "string" ? { command: e.command } : {},
435      reason: `${policy}:${decision}`,
436    };
437    if (e.agentId) payload.agent_id = e.agentId;
438    if (error !== undefined)
439      payload.error = String((error as Error)?.message ?? error);
440    if (block) payload.block = block;
441    await $.process.run(
442      ["bash", `${$.plugin.root}/hooks/scripts/on-mod.sh`],
443      { stdin: JSON.stringify(payload), timeoutMs: 3000 },
444    );
445  })().catch(() => undefined);
446}
447
448// The credential variables' values. $.env.get takes literal names only (the
449// engine lists what a module reads), so veil.ts's SECRET_VARS is spelled out
450// here, and tests/mod/pipeline.test.ts holds the two lists equal.
451async function secretValues($: any): Promise<string[]> {
452  const values: (string | undefined)[] = await Promise.all([
453    $.env.get("ANTHROPIC_API_KEY"),
454    $.env.get("ANTHROPIC_AUTH_TOKEN"),
455    $.env.get("CLAUDE_CODE_OAUTH_TOKEN"),
456    $.env.get("OPENAI_API_KEY"),
457    $.env.get("GITHUB_TOKEN"),
458    $.env.get("GH_TOKEN"),
459    $.env.get("GH_ENTERPRISE_TOKEN"),
460    $.env.get("GITLAB_TOKEN"),
461    $.env.get("GL_TOKEN"),
462    $.env.get("CI_JOB_TOKEN"),
463    $.env.get("NPM_TOKEN"),
464    $.env.get("NODE_AUTH_TOKEN"),
465    $.env.get("AWS_SECRET_ACCESS_KEY"),
466    $.env.get("AWS_SESSION_TOKEN"),
467    $.env.get("OP_SERVICE_ACCOUNT_TOKEN"),
468    $.env.get("OP_CONNECT_TOKEN"),
469    $.env.get("VAULT_TOKEN"),
470    $.env.get("NOMAD_TOKEN"),
471    $.env.get("CONSUL_HTTP_TOKEN"),
472    $.env.get("CLOUDFLARE_API_TOKEN"),
473    $.env.get("CF_API_TOKEN"),
474    $.env.get("SLACK_TOKEN"),
475    $.env.get("SLACK_BOT_TOKEN"),
476    $.env.get("DOCKER_PASSWORD"),
477    $.env.get("HF_TOKEN"),
478    $.env.get("GOOGLE_API_KEY"),
479    $.env.get("SENTRY_AUTH_TOKEN"),
480    $.env.get("DATABASE_URL"),
481  ]);
482  return values.filter((v): v is string => !!v);
483}
484
485async function projectDir($: any): Promise<string> {
486  return (await $.env.get("CLAUDE_PROJECT_DIR")) || (await $.session.cwd());
487}
488
489async function guardCtx(
490  $: any,
491  e: any,
492  patterns: () => Promise<Rules | undefined>,
493): Promise<GuardCtx> {
494  const dir = await projectDir($);
495  const cfg = await config($);
496  const agentId = e.agentId || undefined;
497  return {
498    agentId,
499    rootMain: !agentId && (await $.env.get("KODFLOW_ROOT")) !== "off",
500    projectDir: dir,
501    home: await $.env.get("HOME"),
502    configDir: cfg,
503    read: (path) =>
504      $.fs
505        .read(path.startsWith("/") ? path : `${dir}/${path}`)
506        .catch(() => undefined),
507    git: async (gdir, args) => {
508      const r = await $.process
509        .run(["git", "-C", gdir, ...args], { timeoutMs: 5000 })
510        .catch(() => undefined);
511      return r && r.exitCode === 0 ? r.stdout : undefined;
512    },
513    patterns,
514  };
515}
516
517// The gated list as this copy of the plugin ships it (hooks/gated-models.txt)
518const gatedText = ($: any): Promise<string | undefined> =>
519  $.fs.read(`${$.plugin.root}/hooks/gated-models.txt`).catch(() => undefined);
520
521// Who gave the session its grant, and when; the key is the session's. Only
522// $.store holds it: a file under the session directory could be written by
523// any tool call, so the shell never reads a grant and refuses without the mod.
524async function grantSession($: any, session: string, by: string): Promise<void> {
525  await $.store.set(grantKey(session), { at: Math.floor(Date.now() / 1000), by });
526}
527
528// One spawn judged at a time: two parallel dispatches on a gated model put
529// one question to the user, and the second reads the grant the first wrote.
530let judging: Promise<unknown> = Promise.resolve();
531
532// What agent.spawn's judge reaches; every raw value it reads is kept in `raw`
533// so that a throw can still refuse a spawn naming a gated model.
534async function spawnPort($: any, raw: unknown[]): Promise<SpawnPort & { skillFile: (s: string) => Promise<string | undefined> }> {
535  const session = await $.session.id();
536  return {
537    gated: () => gatedText($),
538    mode: async () => gateMode(await $.env.get("KODFLOW_FABLE")),
539    definition: async (type) => {
540      const cfg = await config($);
541      if (!cfg) return undefined;
542      const installed = await $.fs
543        .read(`${cfg}/plugins/installed_plugins.json`)
544        .catch(() => undefined);
545      for (const path of definitionPaths(type, {
546        project: await projectDir($).catch(() => undefined),
547        config: cfg,
548        installed,
549      })) {
550        const text = await $.fs.read(path).catch(() => undefined);
551        if (text !== undefined) {
552          raw.push(text.slice(0, 4000));
553          return text;
554        }
555      }
556      return undefined;
557    },
558    envModel: async () => {
559      const v = await $.env.get("CLAUDE_CODE_SUBAGENT_MODEL");
560      raw.push(v);
561      return v || undefined;
562    },
563    envForce: async () => forced(await $.env.get("CLAUDE_CODE_SUBAGENT_MODEL_FORCE")),
564    granted: async () => !!(await $.store.get(grantKey(session))),
565    skillFile: async (skill: string) => {
566      const cfg = await config($);
567      if (!cfg) return undefined;
568      const installed = await $.fs
569        .read(`${cfg}/plugins/installed_plugins.json`)
570        .catch(() => undefined);
571      for (const path of skillPaths(skill, { project: await projectDir($).catch(() => undefined), config: cfg, installed })) {
572        const text = await $.fs.read(path).catch(() => undefined);
573        if (text !== undefined) {
574          raw.push(text.slice(0, 4000));
575          return text;
576        }
577      }
578      return undefined;
579    },
580    grant: () => grantSession($, session, "asked at a spawn"),
581    present,
582    ask: (question, options) => $.ui.ask(question, { options, header: "Gated model" }),
583  };
584}
585
586export const register: Register = (on) => {
587  on("session.start", async ($, e, next) => {
588    if (!(await off($))) {
589      await ensureTools($);
590      await $.command.register({
591        name: "lint-setup",
592        description: LINT_SETUP.description,
593        argumentHint: LINT_SETUP.argumentHint,
594      });
595    }
596    await startGuards(guardPort($)).catch(() => undefined);
597    return next(e);
598  });
599
600  on("classic.SessionStart", async ($, e, next) => {
601    if (await off($)) return next(e);
602    await ensureTools($).catch(() => undefined);
603    await beat($, e.session_id, true);
604    const r = await next(e);
605    if (e.source !== "compact") return r;
606    const text = await humanAfterCompact($, e.session_id).catch(() => undefined);
607    return text
608      ? { ...r, additionalContext: [...(r.additionalContext ?? []), text] }
609      : r;
610  }).catch(($, e, next) => next(e));
611
612  on("prompt.submit", async ($, e, next) => {
613    notePrompt(e.origin, Date.now());
614    if (!(await off($))) {
615      await ensureTools($);
616      await beat($);
617      if ((e.origin as { kind?: unknown } | undefined)?.kind === "composer") {
618        const cfg = await config($);
619        if (cfg)
620          await $.fs
621            .write(composerFile(sessionDir(cfg, await $.session.id())), beatText(Date.now()))
622            .catch(() => undefined);
623      }
624    }
625    return next(e);
626  }).catch(($, e, next) => next(e));
627
628  // The gated-model rule at the spawn: pass or refuse, never a model written
629  on("agent.spawn", async ($, e, next) => {
630    const raw: unknown[] = [e.model, e.parentModel];
631    const at = { tool: "Agent", tool_use_id: e.tool_use_id, agentId: e.parentAgentId };
632    let verdict;
633    try {
634      if (await off($)) return next(e);
635      // Read before anything that can fail: a throw later still knows a
636      // gated CLAUDE_CODE_SUBAGENT_MODEL was there
637      raw.push(await $.env.get("CLAUDE_CODE_SUBAGENT_MODEL"));
638      const run = judging.then(async () => judgeSpawn(e, await spawnPort($, raw)));
639      judging = run.catch(() => undefined);
640      verdict = await run;
641    } catch (err) {
642      const tokens = failClosedTokens(await gatedText($));
643      const named = raw.find((r) => typeof r === "string" && isGated(r, tokens));
644      if (anyGated(raw, tokens)) {
645        const deny = fableRefusal(String(named), "the check failed");
646        journal($, at, "fable", "error-refused", err, blockOf(deny));
647        return { deny };
648      }
649      journal($, at, "fable", "error-passed", err);
650      await $.ui
651        .toast("kodflow-hooks: the gated-model check failed on a spawn naming no gated model; it went on", {
652          timeoutMs: 8000,
653        })
654        .catch(() => undefined);
655      return next(e);
656    }
657    const denied =
658      verdict.kind === "refuse" ? fableRefusal(verdict.model, verdict.why) : undefined;
659    journal($, at, "fable", `${verdict.kind}: ${verdict.why}`, undefined, blockOf(denied));
660    if (denied) return { deny: denied };
661    return next(e);
662  }).catch(($, e, next) => next(e));
663
664  // A skill pinned to a gated model would switch the main conversation to it
665  on("tool.call", { tool: "Skill" }, async ($, e, next) => {
666    const raw: unknown[] = [];
667    const skill = String((argsOf(e as any) as any)?.skill ?? "").replace(/^\//, "");
668    const at = { tool: "Skill", tool_use_id: e.tool_use_id, agentId: e.agentId };
669    let verdict;
670    try {
671      if (await off($) || !skill) return next(e);
672      const run = judging.then(async () => judgeSkill(skill, await spawnPort($, raw)));
673      judging = run.catch(() => undefined);
674      verdict = await run;
675    } catch (err) {
676      if (anyGated(raw, failClosedTokens(await gatedText($)))) {
677        const deny = fableRefusal(skill, "the check failed");
678        journal($, at, "fable", "error-refused", err, blockOf(deny));
679        return { deny };
680      }
681      journal($, at, "fable", "error-passed", err);
682      return next(e);
683    }
684    if (verdict.kind === "refuse") {
685      const deny = fableRefusal(verdict.model, verdict.why);
686      journal($, at, "fable", `refuse: ${verdict.why}`, undefined, blockOf(deny));
687      return { deny };
688    }
689    return next(e);
690  }).catch(($, e, next) => next(e));
691
692  // A /model the user types, or the picker, is the consent (D5); a switch from
693  // the SDK asks like a spawn, and is refused with nobody at the prompt
694  on("classic.PreModelSwitch", async ($, e, next) => {
695    const r = await next(e);
696    try {
697      if (await off($) || r.permissionDecision === "deny") return r;
698      const session = await $.session.id();
699      const v = judgeSwitch(e, parseGated(await gatedText($)), gateMode(await $.env.get("KODFLOW_FABLE")));
700      const at = { tool: "PreModelSwitch", tool_use_id: e.prompt_id };
701      if (v.kind === "grant") await grantSession($, session, v.why);
702      let deny: string | undefined;
703      if (v.kind === "ask" && !(await $.store.get(grantKey(session)))) {
704        let answer = "nobody at the prompt";
705        if (present()) {
706          answer = await $.ui
707            .ask(`Switch this session to ${e.to_model}, a gated model (${v.why})?`, {
708              options: ["Switch", "Stay"],
709              header: "Gated model",
710            })
711            .catch(() => "dismissed");
712        }
713        if (answer === "Switch") await grantSession($, session, `asked at a ${v.why}`);
714        else deny = fableRefusal(String(e.to_model), `${v.why}; ${answer}`);
715      }
716      journal($, at, "fable", deny ? `refuse: ${v.why}` : `${v.kind}: ${v.why}`, undefined, blockOf(deny));
717      return deny ? { ...r, permissionDecision: "deny", permissionDecisionReason: deny } : r;
718    } catch (err) {
719      // After next(e): answer from r, never call next again. A gated target
720      // from anywhere but the user's own /model is refused.
721      const gated = isGated(e.to_model, failClosedTokens(await gatedText($)));
722      if (!gated || e.source === "command" || e.source === "picker") return r;
723      return { ...r, permissionDecision: "deny", permissionDecisionReason: fableRefusal(String(e.to_model), `the check failed: ${String((err as Error)?.message ?? err)}`) };
724    }
725  }).catch(($, e, next) => next(e));
726
727  on("tool.call", async ($, e, next) => {
728    if (await off($)) return next(e);
729    const tool = taskTool(e.tool);
730    // Before next: the shell's PreToolUse runs inside it and reads the beat
731    await beat($).catch(() => undefined);
732    if (tool) return serve($, tool, e);
733    if (e.agentId && WRITING_TOOLS.has(e.tool)) void noteWorktrees($, e);
734    // A forge tool writing an mcp.json: refused for every caller, as the
735    // shell does; doubled, so a failure lets the call on to the shell
736    if (/^mcp__(github|gitlab|GitKraken)__/.test(e.tool)) {
737      try {
738        const mj = await forgeMcpJson(
739          e.tool,
740          argsOf(e as any) ?? {},
741          await guardCtx($, e, async () => rules),
742        );
743        if (mj) {
744          journal($, e, "mcp-json", "deny", undefined, { motif: mj.motif, title: mj.title });
745          return { deny: refusalText(mj) };
746        }
747      } catch (err) {
748        journal($, e, "mcp-json", "error", err);
749      }
750    }
751    const r: any = await next(e);
752    let out = r;
753    try {
754      secrets ??= secretValues($);
755      const veiled = veilResult(r, { envValues: await secrets, now: Date.now });
756      if (veiled !== r) journal($, e, "veil", "masked");
757      out = veiled;
758    } catch (err) {
759      journal($, e, "veil", "error", err);
760    }
761    if (isMcpTool(e.tool)) await probeMcp($, e.tool, out);
762    return out;
763  }).catch(($, e, next) => {
764    if (next.called) return next(e);
765    if (taskTool(e.tool))
766      return {
767        deny: `kodflow task tools failed: ${next.error.message ?? next.error.kind}`,
768      };
769    return next(e);
770  });
771
772  on("tool.call", { tool: "Bash" }, async ($, e, next) => {
773    if (await off($)) return next(e);
774    const line = typeof e.command === "string" ? e.command : "";
775    let refused: Block | undefined;
776    return runBash(() => next(e), {
777      guards: async () => {
778        rules ??= await loadRules(
779          (path) => $.fs.read(path),
780          `${$.plugin.root}/hooks/patterns`,
781        );
782        const ctx = await guardCtx($, e, async () => rules);
783        const found = await inspect(line, ctx);
784        const refusal = found && (await verdict(line, found, ctx));
785        if (!refusal) return undefined;
786        refused = { motif: refusal.motif, title: refusal.title };
787        return { deny: refusalText(refusal) };
788      },
789      filter: async (r) => filterResult(line, r),
790      log: (policy, decision, error) =>
791        journal($, e, policy, decision, error, decision === "deny" ? refused : undefined),
792    });
793  }).catch(($, e, next) => next(e));
794
795  on("command.run", { command: "lint-setup" }, async ($, e) => {
796    try {
797      return { text: await lintSetup(await lintPort($), e.args ?? "") };
798    } catch (err: any) {
799      return { text: `/lint-setup failed: ${err?.message ?? String(err)}` };
800    }
801  });
802
803  on("attribution.text", async ($, e, next) => {
804    const text = attributionText(e.kind);
805    return text === undefined || (await off($)) ? next(e) : { text };
806  });
807
808  // modwall: refuses a user-tier module from outside the kodflow marketplace
809  on("plugin.register", async ($, e, next) => {
810    const refused = await admit(guardPort($), e);
811    return refused ?? next(e);
812  }).catch(($, e, next) => next(e));
813
814  on("command.run", { command: "kodflow-mods" }, async ($) => ({
815    text: await modsReport(guardPort($)),
816  }));
817
818  on("session.end", async ($, e, next) => {
819    await endGuards(guardPort($)).catch(() => undefined);
820    return next(e);
821  });
822
823  // collision-guard: a file another live session wrote in the last 30 min
824  on("tool.call", { tool: ["Edit", "Write", "MultiEdit", "NotebookEdit"] }, async ($, e, next) =>
825    guardWrite(guardPort($), e as any, () => next(e)),
826  ).catch(($, e, next) => next(e));
827};
828
hooks/mod/tasks.ts 1224 lines
1// tasks.ts — the session task list, one list per agent. Pure: no `$`, no I/O.
2//
3// Tasks are grouped in epics, one per subject. An agent can have several epics
4// open at once; one of them is active (the one being worked on). Every task
5// names its epic when it is created — there is no default. The file format
6// (tasks.json, version 2) is a contract shared with the status line and the
7// shell hooks (lib/epics.jq), which read it directly.
8//
9// This is a line-for-line port of the former mcp/tasks.py: same messages, same
10// order of validation, timestamps in seconds, lengths in code points. The
11// conformance corpus (tests/mod/conformance.corpus.ts), recorded from tasks.py,
12// holds it to that.
13//
14// One tool came after the port: task_assign_human files a task only the user
15// can do (a "go", a Touch ID, a gesture on a NAS). It is a task like the
16// others, with `assignee: "human"` and the status `waiting`, so the readers
17// of tasks.json that know nothing of the field still count it right.
18//
19// The task tree came after it too (kodflow-hud draws it): three optional
20// fields a task carries only once set, so a file without them is read as
21// before and every reader that ignores them (the status line decodes named
22// fields, lib/epics.jq picks the ones it uses) reads version 2 unchanged:
23// `parent`, the task it is a subtask of (three levels at most); `blockedBy`,
24// the tasks it waits on; `ref`, a short handle (T0, C6) the tree shows.
25
26/** A task title: the tree cuts it at 18 cells, the detail line shows it whole; tasks.py allowed 40. */
27export const MAX_SUBJECT = 30;
28export const MAX_TITLE = 20;
29/** A ref is a handle (T0, C6, #12), not a name. */
30export const MAX_REF = 5;
31/** Task, subtask, sub-subtask. */
32export const MAX_DEPTH = 3;
33export const STATUSES = [
34  "pending",
35  "in_progress",
36  "waiting",
37  "completed",
38  "deleted",
39] as const;
40export const MAIN = "main";
41/** `assignee` of a task only the user can do (task_assign_human). */
42export const HUMAN = "human";
43/** At most this many of them open at once: a queue nobody reads is noise. */
44export const MAX_HUMAN_OPEN = 5;
45
46/** A refusal the caller reads: the tool answers `{ deny: message }`. */
47export class TaskError extends Error {
48  readonly kind = "task-error";
49}
50
51export function isTaskError(err: unknown): err is TaskError {
52  return (
53    typeof err === "object" &&
54    err !== null &&
55    (err as { kind?: unknown }).kind === "task-error"
56  );
57}
58
59type Obj = Record<string, any>;
60export type Data = Obj & {
61  version: 2;
62  next_id: number;
63  next_epic: number;
64  epics: Obj[];
65  active: Record<string, any>;
66  tasks: Obj[];
67};
68
69/** A subagent of the session, as the caller resolved it. */
70export type Worker = {
71  id: string;
72  type: string;
73  name?: string;
74  alive: boolean;
75  started?: number;
76};
77
78/** What a step reads from the world: the time in seconds, the subagents. */
79export type Ctx = { now: number; workers: readonly Worker[] };
80
81// --- Python semantics the port depends on -----------------------------------
82
83const isObj = (v: unknown): v is Obj =>
84  typeof v === "object" && v !== null && !Array.isArray(v);
85const isInt = (v: unknown): v is number =>
86  typeof v === "number" && Number.isInteger(v);
87// dict.get(key, default): a key present with null keeps null
88const get = (o: Obj, k: string, d: unknown): any =>
89  Object.hasOwn(o, k) ? o[k] : d;
90// `x or y`
91const truthy = (v: unknown): boolean =>
92  !(
93    v === undefined ||
94    v === null ||
95    v === false ||
96    v === 0 ||
97    v === "" ||
98    (Array.isArray(v) && v.length === 0) ||
99    (isObj(v) && Object.keys(v).length === 0)
100  );
101const or = <T>(v: unknown, d: T): any => (truthy(v) ? v : d);
102
103/** str(value) for the JSON values a tool call can carry. */
104export function pyStr(v: unknown): string {
105  if (typeof v === "string") return v;
106  if (v === undefined || v === null) return "None";
107  if (v === true) return "True";
108  if (v === false) return "False";
109  if (typeof v === "number") return String(v);
110  return JSON.stringify(v);
111}
112
113// str.strip(): Python's whitespace, not JavaScript's (\x1c-\x1f in,  out)
114const WS =
115  "\\t\\n\\x0b\\x0c\\r\\x1c-\\x1f \\x85\\xa0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000";
116const STRIP = new RegExp(`^[${WS}]+|[${WS}]+$`, "gu");
117export const strip = (s: string): string => s.replace(STRIP, "");
118
119/** len(): code points, not UTF-16 units. */
120export const codePoints = (s: string): number => [...s].length;
121
122// --- the file ----------------------------------------------------------------
123
124/**
125 * Bring a tasks.json of any earlier shape to version 2, in memory.
126 *
127 * v1 kept one epic per agent, {"<agent>": {"id", "title"}}; v2 keeps a list
128 * of epics, several open at once, and the agent's active one in `active`.
129 * The file is rewritten in v2 by the next mutation.
130 */
131export function upgrade(raw: unknown, now: number): Data {
132  const data: Obj = isObj(raw) ? raw : {};
133  let epics: any = data.epics;
134  const active: Obj = isObj(data.active) ? data.active : {};
135  if (isObj(epics)) {
136    const converted: Obj[] = [];
137    for (const [agent, epic] of Object.entries(epics)) {
138      if (isObj(epic) && isInt(epic.id)) {
139        converted.push({
140          id: epic.id,
141          agent,
142          title: pyStr(or(epic.title, "")),
143          created: now,
144          touched: now,
145        });
146        active[agent] = epic.id;
147      }
148    }
149    epics = converted;
150  }
151  if (!Array.isArray(epics)) epics = [];
152  epics = epics.filter((e: unknown) => isObj(e) && isInt(e.id));
153  let tasks: any[] = Array.isArray(data.tasks) ? data.tasks : [];
154  tasks = tasks.filter((t) => isObj(t) && Object.hasOwn(t, "id"));
155  for (const task of tasks) {
156    task.id = pyStr(task.id);
157    if (!Object.hasOwn(task, "agent")) task.agent = MAIN;
158    if (!Object.hasOwn(task, "status")) task.status = "pending";
159    if (!Object.hasOwn(task, "subject")) task.subject = "";
160    if (!isInt(task.epic)) task.epic = 0;
161  }
162  const ids: number[] = epics.map((e: Obj) => e.id);
163  const highest = ids.length ? Math.max(...ids) : 0;
164  Object.assign(data, {
165    version: 2,
166    next_id: isInt(data.next_id) ? data.next_id : 1,
167    next_epic: Math.max(
168      isInt(data.next_epic) ? data.next_epic : 1,
169      highest + 1,
170    ),
171    epics,
172    active,
173    tasks,
174  });
175  return data as Data;
176}
177
178/** Parse the file's text; anything unreadable is an empty list. */
179export function parse(text: string | undefined, now: number): Data {
180  let raw: unknown = {};
181  if (text !== undefined) {
182    try {
183      raw = JSON.parse(text);
184    } catch {
185      raw = {};
186    }
187  }
188  return upgrade(raw, now);
189}
190
191/** The file's text, as tasks.py wrote it (indent 1, UTF-8 kept). */
192export const serialize = (data: Data): string => JSON.stringify(data, null, 1);
193
194// --- validation ----------------------------------------------------------------
195
196function checkText(
197  value: unknown,
198  what: string,
199  limit: number,
200  hint: string,
201): string {
202  const v = strip(pyStr(or(value, "")));
203  if (!v) throw new TaskError(`${what} is required`);
204  const n = codePoints(v);
205  if (n > limit)
206    throw new TaskError(
207      `${what} is ${n} characters, the limit is ${limit}: ${hint}`,
208    );
209  return v;
210}
211
212const checkSubject = (subject: unknown): string =>
213  checkText(
214    subject,
215    "subject",
216    MAX_SUBJECT,
217    "it is the title column of the task tree and is shown in full on the status line. " +
218      "Shorten it to an imperative title and move the detail to description.",
219  );
220
221/** A ref given: the handle, or "" to clear it. */
222function checkRef(value: unknown): string {
223  const v = strip(pyStr(value));
224  const n = codePoints(v);
225  if (n > MAX_REF)
226    throw new TaskError(
227      `ref is ${n} characters, the limit is ${MAX_REF}: a short handle such as T0 or C6, ` +
228        'shown in the tree\'s identifier column; ref="" clears it.',
229    );
230  return v;
231}
232
233/** A task id as a caller spells it: "12", "#12" or 12. */
234const idOf = (value: unknown): string => strip(pyStr(value)).replace(/^#+/, "");
235
236/** blocked_by given: a list of ids (or one, or "3, 4"), once each, in order. */
237function checkIds(value: unknown): string[] {
238  const items = Array.isArray(value) ? value : pyStr(value).split(/[\s,]+/);
239  const ids: string[] = [];
240  for (const item of items) {
241    const id = idOf(item);
242    if (id && !ids.includes(id)) ids.push(id);
243  }
244  return ids;
245}
246
247const checkTitle = (title: unknown): string =>
248  checkText(
249    title,
250    "title",
251    MAX_TITLE,
252    "it is the label of a pill on the status line. Use a short noun phrase " +
253      '("SDK status-line", "api-gateway").',
254  );
255
256// --- epics ---------------------------------------------------------------------
257
258const agentEpics = (data: Data, agent: string): Obj[] =>
259  data.epics.filter((e) => get(e, "agent", MAIN) === agent);
260
261function findEpic(data: Data, agent: string, epicId: unknown): Obj | undefined {
262  return agentEpics(data, agent).find((e) => e.id === epicId);
263}
264
265/** The id of the agent's active epic, 0 when it has none. */
266function activeEpic(data: Data, agent: string): any {
267  const epicId = get(data.active, agent, 0);
268  return findEpic(data, agent, epicId) ? epicId : 0;
269}
270
271const tasksOf = (data: Data, agent: string, epicId: unknown): Obj[] =>
272  data.tasks.filter(
273    (t) => get(t, "agent", MAIN) === agent && get(t, "epic", 0) === epicId,
274  );
275
276function progress(
277  data: Data,
278  agent: string,
279  epicId: unknown,
280): [number, number] {
281  const tasks = tasksOf(data, agent, epicId);
282  return [tasks.filter((t) => t.status === "completed").length, tasks.length];
283}
284
285/** Open: a task not completed, or the active epic with no task yet. */
286function isOpen(data: Data, agent: string, epic: Obj): boolean {
287  const [done, total] = progress(data, agent, epic.id);
288  return done < total || (total === 0 && activeEpic(data, agent) === epic.id);
289}
290
291/** The agent's open epics, most recently touched first. */
292function openEpics(data: Data, agent: string): Obj[] {
293  return agentEpics(data, agent)
294    .filter((e) => isOpen(data, agent, e))
295    .sort((a, b) => get(b, "touched", 0) - get(a, "touched", 0));
296}
297
298function touch(data: Data, agent: string, epicId: unknown, now: number): void {
299  const epic = findEpic(data, agent, epicId);
300  if (epic) epic.touched = now;
301}
302
303function parseEpicId(value: unknown): number | null {
304  const text = strip(pyStr(value)).replace(/^#+/, "");
305  return /^[0-9]+$/.test(text) ? parseInt(text, 10) : null;
306}
307
308function describeOpen(data: Data, agent: string): string {
309  const epics = openEpics(data, agent);
310  if (epics.length === 0) return "no epic is open";
311  const active = activeEpic(data, agent);
312  return (
313    "open epics: " +
314    epics
315      .map((e) => `#${e.id} ${e.title}${e.id === active ? " (active)" : ""}`)
316      .join(", ")
317  );
318}
319
320const EPIC_SYNTAX =
321  "task_create(subject, epic=<id>) files the task in one of your epics; epic=0 files it outside " +
322  "any epic; task_epic(title) opens a new epic first.";
323
324// --- workers ---------------------------------------------------------------------
325
326/** A worker is named by its agent id, its SendMessage name or its type. */
327const matches = (w: Worker, name: string): boolean =>
328  name === w.id || name === (w.type || "") || (!!w.name && name === w.name);
329
330/**
331 * Whether the worker linked to a task is still running, by its recorded id
332 * alone: an agent resumed by SendMessage keeps its id (measured on 2.1.296).
333 */
334function workerAlive(workers: readonly Worker[], task: Obj): boolean {
335  const entry = workers.find((w) => w.id === (task.worker_id || ""));
336  return entry !== undefined && entry.alive;
337}
338
339function since(started: number, now: number): string {
340  const minutes = Math.max(
341    0,
342    Math.floor(Math.trunc(now - (started || 0)) / 60),
343  );
344  return minutes >= 60
345    ? `${Math.floor(minutes / 60)}h${String(minutes % 60).padStart(2, "0")}`
346    : `${minutes} min`;
347}
348
349/** Who is counted: the running workers, and who holds each task in progress. */
350function workersReport(ctx: Ctx, data: Data, agent: string): string {
351  const live = ctx.workers
352    .filter((w) => w.alive)
353    .map((w, i) => [w, i] as const)
354    .sort(([a, i], [b, j]) => (a.started || 0) - (b.started || 0) || i - j)
355    .map(([w]) => w);
356  const lines = [
357    "Running subagents: " +
358      (live
359        .map((w) =>
360          w.started === undefined
361            ? `${w.type || "?"} (id ${w.id})`
362            : `${w.type || "?"} (id ${w.id}, for ${since(w.started, ctx.now)})`,
363        )
364        .join(", ") || "none"),
365  ];
366  for (const t of data.tasks) {
367    if (get(t, "agent", MAIN) !== agent || t.status !== "in_progress") continue;
368    if (truthy(t.worker)) {
369      lines.push(
370        `#${t.id} ${t.subject}: worker ${t.worker} (${workerAlive(ctx.workers, t) ? "running" : "STOPPED"})`,
371      );
372    } else {
373      lines.push(`#${t.id} ${t.subject}: no worker linked`);
374    }
375  }
376  return lines.join("\n");
377}
378
379/** Resolve the worker a task is handed to; refuse a stopped or busy one. */
380function claimWorker(
381  ctx: Ctx,
382  data: Data,
383  agent: string,
384  taskId: string,
385  worker: string,
386): string {
387  const named = ctx.workers.filter((w) => matches(w, worker));
388  const running = named.filter((w) => w.alive);
389  const unblock =
390    "Name a running subagent (its type or id, listed above) with worker=, or start one for this task " +
391    "first; a task nobody runs stays pending.";
392  if (running.length === 0) {
393    const why = named.length
394      ? "is stopped"
395      : "is not a subagent of this session";
396    throw new TaskError(
397      `cannot start #${taskId} on worker ${worker}: it ${why}.\n${workersReport(ctx, data, agent)}\n${unblock}`,
398    );
399  }
400  const holding = new Map<string, Obj>();
401  for (const t of data.tasks) {
402    if (
403      get(t, "agent", MAIN) === agent &&
404      t.status === "in_progress" &&
405      t.id !== taskId &&
406      truthy(t.worker_id)
407    ) {
408      holding.set(t.worker_id, t);
409    }
410  }
411  const free = running.filter((w) => !holding.has(w.id));
412  if (free.length === 0) {
413    const t = holding.get(running[0]!.id)!;
414    throw new TaskError(
415      `cannot start #${taskId} on worker ${worker}: it already holds #${t.id} ${t.subject}. One task per worker: set #${t.id} to ` +
416        `completed, pending or waiting first, or hand this one to another subagent.\n${workersReport(ctx, data, agent)}`,
417    );
418  }
419  return free[0]!.id;
420}
421
422/**
423 * How many tasks an agent may have in progress: one per worker.
424 *
425 * A subagent is one worker. The main agent is one worker plus every
426 * subagent it has running: a task handed to a subagent is in progress
427 * while that subagent works, and only then.
428 */
429const inProgressCap = (ctx: Ctx, agent: string): number =>
430  agent === MAIN ? 1 + ctx.workers.filter((w) => w.alive).length : 1;
431
432// --- the tree ------------------------------------------------------------------------
433
434const taskOf = (data: Data, agent: string, id: string): Obj | undefined =>
435  data.tasks.find((t) => t.id === id && get(t, "agent", MAIN) === agent);
436
437/** 1 for a task with no parent; a parent naming nothing ends the chain. */
438function depthOf(data: Data, agent: string, task: Obj): number {
439  const seen = new Set<string>();
440  let depth = 1;
441  for (let t = task; truthy(t.parent) && !seen.has(t.id); depth++) {
442    seen.add(t.id);
443    const up = taskOf(data, agent, pyStr(t.parent));
444    if (!up) break;
445    t = up;
446  }
447  return depth;
448}
449
450/** Levels under a task: 0 for a leaf, 1 with children, 2 with grandchildren. */
451function heightOf(data: Data, agent: string, id: string, seen = new Set<string>()): number {
452  if (seen.has(id)) return 0;
453  seen.add(id);
454  let height = 0;
455  for (const t of data.tasks)
456    if (get(t, "agent", MAIN) === agent && pyStr(get(t, "parent", "")) === id)
457      height = Math.max(height, 1 + heightOf(data, agent, t.id, seen));
458  return height;
459}
460
461/**
462 * File `task` under `parentId`, "" taking it out of any: the parent exists in
463 * the agent's list, is in the same epic, is neither the task nor under it,
464 * and the task with its own subtasks still fits in MAX_DEPTH levels.
465 */
466function setParent(data: Data, agent: string, task: Obj, parentId: string): void {
467  if (!parentId) {
468    delete task.parent;
469    return;
470  }
471  const parent = taskOf(data, agent, parentId);
472  if (!parent)
473    throw new TaskError(
474      `parent: no task #${parentId} in this agent's list to file #${task.id} under`,
475    );
476  for (let t: Obj | undefined = parent, i = 0; t && i <= data.tasks.length; i++) {
477    if (t.id === task.id)
478      throw new TaskError(
479        `parent: #${task.id} cannot go under #${parentId}, which is #${task.id} itself or one of its subtasks: that would be a cycle`,
480      );
481    t = truthy(t.parent) ? taskOf(data, agent, pyStr(t.parent)) : undefined;
482  }
483  const epic = get(task, "epic", 0);
484  if (get(parent, "epic", 0) !== epic)
485    throw new TaskError(
486      `parent: #${parentId} is in epic #${get(parent, "epic", 0)} and #${task.id} in epic #${epic}: a subtask is filed in its parent's epic`,
487    );
488  const depth = depthOf(data, agent, parent) + 1 + heightOf(data, agent, task.id);
489  if (depth > MAX_DEPTH)
490    throw new TaskError(
491      `parent: under #${parentId}, #${task.id} would reach ${depth} levels, the limit is ${MAX_DEPTH} ` +
492        "(task, subtask, sub-subtask): file it higher up, or split the subject into its own task",
493    );
494  task.parent = parentId;
495}
496
497/** The chain from `from` to `to` along blockedBy, when there is one. */
498function waitPath(data: Data, agent: string, from: string, to: string): string[] | undefined {
499  const seen = new Set<string>();
500  const walk = (id: string): string[] | undefined => {
501    if (id === to) return [id];
502    if (seen.has(id)) return undefined;
503    seen.add(id);
504    const t = taskOf(data, agent, id);
505    for (const next of Array.isArray(t?.blockedBy) ? t!.blockedBy : []) {
506      const rest = walk(pyStr(next));
507      if (rest) return [id, ...rest];
508    }
509    return undefined;
510  };
511  return walk(from);
512}
513
514/**
515 * Make `task` wait on `ids`, [] for none: each one exists in the agent's
516 * list, is not the task, and does not already wait on it, however far.
517 */
518function setBlockers(data: Data, agent: string, task: Obj, ids: string[]): void {
519  if (!ids.length) {
520    delete task.blockedBy;
521    return;
522  }
523  for (const id of ids) {
524    if (id === task.id)
525      throw new TaskError(`blocked_by: #${task.id} cannot wait on itself`);
526    if (!taskOf(data, agent, id))
527      throw new TaskError(`blocked_by: no task #${id} in this agent's list`);
528    const path = waitPath(data, agent, id, task.id);
529    if (path)
530      throw new TaskError(
531        `blocked_by: #${task.id} waiting on #${id} would be a cycle, #${id} already waits on #${task.id} ` +
532          `(${path.map((p) => `#${p}`).join(" → ")})`,
533      );
534  }
535  task.blockedBy = ids;
536}
537
538/** A deleted task leaves no dangling link: its subtasks go up a level. */
539function unlink(data: Data, agent: string, gone: Obj): void {
540  for (const t of data.tasks) {
541    if (get(t, "agent", MAIN) !== agent) continue;
542    if (pyStr(get(t, "parent", "")) === gone.id) {
543      if (truthy(gone.parent)) t.parent = gone.parent;
544      else delete t.parent;
545    }
546    if (Array.isArray(t.blockedBy) && t.blockedBy.some((b: unknown) => pyStr(b) === gone.id)) {
547      t.blockedBy = t.blockedBy.filter((b: unknown) => pyStr(b) !== gone.id);
548      if (!t.blockedBy.length) delete t.blockedBy;
549    }
550  }
551}
552
553/** What task_create and task_update take beyond tasks.py's arguments. */
554type TreeArgs = { parent?: string; blockers?: string[]; ref?: string };
555
556const given = (v: unknown): boolean => v !== undefined && v !== null;
557
558function treeArgs(args: Obj): TreeArgs {
559  const out: TreeArgs = {};
560  if (given(args.parent)) out.parent = idOf(args.parent);
561  if (given(args.blocked_by)) out.blockers = checkIds(args.blocked_by);
562  if (given(args.ref)) out.ref = checkRef(args.ref);
563  return out;
564}
565
566function applyTree(data: Data, agent: string, task: Obj, tree: TreeArgs): void {
567  if (tree.parent !== undefined) setParent(data, agent, task, tree.parent);
568  if (tree.blockers !== undefined) setBlockers(data, agent, task, tree.blockers);
569  if (tree.ref !== undefined) {
570    if (tree.ref) task.ref = tree.ref;
571    else delete task.ref;
572  }
573}
574
575// --- the tools ---------------------------------------------------------------------
576
577/** A tool call checked: whether it writes, and the change it makes. */
578export type Step = { mutates: boolean; run: (data: Data, ctx: Ctx) => string };
579
580function taskCreate(agent: string, args: Obj): Step {
581  const subject = checkSubject(args.subject);
582  const tree = treeArgs(args);
583  const wanted = args.epic;
584  return {
585    mutates: true,
586    run(data, ctx) {
587      // No default epic: a task that silently lands in whatever epic happens
588      // to be active is how work gets filed under the wrong subject. The
589      // caller names the epic every time, 0 included.
590      if (
591        wanted === undefined ||
592        wanted === null ||
593        strip(pyStr(wanted)) === ""
594      ) {
595        throw new TaskError(
596          `epic is required: name the epic this task belongs to; ${describeOpen(data, agent)}. ${EPIC_SYNTAX}`,
597        );
598      }
599      const epicId = parseEpicId(wanted);
600      if (epicId === null || (epicId !== 0 && !findEpic(data, agent, epicId))) {
601        throw new TaskError(
602          `no epic ${pyStr(wanted)} for this agent; ${describeOpen(data, agent)}. ${EPIC_SYNTAX}`,
603        );
604      }
605      const task = {
606        id: String(data.next_id),
607        agent,
608        epic: epicId,
609        subject,
610        description: or(args.description, ""),
611        status: "pending",
612        created: ctx.now,
613        updated: ctx.now,
614      };
615      applyTree(data, agent, task, tree);
616      data.next_id += 1;
617      data.tasks.push(task);
618      touch(data, agent, epicId, ctx.now);
619      let note = "";
620      if (epicId && epicId !== activeEpic(data, agent)) {
621        note = ` (epic #${epicId} is not the active one: task_focus it when you start working on it)`;
622      } else if (epicId) {
623        note = ` in epic #${epicId} ${findEpic(data, agent, epicId)!.title}`;
624      }
625      return `Task #${task.id} created: ${subject}${note}${flowNote(data, agent, epicId)}`;
626    },
627  };
628}
629
630/** Pending tasks in one epic before the flow note speaks. */
631export const FLOW_NOTE_AT = 3;
632
633/**
634 * A plan filed as a flat list says nothing of what waits on what, so nobody
635 * can tell which tasks may run side by side. Not a refusal: a list of truly
636 * independent tasks is legitimate, and they are then all ready at once. The
637 * note is said once, the moment the epic reaches FLOW_NOTE_AT pending tasks
638 * with no blocked_by anywhere in it; it writes nothing to the file.
639 */
640function flowNote(data: Data, agent: string, epicId: number): string {
641  if (!epicId) return "";
642  const mine = data.tasks.filter(
643    (t) => get(t, "agent", MAIN) === agent && get(t, "epic", 0) === epicId,
644  );
645  if (mine.some((t) => Array.isArray(t.blockedBy) && t.blockedBy.length))
646    return "";
647  const pending = mine.filter((t) => t.status === "pending").length;
648  if (pending !== FLOW_NOTE_AT) return "";
649  return (
650    `. Note: epic #${epicId} has ${pending} pending tasks and no blocked_by between them. ` +
651    "If some wait on others, declare it (task_update(id, blocked_by=[...])) so the order of " +
652    "implementation is in the list; tasks left with no blocker are all ready and run in parallel."
653  );
654}
655
656function taskUpdate(agent: string, args: Obj): Step {
657  const taskId = strip(pyStr(or(args.id, ""))).replace(/^#+/, "");
658  // A caller that names the argument something else — task_id is the common
659  // slip — would otherwise look the empty id up and be told "no task # in
660  // this agent's list", which sends the reader hunting for an ownership
661  // problem instead of a missing argument.
662  if (!taskId) throw new TaskError('task_update needs the task id: id="36"');
663  const status = args.status;
664  let subject = args.subject;
665  if (
666    status !== undefined &&
667    status !== null &&
668    !(STATUSES as readonly unknown[]).includes(status)
669  ) {
670    throw new TaskError(`status must be one of ${STATUSES.join(", ")}`);
671  }
672  if (subject !== undefined && subject !== null)
673    subject = checkSubject(subject);
674  const tree = treeArgs(args);
675  // worker only means something on a start; with any other status it is
676  // ignored, and leaving in_progress drops the link anyway
677  const worker =
678    status === "in_progress" ? strip(pyStr(or(args.worker, ""))) : "";
679  return {
680    mutates: true,
681    run(data, ctx) {
682      const idx = data.tasks.findIndex(
683        (t) => t.id === taskId && get(t, "agent", MAIN) === agent,
684      );
685      if (idx < 0)
686        throw new TaskError(`no task #${taskId} in this agent's list`);
687      const task = data.tasks[idx]!;
688      touch(data, agent, get(task, "epic", 0), ctx.now);
689      if (status === "deleted") {
690        data.tasks.splice(idx, 1);
691        unlink(data, agent, task);
692        return `Task #${taskId} deleted`;
693      }
694      // The tree is checked before anything moves: a refusal leaves it as it was
695      applyTree(data, agent, task, tree);
696      // Nobody but the user works on the user's task: no start, no worker
697      if (
698        isHuman(task) &&
699        (status === "in_progress" || status === "pending")
700      ) {
701        throw new TaskError(
702          `#${taskId} is assigned to the user: it stays waiting until they answer, then completed (or deleted when it no longer applies).`,
703        );
704      }
705      // One task in progress per worker: an amber cell on the status
706      // line must mean someone is on it right now
707      const starting =
708        status === "in_progress" && task.status !== "in_progress";
709      if (worker) {
710        // A named worker is checked for itself: running, and on no other
711        // task. The headcount below cannot tell a task held by a live
712        // subagent from one left by a dead one.
713        task.worker_id = claimWorker(ctx, data, agent, taskId, worker);
714        task.worker = worker;
715      } else if (starting) {
716        const busy = data.tasks.filter(
717          (t) =>
718            get(t, "agent", MAIN) === agent &&
719            t.status === "in_progress" &&
720            t.id !== taskId,
721        );
722        const cap = inProgressCap(ctx, agent);
723        if (busy.length >= cap) {
724          const workers =
725            cap === 1 ? "you" : `you and ${cap - 1} running subagent(s)`;
726          throw new TaskError(
727            `cannot start #${taskId}: ${busy.length} task(s) already in progress (${busy.map((t) => `#${t.id} ${t.subject}`).join(", ")}) ` +
728              `for ${cap} worker(s), ${workers}.\n${workersReport(ctx, data, agent)}\n` +
729              "One task per worker: complete a task nobody is on, or set it to pending or waiting; " +
730              "to hand this one to a running subagent, pass worker=<its type or id> with " +
731              "status=in_progress (refused if that subagent is stopped or already holds a task).",
732          );
733        }
734      }
735      if (truthy(status) && status !== "in_progress") {
736        // The link lasts as long as the task is in progress
737        delete task.worker;
738        delete task.worker_id;
739      }
740      if (truthy(status)) task.status = status;
741      if (truthy(subject)) task.subject = subject;
742      if (args.description !== undefined && args.description !== null)
743        task.description = args.description;
744      task.updated = ctx.now;
745      const held = truthy(task.worker) ? ` on worker ${task.worker}` : "";
746      return `Task #${taskId} updated: ${task.subject} (${task.status}${held})`;
747    },
748  };
749}
750
751function taskList(agent: string): Step {
752  return {
753    mutates: false,
754    run(data) {
755      const active = activeEpic(data, agent);
756      const lines: string[] = [];
757      const rows = (tasks: Obj[]) =>
758        lines.push(
759          ...tasks.map(
760            (t) =>
761              `#${t.id} [${t.status}] ${t.subject}${isHuman(t) ? " (assigned to the user)" : ""}`,
762          ),
763        );
764      if (active) {
765        const epic = findEpic(data, agent, active)!;
766        const [done, total] = progress(data, agent, active);
767        lines.push(`Epic #${active}: ${epic.title} (active, ${done}/${total})`);
768        if (total) rows(tasksOf(data, agent, active));
769        else lines.push("No tasks yet.");
770      }
771      const others = openEpics(data, agent).filter((e) => e.id !== active);
772      if (others.length) {
773        lines.push("Other open epics:");
774        for (const epic of others) {
775          const [done, total] = progress(data, agent, epic.id);
776          lines.push(`#${epic.id} ${epic.title} ${done}/${total}`);
777        }
778      }
779      const loose = tasksOf(data, agent, 0);
780      if (loose.length) {
781        lines.push(
782          active
783            ? "Tasks with no epic:"
784            : "No active epic. Tasks with no epic:",
785        );
786        rows(loose);
787      }
788      return lines.join("\n") || "No tasks and no epic.";
789    },
790  };
791}
792
793function taskEpic(agent: string, args: Obj): Step {
794  const title = checkTitle(args.title);
795  return {
796    mutates: true,
797    run(data, ctx) {
798      for (const epic of openEpics(data, agent)) {
799        if (epic.title === title) {
800          data.active[agent] = epic.id;
801          epic.touched = ctx.now;
802          const [done, total] = progress(data, agent, epic.id);
803          return `Epic #${epic.id} ${title} is already open (${done}/${total}): focused it instead of opening a duplicate.`;
804        }
805      }
806      const epic = {
807        id: data.next_epic,
808        agent,
809        title,
810        created: ctx.now,
811        touched: ctx.now,
812      };
813      data.next_epic += 1;
814      data.epics.push(epic);
815      data.active[agent] = epic.id;
816      const others = openEpics(data, agent).filter((e) => e.id !== epic.id);
817      const tail = others.length
818        ? " Still open: " +
819          others.map((e) => `#${e.id} ${e.title}`).join(", ") +
820          "."
821        : "";
822      return `Epic #${epic.id} ${title} opened and active: file its tasks with task_create(epic=${epic.id}).${tail}`;
823    },
824  };
825}
826
827function taskFocus(agent: string, args: Obj): Step {
828  const wanted = strip(pyStr(or(args.epic, "")));
829  if (!wanted)
830    throw new TaskError("epic is required: an epic id or its exact title");
831  return {
832    mutates: true,
833    run(data, ctx) {
834      const epics = openEpics(data, agent);
835      const epicId = parseEpicId(wanted);
836      let match = epics.filter((e) => e.id === epicId);
837      if (!match.length) match = epics.filter((e) => e.title === wanted);
838      if (!match.length) {
839        const closed = epicId !== null && findEpic(data, agent, epicId);
840        const why = closed
841          ? `epic ${wanted} is completed`
842          : `no open epic ${wanted}`;
843        throw new TaskError(
844          `${why}; ${describeOpen(data, agent)}. Open a new one with task_epic.`,
845        );
846      }
847      const epic = match[0]!;
848      data.active[agent] = epic.id;
849      epic.touched = ctx.now;
850      const [done, total] = progress(data, agent, epic.id);
851      return `Epic #${epic.id} ${epic.title} is now active (${done}/${total}): file its tasks with task_create(epic=${epic.id}).`;
852    },
853  };
854}
855
856// --- the user's tasks ----------------------------------------------------------------
857
858const isHuman = (t: Obj): boolean => get(t, "assignee", "") === HUMAN;
859
860/** The main agent's tasks assigned to the user and not yet answered. */
861export function humanOpen(data: Data): Obj[] {
862  return data.tasks.filter(
863    (t) =>
864      get(t, "agent", MAIN) === MAIN &&
865      isHuman(t) &&
866      t.status !== "completed",
867  );
868}
869
870function taskAssignHuman(agent: string, args: Obj): Step {
871  // The user talks to the main agent: a subagent's need reaches them
872  // through the main agent's answer, never as a task of its own list.
873  if (agent !== MAIN)
874    throw new TaskError(
875      "task_assign_human is the main agent's: say in your answer what you need from the user, and the main agent assigns it.",
876    );
877  const subject = checkSubject(args.subject);
878  const wanted = args.epic;
879  return {
880    mutates: true,
881    run(data, ctx) {
882      const epicId =
883        wanted === undefined || wanted === null ? null : parseEpicId(wanted);
884      if (!epicId || !findEpic(data, agent, epicId)) {
885        throw new TaskError(
886          `epic is required: a task for the user belongs to the epic it unblocks; ${describeOpen(data, agent)}. task_epic(title) opens one first.`,
887        );
888      }
889      const open = humanOpen(data);
890      if (open.length >= MAX_HUMAN_OPEN) {
891        throw new TaskError(
892          `the user already has ${open.length} tasks waiting (${open.map((t) => `#${t.id} ${t.subject}`).join(", ")}), the limit is ${MAX_HUMAN_OPEN}: ` +
893            "close the ones they answered with task_update(status=completed), or delete the ones that no longer apply, first.",
894        );
895      }
896      const task = {
897        id: String(data.next_id),
898        agent,
899        epic: epicId,
900        subject,
901        description: or(args.description, ""),
902        status: "waiting",
903        assignee: HUMAN,
904        created: ctx.now,
905        updated: ctx.now,
906      };
907      data.next_id += 1;
908      data.tasks.push(task);
909      touch(data, agent, epicId, ctx.now);
910      return (
911        `Task #${task.id} assigned to the user, waiting: ${subject} in epic #${epicId} ${findEpic(data, agent, epicId)!.title}. ` +
912        `Ask them for it in your reply; once they have answered, task_update(id="${task.id}", status="completed").`
913      );
914    },
915  };
916}
917
918/**
919 * What the model is told again after a compaction: the user's open tasks,
920 * so a "go" asked before the summary is still known to be awaited.
921 * Undefined when there is none.
922 */
923export function humanContext(data: Data): string | undefined {
924  const open = humanOpen(data);
925  if (!open.length) return undefined;
926  const line = (t: Obj): string => {
927    const epic = findEpic(data, MAIN, get(t, "epic", 0));
928    const what = strip(pyStr(or(t.description, "")));
929    const detail = what
930      ? `: ${codePoints(what) > 200 ? [...what].slice(0, 200).join("") + "…" : what}`
931      : "";
932    return `  - #${t.id} ${t.subject}${epic ? ` (epic #${epic.id} ${epic.title})` : ""}${detail}`;
933  };
934  return [
935    "Tasks assigned to the user (task_assign_human), still waiting on them:",
936    ...open.map(line),
937    "Once the user has answered one, close it with task_update(id, status=completed); do not redo what only they can do.",
938  ].join("\n");
939}
940
941export const TOOL_NAMES = [
942  "task_create",
943  "task_update",
944  "task_epic",
945  "task_focus",
946  "task_list",
947  "task_assign_human",
948] as const;
949export type ToolName = (typeof TOOL_NAMES)[number];
950
951/**
952 * Check a call's arguments and return the change it makes. Throws TaskError
953 * on the checks that need no file, in tasks.py's order; the rest throw from
954 * `run`, which sees the file as it is under the lock.
955 */
956export function plan(tool: ToolName, agent: string, args: Obj): Step {
957  switch (tool) {
958    case "task_create":
959      return taskCreate(agent, args);
960    case "task_update":
961      return taskUpdate(agent, args);
962    case "task_epic":
963      return taskEpic(agent, args);
964    case "task_focus":
965      return taskFocus(agent, args);
966    case "task_list":
967      return taskList(agent);
968    case "task_assign_human":
969      return taskAssignHuman(agent, args);
970  }
971}
972
973// --- who the workers are ------------------------------------------------------------
974
975const STALE_AGENT = 12 * 3600; // a subagent with no stop for this long was lost with its session
976const LIVE = new Set(["running", "waiting", "idle"]);
977
978/**
979 * The session's subagents. `listed` is `$.agent.list()` (undefined when it
980 * failed) and decides who runs; agents.json, written by on-agent.sh under
981 * the same ids, only adds when each started. Without the list, agents.json
982 * decides alone, as tasks.py did.
983 */
984export function resolveWorkers(
985  listed:
986    | readonly { id: string; type: string; name?: string; status: string }[]
987    | undefined,
988  agentsJson: string | undefined,
989  now: number,
990): Worker[] {
991  let recorded: Obj = {};
992  try {
993    const parsed = agentsJson === undefined ? {} : JSON.parse(agentsJson);
994    const agents = isObj(parsed) ? or(parsed.agents, {}) : {};
995    if (isObj(agents)) recorded = agents;
996  } catch {
997    recorded = {};
998  }
999  const startedOf = (id: string): number | undefined => {
1000    const e = recorded[id];
1001    return isObj(e) && typeof e.started === "number" ? e.started : undefined;
1002  };
1003  if (listed) {
1004    return listed.map((a) => {
1005      const w: Worker = { id: a.id, type: a.type, alive: LIVE.has(a.status) };
1006      if (a.name) w.name = a.name;
1007      const started = startedOf(a.id);
1008      if (started !== undefined) w.started = started;
1009      return w;
1010    });
1011  }
1012  return Object.entries(recorded)
1013    .filter(([, e]) => isObj(e))
1014    .map(([id, e]) => {
1015      const w: Worker = {
1016        id,
1017        type: pyStr(or(e.type, "")),
1018        alive:
1019          get(e, "stopped", null) === null &&
1020          (or(e.started, 0) as number) >= now - STALE_AGENT,
1021      };
1022      if (typeof e.started === "number") w.started = e.started;
1023      return w;
1024    });
1025}
1026
1027// --- what the model reads -------------------------------------------------------------
1028
1029const TREE =
1030  " Optional, for the user's task tree: parent=<id> files it as a subtask (three levels at most, in its " +
1031  "parent's epic), blocked_by=[<id>, ...] names the tasks it waits on (no cycle), ref names a short handle " +
1032  "of 5 characters at most (T0, C6). A pending task whose blockers are all completed shows as ready, one " +
1033  "with a blocker left as blocked; the longest blocked_by chain is the epic's critical path. When a plan " +
1034  "files several tasks, each one declares blocked_by: the tasks it really waits on, so the list codes the " +
1035  "order of implementation. Every ready task (no blocker left) can start at once, one subagent each in its " +
1036  "own worktree; a task waiting on an unmerged PR may start early on a branch cut from that PR's branch, " +
1037  "rebased onto the default branch once the PR is merged.";
1038
1039/** The tree's arguments, the same on task_create and task_update. */
1040const TREE_PROPS: Obj = {
1041  parent: {
1042    type: "string",
1043    description:
1044      'Id of the task this one is a subtask of, in the same epic; three levels at most. "" for none.',
1045  },
1046  blocked_by: {
1047    type: "array",
1048    items: { type: "string" },
1049    description:
1050      "Ids of the tasks this one waits on; [] for none. A cycle is refused. Declare it whenever the task " +
1051      "needs another one done first: it is what tells which tasks can run in parallel.",
1052  },
1053  ref: {
1054    type: "string",
1055    maxLength: MAX_REF,
1056    description:
1057      'Short handle shown in the tree, 5 characters at most ("T0", "C6"). "" clears it.',
1058  },
1059};
1060
1061const WORKFLOW =
1062  " Work is grouped in epics, one per subject; several can be open at once, one is active (the one being " +
1063  "worked on) and every task names its epic explicitly. The user's status line shows every open epic live, so the list must say what is true at every " +
1064  "moment: in_progress while you work on a task, waiting while it is blocked on the user, completed as soon " +
1065  "as it is done and verified.";
1066
1067export const TOOLS: readonly {
1068  name: ToolName;
1069  description: string;
1070  inputSchema: Obj;
1071}[] = [
1072  {
1073    name: "task_create",
1074    description:
1075      "Add a task. Every message of the user gets one, a question included: file it before acting, and " +
1076      "set it completed as soon as it is answered or done. epic is REQUIRED, there is no default: the id " +
1077      "of the epic the task belongs to (task_list, or the Epics line given with each prompt, lists them), " +
1078      "or 0 for a task outside any epic; open a new subject with task_epic first. task_focus the epic when " +
1079      'you start its work. A change to an already completed task is a new task "Rework #N: ..." in that ' +
1080      "task's epic. subject: at most 30 characters, the title of the task in the task tree, " +
1081      'imperative, no final punctuation ("Add effort gauge"); detail goes in description, which the tree ' +
1082      "shows under the selected task. New tasks start pending." +
1083      TREE +
1084      WORKFLOW,
1085    inputSchema: {
1086      type: "object",
1087      properties: {
1088        subject: {
1089          type: "string",
1090          maxLength: MAX_SUBJECT,
1091          description:
1092            "Short imperative title, 30 characters at most; the detail goes in description.",
1093        },
1094        description: { type: "string", description: "What needs to be done." },
1095        epic: {
1096          type: "integer",
1097          minimum: 0,
1098          description:
1099            "Required. Id of one of your epics, or 0 for no epic. No default.",
1100        },
1101        ...TREE_PROPS,
1102      },
1103      required: ["subject", "epic"],
1104    },
1105  },
1106  {
1107    name: "task_update",
1108    description:
1109      "Update one of your tasks: set in_progress before starting it, completed as soon as its work is done " +
1110      "and verified, waiting when it is blocked on the user (a decision, an approval, an answer), deleted " +
1111      "when it no longer applies. Never end a turn with tasks left to do but none in_progress or waiting: " +
1112      "either one is under way, or they wait on the user and say so. One task in_progress per worker: you " +
1113      "may have one, plus one per running subagent (each subagent works on exactly one task); switching " +
1114      "to another task means setting the current one back to pending first, and a task handed to a " +
1115      "subagent goes in_progress once that subagent has started, with worker=<its type or id> so the task is " +
1116      "tied to it. With worker, the start is refused if that subagent is stopped or already holds another " +
1117      "task; without it, a start beyond the worker count is refused. The link is dropped when the task " +
1118      "leaves in_progress. A refusal lists the running subagents and who holds each task in progress. " +
1119      "subject: at most 30 characters, the detail goes in description. parent, blocked_by and ref " +
1120      'change the task\'s place in the tree (parent="" or blocked_by=[] or ref="" clears one); a deleted ' +
1121      "task's subtasks move up a level and the tasks waiting on it stop waiting.",
1122    inputSchema: {
1123      type: "object",
1124      properties: {
1125        id: {
1126          type: "string",
1127          description: "Task id, as returned by task_create.",
1128        },
1129        status: { type: "string", enum: [...STATUSES] },
1130        subject: {
1131          type: "string",
1132          maxLength: MAX_SUBJECT,
1133          description: "New title, 30 characters at most.",
1134        },
1135        description: { type: "string" },
1136        worker: {
1137          type: "string",
1138          description:
1139            "With status=in_progress: the running subagent that takes the task, by " +
1140            "type (its name) or agent id. Optional.",
1141        },
1142        ...TREE_PROPS,
1143      },
1144      required: ["id"],
1145    },
1146  },
1147  {
1148    name: "task_epic",
1149    description:
1150      "Open a new epic and make it active: a separate subject with its own task list and its own pill on " +
1151      "the user's status line. Use it when the user brings a new subject, rather than appending its tasks " +
1152      "to an unrelated epic; other open epics stay open. If an open epic already has this exact title it " +
1153      'is focused instead. title: at most 20 characters, a short noun phrase ("SDK status-line").' +
1154      WORKFLOW,
1155    inputSchema: {
1156      type: "object",
1157      properties: {
1158        title: {
1159          type: "string",
1160          maxLength: MAX_TITLE,
1161          description: "Subject of the epic, 20 characters at most.",
1162        },
1163      },
1164      required: ["title"],
1165    },
1166  },
1167  {
1168    name: "task_focus",
1169    description:
1170      "Make an open epic the active one, by id or exact title, when the work turns back to it: the status " +
1171      "line expands it. Completed epics cannot be focused; open a new one " +
1172      "with task_epic." +
1173      WORKFLOW,
1174    inputSchema: {
1175      type: "object",
1176      properties: {
1177        epic: {
1178          type: "string",
1179          description: 'Epic id ("3" or "#3") or its exact title.',
1180        },
1181      },
1182      required: ["epic"],
1183    },
1184  },
1185  {
1186    name: "task_list",
1187    description:
1188      "List the active epic's tasks with ids and statuses, one line per other open epic " +
1189      "(id, title, done/total), and tasks with no epic.",
1190    inputSchema: { type: "object", properties: {} },
1191  },
1192  {
1193    name: "task_assign_human",
1194    description:
1195      "Assign the user a task only they can do: a go or an approval, a Touch ID or a password typed on " +
1196      "their machine, a gesture on hardware you cannot reach. The task is filed waiting, marked as the " +
1197      "user's, in the epic it unblocks (epic is required), and shows on their status line. Say in your " +
1198      "reply what you need from them. Once they have answered, close it with task_update(status=completed); " +
1199      "it never goes in_progress. At most 5 open at once. Main agent only: a subagent says what it needs in " +
1200      "its answer.",
hooks/mod/store.ts 139 lines
1// store.ts — reading and rewriting a session's tasks.json. No `$`: the host is
2// reached through a Port, which register.ts builds on `$` and the tests on
3// memory or on node's own file system.
4//
5// The file is read fresh on every call and replaced whole: written to a
6// temporary file in the same directory, then renamed over tasks.json by `mv`,
7// so a reader (status line, shell hooks) never sees half a list. `$.fs` has
8// no rename, hence `mv` through `$.process.run`, its exit code checked.
9//
10// Two writers are kept apart twice. Inside this process (the main loop and
11// every subagent share one copy of the mod) a promise queue per directory
12// runs one mutation at a time. Across processes (a second session on the
13// same id) a lock directory, created by `mkdir`, which is atomic: the same
14// protocol as the shell's lib/lock.sh, stale after KF_LOCK_STALE seconds and
15// broken by renaming it to a unique name. A lock not obtained in time is
16// written through, as lib/lock.sh's callers do: hooks fail open.
17import { parse, serialize, type Data } from "./tasks.ts";
18import { tasksFile } from "./paths.ts";
19
20export type RunResult = { exitCode: number; stdout: string; stderr: string };
21
22export type Port = {
23  /** The file's text, undefined when it is missing or unreadable. */
24  read(path: string): Promise<string | undefined>;
25  /** Write the whole text, creating directories as needed. */
26  write(path: string, text: string): Promise<void>;
27  /** Run a command by argv, no shell. */
28  run(argv: readonly string[]): Promise<RunResult>;
29  /** Modification time in milliseconds, undefined when missing. */
30  mtime(path: string): Promise<number | undefined>;
31  sleep(ms: number): Promise<void>;
32  /** Wall clock in milliseconds. */
33  now(): number;
34};
35
36export const LOCK_STALE_MS = 10_000;
37export const LOCK_WAIT_MS = 2_000;
38const LOCK_POLL_MS = 50;
39
40let counter = 0;
41export const unique = (): string =>
42  `${Date.now().toString(36)}.${Math.random().toString(36).slice(2, 10)}.${++counter}`;
43
44const queues = new Map<string, Promise<unknown>>();
45
46/** Run `work` after every earlier mutation of the same directory settled. */
47function enqueue<T>(dir: string, work: () => Promise<T>): Promise<T> {
48  const prev = queues.get(dir) ?? Promise.resolve();
49  const next = prev.then(work, work);
50  const tail = next.catch(() => undefined);
51  queues.set(dir, tail);
52  void tail.then(() => {
53    if (queues.get(dir) === tail) queues.delete(dir);
54  });
55  return next;
56}
57
58/**
59 * Take the lock directory; true when held, false when written through.
60 * `waitMs` is the budget before writing through: LOCK_WAIT_MS for every
61 * hook, larger only where a caller must never write through (a test of
62 * mutual exclusion, which the fail-open budget would otherwise race).
63 */
64export async function lock(
65  port: Port,
66  lockDir: string,
67  waitMs: number = LOCK_WAIT_MS,
68): Promise<boolean> {
69  const deadline = port.now() + waitMs;
70  for (;;) {
71    if ((await port.run(["mkdir", lockDir])).exitCode === 0) return true;
72    const m = await port.mtime(lockDir);
73    if (m !== undefined && port.now() - m >= LOCK_STALE_MS) {
74      // Of two waiters that both see it stale, one rename wins; the other
75      // finds nothing to move and goes round again.
76      const grave = `${lockDir}.stale.${unique()}`;
77      if ((await port.run(["mv", lockDir, grave])).exitCode === 0) {
78        await port.run(["rmdir", grave]);
79        continue;
80      }
81    }
82    if (port.now() >= deadline) return false;
83    await port.sleep(LOCK_POLL_MS);
84  }
85}
86
87/** Replace tasks.json through a temporary file and `mv`. */
88export async function save(port: Port, dir: string, data: Data): Promise<void> {
89  const tmp = `${dir}/.tasks.${unique()}.tmp`;
90  await port.write(tmp, serialize(data));
91  const moved = await port.run(["mv", "-f", tmp, tasksFile(dir)]);
92  if (moved.exitCode !== 0) {
93    await port.run(["rm", "-f", tmp]);
94    throw new Error(
95      `tasks.json not replaced: mv exited ${moved.exitCode}: ${moved.stderr.trim()}`,
96    );
97  }
98}
99
100/** The list as the file holds it now, for a call that writes nothing. */
101export async function load(
102  port: Port,
103  dir: string,
104  nowSec: number,
105): Promise<Data> {
106  return parse(await port.read(tasksFile(dir)), nowSec);
107}
108
109/**
110 * Read the list, apply `change`, write it back: one at a time per directory,
111 * under the lock. When `change` throws (a refusal), nothing is written.
112 * `waitMs` is lock()'s budget before writing through.
113 */
114export function mutate<T>(
115  port: Port,
116  dir: string,
117  change: (data: Data) => T,
118  waitMs: number = LOCK_WAIT_MS,
119): Promise<T> {
120  return enqueue(dir, async () => {
121    const made = await port.run(["mkdir", "-p", dir]);
122    if (made.exitCode !== 0)
123      throw new Error(`cannot create ${dir}: ${made.stderr.trim()}`);
124    const lockDir = `${dir}/.lock.d`;
125    const held = await lock(port, lockDir, waitMs);
126    try {
127      const data = parse(
128        await port.read(tasksFile(dir)),
129        Math.floor(port.now() / 1000),
130      );
131      const result = change(data);
132      await save(port, dir, data);
133      return result;
134    } finally {
135      if (held) await port.run(["rmdir", lockDir]);
136    }
137  });
138}
139
hooks/mod/lint.ts 340 lines
1// lint.ts — ktn-linter, for Go projects only, and the /lint-setup command.
2// No `$`: register.ts hands the flow a LintPort built on `$`, the tests one
3// in memory.
4//
5// A Go project is the go.mod nearest a changed file (for /lint-setup, the
6// path it is given), never above the session's root: making.codes has none
7// at its root, only projects/making.codes/go.mod. The rule is written twice,
8// once per side, and both are held to the same fixtures
9// (tests/fixtures/gomod.json): here with `$.fs.exists`, in
10// hooks/scripts/lib/gomod.sh with `[ -f ]`.
11//
12// /lint-setup checks what ktn-linter needs in a session (the binary, its own
13// command hooks, the per-user daemon when KTN_USER_DAEMON=1, the module's
14// configuration) and proposes each correction through `$.ui.ask`. The hooks
15// and the daemon are ktn-linter's to manage — `hook install`, `hook doctor`,
16// `daemon ensure` — never this plugin's: nothing here speaks to a port
17// (kodflow/ktn-linter#771). Nothing is installed or started unasked; the
18// configuration belongs to the user and is never written.
19//
20// The binary is `ktn-linter`. `project-linter`, its old name, is only a
21// fallback when ktn-linter is not on PATH.
22
23export type RunResult = { exitCode: number; stdout: string; stderr: string };
24
25export type LintPort = {
26  exists(path: string): Promise<boolean>;
27  /** Whether the path is a directory; false when missing. */
28  isDir(path: string): Promise<boolean>;
29  /** The file's text, undefined when missing or unreadable. */
30  read(path: string): Promise<string | undefined>;
31  /** Run by argv; undefined when the command could not be started at all. */
32  run(
33    argv: readonly string[],
34    timeoutMs: number,
35  ): Promise<RunResult | undefined>;
36  /** The label chosen; undefined when nobody can answer (a -p run, a dismissal). */
37  ask(
38    question: string,
39    options: readonly string[],
40  ): Promise<string | undefined>;
41  /** The variables the check reads, as the session has them. */
42  vars: {
43    KTN_USER_DAEMON?: string;
44  };
45  sleep(ms: number): Promise<void>;
46  /** The session's root directory, absolute. */
47  root: string;
48};
49
50const parent = (p: string): string => {
51  const cut = p.lastIndexOf("/");
52  return cut <= 0 ? "/" : p.slice(0, cut);
53};
54
55const trimSlash = (p: string): string =>
56  p.length > 1 ? p.replace(/\/+$/, "") : p;
57
58/**
59 * The directory of the go.mod nearest `path` (a file, or a directory when
60 * `isDir`), at or below `root`; undefined when there is none or `path` is
61 * outside `root`. Both absolute.
62 */
63export async function goModuleOf(
64  path: string,
65  root: string,
66  exists: (p: string) => Promise<boolean>,
67  isDir = false,
68): Promise<string | undefined> {
69  const top = trimSlash(root);
70  const p = trimSlash(path);
71  if (!top.startsWith("/") || !p.startsWith("/")) return undefined;
72  if (p !== top && !p.startsWith(top === "/" ? "/" : `${top}/`))
73    return undefined;
74  let d = isDir ? p : parent(p);
75  for (;;) {
76    if (await exists(`${d === "/" ? "" : d}/go.mod`)) return d;
77    if (d === top || d === "/") return undefined;
78    d = parent(d);
79  }
80}
81
82// --- configuration ---------------------------------------------------------------
83
84/** What is wrong with a .ktn-linter.yaml, read line by line: empty when nothing. */
85export function yamlProblems(text: string): string[] {
86  const problems: string[] = [];
87  const lines = text.split("\n");
88  let inPhases = false;
89  let enabled = false;
90  let disabled = false;
91  for (const line of lines) {
92    if (/^\S/.test(line)) inPhases = /^phases:\s*(#.*)?$/.test(line);
93    if (/^max_phase:/.test(line))
94      problems.push("max_phase is no longer read: list phases.enabled instead");
95    const scope = /^review_scope:\s*([^\s#]*)/.exec(line);
96    if (scope && !["diff", "full"].includes(scope[1]!.replace(/["']/g, "")))
97      problems.push(`review_scope is "${scope[1]}": it must be diff or full`);
98    if (inPhases && /^\s+enabled:/.test(line)) enabled = true;
99    if (inPhases && /^\s+disabled:/.test(line)) disabled = true;
100  }
101  if (enabled && disabled)
102    problems.push("phases.enabled and phases.disabled are both set: keep one");
103  return problems;
104}
105
106// --- /lint-setup -----------------------------------------------------------------
107
108export const LINT_SETUP = {
109  name: "lint-setup",
110  description:
111    "Check ktn-linter for this Go project: binary, hooks, daemon, configuration. Proposes each fix.",
112  argumentHint: "[path in a Go module]",
113} as const;
114
115// The public mirror: kodflow/ktn-linter, the source, is private.
116const RELEASES = "https://github.com/kodflow/ktn/releases";
117
118/** The binary's name, then the old one, looked up only when the first is absent. */
119const BINARIES = ["ktn-linter", "project-linter"] as const;
120
121/** A subcommand the binary does not know: an older release than `hook install`. */
122const UNKNOWN_COMMAND = 40;
123
124// The latest release's archive for this machine, checked against the
125// release's checksums.txt, then ktn-linter and ktn-hook (the client its
126// command hooks run) into ~/.local/bin, each through a temporary file renamed
127// over the old one. Asked for before it runs.
128const INSTALL = [
129  "set -eu",
130  `tag=$(curl -fsSL --max-time 20 https://api.github.com/repos/kodflow/ktn/releases/latest | sed -n 's/.*"tag_name": *"\\([^"]*\\)".*/\\1/p' | head -n 1)`,
131  '[ -n "$tag" ]',
132  "os=$(uname -s | tr '[:upper:]' '[:lower:]')",
133  'case "$(uname -m)" in x86_64|amd64) arch=amd64 ;; aarch64|arm64) arch=arm64 ;; *) arch=$(uname -m) ;; esac',
134  'asset="ktn-linter_${os}_${arch}.tar.gz"',
135  'work=$(mktemp -d); trap \'rm -rf "$work"\' EXIT',
136  `curl -fsSL --max-time 120 "${RELEASES}/download/$tag/$asset" -o "$work/$asset"`,
137  `curl -fsSL --max-time 20 "${RELEASES}/download/$tag/checksums.txt" -o "$work/checksums.txt"`,
138  'want=$(awk -v a="$asset" \'$2 == a { print $1 }\' "$work/checksums.txt")',
139  'if command -v sha256sum >/dev/null 2>&1; then got=$(sha256sum "$work/$asset"); else got=$(shasum -a 256 "$work/$asset"); fi',
140  '[ -n "$want" ] && [ "${got%% *}" = "$want" ] || { echo "checksum mismatch for $asset" >&2; exit 1; }',
141  'tar -xzf "$work/$asset" -C "$work" ktn-linter ktn-hook',
142  'dir=$HOME/.local/bin; mkdir -p "$dir"',
143  'for b in ktn-linter ktn-hook; do tmp=$(mktemp "$dir/.$b.XXXXXX"); cp "$work/$b" "$tmp"; chmod 755 "$tmp"; mv -f "$tmp" "$dir/$b"; done',
144  'printf "%s %s\\n" "$tag" "$dir/ktn-linter"',
145].join("\n");
146
147const YES_INSTALL = "Install";
148const YES_HOOKS = "Install the hooks";
149const YES_DAEMON = "Start it";
150const NOT_NOW = "Not now";
151
152async function binary(io: LintPort, bin: string): Promise<string | undefined> {
153  const r = await io.run([bin, "version"], 5000);
154  if (!r || r.exitCode !== 0) return undefined;
155  return r.stdout.trim().split("\n")[0] || "unknown version";
156}
157
158type Doctor =
159  | { kind: "ok" }
160  | { kind: "defects"; defects: string[] }
161  | { kind: "unsupported" }
162  | { kind: "failed"; detail: string };
163
164/** `hook doctor --json`, read: the installation of ktn-linter's own hooks. */
165async function doctor(io: LintPort, bin: string): Promise<Doctor> {
166  const r = await io.run([bin, "hook", "doctor", "--json"], 30_000);
167  if (!r) return { kind: "failed", detail: `${bin} hook doctor could not run` };
168  if (r.exitCode === UNKNOWN_COMMAND) return { kind: "unsupported" };
169  let report: { ok?: unknown; defects?: unknown } | undefined;
170  try {
171    report = JSON.parse(r.stdout);
172  } catch {
173    report = undefined;
174  }
175  if (!report || typeof report !== "object")
176    return {
177      kind: "failed",
178      detail: (r.stderr.trim() || r.stdout.trim() || `exit ${r.exitCode}`).slice(0, 300),
179    };
180  if (report.ok === true && r.exitCode === 0) return { kind: "ok" };
181  const defects = Array.isArray(report.defects)
182    ? report.defects.map((d: any) =>
183        `${d?.code ?? "defect"}${d?.host ? ` (${d.host})` : ""}: ${d?.message ?? ""}`.trim(),
184      )
185    : [];
186  return { kind: "defects", defects: defects.length ? defects : [`exit ${r.exitCode}`] };
187}
188
189/** The whole check, as the text the command prints. */
190export async function lintSetup(io: LintPort, args: string): Promise<string> {
191  const root = trimSlash(io.root);
192  const wanted = args.trim();
193  const target = !wanted
194    ? root
195    : wanted.startsWith("/")
196      ? trimSlash(wanted)
197      : `${root === "/" ? "" : root}/${wanted.replace(/^\.\/+/, "")}`;
198  const dir = await io.isDir(target);
199  const module = await goModuleOf(target, root, (p) => io.exists(p), dir);
200  if (!module) {
201    return [
202      `No go.mod at or above ${target} inside ${root}: not a Go project, so the hooks do not run`,
203      "ktn-linter here, and there is nothing to set up.",
204      "Name a file or a directory of a Go module to check it: /lint-setup <path>.",
205    ].join("\n");
206  }
207  const lines = [`Go module: ${module}`];
208
209  // --- binary
210  let bin: string = BINARIES[0];
211  let version: string | undefined;
212  for (const name of BINARIES) {
213    version = await binary(io, name);
214    if (version) {
215      bin = name;
216      break;
217    }
218  }
219  lines.push(
220    !version
221      ? "binary   missing: ktn-linter is not on PATH"
222      : bin === BINARIES[0]
223        ? `binary   ok, ${version}`
224        : `binary   ok, ${version} (found as ${bin}, the old name: ktn-linter is the one to install)`,
225  );
226  if (!version) {
227    const yes = await io.ask(
228      `ktn-linter is not installed. Install its latest release from ${RELEASES} (ktn-linter and ktn-hook, checksum verified) into ~/.local/bin?`,
229      [YES_INSTALL, NOT_NOW],
230    );
231    if (yes === YES_INSTALL) {
232      const r = await io.run(["bash", "-c", INSTALL], 180_000);
233      const [tag, path] = (r?.stdout.trim() ?? "").split(" ");
234      if (r && r.exitCode === 0 && path) {
235        bin = path;
236        version = (await binary(io, bin)) ?? tag;
237        lines.push(
238          `         installed ${tag} at ${path} (add ~/.local/bin to PATH for the hooks)`,
239        );
240      } else {
241        lines.push(
242          `         install failed: ${(r?.stderr.trim() || "could not run bash").slice(0, 300)}`,
243        );
244      }
245    } else {
246      lines.push(`         not installed: download it from ${RELEASES}`);
247    }
248  }
249
250  // --- hooks: ktn-linter's own command hooks, installed and judged by it
251  if (!version) {
252    lines.push("hooks    needs the binary first");
253  } else {
254    let d = await doctor(io, bin);
255    if (d.kind === "ok") {
256      lines.push("hooks    ok, ktn-linter hook doctor reports a sound installation");
257    } else if (d.kind === "unsupported") {
258      lines.push(
259        `hooks    unavailable: ${bin} predates \`hook install\` (ktn-linter v1.46.0); install the latest release from ${RELEASES}`,
260      );
261    } else if (d.kind === "failed") {
262      lines.push(`hooks    unknown: ${d.detail}`);
263    } else {
264      lines.push(`hooks    ${d.defects.length} defect(s) reported by hook doctor:`);
265      for (const x of d.defects) lines.push(`         - ${x}`);
266      const yes = await io.ask(
267        "ktn-linter's command hooks are not sound. Run `ktn-linter hook install`? It rewrites its own entries in your user settings, and nothing else.",
268        [YES_HOOKS, NOT_NOW],
269      );
270      if (yes === YES_HOOKS) {
271        const r = await io.run([bin, "hook", "install"], 120_000);
272        d = await doctor(io, bin);
273        lines.push(
274          d.kind === "ok"
275            ? "         installed; hook doctor now reports ok (restart the session to load them)"
276            : `         hook install did not leave a sound installation: ${(r?.stderr.trim() || (d.kind === "defects" ? d.defects.join("; ") : "see ktn-linter hook doctor")).slice(0, 300)}`,
277        );
278      } else {
279        lines.push(
280          "         not installed: ktn-linter hook install, then ktn-linter hook doctor",
281        );
282      }
283    }
284  }
285
286  // --- daemon: the per-user one when opted in, else the MCP server's own
287  if (io.vars.KTN_USER_DAEMON !== "1") {
288    lines.push(
289      "daemon   per project, started by the MCP server (ktn-linter mcp install; make hooks-install in ktn-linter's own repository)",
290    );
291  } else if (!version) {
292    lines.push("daemon   needs the binary first");
293  } else {
294    const ok = async () => (await io.run([bin, "daemon", "status"], 10_000))?.exitCode === 0;
295    let alive = await ok();
296    lines.push(
297      alive
298        ? "daemon   ok, ktn-linter daemon status reports the per-user daemon healthy"
299        : "daemon   down: ktn-linter daemon status does not report a healthy per-user daemon",
300    );
301    if (!alive) {
302      const yes = await io.ask(
303        "The per-user ktn-linter daemon is not running. Start it with `ktn-linter daemon ensure`?",
304        [YES_DAEMON, NOT_NOW],
305      );
306      if (yes === YES_DAEMON) {
307        await io.run([bin, "daemon", "ensure"], 30_000);
308        alive = await ok();
309        lines.push(
310          alive
311            ? "         started (ktn-linter daemon ensure)"
312            : "         did not come up: see ktn-linter daemon status",
313        );
314      } else {
315        lines.push("         not started: ktn-linter daemon ensure");
316      }
317    }
318  }
319
320  // --- configuration: .ktn-linter.yaml, .project-linter.yaml as a fallback
321  let name = ".ktn-linter.yaml";
322  let yaml = await io.read(`${module}/${name}`);
323  if (yaml === undefined) {
324    const old = await io.read(`${module}/.project-linter.yaml`);
325    if (old !== undefined) {
326      name = ".project-linter.yaml";
327      yaml = old;
328    }
329  }
330  const problems =
331    yaml === undefined ? [] : yamlProblems(yaml).map((p) => `${name}: ${p}`);
332  lines.push(
333    problems.length
334      ? `config   ${problems.length} problem(s), to fix by hand (this command never writes them):`
335      : `config   ok (${yaml === undefined ? "ktn-linter's defaults" : name})`,
336  );
337  for (const p of problems) lines.push(`         - ${p}`);
338  return lines.join("\n");
339}
340
hooks/mod/calls.ts 139 lines
1// calls.ts — the small decisions register.ts makes on an event. Pure.
2import { TOOL_NAMES, type ToolName } from "./tasks.ts";
3
4export const PLUGIN = "kodflow-hooks";
5const PREFIX = `mcp__${PLUGIN}__`;
6
7/** The task tool a `tool.call` names, undefined for any other tool. */
8export function taskTool(tool: unknown): ToolName | undefined {
9  if (typeof tool !== "string" || !tool.startsWith(PREFIX)) return undefined;
10  const name = tool.slice(PREFIX.length);
11  return (TOOL_NAMES as readonly string[]).includes(name)
12    ? (name as ToolName)
13    : undefined;
14}
15
16// What `tool.call` carries beside the tool's own arguments
17const RESERVED = new Set([
18  "tool",
19  "tool_use_id",
20  "agentId",
21  "requestMeta",
22  "consent",
23]);
24
25/** The arguments the model gave, without the envelope. */
26export function argsOf(e: Record<string, unknown>): Record<string, unknown> {
27  const args: Record<string, unknown> = {};
28  for (const [k, v] of Object.entries(e)) if (!RESERVED.has(k)) args[k] = v;
29  return args;
30}
31
32/**
33 * The text the engine asks the model to put in a commit or a pull request:
34 * none. The other kinds (the exemption, the remedy) are the engine's own
35 * sentences about its commit gate and are left as they are.
36 */
37export function attributionText(kind: unknown): string | undefined {
38  return kind === "commit" || kind === "pr" ? "" : undefined;
39}
40
41/** KODFLOW_MOD=off: the mod hooks nothing and leaves no marker. */
42export const isOff = (value: string | undefined): boolean => value === "off";
43
44/** The main loop's call: no agent id. A subagent's carries its own. */
45export const mainLoop = (agentId: unknown): boolean =>
46  agentId === undefined || agentId === null || agentId === "";
47
48/**
49 * The causes a triage-pending file holds, one per line, in order: `prompt
50 * <id>` for each user message not filed yet (on-user.sh, one line per
51 * message) and `resume` (a session that came back with open tasks,
52 * on-session.sh). An empty file is the format before causes: one prompt.
53 */
54export function triageCauses(text: string): string[] {
55  const causes = text
56    .split("\n")
57    .map((line) => line.trim())
58    .filter(Boolean);
59  return causes.length ? causes : ["prompt"];
60}
61
62// A line's kind: its first word. Anything but resume is a message to file.
63const kindOf = (cause: string): "prompt" | "resume" =>
64  cause.split(/\s+/)[0] === "resume" ? "resume" : "prompt";
65
66const given = (v: unknown): boolean =>
67  typeof v === "string" ? v.trim() !== "" : v !== undefined && v !== null;
68
69/**
70 * Whether a task call that succeeded settles one cause of the triage gate.
71 * A user message is settled by a task of its own (task_create,
72 * task_assign_human) or by context added to the task in progress
73 * (task_update with a description); a resumed session by a status set
74 * (task_update with a status). Reading or steering the list (task_list,
75 * task_epic, task_focus) settles nothing. Only the main loop: a subagent
76 * works for a task the main agent already filed. A cause this version does
77 * not know is read as a prompt.
78 */
79export function liftsTriage(
80  tool: ToolName,
81  args: Record<string, unknown>,
82  agentId: unknown,
83  cause: string,
84): boolean {
85  if (!mainLoop(agentId)) return false;
86  if (kindOf(cause) === "resume")
87    return tool === "task_update" && given(args.status);
88  return (
89    tool === "task_create" ||
90    tool === "task_assign_human" ||
91    (tool === "task_update" && given(args.description))
92  );
93}
94
95/**
96 * The causes left once a call that succeeded is counted: one gesture files
97 * one message, so it drops the oldest line of each kind it answers, never
98 * two of the same kind. The other messages wait for their own gesture.
99 */
100export function settleCauses(
101  causes: readonly string[],
102  tool: ToolName,
103  args: Record<string, unknown>,
104  agentId: unknown,
105): string[] {
106  const left = [...causes];
107  for (const kind of ["prompt", "resume"] as const) {
108    if (!liftsTriage(tool, args, agentId, kind)) continue;
109    const at = left.findIndex((c) => kindOf(c) === kind);
110    if (at >= 0) left.splice(at, 1);
111  }
112  return left;
113}
114
115/** The payload on-mod.sh logs for a task call, shaped like a PostToolUse. */
116export function logPayload(
117  session: string,
118  cwd: string,
119  e: Record<string, unknown>,
120  answer: { result: string } | { deny: string },
121): Record<string, unknown> {
122  const base: Record<string, unknown> = {
123    hook_event_name: "deny" in answer ? "PostToolUseFailure" : "PostToolUse",
124    session_id: session,
125    cwd,
126    tool_use_id: e.tool_use_id,
127    tool_name: e.tool,
128    tool_input: argsOf(e),
129  };
130  if (typeof e.agentId === "string" && e.agentId) base.agent_id = e.agentId;
131  if ("deny" in answer) base.error = answer.deny;
132  else base.tool_response = { ok: true };
133  return base;
134}
135
136/** An MCP tool's call (mcp__<server>__<tool>): what the shape probe watches. */
137export const isMcpTool = (tool: unknown): tool is string =>
138  typeof tool === "string" && /^mcp__/.test(tool);
139
hooks/mod/paths.ts 48 lines
1// paths.ts — where the mod keeps a session's state. Pure.
2//
3// <config>/kodflow/sessions/<session>/ is shared with the shell hooks and the
4// status line: tasks.json (the task list), agents.json (on-agent.sh),
5// triage-pending (the triage gate) and mod-beat (the proof the mod is loaded).
6
7/**
8 * The Claude configuration directory: CLAUDE_CONFIG_DIR, else ~/.claude.
9 * Always absolute: `$.fs` resolves a relative path against the session's
10 * working directory and never expands `~`, so anything else is refused.
11 */
12export function configDir(
13  claudeConfigDir: string | undefined,
14  home: string | undefined,
15): string | undefined {
16  const pick =
17    claudeConfigDir || (home ? `${home.replace(/\/+$/, "")}/.claude` : "");
18  if (!pick.startsWith("/")) return undefined;
19  return pick.length > 1 ? pick.replace(/\/+$/, "") : pick;
20}
21
22/** Keep an identifier usable as a single path component (tasks.py's safe). */
23export function safe(value: unknown): string {
24  const chars = [...String(value)].map((c) =>
25    /^[\p{L}\p{N}_-]$/u.test(c) ? c : "-",
26  );
27  return chars.slice(0, 128).join("") || "default";
28}
29
30export const sessionDir = (config: string, session: string): string =>
31  `${config}/kodflow/sessions/${safe(session)}`;
32
33export const tasksFile = (dir: string): string => `${dir}/tasks.json`;
34export const agentsFile = (dir: string): string => `${dir}/agents.json`;
35export const triageFile = (dir: string): string => `${dir}/triage-pending`;
36export const beatFile = (dir: string): string => `${dir}/mod-beat`;
37
38/** The beat's content: the time in whole seconds, as the shell compares it. */
39export const beatText = (nowMs: number): string =>
40  String(Math.floor(nowMs / 1000));
41
42/**
43 * When the user last typed at the prompt, in whole seconds: written on every
44 * composer prompt, read by on-stop.sh before it proposes agent feedback.
45 */
46export const composerFile = (dir: string): string => `${dir}/composer-at`;
47
48
hooks/mod/machine-guards.ts 233 lines
1// machine-guards.ts — modwall, collision-guard and zsh-safe, over a port.
2//
3// The engine follows `$` and `on` only inside register.ts, so register.ts
4// builds a GuardPort from `$` and hooks the events; what each hook does is
5// here, and the decisions themselves in modwall.ts, collision.ts and zsh.ts.
6//
7// Every guard fails open, as every kodflow hook does: a judge that throws
8// lets the module load, a collision check that throws lets the edit through,
9// a zsh setup that throws leaves the shell as it was.
10import { safe, sessionDir, beatFile } from "./paths.ts";
11import { decision, remember, report, type Decision } from "./modwall.ts";
12import {
13  CANCEL,
14  CONTINUE,
15  WORKTREE,
16  answer,
17  editsFile,
18  excluded,
19  isLive,
20  newest,
21  present,
22  question,
23  record,
24  targetOf,
25} from "./collision.ts";
26import { zdotdirOf, zdotdirPlan } from "./zsh.ts";
27
28const STORE_KEY = "modwall";
29
30export type GuardPort = {
31  /** KODFLOW_MOD=off */
32  off: () => Promise<boolean>;
33  /** The absolute Claude configuration directory, when there is one. */
34  config: () => Promise<string | undefined>;
35  read: (path: string) => Promise<string | undefined>;
36  write: (path: string, text: string) => Promise<void>;
37  list: (path: string) => Promise<{ name: string; kind: string }[]>;
38  session: () => Promise<string>;
39  cwd: () => Promise<string>;
40  ask: (question: string, options: string[]) => Promise<string>;
41  storeGet: (key: string) => Promise<unknown>;
42  storeSet: (key: string, value: unknown) => Promise<void>;
43  log: (text: string) => void;
44  toast: (text: string) => void;
45  /** Declares /kodflow-mods. */
46  registerMods: (description: string) => Promise<unknown>;
47  zdotdir: () => Promise<string | undefined>;
48  userZdotdir: () => Promise<string | undefined>;
49  setZdotdir: (value: string) => Promise<void>;
50  setUserZdotdir: (value: string) => Promise<void>;
51  pluginRoot: string;
52  now: () => number;
53};
54
55const sec = (p: GuardPort) => Math.floor(p.now() / 1000);
56
57// The modules judged since this one loaded, for /kodflow-mods
58const judged: Decision[] = [];
59
60// Refusals made before the session bound (a toast then is dropped), shown
61// at session.start
62const unshown: string[] = [];
63
64// When the user last typed a prompt at the terminal (origin `composer`)
65let lastComposerMs: number | undefined;
66
67/**
68 * prompt.submit: remember when the user typed a prompt, for the presence
69 * rule. Any other origin (a notification, a subagent's message) changes
70 * nothing.
71 */
72export function notePrompt(origin: unknown, nowMs: number): void {
73  if ((origin as { kind?: unknown } | undefined)?.kind !== "composer") return;
74  lastComposerMs = nowMs;
75}
76
77/** When the user last typed a prompt at the terminal, for any presence rule. */
78export const lastComposerAt = (): number | undefined => lastComposerMs;
79
80// A collision the user chose to go past: path -> the foreign edit's time.
81// A newer edit by the other session asks again.
82const acknowledged = new Map<string, number>();
83
84// One write of edits.tsv at a time: the main loop and its subagents share
85// this process and this session's file.
86let writing: Promise<unknown> = Promise.resolve();
87
88/**
89 * modwall, on plugin.register: every module that joins after this one
90 * passes here; only the user tier is judged, and only *@kodflow admitted.
91 */
92export async function admit(
93  p: GuardPort,
94  e: { name: string; tier: string; provenance: string },
95): Promise<{ refuse: string } | undefined> {
96  if (await p.off()) return undefined;
97  const d = decision(e, sec(p));
98  judged.push(d);
99  try {
100    if (d.reason) {
101      p.log(d.reason);
102      unshown.push(`modwall refused ${d.provenance}`);
103    }
104    await p.storeSet(STORE_KEY, remember(await p.storeGet(STORE_KEY), d));
105  } catch {
106    // the journal is best effort; the verdict stands
107  }
108  return d.reason ? { refuse: d.reason } : undefined;
109}
110
111/** What /kodflow-mods prints. */
112export async function modsReport(p: GuardPort): Promise<string> {
113  const history = await p.storeGet(STORE_KEY).catch(() => undefined);
114  return report(judged, Array.isArray(history) ? history : []);
115}
116
117/** session.start's share: /kodflow-mods, and zsh-safe's ZDOTDIR. */
118export async function startGuards(p: GuardPort): Promise<void> {
119  if (await p.off()) return;
120  for (const text of unshown.splice(0)) p.toast(text);
121  await p
122    .registerMods(
123      "kodflow: the mods judged at load and the ones modwall refused",
124    )
125    .catch(() => undefined);
126  try {
127    const plan = zdotdirPlan(
128      await p.zdotdir(),
129      await p.userZdotdir(),
130      zdotdirOf(p.pluginRoot),
131    );
132    if (plan) {
133      await p.setUserZdotdir(plan.user);
134      await p.setZdotdir(plan.zdotdir);
135    }
136  } catch {
137    // the shell stays as the user has it
138  }
139}
140
141async function others(
142  p: GuardPort,
143  cfg: string,
144  self: string,
145): Promise<{ session: string; text: string | undefined }[]> {
146  const root = `${cfg}/kodflow/sessions`;
147  const entries = await p.list(root).catch(() => []);
148  const now = sec(p);
149  const found = await Promise.all(
150    entries
151      .filter((d) => d.kind === "dir" && d.name !== self)
152      .map(async (d) => {
153        const dir = `${root}/${d.name}`;
154        const text = await p.read(editsFile(dir));
155        if (!text) return undefined;
156        return isLive(await p.read(beatFile(dir)), now)
157          ? { session: d.name, text }
158          : undefined;
159      }),
160  );
161  return found.filter((x) => x !== undefined);
162}
163
164async function noteEdit(p: GuardPort, dir: string, path: string) {
165  const step = writing.then(async () => {
166    const file = editsFile(dir);
167    await p.write(file, record(await p.read(file), path, sec(p)));
168  });
169  writing = step.catch(() => undefined);
170  await step;
171}
172
173/**
174 * collision-guard, on tool.call of a writing tool: has another live session
175 * of this machine written this file in the last 30 minutes? Ask; then, once
176 * the write went through, note it in this session's edits.tsv.
177 */
178export async function guardWrite<R>(
179  p: GuardPort,
180  e: Record<string, unknown>,
181  next: () => Promise<R>,
182): Promise<R | { deny: string }> {
183  if (await p.off()) return next();
184  const path = targetOf(e.tool, e, await p.cwd());
185  const cfg = await p.config();
186  if (path === undefined || !cfg || excluded(path, cfg)) return next();
187  const self = safe(await p.session());
188  const now = sec(p);
189  const hit = await others(p, cfg, self).then(
190    (o) => newest(path, o, now),
191    () => undefined,
192  );
193  if (
194    hit &&
195    hit.at > (acknowledged.get(path) ?? 0) &&
196    !present(lastComposerMs, p.now())
197  ) {
198    // Nobody typed a prompt lately: asking would hold the edit until someone
199    // comes back. Journaled, and the edit goes on.
200    p.log(
201      `collision-guard: ${path} edited by session ${hit.session} at ${hit.at}; no prompt typed in 10 min, not asked, the edit goes on`,
202    );
203  } else if (hit && hit.at > (acknowledged.get(path) ?? 0)) {
204    // The dialog dismissed, or no one to ask after all: the edit goes on
205    const chosen = await p
206      .ask(question(path, hit, now), [CONTINUE, WORKTREE, CANCEL])
207      .catch(() => undefined);
208    p.log(
209      `collision-guard: ${path} edited by session ${hit.session} at ${hit.at}; answer: ${chosen ?? "none, the edit goes on"}`,
210    );
211    if (chosen !== undefined) {
212      const verdict = answer(chosen, path);
213      if ("deny" in verdict) return verdict;
214      acknowledged.set(path, hit.at);
215    }
216  }
217  const r: any = await next();
218  if (!r?.deny && !r?.isError)
219    await noteEdit(p, sessionDir(cfg, self), path).catch(() => undefined);
220  return r;
221}
222
223/**
224 * session.end: this session's edits stop counting at once, rather than when
225 * its beat ages out of the window.
226 */
227export async function endGuards(p: GuardPort): Promise<void> {
228  const cfg = await p.config();
229  if (!cfg) return;
230  const file = editsFile(sessionDir(cfg, safe(await p.session())));
231  if ((await p.read(file)) !== undefined) await p.write(file, "");
232}
233
hooks/mod/guards.ts 916 lines
1// guards.ts — the shell's Bash guards, doubled in the mod (L4). No `$`.
2//
3// on-tool.sh stays the authority (D1); this is a second copy that only ever
4// refuses, for a session where the shell hook is missing, edited or slow.
5// Same reader (shell.ts), same order of blocks, same motifs, so the
6// bash-guard corpus decides both the same way (tests/mod/guards.corpus.ts).
7//
8// Not doubled: the staged-secret scan (BLOCK 3), which reads the index blob
9// by blob and stays the shell's alone. The mcp.json refusal of the same block
10// is doubled: it reads the index once, by name and status only.
11import { argvOf, fileText, parse, type Parsed } from "./shell.ts";
12import { scan, type Hit, type Kind, type Rules } from "./patterns.ts";
13
14export type GuardCtx = {
15  /** Set when a subagent makes the call. */
16  agentId?: string;
17  /** The delegation gate applies: main thread, KODFLOW_ROOT not off. */
18  rootMain: boolean;
19  /** The session's directory, against which relative paths resolve. */
20  projectDir: string;
21  home?: string;
22  /** <config> (CLAUDE_CONFIG_DIR, else ~/.claude). */
23  configDir?: string;
24  /** A file's text, undefined when absent; relative to projectDir. */
25  read(path: string): Promise<string | undefined>;
26  /** `git -C dir …`'s stdout, undefined on failure. */
27  git(dir: string, args: string[]): Promise<string | undefined>;
28  /** The vendored §5 rules (hooks/patterns), undefined when unreadable. */
29  patterns(): Promise<Rules | undefined>;
30};
31
32export type Findings = {
33  root?: string;
34  noVerify?: string;
35  attr?: Hit;
36  commit: boolean;
37  force: boolean;
38  merge?: string;
39  defaultPush?: string;
40  modWrite?: string;
41  plugin?: string;
42  /** An mcp.json added or committed, and how. */
43  mcpJson?: string;
44};
45
46export type Refusal = { motif: string; title: string; lines: string[] };
47
48const isNoVerify = (v: string) =>
49  v === "--no-veri" || v === "--no-verif" || v === "--no-verify";
50
51export const MERGE_RE =
52  /(^|\/)pulls\/[^/\s]+\/merge\/?$|merge_requests\/[^/\s]+\/merge\/?$/;
53export const MERGE_WORDS =
54  /mergePullRequest|enablePullRequestAutoMerge|merge_when_pipeline_succeeds/;
55
56/** mcp.json or .mcp.json, any case, at any path: it may carry tokens. */
57export const isMcpJson = (path: string) => /(^|\/)\.?mcp\.json$/i.test(path);
58
59/**
60 * `git diff --name-status -z` → the paths it adds or changes; a deletion is
61 * left out, and a rename or a copy gives its new path.
62 */
63export function changedPaths(out: string): string[] {
64  const w = out.split("\0");
65  const paths: string[] = [];
66  for (let i = 0; i + 1 < w.length; ) {
67    const st = w[i]!;
68    if (!st) break;
69    const two = st[0] === "R" || st[0] === "C";
70    const path = w[i + (two ? 2 : 1)] ?? "";
71    if (st[0] !== "D") paths.push(path);
72    i += two ? 3 : 2;
73  }
74  return paths;
75}
76
77/** The refusal of an mcp.json added or committed (BLOCK 3 of on-tool.sh). */
78export function mcpJsonRefusal(what: string): Refusal {
79  return {
80    motif: "mcp-json",
81    title: `BLOCKED — an mcp.json file is never committed (${what})`,
82    lines: [
83      "mcp.json and .mcp.json may carry tokens: neither is added nor committed, at any path.",
84      "Deleting one stays allowed: git rm --cached <path>, then commit the deletion.",
85      "A plugin declares its MCP servers in plugin.json (mcpServers), not in a .mcp.json.",
86    ],
87  };
88}
89
90type SpecMode = "add" | "add-f" | "update" | "commit";
91
92/**
93 * The first mcp.json a set of pathspecs would take in, a deletion left out.
94 * git status resolves them as git add and git commit do ("XY path", the old
95 * path after a rename; Y is the working tree). add-f lists ignored files too.
96 */
97async function mcpJsonSpecs(
98  ctx: Pick<GuardCtx, "git">,
99  dir: string,
100  mode: SpecMode,
101  specs: string[],
102): Promise<string | undefined> {
103  const opt =
104    mode === "update" || mode === "commit"
105      ? ["--untracked-files=no"]
106      : mode === "add-f"
107        ? ["--untracked-files=all", "--ignored"]
108        : ["--untracked-files=all"];
109  const w = (
110    (await ctx.git(dir, ["status", "--porcelain", "-z", ...opt, "--", ...specs])) ?? ""
111  ).split("\0");
112  for (let i = 0; i < w.length; i++) {
113    const e = w[i]!;
114    if (e.length < 4) continue;
115    const x = e[0]!;
116    const y = e[1]!;
117    const f = e.slice(3);
118    if (x === "R" || x === "C") i++;
119    if (!isMcpJson(f) || y === "D") continue;
120    // staged already: only a commit takes it
121    if (y === " " && (mode !== "commit" || x === "D" || x === " ")) continue;
122    return f;
123  }
124  return undefined;
125}
126
127/** A --pathspec-from-file's pathspecs, one a line. */
128async function specsFrom(
129  ctx: GuardCtx,
130  p: Parsed,
131  k: number,
132  file: string,
133  gdir: string,
134): Promise<string[]> {
135  const f = file === "-" || file.startsWith("/") ? file : `${gdir}/${file}`;
136  return (await fileText(p, k, f, ctx.read)).split("\n").filter(Boolean);
137}
138
139/** A path a skills directory must never receive (plugin machinery). */
140export function modPath(
141  path: string,
142  home: string | undefined,
143  configDir: string | undefined,
144): boolean {
145  let f = path;
146  const cfg = (configDir || `${home ?? ""}/.claude`).replace(/\/+$/, "");
147  if (f.startsWith("~/")) f = `${home ?? ""}/${f.slice(2)}`;
148  f = `/${f.replace(/^\//, "")}`;
149  if (!(f.includes("/.claude/skills/") || f.startsWith(`${cfg}/skills/`)))
150    return false;
151  return (
152    f.includes("/.claude-plugin/") ||
153    f.endsWith("/.claude-plugin") ||
154    f.endsWith("/hooks/hooks.json")
155  );
156}
157
158type State = {
159  f: Findings;
160  gdir: string;
161  hooks: boolean;
162  amend: boolean;
163  /** git commit -a: the tracked changes are staged first. */
164  all: boolean;
165  /** The repository the commit runs in. */
166  cgdir: string;
167  scan: (kind: Kind, text: string) => Hit | undefined;
168};
169
170function hit(st: State, h: Hit | undefined): void {
171  if (!st.f.attr && h) st.f.attr = h;
172}
173
174async function defaults(ctx: GuardCtx, dir: string): Promise<Set<string>> {
175  const set = new Set(["main", "master"]);
176  const h = await ctx.git(dir, [
177    "symbolic-ref",
178    "--short",
179    "refs/remotes/origin/HEAD",
180  ]);
181  if (h) set.add(h.trim().replace(/^origin\//, ""));
182  return set;
183}
184
185async function guardPush(
186  ctx: GuardCtx,
187  st: State,
188  A: string[],
189  y0: number,
190  gdir: string,
191): Promise<void> {
192  let pos = 0;
193  const refs: string[] = [];
194  let force = false;
195  let all = false;
196  for (let y = y0; y < A.length; y++) {
197    const v = A[y]!;
198    if (
199      v.startsWith("--force-with-lease") ||
200      v === "--force-if-includes" ||
201      v.startsWith("--no-force-")
202    ) {
203      /* safe */
204    } else if (v === "--force") force = true;
205    else if (v === "--mirror" || v === "--all" || v === "--branches")
206      all = true;
207    else if (
208      ["--repo", "--receive-pack", "--exec", "--push-option", "-o"].includes(v)
209    )
210      y++;
211    else if (v.startsWith("--")) {
212      if (isNoVerify(v)) st.f.noVerify = "--no-verify on git push";
213    } else if (v.startsWith("-")) {
214      if (v.includes("f")) force = true;
215    } else {
216      pos++;
217      if (pos >= 2) refs.push(v);
218      if (v.startsWith("+") && pos >= 2) force = true;
219    }
220  }
221  if (force) st.f.force = true;
222  if (!ctx.agentId) return;
223  const defs = await defaults(ctx, gdir);
224  if (all) {
225    st.f.defaultPush = "git push --all/--mirror includes the default branch";
226    return;
227  }
228  const current = async () =>
229    (await ctx.git(gdir, ["symbolic-ref", "--short", "HEAD"]))?.trim() ?? "";
230  if (!refs.length) {
231    const cur = await current();
232    if (cur && defs.has(cur))
233      st.f.defaultPush = `git push from ${cur}, the default branch`;
234    return;
235  }
236  for (let r of refs) {
237    r = r.replace(/^\+/, "");
238    let dst = r.includes(":") ? r.slice(r.indexOf(":") + 1) : r;
239    if (dst === "HEAD" || r === "HEAD") dst = await current();
240    dst = dst.replace(/^refs\/heads\//, "");
241    if (dst && defs.has(dst))
242      st.f.defaultPush = `git push to ${dst}, the default branch`;
243  }
244}
245
246async function guardGit(
247  ctx: GuardCtx,
248  st: State,
249  p: Parsed,
250  k: number,
251  A: string[],
252): Promise<void> {
253  let y = 1;
254  let gdir = st.gdir;
255  st.hooks = false;
256  while (y < A.length) {
257    const v = A[y]!;
258    if (v === "-C") {
259      // joined onto the cd directory, as git does
260      const c = A[y + 1] ?? "";
261      gdir = c.startsWith("/") || !gdir ? c : `${gdir}/${c}`;
262      y += 2;
263      continue;
264    }
265    if (v === "-c" || v === "--config-env") {
266      if ((A[y + 1] ?? "").toLowerCase().startsWith("core.hookspath="))
267        st.hooks = true;
268      y += 2;
269      continue;
270    }
271    if (v.startsWith("--config-env=")) {
272      if (v.toLowerCase().includes("=core.hookspath=")) st.hooks = true;
273    } else if (
274      ["--git-dir", "--work-tree", "--namespace", "--super-prefix"].includes(v)
275    ) {
276      y += 2;
277      continue;
278    } else if (!v.startsWith("-")) break;
279    y++;
280  }
281  if (!gdir) gdir = ctx.projectDir;
282  else if (!gdir.startsWith("/")) gdir = `${ctx.projectDir}/${gdir}`;
283  const sub = A[y] ?? "";
284  y++;
285  const rest = A.slice(y);
286  if (
287    [
288      "commit",
289      "push",
290      "rebase",
291      "cherry-pick",
292      "merge",
293      "am",
294      "apply",
295      "revert",
296    ].includes(sub)
297  )
298    st.f.root = `git ${sub} from the main thread produces into a repository.`;
299  else if (sub === "worktree" && A[y] === "add")
300    st.f.root = "git worktree from the main thread produces into a repository.";
301  else if (sub === "reset" && rest.includes("--hard"))
302    st.f.root = "git reset from the main thread produces into a repository.";
303  if (
304    st.hooks &&
305    [
306      "commit",
307      "push",
308      "merge",
309      "am",
310      "rebase",
311      "cherry-pick",
312      "revert",
313      "pull",
314    ].includes(sub)
315  )
316    st.f.noVerify = `git -c core.hooksPath on git ${sub}`;
317
318  if (sub === "add" || sub === "stage") {
319    // Every word but an option's names a pathspec, -f or not; then git
320    // status says what `.`, a directory, a glob or -A would take in
321    let mode: SpecMode = "add";
322    let all = false;
323    const specs: string[] = [];
324    while (y < A.length) {
325      const v = A[y]!;
326      if (v === "--pathspec-from-file") {
327        specs.push(...(await specsFrom(ctx, p, k, A[y + 1] ?? "", gdir)));
328        y += 2;
329        continue;
330      }
331      if (v.startsWith("--pathspec-from-file="))
332        specs.push(...(await specsFrom(ctx, p, k, v.slice(21), gdir)));
333      else if (v === "--all" || v === "--no-ignore-removal") all = true;
334      else if (v === "--update") {
335        all = true;
336        if (mode === "add") mode = "update";
337      } else if (v === "--force") mode = "add-f";
338      else if (v.startsWith("--")) {
339        /* another option */
340      } else if (v.startsWith("-")) {
341        if (v.includes("f")) mode = "add-f";
342        if (v.includes("A")) all = true;
343        if (v.includes("u")) {
344          all = true;
345          if (mode === "add") mode = "update";
346        }
347      } else {
348        if (isMcpJson(v)) st.f.mcpJson = `git ${sub} ${v}`;
349        specs.push(v);
350      }
351      y++;
352    }
353    if (!st.f.mcpJson && (specs.length || all)) {
354      const f = await mcpJsonSpecs(ctx, gdir, mode, specs);
355      if (f) st.f.mcpJson = `git ${sub} would add ${f}`;
356    }
357  } else if (sub === "commit") {
358    st.f.commit = true;
359    st.cgdir = gdir;
360    const specs: string[] = [];
361    let msg = "";
362    let farg = "";
363    let given = false;
364    while (y < A.length) {
365      const v = A[y]!;
366      if (v === "--") {
367        for (const w of A.slice(y + 1)) {
368          if (isMcpJson(w)) st.f.mcpJson = `git commit ${w}`;
369          specs.push(w);
370        }
371        break;
372      }
373      if (v === "--pathspec-from-file") {
374        specs.push(...(await specsFrom(ctx, p, k, A[y + 1] ?? "", gdir)));
375        y += 2;
376        continue;
377      }
378      if (v.startsWith("--pathspec-from-file=")) {
379        specs.push(...(await specsFrom(ctx, p, k, v.slice(21), gdir)));
380        y++;
381        continue;
382      }
383      if (v === "-m" || v === "--message" || v === "--trailer") {
384        msg += `\n${A[y + 1] ?? ""}`;
385        given = true;
386        y += 2;
387        continue;
388      }
389      if (v.startsWith("--message=") || v.startsWith("--trailer=")) {
390        msg += `\n${v.slice(v.indexOf("=") + 1)}`;
391        given = true;
392      } else if (v === "-F" || v === "--file") {
393        farg = A[y + 1] ?? "";
394        y += 2;
395        continue;
396      } else if (v.startsWith("--file=")) farg = v.slice(7);
397      else if (
398        [
399          "-C",
400          "-c",
401          "-t",
402          "--reuse-message",
403          "--reedit-message",
404          "--author",
405          "--date",
406          "--cleanup",
407          "--template",
408          "--fixup",
409          "--squash",
410        ].includes(v)
411      ) {
412        y += 2;
413        continue;
414      } else if (v === "--amend") st.amend = true;
415      else if (v === "--all") st.all = true;
416      else if (v.startsWith("--")) {
417        if (isNoVerify(v)) st.f.noVerify = "--no-verify on git commit";
418      } else if (v.startsWith("-")) {
419        let cl = v.slice(1);
420        while (cl) {
421          const ch = cl[0]!;
422          let r = cl.slice(1);
423          if (ch === "n") st.f.noVerify = "-n (--no-verify) on git commit";
424          else if (ch === "a") st.all = true;
425          else if (ch === "u" || ch === "S") break;
426          else if ("mFCct".includes(ch)) {
427            if (!r) {
428              r = A[y + 1] ?? "";
429              y++;
430            }
431            if (ch === "m") {
432              msg += `\n${r}`;
433              given = true;
434            } else if (ch === "F") farg = r;
435            break;
436          }
437          cl = r;
438        }
439      } else {
440        // a pathspec
441        if (isMcpJson(v)) st.f.mcpJson = `git commit ${v}`;
442        specs.push(v);
443      }
444      y++;
445    }
446    // A pathspec (`.`, a directory) takes the working tree's copy in
447    if (!st.f.mcpJson && specs.length) {
448      const f = await mcpJsonSpecs(ctx, gdir, "commit", specs);
449      if (f) st.f.mcpJson = `git commit ${specs.join(" ")} takes in ${f}`;
450    }
451    let hay = msg;
452    if (farg) hay += `\n${await fileText(p, k, farg, ctx.read)}`;
453    if (st.amend && !given && !farg)
454      hay += `\n${(await ctx.git(gdir, ["log", "-1", "--pretty=%B"])) ?? ""}`;
455    hit(st, st.scan("commit", hay));
456  } else if (sub === "merge") {
457    while (y < A.length) {
458      const v = A[y]!;
459      if (v === "-m") {
460        hit(st, st.scan("commit", A[y + 1] ?? ""));
461        y += 2;
462        continue;
463      }
464      if (v === "-F" || v === "--file") {
465        hit(st, st.scan("commit", await fileText(p, k, A[y + 1] ?? "", ctx.read)));
466        y += 2;
467        continue;
468      }
469      if (v.startsWith("--") && isNoVerify(v))
470        st.f.noVerify = "--no-verify on git merge";
471      y++;
472    }
473  } else if (sub === "rebase" || sub === "cherry-pick") {
474    for (const v of rest)
475      if (isNoVerify(v)) st.f.noVerify = `--no-verify on git ${sub}`;
476    hit(
477      st,
478      st.scan("commit", (await ctx.git(gdir, ["log", "-5", "--pretty=%B"])) ?? ""),
479    );
480  } else if (sub === "am" || sub === "revert" || sub === "pull") {
481    for (const v of rest)
482      if (isNoVerify(v)) st.f.noVerify = `--no-verify on git ${sub}`;
483  } else if (sub === "push") await guardPush(ctx, st, A, y, gdir);
484}
485
486async function guardGh(
487  ctx: GuardCtx,
488  st: State,
489  p: Parsed,
490  k: number,
491  A: string[],
492): Promise<void> {
493  let y = 1;
494  while (y < A.length) {
495    const v = A[y]!;
496    if (v === "-R" || v === "--repo" || v === "--hostname") y += 2;
497    else if (v.startsWith("-")) y++;
498    else break;
499  }
500  const sub = A[y] ?? "";
501  const act = A[y + 1] ?? "";
502  let hay = "";
503  if (sub === "pr" && (act === "create" || act === "edit")) {
504    if (act === "create")
505      st.f.root =
506        "gh pr create from the main thread: opening the PR is the subagent's delivery.";
507    y += 2;
508    while (y < A.length) {
509      const v = A[y]!;
510      if (["-t", "--title", "-b", "--body"].includes(v)) {
511        hay += `\n${A[y + 1] ?? ""}`;
512        y += 2;
513        continue;
514      }
515      if (v.startsWith("--title=") || v.startsWith("--body="))
516        hay += `\n${v.slice(v.indexOf("=") + 1)}`;
517      else if (v === "-F" || v === "--body-file") {
518        hay += `\n${await fileText(p, k, A[y + 1] ?? "", ctx.read)}`;
519        y += 2;
520        continue;
521      } else if (v.startsWith("--body-file="))
522        hay += `\n${await fileText(p, k, v.slice(12), ctx.read)}`;
523      else if (
524        [
525          "-R",
526          "--repo",
527          "-B",
528          "--base",
529          "-H",
530          "--head",
531          "-a",
532          "--assignee",
533          "-l",
534          "--label",
535          "-m",
536          "--milestone",
537          "-p",
538          "--project",
539          "-r",
540          "--reviewer",
541          "-T",
542          "--template",
543        ].includes(v) ||
544        v.startsWith("--add-") ||
545        v.startsWith("--remove-")
546      ) {
547        y += 2;
548        continue;
549      }
550      y++;
551    }
552    hit(st, st.scan("pr", hay));
553  } else if (sub === "pr" && act === "merge") st.f.merge = "gh pr merge";
554  else if (sub === "api") {
555    let ep = "";
556    y++;
557    while (y < A.length) {
558      const v = A[y]!;
559      if (["-f", "--raw-field", "-F", "--field"].includes(v)) {
560        const f = A[y + 1] ?? "";
561        const at = f.indexOf("=@");
562        hay +=
563          at >= 0
564            ? `\n${await fileText(p, k, f.slice(at + 2), ctx.read)}`
565            : `\n${f.includes("=") ? f.slice(f.indexOf("=") + 1) : f}`;
566        y += 2;
567        continue;
568      }
569      if (v === "--input") {
570        hay += `\n${await fileText(p, k, A[y + 1] ?? "", ctx.read)}`;
571        y += 2;
572        continue;
573      }
574      if (
575        [
576          "-X",
577          "--method",
578          "-H",
579          "--header",
580          "-q",
581          "--jq",
582          "-t",
583          "--template",
584          "-p",
585          "--preview",
586          "--hostname",
587          "--cache",
588        ].includes(v)
589      ) {
590        y += 2;
591        continue;
592      }
593      if (!v.startsWith("-") && !ep) ep = v;
594      y++;
595    }
596    if (MERGE_RE.test(ep)) st.f.merge = `gh api ${ep}`;
597    else if (ep === "graphql") {
598      const m = MERGE_WORDS.exec(hay);
599      if (m) st.f.merge = `gh api graphql ${m[0]}`;
600      if (/(create|update)PullRequest/.test(hay)) hit(st, st.scan("pr", hay));
601    } else if (/(^|\/)pulls(\/[^/]+)?\/?$/.test(ep)) hit(st, st.scan("pr", hay));
602  }
603}
604
605function guardGlab(st: State, A: string[]): void {
606  let y = 1;
607  while (y < A.length) {
608    const v = A[y]!;
609    if (v === "-R" || v === "--repo") y += 2;
610    else if (v.startsWith("-")) y++;
611    else break;
612  }
613  const sub = A[y] ?? "";
614  const act = A[y + 1] ?? "";
615  const words = MERGE_WORDS.exec(A.join(" "));
616  if (words) st.f.merge = `glab ${words[0]}`;
617  if (sub === "mr" && (act === "create" || act === "update")) {
618    if (act === "create")
619      st.f.root =
620        "glab mr create from the main thread: opening the PR is the subagent's delivery.";
621    let hay = "";
622    y += 2;
623    while (y < A.length) {
624      const v = A[y]!;
625      if (["-t", "--title", "-d", "--description"].includes(v)) {
626        hay += `\n${A[y + 1] ?? ""}`;
627        y += 2;
628        continue;
629      }
630      if (v.startsWith("--title=") || v.startsWith("--description="))
631        hay += `\n${v.slice(v.indexOf("=") + 1)}`;
632      y++;
633    }
634    hit(st, st.scan("pr", hay));
635  } else if (sub === "mr" && act === "merge") st.f.merge = "glab mr merge";
636  else if (sub === "api") {
637    y++;
638    while (y < A.length) {
639      const v = A[y]!;
640      if (
641        [
642          "-X",
643          "--method",
644          "-H",
645          "--header",
646          "-f",
647          "--raw-field",
648          "-F",
649          "--field",
650          "--hostname",
651          "--input",
652        ].includes(v)
653      ) {
654        y += 2;
655        continue;
656      }
657      if (!v.startsWith("-")) {
658        if (MERGE_RE.test(v)) st.f.merge = `glab api ${v}`;
659        break;
660      }
661      y++;
662    }
663  }
664}
665
666function guardHttp(st: State, name: string, A: string[]): void {
667  for (const v of A.slice(1)) {
668    const m = MERGE_RE.exec(v) ?? MERGE_WORDS.exec(v);
669    if (m) {
670      st.f.merge = `${name} ${m[0]}`;
671      return;
672    }
673    if (/\/pulls\/[^/\s]+\/merge([/?\s]|$)/.test(v)) {
674      st.f.merge = `${name} …/merge`;
675      return;
676    }
677  }
678}
679
680function guardClaude(st: State, A: string[]): void {
681  if (A[1] !== "plugin" && A[1] !== "plugins") return;
682  let y: number;
683  if (A[2] === "install" || A[2] === "i") y = 3;
684  else if (A[2] === "marketplace" && A[3] === "add") y = 4;
685  else return;
686  let spec = "";
687  while (y < A.length) {
688    const v = A[y]!;
689    if (v === "-s" || v === "--scope") {
690      y += 2;
691      continue;
692    }
693    if (!v.startsWith("-")) {
694      spec = v;
695      break;
696    }
697    y++;
698  }
699  if (!spec) return;
700  const ok =
701    A[2] === "marketplace"
702      ? /kodflow\/claude-marketplace(\.git|\/)?$/.test(spec)
703      : spec.endsWith("@kodflow");
704  if (!ok)
705    st.f.plugin = `claude plugin ${A[2]}${A[2] === "marketplace" ? ` ${A[3]}` : ""} ${spec}`;
706}
707
708/** The cheap gate of pre_bash: a line naming no verb we know leaves at once. */
709export function gate(line: string): boolean {
710  const t = /["'\\]/.test(line) ? line.replace(/["'\\]/g, "") : line;
711  return (
712    /git|gh|glab|curl|wget|http|skills|claude/.test(t) || line.includes("$'")
713  );
714}
715
716/** What a Bash line does that a guard looks at. */
717export async function inspect(
718  line: string,
719  ctx: GuardCtx,
720): Promise<Findings | undefined> {
721  if (!line || !gate(line)) return undefined;
722  const p = parse(line);
723  const rules = await ctx.patterns();
724  const st: State = {
725    f: { commit: false, force: false },
726    gdir: "",
727    hooks: false,
728    amend: false,
729    all: false,
730    cgdir: "",
731    scan: (kind, text) => scan(kind, text, rules),
732  };
733  for (let k = 0; k < p.commands.length; k++) {
734    const cmd = p.commands[k]!;
735    for (const r of cmd.redirs)
736      if (modPath(r, ctx.home, ctx.configDir)) st.f.modWrite = r;
737    const { argv: A, name } = argvOf(cmd);
738    st.hooks = false;
739    if (name === "claude") guardClaude(st, A);
740    else if (name === "git") await guardGit(ctx, st, p, k, A);
741    else if (name === "gh") await guardGh(ctx, st, p, k, A);
742    else if (name === "glab") guardGlab(st, A);
743    else if (["curl", "wget", "http", "https", "xh"].includes(name))
744      guardHttp(st, name, A);
745    else if (name === "cd") {
746      const d = A[1] ?? "";
747      st.gdir = d.startsWith("/") || !d || !st.gdir ? d : `${st.gdir}/${d}`;
748    }
749  }
750  if (st.f.commit && !st.f.mcpJson) {
751    const dir = st.cgdir || ctx.projectDir;
752    const staged = changedPaths(
753      (await ctx.git(dir, ["diff", "--cached", "--name-status", "-z"])) ?? "",
754    ).find(isMcpJson);
755    if (staged) st.f.mcpJson = `${staged} is staged`;
756    else if (st.all) {
757      const changed = changedPaths(
758        (await ctx.git(dir, ["diff", "--name-status", "-z"])) ?? "",
759      ).find(isMcpJson);
760      if (changed)
761        st.f.mcpJson = `${changed} is modified and git commit -a stages it`;
762    }
763  }
764  return st.f;
765}
766
767/**
768 * A forge tool that writes an mcp.json: a path a write tool names (a read
769 * and a deletion are allowed), else, for a GitKraken add or commit naming no file, what the
770 * repository would take in. pre_forge of on-tool.sh, doubled.
771 */
772export async function forgeMcpJson(
773  tool: string,
774  input: Record<string, any>,
775  ctx: Pick<GuardCtx, "projectDir" | "git">,
776): Promise<Refusal | undefined> {
777  // A read or a deletion of one stays allowed
778  if (
779    !/^mcp__(github|gitlab)__.*(push_files|create_or_update_file|create_commit)$|^mcp__GitKraken__git_(add|commit)$/.test(
780      tool,
781    )
782  )
783    return undefined;
784  const paths: unknown[] = [input.path, input.file_path];
785  for (const f of Array.isArray(input.files) ? input.files : [])
786    paths.push(typeof f === "string" ? f : (f?.path ?? f?.file_path));
787  for (const a of Array.isArray(input.actions) ? input.actions : [])
788    if (a?.action !== "delete") paths.push(a?.file_path);
789  const named = paths.find((p) => typeof p === "string" && isMcpJson(p));
790  if (named) return mcpJsonRefusal(`${tool}: ${named}`);
791  const gk = /GitKraken__git_(add|commit)$/.test(tool);
792  if (!gk || (Array.isArray(input.files) && input.files.length)) return undefined;
793  let dir = typeof input.directory === "string" ? input.directory : ".";
794  if (!dir.startsWith("/")) dir = `${ctx.projectDir}/${dir}`;
795  if (tool.endsWith("git_add")) {
796    // "XY path", the old path after a rename; Y is the working tree
797    const w = (
798      (await ctx.git(dir, ["status", "--porcelain", "-z", "--untracked-files=all"])) ?? ""
799    ).split("\0");
800    for (let i = 0; i < w.length; i++) {
801      const e = w[i]!;
802      if (e.length < 4) continue;
803      if (e[0] === "R" || e[0] === "C") i++;
804      if (e[1] === " " || e[1] === "D") continue;
805      if (isMcpJson(e.slice(3)))
806        return mcpJsonRefusal(`${tool}: ${e.slice(3)}, added with every file`);
807    }
808    return undefined;
809  }
810  const staged = changedPaths(
811    (await ctx.git(dir, ["diff", "--cached", "--name-status", "-z"])) ?? "",
812  ).find(isMcpJson);
813  return staged ? mcpJsonRefusal(`${tool}: ${staged} is staged`) : undefined;
814}
815
816const ROOT_OK =
817  /^([A-Za-z_][A-Za-z0-9_]*=[^ \t\n\r\f\v]*[ \t\n\r\f\v]+)*ROOT_OK=1([ \t\n\r\f\v]|$)/;
818
819/** The command to run instead of a forced push (BLOCK 4). */
820export function withLease(line: string): string {
821  let fixed = line
822    .replace(/(^|\s)(--force|-f)(?=\s|$)/g, "$1--force-with-lease")
823    .replace(/(\s)\+(\S+)/g, "$1$2");
824  if (!fixed.includes("--force-with-lease")) fixed += " --force-with-lease";
825  return fixed;
826}
827
828/** The first block on-tool.sh's pre_bash would raise, in its order. */
829export async function verdict(
830  line: string,
831  f: Findings,
832  ctx: GuardCtx,
833): Promise<Refusal | undefined> {
834  if (f.root && ctx.rootMain && !ROOT_OK.test(line))
835    return {
836      motif: "root",
837      title: "BLOCKED — code production in a repository is delegated",
838      lines: [
839        f.root,
840        "Dispatch the epic's subagent (task_focus the epic first), or SendMessage it if it is running;",
841        "it works in its own worktree and delivers through a PR.",
842        "A genuine exception: prefix the Bash line with ROOT_OK=1 (KODFLOW_ROOT=off turns the gate off).",
843      ],
844    };
845  if (f.noVerify)
846    return {
847      motif: "no-verify",
848      title: `COMMAND BLOCKED — skipping git hooks is forbidden (${f.noVerify})`,
849      lines: [
850        "Local git hooks are the second layer of the attribution and secret guards.",
851        "If a hook is wrong, fix the hook; do not skip it.",
852      ],
853    };
854  if (f.attr)
855    return {
856      motif: f.attr.motif,
857      title: `${f.attr.kind === "pr" ? "PULL REQUEST" : "COMMIT"} BLOCKED — AI reference detected`,
858      lines: [
859        `Forbidden pattern: ${f.attr.pattern}`,
860        "Remove AI attribution (co-authored-by, generated by, the robot emoji) and, in a commit, workflow leaks (.claude/ paths, Plan: footers).",
861      ],
862    };
863  if (f.mcpJson) return mcpJsonRefusal(f.mcpJson);
864  if (f.modWrite)
865    return {
866      motif: "mod-write",
867      title: `COMMAND BLOCKED — plugin machinery written under a skills directory (${f.modWrite})`,
868      lines: ["Ship it as a plugin of the kodflow marketplace instead."],
869    };
870  if (f.plugin)
871    return {
872      motif: "plugin-source",
873      title: `COMMAND BLOCKED — plugin from outside the kodflow marketplace (${f.plugin})`,
874      lines: ["Ask the user to install it themselves if it is wanted."],
875    };
876  if (f.force)
877    return {
878      motif: "force",
879      title: "COMMAND BLOCKED — forced push",
880      lines: [
881        "--force, -f and a +refspec overwrite the remote without checking what is there.",
882        `Run instead: ${withLease(line)}`,
883      ],
884    };
885  if (ctx.agentId) {
886    if (f.merge)
887      return {
888        motif: "merge",
889        title: `COMMAND BLOCKED — a subagent does not merge (${f.merge})`,
890        lines: [
891          "Merging is the main thread's decision.",
892          "Report the PR and its CI state; stop there.",
893        ],
894      };
895    if (f.defaultPush)
896      return {
897        motif: "push-default",
898        title: `COMMAND BLOCKED — a subagent does not push to the default branch (${f.defaultPush})`,
899        lines: ["Push your feature branch and open a PR."],
900      };
901  }
902  return undefined;
903}
904
905/** A refusal as the model reads it, laid out like the shell's _block. */
906export function refusalText(r: Refusal): string {
907  const bar = "═══════════════════════════════════════════════";
908  return [
909    bar,
910    `  ❌ ${r.title}`,
911    bar,
912    ...r.lines.map((l) => `  ${l}`),
913    `  [motif:${r.motif}]`,
914  ].join("\n");
915}
916
hooks/mod/patterns.ts 164 lines
1// patterns.ts — §5 of the user's rules, as on-tool.sh's _scan applies them. Pure.
2//
3// The rules are kodflow/post-commit's patterns.txt and patterns-strict.txt,
4// vendored at a pinned commit in hooks/patterns (SOURCE names it). Both
5// readers apply the same format: one POSIX ERE a line, `#` and blank lines
6// skipped, `# @scope: <list>` for what follows, `commit` before the first.
7// A commit message meets every pattern, strict included; a pull or merge
8// request title or body meets the `pr` scope only.
9//
10// The shell feeds each text to `grep -qiE`, which matches line by line: `^`
11// anchors a line, and neither `.` nor a bracket expression crosses a newline.
12// toRegExp keeps that: the multiline flag, `[ \t\r\f\v]` for POSIX
13// `[[:space:]]`, and a newline added to every negated bracket.
14
15export type Kind = "commit" | "pr";
16export type Hit = { motif: string; pattern: string; kind: Kind };
17export type Rule = { motif: string; re: RegExp };
18/** attr: the commit,pr scope. commit: the commit-only rest, leaks first. */
19export type Rules = { attr: readonly Rule[]; commit: readonly Rule[] };
20
21export const PATTERN_FILES = ["patterns.txt", "patterns-strict.txt"] as const;
22
23const CLASSES: Record<string, string> = {
24  space: " \\t\\r\\f\\v",
25  blank: " \\t",
26  digit: "0-9",
27  lower: "a-z",
28  upper: "A-Z",
29  alpha: "a-zA-Z",
30  alnum: "a-zA-Z0-9",
31};
32
33/** A POSIX ERE as grep -iE reads it, line by line, as a JavaScript RegExp. */
34export function toRegExp(ere: string): RegExp {
35  let out = "";
36  for (let i = 0; i < ere.length; i++) {
37    const c = ere[i]!;
38    if (c === "\\") {
39      out += ere.slice(i, i + 2);
40      i++;
41    } else if (c === "[") {
42      let j = i + 1;
43      const neg = ere[j] === "^";
44      if (neg) j++;
45      let body = "";
46      if (ere[j] === "]") {
47        body += "\\]";
48        j++;
49      }
50      while (j < ere.length && ere[j] !== "]") {
51        const m = /^\[:([a-z]+):\]/.exec(ere.slice(j));
52        if (m) {
53          const cls = CLASSES[m[1]!];
54          if (cls === undefined)
55            throw new Error(`unsupported class [:${m[1]}:]`);
56          body += cls;
57          j += m[0].length;
58        } else {
59          body += ere[j] === "\\" || ere[j] === "[" ? `\\${ere[j]}` : ere[j];
60          j++;
61        }
62      }
63      if (j >= ere.length) throw new Error(`unclosed bracket in ${ere}`);
64      out += `[${neg ? "^" : ""}${body}${neg ? "\\n" : ""}]`;
65      i = j;
66    } else out += c;
67  }
68  return new RegExp(out, "imu");
69}
70
71/**
72 * The rules of the two files' texts, in order; undefined when one is missing,
73 * a directive is malformed or a pattern does not translate, which scan
74 * refuses rather than read as clean. A commit-only pattern naming a workflow
75 * artefact (a .claude path, the Plan: footer) is a leak and is tried before
76 * the vendor keywords, so `\bclaude\b` does not report `.claude/plans/x.md`
77 * as an attribution.
78 */
79export function parseRules(
80  texts: readonly (string | undefined)[],
81): Rules | undefined {
82  const attr: Rule[] = [];
83  const leak: Rule[] = [];
84  const kw: Rule[] = [];
85  for (const text of texts) {
86    if (text === undefined) return undefined;
87    let scope = ["commit"];
88    for (const line of text.split("\n")) {
89      const d = /^#\s*@scope:(.*)$/.exec(line);
90      if (d) {
91        const list = d[1]!.replace(/\s/g, "");
92        if (!/^[a-z]+(,[a-z]+)*$/.test(list)) return undefined;
93        scope = list.split(",");
94        if (scope.some((s) => s !== "commit" && s !== "pr")) return undefined;
95        continue;
96      }
97      if (line === "" || line.startsWith("#")) continue;
98      let re: RegExp;
99      try {
100        re = toRegExp(line);
101      } catch {
102        return undefined;
103      }
104      if (scope.includes("pr")) attr.push({ motif: "attribution", re });
105      else if (/\\\.claude|plan:/.test(line)) leak.push({ motif: "leak", re });
106      else kw.push({ motif: "attribution", re });
107    }
108  }
109  const commit = [...leak, ...kw];
110  return attr.length && commit.length ? { attr, commit } : undefined;
111}
112
113/** The rules read from the vendored directory through `read`. */
114export async function loadRules(
115  read: (path: string) => Promise<string | undefined>,
116  dir: string,
117): Promise<Rules | undefined> {
118  return parseRules(
119    await Promise.all(
120      PATTERN_FILES.map((f) => read(`${dir}/${f}`).catch(() => undefined)),
121    ),
122  );
123}
124
125/** The first §5 pattern `text` meets for `kind`, undefined for none. */
126export function scan(
127  kind: Kind,
128  text: string,
129  rules: Rules | undefined,
130): Hit | undefined {
131  const hay = text.toLowerCase();
132  if (!/\S/.test(hay)) return undefined;
133  if (!rules)
134    return {
135      motif: "attribution",
136      pattern: `(hooks/patterns unreadable or malformed: nothing to check ${kind} text against)`,
137      kind,
138    };
139  for (const p of rules.attr)
140    if (p.re.test(hay)) return { motif: p.motif, pattern: p.re.source, kind };
141  if (kind !== "commit") return undefined;
142  const plain = plainNames(hay);
143  for (const p of rules.commit)
144    if (p.re.test(p.motif === "attribution" ? plain : hay))
145      return { motif: p.motif, pattern: p.re.source, kind };
146  return undefined;
147}
148
149/**
150 * The vendor keywords (claude, anthropic) aim at a mention of the assistant,
151 * not at a name that happens to contain the word. A name is technical when
152 * the word is glued to an alphanumeric by - _ . or / (super-claude,
153 * claude-code.d.ts, CLAUDE.md, @anthropic-ai/sdk) or sits inside backticks;
154 * such an occurrence becomes `x`. Only the keyword pass reads this text:
155 * leaks (.claude/ paths) and the attribution patterns see the text as
156 * written. `hay` is lowercased. Same rule as _plain_names of on-tool.sh.
157 */
158export function plainNames(hay: string): string {
159  return hay
160    .replace(/`[^`\n]*(claude|anthropic)[^`\n]*`/g, " ")
161    .replace(/([a-z0-9][-._/])(claude|anthropic)/g, "$1x")
162    .replace(/(claude|anthropic)([-_/][a-z0-9]|\.[a-z0-9])/g, "x$2");
163}
164
hooks/mod/filter.ts 345 lines
1// filter.ts — Bash output, compressed after the command ran (L3, D3). Pure.
2//
3// The input is never rewritten: the command runs as the model wrote it, and
4// what comes back is shortened for the model to read, in the shape the tool
5// gave it (every other key of the result kept). Only a line that is exactly
6// one simple command of a known kind is touched (git status, log and diff,
7// ls -l, find, grep -rn), never a read whose bytes count (cat, head, tail,
8// sed, diff, git show, git cat-file, …), never a failed, interrupted,
9// persisted, image, background or structured result, and only when the result
10// has the shape a Bash call gives (an object whose stdout is a string): the
11// shape is checked on every call, on whatever engine version, since a
12// version window goes stale with each release. Anything unexpected leaves
13// the result as it came: the caller wraps it, and a throw returns `r`
14// untouched.
15import { argvOf, parse, type Command } from "./shell.ts";
16
17/** Reads whose bytes count: their output is never touched. */
18export const BYTE_READS = new Set([
19  "cat",
20  "head",
21  "tail",
22  "sed",
23  "awk",
24  "diff",
25  "cmp",
26  "od",
27  "xxd",
28  "hexdump",
29  "base64",
30  "less",
31  "more",
32  "tac",
33  "nl",
34  "jq",
35  "yq",
36  "sha256sum",
37  "shasum",
38  "md5sum",
39  "cksum",
40]);
41const BYTE_GIT = new Set([
42  "show",
43  "cat-file",
44  "blame",
45  "format-patch",
46  "archive",
47  "ls-tree",
48  "rev-parse",
49]);
50
51/** The command when the line is exactly one plain one, else undefined. */
52function single(line: string): Command | undefined {
53  const p = parse(line);
54  if (p.nested || p.commands.length !== 1) return undefined;
55  const c = p.commands[0]!;
56  if (c.redirs.length || c.stdin || c.pipe) return undefined;
57  return c;
58}
59
60/** git's subcommand and its arguments, past the global options. */
61function gitSub(A: string[]): { sub: string; rest: string[] } {
62  let y = 1;
63  while (y < A.length && A[y]!.startsWith("-"))
64    y += ["-C", "-c", "--git-dir", "--work-tree"].includes(A[y]!) ? 2 : 1;
65  return { sub: A[y] ?? "", rest: A.slice(y + 1) };
66}
67
68/** True when anything on the line is a read whose bytes count. */
69export function readsBytes(line: string): boolean {
70  for (const c of parse(line).commands) {
71    const { argv, name } = argvOf(c);
72    if (BYTE_READS.has(name)) return true;
73    if (name === "git" && BYTE_GIT.has(gitSub(argv).sub)) return true;
74  }
75  return false;
76}
77
78const has = (rest: string[], ...flags: string[]) =>
79  rest.some((v) => flags.some((f) => v === f || v.startsWith(`${f}=`)));
80
81function squeezeBlank(lines: string[]): string[] {
82  const out: string[] = [];
83  for (const l of lines)
84    if (l.trim() || (out.length && out[out.length - 1]!.trim())) out.push(l);
85  while (out.length && !out[out.length - 1]!.trim()) out.pop();
86  return out;
87}
88
89function gitStatus(rest: string[], text: string): string | undefined {
90  if (has(rest, "--porcelain", "-s", "--short", "-z", "--null"))
91    return undefined;
92  const lines = text
93    .split("\n")
94    .filter(
95      (l) =>
96        !/^\s*\((use|commit or discard|create\/copy|fix conflicts|all conflicts|run)\b[^)]*\)\s*$/.test(
97          l,
98        ),
99    );
100  return (
101    squeezeBlank(
102      lines.map((l) =>
103        l.replace(
104          /^no changes added to commit \(use .*\)$/,
105          "no changes added to commit",
106        ),
107      ),
108    ).join("\n") + (text.endsWith("\n") ? "\n" : "")
109  );
110}
111
112function gitLog(rest: string[], text: string): string | undefined {
113  if (
114    has(
115      rest,
116      "--oneline",
117      "--format",
118      "--pretty",
119      "-p",
120      "-u",
121      "--patch",
122      "--stat",
123      "--shortstat",
124      "--numstat",
125      "--graph",
126      "--name-only",
127      "--name-status",
128      "-L",
129      "--raw",
130      "-z",
131      "--source",
132      "--show-signature",
133      "--decorate-refs",
134    )
135  )
136    return undefined;
137  const lines = text.split("\n");
138  const out: string[] = [];
139  let i = 0;
140  while (i < lines.length) {
141    const head = /^commit ([0-9a-f]{40})(.*)$/.exec(lines[i]!);
142    if (!head) {
143      if (!lines[i]!.trim()) {
144        i++;
145        continue;
146      }
147      return undefined; // not the shape this reads: leave it whole
148    }
149    i++;
150    let author = "";
151    let date = "";
152    while (i < lines.length && lines[i]!.trim()) {
153      const l = lines[i]!;
154      const a = /^Author:\s+(.*?)(\s+<[^>]*>)?$/.exec(l);
155      const d = /^Date:\s+(.*)$/.exec(l);
156      if (a) author = a[1]!;
157      else if (d) date = d[1]!;
158      else if (!/^Merge:\s/.test(l)) return undefined;
159      i++;
160    }
161    out.push(`${head[1]!.slice(0, 12)}${head[2]} · ${author} · ${date}`);
162    while (i < lines.length && !/^commit [0-9a-f]{40}/.test(lines[i]!)) {
163      const l = lines[i]!;
164      if (l.trim()) out.push(`  ${l.replace(/^ {4}/, "")}`);
165      i++;
166    }
167  }
168  return out.length ? `${out.join("\n")}\n` : undefined;
169}
170
171export const DIFF_MAX_LINES = 3000;
172
173function gitDiff(rest: string[], text: string): string | undefined {
174  if (
175    has(
176      rest,
177      "--stat",
178      "--name-only",
179      "--name-status",
180      "--numstat",
181      "--shortstat",
182      "--raw",
183      "-z",
184      "--binary",
185      "--output",
186      "--patch-with-raw",
187      "--summary",
188      "--check",
189    )
190  )
191    return undefined;
192  const lines = text.split("\n");
193  const kept: string[] = [];
194  let inHeader = false;
195  for (const l of lines) {
196    if (l.startsWith("diff --git ")) inHeader = true;
197    else if (l.startsWith("@@")) inHeader = false;
198    if (inHeader && /^index [0-9a-f]+\.\.[0-9a-f]+/.test(l)) continue;
199    kept.push(l);
200  }
201  if (kept.length > DIFF_MAX_LINES) {
202    const more = kept.length - DIFF_MAX_LINES;
203    return `${kept.slice(0, DIFF_MAX_LINES).join("\n")}\n… ${more} more lines (git diff --stat for the whole change, or a path to narrow it)\n`;
204  }
205  return kept.join("\n");
206}
207
208const LS_LONG =
209  /^([dlcbps-][rwxsStT-]{9}[@+.]?)\s+\d+\s+\S+\s+\S+\s+(\S+)\s+(\w{3}\s+\d+\s+[\d:]+|\d+\s+\w{3}\s+[\d:]+)\s(.*)$/;
210
211function ls(A: string[], text: string): string | undefined {
212  const flags = A.slice(1)
213    .filter((v) => /^-[^-]/.test(v))
214    .join("");
215  if (!flags.includes("l") || /[n@eO]/.test(flags)) return undefined;
216  let changed = false;
217  const out = text.split("\n").flatMap((l) => {
218    if (/^total \d+/.test(l)) {
219      changed = true;
220      return [];
221    }
222    const m = LS_LONG.exec(l);
223    if (!m) return [l];
224    changed = true;
225    return [`${m[1]} ${m[2]} ${m[3]!.replace(/\s+/g, " ")} ${m[4]}`];
226  });
227  return changed ? out.join("\n") : undefined;
228}
229
230export const GROUP_MIN_LINES = 20;
231
232function find(A: string[], text: string): string | undefined {
233  if (
234    A.some((v) =>
235      [
236        "-print0",
237        "-printf",
238        "-fprintf",
239        "-ls",
240        "-fls",
241        "-exec",
242        "-execdir",
243        "-ok",
244        "-delete",
245      ].includes(v),
246    )
247  )
248    return undefined;
249  const lines = text.split("\n").filter((l) => l !== "");
250  if (lines.length < GROUP_MIN_LINES) return undefined;
251  const byDir = new Map<string, string[]>();
252  for (const l of lines) {
253    const cut = l.lastIndexOf("/");
254    const dir = cut < 0 ? "." : l.slice(0, cut) || "/";
255    const name = cut < 0 ? l : l.slice(cut + 1);
256    if (!byDir.has(dir)) byDir.set(dir, []);
257    byDir.get(dir)!.push(name);
258  }
259  const out: string[] = [];
260  for (const [dir, names] of byDir) {
261    out.push(`${dir}/`);
262    for (const n of names) out.push(`  ${n}`);
263  }
264  return `${out.join("\n")}\n`;
265}
266
267export const GREP_LINE_MAX = 300;
268
269function grep(A: string[], text: string): string | undefined {
270  const flags = A.slice(1)
271    .filter((v) => /^-[^-]/.test(v))
272    .join("");
273  const long = A.slice(1).filter((v) => v.startsWith("--"));
274  const recursive =
275    /[rR]/.test(flags) ||
276    long.some((v) => /^--(recursive|dereference-recursive)$/.test(v));
277  const numbered = flags.includes("n") || long.includes("--line-number");
278  if (!recursive || !numbered) return undefined;
279  if (
280    /[clLoZzABCbqs]/.test(flags) ||
281    long.some((v) =>
282      /^--(count|files-with|files-without|only-matching|null|after|before|context|byte-offset|quiet|silent)/.test(
283        v,
284      ),
285    )
286  )
287    return undefined;
288  const lines = text.split("\n").filter((l) => l !== "");
289  if (lines.length < GROUP_MIN_LINES) return undefined;
290  const groups = new Map<string, string[]>();
291  for (const l of lines) {
292    const m = /^(.+?):(\d+):(.*)$/.exec(l);
293    if (!m) return undefined;
294    const t =
295      m[3]!.length > GREP_LINE_MAX
296        ? `${m[3]!.slice(0, GREP_LINE_MAX)}…`
297        : m[3]!;
298    if (!groups.has(m[1]!)) groups.set(m[1]!, []);
299    groups.get(m[1]!)!.push(`  ${m[2]}: ${t}`);
300  }
301  const out: string[] = [];
302  for (const [f, ls] of groups) out.push(f, ...ls);
303  return `${out.join("\n")}\n`;
304}
305
306/** The compressed stdout for `line`, undefined to leave it as it is. */
307export function compress(line: string, stdout: string): string | undefined {
308  if (!stdout) return undefined;
309  const c = single(line);
310  if (!c) return undefined;
311  const { argv: A, name } = argvOf(c);
312  if (BYTE_READS.has(name)) return undefined;
313  let out: string | undefined;
314  if (name === "git") {
315    const { sub, rest } = gitSub(A);
316    if (sub === "status") out = gitStatus(rest, stdout);
317    else if (sub === "log") out = gitLog(rest, stdout);
318    else if (sub === "diff") out = gitDiff(rest, stdout);
319  } else if (name === "ls") out = ls(A, stdout);
320  else if (name === "find") out = find(A, stdout);
321  else if (name === "grep") out = grep(A, stdout);
322  return out !== undefined && out.length < stdout.length ? out : undefined;
323}
324
325type AnyResult = Record<string, any>;
326
327/**
328 * `r` with its stdout compressed, or `r` itself. `r` is what `next(e)`
329 * resolved to for a Bash call; every key but `result.stdout` is kept.
330 */
331export function filterResult(line: string, r: AnyResult): AnyResult {
332  if (!r || typeof r !== "object") return r;
333  if (r.deny !== undefined || r.isError) return r;
334  const res = r.result;
335  if (!res || typeof res !== "object" || typeof res.stdout !== "string")
336    return r;
337  if (res.isImage || res.interrupted) return r;
338  for (const k of ["persistedOutputPath", "backgroundTaskId", "structuredContent"])
339    if (res[k] !== undefined && res[k] !== null) return r;
340  if (readsBytes(line)) return r;
341  const stdout = compress(line, res.stdout);
342  if (stdout === undefined) return r;
343  return { ...r, result: { ...res, stdout } };
344}
345
hooks/mod/veil.ts 274 lines
1// veil.ts — secrets masked in what a tool returns, before the model reads it.
2// Pure: register.ts hands in the environment's values and the clock.
3//
4// After the tool ran (`next`), never on its input: the call runs as written,
5// only its result is read through this. Three kinds of secret go:
6//   - the value of a known credential variable of the session's environment;
7//   - a credential by its shape (provider prefixes, Bearer, private key
8//     blocks, user:password@ in a URL, key=value assignments);
9//   - a token of 20 characters or more, letters and digits mixed, whose
10//     entropy passes 4.3 bits per character, unless it is a hash (hex), a
11//     UUID, a path, an integrity digest, or base64 of plain text.
12// An image block ({type:"image"}) is left whole: its data is base64 pixels.
13// A masked value cannot be revealed: nothing keeps it. Past the size or the
14// time budget the result is returned as it came (fail open).
15
16export const VEIL_MAX_CHARS = 2_000_000;
17export const VEIL_MAX_MS = 1_500;
18export const ENTROPY_MIN = 4.3;
19export const TOKEN_MIN = 20;
20
21/** Environment variables whose value is a credential. */
22export const SECRET_VARS = [
23  "ANTHROPIC_API_KEY",
24  "ANTHROPIC_AUTH_TOKEN",
25  "CLAUDE_CODE_OAUTH_TOKEN",
26  "OPENAI_API_KEY",
27  "GITHUB_TOKEN",
28  "GH_TOKEN",
29  "GH_ENTERPRISE_TOKEN",
30  "GITLAB_TOKEN",
31  "GL_TOKEN",
32  "CI_JOB_TOKEN",
33  "NPM_TOKEN",
34  "NODE_AUTH_TOKEN",
35  "AWS_SECRET_ACCESS_KEY",
36  "AWS_SESSION_TOKEN",
37  "OP_SERVICE_ACCOUNT_TOKEN",
38  "OP_CONNECT_TOKEN",
39  "VAULT_TOKEN",
40  "NOMAD_TOKEN",
41  "CONSUL_HTTP_TOKEN",
42  "CLOUDFLARE_API_TOKEN",
43  "CF_API_TOKEN",
44  "SLACK_TOKEN",
45  "SLACK_BOT_TOKEN",
46  "DOCKER_PASSWORD",
47  "HF_TOKEN",
48  "GOOGLE_API_KEY",
49  "SENTRY_AUTH_TOKEN",
50  "DATABASE_URL",
51] as const;
52
53type Shape = { kind: string; re: RegExp; group?: number };
54
55// Assembled so this file does not read as a credential to a line scanner.
56const PEM = `-----BEGIN [A-Z0-9 ]*PRIV${"ATE"} KEY-----[\\s\\S]*?-----END [A-Z0-9 ]*PRIV${"ATE"} KEY-----`;
57
58export const SHAPES: readonly Shape[] = [
59  { kind: "private-key", re: new RegExp(PEM, "g") },
60  {
61    kind: "github",
62    re: /\b(gh[pousr]_[A-Za-z0-9]{30,}|github_pat_[A-Za-z0-9_]{40,})\b/g,
63  },
64  { kind: "gitlab", re: /\bglpat-[A-Za-z0-9_-]{20,}/g },
65  { kind: "anthropic", re: /\bsk-ant-[A-Za-z0-9_-]{20,}/g },
66  { kind: "openai", re: /\bsk-(proj-)?[A-Za-z0-9_-]{32,}/g },
67  { kind: "aws", re: /\b(AK|AS)IA[0-9A-Z]{16}\b/g },
68  { kind: "google", re: /\bAIza[0-9A-Za-z_-]{35}\b/g },
69  { kind: "slack", re: /\bxox[abposr]-[A-Za-z0-9-]{10,}/g },
70  { kind: "1password", re: /\bops_[A-Za-z0-9_-]{40,}/g },
71  { kind: "vault", re: /\bhv[sbr]\.[A-Za-z0-9_-]{20,}/g },
72  { kind: "npm", re: /\bnpm_[A-Za-z0-9]{36}\b/g },
73  {
74    kind: "jwt",
75    re: /\beyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g,
76  },
77  {
78    kind: "bearer",
79    re: /\b(Bearer|Basic)\s+([A-Za-z0-9._~+/=-]{12,})/g,
80    group: 2,
81  },
82  { kind: "url-credentials", re: /:\/\/[^/\s:@]+:([^/\s:@]{3,})@/g, group: 1 },
83  {
84    kind: "assignment",
85    re: /\b(pass(?:word|wd)?|secret|token|api[_-]?key|access[_-]?key|private[_-]?key|client[_-]?secret)(["']?\s*[:=]\s*["']?)([^\s"'`,;]{8,})/gi,
86    group: 3,
87  },
88];
89
90/** Shannon entropy in bits per character. */
91export function entropy(s: string): number {
92  const counts = new Map<string, number>();
93  for (const c of s) counts.set(c, (counts.get(c) ?? 0) + 1);
94  let h = 0;
95  const n = [...s].length;
96  for (const k of counts.values()) {
97    const p = k / n;
98    h -= p * Math.log2(p);
99  }
100  return h;
101}
102
103const printable = (bytes: Uint8Array) => {
104  if (!bytes.length) return false;
105  let ok = 0;
106  for (const b of bytes)
107    if ((b >= 32 && b < 127) || b === 9 || b === 10 || b === 13) ok++;
108  return ok / bytes.length >= 0.9;
109};
110
111function decodeBase64(s: string): Uint8Array | undefined {
112  const t = s.replace(/-/g, "+").replace(/_/g, "/");
113  if (!/^[A-Za-z0-9+/]+=*$/.test(t)) return undefined;
114  try {
115    const bin = atob(t.padEnd(t.length + ((4 - (t.length % 4)) % 4), "="));
116    return Uint8Array.from(bin, (c) => c.charCodeAt(0));
117  } catch {
118    return undefined;
119  }
120}
121
122/** Why a high-entropy token is not a secret, or undefined when it may be one. */
123export function exempt(tok: string): string | undefined {
124  if (/^[0-9a-f]+$/i.test(tok)) return "hex";
125  if (
126    /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(tok)
127  )
128    return "uuid";
129  if (
130    tok.includes("/") &&
131    /^(\.{0,2}\/|~\/)?[\w.@+-]+(\/[\w.@+-]*)+$/.test(tok) &&
132    !/[+=]/.test(tok)
133  )
134    return "path";
135  if (/^sha(1|256|384|512)-/.test(tok)) return "integrity";
136  if (!/[A-Za-z]/.test(tok) || !/[0-9]/.test(tok)) return "not mixed";
137  const bytes = decodeBase64(tok.replace(/=+$/, ""));
138  if (bytes && printable(bytes)) return "base64 text";
139  return undefined;
140}
141
142const TOKEN = /[A-Za-z0-9+/=_.-]{20,}/g;
143
144export type Veiled = { text: string; masked: number; kinds: string[] };
145
146export type VeilCtx = {
147  /** Values of the known credential variables, empty ones left out. */
148  envValues: readonly string[];
149  /** Milliseconds; the time budget is measured with it. */
150  now(): number;
151};
152
153class Budget extends Error {}
154
155/** One text, masked. Throws Budget past the time limit. */
156function maskText(
157  text: string,
158  ctx: VeilCtx,
159  deadline: number,
160  kinds: Set<string>,
161): { text: string; masked: number } {
162  let masked = 0;
163  let out = text;
164  const tag = (kind: string) => {
165    masked++;
166    kinds.add(kind);
167    return `[masked:${kind}]`;
168  };
169  for (const v of ctx.envValues) {
170    if (v.length < 8 || !out.includes(v)) continue;
171    out = out.split(v).join(tag("env"));
172  }
173  for (const s of SHAPES) {
174    if (ctx.now() > deadline) throw new Budget();
175    s.re.lastIndex = 0;
176    out = out.replace(s.re, (...m: any[]) => {
177      if (s.group === undefined) return tag(s.kind);
178      const whole: string = m[0];
179      const part: string | undefined = m[s.group];
180      if (!part || part.startsWith("[masked:")) return whole;
181      return (
182        whole.slice(0, whole.lastIndexOf(part)) +
183        tag(s.kind) +
184        whole.slice(whole.lastIndexOf(part) + part.length)
185      );
186    });
187  }
188  if (ctx.now() > deadline) throw new Budget();
189  out = out.replace(TOKEN, (tok) => {
190    const core = tok.replace(/^[.=_-]+|[.=_-]+$/g, "");
191    if (core.length < TOKEN_MIN || core.startsWith("masked:")) return tok;
192    if (exempt(core) !== undefined) return tok;
193    if (entropy(core) <= ENTROPY_MIN) return tok;
194    return tok.replace(core, tag("entropy"));
195  });
196  return { text: out, masked };
197}
198
199/** Masks every string reached in `value` (depth-limited), in place of a copy. */
200export function veil(
201  value: unknown,
202  ctx: VeilCtx,
203): { value: unknown; masked: number; kinds: string[] } | undefined {
204  const start = ctx.now();
205  const deadline = start + VEIL_MAX_MS;
206  let size = 0;
207  const kinds = new Set<string>();
208  let masked = 0;
209  // Keys that name things rather than carry output
210  const SKIP = new Set([
211    "filePath",
212    "file_path",
213    "path",
214    "type",
215    "tool_use_id",
216    "persistedOutputPath",
217    "backgroundTaskId",
218  ]);
219  const walk = (v: unknown, depth: number): unknown => {
220    if (typeof v === "string") {
221      size += v.length;
222      if (size > VEIL_MAX_CHARS) throw new Budget();
223      const r = maskText(v, ctx, deadline, kinds);
224      masked += r.masked;
225      return r.text;
226    }
227    if (depth > 8 || v === null || typeof v !== "object") return v;
228    if (Array.isArray(v)) return v.map((x) => walk(x, depth + 1));
229    // An image block carries base64 pixels, not text: its data field passes
230    // the entropy test and would be replaced, breaking the picture. Every
231    // text block of the same result is still read.
232    if ((v as { type?: unknown }).type === "image") return v;
233    const o: Record<string, unknown> = {};
234    for (const [k, x] of Object.entries(v))
235      o[k] = SKIP.has(k) ? x : walk(x, depth + 1);
236    return o;
237  };
238  try {
239    const out = walk(value, 0);
240    return { value: out, masked, kinds: [...kinds] };
241  } catch (err) {
242    if (err instanceof Budget) return undefined;
243    throw err;
244  }
245}
246
247type AnyResult = Record<string, any>;
248
249/**
250 * What the model reads for `r`, secrets masked. `r` itself when nothing was
251 * found, or past the budget. An answered result keeps its shape; an errored
252 * one (whose text is the core's own) is withheld with the masked text, the
253 * only answer a hook can give after the tool ran without passing `result`.
254 */
255export function veilResult(r: AnyResult, ctx: VeilCtx): AnyResult {
256  if (!r || typeof r !== "object" || r.deny !== undefined) return r;
257  if (r.isError) {
258    const text =
259      typeof r.text === "string"
260        ? r.text
261        : typeof r.result === "string"
262          ? r.result
263          : undefined;
264    if (text === undefined) return r;
265    const v = veil(text, ctx);
266    if (!v || !v.masked) return r;
267    return { deny: String(v.value) };
268  }
269  if (!("result" in r)) return r;
270  const v = veil(r.result, ctx);
271  if (!v || !v.masked) return r;
272  return { ...r, result: v.value };
273}
274
hooks/mod/mcp-probe.ts 99 lines
1// mcp-probe.ts — the shape and the size of what MCP tools return, never the
2// content. Pure: register.ts hands in the result and the clock, and runs the
3// append.
4//
5// After an MCP tool ran (and its result was veiled), one JSON line goes to
6// <session dir>/mcp-shapes.jsonl: the tool's name, the form of the result,
7// its keys, the types of its content blocks, its length in characters, the
8// time. No value of the result is read into the line: key names and block
9// types are kept only when they look like identifiers, anything else is
10// written as "?". The file is 0600 and local to the session. It exists to
11// say, after a few weeks, how large and how repeated MCP results are before
12// anything is built on them. KODFLOW_MCP_PROBE=off turns it off.
13import { safe } from "./paths.ts";
14
15export const MCP_SHAPES = "mcp-shapes.jsonl";
16const NAME_MAX = 32;
17const LIST_MAX = 20;
18const NAME = /^[A-Za-z_][A-Za-z0-9_-]*$/;
19
20/** The probe's file in a session directory. */
21export const shapesFile = (dir: string): string => `${dir}/${MCP_SHAPES}`;
22
23/** One line of the journal: structure and sizes only. */
24export type Shape = {
25  at: number;
26  tool: string;
27  /** Keys of the answer (result, isError, deny, …). */
28  keys: string[];
29  /** What `result` is: string, array, object, null, number, … */
30  form: string;
31  /** Keys of `result` when it is an object. */
32  resultKeys: string[];
33  /** The `type` of each content block, in order. */
34  blocks: string[];
35  /** Length of the result serialised, in characters. */
36  chars: number;
37};
38
39// A key or a type is structure when it reads like an identifier; anything
40// else could be data and is not copied.
41const label = (v: unknown): string =>
42  typeof v === "string" && v.length <= NAME_MAX && NAME.test(v) ? v : "?";
43
44const keysOf = (v: unknown): string[] =>
45  v && typeof v === "object" && !Array.isArray(v)
46    ? Object.keys(v).slice(0, LIST_MAX).map(label)
47    : [];
48
49const formOf = (v: unknown): string =>
50  v === null ? "null" : Array.isArray(v) ? "array" : typeof v;
51
52// The content blocks of a result: the array itself, or its `content`
53function blocksOf(result: unknown): unknown[] {
54  if (Array.isArray(result)) return result;
55  const c = (result as { content?: unknown } | null | undefined)?.content;
56  return Array.isArray(c) ? c : [];
57}
58
59function sizeOf(v: unknown): number {
60  try {
61    if (typeof v === "string") return v.length;
62    return JSON.stringify(v)?.length ?? 0;
63  } catch {
64    return 0;
65  }
66}
67
68/** The shape of `answer`, what a tool.call over an MCP tool resolved to. */
69export function shapeOf(tool: string, answer: unknown, nowMs: number): Shape {
70  const a = answer && typeof answer === "object" ? (answer as Record<string, unknown>) : {};
71  const result = "result" in a ? a.result : answer;
72  return {
73    at: Math.floor(nowMs / 1000),
74    tool: safe(tool),
75    keys: keysOf(answer),
76    form: formOf(result),
77    resultKeys: keysOf(result),
78    blocks: blocksOf(result)
79      .slice(0, LIST_MAX)
80      .map((b) => label((b as { type?: unknown } | null)?.type)),
81    chars: sizeOf(result),
82  };
83}
84
85/** The line to append, newline included. */
86export const shapeLine = (s: Shape): string => `${JSON.stringify(s)}\n`;
87
88/**
89 * The command that appends a line read on stdin to `file`, 0600 whether or
90 * not the file existed. argv, never a shell string built from data.
91 */
92export const appendArgv = (file: string): string[] => [
93  "sh",
94  "-c",
95  'umask 077; cat >> "$1" && chmod 600 "$1"',
96  "mcp-probe",
97  file,
98];
99