@feigi/fleet-ctl 3.73.3 → 3.74.1

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": "@feigi/fleet-ctl",
3
- "version": "3.73.3",
3
+ "version": "3.74.1",
4
4
  "description": "Agent fleet: run-team controller, merge bot, PR reviewer, and the ticket pipeline they share",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -159,8 +159,8 @@ function workspaceHash(key) {
159
159
  //
160
160
  // A non-empty string, and nothing more: no trim(). A wholly-whitespace
161
161
  // answer to `--git-common-dir` is already refused one layer down, by
162
- // git-env.mjs's workspaceDirFromGitCommonDir() inside fleet-dir.mjs's
163
- // fleetFile(), so no identity reaching either call site can be whitespace —
162
+ // git-env.mjs's resolveWorkspace() inside fleet-dir.mjs's fleetFile(), so no
163
+ // identity reaching either call site can be whitespace —
164
164
  // the construction side gets the workspace fleetFile() resolved and the
165
165
  // parsing side gets a payload some process wrote from it. A second whitespace
166
166
  // rule here would be one more guard of exactly the kind this predicate exists
@@ -17,8 +17,11 @@
17
17
  # specialists). Two independent readers is what drifts.
18
18
  #
19
19
  # THE CACHE is `<workspace>/.fleet/recipe.json`, where <workspace> is the
20
- # directory holding the repository's COMMON git dir — the main checkout, the
21
- # same place the ledger and the heartbeat live — so a claimed worktree and a
20
+ # directory git-env.mjs's resolveWorkspace() names for the repository: the
21
+ # common git dir's parent when the common dir is named `.git` or that parent's
22
+ # own `.git` resolves to it, otherwise the common git dir itself (a bare
23
+ # repository, a submodule). That is the same place the
24
+ # ledger and the heartbeat live — so a claimed worktree and a
22
25
  # review worktree read the one cache the main checkout holds rather than a
23
26
  # private copy each. A single JSON object:
24
27
  #
@@ -158,15 +161,38 @@ if [ -n "$rev" ]; then
158
161
  || die "--at '$rev' does not resolve to a commit in $repo"
159
162
  fi
160
163
 
161
- # `--path-format=absolute` so the workspace is a real directory whatever the
162
- # caller's cwd; the workspace is the common dir's parent, the same rule
163
- # git-env.mjs's workspaceDirFromGitCommonDir() applies for the ledger.
164
+ # `--path-format=absolute` so the common dir is a real path whatever the
165
+ # caller's cwd. The workspace it names is git-env.mjs's resolveWorkspace() rule,
166
+ # written out below in shell.
164
167
  common=$(git -C "$repo" rev-parse --path-format=absolute --git-common-dir 2>&1) || {
165
168
  gitrc=$?
166
169
  case $gitrc in 128) die "cannot resolve the common git dir of $repo — $common" ;; esac
167
170
  unrunnable "git did not resolve the common git dir of $repo (exit $gitrc), so the Recipe cache was not read${common:+ — $common}"
168
171
  }
