continuous-improvement 3.9.2 → 3.11.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.
Files changed (150) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +61 -0
  3. package/QUICKSTART.md +13 -8
  4. package/README.md +84 -153
  5. package/bin/backfill.mjs +0 -0
  6. package/bin/check-doc-runtime-claims.mjs +0 -0
  7. package/bin/check-docs-substrings.mjs +73 -0
  8. package/bin/check-everything-mirror.mjs +0 -0
  9. package/bin/check-routing-targets.mjs +0 -0
  10. package/bin/check-scripts-citation-drift.mjs +210 -0
  11. package/bin/check-skill-count.mjs +110 -0
  12. package/bin/check-skill-law-tag.mjs +0 -0
  13. package/bin/check-skill-mirror.mjs +0 -0
  14. package/bin/check-skill-tiers.mjs +0 -0
  15. package/bin/check-test-imports-only.mjs +126 -0
  16. package/bin/check-third-party-shape.mjs +0 -0
  17. package/bin/companion-preference-status.mjs +231 -0
  18. package/bin/gateguard-clear.mjs +53 -0
  19. package/bin/generate-plugin-manifests.mjs +7 -1
  20. package/bin/harvest-friction.mjs +0 -0
  21. package/bin/hook-stats.mjs +0 -0
  22. package/bin/install.mjs +182 -26
  23. package/bin/lint-transcript.mjs +0 -0
  24. package/bin/mcp-server.mjs +215 -2
  25. package/bin/observe.mjs +0 -0
  26. package/bin/pre-commit-block-strays.sh +0 -0
  27. package/bin/refresh-third-party.mjs +315 -313
  28. package/bin/unified-cli.mjs +0 -0
  29. package/commands/audit.md +34 -0
  30. package/commands/companion-preference.md +58 -0
  31. package/commands/discipline.md +14 -0
  32. package/commands/distill.md +39 -0
  33. package/commands/goal-check.md +53 -0
  34. package/commands/grill-me.md +40 -0
  35. package/commands/grill-with-docs.md +38 -0
  36. package/commands/handoff.md +42 -0
  37. package/commands/proceed-with-the-recommendation.md +20 -0
  38. package/commands/recall.md +49 -0
  39. package/commands/reconcile.md +47 -0
  40. package/commands/superpowers.md +2 -2
  41. package/commands/verify-install.md +55 -0
  42. package/hooks/companion-preference.mjs +190 -0
  43. package/hooks/gateguard.mjs +60 -25
  44. package/hooks/goal-drift-stop.mjs +183 -0
  45. package/hooks/observe.sh +15 -1
  46. package/hooks/route-prompt.mjs +180 -0
  47. package/hooks/route-table.json +35 -0
  48. package/hooks/three-section-close.mjs +134 -132
  49. package/lib/cli-anything.mjs +0 -0
  50. package/lib/compound-engineering.mjs +0 -0
  51. package/lib/gateguard-state.mjs +54 -2
  52. package/lib/goal-drift-gate.mjs +50 -0
  53. package/lib/goal-state.mjs +285 -0
  54. package/lib/observe-event.mjs +0 -0
  55. package/lib/plugin-metadata.mjs +126 -12
  56. package/lib/pm-marketplace.mjs +0 -0
  57. package/lib/pm-skills.mjs +0 -0
  58. package/lib/recall-index.mjs +175 -0
  59. package/lib/resolve-home-dir.mjs +0 -0
  60. package/lib/skill-distill.mjs +222 -0
  61. package/lib/skill-tiers.mjs +0 -0
  62. package/lib/unified-plugin.mjs +0 -0
  63. package/llms.txt +1 -1
  64. package/package.json +11 -7
  65. package/plugins/beginner.json +8 -3
  66. package/plugins/continuous-improvement/.claude-plugin/marketplace.json +2 -2
  67. package/plugins/continuous-improvement/.claude-plugin/plugin.json +2 -2
  68. package/plugins/continuous-improvement/agents/README.md +2 -2
  69. package/plugins/continuous-improvement/bin/backfill.mjs +0 -0
  70. package/plugins/continuous-improvement/bin/gateguard-clear.mjs +53 -0
  71. package/plugins/continuous-improvement/bin/mcp-server.mjs +215 -2
  72. package/plugins/continuous-improvement/bin/observe.mjs +0 -0
  73. package/plugins/continuous-improvement/commands/audit.md +34 -0
  74. package/plugins/continuous-improvement/commands/companion-preference.md +58 -0
  75. package/plugins/continuous-improvement/commands/discipline.md +14 -0
  76. package/plugins/continuous-improvement/commands/distill.md +39 -0
  77. package/plugins/continuous-improvement/commands/goal-check.md +53 -0
  78. package/plugins/continuous-improvement/commands/grill-me.md +40 -0
  79. package/plugins/continuous-improvement/commands/grill-with-docs.md +38 -0
  80. package/plugins/continuous-improvement/commands/handoff.md +42 -0
  81. package/plugins/continuous-improvement/commands/proceed-with-the-recommendation.md +20 -0
  82. package/plugins/continuous-improvement/commands/recall.md +49 -0
  83. package/plugins/continuous-improvement/commands/reconcile.md +47 -0
  84. package/plugins/continuous-improvement/commands/superpowers.md +2 -2
  85. package/plugins/continuous-improvement/commands/verify-install.md +55 -0
  86. package/plugins/continuous-improvement/hooks/companion-preference.mjs +190 -0
  87. package/plugins/continuous-improvement/hooks/gateguard.mjs +60 -25
  88. package/plugins/continuous-improvement/hooks/goal-drift-stop.mjs +183 -0
  89. package/plugins/continuous-improvement/hooks/hooks.json +18 -2
  90. package/plugins/continuous-improvement/hooks/observe.sh +15 -1
  91. package/plugins/continuous-improvement/hooks/route-prompt.mjs +180 -0
  92. package/plugins/continuous-improvement/hooks/route-table.json +35 -0
  93. package/plugins/continuous-improvement/hooks/three-section-close.mjs +134 -132
  94. package/plugins/continuous-improvement/lib/gateguard-state.mjs +137 -0
  95. package/plugins/continuous-improvement/lib/goal-drift-gate.mjs +50 -0
  96. package/plugins/continuous-improvement/lib/goal-state.mjs +285 -0
  97. package/plugins/continuous-improvement/lib/observe-event.mjs +0 -0
  98. package/plugins/continuous-improvement/lib/plugin-metadata.mjs +126 -12
  99. package/plugins/continuous-improvement/lib/recall-index.mjs +175 -0
  100. package/plugins/continuous-improvement/lib/resolve-home-dir.mjs +0 -0
  101. package/plugins/continuous-improvement/lib/skill-distill.mjs +222 -0
  102. package/plugins/continuous-improvement/skills/README.md +8 -0
  103. package/plugins/continuous-improvement/skills/audit/SKILL.md +73 -0
  104. package/plugins/continuous-improvement/skills/deploy-receipt/SKILL.md +13 -17
  105. package/plugins/continuous-improvement/skills/gateguard/SKILL.md +36 -17
  106. package/plugins/continuous-improvement/skills/goal-monitor/SKILL.md +81 -0
  107. package/plugins/continuous-improvement/skills/grill-me/SKILL.md +66 -0
  108. package/plugins/continuous-improvement/skills/grill-with-docs/SKILL.md +252 -0
  109. package/plugins/continuous-improvement/skills/handoff/SKILL.md +59 -0
  110. package/plugins/continuous-improvement/skills/para-memory-files/SKILL.md +1 -1
  111. package/plugins/continuous-improvement/skills/proceed-with-the-recommendation/SKILL.md +82 -6
  112. package/plugins/continuous-improvement/skills/ralph/SKILL.md +1 -0
  113. package/plugins/continuous-improvement/skills/recall/SKILL.md +50 -0
  114. package/plugins/continuous-improvement/skills/reconcile/SKILL.md +80 -0
  115. package/plugins/continuous-improvement/skills/recovery-classification/SKILL.md +1 -0
  116. package/plugins/continuous-improvement/skills/safety-guard/SKILL.md +1 -0
  117. package/plugins/continuous-improvement/skills/skill-distillation/SKILL.md +57 -0
  118. package/plugins/continuous-improvement/skills/state-reconciliation/SKILL.md +1 -0
  119. package/plugins/continuous-improvement/skills/strategic-compact/SKILL.md +1 -0
  120. package/plugins/continuous-improvement/skills/superpowers/SKILL.md +76 -2
  121. package/plugins/continuous-improvement/skills/token-budget-advisor/SKILL.md +1 -1
  122. package/plugins/continuous-improvement/skills/verification-loop/SKILL.md +28 -20
  123. package/plugins/continuous-improvement/skills/wild-risa-balance/SKILL.md +1 -0
  124. package/plugins/continuous-improvement/skills/workspace-surface-audit/SKILL.md +1 -1
  125. package/plugins/continuous-improvement/skills/worktree-safety/SKILL.md +3 -2
  126. package/plugins/expert.json +27 -2
  127. package/skills/README.md +3 -0
  128. package/skills/audit.md +73 -0
  129. package/skills/deploy-receipt.md +13 -17
  130. package/skills/gateguard.md +36 -17
  131. package/skills/goal-monitor.md +81 -0
  132. package/skills/grill-me.md +66 -0
  133. package/skills/grill-with-docs.md +252 -0
  134. package/skills/handoff.md +59 -0
  135. package/skills/para-memory-files.md +1 -1
  136. package/skills/proceed-with-the-recommendation.md +82 -6
  137. package/skills/ralph.md +1 -0
  138. package/skills/recall.md +50 -0
  139. package/skills/reconcile.md +80 -0
  140. package/skills/recovery-classification.md +1 -0
  141. package/skills/safety-guard.md +1 -0
  142. package/skills/skill-distillation.md +57 -0
  143. package/skills/state-reconciliation.md +1 -0
  144. package/skills/strategic-compact.md +1 -0
  145. package/skills/superpowers.md +76 -2
  146. package/skills/token-budget-advisor.md +1 -1
  147. package/skills/verification-loop.md +28 -20
  148. package/skills/wild-risa-balance.md +1 -0
  149. package/skills/workspace-surface-audit.md +1 -1
  150. package/skills/worktree-safety.md +3 -2
