claude-flow-guidance-implementation 0.1.7 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +826 -119
  2. package/bin/cf-guidance-impl.mjs +44 -12
  3. package/docs/architecture.md +738 -0
  4. package/docs/diagrams/architecture/async-hook-sequence.svg +1 -0
  5. package/docs/diagrams/architecture/autopilot-optimisation-loop.svg +1 -0
  6. package/docs/diagrams/architecture/blocking-hook-sequence.svg +1 -0
  7. package/docs/diagrams/architecture/installer-workflow.svg +1 -0
  8. package/docs/diagrams/architecture/integration-paths.svg +1 -0
  9. package/docs/diagrams/architecture/policy-pipeline.svg +1 -0
  10. package/docs/diagrams/architecture/security-architecture.svg +1 -0
  11. package/docs/diagrams/architecture/solution-architecture-overview.svg +1 -0
  12. package/docs/github-screenshot.png +0 -0
  13. package/docs/guide/README.md +34 -0
  14. package/docs/guide/api-reference.md +1082 -0
  15. package/docs/guide/authoring-claude-md.md +418 -0
  16. package/docs/guide/deployment.md +458 -0
  17. package/docs/guide/evolution-workflow.md +494 -0
  18. package/docs/guide/gate-configuration.md +432 -0
  19. package/docs/guide/migration.md +478 -0
  20. package/docs/guide/quick-start.md +313 -0
  21. package/docs/guide/trust-system.md +357 -0
  22. package/docs/guide/user-manual.md +5 -0
  23. package/package.json +47 -5
  24. package/src/cli/analyze-guidance.js +182 -0
  25. package/{scaffold/scripts/guidance-integrations.js → src/cli/event-handlers.js} +10 -160
  26. package/{scaffold/scripts → src/cli}/guidance-ab-benchmark.js +2 -5
  27. package/{scaffold/scripts → src/cli}/guidance-autopilot.js +24 -29
  28. package/{scaffold/scripts → src/cli}/guidance-codex-bridge.js +6 -22
  29. package/src/cli/guidance-integrations.js +112 -0
  30. package/{scaffold/scripts → src/cli}/guidance-runtime.js +8 -5
  31. package/{scaffold/scripts → src/cli}/scaffold-guidance.js +0 -3
  32. package/src/default-settings.mjs +239 -98
  33. package/src/guidance/advanced-runtime.js +293 -0
  34. package/src/guidance/integration-runners.js +481 -0
  35. package/src/hook-handler.cjs +430 -0
  36. package/src/installer.mjs +199 -70
  37. package/src/utils.cjs +62 -0
  38. package/src/utils.mjs +62 -0
  39. package/scaffold/.claude/helpers/hook-handler.cjs +0 -590
  40. package/scaffold/docs/guidance-control-plane.md +0 -441
  41. package/scaffold/docs/guidance-implementation-guide.md +0 -424
  42. package/scaffold/scripts/analyze-guidance.js +0 -176
  43. package/scaffold/src/guidance/advanced-runtime.js +0 -658
  44. /package/{scaffold/src → src}/guidance/content-aware-executor.js +0 -0
  45. /package/{scaffold/src → src}/guidance/phase1-runtime.js +0 -0
package/README.md CHANGED
@@ -1,170 +1,877 @@
1
1
  # claude-flow-guidance-implementation
2
2
 
3
- Implementation kit for wiring `@claude-flow/guidance` into real repos with repeatable automation for Claude Code hooks, Codex lifecycle events, and guidance optimization workflows.
3
+ *Runtime governance for AI coding agents.*
4
4
 
5
- ## What This Package Is
5
+ ---
6
6
 
7
- This package is an installer and scaffold, not just an API example.
8
- It creates a working guidance control plane in a target repo, including:
7
+ ## 1. What This Package Does
9
8
 
10
- - hook event wiring (`pre-*` and `post-*`)
11
- - guidance runtime scripts (`analyze`, `optimize`, `ab-benchmark`, modules)
12
- - Codex bridge commands (optional)
13
- - `CLAUDE.local.md` bootstrap for local-only experiments
14
- - verification checks so setup can be validated immediately
9
+ AI coding agents degrade over long sessions. They forget rules, repeat
10
+ mistakes, leak secrets, and run destructive commands. This package solves
11
+ that problem by wiring the `@claude-flow/guidance` control plane into any
12
+ repository that uses Claude Code or OpenAI Codex as its coding agent.
15
13
 
16
- ## What `quickstart` is doing
14
+ After installation the package does three things automatically:
17
15
 
18
- The quickstart commands do two things:
16
+ 1. **Compiles** your `CLAUDE.md` file into an enforceable policy bundle
17
+ with typed rules, intent-tagged shards, and a machine-readable
18
+ constitution.
19
+ 2. **Intercepts** every agent action (shell commands, file edits, task
20
+ starts, task completions, session lifecycle) through hooks, evaluates
21
+ each action against the compiled policy, and blocks violations before
22
+ they reach your codebase.
23
+ 3. **Records** every decision in a cryptographic proof chain so you can
24
+ replay, audit, and demonstrate compliance after the fact.
19
25
 
20
- - run `init` to install and wire scripts/config into your target repo
21
- - run `verify` to confirm that required files, hooks, and syntax checks pass
26
+ The package ships as an npm module with a CLI installer. You point it at
27
+ a target repository, it scaffolds the wiring, and from that point on
28
+ every Claude Code or Codex session in that repository runs under
29
+ governance.
22
30
 
23
- It is meant to produce a runnable integration, not just generate documentation.
31
+ ### What Problems It Addresses
24
32
 
