@webpieces/agent-workflow-rules 0.4.954 → 0.4.955

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webpieces/agent-workflow-rules",
3
- "version": "0.4.954",
3
+ "version": "0.4.955",
4
4
  "description": "Independent workflow guards, guard hook, installation and shim management for AI coding agents.",
5
5
  "type": "commonjs",
6
6
  "main": "./src/index.js",
@@ -24,20 +24,20 @@
24
24
  "directory": "packages/tooling/agent-workflow-rules"
25
25
  },
26
26
  "dependencies": {
27
- "@webpieces/hook-runtime": "0.4.954",
28
- "@webpieces/rules-config": "0.4.954",
27
+ "@webpieces/hook-runtime": "0.4.955",
28
+ "@webpieces/rules-config": "0.4.955",
29
29
  "inversify": "7.10.4",
30
30
  "reflect-metadata": "0.2.2",
31
- "@webpieces/tooling-common": "0.4.954",
32
- "@webpieces/repo-workflow-core": "0.4.954",
31
+ "@webpieces/tooling-common": "0.4.955",
32
+ "@webpieces/repo-workflow-core": "0.4.955",
33
33
  "tslib": "2.8.1",
34
- "@webpieces/rules-sdk": "0.4.954"
34
+ "@webpieces/rules-sdk": "0.4.955"
35
35
  },
36
36
  "publishConfig": {
37
37
  "access": "public"
38
38
  },
39
39
  "devDependencies": {
40
- "@webpieces/tooling-testkit": "0.4.954"
40
+ "@webpieces/tooling-testkit": "0.4.955"
41
41
  },
42
42
  "types": "./src/index.d.ts",
