avorelo 0.1.0 → 0.3.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 (260) hide show
  1. package/LICENSE +23 -16
  2. package/README.md +90 -51
  3. package/bin/avorelo.mjs +7 -0
  4. package/dist/avorelo.mjs +19741 -0
  5. package/package.json +135 -120
  6. package/bin/avorelo +0 -9
  7. package/scripts/README.md +0 -40
  8. package/scripts/cco-dashboard.js +0 -252
  9. package/scripts/cco-status.js +0 -430
  10. package/scripts/lib/activation/account-state.js +0 -37
  11. package/scripts/lib/activation/activation-runner.js +0 -546
  12. package/scripts/lib/activation/activation-self-healing.js +0 -480
  13. package/scripts/lib/activation/activation-state.js +0 -83
  14. package/scripts/lib/activation/activation-summary.js +0 -191
  15. package/scripts/lib/activation/adapters/claude-code.js +0 -77
  16. package/scripts/lib/activation/adapters/codex-cli.js +0 -52
  17. package/scripts/lib/activation/adapters/cursor.js +0 -37
  18. package/scripts/lib/activation/adapters/github-agent.js +0 -39
  19. package/scripts/lib/activation/adapters/terminal.js +0 -42
  20. package/scripts/lib/activation/adapters/vscode.js +0 -39
  21. package/scripts/lib/activation/adapters/windsurf.js +0 -37
  22. package/scripts/lib/activation/ai-surface-detector.js +0 -151
  23. package/scripts/lib/activation/connect-account.js +0 -145
  24. package/scripts/lib/activation/detect-environment.js +0 -75
  25. package/scripts/lib/activation/detect-hosts.js +0 -62
  26. package/scripts/lib/activation/format-activation-output.js +0 -109
  27. package/scripts/lib/activation/next-action.js +0 -43
  28. package/scripts/lib/activation/repair-engine.js +0 -219
  29. package/scripts/lib/activation-distribution-readiness.js +0 -507
  30. package/scripts/lib/adapter-conformance.js +0 -176
  31. package/scripts/lib/adapter-readiness.js +0 -417
  32. package/scripts/lib/adapter-safety-boundaries.js +0 -335
  33. package/scripts/lib/adapter-technical-readiness-gate.js +0 -205
  34. package/scripts/lib/agent-access-governance.js +0 -455
  35. package/scripts/lib/agent-enforcement.js +0 -765
  36. package/scripts/lib/agent-policy-profile.js +0 -210
  37. package/scripts/lib/agent-security/action-evaluator.js +0 -507
  38. package/scripts/lib/agent-security/adapter-registry.js +0 -98
  39. package/scripts/lib/agent-security/auto-policy.js +0 -139
  40. package/scripts/lib/agent-security/bounded-scan.js +0 -93
  41. package/scripts/lib/agent-security/enforcement-adapter.js +0 -174
  42. package/scripts/lib/agent-security/enforcement-engine.js +0 -1129
  43. package/scripts/lib/agent-security/file-write-adapter.js +0 -183
  44. package/scripts/lib/agent-security/file-write-rules.js +0 -178
  45. package/scripts/lib/agent-security/index.js +0 -3342
  46. package/scripts/lib/agent-security/instruction-risk.js +0 -181
  47. package/scripts/lib/agent-security/mcp-action-adapter.js +0 -185
  48. package/scripts/lib/agent-security/mcp-action-rules.js +0 -184
  49. package/scripts/lib/agent-security/package-action-adapter.js +0 -175
  50. package/scripts/lib/agent-security/package-action-rules.js +0 -233
  51. package/scripts/lib/agent-security/performance.js +0 -148
  52. package/scripts/lib/agent-security/permission-minimizer.js +0 -403
  53. package/scripts/lib/agent-security/scan-cache.js +0 -74
  54. package/scripts/lib/agent-security/source-trust.js +0 -146
  55. package/scripts/lib/ai-install-prompt.js +0 -288
  56. package/scripts/lib/ai-workspace-hygiene.js +0 -1499
  57. package/scripts/lib/alpha-activation.js +0 -520
  58. package/scripts/lib/alpha-feedback.js +0 -263
  59. package/scripts/lib/alpha-readiness-gate.js +0 -332
  60. package/scripts/lib/anti-gaming.js +0 -169
  61. package/scripts/lib/artifact-health.js +0 -431
  62. package/scripts/lib/attribution.js +0 -180
  63. package/scripts/lib/audit.js +0 -289
  64. package/scripts/lib/avorelo-skill-registry.js +0 -810
  65. package/scripts/lib/batch-jobs.js +0 -71
  66. package/scripts/lib/brain-pack.js +0 -578
  67. package/scripts/lib/brand-boundary.js +0 -424
  68. package/scripts/lib/brand.js +0 -74
  69. package/scripts/lib/browser-capability.js +0 -1048
  70. package/scripts/lib/browser-proof-preflight.js +0 -321
  71. package/scripts/lib/cache-readiness.js +0 -187
  72. package/scripts/lib/canonical-reentry.js +0 -162
  73. package/scripts/lib/capability-packs.js +0 -314
  74. package/scripts/lib/capability-recommender.js +0 -512
  75. package/scripts/lib/capability-registry.js +0 -1059
  76. package/scripts/lib/carry-forward-surfacing.js +0 -194
  77. package/scripts/lib/ccusage-adapter.js +0 -188
  78. package/scripts/lib/company-loop.js +0 -1149
  79. package/scripts/lib/config.js +0 -637
  80. package/scripts/lib/context-acquisition-plan.js +0 -287
  81. package/scripts/lib/context-budget-guard.js +0 -170
  82. package/scripts/lib/context-budget-scanner.js +0 -257
  83. package/scripts/lib/context-optimizer.js +0 -715
  84. package/scripts/lib/context-reduction-plan.js +0 -178
  85. package/scripts/lib/context-safety.js +0 -88
  86. package/scripts/lib/context-savings-engine.js +0 -158
  87. package/scripts/lib/cost-evidence.js +0 -254
  88. package/scripts/lib/cross-host-install-plan.js +0 -308
  89. package/scripts/lib/cross-host-install-readiness.js +0 -237
  90. package/scripts/lib/cross-host-value-flow.js +0 -268
  91. package/scripts/lib/dashboard.js +0 -900
  92. package/scripts/lib/design-partner-feedback.js +0 -346
  93. package/scripts/lib/entitlements.js +0 -100
  94. package/scripts/lib/execution-packet.js +0 -559
  95. package/scripts/lib/experimentation-events.js +0 -547
  96. package/scripts/lib/external-capability-compliance.js +0 -107
  97. package/scripts/lib/external-user-simulation.js +0 -166
  98. package/scripts/lib/failure-recovery-readiness.js +0 -81
  99. package/scripts/lib/failure-recovery.js +0 -419
  100. package/scripts/lib/feedback-intelligence.js +0 -537
  101. package/scripts/lib/feedback-signals.js +0 -205
  102. package/scripts/lib/file-integrity.js +0 -68
  103. package/scripts/lib/fsx.js +0 -127
  104. package/scripts/lib/full-readiness-gate.js +0 -451
  105. package/scripts/lib/guidance-builder.js +0 -174
  106. package/scripts/lib/hook-apply.js +0 -1019
  107. package/scripts/lib/hook-baseline.js +0 -310
  108. package/scripts/lib/hook-config-preview.js +0 -275
  109. package/scripts/lib/hook-contracts.js +0 -290
  110. package/scripts/lib/hook-safety-boundary-readiness.js +0 -80
  111. package/scripts/lib/host-capability-matrix.js +0 -351
  112. package/scripts/lib/host-support-context.js +0 -254
  113. package/scripts/lib/http-hook-action.js +0 -538
  114. package/scripts/lib/install-ai-readiness.js +0 -84
  115. package/scripts/lib/install-intake-risk.js +0 -1037
  116. package/scripts/lib/install-journey-intelligence.js +0 -329
  117. package/scripts/lib/intervention-guidance.js +0 -57
  118. package/scripts/lib/known-limitations.js +0 -115
  119. package/scripts/lib/l8-path-truth.js +0 -146
  120. package/scripts/lib/launch-hardening-gate.js +0 -436
  121. package/scripts/lib/launch-readiness.js +0 -628
  122. package/scripts/lib/learning-memory.js +0 -686
  123. package/scripts/lib/lifecycle-hooks.js +0 -802
  124. package/scripts/lib/local-package-smoke.js +0 -423
  125. package/scripts/lib/local-pricing.js +0 -299
  126. package/scripts/lib/mcp-enforcement.js +0 -311
  127. package/scripts/lib/mcp-least-privilege-policy.js +0 -303
  128. package/scripts/lib/mcp-tool-inventory.js +0 -388
  129. package/scripts/lib/mcp-tool-risk.js +0 -0
  130. package/scripts/lib/memory.js +0 -335
  131. package/scripts/lib/metrics.js +0 -699
  132. package/scripts/lib/micro-proof.js +0 -133
  133. package/scripts/lib/next-run-context.js +0 -436
  134. package/scripts/lib/operating-value.js +0 -1648
  135. package/scripts/lib/optimization-v3.js +0 -122
  136. package/scripts/lib/orchestration/adapters/_shared.js +0 -49
  137. package/scripts/lib/orchestration/adapters/aider.js +0 -18
  138. package/scripts/lib/orchestration/adapters/claude-code.js +0 -35
  139. package/scripts/lib/orchestration/adapters/codex.js +0 -35
  140. package/scripts/lib/orchestration/adapters/gemini-cli.js +0 -18
  141. package/scripts/lib/orchestration/adapters/git.js +0 -25
  142. package/scripts/lib/orchestration/adapters/index.js +0 -31
  143. package/scripts/lib/orchestration/adapters/lm-studio.js +0 -18
  144. package/scripts/lib/orchestration/adapters/ollama.js +0 -18
  145. package/scripts/lib/orchestration/adapters/opencode.js +0 -18
  146. package/scripts/lib/orchestration/adapters/openrouter.js +0 -18
  147. package/scripts/lib/orchestration/adapters/test-runner.js +0 -25
  148. package/scripts/lib/orchestration/cli.js +0 -438
  149. package/scripts/lib/orchestration/execution-manager.js +0 -279
  150. package/scripts/lib/orchestration/handoff.js +0 -314
  151. package/scripts/lib/orchestration/index.js +0 -456
  152. package/scripts/lib/orchestration/inventory.js +0 -47
  153. package/scripts/lib/orchestration/model-discovery.js +0 -498
  154. package/scripts/lib/orchestration/model-profiler.js +0 -170
  155. package/scripts/lib/orchestration/model-profiles.js +0 -252
  156. package/scripts/lib/orchestration/model-refresh-policy.js +0 -72
  157. package/scripts/lib/orchestration/proof-writer.js +0 -349
  158. package/scripts/lib/orchestration/provider-discovery/aider.js +0 -49
  159. package/scripts/lib/orchestration/provider-discovery/claude-code.js +0 -56
  160. package/scripts/lib/orchestration/provider-discovery/codex.js +0 -49
  161. package/scripts/lib/orchestration/provider-discovery/common.js +0 -186
  162. package/scripts/lib/orchestration/provider-discovery/gemini.js +0 -106
  163. package/scripts/lib/orchestration/provider-discovery/lm-studio.js +0 -118
  164. package/scripts/lib/orchestration/provider-discovery/models-dev.js +0 -12
  165. package/scripts/lib/orchestration/provider-discovery/ollama.js +0 -100
  166. package/scripts/lib/orchestration/provider-discovery/opencode.js +0 -47
  167. package/scripts/lib/orchestration/provider-discovery/openrouter.js +0 -44
  168. package/scripts/lib/orchestration/risk-classifier.js +0 -130
  169. package/scripts/lib/orchestration/routing-policy.js +0 -486
  170. package/scripts/lib/orchestration/settings.js +0 -112
  171. package/scripts/lib/orchestration/state.js +0 -165
  172. package/scripts/lib/orchestration/verification-manager.js +0 -138
  173. package/scripts/lib/output-profiles.js +0 -146
  174. package/scripts/lib/package-content-audit.js +0 -368
  175. package/scripts/lib/package-runtime.js +0 -278
  176. package/scripts/lib/plan-surface.js +0 -53
  177. package/scripts/lib/plans.js +0 -2318
  178. package/scripts/lib/policy-provider.js +0 -27
  179. package/scripts/lib/prelaunch-activation-readiness.js +0 -409
  180. package/scripts/lib/prelaunch-evidence-store.js +0 -816
  181. package/scripts/lib/prelaunch-intelligence.js +0 -869
  182. package/scripts/lib/pricing-experiment.js +0 -118
  183. package/scripts/lib/pro-moment-events.js +0 -77
  184. package/scripts/lib/pro-moment-state.js +0 -227
  185. package/scripts/lib/pro-moments.js +0 -1216
  186. package/scripts/lib/product-learning-events.js +0 -629
  187. package/scripts/lib/project-profile.js +0 -555
  188. package/scripts/lib/prompt-compiler.js +0 -280
  189. package/scripts/lib/prompt-lint.js +0 -32
  190. package/scripts/lib/prompt-suggestions.js +0 -52
  191. package/scripts/lib/proof-canonical.js +0 -398
  192. package/scripts/lib/proof-drilldown.js +0 -383
  193. package/scripts/lib/proof-events.js +0 -342
  194. package/scripts/lib/proof-history.js +0 -243
  195. package/scripts/lib/proof-metrics.js +0 -296
  196. package/scripts/lib/proof-outcome-evidence.js +0 -134
  197. package/scripts/lib/proof-receipt.js +0 -335
  198. package/scripts/lib/proof-record.js +0 -461
  199. package/scripts/lib/public-activation-distribution-gate.js +0 -258
  200. package/scripts/lib/public-cli.js +0 -3891
  201. package/scripts/lib/public-distribution-truth.js +0 -211
  202. package/scripts/lib/public-install-claim-checker.js +0 -294
  203. package/scripts/lib/publish-provenance-readiness.js +0 -283
  204. package/scripts/lib/readiness-delta.js +0 -218
  205. package/scripts/lib/readiness-evidence-closure.js +0 -196
  206. package/scripts/lib/reentry-memory-capture.js +0 -241
  207. package/scripts/lib/reentry-memory-retrieval.js +0 -302
  208. package/scripts/lib/reentry-memory-status.js +0 -146
  209. package/scripts/lib/reentry-memory-store.js +0 -178
  210. package/scripts/lib/reentry-state.js +0 -66
  211. package/scripts/lib/release-candidate-bundle.js +0 -166
  212. package/scripts/lib/remediation.js +0 -81
  213. package/scripts/lib/repo-map.js +0 -391
  214. package/scripts/lib/run-improvements-lifecycle.js +0 -330
  215. package/scripts/lib/run-improvements.js +0 -789
  216. package/scripts/lib/runtime-decision-policy.js +0 -387
  217. package/scripts/lib/safe-path-engine.js +0 -705
  218. package/scripts/lib/safe-run-controller.js +0 -887
  219. package/scripts/lib/score.js +0 -262
  220. package/scripts/lib/seamless-enforcement.js +0 -329
  221. package/scripts/lib/seamless-outcome.js +0 -689
  222. package/scripts/lib/seamless-reality-gate.js +0 -5043
  223. package/scripts/lib/security-risk-classifier.js +0 -511
  224. package/scripts/lib/security-scan.js +0 -384
  225. package/scripts/lib/session-context-optimizer.js +0 -1211
  226. package/scripts/lib/session-timing.js +0 -315
  227. package/scripts/lib/skill-hygiene.js +0 -805
  228. package/scripts/lib/skill-packs.js +0 -161
  229. package/scripts/lib/skills-operating-layer.js +0 -580
  230. package/scripts/lib/smart-work-routing.js +0 -768
  231. package/scripts/lib/source-catalog.js +0 -700
  232. package/scripts/lib/status-value-summary.js +0 -32
  233. package/scripts/lib/support-bundle.js +0 -578
  234. package/scripts/lib/task-continuation.js +0 -440
  235. package/scripts/lib/test-helpers.js +0 -15
  236. package/scripts/lib/tier.js +0 -38
  237. package/scripts/lib/token-context-quality-gate.js +0 -370
  238. package/scripts/lib/token-cost-capture.js +0 -187
  239. package/scripts/lib/token-cost-intelligence.js +0 -358
  240. package/scripts/lib/token-efficiency-evidence.js +0 -213
  241. package/scripts/lib/token-evidence.js +0 -699
  242. package/scripts/lib/tokenish.js +0 -17
  243. package/scripts/lib/tool-output-sandbox.js +0 -304
  244. package/scripts/lib/trust-audit.js +0 -136
  245. package/scripts/lib/unified-events.js +0 -396
  246. package/scripts/lib/upgrade-interruption-recovery.js +0 -407
  247. package/scripts/lib/usage-ledger.js +0 -201
  248. package/scripts/lib/value-ledger.js +0 -130
  249. package/scripts/lib/value-proof-calibration.js +0 -531
  250. package/scripts/lib/visual-qa.js +0 -231
  251. package/scripts/lib/voice-alpha.js +0 -29
  252. package/scripts/lib/work-aware-orchestration.js +0 -976
  253. package/scripts/lib/work-control-receipts.js +0 -577
  254. package/scripts/lib/work-ledger.js +0 -1123
  255. package/scripts/lib/work-panel-preview.js +0 -352
  256. package/scripts/lib/workflow-discipline.js +0 -280
  257. package/scripts/lib/workflow-signals.js +0 -419
  258. package/scripts/lib/workspace-map.js +0 -281
  259. package/scripts/lib/workspace-registry.js +0 -1367
  260. package/scripts/lib/workspace-resolver.js +0 -480