25
- ## Quickstart
33
+ | Problem | How the Package Solves It |
34
+ |---|---|
35
+ | Agent runs destructive commands (`rm -rf /`, `git push --force`) | Blocking `pre-bash` hook evaluates commands against enforcement gates before execution |
36
+ | Agent edits files it should not touch | Blocking `pre-edit` hook checks file paths and diff sizes against policy |
37
+ | Agent leaks secrets in code | Secrets gate scans content for API keys, passwords, and credential patterns |
38
+ | Agent enters runaway loops | ContinueGate monitors step count, rework ratio, and coherence |
39
+ | Memory corruption across sessions | Trust system scores agents; untrusted agents get reduced throughput |
40
+ | No audit trail | HMAC-SHA256 proof chain records every decision with hash-linked envelopes |
41
+ | Rules drift over time | Evolution pipeline proposes, simulates, and stages rule changes with auto-rollback |
42
+ | Prompt injection attacks | Threat detector analyses command and memory-write inputs for injection patterns |
43
+ | Agent collusion in multi-agent setups | Collusion detector identifies suspicious ring-topology interaction patterns |
44
+
45
+ ---
46
+
47
+ ## Guides
48
+
49
+ | Document | Description |
50
+ |---|---|
51
+ | [Quick Start](docs/guide/quick-start.md) | Hands-on tutorial: install, trigger a blocked command, inspect the proof chain |
52
+ | [Authoring CLAUDE.md](docs/guide/authoring-claude-md.md) | How to write rules that compile well into the guidance control plane |
53
+ | [Trust System](docs/guide/trust-system.md) | Trust tiers, scoring, rate limiting, persistence, and inspection |
54
+ | [Gate Configuration](docs/guide/gate-configuration.md) | The four enforcement gates, ContinueGate, threat detection, and tuning |
55
+ | [Evolution Workflow](docs/guide/evolution-workflow.md) | Rule evolution lifecycle: propose, simulate, stage, rollout, autopilot, A/B benchmark |
56
+ | [Deployment](docs/guide/deployment.md) | Production setup, CI/CD integration, signing keys, monitoring, security hardening |
57
+ | [Migration](docs/guide/migration.md) | Adding guidance to existing repos with or without prior hook wiring |
58
+ | [API Reference](docs/guide/api-reference.md) | Full API surface: exports, method signatures, types, CLI binaries, changelog |
59
+
60
+ ---
61
+
62
+ ## 2. Prerequisites
63
+
64
+ - **Node.js** 20 or later
65
+ - **npm** 10 or later
66
+ - A target repository with a `CLAUDE.md` file (or one will be
67
+ scaffolded for you)
68
+
69
+ The package has two runtime dependencies:
70
+
71
+ | Package | Purpose |
72
+ |---|---|
73
+ | `@claude-flow/guidance` ^3.0.0-alpha.1 | The guidance control plane (compiler, gates, trust, proof, adversarial, evolution) |
74
+ | `@claude-flow/hooks` ^3.0.0-alpha.7 | Hook registry and executor for lifecycle event dispatch |
75
+
76
+ Both are installed automatically when you run `npm install` in the
77
+ target repository after the installer adds them to `package.json`.
78
+
79
+ ---
80
+
81
+ ## 3. Component Selection
82
+
83
+ The package includes 8 optional subsystems. Only the Phase 1 core
84
+ (policy compilation, gates, and ledger) is always installed. You choose
85
+ which additional subsystems to include during installation.
86
+
87
+ ### Available Components
88
+
89
+ | Component | What It Adds |
90
+ |---|---|
91
+ | `trust` | Per-agent trust scoring with privilege tiers |
92
+ | `adversarial` | Prompt injection detection, collusion detection, and memory quorum |
93
+ | `proof` | HMAC-SHA256 hash-chained cryptographic proof chain |
94
+ | `conformance` | Memory Clerk acceptance testing with replay verification |
95
+ | `evolution` | Propose, simulate, stage, and rollout rule changes |
96
+ | `autopilot` | One-shot and daemon-mode CLAUDE.md rule optimization with A/B benchmarking |
97
+ | `analysis` | Policy analysis scoring and project scaffolding |
98
+ | `codex` | OpenAI Codex lifecycle bridge for equivalent guidance enforcement |
99
+
100
+ ### Presets
101
+
102
+ | Preset | Components Included |
103
+ |---|---|
104
+ | `minimal` | None (Phase 1 gates only) |
105
+ | `standard` | trust, proof, analysis |
106
+ | `full` | All 8 components |
107
+
108
+ The CLI defaults to `standard` for new installations. The programmatic
109
+ API defaults to `full` for backwards compatibility.
110
+
111
+ ### CLI Flags
26
112
 
27
- Use directly from npm:
113
+ ```bash
114
+ # Use a named preset
115
+ cf-guidance-impl init --target . --preset standard
116
+
117
+ # Explicit component list (overrides preset)
118
+ cf-guidance-impl init --target . --components trust,proof,adversarial
119
+
120
+ # Start from full and exclude specific components
121
+ cf-guidance-impl init --target . --preset full --exclude autopilot,codex
122
+ ```
123
+
124
+ ### Checking Enabled Components
125
+
126
+ After installation, the selected components are persisted to
127
+ `.claude-flow/guidance/components.json`. Subsequent `install` runs
128
+ without flags read this file and preserve your selection.
129
+
130
+ Disabled subsystems use safe no-op stubs at runtime, so no code changes
131
+ are needed in consumers. Methods like `trustSystem.getAllSnapshots()`
132
+ return empty arrays and `proofChain.export()` returns
133
+ `{ envelopes: [] }` when the corresponding component is disabled.
134
+
135
+ ---
136
+
137
+ ## 4. Installation
138
+
139
+ ### Option A: One-Command Install (Recommended)
140
+
141
+ Run directly from npm without a global install:
28
142
 
29
143
  ```bash
30
- npx --yes -p claude-flow-guidance-implementation cf-guidance-impl init --target ~/source/my-project --install-deps
31
- npx --yes -p claude-flow-guidance-implementation cf-guidance-impl verify --target ~/source/my-project
144
+ npx --yes -p claude-flow-guidance-implementation \
145
+ cf-guidance-impl init \
146
+ --target ~/source/my-project \
147
+ --install-deps
32
148
  ```
33
149
 
34
- Or install as a dev dependency:
150
+ This single command:
151
+
152
+ 1. Runs `npx @claude-flow/cli@latest init` in your target repo (sets up
153
+ base claude-flow configuration).
154
+ 2. Writes a thin hook-handler shim to
155
+ `.claude/helpers/hook-handler.cjs`.
156
+ 3. Merges guidance hooks and environment variables into
157
+ `.claude/settings.json`.
158
+ 4. Adds guidance npm scripts and dependencies to `package.json`.
159
+ 5. Creates `CLAUDE.local.md` (for local experiments) and adds it to
160
+ `.gitignore`.
161
+ 6. Runs verification to confirm everything is wired correctly.
162
+
163
+ ### Option B: Install as a Dev Dependency
164
+
165
+ ```bash
166
+ cd ~/source/my-project
167
+ npm install --save-dev claude-flow-guidance-implementation
168
+ npx cf-guidance-impl init --target . --install-deps
169
+ ```
170
+
171
+ ### Verify the Installation
35
172
 
36
173
  ```bash
37
- npm i -D claude-flow-guidance-implementation
38
- npx cf-guidance-impl init --target ~/source/my-project --install-deps
39
174
  npx cf-guidance-impl verify --target ~/source/my-project
40
175
  ```
41
176
 
