@oakgreencc/graft 0.2.20 → 0.2.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oakgreencc/graft",
3
- "version": "0.2.20",
3
+ "version": "0.2.21",
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,7 +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
+ 6. **Finish.** `graft worktree done [<branch>]` first puts back any path an earlier HEAD left staged (content GitHub already holds, untouched since), then 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.
32
32
 
33
33
  ## Other writes
34
34
 
@@ -3,6 +3,9 @@
3
3
  * `graft worktree done [<branch>]` — finish a worktree whose work is all on
4
4
  * GitHub, so `ExitWorktree remove` passes without `discard_changes`.
5
5
  *
6
+ * 0. put back strays — paths an earlier HEAD left in the index, whose
7
+ * content GitHub holds (src/worktree.mjs `tidy`) — so they do not read as
8
+ * local work;
6
9
  * 1. ask `graft status`'s question (src/status.mjs); anything local only →
7
10
  * print the report, exit 1, change nothing;
8
11
  * 2. rewind the branch to the commit the worktree was created on
@@ -17,8 +20,9 @@
17
20
  import { has, positionals } from '../context.mjs'
18
21
  import { PublishError } from '../errors.mjs'
19
22
  import { syncMain } from '../hooks/sync-worktree.mjs'
20
- import { localOnly, statusLines, verdict } from '../status.mjs'
21
- import { rewind } from '../worktree.mjs'
23
+ import { dirtyPaths } from '../publish/publish.mjs'
24
+ import { localOnly, onGitHub, statusLines, verdict } from '../status.mjs'
25
+ import { rewind, tidy } from '../worktree.mjs'
22
26
  import { COMMON_VALUE_FLAGS, contextFrom } from './common.mjs'
23
27
 
24
28
  const USAGE =