@@ -1,1499 +0,0 @@
1
- "use strict";
2
-
3
- // ── AI Workspace Hygiene + Capability Registry v1 ────────────────────────────
4
- //
5
- // Contract: avorelo.aiWorkspaceHygiene.v1
6
- //
7
- // Scans repo-local AI workspace files, normalizes them into a capability
8
- // registry layer, derives hygiene findings, and writes a compact receipt.
9
- //
10
- // Rules:
11
- // - Deterministic, local-first, no network, no LLM, no package-registry calls
12
- // - No execution of scripts/MCP tools
13
- // - No scanning outside repo root
14
- // - Redact secrets and sensitive values
15
- // - Default output compact; debug exposes asset detail
16
- // - Do not auto-patch user files; recommend cleanup only
17
- // - OpenHands is a reference architecture, not an installed adapter
18
-
19
- const fs = require("fs");
20
- const path = require("path");
21
- const crypto = require("crypto");
22
- const { ensureCcoDirs, nowIso, safeReadJson, safeWriteJson } = require("./fsx");
23
- const { appendProductLearningEvent } = require("./product-learning-events");
24
-
25
- // ── Constants ─────────────────────────────────────────────────────────────────
26
-
27
- const HYGIENE_CONTRACT = "avorelo.aiWorkspaceHygiene.v1";
28
- const HYGIENE_SCHEMA_VERSION = 1;
29
- const LATEST_REPORT_REL = ".claude/cco/orchestration/ai-workspace-hygiene/latest-report.json";
30
- const LATEST_DEBUG_REPORT_REL = ".claude/cco/orchestration/ai-workspace-hygiene/latest-report-debug.json";
31
- const HYGIENE_HISTORY_DIR_REL = ".claude/cco/orchestration/ai-workspace-hygiene/history";
32
- const HYGIENE_EVENT_LOG_REL = ".claude/cco/events/ai-workspace-hygiene.jsonl";
33
-
34
- const SKIP_DIRS = new Set([
35
- ".git", "node_modules", "dist", "build", "coverage",
36
- ".next", ".turbo", ".cache", ".wasp", ".avorelo",
37
- ]);
38
-
39
- const VALID_ASSET_TYPES = new Set([
40
- "agent_instruction", "claude_instruction", "codex_instruction",
41
- "gemini_instruction", "cursor_rule", "copilot_instruction",
42
- "skill", "skill_pack", "mcp_config", "mcp_server", "mcp_tool",
43
- "hook_config", "lifecycle_hook", "plugin_package",
44
- "package_script", "context_pack", "proof_gate", "adapter_config",
45
- "unknown_ai_asset",
46
- ]);
47
-
48
- const VALID_STATUSES = new Set(["ready", "needs_review", "deferred", "blocked", "unknown"]);
49
- const VALID_TRUST_LEVELS = new Set(["high", "medium", "low", "unknown"]);
50
- const VALID_REVIEW_STATUSES = new Set(["reviewed", "known", "unknown", "deferred", "blocked"]);
51
- const VALID_RISK_LEVELS = new Set(["low", "medium", "high", "critical", "unknown"]);
52
- const VALID_CONTEXT_COSTS = new Set(["none", "low", "medium", "high", "unknown"]);
53
-
54
- const VALID_SCOPES = new Set([
55
- "repo", "file", "directory", "network", "browser",
56
- "secrets", "command", "deploy", "unknown",
57
- ]);
58
-
59
- const VALID_CAPABILITIES = new Set([
60
- "read", "write", "execute", "network", "browser",
61
- "secrets", "deploy", "proof", "context", "routing", "unknown",
62
- ]);
63
-
64
- const VALID_LIFECYCLE_STAGES = new Set([
65
- "session_start", "prompt_submit", "pre_tool_use", "post_tool_use",
66
- "stop", "session_end", "manual", "unknown",
67
- ]);
68
-
69
- const VALID_STAGE_HINTS = new Set([
70
- "inspect", "plan", "implement", "verify",
71
- "review", "handoff", "summarize", "debug",
72
- ]);
73
-
74
- const VALID_WORKER_HINTS = new Set([
75
- "local_or_cheap", "strong_model", "local_test_runner",
76
- "human_approval", "reviewed_tool", "none",
77
- ]);
78
-
79
- // Finding codes
80
- const FINDING_CODES = Object.freeze({
81
- DUPLICATE_INSTRUCTION_SURFACE: "DUPLICATE_INSTRUCTION_SURFACE",
82
- CONFLICTING_INSTRUCTION_SURFACES: "CONFLICTING_INSTRUCTION_SURFACES",
83
- HIGH_CONTEXT_COST_ASSET: "HIGH_CONTEXT_COST_ASSET",
84
- MISSING_SKILL_TRIGGERS: "MISSING_SKILL_TRIGGERS",
85
- MISSING_STAGE_HINTS: "MISSING_STAGE_HINTS",
86
- UNKNOWN_SOURCE: "UNKNOWN_SOURCE",
87
- UNKNOWN_MCP_SERVER: "UNKNOWN_MCP_SERVER",
88
- BROAD_MCP_TOOL_CAPABILITY: "BROAD_MCP_TOOL_CAPABILITY",
89
- RISKY_PACKAGE_SCRIPT: "RISKY_PACKAGE_SCRIPT",
90
- SECRET_LIKE_REFERENCE: "SECRET_LIKE_REFERENCE",
91
- EXTERNAL_DOMAIN_REFERENCE: "EXTERNAL_DOMAIN_REFERENCE",
92
- MISSING_PROOF_GATE: "MISSING_PROOF_GATE",
93
- STALE_OR_UNREFERENCED_SKILL: "STALE_OR_UNREFERENCED_SKILL",
94
- FULL_SKILL_BODY_RISK: "FULL_SKILL_BODY_RISK",
95
- ADAPTER_CORE_LOGIC_LEAKAGE: "ADAPTER_CORE_LOGIC_LEAKAGE",
96
- UNKNOWN_HOOK_STAGE: "UNKNOWN_HOOK_STAGE",
97
- });
98
-
99
- // ── Helpers ───────────────────────────────────────────────────────────────────
100
-
101
- function sha256Short(value) {
102
- return crypto.createHash("sha256").update(String(value || "")).digest("hex").slice(0, 12);
103
- }
104
-
105
- function unique(values) {
106
- return [...new Set((values || []).filter(Boolean))];
107
- }
108
-
109
- function normalizeSlash(value) {
110
- return String(value || "").replace(/\\/g, "/");
111
- }
112
-
113
- function safeReadFile(absPath, maxBytes = 32768) {
114
- try {
115
- if (!fs.existsSync(absPath)) return null;
116
- const stat = fs.statSync(absPath);
117
- if (stat.size > maxBytes) return null;
118
- return fs.readFileSync(absPath, "utf8");
119
- } catch {
120
- return null;
121
- }
122
- }
123
-
124
- function safeReadDir(absPath) {
125
- try {
126
- return fs.readdirSync(absPath, { withFileTypes: true });
127
- } catch {
128
- return [];
129
- }
130
- }
131
-
132
- function safeStatSize(absPath) {
133
- try {
134
- return fs.statSync(absPath).size;
135
- } catch {
136
- return 0;
137
- }
138
- }
139
-
140
- function redactSecrets(text) {
141
- return String(text || "")
142
- .replace(/sk-[A-Za-z0-9]{16,}/g, "[redacted]")
143
- .replace(/ghp_[A-Za-z0-9]{20,}/g, "[redacted]")
144
- .replace(/AKIA[0-9A-Z]{16}/g, "[redacted]")
145
- .replace(/((?:api[_ -]?key|token|password|secret|authorization)\s*[:=]\s*)([^\s'"]+)/ig, "$1[redacted]");
146
- }
147
-
148
- function hasSecretLike(text) {
149
- return /\b(api[_ -]?key|token|password|secret|authorization|credential)\s*[:=]\s*[^\s'"]+/i.test(String(text || ""));
150
- }
151
-
152
- function hasExternalDomain(text) {
153
- return /https?:\/\/(?!localhost|127\.0\.0\.1|::1)[^\s)'"`,]+/i.test(String(text || ""));
154
- }
155
-
156
- function hasPolicyBypass(text) {
157
- const val = String(text || "");
158
- return /\b(ignore|bypass|disable|remove)\b[^\n]{0,120}\b(policy|guard|audit|proof|tests?|verification)\b/i.test(val);
159
- }
160
-
161
- function hasAdapterCoreLogicLeak(text) {
162
- const markers = [
163
- "sourceTrustLevel", "reviewStatus", "The Five-Axis Review",
164
- "Write a failing test before writing the code",
165
- "source-backed skill/reference inventory",
166
- ];
167
- const val = String(text || "");
168
- return val.length > 1200 && markers.some((marker) => val.includes(marker));
169
- }
170
-
171
- function contextCostFromSize(bytes) {
172
- if (bytes <= 512) return "none";
173
- if (bytes <= 4096) return "low";
174
- if (bytes <= 16384) return "medium";
175
- return "high";
176
- }
177
-
178
- function maxRiskLevel(a, b) {
179
- const order = { low: 1, medium: 2, high: 3, critical: 4, unknown: 0 };
180
- return (order[a] || 0) >= (order[b] || 0) ? a : b;
181
- }
182
-
183
- function assetId(type, relPath, name) {
184
- return `ws-asset-${sha256Short([type, relPath, name].join("|"))}`;
185
- }
186
-
187
- // ── Asset Builder ─────────────────────────────────────────────────────────────
188
-
189
- function buildAsset(input) {
190
- const type = VALID_ASSET_TYPES.has(input.type) ? input.type : "unknown_ai_asset";
191
- const status = VALID_STATUSES.has(input.status) ? input.status : "unknown";
192
- const trustLevel = VALID_TRUST_LEVELS.has(input.trustLevel) ? input.trustLevel : "unknown";
193
- const reviewStatus = VALID_REVIEW_STATUSES.has(input.reviewStatus) ? input.reviewStatus : "unknown";
194
- const riskLevel = VALID_RISK_LEVELS.has(input.riskLevel) ? input.riskLevel : "unknown";
195
- const contextCost = VALID_CONTEXT_COSTS.has(input.contextCost) ? input.contextCost : "unknown";
196
-
197
- return {
198
- id: input.id || assetId(type, input.path || "", input.name || ""),
199
- type,
200
- name: redactSecrets(String(input.name || type)),
201
- path: normalizeSlash(input.path || ""),
202
- source: String(input.source || "local"),
203
- host: String(input.host || "local"),
204
- status,
205
- trustLevel,
206
- reviewStatus,
207
- riskLevel,
208
- contextCost,
209
- scope: unique((input.scope || ["unknown"]).filter((s) => VALID_SCOPES.has(s))),
210
- capabilities: unique((input.capabilities || ["unknown"]).filter((c) => VALID_CAPABILITIES.has(c))),
211
- lifecycleStage: VALID_LIFECYCLE_STAGES.has(input.lifecycleStage) ? input.lifecycleStage : "unknown",
212
- stageHints: unique((input.stageHints || []).filter((h) => VALID_STAGE_HINTS.has(h))),
213
- workerHints: unique((input.workerHints || ["none"]).filter((h) => VALID_WORKER_HINTS.has(h))),
214
- proofValue: String(input.proofValue || "unknown"),
215
- safetyControls: unique(input.safetyControls || []),
216
- reasonCodes: unique(input.reasonCodes || []),
217
- warnings: (input.warnings || []).map((w) => ({ code: w.code, message: redactSecrets(w.message || "") })),
218
- recommendedAction: redactSecrets(String(input.recommendedAction || "")),
219
- customerVisible: input.customerVisible !== false,
220
- debugVisible: input.debugVisible !== false,
221
- orchestrationReady: Boolean(input.orchestrationReady),
222
- redacted: true,
223
- };
224
- }
225
-
226
- // ── Scanner: Root AI instructions ─────────────────────────────────────────────
227
-
228
- function scanRootInstructions(cwd) {
229
- const candidates = [
230
- { file: "AGENTS.md", type: "agent_instruction", host: "claude-code" },
231
- { file: "CLAUDE.md", type: "claude_instruction", host: "claude-code" },
232
- { file: "GEMINI.md", type: "gemini_instruction", host: "gemini-cli" },
233
- ];
234
- return candidates
235
- .filter(({ file }) => fs.existsSync(path.join(cwd, file)))
236
- .map(({ file, type, host }) => {
237
- const absPath = path.join(cwd, file);
238
- const size = safeStatSize(absPath);
239
- const content = safeReadFile(absPath);
240
- const warnings = [];
241
- if (content && hasPolicyBypass(content)) warnings.push({ code: "GUIDANCE_POLICY_BYPASS", message: "Guidance includes policy-bypass language." });
242
- if (content && hasSecretLike(content)) warnings.push({ code: "SECRET_LIKE_REFERENCE", message: "Guidance may reference secrets or credentials." });
243
- if (content && hasExternalDomain(content)) warnings.push({ code: "EXTERNAL_BROWSER_DOMAIN", message: "Guidance references external domain." });
244
- if (content && hasAdapterCoreLogicLeak(content)) warnings.push({ code: "ADAPTER_CORE_LOGIC_LEAKAGE", message: "Instruction file looks too heavy and may leak internal policy." });
245
- return buildAsset({
246
- type,
247
- name: file,
248
- path: file,
249
- source: "local_repo",
250
- host,
251
- status: warnings.length ? "needs_review" : "ready",
252
- trustLevel: "medium",
253
- reviewStatus: "known",
254
- riskLevel: warnings.some((w) => ["GUIDANCE_POLICY_BYPASS", "SECRET_LIKE_REFERENCE"].includes(w.code)) ? "high" : "low",
255
- contextCost: contextCostFromSize(size),
256
- scope: ["repo"],
257
- capabilities: ["read", "context"],
258
- lifecycleStage: "session_start",
259
- stageHints: ["inspect", "plan"],
260
- workerHints: ["local_or_cheap"],
261
- proofValue: "low",
262
- safetyControls: ["instruction_risk_review"],
263
- reasonCodes: unique(warnings.map((w) => w.code)),
264
- warnings,
265
- recommendedAction: warnings.length
266
- ? "Review this instruction file for policy-bypass language, secret references, or external domain links."
267
- : "Keep instruction bounded and review before sharing.",
268
- customerVisible: false,
269
- debugVisible: true,
270
- orchestrationReady: true,
271
- });
272
- });
273
- }
274
-
275
- // ── Scanner: Editor/Agent instructions ───────────────────────────────────────
276
-
277
- function scanEditorInstructions(cwd) {
278
- const assets = [];
279
-
280
- // Cursor rules
281
- const cursorRulesDir = path.join(cwd, ".cursor", "rules");
282
- if (fs.existsSync(cursorRulesDir)) {
283
- for (const entry of safeReadDir(cursorRulesDir)) {
284
- if (!entry.isFile()) continue;
285
- const filePath = normalizeSlash(path.relative(cwd, path.join(cursorRulesDir, entry.name)));
286
- const absPath = path.join(cwd, filePath);
287
- const size = safeStatSize(absPath);
288
- const content = safeReadFile(absPath);
289
- const warnings = [];
290
- if (content && hasSecretLike(content)) warnings.push({ code: "SECRET_LIKE_REFERENCE", message: "Cursor rule references secret-like value." });
291
- if (content && hasAdapterCoreLogicLeak(content)) warnings.push({ code: "ADAPTER_CORE_LOGIC_LEAKAGE", message: "Cursor rule is too heavy and may leak internal policy." });
292
- assets.push(buildAsset({
293
- type: "cursor_rule",
294
- name: entry.name,
295
- path: filePath,
296
- source: "local_repo",
297
- host: "cursor",
298
- status: warnings.length ? "needs_review" : "ready",
299
- trustLevel: "medium",
300
- reviewStatus: "known",
301
- riskLevel: warnings.length ? "medium" : "low",
302
- contextCost: contextCostFromSize(size),
303
- scope: ["repo"],
304
- capabilities: ["read", "context"],
305
- lifecycleStage: "session_start",
306
- stageHints: ["inspect", "plan"],
307
- workerHints: ["local_or_cheap"],
308
- proofValue: "low",
309
- warnings,
310
- reasonCodes: unique(warnings.map((w) => w.code)),
311
- recommendedAction: warnings.length ? "Review cursor rule for leaked policy." : "Keep cursor rule compact.",
312
- customerVisible: false,
313
- debugVisible: true,
314
- orchestrationReady: true,
315
- }));
316
- }
317
- }
318
-
319
- // Copilot instructions
320
- const copilotCandidates = [
321
- ".github/copilot-instructions.md",
322
- ];
323
- // .github/instructions/*.instructions.md
324
- const ghInstructionsDir = path.join(cwd, ".github", "instructions");
325
- if (fs.existsSync(ghInstructionsDir)) {
326
- for (const entry of safeReadDir(ghInstructionsDir)) {
327
- if (entry.isFile() && entry.name.endsWith(".instructions.md")) {
328
- copilotCandidates.push(normalizeSlash(path.relative(cwd, path.join(ghInstructionsDir, entry.name))));
329
- }
330
- }
331
- }
332
-
333
- for (const relFile of copilotCandidates) {
334
- if (!fs.existsSync(path.join(cwd, relFile))) continue;
335
- const absPath = path.join(cwd, relFile);
336
- const size = safeStatSize(absPath);
337
- const content = safeReadFile(absPath);
338
- const warnings = [];
339
- if (content && hasSecretLike(content)) warnings.push({ code: "SECRET_LIKE_REFERENCE", message: "Copilot instruction references secret-like value." });
340
- if (content && hasAdapterCoreLogicLeak(content)) warnings.push({ code: "ADAPTER_CORE_LOGIC_LEAKAGE", message: "Copilot instruction is too heavy." });
341
- assets.push(buildAsset({
342
- type: "copilot_instruction",
343
- name: path.basename(relFile),
344
- path: relFile,
345
- source: "local_repo",
346
- host: "github-copilot",
347
- status: warnings.length ? "needs_review" : "ready",
348
- trustLevel: "medium",
349
- reviewStatus: "known",
350
- riskLevel: warnings.length ? "medium" : "low",
351
- contextCost: contextCostFromSize(size),
352
- scope: ["repo"],
353
- capabilities: ["read", "context"],
354
- lifecycleStage: "session_start",
355
- stageHints: ["inspect"],
356
- workerHints: ["local_or_cheap"],
357
- proofValue: "low",
358
- warnings,
359
- reasonCodes: unique(warnings.map((w) => w.code)),
360
- recommendedAction: "Keep copilot instruction bounded and reviewed.",
361
- customerVisible: false,
362
- debugVisible: true,
363
- orchestrationReady: false,
364
- }));
365
- }
366
-
367
- return assets;
368
- }
369
-
370
- // ── Scanner: .claude / .openhands config dirs ─────────────────────────────────
371
-
372
- function scanAgentConfigDirs(cwd) {
373
- const assets = [];
374
- const dirs = [
375
- { dir: ".claude", host: "claude-code", type: "claude_instruction" },
376
- { dir: ".openhands", host: "openhands", type: "agent_instruction" },
377
- ];
378
-
379
- for (const { dir, host, type } of dirs) {
380
- const absDir = path.join(cwd, dir);
381
- if (!fs.existsSync(absDir)) continue;
382
-
383
- // Only scan metadata/config-like files; skip generated receipts/large artifacts
384
- const CONFIG_EXTENSIONS = new Set([".json", ".yaml", ".yml", ".toml", ".md"]);
385
- const MAX_CONFIG_BYTES = 16384;
386
-
387
- function walkDir(absPath, relBase) {
388
- const entries = safeReadDir(absPath);
389
- for (const entry of entries) {
390
- const entryAbs = path.join(absPath, entry.name);
391
- const entryRel = normalizeSlash(path.join(relBase, entry.name));
392
- if (entry.isDirectory()) {
393
- // Skip large generated subdirs
394
- if (["cco", "receipts", "history", "events", "runs", "reports", "state", "orchestration"].includes(entry.name)) continue;
395
- walkDir(entryAbs, entryRel);
396
- continue;
397
- }
398
- const ext = path.extname(entry.name).toLowerCase();
399
- if (!CONFIG_EXTENSIONS.has(ext)) continue;
400
- const size = safeStatSize(entryAbs);
401
- if (size > MAX_CONFIG_BYTES) continue;
402
- const content = safeReadFile(entryAbs, MAX_CONFIG_BYTES);
403
- const warnings = [];
404
- if (content && hasSecretLike(content)) warnings.push({ code: "SECRET_LIKE_REFERENCE", message: `${dir} config references secret-like value.` });
405
- assets.push(buildAsset({
406
- type,
407
- name: entry.name,
408
- path: entryRel,
409
- source: "local_repo",
410
- host,
411
- status: "ready",
412
- trustLevel: host === "claude-code" ? "high" : "medium",
413
- reviewStatus: "known",
414
- riskLevel: warnings.length ? "medium" : "low",
415
- contextCost: contextCostFromSize(size),
416
- scope: ["repo"],
417
- capabilities: ["read", "context"],
418
- lifecycleStage: "session_start",
419
- stageHints: ["inspect"],
420
- workerHints: ["local_or_cheap"],
421
- proofValue: "medium",
422
- warnings,
423
- reasonCodes: unique(warnings.map((w) => w.code)),
424
- recommendedAction: warnings.length ? "Review config file for leaked secrets." : "Keep config bounded.",
425
- customerVisible: false,
426
- debugVisible: true,
427
- orchestrationReady: host === "claude-code",
428
- }));
429
- }
430
- }
431
-
432
- walkDir(absDir, dir);
433
- }
434
-
435
- return assets;
436
- }
437
-
438
- // ── Scanner: Skills ───────────────────────────────────────────────────────────
439
-
440
- function scanSkills(cwd) {
441
- const assets = [];
442
- const skillsDirs = [
443
- { dir: "skills", host: "avorelo", reviewStatus: "reviewed", trustLevel: "high" },
444
- { dir: "vendor/skillpacks", host: "vendor", reviewStatus: "known", trustLevel: "medium" },
445
- ];
446
-
447
- for (const { dir, host, reviewStatus, trustLevel } of skillsDirs) {
448
- const absDir = path.join(cwd, dir);
449
- if (!fs.existsSync(absDir)) continue;
450
-
451
- function walkForSkills(absPath, relBase) {
452
- const entries = safeReadDir(absPath);
453
- let foundPackMeta = false;
454
-
455
- for (const entry of entries) {
456
- const entryAbs = path.join(absPath, entry.name);
457
- const entryRel = normalizeSlash(path.join(relBase, entry.name));
458
-
459
- if (entry.isDirectory()) {
460
- if (SKIP_DIRS.has(entry.name)) continue;
461
- walkForSkills(entryAbs, entryRel);
462
- continue;
463
- }
464
-
465
- // Detect skill pack metadata
466
- if (entry.name === "SOURCE.json" || entry.name === "MANIFEST.json") {
467
- foundPackMeta = true;
468
- const size = safeStatSize(entryAbs);
469
- assets.push(buildAsset({
470
- type: "skill_pack",
471
- name: path.basename(relBase),
472
- path: entryRel,
473
- source: host === "vendor" ? "vendor_skill_pack" : "local_skill_pack",
474
- host,
475
- status: "ready",
476
- trustLevel,
477
- reviewStatus,
478
- riskLevel: "low",
479
- contextCost: contextCostFromSize(size),
480
- scope: ["repo"],
481
- capabilities: ["read", "context", "routing"],
482
- lifecycleStage: "prompt_submit",
483
- stageHints: ["inspect", "plan", "implement"],
484
- workerHints: ["local_or_cheap"],
485
- proofValue: "medium",
486
- warnings: [],
487
- reasonCodes: [],
488
- recommendedAction: "Verify skill pack source and trust level before use.",
489
- customerVisible: false,
490
- debugVisible: true,
491
- orchestrationReady: true,
492
- }));
493
- continue;
494
- }
495
-
496
- // Detect individual skill files
497
- if (!/\.(md|yaml|yml|json)$/i.test(entry.name)) continue;
498
- const size = safeStatSize(entryAbs);
499
- const content = safeReadFile(entryAbs, 4096);
500
- const warnings = [];
501
- const hasTrigger = content && /trigger|when|task_type|activation/i.test(content);
502
- const hasStageHint = content && /stage|phase|step|workflow/i.test(content);
503
-
504
- if (!hasTrigger) warnings.push({ code: FINDING_CODES.MISSING_SKILL_TRIGGERS, message: "Skill file has no clear trigger or activation condition." });
505
- if (!hasStageHint) warnings.push({ code: FINDING_CODES.MISSING_STAGE_HINTS, message: "Skill file has no stage or workflow hints." });
506
- if (size > 8192) warnings.push({ code: FINDING_CODES.FULL_SKILL_BODY_RISK, message: "Skill file is large; loading full body risks high context cost." });
507
- if (content && hasAdapterCoreLogicLeak(content)) warnings.push({ code: FINDING_CODES.ADAPTER_CORE_LOGIC_LEAKAGE, message: "Skill file may contain adapter or core logic that should not be exposed." });
508
-
509
- assets.push(buildAsset({
510
- type: "skill",
511
- name: entry.name,
512
- path: entryRel,
513
- source: host === "vendor" ? "vendor_skill_pack" : "local_skill_pack",
514
- host,
515
- status: warnings.some((w) => ["FULL_SKILL_BODY_RISK", "ADAPTER_CORE_LOGIC_LEAKAGE"].includes(w.code)) ? "needs_review" : "ready",
516
- trustLevel,
517
- reviewStatus,
518
- riskLevel: size > 16384 ? "medium" : "low",
519
- contextCost: contextCostFromSize(size),
520
- scope: ["repo"],
521
- capabilities: ["read", "context"],
522
- lifecycleStage: "prompt_submit",
523
- stageHints: hasTrigger ? ["plan", "implement"] : [],
524
- workerHints: hasTrigger ? ["local_or_cheap"] : ["none"],
525
- proofValue: "low",
526
- warnings,
527
- reasonCodes: unique(warnings.map((w) => w.code)),
528
- recommendedAction: warnings.length
529
- ? "Add activation triggers, stage hints, and keep skill compact."
530
- : "Keep skill focused and lazy-loaded.",
531
- customerVisible: false,
532
- debugVisible: true,
533
- orchestrationReady: Boolean(hasTrigger && hasStageHint),
534
- }));
535
- }
536
- }
537
-
538
- walkForSkills(absDir, dir);
539
- }
540
-
541
- return assets;
542
- }
543
-
544
- // ── Scanner: MCP configs ──────────────────────────────────────────────────────
545
-
546
- function parseMcpJson(absPath) {
547
- try {
548
- if (!fs.existsSync(absPath)) return null;
549
- return JSON.parse(fs.readFileSync(absPath, "utf8"));
550
- } catch {
551
- return null;
552
- }
553
- }
554
-
555
- function mcpServersFromParsed(parsed) {
556
- if (!parsed || typeof parsed !== "object") return [];
557
- if (parsed.mcpServers && typeof parsed.mcpServers === "object") {
558
- return Object.entries(parsed.mcpServers).map(([name, value]) => ({ name, value }));
559
- }
560
- if (parsed.servers && typeof parsed.servers === "object") {
561
- return Object.entries(parsed.servers).map(([name, value]) => ({ name, value }));
562
- }
563
- return [];
564
- }
565
-
566
- function detectMcpCapabilities(serverConfig) {
567
- const text = JSON.stringify(serverConfig || {});
568
- const caps = [];
569
- if (/write|patch|delete|mutate|edit|create/i.test(text)) caps.push("write");
570
- if (/http|https|fetch|network|url/i.test(text)) caps.push("network");
571
- if (/command|shell|exec|spawn|terminal/i.test(text)) caps.push("execute");
572
- if (/browser|playwright|chrome|devtools/i.test(text)) caps.push("browser");
573
- if (/secret|token|credential|env/i.test(text)) caps.push("secrets");
574
- if (/deploy|publish|release/i.test(text)) caps.push("deploy");
575
- if (!caps.length) caps.push("read");
576
- return caps;
577
- }
578
-
579
- function scanMcpConfigs(cwd) {
580
- const assets = [];
581
- const MCP_CONFIG_CANDIDATES = [
582
- ".mcp.json",
583
- "mcp.json",
584
- ".claude/mcp.json",
585
- "mcp-config.json",
586
- "mcp-shadow.json",
587
- ];
588
-
589
- for (const relPath of MCP_CONFIG_CANDIDATES) {
590
- const absPath = path.join(cwd, relPath);
591
- if (!fs.existsSync(absPath)) continue;
592
-
593
- const parsed = parseMcpJson(absPath);
594
- const size = safeStatSize(absPath);
595
-
596
- // Emit a mcp_config asset for the config file itself
597
- assets.push(buildAsset({
598
- type: "mcp_config",
599
- name: path.basename(relPath),
600
- path: relPath,
601
- source: "local_repo",
602
- host: "local",
603
- status: "ready",
604
- trustLevel: "medium",
605
- reviewStatus: "known",
606
- riskLevel: "medium",
607
- contextCost: contextCostFromSize(size),
608
- scope: ["repo"],
609
- capabilities: ["read"],
610
- lifecycleStage: "session_start",
611
- stageHints: ["inspect"],
612
- workerHints: ["local_or_cheap"],
613
- proofValue: "medium",
614
- warnings: [],
615
- reasonCodes: [],
616
- recommendedAction: "Review MCP config servers and their tool capabilities.",
617
- customerVisible: false,
618
- debugVisible: true,
619
- orchestrationReady: false,
620
- }));
621
-
622
- // Emit mcp_server assets per server
623
- for (const { name, value } of mcpServersFromParsed(parsed)) {
624
- const caps = detectMcpCapabilities(value);
625
- const hasBroadCap = caps.some((c) => ["write", "network", "execute", "secrets", "deploy"].includes(c));
626
- const warnings = [];
627
- warnings.push({ code: FINDING_CODES.UNKNOWN_MCP_SERVER, message: `MCP server '${name}' is present without reviewed source metadata.` });
628
- if (hasBroadCap) warnings.push({ code: FINDING_CODES.BROAD_MCP_TOOL_CAPABILITY, message: `MCP server '${name}' has broad capabilities: ${caps.join(", ")}.` });
629
-
630
- assets.push(buildAsset({
631
- type: "mcp_server",
632
- name,
633
- path: relPath,
634
- source: "mcp_config",
635
- host: "local",
636
- status: "needs_review",
637
- trustLevel: "unknown",
638
- reviewStatus: "unknown",
639
- riskLevel: hasBroadCap ? "high" : "medium",
640
- contextCost: "none",
641
- scope: unique(caps.map((c) => c === "execute" ? "command" : c === "browser" ? "browser" : c === "deploy" ? "deploy" : c === "network" ? "network" : c === "secrets" ? "secrets" : "repo")),
642
- capabilities: caps,
643
- lifecycleStage: "manual",
644
- stageHints: ["inspect"],
645
- workerHints: ["human_approval"],
646
- proofValue: "low",
647
- warnings,
648
- reasonCodes: unique(warnings.map((w) => w.code)),
649
- recommendedAction: "Review MCP server source, ownership, and capabilities before trusting at runtime.",
650
- customerVisible: false,
651
- debugVisible: true,
652
- orchestrationReady: false,
653
- }));
654
- }
655
- }
656
-
657
- return assets;
658
- }
659
-
660
- // ── Scanner: Hook configs ─────────────────────────────────────────────────────
661
-
662
- function scanHookConfigs(cwd) {
663
- const assets = [];
664
- const HOOK_CONFIG_CANDIDATES = [
665
- ".claude/settings.json",
666
- ".openhands/hooks.json",
667
- ".openhands/config.yaml",
668
- ".openhands/config.json",
669
- "hooks/config.json",
670
- ];
671
-
672
- const HOOK_LIFECYCLE_PATTERNS = {
673
- PreToolUse: "pre_tool_use",
674
- PostToolUse: "post_tool_use",
675
- Stop: "stop",
676
- Notification: "session_end",
677
- UserPromptSubmit: "prompt_submit",
678
- SubagentStop: "stop",
679
- };
680
-
681
- for (const relPath of HOOK_CONFIG_CANDIDATES) {
682
- const absPath = path.join(cwd, relPath);
683
- if (!fs.existsSync(absPath)) continue;
684
- const size = safeStatSize(absPath);
685
- if (size > 32768) continue;
686
-
687
- let parsed = null;
688
- try {
689
- const content = fs.readFileSync(absPath, "utf8");
690
- parsed = JSON.parse(content);
691
- } catch {
692
- // yaml or unreadable
693
- }
694
-
695
- // Detect lifecycle stages from hook config
696
- let detectedStages = [];
697
- if (parsed && typeof parsed === "object") {
698
- const hooksObj = parsed.hooks || parsed;
699
- for (const [key, stage] of Object.entries(HOOK_LIFECYCLE_PATTERNS)) {
700
- if (hooksObj[key] !== undefined) {
701
- detectedStages.push(stage);
702
- }
703
- }
704
- }
705
-
706
- const warnings = [];
707
- if (detectedStages.length === 0) {
708
- warnings.push({ code: FINDING_CODES.UNKNOWN_HOOK_STAGE, message: `Hook config at '${relPath}' has no recognized lifecycle stage.` });
709
- detectedStages = ["unknown"];
710
- }
711
-
712
- assets.push(buildAsset({
713
- type: "hook_config",
714
- name: path.basename(relPath),
715
- path: relPath,
716
- source: "local_repo",
717
- host: relPath.includes(".openhands") ? "openhands" : "claude-code",
718
- status: "ready",
719
- trustLevel: "high",
720
- reviewStatus: "reviewed",
721
- riskLevel: "low",
722
- contextCost: contextCostFromSize(size),
723
- scope: ["repo"],
724
- capabilities: ["execute", "context"],
725
- lifecycleStage: detectedStages[0] || "unknown",
726
- stageHints: ["inspect"],
727
- workerHints: ["local_or_cheap"],
728
- proofValue: "medium",
729
- warnings,
730
- reasonCodes: unique(warnings.map((w) => w.code)),
731
- recommendedAction: "Verify hook configs install and run correctly.",
732
- customerVisible: false,
733
- debugVisible: true,
734
- orchestrationReady: true,
735
- }));
736
- }
737
-
738
- return assets;
739
- }
740
-
741
- // ── Scanner: Package scripts ──────────────────────────────────────────────────
742
-
743
- function scanPackageScripts(cwd) {
744
- const assets = [];
745
- const pkgPath = path.join(cwd, "package.json");
746
- if (!fs.existsSync(pkgPath)) return assets;
747
-
748
- let pkg = null;
749
- try {
750
- pkg = JSON.parse(fs.readFileSync(pkgPath, "utf8"));
751
- } catch {
752
- return assets;
753
- }
754
-
755
- const scripts = pkg.scripts || {};
756
- const RISKY_PATTERNS = [
757
- { re: /\b(preinstall|postinstall|prepare)\b/i, code: "INSTALL_SCRIPT_PRESENT", risk: "high" },
758
- { re: /\b(curl|wget|Invoke-WebRequest|Invoke-RestMethod)\b/i, code: "NETWORK_SCRIPT_PRESENT", risk: "high" },
759
- { re: /\b(token|secret|credential|process\.env|echo\s+\$[A-Z_]+)\b/i, code: "SECRET_EXFIL_SCRIPT", risk: "high" },
760
- { re: /\brm\s+-rf\b|\bdel\s+\/s\s+\/q\b|\brmdir\b/i, code: "DESTRUCTIVE_SCRIPT_PRESENT", risk: "critical" },
761
- { re: /\b(deploy|publish|release|npm publish|gh release)\b/i, code: "DEPLOY_SCRIPT_PRESENT", risk: "high" },
762
- ];
763
-
764
- for (const [name, command] of Object.entries(scripts)) {
765
- const commandStr = String(command || "");
766
- const matchedPatterns = RISKY_PATTERNS.filter(({ re, code }) => {
767
- if (code === "INSTALL_SCRIPT_PRESENT") return ["preinstall", "postinstall", "prepare"].includes(name.toLowerCase());
768
- return re.test(commandStr);
769
- });
770
-
771
- if (matchedPatterns.length === 0) continue;
772
-
773
- const maxRisk = matchedPatterns.reduce((r, p) => maxRiskLevel(r, p.risk), "low");
774
- const warnings = matchedPatterns.map(({ code, risk }) => ({
775
- code: FINDING_CODES.RISKY_PACKAGE_SCRIPT,
776
- message: `Script '${name}' has ${risk}-risk pattern: ${code}.`,
777
- }));
778
-
779
- assets.push(buildAsset({
780
- type: "package_script",
781
- name,
782
- path: "package.json",
783
- source: "package_manifest",
784
- host: "local",
785
- status: "needs_review",
786
- trustLevel: "medium",
787
- reviewStatus: "known",
788
- riskLevel: maxRisk,
789
- contextCost: "none",
790
- scope: ["command", ...(commandStr.match(/deploy|publish|release/i) ? ["deploy"] : []), ...(commandStr.match(/curl|wget/i) ? ["network"] : [])],
791
- capabilities: ["execute", ...(commandStr.match(/deploy|publish/i) ? ["deploy"] : []), ...(commandStr.match(/curl|wget/i) ? ["network"] : [])],
792
- lifecycleStage: "manual",
793
- stageHints: [],
794
- workerHints: ["human_approval"],
795
- proofValue: "low",
796
- warnings,
797
- reasonCodes: unique(matchedPatterns.map((p) => p.code)),
798
- recommendedAction: "Review this script before running; prefer dry-run or no-network alternatives first.",
799
- customerVisible: false,
800
- debugVisible: true,
801
- orchestrationReady: false,
802
- }));
803
- }
804
-
805
- return assets;
806
- }
807
-
808
- // ── Scanner: Avorelo context/proof metadata ───────────────────────────────────
809
-
810
- function scanAvoreloPacks(cwd) {
811
- const assets = [];
812
-
813
- // Context pack metadata
814
- const ctxPackPath = ".claude/cco/orchestration/context-optimizer/latest-pack.json";
815
- const ctxPackAbs = path.join(cwd, ctxPackPath);
816
- if (fs.existsSync(ctxPackAbs)) {
817
- const pack = parseMcpJson(ctxPackAbs);
818
- const tokenEstimate = pack?.tokenEstimate || 0;
819
- const contextCost = tokenEstimate > 8192 ? "high" : tokenEstimate > 2048 ? "medium" : tokenEstimate > 256 ? "low" : "none";
820
- const warnings = [];
821
- if (tokenEstimate > 8192) warnings.push({ code: "HIGH_CONTEXT_COST_ASSET", message: `Context pack is large (${tokenEstimate} tokens estimated).` });
822
- assets.push(buildAsset({
823
- type: "context_pack",
824
- name: "latest-pack.json",
825
- path: ctxPackPath,
826
- source: "avorelo_generated",
827
- host: "avorelo",
828
- status: "ready",
829
- trustLevel: "high",
830
- reviewStatus: "reviewed",
831
- riskLevel: "low",
832
- contextCost,
833
- scope: ["repo"],
834
- capabilities: ["context"],
835
- lifecycleStage: "prompt_submit",
836
- stageHints: ["plan", "implement"],
837
- workerHints: ["local_or_cheap"],
838
- proofValue: "medium",
839
- warnings,
840
- reasonCodes: unique(warnings.map((w) => w.code)),
841
- recommendedAction: tokenEstimate > 8192 ? "Reduce context pack size for local worker compatibility." : "Context pack is compact.",
842
- customerVisible: false,
843
- debugVisible: true,
844
- orchestrationReady: true,
845
- }));
846
- }
847
-
848
- // Proof gate metadata
849
- const proofPath = ".claude/cco/orchestration/current-proof.json";
850
- const proofAbs = path.join(cwd, proofPath);
851
- if (fs.existsSync(proofAbs)) {
852
- assets.push(buildAsset({
853
- type: "proof_gate",
854
- name: "current-proof.json",
855
- path: proofPath,
856
- source: "avorelo_generated",
857
- host: "avorelo",
858
- status: "ready",
859
- trustLevel: "high",
860
- reviewStatus: "reviewed",
861
- riskLevel: "low",
862
- contextCost: "low",
863
- scope: ["repo"],
864
- capabilities: ["proof", "context"],
865
- lifecycleStage: "stop",
866
- stageHints: ["verify", "summarize"],
867
- workerHints: ["local_or_cheap"],
868
- proofValue: "high",
869
- warnings: [],
870
- reasonCodes: [],
871
- recommendedAction: "Proof gate is active and ready.",
872
- customerVisible: false,
873
- debugVisible: true,
874
- orchestrationReady: true,
875
- }));
876
- }
877
-
878
- return assets;
879
- }
880
-
881
- // ── Main Scanner ──────────────────────────────────────────────────────────────
882
-
883
- function scanAiWorkspaceAssets(cwd) {
884
- const assets = [
885
- ...scanRootInstructions(cwd),
886
- ...scanEditorInstructions(cwd),
887
- ...scanAgentConfigDirs(cwd),
888
- ...scanSkills(cwd),
889
- ...scanMcpConfigs(cwd),
890
- ...scanHookConfigs(cwd),
891
- ...scanPackageScripts(cwd),
892
- ...scanAvoreloPacks(cwd),
893
- ];
894
- return assets;
895
- }
896
-
897
- // ── Hygiene Findings ──────────────────────────────────────────────────────────
898
-
899
- function buildHygieneFindings(assets) {
900
- const findings = [];
901
-
902
- // Duplicate instruction surfaces
903
- const instructionTypes = ["agent_instruction", "claude_instruction", "codex_instruction", "gemini_instruction"];
904
- const byType = new Map();
905
- for (const asset of assets) {
906
- if (instructionTypes.includes(asset.type)) {
907
- if (!byType.has(asset.type)) byType.set(asset.type, []);
908
- byType.get(asset.type).push(asset.name);
909
- }
910
- }
911
- for (const [type, names] of byType.entries()) {
912
- if (names.length > 1) {
913
- findings.push({
914
- code: FINDING_CODES.DUPLICATE_INSTRUCTION_SURFACE,
915
- severity: "warn",
916
- message: `Multiple ${type} files detected: ${names.join(", ")}. Only one will typically be read.`,
917
- assetNames: names,
918
- });
919
- }
920
- }
921
-
922
- // Check for conflicting agent instructions (AGENTS.md + CLAUDE.md both present)
923
- const hasAgents = assets.some((a) => a.type === "agent_instruction" && a.name === "AGENTS.md");
924
- const hasClaude = assets.some((a) => a.type === "claude_instruction" && a.name === "CLAUDE.md");
925
- if (hasAgents && hasClaude) {
926
- findings.push({
927
- code: FINDING_CODES.CONFLICTING_INSTRUCTION_SURFACES,
928
- severity: "info",
929
- message: "Both AGENTS.md and CLAUDE.md are present. These are read by different agents; verify intent is consistent.",
930
- assetNames: ["AGENTS.md", "CLAUDE.md"],
931
- });
932
- }
933
-
934
- // High context cost assets
935
- for (const asset of assets) {
936
- if (asset.contextCost === "high") {
937
- findings.push({
938
- code: FINDING_CODES.HIGH_CONTEXT_COST_ASSET,
939
- severity: "warn",
940
- message: `Asset '${asset.name}' (${asset.type}) has high context cost. Loading it always-on wastes tokens.`,
941
- assetNames: [asset.name],
942
- });
943
- }
944
- }
945
-
946
- // Skills missing triggers
947
- const skillsNoTrigger = assets.filter((a) => a.type === "skill" && a.reasonCodes.includes(FINDING_CODES.MISSING_SKILL_TRIGGERS));
948
- if (skillsNoTrigger.length > 0) {
949
- findings.push({
950
- code: FINDING_CODES.MISSING_SKILL_TRIGGERS,
951
- severity: "info",
952
- message: `${skillsNoTrigger.length} skill file(s) have no activation triggers. These may be loaded always-on.`,
953
- assetNames: skillsNoTrigger.map((a) => a.name),
954
- });
955
- }
956
-
957
- // Unknown MCP servers
958
- const unknownMcp = assets.filter((a) => a.type === "mcp_server" && a.reviewStatus === "unknown");
959
- if (unknownMcp.length > 0) {
960
- findings.push({
961
- code: FINDING_CODES.UNKNOWN_MCP_SERVER,
962
- severity: "warn",
963
- message: `${unknownMcp.length} MCP server(s) with unknown source: ${unknownMcp.map((a) => a.name).join(", ")}.`,
964
- assetNames: unknownMcp.map((a) => a.name),
965
- });
966
- }
967
-
968
- // Broad MCP tool capabilities
969
- const broadMcp = assets.filter((a) => a.type === "mcp_server" && a.reasonCodes.includes(FINDING_CODES.BROAD_MCP_TOOL_CAPABILITY));
970
- if (broadMcp.length > 0) {
971
- findings.push({
972
- code: FINDING_CODES.BROAD_MCP_TOOL_CAPABILITY,
973
- severity: "warn",
974
- message: `${broadMcp.length} MCP server(s) have broad capabilities (write/network/execute/secrets/deploy).`,
975
- assetNames: broadMcp.map((a) => a.name),
976
- });
977
- }
978
-
979
- // Risky package scripts
980
- const riskyScripts = assets.filter((a) => a.type === "package_script");
981
- if (riskyScripts.length > 0) {
982
- findings.push({
983
- code: FINDING_CODES.RISKY_PACKAGE_SCRIPT,
984
- severity: "warn",
985
- message: `${riskyScripts.length} package script(s) have deploy/network/destructive risk: ${riskyScripts.map((a) => a.name).join(", ")}.`,
986
- assetNames: riskyScripts.map((a) => a.name),
987
- });
988
- }
989
-
990
- // Secret-like references
991
- const secretRefs = assets.filter((a) => a.reasonCodes.includes(FINDING_CODES.SECRET_LIKE_REFERENCE));
992
- if (secretRefs.length > 0) {
993
- findings.push({
994
- code: FINDING_CODES.SECRET_LIKE_REFERENCE,
995
- severity: "high",
996
- message: `${secretRefs.length} asset(s) may reference secrets or credentials. Redacted in output.`,
997
- assetNames: secretRefs.map((a) => a.name),
998
- });
999
- }
1000
-
1001
- // Adapter/core logic leakage
1002
- const leakAssets = assets.filter((a) => a.reasonCodes.includes(FINDING_CODES.ADAPTER_CORE_LOGIC_LEAKAGE));
1003
- if (leakAssets.length > 0) {
1004
- findings.push({
1005
- code: FINDING_CODES.ADAPTER_CORE_LOGIC_LEAKAGE,
1006
- severity: "warn",
1007
- message: `${leakAssets.length} asset(s) appear to contain adapter or internal policy content that should not be exposed directly.`,
1008
- assetNames: leakAssets.map((a) => a.name),
1009
- });
1010
- }
1011
-
1012
- // Missing proof gate
1013
- const hasProofGate = assets.some((a) => a.type === "proof_gate");
1014
- if (!hasProofGate) {
1015
- findings.push({
1016
- code: FINDING_CODES.MISSING_PROOF_GATE,
1017
- severity: "info",
1018
- message: "No orchestration proof gate found. Run a task to establish proof coverage.",
1019
- assetNames: [],
1020
- });
1021
- }
1022
-
1023
- return findings;
1024
- }
1025
-
1026
- // ── Capability Registry Metadata ──────────────────────────────────────────────
1027
-
1028
- const CAPABILITY_REGISTRY_METADATA = Object.freeze([
1029
- {
1030
- id: "ai_workspace_hygiene_basic",
1031
- family: "ai_workspace_hygiene",
1032
- displayName: "AI Workspace Hygiene",
1033
- description: "Detect and normalize AI workspace assets for hygiene and capability metadata.",
1034
- lifecycleStages: ["session_start"],
1035
- stageHints: ["inspect"],
1036
- workerHints: ["local_or_cheap"],
1037
- riskLevel: "low",
1038
- contextCost: "low",
1039
- trustLevel: "high",
1040
- scopes: ["repo"],
1041
- capabilities: ["read", "context"],
1042
- proofValue: "medium",
1043
- safetyControls: ["local_scan_only", "no_execution", "no_network"],
1044
- autoUsable: true,
1045
- requiresApproval: false,
1046
- customerVisible: false,
1047
- debugVisible: true,
1048
- orchestrationReady: true,
1049
- adapterReady: false,
1050
- },
1051
- {
1052
- id: "ai_workspace_asset_inventory_basic",
1053
- family: "ai_workspace_hygiene",
1054
- displayName: "AI Workspace Asset Inventory",
1055
- description: "Build a normalized inventory of AI workspace assets from local repo files.",
1056
- lifecycleStages: ["session_start"],
1057
- stageHints: ["inspect"],
1058
- workerHints: ["local_or_cheap"],
1059
- riskLevel: "low",
1060
- contextCost: "low",
1061
- trustLevel: "high",
1062
- scopes: ["repo"],
1063
- capabilities: ["read", "context"],
1064
- proofValue: "medium",
1065
- safetyControls: ["local_scan_only"],
1066
- autoUsable: true,
1067
- requiresApproval: false,
1068
- customerVisible: false,
1069
- debugVisible: true,
1070
- orchestrationReady: true,
1071
- adapterReady: false,
1072
- },
1073
- {
1074
- id: "capability_registry_metadata_basic",
1075
- family: "ai_workspace_hygiene",
1076
- displayName: "Capability Registry Metadata",
1077
- description: "Enrich capability IDs with trust, scope, context-cost, stage, and worker metadata for future orchestration.",
1078
- lifecycleStages: ["session_start", "prompt_submit"],
1079
- stageHints: ["inspect", "plan"],
1080
- workerHints: ["local_or_cheap"],
1081
- riskLevel: "low",
1082
- contextCost: "low",
1083
- trustLevel: "high",
1084
- scopes: ["repo"],
1085
- capabilities: ["read", "routing"],
1086
- proofValue: "medium",
1087
- safetyControls: ["local_scan_only"],
1088
- autoUsable: true,
1089
- requiresApproval: false,
1090
- customerVisible: false,
1091
- debugVisible: true,
1092
- orchestrationReady: true,
1093
- adapterReady: false,
1094
- },
1095
- {
1096
- id: "workspace_skill_hygiene_basic",
1097
- family: "ai_workspace_hygiene",
1098
- displayName: "Workspace Skill Hygiene",
1099
- description: "Detect skill files missing triggers, stage hints, or at risk of full-body context loading.",
1100
- lifecycleStages: ["prompt_submit"],
1101
- stageHints: ["inspect"],
1102
- workerHints: ["local_or_cheap"],
1103
- riskLevel: "low",
1104
- contextCost: "low",
1105
- trustLevel: "high",
1106
- scopes: ["repo"],
1107
- capabilities: ["read", "context"],
1108
- proofValue: "low",
1109
- safetyControls: ["local_scan_only"],
1110
- autoUsable: true,
1111
- requiresApproval: false,
1112
- customerVisible: false,
1113
- debugVisible: true,
1114
- orchestrationReady: true,
1115
- adapterReady: false,
1116
- },
1117
- {
1118
- id: "instruction_surface_hygiene_basic",
1119
- family: "ai_workspace_hygiene",
1120
- displayName: "Instruction Surface Hygiene",
1121
- description: "Detect duplicate, conflicting, or overly-heavy agent instruction files.",
1122
- lifecycleStages: ["session_start"],
1123
- stageHints: ["inspect"],
1124
- workerHints: ["local_or_cheap"],
1125
- riskLevel: "low",
1126
- contextCost: "low",
1127
- trustLevel: "high",
1128
- scopes: ["repo"],
1129
- capabilities: ["read", "context"],
1130
- proofValue: "low",
1131
- safetyControls: ["local_scan_only"],
1132
- autoUsable: true,
1133
- requiresApproval: false,
1134
- customerVisible: false,
1135
- debugVisible: true,
1136
- orchestrationReady: true,
1137
- adapterReady: false,
1138
- },
1139
- {
1140
- id: "mcp_workspace_visibility_basic",
1141
- family: "ai_workspace_hygiene",
1142
- displayName: "MCP Workspace Visibility",
1143
- description: "Detect and classify MCP config files and servers without executing them.",
1144
- lifecycleStages: ["session_start"],
1145
- stageHints: ["inspect"],
1146
- workerHints: ["human_approval"],
1147
- riskLevel: "medium",
1148
- contextCost: "none",
1149
- trustLevel: "medium",
1150
- scopes: ["repo"],
1151
- capabilities: ["read"],
1152
- proofValue: "medium",
1153
- safetyControls: ["no_execution", "no_network", "local_scan_only"],
1154
- autoUsable: true,
1155
- requiresApproval: false,
1156
- customerVisible: false,
1157
- debugVisible: true,
1158
- orchestrationReady: false,
1159
- adapterReady: false,
1160
- },
1161
- {
1162
- id: "hook_surface_visibility_basic",
1163
- family: "ai_workspace_hygiene",
1164
- displayName: "Hook Surface Visibility",
1165
- description: "Detect lifecycle hook configs and classify their stage without installing or running hooks.",
1166
- lifecycleStages: ["session_start"],
1167
- stageHints: ["inspect"],
1168
- workerHints: ["local_or_cheap"],
1169
- riskLevel: "low",
1170
- contextCost: "none",
1171
- trustLevel: "high",
1172
- scopes: ["repo"],
1173
- capabilities: ["read"],
1174
- proofValue: "low",
1175
- safetyControls: ["no_execution", "local_scan_only"],
1176
- autoUsable: true,
1177
- requiresApproval: false,
1178
- customerVisible: false,
1179
- debugVisible: true,
1180
- orchestrationReady: true,
1181
- adapterReady: false,
1182
- },
1183
- {
1184
- id: "package_script_hygiene_basic",
1185
- family: "ai_workspace_hygiene",
1186
- displayName: "Package Script Hygiene",
1187
- description: "Flag risky deploy/network/destructive package scripts without running them.",
1188
- lifecycleStages: ["session_start"],
1189
- stageHints: ["inspect"],
1190
- workerHints: ["human_approval"],
1191
- riskLevel: "medium",
1192
- contextCost: "none",
1193
- trustLevel: "medium",
1194
- scopes: ["repo", "command"],
1195
- capabilities: ["read"],
1196
- proofValue: "low",
1197
- safetyControls: ["no_execution", "local_scan_only"],
1198
- autoUsable: true,
1199
- requiresApproval: false,
1200
- customerVisible: false,
1201
- debugVisible: true,
1202
- orchestrationReady: false,
1203
- adapterReady: false,
1204
- },
1205
- {
1206
- id: "orchestration_ready_capability_metadata_basic",
1207
- family: "ai_workspace_hygiene",
1208
- displayName: "Orchestration-Ready Capability Metadata",
1209
- description: "Attach workerHints, stageHints, contextCost, riskLevel, and trustLevel to capability registry entries for future orchestration.",
1210
- lifecycleStages: ["session_start", "prompt_submit"],
1211
- stageHints: ["inspect", "plan"],
1212
- workerHints: ["local_or_cheap"],
1213
- riskLevel: "low",
1214
- contextCost: "low",
1215
- trustLevel: "high",
1216
- scopes: ["repo"],
1217
- capabilities: ["read", "routing"],
1218
- proofValue: "high",
1219
- safetyControls: ["local_scan_only"],
1220
- autoUsable: true,
1221
- requiresApproval: false,
1222
- customerVisible: false,
1223
- debugVisible: true,
1224
- orchestrationReady: true,
1225
- adapterReady: false,
1226
- },
1227
- ]);
1228
-
1229
- // ── Report Builder ────────────────────────────────────────────────────────────
1230
-
1231
- function scoreFromAssets(assets, findings) {
1232
- let score = 100;
1233
- for (const f of findings) {
1234
- if (f.severity === "high") score -= 15;
1235
- else if (f.severity === "warn") score -= 8;
1236
- else if (f.severity === "info") score -= 3;
1237
- }
1238
- const unknownAssets = assets.filter((a) => a.reviewStatus === "unknown").length;
1239
- score -= Math.min(unknownAssets * 3, 20);
1240
- return Math.max(0, Math.min(100, score));
1241
- }
1242
-
1243
- function statusFromScore(score) {
1244
- if (score >= 80) return "pass";
1245
- if (score >= 50) return "warn";
1246
- return "fail";
1247
- }
1248
-
1249
- function nextActionFromFindings(findings) {
1250
- const high = findings.find((f) => f.severity === "high");
1251
- if (high) return `Address: ${high.message}`;
1252
- const warn = findings.find((f) => f.severity === "warn");
1253
- if (warn) return `Review: ${warn.message}`;
1254
- return "AI workspace hygiene is clean. Proceed with confidence.";
1255
- }
1256
-
1257
- function buildHygieneReport(cwd, options = {}) {
1258
- ensureCcoDirs(cwd);
1259
- const assets = scanAiWorkspaceAssets(cwd);
1260
- const findings = buildHygieneFindings(assets);
1261
- const score = scoreFromAssets(assets, findings);
1262
- const status = statusFromScore(score);
1263
- const isDebug = Boolean(options.debug);
1264
-
1265
- const readyAssets = assets.filter((a) => a.status === "ready");
1266
- const needsReviewAssets = assets.filter((a) => a.status === "needs_review");
1267
- const blockedAssets = assets.filter((a) => a.status === "blocked");
1268
- const unknownAssets = assets.filter((a) => a.reviewStatus === "unknown");
1269
- const highRiskAssets = assets.filter((a) => ["high", "critical"].includes(a.riskLevel));
1270
- const highContextCostAssets = assets.filter((a) => a.contextCost === "high");
1271
- const unknownMcpServers = assets.filter((a) => a.type === "mcp_server" && a.reviewStatus === "unknown");
1272
- const riskyPackageScripts = assets.filter((a) => a.type === "package_script");
1273
-
1274
- const duplicateInstructionFindings = findings.filter((f) => f.code === FINDING_CODES.DUPLICATE_INSTRUCTION_SURFACE);
1275
- const missingProofGates = findings.filter((f) => f.code === FINDING_CODES.MISSING_PROOF_GATE);
1276
-
1277
- const cleanAndReady = readyAssets.slice(0, 5).map((a) => a.name);
1278
- const needsReviewList = needsReviewAssets.slice(0, 5).map((a) => `${a.name} (${a.type})`);
1279
- const protectedList = unknownMcpServers.slice(0, 3).map((a) => `${a.name} (unknown MCP — not auto-trusted)`);
1280
-
1281
- const savedOrAvoided = [];
1282
- if (highContextCostAssets.length > 0) {
1283
- savedOrAvoided.push(`${highContextCostAssets.length} high-context-cost asset(s) kept out of automatic loading — context waste may be avoided.`);
1284
- }
1285
- if (unknownMcpServers.length > 0) {
1286
- savedOrAvoided.push(`${unknownMcpServers.length} unknown MCP server(s) isolated from auto-trust — execution risk reduced.`);
1287
- }
1288
-
1289
- const topReasonCodes = unique(
1290
- findings.flatMap((f) => [f.code])
1291
- ).slice(0, 5);
1292
-
1293
- const report = {
1294
- contract: HYGIENE_CONTRACT,
1295
- schemaVersion: HYGIENE_SCHEMA_VERSION,
1296
- createdAt: nowIso(),
1297
- status,
1298
- score,
1299
- summary: {
1300
- totalAssets: assets.length,
1301
- readyAssets: readyAssets.length,
1302
- needsReviewAssets: needsReviewAssets.length,
1303
- blockedAssets: blockedAssets.length,
1304
- unknownAssets: unknownAssets.length,
1305
- highRiskAssets: highRiskAssets.length,
1306
- highContextCostAssets: highContextCostAssets.length,
1307
- duplicateInstructionGroups: duplicateInstructionFindings.length,
1308
- unknownMcpServers: unknownMcpServers.length,
1309
- riskyPackageScripts: riskyPackageScripts.length,
1310
- missingProofGates: missingProofGates.length,
1311
- },
1312
- cleanAndReady,
1313
- needsReview: needsReviewList,
1314
- protected: protectedList,
1315
- savedOrAvoided,
1316
- nextAction: nextActionFromFindings(findings),
1317
- topReasonCodes,
1318
- debugReportPath: LATEST_DEBUG_REPORT_REL,
1319
- redacted: true,
1320
- };
1321
-
1322
- // Write compact report
1323
- safeWriteJson(cwd, LATEST_REPORT_REL, report);
1324
-
1325
- // Write debug report with full asset list
1326
- const debugReport = {
1327
- ...report,
1328
- assets: isDebug ? assets : assets.map((a) => ({
1329
- id: a.id, type: a.type, name: a.name, path: a.path,
1330
- status: a.status, riskLevel: a.riskLevel, contextCost: a.contextCost,
1331
- reviewStatus: a.reviewStatus, reasonCodes: a.reasonCodes,
1332
- })),
1333
- findings,
1334
- capabilityRegistryMetadata: CAPABILITY_REGISTRY_METADATA,
1335
- };
1336
- safeWriteJson(cwd, LATEST_DEBUG_REPORT_REL, debugReport);
1337
-
1338
- // Product-learning events
1339
- try {
1340
- appendProductLearningEvent(cwd, {
1341
- eventName: "ai_workspace_hygiene_scanned",
1342
- category: "workspace_hygiene",
1343
- surface: "local",
1344
- status: "observed",
1345
- payload: {
1346
- totalAssets: assets.length,
1347
- readyAssets: readyAssets.length,
1348
- needsReviewAssets: needsReviewAssets.length,
1349
- unknownAssets: unknownAssets.length,
1350
- highRiskAssets: highRiskAssets.length,
1351
- unknownMcpServers: unknownMcpServers.length,
1352
- riskyPackageScripts: riskyPackageScripts.length,
1353
- findingsCount: findings.length,
1354
- score,
1355
- status,
1356
- topReasonCodes,
1357
- },
1358
- });
1359
- appendProductLearningEvent(cwd, {
1360
- eventName: "ai_workspace_capability_registry_built",
1361
- category: "workspace_hygiene",
1362
- surface: "local",
1363
- status: "observed",
1364
- payload: {
1365
- capabilityCount: CAPABILITY_REGISTRY_METADATA.length,
1366
- orchestrationReadyCount: CAPABILITY_REGISTRY_METADATA.filter((c) => c.orchestrationReady).length,
1367
- },
1368
- });
1369
- } catch {
1370
- // Non-fatal
1371
- }
1372
-
1373
- return { report, assets, findings };
1374
- }
1375
-
1376
- // ── Compact Surface ───────────────────────────────────────────────────────────
1377
-
1378
- function buildAiWorkspaceHygieneSurface(cwd) {
1379
- const reportPath = path.join(cwd, LATEST_REPORT_REL);
1380
- if (!fs.existsSync(reportPath)) {
1381
- return {
1382
- status: "not_run",
1383
- score: null,
1384
- totalAssets: null,
1385
- needsReview: null,
1386
- highRisk: null,
1387
- highContextCost: null,
1388
- nextAction: "Run `avorelo workspace-hygiene` to scan the AI workspace.",
1389
- latestReportPath: null,
1390
- };
1391
- }
1392
-
1393
- let report = null;
1394
- try {
1395
- report = JSON.parse(fs.readFileSync(reportPath, "utf8"));
1396
- } catch {
1397
- return {
1398
- status: "error",
1399
- score: null,
1400
- totalAssets: null,
1401
- needsReview: null,
1402
- highRisk: null,
1403
- highContextCost: null,
1404
- nextAction: "Report file is unreadable. Re-run `avorelo workspace-hygiene`.",
1405
- latestReportPath: LATEST_REPORT_REL,
1406
- };
1407
- }
1408
-
1409
- return {
1410
- status: report.status || "unknown",
1411
- score: report.score ?? null,
1412
- totalAssets: report.summary?.totalAssets ?? null,
1413
- needsReview: report.summary?.needsReviewAssets ?? null,
1414
- highRisk: report.summary?.highRiskAssets ?? null,
1415
- highContextCost: report.summary?.highContextCostAssets ?? null,
1416
- nextAction: report.nextAction || null,
1417
- latestReportPath: LATEST_REPORT_REL,
1418
- };
1419
- }
1420
-
1421
- // ── CLI Renderers ─────────────────────────────────────────────────────────────
1422
-
1423
- function renderHygieneText(report, options = {}) {
1424
- if (!report) return "AI Workspace Hygiene: not run. Use `avorelo workspace-hygiene` to scan.\n";
1425
-
1426
- const statusEmoji = report.status === "pass" ? "✓" : report.status === "warn" ? "⚠" : "✗";
1427
- const lines = [
1428
- `AI Workspace Hygiene: ${statusEmoji} ${String(report.status).toUpperCase()} (score: ${report.score}/100)`,
1429
- "",
1430
- `Assets: ${report.summary.totalAssets} total · ${report.summary.readyAssets} ready · ${report.summary.needsReviewAssets} needs review · ${report.summary.highRiskAssets} high-risk`,
1431
- ];
1432
-
1433
- if (report.cleanAndReady.length > 0) {
1434
- lines.push(`Clean/ready: ${report.cleanAndReady.join(", ")}`);
1435
- }
1436
- if (report.needsReview.length > 0) {
1437
- lines.push(`Needs review: ${report.needsReview.join(", ")}`);
1438
- }
1439
- if (report.protected.length > 0) {
1440
- lines.push(`Protected (not auto-trusted): ${report.protected.join(", ")}`);
1441
- }
1442
- if (report.savedOrAvoided.length > 0) {
1443
- for (const s of report.savedOrAvoided) lines.push(`Saved/avoided: ${s}`);
1444
- }
1445
- lines.push("", `Next action: ${report.nextAction}`);
1446
- if (!options.debug) {
1447
- lines.push(`Full detail: avorelo workspace-hygiene --debug`);
1448
- }
1449
- lines.push("");
1450
- return lines.join("\n");
1451
- }
1452
-
1453
- function renderHygieneDebugText(report, assets, findings) {
1454
- if (!report || !assets) return "No workspace hygiene debug data available.\n";
1455
- const lines = [
1456
- `AI Workspace Hygiene — Debug Report`,
1457
- `Status: ${report.status} · Score: ${report.score}/100`,
1458
- `Assets: ${assets.length} total`,
1459
- "",
1460
- "── Asset List ──────────────────────────────────────────",
1461
- ];
1462
- for (const asset of assets) {
1463
- lines.push(` [${asset.type}] ${asset.name} (${asset.path})`);
1464
- lines.push(` status=${asset.status} risk=${asset.riskLevel} context=${asset.contextCost} trust=${asset.trustLevel}`);
1465
- if (asset.reasonCodes.length > 0) lines.push(` reasons: ${asset.reasonCodes.join(", ")}`);
1466
- if (asset.recommendedAction) lines.push(` action: ${asset.recommendedAction}`);
1467
- }
1468
- lines.push("", "── Findings ────────────────────────────────────────────");
1469
- if (findings.length === 0) {
1470
- lines.push(" No findings.");
1471
- } else {
1472
- for (const f of findings) {
1473
- lines.push(` [${f.severity.toUpperCase()}] ${f.code}: ${f.message}`);
1474
- }
1475
- }
1476
- lines.push("", "── Capability Registry Metadata ────────────────────────");
1477
- for (const cap of CAPABILITY_REGISTRY_METADATA) {
1478
- lines.push(` ${cap.id} (${cap.family}) — orchestration-ready: ${cap.orchestrationReady}`);
1479
- }
1480
- lines.push("");
1481
- return lines.join("\n");
1482
- }
1483
-
1484
- // ── Exports ───────────────────────────────────────────────────────────────────
1485
-
1486
- module.exports = {
1487
- HYGIENE_CONTRACT,
1488
- HYGIENE_SCHEMA_VERSION,
1489
- LATEST_REPORT_REL,
1490
- LATEST_DEBUG_REPORT_REL,
1491
- FINDING_CODES,
1492
- CAPABILITY_REGISTRY_METADATA,
1493
- scanAiWorkspaceAssets,
1494
- buildHygieneFindings,
1495
- buildHygieneReport,
1496
- buildAiWorkspaceHygieneSurface,
1497
- renderHygieneText,
1498
- renderHygieneDebugText,
1499
- };