42
- ## Integration Modes
177
+ The verify command checks:
178
+
179
+ - All required files exist (`.claude/helpers/hook-handler.cjs`,
180
+ `.claude/settings.json`, `package.json`)
181
+ - Helper module compatibility pairs (`.cjs` and `.js` variants)
182
+ - Syntax validation of the hook handler via `node --check`
183
+ - A smoke test that pipes a simulated `pre-bash` event through the hook
184
+ handler
185
+
186
+ A passing verification prints `"passed": true` in the JSON output.
187
+
188
+ ---
189
+
190
+ ## 5. Integration Modes
191
+
192
+ The installer supports three target modes that control which agent
193
+ platform receives hook wiring.
194
+
195
+ | Mode | Flag | What Gets Wired |
196
+ |---|---|---|
197
+ | `both` (default) | `--target-mode both` | Claude Code hooks via `.claude/settings.json` + Codex bridge via `.agents/config.toml` |
198
+ | `claude` | `--target-mode claude` | Claude Code hooks only |
199
+ | `codex` | `--target-mode codex` | Codex bridge only |
200
+
201
+ ```bash
202
+ # Claude Code only
203
+ npx cf-guidance-impl init --target . --target-mode claude
204
+
205
+ # Codex only
206
+ npx cf-guidance-impl init --target . --target-mode codex
207
+
208
+ # Both platforms (default)
209
+ npx cf-guidance-impl init --target .
210
+ ```
211
+
212
+ ### Claude Code Integration
213
+
214
+ When running in `claude` or `both` mode, the installer merges hook
215
+ definitions into `.claude/settings.json`. Claude Code reads this file
216
+ and automatically invokes the hook handler at each lifecycle event. The
217
+ hooks are:
218
+
219
+ | Claude Code Event | Hook Handler Command | Behaviour |
220
+ |---|---|---|
221
+ | `PreToolUse` (Write, Edit, MultiEdit) | `hook-handler.cjs pre-edit` | **Blocking.** Evaluates file path, diff size, and content against gates. Returns exit code 1 to block. |
222
+ | `PreToolUse` (Bash) | `hook-handler.cjs pre-bash` | **Blocking.** Evaluates shell commands against destructive-ops gate and threat detector. Returns exit code 1 to block. |
223
+ | `PreToolUse` (Task) | `hook-handler.cjs pre-task` | **Blocking.** Retrieves task-relevant policy shards and evaluates task description. Returns exit code 1 to block. |
224
+ | `PostToolUse` (Write, Edit, MultiEdit) | `hook-handler.cjs post-edit` | **Async.** Records the edit in the proof chain and intelligence system. Non-blocking. |
225
+ | `PostToolUse` (Task) | `hook-handler.cjs post-task` | **Async.** Records task completion and triggers learning. Non-blocking. |
226
+ | `SessionStart` | `hook-handler.cjs session-restore` | **Async.** Restores session state and loads intelligence patterns. |
227
+ | `SessionEnd` | `hook-handler.cjs session-end` | **Async.** Consolidates intelligence, persists session, launches autopilot. |
228
+
229
+ **Blocking** hooks run synchronously (`spawnSync`). If the guidance
230
+ control plane blocks the action, the hook handler exits with code 1 and
231
+ Claude Code aborts the operation. **Async** hooks spawn detached child
232
+ processes and return immediately so they do not slow down the agent.
233
+
234
+ ### Codex Integration
235
+
236
+ Codex does not have a native hook system like Claude Code's
237
+ `settings.json` event map. Instead, this package provides a bridge
238
+ script (`src/cli/guidance-codex-bridge.js`) that maps Codex lifecycle
239
+ events to the same hook handler.
240
+
241
+ The installer adds npm scripts to `package.json` so Codex can call them
242
+ at each lifecycle point:
243
+
244
+ ```bash
245
+ npm run guidance:codex:session-start
246
+ npm run guidance:codex:pre-task -- --description "Implement feature X"
247
+ npm run guidance:codex:pre-command -- --command "git status"
248
+ npm run guidance:codex:pre-edit -- --file src/example.ts
249
+ npm run guidance:codex:post-edit -- --file src/example.ts
250
+ npm run guidance:codex:post-task -- --task-id task-123 --status completed
251
+ npm run guidance:codex:session-end
252
+ ```
253
+
254
+ The bridge dispatches to the same `.claude/helpers/hook-handler.cjs`
255
+ and, when enabled, also calls `npx @claude-flow/cli@latest hooks ...`
256
+ for telemetry. Disable the secondary call with `--skip-cf-hooks` or
257
+ `GUIDANCE_CODEX_SKIP_CF_HOOKS=1`.
258
+
259
+ ---
260
+
261
+ ## 6. Component Reference
262
+
263
+ ### 6.1 Installer (`src/installer.mjs`)
264
+
265
+ The installer provides three functions:
266
+
267
+ | Function | Purpose |
268
+ |---|---|
269
+ | `initRepo(options)` | Full initialisation: runs `@claude-flow/cli init`, scaffolds files, merges settings, verifies |
270
+ | `installIntoRepo(options)` | Scaffolds files and merges settings without running `@claude-flow/cli init` |
271
+ | `verifyRepo(options)` | Validates that all required files, dependencies, syntax checks, and smoke tests pass |
272
+
273
+ **Options for `initRepo`:**
274
+
275
+ | Option | Type | Default | Description |
276
+ |---|---|---|---|
277
+ | `targetRepo` | string | (required) | Absolute path to the target repository |
278
+ | `targetMode` | `'both'` \| `'claude'` \| `'codex'` | `'both'` | Which platform to wire |
279
+ | `force` | boolean | `false` | Overwrite existing files |
280
+ | `installDeps` | boolean | `false` | Run `npm install` after merging dependencies |
281
+ | `dual` | boolean | `true` | Pass `--dual` to `@claude-flow/cli init` (for `both` mode) |
282
+ | `skipCfInit` | boolean | `false` | Skip the `@claude-flow/cli init` step |
283
+ | `verify` | boolean | `true` | Run verification after install |
284
+
285
+ ### 6.2 Hook Handler (`src/hook-handler.cjs`)
286
+
287
+ The central dispatcher. This is a CommonJS file (`.cjs`) because Claude
288
+ Code's hook system spawns it via `node`, and CommonJS provides the
289
+ fastest cold-start time (no ESM module resolution overhead).
290
+
291
+ **Commands:**
292
+
293
+ | Command | When Invoked | Blocking | What It Does |
294
+ |---|---|---|---|
295
+ | `pre-bash` | Before a shell command | Yes | Runs guidance gates on the command. Checks for dangerous patterns (`rm -rf /`, fork bombs). Runs adversarial threat detection. Exits 1 to block. |
296
+ | `pre-edit` | Before a file write/edit | Yes | Runs guidance gates on the file path, diff size, and content. Exits 1 to block. |
297
+ | `pre-task` | Before a task starts | Yes | Retrieves task-relevant policy shards. Routes to recommended agent. Remembers task context for the matching `post-task`. Exits 1 to block. |
298
+ | `post-edit` | After a file write/edit | No | Records the edit in the intelligence system and launches async guidance event. |
299
+ | `post-task` | After a task completes | No | Records task completion. Triggers intelligence feedback. Launches async guidance event. |
300
+ | `session-restore` | At session start | No | Restores session state, loads intelligence patterns. |
301
+ | `session-end` | At session end | No | Consolidates intelligence, persists session, launches autopilot. |
302
+ | `route` | On demand | No | Routes a prompt to the recommended agent type with confidence score. |
303
+ | `compact-manual` | Before manual context compaction | No | Prints guidance reminders for the compaction operation. |
304
+ | `compact-auto` | Before automatic context compaction | No | Prints guidance context for auto-compaction. |
305
+ | `status` | On demand | No | Health check. |
306
+ | `stats` | On demand | No | Prints intelligence system statistics. |
307
+
308
+ **Stdin protocol:** Claude Code passes a JSON object on stdin with the
309
+ shape `{ tool_input: { command, file_path, ... }, tool_name, ... }`.
310
+ The hook handler parses this to extract the command text, file path,
311
+ task description, and other parameters.
312
+
313
+ **Exit codes:** Exit 0 means the action is allowed. Exit 1 means the
314
+ action is blocked. Async hooks always exit 0 because they do not gate
315
+ the action.
316
+
317
+ ### 6.3 Phase 1 Runtime (`src/guidance/phase1-runtime.js`)
318
+
319
+ Wraps the four core guidance modules into a single class.
320
+
321
+ ```
322
+ CLAUDE.md -> GuidanceCompiler -> Bundle -> ShardRetriever -> EnforcementGates -> PersistentLedger
323
+ ```
324
+
325
+ **Constructor options:**
326
+
327
+ | Option | Default | Description |
328
+ |---|---|---|
329
+ | `rootDir` | `process.cwd()` | Project root directory |
330
+ | `rootGuidancePath` | `'CLAUDE.md'` | Path to the shared guidance file |
331
+ | `localGuidancePath` | `'CLAUDE.local.md'` | Path to the local guidance file |
332
+ | `gateConfig` | `{}` | Custom gate configuration overrides |
333
+
334
+ **Methods:**
335
+
336
+ | Method | Returns | Description |
337
+ |---|---|---|
338
+ | `initialize()` | Promise\<void\> | Compiles CLAUDE.md, loads shards, sets active rules on gates, registers hooks |
339
+ | `preTask({ taskId, taskDescription })` | Promise\<HookResult\> | Evaluates a task against policy before execution |
340
+ | `postTask({ taskId, status, toolsUsed, filesTouched })` | Promise\<HookResult\> | Records task completion in the ledger |
341
+ | `preCommand(command)` | Promise\<HookResult\> | Evaluates a shell command against gates |
342
+ | `preToolUse(toolName, parameters)` | Promise\<HookResult\> | Evaluates a tool invocation against gates |
343
+ | `preEdit({ filePath, operation, content, diffLines })` | Promise\<HookResult\> | Evaluates a file edit against gates |
344
+ | `isBlocked(result)` | boolean | Returns true if the hook result indicates the action was blocked |
345
+ | `extractPolicyText(result)` | string \| null | Extracts the policy text injected by the retriever for context |
346
+ | `getBundle()` | Bundle | Returns the compiled policy bundle |
347
+ | `getStatus()` | object | Returns runtime metrics (hook count, shard count, gate count, ledger events) |
348
+
349
+ ### 6.4 Advanced Runtime (`src/guidance/advanced-runtime.js`)
350
+
351
+ Extends the Phase 1 runtime with trust scoring, adversarial defence,
352
+ cryptographic proof chains, conformance testing, and rule evolution.
353
+
354
+ **Architecture:**
355
+
356
+ ```
357
+ Phase 1 Runtime
358
+ +-- TrustSystem -> Per-agent scoring with privilege tiers
359
+ +-- ThreatDetector -> Prompt injection detection
360
+ +-- CollusionDetector -> Ring-topology interaction analysis
361
+ +-- MemoryQuorum -> Voting-based writes for critical data
362
+ +-- ProofChain -> HMAC-SHA256 hash-chained decision envelopes
363
+ +-- ConformanceRunner -> Memory Clerk acceptance testing with replay
364
+ +-- EvolutionPipeline -> Propose -> Simulate -> Stage -> Rollout
365
+ ```
366
+
367
+ **Key methods:**
368
+
369
+ | Method | Description |
370
+ |---|---|
371
+ | `initialize()` | Initialises Phase 1, restores persisted trust scores and proof chain from disk |
372
+ | `recordTrust(agentId, outcome, reason)` | Records a trust event (allow/warn/deny) for the given agent |
373
+ | `appendProof({ taskId, agentId, toolsUsed, violations, ... })` | Appends a decision envelope to the proof chain |
374
+ | `persistState(extra)` | Writes trust snapshots, threat history, and proof chain to disk |
375
+ | `getStatus()` | Returns metrics including trust agents, threat signals, proof chain length, evolution proposals |
376
+
377
+ **Integration runners** (available via the runtime instance):
43
378
 
