@oakgreencc/graft 0.2.20 → 0.2.22

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.22",
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",
@@ -17,7 +17,7 @@ Every verb takes `-C <dir>` and `--repo <owner/repo>` (default: the `origin` rem
17
17
 
18
18
  ## Publishing work
19
19
 
20
- 1. **Branch.** Pick a fresh branch name (`agent/<topic>`). The base comes from `.graft.json` `baseBranch`, else the repo's default branch; `--base <b>` stacks on another branch.
20
+ 1. **Branch.** Pick a fresh branch name (`agent/<topic>`). The base comes from `.graft.json` `baseBranch`, else the repo's default branch; `--base <b>` picks another base, but only one in `mergeableBases`: graft refuses to cut a branch from, or open a PR against, any other (stacked PRs cannot land). Staged work is two issues, the second blocked by the first.
21
21
  2. **Validate.** `graft validate` runs the project's check and records the base it was green on. Done when it exits 0.
22
22
  3. **Publish.** Uncommitted changes in the worktree → one Verified commit:
23
23
 
@@ -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
 
@@ -8,6 +8,8 @@
8
8
  * 1. scope --paths or --all, named — before any credential is read
9
9
  * 2. no-verify skipping the repo's hooks needs a `no-verify` grant
10
10
  * 3. validated base the green you are relying on is about THIS base
11
+ * 3b. stacked base a new branch or PR only on a base agents may merge into
12
+ * (gates/stacked-base.mjs); a `merge` grant lifts it
11
13
  * 4. the tree built locally; the pre-commit hook runs here, and what it
12
14
  * stages ships
13
15
  * 5. the candidate protection → displacement → payload, judged on the tree
@@ -25,9 +27,11 @@
25
27
  import { readFileSync } from 'node:fs'
26
28
  import { resolve } from 'node:path'
27
29
  import { withClosingTrailers } from '../closing-refs.mjs'
30
+ import { mergeableBases } from '../config.mjs'
28
31
  import { flag, has, positionals } from '../context.mjs'
29
32
  import { PublishError } from '../errors.mjs'
30
33
  import { BOTH_SCOPES_MESSAGE, noPrNote, sweepMessage } from '../gates/scope.mjs'
34
+ import { stackedBaseRefusal } from '../gates/stacked-base.mjs'
31
35
  import { checkValidatedBase, readReceipt } from '../gates/validated-base.mjs'
32
36
  import { hookRunner } from '../git-hooks.mjs'
33
37
  import { allows, grantAdvice } from '../maintainer.mjs'
@@ -96,6 +100,23 @@ function noVerifyGate({ ctx, argv }) {
96
100
  return true
97
101
  }
98
102
 
103
+ /**
104
+ * Stacked-base gate. See gates/stacked-base.mjs. A `merge` grant lifts it: the PR it makes needs that grant to
105
+ * merge anyway.
106
+ */
107
+ async function stackedBaseGate({ ctx, base, newBranch, newPr }) {
108
+ const refusal = stackedBaseRefusal({
109
+ base,
110
+ allowedBases: mergeableBases(ctx.config, await ctx.baseBranch()),
111
+ newBranch,
112
+ newPr,
113
+ })
114
+ if (!refusal) return
115
+ const view = ctx.grant()
116
+ if (!allows(view, 'merge')) throw new PublishError(`${refusal}\n\n${grantAdvice(view, 'merge')}`)
117
+ console.log(`stacked base \`${base}\` under maintainer grant (merge): "${/** @type {any} */ (view).grant.reason}"`)
118
+ }
119
+
99
120
  /** Validated-base gate. See gates/validated-base.mjs. */
100
121
  function validatedBaseGate({ ctx, base, argv }) {
101
122
  const receipt = readReceipt({ gitDir: ctx.gitDir() })
@@ -285,6 +306,7 @@ export async function runPublish(argv, { client: given = null } = {}) {
285
306
  // Read before the write, said after the commit line: a branch nobody opened
286
307
  // a PR for is a branch CI never runs on.
287
308
  const existing = head ? await openPr({ client, owner, repo, branch }) : null
309
+ await stackedBaseGate({ ctx, base, newBranch: !head, newPr: Boolean(prTitle && !existing) })
288
310
 
289
311
  const { runner, hooks } = publishHooks({ ctx, skip: skipHooks, branch, remoteSha: head?.sha ?? null })
290
312
  const out = await publishWorktree({
@@ -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)
@@ -24,7 +24,7 @@
24
24
  * refused at any size, and any path that gains more than
25
25
  * {@link ADDED_BYTES_CEILING} in one publish is refused.
26
26
  * - A publish without `--pr` lands a branch nothing ever runs on. That is
27
- * legitimate — stacking, a second commit to an open PR — so it is a note
27
+ * legitimate — a second commit to an open PR — so it is a note
28
28
  * on stdout, not a refusal: see {@link noPrNote}.
29
29
  *
30
30
  * The branch-name half (`--api` as a ref) belongs to a branch-name ruleset
@@ -243,8 +243,8 @@ export function sweepMessage(wouldSweep, { usage } = {}) {
243
243
 
244
244
  /**
245
245
  * The note a publish without `--pr` prints when the branch has no open PR
246
- * either. Not a refusal — a stacked layer or a second commit to a branch
247
- * whose PR is already open is exactly this shape — but a branch with no PR is
246
+ * either. Not a refusal — a second commit to a branch whose PR is already
247
+ * open is exactly this shape — but a branch with no PR is
248
248
  * a branch CI typically never runs on (most workflows trigger on `pull_request` and
249
249
  * `merge_group` only), and that silence is how the incident's commit sat
250
250
  * unexamined.
@@ -254,6 +254,6 @@ export function sweepMessage(wouldSweep, { usage } = {}) {
254
254
  export function noPrNote({ branch, base }) {
255
255
  return (
256
256
  `note: ${branch} has no open pull request, so no CI runs on it. ` +
257
- `Open one with --pr "<title>" (targets ${base}), or stack it on a branch that has one.`
257
+ `Open one with --pr "<title>" (targets ${base}).`
258
258
  )
259
259
  }
@@ -0,0 +1,35 @@
1
+ // @ts-check
2
+ /**
3
+ * Stacked-base gate: an agent builds only on a base it may merge into.
4
+ *
5
+ * `graft pr merge` refuses a PR whose base is outside `mergeableBases`
6
+ * (pr-policy.mjs). A publish that cuts a NEW branch from such a base, or opens
7
+ * a PR against one, makes exactly that PR: work that no agent can land, and
8
+ * that lands at all only if the PR beneath it merges first. Orchestrators that
9
+ * track one PR per issue (cambium) read the two layers as duplicates and close
10
+ * the lower one, stranding the upper. So the refusal moves forward to publish
11
+ * time, before anything is written.
12
+ *
13
+ * Staged work is two issues, the second blocked by the first, each with its own
14
+ * PR into a mergeable base. A human who wants a stack anyway grants `merge`.
15
+ *
16
+ * Publishing to an EXISTING branch is left alone: the branch, and any PR on
17
+ * it, already exist, and refusing a fix to them helps nobody.
18
+ */
19
+
20
+ /**
21
+ * @param {{ base: string, allowedBases: string[], newBranch: boolean, newPr: boolean }} input
22
+ * `newBranch`: the publish creates the branch from `base`. `newPr`: it opens a PR against `base`.
23
+ * @returns {string | null} the refusal, or null to go ahead
24
+ */
25
+ export function stackedBaseRefusal({ base, allowedBases, newBranch, newPr }) {
26
+ if (allowedBases.includes(base) || (!newBranch && !newPr)) return null
27
+ const bases = allowedBases.length ? allowedBases.map((b) => `\`${b}\``).join(', ') : 'no branch'
28
+ const what = newPr ? `open a PR against \`${base}\`` : `cut a new branch from \`${base}\``
29
+ return (
30
+ `refusing to publish: this would ${what}, and agents merge only into ${bases} (mergeableBases in .graft.json). ` +
31
+ 'A PR stacked on another branch cannot land until the one beneath it merges, and no agent can merge it.\n\n' +
32
+ 'Publish onto a mergeable base instead. Work that must be reviewed in stages is two issues, the second blocked ' +
33
+ 'by the first, each with its own PR.'
34
+ )
35
+ }
@@ -30,6 +30,8 @@
30
30
  * merge `graft pr merge` past the local merge policy: a base outside
31
31
  * `mergeableBases`, protected paths in the diff, a red base.
32
32
  * GitHub's rulesets still apply; this lifts graft's opinion only.
33
+ * Also `graft publish` cutting a branch from, or opening a PR
34
+ * against, a base outside `mergeableBases` (a stacked PR).
33
35
  *
34
36
  * `impossible` paths have no scope. No grant makes the App hold a permission
35
37
  * it does not have.
@@ -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
+ }