continuous-improvement 3.21.0 → 3.22.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.
@@ -0,0 +1,430 @@
1
+ /**
2
+ * git-state: pure classifiers for the `reconcile` ground-truth contract.
3
+ *
4
+ * No I/O. `src/bin/reconcile.mts` does the actual `git` spawning and feeds raw
5
+ * stdout plus exit codes in here; keeping the logic pure lets the unit tests
6
+ * cover every boundary (no configured upstream, detached HEAD, linked worktree,
7
+ * failed remote probe, autocrlf phantom drift) without building a repo per case.
8
+ *
9
+ * This module is also the single source of truth for the ground-truth command
10
+ * set: `GROUND_TRUTH_PROBES` is what `bin/reconcile.mjs` runs and what
11
+ * `bin/check-reconcile-parity.mjs` asserts the reconcile skill and command docs
12
+ * still document. Prose that drifts from this array fails `verify:all`.
13
+ *
14
+ * Every classifier fails closed. "We could not tell" is reported as unknown or
15
+ * unverified, never as clean, even, absent, or landed.
16
+ */
17
+ /** Branch names treated as protected unless the caller overrides the list. */
18
+ export const DEFAULT_PROTECTED_BRANCHES = [
19
+ "main",
20
+ "master",
21
+ "release",
22
+ "production",
23
+ ];
24
+ /**
25
+ * The ground-truth command set.
26
+ *
27
+ * Every entry is portable: plain `git` argv with no shell, no `ls`, no
28
+ * coreutils, and no literal `.git/` path — inside a linked worktree `.git` is a
29
+ * *file*, so a `.git/`-relative probe silently reports nothing. Ordering is the
30
+ * order the runner executes and the renderer prints.
31
+ */
32
+ export const GROUND_TRUTH_PROBES = [
33
+ {
34
+ id: "repo-root",
35
+ args: ["rev-parse", "--show-toplevel"],
36
+ purpose: "Confirm we are inside a work tree and learn its root.",
37
+ tolerateFailure: false,
38
+ },
39
+ {
40
+ id: "head-sha",
41
+ args: ["rev-parse", "HEAD"],
42
+ purpose: "Pin the exact commit every later claim is relative to.",
43
+ tolerateFailure: false,
44
+ },
45
+ {
46
+ id: "head-branch",
47
+ args: ["symbolic-ref", "--quiet", "--short", "HEAD"],
48
+ purpose: "Branch name, or a non-zero exit that proves a detached HEAD.",
49
+ tolerateFailure: true,
50
+ },
51
+ {
52
+ id: "upstream-ref",
53
+ args: ["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"],
54
+ purpose: "Configured upstream, or a non-zero exit that proves there is none.",
55
+ tolerateFailure: true,
56
+ },
57
+ {
58
+ id: "upstream-counts",
59
+ args: ["rev-list", "--left-right", "--count", "@{u}...HEAD"],
60
+ purpose: "Behind/ahead counts; only meaningful once an upstream exists.",
61
+ tolerateFailure: true,
62
+ },
63
+ {
64
+ id: "status-porcelain",
65
+ args: ["status", "--porcelain=v1"],
66
+ purpose: "Reported working-tree changes — inflated by autocrlf on Windows.",
67
+ tolerateFailure: false,
68
+ },
69
+ {
70
+ id: "content-drift",
71
+ args: ["diff", "--name-only", "--ignore-all-space"],
72
+ purpose: "Real content drift — the number to trust when autocrlf is on.",
73
+ tolerateFailure: false,
74
+ },
75
+ {
76
+ id: "stash-list",
77
+ args: ["stash", "list"],
78
+ purpose: "Stashes an earlier session may have left holding real work.",
79
+ tolerateFailure: false,
80
+ },
81
+ {
82
+ id: "worktree-list",
83
+ args: ["worktree", "list", "--porcelain"],
84
+ purpose: "Sibling worktrees another session may be writing to.",
85
+ tolerateFailure: false,
86
+ },
87
+ ];
88
+ /**
89
+ * In-progress operation markers, addressed via `git rev-parse --git-path` so
90
+ * they resolve correctly inside a linked worktree, where `.git` is a file and
91
+ * the real marker lives under `.git/worktrees/<name>/`.
92
+ */
93
+ export const IN_PROGRESS_MARKERS = [
94
+ { id: "merge", gitPath: "MERGE_HEAD", label: "merge in progress" },
95
+ { id: "rebase-merge", gitPath: "rebase-merge", label: "interactive rebase in progress" },
96
+ { id: "rebase-apply", gitPath: "rebase-apply", label: "rebase/am in progress" },
97
+ { id: "cherry-pick", gitPath: "CHERRY_PICK_HEAD", label: "cherry-pick in progress" },
98
+ { id: "revert", gitPath: "REVERT_HEAD", label: "revert in progress" },
99
+ { id: "bisect", gitPath: "BISECT_LOG", label: "bisect in progress" },
100
+ ];
101
+ const SHA = /^[0-9a-f]{7,64}$/i;
102
+ const SAFE_REF = /^[A-Za-z0-9._/-]+$/;
103
+ /** Split git output on either line ending — git on Windows emits CRLF. */
104
+ function toLines(raw) {
105
+ return raw.split(/\r?\n/);
106
+ }
107
+ function isSha(value) {
108
+ return SHA.test(value);
109
+ }
110
+ /**
111
+ * True when `name` is safe to interpolate into a path, an argv entry, or a
112
+ * comparison that authorizes a mutation.
113
+ *
114
+ * Fails closed: null, empty, surrounding whitespace, shell metacharacters,
115
+ * `..`, refspec syntax (`@{`), a leading `-`, empty path components,
116
+ * dot-prefixed or dot-suffixed components, components ending `.lock`, and
117
+ * anything over 255 characters all return false rather than being sanitized
118
+ * into something that then looks valid.
119
+ */
120
+ export function isSafeRefName(name) {
121
+ if (typeof name !== "string")
122
+ return false;
123
+ if (name.length === 0 || name.length > 255)
124
+ return false;
125
+ if (name.trim() !== name)
126
+ return false;
127
+ if (name.startsWith("-"))
128
+ return false;
129
+ if (name.endsWith("/") || name.endsWith(".lock"))
130
+ return false;
131
+ if (name.includes("..") || name.includes("@{"))
132
+ return false;
133
+ const components = name.split("/");
134
+ if (components.some((component) => component.length === 0 ||
135
+ component.startsWith(".") ||
136
+ component.endsWith(".") ||
137
+ component.endsWith(".lock"))) {
138
+ return false;
139
+ }
140
+ return SAFE_REF.test(name);
141
+ }
142
+ /**
143
+ * Classify HEAD from `git symbolic-ref --quiet --short HEAD`.
144
+ *
145
+ * A detached HEAD makes that command exit non-zero with empty output. This
146
+ * module deliberately never uses `git branch --show-current`, which returns an
147
+ * empty string with exit 0 and so cannot be told apart from a successful read.
148
+ * Returns `{ kind: "unknown", branch: null }` when output is present but is not
149
+ * a usable ref name, so an unparseable branch never reads as a match against an
150
+ * expected one.
151
+ */
152
+ export function classifyHead(rawBranch, exitCode = 0) {
153
+ const value = typeof rawBranch === "string" ? rawBranch.trim() : "";
154
+ if (exitCode !== 0 || value.length === 0) {
155
+ return { kind: "detached", branch: null };
156
+ }
157
+ if (!isSafeRefName(value))
158
+ return { kind: "unknown", branch: null };
159
+ return { kind: "branch", branch: value };
160
+ }
161
+ /**
162
+ * Parse `git rev-list --left-right --count @{u}...HEAD` output, which is
163
+ * `"<behind>\t<ahead>"`.
164
+ *
165
+ * Returns null for empty, malformed, negative, non-integer, or unsafe-integer
166
+ * output. Callers must treat null as "unknown" — never as zero.
167
+ */
168
+ export function parseRevListCounts(raw) {
169
+ if (typeof raw !== "string")
170
+ return null;
171
+ const first = toLines(raw).find((line) => line.trim().length > 0);
172
+ if (first === undefined)
173
+ return null;
174
+ const parts = first.trim().split(/\s+/);
175
+ if (parts.length !== 2)
176
+ return null;
177
+ const behind = Number(parts[0]);
178
+ const ahead = Number(parts[1]);
179
+ if (!Number.isSafeInteger(behind) || behind < 0)
180
+ return null;
181
+ if (!Number.isSafeInteger(ahead) || ahead < 0)
182
+ return null;
183
+ return { behind, ahead };
184
+ }
185
+ /**
186
+ * Map counts to an upstream relation.
187
+ *
188
+ * Fails closed: no upstream returns `"no-upstream"`, and an upstream that does
189
+ * exist but whose counts would not parse returns `"unknown"` — never `"even"`.
190
+ */
191
+ export function classifyUpstream(counts, hasUpstream) {
192
+ if (!hasUpstream)
193
+ return "no-upstream";
194
+ if (counts === null)
195
+ return "unknown";
196
+ const { behind, ahead } = counts;
197
+ if (behind === 0 && ahead === 0)
198
+ return "even";
199
+ if (behind > 0 && ahead > 0)
200
+ return "diverged";
201
+ return ahead > 0 ? "ahead" : "behind";
202
+ }
203
+ /**
204
+ * Collect a label for every in-progress operation whose marker is present.
205
+ *
206
+ * `present` is keyed by `InProgressMarker.id`. A marker missing from the map is
207
+ * treated as *unprobed*, not absent, and reported as `"<id>: unprobed"` — a
208
+ * probe that never ran must not masquerade as a clean tree. Returns `[]` only
209
+ * when every known marker was probed and none was present.
210
+ */
211
+ export function classifyInProgress(present) {
212
+ const found = [];
213
+ for (const marker of IN_PROGRESS_MARKERS) {
214
+ const state = present[marker.id];
215
+ if (state === undefined) {
216
+ found.push(`${marker.id}: unprobed`);
217
+ }
218
+ else if (state) {
219
+ found.push(marker.label);
220
+ }
221
+ }
222
+ return found;
223
+ }
224
+ /**
225
+ * True when `branch` must not be pushed to or committed onto directly.
226
+ *
227
+ * Fails closed: null, an unparseable name, and a detached HEAD all return true,
228
+ * because an unknown branch is not proof of safety. Supports one trailing `/*`
229
+ * wildcard per pattern (`release/*`).
230
+ */
231
+ export function isProtectedBranch(branch, patterns = DEFAULT_PROTECTED_BRANCHES) {
232
+ if (!isSafeRefName(branch))
233
+ return true;
234
+ const name = branch;
235
+ return patterns.some((pattern) => pattern.endsWith("/*")
236
+ ? name.startsWith(pattern.slice(0, -1))
237
+ : name === pattern);
238
+ }
239
+ /**
240
+ * Decide whether a push actually landed, from `git ls-remote` output.
241
+ *
242
+ * Three outcomes, never collapsed into two: a non-zero exit is `"unverified"`
243
+ * (the network or the remote failed, so absence of the ref is unproven and the
244
+ * push may well have landed), an empty successful probe is `"not-landed"` (the
245
+ * ref is genuinely absent), and a present ref is compared by SHA. An
246
+ * unparseable local HEAD or unparseable remote output is `"unverified"`.
247
+ */
248
+ export function verifyPushLanded(input) {
249
+ const local = (input.localHead ?? "").trim();
250
+ if (!isSha(local)) {
251
+ return { verdict: "unverified", reason: "local HEAD is not a usable sha" };
252
+ }
253
+ if (input.lsRemoteExitCode !== 0) {
254
+ return {
255
+ verdict: "unverified",
256
+ reason: `git ls-remote exited ${input.lsRemoteExitCode}; absence of the ref is unproven`,
257
+ };
258
+ }
259
+ const raw = (input.lsRemoteStdout ?? "").trim();
260
+ if (raw.length === 0) {
261
+ return { verdict: "not-landed", reason: "remote ref does not exist" };
262
+ }
263
+ const remoteSha = ((toLines(raw)[0] ?? "").trim().split(/\s+/)[0] ?? "");
264
+ if (!isSha(remoteSha)) {
265
+ return { verdict: "unverified", reason: "could not parse a sha from ls-remote output" };
266
+ }
267
+ if (remoteSha.toLowerCase() === local.toLowerCase()) {
268
+ return {
269
+ verdict: "landed",
270
+ reason: `remote tip matches local HEAD ${local.slice(0, 12)}`,
271
+ };
272
+ }
273
+ return {
274
+ verdict: "not-landed",
275
+ reason: `remote tip ${remoteSha.slice(0, 12)} differs from local HEAD ${local.slice(0, 12)}`,
276
+ };
277
+ }
278
+ /**
279
+ * Reconcile `git status --porcelain` output against real content drift.
280
+ *
281
+ * On an `autocrlf=true` tree status reports line-ending-only modifications that
282
+ * carry no content change, which is why the reconcile skill says to trust
283
+ * `git diff` instead. A `contentDrift` of null means the drift probe never ran;
284
+ * it is reported as null rather than assumed to be zero.
285
+ */
286
+ export function accountDirty(statusStdout, diffNamesStdout) {
287
+ const count = (raw) => typeof raw === "string"
288
+ ? toLines(raw).filter((line) => line.trim().length > 0).length
289
+ : null;
290
+ const reported = count(statusStdout) ?? 0;
291
+ const contentDrift = count(diffNamesStdout);
292
+ return {
293
+ reported,
294
+ contentDrift,
295
+ phantomSuspected: contentDrift !== null && reported > contentDrift,
296
+ };
297
+ }
298
+ /**
299
+ * True when the repo moved under us since `before` was captured — the check to
300
+ * run immediately before each mutation on a host with concurrent writers.
301
+ *
302
+ * Fails closed: a missing or unparseable sha on either side counts as shifted,
303
+ * because "we could not tell" must never read as "nothing moved".
304
+ */
305
+ export function baselineShifted(before, after) {
306
+ if (before === null || after === null)
307
+ return true;
308
+ const beforeHead = (before.head ?? "").trim();
309
+ const afterHead = (after.head ?? "").trim();
310
+ if (!isSha(beforeHead) || !isSha(afterHead))
311
+ return true;
312
+ if (beforeHead.toLowerCase() !== afterHead.toLowerCase())
313
+ return true;
314
+ return (before.branch ?? null) !== (after.branch ?? null);
315
+ }
316
+ /**
317
+ * Turn a probed state into the ordered finding list the resolved-state block
318
+ * renders. Every finding carries a severity; `blocker` means do not mutate.
319
+ */
320
+ export function assessGitState(input) {
321
+ const findings = [];
322
+ const protectedList = input.protectedBranches ?? DEFAULT_PROTECTED_BRANCHES;
323
+ if (Object.hasOwn(input, "headCommit")) {
324
+ const commit = (input.headCommit ?? "").trim();
325
+ findings.push({
326
+ id: "head-commit",
327
+ label: "HEAD commit",
328
+ detail: isSha(commit)
329
+ ? commit.slice(0, 12)
330
+ : "unborn or not a usable commit — create or verify the first commit before mutating",
331
+ severity: isSha(commit) ? "ok" : "blocker",
332
+ });
333
+ }
334
+ if (input.head.kind === "branch") {
335
+ const onProtected = isProtectedBranch(input.head.branch, protectedList);
336
+ findings.push({
337
+ id: "head",
338
+ label: "HEAD",
339
+ detail: onProtected
340
+ ? `on protected branch ${input.head.branch} — branch before mutating`
341
+ : `on ${input.head.branch}`,
342
+ severity: onProtected ? "warn" : "ok",
343
+ });
344
+ }
345
+ else if (input.head.kind === "detached") {
346
+ findings.push({
347
+ id: "head",
348
+ label: "HEAD",
349
+ detail: "detached — no branch to commit onto, push, or name in a PR",
350
+ severity: "blocker",
351
+ });
352
+ }
353
+ else {
354
+ findings.push({
355
+ id: "head",
356
+ label: "HEAD",
357
+ detail: "branch name unparseable — treat repo identity as unknown",
358
+ severity: "blocker",
359
+ });
360
+ }
361
+ const relation = classifyUpstream(input.counts, input.upstreamRef !== null);
362
+ const upstreamRows = {
363
+ even: { detail: `even with ${input.upstreamRef}`, severity: "ok" },
364
+ ahead: {
365
+ detail: `${input.counts?.ahead ?? "?"} ahead of ${input.upstreamRef}`,
366
+ severity: "ok",
367
+ },
368
+ behind: {
369
+ detail: `${input.counts?.behind ?? "?"} behind ${input.upstreamRef} — pull --ff-only first`,
370
+ severity: "warn",
371
+ },
372
+ diverged: {
373
+ detail: `diverged from ${input.upstreamRef} ` +
374
+ `(${input.counts?.behind ?? "?"} behind / ${input.counts?.ahead ?? "?"} ahead) — ` +
375
+ "rebase or merge deliberately, never blind --force",
376
+ severity: "warn",
377
+ },
378
+ "no-upstream": {
379
+ detail: "no configured upstream — compare against origin/<default> explicitly before classifying",
380
+ severity: "warn",
381
+ },
382
+ unknown: {
383
+ detail: "upstream exists but counts did not parse — relationship unknown, do not assume even",
384
+ severity: "blocker",
385
+ },
386
+ };
387
+ findings.push({ id: "upstream", label: "upstream", ...upstreamRows[relation] });
388
+ const ops = classifyInProgress(Object.fromEntries(IN_PROGRESS_MARKERS.map((marker) => [marker.id, input.inProgress.includes(marker.id)])));
389
+ findings.push({
390
+ id: "in-progress",
391
+ label: "in-progress op",
392
+ detail: ops.length === 0 ? "none" : `${ops.join(", ")} — another actor may own this tree`,
393
+ severity: ops.length === 0 ? "ok" : "blocker",
394
+ });
395
+ const { reported, contentDrift, phantomSuspected } = input.dirty;
396
+ findings.push({
397
+ id: "dirty",
398
+ label: "working tree",
399
+ detail: contentDrift === null
400
+ ? `${reported} path(s) reported by status; content drift unprobed`
401
+ : phantomSuspected
402
+ ? `${reported} reported by status but only ${contentDrift} with content drift — ` +
403
+ "stage by explicit filename, never git add -A"
404
+ : `${contentDrift} path(s) with content drift`,
405
+ severity: contentDrift === null ? "warn" : "ok",
406
+ });
407
+ return findings;
408
+ }
409
+ /** True when any finding blocks mutation. */
410
+ export function hasBlockers(findings) {
411
+ return findings.some((finding) => finding.severity === "blocker");
412
+ }
413
+ const SEVERITY_TAG = {
414
+ ok: "ok",
415
+ warn: "WARN",
416
+ blocker: "BLOCKER",
417
+ };
418
+ /**
419
+ * Render the resolved-state block an operator reads before mutating. Returns a
420
+ * single "state unknown" line when no probe produced a finding, so an empty
421
+ * result never renders as a clean tree.
422
+ */
423
+ export function renderResolvedState(findings) {
424
+ if (findings.length === 0) {
425
+ return "reconcile (resolved): no probes ran — state unknown";
426
+ }
427
+ const width = Math.max(...findings.map((finding) => finding.label.length));
428
+ const rows = findings.map((finding) => ` ${finding.label.padEnd(width)} ${SEVERITY_TAG[finding.severity].padEnd(7)} ${finding.detail}`);
429
+ return ["reconcile (resolved):", ...rows].join("\n");
430
+ }
@@ -20,27 +20,69 @@ Law 1 says research before executing. The most expensive skipped research is the
20
20
 
