@oakgreencc/graft 0.2.21 → 0.2.23

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,19 +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/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` |
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 (the `finish-worktree` hook runs it) |
63
+ | `src/setup/` | `graft setup` (App manifest flow, project bootstrap) and `graft doctor` |
64
64
 
65
65
  Design notes: [docs/design.md](docs/design.md). The one invariant everything rests on: [docs/verified-commits.md](docs/verified-commits.md).
66
66
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oakgreencc/graft",
3
- "version": "0.2.21",
3
+ "version": "0.2.23",
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>]` 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.
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`. The `finish-worktree` hook runs `done` itself before every `remove`, and denies the remove with `done`'s report when something is local only. If it exits 1 or the remove is denied, 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({
@@ -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
+ }
@@ -0,0 +1,55 @@
1
+ // @ts-check
2
+ /**
3
+ * PreToolUse/ExitWorktree hook — run `graft worktree done` before a remove, so
4
+ * nobody has to remember it.
5
+ *
6
+ * graft hook finish-worktree
7
+ *
8
+ * ExitWorktree `remove` counts the branch's commits past the SHA it recorded at
9
+ * EnterWorktree, and every graft worktree goes past it with published history
10
+ * (src/worktree.mjs). `graft worktree done` rewinds the branch once GitHub holds
11
+ * everything, but only when an agent remembers to run it first. Agents forget,
12
+ * then ask the human whether to pass `discard_changes` over work that is already
13
+ * merged. Running `done` here makes the rewind part of the remove.
14
+ *
15
+ * - Only `action: "remove"` without `discard_changes`. `keep` moves nothing,
16
+ * and an explicit discard has already been decided.
17
+ * - The event's cwd must be in a linked worktree. `done` refuses the main
18
+ * checkout, and that refusal is no opinion here.
19
+ * - Something local only (an unpublished commit, an uncommitted path): the
20
+ * remove is denied with `done`'s report, which names what would be lost.
21
+ * ExitWorktree would refuse anyway, with only a count.
22
+ * - Anything else (no network, no App, an older repo) has no opinion: the call
23
+ * goes through and ExitWorktree's own guard still applies.
24
+ */
25
+ import { run as worktree } from '../cli/worktree.mjs'
26
+
27
+ /**
28
+ * @param {any} event
29
+ * @param {{ done?: typeof worktree }} [deps]
30
+ * @returns {Promise<string | null>}
31
+ */
32
+ export async function finish(event, { done = worktree } = {}) {
33
+ const input = event?.tool_input ?? {}
34
+ if (input.action !== 'remove' || input.discard_changes === true) return null
35
+ const cwd = event?.cwd
36
+ if (typeof cwd !== 'string' || !cwd) return null
37
+ /** @type {string[]} */
38
+ const said = []
39
+ let code
40
+ try {
41
+ code = await done(['done', '-C', cwd], { say: (line) => said.push(line) })
42
+ } catch {
43
+ return null
44
+ }
45
+ if (code === 0) return null
46
+ return ['graft worktree done: this worktree holds work GitHub does not have, so it was not removed.', ...said].join(
47
+ '\n',
48
+ )
49
+ }
50
+
51
+ /** A guard (see hooks/index.mjs): its message denies the remove. */
52
+ export const event = 'PreToolUse'
53
+
54
+ /** @param {any} input */
55
+ export const decide = (input) => finish(input)
@@ -11,6 +11,7 @@
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
13
  * sync-worktree PostToolUse EnterWorktree record the entry commit, fast-forward a new worktree
14
+ * finish-worktree PreToolUse ExitWorktree `graft worktree done` before a remove
14
15
  * session-check SessionStart is raw git bound to the App?
15
16
  *
16
17
  * THE HOST owns what every hook would otherwise repeat: reading the event
@@ -35,6 +36,7 @@ export const HOOKS = {
35
36
  'guard-protected': () => import('./guard-protected.mjs'),
36
37
  'guard-pr-writes': () => import('./guard-pr-writes.mjs'),
37
38
  'sync-worktree': () => import('./sync-worktree.mjs'),
39
+ 'finish-worktree': () => import('./finish-worktree.mjs'),
38
40
  'session-check': () => import('./session-check.mjs'),
39
41
  }
40
42
 
@@ -16,20 +16,53 @@
16
16
  * those settings. What it catches is the session that loaded them and still
17
17
  * is not bound: a foreign block, a remote on another owner's SSH, a helper
18
18
  * that answers before graft's.
19
+ *
20
+ * It also says when this graft is older than `.graft.json`'s `minVersion`.
21
+ * Every verb refuses then (gates/version.mjs), but hooks do not go through
22
+ * that gate: an old graft's hooks run quietly and do less, such as never
23
+ * recording the commit `graft worktree done` rewinds to. Saying so at session
24
+ * start beats finding out at the end of the work.
19
25
  */
20
26
  import { existsSync, readFileSync } from 'node:fs'
21
27
  import { join } from 'node:path'
22
28
  import { resolveContext } from '../context.mjs'
29
+ import { VERSION, versionRefusal } from '../gates/version.mjs'
23
30
  import { readRawGit, sessionFindings } from '../session-env.mjs'
24
31
 
25
32
  /**
26
33
  * @param {any} event
27
- * @param {{ env?: NodeJS.ProcessEnv }} [opts]
34
+ * @param {{ env?: NodeJS.ProcessEnv, running?: string }} [opts] `running`: the graft version (default: this one)
28
35
  * @returns {string | null}
29
36
  */
30
- export function check(event, { env = process.env } = {}) {
37
+ export function check(event, { env = process.env, running } = {}) {
31
38
  const ctx = resolveContext({ cwd: event?.cwd ?? process.cwd(), env })
32
39
  if (!ctx.root) return null
40
+ const stale = staleGraft(ctx, running)
41
+ const bound = binding(ctx, env)
42
+ return [stale, bound].filter(Boolean).join('\n\n') || null
43
+ }
44
+
45
+ /**
46
+ * The notice when this graft is older than the project's `minVersion`, else null.
47
+ * @param {{ config: { minVersion?: string | null } }} ctx @param {string} [running]
48
+ */
49
+ export function staleGraft(ctx, running) {
50
+ let min = null
51
+ try {
52
+ min = ctx.config.minVersion ?? null
53
+ } catch {
54
+ return null // unreadable policy: doctor names it
55
+ }
56
+ if (!versionRefusal(min, running)) return null
57
+ return (
58
+ `graft: this is graft ${running ?? VERSION}; this project's .graft.json requires >= ${min}.\n` +
59
+ 'Every graft verb will refuse, and its hooks are doing less than the project expects.\n' +
60
+ 'Update it (`oakgreen update`, or `npm install -g @oakgreencc/graft`), then start a new session.'
61
+ )
62
+ }
63
+
64
+ /** @param {any} ctx @param {NodeJS.ProcessEnv} env */
65
+ function binding(ctx, env) {
33
66
  const settingsPath = join(ctx.root, '.claude', 'settings.json')
34
67
  let settingsEnv = null
35
68
  try {
@@ -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.
@@ -100,6 +100,13 @@ export function claudeHooks() {
100
100
  matcher: 'Write|Edit|MultiEdit|NotebookEdit',
101
101
  hooks: [hook('graft hook guard-protected', { timeout: 10 })],
102
102
  },
103
+ {
104
+ // `graft worktree done` first, so a merged worktree's branch is rewound and the remove passes.
105
+ matcher: 'ExitWorktree',
106
+ hooks: [
107
+ hook('graft hook finish-worktree', { timeout: 60, statusMessage: 'Checking GitHub holds this worktree' }),
108
+ ],
109
+ },
103
110
  ],
104
111
  PostToolUse: [
105
112
  {
@@ -204,7 +211,7 @@ export function missingFromSettings(settings) {
204
211
  .flat()
205
212
  .flatMap((g) => /** @type {any} */ (g)?.hooks ?? [])
206
213
  .map((h) => String(h?.command ?? ''))
207
- for (const name of ['guard-credentials', 'guard-pr-writes', 'guard-protected', 'session-check'])
214
+ for (const name of ['guard-credentials', 'guard-pr-writes', 'guard-protected', 'finish-worktree', 'session-check'])
208
215
  if (!commands.some((c) => c.includes(`hook ${name}`))) missing.push(`hooks: graft hook ${name}`)
209
216
  return missing
210
217
  }