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, tier.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.
| Event | What the mod does |
|---|---|
session.start | registers 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: compact | adds 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-setup | checks ktn-linter for a Go module (below) |
classic.SessionStart, prompt.submit, every tool.call | writes 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 tool | answers it (below); a refusal is { deny } with the text the model reads, an internal failure a text error, never a crash |
tool.call on Bash | one pipeline of ordered policies (pipeline.ts), below |
every tool.call, after the tool ran | secrets masked in the result (veil.ts), below |
tool.call on an mcp__* tool, after the veil | one line of shape and size in mcp-shapes.jsonl (mcp-probe.ts), below |
prompt.submit | remembers 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.register | modwall: refuses every user-tier hooks module whose provenance is not *@kodflow, *@claude-plugins-official or *@gitkraken (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-mods | the modules judged at this load, and the refusals on record |
session.start | zsh-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, NotebookEdit | collision-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.end | empties this session's edits.tsv |
tool.call on Workflow | tier: every agent() of the script (scriptPath read from its real path inside the session's <config>/projects/<slug>/<session>/, the project or the scratchpad, at most 256 kB; else the inline script) must pass the model and the effort its agentType definition or the environment (CLAUDE_CODE_SUBAGENT_MODEL, CLAUDE_CODE_EFFORT_LEVEL other than auto) does not pin. Only the top-level keys of an object literal given as the 2nd argument are read; a spread, a computed key, a non-literal argument (tier-nonliteral) or a text the lexer and an independent count disagree on (tier-unparsed) passes. name alone (tier-unjudged) and resumeFromRunId (tier-resume) are not judged. Mode as the shell's: off anywhere wins, else KODFLOW_TIER, <config>/kodflow/sessions/<session>/tier-mode, <config>/kodflow/tier-mode, warn; tier-skew turns enforce into warn. Warn appends the advice to the result's context; enforce refuses before the run, and the same script refused once passes the second time (tier-breaker, in $.store). One line per agent() appended to the session's tier.jsonl |
agent.spawn | tier first, logged only: a Workflow agent (tier-workflow), a resume (tier-resume), a named agent (tier-teammate) — never refused, since a spawn carries no effort |
agent.spawn | gated models: passes or refuses a spawn on the model it would run on, never writes one (below) |
tool.call on Skill | gated models: a skill whose frontmatter names one passes only with the session's grant, asked once like a spawn |
classic.PreModelSwitch | a /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 subagent | cleanup 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 task | cleanup 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 composer | writes <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).
| # | Policy | What it does | A failure |
|---|---|---|---|
| 1 | guards (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 it | is logged, the call goes on |
| 2 | the call | the shell's PreToolUse runs beneath, as ever | — |
| 3 | output 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 kept | returns 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 CodeRabbit capacity hint
Before gh pr create, and before a git push (hint kept for a branch that has
a ready PR), on-tool.sh tells Claude whether CodeRabbit is rate limited on
the repository, in how many minutes a review frees up, and the way out: add the
commits to an open PR, open a draft (CodeRabbit skips drafts unless the
repository's .coderabbit.yaml says otherwise), or wait when the delay is
short. It rides in the hook's one JSON document as additionalContext
(PreToolUse), never as a decision: nothing is held, refused or rewritten, and
a repository where CodeRabbit is not limited, or where anything fails
(no python3, no token, no github.com remote, API down, 4 s deadline), gets
no output at all and exit 0.
The reader of CodeRabbit's messages is hooks/coderabbit/probe.py
(capacity, standard library only), called by hooks/scripts/lib/coderabbit.sh.
It is the one reader: kodflow/labs' scheduled relaunch workflow checks the same
file out at a pinned commit and runs its probe and relaunch. It samples the
repository's recent open PRs (the quota is per developer, so the repository is
a proxy for the owner) and reads the token as GH_TOKEN_<OWNER>, GH_TOKEN,
GITHUB_TOKEN, else gh auth token.
Cost. A cached answer (5 minutes per repository, under
<config>/kodflow/coderabbit/, mode 0600) makes no API request. A refresh
makes 1 call for the open PRs, 1 per recent non-draft PR updated in the last 3
hours (at most 5) for its comments, and 1 per PR holding a refusal for its
reviews: 1 call on a quiet repository, at most 11, the case measured on
kitsunium/sdk being below that. KODFLOW_CODERABBIT=off turns the hint off.
The merge gate. Before gh pr merge (every -R form, a number, a URL,
a branch or none) and mcp__github__merge_pull_request, main thread only (a
subagent's merge stays refused), probe.py merge-gate decides, 4 s deadline,
cached covered, the policy directory of KODFLOW_CODERABBIT_POLICY_DIR (else
~/Projects/kodflow/making.codes/coderabbit when it exists):
| CodeRabbit on the head | the hook |
|---|---|
| covered, not eligible, unknown, an error, the deadline | allow, one context line CodeRabbit on PR #N: head <sha> covered=<x> eligible=<y> |
| eligible, positively not covered, no marked request for this head | posts @coderabbitai review then <!-- kodflow-relaunch:hook head=<sha> -->, and denies: "CodeRabbit relancé sur à HH:MM ; réessaie la fusion dès qu'il a relu ou après HH:MM (30 min)" |
| a marked request younger than the wait | denies with the same text, posts nothing |
the wait is over, CodeRabbit answered the request with a refusal, or the quota is out (capacity limited) | allows, after one audit comment per head: merged without CodeRabbit review of <sha>: <reason> |
A merge that does not pin the head (--match-head-commit, MCP
expectedHeadSha) is told to, never held for it. KODFLOW_CR_MERGE_WAIT_MINUTES
sets the wait (default 30), KODFLOW_CODERABBIT=off turns every CodeRabbit
behaviour off. merge-gate --dry-run decides without posting.
Coverage. probe.py covered --repo OWNER/NAME --pr N [--policy-dir DIR]
prints {head, last_reviewed, eligible, reason, covered} for one pull request.
last_reviewed comes from CodeRabbit's summary comment (the
final_review_risk_coverage marker, else Last reviewed commit:, else the
recent-review range; both comment layouts), never from a review's commit_id.
eligible resolves the configuration as CodeRabbit does: the repository's
.coderabbit.yaml at the head if it has one (merged over DIR/settings.yaml
when it says inheritance: true), else DIR/settings.yaml, then
the lists of DIR/override-<owner>.yaml on top (authors exact, title keywords
case-insensitive substrings), drafts, base branches, path filters. Without a
readable DIR, or on any doubt, a field is "unknown", and unknown never
leads to a command. Cached 5 minutes per (repository, PR, head). The YAML
reader is a stdlib subset in the same file: refused constructs (anchors, tags)
make eligible unknown rather than guessed. The scheduled relaunch marks its
comments <!-- kodflow-relaunch:cron head=<sha> --> after the command and,
given --policy-dir, also relaunches a review-eligible head that is
positively not covered, quiet for 20 minutes and not under review; a read
of the head's status or check runs that fails (a token without Checks: 403)
makes that PR no candidate, never a stop of the scan.
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.
| Field | Content |
|---|---|
at | time, whole seconds |
tool | the tool's name |
keys | the keys of the answer (result, isError, deny, …) |
form | what result is: string, array, object, null, … |
resultKeys | the keys of result when it is an object |
blocks | the type of each content block (result or result.content), in order |
chars | the 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 tools | absent: tasks are not tracked |
| triage gate, triage directive, epic state in the prompt, session-start review | off: nothing could lift a gate the tools cannot answer |
built-in TaskCreate/TodoWrite | allowed again: they are the only list left |
| attribution text | Claude Code's own (the shell guard still refuses AI attribution in a commit) |
| what the user is told | once 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:
| Stage | Meaning | Exit |
|---|---|---|
| 1 · gate | the cheapest test that lets most calls leave at once | 0 |
| 2 · block | what must stop the call | 2, reason on stderr |
| 3 · transform | what Claude reads (context, the task identity of a task_* call), emitted as one JSON document; a Bash command is never rewritten | 0 |
| 4 · observe | logging and advice, off the critical path | 0 |
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
| Event | Script | Gate | Block | Transform | Observe |
|---|---|---|---|---|---|
PreToolUse · Bash | on-tool.sh | no 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 branch | none: the input is never rewritten; a kodflow-specialists agent's command outside its Command scope gets one advice line (read before the gate, never a refusal) | log; a main-thread merge is tagged root_guard: merge; scope.jsonl |
PreToolUse · task tools | on-tool.sh | the mod's task tools never reach it (a call a function hook answers fires no PreToolUse); the old MCP names are logged and passed | built-in TaskCreate/TodoWrite while the mod beats: their chat panel duplicates the kodflow list, the refusal points at the kodflow task tools | — | log |
PreToolUse · Write/Edit | on-tool.sh | main thread writing inside a git work tree (memory and Claude configuration excepted, and a plugin's root-write-allow where the repository enables that plugin) · no file path | the 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.sh | no 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/Edit | on-tool.sh | file 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/Task | on-tool.sh | gated-model fallback first, every caller, no jq; then the main thread only | a 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 · Claude in Chrome (mcp__claude-in-chrome__navigate, mcp__claude-in-chrome__javascript_tool) | on-tool.sh | every other browser tool (decided without jq) · KODFLOW_FORGE_BROWSER=off | every caller, subagents included: a navigation to a forge — github.com, gitlab.com and their subdomains, the host of every git remote of the project, KODFLOW_FORGE_HOSTS — or a script naming one, or a GitLab API path (/api/v4/projects, /jobs, /pipelines…); the refusal ([motif:forge-browser]) gives the MCP path, then the CLI path. With KODFLOW_FORGE_BROWSER=ask the user is asked instead, call by call | — | log |
PreToolUse · Skill | on-tool.sh | the mod does not beat | a skill whose frontmatter names a gated model | — | — |
PostToolUse · Task/Agent | on-tool.sh | — | — | — | agent-models.tsv (agent id, resolved model, per-call effort) · log tagged root_guard: dispatch |
PostToolUse · SubagentHandback | on-tool.sh | — | — | — | the report's agent feedback, as at SubagentStop |
PostToolUse · Read | on-tool.sh | — | — | docs.json at most every 30 s · document concerné for each document the file concerns, once per session | log |
PostToolUse · Bash | on-tool.sh | — | — | docs.json at most every 30 s | log |
PostToolUse · other | on-tool.sh | — | — | — | log |
PostToolUseFailure | on-tool.sh | — | — | — | remediation hint (a forge MCP answering 401: the token and instance URL to configure, /mcp to reconnect, gh or glab meanwhile) · log (error redacted) |
PermissionDenied | on-tool.sh | — | — | — | log |
SessionStart | on-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 (including which rtk prefixes are safe and which, such as rtk read, are forbidden), otherwise the forge rule alone (MCP first, CLI last, never Claude in Chrome) · 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/host.sh, scripts/lib/agents.sh, scripts/lib/tier.sh, scripts/lib/identity.sh, scripts/lib/beat.sh, scripts/lib/readlist.sh, scripts/lib/read-tools.txt, 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 |
SessionEnd | on-session.sh | — | — | — | one log line, appended in the background (1.5 s budget) |
PreCompact | on-session.sh | — | — | — | log |
ConfigChange | on-session.sh | — | — | — | log · bypassPermissions flagged in security-events.jsonl |
UserPromptSubmit | on-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 gone | raise the triage gate (mod beating) and reset the Stop loop counter, except on a turn the user did not type · log |
Notification | on-user.sh | — | — | bell (terminalSequence) on idle, permission and elicitation prompts | log |
SubagentStart | on-agent.sh | — | — | the standing rules, injected into the subagent (forge and CI-watch rules from lib/rules.sh, --force-with-lease only, own worktree and never one it did not create, deliver through a PR, and rule 6: end with ## Agent feedback) | running-agents registry, with the main agent's active epic at start · log |
SubagentStop | on-agent.sh | stop_hook_active | — | — | running-agents registry · its whole last message in <session>/agents/<agent id>.md · its agent feedback in agent-feedback.jsonl · log |
TaskCreated · TaskCompleted · TeammateIdle | on-agent.sh | — | — | — | log |
Stop | on-stop.sh | stop_hook_active · 3 feedbacks without a new prompt (the open-tasks relaunch is bounded by its own per-task counter instead) | decision: block while the main agent has tasks to do in an epic, twice per task at most (below, « Relaunch on open tasks ») | 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 file | bell · 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:
| Tool | Refused | Still allowed |
|---|---|---|
Write/Edit/MultiEdit/NotebookEdit | a 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 lexically | everything outside a repository; <config>/projects/*/memory/*, <config>/settings.json, settings.local.json, <config>/CLAUDE.md and ~/CLAUDE.md even inside one |
Bash | git 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 classified | reads, 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
originasgit remote get-urlgives it (insteadOf applied): https,ssh://user@host:port/…,git@host:path, CodeCommit with a key id andcodecommit::<region>://. Noorigin, 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_IDENTandGIT_COMMITTER_IDENTrun in the commit's directory (-C,cd … &&), with the line's-c,--config-env,--git-dir, and theGIT_*,EMAIL,HOMEit sets (X=v git,env [-i] [-u X] X=v git,export X=v; …), so local, global andincludeIfconfiguration all count; then--author, or the reused commit's author for--amend,-C,-cunless--reset-author. The address is compared without case, the name exactly. - An empty address (
<>in a rule) is what git writes foruser.email="", with or withoutuser.useConfigOnly(tests/test_identity.shasks 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 twogit -C <dir> configcommands 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=offturns it off. - Not covered: a commit made by
merge,rebase,cherry-pick,revert,amorpull(their committer), a commit through a forge MCP tool,nohup env X=v git …and other wrappers beforeenv, a variable set withoutexportand not exported already, and the gaps of the shell reader itself (an alias,$c commit). The mod does not double this check, like the staged-secret scan: it needs git.
The shell reader
A regex over the raw line cannot tell git "commit", \git commit or
=git commit from a commit, and it reads a heredoc that merely quotes a
commit as one. on-tool.sh does the shell's first pass instead: it cuts the
line into simple commands on ; && || | & and newlines, removes
quotes and backslashes, decodes $'…', joins \+newline, sets heredoc and
here-string bodies aside as the command's stdin, walks past VAR=value,
reserved words and wrappers (env, command, exec, sudo, doas,
nohup, nice, timeout, xargs, rtk, rtk proxy…), and queues for
another pass every text the shell would itself run: $( ), backticks,
<( ), bash -c/sh -c/zsh -c, eval, su -c/sg -c, a heredoc or a
here-string fed to a shell, and echo …/cat <<EOF piped into one. A
heredoc fed to anything else is data: cat > notes.md <<EOF quoting a commit
and a .claude/ path passes.
It never expands a variable or an alias. Those, and an interpreter other than
a shell (python -c "os.system(…)"), find -exec and a git alias defined on
the line, are the known gaps; each has a known_gap case in the corpus.
The attribution guard reads its rules from kodflow/post-commit, the gate
every repository runs on GitHub: scripts/patterns.txt and
scripts/patterns-strict.txt, vendored byte for byte in hooks/patterns/
at the commit hooks/patterns/SOURCE pins. An installed plugin reads that
copy and never the network. on-tool.sh (builtins only, once per call,
bash 3.2) and the mod (patterns.ts, translating each POSIX ERE to the same
line-by-line match) read the same files with the same format: one ERE a
line, # and blank lines skipped, # @scope: <list> for what follows.
A commit message meets every pattern, the strict file included (vendor
keywords such as \bclaude\b, .claude/ paths). The keywords aim at a
mention of the assistant, not at a technical name: the word glued to an
alphanumeric by -, _, . or / (super-claude, claude-code.d.ts,
CLAUDE.md, @anthropic-ai/sdk) or inside backticks is set aside before
the keyword pass, which is the only pass that reads that text; attribution
trailers and .claude/ leaks see the message as written. A pull or merge request
title or body meets the commit,pr scope only (AI trailers, AI noreply
addresses, "Generated with/by", the robot emoji, "AI-assisted"): a PR may
well be about the tooling, so naming Claude Code or a .claude/ path, or a
Plan: line, passes there. Each hit carries a motif: leak for a
commit-only pattern naming a workflow artefact (a .claude path, the
Plan: footer), tried before the keywords, attribution for the rest. A
copy without both files, or with a scope it does not know, refuses every
commit message and PR text instead of reading it as clean.
Moving the pin is a reviewed change:
bash scripts/sync-post-commit-patterns.sh <40-hex commit of kodflow/post-commit>
bash scripts/tests/test_hooks.sh && bash plugins/kodflow-hooks/tests/run-tests.sh
The script copies both files at that commit, rewrites SOURCE and
regenerates hooks/fingerprints.sha256 (the pattern files are guards too).
CI runs --check, which fetches the files at SOURCE's commit and fails on
any difference with the copy.
Plugin machinery stays in marketplaces (L0.6). For every caller, Edit and
Write, and a shell redirection, are refused when they write a
.claude-plugin/ or a hooks/hooks.json under a skills directory
(~/.claude/skills/**, <config>/skills/**, **/.claude/skills/**), and
claude plugin install|i or claude plugin marketplace add are refused
unless the plugin is name@kodflow or the marketplace is
kodflow/claude-marketplace. cp, tee, sed -i and git clone into a
skills directory are not read (known gaps).
No file named mcp.json or .mcp.json (any case, at any path) is ever
committed: such a file may carry tokens, and a GitHub token once lived in
clear in the user's global mcp.json. For every caller, subagents
included, the shell refuses git add or git stage naming one (-f or
not) or whose pathspecs would take one in (., a directory, a glob, -A,
--pathspec-from-file, ignored files under -f: git status resolves
them), a git commit whose pathspecs name or take in one, a git commit
whose index adds or changes one (git diff --cached --name-status, the
read the secret scan already makes, in the repository the commit runs in,
git -C joined onto a preceding cd), and a git commit -a when a
tracked one is modified in the working tree. A file the same line creates
before adding it is not there yet when the hook runs (a known_gap row);
the commit that follows a separate add is refused. The forge write tools
are held to the same rule: a path that push_files,
create_or_update_file, a GitLab commit action or GitKraken's
git_add/git_commit names, and, for GitKraken naming no file, what the
repository would take in. Reading one on the forge passes. A deletion stays allowed, so a repository that
still tracks one can be cleaned: git rm --cached <path>, then commit, or
the forge's delete_file. Names that merely contain it (mymcp.json,
mcp.json.tmpl) pass. The mod doubles the refusal, refusal only and
failing open. A plugin that needs an MCP server declares it in the
mcpServers field of its plugin.json, never in a .mcp.json; no plugin
of this marketplace tracks one today.
Every refusal ends with a [motif:<id>] line (root, no-verify,
attribution, leak, mcp-json, secrets, force, merge,
push-default, mod-write, plugin-source): tests
compare it, never the wording. The corpus is
tests/fixtures/bash-guard.jsonl, one case per line (cmd or tool and
input, rc, motif, agent, root, known_gap), played by
scripts/tests/test_hooks.sh (HOOK_SHELL=/bin/bash plays it under macOS's
bash 3.2). Its attribution shapes are written with \u escapes so the file
does not carry them in clear.
The denial is short: it is code production in a repository, so dispatch the
epic's subagent (focus the epic first, so the subagent is attributed to it)
or SendMessage it if it is running; ROOT_OK=1 for a genuine exception.
One exception a plugin can ask for, by data rather than by name: a plugin of
this marketplace may ship root-write-allow, globs relative to a
repository's root (** crosses directories). A Write or Edit of the main
thread on a matching path is let through only in a repository whose own
.claude/settings.local.json (else .claude/settings.json) sets
enabledPlugins["<plugin>@kodflow"] to true: installed but not enabled
there, enabled in another repository, a match deeper than the root
(node_modules/…/docs/anim), a path into .git, or a settings file jq
cannot read are all refused. The path is judged after lexical normalisation,
like every other. The list is the plugin's data: these hooks name no
plugin.
The Stop rule closes the other side: a main-agent task in_progress on an
epic with no running subagent attributed to it (agents.json epic, not
stopped, started less than 12 h ago) means the main thread is doing the
epic's work itself, or work that is no code in a repository; it is flagged
once per state (the unattended cause of « The Stop feedback ») — dispatch
a subagent for the epic, carry on when the work is not code in a
repository, or set the task back to pending/waiting. A task tied to a
subagent that stopped is the stopped cause instead, never both.
Ways out: ROOT_OK=1 leading a Bash line, KODFLOW_ROOT=off in the
environment for the session (gate, Stop rule and prompt line all off), and
plan mode, where the gate never fires. Every anomaly — no jq, a malformed
payload, an empty command or path — fails open. Each denial is logged with
root_guard: deny and each dispatch with root_guard: dispatch:
L=.claude/logs/$(git branch --show-current | tr / _)/session.jsonl
grep -c '"root_guard":"deny"' "$L"; grep -c '"root_guard":"dispatch"' "$L"
lib/format.sh is the formatter table (sourced lazily, never registered) and
lib/event.jq is the one sanitization policy behind every log line.
lib/epics.jq is the hooks' read side of tasks.json (v1 or v2, malformed
read as empty), shared by on-user.sh, on-agent.sh and on-stop.sh.
Dispatches: specialists, gated models, agent feedback
Three behaviours around every subagent dispatch, each with its own kill
switch. They are wired on the payloads the CLI actually sends, recorded once
with a throwaway recorder plugin (command hooks on every agent event, a mod on
agent.spawn, classic.PreModelSwitch, prompt.submit and tool.call) and
committed as tests/fixtures/agent-hooks.jsonl, agent-spawn.jsonl and
agent-mod-events.jsonl (CLI 2.1.300, headless, default and auto permission
modes, paths rewritten).
The routing gate (KODFLOW_ROUTE=off)
A main-thread Agent call that leaves subagent_type out or names
general-purpose, and whose description names the technology of an
installed specialist, is refused with the subagent_type to use instead
([motif:route]): general-purpose would run it without that agent's pinned
model, effort and checks. The match is on the description alone — whole
lower-case words of three letters or more, and file extensions at the end of
a word — against <config>/kodflow/sessions/<session>/routing-installed.tsv.
That file is hooks/routing-index.tsv filtered to the plugins
installed_plugins.json lists, written at SessionStart and rebuilt at the
first dispatch when it is missing or older than the shipped index; with no
index at all the call passes (route-noindex). hooks/routing-index.tsv is
generated from the Keywords column of skills/_shared/specialists.md by
scripts/build-routing-index.py, and CI fails when the two disagree. Its fourth
column says whether each agent delivers a change (commit, push, PR) or
reviews only, computed from the agent's tools and Command scope; the refusal
prints it with the rule ("Who delivers a change" in specialists.md).
[general-purpose-ok] in the description or the prompt is the deliberate
exception, written by every skill that means a general-purpose dispatch (the
/challenge lenses, /debug, /search, /plan's explorers, /refine's and
route-agent.sh's fallback, /review, /infra, /ktn). The model writes
that marker too: the gate steers, it does not enforce. Subagents are not
gated.
The isolation gate (KODFLOW_ISOLATION=off)
isolation: "worktree" is Claude Code's: it puts the subagent in a fresh
worktree of the session's repository (<project>/.claude/worktrees/agent-…)
and then refuses every shell command it cannot prove keeps git inside that
worktree (an interpreter fed a heredoc, a variable where a command or an
option stands, screen). That guard is in the CLI and no hook lifts it, so a
subagent sent that way to work in another repository fails on its first
non-trivial command. A main-thread Agent call with isolation: "worktree"
whose description or prompt names an absolute path (or ~/…) inside a git
repository other than the session's is refused before it starts
([motif:isolation], root_guard: isolation-deny), naming that repository:
dispatched without isolation, the subagent makes its own worktree beside it
and delivers through a PR (start-up rule 5). Paths in the session's own
repository, worktrees of it included, and paths in no repository pass.
[isolation-ok] in the description or the prompt is the exception for a path
only quoted for reading (isolation-override). Subagents are not gated.
Gated models (KODFLOW_FABLE=allow|off)
hooks/gated-models.txt (one token a line, a substring of the lower-cased
model id; CI holds it byte-identical to skills/_shared/gated-models.txt)
lists the models no dispatch reaches without the user's yes, once per
session — Fable today (model-policy §6).
- The mod judges every
agent.spawnon the model it would run on: the call'smodel, else the definition's frontmatter (plugin:namein that plugin's installed copy, asinstalled_plugins.jsonnames it; a bare name in the project, the user's agents, then any installed plugin;inheritmeaningparentModel), elseCLAUDE_CODE_SUBAGENT_MODEL, elseparentModel— andCLAUDE_CODE_SUBAGENT_MODELbefore all of them whenCLAUDE_CODE_SUBAGENT_MODEL_FORCEis set. One spawn is judged at a time, so parallel dispatches put one question. A built-in with no file (Explore, a workflow's agents) is judged on the last two. It passes or refuses, and never writesmodel. A gated one passes with the session's grant ($.storefable:<session>, never a file: whatever runs a tool could write one); else, to a user who typed in the last 10 minutes,$.ui.askonce, a yes granting the session; nobody there, a refusal with the reason ([motif:fable]). A throw refuses only when a raw input names a gated model; otherwise the spawn goes on, with a toast and a log line. - A
/modelthe user types (recorded:source: command), or picks, is the consent:classic.PreModelSwitchgrants the session. From the SDK it asks like a spawn. - A skill whose frontmatter names a gated model would switch the main
conversation to it (no switch event was recorded for that): the mod judges
the
Skillcall on itsSKILL.mdthe same way (tool.call). - The shell, while the mod does not beat, refuses any Agent call whose
per-call
modelor definition frontmatter names a gated model, and anySkillwhose frontmatter does, from every caller, without jq (bash regexes, a bounded awk read of the frontmatter, quote- and CRLF-safe). It trusts no grant: without the mod, onlyKODFLOW_FABLE=allowlets one through. With jq the fields are decoded from the JSON, whatever its layout; without jq they are read by regexes tolerant of any whitespace around the colon, so a value holding an escaped quote or a\uescape is read only up to it. SessionStartsays once, to the user and to Claude, when the session itself starts on a gated model (the payload'smodel, absent in a headless run, else the settings', elseANTHROPIC_MODEL).
The tier judge for Agent calls (KODFLOW_TIER=off|warn|enforce)
lib/tier.sh, called at the head of the Agent/Task handling of on-tool.sh
(before every early exit, the agent_id one included, mod beating or not),
checks that a delegation does not leave its model or its effort to
inheritance. It needs jq (absent: the call passes, tier-nojq in the
journal) and reads only .tool_input.*: the payload's top-level effort is
the session's. A field is pinned by the call, by the agent definition's
frontmatter (kf_fm_field; null, ~ and, for a model, inherit pin
nothing), or by the environment (CLAUDE_CODE_SUBAGENT_MODEL;
CLAUDE_CODE_EFFORT_LEVEL other than auto/unset). With
CLAUDE_CODE_SUBAGENT_MODEL_FORCE the call's model is ignored by the engine:
the environment's model, else the parent's (Explore: its own), so the model is
not missing. Exempt: the rows of tier-table.tsv (exempt agents, fork,
mode plan) and [tier-exempt: …] in the description or the prompt. A type
with no readable definition (not a built-in) passes with tier-nodef.
Mode: off in any source wins; else KODFLOW_TIER, then
<session>/tier-mode, then <config>/kodflow/tier-mode, then warn;
<session>/tier-skew (written by on-tier.sh) forces warn. In warn nothing is
refused: the advice comes back as additionalContext (one message naming every
missing field, the rows of the table for the role, the mode and its source,
and printf off > <config>/kodflow/sessions/<sid>/tier-mode). In enforce the
call is refused (exit 2) only when the caller's marker exists
(tier-seen/main or tier-seen/<agent_id>, written when the table was
injected), else it passes as tier-inert. The breaker lets the 4th distinct
refusal of one (subagent_type, caller) through (tier-breaker; counted by
tool_use_id in the append-only <session>/tier-count).
Every verdict is one line of <session>/tier.jsonl: ts, mode, mode_source, would_refuse, action, reason, subagent_type, caller, has_model, has_effort, pinned_model, pinned_effort, tool_use_id. Reasons: tier, tier-sub,
tier-fork, tier-skew, tier-inert, tier-breaker, tier-nodef,
tier-nojq, tier-unparsed. Tests: tests/test_tier_judge.sh.
Tier knobs and motifs
| Knob | Effect |
|---|---|
KODFLOW_TIER=off|warn|enforce | the environment's mode; wins over both files unless one of the three says off |
<config>/kodflow/sessions/<sid>/tier-mode | the session's mode (one word) |
<config>/kodflow/tier-mode | the global mode (one word) |
<config> is ${CLAUDE_CONFIG_DIR:-$HOME/.claude}. Precedence: off in any of
the three wins; else KODFLOW_TIER > session file > global file > warn;
tier-skew turns enforce into warn. An unknown word is ignored. To turn the
check off for the session, the command the advice prints:
printf off > '<config>/kodflow/sessions/<sid>/tier-mode' (the path is
single-quoted, an embedded ' written '\'', the same in the shell judge and
in tier.ts).
Warn is the default and it is what ships. Enforce is a later decision,
taken on the measured week of warn (usage_report.py joins tier.jsonl to the
Agent dispatches by tool_use_id and counts would_refuse, action and reason
per week): false positives under 2 % and non-conformity under 10 %.
Motifs (the reason of a journal line, the [motif:…] of a message):
| Motif | Meaning |
|---|---|
tier | a main-thread dispatch names no model or no effort |
tier-sub | the same, from a subagent |
tier-workflow | an agent() of a Workflow, seen at spawn (logged, never refused) |
tier-fork | a fork: continues the orchestrator, exempt, counted apart |
tier-skew | the hooks' table and the skills' table differ: warn only |
tier-inert | enforce, but the caller never received the table: passes |
tier-breaker | the breaker let a repeated refusal through |
tier-nodef | no readable definition for the type: passes |
tier-nojq | jq is absent: passes |
tier-unparsed | the payload or the script could not be read reliably: passes |
tier-nonliteral | an agent() option that is not a literal (spread, computed key): passes |
tier-unjudged | a Workflow given by name alone: not judged |
tier-resume | a Workflow resume (resumeFromRunId): not judged |
tier-teammate | a named teammate agent at spawn: logged |
tier-nomod | reserved, not emitted yet: with the mod absent no hook sees a Workflow, so it passes without a journal line |
Shared vectors: tests/fixtures/tier-vectors.jsonl is read by
tests/test_tier_vectors.sh (shell) and, through the generated
tests/mod/tier-vectors.ts (scripts/check-tier-vectors.sh --write), by
tests/mod/tier.test.ts.
Agent feedback (KODFLOW_FEEDBACK=off)
SubagentStart adds rule 6: end the answer with ## Agent feedback (an
agent_feedback key in JSON) naming what in the agent's own instructions was
wrong, missing or ambiguous, or nothing. SubagentStop (last_assistant_message)
and PostToolUse SubagentHandback (tool_input.message, auto mode) both
carry the report; its feedback is kept once per agent and text as one line of
<session>/agent-feedback.jsonl (lib/feedback.jq): time, session, agent
type and id, model, effort, source and the feedback, redacted with the log's
rules, under 1 KB, written under kf_lock. The model is the one the parent's
PostToolUse Agent recorded for that agent id (agent-models.tsv, source: tool_result), else the definition's frontmatter (source: frontmatter); the
effort is the payload's own, which is the subagent's effective level. At
Stop, a new set of entries is proposed once, to a user present in the last
10 minutes (composer-at): show the diff to each agent's definition, and ask
before opening anything on kodflow/claude-marketplace; for a kodflow agent the
proposal offers kodflow-review:improve, the deliberate pass over every
session's entries that turns the open needs into one pull request. An entry whose agent
has no definition file (a built-in, an agent defined in the session) is kept
but never proposed: there is no definition to show a diff of.
Command scope advice (KODFLOW_SCOPE=off)
A kodflow-specialists agent's ## Command scope is an instruction, not a
permission: its tools grant Bash whole (#155). on-tool.sh compares
every shell call of a subagent whose agent_type is
kodflow-specialists:<name> (and that carries an agent_id) with the
families the installed definition declares (lib/scope.sh): each
Bash(...) entry of the section, up to its first placeholder, glob, path or
quote, the leading command list of a prose bullet (grep -n, grep -c and
sed -n …, nothing after it, which may name forms the bullet forbids), and,
for an agent that carries Plan review mode, the commands of its inspection
line, since the mode is not visible in the payload. The line is read by the
shell reader (nested bash -c, pipes, wrappers, rtk, env, VAR=), git's
global options are walked past, shell plumbing (cd, echo, test…) and a
command word it cannot see ($c) are not reported.
It never refuses, never rewrites and never causes a permission prompt, and
stays advisory by the owner's decision (10/11/2026): a command the brief
allowed is fine, it is only reported. A call outside goes on and carries one
terse additionalContext line naming the commands outside (the name, and its verb
when the verb is a plain word, never an argument), once per agent and
command; every such call is a line of <session>/scope.jsonl (agent type and
id, tool_use_id, the commands outside, never the line). No definition, no
section, no Bash(...) entry, a bare agent name, no jq: silence.
KODFLOW_SCOPE=off, off in <config>/kodflow/scope-mode and a line over
8192 characters are decided before the line is parsed, so a large heredoc
costs a specialist what it costs any other caller. Replayed on 480 recorded
specialist calls, 425 ran a command outside the declared scope, mostly
head, sed, grep, cat, tail and wc in pipes: what a refusal would
have stopped, and why there is none. The identity it relies on
is recorded: every PreToolUse a subagent sends carries agent_id and its
agent_type, the plugin-qualified name for a plugin agent
(tests/fixtures/specialist-bash.jsonl). Cost: about 30 ms on a specialist's
shell call of at most 8192 characters (measured on the replay), nothing
past that cap and nothing on any other caller. Tested by tests/test_scope.sh.
Holes — what was not observed, and is not claimed
| Case | What happens |
|---|---|
A session launched on a gated model (--model, the settings' model, ANTHROPIC_MODEL) | no switch event: the SessionStart notice only. Its subagents that inherit it are asked by the mod; without the mod the shell cannot see the parent's model and lets them through |
inherit under an unknown main model, in the shell fallback | passes: a PreToolUse payload carries no parent model |
| Automatic model switches made by the engine (fallback on overload or a limit) | not recorded; if they raise PreModelSwitch with source: sdk they ask or are refused like one |
The model picker, and set_model from the SDK | not recorded (only /model, source: command); handled by the type's documented values |
A fork (subagent_type: fork) | not recorded: the recorded build had no fork type. Judged on parentModel, which the types say a fork always inherits |
| The resume of an agent granted earlier | not recorded; judged as a spawn, so a resume in another session asks again |
turn.step or another plugin rewriting a spawn's model after this mod | not judged; modwall refuses user-tier modules from outside its three marketplaces, a managed one is not judged |
A Skill called from inside a subagent | not recorded; judged as from the main thread |
[general-purpose-ok] | written by the model as easily as by a skill: the routing gate steers |
| The isolation gate | reads paths written out in the prompt only: a repository named by a relative path, a variable or a remote URL is not seen; [isolation-ok] is written by the model as easily |
| The shell fallback without jq | a model or skill value written with an escaped quote or a \u escape is not decoded; with jq it is |
| A foreground subagent's model in its feedback | its PostToolUse Agent comes after its SubagentStop (recorded): the frontmatter's model is named instead |
The task list (mod)
Six tools the mod registers and answers itself (hooks/mod/tasks.ts):
task_create, task_update, task_epic, task_focus, task_list,
task_assign_human, named
mcp__kodflow-hooks__task_*. They keep the session task list in
<config>/kodflow/sessions/<session>/tasks.json, <config> being
CLAUDE_CONFIG_DIR or ~/.claude (always an absolute path). They replace the
built-in task tools, whose panel in the chat duplicates this list. The file
format (version 2) is a contract shared with the shell hooks
(lib/epics.jq), /recap and kodflow-hud, which read it directly. They were an MCP server in Python
(mcp/tasks.py, gone): the port gives the same answers and leaves the same
files, proven by a corpus recorded from it (Tests, below).
- One list per agent. The mod reads the caller from the call itself
(
agentId, absent on the main loop, kept path-safe) and the session from$.session.id()on every call, so a/clearor a/resumelands in the right file. The Stop rules and /recap read the main agent's entries only; kodflow-hud hangs a subagent's own tasks under the task it was handed. - Writes. The file is read fresh on every call and replaced whole: a
temporary file in the session directory, then
mv(exit code checked), so a reader never sees half a list. Calls are queued one at a time inside the process (the main loop and every subagent share one copy of the mod), and amkdirlock (.lock.d, the protocol oflib/lock.sh: stale after 10 s, broken by a rename, written through after 2 s) keeps two processes apart.task_listwrites nothing. Timestamps are in seconds, lengths in code points. Each call is logged throughon-mod.shandlib/event.jq. - Tasks only the user can do.
task_assign_human(subject, epic, description)files a "go", a Touch ID, a gesture on a NAS as a task withassignee: "human"and the statuswaiting, in the epic it unblocks (required, never 0). Main agent only (a subagent says what it needs in its answer), at most 5 open.task_updatecloses it withcompletedonce the user has answered, ordeleted; it never goesin_progressorpending.task_listmarks it "(assigned to the user)", the prompt's epic state lists the open ones ("waiting on the user: …"), and after a compaction the mod puts them back in the context. The user reads what is asked of them in the main agent's reply, which says it. The field is optional:lib/epics.jqand the Stop rules read such a task as anywaitingone. Nothing is submitted on the user's behalf (no$.prompt.submit). - Statuses:
pending,in_progress,waiting(blocked on the user: a decision, an approval, an answer),completed,deleted. The list must say what is true now; the Stop hook flags an active epic with tasks to do and none in progress or waiting, on every turn until it does. - Epics, several open at once. An epic is one subject with its own
tasks.
task_epic(title)opens one and makes it active; the others stay open.task_focus(epic)(id or exact title) switches the active epic back to an open one.task_createrequiresepic: the id of one of the caller's epics, or0for a task outside any epic. There is no default — a task that silently followed the active epic is how work got filed under the wrong subject — so a call without it is refused with the caller's open epics (the active one marked) and the syntax; an unknown id, or another agent's epic, is refused the same way. An epic is open while it is not closed and a task of it is not completed, or while it is active and still empty; completed epics cannot be focused, andtask_epicwith the title of an open epic focuses it instead of duplicating it.task_listshows the active epic's tasks, one#id title done/totalline per other open epic, then the tasks with no epic. Each create, update and focus stamps the epic'stouched. - Closing an epic.
task_focus(epic, close=true)closes an epic of the caller's whose subject is finished: it stampsclosed_at(epoch seconds) and, when it was the active one, leaves the agent with none. It is refused while a task of the epic isin_progress, while one of the user's tasks waits in it, or while a running worker anchored on one of its tasks (the task'sworkers; a worker is anchored on its current assignment or, failing that, its last assignment) still has a task of its own not completed; the refusal names them.closeandreopentogether are refused. A closed epic takes no new task (task_create,task_assign_human), cannot be focused, and its tasks take onlycompletedordeleted("reopen first");task_focus(epic, reopen=true)clearsclosed_atand makes it active again. Another agent's epic is not found. Every reader leaves a closed epic out: the mod (isOpen,openEpics,activeEpic, the user's open tasks),lib/epics.jq(active(),epic_rows), the Stop rules (a blocker in a closed epic is settled), the session-start review, the prompt's epic state and /recap. An epic is closed whenclosed_atis a finite number above 0 (jq:type == "number" and (isinfinite | not) and . > 0); the cases are one fixture,tests/fixtures/epic-predicates.json, read by the jq test andrun-node.tsas a file and by the engine tests of kodflow-hooks and kodflow-hud through the modulesscripts/check-epic-predicates.shwrites. An open epic of the main agent's untouched for 24 h (notouched, no taskupdated), with no task in progress on a live worker and none of the user's waiting, is offered for closing in the prompt's context, once per idle period. The closure hands every worker of the epic to the cleanup below, as the completion of its last task does (epicDone). - Subagents have no epic.
task_epicis the main agent's: a subagent is refused and files its own tasks withepic=0; every refusal a subagent reads about an epic says so. - Triage. Work that writes is filed before anything is written; a
question answered by reading needs no task.
UserPromptSubmitinjects the epic state and a directive to sort the work, everytask_createnaming its epic: new work for an open epic (create it there, focus when starting), context on the task in progress (task_update(id, description)), a change to a completed task (Rework #N: …in its epic), or a new subject (task_epic). At Stop, the main agent's pending tasks with no epic are said whatever epic is active (theloosecause). - One task in progress per worker. The main agent may have one task
in_progressplus one per subagent that isrunning,waitingoridlein$.agent.list()(agents.jsonwhen the list cannot be read); a subagent has one.task_updaterefuses an extra start, and the Stop hook flags more tasks in progress than workers, across every epic, once per state. - A task tied to its worker.
task_update(status=in_progress, worker=<type, name or agent id>)hands a task to a subagent as$.agent.list()names it (its id, itsSendMessagename or its type). The start is refused if that subagent is stopped, unknown, or already holds another task in progress; otherwise it is accepted whatever the headcount, so tasks leftin_progressby finished subagents no longer block a live one.workerandworker_idare stored on the task and dropped when it leavesin_progress; the agent id is also added once to the task'sworkers, which keeps every worker the task was ever handed to in the order they were accepted and never loses one (acompletedwithworker=adds nothing).worker_assignment_orderrecords the order of each worker's assignments across tasks. For history without this field, the last task edit is the fallback. Withoutworker, the headcount above applies as before. Every refusal lists the running subagents (type, id, for how long) and, for each task in progress, its worker and whether it runs, or "no worker linked", then says how to unblock (how long each has run comes fromagents.json, whenon-agent.shrecorded it). At Stop, a task whose worker has stopped is named once per set of such tasks; the headcount rule counts only untied tasks, against the main thread plus the running subagents that hold no tied task; and a task tied to a running subagent never trips the delegation rule. - Session start review. On
startup,resume,clearandcompact,SessionStartlists the main agent's open tasks of every epic (lib/review.jq) and asks to reconcile them first — anin_progressleft by the previous run is not work in progress — and raises the triage gate, so nothing is done before the list is true again. Only while the mod beats. - Turns the user did not type.
UserPromptSubmitalso fires for a background task finishing and for a message relayed from another agent (a subagent's hand-back arrives inside that wrapper, never on its own). Theirpromptstarts with<task-notification>or<agent-message …>;<teammate-message …>and[SYSTEM NOTIFICATION - NOT USER INPUT]are matched too, as shapes seen reaching a session but not yet in a hook payload. Matched anchored, so quoting one is still a user message. Those raise no gate, get no triage directive and leave the Stop loop counter alone — a notification is not the user taking back control. The branch, plan, goal and epic state are still injected: a finishing task is exactly when where-things-stand is wanted. AStop hook feedback:turn is not in that list: it quotes the user's own pending message, so it keeps the gate. - Triage gate.
<config>/kodflow/sessions/<session>/triage-pendingholds one cause per line, raised while the mod beats: oneprompt <id>line per user message (on-user.sh) andresumefor a session start with open tasks (on-session.sh); an empty file is read as one message. The shell appends and the mod drops lines under the same lock (.triage.lock.d,lib/lock.sh), the mod replacing the file through a temporary file andmv. While it is there,PreToolUselets the main agent use the read list,hooks/scripts/lib/read-tools.txt(Read, Glob, Grep, LS, ToolSearch, AskUserQuestion, WebFetch, WebSearch, the task tools by their two exact prefixes, and an exact list of forge reads — no open pattern:mcp__github__mark_all_notifications_readends in_readand writes), and Bash, which keeps its own checks; every other tool (Write, Edit, MultiEdit, NotebookEdit, Agent, Skill, a forge write, a tool nobody listed) is refused with the gesture of each cause left. A question thus never blocks anything. The gate's fast path, its full path and the mod read the same list.KODFLOW_TRIAGE=offturns triage off end to end (below). The mod's outermosttool.callhook writes<session>/triage-wrotewhen the main loop tries a tool off the list (Bash aside) while the gate is up, before the call runs, so a refusal, an error or a cancel counts. A cause is settled on a main-agent task call that succeeded (liftsTriage,settleCauses,calls.ts): apromptbytask_create,task_assign_humanortask_update(id, description),resumebytask_update(id, status), one line per call; oncetriage-wroteexists, the first such call settles every cause at once and removes the mark (settlesAny). Nothing settles a cause on its own.task_list,task_epicandtask_focussettle nothing; a refused call leaves the gate; a store that fails lifts it (fail open). The Stop reminder about an unfiled message comes only whentriage-wroteexists (a question answered by reading is never reminded), and never on a turn the user did not type (turn-systemin the scratchpad); aresumeleft is said either way. Subagents are neither gated nor marked. A stale beat lifts the gate and its mark (nothing could lower it any more) and says/reload-plugins. ThePreToolUsematcher is the catch-all for this; tools the script does not handle are decided without jq (~6 ms per call, measured, the delegation gate included). - The task tree.
task_createandtask_updatealso takeparent(the id of the task this one is a subtask of),blocked_by(the ids it waits on, a list;"3, 4"is read too) andref(a short handle,T0,C6), stored on the task asparent,blockedByandrefonly once set. A parent exists in the caller's list, is in the same epic, and the tree stays three levels deep at most (task, subtask, sub-subtask), counting the subtasks of a task that moves; a task under itself or under one of its own subtasks, a blocker that does not exist, a task waiting on itself, and a wait that closes a cycle (#1 waiting on #3 would be a cycle, #3 already waits on #1 (#3 → #2 → #1)) are refused with the reason, and a refused call changes nothing.parent="",blocked_by=[]andref=""clear one. A deleted task's subtasks move up a level and the tasks waiting on it stop waiting. kodflow-hud draws the tree; nothing else reads these fields. - Limits: task subjects 30 characters (the tree of kodflow-hud cuts the title at 18
cells and shows it whole on the selected task's line; tasks.py allowed 40), refs 5, epic titles 20, refused beyond with the
limit and where the detail goes (
description). A subject written longer before the limit stays as written: it is never rewritten, the tree cuts it. - Format version. The tree's fields, an epic's
closed_atand a task'sworkersandworker_assignment_orderare additive fields in version 2.upgrade()keeps the fields it does not know, and every reader (lib/epics.jq, /recap, kodflow-hud) picks the fields it uses. A file without them is unchanged. A kodflow-hud older than this plugin still shows closed epics: update kodflow-hooks and kodflow-hud together. - v1 files (one epic per agent, a dict) are read as v2 and rewritten by the next change; the hooks read both shapes.
- Running subagents are recorded next to it, in
agents.json, by theSubagentStart/SubagentStophooks, each with the main agent's active epic at its start (0when none), which the cleanup of a closed epic reads. A start merges into the agent's entry when it has one (a resumed agent keeps its id):stoppedis reset tonulland the firstepicis kept. Writes holdlib/lock.sh, amkdirlock (.agents.lock.d):flock(1)does not exist on macOS, where the formerflock -w 2serialised nothing and concurrent starts lost entries. A lock older than 10 s is broken by an atomic rename; one not obtained in 2 s is written through, never blocking.
tests/run-tests.sh runs the mod's node suite (when node can run TypeScript),
then test_root_gate.sh, test_agents.sh (routing gate, gated-model fallback,
agent feedback, on the recorded payloads), test_lock.sh and test_cleanup.sh.
Cleanup on close (KODFLOW_CLEANUP=off)
A subagent works in its own worktree and branch; once its PR is merged, the
worktree, the local branch and the remote branch were removed by hand. The
mod does it when the main agent completes the task linked to that subagent
(task_update with worker=), or closes the epic it worked on.
- Whose worktree. Claude Code does not say where a subagent worked, and
agents.jsonrecords no directory. The mod reads every writing call a subagent makes (Bash command,file_path) for absolute<parent>/.worktrees/<name>paths, the layout rule 5 of the subagent context and the delegation gate impose, and keeps them per agent id inworktrees.json. A path read by mistake is harmless: the checks below decide, not the attribution. - When. In the mod, on the successful
task_update(status=completed)of a main-agent task: the list before the update still holds the task'sworker_id, which the update drops. A Stop hook would find the link gone. A worker cleaned after for a task is tied to that task's epic, so the epic's end tries again what a first attempt left (a PR merged after the task was completed). The epic ends when its last task is completed or whentask_focus(close=true)closes it (epicDone): every worker its tasks ever had (workers) is handed over, with the subagentsagents.jsonsaw start on it. - What must hold (
hooks/scripts/cleanup.sh), for each worktree: a linked worktree, never the repository's main one; its branch neither the default branch (<remote>/HEAD) normainnormaster;git status --porcelainempty; a PR for the branchMERGEDwhoseheadRefOidequals the branch's local head. A squash merge leaves no ancestry, so the heads are compared; a local commit past the merged head is unpublished work. Thengit worktree remove(never--force, run from the main worktree),git branch -D,git push <remote> --delete <head>, where<head>is the merged PR'sheadRefName, never the branch's upstream (a branch cut fromorigin/maintracksmain); the upstream only serves when gh gave no name. A remote name that ismain,masteror the default branch is never deleted: the worktree and local branch go, the notice saysremote-default. When the push fails,git ls-remote --exit-codetells a branch the forge already deleted (said as removed) from a deletion that failed; git's message is never read, since git translates it. - Otherwise nothing is touched, and one line names what is missing
(uncommitted changes, PR open or absent, heads that differ, gh failing or
silent, default branch, main worktree), once per worktree and motif: a
refusal is not repeated, a new motif is said, and a removal is always said,
even after an earlier refusal. The lines go to
cleanup-notices;on-user.shhands them to the model with the next prompt, whole lines up to 4000 bytes, and carries the others incleanup-notices.restfor the prompt after, counted in a line of their own: none is lost or cut. A path that is no longer a worktree is skipped in silence. - Never in the way. The script is started without being awaited, so the
task call answers at once;
gh pr listand the push are each bounded byKODFLOW_CLEANUP_TIMEOUTseconds (default 15), a timeout or a failure counting as "not known to be merged"; the whole run by 300 s. One run per session at a time (lib/lock.sh). Every failure is swallowed.
The project's documents (KODFLOW_DOCS=off)
hooks/docs-catalog.json names fifteen documents (id, French name,
default path, source video or extra, why, touches): requirements,
flow, design brief, data, implementation plan, ADRs, voice, glossary,
quality, testing, threat model, GDPR register, operations, README. A project
moves one (path) or greys one (ignored, a reason, possibly empty) in
docs/manifest.json at its git root; no manifest means every default path,
nothing ignored; a manifest that does not parse reads as absent; unknown ids
are skipped. The hooks only read the manifest. A file is present when it
exists and is not empty; a path ending in / is a directory, present when a
non-empty .md lies anywhere below it.
docs.json, at<config>/kodflow/sessions/<session>/docs.jsonbesidetasks.json(lib/docs.sh, replaced whole bymv): version, git root, manifest, time, and per document its id, name, path,state(ok,missing,ignoredwith itsreason), source and why. Written at SessionStart, after a Write or Edit underdocs/, and at most every 30 s on the next Read, Write, Edit or Bash. Outside a git repository there is none (a stale one is removed at SessionStart). The HUD panel reads it.- SessionStart adds an index to the context: one line per document
(
- <id> <name>: <path>, <state>), then the missing ids. Never a document's text, and nothing in the per-prompt directive ofon-user.sh. - A file read or written (PostToolUse Read, Write, Edit, MultiEdit)
whose path, relative to its own git root (a subagent's worktree included),
matches the
touchesof a document addsdocument concerné : <name> (<path>), ordocument concerné absent : …, /kodflow-workflow:docs <id> le créewhen it is missing; once per document, root and session (docs-noted); nothing for an ignored one, fordocs/,.mdfiles,.git/or.claude/.touchesare bash patterns where*crosses/.
What the log is
.claude/logs/<branch>/session.jsonl, one line per event, every script through
the same jq program. Tool inputs are allow-listed per tool — a Read keeps its
path, never its content; a Bash keeps 500 characters of command and 2000 of
output — and every string is clipped, then redacted (token=, api_key=,
Bearer, provider token prefixes). /learn reads it. It is gitignored.
What was removed, and why
| Was | Now | Reason |
|---|---|---|
permission-request.sh auto-approving "safe" Bash prefixes | gone | a prefix match approved git status; rm -rf ~. Claude Code's own permissions.allow rules do this properly |
worktree-create.sh / worktree-remove.sh | gone | a WorktreeCreate hook replaces Claude Code's worktree support, and the replacement deleted index.lock and ran git fetch on every creation. The native path handles .worktreeinclude and removes unchanged worktrees itself |
worktree cleanup in session-init.sh | gone | it force-removed any worktree older than 24 h, including one with uncommitted work |
task-created.sh contract registry | gone | it needed a capability file nothing writes and a primitives library the plugin never shipped, so it never ran. Team tasks are logged, not adjudicated |
feature-update.sh | gone | errexit on a fail-open hook; its only output went to an async hook and arrived a turn late |
rtk rewrite with permissionDecision: allow | rewrite only, then gone | allow skipped the permission prompt for every command rtk knows. The rewrite itself went next (D3): a hook that changes the input is a second author of every command. rtk is now a prefix the caller chooses |
--force → --force-with-lease rewrite | refusal with the command to run | the rewrite was only correct when the whole line was the push; the refusal says what to run instead |
| stderr "warnings" on exit 0 | additionalContext | stderr on exit 0 goes to the debug log; Claude never saw them |
printf '\a' | terminalSequence | hooks have no terminal; the bell never rang, and on Stop it corrupted the JSON that followed it |
per-event jsonl files, checkpoint.json, compaction snapshots | one log | no reader for any of them; compaction recovery is Claude Code's job |
CLAUDE_ENV_FILE caching of GH_ORG/GH_REPO | gone | no consumer |
common.sh, hook profiles | gone | sourced by one script that used none of it; HOOK_PROFILE set nowhere |
Measured
Wall time per hook invocation on the same machine, 20 runs, realistic payloads
(scripts/tests/test_hooks.sh has the harness):
| Event | 24 scripts | 5 scripts |
|---|---|---|
PreToolUse · Bash ls | 145 ms | 44 ms |
PreToolUse · Bash git commit | 176 ms | 85 ms |
| PreToolUse · Edit | 34 ms | 14 ms |
| PostToolUse · Edit | 103 ms | 37 ms |
| PostToolUse · Bash / Read | 77 ms | 14 ms |
| UserPromptSubmit | 26 ms | 20 ms |
| Stop | 43 ms | 16 ms |
The shell reader runs only when the unquoted line names a verb it knows; a
2.5 kB heredoc commit message costs about 100 ms under bash 5 and bash 3.2
alike. Global substitutions (${x//…/}) are quadratic in bash 3.2 and are
kept off long strings. Logging is a detached subshell and no longer on the
path; its lock is a mkdir, flock being absent on macOS.
Project knobs
| File | Effect |
|---|---|
.claude/protected-paths | one glob per line; replaces the default list (node_modules/, .git/, vendor/, dist/, build/, .env*, *.lock, lockfiles, go.sum) |
ktn-linter on PATH | after each Write, Edit or MultiEdit of a Go file, ktn-linter run --json on the file's package, from its module's directory (the go.mod nearest the file, never above the project root: lib/gomod.sh, lint.ts, one fixture file tests/fixtures/gomod.json), at most 10 s (KF_LINT_TIMEOUT); only that file's findings are kept and given to the model as additionalContext, with the instruction below. Silent when the file is clean, when the run fails, times out or exits 42 (a daemon serves the module through its own hooks), and when the same findings were already given for that file (line numbers left out of the comparison). When ktn-linter's own PostToolUse hook is installed (a ktn-hook command in ~/.claude/settings.json, written by ktn-linter hook install, or in the project's .claude/settings.json or settings.local.json), it already lints each edit through the daemon: nothing is run here, the instruction is given once per session for the findings it reports. The instruction: fix each finding now, in this change; a fix that needs a heavy refactor is still a fix, not a false positive (do it, or say to the user that it is outside the task, never skip silently); only a finding certain to be a false positive gets a complete issue on kodflow/ktn-linter (rule ID, minimal reproduction, file:line, expected and actual, ktn-linter version), then the work goes on |
/lint-setup [path] | checks, for the Go module of path (default the session root), the ktn-linter binary, its command hooks (ktn-linter hook doctor --json), the per-user daemon when KTN_USER_DAEMON=1 (ktn-linter daemon status) and the module's .ktn-linter.yaml; proposes installing the latest release (ktn-linter and ktn-hook, checksum verified) into ~/.local/bin, ktn-linter hook install and ktn-linter daemon ensure, each only after a yes in $.ui.ask; configuration problems are reported, never written |
ROOT_OK=1 prefix on a command | that line is exempt from the delegation gate |
KODFLOW_ROOT=off | the delegation gate, its Stop rule and its prompt line are off for the session |
KODFLOW_MOD=off | the mod hooks nothing: no task tools, no beat, attribution left to Claude Code |
KODFLOW_MCP_PROBE=off | no mcp-shapes.jsonl line after an MCP tool's result |
KODFLOW_ROUTE=off | the routing gate is off for the session |
KODFLOW_ISOLATION=off | the isolation gate is off for the session |
KODFLOW_FABLE=allow · off | gated models pass (allow, still logged) or the gate is not evaluated (off), in the mod and the shell alike |
KODFLOW_FEEDBACK=off | no rule 6, nothing kept, nothing proposed |
KODFLOW_SCOPE=off | no Command scope advice on a kodflow-specialists agent's shell call, no scope.jsonl (also off in <config>/kodflow/scope-mode) |
KODFLOW_FORGE_BROWSER=ask · off | Claude in Chrome toward a forge: each call asks the user (ask, the way to grant one call they agreed to) or is not checked (off); refused by default |
KODFLOW_FORGE_HOSTS | more forge hosts for that check, space- or comma-separated (a GitLab instance the session's directory has no remote for) |
KODFLOW_LINT=off | no ktn-linter run after an edit and no instruction; ktn-linter's own hooks, when installed, are not affected. For every project: "env": {"KODFLOW_LINT": "off"} in ~/.claude/settings.json. For one project: the same env block in that project's .claude/settings.json (applied once the workspace is trusted, and in -p runs; a hook inherits it) |
KODFLOW_STOP_TASKS=off | no Stop line about the task list (stopped, overcount, idle, loose, builtin); the triage line and the delegation line (unattended, KODFLOW_ROOT) stay; no relaunch on open tasks either |
KODFLOW_TRIAGE=off | no triage at all: no cause raised (prompt or resume), no gate, no write mark, no directive with the prompt, no Stop reminder; the session-start review is still said |
KODFLOW_STOP_CONTINUE=off | the Stop hook never relaunches the turn on open tasks (« Relaunch on open tasks ») |
KODFLOW_LANG=en · fr | the language of the texts, over Claude Code's language setting |
NO_COLOR · KODFLOW_COLOR=off | the Stop feedback without colour |
KODFLOW_COMMIT_IDENTITY=<path> · off | another commit-identity rules file, or the check off (default ${CLAUDE_CONFIG_DIR:-~/.claude}/kodflow/commit-identity.conf, absent means off) |
KODFLOW_DOCS=off | no docs.json, no index at SessionStart, no document concerné line |
docs/manifest.json | moves (path) or ignores (ignored) a document of the catalogue for this project |
KODFLOW_CLEANUP=off | no worktree, branch or remote branch is removed on close, no notice; KODFLOW_CLEANUP_TIMEOUT (seconds, default 15) bounds each gh and push call |
The Stop feedback
What on-stop.sh returns as additionalContext is shown on screen as
« Stop hook feedback » and read by Claude. It speaks only when the task list
says something false, one line per cause, each task named once (by the
first cause that claims it, in this order), and each cause once per state:
stop-said in the scratchpad keeps, per cause, the fingerprint of the
state last said; the same state is not said twice in a row, a changed one
is, and a cause that clears drops its record.
| Cause | Colour | When |
|---|---|---|
stopped | red | in_progress, tied to a subagent that has stopped |
unattended | orange | in_progress, tied to nobody, on an epic no running subagent covers (KODFLOW_ROOT) |
overcount | orange | more untied tasks in_progress than workers |
idle | orange | the active epic has work to do, nothing in_progress or waiting |
loose | orange | requests with no epic left pending |
builtin | orange | open tasks of Claude Code's own list (TaskUpdate) |
| triage, resume | orange | a message with no task, tasks left open at the session start |
| CLAUDE.md | orange | a changed directory whose CLAUDE.md was not updated |
| agent feedback | green | subagent feedback that waits on the user's decision |
A task in_progress on a running subagent and a waiting task are true
and never said. The reported case, three tasks on stopped subagents, was
three sections and nine lines; it is now one:
Tâches à remettre d'aplomb : #99 #100 #101 (sous-agent arrêté : terminer, remettre en pending ou waiting, ou relancer l'agent)
Relaunch on open tasks. Anthropic's Prompting Claude Opus 5.5 says to
"treat a text-only end of turn as a report rather than as proof the task is
done" and to "stop after two or three automatic continuations on the same
task". When the main agent ends its turn with tasks to do, the same document
carries decision: "block" and a reason built on the guide's sample:
Your task list still has open items: #7 Ship the hook. Continue with them. If one is blocked, say what is blocking it.
To do means the main agent's task, in an epic, pending with every
blocked_by done, or in_progress and not on a running subagent. A
waiting task never relaunches anything. Each task relaunches the turn twice
at most per session (stop-continue in the scratchpad, id<TAB>count,
written before the block is sent; a counter that cannot be written blocks
nothing), so the relaunch passes stop_hook_active without looping. Never for
a subagent, never in plan mode, off with KODFLOW_STOP_CONTINUE=off or
KODFLOW_STOP_TASKS=off, and any error lets the stop through.
Colour. Claude Code 2.1.309 renders the ANSI colours of a Stop hook's
additionalContext and systemMessage (measured in a pty: the escape
reaches the screen as sent, \e[31m before the text). Only the label of
each line is coloured, so the model pays a few tokens on a turn the hook
speaks. Nothing the screen does not show is coloured: the
UserPromptSubmit context is not displayed, it stays plain.
Language. Every text of the shell scripts that the user or the model
reads at Stop and at each prompt lives in one table, hooks/messages.json
(en and fr), read by lib/msg.sh. The language is Claude Code's
language setting (free text, read from the user settings, then the
project's settings.json and settings.local.json, the last one that sets
it winning): French when it names French (fr, french, Français...),
English otherwise. The guards' refusals (on-tool.sh and their double in
the mod) and the task tools' answers are still in English.
Tests
bash scripts/tests/test_hooks.sh
bash plugins/kodflow-hooks/tests/run-tests.sh # mod (node) + delegation gate + test_agents.sh + test_cleanup.sh + test_identity.sh + test_docs.sh + test_adr.sh + test_scope.sh
claude plugin validate --json plugins/kodflow-hooks
claude plugin test plugins/kodflow-hooks # tests/mod/*.test.ts, in the engine
node plugins/kodflow-hooks/tests/mod/run-node.ts # corpora, real disk, several processes, invariants
The mod is held three ways. tests/mod/conformance.corpus.ts was recorded
from mcp/tasks.py before it was removed (38 scenarios, 184 calls: the 26
tests of its suite, the worker cases, the order of validation, code points,
task_list writing nothing, the agent id made path-safe, a worker judged by its id alone): each step keeps the
file before, the call, the answer and the file after, and the port must match
every one (conformance.ts, run by claude plugin test and by node). The
changes since are deliberate, and the corpus is replayed amended for them,
every other byte as recorded: the 30-character subject (its long subjects
shortened, its limits moved); the subject and title refusals reworded to
name the task tree (5 scenarios); a subagent's refusals sending it to
epic=0 rather than task_epic (3 scenarios), the scenario where a
subagent opened epics of its own retired (1) and its refusal tested apart;
and worker history carried forward (amendState: from the first worker=
accepted in a scenario, the fields in the state after that step and before
and after every later one — 9 accepted starts,
16 steps, 26 states, 6 scenarios; the counts are asserted). task_create,
task_update, task_epic and task_focus, whose text or arguments moved,
must still take every argument tasks.py gave them, as it gave them.
tests/mod/tasks.test.ts holds the tree (parent, depth, cycles, blockers,
refs, a deletion's links, the file left at version 2), the epic lifecycle
(close and its refusals, a closed epic's refusals, reopen), workers
(deduplicated, a completed with worker= adding nothing), the subagents'
refusals, the read list, and the predicates against the shared fixture
(tests/fixtures/epic-predicates.json, through the generated
tests/mod/epic-predicates.ts; test_epic_predicates.sh reads it with jq).
tests/mod/register.test.ts runs the wiring in the engine's own test kit,
with the host in memory: registration, the temporary file and mv under the
lock, refusals as { deny }, the cap read from $.agent.list(), the beat
written before the call goes on, KODFLOW_MOD=off, the attribution text,
and the triage mark: a question that reads and Bash alone mark nothing, an
Edit refused beneath the mod is marked before it runs, a Skill an inner hook
refuses and mark_all_notifications_read are marked, a subagent never is,
the first task gesture after a mark settles every cause, an unreadable read
list marks every tool but Bash and is read again.
run-node.ts runs the store on a real disk, a stale lock, and six processes
writing one tasks.json at once (every task kept, ids unique); then the
bash-guard corpus against the mod's guards in a real repository (every Bash
row decided as on-tool.sh decides it, known gaps reported), and the module's
invariants read from its sources (never allow; { result } built only by a
task tool, the filter and the veil; the secret variables read are
SECRET_VARS; the MCP probe imports paths.ts alone and reads no text or
data field), and the probe's append on a real file system (0600, also on a
file that was 0644, no value written). tests/mod/mcp-probe.test.ts holds the
probe's line. tests/mod/pipeline.test.ts holds the pipeline's logic: the
order of the policies and a failure injected into each, the filter on its
corpus and on the "bytes" corpus (reads never touched), the veil and its false
positives (git hashes, base64 of text) and its image blocks left whole, and the shell reader's details.
A hundred and forty cases in a throwaway repository, plus the bash-guard
corpus (about two hundred lines, rc and motif compared): every block, the
input never rewritten, the tracker fed a file name that is also a shell command, the
redaction of every persisted string, the Stop reminder firing once, the task rules on the active epic only, the
lint of the file just edited (its findings only, the instruction, a set given
once, a clean run clearing it, silence on a failed run, nothing run beside
ktn-linter's own hook, KODFLOW_LINT=off), KODFLOW_STOP_TASKS=off, the
triage and epic state injected with each prompt, and every
script fed garbage or nothing and exiting 0.
test_hooks.sh runs with KODFLOW_ROOT=off so its main-thread payloads reach
the guard they test. The delegation gate has its own suite,
tests/test_root_gate.sh (run by tests/run-tests.sh): writes inside and
outside a work tree (worktree gitdir files, relative and .. paths), memory
and configuration inside a repository, sysadmin commands allowed, every
producing git/forge op refused including wrapped forms, merges allowed and journaled, the
forge MCP tools, the escapes, the subagent never gated, the Stop rule with and
without a subagent on the epic, and the log tags.
ADR header contract (lib/adr_lint.py)
An ADR is docs/adr/NNNN-slug.md; its header (bullets before the first ## ,
- Status: or - **Status**:, MADR front matter tolerated) carries Status
(first word in proposed|accepted|rejected|deprecated|superseded|amended),
Date (ISO), Area (tags from docs/adr/areas.txt when that file exists) and
Need (decision|constraint|incident|convention|record). python3 -I adr_lint.py --check <dir|file> [--strict] prints one line per defect (exit 1 only with
--strict). on-tool.sh runs it on Write/Edit of docs/adr/NNNN-*.md:
KODFLOW_ADR_LINT unset = a new ADR without a valid Area/Need is refused, an
existing one gets its defects as PostToolUse context; warn never refuses;
strict refuses any defect; off is silent. A repository runs the same check
in CI: see docs/marketplace/adr-lint-ci.md.
Document index (lib/kf_docs.py)
A stdlib-only SQLite FTS5 index (BM25, no network) of the project's documents:
docs/adr/*.md split by ## section, docs/**/*.md and every CLAUDE.md,
in ~/.cache/kodflow/docs-index/<sha1(git root)>.db, plus global.db for
~/.claude/docs and ~/.claude/projects/*/memory. The tokenizer is unicode61
with tokenchars '.-_/', so 0.2.57, ADR-0152 and net/http1 match whole,
and num is an exact column. Reindexing is incremental by mtime and size.
python3 -I lib/kf_docs.py index [--root DIR]
python3 -I lib/kf_docs.py search QUERY [--area A] [--need N] [--status S] [--all] [--limit 8] [--format text|json|md]
A search returns at most 8 files (their best section), each num · title · status · area · path:line and a snippet of at most 200 characters; superseded
ADRs are left out unless --all. The mod registers the same search as the
docs_search tool (read-only, on read-tools.txt), for sessions where a CLI
call is not wanted. SessionStart and a Write/Edit under docs/ (or of a
CLAUDE.md) refresh the index in a detached background child, never waited on;
KODFLOW_DOCS_INDEX=off lifts that, KODFLOW_DOCS_CACHE moves the cache.
Decision map and CLAUDE.md budget (SessionStart)
kf_docs.py map prints at most 60 lines and 3600 bytes: the accepted ADRs
(superseded ones left out) grouped by Area (- when absent), a short title
and the amends / supersedes edges; ADRs with edges come first, then the
newest, the rest is counted. SessionStart appends it to the document index
(headers only, 5 s bound, fails open; KODFLOW_DOCS_INDEX=off lifts it). It
also adds one line when the root CLAUDE.md exceeds 24 KB or another one 12
KB (kf_docs.py budget; KODFLOW_CLAUDE_MD_ROOT_KB, KODFLOW_CLAUDE_MD_SUB_KB
move the numbers, KODFLOW_CLAUDE_MD_BUDGET=off lifts it). kf_docs.py export --obsidian DIR writes one generated note per ADR with [[ADR-NNNN]] links:
an output, never a source.