21
21
  ## Establish Ground Truth First
22
22
 
23
- Read before you write. Capture the full state in one pass:
23
+ Read before you write. One command runs the whole pass and prints the resolved-state block:
24
24
 
25
25
  ```
26
- git branch --show-current
27
- git status --porcelain=v1
28
- git rev-list --left-right --count '@{u}...HEAD' # behind / ahead of upstream (quote the ref bare @{u} trips the Bash parser)
26
+ npx ci-reconcile # resolved-state block; exit 1 if anything blocks a mutation
27
+ npx ci-reconcile --json # the same state, machine-readable
28
+ npx ci-reconcile --explain # print the probe set and why each probe runs
29
+ ```
30
+
31
+ Exit codes: `0` nothing blocks, `1` at least one blocker, `2` not a git repository. The probe set is defined once in `src/lib/git-state.mts`, and `npm run verify:reconcile-parity` fails if this document drifts from it — the list below is the list the runner executes.
32
+
33
+ Run the pass by hand when the runner is not installed:
34
+
35
+ ```
36
+ git rev-parse --show-toplevel # inside a work tree, and where
37
+ git rev-parse HEAD # the sha every later claim is relative to
38
+ git symbolic-ref --quiet --short HEAD # branch name; NON-ZERO EXIT = detached HEAD
39
+ git rev-parse --abbrev-ref --symbolic-full-name @{u} # upstream, or non-zero = none configured
40
+ git rev-list --left-right --count @{u}...HEAD # behind/ahead — only after the line above succeeded
41
+ git status --porcelain=v1 # reported changes (inflated by autocrlf)
42
+ git diff --name-only --ignore-all-space # real content drift — the number to trust
29
43
  git stash list
30
- git worktree list
31
- ls .git/MERGE_HEAD .git/rebase-merge .git/rebase-apply 2>/dev/null # in-progress operation?
44
+ git worktree list --porcelain
45
+ git rev-parse --git-path MERGE_HEAD # in-progress op: test the RESOLVED path for existence
32
46
  ```
