rungate 0.7.0 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/gates/.gate-salt +1 -0
  2. package/gates/SCHEMA-GUIDE.md +485 -0
  3. package/gates/ac-quality.test.ts +106 -0
  4. package/gates/adversarial.test.ts +283 -0
  5. package/gates/brief-assembler.test.ts +487 -0
  6. package/gates/brief-assembler.ts +448 -0
  7. package/gates/bunfig.toml +2 -0
  8. package/gates/chain.test.ts +91 -0
  9. package/gates/e2e-smoke.test.ts +234 -0
  10. package/gates/error-classifier.test.ts +250 -0
  11. package/gates/error-classifier.ts +99 -0
  12. package/gates/gate-executor.ts +3071 -0
  13. package/gates/orchestrator.test.ts +968 -0
  14. package/gates/orchestrator.ts +827 -0
  15. package/gates/preload.ts +89 -0
  16. package/gates/prompts/ac-adversary.md +20 -0
  17. package/gates/prompts/evidence-validator.md +22 -0
  18. package/gates/prompts/prove-reproducer.md +53 -0
  19. package/gates/prompts.sha256 +3 -0
  20. package/gates/prove.test.ts +164 -0
  21. package/gates/rook-state.test.ts +108 -0
  22. package/gates/run-attribution.ts +290 -0
  23. package/gates/run-gate.ts +163 -0
  24. package/gates/schema-parity.test.ts +378 -0
  25. package/gates/schema.ts +1209 -0
  26. package/gates/self-heal.test.ts +511 -0
  27. package/gates/self-heal.ts +125 -0
  28. package/gates/ship-orchestrator.test.ts +399 -0
  29. package/gates/ship-orchestrator.ts +384 -0
  30. package/gates/spec-compliance-probe.ts +159 -0
  31. package/gates/test-fixtures/broken-no-environments.json +110 -0
  32. package/gates/test-fixtures/consumer-directory-layout.json +90 -0
  33. package/gates/test-fixtures/valid-standard.json +91 -0
  34. package/gates/test-utils.ts +43 -0
  35. package/gates/typecheck-gate.ts +111 -0
  36. package/gates/witness.ts +349 -0
  37. package/gates/workflow.test.ts +2018 -0
  38. package/hooks/ActionVerificationGate.hook.ts +96 -0
  39. package/hooks/AgentBriefGuard.hook.ts +38 -0
  40. package/hooks/AgentVerdictCapture.hook.ts +87 -0
  41. package/hooks/AutoVerifyGate.hook.ts +79 -0
  42. package/hooks/BashToolGuard.hook.ts +65 -0
  43. package/hooks/BashWriteGuard.hook.ts +60 -0
  44. package/hooks/CommitEnforcement.hook.ts +130 -0
  45. package/hooks/DocHygiene.hook.ts +148 -0
  46. package/hooks/GateEnforcement.hook.ts +58 -0
  47. package/hooks/GateResultProtection.hook.ts +95 -0
  48. package/hooks/HarnessAFKGate.hook.ts +85 -0
  49. package/hooks/HookCurrency.hook.ts +99 -0
  50. package/hooks/IssueCloseGuard.hook.ts +149 -0
  51. package/hooks/MergeGuard.hook.ts +58 -0
  52. package/hooks/PostCompact.hook.ts +60 -0
  53. package/hooks/ProjectStateSync.hook.ts +103 -0
  54. package/hooks/SkillGuard.hook.ts +69 -0
  55. package/hooks/SpecConformityTrigger.hook.ts +43 -0
  56. package/hooks/SpecSCGuard.hook.ts +123 -0
  57. package/hooks/StaleTTLCleanup.hook.ts +141 -0
  58. package/hooks/TaskCompleted.hook.ts +51 -0
  59. package/hooks/TeamInit.hook.ts +85 -0
  60. package/hooks/TestSuiteGuard.hook.ts +70 -0
  61. package/hooks/TestSuiteRelease.hook.ts +85 -0
  62. package/hooks/TopLevelCdGuard.hook.ts +108 -0
  63. package/hooks/VerifyPhaseLock.hook.ts +84 -0
  64. package/hooks/WorkflowStateGuard.hook.ts +64 -0
  65. package/hooks/lib/agent-config.json +9 -0
  66. package/hooks/lib/agentDetection.ts +201 -0
  67. package/hooks/lib/comment-template.ts +86 -0
  68. package/hooks/lib/findWorkflow.ts +101 -0
  69. package/hooks/lib/parseStdin.ts +37 -0
  70. package/hooks/lib/paths.ts +111 -0
  71. package/hooks/lib/utils.ts +338 -0
  72. package/lib/affected-tests.ts +29 -0
  73. package/lib/bash-write-guard.ts +627 -0
  74. package/lib/branch-cleanup.ts +279 -7
  75. package/lib/config-trackable.ts +9 -0
  76. package/lib/distribution-currency.ts +55 -5
  77. package/lib/failure-intake.ts +7 -1
  78. package/lib/gate-enforcement.ts +360 -38
  79. package/lib/gate-names.ts +72 -0
  80. package/lib/gate-result-protection.ts +437 -0
  81. package/lib/generators/code-map.ts +55 -4
  82. package/lib/generators/types.ts +27 -1
  83. package/lib/intake-sources.ts +380 -0
  84. package/lib/js-top-level-code.ts +20 -2
  85. package/lib/junit-checks.ts +239 -1
  86. package/lib/late-env-spawn.ts +331 -0
  87. package/lib/launch-base.ts +128 -5
  88. package/lib/package-closure.ts +114 -0
  89. package/lib/paths.ts +96 -3
  90. package/lib/phase2-decomposition.ts +1 -1
  91. package/lib/published-artifact.ts +162 -18
  92. package/lib/sc-id-cross-tree.ts +84 -8
  93. package/lib/scaffold/ai-review-findings.ts +149 -4
  94. package/lib/scaffold/ai-review-step.ts +1006 -132
  95. package/lib/scaffold/defaults.ts +82 -1
  96. package/lib/scaffold/steps.ts +642 -54
  97. package/lib/scanner.ts +4 -2
  98. package/lib/security-verdict.ts +1 -1
  99. package/lib/shell-path-interpolation.ts +594 -0
  100. package/lib/text-dependents.ts +875 -0
  101. package/lib/transcript-checker.ts +6 -0
  102. package/lib/workflow-security.ts +29 -0
  103. package/lib/workflow-taint.ts +732 -0
  104. package/lib/worktree-cleanup.ts +65 -38
  105. package/lib/worktree-repo.ts +32 -2
  106. package/package.json +4 -1
  107. package/scripts/check-installed-hook-currency.ts +825 -0
  108. package/scripts/generate-code-map.ts +13 -8
@@ -9,10 +9,10 @@
9
9
  */
