turnstamp 0.0.0-stage → 0.2.0

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/package.json CHANGED
@@ -1,6 +1,57 @@
1
1
  {
2
2
  "name": "turnstamp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Tamper-evident ledger for AI coding agents: prove what your agent actually did.",
5
+ "license": "MIT",
6
+ "author": "akshaytheflash",
7
+ "homepage": "https://github.com/akshaytheflash/turnstamp#readme",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/akshaytheflash/turnstamp.git"
11
+ },
12
+ "bugs": {
13
+ "url": "https://github.com/akshaytheflash/turnstamp/issues"
14
+ },
15
+ "type": "module",
16
+ "bin": {
17
+ "turnstamp": "./bin/turnstamp.js"
18
+ },
19
+ "exports": {
20
+ ".": "./src/index.js",
21
+ "./server": "./opencode.js",
22
+ "./opencode": "./opencode.js",
23
+ "./hooks/claude-code": "./hooks/claude-code.js"
24
+ },
25
+ "files": [
26
+ "bin",
27
+ "src",
28
+ "hooks",
29
+ "opencode.js",
30
+ "README.md",
31
+ "LICENSE"
32
+ ],
33
+ "peerDependencies": {
34
+ "@opencode/plugin": "*"
35
+ },
36
+ "peerDependenciesMeta": {
37
+ "@opencode/plugin": {
38
+ "optional": true
39
+ }
40
+ },
41
+ "engines": {
42
+ "node": ">=18"
43
+ },
44
+ "scripts": {
45
+ "test": "node --test test/*.test.js"
46
+ },
47
+ "keywords": [
48
+ "ai",
49
+ "agents",
50
+ "audit",
51
+ "ledger",
52
+ "provenance",
53
+ "tamper-evident",
54
+ "hash-chain",
55
+ "coding-agents"
56
+ ]
57
+ }
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/index.js ADDED
@@ -0,0 +1,18 @@
1
+ export {
2
+ GENESIS,
3
+ SCHEMA,
4
+ appendEvent,
5
+ canonical,
6
+ chainHash,
7
+ checkTree,
8
+ lastHash,
9
+ ledgerPath,
10
+ readLedger,
11
+ sha256,
12
+ stamp,
13
+ treeDigest,
14
+ verifyEntries,
15
+ writeLedger,
16
+ } from "./ledger.js";
17
+
18
+ export { diffTrees, fileHash, hashTree } from "./tree.js";
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 ADDED
@@ -0,0 +1,261 @@
1
+ import { createHash } from "node:crypto";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+
5
+ import { hashTree } from "./tree.js";
6
+
7
+ export const GENESIS = "0".repeat(64);
8
+ export const SCHEMA = 2;
9
+
10
+ // Every entry hashes the previous one, so changing anything in the middle breaks
11
+ // every hash after it. The canonical form is built by hand instead of relying on
12
+ // JSON.stringify, because object key order is not something we want to trust.
13
+ // The chain value is excluded on purpose: it is computed from everything else,
14
+ // so including it would make the hash depend on itself.
15
+ const FIELDS = [
16
+ "schema",
17
+ "seq",
18
+ "at",
19
+ "turn",
20
+ "actor",
21
+ "kind",
22
+ "session",
23
+ "call",
24
+ "tool",
25
+ "action",
26
+ "target",
27
+ "before",
28
+ "detail",
29
+ "prev",
30
+ ];
31
+
32
+ export function sha256(input) {
33
+ return createHash("sha256").update(input).digest("hex");
34
+ }
35
+
36
+ // One digest for a whole file map. Sorting first means the answer never depends
37
+ // on the order the filesystem happened to hand names back in.
38
+ export function treeDigest(map) {
39
+ const parts = [...map.entries()]
40
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
41
+ .map(([name, hash]) => `${name}:${hash}`);
42
+ return sha256(parts.join("\n"));
43
+ }
44
+
45
+ export function canonical(entry) {
46
+ const ordered = {};
47
+ for (const key of FIELDS) {
48
+ const value = entry[key];
49
+ ordered[key] = value === undefined ? null : value;
50
+ }
51
+ return JSON.stringify(ordered);
52
+ }
53
+
54
+ export function chainHash(entry) {
55
+ return sha256(canonical(entry));
56
+ }
57
+
58
+ // An entry is complete once it has a chain value. Everything else is data.
59
+ export function stamp(entry) {
60
+ const next = { ...entry };
61
+ next.schema = SCHEMA;
62
+ next.chain = chainHash(next);
63
+ return next;
64
+ }
65
+
66
+ export function ledgerPath(cwd = process.cwd()) {
67
+ return path.join(cwd, ".turnstamp", "ledger.jsonl");
68
+ }
69
+
70
+ export function readLedger(file) {
71
+ if (!fs.existsSync(file)) {
72
+ return [];
73
+ }
74
+ const raw = fs.readFileSync(file, "utf8");
75
+ const lines = raw.split("\n").filter((line) => line.trim() !== "");
76
+ return lines.map((line, index) => {
77
+ try {
78
+ return JSON.parse(line);
79
+ } catch (err) {
80
+ throw new Error(`line ${index + 1} is not valid JSON: ${err.message}`);
81
+ }
82
+ });
83
+ }
84
+
85
+ export function writeLedger(file, entries) {
86
+ fs.mkdirSync(path.dirname(file), { recursive: true });
87
+ const body = entries.map((entry) => JSON.stringify(entry)).join("\n");
88
+ fs.writeFileSync(file, entries.length ? body + "\n" : "", "utf8");
89
+ }
90
+
91
+ export function lastHash(entries) {
92
+ if (entries.length === 0) {
93
+ return GENESIS;
94
+ }
95
+ return entries[entries.length - 1].chain;
96
+ }
97
+
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.
100
+ export function appendEvent(file, event) {
101
+ const entries = readLedger(file);
102
+ const seq = entries.length + 1;
103
+ const entry = stamp({
104
+ schema: SCHEMA,
105
+ seq,
106
+ at: event.at || new Date().toISOString(),
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,
112
+ tool: event.tool || "unknown",
113
+ action: event.action || "event",
114
+ target: event.target ?? null,
115
+ before: event.before ?? null,
116
+ detail: event.detail ?? null,
117
+ prev: lastHash(entries),
118
+ });
119
+ fs.mkdirSync(path.dirname(file), { recursive: true });
120
+ fs.appendFileSync(file, JSON.stringify(entry) + "\n", "utf8");
121
+ return entry;
122
+ }
123
+
124
+ // Recomputes every hash and checks that each entry points at the one before it.
125
+ // Returns a report instead of throwing, so callers can print all the damage at once.
126
+ export function verifyEntries(entries) {
127
+ const problems = [];
128
+ let prev = GENESIS;
129
+
130
+ entries.forEach((entry, index) => {
131
+ const where = `entry ${index + 1}`;
132
+
133
+ if (entry.seq !== index + 1) {
134
+ problems.push({
135
+ at: where,
136
+ kind: "sequence",
137
+ message: `expected seq ${index + 1}, found ${entry.seq}`,
138
+ });
139
+ }
140
+
141
+ if (entry.prev !== prev) {
142
+ problems.push({
143
+ at: where,
144
+ kind: "link",
145
+ message: `does not point at the entry before it`,
146
+ });
147
+ }
148
+
149
+ const expected = chainHash(entry);
150
+ if (entry.chain !== expected) {
151
+ problems.push({
152
+ at: where,
153
+ kind: "digest",
154
+ message: `content changed after it was stamped`,
155
+ });
156
+ }
157
+
158
+ prev = entry.chain;
159
+ });
160
+
161
+ return {
162
+ ok: problems.length === 0,
163
+ count: entries.length,
164
+ head: prev,
165
+ problems,
166
+ };
167
+ }
168
+
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;
179
+ const entries = readLedger(file);
180
+ const report = verifyEntries(entries);
181
+
182
+ // Last recorded state per path, from any actor, plus the call that set it.
183
+ const lastByTarget = new Map();
184
+ for (const entry of entries) {
185
+ if (!isFileEvent(entry)) {
186
+ continue;
187
+ }
188
+ lastByTarget.set(entry.target, entry);
189
+ }
190
+
191
+ const files = [];
192
+ for (const [target, entry] of lastByTarget) {
193
+ const current = readTreeState(path.join(root, target));
194
+
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;
199
+ }
200
+
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({
221
+ target,
222
+ state: "untracked",
223
+ by: null,
224
+ stamped: null,
225
+ current,
226
+ at: null,
227
+ tool: null,
228
+ session: null,
229
+ });
230
+ }
231
+ }
232
+
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
+ }
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
+ }