33
47
 
34
- On Windows with `autocrlf=true`, `git status` reports phantom line-ending-only modifications. Trust `git diff --stat` (and `git diff --ignore-all-space`) for real content drift, not `git status`. Never stage with `git add -A` / `git add .` on such a tree — stage by explicit filename.
48
+ Four boundaries make the obvious commands lie. Each was reproduced against real git; do not simplify them back.
49
+
50
+ - **No configured upstream.** Asking `git rev-list` for counts against `@{u}` exits **128** with `fatal: no upstream configured` — it does not return zeros. Probe for the upstream first and ask for counts only once it resolved. With no upstream, compare against `origin/<default>` explicitly; never read the failure as "even".
51
+ - **Detached HEAD.** The `--show-current` form of `git branch` prints an empty string and exits **0**, so a detached HEAD is indistinguishable from a successful read. `git symbolic-ref --quiet --short HEAD` exits non-zero instead, which is checkable. A detached HEAD blocks: there is no branch to commit onto, push, or name in a PR.
52
+ - **Linked worktrees.** Inside a worktree `.git` is a *file*, not a directory, so listing a `.git/`-relative path for `MERGE_HEAD` fails with "Not a directory" and exit **2** — byte-identical to the "no operation in progress" result on a clean tree. A real conflicted merge therefore reads as clean. Resolve the marker with `git rev-parse --git-path MERGE_HEAD` and test *that* path; it is correct in a main checkout and in a worktree alike. Same for `rebase-merge`, `rebase-apply`, `CHERRY_PICK_HEAD`, `REVERT_HEAD`, `BISECT_LOG`.
53
+ - **Windows `autocrlf=true`.** `git status` reports phantom line-ending-only modifications. Trust `git diff --stat` / `git diff --name-only --ignore-all-space` for real content drift. Never stage with `git add -A` / `git add .` on such a tree — stage by explicit filename. The runner prints both numbers so the gap is visible instead of assumed.
54
+
55
+ ## Compatibility
56
+
57
+ The ground-truth pass has to work wherever the agent runs, not only in Bash. `ci-reconcile` spawns `git` argv directly with no shell, so it needs no `bash`, no coreutils, and no `.git/`-relative path.
58
+
59
+ | Surface | PowerShell / cmd | Git Bash / WSL | POSIX shell | Linked worktree | Detached HEAD | No upstream |
60
+ |---|---|---|---|---|---|---|
61
+ | `ci-reconcile` (Node) | yes | yes | yes | correct | blocks | warns |
62
+ | `scripts/git-state-snapshot.sh` | needs Git Bash | yes | yes | root/branch only | reports `detached` | reports `none` |
63
+ | Hand-run probe list above | yes | yes | yes | correct | non-zero exit | non-zero exit |
64
+
65
+ Smoke-test on the OS you actually ship on. Both surfaces emit the same `{head, upstream, dirty, root, branch}` envelope — `ci-reconcile --snapshot` adds `contentDrift`, `inProgress`, `blocked` and `blockers` — and a test pins that parity so the two cannot drift apart silently.
66
+
67
+ `--snapshot` follows the same exit-code contract as the default mode: `0` clear, `1` at least one blocker, `2` not a git repository. It still writes the envelope on a blocker, so a script that wants the JSON regardless must tolerate exit 1 (`set -e` will otherwise abort on a detached HEAD or an unborn repo).
68
+
69
+ An **unborn HEAD** — `git init` with no commit yet — is a real git repository with no usable baseline. `git rev-parse HEAD` fails there, so the shell script reports `not-a-git-repo` and the envelope's `head` field would otherwise be empty in a way that reads like success. `ci-reconcile` reports `head: "unborn"` with `blocked: true` and blocks the mutation instead.
35
70
 
