avorelo 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (260) hide show
  1. package/LICENSE +23 -16
  2. package/README.md +91 -51
  3. package/bin/avorelo.mjs +7 -0
  4. package/dist/avorelo.mjs +14337 -0
  5. package/package.json +106 -120
  6. package/bin/avorelo +0 -9
  7. package/scripts/README.md +0 -40
  8. package/scripts/cco-dashboard.js +0 -252
  9. package/scripts/cco-status.js +0 -430
  10. package/scripts/lib/activation/account-state.js +0 -37
  11. package/scripts/lib/activation/activation-runner.js +0 -546
  12. package/scripts/lib/activation/activation-self-healing.js +0 -480
  13. package/scripts/lib/activation/activation-state.js +0 -83
  14. package/scripts/lib/activation/activation-summary.js +0 -191
  15. package/scripts/lib/activation/adapters/claude-code.js +0 -77
  16. package/scripts/lib/activation/adapters/codex-cli.js +0 -52
  17. package/scripts/lib/activation/adapters/cursor.js +0 -37
  18. package/scripts/lib/activation/adapters/github-agent.js +0 -39
  19. package/scripts/lib/activation/adapters/terminal.js +0 -42
  20. package/scripts/lib/activation/adapters/vscode.js +0 -39
  21. package/scripts/lib/activation/adapters/windsurf.js +0 -37
  22. package/scripts/lib/activation/ai-surface-detector.js +0 -151
  23. package/scripts/lib/activation/connect-account.js +0 -145
  24. package/scripts/lib/activation/detect-environment.js +0 -75
  25. package/scripts/lib/activation/detect-hosts.js +0 -62
  26. package/scripts/lib/activation/format-activation-output.js +0 -109
  27. package/scripts/lib/activation/next-action.js +0 -43
  28. package/scripts/lib/activation/repair-engine.js +0 -219
  29. package/scripts/lib/activation-distribution-readiness.js +0 -507
  30. package/scripts/lib/adapter-conformance.js +0 -176
  31. package/scripts/lib/adapter-readiness.js +0 -417
  32. package/scripts/lib/adapter-safety-boundaries.js +0 -335
  33. package/scripts/lib/adapter-technical-readiness-gate.js +0 -205
  34. package/scripts/lib/agent-access-governance.js +0 -455
  35. package/scripts/lib/agent-enforcement.js +0 -765
  36. package/scripts/lib/agent-policy-profile.js +0 -210
  37. package/scripts/lib/agent-security/action-evaluator.js +0 -507
  38. package/scripts/lib/agent-security/adapter-registry.js +0 -98
  39. package/scripts/lib/agent-security/auto-policy.js +0 -139
  40. package/scripts/lib/agent-security/bounded-scan.js +0 -93
  41. package/scripts/lib/agent-security/enforcement-adapter.js +0 -174
  42. package/scripts/lib/agent-security/enforcement-engine.js +0 -1129
  43. package/scripts/lib/agent-security/file-write-adapter.js +0 -183
  44. package/scripts/lib/agent-security/file-write-rules.js +0 -178
  45. package/scripts/lib/agent-security/index.js +0 -3342
  46. package/scripts/lib/agent-security/instruction-risk.js +0 -181
  47. package/scripts/lib/agent-security/mcp-action-adapter.js +0 -185
  48. package/scripts/lib/agent-security/mcp-action-rules.js +0 -184
  49. package/scripts/lib/agent-security/package-action-adapter.js +0 -175
  50. package/scripts/lib/agent-security/package-action-rules.js +0 -233
  51. package/scripts/lib/agent-security/performance.js +0 -148
  52. package/scripts/lib/agent-security/permission-minimizer.js +0 -403
  53. package/scripts/lib/agent-security/scan-cache.js +0 -74
  54. package/scripts/lib/agent-security/source-trust.js +0 -146
  55. package/scripts/lib/ai-install-prompt.js +0 -288
  56. package/scripts/lib/ai-workspace-hygiene.js +0 -1499
  57. package/scripts/lib/alpha-activation.js +0 -520
  58. package/scripts/lib/alpha-feedback.js +0 -263
  59. package/scripts/lib/alpha-readiness-gate.js +0 -332
  60. package/scripts/lib/anti-gaming.js +0 -169
  61. package/scripts/lib/artifact-health.js +0 -431
  62. package/scripts/lib/attribution.js +0 -180
  63. package/scripts/lib/audit.js +0 -289
  64. package/scripts/lib/avorelo-skill-registry.js +0 -810
  65. package/scripts/lib/batch-jobs.js +0 -71
  66. package/scripts/lib/brain-pack.js +0 -578
  67. package/scripts/lib/brand-boundary.js +0 -424
  68. package/scripts/lib/brand.js +0 -74
  69. package/scripts/lib/browser-capability.js +0 -1048
  70. package/scripts/lib/browser-proof-preflight.js +0 -321
  71. package/scripts/lib/cache-readiness.js +0 -187
  72. package/scripts/lib/canonical-reentry.js +0 -162
  73. package/scripts/lib/capability-packs.js +0 -314
  74. package/scripts/lib/capability-recommender.js +0 -512
  75. package/scripts/lib/capability-registry.js +0 -1059
  76. package/scripts/lib/carry-forward-surfacing.js +0 -194
  77. package/scripts/lib/ccusage-adapter.js +0 -188
  78. package/scripts/lib/company-loop.js +0 -1149
  79. package/scripts/lib/config.js +0 -637
  80. package/scripts/lib/context-acquisition-plan.js +0 -287
  81. package/scripts/lib/context-budget-guard.js +0 -170
  82. package/scripts/lib/context-budget-scanner.js +0 -257
  83. package/scripts/lib/context-optimizer.js +0 -715
  84. package/scripts/lib/context-reduction-plan.js +0 -178
  85. package/scripts/lib/context-safety.js +0 -88
  86. package/scripts/lib/context-savings-engine.js +0 -158
  87. package/scripts/lib/cost-evidence.js +0 -254
  88. package/scripts/lib/cross-host-install-plan.js +0 -308
  89. package/scripts/lib/cross-host-install-readiness.js +0 -237
  90. package/scripts/lib/cross-host-value-flow.js +0 -268
  91. package/scripts/lib/dashboard.js +0 -900
  92. package/scripts/lib/design-partner-feedback.js +0 -346
  93. package/scripts/lib/entitlements.js +0 -100
  94. package/scripts/lib/execution-packet.js +0 -559
  95. package/scripts/lib/experimentation-events.js +0 -547
  96. package/scripts/lib/external-capability-compliance.js +0 -107
  97. package/scripts/lib/external-user-simulation.js +0 -166
  98. package/scripts/lib/failure-recovery-readiness.js +0 -81
  99. package/scripts/lib/failure-recovery.js +0 -419
  100. package/scripts/lib/feedback-intelligence.js +0 -537
  101. package/scripts/lib/feedback-signals.js +0 -205
  102. package/scripts/lib/file-integrity.js +0 -68
  103. package/scripts/lib/fsx.js +0 -127
  104. package/scripts/lib/full-readiness-gate.js +0 -451
  105. package/scripts/lib/guidance-builder.js +0 -174
  106. package/scripts/lib/hook-apply.js +0 -1019
  107. package/scripts/lib/hook-baseline.js +0 -310
  108. package/scripts/lib/hook-config-preview.js +0 -275
  109. package/scripts/lib/hook-contracts.js +0 -290
  110. package/scripts/lib/hook-safety-boundary-readiness.js +0 -80
  111. package/scripts/lib/host-capability-matrix.js +0 -351
  112. package/scripts/lib/host-support-context.js +0 -254
  113. package/scripts/lib/http-hook-action.js +0 -538
  114. package/scripts/lib/install-ai-readiness.js +0 -84
  115. package/scripts/lib/install-intake-risk.js +0 -1037
  116. package/scripts/lib/install-journey-intelligence.js +0 -329
  117. package/scripts/lib/intervention-guidance.js +0 -57
  118. package/scripts/lib/known-limitations.js +0 -115
  119. package/scripts/lib/l8-path-truth.js +0 -146
  120. package/scripts/lib/launch-hardening-gate.js +0 -436
  121. package/scripts/lib/launch-readiness.js +0 -628
  122. package/scripts/lib/learning-memory.js +0 -686
  123. package/scripts/lib/lifecycle-hooks.js +0 -802
  124. package/scripts/lib/local-package-smoke.js +0 -423
  125. package/scripts/lib/local-pricing.js +0 -299
  126. package/scripts/lib/mcp-enforcement.js +0 -311
  127. package/scripts/lib/mcp-least-privilege-policy.js +0 -303
  128. package/scripts/lib/mcp-tool-inventory.js +0 -388
  129. package/scripts/lib/mcp-tool-risk.js +0 -0
  130. package/scripts/lib/memory.js +0 -335
  131. package/scripts/lib/metrics.js +0 -699
  132. package/scripts/lib/micro-proof.js +0 -133
  133. package/scripts/lib/next-run-context.js +0 -436
  134. package/scripts/lib/operating-value.js +0 -1648
  135. package/scripts/lib/optimization-v3.js +0 -122
  136. package/scripts/lib/orchestration/adapters/_shared.js +0 -49
  137. package/scripts/lib/orchestration/adapters/aider.js +0 -18
  138. package/scripts/lib/orchestration/adapters/claude-code.js +0 -35
  139. package/scripts/lib/orchestration/adapters/codex.js +0 -35
  140. package/scripts/lib/orchestration/adapters/gemini-cli.js +0 -18
  141. package/scripts/lib/orchestration/adapters/git.js +0 -25
  142. package/scripts/lib/orchestration/adapters/index.js +0 -31
  143. package/scripts/lib/orchestration/adapters/lm-studio.js +0 -18
  144. package/scripts/lib/orchestration/adapters/ollama.js +0 -18
  145. package/scripts/lib/orchestration/adapters/opencode.js +0 -18
  146. package/scripts/lib/orchestration/adapters/openrouter.js +0 -18
  147. package/scripts/lib/orchestration/adapters/test-runner.js +0 -25
  148. package/scripts/lib/orchestration/cli.js +0 -438
  149. package/scripts/lib/orchestration/execution-manager.js +0 -279
  150. package/scripts/lib/orchestration/handoff.js +0 -314
  151. package/scripts/lib/orchestration/index.js +0 -456
  152. package/scripts/lib/orchestration/inventory.js +0 -47
  153. package/scripts/lib/orchestration/model-discovery.js +0 -498
  154. package/scripts/lib/orchestration/model-profiler.js +0 -170
  155. package/scripts/lib/orchestration/model-profiles.js +0 -252
  156. package/scripts/lib/orchestration/model-refresh-policy.js +0 -72
  157. package/scripts/lib/orchestration/proof-writer.js +0 -349
  158. package/scripts/lib/orchestration/provider-discovery/aider.js +0 -49
  159. package/scripts/lib/orchestration/provider-discovery/claude-code.js +0 -56
  160. package/scripts/lib/orchestration/provider-discovery/codex.js +0 -49
  161. package/scripts/lib/orchestration/provider-discovery/common.js +0 -186
  162. package/scripts/lib/orchestration/provider-discovery/gemini.js +0 -106
  163. package/scripts/lib/orchestration/provider-discovery/lm-studio.js +0 -118
  164. package/scripts/lib/orchestration/provider-discovery/models-dev.js +0 -12
  165. package/scripts/lib/orchestration/provider-discovery/ollama.js +0 -100
  166. package/scripts/lib/orchestration/provider-discovery/opencode.js +0 -47
  167. package/scripts/lib/orchestration/provider-discovery/openrouter.js +0 -44
  168. package/scripts/lib/orchestration/risk-classifier.js +0 -130
  169. package/scripts/lib/orchestration/routing-policy.js +0 -486
  170. package/scripts/lib/orchestration/settings.js +0 -112
  171. package/scripts/lib/orchestration/state.js +0 -165
  172. package/scripts/lib/orchestration/verification-manager.js +0 -138
  173. package/scripts/lib/output-profiles.js +0 -146
  174. package/scripts/lib/package-content-audit.js +0 -368
  175. package/scripts/lib/package-runtime.js +0 -278
  176. package/scripts/lib/plan-surface.js +0 -53
  177. package/scripts/lib/plans.js +0 -2318
  178. package/scripts/lib/policy-provider.js +0 -27
  179. package/scripts/lib/prelaunch-activation-readiness.js +0 -409
  180. package/scripts/lib/prelaunch-evidence-store.js +0 -816
  181. package/scripts/lib/prelaunch-intelligence.js +0 -869
  182. package/scripts/lib/pricing-experiment.js +0 -118
  183. package/scripts/lib/pro-moment-events.js +0 -77
  184. package/scripts/lib/pro-moment-state.js +0 -227
  185. package/scripts/lib/pro-moments.js +0 -1216
  186. package/scripts/lib/product-learning-events.js +0 -629
  187. package/scripts/lib/project-profile.js +0 -555
  188. package/scripts/lib/prompt-compiler.js +0 -280
  189. package/scripts/lib/prompt-lint.js +0 -32
  190. package/scripts/lib/prompt-suggestions.js +0 -52
  191. package/scripts/lib/proof-canonical.js +0 -398
  192. package/scripts/lib/proof-drilldown.js +0 -383
  193. package/scripts/lib/proof-events.js +0 -342
  194. package/scripts/lib/proof-history.js +0 -243
  195. package/scripts/lib/proof-metrics.js +0 -296
  196. package/scripts/lib/proof-outcome-evidence.js +0 -134
  197. package/scripts/lib/proof-receipt.js +0 -335
  198. package/scripts/lib/proof-record.js +0 -461
  199. package/scripts/lib/public-activation-distribution-gate.js +0 -258
  200. package/scripts/lib/public-cli.js +0 -3891
  201. package/scripts/lib/public-distribution-truth.js +0 -211
  202. package/scripts/lib/public-install-claim-checker.js +0 -294
  203. package/scripts/lib/publish-provenance-readiness.js +0 -283
  204. package/scripts/lib/readiness-delta.js +0 -218
  205. package/scripts/lib/readiness-evidence-closure.js +0 -196
  206. package/scripts/lib/reentry-memory-capture.js +0 -241
  207. package/scripts/lib/reentry-memory-retrieval.js +0 -302
  208. package/scripts/lib/reentry-memory-status.js +0 -146
  209. package/scripts/lib/reentry-memory-store.js +0 -178
  210. package/scripts/lib/reentry-state.js +0 -66
  211. package/scripts/lib/release-candidate-bundle.js +0 -166
  212. package/scripts/lib/remediation.js +0 -81
  213. package/scripts/lib/repo-map.js +0 -391
  214. package/scripts/lib/run-improvements-lifecycle.js +0 -330
  215. package/scripts/lib/run-improvements.js +0 -789
  216. package/scripts/lib/runtime-decision-policy.js +0 -387
  217. package/scripts/lib/safe-path-engine.js +0 -705
  218. package/scripts/lib/safe-run-controller.js +0 -887
  219. package/scripts/lib/score.js +0 -262
  220. package/scripts/lib/seamless-enforcement.js +0 -329
  221. package/scripts/lib/seamless-outcome.js +0 -689
  222. package/scripts/lib/seamless-reality-gate.js +0 -5043
  223. package/scripts/lib/security-risk-classifier.js +0 -511
  224. package/scripts/lib/security-scan.js +0 -384
  225. package/scripts/lib/session-context-optimizer.js +0 -1211
  226. package/scripts/lib/session-timing.js +0 -315
  227. package/scripts/lib/skill-hygiene.js +0 -805
  228. package/scripts/lib/skill-packs.js +0 -161
  229. package/scripts/lib/skills-operating-layer.js +0 -580
  230. package/scripts/lib/smart-work-routing.js +0 -768
  231. package/scripts/lib/source-catalog.js +0 -700
  232. package/scripts/lib/status-value-summary.js +0 -32
  233. package/scripts/lib/support-bundle.js +0 -578
  234. package/scripts/lib/task-continuation.js +0 -440
  235. package/scripts/lib/test-helpers.js +0 -15
  236. package/scripts/lib/tier.js +0 -38
  237. package/scripts/lib/token-context-quality-gate.js +0 -370
  238. package/scripts/lib/token-cost-capture.js +0 -187
  239. package/scripts/lib/token-cost-intelligence.js +0 -358
  240. package/scripts/lib/token-efficiency-evidence.js +0 -213
  241. package/scripts/lib/token-evidence.js +0 -699
  242. package/scripts/lib/tokenish.js +0 -17
  243. package/scripts/lib/tool-output-sandbox.js +0 -304
  244. package/scripts/lib/trust-audit.js +0 -136
  245. package/scripts/lib/unified-events.js +0 -396
  246. package/scripts/lib/upgrade-interruption-recovery.js +0 -407
  247. package/scripts/lib/usage-ledger.js +0 -201
  248. package/scripts/lib/value-ledger.js +0 -130
  249. package/scripts/lib/value-proof-calibration.js +0 -531
  250. package/scripts/lib/visual-qa.js +0 -231
  251. package/scripts/lib/voice-alpha.js +0 -29
  252. package/scripts/lib/work-aware-orchestration.js +0 -976
  253. package/scripts/lib/work-control-receipts.js +0 -577
  254. package/scripts/lib/work-ledger.js +0 -1123
  255. package/scripts/lib/work-panel-preview.js +0 -352
  256. package/scripts/lib/workflow-discipline.js +0 -280
  257. package/scripts/lib/workflow-signals.js +0 -419
  258. package/scripts/lib/workspace-map.js +0 -281
  259. package/scripts/lib/workspace-registry.js +0 -1367
  260. package/scripts/lib/workspace-resolver.js +0 -480
