@oakgreencc/graft 0.2.17 → 0.2.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -48,18 +48,19 @@ Full walkthrough: [skills/graft/references/setup.md](skills/graft/references/set
48
48
 
49
49
  ## Pieces
50
50
 
51
- | | |
52
- | ----------------------------------------- | ---------------------------------------------------------------------------------------- |
53
- | `bin/graft.mjs` | the CLI; `graft help` |
54
- | `skills/graft/` | the agent skill (also installable as a Claude Code plugin from this repo) |
55
- | `src/publish/` | the primitive: tree build, blob shipping, signed commit, fast-forward ref, safe advance |
56
- | `src/gates/` | scope, payload, displacement, validated base, version |
57
- | `src/git-hooks.mjs` | runs the repository's git hooks during a publish |
58
- | `src/codeowners.mjs`, `src/protected.mjs` | CODEOWNERS parsed with GitHub's semantics → the protection policy |
59
- | `src/maintainer.mjs` | scoped, session-bound grants in `.git/graft/` |
60
- | `src/github/` | the App client; issue reads/writes (`graft issue`); check verdicts (`graft ci wait`) |
61
- | `src/hooks/` | Claude Code hooks: credential guard, protected-path guard, PR-write guard, worktree sync |
62
- | `src/setup/` | `graft setup` (App manifest flow, project bootstrap) and `graft doctor` |
51
+ | | |
52
+ | ----------------------------------------- | ------------------------------------------------------------------------------------------ |
53
+ | `bin/graft.mjs` | the CLI; `graft help` |
54
+ | `skills/graft/` | the agent skill (also installable as a Claude Code plugin from this repo) |
55
+ | `src/publish/` | the primitive: tree build, blob shipping, signed commit, fast-forward ref, safe advance |
56
+ | `src/gates/` | scope, payload, displacement, validated base, version |
57
+ | `src/git-hooks.mjs` | runs the repository's git hooks during a publish |
58
+ | `src/codeowners.mjs`, `src/protected.mjs` | CODEOWNERS parsed with GitHub's semantics → the protection policy |
59
+ | `src/maintainer.mjs` | scoped, session-bound grants in `.git/graft/` |
60
+ | `src/github/` | the App client; issue reads/writes (`graft issue`); check verdicts (`graft ci wait`) |
61
+ | `src/hooks/` | Claude Code hooks: credential guard, protected-path guard, PR-write guard, worktree sync |
62
+ | `src/status.mjs`, `src/worktree.mjs` | `graft status`, and `graft worktree done`: rewind a merged worktree so ExitWorktree passes |
63
+ | `src/setup/` | `graft setup` (App manifest flow, project bootstrap) and `graft doctor` |
63
64
 
64
65
  Design notes: [docs/design.md](docs/design.md). The one invariant everything rests on: [docs/verified-commits.md](docs/verified-commits.md).
65
66
 
package/bin/graft.mjs CHANGED
@@ -43,6 +43,7 @@ Read path:
43
43
  graft ci wait <sha|ref> [--check c] one check's verdict: exit 0 green, 1 red, 2 unknowable
44
44
  graft issue read <n> an issue as JSON (with the etag \`issue edit\` needs)
45
45
  graft status [<branch>] what this worktree holds that GitHub does not (run before removing it)
46
+ graft worktree done [<branch>] all on GitHub? rewind so ExitWorktree remove passes; ff local base
46
47
  graft credential get git credential helper (git runs this)
47
48
 
48
49
  Gates and grants:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oakgreencc/graft",
3
- "version": "0.2.17",
3
+ "version": "0.2.19",
4
4
  "description": "Let an agent work a GitHub project without the local git CLI's write path: Verified commits created by a GitHub App, the repo's git hooks run at the right moments, CODEOWNERS as the manifest of what needs a human, and a scoped maintainer mode for when one says yes.",
5
5
  "license": "AGPL-3.0-only",
6
6
  "type": "module",
@@ -28,6 +28,7 @@ Every verb takes `-C <dir>` and `--repo <owner/repo>` (default: the `origin` rem
28
28
  Name every path with `--paths`; `--all` means every dirty path, untracked included, on purpose. The repo's git hooks (pre-commit, commit-msg, pre-push) run before anything is sent. Done when the output shows `commit: … [Verified]` and, with `--pr`, a `pr:` URL.
29
29
  4. **Follow up.** Later commits to the same branch: same `publish` command without `--pr`. The worktree advances onto each published commit automatically.
30
30
  5. **Before removing the worktree.** `graft status [<branch>]` says what it holds that GitHub does not (uncommitted paths, commits no branch on GitHub contains, whether the PR merged), checked through the API — never `git fetch` to find out. `publish` and `merge` end with the same verdict line. A worktree tool that reports "discarded N commits" after publishing is counting from where the session started; trust `nothing local that GitHub does not have`.
31
+ 6. **Finish.** `graft worktree done [<branch>]` asks the same question; when GitHub holds everything it rewinds the branch to the commit the worktree was created on (the one `ExitWorktree` counts from) and fast-forwards the main checkout's base. Then `ExitWorktree` `remove` passes without `discard_changes`. If it exits 1, the worktree holds work GitHub lacks: never reach for `discard_changes` to get past that.
31
32
 
32
33
  ## Other writes
33
34
 
package/src/cli/verbs.mjs CHANGED
@@ -20,6 +20,7 @@ export const VERBS = {
20
20
  pr: () => import('./pr.mjs').then((m) => m.run),
21
21
  issue: () => import('./issue.mjs').then((m) => m.run),
22
22
  ci: () => import('./ci.mjs').then((m) => m.run),
23
+ worktree: () => import('./worktree.mjs').then((m) => m.run),
23
24
  hook: () => import('../hooks/index.mjs').then((m) => m.run),
24
25
  setup: () => import('../setup/index.mjs').then((m) => m.run),
25
26
  doctor: () => import('../setup/doctor.mjs').then((m) => m.run),
@@ -35,6 +36,7 @@ export const SUBVERBS = Object.freeze({
35
36
  pr: ['merge', 'update'],
36
37
  issue: ['read', 'create', 'comment', 'close', 'edit', 'assign', 'label'],
37
38
  ci: ['wait'],
39
+ worktree: ['done'],
38
40
  maintainer: ['status', 'grant', 'on', 'revoke', 'off'],
39
41
  setup: ['app', 'project'],
40
42
  credential: ['get'],
@@ -0,0 +1,76 @@
1
+ // @ts-check
2
+ /**
3
+ * `graft worktree done [<branch>]` — finish a worktree whose work is all on
4
+ * GitHub, so `ExitWorktree remove` passes without `discard_changes`.
5
+ *
6
+ * 1. ask `graft status`'s question (src/status.mjs); anything local only →
7
+ * print the report, exit 1, change nothing;
8
+ * 2. rewind the branch to the commit the worktree was created on
9
+ * (src/worktree.mjs explains why that is the commit ExitWorktree counts
10
+ * from);
11
+ * 3. fetch the base the way graft fetches (origin over `graft credential`)
12
+ * and fast-forward the main checkout's base onto it, under the
13
+ * sync-worktree rules (ff-only, never a dirty checkout), so the merged
14
+ * work is in local `main` too.
15
+ */
16
+
17
+ import { has, positionals } from '../context.mjs'
18
+ import { PublishError } from '../errors.mjs'
19
+ import { syncMain } from '../hooks/sync-worktree.mjs'
20
+ import { localOnly, statusLines, verdict } from '../status.mjs'
21
+ import { rewind } from '../worktree.mjs'
22
+ import { COMMON_VALUE_FLAGS, contextFrom } from './common.mjs'
23
+
24
+ const USAGE =
25
+ 'usage: graft worktree done [<branch>] [-C <dir>] [--repo <owner/repo>]\n\n' +
26
+ 'Run when the work is merged, before ExitWorktree remove (or git worktree remove). If GitHub holds\n' +
27
+ 'everything in this worktree, rewinds its branch to the commit the worktree was created on — the\n' +
28
+ "commit ExitWorktree counts from — and fast-forwards the main checkout's base branch. Anything\n" +
29
+ 'local only: prints what, exits 1, changes nothing. <branch> is the branch you published to.'
30
+
31
+ /**
32
+ * @param {string[]} argv
33
+ * @param {{ client?: import('../github/app.mjs').Client, say?: (line: string) => void }} [deps]
34
+ */
35
+ export async function run(argv, { client: given, say = console.log } = {}) {
36
+ if (has(argv, '--help')) {
37
+ say(USAGE)
38
+ return 0
39
+ }
40
+ const [sub, branch, ...extra] = positionals(argv, COMMON_VALUE_FLAGS)
41
+ if (sub !== 'done' || extra.length) throw new PublishError(USAGE)
42
+ const ctx = contextFrom(argv, { client: given ?? null })
43
+ const { git } = ctx
44
+ const root = /** @type {string} */ (ctx.root)
45
+ const dirs = git(['rev-parse', '--path-format=absolute', '--git-dir', '--git-common-dir']).trim().split('\n')
46
+ if (dirs[0] === dirs[1])
47
+ throw new PublishError(`${root} is the main checkout, not a linked worktree: nothing to finish.`)
48
+
49
+ const { owner, repo } = ctx.repo()
50
+ const client = await ctx.client()
51
+ const base = await ctx.baseBranch()
52
+ const status = await localOnly({ git, client, owner, repo, base, branch: branch ?? null })
53
+ const out = rewind({ git, status })
54
+ if (!out.rewound && out.why === 'local-only') {
55
+ for (const line of statusLines(status)) say(line)
56
+ say('Not finished: publish it (graft publish) or confirm with the user that it may be discarded.')
57
+ return 1
58
+ }
59
+ say(verdict(status))
60
+ if (out.rewound)
61
+ say(
62
+ `Rewound ${status.local ?? 'HEAD'} ${out.from.slice(0, 7)} → ${out.to.slice(0, 7)}, the commit this worktree was created on.`,
63
+ )
64
+ else if (out.why === 'unknown-entry')
65
+ say('Could not tell which commit this worktree was created on, so its branch was left where it is.')
66
+
67
+ try {
68
+ git(['fetch', '--quiet', 'origin', base])
69
+ const main = syncMain(root, base, git(['rev-parse', 'FETCH_HEAD']).trim())
70
+ if (main) say(main)
71
+ } catch (err) {
72
+ say(`Could not bring the main checkout's ${base} up to date: ${/** @type {Error} */ (err)?.message ?? err}`)
73
+ }
74
+ say('Done: remove it with ExitWorktree action "remove" (no discard_changes), or git worktree remove.')
75
+ return 0
76
+ }
@@ -66,7 +66,7 @@ import { isAbsolute, resolve } from 'node:path'
66
66
  import { contextForPath } from '../context.mjs'
