@marcomigozzi/trailhead 0.13.0 → 0.15.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/README.it.md +142 -29
- package/README.md +141 -28
- package/bin/base-preflight-docs.test.js +65 -0
- package/bin/execute-split-docs.test.js +146 -0
- package/bin/isolation-answer-docs.test.js +41 -0
- package/bin/isolation-copy-docs.test.js +28 -0
- package/bin/lib/codex-projection.js +17 -10
- package/bin/lib/codex-projection.test.js +80 -11
- package/bin/lib/install-verify.js +10 -5
- package/bin/lib/install-verify.test.js +51 -0
- package/bin/report-status-docs.test.js +195 -0
- package/bin/resolve-helpers-docs.test.js +36 -0
- package/bin/scope-confirm-skip-docs.test.js +70 -0
- package/bin/trailhead.js +40 -28
- package/bin/trailhead.test.js +503 -6
- package/bin/uat-setup-docs.test.js +65 -0
- package/package.json +4 -1
- package/plugins/trailhead/.claude-plugin/plugin.json +3 -2
- package/plugins/trailhead/agents/trailhead-code-review.md +15 -2
- package/plugins/trailhead/agents/trailhead-codebase-map.md +20 -1
- package/plugins/trailhead/agents/trailhead-debug.md +20 -1
- package/plugins/trailhead/agents/trailhead-executor.md +29 -2
- package/plugins/trailhead/agents/trailhead-fix.md +29 -2
- package/plugins/trailhead/agents/trailhead-plan.md +20 -1
- package/plugins/trailhead/agents/trailhead-research.md +22 -3
- package/plugins/trailhead/agents/trailhead-verify.md +15 -2
- package/plugins/trailhead/commands/panel.md +10 -0
- package/plugins/trailhead/hooks/hooks.json +3 -18
- package/plugins/trailhead/hooks/lib/base-preflight.test.js +513 -0
- package/plugins/trailhead/hooks/lib/body-sources.js +795 -0
- package/plugins/trailhead/hooks/lib/commit-message-check.js +1 -1
- package/plugins/trailhead/hooks/lib/commit-message-check.test.js +3 -2
- package/plugins/trailhead/hooks/lib/commit-msg-module-repo.test.js +116 -0
- package/plugins/trailhead/hooks/lib/commit-msg-sync.test.js +100 -9
- package/plugins/trailhead/hooks/lib/dashboard.test.js +409 -0
- package/plugins/trailhead/hooks/lib/fixtures/commit-msg-legacy-js +104 -0
- package/plugins/trailhead/hooks/lib/gh-subcommand.js +92 -10
- package/plugins/trailhead/hooks/lib/gh-subcommand.test.js +55 -0
- package/plugins/trailhead/hooks/lib/isolation-answer.test.js +258 -0
- package/plugins/trailhead/hooks/lib/isolation-copy.test.js +298 -0
- package/plugins/trailhead/hooks/lib/issue-body.test.js +470 -0
- package/plugins/trailhead/hooks/lib/mockup-link.js +21 -5
- package/plugins/trailhead/hooks/lib/report-status.test.js +366 -0
- package/plugins/trailhead/hooks/lib/shell-scan.js +532 -65
- package/plugins/trailhead/hooks/lib/shell-scan.test.js +434 -0
- package/plugins/trailhead/hooks/lib/uat-backfill.test.js +150 -0
- package/plugins/trailhead/hooks/lib/uat-setup.test.js +340 -0
- package/plugins/trailhead/hooks/lib/unmodelled.js +345 -0
- package/plugins/trailhead/hooks/lib/unmodelled.test.js +173 -0
- package/plugins/trailhead/hooks/lib/work-state.test.js +297 -0
- package/plugins/trailhead/hooks/mod/README.md +219 -0
- package/plugins/trailhead/hooks/mod/map-pane-view.ts +606 -0
- package/plugins/trailhead/hooks/mod/map-pane.tsx +832 -0
- package/plugins/trailhead/hooks/mod/register.tsx +293 -0
- package/plugins/trailhead/hooks/mod/work-state-prompt.ts +69 -0
- package/plugins/trailhead/hooks/mod/work-state-view.ts +110 -0
- package/plugins/trailhead/hooks/trailhead-bash-guards.js +140 -0
- package/plugins/trailhead/hooks/trailhead-bash-guards.test.js +233 -0
- package/plugins/trailhead/hooks/trailhead-body-guard.js +145 -61
- package/plugins/trailhead/hooks/trailhead-body-guard.test.js +224 -3
- package/plugins/trailhead/hooks/trailhead-commit-guard.js +41 -14
- package/plugins/trailhead/hooks/trailhead-commit-guard.test.js +2 -1
- package/plugins/trailhead/hooks/trailhead-install-guard.js +187 -42
- package/plugins/trailhead/hooks/trailhead-install-guard.test.js +182 -2
- package/plugins/trailhead/hooks/trailhead-mockup-link-guard.js +48 -11
- package/plugins/trailhead/hooks/trailhead-mockup-link-guard.test.js +75 -3
- package/plugins/trailhead/hooks/trailhead-search-guard.js +59 -13
- package/plugins/trailhead/hooks/trailhead-search-guard.test.js +68 -3
- package/plugins/trailhead/hooks/trailhead-secret-guard.js +541 -57
- package/plugins/trailhead/hooks/trailhead-secret-guard.test.js +1000 -4
- package/plugins/trailhead/hooks/trailhead-secret-read-guard.js +171 -6
- package/plugins/trailhead/hooks/trailhead-secret-read-guard.test.js +170 -0
- package/plugins/trailhead/skills/_shared/choices.md +7 -3
- package/plugins/trailhead/skills/_shared/configuration-reference.md +15 -3
- package/plugins/trailhead/skills/_shared/load-first.md +3 -3
- package/plugins/trailhead/skills/_shared/multi-map.md +3 -3
- package/plugins/trailhead/skills/_shared/session-handoff.md +1 -1
- package/plugins/trailhead/skills/_shared/substrate-commands.md +22 -11
- package/plugins/trailhead/skills/_shared/substrate.md +6 -4
- package/plugins/trailhead/skills/_shared/teamwork.md +17 -6
- package/plugins/trailhead/skills/_shared/techniques/acceptance-testing.md +17 -9
- package/plugins/trailhead/skills/_shared/techniques/code-review.md +1 -1
- package/plugins/trailhead/skills/_shared/techniques/codebase-map.md +1 -1
- package/plugins/trailhead/skills/_shared/techniques/debug.md +2 -0
- package/plugins/trailhead/skills/_shared/techniques/prototype.md +1 -1
- package/plugins/trailhead/skills/_shared/techniques/research.md +4 -2
- package/plugins/trailhead/skills/_shared/techniques/verify.md +1 -1
- package/plugins/trailhead/skills/_shared/techniques.md +12 -2
- package/plugins/trailhead/skills/trailhead/SKILL.md +3 -3
- package/plugins/trailhead/skills/trailhead-capture/SKILL.md +1 -1
- package/plugins/trailhead/skills/trailhead-capture/references/capture.md +2 -2
- package/plugins/trailhead/skills/trailhead-chart/SKILL.md +1 -1
- package/plugins/trailhead/skills/trailhead-chart/references/charting.md +1 -1
- package/plugins/trailhead/skills/trailhead-manage/SKILL.md +1 -1
- package/plugins/trailhead/skills/trailhead-manage/references/auditing.md +1 -1
- package/plugins/trailhead/skills/trailhead-view/SKILL.md +8 -6
- package/plugins/trailhead/skills/trailhead-work/SKILL.md +16 -13
- package/plugins/trailhead/skills/trailhead-work/references/auto.md +6 -4
- package/plugins/trailhead/skills/trailhead-work/references/executor-brief.md +29 -0
- package/plugins/trailhead/skills/trailhead-work/references/ticket-engines.md +28 -10
- package/plugins/trailhead/templates/trailhead-base-preflight.js +305 -0
- package/plugins/trailhead/templates/trailhead-commit-msg +38 -102
- package/plugins/trailhead/templates/trailhead-commit-msg-sync.js +58 -27
- package/plugins/trailhead/templates/trailhead-commit-msg.cjs +114 -0
- package/plugins/trailhead/templates/trailhead-dashboard.js +340 -0
- package/plugins/trailhead/templates/trailhead-isolation-answer.js +227 -0
- package/plugins/trailhead/templates/trailhead-isolation-copy.js +239 -0
- package/plugins/trailhead/templates/trailhead-issue-body.js +459 -0
- package/plugins/trailhead/templates/trailhead-report-status.js +274 -0
- package/plugins/trailhead/templates/trailhead-uat-backfill.js +114 -0
- package/plugins/trailhead/templates/trailhead-uat-setup.js +385 -0
- package/plugins/trailhead/templates/trailhead-work-state.js +217 -0
- package/plugins/trailhead/tests/map-pane-ui.test.ts +1921 -0
- package/plugins/trailhead/tests/map-pane-view.test.ts +853 -0
- package/plugins/trailhead/tests/mod.test.ts +14 -0
- package/plugins/trailhead/tests/work-state-prompt-hook.test.ts +207 -0
- package/plugins/trailhead/tests/work-state-prompt.test.ts +109 -0
- package/plugins/trailhead/tests/work-state-ui.test.ts +365 -0
- package/plugins/trailhead/tests/work-state-view.test.ts +110 -0
- package/plugins/trailhead/types/index.d.ts +103 -0
|
@@ -6,8 +6,10 @@ Every ticket is **HITL** (human in the loop, speaking for themselves) or **AFK**
|
|
|
6
6
|
|
|
7
7
|
Technique names below (**Grilling**, **Domain vocabulary**, **Prototype**, **Research**, **TDD**, **Code review**, **Acceptance testing**, **Debug**) are indexed in `../../_shared/techniques.md`; their full protocols live in `_shared/`, read from `../../_shared/techniques/<name>.md`.
|
|
8
8
|
|
|
9
|
+
**Work state (every type).** Keep `.trailhead/work-state.json` current with the `set --step` call in the **Work state file** paragraph of `../../_shared/teamwork.md`: `build` Discuss/Plan/Execute/Verify/Resolve set `discuss`/`plan`/`execute`/`verify`/`resolve`; `bug` Repro and Diagnose set `discuss`, Fix `execute`, Verify `verify`, Resolve `resolve`; `decision`, `prototype` and `task` stay `discuss` until `resolve`. A loop back from Verify to Execute (or Fix) sets `execute` again, and a UAT follow-up (`UAT of:`) sets `verify`. `research` tickets never write it: they run AFK and possibly in parallel, and the single file tracks only the one ticket in play.
|
|
10
|
+
|
|
9
11
|
## UAT follow-ups (any type)
|
|
10
|
-
A ticket whose body carries `UAT of: <parent
|
|
12
|
+
A ticket whose body carries a `UAT of: [<parent name>](<parent url>)` line is a UAT follow-up (it also carries the `trailhead:uat` label, a marker that never changes the frontier; the body line stays the authority, since a ticket opened before the label existed is tagged by the backfill), **whatever its type label**, including a graduated seed (a `trailhead:seed` that dropped `trailhead:seed` + `trailhead:blocked` on graduating, keeping whatever type label it had, or none). `work`, `quick`, and `auto` all dispatch through this file, so this check runs **before** the per-type engines below. It resolves via the **Acceptance testing** technique (`../../_shared/techniques/acceptance-testing.md`), starting with the stale-base preflight (`trailhead-base-preflight.js`, **Stale-base preflight** in `../../_shared/teamwork.md`), then the UAT setup (`trailhead-uat-setup.js`, **UAT setup comes next** in the technique), and then the drive-mode ask; the record is a `VERIFY` comment on the follow-up itself, never on the parent. It closes only on a confirmed pass or an explicit waiver (the user's skip at the drive-mode ask, recorded in the `VERIFY` comment as unconfirmed; the follow-up closes as waived), with a resolution comment linking back to the parent and stating the waiver when there was one.
|
|
11
13
|
|
|
12
14
|
## `decision`: HITL, *default for decision tickets*
|
|
13
15
|
Close a choice, but widen before you narrow:
|
|
@@ -18,7 +20,7 @@ Close a choice, but widen before you narrow:
|
|
|
18
20
|
The two phases are distinct on purpose: divergence generates, grilling chooses. Never let the agent invent the options *and* pick for the human: the choice stays theirs.
|
|
19
21
|
|
|
20
22
|
## `research`: AFK
|
|
21
|
-
Reading docs, third-party APIs, or local resources to surface a fact a decision waits on. Resolved by the **Research** technique. The only type that runs in parallel and more than one per session.
|
|
23
|
+
Reading docs, third-party APIs, or local resources to surface a fact a decision waits on. Resolved by the **Research** technique, whose `trailhead-research` report the orchestrator checks and posts as a `RESEARCH` comment (see the technique). The only type that runs in parallel and more than one per session.
|
|
22
24
|
|
|
23
25
|
## `prototype`: HITL
|
|
24
26
|
Raise the fidelity of the discussion with a rough, concrete artifact to react to: the **Prototype** technique. Link the prototype as an asset.
|
|
@@ -29,10 +31,18 @@ The ticket that *builds*. Lean cycle, all in **ticket comments**:
|
|
|
29
31
|
**Size triage (`effort`-gated, before Discuss).** When `config.effort` is `lean`, run the **size triage and ask-to-skip offer defined canonically under effort in `../../_shared/configuration-reference.md`** before Discuss: classify the change, and on trivial/small surface the one consolidated offer (its skippable steps here: the plan subagent -> a short inline plan; TDD; Cross-AI plan review; the full Code-review subagent -> a lighter inline pass; the Goal-backward verification subagent -> a quick inline goal check), going lean **only on an explicit yes**. On `normal`, on a no/silence/ambiguity, and always under `effort: standard` (the default), run the full cycle below unchanged. The correctness spine (atomic `Refs:` commits, the tests / the plan's criterion, the post-commit self-check, Resolve) is never in the offer.
|
|
30
32
|
|
|
31
33
|
1. **Discuss**: **never auto-grill.** Start from Plan. If reading the ticket surfaces blocking ambiguity, **stop and ask the user** whether they want a **Grilling** round: don't launch it on your own initiative. Only on their assent run the short round and post a `DISCUSS` comment with the closed choices. The user may also ask for it themselves at any time. Advisory choices raised here **offer** the delegate/defer options, per the injection recipe in `../../_shared/choices.md`.
|
|
32
|
-
2. **Plan**: a `PLAN` comment: the steps, the seams, the files touched, the verification criteria. Apply **TDD** per `config.tdd` (`seams`/`on`/`off`). Produce this plan via a *planner subagent* on `config.models.plan` (dispatch the **`trailhead-plan`** agent, read-only, passing `config.models.plan` as the model override; inline when the model is unset or equals the session model; Execute then runs as its own subagent, see below). If `config.plan_review` is on, run **Cross-AI plan review** before Execute: send the plan to external AI CLIs and converge on their concerns. Now that the files/seam are known, run the **undeclared-coupling check** (`../../_shared/teamwork.md`) against in-progress tickets. **Plan to sufficiency:** stop once you can name the steps, seams, and files with confidence, and never re-read a file already read in this planning pass; act when you have enough to plan, rather than re-deriving what the pass already established. **The single exception:** under an accepted `lean` skip (see the Size triage above), produce a short inline plan here instead of the planner subagent, and skip Cross-AI plan review; absent that accepted skip, this step runs in full as described.
|
|
33
|
-
3. **Execute**:
|
|
34
|
-
|
|
35
|
-
|
|
34
|
+
2. **Plan**: a `PLAN` comment: the steps, the seams, the files touched, the verification criteria. Apply **TDD** per `config.tdd` (`seams`/`on`/`off`). Produce this plan via a *planner subagent* on `config.models.plan` (dispatch the **`trailhead-plan`** agent, read-only, passing `config.models.plan` as the model override; inline when the model is unset or equals the session model; Execute then runs as its own subagent, see below). **Report (orchestrator).** Run the report-status check on the planner's report (`--technique plan`, the *Malformed review report* protocol in `../../_shared/techniques.md`) and branch on the checker's `verdict`: `status: ready` -> post the checker's `body` verbatim as the `PLAN` comment; `status: needs_input` -> ask the user the `questions:` (the checker's `fields`), then re-spawn the planner with the answers; never answer them yourself or guess. If `config.plan_review` is on, run **Cross-AI plan review** before Execute: send the plan to external AI CLIs and converge on their concerns. Now that the files/seam are known, run the **undeclared-coupling check** (`../../_shared/teamwork.md`) against in-progress tickets. **Plan to sufficiency:** stop once you can name the steps, seams, and files with confidence, and never re-read a file already read in this planning pass; act when you have enough to plan, rather than re-deriving what the pass already established. **The single exception:** under an accepted `lean` skip (see the Size triage above), produce a short inline plan here instead of the planner subagent, and skip Cross-AI plan review; absent that accepted skip, this step runs in full as described.
|
|
35
|
+
3. **Execute**: the orchestrator runs the HITL and tracker moves around an **executor subagent on `config.models.execute`**; the implementing protocol itself lives in `executor-brief.md` (this directory), the only protocol text the agent receives from this step. The agent cannot ask the user and never writes to the tracker, pushes or creates a branch.
|
|
36
|
+
- **Prototype FIRST (orchestrator).** **If this ticket changes user-facing UI (a new screen, a redesign, a changed layout), run the Prototype technique FIRST, before any real UI code**: surface a mockup to react to (its clickable link always in the same message as the approval question, per the Prototype technique; the guard also accepts a link inside the approval question itself, the prose stays preferred), routed by `config.design` (disk / artifacts / stitch) and gated by `config.design.approval` (`explicit` waits for a go-ahead, `auto` proceeds after surfacing). **Route by `config.design` and never shortcut a hosted mode to a local disk mockup**: when `config.design` is `artifacts` (or the legacy `claude.ai/design`) or `stitch`, the mockup is built there (reusing a cached `design.project`); `disk` is only for `config.design: disk` or the technique's explicit, announced fallback, never a convenience default. Read `config.design` before producing anything. For a redesign or new screen the default is to offer mockups; don't jump straight to code on a UI ticket (full statement in the **Prototype** technique, `../../_shared/techniques/prototype.md`).
|
|
37
|
+
- **Branch and worktree (orchestrator).** Following the repo's `trailhead:conventions` `git:`, straight to `main` by default, or a feature branch + PR when `git: pr` (the orchestrator creates the branch before the spawn and opens the PR; the executor only commits, never pushes, switches branch or writes to the tracker). **Under `isolation: worktree`, the work happens in this ticket's `git worktree`** (`trailhead/t<n>` branch), integrating to the trunk at Resolve (see `../../_shared/teamwork.md`).
|
|
38
|
+
- **Dispatch.** Spawn the **`trailhead-executor`** agent (full tools that can Edit/Write/commit), passing `config.models.execute` as the model override and `executor-brief.md` as the only protocol text, plus the runtime inputs: the ticket number, the PLAN, the base SHA, the `config.tdd` value, the approved mockup link if any, the accepted mockup deviations, and, for a resumed spawn, the packages the user approved. Inline when the model is unset or equals the session model: the session then does both parts. Inline, the session reads `executor-brief.md` and applies it, asking the user directly at the points the brief says to report. The agent implements with **atomic commits** (conventional commits, each with a `Refs: #<n>` trailer for this ticket, see **Principles** in `../../_shared/principles.md`; the trailer is also what scopes Verify's review and goal check, per **Ticket diff** in `../../_shared/techniques/code-review.md`; one commit = one verifiable step); the commits land on `main`, visible.
|
|
39
|
+
- **Fidelity (orchestrator).** The approved mockup is reproduced with **100% fidelity** (layout, spacing, sizing, colour, type, copy, and every state), never a loose approximation. **Make fidelity verifiable, not a hope:** the executor returns the enumerated fidelity list in its report and the orchestrator posts it as a ticket comment (noting any element raised as infeasible with its resolution), so Verify works from a durable checklist instead of reconstructing intent. At Verify, **Acceptance testing** checks the built screen against the approved mockup (element by element, state by state) and **Goal-backward verification** carries fidelity as an explicit goal claim (see `../../_shared/techniques/acceptance-testing.md` and `../../_shared/techniques/verify.md`).
|
|
40
|
+
- **Infeasible element (orchestrator).** When the report marks an element infeasible, raise it with the user and settle it: revise and re-approve the mockup, or the user accepts a named deviation. Then re-spawn the executor with the settled mockup and the accepted deviations; never let it deviate silently.
|
|
41
|
+
- **Flagged package (orchestrator).** The **verify-before-install gate** (slopsquatting barrier) runs in the executor (legitimacy, typosquat similarity, age, downloads, repository metadata). On a flagged package in the report, block-and-ask: stop and ask the user, never installing on your own judgement. Only on an explicit yes, re-spawn the executor with that package passed as user-approved (it then re-runs the exact install command prefixed with `TRAILHEAD_VERIFIED_INSTALL=1`); on a no it is not installed and the plan is revisited with the user. On a host with a hook bus the `trailhead-install-guard` `PreToolUse` hook enforces the gate, blocking a named public-registry install (npm / PyPI / crates.io / Go / RubyGems) until it is vetted.
|
|
42
|
+
- **Surfaced scope (orchestrator).** New scope surfacing mid-execute, reported by the executor in `surfaced scope:`, is captured/split, not worked here.
|
|
43
|
+
- **Report (orchestrator).** Run the report-status check on the agent's report (`--technique executor`, the *Malformed review report* protocol in `../../_shared/techniques.md`) and branch on the checker's `verdict`, reading its `fields`: never reconstruct a result from the prose. `status: done` -> Verify. `status: partial` or `blocked` -> act on each `blockers:` entry with the moves above (flagged package, infeasible element; a foreign change in the way is raised with the user), then re-spawn. Post `fidelity:` as the fidelity comment and route `surfaced scope:` as below. Check `commits:` against the repo: it must equal the `Refs: #<n>` commit set since the base SHA, in both directions, and every SHA must resolve (`git cat-file -e <sha>^{commit}`); a mismatch is surfaced to the user, never patched over.
|
|
44
|
+
4. **Verify**: a `VERIFY` comment: **start with the Stale-base preflight** (`trailhead-base-preflight.js --sync`, **Stale-base preflight** in `../../_shared/teamwork.md`): preflight, then sync, then re-run the tests, all before anything is reviewed (a rebase rewrites SHAs the review ledger cites, and the Code review and goal check must see the synced tree); then run the tests / the plan's criterion; then the **Code review** technique, scoped to the ticket's own commits per its **Ticket diff** rule (`../../_shared/techniques/code-review.md`: the `Refs: #<n>` set, read per commit, recomputed each round, an empty set surfaced as an error, never a `<base>...HEAD` range) (its subagent reviews *adversarially*: it doesn't defer to a `CLAUDE.md` convention or a "settled decision" memory), and carries the review's counts line and findings ledger, per code-review.md, **run in the background and collected by polling, never a blind blocking wait** (a hard engine default on every host, see *Reviews never block the session* in `../../_shared/techniques.md`); run the report-status check before branching on status (each report, from the subagent or inline, goes through the *Malformed review report* protocol in `../../_shared/techniques.md`, which also fixes the layout of the round's single `VERIFY` comment); **read the review's leading `status:` tag to branch deterministically: `status: clean` -> proceed to Resolve, `status: issues_found` -> iterate the fix-and-re-review loop (or run the HITL checkpoint) before resolving**; then the **Goal-backward verification** technique on `config.models.verify` (does the change deliver what the ticket promised, backward from its `Question` and the `PLAN`'s criteria; the read-only `trailhead-verify` subagent, on the same **Ticket diff** set), **run in the background and collected by polling** like Code review, branching on its leading `status:` tag (`status: met` -> proceed, `status: gaps_found` -> loop back to Execute for the gap or run the HITL checkpoint before resolving, `status: inconclusive` as the leading tag (all gaps cleared) -> a per-reason-class HITL checkpoint with no auto-retry, never auto-resolving over the unevaluated goal); then **Acceptance testing** if the change is user-facing, opening with the UAT setup (`trailhead-uat-setup.js`, after the preflight) and then the drive-mode ask (`../../_shared/techniques/acceptance-testing.md`): AI-driven, or **walk the user through a guided UAT conversationally, one step at a time**, never a checklist dumped in a comment (or skip (waive acceptance), recorded as waived, if the user so chooses): interactive by design, so it runs inline, not backgrounded. Report the outcome honestly (if a test fails, say so). **The single exception:** under an accepted `lean` skip, run a lighter inline review pass instead of the full Code-review subagent and a quick inline goal check instead of the full Goal-backward verification subagent (or skip either only when the change is truly cosmetic); the lighter inline review still uses the same finding IDs, counts line, and ledger, and the same no-`open` gate, per code-review.md; the tests / criterion and the honest outcome report still run regardless. At a HITL checkpoint here, an advisory sub-choice (which fix, how to proceed) **offers** the delegate option, per the injection recipe in `../../_shared/choices.md`; the accept/resolve decision stays the human's.
|
|
45
|
+
5. **Resolve**: a resolution comment with what was done → `gh issue close` → update `Decisions so far` on the map (default path: `node <templates>/trailhead-issue-body.js append --issue <map> --section "Decisions so far" --line "<pointer>"`, a body read-modify-write that obeys the **Fail-safe body rewrites** rule in `../../_shared/substrate.md` for you; `<templates>` is the same three-dir lookup as for `trailhead-work-state.js` (**Work state file** in `../../_shared/teamwork.md`); when the helper is missing, do the read-modify-write by hand per that rule). **Disposition gate (before the close)**: the latest `VERIFY` comment's findings ledger covers every finding the counts line counts and none of them is `open`; the resolution comment links that ledger rather than duplicating it; otherwise do not `gh issue close` (per code-review.md's Disposition gate). **Stale-base preflight (before integrating).** Run the preflight per **Stale-base preflight** in `../../_shared/teamwork.md` (`git: main`: right before the trunk push; `git: pr` without isolation: on the ticket branch, immediately before the push and PR; `worktree`/`clone`: on the main checkout, then on the ticket branch) and integrate only on `current`/`synced` with the tests green and `checksOk`. **Pending-UAT guard (before the close).** If Verify left acceptance testing **not yet run** (it would otherwise be deferred), **pose the two-way choice to the user and wait for an explicit answer, never open a ticket unilaterally**: (a) run the UAT now, in this session, with no ticket (the stale-base preflight first, then the UAT setup, then the drive-mode ask, `../../_shared/techniques/acceptance-testing.md`), or (b) open a UAT follow-up ticket to run it later. On (a), run the guided walkthrough now and resolve on a confirmed pass, or on an explicit waiver if the user skips at the ask (recorded as unconfirmed; the resolution comment states it) (a failing step becomes a fix or a `bug` follow-up and an incomplete/blocked step is marked pending and tracked, per the guided-UAT rules in `../../_shared/techniques/acceptance-testing.md`, not a silent close); on (b), **open the follow-up ticket carrying the owed UAT first**, linked back to this parent (a `task` on the frontier or a `trailhead:seed` gated on the run, per *Pending UAT must stay tracked* in `../../_shared/techniques/acceptance-testing.md`). **Never open a UAT ticket without asking, never `gh issue close` on a chosen-deferred UAT with nothing opened, and never let silence or an ambiguous reply default to either path.** When acceptance was already completed at Verify, or was **explicitly waived** by the user at the drive-mode ask (a waiver is not a deferral: nothing is owed, so nothing is opened; the resolution comment states the waiver), this guard doesn't fire. **Post-commit self-check (before the comment goes out).** For each commit the comment cites, confirm the hash resolves (`git cat-file -e <hash>^{commit}`, or `git show --stat <hash>`) and that every file the comment names as touched actually appears in that commit's diff (`git -c core.quotepath=false show --name-only --format= <hash>`, with `core.quotepath=false` so a non-ASCII filename compares plainly instead of in git's C-quoted form); correct or drop any citation that fails the check, so a hallucinated or mis-stated commit never lands in the tracker record. **If this change materially altered the codebase** (a new module/layer, dependency, seam, or build/test command), **patch the affected facet of the `trailhead:codebase` issue** (see **Codebase** in `../../_shared/substrate.md`) in place (a line or two, not a re-map). When a structural event is due (a whiteboard ticket resolved, a map exhausted), refresh the dashboard with `node <templates>/trailhead-dashboard.js` (one call, whole body from the live tracker; by hand per `../../_shared/substrate-commands.md` when the helper is missing). Then close the session with the **Session handoff** ritual (`../../_shared/session-handoff.md`): one `node <templates>/trailhead-work-state.js clear --repo <working-root>` removes the work state and the session-ticket marker, then `/clear` + next command.
|
|
36
46
|
|
|
37
47
|
New scope that surfaces mid-build (while planning, executing, or testing) → **capture or split, never expand this ticket in flight** (see **Scope that surfaces while working a ticket**, served by the capture cluster). If the user defers that in-the-moment choice rather than settling it, mark the follow-up **pending** so the **Pending follow-up guard** re-poses it at handoff (`../../_shared/session-handoff.md`), instead of losing it to scrollback.
|
|
38
48
|
|
|
@@ -48,10 +58,18 @@ Then run the cycle, all in ticket comments:
|
|
|
48
58
|
**Size triage (`effort`-gated).** Under `config.effort: lean`, run the **size triage and ask-to-skip offer defined canonically under effort in `../../_shared/configuration-reference.md`**, classifying the fix as in the `build` engine. On trivial/small, offer to skip only the *heavy verification* a tiny fix does not warrant: lighten or skip **TDD**, run a **lighter inline Code review** instead of the full subagent, and a **quick inline goal check** instead of the full **Goal-backward verification** subagent, going lean **only on an explicit yes**. **Diagnose is never in the offer**: a bug always needs a confirmed root cause before Fix, whatever its size. On a no/silence/ambiguity, and under `effort: standard` (default), the full cycle runs.
|
|
49
59
|
|
|
50
60
|
1. **Repro**: a `REPRO` comment: how to reproduce, expected vs observed behaviour.
|
|
51
|
-
2. **Diagnose**: run the **Debug** technique. A `DIAGNOSIS` comment with the root cause **stated as a falsifiable hypothesis plus the falsification test that confirmed it**. **Pre-fix checkpoint: only a confirmed cause proceeds to Fix** (a cause that has not survived its falsification test stays in diagnosis, looping the hypothesis steps); the full gate lives in the **Debug** technique (`../../_shared/techniques/debug.md`).
|
|
52
|
-
3. **Fix**:
|
|
53
|
-
|
|
54
|
-
|
|
61
|
+
2. **Diagnose**: run the **Debug** technique. Dispatch `trailhead-debug` and run the report-status check on its report (`--technique debug`, the *Malformed review report* protocol in `../../_shared/techniques.md`); branch on the checker's `verdict`, reading its `fields`: `status: found` -> its `answer:` (the cause) and `evidence:` (the falsification test and its result) feed the `DIAGNOSIS`; `status: inconclusive` -> the ticket stays in diagnosis, next hypotheses, never on to Fix; `status: needs_input` -> ask the user the `open questions:`, then re-spawn with the answers. A `DIAGNOSIS` comment with the root cause **stated as a falsifiable hypothesis plus the falsification test that confirmed it**. **Pre-fix checkpoint: only a confirmed cause proceeds to Fix** (a cause that has not survived its falsification test stays in diagnosis, looping the hypothesis steps); the full gate lives in the **Debug** technique (`../../_shared/techniques/debug.md`).
|
|
62
|
+
3. **Fix**: the orchestrator runs the HITL and tracker moves around an **executor subagent on `config.models.execute`**; the implementing protocol itself lives in `executor-brief.md` (this directory), the only protocol text the agent receives from this step. The agent cannot ask the user and never writes to the tracker, pushes or creates a branch.
|
|
63
|
+
- **Dispatch.** Spawn the **`trailhead-fix`** agent (full tools), passing `config.models.execute` as the model override and `executor-brief.md` as the only protocol text, plus the runtime inputs: the ticket number, the base SHA, the confirmed `DIAGNOSIS`, the `config.tdd` value, the approved mockup link if any, the accepted mockup deviations, and, for a resumed spawn, the packages the user approved. Inline when unset/same as session: the session then does both parts. Inline, the session reads `executor-brief.md` and applies it, asking the user directly at the points the brief says to report. The agent implements the correction with **atomic commits** (each with a `Refs: #<n>` trailer for this ticket, see **Principles** in `../../_shared/principles.md`; the trailer is also what scopes Verify's review and goal check, per **Ticket diff** in `../../_shared/techniques/code-review.md`), and where sensible a test that fails before and passes after (**TDD**).
|
|
64
|
+
- **Branch and worktree (orchestrator).** Per the repo's `trailhead:conventions` `git:`, `main` by default, else a branch + PR: the orchestrator creates the branch before the spawn and opens the PR under `git: pr`; the agent only commits. Under `isolation: worktree`, the work happens in this ticket's `git worktree`.
|
|
65
|
+
- **UI fix: Prototype and approval (orchestrator).** Where the fix changes a screen (a user-facing UI fix), run the Prototype technique FIRST, before any real UI code: surface a mockup, routed by `config.design` (never shortcut a hosted mode to a local disk mockup) and gated by `config.design.approval`, per the technique (`../../_shared/techniques/prototype.md`). Once approved, the executor reproduces it with 100% fidelity.
|
|
66
|
+
- **Fidelity (orchestrator).** The executor returns the enumerated fidelity list in its report and the orchestrator posts it as a ticket comment, so Verify (Acceptance testing and Goal-backward verification) checks against a durable list.
|
|
67
|
+
- **Infeasible element (orchestrator).** When the report marks an element infeasible, raise it with the user and settle it: revise and re-approve the mockup, or the user accepts a named deviation; then re-spawn the executor with the settled mockup and the accepted deviations.
|
|
68
|
+
- **Flagged package (orchestrator).** The **verify-before-install gate** runs in the executor (typosquat similarity, age, downloads, repository metadata). On a flagged package in the report, block-and-ask: stop and ask the user before anything is installed. Only on an explicit yes, re-spawn the executor with that package passed as user-approved; on a no it is not installed and the plan is revisited with the user.
|
|
69
|
+
- **Surfaced scope (orchestrator).** New scope the executor reports in `surfaced scope:` is captured/split, never worked in this ticket.
|
|
70
|
+
- **Report (orchestrator).** Run the report-status check on the agent's report (`--technique fix`, the *Malformed review report* protocol in `../../_shared/techniques.md`) and branch on the checker's `verdict`, reading its `fields`: never reconstruct a result from the prose. `status: done` -> Verify. `status: partial` or `blocked` -> act on each `blockers:` entry with the moves above (flagged package, infeasible element; a foreign change in the way is raised with the user), then re-spawn. Post `fidelity:` as the fidelity comment and route `surfaced scope:` as below. Check `commits:` against the repo: it must equal the `Refs: #<n>` commit set since the base SHA, in both directions, and every SHA must resolve (`git cat-file -e <sha>^{commit}`); a mismatch is surfaced to the user, never patched over.
|
|
71
|
+
4. **Verify**: a `VERIFY` comment: **start with the Stale-base preflight** (`trailhead-base-preflight.js --sync`, **Stale-base preflight** in `../../_shared/teamwork.md`): preflight, then sync, then re-run the tests, all before anything is reviewed (a rebase rewrites SHAs the review ledger cites, and the Code review and goal check must see the synced tree); then the repro now passes, no regressions; **Code review** on the fix, scoped to the ticket's own commits per its **Ticket diff** rule (`../../_shared/techniques/code-review.md`: the `Refs: #<n>` set, read per commit, recomputed each round, an empty set surfaced as an error, never a `<base>...HEAD` range), and carries the review's counts line and findings ledger, per code-review.md, **run in the background and collected by polling, never a blind blocking wait** (a hard engine default on every host, see *Reviews never block the session* in `../../_shared/techniques.md`); run the report-status check before branching on status (each report, from the subagent or inline, goes through the *Malformed review report* protocol in `../../_shared/techniques.md`, which also fixes the layout of the round's single `VERIFY` comment); **read the review's leading `status:` tag to branch deterministically (`status: clean` -> Resolve, `status: issues_found` -> iterate the loop or run the checkpoint first)**; then the **Goal-backward verification** technique on `config.models.verify` (does the fix deliver what the ticket promised, backward from its `Question`; the read-only `trailhead-verify` subagent, on the same **Ticket diff** set), background and collected by polling, branching on its leading `status:` tag (`status: met` -> proceed, `status: gaps_found` -> loop back to Fix for the gap or run the checkpoint, `status: inconclusive` as the leading tag (all gaps cleared) -> a per-reason-class HITL checkpoint with no auto-retry, never auto-resolving over the unevaluated goal); **Acceptance testing** if the bug was user-facing, opening with the UAT setup (`trailhead-uat-setup.js`, after the preflight) and then the drive-mode ask (`../../_shared/techniques/acceptance-testing.md`): AI-driven, or **walk the user through a guided UAT conversationally, step by step**, not a checklist to self-serve (or skip (waive acceptance), recorded as waived, if the user so chooses): interactive by design, so it runs inline, not backgrounded. At a HITL checkpoint here, an advisory sub-choice (which fix, how to proceed) **offers** the delegate option, per the injection recipe in `../../_shared/choices.md`; the accept/resolve decision stays the human's.
|
|
72
|
+
5. **Resolve**: a resolution comment (cause + fix) → `gh issue close` → update `Decisions so far` (default path: `node <templates>/trailhead-issue-body.js append --issue <map> --section "Decisions so far" --line "<pointer>"`, same helper and fallback as the `build` Resolve step; a body read-modify-write that obeys the **Fail-safe body rewrites** rule in `../../_shared/substrate.md`). **Disposition gate (before the close)**: the latest `VERIFY` comment's findings ledger covers every finding the counts line counts and none of them is `open`; the resolution comment links that ledger rather than duplicating it; otherwise do not `gh issue close` (per code-review.md's Disposition gate). **Stale-base preflight (before integrating).** Run the preflight per **Stale-base preflight** in `../../_shared/teamwork.md` (`git: main`: right before the trunk push; `git: pr` without isolation: on the ticket branch, immediately before the push and PR; `worktree`/`clone`: on the main checkout, then on the ticket branch) and integrate only on `current`/`synced` with the tests green and `checksOk`. **Pending-UAT guard (before the close).** If Verify left acceptance testing **not yet run** (it would otherwise be deferred), **pose the two-way choice to the user and wait for an explicit answer, never open a ticket unilaterally**: (a) run the UAT now, in this session, with no ticket (the stale-base preflight first, then the UAT setup, then the drive-mode ask, `../../_shared/techniques/acceptance-testing.md`), or (b) open a UAT follow-up ticket to run it later. On (a), run the guided walkthrough now and resolve on a confirmed pass, or on an explicit waiver if the user skips at the ask (recorded as unconfirmed; the resolution comment states it) (a failing step becomes a fix or a `bug` follow-up and an incomplete/blocked step is marked pending and tracked, per the guided-UAT rules in `../../_shared/techniques/acceptance-testing.md`, not a silent close); on (b), **open the follow-up ticket carrying the owed UAT first**, linked back to this parent (a `task` on the frontier or a `trailhead:seed` gated on the run, per *Pending UAT must stay tracked* in `../../_shared/techniques/acceptance-testing.md`). **Never open a UAT ticket without asking, never `gh issue close` on a chosen-deferred UAT with nothing opened, and never let silence or an ambiguous reply default to either path.** When acceptance was already completed at Verify, or was **explicitly waived** by the user at the drive-mode ask (a waiver is not a deferral: nothing is owed, so nothing is opened; the resolution comment states the waiver), this guard doesn't fire. **Run the post-commit self-check before posting, exactly as in the `build` Resolve step** (each cited hash resolves and the files it names appear in that commit's diff; correct or drop any citation that fails). **If the fix materially altered the codebase**, patch the affected facet of the `trailhead:codebase` issue (see **Codebase** in `../../_shared/substrate.md`; also a body read-modify-write, same **Fail-safe body rewrites** rule) in place (a line or two; the same `trailhead-issue-body.js` helper does it with `--section "<facet>"`). When a structural event is due, refresh the dashboard with `node <templates>/trailhead-dashboard.js`. Then close the session with the **Session handoff** ritual (`../../_shared/session-handoff.md`): one `node <templates>/trailhead-work-state.js clear --repo <working-root>` removes the work state and the session-ticket marker, then `/clear` + next command.
|
|
55
73
|
|
|
56
74
|
A **blocking** bug that halts other work is worked immediately; an isolated one is a normal frontier ticket. New scope surfacing while fixing → capture or split, never expand this ticket in flight (see **Scope that surfaces while working a ticket**). A follow-up raised but left unopened is carried to the **Pending follow-up guard** at handoff (`../../_shared/session-handoff.md`), re-posed at Resolve rather than dropped.
|
|
57
75
|
|
|
@@ -0,0 +1,305 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
'use strict';
|
|
3
|
+
// trailhead base preflight (self-contained, ships in templates/ so it reaches every
|
|
4
|
+
// install channel: bin/trailhead.js copies templates/ wholesale for Claude/npm
|
|
5
|
+
// and Codex). Measures how far the working base is behind the trunk, optionally
|
|
6
|
+
// syncs it, and runs the project's own preflight checks. #243.
|
|
7
|
+
//
|
|
8
|
+
// CLI:
|
|
9
|
+
// node trailhead-base-preflight.js --repo <working-root> [--config-root <project-root>]
|
|
10
|
+
// [--trunk <name>] [--sync] [--no-fetch]
|
|
11
|
+
// --config-root is the original checkout the effective config was loaded from
|
|
12
|
+
// (defaults to --repo); a worktree/clone workspace never re-resolves config.
|
|
13
|
+
//
|
|
14
|
+
// Trunk: --trunk, else the remote default branch (refs/remotes/origin/HEAD), else
|
|
15
|
+
// the first existing of main / master; none found -> status skipped.
|
|
16
|
+
// Fetch: an explicit destination refspec so origin/<trunk> really advances. A
|
|
17
|
+
// failed fetch is never tolerated silently: status unverified (distance on local refs).
|
|
18
|
+
// Base (one ref, deterministic): no remote ref -> local <trunk>; HEAD is the trunk ->
|
|
19
|
+
// origin/<trunk>; HEAD on a ticket branch -> origin/<trunk> unless the local trunk is
|
|
20
|
+
// strictly ahead (then the local trunk); both moved -> status trunk-diverged.
|
|
21
|
+
// Sync (--sync, only when behind): refuses a dirty tracked tree (dirty); on the trunk
|
|
22
|
+
// ff-only (rebase --rebase-merges when it has diverged, merge commits are kept); on a ticket branch rebase when unpublished,
|
|
23
|
+
// merge when it has an upstream. Any failed sync is aborted and HEAD verified back at
|
|
24
|
+
// its pre-sync commit: conflict (paths listed) or sync-failed (git's message).
|
|
25
|
+
// Checks: `preflight.checks` (array of shell commands), nested ({"preflight":
|
|
26
|
+
// {"checks":[...]}}) or flat ({"preflight.checks":[...]}); nested wins when a file
|
|
27
|
+
// carries both. The project file (read from --config-root) wins over the global one
|
|
28
|
+
// (${CLAUDE_CONFIG_DIR:-~/.claude}/trailhead/config.json) as a whole value. Each
|
|
29
|
+
// command runs with `sh -c` at --repo after any sync. Not run on unverified,
|
|
30
|
+
// trunk-diverged, error, conflict, dirty, sync-failed.
|
|
31
|
+
// Prints one JSON line:
|
|
32
|
+
// {"status","trunk","base","behind","ahead","method"?,"pulled"?,"testsRequired",
|
|
33
|
+
// "conflicts":[],"checks":[{command,ok,code,output}],"checksOk","checksError"?,"warnings":[],"message"?}
|
|
34
|
+
// status: current | behind | synced | unverified | trunk-diverged | dirty | conflict |
|
|
35
|
+
// sync-failed | error | skipped
|
|
36
|
+
// Fail closed: only current and synced (with checksOk) let the caller go on.
|
|
37
|
+
// Exit 0 whenever a JSON line is printed; exit 2 only on a usage error.
|
|
38
|
+
|
|
39
|
+
const fs = require('fs');
|
|
40
|
+
const os = require('os');
|
|
41
|
+
const path = require('path');
|
|
42
|
+
const { spawnSync } = require('child_process');
|
|
43
|
+
|
|
44
|
+
const CONFIG_REL = path.join('.trailhead', 'config.json');
|
|
45
|
+
const CHECK_TIMEOUT_MS = 300000;
|
|
46
|
+
const OUTPUT_TAIL = 2000;
|
|
47
|
+
const FLAGS = ['sync', 'no-fetch'];
|
|
48
|
+
const VALUED = ['repo', 'config-root', 'trunk'];
|
|
49
|
+
|
|
50
|
+
function parseArgs(argv) {
|
|
51
|
+
const out = {};
|
|
52
|
+
for (let i = 0; i < argv.length; i++) {
|
|
53
|
+
const a = argv[i];
|
|
54
|
+
const name = a.startsWith('--') ? a.slice(2) : null;
|
|
55
|
+
if (name && VALUED.includes(name)) {
|
|
56
|
+
const v = argv[++i];
|
|
57
|
+
if (v === undefined || v.startsWith('--')) return { error: `usage: ${a} needs a value` };
|
|
58
|
+
out[name] = v;
|
|
59
|
+
} else if (name && FLAGS.includes(name)) {
|
|
60
|
+
out[name] = true;
|
|
61
|
+
} else {
|
|
62
|
+
return { error: `usage: unknown argument ${a}` };
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
if (!out.repo) return { error: 'usage: missing --repo <working-root>' };
|
|
66
|
+
return out;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// Reads preflight.checks out of one config file.
|
|
70
|
+
// { state: 'unset' } | { state: 'set', list, warnings } | { state: 'invalid', message }
|
|
71
|
+
function readChecks(file, fs_) {
|
|
72
|
+
let text;
|
|
73
|
+
try {
|
|
74
|
+
text = fs_.readFileSync(file, 'utf8');
|
|
75
|
+
} catch (err) {
|
|
76
|
+
if (err && err.code === 'ENOENT') return { state: 'unset' };
|
|
77
|
+
return { state: 'invalid', message: `cannot read ${file}: ${err && err.message ? err.message : err}` };
|
|
78
|
+
}
|
|
79
|
+
let cfg;
|
|
80
|
+
try {
|
|
81
|
+
cfg = JSON.parse(text);
|
|
82
|
+
} catch (err) {
|
|
83
|
+
return { state: 'invalid', message: `${file} is not valid JSON` };
|
|
84
|
+
}
|
|
85
|
+
if (cfg === null || typeof cfg !== 'object' || Array.isArray(cfg)) {
|
|
86
|
+
return { state: 'invalid', message: `${file} is not a JSON object` };
|
|
87
|
+
}
|
|
88
|
+
const has = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
|
|
89
|
+
const nested = cfg.preflight !== null && typeof cfg.preflight === 'object' && !Array.isArray(cfg.preflight) && has(cfg.preflight, 'checks');
|
|
90
|
+
const flat = has(cfg, 'preflight.checks');
|
|
91
|
+
if (!nested && !flat) return { state: 'unset' };
|
|
92
|
+
const warnings = [];
|
|
93
|
+
if (nested && flat) warnings.push(`${file} sets preflight.checks in both nested and flat form; the nested form wins`);
|
|
94
|
+
const value = nested ? cfg.preflight.checks : cfg['preflight.checks'];
|
|
95
|
+
if (!Array.isArray(value)) return { state: 'invalid', message: `preflight.checks in ${file} must be an array of shell commands` };
|
|
96
|
+
if (value.some((e) => typeof e !== 'string' || e.trim() === '')) {
|
|
97
|
+
return { state: 'invalid', message: `preflight.checks in ${file} must hold only non-empty strings` };
|
|
98
|
+
}
|
|
99
|
+
return { state: 'set', list: value, warnings };
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function globalConfigPath(env) {
|
|
103
|
+
const base = env.CLAUDE_CONFIG_DIR || path.join(env.HOME || os.homedir(), '.claude');
|
|
104
|
+
return path.join(base, 'trailhead', 'config.json');
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function tail(text) {
|
|
108
|
+
const t = String(text || '');
|
|
109
|
+
return t.length > OUTPUT_TAIL ? '...' + t.slice(t.length - OUTPUT_TAIL) : t;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// Runs git at `repo`; never throws on a non-zero exit.
|
|
113
|
+
function makeGit(repo, env) {
|
|
114
|
+
const gitEnv = { ...process.env, ...env, GIT_EDITOR: 'true', GIT_TERMINAL_PROMPT: '0' };
|
|
115
|
+
const G = (args) => {
|
|
116
|
+
const r = spawnSync('git', ['-C', repo, ...args], { encoding: 'utf8', env: gitEnv, maxBuffer: 64 * 1024 * 1024 });
|
|
117
|
+
if (r.error) throw r.error;
|
|
118
|
+
const res = { ok: r.status === 0, out: (r.stdout || '').trim(), err: (r.stderr || '').trim() };
|
|
119
|
+
G.last = res;
|
|
120
|
+
return res;
|
|
121
|
+
};
|
|
122
|
+
return G;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function detectTrunk(requested, G) {
|
|
126
|
+
if (requested) return requested;
|
|
127
|
+
const head = G(['symbolic-ref', '-q', '--short', 'refs/remotes/origin/HEAD']);
|
|
128
|
+
if (head.ok && head.out.startsWith('origin/')) return head.out.slice('origin/'.length);
|
|
129
|
+
for (const name of ['main', 'master']) {
|
|
130
|
+
if (G(['show-ref', '--verify', '-q', `refs/heads/${name}`]).ok || G(['show-ref', '--verify', '-q', `refs/remotes/origin/${name}`]).ok) return name;
|
|
131
|
+
}
|
|
132
|
+
return null;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// Commit count of a range; null when git fails (the caller reports the error, never a 0).
|
|
136
|
+
const count = (G, range) => {
|
|
137
|
+
const r = G(['rev-list', '--count', range]);
|
|
138
|
+
const n = Number(r.out);
|
|
139
|
+
return r.ok && r.out !== '' && Number.isInteger(n) ? n : null;
|
|
140
|
+
};
|
|
141
|
+
|
|
142
|
+
const gitFailure = (G, what) => `${what}: ${(G.last && (G.last.err || G.last.out)) || 'git failed'}`;
|
|
143
|
+
|
|
144
|
+
// Picks the one base ref. { base, diverged } or { error } when a comparison fails.
|
|
145
|
+
function pickBase(G, trunk, head, hasLocal, hasRemote) {
|
|
146
|
+
const remote = `origin/${trunk}`;
|
|
147
|
+
if (!hasRemote) return { base: trunk, diverged: false };
|
|
148
|
+
if (!hasLocal || head === trunk) return { base: remote, diverged: false };
|
|
149
|
+
const what = `cannot compare ${trunk} with ${remote}`;
|
|
150
|
+
const localBehind = count(G, `${trunk}..${remote}`);
|
|
151
|
+
if (localBehind === null) return { error: gitFailure(G, what) };
|
|
152
|
+
const localAhead = count(G, `${remote}..${trunk}`);
|
|
153
|
+
if (localAhead === null) return { error: gitFailure(G, what) };
|
|
154
|
+
if (localBehind > 0 && localAhead > 0) return { base: remote, diverged: true };
|
|
155
|
+
return { base: localAhead > 0 ? trunk : remote, diverged: false };
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
// Puts HEAD and the tree back at `pre` after a failed sync.
|
|
159
|
+
function restore(G, pre, warnings) {
|
|
160
|
+
G(['rebase', '--abort']);
|
|
161
|
+
G(['merge', '--abort']);
|
|
162
|
+
if (G(['rev-parse', 'HEAD']).out !== pre) {
|
|
163
|
+
G(['reset', '--hard', pre]);
|
|
164
|
+
warnings.push('the failed sync left HEAD moved; it was reset to the pre-sync commit');
|
|
165
|
+
}
|
|
166
|
+
const back = G(['rev-parse', 'HEAD']).out === pre && G(['status', '--porcelain', '--untracked-files=no']).out === '';
|
|
167
|
+
if (!back) warnings.push('could not verify the tree is back at its pre-sync state; inspect it before going on');
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// Syncs the working base onto `base`. Returns fields for the result.
|
|
171
|
+
function sync(G, { trunk, head, base, ahead, behind, warnings }) {
|
|
172
|
+
if (G(['status', '--porcelain', '--untracked-files=no']).out !== '') {
|
|
173
|
+
return { status: 'dirty', message: 'tracked changes in the working tree; commit or stash them before syncing' };
|
|
174
|
+
}
|
|
175
|
+
if (!head) return { status: 'sync-failed', message: 'detached HEAD: nothing to sync' };
|
|
176
|
+
const pre = G(['rev-parse', 'HEAD']).out;
|
|
177
|
+
let method;
|
|
178
|
+
let r;
|
|
179
|
+
if (head === trunk) {
|
|
180
|
+
method = ahead === 0 ? 'ff' : 'rebase';
|
|
181
|
+
r = method === 'ff' ? G(['merge', '--ff-only', '-q', base]) : G(['rebase', '-q', '--rebase-merges', base]);
|
|
182
|
+
} else if (G(['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{u}']).ok) {
|
|
183
|
+
method = 'merge';
|
|
184
|
+
r = G(['merge', '--no-edit', '-q', base]);
|
|
185
|
+
} else {
|
|
186
|
+
method = 'rebase';
|
|
187
|
+
r = G(['rebase', '-q', '--rebase-merges', base]);
|
|
188
|
+
}
|
|
189
|
+
if (r.ok) return { status: 'synced', method, pulled: behind, testsRequired: true };
|
|
190
|
+
const conflicts = G(['diff', '--name-only', '--diff-filter=U']).out.split('\n').filter(Boolean);
|
|
191
|
+
restore(G, pre, warnings);
|
|
192
|
+
if (conflicts.length > 0) return { status: 'conflict', method, conflicts, message: `${method} onto ${base} conflicts; aborted, the tree is unchanged` };
|
|
193
|
+
return { status: 'sync-failed', method, message: r.err || r.out || `${method} failed` };
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
function runChecks(list, repo, env) {
|
|
197
|
+
const results = list.map((command) => {
|
|
198
|
+
const r = spawnSync('sh', ['-c', command], { cwd: repo, encoding: 'utf8', env: { ...process.env, ...env }, timeout: CHECK_TIMEOUT_MS, maxBuffer: 16 * 1024 * 1024 });
|
|
199
|
+
const timedOut = r.error && r.error.code === 'ETIMEDOUT';
|
|
200
|
+
const output = (r.stdout || '') + (r.stderr || '') + (timedOut ? `\n(timed out after ${CHECK_TIMEOUT_MS / 1000}s)` : r.error && !timedOut ? `\n${r.error.message}` : '');
|
|
201
|
+
return { command, ok: r.status === 0, code: r.status, output: tail(output) };
|
|
202
|
+
});
|
|
203
|
+
return results;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
const NO_CHECKS = new Set(['unverified', 'trunk-diverged', 'error', 'skipped', 'conflict', 'dirty', 'sync-failed']);
|
|
207
|
+
|
|
208
|
+
function preflight(parsed, cwd, env, fs_) {
|
|
209
|
+
const repo = path.resolve(cwd, parsed.repo);
|
|
210
|
+
const configRoot = path.resolve(cwd, parsed['config-root'] || parsed.repo);
|
|
211
|
+
const G = makeGit(repo, env);
|
|
212
|
+
const warnings = [];
|
|
213
|
+
const result = { status: 'error', trunk: null, base: null, behind: 0, ahead: 0, testsRequired: false, conflicts: [], checks: [], checksOk: false, warnings };
|
|
214
|
+
|
|
215
|
+
if (!G(['rev-parse', '--git-dir']).ok) return { ...result, message: `${repo} is not a git repository` };
|
|
216
|
+
const trunk = detectTrunk(parsed.trunk, G);
|
|
217
|
+
if (!trunk) return { ...result, status: 'skipped', message: 'no trunk found (no remote default branch, main or master)' };
|
|
218
|
+
result.trunk = trunk;
|
|
219
|
+
|
|
220
|
+
let fetchFailed = false;
|
|
221
|
+
const hasOrigin = G(['remote', 'get-url', 'origin']).ok;
|
|
222
|
+
if (!hasOrigin) {
|
|
223
|
+
const remotes = G(['remote']).out.split('\n').filter(Boolean);
|
|
224
|
+
if (remotes.length > 0) warnings.push(`no remote named origin (found: ${remotes.join(', ')}); distance measured on local refs`);
|
|
225
|
+
}
|
|
226
|
+
if (hasOrigin && !parsed['no-fetch']) {
|
|
227
|
+
const f = G(['fetch', '--quiet', 'origin', `+refs/heads/${trunk}:refs/remotes/origin/${trunk}`]);
|
|
228
|
+
if (!f.ok) {
|
|
229
|
+
fetchFailed = true;
|
|
230
|
+
warnings.push(`fetch of origin/${trunk} failed, distance measured on local refs: ${f.err || 'unknown error'}`);
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
if (parsed['no-fetch']) warnings.push('--no-fetch: distance measured on local refs');
|
|
234
|
+
|
|
235
|
+
const hasLocal = G(['show-ref', '--verify', '-q', `refs/heads/${trunk}`]).ok;
|
|
236
|
+
const hasRemote = G(['show-ref', '--verify', '-q', `refs/remotes/origin/${trunk}`]).ok;
|
|
237
|
+
if (!hasLocal && !hasRemote) return { ...result, status: 'skipped', message: `trunk ${trunk} has no local or remote ref` };
|
|
238
|
+
const headName = G(['symbolic-ref', '-q', '--short', 'HEAD']);
|
|
239
|
+
const head = headName.ok ? headName.out : null;
|
|
240
|
+
const picked = pickBase(G, trunk, head, hasLocal, hasRemote);
|
|
241
|
+
if (picked.error) return { ...result, message: picked.error };
|
|
242
|
+
result.base = picked.base;
|
|
243
|
+
const behind = count(G, `HEAD..${picked.base}`);
|
|
244
|
+
const ahead = behind === null ? null : count(G, `${picked.base}..HEAD`);
|
|
245
|
+
if (behind === null || ahead === null) return { ...result, message: gitFailure(G, `cannot measure HEAD against ${picked.base}`) };
|
|
246
|
+
result.behind = behind;
|
|
247
|
+
result.ahead = ahead;
|
|
248
|
+
result.status = fetchFailed ? 'unverified' : picked.diverged ? 'trunk-diverged' : result.behind > 0 ? 'behind' : 'current';
|
|
249
|
+
if (fetchFailed) result.message = `could not fetch origin/${trunk}; the distance is not verified`;
|
|
250
|
+
if (picked.diverged) result.message = `local ${trunk} and origin/${trunk} have diverged; reconcile the trunk first`;
|
|
251
|
+
|
|
252
|
+
if (parsed.sync && result.status === 'behind') {
|
|
253
|
+
const s = sync(G, { trunk, head, base: picked.base, ahead: result.ahead, behind: result.behind, warnings });
|
|
254
|
+
Object.assign(result, s);
|
|
255
|
+
if (s.status === 'synced') {
|
|
256
|
+
// The sync succeeded; a failed recount is reported, never turned into a 0.
|
|
257
|
+
result.behind = count(G, `HEAD..${picked.base}`);
|
|
258
|
+
result.ahead = count(G, `${picked.base}..HEAD`);
|
|
259
|
+
if (result.behind === null || result.ahead === null) warnings.push(gitFailure(G, `cannot recount HEAD against ${picked.base} after the sync`));
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
if (!NO_CHECKS.has(result.status)) {
|
|
264
|
+
let cfg = readChecks(path.join(configRoot, CONFIG_REL), fs_);
|
|
265
|
+
if (cfg.state === 'unset') cfg = readChecks(globalConfigPath(env), fs_);
|
|
266
|
+
if (cfg.state === 'invalid') {
|
|
267
|
+
result.checksError = cfg.message;
|
|
268
|
+
} else {
|
|
269
|
+
if (cfg.state === 'set') {
|
|
270
|
+
warnings.push(...cfg.warnings);
|
|
271
|
+
result.checks = runChecks(cfg.list, repo, env);
|
|
272
|
+
}
|
|
273
|
+
result.checksOk = result.checks.every((c) => c.ok);
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
return result;
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
function main(argv, { cwd, stdout, env, fs: fsMod } = {}) {
|
|
280
|
+
const cwd_ = cwd || process.cwd();
|
|
281
|
+
const out = stdout || process.stdout;
|
|
282
|
+
const env_ = env || process.env;
|
|
283
|
+
const fs_ = fsMod || fs;
|
|
284
|
+
|
|
285
|
+
const parsed = parseArgs(argv || []);
|
|
286
|
+
if (parsed.error) {
|
|
287
|
+
process.stderr.write(parsed.error + '\n');
|
|
288
|
+
return 2;
|
|
289
|
+
}
|
|
290
|
+
let result;
|
|
291
|
+
try {
|
|
292
|
+
result = preflight(parsed, cwd_, env_, fs_);
|
|
293
|
+
} catch (err) {
|
|
294
|
+
result = { status: 'error', trunk: null, base: null, behind: 0, ahead: 0, testsRequired: false, conflicts: [], checks: [], checksOk: false, warnings: [], message: 'error: ' + (err && err.message ? err.message : String(err)) };
|
|
295
|
+
}
|
|
296
|
+
out.write(JSON.stringify(result) + '\n');
|
|
297
|
+
return 0;
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
module.exports = { parseArgs, readChecks, main };
|
|
301
|
+
|
|
302
|
+
if (require.main === module) {
|
|
303
|
+
const code = main(process.argv.slice(2), { cwd: process.cwd(), stdout: process.stdout, env: process.env });
|
|
304
|
+
process.exit(code);
|
|
305
|
+
}
|