avorelo 0.1.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 (258) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +56 -0
  3. package/bin/avorelo +9 -0
  4. package/package.json +135 -0
  5. package/scripts/README.md +40 -0
  6. package/scripts/cco-dashboard.js +252 -0
  7. package/scripts/cco-status.js +430 -0
  8. package/scripts/lib/activation/account-state.js +37 -0
  9. package/scripts/lib/activation/activation-runner.js +546 -0
  10. package/scripts/lib/activation/activation-self-healing.js +480 -0
  11. package/scripts/lib/activation/activation-state.js +83 -0
  12. package/scripts/lib/activation/activation-summary.js +191 -0
  13. package/scripts/lib/activation/adapters/claude-code.js +77 -0
  14. package/scripts/lib/activation/adapters/codex-cli.js +52 -0
  15. package/scripts/lib/activation/adapters/cursor.js +37 -0
  16. package/scripts/lib/activation/adapters/github-agent.js +39 -0
  17. package/scripts/lib/activation/adapters/terminal.js +42 -0
  18. package/scripts/lib/activation/adapters/vscode.js +39 -0
  19. package/scripts/lib/activation/adapters/windsurf.js +37 -0
  20. package/scripts/lib/activation/ai-surface-detector.js +151 -0
  21. package/scripts/lib/activation/connect-account.js +145 -0
  22. package/scripts/lib/activation/detect-environment.js +75 -0
  23. package/scripts/lib/activation/detect-hosts.js +62 -0
  24. package/scripts/lib/activation/format-activation-output.js +109 -0
  25. package/scripts/lib/activation/next-action.js +43 -0
  26. package/scripts/lib/activation/repair-engine.js +219 -0
  27. package/scripts/lib/activation-distribution-readiness.js +507 -0
  28. package/scripts/lib/adapter-conformance.js +176 -0
  29. package/scripts/lib/adapter-readiness.js +417 -0
  30. package/scripts/lib/adapter-safety-boundaries.js +335 -0
  31. package/scripts/lib/adapter-technical-readiness-gate.js +205 -0
  32. package/scripts/lib/agent-access-governance.js +455 -0
  33. package/scripts/lib/agent-enforcement.js +765 -0
  34. package/scripts/lib/agent-policy-profile.js +210 -0
  35. package/scripts/lib/agent-security/action-evaluator.js +507 -0
  36. package/scripts/lib/agent-security/adapter-registry.js +98 -0
  37. package/scripts/lib/agent-security/auto-policy.js +139 -0
  38. package/scripts/lib/agent-security/bounded-scan.js +93 -0
  39. package/scripts/lib/agent-security/enforcement-adapter.js +174 -0
  40. package/scripts/lib/agent-security/enforcement-engine.js +1129 -0
  41. package/scripts/lib/agent-security/file-write-adapter.js +183 -0
  42. package/scripts/lib/agent-security/file-write-rules.js +178 -0
  43. package/scripts/lib/agent-security/index.js +3342 -0
  44. package/scripts/lib/agent-security/instruction-risk.js +181 -0
  45. package/scripts/lib/agent-security/mcp-action-adapter.js +185 -0
  46. package/scripts/lib/agent-security/mcp-action-rules.js +184 -0
  47. package/scripts/lib/agent-security/package-action-adapter.js +175 -0
  48. package/scripts/lib/agent-security/package-action-rules.js +233 -0
  49. package/scripts/lib/agent-security/performance.js +148 -0
  50. package/scripts/lib/agent-security/permission-minimizer.js +403 -0
  51. package/scripts/lib/agent-security/scan-cache.js +74 -0
  52. package/scripts/lib/agent-security/source-trust.js +146 -0
  53. package/scripts/lib/ai-install-prompt.js +288 -0
  54. package/scripts/lib/ai-workspace-hygiene.js +1499 -0
  55. package/scripts/lib/alpha-activation.js +520 -0
  56. package/scripts/lib/alpha-feedback.js +263 -0
  57. package/scripts/lib/alpha-readiness-gate.js +332 -0
  58. package/scripts/lib/anti-gaming.js +169 -0
  59. package/scripts/lib/artifact-health.js +431 -0
  60. package/scripts/lib/attribution.js +180 -0
  61. package/scripts/lib/audit.js +289 -0
  62. package/scripts/lib/avorelo-skill-registry.js +810 -0
  63. package/scripts/lib/batch-jobs.js +71 -0
  64. package/scripts/lib/brain-pack.js +578 -0
  65. package/scripts/lib/brand-boundary.js +424 -0
  66. package/scripts/lib/brand.js +74 -0
  67. package/scripts/lib/browser-capability.js +1048 -0
  68. package/scripts/lib/browser-proof-preflight.js +321 -0
  69. package/scripts/lib/cache-readiness.js +187 -0
  70. package/scripts/lib/canonical-reentry.js +162 -0
  71. package/scripts/lib/capability-packs.js +314 -0
  72. package/scripts/lib/capability-recommender.js +512 -0
  73. package/scripts/lib/capability-registry.js +1059 -0
  74. package/scripts/lib/carry-forward-surfacing.js +194 -0
  75. package/scripts/lib/ccusage-adapter.js +188 -0
  76. package/scripts/lib/company-loop.js +1149 -0
  77. package/scripts/lib/config.js +637 -0
  78. package/scripts/lib/context-acquisition-plan.js +287 -0
  79. package/scripts/lib/context-budget-guard.js +170 -0
  80. package/scripts/lib/context-budget-scanner.js +257 -0
  81. package/scripts/lib/context-optimizer.js +715 -0
  82. package/scripts/lib/context-reduction-plan.js +178 -0
  83. package/scripts/lib/context-safety.js +88 -0
  84. package/scripts/lib/context-savings-engine.js +158 -0
  85. package/scripts/lib/cost-evidence.js +254 -0
  86. package/scripts/lib/cross-host-install-plan.js +308 -0
  87. package/scripts/lib/cross-host-install-readiness.js +237 -0
  88. package/scripts/lib/cross-host-value-flow.js +268 -0
  89. package/scripts/lib/dashboard.js +900 -0
  90. package/scripts/lib/design-partner-feedback.js +346 -0
  91. package/scripts/lib/entitlements.js +100 -0
  92. package/scripts/lib/execution-packet.js +559 -0
  93. package/scripts/lib/experimentation-events.js +547 -0
  94. package/scripts/lib/external-capability-compliance.js +107 -0
  95. package/scripts/lib/external-user-simulation.js +166 -0
  96. package/scripts/lib/failure-recovery-readiness.js +81 -0
  97. package/scripts/lib/failure-recovery.js +419 -0
  98. package/scripts/lib/feedback-intelligence.js +537 -0
  99. package/scripts/lib/feedback-signals.js +205 -0
  100. package/scripts/lib/file-integrity.js +68 -0
  101. package/scripts/lib/fsx.js +127 -0
  102. package/scripts/lib/full-readiness-gate.js +451 -0
  103. package/scripts/lib/guidance-builder.js +174 -0
  104. package/scripts/lib/hook-apply.js +1019 -0
  105. package/scripts/lib/hook-baseline.js +310 -0
  106. package/scripts/lib/hook-config-preview.js +275 -0
  107. package/scripts/lib/hook-contracts.js +290 -0
  108. package/scripts/lib/hook-safety-boundary-readiness.js +80 -0
  109. package/scripts/lib/host-capability-matrix.js +351 -0
  110. package/scripts/lib/host-support-context.js +254 -0
  111. package/scripts/lib/http-hook-action.js +538 -0
  112. package/scripts/lib/install-ai-readiness.js +84 -0
  113. package/scripts/lib/install-intake-risk.js +1037 -0
  114. package/scripts/lib/install-journey-intelligence.js +329 -0
  115. package/scripts/lib/intervention-guidance.js +57 -0
  116. package/scripts/lib/known-limitations.js +115 -0
  117. package/scripts/lib/l8-path-truth.js +146 -0
  118. package/scripts/lib/launch-hardening-gate.js +436 -0
  119. package/scripts/lib/launch-readiness.js +628 -0
  120. package/scripts/lib/learning-memory.js +686 -0
  121. package/scripts/lib/lifecycle-hooks.js +802 -0
  122. package/scripts/lib/local-package-smoke.js +423 -0
  123. package/scripts/lib/local-pricing.js +299 -0
  124. package/scripts/lib/mcp-enforcement.js +311 -0
  125. package/scripts/lib/mcp-least-privilege-policy.js +303 -0
  126. package/scripts/lib/mcp-tool-inventory.js +388 -0
  127. package/scripts/lib/mcp-tool-risk.js +0 -0
  128. package/scripts/lib/memory.js +335 -0
  129. package/scripts/lib/metrics.js +699 -0
  130. package/scripts/lib/micro-proof.js +133 -0
  131. package/scripts/lib/next-run-context.js +436 -0
  132. package/scripts/lib/operating-value.js +1648 -0
  133. package/scripts/lib/optimization-v3.js +122 -0
  134. package/scripts/lib/orchestration/adapters/_shared.js +49 -0
  135. package/scripts/lib/orchestration/adapters/aider.js +18 -0
  136. package/scripts/lib/orchestration/adapters/claude-code.js +35 -0
  137. package/scripts/lib/orchestration/adapters/codex.js +35 -0
  138. package/scripts/lib/orchestration/adapters/gemini-cli.js +18 -0
  139. package/scripts/lib/orchestration/adapters/git.js +25 -0
  140. package/scripts/lib/orchestration/adapters/index.js +31 -0
  141. package/scripts/lib/orchestration/adapters/lm-studio.js +18 -0
  142. package/scripts/lib/orchestration/adapters/ollama.js +18 -0
  143. package/scripts/lib/orchestration/adapters/opencode.js +18 -0
  144. package/scripts/lib/orchestration/adapters/openrouter.js +18 -0
  145. package/scripts/lib/orchestration/adapters/test-runner.js +25 -0
  146. package/scripts/lib/orchestration/cli.js +438 -0
  147. package/scripts/lib/orchestration/execution-manager.js +279 -0
  148. package/scripts/lib/orchestration/handoff.js +314 -0
  149. package/scripts/lib/orchestration/index.js +456 -0
  150. package/scripts/lib/orchestration/inventory.js +47 -0
  151. package/scripts/lib/orchestration/model-discovery.js +498 -0
  152. package/scripts/lib/orchestration/model-profiler.js +170 -0
  153. package/scripts/lib/orchestration/model-profiles.js +252 -0
  154. package/scripts/lib/orchestration/model-refresh-policy.js +72 -0
  155. package/scripts/lib/orchestration/proof-writer.js +349 -0
  156. package/scripts/lib/orchestration/provider-discovery/aider.js +49 -0
  157. package/scripts/lib/orchestration/provider-discovery/claude-code.js +56 -0
  158. package/scripts/lib/orchestration/provider-discovery/codex.js +49 -0
  159. package/scripts/lib/orchestration/provider-discovery/common.js +186 -0
  160. package/scripts/lib/orchestration/provider-discovery/gemini.js +106 -0
  161. package/scripts/lib/orchestration/provider-discovery/lm-studio.js +118 -0
  162. package/scripts/lib/orchestration/provider-discovery/models-dev.js +12 -0
  163. package/scripts/lib/orchestration/provider-discovery/ollama.js +100 -0
  164. package/scripts/lib/orchestration/provider-discovery/opencode.js +47 -0
  165. package/scripts/lib/orchestration/provider-discovery/openrouter.js +44 -0
  166. package/scripts/lib/orchestration/risk-classifier.js +130 -0
  167. package/scripts/lib/orchestration/routing-policy.js +486 -0
  168. package/scripts/lib/orchestration/settings.js +112 -0
  169. package/scripts/lib/orchestration/state.js +165 -0
  170. package/scripts/lib/orchestration/verification-manager.js +138 -0
  171. package/scripts/lib/output-profiles.js +146 -0
  172. package/scripts/lib/package-content-audit.js +368 -0
  173. package/scripts/lib/package-runtime.js +278 -0
  174. package/scripts/lib/plan-surface.js +53 -0
  175. package/scripts/lib/plans.js +2318 -0
  176. package/scripts/lib/policy-provider.js +27 -0
  177. package/scripts/lib/prelaunch-activation-readiness.js +409 -0
  178. package/scripts/lib/prelaunch-evidence-store.js +816 -0
  179. package/scripts/lib/prelaunch-intelligence.js +869 -0
  180. package/scripts/lib/pricing-experiment.js +118 -0
  181. package/scripts/lib/pro-moment-events.js +77 -0
  182. package/scripts/lib/pro-moment-state.js +227 -0
  183. package/scripts/lib/pro-moments.js +1216 -0
  184. package/scripts/lib/product-learning-events.js +629 -0
  185. package/scripts/lib/project-profile.js +555 -0
  186. package/scripts/lib/prompt-compiler.js +280 -0
  187. package/scripts/lib/prompt-lint.js +32 -0
  188. package/scripts/lib/prompt-suggestions.js +52 -0
  189. package/scripts/lib/proof-canonical.js +398 -0
  190. package/scripts/lib/proof-drilldown.js +383 -0
  191. package/scripts/lib/proof-events.js +342 -0
  192. package/scripts/lib/proof-history.js +243 -0
  193. package/scripts/lib/proof-metrics.js +296 -0
  194. package/scripts/lib/proof-outcome-evidence.js +134 -0
  195. package/scripts/lib/proof-receipt.js +335 -0
  196. package/scripts/lib/proof-record.js +461 -0
  197. package/scripts/lib/public-activation-distribution-gate.js +258 -0
  198. package/scripts/lib/public-cli.js +3891 -0
  199. package/scripts/lib/public-distribution-truth.js +211 -0
  200. package/scripts/lib/public-install-claim-checker.js +294 -0
  201. package/scripts/lib/publish-provenance-readiness.js +283 -0
  202. package/scripts/lib/readiness-delta.js +218 -0
  203. package/scripts/lib/readiness-evidence-closure.js +196 -0
  204. package/scripts/lib/reentry-memory-capture.js +241 -0
  205. package/scripts/lib/reentry-memory-retrieval.js +302 -0
  206. package/scripts/lib/reentry-memory-status.js +146 -0
  207. package/scripts/lib/reentry-memory-store.js +178 -0
  208. package/scripts/lib/reentry-state.js +66 -0
  209. package/scripts/lib/release-candidate-bundle.js +166 -0
  210. package/scripts/lib/remediation.js +81 -0
  211. package/scripts/lib/repo-map.js +391 -0
  212. package/scripts/lib/run-improvements-lifecycle.js +330 -0
  213. package/scripts/lib/run-improvements.js +789 -0
  214. package/scripts/lib/runtime-decision-policy.js +387 -0
  215. package/scripts/lib/safe-path-engine.js +705 -0
  216. package/scripts/lib/safe-run-controller.js +887 -0
  217. package/scripts/lib/score.js +262 -0
  218. package/scripts/lib/seamless-enforcement.js +329 -0
  219. package/scripts/lib/seamless-outcome.js +689 -0
  220. package/scripts/lib/seamless-reality-gate.js +5043 -0
  221. package/scripts/lib/security-risk-classifier.js +511 -0
  222. package/scripts/lib/security-scan.js +384 -0
  223. package/scripts/lib/session-context-optimizer.js +1211 -0
  224. package/scripts/lib/session-timing.js +315 -0
  225. package/scripts/lib/skill-hygiene.js +805 -0
  226. package/scripts/lib/skill-packs.js +161 -0
  227. package/scripts/lib/skills-operating-layer.js +580 -0
  228. package/scripts/lib/smart-work-routing.js +768 -0
  229. package/scripts/lib/source-catalog.js +700 -0
  230. package/scripts/lib/status-value-summary.js +32 -0
  231. package/scripts/lib/support-bundle.js +578 -0
  232. package/scripts/lib/task-continuation.js +440 -0
  233. package/scripts/lib/test-helpers.js +15 -0
  234. package/scripts/lib/tier.js +38 -0
  235. package/scripts/lib/token-context-quality-gate.js +370 -0
  236. package/scripts/lib/token-cost-capture.js +187 -0
  237. package/scripts/lib/token-cost-intelligence.js +358 -0
  238. package/scripts/lib/token-efficiency-evidence.js +213 -0
  239. package/scripts/lib/token-evidence.js +699 -0
  240. package/scripts/lib/tokenish.js +17 -0
  241. package/scripts/lib/tool-output-sandbox.js +304 -0
  242. package/scripts/lib/trust-audit.js +136 -0
  243. package/scripts/lib/unified-events.js +396 -0
  244. package/scripts/lib/upgrade-interruption-recovery.js +407 -0
  245. package/scripts/lib/usage-ledger.js +201 -0
  246. package/scripts/lib/value-ledger.js +130 -0
  247. package/scripts/lib/value-proof-calibration.js +531 -0
  248. package/scripts/lib/visual-qa.js +231 -0
  249. package/scripts/lib/voice-alpha.js +29 -0
  250. package/scripts/lib/work-aware-orchestration.js +976 -0
  251. package/scripts/lib/work-control-receipts.js +577 -0
  252. package/scripts/lib/work-ledger.js +1123 -0
  253. package/scripts/lib/work-panel-preview.js +352 -0
  254. package/scripts/lib/workflow-discipline.js +280 -0
  255. package/scripts/lib/workflow-signals.js +419 -0
  256. package/scripts/lib/workspace-map.js +281 -0
  257. package/scripts/lib/workspace-registry.js +1367 -0
  258. package/scripts/lib/workspace-resolver.js +480 -0