@@ -1,407 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- /**
4
- * upgrade-interruption-recovery
5
- * Detects and recovers from interrupted upgrade/setup states
6
- * Bounded scope: handles "initialized but not completed" pattern only
7
- */
8
-
9
- const fs = require('fs');
10
- const path = require('path');
11
- const { safeReadJson, safeWriteJson, ensureCcoDirs } = require('./fsx');
12
-
13
- const ONBOARDING_FILE = '.claude/cco/state/onboarding.json';
14
- const CONFIG_FILE = '.claude/cco/config.json';
15
- const SEQUENCE_CHECKPOINT_FILE = '.claude/cco/state/sequence-checkpoint.json';
16
-
17
- const INIT_SEQUENCE_CHECKPOINTS = {
18
- START: 'init_start',
19
- DIRS_CREATED: 'dirs_created',
20
- CONFIG_WRITTEN: 'config_written',
21
- STATE_INITIALIZED: 'state_initialized',
22
- CONFIG_UPDATED: 'config_updated',
23
- COMPLETED: 'completed'
24
- };
25
-
26
- function safeWriteCheckpoint(cwd, checkpoint, meta = {}) {
27
- const checkpointData = {
28
- checkpoint,
29
- timestamp: new Date().toISOString(),
30
- sequence: 'init',
31
- meta
32
- };
33
- safeWriteJson(cwd, SEQUENCE_CHECKPOINT_FILE, checkpointData);
34
- }
35
-
36
- function safeClearCheckpoint(cwd) {
37
- const checkpointPath = path.join(cwd, SEQUENCE_CHECKPOINT_FILE);
38
- try {
39
- if (fs.existsSync(checkpointPath)) {
40
- fs.unlinkSync(checkpointPath);
41
- }
42
- } catch {
43
- // Ignore cleanup errors
44
- }
45
- }
46
-
47
- function readCheckpoint(cwd) {
48
- const checkpoint = safeReadJson(cwd, SEQUENCE_CHECKPOINT_FILE, null);
49
- if (!checkpoint || !checkpoint.checkpoint) return null;
50
- return checkpoint.checkpoint;
51
- }
52
-
53
- function getPendingSteps(lastCheckpoint) {
54
- const orderedSteps = [
55
- INIT_SEQUENCE_CHECKPOINTS.START,
56
- INIT_SEQUENCE_CHECKPOINTS.DIRS_CREATED,
57
- INIT_SEQUENCE_CHECKPOINTS.CONFIG_WRITTEN,
58
- INIT_SEQUENCE_CHECKPOINTS.STATE_INITIALIZED,
59
- INIT_SEQUENCE_CHECKPOINTS.CONFIG_UPDATED,
60
- INIT_SEQUENCE_CHECKPOINTS.COMPLETED
61
- ];
62
-
63
- if (!lastCheckpoint) {
64
- return orderedSteps;
65
- }
66
-
67
- const checkpointIndex = orderedSteps.indexOf(lastCheckpoint);
68
- if (checkpointIndex === -1) {
69
- // Unknown checkpoint, start from beginning
70
- return orderedSteps;
71
- }
72
-
73
- return orderedSteps.slice(checkpointIndex + 1);
74
- }
75
-
76
- /**
77
- * Validates consistency between onboarding state and checkpoint markers
78
- * @param {string} cwd - Current working directory
79
- * @returns {Object} Validation result
80
- */
81
- function validateMarkerConsistency(cwd) {
82
- const onboardingPath = path.join(cwd, ONBOARDING_FILE);
83
- const checkpointPath = path.join(cwd, SEQUENCE_CHECKPOINT_FILE);
84
-
85
- const onboardingExists = fs.existsSync(onboardingPath);
86
- const checkpointExists = fs.existsSync(checkpointPath);
87
-
88
- // Case 1: Checkpoint without onboarding state
89
- if (checkpointExists && !onboardingExists) {
90
- return {
91
- isConsistent: false,
92
- reason: 'checkpoint_without_state',
93
- action: 'clear_checkpoint',
94
- details: 'Checkpoint exists but onboarding state is missing'
95
- };
96
- }
97
-
98
- // Case 2: Completed onboarding with lingering checkpoint
99
- if (onboardingExists && checkpointExists) {
100
- try {
101
- const state = JSON.parse(fs.readFileSync(onboardingPath, 'utf8'));
102
- if (state.status === 'completed') {
103
- return {
104
- isConsistent: false,
105
- reason: 'completed_with_checkpoint',
106
- action: 'clear_checkpoint',
107
- details: 'Onboarding completed but checkpoint remains'
108
- };
109
- }
110
- } catch (err) {
111
- // If we can't read onboarding state, treat as inconsistent
112
- return {
113
- isConsistent: false,
114
- reason: 'unreadable_onboarding',
115
- action: 'clear_checkpoint',
116
- details: 'Cannot read onboarding state file'
117
- };
118
- }
119
- }
120
-
121
- return { isConsistent: true };
122
- }
123
-
124
- /**
125
- * Attempts to auto-repair inconsistent markers
126
- * @param {string} cwd - Current working directory
127
- * @returns {Object} Repair result
128
- */
129
- function autoRepairMarkers(cwd) {
130
- const validation = validateMarkerConsistency(cwd);
131
-
132
- if (!validation.isConsistent) {
133
- switch (validation.action) {
134
- case 'clear_checkpoint':
135
- safeClearCheckpoint(cwd);
136
- return {
137
- repaired: true,
138
- action: 'cleared_stale_checkpoint',
139
- reason: validation.reason,
140
- details: validation.details
141
- };
142
- }
143
- }
144
-
145
- return { repaired: false };
146
- }
147
-
148
- /**
149
- * Detection result type
150
- * @typedef {Object} InterruptionState
151
- * @property {boolean} isInterrupted - True if interrupted state detected
152
- * @property {string} interruptionType - Type of interruption
153
- * @property {Object} currentState - Current state values
154
- * @property {string} recommendedAction - Next action to take
155
- * @property {boolean} isSafeToAutoRecover - Whether auto-recovery is safe
156
- * @property {string} lastCheckpoint - Last successfully completed checkpoint
157
- * @property {Array<string>} pendingSteps - Steps that need to be completed
158
- */
159
-
160
- /**
161
- * Detects if system is in an interrupted upgrade/setup state
162
- * @param {string} cwd - Current working directory
163
- * @returns {InterruptionState} Detection result
164
- */
165
- function detectInterruptedState(cwd) {
166
- // Auto-repair any inconsistent markers before detection
167
- const repairResult = autoRepairMarkers(cwd);
168
- if (repairResult.repaired) {
169
- // Note: This goes to stderr to not interfere with JSON output
170
- console.error('[detect] Auto-repaired markers:', repairResult.reason);
171
- }
172
-
173
- const onboardingPath = path.join(cwd, ONBOARDING_FILE);
174
- const checkpoint = readCheckpoint(cwd);
175
-
176
- // Debug info to stderr
177
- console.error('[detect] Found checkpoint:', checkpoint);
178
-
179
- // Check if onboarding state file exists
180
- if (!fs.existsSync(onboardingPath)) {
181
- return {
182
- isInterrupted: false,
183
- interruptionType: 'not_started',
184
- currentState: null,
185
- lastCheckpoint: null,
186
- pendingSteps: getPendingSteps(null),
187
- recommendedAction: 'Run initial setup with: node scripts/cco-init.js',
188
- isSafeToAutoRecover: false
189
- };
190
- }
191
-
192
- const state = safeReadJson(cwd, ONBOARDING_FILE, null);
193
-
194
- // Onboarding state is authoritative - check its status first
195
- if (state && state.status === 'completed') {
196
- // Validate file integrity for completed state
197
- // If critical files are missing, downgrade to incomplete
198
- const configPath = path.join(cwd, CONFIG_FILE);
199
- if (!fs.existsSync(configPath)) {
200
- return {
201
- isInterrupted: true,
202
- interruptionType: 'missing_config',
203
- currentState: {
204
- status: state.status,
205
- hasConfigFile: false
206
- },
207
- lastCheckpoint: checkpoint,
208
- pendingSteps: checkpoint ? getPendingSteps(checkpoint) : [],
209
- recommendedAction: 'Missing critical files. Run: node scripts/cco-init.js to complete initialization',
210
- isSafeToAutoRecover: true
211
- };
212
- }
213
-
214
- // Should not have a checkpoint at this point (autoRepair would have cleared it)
215
- return {
216
- isInterrupted: false,
217
- interruptionType: 'completed',
218
- currentState: {
219
- status: state.status,
220
- stepsCompleted: state.stepsCompleted || []
221
- },
222
- lastCheckpoint: null,
223
- pendingSteps: [],
224
- recommendedAction: 'System is fully initialized. Run: node scripts/cco-status.js',
225
- isSafeToAutoRecover: false
226
- };
227
- }
228
-
229
- // Check for "initialized but not completed" pattern
230
- if (state && state.status === 'initialized' && state.stepsCompleted && state.stepsCompleted.length === 1) {
231
- const pending = getPendingSteps(checkpoint);
232
- return {
233
- isInterrupted: true,
234
- interruptionType: 'init_incomplete',
235
- currentState: {
236
- status: state.status,
237
- stepsCompleted: state.stepsCompleted,
238
- createdAt: state.createdAt
239
- },
240
- lastCheckpoint: checkpoint,
241
- pendingSteps: pending,
242
- recommendedAction: 'Run: node scripts/cco-init.js to complete initialization',
243
- isSafeToAutoRecover: true
244
- };
245
- }
246
-
247
- // Check for missing expected files
248
- const configPath = path.join(cwd, CONFIG_FILE);
249
- if (state && state.status === 'initialized' && !fs.existsSync(configPath)) {
250
- const pending = getPendingSteps(checkpoint);
251
- return {
252
- isInterrupted: true,
253
- interruptionType: 'missing_config',
254
- currentState: {
255
- status: state.status,
256
- hasConfigFile: false
257
- },
258
- lastCheckpoint: checkpoint,
259
- pendingSteps: pending,
260
- recommendedAction: 'Run: node scripts/cco-init.js to recreate missing files',
261
- isSafeToAutoRecover: true
262
- };
263
- }
264
-
265
- // If we reach here, onboarding state exists but is in an unexpected state
266
- return {
267
- isInterrupted: true,
268
- interruptionType: state ? 'unknown_state' : 'missing_or_invalid_state',
269
- currentState: state,
270
- lastCheckpoint: checkpoint,
271
- pendingSteps: checkpoint ? getPendingSteps(checkpoint) : [],
272
- recommendedAction: state ? 'Manual inspection required. Check: .claude/cco/state/onboarding.json' : 'Run initial setup with: node scripts/cco-init.js',
273
- isSafeToAutoRecover: false
274
- };
275
- }
276
-
277
- /**
278
- * Attempts safe auto-recovery for detectable interrupted states
279
- * @param {string} cwd - Current working directory
280
- * @returns {Object} Recovery result
281
- */
282
- function attemptAutoRecovery(cwd) {
283
- const detection = detectInterruptedState(cwd);
284
-
285
- if (!detection.isInterrupted || !detection.isSafeToAutoRecover) {
286
- return {
287
- success: false,
288
- reason: detection.isInterrupted ? 'Manual recovery required' : 'No interruption detected',
289
- detection: detection
290
- };
291
- }
292
-
293
- try {
294
- // Safe recovery actions based on interruption type
295
- switch (detection.interruptionType) {
296
- case 'init_incomplete':
297
- case 'missing_config':
298
- // Recovery: ensure directories exist (idempotent)
299
- ensureCcoDirs(cwd);
300
-
301
- // Check if config.json needs to be created
302
- const config = safeReadJson(cwd, CONFIG_FILE, null);
303
- if (!config) {
304
- // Create minimal config (will be enhanced by init script)
305
- safeWriteJson(cwd, CONFIG_FILE, {
306
- version: '0.1.0',
307
- initializedAt: new Date().toISOString(),
308
- tier: 'free',
309
- profile: 'balanced'
310
- });
311
- }
312
-
313
- return {
314
- success: true,
315
- recoveryType: detection.interruptionType,
316
- nextAction: 'Run: node scripts/cco-init.js to complete initialization'
317
- };
318
-
319
- default:
320
- return {
321
- success: false,
322
- reason: `Auto-recovery not implemented for type: ${detection.interruptionType}`
323
- };
324
- }
325
- } catch (error) {
326
- return {
327
- success: false,
328
- reason: `Recovery error: ${error.message}`,
329
- error: error
330
- };
331
- }
332
- }
333
-
334
- /**
335
- * CLI interface
336
- */
337
- function main() {
338
- const cwd = process.cwd();
339
- const [, , command] = process.argv;
340
-
341
- switch (command) {
342
- case 'detect':
343
- const detection = detectInterruptedState(cwd);
344
- console.log(JSON.stringify(detection, null, 2));
345
- break;
346
-
347
- case 'recover':
348
- const recovery = attemptAutoRecovery(cwd);
349
- console.log(JSON.stringify(recovery, null, 2));
350
-
351
- if (recovery.success) {
352
- console.log('\n✅ Recovery successful');
353
- console.log('📋 Next action:', recovery.nextAction);
354
- } else {
355
- console.log('\n❌ Recovery failed');
356
- if (recovery.reason) {
357
- console.log('Reason:', recovery.reason);
358
- }
359
- if (recovery.detection) {
360
- console.log('\nDetection result:');
361
- console.log('Recommended action:', recovery.detection.recommendedAction);
362
- }
363
- }
364
- break;
365
-
366
- case 'status':
367
- const status = detectInterruptedState(cwd);
368
- console.log('Interruption Status:', status.isInterrupted ? 'INTERRUPTED ⚠️' : 'OK ✅');
369
- console.log('Type:', status.interruptionType);
370
-
371
- if (status.isInterrupted) {
372
- console.log('\n📊 Current State:', JSON.stringify(status.currentState, null, 2));
373
- console.log('\n💡 Recommended Action:', status.recommendedAction);
374
-
375
- if (status.isSafeToAutoRecover) {
376
- console.log('\n🤖 Auto-recovery: Available (run with "recover" command)');
377
- } else {
378
- console.log('\n🔧 Auto-recovery: Manual intervention required');
379
- }
380
- } else {
381
- console.log('\n✨ System is fully initialized and ready');
382
- }
383
- break;
384
-
385
- default:
386
- console.log('Usage: node scripts/lib/upgrade-interruption-recovery.js [detect|recover|status]');
387
- console.log('');
388
- console.log('Commands:');
389
- console.log(' detect - Detect interrupted state and return JSON details');
390
- console.log(' recover - Attempt auto-recovery if safe (returns result JSON)');
391
- console.log(' status - Show human-readable status');
392
- }
393
- }
394
-
395
- if (require.main === module) {
396
- main();
397
- }
398
-
399
- module.exports = {
400
- detectInterruptedState,
401
- attemptAutoRecovery,
402
- safeWriteCheckpoint,
403
- safeClearCheckpoint,
404
- readCheckpoint,
405
- getPendingSteps,
406
- INIT_SEQUENCE_CHECKPOINTS
407
- };
@@ -1,201 +0,0 @@
1
- "use strict";
2
-
3
- const fs = require("fs");
4
- const path = require("path");
5
- const { ensureCcoDirs, safeWriteJson, nowIso } = require("./fsx");
6
- const { getQuota, getCurrentPlan } = require("./entitlements");
7
-
8
- const USAGE_LEDGER_REL_PATH = ".claude/cco/state/avorelo-usage.json";
9
- const SCHEMA_VERSION = 1;
10
-
11
- function ledgerPath(cwd) {
12
- return path.join(cwd, USAGE_LEDGER_REL_PATH);
13
- }
14
-
15
- function startOfUtcWeek(date) {
16
- const copy = new Date(date.getTime());
17
- const day = copy.getUTCDay();
18
- const diff = day === 0 ? -6 : 1 - day;
19
- copy.setUTCDate(copy.getUTCDate() + diff);
20
- copy.setUTCHours(0, 0, 0, 0);
21
- return copy;
22
- }
23
-
24
- function formatWindowKey(date, period) {
25
- const current = new Date(date.getTime());
26
- if (period === "month") {
27
- const month = `${current.getUTCMonth() + 1}`.padStart(2, "0");
28
- return `${current.getUTCFullYear()}-${month}`;
29
- }
30
- const start = startOfUtcWeek(current);
31
- const month = `${start.getUTCMonth() + 1}`.padStart(2, "0");
32
- const day = `${start.getUTCDate()}`.padStart(2, "0");
33
- return `${start.getUTCFullYear()}-W-${month}-${day}`;
34
- }
35
-
36
- function buildEmptyLedger() {
37
- return {
38
- schemaVersion: SCHEMA_VERSION,
39
- updatedAt: nowIso(),
40
- usage: {},
41
- };
42
- }
43
-
44
- function readUsageLedger(cwd) {
45
- const absPath = ledgerPath(cwd);
46
- if (!fs.existsSync(absPath)) {
47
- return {
48
- ok: true,
49
- ledger: buildEmptyLedger(),
50
- warnings: [],
51
- path: USAGE_LEDGER_REL_PATH,
52
- };
53
- }
54
-
55
- try {
56
- const raw = JSON.parse(fs.readFileSync(absPath, "utf8").replace(/^\uFEFF/, ""));
57
- const usage = raw && typeof raw === "object" && raw.usage && typeof raw.usage === "object" ? raw.usage : {};
58
- return {
59
- ok: true,
60
- ledger: {
61
- schemaVersion: SCHEMA_VERSION,
62
- updatedAt: typeof raw?.updatedAt === "string" ? raw.updatedAt : nowIso(),
63
- usage,
64
- },
65
- warnings: [],
66
- path: USAGE_LEDGER_REL_PATH,
67
- };
68
- } catch (error) {
69
- return {
70
- ok: false,
71
- ledger: buildEmptyLedger(),
72
- warnings: [`Usage ledger is unreadable: ${error.message}`],
73
- path: USAGE_LEDGER_REL_PATH,
74
- };
75
- }
76
- }
77
-
78
- function writeUsageLedger(cwd, ledger) {
79
- ensureCcoDirs(cwd);
80
- safeWriteJson(cwd, USAGE_LEDGER_REL_PATH, {
81
- schemaVersion: SCHEMA_VERSION,
82
- updatedAt: nowIso(),
83
- usage: ledger.usage || {},
84
- });
85
- }
86
-
87
- function getUsageCount(ledger, capabilityId, period, date = new Date()) {
88
- const windowKey = formatWindowKey(date, period);
89
- return Number(ledger?.usage?.[capabilityId]?.[windowKey] || 0);
90
- }
91
-
92
- function getQuotaStatus(cwd, capabilityId, options = {}) {
93
- const plan = options.plan || getCurrentPlan({ cwd });
94
- const quota = getQuota(capabilityId, { cwd, plan });
95
- const state = readUsageLedger(cwd);
96
- if (!quota || !quota.period || !Number.isFinite(Number(quota.limit))) {
97
- return {
98
- plan,
99
- capabilityId,
100
- tracked: false,
101
- allowed: true,
102
- used: 0,
103
- limit: null,
104
- remaining: null,
105
- warnings: state.warnings,
106
- ledgerPath: state.path,
107
- };
108
- }
109
-
110
- const used = getUsageCount(state.ledger, capabilityId, quota.period, options.date || new Date());
111
- const remaining = Math.max(0, Number(quota.limit) - used);
112
- return {
113
- plan,
114
- capabilityId,
115
- tracked: true,
116
- allowed: state.ok && used < Number(quota.limit),
117
- used,
118
- limit: Number(quota.limit),
119
- remaining,
120
- period: quota.period,
121
- windowKey: formatWindowKey(options.date || new Date(), quota.period),
122
- warnings: state.warnings,
123
- ledgerPath: state.path,
124
- };
125
- }
126
-
127
- function consumeQuota(cwd, capabilityId, options = {}) {
128
- const date = options.date || new Date();
129
- const plan = options.plan || getCurrentPlan({ cwd });
130
- const quota = getQuota(capabilityId, { cwd, plan });
131
- if (!quota || !quota.period || !Number.isFinite(Number(quota.limit))) {
132
- return {
133
- ok: true,
134
- consumed: false,
135
- plan,
136
- capabilityId,
137
- tracked: false,
138
- message: "This capability does not use a counted quota.",
139
- };
140
- }
141
-
142
- const state = readUsageLedger(cwd);
143
- if (!state.ok) {
144
- return {
145
- ok: false,
146
- consumed: false,
147
- plan,
148
- capabilityId,
149
- tracked: true,
150
- message: `Cannot safely consume quota because ${USAGE_LEDGER_REL_PATH} is unreadable.`,
151
- warnings: state.warnings,
152
- };
153
- }
154
-
155
- const windowKey = formatWindowKey(date, quota.period);
156
- const used = getUsageCount(state.ledger, capabilityId, quota.period, date);
157
- if (used >= Number(quota.limit)) {
158
- return {
159
- ok: false,
160
- consumed: false,
161
- plan,
162
- capabilityId,
163
- tracked: true,
164
- used,
165
- limit: Number(quota.limit),
166
- remaining: 0,
167
- period: quota.period,
168
- windowKey,
169
- message: `Quota reached for ${capabilityId}: ${used}/${quota.limit} ${quota.period} uses.`,
170
- };
171
- }
172
-
173
- const next = buildEmptyLedger();
174
- next.usage = { ...(state.ledger.usage || {}) };
175
- next.usage[capabilityId] = { ...(next.usage[capabilityId] || {}) };
176
- next.usage[capabilityId][windowKey] = used + 1;
177
- writeUsageLedger(cwd, next);
178
-
179
- return {
180
- ok: true,
181
- consumed: true,
182
- plan,
183
- capabilityId,
184
- tracked: true,
185
- used: used + 1,
186
- limit: Number(quota.limit),
187
- remaining: Math.max(0, Number(quota.limit) - used - 1),
188
- period: quota.period,
189
- windowKey,
190
- message: `Quota recorded for ${capabilityId}: ${used + 1}/${quota.limit} ${quota.period} uses.`,
191
- };
192
- }
193
-
194
- module.exports = {
195
- USAGE_LEDGER_REL_PATH,
196
- formatWindowKey,
197
- readUsageLedger,
198
- writeUsageLedger,
199
- getQuotaStatus,
200
- consumeQuota,
201
- };