@@ -0,0 +1,49 @@
1
+ ---
2
+ name: recall
3
+ description: Search past tool-call observations with BM25 ranking to answer "have I seen this before?" before re-deriving a fix or repeating a mistake. Enforces Law 1 (Research Before Executing).
4
+ ---
5
+
6
+ # /recall — Episodic Search Over Past Sessions
7
+
8
+ Search this project's observation history for relevant prior activity and return the most relevant past tool calls, ranked.
9
+
10
+ ## What it does
11
+
12
+ Builds an in-memory BM25 index over `~/.claude/instincts/<project-hash>/observations.jsonl` and returns the top matches with redacted snippets, relevance scores, and timestamps. Backed by the `ci_recall` MCP tool (expert mode) and the `recall` skill.
13
+
14
+ ## How to invoke
15
+
16
+ ```
17
+ ci_recall query="permission denied push" # top 5 matches
18
+ ci_recall query="jq command not found" k=3 # cap results
19
+ ci_recall query="auth login" since=7d # only the last 7 days
20
+ ```
21
+
22
+ `since` accepts an ISO timestamp or a relative window: `7d`, `24h`, `30m`.
23
+
24
+ ## Output shape
25
+
26
+ ```
27
+ ## Recall: "permission denied push"
28
+
29
+ 2 match(es), most relevant first:
30
+
31
+ - [2026-05-20T10:00:00Z] **Bash** (score 3.41)
32
+ …git push origin main Permission denied: harness blocked direct push to main…
33
+ - ...
34
+ ```
35
+
36
+ ## Privacy
37
+
38
+ Snippets are passed through a secret redactor (AWS keys, JWT-shaped triplets, bearer tokens, KEY/SECRET/TOKEN/PASSWORD assignments, long hex strings) before display.
39
+
40
+ ## Notes
41
+
42
+ - **Lexical, not semantic** — search with the vocabulary that actually appeared in the tool calls; try several phrasings if the first returns nothing.
43
+ - Searches the full captured history, not just the recent window.
44
+
45
+ ## Pairs with
46
+
47
+ - **`recall`** skill — the discipline this command runs.
48
+ - **`continuous-improvement`** (core SKILL.md, Law 1 — Research Before Executing).
49
+ - **`gateguard`** — recall a past failure before clearing a high-risk action.
@@ -0,0 +1,47 @@
1
+ ---
2
+ name: reconcile
3
+ description: Establish git ground truth (branch, status, stashes, worktrees, ahead/behind) before any mutation, halt on protected or destructive operations, and verify a push actually landed. Enforces Law 1 (Research Before Executing).
4
+ ---
5
+
6
+ # /reconcile — Ground-Truth Git State Before You Touch It
7
+
8
+ Read the repo's real state before acting on it: a branch that shifted, a push that did not land, or another session mid-merge will burn a whole session if you assume instead of check.
9
+
10
+ ## What it does
11
+
12
+ Snapshots the full git state in one pass, detects a concurrent writer, classifies the upstream relationship, then acts only on the known state — stopping at every operation that is hard to reverse. Backed by the `reconcile` skill.
13
+
14
+ ## Establish ground truth
15
+
16
+ ```
17
+ git branch --show-current
18
+ git status --porcelain=v1 # but trust git diff --stat for real drift (autocrlf)
19
+ git rev-list --left-right --count @{u}...HEAD # behind / ahead
20
+ git stash list
21
+ git worktree list
22
+ ls .git/MERGE_HEAD .git/rebase-merge .git/rebase-apply 2>/dev/null # in-progress op = another actor; do not race
23
+ ```
24
+
25
+ ## Then act, with gates
26
+
27
+ ```
28
+ even -> safe to branch (confirm local base == origin/base first)
29
+ ahead -> push or PR, AFTER the protected-op gate
30
+ behind -> git pull --ff-only
31
+ diverged -> rebase/merge deliberately; never blind --force
32
+ ```
33
+
34
+ STOP for authorization before: pushing to a protected branch (this repo = feature branch + PR, never direct push to main), `--force` / `--force-with-lease`, `reset --hard`, `clean -fd`, or removing a dirty worktree. Never stage with `git add -A` on a Windows autocrlf tree (it commits phantom line-ending-only changes) — stage by explicit filename.
35
+
36
+ ## Verify the push landed
37
+
38
+ ```
39
+ git ls-remote origin refs/heads/<branch> # remote tip must equal local HEAD, else it did not land
40
+ ```
41
+
42
+ ## Pairs with
43
+
44
+ - **`reconcile`** skill — the discipline this command runs.
45
+ - **`gateguard`** / **`safety-guard`** — runtime + destructive-op guardrails.
46
+ - **`recall`** — recall whether the same git op failed here before.
47
+ - **`audit`** — the loop that often produces the fix `reconcile` then ships.
@@ -7,9 +7,9 @@ description: "Law activator and dispatcher — route the task to the right Law-a
7
7
 