@@ -0,0 +1,3891 @@
1
+ "use strict";
2
+
3
+ const fs = require("fs");
4
+ const path = require("path");
5
+ const { spawnSync } = require("child_process");
6
+ const {
7
+ PRODUCT_NAME,
8
+ CLI_NAME,
9
+ PUBLIC_INIT_COMMAND,
10
+ formatCliCommand,
11
+ } = require("./brand");
12
+ const {
13
+ findWorkspaceRoot,
14
+ resolveWorkspace,
15
+ registerWorkspace,
16
+ clearLastWorkspace,
17
+ validateWorkspacePath,
18
+ workspaceDoctor,
19
+ formatWorkspaceShowText,
20
+ formatWorkspaceDoctorText,
21
+ } = require("./workspace-resolver");
22
+ const {
23
+ renderRouteCommand,
24
+ renderRunCommand,
25
+ renderModelsCommand,
26
+ renderStatusCommand: renderOrchestrationStatusCommand,
27
+ renderProofCommand,
28
+ renderVerifyCommand: renderOrchestrationVerifyCommand,
29
+ renderSettingsCommand: renderOrchestrationSettingsCommand,
30
+ renderHandoffCommand,
31
+ renderOrchestrationSurfaceCommand,
32
+ } = require("./orchestration/cli");
33
+ const REPO_ROOT = path.resolve(__dirname, "..", "..");
34
+
35
+ function getCanonicalSessionId(cwd = process.cwd()) {
36
+ const carryForwardPath = path.join(cwd, ".claude", "cco", "state", "reentry-carry-forward.json");
37
+ if (fs.existsSync(carryForwardPath)) {
38
+ try {
39
+ const state = JSON.parse(fs.readFileSync(carryForwardPath, "utf8"));
40
+ if (state.sessionId) return state.sessionId;
41
+ } catch {}
42
+ }
43
+ return `${CLI_NAME}-${Date.now()}`;
44
+ }
45
+
46
+ function printHelp() {
47
+ process.stdout.write(
48
+ [
49
+ `${PRODUCT_NAME} CLI`,
50
+ "",
51
+ `Usage: ${CLI_NAME} <command> [args]`,
52
+ "",
53
+ "Commands:",
54
+ ` activate Run the public activation flow`,
55
+ ` init Print or run the public init path (${PUBLIC_INIT_COMMAND})`,
56
+ " status Show the current Avorelo status",
57
+ " dashboard Show the current Avorelo dashboard",
58
+ " audit Run the current Avorelo audit",
59
+ " settings Open or print the current settings surface",
60
+ " panel Start the local panel",
61
+ " doctor Run the setup checks",
62
+ " summary Show the post-run summary",
63
+ " prompt Improve a rough AI coding instruction",
64
+ " route Route a task to the cheapest capable safe path",
65
+ " run Safe execution controller: routes, compiles packet, prepares handoff, runs whitelisted local proof steps (alias: execute)",
66
+ " models Show detected workers, providers, and model/profile signals",
67
+ " orchestration Show orchestration status and settings helpers (subcommands: status, handoff, surface, settings)",
68
+ " handoff Generate a compact handoff prompt for the next worker/session",
69
+ " workspace Show or manage workspace resolution for global usage",
70
+ " workspace-map Generate a compact workspace navigation map",
71
+ " workspace-registry Build and inspect the local AI workspace asset registry (alias: assets, registry)",
72
+ " skills Review sources, parse skills, route tasks, and sync thin adapters",
73
+ " proof Show the latest orchestration proof (--history: retained proof trail, --export: local proof export, --debug: include blocked/unavailable worker details)",
74
+ " context Build a stage-specific context pack for a task (alias: context-pack)",
75
+ " intake Scan local install and intake surfaces and write a compact receipt",
76
+ " visual-qa Run local screenshot-backed Visual QA when configured",
77
+ " capabilities Show recommended capability packs and next action",
78
+ " guard Evaluate a proposed agent action without executing it",
79
+ " work-control Show unified work-control receipt (what happened, what was risky, what is next)",
80
+ " brain-pack Generate a compact Brain Pack with project/repo/user context for session continuity",
81
+ " session-context Generate compact session-start context for the next AI session (alias: session-start)",
82
+ " verify Verify a file with the local verifier or run orchestration verification",
83
+ " operating-value Show what Avorelo did for you: time saved, tokens/context reduced, risks avoided (alias: value, savings)",
84
+ " readiness Check launch readiness: package audit, install, external repo gate (alias: install-check)",
85
+ " outcome Show end-of-run value summary: completed/saved/protected/verified/next (alias: reality-gate)",
86
+ " workspace-hygiene Scan AI workspace assets and show hygiene report (aliases: hygiene, ai-workspace). Use --debug for full asset detail.",
87
+ " orchestrate Build a work-aware stage plan for a task (aliases: work-plan, plan-work). Use --debug for stage/worker/context detail.",
88
+ " ledger Build and show the unified work ledger linking all receipts (alias: work-ledger). Use --debug for full entry detail.",
89
+ " company-loop Run the AI-native company operating loop: personas, friction clusters, next PR recommendation (aliases: loop, learn). Use --debug for persona findings.",
90
+ " project-profile Detect and show the project profile: framework, package manager, scripts, deploy, risk boundaries (alias: profile).",
91
+ " execution-packet Compile a scoped execution packet for a task: allowed/blocked scope, risk, proof, agent prompt (alias: packet). Use --debug for agent prompt.",
92
+ " work-panel Generate a local work panel preview for the current or a new task (alias: panel-preview). Use --debug for full detail.",
93
+ " smart-route Route work to the cheapest safe capable path: decide, prepare handoff, write receipts (alias: work-route). Use --debug for reason codes.",
94
+ " worker-handoff Show the latest worker handoff receipt prepared by smart-route.",
95
+ " hooks Show hook baseline and lifecycle readiness (alias: hook-baseline, hook-readiness). Use --debug for event detail.",
96
+ " hooks preview Generate hook config preview (what would be added — no config modified). Use --json for machine output.",
97
+ " hooks apply [--dry-run] [--yes] Apply Avorelo hooks to repo-local config. Default: dry-run. Requires --yes for real apply.",
98
+ " hooks rollback Restore the latest config backup from before hook apply.",
99
+ " hooks uninstall --yes Remove only Avorelo-managed hooks from config. Preserves all other hooks.",
100
+ " hooks doctor Validate installed hooks, command paths, recursion guard, and lifecycle smoke.",
101
+ " adapter-readiness Detect which AI coding host adapters are available (claude_code, openhands, generic_cli).",
102
+ " lifecycle-hook <event> Handle a lifecycle event (session-start, user-prompt-submit, pre-tool-use, post-tool-use, stop, session-end). Use --json.",
103
+ " token-efficiency Show token efficiency evidence and context quality status (alias: token-evidence). Use --json.",
104
+ " repo-map Build and show the repo/symbol map for context-efficient task planning. Use --json.",
105
+ " context-plan <task> Build a context acquisition plan for a task. Use --json.",
106
+ " cache-readiness Check prompt layout stability for cache readiness. Use --json.",
107
+ " artifacts Scan and manage .claude/cco artifact health (subcommands: health, cleanup --dry-run, cleanup --yes).",
108
+ " launch-hardening Run the launch hardening gate: checks all critical alpha-readiness surfaces. Use --json.",
109
+ " mcp MCP tool governance: inventory, risk, policy, preview, doctor (subcommands). Use --json.",
110
+ " mcp inventory Discover MCP config files and build local tool inventory (no server execution). Use --json.",
111
+ " mcp risk Classify MCP server/tool risk using static metadata analysis. Use --json.",
112
+ " mcp policy Build least-privilege policy decisions (preview only — config not modified). Use --json.",
113
+ " mcp preview Show policy preview without writing policy. Use --json.",
114
+ " mcp doctor Full MCP governance status: inventory + risk + policy summary. Use --json.",
115
+ " install-ai Generate the one-prompt AI install experience (aliases: ai-install, install-prompt). Use --prompt for text, --json for receipt, --dry-run to skip artifact write.",
116
+ " prelaunch-readiness Run the pre-launch activation readiness gate (all surfaces). Use --json.",
117
+ " first-value-check Run the first-value journey check (readiness + safe path + summary). Use --json.",
118
+ " public-distribution Run public activation distribution truth gate (aliases: distribution-truth). Use --json or --debug.",
119
+ " package-audit Audit npm pack contents for forbidden/suspicious files. Use --json.",
120
+ " package-smoke Run local tarball smoke test (install + CLI help from packed tarball). Use --json.",
121
+ " install-claims Scan docs and README for false public install claims. Use --json.",
122
+ " publish-readiness Check publish/provenance readiness without publishing. Use --json.",
123
+ " host-matrix Build host capability matrix: detect hosts, map hook/MCP/install-ai capabilities. Use --json.",
124
+ " cross-host-install Check cross-host install-ai readiness for all supported hosts. Use --json.",
125
+ " cross-host-value Check cross-host value flow: proof, ledger, token cost, events, support bundle. Use --json.",
126
+ " adapter-safety Check adapter safety boundaries: no state leak, hook timeout, MCP isolation. Use --json.",
127
+ " host-support Check host support context: support bundle, proof, ledger, host state. Use --json.",
128
+ " browser-preflight Run browser proof preflight (PREFLIGHT ONLY — no browser launched). Use --json.",
129
+ " adapter-readiness-technical Run full adapter technical readiness gate (all 6 sub-modules). Use --json.",
130
+ " run-improvements Show or generate next-run preparation (alias: next-run-prep). Use --generate to refresh, --consume to record consumption, --apply to set applied state with receipt. Use --json.",
131
+ " learning Show or generate the local evidence-backed learning memory (decisions, risks, capabilities). Use --generate to build, --summary to show, --json for machine output.",
132
+ " --help Show this help",
133
+ "",
134
+ `Examples: ${formatCliCommand("activate")}, ${formatCliCommand("status")}, ${formatCliCommand('prompt "fix landing page"')}`,
135
+ ].join("\n") + "\n"
136
+ );
137
+ }
138
+
139
+ function runNodeScript(scriptRelPath, forwardedArgs = [], options = {}) {
140
+ const cwd = options.cwd || process.cwd();
141
+ const result = spawnSync(process.execPath || "node", [path.join(REPO_ROOT, scriptRelPath), ...forwardedArgs], {
142
+ cwd,
143
+ encoding: "utf8",
144
+ env: {
145
+ ...process.env,
146
+ ...(options.env || {}),
147
+ PROJECT_CWD: cwd,
148
+ },
149
+ });
150
+ if (result.stdout) process.stdout.write(result.stdout);
151
+ if (result.stderr) process.stderr.write(result.stderr);
152
+ process.exit(result.status === null ? 1 : result.status);
153
+ }
154
+
155
+ function renderActivation(forwardedArgs = []) {
156
+ const wantJson = forwardedArgs.includes("--json");
157
+ const wantDebug = forwardedArgs.includes("--debug");
158
+ const wantHelp = forwardedArgs.includes("--help");
159
+ const useLegacy = forwardedArgs.some((a) =>
160
+ ["--dry-run", "--repair", "--force-refresh", "--open", "--agent-repair", "--local-only", "--text"].includes(a)
161
+ );
162
+
163
+ if (wantHelp) {
164
+ process.stdout.write([
165
+ "Usage: avorelo activate [options]",
166
+ "",
167
+ "Options:",
168
+ " --json Alpha activation contract as JSON (avorelo.alphaActivation.v1)",
169
+ " --debug Show full internal detail",
170
+ " --dry-run (legacy) Show planned repairs without applying",
171
+ " --repair (legacy) Force repair loop",
172
+ " --target <t> (legacy) Prepare target handoff",
173
+ " --open (legacy) Print dashboard preview path",
174
+ " --agent-repair (legacy) Output machine-readable repair plan",
175
+ " --help Show this help",
176
+ "",
177
+ ].join("\n"));
178
+ return;
179
+ }
180
+
181
+ const rawCwd = process.env.PROJECT_CWD || process.cwd();
182
+
183
+ // Legacy flow: preserve old behavior for legacy flags
184
+ if (useLegacy) {
185
+ const {
186
+ runActivationV1,
187
+ parseActivationArgs,
188
+ formatActivationText: legacyFormatText,
189
+ formatActivationJson,
190
+ } = require("./activation/activation-runner");
191
+ const { detectProject } = require("./activation/detect-environment");
192
+ const args = parseActivationArgs(forwardedArgs);
193
+ const currentWorkspace = findWorkspaceRoot(rawCwd)?.workspace;
194
+ const project = detectProject(rawCwd, { env: process.env });
195
+ const cwd = currentWorkspace || project.repoRoot || rawCwd;
196
+ const result = runActivationV1(cwd, {
197
+ dryRun: args.dryRun,
198
+ repair: args.repair,
199
+ target: args.target,
200
+ forceRefresh: args.forceRefresh,
201
+ env: process.env,
202
+ });
203
+ try { registerWorkspace(cwd, { env: process.env }); } catch {}
204
+ if (args.open) {
205
+ const dashPath = result.dashboardPath || ".claude/cco/orchestration/operating-value/dashboard-preview.md";
206
+ process.stdout.write(`Dashboard preview:\n ${dashPath}\n\nRun: cat "${dashPath}"\n`);
207
+ return;
208
+ }
209
+ if (args.agentRepair) {
210
+ process.stdout.write(`${JSON.stringify(result.agentRepairInstructions || result, null, 2)}\n`);
211
+ return;
212
+ }
213
+ if (args.json) {
214
+ process.stdout.write(`${formatActivationJson(result)}\n`);
215
+ return;
216
+ }
217
+ process.stdout.write(`${legacyFormatText(result)}\n`);
218
+ return;
219
+ }
220
+
221
+ // Alpha activation flow (default for plain activate / activate --json / activate --debug)
222
+ const {
223
+ buildActivationSurface,
224
+ formatActivationText,
225
+ } = require("./alpha-activation");
226
+
227
+ const currentWorkspace = findWorkspaceRoot(rawCwd)?.workspace;
228
+ const cwd = currentWorkspace || rawCwd;
229
+
230
+ const receipt = buildActivationSurface(cwd, { debug: wantDebug });
231
+
232
+ try { registerWorkspace(cwd, { env: process.env }); } catch {}
233
+
234
+ if (wantJson) {
235
+ process.stdout.write(`${JSON.stringify(receipt, null, 2)}\n`);
236
+ return;
237
+ }
238
+
239
+ // Default: compact human-readable
240
+ process.stdout.write(`${formatActivationText(receipt, { debug: wantDebug })}\n`);
241
+ }
242
+
243
+ function renderFirstValue(cwd, forwardedArgs = []) {
244
+ // Alias for activate with alpha activation surface
245
+ renderActivation(forwardedArgs);
246
+ }
247
+
248
+ function renderAlphaReadinessGate(cwd, forwardedArgs = []) {
249
+ const wantJson = forwardedArgs.includes("--json");
250
+ const { runAlphaReadinessGate, formatAlphaReadinessGateText } = require("./alpha-readiness-gate");
251
+ const report = runAlphaReadinessGate(cwd);
252
+ if (wantJson) {
253
+ process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
254
+ return;
255
+ }
256
+ process.stdout.write(`${formatAlphaReadinessGateText(report)}\n`);
257
+ }
258
+
259
+ function renderFeedbackCommand(cwd, forwardedArgs = []) {
260
+ const wantJson = forwardedArgs.includes("--json");
261
+ const { addFeedback, listFeedback, formatFeedbackListText } = require("./alpha-feedback");
262
+ const { importFeedbackEvidence, validateFeedbackEvidence, generateFeedbackIntakePack } = require("./prelaunch-evidence-store");
263
+
264
+ const subcommand = forwardedArgs.find((a) => !a.startsWith("-")) || "list";
265
+
266
+ if (subcommand === "add") {
267
+ const source = readFlagValue(forwardedArgs, "--source") || "dogfood";
268
+ const persona = readFlagValue(forwardedArgs, "--persona") || "unknown";
269
+ const frictionType = readFlagValue(forwardedArgs, "--friction-type") || readFlagValue(forwardedArgs, "--friction") || "other";
270
+ const severity = readFlagValue(forwardedArgs, "--severity") || "medium";
271
+ const summary = readFlagValue(forwardedArgs, "--summary") || "";
272
+ const desiredBehavior = readFlagValue(forwardedArgs, "--desired") || "";
273
+ const segment = readFlagValue(forwardedArgs, "--segment") || "unknown";
274
+ const theme = readFlagValue(forwardedArgs, "--theme") || null;
275
+ const issueCategory = readFlagValue(forwardedArgs, "--issue-category") || null;
276
+ const activationStage = readFlagValue(forwardedArgs, "--activation-stage") || "unknown";
277
+ const evidencePath = readFlagValue(forwardedArgs, "--evidence-path") || null;
278
+ const trustConcern = forwardedArgs.includes("--trust-concern");
279
+ const pricingConcern = forwardedArgs.includes("--pricing-concern");
280
+ const simulated = forwardedArgs.includes("--simulated");
281
+ const result = addFeedback(cwd, {
282
+ source, persona, frictionType, severity, summary, desiredBehavior,
283
+ segment, theme, issueCategory, activationStage, evidencePath,
284
+ trustConcern, pricingConcern, simulated,
285
+ });
286
+ if (wantJson) {
287
+ process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
288
+ return;
289
+ }
290
+ if (result.ok) {
291
+ process.stdout.write(`Feedback captured: ${result.path}\n`);
292
+ } else {
293
+ process.stderr.write(`Feedback error: ${result.errors.join(", ")}\n`);
294
+ process.exit(1);
295
+ }
296
+ return;
297
+ }
298
+
299
+ if (subcommand === "intake-pack" || subcommand === "pack") {
300
+ const receipt = generateFeedbackIntakePack(cwd);
301
+ if (wantJson) {
302
+ process.stdout.write(`${JSON.stringify(receipt, null, 2)}\n`);
303
+ return;
304
+ }
305
+ process.stdout.write(`Feedback intake pack: ${receipt.outputDir}\n`);
306
+ return;
307
+ }
308
+
309
+ if (subcommand === "validate") {
310
+ const file = readFlagValue(forwardedArgs, "--file");
311
+ if (!file) {
312
+ const message = { ok: false, error: "--file is required", redacted: true };
313
+ if (wantJson) {
314
+ process.stdout.write(`${JSON.stringify(message, null, 2)}\n`);
315
+ return;
316
+ }
317
+ process.stderr.write("Feedback validate error: --file is required\n");
318
+ process.exit(1);
319
+ }
320
+ const receipt = validateFeedbackEvidence(cwd, file);
321
+ if (wantJson) {
322
+ process.stdout.write(`${JSON.stringify(receipt, null, 2)}\n`);
323
+ return;
324
+ }
325
+ process.stdout.write(`Feedback validation: ${receipt.acceptedCount} accepted, ${receipt.rejectedCount} rejected.\n`);
326
+ return;
327
+ }
328
+
329
+ if (subcommand === "import") {
330
+ const file = readFlagValue(forwardedArgs, "--file");
331
+ if (!file) {
332
+ const message = { ok: false, error: "--file is required", redacted: true };
333
+ if (wantJson) {
334
+ process.stdout.write(`${JSON.stringify(message, null, 2)}\n`);
335
+ return;
336
+ }
337
+ process.stderr.write("Feedback import error: --file is required\n");
338
+ process.exit(1);
339
+ }
340
+ const receipt = importFeedbackEvidence(cwd, file);
341
+ if (wantJson) {
342
+ process.stdout.write(`${JSON.stringify(receipt, null, 2)}\n`);
343
+ return;
344
+ }
345
+ process.stdout.write(`Feedback import: ${receipt.acceptedCount} accepted, ${receipt.rejectedCount} rejected.\n`);
346
+ return;
347
+ }
348
+
349
+ if (subcommand === "session") {
350
+ const { buildDesignPartnerFeedbackSession, writeDesignPartnerFeedbackSession } = require("./design-partner-feedback");
351
+ const partnerAlias = readFlagValue(forwardedArgs, "--partner") || readFlagValue(forwardedArgs, "--partner-alias") || "";
352
+ const activationStage = readFlagValue(forwardedArgs, "--stage") || "unknown";
353
+ const frictionType = readFlagValue(forwardedArgs, "--friction-type") || readFlagValue(forwardedArgs, "--friction") || "unknown";
354
+ const severity = readFlagValue(forwardedArgs, "--severity") || "medium";
355
+ const consent = readFlagValue(forwardedArgs, "--consent") || "not_recorded";
356
+ const summary = readFlagValue(forwardedArgs, "--summary") || "";
357
+ const desiredBehavior = readFlagValue(forwardedArgs, "--desired") || "";
358
+ const sessionNotes = readFlagValue(forwardedArgs, "--notes") || "";
359
+ const theme = readFlagValue(forwardedArgs, "--theme") || "";
360
+ const simulated = forwardedArgs.includes("--simulated");
361
+ const result = buildDesignPartnerFeedbackSession(cwd, {
362
+ partnerAlias, activationStage, frictionType, severity, consent,
363
+ summary, desiredBehavior, sessionNotes, theme, simulated,
364
+ });
365
+ if (!result.ok) {
366
+ if (wantJson) { process.stdout.write(`${JSON.stringify(result, null, 2)}\n`); return; }
367
+ process.stderr.write(`Feedback session error: ${result.errors.join(", ")}\n`);
368
+ process.exit(1);
369
+ }
370
+ const writeResult = writeDesignPartnerFeedbackSession(cwd, result.session);
371
+ if (wantJson) { process.stdout.write(`${JSON.stringify({ ok: true, sessionId: result.session.sessionId, path: writeResult.path, redacted: true }, null, 2)}\n`); return; }
372
+ process.stdout.write(`Design partner session captured: ${writeResult.path}\n`);
373
+ return;
374
+ }
375
+
376
+ if (subcommand === "summary") {
377
+ const { buildDesignPartnerFeedbackSummary, writeDesignPartnerFeedbackSummary, formatDesignPartnerFeedbackText } = require("./design-partner-feedback");
378
+ const summary = buildDesignPartnerFeedbackSummary(cwd);
379
+ writeDesignPartnerFeedbackSummary(cwd, summary);
380
+ if (wantJson) { process.stdout.write(`${JSON.stringify(summary, null, 2)}\n`); return; }
381
+ process.stdout.write(`${formatDesignPartnerFeedbackText(summary)}\n`);
382
+ return;
383
+ }
384
+
385
+ if (subcommand === "design-partner-pack") {
386
+ const { buildDesignPartnerFeedbackSummary, writeDesignPartnerFeedbackSummary, formatDesignPartnerFeedbackText } = require("./design-partner-feedback");
387
+ const summary = buildDesignPartnerFeedbackSummary(cwd);
388
+ writeDesignPartnerFeedbackSummary(cwd, summary);
389
+ const wantMarkdown = forwardedArgs.includes("--markdown");
390
+ if (wantJson) { process.stdout.write(`${JSON.stringify(summary, null, 2)}\n`); return; }
391
+ if (wantMarkdown) {
392
+ const lines = ["# Design Partner Feedback Pack", "", `Status: ${summary.status}`, `Sessions: ${summary.qualifiedSessionCount} qualified / ${summary.totalSessionCount} total`, `Partners: ${summary.partnerAliasCount}`, `Blockers: ${summary.blockerCount}`, ""];
393
+ if (summary.topFrictions && summary.topFrictions.length > 0) {
394
+ lines.push("## Top Frictions");
395
+ summary.topFrictions.forEach((f) => lines.push(`- ${f.frictionType}: ${f.count}`));
396
+ lines.push("");
397
+ }
398
+ lines.push("_No public launch claim. Redacted._");
399
+ process.stdout.write(lines.join("\n") + "\n");
400
+ return;
401
+ }
402
+ process.stdout.write(`${formatDesignPartnerFeedbackText(summary)}\n`);
403
+ return;
404
+ }
405
+
406
+ // list (default)
407
+ const sourceFilter = readFlagValue(forwardedArgs, "--source") || null;
408
+ const list = listFeedback(cwd, { source: sourceFilter });
409
+ if (wantJson) {
410
+ process.stdout.write(`${JSON.stringify(list, null, 2)}\n`);
411
+ return;
412
+ }
413
+ process.stdout.write(`${formatFeedbackListText(list)}\n`);
414
+ }
415
+
416
+ function renderSupportBundle(cwd, forwardedArgs = []) {
417
+ const wantJson = forwardedArgs.includes("--json");
418
+ const { generateSupportBundle, formatSupportBundleText } = require("./support-bundle");
419
+ const bundle = generateSupportBundle(cwd);
420
+ if (wantJson) {
421
+ process.stdout.write(`${JSON.stringify(bundle, null, 2)}\n`);
422
+ return;
423
+ }
424
+ process.stdout.write(`${formatSupportBundleText(bundle)}\n`);
425
+ }
426
+
427
+ function renderTokenEfficiency(cwd, forwardedArgs = []) {
428
+ const wantJson = forwardedArgs.includes("--json");
429
+ const {
430
+ buildTokenEfficiencyEvidence,
431
+ writeTokenEfficiencyEvidence,
432
+ buildTokenEfficiencySurface,
433
+ formatTokenEfficiencyText,
434
+ } = require("./token-efficiency-evidence");
435
+ const {
436
+ runTokenContextQualityGate,
437
+ writeTokenContextQualityGate,
438
+ formatTokenContextQualityText,
439
+ } = require("./token-context-quality-gate");
440
+ const evidence = buildTokenEfficiencyEvidence(cwd, {}, {});
441
+ writeTokenEfficiencyEvidence(cwd, evidence);
442
+ const gate = runTokenContextQualityGate(cwd, {}, {});
443
+ writeTokenContextQualityGate(cwd, gate);
444
+ if (wantJson) {
445
+ process.stdout.write(`${JSON.stringify({ evidence, gate }, null, 2)}\n`);
446
+ return;
447
+ }
448
+ process.stdout.write(`${formatTokenEfficiencyText(evidence)}\n${formatTokenContextQualityText(gate)}\n`);
449
+ }
450
+
451
+ function renderRepoMap(cwd, forwardedArgs = []) {
452
+ const wantJson = forwardedArgs.includes("--json");
453
+ const { buildRepoMap, writeRepoMap, formatRepoMapText } = require("./repo-map");
454
+ const map = buildRepoMap(cwd, {});
455
+ writeRepoMap(cwd, map);
456
+ if (wantJson) {
457
+ const { files: _files, symbols: _symbols, tokenCountTree: _tree, ...compact } = map;
458
+ process.stdout.write(`${JSON.stringify(compact, null, 2)}\n`);
459
+ return;
460
+ }
461
+ process.stdout.write(`${formatRepoMapText(map)}\n`);
462
+ }
463
+
464
+ function renderContextPlan(cwd, forwardedArgs = []) {
465
+ const wantJson = forwardedArgs.includes("--json");
466
+ const taskText = forwardedArgs.filter((a) => !a.startsWith("--")).join(" ") || "unknown task";
467
+ const { buildContextAcquisitionPlan, writeContextAcquisitionPlan, formatContextPlanText } = require("./context-acquisition-plan");
468
+ const plan = buildContextAcquisitionPlan(cwd, taskText, {});
469
+ writeContextAcquisitionPlan(cwd, plan);
470
+ if (wantJson) {
471
+ process.stdout.write(`${JSON.stringify(plan, null, 2)}\n`);
472
+ return;
473
+ }
474
+ process.stdout.write(`${formatContextPlanText(plan)}\n`);
475
+ }
476
+
477
+ function renderCacheReadiness(cwd, forwardedArgs = []) {
478
+ const wantJson = forwardedArgs.includes("--json");
479
+ const { buildCacheReadiness, writeCacheReadiness, formatCacheReadinessText } = require("./cache-readiness");
480
+ const readiness = buildCacheReadiness(cwd, {}, {});
481
+ writeCacheReadiness(cwd, readiness);
482
+ if (wantJson) {
483
+ process.stdout.write(`${JSON.stringify(readiness, null, 2)}\n`);
484
+ return;
485
+ }
486
+ process.stdout.write(`${formatCacheReadinessText(readiness)}\n`);
487
+ }
488
+
489
+ function renderDoctor(cwd, forwardedArgs = []) {
490
+ const { parseArgs, runDoctor, formatDoctorText } = require("../wuz-doctor");
491
+ const args = parseArgs(forwardedArgs);
492
+ const report = runDoctor(cwd, args);
493
+ process.stdout.write(args.json ? `${JSON.stringify(report, null, 2)}\n` : `${formatDoctorText(report)}\n`);
494
+ }
495
+
496
+ function renderStatus(cwd, forwardedArgs = []) {
497
+ const { buildStatusJson, formatBoundedStatus } = require("../cco-status");
498
+ const wantJson = forwardedArgs.includes("--json");
499
+ const payload = buildStatusJson(cwd);
500
+ if (wantJson) {
501
+ process.stdout.write(`${JSON.stringify(payload, null, 2)}\n`);
502
+ return;
503
+ }
504
+ process.stdout.write(`${formatBoundedStatus(payload)}\n`);
505
+ }
506
+
507
+ function printStatusHelp() {
508
+ process.stdout.write(
509
+ [
510
+ `Usage: ${CLI_NAME} status [--text|--json]`,
511
+ "",
512
+ "Show the current Avorelo status for the resolved workspace.",
513
+ "",
514
+ "Options:",
515
+ " --text Print human-readable status output",
516
+ " --json Print machine-readable status output",
517
+ " --help Show this help",
518
+ "",
519
+ `Note: Run inside your repo, use "${CLI_NAME} workspace set <path>", or set AVORELO_WORKSPACE when using this globally.`,
520
+ ].join("\n") + "\n"
521
+ );
522
+ }
523
+
524
+ function renderDashboard(cwd, forwardedArgs = []) {
525
+ const { buildStatusDashboard } = require("./dashboard");
526
+ const { buildDashboardJson, formatBoundedDashboard } = require("../cco-dashboard");
527
+ const wantJson = forwardedArgs.includes("--json");
528
+ const wantValue = forwardedArgs.includes("--value");
529
+ const wantOpen = forwardedArgs.includes("--open");
530
+ const platformArg = forwardedArgs.find((arg) => arg.startsWith("--platform="));
531
+ const platform = platformArg ? platformArg.split("=")[1] : "claude";
532
+
533
+ // --open: write and print path to local dashboard preview
534
+ if (wantOpen) {
535
+ const { buildOperatingValue, writeOperatingValue, OPERATING_VALUE_DASHBOARD_PREVIEW_REL } = require("./operating-value");
536
+ const value = buildOperatingValue(cwd);
537
+ writeOperatingValue(cwd, value);
538
+ const previewPath = value.dashboardReady && value.dashboardReady.localDashboardPath;
539
+ if (previewPath) {
540
+ process.stdout.write(`Avorelo local dashboard preview written to:\n ${previewPath}\n\nOpen it in your editor or run: cat "${previewPath}"\n`);
541
+ } else {
542
+ process.stdout.write(`Dashboard preview not generated. Run \`avorelo operating-value --summary\` instead.\n`);
543
+ }
544
+ return;
545
+ }
546
+
547
+ const dashboard = buildStatusDashboard(cwd, { limit: 7 });
548
+ if (wantJson) {
549
+ process.stdout.write(`${JSON.stringify(buildDashboardJson(dashboard, platform, cwd), null, 2)}\n`);
550
+ return;
551
+ }
552
+ process.stdout.write(`${formatBoundedDashboard({
553
+ cwd,
554
+ platform,
555
+ tier: dashboard.tier,
556
+ what: "Quick view of optimization opportunities.",
557
+ why: "See Time, Risk, Cost impact and clear next steps.",
558
+ nextBestAction: dashboard.nextBestAction,
559
+ topFixesNow: (dashboard.topRecommendedFixes || []).slice(0, 3),
560
+ benefitSummary: dashboard.benefitSummary,
561
+ agentSecurity: dashboard.agentSecurity || null,
562
+ agentAccessGovernance: dashboard.agentAccessGovernance || null,
563
+ safePath: dashboard.safePath || null,
564
+ browserCapability: dashboard.browserCapability || null,
565
+ skillsOperatingLayer: dashboard.skillsOperatingLayer || null,
566
+ settingsControls: dashboard.settingsControls || null,
567
+ })}\n`);
568
+ // --value: append operating value section after existing dashboard surfaces
569
+ if (wantValue) {
570
+ try {
571
+ const { buildOperatingValue, writeOperatingValue, formatOperatingValueText } = require("./operating-value");
572
+ const value = buildOperatingValue(cwd);
573
+ writeOperatingValue(cwd, value);
574
+ process.stdout.write("\n" + formatOperatingValueText(value) + "\n");
575
+ } catch { /* operating-value surface unavailable; existing dashboard output is unaffected */ }
576
+ }
577
+ }
578
+
579
+ function printDashboardHelp() {
580
+ process.stdout.write(
581
+ [
582
+ `Usage: ${CLI_NAME} dashboard [--json] [--value] [--open] [--platform=<host>]`,
583
+ "",
584
+ "Show the current Avorelo dashboard for the resolved workspace.",
585
+ "",
586
+ "Options:",
587
+ " --json Print machine-readable dashboard output",
588
+ " --value Append operating-value detail after the dashboard",
589
+ " --open Write and print the local dashboard preview path",
590
+ " --platform=<host> Set the dashboard platform context (default: claude)",
591
+ " --help Show this help",
592
+ "",
593
+ `Note: Run inside your repo, use "${CLI_NAME} workspace set <path>", or set AVORELO_WORKSPACE when using this globally.`,
594
+ ].join("\n") + "\n"
595
+ );
596
+ }
597
+
598
+ function readFlagValue(args, name) {
599
+ const match = args.find((arg) => arg.startsWith(`${name}=`));
600
+ if (match) return match.split("=").slice(1).join("=");
601
+ const index = args.indexOf(name);
602
+ return index >= 0 ? args[index + 1] || null : null;
603
+ }
604
+
605
+ function renderPrompt(cwd, forwardedArgs = []) {
606
+ const wantJson = forwardedArgs.includes("--json");
607
+ const taskType = readFlagValue(forwardedArgs, "--task-type");
608
+ const plan = readFlagValue(forwardedArgs, "--plan");
609
+ const instruction = forwardedArgs.filter((arg) => !arg.startsWith("--")).join(" ").trim();
610
+ const { compilePrompt } = require("./prompt-compiler");
611
+ const result = compilePrompt({
612
+ instruction,
613
+ taskType,
614
+ plan,
615
+ cwd,
616
+ });
617
+ if (wantJson) {
618
+ process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
619
+ return;
620
+ }
621
+ process.stdout.write(`${result.compiledPrompt}\n`);
622
+ }
623
+
624
+ function renderCapabilities(cwd, forwardedArgs = []) {
625
+ const wantJson = forwardedArgs.includes("--json");
626
+ const packArg = (() => {
627
+ const idx = forwardedArgs.indexOf("--pack");
628
+ return idx >= 0 ? (forwardedArgs[idx + 1] || null) : null;
629
+ })();
630
+
631
+ const { buildCapabilityLayerSurface } = require("./capability-recommender");
632
+ const { listPacks, getPack } = require("./capability-packs");
633
+
634
+ // Single pack detail mode
635
+ if (packArg) {
636
+ const pack = getPack(packArg);
637
+ if (!pack) {
638
+ process.stderr.write(`[avorelo] Unknown pack: ${packArg}\n`);
639
+ process.stderr.write(`Available packs: ${listPacks().map((p) => p.id).join(", ")}\n`);
640
+ process.exit(1);
641
+ }
642
+ if (wantJson) {
643
+ process.stdout.write(`${JSON.stringify(pack, null, 2)}\n`);
644
+ return;
645
+ }
646
+ process.stdout.write([
647
+ `Pack: ${pack.name}`,
648
+ ` ${pack.description}`,
649
+ "",
650
+ "Outcomes:",
651
+ ...(pack.outcomes || []).map((o) => ` - ${o}`),
652
+ "",
653
+ `Entitlement: ${pack.defaultEntitlement}`,
654
+ "",
655
+ pack.userFacingCopy,
656
+ "",
657
+ ].join("\n") + "\n");
658
+ return;
659
+ }
660
+
661
+ // Default: compact recommendation summary (not a catalog dump)
662
+ const surface = buildCapabilityLayerSurface(cwd, {}, null);
663
+ if (wantJson) {
664
+ process.stdout.write(`${JSON.stringify(surface, null, 2)}\n`);
665
+ return;
666
+ }
667
+
668
+ const lines = [
669
+ `${PRODUCT_NAME} Capability Layer`,
670
+ "",
671
+ "Avorelo prepares the right capability for the job — locally, safely, and with evidence.",
672
+ "",
673
+ ];
674
+
675
+ if (surface && surface.recommendedPack) {
676
+ lines.push(`Recommended: ${surface.recommendedPack.name} (${surface.entitlement || "free"})`);
677
+ lines.push(`Why: ${surface.reason}`);
678
+ lines.push(`Next: ${surface.nextAction}`);
679
+ if (surface.evidencePath) {
680
+ lines.push(`Evidence: ${surface.evidencePath}`);
681
+ }
682
+ lines.push("");
683
+ }
684
+
685
+ if (surface && surface.activePacks && surface.activePacks.length > 0) {
686
+ lines.push(`Active packs: ${surface.activePacks.map((p) => p.name).join(", ")}`);
687
+ lines.push("");
688
+ }
689
+
690
+ if (surface && surface.additionalPacks && surface.additionalPacks.length > 0) {
691
+ lines.push("Also relevant:");
692
+ for (const p of surface.additionalPacks) {
693
+ lines.push(` ${p.name}`);
694
+ }
695
+ lines.push("");
696
+ }
697
+
698
+ lines.push(`Run: ${CLI_NAME} capabilities --pack <id> to see details for a specific pack.`);
699
+ lines.push(`Available packs: ${listPacks().map((p) => p.id).join(", ")}`);
700
+ lines.push("");
701
+
702
+ process.stdout.write(lines.join("\n") + "\n");
703
+ }
704
+
705
+ function renderWorkspaceRegistry(cwd, forwardedArgs = []) {
706
+ const wantJson = forwardedArgs.includes("--json");
707
+ const wantSummary = forwardedArgs.includes("--summary");
708
+ const wantDiff = forwardedArgs.includes("--diff");
709
+ const typeFilter = readFlagValue(forwardedArgs, "--type");
710
+ const refreshIntake = forwardedArgs.includes("--refresh-intake");
711
+
712
+ const {
713
+ buildWorkspaceRegistry,
714
+ writeWorkspaceRegistry,
715
+ readLatestRegistry,
716
+ formatRegistryText,
717
+ formatRegistrySummaryMarkdown,
718
+ } = require("./workspace-registry");
719
+
720
+ if (refreshIntake) {
721
+ try {
722
+ const { scanInstallIntakeRisk } = require("./install-intake-risk");
723
+ scanInstallIntakeRisk(cwd, { writeReceipt: true, plan: process.env.AVORELO_PLAN || "free", generatedBy: "workspace_registry_refresh_intake" });
724
+ } catch {}
725
+ }
726
+
727
+ const registry = buildWorkspaceRegistry(cwd);
728
+ writeWorkspaceRegistry(cwd, registry);
729
+
730
+ if (wantDiff) {
731
+ const drift = registry.drift;
732
+ process.stdout.write(JSON.stringify({
733
+ registryId: registry.registryId,
734
+ previousRegistryId: drift.previousRegistryId,
735
+ addedAssets: drift.addedAssets,
736
+ removedAssets: drift.removedAssets,
737
+ changedAssets: drift.changedAssets,
738
+ unchangedAssets: drift.unchangedAssets,
739
+ }, null, 2) + "\n");
740
+ return;
741
+ }
742
+
743
+ if (typeFilter) {
744
+ const filtered = (registry.assets || []).filter((a) => a.type === typeFilter);
745
+ process.stdout.write(JSON.stringify({ type: typeFilter, count: filtered.length, assets: filtered }, null, 2) + "\n");
746
+ return;
747
+ }
748
+
749
+ if (wantJson) {
750
+ const { assets, ...meta } = registry;
751
+ process.stdout.write(JSON.stringify({
752
+ ...meta,
753
+ assetCount: (assets || []).length,
754
+ assetPaths: (assets || []).map((a) => a.path).filter(Boolean).slice(0, 30),
755
+ }, null, 2) + "\n");
756
+ return;
757
+ }
758
+
759
+ if (wantSummary) {
760
+ process.stdout.write(formatRegistrySummaryMarkdown(registry) + "\n");
761
+ return;
762
+ }
763
+
764
+ process.stdout.write(formatRegistryText(registry) + "\n");
765
+ }
766
+
767
+ function renderWorkspaceHygiene(cwd, forwardedArgs = []) {
768
+ const wantJson = forwardedArgs.includes("--json");
769
+ const wantDebug = forwardedArgs.includes("--debug");
770
+ const {
771
+ buildHygieneReport,
772
+ renderHygieneText,
773
+ renderHygieneDebugText,
774
+ } = require("./ai-workspace-hygiene");
775
+
776
+ const { report, assets, findings } = buildHygieneReport(cwd, { debug: wantDebug });
777
+
778
+ if (wantJson) {
779
+ if (wantDebug) {
780
+ const {
781
+ LATEST_DEBUG_REPORT_REL,
782
+ CAPABILITY_REGISTRY_METADATA,
783
+ } = require("./ai-workspace-hygiene");
784
+ const debugOutput = {
785
+ ...report,
786
+ assets: assets.map((a) => ({
787
+ id: a.id, type: a.type, name: a.name, path: a.path,
788
+ status: a.status, riskLevel: a.riskLevel, contextCost: a.contextCost,
789
+ reviewStatus: a.reviewStatus, trustLevel: a.trustLevel,
790
+ reasonCodes: a.reasonCodes, recommendedAction: a.recommendedAction,
791
+ lifecycleStage: a.lifecycleStage, stageHints: a.stageHints,
792
+ workerHints: a.workerHints, orchestrationReady: a.orchestrationReady,
793
+ })),
794
+ findings,
795
+ capabilityRegistryMetadata: CAPABILITY_REGISTRY_METADATA,
796
+ };
797
+ process.stdout.write(JSON.stringify(debugOutput, null, 2) + "\n");
798
+ } else {
799
+ process.stdout.write(JSON.stringify(report, null, 2) + "\n");
800
+ }
801
+ return;
802
+ }
803
+
804
+ if (wantDebug) {
805
+ process.stdout.write(renderHygieneDebugText(report, assets, findings));
806
+ return;
807
+ }
808
+
809
+ process.stdout.write(renderHygieneText(report));
810
+ }
811
+
812
+ function renderWorkspaceMap(cwd, forwardedArgs = []) {
813
+ const wantJson = forwardedArgs.includes("--json");
814
+ const task = readFlagValue(forwardedArgs, "--task");
815
+ const { writeWorkspaceMap, formatWorkspaceMapText } = require("./workspace-map");
816
+ const map = writeWorkspaceMap(cwd, { task });
817
+ if (wantJson) {
818
+ process.stdout.write(`${JSON.stringify(map, null, 2)}\n`);
819
+ return;
820
+ }
821
+ process.stdout.write(`${formatWorkspaceMapText(map)}\n`);
822
+ }
823
+
824
+ function renderVisualQa(cwd, forwardedArgs = []) {
825
+ const wantJson = forwardedArgs.includes("--json");
826
+ const dryRun = forwardedArgs.includes("--dry-run");
827
+ const target = readFlagValue(forwardedArgs, "--target");
828
+ const plan = readFlagValue(forwardedArgs, "--plan");
829
+ const { runVisualQa } = require("./visual-qa");
830
+ const result = runVisualQa(cwd, {
831
+ target,
832
+ plan,
833
+ dryRun,
834
+ });
835
+ if (wantJson) {
836
+ process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
837
+ return;
838
+ }
839
+ if (!result.ok) {
840
+ process.stdout.write(`${result.what}\n`);
841
+ if (result.nextAction) process.stdout.write(`${result.nextAction}\n`);
842
+ return;
843
+ }
844
+ process.stdout.write(
845
+ [
846
+ `Visual QA: ${result.checkedSurface}`,
847
+ `Plan: ${result.plan}`,
848
+ result.guardDecision ? `Guard: ${result.guardDecision.decision} (${result.guardDecision.riskLevel})` : null,
849
+ `Screenshots captured: ${result.screenshotsCaptured ? "yes" : "no"}`,
850
+ `Evidence: ${result.evidenceStoredAt || "not available"}`,
851
+ `Next: ${result.nextAction}`,
852
+ ].filter(Boolean).join("\n") + "\n"
853
+ );
854
+ }
855
+
856
+ function renderGuard(cwd, forwardedArgs = []) {
857
+ const wantJson = forwardedArgs.includes("--json");
858
+ const dryRun = forwardedArgs.includes("--dry-run");
859
+ const action = readFlagValue(forwardedArgs, "--action");
860
+ const target = readFlagValue(forwardedArgs, "--target");
861
+ const task = readFlagValue(forwardedArgs, "--task");
862
+ const plan = readFlagValue(forwardedArgs, "--plan");
863
+
864
+ if (!action) {
865
+ throw new Error("`avorelo guard` requires --action.");
866
+ }
867
+
868
+ const input = {
869
+ actionType: action,
870
+ requestedBy: "cli",
871
+ userIntent: task || "",
872
+ taskType: task || "",
873
+ target,
874
+ plan,
875
+ };
876
+
877
+ if (action === "file_read" || action === "file_write" || action === "config_change") {
878
+ input.targetPaths = target ? [target] : [];
879
+ }
880
+ if (action === "command_run" || action === "git_operation" || action === "deploy_operation") {
881
+ input.command = target || "";
882
+ }
883
+ if (action === "browser_action" || action === "visual_qa_run") {
884
+ input.url = target || "";
885
+ try {
886
+ input.domain = target ? new URL(/^https?:\/\//i.test(target) ? target : `http://${target}`).hostname : null;
887
+ } catch {
888
+ input.domain = null;
889
+ }
890
+ }
891
+ if (action === "tool_call") {
892
+ input.toolName = target || "";
893
+ }
894
+ if (action === "mcp_tool_call") {
895
+ if (target && target.includes(":")) {
896
+ const [mcpServer, toolName] = target.split(":");
897
+ input.mcpServer = mcpServer;
898
+ input.toolName = toolName || "";
899
+ } else {
900
+ input.toolName = target || "";
901
+ }
902
+ }
903
+
904
+ const { evaluateAgentAction } = require("./agent-enforcement");
905
+ const decision = evaluateAgentAction(input, {
906
+ cwd,
907
+ writeEvidence: true,
908
+ source: "cli",
909
+ });
910
+
911
+ const {
912
+ getDecisionVisibility,
913
+ buildGuardBlockOutcome,
914
+ writeSeamlessRunReceipt,
915
+ emitTaskContinuationEvents,
916
+ formatCompactGuardLine,
917
+ } = require("./seamless-enforcement");
918
+
919
+ // Determine whether this action should be visible in detail or compact
920
+ const visibility = getDecisionVisibility({
921
+ actionType: action,
922
+ riskLevel: decision.riskLevel,
923
+ isDestructive: decision.reasonCodes?.includes("DESTRUCTIVE") || false,
924
+ isIrreversible: decision.reasonCodes?.includes("IRREVERSIBLE") || false,
925
+ hasSecretsRisk: decision.reasonCodes?.includes("SECRETS_RISK") || decision.reasonCodes?.includes("SENSITIVE_ENV_FILE") || false,
926
+ requiresExplicitApproval: decision.decision === "block",
927
+ });
928
+
929
+ // Build task-specific continuation for all non-allow decisions
930
+ const outcomeCheck = buildGuardBlockOutcome(decision.decision, {
931
+ actionType: action,
932
+ riskLevel: decision.riskLevel,
933
+ target,
934
+ userIntent: task,
935
+ taskType: task,
936
+ saferAlternative: decision.saferAlternative,
937
+ reasonCodes: decision.reasonCodes,
938
+ });
939
+
940
+ const payload = {
941
+ dryRun,
942
+ decisionId: decision.decisionId,
943
+ decision: decision.decision,
944
+ riskLevel: decision.riskLevel,
945
+ reasonCodes: decision.reasonCodes,
946
+ matchedRules: decision.matchedRules,
947
+ explanation: decision.explanation,
948
+ saferAlternative: decision.saferAlternative,
949
+ // Task-specific continuation fields (top-level for automation consumers)
950
+ taskStillExecutable: outcomeCheck?.taskStillExecutable ?? null,
951
+ fallbackAvailable: outcomeCheck?.fallbackAvailable ?? null,
952
+ escalationRecommended: outcomeCheck?.escalationRecommended ?? null,
953
+ safeNextAction: outcomeCheck?.safeNextAction ?? decision.saferAlternative ?? null,
954
+ continuationType: outcomeCheck?.continuationType ?? null,
955
+ suggestedScope: outcomeCheck?.suggestedScope ?? null,
956
+ suggestedCommand: outcomeCheck?.suggestedCommand ?? null,
957
+ verificationNextStep: outcomeCheck?.verificationNextStep ?? null,
958
+ evidencePath: decision.evidencePath,
959
+ governanceReceiptPath: decision.governanceReceiptPath || null,
960
+ safePathReceiptPath: decision.safePathReceiptPath || null,
961
+ installIntakeReceiptPath: decision.installIntakeReceiptPath || null,
962
+ plan: decision.plan,
963
+ mode: decision.mode,
964
+ governance: decision.governance || null,
965
+ safePath: decision.safePath || null,
966
+ installIntake: decision.installIntake || null,
967
+ outcomePreservation: outcomeCheck || null,
968
+ seamlessMode: visibility.mode,
969
+ interruptRequired: visibility.interruptRequired,
970
+ };
971
+
972
+ // Auto-write value summary after guard evaluation (best-effort)
973
+ writeSeamlessRunReceipt(cwd, {
974
+ command: "guard",
975
+ manualDecisionsAvoided: visibility.interruptRequired ? 0 : 1,
976
+ unsafeActionsBlocked: decision.decision === "block" ? 1 : 0,
977
+ qualityPreserved: true,
978
+ userInterruptAvoided: !visibility.interruptRequired,
979
+ interruptionRequired: visibility.interruptRequired,
980
+ interruptReason: visibility.interruptReason,
981
+ });
982
+
983
+ // Emit task continuation events (best-effort)
984
+ if (outcomeCheck) {
985
+ emitTaskContinuationEvents(cwd, {
986
+ continuationType: outcomeCheck.continuationType,
987
+ safeNextAction: outcomeCheck.safeNextAction,
988
+ decision: decision.decision,
989
+ riskLevel: decision.riskLevel,
990
+ actionType: action,
991
+ taskStillExecutable: outcomeCheck.taskStillExecutable,
992
+ fallbackAvailable: outcomeCheck.fallbackAvailable,
993
+ escalationRecommended: outcomeCheck.escalationRecommended,
994
+ });
995
+ }
996
+
997
+ if (wantJson) {
998
+ process.stdout.write(`${JSON.stringify(payload, null, 2)}\n`);
999
+ return;
1000
+ }
1001
+
1002
+ // Compact output for safe routine actions in automatic mode
1003
+ if (!visibility.showDetail) {
1004
+ process.stdout.write(formatCompactGuardLine(decision.decision, decision.riskLevel) + "\n");
1005
+ return;
1006
+ }
1007
+
1008
+ // Full detail output — required when interruption is needed or mode is manual_debug
1009
+ process.stdout.write(
1010
+ [
1011
+ `Guard decision: ${payload.decision}`,
1012
+ visibility.interruptRequired ? `ACTION REQUIRED: ${visibility.interruptReason || "approval needed"}` : null,
1013
+ `Risk: ${payload.riskLevel}`,
1014
+ `Why: ${payload.explanation}`,
1015
+ `Reason codes: ${payload.reasonCodes.length ? payload.reasonCodes.join(", ") : "none"}`,
1016
+ `Matched rules: ${payload.matchedRules.length ? payload.matchedRules.join(", ") : "none"}`,
1017
+ payload.governance ? `Subject: ${payload.governance.subjectSummary.type} / ${payload.governance.subjectSummary.name} / ${payload.governance.subjectSummary.trustStatus}` : null,
1018
+ payload.governance ? `Approval boundary: ${payload.governance.approvalBoundary.summary}` : null,
1019
+ payload.safePath ? `Safe path: ${payload.safePath.safePathDecision}` : null,
1020
+ payload.installIntake ? `Install intake: ${payload.installIntake.summary.totalItems} items / ${payload.installIntake.summary.unknownItems} unknown / ${payload.installIntake.summary.highRiskItems} high` : null,
1021
+ payload.installIntake?.matchedItems?.length ? `Matched intake: ${payload.installIntake.matchedItems.map((item) => `${item.name} (${item.reviewStatus}/${item.riskLevel})`).join(", ")}` : null,
1022
+ payload.safePath?.recommendedBoundary ? `Boundary: ${payload.safePath.recommendedBoundary.accessMode} / ${payload.safePath.recommendedBoundary.pathScope?.join(",") || payload.safePath.recommendedBoundary.domainScope?.join(",") || "narrow local scope"} / ${payload.safePath.recommendedBoundary.allowSecrets === false ? "no-secrets" : "secrets-possible"}` : null,
1023
+ payload.safePath?.nextAction ? `Safe path next: ${payload.safePath.nextAction}` : null,
1024
+ payload.installIntake?.nextAction ? `Intake next: ${payload.installIntake.nextAction}` : null,
1025
+ `Safe next action: ${payload.safeNextAction || payload.saferAlternative}`,
1026
+ payload.continuationType ? `Continuation: ${payload.continuationType}` : null,
1027
+ payload.suggestedCommand ? `Suggested command: ${payload.suggestedCommand}` : null,
1028
+ payload.verificationNextStep ? `Verify next: ${payload.verificationNextStep}` : null,
1029
+ outcomeCheck ? `Task still executable: ${outcomeCheck.taskStillExecutable}` : null,
1030
+ outcomeCheck?.escalationRecommended ? `Escalation recommended: yes` : null,
1031
+ payload.evidencePath ? `Evidence: ${payload.evidencePath}` : null,
1032
+ payload.governanceReceiptPath ? `Governance receipt: ${payload.governanceReceiptPath}` : null,
1033
+ payload.safePathReceiptPath ? `Safe path receipt: ${payload.safePathReceiptPath}` : null,
1034
+ payload.installIntakeReceiptPath ? `Install intake receipt: ${payload.installIntakeReceiptPath}` : null,
1035
+ ].filter(Boolean).join("\n") + "\n"
1036
+ );
1037
+ }
1038
+
1039
+ function renderBrainPack(cwd, forwardedArgs = []) {
1040
+ const wantJson = forwardedArgs.includes("--json");
1041
+ const wantSummary = forwardedArgs.includes("--summary");
1042
+ const wantInit = forwardedArgs.includes("--init");
1043
+ const recipeArg = (() => {
1044
+ const idx = forwardedArgs.indexOf("--recipe");
1045
+ return idx >= 0 ? (forwardedArgs[idx + 1] || null) : null;
1046
+ })();
1047
+
1048
+ const {
1049
+ buildBrainPack,
1050
+ writeBrainPack,
1051
+ readLatestBrainPack,
1052
+ buildBrainPackSurface,
1053
+ buildBrainPackMarkdown,
1054
+ formatBrainPackText,
1055
+ detectRecipe,
1056
+ BRAIN_PACK_CONTRACT,
1057
+ BRAIN_PACK_LATEST_JSON,
1058
+ BRAIN_PACK_LATEST_MD,
1059
+ } = require("./brain-pack");
1060
+
1061
+ // Recipe detection only
1062
+ if (recipeArg) {
1063
+ const result = detectRecipe(recipeArg, { cwd });
1064
+ if (wantJson) {
1065
+ process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
1066
+ return;
1067
+ }
1068
+ process.stdout.write([
1069
+ `Recipe: ${result.detectedRecipe || "none"}`,
1070
+ `Confidence: ${result.confidence}`,
1071
+ `Reason: ${result.reason}`,
1072
+ result.recommendedCapabilityPack ? `Capability: ${result.recommendedCapabilityPack}` : null,
1073
+ result.firstCommand ? `First command: ${result.firstCommand}` : null,
1074
+ ...(result.doNotRepeat || []).map((d) => `- ${d}`),
1075
+ ...(result.deferredCapabilities || []).map((d) => `Deferred: ${d}`),
1076
+ ].filter(Boolean).join("\n") + "\n");
1077
+ return;
1078
+ }
1079
+
1080
+ // --init: create default brain pack if missing
1081
+ if (wantInit) {
1082
+ const existing = readLatestBrainPack(cwd);
1083
+ if (existing) {
1084
+ process.stdout.write(`Brain Pack already exists: ${BRAIN_PACK_LATEST_JSON}\n`);
1085
+ return;
1086
+ }
1087
+ const bp = buildBrainPack(cwd, {});
1088
+ const paths = writeBrainPack(cwd, bp);
1089
+ process.stdout.write(`Brain Pack initialized: ${paths.jsonPath}\n`);
1090
+ return;
1091
+ }
1092
+
1093
+ // Default: build, write, and output
1094
+ const bp = buildBrainPack(cwd, {});
1095
+ writeBrainPack(cwd, bp);
1096
+
1097
+ if (wantJson) {
1098
+ process.stdout.write(`${JSON.stringify({
1099
+ contract: bp.contract,
1100
+ brainPackId: bp.brainPackId,
1101
+ createdAt: bp.createdAt,
1102
+ project: bp.project,
1103
+ repoConventions: bp.repoConventions,
1104
+ contextRules: bp.contextRules,
1105
+ recipes: bp.recipes,
1106
+ signals: {
1107
+ lastWorkControlFinalState: bp.signals?.lastWorkControlFinalState,
1108
+ nextSafestAction: bp.signals?.nextSafestAction,
1109
+ nextRoadmapCandidates: bp.signals?.nextRoadmapCandidates,
1110
+ },
1111
+ capabilityRecommendation: bp.capabilityRecommendation,
1112
+ jsonPath: BRAIN_PACK_LATEST_JSON,
1113
+ mdPath: BRAIN_PACK_LATEST_MD,
1114
+ }, null, 2)}\n`);
1115
+ return;
1116
+ }
1117
+
1118
+ if (wantSummary) {
1119
+ const { buildBrainPackMarkdown: mkMd } = require("./brain-pack");
1120
+ process.stdout.write(mkMd(bp) + "\n");
1121
+ return;
1122
+ }
1123
+
1124
+ process.stdout.write(formatBrainPackText(bp));
1125
+ }
1126
+
1127
+ function renderSessionContext(cwd, forwardedArgs = []) {
1128
+ const wantJson = forwardedArgs.includes("--json");
1129
+ const wantHandoff = forwardedArgs.includes("--handoff");
1130
+ const targetArg = readFlagValue(forwardedArgs, "--target");
1131
+ const maxCharsArg = readFlagValue(forwardedArgs, "--max-chars");
1132
+
1133
+ // Exclude flag names and their values from bare task args
1134
+ const flagsWithValues = new Set(["--target", "--max-chars", "--task"]);
1135
+ const taskArgTokens = [];
1136
+ for (let i = 0; i < forwardedArgs.length; i++) {
1137
+ const a = forwardedArgs[i];
1138
+ if (a.startsWith("--")) {
1139
+ if (flagsWithValues.has(a)) i += 1;
1140
+ continue;
1141
+ }
1142
+ taskArgTokens.push(a);
1143
+ }
1144
+ const taskArg = taskArgTokens.join(" ").trim() || null;
1145
+
1146
+ const targetSurface = targetArg === "codex"
1147
+ ? "codex"
1148
+ : targetArg === "local-model"
1149
+ ? "local_model"
1150
+ : targetArg === "claude"
1151
+ ? "claude"
1152
+ : "generic";
1153
+
1154
+ const maxChars = maxCharsArg ? parseInt(maxCharsArg, 10) || 6000 : 6000;
1155
+
1156
+ const {
1157
+ buildSessionContext,
1158
+ writeSessionContext,
1159
+ buildSessionContextSurface,
1160
+ formatSessionContextText,
1161
+ LATEST_CONTEXT_REL_PATH,
1162
+ LATEST_CONTEXT_MD_REL_PATH,
1163
+ } = require("./session-context-optimizer");
1164
+
1165
+ const context = buildSessionContext(cwd, {
1166
+ task: taskArg || undefined,
1167
+ targetSurface,
1168
+ maxChars,
1169
+ });
1170
+
1171
+ writeSessionContext(cwd, context, {
1172
+ plan: process.env.AVORELO_PLAN || "free",
1173
+ });
1174
+
1175
+ if (wantJson) {
1176
+ const { markdownHandoff, compactPrompt, ...sessionStartSafe } = context.sessionStart;
1177
+ process.stdout.write(`${JSON.stringify({
1178
+ contract: context.contract,
1179
+ contextId: context.contextId,
1180
+ createdAt: context.createdAt,
1181
+ targetSurface: context.targetSurface,
1182
+ finalState: context.sessionStart.currentState?.finalState || "missing",
1183
+ nextSafestAction: context.sessionStart.nextSafestAction,
1184
+ compactPrompt,
1185
+ tokenDiscipline: context.tokenDiscipline,
1186
+ sourceReceipts: context.sourceReceipts,
1187
+ receiptPath: LATEST_CONTEXT_REL_PATH,
1188
+ markdownHandoffPath: LATEST_CONTEXT_MD_REL_PATH,
1189
+ }, null, 2)}\n`);
1190
+ return;
1191
+ }
1192
+
1193
+ if (wantHandoff) {
1194
+ process.stdout.write(formatSessionContextText(context, { handoff: true, targetSurface }));
1195
+ return;
1196
+ }
1197
+
1198
+ process.stdout.write(formatSessionContextText(context, { targetSurface }));
1199
+ }
1200
+
1201
+ function renderWorkControl(cwd, forwardedArgs = []) {
1202
+ const wantJson = forwardedArgs.includes("--json");
1203
+ const wantHandoff = forwardedArgs.includes("--handoff");
1204
+ const doWrite = forwardedArgs.includes("--write") || true;
1205
+
1206
+ const {
1207
+ buildWorkControlReceipt,
1208
+ writeWorkControlReceipt,
1209
+ buildWorkControlSurface,
1210
+ formatWorkControlText,
1211
+ } = require("./work-control-receipts");
1212
+
1213
+ const receipt = buildWorkControlReceipt(cwd, {
1214
+ surface: "avorelo_cli",
1215
+ });
1216
+
1217
+ if (doWrite) {
1218
+ writeWorkControlReceipt(cwd, receipt, {
1219
+ plan: process.env.AVORELO_PLAN || "free",
1220
+ });
1221
+ }
1222
+
1223
+ if (wantJson) {
1224
+ process.stdout.write(`${JSON.stringify(receipt, null, 2)}\n`);
1225
+ return;
1226
+ }
1227
+
1228
+ if (wantHandoff) {
1229
+ process.stdout.write(formatWorkControlText(receipt, { handoff: true }));
1230
+ return;
1231
+ }
1232
+
1233
+ process.stdout.write(formatWorkControlText(receipt));
1234
+ }
1235
+
1236
+ function renderIntake(cwd, forwardedArgs = []) {
1237
+ const wantJson = forwardedArgs.includes("--json");
1238
+ const typeFilter = readFlagValue(forwardedArgs, "--type");
1239
+ const { scanInstallIntakeRisk } = require("./install-intake-risk");
1240
+ const result = scanInstallIntakeRisk(cwd, {
1241
+ writeReceipt: true,
1242
+ plan: process.env.AVORELO_PLAN || "free",
1243
+ generatedBy: "public_cli_intake",
1244
+ });
1245
+ const filteredItems = typeFilter
1246
+ ? (result.receipt.items || []).filter((item) => item.type === typeFilter)
1247
+ : (result.receipt.items || []);
1248
+ const payload = {
1249
+ contract: result.receipt.contract,
1250
+ summary: {
1251
+ ...result.receipt.summary,
1252
+ filteredItems: filteredItems.length,
1253
+ },
1254
+ topRiskyItems: filteredItems
1255
+ .filter((item) => ["high", "critical"].includes(item.riskLevel) || ["unknown", "deferred", "blocked"].includes(item.reviewStatus))
1256
+ .slice(0, 8)
1257
+ .map((item) => ({
1258
+ id: item.id,
1259
+ type: item.type,
1260
+ name: item.name,
1261
+ reviewStatus: item.reviewStatus,
1262
+ riskLevel: item.riskLevel,
1263
+ reasonCodes: item.reasonCodes.slice(0, 5),
1264
+ safeNextAction: item.safeNextAction,
1265
+ })),
1266
+ topReasonCodes: result.receipt.topReasonCodes.slice(0, 8),
1267
+ safeNextActions: filteredItems
1268
+ .map((item) => item.safeNextAction)
1269
+ .filter(Boolean)
1270
+ .filter((value, index, array) => array.indexOf(value) === index)
1271
+ .slice(0, 5),
1272
+ receiptPath: result.receiptPath,
1273
+ redacted: true,
1274
+ };
1275
+ if (wantJson) {
1276
+ process.stdout.write(`${JSON.stringify(payload, null, 2)}\n`);
1277
+ return;
1278
+ }
1279
+ process.stdout.write(
1280
+ [
1281
+ "Install Intake",
1282
+ `Items: ${payload.summary.totalItems} total · ${payload.summary.unknownItems} unknown · ${payload.summary.deferredItems} deferred · ${payload.summary.blockedItems} blocked · ${payload.summary.highRiskItems} high · ${payload.summary.criticalRiskItems} critical`,
1283
+ `Top reason codes: ${payload.topReasonCodes.join(", ") || "none"}`,
1284
+ `Next: ${result.receipt.nextAction}`,
1285
+ `Receipt: ${result.receiptPath}`,
1286
+ ].join("\n") + "\n"
1287
+ );
1288
+ }
1289
+
1290
+ function renderOperatingValue(cwd, forwardedArgs = []) {
1291
+ const wantJson = forwardedArgs.includes("--json");
1292
+ const wantSummary = forwardedArgs.includes("--summary");
1293
+ const wantMoments = forwardedArgs.includes("--moments");
1294
+ const wantValidate = forwardedArgs.includes("--validate");
1295
+
1296
+ const {
1297
+ buildOperatingValue,
1298
+ writeOperatingValue,
1299
+ formatOperatingValueText,
1300
+ buildOperatingValueSummaryMarkdown,
1301
+ OPERATING_VALUE_LATEST_REL,
1302
+ OPERATING_VALUE_SUMMARY_REL,
1303
+ OPERATING_VALUE_DASHBOARD_PREVIEW_REL,
1304
+ } = require("./operating-value");
1305
+
1306
+ const value = buildOperatingValue(cwd);
1307
+ writeOperatingValue(cwd, value);
1308
+
1309
+ if (wantJson) {
1310
+ process.stdout.write(`${JSON.stringify(value, null, 2)}\n`);
1311
+ return;
1312
+ }
1313
+
1314
+ if (wantSummary) {
1315
+ process.stdout.write(buildOperatingValueSummaryMarkdown(value) + "\n");
1316
+ return;
1317
+ }
1318
+
1319
+ if (wantMoments) {
1320
+ process.stdout.write(formatOperatingValueText(value, { momentsOnly: true }) + "\n");
1321
+ return;
1322
+ }
1323
+
1324
+ if (wantValidate) {
1325
+ process.stdout.write(formatOperatingValueText(value, { validateOnly: true }) + "\n");
1326
+ return;
1327
+ }
1328
+
1329
+ process.stdout.write(formatOperatingValueText(value) + "\n");
1330
+ }
1331
+
1332
+ // ── Measurement Evidence CLI ───────────────────────────────────────────────────
1333
+
1334
+ function renderPricing(cwd, forwardedArgs = []) {
1335
+ const {
1336
+ initLocalPricing,
1337
+ validateLocalPricing,
1338
+ readLocalPricing,
1339
+ getLocalPricingSource,
1340
+ formatPricingText,
1341
+ } = require("./local-pricing");
1342
+
1343
+ const wantJson = forwardedArgs.includes("--json");
1344
+ const wantInit = forwardedArgs.includes("--init");
1345
+ const wantValidate = forwardedArgs.includes("--validate");
1346
+
1347
+ if (wantInit) {
1348
+ const result = initLocalPricing(cwd);
1349
+ process.stdout.write(wantJson
1350
+ ? `${JSON.stringify(result, null, 2)}\n`
1351
+ : `${result.message}\n Path: ${result.path}\n`);
1352
+ return;
1353
+ }
1354
+
1355
+ if (wantValidate) {
1356
+ const config = readLocalPricing(cwd);
1357
+ if (!config) {
1358
+ process.stderr.write("No local pricing config found. Run `avorelo pricing --init` first.\n");
1359
+ process.exit(1);
1360
+ }
1361
+ const result = validateLocalPricing(config);
1362
+ if (wantJson) {
1363
+ process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
1364
+ return;
1365
+ }
1366
+ if (result.valid) {
1367
+ process.stdout.write(`Local pricing config is valid. (${config.entries.length} entries)\n`);
1368
+ } else {
1369
+ process.stderr.write(`Local pricing config has errors:\n${result.errors.map((e) => ` - ${e}`).join("\n")}\n`);
1370
+ process.exit(1);
1371
+ }
1372
+ return;
1373
+ }
1374
+
1375
+ if (wantJson) {
1376
+ const source = getLocalPricingSource(cwd);
1377
+ const config = readLocalPricing(cwd);
1378
+ process.stdout.write(`${JSON.stringify({ source, config }, null, 2)}\n`);
1379
+ return;
1380
+ }
1381
+
1382
+ process.stdout.write(formatPricingText(cwd));
1383
+ }
1384
+
1385
+ function renderTokenEvidence(cwd, forwardedArgs = []) {
1386
+ const {
1387
+ buildTokenEvidence,
1388
+ writeTokenEvidence,
1389
+ formatTokenEvidenceText,
1390
+ formatTokenEvidenceDebugSources,
1391
+ } = require("./token-evidence");
1392
+
1393
+ const wantJson = forwardedArgs.includes("--json");
1394
+ const wantDebugSources = forwardedArgs.includes("--debug-sources");
1395
+
1396
+ const evidence = buildTokenEvidence(cwd);
1397
+ writeTokenEvidence(cwd, evidence);
1398
+
1399
+ if (wantJson) {
1400
+ process.stdout.write(`${JSON.stringify(evidence, null, 2)}\n`);
1401
+ return;
1402
+ }
1403
+
1404
+ if (wantDebugSources) {
1405
+ process.stdout.write(formatTokenEvidenceDebugSources(evidence));
1406
+ return;
1407
+ }
1408
+
1409
+ process.stdout.write(formatTokenEvidenceText(evidence));
1410
+ }
1411
+
1412
+ function renderSessionTiming(cwd, forwardedArgs = []) {
1413
+ const {
1414
+ buildSessionTimingSummary,
1415
+ writeSessionTiming,
1416
+ recordTimingEvent,
1417
+ formatSessionTimingText,
1418
+ } = require("./session-timing");
1419
+
1420
+ const wantJson = forwardedArgs.includes("--json");
1421
+ const wantSummary = forwardedArgs.includes("--summary");
1422
+ const markIdx = forwardedArgs.indexOf("--mark");
1423
+ const markEvent = markIdx >= 0 ? (forwardedArgs[markIdx + 1] || "first-useful-action") : null;
1424
+
1425
+ if (markEvent) {
1426
+ const eventName = markEvent.replace(/-/g, "_");
1427
+ const entry = recordTimingEvent(cwd, eventName);
1428
+ process.stdout.write(wantJson
1429
+ ? `${JSON.stringify(entry, null, 2)}\n`
1430
+ : `Timing event recorded: ${eventName} at ${entry.timestamp}\n`);
1431
+ return;
1432
+ }
1433
+
1434
+ const timing = buildSessionTimingSummary(cwd);
1435
+ writeSessionTiming(cwd, timing);
1436
+
1437
+ if (wantJson) {
1438
+ process.stdout.write(`${JSON.stringify(timing, null, 2)}\n`);
1439
+ return;
1440
+ }
1441
+
1442
+ process.stdout.write(formatSessionTimingText(timing));
1443
+ }
1444
+
1445
+ function renderContextPack(cwd, forwardedArgs = []) {
1446
+ const {
1447
+ buildAndWriteContextPack,
1448
+ buildContextOptimizerSurface,
1449
+ STAGE_BUDGETS,
1450
+ } = require("./context-optimizer");
1451
+
1452
+ const wantJson = forwardedArgs.includes("--json");
1453
+ const taskText = forwardedArgs.filter((a) => !a.startsWith("--")).join(" ").trim();
1454
+ const stageArg = forwardedArgs.find((a) => a.startsWith("--stage="));
1455
+ const stageId = stageArg ? stageArg.split("=")[1] : "implement";
1456
+ const workerArg = forwardedArgs.find((a) => a.startsWith("--worker="));
1457
+ const worker = workerArg ? workerArg.split("=")[1] : null;
1458
+
1459
+ if (!taskText) {
1460
+ if (wantJson) {
1461
+ const surface = buildContextOptimizerSurface(cwd);
1462
+ process.stdout.write(`${JSON.stringify(surface, null, 2)}\n`);
1463
+ return;
1464
+ }
1465
+ const surface = buildContextOptimizerSurface(cwd);
1466
+ process.stdout.write([
1467
+ "Context Optimization",
1468
+ `Status: ${surface.status || "not_run"}`,
1469
+ surface.stageId ? `Stage: ${surface.stageId} · Budget: ${surface.budgetClass} · ~${surface.lastEstimatedTokens || 0} tokens` : "",
1470
+ surface.budgetWarning ? `Budget warning: ${surface.budgetWarning}` : "",
1471
+ surface.latestContextPackPath ? `Pack: ${surface.latestContextPackPath}` : "",
1472
+ `Next: ${surface.nextAction}`,
1473
+ ].filter(Boolean).join("\n") + "\n");
1474
+ return;
1475
+ }
1476
+
1477
+ const result = buildAndWriteContextPack(cwd, {
1478
+ taskSummary: taskText,
1479
+ stageId,
1480
+ stageRole: stageId,
1481
+ selectedWorker: worker,
1482
+ });
1483
+
1484
+ const payload = {
1485
+ contract: result.pack.contract,
1486
+ contextPackId: result.pack.contextPackId,
1487
+ taskSummary: result.pack.taskSummary,
1488
+ stageId: result.pack.stageId,
1489
+ budgetClass: result.pack.targetBudget.budgetClass,
1490
+ tokenEstimate: result.pack.tokenEstimate.estimatedTokens,
1491
+ maxInputTokens: result.pack.tokenEstimate.maxInputTokens,
1492
+ budgetWarning: result.pack.tokenEstimate.warning,
1493
+ includedCount: result.pack.includedContext.length,
1494
+ excludedCount: result.pack.excludedContext.length,
1495
+ compactionUsed: result.pack.reductionSummary.compactionUsed,
1496
+ localWorkerCapped: result.pack.localWorkerCapped,
1497
+ contextPackPath: result.latestPackPath,
1498
+ receiptPath: result.latestReceiptPath,
1499
+ nextAction: result.pack.nextAction,
1500
+ };
1501
+
1502
+ // Auto-write value summary after context pack build (best-effort)
1503
+ const { writeSeamlessRunReceipt: writeCtxReceipt, formatCompactContextLine } = require("./seamless-enforcement");
1504
+ const { getDecisionVisibility: getCtxVisibility } = require("./seamless-enforcement");
1505
+ const ctxVisibility = getCtxVisibility({ actionType: "context_optimization", riskLevel: "low" });
1506
+ writeCtxReceipt(cwd, {
1507
+ command: "context",
1508
+ manualDecisionsAvoided: 1,
1509
+ userInterruptAvoided: !ctxVisibility.interruptRequired,
1510
+ });
1511
+
1512
+ if (wantJson) {
1513
+ process.stdout.write(`${JSON.stringify(payload, null, 2)}\n`);
1514
+ return;
1515
+ }
1516
+
1517
+ // Compact outcome line for automatic mode
1518
+ if (!ctxVisibility.showDetail) {
1519
+ process.stdout.write(formatCompactContextLine(result.pack) + "\n");
1520
+ return;
1521
+ }
1522
+
1523
+ process.stdout.write([
1524
+ "Context Pack",
1525
+ `ID: ${payload.contextPackId}`,
1526
+ `Stage: ${payload.stageId} · Budget: ${payload.budgetClass} · ~${payload.tokenEstimate} / ${payload.maxInputTokens} tokens`,
1527
+ `Warning: ${payload.budgetWarning}`,
1528
+ `Included: ${payload.includedCount} · Excluded: ${payload.excludedCount} · Compacted: ${payload.compactionUsed}`,
1529
+ `Local worker capped: ${payload.localWorkerCapped}`,
1530
+ `Pack: ${payload.contextPackPath}`,
1531
+ `Receipt: ${payload.receiptPath}`,
1532
+ payload.nextAction ? `Next: ${payload.nextAction}` : "",
1533
+ ].filter(Boolean).join("\n") + "\n");
1534
+ }
1535
+
1536
+ function renderCostEvidence(cwd, forwardedArgs = []) {
1537
+ const { getLocalPricingSource, getLocalPricingEntry } = require("./local-pricing");
1538
+ const { buildTokenEvidence, writeTokenEvidence } = require("./token-evidence");
1539
+ const { buildCostEvidenceV1 } = require("./cost-evidence");
1540
+
1541
+ const wantJson = forwardedArgs.includes("--json");
1542
+
1543
+ const pricingSource = getLocalPricingSource(cwd);
1544
+ const pricingEntry = pricingSource.available
1545
+ ? getLocalPricingEntry(cwd, "anthropic", "claude-sonnet-4-6")
1546
+ : null;
1547
+ const tokenEvidence = buildTokenEvidence(cwd);
1548
+ writeTokenEvidence(cwd, tokenEvidence);
1549
+ const costEvidence = buildCostEvidenceV1({ pricingSource, pricingEntry, tokenEvidence });
1550
+
1551
+ if (wantJson) {
1552
+ process.stdout.write(`${JSON.stringify(costEvidence, null, 2)}\n`);
1553
+ return;
1554
+ }
1555
+
1556
+ const lines = [
1557
+ "Avorelo Cost Evidence",
1558
+ "",
1559
+ ` Contract: ${costEvidence.contract}`,
1560
+ ` Confidence: ${costEvidence.confidence}`,
1561
+ ` Value class: ${costEvidence.valueClass}`,
1562
+ "",
1563
+ costEvidence.costAvoidedEstimate !== null
1564
+ ? ` Estimated cost impact: ~$${costEvidence.costAvoidedEstimate.toFixed(4)}`
1565
+ : " Cost estimate: unavailable",
1566
+ costEvidence.formula ? ` Formula: ${costEvidence.formula}` : null,
1567
+ costEvidence.pricingSource ? ` Pricing source: ${costEvidence.pricingSource}` : null,
1568
+ "",
1569
+ " Caveats:",
1570
+ ...(costEvidence.caveats || []).map((c) => ` - ${c}`),
1571
+ "",
1572
+ ` pricingAllowed: ${costEvidence.pricingAllowed}`,
1573
+ ` dashboardAllowed: ${costEvidence.dashboardAllowed}`,
1574
+ ` websiteAllowed: ${costEvidence.websiteAllowed}`,
1575
+ "",
1576
+ ].filter((l) => l !== null);
1577
+ process.stdout.write(lines.join("\n"));
1578
+ }
1579
+
1580
+ function renderLaunchReadiness(cwd, forwardedArgs = []) {
1581
+ const {
1582
+ buildLaunchReadiness,
1583
+ formatLaunchReadinessText,
1584
+ } = require("./launch-readiness");
1585
+
1586
+ const wantJson = forwardedArgs.includes("--json");
1587
+ const externalCwdArg = forwardedArgs.find((a) => a.startsWith("--external-cwd="));
1588
+ const externalCwd = externalCwdArg ? externalCwdArg.split("=")[1] : null;
1589
+
1590
+ const result = buildLaunchReadiness(REPO_ROOT, {
1591
+ runExternalDogfood: !!externalCwd,
1592
+ externalCwd,
1593
+ });
1594
+
1595
+ if (wantJson) {
1596
+ process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
1597
+ return;
1598
+ }
1599
+
1600
+ process.stdout.write(`${formatLaunchReadinessText(result)}\n`);
1601
+ }
1602
+
1603
+ function renderOutcome(cwd, forwardedArgs = []) {
1604
+ const wantJson = forwardedArgs.includes("--json");
1605
+ const wantGate = forwardedArgs.includes("--gate") || forwardedArgs.includes("--reality-gate");
1606
+ const wantSummary = forwardedArgs.includes("--summary");
1607
+ const doWrite = !forwardedArgs.includes("--no-write");
1608
+
1609
+ const { buildValueSummaryFromReceipts, buildSeamlessOutcomeSurface, readLatestValueSummary } = require("./seamless-outcome");
1610
+ const { runSeamlessRealityGate, writeGateReport, buildRealityGateSurface } = require("./seamless-reality-gate");
1611
+
1612
+ if (wantGate) {
1613
+ const report = runSeamlessRealityGate(cwd);
1614
+ if (doWrite) writeGateReport(cwd, report);
1615
+ if (wantJson) {
1616
+ process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
1617
+ return;
1618
+ }
1619
+ process.stdout.write([
1620
+ `Seamless Reality Gate: ${report.status.toUpperCase()} (score: ${report.score}/100)`,
1621
+ `Checks: ${report.summary.pass} pass · ${report.summary.warn} warn · ${report.summary.fail} fail · ${report.summary.skip} skip`,
1622
+ ...(report.gaps || []).map((g) => ` [${g.status}] ${g.id}: ${g.nextAction || ""}`),
1623
+ report.gaps?.length === 0 ? " All checks pass." : "",
1624
+ `Report: ${report.contract}`,
1625
+ ].filter(Boolean).join("\n") + "\n");
1626
+ return;
1627
+ }
1628
+
1629
+ // Build value summary from receipts
1630
+ const { summary, path: summaryPath } = buildValueSummaryFromReceipts(cwd);
1631
+
1632
+ // Also run the reality gate and write report
1633
+ const gateReport = runSeamlessRealityGate(cwd);
1634
+ if (doWrite) writeGateReport(cwd, gateReport);
1635
+
1636
+ if (wantJson) {
1637
+ process.stdout.write(`${JSON.stringify({
1638
+ ...summary,
1639
+ realityGate: {
1640
+ status: gateReport.status,
1641
+ score: gateReport.score,
1642
+ warnings: gateReport.summary?.warn || 0,
1643
+ failures: gateReport.summary?.fail || 0,
1644
+ },
1645
+ summaryPath,
1646
+ }, null, 2)}\n`);
1647
+ return;
1648
+ }
1649
+
1650
+ if (wantSummary) {
1651
+ const s = summary;
1652
+ process.stdout.write([
1653
+ `Seamless Outcome Summary`,
1654
+ `Mode: ${s.mode}`,
1655
+ `Status: ${s.completed?.status}`,
1656
+ `Completed: ${s.completed?.completedItems} stages`,
1657
+ `Saved (estimated): ${s.saved?.estimatedPremiumCallsAvoided} premium calls avoided · ${s.saved?.estimatedContextTokensAvoided} context tokens avoided`,
1658
+ `Protected: ${s.protected?.unsafeActionsBlocked} blocked · ${s.protected?.unknownToolsIsolated} isolated`,
1659
+ `Quality preserved: ${s.quality?.qualityPreserved}`,
1660
+ `Reality gate: ${gateReport.status} (score: ${gateReport.score})`,
1661
+ `Next: ${s.completed?.nextAction || "Run avorelo route to continue."}`,
1662
+ `Caveats: ${s.caveats?.join("; ")}`,
1663
+ ].filter(Boolean).join("\n") + "\n");
1664
+ return;
1665
+ }
1666
+
1667
+ // Default: compact human-readable
1668
+ const s = summary;
1669
+ process.stdout.write([
1670
+ `Seamless Outcome [${s.mode}]`,
1671
+ ` Completed: ${s.completed?.completedItems} stages · ${s.completed?.status}`,
1672
+ ` Saved (est.): ${s.saved?.estimatedPremiumCallsAvoided} premium calls avoided, ~${s.saved?.estimatedContextTokensAvoided} context tokens`,
1673
+ ` Protected: ${s.protected?.unsafeActionsBlocked} blocked, ${s.protected?.unknownToolsIsolated} isolated`,
1674
+ ` Quality preserved: ${s.quality?.qualityPreserved} · risk introduced: ${s.quality?.qualityRiskIntroduced}`,
1675
+ ` Reality gate: ${gateReport.status} (${gateReport.score}/100)`,
1676
+ ` Next: ${s.completed?.nextAction || "Run avorelo route to continue."}`,
1677
+ ` Note: ${s.caveats?.[0]}`,
1678
+ ].join("\n") + "\n");
1679
+ }
1680
+
1681
+ function renderOrchestrate(cwd, forwardedArgs = []) {
1682
+ const wantJson = forwardedArgs.includes("--json");
1683
+ const wantDebug = forwardedArgs.includes("--debug");
1684
+ const taskText = forwardedArgs.filter((a) => !a.startsWith("--")).join(" ").trim();
1685
+
1686
+ const {
1687
+ runWorkOrchestration,
1688
+ buildWorkOrchestrationSurface,
1689
+ formatWorkOrchestrationText,
1690
+ } = require("./work-aware-orchestration");
1691
+
1692
+ if (!taskText) {
1693
+ const surface = buildWorkOrchestrationSurface(cwd);
1694
+ if (wantJson) {
1695
+ process.stdout.write(`${JSON.stringify(surface, null, 2)}\n`);
1696
+ return;
1697
+ }
1698
+ process.stdout.write([
1699
+ "Work-Aware Orchestration",
1700
+ `Status: ${surface.status}`,
1701
+ surface.stageCount ? `Stages: ${surface.stageCount} (${surface.localOrCheapStages} local/cheap, ${surface.strongWorkerStages} strong)` : "",
1702
+ surface.nextAction ? `Next: ${surface.nextAction}` : "",
1703
+ "",
1704
+ `Run: avorelo orchestrate "your task description" to build a work plan.`,
1705
+ ].filter(Boolean).join("\n") + "\n");
1706
+ return;
1707
+ }
1708
+
1709
+ const plan = runWorkOrchestration(cwd, taskText, { debug: wantDebug });
1710
+
1711
+ if (wantJson) {
1712
+ const safe = {
1713
+ contract: plan.contract,
1714
+ schemaVersion: plan.schemaVersion,
1715
+ createdAt: plan.createdAt,
1716
+ mode: plan.mode,
1717
+ task: plan.task,
1718
+ stages: plan.stages.map((s) => ({
1719
+ stageId: s.stageId,
1720
+ objective: s.objective,
1721
+ lifecycleStage: s.lifecycleStage,
1722
+ riskLevel: s.riskLevel,
1723
+ contextNeed: s.contextNeed,
1724
+ qualityRequirement: s.qualityRequirement,
1725
+ recommendedWorker: s.recommendedWorker,
1726
+ fallbackWorker: s.fallbackWorker,
1727
+ workerSelection: s.workerSelection,
1728
+ contextSelection: s.contextSelection,
1729
+ continuation: s.continuation,
1730
+ proofExpected: s.proofExpected,
1731
+ customerVisible: s.customerVisible,
1732
+ debugVisible: s.debugVisible,
1733
+ redacted: true,
1734
+ })),
1735
+ summary: plan.summary,
1736
+ valueEvidence: plan.valueEvidence,
1737
+ nextAction: plan.nextAction,
1738
+ receipts: plan.receipts,
1739
+ redacted: true,
1740
+ };
1741
+ process.stdout.write(`${JSON.stringify(safe, null, 2)}\n`);
1742
+ return;
1743
+ }
1744
+
1745
+ process.stdout.write(formatWorkOrchestrationText(plan, { debug: wantDebug }) + "\n");
1746
+ }
1747
+
1748
+ function renderLedger(cwd, forwardedArgs = []) {
1749
+ const wantJson = forwardedArgs.includes("--json");
1750
+ const wantDebug = forwardedArgs.includes("--debug");
1751
+
1752
+ const {
1753
+ buildWorkLedger,
1754
+ writeWorkLedger,
1755
+ formatWorkLedgerText,
1756
+ LATEST_LEDGER_REL,
1757
+ } = require("./work-ledger");
1758
+ const { appendProductLearningEvent } = require("./product-learning-events");
1759
+
1760
+ const ledger = buildWorkLedger(cwd);
1761
+ writeWorkLedger(cwd, ledger);
1762
+
1763
+ try {
1764
+ appendProductLearningEvent(cwd, {
1765
+ eventName: "work_ledger_built",
1766
+ category: "work_ledger",
1767
+ surface: "local",
1768
+ status: "observed",
1769
+ payload: {
1770
+ status: ledger.status,
1771
+ entryCount: (ledger.entries || []).length,
1772
+ frictionCount: (ledger.rollup?.friction || []).length,
1773
+ receiptPathCount: (ledger.evidence?.receiptPaths || []).length,
1774
+ },
1775
+ });
1776
+ } catch {
1777
+ // non-blocking
1778
+ }
1779
+
1780
+ if (wantJson) {
1781
+ const safe = wantDebug
1782
+ ? ledger
1783
+ : {
1784
+ contract: ledger.contract,
1785
+ schemaVersion: ledger.schemaVersion,
1786
+ runId: ledger.runId,
1787
+ status: ledger.status,
1788
+ createdAt: ledger.createdAt,
1789
+ rollup: ledger.rollup,
1790
+ evidence: {
1791
+ receiptPaths: ledger.evidence.receiptPaths,
1792
+ feedbackPaths: ledger.evidence.feedbackPaths,
1793
+ },
1794
+ caveats: ledger.caveats,
1795
+ redacted: true,
1796
+ };
1797
+ process.stdout.write(`${JSON.stringify(safe, null, 2)}\n`);
1798
+ return;
1799
+ }
1800
+
1801
+ process.stdout.write(formatWorkLedgerText(ledger, { debug: wantDebug }) + "\n");
1802
+ }
1803
+
1804
+ function renderCompanyLoop(cwd, forwardedArgs = []) {
1805
+ const wantJson = forwardedArgs.includes("--json");
1806
+ const wantDebug = forwardedArgs.includes("--debug");
1807
+
1808
+ const {
1809
+ buildCompanyLoop,
1810
+ writeCompanyLoopReport,
1811
+ formatCompanyLoopText,
1812
+ } = require("./company-loop");
1813
+ const { appendProductLearningEvent } = require("./product-learning-events");
1814
+
1815
+ const report = buildCompanyLoop(cwd);
1816
+ writeCompanyLoopReport(cwd, report);
1817
+
1818
+ try {
1819
+ appendProductLearningEvent(cwd, {
1820
+ eventName: "company_loop_report_generated",
1821
+ category: "company_loop",
1822
+ surface: "local",
1823
+ status: "observed",
1824
+ payload: {
1825
+ status: report.status,
1826
+ personaWarnCount: report.surface?.personaWarnCount || 0,
1827
+ frictionClusterCount: (report.frictionClusters || []).length,
1828
+ topFriction: report.surface?.topFriction || null,
1829
+ confidence: report.nextPrRecommendation?.confidence || "low",
1830
+ },
1831
+ });
1832
+ } catch {
1833
+ // non-blocking
1834
+ }
1835
+
1836
+ if (wantJson) {
1837
+ const safe = wantDebug
1838
+ ? report
1839
+ : {
1840
+ contract: report.contract,
1841
+ schemaVersion: report.schemaVersion,
1842
+ createdAt: report.createdAt,
1843
+ status: report.status,
1844
+ surface: report.surface,
1845
+ frictionClusters: (report.frictionClusters || []).map((c) => ({
1846
+ clusterId: c.clusterId,
1847
+ type: c.type,
1848
+ severity: c.severity,
1849
+ count: c.count,
1850
+ recommendedFix: c.recommendedFix,
1851
+ candidateRoadmapItem: c.candidateRoadmapItem,
1852
+ })),
1853
+ cogsRollup: report.cogsRollup,
1854
+ nextPrRecommendation: report.nextPrRecommendation,
1855
+ redacted: true,
1856
+ };
1857
+ process.stdout.write(`${JSON.stringify(safe, null, 2)}\n`);
1858
+ return;
1859
+ }
1860
+
1861
+ process.stdout.write(formatCompanyLoopText(report, { debug: wantDebug }) + "\n");
1862
+ }
1863
+
1864
+ function renderProjectProfile(cwd, forwardedArgs = []) {
1865
+ const wantJson = forwardedArgs.includes("--json");
1866
+ const wantDebug = forwardedArgs.includes("--debug");
1867
+
1868
+ const {
1869
+ buildProjectProfile,
1870
+ writeProjectProfile,
1871
+ formatProjectProfileText,
1872
+ } = require("./project-profile");
1873
+
1874
+ const profile = buildProjectProfile(cwd);
1875
+ writeProjectProfile(cwd, profile);
1876
+
1877
+ if (wantJson) {
1878
+ process.stdout.write(`${JSON.stringify(profile, null, 2)}\n`);
1879
+ return;
1880
+ }
1881
+
1882
+ process.stdout.write(formatProjectProfileText(profile, { debug: wantDebug }));
1883
+ }
1884
+
1885
+ function renderExecutionPacket(cwd, forwardedArgs = []) {
1886
+ const wantJson = forwardedArgs.includes("--json");
1887
+ const wantDebug = forwardedArgs.includes("--debug");
1888
+ const { appendProductLearningEvent } = require("./product-learning-events");
1889
+
1890
+ const taskArgs = forwardedArgs.filter((a) => !a.startsWith("--"));
1891
+ const task = taskArgs.join(" ").trim();
1892
+
1893
+ const {
1894
+ compileExecutionPacket,
1895
+ compileAgentPrompt,
1896
+ writeExecutionPacket,
1897
+ formatExecutionPacketText,
1898
+ } = require("./execution-packet");
1899
+
1900
+ const packet = compileExecutionPacket(cwd, { userIntent: task });
1901
+ writeExecutionPacket(cwd, packet);
1902
+
1903
+ if (wantJson) {
1904
+ if (wantDebug) {
1905
+ const prompt = compileAgentPrompt(packet, { target: "claude_code" });
1906
+ process.stdout.write(`${JSON.stringify({ ...packet, compiledAgentPrompt: prompt.promptText }, null, 2)}\n`);
1907
+ } else {
1908
+ process.stdout.write(`${JSON.stringify(packet, null, 2)}\n`);
1909
+ }
1910
+ return;
1911
+ }
1912
+
1913
+ if (wantDebug) {
1914
+ const prompt = compileAgentPrompt(packet, { target: "claude_code" });
1915
+ process.stdout.write(formatExecutionPacketText(packet, { debug: true }));
1916
+ process.stdout.write("\n--- Compiled Agent Prompt ---\n");
1917
+ process.stdout.write(prompt.promptText + "\n");
1918
+ return;
1919
+ }
1920
+
1921
+ process.stdout.write(formatExecutionPacketText(packet));
1922
+
1923
+ try {
1924
+ appendProductLearningEvent(cwd, {
1925
+ eventName: "agent_prompt_compiled",
1926
+ category: "execution_packet",
1927
+ surface: "local",
1928
+ status: "observed",
1929
+ payload: {
1930
+ packetId: packet.packetId,
1931
+ mode: packet.mode,
1932
+ riskLevel: packet.risk?.level || "unknown",
1933
+ debugRequested: wantDebug,
1934
+ },
1935
+ });
1936
+ } catch {}
1937
+ }
1938
+
1939
+ function renderWorkPanel(cwd, forwardedArgs = []) {
1940
+ const wantJson = forwardedArgs.includes("--json");
1941
+ const wantDebug = forwardedArgs.includes("--debug");
1942
+
1943
+ const taskArgs = forwardedArgs.filter((a) => !a.startsWith("--"));
1944
+ const task = taskArgs.join(" ").trim();
1945
+
1946
+ // If a task is provided, compile a packet first
1947
+ if (task) {
1948
+ const {
1949
+ compileExecutionPacket,
1950
+ writeExecutionPacket,
1951
+ } = require("./execution-packet");
1952
+ const packet = compileExecutionPacket(cwd, { userIntent: task });
1953
+ writeExecutionPacket(cwd, packet);
1954
+ }
1955
+
1956
+ const {
1957
+ buildWorkPanelPreview,
1958
+ writeWorkPanelPreview,
1959
+ formatWorkPanelText,
1960
+ } = require("./work-panel-preview");
1961
+
1962
+ const preview = buildWorkPanelPreview(cwd);
1963
+ writeWorkPanelPreview(cwd, preview);
1964
+
1965
+ if (wantJson) {
1966
+ process.stdout.write(`${JSON.stringify(preview, null, 2)}\n`);
1967
+ return;
1968
+ }
1969
+
1970
+ process.stdout.write(formatWorkPanelText(preview, { debug: wantDebug }));
1971
+ }
1972
+
1973
+ function renderSmartRoute(cwd, forwardedArgs = []) {
1974
+ const wantJson = forwardedArgs.includes("--json");
1975
+ const wantDebug = forwardedArgs.includes("--debug");
1976
+ const { appendProductLearningEvent } = require("./product-learning-events");
1977
+
1978
+ const taskArgs = forwardedArgs.filter((a) => !a.startsWith("--"));
1979
+ const taskText = taskArgs.join(" ").trim();
1980
+
1981
+ const {
1982
+ buildSmartWorkRoute,
1983
+ writeSmartWorkRouteReceipt,
1984
+ writeWorkerHandoffReceipt,
1985
+ buildSmartRouteSurface,
1986
+ formatSmartRouteText,
1987
+ } = require("./smart-work-routing");
1988
+
1989
+ if (!taskText) {
1990
+ const surface = buildSmartRouteSurface(cwd);
1991
+ if (wantJson) {
1992
+ process.stdout.write(`${JSON.stringify(surface, null, 2)}\n`);
1993
+ return;
1994
+ }
1995
+ process.stdout.write([
1996
+ "Smart Work Routing",
1997
+ `Status: ${surface.status}`,
1998
+ surface.nextAction ? `Next: ${surface.nextAction}` : "",
1999
+ "",
2000
+ `Run: avorelo smart-route "your task" to route work to the cheapest safe capable path.`,
2001
+ ].filter(Boolean).join("\n") + "\n");
2002
+ return;
2003
+ }
2004
+
2005
+ const route = buildSmartWorkRoute(cwd, taskText, { debug: wantDebug });
2006
+ writeSmartWorkRouteReceipt(cwd, route);
2007
+
2008
+ if (route.workerHandoff) {
2009
+ writeWorkerHandoffReceipt(cwd, route.workerHandoff);
2010
+ }
2011
+
2012
+ try {
2013
+ appendProductLearningEvent(cwd, {
2014
+ eventName: "smart_work_route_built",
2015
+ category: "smart_work_routing",
2016
+ surface: "local",
2017
+ status: "observed",
2018
+ payload: {
2019
+ routingId: route.routingId,
2020
+ decision: route.decision,
2021
+ pathType: route.executionPath && route.executionPath.pathType,
2022
+ taskType: route.task && route.task.taskType,
2023
+ riskLevel: route.task && route.task.riskLevel,
2024
+ sameSurfacePreferred: route.executionPath && route.executionPath.sameSurfacePreferred,
2025
+ crossVendorAllowed: route.executionPath && route.executionPath.crossVendorAllowed,
2026
+ proofRequired: route.executionPath && route.executionPath.proofRequired,
2027
+ acpNeeded: route.protocolReadiness && route.protocolReadiness.acp && route.protocolReadiness.acp.neededNow,
2028
+ a2aNeeded: route.protocolReadiness && route.protocolReadiness.a2a && route.protocolReadiness.a2a.neededNow,
2029
+ },
2030
+ });
2031
+ appendProductLearningEvent(cwd, {
2032
+ eventName: "smart_route_execution_path_selected",
2033
+ category: "smart_work_routing",
2034
+ surface: "local",
2035
+ status: "observed",
2036
+ payload: {
2037
+ pathType: route.executionPath && route.executionPath.pathType,
2038
+ selectedWorker: route.executionPath && route.executionPath.selectedWorker,
2039
+ reasonCodes: route.executionPath && route.executionPath.reasonCodes,
2040
+ },
2041
+ });
2042
+ if (route.workerHandoff) {
2043
+ appendProductLearningEvent(cwd, {
2044
+ eventName: "worker_handoff_prepared",
2045
+ category: "smart_work_routing",
2046
+ surface: "local",
2047
+ status: "observed",
2048
+ payload: {
2049
+ handoffId: route.workerHandoff.handoffId,
2050
+ targetWorker: route.workerHandoff.targetWorker,
2051
+ sameSurfacePreferred: route.workerHandoff.sameSurfacePreferred,
2052
+ proofRequired: route.workerHandoff.proofRequired,
2053
+ },
2054
+ });
2055
+ }
2056
+ appendProductLearningEvent(cwd, {
2057
+ eventName: "protocol_readiness_evaluated",
2058
+ category: "smart_work_routing",
2059
+ surface: "local",
2060
+ status: "observed",
2061
+ payload: {
2062
+ acpNeeded: route.protocolReadiness && route.protocolReadiness.acp && route.protocolReadiness.acp.neededNow,
2063
+ a2aNeeded: route.protocolReadiness && route.protocolReadiness.a2a && route.protocolReadiness.a2a.neededNow,
2064
+ acpAdapterReady: false,
2065
+ a2aAdapterReady: false,
2066
+ },
2067
+ });
2068
+ if (route.executionPath && route.executionPath.sameSurfacePreferred) {
2069
+ appendProductLearningEvent(cwd, {
2070
+ eventName: "same_surface_preferred",
2071
+ category: "smart_work_routing",
2072
+ surface: "local",
2073
+ status: "observed",
2074
+ payload: { pathType: route.executionPath.pathType },
2075
+ });
2076
+ }
2077
+ if (route.executionPath && !route.executionPath.crossVendorAllowed) {
2078
+ appendProductLearningEvent(cwd, {
2079
+ eventName: "cross_vendor_blocked_by_default",
2080
+ category: "smart_work_routing",
2081
+ surface: "local",
2082
+ status: "observed",
2083
+ payload: { decision: route.decision },
2084
+ });
2085
+ }
2086
+ if (route.decision === "blocked" || route.decision === "approval_required") {
2087
+ appendProductLearningEvent(cwd, {
2088
+ eventName: "remote_agent_delegation_blocked",
2089
+ category: "smart_work_routing",
2090
+ surface: "local",
2091
+ status: "observed",
2092
+ payload: { decision: route.decision, interruptReason: route.executionPath && route.executionPath.interruptReason },
2093
+ });
2094
+ }
2095
+ appendProductLearningEvent(cwd, {
2096
+ eventName: "smart_route_receipt_written",
2097
+ category: "smart_work_routing",
2098
+ surface: "local",
2099
+ status: "observed",
2100
+ payload: { routingId: route.routingId },
2101
+ });
2102
+ } catch {
2103
+ // non-blocking
2104
+ }
2105
+
2106
+ if (wantJson) {
2107
+ const safe = {
2108
+ contract: route.contract,
2109
+ schemaVersion: route.schemaVersion,
2110
+ routingId: route.routingId,
2111
+ task: route.task,
2112
+ mode: route.mode,
2113
+ decision: route.decision,
2114
+ executionPath: route.executionPath,
2115
+ stages: route.stages,
2116
+ context: route.context,
2117
+ safety: route.safety,
2118
+ protocolReadiness: route.protocolReadiness,
2119
+ workerHandoff: route.workerHandoff
2120
+ ? {
2121
+ contract: route.workerHandoff.contract,
2122
+ handoffId: route.workerHandoff.handoffId,
2123
+ targetWorker: route.workerHandoff.targetWorker,
2124
+ targetSurface: route.workerHandoff.targetSurface,
2125
+ sameSurfacePreferred: route.workerHandoff.sameSurfacePreferred,
2126
+ taskGoal: route.workerHandoff.taskGoal,
2127
+ executionPacketRef: route.workerHandoff.executionPacketRef,
2128
+ allowedScopeSummary: route.workerHandoff.allowedScopeSummary,
2129
+ blockedScopeSummary: route.workerHandoff.blockedScopeSummary,
2130
+ proofRequired: route.workerHandoff.proofRequired,
2131
+ safeNextAction: route.workerHandoff.safeNextAction,
2132
+ continuation: route.workerHandoff.continuation,
2133
+ outputExpectations: route.workerHandoff.outputExpectations,
2134
+ redacted: true,
2135
+ }
2136
+ : null,
2137
+ proof: route.proof,
2138
+ valueEvidence: route.valueEvidence,
2139
+ receipts: route.receipts,
2140
+ redacted: true,
2141
+ };
2142
+ process.stdout.write(`${JSON.stringify(safe, null, 2)}\n`);
2143
+ return;
2144
+ }
2145
+
2146
+ process.stdout.write(formatSmartRouteText(route, { debug: wantDebug }) + "\n");
2147
+ }
2148
+
2149
+ function resolveWorkspaceOrExit(commandLabel) {
2150
+ const resolution = resolveWorkspace({
2151
+ cwd: process.cwd(),
2152
+ env: process.env,
2153
+ cliName: CLI_NAME,
2154
+ });
2155
+ if (!resolution.ok) {
2156
+ process.stderr.write(`[${CLI_NAME}] ${resolution.message}\n`);
2157
+ process.exit(1);
2158
+ }
2159
+ return resolution.workspace;
2160
+ }
2161
+
2162
+ function renderWorkspace(forwardedArgs = []) {
2163
+ const [subcommand = "show", ...subrest] = forwardedArgs;
2164
+ const wantJson = forwardedArgs.includes("--json");
2165
+
2166
+ if (subcommand === "show") {
2167
+ const result = resolveWorkspace({
2168
+ cwd: process.cwd(),
2169
+ env: process.env,
2170
+ cliName: CLI_NAME,
2171
+ });
2172
+ if (wantJson) {
2173
+ process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
2174
+ return;
2175
+ }
2176
+ process.stdout.write(`${formatWorkspaceShowText(result)}\n`);
2177
+ return;
2178
+ }
2179
+
2180
+ if (subcommand === "set") {
2181
+ const targetPath = subrest.filter((arg) => arg !== "--json").join(" ").trim();
2182
+ if (!targetPath) {
2183
+ process.stderr.write(`[${CLI_NAME}] Usage: ${CLI_NAME} workspace set <path>\n`);
2184
+ process.exit(1);
2185
+ }
2186
+ const result = registerWorkspace(targetPath, { env: process.env });
2187
+ if (!result.ok) {
2188
+ process.stderr.write(`[${CLI_NAME}] ${result.message}\n`);
2189
+ process.exit(1);
2190
+ }
2191
+ const payload = {
2192
+ ok: true,
2193
+ workspace: result.workspace,
2194
+ configPath: result.configPath,
2195
+ knownWorkspaces: result.config.knownWorkspaces,
2196
+ lastWorkspace: result.config.lastWorkspace,
2197
+ };
2198
+ if (wantJson) {
2199
+ process.stdout.write(`${JSON.stringify(payload, null, 2)}\n`);
2200
+ return;
2201
+ }
2202
+ process.stdout.write(
2203
+ [
2204
+ "Avorelo Workspace",
2205
+ `Workspace set: ${payload.workspace}`,
2206
+ `User config: ${payload.configPath}`,
2207
+ `Known workspaces: ${payload.knownWorkspaces.length}`,
2208
+ ].join("\n") + "\n"
2209
+ );
2210
+ return;
2211
+ }
2212
+
2213
+ if (subcommand === "clear") {
2214
+ const result = clearLastWorkspace({ env: process.env });
2215
+ const payload = {
2216
+ ok: true,
2217
+ configPath: result.configPath,
2218
+ lastWorkspace: result.config.lastWorkspace,
2219
+ knownWorkspaces: result.config.knownWorkspaces,
2220
+ };
2221
+ if (wantJson) {
2222
+ process.stdout.write(`${JSON.stringify(payload, null, 2)}\n`);
2223
+ return;
2224
+ }
2225
+ process.stdout.write(
2226
+ [
2227
+ "Avorelo Workspace",
2228
+ "Cleared lastWorkspace.",
2229
+ `Known workspaces retained: ${payload.knownWorkspaces.length}`,
2230
+ `User config: ${payload.configPath}`,
2231
+ ].join("\n") + "\n"
2232
+ );
2233
+ return;
2234
+ }
2235
+
2236
+ if (subcommand === "doctor") {
2237
+ const result = workspaceDoctor({
2238
+ cwd: process.cwd(),
2239
+ env: process.env,
2240
+ cliName: CLI_NAME,
2241
+ repoRoot: REPO_ROOT,
2242
+ });
2243
+ if (wantJson) {
2244
+ process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
2245
+ return;
2246
+ }
2247
+ process.stdout.write(`${formatWorkspaceDoctorText(result)}\n`);
2248
+ return;
2249
+ }
2250
+
2251
+ process.stderr.write(`[${CLI_NAME}] Unknown workspace command: ${subcommand}\n`);
2252
+ process.exit(1);
2253
+ }
2254
+
2255
+ // ── Hook Baseline / Lifecycle Automation Preview commands ─────────────────────
2256
+
2257
+ function renderHooksCommand(cwd, forwardedArgs = []) {
2258
+ const wantJson = forwardedArgs.includes("--json");
2259
+ const wantDebug = forwardedArgs.includes("--debug");
2260
+ const wantDryRun = forwardedArgs.includes("--dry-run");
2261
+ const wantYes = forwardedArgs.includes("--yes") || forwardedArgs.includes("--confirm");
2262
+ const subcommand = forwardedArgs.find((a) => !a.startsWith("-"));
2263
+
2264
+ if (subcommand === "preview") {
2265
+ const { buildHookConfigPreviewSurface, formatHookConfigPreviewText } = require("./hook-config-preview");
2266
+ const { preview } = buildHookConfigPreviewSurface(cwd, { debug: wantDebug });
2267
+ if (wantJson) {
2268
+ process.stdout.write(`${JSON.stringify(preview, null, 2)}\n`);
2269
+ return;
2270
+ }
2271
+ process.stdout.write(`${formatHookConfigPreviewText(preview, { debug: wantDebug })}\n`);
2272
+ return;
2273
+ }
2274
+
2275
+ if (subcommand === "apply") {
2276
+ const {
2277
+ buildHookApplyPlan,
2278
+ applyHookConfig,
2279
+ formatHookApplyText,
2280
+ } = require("./hook-apply");
2281
+ const options = { dryRun: wantDryRun || !wantYes, yes: wantYes, confirm: wantYes, debug: wantDebug };
2282
+ const plan = buildHookApplyPlan(cwd, options);
2283
+ if (wantDryRun || (!wantYes && !wantDebug)) {
2284
+ // Dry-run or no explicit approval: show plan only
2285
+ if (wantJson) {
2286
+ process.stdout.write(`${JSON.stringify(plan, null, 2)}\n`);
2287
+ return;
2288
+ }
2289
+ process.stdout.write(`${formatHookApplyText(plan, { debug: wantDebug })}\n`);
2290
+ return;
2291
+ }
2292
+ // Explicit apply
2293
+ const receipt = applyHookConfig(cwd, plan, options);
2294
+ if (wantJson) {
2295
+ process.stdout.write(`${JSON.stringify(receipt, null, 2)}\n`);
2296
+ return;
2297
+ }
2298
+ process.stdout.write(`${formatHookApplyText(receipt, { debug: wantDebug })}\n`);
2299
+ return;
2300
+ }
2301
+
2302
+ if (subcommand === "rollback") {
2303
+ const { rollbackHookApply, formatHookApplyText } = require("./hook-apply");
2304
+ const receipt = rollbackHookApply(cwd, { debug: wantDebug });
2305
+ if (wantJson) {
2306
+ process.stdout.write(`${JSON.stringify(receipt, null, 2)}\n`);
2307
+ return;
2308
+ }
2309
+ process.stdout.write(`${formatHookApplyText(receipt, { debug: wantDebug })}\n`);
2310
+ return;
2311
+ }
2312
+
2313
+ if (subcommand === "uninstall") {
2314
+ const { uninstallAvoreloHooks, formatHookApplyText } = require("./hook-apply");
2315
+ const options = { yes: wantYes, confirm: wantYes, debug: wantDebug };
2316
+ const receipt = uninstallAvoreloHooks(cwd, options);
2317
+ if (wantJson) {
2318
+ process.stdout.write(`${JSON.stringify(receipt, null, 2)}\n`);
2319
+ return;
2320
+ }
2321
+ process.stdout.write(`${formatHookApplyText(receipt, { debug: wantDebug })}\n`);
2322
+ return;
2323
+ }
2324
+
2325
+ if (subcommand === "doctor") {
2326
+ const { runHookDoctor, formatHookDoctorText } = require("./hook-apply");
2327
+ const receipt = runHookDoctor(cwd, { debug: wantDebug });
2328
+ if (wantJson) {
2329
+ process.stdout.write(`${JSON.stringify(receipt, null, 2)}\n`);
2330
+ return;
2331
+ }
2332
+ process.stdout.write(`${formatHookDoctorText(receipt, { debug: wantDebug })}\n`);
2333
+ return;
2334
+ }
2335
+
2336
+ const { buildHookBaselineSurface, formatHookBaselineText } = require("./hook-baseline");
2337
+ const { baseline } = buildHookBaselineSurface(cwd, { debug: wantDebug });
2338
+ if (wantJson) {
2339
+ process.stdout.write(`${JSON.stringify(baseline, null, 2)}\n`);
2340
+ return;
2341
+ }
2342
+ process.stdout.write(`${formatHookBaselineText(baseline, { debug: wantDebug })}\n`);
2343
+ }
2344
+
2345
+ function renderAdapterReadinessCommand(cwd, forwardedArgs = []) {
2346
+ const wantJson = forwardedArgs.includes("--json");
2347
+ const wantDebug = forwardedArgs.includes("--debug");
2348
+ const { buildAdapterReadinessSurface, formatAdapterReadinessText } = require("./adapter-readiness");
2349
+ const { readiness } = buildAdapterReadinessSurface(cwd, { debug: wantDebug });
2350
+ if (wantJson) {
2351
+ process.stdout.write(`${JSON.stringify(readiness, null, 2)}\n`);
2352
+ return;
2353
+ }
2354
+ process.stdout.write(`${formatAdapterReadinessText(readiness, { debug: wantDebug })}\n`);
2355
+ }
2356
+
2357
+ function renderLifecycleHookCommand(cwd, forwardedArgs = []) {
2358
+ const wantJson = forwardedArgs.includes("--json");
2359
+ const wantDebug = forwardedArgs.includes("--debug");
2360
+ const { handleLifecycleHook, formatLifecycleHookText } = require("./lifecycle-hooks");
2361
+
2362
+ // First non-flag arg is the event
2363
+ const event = forwardedArgs.find((a) => !a.startsWith("-"));
2364
+ if (!event) {
2365
+ const events = ["session-start", "user-prompt-submit", "pre-tool-use", "post-tool-use", "stop", "session-end"];
2366
+ process.stderr.write(`[avorelo] lifecycle-hook requires an event. Valid events: ${events.join(", ")}\n`);
2367
+ process.exit(1);
2368
+ }
2369
+
2370
+ // Try to read JSON input from remaining args
2371
+ let input = {};
2372
+ const inputFlagIdx = forwardedArgs.indexOf("--input");
2373
+ if (inputFlagIdx >= 0 && forwardedArgs[inputFlagIdx + 1]) {
2374
+ try {
2375
+ input = JSON.parse(forwardedArgs[inputFlagIdx + 1]);
2376
+ } catch { /* ignore */ }
2377
+ }
2378
+
2379
+ const result = handleLifecycleHook(cwd, event, input, { debug: wantDebug });
2380
+
2381
+ if (wantJson) {
2382
+ process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
2383
+ // Exit 1 if blocking hook blocked
2384
+ if (result.blocking && result.decision === "block") {
2385
+ process.exitCode = 1;
2386
+ }
2387
+ return;
2388
+ }
2389
+ process.stdout.write(`${formatLifecycleHookText(result, { debug: wantDebug })}\n`);
2390
+ if (result.blocking && result.decision === "block") {
2391
+ process.exitCode = 1;
2392
+ }
2393
+ }
2394
+
2395
+ async function runVerify(inputFile) {
2396
+ if (!inputFile) {
2397
+ console.error(`[${CLI_NAME}] No input file provided`);
2398
+ console.error(`Usage: ${CLI_NAME} verify <file>`);
2399
+ process.exit(1);
2400
+ }
2401
+ if (!fs.existsSync(inputFile)) {
2402
+ console.error(`[${CLI_NAME}] File not found: ${inputFile}`);
2403
+ process.exit(1);
2404
+ }
2405
+ const input = fs.readFileSync(inputFile, "utf8");
2406
+ const Verifier = require("../../src/verify/verifier.js").Verifier;
2407
+ const verifier = new Verifier();
2408
+ const result = await verifier.verify({
2409
+ environment: "local",
2410
+ executionMode: "safe_interaction",
2411
+ depth: "standard",
2412
+ input,
2413
+ policyConfig: {},
2414
+ });
2415
+ console.log(JSON.stringify({
2416
+ product: PRODUCT_NAME,
2417
+ sessionId: getCanonicalSessionId(process.cwd()),
2418
+ verdict: result.verdict,
2419
+ policyOutcome: result.policyOutcome,
2420
+ riskScore: result.riskScore,
2421
+ executionTimeMs: result.executionTimeMs,
2422
+ findings: result.findings,
2423
+ evidencePath: result.evidencePath,
2424
+ }, null, 2));
2425
+ process.exit(result.verdict === "fail" || result.verdict === "error" ? 1 : 0);
2426
+ }
2427
+
2428
+ function renderArtifactsCommand(cwd, forwardedArgs = []) {
2429
+ const wantJson = forwardedArgs.includes("--json");
2430
+ const wantDebug = forwardedArgs.includes("--debug");
2431
+ const wantYes = forwardedArgs.includes("--yes");
2432
+ const subcommand = forwardedArgs.find((a) => !a.startsWith("-")) || "health";
2433
+
2434
+ const {
2435
+ scanArtifactHealth,
2436
+ writeArtifactHealthReceipt,
2437
+ buildArtifactCleanupPlan,
2438
+ applyArtifactCleanup,
2439
+ writeArtifactCleanupReceipt,
2440
+ formatArtifactHealthText,
2441
+ formatArtifactCleanupText,
2442
+ } = require("./artifact-health");
2443
+
2444
+ if (subcommand === "cleanup") {
2445
+ const health = scanArtifactHealth(cwd, { debug: wantDebug });
2446
+ const plan = buildArtifactCleanupPlan(cwd, health, { dryRun: !wantYes });
2447
+ if (wantYes) {
2448
+ const receipt = applyArtifactCleanup(cwd, plan, { yes: true, dryRun: false });
2449
+ writeArtifactCleanupReceipt(cwd, receipt);
2450
+ if (wantJson) {
2451
+ process.stdout.write(`${JSON.stringify(receipt, null, 2)}\n`);
2452
+ return;
2453
+ }
2454
+ process.stdout.write(`${formatArtifactCleanupText(receipt, { debug: wantDebug })}\n`);
2455
+ return;
2456
+ }
2457
+ // Default: dry-run plan
2458
+ if (wantJson) {
2459
+ process.stdout.write(`${JSON.stringify(plan, null, 2)}\n`);
2460
+ return;
2461
+ }
2462
+ process.stdout.write(`${formatArtifactCleanupText(plan, { debug: wantDebug })}\n`);
2463
+ return;
2464
+ }
2465
+
2466
+ // Default: health
2467
+ const health = scanArtifactHealth(cwd, { debug: wantDebug });
2468
+ writeArtifactHealthReceipt(cwd, health);
2469
+ if (wantJson) {
2470
+ process.stdout.write(`${JSON.stringify(health, null, 2)}\n`);
2471
+ return;
2472
+ }
2473
+ process.stdout.write(`${formatArtifactHealthText(health, { debug: wantDebug })}\n`);
2474
+ }
2475
+
2476
+ function renderLaunchHardening(cwd, forwardedArgs = []) {
2477
+ const wantJson = forwardedArgs.includes("--json");
2478
+ const {
2479
+ runLaunchHardeningGate,
2480
+ writeLaunchHardeningGate,
2481
+ formatLaunchHardeningText,
2482
+ } = require("./launch-hardening-gate");
2483
+ const gate = runLaunchHardeningGate(cwd, {});
2484
+ writeLaunchHardeningGate(cwd, gate);
2485
+ if (wantJson) {
2486
+ process.stdout.write(`${JSON.stringify(gate, null, 2)}\n`);
2487
+ return;
2488
+ }
2489
+ process.stdout.write(`${formatLaunchHardeningText(gate)}\n`);
2490
+ }
2491
+
2492
+ function renderInstallAi(cwd, forwardedArgs = []) {
2493
+ const wantJson = forwardedArgs.includes("--json");
2494
+ const wantPrompt = forwardedArgs.includes("--prompt");
2495
+ const wantDryRun = forwardedArgs.includes("--dry-run");
2496
+ const {
2497
+ buildAiInstallPrompt,
2498
+ writeAiInstallPromptReceipt,
2499
+ formatAiInstallPromptText,
2500
+ } = require("./ai-install-prompt");
2501
+ const receipt = buildAiInstallPrompt(cwd, {});
2502
+ if (!wantDryRun) {
2503
+ writeAiInstallPromptReceipt(cwd, receipt);
2504
+ }
2505
+ if (wantJson) {
2506
+ process.stdout.write(`${JSON.stringify(receipt, null, 2)}\n`);
2507
+ return;
2508
+ }
2509
+ if (wantPrompt) {
2510
+ process.stdout.write(`${receipt.promptText}\n`);
2511
+ return;
2512
+ }
2513
+ process.stdout.write(`${formatAiInstallPromptText(receipt)}\n`);
2514
+ }
2515
+
2516
+ function renderPrelaunchReadiness(cwd, forwardedArgs = []) {
2517
+ const wantJson = forwardedArgs.includes("--json");
2518
+ const wantDebug = forwardedArgs.includes("--debug");
2519
+ const {
2520
+ runPrelaunchActivationReadiness,
2521
+ writePrelaunchActivationReadiness,
2522
+ formatPrelaunchActivationText,
2523
+ } = require("./prelaunch-activation-readiness");
2524
+ const gate = runPrelaunchActivationReadiness(cwd, { debug: wantDebug });
2525
+ writePrelaunchActivationReadiness(cwd, gate);
2526
+ if (wantJson) {
2527
+ process.stdout.write(`${JSON.stringify(gate, null, 2)}\n`);
2528
+ return;
2529
+ }
2530
+ process.stdout.write(`${formatPrelaunchActivationText(gate, { debug: wantDebug })}\n`);
2531
+ }
2532
+
2533
+ function renderFirstValueCheck(cwd, forwardedArgs = []) {
2534
+ const wantJson = forwardedArgs.includes("--json");
2535
+ const {
2536
+ runPrelaunchActivationReadiness,
2537
+ buildFirstValueJourney,
2538
+ } = require("./prelaunch-activation-readiness");
2539
+ const gate = runPrelaunchActivationReadiness(cwd, {});
2540
+ const journey = buildFirstValueJourney(cwd, {});
2541
+ const result = {
2542
+ contract: "avorelo.firstValueCheck.v1",
2543
+ status: gate.status,
2544
+ score: gate.score,
2545
+ firstValueJourney: journey,
2546
+ nextAction: gate.nextAction,
2547
+ noPublicLaunchClaim: true,
2548
+ redacted: true,
2549
+ };
2550
+ if (wantJson) {
2551
+ process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
2552
+ return;
2553
+ }
2554
+ const lines = [
2555
+ `First-Value Check: ${result.status}`,
2556
+ ``,
2557
+ `Journey steps:`,
2558
+ ...journey.steps.map((s) => ` ${s.step}. ${s.label}`),
2559
+ ` Command: ${s => s.command}`,
2560
+ ``,
2561
+ `Next: ${result.nextAction}`,
2562
+ ``,
2563
+ `Note: Pre-launch activation readiness only. Not a public launch claim.`,
2564
+ ];
2565
+ // rebuild cleanly
2566
+ const textLines = [
2567
+ `First-Value Check: ${result.status}`,
2568
+ ``,
2569
+ `Journey steps:`,
2570
+ ...journey.steps.map((s) => ` ${s.step}. ${s.label}`),
2571
+ ``,
2572
+ `Next: ${result.nextAction}`,
2573
+ ``,
2574
+ `Note: Pre-launch activation readiness only. Not a public launch claim.`,
2575
+ ];
2576
+ process.stdout.write(`${textLines.join("\n")}\n`);
2577
+ }
2578
+
2579
+ async function main(argv = process.argv.slice(2)) {
2580
+ const [command, ...rest] = argv;
2581
+
2582
+ if (!command || command === "--help" || command === "help") {
2583
+ printHelp();
2584
+ return;
2585
+ }
2586
+
2587
+ if (command === "status") {
2588
+ if (rest.includes("--help")) {
2589
+ printStatusHelp();
2590
+ return;
2591
+ }
2592
+ renderStatus(resolveWorkspaceOrExit("status"), rest.length ? rest : ["--text"]);
2593
+ return;
2594
+ }
2595
+
2596
+ if (command === "route") {
2597
+ process.stdout.write(`${renderRouteCommand(resolveWorkspaceOrExit("route"), rest)}\n`);
2598
+ return;
2599
+ }
2600
+
2601
+ if (command === "run" || command === "execute") {
2602
+ process.stdout.write(`${renderRunCommand(resolveWorkspaceOrExit("run"), rest)}\n`);
2603
+ return;
2604
+ }
2605
+
2606
+ if (command === "models") {
2607
+ process.stdout.write(`${renderModelsCommand(resolveWorkspaceOrExit("models"), rest)}\n`);
2608
+ return;
2609
+ }
2610
+
2611
+ if (command === "dashboard") {
2612
+ if (rest.includes("--help")) {
2613
+ printDashboardHelp();
2614
+ return;
2615
+ }
2616
+ renderDashboard(resolveWorkspaceOrExit("dashboard"), rest);
2617
+ return;
2618
+ }
2619
+
2620
+ if (command === "audit") {
2621
+ runNodeScript("scripts/cco-audit.js", rest, { cwd: resolveWorkspaceOrExit("audit") });
2622
+ return;
2623
+ }
2624
+
2625
+ if (command === "settings") {
2626
+ runNodeScript("scripts/cco-settings.js", rest, { cwd: resolveWorkspaceOrExit("settings") });
2627
+ return;
2628
+ }
2629
+
2630
+ if (command === "orchestration") {
2631
+ const cwd = resolveWorkspaceOrExit("orchestration");
2632
+ const [subcommand, ...subrest] = rest;
2633
+ if (!subcommand || subcommand === "status") {
2634
+ process.stdout.write(`${renderOrchestrationStatusCommand(cwd, subrest)}\n`);
2635
+ return;
2636
+ }
2637
+ if (subcommand === "settings") {
2638
+ process.stdout.write(`${renderOrchestrationSettingsCommand(cwd, subrest)}\n`);
2639
+ return;
2640
+ }
2641
+ if (subcommand === "handoff") {
2642
+ process.stdout.write(`${renderHandoffCommand(cwd, subrest)}\n`);
2643
+ return;
2644
+ }
2645
+ if (subcommand === "surface") {
2646
+ process.stdout.write(`${renderOrchestrationSurfaceCommand(cwd, subrest)}\n`);
2647
+ return;
2648
+ }
2649
+ console.error(`[${CLI_NAME}] Unknown orchestration command: ${subcommand}`);
2650
+ process.exit(1);
2651
+ }
2652
+
2653
+ if (command === "handoff") {
2654
+ process.stdout.write(`${renderHandoffCommand(resolveWorkspaceOrExit("handoff"), rest)}\n`);
2655
+ return;
2656
+ }
2657
+
2658
+ if (command === "panel") {
2659
+ runNodeScript("scripts/cco-panel.js", rest, { cwd: resolveWorkspaceOrExit("panel") });
2660
+ return;
2661
+ }
2662
+
2663
+ if (command === "activate") {
2664
+ renderActivation(rest);
2665
+ return;
2666
+ }
2667
+
2668
+ if (command === "first-value" || command === "first_value") {
2669
+ renderFirstValue(resolveWorkspaceOrExit("first-value"), rest);
2670
+ return;
2671
+ }
2672
+
2673
+ if (command === "alpha-readiness" || command === "alpha-readiness-gate") {
2674
+ renderAlphaReadinessGate(resolveWorkspaceOrExit(command), rest);
2675
+ return;
2676
+ }
2677
+
2678
+ if (command === "feedback" && rest[0] === "insights") {
2679
+ renderFeedbackInsights(resolveWorkspaceOrExit(command), rest.slice(1));
2680
+ return;
2681
+ }
2682
+
2683
+ if (command === "feedback") {
2684
+ renderFeedbackCommand(resolveWorkspaceOrExit("feedback"), rest);
2685
+ return;
2686
+ }
2687
+
2688
+ if (command === "support-bundle" || command === "support_bundle") {
2689
+ renderSupportBundle(resolveWorkspaceOrExit("support-bundle"), rest);
2690
+ return;
2691
+ }
2692
+
2693
+ if (command === "token-efficiency" || command === "token-evidence" || command === "token_efficiency") {
2694
+ renderTokenEfficiency(resolveWorkspaceOrExit("token-efficiency"), rest);
2695
+ return;
2696
+ }
2697
+
2698
+ if (command === "repo-map" || command === "repo_map") {
2699
+ renderRepoMap(resolveWorkspaceOrExit("repo-map"), rest);
2700
+ return;
2701
+ }
2702
+
2703
+ if (command === "context-plan" || command === "context_plan") {
2704
+ renderContextPlan(resolveWorkspaceOrExit("context-plan"), rest);
2705
+ return;
2706
+ }
2707
+
2708
+ if (command === "cache-readiness" || command === "cache_readiness") {
2709
+ renderCacheReadiness(resolveWorkspaceOrExit("cache-readiness"), rest);
2710
+ return;
2711
+ }
2712
+
2713
+ if (command === "doctor") {
2714
+ if (rest.includes("--orchestration")) {
2715
+ process.stdout.write(`${renderOrchestrationStatusCommand(resolveWorkspaceOrExit("doctor"), rest.includes("--deep") ? ["--refresh", "--deep"] : [])}\n`);
2716
+ return;
2717
+ }
2718
+ renderDoctor(resolveWorkspaceOrExit("doctor"), rest);
2719
+ return;
2720
+ }
2721
+
2722
+ if (command === "summary") {
2723
+ runNodeScript("scripts/wuz-post-run.js", rest, { cwd: resolveWorkspaceOrExit("summary") });
2724
+ return;
2725
+ }
2726
+
2727
+ if (command === "prompt") {
2728
+ renderPrompt(resolveWorkspaceOrExit("prompt"), rest);
2729
+ return;
2730
+ }
2731
+
2732
+ if (command === "visual-qa") {
2733
+ renderVisualQa(resolveWorkspaceOrExit("visual-qa"), rest);
2734
+ return;
2735
+ }
2736
+
2737
+ if (command === "capabilities" || command === "packs") {
2738
+ renderCapabilities(resolveWorkspaceOrExit("capabilities"), rest);
2739
+ return;
2740
+ }
2741
+
2742
+ if (command === "guard") {
2743
+ renderGuard(resolveWorkspaceOrExit("guard"), rest);
2744
+ return;
2745
+ }
2746
+
2747
+ if (command === "init") {
2748
+ if (rest.includes("--print")) {
2749
+ process.stdout.write(`${PUBLIC_INIT_COMMAND}\n`);
2750
+ return;
2751
+ }
2752
+ runNodeScript("scripts/cco-init.js", rest, { cwd: resolveWorkspaceOrExit("init") });
2753
+ return;
2754
+ }
2755
+
2756
+ if (command === "verify") {
2757
+ if (rest[0] && fs.existsSync(rest[0])) {
2758
+ await runVerify(rest[0]);
2759
+ return;
2760
+ }
2761
+ process.stdout.write(`${renderOrchestrationVerifyCommand(resolveWorkspaceOrExit("verify"), rest)}\n`);
2762
+ return;
2763
+ }
2764
+
2765
+ if (command === "proof") {
2766
+ process.stdout.write(`${renderProofCommand(resolveWorkspaceOrExit("proof"), rest)}\n`);
2767
+ return;
2768
+ }
2769
+
2770
+ if (command === "intake" || command === "install-intake") {
2771
+ renderIntake(resolveWorkspaceOrExit("intake"), rest);
2772
+ return;
2773
+ }
2774
+
2775
+ if (command === "work-control" || command === "receipt") {
2776
+ renderWorkControl(resolveWorkspaceOrExit("work-control"), rest);
2777
+ return;
2778
+ }
2779
+
2780
+ if (command === "brain-pack" || command === "brain_pack") {
2781
+ renderBrainPack(resolveWorkspaceOrExit("brain-pack"), rest);
2782
+ return;
2783
+ }
2784
+
2785
+ if (command === "session-context" || command === "session-start") {
2786
+ renderSessionContext(resolveWorkspaceOrExit("session-context"), rest);
2787
+ return;
2788
+ }
2789
+
2790
+ if (command === "workspace-map") {
2791
+ renderWorkspaceMap(resolveWorkspaceOrExit("workspace-map"), rest);
2792
+ return;
2793
+ }
2794
+
2795
+ if (command === "workspace-registry" || command === "assets" || command === "registry") {
2796
+ renderWorkspaceRegistry(resolveWorkspaceOrExit("workspace-registry"), rest);
2797
+ return;
2798
+ }
2799
+
2800
+ if (command === "workspace-hygiene" || command === "hygiene" || command === "ai-workspace") {
2801
+ renderWorkspaceHygiene(resolveWorkspaceOrExit("workspace-hygiene"), rest);
2802
+ return;
2803
+ }
2804
+
2805
+ if (command === "skills") {
2806
+ runNodeScript("scripts/avorelo-skills.js", rest, { cwd: resolveWorkspaceOrExit("skills") });
2807
+ return;
2808
+ }
2809
+
2810
+ if (command === "workspace") {
2811
+ renderWorkspace(rest);
2812
+ return;
2813
+ }
2814
+
2815
+ if (command === "operating-value" || command === "value" || command === "savings") {
2816
+ renderOperatingValue(resolveWorkspaceOrExit("operating-value"), rest);
2817
+ return;
2818
+ }
2819
+
2820
+ if (command === "pricing") {
2821
+ renderPricing(resolveWorkspaceOrExit("pricing"), rest);
2822
+ return;
2823
+ }
2824
+
2825
+ if (command === "token-evidence") {
2826
+ renderTokenEvidence(resolveWorkspaceOrExit("token-evidence"), rest);
2827
+ return;
2828
+ }
2829
+
2830
+ if (command === "session-timing") {
2831
+ renderSessionTiming(resolveWorkspaceOrExit("session-timing"), rest);
2832
+ return;
2833
+ }
2834
+
2835
+ if (command === "cost-evidence") {
2836
+ renderCostEvidence(resolveWorkspaceOrExit("cost-evidence"), rest);
2837
+ return;
2838
+ }
2839
+
2840
+ if (command === "context" || command === "context-pack") {
2841
+ renderContextPack(resolveWorkspaceOrExit("context"), rest);
2842
+ return;
2843
+ }
2844
+
2845
+ if (command === "readiness" || command === "install-check") {
2846
+ renderLaunchReadiness(resolveWorkspaceOrExit(command), rest);
2847
+ return;
2848
+ }
2849
+
2850
+ if (command === "outcome" || command === "reality-gate") {
2851
+ renderOutcome(resolveWorkspaceOrExit(command), rest);
2852
+ return;
2853
+ }
2854
+
2855
+ if (command === "orchestrate" || command === "work-plan" || command === "plan-work") {
2856
+ renderOrchestrate(resolveWorkspaceOrExit(command), rest);
2857
+ return;
2858
+ }
2859
+
2860
+ if (command === "ledger" || command === "work-ledger") {
2861
+ renderLedger(resolveWorkspaceOrExit(command), rest);
2862
+ return;
2863
+ }
2864
+
2865
+ if (command === "company-loop" || command === "loop" || command === "learn") {
2866
+ renderCompanyLoop(resolveWorkspaceOrExit(command), rest);
2867
+ return;
2868
+ }
2869
+
2870
+ if (command === "project-profile" || command === "profile") {
2871
+ renderProjectProfile(resolveWorkspaceOrExit(command), rest);
2872
+ return;
2873
+ }
2874
+
2875
+ if (command === "execution-packet" || command === "packet") {
2876
+ renderExecutionPacket(resolveWorkspaceOrExit(command), rest);
2877
+ return;
2878
+ }
2879
+
2880
+ if (command === "work-panel" || command === "panel-preview") {
2881
+ renderWorkPanel(resolveWorkspaceOrExit(command), rest);
2882
+ return;
2883
+ }
2884
+
2885
+ if (command === "smart-route" || command === "work-route") {
2886
+ renderSmartRoute(resolveWorkspaceOrExit(command), rest);
2887
+ return;
2888
+ }
2889
+
2890
+ if (command === "hooks" || command === "hook-baseline" || command === "hook-readiness" || command === "hook-preview") {
2891
+ const cwd = resolveWorkspaceOrExit(command);
2892
+ // hook-preview is an alias for hooks preview
2893
+ if (command === "hook-preview") {
2894
+ renderHooksCommand(cwd, ["preview", ...rest]);
2895
+ } else {
2896
+ renderHooksCommand(cwd, rest);
2897
+ }
2898
+ return;
2899
+ }
2900
+
2901
+ if (command === "adapter-readiness") {
2902
+ renderAdapterReadinessCommand(resolveWorkspaceOrExit(command), rest);
2903
+ return;
2904
+ }
2905
+
2906
+ if (command === "lifecycle-hook") {
2907
+ renderLifecycleHookCommand(resolveWorkspaceOrExit(command), rest);
2908
+ return;
2909
+ }
2910
+
2911
+ if (command === "worker-handoff") {
2912
+ const cwd = resolveWorkspaceOrExit(command);
2913
+ const wantJson = rest.includes("--json");
2914
+ const { buildSmartRouteSurface } = require("./smart-work-routing");
2915
+ const surface = buildSmartRouteSurface(cwd);
2916
+ const fs2 = require("fs");
2917
+ const path2 = require("path");
2918
+ const handoffPath = path2.join(cwd, surface.latestHandoffPath || ".claude/cco/orchestration/worker-handoff/latest-handoff.json");
2919
+ if (fs2.existsSync(handoffPath)) {
2920
+ try {
2921
+ const data = JSON.parse(fs2.readFileSync(handoffPath, "utf8"));
2922
+ process.stdout.write(`${wantJson ? JSON.stringify(data, null, 2) : `Worker handoff: ${data.handoffId || "available"}\nTarget: ${data.targetWorker || "unknown"}\nNext: ${data.safeNextAction || "Review handoff receipt."}`}\n`);
2923
+ } catch {
2924
+ process.stdout.write("Worker handoff receipt unavailable. Run avorelo smart-route \"<task>\" first.\n");
2925
+ }
2926
+ } else {
2927
+ process.stdout.write("No worker handoff receipt found. Run avorelo smart-route \"<task>\" first.\n");
2928
+ }
2929
+ return;
2930
+ }
2931
+
2932
+ if (command === "artifacts") {
2933
+ renderArtifactsCommand(resolveWorkspaceOrExit(command), rest);
2934
+ return;
2935
+ }
2936
+
2937
+ if (command === "launch-hardening" || command === "launch_hardening") {
2938
+ renderLaunchHardening(resolveWorkspaceOrExit(command), rest);
2939
+ return;
2940
+ }
2941
+
2942
+ if (command === "install-ai" || command === "ai-install" || command === "install-prompt") {
2943
+ renderInstallAi(resolveWorkspaceOrExit(command), rest);
2944
+ return;
2945
+ }
2946
+
2947
+ if (command === "prelaunch-readiness" || command === "prelaunch_readiness") {
2948
+ renderPrelaunchReadiness(resolveWorkspaceOrExit(command), rest);
2949
+ return;
2950
+ }
2951
+
2952
+ if (command === "first-value-check" || command === "first_value_check") {
2953
+ renderFirstValueCheck(resolveWorkspaceOrExit(command), rest);
2954
+ return;
2955
+ }
2956
+
2957
+ if (command === "prelaunch-intelligence" || command === "intelligence") {
2958
+ renderPrelaunchIntelligence(resolveWorkspaceOrExit(command), rest);
2959
+ return;
2960
+ }
2961
+
2962
+ if (command === "token-cost" || command === "cost-intelligence") {
2963
+ renderTokenCostIntelligence(resolveWorkspaceOrExit(command), rest);
2964
+ return;
2965
+ }
2966
+
2967
+ if (command === "install-journey") {
2968
+ renderInstallJourneyIntelligence(resolveWorkspaceOrExit(command), rest);
2969
+ return;
2970
+ }
2971
+
2972
+ if (command === "mcp" || command === "tools") {
2973
+ renderMcpCommand(resolveWorkspaceOrExit(command), rest);
2974
+ return;
2975
+ }
2976
+
2977
+ if (command === "full-readiness" || command === "rc-gate") {
2978
+ renderFullReadiness(resolveWorkspaceOrExit(command), rest);
2979
+ return;
2980
+ }
2981
+ if (command === "readiness-delta") {
2982
+ renderReadinessDelta(resolveWorkspaceOrExit(command), rest);
2983
+ return;
2984
+ }
2985
+ if (command === "readiness-closure") {
2986
+ renderReadinessClosure(resolveWorkspaceOrExit(command), rest);
2987
+ return;
2988
+ }
2989
+ if (command === "known-limitations") {
2990
+ renderKnownLimitations(resolveWorkspaceOrExit(command), rest);
2991
+ return;
2992
+ }
2993
+ if (command === "external-user-sim") {
2994
+ renderExternalUserSim(resolveWorkspaceOrExit(command), rest);
2995
+ return;
2996
+ }
2997
+ if (command === "release-candidate-bundle") {
2998
+ renderReleaseCandidateBundle(resolveWorkspaceOrExit(command), rest);
2999
+ return;
3000
+ }
3001
+
3002
+ if (command === "activation-distribution" || command === "readiness-activation") {
3003
+ renderActivationDistributionReadiness(resolveWorkspaceOrExit(command), rest);
3004
+ return;
3005
+ }
3006
+
3007
+ if (command === "public-distribution" || command === "distribution-truth") {
3008
+ renderPublicDistribution(resolveWorkspaceOrExit(command), rest);
3009
+ return;
3010
+ }
3011
+
3012
+ if (command === "package-audit" || command === "npm-readiness") {
3013
+ renderPackageAudit(resolveWorkspaceOrExit(command), rest);
3014
+ return;
3015
+ }
3016
+
3017
+ if (command === "package-smoke") {
3018
+ renderPackageSmoke(resolveWorkspaceOrExit(command), rest);
3019
+ return;
3020
+ }
3021
+
3022
+ if (command === "install-claims") {
3023
+ renderInstallClaims(resolveWorkspaceOrExit(command), rest);
3024
+ return;
3025
+ }
3026
+
3027
+ if (command === "publish-readiness") {
3028
+ renderPublishReadiness(resolveWorkspaceOrExit(command), rest);
3029
+ return;
3030
+ }
3031
+
3032
+ if (command === "host-matrix") {
3033
+ renderHostMatrix(resolveWorkspaceOrExit(command), rest);
3034
+ return;
3035
+ }
3036
+
3037
+ if (command === "cross-host-install") {
3038
+ renderCrossHostInstall(resolveWorkspaceOrExit(command), rest);
3039
+ return;
3040
+ }
3041
+
3042
+ if (command === "cross-host-value") {
3043
+ renderCrossHostValue(resolveWorkspaceOrExit(command), rest);
3044
+ return;
3045
+ }
3046
+
3047
+ if (command === "adapter-safety") {
3048
+ renderAdapterSafety(resolveWorkspaceOrExit(command), rest);
3049
+ return;
3050
+ }
3051
+
3052
+ if (command === "host-support") {
3053
+ renderHostSupport(resolveWorkspaceOrExit(command), rest);
3054
+ return;
3055
+ }
3056
+
3057
+ if (command === "browser-preflight") {
3058
+ renderBrowserPreflight(resolveWorkspaceOrExit(command), rest);
3059
+ return;
3060
+ }
3061
+
3062
+ if (command === "adapter-readiness-technical") {
3063
+ renderAdapterTechnicalReadiness(resolveWorkspaceOrExit(command), rest);
3064
+ return;
3065
+ }
3066
+
3067
+ // ── adapter <subcommand> — unified adapter/host routing (PR #163) ─────────
3068
+ if (command === "adapter" || command === "hosts" || command === "adapters") {
3069
+ const sub = rest[0] || "";
3070
+ const subRest = rest.slice(1);
3071
+ const cwd = resolveWorkspaceOrExit(command);
3072
+ if (sub === "matrix" || sub === "host-matrix") {
3073
+ renderHostMatrix(cwd, subRest);
3074
+ } else if (sub === "readiness") {
3075
+ renderAdapterReadinessCommand(cwd, subRest);
3076
+ } else if (sub === "technical" || sub === "readiness-technical") {
3077
+ renderAdapterTechnicalReadiness(cwd, subRest);
3078
+ } else if (sub === "install-plan") {
3079
+ renderCrossHostInstallPlan(cwd, subRest);
3080
+ } else if (sub === "install") {
3081
+ renderCrossHostInstall(cwd, subRest);
3082
+ } else if (sub === "value-flow" || sub === "value") {
3083
+ renderCrossHostValue(cwd, subRest);
3084
+ } else if (sub === "safety") {
3085
+ renderAdapterSafety(cwd, subRest);
3086
+ } else if (sub === "support" || sub === "host-support") {
3087
+ renderHostSupport(cwd, subRest);
3088
+ } else if (sub === "browser-preflight" || sub === "preflight") {
3089
+ renderBrowserPreflight(cwd, subRest);
3090
+ } else {
3091
+ // Default: show adapter readiness
3092
+ renderAdapterReadinessCommand(cwd, rest);
3093
+ }
3094
+ return;
3095
+ }
3096
+
3097
+ // ── run-improvements — next-run preparation based on last-run evidence ──
3098
+ if (command === "run-improvements" || command === "next-run-prep") {
3099
+ renderRunImprovements(resolveWorkspaceOrExit(command), rest);
3100
+ return;
3101
+ }
3102
+
3103
+ // ── learning — evidence-backed learning memory ──────────────────────────
3104
+ if (command === "learning") {
3105
+ renderLearning(resolveWorkspaceOrExit(command), rest);
3106
+ return;
3107
+ }
3108
+
3109
+ // ── browser-proof <subcommand> — browser proof preflight alias (PR #163) ──
3110
+ if (command === "browser-proof") {
3111
+ const sub = rest[0] || "";
3112
+ const subRest = rest.slice(1);
3113
+ const cwd = resolveWorkspaceOrExit(command);
3114
+ if (sub === "preflight") {
3115
+ renderBrowserPreflight(cwd, subRest);
3116
+ } else {
3117
+ renderBrowserPreflight(cwd, rest);
3118
+ }
3119
+ return;
3120
+ }
3121
+
3122
+ console.error(`[${CLI_NAME}] Unknown command: ${command}`);
3123
+ console.error(`Run ${CLI_NAME} --help to see the supported commands.`);
3124
+ process.exit(1);
3125
+ }
3126
+
3127
+ // ── Pre-Launch Intelligence CLI (PR #147) ─────────────────────────────────────
3128
+
3129
+ function renderPrelaunchIntelligence(cwd, forwardedArgs = []) {
3130
+ const wantJson = forwardedArgs.includes("--json");
3131
+ const wantDebug = forwardedArgs.includes("--debug");
3132
+ const refresh = forwardedArgs.includes("--refresh");
3133
+
3134
+ const {
3135
+ buildPrelaunchIntelligence,
3136
+ writePrelaunchIntelligence,
3137
+ formatPrelaunchIntelligenceText,
3138
+ } = require("./prelaunch-intelligence");
3139
+ const { appendProductLearningEvent } = require("./product-learning-events");
3140
+
3141
+ const intel = buildPrelaunchIntelligence(cwd, { refresh });
3142
+ writePrelaunchIntelligence(cwd, intel);
3143
+
3144
+ try {
3145
+ appendProductLearningEvent(cwd, {
3146
+ eventName: "prelaunch_intelligence_run",
3147
+ category: "prelaunch_intelligence",
3148
+ status: intel.status,
3149
+ score: intel.score,
3150
+ });
3151
+ } catch {}
3152
+
3153
+ if (wantJson) {
3154
+ process.stdout.write(`${JSON.stringify(intel, null, 2)}\n`);
3155
+ return;
3156
+ }
3157
+ process.stdout.write(formatPrelaunchIntelligenceText(intel, { debug: wantDebug }) + "\n");
3158
+ }
3159
+
3160
+ function renderFeedbackInsights(cwd, forwardedArgs = []) {
3161
+ const wantJson = forwardedArgs.includes("--json");
3162
+ const wantDebug = forwardedArgs.includes("--debug");
3163
+
3164
+ const {
3165
+ buildFeedbackIntelligence,
3166
+ writeFeedbackIntelligence,
3167
+ formatFeedbackIntelligenceText,
3168
+ } = require("./feedback-intelligence");
3169
+ const { appendProductLearningEvent } = require("./product-learning-events");
3170
+
3171
+ const intel = buildFeedbackIntelligence(cwd);
3172
+ writeFeedbackIntelligence(cwd, intel);
3173
+
3174
+ try {
3175
+ appendProductLearningEvent(cwd, {
3176
+ eventName: "feedback_intelligence_built",
3177
+ category: "prelaunch_intelligence",
3178
+ status: intel.status,
3179
+ topFriction: intel.topFriction,
3180
+ });
3181
+ } catch {}
3182
+
3183
+ if (wantJson) {
3184
+ process.stdout.write(`${JSON.stringify(intel, null, 2)}\n`);
3185
+ return;
3186
+ }
3187
+ process.stdout.write(formatFeedbackIntelligenceText(intel, { debug: wantDebug }) + "\n");
3188
+ }
3189
+
3190
+ function renderTokenCostIntelligence(cwd, forwardedArgs = []) {
3191
+ const subcommand = forwardedArgs.find((a) => !a.startsWith("-")) || null;
3192
+ const wantJson = forwardedArgs.includes("--json");
3193
+ const wantDebug = forwardedArgs.includes("--debug");
3194
+
3195
+ const {
3196
+ buildTokenCostRollup,
3197
+ writeTokenCostIntelligence,
3198
+ formatTokenCostIntelligenceText,
3199
+ } = require("./token-cost-intelligence");
3200
+ const {
3201
+ buildRealUsageTokenCostCapture,
3202
+ writeRealUsageTokenCostCapture,
3203
+ } = require("./token-cost-capture");
3204
+ const { appendProductLearningEvent } = require("./product-learning-events");
3205
+ const {
3206
+ importTokenCostEvidence,
3207
+ validateTokenCostEvidence,
3208
+ buildTokenCostEvidenceSummary,
3209
+ writeTokenCostEvidenceSummary,
3210
+ } = require("./prelaunch-evidence-store");
3211
+
3212
+ if (subcommand === "validate") {
3213
+ const file = readFlagValue(forwardedArgs, "--file");
3214
+ if (!file) {
3215
+ const message = { ok: false, error: "--file is required", redacted: true };
3216
+ if (wantJson) {
3217
+ process.stdout.write(`${JSON.stringify(message, null, 2)}\n`);
3218
+ return;
3219
+ }
3220
+ process.stderr.write("Token-cost validate error: --file is required\n");
3221
+ process.exit(1);
3222
+ }
3223
+ const receipt = validateTokenCostEvidence(cwd, file);
3224
+ if (wantJson) {
3225
+ process.stdout.write(`${JSON.stringify(receipt, null, 2)}\n`);
3226
+ return;
3227
+ }
3228
+ process.stdout.write(`Token-cost validation: ${receipt.acceptedCount} accepted, ${receipt.rejectedCount} rejected.\n`);
3229
+ return;
3230
+ }
3231
+
3232
+ if (subcommand === "import") {
3233
+ const file = readFlagValue(forwardedArgs, "--file");
3234
+ if (!file) {
3235
+ const message = { ok: false, error: "--file is required", redacted: true };
3236
+ if (wantJson) {
3237
+ process.stdout.write(`${JSON.stringify(message, null, 2)}\n`);
3238
+ return;
3239
+ }
3240
+ process.stderr.write("Token-cost import error: --file is required\n");
3241
+ process.exit(1);
3242
+ }
3243
+ const receipt = importTokenCostEvidence(cwd, file);
3244
+ if (wantJson) {
3245
+ process.stdout.write(`${JSON.stringify(receipt, null, 2)}\n`);
3246
+ return;
3247
+ }
3248
+ process.stdout.write(`Token-cost import: ${receipt.acceptedCount} accepted, ${receipt.rejectedCount} rejected.\n`);
3249
+ return;
3250
+ }
3251
+
3252
+ if (subcommand === "capture") {
3253
+ const capture = buildRealUsageTokenCostCapture(cwd);
3254
+ const receipt = writeRealUsageTokenCostCapture(cwd, capture);
3255
+ const summary = writeTokenCostEvidenceSummary(cwd, buildTokenCostEvidenceSummary(cwd));
3256
+ const output = Object.assign({}, receipt, { summary });
3257
+ if (wantJson) {
3258
+ process.stdout.write(`${JSON.stringify(output, null, 2)}\n`);
3259
+ return;
3260
+ }
3261
+ process.stdout.write(`Token-cost capture: ${receipt.status} (${receipt.realUsageSamplesCount} measured sample(s), ${receipt.capturedRowsCount} captured row(s)).\n`);
3262
+ return;
3263
+ }
3264
+
3265
+ if (subcommand === "summary") {
3266
+ const summary = writeTokenCostEvidenceSummary(cwd, buildTokenCostEvidenceSummary(cwd));
3267
+ if (wantJson) {
3268
+ process.stdout.write(`${JSON.stringify(summary, null, 2)}\n`);
3269
+ return;
3270
+ }
3271
+ process.stdout.write(`Token-cost summary: ${summary.status} (${summary.evidenceMode}, ${summary.realUsageSamplesCount} measured sample(s)).\n`);
3272
+ return;
3273
+ }
3274
+
3275
+ const intel = buildTokenCostRollup(cwd);
3276
+ writeTokenCostIntelligence(cwd, intel);
3277
+
3278
+ try {
3279
+ appendProductLearningEvent(cwd, {
3280
+ eventName: "token_cost_intelligence_built",
3281
+ category: "prelaunch_intelligence",
3282
+ status: intel.status,
3283
+ evidenceLevel: intel.evidenceLevel,
3284
+ });
3285
+ } catch {}
3286
+
3287
+ if (wantJson) {
3288
+ process.stdout.write(`${JSON.stringify(intel, null, 2)}\n`);
3289
+ return;
3290
+ }
3291
+ process.stdout.write(formatTokenCostIntelligenceText(intel, { debug: wantDebug }) + "\n");
3292
+ }
3293
+
3294
+ function renderInstallJourneyIntelligence(cwd, forwardedArgs = []) {
3295
+ const wantJson = forwardedArgs.includes("--json");
3296
+ const wantDebug = forwardedArgs.includes("--debug");
3297
+
3298
+ const {
3299
+ buildInstallJourneyIntelligence,
3300
+ writeInstallJourneyIntelligence,
3301
+ formatInstallJourneyText,
3302
+ } = require("./install-journey-intelligence");
3303
+ const { appendProductLearningEvent } = require("./product-learning-events");
3304
+
3305
+ const intel = buildInstallJourneyIntelligence(cwd);
3306
+ writeInstallJourneyIntelligence(cwd, intel);
3307
+
3308
+ try {
3309
+ appendProductLearningEvent(cwd, {
3310
+ eventName: "install_journey_intelligence_built",
3311
+ category: "prelaunch_intelligence",
3312
+ status: intel.status,
3313
+ stepsComplete: intel.stepsComplete,
3314
+ stepsTotal: intel.stepsTotal,
3315
+ });
3316
+ } catch {}
3317
+
3318
+ if (wantJson) {
3319
+ process.stdout.write(`${JSON.stringify(intel, null, 2)}\n`);
3320
+ return;
3321
+ }
3322
+ process.stdout.write(formatInstallJourneyText(intel, { debug: wantDebug }) + "\n");
3323
+ }
3324
+
3325
+ // ── MCP Tool Governance CLI ───────────────────────────────────────────────────
3326
+
3327
+ function renderMcpCommand(cwd, forwardedArgs = []) {
3328
+ const subcommand = forwardedArgs[0] || "doctor";
3329
+ const rest = forwardedArgs.slice(1);
3330
+ const wantJson = forwardedArgs.includes("--json");
3331
+ const wantDebug = forwardedArgs.includes("--debug");
3332
+
3333
+ const { buildMcpToolInventory, writeMcpToolInventory, buildMcpToolInventorySurface, formatMcpToolInventoryText } = require("./mcp-tool-inventory");
3334
+ const { buildMcpToolRiskReport, writeMcpToolRiskReport, formatMcpToolRiskText } = require("./mcp-tool-risk");
3335
+ const { buildMcpLeastPrivilegePolicy, writeMcpPolicy, buildMcpPolicyPreview, writeMcpPolicyPreview, formatMcpPolicyText } = require("./mcp-least-privilege-policy");
3336
+ const { appendProductLearningEvent } = require("./product-learning-events");
3337
+
3338
+ if (subcommand === "inventory" || subcommand === "inv") {
3339
+ const inventory = buildMcpToolInventory(cwd);
3340
+ writeMcpToolInventory(cwd, inventory);
3341
+ try {
3342
+ appendProductLearningEvent(cwd, {
3343
+ eventName: "mcp_tool_inventory_scanned",
3344
+ payload: { status: inventory.status, serverCount: inventory.servers.length, configFiles: inventory.configFiles.length, redacted: true },
3345
+ });
3346
+ } catch {}
3347
+ if (wantJson) {
3348
+ process.stdout.write(`${JSON.stringify(inventory, null, 2)}\n`);
3349
+ return;
3350
+ }
3351
+ process.stdout.write(formatMcpToolInventoryText(inventory, { debug: wantDebug }) + "\n");
3352
+ return;
3353
+ }
3354
+
3355
+ if (subcommand === "risk") {
3356
+ const inventory = buildMcpToolInventory(cwd);
3357
+ writeMcpToolInventory(cwd, inventory);
3358
+ const riskReport = buildMcpToolRiskReport(cwd, inventory);
3359
+ writeMcpToolRiskReport(cwd, riskReport);
3360
+ try {
3361
+ appendProductLearningEvent(cwd, {
3362
+ eventName: "mcp_tool_risk_classified",
3363
+ payload: { status: riskReport.status, serverCount: riskReport.summary.serverCount, highCritical: riskReport.summary.highCriticalTools, unknownServers: riskReport.summary.unknownServers, redacted: true },
3364
+ });
3365
+ if (riskReport.summary.unknownServers > 0) {
3366
+ appendProductLearningEvent(cwd, { eventName: "mcp_unknown_tool_detected", payload: { count: riskReport.summary.unknownServers, redacted: true } });
3367
+ }
3368
+ } catch {}
3369
+ if (wantJson) {
3370
+ process.stdout.write(`${JSON.stringify(riskReport, null, 2)}\n`);
3371
+ return;
3372
+ }
3373
+ process.stdout.write(formatMcpToolRiskText(riskReport, { debug: wantDebug }) + "\n");
3374
+ return;
3375
+ }
3376
+
3377
+ if (subcommand === "policy") {
3378
+ const inventory = buildMcpToolInventory(cwd);
3379
+ const riskReport = buildMcpToolRiskReport(cwd, inventory);
3380
+ const policy = buildMcpLeastPrivilegePolicy(cwd, riskReport);
3381
+ writeMcpPolicy(cwd, policy);
3382
+ try {
3383
+ appendProductLearningEvent(cwd, {
3384
+ eventName: "mcp_policy_preview_generated",
3385
+ payload: { status: policy.status, approvalRequired: policy.summary.approvalRequired, blocked: policy.summary.blocked, redacted: true },
3386
+ });
3387
+ if (policy.summary.blocked > 0) {
3388
+ appendProductLearningEvent(cwd, { eventName: "mcp_tool_blocked", payload: { count: policy.summary.blocked, redacted: true } });
3389
+ }
3390
+ if (policy.summary.approvalRequired > 0) {
3391
+ appendProductLearningEvent(cwd, { eventName: "mcp_tool_approval_required", payload: { count: policy.summary.approvalRequired, redacted: true } });
3392
+ }
3393
+ } catch {}
3394
+ if (wantJson) {
3395
+ process.stdout.write(`${JSON.stringify(policy, null, 2)}\n`);
3396
+ return;
3397
+ }
3398
+ process.stdout.write(formatMcpPolicyText(policy, { debug: wantDebug }) + "\n");
3399
+ return;
3400
+ }
3401
+
3402
+ if (subcommand === "preview") {
3403
+ const inventory = buildMcpToolInventory(cwd);
3404
+ const riskReport = buildMcpToolRiskReport(cwd, inventory);
3405
+ const policy = buildMcpLeastPrivilegePolicy(cwd, riskReport);
3406
+ const preview = buildMcpPolicyPreview(cwd, policy);
3407
+ writeMcpPolicyPreview(cwd, preview);
3408
+ if (wantJson) {
3409
+ process.stdout.write(`${JSON.stringify(preview, null, 2)}\n`);
3410
+ return;
3411
+ }
3412
+ process.stdout.write([
3413
+ `MCP Policy Preview [${preview.status}]`,
3414
+ `Preview only — config not modified.`,
3415
+ `Allow: ${preview.summary?.allow || 0} · Warn: ${preview.summary?.warn || 0} · Approval: ${preview.summary?.approvalRequired || 0} · Blocked: ${preview.summary?.blocked || 0}`,
3416
+ preview.topDecisions && preview.topDecisions.length > 0 ? `Top issues:\n${preview.topDecisions.map((d) => ` ${d.name} → ${d.decision} [${d.riskLevel}]`).join("\n")}` : "No high/critical issues.",
3417
+ `Next: Run \`avorelo mcp doctor\` for full governance status.`,
3418
+ ].join("\n") + "\n");
3419
+ return;
3420
+ }
3421
+
3422
+ // Default: doctor (full governance status)
3423
+ const inventory = buildMcpToolInventory(cwd);
3424
+ writeMcpToolInventory(cwd, inventory);
3425
+ const riskReport = buildMcpToolRiskReport(cwd, inventory);
3426
+ writeMcpToolRiskReport(cwd, riskReport);
3427
+ const policy = buildMcpLeastPrivilegePolicy(cwd, riskReport);
3428
+ writeMcpPolicy(cwd, policy);
3429
+
3430
+ if (wantJson) {
3431
+ process.stdout.write(`${JSON.stringify({
3432
+ inventory: { status: inventory.status, servers: inventory.servers.length, tools: inventory.tools.length },
3433
+ risk: { status: riskReport.status, unknownServers: riskReport.summary.unknownServers, highCritical: riskReport.summary.highCriticalTools },
3434
+ policy: { status: policy.status, allow: policy.summary.allow, warn: policy.summary.warn, approvalRequired: policy.summary.approvalRequired, blocked: policy.summary.blocked },
3435
+ note: "Avorelo does not execute MCP servers during inventory. Preview only — config not modified.",
3436
+ redacted: true,
3437
+ }, null, 2)}\n`);
3438
+ return;
3439
+ }
3440
+
3441
+ const lines = [
3442
+ `MCP Tool Governance: ${policy.status}`,
3443
+ ``,
3444
+ `Found: ${inventory.servers.length} server(s) · ${inventory.tools.length} tool surface(s)`,
3445
+ `Unknown servers: ${riskReport.summary.unknownServers}`,
3446
+ `Approval-gated: ${policy.summary.approvalRequired}`,
3447
+ `Blocked: ${policy.summary.blocked}`,
3448
+ ``,
3449
+ `Protected: Secrets/prod/destructive actions remain blocked.`,
3450
+ `Preview only: No MCP config modified.`,
3451
+ ``,
3452
+ `Next: Run \`avorelo mcp policy --debug\` for per-tool decisions.`,
3453
+ ];
3454
+ process.stdout.write(lines.join("\n") + "\n");
3455
+ }
3456
+
3457
+
3458
+ // PR #148: Full Readiness / Release Candidate Gate CLI
3459
+
3460
+ function renderFullReadiness(cwd, args) {
3461
+ args = args || [];
3462
+ var wantJson = args.indexOf("--json") !== -1;
3463
+ var wantDebug = args.indexOf("--debug") !== -1;
3464
+ var frg = require("./full-readiness-gate");
3465
+ var kll = require("./known-limitations");
3466
+ var rec = require("./readiness-evidence-closure");
3467
+ var eus = require("./external-user-simulation");
3468
+ var ple = require("./product-learning-events");
3469
+ var closure = rec.runReadinessEvidenceClosure(cwd, {});
3470
+ rec.writeEvidenceClosure(cwd, closure);
3471
+ var signals = frg.collectFullReadinessSignals(cwd, {});
3472
+ var limitations = kll.buildKnownLimitations(cwd, signals, {});
3473
+ kll.writeKnownLimitations(cwd, limitations);
3474
+ var sim = eus.runExternalUserSimulation(cwd, {});
3475
+ eus.writeExternalUserSimulation(cwd, sim);
3476
+ var gate = frg.runFullReadinessGate(cwd, { knownLimitations: limitations });
3477
+ frg.writeFullReadinessGate(cwd, gate);
3478
+ try { ple.appendProductLearningEvent(cwd, { eventName: "full_readiness_gate_run", category: "full_readiness", status: gate.status, score: gate.score, blockerCount: (gate.blockers || []).length }); } catch (e) {}
3479
+ if (wantJson) { process.stdout.write(JSON.stringify(gate, null, 2) + "\n"); return; }
3480
+ process.stdout.write(frg.formatFullReadinessText(gate, { debug: wantDebug }) + "\n");
3481
+ }
3482
+
3483
+ function renderReadinessDelta(cwd, args) {
3484
+ args = args || [];
3485
+ var wantJson = args.indexOf("--json") !== -1;
3486
+ var rd = require("./readiness-delta");
3487
+ var delta = rd.buildReadinessDelta(cwd, {});
3488
+ rd.writeReadinessDelta(cwd, delta);
3489
+ if (wantJson) { process.stdout.write(JSON.stringify(delta, null, 2) + "\n"); return; }
3490
+ process.stdout.write(rd.formatReadinessDeltaText(delta) + "\n");
3491
+ }
3492
+
3493
+ function renderReadinessClosure(cwd, args) {
3494
+ args = args || [];
3495
+ var wantJson = args.indexOf("--json") !== -1;
3496
+ var rec = require("./readiness-evidence-closure");
3497
+ var ple = require("./product-learning-events");
3498
+ var closure = rec.runReadinessEvidenceClosure(cwd, {});
3499
+ rec.writeEvidenceClosure(cwd, closure);
3500
+ try { ple.appendProductLearningEvent(cwd, { eventName: "readiness_evidence_closure_run", category: "full_readiness", status: closure.status }); } catch (e) {}
3501
+ if (wantJson) { process.stdout.write(JSON.stringify(closure, null, 2) + "\n"); return; }
3502
+ process.stdout.write(rec.formatEvidenceClosureText(closure) + "\n");
3503
+ }
3504
+
3505
+ function renderKnownLimitations(cwd, args) {
3506
+ args = args || [];
3507
+ var wantJson = args.indexOf("--json") !== -1;
3508
+ var frg = require("./full-readiness-gate");
3509
+ var kll = require("./known-limitations");
3510
+ var ple = require("./product-learning-events");
3511
+ var signals = frg.collectFullReadinessSignals(cwd, {});
3512
+ var limitations = kll.buildKnownLimitations(cwd, signals, {});
3513
+ kll.writeKnownLimitations(cwd, limitations);
3514
+ try { ple.appendProductLearningEvent(cwd, { eventName: "known_limitations_built", category: "full_readiness", totalLimitations: limitations.totalLimitations }); } catch (e) {}
3515
+ if (wantJson) { process.stdout.write(JSON.stringify(limitations, null, 2) + "\n"); return; }
3516
+ process.stdout.write(kll.formatKnownLimitationsText(limitations) + "\n");
3517
+ }
3518
+
3519
+ function renderExternalUserSim(cwd, args) {
3520
+ args = args || [];
3521
+ var wantJson = args.indexOf("--json") !== -1;
3522
+ var eus = require("./external-user-simulation");
3523
+ var ple = require("./product-learning-events");
3524
+ var sim = eus.runExternalUserSimulation(cwd, {});
3525
+ eus.writeExternalUserSimulation(cwd, sim);
3526
+ try { ple.appendProductLearningEvent(cwd, { eventName: "external_user_simulation_run", category: "full_readiness", status: sim.status, passed: sim.passed }); } catch (e) {}
3527
+ if (wantJson) { process.stdout.write(JSON.stringify(sim, null, 2) + "\n"); return; }
3528
+ process.stdout.write(eus.formatExternalUserSimulationText(sim) + "\n");
3529
+ }
3530
+
3531
+ function renderReleaseCandidateBundle(cwd, args) {
3532
+ args = args || [];
3533
+ var wantJson = args.indexOf("--json") !== -1;
3534
+ var rcb = require("./release-candidate-bundle");
3535
+ var ple = require("./product-learning-events");
3536
+ var bundle = rcb.buildReleaseCandidateBundle(cwd, {});
3537
+ rcb.writeReleaseCandidateBundle(cwd, bundle);
3538
+ try { ple.appendProductLearningEvent(cwd, { eventName: "release_candidate_bundle_built", category: "full_readiness", status: bundle.status, releaseCandidateStatus: bundle.releaseCandidateStatus }); } catch (e) {}
3539
+ if (wantJson) { process.stdout.write(JSON.stringify(bundle, null, 2) + "\n"); return; }
3540
+ process.stdout.write(rcb.formatReleaseCandidateBundleText(bundle) + "\n");
3541
+ }
3542
+
3543
+ function renderActivationDistributionReadiness(cwd, args) {
3544
+ args = args || [];
3545
+ var wantJson = args.indexOf("--json") !== -1;
3546
+ var debug = args.indexOf("--debug") !== -1;
3547
+ var adr = require("./activation-distribution-readiness");
3548
+ var ple = require("./product-learning-events");
3549
+ var result = adr.runActivationDistributionReadiness(cwd, {});
3550
+ adr.writeActivationDistributionReadiness(cwd, result);
3551
+ try { ple.appendProductLearningEvent(cwd, { eventName: "activation_distribution_readiness_run", category: "activation_distribution", status: result.status, score: result.score }); } catch (e) {}
3552
+ if (wantJson) { process.stdout.write(JSON.stringify(result, null, 2) + "\n"); return; }
3553
+ process.stdout.write(adr.formatActivationDistributionText(result, { debug: debug }) + "\n");
3554
+ }
3555
+
3556
+ // ── Public Distribution Truth CLI (PR #148) ───────────────────────────────────
3557
+
3558
+ function renderPublicDistribution(cwd, args) {
3559
+ args = args || [];
3560
+ var wantJson = args.indexOf("--json") !== -1;
3561
+ var wantDebug = args.indexOf("--debug") !== -1;
3562
+ var pag = require("./public-activation-distribution-gate");
3563
+ var ple = require("./product-learning-events");
3564
+ var gate = pag.runPublicActivationDistributionGate(cwd, {});
3565
+ pag.writePublicActivationDistributionGate(cwd, gate);
3566
+ try { ple.appendProductLearningEvent(cwd, { eventName: "public_activation_distribution_gate_run", category: "public_distribution", status: gate.status, score: gate.score }); } catch (e) {}
3567
+ if (wantJson) { process.stdout.write(JSON.stringify(gate, null, 2) + "\n"); return; }
3568
+ process.stdout.write(pag.formatPublicActivationDistributionText(gate, { debug: wantDebug }) + "\n");
3569
+ }
3570
+
3571
+ function renderPackageAudit(cwd, args) {
3572
+ args = args || [];
3573
+ var wantJson = args.indexOf("--json") !== -1;
3574
+ var pca = require("./package-content-audit");
3575
+ var ple = require("./product-learning-events");
3576
+ var audit = pca.buildPackageContentAudit(cwd, {});
3577
+ pca.writePackageContentAudit(cwd, audit);
3578
+ try { ple.appendProductLearningEvent(cwd, { eventName: "package_content_audit_run", category: "public_distribution", status: audit.status, fileCount: audit.fileCount }); } catch (e) {}
3579
+ if (wantJson) { process.stdout.write(JSON.stringify(audit, null, 2) + "\n"); return; }
3580
+ process.stdout.write(pca.formatPackageContentAuditText(audit) + "\n");
3581
+ }
3582
+
3583
+ function renderPackageSmoke(cwd, args) {
3584
+ args = args || [];
3585
+ var wantJson = args.indexOf("--json") !== -1;
3586
+ var lps = require("./local-package-smoke");
3587
+ var ple = require("./product-learning-events");
3588
+ var smoke = lps.runLocalPackageSmoke(cwd, {});
3589
+ lps.writeLocalPackageSmoke(cwd, smoke);
3590
+ try { ple.appendProductLearningEvent(cwd, { eventName: "local_package_smoke_run", category: "public_distribution", status: smoke.status, tarballCreated: smoke.tarballCreated }); } catch (e) {}
3591
+ if (wantJson) { process.stdout.write(JSON.stringify(smoke, null, 2) + "\n"); return; }
3592
+ process.stdout.write(lps.formatLocalPackageSmokeText(smoke) + "\n");
3593
+ }
3594
+
3595
+ function renderInstallClaims(cwd, args) {
3596
+ args = args || [];
3597
+ var wantJson = args.indexOf("--json") !== -1;
3598
+ var picc = require("./public-install-claim-checker");
3599
+ var ple = require("./product-learning-events");
3600
+ var report = picc.validateInstallClaims(cwd, {});
3601
+ picc.writePublicInstallClaimCheck(cwd, report);
3602
+ try { ple.appendProductLearningEvent(cwd, { eventName: "public_install_claim_check_run", category: "public_distribution", status: report.status, blockedCount: (report.blockedClaims || []).length }); } catch (e) {}
3603
+ if (wantJson) { process.stdout.write(JSON.stringify(report, null, 2) + "\n"); return; }
3604
+ process.stdout.write(picc.formatPublicInstallClaimText(report) + "\n");
3605
+ }
3606
+
3607
+ function renderPublishReadiness(cwd, args) {
3608
+ args = args || [];
3609
+ var wantJson = args.indexOf("--json") !== -1;
3610
+ var ppr = require("./publish-provenance-readiness");
3611
+ var ple = require("./product-learning-events");
3612
+ var readiness = ppr.buildPublishProvenanceReadiness(cwd, {});
3613
+ ppr.writePublishProvenanceReadiness(cwd, readiness);
3614
+ try { ple.appendProductLearningEvent(cwd, { eventName: "publish_provenance_readiness_run", category: "public_distribution", status: readiness.status }); } catch (e) {}
3615
+ if (wantJson) { process.stdout.write(JSON.stringify(readiness, null, 2) + "\n"); return; }
3616
+ process.stdout.write(ppr.formatPublishProvenanceText(readiness) + "\n");
3617
+ }
3618
+
3619
+ // ── Adapter Technical Readiness CLI (PR #162) ─────────────────────────────────
3620
+
3621
+ function renderHostMatrix(cwd, args) {
3622
+ args = args || [];
3623
+ var wantJson = args.indexOf("--json") !== -1;
3624
+ var mod = require("./host-capability-matrix");
3625
+ var ple = require("./product-learning-events");
3626
+ var surface = mod.buildHostCapabilityMatrixSurface(cwd, {});
3627
+ try { ple.appendProductLearningEvent(cwd, { eventName: "host_matrix_run", category: "adapter_readiness", status: surface.status }); } catch (e) {}
3628
+ if (wantJson) { process.stdout.write(JSON.stringify(surface, null, 2) + "\n"); return; }
3629
+ var full = mod.buildHostCapabilityMatrix(cwd, {});
3630
+ process.stdout.write(mod.formatHostCapabilityMatrixText(full) + "\n");
3631
+ }
3632
+
3633
+ function renderCrossHostInstall(cwd, args) {
3634
+ args = args || [];
3635
+ var wantJson = args.indexOf("--json") !== -1;
3636
+ var mod = require("./cross-host-install-readiness");
3637
+ var ple = require("./product-learning-events");
3638
+ var surface = mod.buildCrossHostInstallSurface(cwd, {});
3639
+ try { ple.appendProductLearningEvent(cwd, { eventName: "cross_host_install_run", category: "adapter_readiness", status: surface.status }); } catch (e) {}
3640
+ if (wantJson) { process.stdout.write(JSON.stringify(surface, null, 2) + "\n"); return; }
3641
+ var full = mod.buildCrossHostInstallReadiness(cwd, {});
3642
+ process.stdout.write(mod.formatCrossHostInstallText(full) + "\n");
3643
+ }
3644
+
3645
+ function renderCrossHostInstallPlan(cwd, args) {
3646
+ args = args || [];
3647
+ var wantJson = args.indexOf("--json") !== -1;
3648
+ var wantDebug = args.indexOf("--debug") !== -1;
3649
+ var mod = require("./cross-host-install-plan");
3650
+ var ple = require("./product-learning-events");
3651
+ var surface = mod.buildCrossHostInstallSurface(cwd, {});
3652
+ try { ple.appendProductLearningEvent(cwd, { eventName: "cross_host_install_plan_run", category: "adapter_readiness", status: surface.status }); } catch (e) {}
3653
+ if (wantJson) {
3654
+ var full = mod.buildAllHostInstallPlans(cwd, {});
3655
+ process.stdout.write(JSON.stringify(full, null, 2) + "\n");
3656
+ return;
3657
+ }
3658
+ var full2 = mod.buildAllHostInstallPlans(cwd, {});
3659
+ process.stdout.write(mod.formatCrossHostInstallText(full2, { debug: wantDebug }) + "\n");
3660
+ }
3661
+
3662
+ function renderCrossHostValue(cwd, args) {
3663
+ args = args || [];
3664
+ var wantJson = args.indexOf("--json") !== -1;
3665
+ var mod = require("./cross-host-value-flow");
3666
+ var ple = require("./product-learning-events");
3667
+ var surface = mod.buildCrossHostValueFlowSurface(cwd, {});
3668
+ try { ple.appendProductLearningEvent(cwd, { eventName: "cross_host_value_run", category: "adapter_readiness", status: surface.status }); } catch (e) {}
3669
+ if (wantJson) { process.stdout.write(JSON.stringify(surface, null, 2) + "\n"); return; }
3670
+ var full = mod.buildCrossHostValueFlow(cwd, {});
3671
+ process.stdout.write(mod.formatCrossHostValueFlowText(full) + "\n");
3672
+ }
3673
+
3674
+ function renderAdapterSafety(cwd, args) {
3675
+ args = args || [];
3676
+ var wantJson = args.indexOf("--json") !== -1;
3677
+ var mod = require("./adapter-safety-boundaries");
3678
+ var ple = require("./product-learning-events");
3679
+ var surface = mod.buildAdapterSafetyBoundariesSurface(cwd, {});
3680
+ try { ple.appendProductLearningEvent(cwd, { eventName: "adapter_safety_run", category: "adapter_readiness", status: surface.status }); } catch (e) {}
3681
+ if (wantJson) { process.stdout.write(JSON.stringify(surface, null, 2) + "\n"); return; }
3682
+ var full = mod.buildAdapterSafetyBoundaries(cwd, {});
3683
+ process.stdout.write(mod.formatAdapterSafetyBoundariesText(full) + "\n");
3684
+ }
3685
+
3686
+ function renderHostSupport(cwd, args) {
3687
+ args = args || [];
3688
+ var wantJson = args.indexOf("--json") !== -1;
3689
+ var mod = require("./host-support-context");
3690
+ var ple = require("./product-learning-events");
3691
+ var surface = mod.buildHostSupportContextSurface(cwd, {});
3692
+ try { ple.appendProductLearningEvent(cwd, { eventName: "host_support_run", category: "adapter_readiness", status: surface.status }); } catch (e) {}
3693
+ if (wantJson) { process.stdout.write(JSON.stringify(surface, null, 2) + "\n"); return; }
3694
+ var full = mod.buildHostSupportContext(cwd, {});
3695
+ process.stdout.write(mod.formatHostSupportContextText(full) + "\n");
3696
+ }
3697
+
3698
+ function renderBrowserPreflight(cwd, args) {
3699
+ args = args || [];
3700
+ var wantJson = args.indexOf("--json") !== -1;
3701
+ var mod = require("./browser-proof-preflight");
3702
+ var ple = require("./product-learning-events");
3703
+ var surface = mod.buildBrowserProofPreflightSurface(cwd, {});
3704
+ try { ple.appendProductLearningEvent(cwd, { eventName: "browser_preflight_run", category: "adapter_readiness", status: surface.status, noBrowserLaunch: true }); } catch (e) {}
3705
+ if (wantJson) { process.stdout.write(JSON.stringify(surface, null, 2) + "\n"); return; }
3706
+ var full = mod.buildBrowserProofPreflight(cwd, {});
3707
+ process.stdout.write(mod.formatBrowserProofPreflightText(full) + "\n");
3708
+ }
3709
+
3710
+ function renderAdapterTechnicalReadiness(cwd, args) {
3711
+ args = args || [];
3712
+ var wantJson = args.indexOf("--json") !== -1;
3713
+ var mod = require("./adapter-technical-readiness-gate");
3714
+ var ple = require("./product-learning-events");
3715
+ var surface = mod.buildAdapterTechnicalReadinessSurface(cwd, {});
3716
+ try { ple.appendProductLearningEvent(cwd, { eventName: "adapter_technical_readiness_run", category: "adapter_readiness", status: surface.status, score: surface.score, verdict: surface.verdict }); } catch (e) {}
3717
+ if (wantJson) { process.stdout.write(JSON.stringify(surface, null, 2) + "\n"); return; }
3718
+ var full = mod.buildAdapterTechnicalReadinessGate(cwd, {});
3719
+ process.stdout.write(mod.formatAdapterTechnicalReadinessText(full) + "\n");
3720
+ }
3721
+
3722
+ // ── Run Improvements CLI (Add Run Improvements E2E) ──────────────────────────
3723
+
3724
+ function renderRunImprovements(cwd, forwardedArgs = []) {
3725
+ const wantJson = forwardedArgs.includes("--json");
3726
+ const forceGenerate = forwardedArgs.includes("--generate");
3727
+ const wantConsume = forwardedArgs.includes("--consume");
3728
+ const wantApply = forwardedArgs.includes("--apply");
3729
+
3730
+ const {
3731
+ generateRunImprovementsArtifact,
3732
+ loadRunImprovements,
3733
+ formatRunImprovementsText,
3734
+ formatRunImprovementsStatusLine,
3735
+ } = require("./run-improvements");
3736
+
3737
+ // --apply: inject next-run context artifact and mark lifecycle applied
3738
+ // This is the real application path — creates bounded next-run-context artifact
3739
+ // and sets applied receipt with surface = "next_run_context".
3740
+ if (wantApply) {
3741
+ const { injectNextRunContext } = require("./run-improvements-lifecycle");
3742
+ const result = injectNextRunContext(cwd);
3743
+ if (wantJson) {
3744
+ process.stdout.write(JSON.stringify(result, null, 2) + "\n");
3745
+ } else if (result.success) {
3746
+ process.stdout.write(`Run Improvements: applied via next-run context.\n`);
3747
+ process.stdout.write(` Artifact: ${result.artifactPath || ".claude/cco/state/next-run-context.json"}\n`);
3748
+ process.stdout.write(` Defaults: ${result.defaultsCount || 0} · Decisions: ${result.decisionsCount || 0} · Risks: ${result.risksCount || 0}\n`);
3749
+ process.stdout.write(` Surface: ${result.surface || "next_run_context"}\n`);
3750
+ process.stdout.write(` Applied at: ${result.receipt?.appliedAt || "n/a"}\n`);
3751
+ if (result.reason === "already_applied") {
3752
+ process.stdout.write(` (Already applied for this fingerprint — idempotent.)\n`);
3753
+ }
3754
+ } else {
3755
+ process.stdout.write(`Run Improvements: apply failed — ${result.reason}\n`);
3756
+ if (result.error) process.stdout.write(` Error: ${result.error}\n`);
3757
+ }
3758
+ return;
3759
+ }
3760
+
3761
+ // --consume: mark defaults as consumed by a supported surface
3762
+ if (wantConsume) {
3763
+ const { consumeRunImprovements } = require("./run-improvements-lifecycle");
3764
+ const receipt = consumeRunImprovements(cwd, "cli");
3765
+ if (wantJson) {
3766
+ process.stdout.write(JSON.stringify(receipt || { status: "no_artifact" }, null, 2) + "\n");
3767
+ } else if (receipt) {
3768
+ process.stdout.write(`Run Improvements: consumed.\n`);
3769
+ process.stdout.write(` Fingerprint: ${receipt.sourceRunFingerprint}\n`);
3770
+ process.stdout.write(` Consumed at: ${receipt.consumedAt}\n`);
3771
+ } else {
3772
+ process.stdout.write(`Run Improvements: consume failed — no prepared artifact found.\n`);
3773
+ }
3774
+ return;
3775
+ }
3776
+
3777
+ if (forceGenerate) {
3778
+ const { artifact, written, reason } = generateRunImprovementsArtifact(cwd, { mode: "prepare" });
3779
+ if (wantJson) {
3780
+ process.stdout.write(JSON.stringify({ written, reason, artifact }, null, 2) + "\n");
3781
+ } else {
3782
+ const text = formatRunImprovementsText(cwd) || artifact.publicSummary;
3783
+ process.stdout.write(text + "\n");
3784
+ if (written) {
3785
+ process.stdout.write(` Generated: ${artifact.topImprovements.length} improvement(s).\n`);
3786
+ } else {
3787
+ process.stdout.write(` Skipped (same fingerprint, not expired).\n`);
3788
+ }
3789
+ }
3790
+ return;
3791
+ }
3792
+
3793
+ const existing = loadRunImprovements(cwd);
3794
+ if (wantJson) {
3795
+ process.stdout.write(JSON.stringify(existing || { status: "not_available" }, null, 2) + "\n");
3796
+ return;
3797
+ }
3798
+
3799
+ if (!existing || existing.status === "not_available") {
3800
+ process.stdout.write(
3801
+ "Run Improvements: not available.\n" +
3802
+ "No prior run evidence found. Run an Avorelo session first, or use --generate to check now.\n"
3803
+ );
3804
+ return;
3805
+ }
3806
+
3807
+ const line = formatRunImprovementsStatusLine(cwd);
3808
+ const text = formatRunImprovementsText(cwd);
3809
+ process.stdout.write((line || text || existing.publicSummary) + "\n");
3810
+
3811
+ if (
3812
+ (existing.status === "prepared" || existing.status === "applied") &&
3813
+ existing.nextRunDefaults.length > 0
3814
+ ) {
3815
+ process.stdout.write("\nNext-run defaults:\n");
3816
+ existing.nextRunDefaults.forEach((d, i) => {
3817
+ process.stdout.write(` ${i + 1}. ${d.text}\n`);
3818
+ });
3819
+ }
3820
+
3821
+ // Show next-run context status if applied
3822
+ if (existing.status === "applied") {
3823
+ try {
3824
+ const { buildNextRunContextSurface } = require("./next-run-context");
3825
+ const nrcSurface = buildNextRunContextSurface(cwd);
3826
+ if (nrcSurface.showInStatus && nrcSurface.statusLine) {
3827
+ process.stdout.write(`\n${nrcSurface.statusLine}\n`);
3828
+ }
3829
+ } catch {}
3830
+ }
3831
+
3832
+ if (existing.limitations && existing.limitations.length > 0) {
3833
+ process.stdout.write("\nLimitations:\n");
3834
+ existing.limitations.forEach((l) => process.stdout.write(` - ${l}\n`));
3835
+ }
3836
+ }
3837
+
3838
+ // ── Learning CLI ──────────────────────────────────────────────────────────────
3839
+
3840
+ function renderLearning(cwd, forwardedArgs = []) {
3841
+ const wantJson = forwardedArgs.includes("--json");
3842
+ const wantGenerate = forwardedArgs.includes("--generate");
3843
+ const wantSummary = forwardedArgs.includes("--summary") || !wantGenerate;
3844
+
3845
+ const {
3846
+ generateLearningArtifacts,
3847
+ loadLearningSummary,
3848
+ formatLearningSummaryText,
3849
+ } = require("./learning-memory");
3850
+
3851
+ if (wantGenerate) {
3852
+ const result = generateLearningArtifacts(cwd);
3853
+ if (wantJson) {
3854
+ process.stdout.write(JSON.stringify(result.summary, null, 2) + "\n");
3855
+ } else {
3856
+ const text = formatLearningSummaryText(cwd);
3857
+ process.stdout.write((text || "Learning: generated.") + "\n");
3858
+ process.stdout.write(` Decisions: ${result.summary.activeDecisionCount}\n`);
3859
+ process.stdout.write(` Risks: ${result.summary.activeRiskCount}\n`);
3860
+ process.stdout.write(` Capabilities: ${result.summary.capabilityCount}\n`);
3861
+ }
3862
+ return;
3863
+ }
3864
+
3865
+ if (wantSummary) {
3866
+ const summary = loadLearningSummary(cwd);
3867
+ if (wantJson) {
3868
+ process.stdout.write(JSON.stringify(summary || { status: "not_available" }, null, 2) + "\n");
3869
+ return;
3870
+ }
3871
+ if (!summary) {
3872
+ process.stdout.write(
3873
+ "Learning: not available.\nNo learning summary found. Run --generate to build learning artifacts.\n"
3874
+ );
3875
+ return;
3876
+ }
3877
+ const text = formatLearningSummaryText(cwd);
3878
+ process.stdout.write((text || "Learning: available.") + "\n");
3879
+ if (summary.nextRunInfluence.length > 0) {
3880
+ process.stdout.write("\nNext-run influence:\n");
3881
+ summary.nextRunInfluence.forEach((inf) => {
3882
+ process.stdout.write(` - ${inf.text}\n`);
3883
+ });
3884
+ }
3885
+ }
3886
+ }
3887
+
3888
+ module.exports = {
3889
+ main,
3890
+ printHelp,
3891
+ };