@@ -49,6 +53,21 @@ export async function run(argv, { client: given, say = console.log } = {}) {
49
53
  const { owner, repo } = ctx.repo()
50
54
  const client = await ctx.client()
51
55
  const base = await ctx.baseBranch()
56
+ let local = null
57
+ try {
58
+ local = git(['symbolic-ref', '--short', '-q', 'HEAD']).trim() || null
59
+ } catch {} // detached
60
+ const refs = [base, branch, local].filter((r) => r != null)
61
+ const tidied = await tidy({
62
+ git,
63
+ dirty: dirtyPaths(git),
64
+ held: (sha) => onGitHub({ client, owner, repo, sha, refs }),
65
+ })
66
+ if (tidied.length)
67
+ say(
68
+ `Put back ${tidied.length} path${tidied.length === 1 ? '' : 's'} an earlier HEAD left behind (GitHub holds them):\n` +
69
+ tidied.map((p) => ` ${p}`).join('\n'),
70
+ )
52
71
  const status = await localOnly({ git, client, owner, repo, base, branch: branch ?? null })
53
72
  const out = rewind({ git, status })
54
73
  if (!out.rewound && out.why === 'local-only') {
@@ -57,7 +57,8 @@
57
57
  export function findDisplacement({ git, worktreeBase, branchHead, paths }) {
58
58
  // No pathspec when nothing is scoped: an unscoped publish sweeps the whole
59
59
  // worktree, so the whole tree is what it can displace.
60
- const args = ['diff', '--name-only', worktreeBase, branchHead]
60
+ // --no-renames: a rename must list its old path too, or that path's drift goes unseen.
61
+ const args = ['diff', '--no-renames', '--name-only', worktreeBase, branchHead]
61
62
  if (paths?.length) args.push('--', ...paths)
62
63
 
63
64
  return git(args)
@@ -559,7 +559,10 @@ export function advance({ git, target }) {
559
559
  }
560
560
 
561
561
  const dirty = new Set(dirtyPaths(git))
562
- const changed = nulSplit(git(['diff', '--name-only', '-z', old, target]))
562
+ // --no-renames: with rename detection a moved file lists only its new
563
+ // path, so the old one would survive `reset --soft` in the index — a staged
564
+ // add of a file the branch deleted, which `worktree done` then refuses over.
565
+ const changed = nulSplit(git(['diff', '--no-renames', '--name-only', '-z', old, target]))
563
566
  const untouched = changed.filter((p) => !dirty.has(p))
564
567
  const collide = changed.filter((p) => dirty.has(p))
565
568
 
package/src/status.mjs CHANGED
@@ -159,7 +159,7 @@ async function pullsFor({ client, owner, repo, sha, branch }) {
159
159
  }
160
160
 
161
161
  /** Whether any of `refs` (branch names or shas) on GitHub contains `sha`. A missing ref, or a sha GitHub lacks, is a 404: no. */
162
- async function onGitHub({ client, owner, repo, sha, refs }) {
162
+ export async function onGitHub({ client, owner, repo, sha, refs }) {
163
163
  for (const ref of new Set(refs)) {
164
164
  const cmp = await client.getOrNull(`/repos/${owner}/${repo}/compare/${encodeURIComponent(ref)}...${sha}`)
165
165
  if (cmp && cmp.ahead_by === 0) return true
package/src/worktree.mjs CHANGED
@@ -32,7 +32,8 @@
32
32
  * is the same commit.
33
33
  */
34
34
 
35
- import { existsSync, readFileSync, writeFileSync } from 'node:fs'
35
+ import { existsSync, lstatSync, readFileSync, writeFileSync } from 'node:fs'
36
+ import { join } from 'node:path'
36
37
 
37
38
  /** The file, in the worktree's git dir, holding the commit the worktree was created on. */
38
39
  export const ENTERED_AT = 'graft-entered-at'
@@ -119,3 +120,105 @@ export function rewind({ git, status }) {
119
120
  git(['reset', '--quiet', '--keep', to])
120
121
  return { rewound: true, from, to }
121
122
  }
123
+
124
+ // ---------------------------------------------------------------------------
125
+ // STRAYS. A path HEAD left behind when it moved: the index and the file still
126
+ // hold a commit HEAD was on before, though the commit it is on now does not.
127
+ // `advance` before `--no-renames` made them — a renamed file's old path stayed
128
+ // in the index across `reset --soft` as a staged add — and they are the
129
+ // uncommitted paths `worktree done` and ExitWorktree then refuse over.
130
+ //
131
+ // A dirty path is a stray only when all of these hold, so an agent's own edit
132
+ // is never one:
133
+ // - it is a file on disk, and the index holds exactly it (fully staged);
134
+ // - a commit HEAD was on before (its reflog) has that same content there;
135
+ // - the file is no newer than HEAD's move off that commit — a later write,
136
+ // even one restoring that old content, is somebody's work;
137
+ // - GitHub holds that commit (`held`), so the content is not lost.
138
+ // Putting a stray back to HEAD loses nothing GitHub lacks.
139
+ // ---------------------------------------------------------------------------
140
+
141
+ /**
142
+ * @param {(args: string[]) => string} git
143
+ * @param {string[]} dirty the worktree's uncommitted paths
144
+ * @returns {{ path: string, from: string }[]} each stray and the earlier HEAD holding it
145
+ */
146
+ export function strayPaths(git, dirty) {
147
+ if (!dirty.length) return []
148
+ // Newest first: `<sha> HEAD@{<unix time it became HEAD>}`.
149
+ let moves
150
+ try {
151
+ moves = git(['log', '-g', '--date=unix', '--format=%H %gd', 'HEAD', '--'])
152
+ .trim()
153
+ .split('\n')
154
+ .map((l) => /^([0-9a-f]{40}) HEAD@\{(\d+)\}$/.exec(l.trim()))
155
+ .filter((m) => m !== null)
156
+ .map((m) => ({ sha: m[1], at: Number(m[2]) }))
157
+ } catch {
158
+ return [] // no reflog: nothing to compare against
159
+ }
160
+ // Each earlier HEAD, with the time HEAD moved off it.
161
+ const earlier = []
162
+ const seen = new Set([moves[0]?.sha])
163
+ for (let i = 1; i < moves.length; i++) {
164
+ if (seen.has(moves[i].sha)) continue
165
+ seen.add(moves[i].sha)
166
+ earlier.push({ sha: moves[i].sha, leftAt: moves[i - 1].at })
167
+ }
168
+ if (!earlier.length) return []
169
+
170
+ const root = git(['rev-parse', '--show-toplevel']).trim()
171
+ const out = []
172
+ for (const path of dirty) {
173
+ let mtime
174
+ try {
175
+ const st = lstatSync(join(root, path))
176
+ if (!st.isFile()) continue
177
+ mtime = Math.floor(st.mtimeMs / 1000)
178
+ } catch {
179
+ continue // gone from disk: a deletion, never left behind by a move
180
+ }
181
+ const staged = /^\d{6} ([0-9a-f]{40}) 0\t/.exec(git(['ls-files', '-s', '--', path]))?.[1]
182
+ if (!staged) continue
183
+ let disk
184
+ try {
185
+ disk = git(['hash-object', '--', path]).trim()
186
+ } catch {
187
+ continue
188
+ }
189
+ if (disk !== staged) continue
190
+ const from = earlier.find(({ sha, leftAt }) => mtime <= leftAt && blobAt(git, sha, path) === disk)
191
+ if (from) out.push({ path, from: from.sha })
192
+ }
193
+ return out
194
+ }
195
+
196
+ /** @param {(args: string[]) => string} git @param {string} sha @param {string} path */
197
+ function blobAt(git, sha, path) {
198
+ try {
199
+ return /^\d{6} blob ([0-9a-f]{40})\t/.exec(git(['ls-tree', sha, '--', path]))?.[1] ?? null
200
+ } catch {
201
+ return null
202
+ }
203
+ }
204
+
205
+ /**
206
+ * Put every stray whose earlier HEAD GitHub holds back to HEAD: dropped when
207
+ * HEAD lacks the path, else restored to HEAD's content. Returns the paths put back.
208
+ *
209
+ * @param {object} input
210
+ * @param {(args: string[]) => string} input.git
211
+ * @param {string[]} input.dirty
212
+ * @param {(sha: string) => Promise<boolean>} input.held whether GitHub holds the commit
213
+ */
214
+ export async function tidy({ git, dirty, held }) {
215
+ /** @type {Map<string, boolean>} */
216
+ const known = new Map()
217
+ const back = []
218
+ for (const { path, from } of strayPaths(git, dirty)) {
219
+ if (!known.has(from)) known.set(from, await held(from))
220
+ if (known.get(from)) back.push(path)
221
+ }
222
+ if (back.length) git(['restore', '--source=HEAD', '--staged', '--worktree', '--', ...back])
223
+ return back
224
+ }