67
67
  import { currentSession, grantAdvice } from '../maintainer.mjs'
68
68
  import { judge, keyDiffers, normalise } from '../protected.mjs'
69
- import { executedCommands, segments, tokens } from './shell-text.mjs'
69
+ import { executedCommands, segments, statements, tokens } from './shell-text.mjs'
70
70
 
71
71
  /** Tools whose `file_path` (or `notebook_path`) input is a write. */
72
72
  const WRITE_TOOLS = new Set(['Write', 'Edit', 'NotebookEdit', 'MultiEdit'])
@@ -110,31 +110,89 @@ const REMOVER = verb('rm|unlink|truncate')
110
110
  * @returns {string[]}
111
111
  */
112
112
  export function writeTargets(command) {
113
- return [...new Set(executedCommands(command).flatMap(targetsOf))]
113
+ return [...new Set(writeTargetsIn(command).map((t) => t.path))]
114
+ }
115
+
116
+ /**
117
+ * Like `writeTargets`, each with the directory a preceding `cd <dir>` in the
118
+ * same command moved to (`dir`, as typed: relative to the event's `cwd`, or
119
+ * absolute), or `null` for none. `cd packages/x && sed -i … package.json`
120
+ * writes `packages/x/package.json`, not the root `package.json`. A `cd` whose
121
+ * target cannot be read (`cd`, `cd -`, `cd "$D"`) leaves the paths after it
122
+ * judged from `cwd`, as before. Nested `sh -c` payloads start from `cwd`.
123
+ *
124
+ * @param {string} command
125
+ * @returns {{ path: string, dir: string | null }[]}
126
+ */
127
+ export function writeTargetsIn(command) {
128
+ const seen = new Set()
129
+ const out = []
130
+ for (const t of executedCommands(command).flatMap(targetsOf)) {
131
+ const k = `${t.dir ?? ''}\0${t.path}`
132
+ if (seen.has(k)) continue
133
+ seen.add(k)
134
+ out.push(t)
135
+ }
136
+ return out
137
+ }
138
+
139
+ /** A `cd` target that can be read as typed: no expansion, not `-`, not `~`. */
140
+ const PLAIN_DIR = /^[\w./@+-]+$/
141
+
142
+ /**
143
+ * Where each statement of ONE command runs, by offset: the `cd <dir>`
144
+ * statements before it, chained. A `cd` inside a pipeline runs in a subshell
145
+ * and moves nothing.
146
+ *
147
+ * @param {{ raw: string, masked: string }} one
148
+ * @returns {(offset: number) => string | null}
149
+ */
150
+ function dirsOf({ raw, masked }) {
151
+ /** @type {{ start: number, dir: string | null }[]} */
152
+ const moves = []
153
+ let dir = /** @type {string | null} */ (null)
154
+ for (const st of statements(masked)) {
155
+ const toks = tokens(st, raw)
156
+ if (toks[0]?.masked !== 'cd') continue
157
+ if (segments(st.text).length > 1) continue
158
+ const arg = toks.length === 2 ? unquote(toks[1].raw) : null
159
+ const to = arg && PLAIN_DIR.test(arg) && arg !== '-' ? arg : null
160
+ dir = to === null ? null : isAbsolute(to) || dir === null ? to : `${dir}/${to}`
161
+ moves.push({ start: st.start + st.text.length, dir })
162
+ }
163
+ return (offset) => {
164
+ let at = null
165
+ for (const m of moves) if (m.start <= offset) at = m.dir
166
+ return at
167
+ }
114
168
  }
