From 2963382da8e6aba9666750877db8c1d028c14d49 Mon Sep 17 00:00:00 2001
From: Claude
Date: Sat, 25 Jul 2026 18:00:14 +0000
Subject: [PATCH] v0.5.0: per-agent attribution in the record, and the
concurrency fix it needed
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
The record could say what happened and under which loop, but not *who*. With
one human and one agent that was fine — everything in the log was "the agent".
Running three in three worktrees on one repo, it stops being fine: at merge
time, "what was it allowed to do, and what did it do?" needs a subject.
Every entry is now stamped with `by` (the agent), `branch`, `worktree`, and
`session` when the harness supplies one. Resolution is explicit-first — `--by`,
then DOCKET_BY, then a detected agent, then the OS user — and every field is
omitted rather than filled with a placeholder that reads like a fact. Read it
back with `docket record log --by` and `docket metrics --by`.
Two properties stated plainly, because attribution is easy to oversell: `by`
is self-reported (provenance, not authentication), and it cannot be revised —
it is inside the hashed entry, so rewriting who an old entry blames breaks the
chain there.
Fixes a real bug found while building it: appending is read-the-head-then-
chain-to-it, so parallel agents could both chain to the same entry and leave
`verify` reporting "an entry was removed, added, or reordered" on a log nobody
had touched. Six concurrent writers corrupted the chain reliably. Appends are
now serialized across processes with an exclusive lock file (stale locks broken
after 10s, an error rather than an unlocked write if it can't acquire one). A
false tamper alarm is worse than no alarm — it teaches people to disbelieve the
real one.
Also fixes `docket record log --n ` silently printing the entire
log instead of erroring, and a stale "this is v0.3.x" in the README.
16 new tests, including five agents writing simultaneously from separate
processes; verified they fail when the lock is removed. Eval unchanged:
10,582 checks, zero silent allows, zero fail-open.
Co-Authored-By: Claude Opus 5
Claude-Session: https://claude.ai/code/session_019xDGH82gMx6NWh3xqinF9B
---
.gitignore | 1 +
README.md | 50 +++++++++++-
README.zh.md | 43 ++++++++++-
docs/docs.html | 48 ++++++++++--
package.json | 2 +-
spec/SPEC.md | 48 +++++++++++-
src/cli.js | 8 +-
src/commands/check.js | 5 +-
src/commands/hook.js | 12 ++-
src/commands/init.js | 4 +
src/commands/mcp.js | 19 ++++-
src/commands/metrics.js | 29 ++++++-
src/commands/record.js | 43 ++++++++---
src/lib/actor.js | 125 ++++++++++++++++++++++++++++++
src/lib/metrics.js | 21 ++++-
src/lib/record.js | 135 ++++++++++++++++++++++++++------
test/attribution.test.js | 163 +++++++++++++++++++++++++++++++++++++++
test/concurrency.test.js | 133 ++++++++++++++++++++++++++++++++
18 files changed, 828 insertions(+), 61 deletions(-)
create mode 100644 src/lib/actor.js
create mode 100644 test/attribution.test.js
create mode 100644 test/concurrency.test.js
diff --git a/.gitignore b/.gitignore
index 552f221..04bec35 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,2 +1,3 @@
node_modules/
*.log
+record.jsonl.lock
diff --git a/README.md b/README.md
index 416cf0d..23dfb31 100644
--- a/README.md
+++ b/README.md
@@ -32,6 +32,7 @@ Zero dependencies · plain Markdown + JSONL · MIT
## News
+- **2026.07** — **`v0.5.0`: the record learns *who*.** Every entry is now stamped with the agent, branch, and worktree that wrote it (**`by`**), so parallel agents stay separable at merge time — with `docket record log --by` and `docket metrics --by` to read one agent's posture back. Appends are now serialized across processes, fixing a real bug: agents writing in parallel could break the hash chain and make `verify` report tampering that never happened. ([who did what](#who-did-what-attribution-for-parallel-agents))
- **2026.07** — **`v0.4.0` on npm.** One command to make docket ambient in a repo (**`docket install`** — context + hook + MCP, committed and shared); the loop becomes the full **agent contract** (`goal` / `stop` / `budget`); and **`docket metrics`** reads the record back as your autonomy posture — auto-approve vs ask vs deny, longest unattended run, actions per intervention. ([why this matters](#the-loop-is-the-agent-contract))
- **2026.07** — The red-team program grows to [**10,582 checks across six suites**](eval/REPORT.md): adversarial phrasing, vague-target probes, 10,000 fuzzed targets, 239 tamper mutations, and a live hook-gate corpus — zero silent allows, zero fail-open. The matcher now splits compound targets clause by clause, so a consequence can't ride along with an allowed phrase.
- **2026.07** — `v0.3.0` ships **`docket hook`**: the warrant as a Claude Code PreToolUse gate — allow/ask/deny enforced by the harness, not the prompt. Plus the deferred-consequence rule in the spec and the **scheduled escape** red-team family.
@@ -302,7 +303,7 @@ $ docket record add appeal \
--saw "policy §4.2, denial letter 2026-06-12" \
--did "drafted appeal citing §4.2(b), built evidence list" \
--stopped "before send — two claims need human verification"
-✓ record #4 sha256:fd4394fc8cd4b288…
+✓ record #4 sha256:fd4394fc8cd4b288… by claude-code
$ docket record verify
✓ chain intact — 4 entries, every entry commits to the one before it
@@ -323,6 +324,49 @@ And because a hash chain can't see its own tail being cut off, `verify`
prints the head hash: pin it anywhere the log can't reach, then
`docket record verify --head ` catches truncation too.
+## Who did what: attribution for parallel agents
+
+One human running one agent needs no subject in the log — everything in it is
+*the* agent. That stops being true the moment you run three, in three
+worktrees, on the same repo. At merge time, "what was it allowed to do, and
+what did it do?" needs a **who**.
+
+Every entry now carries one, stamped automatically:
+
+```console
+$ docket record log
+#7 2026-07-24 09:12Z deploy allow change → "src/api/rates.ts" (change: source files) ← claude-code @ hotfix-402
+#8 2026-07-24 09:12Z deploy ask send → "Bash: gh pr merge" (default) ← claude-code @ hotfix-402
+#9 2026-07-24 09:14Z deploy allow read → "test/rates.test.ts" (read: the repo) ← cursor @ wt-perf:perf-pass
+
+$ docket metrics --by claude-code # one agent's posture, not the team average
+```
+
+`by` is resolved in precedence order — `--by `, then `DOCKET_BY`, then
+a detected agent (Claude Code, Cursor, Gemini CLI, Codex, Aider, GitHub
+Actions), then the OS user — alongside the git `branch`, the `worktree` name
+when the write came from a linked one, and the harness's `session` id when it
+supplies one (the Claude Code hook does). Fields with no honest value are
+**left out** rather than filled with a placeholder that reads like a fact.
+
+Two things worth being precise about, because attribution is easy to oversell:
+
+- **`by` is self-reported.** A process that can write to the record can claim
+ any subject. This is provenance, not authentication.
+- **But it can't be revised.** `by` is inside the hashed entry, so rewriting
+ who an old entry blames breaks the chain at that entry. Whoever wrote it is
+ stuck with what they claimed at the time — which is the property an audit
+ actually needs.
+
+**And parallel agents no longer break the chain.** Appending is
+read-the-head-then-chain-to-it, so two agents writing at once could both chain
+to entry 5 — after which `verify` reported *"an entry was removed, added, or
+reordered"* on a log nobody had touched. Appends are now serialized across
+processes (an exclusive lock file, stale locks broken after 10s, an error
+rather than an unlocked write if it can't acquire one). A false tamper alarm
+is worse than no alarm: it teaches people to disbelieve the real one. Five
+agents × twelve writes each, landing simultaneously, is now a test.
+
## Your context, every model
Context locked inside one vendor's assistant is their context, not yours.
@@ -593,7 +637,7 @@ Selling this honestly means saying where the edges are:
[hook](#enforced-not-suggested-claude-code-hook) enforces them mechanically
where you wire it; and either way, every check lands on the record. Each
layer is exactly as strong as it claims, and no stronger.
-- **Not finished.** This is v0.3.x, and the spec may still break before 1.0
+- **Not finished.** This is v0.5.x, and the spec may still break before 1.0
(loop files carry a `version` field for exactly that reason). What won't
move: unlisted means ask, failures land on the human, and the record stays
tamper-evident.
@@ -615,7 +659,7 @@ Read the [Loop File Spec](spec/SPEC.md) — it's short on purpose.
## Roadmap
- [x] ~~`docket check` as a Claude Code PreToolUse hook~~ — shipped as `docket hook claude`
-- [ ] Per-agent / worktree attribution in the record (a `by:` field) — the merge-time audit trail when many agents write in parallel (autonomy levels 4–5)
+- [x] ~~Per-agent / worktree attribution in the record (a `by:` field)~~ — shipped in v0.5.0, [with the concurrency fix it needed](#who-did-what-attribution-for-parallel-agents)
- [ ] Autonomy-levels guide — mapping loops and readiness to L0–L5, so teams pick a level by its verification, not the task name
- [ ] Signed record heads (attest the chain tip, share the attestation)
- [ ] Loop inheritance (`extends:`) for team baselines
diff --git a/README.zh.md b/README.zh.md
index e94219d..2792802 100644
--- a/README.zh.md
+++ b/README.zh.md
@@ -32,6 +32,7 @@ ChatGPT/Codex、Gemini、Cursor、OpenClaw、Hermes 以及任何 MCP 客户端
## 最新动态
+- **2026.07** — **`v0.5.0`:记录开始回答“是谁”。** 每一条记录都会自动盖上写入者的智能体、分支与工作树(**`by`**),并行工作的多个智能体在合并时依然可以分辨;配套 `docket record log --by` 与 `docket metrics --by`,可单独回看某一个智能体的自治姿态。同时修复了一个真实缺陷:并行写入的智能体会撑破哈希链,让 `verify` 报出根本没发生过的篡改——现在追加写入在进程之间串行化。([谁做了什么](#谁做了什么并行智能体的归属))
- **2026.07** — **`v0.4.0` 发布至 npm。** 一条命令让 docket 覆盖整个仓库(**`docket install`**——上下文 + 钩子 + MCP,随仓库提交共享);loop 成为完整的**智能体契约**(`goal` / `stop` / `budget`);**`docket metrics`** 把记录读回为你的自治姿态——自动放行 vs 询问 vs 拒绝、最长无人值守连续、每次干预的动作数。
- **2026.07** — 红队测试计划扩展到[**六个套件、10,582 项检查**](eval/REPORT.md):对抗性措辞、模糊目标探针、10,000 次模糊测试、239 次篡改变异、真实钩子门禁语料——零静默放行,零失效开门。匹配器现按子句拆分复合目标,后果无法搭上被许可短语的顺风车。
- **2026.07** — `v0.3.0` 推出 **`docket hook claude`**:把授权令变成 Claude Code 的 PreToolUse 门禁——allow/ask/deny 由执行框架强制执行,而不是靠提示词。同时规范新增“延迟后果”规则,红队套件新增**定时逃逸**场景族。
@@ -201,7 +202,7 @@ $ docket record add appeal \
--saw "policy §4.2, denial letter 2026-06-12" \
--did "drafted appeal citing §4.2(b), built evidence list" \
--stopped "before send — two claims need human verification"
-✓ record #4 sha256:fd4394fc8cd4b288…
+✓ record #4 sha256:fd4394fc8cd4b288… by claude-code
$ docket record verify
✓ chain intact — 4 entries, every entry commits to the one before it
@@ -222,6 +223,42 @@ $ docket record verify
把它钉在日志够不到的任何地方,之后用 `docket record verify --head `
连截尾也能查出来。
+## 谁做了什么:并行智能体的归属
+
+一个人跑一个智能体时,日志里不需要“主语”——里面的一切都是*那个*智能体。
+但当你在同一个仓库的三个工作树里跑三个智能体,这一点立刻失效。
+到了合并的时刻,“它被允许做什么、它又做了什么”需要一个**谁**。
+
+现在每一条记录都自动带上它:
+
+```console
+$ docket record log
+#7 2026-07-24 09:12Z deploy allow change → "src/api/rates.ts" (change: source files) ← claude-code @ hotfix-402
+#8 2026-07-24 09:12Z deploy ask send → "Bash: gh pr merge" (default) ← claude-code @ hotfix-402
+#9 2026-07-24 09:14Z deploy allow read → "test/rates.test.ts" (read: the repo) ← cursor @ wt-perf:perf-pass
+
+$ docket metrics --by claude-code # 只看这一个智能体的姿态,而不是团队平均值
+```
+
+`by` 按优先级解析——`--by `、`DOCKET_BY`、自动识别的智能体
+(Claude Code、Cursor、Gemini CLI、Codex、Aider、GitHub Actions),最后才是操作系统用户;
+同时记录 git `branch`、来自关联工作树时的 `worktree` 名,
+以及执行框架提供的 `session` id(Claude Code 钩子会提供)。
+没有确切值的字段会被**留空省略**,而不是填一个读起来像事实的占位符。
+
+有两点必须说清楚,因为归属很容易被夸大:
+
+- **`by` 是自述的。** 能写入记录的进程就能声称任意身份。这是来源信息,不是身份认证。
+- **但它无法被事后改写。** `by` 参与条目哈希,改动旧条目归属谁会当场撑破哈希链。
+ 写的人被钉在他当时的声称上——这才是审计真正需要的性质。
+
+**并行的智能体也不再撑破链条。** 追加写入是“先读链头、再锚定它”,
+所以两个同时写入的智能体可能都锚定到第 5 条——之后 `verify` 会对一份
+没人碰过的日志报出*“有条目被删除、插入或重排”*。
+现在追加写入在进程之间串行化(独占锁文件、超过 10 秒的陈旧锁会被打破、
+拿不到锁就报错而不是无锁写入)。误报的篡改警报比没有警报更糟:
+它教会人们不相信真正的警报。五个智能体各写十二条、同时落盘,现在是一条测试。
+
## 你的上下文,任何模型
锁在某一家厂商助手里的上下文,是他们的上下文,不是你的。
@@ -416,7 +453,7 @@ allow read: "state insurance regulations" in appeal? [y/N] y
- **不是魔法牢笼。** 配合的智能体遵循编译进上下文的规则;钩子在你接线的地方
机械地强制执行;无论哪种情况,每次检查都落在记录上。每一层的强度恰如其分,
不多不少。
-- **还没有完成。** 现在是 v0.3.x,规范在 1.0 之前仍可能有破坏性变更
+- **还没有完成。** 现在是 v0.5.x,规范在 1.0 之前仍可能有破坏性变更
(loop 文件带 `version` 字段正是为此)。不会变的是:未列出即询问、
故障落向人类、记录防篡改。
@@ -435,6 +472,8 @@ allow read: "state insurance regulations" in appeal? [y/N] y
## 路线图
- [x] ~~`docket check` 作为 Claude Code PreToolUse 钩子~~ — 已以 `docket hook claude` 发布
+- [x] ~~记录中的按智能体 / 工作树归属(`by:` 字段)~~ — 已在 v0.5.0 发布,[连同它所需要的并发修复](#谁做了什么并行智能体的归属)
+- [ ] 自治层级指南——把 loop 与就绪度映射到 L0–L5,让团队按验证方式而不是任务名称来选层级
- [ ] 记录链头签名(为链尖出具证明,可对外分享)
- [ ] loop 继承(`extends:`),用于团队基线
- [ ] 记录导出 → 人类可读的工作摘要
diff --git a/docs/docs.html b/docs/docs.html
index a4504c9..1cdb3f5 100644
--- a/docs/docs.html
+++ b/docs/docs.html
@@ -466,6 +466,36 @@ The record
| note | work evidence: saw, did, skipped, stopped, note |
| amend | a human-approved warrant widening from docket review — rule changes are evidence too |
+ Who wrote it
+ Every entry is stamped with its subject, so several agents working the same repo
+ in parallel worktrees stay separable at merge time:
+ $ docket record log
+#7 2026-07-24 09:12Z deploy allow change → "src/api/rates.ts" (change: source files) ← claude-code @ hotfix-402
+#9 2026-07-24 09:14Z deploy allow read → "test/rates.test.ts" (read: the repo) ← cursor @ wt-perf:perf-pass
+
+ Read it back with docket record log --by <agent> or
+ docket metrics --by <agent>. Fields with no honest value are omitted
+ rather than filled with a placeholder, and entries written before attribution existed
+ read as unattributed — never guessed at.
+ Attribution is self-reported, and cannot be revised. A process that can
+ write to the record can claim any by it likes — this is provenance, not
+ authentication. But by is inside the hashed entry, so rewriting who an
+ old entry blames breaks the chain at that entry. Whoever wrote it is held to what
+ they claimed at the time.
+ Parallel writers
+ Appending is read-the-head-then-chain-to-it, so appends are serialized across
+ processes with an exclusive lock file next to the record (stale locks broken after
+ 10s; an error rather than an unlocked write if it can’t acquire one). Without that,
+ two agents writing at once both chain to the same entry and verify
+ reports tampering nobody did — and a false alarm in an audit trail is worse than no
+ alarm. Scope is one machine; a record on a shared network filesystem is outside what
+ this guarantees.
The hash chain
Each entry commits to the previous one:
hash = sha256(prev + canonical(entry)). Any edit, deletion, insertion, or
@@ -526,11 +556,13 @@
Metrics: your autonomy posture, from the record
warrant amendments 0 human-approved widenings (docket review)
It reports the auto-approve / ask / deny split, the longest unattended run
(consecutive allows with no human stop), a proxy for actions-per-intervention, and a
- per-loop and per-channel breakdown. Every number is exact from the hash chain except
+ per-loop, per-channel, and per-agent breakdown. Every number is exact from the hash chain except
the labeled proxies — the record measures actions and verdicts, not wall-clock or
intent. This is the dashboard Addy Osmani argues teams need to climb the autonomy
ladder deliberately toward “calibrated autonomy.” Add --json to
- gate CI on it, or --loop <name> to scope it.
+ gate CI on it, or --loop <name> / --by <agent> to scope it — with several
+ agents on one repo, “how autonomous is this agent?” is the question that has an
+ actionable answer.
@@ -738,15 +770,15 @@ CLI reference
docket list | list your loops |
docket show <loop> | print a loop’s five layers |
docket match <task…> | which loop covers this task? — ranked with why (--limit N); exits 0 matched / 2 no coverage |
- docket check <loop> <verb> <target…> | verdict + rule; exits 0/2/3; logged unless --no-record; --quiet prints the bare verdict |
- docket record add <loop> | append evidence: --saw --did --skipped --stopped --note |
- docket record log [loop] | show recent entries (--n 20) |
+ docket check <loop> <verb> <target…> | verdict + rule; exits 0/2/3; logged unless --no-record; --quiet prints the bare verdict; --by <agent> names the writer |
+ docket record add <loop> | append evidence: --saw --did --skipped --stopped --note; --by <agent> names the writer |
+ docket record log [loop] | show recent entries (--n 20), each with who wrote it; --by <agent> shows one agent’s |
docket record verify | verify the chain end to end; --head <hash> pins against tail truncation |
- docket metrics | autonomy posture from the record: auto-approve / ask / deny split, longest unattended run, actions per intervention, per-loop & per-channel (--loop, --json) |
+ docket metrics | autonomy posture from the record: auto-approve / ask / deny split, longest unattended run, actions per intervention, per-loop, per-channel & per-agent (--loop, --by, --json) |
docket review | propose warrant updates from repeated asks (--min, --loop, --yes) |
docket compile | --target claude|agents|gemini|cursor|raw, --write to update the file in place, --loop to preview one loop on stdout, --index to compile the routing table instead of full loops |
- docket mcp | run the MCP server (--dir or DOCKET_DIR to locate the project) |
- docket hook claude | Claude Code PreToolUse hook: deny blocks, ask prompts the human, allow stays silent (--loop pins a loop, --strict asks on no coverage, --dir locates the project); with a gate pinned, every failure mode fails closed to ask |
+ docket mcp | run the MCP server (--dir or DOCKET_DIR to locate the project; --by names the client in the record) |
+ docket hook claude | Claude Code PreToolUse hook: deny blocks, ask prompts the human, allow stays silent (--loop pins a loop, --strict asks on no coverage, --dir locates the project, --by names the writer); with a gate pinned, every failure mode fails closed to ask |
diff --git a/package.json b/package.json
index e0ea574..56acd6f 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "docket-agent",
- "version": "0.4.0",
+ "version": "0.5.0",
"description": "The permission layer and paper trail for AI agents. Your agent checks a rule file before it acts - allow, ask, or deny - and leaves a tamper-evident record after.",
"type": "module",
"bin": {
diff --git a/spec/SPEC.md b/spec/SPEC.md
index 094b5bf..8742bcb 100644
--- a/spec/SPEC.md
+++ b/spec/SPEC.md
@@ -265,7 +265,7 @@ do, leave alone, and where did it stop?*
Storage: `.docket/record.jsonl`, one JSON object per line, append-only.
```json
-{"seq":3,"ts":"2026-07-03T10:15:00.000Z","loop":"insurance-appeal","kind":"check","action":"send","target":"appeal email to insurer","verdict":"ask","rule":"ask: anything addressed to the insurer","prev":"sha256:…","hash":"sha256:…"}
+{"seq":3,"ts":"2026-07-03T10:15:00.000Z","loop":"insurance-appeal","kind":"check","action":"send","target":"appeal email to insurer","verdict":"ask","rule":"ask: anything addressed to the insurer","by":"claude-code","branch":"fix/claim-402","prev":"sha256:…","hash":"sha256:…"}
```
Three kinds today:
@@ -277,6 +277,47 @@ Three kinds today:
- `amend` — a human-approved warrant widening (`action`, `added`, `asks`),
written by `docket review`. Rule changes are evidence too.
+### Attribution
+
+Every entry carries the subject that wrote it. With one human and one agent,
+`loop` was enough; with several agents working the same repo in parallel
+worktrees, "what was it allowed to do, and what did it do?" needs a *who*.
+
+| Field | Meaning |
+|---|---|
+| `by` | the writer — a detected agent id (`claude-code`, `cursor`, …), an explicit `--by`, or `user:` |
+| `branch` | the git branch at write time; a short sha when HEAD is detached |
+| `worktree` | the linked worktree's name, when the write came from one |
+| `session` | the harness's own session id, when it supplies one (the hook does) |
+
+`by` resolves in precedence order — explicit `--by`, then `DOCKET_BY`, then a
+detected agent, then the OS user — and every field is **omitted** rather than
+filled with a placeholder when there is no honest value. Implementations must
+not invent a subject for entries that lack one; readers report those as
+unattributed.
+
+**`by` is self-reported, and that limit is the point of stating it.** A
+process that can append to the record can append any `by` it likes — this is
+provenance, not authentication. What the chain does guarantee is that
+attribution cannot be *revised*: `by` is inside the hashed entry, so changing
+who an old entry blames breaks the chain at that entry. Whoever wrote it is
+held to what they claimed at the time.
+
+### Concurrent writers
+
+Appending is read-the-head-then-chain-to-it, so the read and the write must be
+atomic with respect to other writers. Two agents that both chain to entry 5
+produce two entry 6s, and `verify` then reports tampering that nobody did —
+a false alarm in an audit trail is worse than a missing one, because it
+teaches people to disbelieve the real alarm.
+
+Implementations must serialize appends across processes. The reference
+implementation takes an exclusive lock file next to the record
+(`record.jsonl.lock`), breaks a lock older than 10s as a crashed holder, and
+raises an error rather than writing unlocked if it cannot acquire one within
+15s. The scope is one machine — a record on a shared network filesystem is
+outside what this guarantees.
+
### The hash chain
Each entry commits to the previous one:
@@ -306,7 +347,10 @@ agent's **autonomy posture** without collecting anything new. `docket metrics`
derives it: the auto-approve / ask / deny split, the longest unattended run
(consecutive `allow` checks with no human stop between them), a proxy for
actions-per-intervention (checks ÷ asks+denies), amendment count, and a
-per-loop and per-channel breakdown. Every number is exact from the hash chain
+per-loop, per-channel, and per-agent breakdown. Because every entry carries a
+subject, the same numbers scope to one agent (`--by`) — the level-4 question
+is not "how autonomous are we?" but "how autonomous is *this* agent, on this
+branch?" Every number is exact from the hash chain
except proxies, which must be labeled as such — the record can measure actions
and their verdicts, not wall-clock or human intent.
diff --git a/src/cli.js b/src/cli.js
index 3502c0f..4925f75 100644
--- a/src/cli.js
+++ b/src/cli.js
@@ -42,12 +42,16 @@ ${bold('Iterating')}
${bold('The record')}
${cyan('record add')} [--did ..] [--saw ..] [--skipped ..] [--stopped ..] [--note ..]
- ${cyan('record log')} [loop] [--n 20]
+ ${cyan('record log')} [loop] [--n 20] [--by ]
${cyan('record verify')} verify the hash chain end to end
- ${cyan('metrics')} [--loop ] [--json]
+ ${cyan('metrics')} [--loop ] [--by ] [--json]
autonomy posture from the record: auto-approve vs
ask vs deny, longest unattended run, actions/intervention
+${dim('Every entry is stamped with who wrote it — agent, branch, worktree —')}
+${dim('so parallel agents stay separable at merge time. Override the guess')}
+${dim('with --by or DOCKET_BY; scope any read back with --by.')}
+
${bold('Portability')}
${cyan('compile')} [--target claude|agents|gemini|cursor|raw] [--loop ] [--index] [--write]
render loops into CLAUDE.md / AGENTS.md / Cursor rules
diff --git a/src/commands/check.js b/src/commands/check.js
index 2d5f9ae..87a548e 100644
--- a/src/commands/check.js
+++ b/src/commands/check.js
@@ -24,9 +24,10 @@ export function cmdCheck(argv) {
const loop = loadLoop(docketDir, loopName);
const result = checkWarrant(loop, action, target);
- // The check itself is evidence: record what was asked and what was answered.
+ // The check itself is evidence: record what was asked, what was answered,
+ // and who asked — `--by` names the agent when the environment can't.
if (!flags['no-record']) {
- recordCheck(docketDir, loop.name, action, target, result, { via: 'cli' });
+ recordCheck(docketDir, loop.name, action, target, result, { via: 'cli' }, { by: flags.by });
}
const style = VERDICT_STYLE[result.verdict];
diff --git a/src/commands/hook.js b/src/commands/hook.js
index d435383..a06b68a 100644
--- a/src/commands/hook.js
+++ b/src/commands/hook.js
@@ -163,7 +163,17 @@ export async function cmdHook(argv) {
emitDecision('ask', `docket loop "${loop.name}" (${result.rule}): ${result.reason}`);
}
try {
- recordCheck(docketDir, loop.name, action, target, result, { via: 'hook', tool: toolName });
+ // The harness hands us the session id — the one attribution docket never
+ // has to guess. Two agents in two worktrees become two subjects at merge.
+ recordCheck(
+ docketDir,
+ loop.name,
+ action,
+ target,
+ result,
+ { via: 'hook', tool: toolName },
+ { by: flags.by, session: event.session_id, cwd: startDir }
+ );
} catch (err) {
console.error(`docket hook: decision emitted but record append failed — ${err.message}`);
}
diff --git a/src/commands/init.js b/src/commands/init.js
index 15462d3..814bd82 100644
--- a/src/commands/init.js
+++ b/src/commands/init.js
@@ -8,6 +8,10 @@ const GITIGNORE_HINT = `# Docket keeps everything in plain files on purpose —
# If a loop's Memory section holds things you don't want in git, move the
# loop here and ignore it explicitly, e.g.:
# loops/private-*.loop.md
+#
+# One exception worth ignoring: record.jsonl.lock is a transient lock held
+# while an entry is appended (so parallel agents can't break the chain).
+# It is deleted on release and should never be committed.
`;
export function cmdInit(argv) {
diff --git a/src/commands/mcp.js b/src/commands/mcp.js
index b22b400..49ee01d 100644
--- a/src/commands/mcp.js
+++ b/src/commands/mcp.js
@@ -3,6 +3,7 @@
// Zero dependencies — the protocol surface we need is small.
import readline from 'node:readline';
+import path from 'node:path';
import { parseArgs } from '../lib/args.js';
import { requireDocketDir, listLoops, loadLoop, loopExists, loopNames, ACTIONS } from '../lib/loop.js';
import { checkWarrant } from '../lib/warrant.js';
@@ -87,7 +88,10 @@ function textResult(text, isError = false) {
return { content: [{ type: 'text', text }], ...(isError ? { isError: true } : {}) };
}
-export function handleToolCall(docketDir, name, args = {}) {
+// `actor` carries the server's attribution hint ({ by, cwd }) into every write.
+// An MCP host often spawns the server with cwd `/`, so the project dir — not
+// the process cwd — is what tells us the branch and worktree.
+export function handleToolCall(docketDir, name, args = {}, actor = {}) {
switch (name) {
case 'docket_list_loops': {
const loops = listLoops(docketDir);
@@ -129,7 +133,7 @@ export function handleToolCall(docketDir, name, args = {}) {
case 'docket_warrant_check': {
const loop = loadLoop(docketDir, args.loop);
const result = checkWarrant(loop, args.action, args.target);
- recordCheck(docketDir, loop.name, args.action, args.target, result, { via: 'mcp' });
+ recordCheck(docketDir, loop.name, args.action, args.target, result, { via: 'mcp' }, actor);
const instruction = {
allow: 'Proceed.',
ask: 'STOP. Do not do this yet — tell the human what you want to do and why, and wait for approval.',
@@ -153,7 +157,11 @@ export function handleToolCall(docketDir, name, args = {}) {
if (!Object.keys(fields).length) {
return textResult('a record entry needs at least one of: saw, did, skipped, stopped, note', true);
}
- const entry = appendRecord(docketDir, { loop: args.loop, kind: 'note', via: 'mcp', ...fields });
+ const entry = appendRecord(
+ docketDir,
+ { loop: args.loop, kind: 'note', via: 'mcp', ...fields },
+ actor
+ );
return textResult(`record #${entry.seq} appended (${entry.hash.slice(0, 23)}…)`);
}
default:
@@ -175,6 +183,9 @@ export function cmdMcp(argv = []) {
} catch (err) {
startupError = `${err.message} (searched upward from ${startDir}; pass --dir or set DOCKET_DIR)`;
}
+ // Name the client in the record: `--by cursor` in the MCP config is the one
+ // place a host that sets no env signal can still identify itself.
+ const actor = { by: flags.by, cwd: docketDir ? path.dirname(docketDir) : startDir };
const rl = readline.createInterface({ input: process.stdin, terminal: false });
const send = (msg) => process.stdout.write(JSON.stringify(msg) + '\n');
@@ -215,7 +226,7 @@ export function cmdMcp(argv = []) {
reply(textResult(startupError, true));
break;
}
- reply(handleToolCall(docketDir, params?.name, params?.arguments ?? {}));
+ reply(handleToolCall(docketDir, params?.name, params?.arguments ?? {}, actor));
break;
default:
fail(-32601, `method not found: ${method}`);
diff --git a/src/commands/metrics.js b/src/commands/metrics.js
index f6d149c..aa7bb2e 100644
--- a/src/commands/metrics.js
+++ b/src/commands/metrics.js
@@ -28,18 +28,27 @@ export function cmdMetrics(argv) {
}
const entries = readRecords(docketDir);
- const m = computeMetrics(entries, { loop: flags.loop ? String(flags.loop) : undefined });
+ const m = computeMetrics(entries, {
+ loop: flags.loop ? String(flags.loop) : undefined,
+ by: typeof flags.by === 'string' ? flags.by : undefined,
+ });
if (flags.json) {
console.log(JSON.stringify(m, null, 2));
return 0;
}
- const scope = flags.loop ? ` · loop ${cyan(String(flags.loop))}` : '';
+ const scope =
+ (flags.loop ? ` · loop ${cyan(String(flags.loop))}` : '') +
+ (typeof flags.by === 'string' ? ` · by ${cyan(flags.by)}` : '');
console.log(`${bold('docket metrics')}${scope} ${dim(`· ${recordFile(docketDir)}`)}`);
if (!m.checks) {
- console.log(dim('\nno warrant checks recorded yet — the numbers appear once the agent starts checking.'));
+ const why =
+ typeof flags.by === 'string'
+ ? `\nno warrant checks recorded by "${flags.by}" — check \`docket metrics\` for who has been writing.`
+ : '\nno warrant checks recorded yet — the numbers appear once the agent starts checking.';
+ console.log(dim(why));
return 0;
}
@@ -62,6 +71,20 @@ export function cmdMetrics(argv) {
}
}
+ // Only worth a section when the record has more than one subject: with a
+ // single agent this is a row that says what the header already said.
+ const actorKeys = Object.keys(m.byActor);
+ if (actorKeys.length > 1) {
+ console.log(`\n${bold('By agent')}`);
+ for (const [who, b] of Object.entries(m.byActor).sort((a, c) => c[1].checks - a[1].checks)) {
+ const where = b.branches.length ? ` ${dim(`· ${b.branches.join(', ')}`)}` : '';
+ console.log(
+ ` ${cyan(who.padEnd(20))} ${String(b.checks).padStart(4)} checks ${dim(`allow ${b.allow} · ask ${b.ask} · deny ${b.deny}`)}${where}`
+ );
+ }
+ console.log(dim(' scope to one with --by · attribution is self-reported, and hash-chained once written'));
+ }
+
const chans = Object.entries(m.byChannel).map(([k, v]) => `${k} ${v}`).join(' · ');
console.log(`\n${bold('By channel')} ${dim(chans)}`);
console.log(dim('\nEvery number is exact from the hash chain except the labeled proxy.'));
diff --git a/src/commands/record.js b/src/commands/record.js
index fa44c4f..1c4418a 100644
--- a/src/commands/record.js
+++ b/src/commands/record.js
@@ -9,15 +9,24 @@ import {
} from '../lib/record.js';
import { bold, cyan, dim, green, red, VERDICT_STYLE } from '../lib/ui.js';
+// Who wrote it, appended dim so it never crowds out what was written.
+// Entries predating attribution simply have nothing to show — the log stays
+// readable across the whole history of a project.
+function attribution(e) {
+ if (!e.by) return '';
+ const where = e.worktree ? `${e.worktree}:${e.branch ?? '?'}` : e.branch;
+ return dim(` ← ${e.by}${where ? ` @ ${where}` : ''}`);
+}
+
function formatEntry(e) {
- const ts = dim(e.ts.replace('T', ' ').replace(/\.\d+Z$/, 'Z'));
+ const ts = dim(String(e.ts ?? '').replace('T', ' ').replace(/\.\d+Z$/, 'Z'));
const head = `${dim(`#${e.seq}`)} ${ts} ${cyan(e.loop)}`;
if (e.kind === 'check') {
const style = VERDICT_STYLE[e.verdict] ?? { color: (s) => s, badge: e.verdict };
- return `${head} ${style.color(style.badge.toLowerCase())} ${e.action} → "${e.target}" ${dim(`(${e.rule})`)}`;
+ return `${head} ${style.color(style.badge.toLowerCase())} ${e.action} → "${e.target}" ${dim(`(${e.rule})`)}${attribution(e)}`;
}
if (e.kind === 'amend') {
- return `${head} amended warrant: ${e.action} now covers "${e.added}" ${dim(`(after ${e.asks} asks)`)}`;
+ return `${head} amended warrant: ${e.action} now covers "${e.added}" ${dim(`(after ${e.asks} asks)`)}${attribution(e)}`;
}
const parts = [];
if (e.saw) parts.push(`saw: ${e.saw}`);
@@ -25,7 +34,7 @@ function formatEntry(e) {
if (e.skipped) parts.push(`skipped: ${e.skipped}`);
if (e.stopped) parts.push(`stopped: ${e.stopped}`);
if (e.note) parts.push(e.note);
- return `${head} ${parts.join(' · ') || dim('(empty note)')}`;
+ return `${head} ${parts.join(' · ') || dim('(empty note)')}${attribution(e)}`;
}
export function cmdRecord(argv) {
@@ -48,7 +57,7 @@ function recordAdd(argv) {
const loopName = positional[0];
if (!loopName) {
console.error(
- 'usage: docket record add [--saw ..] [--did ..] [--skipped ..] [--stopped ..] [--note ..]'
+ 'usage: docket record add [--saw ..] [--did ..] [--skipped ..] [--stopped ..] [--note ..] [--by ]'
);
return 1;
}
@@ -75,8 +84,15 @@ function recordAdd(argv) {
console.error('docket: a record entry with nothing in it proves nothing — pass --saw/--did/--skipped/--stopped/--note');
return 1;
}
- const entry = appendRecord(docketDir, { loop: loopName, kind: 'note', via: 'cli', ...fields });
- console.log(green('✓') + ` record #${entry.seq} ${dim(entry.hash.slice(0, 23) + '…')}`);
+ const entry = appendRecord(
+ docketDir,
+ { loop: loopName, kind: 'note', via: 'cli', ...fields },
+ { by: flags.by }
+ );
+ console.log(
+ green('✓') +
+ ` record #${entry.seq} ${dim(entry.hash.slice(0, 23) + '…')} ${dim(`by ${entry.by}`)}`
+ );
return 0;
}
@@ -84,15 +100,24 @@ function recordLog(argv) {
const { flags, positional } = parseArgs(argv);
const docketDir = requireDocketDir();
const loopName = positional[0];
+ // A mistyped --n must not silently print the whole log: "20 lines" and
+ // "everything since March" are very different answers to the same command.
const n = Number(flags.n ?? 20);
+ if (!Number.isFinite(n) || n <= 0) {
+ console.error(`docket: --n must be a positive number (got "${flags.n}")`);
+ return 1;
+ }
+ const by = typeof flags.by === 'string' ? flags.by : null;
let entries = readRecords(docketDir);
if (loopName) entries = entries.filter((e) => e.loop === loopName);
+ if (by) entries = entries.filter((e) => e.by === by);
if (!entries.length) {
- console.log('no record entries yet');
+ console.log(by ? `no record entries by "${by}"` : 'no record entries yet');
return 0;
}
for (const e of entries.slice(-n)) console.log(formatEntry(e));
- console.log(dim(`\n${entries.length} total · file: ${recordFile(docketDir)}`));
+ const scope = by ? ` by ${by}` : '';
+ console.log(dim(`\n${entries.length} total${scope} · file: ${recordFile(docketDir)}`));
return 0;
}
diff --git a/src/lib/actor.js b/src/lib/actor.js
new file mode 100644
index 0000000..c2279be
--- /dev/null
+++ b/src/lib/actor.js
@@ -0,0 +1,125 @@
+// Who wrote this record entry?
+//
+// When one human ran one agent, the record's `loop` field was enough. At
+// autonomy levels 4–5 that stops being true: several agents work the same
+// repo in parallel worktrees, and at merge time "what was this allowed to do,
+// and what did it do?" needs a subject. That subject is the `by` field.
+//
+// HONESTY NOTE, and it matters: `by` is SELF-REPORTED. It is evidence about
+// provenance, not an authentication claim — a process that can append to the
+// record can append any `by` it likes. What the hash chain guarantees is that
+// the attribution cannot be changed *after the fact* without breaking the
+// chain: whoever wrote the entry is stuck with what they claimed at the time.
+// That is the same promise as the rest of the record, stated plainly.
+
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+
+// Best-effort agent detection from the harness's own environment. First match
+// wins. These are signals the tools set for themselves — we only read them.
+// Adding a row here is the intended way to teach docket a new agent; a wrong
+// guess is a mislabeled entry, so keep each signal specific to one tool.
+export const AGENT_SIGNALS = [
+ ['claude-code', (e) => e.CLAUDECODE || e.CLAUDE_CODE],
+ ['cursor', (e) => e.CURSOR_AGENT || e.CURSOR_TRACE_ID],
+ ['gemini-cli', (e) => e.GEMINI_CLI],
+ ['codex', (e) => e.CODEX_SANDBOX || e.CODEX_HOME],
+ ['aider', (e) => e.AIDER_MODEL],
+ ['github-actions', (e) => e.GITHUB_ACTIONS],
+];
+
+const MAX_LEN = 64;
+
+// One field, one shape: short, single-line, greppable. A record you can't
+// `grep` is a database, and this is deliberately not one.
+export function normalizeActor(value) {
+ if (typeof value !== 'string') return null;
+ const clean = value.replace(/\s+/g, ' ').trim().slice(0, MAX_LEN);
+ return clean || null;
+}
+
+export function detectAgent(env = process.env) {
+ for (const [name, signal] of AGENT_SIGNALS) {
+ if (signal(env)) return name;
+ }
+ return null;
+}
+
+function username() {
+ try {
+ return os.userInfo().username;
+ } catch {
+ return 'unknown';
+ }
+}
+
+// Find the git directory for `cwd`, following the `gitdir:` pointer that a
+// linked worktree leaves in its `.git` FILE. Returns null outside a repo.
+function findGitDir(cwd) {
+ let dir = path.resolve(cwd);
+ for (;;) {
+ const dotGit = path.join(dir, '.git');
+ try {
+ const stat = fs.statSync(dotGit);
+ if (stat.isDirectory()) return dotGit;
+ if (stat.isFile()) {
+ const m = fs.readFileSync(dotGit, 'utf8').match(/^gitdir:\s*(.+)$/m);
+ if (m) return path.resolve(dir, m[1].trim());
+ return null;
+ }
+ } catch {
+ // not here — keep walking up
+ }
+ const parent = path.dirname(dir);
+ if (parent === dir) return null;
+ dir = parent;
+ }
+}
+
+// Resolving the git dir walks the tree; re-reading HEAD is two syscalls. Cache
+// the walk, never the branch — a long-lived MCP server outlives a checkout.
+const gitDirCache = new Map();
+
+export function gitContext(cwd = process.cwd()) {
+ const key = path.resolve(cwd);
+ if (!gitDirCache.has(key)) gitDirCache.set(key, findGitDir(key));
+ const gitDir = gitDirCache.get(key);
+ if (!gitDir) return {};
+ const out = {};
+ try {
+ const head = fs.readFileSync(path.join(gitDir, 'HEAD'), 'utf8').trim();
+ const ref = head.match(/^ref:\s*refs\/heads\/(.+)$/);
+ // Detached HEAD is still an answer — the short sha says where you were.
+ out.branch = ref ? ref[1].trim() : head.slice(0, 12);
+ } catch {
+ // a repo mid-clone or mid-rebase has no readable HEAD; attribution
+ // degrades to just `by` rather than failing the write
+ }
+ // A linked worktree lives at /worktrees/; the main checkout
+ // has no worktree name to report, and inventing one would be noise.
+ const parts = gitDir.split(path.sep);
+ const i = parts.lastIndexOf('worktrees');
+ if (i !== -1 && parts[i + 1]) out.worktree = parts[i + 1];
+ return out;
+}
+
+// The attribution fields for one record entry. Precedence is explicit intent
+// first: `--by` beats the environment, the environment beats a guess, and a
+// guess beats nothing. Every field is omitted when it has no honest value —
+// a record should not carry placeholders that read like facts.
+export function resolveActor({ by, session, env = process.env, cwd = process.cwd() } = {}) {
+ const actor = {
+ by:
+ normalizeActor(by) ||
+ normalizeActor(env.DOCKET_BY) ||
+ detectAgent(env) ||
+ `user:${username()}`,
+ };
+ const git = gitContext(cwd);
+ if (git.branch) actor.branch = git.branch;
+ if (git.worktree) actor.worktree = git.worktree;
+ const sess = normalizeActor(session) || normalizeActor(env.DOCKET_SESSION);
+ if (sess) actor.session = sess;
+ return actor;
+}
diff --git a/src/lib/metrics.js b/src/lib/metrics.js
index 47b290b..27ab02e 100644
--- a/src/lib/metrics.js
+++ b/src/lib/metrics.js
@@ -11,8 +11,12 @@
// record can't measure directly. They're marked so nobody reads more into
// them than the data supports.
-export function computeMetrics(entries, { loop } = {}) {
- const scoped = loop ? entries.filter((e) => e.loop === loop) : entries;
+export function computeMetrics(entries, { loop, by } = {}) {
+ let scoped = entries;
+ if (loop) scoped = scoped.filter((e) => e.loop === loop);
+ // Scoping by agent answers the level-4 question directly: not "how
+ // autonomous are we?" but "how autonomous is *this* agent, on this branch?"
+ if (by) scoped = scoped.filter((e) => e.by === by);
const checks = scoped.filter((e) => e.kind === 'check');
const notes = scoped.filter((e) => e.kind === 'note');
const amends = scoped.filter((e) => e.kind === 'amend');
@@ -49,6 +53,18 @@ export function computeMetrics(entries, { loop } = {}) {
byChannel[via] = (byChannel[via] || 0) + 1;
}
+ // Per-agent posture. Entries written before attribution existed have no
+ // `by`, and are counted as `unattributed` rather than guessed at — the
+ // record says what it knows and nothing more.
+ const byActor = {};
+ for (const c of checks) {
+ const who = c.by || 'unattributed';
+ const b = (byActor[who] ??= { checks: 0, allow: 0, ask: 0, deny: 0, branches: [] });
+ b.checks++;
+ if (c.verdict in b) b[c.verdict]++;
+ if (c.branch && !b.branches.includes(c.branch)) b.branches.push(c.branch);
+ }
+
const rate = (n) => (total ? n / total : 0);
const ts = scoped.map((e) => e.ts).filter(Boolean).sort();
@@ -69,6 +85,7 @@ export function computeMetrics(entries, { loop } = {}) {
work: { notes: notes.length, withStop: notes.filter((n) => n.stopped).length },
byLoop,
byChannel,
+ byActor,
span: ts.length ? { first: ts[0], last: ts[ts.length - 1] } : null,
};
}
diff --git a/src/lib/record.js b/src/lib/record.js
index c1d2dbd..26bd247 100644
--- a/src/lib/record.js
+++ b/src/lib/record.js
@@ -12,6 +12,7 @@
import crypto from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';
+import { resolveActor } from './actor.js';
export const GENESIS = 'GENESIS';
@@ -19,6 +20,10 @@ export const GENESIS = 'GENESIS';
// filters through collectRecordFields so the audit schema has one owner.
export const RECORD_FIELDS = ['saw', 'did', 'skipped', 'stopped', 'note'];
+// Who wrote the entry — stamped by appendRecord, never by a caller's hand.
+// See lib/actor.js for how each is resolved and why `by` is self-reported.
+export const ATTRIBUTION_FIELDS = ['by', 'branch', 'worktree', 'session'];
+
export function collectRecordFields(source) {
const fields = {};
const dropped = [];
@@ -100,32 +105,118 @@ export function readLastRecord(docketDir) {
}
}
-export function appendRecord(docketDir, fields) {
- const last = readLastRecord(docketDir);
- const prev = last ? last.hash : GENESIS;
- const entry = {
- seq: last ? last.seq + 1 : 1,
- ts: new Date().toISOString(),
- ...fields,
- prev,
- };
- entry.hash = hashEntry(entry, prev);
- fs.appendFileSync(recordFile(docketDir), JSON.stringify(entry) + '\n');
- return entry;
+// Appending is read-then-write — read the head, chain to it, append — and that
+// pair must be ATOMIC. Two agents working the same repo in parallel would
+// otherwise both read entry 5 and both write entry 6, and `verify` would
+// report "an entry was removed, added, or reordered": a tamper alarm raised by
+// honest concurrent work. A false alarm in an audit trail is not a small bug;
+// it teaches people to ignore the alarm.
+//
+// The lock is an exclusively-created file next to the record. Zero
+// dependencies, works across processes and worktrees on one machine (which is
+// the multi-agent case; a record shared over NFS is out of scope and says so).
+export class RecordLockError extends Error {}
+
+const LOCK_STALE_MS = 10_000; // a holder older than this crashed mid-write
+const LOCK_WAIT_MS = 15_000; // > STALE, so a stale lock is always broken, never waited out
+
+function lockFile(docketDir) {
+ return recordFile(docketDir) + '.lock';
+}
+
+// Sync sleep with no dependencies and no busy-wait: appendRecord is sync
+// everywhere it's called (CLI, hook, MCP handler), and making it async would
+// change every writer's signature for a millisecond of contention.
+function sleepSync(ms) {
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
+}
+
+export function withRecordLock(docketDir, fn, { waitMs = LOCK_WAIT_MS, staleMs = LOCK_STALE_MS } = {}) {
+ const lock = lockFile(docketDir);
+ const deadline = Date.now() + waitMs;
+ let fd;
+ for (;;) {
+ try {
+ fd = fs.openSync(lock, 'wx');
+ break;
+ } catch (err) {
+ if (err.code !== 'EEXIST') throw err;
+ let age;
+ try {
+ age = Date.now() - fs.statSync(lock).mtimeMs;
+ } catch {
+ continue; // the holder released it between our open and our stat
+ }
+ if (age > staleMs) {
+ // The holder died mid-write. Break the lock rather than block the
+ // record forever — evidence that can't be written isn't evidence.
+ try {
+ fs.unlinkSync(lock);
+ } catch {
+ /* someone else broke it first */
+ }
+ continue;
+ }
+ if (Date.now() >= deadline) {
+ throw new RecordLockError(
+ `could not lock ${lock} within ${waitMs}ms — another process is holding it. ` +
+ 'If nothing else is running, delete that file.'
+ );
+ }
+ // Jittered backoff: without it, N waiters wake together and one wins N
+ // times in a row while the rest keep colliding.
+ sleepSync(2 + Math.floor(Math.random() * 8));
+ }
+ }
+ try {
+ return fn();
+ } finally {
+ fs.closeSync(fd);
+ try {
+ fs.unlinkSync(lock);
+ } catch {
+ /* already broken as stale — the next writer creates it fresh */
+ }
+ }
+}
+
+// `actor` is the attribution hint from the caller ({ by, session }); every
+// writer passes it and none of them can forget to, because stamping happens
+// here. Attribution is part of the hashed entry, so it is as tamper-evident
+// as the verdict it sits next to.
+export function appendRecord(docketDir, fields, actor = {}) {
+ return withRecordLock(docketDir, () => {
+ const last = readLastRecord(docketDir);
+ const prev = last ? last.hash : GENESIS;
+ const entry = {
+ seq: last ? last.seq + 1 : 1,
+ ts: new Date().toISOString(),
+ ...fields,
+ ...resolveActor(actor),
+ prev,
+ };
+ entry.hash = hashEntry(entry, prev);
+ fs.appendFileSync(recordFile(docketDir), JSON.stringify(entry) + '\n');
+ return entry;
+ });
}
// One writer for warrant-check evidence, whoever asked (CLI or MCP) —
// the audit schema for checks is defined here and nowhere else.
-export function recordCheck(docketDir, loopName, action, target, result, extra = {}) {
- return appendRecord(docketDir, {
- loop: loopName,
- kind: 'check',
- action,
- target,
- verdict: result.verdict,
- rule: result.rule,
- ...extra,
- });
+export function recordCheck(docketDir, loopName, action, target, result, extra = {}, actor = {}) {
+ return appendRecord(
+ docketDir,
+ {
+ loop: loopName,
+ kind: 'check',
+ action,
+ target,
+ verdict: result.verdict,
+ rule: result.rule,
+ ...extra,
+ },
+ actor
+ );
}
// Returns { ok, count, head, brokenAt, problem }.
diff --git a/test/attribution.test.js b/test/attribution.test.js
new file mode 100644
index 0000000..4b9c533
--- /dev/null
+++ b/test/attribution.test.js
@@ -0,0 +1,163 @@
+// Per-agent attribution: the `by` field, and everything that reads it back.
+//
+// The property that matters is not "we write a string" — it's that the string
+// is resolved from explicit intent first, omitted when it would be a guess
+// dressed as a fact, and covered by the hash chain once written.
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { execFileSync } from 'node:child_process';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { resolveActor, normalizeActor, detectAgent, gitContext } from '../src/lib/actor.js';
+import { appendRecord, readRecords, verifyRecord, recordFile } from '../src/lib/record.js';
+import { computeMetrics } from '../src/lib/metrics.js';
+
+const BIN = new URL('../bin/docket.js', import.meta.url).pathname;
+const ENV = { ...process.env, NO_COLOR: '1', FORCE_COLOR: '0' };
+
+function tmpDir() {
+ return fs.mkdtempSync(path.join(os.tmpdir(), 'docket-attr-'));
+}
+
+// A bare env: the host's real CLAUDECODE/CI vars must not leak into a test
+// that is asserting what docket infers from an environment.
+const BARE = { PATH: process.env.PATH };
+
+test('--by beats the environment, the environment beats a guess', () => {
+ const cwd = tmpDir();
+ assert.equal(resolveActor({ by: 'explicit', env: { ...BARE, DOCKET_BY: 'env' }, cwd }).by, 'explicit');
+ assert.equal(resolveActor({ env: { ...BARE, DOCKET_BY: 'env', CLAUDECODE: '1' }, cwd }).by, 'env');
+ assert.equal(resolveActor({ env: { ...BARE, CLAUDECODE: '1' }, cwd }).by, 'claude-code');
+ // Nothing to go on: fall back to the human, and say so in the shape.
+ assert.match(resolveActor({ env: BARE, cwd }).by, /^user:/);
+});
+
+test('agent signals map to stable ids, first match wins', () => {
+ assert.equal(detectAgent({ CURSOR_TRACE_ID: 'abc' }), 'cursor');
+ assert.equal(detectAgent({ GEMINI_CLI: '1' }), 'gemini-cli');
+ assert.equal(detectAgent({ GITHUB_ACTIONS: 'true' }), 'github-actions');
+ assert.equal(detectAgent({}), null);
+ assert.equal(detectAgent({ CLAUDECODE: '1', CURSOR_TRACE_ID: 'x' }), 'claude-code');
+});
+
+test('actor names are normalized to one short greppable line', () => {
+ assert.equal(normalizeActor(' claude code \n'), 'claude code');
+ assert.equal(normalizeActor(''), null);
+ assert.equal(normalizeActor(' '), null);
+ assert.equal(normalizeActor(undefined), null);
+ assert.equal(normalizeActor('x'.repeat(200)).length, 64);
+});
+
+test('an empty --by falls through instead of writing a blank subject', () => {
+ const cwd = tmpDir();
+ const actor = resolveActor({ by: ' ', env: { ...BARE, DOCKET_BY: 'fallback' }, cwd });
+ assert.equal(actor.by, 'fallback');
+});
+
+test('git context reports the branch, and names a linked worktree', () => {
+ const dir = tmpDir();
+ const git = (cwd, ...args) =>
+ execFileSync('git', args, { cwd, env: { ...process.env, GIT_CONFIG_GLOBAL: '/dev/null' } });
+ git(dir, 'init', '-q', '-b', 'trunk', '.');
+ assert.equal(gitContext(dir).branch, 'trunk');
+ assert.equal(gitContext(dir).worktree, undefined, 'the main checkout is not a named worktree');
+
+ fs.writeFileSync(path.join(dir, 'f.txt'), 'x');
+ git(dir, 'add', '-A');
+ git(dir, '-c', 'user.email=t@t', '-c', 'user.name=t', 'commit', '-qm', 'init');
+ const wt = path.join(dir, '..', path.basename(dir) + '-wt');
+ git(dir, 'worktree', 'add', '-q', wt, '-b', 'side');
+ assert.equal(gitContext(wt).branch, 'side');
+ assert.equal(gitContext(wt).worktree, path.basename(wt), 'linked worktrees are named');
+});
+
+test('outside a repo, attribution degrades to just `by`', () => {
+ const dir = tmpDir();
+ const actor = resolveActor({ by: 'agent', env: BARE, cwd: dir });
+ assert.equal(actor.by, 'agent');
+ assert.equal('branch' in actor, false, 'no placeholder branch');
+ assert.equal('worktree' in actor, false);
+});
+
+test('every entry is stamped, and the stamp is part of the hash', () => {
+ const dir = tmpDir();
+ const entry = appendRecord(dir, { loop: 'x', kind: 'note', did: 'work' }, { by: 'agent-a' });
+ assert.equal(entry.by, 'agent-a');
+
+ // Rewrite the attribution of a past entry: the chain must notice. An audit
+ // trail whose subject can be swapped afterward attributes nothing.
+ const lines = fs.readFileSync(recordFile(dir), 'utf8').trim().split('\n');
+ const forged = { ...JSON.parse(lines[0]), by: 'someone-else' };
+ fs.writeFileSync(recordFile(dir), JSON.stringify(forged) + '\n');
+ const result = verifyRecord(dir);
+ assert.equal(result.ok, false);
+ assert.match(result.problem, /modified after it was written/);
+});
+
+test('a session id rides along when the harness knows it', () => {
+ const dir = tmpDir();
+ const e = appendRecord(dir, { loop: 'x', kind: 'note', did: 'w' }, { by: 'a', session: 'sess-99' });
+ assert.equal(e.session, 'sess-99');
+ const bare = appendRecord(dir, { loop: 'x', kind: 'note', did: 'w' }, { by: 'a', env: {} });
+ assert.equal('session' in bare, false, 'no session, no field');
+});
+
+test('metrics break down by agent and scope to one', () => {
+ const entries = [
+ { loop: 'a', kind: 'check', verdict: 'allow', by: 'claude-code', branch: 'main' },
+ { loop: 'a', kind: 'check', verdict: 'allow', by: 'claude-code', branch: 'side' },
+ { loop: 'a', kind: 'check', verdict: 'ask', by: 'cursor', branch: 'main' },
+ { loop: 'a', kind: 'check', verdict: 'deny' }, // predates attribution
+ ];
+ const m = computeMetrics(entries);
+ assert.equal(m.byActor['claude-code'].checks, 2);
+ assert.deepEqual(m.byActor['claude-code'].branches, ['main', 'side']);
+ assert.equal(m.byActor.cursor.ask, 1);
+ assert.equal(m.byActor.unattributed.deny, 1, 'never guess a subject for old entries');
+
+ const scoped = computeMetrics(entries, { by: 'claude-code' });
+ assert.equal(scoped.checks, 2);
+ assert.equal(scoped.verdict.allow, 2);
+});
+
+test('end to end: two agents stay separable in the log and the metrics', () => {
+ const dir = tmpDir();
+ const run = (args, env = {}) =>
+ execFileSync('node', [BIN, ...args], { cwd: dir, env: { ...ENV, ...env }, encoding: 'utf8' });
+ run(['init']);
+ run(['new', 'deploy', '--template', 'prod-hotfix']);
+ run(['record', 'add', 'deploy', '--did', 'first pass', '--by', 'claude-code']);
+ run(['record', 'add', 'deploy', '--did', 'second pass', '--by', 'cursor']);
+ run(['record', 'add', 'deploy', '--did', 'third pass'], { DOCKET_BY: 'claude-code' });
+
+ const log = run(['record', 'log']);
+ assert.match(log, /← claude-code/);
+ assert.match(log, /← cursor/);
+
+ const filtered = run(['record', 'log', '--by', 'cursor']);
+ assert.match(filtered, /second pass/);
+ assert.doesNotMatch(filtered, /first pass/);
+ assert.match(filtered, /1 total by cursor/);
+
+ const entries = readRecords(path.join(dir, '.docket'));
+ assert.deepEqual(
+ entries.map((e) => e.by),
+ ['claude-code', 'cursor', 'claude-code']
+ );
+ assert.equal(verifyRecord(path.join(dir, '.docket')).ok, true);
+});
+
+test('record log rejects a mistyped --n instead of dumping everything', () => {
+ const dir = tmpDir();
+ const run = (args) =>
+ execFileSync('node', [BIN, ...args], { cwd: dir, env: ENV, encoding: 'utf8' });
+ run(['init']);
+ run(['new', 'deploy', '--template', 'prod-hotfix']);
+ for (let i = 0; i < 3; i++) run(['record', 'add', 'deploy', '--did', `entry ${i}`]);
+ assert.throws(
+ () => execFileSync('node', [BIN, 'record', 'log', '--n', 'abc'], { cwd: dir, env: ENV, stdio: 'pipe' }),
+ /--n must be a positive number/
+ );
+ assert.equal(run(['record', 'log', '--n', '2']).split('\n').filter((l) => l.startsWith('#')).length, 2);
+});
diff --git a/test/concurrency.test.js b/test/concurrency.test.js
new file mode 100644
index 0000000..5aa01e9
--- /dev/null
+++ b/test/concurrency.test.js
@@ -0,0 +1,133 @@
+// Parallel agents must not break the chain.
+//
+// Appending is read-the-head-then-write, and that pair has to be atomic. Two
+// agents in two worktrees would otherwise both chain to entry 5 and both write
+// entry 6 — and `verify` would report tampering that nobody did. A false
+// tamper alarm is worse than no alarm: it trains people to ignore the real one.
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { execFileSync, spawn } from 'node:child_process';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import {
+ appendRecord,
+ readRecords,
+ verifyRecord,
+ recordFile,
+ withRecordLock,
+ RecordLockError,
+} from '../src/lib/record.js';
+
+const BIN = new URL('../bin/docket.js', import.meta.url).pathname;
+const ENV = { ...process.env, NO_COLOR: '1', FORCE_COLOR: '0' };
+
+function tmpDir() {
+ return fs.mkdtempSync(path.join(os.tmpdir(), 'docket-conc-'));
+}
+
+// Genuinely concurrent: all children are spawned before any is awaited. A
+// loop of execFileSync would serialize them and test nothing.
+function runAllAtOnce(commands) {
+ return Promise.all(
+ commands.map(
+ ({ args, cwd, env }) =>
+ new Promise((resolve, reject) => {
+ const p = spawn('node', args, { cwd, env: { ...ENV, ...env }, stdio: 'ignore' });
+ p.on('error', reject);
+ p.on('close', resolve);
+ })
+ )
+ );
+}
+
+test('concurrent writers from separate processes keep the chain intact', async () => {
+ const dir = tmpDir();
+ const docketDir = path.join(dir, '.docket');
+ fs.mkdirSync(docketDir);
+ const writer = path.join(dir, 'writer.mjs');
+ const recordLib = new URL('../src/lib/record.js', import.meta.url).pathname;
+ fs.writeFileSync(
+ writer,
+ `import { appendRecord } from ${JSON.stringify(recordLib)};
+ const [dir, id] = process.argv.slice(2);
+ for (let i = 0; i < 12; i++) appendRecord(dir, { loop: 'x', kind: 'note', did: id + '-' + i }, { by: id });`
+ );
+
+ const AGENTS = 5;
+ await runAllAtOnce(
+ Array.from({ length: AGENTS }, (_, i) => ({ args: [writer, docketDir, `agent-${i}`] }))
+ );
+
+ const result = verifyRecord(docketDir);
+ assert.equal(result.ok, true, `chain broken: ${result.problem}`);
+ assert.equal(result.count, AGENTS * 12, 'every write landed — no entry lost to a lost race');
+
+ // Every agent's work is present and attributable.
+ const entries = readRecords(docketDir);
+ for (let i = 0; i < AGENTS; i++) {
+ assert.equal(entries.filter((e) => e.by === `agent-${i}`).length, 12);
+ }
+ // seq is dense and ordered — the property `verify` depends on.
+ assert.deepEqual(
+ entries.map((e) => e.seq),
+ entries.map((_, i) => i + 1)
+ );
+});
+
+test('the lock is released even when the write throws', () => {
+ const dir = tmpDir();
+ assert.throws(() => withRecordLock(dir, () => {
+ throw new Error('disk full');
+ }), /disk full/);
+ assert.equal(fs.existsSync(recordFile(dir) + '.lock'), false, 'a crashed write must not wedge the record');
+ // And the next writer proceeds normally.
+ assert.equal(appendRecord(dir, { loop: 'x', kind: 'note', did: 'after' }).seq, 1);
+});
+
+test('a stale lock from a dead process is broken, not waited out', () => {
+ const dir = tmpDir();
+ const lock = recordFile(dir) + '.lock';
+ fs.writeFileSync(lock, '');
+ // Backdate past the stale threshold: this is what a holder killed mid-write
+ // leaves behind. The record must not be wedged forever by a dead process.
+ const old = Date.now() - 60_000;
+ fs.utimesSync(lock, old / 1000, old / 1000);
+
+ const started = Date.now();
+ const entry = appendRecord(dir, { loop: 'x', kind: 'note', did: 'recovered' });
+ assert.equal(entry.seq, 1);
+ assert.ok(Date.now() - started < 5_000, 'breaking a stale lock should be immediate');
+ assert.equal(verifyRecord(dir).ok, true);
+});
+
+test('a live lock held past the deadline fails loudly, never silently', () => {
+ const dir = tmpDir();
+ const lock = recordFile(dir) + '.lock';
+ fs.writeFileSync(lock, '');
+ // Fresh mtime = a live holder. We refuse to wait forever, and we refuse to
+ // write unlocked: the caller hears about it rather than the chain breaking.
+ assert.throws(
+ () => withRecordLock(dir, () => 'never runs', { waitMs: 40 }),
+ (err) => err instanceof RecordLockError && /could not lock/.test(err.message)
+ );
+ fs.unlinkSync(lock);
+});
+
+test('end to end: parallel `docket check` calls leave a verifiable record', async () => {
+ const dir = tmpDir();
+ execFileSync('node', [BIN, 'init'], { cwd: dir, env: ENV });
+ execFileSync('node', [BIN, 'new', 'deploy', '--template', 'prod-hotfix'], { cwd: dir, env: ENV });
+
+ await runAllAtOnce(
+ Array.from({ length: 6 }, (_, i) => ({
+ args: [BIN, 'check', 'deploy', 'read', `log file ${i}`, '--quiet'],
+ cwd: dir,
+ env: { DOCKET_BY: `agent-${i}` },
+ }))
+ );
+
+ const docketDir = path.join(dir, '.docket');
+ assert.equal(verifyRecord(docketDir).ok, true);
+ assert.equal(readRecords(docketDir).length, 6);
+});