8
8
  `/superpowers` is **the dispatcher**, not a peer skill. It does not do work itself; it routes each user task to the correct Law-aligned specialist so the right discipline fires automatically instead of the agent skipping a step.
9
9
 
10
- The 7 Laws define *what* discipline must be applied. `/superpowers` decides *which specialist* enforces it for this specific task, across five sources installed from this marketplace.
10
+ The 7 Laws define *what* discipline must be applied. `/superpowers` decides *which specialist* enforces it for this specific task, across four sources installed from this marketplace.
11
11
 
12
- ## Routing surface (five sources)
12
+ ## Routing surface (four sources)
13
13
 
14
14
  | Source | Where it lives | Examples of what it routes to |
15
15
  |---|---|---|
@@ -0,0 +1,55 @@
1
+ ---
2
+ name: verify-install
3
+ description: Walk the post-install verification in one shot — confirm slash commands loaded, the gateguard runtime hook fires, and observation capture is recording — then print a single ✓ wired / ✗ missing line.
4
+ ---
5
+
6
+ # /verify-install
7
+
8
+ Replaces the manual post-install dance (restart, run `/discipline`, hand-write a
9
+ hostile prompt, eyeball `/dashboard`) with one command that runs all three
10
+ checks and reports a single line.
11
+
12
+ Run the three checks **in order**. Do not skip a check because an earlier one
13
+ passed — each proves a different layer.
14
+
15
+ ## Check 1 — slash commands loaded
16
+
17
+ If this command is executing, the marketplace did pick the plugin up and the
18
+ command registry loaded it. Record `commands: ✓`.
19
+
20
+ If you are reading this file directly rather than running it as `/verify-install`,
21
+ stop — the command is not registered. The fix is a Claude Code session restart
22
+ (slash commands load on session start). Record `commands: ✗ (restart the session)`.
23
+
24
+ ## Check 2 — gateguard runtime hook fires
25
+
26
+ The runtime gate ships as a PreToolUse hook (`hooks/gateguard.mjs`). Probe it:
27
+ attempt to `Write` a throwaway file at a sandbox path (`./.ci-verify-install-probe.txt`
28
+ with the text `probe`) **without presenting any research first**.
29
+
30
+ - If the hook **blocks** the write with a fact-list reason — the runtime layer is
31
+ wired. Record `gateguard: ✓`. Do not retry the write; the block is the pass.
32
+ - If the write **goes through** with no pause — the hook did not load. Record
33
+ `gateguard: ✗ (hooks/gateguard.mjs not wired — see README → Troubleshooting install)`.
34
+ Delete the probe file if it was created.
35
+
36
+ ## Check 3 — observation capture recording
37
+
38
+ The observation hook appends one row per tool call to
39
+ `~/.claude/instincts/<project-hash>/observations.jsonl`. Read that file (resolve
40
+ `<project-hash>` from the current repo, or check `~/.claude/instincts/global/`).
41
+
42
+ - If it exists and has at least one row — capture is recording. Record `observe: ✓`.
43
+ - If it is missing or empty — record `observe: ✗ (observation hook not recording —
44
+ on Windows confirm Git Bash / WSL is installed, then re-run the installer)`.
45
+
46
+ ## Report
47
+
48
+ Emit exactly one summary line, nothing else after it:
49
+
50
+ - All three passed: `✓ wired — commands, gateguard, observe all confirmed.`
51
+ - Any failed: `✗ <comma-separated failing checks with their fix hints>.`
52
+
53
+ Do not claim "should be fine" for a check you could not actually run. If a check
54
+ is genuinely unrunnable (e.g. no repo context for the project hash), mark it
55
+ `unverified` with the reason rather than `✓`.
@@ -0,0 +1,190 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Runtime PreToolUse companion-preference hook.
4
+ *
5
+ * Reads ~/.claude/settings.json → continuous_improvement.companion_preference
6
+ * and enforces the Companion-Preference Override contract documented in
7
+ * skills/superpowers.md for `Skill` tool calls.
8
+ *
9
+ * ci-first (default): no-op, allow.
10
+ * companions-first : advisory stderr on mapped CI→companion pair; allow.
11
+ * strict-companions : block mapped CI route. Reason names the companion
12
+ * (when installed) or the install hint (when not).
13
+ *
14
+ * Fail-open: any unexpected error reading stdin / parsing settings / probing
15
+ * the filesystem → emit { decision: "allow" } and exit 0. The hook never
16
+ * blocks on its own bugs.
17
+ *
18
+ * Stdin : JSON { tool_name, tool_input }
19
+ * Stdout : JSON { decision: "allow" | "block", reason?: string }
20
+ * Exit : 0 always — decision lives in stdout, never in the exit code.
21
+ *
22
+ * OVERRIDES map must stay row-aligned with skills/superpowers.md
23
+ * § "Which rows the override affects" — drift will surface when the test
24
+ * suite or a follow-up audit walks the table against this map.
25
+ */
26
+ import { execFileSync } from "node:child_process";
27
+ import { createHash } from "node:crypto";
28
+ import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
29
+ import { homedir } from "node:os";
30
+ import { join } from "node:path";
31
+ const OVERRIDES = {
32
+ "tdd-workflow": {
33
+ companion: "superpowers:test-driven-development",
34
+ plugin: "superpowers",
35
+ },
36
+ "verification-loop": {
37
+ companion: "superpowers:verification-before-completion",
38
+ plugin: "superpowers",
39
+ },
40
+ "context-budget": {
41
+ companion: "agent-skills:context-engineering",
42
+ plugin: "agent-skills",
43
+ },
44
+ ralph: {
45
+ companion: "oh-my-claudecode:ultrawork",
46
+ plugin: "oh-my-claudecode",
47
+ },
48
+ "learn-eval": {
49
+ companion: "oh-my-claudecode:retrospective",
50
+ plugin: "oh-my-claudecode",
51
+ },
52
+ };
53
+ function emitAndExit(d) {
54
+ process.stdout.write(`${JSON.stringify(d)}\n`);
55
+ process.exit(0);
56
+ }
57
+ function readStdin() {
58
+ try {
59
+ return readFileSync(0, "utf8");
60
+ }
61
+ catch {
62
+ return "";
63
+ }
64
+ }
65
+ function readMode(home) {
66
+ try {
67
+ const raw = readFileSync(join(home, ".claude", "settings.json"), "utf8");
68
+ const settings = JSON.parse(raw);
69
+ const mode = settings.continuous_improvement?.companion_preference;
70
+ if (mode === "companions-first" || mode === "strict-companions")
71
+ return mode;
72
+ return "ci-first";
73
+ }
74
+ catch {
75
+ return "ci-first";
76
+ }
77
+ }
78
+ function isCompanionInstalled(home, plugin) {
79
+ try {
80
+ return existsSync(join(home, ".claude", "plugins", plugin));
81
+ }
82
+ catch {
83
+ return false;
84
+ }
85
+ }
86
+ function normalizeSkill(skill) {
87
+ return skill.startsWith("ci:") ? skill.slice(3) : skill;
88
+ }
89
+ function resolveHome() {
90
+ return process.env.HOME ?? process.env.USERPROFILE ?? homedir();
91
+ }
92
+ function resolveProjectRoot() {
93
+ const fromEnv = process.env.CLAUDE_PROJECT_DIR;
94
+ if (fromEnv)
95
+ return fromEnv;
96
+ try {
97
+ const root = execFileSync("git", ["rev-parse", "--show-toplevel"], {
98
+ encoding: "utf8",
99
+ stdio: ["ignore", "pipe", "ignore"],
100
+ }).trim();
101
+ if (root)
102
+ return root;
103
+ }
104
+ catch {
105
+ // not in a git repo
106
+ }
107
+ return "global";
108
+ }
109
+ function telemetryPath(home) {
110
+ const hash = createHash("sha256")
111
+ .update(resolveProjectRoot())
112
+ .digest("hex")
113
+ .slice(0, 12);
114
+ return join(home, ".claude", "instincts", hash, "companion-preference.jsonl");
115
+ }
116
+ /**
117
+ * Append one JSONL line per hook decision. Wrapped to fail open: any write
118
+ * error (read-only dir, disk full, race on mkdir) is swallowed and the hook
119
+ * decision proceeds. Telemetry must never block tool calls.
120
+ */
121
+ function writeTelemetry(home, event) {
122
+ try {
123
+ const path = telemetryPath(home);
124
+ const dir = join(path, "..");
125
+ if (!existsSync(dir))
126
+ mkdirSync(dir, { recursive: true });
127
+ appendFileSync(path, `${JSON.stringify(event)}\n`);
128
+ }
129
+ catch {
130
+ // fail-open — telemetry failure never changes the decision
131
+ }
132
+ }
133
+ function main() {
134
+ const raw = readStdin();
135
+ let payload;
136
+ try {
137
+ payload = JSON.parse(raw);
138
+ }
139
+ catch {
140
+ emitAndExit({ decision: "allow" });
141
+ }
142
+ if (payload.tool_name !== "Skill") {
143
+ emitAndExit({ decision: "allow" });
144
+ }
145
+ const skill = payload.tool_input?.skill;
146
+ if (typeof skill !== "string" || skill.length === 0) {
147
+ emitAndExit({ decision: "allow" });
148
+ }
149
+ const normalized = normalizeSkill(skill);
150
+ const override = OVERRIDES[normalized];
151
+ if (!override) {
152
+ emitAndExit({ decision: "allow" });
153
+ }
154
+ const home = resolveHome();
155
+ const mode = readMode(home);
156
+ const installed = isCompanionInstalled(home, override.plugin);
157
+ const baseEvent = {
158
+ ts: new Date().toISOString(),
159
+ hook: "companion-preference",
160
+ ci_skill: normalized,
161
+ companion: override.companion,
162
+ plugin: override.plugin,
163
+ companion_installed: installed,
164
+ };
165
+ if (mode === "ci-first") {
166
+ // Shadow row: what companions-first would have done. This is the data
167
+ // set that earns a future default-flip decision.
168
+ writeTelemetry(home, { ...baseEvent, mode, action: "observation" });
169
+ emitAndExit({ decision: "allow" });
170
+ }
171
+ if (mode === "companions-first") {
172
+ process.stderr.write(`[continuous-improvement] companion_preference=companions-first → prefer \`${override.companion}\` over \`ci:${normalized}\`.\n`);
173
+ writeTelemetry(home, { ...baseEvent, mode, action: "advisory" });
174
+ emitAndExit({ decision: "allow" });
175
+ }
176
+ // strict-companions: always block; reason depends on install state.
177
+ if (installed) {
178
+ writeTelemetry(home, { ...baseEvent, mode, action: "block" });
179
+ emitAndExit({
180
+ decision: "block",
181
+ reason: `companion_preference=strict-companions: route to \`${override.companion}\` instead of \`ci:${normalized}\`. The CI fallback is suppressed by your setting.`,
182
+ });
183
+ }
184
+ writeTelemetry(home, { ...baseEvent, mode, action: "block-not-installed" });
185
+ emitAndExit({
186
+ decision: "block",
187
+ reason: `companion_preference=strict-companions: companion plugin \`${override.plugin}\` is not installed. Install with \`/plugin install ${override.plugin}@continuous-improvement\` or relax the setting to \`companions-first\` or \`ci-first\` in ~/.claude/settings.json.`,
188
+ });
189
+ }
190
+ main();
@@ -9,8 +9,10 @@
9
9
  * Three-stage gate per skills/gateguard.md:
