@tduyng/pi-rewind 0.0.0-stage → 0.0.5

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,178 @@
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
+ Copyright 2026 tduyng
package/README.md CHANGED
@@ -1,3 +1,44 @@
1
- # Temporary Holding Version
1
+ # @tduyng/pi-rewind
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
+ `/tree` and `/fork` take the conversation back to an earlier prompt, and the files stay where the agent left them. The model then reasons about code that no longer matches what it sees, and undoing the agent's edits by hand is the work a rewind was meant to save.
4
+
5
+ This package takes the files back too. It adds nothing to a request: no tool, no prompt text.
6
+
7
+ ## How it works
8
+
9
+ Before each prompt runs, the work tree is written to a git commit under `refs/pi-rewind/<session>/before/<prompt entry>`. When a run settles, the end state goes under `after/<last entry>`. Tracked edits, deletions, and untracked files that are not ignored are all included. The snapshot goes through a temporary index, so your staging area, stash, branches, and `git status` never change.
10
+
11
+ Every snapshot is a fresh commit, even when the tree matches the last one. Git stores an identical tree once, so the extra cost is a commit object of about 200 bytes. The prune at session start drops refs whose commit is older than 14 days, and reusing an old commit for a new prompt once made that prune delete yesterday's checkpoint.
12
+
13
+ - `/tree` to an earlier prompt, or `/fork` from one, asks whether to rewind the files as well and lists what would change.
14
+ - `/rewind` picks a prompt on the current branch and rewinds only the files. The conversation stays, and the model is told on its next turn which paths changed under it. `/rewind 2` takes the second newest checkpoint without a picker, and a client with no UI takes the newest.
15
+ - `/rewind undo` reverses the last rewind. Every rewind first saves the current tree, so a rewind is never the last copy of anything.
16
+
17
+ A restore writes the files that differ and deletes the files the target never had. Files that are the same are left alone, so their timestamps do not change and a watcher does not rebuild them.
18
+
19
+ A file changed since the agent last finished is left alone too, and the confirm prompt lists it. That covers an edit you made in your editor, a `!` command, or another pi session in the same repository. The agent's own edits are the ones a rewind takes back.
20
+
21
+ ## Cost
22
+
23
+ Nothing in the context. The snapshot starts when the prompt is sent, and the first tool call waits for whatever is left of it, so no edit can land before the snapshot. Measured on this machine: about 95 ms on a repository of 419 tracked files and about 360 ms on one of 31,572. That is shorter than the model's first response, so the prompt does not wait.
24
+
25
+ Unchanged files share git objects with your history, so a snapshot stores only what differs. Refs older than 14 days are deleted at session start, and `git gc` reclaims their objects as it would any unreachable commit.
26
+
27
+ ## Install
28
+
29
+ ```bash
30
+ pi install npm:@tduyng/pi-rewind
31
+ ```
32
+
33
+ Local checkout: `pi install /path/to/dotfiles/pi/agent/extensions/pi-rewind`
34
+
35
+ Needs git 2.26 or newer. Outside a git work tree the package does nothing.
36
+
37
+ ## Limits
38
+
39
+ - An untracked file over 5 MiB is left out of every snapshot, so a rewind neither restores nor deletes it. Data files that are not ignored stay where they are.
40
+ - Ignored files are never touched.
41
+ - The staging area is not restored. A rewind changes the work tree only.
42
+ - A `/tree` target in the middle of a run has no snapshot of its own, so only prompts and the ends of runs can be rewound to.
43
+ - Two sessions running at the same time in one repository are not told apart. A file another session changes while this one runs counts as this session's edit.
44
+ - A forked session starts its own snapshots. Its copied prompts rewind from the parent session only through `/fork` itself.
package/package.json CHANGED
@@ -1,6 +1,42 @@
1
1
  {
2
2
  "name": "@tduyng/pi-rewind",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.5",
4
+ "description": "Go back in a session and the files go back too: a git snapshot before every prompt, restored on /tree, /fork and /rewind.",
5
+ "keywords": [
6
+ "pi",
7
+ "pi-package",
8
+ "pi-extension",
9
+ "pi-coding-agent",
10
+ "rewind",
11
+ "checkpoint",
12
+ "undo",
13
+ "git"
14
+ ],
15
+ "homepage": "https://gitlab.com/tduyng/pi-agent/-/tree/main/extensions/pi-rewind#readme",
16
+ "bugs": "https://gitlab.com/tduyng/pi-agent/-/issues",
17
+ "license": "Apache-2.0",
18
+ "author": "tduyng",
19
+ "repository": {
20
+ "type": "git",
21
+ "url": "git+https://gitlab.com/tduyng/pi-agent.git",
22
+ "directory": "extensions/pi-rewind"
23
+ },
24
+ "type": "module",
25
+ "files": [
26
+ "src",
27
+ "!src/**/*.test.ts",
28
+ "README.md",
29
+ "LICENSE"
30
+ ],
31
+ "peerDependencies": {
32
+ "@earendil-works/pi-coding-agent": "*"
33
+ },
34
+ "publishConfig": {
35
+ "access": "public"
36
+ },
37
+ "pi": {
38
+ "extensions": [
39
+ "./src/index.ts"
40
+ ]
41
+ }
42
+ }
package/src/index.ts ADDED
@@ -0,0 +1,234 @@
1
+ import type { ExtensionAPI, ExtensionContext, SessionEntry } from '@earendil-works/pi-coding-agent'
2
+ import { changes, listRefs, lookup, openRepo, prune, refName, restore, save, snapshot } from './snapshot.js'
3
+ import type { Change, Repo } from './snapshot.js'
4
+
5
+ const MAX_AGE_MS = 14 * 24 * 60 * 60 * 1000
6
+ const UNDO = 'undo'
7
+ const SETTLED = 'settled'
8
+
9
+ interface Run {
10
+ preLeaf: string | null
11
+ commit: Promise<string | null>
12
+ bound: boolean
13
+ }
14
+
15
+ type UserEntry = Extract<SessionEntry, { type: 'message' }> & { message: { role: 'user' } }
16
+
17
+ function isUserEntry(entry: SessionEntry | undefined): entry is UserEntry {
18
+ return entry?.type === 'message' && entry.message.role === 'user'
19
+ }
20
+
21
+ export function promptAfter(branch: SessionEntry[], preLeaf: string | null): UserEntry | undefined {
22
+ const start = preLeaf === null ? 0 : branch.findIndex((entry) => entry.id === preLeaf) + 1
23
+ if (start === 0 && preLeaf !== null) return undefined
24
+ return branch.slice(start).find(isUserEntry)
25
+ }
26
+
27
+ export function slotFor(entry: SessionEntry): string {
28
+ return isUserEntry(entry) ? `before/${entry.id}` : `after/${entry.id}`
29
+ }
30
+
31
+ export function promptText(entry: UserEntry): string {
32
+ const content = entry.message.content
33
+ const text = Array.isArray(content)
34
+ ? content.map((block) => (block.type === 'text' ? block.text : '')).join(' ')
35
+ : content
36
+ const line = text.replace(/\s+/g, ' ').trim()
37
+ return line.length > 60 ? `${line.slice(0, 59)}…` : line
38
+ }
39
+
40
+ function listChanges(diff: Change[]): string[] {
41
+ const sample = diff.slice(0, 5).map((change) => `${change.kind === 'delete' ? '-' : '~'} ${change.path}`)
42
+ return diff.length > sample.length ? [...sample, `and ${diff.length - sample.length} more`] : sample
43
+ }
44
+
45
+ export function describe(diff: Change[]): string {
46
+ const deleted = diff.filter((change) => change.kind === 'delete').length
47
+ return [`${diff.length - deleted} file(s) written, ${deleted} deleted`, ...listChanges(diff)].join('\n')
48
+ }
49
+
50
+ function describeKept(kept: Change[]): string {
51
+ return ['Left as they are, changed since the agent last finished:', ...listChanges(kept)].join('\n')
52
+ }
53
+
54
+ async function pickBySelect(
55
+ ctx: ExtensionContext,
56
+ options: string[],
57
+ prompts: UserEntry[]
58
+ ): Promise<UserEntry | undefined> {
59
+ const choice = await ctx.ui.select('Rewind files to before which prompt?', options)
60
+ return choice === undefined ? undefined : prompts[options.indexOf(choice)]
61
+ }
62
+
63
+ export default function rewindExtension(pi: ExtensionAPI): void {
64
+ let repo: Promise<Repo | null> = Promise.resolve(null)
65
+ let run: Run | undefined
66
+ let treeTarget: string | undefined
67
+
68
+ const ref = (ctx: ExtensionContext, slot: string) => refName(ctx.sessionManager.getSessionId(), slot)
69
+
70
+ async function bindPrompt(ctx: ExtensionContext): Promise<void> {
71
+ const current = run
72
+ if (!current || current.bound) return
73
+ current.bound = true
74
+ const [r, commit] = await Promise.all([repo, current.commit])
75
+ const prompt = promptAfter(ctx.sessionManager.getBranch(), current.preLeaf)
76
+ const name = prompt && ref(ctx, slotFor(prompt))
77
+ if (r && commit && name) await save(r, name, commit)
78
+ }
79
+
80
+ async function rewindTo(
81
+ ctx: ExtensionContext,
82
+ target: string,
83
+ title: string,
84
+ ask: boolean
85
+ ): Promise<Change[] | null> {
86
+ const r = await repo
87
+ const undo = ref(ctx, UNDO)
88
+ const settledRef = ref(ctx, SETTLED)
89
+ if (!r || !undo || !settledRef) return null
90
+ const current = await snapshot(r)
91
+ if (!current) return null
92
+ const settled = await lookup(r, settledRef)
93
+ const outside = new Set(settled ? (await changes(r, settled, current)).map((change) => change.path) : [])
94
+ const all = await changes(r, current, target)
95
+ const diff = all.filter((change) => !outside.has(change.path))
96
+ const kept = all.filter((change) => outside.has(change.path))
97
+ const detail = kept.length > 0 ? `${describe(diff)}\n\n${describeKept(kept)}` : describe(diff)
98
+ if (diff.length === 0 && kept.length > 0) {
99
+ ctx.ui.notify(`rewind: nothing to rewind.\n${describeKept(kept)}`, 'info')
100
+ return null
101
+ }
102
+ if (diff.length === 0) return diff
103
+ if (ask && !(await ctx.ui.confirm(title, detail))) return null
104
+ await save(r, undo, current)
105
+ await restore(r, target, diff)
106
+ const after = await snapshot(r)
107
+ if (after) await save(r, settledRef, after)
108
+ const note =
109
+ kept.length > 0
110
+ ? ` ${kept.length} file(s) changed since the agent last finished were left as they are.`
111
+ : ''
112
+ ctx.ui.notify(`Files rewound. ${describe(diff).split('\n', 1)[0]}.${note} /rewind undo puts them back.`, 'info')
113
+ return diff
114
+ }
115
+
116
+ async function offer(ctx: ExtensionContext, entryId: string): Promise<void> {
117
+ const entry = ctx.sessionManager.getEntry(entryId)
118
+ const r = await repo
119
+ const name = entry && ref(ctx, slotFor(entry))
120
+ if (!ctx.hasUI || !r || !name) return
121
+ const target = await lookup(r, name)
122
+ if (target) await rewindTo(ctx, target, 'Rewind files to this point too?', true)
123
+ }
124
+
125
+ pi.on('session_start', (_event, ctx) => {
126
+ repo = openRepo((command, args, options) => pi.exec(command, args, options), ctx.cwd)
127
+ void repo.then((r) => r && prune(r, Date.now() - MAX_AGE_MS)).catch(() => undefined)
128
+ })
129
+
130
+ pi.on('before_agent_start', async (_event, ctx) => {
131
+ run = {
132
+ preLeaf: ctx.sessionManager.getLeafId(),
133
+ commit: repo.then((r) => (r ? snapshot(r) : null)).catch(() => null),
134
+ bound: false
135
+ }
136
+ })
137
+
138
+ pi.on('tool_call', async (_event, ctx) => {
139
+ await bindPrompt(ctx).catch(() => undefined)
140
+ })
141
+
142
+ pi.on('agent_settled', async (_event, ctx) => {
143
+ try {
144
+ await bindPrompt(ctx)
145
+ run = undefined
146
+ const r = await repo
147
+ const leaf = ctx.sessionManager.getLeafEntry()
148
+ const name = leaf && ref(ctx, slotFor(leaf))
149
+ const settled = ref(ctx, SETTLED)
150
+ const commit = r && name ? await snapshot(r) : null
151
+ if (r && name && commit) await save(r, name, commit)
152
+ if (r && settled && commit) await save(r, settled, commit)
153
+ } catch {}
154
+ })
155
+
156
+ pi.on('session_before_tree', (event) => {
157
+ treeTarget = event.preparation.targetId
158
+ })
159
+
160
+ pi.on('session_tree', async (_event, ctx) => {
161
+ const target = treeTarget
162
+ treeTarget = undefined
163
+ if (target) await offer(ctx, target).catch((error: Error) => ctx.ui.notify(`rewind: ${error.message}`, 'error'))
164
+ })
165
+
166
+ pi.on('session_before_fork', async (event, ctx) => {
167
+ await offer(ctx, event.entryId).catch((error: Error) => ctx.ui.notify(`rewind: ${error.message}`, 'error'))
168
+ })
169
+
170
+ pi.registerCommand('rewind', {
171
+ description:
172
+ 'Put files back as they were before an earlier prompt. The conversation stays. `/rewind undo` reverses the last rewind.',
173
+ getArgumentCompletions: (prefix) => (UNDO.startsWith(prefix) ? [{ value: UNDO, label: UNDO }] : null),
174
+ handler: async (args, ctx) => {
175
+ const r = await repo
176
+ const undo = ref(ctx, UNDO)
177
+ if (!r || !undo) {
178
+ ctx.ui.notify('rewind: not a git work tree, nothing to rewind', 'warning')
179
+ return
180
+ }
181
+ let target: string | null = null
182
+ let label = ''
183
+ if (args.trim() === UNDO) {
184
+ target = await lookup(r, undo)
185
+ label = 'the state before the last rewind'
186
+ } else {
187
+ const prefix = ref(ctx, 'before/')
188
+ const saved = prefix ? await listRefs(r, prefix) : new Map<string, number>()
189
+ const prompts = ctx.sessionManager
190
+ .getBranch()
191
+ .filter(isUserEntry)
192
+ .filter((entry) => saved.has(`${prefix}${entry.id}`))
193
+ .toReversed()
194
+ if (prompts.length === 0) {
195
+ ctx.ui.notify('rewind: no file snapshot on this branch yet', 'warning')
196
+ return
197
+ }
198
+ const options = prompts.map((entry, i) => `${i + 1}. before "${promptText(entry)}"`)
199
+ // A headless client has nobody to ask, and an unanswered picker left the
200
+ // command doing nothing at all in RPC mode. The number picks the same entry a
201
+ // reader would have selected, newest first.
202
+ const wanted = Number(args.trim())
203
+ const picked =
204
+ Number.isInteger(wanted) && wanted >= 1
205
+ ? prompts[wanted - 1]
206
+ : ctx.hasUI
207
+ ? await pickBySelect(ctx, options, prompts)
208
+ : prompts[0]
209
+ if (!picked) return
210
+ const name = ref(ctx, slotFor(picked))
211
+ target = name ? await lookup(r, name) : null
212
+ label = `before "${promptText(picked)}"`
213
+ }
214
+ if (!target) {
215
+ ctx.ui.notify('rewind: that snapshot is gone', 'warning')
216
+ return
217
+ }
218
+ const diff = await rewindTo(ctx, target, `Rewind files to ${label}?`, ctx.hasUI)
219
+ if (diff === null) return
220
+ if (diff.length === 0) {
221
+ ctx.ui.notify('rewind: files already match', 'info')
222
+ return
223
+ }
224
+ pi.sendMessage(
225
+ {
226
+ customType: 'rewind',
227
+ content: `The user rewound the files to ${label}. The conversation was not rewound, so earlier edits to these paths are gone:\n${describe(diff)}`,
228
+ display: true
229
+ },
230
+ { deliverAs: 'nextTurn' }
231
+ )
232
+ }
233
+ })
234
+ }
@@ -0,0 +1,171 @@
1
+ import { randomUUID } from 'node:crypto'
2
+ import { copyFile, lstat, rm, rmdir, writeFile } from 'node:fs/promises'
3
+ import { dirname, join } from 'node:path'
4
+ import type { ExtensionAPI } from '@earendil-works/pi-coding-agent'
5
+
6
+ export const MAX_UNTRACKED_BYTES = 5 * 1024 * 1024
7
+
8
+ const IDENTITY = [
9
+ 'GIT_AUTHOR_NAME=pi-rewind',
10
+ 'GIT_AUTHOR_EMAIL=pi-rewind@localhost',
11
+ 'GIT_COMMITTER_NAME=pi-rewind',
12
+ 'GIT_COMMITTER_EMAIL=pi-rewind@localhost',
13
+ 'GIT_OPTIONAL_LOCKS=0'
14
+ ]
15
+
16
+ export type Exec = ExtensionAPI['exec']
17
+
18
+ export interface Repo {
19
+ exec: Exec
20
+ top: string
21
+ gitDir: string
22
+ }
23
+
24
+ export interface Change {
25
+ path: string
26
+ kind: 'write' | 'delete'
27
+ }
28
+
29
+ async function git(exec: Exec, cwd: string, args: string[], index?: string) {
30
+ const env = index ? [...IDENTITY, `GIT_INDEX_FILE=${index}`] : IDENTITY
31
+ return exec('env', [...env, 'git', '--literal-pathspecs', ...args], { cwd })
32
+ }
33
+
34
+ async function withPathspec<T>(repo: Repo, paths: string[], run: (args: string[]) => Promise<T>): Promise<T> {
35
+ const file = join(repo.gitDir, `pi-rewind-${randomUUID()}.paths`)
36
+ try {
37
+ await writeFile(file, paths.join('\0'))
38
+ return await run([`--pathspec-from-file=${file}`, '--pathspec-file-nul'])
39
+ } finally {
40
+ await rm(file, { force: true })
41
+ }
42
+ }
43
+
44
+ export async function openRepo(exec: Exec, cwd: string): Promise<Repo | null> {
45
+ const { code, stdout } = await git(exec, cwd, ['rev-parse', '--show-toplevel', '--absolute-git-dir'])
46
+ const [top, gitDir] = stdout.split('\n')
47
+ return code === 0 && top && gitDir ? { exec, top, gitDir } : null
48
+ }
49
+
50
+ async function snapshotCandidates(top: string, paths: string[]): Promise<string[]> {
51
+ const stats = await Promise.all(paths.map((path) => lstat(join(top, path)).catch(() => null)))
52
+ return paths.filter((_, i) => {
53
+ const stat = stats[i]
54
+ return (
55
+ stat !== null &&
56
+ stat !== undefined &&
57
+ (stat.isSymbolicLink() || (stat.isFile() && stat.size <= MAX_UNTRACKED_BYTES))
58
+ )
59
+ })
60
+ }
61
+
62
+ export async function snapshot(repo: Repo): Promise<string | null> {
63
+ const index = join(repo.gitDir, `pi-rewind-${randomUUID()}.index`)
64
+ const run = (args: string[]) => git(repo.exec, repo.top, args, index)
65
+ try {
66
+ await copyFile(join(repo.gitDir, 'index'), index).catch(() => undefined)
67
+ if ((await run(['add', '-u'])).code !== 0) return null
68
+ const others = await run(['ls-files', '-z', '--others', '--exclude-standard'])
69
+ if (others.code !== 0) return null
70
+ const untracked = await snapshotCandidates(repo.top, others.stdout.split('\0').filter(Boolean))
71
+ if (untracked.length > 0) {
72
+ const added = await withPathspec(repo, untracked, (pathspec) => run(['add', ...pathspec]))
73
+ if (added.code !== 0) return null
74
+ }
75
+ const tree = await run(['write-tree'])
76
+ if (tree.code !== 0) return null
77
+ // Always a fresh commit, even for an unchanged tree: the prune reads a ref's age from
78
+ // its commit date, and git already stores an identical tree once.
79
+ const commit = await git(repo.exec, repo.top, ['commit-tree', '--no-gpg-sign', '-m', 'pi-rewind', tree.stdout.trim()])
80
+ return commit.code === 0 ? commit.stdout.trim() : null
81
+ } finally {
82
+ await rm(index, { force: true })
83
+ }
84
+ }
85
+
86
+ export async function changes(repo: Repo, from: string, to: string): Promise<Change[]> {
87
+ const { code, stdout } = await git(repo.exec, repo.top, [
88
+ 'diff-tree',
89
+ '-r',
90
+ '-z',
91
+ '--no-renames',
92
+ '--name-status',
93
+ from,
94
+ to
95
+ ])
96
+ if (code !== 0) throw new Error(`git diff-tree ${from} ${to} failed`)
97
+ const fields = stdout.split('\0')
98
+ const result: Change[] = []
99
+ for (let i = 0; i + 1 < fields.length; i += 2) {
100
+ const status = fields[i]
101
+ const path = fields[i + 1]
102
+ if (status && path) result.push({ path, kind: status === 'D' ? 'delete' : 'write' })
103
+ }
104
+ return result
105
+ }
106
+
107
+ async function removeEmptyParents(top: string, path: string): Promise<void> {
108
+ for (let dir = dirname(path); dir !== '.' && dir !== '/'; dir = dirname(dir)) {
109
+ if (
110
+ !(await rmdir(join(top, dir)).then(
111
+ () => true,
112
+ () => false
113
+ ))
114
+ )
115
+ return
116
+ }
117
+ }
118
+
119
+ export async function restore(repo: Repo, target: string, diff: Change[]): Promise<void> {
120
+ const writes = diff.filter((change) => change.kind === 'write').map((change) => change.path)
121
+ if (writes.length > 0) {
122
+ const result = await withPathspec(repo, writes, (pathspec) =>
123
+ git(repo.exec, repo.top, ['restore', `--source=${target}`, '--worktree', ...pathspec])
124
+ )
125
+ if (result.code !== 0) throw new Error(`git restore from ${target} failed: ${result.stderr.trim()}`)
126
+ }
127
+ for (const change of diff) {
128
+ if (change.kind !== 'delete') continue
129
+ await rm(join(repo.top, change.path), { force: true })
130
+ await removeEmptyParents(repo.top, change.path)
131
+ }
132
+ }
133
+
134
+ export function refName(sessionId: string, slot: string): string | null {
135
+ return /^[\w-]+$/.test(sessionId) && /^[\w/-]+$/.test(slot) ? `refs/pi-rewind/${sessionId}/${slot}` : null
136
+ }
137
+
138
+ export async function save(repo: Repo, ref: string, commit: string): Promise<boolean> {
139
+ return (await git(repo.exec, repo.top, ['update-ref', ref, commit])).code === 0
140
+ }
141
+
142
+ export async function lookup(repo: Repo, ref: string): Promise<string | null> {
143
+ const { code, stdout } = await git(repo.exec, repo.top, ['rev-parse', '--verify', '--quiet', `${ref}^{commit}`])
144
+ const sha = stdout.trim()
145
+ return code === 0 && sha ? sha : null
146
+ }
147
+
148
+ export async function listRefs(repo: Repo, prefix: string): Promise<Map<string, number>> {
149
+ const { stdout } = await git(repo.exec, repo.top, [
150
+ 'for-each-ref',
151
+ '--format=%(refname) %(committerdate:unix)',
152
+ prefix
153
+ ])
154
+ const refs = new Map<string, number>()
155
+ for (const line of stdout.split('\n')) {
156
+ const [ref, at] = line.split(' ')
157
+ if (ref && at) refs.set(ref, Number(at) * 1000)
158
+ }
159
+ return refs
160
+ }
161
+
162
+ export async function prune(repo: Repo, olderThan: number): Promise<number> {
163
+ const stale = [...(await listRefs(repo, 'refs/pi-rewind/'))]
164
+ .filter(([, at]) => at < olderThan)
165
+ .map(([ref]) => ref)
166
+ let deleted = 0
167
+ for (const ref of stale) {
168
+ if ((await git(repo.exec, repo.top, ['update-ref', '-d', ref])).code === 0) deleted += 1
169
+ }
170
+ return deleted
171
+ }