@yasaswy.nagavolu/agents 0.17.2 → 0.17.3

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/bin/cli.js CHANGED
@@ -624,6 +624,12 @@ async function runUninstall(argv) {
624
624
  `${result.filesKeptUserEdited.join(', ')}`
625
625
  );
626
626
  }
627
+ if (result.filesKeptShared.length > 0) {
628
+ console.log(
629
+ ` Kept ${result.filesKeptShared.length} shared file(s) still claimed by other installed bundles: ` +
630
+ `${result.filesKeptShared.map((f) => `${f.file} (now owned by ${f.owner})`).join(', ')}`
631
+ );
632
+ }
627
633
  if (result.mcpKeptUserEdited.length > 0) {
628
634
  console.log(
629
635
  ` Kept ${result.mcpKeptUserEdited.length} MCP server entry(ies) edited since install: ` +
@@ -86,6 +86,19 @@
86
86
  {
87
87
  "path": "skills/ship-the-code",
88
88
  "kind": "skill"
89
+ },
90
+ {
91
+ "path": "proxy/agents_env.py",
92
+ "kind": "hook",
93
+ "note": "Shared secrets-resolution library imported by this bundle's scripts — not wired to an event itself. Already deployed by other bundles too; safe to double-claim, install.js is idempotent per-file."
94
+ },
95
+ {
96
+ "path": "agents/scribe-agent",
97
+ "kind": "agent",
98
+ "exclude": [
99
+ "test_scribe_runner.py"
100
+ ],
101
+ "note": "ship.py loads scribe_runner.py by file path for its GitLab helpers (skills/ship-the-code/ship.py scribe_agent_path); scribe_runner.py launches scribe_item_read.py/scribe_item_write.py, so the folder ships whole. Also claimed by agent-orchestration; safe to double-claim."
89
102
  }
90
103
  ],
91
104
  "deps": [],
@@ -507,6 +520,11 @@
507
520
  "path": "skills/launch-litellm",
508
521
  "kind": "skill",
509
522
  "note": "Starts/restarts the LiteLLM proxy this bundle depends on, in a visible window outside the caller's process tree."
523
+ },
524
+ {
525
+ "path": "proxy/git_shell_parse.py",
526
+ "kind": "hook",
527
+ "note": "Shared shell-command parsing helpers imported by execution_worker_review_gate.py (without it that hook dies with ModuleNotFoundError on every Bash call) — not wired to an event itself. Also claimed by self-infra; safe to double-claim."
510
528
  }
511
529
  ],
512
530
  "deps": [
@@ -928,6 +946,19 @@
928
946
  "path": "proxy/project_resolver.py",
929
947
  "kind": "infra",
930
948
  "note": "Shared GitLab-project-slug resolution extracted from conclusion_scribe_hook.py, imported by gitlab_api.py, prd_closing_gate.py, tracker_proof_gate.py, and prd_registry.py — pure functions, no hook-event I/O of its own."
949
+ },
950
+ {
951
+ "path": "proxy/route_lock.py",
952
+ "kind": "hook",
953
+ "note": "Shared route-classification library imported by agent_model_guard.py, shared_worktree_revert_guard.py and validate_dispatch_tiers.py — not wired to an event itself. Also claimed by agent-orchestration; safe to double-claim."
954
+ },
955
+ {
956
+ "path": "agents/scribe-agent",
957
+ "kind": "agent",
958
+ "exclude": [
959
+ "test_scribe_runner.py"
960
+ ],
961
+ "note": "Module under test in test_scribe_runner.py (claimed above) plus the scribe_item_read.py/scribe_item_write.py scripts scribe_runner.py launches. Also claimed by agent-orchestration; safe to double-claim."
931
962
  }
932
963
  ],
933
964
  "deps": [
@@ -945,6 +976,16 @@
945
976
  {
946
977
  "path": "scripts",
947
978
  "kind": "infra"
979
+ },
980
+ {
981
+ "path": "proxy/agents_env.py",
982
+ "kind": "hook",
983
+ "note": "Shared secrets-resolution library imported by this bundle's scripts — not wired to an event itself. Already deployed by other bundles too; safe to double-claim, install.js is idempotent per-file."
984
+ },
985
+ {
986
+ "path": "proxy/project_resolver.py",
987
+ "kind": "hook",
988
+ "note": "Shared GitLab-project-slug resolution imported by prd_registry.py — pure functions, no hook-event I/O. Also claimed by self-infra; safe to double-claim."
948
989
  }
949
990
  ],
950
991
  "deps": [],
@@ -1022,6 +1063,19 @@
1022
1063
  "command": "python ~/.claude/proxy/grilling_format_gate.py"
1023
1064
  }
1024
1065
  ]