44
- | Mode | What gets wired |
379
+ | Method | Description |
45
380
  |---|---|
46
- | `both` (default) | Claude hooks + Codex bridge + guidance scripts |
47
- | `claude` | Claude hooks + guidance scripts |
48
- | `codex` | Codex bridge + guidance scripts |
381
+ | `runHooksIntegration()` | End-to-end test of the hook pipeline with safe and destructive commands |
382
+ | `runTrustIntegration()` | Records a sequence of outcomes and reports the trust tier |
383
+ | `runAdversarialIntegration()` | Tests injection detection, collusion detection, and memory quorum |
384
+ | `runProofIntegration()` | Appends proof envelopes and verifies chain integrity |
385
+ | `runConformanceIntegration()` | Runs Memory Clerk acceptance tests with replay verification |
386
+ | `runEvolutionIntegration()` | Full evolution pipeline: propose, simulate, compare, stage, advance |
387
+ | `runAllIntegrations()` | Runs all six integration runners and returns a combined report |
49
388
 
50
- Examples:
389
+ ### 6.5 Event Handlers (`src/cli/event-handlers.js`)
390
+
391
+ Implements the full event processing pipeline for guidance events
392
+ dispatched from the hook handler. Each event type follows the same
393
+ pattern:
394
+
395
+ 1. Evaluate the action through Phase 1 gates.
396
+ 2. Run adversarial threat detection (for `pre-command`).
397
+ 3. Record the trust outcome.
398
+ 4. Append a proof envelope.
399
+ 5. Persist state.
400
+ 6. Return a structured summary with the block/allow decision.
401
+
402
+ Supported events: `pre-command`, `pre-edit`, `pre-task`, `post-task`,
403
+ `post-edit`, `session-end`.
404
+
405
+ ### 6.6 Codex Bridge (`src/cli/guidance-codex-bridge.js`)
406
+
407
+ Adapts Codex lifecycle events to the hook handler protocol. Accepts
408
+ command-line arguments, constructs the stdin JSON that the hook handler
409
+ expects, spawns `hook-handler.cjs` via `spawnSync`, and optionally
410
+ forwards to `@claude-flow/cli` hooks for telemetry.
411
+
412
+ ### 6.7 Autopilot (`src/cli/guidance-autopilot.js`)
413
+
414
+ Continuously or one-shot optimises `CLAUDE.md` rules by:
415
+
416
+ 1. Analysing the current CLAUDE.md with the guidance analyzer.
417
+ 2. Identifying local rules in `CLAUDE.local.md` that score higher.
418
+ 3. Promoting winning local rules into `CLAUDE.md`.
419
+ 4. Optionally running A/B benchmarks to validate the promotion.
420
+
421
+ **Modes:**
422
+
423
+ | Flag | Behaviour |
424
+ |---|---|
425
+ | `--once` | Run one optimisation cycle and exit |
426
+ | `--daemon` | Run on a timer (default: 30 minutes) |
427
+ | `--apply` | Apply promotions to CLAUDE.md (without this flag, dry-run only) |
428
+ | `--ab` | Run A/B benchmark before promoting |
429
+
430
+ **Environment variables:**
431
+
432
+ | Variable | Default | Description |
433
+ |---|---|---|
434
+ | `GUIDANCE_AUTOPILOT_ENABLED` | `1` | Set to `0` to disable autopilot globally |
435
+ | `GUIDANCE_AUTOPILOT_MIN_DELTA` | `0.5` | Minimum score improvement to trigger promotion |
436
+ | `GUIDANCE_AUTOPILOT_AB` | `0` | Set to `1` to enable A/B benchmarking before promotion |
437
+ | `GUIDANCE_AUTOPILOT_MIN_AB_GAIN` | `0.05` | Minimum A/B composite gain to proceed |
438
+
439
+ ### 6.8 Analyzer (`src/cli/analyze-guidance.js`)
440
+
441
+ Compiles `CLAUDE.md` into a policy bundle and scores it across six
442
+ dimensions:
443
+
444
+ | Dimension | What It Measures |
445
+ |---|---|
446
+ | Structure | Heading hierarchy, section organisation |
447
+ | Coverage | Breadth of topics covered (security, testing, deployment, etc.) |
448
+ | Enforceability | Ratio of rules with clear MUST/NEVER/ALWAYS enforcement language |
449
+ | Compilability | Successful compilation into typed policy bundles |
450
+ | Clarity | Readability and conciseness of rule text |
451
+ | Completeness | Presence of all recommended sections |
452
+
453
+ Run with `--optimize` to auto-improve the CLAUDE.md score.
454
+
455
+ ### 6.9 A/B Benchmark (`src/cli/guidance-ab-benchmark.js`)
456
+
457
+ Runs controlled comparisons using a synthetic content-aware executor:
458
+
459
+ 1. **Config A (Baseline):** Executes 20 tasks with no guidance context.
460
+ 2. **Config B (Guided):** Executes the same 20 tasks with the compiled
461
+ CLAUDE.md injected as context.
462
+ 3. Measures success rate, violations, interventions, and cost.
463
+ 4. Reports a composite score delta and category shift.
464
+
465
+ The synthetic executor does not call an LLM. It simulates agent
466
+ behaviour based on the enforcement strength of the CLAUDE.md content
467
+ (counting MUST/NEVER/ALWAYS terms) to produce deterministic,
468
+ reproducible benchmarks.
469
+
470
+ ### 6.10 Scaffold (`src/cli/scaffold-guidance.js`)
471
+
472
+ Generates a recommended `CLAUDE.md` from your project's `package.json`.
473
+ Detects frameworks, build commands, test commands, and produces a
474
+ structured guidance file with best-practice rules.
51
475
 