10
10
  import { existsSync, lstatSync, mkdirSync, readFileSync, writeFileSync, statSync } from "fs";
11
11
  import { readdirSorted } from "../readdir-sorted";
12
- import { join, basename, dirname } from "path";
12
+ import { join, basename, dirname, resolve, sep } from "path";
13
13
  import { auditSpecs } from "../../scripts/audit-specs";
14
14
  import { generateAgentsMd as buildAgentsMdContent, generateScopedRules } from "../generators/agents-md";
15
- import { isHarnessItself } from "../harness-identity";
15
+ import { HARNESS_PACKAGE, isHarnessItself } from "../harness-identity";
16
16
  import { scanSpecs } from "../scanner";
17
17
  import { projectStateDerivation, projectStateKeyFileNote } from "../project-state-derivation";
18
18
  import { generateAgentBriefs as buildAgentBriefsContent } from "../generators/agent-briefs";
@@ -82,6 +82,7 @@ import {
82
82
  type WriteStrategy,
83
83
  } from "./owned-files";
84
84
  import type { SectionSpec } from "../agents-md-sections";
85
+ import { executedHookPath, hookRegistrationPath } from "../hook-trees";
85
86
 
86
87
  /**
87
88
  * Look for a declared health route in the places a server declares one.
@@ -1555,7 +1556,7 @@ export function generateCodeMapStep(
1555
1556
  function generateCodeMapInline(root: string, outPath: string, actions: string[]): void {
1556
1557
  const name = basename(root);
1557
1558
  const skip = new Set(["node_modules", ".git", "reference", "dist", "build", ".next", ".fallow"]);
1558
- const dirs: Array<{ name: string; fileCount: number; types: string[] }> = [];
1559
+ const dirs: Array<{ name: string; types: string[] }> = [];
1559
1560
  for (const entry of readdirSorted(root)) {
1560
1561
  if (entry.startsWith(".") && entry !== ".claude") continue;
1561
1562
  if (skip.has(entry)) continue;
@@ -1564,10 +1565,10 @@ function generateCodeMapInline(root: string, outPath: string, actions: string[])
1564
1565
  if (!statSync(full).isDirectory()) continue;
1565
1566
  const files = readdirSorted(full, { recursive: true });
1566
1567
  const exts = new Set(files.map(f => f.split(".").pop()).filter((e): e is string => Boolean(e)));
1567
- dirs.push({ name: entry, fileCount: files.length, types: [...exts].slice(0, 5) });
1568
+ dirs.push({ name: entry, types: [...exts].slice(0, 5) });
1568
1569
  } catch {}
1569
1570
  }
1570
- dirs.sort((a, b) => b.fileCount - a.fileCount);
1571
+ // Unsorted. Row order is `directoryTable`'s single decision (#1163).
1571
1572
 
1572
1573
  let deps = 0, devDeps = 0;
1573
1574
  const pkgPath = join(root, "package.json");
@@ -2788,6 +2789,190 @@ export function shardCount(ci: unknown): number {
2788
2789
  return Math.min(raw, 32);
2789
2790
  }
2790
2791
 
2792
+ /**
2793
+ * The one non-zero exit the shard aggregate ever takes (#1181).
2794
+ *
2795
+ * Declared once, and spelled nowhere else in the script, so
2796
+ * `test/ci-shard-aggregate-measured.test.ts` can build a mutant copy with it
2797
+ * set to `0` and prove each refusal is the thing the case observed rather
2798
+ * than something that happened to be red —
2799
+ * `.claude/rules/checks-must-be-able-to-fail.md`, "For a script whose job is
2800
+ * to exit non-zero".
2801
+ */
2802
+ export const SHARD_AGGREGATE_REFUSAL_EXIT = 1;
2803
+
2804
+ /**
2805
+ * Environment variable names the shard aggregate's script reads (#1181).
2806
+ *
2807
+ * The script contains **no `${{ }}` expression at all**. Every GitHub-side
2808
+ * value arrives through the step's `env:`, which is what makes the shipped
2809
+ * script text executable by a test with a stubbed `gh` on PATH. A script that
2810
+ * can only run inside Actions is a script no negative control can reach, and
2811
+ * the negative control is the whole of #1181.
2812
+ */
2813
+ export const SHARD_AGGREGATE_ENV = {
2814
+ rollup: "SHARD_ROLLUP",
2815
+ expected: "SHARD_EXPECTED",
2816
+ jobName: "SHARD_JOB_NAME",
2817
+ repo: "SHARD_REPO",
2818
+ runId: "SHARD_RUN_ID",
2819
+ runAttempt: "SHARD_RUN_ATTEMPT",
2820
+ pollAttempts: "SHARD_POLL_ATTEMPTS",
2821
+ pollSeconds: "SHARD_POLL_SECONDS",
2822
+ } as const;
2823
+
2824
+ /**
2825
+ * The shard aggregate's verdict script — it asserts that it MEASURED (#1181).
2826
+ *
2827
+ * ## What went wrong
2828
+ *
2829
+ * PR #1154 merged on run `39799846607`. `test-shard (1)`, `(2)` and `(3)` were
2830
+ * `queued` with `completed_at: null` and **no conclusion**; only shard 4 ran.
2831
+ * The aggregate read `needs.test-shard.result` as `success`, printed "All 4
2832
+ * shards passed", and went green in three seconds. `test` is a required check
2833
+ * and auto-merge is armed repo-wide, so a quarter of the suite authorised the
2834
+ * merge. The three preceding `main` runs were 4/4 — this was an anomaly, not
2835
+ * the pattern, and **the cause of the non-conclusion is unknown**. A fix that
2836
+ * depended on knowing it would not be a fix.
2837
+ *
2838
+ * `if: always()` was added so a **failed or cancelled** shard still reaches
2839
+ * this job. It does nothing about a shard that never concludes, because
2840
+ * `needs.<job>.result` collapses a whole matrix into one word and that word
2841
+ * was `success`.
2842
+ *
2843
+ * ## What this does instead
2844
+ *
2845
+ * The rollup is still read first, so a failed or a cancelled shard produces
2846
+ * exactly the diagnostic it produces today. Then the job asks the Actions API
2847
+ * how many `test-shard (N)` jobs this run **actually concluded**, and refuses
2848
+ * unless that count equals the matrix width. The printed count is the measured
2849
+ * one, never the generated one: a sentence that says "4" because the generator
2850
+ * wrote "4" is the thing that lied on `39799846607`.
2851
+ *
2852
+ * Every reading that cannot be taken is a refusal. No `gh`, no token, an API
2853
+ * error, a malformed count — all exit non-zero, because UNMEASURED is not a
2854
+ * pass. A consumer whose runner has no `gh` gets a red required check rather
2855
+ * than a green one that measured nothing.
2856
+ *
2857
+ * The poll exists for propagation lag, not for the defect: `needs` already
2858
+ * gates on the legs being terminal, so on an ordinary run the first reading
2859
+ * is complete and the loop costs nothing. It bounds how long a genuinely
2860
+ * stalled shard delays the refusal.
2861
+ */
2862
+ export function buildShardAggregateScript(): string {
2863
+ const E = SHARD_AGGREGATE_ENV;
2864
+ return `set -uo pipefail
2865
+
2866
+ # 1. The rollup, read exactly as it is read today. A failed or a cancelled
2867
+ # shard reaches this job through \`if: always()\` and refuses here, with
2868
+ # the same sentence it has always printed.
2869
+ rollup="\${${E.rollup}:-}"
2870
+ if [ "$rollup" != "success" ]; then
2871
+ echo "::error::test-shard concluded '$rollup' — the suite is not green."
2872
+ exit ${SHARD_AGGREGATE_REFUSAL_EXIT}
2873
+ fi
2874
+
2875
+ # 2. A success rollup is not a measurement. Everything below establishes how
2876
+ # many shards this run actually concluded (#1181).
2877
+ expected="\${${E.expected}:-}"
2878
+ case "$expected" in
2879
+ "" | *[!0-9]*)
2880
+ echo "::error::${E.expected} is '$expected', which is not a shard count. UNMEASURED, so refusing."
2881
+ exit ${SHARD_AGGREGATE_REFUSAL_EXIT}
2882
+ ;;
2883
+ esac
2884
+ if [ "$expected" -lt 1 ]; then
2885
+ echo "::error::${E.expected} is $expected, so this job would assert nothing. UNMEASURED, so refusing."
2886
+ exit ${SHARD_AGGREGATE_REFUSAL_EXIT}
2887
+ fi
2888
+
2889
+ job_name="\${${E.jobName}:-test-shard}"
2890
+ attempts="\${${E.pollAttempts}:-3}"
2891
+ pause="\${${E.pollSeconds}:-5}"
2892
+ attempt=1
2893
+
2894
+ while : ; do
2895
+ # \`|| api_status=$?\` rather than a bare assignment followed by \`$?\`.
2896
+ # GitHub runs a \`run:\` block as \`bash -e\`, and under errexit an
2897
+ # assignment whose only word is a failing command substitution aborts the
2898
+ # shell THERE — so the bare form never reaches the handler below, and the
2899
+ # operator gets a red job with gh's stderr captured into a variable
2900
+ # nothing prints. Measured: \`bash -e\` skipped the handler, \`bash\` ran
2901
+ # it. A \`||\` compound is exempt from errexit and \`$?\` is still the
2902
+ # substitution's. Same #826 shape this whole step is written against: a
2903
+ # script proved correct under a shell the generated step does not use.
2904
+ api_status=0
2905
+ rows="$(gh api --paginate \\
2906
+ "repos/\${${E.repo}}/actions/runs/\${${E.runId}}/attempts/\${${E.runAttempt}}/jobs?per_page=100" \\
2907
+ --jq '.jobs[] | [.name, (.conclusion // "none")] | @tsv' 2>&1)" || api_status=$?
2908
+ if [ "$api_status" -ne 0 ]; then
2909
+ # No reading at all. This is the one branch most likely to be written
2910
+ # fail-open, and fail-open here reproduces the defect exactly.
2911
+ echo "::error::could not read this run's jobs from the Actions API (gh exit $api_status): $rows"
2912
+ echo "::error::the shard count is UNMEASURED, which is not a pass. Refusing."
2913
+ exit ${SHARD_AGGREGATE_REFUSAL_EXIT}
2914
+ fi
2915
+
2916
+ seen=0
2917
+ passed=0
2918
+ pending=0
2919
+ detail=""
2920
+ while IFS="$(printf '\\t')" read -r name conclusion; do
2921
+ [ -n "$name" ] || continue
2922
+ case "$name" in
2923
+ "$job_name ("*")") ;;
2924
+ *) continue ;;
2925
+ esac
2926
+ seen=$((seen + 1))
2927
+ case "$conclusion" in
2928
+ success) passed=$((passed + 1)) ;;
2929
+ none | "")
2930
+ pending=$((pending + 1))
2931
+ detail="$detail \\"$name\\"=no-conclusion"
2932
+ ;;
2933
+ *) detail="$detail \\"$name\\"=$conclusion" ;;
2934
+ esac
2935
+ done <<< "$rows"
2936
+
2937
+ # Complete reading, or out of attempts. The loop is for API propagation
2938
+ # lag on an ordinary run, not for the defect.
2939
+ if [ "$pending" -eq 0 ] && [ "$seen" -ge "$expected" ]; then break; fi
2940
+ if [ "$attempt" -ge "$attempts" ]; then break; fi
2941
+ attempt=$((attempt + 1))
2942
+ sleep "$pause"
2943
+ done
2944
+
2945
+ if [ "$seen" -ne "$expected" ]; then
2946
+ echo "::error::this run reports $seen \\"$job_name\\" jobs, and the matrix declares $expected. The aggregate cannot speak for a suite it did not measure."
2947
+ exit ${SHARD_AGGREGATE_REFUSAL_EXIT}
2948
+ fi
2949
+
2950
+ if [ "$pending" -ne 0 ]; then
2951
+ echo "::error::$pending of $expected shards produced NO conclusion:$detail"
2952
+ echo "::error::a shard that never concluded is UNMEASURED, not a pass — this is #1181, where three of four were queued and the aggregate went green."
2953
+ exit ${SHARD_AGGREGATE_REFUSAL_EXIT}
2954
+ fi
2955
+
2956
+ if [ "$passed" -ne "$expected" ]; then
2957
+ echo "::error::$passed of $expected shards concluded success:$detail"
2958
+ exit ${SHARD_AGGREGATE_REFUSAL_EXIT}
2959
+ fi
2960
+
2961
+ # $passed is the measured count, never the generated one. The sentence on
2962
+ # run 39799846607 said "All 4 shards passed" because the generator wrote 4.
2963
+ echo "All $passed shards concluded, and all $passed passed."
2964
+ `;
2965
+ }
2966
+
2967
+ /** Indent a script for a YAML block scalar, leaving blank lines blank. */
2968
+ function indentedScript(script: string, indent: string): string {
2969
+ return script
2970
+ .trimEnd()
2971
+ .split("\n")
2972
+ .map(line => (line ? `${indent}${line}` : ""))
2973
+ .join("\n");
2974
+ }
2975
+
2791
2976
  /**
2792
2977
  * Top-level workflow keys this consumer has taken back from the generator
2793
2978
  * (#839). Declared in `lib/scaffold/managed-workflow.ts`, beside the merge
@@ -2900,6 +3085,60 @@ export function globalToolInstallStep(ci: unknown, indent = " "): GlobalToo
2900
3085
  * declares `cancel-in-progress` keeps its own value, and this reaches only the
2901
3086
  * consumers that have no concurrency block at all.
2902
3087
  */
