turnstamp 0.1.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,114 +1,139 @@
1
1
  # turnstamp
2
2
 
3
- Prove what your AI coding agent actually did.
3
+ Prove what your AI coding agent actually did, and which files a human touched.
4
4
 
5
- Your agent says it only changed three files. turnstamp lets you check. It keeps a
6
- tamper evident ledger of every turn: what the tree looked like, what each turn
7
- touched, and a hash chain that breaks the moment someone edits history.
5
+ Your agent says it changed three files. turnstamp tells you which files the agent
6
+ wrote, and flags every file a human changed after the agent said it was done.
8
7
 
9
8
  ```
10
- npx turnstamp init
11
- npx turnstamp stamp --turn 1 --tool claude
12
- npx turnstamp verify
9
+ npm install -g turnstamp
10
+ turnstamp install # wires up OpenCode and Claude Code
11
+ turnstamp verify
13
12
  ```
14
13
 
15
- ## Why
14
+ Works with **OpenCode** and **Claude Code**, using each tool's own hooks. No
15
+ filesystem watching and no guessing, because the agent reports each file it
16
+ touches at the moment it touches it.
16
17
 
17
- Coding agents are fast and confident and not always accurate about their own
18
- work. A diff shows you the end state of a file. It does not show you that your
19
- agent read `.env`, ran a script, or quietly rewrote a file two turns after it
20
- said it was done.
18
+ ## Why
21
19
 
22
- turnstamp records the sequence and makes the record hard to fake. Every entry
23
- carries the hash of the entry before it, so deleting or editing one line in the
24
- middle breaks every hash after it.
20
+ A diff shows the end state of a file. It does not tell you who wrote it, or
21
+ whether something changed after the agent finished.
25
22
 
26
- ## Commands
23
+ turnstamp records the agent's tool calls as they happen. Before the call it
24
+ hashes the files the call is about to touch, after the call it hashes them
25
+ again. That pair is the agent's own account of what it did, and it goes into a
26
+ hash chain that breaks the moment anyone edits history.
27
27
 
28
- | Command | What it does |
29
- | --- | --- |
30
- | `turnstamp init` | Creates `.turnstamp/ledger.jsonl` |
31
- | `turnstamp stamp` | Records the files that changed since the last stamp |
32
- | `turnstamp event --json '{...}'` | Records one agent event, for hooks |
33
- | `turnstamp verify` | Checks the hash chain and the files on disk |
34
- | `turnstamp log` | Reads the ledger back, optionally `--turn N` |
28
+ Anything the chain does not cover is not the agent. That is how a human edit is
29
+ told apart from an agent edit without guessing.
35
30
 
36
- ### stamp
31
+ ## Install
37
32
 
38
- ```bash
39
- turnstamp stamp --turn 3 --tool claude --action edit
33
+ ```
34
+ npm install -g turnstamp
35
+ cd your-project
36
+ turnstamp install
40
37
  ```
41
38
 
42
- It hashes the tree, compares it to the previous snapshot, and writes one entry
43
- per changed file plus a summary entry. The summary holds the digest of the whole
44
- tree, so you can tell two turns apart without walking every file again.
39
+ That writes:
45
40
 
46
- ### event
41
+ - `.opencode/plugins/turnstamp/index.js` for OpenCode
42
+ - `.claude/settings.json` hook entries for Claude Code, merged with whatever is already there
47
43
 
48
- For agent hooks and wrapper scripts. Feed it whatever your agent gives you.
44
+ Start a new agent session and the hooks are live. Use `turnstamp install opencode`
45
+ or `turnstamp install claude` to do just one. Add `--scope user` to install for
46
+ every project instead of just this one.
49
47
 
50
- ```bash
51
- turnstamp event --json '{"turn":3,"tool":"claude","action":"bash","target":"npm test","detail":"exit 0"}'
52
- turnstamp event --json '{"turn":3,"tool":"claude","action":"read","target":"src/auth.js"}'
53
- ```
48
+ ### What gets recorded
54
49
 
55
- ### verify
50
+ | Agent | Tool | Recorded as |
51
+ | --- | --- | --- |
52
+ | OpenCode | `write`, `edit`, `patch` | file event with before and after hashes |
53
+ | OpenCode | `shell` | call event with the command, since the files cannot be known up front |
54
+ | Claude Code | `Write`, `Edit`, `MultiEdit`, `NotebookEdit` | file event with before and after hashes |
55
+ | Claude Code | `Bash` | call event with the command |
56
56
 
57
- ```bash
58
- turnstamp verify
59
- ```
57
+ ## Commands
58
+
59
+ | Command | What it does |
60
+ | --- | --- |
61
+ | `turnstamp install [agent]` | Wire up the hooks, create the ledger |
62
+ | `turnstamp verify` | Check the chain and say who changed what |
63
+ | `turnstamp log` | Read the ledger back, optionally `--turn N` |
64
+ | `turnstamp stamp` | Manual snapshot, for when no hook is installed |
65
+ | `turnstamp event --json '{...}'` | Record one event from your own tooling |
66
+
67
+ ### verify
60
68
 
61
69
  ```
62
70
  ledger .turnstamp/ledger.jsonl
63
- entries 7
64
- head 7d5597b5559bff0a
71
+ entries 14
72
+ head 40af85f1ae3ce639
65
73
  chain intact