52
476
  ```bash
53
- npx cf-guidance-impl init --target ~/source/my-project --target-mode both
54
- npx cf-guidance-impl init --target ~/source/my-project --target-mode claude
55
- npx cf-guidance-impl init --target ~/source/my-project --target-mode codex
477
+ npx cf-guidance-scaffold --output ./scaffolded
56
478
  ```
57
479
 
58
- ## CLI Reference
480
+ ### 6.11 Default Settings (`src/default-settings.mjs`)
481
+
482
+ Exports the default hook definitions, environment variables, npm
483
+ scripts, and dependency declarations that the installer merges into the
484
+ target repository. These values are the source of truth for what the
485
+ installer writes.
486
+
487
+ ### 6.12 Content-Aware Executor (`src/guidance/content-aware-executor.js`)
488
+
489
+ A lightweight synthetic executor used by the A/B benchmark. It does not
490
+ call any LLM. Instead, it counts enforcement terms in the CLAUDE.md to
491
+ determine guidance strength and produces prompt-sensitive output
492
+ snippets that simulate guided vs. unguided agent behaviour.
493
+
494
+ ---
495
+
496
+ ## 7. How the Hook Integration Works
497
+
498
+ ### 7.1 The Request Path
499
+
500
+ When Claude Code is about to execute a tool (shell command, file edit,
501
+ or task), the following sequence runs:
502
+
503
+ ```
504
+ Claude Code
505
+ |
506
+ +- PreToolUse event fires
507
+ |
508
+ +- Claude Code reads .claude/settings.json
509
+ | +- Finds hook: node .claude/helpers/hook-handler.cjs pre-bash
510
+ |
511
+ +- Spawns hook-handler.cjs synchronously (spawnSync)
512
+ | +- Receives { tool_input: { command: "..." } } on stdin
513
+ | |
514
+ | +- hook-handler.cjs dispatches to handlePreBash()
515
+ | | +- Calls guidance-integrations.js event pre-command synchronously
516
+ | | | +- Initialises GuidanceAdvancedRuntime
517
+ | | | +- Compiles CLAUDE.md -> policy bundle
518
+ | | | +- Evaluates command through 4 enforcement gates
519
+ | | | +- Runs adversarial threat detection
520
+ | | | +- Records trust outcome
521
+ | | | +- Appends proof envelope
522
+ | | | +- Returns { blocked: true/false }
523
+ | | |
524
+ | | +- Checks local dangerous-pattern regex list
525
+ | | +- If blocked -> stderr "[BLOCKED]", exit(1)
526
+ | |
527
+ | +- exit(0) if allowed
528
+ |
529
+ +- Claude Code proceeds with (or aborts) the tool use
530
+ ```
531
+
532
+ ### 7.2 Blocking vs. Async Hooks
533
+
534
+ **Blocking hooks** (`pre-bash`, `pre-edit`, `pre-task`) use `spawnSync`
535
+ to call the guidance event handler. The hook handler waits for the
536
+ result and returns exit code 1 to block or 0 to allow. Claude Code
537
+ honours the exit code and aborts the tool use if it is non-zero.
538
+
539
+ **Async hooks** (`post-edit`, `post-task`, `session-end`) use `spawn`
540
+ with `detached: true` and `stdio: 'ignore'`. The child process runs in
541
+ the background and the hook handler returns immediately with exit code
542
+ 0. This ensures post-action recording does not slow down the agent.
543
+
544
+ ### 7.3 The Hook Handler Dispatch Table
545
+
546
+ The hook handler uses a flat dispatch table:
547
+
548
+ ```javascript
549
+ const handlers = {
550
+ 'route': handleRoute,
551
+ 'pre-bash': handlePreBash,
552
+ 'pre-edit': handlePreEdit,
553
+ 'post-edit': handlePostEdit,
554
+ 'session-restore': handleSessionRestore,
555
+ 'session-end': handleSessionEnd,
556
+ 'pre-task': handlePreTask,
557
+ 'post-task': handlePostTask,
558
+ 'compact-manual': handleCompactManual,
559
+ 'compact-auto': handleCompactAuto,
560
+ 'status': handleStatus,
561
+ 'stats': handleStats,
562
+ };
563
+ ```
564
+
565
+ Each handler function is self-contained and accesses shared utilities
566
+ (stdin parsing, guidance event dispatch, task cache) through module-level
567
+ functions.
568
+
569
+ ### 7.4 Task Context Persistence
570
+
571
+ The hook handler maintains a task cache at
572
+ `.claude-flow/guidance/hook-task-cache.json`. When `pre-task` fires, it
573
+ writes the task ID and description. When `post-task` fires (often
574
+ without the original description), it reads back the cached context to
575
+ correlate the completion with the original task. This is necessary
576
+ because Claude Code does not pass the task description in the
577
+ `PostToolUse` event.
578
+
579
+ ---
580
+
581
+ ## 8. Environment Variables
582
+
583
+ | Variable | Default | Description |
584
+ |---|---|---|
585
+ | `GUIDANCE_EVENT_WIRING_ENABLED` | `1` | Set to `0` to disable all guidance event wiring |
586
+ | `GUIDANCE_EVENT_SYNC_TIMEOUT_MS` | `8000` | Timeout for blocking guidance calls (milliseconds) |
587
+ | `GUIDANCE_EVENT_FAIL_CLOSED` | `0` | Set to `1` to block actions when guidance calls fail (fail-closed mode) |
588
+ | `GUIDANCE_PROOF_KEY` | *(dev key)* | HMAC signing key for proof chain envelopes. Set in production. |
589
+ | `GUIDANCE_AUTOPILOT_ENABLED` | `1` | Set to `0` to disable autopilot at session end |
590
+ | `GUIDANCE_AUTOPILOT_MIN_DELTA` | `0.5` | Minimum score improvement to trigger rule promotion |
591
+ | `GUIDANCE_AUTOPILOT_AB` | `0` | Set to `1` to enable A/B benchmarking before promotion |
592
+ | `GUIDANCE_AUTOPILOT_MIN_AB_GAIN` | `0.05` | Minimum A/B composite gain to proceed with promotion |
593
+ | `GUIDANCE_CODEX_SKIP_CF_HOOKS` | `0` | Set to `1` to skip secondary `@claude-flow/cli` hook calls in Codex bridge |
594
+ | `GUIDANCE_PROJECT_DIR` | *(cwd)* | Override the project root directory for CLI scripts |
595
+ | `CLAUDE_PROJECT_DIR` | *(cwd)* | Fallback project root directory (set by Claude Code) |
596
+ | `CLAUDE_SESSION_ID` | *(auto)* | Session identifier |
597
+ | `CLAUDE_AGENT_ID` | `claude-main` | Agent identifier for trust scoring |
598
+
599
+ ---
600
+
601
+ ## 9. CLI Reference
602
+
603
+ ### Installer CLI (`cf-guidance-impl`)
59
604
 
