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,976 +0,0 @@
1
- "use strict";
2
-
3
- // ── Work-Aware Orchestration ──────────────────────────────────────────────────
4
- //
5
- // Contract: avorelo.workOrchestration.v1
6
- //
7
- // Deterministic work orchestration: classifies a task, splits it into stages,
8
- // selects cheapest capable safe worker per stage, selects focused context per
9
- // stage from workspace hygiene metadata, builds stage-aware handoff, and writes
10
- // evidence-backed value receipts.
11
- //
12
- // No network calls. No LLM calls. No script execution. Local only.
13
-
14
- const fs = require("fs");
15
- const path = require("path");
16
-
17
- const CONTRACT = "avorelo.workOrchestration.v1";
18
- const SCHEMA_VERSION = 1;
19
-
20
- const LATEST_PLAN_REL = ".claude/cco/orchestration/work-aware-orchestration/latest-plan.json";
21
- const STAGES_DIR_REL = ".claude/cco/orchestration/work-aware-orchestration/stages";
22
-
23
- // ── Task types ────────────────────────────────────────────────────────────────
24
-
25
- const TASK_TYPES = [
26
- "repo_inspection",
27
- "planning",
28
- "implementation",
29
- "refactor",
30
- "bug_fix",
31
- "test_or_verification",
32
- "security_sensitive",
33
- "deployment_release",
34
- "documentation",
35
- "handoff",
36
- "summarization",
37
- "unknown",
38
- ];
39
-
40
- const COMPLEXITY = ["low", "medium", "high"];
41
- const RISK_LEVELS = ["low", "medium", "high", "critical"];
42
- const CONTEXT_PRESSURE = ["low", "medium", "high"];
43
-
44
- // ── Worker roles ──────────────────────────────────────────────────────────────
45
-
46
- const WORKER_ROLES = [
47
- "local_or_cheap",
48
- "strong_model",
49
- "local_test_runner",
50
- "reviewed_tool",
51
- "human_approval",
52
- "none_available",
53
- ];
54
-
55
- // ── Reason codes ──────────────────────────────────────────────────────────────
56
-
57
- const WORKER_REASON_CODES = {
58
- WORKER_SUPPORTS_STAGE: "WORKER_SUPPORTS_STAGE",
59
- WORKER_LOW_COST_FOR_LOW_RISK: "WORKER_LOW_COST_FOR_LOW_RISK",
60
- STRONG_WORKER_RESERVED_FOR_CRITICAL_STAGE: "STRONG_WORKER_RESERVED_FOR_CRITICAL_STAGE",
61
- LOCAL_TEST_RUNNER_FOR_VERIFICATION: "LOCAL_TEST_RUNNER_FOR_VERIFICATION",
62
- WORKER_UNAVAILABLE: "WORKER_UNAVAILABLE",
63
- WORKER_RECENTLY_LIMITED: "WORKER_RECENTLY_LIMITED",
64
- WORKER_CONTEXT_TOO_SMALL: "WORKER_CONTEXT_TOO_SMALL",
65
- WORKER_TRUST_TOO_LOW: "WORKER_TRUST_TOO_LOW",
66
- WORKER_RISK_TOO_HIGH: "WORKER_RISK_TOO_HIGH",
67
- FALLBACK_ALLOWED: "FALLBACK_ALLOWED",
68
- FALLBACK_BLOCKED_QUALITY: "FALLBACK_BLOCKED_QUALITY",
69
- FALLBACK_BLOCKED_SAFETY: "FALLBACK_BLOCKED_SAFETY",
70
- };
71
-
72
- const CONTEXT_REASON_CODES = {
73
- UNKNOWN_ASSET_EXCLUDED: "UNKNOWN_ASSET_EXCLUDED",
74
- HIGH_CONTEXT_COST_EXCLUDED: "HIGH_CONTEXT_COST_EXCLUDED",
75
- HIGH_RISK_ASSET_EXCLUDED: "HIGH_RISK_ASSET_EXCLUDED",
76
- SKILL_BODY_EXCLUDED: "SKILL_BODY_EXCLUDED",
77
- SECRET_LIKE_EXCLUDED: "SECRET_LIKE_EXCLUDED",
78
- STAGE_BUDGET_EXCEEDED: "STAGE_BUDGET_EXCEEDED",
79
- WORKSPACE_HYGIENE_USED: "WORKSPACE_HYGIENE_USED",
80
- NO_HYGIENE_REPORT: "NO_HYGIENE_REPORT",
81
- INSPECT_MAP_FIRST: "INSPECT_MAP_FIRST",
82
- };
83
-
84
- // ── Stage budgets (tokens) ────────────────────────────────────────────────────
85
-
86
- const STAGE_TOKEN_BUDGETS = {
87
- inspect: 4000,
88
- plan: 8000,
89
- implement: 16000,
90
- verify: 4000,
91
- review: 8000,
92
- handoff: 4000,
93
- summarize: 4000,
94
- };
95
-
96
- const LOCAL_WORKER_TOKEN_CAP = 4000;
97
-
98
- // ── Keyword helpers ───────────────────────────────────────────────────────────
99
-
100
- function includesAny(text, patterns) {
101
- const t = String(text || "").toLowerCase();
102
- return patterns.some((p) => t.includes(p.toLowerCase()));
103
- }
104
-
105
- // ── Phase 4: Task Classification ─────────────────────────────────────────────
106
-
107
- const SECURITY_KEYWORDS = ["security", "auth", "authentication", "authorization", "secret", "secrets", "token", "tokens", "key", "credential", "credentials", "permission", "permissions", "policy", "policies", "oauth", "jwt", "password", "encrypt"];
108
- const DEPLOY_KEYWORDS = ["deploy", "deployment", "release", "ship", "ci/cd", "pipeline", "prod", "production", "infra", "terraform", "docker", "publish", "migrate"];
109
- const CUSTOMER_DATA_KEYWORDS = ["customer", "customer data", "pii", "personal data", "user data", "billing", "payment", "subscription"];
110
- const DESTRUCTIVE_KEYWORDS = ["delete", "remove", "drop", "truncate", "rm -rf", "destroy", "wipe", "rollback", "revert", "reset"];
111
- const REFACTOR_KEYWORDS = ["refactor", "rename", "cleanup", "reorganize", "restructure", "extract", "move", "split", "merge module"];
112
- const IMPLEMENTATION_KEYWORDS = ["implement", "build", "add", "create", "write", "develop", "feature", "functionality", "endpoint", "api", "component"];
113
- const INSPECT_KEYWORDS = ["inspect", "read", "scan", "review files", "look at", "examine", "explore", "understand", "find", "grep"];
114
- const DOCS_KEYWORDS = ["docs", "documentation", "readme", "guide", "summary", "summarize", "explain", "describe", "changelog"];
115
- const TEST_KEYWORDS = ["test", "tests", "spec", "coverage", "verify", "validation", "assert", "check"];
116
- const BUG_KEYWORDS = ["bug", "fix", "broken", "error", "issue", "crash", "regression", "debug", "patch"];
117
- const BROAD_KEYWORDS = ["all files", "entire codebase", "all skills", "every file", "broad", "full scan", "review all", "check all"];
118
-
119
- function classifyWorkTask(input) {
120
- const text = String(input || "");
121
-
122
- // Task type
123
- let taskType = "unknown";
124
- if (includesAny(text, SECURITY_KEYWORDS)) taskType = "security_sensitive";
125
- else if (includesAny(text, DEPLOY_KEYWORDS)) taskType = "deployment_release";
126
- else if (includesAny(text, REFACTOR_KEYWORDS)) taskType = "refactor";
127
- else if (includesAny(text, BUG_KEYWORDS)) taskType = "bug_fix";
128
- else if (includesAny(text, TEST_KEYWORDS)) taskType = "test_or_verification";
129
- else if (includesAny(text, DOCS_KEYWORDS)) taskType = "documentation";
130
- else if (includesAny(text, INSPECT_KEYWORDS) && !includesAny(text, IMPLEMENTATION_KEYWORDS)) taskType = "repo_inspection";
131
- else if (includesAny(text, IMPLEMENTATION_KEYWORDS)) taskType = "implementation";
132
- else if (text.trim()) taskType = "implementation";
133
-
134
- // Handoff/summarization overrides
135
- if (includesAny(text, ["handoff", "hand off", "hand-off", "next worker", "next session"])) taskType = "handoff";
136
- if (includesAny(text, ["summarize", "summarization", "summary"])) taskType = "summarization";
137
-
138
- // Risk level
139
- let riskLevel = "medium";
140
- if (includesAny(text, SECURITY_KEYWORDS) || includesAny(text, CUSTOMER_DATA_KEYWORDS)) riskLevel = "critical";
141
- else if (includesAny(text, DEPLOY_KEYWORDS) || includesAny(text, DESTRUCTIVE_KEYWORDS)) riskLevel = "high";
142
- else if (["refactor", "bug_fix", "implementation"].includes(taskType)) riskLevel = "medium";
143
- else if (["documentation", "repo_inspection", "summarization", "handoff", "test_or_verification"].includes(taskType)) riskLevel = "low";
144
-
145
- // Complexity
146
- let complexity = "medium";
147
- if (["security_sensitive", "deployment_release"].includes(taskType)) complexity = "high";
148
- else if (["refactor"].includes(taskType) && includesAny(text, ["multi-file", "architecture", "restructure", "all"])) complexity = "high";
149
- else if (["documentation", "repo_inspection", "summarization", "handoff"].includes(taskType)) complexity = "low";
150
- else if (text.length > 200) complexity = "high";
151
-
152
- // Context pressure
153
- let contextPressure = "medium";
154
- if (includesAny(text, BROAD_KEYWORDS)) contextPressure = "high";
155
- else if (["documentation", "summarization", "handoff", "repo_inspection"].includes(taskType)) contextPressure = "low";
156
- else if (["security_sensitive", "deployment_release"].includes(taskType)) contextPressure = "low";
157
-
158
- return {
159
- summary: text.slice(0, 120),
160
- taskType,
161
- riskLevel,
162
- complexity,
163
- contextPressure,
164
- redacted: true,
165
- };
166
- }
167
-
168
- // ── Phase 5: Stage Planner ────────────────────────────────────────────────────
169
-
170
- function getStageQualityRequirement(stageId, riskLevel) {
171
- if (stageId === "implement" && ["high", "critical"].includes(riskLevel)) return "high";
172
- if (stageId === "review") return "high";
173
- if (stageId === "verify") return "deterministic";
174
- if (stageId === "inspect" && riskLevel === "critical") return "medium";
175
- return "medium";
176
- }
177
-
178
- function getStageContextNeed(stageId) {
179
- return { inspect: "small", plan: "medium", implement: "large", verify: "small", review: "medium", handoff: "small", summarize: "small" }[stageId] || "medium";
180
- }
181
-
182
- function getStageObjective(stageId, taskType, riskLevel) {
183
- const objectives = {
184
- inspect: "Scan relevant files and workspace state to understand scope before acting.",
185
- plan: "Propose a safe, bounded implementation approach based on inspect findings.",
186
- implement: "Make scoped changes with tests, following the plan from inspect/plan stages.",
187
- verify: "Run focused tests, build checks, and proof gates to confirm correctness.",
188
- review: "Adversarially review changes for security, quality, and correctness.",
189
- handoff: "Summarize what was done, what not to redo, and the exact next action for the next worker.",
190
- summarize: "Produce a compact human-readable summary of the work done and evidence collected.",
191
- };
192
- return objectives[stageId] || `Execute ${stageId} stage.`;
193
- }
194
-
195
- function getVerificationNextStep(stageId, taskType) {
196
- if (stageId === "verify") return "Check test output and proof artifact for pass/fail.";
197
- if (stageId === "implement") return "Run `avorelo verify` and focused tests for the changed files.";
198
- if (stageId === "review") return "Confirm no security/quality issues remain before continuing.";
199
- if (stageId === "handoff") return "Next worker reads handoff receipt and continues from last safe state.";
200
- if (stageId === "inspect") return "Review inspect output before proceeding to plan/implement.";
201
- return "Check output before proceeding to next stage.";
202
- }
203
-
204
- function getRecommendedWorkerRole(stageId, riskLevel, complexity, taskType) {
205
- if (stageId === "verify") return "local_test_runner";
206
- if (stageId === "inspect") return "local_or_cheap";
207
- if (stageId === "handoff") return "local_or_cheap";
208
- if (stageId === "summarize") return "local_or_cheap";
209
- if (stageId === "review" && ["high", "critical"].includes(riskLevel)) return "reviewed_tool";
210
- if (stageId === "implement" && riskLevel === "critical") return "strong_model";
211
- if (stageId === "implement" && complexity === "high") return "strong_model";
212
- if (stageId === "plan" && ["high", "critical"].includes(riskLevel)) return "strong_model";
213
- return "local_or_cheap";
214
- }
215
-
216
- function getFallbackWorkerRole(recommendedRole, riskLevel) {
217
- if (recommendedRole === "strong_model") return "none_available";
218
- if (recommendedRole === "reviewed_tool" && ["high", "critical"].includes(riskLevel)) return "strong_model";
219
- if (recommendedRole === "local_test_runner") return "local_or_cheap";
220
- if (recommendedRole === "local_or_cheap") return "strong_model";
221
- return "none_available";
222
- }
223
-
224
- function buildStagePlan(cwd, taskText, options = {}) {
225
- const task = classifyWorkTask(taskText);
226
- const { taskType, riskLevel, complexity, contextPressure } = task;
227
-
228
- const stageIds = [];
229
-
230
- // Always start with inspect
231
- stageIds.push("inspect");
232
-
233
- // Add plan stage for complex or security-sensitive work
234
- if (["security_sensitive", "deployment_release"].includes(taskType) || complexity === "high") {
235
- stageIds.push("plan");
236
- }
237
-
238
- // Core work stage
239
- if (["documentation", "summarization"].includes(taskType)) {
240
- stageIds.push("summarize");
241
- } else if (taskType !== "repo_inspection" && taskType !== "handoff") {
242
- stageIds.push("implement");
243
- }
244
-
245
- // Review for security/deploy
246
- if (["security_sensitive", "deployment_release"].includes(taskType)) {
247
- stageIds.push("review");
248
- }
249
-
250
- // Always verify for non-trivial work
251
- if (!["documentation", "summarization", "repo_inspection", "handoff"].includes(taskType)) {
252
- stageIds.push("verify");
253
- }
254
-
255
- // Always end with handoff
256
- stageIds.push("handoff");
257
-
258
- const stages = stageIds.map((stageId) => {
259
- const recommendedWorker = getRecommendedWorkerRole(stageId, riskLevel, complexity, taskType);
260
- const fallbackWorker = getFallbackWorkerRole(recommendedWorker, riskLevel);
261
- const isCustomerVisible = stageId === "handoff" || stageId === "summarize";
262
- return {
263
- stageId,
264
- objective: getStageObjective(stageId, taskType, riskLevel),
265
- lifecycleStage: stageId,
266
- riskLevel: (stageId === "implement" && ["high", "critical"].includes(riskLevel)) ? riskLevel : (["inspect", "handoff", "summarize"].includes(stageId) ? "low" : riskLevel),
267
- contextNeed: getStageContextNeed(stageId),
268
- qualityRequirement: getStageQualityRequirement(stageId, riskLevel),
269
- recommendedWorker,
270
- fallbackWorker,
271
- workerSelection: null,
272
- contextSelection: null,
273
- continuation: {
274
- safeNextAction: getVerificationNextStep(stageId, taskType),
275
- verificationNextStep: stageId === "implement" ? "Run focused tests and `avorelo proof`." : null,
276
- handoffRequired: stageId === "handoff" || stageId === "implement",
277
- },
278
- proofExpected: ["implement", "verify", "review"].includes(stageId),
279
- customerVisible: isCustomerVisible,
280
- debugVisible: true,
281
- redacted: true,
282
- };
283
- });
284
-
285
- return stages;
286
- }
287
-
288
- // ── Phase 6: Worker Selection Policy ─────────────────────────────────────────
289
-
290
- function selectWorkerForStage(cwd, stage, inventory, options = {}) {
291
- const { stageId, riskLevel, recommendedWorker, fallbackWorker, contextNeed } = stage;
292
- const tools = Array.isArray(inventory?.tools) ? inventory.tools : [];
293
-
294
- const localCheapTools = tools.filter((t) =>
295
- ["local_or_cheap"].includes(t.workerRole) ||
296
- ["free_local", "local"].includes(t.costTier) ||
297
- ["local", "lm_studio", "ollama", "aider", "opencode"].includes(t.toolId)
298
- );
299
-
300
- const strongTools = tools.filter((t) =>
301
- t.qualityTier === "highest" || t.qualityTier === "high" ||
302
- t.costTier === "premium" || t.costTier === "high" ||
303
- ["claude_code", "gemini_cli"].includes(t.toolId)
304
- );
305
-
306
- const testRunners = tools.filter((t) =>
307
- t.toolId === "test_runner" || t.toolId === "git" ||
308
- (t.supportedRoles || []).includes("verify")
309
- );
310
-
311
- function isAvailable(tool) {
312
- return !["unavailable", "missing", "stale", "disabled_by_user"].includes(tool.workerState) &&
313
- tool.installStatus !== "not_installed" &&
314
- tool.workerState !== "needs_login" &&
315
- tool.workerState !== "recently_limited" &&
316
- tool.workerState !== "recently_failed";
317
- }
318
-
319
- function isSafeForStage(tool, stRisk) {
320
- if (["critical", "high"].includes(stRisk) && !tool.safeForHighRisk) {
321
- if (["free_local", "local"].includes(tool.costTier) && tool.trustTier !== "local") return false;
322
- }
323
- return true;
324
- }
325
-
326
- const reasonCodes = [];
327
- let selected = null;
328
- let role = null;
329
- let fallbackAllowed = false;
330
- let fallbackBlocked = null;
331
-
332
- // Verify stage: prefer local test runner
333
- if (stageId === "verify") {
334
- const runner = testRunners.find((t) => isAvailable(t));
335
- if (runner) {
336
- selected = runner.toolId;
337
- role = "local_test_runner";
338
- reasonCodes.push(WORKER_REASON_CODES.LOCAL_TEST_RUNNER_FOR_VERIFICATION);
339
- reasonCodes.push(WORKER_REASON_CODES.WORKER_SUPPORTS_STAGE);
340
- } else {
341
- const local = localCheapTools.find((t) => isAvailable(t));
342
- if (local) {
343
- selected = local.toolId;
344
- role = "local_or_cheap";
345
- reasonCodes.push(WORKER_REASON_CODES.WORKER_SUPPORTS_STAGE);
346
- reasonCodes.push(WORKER_REASON_CODES.FALLBACK_ALLOWED);
347
- } else {
348
- role = "none_available";
349
- reasonCodes.push(WORKER_REASON_CODES.WORKER_UNAVAILABLE);
350
- }
351
- }
352
- }
353
- // Inspect / handoff / summarize: prefer local/cheap
354
- else if (["inspect", "handoff", "summarize"].includes(stageId)) {
355
- const local = localCheapTools.find((t) => isAvailable(t) && isSafeForStage(t, riskLevel));
356
- if (local) {
357
- selected = local.toolId;
358
- role = "local_or_cheap";
359
- reasonCodes.push(WORKER_REASON_CODES.WORKER_LOW_COST_FOR_LOW_RISK);
360
- reasonCodes.push(WORKER_REASON_CODES.WORKER_SUPPORTS_STAGE);
361
- } else {
362
- const strong = strongTools.find((t) => isAvailable(t));
363
- if (strong) {
364
- selected = strong.toolId;
365
- role = "strong_model";
366
- reasonCodes.push(WORKER_REASON_CODES.FALLBACK_ALLOWED);
367
- reasonCodes.push(WORKER_REASON_CODES.WORKER_SUPPORTS_STAGE);
368
- fallbackAllowed = true;
369
- } else {
370
- role = "none_available";
371
- reasonCodes.push(WORKER_REASON_CODES.WORKER_UNAVAILABLE);
372
- }
373
- }
374
- }
375
- // Critical/high risk implement: must use strong model
376
- else if (["implement", "plan", "review"].includes(stageId) && ["critical", "high"].includes(riskLevel)) {
377
- const strong = strongTools.find((t) => isAvailable(t) && t.safeForHighRisk !== false);
378
- if (strong) {
379
- selected = strong.toolId;
380
- role = "strong_model";
381
- reasonCodes.push(WORKER_REASON_CODES.STRONG_WORKER_RESERVED_FOR_CRITICAL_STAGE);
382
- reasonCodes.push(WORKER_REASON_CODES.WORKER_SUPPORTS_STAGE);
383
- } else {
384
- const local = localCheapTools.find((t) => isAvailable(t) && t.trustTier === "local");
385
- if (local && local.trustTier === "local") {
386
- selected = local.toolId;
387
- role = "local_or_cheap";
388
- reasonCodes.push(WORKER_REASON_CODES.WORKER_SUPPORTS_STAGE);
389
- fallbackAllowed = true;
390
- reasonCodes.push(WORKER_REASON_CODES.FALLBACK_ALLOWED);
391
- } else {
392
- role = "none_available";
393
- reasonCodes.push(WORKER_REASON_CODES.WORKER_UNAVAILABLE);
394
- if (localCheapTools.length > 0) {
395
- fallbackBlocked = WORKER_REASON_CODES.FALLBACK_BLOCKED_SAFETY;
396
- reasonCodes.push(WORKER_REASON_CODES.FALLBACK_BLOCKED_SAFETY);
397
- }
398
- }
399
- }
400
- }
401
- // Medium risk implement: prefer strong but allow local if capable
402
- else {
403
- const strong = strongTools.find((t) => isAvailable(t));
404
- if (strong) {
405
- selected = strong.toolId;
406
- role = "strong_model";
407
- reasonCodes.push(WORKER_REASON_CODES.WORKER_SUPPORTS_STAGE);
408
- } else {
409
- const local = localCheapTools.find((t) => isAvailable(t));
410
- if (local) {
411
- selected = local.toolId;
412
- role = "local_or_cheap";
413
- reasonCodes.push(WORKER_REASON_CODES.WORKER_SUPPORTS_STAGE);
414
- reasonCodes.push(WORKER_REASON_CODES.FALLBACK_ALLOWED);
415
- fallbackAllowed = true;
416
- } else {
417
- role = "none_available";
418
- reasonCodes.push(WORKER_REASON_CODES.WORKER_UNAVAILABLE);
419
- }
420
- }
421
- }
422
-
423
- const toolMeta = tools.find((t) => t.toolId === selected);
424
-
425
- return {
426
- selected: selected || "none",
427
- role,
428
- costTier: toolMeta?.costTier || "unknown",
429
- qualityTier: toolMeta?.qualityTier || "unknown",
430
- trustLevel: toolMeta?.trustTier || "unknown",
431
- availability: toolMeta?.availability || "unknown",
432
- fallbackAllowed,
433
- fallbackBlocked,
434
- reasonCodes,
435
- };
436
- }
437
-
438
- // ── Phase 7: Workspace Relevance / Context Auto-Selection ─────────────────────
439
-
440
- function safeReadJson(absPath) {
441
- try {
442
- if (!fs.existsSync(absPath)) return null;
443
- return JSON.parse(fs.readFileSync(absPath, "utf8").replace(/^/, ""));
444
- } catch {
445
- return null;
446
- }
447
- }
448
-
449
- function selectContextForStage(cwd, stage, workspaceHygieneReport, options = {}) {
450
- const { stageId, contextNeed, riskLevel } = stage;
451
- const assets = workspaceHygieneReport?.allAssets || [];
452
- const reasonCodes = [];
453
-
454
- const selectedAssetIds = [];
455
- const selectedFiles = [];
456
- const excludedAssetIds = [];
457
-
458
- const budgetTokens = Math.min(
459
- STAGE_TOKEN_BUDGETS[stageId] || 4000,
460
- contextNeed === "small" ? LOCAL_WORKER_TOKEN_CAP : (STAGE_TOKEN_BUDGETS[stageId] || 8000)
461
- );
462
-
463
- let estimatedTokens = 0;
464
- let source = "none";
465
- let contextPackRef = null;
466
-
467
- if (assets.length > 0) {
468
- source = "ai_workspace_hygiene";
469
- reasonCodes.push(CONTEXT_REASON_CODES.WORKSPACE_HYGIENE_USED);
470
-
471
- for (const asset of assets) {
472
- const isUnknown = asset.reviewStatus === "unknown";
473
- const isHighRisk = asset.contextCost === "high" || asset.trustLevel === "low";
474
- const isSkillBody = asset.assetType === "skill" && asset.fullBodyRisk;
475
- const isSecretLike = (asset.findingCodes || []).includes("SECRET_LIKE_REFERENCE");
476
-
477
- if (isUnknown) {
478
- excludedAssetIds.push(asset.id || asset.name);
479
- continue;
480
- }
481
- if (isSecretLike) {
482
- excludedAssetIds.push(asset.id || asset.name);
483
- reasonCodes.push(CONTEXT_REASON_CODES.SECRET_LIKE_EXCLUDED);
484
- continue;
485
- }
486
- if (isHighRisk && stageId !== "review") {
487
- excludedAssetIds.push(asset.id || asset.name);
488
- reasonCodes.push(CONTEXT_REASON_CODES.HIGH_CONTEXT_COST_EXCLUDED);
489
- continue;
490
- }
491
- if (isSkillBody) {
492
- excludedAssetIds.push(asset.id || asset.name);
493
- reasonCodes.push(CONTEXT_REASON_CODES.SKILL_BODY_EXCLUDED);
494
- continue;
495
- }
496
-
497
- // Stage relevance filter
498
- const stageHints = asset.stageHints || [];
499
- if (stageHints.length > 0 && !stageHints.includes(stageId) && !stageHints.includes("all")) continue;
500
-
501
- const tokenEstimate = asset.estimatedTokens || 100;
502
- if (estimatedTokens + tokenEstimate > budgetTokens) {
503
- reasonCodes.push(CONTEXT_REASON_CODES.STAGE_BUDGET_EXCEEDED);
504
- continue;
505
- }
506
-
507
- estimatedTokens += tokenEstimate;
508
- if (asset.id) selectedAssetIds.push(asset.id);
509
- if (asset.filePath) selectedFiles.push(asset.filePath);
510
- }
511
-
512
- if (selectedAssetIds.length === 0 && stageId === "inspect") {
513
- reasonCodes.push(CONTEXT_REASON_CODES.INSPECT_MAP_FIRST);
514
- }
515
- } else {
516
- // No hygiene report — use manual fallback
517
- source = assets.length === 0 && !workspaceHygieneReport ? "none" : "manual_fallback";
518
- reasonCodes.push(CONTEXT_REASON_CODES.NO_HYGIENE_REPORT);
519
- if (stageId === "inspect") {
520
- reasonCodes.push(CONTEXT_REASON_CODES.INSPECT_MAP_FIRST);
521
- }
522
- }
523
-
524
- const packPath = `${STAGES_DIR_REL}/${stageId}-context-pack.json`;
525
- if (cwd) {
526
- contextPackRef = path.join(cwd, packPath).replace(/\\/g, "/");
527
- }
528
-
529
- const unknownAssetsExcluded = excludedAssetIds.length;
530
-
531
- return {
532
- source,
533
- selectedAssetIds,
534
- selectedFiles,
535
- excludedAssetIds,
536
- unknownAssetsExcluded,
537
- estimatedTokens,
538
- budgetTokens,
539
- contextPackRef,
540
- reasonCodes,
541
- };
542
- }
543
-
544
- // ── Phase 8: Stage Context Pack Writing ───────────────────────────────────────
545
-
546
- function writeStageContextPack(cwd, stageId, contextSelection, stage) {
547
- const dir = path.join(cwd, STAGES_DIR_REL);
548
- fs.mkdirSync(dir, { recursive: true });
549
-
550
- const pack = {
551
- stageId,
552
- source: contextSelection.source,
553
- selectedAssetIds: contextSelection.selectedAssetIds,
554
- selectedFiles: contextSelection.selectedFiles,
555
- estimatedTokens: contextSelection.estimatedTokens,
556
- budgetTokens: contextSelection.budgetTokens,
557
- contextPackRef: contextSelection.contextPackRef,
558
- reasonCodes: contextSelection.reasonCodes,
559
- constraints: {
560
- noSecrets: true,
561
- noRawPrompt: true,
562
- noRawThirdPartySkillBodies: true,
563
- noUnknownAssets: true,
564
- },
565
- redacted: true,
566
- };
567
-
568
- const packPath = path.join(dir, `${stageId}-context-pack.json`);
569
- fs.writeFileSync(packPath, JSON.stringify(pack, null, 2), "utf8");
570
- return packPath;
571
- }
572
-
573
- // ── Phase 9: Stage-Aware Handoff ─────────────────────────────────────────────
574
-
575
- function buildStageHandoff(cwd, orchestrationPlan, options = {}) {
576
- const stages = orchestrationPlan.stages || [];
577
- const handoffStage = stages.find((s) => s.stageId === "handoff");
578
- const lastImplementStage = [...stages].reverse().find((s) => ["implement", "review", "verify"].includes(s.stageId));
579
-
580
- const nextStage = handoffStage || stages[stages.length - 1];
581
- const nextWorkerRole = nextStage?.workerSelection?.role || handoffStage?.recommendedWorker || "strong_model";
582
-
583
- const doneStages = stages.filter((s) => s.stageId !== "handoff").map((s) => s.stageId);
584
-
585
- return {
586
- contract: "avorelo.stageHandoff.v1",
587
- whatWasDone: doneStages,
588
- doNotRedo: doneStages,
589
- currentBranch: null,
590
- relevantFiles: lastImplementStage?.contextSelection?.selectedFiles || [],
591
- contextPackRefs: stages
592
- .filter((s) => s.contextSelection?.contextPackRef)
593
- .map((s) => ({ stageId: s.stageId, path: s.contextSelection.contextPackRef })),
594
- riskConstraints: {
595
- riskLevel: orchestrationPlan.task?.riskLevel || "medium",
596
- noAutoTrustUnknownAssets: true,
597
- noDestructiveActionsWithoutGuard: true,
598
- },
599
- selectedNextStage: nextStage?.stageId || "handoff",
600
- selectedWorkerRole: nextWorkerRole,
601
- verificationNextStep: lastImplementStage?.continuation?.verificationNextStep || "Run `avorelo verify` and focused tests.",
602
- nextAction: orchestrationPlan.nextAction || "Continue with the next stage.",
603
- proofPaths: [LATEST_PLAN_REL],
604
- redacted: true,
605
- };
606
- }
607
-
608
- // ── Phase 10: Receipts / Value Evidence ───────────────────────────────────────
609
-
610
- function buildValueEvidence(plan) {
611
- const stages = plan.stages || [];
612
-
613
- const localOrCheapStages = stages.filter((s) => s.workerSelection?.role === "local_or_cheap").length;
614
- const strongWorkerStages = stages.filter((s) => s.workerSelection?.role === "strong_model").length;
615
- const verificationStages = stages.filter((s) => s.stageId === "verify").length;
616
- const handoffStages = stages.filter((s) => s.stageId === "handoff").length;
617
-
618
- const allContextSelections = stages.map((s) => s.contextSelection).filter(Boolean);
619
- const unknownAssetsExcluded = allContextSelections.reduce((sum, cs) => sum + (cs.unknownAssetsExcluded || 0), 0);
620
- const highContextAssetsExcluded = allContextSelections.filter((cs) => cs.reasonCodes?.includes(CONTEXT_REASON_CODES.HIGH_CONTEXT_COST_EXCLUDED)).length;
621
-
622
- const contextTokensFromReceipt = allContextSelections.reduce((sum, cs) => sum + (cs.estimatedTokens || 0), 0);
623
-
624
- return {
625
- localOrCheapStages,
626
- strongWorkerStages,
627
- verificationStages,
628
- handoffStages,
629
- premiumStagesReserved: strongWorkerStages > 0 ? `${strongWorkerStages} stage(s) reserved for strong model (evidence: critical/high risk or complexity)` : null,
630
- contextTokensConsumed: contextTokensFromReceipt,
631
- unknownAssetsExcluded,
632
- highContextAssetsExcluded,
633
- manualDecisionsAvoided: "automatic mode applied silently for low-risk stage decisions",
634
- repeatedWorkAvoided: null,
635
- verificationPrepared: verificationStages > 0,
636
- verificationCompleted: null,
637
- caveats: [
638
- "Stage plan and worker selection are evidence-based estimates, not guarantees.",
639
- "Actual savings depend on worker availability and task complexity at execution time.",
640
- "No exact dollar or token savings claimed — counts are from the stage plan only.",
641
- ],
642
- redacted: true,
643
- };
644
- }
645
-
646
- function writeWorkOrchestrationReceipt(cwd, plan) {
647
- const dir = path.dirname(path.join(cwd, LATEST_PLAN_REL));
648
- fs.mkdirSync(dir, { recursive: true });
649
-
650
- const latestPath = path.join(cwd, LATEST_PLAN_REL);
651
- fs.writeFileSync(latestPath, JSON.stringify(plan, null, 2), "utf8");
652
-
653
- return latestPath;
654
- }
655
-
656
- // ── Orchestration plan builder ────────────────────────────────────────────────
657
-
658
- function buildWorkOrchestrationPlan(cwd, taskText, options = {}) {
659
- const mode = options.mode || "automatic";
660
- const task = classifyWorkTask(taskText);
661
-
662
- // Load inventory if available
663
- let inventory = options.inventory || null;
664
- if (!inventory) {
665
- try {
666
- const { loadInventory } = require("./orchestration/inventory");
667
- inventory = loadInventory(cwd, { refreshLevel: "cache" });
668
- } catch {
669
- inventory = { tools: [] };
670
- }
671
- }
672
-
673
- // Load workspace hygiene if available
674
- let hygieneReport = options.hygieneReport || null;
675
- if (!hygieneReport) {
676
- try {
677
- const reportPath = path.join(cwd, ".claude/cco/orchestration/ai-workspace-hygiene/latest-report-debug.json");
678
- hygieneReport = safeReadJson(reportPath);
679
- } catch {
680
- hygieneReport = null;
681
- }
682
- }
683
-
684
- // Build stages
685
- const rawStages = buildStagePlan(cwd, taskText, options);
686
-
687
- // Enrich stages with worker and context selection
688
- const stages = rawStages.map((stage) => {
689
- const workerSelection = selectWorkerForStage(cwd, stage, inventory, options);
690
- const contextSelection = selectContextForStage(cwd, stage, hygieneReport, options);
691
-
692
- // Write stage context packs
693
- try {
694
- writeStageContextPack(cwd, stage.stageId, contextSelection, stage);
695
- } catch {
696
- // best-effort
697
- }
698
-
699
- return { ...stage, workerSelection, contextSelection };
700
- });
701
-
702
- const summary = {
703
- stageCount: stages.length,
704
- localOrCheapStages: stages.filter((s) => s.workerSelection?.role === "local_or_cheap").length,
705
- strongWorkerStages: stages.filter((s) => s.workerSelection?.role === "strong_model").length,
706
- verificationStages: stages.filter((s) => s.stageId === "verify").length,
707
- handoffStages: stages.filter((s) => s.stageId === "handoff").length,
708
- unknownAssetsExcluded: stages.reduce((sum, s) => sum + (s.contextSelection?.unknownAssetsExcluded || 0), 0),
709
- highContextAssetsExcluded: stages.filter((s) => s.contextSelection?.reasonCodes?.includes(CONTEXT_REASON_CODES.HIGH_CONTEXT_COST_EXCLUDED)).length,
710
- };
711
-
712
- const firstPendingStage = stages.find((s) => s.stageId !== "handoff") || stages[0];
713
- const nextAction = firstPendingStage
714
- ? `Continue with the '${firstPendingStage.stageId}' stage using a ${firstPendingStage.workerSelection?.role || "capable"} worker.`
715
- : "Review the orchestration plan and begin with the inspect stage.";
716
-
717
- const plan = {
718
- contract: CONTRACT,
719
- schemaVersion: SCHEMA_VERSION,
720
- createdAt: new Date().toISOString(),
721
- mode,
722
- task,
723
- stages,
724
- summary,
725
- valueEvidence: null,
726
- nextAction,
727
- receipts: [],
728
- redacted: true,
729
- };
730
-
731
- // Add value evidence
732
- plan.valueEvidence = buildValueEvidence(plan);
733
-
734
- // Build handoff
735
- plan.stageHandoff = buildStageHandoff(cwd, plan, options);
736
-
737
- return plan;
738
- }
739
-
740
- // ── Phase 11: CLI Surfaces ────────────────────────────────────────────────────
741
-
742
- function buildWorkOrchestrationSurface(cwd) {
743
- const latestPath = path.join(cwd, LATEST_PLAN_REL);
744
- const plan = safeReadJson(latestPath);
745
-
746
- if (!plan) {
747
- return {
748
- status: "not_run",
749
- latestPlanPath: null,
750
- stageCount: 0,
751
- localOrCheapStages: 0,
752
- strongWorkerStages: 0,
753
- unknownAssetsExcluded: 0,
754
- highContextAssetsExcluded: 0,
755
- nextAction: "Run `avorelo orchestrate <task>` to build a work plan.",
756
- };
757
- }
758
-
759
- return {
760
- status: "planned",
761
- latestPlanPath: LATEST_PLAN_REL,
762
- stageCount: plan.summary?.stageCount || 0,
763
- localOrCheapStages: plan.summary?.localOrCheapStages || 0,
764
- strongWorkerStages: plan.summary?.strongWorkerStages || 0,
765
- unknownAssetsExcluded: plan.summary?.unknownAssetsExcluded || 0,
766
- highContextAssetsExcluded: plan.summary?.highContextAssetsExcluded || 0,
767
- nextAction: plan.nextAction || null,
768
- };
769
- }
770
-
771
- function formatWorkOrchestrationText(plan, options = {}) {
772
- const isDebug = options.debug === true;
773
-
774
- if (!plan || !plan.stages) {
775
- return "No work orchestration plan available.";
776
- }
777
-
778
- const { task, stages, summary, valueEvidence, nextAction } = plan;
779
-
780
- const lines = [
781
- "Avorelo prepared the work plan.",
782
- "",
783
- "Done:",
784
- `- Split task into ${summary.stageCount} stage(s): ${stages.map((s) => s.stageId).join(", ")}.`,
785
- `- Prepared focused context for each stage.`,
786
- ];
787
-
788
- if (summary.strongWorkerStages > 0) {
789
- lines.push(`- Reserved strong worker for ${summary.strongWorkerStages} critical stage(s).`);
790
- }
791
-
792
- lines.push("", "Saved:");
793
- if (summary.localOrCheapStages > 0) {
794
- lines.push(`- Used local/cheap worker for ${summary.localOrCheapStages} low-risk stage(s).`);
795
- }
796
- if (summary.unknownAssetsExcluded > 0) {
797
- lines.push(`- Avoided broad workspace context (unknown assets excluded).`);
798
- }
799
-
800
- lines.push("", "Protected:");
801
- if (summary.unknownAssetsExcluded > 0) {
802
- lines.push(`- Excluded ${summary.unknownAssetsExcluded} unknown/high-risk workspace asset(s) from automatic context.`);
803
- }
804
- lines.push("- Kept destructive/deploy actions behind guard.");
805
-
806
- lines.push("", `Next:`);
807
- lines.push(`- ${nextAction}`);
808
-
809
- if (isDebug) {
810
- lines.push("", "--- Debug: Stage Plan ---");
811
- for (const stage of stages) {
812
- lines.push(`Stage: ${stage.stageId}`);
813
- lines.push(` Objective: ${stage.objective}`);
814
- lines.push(` Risk: ${stage.riskLevel} | Context: ${stage.contextNeed} | Quality: ${stage.qualityRequirement}`);
815
- lines.push(` Worker: ${stage.workerSelection?.selected || "none"} (role: ${stage.workerSelection?.role})`);
816
- lines.push(` Worker reason codes: ${(stage.workerSelection?.reasonCodes || []).join(", ")}`);
817
- lines.push(` Context source: ${stage.contextSelection?.source}`);
818
- lines.push(` Context assets: ${(stage.contextSelection?.selectedAssetIds || []).length} selected, ${(stage.contextSelection?.excludedAssetIds || []).length} excluded`);
819
- lines.push(` Context reason codes: ${(stage.contextSelection?.reasonCodes || []).join(", ")}`);
820
- lines.push(` Context tokens: ~${stage.contextSelection?.estimatedTokens || 0}`);
821
- lines.push("");
822
- }
823
- lines.push("--- Debug: Value Evidence ---");
824
- lines.push(` localOrCheapStages: ${valueEvidence?.localOrCheapStages}`);
825
- lines.push(` strongWorkerStages: ${valueEvidence?.strongWorkerStages}`);
826
- lines.push(` unknownAssetsExcluded: ${valueEvidence?.unknownAssetsExcluded}`);
827
- lines.push(` highContextAssetsExcluded: ${valueEvidence?.highContextAssetsExcluded}`);
828
- lines.push(` verificationPrepared: ${valueEvidence?.verificationPrepared}`);
829
- lines.push("");
830
- if (valueEvidence?.caveats) {
831
- lines.push("Caveats:");
832
- for (const c of valueEvidence.caveats) lines.push(` - ${c}`);
833
- }
834
- }
835
-
836
- return lines.join("\n");
837
- }
838
-
839
- // ── Product learning events ───────────────────────────────────────────────────
840
-
841
- function emitOrchestrationEvents(cwd, plan) {
842
- try {
843
- const { appendProductLearningEvent } = require("./product-learning-events");
844
- const { stages, summary, task } = plan;
845
-
846
- appendProductLearningEvent(cwd, {
847
- eventName: "work_orchestration_plan_generated",
848
- category: "work_orchestration",
849
- surface: "local",
850
- status: "observed",
851
- payload: {
852
- stageCount: summary.stageCount,
853
- localOrCheapStages: summary.localOrCheapStages,
854
- strongWorkerStages: summary.strongWorkerStages,
855
- verificationStages: summary.verificationStages,
856
- unknownAssetsExcluded: summary.unknownAssetsExcluded,
857
- taskType: task.taskType,
858
- riskLevel: task.riskLevel,
859
- complexity: task.complexity,
860
- },
861
- });
862
-
863
- for (const stage of stages) {
864
- if (stage.workerSelection?.role === "local_or_cheap") {
865
- appendProductLearningEvent(cwd, {
866
- eventName: "local_or_cheap_stage_used",
867
- category: "work_orchestration",
868
- surface: "local",
869
- status: "observed",
870
- payload: {
871
- stageId: stage.stageId,
872
- workerRole: stage.workerSelection.role,
873
- reasonCodes: stage.workerSelection.reasonCodes,
874
- },
875
- });
876
- }
877
- if (stage.workerSelection?.role === "strong_model") {
878
- appendProductLearningEvent(cwd, {
879
- eventName: "strong_worker_reserved",
880
- category: "work_orchestration",
881
- surface: "local",
882
- status: "observed",
883
- payload: {
884
- stageId: stage.stageId,
885
- workerRole: stage.workerSelection.role,
886
- reasonCodes: stage.workerSelection.reasonCodes,
887
- },
888
- });
889
- }
890
- if ((stage.contextSelection?.unknownAssetsExcluded || 0) > 0) {
891
- appendProductLearningEvent(cwd, {
892
- eventName: "unknown_workspace_asset_excluded",
893
- category: "work_orchestration",
894
- surface: "local",
895
- status: "observed",
896
- payload: {
897
- stageId: stage.stageId,
898
- count: stage.contextSelection.unknownAssetsExcluded,
899
- },
900
- });
901
- }
902
- }
903
-
904
- if (summary.unknownAssetsExcluded > 0) {
905
- appendProductLearningEvent(cwd, {
906
- eventName: "workspace_relevance_used",
907
- category: "work_orchestration",
908
- surface: "local",
909
- status: "observed",
910
- payload: {
911
- unknownAssetsExcluded: summary.unknownAssetsExcluded,
912
- highContextAssetsExcluded: summary.highContextAssetsExcluded,
913
- },
914
- });
915
- }
916
-
917
- appendProductLearningEvent(cwd, {
918
- eventName: "stage_handoff_prepared",
919
- category: "work_orchestration",
920
- surface: "local",
921
- status: "observed",
922
- payload: {
923
- handoffStages: summary.handoffStages,
924
- stageCount: summary.stageCount,
925
- },
926
- });
927
-
928
- appendProductLearningEvent(cwd, {
929
- eventName: "orchestration_value_evidence_written",
930
- category: "work_orchestration",
931
- surface: "local",
932
- status: "observed",
933
- payload: {
934
- localOrCheapStages: summary.localOrCheapStages,
935
- strongWorkerStages: summary.strongWorkerStages,
936
- unknownAssetsExcluded: summary.unknownAssetsExcluded,
937
- },
938
- });
939
- } catch {
940
- // product learning is best-effort
941
- }
942
- }
943
-
944
- // ── Main entrypoint ───────────────────────────────────────────────────────────
945
-
946
- function runWorkOrchestration(cwd, taskText, options = {}) {
947
- const plan = buildWorkOrchestrationPlan(cwd, taskText, options);
948
-
949
- const receiptPath = writeWorkOrchestrationReceipt(cwd, plan);
950
- plan.receipts = [receiptPath];
951
-
952
- emitOrchestrationEvents(cwd, plan);
953
-
954
- return plan;
955
- }
956
-
957
- module.exports = {
958
- CONTRACT,
959
- SCHEMA_VERSION,
960
- LATEST_PLAN_REL,
961
- TASK_TYPES,
962
- WORKER_ROLES,
963
- WORKER_REASON_CODES,
964
- CONTEXT_REASON_CODES,
965
- classifyWorkTask,
966
- buildStagePlan,
967
- selectWorkerForStage,
968
- selectContextForStage,
969
- buildStageHandoff,
970
- writeWorkOrchestrationReceipt,
971
- buildWorkOrchestrationSurface,
972
- formatWorkOrchestrationText,
973
- buildWorkOrchestrationPlan,
974
- buildValueEvidence,
975
- runWorkOrchestration,
976
- };