avorelo 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (260) hide show
  1. package/LICENSE +23 -16
  2. package/README.md +90 -51
  3. package/bin/avorelo.mjs +7 -0
  4. package/dist/avorelo.mjs +19741 -0
  5. package/package.json +135 -120
  6. package/bin/avorelo +0 -9
  7. package/scripts/README.md +0 -40
  8. package/scripts/cco-dashboard.js +0 -252
  9. package/scripts/cco-status.js +0 -430
  10. package/scripts/lib/activation/account-state.js +0 -37
  11. package/scripts/lib/activation/activation-runner.js +0 -546
  12. package/scripts/lib/activation/activation-self-healing.js +0 -480
  13. package/scripts/lib/activation/activation-state.js +0 -83
  14. package/scripts/lib/activation/activation-summary.js +0 -191
  15. package/scripts/lib/activation/adapters/claude-code.js +0 -77
  16. package/scripts/lib/activation/adapters/codex-cli.js +0 -52
  17. package/scripts/lib/activation/adapters/cursor.js +0 -37
  18. package/scripts/lib/activation/adapters/github-agent.js +0 -39
  19. package/scripts/lib/activation/adapters/terminal.js +0 -42
  20. package/scripts/lib/activation/adapters/vscode.js +0 -39
  21. package/scripts/lib/activation/adapters/windsurf.js +0 -37
  22. package/scripts/lib/activation/ai-surface-detector.js +0 -151
  23. package/scripts/lib/activation/connect-account.js +0 -145
  24. package/scripts/lib/activation/detect-environment.js +0 -75
  25. package/scripts/lib/activation/detect-hosts.js +0 -62
  26. package/scripts/lib/activation/format-activation-output.js +0 -109
  27. package/scripts/lib/activation/next-action.js +0 -43
  28. package/scripts/lib/activation/repair-engine.js +0 -219
  29. package/scripts/lib/activation-distribution-readiness.js +0 -507
  30. package/scripts/lib/adapter-conformance.js +0 -176
  31. package/scripts/lib/adapter-readiness.js +0 -417
  32. package/scripts/lib/adapter-safety-boundaries.js +0 -335
  33. package/scripts/lib/adapter-technical-readiness-gate.js +0 -205
  34. package/scripts/lib/agent-access-governance.js +0 -455
  35. package/scripts/lib/agent-enforcement.js +0 -765
  36. package/scripts/lib/agent-policy-profile.js +0 -210
  37. package/scripts/lib/agent-security/action-evaluator.js +0 -507
  38. package/scripts/lib/agent-security/adapter-registry.js +0 -98
  39. package/scripts/lib/agent-security/auto-policy.js +0 -139
  40. package/scripts/lib/agent-security/bounded-scan.js +0 -93
  41. package/scripts/lib/agent-security/enforcement-adapter.js +0 -174
  42. package/scripts/lib/agent-security/enforcement-engine.js +0 -1129
  43. package/scripts/lib/agent-security/file-write-adapter.js +0 -183
  44. package/scripts/lib/agent-security/file-write-rules.js +0 -178
  45. package/scripts/lib/agent-security/index.js +0 -3342
  46. package/scripts/lib/agent-security/instruction-risk.js +0 -181
  47. package/scripts/lib/agent-security/mcp-action-adapter.js +0 -185
  48. package/scripts/lib/agent-security/mcp-action-rules.js +0 -184
  49. package/scripts/lib/agent-security/package-action-adapter.js +0 -175
  50. package/scripts/lib/agent-security/package-action-rules.js +0 -233
  51. package/scripts/lib/agent-security/performance.js +0 -148
  52. package/scripts/lib/agent-security/permission-minimizer.js +0 -403
  53. package/scripts/lib/agent-security/scan-cache.js +0 -74
  54. package/scripts/lib/agent-security/source-trust.js +0 -146
  55. package/scripts/lib/ai-install-prompt.js +0 -288
  56. package/scripts/lib/ai-workspace-hygiene.js +0 -1499
  57. package/scripts/lib/alpha-activation.js +0 -520
  58. package/scripts/lib/alpha-feedback.js +0 -263
  59. package/scripts/lib/alpha-readiness-gate.js +0 -332
  60. package/scripts/lib/anti-gaming.js +0 -169
  61. package/scripts/lib/artifact-health.js +0 -431
  62. package/scripts/lib/attribution.js +0 -180
  63. package/scripts/lib/audit.js +0 -289
  64. package/scripts/lib/avorelo-skill-registry.js +0 -810
  65. package/scripts/lib/batch-jobs.js +0 -71
  66. package/scripts/lib/brain-pack.js +0 -578
  67. package/scripts/lib/brand-boundary.js +0 -424
  68. package/scripts/lib/brand.js +0 -74
  69. package/scripts/lib/browser-capability.js +0 -1048
  70. package/scripts/lib/browser-proof-preflight.js +0 -321
  71. package/scripts/lib/cache-readiness.js +0 -187
  72. package/scripts/lib/canonical-reentry.js +0 -162
  73. package/scripts/lib/capability-packs.js +0 -314
  74. package/scripts/lib/capability-recommender.js +0 -512
  75. package/scripts/lib/capability-registry.js +0 -1059
  76. package/scripts/lib/carry-forward-surfacing.js +0 -194
  77. package/scripts/lib/ccusage-adapter.js +0 -188
  78. package/scripts/lib/company-loop.js +0 -1149
  79. package/scripts/lib/config.js +0 -637
  80. package/scripts/lib/context-acquisition-plan.js +0 -287
  81. package/scripts/lib/context-budget-guard.js +0 -170
  82. package/scripts/lib/context-budget-scanner.js +0 -257
  83. package/scripts/lib/context-optimizer.js +0 -715
  84. package/scripts/lib/context-reduction-plan.js +0 -178
  85. package/scripts/lib/context-safety.js +0 -88
  86. package/scripts/lib/context-savings-engine.js +0 -158
  87. package/scripts/lib/cost-evidence.js +0 -254
  88. package/scripts/lib/cross-host-install-plan.js +0 -308
  89. package/scripts/lib/cross-host-install-readiness.js +0 -237
  90. package/scripts/lib/cross-host-value-flow.js +0 -268
  91. package/scripts/lib/dashboard.js +0 -900
  92. package/scripts/lib/design-partner-feedback.js +0 -346
  93. package/scripts/lib/entitlements.js +0 -100
  94. package/scripts/lib/execution-packet.js +0 -559
  95. package/scripts/lib/experimentation-events.js +0 -547
  96. package/scripts/lib/external-capability-compliance.js +0 -107
  97. package/scripts/lib/external-user-simulation.js +0 -166
  98. package/scripts/lib/failure-recovery-readiness.js +0 -81
  99. package/scripts/lib/failure-recovery.js +0 -419
  100. package/scripts/lib/feedback-intelligence.js +0 -537
  101. package/scripts/lib/feedback-signals.js +0 -205
  102. package/scripts/lib/file-integrity.js +0 -68
  103. package/scripts/lib/fsx.js +0 -127
  104. package/scripts/lib/full-readiness-gate.js +0 -451
  105. package/scripts/lib/guidance-builder.js +0 -174
  106. package/scripts/lib/hook-apply.js +0 -1019
  107. package/scripts/lib/hook-baseline.js +0 -310
  108. package/scripts/lib/hook-config-preview.js +0 -275
  109. package/scripts/lib/hook-contracts.js +0 -290
  110. package/scripts/lib/hook-safety-boundary-readiness.js +0 -80
  111. package/scripts/lib/host-capability-matrix.js +0 -351
  112. package/scripts/lib/host-support-context.js +0 -254
  113. package/scripts/lib/http-hook-action.js +0 -538
  114. package/scripts/lib/install-ai-readiness.js +0 -84
  115. package/scripts/lib/install-intake-risk.js +0 -1037
  116. package/scripts/lib/install-journey-intelligence.js +0 -329
  117. package/scripts/lib/intervention-guidance.js +0 -57
  118. package/scripts/lib/known-limitations.js +0 -115
  119. package/scripts/lib/l8-path-truth.js +0 -146
  120. package/scripts/lib/launch-hardening-gate.js +0 -436
  121. package/scripts/lib/launch-readiness.js +0 -628
  122. package/scripts/lib/learning-memory.js +0 -686
  123. package/scripts/lib/lifecycle-hooks.js +0 -802
  124. package/scripts/lib/local-package-smoke.js +0 -423
  125. package/scripts/lib/local-pricing.js +0 -299
  126. package/scripts/lib/mcp-enforcement.js +0 -311
  127. package/scripts/lib/mcp-least-privilege-policy.js +0 -303
  128. package/scripts/lib/mcp-tool-inventory.js +0 -388
  129. package/scripts/lib/mcp-tool-risk.js +0 -0
  130. package/scripts/lib/memory.js +0 -335
  131. package/scripts/lib/metrics.js +0 -699
  132. package/scripts/lib/micro-proof.js +0 -133
  133. package/scripts/lib/next-run-context.js +0 -436
  134. package/scripts/lib/operating-value.js +0 -1648
  135. package/scripts/lib/optimization-v3.js +0 -122
  136. package/scripts/lib/orchestration/adapters/_shared.js +0 -49
  137. package/scripts/lib/orchestration/adapters/aider.js +0 -18
  138. package/scripts/lib/orchestration/adapters/claude-code.js +0 -35
  139. package/scripts/lib/orchestration/adapters/codex.js +0 -35
  140. package/scripts/lib/orchestration/adapters/gemini-cli.js +0 -18
  141. package/scripts/lib/orchestration/adapters/git.js +0 -25
  142. package/scripts/lib/orchestration/adapters/index.js +0 -31
  143. package/scripts/lib/orchestration/adapters/lm-studio.js +0 -18
  144. package/scripts/lib/orchestration/adapters/ollama.js +0 -18
  145. package/scripts/lib/orchestration/adapters/opencode.js +0 -18
  146. package/scripts/lib/orchestration/adapters/openrouter.js +0 -18
  147. package/scripts/lib/orchestration/adapters/test-runner.js +0 -25
  148. package/scripts/lib/orchestration/cli.js +0 -438
  149. package/scripts/lib/orchestration/execution-manager.js +0 -279
  150. package/scripts/lib/orchestration/handoff.js +0 -314
  151. package/scripts/lib/orchestration/index.js +0 -456
  152. package/scripts/lib/orchestration/inventory.js +0 -47
  153. package/scripts/lib/orchestration/model-discovery.js +0 -498
  154. package/scripts/lib/orchestration/model-profiler.js +0 -170
  155. package/scripts/lib/orchestration/model-profiles.js +0 -252
  156. package/scripts/lib/orchestration/model-refresh-policy.js +0 -72
  157. package/scripts/lib/orchestration/proof-writer.js +0 -349
  158. package/scripts/lib/orchestration/provider-discovery/aider.js +0 -49
  159. package/scripts/lib/orchestration/provider-discovery/claude-code.js +0 -56
  160. package/scripts/lib/orchestration/provider-discovery/codex.js +0 -49
  161. package/scripts/lib/orchestration/provider-discovery/common.js +0 -186
  162. package/scripts/lib/orchestration/provider-discovery/gemini.js +0 -106
  163. package/scripts/lib/orchestration/provider-discovery/lm-studio.js +0 -118
  164. package/scripts/lib/orchestration/provider-discovery/models-dev.js +0 -12
  165. package/scripts/lib/orchestration/provider-discovery/ollama.js +0 -100
  166. package/scripts/lib/orchestration/provider-discovery/opencode.js +0 -47
  167. package/scripts/lib/orchestration/provider-discovery/openrouter.js +0 -44
  168. package/scripts/lib/orchestration/risk-classifier.js +0 -130
  169. package/scripts/lib/orchestration/routing-policy.js +0 -486
  170. package/scripts/lib/orchestration/settings.js +0 -112
  171. package/scripts/lib/orchestration/state.js +0 -165
  172. package/scripts/lib/orchestration/verification-manager.js +0 -138
  173. package/scripts/lib/output-profiles.js +0 -146
  174. package/scripts/lib/package-content-audit.js +0 -368
  175. package/scripts/lib/package-runtime.js +0 -278
  176. package/scripts/lib/plan-surface.js +0 -53
  177. package/scripts/lib/plans.js +0 -2318
  178. package/scripts/lib/policy-provider.js +0 -27
  179. package/scripts/lib/prelaunch-activation-readiness.js +0 -409
  180. package/scripts/lib/prelaunch-evidence-store.js +0 -816
  181. package/scripts/lib/prelaunch-intelligence.js +0 -869
  182. package/scripts/lib/pricing-experiment.js +0 -118
  183. package/scripts/lib/pro-moment-events.js +0 -77
  184. package/scripts/lib/pro-moment-state.js +0 -227
  185. package/scripts/lib/pro-moments.js +0 -1216
  186. package/scripts/lib/product-learning-events.js +0 -629
  187. package/scripts/lib/project-profile.js +0 -555
  188. package/scripts/lib/prompt-compiler.js +0 -280
  189. package/scripts/lib/prompt-lint.js +0 -32
  190. package/scripts/lib/prompt-suggestions.js +0 -52
  191. package/scripts/lib/proof-canonical.js +0 -398
  192. package/scripts/lib/proof-drilldown.js +0 -383
  193. package/scripts/lib/proof-events.js +0 -342
  194. package/scripts/lib/proof-history.js +0 -243
  195. package/scripts/lib/proof-metrics.js +0 -296
  196. package/scripts/lib/proof-outcome-evidence.js +0 -134
  197. package/scripts/lib/proof-receipt.js +0 -335
  198. package/scripts/lib/proof-record.js +0 -461
  199. package/scripts/lib/public-activation-distribution-gate.js +0 -258
  200. package/scripts/lib/public-cli.js +0 -3891
  201. package/scripts/lib/public-distribution-truth.js +0 -211
  202. package/scripts/lib/public-install-claim-checker.js +0 -294
  203. package/scripts/lib/publish-provenance-readiness.js +0 -283
  204. package/scripts/lib/readiness-delta.js +0 -218
  205. package/scripts/lib/readiness-evidence-closure.js +0 -196
  206. package/scripts/lib/reentry-memory-capture.js +0 -241
  207. package/scripts/lib/reentry-memory-retrieval.js +0 -302
  208. package/scripts/lib/reentry-memory-status.js +0 -146
  209. package/scripts/lib/reentry-memory-store.js +0 -178
  210. package/scripts/lib/reentry-state.js +0 -66
  211. package/scripts/lib/release-candidate-bundle.js +0 -166
  212. package/scripts/lib/remediation.js +0 -81
  213. package/scripts/lib/repo-map.js +0 -391
  214. package/scripts/lib/run-improvements-lifecycle.js +0 -330
  215. package/scripts/lib/run-improvements.js +0 -789
  216. package/scripts/lib/runtime-decision-policy.js +0 -387
  217. package/scripts/lib/safe-path-engine.js +0 -705
  218. package/scripts/lib/safe-run-controller.js +0 -887
  219. package/scripts/lib/score.js +0 -262
  220. package/scripts/lib/seamless-enforcement.js +0 -329
  221. package/scripts/lib/seamless-outcome.js +0 -689
  222. package/scripts/lib/seamless-reality-gate.js +0 -5043
  223. package/scripts/lib/security-risk-classifier.js +0 -511
  224. package/scripts/lib/security-scan.js +0 -384
  225. package/scripts/lib/session-context-optimizer.js +0 -1211
  226. package/scripts/lib/session-timing.js +0 -315
  227. package/scripts/lib/skill-hygiene.js +0 -805
  228. package/scripts/lib/skill-packs.js +0 -161
  229. package/scripts/lib/skills-operating-layer.js +0 -580
  230. package/scripts/lib/smart-work-routing.js +0 -768
  231. package/scripts/lib/source-catalog.js +0 -700
  232. package/scripts/lib/status-value-summary.js +0 -32
  233. package/scripts/lib/support-bundle.js +0 -578
  234. package/scripts/lib/task-continuation.js +0 -440
  235. package/scripts/lib/test-helpers.js +0 -15
  236. package/scripts/lib/tier.js +0 -38
  237. package/scripts/lib/token-context-quality-gate.js +0 -370
  238. package/scripts/lib/token-cost-capture.js +0 -187
  239. package/scripts/lib/token-cost-intelligence.js +0 -358
  240. package/scripts/lib/token-efficiency-evidence.js +0 -213
  241. package/scripts/lib/token-evidence.js +0 -699
  242. package/scripts/lib/tokenish.js +0 -17
  243. package/scripts/lib/tool-output-sandbox.js +0 -304
  244. package/scripts/lib/trust-audit.js +0 -136
  245. package/scripts/lib/unified-events.js +0 -396
  246. package/scripts/lib/upgrade-interruption-recovery.js +0 -407
  247. package/scripts/lib/usage-ledger.js +0 -201
  248. package/scripts/lib/value-ledger.js +0 -130
  249. package/scripts/lib/value-proof-calibration.js +0 -531
  250. package/scripts/lib/visual-qa.js +0 -231
  251. package/scripts/lib/voice-alpha.js +0 -29
  252. package/scripts/lib/work-aware-orchestration.js +0 -976
  253. package/scripts/lib/work-control-receipts.js +0 -577
  254. package/scripts/lib/work-ledger.js +0 -1123
  255. package/scripts/lib/work-panel-preview.js +0 -352
  256. package/scripts/lib/workflow-discipline.js +0 -280
  257. package/scripts/lib/workflow-signals.js +0 -419
  258. package/scripts/lib/workspace-map.js +0 -281
  259. package/scripts/lib/workspace-registry.js +0 -1367
  260. package/scripts/lib/workspace-resolver.js +0 -480