36
71
  ## Detect a Concurrent Writer
37
72
 
38
73
  When another session/loop may be active, do not assume the tree is yours:
39
74
 
40
- - An in-progress `MERGE_HEAD` / `rebase-merge` you did not start means another actor is mid-operation. Do not "help" by editing conflicted files — wait, or hand off.
41
- - Re-read the current branch immediately before any mutation; if it shifted since your snapshot, re-survey from the top.
42
- - If `.git/index` keeps changing while you are idle, a writer is active. Pause and surface it rather than racing.
43
- - If `gateguard` is installed, its Parallel-Actor Gate already captured this baseline on the session's first mutation by running `bash "${CLAUDE_PLUGIN_ROOT}/scripts/git-state-snapshot.sh"` (source: `scripts/git-state-snapshot.sh`) and divergence-checks every later mutation — `reconcile` complements that gate, it does not replace it. Without gateguard, run the snapshot above yourself.
75
+ - An in-progress `MERGE_HEAD` / `rebase-merge` you did not start means another actor is mid-operation. Do not "help" by editing conflicted files — wait, or hand off. The runner reports this as a blocker; the retired `.git/`-relative probe could not see it inside a worktree at all.
76
+ - **Re-read HEAD and the branch immediately before every mutation, not once per session.** Capture a baseline, then compare right before you commit, push, or rebase:
77
+ ```
78
+ npx ci-reconcile --snapshot > .git/reconcile-baseline.json # or any scratch path
79
+ # ... do work ...
80
+ npx ci-reconcile --snapshot # compare head + branch against the baseline
81
+ ```
82
+ If either field moved, another writer got there first — re-survey from the top instead of committing onto an unexpected base. A missing or unparseable field counts as *shifted*; "we could not tell" is never "nothing moved". Both calls exit 1 if the tree is blocked, so capture the baseline without `set -e` (or guard it) when a blocker is expected.
83
+ - More than one entry in `git worktree list --porcelain` means a sibling checkout exists that another session may be writing to. The runner flags this.
84
+ - If the git index keeps changing while you are idle, a writer is active. Pause and surface it rather than racing.
85
+ - If `gateguard` is installed, its Parallel-Actor Gate already captured this baseline on the session's first mutation by running `bash "${CLAUDE_PLUGIN_ROOT}/scripts/git-state-snapshot.sh"` (source: `scripts/git-state-snapshot.sh`) and divergence-checks every later mutation — `reconcile` complements that gate, it does not replace it. That shell snapshot needs Git Bash and derives its `dirty` count from `git status`, which overstates drift on an `autocrlf` tree; `ci-reconcile --snapshot` is the same envelope without either limitation. Without gateguard, run one of them yourself.
44
86
 
