avorelo 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (260) hide show
  1. package/LICENSE +23 -16
  2. package/README.md +91 -51
  3. package/bin/avorelo.mjs +7 -0
  4. package/dist/avorelo.mjs +14337 -0
  5. package/package.json +106 -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,1037 +0,0 @@
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
- };