3088
+ /**
3089
+ * The `on.pull_request` trigger, carrying NO `branches:` filter — the one
3090
+ * shared binding every generated workflow renders (#1136).
3091
+ *
3092
+ * The filter used to be the same `branchList` emitted under `on.push`, which
3093
+ * made a pull request whose BASE was a feature branch match nothing and
3094
+ * trigger nothing: no `test`, no shards, no `gates`, no `ai-review`. Measured
3095
+ * on this repository before the change, by full 40-char head SHA — a short SHA
3096
+ * silently returns zero runs, so the two look identical and the query must use
3097
+ * the full one:
3098
+ *
3099
+ * witness #1128 base feat/713-migrate-product-hooks 0 runs
3100
+ * witness #1133 base feat/713-migrate-product-hooks 0 runs
3101
+ * control #1125 base main 3 runs
3102
+ * control #1134 base main 3 runs
3103
+ *
3104
+ * Base branch is the only input that differs. Both witnesses merged: with no
3105
+ * workflow triggered there is no required check left pending, so a pull
3106
+ * request that measured NOTHING is reported to the merge box exactly as a
3107
+ * green one is. That is the half worth naming — the gap is invisible from the
3108
+ * side that acts on it.
3109
+ *
3110
+ * `on.push` KEEPS its filter, and that is not an oversight. The two keys
3111
+ * answer different questions: `push.branches` is "which branches earn a CI run
3112
+ * on their own", `pull_request.branches` was answering "which bases may be
3113
+ * merged into", which nothing here ever wanted to ask. Deleting `branchList`
3114
+ * from both — the cheapest wrong fix, and it does turn every witness above
3115
+ * green — fires a full CI run on every push to every feature branch on top of
3116
+ * the `pull_request` run already covering that commit. Sampled over 25 recent
3117
+ * merged PRs: 44 commits, mean 1.76 pushes each, against 72 push-event runs in
3118
+ * the last 300. Roughly an order of magnitude of duplicated runner time for no
3119
+ * new coverage. The `on.push` cases in test/stacked-pr-ci-trigger.test.ts are
3120
+ * the control that stays red for it.
3121
+ *
3122
+ * Enumerating the namespaces instead (`feat/**`, `fix/**`) would have covered
3123
+ * all 6 of the non-`main`-based PRs in the last 200, so history cannot falsify
3124
+ * it. The prospective count can: of those 200, 24 head branches sit outside
3125
+ * both namespaces — `chore/`, `rg/`, `wt/`, `docs/`, `revert/`, bare names —
3126
+ * and any of them can be a base tomorrow. An allowlist re-creates this exact
3127
+ * defect the first time someone picks a prefix nobody enumerated, and does it
3128
+ * silently, which is the property that made #1136 cost two merges.
3129
+ */
3130
+ export const CI_PULL_REQUEST_TRIGGER = ` # NO branches: filter, deliberately (#1136). A pull request based on a
3131
+ # feature branch matched no entry here and so triggered nothing at all —
3132
+ # and because no required check was left pending, it reported CLEAN. A
3133
+ # stack is how multi-part work is built in this repo, so the changes
3134
+ # least likely to run CI were the ones most likely to need it.
3135
+ #
3136
+ # Where a \`push\` trigger exists it KEEPS its filter — that key asks which
3137
+ # branches earn a run on their own, which is a different question.
3138
+ # Removing it there too duplicates a run on every feature-branch push for
3139
+ # no new coverage.
3140
+ pull_request:`;
3141
+
2903
3142
  export const CI_CONCURRENCY = `# The GROUP does the work here, not the flag. A run is only ever cancelled by
2904
3143
  # another run in the SAME group, so keying a push on its own commit makes the
2905
3144
  # question moot: there is never a second occupant to do the cancelling.
@@ -3121,9 +3360,7 @@ on:
3121
3360
  push:
3122
3361
  branches:
3123
3362
  ${branchList}
3124
- pull_request:
3125
- branches:
3126
- ${branchList}
3363
+ ${CI_PULL_REQUEST_TRIGGER}
3127
3364
 
3128
3365
  ${CI_CONCURRENCY}
3129
3366
  permissions:
@@ -3164,15 +3401,27 @@ ${bunStep}
3164
3401
  # protection configurations read a skip as satisfied — which would make
3165
3402
  # this aggregate a gate that cannot refuse.
3166
3403
  if: always()
3404
+ permissions:
3405
+ contents: read
3406
+ # #1181. The aggregate asks the Actions API how many shards actually
3407
+ # concluded, because \`needs.test-shard.result\` collapses a matrix into
3408
+ # one word and reported \`success\` for three legs that never ran.
3409
+ actions: read
3167
3410
  steps:
3168
- - name: Every shard passed
3411
+ - name: Every shard concluded, and every shard passed
3412
+ env:
3413
+ # Every GitHub-side value arrives here, and the script below holds
3414
+ # no GitHub expression at all — that is what lets a test execute
3415
+ # the shipped text with a stubbed gh and watch it refuse (#1181).
3416
+ ${SHARD_AGGREGATE_ENV.rollup}: \${{ needs.test-shard.result }}
3417
+ ${SHARD_AGGREGATE_ENV.expected}: "${shards}"
3418
+ ${SHARD_AGGREGATE_ENV.jobName}: test-shard
3419
+ ${SHARD_AGGREGATE_ENV.repo}: \${{ github.repository }}
3420
+ ${SHARD_AGGREGATE_ENV.runId}: \${{ github.run_id }}
3421
+ ${SHARD_AGGREGATE_ENV.runAttempt}: \${{ github.run_attempt }}
3422
+ GH_TOKEN: \${{ github.token }}
3169
3423
  run: |
3170
- result='\${{ needs.test-shard.result }}'
3171
- if [ "$result" != "success" ]; then
3172
- echo "::error::test-shard concluded '$result' — the suite is not green."
3173
- exit 1
3174
- fi
3175
- echo "All ${shards} shards passed."
3424
+ ${indentedScript(buildShardAggregateScript(), " ")}
3176
3425
  `