10
10
  * - DENY : first mutating tool call per file, with fact-list reason
11
11
  * - FORCE : agent presents facts (model-side; out of band)
12
- * - ALLOW : retry once `_gateguard_facts_presented: true` is set or the
13
- * per-file marker is recorded in session state
12
+ * - ALLOW : retry once the per-file marker is recorded in session state
13
+ * (harness-portable, written out of band via Bash), or
14
+ * `_gateguard_facts_presented: true` is set where the harness
15
+ * forwards unknown tool params
14
16
  *
15
17
  * Read-only and exploratory tools (Read, Grep, Glob, routine Bash) bypass
16
18
  * unconditionally. Destructive Bash gates EVERY call, not just first.
@@ -18,12 +20,15 @@
18
20
  * V1 honest limitations (see src/lib/gateguard-state.mts header):
19
21
  * honor-system flag, state-file deletion, parallel-hook race.
20
22
  *
21
- * MultiEdit handling (V1): gates on edits[0].file_path only. Per-file
22
- * batching is not implemented TODO: extend to gate every entry in
23
- * edits[]. Tracked in issue #106 acceptance criteria item 5.
23
+ * MultiEdit handling gates every edited file individually. The hook blocks
24
+ * unless all edited paths are already cleared, or the agent presents facts
25
+ * for the call and the hook records clearance for each edited path.
26
+ * Block reasons now name the whole batch instead of just the first uncleared
27
+ * path.
24
28
  */