66
- files match the last stamp
74
+ files every file matches what the agent recorded
67
75
  ```
68
76
 
69
- Exit code is 0 when everything checks out and 1 when something does not. Use it
70
- as a CI gate or a pre commit hook.
77
+ Exit code is 0 when everything checks out and 1 when something does not, so it
78
+ works as a CI gate or a pre-commit hook.
71
79
 
72
- Two separate things get checked. The chain tells you whether the ledger itself
73
- was edited. The file check tells you whether anything was rewritten after it was
74
- stamped.
80
+ When a human edits a file the agent wrote:
75
81
 
76
82
  ```
77
- chain BROKEN
78
- entry 6: digest - content changed after it was stamped
79
- files changed after they were stamped
80
- src/a.js: stamped 1df3032e75cb45e5..., now 19b1f8a398e0bf0c...
83
+ chain intact
84
+ files changed with no agent call behind them
85
+ hello.txt: last written by write, now 2a688f29a91d0f54...
81
86
  ```
82
87
 
83
- ## What it does not do
88
+ When someone edits the ledger itself:
84
89
 
85
- It does not stop an agent from doing something. It records what happened so you
86
- can check afterwards. It also cannot prove anything against someone who deletes
87
- the whole ledger and starts over, which is why a sealed head matters and why the
88
- next version signs the head with a key you keep.
90
+ ```
91
+ chain BROKEN
92
+ entry 6: digest - content changed after it was stamped
93
+ ```
89
94
 
90
- It catches the common cases:
95
+ ## What it catches
91
96
 
92
97
  - a file rewritten after the agent said it was done
98
+ - an agent claiming a write that never landed on disk
93
99
  - an entry edited to hide a file
94
100
  - an entry deleted from the middle
95
- - a careful forger who fixes the digest but not the link to the next entry
101
+ - a careful forger who fixes one digest but not the link to the next entry
102
+
103
+ ## What it does not do
104
+
105
+ It does not stop an agent from doing something, it records what happened so you
106
+ can check afterwards. A shell command is recorded as a call, not as a list of
107
+ files, because there is no way to know what a command will touch before it runs.
108
+
109
+ It also cannot prove anything against someone who deletes the whole ledger and
110
+ starts over. Signing the head with a key is the next step, not something 0.1.0
111
+ does.
96
112
 
97
113
  ## Library
98
114
 
99
- The CLI is a thin wrapper. Everything is exported if you want it inside your own
100
- tooling.
115
+ The CLI is a thin wrapper. Everything is exported.
101
116
 
102
117
  ```js
103
118
  import { appendEvent, verifyEntries, readLedger, ledgerPath } from "turnstamp";
104
119
 
105
120
  const file = ledgerPath(process.cwd());
106
- appendEvent(file, { turn: 1, tool: "claude", action: "read", target: "src/app.js" });
121
+ appendEvent(file, {
122
+ actor: "agent",
123
+ kind: "file",
124
+ tool: "custom",
125
+ action: "write",
126
+ target: "src/app.js",
127
+ detail: "sha256 of the file",
128
+ });
107
129
 
108
130
  const report = verifyEntries(readLedger(file));
109
131
  console.log(report.ok, report.problems);
110
132
  ```
111
133
 
134
+ The OpenCode plugin lives at `turnstamp/opencode` if you would rather import it
135
+ directly than use the installer.
136
+
112
137
  ## Ledger format
113
138
 
114
139
  One JSON object per line in `.turnstamp/ledger.jsonl`. Fixed key order, so the
@@ -116,21 +141,27 @@ hash is stable across machines and Node versions.
116
141
 
117
142
  ```json
118
143
  {
119
- "schema": 1,
144
+ "schema": 2,
120
145
  "seq": 2,
121
- "at": "2026-11-16T13:42:59.123Z",
122
- "turn": 1,
123
- "tool": "claude",
146
+ "at": "2026-11-16T14:20:18.417Z",
147
+ "turn": null,
148
+ "actor": "opencode",
149
+ "kind": "file",
150
+ "session": "ses_abc",
151
+ "call": "call_def",
152
+ "tool": "write",
124
153
  "action": "write",
125
- "target": "src/app.js",
126
- "detail": "f51105f5972c...",
127
- "prev": "948bccbeadb7...",
128
- "chain": "3d1484ea99d5..."
154
+ "target": "hello.txt",
155
+ "before": "missing",
156
+ "detail": "40af85f1ae3ce639...",
157
+ "prev": "cab1073cf729ddf1...",
158
+ "chain": "8a1b9b0d0e6d0b4b..."
129
159
  }
130
160
  ```
131
161
 
132
162
  `prev` is the previous entry's `chain`. The first entry points at 64 zeroes.
133
- `detail` is the file's sha256 for a write, or free text for other events.
163
+ `detail` is the hash after the call, `before` is the hash before it. `missing`
164
+ means the file did not exist.
134
165
 
135
166
  Commit the ledger if you want other people to be able to check your work. It is
136
167
  a record, not a secret.
package/bin/turnstamp.js CHANGED
@@ -10,22 +10,23 @@ import {
10
10
  treeDigest,
11
11
  } from "../src/ledger.js";
12
12
  import { diffTrees, hashTree } from "../src/tree.js";
13
+ import { initLedger, installClaudeCode, installOpencode } from "../src/install.js";
13
14
 
14
15
  const HELP = `turnstamp - prove what your agent actually did
15
16
 
16
17
  Usage
17
18
  turnstamp init create the ledger for this project