115
169
 
116
170
  /**
117
171
  * The write targets of ONE command, nested payloads not included.
118
172
  *
119
173
  * @param {{ raw: string, masked: string }} one
120
- * @returns {string[]}
174
+ * @returns {{ path: string, dir: string | null }[]}
121
175
  */
122
- function targetsOf({ raw: command, masked }) {
176
+ function targetsOf(one) {
177
+ const { raw: command, masked } = one
178
+ const dirAt = dirsOf(one)
179
+ /** @type {{ path: string, dir: string | null }[]} */
123
180
  const out = []
124
- const add = (t) => {
181
+ const add = (t, offset) => {
125
182
  const p = unquote(t ?? '')
126
- if (pathish(p)) out.push(p)
183
+ if (pathish(p)) out.push({ path: p, dir: dirAt(offset) })
127
184
  }
128
185
  const rawAt = (m, group) => command.slice(m.index + m[0].length - m[group].length, m.index + m[0].length)
129
186
 
130
187
  // `> path`, `>> path`, `2> path`, `&> path`.
131
- for (const m of masked.matchAll(/(?:^|[^0-9<>&])(?:[0-9]|&)?>>?\s*(['"]?[^\s;|&<>()]+['"]?)/g)) add(rawAt(m, 1))
188
+ for (const m of masked.matchAll(/(?:^|[^0-9<>&])(?:[0-9]|&)?>>?\s*(['"]?[^\s;|&<>()]+['"]?)/g))
189
+ add(rawAt(m, 1), m.index)
132
190
 
133
191
  // `dd of=path`
134
- for (const m of masked.matchAll(/\bdd\b[^\n;|&]*?\bof=(['"]?[^\s;|&]+['"]?)/g)) add(rawAt(m, 1))
192
+ for (const m of masked.matchAll(/\bdd\b[^\n;|&]*?\bof=(['"]?[^\s;|&]+['"]?)/g)) add(rawAt(m, 1), m.index)
135
193
 
136
194
  // `tee path`, `tee -a path`
137
- for (const m of masked.matchAll(/\btee\b\s+(?:-\S+\s+)*(['"]?[^\s;|&<>()]+['"]?)/g)) add(rawAt(m, 1))
195
+ for (const m of masked.matchAll(/\btee\b\s+(?:-\S+\s+)*(['"]?[^\s;|&<>()]+['"]?)/g)) add(rawAt(m, 1), m.index)
138
196
 
139
197
  for (const seg of segments(masked)) {
140
198
  const toks = tokens(seg, command)
@@ -145,7 +203,7 @@ function targetsOf({ raw: command, masked }) {
145
203
  if (editor >= 0) {
146
204
  const args = toks.slice(editor + 1)
147
205
  if (args.some((t) => isFlag(t.masked) && IN_PLACE_FLAG.test(t.masked))) {
148
- for (const t of args) if (!isFlag(t.masked) && !SED_EXPRESSION.test(t.masked)) add(t.raw)
206
+ for (const t of args) if (!isFlag(t.masked) && !SED_EXPRESSION.test(t.masked)) add(t.raw, seg.start)
149
207
  }
150
208
  }
151
209
 
@@ -154,20 +212,20 @@ function targetsOf({ raw: command, masked }) {
154
212
  const mover = verbIndex(toks, MOVER)
155
213
  if (mover >= 0) {
156
214
  const args = toks.slice(mover + 1).filter((t) => !isFlag(t.masked))
157
- if (toks[mover].masked.endsWith('mv')) for (const t of args) add(t.raw)
158
- else if (args.length >= 2) add(args[args.length - 1].raw)
215
+ if (toks[mover].masked.endsWith('mv')) for (const t of args) add(t.raw, seg.start)
216
+ else if (args.length >= 2) add(args[args.length - 1].raw, seg.start)
159
217
  }
160
218
 
161
219
  // Removal is a write.
162
220
  const remover = verbIndex(toks, REMOVER)
163
- if (remover >= 0) for (const t of toks.slice(remover + 1)) if (!isFlag(t.masked)) add(t.raw)
221
+ if (remover >= 0) for (const t of toks.slice(remover + 1)) if (!isFlag(t.masked)) add(t.raw, seg.start)
164
222
  }
165
223
 
166
224
  // Scripting one-liners that open a file for writing. Scanned RAW — the path
167
225
  // is the quoted string. A read (`open(path).read()`) is not matched.
168
- for (const m of command.matchAll(/\bopen\(\s*(['"])([^'"\n]+)\1\s*,\s*(?:mode\s*=\s*)?['"][wax]/g)) add(m[2])
169
- for (const m of command.matchAll(/\bPath\(\s*(['"])([^'"\n]+)\1\s*\)\.write_(?:text|bytes)\(/g)) add(m[2])
170
- for (const m of command.matchAll(/\b(?:writeFile|appendFile)(?:Sync)?\(\s*(['"])([^'"\n]+)\1/g)) add(m[2])
226
+ for (const m of command.matchAll(/\bopen\(\s*(['"])([^'"\n]+)\1\s*,\s*(?:mode\s*=\s*)?['"][wax]/g)) add(m[2], m.index)
227
+ for (const m of command.matchAll(/\bPath\(\s*(['"])([^'"\n]+)\1\s*\)\.write_(?:text|bytes)\(/g)) add(m[2], m.index)
228
+ for (const m of command.matchAll(/\b(?:writeFile|appendFile)(?:Sync)?\(\s*(['"])([^'"\n]+)\1/g)) add(m[2], m.index)
171
229
 
172
230
  return out
173
231
  }
@@ -322,8 +380,9 @@ export function bashVerdict({ command, cwd, lookup }) {
322
380
  ' ! graft maintainer grant "<why this session needs it>" --scope <scope>\n\n' +
323
381
  'Say which scope you need (protected, no-verify, merge) and why.'
324
382
  )
325
- for (const path of writeTargets(command)) {
326
- const reason = judgePath({ path, cwd, lookup, how: ' (named by a shell write)', keyChanged: () => false })
383
+ for (const { path, dir } of writeTargetsIn(command)) {
384
+ const at = dir === null ? cwd : resolve(cwd, dir)
385
+ const reason = judgePath({ path, cwd: at, lookup, how: ' (named by a shell write)', keyChanged: () => false })
327
386
  if (reason) return reason
328
387
  }
329
388
  return null
@@ -10,7 +10,7 @@
10
10
  * guard-credentials PreToolUse Bash keep off human credentials
11
11
  * guard-protected PreToolUse Bash, Write|Edit|… CODEOWNERS paths need a grant
12
12
  * guard-pr-writes PreToolUse Bash merges go through `graft pr merge`
13
- * sync-worktree PostToolUse EnterWorktree fast-forward a new worktree
13
+ * sync-worktree PostToolUse EnterWorktree record the entry commit, fast-forward a new worktree
14
14
  * session-check SessionStart is raw git bound to the App?
15
15
  *
16
16
  * THE HOST owns what every hook would otherwise repeat: reading the event
@@ -29,6 +29,13 @@
29
29
  * Every failure is reported and none is fatal: the hook always exits 0.
30
30
  *
31
31
  * ---------------------------------------------------------------------------
32
+ * THE ENTRY COMMIT. Claude Code recorded HEAD before this hook ran, and its
33
+ * `ExitWorktree remove` counts the branch's commits past that SHA. The hook
34
+ * writes it to `graft-entered-at` in the worktree's git dir before moving
35
+ * anything, so `graft worktree done` can rewind there once GitHub holds the
36
+ * work (src/worktree.mjs).
37
+ *
38
+ * ---------------------------------------------------------------------------
32
39
  * THE MAIN CHECKOUT TOO. The repository's primary worktree is where a human
33
40
  * reads, runs and starts things, and what the next worktree hydrates from. Its
34
41
  * base branch is fast-forwarded to the same fetched commit under the same
@@ -38,6 +45,7 @@
38
45
  import { execFileSync } from 'node:child_process'
39
46
  import { existsSync, realpathSync } from 'node:fs'
40
47
  import { resolveContext } from '../context.mjs'
48
+ import { recordEntry } from '../worktree.mjs'
41
49
 
42
50
  /**
43
51
  * The worktree path: from the tool's result text ("Created worktree at <path>
@@ -116,6 +124,9 @@ export function sync(event, { env = process.env } = {}) {
116
124
  return `Worktree has uncommitted changes, so it was NOT synced to origin/${base}. If it is behind, publishing would revert files — graft's displacement gate will say so.`
117
125
  }
118
126
  const before = git(['rev-parse', 'HEAD']).trim()
127
+ // ExitWorktree counts from `before`, not from where this hook leaves the
128
+ // branch: `graft worktree done` rewinds to it (src/worktree.mjs).
129
+ recordEntry(git, before)
119
130
  git(['fetch', 'origin', base])
120
131
  const target = git(['rev-parse', 'FETCH_HEAD']).trim()
121
132
  let main = null
@@ -44,6 +44,7 @@ export const AGENT_CALLS = Object.freeze([
44
44
  why: 'land work as a Verified commit',
45
45
  },
46
46
  { tool: 'Bash', command: 'graft status agent/topic', why: 'what the worktree holds that GitHub does not' },
47
+ { tool: 'Bash', command: 'graft worktree done agent/topic', why: 'finish a merged worktree before removing it' },
47
48
  { tool: 'Bash', command: 'graft advance agent/topic', why: 'follow a branch that moved' },
48
49
  { tool: 'Bash', command: 'graft merge agent/topic', why: 'publish a resolved merge' },
49
50
  { tool: 'Bash', command: 'graft api GET /repos/o/r/pulls --paginate', why: 'every read of GitHub' },
@@ -0,0 +1,121 @@
1
+ // @ts-check
2
+ /**
3
+ * Finishing a worktree: once GitHub holds everything in it, put its branch
4
+ * back where the session found it, so Claude Code's `ExitWorktree remove`
5
+ * sees nothing to lose (#73).
6
+ *
7
+ * ---------------------------------------------------------------------------
8
+ * WHAT ExitWorktree COUNTS. When `EnterWorktree` creates a worktree it records
9
+ * the commit HEAD was on (its "original head commit": a SHA, not a ref). On
10
+ * `remove` it counts `git rev-list refs/heads/<worktree-branch> ^<that SHA>`
11
+ * and refuses on anything above zero. No ref enters the count — not local
12
+ * `main`, not `origin/*` — so no fetch or fast-forward of `main` can satisfy
13
+ * it. Every graft worktree goes past that SHA twice:
14
+ *
15
+ * 1. `graft hook sync-worktree` (PostToolUse EnterWorktree) fast-forwards
16
+ * the branch onto origin/<base> AFTER the SHA was recorded;
17
+ * 2. `graft publish` moves the branch onto the commit GitHub created, which
18
+ * no local commit before it can contain, and the merge happens on GitHub.
19
+ *
20
+ * Both are published history. So once `graft status` would say `nothing local
21
+ * that GitHub does not have`, the branch's commits are disposable locally and
22
+ * the branch is rewound to the recorded SHA: the count is zero, and
23
+ * `ExitWorktree remove` passes without `discard_changes`. A worktree holding
24
+ * one commit GitHub lacks is never rewound — its count stays and the guard
25
+ * still refuses, which is the one case it exists for.
26
+ *
27
+ * ---------------------------------------------------------------------------
28
+ * THE RECORDED SHA. The sync hook writes the HEAD it found, before moving it,
29
+ * to `graft-entered-at` in the worktree's own git dir (removed with the
30
+ * worktree). Without that file — a worktree made before this, or with the hook
31
+ * off — the oldest entry of the branch's reflog is its creation point, which
32
+ * is the same commit.
33
+ */
34
+
35
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs'
36
+
37
+ /** The file, in the worktree's git dir, holding the commit the worktree was created on. */
38
+ export const ENTERED_AT = 'graft-entered-at'
39
+
40
+ const SHA = /^[0-9a-f]{40}$/
41
+
42
+ /** @param {(args: string[]) => string} git */
43
+ const enteredAtPath = (git) => git(['rev-parse', '--path-format=absolute', '--git-path', ENTERED_AT]).trim()
44
+
45
+ /**
46
+ * Record `sha` as the commit this worktree was created on — once: the first
47
+ * record is the one ExitWorktree also holds.
48
+ *
49
+ * @param {(args: string[]) => string} git @param {string} sha
50
+ */
51
+ export function recordEntry(git, sha) {
52
+ const p = enteredAtPath(git)
53
+ if (!existsSync(p)) writeFileSync(p, `${sha}\n`)
54
+ }
55
+
56
+ /**
57
+ * The commit this worktree was created on: the recorded one, else the oldest
58
+ * reflog entry of `branch`. Null when neither is known.
59
+ *
60
+ * @param {(args: string[]) => string} git @param {string | null} branch
61
+ */
62
+ export function enteredAt(git, branch) {
63
+ const p = enteredAtPath(git)
64
+ if (existsSync(p)) {
65
+ const sha = readFileSync(p, 'utf8').trim()
66
+ if (SHA.test(sha) && exists(git, sha)) return sha
67
+ }
68
+ if (!branch) return null
69
+ try {
70
+ const oldest = git(['reflog', 'show', '--format=%H', `refs/heads/${branch}`, '--'])
71
+ .trim()
72
+ .split('\n')
73
+ .at(-1)
74
+ return oldest && SHA.test(oldest) ? oldest : null
75
+ } catch {
76
+ return null
77
+ }
78
+ }
79
+
80
+ /** @param {(args: string[]) => string} git @param {string} sha */
81
+ function exists(git, sha) {
82
+ try {
83
+ git(['cat-file', '-e', `${sha}^{commit}`])
84
+ return true
85
+ } catch {
86
+ return false
87
+ }
88
+ }
89
+
90
+ /** @param {(args: string[]) => string} git @param {string} a @param {string} b */
91
+ function isAncestor(git, a, b) {
92
+ try {
93
+ git(['merge-base', '--is-ancestor', a, b])
94
+ return true
95
+ } catch {
96
+ return false
97
+ }
98
+ }
99
+
100
+ /**
101
+ * Rewind a fully published worktree to the commit it was created on.
102
+ *
103
+ * `status` is `localOnly`'s answer for this worktree; anything dirty or
104
+ * unpublished in it refuses, and nothing moves. The move is `reset --keep`,
105
+ * which refuses rather than overwrite a local change.
106
+ *
107
+ * @param {object} input
108
+ * @param {(args: string[]) => string} input.git runs git in the worktree
109
+ * @param {{ head: string | null, local: string | null, dirty: string[], unpublished: string[] }} input.status
110
+ * @returns {{ rewound: true, from: string, to: string }
111
+ * | { rewound: false, why: 'local-only' | 'unknown-entry' | 'already-there', to?: string }}
112
+ */
113
+ export function rewind({ git, status }) {
114
+ if (status.dirty.length || status.unpublished.length) return { rewound: false, why: 'local-only' }
115
+ const to = enteredAt(git, status.local)
116
+ if (!to) return { rewound: false, why: 'unknown-entry' }
117
+ const from = status.head
118
+ if (!from || isAncestor(git, from, to)) return { rewound: false, why: 'already-there', to }
119
+ git(['reset', '--quiet', '--keep', to])
120
+ return { rewound: true, from, to }
121
+ }