60
605
  ```bash
61
- cf-guidance-impl init --target <repoPath> [--target-mode both|claude|codex] [--force] [--install-deps] [--no-dual] [--skip-cf-init] [--no-verify]
62
- cf-guidance-impl install --target <repoPath> [--target-mode both|claude|codex] [--force] [--install-deps]
63
- cf-guidance-impl verify --target <repoPath> [--target-mode both|claude|codex]
64
- ```
65
-
66
- ## What `init` Changes In Your Target Repo
67
-
68
- `cf-guidance-impl init` performs:
69
-
70
- 1. Runs `npx @claude-flow/cli@latest init` unless `--skip-cf-init`.
71
- 2. Adds CLI mode flags automatically:
72
- - `both` uses `--dual` unless `--no-dual`
73
- - `codex` uses `--codex`
74
- - `claude` uses standard init
75
- 3. Copies scaffold runtime files (`scripts/`, `src/guidance/`, docs, hook handler).
76
- 4. Merges guidance scripts and dependencies into `package.json`.
77
- 5. Merges `.claude/settings.json` env and hooks in Claude-enabled modes.
78
- 6. Appends Codex bridge sections to `.agents/config.toml` and `AGENTS.md` in Codex-enabled modes.
79
- 7. Creates `CLAUDE.local.md` (if missing) and appends `CLAUDE.local.md` to `.gitignore`.
80
- 8. Runs verification unless `--no-verify`.
81
-
82
- ## Installed Scripts (Target Repo)
83
-
84
- Core:
85
-
86
- - `guidance:analyze`
87
- - `guidance:optimize`
88
- - `guidance:autopilot:once`
89
- - `guidance:autopilot:daemon`
90
- - `guidance:ab-benchmark`
91
- - `guidance:status`
92
- - `guidance:all`
93
- - `guidance:trust`
94
- - `guidance:adversarial`
95
- - `guidance:proof`
96
- - `guidance:conformance`
97
- - `guidance:evolution`
98
-
99
- Codex lifecycle bridge:
100
-
101
- - `guidance:codex:status`
102
- - `guidance:codex:session-start`
103
- - `guidance:codex:pre-command`
104
- - `guidance:codex:pre-edit`
105
- - `guidance:codex:pre-task`
106
- - `guidance:codex:post-edit`
107
- - `guidance:codex:post-task`
108
- - `guidance:codex:session-end`
109
-
110
- ## Manual Runtime Mode (No Copied Runtime Files)
111
-
112
- You can also execute scripts directly from `node_modules`:
113
-
114
- ```json
115
- {
116
- "scripts": {
117
- "guidance:analyze": "node ./node_modules/claude-flow-guidance-implementation/scaffold/scripts/analyze-guidance.js",
118
- "guidance:optimize": "node ./node_modules/claude-flow-guidance-implementation/scaffold/scripts/guidance-autopilot.js --once --apply --source manual",
119
- "guidance:ab-benchmark": "node ./node_modules/claude-flow-guidance-implementation/scaffold/scripts/guidance-ab-benchmark.js",
120
- "guidance:codex:status": "node ./node_modules/claude-flow-guidance-implementation/scaffold/scripts/guidance-codex-bridge.js status"
121
- }
606
+ # Full initialisation (recommended)
607
+ cf-guidance-impl init \
608
+ --target <path> \
609
+ [--target-mode both|claude|codex] \
610
+ [--force] \
611
+ [--install-deps] \
612
+ [--no-dual] \
613
+ [--skip-cf-init] \
614
+ [--no-verify] \
615
+ [--fail-closed] \
616
+ [--hook-timeout <ms>] \
617
+ [--event-timeout <ms>] \
618
+ [--generate-key] \
619
+ [--no-autopilot] \
620
+ [--dry-run]
621
+
622
+ # Install without running @claude-flow/cli init
623
+ cf-guidance-impl install \
624
+ --target <path> \
625
+ [--target-mode both|claude|codex] \
626
+ [--force] \
627
+ [--install-deps] \
628
+ [--fail-closed] \
629
+ [--hook-timeout <ms>] \
630
+ [--event-timeout <ms>] \
631
+ [--generate-key] \
632
+ [--no-autopilot] \
633
+ [--dry-run]
634
+
635
+ # Verify installation
636
+ cf-guidance-impl verify \
637
+ --target <path> \
638
+ [--target-mode both|claude|codex]
639
+ ```
640
+
641
+ **Additional flags for `init` and `install`:**
642
+
643
+ | Flag | Description |
644
+ |---|---|
645
+ | `--fail-closed` | Set `GUIDANCE_EVENT_FAIL_CLOSED=1` in settings (block on hook failure). |
646
+ | `--hook-timeout <ms>` | Override the timeout on every hook definition (default: 5000 ms). |
647
+ | `--event-timeout <ms>` | Set `GUIDANCE_EVENT_SYNC_TIMEOUT_MS` in settings. |
648
+ | `--generate-key` | Generate a cryptographic signing key and set `GUIDANCE_PROOF_KEY`. |
649
+ | `--no-autopilot` | Set `GUIDANCE_AUTOPILOT_ENABLED=0` (disable autopilot). |
650
+ | `--dry-run` | Print a JSON report of what would be written, then exit without changes. |
651
+
652
+ ### Guidance Runtime CLIs
653
+
654
+ | Command | Description |
655
+ |---|---|
656
+ | `cf-guidance status` | Print runtime status (initialised, hook count, shard count, gate count) |
657
+ | `cf-guidance hooks [taskDescription]` | Run hooks integration test |
658
+ | `cf-guidance trust` | Run trust integration test |
659
+ | `cf-guidance adversarial` | Run adversarial integration test |
660
+ | `cf-guidance proof` | Run proof chain integration test |
661
+ | `cf-guidance conformance` | Run conformance integration test |
662
+ | `cf-guidance evolution` | Run evolution pipeline integration test |
663
+ | `cf-guidance all` | Run all integration tests |
664
+ | `cf-guidance event <name> [json]` | Dispatch a single guidance event |
665
+ | `cf-guidance-runtime demo` | Run a demo sequence (pre-task, pre-command safe/destructive, post-task) |
666
+ | `cf-guidance-runtime status` | Print Phase 1 runtime status |
667
+ | `cf-guidance-runtime task "<desc>" [id]` | Evaluate a task through the runtime |
668
+ | `cf-guidance-runtime command "<cmd>"` | Evaluate a shell command through gates |
669
+ | `cf-guidance-runtime tool "<name>" [json]` | Evaluate a tool use through gates |
670
+ | `cf-guidance-runtime edit "<path>" [lines]` | Evaluate a file edit through gates |
671
+ | `cf-guidance-analyze` | Analyse and score CLAUDE.md |
672
+ | `cf-guidance-analyze --optimize` | Analyse, then auto-optimise CLAUDE.md |
673
+ | `cf-guidance-autopilot --once --apply` | One-shot rule promotion |
674
+ | `cf-guidance-autopilot --daemon --apply` | Daemon-mode rule promotion |
675
+ | `cf-guidance-benchmark` | Run A/B benchmark |
676
+ | `cf-guidance-scaffold` | Generate CLAUDE.md from package.json |
677
+ | `cf-guidance-codex <event> [options]` | Codex bridge (see Section 5) |
678
+
679
+ ---
680
+
681
+ ## 10. npm Scripts (Installed in Target Repo)
682
+
683
+ After running `cf-guidance-impl init`, the following scripts are
684
+ available in the target repository:
685
+
686
+ | Script | What It Runs |
687
+ |---|---|
688
+ | `npm run guidance:analyze` | Score CLAUDE.md across 6 dimensions |
689
+ | `npm run guidance:optimize` | One-shot rule optimisation with apply |
690
+ | `npm run guidance:autopilot:once` | One-shot autopilot (dry-run) |
691
+ | `npm run guidance:autopilot:daemon` | Daemon-mode autopilot |
692
+ | `npm run guidance:ab-benchmark` | A/B benchmark |
693
+ | `npm run guidance:scaffold` | Scaffold CLAUDE.md |
694
+ | `npm run guidance:status` | Runtime status |
695
+ | `npm run guidance:all` | Run all integration tests |
696
+ | `npm run guidance:hooks` | Hooks integration test |
697
+ | `npm run guidance:trust` | Trust integration test |
698
+ | `npm run guidance:adversarial` | Adversarial integration test |
699
+ | `npm run guidance:proof` | Proof chain integration test |
700
+ | `npm run guidance:conformance` | Conformance integration test |
701
+ | `npm run guidance:evolution` | Evolution pipeline integration test |
702
+ | `npm run guidance:runtime` | Runtime demo |
703
+ | `npm run guidance:codex:status` | Codex bridge status |
704
+ | `npm run guidance:codex:session-start` | Codex session start |
705
+ | `npm run guidance:codex:pre-command` | Codex pre-command |
706
+ | `npm run guidance:codex:pre-edit` | Codex pre-edit |
707
+ | `npm run guidance:codex:pre-task` | Codex pre-task |
708
+ | `npm run guidance:codex:post-edit` | Codex post-edit |
709
+ | `npm run guidance:codex:post-task` | Codex post-task |
710
+ | `npm run guidance:codex:session-end` | Codex session end |
711
+
712
+ ---
713
+
714
+ ## 11. Programmatic API
715
+
716
+ The package exports several entry points for use in your own code:
717
+
718
+ ```javascript
719
+ // Full installer API
720
+ import { initRepo, installIntoRepo, verifyRepo } from 'claude-flow-guidance-implementation/installer';
721
+
722
+ // Default settings (hooks, env, scripts, deps)
723
+ import {
724
+ GUIDANCE_ENV_DEFAULTS,
725
+ GUIDANCE_HOOKS_DEFAULTS,
726
+ GUIDANCE_PACKAGE_SCRIPTS,
727
+ GUIDANCE_PACKAGE_DEPS,
728
+ } from 'claude-flow-guidance-implementation/settings';
729
+
730
+ // Phase 1 runtime (compile -> retrieve -> gates -> ledger)
731
+ import { createGuidancePhase1Runtime } from 'claude-flow-guidance-implementation/phase1';
732
+
733
+ // Advanced runtime (trust + adversarial + proof + conformance + evolution)
734
+ import { createGuidanceAdvancedRuntime } from 'claude-flow-guidance-implementation/runtime';
735
+
736
+ // Synthetic executor for benchmarks
737
+ import { createSyntheticContentAwareExecutor } from 'claude-flow-guidance-implementation/executor';
738
+ ```
739
+
740
+ ### Example: Evaluating a Command Programmatically
741
+
742
+ ```javascript
743
+ import { createGuidancePhase1Runtime } from 'claude-flow-guidance-implementation/phase1';
744
+
745
+ const runtime = createGuidancePhase1Runtime({
746
+ rootDir: '/path/to/project',
747
+ });
748
+ await runtime.initialize();
749
+
750
+ const result = await runtime.preCommand('git push --force origin main');
751
+ if (runtime.isBlocked(result)) {
752
+ console.log('Command blocked by guidance policy');
753
+ } else {
754
+ console.log('Command allowed');
122
755
  }
123
756
  ```
