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,1648 +0,0 @@
1
- "use strict";
2
-
3
- const fs = require("fs");
4
- const path = require("path");
5
- const crypto = require("crypto");
6
-
7
- const {
8
- buildValueProofs,
9
- confidenceLabel,
10
- } = require("./value-proof-calibration");
11
-
12
- const {
13
- getLocalPricingSource,
14
- getLocalPricingEntry,
15
- } = require("./local-pricing");
16
-
17
- const {
18
- buildTokenEvidence,
19
- writeTokenEvidence,
20
- } = require("./token-evidence");
21
-
22
- const {
23
- buildCostEvidenceV1,
24
- } = require("./cost-evidence");
25
-
26
- // ── Constants ─────────────────────────────────────────────────────────────────
27
-
28
- const OPERATING_VALUE_CONTRACT = "avorelo.operatingValue.v1";
29
- const OPERATING_VALUE_SCHEMA_VERSION = 1;
30
- const OPERATING_VALUE_DIR_REL = ".claude/cco/orchestration/operating-value";
31
- const OPERATING_VALUE_LATEST_REL = `${OPERATING_VALUE_DIR_REL}/latest-value.json`;
32
- const OPERATING_VALUE_SUMMARY_REL = `${OPERATING_VALUE_DIR_REL}/latest-summary.md`;
33
- const OPERATING_VALUE_HISTORY_DIR_REL = `${OPERATING_VALUE_DIR_REL}/history`;
34
- const OPERATING_VALUE_EVENTS_REL = ".claude/cco/events/operating-value.jsonl";
35
- const OPERATING_VALUE_DASHBOARD_PREVIEW_REL = `${OPERATING_VALUE_DIR_REL}/dashboard-preview.md`;
36
-
37
- // Receipt source paths
38
- const WORK_CONTROL_REL = ".claude/cco/orchestration/work-control/latest-receipt.json";
39
- const SESSION_CONTEXT_REL = ".claude/cco/orchestration/session-context/latest-context.json";
40
- const BRAIN_PACK_REL = ".claude/cco/context/brain-pack/latest.json";
41
- const WORKSPACE_REGISTRY_REL = ".claude/cco/orchestration/workspace-registry/latest-registry.json";
42
- const INSTALL_INTAKE_REL = ".claude/cco/security/install-intake/latest-receipt.json";
43
- const SAFE_PATH_REL = ".claude/cco/security/safe-path/latest-receipt.json";
44
- const PROOF_REL = ".claude/cco/orchestration/current-proof.json";
45
-
46
- // Staleness thresholds (ms)
47
- const STALE_SHORT_MS = 2 * 60 * 60 * 1000; // 2 hours
48
- const STALE_LONG_MS = 24 * 60 * 60 * 1000; // 24 hours
49
-
50
- // Token estimation constants
51
- const AVG_CHARS_PER_TOKEN = 4;
52
- const AVG_ASSET_SUMMARY_CHARS = 150;
53
- const RAW_TOKEN_CAP = 50000;
54
- const MINUTES_PER_MANUAL_STEP_LOW = 1;
55
- const MINUTES_PER_MANUAL_STEP_HIGH = 3;
56
- const MINUTES_CAP = 30;
57
-
58
- // ── File helpers ──────────────────────────────────────────────────────────────
59
-
60
- function ensureDir(p) {
61
- fs.mkdirSync(p, { recursive: true });
62
- }
63
-
64
- function nowIso() {
65
- return new Date().toISOString();
66
- }
67
-
68
- function safeReadJson(filePath) {
69
- try {
70
- if (!fs.existsSync(filePath)) return null;
71
- const raw = fs.readFileSync(filePath, "utf8").replace(/^/, "");
72
- return JSON.parse(raw);
73
- } catch {
74
- return null;
75
- }
76
- }
77
-
78
- function fileAgeMs(filePath) {
79
- try {
80
- const stat = fs.statSync(filePath);
81
- return Date.now() - stat.mtimeMs;
82
- } catch {
83
- return Infinity;
84
- }
85
- }
86
-
87
- function fileCharLen(filePath) {
88
- try {
89
- return fs.statSync(filePath).size;
90
- } catch {
91
- return 0;
92
- }
93
- }
94
-
95
- function shortId() {
96
- return crypto.randomBytes(4).toString("hex");
97
- }
98
-
99
- // ── Receipt readers ───────────────────────────────────────────────────────────
100
-
101
- function readReceipts(cwd) {
102
- const read = (rel) => {
103
- const abs = path.join(cwd, rel);
104
- const data = safeReadJson(abs);
105
- const ageMs = fileAgeMs(abs);
106
- const charLen = fileCharLen(abs);
107
- return { data, ageMs, present: data !== null, charLen, path: rel };
108
- };
109
- return {
110
- workControl: read(WORK_CONTROL_REL),
111
- sessionContext: read(SESSION_CONTEXT_REL),
112
- brainPack: read(BRAIN_PACK_REL),
113
- workspaceRegistry: read(WORKSPACE_REGISTRY_REL),
114
- installIntake: read(INSTALL_INTAKE_REL),
115
- safePath: read(SAFE_PATH_REL),
116
- proof: read(PROOF_REL),
117
- };
118
- }
119
-
120
- // ── Staleness checks ──────────────────────────────────────────────────────────
121
-
122
- function isStale(ageMs, thresholdMs) {
123
- return ageMs > thresholdMs;
124
- }
125
-
126
- function ageLabel(ageMs) {
127
- if (ageMs === Infinity) return "missing";
128
- const hours = Math.round(ageMs / 1000 / 60 / 60);
129
- if (hours < 1) return "< 1h ago";
130
- if (hours < 24) return `${hours}h ago`;
131
- return `${Math.round(hours / 24)}d ago`;
132
- }
133
-
134
- // ── Token estimation ──────────────────────────────────────────────────────────
135
-
136
- function estimateCharsToTokens(chars) {
137
- return Math.round(chars / AVG_CHARS_PER_TOKEN);
138
- }
139
-
140
- function estimateRawContextTokens(receipts) {
141
- let totalChars = 0;
142
- const sources = [];
143
-
144
- // Registry: totalAssets × avg chars
145
- const reg = receipts.workspaceRegistry.data;
146
- if (reg && reg.summary && reg.summary.totalAssets) {
147
- const regChars = reg.summary.totalAssets * AVG_ASSET_SUMMARY_CHARS;
148
- totalChars += regChars;
149
- sources.push(`registry (${reg.summary.totalAssets} assets × ~${AVG_ASSET_SUMMARY_CHARS} chars)`);
150
- }
151
-
152
- // Work-control receipt file size
153
- if (receipts.workControl.present && receipts.workControl.charLen > 0) {
154
- totalChars += receipts.workControl.charLen;
155
- sources.push(`work-control receipt (~${receipts.workControl.charLen} chars)`);
156
- }
157
-
158
- // Brain-pack file size
159
- if (receipts.brainPack.present && receipts.brainPack.charLen > 0) {
160
- totalChars += receipts.brainPack.charLen;
161
- sources.push(`brain-pack (~${receipts.brainPack.charLen} chars)`);
162
- }
163
-
164
- // Session context source sections if available
165
- const sc = receipts.sessionContext.data;
166
- if (sc && sc.tokenDiscipline && sc.tokenDiscipline.estimatedTokens) {
167
- // This is already the compact form — we're building raw estimate, so DON'T add compact here
168
- }
169
-
170
- if (totalChars === 0) return { tokens: null, sources: [], confidence: "unavailable" };
171
-
172
- const rawTokens = Math.min(estimateCharsToTokens(totalChars), RAW_TOKEN_CAP);
173
- return { tokens: rawTokens, sources, confidence: "estimated" };
174
- }
175
-
176
- function estimateCompactHandoffTokens(receipts) {
177
- const sc = receipts.sessionContext.data;
178
- if (sc && sc.tokenDiscipline && sc.tokenDiscipline.estimatedTokens) {
179
- return { tokens: sc.tokenDiscipline.estimatedTokens, basis: "session-context.estimatedTokens", confidence: "measured" };
180
- }
181
- // Fallback: markdown handoff file size
182
- const abs = path.join(
183
- path.dirname(
184
- path.join(process.cwd(), receipts.sessionContext.path || SESSION_CONTEXT_REL)
185
- ),
186
- "latest-context.md"
187
- );
188
- const mdPath = abs.replace(/latest-context\.json$/, "latest-context.md");
189
- const mdCharLen = fileCharLen(mdPath);
190
- if (mdCharLen > 0) {
191
- return { tokens: estimateCharsToTokens(mdCharLen), basis: "session-context.md file size", confidence: "estimated" };
192
- }
193
- return { tokens: null, basis: "unavailable", confidence: "unavailable" };
194
- }
195
-
196
- // ── Manual steps count ────────────────────────────────────────────────────────
197
-
198
- function countManualStepsAvoided(receipts, capabilityRec) {
199
- let count = 0;
200
- const details = [];
201
-
202
- if (capabilityRec && capabilityRec.recommendedPack) {
203
- count++;
204
- details.push("capability auto-recommended");
205
- }
206
-
207
- const wc = receipts.workControl.data;
208
- if (wc && wc.workControl && wc.workControl.nextSafestAction) {
209
- count++;
210
- details.push("next command generated");
211
- }
212
-
213
- const sc = receipts.sessionContext.data;
214
- if (sc && sc.sessionStart && (sc.sessionStart.relevantFiles || []).length > 0) {
215
- count++;
216
- details.push("relevant files selected");
217
- }
218
-
219
- if (receipts.workspaceRegistry.present) {
220
- count++;
221
- details.push("registry already available");
222
- }
223
-
224
- if (receipts.workControl.present) {
225
- count++;
226
- details.push("work-control available");
227
- }
228
-
229
- if (receipts.sessionContext.present) {
230
- count++;
231
- details.push("session-context available");
232
- }
233
-
234
- if (receipts.brainPack.present) {
235
- count++;
236
- details.push("brain-pack available");
237
- }
238
-
239
- if (receipts.proof.present) {
240
- count++;
241
- details.push("proof available");
242
- }
243
-
244
- return { count, details };
245
- }
246
-
247
- // ── Value Card builders ───────────────────────────────────────────────────────
248
-
249
- function buildTimeSavedCard(receipts, capabilityRec) {
250
- const steps = countManualStepsAvoided(receipts, capabilityRec);
251
- const sc = receipts.sessionContext.data;
252
- const reg = receipts.workspaceRegistry.data;
253
-
254
- const rediscoveryAvoided = sc && sc.tokenDiscipline && sc.tokenDiscipline.avoidedBroadRediscovery === true;
255
- const relevantFiles = sc && sc.sessionStart ? (sc.sessionStart.relevantFiles || []).length : 0;
256
- const totalAssets = reg && reg.summary ? reg.summary.totalAssets : null;
257
-
258
- const lowEstimate = steps.count * MINUTES_PER_MANUAL_STEP_LOW;
259
- const highEstimate = Math.min(steps.count * MINUTES_PER_MANUAL_STEP_HIGH, MINUTES_CAP);
260
-
261
- const hasValue = steps.count > 0;
262
- const timeSavedMinuteRange = hasValue ? `${lowEstimate}–${highEstimate}` : "0";
263
-
264
- return {
265
- id: "timeSaved",
266
- label: "Time Saved",
267
- status: hasValue ? "available" : "partial",
268
- headline: hasValue
269
- ? `Estimated ${timeSavedMinuteRange} minutes saved`
270
- : "Limited time savings measured",
271
- plainEnglishValue: hasValue
272
- ? `Avorelo prepared ${steps.count} manual steps automatically (${steps.details.join(", ")}).${rediscoveryAvoided ? " Broad repo rediscovery avoided." : ""}`
273
- : "Some Avorelo surfaces were not available to measure time savings.",
274
- primaryMetric: `${steps.count} manual steps avoided`,
275
- secondaryMetric: relevantFiles && totalAssets
276
- ? `${relevantFiles} relevant files pre-selected from ${totalAssets} total assets`
277
- : rediscoveryAvoided ? "Broad repo scan avoided" : null,
278
- evidence: ["work-control", "session-context", "workspace-registry", "capability-recommender"].filter(
279
- (s) => (s === "work-control" && receipts.workControl.present) ||
280
- (s === "session-context" && receipts.sessionContext.present) ||
281
- (s === "workspace-registry" && receipts.workspaceRegistry.present) ||
282
- (s === "capability-recommender" && capabilityRec && capabilityRec.recommendedPack)
283
- ),
284
- confidence: steps.count >= 5 ? "medium" : "low",
285
- estimateBasis: "heuristic: manual steps avoided × 1–3 minutes",
286
- nextAction: sc && sc.sessionStart && sc.sessionStart.nextSafestAction
287
- ? sc.sessionStart.nextSafestAction
288
- : "Run `avorelo session-context --handoff --target claude` to prepare compact handoff.",
289
- userFacingSentence: hasValue
290
- ? `Avorelo saved an estimated ${timeSavedMinuteRange} minutes by handling ${steps.count} steps automatically.`
291
- : "Run the core Avorelo surfaces to measure time savings.",
292
- };
293
- }
294
-
295
- function buildCostOrTokensSavedCard(receipts, costEvidence) {
296
- const rawEst = estimateRawContextTokens(receipts);
297
- const compactEst = estimateCompactHandoffTokens(receipts);
298
- const hasCostEstimate = costEvidence && costEvidence.costAvoidedEstimate !== null && costEvidence.dashboardAllowed;
299
-
300
- const rawTokens = rawEst.tokens;
301
- const compactTokens = compactEst.tokens;
302
-
303
- let tokenReduction = null;
304
- let compressionRatio = null;
305
- let hasValue = false;
306
-
307
- if (rawTokens !== null && compactTokens !== null && rawTokens > 0) {
308
- tokenReduction = Math.max(0, rawTokens - compactTokens);
309
- compressionRatio = Math.round((compactTokens / rawTokens) * 100) / 100;
310
- hasValue = tokenReduction > 0;
311
- }
312
-
313
- const reg = receipts.workspaceRegistry.data;
314
- const totalAssets = reg && reg.summary ? reg.summary.totalAssets : null;
315
- const sc = receipts.sessionContext.data;
316
- const relevantFiles = sc && sc.sessionStart ? (sc.sessionStart.relevantFiles || []).length : 0;
317
-
318
- return {
319
- id: "costOrTokensSaved",
320
- label: "Context / Tokens Saved",
321
- status: hasValue ? "available" : compactTokens !== null ? "partial" : "unavailable",
322
- headline: hasValue
323
- ? `~${tokenReduction.toLocaleString()} tokens not loaded into context`
324
- : compactTokens !== null
325
- ? `Compact handoff: ~${compactTokens.toLocaleString()} tokens`
326
- : "Token savings not yet measurable",
327
- plainEnglishValue: hasValue
328
- ? `Avorelo prepared a ~${compactTokens.toLocaleString()}-token compact handoff instead of loading ~${rawTokens.toLocaleString()} candidate context tokens.`
329
- : compactTokens !== null
330
- ? `Compact handoff prepared (~${compactTokens.toLocaleString()} tokens). Run workspace-registry to enable before/after comparison.`
331
- : "Run `avorelo session-context` and `avorelo workspace-registry` to enable context reduction measurement.",
332
- primaryMetric: rawTokens && compactTokens
333
- ? `~${rawTokens.toLocaleString()} raw candidate tokens → ~${compactTokens.toLocaleString()} compact tokens`
334
- : compactTokens
335
- ? `Compact handoff: ~${compactTokens.toLocaleString()} tokens`
336
- : "unavailable",
337
- secondaryMetric: relevantFiles && totalAssets
338
- ? `${relevantFiles} of ${totalAssets} assets in compact context`
339
- : null,
340
- evidence: [
341
- rawEst.tokens !== null ? "workspace-registry" : null,
342
- compactEst.tokens !== null ? "session-context" : null,
343
- ].filter(Boolean),
344
- confidence: compactEst.confidence === "measured" && rawEst.confidence === "estimated" ? "medium" : "low",
345
- estimateBasis: [
346
- rawEst.sources.length ? `raw estimate from: ${rawEst.sources.join("; ")}` : null,
347
- `compact from: ${compactEst.basis}`,
348
- ].filter(Boolean).join(". "),
349
- costAvoidedEstimate: hasCostEstimate ? costEvidence.costAvoidedEstimate : null,
350
- costNote: hasCostEstimate
351
- ? `Estimated cost impact: ~$${costEvidence.costAvoidedEstimate.toFixed(4)} (${costEvidence.confidence} confidence, local pricing)`
352
- : "Cost estimate requires a local token pricing source. Token reduction shown instead.",
353
- nextAction: receipts.sessionContext.present
354
- ? "Review compact handoff at session-context --handoff --target claude"
355
- : "Run `avorelo session-context --handoff --target claude` to generate compact handoff.",
356
- userFacingSentence: hasValue
357
- ? `Avorelo reduced estimated context from ~${rawTokens.toLocaleString()} to ~${compactTokens.toLocaleString()} tokens (~${tokenReduction.toLocaleString()} tokens avoided).`
358
- : "Run core surfaces to measure context/token reduction.",
359
- };
360
- }
361
-
362
- function buildSecurityRiskAvoidedCard(receipts) {
363
- const intake = receipts.installIntake.data;
364
- const safePath = receipts.safePath.data;
365
- const reg = receipts.workspaceRegistry.data;
366
-
367
- const highRiskItems = intake && intake.summary ? intake.summary.highRiskItems || 0 : 0;
368
- const criticalRiskItems = intake && intake.summary ? intake.summary.criticalRiskItems || 0 : 0;
369
- const totalRiskyItems = highRiskItems + criticalRiskItems;
370
- const unknownItems = intake && intake.summary ? intake.summary.unknownItems || 0 : 0;
371
-
372
- const highRiskAssets = reg && reg.summary ? reg.summary.highRiskAssets || 0 : 0;
373
-
374
- const safePathDecision = safePath && safePath.safePathDecision ? safePath.safePathDecision : null;
375
- const risksBlocked = safePathDecision === "block" ? 1 : 0;
376
- const risksRouted = (safePathDecision === "approval_required" || safePathDecision === "recommend_reduced_scope" || safePathDecision === "warn_with_boundary") ? 1 : 0;
377
- const risksAvoided = risksBlocked + risksRouted;
378
-
379
- const hasValue = totalRiskyItems > 0 || highRiskAssets > 0 || risksAvoided > 0;
380
- const intakePresent = receipts.installIntake.present;
381
- const safePathPresent = receipts.safePath.present;
382
-
383
- return {
384
- id: "securityRiskAvoided",
385
- label: "Security Risk Avoided",
386
- status: intakePresent ? "available" : "partial",
387
- headline: totalRiskyItems > 0
388
- ? `${totalRiskyItems} risky item${totalRiskyItems !== 1 ? "s" : ""} surfaced before execution`
389
- : intakePresent
390
- ? "No high-risk items detected"
391
- : "Security scan not yet run",
392
- plainEnglishValue: intakePresent
393
- ? `Avorelo scanned ${(intake.summary.totalItems || 0).toLocaleString()} intake items. ${totalRiskyItems} high/critical-risk item${totalRiskyItems !== 1 ? "s" : ""} flagged before execution.${risksBlocked ? ` ${risksBlocked} blocked.` : ""}${risksRouted ? ` ${risksRouted} routed via Safe Path.` : ""}${unknownItems > 0 ? ` ${unknownItems} unknown items need review.` : ""}`
394
- : "Run `avorelo intake` to scan for risky packages, scripts, and MCP surfaces.",
395
- primaryMetric: intakePresent
396
- ? `${totalRiskyItems} high/critical-risk items` + (risksAvoided > 0 ? `, ${risksAvoided} routed/blocked` : "")
397
- : "unavailable",
398
- secondaryMetric: highRiskAssets > 0
399
- ? `${highRiskAssets} high-risk workspace assets flagged`
400
- : safePathDecision && safePathDecision !== "allow_as_is"
401
- ? `Safe Path decision: ${safePathDecision.replace(/_/g, " ")}`
402
- : null,
403
- evidence: [
404
- intakePresent ? "install-intake" : null,
405
- safePathPresent ? "safe-path" : null,
406
- reg ? "workspace-registry" : null,
407
- ].filter(Boolean),
408
- confidence: intakePresent ? "high" : "unavailable",
409
- risksBlocked,
410
- risksRouted,
411
- nextAction: totalRiskyItems > 0
412
- ? "Review risky items: run `avorelo intake --json` then use Safe Path for deploy/network scripts."
413
- : intakePresent
414
- ? "Intake scan clean. No action needed."
415
- : "Run `avorelo intake` to scan local intake surfaces.",
416
- userFacingSentence: intakePresent
417
- ? totalRiskyItems > 0
418
- ? `Avorelo surfaced ${totalRiskyItems} risky item${totalRiskyItems !== 1 ? "s" : ""} before execution.${risksBlocked ? ` ${risksBlocked} blocked.` : ""}`
419
- : "Avorelo scanned all intake surfaces — no high-risk items detected."
420
- : "Run `avorelo intake` to enable security risk measurement.",
421
- };
422
- }
423
-
424
- function buildClarityCard(receipts) {
425
- const wc = receipts.workControl.data;
426
- const sc = receipts.sessionContext.data;
427
-
428
- const nextActionPresent = Boolean(
429
- (wc && wc.workControl && wc.workControl.nextSafestAction) ||
430
- (sc && sc.sessionStart && sc.sessionStart.nextSafestAction)
431
- );
432
- const doNotRepeatCount = wc && wc.workControl && Array.isArray(wc.workControl.doNotRepeat)
433
- ? wc.workControl.doNotRepeat.length : 0;
434
- const relevantCommandsCount = sc && sc.sessionStart && Array.isArray(sc.sessionStart.relevantCommands)
435
- ? sc.sessionStart.relevantCommands.length : 0;
436
- const targetHandoffPrepared = Boolean(sc && sc.sessionStart && sc.sessionStart.compactPrompt);
437
- const proofAvailable = receipts.proof.present;
438
-
439
- const clarityScore = [nextActionPresent, doNotRepeatCount > 0, relevantCommandsCount > 0, targetHandoffPrepared, proofAvailable]
440
- .filter(Boolean).length;
441
-
442
- return {
443
- id: "clarity",
444
- label: "Clarity",
445
- status: clarityScore >= 3 ? "available" : clarityScore >= 1 ? "partial" : "unavailable",
446
- headline: nextActionPresent ? "Next action prepared" : "Clarity surface incomplete",
447
- plainEnglishValue: nextActionPresent
448
- ? `The next model session gets clear guidance: ${doNotRepeatCount > 0 ? `${doNotRepeatCount} do-not-repeat items, ` : ""}${relevantCommandsCount > 0 ? `${relevantCommandsCount} relevant commands, ` : ""}${targetHandoffPrepared ? "compact handoff, " : ""}${proofAvailable ? "proof evidence." : "no proof yet."}`
449
- : "Run work-control and session-context to build the clarity surface.",
450
- primaryMetric: nextActionPresent ? "Next action: available" : "Next action: missing",
451
- secondaryMetric: `do-not-repeat: ${doNotRepeatCount}, commands: ${relevantCommandsCount}`,
452
- evidence: [
453
- wc ? "work-control" : null,
454
- sc ? "session-context" : null,
455
- proofAvailable ? "proof" : null,
456
- ].filter(Boolean),
457
- confidence: clarityScore >= 3 ? "medium" : "low",
458
- nextActionPresent,
459
- doNotRepeatCount,
460
- relevantCommandsCount,
461
- targetHandoffPrepared,
462
- proofAvailable,
463
- nextAction: !nextActionPresent
464
- ? "Run `avorelo work-control --json` to generate next safest action guidance."
465
- : null,
466
- userFacingSentence: nextActionPresent
467
- ? `Avorelo prepared clear next-step guidance with ${doNotRepeatCount} anti-patterns and ${relevantCommandsCount} relevant commands.`
468
- : "Run core surfaces to build clarity for the next model session.",
469
- };
470
- }
471
-
472
- function buildSeamlessnessCard(receipts, capabilityRec) {
473
- const capabilityAutoRecommended = Boolean(capabilityRec && capabilityRec.recommendedPack);
474
- const userDidNotChooseCapability = capabilityAutoRecommended;
475
- const sc = receipts.sessionContext.data;
476
- const jsonDumpAvoided = sc && sc.tokenDiscipline ? sc.tokenDiscipline.avoidedJsonDump === true : false;
477
-
478
- const autoHandledCount = [
479
- receipts.workControl.present,
480
- receipts.sessionContext.present,
481
- receipts.workspaceRegistry.present,
482
- receipts.brainPack.present,
483
- capabilityAutoRecommended,
484
- jsonDumpAvoided,
485
- ].filter(Boolean).length;
486
-
487
- const userActionFindings = [
488
- !receipts.installIntake.present,
489
- !receipts.proof.present,
490
- ].filter(Boolean).length;
491
-
492
- const seamlessnessScore = Math.round((autoHandledCount / 6) * 100);
493
-
494
- return {
495
- id: "seamlessness",
496
- label: "Seamlessness",
497
- status: seamlessnessScore >= 60 ? "available" : "partial",
498
- headline: capabilityAutoRecommended ? "Capability selected automatically" : "Some manual steps needed",
499
- plainEnglishValue: capabilityAutoRecommended
500
- ? `Avorelo automatically selected the right capability pack without requiring the user to choose. ${autoHandledCount} surfaces prepared automatically.`
501
- : "The capability recommender did not run. Run `avorelo capabilities` to get an auto-routed recommendation.",
502
- primaryMetric: `${autoHandledCount}/6 surfaces auto-handled`,
503
- secondaryMetric: userActionFindings > 0 ? `${userActionFindings} surface${userActionFindings !== 1 ? "s" : ""} need user action` : null,
504
- evidence: [
505
- capabilityAutoRecommended ? "capability-recommender" : null,
506
- sc ? "session-context" : null,
507
- ].filter(Boolean),
508
- confidence: autoHandledCount >= 4 ? "medium" : "low",
509
- userDidNotChooseCapability,
510
- autoHandledFindings: autoHandledCount,
511
- userActionRequiredFindings: userActionFindings,
512
- seamlessnessScore,
513
- nextAction: !capabilityAutoRecommended
514
- ? "Run `avorelo capabilities` to auto-recommend the right pack."
515
- : null,
516
- userFacingSentence: capabilityAutoRecommended
517
- ? `Avorelo handled ${autoHandledCount} surfaces automatically — no manual capability selection needed.`
518
- : "Run `avorelo capabilities` to enable seamless capability routing.",
519
- };
520
- }
521
-
522
- // ── Readiness score ───────────────────────────────────────────────────────────
523
-
524
- function buildOperatingLoopReadiness(receipts, capabilityRec) {
525
- const sc = receipts.sessionContext.data;
526
- const wc = receipts.workControl.data;
527
- const reg = receipts.workspaceRegistry.data;
528
- const intake = receipts.installIntake.data;
529
- const safePath = receipts.safePath.data;
530
-
531
- const checks = {
532
- workControlAvailable: receipts.workControl.present && !isStale(receipts.workControl.ageMs, STALE_SHORT_MS),
533
- sessionContextFresh: receipts.sessionContext.present && !isStale(receipts.sessionContext.ageMs, STALE_SHORT_MS),
534
- registryFresh: receipts.workspaceRegistry.present && !isStale(receipts.workspaceRegistry.ageMs, STALE_SHORT_MS),
535
- brainPackAvailable: receipts.brainPack.present && !isStale(receipts.brainPack.ageMs, STALE_LONG_MS),
536
- capabilityRecommendationAvailable: Boolean(capabilityRec && capabilityRec.recommendedPack),
537
- nextActionAvailable: Boolean(
538
- (wc && wc.workControl && wc.workControl.nextSafestAction) ||
539
- (sc && sc.sessionStart && sc.sessionStart.nextSafestAction)
540
- ),
541
- proofAvailable: receipts.proof.present,
542
- activeRisksRouted: (() => {
543
- // A block/approval/reduced_scope is a SUCCESSFUL routing outcome
544
- const highRiskItems = intake && intake.summary ? intake.summary.highRiskItems || 0 : 0;
545
- const criticalRiskItems = intake && intake.summary ? intake.summary.criticalRiskItems || 0 : 0;
546
- const safePathDecision = safePath && safePath.safePathDecision ? safePath.safePathDecision : null;
547
- const intakeNextAction = intake && intake.nextAction ? intake.nextAction : null;
548
- if (highRiskItems === 0 && criticalRiskItems === 0) return true;
549
- // Risks exist — check if they are routed
550
- return Boolean(
551
- safePathDecision && safePathDecision !== "allow_as_is" ||
552
- intakeNextAction ||
553
- (receipts.safePath.present && receipts.safePath.data)
554
- );
555
- })(),
556
- relevantFilesAvailable: Boolean(sc && sc.sessionStart && (sc.sessionStart.relevantFiles || []).length > 0),
557
- targetHandoffPrepared: Boolean(sc && sc.sessionStart && sc.sessionStart.compactPrompt),
558
- };
559
-
560
- const score = Object.values(checks).filter(Boolean).length * 10;
561
- const band = score >= 85 ? "excellent" : score >= 65 ? "good" : score >= 40 ? "fair" : "needs_attention";
562
-
563
- const missingPieces = Object.entries(checks)
564
- .filter(([, v]) => !v)
565
- .map(([k]) => k);
566
-
567
- const nextAction = missingPieces.length === 0
568
- ? "All operating loop surfaces are ready."
569
- : `Missing: ${missingPieces.slice(0, 3).join(", ")}. Run the corresponding Avorelo surface to improve readiness.`;
570
-
571
- const bandLabel = { excellent: "Excellent", good: "Good", fair: "Fair", needs_attention: "Needs Attention" }[band];
572
-
573
- return {
574
- score,
575
- band,
576
- bandLabel,
577
- summary: `Operating loop readiness: ${bandLabel} (${score}/100)`,
578
- checks,
579
- missingPieces,
580
- nextAction,
581
- };
582
- }
583
-
584
- // ── Opportunity detectors ─────────────────────────────────────────────────────
585
-
586
- function buildOpportunityFindings(receipts, capabilityRec, readiness) {
587
- const findings = [];
588
- const sc = receipts.sessionContext.data;
589
- const wc = receipts.workControl.data;
590
- const intake = receipts.installIntake.data;
591
-
592
- function addFinding(id, severity, confidence, valueType, plainEnglish, evidence, recommendedAction, handledAuto, needsUser) {
593
- findings.push({ id, severity, confidence, valueType, plainEnglish, evidence, recommendedAction, handledAutomatically: handledAuto, needsUserAction: needsUser });
594
- }
595
-
596
- if (!receipts.sessionContext.present) {
597
- addFinding("missing_session_context", "warning", "high", "time",
598
- "Session context not found. The next model session will need to rediscover the repo.",
599
- [], "Run `avorelo session-context --handoff --target claude`.", false, true);
600
- } else if (isStale(receipts.sessionContext.ageMs, STALE_SHORT_MS)) {
601
- addFinding("stale_session_context", "info", "high", "time",
602
- `Session context is stale (${ageLabel(receipts.sessionContext.ageMs)}). May not reflect current repo state.`,
603
- ["session-context"], "Run `avorelo session-context --handoff --target claude` to refresh.", false, true);
604
- }
605
-
606
- if (!receipts.workControl.present) {
607
- addFinding("missing_work_control", "warning", "high", "clarity",
608
- "Work-control receipt not found. No finalState or nextSafestAction guidance available.",
609
- [], "Run `avorelo work-control --json`.", false, true);
610
- } else if (isStale(receipts.workControl.ageMs, STALE_SHORT_MS)) {
611
- addFinding("stale_work_control", "info", "medium", "clarity",
612
- `Work-control receipt is stale (${ageLabel(receipts.workControl.ageMs)}).`,
613
- ["work-control"], "Run `avorelo work-control --json` to refresh.", false, true);
614
- }
615
-
616
- if (!receipts.workspaceRegistry.present) {
617
- addFinding("missing_workspace_registry", "warning", "high", "time",
618
- "Workspace registry not found. Asset inventory not available for session context.",
619
- [], "Run `avorelo workspace-registry`.", false, true);
620
- } else if (isStale(receipts.workspaceRegistry.ageMs, STALE_SHORT_MS)) {
621
- addFinding("stale_workspace_registry", "info", "medium", "time",
622
- `Workspace registry is stale (${ageLabel(receipts.workspaceRegistry.ageMs)}).`,
623
- ["workspace-registry"], "Run `avorelo workspace-registry` to refresh.", false, true);
624
- }
625
-
626
- if (receipts.brainPack.present && isStale(receipts.brainPack.ageMs, STALE_LONG_MS)) {
627
- addFinding("stale_brain_pack", "info", "low", "time",
628
- `Brain Pack is stale (${ageLabel(receipts.brainPack.ageMs)}).`,
629
- ["brain-pack"], "Run `avorelo brain-pack` to refresh project context.", false, true);
630
- }
631
-
632
- // Rediscovery loop risk: registry present but session context missing
633
- if (receipts.workspaceRegistry.present && !receipts.sessionContext.present) {
634
- addFinding("rediscovery_loop_risk", "warning", "high", "time",
635
- "Workspace registry is available but session context is missing. The next model will rediscover files already indexed.",
636
- ["workspace-registry"], "Run `avorelo session-context --handoff --target claude` to use the indexed registry.", false, true);
637
- }
638
-
639
- // Huge JSON dump risk
640
- const hasHighRawCandidate = (() => {
641
- const rawEst = estimateRawContextTokens(receipts);
642
- return rawEst.tokens !== null && rawEst.tokens > 8000;
643
- })();
644
- const scMissingWithHighRaw = !receipts.sessionContext.present && hasHighRawCandidate;
645
- const scPresentButNoAvoid = sc && sc.tokenDiscipline && sc.tokenDiscipline.avoidedJsonDump === false;
646
- if (scMissingWithHighRaw || scPresentButNoAvoid) {
647
- addFinding("huge_json_dump_risk", "warning", "medium", "cost_tokens",
648
- scMissingWithHighRaw
649
- ? `No compact handoff prepared. Raw candidate context estimated at ~${estimateRawContextTokens(receipts).tokens?.toLocaleString()} tokens.`
650
- : "Session context did not avoid a JSON dump.",
651
- scPresentButNoAvoid ? ["session-context"] : [], "Run `avorelo session-context --handoff --target claude` to produce a compact handoff.", false, true);
652
- }
653
-
654
- // Overwide context
655
- const compactTokens = sc && sc.tokenDiscipline ? sc.tokenDiscipline.estimatedTokens : null;
656
- if (compactTokens && compactTokens > 8000 && sc.tokenDiscipline.truncationApplied !== true) {
657
- addFinding("overwide_context_risk", "info", "medium", "cost_tokens",
658
- `Compact handoff is ${compactTokens.toLocaleString()} tokens. Consider narrowing scope.`,
659
- ["session-context"], "Run `avorelo session-context --max-chars 4000` to reduce context.", false, true);
660
- }
661
-
662
- if (!capabilityRec || !capabilityRec.recommendedPack) {
663
- addFinding("missing_capability_recommendation", "info", "medium", "seamlessness",
664
- "No capability recommendation found. Capability routing may not be optimal.",
665
- [], "Run `avorelo capabilities --json` to get a recommendation.", false, true);
666
- } else if (capabilityRec.wrongCapabilityRisk) {
667
- addFinding("wrong_capability_risk", "warning", "medium", "seamlessness",
668
- "Capability recommender flagged potential wrong-capability risk.",
669
- ["capability-recommender"], "Review recommended pack and consider alternatives.", false, true);
670
- }
671
-
672
- // Unsafe action needs safe path
673
- const highRisk = intake && intake.summary ? (intake.summary.highRiskItems || 0) : 0;
674
- const critRisk = intake && intake.summary ? (intake.summary.criticalRiskItems || 0) : 0;
675
- if ((highRisk > 0 || critRisk > 0) && !receipts.safePath.present) {
676
- addFinding("unsafe_action_needs_safe_path", "warning", "high", "security",
677
- `${highRisk + critRisk} high/critical-risk intake item(s) found but no Safe Path receipt generated.`,
678
- ["install-intake"], "Run `avorelo guard --action command_run --action deploy_operation` before executing risky scripts.", false, true);
679
- }
680
-
681
- if (critRisk > 0) {
682
- addFinding("high_risk_intake_needs_review", "error", "high", "security",
683
- `${critRisk} critical-risk intake item(s) need review before proceeding.`,
684
- ["install-intake"], "Review: run `avorelo intake --json` and inspect criticalRiskItems.", false, true);
685
- }
686
-
687
- if (!receipts.proof.present) {
688
- addFinding("missing_proof", "info", "medium", "clarity",
689
- "No proof receipt found. Verification status unknown.",
690
- [], "Run `avorelo proof` after a session to capture what was checked.", true, false);
691
- }
692
-
693
- if (!readiness.checks.nextActionAvailable) {
694
- addFinding("missing_next_action", "warning", "high", "clarity",
695
- "No nextSafestAction available in work-control or session context.",
696
- [], "Run `avorelo work-control --json` to generate next-action guidance.", false, true);
697
- }
698
-
699
- if (!readiness.checks.targetHandoffPrepared) {
700
- addFinding("target_handoff_not_prepared", "info", "medium", "seamlessness",
701
- "No compact handoff prepared for a target (Claude/Codex/local model).",
702
- [], "Run `avorelo session-context --handoff --target claude`.", false, true);
703
- }
704
-
705
- return findings;
706
- }
707
-
708
- // ── In-session value moments ──────────────────────────────────────────────────
709
-
710
- function buildSessionValueMoments(receipts, capabilityRec, findings, readiness) {
711
- const moments = [];
712
- const sc = receipts.sessionContext.data;
713
- const wc = receipts.workControl.data;
714
- const intake = receipts.installIntake.data;
715
-
716
- // session_start
717
- const sessionContextFresh = receipts.sessionContext.present && !isStale(receipts.sessionContext.ageMs, STALE_SHORT_MS);
718
- const relevantFiles = sc && sc.sessionStart ? (sc.sessionStart.relevantFiles || []).length : 0;
719
- const compactTokens = sc && sc.tokenDiscipline ? sc.tokenDiscipline.estimatedTokens : null;
720
- // Suppress moment if session context value is weak (no relevant files, no compact tokens)
721
- const sessionStartValueStrong = sessionContextFresh && (relevantFiles > 0 || compactTokens !== null);
722
- if (sessionStartValueStrong) {
723
- moments.push({
724
- moment: "session_start",
725
- severity: "success",
726
- oneLine: `Ready to continue. Avorelo selected ${relevantFiles} relevant files and prepared a compact Claude handoff${compactTokens ? ` (~${compactTokens.toLocaleString()} tokens)` : ""}.`,
727
- whyItMatters: "The next model session gets targeted context instead of broad rediscovery.",
728
- evidence: ["session-context", "workspace-registry"],
729
- nextAction: sc && sc.sessionStart && sc.sessionStart.nextSafestAction ? sc.sessionStart.nextSafestAction : null,
730
- suppressIfLowValue: false,
731
- });
732
- } else if (!sessionContextFresh) {
733
- moments.push({
734
- moment: "session_start",
735
- severity: "info",
736
- oneLine: "Session context not ready. Run `avorelo session-context --handoff --target claude` before the next session.",
737
- whyItMatters: "Without compact session context, the next model will rediscover files and context manually.",
738
- evidence: [],
739
- nextAction: "avorelo session-context --handoff --target claude",
740
- suppressIfLowValue: false,
741
- });
742
- }
743
-
744
- // routing_decision
745
- const capPack = capabilityRec && capabilityRec.recommendedPack;
746
- if (capPack) {
747
- moments.push({
748
- moment: "routing_decision",
749
- severity: "info",
750
- oneLine: `Recommended path: ${capPack.name}. Why: ${capabilityRec.reason || "capability matched workspace signals"}.`,
751
- whyItMatters: "Using the right capability reduces wasted context and manual routing decisions.",
752
- evidence: ["capability-recommender"],
753
- nextAction: capabilityRec.nextAction || null,
754
- suppressIfLowValue: readiness.score >= 80,
755
- });
756
- }
757
-
758
- // risk_detected
759
- const highRisk = intake && intake.summary ? (intake.summary.highRiskItems || 0) : 0;
760
- const critRisk = intake && intake.summary ? (intake.summary.criticalRiskItems || 0) : 0;
761
- if (highRisk > 0 || critRisk > 0) {
762
- moments.push({
763
- moment: "risk_detected",
764
- severity: critRisk > 0 ? "warning" : "info",
765
- oneLine: `Risk surfaced: ${highRisk + critRisk} risky item${(highRisk + critRisk) !== 1 ? "s" : ""} detected (${critRisk} critical). Use Safe Path before executing deploy/network scripts.`,
766
- whyItMatters: "Executing risky scripts without review can cause irreversible damage.",
767
- evidence: ["install-intake"],
768
- nextAction: "avorelo guard --action command_run --action deploy_operation",
769
- suppressIfLowValue: false,
770
- });
771
- }
772
-
773
- // proof_complete
774
- if (receipts.proof.present) {
775
- const proof = receipts.proof.data;
776
- const finalStatus = proof && proof.finalStatus ? proof.finalStatus : "unknown";
777
- const checkedStages = proof && proof.verification ? proof.verification : null;
778
- moments.push({
779
- moment: "proof_complete",
780
- severity: finalStatus === "success" ? "success" : "info",
781
- oneLine: `Proof: ${finalStatus}. Verification: ${checkedStages ? "recorded" : "not recorded"}.`,
782
- whyItMatters: "Proof shows what was checked so the next session knows where to continue.",
783
- evidence: ["proof"],
784
- nextAction: null,
785
- suppressIfLowValue: finalStatus === "success",
786
- });
787
- }
788
-
789
- // session_end
790
- const hasAnySavings = receipts.sessionContext.present || receipts.workControl.present;
791
- if (hasAnySavings) {
792
- const savers = [
793
- receipts.sessionContext.present ? "context reduced" : null,
794
- receipts.workControl.present && wc && wc.workControl && wc.workControl.nextSafestAction ? "next action preserved" : null,
795
- (highRisk > 0 || critRisk > 0) ? "risk surfaced" : null,
796
- capPack ? "capability auto-selected" : null,
797
- ].filter(Boolean);
798
- moments.push({
799
- moment: "session_end",
800
- severity: "success",
801
- oneLine: savers.length > 0
802
- ? `Saved this session: ${savers.join(", ")}.`
803
- : "Avorelo surfaces are ready for the next session.",
804
- whyItMatters: "These savings compound — each prepared session reduces rediscovery in the next.",
805
- evidence: [],
806
- nextAction: null,
807
- suppressIfLowValue: savers.length === 0,
808
- });
809
- }
810
-
811
- return moments;
812
- }
813
-
814
- // ── Coach output ──────────────────────────────────────────────────────────────
815
-
816
- function buildCoachOutput(findings, readiness, receipts) {
817
- // Find the most impactful finding
818
- const priority = ["error", "warning", "info"];
819
- const valueTypePriority = ["security", "time", "cost_tokens", "clarity", "seamlessness"];
820
-
821
- const prioritized = [...findings].sort((a, b) => {
822
- const ai = priority.indexOf(a.severity);
823
- const bi = priority.indexOf(b.severity);
824
- if (ai !== bi) return ai - bi;
825
- return valueTypePriority.indexOf(a.valueType) - valueTypePriority.indexOf(b.valueType);
826
- });
827
-
828
- const top = prioritized[0];
829
-
830
- if (!top) {
831
- return {
832
- finding: "All operating loop surfaces are ready.",
833
- whyItMatters: "Avorelo has prepared context, capability routing, and safety surfaces.",
834
- expectedValue: "The next session starts with no rediscovery needed.",
835
- recommendedAction: "Run `avorelo session-context --handoff --target claude` when starting a new session.",
836
- confidence: readiness.score >= 80 ? "high" : "medium",
837
- askUserOnlyIfBlocked: null,
838
- };
839
- }
840
-
841
- const valueTypeLabels = {
842
- time: "time saved",
843
- cost_tokens: "context/token reduction",
844
- security: "security risk avoided",
845
- clarity: "clarity improved",
846
- seamlessness: "seamlessness improved",
847
- };
848
-
849
- return {
850
- finding: top.plainEnglish,
851
- whyItMatters: `This ${top.severity === "error" ? "critical issue" : "opportunity"} affects ${valueTypeLabels[top.valueType] || top.valueType}.`,
852
- expectedValue: top.valueType === "time" ? "Avoid repo rediscovery in the next session."
853
- : top.valueType === "security" ? "Prevent risky actions from running without review."
854
- : top.valueType === "cost_tokens" ? "Reduce candidate context loaded in the next session."
855
- : "Improve operating loop quality.",
856
- recommendedAction: top.recommendedAction,
857
- confidence: top.confidence,
858
- askUserOnlyIfBlocked: top.needsUserAction ? null : null,
859
- };
860
- }
861
-
862
- // ── Impact validation ─────────────────────────────────────────────────────────
863
-
864
- function buildImpactValidation(receipts, readiness) {
865
- const rawEst = estimateRawContextTokens(receipts);
866
- const compactEst = estimateCompactHandoffTokens(receipts);
867
- const sc = receipts.sessionContext.data;
868
- const reg = receipts.workspaceRegistry.data;
869
- const wc = receipts.workControl.data;
870
-
871
- const rawTokens = rawEst.tokens;
872
- const compactTokens = compactEst.tokens;
873
-
874
- const before = {
875
- rawContextEstimateTokens: rawTokens,
876
- rawContextEstimateBasis: rawEst.sources.join("; ") || "unavailable",
877
- workControlReceiptChars: receipts.workControl.charLen,
878
- registryAssets: reg && reg.summary ? reg.summary.totalAssets : null,
879
- broadScanWouldHaveOccurred: !receipts.sessionContext.present,
880
- };
881
-
882
- const after = {
883
- compactHandoffTokens: compactTokens,
884
- compactHandoffBasis: compactEst.basis,
885
- relevantFilesSelected: sc && sc.sessionStart ? (sc.sessionStart.relevantFiles || []).length : 0,
886
- broadScanAvoided: receipts.sessionContext.present,
887
- jsonDumpAvoided: Boolean(sc && sc.tokenDiscipline && sc.tokenDiscipline.avoidedJsonDump),
888
- nextActionPresent: readiness.checks.nextActionAvailable,
889
- proofPresent: receipts.proof.present,
890
- };
891
-
892
- let verdict = "insufficient_data";
893
- let confidence = "low";
894
-
895
- if (rawTokens === null || compactTokens === null) {
896
- verdict = "insufficient_data";
897
- confidence = "low";
898
- } else if (compactTokens > rawTokens) {
899
- verdict = "regressed";
900
- confidence = "low";
901
- } else {
902
- const reduction = (rawTokens - compactTokens) / rawTokens;
903
- const hasQualitySignals = after.nextActionPresent && (after.proofPresent || after.relevantFilesSelected > 0);
904
- if (reduction >= 0.5 && hasQualitySignals) {
905
- verdict = "improved";
906
- confidence = "medium";
907
- } else if (reduction > 0 || hasQualitySignals) {
908
- verdict = "unclear";
909
- confidence = "low";
910
- } else {
911
- verdict = "insufficient_data";
912
- }
913
- }
914
-
915
- const tokenReduction = rawTokens && compactTokens ? Math.max(0, rawTokens - compactTokens) : null;
916
- const evidenceSources = [
917
- rawEst.sources.length ? `raw estimate sources: ${rawEst.sources.join(", ")}` : null,
918
- `compact from: ${compactEst.basis}`,
919
- ].filter(Boolean);
920
-
921
- return {
922
- verdict,
923
- before,
924
- after,
925
- tokenReduction,
926
- tokenReductionPercent: rawTokens && tokenReduction ? Math.round((tokenReduction / rawTokens) * 100) : null,
927
- evidence: evidenceSources,
928
- confidence,
929
- caveat: "Context estimates are based on candidate source sizes, not measured model context window usage. Confidence is intentionally conservative.",
930
- };
931
- }
932
-
933
- // ── Dashboard-ready surface ───────────────────────────────────────────────────
934
-
935
- function buildDashboardReady(cards, readiness, capabilityRec, receipts, localDashboardPath, calibration) {
936
- const timeSaved = cards.timeSaved;
937
- const costTokens = cards.costOrTokensSaved;
938
- const security = cards.securityRiskAvoided;
939
-
940
- // Hero sentence: pick strongest available signal
941
- let hero = "Avorelo operating surfaces are ready.";
942
- if (timeSaved.status === "available" && timeSaved.headline.includes("minutes")) {
943
- hero = timeSaved.userFacingSentence;
944
- } else if (costTokens.status === "available" && costTokens.userFacingSentence.includes("tokens")) {
945
- hero = costTokens.userFacingSentence;
946
- } else if (security.status === "available") {
947
- hero = security.userFacingSentence;
948
- }
949
-
950
- const nextAction = readiness.nextAction;
951
-
952
- const wc = receipts.workControl.data;
953
- const evidenceLine = [
954
- receipts.workControl.present ? `work-control: ${wc && wc.workControl ? wc.workControl.finalState || "ok" : "ok"}` : null,
955
- receipts.sessionContext.present ? "session-context: ready" : null,
956
- receipts.workspaceRegistry.present ? `registry: ${receipts.workspaceRegistry.data && receipts.workspaceRegistry.data.summary ? receipts.workspaceRegistry.data.summary.totalAssets + " assets" : "ready"}` : null,
957
- receipts.installIntake.present ? `intake: scanned` : null,
958
- ].filter(Boolean).join(" · ");
959
-
960
- const shouldShowInSession = readiness.band === "needs_attention" || readiness.band === "fair";
961
- const shouldShowDashboard = true;
962
-
963
- // Derive proof data for primary card enrichment from calibration
964
- const proofs = calibration ? calibration.proofs : [];
965
- const getProof = (id) => proofs.find((p) => p.valueId === id) || null;
966
- const timeSavedProof = getProof("timeSaved");
967
- const tokenProof = getProof("tokenReduction");
968
- const securityProof = getProof("risksSurfaced") || proofs.find((p) => p.dimension === "security" && p.value !== null) || null;
969
-
970
- const calibVerdict = calibration ? calibration.calibrationReport.overallVerdict : null;
971
- const safeCopyCandidates = calibration ? (calibration.calibrationReport.recommendedCopySafe || []) : [];
972
- const blockedCopyCandidates = calibration ? (calibration.calibrationReport.blockedCopy || []) : [];
973
-
974
- return {
975
- hero,
976
- primaryCards: [
977
- {
978
- id: timeSaved.id, label: timeSaved.label, headline: timeSaved.headline,
979
- status: timeSaved.status, userFacingSentence: timeSaved.userFacingSentence,
980
- confidence: timeSaved.confidence, estimateBasis: timeSaved.estimateBasis,
981
- valueClass: timeSavedProof ? timeSavedProof.valueClass : "heuristic",
982
- caveat: timeSavedProof && timeSavedProof.caveats.length ? timeSavedProof.caveats[0] : null,
983
- evidence: timeSavedProof ? timeSavedProof.evidence : (timeSaved.evidence || []),
984
- userFacingAllowed: timeSavedProof ? timeSavedProof.userFacingAllowed : (timeSaved.status !== "unavailable"),
985
- dashboardAllowed: timeSavedProof ? timeSavedProof.dashboardAllowed : (timeSaved.status !== "unavailable"),
986
- },
987
- {
988
- id: costTokens.id, label: costTokens.label, headline: costTokens.headline,
989
- status: costTokens.status, userFacingSentence: costTokens.userFacingSentence,
990
- confidence: costTokens.confidence, estimateBasis: costTokens.estimateBasis,
991
- valueClass: tokenProof ? tokenProof.valueClass : "unavailable",
992
- caveat: tokenProof && tokenProof.caveats.length ? tokenProof.caveats[0] : "Cost unavailable — no local pricing source",
993
- evidence: tokenProof ? tokenProof.evidence : (costTokens.evidence || []),
994
- userFacingAllowed: tokenProof ? tokenProof.userFacingAllowed : (costTokens.status !== "unavailable"),
995
- dashboardAllowed: tokenProof ? tokenProof.dashboardAllowed : (costTokens.status !== "unavailable"),
996
- },
997
- {
998
- id: security.id, label: security.label, headline: security.headline,
999
- status: security.status, userFacingSentence: security.userFacingSentence,
1000
- confidence: security.confidence,
1001
- valueClass: securityProof ? securityProof.valueClass : (security.confidence === "high" ? "measured" : "unavailable"),
1002
- caveat: securityProof && securityProof.caveats.length ? securityProof.caveats[0] : null,
1003
- evidence: securityProof ? securityProof.evidence : (security.evidence || []),
1004
- userFacingAllowed: securityProof ? securityProof.userFacingAllowed : (security.status !== "unavailable"),
1005
- dashboardAllowed: securityProof ? securityProof.dashboardAllowed : (security.status !== "unavailable"),
1006
- },
1007
- ],
1008
- secondaryCards: [
1009
- { id: cards.clarity.id, label: cards.clarity.label, headline: cards.clarity.headline, status: cards.clarity.status },
1010
- { id: cards.seamlessness.id, label: cards.seamlessness.label, headline: cards.seamlessness.headline, status: cards.seamlessness.status },
1011
- ],
1012
- evidenceLine: evidenceLine || "No evidence available yet.",
1013
- readinessScore: readiness.score,
1014
- readinessBand: readiness.band,
1015
- nextAction,
1016
- calibrationVerdict: calibVerdict,
1017
- caveatLine: "Time estimate is heuristic. Token estimate is based on candidate context size, not measured model context window usage.",
1018
- localDashboardPath: localDashboardPath || null,
1019
- displayPolicy: {
1020
- onlyUserFacingAllowedByDefault: true,
1021
- caveatsRequired: true,
1022
- pricingClaimsBlocked: true,
1023
- websiteClaimsBlockedUntilMeasuredHighConfidence: true,
1024
- },
1025
- safeCopyCandidates,
1026
- blockedCopyCandidates,
1027
- shouldShowInSession,
1028
- shouldShowDashboard,
1029
- };
1030
- }
1031
-
1032
- // ── Willingness-to-pay signals ────────────────────────────────────────────────
1033
-
1034
- function buildWillingnessToPaySignals(cards, readiness, receipts) {
1035
- const signals = [];
1036
-
1037
- const timeSaved = cards.timeSaved;
1038
- if (timeSaved.status === "available" && timeSaved.primaryMetric.includes("steps")) {
1039
- signals.push({
1040
- signal: "time_savings_measurable",
1041
- value: timeSaved.headline,
1042
- evidence: "work-control + session-context + registry surfaces",
1043
- userFacingHook: timeSaved.userFacingSentence,
1044
- });
1045
- }
1046
-
1047
- const reg = receipts.workspaceRegistry.data;
1048
- if (reg && reg.valueMeasurement && reg.valueMeasurement.willingnessToPaySignal) {
1049
- signals.push({
1050
- signal: "workspace_registry_wtp",
1051
- value: reg.valueMeasurement.willingnessToPaySignal,
1052
- evidence: "workspace-registry.valueMeasurement",
1053
- });
1054
- }
1055
-
1056
- if (readiness.score >= 70) {
1057
- signals.push({
1058
- signal: "high_readiness_score",
1059
- value: `${readiness.score}/100 (${readiness.band})`,
1060
- evidence: "operating loop readiness score",
1061
- userFacingHook: "Your AI coding environment is well-prepared. Avorelo handles the setup automatically.",
1062
- });
1063
- }
1064
-
1065
- return signals;
1066
- }
1067
-
1068
- // ── Display policy helpers ────────────────────────────────────────────────────
1069
-
1070
- function filterUserFacingValueCards(proofs) {
1071
- return (proofs || []).filter((p) => p.userFacingAllowed === true);
1072
- }
1073
-
1074
- function buildSafeCopyCandidates(calibrationReport) {
1075
- return calibrationReport ? (calibrationReport.recommendedCopySafe || []) : [];
1076
- }
1077
-
1078
- function buildBlockedCopyCandidates(calibrationReport) {
1079
- return calibrationReport ? (calibrationReport.blockedCopy || []) : [];
1080
- }
1081
-
1082
- function formatCaveatLine(proof) {
1083
- if (!proof || !proof.caveats || !proof.caveats.length) return null;
1084
- return proof.caveats[0];
1085
- }
1086
-
1087
- function formatEvidenceLine(proofs) {
1088
- const sources = new Set();
1089
- (proofs || []).forEach((p) => {
1090
- (p.evidence || []).forEach((e) => sources.add(e));
1091
- });
1092
- return sources.size ? Array.from(sources).join(" · ") : null;
1093
- }
1094
-
1095
- // ── Local dashboard preview ───────────────────────────────────────────────────
1096
-
1097
- function buildLocalDashboardPreview(cwd, value) {
1098
- const dashboardReady = value.dashboardReady;
1099
- const readiness = value.operatingLoopReadiness;
1100
-
1101
- if (!dashboardReady) return null;
1102
-
1103
- // Filter primary cards to user-facing-allowed only
1104
- const visiblePrimaryCards = (dashboardReady.primaryCards || []).filter(
1105
- (c) => c.userFacingAllowed !== false
1106
- );
1107
-
1108
- const calibVerdict = dashboardReady.calibrationVerdict;
1109
- const caveatLine = dashboardReady.caveatLine;
1110
-
1111
- const lines = [
1112
- `# Avorelo Value Summary`,
1113
- `_Generated: ${value.createdAt || new Date().toISOString()}_`,
1114
- ``,
1115
- `## Hero`,
1116
- `**${dashboardReady.hero}**`,
1117
- ``,
1118
- `Readiness: **${readiness.bandLabel}** (${readiness.score}/100)`,
1119
- ``,
1120
- `## Primary Value`,
1121
- ``,
1122
- `| Dimension | Status | Headline | Confidence |`,
1123
- `|-----------|--------|----------|------------|`,
1124
- ...visiblePrimaryCards.map((c) => {
1125
- const conf = c.valueClass ? `${c.valueClass}${c.confidence ? `, ${c.confidence}` : ""}` : (c.confidence || "");
1126
- return `| ${c.label} | ${c.status} | ${c.headline} | ${conf} |`;
1127
- }),
1128
- ``,
1129
- visiblePrimaryCards.some((c) => c.caveat) ? `## Caveats` : null,
1130
- ...visiblePrimaryCards
1131
- .filter((c) => c.caveat)
1132
- .map((c) => `- **${c.label}:** ${c.caveat}`),
1133
- visiblePrimaryCards.some((c) => c.caveat) ? `` : null,
1134
- `## Next Action`,
1135
- `${dashboardReady.nextAction}`,
1136
- ``,
1137
- `## Evidence`,
1138
- `${dashboardReady.evidenceLine}`,
1139
- ``,
1140
- calibVerdict ? `## Calibration` : null,
1141
- calibVerdict ? `Verdict: **${calibVerdict.replace(/_/g, " ")}**` : null,
1142
- caveatLine ? `_${caveatLine}_` : null,
1143
- calibVerdict ? `` : null,
1144
- `_Run \`avorelo operating-value --json\` for the full calibrated data contract._`,
1145
- ].filter((l) => l !== null);
1146
-
1147
- const content = lines.join("\n") + "\n";
1148
- const abs = path.join(cwd, OPERATING_VALUE_DASHBOARD_PREVIEW_REL);
1149
- try {
1150
- fs.mkdirSync(path.dirname(abs), { recursive: true });
1151
- fs.writeFileSync(abs, content, "utf8");
1152
- return OPERATING_VALUE_DASHBOARD_PREVIEW_REL;
1153
- } catch {
1154
- return null;
1155
- }
1156
- }
1157
-
1158
- // ── Main builder ──────────────────────────────────────────────────────────────
1159
-
1160
- function buildOperatingValue(cwd, options = {}) {
1161
- const valueId = `ov-${Date.now()}-${shortId()}`;
1162
- const createdAt = nowIso();
1163
-
1164
- const receipts = readReceipts(cwd);
1165
-
1166
- // Read capability recommendation (non-blocking)
1167
- let capabilityRec = null;
1168
- try {
1169
- const { buildCapabilityLayerSurface } = require("./capability-recommender");
1170
- capabilityRec = buildCapabilityLayerSurface(cwd, {}, null);
1171
- } catch {}
1172
-
1173
- // ── Measurement evidence (non-blocking) ──────────────────────────────────────
1174
- let pricingSource = null;
1175
- let pricingEntry = null;
1176
- let tokenEvidence = null;
1177
- let costEvidenceV1 = null;
1178
- try {
1179
- pricingSource = getLocalPricingSource(cwd);
1180
- if (pricingSource.available) {
1181
- // Default to claude-sonnet-4-6 if no specific model info available
1182
- pricingEntry = getLocalPricingEntry(cwd, "anthropic", "claude-sonnet-4-6");
1183
- }
1184
- tokenEvidence = buildTokenEvidence(cwd);
1185
- writeTokenEvidence(cwd, tokenEvidence);
1186
- costEvidenceV1 = buildCostEvidenceV1({ pricingSource, pricingEntry, tokenEvidence });
1187
- } catch {}
1188
-
1189
- const cards = {
1190
- timeSaved: buildTimeSavedCard(receipts, capabilityRec),
1191
- costOrTokensSaved: buildCostOrTokensSavedCard(receipts, costEvidenceV1),
1192
- securityRiskAvoided: buildSecurityRiskAvoidedCard(receipts),
1193
- clarity: buildClarityCard(receipts),
1194
- seamlessness: buildSeamlessnessCard(receipts, capabilityRec),
1195
- };
1196
-
1197
- const readiness = buildOperatingLoopReadiness(receipts, capabilityRec);
1198
- const findings = buildOpportunityFindings(receipts, capabilityRec, readiness);
1199
- const moments = buildSessionValueMoments(receipts, capabilityRec, findings, readiness);
1200
- const coach = buildCoachOutput(findings, readiness, receipts);
1201
- const impactValidation = buildImpactValidation(receipts, readiness);
1202
- const willingnessToPaySignals = buildWillingnessToPaySignals(cards, readiness, receipts);
1203
-
1204
- const rawEst = estimateRawContextTokens(receipts);
1205
- const compactEst = estimateCompactHandoffTokens(receipts);
1206
- const steps = countManualStepsAvoided(receipts, capabilityRec);
1207
- const sc = receipts.sessionContext.data;
1208
- const reg = receipts.workspaceRegistry.data;
1209
- const intake = receipts.installIntake.data;
1210
- const safePath = receipts.safePath.data;
1211
-
1212
- // ── Value proof calibration (computed before dashboardReady so display policy fields are populated) ─
1213
- const highRiskItemsForProof = intake && intake.summary ? intake.summary.highRiskItems || 0 : 0;
1214
- const critRiskItemsForProof = intake && intake.summary ? intake.summary.criticalRiskItems || 0 : 0;
1215
- const safePathDecisionForProof = safePath && safePath.safePathDecision ? safePath.safePathDecision : null;
1216
- const risksBlockedForProof = safePathDecisionForProof === "block" ? 1 : 0;
1217
- const risksRoutedForProof = (safePathDecisionForProof === "approval_required" || safePathDecisionForProof === "recommend_reduced_scope" || safePathDecisionForProof === "warn_with_boundary") ? 1 : 0;
1218
- const tokenReductionForProof = rawEst.tokens && compactEst.tokens ? Math.max(0, rawEst.tokens - compactEst.tokens) : null;
1219
- const capAppliedForProof = steps.count * MINUTES_PER_MANUAL_STEP_HIGH > MINUTES_CAP;
1220
-
1221
- const calibration = buildValueProofs({
1222
- manualStepsAvoided: steps.count,
1223
- minMinutes: steps.count * MINUTES_PER_MANUAL_STEP_LOW,
1224
- maxMinutes: Math.min(steps.count * MINUTES_PER_MANUAL_STEP_HIGH, MINUTES_CAP),
1225
- timeSavedEvidence: cards.timeSaved.evidence,
1226
- capApplied: capAppliedForProof,
1227
- rawCandidateTokens: rawEst.tokens,
1228
- rawConfidence: rawEst.confidence,
1229
- rawSources: rawEst.sources,
1230
- compactHandoffTokens: compactEst.tokens,
1231
- compactConfidence: compactEst.confidence,
1232
- tokenReduction: tokenReductionForProof,
1233
- hasLocalPricingSource: !!(pricingSource && pricingSource.available),
1234
- costEvidence: costEvidenceV1,
1235
- risksSurfaced: highRiskItemsForProof + critRiskItemsForProof,
1236
- risksRouted: risksRoutedForProof,
1237
- risksBlocked: risksBlockedForProof,
1238
- approvalsRequired: 0,
1239
- reducedScopeRecommendations: 0,
1240
- reviewRequiredItems: 0,
1241
- highRiskAssetsInRegistry: reg && reg.summary ? reg.summary.highRiskAssets || 0 : 0,
1242
- intakePresent: receipts.installIntake.present,
1243
- safePathPresent: receipts.safePath.present,
1244
- nextActionPresent: readiness.checks.nextActionAvailable,
1245
- doNotRepeatCount: cards.clarity.doNotRepeatCount,
1246
- relevantCommandsCount: cards.clarity.relevantCommandsCount,
1247
- targetHandoffPrepared: readiness.checks.targetHandoffPrepared,
1248
- proofAvailable: receipts.proof.present,
1249
- });
1250
-
1251
- const dashboardReady = buildDashboardReady(cards, readiness, capabilityRec, receipts, null, calibration);
1252
-
1253
- // Build local dashboard preview now that dashboardReady has calibration data
1254
- const finalPreviewPath = options.skipPreview ? null : buildLocalDashboardPreview(cwd, {
1255
- createdAt,
1256
- operatingLoopReadiness: readiness,
1257
- valueCards: cards,
1258
- dashboardReady,
1259
- });
1260
- dashboardReady.localDashboardPath = finalPreviewPath;
1261
-
1262
- const optimizationEffectiveness = {
1263
- rawContextWouldHaveLoadedTokens: rawEst.tokens,
1264
- rawContextSources: rawEst.sources,
1265
- compactHandoffTokens: compactEst.tokens,
1266
- compactHandoffBasis: compactEst.basis,
1267
- tokenReductionEstimate: rawEst.tokens && compactEst.tokens ? Math.max(0, rawEst.tokens - compactEst.tokens) : null,
1268
- contextCompressionRatio: rawEst.tokens && compactEst.tokens && rawEst.tokens > 0 ? Math.round((compactEst.tokens / rawEst.tokens) * 100) / 100 : null,
1269
- relevantFilesSelected: sc && sc.sessionStart ? (sc.sessionStart.relevantFiles || []).length : 0,
1270
- totalWorkspaceAssets: reg && reg.summary ? reg.summary.totalAssets : null,
1271
- broadScanAvoided: Boolean(sc && sc.tokenDiscipline && sc.tokenDiscipline.avoidedBroadRediscovery),
1272
- hugeJsonDumpAvoided: Boolean(sc && sc.tokenDiscipline && sc.tokenDiscipline.avoidedJsonDump),
1273
- manualStepsAvoided: steps.count,
1274
- manualStepsDetail: steps.details,
1275
- timeSavedEstimateMinutesLow: steps.count * MINUTES_PER_MANUAL_STEP_LOW,
1276
- timeSavedEstimateMinutesHigh: Math.min(steps.count * MINUTES_PER_MANUAL_STEP_HIGH, MINUTES_CAP),
1277
- costAvoidedEstimate: null,
1278
- costNote: "Cost avoided requires a local token pricing source. Not available.",
1279
- estimateBasis: "heuristic (manual steps × 1–3 min, token estimates from source char lengths)",
1280
- confidence: steps.count >= 5 ? "medium" : "low",
1281
- };
1282
-
1283
- const routingQuality = {
1284
- recommendedCapabilityPack: capabilityRec ? capabilityRec.recommendedPack : null,
1285
- additionalPacks: capabilityRec ? capabilityRec.additionalPacks : [],
1286
- capabilityAutoRecommended: Boolean(capabilityRec && capabilityRec.recommendedPack),
1287
- wrongCapabilityRisk: Boolean(capabilityRec && capabilityRec.wrongCapabilityRisk),
1288
- nextActionQuality: readiness.checks.nextActionAvailable ? "available" : "missing",
1289
- confidence: capabilityRec ? "medium" : "unavailable",
1290
- };
1291
-
1292
- const highRiskItems = intake && intake.summary ? intake.summary.highRiskItems || 0 : 0;
1293
- const critRiskItems = intake && intake.summary ? intake.summary.criticalRiskItems || 0 : 0;
1294
- const safePathDecision = safePath && safePath.safePathDecision ? safePath.safePathDecision : null;
1295
-
1296
- const securityRoutingEffectiveness = {
1297
- highRiskAssets: reg && reg.summary ? reg.summary.highRiskAssets || 0 : null,
1298
- riskyAssetsRouted: Boolean(safePathDecision && safePathDecision !== "allow_as_is"),
1299
- risksBlocked: safePathDecision === "block" ? 1 : 0,
1300
- risksRouted: (safePathDecision === "approval_required" || safePathDecision === "recommend_reduced_scope" || safePathDecision === "warn_with_boundary") ? 1 : 0,
1301
- unknownToolOrMcpDetected: intake && intake.summary ? intake.summary.unknownItems > 0 : null,
1302
- safePathRecommended: Boolean(safePathDecision && safePathDecision !== "allow_as_is"),
1303
- riskAvoidedSummary: intake && intake.summary
1304
- ? `${highRiskItems + critRiskItems} high/critical-risk items scanned, ${safePathDecision ? safePathDecision.replace(/_/g, " ") : "no safe-path receipt"}`
1305
- : "Install intake not yet run.",
1306
- confidence: receipts.installIntake.present ? "high" : "unavailable",
1307
- };
1308
-
1309
- const clarityEff = {
1310
- nextActionPresent: readiness.checks.nextActionAvailable,
1311
- doNotRepeatCount: cards.clarity.doNotRepeatCount,
1312
- relevantCommandsCount: cards.clarity.relevantCommandsCount,
1313
- targetHandoffPrepared: readiness.checks.targetHandoffPrepared,
1314
- proofAvailable: receipts.proof.present,
1315
- };
1316
-
1317
- const seamlessnessEff = {
1318
- userDidNotChooseCapability: cards.seamlessness.userDidNotChooseCapability,
1319
- oneCommandToContinue: Boolean(sc && sc.sessionStart && sc.sessionStart.nextSafestAction),
1320
- autoHandledFindings: cards.seamlessness.autoHandledFindings,
1321
- userActionRequiredFindings: cards.seamlessness.userActionRequiredFindings,
1322
- seamlessnessScore: cards.seamlessness.seamlessnessScore,
1323
- };
1324
-
1325
- const primaryValue = {
1326
- timeSaved: { headline: cards.timeSaved.headline, status: cards.timeSaved.status, userFacingSentence: cards.timeSaved.userFacingSentence },
1327
- costOrTokensSaved: { headline: cards.costOrTokensSaved.headline, status: cards.costOrTokensSaved.status, userFacingSentence: cards.costOrTokensSaved.userFacingSentence },
1328
- securityRiskAvoided: { headline: cards.securityRiskAvoided.headline, status: cards.securityRiskAvoided.status, userFacingSentence: cards.securityRiskAvoided.userFacingSentence },
1329
- };
1330
-
1331
- // Source receipt summary (no raw content — paths only)
1332
- const sourceReceipts = {
1333
- workControl: { present: receipts.workControl.present, path: WORK_CONTROL_REL, ageMs: receipts.workControl.present ? receipts.workControl.ageMs : null },
1334
- sessionContext: { present: receipts.sessionContext.present, path: SESSION_CONTEXT_REL, ageMs: receipts.sessionContext.present ? receipts.sessionContext.ageMs : null },
1335
- brainPack: { present: receipts.brainPack.present, path: BRAIN_PACK_REL, ageMs: receipts.brainPack.present ? receipts.brainPack.ageMs : null },
1336
- workspaceRegistry: { present: receipts.workspaceRegistry.present, path: WORKSPACE_REGISTRY_REL, ageMs: receipts.workspaceRegistry.present ? receipts.workspaceRegistry.ageMs : null },
1337
- capabilityRecommendation: { present: Boolean(capabilityRec), path: null },
1338
- installIntake: { present: receipts.installIntake.present, path: INSTALL_INTAKE_REL, ageMs: receipts.installIntake.present ? receipts.installIntake.ageMs : null },
1339
- safePath: { present: receipts.safePath.present, path: SAFE_PATH_REL, ageMs: receipts.safePath.present ? receipts.safePath.ageMs : null },
1340
- proof: { present: receipts.proof.present, path: PROOF_REL, ageMs: receipts.proof.present ? receipts.proof.ageMs : null },
1341
- };
1342
-
1343
- return {
1344
- schemaVersion: OPERATING_VALUE_SCHEMA_VERSION,
1345
- contract: OPERATING_VALUE_CONTRACT,
1346
- valueId,
1347
- createdAt,
1348
- cwd,
1349
- sourceReceipts,
1350
- primaryValue,
1351
- valueCards: cards,
1352
- operatingLoopReadiness: readiness,
1353
- optimizationEffectiveness,
1354
- routingQuality,
1355
- securityRoutingEffectiveness,
1356
- clarityEffectiveness: clarityEff,
1357
- seamlessness: seamlessnessEff,
1358
- opportunityFindings: findings,
1359
- sessionValueMoments: moments,
1360
- coach,
1361
- impactValidation,
1362
- dashboardReady,
1363
- willingnessToPaySignals,
1364
- valueProofs: calibration.proofs,
1365
- calibrationReport: calibration.calibrationReport,
1366
- productLearning: {
1367
- eventsWritten: [],
1368
- suggestedEvents: [
1369
- "operating_value_generated",
1370
- "value_proof_calibrated",
1371
- calibration.calibrationReport.overclaimRisks.length > 0 ? "value_claim_overclaim_risk_detected" : null,
1372
- ].filter(Boolean),
1373
- },
1374
- redacted: true,
1375
- };
1376
- }
1377
-
1378
- // ── Write / read functions ────────────────────────────────────────────────────
1379
-
1380
- function writeOperatingValue(cwd, value) {
1381
- const dir = path.join(cwd, OPERATING_VALUE_DIR_REL);
1382
- const histDir = path.join(cwd, OPERATING_VALUE_HISTORY_DIR_REL);
1383
- fs.mkdirSync(dir, { recursive: true });
1384
- fs.mkdirSync(histDir, { recursive: true });
1385
-
1386
- const latestAbs = path.join(cwd, OPERATING_VALUE_LATEST_REL);
1387
- fs.writeFileSync(latestAbs, JSON.stringify(value, null, 2), "utf8");
1388
-
1389
- const histAbs = path.join(histDir, `${value.valueId}.json`);
1390
- fs.writeFileSync(histAbs, JSON.stringify(value, null, 2), "utf8");
1391
-
1392
- // Write summary markdown
1393
- const summaryAbs = path.join(cwd, OPERATING_VALUE_SUMMARY_REL);
1394
- fs.writeFileSync(summaryAbs, buildOperatingValueSummaryMarkdown(value), "utf8");
1395
-
1396
- // Append event
1397
- try {
1398
- const { appendProductLearningEvent } = require("./product-learning-events");
1399
- appendProductLearningEvent(cwd, {
1400
- eventName: "operating_value_generated",
1401
- category: "operating_value",
1402
- payload: {
1403
- readinessScore: value.operatingLoopReadiness.score,
1404
- readinessBand: value.operatingLoopReadiness.band,
1405
- manualStepsAvoided: value.optimizationEffectiveness.manualStepsAvoided,
1406
- tokenReductionEstimate: value.optimizationEffectiveness.tokenReductionEstimate,
1407
- impactValidationVerdict: value.impactValidation.verdict,
1408
- confidence: value.optimizationEffectiveness.confidence,
1409
- opportunityCount: value.opportunityFindings.length,
1410
- },
1411
- });
1412
- if (value.calibrationReport) {
1413
- appendProductLearningEvent(cwd, {
1414
- eventName: "value_proof_calibrated",
1415
- category: "operating_value",
1416
- payload: {
1417
- overallVerdict: value.calibrationReport.overallVerdict,
1418
- measuredCount: value.calibrationReport.measuredCount,
1419
- estimatedCount: value.calibrationReport.estimatedCount,
1420
- heuristicCount: value.calibrationReport.heuristicCount,
1421
- unavailableCount: value.calibrationReport.unavailableCount,
1422
- overclaimRiskCount: value.calibrationReport.overclaimRisks.length,
1423
- },
1424
- });
1425
- }
1426
- } catch {}
1427
-
1428
- return {
1429
- valuePath: OPERATING_VALUE_LATEST_REL,
1430
- summaryPath: OPERATING_VALUE_SUMMARY_REL,
1431
- historyPath: path.posix.join(OPERATING_VALUE_HISTORY_DIR_REL.replace(/\\/g, "/"), `${value.valueId}.json`),
1432
- };
1433
- }
1434
-
1435
- function readLatestOperatingValue(cwd) {
1436
- const abs = path.join(cwd, OPERATING_VALUE_LATEST_REL);
1437
- return safeReadJson(abs);
1438
- }
1439
-
1440
- // ── Surface for dashboard integration ────────────────────────────────────────
1441
-
1442
- function buildOperatingValueSurface(cwd) {
1443
- try {
1444
- const latest = readLatestOperatingValue(cwd);
1445
- if (!latest) {
1446
- return { status: "missing", hero: null, latestValuePath: null };
1447
- }
1448
- const dr = latest.dashboardReady;
1449
- return {
1450
- status: "available",
1451
- latestValuePath: OPERATING_VALUE_LATEST_REL,
1452
- hero: dr ? dr.hero : null,
1453
- timeSaved: latest.valueCards ? latest.valueCards.timeSaved : null,
1454
- costOrTokensSaved: latest.valueCards ? latest.valueCards.costOrTokensSaved : null,
1455
- securityRiskAvoided: latest.valueCards ? latest.valueCards.securityRiskAvoided : null,
1456
- clarity: latest.valueCards ? latest.valueCards.clarity : null,
1457
- seamlessness: latest.valueCards ? latest.valueCards.seamlessness : null,
1458
- readinessScore: latest.operatingLoopReadiness ? latest.operatingLoopReadiness.score : null,
1459
- readinessBand: latest.operatingLoopReadiness ? latest.operatingLoopReadiness.band : null,
1460
- nextAction: dr ? dr.nextAction : null,
1461
- localDashboardPath: dr ? dr.localDashboardPath : null,
1462
- shouldShowInSession: dr ? dr.shouldShowInSession : false,
1463
- shouldShowDashboard: dr ? dr.shouldShowDashboard : false,
1464
- calibrationVerdict: dr ? dr.calibrationVerdict : null,
1465
- calibrationReport: latest.calibrationReport || null,
1466
- createdAt: latest.createdAt,
1467
- };
1468
- } catch {
1469
- return { status: "error", hero: null, latestValuePath: null };
1470
- }
1471
- }
1472
-
1473
- // ── Text formatters ───────────────────────────────────────────────────────────
1474
-
1475
- function buildOperatingValueSummaryMarkdown(value) {
1476
- const dr = value.dashboardReady;
1477
- const readiness = value.operatingLoopReadiness;
1478
- const coach = value.coach;
1479
- const validation = value.impactValidation;
1480
- const findings = value.opportunityFindings || [];
1481
- const actionFindings = findings.filter((f) => f.needsUserAction);
1482
-
1483
- const lines = [
1484
- `# Avorelo Operating Value Summary`,
1485
- `_${value.createdAt}_`,
1486
- ``,
1487
- `## Hero`,
1488
- `**${dr ? dr.hero : "Operating surfaces ready."}**`,
1489
- ``,
1490
- `## Readiness: ${readiness.bandLabel} (${readiness.score}/100)`,
1491
- readiness.nextAction,
1492
- ``,
1493
- `## Primary Value`,
1494
- `- **Time Saved:** ${value.valueCards.timeSaved.headline} — ${value.valueCards.timeSaved.userFacingSentence}`,
1495
- `- **Context/Tokens:** ${value.valueCards.costOrTokensSaved.headline} — ${value.valueCards.costOrTokensSaved.userFacingSentence}`,
1496
- `- **Security:** ${value.valueCards.securityRiskAvoided.headline} — ${value.valueCards.securityRiskAvoided.userFacingSentence}`,
1497
- ``,
1498
- `## Coach`,
1499
- `**Finding:** ${coach.finding}`,
1500
- `**Expected value:** ${coach.expectedValue}`,
1501
- `**Recommended action:** ${coach.recommendedAction}`,
1502
- ``,
1503
- `## Impact Validation`,
1504
- `Verdict: **${validation.verdict}** (confidence: ${validation.confidence})`,
1505
- validation.tokenReduction ? `Token reduction: ~${validation.tokenReduction.toLocaleString()} tokens (${validation.tokenReductionPercent || "?"}%)` : "Token data insufficient for comparison.",
1506
- `_${validation.caveat}_`,
1507
- ``,
1508
- actionFindings.length > 0 ? [
1509
- `## Action Needed (${actionFindings.length})`,
1510
- ...actionFindings.slice(0, 3).map((f) => `- [${f.severity.toUpperCase()}] ${f.plainEnglish} → ${f.recommendedAction}`),
1511
- ].join("\n") : `## All Clear`,
1512
- actionFindings.length === 0 ? "No user action needed. All findings handled automatically." : "",
1513
- ``,
1514
- (() => {
1515
- const cr = value.calibrationReport;
1516
- if (!cr) return null;
1517
- const lines = [
1518
- `## Calibration`,
1519
- `Verdict: **${cr.overallVerdict}** (measured: ${cr.measuredCount}, estimated: ${cr.estimatedCount}, heuristic: ${cr.heuristicCount}, unavailable: ${cr.unavailableCount})`,
1520
- cr.strongestClaims.length ? `Strongest: ${cr.strongestClaims.slice(0, 2).join("; ")}` : null,
1521
- cr.weakestClaims.length ? `Weakest: ${cr.weakestClaims.slice(0, 2).join("; ")}` : null,
1522
- cr.overclaimRisks.length ? `Overclaim risks: ${cr.overclaimRisks.map((r) => r.valueId).join(", ")}` : null,
1523
- ``,
1524
- `## Safe Copy Candidates`,
1525
- cr.recommendedCopySafe && cr.recommendedCopySafe.length
1526
- ? cr.recommendedCopySafe.map((s) => `- ${s}`).join("\n")
1527
- : "- None ready yet — run more Avorelo surfaces to generate measured or estimated claims.",
1528
- ``,
1529
- `## Blocked Copy`,
1530
- cr.blockedCopy && cr.blockedCopy.length
1531
- ? cr.blockedCopy.map((s) => `- BLOCKED: ${s}`).join("\n")
1532
- : "- No specific blocked copy identified.",
1533
- ].filter((l) => l !== null);
1534
- return lines.join("\n");
1535
- })(),
1536
- ``,
1537
- `_Run \`avorelo operating-value --json\` for the full data contract._`,
1538
- ].filter((l) => l !== undefined && l !== null);
1539
-
1540
- return lines.join("\n") + "\n";
1541
- }
1542
-
1543
- function formatOperatingValueText(value, options = {}) {
1544
- if (options.momentsOnly) {
1545
- const moments = value.sessionValueMoments || [];
1546
- if (!moments.length) return "No in-session value moments generated.\n";
1547
- return moments
1548
- .filter((m) => !m.suppressIfLowValue || options.showAll)
1549
- .map((m) => `[${m.moment.toUpperCase()}] ${m.oneLine}${m.nextAction ? `\n → ${m.nextAction}` : ""}`)
1550
- .join("\n") + "\n";
1551
- }
1552
-
1553
- if (options.validateOnly) {
1554
- const v = value.impactValidation;
1555
- const cr = value.calibrationReport;
1556
- const lines = [
1557
- `Impact Validation: ${v.verdict.toUpperCase()} (confidence: ${v.confidence})`,
1558
- v.tokenReduction ? `Token reduction: ~${v.tokenReduction.toLocaleString()} tokens (${v.tokenReductionPercent || "?"}%)` : "Token comparison unavailable.",
1559
- `Before: ~${v.before.rawContextEstimateTokens || "?"} raw candidate tokens`,
1560
- `After: ~${v.after.compactHandoffTokens || "?"} compact tokens`,
1561
- v.after.broadScanAvoided ? "Broad scan: avoided" : "Broad scan: not detected as avoided",
1562
- v.after.nextActionPresent ? "Next action: present" : "Next action: missing",
1563
- `Caveat: ${v.caveat}`,
1564
- cr ? "" : null,
1565
- cr ? `Calibration Verdict: ${cr.overallVerdict}` : null,
1566
- cr && cr.strongestClaims.length ? `Strongest: ${cr.strongestClaims.slice(0, 2).join("; ")}` : null,
1567
- cr && cr.weakestClaims.length ? `Weakest: ${cr.weakestClaims.slice(0, 2).join("; ")}` : null,
1568
- cr && cr.overclaimRisks.length ? `Overclaim risks: ${cr.overclaimRisks.map((r) => r.valueId).join(", ")}` : null,
1569
- ].filter((l) => l !== null);
1570
- return lines.join("\n") + "\n";
1571
- }
1572
-
1573
- const dr = value.dashboardReady;
1574
- const readiness = value.operatingLoopReadiness;
1575
- const coach = value.coach;
1576
-
1577
- const timeSavedLabel = confidenceLabel(value.valueCards.timeSaved.estimateBasis && value.valueCards.timeSaved.estimateBasis.startsWith("heuristic") ? "heuristic" : "estimated", value.valueCards.timeSaved.confidence);
1578
- const tokensLabel = confidenceLabel(value.valueCards.costOrTokensSaved.confidence === "low" ? "estimated" : "estimated", value.valueCards.costOrTokensSaved.confidence);
1579
- const securityLabel = value.valueCards.securityRiskAvoided.confidence === "high" ? "measured" : null;
1580
- const calibVerdict = value.calibrationReport ? value.calibrationReport.overallVerdict : null;
1581
- const costCard = value.valueCards.costOrTokensSaved;
1582
- const costNote = costCard.costAvoidedEstimate !== null
1583
- ? ` · ${costCard.costNote}`
1584
- : null;
1585
-
1586
- // Build token method label for Tokens/Cost line
1587
- let tokenMethodLabel = null;
1588
- try {
1589
- const { readTokenEvidence } = require("./token-evidence");
1590
- const te = readTokenEvidence(value.cwd || process.cwd());
1591
- if (te && te.tokenizer) {
1592
- const m = te.tokenizer.method;
1593
- if (m === "provider_usage") {
1594
- tokenMethodLabel = "measured from local provider usage";
1595
- } else if (m === "local_tokenizer") {
1596
- tokenMethodLabel = "estimated with local tokenizer";
1597
- } else if (m && m.includes("chars_div_4")) {
1598
- tokenMethodLabel = "estimated from chars/4";
1599
- }
1600
- }
1601
- } catch { /* non-blocking */ }
1602
-
1603
- const tokensLine = tokenMethodLabel
1604
- ? ` Tokens/Cost: ${costCard.headline} (${tokenMethodLabel})${costNote || ""}`
1605
- : ` Tokens/Cost: ${costCard.headline}${tokensLabel ? ` (${tokensLabel})` : ""}${costNote || ""}`;
1606
-
1607
- return [
1608
- `Avorelo Operating Value`,
1609
- ``,
1610
- ` ${dr ? dr.hero : "Surfaces ready."}`,
1611
- ``,
1612
- ` Readiness: ${readiness.bandLabel} (${readiness.score}/100)`,
1613
- ``,
1614
- ` Time Saved: ${value.valueCards.timeSaved.headline}${timeSavedLabel ? ` (${timeSavedLabel})` : ""}`,
1615
- tokensLine,
1616
- ` Security: ${value.valueCards.securityRiskAvoided.headline}${securityLabel ? ` (${securityLabel})` : ""}`,
1617
- calibVerdict && calibVerdict !== "safe_to_show" ? ` Calibration: ${calibVerdict.replace(/_/g, " ")}` : null,
1618
- ``,
1619
- coach.finding ? ` Action: ${coach.recommendedAction}` : null,
1620
- ``,
1621
- ` Evidence: ${dr ? dr.evidenceLine : "—"}`,
1622
- dr && dr.localDashboardPath ? ` Dashboard: ${dr.localDashboardPath}` : null,
1623
- ` Full data: avorelo operating-value --json`,
1624
- ``,
1625
- ].filter((l) => l !== null).join("\n");
1626
- }
1627
-
1628
- // ── Exports ───────────────────────────────────────────────────────────────────
1629
-
1630
- module.exports = {
1631
- OPERATING_VALUE_CONTRACT,
1632
- OPERATING_VALUE_SCHEMA_VERSION,
1633
- OPERATING_VALUE_LATEST_REL,
1634
- OPERATING_VALUE_SUMMARY_REL,
1635
- OPERATING_VALUE_DIR_REL,
1636
- OPERATING_VALUE_DASHBOARD_PREVIEW_REL,
1637
- buildOperatingValue,
1638
- writeOperatingValue,
1639
- readLatestOperatingValue,
1640
- buildOperatingValueSurface,
1641
- buildOperatingValueSummaryMarkdown,
1642
- formatOperatingValueText,
1643
- filterUserFacingValueCards,
1644
- buildSafeCopyCandidates,
1645
- buildBlockedCopyCandidates,
1646
- formatCaveatLine,
1647
- formatEvidenceLine,
1648
- };