@sabaiway/agent-workflow-kit 3.12.0 → 3.13.0
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/CHANGELOG.md +60 -0
- package/README.md +1 -1
- package/SKILL.md +1 -1
- package/capability.json +1 -1
- package/package.json +1 -1
- package/references/modes/commit-guard.md +14 -7
- package/tools/commands.mjs +1 -1
- package/tools/commit-guard.mjs +139 -8
- package/tools/core-evidence.mjs +229 -18
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,66 @@ Semantically versioned ([semver](https://semver.org)), newest first. The `versio
|
|
|
4
4
|
is the current release. `upgrade` mode reads a project's `docs/ai/.workflow-version` and applies
|
|
5
5
|
every `migrations/<version>-<slug>.md` newer than it, in semver order.
|
|
6
6
|
|
|
7
|
+
## 3.13.0 — the commit guard proves the INDEX carries the verified tree (AD-074)
|
|
8
|
+
|
|
9
|
+
`commit-guard --check` now refuses an index that lags the working tree, so «verified» and «about to
|
|
10
|
+
be committed» are the same bytes by construction instead of by operator discipline.
|
|
11
|
+
|
|
12
|
+
The gap it closes was real and it fired: the gates and the tree fingerprint both describe the
|
|
13
|
+
WORKING tree, while `git commit` builds the commit from the INDEX alone — and against an
|
|
14
|
+
otherwise-empty index the fingerprint is byte-identical whether a hunk sits staged or unstaged. A
|
|
15
|
+
lagging index therefore passed every gate and every guard arm, and the commit shipped a strict
|
|
16
|
+
subset of what was verified. The kit's own 3.12.0 release commit did exactly that: a fix landed
|
|
17
|
+
without its regression arm, and only the publish dispatcher's dirty-tree refusal caught it, one step
|
|
18
|
+
later.
|
|
19
|
+
|
|
20
|
+
- **A new FIRST refusal, ahead of the fingerprint.** It fires on tracked paths differing
|
|
21
|
+
index↔worktree or on reviewable untracked-not-ignored paths — the same never-committable stat
|
|
22
|
+
filter the fingerprint applies, so ignored paths and device/FIFO/socket nodes never refuse. It runs
|
|
23
|
+
first because its recovery re-stages the tree and re-mints the receipt, which re-decides every arm
|
|
24
|
+
below it.
|
|
25
|
+
- **The message is actionable and bounded.** Offending paths are named up to a cap with the
|
|
26
|
+
remainder stated, each rendered through the same escaper the review-state report uses, so no
|
|
27
|
+
filename can break or forge an output line. The recovery is the complete whole-tree sequence
|
|
28
|
+
(`git add -A`, re-run `--final`, commit the whole tree) — a truncated list cannot serve as a
|
|
29
|
+
complete `git add -- <paths>` argument.
|
|
30
|
+
- **The probes cannot be blinded by configuration or index bits.** Entries carrying `skip-worktree`
|
|
31
|
+
or `assume-unchanged` are invisible to `git diff`, so they are compared directly against the
|
|
32
|
+
worktree — type, symlink target, executable bit where `core.fileMode` applies, and the blob oid
|
|
33
|
+
through git's own clean filters. A de-materialised skip-worktree path is an ordinary sparse
|
|
34
|
+
checkout and never refuses; a missing assume-unchanged path does. The submodule probe forces
|
|
35
|
+
`--ignore-submodules=none`, so `diff.ignoreSubmodules` cannot erase a dirty submodule either.
|
|
36
|
+
- **A tracked submodule the index cannot prove current is named separately, with its own recovery**
|
|
37
|
+
(commit or clean inside the submodule, then stage the gitlink): a root-level `git add -A` cannot
|
|
38
|
+
reach a submodule's own worktree, so offering it there would be a recovery known in advance to
|
|
39
|
+
fail. A submodule whose gitlink itself carries one of those index bits is not probed at all — it
|
|
40
|
+
lags by construction. That reduction is deliberate: three review rounds each found a new way for a
|
|
41
|
+
nested probe to answer "clean" wrongly, so the guard stops asking rather than accumulate patches.
|
|
42
|
+
It stays a converging refusal (clear the bit and the guard falls silent), and an unflagged
|
|
43
|
+
submodule is judged exactly as before.
|
|
44
|
+
- **Fail-closed.** An undecidable git probe refuses with its own named cause. The guard's claim is
|
|
45
|
+
that the committed bytes ARE the verified bytes; it cannot make that claim about a tree it failed
|
|
46
|
+
to read.
|
|
47
|
+
|
|
48
|
+
**Behaviour change worth knowing:** a deliberate partial commit is now blocked. `git commit --only
|
|
49
|
+
<path>` hands the hook a temporary index carrying less than the verified tree — precisely the
|
|
50
|
+
blindness this closes — so it refuses. No opt-out flag exists, deliberately: a flag that suspends
|
|
51
|
+
the arm would suspend the guard's whole claim. `git commit --no-verify` remains the stated residual.
|
|
52
|
+
`git commit -a` is unaffected when it captures the whole verified tree, and refuses when a reviewable
|
|
53
|
+
untracked path would be left behind.
|
|
54
|
+
|
|
55
|
+
The tree fingerprint itself is unchanged — making it stage-sensitive would have closed the same gap
|
|
56
|
+
at the cost of the lockstep with the wrappers' bash twin. Internally, one new computation of the
|
|
57
|
+
index↔worktree split now serves both this arm and `isTreeClean`, so the two can never disagree.
|
|
58
|
+
|
|
59
|
+
**Stated residual.** This makes the COMMIT capture the whole current working tree; it does not make
|
|
60
|
+
the RECEIPT unforgeable. The fingerprint payload still runs its diffs without
|
|
61
|
+
`--ignore-submodules=none`, so under `diff.ignoreSubmodules=all` a submodule can be changed and its
|
|
62
|
+
gitlink staged after a green final run while the fingerprint stays put, and the stale receipt is
|
|
63
|
+
reused. That is a receipt collision, not an under-capture — no commit ships less than the working
|
|
64
|
+
tree because of it — and closing it means moving the node payload and both bash twins in one
|
|
65
|
+
release. Tracked as its own class, deliberately not folded here.
|
|
66
|
+
|
|
7
67
|
## 3.12.0 — `--resume` tolerates the session's work: the verify proves per placed path (AD-073)
|
|
8
68
|
|
|
9
69
|
`provision --resume` no longer refuses a satellite you have worked in. The closing slice of the
|
package/README.md
CHANGED
|
@@ -240,7 +240,7 @@ file), or run the guarded `/agent-workflow-kit uninstall`.
|
|
|
240
240
|
| `/agent-workflow-kit grounding` | any time | **grounded-review facts assembler** — mechanizes populating `agy-review --facts @f`: slices your entry-point's **Hard Constraints** section verbatim (exactly one match, else a loud stop) and/or a plan's decision-bearing sections (`## Approach` + `## Verification` required, `## Decisions (locked)` when present; duplicates stop), under the same byte budget the agy wrapper enforces (minus `--reserve-bytes` for the artifact share), with a loud tail-trim on overflow. `--autonomy` (AD-044) appends the COMPUTED effective autonomy policy from the git-top `docs/ai/autonomy.json` (every red-line + per-activity level, stated source line; absent file → the computed defaults ARE the policy, exit 0; a malformed policy fails CLOSED, exit 1). Prints to stdout; `--out` writes **one scratch file only** — system-temp outside the repo ($TMPDIR / /tmp, rewritable) or a **fresh** gitignored in-repo path (create-only, exclusive write; an existing in-repo file, even gitignored, is refused — the `.env` clobber class); tracked, not-ignored-in-repo, other outside-repo, and symlink/non-regular destinations are all refused. Never commits, never runs a subscription CLI. |
|
|
241
241
|
| `/agent-workflow-kit core-evidence` | any time | **the ONE loop-evidence writer** (strip-the-kit) — every core evidence record lands in a single append-only JSONL store inside the git dir (never committable; versioned schema, latest-per-key supersession, byte-identical duplicates refused, malformed lines fail every reader closed). `red-proof "<file>#<pattern>"` declares an observed-red **BEFORE a bugfix** (N/N red runs + content custody + base + the pre-fix fingerprint; green/mixed/timeout are DISTINGUISHED refusals — nothing written); `degrade --backend --reason` is the ONLY escape for an unavailable review backend (per-tree, never all backends); `summary` renders the whole loop state statelessly (gate result · per-backend verdicts · red-proofs · degrades) — no ledger, no rounds, nothing remembered. Honest residual: records are forgeable — self-discipline, not a security boundary. Never commits, never runs a subscription CLI. |
|
|
242
242
|
| `/agent-workflow-kit coverage-check` | any time | **the final-run checker** (D3(c)+(d)) — reads the lcov the declared `unit-tests` gate produced at the FIXED git-dir path and fails on any uncovered CHANGED executable Node line (listed `file:line`; a changed file absent from the map is a file-level red; out-of-domain/unsupported files are LISTED — the claim narrowed honestly); VERIFIES every current-base red-proof declaration (bound test exists · custody hash unchanged · green N/N now · pre-fix fingerprint differs); prints `lcov-sha256=<hex|none>` of the exact bytes it consumed — the sha the `--final` receipt binds and re-hashes. An absent lcov is a LOUD `skipped-no-lcov`; a symlinked path is a refusal. `--check` is the gate exit code — declare it as the LAST gate (`run-gates --final` refuses otherwise). Read-only. |
|
|
243
|
-
| `/agent-workflow-kit commit-guard` | any time | **the read-only pre-commit guard** (D10) — binds the LATEST completed `run-gates --final` receipt to the EXACT current tree: refuses on a missing/red/stale receipt, fingerprint drift under the run, a dangling later attempt, declaration content drift, evidence-hash or lcov drift, or unsatisfied review obligations (the same review-state decision, recomputed over a sanitized env — forged out-of-repo stores never satisfy). Re-runs NO gate or test. Wire it into `.git/hooks/pre-commit` (the installer writes the RESOLVED invocation). `git commit --no-verify` stays the stated residual. |
|
|
243
|
+
| `/agent-workflow-kit commit-guard` | any time | **the read-only pre-commit guard** (D10) — makes the commit capture the whole current working tree, so «verified» and «about to be committed» are the same bytes (the receipt itself has a stated residual — see the mode doc). FIRST it refuses an **INDEX that lags the verified working tree** (the gates and the fingerprint describe the WORKING tree while `git commit` takes the INDEX alone, and the fingerprint cannot tell them apart — so a lagging index used to ship a strict subset of what was verified): unstaged tracked paths or reviewable untracked-not-ignored paths, named up to a bounded cap with the remainder stated, a dirty tracked **submodule** named separately with its own recovery, and fail-closed on an undecidable probe. This deliberately blocks a partial commit. Then it binds the LATEST completed `run-gates --final` receipt to the EXACT current tree: refuses on a missing/red/stale receipt, fingerprint drift under the run, a dangling later attempt, declaration content drift, evidence-hash or lcov drift, or unsatisfied review obligations (the same review-state decision, recomputed over a sanitized env — forged out-of-repo stores never satisfy). Re-runs NO gate or test. Wire it into `.git/hooks/pre-commit` (the installer writes the RESOLVED invocation). `git commit --no-verify` stays the stated residual. |
|
|
244
244
|
| `/agent-workflow-kit recommendations` | any time (every `upgrade` ends with it) | **read-only deployment advisor** (AD-044) — computes what in THIS deployment is configured sub-optimally (allowlist not seeded, autonomy render drifted, OS sandbox unavailable, gates undeclared, bridge friction, sandbox-mask clutter, an unacknowledged sandbox recipe) and renders **verdict-first**: one composed verdict line (does anything need attention?), then each item as **{severity · what · one-line benefit · an optional `recipe:` line (the sandbox-lane live recipe, or the worktrees-dir hand-apply-first grant advice) · the exact consent-gated apply one-liner}**. The agent PRESENTS the section in the user's conversational language — every fact and count, nothing added or dropped; commands, paths, hosts and rule strings byte-exact; raw tool block on request — and runs EXACTLY the rendered one-liners only on your yes, surfacing each item's posture note first. Renders **present-even-when-empty** (`no recommendations — flow optimal.`); a failed probe degrades to a stated skip line. Registry strings are fact-true frozen one-line data (posture/risk notes live in the mode doc at the consent moment); the kit never seeds `sandbox.network.allowedDomains` / `filesystem.allowWrite` (**HAND-APPLY** territory), and the sandbox-lane item's convergence is a neutral fingerprint acknowledgement recorded by a consent-gated ack writer into `docs/ai/acks.json` — never a security key (the recipe is documented per bridge in `capability.json` `networkHosts` + `writableDirs`). `--cwd` is required (the target project is explicit); never writes, never commits, never runs a subscription CLI. |
|
|
245
245
|
| `/agent-workflow-kit doc-parity` | any time | **read-only doc-parity lint** (AD-049) — kills the doc-drift class where a mode-contract doc silently lags a code constant (a `--check` doc still reading `300` after the diff cap moved to `400`): a **closed, exported registry** binds each live constant (review caps, schema versions, the ledger's own class/scope vocabulary, and the autonomy-doctor EXIT/status/trusted-dir contract) to the exact token its `references/modes/*.md` contract must carry, and asserts the CURRENT value renders into every bound file — a drifted doc, an unreadable file, or an absent token **fails closed**. The values are sourced from the live imports (never re-typed), so the lint can't itself go stale; adding a binding is adding a checked entry (closed-world, edit-safe). `--check` is a gate exit code for `docs/ai/gates.json`. Never writes, never commits, never runs a subscription CLI. |
|
|
246
246
|
| `/agent-workflow-kit worktrees` | any time | **parallel feature worktrees** — run several features in DIFFERENT agent sessions on one repo, zero interference on working-tree files (the ONE exception is the dependency cache, below): `provision <slug> --plan <file>` creates a sibling git worktree on branch `aw/<slug>` and populates it (registry-derived footprint copy-if-missing — a tracked file is never overwritten; EXACTLY ONE seeded feature plan; the `handoff-<slug>.md` record from minute zero; `node_modules` symlinked where the link stays ignored — a shared MUTABLE dependency cache: writes through it hit MAIN's node_modules; for isolation run the printed isolated-install command (`--install` only PRINTS it; on `--resume` run the printed unlink-first recovery first); absolute root-pinned gate commands rebased on untracked copies only, and only while their bytes equal the MAIN source or its rebased form — user-modified copies stay untouched); `list` is read-only (slug, branch, base, dirty, handoff); `land <slug> --prepare` locks the common git dir, fail-closes on divergence or incomplete satellite state, transfers the complete accepted satellite diff onto a CLEAN main, runs sync plus the declared gates, and reports HEAD/TRANSFER/PREPARED OIDs — the commit ALWAYS stays a dialogue ask; `cleanup <slug>` takes the same lock and removes a LANDED worktree only after live landed-verification against main HEAD, while `--abandon` is the ONE destructive arm (destroys unlanded work; **no preview step** on any writer). The parent dir is the `docs/ai/worktrees.json` `parentDir` setting (default: the repo's sibling parent); an unwritable parent degrades to printed maintainer-pasted commands, and the one-time host consent that makes it promptless surfaces via `recommendations`. Never commits, never pushes, never runs a subscription CLI. |
|
package/SKILL.md
CHANGED
|
@@ -3,7 +3,7 @@ name: agent-workflow-kit
|
|
|
3
3
|
description: Deploy or upgrade a portable AI-agent memory-and-workflow system in any project. Use when the user wants to bootstrap `docs/ai/` + an entry-point `AGENTS.md` (+ `CLAUDE.md` alias) + cap/archive/index enforcement in a new or existing repo, set up the Memory Map and session protocols, install the docs-rotation pre-commit hook, or run `/agent-workflow-kit` / `/agent-workflow-kit upgrade`. Triggers on phrases like "set up the memory system", "deploy the AI workflow here", "bootstrap docs/ai", "upgrade the workflow".
|
|
4
4
|
disable-model-invocation: true
|
|
5
5
|
metadata:
|
|
6
|
-
version: '3.
|
|
6
|
+
version: '3.13.0'
|
|
7
7
|
---
|
|
8
8
|
|
|
9
9
|
# agent-workflow-kit
|
package/capability.json
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sabaiway/agent-workflow-kit",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.13.0",
|
|
4
4
|
"description": "Portable, cross-agent memory & workflow for AI coding agents — Claude Code, Codex, Cursor, Devin Desktop. One command deploys an AGENTS.md entry point + docs/ai context with cap/archive/index enforcement into any repo.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ai-agents",
|
|
@@ -4,16 +4,23 @@ The **read-only pre-commit guard** (strip-the-kit D10) — the last line of the
|
|
|
4
4
|
|
|
5
5
|
Run `node ${CLAUDE_SKILL_DIR}/tools/commit-guard.mjs --check [--cwd <dir>]` — it refuses, each with a named recovery, on:
|
|
6
6
|
|
|
7
|
-
1.
|
|
8
|
-
2.
|
|
9
|
-
3.
|
|
10
|
-
4.
|
|
11
|
-
5.
|
|
12
|
-
6.
|
|
13
|
-
7.
|
|
7
|
+
1. **an INDEX that lags the verified working tree** — the gates and the fingerprint both describe the WORKING tree, while `git commit` builds the commit from the INDEX alone, and the fingerprint domain is identical whether a hunk sits staged or unstaged (staging a lone tracked modification does not even move it). So this arm runs FIRST, before the fingerprint is computed: it refuses when the working tree holds anything the index does not — tracked paths differing between index and worktree, or reviewable untracked-not-ignored paths (the SAME never-committable stat filter the fingerprint applies; ignored paths never refuse). An index entry carrying **skip-worktree** or **assume-unchanged** is invisible to `git diff`, so those entries are compared DIRECTLY against the worktree (type, symlink target, executable bit where `core.fileMode` says so, and the blob oid through git's own clean filters) — a de-materialised skip-worktree path is an ordinary sparse checkout and never refuses, while a missing assume-unchanged path does. The submodule probe forces `--ignore-submodules=none`, so `diff.ignoreSubmodules` / `submodule.<name>.ignore` cannot erase a dirty submodule from the comparison. Offending paths are named in THREE categories — plain lagging paths, paths held back by an index bit, and submodules — because their recoveries differ; ONE shared cap spans all of them, each category reserves a slot so no clause is ever nameless, the remainder is stated once, and every path is rendered as one escaped line. Recovery is ONE ordered sequence, and `git add -A` alone is NOT it: a bit-carrying entry must have its `skip-worktree` / `assume-unchanged` bit cleared FIRST (scoped to the paths the refusal names — never to everything `git ls-files -v` reports, which includes de-materialised sparse paths whose deletions would then be staged), then `git add -A`, then re-run `run-gates --final` at its RESOLVED path beside this tool, then commit the WHOLE tree. The listed paths are capped, so the loop is the completion signal: re-run the guard until it names none. A tracked **submodule** the index cannot prove current is named separately with its own recovery — commit or clean inside the submodule and stage the gitlink — because a root-level `git add -A` cannot capture a submodule's internal worktree changes. A submodule whose gitlink itself carries one of those index bits is **not probed at all**: it lags by construction. That is a deliberate REDUCTION — three consecutive review rounds each found a new way for a nested probe to answer "clean" wrongly (inherited superproject `GIT_*`, status config blindness, the submodule's OWN flagged entries, a symlink standing in for the directory) — and it stays a CONVERGING refusal, since clearing the bit is a recovery the guard prints and then falls silent on. An UNflagged submodule is judged by the ordinary probe exactly as before. **Fail-closed:** an undecidable git probe refuses with its own named cause, never a silent pass;
|
|
8
|
+
2. no completed final record for the CURRENT fingerprint (the tree moved after the final run — any edit re-stales it);
|
|
9
|
+
3. a RED latest attempt (a dead green never revives — the latest attempt at a fingerprint is authoritative);
|
|
10
|
+
4. fingerprint before ≠ after on the receipt (the tree moved UNDER the final run);
|
|
11
|
+
5. a LATER `final-start` whose attempt never completed (interrupted run / failed receipt append — an attempt of unknown outcome never lets an earlier green stand);
|
|
12
|
+
6. declaration content drift (the current `docs/ai/gates.json` {id, cmd} array no longer matches the receipt's recorded one);
|
|
13
|
+
7. evidence-hash drift (the store's canonical red-proof/degrade serializations moved under the receipt) or lcov drift (the consumed file's sha moved or vanished);
|
|
14
|
+
8. unsatisfied review obligations — the SAME normative decision `review-state --check` computes (configured recipe backends, ship-class-only on the latest normal receipt, veto, the explicit degrade escape), recomputed over a SANITIZED env: the guard resolves FIXED git-dir paths for its own reads and ignores `AW_REVIEW_RECEIPTS`/`AW_CORE_EVIDENCE` (producer test seams are never guard inputs — a forged out-of-repo store never satisfies).
|
|
14
15
|
|
|
15
16
|
**Wiring:** this repo's dogfood rides `scripts/install-git-hooks.mjs`; a consumer install is a consented surface (init/recommendations) — the hook INSTALLER resolves the installed kit location at install time and writes the RESOLVED invocation into the hook it places (no runtime guessing). The final-run ordering that keeps the guard green is D13: stage everything FIRST → run the reviews on the staged tree → `run-gates --final` → commit immediately (any index/worktree mutation after the final run re-stales the receipt).
|
|
16
17
|
|
|
18
|
+
**The deliberate partial commit is BLOCKED — stated, accepted.** Refusal 1 means staging a subset on purpose no longer commits: a pathspec commit (`git commit --only <path>`, `git commit <path>`) hands the hook a temporary index carrying less than the verified tree, and that is exactly the capture blindness this arm closes. No opt-out flag exists, deliberately — the guard's whole claim is that the committed bytes ARE the verified bytes, and a flag that suspends it would suspend the claim. An intentional partial commit stays `--no-verify` territory.
|
|
19
|
+
|
|
20
|
+
**Boundary — what «the commit captures the tree» means for submodules.** The guard proves the SUPERPROJECT commit captures the SUPERPROJECT working tree. A superproject commit stores a submodule as a gitlink OID and never captures its file content — that content is the submodule's own commit boundary. The dirty-submodule refusal is therefore a best-effort COURTESY beyond the guard's boundary, and its completeness is bounded by what the submodule itself reports: a file held behind a `skip-worktree` / `assume-unchanged` bit in the SUBMODULE's own index is invisible to the submodule's status and so to this refusal. Deepening the nested probe was tried and abandoned — three consecutive review rounds each produced a new way for it to answer wrongly — so the honest contract is the boundary, not a completeness claim. Tracked as its own class.
|
|
21
|
+
|
|
22
|
+
**Stated residual — the fingerprint can still be blinded by config.** Refusal 1 makes the COMMIT capture the whole current working tree. It does not make the RECEIPT unforgeable: `computeFingerprintPayload` still runs its diffs without `--ignore-submodules=none`, so under `diff.ignoreSubmodules=all` a submodule can be changed and its gitlink staged AFTER a green `--final` while the fingerprint stays put, and the stale receipt is reused. That is a receipt-collision defect, not an under-capture one — no commit ships less than the working tree because of it — and closing it means moving the node payload and both bash twins together (the AD-044 lockstep). Tracked as its own class.
|
|
23
|
+
|
|
17
24
|
**Human residual (stated, accepted):** `git commit --no-verify` bypasses any pre-commit hook — a self-discipline mechanism, not a security boundary.
|
|
18
25
|
|
|
19
26
|
**Invariants:** read-only · re-runs nothing · fixed git-dir reads (env overrides ignored) · exit 0 pass / 1 refused (reason + recovery named) / 2 usage.
|
package/tools/commands.mjs
CHANGED
|
@@ -222,7 +222,7 @@ const CATALOG = [
|
|
|
222
222
|
invocation: invocationOf('commit-guard'),
|
|
223
223
|
group: 'Orchestrate',
|
|
224
224
|
kind: READ_ONLY,
|
|
225
|
-
oneLine: 'The read-only pre-commit guard: binds the LATEST completed run-gates --final receipt to the CURRENT tree
|
|
225
|
+
oneLine: 'The read-only pre-commit guard: FIRST refuses an INDEX that lags the working tree — so the commit cannot ship less than was verified, which deliberately blocks a partial commit (--no-verify stays the residual) — then binds the LATEST completed run-gates --final receipt to the CURRENT tree, refusing on any fingerprint, declaration, evidence-hash, or lcov drift, a dangling later attempt, or unsatisfied review obligations; re-runs no gate or test.',
|
|
226
226
|
},
|
|
227
227
|
{
|
|
228
228
|
key: 'doc-parity',
|
package/tools/commit-guard.mjs
CHANGED
|
@@ -2,6 +2,15 @@
|
|
|
2
2
|
// commit-guard.mjs — the read-only pre-commit guard (strip-the-kit 2.5, D10). It re-runs NO
|
|
3
3
|
// gate/test subprocess: the heavy D3(b)/(c)/(d) verification lives in `run-gates --final`, whose
|
|
4
4
|
// receipt this guard binds. `--check`:
|
|
5
|
+
// 0. refuses an INDEX that lags the verified working tree — FIRST, before the fingerprint is
|
|
6
|
+
// computed. The gates and the fingerprint describe the WORKING tree while `git commit` builds
|
|
7
|
+
// the commit from the INDEX alone, and the fingerprint domain is identical either way, so
|
|
8
|
+
// without this arm a lagging index ships a strict SUBSET of what was verified. Refuses on
|
|
9
|
+
// tracked paths differing index↔worktree or reviewable untracked-not-ignored paths (the same
|
|
10
|
+
// never-committable filter the fingerprint applies; ignored paths never refuse), naming them
|
|
11
|
+
// up to INDEX_LAG_PATH_CAP with the remainder stated. A dirty tracked SUBMODULE is named
|
|
12
|
+
// separately with its own recovery. Fail-closed on an undecidable probe. This BLOCKS the
|
|
13
|
+
// deliberate partial commit by design — `--no-verify` is the stated residual, not a flag;
|
|
5
14
|
// 1. recomputes the CURRENT tree fingerprint (the review-state export — read-only git plumbing);
|
|
6
15
|
// 2. reads the LATEST completed final-run record from the core-evidence store (only the latest
|
|
7
16
|
// attempt at a fingerprint is authoritative — a green receipt is DEAD once a later attempt at
|
|
@@ -18,11 +27,11 @@
|
|
|
18
27
|
|
|
19
28
|
import { readFileSync, lstatSync } from 'node:fs';
|
|
20
29
|
import { resolve } from 'node:path';
|
|
21
|
-
import { pathToFileURL } from 'node:url';
|
|
30
|
+
import { pathToFileURL, fileURLToPath } from 'node:url';
|
|
22
31
|
import { spawnSync } from 'node:child_process';
|
|
23
32
|
import { createHash } from 'node:crypto';
|
|
24
|
-
import { computeTreeFingerprint, buildState, decideCheck } from './review-state.mjs';
|
|
25
|
-
import { resolveEvidencePath, readEvidence, authoritativeOfKind, canonicalKindSerialization } from './core-evidence.mjs';
|
|
33
|
+
import { computeTreeFingerprint, buildState, decideCheck, quoteReportName, shellQuoteArg } from './review-state.mjs';
|
|
34
|
+
import { resolveEvidencePath, readEvidence, authoritativeOfKind, canonicalKindSerialization, computeWorkingState } from './core-evidence.mjs';
|
|
26
35
|
import { resolveLcovPath } from './coverage-check.mjs';
|
|
27
36
|
import { GATES_REL, loadDeclaration } from './run-gates.mjs';
|
|
28
37
|
|
|
@@ -44,10 +53,130 @@ export const resolveGitHooksPath = (projectDir) => {
|
|
|
44
53
|
return line == null ? null : resolve(projectDir, line);
|
|
45
54
|
};
|
|
46
55
|
|
|
56
|
+
// How many offending paths the index-lag refusal names before it states a remainder count: enough
|
|
57
|
+
// to act on, bounded so a wide lag cannot bury a pre-commit hook's output.
|
|
58
|
+
export const INDEX_LAG_PATH_CAP = 10;
|
|
59
|
+
|
|
60
|
+
// The recovery must name the run-gates the CONSUMER actually has. A repo-relative literal is only
|
|
61
|
+
// correct inside this monorepo; every installed deployment keeps the tool beside this file. Shell-
|
|
62
|
+
// quoted, because an install path carrying a space or a metacharacter would otherwise render an
|
|
63
|
+
// instruction that is unrunnable at best and dangerous to paste at worst.
|
|
64
|
+
const FINAL_RUN_TOOL = shellQuoteArg(fileURLToPath(new URL('./run-gates.mjs', import.meta.url)));
|
|
65
|
+
|
|
66
|
+
// ONE budget across every named category — a per-category cap would print 2× the stated number.
|
|
67
|
+
const renderBudgeted = (paths, budget) => ({
|
|
68
|
+
text: paths.slice(0, Math.max(budget, 0)).map(quoteReportName).join(', '),
|
|
69
|
+
used: Math.min(paths.length, Math.max(budget, 0)),
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
// The ONE ordered recovery plan — text and executable `argv` built from the SAME structure, so a
|
|
73
|
+
// test can run exactly what the operator is shown instead of reconstructing its own commands.
|
|
74
|
+
// Order matters: the submodule step first (staging and re-running --final before it would stale the
|
|
75
|
+
// fresh receipt at once), then the index bits, because `git add -A` CANNOT restage a skip-worktree
|
|
76
|
+
// or assume-unchanged entry — printing it alone is a recovery that silently does nothing. The two
|
|
77
|
+
// bits get SEPARATE commands: one `update-index` invocation carrying both flags applies only one.
|
|
78
|
+
// The text points at `git ls-files -v` rather than pasting names — the displayed list is capped,
|
|
79
|
+
// and a name safe to display is not automatically safe to paste into a shell.
|
|
80
|
+
export const buildIndexLagRecovery = (state) => {
|
|
81
|
+
const flags = state.flaggedPaths ?? [];
|
|
82
|
+
const steps = [];
|
|
83
|
+
if (state.unstagedSubmodulePaths.length > 0) {
|
|
84
|
+
steps.push({ text: 'commit or clean INSIDE every dirty submodule named above and stage its gitlink — a root-level git add -A cannot reach a submodule\'s own worktree' });
|
|
85
|
+
}
|
|
86
|
+
for (const [bit, key] of [['--no-skip-worktree', 'skipWorktree'], ['--no-assume-unchanged', 'assumeUnchanged']]) {
|
|
87
|
+
const affected = flags.filter((flag) => flag[key]);
|
|
88
|
+
if (affected.length === 0) continue;
|
|
89
|
+
// Scoped to the LAGGING paths only, never to `git ls-files -v`: that set also holds every
|
|
90
|
+
// de-materialised sparse-checkout entry, and clearing THEIR bit before `git add -A` would stage
|
|
91
|
+
// their deletions. The cap is handled by iteration, not by a wider enumeration. The executable
|
|
92
|
+
// form is offered ONLY when every affected name survives a byte round-trip — a lossily decoded
|
|
93
|
+
// name would address a DIFFERENT path, so there the text stands alone and says so.
|
|
94
|
+
const exact = affected.every((flag) => flag.exactName);
|
|
95
|
+
steps.push({
|
|
96
|
+
text: `clear the ${bit.slice(5)} bit on the bit-carrying path(s) named above — it is what makes git add -A a no-op on them — with git update-index ${bit} -- <path>, for those paths ONLY (never every entry git ls-files -v reports: that set includes de-materialised sparse paths whose deletions would then be staged)${exact ? '' : '; at least one of these names carries bytes that do not decode cleanly, so the name shown above is LOSSY and this refusal cannot give you a runnable command for it — its record is visible in git ls-files -v -z, and clearing that one is a by-hand step'}`,
|
|
97
|
+
...(exact ? { argv: ['update-index', bit, '--', ...affected.map((flag) => flag.rel)] } : {}),
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
steps.push({ text: 'run git add -A from the work-tree root', argv: ['add', '-A'] });
|
|
101
|
+
steps.push({ text: `re-run node ${FINAL_RUN_TOOL} --final` });
|
|
102
|
+
steps.push({ text: 'commit the WHOLE tree' });
|
|
103
|
+
return steps;
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
// decideIndexLag(state) → a refusal, or null when the index already carries the verified tree.
|
|
107
|
+
// The gates and the fingerprint both describe the WORKING tree; `git commit` takes the INDEX, and
|
|
108
|
+
// the fingerprint domain cannot tell the two apart — so without this arm a lagging index ships a
|
|
109
|
+
// strict subset of what was verified (it did, on 2026-07-25). FAIL-CLOSED on an undecidable probe:
|
|
110
|
+
// the guard's whole claim is that the committed bytes ARE the verified bytes, and it cannot make
|
|
111
|
+
// that claim about a tree it failed to read.
|
|
112
|
+
export const decideIndexLag = (state) => {
|
|
113
|
+
if (state == null) {
|
|
114
|
+
return { code: 1, lines: ['commit-guard: REFUSED — the index/worktree comparison could not be decided (a git probe failed); re-run inside the work tree and inspect `git status` by hand before committing'] };
|
|
115
|
+
}
|
|
116
|
+
// THREE categories, because they take DIFFERENT recoveries. A bit-carrying path folded into the
|
|
117
|
+
// plain list would be un-actionable: its clause is the only one whose recovery is not `git add -A`,
|
|
118
|
+
// and on cap overflow the plain paths could hide every one of them.
|
|
119
|
+
const flaggedSet = new Set((state.flaggedPaths ?? []).map((flag) => flag.rel));
|
|
120
|
+
const all = [...state.unstagedPaths, ...state.untrackedPaths];
|
|
121
|
+
const plain = all.filter((rel) => !flaggedSet.has(rel));
|
|
122
|
+
const bitCarrying = all.filter((rel) => flaggedSet.has(rel));
|
|
123
|
+
const submodules = state.unstagedSubmodulePaths;
|
|
124
|
+
const total = plain.length + bitCarrying.length + submodules.length;
|
|
125
|
+
if (total === 0) return null;
|
|
126
|
+
// Every non-empty category reserves a slot before the budget is spent — a clause that names no
|
|
127
|
+
// path cannot deliver the recovery it exists to state.
|
|
128
|
+
const groups = [plain, bitCarrying, submodules];
|
|
129
|
+
const rendered = [];
|
|
130
|
+
let spent = 0;
|
|
131
|
+
groups.forEach((group, index) => {
|
|
132
|
+
if (group.length === 0) {
|
|
133
|
+
rendered[index] = { text: '', used: 0 };
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
const stillToReserve = groups.slice(index + 1).filter((later) => later.length > 0).length;
|
|
137
|
+
rendered[index] = renderBudgeted(group, INDEX_LAG_PATH_CAP - spent - stillToReserve);
|
|
138
|
+
spent += rendered[index].used;
|
|
139
|
+
});
|
|
140
|
+
const hidden = total - spent;
|
|
141
|
+
const remainder = hidden > 0 ? `, plus ${hidden} further path(s) not listed` : '';
|
|
142
|
+
const clauses = [];
|
|
143
|
+
if (plain.length > 0) {
|
|
144
|
+
clauses.push(`paths the index does not carry: ${rendered[0].text}`);
|
|
145
|
+
}
|
|
146
|
+
if (bitCarrying.length > 0) {
|
|
147
|
+
clauses.push(`path(s) held back by a skip-worktree / assume-unchanged index bit: ${rendered[1].text}`);
|
|
148
|
+
}
|
|
149
|
+
if (submodules.length > 0) {
|
|
150
|
+
clauses.push(`tracked submodule(s) not proven current: ${rendered[2].text}`);
|
|
151
|
+
}
|
|
152
|
+
// ONE ordered recovery, and every step must actually converge. The submodule step comes FIRST:
|
|
153
|
+
// staging and re-running --final before it would stale the fresh receipt at once. The index-bit
|
|
154
|
+
// step comes next, because `git add -A` CANNOT restage a skip-worktree / assume-unchanged entry —
|
|
155
|
+
// printing it alone would be a recovery that silently does nothing. It deliberately points at
|
|
156
|
+
// `git ls-files -v` rather than pasting names: the list above is capped, and a filename safe to
|
|
157
|
+
// display is not automatically safe to paste into a shell.
|
|
158
|
+
const steps = buildIndexLagRecovery(state);
|
|
159
|
+
// The iterate-until-silent hint must also fire when the CAP hid work — otherwise a truncated
|
|
160
|
+
// list of submodules with no index bits would send the operator to --final and commit while
|
|
161
|
+
// unnamed ones are still unhandled.
|
|
162
|
+
const converge = hidden > 0 || (state.flaggedPaths ?? []).length > 0
|
|
163
|
+
? ' The listed paths are capped: re-run this guard after each pass and it names the next batch, until it names none — that is the completion signal.'
|
|
164
|
+
: '';
|
|
165
|
+
return {
|
|
166
|
+
code: 1,
|
|
167
|
+
lines: [`commit-guard: REFUSED — the index does NOT carry the whole CURRENT working tree, so this commit would leave part of it behind: ${clauses.join('; ')}${remainder}. To recover, in order: ${steps.map((step, i) => `(${i + 1}) ${step.text}`).join('; ')}. An intentional partial commit stays git commit --no-verify.${converge}`],
|
|
168
|
+
};
|
|
169
|
+
};
|
|
170
|
+
|
|
47
171
|
// runGuard({ cwd, env }) → { code, lines }. Every refusal names its recovery.
|
|
48
172
|
export const runGuard = ({ cwd = process.cwd(), env = process.env } = {}) => {
|
|
49
173
|
const rootTop = gitLine(['rev-parse', '--show-toplevel'], cwd);
|
|
50
174
|
if (rootTop == null) return { code: 1, lines: ['commit-guard: not a git work tree — nothing to guard'] };
|
|
175
|
+
// FIRST: a pure tree property needing no store read. Its recovery re-stages the tree and re-mints
|
|
176
|
+
// the receipt, so every arm below is re-decided anyway — naming a stale fingerprint ahead of it
|
|
177
|
+
// would send the operator down a recovery they must redo.
|
|
178
|
+
const indexLag = decideIndexLag(computeWorkingState(cwd));
|
|
179
|
+
if (indexLag !== null) return indexLag;
|
|
51
180
|
const fingerprint = computeTreeFingerprint(cwd);
|
|
52
181
|
// The guard's OWN reads resolve FIXED git-dir paths — a stray AW_CORE_EVIDENCE / AW_LCOV_FILE
|
|
53
182
|
// in the committing shell must never redirect the LAST line of defense to a forged artifact
|
|
@@ -128,11 +257,13 @@ const HELP = `commit-guard — the read-only pre-commit guard (agent-workflow fa
|
|
|
128
257
|
Usage:
|
|
129
258
|
node commit-guard.mjs --check [--cwd <dir>]
|
|
130
259
|
|
|
131
|
-
Re-runs NOTHING:
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
260
|
+
Re-runs NOTHING: refuses an INDEX that lags the verified working tree (FIRST — unstaged tracked
|
|
261
|
+
paths, reviewable untracked paths, or a dirty tracked submodule, each named with its recovery;
|
|
262
|
+
this deliberately blocks a partial commit), then recomputes the current tree fingerprint and binds
|
|
263
|
+
the LATEST completed run-gates --final receipt — refusing on { no receipt for this tree · a red
|
|
264
|
+
latest attempt · before≠after · declaration content drift · evidence-hash drift · lcov drift ·
|
|
265
|
+
unsatisfied review obligations (the review-state decision) }. Wire it into pre-commit;
|
|
266
|
+
\`git commit --no-verify\` stays the stated residual (self-discipline, not a security boundary).
|
|
136
267
|
|
|
137
268
|
Exit codes: 0 pass; 1 refused (reason named); 2 usage.`;
|
|
138
269
|
|
package/tools/core-evidence.mjs
CHANGED
|
@@ -152,29 +152,240 @@ export const computeTreeFingerprint = (cwd, fsx) => {
|
|
|
152
152
|
return payload == null ? null : createHash('sha256').update(payload).digest('hex');
|
|
153
153
|
};
|
|
154
154
|
|
|
155
|
-
//
|
|
156
|
-
//
|
|
157
|
-
//
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
155
|
+
// The index↔worktree split the fingerprint deliberately CANNOT see: the payload above concatenates
|
|
156
|
+
// the staged and unstaged diffs, so against an otherwise-empty index a hunk moving into the index
|
|
157
|
+
// leaves it byte-identical — while `git commit` builds the commit from the INDEX alone. This is the
|
|
158
|
+
// ONE computation of that split; isTreeClean and the commit guard's index-lag arm both read it, so
|
|
159
|
+
// they can never disagree about what "the index carries the verified tree" means. Submodule paths
|
|
160
|
+
// are separated because a root-level `git add -A` cannot reach a submodule's own worktree, so they
|
|
161
|
+
// need their own recovery. Anchored at the work-tree ROOT (ls-files is cwd-scoped); null when not
|
|
162
|
+
// decidable — every consumer treats that as fail-closed, never as clean.
|
|
163
|
+
const LS_FILES_TAG_SKIP_WORKTREE = 'S';
|
|
164
|
+
const GITLINK_MODE = '160000';
|
|
165
|
+
const SYMLINK_MODE = '120000';
|
|
166
|
+
const EXECUTABLE_MODE = '100755';
|
|
167
|
+
const OWNER_EXECUTE_BIT = 0o100;
|
|
168
|
+
// `ls-files -v` lowercases the tag for assume-unchanged; skip-worktree is `S`, and an entry
|
|
169
|
+
// carrying BOTH bits prints lowercase `s` (live-pinned by test). The skip test is therefore
|
|
170
|
+
// case-INSENSITIVE — a case-sensitive one would lose skip-worktree on such an entry and turn a
|
|
171
|
+
// legitimate sparse checkout into an endless refusal.
|
|
172
|
+
const isAssumeUnchangedTag = (tag) => tag >= 'a' && tag <= 'z';
|
|
173
|
+
const isSkipWorktreeTag = (tag) => tag.toUpperCase() === LS_FILES_TAG_SKIP_WORKTREE;
|
|
174
|
+
|
|
175
|
+
// `git diff` SKIPS index entries carrying skip-worktree or assume-unchanged, so such a path can
|
|
176
|
+
// hold worktree bytes the gates read while `git commit` takes the stale INDEX blob — the same
|
|
177
|
+
// capture blindness one layer down, and invisible to the plain probe. Those entries are therefore
|
|
178
|
+
// compared DIRECTLY against the worktree. A MISSING skip-worktree path is an ordinary sparse
|
|
179
|
+
// checkout and never a lag; a missing assume-unchanged path is one. Gitlinks belong to the
|
|
180
|
+
// submodule lane. Any probe that cannot answer counts the path as lagging (fail-safe).
|
|
181
|
+
const flaggedIndexLag = (top, runGit, lstat, readlink) => {
|
|
182
|
+
const buf = (args) => {
|
|
183
|
+
const r = runGit(args, top);
|
|
184
|
+
return r.error || r.status !== 0 ? null : r.stdout;
|
|
185
|
+
};
|
|
186
|
+
const splitZ = (b) => b.toString('utf8').split('\0').filter(Boolean);
|
|
187
|
+
// Git emits raw path BYTES. Decoding to UTF-8 first turns a name carrying invalid bytes into a
|
|
188
|
+
// DIFFERENT path, whose lstat then answers ENOENT — which for a skip-worktree entry reads as a
|
|
189
|
+
// de-materialised sparse path and lets a stale index walk through. So each record keeps its
|
|
190
|
+
// original slice and a name that does not survive a byte round-trip is lagging by construction.
|
|
191
|
+
const splitZBytes = (b) => {
|
|
192
|
+
const out = [];
|
|
193
|
+
let start = 0;
|
|
194
|
+
for (let i = 0; i < b.length; i += 1) {
|
|
195
|
+
if (b[i] !== 0) continue;
|
|
196
|
+
if (i > start) out.push(b.subarray(start, i));
|
|
197
|
+
start = i + 1;
|
|
198
|
+
}
|
|
199
|
+
if (start < b.length) out.push(b.subarray(start));
|
|
200
|
+
return out;
|
|
201
|
+
};
|
|
202
|
+
const decodesExactly = (slice) => Buffer.from(slice.toString('utf8'), 'utf8').equals(slice);
|
|
203
|
+
const taggedZ = buf(['ls-files', '-v', '-z']);
|
|
204
|
+
if (taggedZ == null) return null;
|
|
205
|
+
// The two bits are INDEPENDENT — an entry can carry both (which is what lowercases the `S`), so
|
|
206
|
+
// they travel as a pair and the recovery clears whichever are actually set.
|
|
207
|
+
const flagged = splitZBytes(taggedZ)
|
|
208
|
+
.map((record) => {
|
|
209
|
+
const tag = record.subarray(0, 1).toString('utf8');
|
|
210
|
+
const pathBytes = record.subarray(2);
|
|
211
|
+
return {
|
|
212
|
+
rel: pathBytes.toString('utf8'),
|
|
213
|
+
pathBytes,
|
|
214
|
+
exactName: decodesExactly(pathBytes),
|
|
215
|
+
skipWorktree: isSkipWorktreeTag(tag),
|
|
216
|
+
assumeUnchanged: isAssumeUnchangedTag(tag),
|
|
217
|
+
};
|
|
218
|
+
})
|
|
219
|
+
.filter(({ skipWorktree, assumeUnchanged }) => skipWorktree || assumeUnchanged);
|
|
220
|
+
if (flagged.length === 0) return { paths: [], submodules: [], flagged: [] };
|
|
221
|
+
const stagedZ = buf(['ls-files', '-s', '-z']);
|
|
222
|
+
if (stagedZ == null) return null;
|
|
223
|
+
const entries = new Map();
|
|
224
|
+
for (const line of splitZ(stagedZ)) {
|
|
225
|
+
const tab = line.indexOf('\t');
|
|
226
|
+
if (tab === -1) continue;
|
|
227
|
+
const [mode, oid] = line.slice(0, tab).split(' ');
|
|
228
|
+
entries.set(line.slice(tab + 1), { mode, oid });
|
|
229
|
+
}
|
|
230
|
+
// `git diff` honours core.fileMode; mirroring it keeps a false-mode host (WSL, network mounts)
|
|
231
|
+
// from reading every executable bit as a lag. Exit 1 is the only "unset" (git's default is true);
|
|
232
|
+
// any other failure leaves the comparison undecidable rather than guessing.
|
|
233
|
+
const boolConfig = (key) => {
|
|
234
|
+
const r = runGit(['config', '--type=bool', '--get', key], top);
|
|
235
|
+
if (r.error || (r.status !== 0 && r.status !== 1)) return null; // undecidable — never guessed
|
|
236
|
+
return r.status === 1 || r.stdout.toString('utf8').trim() !== 'false'; // exit 1 = unset = git's default true
|
|
237
|
+
};
|
|
238
|
+
const honoursFileMode = boolConfig('core.fileMode');
|
|
239
|
+
// On a host without symlink support git materialises a symlink as a REGULAR FILE holding the
|
|
240
|
+
// target bytes; demanding a real link there would refuse forever.
|
|
241
|
+
const materialisesSymlinks = boolConfig('core.symlinks');
|
|
242
|
+
if (honoursFileMode === null || materialisesSymlinks === null) return null;
|
|
243
|
+
const lagging = [];
|
|
244
|
+
const laggingSubmodules = [];
|
|
245
|
+
const laggingFlags = [];
|
|
246
|
+
for (const { rel, pathBytes, exactName, skipWorktree, assumeUnchanged } of flagged) {
|
|
247
|
+
const entry = entries.get(rel);
|
|
248
|
+
if (entry === undefined) continue;
|
|
249
|
+
const isGitlink = entry.mode === GITLINK_MODE;
|
|
250
|
+
// Every path this loop reports needs its index bits cleared before ANY staging command can
|
|
251
|
+
// pick it up — `git add -A` alone is a recovery that silently does nothing here.
|
|
252
|
+
const lag = () => {
|
|
253
|
+
(isGitlink ? laggingSubmodules : lagging).push(rel);
|
|
254
|
+
laggingFlags.push({ rel, skipWorktree, assumeUnchanged, exactName });
|
|
255
|
+
};
|
|
256
|
+
// Probed by RAW BYTES, never by the decoded name: a lossy decode addresses a DIFFERENT path,
|
|
257
|
+
// and answering ENOENT for it would either wave a stale index through or — worse — call a
|
|
258
|
+
// legitimately absent sparse entry "lagging", whose prescribed bit-clear plus `git add -A`
|
|
259
|
+
// would then stage its DELETION.
|
|
260
|
+
const absPath = Buffer.concat([Buffer.from(top), Buffer.from(sep), pathBytes]);
|
|
261
|
+
let stat = null;
|
|
262
|
+
let absent = false;
|
|
263
|
+
try {
|
|
264
|
+
stat = lstat(absPath);
|
|
265
|
+
} catch (err) {
|
|
266
|
+
// ONLY a genuine absence is the sparse-checkout case; EACCES / EIO leave the path unproven,
|
|
267
|
+
// and an unproven path can never be waved through as "not materialised".
|
|
268
|
+
absent = err != null && err.code === 'ENOENT';
|
|
269
|
+
}
|
|
270
|
+
if (stat === null) {
|
|
271
|
+
if (!absent || !skipWorktree) lag();
|
|
272
|
+
continue;
|
|
273
|
+
}
|
|
274
|
+
if (!exactName) {
|
|
275
|
+
// Materialised, but the name cannot be addressed through an argv string, so it can never be
|
|
276
|
+
// PROVEN current — fail-safe. Absence was already decided above, on the real bytes.
|
|
277
|
+
lag();
|
|
278
|
+
continue;
|
|
279
|
+
}
|
|
280
|
+
// A flagged GITLINK is hidden from `git diff` too, so the submodule lane would never see it —
|
|
281
|
+
// and it is deliberately NOT proven current here. Three consecutive review rounds each found a
|
|
282
|
+
// new way for a nested probe to answer "clean" wrongly (inherited superproject GIT_*, status
|
|
283
|
+
// config blindness, the submodule's OWN flagged entries, a symlink standing in for the
|
|
284
|
+
// directory). The set was not shrinking, so the verdict is REDUCTION rather than another patch:
|
|
285
|
+
// a materialised flagged gitlink LAGS by construction. It is a refusal, never an endless one —
|
|
286
|
+
// the printed recovery (clear the bit, then git add -A) converges, and an UNflagged submodule
|
|
287
|
+
// is unaffected because the ordinary --ignore-submodules=none probe still judges it.
|
|
288
|
+
if (isGitlink) {
|
|
289
|
+
lag();
|
|
290
|
+
continue;
|
|
291
|
+
}
|
|
292
|
+
if (entry.mode === SYMLINK_MODE && !stat.isSymbolicLink() && !materialisesSymlinks) {
|
|
293
|
+
// The placeholder file's RAW bytes are the stored target — no filters ever apply to a link.
|
|
294
|
+
const placeholder = runGit(['hash-object', '--no-filters', '-t', 'blob', '--', join(top, rel)], top);
|
|
295
|
+
if (placeholder.error || placeholder.status !== 0 || placeholder.stdout.toString('utf8').trim() !== entry.oid) lag();
|
|
296
|
+
continue;
|
|
297
|
+
}
|
|
298
|
+
if (entry.mode === SYMLINK_MODE || stat.isSymbolicLink()) {
|
|
299
|
+
if (entry.mode !== SYMLINK_MODE || !stat.isSymbolicLink()) {
|
|
300
|
+
lag();
|
|
301
|
+
continue;
|
|
302
|
+
}
|
|
303
|
+
let target = null;
|
|
304
|
+
try {
|
|
305
|
+
target = readlink(join(top, rel));
|
|
306
|
+
} catch {
|
|
307
|
+
target = null;
|
|
308
|
+
}
|
|
309
|
+
if (target === null) {
|
|
310
|
+
lag(); // an unreadable link can never be proven current — fail-safe
|
|
311
|
+
continue;
|
|
312
|
+
}
|
|
313
|
+
const hashed = runGit(['hash-object', '-t', 'blob', '--stdin'], top, target);
|
|
314
|
+
if (hashed.error || hashed.status !== 0 || hashed.stdout.toString('utf8').trim() !== entry.oid) lag();
|
|
315
|
+
continue;
|
|
316
|
+
}
|
|
317
|
+
if (!stat.isFile()) {
|
|
318
|
+
lag();
|
|
319
|
+
continue;
|
|
320
|
+
}
|
|
321
|
+
// Git canonicalises the executable mode on the OWNER bit alone — a file with only group/other
|
|
322
|
+
// exec set is still `100644` to git, so testing 0o111 would call a stale index current.
|
|
323
|
+
if (honoursFileMode && (entry.mode === EXECUTABLE_MODE) !== ((stat.mode & OWNER_EXECUTE_BIT) !== 0)) {
|
|
324
|
+
lag();
|
|
325
|
+
continue;
|
|
326
|
+
}
|
|
327
|
+
const hashed = runGit(['hash-object', '--path', rel, '--', join(top, rel)], top);
|
|
328
|
+
if (hashed.error || hashed.status !== 0 || hashed.stdout.toString('utf8').trim() !== entry.oid) lag();
|
|
329
|
+
}
|
|
330
|
+
return { paths: lagging, submodules: laggingSubmodules, flagged: laggingFlags };
|
|
331
|
+
};
|
|
332
|
+
|
|
333
|
+
export const computeWorkingState = (cwd, { lstat = lstatSync, readlink = readlinkSync, runGit = null } = {}) => {
|
|
334
|
+
const run = runGit ?? ((args, dir, input, env) => spawnSync('git', args, { cwd: dir, input, env: env ?? process.env, maxBuffer: GIT_MAX_BUFFER, windowsHide: true }));
|
|
335
|
+
const topRun = run(['rev-parse', '--show-toplevel'], cwd);
|
|
336
|
+
if (topRun.error || topRun.status !== 0) return null;
|
|
337
|
+
const top = topRun.stdout.toString('utf8').replace(/\r?\n$/, '');
|
|
338
|
+
// `--ignore-submodules=none` on the staged probe too: a config-hidden STAGED gitlink would
|
|
339
|
+
// otherwise make stagedDirty false, and isTreeClean would call such a tree clean.
|
|
340
|
+
const staged = run(['diff', '--cached', '--quiet', '--ignore-submodules=none'], top);
|
|
341
|
+
// ONLY 0 or 1 is a usable answer: a signal-killed probe reports status null, which the old
|
|
342
|
+
// `> 1` guard let through as "nothing staged" — a fail-OPEN the whole arm cannot afford.
|
|
343
|
+
if (staged.error || (staged.status !== 0 && staged.status !== 1)) return null;
|
|
344
|
+
const buf = (args) => {
|
|
345
|
+
const r = run(args, top);
|
|
346
|
+
return r.error || r.status !== 0 ? null : r.stdout;
|
|
347
|
+
};
|
|
348
|
+
// The FULL probe forces submodules back in: diff.ignoreSubmodules / submodule.<n>.ignore would
|
|
349
|
+
// otherwise erase a dirty submodule from the comparison entirely.
|
|
350
|
+
const changedZ = buf(['diff', '--name-only', '-z', '--ignore-submodules=none']);
|
|
351
|
+
const plainZ = buf(['diff', '--name-only', '-z', '--ignore-submodules=all']);
|
|
352
|
+
const untrackedZ = buf(['ls-files', '--others', '--exclude-standard', '-z']);
|
|
353
|
+
if (changedZ == null || plainZ == null || untrackedZ == null) return null;
|
|
354
|
+
const split = (b) => b.toString('utf8').split('\0').filter(Boolean);
|
|
355
|
+
const changed = split(changedZ);
|
|
356
|
+
const plain = new Set(split(plainZ));
|
|
357
|
+
const flagged = flaggedIndexLag(top, run, lstat, readlink);
|
|
358
|
+
if (flagged == null) return null;
|
|
359
|
+
const unstaged = changed.filter((rel) => plain.has(rel));
|
|
360
|
+
const submodules = changed.filter((rel) => !plain.has(rel));
|
|
361
|
+
return {
|
|
362
|
+
stagedDirty: staged.status === 1,
|
|
363
|
+
unstagedPaths: [...unstaged, ...flagged.paths.filter((rel) => !unstaged.includes(rel))],
|
|
364
|
+
unstagedSubmodulePaths: [...submodules, ...flagged.submodules.filter((rel) => !submodules.includes(rel))],
|
|
365
|
+
// Which lagging paths carry index bits, and which — `git add -A` cannot restage these at all.
|
|
366
|
+
flaggedPaths: flagged.flagged,
|
|
367
|
+
untrackedPaths: split(untrackedZ).filter((rel) => {
|
|
171
368
|
try {
|
|
172
369
|
return !isNeverCommittableStat(lstat(join(top, rel)));
|
|
173
370
|
} catch {
|
|
174
371
|
return true;
|
|
175
372
|
}
|
|
176
|
-
})
|
|
177
|
-
|
|
373
|
+
}),
|
|
374
|
+
};
|
|
375
|
+
};
|
|
376
|
+
|
|
377
|
+
// Clean = nothing staged, nothing unstaged, no REVIEWABLE untracked-not-ignored paths — the same
|
|
378
|
+
// never-committable filter as the fingerprint, so the two can never disagree about a masks-only
|
|
379
|
+
// tree. Null when not decidable.
|
|
380
|
+
export const isTreeClean = (cwd, fsx) => {
|
|
381
|
+
const state = computeWorkingState(cwd, fsx);
|
|
382
|
+
if (state == null) return null;
|
|
383
|
+
return (
|
|
384
|
+
!state.stagedDirty &&
|
|
385
|
+
state.unstagedPaths.length === 0 &&
|
|
386
|
+
state.unstagedSubmodulePaths.length === 0 &&
|
|
387
|
+
state.untrackedPaths.length === 0
|
|
388
|
+
);
|
|
178
389
|
};
|
|
179
390
|
|
|
180
391
|
// ── the review-receipt read path + attesting predicate (ONE home) ────────────────────────────────
|