45
87
  ## Classify, Then Act
46
88
 
@@ -99,12 +141,24 @@ Once ground truth is known and the halt gates are clear, carry the work to an op
99
141
 
100
142
  A push that printed no error is still a claim. Confirm:
101
143
 
144
+ ```
145
+ npx ci-reconcile --verify-push <branch> # exit 0 only when the remote tip equals local HEAD
146
+ ```
147
+
148
+ or by hand:
149
+
102
150
  ```
103
151
  git rev-parse HEAD
104
152
  git ls-remote origin refs/heads/<branch> # remote tip must equal local HEAD
105
153
  ```
106
154
 
107
- If the remote ref is absent or behind, the push did not land investigate before reporting success.
155
+ There are **three** outcomes here, not two, and collapsing them is how a false report gets made:
156
+
157
+ - **landed** — the probe succeeded and the remote tip equals local HEAD.
158
+ - **not-landed** — the probe succeeded and the ref is absent, or points at a different sha. The push really did not land.
159
+ - **unverified** — `git ls-remote` itself failed (network, auth, remote down). This is *not* evidence the push failed; it is evidence you do not know. Retry the probe. Never report success, and never report failure, from a probe that did not run.
160
+
161
+ Report only what the probe proved.
108
162
 
109
163
  ## Sync the Default Branch After the PR Merges
