turnstamp 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Akshay (akshaytheflash)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,140 @@
1
- # Temporary Holding Version
1
+ # turnstamp
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Prove what your AI coding agent actually did.
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.
8
+
9
+ ```
10
+ npx turnstamp init
11
+ npx turnstamp stamp --turn 1 --tool claude
12
+ npx turnstamp verify
13
+ ```
14
+
15
+ ## Why
16
+
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.
21
+
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.
25
+
26
+ ## Commands
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` |
35
+
36
+ ### stamp
37
+
38
+ ```bash
39
+ turnstamp stamp --turn 3 --tool claude --action edit
40
+ ```
41
+
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.
45
+
46
+ ### event
47
+
48
+ For agent hooks and wrapper scripts. Feed it whatever your agent gives you.
49
+
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
+ ```
54
+
55
+ ### verify
56
+
57
+ ```bash
58
+ turnstamp verify
59
+ ```
60
+
61
+ ```
62
+ ledger .turnstamp/ledger.jsonl
63
+ entries 7
64
+ head 7d5597b5559bff0a
65
+ chain intact
66
+ files match the last stamp
67
+ ```
68
+
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.
71
+
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.
75
+
76
+ ```
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...
81
+ ```
82
+
83
+ ## What it does not do
84
+
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.
89
+
90
+ It catches the common cases:
91
+
92
+ - a file rewritten after the agent said it was done
93
+ - an entry edited to hide a file
94
+ - an entry deleted from the middle
95
+ - a careful forger who fixes the digest but not the link to the next entry
96
+
97
+ ## Library
98
+
99
+ The CLI is a thin wrapper. Everything is exported if you want it inside your own
100
+ tooling.
101
+
102
+ ```js
103
+ import { appendEvent, verifyEntries, readLedger, ledgerPath } from "turnstamp";
104
+
105
+ const file = ledgerPath(process.cwd());
106
+ appendEvent(file, { turn: 1, tool: "claude", action: "read", target: "src/app.js" });
107
+
108
+ const report = verifyEntries(readLedger(file));
109
+ console.log(report.ok, report.problems);
110
+ ```
111
+
112
+ ## Ledger format
113
+
114
+ One JSON object per line in `.turnstamp/ledger.jsonl`. Fixed key order, so the
115
+ hash is stable across machines and Node versions.
116
+
117
+ ```json
118
+ {
119
+ "schema": 1,
120
+ "seq": 2,
121
+ "at": "2026-11-16T13:42:59.123Z",
122
+ "turn": 1,
123
+ "tool": "claude",
124
+ "action": "write",
125
+ "target": "src/app.js",
126
+ "detail": "f51105f5972c...",
127
+ "prev": "948bccbeadb7...",
128
+ "chain": "3d1484ea99d5..."
129
+ }
130
+ ```
131
+
132
+ `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.
134
+
135
+ Commit the ledger if you want other people to be able to check your work. It is
136
+ a record, not a secret.
137
+
138
+ ## Licence
139
+
140
+ MIT
@@ -0,0 +1,261 @@
1
+ #!/usr/bin/env node
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+
5
+ import {
6
+ appendEvent,
7
+ checkTree,
8
+ ledgerPath,
9
+ readLedger,
10
+ treeDigest,
11
+ } from "../src/ledger.js";
12
+ import { diffTrees, hashTree } from "../src/tree.js";
13
+
14
+ const HELP = `turnstamp - prove what your agent actually did
15
+
16
+ Usage
17
+ 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
21
+ turnstamp log [--turn N] [--json] read the ledger back
22
+
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
27
+
28
+ verify exits 1 when the chain is broken or a stamped file changed on disk.
29
+ `;
30
+
31
+ export function parseArgs(argv) {
32
+ const args = { _: [] };
33
+ for (let i = 0; i < argv.length; i++) {
34
+ const token = argv[i];
35
+ if (token.startsWith("--")) {
36
+ const key = token.slice(2);
37
+ const next = argv[i + 1];
38
+ if (next === undefined || next.startsWith("--")) {
39
+ args[key] = true;
40
+ } else {
41
+ args[key] = next;
42
+ i++;
43
+ }
44
+ } else {
45
+ args._.push(token);
46
+ }
47
+ }
48
+ return args;
49
+ }
50
+
51
+ // Rebuilds the file map as it stood at the end of a turn, by replaying the per
52
+ // file entries that belong to that turn.
53
+ function snapshotAtTurn(entries, turn) {
54
+ const map = new Map();
55
+ for (const entry of entries) {
56
+ if (!entry.target || entry.turn !== turn) continue;
57
+ if (entry.action === "delete") {
58
+ map.delete(entry.target);
59
+ } else {
60
+ map.set(entry.target, entry.detail);
61
+ }
62
+ }
63
+ return map;
64
+ }
65
+
66
+ function snapshotTurns(entries) {
67
+ const turns = new Set();
68
+ for (const entry of entries) {
69
+ if (!entry.target && entry.action === "snapshot" && typeof entry.turn === "number") {
70
+ turns.add(entry.turn);
71
+ }
72
+ }
73
+ return [...turns].sort((a, b) => a - b);
74
+ }
75
+
76
+ function nextTurn(entries) {
77
+ let max = -1;
78
+ for (const entry of entries) {
79
+ if (typeof entry.turn === "number" && entry.turn > max) {
80
+ max = entry.turn;
81
+ }
82
+ }
83
+ return max + 1;
84
+ }
85
+
86
+ function cmdInit() {
87
+ const file = ledgerPath(process.cwd());
88
+ if (fs.existsSync(file)) {
89
+ console.log("ledger already exists");
90
+ return 0;
91
+ }
92
+ fs.mkdirSync(path.dirname(file), { recursive: true });
93
+ fs.writeFileSync(file, "", "utf8");
94
+ console.log(`created ${path.relative(process.cwd(), file)}`);
95
+ return 0;
96
+ }
97
+
98
+ // A stamp records the files that changed since the previous snapshot, one entry
99
+ // each, then a summary entry. verify replays those entries to catch rewrites.
100
+ function cmdStamp(args) {
101
+ const root = process.cwd();
102
+ const file = ledgerPath(root);
103
+ const entries = readLedger(file);
104
+ const tool = args.tool || "manual";
105
+ const action = args.action || "snapshot";
106
+ const turn = args.turn ? Number(args.turn) : nextTurn(entries);
107
+
108
+ const now = hashTree(root);
109
+ const previousTurns = snapshotTurns(entries);
110
+ const previous =
111
+ previousTurns.length > 0 ? snapshotAtTurn(entries, previousTurns.at(-1)) : new Map();
112
+
113
+ const delta = diffTrees(previous, now);
114
+ const touched = [...new Set([...delta.added, ...delta.changed, ...delta.removed])].sort();
115
+
116
+ for (const target of touched) {
117
+ const detail = now.get(target) ?? "missing";
118
+ appendEvent(file, {
119
+ turn,
120
+ tool,
121
+ action: detail === "missing" ? "delete" : "write",
122
+ target,
123
+ detail,
124
+ });
125
+ }
126
+
127
+ const summary = appendEvent(file, {
128
+ turn,
129
+ tool,
130
+ action,
131
+ target: null,
132
+ detail: JSON.stringify({
133
+ files: now.size,
134
+ added: delta.added.length,
135
+ changed: delta.changed.length,
136
+ removed: delta.removed.length,
137
+ tree: treeDigest(now),
138
+ }),
139
+ });
140
+
141
+ console.log(
142
+ `stamped turn ${turn}: ${delta.added.length} added, ${delta.changed.length} changed, ` +
143
+ `${delta.removed.length} removed (${now.size} files, ${summary.chain.slice(0, 12)})`,
144
+ );
145
+ return 0;
146
+ }
147
+
148
+ function short(value) {
149
+ if (typeof value !== "string") return String(value);
150
+ return value.length > 16 ? `${value.slice(0, 16)}...` : value;
151
+ }
152
+
153
+ function cmdVerify(args) {
154
+ const root = process.cwd();
155
+ const file = ledgerPath(root);
156
+ const report = checkTree(file, root);
157
+ const ok = report.ok && report.drift.length === 0;
158
+
159
+ if (args.json) {
160
+ console.log(JSON.stringify(report, null, 2));
161
+ return ok ? 0 : 1;
162
+ }
163
+
164
+ console.log(`ledger ${path.relative(root, file)}`);
165
+ console.log(`entries ${report.count}`);
166
+ console.log(`head ${report.head.slice(0, 16)}`);
167
+
168
+ if (report.ok) {
169
+ console.log("chain intact");
170
+ } else {
171
+ console.log("chain BROKEN");
172
+ for (const problem of report.problems) {
173
+ console.log(` ${problem.at}: ${problem.kind} - ${problem.message}`);
174
+ }
175
+ }
176
+
177
+ if (report.drift.length === 0) {
178
+ console.log("files match the last stamp");
179
+ } else {
180
+ console.log("files changed after they were stamped");
181
+ for (const item of report.drift) {
182
+ console.log(` ${item.target}: stamped ${short(item.stamped)}, now ${short(item.current)}`);
183
+ }
184
+ }
185
+
186
+ return ok ? 0 : 1;
187
+ }
188
+
189
+ function cmdLog(args) {
190
+ const entries = readLedger(ledgerPath(process.cwd()));
191
+ const filtered =
192
+ args.turn !== undefined
193
+ ? entries.filter((entry) => String(entry.turn) === String(args.turn))
194
+ : entries;
195
+
196
+ if (args.json) {
197
+ console.log(JSON.stringify(filtered, null, 2));
198
+ return 0;
199
+ }
200
+
201
+ if (filtered.length === 0) {
202
+ console.log("nothing recorded yet");
203
+ return 0;
204
+ }
205
+
206
+ for (const entry of filtered) {
207
+ const when = entry.at.slice(11, 19);
208
+ const turn = entry.turn === null ? "-" : String(entry.turn);
209
+ console.log(
210
+ `${when} t${turn} ${entry.tool}/${entry.action} ${entry.target || "(turn)"} ${entry.chain.slice(0, 10)}`,
211
+ );
212
+ }
213
+ return 0;
214
+ }
215
+
216
+ function cmdEvent(args) {
217
+ if (!args.json || args.json === true) {
218
+ console.error("event needs --json '{...}'");
219
+ return 1;
220
+ }
221
+
222
+ let payload;
223
+ try {
224
+ payload = JSON.parse(String(args.json));
225
+ } catch (err) {
226
+ console.error(`bad json: ${err.message}`);
227
+ return 1;
228
+ }
229
+
230
+ const entry = appendEvent(ledgerPath(process.cwd()), payload);
231
+ console.log(`${entry.seq} ${entry.chain.slice(0, 12)}`);
232
+ return 0;
233
+ }
234
+
235
+ function main(argv) {
236
+ const [command, ...rest] = argv;
237
+ const args = parseArgs(rest);
238
+
239
+ if (!command || command === "help" || args.help) {
240
+ console.log(HELP);
241
+ return 0;
242
+ }
243
+
244
+ switch (command) {
245
+ case "init":
246
+ return cmdInit();
247
+ case "stamp":
248
+ return cmdStamp(args);
249
+ case "event":
250
+ return cmdEvent(args);
251
+ case "verify":
252
+ return cmdVerify(args);
253
+ case "log":
254
+ return cmdLog(args);
255
+ default:
256
+ console.error(`unknown command: ${command}`);
257
+ return 1;
258
+ }
259
+ }
260
+
261
+ process.exitCode = main(process.argv.slice(2));
package/package.json CHANGED
@@ -1,6 +1,44 @@
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.1.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
+ },
22
+ "files": [
23
+ "bin",
24
+ "src",
25
+ "README.md",
26
+ "LICENSE"
27
+ ],
28
+ "engines": {
29
+ "node": ">=18"
30
+ },
31
+ "scripts": {
32
+ "test": "node --test test/*.test.js"
33
+ },
34
+ "keywords": [
35
+ "ai",
36
+ "agents",
37
+ "audit",
38
+ "ledger",
39
+ "provenance",
40
+ "tamper-evident",
41
+ "hash-chain",
42
+ "coding-agents"
43
+ ]
44
+ }
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/ledger.js ADDED
@@ -0,0 +1,199 @@
1
+ import { createHash } from "node:crypto";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+
5
+ export const GENESIS = "0".repeat(64);
6
+ export const SCHEMA = 1;
7
+
8
+ // Every entry hashes the previous one, so changing anything in the middle breaks
9
+ // every hash after it. The canonical form is built by hand instead of relying on
10
+ // JSON.stringify, because object key order is not something we want to trust.
11
+ // The chain value is excluded on purpose: it is computed from everything else,
12
+ // so including it would make the hash depend on itself.
13
+ const FIELDS = [
14
+ "schema",
15
+ "seq",
16
+ "at",
17
+ "turn",
18
+ "tool",
19
+ "action",
20
+ "target",
21
+ "detail",
22
+ "prev",
23
+ ];
24
+
25
+ export function sha256(input) {
26
+ return createHash("sha256").update(input).digest("hex");
27
+ }
28
+
29
+ // One digest for a whole file map. Sorting first means the answer never depends
30
+ // on the order the filesystem happened to hand names back in.
31
+ export function treeDigest(map) {
32
+ const parts = [...map.entries()]
33
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
34
+ .map(([name, hash]) => `${name}:${hash}`);
35
+ return sha256(parts.join("\n"));
36
+ }
37
+
38
+ export function canonical(entry) {
39
+ const ordered = {};
40
+ for (const key of FIELDS) {
41
+ const value = entry[key];
42
+ ordered[key] = value === undefined ? null : value;
43
+ }
44
+ return JSON.stringify(ordered);
45
+ }
46
+
47
+ export function chainHash(entry) {
48
+ return sha256(canonical(entry));
49
+ }
50
+
51
+ // An entry is complete once it has a chain value. Everything else is data.
52
+ export function stamp(entry) {
53
+ const next = { ...entry };
54
+ next.schema = SCHEMA;
55
+ next.chain = chainHash(next);
56
+ return next;
57
+ }
58
+
59
+ export function ledgerPath(cwd = process.cwd()) {
60
+ return path.join(cwd, ".turnstamp", "ledger.jsonl");
61
+ }
62
+
63
+ export function readLedger(file) {
64
+ if (!fs.existsSync(file)) {
65
+ return [];
66
+ }
67
+ const raw = fs.readFileSync(file, "utf8");
68
+ const lines = raw.split("\n").filter((line) => line.trim() !== "");
69
+ return lines.map((line, index) => {
70
+ try {
71
+ return JSON.parse(line);
72
+ } catch (err) {
73
+ throw new Error(`line ${index + 1} is not valid JSON: ${err.message}`);
74
+ }
75
+ });
76
+ }
77
+
78
+ export function writeLedger(file, entries) {
79
+ fs.mkdirSync(path.dirname(file), { recursive: true });
80
+ const body = entries.map((entry) => JSON.stringify(entry)).join("\n");
81
+ fs.writeFileSync(file, entries.length ? body + "\n" : "", "utf8");
82
+ }
83
+
84
+ export function lastHash(entries) {
85
+ if (entries.length === 0) {
86
+ return GENESIS;
87
+ }
88
+ return entries[entries.length - 1].chain;
89
+ }
90
+
91
+ // Appends one event. Called by the CLI and by wrappers around agent hooks.
92
+ export function appendEvent(file, event) {
93
+ const entries = readLedger(file);
94
+ const seq = entries.length + 1;
95
+ const entry = stamp({
96
+ schema: SCHEMA,
97
+ seq,
98
+ at: event.at || new Date().toISOString(),
99
+ turn: event.turn ?? null,
100
+ tool: event.tool || "unknown",
101
+ action: event.action || "event",
102
+ target: event.target ?? null,
103
+ detail: event.detail ?? null,
104
+ prev: lastHash(entries),
105
+ });
106
+ fs.mkdirSync(path.dirname(file), { recursive: true });
107
+ fs.appendFileSync(file, JSON.stringify(entry) + "\n", "utf8");
108
+ return entry;
109
+ }
110
+
111
+ // Recomputes every hash and checks that each entry points at the one before it.
112
+ // Returns a report instead of throwing, so callers can print all the damage at once.
113
+ export function verifyEntries(entries) {
114
+ const problems = [];
115
+ let prev = GENESIS;
116
+
117
+ entries.forEach((entry, index) => {
118
+ const where = `entry ${index + 1}`;
119
+
120
+ if (entry.seq !== index + 1) {
121
+ problems.push({
122
+ at: where,
123
+ kind: "sequence",
124
+ message: `expected seq ${index + 1}, found ${entry.seq}`,
125
+ });
126
+ }
127
+
128
+ if (entry.prev !== prev) {
129
+ problems.push({
130
+ at: where,
131
+ kind: "link",
132
+ message: `does not point at the entry before it`,
133
+ });
134
+ }
135
+
136
+ const expected = chainHash(entry);
137
+ if (entry.chain !== expected) {
138
+ problems.push({
139
+ at: where,
140
+ kind: "digest",
141
+ message: `content changed after it was stamped`,
142
+ });
143
+ }
144
+
145
+ prev = entry.chain;
146
+ });
147
+
148
+ return {
149
+ ok: problems.length === 0,
150
+ count: entries.length,
151
+ head: prev,
152
+ problems,
153
+ };
154
+ }
155
+
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()) {
159
+ const entries = readLedger(file);
160
+ const report = verifyEntries(entries);
161
+
162
+ const lastByTarget = new Map();
163
+ 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")) {
167
+ continue;
168
+ }
169
+ lastByTarget.set(entry.target, entry);
170
+ }
171
+
172
+ const drift = [];
173
+ for (const [target, entry] of lastByTarget) {
174
+ const abs = path.join(root, target);
175
+ let current = null;
176
+
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";
186
+ }
187
+
188
+ if (current !== entry.detail) {
189
+ drift.push({
190
+ target,
191
+ stamped: entry.detail,
192
+ current,
193
+ at: entry.at,
194
+ });
195
+ }
196
+ }
197
+
198
+ return { ...report, drift };
199
+ }
package/src/tree.js ADDED
@@ -0,0 +1,91 @@
1
+ import { createHash } from "node:crypto";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+
5
+ const SKIP_DIRS = new Set([
6
+ ".git",
7
+ "node_modules",
8
+ ".turnstamp",
9
+ "dist",
10
+ "build",
11
+ "target",
12
+ ".venv",
13
+ "__pycache__",
14
+ ]);
15
+
16
+ export function fileHash(file) {
17
+ return createHash("sha256").update(fs.readFileSync(file)).digest("hex");
18
+ }
19
+
20
+ // Walks the directory and returns a target -> digest map. Directories are
21
+ // recorded as "dir" so an empty folder is still accounted for in the ledger.
22
+ export function hashTree(root, options = {}) {
23
+ const prefix = options.prefix || "";
24
+ const out = new Map();
25
+
26
+ function walk(dir, relative) {
27
+ let names;
28
+ try {
29
+ names = fs.readdirSync(dir);
30
+ } catch {
31
+ return;
32
+ }
33
+
34
+ for (const name of names.sort()) {
35
+ if (SKIP_DIRS.has(name)) {
36
+ continue;
37
+ }
38
+
39
+ const full = path.join(dir, name);
40
+ const rel = relative ? `${relative}/${name}` : name;
41
+ let stat;
42
+ try {
43
+ stat = fs.lstatSync(full);
44
+ } catch {
45
+ continue;
46
+ }
47
+
48
+ if (stat.isSymbolicLink()) {
49
+ out.set(rel, `link:${fs.readlinkSync(full)}`);
50
+ continue;
51
+ }
52
+
53
+ if (stat.isDirectory()) {
54
+ out.set(rel, "dir");
55
+ walk(full, rel);
56
+ continue;
57
+ }
58
+
59
+ if (stat.isFile()) {
60
+ out.set(rel, fileHash(full));
61
+ }
62
+ }
63
+ }
64
+
65
+ walk(root, prefix);
66
+ return out;
67
+ }
68
+
69
+ // Compares two maps and returns what appeared, changed and disappeared. Used by
70
+ // the snapshot writer so a turn records the delta, not the whole tree twice.
71
+ export function diffTrees(before, after) {
72
+ const added = [];
73
+ const changed = [];
74
+ const removed = [];
75
+
76
+ for (const [target, hash] of after) {
77
+ if (!before.has(target)) {
78
+ added.push(target);
79
+ } else if (before.get(target) !== hash) {
80
+ changed.push(target);
81
+ }
82
+ }
83
+
84
+ for (const target of before.keys()) {
85
+ if (!after.has(target)) {
86
+ removed.push(target);
87
+ }
88
+ }
89
+
90
+ return { added, changed, removed };
91
+ }