169
- cache="${common%/*}/.fleet/recipe.json"
172
+ # The workspace is the rule in git-env.mjs's resolveWorkspace(), written out in
173
+ # shell rather than asked of node: the interpreter probe below must stay the
174
+ # first node call, since its refusals are pinned in that order. A common dir
175
+ # named `.git` belongs to its parent checkout. Otherwise the parent's `.git`,
176
+ # a symlink or a gitfile, that resolves to the common dir makes the parent the
177
+ # workspace. Otherwise the common dir is the workspace itself (a bare
178
+ # repository, a submodule's git dir).
179
+ real=$(cd -P "$common" 2>/dev/null && pwd -P) || real=$common
180
+ parent=${common%/*}
181
+ case ${real##*/} in
182
+ .git) ws=$parent ;;
183
+ *)
184
+ ws=$common
185
+ target=${real%/*}/.git
186
+ if [ -f "$target" ]; then
187
+ IFS= read -r gl < "$target" || :
188
+ gl=${gl#gitdir: }
189
+ case $gl in /*) target=$gl ;; *) target=${real%/*}/$gl ;; esac
190
+ fi
191
+ named=$(cd -P "$target" 2>/dev/null && pwd -P) || named=
192
+ if [ "$named" = "$real" ]; then ws=$parent; fi
193
+ ;;
194
+ esac
195
+ cache="$ws/.fleet/recipe.json"
170
196
 
171
197
  # Absent is its own refusal, ahead of the interpreter probe: it is the one
172
198
  # state every fresh repository starts in, and its message must name the step
@@ -7,11 +7,13 @@
7
7
  // private copy of it.
8
8
  //
9
9
  // The answer is git's: `rev-parse --git-common-dir` names the common git dir
10
- // every worktree of one repository shares, and git-env.mjs's
11
- // workspaceDirFromGitCommonDir() turns that answer into the workspace
12
- // holding it. This module is the spawn around that function — the scrubbed
13
- // env, the bound, the join onto `.fleet/` — so a new `.fleet/`-rooted file is
14
- // one `fleetFile("name")` call rather than another hand-spelled probe.
10
+ // every worktree of one repository shares, and git-env.mjs's resolveWorkspace()
11
+ // turns that answer into the workspace it names: the common git dir's parent
12
+ // when the common dir is named `.git` or that parent's own `.git` resolves to
13
+ // it, otherwise the common git dir itself. This module is the spawn around
14
+ // that function — the scrubbed env, the bound, the join onto `.fleet/` — so a
15
+ // new `.fleet/`-rooted file is one `fleetFile("name")` call rather than
16
+ // another hand-spelled probe.
15
17
  //
16
18
  // One error policy: anything that leaves no workspace THROWS
17
19
  // FleetDirUnresolvable, never a null or an empty path. What a caller does
@@ -32,13 +34,7 @@ import { createHash } from "node:crypto";
32
34
  import { existsSync } from "node:fs";
33
35
  import { homedir } from "node:os";
34
36
  import { basename, dirname, join } from "node:path";
35
- import { gitEnv, workspaceDirFromGitCommonDir } from "./git-env.mjs";
36
-
37
- // A `rev-parse` answers in milliseconds; this bound exists so a git that
38
- // never answers cannot hang its caller, not to time a healthy one. A caller
39
- // with an override of its own (ledger.mjs's LEDGER_GIT_TIMEOUT) passes the
40
- // value it settled on as `timeoutMs`.
41
- const DEFAULT_GIT_TIMEOUT_MS = 10_000;
37
+ import { DEFAULT_GIT_TIMEOUT_MS, WorkspaceProbeFailed, gitEnv, resolveWorkspace } from "./git-env.mjs";
42
38
 
43
39
  // The cause reaches stderr inside a single warning line, so it is capped,
44
40
  // keeping the END — the part of a child's stderr that says why it stopped.
@@ -73,6 +69,33 @@ function ended(r) {
73
69
  return r.status === null ? "" : `exit ${r.status}`;
74
70
  }
75
71
 
72
+ // The probe every `.fleet/` answer and the scratch root share: git's common
73
+ // dir, then the workspace it names. Every failure throws FleetDirUnresolvable
74
+ // with git's own reason.
75
+ function workspaceOf(cwd, timeoutMs, canonicalise) {
76
+ const r = spawnSync("git", ["rev-parse", "--git-common-dir"], {
77
+ cwd, encoding: "utf8", timeout: timeoutMs ?? DEFAULT_GIT_TIMEOUT_MS, env: gitEnv(),
78
+ });
79
+ // No separate `r.status === 0` gate: every failure mode (no repository, an
80
+ // unresolvable GIT_DIR, a permission-denied `.git`, a corrupt worktree
81
+ // pointer, a missing `git` binary, a timed-out probe) leaves `r.stdout`
82
+ // empty, which resolveWorkspace() reads as `null` on its own.
83
+ let found;
84
+ try {
85
+ found = resolveWorkspace(r.stdout, cwd, { canonicalise, timeoutMs });
86
+ } catch (e) {
87
+ // `--git-common-dir` answered; the rule's own probe is what failed, and
88
+ // its message names that probe.
89
+ if (!(e instanceof WorkspaceProbeFailed)) throw e;
90
+ throw new FleetDirUnresolvable(`could not resolve the workspace: ${e.message}`);
91
+ }
92
+ if (found === null) {
93
+ const why = cause(r.error && r.error.message, r.stderr) || ended(r);
94
+ throw new FleetDirUnresolvable(`could not resolve --git-common-dir${why ? `: ${why}` : ""}`);
95
+ }
96
+ return found;
97
+ }
98
+
76
99
  /**
77
100
  * The absolute path of `name` under the run's `.fleet/` directory, resolved
78
101
  * from `cwd` — or the `.fleet/` directory itself when `name` is null.
@@ -81,7 +104,7 @@ function ended(r) {
81
104
  * makes `--git-common-dir` answer for a DIFFERENT repository, which would put
82
105
  * the run's file in someone else's workspace, silently, at exit 0.
83
106
  *
84
- * `canonicalise` is workspaceDirFromGitCommonDir()'s opt-in, passed through:
107
+ * `canonicalise` is git-env.mjs's resolveWorkspace() opt-in, passed through:
85
108
  * only a caller that keys something on the path (the cockpit's port) takes
86
109
  * it. Everyone else prints the path it resolves, and realpath would change
87
110
  * that spelling without changing which file it names.
@@ -91,19 +114,8 @@ function ended(r) {
91
114
  * `timeoutMs` — with git's own reason in the message.
92
115
  */
93
116
  export function fleetFile(name, { cwd = process.cwd(), timeoutMs, canonicalise = false } = {}) {
94
- const r = spawnSync("git", ["rev-parse", "--git-common-dir"], {
95
- cwd, encoding: "utf8", timeout: timeoutMs ?? DEFAULT_GIT_TIMEOUT_MS, env: gitEnv(),
96
- });
97
- // No separate `r.status === 0` gate: every failure mode (no repository, an
98
- // unresolvable GIT_DIR, a permission-denied `.git`, a corrupt worktree
99
- // pointer, a missing `git` binary, a timed-out probe) leaves `r.stdout`
100
- // empty, which workspaceDirFromGitCommonDir() reads as `null` on its own.
101
- const workspace = workspaceDirFromGitCommonDir(r.stdout, cwd, { canonicalise });
102
- if (workspace === null) {
103
- const why = cause(r.error && r.error.message, r.stderr) || ended(r);
104
- throw new FleetDirUnresolvable(`could not resolve --git-common-dir${why ? `: ${why}` : ""}`);
105
- }
106
- return name === null ? join(workspace, ".fleet") : join(workspace, ".fleet", name);
117
+ const { dir } = workspaceOf(cwd, timeoutMs, canonicalise);
118
+ return name === null ? join(dir, ".fleet") : join(dir, ".fleet", name);
107
119
  }
108
120
 
109
121
  /**
@@ -113,8 +125,9 @@ export function fleetFile(name, { cwd = process.cwd(), timeoutMs, canonicalise =
113
125
  * point that has no dispatcher to name one.
114
126
  *
115
127
  * `<repo-key>` is `<basename>-<8 hex>`. `<basename>` is the folder name of the
116
- * workspace — the directory holding the COMMON git dir, the same lookup
117
- * fleetFile() makes, so a linked worktree maps to its main checkout — and the
128
+ * workspace fleetFile() resolves — a checkout's directory, so a linked worktree
129
+ * maps to its main checkout, or a bare repository's or submodule's git dir
130
+ * (a trailing `.git` on that name is dropped) — and the
118
131
  * hex is the first 8 characters of the sha256 of that directory's realpath,
119
132
  * so two clones that share a name get different roots. Both come from the
120
133
  * canonical form, so a symlinked route to one workspace is not a second root.
@@ -123,9 +136,10 @@ export function fleetFile(name, { cwd = process.cwd(), timeoutMs, canonicalise =
123
136
  * FleetDirUnresolvable exactly as fleetFile() does.
124
137
  */
125
138
  export function scratchRoot({ cwd = process.cwd(), timeoutMs, home = homedir() } = {}) {
126
- const workspace = dirname(fleetFile(null, { cwd, timeoutMs, canonicalise: true }));
127
- const hex = createHash("sha256").update(workspace).digest("hex").slice(0, 8);
128
- return join(scratchParent(home), `${basename(workspace)}-${hex}`);
139
+ const { dir, gitDir } = workspaceOf(cwd, timeoutMs, true);
140
+ const folder = basename(dir);
141
+ const hex = createHash("sha256").update(dir).digest("hex").slice(0, 8);
142
+ return join(scratchParent(home), `${gitDir ? folder.replace(/\.git$/, "") : folder}-${hex}`);
129
143
  }
130
144
 
131
145
  /** The directory every run's scratch root sits directly in: `<home>/.fleet/scratch`. */
@@ -1,9 +1,11 @@
1
- // Shared by every `.mjs` script under this directory that shells out to git —
2
- // two exports, one per half of the same spawn. `gitEnv()` builds the env the
3
- // git child is given; `workspaceDirFromGitCommonDir()` turns what the most
4
- // common of those children answers with, `rev-parse --git-common-dir`, into
5
- // the workspace directory a run's files live under. The first half's
6
- // reasoning is below; the second's sits beside its own function.
1
+ // Shared by every `.mjs` script under this directory that shells out to git.
2
+ // `gitEnv()` builds the env a git child is given. The rest turns what the
3
+ // most common of those children answers with, `rev-parse --git-common-dir`,
4
+ // into a directory: `resolveWorkspace()` (and `workspaceDirFromGitCommonDir()`,
5
+ // its directory alone) names where a run's files live, spawning one more
6
+ // probe of its own when the answer needs it; `mainCheckoutDirFromGitCommonDir()`
7
+ // names the main checkout's work tree. `gitEnv()`'s reasoning is below; the
8
+ // rest sits beside its own functions.
7
9
  //
8
10
  // GIT_DIR and GIT_WORK_TREE outrank both the child's cwd and an explicit `-C`
9
11
  // argument — measured directly: a `git rev-parse`/`ls-files` call
@@ -29,9 +31,6 @@
29
31
  // would be churn with no behavioural change. The suite's census of
30
32
  // ambient-var scrubs carries it by name instead of by import.
31
33
 
32
- import { realpathSync } from "node:fs";
33
- import { dirname, resolve } from "node:path";
34
-
35
34
  /**
36
35
  * `base` (defaulting to `process.env`) with GIT_DIR and GIT_WORK_TREE
37
36
  * removed, so a git child spawned with the result cannot be retargeted by
@@ -55,61 +54,154 @@ export function gitEnv(overrides = {}, base = process.env) {
55
54
  // answer the same way, because the answer is the same shape wherever it is
56
55
  // asked: the common dir is shared by every worktree of one repository (git
57
56
  // answers with the MAIN checkout's git dir from inside a linked worktree), so
58
- // its PARENT is the one workspace a run has, whichever worktree asked. That
59
- // is why a member running from `.worktrees/<n>-slug` and the controller
60
- // running from the checkout root agree about the run's single ledger, its
61
- // single heartbeat and its single board.
57
+ // every worktree of one repository resolves to ONE workspace, whichever
58
+ // worktree asked. That is why a member running from `.worktrees/<n>-slug` and
59
+ // the controller running from the checkout root agree about the run's single
60
+ // ledger, its single heartbeat and its single board.
61
+ //
62
+ // The workspace is the common dir's parent when the common dir is named
63
+ // `.git` or when that parent's own `.git` resolves to it (the `.bare`
64
+ // layout's gitfile); otherwise it is the common dir itself — a bare
65
+ // repository's, a submodule's or a `--separate-git-dir` clone's git dir — so
66
+ // two such dirs sharing a parent do not collapse onto one workspace. The
67
+ // rule's full statement sits beside `resolveWorkspace()` below. The main
68
+ // checkout's work tree is a separate question with its own answer,
69
+ // `mainCheckoutDirFromGitCommonDir()`: a `.git` symlinked to a git dir
70
+ // elsewhere moves the workspace out of the checkout, never the work tree.
62
71
  //
63
72
  // For a run's `.fleet/` files the question is asked in one place,
64
- // fleet-dir.mjs's fleetFile(), which spawns the probe and hands its answer to
65
- // this function. What is NOT shared is the part each caller owns: the
73
+ // fleet-dir.mjs's private workspaceOf(), which spawns `--git-common-dir`,
74
+ // hands the answer to `resolveWorkspace()` and serves both fleetFile() and
75
+ // scratchRoot(). What is NOT shared is the part each caller owns: the
66
76
  // filename it joins on, the wording of the warning it degrades with, and what
67
- // its own degraded answer is. Hence the seam: this function answers the
68
- // directory or `null`, and every caller composes the rest around it.
77
+ // its own degraded answer is. Hence the seam: this module answers
78
+ // `{dir, gitDir}` or `null`, or throws WorkspaceProbeFailed, and every caller
79
+ // composes the rest around it.
80
+
81
+ import { spawnSync } from "node:child_process";
82
+ import { realpathSync } from "node:fs";
83
+ import { basename, dirname, join, resolve } from "node:path";
84
+
85
+ // A `rev-parse` answers in milliseconds; this bound exists so a git that never
86
+ // answers cannot hang its caller, not to time a healthy one.
87
+ export const DEFAULT_GIT_TIMEOUT_MS = 10_000;
88
+
89
+ // Thrown when the one probe the rule needs beyond `--git-common-dir` could not
90
+ // run to an answer: git missing, or killed at its bound. Not thrown for a git
91
+ // that ran and refused — that is an answer, and the rule reads it as "no".
92
+ export class WorkspaceProbeFailed extends Error {
93
+ constructor(message) {
94
+ super(message);
95
+ this.name = "WorkspaceProbeFailed";
96
+ }
97
+ }
98
+
99
+ /** The realpath of `path`, or `path` itself when it does not resolve. */
100
+ function realpathOr(path) {
101
+ try { return realpathSync(path); } catch { return path; }
102
+ }
103
+
104
+ /** The realpath of `path`; when `path` itself does not exist, the realpath of its parent joined with its basename. */
105
+ function canonicalPath(path) {
106
+ try { return realpathSync(path); } catch { return join(realpathOr(dirname(path)), basename(path)); }
107
+ }
108
+
109
+ // Why a probe that did not answer did not: the spawn error, the signal that
110
+ // killed it, or its stderr. Its caller reaches it only for a spawn error or a
111
+ // probe with no exit status, so no exit code is ever left to name.
112
+ function probeWhy(r) {
113
+ if (r.error && r.error.message) return r.error.message;
114
+ if (r.signal) return `killed by ${r.signal}`;
115
+ return String(r.stderr ?? "").trim() || "no answer";
116
+ }
117
+
118
+ // Does `<parent>/.git` name `gitDir` (a realpath)? `--resolve-git-dir` follows
119
+ // a gitfile, so the `.bare` layout's `.git` file answers with `.bare`.
120
+ function parentGitDirNames(parent, gitDir, cwd, timeoutMs) {
121
+ const candidate = join(parent, ".git");
122
+ const r = spawnSync("git", ["rev-parse", "--resolve-git-dir", candidate], {
123
+ cwd, encoding: "utf8", timeout: timeoutMs ?? DEFAULT_GIT_TIMEOUT_MS, env: gitEnv(),
124
+ });
125
+ if (r.error || r.status === null) {
126
+ throw new WorkspaceProbeFailed(`could not resolve ${candidate}: ${probeWhy(r)}`);
127
+ }
128
+ if (r.status !== 0) return false;
129
+ return realpathOr(resolve(parent, r.stdout.trim())) === gitDir;
130
+ }
69
131
 
70
132
  /**
71
- * The workspace directory a `git rev-parse --git-common-dir` answer names —
72
- * the directory HOLDING the common git dir — resolved against `cwd`, or
73
- * `null` when the answer carries nothing usable.
133
+ * The workspace a `git rev-parse --git-common-dir` answer names, resolved
134
+ * against `cwd`, plus `gitDir`: true when the workspace IS the common git dir,
135
+ * false when it is the directory holding a checkout's `.git`. `null` when the
136
+ * answer is empty.
137
+ *
138
+ * The rule, on the common dir `C` (the realpath of the answer):
139
+ * 1. `C` is named `.git`: the workspace is its parent. No spawn.
140
+ * 2. Otherwise `<parent of C>/.git` is probed with `--resolve-git-dir`. If it
141
+ * names `C`, the workspace is that parent (the `.bare` layout). A git that
142
+ * refuses, or names something else, is "no".
143
+ * 3. Otherwise the workspace is `C` itself, with `gitDir: true`.
144
+ *
145
+ * `gitDir` is what the scratch root's key reads: a git dir's `.git` suffix
146
+ * (`x.git`) is dropped from the key; a checkout's folder name is not touched,
147
+ * so a plain clone in a folder named `x.git` keeps its key.
74
148
  *
75
- * `null` is the signal every caller's degrade arm branches on, and the reason
76
- * this returns it rather than a cwd-relative fallback of its own: what a
77
- * degraded answer should be is the caller's to say (fleet-dir.mjs turns it
78
- * into a thrown error its own callers each degrade from in their own way),
79
- * and so is the warning that must accompany it — a degrade nobody announces
80
- * is the failure class those warnings exist to close.
149
+ * The answer is resolved against `cwd` (default `process.cwd()`): git answers
150
+ * RELATIVE — `.git` — from a checkout's top level.
81
151
  *
82
- * `resolve(cwd, …)` rather than resolve()'s implicit `process.cwd()`: git
83
- * answers this RELATIVE — a bare `.git` — when it runs from a checkout's top
84
- * level, and the cwd that was relative to is an argument here, not ambient,
85
- * so a caller that spawned git in a cwd of its choosing (fleet-dir.mjs's
86
- * `cwd` option) resolves the answer against that same cwd. `cwd` defaults to
87
- * `process.cwd()`, which is what a caller that spawns git without one
88
- * resolved against.
152
+ * Return spelling, when `canonicalise` is off: the path as the answer spelled
153
+ * it, resolved against `cwd`. `canonicalise: true` returns the realpath form.
154
+ * The cockpit's key needs the canonical form; the ledger and the heartbeat
155
+ * print the path they resolve, so they keep the spelling. The probe itself
156
+ * always works from the realpath, so a symlinked `.git` and the checkout it
157
+ * serves agree on the shape.
89
158
  *
90
- * The `trim()` is what makes a newline-only answer the `null` case rather
91
- * than a path; a trailing newline riding on a real answer would be discarded
92
- * by `dirname()` anyway, together with the rest of the final segment.
159
+ * A path that does not resolve is not a failure: the caller gets back the
160
+ * uncanonicalised path.
161
+ *
162
+ * Throws WorkspaceProbeFailed only when the step-2 probe could not run to an
163
+ * answer.
164
+ */
165
+ export function resolveWorkspace(gitCommonDir, cwd = process.cwd(), { canonicalise = false, timeoutMs } = {}) {
166
+ const common = String(gitCommonDir ?? "").trim();
167
+ if (!common) return null;
168
+ const spelled = resolve(cwd, common);
169
+ const real = canonicalPath(spelled);
170
+ const chosen = canonicalise ? real : spelled;
171
+ if (basename(real) === ".git" || parentGitDirNames(dirname(real), real, cwd, timeoutMs)) {
172
+ return { dir: dirname(chosen), gitDir: false };
173
+ }
174
+ return { dir: chosen, gitDir: true };
175
+ }
176
+
177
+ /** `resolveWorkspace()`'s directory, without its shape. Same rule, same throw. */
178
+ export function workspaceDirFromGitCommonDir(gitCommonDir, cwd = process.cwd(), options = {}) {
179
+ return resolveWorkspace(gitCommonDir, cwd, options)?.dir ?? null;
180
+ }
181
+
182
+ /**
183
+ * The main checkout's WORK TREE a `git rev-parse --git-common-dir` answer
184
+ * names: the answer's parent, resolved against `cwd`. `null` when the answer
185
+ * is empty. No spawn, no throw.
93
186
  *
94
- * `canonicalise` is OPT-IN, and deliberately so. The cockpit takes it,
95
- * through fleet-dir.mjs: a symlinked route to one workspace derives a SECOND
96
- * port and a second state directory for a cockpit already being served, so
97
- * the cockpit's key has to be the canonical form. The ledger and the
98
- * heartbeat do not — both PRINT the path they resolve (the ledger in
99
- * `check`'s JSON, both in their degrade warnings), and realpath would change
100
- * that output without changing which file they reach, since the canonical and
101
- * symlinked spellings of one path are one file. Left off, this function reads
102
- * nothing: `canonicalise: true` is its only filesystem access.
187
+ * This is a different question from `resolveWorkspace()`'s, which asks where
188
+ * a repository's stores live, and the two answers part for a `.git`
189
+ * symlinked to a git dir elsewhere: asked from that checkout, git spells the
190
+ * common dir through the link (`.git`, `../.git`), so this answers the
191
+ * folder holding the link, while the store rule follows the link out of the
192
+ * checkout. A caller that runs `git status` in the main checkout, hashes its
193
+ * files or guards writes into it asks this one. From a linked worktree of
194
+ * such a checkout git answers with the link's target instead, so its parent
195
+ * is not the checkout — a known limit of this formula. In a bare, submodule
196
+ * or `--separate-git-dir` layout the parent is not a work tree at all;
197
+ * running a run from one of those is not supported.
103
198
  *
104
- * A path that does not resolve is not a failure when it is asked for: the
105
- * caller gets a usable key back, just an uncanonicalised one. A workspace
106
- * directory removed out from under a running cockpit must not turn resolution
107
- * into a throw.
199
+ * `canonicalise: true` returns the realpath form, or the path as resolved
200
+ * when it does not resolve.
108
201
  */
109
- export function workspaceDirFromGitCommonDir(gitCommonDir, cwd = process.cwd(), { canonicalise = false } = {}) {
202
+ export function mainCheckoutDirFromGitCommonDir(gitCommonDir, cwd = process.cwd(), { canonicalise = false } = {}) {
110
203
  const common = String(gitCommonDir ?? "").trim();
111
204
  if (!common) return null;
112
- const workspace = dirname(resolve(cwd, common));
113
- if (!canonicalise) return workspace;
114
- try { return realpathSync(workspace); } catch { return workspace; }
205
+ const dir = dirname(resolve(cwd, common));
206
+ return canonicalise ? realpathOr(dir) : dir;
115
207
  }
@@ -10,7 +10,7 @@
10
10
  //
11
11
  // THE BASELINE. Recorded once per run, in Phase 0 beside `instruments.sh
12
12
  // --pin` (after the fast-forward, before anything reads), at
13
- // `<workspace>/.fleet/main-checkout.sha` — instruments.sh's own
13
+ // `<main checkout>/.fleet/main-checkout.sha` (ROOT below) — instruments.sh's own
14
14
  // `.fleet/instruments.sha` precedent. It holds the main checkout's
15
15
  // `git status --porcelain -uall` entries AND a content hash of every path
16
16
  // they name, so the maintainer's own uncommitted work at run start is allowed
@@ -102,10 +102,11 @@
102
102
  // any ancestry read.
103
103
  //
104
104
  // ROOT. The main checkout is the parent of `git rev-parse --git-common-dir`
105
- // (git-env.mjs's `workspaceDirFromGitCommonDir`, as fleet-tick.mjs resolves
106
- // the shortlist) — never `--show-toplevel`, which answers a WORKTREE's root
107
- // from inside one — and every git child gets `gitEnv()`, so an ambient
108
- // GIT_DIR/GIT_WORK_TREE cannot answer for another repository.
105
+ // (git-env.mjs's `mainCheckoutDirFromGitCommonDir`) — the work tree, which a
106
+ // symlinked `.git` does not move, never git-env.mjs's store rule — and never
107
+ // `--show-toplevel`, which answers a WORKTREE's root from inside one. Every
108
+ // git child gets `gitEnv()`, so an ambient GIT_DIR/GIT_WORK_TREE cannot answer
109
+ // for another repository.
109
110
  //
110
111
  // CLI:
111
112
  // main-checkout.mjs --record write the baseline (Phase 0; or the
@@ -122,7 +123,7 @@ import { lstatSync, mkdirSync, readFileSync, readlinkSync, renameSync, writeFile
122
123
  import { join } from "node:path";
123
124
  import { isCLI } from "./is-cli.mjs";
124
125
  import { makeDie, defineFlags } from "./arg.mjs";
125
- import { gitEnv, workspaceDirFromGitCommonDir } from "./git-env.mjs";
126
+ import { gitEnv, mainCheckoutDirFromGitCommonDir } from "./git-env.mjs";
126
127
 
127
128
  export const BASELINE_FILE = "main-checkout.sha";
128
129
  export const RECORD_COMMAND = "~/.fleet/bin/fleet-run main-checkout.mjs --record";
@@ -157,7 +158,7 @@ function git(what, args, cwd, env) {
157
158
  export function resolveMainCheckout(cwd = process.cwd(), env = process.env) {
158
159
  const r = git("git rev-parse --git-common-dir", ["rev-parse", "--git-common-dir"], cwd, env);
159
160
  if (!r.ok) return r;
160
- const root = workspaceDirFromGitCommonDir(r.stdout, cwd);
161
+ const root = mainCheckoutDirFromGitCommonDir(r.stdout, cwd);
161
162
  return root === null ? { ok: false, why: "git rev-parse --git-common-dir answered nothing" } : { ok: true, root };
162
163
  }
163
164
 
@@ -57,10 +57,10 @@
57
57
  // `decide()` is the whole policy and touches nothing: the handler resolves the
58
58
  // main checkout, then hands it and a `check-ignore` probe in. The main
59
59
  // checkout is the parent of `git rev-parse --git-common-dir` (git-env.mjs's
60
- // `workspaceDirFromGitCommonDir`, as `fleet-tick.mjs` resolves the run's
61
- // workspace) — never `--show-toplevel`, which answers a WORKTREE's root from
62
- // inside one — and every git child gets `gitEnv()`, so an ambient GIT_DIR
63
- // cannot answer for another repository.
60
+ // `mainCheckoutDirFromGitCommonDir`) — the work tree, which a symlinked `.git`
61
+ // does not move, never git-env.mjs's store rule — and never `--show-toplevel`,
62
+ // which answers a WORKTREE's root from inside one. Every git child gets
63
+ // `gitEnv()`, so an ambient GIT_DIR cannot answer for another repository.
64
64
  //
65
65
  // Zero deps: node builtins and sibling scripts only.
66
66
 
@@ -69,7 +69,7 @@ import { realpathSync } from "node:fs";
69
69
  import { homedir } from "node:os";
70
70
  import { basename, dirname, isAbsolute, join, resolve, sep } from "node:path";
71
71
  import { fileURLToPath } from "node:url";
72
- import { gitEnv, workspaceDirFromGitCommonDir } from "./git-env.mjs";
72
+ import { gitEnv, mainCheckoutDirFromGitCommonDir } from "./git-env.mjs";
73
73
  import { CELL_DEF } from "./ledger-grammar.mjs";
74
74
 
75
75
  /** The task names the controller gives fleet members; a subagent whose parent carries one is a member's child, and a member whose own id matches this is caught directly, whatever definition name its dispatch gave it. */
@@ -238,7 +238,7 @@ async function resolveMainRoot(cwd) {
238
238
  // by the dead path rather than "(or any …": that is a broken repo, and blocks.
239
239
  if (!r.error && r.status !== 0 && /not a git repository \(or any/i.test(r.stderr)) return null;
240
240
  if (r.error || r.status !== 0) return new Error(failure(r, "git rev-parse --git-common-dir"));
241
- return workspaceDirFromGitCommonDir(r.stdout, cwd, { canonicalise: true })
241
+ return mainCheckoutDirFromGitCommonDir(r.stdout, cwd, { canonicalise: true })
242
242
  ?? new Error("git rev-parse --git-common-dir answered nothing");
243
243
  }
244
244
 
@@ -81,7 +81,7 @@ import { mkdirSync, writeFileSync } from "node:fs";
81
81
  import { dirname, join } from "node:path";
82
82
  import { fileURLToPath } from "node:url";
83
83
  import { makeDie, defineFlags, writeAll } from "./arg.mjs";
84
- import { gitEnv, workspaceDirFromGitCommonDir } from "./git-env.mjs";
84
+ import { gitEnv, mainCheckoutDirFromGitCommonDir } from "./git-env.mjs";
85
85
 
86
86
  const NAME = "merge-gate";
87
87
 
@@ -214,8 +214,9 @@ const isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v)
214
214
  const CHILD = { encoding: "utf8", stdio: ["ignore", "pipe", "inherit"] };
215
215
 
216
216
  // --- instruments.sh -------------------------------------------------------
217
- // `--repo` is the directory holding the git COMMON dir — the main checkout,
218
- // where the run's baseline `.fleet/instruments.sha` lives — never the cwd's
217
+ // `--repo` is the main checkout — the directory holding the git COMMON dir,
218
+ // git-env.mjs's `mainCheckoutDirFromGitCommonDir` — where the run's baseline
219
+ // `.fleet/instruments.sha` lives, never the cwd's
219
220
  // own top level: from a worktree that has no baseline, and instruments.sh
220
221
  // exits 2 on a missing baseline instead of comparing anything. gitEnv():
221
222
  // an ambient GIT_DIR would otherwise answer `--git-common-dir` for a
@@ -226,7 +227,7 @@ const CHILD = { encoding: "utf8", stdio: ["ignore", "pipe", "inherit"] };
226
227
  // `root` is returned too: main-gain.mjs reads the same main checkout.
227
228
  function readInstruments() {
228
229
  const common = spawnSync("git", ["rev-parse", "--git-common-dir"], { ...CHILD, env: gitEnv() });
229
- const root = common.error || common.status !== 0 ? null : workspaceDirFromGitCommonDir(common.stdout);
230
+ const root = !common.error && common.status === 0 ? mainCheckoutDirFromGitCommonDir(common.stdout) : null;
230
231
  if (root === null) return { exit: null, digest: null, root };
231
232
  const r = spawnSync("sh", [join(SCRIPT_DIR, "instruments.sh"), "--repo", root], CHILD);
232
233
  const digest = (r.stdout ?? "").trim().split("\n")[0] || null;
package/scripts/pull.mjs CHANGED
@@ -53,19 +53,32 @@
53
53
  // the brief.
54
54
  // 4 Q2 decided `decided`, or a cause whose comment is posted and whose
55
55
  // label replaces `ready-for-agent`.
56
- // 5 Q3 collision the scan first: the brief's paths, and every path a
57
- // `paths <p>…` answer added, against each open PR's `gh pr diff
58
- // <M> --name-only` and each live worktree branch's `git diff
59
- // --name-only -z origin/main...<branch>` — `main` excepted, and
60
- // a branch whose upstream is gone, its PR already merged or
61
- // closed. A path matches a changed file of that path, one
62
- // under it as a directory, or, with no `/`, one of that name.
63
- // One line per PR or branch sharing a path, `no overlap` when
64
- // none, and `could not look: <which>` for one that could not be
65
- // read; the `#N` refs of the brief's Out of scope section are
66
- // printed as the behind-issue candidates. Then `clear`,
67
- // `behind-pr:#M`, `behind-issue:#M`, or `paths <p>…`, which
68
- // scans again and asks again. An exclusion is a ledger row.
56
+ // 5 Q3 collision the scan first: the brief's paths, its Out of scope
57
+ // section's excepted, and every path a `paths <p>…` answer
58
+ // added, against each open PR's `gh pr diff <M> --name-only`
59
+ // and each live worktree branch's `git diff --name-only -z
60
+ // origin/main...<branch>` — `main` excepted, and a branch whose
61
+ // upstream is gone, its PR already merged or closed. A path,
62
+ // its trailing `:N` or `:N-M` dropped, matches a changed file
63
+ // of that path, one under it as a directory, with no `/` one of
64
+ // that name, or, holding a `/` but not starting with one, one
65
+ // whose trailing whole segments it is or sits under. One line
66
+ // per PR or branch sharing a path, then, from its full diff
67
+ // (`gh pr diff <M>`, or `git diff origin/main...<branch>`),
68
+ // each shared file's hunks by base-side range, each with the
69
+ // Markdown headings its changed lines sit under in the file
70
+ // at the merge-base (a PR's head fetched as `pull/<M>/head`);
71
+ // ranges only for a file that is not Markdown or whose base
72
+ // could not be read, `(new file)` beside each range of a file
73
+ // new in the diff, and `no hunk in the diff` for a shared file
74
+ // the diff holds no hunk for. Each brief path with a line
75
+ // reference in a shared file follows, with its headings on
76
+ // origin/main. `no overlap` when none, and `could not look:
77
+ // <which>` for one that could not be read; the `#N` refs of
78
+ // the brief's Out of scope section are printed as the
79
+ // behind-issue candidates. Then `clear`, `behind-pr:#M`,
80
+ // `behind-issue:#M`, or `paths <p>…`, which scans again and
81
+ // asks again. An exclusion is a ledger row.
69
82
  // 6 claim `claim-ticket.sh <N> impl-<N> implementer --apply`.
70
83
  // 7 route `ticket-router.mjs route …`; a router that refuses releases
71
84
  // the claim, and a release that fails is exit 2 with the claim
@@ -99,7 +112,7 @@ import { gitEnv } from "./git-env.mjs";
99
112
  import { isCLI } from "./is-cli.mjs";
100
113
  import { memberTokens, premisesOf, tierValues } from "./ledger-grammar.mjs";
101
114
  import { sessionFromReceipt } from "./phase0-receipt.mjs";
102
- import { briefPaths, briefText } from "./ticket-router.mjs";
115
+ import { briefPaths, briefText, outOfScope } from "./ticket-router.mjs";
103
116
 
104
117
  const NAME = "pull";
105
118
  const SCRIPTS = dirname(fileURLToPath(import.meta.url));
@@ -186,23 +199,6 @@ export function chainHead(rows, n) {
186
199
 
187
200
  // ── the brief ────────────────────────────────────────────────────────────────
188
201
 
189
- /** The `Out of scope` section of `text`, heading to the next heading of its level or above; null when there is none. */
190
- export function outOfScope(text) {
191
- const all = text.split("\n");
192
- const at = all.findIndex((l) => /^#{1,6}\s*out of scope\b/i.test(l));
193
- if (at === -1) return null;
194
- const level = /^#+/.exec(all[at])[0].length;
195
- let end = all.length;
196
- for (let i = at + 1; i < all.length; i++) {
197
- const h = /^(#{1,6})\s/.exec(all[i]);
198
- if (h !== null && h[1].length <= level) {
199
- end = i;
200
- break;
201
- }
202
- }
203
- return all.slice(at, end).join("\n").trim();
204
- }
205
-
206
202
  /** The ticket's `Out of scope` section: the brief's, else the body's; null when neither holds one. */
207
203
  function scopeOf(issue) {
208
204
  return outOfScope(briefText(issue).trim()) ?? outOfScope(String(issue.body ?? ""));
@@ -214,6 +210,143 @@ export function issueRefs(section) {
214
210
  return [...new Set([...section.matchAll(/(?<![\w/.-])#(\d+)\b/g)].map((m) => `#${m[1]}`))];
215
211
  }
216
212
 
213
+ // ── the collision scan ───────────────────────────────────────────────────────
214
+
215
+ // A brief path's trailing line reference, `:N` or `:N-M`.
216
+ const LINE_REF = /:(\d+)(?:-(\d+))?$/;
217
+ const MARKDOWN = /\.(md|markdown|mdx)$/i;
218
+ // The byte each one-letter escape of a C-quoted diff path stands for.
219
+ const ESC = { n: 10, t: 9, '"': 34, "\\": 92, a: 7, b: 8, f: 12, r: 13, v: 11 };
220
+
221
+ /**
222
+ * Whether brief path `p` names changed file `f`, once a trailing `:N` or `:N-M`
223
+ * line reference is dropped: the same path, a directory above it (with or
224
+ * without its trailing `/`), or, with no `/`, a file by its name. A path that
225
+ * holds a `/` and does not start with one is also a suffix on whole segments,
226
+ * naming a file whose trailing segments equal it or one under a directory
227
+ * whose trailing segments do. A path starting with `/` is a slash command and
228
+ * is never a suffix.
229
+ */
230
+ export function pathHits(p, f) {
231
+ const t = p.replace(LINE_REF, "");
232
+ const q = t.replace(/\/+$/, "");
233
+ if (q === "") return false;
234
+ if (f === q || f.startsWith(`${q}/`)) return true;
235
+ if (!q.includes("/")) return f.split("/").pop() === q || (t !== q && f.includes(`/${q}/`));
236
+ return !t.startsWith("/") && (f.endsWith(`/${q}`) || f.includes(`/${q}/`));
237
+ }
238
+
239
+ /** A path as a diff header spells it: C-quoted when git quotes it, its trailing tab dropped. */
240
+ function diffPath(s) {
241
+ const raw = s.replace(/\t$/, "");
242
+ if (!raw.startsWith('"') || !raw.endsWith('"')) return raw;
243
+ const bytes = [];
244
+ for (let i = 1; i < raw.length - 1; i++) {
245
+ if (raw[i] !== "\\") {
246
+ const ch = String.fromCodePoint(raw.codePointAt(i));
247
+ bytes.push(...Buffer.from(ch));
248
+ i += ch.length - 1;
249
+ } else if (/[0-7]{3}/.test(raw.slice(i + 1, i + 4))) {
250
+ bytes.push(parseInt(raw.slice(i + 1, i + 4), 8));
251
+ i += 3;
252
+ } else {
253
+ i += 1;
254
+ bytes.push(ESC[raw[i]] ?? raw.charCodeAt(i));
255
+ }
256
+ }
257
+ return Buffer.from(bytes).toString("utf8");
258
+ }
259
+
260
+ /** The side of a `--- a/<p>` or `+++ b/<p>` line: the path, or null for `/dev/null`. */
261
+ function diffSide(s, prefix) {
262
+ const p = diffPath(s);
263
+ if (p === "/dev/null") return null;
264
+ return p.startsWith(prefix) ? p.slice(prefix.length) : p;
265
+ }
266
+
267
+ /**
268
+ * Every file of a unified git diff, `{ old, new, hunks }`: `old` the base-side
269
+ * path and `new` the other, null for `/dev/null`, and each hunk its base-side
270
+ * range `{ a, b }` from `@@ -a,b` with `from`..`to`, the base-side lines its
271
+ * changes touch — a removed line its own, an added line the one it follows, 0
272
+ * before the first — so its context lines are no part of it. A hunk's own
273
+ * lines are counted off its header, so a removed `-- x` line is never read as
274
+ * a file header.
275
+ */
276
+ export function diffHunks(text) {
277
+ const files = [];
278
+ let file = null;
279
+ let hunk = null;
280
+ let left = 0;
281
+ let right = 0;
282
+ let at = 0;
283
+ for (const line of text.split("\n")) {
284
+ if (left > 0 || right > 0) {
285
+ if (line.startsWith("-")) {
286
+ hunk.from ??= at;
287
+ hunk.to = at++;
288
+ left--;
289
+ } else if (line.startsWith("+")) {
290
+ hunk.from ??= at - 1;
291
+ hunk.to = at - 1;
292
+ right--;
293
+ } else if (!line.startsWith("\\")) {
294
+ at++;
295
+ left--;
296
+ right--;
297
+ }
298
+ continue;
299
+ }
300
+ if (line.startsWith("diff --git ")) {
301
+ file = { old: null, new: null, hunks: [] };
302
+ files.push(file);
303
+ continue;
304
+ }
305
+ if (file === null) continue;
306
+ const h = /^@@ -(\d+)(?:,(\d+))? \+\d+(?:,(\d+))? @@/.exec(line);
307
+ if (h !== null) {
308
+ const a = Number(h[1]);
309
+ const b = h[2] === undefined ? 1 : Number(h[2]);
310
+ hunk = { a, b, from: null, to: null };
311
+ file.hunks.push(hunk);
312
+ left = b;
313
+ right = h[3] === undefined ? 1 : Number(h[3]);
314
+ // An empty base range `-a,0` sits after line a, not on it.
315
+ at = b === 0 ? a + 1 : a;
316
+ } else if (line.startsWith("--- ")) file.old = diffSide(line.slice(4), "a/");
317
+ else if (line.startsWith("+++ ")) file.new = diffSide(line.slice(4), "b/");
318
+ }
319
+ return files;
320
+ }
321
+
322
+ /**
323
+ * The ATX headings of Markdown `text`, `{ line, text }`, 1-based, fenced code
324
+ * skipped. A fence closes only on a run of its own character at least as long
325
+ * with nothing after it but whitespace: a fence line carrying an info string
326
+ * inside a fence is code.
327
+ */
328
+ export function headings(text) {
329
+ const out = [];
330
+ let fence = null;
331
+ text.split("\n").forEach((l, i) => {
332
+ const f = /^ {0,3}(`{3,}|~{3,})(.*)$/.exec(l);
333
+ if (f !== null) {
334
+ if (fence === null) fence = f[1];
335
+ else if (f[1][0] === fence[0] && f[1].length >= fence.length && f[2].trim() === "") fence = null;
336
+ return;
337
+ }
338
+ if (fence === null && /^ {0,3}#{1,6}(\s|$)/.test(l)) out.push({ line: i + 1, text: l.trim() });
339
+ });
340
+ return out;
341
+ }
342
+
343
+ /** The heading lines `from`..`to` sit under: the one enclosing `from`, then each that starts after it, up to `to`. */
344
+ export function sectionsOf(hs, from, to) {
345
+ const above = hs.filter((h) => h.line <= from).at(-1);
346
+ const within = hs.filter((h) => h.line > from && h.line <= to);
347
+ return [above === undefined ? "(no heading above)" : above.text, ...within.map((h) => h.text)].join(" → ");
348
+ }
349
+
217
350
  // The placeholders the implementer's brief template declares. dispatch-prompt.mjs
218
351
  // refuses a value that spells one, and a ticket's text is a value: one that
219
352
  // names `<N>` would stop every render, with the claim standing.
@@ -240,6 +373,8 @@ export function defang(text, names) {
240
373
 
241
374
  const trimmed = (s) => String(s ?? "").trim();
242
375
  const cap = (s) => (s.length > RECORD_MAX ? `…${s.slice(-(RECORD_MAX - 1))}` : s);
376
+ // What the record keeps of a child whose stdout is a whole file or diff: its size.
377
+ const sized = (r) => `${Buffer.byteLength(r.stdout)} bytes`;
243
378
  const now = () => new Date().toISOString();
244
379
 
245
380
  function how(r) {
@@ -248,10 +383,10 @@ function how(r) {
248
383
  return `exit ${r.status}`;
249
384
  }
250
385
 
251
- /** `status` is the exit status, null when the child never ran or was killed (`how` says which). */
252
- function spawn(cmd, args, { cwd, env, timeoutMs } = {}) {
386
+ /** `status` is the exit status, null when the child never ran or was killed (`how` says which). `raw` keeps stdout as printed. */
387
+ function spawn(cmd, args, { cwd, env, timeoutMs, raw = false } = {}) {
253
388
  const r = spawnSync(cmd, args, { cwd, encoding: "utf8", maxBuffer: MAX_BUFFER, env: gitEnv(env), timeout: timeoutMs });
254
- const stdout = trimmed(r.stdout);
389
+ const stdout = raw ? String(r.stdout ?? "") : trimmed(r.stdout);
255
390
  const stderr = trimmed(r.stderr);
256
391
  return { status: r.error ? null : r.status, stdout, stderr, text: [stdout, stderr].filter(Boolean).join("\n"), how: how(r) };
257
392
  }
@@ -546,20 +681,70 @@ class Pull {
546
681
  ];
547
682
  }
548
683
 
549
- // The latest scan, line by line, and the behind-issue candidates.
684
+ // The latest scan, line by line, and the behind-issue candidates. A scan
685
+ // recorded before the hunk evidence holds no `evidence` and no `lineRefs`.
550
686
  collisionContext() {
551
- const { paths, overlaps, unread } = this.st.scans.at(-1);
687
+ const { paths, overlaps, lineRefs = [], unread } = this.st.scans.at(-1);
552
688
  const refs = issueRefs(scopeOf(this.issue()));
553
689
  const who = (o) => (o.branch === undefined ? `PR #${o.pr}` : `branch ${o.branch}${o.pr === null ? "" : ` (PR #${o.pr})`}`);
554
690
  return [
555
691
  `paths scanned: ${paths.length === 0 ? "(none)" : paths.join(" ")}`,
556
- ...overlaps.map((o) => `${who(o)}: ${o.paths.join(" ")}`),
692
+ ...overlaps.flatMap((o) => [`${who(o)}: ${o.paths.join(" ")}`, ...(o.evidence ?? [])]),
693
+ ...lineRefs,
557
694
  ...unread.map((u) => `could not look: ${u}`),
558
695
  ...(overlaps.length === 0 ? ["no overlap"] : []),
559
696
  `behind-issue candidates (Out of scope): ${refs.length === 0 ? "(none)" : refs.join(" ")}`,
560
697
  ];
561
698
  }
562
699
 
700
+ // A Markdown file's headings as it stands at `rev`, `{ hs }`, or `{ why }` it could not be read.
701
+ headingsAt(rev, path) {
702
+ const r = this.exec("collision", "git", "git", [], ["cat-file", "blob", `${rev}:${path}`], { raw: true }, sized);
703
+ return r.status === 0 ? { hs: headings(r.stdout) } : { why: `git cat-file blob ${rev}:${path}: ${failure(r)}` };
704
+ }
705
+
706
+ // The merge-base of origin/main and `rev`, `{ rev }`, or `{ why }` there is none.
707
+ mergeBase(rev) {
708
+ const r = this.exec("collision", "git", "git", [], ["merge-base", "origin/main", rev]);
709
+ return r.status === 0 && r.stdout !== "" ? { rev: r.stdout } : { why: `git merge-base origin/main ${rev}: ${failure(r)}` };
710
+ }
711
+
712
+ // The merge-base a PR's diff is taken against: its head fetched, then met with origin/main.
713
+ prBase(pr) {
714
+ const r = this.exec("collision", "git", "git", [], ["fetch", "-q", "origin", `pull/${pr}/head`], { timeoutMs: NETWORK_TIMEOUT_MS });
715
+ return r.status === 0 ? this.mergeBase("FETCH_HEAD") : { why: `git fetch origin pull/${pr}/head: ${failure(r)}` };
716
+ }
717
+
718
+ // Each shared file's hunks in `diff`, by base-side range, each with the
719
+ // headings its changed lines sit under in the base file `base()` names —
720
+ // ranges only for a file that is not Markdown or whose base could not be
721
+ // read, and `(new file)` beside each range of a file new in the diff. A
722
+ // shared file the diff holds no hunk for prints `no hunk in the diff`.
723
+ hunkLines(files, diff, base) {
724
+ const parsed = diffHunks(diff);
725
+ const lines = [];
726
+ let at;
727
+ for (const f of files) {
728
+ const d = parsed.find((x) => (x.new ?? x.old) === f);
729
+ if (d === undefined || d.hunks.length === 0) {
730
+ lines.push(` ${f}: no hunk in the diff`);
731
+ continue;
732
+ }
733
+ let hs = null;
734
+ if (d.old !== null && MARKDOWN.test(d.old)) {
735
+ at ??= base();
736
+ const read = at.rev === undefined ? at : this.headingsAt(at.rev, d.old);
737
+ if (read.hs === undefined) lines.push(` ${f}: base not read (${read.why})`);
738
+ else hs = read.hs;
739
+ }
740
+ for (const { a, b, from, to } of d.hunks) {
741
+ const where = d.old === null ? " (new file)" : hs === null ? "" : ` ${sectionsOf(hs, from, to)}`;
742
+ lines.push(` ${f} @@ -${a},${b} @@${where}`);
743
+ }
744
+ }
745
+ return lines;
746
+ }
747
+
563
748
  // ── the stages: each returns null to go on to the stage `stage` now names, or a result ──
564
749
  advance() {
565
750
  const { st } = this;
@@ -645,14 +830,11 @@ class Pull {
645
830
  const gone = goneBranches(refs.stdout);
646
831
 
647
832
  const paths = [...new Set([...briefPaths(briefText(this.issue()).trim()), ...st.addedPaths])];
648
- // A path names a changed file, a directory above it (with or without its trailing `/`), or, with no `/`, a file by its name.
649
- const hits = (p, f) => {
650
- const q = p.replace(/\/+$/, "");
651
- return f === q || f.startsWith(`${q}/`) || (!q.includes("/") && f.split("/").pop() === q);
652
- };
833
+ const sharedFiles = new Set();
834
+ // The brief paths a listing shares, and its files they name.
653
835
  const shared = (stdout, sep) => {
654
836
  const files = stdout.split(sep).filter((f) => f !== "");
655
- return paths.filter((p) => files.some((f) => hits(p, f)));
837
+ return { paths: paths.filter((p) => files.some((f) => pathHits(p, f))), files: files.filter((f) => paths.some((p) => pathHits(p, f))) };
656
838
  };
657
839
  const overlaps = [];
658
840
  const unread = [];
@@ -662,7 +844,15 @@ class Pull {
662
844
  if (d.status !== 0) unread.push(`gh pr diff ${pr} (${failure(d)})`);
663
845
  // Fail closed, as pr-overlap.mjs does: a PR with no changed file is a query that did not work, never "no overlap".
664
846
  else if (d.stdout === "") unread.push(`gh pr diff ${pr} (printed no file)`);
665
- else if (common.length > 0) overlaps.push({ pr, paths: common });
847
+ else if (common.paths.length > 0) {
848
+ for (const f of common.files) sharedFiles.add(f);
849
+ const full = this.gh("collision", ["pr", "diff", String(pr)], sized);
850
+ let evidence = [];
851
+ if (full.status !== 0) unread.push(`gh pr diff ${pr} (${failure(full)})`);
852
+ else if (full.stdout === "") unread.push(`gh pr diff ${pr} (printed no diff)`);
853
+ else evidence = this.hunkLines(common.files, full.stdout, () => this.prBase(pr));
854
+ overlaps.push({ pr, paths: common.paths, evidence });
855
+ }
666
856
  }
667
857
  const heads = new Map(prs.map((p) => [p.headRefName, p.number]));
668
858
  for (const branch of worktreeBranches(wt.stdout).filter((b) => b !== "main" && !gone.has(b)).sort()) {
@@ -671,9 +861,32 @@ class Pull {
671
861
  const d = this.exec("collision", "git", "git", [], ["diff", "--name-only", "-z", range, "--"]);
672
862
  const common = shared(d.stdout, "\0");
673
863
  if (d.status !== 0) unread.push(`git diff --name-only ${range} (${failure(d)})`);
674
- else if (common.length > 0) overlaps.push({ branch, pr: heads.get(branch) ?? null, paths: common });
864
+ else if (common.paths.length > 0) {
865
+ for (const f of common.files) sharedFiles.add(f);
866
+ const full = this.exec("collision", "git", "git", [], ["diff", "--no-color", "--no-ext-diff", "--no-textconv", "--src-prefix=a/", "--dst-prefix=b/", range, "--"], {}, sized);
867
+ let evidence = [];
868
+ if (full.status !== 0) unread.push(`git diff ${range} (${failure(full)})`);
869
+ else evidence = this.hunkLines(common.files, full.stdout, () => this.mergeBase(branch));
870
+ overlaps.push({ branch, pr: heads.get(branch) ?? null, paths: common.paths, evidence });
871
+ }
872
+ }
873
+ // A brief path carrying a line reference, in a shared file, with the headings it sits under on origin/main.
874
+ const lineRefs = [];
875
+ const onMain = new Map();
876
+ for (const p of paths) {
877
+ const ref = LINE_REF.exec(p);
878
+ if (ref === null) continue;
879
+ for (const f of [...sharedFiles].filter((x) => pathHits(p, x))) {
880
+ let where = "(not Markdown)";
881
+ if (MARKDOWN.test(f)) {
882
+ if (!onMain.has(f)) onMain.set(f, this.headingsAt("origin/main", f));
883
+ const read = onMain.get(f);
884
+ where = read.hs === undefined ? `(not read: ${read.why})` : sectionsOf(read.hs, Number(ref[1]), Number(ref[2] ?? ref[1]));
885
+ }
886
+ lineRefs.push(`brief ref ${p} (${f} on origin/main): ${where}`);
887
+ }
675
888
  }
676
- st.scans.push({ at: now(), paths, overlaps, unread });
889
+ st.scans.push({ at: now(), paths, overlaps, lineRefs, unread });
677
890
  return this.ask("collision", this.collisionContext());
678
891
  }
679
892
 
@@ -53,7 +53,7 @@
53
53
  // the bound and the command's log.
54
54
  //
55
55
  // On proof, the cache is written atomically to <workspace>/.fleet/recipe.json
56
- // — <workspace> being the directory holding the repository's common git dir,
56
+ // — <workspace> being the directory workspaceDirFromGitCommonDir() names for the repository,
57
57
  // the place derive-testcmd.sh reads it from — and then read back through
58
58
  // derive-testcmd.sh for every field, `uncovered` byte for byte as the compact
59
59
  // JSON of the list given, the Test entrypoint against `derivedAt`'s
@@ -87,7 +87,7 @@ import { tmpdir } from "node:os";
87
87
  import { dirname, join } from "node:path";
88
88
  import { fileURLToPath } from "node:url";
89
89
  import { isCLI } from "./is-cli.mjs";
90
- import { gitEnv, workspaceDirFromGitCommonDir } from "./git-env.mjs";
90
+ import { WorkspaceProbeFailed, gitEnv, workspaceDirFromGitCommonDir } from "./git-env.mjs";
91
91
  import { isDigits } from "./arg.mjs";
92
92
 
93
93
  const NAME = "recipe-prove";
@@ -454,7 +454,11 @@ function main(argv) {
454
454
  const gitDir = git(["rev-parse", "--git-dir"], o.repo);
455
455
  if (!gitDir.ok) throw cannot(`${o.repo} is not a git repository: ${gitDir.err}`);
456
456
  const common = git(["rev-parse", "--path-format=absolute", "--git-common-dir"], o.repo);
457
- const workspace = common.ok ? workspaceDirFromGitCommonDir(common.out, o.repo) : null;
457
+ let workspace = null;
458
+ if (common.ok) {
459
+ try { workspace = workspaceDirFromGitCommonDir(common.out, o.repo); }
460
+ catch (e) { if (!(e instanceof WorkspaceProbeFailed)) throw e; throw cannot(`cannot resolve the common git dir of ${o.repo}: ${e.message}`); }
461
+ }
458
462
  if (!workspace) throw cannot(`cannot resolve the common git dir of ${o.repo}: ${common.err}`);
459
463
  const sha = git(["rev-parse", "--verify", "origin/main^{commit}"], o.repo);
460
464
  if (!sha.ok) throw cannot(`origin/main does not resolve to a commit (${sha.err}) — fetch it; the proof runs against it`);
@@ -5,7 +5,8 @@
5
5
  //
6
6
  // `~/.fleet/scratch/<repo-key>/`, computed by fleet-dir.mjs's scratchRoot() —
7
7
  // the same path from the main checkout and from any linked worktree, a
8
- // different one for a second clone with the same folder name. Nothing is
8
+ // different one for each workspace — a second clone, a bare repository, a
9
+ // submodule — even where folder names collide. Nothing is
9
10
  // written to `.fleet/` or anywhere else to record it: the controller (and any
10
11
  // standalone entry point with no dispatcher) runs this again and gets the same
11
12
  // answer. The controller writes the printed path, absolute, into the prompt of
@@ -90,13 +90,36 @@ export function briefText(issue) {
90
90
  return String(issue.body ?? "");
91
91
  }
92
92
 
93
+ /** The line span `[at, end)` of `lines`' `Out of scope` section, heading to the next heading of its level or above; null when there is none. */
94
+ function outOfScopeSpan(lines) {
95
+ const at = lines.findIndex((l) => /^#{1,6}\s*out of scope\b/i.test(l));
96
+ if (at === -1) return null;
97
+ const level = /^#+/.exec(lines[at])[0].length;
98
+ for (let i = at + 1; i < lines.length; i++) {
99
+ const h = /^(#{1,6})\s/.exec(lines[i]);
100
+ if (h !== null && h[1].length <= level) return { at, end: i };
101
+ }
102
+ return { at, end: lines.length };
103
+ }
104
+
105
+ /** The `Out of scope` section of `text`, heading to the next heading of its level or above; null when there is none. */
106
+ export function outOfScope(text) {
107
+ const all = text.split("\n");
108
+ const span = outOfScopeSpan(all);
109
+ return span === null ? null : all.slice(span.at, span.end).join("\n").trim();
110
+ }
111
+
93
112
  /**
94
113
  * The file paths a brief names: every backticked token without whitespace that
95
- * holds a `/` or ends in an extension, in first-seen order, each once.
114
+ * holds a `/` or ends in an extension, in first-seen order, each once. The
115
+ * brief's `Out of scope` section names no target, so its tokens are skipped.
96
116
  */
97
117
  export function briefPaths(brief) {
118
+ const all = brief.split("\n");
119
+ const span = outOfScopeSpan(all);
120
+ const kept = span === null ? brief : [...all.slice(0, span.at), ...all.slice(span.end)].join("\n");
98
121
  const paths = new Set();
99
- for (const m of brief.matchAll(/`([^`\n]+)`/g)) {
122
+ for (const m of kept.matchAll(/`([^`\n]+)`/g)) {
100
123
  const tok = m[1];
101
124
  if (/\s/.test(tok)) continue;
102
125
  if (tok.includes("/") || /\.[A-Za-z][A-Za-z0-9]*$/.test(tok)) paths.add(tok);
@@ -189,8 +189,17 @@ terminating in exactly one dispatch or an empty shortlist:
189
189
  4. **Collision scan against open PRs and live branches** — `pull.mjs` runs it
190
190
  before Q3 and prints one line per open PR or live worktree branch that shares
191
191
  a path with the brief, `no overlap` when none, and `could not look: <which>`
192
- for one it could not read. Answer Q3 off those lines: an overlap →
193
- `behind-pr:#M`, a branch with no PR yet by its name; a target file the brief
192
+ for one it could not read. A path the brief names only in its `Out of scope`
193
+ section is no target and is not scanned. Under each line come the shared
194
+ files' hunks, each by its base-side range with the Markdown headings its
195
+ changed lines sit under, then each brief `path:line` reference in a shared
196
+ file with its headings on `origin/main`. A shared file is evidence, not a
197
+ verdict. Answer Q3 off those lines: `behind-pr:#M`, a branch with no PR yet
198
+ by its name, only when a construct the brief names, or a brief `path:line`
199
+ reference, lands in or next to a hunk of `#M`'s diff in a shared file — next
200
+ to is the same Markdown section, under the nearest heading above, or, in a
201
+ file with no headings, within 20 lines of the hunk; with no such evidence the
202
+ ticket does not collide, whatever files it shares. A target file the brief
194
203
  does not spell as a path → `paths <p>…`, which scans again and asks again. A
195
204
  PR the scan could not read is still yours to judge, and `behind-pr` on it is
196
205
  taken. `pr-overlap.mjs` is **PR-vs-PR only** — it runs `gh pr diff` on both
@@ -223,7 +232,7 @@ does:
223
232
  | brief names no *what* | relabel `needs-triage`, next entry |
224
233
  | genuine fork — options named, none ruled | relabel `ready-for-human`, next entry |
225
234
  | needs human hands — external access, manual testing, judgment during the work | relabel `ready-for-human`, next entry |
226
- | target files collide with an open PR or a live branch | exclude `behind-pr:#M`, next entry |
235
+ | a construct the brief names, or a brief `path:line` reference, lands in or next to a hunk of an open PR or a live branch | exclude `behind-pr:#M`, next entry |
227
236
  | `Out of scope` sequences it after an open ticket | exclude `behind-issue:#M`, next entry |
228
237
  | `claim-ticket.sh` exit 2 | taken, next entry |
229
238
  | decided, live, free, claimed | row, then dispatch (phase 2) |