18
- turnstamp stamp [options] record the current state of the tree
19
- turnstamp event --json '{...}' record one agent event (for hooks)
20
- turnstamp verify [--json] check the chain and the files on disk
19
+ turnstamp install [agent] wire up OpenCode and Claude Code hooks
20
+ turnstamp stamp [options] manual snapshot, when no hook is installed
21
+ turnstamp event --json '{...}' record one agent event yourself
22
+ turnstamp verify [--json] check the chain and who changed what
21
23
  turnstamp log [--turn N] [--json] read the ledger back
22
24
 
23
- Options for stamp
24
- --turn N which agent turn this belongs to, defaults to the next one
25
- --tool NAME tool name, defaults to manual
26
- --action NAME action name, defaults to snapshot
25
+ install takes: opencode, claude, both (default)
26
+ and --scope user to write to your home directory
27
27
 
28
- verify exits 1 when the chain is broken or a stamped file changed on disk.
28
+ verify exits 1 when the chain is broken or a file no longer matches what an
29
+ agent recorded.
29
30
  `;
30
31
 
31
32
  export function parseArgs(argv) {
@@ -84,14 +85,29 @@ function nextTurn(entries) {
84
85
  }
85
86
 
86
87
  function cmdInit() {
87
- const file = ledgerPath(process.cwd());
88
- if (fs.existsSync(file)) {
89
- console.log("ledger already exists");
90
- return 0;
88
+ const file = initLedger(process.cwd());
89
+ console.log(`ready ${path.relative(process.cwd(), file)}`);
90
+ return 0;
91
+ }
92
+
93
+ function cmdInstall(args) {
94
+ const which = args._[0] || "both";
95
+ const scope = args.scope === "user" ? "user" : "project";
96
+ const cwd = process.cwd();
97
+
98
+ if (which === "opencode" || which === "both") {
99
+ const result = installOpencode(scope, cwd);
100
+ console.log(`opencode plugin written to ${result.dir}`);
101
+ }
102
+
103
+ if (which === "claude" || which === "both") {
104
+ const result = installClaudeCode(scope, cwd);
105
+ console.log(`claude code hooks merged into ${result.file}`);
91
106
  }
92
- fs.mkdirSync(path.dirname(file), { recursive: true });
93
- fs.writeFileSync(file, "", "utf8");
94
- console.log(`created ${path.relative(process.cwd(), file)}`);
107
+
108
+ const file = initLedger(cwd);
109
+ console.log(`ledger ready at ${path.relative(cwd, file)}`);
110
+ console.log("restart the agent, or start a new session, to pick this up");
95
111
  return 0;
96
112
  }
97
113
 
@@ -117,6 +133,8 @@ function cmdStamp(args) {
117
133
  const detail = now.get(target) ?? "missing";
118
134
  appendEvent(file, {
119
135
  turn,
136
+ actor: "agent",
137
+ kind: "file",
120
138
  tool,
121
139
  action: detail === "missing" ? "delete" : "write",
122
140
  target,
@@ -126,6 +144,8 @@ function cmdStamp(args) {
126
144
 
127
145
  const summary = appendEvent(file, {
128
146
  turn,
147
+ actor: "agent",
148
+ kind: "call",
129
149
  tool,
130
150
  action,
131
151
  target: null,
@@ -175,11 +195,12 @@ function cmdVerify(args) {
175
195
  }
176
196
 
177
197
  if (report.drift.length === 0) {
178
- console.log("files match the last stamp");
198
+ console.log("files every file matches what the agent recorded");
179
199
  } else {
180
- console.log("files changed after they were stamped");
200
+ console.log("files changed with no agent call behind them");
181
201
  for (const item of report.drift) {
182
- console.log(` ${item.target}: stamped ${short(item.stamped)}, now ${short(item.current)}`);
202
+ const by = item.tool ? `last written by ${item.tool}` : "never seen by an agent";
203
+ console.log(` ${item.target}: ${by}, now ${short(item.current)}`);
183
204
  }
184
205
  }
185
206
 
@@ -244,6 +265,8 @@ function main(argv) {
244
265
  switch (command) {
245
266
  case "init":
246
267
  return cmdInit();
268
+ case "install":
269
+ return cmdInstall(args);
247
270
  case "stamp":
248
271
  return cmdStamp(args);
249
272
  case "event":
@@ -0,0 +1,173 @@
1
+ #!/usr/bin/env node
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+
5
+ import { appendEvent, ledgerPath } from "../src/ledger.js";
6
+ import { normalizeTarget } from "../src/events.js";
7
+ import { isFileTool, readState, shellCommand, toolPaths } from "../src/tools.js";
8
+
9
+ // Claude Code hook.
10
+ //
11
+ // Reads the event JSON on stdin and appends one entry. It runs inline on every
12
+ // tool call, so it does no tree walking and makes no network calls.
13
+ //
14
+ // Register it for PreToolUse and PostToolUse on the file tools, and for Bash so
15
+ // shell commands show up too.
16
+
17
+ async function readStdin() {
18
+ if (process.stdin.isTTY) {
19
+ return "";
20
+ }
21
+ const chunks = [];
22
+ for await (const chunk of process.stdin) {
23
+ chunks.push(chunk);
24
+ }
25
+ return Buffer.concat(chunks).toString("utf8");
26
+ }
27
+
28
+ function rootOf(payload) {
29
+ return path.resolve(payload.cwd || process.env.CLAUDE_PROJECT_DIR || process.cwd());
30
+ }
31
+
32
+ function pendingFile(root, call) {
33
+ const safe = String(call).replace(/[^A-Za-z0-9_-]/g, "_");
34
+ return path.join(root, ".turnstamp", "pending", `${safe}.json`);
35
+ }
36
+
37
+ // The before state has to survive until the after hook runs, and that is a
38
+ // separate process, so it goes to a small side file.
39
+ function writePending(root, call, states) {
40
+ if (!call) return;
41
+ const file = pendingFile(root, call);
42
+ fs.mkdirSync(path.dirname(file), { recursive: true });
43
+ fs.writeFileSync(file, JSON.stringify(states), "utf8");
44
+ }
45
+
46
+ function readPending(root, call) {
47
+ if (!call) return [];
48
+ try {
49
+ return JSON.parse(fs.readFileSync(pendingFile(root, call), "utf8"));
50
+ } catch {
51
+ return [];
52
+ }
53
+ }
54
+
55
+ function clearPending(root, call) {
56
+ if (!call) return;
57
+ try {
58
+ fs.unlinkSync(pendingFile(root, call));
59
+ } catch {
60
+ // Already gone.
61
+ }
62
+ }
63
+
64
+ function fileStates(root, tool, input) {
65
+ return toolPaths(tool, input)
66
+ .map((p) => normalizeTarget(root, p))
67
+ .filter(Boolean)
68
+ .map((target) => ({ target, before: readState(path.join(root, target)) }));
69
+ }
70
+
71
+ function onBefore(root, file, fields) {
72
+ const { tool, session, call, input } = fields;
73
+
74
+ if (isFileTool(tool)) {
75
+ const states = fileStates(root, tool, input);
76
+ appendEvent(file, {
77
+ actor: "claude-code",
78
+ kind: "call",
79
+ session,
80
+ call,
81
+ tool,
82
+ action: "call",
83
+ detail: JSON.stringify({ phase: "before", files: states.map((s) => s.target) }),
84
+ });
85
+ writePending(root, call, states);
86
+ return;
87
+ }
88
+
89
+ const command = tool === "Bash" || tool === "PowerShell" ? shellCommand(input) : null;
90
+ appendEvent(file, {
91
+ actor: "claude-code",
92
+ kind: "call",
93
+ session,
94
+ call,
95
+ tool,
96
+ action: command ? "shell" : "call",
97
+ target: command,
98
+ detail: JSON.stringify({ phase: "before" }),
99
+ });
100
+ }
101
+
102
+ function onAfter(root, file, fields) {
103
+ const { tool, session, call, input, failed } = fields;
104
+
105
+ if (!isFileTool(tool)) {
106
+ appendEvent(file, {
107
+ actor: "claude-code",
108
+ kind: "call",
109
+ session,
110
+ call,
111
+ tool,
112
+ action: failed ? "failed" : "done",
113
+ detail: null,
114
+ });
115
+ return;
116
+ }
117
+
118
+ const held = readPending(root, call);
119
+ const states = held.length ? held : fileStates(root, tool, input);
120
+
121
+ for (const item of states) {
122
+ if (!item.target) continue;
123
+ const after = readState(path.join(root, item.target));
124
+ appendEvent(file, {
125
+ actor: "claude-code",
126
+ kind: "file",
127
+ session,
128
+ call,
129
+ tool,
130
+ action: after === "missing" ? "delete" : "write",
131
+ target: item.target,
132
+ before: item.before ?? null,
133
+ detail: after,
134
+ });
135
+ }
136
+
137
+ clearPending(root, call);
138
+ }
139
+
140
+ function main(payload) {
141
+ const root = rootOf(payload);
142
+ const file = ledgerPath(root);
143
+ const fields = {
144
+ tool: String(payload.tool_name || "unknown"),
145
+ session: String(payload.session_id || ""),
146
+ call: String(payload.tool_use_id || ""),
147
+ input: payload.tool_input || {},
148
+ failed: payload.hook_event_name === "PostToolUseFailure",
149
+ };
150
+
151
+ switch (payload.hook_event_name) {
152
+ case "PreToolUse":
153
+ onBefore(root, file, fields);
154
+ break;
155
+ case "PostToolUse":
156
+ case "PostToolUseFailure":
157
+ onAfter(root, file, fields);
158
+ break;
159
+ default:
160
+ break;
161
+ }
162
+ }
163
+
164
+ const raw = await readStdin();
165
+ if (raw.trim()) {
166
+ try {
167
+ main(JSON.parse(raw));
168
+ } catch (err) {
169
+ // A hook must never break the session. Exit 0 with no output is a no-op.
170
+ process.stderr.write(`turnstamp hook: ${err.message}\n`);
171
+ }
172
+ }
173
+ process.exit(0);
package/opencode.js ADDED
@@ -0,0 +1,31 @@
1
+ import { Plugin } from "@opencode/plugin";
2
+
3
+ import { createTracker } from "./src/opencode-plugin.js";
4
+
5
+ // OpenCode plugin entrypoint.
6
+ //
7
+ // This is both the package default export and the "./opencode" subpath, so
8
+ // OpenCode can load the package directly from a plugins entry.
9
+ //
10
+ // Options:
11
+ // actor name written into the ledger, defaults to opencode
12
+ // root project root, defaults to the location directory
13
+ // debug print ledger errors instead of swallowing them
14
+ export default Plugin.define({
15
+ id: "turnstamp",
16
+ async setup(ctx) {
17
+ const tracker = createTracker({
18
+ root: ctx.options.root || ctx.location.directory,
19
+ actor: ctx.options.actor || "opencode",
20
+ debug: ctx.options.debug === true,
21
+ });
22
+
23
+ await ctx.tool.hook("execute.before", (event) => {
24
+ tracker.before(event);
25
+ });
26
+
27
+ await ctx.tool.hook("execute.after", (event) => {
28
+ tracker.after(event);
29
+ });
30
+ },
31
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "turnstamp",
3
- "version": "0.1.0",
3
+ "version": "0.2.1",
4
4
  "description": "Tamper-evident ledger for AI coding agents: prove what your agent actually did.",
5
5
  "license": "MIT",
6
6
  "author": "akshaytheflash",
@@ -17,14 +17,27 @@
17
17
  "turnstamp": "./bin/turnstamp.js"
18
18
  },
19
19
  "exports": {
20
- ".": "./src/index.js"
20
+ ".": "./src/index.js",
21
+ "./server": "./opencode.js",
22
+ "./opencode": "./opencode.js",
23
+ "./hooks/claude-code": "./hooks/claude-code.js"
21
24
  },
22
25
  "files": [
23
26
  "bin",
24
27
  "src",
28
+ "hooks",
29
+ "opencode.js",
25
30
  "README.md",
26
31
  "LICENSE"
27
32
  ],
33
+ "peerDependencies": {
34
+ "@opencode/plugin": "*"
35
+ },
36
+ "peerDependenciesMeta": {
37
+ "@opencode/plugin": {
38
+ "optional": true
39
+ }
40
+ },
28
41
  "engines": {
29
42
  "node": ">=18"
30
43
  },
package/src/events.js ADDED
@@ -0,0 +1,58 @@
1
+ // One vocabulary for every agent. Each integration translates its own payload
2
+ // into these, so the ledger, the verifier and the report never need to know
3
+ // which tool produced an event.
4
+
5
+ export const ACTOR_KINDS = ["agent", "human", "system"];
6
+
7
+ // A call is the agent asking for one tool. A tool may touch several files, so a
8
+ // call fans out into one file event per path.
9
+ export function callEvent(fields) {
10
+ return {
11
+ actor: fields.actor || "agent",
12
+ kind: "call",
13
+ session: fields.session ?? null,
14
+ call: fields.call ?? null,
15
+ tool: fields.tool || "unknown",
16
+ action: fields.action || "call",
17
+ target: null,
18
+ detail: fields.detail ?? null,
19
+ ...(fields.phase ? { phase: fields.phase } : {}),
20
+ };
21
+ }
22
+
23
+ // A file event says: this path went from `before` to `after` because of this
24
+ // call. `before` is missing when the file did not exist.
25
+ export function fileEvent(fields) {
26
+ return {
27
+ actor: fields.actor || "agent",
28
+ kind: "file",
29
+ session: fields.session ?? null,
30
+ call: fields.call ?? null,
31
+ tool: fields.tool || "unknown",
32
+ action: fields.action || "write",
33
+ target: fields.target,
34
+ detail: fields.after ?? null,
35
+ before: fields.before ?? null,
36
+ };
37
+ }
38
+
39
+ // Paths that arrive absolute, or with Windows separators, are normalised so the
40
+ // same file always becomes the same target in the ledger.
41
+ export function normalizeTarget(root, filePath) {
42
+ if (!filePath || typeof filePath !== "string") {
43
+ return null;
44
+ }
45
+ let p = filePath.replace(/\\/g, "/");
46
+ const base = root.replace(/\\/g, "/").replace(/\/+$/, "");
47
+ if (p === base) {
48
+ return ".";
49
+ }
50
+ if (p.startsWith(base + "/")) {
51
+ p = p.slice(base.length + 1);
52
+ }
53
+ p = p.replace(/^\.\//, "");
54
+ while (p.startsWith("../")) {
55
+ p = p.slice(3);
56
+ }
57
+ return p || null;
58
+ }
package/src/install.js ADDED
@@ -0,0 +1,114 @@
1
+ #!/usr/bin/env node
2
+ import fs from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { pathToFileURL } from "node:url";
6
+
7
+ import { ledgerPath } from "../src/ledger.js";
8
+
9
+ // Wires turnstamp into the agents on this machine. Both installs are additive:
10
+ // existing settings are read, merged and written back, never replaced.
11
+
12
+ const HOOK = path.resolve(import.meta.dirname, "..", "hooks", "claude-code.js");
13
+
14
+ function readJson(file) {
15
+ try {
16
+ return JSON.parse(fs.readFileSync(file, "utf8"));
17
+ } catch {
18
+ return null;
19
+ }
20
+ }
21
+
22
+ function writeJson(file, value) {
23
+ fs.mkdirSync(path.dirname(file), { recursive: true });
24
+ fs.writeFileSync(file, JSON.stringify(value, null, 2) + "\n", "utf8");
25
+ }
26
+
27
+ // True when a matcher group already contains one of our hooks. The command is
28
+ // the node binary in exec form, so the script path lives in args.
29
+ function isOurs(group) {
30
+ return (group.hooks || []).some((hook) => {
31
+ const texts = [hook.command, ...(hook.args || [])].filter((v) => typeof v === "string");
32
+ return texts.some((text) => text.includes("turnstamp") || text.includes("claude-code.js"));
33
+ });
34
+ }
35
+
36
+ function merged(existing, entry) {
37
+ const list = Array.isArray(existing) ? existing : [];
38
+ const matcher = entry.matcher;
39
+ const already = list.some((group) => group.matcher === matcher && isOurs(group));
40
+ return already ? list : [...list, entry];
41
+ }
42
+
43
+ function claudeHook(command, matcher, async) {
44
+ return {
45
+ matcher,
46
+ hooks: [
47
+ {
48
+ type: "command",
49
+ command: "node",
50
+ args: [command],
51
+ ...(async ? { async: true } : {}),
52
+ },
53
+ ],
54
+ };
55
+ }
56
+
57
+ export function installClaudeCode(scope = "project", cwd = process.cwd()) {
58
+ const file =
59
+ scope === "user"
60
+ ? path.join(os.homedir(), ".claude", "settings.json")
61
+ : path.join(cwd, ".claude", "settings.json");
62
+
63
+ const settings = readJson(file) || {};
64
+ settings.hooks = settings.hooks || {};
65
+
66
+ const matcher = "Write|Edit|MultiEdit|NotebookEdit";
67
+ settings.hooks.PreToolUse = merged(settings.hooks.PreToolUse, claudeHook(HOOK, matcher, false));
68
+ settings.hooks.PostToolUse = merged(settings.hooks.PostToolUse, claudeHook(HOOK, matcher, false));
69
+ settings.hooks.PostToolUseFailure = merged(
70
+ settings.hooks.PostToolUseFailure,
71
+ claudeHook(HOOK, matcher, false),
72
+ );
73
+ // Bash is logged as a call. It is async so it never delays the command.
74
+ settings.hooks.PreToolUse = merged(
75
+ settings.hooks.PreToolUse,
76
+ claudeHook(HOOK, "Bash|PowerShell", true),
77
+ );
78
+
79
+ writeJson(file, settings);
80
+ return { file, hook: HOOK };
81
+ }
82
+
83
+ export function installOpencode(scope = "project", cwd = process.cwd(), entrypoint) {
84
+ const dir =
85
+ scope === "user"
86
+ ? path.join(os.homedir(), ".config", "opencode")
87
+ : path.join(cwd, ".opencode");
88
+
89
+ const pluginDir = path.join(dir, "plugins", "turnstamp");
90
+ fs.mkdirSync(pluginDir, { recursive: true });
91
+
92
+ // OpenCode loads a local plugin directory by file name, not through package
93
+ // exports, so this file just re-exports the implementation. A file URL keeps
94
+ // it working when the package is installed globally.
95
+ const target = entrypoint || path.resolve(import.meta.dirname, "..", "opencode.js");
96
+ const url = pathToFileURL(target).href;
97
+
98
+ fs.writeFileSync(
99
+ path.join(pluginDir, "index.js"),
100
+ ['import plugin from "' + url + '";', "", "export default plugin;", ""].join("\n"),
101
+ "utf8",
102
+ );
103
+
104
+ return { dir: pluginDir };
105
+ }
106
+
107
+ export function initLedger(cwd = process.cwd()) {
108
+ const file = ledgerPath(cwd);
109
+ fs.mkdirSync(path.dirname(file), { recursive: true });
110
+ if (!fs.existsSync(file)) {
111
+ fs.writeFileSync(file, "", "utf8");
112
+ }
113
+ return file;
114
+ }
package/src/ledger.js CHANGED
@@ -2,8 +2,10 @@ import { createHash } from "node:crypto";
2
2
  import fs from "node:fs";
3
3
  import path from "node:path";
4
4
 
5
+ import { hashTree } from "./tree.js";
6
+
5
7
  export const GENESIS = "0".repeat(64);
6
- export const SCHEMA = 1;
8
+ export const SCHEMA = 2;
7
9
 
8
10
  // Every entry hashes the previous one, so changing anything in the middle breaks
9
11
  // every hash after it. The canonical form is built by hand instead of relying on
@@ -15,9 +17,14 @@ const FIELDS = [
15
17
  "seq",
16
18
  "at",
17
19
  "turn",
20
+ "actor",
21
+ "kind",
22
+ "session",
23
+ "call",
18
24
  "tool",
19
25
  "action",
20
26
  "target",
27
+ "before",
21
28
  "detail",
22
29
  "prev",
23
30
  ];
@@ -88,7 +95,8 @@ export function lastHash(entries) {
88
95
  return entries[entries.length - 1].chain;
89
96
  }
90
97
 
91
- // Appends one event. Called by the CLI and by wrappers around agent hooks.
98
+ // Appends one event. Called by the CLI, by the OpenCode plugin and by the
99
+ // Claude Code hook, so every path into the ledger lands here.
92
100
  export function appendEvent(file, event) {
93
101
  const entries = readLedger(file);
94
102
  const seq = entries.length + 1;
@@ -97,9 +105,14 @@ export function appendEvent(file, event) {
97
105
  seq,
98
106
  at: event.at || new Date().toISOString(),
99
107
  turn: event.turn ?? null,
108
+ actor: event.actor || "agent",
109
+ kind: event.kind || "event",
110
+ session: event.session ?? null,
111
+ call: event.call ?? null,
100
112
  tool: event.tool || "unknown",
101
113
  action: event.action || "event",
102
114
  target: event.target ?? null,
115
+ before: event.before ?? null,
103
116
  detail: event.detail ?? null,
104
117
  prev: lastHash(entries),
105
118
  });
@@ -153,47 +166,96 @@ export function verifyEntries(entries) {
153
166
  };
154
167
  }
155
168
 
156
- // Reads the ledger off disk and decides whether the working tree still matches
157
- // what the last stamps said it looked like.
158
- export function checkTree(file, root = process.cwd()) {
169
+ // Reads the ledger off disk and classifies every file it knows about:
170
+ //
171
+ // agent the file on disk matches the last thing an agent recorded
172
+ // human the file changed and no agent call explains it
173
+ // unknown the file exists but no event ever named it
174
+ //
175
+ // That is the whole point of the hooks. A file the ledger never saw cannot be
176
+ // blamed on the agent, so it is reported as a human change.
177
+ export function checkTree(file, root = process.cwd(), options = {}) {
178
+ const { includeUntracked = false } = options;
159
179
  const entries = readLedger(file);
160
180
  const report = verifyEntries(entries);
161
181
 
182
+ // Last recorded state per path, from any actor, plus the call that set it.
162
183
  const lastByTarget = new Map();
163
184
  for (const entry of entries) {
164
- // Only write and delete describe a file's content. Other events can carry a
165
- // target too, like a shell command, and those are not files on disk.
166
- if (!entry.target || (entry.action !== "write" && entry.action !== "delete")) {
185
+ if (!isFileEvent(entry)) {
167
186
  continue;
168
187
  }
169
188
  lastByTarget.set(entry.target, entry);
170
189
  }
171
190
 
172
- const drift = [];
191
+ const files = [];
173
192
  for (const [target, entry] of lastByTarget) {
174
- const abs = path.join(root, target);
175
- let current = null;
193
+ const current = readTreeState(path.join(root, target));
176
194
 
177
- try {
178
- const stat = fs.statSync(abs);
179
- if (stat.isFile()) {
180
- current = sha256(fs.readFileSync(abs));
181
- } else if (stat.isDirectory()) {
182
- current = "dir";
183
- }
184
- } catch {
185
- current = "missing";
195
+ // A file that still matches what the agent last wrote is accounted for. The
196
+ // rest is drift, and drift with no agent call behind it is the human's.
197
+ if (current === entry.detail) {
198
+ continue;
186
199
  }
187
200
 
188
- if (current !== entry.detail) {
189
- drift.push({
201
+ files.push({
202
+ target,
203
+ state: "human",
204
+ by: entry.actor,
205
+ stamped: entry.detail,
206
+ current,
207
+ at: entry.at,
208
+ tool: entry.tool,
209
+ session: entry.session,
210
+ });
211
+ }
212
+
213
+ // Files the agent never touched cannot be blamed on it. Listing every one of
214
+ // them would drown the report, so this only runs when asked.
215
+ if (includeUntracked) {
216
+ for (const [target, current] of hashTree(root)) {
217
+ if (lastByTarget.has(target)) {
218
+ continue;
219
+ }
220
+ files.push({
190
221
  target,
191
- stamped: entry.detail,
222
+ state: "untracked",
223
+ by: null,
224
+ stamped: null,
192
225
  current,
193
- at: entry.at,
226
+ at: null,
227
+ tool: null,
228
+ session: null,
194
229
  });
195
230
  }
196
231
  }
197
232
 
198
- return { ...report, drift };
233
+ return { ...report, drift: files.sort((a, b) => a.target.localeCompare(b.target)) };
234
+ }
235
+
236
+ // Which entries describe a file's content. A call event or a shell command can
237
+ // carry a target too, and those are not files on disk.
238
+ export function isFileEvent(entry) {
239
+ if (!entry.target) {
240
+ return false;
241
+ }
242
+ if (entry.kind && entry.kind !== "file") {
243
+ return false;
244
+ }
245
+ return entry.action === "write" || entry.action === "edit" || entry.action === "delete";
246
+ }
247
+
248
+ export function readTreeState(abs) {
249
+ try {
250
+ const stat = fs.statSync(abs);
251
+ if (stat.isFile()) {
252
+ return sha256(fs.readFileSync(abs));
253
+ }
254
+ if (stat.isDirectory()) {
255
+ return "dir";
256
+ }
257
+ return "other";
258
+ } catch {
259
+ return "missing";
260
+ }
199
261
  }
@@ -0,0 +1,115 @@
1
+ import path from "node:path";
2
+
3
+ import { appendEvent, ledgerPath } from "./ledger.js";
4
+ import { normalizeTarget } from "./events.js";
5
+ import { isFileTool, readState, shellCommand, toolPaths } from "./tools.js";
6
+
7
+ // Records every OpenCode tool call in the ledger.
8
+ //
9
+ // The before hook reads the state of each file the call is about to touch. The
10
+ // after hook reads it again. The pair is what proves the transition, and it is
11
+ // the agent's own account of what it did.
12
+ //
13
+ // A Map keyed by call id holds the pending "before" states between the two
14
+ // hooks. Calls that never finish are simply dropped.
15
+ export function createTracker(options = {}) {
16
+ const root = path.resolve(options.root || process.cwd());
17
+ const file = options.ledger || ledgerPath(root);
18
+ const actor = options.actor || "opencode";
19
+ const pending = new Map();
20
+
21
+ function record(event) {
22
+ try {
23
+ appendEvent(file, { ...event, actor });
24
+ } catch (err) {
25
+ // A ledger that cannot be written must never take the session down.
26
+ if (options.debug) {
27
+ console.error(`turnstamp: ${err.message}`);
28
+ }
29
+ }
30
+ }
31
+
32
+ return {
33
+ before(event) {
34
+ const tool = String(event.tool);
35
+ const session = String(event.sessionID || "");
36
+ const call = String(event.id || "");
37
+
38
+ if (isFileTool(tool)) {
39
+ const paths = toolPaths(tool, event.input).map((p) => normalizeTarget(root, p)).filter(Boolean);
40
+ const states = paths.map((p) => ({ target: p, before: readState(path.join(root, p)) }));
41
+ pending.set(call, { tool, session, states });
42
+
43
+ record({
44
+ kind: "call",
45
+ phase: "before",
46
+ session,
47
+ call,
48
+ tool,
49
+ action: "call",
50
+ detail: JSON.stringify({ files: paths }),
51
+ });
52
+ return;
53
+ }
54
+
55
+ const command = tool === "shell" ? shellCommand(event.input) : null;
56
+ pending.set(call, { tool, session, states: [] });
57
+ record({
58
+ kind: "call",
59
+ phase: "before",
60
+ session,
61
+ call,
62
+ tool,
63
+ action: tool === "shell" ? "shell" : "call",
64
+ target: command,
65
+ detail: command,
66
+ });
67
+ },
68
+
69
+ after(event) {
70
+ const tool = String(event.tool);
71
+ const session = String(event.sessionID || "");
72
+ const call = String(event.id || "");
73
+ const held = pending.get(call);
74
+ pending.delete(call);
75
+
76
+ if (!isFileTool(tool)) {
77
+ record({
78
+ kind: "call",
79
+ phase: "after",
80
+ session,
81
+ call,
82
+ tool,
83
+ action: event.status === "error" ? "failed" : "done",
84
+ detail: event.status === "error" ? String(event.error?.message || "error") : null,
85
+ });
86
+ return;
87
+ }
88
+
89
+ const states = held ? held.states : [];
90
+ const paths = states.length
91
+ ? states
92
+ : toolPaths(tool, event.input).map((p) => ({
93
+ target: normalizeTarget(root, p),
94
+ before: "missing",
95
+ }));
96
+
97
+ for (const item of paths) {
98
+ if (!item.target) {
99
+ continue;
100
+ }
101
+ const after = readState(path.join(root, item.target));
102
+ record({
103
+ kind: "file",
104
+ session,
105
+ call,
106
+ tool,
107
+ action: after === "missing" ? "delete" : "write",
108
+ target: item.target,
109
+ before: item.before ?? null,
110
+ detail: after,
111
+ });
112
+ }
113
+ },
114
+ };
115
+ }
package/src/tools.js ADDED
@@ -0,0 +1,87 @@
1
+ import { createHash } from "node:crypto";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+
5
+ // Tools that write files, and where each keeps the path in its input.
6
+ // OpenCode uses filePath. Anything new can be added here.
7
+ const PATH_KEYS = ["filePath", "file_path", "path"];
8
+
9
+ export function toolPaths(tool, input) {
10
+ if (!input || typeof input !== "object") {
11
+ return [];
12
+ }
13
+
14
+ if (String(tool).toLowerCase() === "patch") {
15
+ return patchPaths(input);
16
+ }
17
+
18
+ const found = [];
19
+ for (const key of PATH_KEYS) {
20
+ if (typeof input[key] === "string") {
21
+ found.push(input[key]);
22
+ }
23
+ }
24
+
25
+ if (Array.isArray(input.filePaths)) {
26
+ for (const p of input.filePaths) {
27
+ if (typeof p === "string") found.push(p);
28
+ }
29
+ }
30
+
31
+ return [...new Set(found)];
32
+ }
33
+
34
+ // The patch tool takes freeform text with the same headers git apply uses.
35
+ export function patchPaths(input) {
36
+ const text =
37
+ typeof input === "string" ? input : input.patchText || input.patch || input.text || "";
38
+ if (typeof text !== "string") {
39
+ return [];
40
+ }
41
+
42
+ const out = [];
43
+ for (const line of text.split("\n")) {
44
+ const match = line.match(/^\*\*\* (?:Update|Add|Delete) File: (.+)$/);
45
+ if (match) {
46
+ out.push(match[1].trim());
47
+ }
48
+ }
49
+ return [...new Set(out)];
50
+ }
51
+
52
+ // Only these tools can leave a file behind. Compared case sensitively against
53
+ // lowercase names, because OpenCode says write while Claude Code says Write.
54
+ const FILE_TOOLS = new Set(["write", "edit", "multiedit", "patchedit", "notebookedit", "patch"]);
55
+
56
+ export function isFileTool(tool) {
57
+ return FILE_TOOLS.has(String(tool).toLowerCase());
58
+ }
59
+
60
+ export function readState(abs) {
61
+ try {
62
+ const stat = fs.statSync(abs);
63
+ if (!stat.isFile()) {
64
+ return stat.isDirectory() ? "dir" : "other";
65
+ }
66
+ return createHash("sha256").update(fs.readFileSync(abs)).digest("hex");
67
+ } catch {
68
+ return "missing";
69
+ }
70
+ }
71
+
72
+ // A shell call can write files, but we cannot know which. Record it as a call
73
+ // so the ledger shows it happened, and let the next verify attribute whatever
74
+ // moved.
75
+ export function shellCommand(input) {
76
+ if (typeof input === "string") {
77
+ return input;
78
+ }
79
+ if (input && typeof input.command === "string") {
80
+ return input.command;
81
+ }
82
+ return null;
83
+ }
84
+
85
+ export function projectRoot(cwd) {
86
+ return path.resolve(cwd || process.cwd());
87
+ }