3177
3426
  : `# Managed by rungate — do not edit. Customize the ci section of .claude/rungate/config.json.
3178
3427
  name: CI
@@ -3187,9 +3436,7 @@ on:
3187
3436
  push:
3188
3437
  branches:
3189
3438
  ${branchList}
3190
- pull_request:
3191
- branches:
3192
- ${branchList}
3439
+ ${CI_PULL_REQUEST_TRIGGER}
3193
3440
 
3194
3441
  ${CI_CONCURRENCY}
3195
3442
  permissions:
@@ -3228,9 +3475,7 @@ on:
3228
3475
  push:
3229
3476
  branches:
3230
3477
  ${branchList}
3231
- pull_request:
3232
- branches:
3233
- ${branchList}
3478
+ ${CI_PULL_REQUEST_TRIGGER}
3234
3479
 
3235
3480
  permissions:
3236
3481
  # Least privilege, and it matters most on the consumers. A workflow with
@@ -3423,9 +3668,7 @@ on:
3423
3668
  # See the block comment in lib/scaffold/steps.ts: no branches: filter, and
3424
3669
  # its absence hangs a merge queue silently rather than failing it (#867).
3425
3670
  merge_group:
3426
- pull_request:
3427
- branches:
3428
- ${branchList}
3671
+ ${CI_PULL_REQUEST_TRIGGER}
3429
3672
 
3430
3673
  ${aiReviewPermissions}
3431
3674
 
@@ -3433,11 +3676,29 @@ jobs:
3433
3676
  ${AI_REVIEW_JOB}:
3434
3677
  runs-on: ${runsOn}
3435
3678
  steps:
3436
- ${buildAuthDetectStep(vertex)}${buildReviewRunStep(vertex, {
3437
- checkout: actionRef("actions/checkout"),
3438
- auth: actionRef(GOOGLE_AUTH_ACTION),
3439
- review: actionRef(CLAUDE_CODE_ACTION),
3440
- })}`;
3679
+ ${buildAuthDetectStep(vertex)}${buildReviewRunStep(
3680
+ vertex,
3681
+ {
3682
+ checkout: actionRef("actions/checkout"),
3683
+ auth: actionRef(GOOGLE_AUTH_ACTION),
3684
+ review: actionRef(CLAUDE_CODE_ACTION),
3685
+ setupBun: actionRef("oven-sh/setup-bun"),
3686
+ // The same single declaration the test and gates jobs resolve from
3687
+ // (#622), at the indent this job's step bodies use.
3688
+ setupBunWith: setupBunWith(declaredBunVersion(root), " "),
3689
+ },
3690
+ // #1013. The GENERATING version, and the same reading `harnessDevDepRange`
3691
+ // takes — one function, so a scaffold cannot write a `bunx rungate@X` next
3692
+ // to a `devDependencies` entry floored at a different minor.
3693
+ //
3694
+ // A tree running ahead of npm emits a command the registry cannot satisfy
3695
+ // yet, exactly as that function's own docstring describes for the
3696
+ // dependency range, and it becomes resolvable the moment the version
3697
+ // ships. It is not silent in the window: the adjudicator prints no outcome
3698
+ // line, and the verdict step reports UNMEASURED rather than reading the
3699
+ // failure as a refusal.
3700
+ harnessVersion(),
3701
+ )}`;
3441
3702
 
3442
3703
  // Not `writeFileSync`. The harness owns the `test` and `gates` jobs; it does
3443
3704
  // not own the file, and a consumer's own jobs have to survive the update
@@ -3492,6 +3753,111 @@ ${buildAuthDetectStep(vertex)}${buildReviewRunStep(vertex, {
3492
3753
 
3493
3754
  // ── Consumer hook deployment ─────────────────────────────────
3494
3755
 
3756
+ /**
3757
+ * The commands Claude Code would actually RUN for one event, read the way
3758
+ * Claude Code reads them (#1088).
3759
+ *
3760
+ * The schema is `event → matcher group → hooks[] → { type, command }`, and a
3761
+ * leaf is a registration only when every level is present:
3762
+ *
3763
+ * ```json
3764
+ * "PreToolUse": [
3765
+ * { "matcher": "Bash", "hooks": [ { "type": "command", "command": "…" } ] }
3766
+ * ]
3767
+ * ```
3768
+ *
3769
+ * `matcher` is omitted for events that do not have one — `SessionStart`,
3770
+ * `SubagentStop`, `PostCompact` and the rest — but `hooks[]` and
3771
+ * `type: "command"` are not optional anywhere. Read off a live
3772
+ * `~/.claude/settings.json` holding twenty-five groups across eleven events,
3773
+ * not off documentation.
3774
+ *
3775
+ * ## Why this is not `settingsCommands` from `lib/hook-trees.ts`
3776
+ *
3777
+ * That function walks the document recursively and collects any `command`
3778
+ * string **at any depth**, deliberately: it answers a census question —
3779
+ * *which trees does this machine register hooks from* — and a census that
3780
+ * knew one shape would report a document in the next shape as empty, which
3781
+ * is indistinguishable from a machine with no registrations.
3782
+ *
3783
+ * That tolerance is exactly why #1088 survived. `deployHooksToConsumers`
3784
+ * wrote a bare `{ command }` straight into the event array; the permissive
3785
+ * walk found the string, every test that asked "is the hook there?" said yes,
3786
+ * and Claude Code — the only reader whose answer decides whether the guard
3787
+ * runs — saw an array element it does not recognise as a hook. Two readers
3788
+ * disagreed and the authoritative one was not under test.
3789
+ *
3790
+ * So this reader is **strict on purpose**, and it is a second binding on
3791
+ * purpose. The two answer different questions and must be able to disagree:
3792
+ * their disagreement on a bare `{ command }` is the whole defect, and a
3793
+ * reading that cannot disagree cannot witness it
3794
+ * (`.claude/rules/checks-must-be-able-to-fail.md`, fourth shape).
3795
+ */
3796
+ export function executingHookCommands(settings: unknown, event: string): string[] {
3797
+ if (settings === null || typeof settings !== "object" || Array.isArray(settings)) return [];
3798
+ const hooks = (settings as Record<string, unknown>).hooks;
3799
+ if (hooks === null || typeof hooks !== "object" || Array.isArray(hooks)) return [];
3800
+ const groups = (hooks as Record<string, unknown>)[event];
3801
+ if (!Array.isArray(groups)) return [];
3802
+
3803
+ const out: string[] = [];
3804
+ for (const group of groups) {
3805
+ if (group === null || typeof group !== "object" || Array.isArray(group)) continue;
3806
+ // A bare `{ command }` has no `hooks[]`, and that is the #1088 shape. It
3807
+ // is not a registration, so it is not reported as one.
3808
+ const leaves = (group as Record<string, unknown>).hooks;
3809
+ if (!Array.isArray(leaves)) continue;
3810
+ for (const leaf of leaves) {
3811
+ if (leaf === null || typeof leaf !== "object" || Array.isArray(leaf)) continue;
3812
+ const rec = leaf as Record<string, unknown>;
3813
+ // The field #1088 omitted. `type` is what tells a command hook from
3814
+ // the other leaf kinds the schema allows, so a leaf without it is not
3815
+ // a command this can claim will run.
3816
+ if (rec.type !== "command") continue;
3817
+ if (typeof rec.command === "string") out.push(rec.command);
3818
+ }
3819
+ }
3820
+ return out;
3821
+ }
3822
+
3823
+ /**
3824
+ * Where a deployed hook command points, in the two spellings one deployment
3825
+ * needs (#1088).
3826
+ *
3827
+ * `command` is what goes into the consumer's settings file; `disk` is the
3828
+ * path this process checks for existence. They are returned together because
3829
+ * writing one and checking the other is the defect: before this, the command
3830
+ * was built from `join(harnessRoot, "hooks")` and nothing was checked at all,
3831
+ * so a consumer that installed rungate from npm received twelve guards whose
3832
+ * commands named a directory on the harness author's machine — and the run
3833
+ * reported `DEPLOYED: 12 hooks`.
3834
+ *
3835
+ * Resolved against the CONSUMER, which is the tree the hook will run in:
3836
+ *
3837
+ * | the consumer is | command | disk |
3838
+ * |---|---|---|
3839
+ * | the harness itself | `${CLAUDE_PROJECT_DIR}/hooks` | `<root>/hooks` |
3840
+ * | anything else | `${CLAUDE_PROJECT_DIR}/node_modules/rungate/hooks` | `<root>/node_modules/rungate/hooks` |
3841
+ *
3842
+ * `${CLAUDE_PROJECT_DIR}` rather than an absolute path, for the same reason
3843
+ * the harness's own `.claude/settings.json` is spelled that way: the variable
3844
+ * survives the checkout moving, and an absolute path baked at scaffold time
3845
+ * is wrong the first time the consumer is cloned somewhere else.
3846
+ *
3847
+ * Identity comes from `isHarnessItself` — the project's own `package.json`
3848
+ * `name` — which is the single existing binding for this question (#380) and
3849
+ * the same one `promptPrefix` and `detectPromptPrefix` read. A second
3850
+ * decider agreeing with it would be behaviourally one decider.
3851
+ */
3852
+ export function consumerHooksDir(consumerRoot: string): { command: string; disk: string } {
3853
+ return isHarnessItself(consumerRoot)
3854
+ ? { command: "${CLAUDE_PROJECT_DIR}/hooks", disk: join(consumerRoot, "hooks") }
3855
+ : {
3856
+ command: "${CLAUDE_PROJECT_DIR}/node_modules/" + HARNESS_PACKAGE + "/hooks",
3857
+ disk: join(consumerRoot, "node_modules", HARNESS_PACKAGE, "hooks"),
3858
+ };
3859
+ }
3860
+
3495
3861
  /**
3496
3862
  * Deploy hooks marked deployToConsumers:true to consumer projects'
3497
3863
  * .claude/settings.local.json with correct hookFor and command paths.
@@ -3503,6 +3869,58 @@ ${buildAuthDetectStep(vertex)}${buildReviewRunStep(vertex, {
3503
3869
  * directly — as this did — meant a project on the directory layout deployed
3504
3870
  * nothing and said nothing, because the early return is indistinguishable
3505
3871
  * from "this project has no hooks" (#70).
3872
+ *
3873
+ * ## Every exit leaves a reading (#1047)
3874
+ *
3875
+ * #70 fixed one silent return and left four. When #1047 was written, zero of
3876
+ * twenty registry entries set `deployToConsumers`, so the eligible set was
3877
+ * empty on every run this function had ever had, and the only line it emitted
3878
+ * was `SKIP: All hooks already deployed to <consumer>` — a claim about hooks
3879
+ * that were never eligible, printed by the `else` of `deployed > 0`. A caller
3880
+ * reading the action list saw a successful no-op. So did the release.
3881
+ *
3882
+ * **That count is no longer true, and this docblock asserted it for longer
3883
+ * than it held.** Re-measured 2026-10-21 by parsing
3884
+ * `.claude/rungate/hooks.json`: **twenty entries, twelve `true`, eight
3885
+ * `false`, none absent.** #1047's AC-11 now refuses an entry that leaves the
3886
+ * field unset, which is why nothing is absent and why the number cannot drift
3887
+ * back. Corrected by #713, which found the same stale claim in two other
3888
+ * places; if you are reading this docblock you are most likely the person
3889
+ * about to decide what a consumer receives, and the old sentence told you
3890
+ * nobody had opted in when twelve entries had.
3891
+ *
3892
+ * What that does and does not mean, since the eligible set being non-empty is
3893
+ * the whole precondition for everything below:
3894
+ *
3895
+ * - Deployment is **armed**, not dormant. `hooks/` is in `package.json`'s
3896
+ * `files[]`, so the `node_modules/<pkg>/hooks` command this function writes
3897
+ * resolves on a consumer.
3898
+ * - **Publishing deploys nothing by itself.** This function runs from the
3899
+ * scaffold's write-steps, not from an install hook, so the trigger is a
3900
+ * scaffold run and the sink is `<consumerRoot>/.claude/settings.local.json`.
3901
+ * - **`consumers` is `[]` on this repository today**, so the guard below
3902
+ * returns before any of that. The first declared consumer to be scaffolded
3903
+ * is when twelve hook registrations first appear in somebody's settings.
3904
+ *
3905
+ * Four outcomes used to arrive as one, or as nothing:
3906
+ *
3907
+ * | what happened | what it said before | what it says now |
3908
+ * |---|---|---|
3909
+ * | no rungate config at all | nothing | `SKIP:` naming the root |
3910
+ * | config has no `hooks` array | nothing | `SKIP:` naming the absence |
3911
+ * | no `consumers` declared | nothing | `SKIP:` naming the absence |
3912
+ * | hooks exist, none opted in | `SKIP: All hooks already deployed` | `UNMEASURED:` with the count |
3913
+ * | all eligible already present | `SKIP: All hooks already deployed` | `SKIP:` with the eligible count |
3914
+ *
3915
+ * The UNMEASURED row is the one the issue turns on. `0 deployed because the
3916
+ * project wanted none` and `0 deployed because nobody set the flag` are
3917
+ * different facts and only one of them is fine; the first is now a `SKIP`
3918
+ * over a non-empty eligible set and the second is an `UNMEASURED` that names
3919
+ * how many entries were read and how many opted in. `.claude/rules/
3920
+ * config-access.md`: a reading is not `0`, `{}`, `null` or silence.
3921
+ *
3922
+ * A DEPLOYED line also names the hooks, because a count cannot be checked
3923
+ * against a registry and a list can.
3506
3924
  */
3507
3925
  export function deployHooksToConsumers(root: string, actions: string[]): void {
3508
3926
  let harness: any;
@@ -3514,15 +3932,55 @@ export function deployHooksToConsumers(root: string, actions: string[]): void {
3514
3932
  actions.push(`SKIP: hook deployment — unreadable rungate config: ${(err as Error).message}`);
3515
3933
  return;
3516
3934
  }
3517
- if (!harness) return;
3935
+ if (!harness) {
3936
+ actions.push(`SKIP: hook deployment — no rungate config under ${root}`);
3937
+ return;
3938
+ }
3518
3939
 
3519
- if (!harness?.hooks || !Array.isArray(harness.hooks)) return;
3520
- if (!harness?.consumers || !Array.isArray(harness.consumers) || harness.consumers.length === 0) return;
3940
+ if (!harness?.hooks || !Array.isArray(harness.hooks)) {
3941
+ actions.push("SKIP: hook deployment — the rungate config declares no hooks array");
3942
+ return;
3943
+ }
3944
+ if (!harness?.consumers || !Array.isArray(harness.consumers) || harness.consumers.length === 0) {
3945
+ actions.push("SKIP: hook deployment — the rungate config declares no consumers");
3946
+ return;
3947
+ }
3521
3948
 
3522
- const hooksDir = join(root, "hooks");
3949
+ // Taken ONCE, before any consumer loop, because it is a fact about the
3950
+ // registry and not about a consumer. Reporting it per-consumer would make
3951
+ // a repository with no consumers unable to say it, which is the same
3952
+ // silence one layer down.
3953
+ const eligible = harness.hooks.filter(
3954
+ (h: any) => h?.enabled && h?.hookFor && h?.command && h?.deployToConsumers === true,
3955
+ );
3956
+ if (eligible.length === 0) {
3957
+ actions.push(
3958
+ `UNMEASURED: hook deployment — 0 of ${harness.hooks.length} registry entries set ` +
3959
+ `deployToConsumers, so nothing was eligible and nothing declined it. This is not ` +
3960
+ `"this project wants no hooks"; it is "nobody said". Set deployToConsumers on the ` +
3961
+ `entries a consumer needs, or false with a notDeployedReason on the ones it does not.`,
3962
+ );
3963
+ return;
3964
+ }
3523
3965
 
3524
3966
  for (const consumer of harness.consumers) {
3525
- const consumerRoot = consumer.startsWith("/") ? consumer : join(root, consumer);
3967
+ // An absolute entry is the repository owner naming a tree outside this
3968
+ // one on purpose, and that is a supported declaration. A RELATIVE entry
3969
+ // says "inside this repository", so one containing `..` is saying two
3970
+ // things at once and only one of them can be true — refuse it rather
3971
+ // than writing to wherever it lands (#1088).
3972
+ const consumerRoot = consumer.startsWith("/") ? consumer : resolve(root, consumer);
3973
+ if (!consumer.startsWith("/")) {
3974
+ const base = resolve(root);
3975
+ if (consumerRoot !== base && !consumerRoot.startsWith(base + sep)) {
3976
+ actions.push(
3977
+ `SKIP: Consumer ${consumer} — a relative consumer path must stay inside ${base}, ` +
3978
+ `and this one resolves to ${consumerRoot}. Declare it as an absolute path if ` +
3979
+ `that is deliberate.`,
3980
+ );
3981
+ continue;
3982
+ }
3983
+ }
3526
3984
  if (!existsSync(consumerRoot)) {
3527
3985
  actions.push(`SKIP: Consumer ${consumer} — directory not found`);
3528
3986
  continue;
@@ -3536,39 +3994,169 @@ export function deployHooksToConsumers(root: string, actions: string[]): void {
3536
3994
  const settingsPath = join(consumerRoot, ".claude", "settings.local.json");
3537
3995
  let settings: any = {};
3538
3996
  if (existsSync(settingsPath)) {
3539
- try { settings = JSON.parse(readFileSync(settingsPath, "utf-8")); } catch {}
3997
+ // A corrupt config is never a missing config (`.claude/rules/
3998
+ // config-access.md`). The `catch {}` this replaces left `settings` as
3999
+ // `{}` and then fell through to `writeFileSync` — so a consumer's
4000
+ // settings.local.json that failed to parse for any reason, including a
4001
+ // half-written file or a merge conflict marker, was OVERWRITTEN with a
4002
+ // file containing nothing but our hooks. Their permissions, their
4003
+ // allowlists, their own hook registrations: gone, silently, during a
4004
+ // run whose purpose was to add three lines.
4005
+ //
4006
+ // Refuse this consumer and keep going to the next. Repairing somebody
4007
+ // else's security settings is not a decision a scaffold step gets to
4008
+ // take, and neither is discarding them.
4009
+ try {
4010
+ settings = JSON.parse(readFileSync(settingsPath, "utf-8"));
4011
+ } catch (err) {
4012
+ actions.push(
4013
+ `SKIP: ${consumer} — .claude/settings.local.json exists but does not parse ` +
4014
+ `(${(err as Error).message}). Refusing to overwrite it. Fix the file and re-run.`,
4015
+ );
4016
+ continue;
4017
+ }
4018
+ if (settings === null || typeof settings !== "object" || Array.isArray(settings)) {
4019
+ // `JSON.parse("null")` and `JSON.parse("[]")` both succeed and both
4020
+ // take `settings.hooks = {}` without complaint, so the parse alone
4021
+ // does not establish that this is a settings object.
4022
+ actions.push(
4023
+ `SKIP: ${consumer} — .claude/settings.local.json parses but is not an object. ` +
4024
+ `Refusing to overwrite it.`,
4025
+ );
4026
+ continue;
4027
+ }
3540
4028
  }
