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,1037 @@
1
+ "use strict";
2
+
3
+ const fs = require("fs");
4
+ const path = require("path");
5
+ const crypto = require("crypto");
6
+ const { ensureCcoDirs, nowIso, safeReadJson, safeWriteJson } = require("./fsx");
7
+ const { appendProductLearningEvent } = require("./product-learning-events");
8
+ const { buildSkillRegistry } = require("./avorelo-skill-registry");
9
+
10
+ const INSTALL_INTAKE_CONTRACT = "avorelo.installIntakeRisk.v1";
11
+ const INSTALL_INTAKE_SCHEMA_VERSION = 1;
12
+ const LATEST_INSTALL_INTAKE_RECEIPT_REL_PATH = ".claude/cco/security/install-intake/latest-receipt.json";
13
+ const INSTALL_INTAKE_HISTORY_DIR_REL_PATH = ".claude/cco/security/install-intake/history";
14
+ const INSTALL_INTAKE_EVENT_LOG_REL_PATH = ".claude/cco/events/install-intake-risk.jsonl";
15
+
16
+ const VALID_ITEM_TYPES = new Set([
17
+ "mcp_server",
18
+ "mcp_tool",
19
+ "package_dependency",
20
+ "dev_dependency",
21
+ "npm_script",
22
+ "vscode_extension",
23
+ "cursor_rule_or_extension",
24
+ "claude_or_agents_guidance",
25
+ "gemini_guidance",
26
+ "copilot_guidance",
27
+ "connector",
28
+ "skill_pack",
29
+ "browser_integration",
30
+ "unknown",
31
+ ]);
32
+
33
+ const REVIEW_STATUSES = new Set(["reviewed", "known", "unknown", "deferred", "blocked"]);
34
+ const TRUST_LEVELS = new Set(["high", "medium", "low", "unknown"]);
35
+ const RISK_LEVELS = Object.freeze(["low", "medium", "high", "critical"]);
36
+ const RISK_ORDER = Object.freeze({ low: 1, medium: 2, high: 3, critical: 4 });
37
+ const CAPABILITY_FLAGS = new Set(["read", "write", "execute", "network", "browser", "secrets", "deploy", "unknown"]);
38
+
39
+ const SKIP_DIRS = new Set([
40
+ ".git",
41
+ "node_modules",
42
+ "dist",
43
+ "build",
44
+ "coverage",
45
+ ".next",
46
+ ".turbo",
47
+ ".cache",
48
+ ".claude",
49
+ ]);
50
+
51
+ const GUIDANCE_FILE_CANDIDATES = Object.freeze([
52
+ "AGENTS.md",
53
+ "CLAUDE.md",
54
+ "GEMINI.md",
55
+ path.posix.join(".github", "copilot-instructions.md"),
56
+ ]);
57
+
58
+ const ADAPTER_POLICY_LEAK_MARKERS = Object.freeze([
59
+ "sourceTrustLevel",
60
+ "reviewStatus",
61
+ "The Five-Axis Review",
62
+ "Write a failing test before writing the code",
63
+ "source-backed skill/reference inventory",
64
+ ]);
65
+
66
+ function sha256(value) {
67
+ return crypto.createHash("sha256").update(String(value || "")).digest("hex");
68
+ }
69
+
70
+ function unique(values) {
71
+ return [...new Set((values || []).filter(Boolean))];
72
+ }
73
+
74
+ function maxRisk(left, right) {
75
+ return (RISK_ORDER[left] || 0) >= (RISK_ORDER[right] || 0) ? left : right;
76
+ }
77
+
78
+ function normalizePathValue(value) {
79
+ return String(value || "").replace(/\\/g, "/").trim();
80
+ }
81
+
82
+ function relativeRepoPath(cwd, absolutePath) {
83
+ return normalizePathValue(path.relative(cwd, absolutePath));
84
+ }
85
+
86
+ function sanitizeText(value) {
87
+ return String(value || "")
88
+ .replace(/sk-[A-Za-z0-9]{16,}/g, "[redacted-openai-key]")
89
+ .replace(/ghp_[A-Za-z0-9]{20,}/g, "[redacted-github-token]")
90
+ .replace(/AKIA[0-9A-Z]{16}/g, "[redacted-aws-key]")
91
+ .replace(/((?:api[_ -]?key|token|password|secret|authorization)\s*[:=]\s*)([^\s'"]+)/ig, "$1[redacted]");
92
+ }
93
+
94
+ function createItemId(parts) {
95
+ return `intake-${sha256(parts.filter(Boolean).join("|")).slice(0, 12)}`;
96
+ }
97
+
98
+ function createReceiptPath(cwd, relPath, payload, options = {}) {
99
+ ensureCcoDirs(cwd);
100
+ safeWriteJson(cwd, relPath, payload);
101
+ if (options.plan === "pro") {
102
+ safeWriteJson(cwd, `${INSTALL_INTAKE_HISTORY_DIR_REL_PATH}/${payload.receiptId || sha256(JSON.stringify(payload)).slice(0, 12)}.json`, payload);
103
+ }
104
+ const eventPath = path.join(cwd, INSTALL_INTAKE_EVENT_LOG_REL_PATH);
105
+ fs.mkdirSync(path.dirname(eventPath), { recursive: true });
106
+ fs.appendFileSync(eventPath, `${JSON.stringify(payload)}\n`, "utf8");
107
+ return relPath;
108
+ }
109
+
110
+ function isValidEnum(value, set, fallback) {
111
+ const normalized = String(value || "").trim().toLowerCase();
112
+ return set.has(normalized) ? normalized : fallback;
113
+ }
114
+
115
+ function walkRepo(cwd, visitor, options = {}) {
116
+ const maxDepth = Number.isFinite(Number(options.maxDepth)) ? Number(options.maxDepth) : 6;
117
+ function visit(absPath, depth) {
118
+ if (depth > maxDepth) return;
119
+ const rel = relativeRepoPath(cwd, absPath);
120
+ const stat = fs.statSync(absPath);
121
+ if (stat.isDirectory()) {
122
+ const base = path.basename(absPath);
123
+ if (SKIP_DIRS.has(base)) return;
124
+ for (const entry of fs.readdirSync(absPath, { withFileTypes: true })) {
125
+ visit(path.join(absPath, entry.name), depth + 1);
126
+ }
127
+ return;
128
+ }
129
+ visitor(absPath, rel);
130
+ }
131
+ visit(cwd, 0);
132
+ }
133
+
134
+ function findRepoFiles(cwd, predicate, options = {}) {
135
+ const files = [];
136
+ walkRepo(cwd, (absPath, relPath) => {
137
+ if (predicate(absPath, relPath)) files.push({ absPath, relPath });
138
+ }, options);
139
+ return files;
140
+ }
141
+
142
+ function capabilitySet(flags = []) {
143
+ const deduped = unique(flags.filter((flag) => CAPABILITY_FLAGS.has(flag)));
144
+ return deduped.length ? deduped : ["unknown"];
145
+ }
146
+
147
+ function packageReviewStatus(version) {
148
+ const spec = String(version || "").trim();
149
+ if (!spec) return "unknown";
150
+ if (/^(https?:|git\+|git@|github:)/i.test(spec)) return "deferred";
151
+ if (/^(file:|link:)/i.test(spec)) return "unknown";
152
+ return "known";
153
+ }
154
+
155
+ function packageTrustLevel(reviewStatus) {
156
+ if (reviewStatus === "known") return "medium";
157
+ if (reviewStatus === "reviewed") return "high";
158
+ if (reviewStatus === "blocked") return "low";
159
+ return "unknown";
160
+ }
161
+
162
+ function guidanceSignals(text) {
163
+ const signals = [];
164
+ const value = String(text || "");
165
+ if (/\b(ignore|bypass|disable|remove)\b[^\n]{0,120}\b(policy|guard|audit|proof|tests?|verification)\b/i.test(value)) {
166
+ signals.push({ code: "GUIDANCE_POLICY_BYPASS", risk: "high", message: "Guidance includes policy-bypass language." });
167
+ }
168
+ if (/\b(auto-?run|run immediately|execute automatically)\b/i.test(value)) {
169
+ signals.push({ code: "GUIDANCE_AUTO_EXECUTION", risk: "high", message: "Guidance encourages automatic execution." });
170
+ }
171
+ if (/\b(secret|token|credential|authorization|cookie|session)\b[^\n]{0,80}\b(access|reuse|read|print|upload)\b/i.test(value)) {
172
+ signals.push({ code: "GUIDANCE_SECRET_ACCESS", risk: "high", message: "Guidance implies broad secret or session access." });
173
+ }
174
+ if (ADAPTER_POLICY_LEAK_MARKERS.some((marker) => value.includes(marker)) && value.length > 1200) {
175
+ signals.push({ code: "ADAPTER_POLICY_LEAKAGE", risk: "medium", message: "Adapter or guidance file looks too heavy and leaks policy detail." });
176
+ }
177
+ return signals;
178
+ }
179
+
180
+ function browserSignals(text) {
181
+ const signals = [];
182
+ const value = String(text || "");
183
+ if (/https?:\/\/(?!localhost|127\.0\.0\.1|::1)[^\s)'"`]+/i.test(value)) {
184
+ signals.push({ code: "EXTERNAL_BROWSER_DOMAIN", risk: "medium", message: "External browser domain reference detected." });
185
+ }
186
+ if (/\b(cookie|session|localStorage|auth header|authorization)\b/i.test(value)) {
187
+ signals.push({ code: "BROWSER_SESSION_RISK", risk: "high", message: "Browser guidance references session, cookies, or auth-bearing state." });
188
+ }
189
+ if (/\b(browser|playwright|devtools|chrome|edge)\b/i.test(value) && !/localhost|127\.0\.0\.1|local preview/i.test(value)) {
190
+ signals.push({ code: "NO_LOCAL_PREVIEW_BOUNDARY", risk: "medium", message: "Browser automation is referenced without a local preview boundary." });
191
+ }
192
+ return signals;
193
+ }
194
+
195
+ function packageScriptSignals(name, command) {
196
+ const signals = [];
197
+ const text = String(command || "");
198
+ const lowerName = String(name || "").toLowerCase();
199
+ if (["preinstall", "postinstall", "prepare"].includes(lowerName)) {
200
+ signals.push({ code: "INSTALL_SCRIPT_PRESENT", risk: "high", message: `${lowerName} lifecycle script detected.` });
201
+ }
202
+ if (/\b(curl|wget|Invoke-WebRequest|Invoke-RestMethod)\b/i.test(text)) {
203
+ signals.push({ code: "NETWORK_SCRIPT_PRESENT", risk: "high", message: "Lifecycle or package script makes a network request." });
204
+ }
205
+ if (/\b(token|secret|credential|authorization|process\.env|echo\s+\$[A-Z_]+)\b/i.test(text)) {
206
+ signals.push({ code: "SECRET_EXFIL_SCRIPT", risk: "high", message: "Lifecycle or package script references possible secret or env exfiltration." });
207
+ }
208
+ if (/\brm\s+-rf\b|\bdel\s+\/s\s+\/q\b|\brmdir\b/i.test(text)) {
209
+ signals.push({ code: "DESTRUCTIVE_SCRIPT_PRESENT", risk: "critical", message: "Lifecycle or package script includes destructive deletion." });
210
+ }
211
+ if (/\b(deploy|publish|release|npm publish|gh release)\b/i.test(text) || /\b(predeploy|deploy|publish)\b/i.test(lowerName)) {
212
+ signals.push({ code: "DEPLOY_SCRIPT_PRESENT", risk: "high", message: "Lifecycle or package script deploys or publishes." });
213
+ }
214
+ return signals;
215
+ }
216
+
217
+ function packageDependencySignals(name, version) {
218
+ const signals = [];
219
+ const spec = String(version || "").trim();
220
+ if (/^(https?:|git\+|git@|github:)/i.test(spec)) {
221
+ signals.push({ code: "PACKAGE_NON_REGISTRY_SOURCE", risk: "high", message: `${name} installs from git or HTTP instead of a normal registry spec.` });
222
+ }
223
+ if (/^(file:|link:)/i.test(spec)) {
224
+ signals.push({ code: "PACKAGE_LOCAL_FILE_SOURCE", risk: "medium", message: `${name} installs from a local file or link path.` });
225
+ }
226
+ if (/workspace:/i.test(spec)) {
227
+ signals.push({ code: "PACKAGE_WORKSPACE_SOURCE", risk: "low", message: `${name} uses a local workspace source.` });
228
+ }
229
+ return signals;
230
+ }
231
+
232
+ function detectToolCapabilities(serverOrTool = {}) {
233
+ const capabilities = [];
234
+ const text = JSON.stringify(serverOrTool || {});
235
+ if (serverOrTool.writeCapable === true || /\b(write|patch|delete|mutate|edit|create)\b/i.test(text)) capabilities.push("write");
236
+ if (serverOrTool.networkCapable === true || /\b(http|https|fetch|network|url)\b/i.test(text)) capabilities.push("network");
237
+ if (serverOrTool.commandCapable === true || /\b(command|shell|exec|spawn|terminal)\b/i.test(text)) capabilities.push("execute");
238
+ if (serverOrTool.browserCapable === true || /\b(browser|playwright|chrome|devtools)\b/i.test(text)) capabilities.push("browser");
239
+ if (serverOrTool.secretCapable === true || /\b(secret|token|credential|env)\b/i.test(text)) capabilities.push("secrets");
240
+ if (serverOrTool.deployCapable === true || /\b(deploy|publish|release)\b/i.test(text)) capabilities.push("deploy");
241
+ if (!capabilities.length) capabilities.push("read");
242
+ return capabilitySet(capabilities);
243
+ }
244
+
245
+ function mcpSignals(serverOrTool, reviewStatus) {
246
+ const signals = [];
247
+ const caps = detectToolCapabilities(serverOrTool);
248
+ if (reviewStatus === "unknown" || reviewStatus === "deferred") {
249
+ signals.push({ code: "UNKNOWN_MCP_SOURCE", risk: "high", message: "MCP server or tool is present without reviewed source metadata." });
250
+ }
251
+ if (caps.includes("write")) signals.push({ code: "WRITE_CAPABLE_MCP", risk: "high", message: "MCP item appears write-capable." });
252
+ if (caps.includes("network")) signals.push({ code: "NETWORK_CAPABLE_MCP", risk: "high", message: "MCP item appears network-capable." });
253
+ if (caps.includes("execute")) signals.push({ code: "COMMAND_CAPABLE_MCP", risk: "high", message: "MCP item appears shell or command-capable." });
254
+ if (caps.includes("secrets")) signals.push({ code: "SECRET_CAPABLE_MCP", risk: "high", message: "MCP item appears secret-sensitive." });
255
+ return { caps, signals };
256
+ }
257
+
258
+ function signalsToRisk(signals = [], fallback = "low") {
259
+ return signals.reduce((level, signal) => maxRisk(level, signal.risk || "low"), fallback);
260
+ }
261
+
262
+ function signalsToReasonCodes(signals = []) {
263
+ return unique(signals.map((signal) => signal.code));
264
+ }
265
+
266
+ function defaultSafeNextAction(item) {
267
+ if (item.reviewStatus === "blocked") return "Keep this item blocked until the source or config is intentionally replaced.";
268
+ if (item.reviewStatus === "deferred" || item.reviewStatus === "unknown") return "Review source, ownership, and scope before relying on this item at runtime.";
269
+ if (item.riskLevel === "critical" || item.riskLevel === "high") return "Use read-only, no-secrets, or no-network alternatives first and review this item before normal use.";
270
+ return "Keep this item in the smallest useful reviewed scope and preserve evidence.";
271
+ }
272
+
273
+ function createItem(input) {
274
+ const type = isValidEnum(input.type, VALID_ITEM_TYPES, "unknown");
275
+ const reviewStatus = isValidEnum(input.reviewStatus, REVIEW_STATUSES, "unknown");
276
+ const trustLevel = isValidEnum(input.trustLevel, TRUST_LEVELS, "unknown");
277
+ const riskLevel = isValidEnum(input.riskLevel, new Set(RISK_LEVELS), "low");
278
+ const capabilities = capabilitySet(input.capabilities);
279
+ const item = {
280
+ id: input.id || createItemId([type, input.name, input.configPath, input.detectedFrom]),
281
+ type,
282
+ name: sanitizeText(input.name || type),
283
+ source: sanitizeText(input.source || "local"),
284
+ configPath: normalizePathValue(input.configPath || ""),
285
+ detectedFrom: sanitizeText(input.detectedFrom || "local_scan"),
286
+ ownerOrPublisher: sanitizeText(input.ownerOrPublisher || ""),
287
+ version: sanitizeText(input.version || ""),
288
+ reviewStatus,
289
+ trustLevel,
290
+ riskLevel,
291
+ capabilities,
292
+ riskSignals: (input.riskSignals || []).map((signal) => ({
293
+ code: signal.code,
294
+ risk: signal.risk,
295
+ message: sanitizeText(signal.message),
296
+ })),
297
+ reasonCodes: unique(input.reasonCodes || signalsToReasonCodes(input.riskSignals || [])),
298
+ safeNextAction: sanitizeText(input.safeNextAction || defaultSafeNextAction({
299
+ reviewStatus,
300
+ riskLevel,
301
+ })),
302
+ feedsGovernance: input.feedsGovernance !== false,
303
+ feedsSafePath: input.feedsSafePath !== false,
304
+ redacted: true,
305
+ };
306
+ return item;
307
+ }
308
+
309
+ function detectPackageItems(cwd) {
310
+ const files = findRepoFiles(cwd, (_abs, rel) => path.basename(rel) === "package.json", { maxDepth: 6 });
311
+ const items = [];
312
+ const scannedSources = [];
313
+
314
+ files.forEach(({ absPath, relPath }) => {
315
+ let pkg = null;
316
+ try {
317
+ pkg = JSON.parse(fs.readFileSync(absPath, "utf8"));
318
+ } catch {
319
+ return;
320
+ }
321
+ scannedSources.push(relPath);
322
+ [
323
+ { key: "dependencies", type: "package_dependency" },
324
+ { key: "devDependencies", type: "dev_dependency" },
325
+ ].forEach(({ key, type }) => {
326
+ const deps = pkg[key] || {};
327
+ Object.entries(deps).forEach(([name, version]) => {
328
+ const reviewStatus = packageReviewStatus(version);
329
+ const riskSignals = packageDependencySignals(name, version);
330
+ const riskLevel = signalsToRisk(riskSignals, reviewStatus === "known" ? "low" : reviewStatus === "deferred" ? "high" : "medium");
331
+ const capabilities = [];
332
+ if (riskSignals.some((signal) => signal.code === "PACKAGE_NON_REGISTRY_SOURCE")) capabilities.push("execute", "network");
333
+ if (riskSignals.some((signal) => signal.code === "PACKAGE_LOCAL_FILE_SOURCE")) capabilities.push("read", "execute");
334
+ items.push(createItem({
335
+ type,
336
+ name,
337
+ source: "package_manifest",
338
+ configPath: relPath,
339
+ detectedFrom: `${relPath}:${key}`,
340
+ ownerOrPublisher: name.startsWith("@") ? name.slice(1).split("/")[0] : "",
341
+ version,
342
+ reviewStatus,
343
+ trustLevel: packageTrustLevel(reviewStatus),
344
+ riskLevel,
345
+ capabilities,
346
+ riskSignals,
347
+ safeNextAction: reviewStatus === "deferred"
348
+ ? "Review non-registry or git-sourced dependencies before install and prefer a pinned reviewed version."
349
+ : undefined,
350
+ feedsGovernance: true,
351
+ feedsSafePath: true,
352
+ }));
353
+ });
354
+ });
355
+ const scripts = pkg.scripts || {};
356
+ Object.entries(scripts).forEach(([name, command]) => {
357
+ const riskSignals = packageScriptSignals(name, command);
358
+ const capabilities = capabilitySet([
359
+ "execute",
360
+ ...(/curl|wget|Invoke-WebRequest|Invoke-RestMethod/i.test(String(command || "")) ? ["network"] : []),
361
+ ...(/token|secret|credential|process\.env/i.test(String(command || "")) ? ["secrets"] : []),
362
+ ...(/deploy|publish|release|npm publish/i.test(String(command || "")) ? ["deploy"] : []),
363
+ ]);
364
+ items.push(createItem({
365
+ type: "npm_script",
366
+ name,
367
+ source: "package_manifest",
368
+ configPath: relPath,
369
+ detectedFrom: `${relPath}:scripts`,
370
+ version: "",
371
+ reviewStatus: "known",
372
+ trustLevel: "medium",
373
+ riskLevel: signalsToRisk(riskSignals, "low"),
374
+ capabilities,
375
+ riskSignals,
376
+ safeNextAction: riskSignals.length
377
+ ? "Review the script before install or runtime use, then prefer dry-run, test-only, or no-network alternatives first."
378
+ : undefined,
379
+ feedsGovernance: true,
380
+ feedsSafePath: true,
381
+ }));
382
+ });
383
+ });
384
+ return { items, scannedSources };
385
+ }
386
+
387
+ function parseMcpServers(absPath) {
388
+ const parsed = safeReadJson(path.dirname(absPath), path.basename(absPath), null);
389
+ if (!parsed || typeof parsed !== "object") return [];
390
+ if (parsed.mcpServers && typeof parsed.mcpServers === "object") {
391
+ return Object.entries(parsed.mcpServers).map(([name, value]) => ({ name, value }));
392
+ }
393
+ if (parsed.servers && typeof parsed.servers === "object" && /mcp/i.test(path.basename(absPath))) {
394
+ return Object.entries(parsed.servers).map(([name, value]) => ({ name, value }));
395
+ }
396
+ return [];
397
+ }
398
+
399
+ function detectMcpItems(cwd) {
400
+ const files = findRepoFiles(
401
+ cwd,
402
+ (_abs, rel) => /mcp/i.test(path.basename(rel)) && /\.(json|ya?ml)$/i.test(rel),
403
+ { maxDepth: 6 }
404
+ );
405
+ const items = [];
406
+ const scannedSources = [];
407
+ files.forEach(({ absPath, relPath }) => {
408
+ scannedSources.push(relPath);
409
+ const servers = parseMcpServers(absPath);
410
+ servers.forEach(({ name, value }) => {
411
+ const reviewStatus = isValidEnum(value.reviewStatus || value.trustStatus || (value.reviewed === true ? "reviewed" : "unknown"), REVIEW_STATUSES, "unknown");
412
+ const trustLevel = value.reviewed === true ? "high" : reviewStatus === "known" ? "medium" : reviewStatus === "blocked" ? "low" : "unknown";
413
+ const { caps, signals } = mcpSignals(value, reviewStatus);
414
+ items.push(createItem({
415
+ type: "mcp_server",
416
+ name,
417
+ source: sanitizeText(value.source || value.command || value.url || "mcp_config"),
418
+ configPath: relPath,
419
+ detectedFrom: `${relPath}:mcpServers`,
420
+ ownerOrPublisher: value.owner || value.publisher || "",
421
+ version: value.version || "",
422
+ reviewStatus,
423
+ trustLevel,
424
+ riskLevel: signalsToRisk(signals, reviewStatus === "reviewed" ? "medium" : "high"),
425
+ capabilities: caps,
426
+ riskSignals: signals,
427
+ safeNextAction: "Review the MCP server source and owner first, then prefer one reviewed read-only tool scope before wider use.",
428
+ feedsGovernance: true,
429
+ feedsSafePath: true,
430
+ }));
431
+
432
+ const tools = Array.isArray(value.tools)
433
+ ? value.tools.map((tool) => [tool.name || tool.id || "unnamed-tool", tool])
434
+ : value.tools && typeof value.tools === "object"
435
+ ? Object.entries(value.tools)
436
+ : [];
437
+ tools.forEach(([toolName, toolValue]) => {
438
+ const toolReviewStatus = isValidEnum(toolValue.reviewStatus || toolValue.trustStatus || reviewStatus, REVIEW_STATUSES, reviewStatus);
439
+ const { caps: toolCaps, signals: toolSignals } = mcpSignals(toolValue, toolReviewStatus);
440
+ items.push(createItem({
441
+ type: "mcp_tool",
442
+ name: `${name}:${toolName}`,
443
+ source: sanitizeText(value.source || name),
444
+ configPath: relPath,
445
+ detectedFrom: `${relPath}:mcpServers.${name}.tools`,
446
+ ownerOrPublisher: value.owner || value.publisher || "",
447
+ version: value.version || "",
448
+ reviewStatus: toolReviewStatus,
449
+ trustLevel: toolReviewStatus === "reviewed" ? "high" : toolReviewStatus === "known" ? "medium" : "unknown",
450
+ riskLevel: signalsToRisk(toolSignals, toolReviewStatus === "reviewed" ? "medium" : "high"),
451
+ capabilities: toolCaps,
452
+ riskSignals: toolSignals,
453
+ safeNextAction: "Review the MCP tool source and scope before runtime use, then prefer the narrowest reviewed tool boundary.",
454
+ feedsGovernance: true,
455
+ feedsSafePath: true,
456
+ }));
457
+ });
458
+ });
459
+ });
460
+ return { items, scannedSources };
461
+ }
462
+
463
+ function detectExtensionItems(cwd) {
464
+ const items = [];
465
+ const scannedSources = [];
466
+ const vscodePath = path.join(cwd, ".vscode", "extensions.json");
467
+ if (fs.existsSync(vscodePath)) {
468
+ scannedSources.push(".vscode/extensions.json");
469
+ const payload = safeReadJson(path.join(cwd, ".vscode"), "extensions.json", {});
470
+ const recommendations = unique([
471
+ ...((payload.recommendations || []).filter(Boolean)),
472
+ ...((payload.unwantedRecommendations || []).filter(Boolean)),
473
+ ]);
474
+ recommendations.forEach((name) => {
475
+ const parts = String(name || "").split(".");
476
+ const hasPublisher = parts.length >= 2;
477
+ const signals = [];
478
+ if (!hasPublisher) signals.push({ code: "UNKNOWN_EXTENSION_SOURCE", risk: "high", message: "Extension recommendation is missing a publisher." });
479
+ if (/\b(browser|playwright|devtools|chrome)\b/i.test(name)) signals.push({ code: "EXTENSION_BROWSER_ACCESS", risk: "medium", message: "Extension likely touches browser or devtools surfaces." });
480
+ items.push(createItem({
481
+ type: "vscode_extension",
482
+ name,
483
+ source: "vscode_extensions",
484
+ configPath: ".vscode/extensions.json",
485
+ detectedFrom: ".vscode/extensions.json",
486
+ ownerOrPublisher: hasPublisher ? parts[0] : "",
487
+ reviewStatus: hasPublisher ? "known" : "unknown",
488
+ trustLevel: hasPublisher ? "medium" : "unknown",
489
+ riskLevel: signalsToRisk(signals, hasPublisher ? "low" : "medium"),
490
+ capabilities: /\b(browser|playwright|devtools|chrome)\b/i.test(name) ? ["browser", "network"] : ["unknown"],
491
+ riskSignals: signals,
492
+ safeNextAction: "Review the publisher and required workspace access before enabling the extension.",
493
+ }));
494
+ });
495
+ }
496
+ return { items, scannedSources };
497
+ }
498
+
499
+ function detectGuidanceItems(cwd) {
500
+ const items = [];
501
+ const scannedSources = [];
502
+ const addGuidanceFile = (relPath, type, source) => {
503
+ const absPath = path.join(cwd, relPath);
504
+ if (!fs.existsSync(absPath) || fs.statSync(absPath).isDirectory()) return;
505
+ const text = fs.readFileSync(absPath, "utf8");
506
+ const signals = guidanceSignals(text);
507
+ scannedSources.push(relPath);
508
+ items.push(createItem({
509
+ type,
510
+ name: relPath,
511
+ source,
512
+ configPath: relPath,
513
+ detectedFrom: relPath,
514
+ reviewStatus: relPath.startsWith(".avorelo/generated/") ? "reviewed" : "known",
515
+ trustLevel: relPath.startsWith(".avorelo/generated/") ? "high" : "medium",
516
+ riskLevel: signalsToRisk(signals, "low"),
517
+ capabilities: capabilitySet([
518
+ "read",
519
+ ...(/auto-?run|execute/i.test(text) ? ["execute"] : []),
520
+ ...(/cookie|session|browser|playwright|devtools/i.test(text) ? ["browser"] : []),
521
+ ...(/secret|token|credential|authorization/i.test(text) ? ["secrets"] : []),
522
+ ...(/network|http|https|curl|wget/i.test(text) ? ["network"] : []),
523
+ ]),
524
+ riskSignals: signals,
525
+ safeNextAction: signals.length
526
+ ? "Keep generated or local guidance thin, remove bypass language, and route core policy through Avorelo rather than adapter files."
527
+ : undefined,
528
+ feedsGovernance: false,
529
+ feedsSafePath: true,
530
+ }));
531
+ const browserRiskSignals = browserSignals(text);
532
+ if (browserRiskSignals.length) {
533
+ items.push(createItem({
534
+ type: "browser_integration",
535
+ name: `${relPath}:browser`,
536
+ source,
537
+ configPath: relPath,
538
+ detectedFrom: relPath,
539
+ reviewStatus: relPath.startsWith(".avorelo/generated/") ? "reviewed" : "known",
540
+ trustLevel: relPath.startsWith(".avorelo/generated/") ? "high" : "medium",
541
+ riskLevel: signalsToRisk(browserRiskSignals, "medium"),
542
+ capabilities: capabilitySet(["browser", "network"]),
543
+ riskSignals: browserRiskSignals,
544
+ safeNextAction: "Prefer localhost preview or reviewed domain boundaries before browser automation uses this guidance.",
545
+ feedsGovernance: false,
546
+ feedsSafePath: true,
547
+ }));
548
+ }
549
+ };
550
+
551
+ GUIDANCE_FILE_CANDIDATES.forEach((relPath) => {
552
+ if (relPath.endsWith("GEMINI.md")) addGuidanceFile(relPath, "gemini_guidance", "guidance");
553
+ else if (relPath.includes("copilot")) addGuidanceFile(relPath, "copilot_guidance", "guidance");
554
+ else addGuidanceFile(relPath, "claude_or_agents_guidance", "guidance");
555
+ });
556
+
557
+ const cursorRuleFiles = findRepoFiles(cwd, (_abs, rel) => rel.startsWith(".cursor/"), { maxDepth: 5 });
558
+ cursorRuleFiles.forEach(({ relPath }) => addGuidanceFile(relPath, "cursor_rule_or_extension", "cursor"));
559
+
560
+ const generatedGuidance = findRepoFiles(cwd, (_abs, rel) => rel.startsWith(".avorelo/generated/") && /\.(md|mdc|txt)$/i.test(rel), { maxDepth: 6 });
561
+ generatedGuidance.forEach(({ relPath }) => {
562
+ const type = /GEMINI/i.test(relPath)
563
+ ? "gemini_guidance"
564
+ : /copilot/i.test(relPath)
565
+ ? "copilot_guidance"
566
+ : /cursor/i.test(relPath)
567
+ ? "cursor_rule_or_extension"
568
+ : "claude_or_agents_guidance";
569
+ addGuidanceFile(relPath, type, "generated_guidance");
570
+ });
571
+
572
+ const copilotInstructions = findRepoFiles(cwd, (_abs, rel) => rel.startsWith(".github/instructions/") && /\.instructions\.md$/i.test(rel), { maxDepth: 5 });
573
+ copilotInstructions.forEach(({ relPath }) => addGuidanceFile(relPath, "copilot_guidance", "guidance"));
574
+
575
+ return { items, scannedSources };
576
+ }
577
+
578
+ function detectSkillSourceItems(cwd) {
579
+ const items = [];
580
+ const scannedSources = ["skills/avorelo", "vendor/skillpacks", "docs/references/references.json", "scripts/lib/source-catalog.js"];
581
+ const registry = buildSkillRegistry(cwd);
582
+ const bySource = new Map();
583
+ registry.skills.forEach((skill) => {
584
+ const key = skill.sourceId || skill.packId;
585
+ if (!bySource.has(key)) {
586
+ bySource.set(key, {
587
+ sourceId: key,
588
+ name: skill.sourceName || key,
589
+ reviewStatus: skill.sourceReviewStatus,
590
+ trustLevel: skill.sourceTrustLevel,
591
+ warnings: [],
592
+ scripts: [],
593
+ sourcePath: skill.packId === "avorelo" ? "skills/avorelo" : `vendor/skillpacks/${skill.packId}`,
594
+ });
595
+ }
596
+ const aggregate = bySource.get(key);
597
+ aggregate.reviewStatus = aggregate.reviewStatus === "blocked" || skill.sourceReviewStatus === "blocked"
598
+ ? "blocked"
599
+ : aggregate.reviewStatus === "reviewed" || skill.sourceReviewStatus === "reviewed" || skill.sourceReviewStatus === "trusted"
600
+ ? "reviewed"
601
+ : !skill.routeEligible
602
+ ? "deferred"
603
+ : aggregate.reviewStatus;
604
+ aggregate.warnings.push(...(skill.warnings || []));
605
+ aggregate.scripts.push(...(skill.scripts || []));
606
+ });
607
+
608
+ bySource.forEach((aggregate) => {
609
+ const riskSignals = [];
610
+ if (aggregate.reviewStatus === "deferred") {
611
+ riskSignals.push({ code: "DEFERRED_SKILL_SOURCE", risk: "high", message: "Skill source is deferred and must not be trusted like a reviewed source." });
612
+ }
613
+ if (aggregate.reviewStatus === "blocked") {
614
+ riskSignals.push({ code: "BLOCKED_SKILL_SOURCE", risk: "critical", message: "Skill source is blocked." });
615
+ }
616
+ if (aggregate.scripts.length) {
617
+ riskSignals.push({ code: "SKILL_SCRIPT_METADATA_ONLY", risk: "medium", message: "Skill source references scripts that must remain metadata-only." });
618
+ }
619
+ aggregate.warnings.forEach((warning) => {
620
+ if (warning.code === "unknown_or_unconfirmed_license") {
621
+ riskSignals.push({ code: "UNKNOWN_SKILL_LICENSE", risk: "high", message: "Skill source license is not confirmed for reuse." });
622
+ }
623
+ if (warning.code === "hidden_unicode") {
624
+ riskSignals.push({ code: "SKILL_HIDDEN_UNICODE", risk: "high", message: "Skill source includes hidden Unicode markers." });
625
+ }
626
+ if (warning.code === "policy_bypass_phrase") {
627
+ riskSignals.push({ code: "SKILL_POLICY_BYPASS", risk: "high", message: "Skill source includes instruction-bypass language." });
628
+ }
629
+ if (warning.code === "context_heavy_skill") {
630
+ riskSignals.push({ code: "SKILL_CONTEXT_HEAVY", risk: "medium", message: "Skill source is context-heavy and should be lazy-loaded." });
631
+ }
632
+ if (warning.code === "adapter_leakage_risk") {
633
+ riskSignals.push({ code: "SKILL_ADAPTER_LEAKAGE", risk: "medium", message: "Skill source is too heavy for thin adapter copying." });
634
+ }
635
+ });
636
+ items.push(createItem({
637
+ type: "skill_pack",
638
+ name: aggregate.name,
639
+ source: aggregate.sourceId,
640
+ configPath: aggregate.sourcePath,
641
+ detectedFrom: "skill_registry",
642
+ reviewStatus: aggregate.reviewStatus === "trusted" ? "reviewed" : aggregate.reviewStatus,
643
+ trustLevel: aggregate.trustLevel || "unknown",
644
+ riskLevel: signalsToRisk(riskSignals, aggregate.reviewStatus === "reviewed" ? "low" : aggregate.reviewStatus === "deferred" ? "high" : "medium"),
645
+ capabilities: capabilitySet(aggregate.scripts.length ? ["read"] : ["read"]),
646
+ riskSignals,
647
+ safeNextAction: aggregate.reviewStatus === "reviewed"
648
+ ? "Use only the reviewed source-backed subset and keep any script references as data-only metadata."
649
+ : "Do not trust deferred or unknown skill sources at runtime until their source, license, and warnings are reviewed.",
650
+ feedsGovernance: true,
651
+ feedsSafePath: true,
652
+ }));
653
+ });
654
+
655
+ return { items, scannedSources };
656
+ }
657
+
658
+ function buildReceipt(cwd, items, scannedSources, options = {}) {
659
+ const sortedItems = items.slice().sort((left, right) => {
660
+ const risk = (RISK_ORDER[right.riskLevel] || 0) - (RISK_ORDER[left.riskLevel] || 0);
661
+ if (risk !== 0) return risk;
662
+ return left.name.localeCompare(right.name);
663
+ });
664
+ const summary = {
665
+ totalItems: sortedItems.length,
666
+ reviewedItems: sortedItems.filter((item) => item.reviewStatus === "reviewed").length,
667
+ unknownItems: sortedItems.filter((item) => item.reviewStatus === "unknown").length,
668
+ deferredItems: sortedItems.filter((item) => item.reviewStatus === "deferred").length,
669
+ blockedItems: sortedItems.filter((item) => item.reviewStatus === "blocked").length,
670
+ highRiskItems: sortedItems.filter((item) => item.riskLevel === "high").length,
671
+ criticalRiskItems: sortedItems.filter((item) => item.riskLevel === "critical").length,
672
+ itemsFeedingGovernance: sortedItems.filter((item) => item.feedsGovernance).length,
673
+ itemsFeedingSafePath: sortedItems.filter((item) => item.feedsSafePath).length,
674
+ };
675
+ const reasonCounts = new Map();
676
+ sortedItems.forEach((item) => {
677
+ item.reasonCodes.forEach((code) => reasonCounts.set(code, (reasonCounts.get(code) || 0) + 1));
678
+ });
679
+ const topReasonCodes = Array.from(reasonCounts.entries())
680
+ .sort((left, right) => right[1] - left[1])
681
+ .slice(0, 8)
682
+ .map(([code]) => code);
683
+ const nextAction = summary.blockedItems > 0
684
+ ? "Keep blocked intake items out of runtime use and review the highest-risk unknown or deferred sources first."
685
+ : summary.unknownItems > 0 || summary.deferredItems > 0
686
+ ? "Review unknown or deferred intake sources before relying on them in governance, Safe Path, or runtime tool use."
687
+ : summary.highRiskItems > 0
688
+ ? "Reduce scope around the highest-risk reviewed items and prefer read-only, no-network, or no-secrets alternatives first."
689
+ : "Keep reviewed intake items scoped narrowly and preserve local evidence.";
690
+ return {
691
+ schemaVersion: INSTALL_INTAKE_SCHEMA_VERSION,
692
+ contract: INSTALL_INTAKE_CONTRACT,
693
+ receiptId: `intake-${sha256(JSON.stringify({
694
+ scannedSources,
695
+ totalItems: summary.totalItems,
696
+ highRiskItems: summary.highRiskItems,
697
+ createdAt: nowIso(),
698
+ })).slice(0, 12)}`,
699
+ receiptType: "workspace_intake_scan",
700
+ createdAt: nowIso(),
701
+ scannedSources: unique(scannedSources),
702
+ items: sortedItems,
703
+ summary,
704
+ topReasonCodes,
705
+ nextAction,
706
+ redacted: true,
707
+ generatedBy: options.generatedBy || "install_intake_scan",
708
+ };
709
+ }
710
+
711
+ function appendIntakeEvents(cwd, receipt) {
712
+ appendProductLearningEvent(cwd, {
713
+ eventName: "intake_scan_completed",
714
+ category: "install_intake_risk",
715
+ status: "pass",
716
+ payload: {
717
+ totalItems: receipt.summary.totalItems,
718
+ unknownItems: receipt.summary.unknownItems,
719
+ highRiskItems: receipt.summary.highRiskItems,
720
+ },
721
+ });
722
+ if (receipt.summary.unknownItems > 0) {
723
+ appendProductLearningEvent(cwd, {
724
+ eventName: "intake_unknown_item_detected",
725
+ category: "install_intake_risk",
726
+ status: "warn",
727
+ payload: { unknownItems: receipt.summary.unknownItems },
728
+ });
729
+ }
730
+ if (receipt.summary.highRiskItems > 0 || receipt.summary.criticalRiskItems > 0) {
731
+ appendProductLearningEvent(cwd, {
732
+ eventName: "intake_high_risk_item_detected",
733
+ category: "install_intake_risk",
734
+ status: "warn",
735
+ payload: {
736
+ highRiskItems: receipt.summary.highRiskItems,
737
+ criticalRiskItems: receipt.summary.criticalRiskItems,
738
+ },
739
+ });
740
+ }
741
+ if (receipt.summary.blockedItems > 0) {
742
+ appendProductLearningEvent(cwd, {
743
+ eventName: "intake_blocked_item_detected",
744
+ category: "install_intake_risk",
745
+ status: "block",
746
+ payload: { blockedItems: receipt.summary.blockedItems },
747
+ });
748
+ }
749
+ appendProductLearningEvent(cwd, {
750
+ eventName: "intake_safe_next_action_recommended",
751
+ category: "install_intake_risk",
752
+ status: "pass",
753
+ payload: {
754
+ nextAction: receipt.nextAction,
755
+ topReasonCodes: receipt.topReasonCodes.slice(0, 5),
756
+ },
757
+ });
758
+ appendProductLearningEvent(cwd, {
759
+ eventName: "intake_receipt_written",
760
+ category: "install_intake_risk",
761
+ status: "pass",
762
+ payload: {
763
+ receiptPath: LATEST_INSTALL_INTAKE_RECEIPT_REL_PATH,
764
+ totalItems: receipt.summary.totalItems,
765
+ },
766
+ });
767
+ appendProductLearningEvent(cwd, {
768
+ eventName: "intake_feeds_governance",
769
+ category: "install_intake_risk",
770
+ status: "pass",
771
+ payload: { items: receipt.summary.itemsFeedingGovernance },
772
+ });
773
+ appendProductLearningEvent(cwd, {
774
+ eventName: "intake_feeds_safe_path",
775
+ category: "install_intake_risk",
776
+ status: "pass",
777
+ payload: { items: receipt.summary.itemsFeedingSafePath },
778
+ });
779
+ }
780
+
781
+ function scanInstallIntakeRisk(cwd, options = {}) {
782
+ const packageData = detectPackageItems(cwd);
783
+ const mcpData = detectMcpItems(cwd);
784
+ const extensionData = detectExtensionItems(cwd);
785
+ const guidanceData = detectGuidanceItems(cwd);
786
+ const skillData = detectSkillSourceItems(cwd);
787
+
788
+ const items = [
789
+ ...packageData.items,
790
+ ...mcpData.items,
791
+ ...extensionData.items,
792
+ ...guidanceData.items,
793
+ ...skillData.items,
794
+ ];
795
+ const receipt = buildReceipt(cwd, items, [
796
+ ...packageData.scannedSources,
797
+ ...mcpData.scannedSources,
798
+ ...extensionData.scannedSources,
799
+ ...guidanceData.scannedSources,
800
+ ...skillData.scannedSources,
801
+ ], {
802
+ generatedBy: options.generatedBy || "install_intake_scan",
803
+ });
804
+
805
+ let receiptPath = null;
806
+ if (options.writeReceipt !== false) {
807
+ receiptPath = createReceiptPath(cwd, LATEST_INSTALL_INTAKE_RECEIPT_REL_PATH, receipt, { plan: options.plan || "free" });
808
+ appendIntakeEvents(cwd, receipt);
809
+ }
810
+
811
+ return { receipt, receiptPath };
812
+ }
813
+
814
+ function readLatestInstallIntakeReceipt(cwd) {
815
+ return safeReadJson(cwd, LATEST_INSTALL_INTAKE_RECEIPT_REL_PATH, null);
816
+ }
817
+
818
+ function buildInstallIntakeRiskSurface(cwd) {
819
+ const latestReceipt = readLatestInstallIntakeReceipt(cwd);
820
+ const source = latestReceipt || scanInstallIntakeRisk(cwd, { writeReceipt: false }).receipt;
821
+ const status = source.summary.totalItems > 0 ? "foundation" : "partial";
822
+ return {
823
+ status,
824
+ showInStatus: true,
825
+ showInDashboard: true,
826
+ latestReceiptPath: latestReceipt ? LATEST_INSTALL_INTAKE_RECEIPT_REL_PATH : null,
827
+ totalItems: source.summary.totalItems,
828
+ unknownItems: source.summary.unknownItems,
829
+ deferredItems: source.summary.deferredItems,
830
+ blockedItems: source.summary.blockedItems,
831
+ highRiskItems: source.summary.highRiskItems,
832
+ criticalRiskItems: source.summary.criticalRiskItems,
833
+ topReasonCodes: source.topReasonCodes.slice(0, 5),
834
+ nextAction: source.nextAction,
835
+ latestReceipt,
836
+ topRiskyItems: source.items
837
+ .filter((item) => ["high", "critical"].includes(item.riskLevel) || ["unknown", "deferred", "blocked"].includes(item.reviewStatus))
838
+ .slice(0, 5)
839
+ .map((item) => ({
840
+ id: item.id,
841
+ type: item.type,
842
+ name: item.name,
843
+ reviewStatus: item.reviewStatus,
844
+ riskLevel: item.riskLevel,
845
+ reasonCodes: item.reasonCodes.slice(0, 4),
846
+ safeNextAction: item.safeNextAction,
847
+ })),
848
+ statusLine: `Install Intake: ${status.toUpperCase()} · items=${source.summary.totalItems} · unknown=${source.summary.unknownItems} · deferred=${source.summary.deferredItems} · high=${source.summary.highRiskItems} · critical=${source.summary.criticalRiskItems}`,
849
+ };
850
+ }
851
+
852
+ function matchItemByName(items, name) {
853
+ const target = String(name || "").trim().toLowerCase();
854
+ return items.find((item) => {
855
+ const itemName = String(item.name || "").trim().toLowerCase();
856
+ if (itemName === target) return true;
857
+ if (itemName.endsWith(`:${target}`)) return true;
858
+ return false;
859
+ }) || null;
860
+ }
861
+
862
+ function extractPackageInstallTarget(command) {
863
+ const text = String(command || "").trim();
864
+ const match = text.match(/\b(?:npm\s+install|pnpm\s+add|yarn\s+add)\s+([@A-Za-z0-9._/-]+)/i);
865
+ return match ? match[1] : null;
866
+ }
867
+
868
+ function buildSubjectFromItem(item) {
869
+ if (!item) return null;
870
+ const typeMap = {
871
+ mcp_server: "mcp_server",
872
+ mcp_tool: "tool",
873
+ package_dependency: "package",
874
+ dev_dependency: "package",
875
+ npm_script: "package",
876
+ vscode_extension: "extension",
877
+ cursor_rule_or_extension: "extension",
878
+ connector: "connector",
879
+ skill_pack: "skill",
880
+ browser_integration: "browser_integration",
881
+ };
882
+ const trustMap = {
883
+ reviewed: "reviewed",
884
+ known: "known",
885
+ blocked: "blocked",
886
+ unknown: "unknown",
887
+ deferred: "unknown",
888
+ };
889
+ return {
890
+ type: typeMap[item.type] || "unknown",
891
+ name: item.name,
892
+ source: item.source,
893
+ configPath: item.configPath || null,
894
+ owner: item.ownerOrPublisher || "workspace operator",
895
+ sponsor: "Avorelo install intake",
896
+ trustStatus: trustMap[item.reviewStatus] || "unknown",
897
+ };
898
+ }
899
+
900
+ function buildToolMetadataFromItem(item) {
901
+ if (!item) return {};
902
+ const caps = new Set(item.capabilities || []);
903
+ return {
904
+ trusted: item.reviewStatus === "reviewed" || item.reviewStatus === "known",
905
+ reviewed: item.reviewStatus === "reviewed",
906
+ unknown: item.reviewStatus === "unknown" || item.reviewStatus === "deferred",
907
+ blocked: item.reviewStatus === "blocked",
908
+ writeCapable: caps.has("write"),
909
+ networkCapable: caps.has("network"),
910
+ secretSensitive: caps.has("secrets"),
911
+ };
912
+ }
913
+
914
+ function buildActionIntakeContext(cwd, input = {}, options = {}) {
915
+ const result = scanInstallIntakeRisk(cwd, {
916
+ writeReceipt: options.writeReceipt !== false,
917
+ plan: options.plan || "free",
918
+ generatedBy: "guard_intake_scan",
919
+ });
920
+ const items = result.receipt.items || [];
921
+ const actionType = String(input.actionType || "").trim().toLowerCase();
922
+ const matches = [];
923
+
924
+ if (actionType === "tool_call") {
925
+ const item = matchItemByName(items.filter((entry) => entry.type === "mcp_tool"), input.toolName)
926
+ || matchItemByName(items.filter((entry) => entry.type === "mcp_server"), input.toolName);
927
+ if (item) {
928
+ matches.push(item);
929
+ } else if (input.toolName) {
930
+ matches.push(createItem({
931
+ type: "mcp_tool",
932
+ name: input.toolName,
933
+ source: "runtime_target",
934
+ configPath: "",
935
+ detectedFrom: "tool_call",
936
+ reviewStatus: "unknown",
937
+ trustLevel: "unknown",
938
+ riskLevel: "high",
939
+ capabilities: ["execute"],
940
+ riskSignals: [
941
+ { code: "UNKNOWN_MCP_SOURCE", risk: "high", message: "Tool target is not present in reviewed local intake." },
942
+ ],
943
+ safeNextAction: "Review the tool or MCP source first, then prefer one reviewed read-only tool scope before wider runtime access.",
944
+ feedsGovernance: true,
945
+ feedsSafePath: true,
946
+ }));
947
+ }
948
+ }
949
+ if (actionType === "mcp_tool_call") {
950
+ const specific = input.mcpServer && input.toolName ? `${input.mcpServer}:${input.toolName}` : input.toolName;
951
+ const item = matchItemByName(items.filter((entry) => entry.type === "mcp_tool"), specific)
952
+ || matchItemByName(items.filter((entry) => entry.type === "mcp_server"), input.mcpServer || input.toolName);
953
+ if (item) {
954
+ matches.push(item);
955
+ } else if (specific || input.mcpServer) {
956
+ matches.push(createItem({
957
+ type: input.toolName ? "mcp_tool" : "mcp_server",
958
+ name: specific || input.mcpServer,
959
+ source: "runtime_target",
960
+ configPath: "",
961
+ detectedFrom: "mcp_tool_call",
962
+ reviewStatus: "unknown",
963
+ trustLevel: "unknown",
964
+ riskLevel: "high",
965
+ capabilities: ["execute"],
966
+ riskSignals: [
967
+ { code: "UNKNOWN_MCP_SOURCE", risk: "high", message: "MCP target is not present in reviewed local intake." },
968
+ ],
969
+ safeNextAction: "Review the MCP server or tool source first, then keep runtime scope to one reviewed target with no-secrets or no-network alternatives where possible.",
970
+ feedsGovernance: true,
971
+ feedsSafePath: true,
972
+ }));
973
+ }
974
+ }
975
+ if (actionType === "command_run") {
976
+ const packageName = extractPackageInstallTarget(input.command || input.target);
977
+ if (packageName) {
978
+ const item = matchItemByName(items.filter((entry) => entry.type === "package_dependency" || entry.type === "dev_dependency"), packageName);
979
+ if (item) {
980
+ matches.push(item);
981
+ } else {
982
+ matches.push(createItem({
983
+ type: "package_dependency",
984
+ name: packageName,
985
+ source: "install_command",
986
+ configPath: "",
987
+ detectedFrom: "command_run",
988
+ reviewStatus: "unknown",
989
+ trustLevel: "unknown",
990
+ riskLevel: "high",
991
+ capabilities: ["execute", "network"],
992
+ riskSignals: [
993
+ { code: "UNKNOWN_PACKAGE_INSTALL", risk: "high", message: "Package install target is not yet present in local reviewed intake." },
994
+ ],
995
+ safeNextAction: "Review the package source first, pin the intended version, inspect install scripts, and keep the install outside secret-bearing contexts.",
996
+ feedsGovernance: true,
997
+ feedsSafePath: true,
998
+ }));
999
+ }
1000
+ }
1001
+ const scriptNameMatch = String(input.command || "").match(/\bnpm\s+run\s+([A-Za-z0-9:_-]+)/i);
1002
+ if (scriptNameMatch) {
1003
+ const scriptItem = matchItemByName(items.filter((entry) => entry.type === "npm_script"), scriptNameMatch[1]);
1004
+ if (scriptItem) matches.push(scriptItem);
1005
+ }
1006
+ }
1007
+
1008
+ const matchedItems = unique(matches.map((item) => item.id)).map((id) => matches.find((item) => item.id === id)).filter(Boolean);
1009
+ const riskLevel = matchedItems.reduce((level, item) => maxRisk(level, item.riskLevel || "low"), "low");
1010
+ const reasonCodes = unique(matchedItems.flatMap((item) => item.reasonCodes || []));
1011
+ const safeNextAction = matchedItems[0]?.safeNextAction || result.receipt.nextAction;
1012
+ const subject = matchedItems[0] ? buildSubjectFromItem(matchedItems[0]) : null;
1013
+ const toolMetadata = matchedItems[0] ? buildToolMetadataFromItem(matchedItems[0]) : {};
1014
+
1015
+ return {
1016
+ receipt: result.receipt,
1017
+ receiptPath: result.receiptPath || LATEST_INSTALL_INTAKE_RECEIPT_REL_PATH,
1018
+ matchedItems,
1019
+ riskLevel,
1020
+ reasonCodes,
1021
+ safeNextAction,
1022
+ subject,
1023
+ toolMetadata,
1024
+ };
1025
+ }
1026
+
1027
+ module.exports = {
1028
+ INSTALL_INTAKE_CONTRACT,
1029
+ INSTALL_INTAKE_SCHEMA_VERSION,
1030
+ LATEST_INSTALL_INTAKE_RECEIPT_REL_PATH,
1031
+ INSTALL_INTAKE_HISTORY_DIR_REL_PATH,
1032
+ INSTALL_INTAKE_EVENT_LOG_REL_PATH,
1033
+ scanInstallIntakeRisk,
1034
+ readLatestInstallIntakeReceipt,
1035
+ buildInstallIntakeRiskSurface,
1036
+ buildActionIntakeContext,
1037
+ };