1066
+ },
1067
+ {
1068
+ "path": "proxy/agents_env.py",
1069
+ "kind": "hook",
1070
+ "note": "Shared secrets-resolution library imported by this bundle's scripts — not wired to an event itself. Already deployed by other bundles too; safe to double-claim, install.js is idempotent per-file."
1071
+ },
1072
+ {
1073
+ "path": "agents/scribe-agent",
1074
+ "kind": "agent",
1075
+ "exclude": [
1076
+ "test_scribe_runner.py"
1077
+ ],
1078
+ "note": "gitlab_phase.py loads scribe_runner.py by file path for its GitLab helpers; scribe_runner.py launches scribe_item_read.py/scribe_item_write.py, so the folder ships whole. Also claimed by agent-orchestration; safe to double-claim."
1025
1079
  }
1026
1080
  ],
1027
1081
  "deps": [],
@@ -1060,6 +1114,11 @@
1060
1114
  "test_council_common.py"
1061
1115
  ],
1062
1116
  "note": "Shared council preflight/exit-code contract — imported at runtime via parents[1]/lib by visual_diagnosis.py and visual_review_council_fanout.py."
1117
+ },
1118
+ {
1119
+ "path": "proxy/agents_env.py",
1120
+ "kind": "hook",
1121
+ "note": "Shared secrets-resolution library imported by this bundle's scripts — not wired to an event itself. Already deployed by other bundles too; safe to double-claim, install.js is idempotent per-file."
1063
1122
  }
1064
1123
  ],