124
757
 
125
- Project root resolution for scaffold scripts:
758
+ ### Example: Running the Full Integration Suite
759
+
760
+ ```javascript
761
+ import { createGuidanceAdvancedRuntime } from 'claude-flow-guidance-implementation/runtime';
762
+
763
+ const runtime = createGuidanceAdvancedRuntime({
764
+ rootDir: '/path/to/project',
765
+ signingKey: process.env.GUIDANCE_PROOF_KEY,
766
+ });
767
+
768
+ const report = await runtime.runAllIntegrations();
769
+ console.log(JSON.stringify(report, null, 2));
770
+ ```
771
+
772
+ ---
126
773
 
127
- - `GUIDANCE_PROJECT_DIR` if set
128
- - else `CLAUDE_PROJECT_DIR` if set
129
- - else `process.cwd()`
774
+ ## 12. File Layout
130
775
 
131
- ## Verify + Smoke Test
776
+ After installation, your target repository contains:
777
+
778
+ ```
779
+ my-project/
780
+ +-- .claude/
781
+ | +-- helpers/
782
+ | | +-- hook-handler.cjs <- Thin shim (delegates to npm package)
783
+ | +-- settings.json <- Hook definitions + env vars
784
+ +-- .agents/
785
+ | +-- config.toml <- Codex bridge configuration (if Codex mode)
786
+ +-- .claude-flow/
787
+ | +-- guidance/
788
+ | +-- advanced/
789
+ | | +-- advanced-state.json <- Persisted trust + threat state
790
+ | | +-- proof-chain.json <- Proof chain envelopes
791
+ | +-- hook-task-cache.json <- Task context correlation cache
792
+ +-- CLAUDE.md <- Shared team guidance (committed)
793
+ +-- CLAUDE.local.md <- Local experiments (gitignored)
794
+ +-- AGENTS.md <- Codex agent documentation (if Codex mode)
795
+ +-- package.json <- Guidance scripts + dependencies merged
796
+ ```
797
+
798
+ ---
799
+
800
+ ## 13. Troubleshooting
801
+
802
+ ### Hook handler exits with "Missing required guidance file"
803
+
804
+ Your project does not have a `CLAUDE.md` file. Create one manually or
805
+ run `npx cf-guidance-scaffold` to generate one from your `package.json`.
806
+
807
+ ### Verification fails on "dependency:claude-flow-guidance-implementation"
808
+
809
+ Run `npm install` in your target repository. The installer adds the
810
+ dependency to `package.json` but only runs `npm install` when you pass
811
+ `--install-deps`.
812
+
813
+ ### Blocking hooks are too slow
814
+
815
+ The default sync timeout is 8000 ms. Lower it with:
132
816
 