3541
4029
 
3542
4030
  if (!settings.hooks) settings.hooks = {};
3543
4031
 
3544
- let deployed = 0;
3545
- for (const hook of harness.hooks) {
3546
- if (!hook.enabled || !hook.hookFor || !hook.command) continue;
3547
- if (hook.deployToConsumers !== true) continue;
3548
-
3549
- const resolvedCommand = hook.command.replace("${RUNGATE_HOOKS_DIR}", hooksDir);
4032
+ // Resolved against the CONSUMER, not against the harness (#1088). `disk`
4033
+ // is only ever used to ask whether the file is there; `command` is the
4034
+ // only spelling that reaches the consumer's settings file.
4035
+ const dirs = consumerHooksDir(consumerRoot);
4036
+
4037
+ const deployedNames: string[] = [];
4038
+ const repairedNames: string[] = [];
4039
+ let alreadyPresent = 0;
4040
+ for (const hook of eligible) {
4041
+ const resolvedCommand = hook.command.replace("${RUNGATE_HOOKS_DIR}", dirs.command);
4042
+ const diskCommand = hook.command.replace("${RUNGATE_HOOKS_DIR}", dirs.disk);
3550
4043
  const hookType = hook.hookFor as string;
3551
4044
 
3552
- if (!settings.hooks[hookType]) settings.hooks[hookType] = [];
4045
+ if (!Array.isArray(settings.hooks[hookType])) settings.hooks[hookType] = [];
4046
+ const groups: any[] = settings.hooks[hookType];
4047
+
4048
+ // Does the file this command runs exist in the tree it will run in?
4049
+ //
4050
+ // Nothing asked before, so the deployment could not tell "the guard is
4051
+ // installed" from "the guard's path names nothing here" — and both
4052
+ // reported `DEPLOYED`. A silently inert security control is worse than
4053
+ // an absent one; an absent one gets noticed.
4054
+ const executed = executedHookPath(diskCommand);
4055
+ if (executed === null) {
4056
+ actions.push(
4057
+ `UNMEASURED: ${consumer} — ${hook.name}: could not read which file ` +
4058
+ `"${hook.command}" executes, so whether it is present was never established. ` +
4059
+ `Not deployed.`,
4060
+ );
4061
+ continue;
4062
+ }
4063
+ if (!existsSync(executed)) {
4064
+ actions.push(
4065
+ `UNMEASURED: ${consumer} — ${hook.name}: nothing at ${executed}, which is where ` +
4066
+ `the command being written points. Not deployed. Install ${HARNESS_PACKAGE} in ` +
4067
+ `the consumer, or drop deployToConsumers on this entry.`,
4068
+ );
4069
+ continue;
4070
+ }
3553
4071
 
3554
- // Check if this hook is already deployed
3555
- const existing = settings.hooks[hookType].find(
3556
- (h: any) => h.command === resolvedCommand || (h.command && h.command.includes(hook.name))
4072
+ // Registrations as CLAUDE CODE would see them. Reading `groups` for a
4073
+ // top-level `command` — which is what this used to do — counts the
4074
+ // inert pre-#1088 entries as deployments, so a consumer that already
4075
+ // received the broken shape would never receive the working one and
4076
+ // the run would report "already deployed" forever.
4077
+ const registered = executingHookCommands(settings, hookType).filter(
4078
+ c => hookRegistrationPath(c, hook.name) !== null,
3557
4079
  );
3558
- if (existing) continue;
4080
+ if (registered.includes(resolvedCommand)) {
4081
+ alreadyPresent++;
4082
+ continue;
4083
+ }
4084
+ if (registered.length > 0) {
4085
+ // Names the hook, runs something else. That is a disagreement about
4086
+ // which program a guard is, and resolving it by appending a second
4087
+ // registration — or by treating it as already deployed — both pick a
4088
+ // winner silently. Say it and leave the consumer's entry alone.
4089
+ actions.push(
4090
+ `CONFLICT: ${consumer} — ${hook.name} is already registered under ${hookType} as ` +
4091
+ `${registered.join(", ")}, which is not ${resolvedCommand}. Left alone; ` +
4092
+ `nothing was deployed for this hook.`,
4093
+ );
4094
+ continue;
4095
+ }
3559
4096
 
3560
- const hookEntry: any = { command: resolvedCommand };
3561
- if (hook.matcher) hookEntry.matcher = hook.matcher;
4097
+ // Inert leftovers from the shape this fixes: a bare `{ command }` in
4098
+ // the event array, which Claude Code does not recognise as a hook.
4099
+ // Removed rather than left beside the correct entry, because a reader
4100
+ // cannot tell one of ours from one of the consumer's — and ours is
4101
+ // identified exactly: it EXECUTES `<name>.hook.ts`, by the same parse
4102
+ // the registration check uses.
4103
+ for (let i = groups.length - 1; i >= 0; i--) {
4104
+ const g = groups[i];
4105
+ if (g === null || typeof g !== "object" || Array.isArray(g)) continue;
4106
+ if (Array.isArray(g.hooks)) continue;
4107
+ if (typeof g.command !== "string") continue;
4108
+ if (hookRegistrationPath(g.command, hook.name) === null) continue;
4109
+ groups.splice(i, 1);
4110
+ repairedNames.push(hook.name);
4111
+ }
3562
4112
 
3563
- settings.hooks[hookType].push(hookEntry);
3564
- deployed++;
4113
+ // The executing shape: event → matcher group → `hooks[]` → `{ type,
4114
+ // command }`. An existing group with the SAME matcher is reused, so a
4115
+ // re-scaffold does not accumulate one group per run, and events with
4116
+ // no matcher get a group with the key omitted rather than set to
4117
+ // `undefined` — which is what `~/.claude/settings.json` holds for
4118
+ // SessionStart, SubagentStop and PostCompact.
4119
+ const matcher: string | undefined =
4120
+ typeof hook.matcher === "string" && hook.matcher.length > 0 ? hook.matcher : undefined;
4121
+ let group = groups.find(
4122
+ (g: any) =>
4123
+ g !== null &&
4124
+ typeof g === "object" &&
4125
+ !Array.isArray(g) &&
4126
+ Array.isArray(g.hooks) &&
4127
+ (typeof g.matcher === "string" ? g.matcher : undefined) === matcher,
4128
+ );
4129
+ if (!group) {
4130
+ group = matcher === undefined ? { hooks: [] } : { matcher, hooks: [] };
4131
+ groups.push(group);
4132
+ }
4133
+ group.hooks.push({ type: "command", command: resolvedCommand });
4134
+ deployedNames.push(hook.name);
3565
4135
  }
3566
4136
 
3567
- if (deployed > 0) {
4137
+ if (deployedNames.length > 0 || repairedNames.length > 0) {
3568
4138
  writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + "\n");
3569
- actions.push(`DEPLOYED: ${deployed} hooks to ${consumer}/.claude/settings.local.json`);
3570
- } else {
3571
- actions.push(`SKIP: All hooks already deployed to ${consumer}`);
4139
+ if (repairedNames.length > 0) {
4140
+ actions.push(
4141
+ `REPAIRED: ${repairedNames.length} unrecognised hook entries removed from ` +
4142
+ `${consumer}/.claude/settings.local.json — ${repairedNames.join(", ")}. They were ` +
4143
+ `written in a shape Claude Code does not execute (#1088) and never ran.`,
4144
+ );
4145
+ }
4146
+ if (deployedNames.length > 0) {
4147
+ actions.push(
4148
+ `DEPLOYED: ${deployedNames.length} hooks to ${consumer}/.claude/settings.local.json ` +
4149
+ `— ${deployedNames.join(", ")}`,
4150
+ );
4151
+ }
4152
+ } else if (alreadyPresent === eligible.length) {
4153
+ // Reachable only with a non-empty eligible set, so this now means what
4154
+ // it says. The `eligible.length === 0` guard above took the other case,
4155
+ // and an UNMEASURED or CONFLICT hook is no longer swept in here — each
4156
+ // pushed its own line and this count excludes it.
4157
+ actions.push(
4158
+ `SKIP: all ${eligible.length} eligible hooks already deployed to ${consumer}`,
4159
+ );
3572
4160
  }
3573
4161
  }
3574
4162
  }