avorelo 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +56 -0
- package/bin/avorelo +9 -0
- package/package.json +135 -0
- package/scripts/README.md +40 -0
- package/scripts/cco-dashboard.js +252 -0
- package/scripts/cco-status.js +430 -0
- package/scripts/lib/activation/account-state.js +37 -0
- package/scripts/lib/activation/activation-runner.js +546 -0
- package/scripts/lib/activation/activation-self-healing.js +480 -0
- package/scripts/lib/activation/activation-state.js +83 -0
- package/scripts/lib/activation/activation-summary.js +191 -0
- package/scripts/lib/activation/adapters/claude-code.js +77 -0
- package/scripts/lib/activation/adapters/codex-cli.js +52 -0
- package/scripts/lib/activation/adapters/cursor.js +37 -0
- package/scripts/lib/activation/adapters/github-agent.js +39 -0
- package/scripts/lib/activation/adapters/terminal.js +42 -0
- package/scripts/lib/activation/adapters/vscode.js +39 -0
- package/scripts/lib/activation/adapters/windsurf.js +37 -0
- package/scripts/lib/activation/ai-surface-detector.js +151 -0
- package/scripts/lib/activation/connect-account.js +145 -0
- package/scripts/lib/activation/detect-environment.js +75 -0
- package/scripts/lib/activation/detect-hosts.js +62 -0
- package/scripts/lib/activation/format-activation-output.js +109 -0
- package/scripts/lib/activation/next-action.js +43 -0
- package/scripts/lib/activation/repair-engine.js +219 -0
- package/scripts/lib/activation-distribution-readiness.js +507 -0
- package/scripts/lib/adapter-conformance.js +176 -0
- package/scripts/lib/adapter-readiness.js +417 -0
- package/scripts/lib/adapter-safety-boundaries.js +335 -0
- package/scripts/lib/adapter-technical-readiness-gate.js +205 -0
- package/scripts/lib/agent-access-governance.js +455 -0
- package/scripts/lib/agent-enforcement.js +765 -0
- package/scripts/lib/agent-policy-profile.js +210 -0
- package/scripts/lib/agent-security/action-evaluator.js +507 -0
- package/scripts/lib/agent-security/adapter-registry.js +98 -0
- package/scripts/lib/agent-security/auto-policy.js +139 -0
- package/scripts/lib/agent-security/bounded-scan.js +93 -0
- package/scripts/lib/agent-security/enforcement-adapter.js +174 -0
- package/scripts/lib/agent-security/enforcement-engine.js +1129 -0
- package/scripts/lib/agent-security/file-write-adapter.js +183 -0
- package/scripts/lib/agent-security/file-write-rules.js +178 -0
- package/scripts/lib/agent-security/index.js +3342 -0
- package/scripts/lib/agent-security/instruction-risk.js +181 -0
- package/scripts/lib/agent-security/mcp-action-adapter.js +185 -0
- package/scripts/lib/agent-security/mcp-action-rules.js +184 -0
- package/scripts/lib/agent-security/package-action-adapter.js +175 -0
- package/scripts/lib/agent-security/package-action-rules.js +233 -0
- package/scripts/lib/agent-security/performance.js +148 -0
- package/scripts/lib/agent-security/permission-minimizer.js +403 -0
- package/scripts/lib/agent-security/scan-cache.js +74 -0
- package/scripts/lib/agent-security/source-trust.js +146 -0
- package/scripts/lib/ai-install-prompt.js +288 -0
- package/scripts/lib/ai-workspace-hygiene.js +1499 -0
- package/scripts/lib/alpha-activation.js +520 -0
- package/scripts/lib/alpha-feedback.js +263 -0
- package/scripts/lib/alpha-readiness-gate.js +332 -0
- package/scripts/lib/anti-gaming.js +169 -0
- package/scripts/lib/artifact-health.js +431 -0
- package/scripts/lib/attribution.js +180 -0
- package/scripts/lib/audit.js +289 -0
- package/scripts/lib/avorelo-skill-registry.js +810 -0
- package/scripts/lib/batch-jobs.js +71 -0
- package/scripts/lib/brain-pack.js +578 -0
- package/scripts/lib/brand-boundary.js +424 -0
- package/scripts/lib/brand.js +74 -0
- package/scripts/lib/browser-capability.js +1048 -0
- package/scripts/lib/browser-proof-preflight.js +321 -0
- package/scripts/lib/cache-readiness.js +187 -0
- package/scripts/lib/canonical-reentry.js +162 -0
- package/scripts/lib/capability-packs.js +314 -0
- package/scripts/lib/capability-recommender.js +512 -0
- package/scripts/lib/capability-registry.js +1059 -0
- package/scripts/lib/carry-forward-surfacing.js +194 -0
- package/scripts/lib/ccusage-adapter.js +188 -0
- package/scripts/lib/company-loop.js +1149 -0
- package/scripts/lib/config.js +637 -0
- package/scripts/lib/context-acquisition-plan.js +287 -0
- package/scripts/lib/context-budget-guard.js +170 -0
- package/scripts/lib/context-budget-scanner.js +257 -0
- package/scripts/lib/context-optimizer.js +715 -0
- package/scripts/lib/context-reduction-plan.js +178 -0
- package/scripts/lib/context-safety.js +88 -0
- package/scripts/lib/context-savings-engine.js +158 -0
- package/scripts/lib/cost-evidence.js +254 -0
- package/scripts/lib/cross-host-install-plan.js +308 -0
- package/scripts/lib/cross-host-install-readiness.js +237 -0
- package/scripts/lib/cross-host-value-flow.js +268 -0
- package/scripts/lib/dashboard.js +900 -0
- package/scripts/lib/design-partner-feedback.js +346 -0
- package/scripts/lib/entitlements.js +100 -0
- package/scripts/lib/execution-packet.js +559 -0
- package/scripts/lib/experimentation-events.js +547 -0
- package/scripts/lib/external-capability-compliance.js +107 -0
- package/scripts/lib/external-user-simulation.js +166 -0
- package/scripts/lib/failure-recovery-readiness.js +81 -0
- package/scripts/lib/failure-recovery.js +419 -0
- package/scripts/lib/feedback-intelligence.js +537 -0
- package/scripts/lib/feedback-signals.js +205 -0
- package/scripts/lib/file-integrity.js +68 -0
- package/scripts/lib/fsx.js +127 -0
- package/scripts/lib/full-readiness-gate.js +451 -0
- package/scripts/lib/guidance-builder.js +174 -0
- package/scripts/lib/hook-apply.js +1019 -0
- package/scripts/lib/hook-baseline.js +310 -0
- package/scripts/lib/hook-config-preview.js +275 -0
- package/scripts/lib/hook-contracts.js +290 -0
- package/scripts/lib/hook-safety-boundary-readiness.js +80 -0
- package/scripts/lib/host-capability-matrix.js +351 -0
- package/scripts/lib/host-support-context.js +254 -0
- package/scripts/lib/http-hook-action.js +538 -0
- package/scripts/lib/install-ai-readiness.js +84 -0
- package/scripts/lib/install-intake-risk.js +1037 -0
- package/scripts/lib/install-journey-intelligence.js +329 -0
- package/scripts/lib/intervention-guidance.js +57 -0
- package/scripts/lib/known-limitations.js +115 -0
- package/scripts/lib/l8-path-truth.js +146 -0
- package/scripts/lib/launch-hardening-gate.js +436 -0
- package/scripts/lib/launch-readiness.js +628 -0
- package/scripts/lib/learning-memory.js +686 -0
- package/scripts/lib/lifecycle-hooks.js +802 -0
- package/scripts/lib/local-package-smoke.js +423 -0
- package/scripts/lib/local-pricing.js +299 -0
- package/scripts/lib/mcp-enforcement.js +311 -0
- package/scripts/lib/mcp-least-privilege-policy.js +303 -0
- package/scripts/lib/mcp-tool-inventory.js +388 -0
- package/scripts/lib/mcp-tool-risk.js +0 -0
- package/scripts/lib/memory.js +335 -0
- package/scripts/lib/metrics.js +699 -0
- package/scripts/lib/micro-proof.js +133 -0
- package/scripts/lib/next-run-context.js +436 -0
- package/scripts/lib/operating-value.js +1648 -0
- package/scripts/lib/optimization-v3.js +122 -0
- package/scripts/lib/orchestration/adapters/_shared.js +49 -0
- package/scripts/lib/orchestration/adapters/aider.js +18 -0
- package/scripts/lib/orchestration/adapters/claude-code.js +35 -0
- package/scripts/lib/orchestration/adapters/codex.js +35 -0
- package/scripts/lib/orchestration/adapters/gemini-cli.js +18 -0
- package/scripts/lib/orchestration/adapters/git.js +25 -0
- package/scripts/lib/orchestration/adapters/index.js +31 -0
- package/scripts/lib/orchestration/adapters/lm-studio.js +18 -0
- package/scripts/lib/orchestration/adapters/ollama.js +18 -0
- package/scripts/lib/orchestration/adapters/opencode.js +18 -0
- package/scripts/lib/orchestration/adapters/openrouter.js +18 -0
- package/scripts/lib/orchestration/adapters/test-runner.js +25 -0
- package/scripts/lib/orchestration/cli.js +438 -0
- package/scripts/lib/orchestration/execution-manager.js +279 -0
- package/scripts/lib/orchestration/handoff.js +314 -0
- package/scripts/lib/orchestration/index.js +456 -0
- package/scripts/lib/orchestration/inventory.js +47 -0
- package/scripts/lib/orchestration/model-discovery.js +498 -0
- package/scripts/lib/orchestration/model-profiler.js +170 -0
- package/scripts/lib/orchestration/model-profiles.js +252 -0
- package/scripts/lib/orchestration/model-refresh-policy.js +72 -0
- package/scripts/lib/orchestration/proof-writer.js +349 -0
- package/scripts/lib/orchestration/provider-discovery/aider.js +49 -0
- package/scripts/lib/orchestration/provider-discovery/claude-code.js +56 -0
- package/scripts/lib/orchestration/provider-discovery/codex.js +49 -0
- package/scripts/lib/orchestration/provider-discovery/common.js +186 -0
- package/scripts/lib/orchestration/provider-discovery/gemini.js +106 -0
- package/scripts/lib/orchestration/provider-discovery/lm-studio.js +118 -0
- package/scripts/lib/orchestration/provider-discovery/models-dev.js +12 -0
- package/scripts/lib/orchestration/provider-discovery/ollama.js +100 -0
- package/scripts/lib/orchestration/provider-discovery/opencode.js +47 -0
- package/scripts/lib/orchestration/provider-discovery/openrouter.js +44 -0
- package/scripts/lib/orchestration/risk-classifier.js +130 -0
- package/scripts/lib/orchestration/routing-policy.js +486 -0
- package/scripts/lib/orchestration/settings.js +112 -0
- package/scripts/lib/orchestration/state.js +165 -0
- package/scripts/lib/orchestration/verification-manager.js +138 -0
- package/scripts/lib/output-profiles.js +146 -0
- package/scripts/lib/package-content-audit.js +368 -0
- package/scripts/lib/package-runtime.js +278 -0
- package/scripts/lib/plan-surface.js +53 -0
- package/scripts/lib/plans.js +2318 -0
- package/scripts/lib/policy-provider.js +27 -0
- package/scripts/lib/prelaunch-activation-readiness.js +409 -0
- package/scripts/lib/prelaunch-evidence-store.js +816 -0
- package/scripts/lib/prelaunch-intelligence.js +869 -0
- package/scripts/lib/pricing-experiment.js +118 -0
- package/scripts/lib/pro-moment-events.js +77 -0
- package/scripts/lib/pro-moment-state.js +227 -0
- package/scripts/lib/pro-moments.js +1216 -0
- package/scripts/lib/product-learning-events.js +629 -0
- package/scripts/lib/project-profile.js +555 -0
- package/scripts/lib/prompt-compiler.js +280 -0
- package/scripts/lib/prompt-lint.js +32 -0
- package/scripts/lib/prompt-suggestions.js +52 -0
- package/scripts/lib/proof-canonical.js +398 -0
- package/scripts/lib/proof-drilldown.js +383 -0
- package/scripts/lib/proof-events.js +342 -0
- package/scripts/lib/proof-history.js +243 -0
- package/scripts/lib/proof-metrics.js +296 -0
- package/scripts/lib/proof-outcome-evidence.js +134 -0
- package/scripts/lib/proof-receipt.js +335 -0
- package/scripts/lib/proof-record.js +461 -0
- package/scripts/lib/public-activation-distribution-gate.js +258 -0
- package/scripts/lib/public-cli.js +3891 -0
- package/scripts/lib/public-distribution-truth.js +211 -0
- package/scripts/lib/public-install-claim-checker.js +294 -0
- package/scripts/lib/publish-provenance-readiness.js +283 -0
- package/scripts/lib/readiness-delta.js +218 -0
- package/scripts/lib/readiness-evidence-closure.js +196 -0
- package/scripts/lib/reentry-memory-capture.js +241 -0
- package/scripts/lib/reentry-memory-retrieval.js +302 -0
- package/scripts/lib/reentry-memory-status.js +146 -0
- package/scripts/lib/reentry-memory-store.js +178 -0
- package/scripts/lib/reentry-state.js +66 -0
- package/scripts/lib/release-candidate-bundle.js +166 -0
- package/scripts/lib/remediation.js +81 -0
- package/scripts/lib/repo-map.js +391 -0
- package/scripts/lib/run-improvements-lifecycle.js +330 -0
- package/scripts/lib/run-improvements.js +789 -0
- package/scripts/lib/runtime-decision-policy.js +387 -0
- package/scripts/lib/safe-path-engine.js +705 -0
- package/scripts/lib/safe-run-controller.js +887 -0
- package/scripts/lib/score.js +262 -0
- package/scripts/lib/seamless-enforcement.js +329 -0
- package/scripts/lib/seamless-outcome.js +689 -0
- package/scripts/lib/seamless-reality-gate.js +5043 -0
- package/scripts/lib/security-risk-classifier.js +511 -0
- package/scripts/lib/security-scan.js +384 -0
- package/scripts/lib/session-context-optimizer.js +1211 -0
- package/scripts/lib/session-timing.js +315 -0
- package/scripts/lib/skill-hygiene.js +805 -0
- package/scripts/lib/skill-packs.js +161 -0
- package/scripts/lib/skills-operating-layer.js +580 -0
- package/scripts/lib/smart-work-routing.js +768 -0
- package/scripts/lib/source-catalog.js +700 -0
- package/scripts/lib/status-value-summary.js +32 -0
- package/scripts/lib/support-bundle.js +578 -0
- package/scripts/lib/task-continuation.js +440 -0
- package/scripts/lib/test-helpers.js +15 -0
- package/scripts/lib/tier.js +38 -0
- package/scripts/lib/token-context-quality-gate.js +370 -0
- package/scripts/lib/token-cost-capture.js +187 -0
- package/scripts/lib/token-cost-intelligence.js +358 -0
- package/scripts/lib/token-efficiency-evidence.js +213 -0
- package/scripts/lib/token-evidence.js +699 -0
- package/scripts/lib/tokenish.js +17 -0
- package/scripts/lib/tool-output-sandbox.js +304 -0
- package/scripts/lib/trust-audit.js +136 -0
- package/scripts/lib/unified-events.js +396 -0
- package/scripts/lib/upgrade-interruption-recovery.js +407 -0
- package/scripts/lib/usage-ledger.js +201 -0
- package/scripts/lib/value-ledger.js +130 -0
- package/scripts/lib/value-proof-calibration.js +531 -0
- package/scripts/lib/visual-qa.js +231 -0
- package/scripts/lib/voice-alpha.js +29 -0
- package/scripts/lib/work-aware-orchestration.js +976 -0
- package/scripts/lib/work-control-receipts.js +577 -0
- package/scripts/lib/work-ledger.js +1123 -0
- package/scripts/lib/work-panel-preview.js +352 -0
- package/scripts/lib/workflow-discipline.js +280 -0
- package/scripts/lib/workflow-signals.js +419 -0
- package/scripts/lib/workspace-map.js +281 -0
- package/scripts/lib/workspace-registry.js +1367 -0
- package/scripts/lib/workspace-resolver.js +480 -0
|
@@ -0,0 +1,887 @@
|
|
|
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
|
+
};
|