133
817
  ```bash
134
- npx cf-guidance-impl verify --target ~/source/my-project
135
- cd ~/source/my-project
136
- npm run guidance:status
137
- npm run guidance:analyze
138
- npm run guidance:codex:status
818
+ export GUIDANCE_EVENT_SYNC_TIMEOUT_MS=3000
139
819
  ```
140
820
 
141
- For Codex bridge smoke checks:
821
+ Or set it in `.claude/settings.json` under `env`.
822
+
823
+ ### Hook blocks a command that should be allowed
824
+
825
+ 1. Check which gate blocked it:
826
+ ```bash
827
+ npx cf-guidance-runtime command "your command here"
828
+ ```
829
+ 2. Review your CLAUDE.md rules for overly broad patterns.
830
+ 3. Temporarily disable guidance wiring:
831
+ ```bash
832
+ export GUIDANCE_EVENT_WIRING_ENABLED=0
833
+ ```
834
+
835
+ ### Proof chain file is corrupted
836
+
837
+ Delete `.claude-flow/guidance/advanced/proof-chain.json`. The runtime
838
+ starts a fresh chain on the next initialisation.
839
+
840
+ ### "GUIDANCE_PROOF_KEY not set" warning
841
+
842
+ Set a production signing key:
142
843
 
143
844
  ```bash
144
- npm run guidance:codex:pre-task -- --task-id smoke-1 --description "smoke"
845
+ export GUIDANCE_PROOF_KEY=$(openssl rand -hex 32)
145
846
  ```
146
847
 
147
- Expected success signals:
848
+ Without this, the runtime uses an insecure development key. Proof chains
849
+ signed with the dev key should not be used for compliance purposes.
148
850
 
149
- - `handler.ok: true` means local bridge path succeeded
150
- - `claudeFlowHook.ok: true` means optional `@claude-flow/cli` hook call succeeded
851
+ ---
151
852
 
152
- ## Installed Files (High-Level)
853
+ ## 14. Security Considerations
153
854
 
154
- | Path | Purpose |
155
- |---|---|
156
- | `.claude/helpers/hook-handler.cjs` | Event entrypoint for hook dispatch |
157
- | `scripts/guidance-integrations.js` | Unified guidance module runner |
158
- | `scripts/guidance-codex-bridge.js` | Codex lifecycle adapter |
159
- | `scripts/guidance-autopilot.js` | Local-rule optimization/promotion loop |
160
- | `src/guidance/phase1-runtime.js` | Compile/retrieve/gates/ledger integration |
161
- | `src/guidance/advanced-runtime.js` | Trust/adversarial/proof/conformance/evolution modules |
162
- | `docs/guidance-control-plane.md` | Operational overview |
163
- | `docs/guidance-implementation-guide.md` | Authoritative implementation guide |
855
+ - **Fail-open by default.** If the guidance control plane fails (crash,
856
+ timeout, missing dependency), actions are allowed to proceed. Set
857
+ `GUIDANCE_EVENT_FAIL_CLOSED=1` for fail-closed mode in production.
858
+ - **Proof chain signing.** Always set `GUIDANCE_PROOF_KEY` in
859
+ production. Without it, anyone can forge proof envelopes.
860
+ - **CLAUDE.local.md is gitignored.** Local experiments are not shared
861
+ with the team. The autopilot can promote winning local rules into the
862
+ shared CLAUDE.md.
863
+ - **Credential scanning.** The secrets gate scans file content for API
864
+ key, password, and credential patterns. It does not replace a
865
+ dedicated secrets scanner like `gitleaks` or `trufflehog`.
866
+ - **Threat detection is heuristic.** The threat detector uses pattern
867
+ matching, not ML. Sophisticated prompt injections may not be caught.
868
+ Layer this with other security controls.
869
+
870
+ ---
164
871
 
165
872
  ## Links
166
873
 
167
- - Homepage: https://sparklingideas.co.uk/guidance
874
+ - Homepage: https://sparklingideas.co.uk/guidance/claude-flow
168
875
  - Package: https://www.npmjs.com/package/claude-flow-guidance-implementation
169
876
  - GitHub: https://github.com/sparkling/claude-flow-guidance-implementation
170
877
  - Issues: https://github.com/sparkling/claude-flow-guidance-implementation/issues