@@ -1,887 +0,0 @@
1
- "use strict";
2
-
3
- // ── Safe Run Controller ───────────────────────────────────────────────────────
4
- //
5
- // Contract: avorelo.safeRun.v1
6
- //
7
- // Orchestrates the full safe-run control pipeline:
8
- // project-profile → smart-route → execution-packet → worker-handoff
9
- // → safe local proof steps (whitelisted only) → receipt → ledger/proof/outcome
10
- //
11
- // Does NOT:
12
- // - modify user code
13
- // - execute remote agents
14
- // - call external APIs
15
- // - implement ACP/A2A
16
- // - run deploy/publish/prod/release commands
17
- // - run destructive commands
18
- // - read secrets
19
- // - include raw prompts/code/secrets/PII in receipts
20
-
21
- const fs = require("node:fs");
22
- const path = require("node:path");
23
- const crypto = require("node:crypto");
24
- const { spawnSync } = require("node:child_process");
25
-
26
- const CONTRACT = "avorelo.safeRun.v1";
27
- const SCHEMA_VERSION = 1;
28
-
29
- const SAFE_RUN_DIR_REL = ".claude/cco/orchestration/safe-run";
30
- const LATEST_RUN_REL = `${SAFE_RUN_DIR_REL}/latest-run.json`;
31
-
32
- // ── Allowed local step types ──────────────────────────────────────────────────
33
-
34
- const ALLOWED_STEP_TYPES = Object.freeze([
35
- "project_profile",
36
- "smart_route",
37
- "execution_packet",
38
- "worker_handoff",
39
- "ledger_update",
40
- "proof_summary",
41
- "outcome_summary",
42
- "test_command",
43
- "build_command",
44
- "lint_command",
45
- ]);
46
-
47
- // ── Blocked command patterns ──────────────────────────────────────────────────
48
-
49
- const BLOCKED_COMMAND_PATTERNS = Object.freeze([
50
- /deploy/i,
51
- /publish/i,
52
- /release/i,
53
- /production/i,
54
- /prod/i,
55
- /rm\s+-rf/i,
56
- /git\s+clean/i,
57
- /git\s+reset\s+--hard/i,
58
- /drop\s+table/i,
59
- /truncate/i,
60
- /secret/i,
61
- /auth/i,
62
- /credential/i,
63
- /\.env/i,
64
- /wipe/i,
65
- /destroy/i,
66
- ]);
67
-
68
- // Whitelisted npm script prefixes that are safe to run
69
- const SAFE_SCRIPT_PREFIXES = Object.freeze([
70
- "test",
71
- "build",
72
- "lint",
73
- "type-check",
74
- "typecheck",
75
- "check",
76
- "verify",
77
- "validate",
78
- ]);
79
-
80
- // Maximum allowed command execution timeout (30s)
81
- const MAX_COMMAND_TIMEOUT_MS = 30_000;
82
-
83
- // Max stdout/stderr captured per command
84
- const MAX_OUTPUT_CHARS = 2_000;
85
-
86
- // ── Helpers ───────────────────────────────────────────────────────────────────
87
-
88
- function createRunId() {
89
- return `saferun-${crypto.randomBytes(6).toString("hex")}`;
90
- }
91
-
92
- function nowIso() {
93
- return new Date().toISOString();
94
- }
95
-
96
- function safeReadJson(absPath) {
97
- try {
98
- if (!fs.existsSync(absPath)) return null;
99
- return JSON.parse(fs.readFileSync(absPath, "utf8").replace(/^/, ""));
100
- } catch {
101
- return null;
102
- }
103
- }
104
-
105
- function ensureDir(p) {
106
- fs.mkdirSync(p, { recursive: true });
107
- }
108
-
109
- function safeWriteJson(absPath, obj) {
110
- ensureDir(path.dirname(absPath));
111
- fs.writeFileSync(absPath, JSON.stringify(obj, null, 2), "utf8");
112
- }
113
-
114
- function summarizeOutput(raw) {
115
- if (!raw) return "";
116
- const text = String(raw).slice(0, MAX_OUTPUT_CHARS);
117
- const lines = text.split("\n").filter((l) => l.trim());
118
- if (lines.length === 0) return "";
119
- if (lines.length <= 5) return lines.join("\n");
120
- // Show first 3 and last 2 lines
121
- return [
122
- ...lines.slice(0, 3),
123
- `... (${lines.length - 5} more lines) ...`,
124
- ...lines.slice(-2),
125
- ].join("\n");
126
- }
127
-
128
- // ── Command safety check ──────────────────────────────────────────────────────
129
-
130
- function isCommandSafe(command) {
131
- if (!command || typeof command !== "string") return false;
132
- const lower = command.toLowerCase().trim();
133
- // Must not match any blocked pattern
134
- for (const pattern of BLOCKED_COMMAND_PATTERNS) {
135
- if (pattern.test(lower)) return false;
136
- }
137
- return true;
138
- }
139
-
140
- function isScriptNameSafe(scriptName) {
141
- if (!scriptName || typeof scriptName !== "string") return false;
142
- const lower = scriptName.toLowerCase().trim();
143
- for (const pattern of BLOCKED_COMMAND_PATTERNS) {
144
- if (pattern.test(lower)) return false;
145
- }
146
- return SAFE_SCRIPT_PREFIXES.some((prefix) => lower === prefix || lower.startsWith(prefix + ":") || lower.startsWith(prefix + "-") || lower.startsWith(prefix + "_"));
147
- }
148
-
149
- // ── Project profile discovery ─────────────────────────────────────────────────
150
-
151
- function getProjectProfile(cwd) {
152
- try {
153
- const { detectProjectProfile } = require("./project-profile");
154
- return detectProjectProfile(cwd);
155
- } catch {
156
- return null;
157
- }
158
- }
159
-
160
- // ── Discover safe local proof commands from project profile ───────────────────
161
-
162
- function discoverSafeLocalCommands(cwd, profile) {
163
- const commands = [];
164
-
165
- // Read package.json scripts to determine what's available
166
- let scripts = {};
167
- try {
168
- const pkgPath = path.join(cwd, "package.json");
169
- const pkg = safeReadJson(pkgPath);
170
- scripts = (pkg && pkg.scripts) || {};
171
- } catch {}
172
-
173
- const profileCommands = (profile && profile.commands) || {};
174
-
175
- // test
176
- if (profileCommands.test && isCommandSafe(profileCommands.test)) {
177
- const scriptName = profileCommands.test.replace(/^npm\s+(run\s+)?/, "").trim();
178
- if (scriptName === "test" || scripts[scriptName]) {
179
- commands.push({
180
- type: "test_command",
181
- label: "Run tests",
182
- command: "npm",
183
- args: profileCommands.test.includes("run") ? ["run", scriptName] : ["test"],
184
- scriptName: scriptName === "test" ? "test" : `run:${scriptName}`,
185
- });
186
- }
187
- }
188
-
189
- // build
190
- if (profileCommands.build && isCommandSafe(profileCommands.build)) {
191
- const scriptName = profileCommands.build.replace(/^npm\s+(run\s+)?/, "").trim();
192
- if (scripts[scriptName] || scriptName === "build") {
193
- commands.push({
194
- type: "build_command",
195
- label: "Run build",
196
- command: "npm",
197
- args: ["run", scriptName],
198
- scriptName: `run:${scriptName}`,
199
- });
200
- }
201
- }
202
-
203
- // lint (only if present)
204
- if (profileCommands.lint && isCommandSafe(profileCommands.lint)) {
205
- const scriptName = profileCommands.lint.replace(/^npm\s+(run\s+)?/, "").trim();
206
- if (scripts[scriptName]) {
207
- commands.push({
208
- type: "lint_command",
209
- label: "Run lint",
210
- command: "npm",
211
- args: ["run", scriptName],
212
- scriptName: `run:${scriptName}`,
213
- });
214
- }
215
- }
216
-
217
- return commands;
218
- }
219
-
220
- // ── Run a single whitelisted local step ───────────────────────────────────────
221
-
222
- function runAllowedLocalStep(cwd, step, options = {}) {
223
- const timeout = Math.min(options.timeout || MAX_COMMAND_TIMEOUT_MS, MAX_COMMAND_TIMEOUT_MS);
224
- const startedAt = nowIso();
225
- const startMs = Date.now();
226
-
227
- if (!step || !ALLOWED_STEP_TYPES.includes(step.type)) {
228
- return {
229
- stepType: step?.type || "unknown",
230
- status: "blocked",
231
- reason: "Step type not in allowed list.",
232
- exitCode: null,
233
- duration: 0,
234
- outputSummary: "",
235
- redacted: true,
236
- };
237
- }
238
-
239
- // Only command steps require actual execution
240
- if (!["test_command", "build_command", "lint_command"].includes(step.type)) {
241
- return {
242
- stepType: step.type,
243
- status: "non_executable",
244
- reason: "Non-command step — orchestration only.",
245
- exitCode: null,
246
- duration: 0,
247
- outputSummary: "",
248
- redacted: true,
249
- };
250
- }
251
-
252
- // Safety gate on the command
253
- const fullCommand = [step.command, ...(step.args || [])].join(" ");
254
- if (!isCommandSafe(fullCommand)) {
255
- return {
256
- stepType: step.type,
257
- status: "blocked",
258
- reason: "Command failed safety check — blocked pattern detected.",
259
- command: "[redacted]",
260
- exitCode: null,
261
- duration: 0,
262
- outputSummary: "",
263
- redacted: true,
264
- };
265
- }
266
-
267
- // Additional script name check
268
- const scriptArg = (step.args || []).find((a) => a !== "run" && a !== "test");
269
- if (scriptArg && step.args[0] === "run" && !isScriptNameSafe(scriptArg)) {
270
- return {
271
- stepType: step.type,
272
- status: "blocked",
273
- reason: `Script name '${scriptArg}' is not in safe script whitelist.`,
274
- exitCode: null,
275
- duration: 0,
276
- outputSummary: "",
277
- redacted: true,
278
- };
279
- }
280
-
281
- try {
282
- const result = spawnSync(step.command, step.args || [], {
283
- cwd,
284
- timeout,
285
- encoding: "utf8",
286
- env: { ...process.env, CI: "true", FORCE_COLOR: "0" },
287
- maxBuffer: 1024 * 512, // 512 KB
288
- });
289
-
290
- const duration = Date.now() - startMs;
291
- const stdout = summarizeOutput(result.stdout || "");
292
- const stderr = summarizeOutput(result.stderr || "");
293
- const exitCode = result.status ?? (result.error ? 1 : 0);
294
- const timedOut = result.signal === "SIGTERM" || (result.error && result.error.code === "ETIMEDOUT");
295
-
296
- return {
297
- stepType: step.type,
298
- label: step.label,
299
- status: timedOut ? "timeout" : exitCode === 0 ? "pass" : "fail",
300
- exitCode,
301
- duration,
302
- timedOut,
303
- outputSummary: [stdout, stderr].filter(Boolean).join("\n---\n").slice(0, MAX_OUTPUT_CHARS),
304
- redacted: true,
305
- };
306
- } catch (err) {
307
- return {
308
- stepType: step.type,
309
- status: "error",
310
- reason: err.message,
311
- exitCode: null,
312
- duration: Date.now() - startMs,
313
- outputSummary: "",
314
- redacted: true,
315
- };
316
- }
317
- }
318
-
319
- // ── Determine overall run decision ────────────────────────────────────────────
320
-
321
- function resolveRunDecision(routeDecision, taskRiskLevel, options = {}) {
322
- if (options.prepareOnly) return "prepared";
323
- if (["blocked"].includes(routeDecision)) return "blocked";
324
- if (["approval_required"].includes(routeDecision)) return "approval_required";
325
- if (["auto_execute", "auto_prepare"].includes(routeDecision)) {
326
- return taskRiskLevel === "low" ? "verified" : "prepared";
327
- }
328
- return "prepared";
329
- }
330
-
331
- function resolveRunMode(routeDecision, riskLevel) {
332
- if (["blocked", "approval_required"].includes(routeDecision)) return "manual_debug";
333
- if (riskLevel === "low") return "automatic";
334
- return "assisted";
335
- }
336
-
337
- // ── Build safe run plan ───────────────────────────────────────────────────────
338
-
339
- function buildSafeRunPlan(cwd, taskText, options = {}) {
340
- const runId = createRunId();
341
- const createdAt = nowIso();
342
-
343
- // Step 1: project profile
344
- const profile = getProjectProfile(cwd);
345
- const profileRef = path.join(".claude/cco/orchestration/project-profile", "latest-profile.json");
346
-
347
- // Step 2: smart route (reuse existing module, do not duplicate)
348
- let route = null;
349
- let routeDecision = "auto_prepare";
350
- let routeReasonCodes = [];
351
- let smartRouteRef = null;
352
- try {
353
- const { buildSmartWorkRoute, writeSmartWorkRouteReceipt, LATEST_ROUTE_REL } = require("./smart-work-routing");
354
- route = buildSmartWorkRoute(cwd, taskText, { taskText });
355
- if (!options.dryRun) {
356
- writeSmartWorkRouteReceipt(cwd, route);
357
- }
358
- routeDecision = route.decision || "auto_prepare";
359
- routeReasonCodes = (route.executionPath && route.executionPath.reasonCodes) || [];
360
- smartRouteRef = LATEST_ROUTE_REL;
361
- } catch (err) {
362
- routeDecision = "auto_prepare";
363
- }
364
-
365
- // Step 3: execution packet (reuse existing module)
366
- let packet = null;
367
- let packetRef = null;
368
- try {
369
- const { compileExecutionPacket, writeExecutionPacket, LATEST_PACKET_REL } = require("./execution-packet");
370
- packet = compileExecutionPacket(cwd, { userIntent: taskText });
371
- if (!options.dryRun) {
372
- writeExecutionPacket(cwd, packet);
373
- }
374
- packetRef = LATEST_PACKET_REL;
375
- } catch {}
376
-
377
- // Step 4: worker handoff (reuse existing module)
378
- let handoff = null;
379
- let handoffRef = null;
380
- try {
381
- const { buildWorkerHandoff, writeWorkerHandoffReceipt, LATEST_HANDOFF_REL } = require("./smart-work-routing");
382
- if (route) {
383
- handoff = buildWorkerHandoff(cwd, route, {});
384
- if (!options.dryRun) {
385
- writeWorkerHandoffReceipt(cwd, handoff);
386
- }
387
- handoffRef = LATEST_HANDOFF_REL;
388
- }
389
- } catch {}
390
-
391
- // Step 5: classify task for safe step planning
392
- const task = (route && route.task) || { summary: taskText, riskLevel: "medium", taskType: "unknown" };
393
- const riskLevel = task.riskLevel || "medium";
394
- const taskType = task.taskType || "unknown";
395
-
396
- // Step 6: determine allowed local steps
397
- const allowedLocalSteps = [];
398
- const blockedSteps = [];
399
-
400
- // Always allow orchestration steps
401
- allowedLocalSteps.push(
402
- { type: "project_profile", label: "Detect project profile", status: "done", ref: profileRef },
403
- { type: "smart_route", label: "Build smart route", status: "done", ref: smartRouteRef },
404
- { type: "execution_packet", label: "Compile execution packet", status: "done", ref: packetRef },
405
- { type: "worker_handoff", label: "Prepare worker handoff", status: "done", ref: handoffRef }
406
- );
407
-
408
- // Proof/local command steps only when safe
409
- const localCommandsAllowed =
410
- !options.prepareOnly &&
411
- !["high", "critical"].includes(riskLevel) &&
412
- !["blocked", "approval_required"].includes(routeDecision);
413
-
414
- const discoveredCommands = (profile && localCommandsAllowed)
415
- ? discoverSafeLocalCommands(cwd, profile)
416
- : [];
417
-
418
- for (const cmd of discoveredCommands) {
419
- allowedLocalSteps.push({ ...cmd, status: "pending" });
420
- }
421
-
422
- if (!localCommandsAllowed && !options.prepareOnly) {
423
- blockedSteps.push({
424
- reason: routeDecision === "blocked"
425
- ? "Task is blocked — no local execution performed."
426
- : routeDecision === "approval_required"
427
- ? "Task requires approval — no local execution performed."
428
- : `Task risk level '${riskLevel}' prevents automatic local proof execution.`,
429
- });
430
- }
431
-
432
- // Ledger/proof/outcome steps
433
- allowedLocalSteps.push(
434
- { type: "ledger_update", label: "Update work ledger", status: "pending" },
435
- { type: "proof_summary", label: "Write proof summary", status: "pending" },
436
- { type: "outcome_summary", label: "Update outcome summary", status: "pending" }
437
- );
438
-
439
- // Step 7: proof plan
440
- const proofRequired = (route && route.executionPath && route.executionPath.proofRequired) === true;
441
- const proofPlan = {
442
- proofRequired,
443
- steps: proofRequired
444
- ? ["run tests", "run build", "write proof artifact"]
445
- : ["route receipt written", "packet receipt written", "handoff receipt written"],
446
- approvalRequiredFirst: ["blocked", "approval_required"].includes(routeDecision),
447
- };
448
-
449
- // Step 8: safe next action
450
- const safeNextAction = buildSafeNextAction(routeDecision, riskLevel, taskType, route);
451
-
452
- // Step 9: run decision and mode
453
- const decision = resolveRunDecision(routeDecision, riskLevel, options);
454
- const mode = resolveRunMode(routeDecision, riskLevel);
455
-
456
- // Step 10: value evidence
457
- const valueEvidence = {
458
- stepsOrchestrated: allowedLocalSteps.length,
459
- localCommandsAllowed: discoveredCommands.length,
460
- secretsExcluded: true,
461
- deployBlocked: routeDecision === "blocked" || routeDecision === "approval_required",
462
- caveats: [
463
- "Savings estimates are approximations from receipt data, not exact billing amounts.",
464
- "No guaranteed savings claimed.",
465
- ],
466
- redacted: true,
467
- };
468
-
469
- return {
470
- contract: CONTRACT,
471
- schemaVersion: SCHEMA_VERSION,
472
- runId,
473
- createdAt,
474
- task: {
475
- summary: task.summary || taskText,
476
- riskLevel,
477
- taskType,
478
- },
479
- mode,
480
- decision,
481
- smartRouteRef,
482
- executionPacketRef: packetRef,
483
- workerHandoffRef: handoffRef,
484
- allowedLocalSteps,
485
- blockedSteps,
486
- proofPlan,
487
- executionSummary: null, // filled after execution
488
- safety: {
489
- secretsExcluded: true,
490
- broadContextExcluded: true,
491
- deployBlocked: true,
492
- destructiveBlocked: true,
493
- remoteAgentExecutionBlocked: true,
494
- codeModificationBlocked: true,
495
- localCommandsWhitelisted: true,
496
- },
497
- receipts: {
498
- smartRoute: smartRouteRef,
499
- executionPacket: packetRef,
500
- workerHandoff: handoffRef,
501
- safeRun: LATEST_RUN_REL,
502
- },
503
- valueEvidence,
504
- safeNextAction,
505
- redacted: true,
506
- };
507
- }
508
-
509
- function buildSafeNextAction(routeDecision, riskLevel, taskType, route) {
510
- if (routeDecision === "blocked") {
511
- return "Task blocked. Review the reason codes, narrow the scope, and re-run with a safer task description.";
512
- }
513
- if (routeDecision === "approval_required") {
514
- const base = (route && route.executionPath && route.executionPath.safeNextAction) || "";
515
- if (taskType === "deployment_release") {
516
- return "Run tests and build verification first: avorelo run \"run tests and build\", then request deployment approval.";
517
- }
518
- if (taskType === "security_sensitive") {
519
- return "Review security scope with avorelo guard before making auth changes.";
520
- }
521
- return base || "Approval required. Review scope and constraints, then proceed with worker handoff.";
522
- }
523
- if (riskLevel === "high") {
524
- return "Worker handoff prepared. Review scope before executing with target worker.";
525
- }
526
- if (["documentation", "summarization"].includes(taskType)) {
527
- return "Route, packet, and handoff prepared. Safe to execute with local or cheap worker.";
528
- }
529
- return "Route, packet, and handoff prepared. Run local proof steps, then execute with worker.";
530
- }
531
-
532
- // ── Execute safe run plan ─────────────────────────────────────────────────────
533
-
534
- function executeSafeRunPlan(cwd, runPlan, options = {}) {
535
- if (!runPlan || runPlan.contract !== CONTRACT) {
536
- throw new Error("Invalid run plan: missing or mismatched contract.");
537
- }
538
-
539
- const execResults = [];
540
- let localStepsRun = 0;
541
- let localStepsPassed = 0;
542
- let localStepsFailed = 0;
543
- let localStepsBlocked = 0;
544
-
545
- const pendingCommandSteps = (runPlan.allowedLocalSteps || []).filter(
546
- (s) => ["test_command", "build_command", "lint_command"].includes(s.type) && s.status === "pending"
547
- );
548
-
549
- for (const step of pendingCommandSteps) {
550
- const result = runAllowedLocalStep(cwd, step, { timeout: MAX_COMMAND_TIMEOUT_MS });
551
- execResults.push(result);
552
- localStepsRun++;
553
-
554
- if (result.status === "pass") localStepsPassed++;
555
- else if (result.status === "blocked") localStepsBlocked++;
556
- else localStepsFailed++;
557
-
558
- // Emit product learning event (best-effort)
559
- try {
560
- const { appendProductLearningEvent } = require("./product-learning-events");
561
- appendProductLearningEvent(cwd, {
562
- eventName: result.status === "pass" ? "safe_run_local_step_completed" : "safe_run_local_step_blocked",
563
- category: "safe_run",
564
- surface: "local",
565
- status: "observed",
566
- payload: {
567
- stepType: result.stepType,
568
- status: result.status,
569
- exitCode: result.exitCode,
570
- durationMs: result.duration,
571
- },
572
- });
573
- } catch {}
574
- }
575
-
576
- // Ledger update (best-effort)
577
- try {
578
- writeSafeRunLedgerEntry(cwd, runPlan, execResults);
579
- } catch {}
580
-
581
- const allPassed = localStepsFailed === 0 && localStepsBlocked === 0;
582
- const finalDecision =
583
- runPlan.decision === "blocked" ? "blocked"
584
- : runPlan.decision === "approval_required" ? "approval_required"
585
- : localStepsRun > 0 && allPassed ? "verified"
586
- : localStepsRun > 0 && localStepsFailed > 0 ? "partial"
587
- : "prepared";
588
-
589
- const executionSummary = {
590
- localStepsRun,
591
- localStepsPassed,
592
- localStepsFailed,
593
- localStepsBlocked,
594
- results: execResults,
595
- finalDecision,
596
- completedAt: nowIso(),
597
- redacted: true,
598
- };
599
-
600
- return { ...runPlan, executionSummary, decision: finalDecision };
601
- }
602
-
603
- // ── Write safe run receipt ────────────────────────────────────────────────────
604
-
605
- function writeSafeRunReceipt(cwd, receipt) {
606
- const absPath = path.join(cwd, LATEST_RUN_REL);
607
- // Ensure no raw prompt/code/secrets in receipt
608
- const safe = {
609
- ...receipt,
610
- task: receipt.task
611
- ? { summary: receipt.task.summary, riskLevel: receipt.task.riskLevel, taskType: receipt.task.taskType }
612
- : null,
613
- redacted: true,
614
- };
615
- safeWriteJson(absPath, safe);
616
- return absPath;
617
- }
618
-
619
- // ── Ledger entry writer ───────────────────────────────────────────────────────
620
-
621
- function writeSafeRunLedgerEntry(cwd, runPlan, execResults) {
622
- try {
623
- const { normalizeLedgerEntry } = require("./work-ledger");
624
- const decision = runPlan.decision || "prepared";
625
- const localRan = (execResults || []).filter((r) => r.status === "pass").length;
626
- const localFailed = (execResults || []).filter((r) => r.status === "fail").length;
627
-
628
- const valueSignals = [];
629
- if (localRan > 0) valueSignals.push(`${localRan} local proof step(s) passed`);
630
- if (runPlan.safety && runPlan.safety.deployBlocked) valueSignals.push("deploy_blocked");
631
- if (runPlan.safety && runPlan.safety.secretsExcluded) valueSignals.push("secrets_excluded");
632
-
633
- const frictionSignals = [];
634
- if (decision === "approval_required") frictionSignals.push("approval_required");
635
- if (decision === "blocked") frictionSignals.push("task_blocked");
636
- if (localFailed > 0) frictionSignals.push(`${localFailed}_local_step(s)_failed`);
637
-
638
- return normalizeLedgerEntry("safe_run", "safe_run_controller", runPlan, {
639
- // blocked/approval_required = safety working correctly (warn), not a broken system
640
- status: decision === "verified" ? "pass" : "warn",
641
- summary: `Safe run: decision=${decision}, localStepsRun=${(execResults || []).length}.`,
642
- evidencePath: LATEST_RUN_REL,
643
- evidenceKind: "receipt",
644
- valueSignals,
645
- frictionSignals,
646
- reasonCodes: [],
647
- });
648
- } catch {
649
- return null;
650
- }
651
- }
652
-
653
- // ── Build safe run surface ────────────────────────────────────────────────────
654
-
655
- function buildSafeRunSurface(cwd, options = {}) {
656
- const absPath = path.join(cwd, LATEST_RUN_REL);
657
- const receipt = safeReadJson(absPath);
658
-
659
- if (!receipt) {
660
- return {
661
- status: "not_run",
662
- latestRunPath: LATEST_RUN_REL,
663
- decision: null,
664
- nextAction: "Run `avorelo run \"<task>\"` to execute the safe run pipeline.",
665
- };
666
- }
667
-
668
- return {
669
- status: "present",
670
- latestRunPath: LATEST_RUN_REL,
671
- decision: receipt.decision,
672
- mode: receipt.mode,
673
- runId: receipt.runId,
674
- task: receipt.task
675
- ? { taskType: receipt.task.taskType, riskLevel: receipt.task.riskLevel }
676
- : null,
677
- localStepsRun: receipt.executionSummary?.localStepsRun ?? 0,
678
- nextAction: receipt.safeNextAction,
679
- };
680
- }
681
-
682
- // ── Format safe run text ──────────────────────────────────────────────────────
683
-
684
- function formatSafeRunText(receipt, options = {}) {
685
- const debug = options.debug === true;
686
- const decision = receipt.decision || "prepared";
687
- const execSummary = receipt.executionSummary;
688
-
689
- const lines = [];
690
-
691
- if (decision === "blocked") {
692
- lines.push("Blocked:");
693
- const blockedSteps = receipt.blockedSteps || [];
694
- for (const b of blockedSteps) {
695
- lines.push(` - ${b.reason}`);
696
- }
697
- lines.push("Safe next action:");
698
- lines.push(` - ${receipt.safeNextAction}`);
699
- lines.push("No execution performed.");
700
- return lines.join("\n");
701
- }
702
-
703
- if (decision === "approval_required") {
704
- lines.push("ACTION REQUIRED");
705
- const route = null; // route reason comes from reasonCodes in receipt
706
- lines.push(`Reason: Task requires explicit approval before execution.`);
707
- lines.push(`Safe next action: ${receipt.safeNextAction}`);
708
- lines.push("Prepared:");
709
- lines.push(" - smart route");
710
- lines.push(" - execution packet");
711
- lines.push(" - worker handoff");
712
- lines.push("Proof needed:");
713
- for (const step of (receipt.proofPlan && receipt.proofPlan.steps) || []) {
714
- lines.push(` - ${step}`);
715
- }
716
- return lines.join("\n");
717
- }
718
-
719
- // Normal (prepared / verified / partial)
720
- lines.push("Avorelo prepared the safe run.");
721
- lines.push("");
722
- lines.push("Done:");
723
- lines.push(" - Routed task safely.");
724
- lines.push(" - Compiled execution packet.");
725
- lines.push(" - Prepared worker handoff.");
726
-
727
- if (execSummary && execSummary.localStepsRun > 0) {
728
- const passed = execSummary.localStepsPassed;
729
- const total = execSummary.localStepsRun;
730
- lines.push(` - Ran allowed local proof steps: ${passed}/${total} passed.`);
731
- } else {
732
- lines.push(" - Proof prepared (local steps deferred or not applicable).");
733
- }
734
-
735
- lines.push("");
736
- lines.push("Protected:");
737
- lines.push(" - Secrets/deploy/destructive actions blocked.");
738
- lines.push(" - Broad context excluded.");
739
- lines.push("");
740
- lines.push(`Next:`);
741
- lines.push(` - ${receipt.safeNextAction}`);
742
-
743
- if (debug) {
744
- lines.push("");
745
- lines.push("--- Debug ---");
746
- lines.push(`Run ID: ${receipt.runId}`);
747
- lines.push(`Mode: ${receipt.mode}`);
748
- lines.push(`Decision: ${decision}`);
749
- lines.push(`Task type: ${receipt.task && receipt.task.taskType}`);
750
- lines.push(`Risk level: ${receipt.task && receipt.task.riskLevel}`);
751
- lines.push(`Smart route ref: ${receipt.smartRouteRef || "none"}`);
752
- lines.push(`Execution packet ref: ${receipt.executionPacketRef || "none"}`);
753
- lines.push(`Worker handoff ref: ${receipt.workerHandoffRef || "none"}`);
754
- lines.push(`Safe run receipt: ${LATEST_RUN_REL}`);
755
-
756
- const allowedSteps = receipt.allowedLocalSteps || [];
757
- lines.push(`Allowed local steps: ${allowedSteps.length}`);
758
- for (const s of allowedSteps) {
759
- lines.push(` [${s.status || "?"}] ${s.type}: ${s.label || ""}`);
760
- }
761
-
762
- const blockedSteps = receipt.blockedSteps || [];
763
- if (blockedSteps.length > 0) {
764
- lines.push(`Blocked steps: ${blockedSteps.length}`);
765
- for (const b of blockedSteps) {
766
- lines.push(` - ${b.reason}`);
767
- }
768
- }
769
-
770
- if (execSummary && Array.isArray(execSummary.results)) {
771
- lines.push("Local command results:");
772
- for (const r of execSummary.results) {
773
- lines.push(` [${r.status}] ${r.stepType} (exit ${r.exitCode}, ${r.duration}ms)`);
774
- if (r.outputSummary) {
775
- lines.push(` ${r.outputSummary.replace(/\n/g, "\n ")}`);
776
- }
777
- }
778
- }
779
- }
780
-
781
- return lines.join("\n");
782
- }
783
-
784
- // ── Main run orchestrator ─────────────────────────────────────────────────────
785
-
786
- function runSafeControlPipeline(cwd, taskText, options = {}) {
787
- // Build plan
788
- const plan = buildSafeRunPlan(cwd, taskText, options);
789
-
790
- // Execute (unless prepare-only or dry-run)
791
- let finalReceipt = plan;
792
- if (!options.prepareOnly && !options.dryRun && !["blocked", "approval_required"].includes(plan.decision)) {
793
- finalReceipt = executeSafeRunPlan(cwd, plan, options);
794
- }
795
-
796
- // Emit events (best-effort)
797
- try {
798
- const { appendProductLearningEvent } = require("./product-learning-events");
799
- appendProductLearningEvent(cwd, {
800
- eventName: "safe_run_started",
801
- category: "safe_run",
802
- surface: "local",
803
- status: "observed",
804
- payload: { runId: plan.runId, taskType: plan.task.taskType, riskLevel: plan.task.riskLevel },
805
- });
806
- appendProductLearningEvent(cwd, {
807
- eventName: "safe_run_plan_built",
808
- category: "safe_run",
809
- surface: "local",
810
- status: "observed",
811
- payload: {
812
- decision: plan.decision,
813
- allowedLocalSteps: plan.allowedLocalSteps.length,
814
- blockedSteps: plan.blockedSteps.length,
815
- },
816
- });
817
- if (finalReceipt.decision === "approval_required") {
818
- appendProductLearningEvent(cwd, {
819
- eventName: "safe_run_approval_required",
820
- category: "safe_run",
821
- surface: "local",
822
- status: "observed",
823
- payload: { runId: plan.runId, taskType: plan.task.taskType },
824
- });
825
- } else if (finalReceipt.decision === "blocked") {
826
- appendProductLearningEvent(cwd, {
827
- eventName: "safe_run_blocked",
828
- category: "safe_run",
829
- surface: "local",
830
- status: "observed",
831
- payload: { runId: plan.runId, taskType: plan.task.taskType },
832
- });
833
- } else {
834
- appendProductLearningEvent(cwd, {
835
- eventName: "safe_run_completed",
836
- category: "safe_run",
837
- surface: "local",
838
- status: "observed",
839
- payload: {
840
- runId: plan.runId,
841
- decision: finalReceipt.decision,
842
- localStepsRun: finalReceipt.executionSummary?.localStepsRun ?? 0,
843
- },
844
- });
845
- }
846
- } catch {}
847
-
848
- // Write receipt (best-effort)
849
- try {
850
- if (!options.dryRun) {
851
- writeSafeRunReceipt(cwd, finalReceipt);
852
- appendProductLearningEventSafe(cwd, {
853
- eventName: "safe_run_receipt_written",
854
- category: "safe_run",
855
- surface: "local",
856
- status: "observed",
857
- payload: { runId: plan.runId, receiptPath: LATEST_RUN_REL },
858
- });
859
- }
860
- } catch {}
861
-
862
- return finalReceipt;
863
- }
864
-
865
- function appendProductLearningEventSafe(cwd, event) {
866
- try {
867
- const { appendProductLearningEvent } = require("./product-learning-events");
868
- appendProductLearningEvent(cwd, event);
869
- } catch {}
870
- }
871
-
872
- module.exports = {
873
- CONTRACT,
874
- SCHEMA_VERSION,
875
- LATEST_RUN_REL,
876
- ALLOWED_STEP_TYPES,
877
- buildSafeRunPlan,
878
- executeSafeRunPlan,
879
- runAllowedLocalStep,
880
- writeSafeRunReceipt,
881
- writeSafeRunLedgerEntry,
882
- buildSafeRunSurface,
883
- formatSafeRunText,
884
- runSafeControlPipeline,
885
- isCommandSafe,
886
- discoverSafeLocalCommands,
887
- };