1065
1124
  "deps": [
@@ -172,7 +172,7 @@ Tests: `proxy/tests/test_shared_worktree_revert_guard.py` (real temp git repos,
172
172
  **What it does**
173
173
  Compensating control for any leaf agent whose frontmatter declares `dispatch_tier: mandatory-review` (see `route_lock.py` / `agent_model_guard.py` above) — such a leaf is auto-dispatchable with no `@tag` and no route lock, so the control moves to commit time instead: if a mandatory-review agent has run in this farm-style project and no `clears_review: true` agent has run since (`route_lock.is_review_pending`), any `git commit` is denied until the reviewer dispatches (which clears the flag via `route_lock.clear_pending_review`).
174
174
 
175
- Scoped to `git commit` invocations via both the settings.json `"if"` clause below AND its own token-based check on the command (shared `git_shell_parse.find_git_subcommand`/`unwind_shell_wrapper` primitives, not a bare regex — resolves `git commit` through `-C`/`-c` flags and unwinds the same wrapper shapes `shared_worktree_revert_guard.py` does) — belt-and-suspenders, so it's harmless to leave unconditionally wired to the `Bash` matcher.
175
+ Scoped to `git commit` invocations via both the settings.json handler-level `"if"` clause below AND its own token-based check on the command (shared `git_shell_parse.find_git_subcommand`/`unwind_shell_wrapper` primitives, not a bare regex — resolves `git commit` through `-C`/`-c` flags and unwinds the same wrapper shapes `shared_worktree_revert_guard.py` does) — belt-and-suspenders, so it's harmless to leave unconditionally wired to the `Bash` matcher.
176
176
 
177
177
  **Manual setup**
178
178
 
@@ -181,13 +181,14 @@ Wire into PreToolUse in `~/.claude/settings.json`:
181
181
  ```json
182
182
  "PreToolUse": [{
183
183
  "matcher": "Bash",
184
- "if": "Bash(git commit *)",
185
184
  "hooks": [
186
- {"type": "command", "command": "python C:/Users/<you>/.claude/proxy/execution_worker_review_gate.py"}
185
+ {"type": "command", "if": "Bash(git commit *)", "command": "python C:/Users/<you>/.claude/proxy/execution_worker_review_gate.py"}
187
186
  ]
188
187
  }]
189
188
  ```
190
189
 
190
+ `if` goes on the hook handler (inside `hooks[]`, beside `type`/`command`), not on the matcher group — Claude Code silently ignores a group-level `if` and the hook then fires on every `Bash` call.
191
+
191
192
  **Verify**
192
193
 
193
194
  ```bash
@@ -17,8 +17,10 @@ reviewer-subagent) has run since (route_lock.is_review_pending), any
17
17
  pending-review flag via route_lock.clear_pending_review).
18
18
 
19
19
  Wired as a PreToolUse hook on the "Bash" matcher in ~/.claude/settings.json,
20
- scoped with an "if": "Bash(git commit *)" permission-rule clause so it only
21
- runs for commit invocations. That scoping is belt-and-suspenders: this script
20
+ scoped with an "if": "Bash(git commit *)" permission-rule clause on the hook
21
+ handler (inside the matcher group's "hooks" list, beside "type"/"command" --
22
+ a group-level "if" is silently ignored) so it only runs for commit
23
+ invocations. That scoping is belt-and-suspenders: this script
22
24
  also does its own detection of a `git ... commit` invocation on the command
23
25
  and is a no-op for anything else, so it is safe to run unconditionally too.
24
26
 
package/lib/claims.js ADDED
@@ -0,0 +1,57 @@
1
+ 'use strict';
2
+
3
+ const fs = require('node:fs');
4
+ const path = require('node:path');
5
+ const { walk } = require('./fsutil');
6
+ const { bundleKeysInLedger } = require('./ledger');
7
+
8
+ /**
9
+ * The ledger records ONE owner per deployed file (`entries[rel].bundle`, the
10
+ * first bundle that wrote it), but manifest.json lets several bundles claim
11
+ * the same target path. Ownership is therefore not a claim registry: to know
12
+ * whether a file is still wanted after its owner goes away, ask the manifest
13
+ * which OTHER installed bundles claim the same path.
14
+ */
15
+
16
+ /**
17
+ * Every target path (relative to the install base, POSIX-style) that
18
+ * `bundle`'s file items deploy — same walk/exclude/targetPath rules as
19
+ * install.js. mcp/setting items deploy no files, and an item whose source is
20
+ * missing from this repo checkout claims nothing (install/update own that error).
21
+ */
22
+ function bundleTargetPaths(bundle, repoRoot) {
23
+ const targets = new Set();
24
+ for (const item of bundle.items) {
25
+ if (item.kind === 'mcp' || item.kind === 'setting') continue;
26
+ const srcRoot = path.join(repoRoot, ...item.path.split('/'));
27
+ if (!fs.existsSync(srcRoot)) continue;
28
+
29
+ const excluded = new Set(item.exclude || []);
30
+ const srcIsFile = fs.statSync(srcRoot).isFile();
31
+ const targetPrefix = item.targetPath || item.path;
32
+ for (const relFile of walk(srcRoot)) {
33
+ if (excluded.has(relFile)) continue;
34
+ targets.add(srcIsFile ? targetPrefix : `${targetPrefix}/${relFile}`);
35
+ }
36
+ }
37
+ return targets;
38
+ }
39
+
40
+ /**
41
+ * Map of relTarget -> key of the first (manifest order) still-installed bundle
42
+ * other than `excludingKey` that claims it. "Installed" means the ledger has
43
+ * entries/wiring/mcp for the bundle (bundleKeysInLedger).
44
+ */
45
+ function otherClaimants({ manifest, repoRoot, ledger, excludingKey }) {
46
+ const installed = new Set(bundleKeysInLedger(ledger));
47
+ const claimants = new Map();
48
+ for (const bundle of manifest.bundles) {
49
+ if (bundle.key === excludingKey || !installed.has(bundle.key)) continue;
50
+ for (const relTarget of bundleTargetPaths(bundle, repoRoot)) {
51
+ if (!claimants.has(relTarget)) claimants.set(relTarget, bundle.key);
52
+ }
53
+ }
54
+ return claimants;
55
+ }
56
+
57
+ module.exports = { bundleTargetPaths, otherClaimants };
package/lib/uninstall.js CHANGED
@@ -3,6 +3,7 @@
3
3
  const fs = require('node:fs');
4
4
  const path = require('node:path');
5
5
  const { loadManifest, findBundle } = require('./manifest');
6
+ const { otherClaimants } = require('./claims');
6
7
  const { loadLedger, saveLedger } = require('./ledger');
7
8
  const { sha256File, removeEmptyParents } = require('./fsutil');
8
9
  const { unwireBundle, unwireSettingsBundle } = require('./wiring');
@@ -12,6 +13,24 @@ const { uninstallComponentsForBundle } = require('./components');
12
13
 
13
14
  class UninstallError extends Error {}
14
15
 
16
+ const wiringKey = (r) => JSON.stringify([r.event, r.matcher || null, r.if || null, r.command]);
17
+
18
+ /**
19
+ * Drop from `ledger.wiring[bundleKey]` every hook record that another bundle's
20
+ * wiring also holds, so unwireBundle() (which removes the settings.json entry
21
+ * for each record it is given) leaves that shared hook in place.
22
+ */
23
+ function keepWiringRecordedByOthers(ledger, bundleKey) {
24
+ const own = (ledger.wiring && ledger.wiring[bundleKey]) || [];
25
+ if (own.length === 0) return;
26
+ const others = new Set();
27
+ for (const [key, records] of Object.entries(ledger.wiring)) {
28
+ if (key === bundleKey) continue;
29
+ for (const r of records) others.add(wiringKey(r));
30
+ }
31
+ ledger.wiring[bundleKey] = own.filter((r) => !others.has(wiringKey(r)));
32
+ }
33
+
15
34
  /**
16
35
  * Remove everything `installBundle` put down for one bundle: files whose
17
36
  * on-disk hash still matches the ledger (user-edited files are left in
@@ -19,13 +38,20 @@ class UninstallError extends Error {}
19
38
  * and exactly the settings.json hook entries this bundle wired (via
20
39
  * wiring.js's `unwireBundle`, scoped to `ledger.wiring[bundleKey]`).
21
40
  *
41
+ * A file another still-installed bundle also claims in the manifest is NOT
42
+ * deleted: the ledger keeps one owner per file (whoever installed it first),
43
+ * so the entry is handed to that other bundle instead (hash baseline
44
+ * untouched, so drift/missing stay detectable) and reported as
45
+ * `filesKeptShared`. Likewise a hook wiring record that another installed
46
+ * bundle also recorded is left wired. The last claimant to go removes the file.
47
+ *
22
48
  * Unknown bundle key -> UninstallError listing every bundle the manifest
23
49
  * declares (same convention as installBundle's InstallError). A bundle
24
50
  * that's valid but was never installed at targetBase (no ledger entries, no
25
51
  * recorded wiring) is a no-op, not an error.
26
52
  */
27
53
  function uninstallBundle({ packageRoot, bundleKey, targetBase, cliVersion, mcpConfigPath }) {
28
- const { manifest } = loadManifest(packageRoot);
54
+ const { manifest, manifestPath } = loadManifest(packageRoot);
29
55
  const bundle = findBundle(manifest, bundleKey);
30
56
  if (!bundle) {
31
57
  const available = manifest.bundles.map((b) => b.key);
@@ -39,10 +65,25 @@ function uninstallBundle({ packageRoot, bundleKey, targetBase, cliVersion, mcpCo
39
65
 
40
66
  const filesRemoved = [];
41
67
  const filesKeptUserEdited = [];
68
+ const filesKeptShared = [];
69
+
70
+ const claimants = otherClaimants({
71
+ manifest,
72
+ repoRoot: path.dirname(manifestPath),
73
+ ledger,
74
+ excludingKey: bundle.key,
75
+ });
42
76
 
43
77
  for (const [relTarget, entry] of Object.entries(ledger.entries)) {
44
78
  if (entry.bundle !== bundle.key) continue;
45
79
 
80
+ const heir = claimants.get(relTarget);
81
+ if (heir) {
82
+ entry.bundle = heir;
83
+ filesKeptShared.push({ file: relTarget, owner: heir });
84
+ continue;
85
+ }
86
+
46
87
  const destFile = path.join(resolvedTargetBase, ...relTarget.split('/'));
47
88
  if (fs.existsSync(destFile)) {
48
89
  const currentHash = sha256File(destFile);
@@ -60,6 +101,7 @@ function uninstallBundle({ packageRoot, bundleKey, targetBase, cliVersion, mcpCo
60
101
  delete ledger.entries[relTarget];
61
102
  }
62
103
 
104
+ keepWiringRecordedByOthers(ledger, bundle.key);
63
105
  const wiringResult = unwireBundle(bundle.key, { targetBase: resolvedTargetBase, ledger });
64
106
  const mcpResult = unwireMcpBundle(bundle.key, { targetBase: resolvedTargetBase, configPath: mcpConfigPath, ledger });
65
107
  const settingsResult = unwireSettingsBundle(bundle.key, { targetBase: resolvedTargetBase, ledger });
@@ -78,6 +120,7 @@ function uninstallBundle({ packageRoot, bundleKey, targetBase, cliVersion, mcpCo
78
120
  targetBase: resolvedTargetBase,
79
121
  filesRemoved,
80
122
  filesKeptUserEdited,
123
+ filesKeptShared,
81
124
  hooksRemoved: wiringResult.removed,
82
125
  mcpRemoved: mcpResult.removed,
83
126
  mcpKeptUserEdited: mcpResult.keptUserEdited,
@@ -86,6 +129,7 @@ function uninstallBundle({ packageRoot, bundleKey, targetBase, cliVersion, mcpCo
86
129
  noop:
87
130
  filesRemoved.length === 0 &&
88
131
  filesKeptUserEdited.length === 0 &&
132
+ filesKeptShared.length === 0 &&
89
133
  wiringResult.removed.length === 0 &&
90
134
  mcpResult.removed.length === 0 &&
91
135
  mcpResult.keptUserEdited.length === 0 &&
package/lib/update.js CHANGED
@@ -4,6 +4,7 @@ const fs = require('node:fs');
4
4
  const path = require('node:path');
5
5
  const { loadManifest, findBundle } = require('./manifest');
6
6
  const { loadLedger, saveLedger, bundleKeysInLedger } = require('./ledger');
7
+ const { otherClaimants } = require('./claims');
7
8
  const { sha256File, walk, copyFileEnsuringDir, removeEmptyParents } = require('./fsutil');
8
9
  const {
9
10
  wireItems,
@@ -140,6 +141,26 @@ function planFileUpdates(currentFiles, { targetBase, ledger, bundleTag }) {
140
141
  return plan;
141
142
  }
142
143
 
144
+ /**
145
+ * A file this bundle no longer ships is only really gone if no other installed
146
+ * bundle still claims it (the ledger has a single owner per file, so "owned by
147
+ * this bundle and not in its items" does not mean "unwanted"). For those files,
148
+ * hand the ledger entry to the other bundle and drop them from the plan so
149
+ * applyFilePlan neither deletes nor untracks them.
150
+ */
151
+ function handOverSharedUpstreamRemovals(plan, { manifest, repoRoot, ledger, bundleKey }) {
152
+ if (plan.removedUpstream.length === 0 && plan.keptUpstreamUserEdited.length === 0) return;
153
+ const claimants = otherClaimants({ manifest, repoRoot, ledger, excludingKey: bundleKey });
154
+ const handOver = (item) => {
155
+ const heir = claimants.get(item.relTarget);
156
+ if (!heir) return true;
157
+ ledger.entries[item.relTarget].bundle = heir;
158
+ return false;
159
+ };
160
+ plan.removedUpstream = plan.removedUpstream.filter(handOver);
161
+ plan.keptUpstreamUserEdited = plan.keptUpstreamUserEdited.filter(handOver);
162
+ }
163
+
143
164
  /** planFileUpdates() for a bundle's own (non-mcp) items. */
144
165
  function planBundleUpdate(bundle, { repoRoot, targetBase, ledger }) {
145
166
  const currentFiles = collectBundleFiles(bundle, repoRoot);
@@ -313,8 +334,9 @@ async function applyFilePlan(plan, { ledger, tag, targetBase, timestamp, cliVers
313
334
  return summary;
314
335
  }
315
336
 
316
- async function updateOneBundle(bundle, { repoRoot, targetBase, ledger, timestamp, cliVersion, strategy, io, isTTY, log, pythonChecker, mcpConfigPath }) {
337
+ async function updateOneBundle(bundle, { manifest, repoRoot, targetBase, ledger, timestamp, cliVersion, strategy, io, isTTY, log, pythonChecker, mcpConfigPath }) {
317
338
  const plan = planBundleUpdate(bundle, { repoRoot, targetBase, ledger });
339
+ handOverSharedUpstreamRemovals(plan, { manifest, repoRoot, ledger, bundleKey: bundle.key });
318
340
  const summary = await applyFilePlan(plan, {
319
341
  ledger,
320
342
  tag: bundle.key,
@@ -464,6 +486,7 @@ async function updateBundles({
464
486
  }
465
487
  // eslint-disable-next-line no-await-in-loop
466
488
  const result = await updateOneBundle(bundle, {
489
+ manifest,
467
490
  repoRoot,
468
491
  targetBase: resolvedTargetBase,
469
492
  ledger,
package/lib/wiring.js CHANGED
@@ -87,10 +87,83 @@ function asWiringList(wiring) {
87
87
  return Array.isArray(wiring) ? wiring : [wiring];
88
88
  }
89
89
 
90
- function blockKeyMatches(block, matcher, ifClause) {
91
- const blockMatcher = block.matcher || null;
92
- const blockIf = block.if || null;
93
- return blockMatcher === (matcher || null) && blockIf === (ifClause || null);
90
+ /**
91
+ * Where a hook's `if` permission-rule clause lives. Claude Code reads it on
92
+ * the individual hook HANDLER (inside `hooks[]`, beside `type`/`command`):
93
+ * `{"matcher":"Bash","hooks":[{"type":"command","if":"Bash(git *)","command":"..."}]}`.
94
+ * Released CLI versions 0.17.0-0.17.2 wrote it on the matcher GROUP instead,
95
+ * where Claude Code silently ignores it (the hook fired on every match). The
96
+ * effective `if` of a handler is therefore its own `if`, falling back to the
97
+ * enclosing group's so hooks written by ANY released version are still
98
+ * recognised (matching, dedupe, unwire, prune); healLegacyGroupIf() migrates
99
+ * the legacy placement to the handler.
100
+ */
101
+ function handlerIf(block, hook) {
102
+ return (hook && hook.if) || block.if || null;
103
+ }
104
+
105
+ function blockMatcherMatches(block, matcher) {
106
+ return (block.matcher || null) === (matcher || null);
107
+ }
108
+
109
+ function ownedKey(event, matcher, command) {
110
+ return [event, matcher || '', command].join('\u0000');
111
+ }
112
+
113
+ function expectedIfsByKey(expectedRecords) {
114
+ const expectedByKey = new Map();
115
+ for (const rec of expectedRecords) {
116
+ const key = ownedKey(rec.event, rec.matcher, rec.command);
117
+ if (!expectedByKey.has(key)) expectedByKey.set(key, new Set());
118
+ expectedByKey.get(key).add(rec.if || null);
119
+ }
120
+ return expectedByKey;
121
+ }
122
+
123
+ function hasHookEvents(settings) {
124
+ return settings.hooks && typeof settings.hooks === 'object' && !Array.isArray(settings.hooks);
125
+ }
126
+
127
+ /**
128
+ * Migrate a legacy group-level `if` (written by 0.17.0-0.17.2, ignored by
129
+ * Claude Code) onto the handler(s) it was meant to scope. Only handlers the
130
+ * CURRENT manifest owns (same event, matcher, command AND the same `if` the
131
+ * manifest declares) are touched; a non-owned handler in the same group is
132
+ * left exactly as it was. The group's `if` is dropped only when every handler
133
+ * in it now carries its own, so a group holding a hand-added handler keeps
134
+ * whatever it had. Mutates `settings` in place, never touches disk.
135
+ */
136
+ function healLegacyGroupIf(settings, expectedRecords) {
137
+ const healed = [];
138
+ if (!hasHookEvents(settings)) return healed;
139
+ const expectedByKey = expectedIfsByKey(expectedRecords);
140
+
141
+ for (const event of Object.keys(settings.hooks)) {
142
+ const eventArray = settings.hooks[event];
143
+ if (!Array.isArray(eventArray)) continue;
144
+ for (const block of eventArray) {
145
+ if (!block || !block.if || !Array.isArray(block.hooks)) continue;
146
+ const matcher = block.matcher || null;
147
+ let healedHere = 0;
148
+ for (const hook of block.hooks) {
149
+ if (hook.if) continue;
150
+ const expectedIfs = expectedByKey.get(ownedKey(event, matcher, hook.command));
151
+ if (expectedIfs && expectedIfs.has(block.if)) {
152
+ hook.if = block.if;
153
+ healed.push({ event, matcher, if: block.if, command: hook.command });
154
+ healedHere += 1;
155
+ }
156
+ }
157
+ if (healedHere > 0 && block.hooks.every((hook) => hook.if)) {
158
+ delete block.if;
159
+ }
160
+ }
161
+ }
162
+ return healed;
163
+ }
164
+
165
+ function isRecordHandler(block, hook, record) {
166
+ return hook.command === record.command && handlerIf(block, hook) === (record.if || null);
94
167
  }
95
168
 
96
169
  function recordKey(record) {
@@ -141,7 +214,9 @@ function ensureSettingsBackup(targetBase, ledger, timestamp) {
141
214
  * (and only) what this bundle wired later.
142
215
  *
143
216
  * Idempotent: re-running with the same items produces zero duplicate hook
144
- * entries — the dedupe key is (event, matcher, if, resolvedCommand). Every
217
+ * entries — the dedupe key is (event, matcher, if, resolvedCommand). The
218
+ * `if` is written on the hook handler (see handlerIf), and a group-level
219
+ * `if` left by 0.17.0-0.17.2 is healed onto the handler in the same pass. Every
145
220
  * unrelated key already in settings.json (other hook events/matchers,
146
221
  * top-level settings) is preserved verbatim — the whole parsed object is
147
222
  * round-tripped through JSON.parse/stringify and only the blocks we own are
@@ -204,27 +279,41 @@ function wireItems(items, { targetBase, bundleKey, ledger, timestamp, pythonChec
204
279
  }
205
280
  const eventArray = settings.hooks[wiring.event];
206
281
 
207
- let block = eventArray.find((b) => blockKeyMatches(b, wiring.matcher, wiring.if));
282
+ const record = { event: wiring.event, matcher: wiring.matcher || null, if: wiring.if || null, command: resolvedCommand };
283
+ ownedThisRun.push(record);
284
+
285
+ // A group-level `if` written by 0.17.0-0.17.2 is moved onto this
286
+ // hook's handler first, so the lookup below finds it instead of
287
+ // registering a second copy next to the legacy group.
288
+ if (healLegacyGroupIf(settings, [record]).length > 0) {
289
+ mutated = true;
290
+ }
291
+
292
+ // Groups are keyed by matcher alone; `if` is per-handler. A group that
293
+ // still carries a (legacy, unhealable) group-level `if` is not reused.
294
+ let block = eventArray.find((b) => blockMatcherMatches(b, wiring.matcher) && !b.if);
208
295
  if (!block) {
209
296
  block = { hooks: [] };
210
297
  if (wiring.matcher) block.matcher = wiring.matcher;
211
- if (wiring.if) block.if = wiring.if;
212
298
  eventArray.push(block);
213
299
  }
214
300
  if (!Array.isArray(block.hooks)) {
215
301
  block.hooks = [];
216
302
  }
217
303
 
218
- const record = { event: wiring.event, matcher: wiring.matcher || null, if: wiring.if || null, command: resolvedCommand };
219
- ownedThisRun.push(record);
220
-
221
- const exists = block.hooks.some((h) => h.command === resolvedCommand);
304
+ const exists = eventArray.some(
305
+ (b) =>
306
+ blockMatcherMatches(b, wiring.matcher) &&
307
+ Array.isArray(b.hooks) &&
308
+ b.hooks.some((h) => h.command === resolvedCommand && handlerIf(b, h) === record.if)
309
+ );
222
310
  if (exists) {
223
311
  alreadyWired.push({ path: item.path, ...record });
224
312
  continue;
225
313
  }
226
314
 
227
315
  const entry = { type: wiring.type, command: resolvedCommand };
316
+ if (wiring.if) entry.if = wiring.if;
228
317
  if (wiring.timeout) entry.timeout = wiring.timeout;
229
318
  block.hooks.push(entry);
230
319
  wired.push({ path: item.path, ...record });
@@ -272,10 +361,10 @@ function unwireBundle(bundleKey, { targetBase, ledger }) {
272
361
 
273
362
  for (let i = eventArray.length - 1; i >= 0; i -= 1) {
274
363
  const block = eventArray[i];
275
- if (!blockKeyMatches(block, record.matcher, record.if) || !Array.isArray(block.hooks)) continue;
364
+ if (!blockMatcherMatches(block, record.matcher) || !Array.isArray(block.hooks)) continue;
276
365
 
277
366
  const beforeLen = block.hooks.length;
278
- block.hooks = block.hooks.filter((h) => h.command !== record.command);
367
+ block.hooks = block.hooks.filter((h) => !isRecordHandler(block, h, record));
279
368
  if (block.hooks.length !== beforeLen) {
280
369
  removed.push(record);
281
370
  mutated = true;
@@ -372,9 +461,9 @@ function pruneStaleWiring(bundleKey, { targetBase, ledger, expectedRecords }) {
372
461
 
373
462
  for (let i = eventArray.length - 1; i >= 0; i -= 1) {
374
463
  const block = eventArray[i];
375
- if (!blockKeyMatches(block, record.matcher, record.if) || !Array.isArray(block.hooks)) continue;
464
+ if (!blockMatcherMatches(block, record.matcher) || !Array.isArray(block.hooks)) continue;
376
465
  const beforeLen = block.hooks.length;
377
- block.hooks = block.hooks.filter((h) => h.command !== record.command);
466
+ block.hooks = block.hooks.filter((h) => !isRecordHandler(block, h, record));
378
467
  if (block.hooks.length !== beforeLen) mutated = true;
379
468
  if (block.hooks.length === 0) eventArray.splice(i, 1);
380
469
  }
@@ -411,16 +500,21 @@ function pruneStaleWiring(bundleKey, { targetBase, ledger, expectedRecords }) {
411
500
  * anything the CLI did not put there".
412
501
  *
413
502
  * "Duplicate" means: within one (event, matcher) pair, the same resolved
414
- * `command` string is registered in more than one block. Since a block's
415
- * `if` clause is the only thing that can differ between such blocks, and an
416
- * absent `if` (unconditional) always fires on a superset of what any `if`
417
- * value would gate, every block-registration whose `if` does not match one
418
- * the manifest currently declares for that exact (event, matcher, command)
419
- * is redundant and is removed; the block(s) whose `if` DOES match a
420
- * manifest-declared record for that key survive untouched. If NONE of a
421
- * group's `if` values match what the manifest expects (e.g. the manifest's
422
- * wiring changed shape entirely since these were written), the whole group
423
- * is left alone rather than guessing which one to keep.
503
+ * `command` string is registered more than once. Since a handler's `if`
504
+ * clause (see handlerIf: handler-level, or the legacy group-level placement
505
+ * of 0.17.0-0.17.2) is the only thing that can differ between such
506
+ * registrations, and an absent `if` (unconditional) always fires on a
507
+ * superset of what any `if` value would gate, every registration whose `if`
508
+ * does not match one the manifest currently declares for that exact (event,
509
+ * matcher, command) is redundant and is removed; the registration(s) whose
510
+ * `if` DOES match a manifest-declared record for that key survive (one per
511
+ * distinct `if` value -- exact repeats collapse). If NONE of a key's `if`
512
+ * values match what the manifest expects (e.g. the manifest's wiring changed
513
+ * shape entirely since these were written), the whole set is left alone
514
+ * rather than guessing which one to keep.
515
+ *
516
+ * Before comparing, a legacy group-level `if` on an owned handler is moved
517
+ * onto the handler (healLegacyGroupIf) -- returned as `healed`.
424
518
  *
425
519
  * This is why two real multi-registrations legitimately survive:
426
520
  * - recall_hook.py: registered under two different EVENTS
@@ -437,50 +531,59 @@ function pruneStaleWiring(bundleKey, { targetBase, ledger, expectedRecords }) {
437
531
  * decides whether/when to save and back up.
438
532
  */
439
533
  function dedupeOwnedHookWiring(settings, expectedRecords) {
440
- if (!settings.hooks || typeof settings.hooks !== 'object' || Array.isArray(settings.hooks)) {
441
- return { removed: [], settingsChanged: false };
534
+ if (!hasHookEvents(settings)) {
535
+ return { removed: [], healed: [], settingsChanged: false };
442
536
  }
443
537
 
444
- const expectedByKey = new Map();
445
- for (const rec of expectedRecords) {
446
- const key = `${rec.event}${rec.matcher || ''}${rec.command}`;
447
- if (!expectedByKey.has(key)) expectedByKey.set(key, new Set());
448
- expectedByKey.get(key).add(rec.if || null);
449
- }
538
+ // Move any legacy group-level `if` onto its handler BEFORE comparing, so a
539
+ // healed registration and a same-command unconditional leftover are seen
540
+ // side by side and the leftover collapses.
541
+ const healed = healLegacyGroupIf(settings, expectedRecords);
542
+ const expectedByKey = expectedIfsByKey(expectedRecords);
450
543
 
451
544
  const removed = [];
452
- let mutated = false;
545
+ let mutated = healed.length > 0;
453
546
 
454
547
  for (const event of Object.keys(settings.hooks)) {
455
548
  const eventArray = settings.hooks[event];
456
549
  if (!Array.isArray(eventArray)) continue;
457
550
 
458
- // key -> [{blockIdx, matcher, ifValue, command}], one entry per block
551
+ // key -> [{blockIdx, matcher, ifValue, command}], one entry per handler
459
552
  // that registers this CLI-owned (matcher, command) pair.
460
553
  const groups = new Map();
461
554
  eventArray.forEach((block, blockIdx) => {
462
555
  if (!Array.isArray(block.hooks)) return;
463
556
  const matcher = block.matcher || null;
464
- const ifValue = block.if || null;
465
557
  for (const hook of block.hooks) {
466
- const key = `${event}${matcher || ''}${hook.command}`;
558
+ const key = ownedKey(event, matcher, hook.command);
467
559
  if (!expectedByKey.has(key)) continue; // not CLI-owned -- hands off
468
560
  if (!groups.has(key)) groups.set(key, []);
469
- groups.get(key).push({ blockIdx, matcher, ifValue, command: hook.command });
561
+ groups.get(key).push({ blockIdx, matcher, ifValue: handlerIf(block, hook), command: hook.command, hook });
470
562
  }
471
563
  });
472
564
 
473
- // blockIdx -> Set(commands) to strip from that block.
565
+ // blockIdx -> Set(handler objects) to strip from that block.
474
566
  const stripByBlock = new Map();
475
567
  for (const [key, occurrences] of groups) {
476
568
  if (occurrences.length < 2) continue;
477
569
  const expectedIfs = expectedByKey.get(key);
478
570
  const toRemove = occurrences.filter((occ) => !expectedIfs.has(occ.ifValue));
479
- if (toRemove.length === 0 || toRemove.length === occurrences.length) continue;
571
+ if (toRemove.length === occurrences.length) continue;
572
+
573
+ // Of the registrations that DO match the manifest, keep the first per
574
+ // `if` value; an exact repeat (e.g. a healed group-level `if` next to
575
+ // an already handler-level copy) is redundant too.
576
+ const keptIfs = new Set();
577
+ for (const occ of occurrences) {
578
+ if (!expectedIfs.has(occ.ifValue)) continue;
579
+ if (keptIfs.has(occ.ifValue)) toRemove.push(occ);
580
+ else keptIfs.add(occ.ifValue);
581
+ }
582
+ if (toRemove.length === 0) continue;
480
583
 
481
584
  for (const occ of toRemove) {
482
585
  if (!stripByBlock.has(occ.blockIdx)) stripByBlock.set(occ.blockIdx, new Set());
483
- stripByBlock.get(occ.blockIdx).add(occ.command);
586
+ stripByBlock.get(occ.blockIdx).add(occ.hook);
484
587
  removed.push({ event, matcher: occ.matcher, if: occ.ifValue, command: occ.command });
485
588
  }
486
589
  }
@@ -492,7 +595,7 @@ function dedupeOwnedHookWiring(settings, expectedRecords) {
492
595
  if (!stripSet) continue;
493
596
  const block = eventArray[i];
494
597
  const before = block.hooks.length;
495
- block.hooks = block.hooks.filter((hook) => !stripSet.has(hook.command));
598
+ block.hooks = block.hooks.filter((hook) => !stripSet.has(hook));
496
599
  if (block.hooks.length !== before) mutated = true;
497
600
  if (block.hooks.length === 0) {
498
601
  eventArray.splice(i, 1);
@@ -501,7 +604,7 @@ function dedupeOwnedHookWiring(settings, expectedRecords) {
501
604
  if (eventArray.length === 0) delete settings.hooks[event];
502
605
  }
503
606
 
504
- return { removed, settingsChanged: mutated };
607
+ return { removed, healed, settingsChanged: mutated };
505
608
  }
506
609
 
507
610
  /**
@@ -528,13 +631,13 @@ function expectedWiringRecordsForManifest(manifest, targetBase, { pythonChecker
528
631
  function repairDuplicateHookWiring(manifest, { targetBase, ledger, timestamp, pythonChecker }) {
529
632
  const expectedRecords = expectedWiringRecordsForManifest(manifest, targetBase, { pythonChecker });
530
633
  const settings = loadSettings(targetBase);
531
- const { removed, settingsChanged } = dedupeOwnedHookWiring(settings, expectedRecords);
634
+ const { removed, healed, settingsChanged } = dedupeOwnedHookWiring(settings, expectedRecords);
532
635
  if (!settingsChanged) {
533
- return { removed, settingsChanged: false, backupFile: null };
636
+ return { removed, healed, settingsChanged: false, backupFile: null };
534
637
  }
535
638
  const backupFile = ensureSettingsBackup(targetBase, ledger || {}, timestamp);
536
639
  saveSettings(targetBase, settings);
537
- return { removed, settingsChanged: true, backupFile };
640
+ return { removed, healed, settingsChanged: true, backupFile };
538
641
  }
539
642
 
540
643
  function settingsRecordKey(record) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yasaswy.nagavolu/agents",
3
- "version": "0.17.2",
3
+ "version": "0.17.3",
4
4
  "description": "CLI for installing the yasaswy.nagavolu agent/skill/hook bundle. `install` opens an interactive bundle menu in a TTY (or `--bundle <key> --yes` for non-interactive installs), with hash-tracked idempotent deploys, automatic hook wiring into settings.json, and masked secret prompting. `update` reconciles installed bundles against the current source (hash-tracked: silent overwrite, conflict diff+prompt, or --theirs/--keep-mine). `uninstall` removes a bundle's files and wiring. `secrets` re-runs secret prompting for already-installed bundles.",
5
5
  "license": "MIT",
6
6
  "type": "commonjs",