checkpointer 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,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,137 @@
1
+ # checkpointer
2
+
3
+ > Git-isolated checkpoints that humans and AI agents share — save working states, revert anytime, ship a range as one clean commit.
4
+
5
+ When you (or an AI agent) work through a long task, you want save points: a way to
6
+ mark "this works", roll back when something breaks, and at the end turn all that
7
+ churn into **one clean commit**. `checkpointer` does exactly that, in a shadow git
8
+ repo kept outside your project — so your real `git log` stays clean until you ship.
9
+
10
+ - **Shared by humans and agents** — same commands, same checkpoints. Works with Claude Code, Cursor, or any tool that can run a shell command.
11
+ - **Isolated from your repo** — checkpoints live in `~/.checkpointer`, never in your project's `.git`. Nothing shows up in `git log` until you `ship`.
12
+ - **Captures everything** — unlike editor undo, it snapshots the whole working tree, including files changed by scripts, formatters, and codemods.
13
+ - **Ships to one commit** — bundle a range of checkpoints into a single commit on your branch, then push when you're ready.
14
+
15
+ ## Install
16
+
17
+ ```bash
18
+ npm install -g checkpointer # then: checkpointer <command>
19
+ npx checkpointer <command> # or run without installing
20
+ ```
21
+
22
+ Requires Node 18+ and git. Also available as `ckpt`.
23
+
24
+ ## Quick start
25
+
26
+ ```bash
27
+ checkpointer init # set up checkpointing here
28
+ checkpointer save before-refactor # snapshot before risky work
29
+ # ... make changes ...
30
+ checkpointer save working --status working # mark a known-good state
31
+ checkpointer restore before-refactor # something broke? roll back
32
+ checkpointer ship -m "Refactor auth module" # bundle it all into one commit
33
+ git push # ship never pushes — you do
34
+ ```
35
+
36
+ ## Concepts
37
+
38
+ - **Checkpoint** — a full snapshot of your working tree at a moment in time, with a
39
+ name, a status, and (optionally) who made it and why.
40
+ - **Status** — `working` (verified good), `wip` (in progress, the default), or
41
+ `broken` (known bad). `ship` refuses to include `broken` checkpoints unless forced.
42
+ - **Shipping** — replaying the state of a chosen checkpoint onto your real repo as a
43
+ single commit. Everything since the last ship is bundled together.
44
+ - **Shadow repo** — a hidden git repository per project under `~/.checkpointer`. It is
45
+ how snapshots are stored cheaply; it never touches your project's `.git`.
46
+
47
+ ## Commands
48
+
49
+ | Command | What it does |
50
+ | --- | --- |
51
+ | `init` | Initialize checkpointing for the current project |
52
+ | `save [name]` | Snapshot the working tree (auto-names `cp-N` if no name) |
53
+ | `list` (`ls`) | List all checkpoints |
54
+ | `status` | Show how many checkpoints are waiting to be shipped |
55
+ | `show <id>` | Show a checkpoint's details and tracked files |
56
+ | `diff <a> [b]` | Diff two checkpoints, or one checkpoint vs current files |
57
+ | `restore <id>` | Reset the working tree to a checkpoint (auto-saves first) |
58
+ | `tag <id> <status>` | Mark a checkpoint `working`, `wip`, or `broken` |
59
+ | `ship` | Bundle unshipped checkpoints into one commit on your repo |
60
+ | `info` | Show where checkpoints are stored and which paths are excluded |
61
+ | `skill install` | Install the Claude Code skill so agents know how to use this |
62
+
63
+ Reference any checkpoint by **name** (`login`), **sequence** (`#4`), or **short sha**.
64
+ Add `--json` to any command for machine-readable output; on failure it prints
65
+ `{"error": "...", "code": "..."}` to stdout and exits non-zero. Run `checkpointer
66
+ <command> --help` for full options and examples.
67
+
68
+ ### Key options
69
+
70
+ ```bash
71
+ checkpointer save v1 --status working -m "first working version"
72
+ checkpointer save --intent "extracting the parser" # record why (for agents)
73
+
74
+ checkpointer ship --dry-run # preview what will commit
75
+ checkpointer ship --upto v1 -m "Ship first version" # ship up to a checkpoint
76
+ checkpointer ship --force -m "..." # include broken checkpoints
77
+ ```
78
+
79
+ ## Safety
80
+
81
+ - **Restore can't lose work.** Every `restore` first auto-saves your current state, so
82
+ you can always restore that to undo. These auto checkpoints are marked and don't
83
+ count toward what gets shipped.
84
+ - **Ship only adds a commit.** `ship` builds the commit from a checkpoint's snapshot
85
+ using git plumbing — it never resets your working tree, so uncommitted edits and
86
+ untracked files are left exactly as they were.
87
+ - **Secrets stay put.** `.env`, `*.pem`, `*.key`, `secrets.*`, `node_modules`, and your
88
+ `.git` are never snapshotted — so a restore never overwrites them. See `checkpointer
89
+ info` for the full list; add your own patterns in the shown `ignore` file.
90
+ - **Nothing leaves your machine.** No telemetry. Checkpoints are local git objects.
91
+
92
+ ## Using it with AI agents
93
+
94
+ `checkpointer` is just a CLI, so any agent that can run shell commands can use it.
95
+ Agents identify themselves with environment variables so their checkpoints are
96
+ attributed:
97
+
98
+ ```bash
99
+ export CHECKPOINTER_AGENT=claude-code
100
+ export CHECKPOINTER_SESSION="<session-id>"
101
+ export CHECKPOINTER_AUTHOR="<name>" # optional: override the attributed author
102
+ ```
103
+
104
+ Then a `checkpointer save` records the agent and session automatically.
105
+
106
+ ### Claude Code
107
+
108
+ Install the bundled skill once and Claude Code will know when and how to checkpoint:
109
+
110
+ ```bash
111
+ checkpointer skill install
112
+ ```
113
+
114
+ This copies a skill into `~/.claude/skills/checkpointer`. Claude will then save
115
+ checkpoints before risky changes, roll back on failure, and offer to ship when you're
116
+ done.
117
+
118
+ ### Cursor and other agents
119
+
120
+ Point the agent at the command reference above, or copy the skill's guidance into your
121
+ agent rules (`checkpointer skill path` prints the bundled skill directory; read
122
+ `SKILL.md` inside it). The same env-var protocol applies.
123
+
124
+ ## How it works
125
+
126
+ For each project, `checkpointer` keeps a bare git repo at
127
+ `~/.checkpointer/projects/<id>/repo.git`. Every checkpoint is a commit there, made with
128
+ `git --git-dir=<shadow> --work-tree=<project>` so your project's `.git` is never read or
129
+ written. `ship` transfers the chosen checkpoint's objects into your real repo and builds
130
+ one ordinary commit from its tree — without resetting your working tree, so your
131
+ uncommitted work is untouched. It never pushes.
132
+
133
+ Set `CHECKPOINTER_HOME` to store checkpoints somewhere other than `~/.checkpointer`.
134
+
135
+ ## License
136
+
137
+ Apache-2.0
package/dist/cli.js ADDED
@@ -0,0 +1,875 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/cli.ts
4
+ import { Command } from "commander";
5
+ import pc3 from "picocolors";
6
+
7
+ // src/actions.ts
8
+ import pc2 from "picocolors";
9
+
10
+ // src/core/store.ts
11
+ import { existsSync as existsSync3, mkdirSync as mkdirSync3 } from "fs";
12
+
13
+ // src/core/exec.ts
14
+ import { spawnSync } from "child_process";
15
+ function run(command, args, options = {}) {
16
+ const result = spawnSync(command, args, {
17
+ cwd: options.cwd,
18
+ input: options.input,
19
+ env: options.env ?? process.env,
20
+ encoding: "utf8",
21
+ maxBuffer: 256 * 1024 * 1024
22
+ });
23
+ if (result.error) {
24
+ throw result.error;
25
+ }
26
+ return {
27
+ status: result.status ?? 1,
28
+ stdout: result.stdout ?? "",
29
+ stderr: result.stderr ?? ""
30
+ };
31
+ }
32
+
33
+ // src/core/errors.ts
34
+ var CheckpointerError = class extends Error {
35
+ code;
36
+ constructor(message, code = "error") {
37
+ super(message);
38
+ this.name = "CheckpointerError";
39
+ this.code = code;
40
+ }
41
+ };
42
+ function fail(message, code) {
43
+ throw new CheckpointerError(message, code);
44
+ }
45
+
46
+ // src/core/git.ts
47
+ var IDENTITY = [
48
+ "-c",
49
+ "user.name=checkpointer",
50
+ "-c",
51
+ "user.email=checkpointer@local",
52
+ "-c",
53
+ "commit.gpgsign=false"
54
+ ];
55
+ var ShadowGit = class {
56
+ constructor(gitDir, workTree) {
57
+ this.gitDir = gitDir;
58
+ this.workTree = workTree;
59
+ }
60
+ gitDir;
61
+ workTree;
62
+ base() {
63
+ return [`--git-dir=${this.gitDir}`, `--work-tree=${this.workTree}`];
64
+ }
65
+ run(args, input) {
66
+ return run("git", [...this.base(), ...args], { input });
67
+ }
68
+ capture(args, context) {
69
+ const result = this.run(args);
70
+ if (result.status !== 0) {
71
+ fail(`git ${context} failed: ${result.stderr.trim() || result.stdout.trim()}`);
72
+ }
73
+ return result.stdout.trim();
74
+ }
75
+ init() {
76
+ this.capture(["init", "-q"], "init");
77
+ this.run(["symbolic-ref", "HEAD", "refs/heads/checkpoints"]);
78
+ }
79
+ hasCommits() {
80
+ return this.run(["rev-parse", "--verify", "-q", "refs/heads/checkpoints"]).status === 0;
81
+ }
82
+ stageAll() {
83
+ this.capture(["add", "-A"], "stage");
84
+ }
85
+ commit(message) {
86
+ const args = [...IDENTITY, "commit", "-q", "--allow-empty", "-m", message];
87
+ const result = this.run(args);
88
+ if (result.status !== 0) {
89
+ fail(`git commit failed: ${result.stderr.trim() || result.stdout.trim()}`);
90
+ }
91
+ return this.capture(["rev-parse", "HEAD"], "rev-parse");
92
+ }
93
+ resolve(ref) {
94
+ const result = this.run(["rev-parse", "--verify", "-q", `${ref}^{commit}`]);
95
+ return result.status === 0 ? result.stdout.trim() : null;
96
+ }
97
+ restoreTree(sha) {
98
+ this.capture(["read-tree", "--reset", "-u", sha], "read-tree");
99
+ }
100
+ diff(from, to, paths = []) {
101
+ const args = ["diff", from, to];
102
+ if (paths.length) args.push("--", ...paths);
103
+ return this.capture(args, "diff");
104
+ }
105
+ diffWorkTree(from) {
106
+ return this.capture(["diff", from], "diff");
107
+ }
108
+ listFiles(sha) {
109
+ const out = this.capture(["ls-tree", "-r", "--name-only", sha], "ls-tree");
110
+ return out ? out.split("\n") : [];
111
+ }
112
+ diffStat(from, to) {
113
+ return this.capture(["diff", "--stat", from, to], "diff");
114
+ }
115
+ treeOf(sha) {
116
+ return this.capture(["rev-parse", `${sha}^{tree}`], "rev-parse");
117
+ }
118
+ get path() {
119
+ return this.gitDir;
120
+ }
121
+ };
122
+
123
+ // src/core/metadata.ts
124
+ import { existsSync, readFileSync, writeFileSync, renameSync } from "fs";
125
+ var STATUSES = ["working", "wip", "broken"];
126
+ function empty(root) {
127
+ return { version: 1, root, shippedSeq: 0, checkpoints: [] };
128
+ }
129
+ function read(file, root) {
130
+ if (!existsSync(file)) return empty(root);
131
+ let parsed;
132
+ try {
133
+ parsed = JSON.parse(readFileSync(file, "utf8"));
134
+ } catch {
135
+ fail(`checkpoint metadata at ${file} is corrupt (invalid JSON)`);
136
+ }
137
+ const data = parsed;
138
+ if (data?.version !== 1 || !Array.isArray(data.checkpoints) || typeof data.shippedSeq !== "number") {
139
+ fail(`checkpoint metadata at ${file} is invalid or from an unsupported version`);
140
+ }
141
+ return data;
142
+ }
143
+ var Metadata = class _Metadata {
144
+ constructor(file, data) {
145
+ this.file = file;
146
+ this.data = data;
147
+ }
148
+ file;
149
+ data;
150
+ static load(paths) {
151
+ return new _Metadata(paths.metaFile, read(paths.metaFile, paths.root));
152
+ }
153
+ // Re-read from disk; call under the lock before a read-modify-write so we
154
+ // never compute a sequence number from a stale in-memory snapshot.
155
+ reload() {
156
+ this.data = read(this.file, this.data.root);
157
+ }
158
+ save() {
159
+ const tmp = `${this.file}.${process.pid}.tmp`;
160
+ writeFileSync(tmp, JSON.stringify(this.data, null, 2) + "\n");
161
+ renameSync(tmp, this.file);
162
+ }
163
+ all() {
164
+ return this.data.checkpoints;
165
+ }
166
+ shippedSeq() {
167
+ return this.data.shippedSeq;
168
+ }
169
+ nextSeq() {
170
+ return this.data.checkpoints.reduce((max, cp) => Math.max(max, cp.seq), 0) + 1;
171
+ }
172
+ nameTaken(name) {
173
+ return this.data.checkpoints.some((cp) => cp.name === name);
174
+ }
175
+ // Derive a name that does not collide with an existing checkpoint, suffixing
176
+ // -2, -3, … as needed. Used for auto/default names, which must never fail.
177
+ uniqueName(base) {
178
+ if (!this.nameTaken(base)) return base;
179
+ for (let n = 2; ; n++) {
180
+ const candidate = `${base}-${n}`;
181
+ if (!this.nameTaken(candidate)) return candidate;
182
+ }
183
+ }
184
+ add(checkpoint) {
185
+ this.data.checkpoints.push(checkpoint);
186
+ this.save();
187
+ }
188
+ setStatus(seq, status2) {
189
+ const cp = this.data.checkpoints.find((c) => c.seq === seq);
190
+ if (cp) {
191
+ cp.status = status2;
192
+ this.save();
193
+ }
194
+ }
195
+ markShipped(seq) {
196
+ this.data.shippedSeq = Math.max(this.data.shippedSeq, seq);
197
+ this.save();
198
+ }
199
+ find(ref) {
200
+ if (ref.startsWith("#") && /^\d+$/.test(ref.slice(1))) {
201
+ const seq = Number(ref.slice(1));
202
+ return this.data.checkpoints.find((cp) => cp.seq === seq) ?? null;
203
+ }
204
+ const byName = this.data.checkpoints.find((cp) => cp.name === ref);
205
+ if (byName) return byName;
206
+ if (/^\d+$/.test(ref)) {
207
+ const bySeq = this.data.checkpoints.find((cp) => cp.seq === Number(ref));
208
+ if (bySeq) return bySeq;
209
+ }
210
+ return this.data.checkpoints.find((cp) => cp.sha.startsWith(ref)) ?? null;
211
+ }
212
+ require(ref) {
213
+ const cp = this.find(ref);
214
+ if (!cp) fail(`no checkpoint matches '${ref}' (try 'checkpointer list')`, "no_match");
215
+ return cp;
216
+ }
217
+ latest() {
218
+ return this.data.checkpoints.at(-1) ?? null;
219
+ }
220
+ latestManual() {
221
+ return [...this.data.checkpoints].reverse().find((cp) => !cp.auto) ?? null;
222
+ }
223
+ unshipped() {
224
+ return this.data.checkpoints.filter((cp) => cp.seq > this.data.shippedSeq && !cp.auto);
225
+ }
226
+ };
227
+
228
+ // src/core/paths.ts
229
+ import { homedir } from "os";
230
+ import { createHash } from "crypto";
231
+ import { join } from "path";
232
+ function home() {
233
+ return process.env.CHECKPOINTER_HOME ?? join(homedir(), ".checkpointer");
234
+ }
235
+ function projectId(root) {
236
+ return createHash("sha256").update(root).digest("hex").slice(0, 12);
237
+ }
238
+ function projectPaths(root) {
239
+ const id = projectId(root);
240
+ const dir = join(home(), "projects", id);
241
+ return {
242
+ id,
243
+ root,
244
+ dir,
245
+ gitDir: join(dir, "repo.git"),
246
+ metaFile: join(dir, "meta.json"),
247
+ ignoreFile: join(dir, "ignore"),
248
+ lockFile: join(dir, "lock")
249
+ };
250
+ }
251
+
252
+ // src/core/ignore.ts
253
+ import { existsSync as existsSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync2, mkdirSync } from "fs";
254
+ import { join as join2 } from "path";
255
+ var DEFAULT_EXCLUDES = [
256
+ ".git/",
257
+ "node_modules/",
258
+ ".env",
259
+ ".env.*",
260
+ "*.pem",
261
+ "*.key",
262
+ "secrets.*",
263
+ ".DS_Store"
264
+ ];
265
+ function userPatterns(paths) {
266
+ if (!existsSync2(paths.ignoreFile)) return [];
267
+ return readFileSync2(paths.ignoreFile, "utf8").split("\n").map((line) => line.trim()).filter((line) => line && !line.startsWith("#"));
268
+ }
269
+ function effectivePatterns(paths) {
270
+ return [...DEFAULT_EXCLUDES, ...userPatterns(paths)];
271
+ }
272
+ function writeExcludes(paths) {
273
+ const infoDir = join2(paths.gitDir, "info");
274
+ mkdirSync(infoDir, { recursive: true });
275
+ const body = effectivePatterns(paths).join("\n") + "\n";
276
+ writeFileSync2(join2(infoDir, "exclude"), body);
277
+ }
278
+
279
+ // src/core/project.ts
280
+ import { realpathSync } from "fs";
281
+ function resolveRoot(cwd = process.cwd()) {
282
+ const result = run("git", ["rev-parse", "--show-toplevel"], { cwd });
283
+ const top = result.stdout.trim();
284
+ const base = result.status === 0 && top ? top : cwd;
285
+ return realpathSync(base);
286
+ }
287
+ function isGitRepo(root) {
288
+ return run("git", ["rev-parse", "--git-dir"], { cwd: root }).status === 0;
289
+ }
290
+ function requireGitRepo(root) {
291
+ if (!isGitRepo(root)) {
292
+ fail(`not a git repository: ${root}
293
+ Run 'git init' first so checkpointer can ship to it.`, "not_a_repo");
294
+ }
295
+ }
296
+
297
+ // src/core/lock.ts
298
+ import { writeFileSync as writeFileSync3, linkSync, unlinkSync, readFileSync as readFileSync3, statSync, mkdirSync as mkdirSync2 } from "fs";
299
+ import { dirname } from "path";
300
+ var RETRY_MS = 50;
301
+ var TIMEOUT_MS = 1e4;
302
+ var STALE_MS = 6e4;
303
+ function sleep(ms) {
304
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
305
+ }
306
+ function liveHolder(file) {
307
+ let pid = 0;
308
+ try {
309
+ pid = Number(readFileSync3(file, "utf8").trim());
310
+ } catch {
311
+ return false;
312
+ }
313
+ if (Number.isInteger(pid) && pid > 0) {
314
+ try {
315
+ process.kill(pid, 0);
316
+ return true;
317
+ } catch (err) {
318
+ return err.code === "EPERM";
319
+ }
320
+ }
321
+ try {
322
+ return Date.now() - statSync(file).mtimeMs < STALE_MS;
323
+ } catch {
324
+ return false;
325
+ }
326
+ }
327
+ var held = /* @__PURE__ */ new Set();
328
+ function withLock(file, fn) {
329
+ if (held.has(file)) return fn();
330
+ mkdirSync2(dirname(file), { recursive: true });
331
+ const temp = `${file}.${process.pid}`;
332
+ writeFileSync3(temp, String(process.pid));
333
+ const deadline = Date.now() + TIMEOUT_MS;
334
+ try {
335
+ for (; ; ) {
336
+ try {
337
+ linkSync(temp, file);
338
+ break;
339
+ } catch (err) {
340
+ if (err.code !== "EEXIST") throw err;
341
+ if (!liveHolder(file)) {
342
+ try {
343
+ unlinkSync(file);
344
+ } catch {
345
+ }
346
+ continue;
347
+ }
348
+ if (Date.now() > deadline) {
349
+ fail("another checkpointer operation is in progress \u2014 try again in a moment");
350
+ }
351
+ sleep(RETRY_MS);
352
+ }
353
+ }
354
+ } finally {
355
+ try {
356
+ unlinkSync(temp);
357
+ } catch {
358
+ }
359
+ }
360
+ held.add(file);
361
+ try {
362
+ return fn();
363
+ } finally {
364
+ held.delete(file);
365
+ try {
366
+ unlinkSync(file);
367
+ } catch {
368
+ }
369
+ }
370
+ }
371
+
372
+ // src/core/store.ts
373
+ var Store = class _Store {
374
+ paths;
375
+ git;
376
+ meta;
377
+ constructor(paths) {
378
+ this.paths = paths;
379
+ this.git = new ShadowGit(paths.gitDir, paths.root);
380
+ this.meta = Metadata.load(paths);
381
+ }
382
+ static open(root = resolveRoot()) {
383
+ const paths = projectPaths(root);
384
+ if (!existsSync3(paths.gitDir)) {
385
+ fail("checkpointer is not initialized here \u2014 run 'checkpointer init' first", "not_initialized");
386
+ }
387
+ return new _Store(paths);
388
+ }
389
+ static init(root = resolveRoot()) {
390
+ const paths = projectPaths(root);
391
+ const fresh = !existsSync3(paths.gitDir);
392
+ mkdirSync3(paths.dir, { recursive: true });
393
+ const store = new _Store(paths);
394
+ if (fresh) store.git.init();
395
+ writeExcludes(paths);
396
+ return store;
397
+ }
398
+ static isInitialized(root) {
399
+ return existsSync3(projectPaths(root).gitDir);
400
+ }
401
+ save(input) {
402
+ return withLock(this.paths.lockFile, () => {
403
+ this.meta.reload();
404
+ writeExcludes(this.paths);
405
+ const seq = this.meta.nextSeq();
406
+ const auto = input.auto ?? false;
407
+ let name;
408
+ if (input.name === void 0) {
409
+ name = this.meta.uniqueName(`cp-${seq}`);
410
+ } else if (auto) {
411
+ name = this.meta.uniqueName(input.name);
412
+ } else {
413
+ if (this.meta.nameTaken(input.name)) {
414
+ fail(`a checkpoint named '${input.name}' already exists`, "name_taken");
415
+ }
416
+ name = input.name;
417
+ }
418
+ this.git.stageAll();
419
+ const message = input.message ?? name;
420
+ const sha = this.git.commit(`[${seq}] ${name}: ${message}`);
421
+ const checkpoint = {
422
+ seq,
423
+ name,
424
+ sha,
425
+ status: input.status,
426
+ message,
427
+ author: input.author,
428
+ agent: input.agent,
429
+ session: input.session,
430
+ intent: input.intent,
431
+ auto,
432
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
433
+ };
434
+ this.meta.add(checkpoint);
435
+ return checkpoint;
436
+ });
437
+ }
438
+ setStatus(seq, status2) {
439
+ withLock(this.paths.lockFile, () => {
440
+ this.meta.reload();
441
+ this.meta.setStatus(seq, status2);
442
+ });
443
+ }
444
+ restore(target, safetyAuthor) {
445
+ return withLock(this.paths.lockFile, () => {
446
+ const safety = this.save({
447
+ name: `before-restore-${target.name}`,
448
+ message: `auto-saved before restoring ${target.name}`,
449
+ status: "wip",
450
+ author: safetyAuthor,
451
+ agent: null,
452
+ session: null,
453
+ intent: null,
454
+ auto: true
455
+ });
456
+ this.git.restoreTree(target.sha);
457
+ return safety;
458
+ });
459
+ }
460
+ };
461
+
462
+ // src/core/identity.ts
463
+ function resolveIdentity(root, overrides = {}) {
464
+ const agent = overrides.agent ?? process.env.CHECKPOINTER_AGENT ?? null;
465
+ const session = overrides.session ?? process.env.CHECKPOINTER_SESSION ?? null;
466
+ const intent = overrides.intent ?? process.env.CHECKPOINTER_INTENT ?? null;
467
+ const author = overrides.author ?? process.env.CHECKPOINTER_AUTHOR ?? gitUser(root) ?? (agent ? agent : "you");
468
+ return { author, agent, session, intent };
469
+ }
470
+ function gitUser(root) {
471
+ const result = run("git", ["config", "user.name"], { cwd: root });
472
+ const name = result.stdout.trim();
473
+ return result.status === 0 && name ? name : null;
474
+ }
475
+
476
+ // src/core/ship.ts
477
+ function planShip(store, uptoRef) {
478
+ const upto = uptoRef ? store.meta.require(uptoRef) : latestOrFail(store);
479
+ if (upto.auto) {
480
+ fail(`'${upto.name}' is an auto safety checkpoint \u2014 ship to a manual checkpoint instead`, "auto_target");
481
+ }
482
+ const all = store.meta.all();
483
+ const shippedSeq = store.meta.shippedSeq();
484
+ const from = all.find((cp) => cp.seq === shippedSeq) ?? null;
485
+ const included = all.filter((cp) => cp.seq > shippedSeq && cp.seq <= upto.seq && !cp.auto);
486
+ return {
487
+ upto,
488
+ from,
489
+ included,
490
+ files: store.git.listFiles(upto.sha),
491
+ diffStat: from ? store.git.diffStat(from.sha, upto.sha) : "(everything \u2014 nothing shipped yet)"
492
+ };
493
+ }
494
+ function executeShip(store, plan, message, author) {
495
+ return withLock(store.paths.lockFile, () => {
496
+ store.meta.reload();
497
+ if (!plan.included.length) {
498
+ fail(`nothing to ship \u2014 no unshipped checkpoints up to ${plan.upto.name}`, "nothing_to_ship");
499
+ }
500
+ const root = store.paths.root;
501
+ const fetch = run("git", ["fetch", "--no-tags", "-q", store.git.path, "refs/heads/checkpoints"], { cwd: root });
502
+ if (fetch.status !== 0) fail(`could not read checkpoints into the repo: ${fetch.stderr.trim()}`);
503
+ const tree = store.git.treeOf(plan.upto.sha);
504
+ const parent = run("git", ["rev-parse", "--verify", "-q", "HEAD"], { cwd: root }).stdout.trim();
505
+ if (parent) {
506
+ const headTree = run("git", ["rev-parse", "HEAD^{tree}"], { cwd: root }).stdout.trim();
507
+ if (headTree === tree) {
508
+ fail(`nothing to commit \u2014 your repo already matches checkpoint ${plan.upto.name}`, "nothing_to_commit");
509
+ }
510
+ }
511
+ const args = ["commit-tree", tree, "-m", message];
512
+ if (parent) args.push("-p", parent);
513
+ const built = run("git", args, {
514
+ cwd: root,
515
+ env: { ...process.env, GIT_AUTHOR_NAME: author, GIT_COMMITTER_NAME: author }
516
+ });
517
+ if (built.status !== 0) fail(`git commit-tree failed: ${built.stderr.trim()}`);
518
+ const commit = built.stdout.trim();
519
+ const update = run("git", ["update-ref", "HEAD", commit], { cwd: root });
520
+ if (update.status !== 0) fail(`git update-ref failed: ${update.stderr.trim()}`);
521
+ run("git", ["reset", "-q", "--mixed", "HEAD"], { cwd: root });
522
+ store.meta.markShipped(plan.upto.seq);
523
+ return { commit, message };
524
+ });
525
+ }
526
+ function latestOrFail(store) {
527
+ const latest = store.meta.latestManual();
528
+ if (!latest) fail("no checkpoints to ship \u2014 run 'checkpointer save' first", "nothing_to_ship");
529
+ return latest;
530
+ }
531
+
532
+ // src/ui/format.ts
533
+ import pc from "picocolors";
534
+ function statusBadge(status2) {
535
+ switch (status2) {
536
+ case "working":
537
+ return pc.green("\u25CF working");
538
+ case "wip":
539
+ return pc.yellow("\u25CF wip");
540
+ case "broken":
541
+ return pc.red("\u25CF broken");
542
+ }
543
+ }
544
+ function relativeTime(iso) {
545
+ const then = new Date(iso).getTime();
546
+ const seconds = Math.round((Date.now() - then) / 1e3);
547
+ if (seconds < 60) return `${seconds}s ago`;
548
+ const minutes = Math.round(seconds / 60);
549
+ if (minutes < 60) return `${minutes}m ago`;
550
+ const hours = Math.round(minutes / 60);
551
+ if (hours < 24) return `${hours}h ago`;
552
+ return `${Math.round(hours / 24)}d ago`;
553
+ }
554
+ function who(cp) {
555
+ return cp.agent ? `${cp.author} via ${cp.agent}` : cp.author;
556
+ }
557
+ function checkpointLine(cp, shippedSeq) {
558
+ const marker = cp.seq <= shippedSeq ? pc.dim("\u2713") : cp.auto ? pc.dim("\xB7") : " ";
559
+ const id = pc.cyan(`#${cp.seq}`.padEnd(4));
560
+ const label = cp.auto ? pc.dim(cp.name.padEnd(22)) : pc.bold(cp.name.padEnd(22));
561
+ return `${marker} ${id} ${label} ${statusBadge(cp.status).padEnd(20)} ${pc.dim(relativeTime(cp.createdAt).padStart(8))} ${cp.message}`;
562
+ }
563
+ function heading(text) {
564
+ return pc.bold(pc.underline(text));
565
+ }
566
+ var ok = (text) => pc.green(text);
567
+ var dim = (text) => pc.dim(text);
568
+
569
+ // src/actions.ts
570
+ function parseStatus(value, fallback) {
571
+ if (!value) return fallback;
572
+ if (!STATUSES.includes(value)) {
573
+ fail(`invalid status '${value}' (expected: ${STATUSES.join(", ")})`, "invalid_status");
574
+ }
575
+ return value;
576
+ }
577
+ function emit(json2, data, render) {
578
+ if (json2) {
579
+ process.stdout.write(JSON.stringify(data, null, 2) + "\n");
580
+ } else {
581
+ render();
582
+ }
583
+ }
584
+ function init(opts = {}) {
585
+ const root = resolveRoot();
586
+ requireGitRepo(root);
587
+ const existed = Store.isInitialized(root);
588
+ const store = Store.init(root);
589
+ emit(opts.json ?? false, { initialized: true, alreadyExisted: existed, id: store.paths.id, dir: store.paths.dir }, () => {
590
+ console.log(existed ? dim("checkpointer already initialized") : ok("\u2713 checkpointer initialized"));
591
+ console.log(dim(` checkpoints stored in ${store.paths.dir}`));
592
+ console.log(dim(` your project's git history is never touched`));
593
+ });
594
+ }
595
+ function save(name, opts) {
596
+ const root = resolveRoot();
597
+ requireGitRepo(root);
598
+ const store = Store.isInitialized(root) ? Store.open(root) : Store.init(root);
599
+ const id = resolveIdentity(root, {
600
+ author: opts.author,
601
+ agent: opts.agent,
602
+ session: opts.session,
603
+ intent: opts.intent
604
+ });
605
+ const cp = store.save({
606
+ name,
607
+ message: opts.message,
608
+ status: parseStatus(opts.status, "wip"),
609
+ ...id
610
+ });
611
+ emit(opts.json ?? false, cp, () => {
612
+ console.log(`${ok("\u2713 saved")} ${pc2.cyan(`#${cp.seq}`)} ${pc2.bold(cp.name)} ${statusBadge(cp.status)}`);
613
+ if (cp.intent) console.log(dim(` intent: ${cp.intent}`));
614
+ });
615
+ }
616
+ function list(opts = {}) {
617
+ const store = Store.open();
618
+ const checkpoints = store.meta.all();
619
+ emit(opts.json ?? false, { shippedSeq: store.meta.shippedSeq(), checkpoints }, () => {
620
+ if (!checkpoints.length) {
621
+ console.log(dim("no checkpoints yet \u2014 run 'checkpointer save'"));
622
+ return;
623
+ }
624
+ const shipped = store.meta.shippedSeq();
625
+ for (const cp of checkpoints) console.log(checkpointLine(cp, shipped));
626
+ const legend = [];
627
+ if (shipped > 0) legend.push("\u2713 shipped to git");
628
+ if (checkpoints.some((cp) => cp.auto)) legend.push("\xB7 auto safety checkpoint");
629
+ if (legend.length) console.log(dim(`
630
+ ${legend.join(" ")}`));
631
+ });
632
+ }
633
+ function show(ref, opts = {}) {
634
+ const store = Store.open();
635
+ const cp = store.meta.require(ref);
636
+ const files = store.git.listFiles(cp.sha);
637
+ emit(opts.json ?? false, { ...cp, files }, () => {
638
+ console.log(`${pc2.cyan(`#${cp.seq}`)} ${pc2.bold(cp.name)} ${statusBadge(cp.status)}`);
639
+ console.log(` message ${cp.message}`);
640
+ console.log(` by ${who(cp)}`);
641
+ if (cp.session) console.log(` session ${cp.session}`);
642
+ if (cp.intent) console.log(` intent ${cp.intent}`);
643
+ console.log(` created ${cp.createdAt} (${relativeTime(cp.createdAt)})`);
644
+ console.log(` commit ${cp.sha.slice(0, 12)}`);
645
+ console.log(dim(` ${files.length} file(s) tracked`));
646
+ });
647
+ }
648
+ function diff(refA, refB, opts = {}) {
649
+ const store = Store.open();
650
+ const a = store.meta.require(refA);
651
+ if (refB) {
652
+ const b = store.meta.require(refB);
653
+ const patch = store.git.diff(a.sha, b.sha);
654
+ emit(opts.json ?? false, { from: a.name, to: b.name, patch }, () => process.stdout.write(patch + "\n"));
655
+ } else {
656
+ store.git.stageAll();
657
+ const patch = store.git.diffWorkTree(a.sha);
658
+ emit(opts.json ?? false, { from: a.name, to: "working-tree", patch }, () => process.stdout.write(patch + "\n"));
659
+ }
660
+ }
661
+ function restore(ref, opts = {}) {
662
+ const store = Store.open();
663
+ const target = store.meta.require(ref);
664
+ const id = resolveIdentity(store.paths.root);
665
+ const safety = store.restore(target, id.author);
666
+ emit(opts.json ?? false, { restored: target.name, safety: safety.name }, () => {
667
+ console.log(`${ok("\u2713 restored")} working tree to ${pc2.bold(target.name)} ${pc2.cyan(`#${target.seq}`)}`);
668
+ console.log(dim(` current state was auto-saved as '${safety.name}' (#${safety.seq}) \u2014 restore it to undo`));
669
+ });
670
+ }
671
+ function tag(ref, status2, opts = {}) {
672
+ const store = Store.open();
673
+ const cp = store.meta.require(ref);
674
+ const next = parseStatus(status2, cp.status);
675
+ store.setStatus(cp.seq, next);
676
+ emit(opts.json ?? false, { seq: cp.seq, name: cp.name, status: next }, () => {
677
+ console.log(`${ok("\u2713 tagged")} ${pc2.bold(cp.name)} as ${statusBadge(next)}`);
678
+ });
679
+ }
680
+ function status(opts = {}) {
681
+ const root = resolveRoot();
682
+ if (!Store.isInitialized(root)) {
683
+ emit(
684
+ opts.json ?? false,
685
+ { initialized: false },
686
+ () => console.log(dim("checkpointer not initialized here \u2014 run 'checkpointer init'"))
687
+ );
688
+ return;
689
+ }
690
+ const store = Store.open(root);
691
+ const all = store.meta.all();
692
+ const shipped = store.meta.shippedSeq();
693
+ const pending = store.meta.unshipped();
694
+ const latest = store.meta.latestManual();
695
+ emit(
696
+ opts.json ?? false,
697
+ { initialized: true, root, total: all.length, pending: pending.length, shippedSeq: shipped, latest },
698
+ () => {
699
+ console.log(`${heading("checkpointer")} ${dim(root)}`);
700
+ console.log(` ${all.length} checkpoint(s), ${pending.length} unshipped`);
701
+ if (latest) console.log(` latest: ${pc2.bold(latest.name)} ${statusBadge(latest.status)} ${dim(relativeTime(latest.createdAt))}`);
702
+ if (pending.length) console.log(dim(` run 'checkpointer ship -m "..."' to bundle them into one commit`));
703
+ }
704
+ );
705
+ }
706
+ function ship(opts) {
707
+ const root = resolveRoot();
708
+ requireGitRepo(root);
709
+ const store = Store.open(root);
710
+ const plan = planShip(store, opts.upto);
711
+ const broken = plan.included.filter((cp) => cp.status === "broken");
712
+ if (broken.length && !opts.force) {
713
+ fail(
714
+ `refusing to ship: ${broken.map((c) => c.name).join(", ")} tagged 'broken'
715
+ re-tag them or pass --force to ship anyway`,
716
+ "broken_refusal"
717
+ );
718
+ }
719
+ if (opts.dryRun) {
720
+ emit(opts.json ?? false, { dryRun: true, ...summarizePlan(plan) }, () => renderPlan(plan));
721
+ return;
722
+ }
723
+ if (!opts.message) fail('a commit message is required: checkpointer ship -m "your message"', "missing_message");
724
+ const id = resolveIdentity(root);
725
+ const result = executeShip(store, plan, opts.message, id.author);
726
+ emit(opts.json ?? false, { committed: result.commit, message: result.message, ...summarizePlan(plan) }, () => {
727
+ console.log(`${ok("\u2713 shipped")} ${plan.included.length} checkpoint(s) as one commit`);
728
+ console.log(` ${pc2.yellow(result.commit.slice(0, 12))} ${result.message.split("\n")[0]}`);
729
+ console.log(dim(` your uncommitted and untracked changes were left untouched`));
730
+ console.log(dim(` push when ready: git push`));
731
+ });
732
+ }
733
+ function summarizePlan(plan) {
734
+ return {
735
+ upto: plan.upto.name,
736
+ from: plan.from?.name ?? null,
737
+ included: plan.included.map((cp) => ({ seq: cp.seq, name: cp.name, status: cp.status })),
738
+ fileCount: plan.files.length
739
+ };
740
+ }
741
+ function renderPlan(plan) {
742
+ console.log(heading("ship plan (dry run)"));
743
+ console.log(` base: ${plan.from ? plan.from.name : "(empty \u2014 first ship)"}`);
744
+ console.log(` upto: ${pc2.bold(plan.upto.name)} ${pc2.cyan(`#${plan.upto.seq}`)}`);
745
+ console.log(` bundles ${plan.included.length} checkpoint(s):`);
746
+ for (const cp of plan.included) console.log(` ${pc2.cyan(`#${cp.seq}`)} ${cp.name} ${statusBadge(cp.status)}`);
747
+ console.log(dim("\n" + (plan.diffStat || "(no changes)")));
748
+ console.log(dim('\nrun without --dry-run and with -m "message" to commit'));
749
+ }
750
+ function info(opts = {}) {
751
+ const root = resolveRoot();
752
+ const store = Store.isInitialized(root) ? Store.open(root) : null;
753
+ const patterns = store ? effectivePatterns(store.paths) : [];
754
+ emit(
755
+ opts.json ?? false,
756
+ { root, initialized: !!store, dir: store?.paths.dir, ignoreFile: store?.paths.ignoreFile, excluded: patterns },
757
+ () => {
758
+ console.log(`${heading("checkpointer config")}`);
759
+ console.log(` project root: ${root}`);
760
+ console.log(` initialized: ${store ? "yes" : "no"}`);
761
+ if (store) console.log(` storage dir: ${store.paths.dir}`);
762
+ console.log(` excluded (never snapshotted or restored over):`);
763
+ for (const p of patterns) console.log(dim(` ${p}`));
764
+ if (store) console.log(dim(` add patterns by editing ${store.paths.ignoreFile}`));
765
+ }
766
+ );
767
+ }
768
+
769
+ // src/skill.ts
770
+ import { cpSync, existsSync as existsSync4, mkdirSync as mkdirSync4, rmSync } from "fs";
771
+ import { homedir as homedir2 } from "os";
772
+ import { dirname as dirname2, join as join3 } from "path";
773
+ import { fileURLToPath } from "url";
774
+ function packagedSkillDir() {
775
+ const here = dirname2(fileURLToPath(import.meta.url));
776
+ const candidates = [
777
+ join3(here, "..", "skills", "checkpointer"),
778
+ join3(here, "..", "..", "skills", "checkpointer")
779
+ ];
780
+ const found = candidates.find((dir) => existsSync4(join3(dir, "SKILL.md")));
781
+ if (!found) fail("bundled skill not found \u2014 reinstall the package");
782
+ return found;
783
+ }
784
+ function installSkill(opts = {}) {
785
+ const source = packagedSkillDir();
786
+ const target = opts.dir ?? join3(homedir2(), ".claude", "skills", "checkpointer");
787
+ mkdirSync4(dirname2(target), { recursive: true });
788
+ rmSync(target, { recursive: true, force: true });
789
+ cpSync(source, target, { recursive: true });
790
+ if (opts.json) {
791
+ process.stdout.write(JSON.stringify({ installed: true, target }, null, 2) + "\n");
792
+ return;
793
+ }
794
+ console.log(`${ok("\u2713 installed")} checkpointer skill to ${target}`);
795
+ console.log(dim(" Claude Code will pick it up next session. Cursor/other agents: see the README."));
796
+ }
797
+ function skillPath(opts = {}) {
798
+ const source = packagedSkillDir();
799
+ if (opts.json) {
800
+ process.stdout.write(JSON.stringify({ path: source }, null, 2) + "\n");
801
+ return;
802
+ }
803
+ console.log(source);
804
+ }
805
+
806
+ // src/cli.ts
807
+ var VERSION = "0.1.0";
808
+ var program = new Command();
809
+ program.name("checkpointer").description(
810
+ "Git-isolated checkpoints that humans and AI agents share.\n\nSave working states during a long task, revert when something breaks,\nthen bundle a range of checkpoints into one clean commit on your repo.\nYour project's real git history is never touched until you 'ship'."
811
+ ).version(VERSION, "-v, --version", "print version").showHelpAfterError("(run 'checkpointer --help' for usage)").configureHelp({ showGlobalOptions: true });
812
+ program.addHelpText(
813
+ "after",
814
+ `
815
+ ${pc3.bold("Examples:")}
816
+ ${pc3.dim("$")} checkpointer init initialize checkpointing here
817
+ ${pc3.dim("$")} checkpointer save snapshot the working tree
818
+ ${pc3.dim("$")} checkpointer save login --status working -m "login works"
819
+ ${pc3.dim("$")} checkpointer list see all checkpoints
820
+ ${pc3.dim("$")} checkpointer restore login roll back to a checkpoint
821
+ ${pc3.dim("$")} checkpointer ship -m "Add login flow" bundle into one commit
822
+
823
+ ${pc3.bold("Identifying checkpoints:")} by name (login), sequence (#4), or short sha.
824
+
825
+ ${pc3.bold("For AI agents:")} set CHECKPOINTER_AGENT and CHECKPOINTER_SESSION env vars
826
+ so saves are attributed. Run 'checkpointer skill install' to teach Claude Code.
827
+
828
+ Docs: https://github.com/checkpointer/checkpointer`
829
+ );
830
+ var json = ["--json", "output machine-readable JSON"];
831
+ program.command("init").description("initialize checkpointing for this project").option(...json).action((opts) => init(opts));
832
+ program.command("save [name]").description("snapshot the working tree as a checkpoint").option("-m, --message <text>", "describe what this checkpoint contains").option("-s, --status <status>", "working | wip | broken (default: wip)").option("--intent <text>", "why this checkpoint is being made (useful for agents)").option("--author <name>", "override the author").option("--agent <name>", "agent making the checkpoint (or set CHECKPOINTER_AGENT)").option("--session <id>", "agent session id (or set CHECKPOINTER_SESSION)").option(...json).addHelpText(
833
+ "after",
834
+ '\nExamples:\n $ checkpointer save\n $ checkpointer save before-refactor --intent "extracting auth module"\n $ checkpointer save v1 --status working -m "first working version"'
835
+ ).action((name, opts) => save(name, opts));
836
+ program.command("list").alias("ls").description("list all checkpoints").option(...json).action((opts) => list(opts));
837
+ program.command("status").description("show how many checkpoints are unshipped").option(...json).action((opts) => status(opts));
838
+ program.command("show <id>").description("show details and tracked files of a checkpoint").option(...json).action((id, opts) => show(id, opts));
839
+ program.command("diff <a> [b]").description("diff two checkpoints, or one checkpoint vs the working tree").option(...json).addHelpText(
840
+ "after",
841
+ "\nExamples:\n $ checkpointer diff login compare 'login' to current files\n $ checkpointer diff login #6 compare two checkpoints"
842
+ ).action((a, b, opts) => diff(a, b, opts));
843
+ program.command("restore <id>").description("reset the working tree to a checkpoint (auto-saves current state first)").option(...json).action((id, opts) => restore(id, opts));
844
+ program.command("tag <id> <status>").description("mark a checkpoint working | wip | broken").option(...json).action((id, status2, opts) => tag(id, status2, opts));
845
+ program.command("ship").description("bundle unshipped checkpoints into one commit on your real repo").option("-u, --upto <id>", "ship up to this checkpoint (default: latest)").option("-m, --message <text>", "commit message").option("--dry-run", "show what would be committed without committing").option("--force", "ship even if a checkpoint is tagged 'broken'").option(...json).addHelpText(
846
+ "after",
847
+ `
848
+ Ship never pushes \u2014 run 'git push' yourself afterward.
849
+ A safety checkpoint is auto-saved so a ship can be undone.
850
+
851
+ Examples:
852
+ $ checkpointer ship --dry-run
853
+ $ checkpointer ship -m "Add login flow"
854
+ $ checkpointer ship --upto v1 -m "Ship first version"`
855
+ ).action((opts) => ship(opts));
856
+ program.command("info").description("show storage location and excluded paths").option(...json).action((opts) => info(opts));
857
+ var skill = program.command("skill").description("manage the Claude / agent skill");
858
+ skill.command("install").description("install the skill into ~/.claude/skills so Claude Code can use checkpointer").option("--dir <path>", "install to a custom directory").option(...json).action((opts) => installSkill(opts));
859
+ skill.command("path").description("print the path to the bundled skill (for manual install)").option(...json).action((opts) => skillPath(opts));
860
+ async function main() {
861
+ try {
862
+ await program.parseAsync(process.argv);
863
+ } catch (error) {
864
+ if (error instanceof CheckpointerError) {
865
+ if (process.argv.includes("--json")) {
866
+ process.stdout.write(JSON.stringify({ error: error.message, code: error.code }) + "\n");
867
+ } else {
868
+ process.stderr.write(pc3.red("error: ") + error.message + "\n");
869
+ }
870
+ process.exit(1);
871
+ }
872
+ throw error;
873
+ }
874
+ }
875
+ void main();
package/package.json ADDED
@@ -0,0 +1,50 @@
1
+ {
2
+ "name": "checkpointer",
3
+ "version": "0.1.0",
4
+ "description": "Git-isolated checkpoints that humans and AI agents share — save working states, revert anytime, ship a range as one clean commit.",
5
+ "keywords": [
6
+ "checkpoint",
7
+ "git",
8
+ "ai",
9
+ "agent",
10
+ "claude",
11
+ "cursor",
12
+ "snapshot",
13
+ "undo",
14
+ "rollback",
15
+ "cli"
16
+ ],
17
+ "license": "Apache-2.0",
18
+ "type": "module",
19
+ "bin": {
20
+ "checkpointer": "dist/cli.js",
21
+ "ckpt": "dist/cli.js"
22
+ },
23
+ "files": [
24
+ "dist",
25
+ "skills",
26
+ "README.md",
27
+ "LICENSE"
28
+ ],
29
+ "engines": {
30
+ "node": ">=18"
31
+ },
32
+ "scripts": {
33
+ "build": "tsup",
34
+ "dev": "tsup --watch",
35
+ "test": "vitest run",
36
+ "test:watch": "vitest",
37
+ "typecheck": "tsc --noEmit",
38
+ "prepublishOnly": "npm run build"
39
+ },
40
+ "dependencies": {
41
+ "commander": "^12.1.0",
42
+ "picocolors": "^1.1.1"
43
+ },
44
+ "devDependencies": {
45
+ "@types/node": "^22.10.0",
46
+ "tsup": "^8.3.5",
47
+ "typescript": "^5.7.2",
48
+ "vitest": "^2.1.8"
49
+ }
50
+ }
@@ -0,0 +1,79 @@
1
+ ---
2
+ name: checkpointer
3
+ description: Save, restore, and ship git-isolated checkpoints during multi-step work. Use this skill when the user wants save points while you make changes, asks to undo/revert to an earlier state, or asks to bundle progress into a clean commit. Use it proactively — save a checkpoint before risky edits (large refactors, codemods, formatter runs, dependency upgrades) so the work can be rolled back.
4
+ ---
5
+
6
+ # checkpointer
7
+
8
+ `checkpointer` is a CLI that snapshots the working tree into a shadow git repo kept
9
+ outside the project. It never touches the project's real `.git`, so checkpoints never
10
+ appear in `git log`. At the end you bundle a range of checkpoints into one clean commit.
11
+
12
+ ## Setup
13
+
14
+ At the start of a session, identify yourself so checkpoints are attributed to you:
15
+
16
+ ```bash
17
+ export CHECKPOINTER_AGENT=claude-code
18
+ export CHECKPOINTER_SESSION="<session-or-task-id>"
19
+ ```
20
+
21
+ Optionally set `CHECKPOINTER_AUTHOR` to override the name attributed to checkpoints.
22
+ If `checkpointer` is not installed, run it through `npx checkpointer <command>`.
23
+
24
+ ## When to act
25
+
26
+ 1. **Before risky changes** — large refactors, codemods, `prettier`/`eslint --fix`,
27
+ dependency upgrades, or anything you are unsure about:
28
+ ```bash
29
+ checkpointer save --intent "why you are about to make this change"
30
+ ```
31
+ 2. **After reaching a known-good state** — tests pass, feature works:
32
+ ```bash
33
+ checkpointer save working-login --status working -m "login flow works end to end"
34
+ ```
35
+ 3. **When something breaks** — tag it so it won't be shipped, then keep going or roll back:
36
+ ```bash
37
+ checkpointer tag <id> broken
38
+ checkpointer restore <id> # roll the working tree back to a good checkpoint
39
+ ```
40
+ 4. **When the user says "ship it" / "commit this"** — review, then bundle into one commit:
41
+ ```bash
42
+ checkpointer status
43
+ checkpointer ship --dry-run # show what will be committed
44
+ checkpointer ship -m "Add login flow" # one clean commit on the current branch
45
+ ```
46
+ Tell the user to `git push` themselves — `ship` never pushes.
47
+
48
+ ## Status values
49
+
50
+ - `working` — verified good state
51
+ - `wip` — in progress (default)
52
+ - `broken` — known bad; `ship` refuses to include these unless `--force`
53
+
54
+ ## Rules
55
+
56
+ - Restoring is always safe: it auto-saves the current state first, so a restore can be undone.
57
+ - `ship` only adds a commit — it never overwrites the user's uncommitted or untracked work.
58
+ - Never run `ship` without showing `status` or `--dry-run` output to the user first.
59
+ - Don't `--force` past a `broken` checkpoint without telling the user why.
60
+ - To reassure the user that secrets are safe, run `checkpointer info` to show the exclusion list.
61
+ - Reference checkpoints by name (`login-fix`), sequence (`#4`), or short sha.
62
+
63
+ ## Command reference
64
+
65
+ | Command | Purpose |
66
+ | --- | --- |
67
+ | `checkpointer init` | Set up checkpointing here (save auto-inits; use to initialize deliberately) |
68
+ | `checkpointer save [name]` | Snapshot the working tree |
69
+ | `checkpointer list` | List checkpoints |
70
+ | `checkpointer status` | Show how many checkpoints are unshipped |
71
+ | `checkpointer show <id>` | Details + files in a checkpoint |
72
+ | `checkpointer diff <a> [b]` | Diff two checkpoints, or one vs the working tree |
73
+ | `checkpointer restore <id>` | Reset working tree to a checkpoint (auto-saves first) |
74
+ | `checkpointer tag <id> <status>` | Mark working / wip / broken |
75
+ | `checkpointer ship -m "msg"` | Bundle unshipped checkpoints into one commit |
76
+ | `checkpointer info` | Show storage location and excluded paths (e.g. .env, *.key) |
77
+
78
+ Add `--json` to any command for structured output. On failure with `--json`, the
79
+ command prints `{"error": "...", "code": "..."}` to stdout and exits non-zero.