43
43
  "bin": {
@@ -12,7 +12,7 @@ const l0_allowlist_1 = require("./l0-allowlist");
12
12
  function seedOrSyncConfig(projectRoot) {
13
13
  const filename = path.join(projectRoot, rules_config_1.CONFIG_FILENAME);
14
14
  if (!fs.existsSync(filename)) {
15
- throw new tooling_common_1.InformAiError(`Create webpieces.config.json with explicit rulePacks, commands, excludePaths and match-rules, then rerun ${l0_allowlist_1.INSTALL_HOOKS_CMD}: it writes the owners' recommended seeds into the declared files for review. Installed packages are never inferred as selected policy packs.`);
15
+ throw new tooling_common_1.InformAiError(`Create webpieces.config.json with "${rules_config_1.CONFIG_DOCUMENTATION_KEY}": "${rules_config_1.CONFIG_DOCUMENTATION_PATH}", explicit rulePacks, commands, excludePaths and match-rules, then rerun ${l0_allowlist_1.INSTALL_HOOKS_CMD}: it writes the owners' recommended seeds into the declared files for review. Installed packages are never inferred as selected policy packs.`);
16
16
  }
17
17
  const configFile = new rules_config_1.ConfigFile(), raw = configFile.readRawConfig(filename);
18
18
  if (raw.rulePacks === undefined) {
@@ -1 +1 @@
1
- {"version":3,"file":"setup-config.js","sourceRoot":"","sources":["../../../../../../packages/tooling/agent-workflow-rules/src/bin/setup-config.ts"],"names":[],"mappings":";;AAQA,4CAoBC;;AA5BD,oDAA8B;AAC9B,wDAAkC;AAClC,8DAAsE;AACtE,0DAAqG;AACrG,iDAAmD;AAEnD,wGAAwG;AACxG,gHAAgH;AAChH,SAAgB,gBAAgB,CAAC,WAAmB;IAChD,MAAM,QAAQ,GAAG,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE,8BAAe,CAAC,CAAC;IACzD,IAAI,CAAC,EAAE,CAAC,UAAU,CAAC,QAAQ,CAAC,EAAE,CAAC;QAC3B,MAAM,IAAI,8BAAa,CACnB,4GAA4G,gCAAiB,+IAA+I,CAC/Q,CAAC;IACN,CAAC;IACD,MAAM,UAAU,GAAG,IAAI,yBAAU,EAAE,EAC/B,GAAG,GAAG,UAAU,CAAC,aAAa,CAAC,QAAQ,CAAC,CAAC;IAC7C,IAAI,GAAG,CAAC,SAAS,KAAK,SAAS,EAAE,CAAC;QAC9B,MAAM,IAAI,8BAAa,CACnB,4QAA4Q,gCAAiB,GAAG,CACnS,CAAC;IACN,CAAC;IACD,MAAM,OAAO,GAAG,IAAI,2BAAY,CAAC,UAAU,EAAE,IAAI,8BAAe,EAAE,EAAE,IAAI,2BAAU,EAAE,CAAC,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC;IACvG,OAAO,CAAC,GAAG,CACP,OAAO,CAAC,MAAM;QACV,CAAC,CAAC,qDAAqD,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE;QAC3E,CAAC,CAAC,uEAAuE,CAChF,CAAC;AACN,CAAC","sourcesContent":["import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { AtomicFile, InformAiError } from '@webpieces/tooling-common';\nimport { ConfigFile, CONFIG_FILENAME, PackPolicyFiles, RulePackSync } from '@webpieces/rules-config';\nimport { INSTALL_HOOKS_CMD } from './l0-allowlist';\n\n/** Installation seeds the declared owner files; a flat root config must first declare its rulePacks. */\n// webpieces-disable no-function-outside-class -- DI-free installer composition must work before hooks are wired\nexport function seedOrSyncConfig(projectRoot: string): void {\n const filename = path.join(projectRoot, CONFIG_FILENAME);\n if (!fs.existsSync(filename)) {\n throw new InformAiError(\n `Create webpieces.config.json with explicit rulePacks, commands, excludePaths and match-rules, then rerun ${INSTALL_HOOKS_CMD}: it writes the owners' recommended seeds into the declared files for review. Installed packages are never inferred as selected policy packs.`,\n );\n }\n const configFile = new ConfigFile(),\n raw = configFile.readRawConfig(filename);\n if (raw.rulePacks === undefined) {\n throw new InformAiError(\n `The flat root config is retired. Add \"rulePacks\": [{\"package\":\"<pack>\",\"config\":\".webpieces-config/rules/<pack>.json\"}, ...] to webpieces.config.json, move each \"rules\"/\"hookGuards\" entry into the owner file its pack declares, delete those two sections, then rerun ${INSTALL_HOOKS_CMD}.`,\n );\n }\n const changed = new RulePackSync(configFile, new PackPolicyFiles(), new AtomicFile()).run(projectRoot);\n console.log(\n changed.length\n ? `[ai-hooks] Review explicit owner config changes:\\n${changed.join('\\n')}`\n : '[ai-hooks] Declared owner config files already hold every owned rule.',\n );\n}\n"]}
1
+ {"version":3,"file":"setup-config.js","sourceRoot":"","sources":["../../../../../../packages/tooling/agent-workflow-rules/src/bin/setup-config.ts"],"names":[],"mappings":";;AAQA,4CAoBC;;AA5BD,oDAA8B;AAC9B,wDAAkC;AAClC,8DAAsE;AACtE,0DAA0J;AAC1J,iDAAmD;AAEnD,wGAAwG;AACxG,gHAAgH;AAChH,SAAgB,gBAAgB,CAAC,WAAmB;IAChD,MAAM,QAAQ,GAAG,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE,8BAAe,CAAC,CAAC;IACzD,IAAI,CAAC,EAAE,CAAC,UAAU,CAAC,QAAQ,CAAC,EAAE,CAAC;QAC3B,MAAM,IAAI,8BAAa,CACnB,sCAAsC,uCAAwB,OAAO,wCAAyB,6EAA6E,gCAAiB,+IAA+I,CAC9U,CAAC;IACN,CAAC;IACD,MAAM,UAAU,GAAG,IAAI,yBAAU,EAAE,EAC/B,GAAG,GAAG,UAAU,CAAC,aAAa,CAAC,QAAQ,CAAC,CAAC;IAC7C,IAAI,GAAG,CAAC,SAAS,KAAK,SAAS,EAAE,CAAC;QAC9B,MAAM,IAAI,8BAAa,CACnB,4QAA4Q,gCAAiB,GAAG,CACnS,CAAC;IACN,CAAC;IACD,MAAM,OAAO,GAAG,IAAI,2BAAY,CAAC,UAAU,EAAE,IAAI,8BAAe,EAAE,EAAE,IAAI,2BAAU,EAAE,CAAC,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC;IACvG,OAAO,CAAC,GAAG,CACP,OAAO,CAAC,MAAM;QACV,CAAC,CAAC,qDAAqD,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE;QAC3E,CAAC,CAAC,uEAAuE,CAChF,CAAC;AACN,CAAC","sourcesContent":["import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { AtomicFile, InformAiError } from '@webpieces/tooling-common';\nimport { ConfigFile, CONFIG_FILENAME, CONFIG_DOCUMENTATION_KEY, CONFIG_DOCUMENTATION_PATH, PackPolicyFiles, RulePackSync } from '@webpieces/rules-config';\nimport { INSTALL_HOOKS_CMD } from './l0-allowlist';\n\n/** Installation seeds the declared owner files; a flat root config must first declare its rulePacks. */\n// webpieces-disable no-function-outside-class -- DI-free installer composition must work before hooks are wired\nexport function seedOrSyncConfig(projectRoot: string): void {\n const filename = path.join(projectRoot, CONFIG_FILENAME);\n if (!fs.existsSync(filename)) {\n throw new InformAiError(\n `Create webpieces.config.json with \"${CONFIG_DOCUMENTATION_KEY}\": \"${CONFIG_DOCUMENTATION_PATH}\", explicit rulePacks, commands, excludePaths and match-rules, then rerun ${INSTALL_HOOKS_CMD}: it writes the owners' recommended seeds into the declared files for review. Installed packages are never inferred as selected policy packs.`,\n );\n }\n const configFile = new ConfigFile(),\n raw = configFile.readRawConfig(filename);\n if (raw.rulePacks === undefined) {\n throw new InformAiError(\n `The flat root config is retired. Add \"rulePacks\": [{\"package\":\"<pack>\",\"config\":\".webpieces-config/rules/<pack>.json\"}, ...] to webpieces.config.json, move each \"rules\"/\"hookGuards\" entry into the owner file its pack declares, delete those two sections, then rerun ${INSTALL_HOOKS_CMD}.`,\n );\n }\n const changed = new RulePackSync(configFile, new PackPolicyFiles(), new AtomicFile()).run(projectRoot);\n console.log(\n changed.length\n ? `[ai-hooks] Review explicit owner config changes:\\n${changed.join('\\n')}`\n : '[ai-hooks] Declared owner config files already hold every owned rule.',\n );\n}\n"]}
package/src/bin/setup.js CHANGED
@@ -370,11 +370,11 @@ async function main() {
370
370
  // Anchor the install at the repo root (git toplevel — webpieces.config.json may not exist yet on
371
371
  // a first install), never a subdir cwd, so `.webpieces`/hooks/config all land at the root.
372
372
  const projectRoot = new rules_config_1.RepoRootFinder().resolveRepoRoot(process.cwd());
373
- (0, setup_config_1.seedOrSyncConfig)(projectRoot);
374
373
  // Always refreshed: it explains why a retired key is rejected rather than accepted, and what to do
375
374
  // about it — which is exactly what an agent needs on the run where a migration just moved keys out
376
375
  // from under its config.
377
376
  (0, rules_config_1.writeTemplate)(projectRoot, rules_config_1.CONFIG_POLICY_DOC);
377
+ (0, setup_config_1.seedOrSyncConfig)(projectRoot);
378
378
  scaffoldCiGate(projectRoot);
379
379
  const targets = installTargets(projectRoot);
380
380
  // Non-interactive: `--target=project|project-personal|global|none` installs BOTH hooks at that
@@ -1 +1 @@
1
- {"version":3,"file":"setup.js","sourceRoot":"","sources":["../../../../../../packages/tooling/agent-workflow-rules/src/bin/setup.ts"],"names":[],"mappings":";;;AAuJA,wCAaC;AAMD,0BAGC;AAwBD,8BA8CC;AAyCD,kDAWC;AAID,wCAGC;AAUD,kCAOC;AA2CD,oBA4CC;;AAtZD,+CAAyB;AACzB,mDAA6B;AAC7B,2BAA6B;AAC7B,uCAA2C;AAE3C,0DAAmH;AAEnH,iCAA2D;AAC3D,qDAA6E;AAC7E,2DAA2O;AAE3O,+CAAqE;AACrE,+CAAgD;AAChD,uGAAuG;AACvG,yFAAyF;AACzF,iDAAkD;AAGlD,8EAA8E;AAC9E,iGAAiG;AACjG,kGAAkG;AAClG,wGAAwG;AACxG,oGAAoG;AACpG,0FAA0F;AAC1F,8EAA8E;AAC9E,MAAM,QAAQ;IAEG;IACA;IACA;IAHb,YACa,GAAW,EACX,KAAa,EACb,GAAW;QAFX,QAAG,GAAH,GAAG,CAAQ;QACX,UAAK,GAAL,KAAK,CAAQ;QACb,QAAG,GAAH,GAAG,CAAQ;IACrB,CAAC;IAEJ;;;;;;;OAOG;IACH,UAAU,CAAC,MAAqB;QAC5B,OAAO,MAAM,CAAC,OAAO,CAAC,UAAU,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IAC/C,CAAC;IAED,6FAA6F;IAC7F,qGAAqG;IACrG,+FAA+F;IAC/F,mGAAmG;IACnG,UAAU,CAAC,MAAqB,EAAE,WAAmB;QACjD,IAAI,MAAM,CAAC,QAAQ,EAAE,CAAC;YAClB,OAAO,QAAQ,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE,cAAc,EAAE,MAAM,EAAE,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;QAC9E,CAAC;QACD,OAAO,MAAM,CAAC,OAAO,CAAC,WAAW,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IAChD,CAAC;CACJ;AAED,6EAA6E;AAC7E,gKAAgK;AAChK,SAAS,SA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* as fs from 'fs';\nimport * as path from 'path';\nimport { homedir } from 'os';\nimport { createInterface } from 'readline';\n\nimport { RepoRootFinder, writeTemplate, writeTemplateIfMissing, CONFIG_POLICY_DOC } from '@webpieces/rules-config';\n\nimport { SHIM_MARKER, shimPath, renderShim } from './shim';\nimport { REVIEWER_AGENT_MARKER, writeReviewerAgent } from './reviewer-agent';\nimport { HookRegistrationEntry, GUARDS_BIN, LEGACY_GUARANTEE_ROOT_MARKER, RULES_BIN, addHookEntry, applyManagedEnv, readSettings, writeSettings, HarnessRegistration, CLAUDE_REGISTRATION, CODEX_REGISTRATION } from './hook-registration';\nimport type { ClaudeSettings, HookCommand, HookEntry } from './settings-shape';\nimport { BASH_CWD_ENV_KEY, BASH_CWD_ENV_VALUE } from './managed-env';\nimport { CodexTrustProbe } from './codex-trust';\n// The config half of the installer — seeding and migrating webpieces.config.json. Split for size along\n// the seam that was already there: this module is hook WIRING, that one is CONFIG SHAPE.\nimport { seedOrSyncConfig } from './setup-config';\n\n\n// ---------------------------------------------------------------------------\n// The two independently-installable GUARD hooks. Each can land in a different settings file (see\n// InstallTarget) so a team can ship the guards while a developer keeps the code-style rules local\n// while iterating. Both are registered ABSOLUTE via $CLAUDE_PROJECT_DIR, so the MAIN tree governs every\n// tree. There used to be a third — the L-1 hook, which existed only to keep a RELATIVE registration\n// resolvable; it is retired, and purgeRetiredGuaranteeRoot() removes anything left of it.\n// ---------------------------------------------------------------------------\nclass HookSpec {\n constructor(\n readonly key: string,\n readonly label: string,\n readonly bin: string,\n ) {}\n\n /**\n * WHICH TOOL NAMES this hook must see, in the harness the target belongs to.\n *\n * It is a lookup on the target rather than a field on the spec because the answer is not a property\n * of the hook: the rules hook matches `Write|Edit|MultiEdit` under Claude Code and `apply_patch`\n * under Codex, and a single stored matcher is exactly how `.codex/hooks.json` came to be registered\n * against tool names Codex never emits.\n */\n matcherFor(target: InstallTarget): string {\n return target.harness.matcherFor(this.bin);\n }\n\n // Absolute targets (global) need the exact path to this repo's bin — no ~/.webpieces bridge.\n // Project targets get the ABSOLUTE shim command, anchored on the harness's own project-root variable\n // (see HarnessRegistration.shimCommand): it resolves from ANY cwd, so a hook can never fail to\n // launch — which per the hooks reference would be exit 127, a SILENT UNGUARDED ALLOW, not a block.\n commandFor(target: InstallTarget, projectRoot: string): string {\n if (target.absolute) {\n return `node ${path.join(projectRoot, 'node_modules', '.bin', this.bin)}`;\n }\n return target.harness.shimCommand(this.bin);\n }\n}\n\n// Idempotent: re-running the installer overwrites the managed shim in place.\n// webpieces-disable no-function-outside-class -- existing CLI/shim bootstrap function moved intact; it must remain callable without constructing a DI container\nfunction writeShim(projectRoot: string): void {\n const target = shimPath(projectRoot);\n fs.mkdirSync(path.dirname(target), { recursive: true });\n fs.writeFileSync(target, renderShim(), { mode: 0o755 });\n // writeFileSync's mode is only applied when creating the file; force it on overwrite too.\n fs.chmodSync(target, 0o755);\n}\n\n// webpieces-disable no-function-outside-class -- existing CLI/shim bootstrap function moved intact; it must remain callable without constructing a DI container\nfunction removeShim(projectRoot: string): void {\n const target = shimPath(projectRoot);\n if (fs.existsSync(target)) fs.rmSync(target);\n}\n\n// A managed .sh is shared by the project hooks — only safe to delete once no project settings file\n// references it anymore (i.e. the other hook was moved to global or uninstalled too).\n// webpieces-disable no-function-outside-class -- setup.ts is deliberately DI-free (it must run on a half-written node_modules; see install-entry.ts), so every function here is module-scope\nfunction markerReferenced(targets: InstallTarget[], marker: string): boolean {\n return targets.some((t: InstallTarget) => {\n const entries = readSettings(t.settingsPath).hooks?.PreToolUse ?? [];\n return entries.some((e: HookEntry) => e.hooks.some((h: HookCommand) => h.command.includes(marker)));\n });\n}\n\n/**\n * Remove every trace of the RETIRED L-1 hook (`guarantee-root.sh`) — the file and any PreToolUse entry\n * still pointing at it. REMOVAL ONLY: nothing here can ever write one back.\n *\n * L-1 existed to guarantee a RELATIVE guard-hook path resolved, by refusing any `cd` that would park the\n * shell in a subdirectory. The guard hooks are ABSOLUTE now (`$CLAUDE_PROJECT_DIR/...`), so they resolve\n * from any cwd and the guarantee is structural — there is nothing left to police, and the subdirectory\n * denial that used to pay for it is gone with it.\n */\n// webpieces-disable no-function-outside-class -- setup.ts is deliberately DI-free (it must run on a half-written node_modules; see install-entry.ts), so every function here is module-scope\nfunction purgeRetiredGuaranteeRoot(targets: InstallTarget[], projectRoot: string): void {\n for (const target of targets) {\n const settings = readSettings(target.settingsPath);\n if (removeHookByMarker(settings, LEGACY_GUARANTEE_ROOT_MARKER)) {\n writeSettings(target.settingsPath, settings);\n console.log(` 🗑️ removed the retired L-1 guarantee-root hook from ${target.label}`);\n }\n }\n const legacyFile = path.join(projectRoot, LEGACY_GUARANTEE_ROOT_MARKER);\n if (fs.existsSync(legacyFile)) {\n fs.rmSync(legacyFile, { force: true });\n console.log(' 🗑️ deleted the retired .claude/webpieces/guarantee-root.sh');\n }\n}\n\nexport class InstallTarget {\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(\n readonly choice: string,\n readonly label: string,\n readonly settingsPath: string,\n readonly absolute: boolean,\n /**\n * WHICH HARNESS this file arms — it decides the matcher and the shim anchor written into it.\n *\n * REQUIRED, with no default, and the absence of one is the point. A default of\n * CLAUDE_REGISTRATION would make \"omit the harness\" mean \"Claude Code\" — a widening that is an\n * ABSENCE rather than a token, so a target built for Codex without it would silently carry\n * `Write|Edit|MultiEdit` and `$CLAUDE_PROJECT_DIR`, which is EXACTLY the silently-unguarded\n * state this class exists to end, and ungreppable besides.\n */\n readonly harness: HarnessRegistration,\n ) {}\n}\n\n// The bin names come from ./hook-registration, which is also what the drift check and wp-upgrade-shim\n// compare against — one spelling of the registration, or the installer and the validator can disagree\n// about what \"installed\" means. The MATCHER is not here: it belongs to the harness, not the hook (see\n// HookSpec.matcherFor).\nexport const RULES_HOOK = new HookSpec('rules', 'Rules hook (code-style validation)', RULES_BIN);\nexport const GUARDS_HOOK = new HookSpec('guards', 'Guards hook (git/PR/branch protection)', GUARDS_BIN);\n\n/**\n * Every file the installer can write, keyed by the CHOICE a human makes.\n *\n * TWO TARGETS SHARE CHOICE `1`, and that is the design rather than an oversight: \"the project, committed,\n * for the team\" is ONE intention, and a repo that is worked on by both harnesses needs both files armed\n * to mean it. Splitting it into two questions would let a human answer them differently and end up with a\n * repo where Codex is silently unguarded — which is the state this whole change exists to end. Every\n * caller selects by choice id (`targets.filter(t => t.choice === answer)`), never by index, so adding a\n * harness adds a row and changes no numbering.\n *\n * `2` (personal) and `3` (global) stay Claude-only because neither has a Codex counterpart: Codex reads\n * one repo-local `hooks.json` and has no personal or home-scoped hook file.\n *\n * `homeDir` is injectable so tests can point the global target at a temp dir instead of the real\n * ~/.claude/settings.json (a unit test must never write the user's actual global settings).\n */\n// webpieces-disable no-function-outside-class -- existing CLI/shim bootstrap function moved intact; it must remain callable without constructing a DI container\nexport function installTargets(projectRoot: string, homeDir: string = homedir()): InstallTarget[] {\n return [\n new InstallTarget('1', 'project (.claude/settings.json — committed, for the team)',\n path.join(projectRoot, '.claude', 'settings.json'), false, CLAUDE_REGISTRATION),\n new InstallTarget('2', 'project for you (.claude/settings.local.json — personal)',\n path.join(projectRoot, '.claude', 'settings.local.json'), false, CLAUDE_REGISTRATION),\n new InstallTarget('3', 'global (~/.claude/settings.json — exact path, this repo only)',\n path.join(homeDir, '.claude', 'settings.json'), true, CLAUDE_REGISTRATION),\n // Given choice `1` so one answer arms the whole project — see the docblock. Its position in the\n // array carries no meaning: every caller selects by choice id.\n new InstallTarget('1', 'project, for Codex too (.codex/hooks.json — committed, for the team)',\n path.join(projectRoot, ...CODEX_REGISTRATION.settingsFiles[0].split('/')), false, CODEX_REGISTRATION),\n ];\n}\n\n// ---------------------------------------------------------------------------\n// Claude Code settings.json hook wiring.\n// ---------------------------------------------------------------------------\n// webpieces-disable no-function-outside-class -- existing CLI/shim bootstrap function moved intact; it must remain callable without constructing a DI container\nexport function hasHook(settings: ClaudeSettings, bin: string): boolean {\n const entries = settings.hooks?.PreToolUse ?? [];\n return entries.some((e: HookEntry) => e.hooks.some((h: HookCommand) => h.command.includes(bin)));\n}\n\n// Drop every PreToolUse command containing `marker` (a bin name, or a managed .sh path); returns true\n// if anything was removed. REMOVE-then-ADD is what keeps an upgrade from leaving a superseded spelling\n// (a relative command, or the retired L-1 entry) beside the current one — two spellings of one\n// registration is the compatibility shim the backwards-compat reviewer rejects.\n// webpieces-disable no-function-outside-class -- setup.ts is deliberately DI-free (it must run on a half-written node_modules; see install-entry.ts), so every function here is module-scope\nfunction removeHookByMarker(settings: ClaudeSettings, marker: string): boolean {\n const entries = settings.hooks?.PreToolUse;\n if (!entries) return false;\n let changed = false;\n const kept: HookEntry[] = [];\n for (const entry of entries) {\n const hooks = entry.hooks.filter((h: HookCommand) => !h.command.includes(marker));\n if (hooks.length !== entry.hooks.length) changed = true;\n if (hooks.length > 0) kept.push({ matcher: entry.matcher, hooks });\n }\n if (changed) settings.hooks!.PreToolUse = kept;\n return changed;\n}\n\n// Apply the chosen install for one hook: remove it from every target file, then add it back to the\n// chosen one (or nowhere, for uninstall). Writes only the files that changed.\n// webpieces-disable no-function-outside-class -- existing CLI/shim bootstrap function moved intact; it must remain callable without constructing a DI container\nexport function applyHook(hook: HookSpec, chosen: InstallTarget | null, targets: InstallTarget[], projectRoot: string): void {\n // SCOPED TO THE CHOSEN HARNESS, and this is what makes one call per target composable. Installing\n // the Claude hook must not strip the Codex one, so \"remove it from everywhere else\" means everywhere\n // else THIS HARNESS could live. Uninstall (chosen === null) is the one case that means every\n // harness, because \"not installed\" has to be true everywhere or the hook is still armed somewhere.\n const scope = chosen === null ? targets : targets.filter((t: InstallTarget) => t.harness === chosen.harness);\n for (const target of scope) {\n const settings = readSettings(target.settingsPath);\n const removed = removeHookByMarker(settings, hook.bin);\n const isChosen = chosen !== null && chosen.settingsPath === target.settingsPath;\n if (isChosen) {\n addHookEntry(settings, new HookRegistrationEntry(hook.matcherFor(target), hook.commandFor(target, projectRoot)));\n // The managed `env` entry goes into the SAME file the hooks go into, on every path that\n // writes hooks — interactive or `--target=`. It pins the Bash cwd to the project root, so a\n // guard's answer depends on the command rather than on where an earlier `cd` left the shell,\n // and settings `env` is inherited, so every subagent gets the identical cwd and therefore the\n // identical guard verdict. (It no longer has a RESOLUTION job — the hooks are absolute.) See\n // hook-registration.ts for the full argument; `wp-upgrade-shim` self-heals it afterwards.\n // …in the harness that HAS that surface. Codex has no settings `env`, and needs none: its\n // cwd is MEASURED not to drift, which is the whole thing this entry buys under Claude Code.\n if (target.harness.managesEnv && applyManagedEnv(settings)) {\n console.log(` ✅ env.${BASH_CWD_ENV_KEY}=${BASH_CWD_ENV_VALUE} → ${target.label} (pins the Bash cwd to the project root, for this session and every subagent)`);\n }\n writeSettings(target.settingsPath, settings);\n console.log(` ✅ ${hook.label} → ${target.label}`);\n } else if (removed) {\n writeSettings(target.settingsPath, settings);\n }\n }\n // Manage the shared checked-in shim: (re)write it whenever a project (relative) install exists,\n // otherwise clean it up once neither hook references it anymore.\n if (chosen !== null && !chosen.absolute) {\n writeShim(projectRoot);\n // The generic PR-gate reviewer agent is part of the same committed, managed set as the shim — the\n // drift check reports it beside the shim, so the installer writes it beside the shim.\n if (writeReviewerAgent(projectRoot)) {\n console.log(` ✅ ${REVIEWER_AGENT_MARKER} (the generic PR-gate reviewer; generated — commit it, do not edit it)`);\n }\n } else if (!markerReferenced(targets, SHIM_MARKER)) {\n removeShim(projectRoot);\n }\n // The RETIRED L-1 hook rode with the GUARDS hook, so its removal does too. Doing it here rather than\n // at a separate call site means every existing caller of applyHook — the installer's interactive and\n // --target paths, and every test — converges on the two-hook absolute form with no second step.\n if (hook.bin === GUARDS_BIN) purgeRetiredGuaranteeRoot(targets, projectRoot);\n if (chosen === null) console.log(` ⛔ ${hook.label} not installed (removed from all locations).`);\n}\n\n/**\n * Say whether Codex will actually RUN what we just registered — the one thing the installer cannot do\n * anything about and therefore must not leave silent.\n *\n * Codex trusts a hook entry TOFU and re-prompts whenever its bytes change, and the prompt's third option\n * is \"Continue without trusting (hooks won't run)\". So a perfectly successful install can be followed by\n * a fully unguarded session, and the only honest thing to print is what is true plus the one action a\n * HUMAN has to take. Nothing here writes `~/.codex/config.toml` — see codex-trust.ts for why forging a\n * `trusted_hash` is not on the table.\n *\n * Silent when this repo did not arm Codex, so a Claude-only install gains no noise.\n */\n// webpieces-disable no-function-outside-class -- setup.ts is deliberately DI-free (it must run on a half-written node_modules; see install-entry.ts), so every function here is module-scope\nfunction reportCodexTrust(projectRoot: string, targets: InstallTarget[], choice: string): void {\n const armed = targets.some((t: InstallTarget): boolean => t.choice === choice && t.harness === CODEX_REGISTRATION);\n if (!armed) return;\n const lines = new CodexTrustProbe().read(projectRoot).lines();\n if (lines.length === 0) return;\n console.log('');\n for (const line of lines) console.log(line);\n}\n\n// webpieces-disable no-function-outside-class -- existing CLI/shim bootstrap function moved intact; it must remain callable without constructing a DI container\nfunction currentLocation(hook: HookSpec, targets: InstallTarget[]): string {\n const here = targets.filter((t: InstallTarget) => hasHook(readSettings(t.settingsPath), hook.bin));\n return here.length === 0 ? 'none' : here.map((t: InstallTarget) => t.label.split(' (')[0]).join(', ');\n}\n\n// webpieces-disable no-function-outside-class -- existing CLI/shim bootstrap function moved intact; it must remain callable without constructing a DI container\nfunction prompt(question: string): Promise<string> {\n return new Promise((resolve: (answer: string) => void) => {\n const rl = createInterface({ input: process.stdin, output: process.stdout });\n rl.question(question, (answer: string) => { rl.close(); resolve(answer.trim()); });\n });\n}\n\n// Map a friendly `--target` name to an InstallTarget choice id (see installTargets). Returns null\n// for an unknown name so the caller can error out. Kept separate + exported for unit testing.\n// webpieces-disable no-function-outside-class -- existing CLI/shim bootstrap function moved intact; it must remain callable without constructing a DI container\nexport function resolveTargetChoice(name: string): string | null {\n switch (name) {\n case 'project': return '1';\n case 'project-personal':\n case 'projectpersonal':\n case 'local': return '2';\n case 'global': return '3';\n case 'none':\n case 'uninstall': return '4';\n default: return null;\n }\n}\n\n// Extract the value of `--target=<name>` from argv (null if the flag is absent).\n// webpieces-disable no-function-outside-class -- existing CLI/shim bootstrap function moved intact; it must remain callable without constructing a DI container\nexport function parseTargetArg(args: string[]): string | null {\n const flag = args.find((a: string): boolean => a.startsWith('--target='));\n return flag ? flag.slice('--target='.length) : null;\n}\n\n/**\n * Apply ONE choice for one hook: every target that answer selects, or uninstall when it selects none.\n *\n * The loop is what lets one choice arm several harnesses (choice `1` writes both the Claude settings\n * file and the Codex hooks file — see installTargets). `applyHook` scopes its removals to the chosen\n * target's harness, which is what keeps these calls from undoing one another.\n */\n// webpieces-disable no-function-outside-class -- setup.ts is deliberately DI-free (it must run on a half-written node_modules; see install-entry.ts), so every function here is module-scope\nexport function applyChoice(hook: HookSpec, choice: string, targets: InstallTarget[], projectRoot: string): void {\n const chosen = targets.filter((t: InstallTarget): boolean => t.choice === choice);\n if (chosen.length === 0) {\n applyHook(hook, null, targets, projectRoot);\n return;\n }\n for (const target of chosen) applyHook(hook, target, targets, projectRoot);\n}\n\n// webpieces-disable no-function-outside-class -- existing CLI/shim bootstrap function moved intact; it must remain callable without constructing a DI container\nasync function wireHook(hook: HookSpec, targets: InstallTarget[], projectRoot: string): Promise<void> {\n console.log('');\n console.log(`${hook.label}`);\n console.log(` currently installed in: ${currentLocation(hook, targets)}`);\n // The matcher is printed PER TARGET now, because it differs per harness — Codex's file tool is\n // `apply_patch`, Claude's are Write|Edit|MultiEdit — and one matcher printed above the list would be\n // wrong for whichever harness it did not describe.\n for (const target of targets) console.log(` ${target.choice}) ${target.label} [matcher: ${hook.matcherFor(target)}]`);\n console.log(' 4) none / uninstall');\n const answer = await prompt(' Where should it live? [1/2/3/4, default 4]: ');\n applyChoice(hook, answer, targets, projectRoot);\n}\n\n/**\n * Scaffold the SERVER-SIDE PR gate: the CI workflow plus the doc explaining how to turn it on.\n *\n * This lives in the installer, not the PR flow. `wp-start-upsert-pr` used to do it — printing\n * copy-to-`.github` and branch-protection instructions on EVERY run, at an agent doing feature work\n * that could not act on them anyway (marking a check required needs a repo admin). Setup is a\n * one-time, admin-shaped act, so it belongs with the other one-time setup.\n *\n * Written UNCONDITIONALLY, unlike the old version which required a `gateSalt` to already be set: the\n * whole point of the doc is to tell you to set one, so gating it on the thing it teaches meant the\n * instructions only appeared to repos that no longer needed them.\n *\n * Both land in gitignored `.webpieces/instruct-ai/`, never `.github/` directly — writing there would\n * dirty the tree, and copying it is the human's decision. `IfMissing` for the yml so a repo that has\n * customized its workflow never gets it clobbered; the doc itself is refreshed so it cannot go stale.\n */\n// webpieces-disable no-function-outside-class -- setup.ts is deliberately DI-free (it must run on a half-written node_modules; see install-entry.ts), so every function here is module-scope\nfunction scaffoldCiGate(projectRoot: string): void {\n writeTemplateIfMissing(projectRoot, 'webpieces-pr-gate.yml');\n writeTemplate(projectRoot, 'webpieces.ci-gate-setup.md');\n console.log('');\n console.log('ℹ️ Optional: server-side PR gate (stops an UNHOOKED teammate opening a PR in the web UI).');\n console.log(' It is OFF until you set a gateSalt. Three steps, one of which needs a repo admin:');\n console.log(' .webpieces/instruct-ai/webpieces.ci-gate-setup.md');\n}\n\n// webpieces-disable no-function-outside-class -- existing CLI/shim bootstrap function moved intact; it must remain callable without constructing a DI container\nexport async function main(): Promise<void> {\n const args = process.argv.slice(2);\n // Anchor the install at the repo root (git toplevel — webpieces.config.json may not exist yet on\n // a first install), never a subdir cwd, so `.webpieces`/hooks/config all land at the root.\n const projectRoot = new RepoRootFinder().resolveRepoRoot(process.cwd());\n\n seedOrSyncConfig(projectRoot);\n // Always refreshed: it explains why a retired key is rejected rather than accepted, and what to do\n // about it — which is exactly what an agent needs on the run where a migration just moved keys out\n // from under its config.\n writeTemplate(projectRoot, CONFIG_POLICY_DOC);\n\n scaffoldCiGate(projectRoot);\n\n const targets = installTargets(projectRoot);\n\n // Non-interactive: `--target=project|project-personal|global|none` installs BOTH hooks at that\n // location without prompting, so an agent or CI can run the installer unattended (e.g. after a\n // @webpieces upgrade that changed the hook entry). Omit the flag for the interactive per-hook chooser.\n const targetName = parseTargetArg(args);\n if (targetName !== null) {\n const choice = resolveTargetChoice(targetName);\n if (choice === null) {\n console.error(`❌ Unknown --target '${targetName}'. Use one of: project | project-personal | global | none`);\n process.exitCode = 1;\n return;\n }\n applyChoice(RULES_HOOK, choice, targets, projectRoot);\n applyChoice(GUARDS_HOOK, choice, targets, projectRoot);\n console.log(`\\nDone. Both hooks set to: ${targetName}.`);\n reportCodexTrust(projectRoot, targets, choice);\n return;\n }\n\n console.log('');\n console.log('Two webpieces hooks can be installed independently — choose a location for each:');\n await wireHook(RULES_HOOK, targets, projectRoot);\n await wireHook(GUARDS_HOOK, targets, projectRoot);\n // Whichever choices were made above, report Codex trust for the project choice — an interactive run\n // that armed Codex needs the same warning the --target path prints.\n reportCodexTrust(projectRoot, targets, '1');\n console.log('');\n console.log('Done. Re-run `pnpm wp-install-ai-hooks` anytime to move or uninstall a hook.');\n console.log('(Non-interactive: pnpm wp-install-ai-hooks --target=project|project-personal|global|none)');\n}\n\nif (require.main === module) {\n void main();\n}\n"]}
1
+ {"version":3,"file":"setup.js","sourceRoot":"","sources":["../../../../../../packages/tooling/agent-workflow-rules/src/bin/setup.ts"],"names":[],"mappings":";;;AAuJA,wCAaC;AAMD,0BAGC;AAwBD,8BA8CC;AAyCD,kDAWC;AAID,wCAGC;AAUD,kCAOC;AA2CD,oBA2CC;;AArZD,+CAAyB;AACzB,mDAA6B;AAC7B,2BAA6B;AAC7B,uCAA2C;AAE3C,0DAAmH;AAEnH,iCAA2D;AAC3D,qDAA6E;AAC7E,2DAA2O;AAE3O,+CAAqE;AACrE,+CAAgD;AAChD,uGAAuG;AACvG,yFAAyF;AACzF,iDAAkD;AAGlD,8EAA8E;AAC9E,iGAAiG;AACjG,kGAAkG;AAClG,wGAAwG;AACxG,oGAAoG;AACpG,0FAA0F;AAC1F,8EAA8E;AAC9E,MAAM,QAAQ;IAEG;IACA;IACA;IAHb,YACa,GAAW,EACX,KAAa,EACb,GAAW;QAFX,QAAG,GAAH,GAAG,CAAQ;QACX,UAAK,GAAL,KAAK,CAAQ;QACb,Q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GAAG,CAAC,EAAE,CAAC,CAAC;IAChB,OAAO,CAAC,GAAG,CAAC,kFAAkF,CAAC,CAAC;IAChG,MAAM,QAAQ,CAAC,kBAAU,EAAE,OAAO,EAAE,WAAW,CAAC,CAAC;IACjD,MAAM,QAAQ,CAAC,mBAAW,EAAE,OAAO,EAAE,WAAW,CAAC,CAAC;IAClD,oGAAoG;IACpG,oEAAoE;IACpE,gBAAgB,CAAC,WAAW,EAAE,OAAO,EAAE,GAAG,CAAC,CAAC;IAC5C,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;IAChB,OAAO,CAAC,GAAG,CAAC,8EAA8E,CAAC,CAAC;IAC5F,OAAO,CAAC,GAAG,CAAC,2FAA2F,CAAC,CAAC;AAC7G,CAAC;AAED,IAAI,OAAO,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;IAC1B,KAAK,IAAI,EAAE,CAAC;AAChB,CAAC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport { homedir } from 'os';\nimport { createInterface } from 'readline';\n\nimport { RepoRootFinder, writeTemplate, writeTemplateIfMissing, CONFIG_POLICY_DOC } from '@webpieces/rules-config';\n\nimport { SHIM_MARKER, shimPath, renderShim } from './shim';\nimport { REVIEWER_AGENT_MARKER, writeReviewerAgent } from './reviewer-agent';\nimport { HookRegistrationEntry, GUARDS_BIN, LEGACY_GUARANTEE_ROOT_MARKER, RULES_BIN, addHookEntry, applyManagedEnv, readSettings, writeSettings, HarnessRegistration, CLAUDE_REGISTRATION, CODEX_REGISTRATION } from './hook-registration';\nimport type { ClaudeSettings, HookCommand, HookEntry } from './settings-shape';\nimport { BASH_CWD_ENV_KEY, BASH_CWD_ENV_VALUE } from './managed-env';\nimport { CodexTrustProbe } from './codex-trust';\n// The config half of the installer — seeding and migrating webpieces.config.json. Split for size along\n// the seam that was already there: this module is hook WIRING, that one is CONFIG SHAPE.\nimport { seedOrSyncConfig } from './setup-config';\n\n\n// ---------------------------------------------------------------------------\n// The two independently-installable GUARD hooks. Each can land in a different settings file (see\n// InstallTarget) so a team can ship the guards while a developer keeps the code-style rules local\n// while iterating. Both are registered ABSOLUTE via $CLAUDE_PROJECT_DIR, so the MAIN tree governs every\n// tree. There used to be a third — the L-1 hook, which existed only to keep a RELATIVE registration\n// resolvable; it is retired, and purgeRetiredGuaranteeRoot() removes anything left of it.\n// ---------------------------------------------------------------------------\nclass HookSpec {\n constructor(\n readonly key: string,\n readonly label: string,\n readonly bin: string,\n ) {}\n\n /**\n * WHICH TOOL NAMES this hook must see, in the harness the target belongs to.\n *\n * It is a lookup on the target rather than a field on the spec because the answer is not a property\n * of the hook: the rules hook matches `Write|Edit|MultiEdit` under Claude Code and `apply_patch`\n * under Codex, and a single stored matcher is exactly how `.codex/hooks.json` came to be registered\n * against tool names Codex never emits.\n */\n matcherFor(target: InstallTarget): string {\n return target.harness.matcherFor(this.bin);\n }\n\n // Absolute targets (global) need the exact path to this repo's bin — no ~/.webpieces bridge.\n // Project targets get the ABSOLUTE shim command, anchored on the harness's own project-root variable\n // (see HarnessRegistration.shimCommand): it resolves from ANY cwd, so a hook can never fail to\n // launch — which per the hooks reference would be exit 127, a SILENT UNGUARDED ALLOW, not a block.\n commandFor(target: InstallTarget, projectRoot: string): string {\n if (target.absolute) {\n return `node ${path.join(projectRoot, 'node_modules', '.bin', this.bin)}`;\n }\n return target.harness.shimCommand(this.bin);\n }\n}\n\n// Idempotent: re-running the installer overwrites the managed shim in place.\n// webpieces-disable no-function-outside-class -- existing CLI/shim bootstrap function moved intact; it must remain callable without constructing a DI container\nfunction writeShim(projectRoot: string): void {\n const target = shimPath(projectRoot);\n fs.mkdirSync(path.dirname(target), { recursive: true });\n fs.writeFileSync(target, renderShim(), { mode: 0o755 });\n // writeFileSync's mode is only applied when creating the file; force it on overwrite too.\n fs.chmodSync(target, 0o755);\n}\n\n// webpieces-disable no-function-outside-class -- existing CLI/shim bootstrap function moved intact; it must remain callable without constructing a DI container\nfunction removeShim(projectRoot: string): void {\n const target = shimPath(projectRoot);\n if (fs.existsSync(target)) fs.rmSync(target);\n}\n\n// A managed .sh is shared by the project hooks — only safe to delete once no project settings file\n// references it anymore (i.e. the other hook was moved to global or uninstalled too).\n// webpieces-disable no-function-outside-class -- setup.ts is deliberately DI-free (it must run on a half-written node_modules; see install-entry.ts), so every function here is module-scope\nfunction markerReferenced(targets: InstallTarget[], marker: string): boolean {\n return targets.some((t: InstallTarget) => {\n const entries = readSettings(t.settingsPath).hooks?.PreToolUse ?? [];\n return entries.some((e: HookEntry) => e.hooks.some((h: HookCommand) => h.command.includes(marker)));\n });\n}\n\n/**\n * Remove every trace of the RETIRED L-1 hook (`guarantee-root.sh`) — the file and any PreToolUse entry\n * still pointing at it. REMOVAL ONLY: nothing here can ever write one back.\n *\n * L-1 existed to guarantee a RELATIVE guard-hook path resolved, by refusing any `cd` that would park the\n * shell in a subdirectory. The guard hooks are ABSOLUTE now (`$CLAUDE_PROJECT_DIR/...`), so they resolve\n * from any cwd and the guarantee is structural — there is nothing left to police, and the subdirectory\n * denial that used to pay for it is gone with it.\n */\n// webpieces-disable no-function-outside-class -- setup.ts is deliberately DI-free (it must run on a half-written node_modules; see install-entry.ts), so every function here is module-scope\nfunction purgeRetiredGuaranteeRoot(targets: InstallTarget[], projectRoot: string): void {\n for (const target of targets) {\n const settings = readSettings(target.settingsPath);\n if (removeHookByMarker(settings, LEGACY_GUARANTEE_ROOT_MARKER)) {\n writeSettings(target.settingsPath, settings);\n console.log(` 🗑️ removed the retired L-1 guarantee-root hook from ${target.label}`);\n }\n }\n const legacyFile = path.join(projectRoot, LEGACY_GUARANTEE_ROOT_MARKER);\n if (fs.existsSync(legacyFile)) {\n fs.rmSync(legacyFile, { force: true });\n console.log(' 🗑️ deleted the retired .claude/webpieces/guarantee-root.sh');\n }\n}\n\nexport class InstallTarget {\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(\n readonly choice: string,\n readonly label: string,\n readonly settingsPath: string,\n readonly absolute: boolean,\n /**\n * WHICH HARNESS this file arms — it decides the matcher and the shim anchor written into it.\n *\n * REQUIRED, with no default, and the absence of one is the point. A default of\n * CLAUDE_REGISTRATION would make \"omit the harness\" mean \"Claude Code\" — a widening that is an\n * ABSENCE rather than a token, so a target built for Codex without it would silently carry\n * `Write|Edit|MultiEdit` and `$CLAUDE_PROJECT_DIR`, which is EXACTLY the silently-unguarded\n * state this class exists to end, and ungreppable besides.\n */\n readonly harness: HarnessRegistration,\n ) {}\n}\n\n// The bin names come from ./hook-registration, which is also what the drift check and wp-upgrade-shim\n// compare against — one spelling of the registration, or the installer and the validator can disagree\n// about what \"installed\" means. The MATCHER is not here: it belongs to the harness, not the hook (see\n// HookSpec.matcherFor).\nexport const RULES_HOOK = new HookSpec('rules', 'Rules hook (code-style validation)', RULES_BIN);\nexport const GUARDS_HOOK = new HookSpec('guards', 'Guards hook (git/PR/branch protection)', GUARDS_BIN);\n\n/**\n * Every file the installer can write, keyed by the CHOICE a human makes.\n *\n * TWO TARGETS SHARE CHOICE `1`, and that is the design rather than an oversight: \"the project, committed,\n * for the team\" is ONE intention, and a repo that is worked on by both harnesses needs both files armed\n * to mean it. Splitting it into two questions would let a human answer them differently and end up with a\n * repo where Codex is silently unguarded — which is the state this whole change exists to end. Every\n * caller selects by choice id (`targets.filter(t => t.choice === answer)`), never by index, so adding a\n * harness adds a row and changes no numbering.\n *\n * `2` (personal) and `3` (global) stay Claude-only because neither has a Codex counterpart: Codex reads\n * one repo-local `hooks.json` and has no personal or home-scoped hook file.\n *\n * `homeDir` is injectable so tests can point the global target at a temp dir instead of the real\n * ~/.claude/settings.json (a unit test must never write the user's actual global settings).\n */\n// webpieces-disable no-function-outside-class -- existing CLI/shim bootstrap function moved intact; it must remain callable without constructing a DI container\nexport function installTargets(projectRoot: string, homeDir: string = homedir()): InstallTarget[] {\n return [\n new InstallTarget('1', 'project (.claude/settings.json — committed, for the team)',\n path.join(projectRoot, '.claude', 'settings.json'), false, CLAUDE_REGISTRATION),\n new InstallTarget('2', 'project for you (.claude/settings.local.json — personal)',\n path.join(projectRoot, '.claude', 'settings.local.json'), false, CLAUDE_REGISTRATION),\n new InstallTarget('3', 'global (~/.claude/settings.json — exact path, this repo only)',\n path.join(homeDir, '.claude', 'settings.json'), true, CLAUDE_REGISTRATION),\n // Given choice `1` so one answer arms the whole project — see the docblock. Its position in the\n // array carries no meaning: every caller selects by choice id.\n new InstallTarget('1', 'project, for Codex too (.codex/hooks.json — committed, for the team)',\n path.join(projectRoot, ...CODEX_REGISTRATION.settingsFiles[0].split('/')), false, CODEX_REGISTRATION),\n ];\n}\n\n// ---------------------------------------------------------------------------\n// Claude Code settings.json hook wiring.\n// ---------------------------------------------------------------------------\n// webpieces-disable no-function-outside-class -- existing CLI/shim bootstrap function moved intact; it must remain callable without constructing a DI container\nexport function hasHook(settings: ClaudeSettings, bin: string): boolean {\n const entries = settings.hooks?.PreToolUse ?? [];\n return entries.some((e: HookEntry) => e.hooks.some((h: HookCommand) => h.command.includes(bin)));\n}\n\n// Drop every PreToolUse command containing `marker` (a bin name, or a managed .sh path); returns true\n// if anything was removed. REMOVE-then-ADD is what keeps an upgrade from leaving a superseded spelling\n// (a relative command, or the retired L-1 entry) beside the current one — two spellings of one\n// registration is the compatibility shim the backwards-compat reviewer rejects.\n// webpieces-disable no-function-outside-class -- setup.ts is deliberately DI-free (it must run on a half-written node_modules; see install-entry.ts), so every function here is module-scope\nfunction removeHookByMarker(settings: ClaudeSettings, marker: string): boolean {\n const entries = settings.hooks?.PreToolUse;\n if (!entries) return false;\n let changed = false;\n const kept: HookEntry[] = [];\n for (const entry of entries) {\n const hooks = entry.hooks.filter((h: HookCommand) => !h.command.includes(marker));\n if (hooks.length !== entry.hooks.length) changed = true;\n if (hooks.length > 0) kept.push({ matcher: entry.matcher, hooks });\n }\n if (changed) settings.hooks!.PreToolUse = kept;\n return changed;\n}\n\n// Apply the chosen install for one hook: remove it from every target file, then add it back to the\n// chosen one (or nowhere, for uninstall). Writes only the files that changed.\n// webpieces-disable no-function-outside-class -- existing CLI/shim bootstrap function moved intact; it must remain callable without constructing a DI container\nexport function applyHook(hook: HookSpec, chosen: InstallTarget | null, targets: InstallTarget[], projectRoot: string): void {\n // SCOPED TO THE CHOSEN HARNESS, and this is what makes one call per target composable. Installing\n // the Claude hook must not strip the Codex one, so \"remove it from everywhere else\" means everywhere\n // else THIS HARNESS could live. Uninstall (chosen === null) is the one case that means every\n // harness, because \"not installed\" has to be true everywhere or the hook is still armed somewhere.\n const scope = chosen === null ? targets : targets.filter((t: InstallTarget) => t.harness === chosen.harness);\n for (const target of scope) {\n const settings = readSettings(target.settingsPath);\n const removed = removeHookByMarker(settings, hook.bin);\n const isChosen = chosen !== null && chosen.settingsPath === target.settingsPath;\n if (isChosen) {\n addHookEntry(settings, new HookRegistrationEntry(hook.matcherFor(target), hook.commandFor(target, projectRoot)));\n // The managed `env` entry goes into the SAME file the hooks go into, on every path that\n // writes hooks — interactive or `--target=`. It pins the Bash cwd to the project root, so a\n // guard's answer depends on the command rather than on where an earlier `cd` left the shell,\n // and settings `env` is inherited, so every subagent gets the identical cwd and therefore the\n // identical guard verdict. (It no longer has a RESOLUTION job — the hooks are absolute.) See\n // hook-registration.ts for the full argument; `wp-upgrade-shim` self-heals it afterwards.\n // …in the harness that HAS that surface. Codex has no settings `env`, and needs none: its\n // cwd is MEASURED not to drift, which is the whole thing this entry buys under Claude Code.\n if (target.harness.managesEnv && applyManagedEnv(settings)) {\n console.log(` ✅ env.${BASH_CWD_ENV_KEY}=${BASH_CWD_ENV_VALUE} → ${target.label} (pins the Bash cwd to the project root, for this session and every subagent)`);\n }\n writeSettings(target.settingsPath, settings);\n console.log(` ✅ ${hook.label} → ${target.label}`);\n } else if (removed) {\n writeSettings(target.settingsPath, settings);\n }\n }\n // Manage the shared checked-in shim: (re)write it whenever a project (relative) install exists,\n // otherwise clean it up once neither hook references it anymore.\n if (chosen !== null && !chosen.absolute) {\n writeShim(projectRoot);\n // The generic PR-gate reviewer agent is part of the same committed, managed set as the shim — the\n // drift check reports it beside the shim, so the installer writes it beside the shim.\n if (writeReviewerAgent(projectRoot)) {\n console.log(` ✅ ${REVIEWER_AGENT_MARKER} (the generic PR-gate reviewer; generated — commit it, do not edit it)`);\n }\n } else if (!markerReferenced(targets, SHIM_MARKER)) {\n removeShim(projectRoot);\n }\n // The RETIRED L-1 hook rode with the GUARDS hook, so its removal does too. Doing it here rather than\n // at a separate call site means every existing caller of applyHook — the installer's interactive and\n // --target paths, and every test — converges on the two-hook absolute form with no second step.\n if (hook.bin === GUARDS_BIN) purgeRetiredGuaranteeRoot(targets, projectRoot);\n if (chosen === null) console.log(` ⛔ ${hook.label} not installed (removed from all locations).`);\n}\n\n/**\n * Say whether Codex will actually RUN what we just registered — the one thing the installer cannot do\n * anything about and therefore must not leave silent.\n *\n * Codex trusts a hook entry TOFU and re-prompts whenever its bytes change, and the prompt's third option\n * is \"Continue without trusting (hooks won't run)\". So a perfectly successful install can be followed by\n * a fully unguarded session, and the only honest thing to print is what is true plus the one action a\n * HUMAN has to take. Nothing here writes `~/.codex/config.toml` — see codex-trust.ts for why forging a\n * `trusted_hash` is not on the table.\n *\n * Silent when this repo did not arm Codex, so a Claude-only install gains no noise.\n */\n// webpieces-disable no-function-outside-class -- setup.ts is deliberately DI-free (it must run on a half-written node_modules; see install-entry.ts), so every function here is module-scope\nfunction reportCodexTrust(projectRoot: string, targets: InstallTarget[], choice: string): void {\n const armed = targets.some((t: InstallTarget): boolean => t.choice === choice && t.harness === CODEX_REGISTRATION);\n if (!armed) return;\n const lines = new CodexTrustProbe().read(projectRoot).lines();\n if (lines.length === 0) return;\n console.log('');\n for (const line of lines) console.log(line);\n}\n\n// webpieces-disable no-function-outside-class -- existing CLI/shim bootstrap function moved intact; it must remain callable without constructing a DI container\nfunction currentLocation(hook: HookSpec, targets: InstallTarget[]): string {\n const here = targets.filter((t: InstallTarget) => hasHook(readSettings(t.settingsPath), hook.bin));\n return here.length === 0 ? 'none' : here.map((t: InstallTarget) => t.label.split(' (')[0]).join(', ');\n}\n\n// webpieces-disable no-function-outside-class -- existing CLI/shim bootstrap function moved intact; it must remain callable without constructing a DI container\nfunction prompt(question: string): Promise<string> {\n return new Promise((resolve: (answer: string) => void) => {\n const rl = createInterface({ input: process.stdin, output: process.stdout });\n rl.question(question, (answer: string) => { rl.close(); resolve(answer.trim()); });\n });\n}\n\n// Map a friendly `--target` name to an InstallTarget choice id (see installTargets). Returns null\n// for an unknown name so the caller can error out. Kept separate + exported for unit testing.\n// webpieces-disable no-function-outside-class -- existing CLI/shim bootstrap function moved intact; it must remain callable without constructing a DI container\nexport function resolveTargetChoice(name: string): string | null {\n switch (name) {\n case 'project': return '1';\n case 'project-personal':\n case 'projectpersonal':\n case 'local': return '2';\n case 'global': return '3';\n case 'none':\n case 'uninstall': return '4';\n default: return null;\n }\n}\n\n// Extract the value of `--target=<name>` from argv (null if the flag is absent).\n// webpieces-disable no-function-outside-class -- existing CLI/shim bootstrap function moved intact; it must remain callable without constructing a DI container\nexport function parseTargetArg(args: string[]): string | null {\n const flag = args.find((a: string): boolean => a.startsWith('--target='));\n return flag ? flag.slice('--target='.length) : null;\n}\n\n/**\n * Apply ONE choice for one hook: every target that answer selects, or uninstall when it selects none.\n *\n * The loop is what lets one choice arm several harnesses (choice `1` writes both the Claude settings\n * file and the Codex hooks file — see installTargets). `applyHook` scopes its removals to the chosen\n * target's harness, which is what keeps these calls from undoing one another.\n */\n// webpieces-disable no-function-outside-class -- setup.ts is deliberately DI-free (it must run on a half-written node_modules; see install-entry.ts), so every function here is module-scope\nexport function applyChoice(hook: HookSpec, choice: string, targets: InstallTarget[], projectRoot: string): void {\n const chosen = targets.filter((t: InstallTarget): boolean => t.choice === choice);\n if (chosen.length === 0) {\n applyHook(hook, null, targets, projectRoot);\n return;\n }\n for (const target of chosen) applyHook(hook, target, targets, projectRoot);\n}\n\n// webpieces-disable no-function-outside-class -- existing CLI/shim bootstrap function moved intact; it must remain callable without constructing a DI container\nasync function wireHook(hook: HookSpec, targets: InstallTarget[], projectRoot: string): Promise<void> {\n console.log('');\n console.log(`${hook.label}`);\n console.log(` currently installed in: ${currentLocation(hook, targets)}`);\n // The matcher is printed PER TARGET now, because it differs per harness — Codex's file tool is\n // `apply_patch`, Claude's are Write|Edit|MultiEdit — and one matcher printed above the list would be\n // wrong for whichever harness it did not describe.\n for (const target of targets) console.log(` ${target.choice}) ${target.label} [matcher: ${hook.matcherFor(target)}]`);\n console.log(' 4) none / uninstall');\n const answer = await prompt(' Where should it live? [1/2/3/4, default 4]: ');\n applyChoice(hook, answer, targets, projectRoot);\n}\n\n/**\n * Scaffold the SERVER-SIDE PR gate: the CI workflow plus the doc explaining how to turn it on.\n *\n * This lives in the installer, not the PR flow. `wp-start-upsert-pr` used to do it — printing\n * copy-to-`.github` and branch-protection instructions on EVERY run, at an agent doing feature work\n * that could not act on them anyway (marking a check required needs a repo admin). Setup is a\n * one-time, admin-shaped act, so it belongs with the other one-time setup.\n *\n * Written UNCONDITIONALLY, unlike the old version which required a `gateSalt` to already be set: the\n * whole point of the doc is to tell you to set one, so gating it on the thing it teaches meant the\n * instructions only appeared to repos that no longer needed them.\n *\n * Both land in gitignored `.webpieces/instruct-ai/`, never `.github/` directly — writing there would\n * dirty the tree, and copying it is the human's decision. `IfMissing` for the yml so a repo that has\n * customized its workflow never gets it clobbered; the doc itself is refreshed so it cannot go stale.\n */\n// webpieces-disable no-function-outside-class -- setup.ts is deliberately DI-free (it must run on a half-written node_modules; see install-entry.ts), so every function here is module-scope\nfunction scaffoldCiGate(projectRoot: string): void {\n writeTemplateIfMissing(projectRoot, 'webpieces-pr-gate.yml');\n writeTemplate(projectRoot, 'webpieces.ci-gate-setup.md');\n console.log('');\n console.log('ℹ️ Optional: server-side PR gate (stops an UNHOOKED teammate opening a PR in the web UI).');\n console.log(' It is OFF until you set a gateSalt. Three steps, one of which needs a repo admin:');\n console.log(' .webpieces/instruct-ai/webpieces.ci-gate-setup.md');\n}\n\n// webpieces-disable no-function-outside-class -- existing CLI/shim bootstrap function moved intact; it must remain callable without constructing a DI container\nexport async function main(): Promise<void> {\n const args = process.argv.slice(2);\n // Anchor the install at the repo root (git toplevel — webpieces.config.json may not exist yet on\n // a first install), never a subdir cwd, so `.webpieces`/hooks/config all land at the root.\n const projectRoot = new RepoRootFinder().resolveRepoRoot(process.cwd());\n\n // Always refreshed: it explains why a retired key is rejected rather than accepted, and what to do\n // about it — which is exactly what an agent needs on the run where a migration just moved keys out\n // from under its config.\n writeTemplate(projectRoot, CONFIG_POLICY_DOC);\n seedOrSyncConfig(projectRoot);\n scaffoldCiGate(projectRoot);\n\n const targets = installTargets(projectRoot);\n\n // Non-interactive: `--target=project|project-personal|global|none` installs BOTH hooks at that\n // location without prompting, so an agent or CI can run the installer unattended (e.g. after a\n // @webpieces upgrade that changed the hook entry). Omit the flag for the interactive per-hook chooser.\n const targetName = parseTargetArg(args);\n if (targetName !== null) {\n const choice = resolveTargetChoice(targetName);\n if (choice === null) {\n console.error(`❌ Unknown --target '${targetName}'. Use one of: project | project-personal | global | none`);\n process.exitCode = 1;\n return;\n }\n applyChoice(RULES_HOOK, choice, targets, projectRoot);\n applyChoice(GUARDS_HOOK, choice, targets, projectRoot);\n console.log(`\\nDone. Both hooks set to: ${targetName}.`);\n reportCodexTrust(projectRoot, targets, choice);\n return;\n }\n\n console.log('');\n console.log('Two webpieces hooks can be installed independently — choose a location for each:');\n await wireHook(RULES_HOOK, targets, projectRoot);\n await wireHook(GUARDS_HOOK, targets, projectRoot);\n // Whichever choices were made above, report Codex trust for the project choice — an interactive run\n // that armed Codex needs the same warning the --target path prints.\n reportCodexTrust(projectRoot, targets, '1');\n console.log('');\n console.log('Done. Re-run `pnpm wp-install-ai-hooks` anytime to move or uninstall a hook.');\n console.log('(Non-interactive: pnpm wp-install-ai-hooks --target=project|project-personal|global|none)');\n}\n\nif (require.main === module) {\n void main();\n}\n"]}