25
29
  import { readFileSync } from "node:fs";
26
- import { isCapReached, loadState, markFileCleared, resolveSessionDir, saveState, } from "../lib/gateguard-state.mjs";
30
+ import { join } from "node:path";
31
+ import { MAX_CLEARED_FILES, canonicalizeFileKey, isCapReached, isFileCleared, loadState, markFileCleared, resolveSessionDir, saveState, } from "../lib/gateguard-state.mjs";
27
32
  const TOOL_ROUTE = {
28
33
  Read: "allow",
29
34
  Grep: "allow",
@@ -71,30 +76,54 @@ function classifyTool(toolName, toolInput) {
71
76
  }
72
77
  return "allow";
73
78
  }
74
- function extractFilePath(toolInput) {
79
+ function extractFilePaths(toolInput) {
75
80
  if (typeof toolInput.file_path === "string")
76
- return toolInput.file_path;
77
- // MultiEdit V1: first edit's file_path is the canonical key.
81
+ return [toolInput.file_path];
78
82
  if (Array.isArray(toolInput.edits) && toolInput.edits.length > 0) {
79
- const first = toolInput.edits[0];
80
- if (first && typeof first.file_path === "string")
81
- return first.file_path;
83
+ return toolInput.edits
84
+ .map((edit) => (edit && typeof edit.file_path === "string" ? edit.file_path : ""))
85
+ .filter((filePath) => filePath !== "");
82
86
  }
83
87
  if (typeof toolInput.command === "string")
84
- return toolInput.command;
85
- return "";
88
+ return [toolInput.command];
89
+ return [];
86
90
  }
87
- function buildMutatingFileReason(toolName, filePath) {
91
+ // The call site only reads this inside the block branch, where at least one
92
+ // path is uncleared; an all-cleared batch returns "" and is never consumed.
93
+ function firstUnclearedFilePath(toolInput, state) {
94
+ return extractFilePaths(toolInput).find((path) => !isFileCleared(state, path)) ?? "";
95
+ }
96
+ function countDistinctNewFilePaths(filePaths, state) {
97
+ return new Set(filePaths.filter((path) => !isFileCleared(state, path)).map((path) => canonicalizeFileKey(path))).size;
98
+ }
99
+ function formatFileTarget(filePaths) {
100
+ const nonEmpty = filePaths.filter((path) => path !== "");
101
+ if (nonEmpty.length === 0)
102
+ return "<unknown>";
103
+ if (nonEmpty.length === 1)
104
+ return nonEmpty[0];
105
+ return `${nonEmpty.length} files (${nonEmpty.join(", ")})`;
106
+ }
107
+ function buildMutatingFileReason(toolName, filePaths, stateFilePath) {
108
+ const target = formatFileTarget(filePaths);
109
+ const pathList = filePaths.filter((p) => p !== "");
110
+ const jsonArray = (pathList.length > 0 ? pathList : [target]).map((p) => JSON.stringify(p)).join(", ");
111
+ const cliArgs = (pathList.length > 0 ? pathList : [target]).map((p) => JSON.stringify(p)).join(" ");
88
112
  return [
89
- `Before ${toolName === "Write" ? "creating" : "editing"} ${filePath || "<unknown>"}, present these facts:`,
113
+ `Before ${toolName === "Write" ? "creating" : "editing"} ${target}, present these facts:`,
90
114
  "",
91
115
  " 1. List ALL files that import/require this file (use Grep)",
92
116
  " 2. List the public functions/classes affected by this change",
93
117
  " 3. If this file reads/writes data files, show field names, structure, and date format",
94
118
  " 4. Quote the user's current instruction verbatim",
95
119
  "",
96
- "After presenting the facts, retry with `_gateguard_facts_presented: true` in tool_input,",
97
- "or with the same file_path after a previous clearance has been recorded for this session.",
120
+ "Then clear the gate and retry the same call. Any one of:",
121
+ ` A. MCP tool: ci_gateguard_clear {file_paths: [${jsonArray}]}`,
122
+ ` B. CLI (Bash, never gated): node "\${CLAUDE_PLUGIN_ROOT}/bin/gateguard-clear.mjs" ${cliArgs}`,
123
+ ` C. Manual: append each path to "cleared_files" in ${stateFilePath} via a non-destructive Bash write.`,
124
+ " Clearance matches regardless of drive-letter case or path separator.",
125
+ " (On harnesses that forward unknown tool params you may instead retry with",
126
+ " `_gateguard_facts_presented: true`; Claude Code's strict schema rejects that, so use A/B/C.)",
98
127
  ].join("\n");
99
128
  }
100
129
  function buildDestructiveBashReason(command) {
@@ -110,7 +139,7 @@ function buildDestructiveBashReason(command) {
110
139
  }
111
140
  function buildCapReachedReason() {
112
141
  return [
113
- "Gateguard session clearance cap reached (50 distinct files).",
142
+ `Gateguard session clearance cap reached (${MAX_CLEARED_FILES} distinct files).`,
114
143
  "Start a new Claude Code session to reset the gate. The cap exists to bound",
115
144
  "stuck-loop or rogue-agent clearance from compounding within a single session.",
116
145
  ].join("\n");
@@ -150,22 +179,28 @@ function main() {
150
179
  }
151
180
  // mutating-file
152
181
  const sessionDir = resolveSessionDir();
182
+ const stateFilePath = join(sessionDir, "gateguard-session.json");
153
183
  const state = loadState(sessionDir);
154
- const filePath = extractFilePath(toolInput);
184
+ const filePaths = extractFilePaths(toolInput);
185
+ const filePath = firstUnclearedFilePath(toolInput, state);
155
186
  const factsFlagged = toolInput._gateguard_facts_presented === true;
156
- const alreadyCleared = filePath !== "" && filePath in state.cleared_files;
187
+ const alreadyCleared = filePaths.length > 0 && filePaths.every((path) => isFileCleared(state, path));
188
+ const newFileCount = countDistinctNewFilePaths(filePaths, state);
157
189
  if (!factsFlagged && !alreadyCleared) {
158
- emit({ decision: "block", reason: buildMutatingFileReason(toolName, filePath) });
190
+ emit({ decision: "block", reason: buildMutatingFileReason(toolName, filePaths.length > 0 ? filePaths : [filePath], stateFilePath) });
159
191
  return;
160
192
  }
161
193
  if (factsFlagged && !alreadyCleared) {
162
- if (isCapReached(state)) {
194
+ if (isCapReached(state) || Object.keys(state.cleared_files).length + newFileCount > MAX_CLEARED_FILES) {
163
195
  emit({ decision: "block", reason: buildCapReachedReason() });
164
196
  return;
165
197
  }
166
- if (filePath !== "") {
167
- saveState(sessionDir, markFileCleared(state, filePath));
198
+ let nextState = state;
199
+ for (const path of filePaths) {
200
+ nextState = markFileCleared(nextState, path);
168
201
  }
202
+ if (filePaths.length > 0)
203
+ saveState(sessionDir, nextState);
169
204
  }
170
205
  emit({ decision: "allow" });
171
206
  }