110
164
 
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "continuous-improvement",
3
- "version": "3.21.0",
3
+ "version": "3.22.1",
4
4
  "mode": "expert",
5
5
  "description": "Expert mode: tune confidence, manage instincts, and persist plans on disk. Adds safety, token-budget, and strategic-compact skills plus the /learn-eval command so long sessions stay sharp and learnings survive context resets.",
6
6
  "tools": [
@@ -20,27 +20,69 @@ Law 1 says research before executing. The most expensive skipped research is the
20
20
 
21
21
  ## Establish Ground Truth First
22
22
 
23
- Read before you write. Capture the full state in one pass:
23
+ Read before you write. One command runs the whole pass and prints the resolved-state block:
24
24
 
25
25
  ```
26
- git branch --show-current
27
- git status --porcelain=v1
28
- git rev-list --left-right --count '@{u}...HEAD' # behind / ahead of upstream (quote the ref bare @{u} trips the Bash parser)
26
+ npx ci-reconcile # resolved-state block; exit 1 if anything blocks a mutation
27
+ npx ci-reconcile --json # the same state, machine-readable
28
+ npx ci-reconcile --explain # print the probe set and why each probe runs
29
+ ```
30
+
31
+ Exit codes: `0` nothing blocks, `1` at least one blocker, `2` not a git repository. The probe set is defined once in `src/lib/git-state.mts`, and `npm run verify:reconcile-parity` fails if this document drifts from it — the list below is the list the runner executes.
32
+
33
+ Run the pass by hand when the runner is not installed:
34
+
35
+ ```
36
+ git rev-parse --show-toplevel # inside a work tree, and where
37
+ git rev-parse HEAD # the sha every later claim is relative to
38
+ git symbolic-ref --quiet --short HEAD # branch name; NON-ZERO EXIT = detached HEAD
39
+ git rev-parse --abbrev-ref --symbolic-full-name @{u} # upstream, or non-zero = none configured
40
+ git rev-list --left-right --count @{u}...HEAD # behind/ahead — only after the line above succeeded
41
+ git status --porcelain=v1 # reported changes (inflated by autocrlf)
42
+ git diff --name-only --ignore-all-space # real content drift — the number to trust
29
43
  git stash list
30
- git worktree list
31
- ls .git/MERGE_HEAD .git/rebase-merge .git/rebase-apply 2>/dev/null # in-progress operation?
44
+ git worktree list --porcelain
45
+ git rev-parse --git-path MERGE_HEAD # in-progress op: test the RESOLVED path for existence
32
46
  ```
33
47
 
34
- On Windows with `autocrlf=true`, `git status` reports phantom line-ending-only modifications. Trust `git diff --stat` (and `git diff --ignore-all-space`) for real content drift, not `git status`. Never stage with `git add -A` / `git add .` on such a tree — stage by explicit filename.
48
+ Four boundaries make the obvious commands lie. Each was reproduced against real git; do not simplify them back.
49
+
50
+ - **No configured upstream.** Asking `git rev-list` for counts against `@{u}` exits **128** with `fatal: no upstream configured` — it does not return zeros. Probe for the upstream first and ask for counts only once it resolved. With no upstream, compare against `origin/<default>` explicitly; never read the failure as "even".
51
+ - **Detached HEAD.** The `--show-current` form of `git branch` prints an empty string and exits **0**, so a detached HEAD is indistinguishable from a successful read. `git symbolic-ref --quiet --short HEAD` exits non-zero instead, which is checkable. A detached HEAD blocks: there is no branch to commit onto, push, or name in a PR.
52
+ - **Linked worktrees.** Inside a worktree `.git` is a *file*, not a directory, so listing a `.git/`-relative path for `MERGE_HEAD` fails with "Not a directory" and exit **2** — byte-identical to the "no operation in progress" result on a clean tree. A real conflicted merge therefore reads as clean. Resolve the marker with `git rev-parse --git-path MERGE_HEAD` and test *that* path; it is correct in a main checkout and in a worktree alike. Same for `rebase-merge`, `rebase-apply`, `CHERRY_PICK_HEAD`, `REVERT_HEAD`, `BISECT_LOG`.
53
+ - **Windows `autocrlf=true`.** `git status` reports phantom line-ending-only modifications. Trust `git diff --stat` / `git diff --name-only --ignore-all-space` for real content drift. Never stage with `git add -A` / `git add .` on such a tree — stage by explicit filename. The runner prints both numbers so the gap is visible instead of assumed.
54
+
55
+ ## Compatibility
56
+
57
+ The ground-truth pass has to work wherever the agent runs, not only in Bash. `ci-reconcile` spawns `git` argv directly with no shell, so it needs no `bash`, no coreutils, and no `.git/`-relative path.
58
+
59
+ | Surface | PowerShell / cmd | Git Bash / WSL | POSIX shell | Linked worktree | Detached HEAD | No upstream |
60
+ |---|---|---|---|---|---|---|
61
+ | `ci-reconcile` (Node) | yes | yes | yes | correct | blocks | warns |
62
+ | `scripts/git-state-snapshot.sh` | needs Git Bash | yes | yes | root/branch only | reports `detached` | reports `none` |
63
+ | Hand-run probe list above | yes | yes | yes | correct | non-zero exit | non-zero exit |
64
+
65
+ Smoke-test on the OS you actually ship on. Both surfaces emit the same `{head, upstream, dirty, root, branch}` envelope — `ci-reconcile --snapshot` adds `contentDrift`, `inProgress`, `blocked` and `blockers` — and a test pins that parity so the two cannot drift apart silently.
66
+
67
+ `--snapshot` follows the same exit-code contract as the default mode: `0` clear, `1` at least one blocker, `2` not a git repository. It still writes the envelope on a blocker, so a script that wants the JSON regardless must tolerate exit 1 (`set -e` will otherwise abort on a detached HEAD or an unborn repo).
68
+
69
+ An **unborn HEAD** — `git init` with no commit yet — is a real git repository with no usable baseline. `git rev-parse HEAD` fails there, so the shell script reports `not-a-git-repo` and the envelope's `head` field would otherwise be empty in a way that reads like success. `ci-reconcile` reports `head: "unborn"` with `blocked: true` and blocks the mutation instead.
35
70
 
36
71
  ## Detect a Concurrent Writer
37
72
 
38
73
  When another session/loop may be active, do not assume the tree is yours:
39
74
 
40
- - An in-progress `MERGE_HEAD` / `rebase-merge` you did not start means another actor is mid-operation. Do not "help" by editing conflicted files — wait, or hand off.
41
- - Re-read the current branch immediately before any mutation; if it shifted since your snapshot, re-survey from the top.
42
- - If `.git/index` keeps changing while you are idle, a writer is active. Pause and surface it rather than racing.
43
- - If `gateguard` is installed, its Parallel-Actor Gate already captured this baseline on the session's first mutation by running `bash "${CLAUDE_PLUGIN_ROOT}/scripts/git-state-snapshot.sh"` (source: `scripts/git-state-snapshot.sh`) and divergence-checks every later mutation — `reconcile` complements that gate, it does not replace it. Without gateguard, run the snapshot above yourself.
75
+ - An in-progress `MERGE_HEAD` / `rebase-merge` you did not start means another actor is mid-operation. Do not "help" by editing conflicted files — wait, or hand off. The runner reports this as a blocker; the retired `.git/`-relative probe could not see it inside a worktree at all.
76
+ - **Re-read HEAD and the branch immediately before every mutation, not once per session.** Capture a baseline, then compare right before you commit, push, or rebase:
77
+ ```
78
+ npx ci-reconcile --snapshot > .git/reconcile-baseline.json # or any scratch path
79
+ # ... do work ...
80
+ npx ci-reconcile --snapshot # compare head + branch against the baseline
81
+ ```
82
+ If either field moved, another writer got there first — re-survey from the top instead of committing onto an unexpected base. A missing or unparseable field counts as *shifted*; "we could not tell" is never "nothing moved". Both calls exit 1 if the tree is blocked, so capture the baseline without `set -e` (or guard it) when a blocker is expected.
83
+ - More than one entry in `git worktree list --porcelain` means a sibling checkout exists that another session may be writing to. The runner flags this.
84
+ - If the git index keeps changing while you are idle, a writer is active. Pause and surface it rather than racing.
85
+ - If `gateguard` is installed, its Parallel-Actor Gate already captured this baseline on the session's first mutation by running `bash "${CLAUDE_PLUGIN_ROOT}/scripts/git-state-snapshot.sh"` (source: `scripts/git-state-snapshot.sh`) and divergence-checks every later mutation — `reconcile` complements that gate, it does not replace it. That shell snapshot needs Git Bash and derives its `dirty` count from `git status`, which overstates drift on an `autocrlf` tree; `ci-reconcile --snapshot` is the same envelope without either limitation. Without gateguard, run one of them yourself.
44
86
 
45
87
  ## Classify, Then Act
46
88
 
@@ -99,12 +141,24 @@ Once ground truth is known and the halt gates are clear, carry the work to an op
99
141
 
100
142
  A push that printed no error is still a claim. Confirm:
101
143
 
144
+ ```
145
+ npx ci-reconcile --verify-push <branch> # exit 0 only when the remote tip equals local HEAD
146
+ ```
147
+
148
+ or by hand:
149
+
102
150
  ```
103
151
  git rev-parse HEAD
104
152
  git ls-remote origin refs/heads/<branch> # remote tip must equal local HEAD
105
153
  ```
106
154
 
107
- If the remote ref is absent or behind, the push did not land investigate before reporting success.
155
+ There are **three** outcomes here, not two, and collapsing them is how a false report gets made:
156
+
157
+ - **landed** — the probe succeeded and the remote tip equals local HEAD.
158
+ - **not-landed** — the probe succeeded and the ref is absent, or points at a different sha. The push really did not land.
159
+ - **unverified** — `git ls-remote` itself failed (network, auth, remote down). This is *not* evidence the push failed; it is evidence you do not know. Retry the probe. Never report success, and never report failure, from a probe that did not run.
160
+
161
+ Report only what the probe proved.
108
162
 
109
163
  ## Sync the Default Branch After the PR Merges
110
164