avorelo 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (258) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +56 -0
  3. package/bin/avorelo +9 -0
  4. package/package.json +135 -0
  5. package/scripts/README.md +40 -0
  6. package/scripts/cco-dashboard.js +252 -0
  7. package/scripts/cco-status.js +430 -0
  8. package/scripts/lib/activation/account-state.js +37 -0
  9. package/scripts/lib/activation/activation-runner.js +546 -0
  10. package/scripts/lib/activation/activation-self-healing.js +480 -0
  11. package/scripts/lib/activation/activation-state.js +83 -0
  12. package/scripts/lib/activation/activation-summary.js +191 -0
  13. package/scripts/lib/activation/adapters/claude-code.js +77 -0
  14. package/scripts/lib/activation/adapters/codex-cli.js +52 -0
  15. package/scripts/lib/activation/adapters/cursor.js +37 -0
  16. package/scripts/lib/activation/adapters/github-agent.js +39 -0
  17. package/scripts/lib/activation/adapters/terminal.js +42 -0
  18. package/scripts/lib/activation/adapters/vscode.js +39 -0
  19. package/scripts/lib/activation/adapters/windsurf.js +37 -0
  20. package/scripts/lib/activation/ai-surface-detector.js +151 -0
  21. package/scripts/lib/activation/connect-account.js +145 -0
  22. package/scripts/lib/activation/detect-environment.js +75 -0
  23. package/scripts/lib/activation/detect-hosts.js +62 -0
  24. package/scripts/lib/activation/format-activation-output.js +109 -0
  25. package/scripts/lib/activation/next-action.js +43 -0
  26. package/scripts/lib/activation/repair-engine.js +219 -0
  27. package/scripts/lib/activation-distribution-readiness.js +507 -0
  28. package/scripts/lib/adapter-conformance.js +176 -0
  29. package/scripts/lib/adapter-readiness.js +417 -0
  30. package/scripts/lib/adapter-safety-boundaries.js +335 -0
  31. package/scripts/lib/adapter-technical-readiness-gate.js +205 -0
  32. package/scripts/lib/agent-access-governance.js +455 -0
  33. package/scripts/lib/agent-enforcement.js +765 -0
  34. package/scripts/lib/agent-policy-profile.js +210 -0
  35. package/scripts/lib/agent-security/action-evaluator.js +507 -0
  36. package/scripts/lib/agent-security/adapter-registry.js +98 -0
  37. package/scripts/lib/agent-security/auto-policy.js +139 -0
  38. package/scripts/lib/agent-security/bounded-scan.js +93 -0
  39. package/scripts/lib/agent-security/enforcement-adapter.js +174 -0
  40. package/scripts/lib/agent-security/enforcement-engine.js +1129 -0
  41. package/scripts/lib/agent-security/file-write-adapter.js +183 -0
  42. package/scripts/lib/agent-security/file-write-rules.js +178 -0
  43. package/scripts/lib/agent-security/index.js +3342 -0
  44. package/scripts/lib/agent-security/instruction-risk.js +181 -0
  45. package/scripts/lib/agent-security/mcp-action-adapter.js +185 -0
  46. package/scripts/lib/agent-security/mcp-action-rules.js +184 -0
  47. package/scripts/lib/agent-security/package-action-adapter.js +175 -0
  48. package/scripts/lib/agent-security/package-action-rules.js +233 -0
  49. package/scripts/lib/agent-security/performance.js +148 -0
  50. package/scripts/lib/agent-security/permission-minimizer.js +403 -0
  51. package/scripts/lib/agent-security/scan-cache.js +74 -0
  52. package/scripts/lib/agent-security/source-trust.js +146 -0
  53. package/scripts/lib/ai-install-prompt.js +288 -0
  54. package/scripts/lib/ai-workspace-hygiene.js +1499 -0
  55. package/scripts/lib/alpha-activation.js +520 -0
  56. package/scripts/lib/alpha-feedback.js +263 -0
  57. package/scripts/lib/alpha-readiness-gate.js +332 -0
  58. package/scripts/lib/anti-gaming.js +169 -0
  59. package/scripts/lib/artifact-health.js +431 -0
  60. package/scripts/lib/attribution.js +180 -0
  61. package/scripts/lib/audit.js +289 -0
  62. package/scripts/lib/avorelo-skill-registry.js +810 -0
  63. package/scripts/lib/batch-jobs.js +71 -0
  64. package/scripts/lib/brain-pack.js +578 -0
  65. package/scripts/lib/brand-boundary.js +424 -0
  66. package/scripts/lib/brand.js +74 -0
  67. package/scripts/lib/browser-capability.js +1048 -0
  68. package/scripts/lib/browser-proof-preflight.js +321 -0
  69. package/scripts/lib/cache-readiness.js +187 -0
  70. package/scripts/lib/canonical-reentry.js +162 -0
  71. package/scripts/lib/capability-packs.js +314 -0
  72. package/scripts/lib/capability-recommender.js +512 -0
  73. package/scripts/lib/capability-registry.js +1059 -0
  74. package/scripts/lib/carry-forward-surfacing.js +194 -0
  75. package/scripts/lib/ccusage-adapter.js +188 -0
  76. package/scripts/lib/company-loop.js +1149 -0
  77. package/scripts/lib/config.js +637 -0
  78. package/scripts/lib/context-acquisition-plan.js +287 -0
  79. package/scripts/lib/context-budget-guard.js +170 -0
  80. package/scripts/lib/context-budget-scanner.js +257 -0
  81. package/scripts/lib/context-optimizer.js +715 -0
  82. package/scripts/lib/context-reduction-plan.js +178 -0
  83. package/scripts/lib/context-safety.js +88 -0
  84. package/scripts/lib/context-savings-engine.js +158 -0
  85. package/scripts/lib/cost-evidence.js +254 -0
  86. package/scripts/lib/cross-host-install-plan.js +308 -0
  87. package/scripts/lib/cross-host-install-readiness.js +237 -0
  88. package/scripts/lib/cross-host-value-flow.js +268 -0
  89. package/scripts/lib/dashboard.js +900 -0
  90. package/scripts/lib/design-partner-feedback.js +346 -0
  91. package/scripts/lib/entitlements.js +100 -0
  92. package/scripts/lib/execution-packet.js +559 -0
  93. package/scripts/lib/experimentation-events.js +547 -0
  94. package/scripts/lib/external-capability-compliance.js +107 -0
  95. package/scripts/lib/external-user-simulation.js +166 -0
  96. package/scripts/lib/failure-recovery-readiness.js +81 -0
  97. package/scripts/lib/failure-recovery.js +419 -0
  98. package/scripts/lib/feedback-intelligence.js +537 -0
  99. package/scripts/lib/feedback-signals.js +205 -0
  100. package/scripts/lib/file-integrity.js +68 -0
  101. package/scripts/lib/fsx.js +127 -0
  102. package/scripts/lib/full-readiness-gate.js +451 -0
  103. package/scripts/lib/guidance-builder.js +174 -0
  104. package/scripts/lib/hook-apply.js +1019 -0
  105. package/scripts/lib/hook-baseline.js +310 -0
  106. package/scripts/lib/hook-config-preview.js +275 -0
  107. package/scripts/lib/hook-contracts.js +290 -0
  108. package/scripts/lib/hook-safety-boundary-readiness.js +80 -0
  109. package/scripts/lib/host-capability-matrix.js +351 -0
  110. package/scripts/lib/host-support-context.js +254 -0
  111. package/scripts/lib/http-hook-action.js +538 -0
  112. package/scripts/lib/install-ai-readiness.js +84 -0
  113. package/scripts/lib/install-intake-risk.js +1037 -0
  114. package/scripts/lib/install-journey-intelligence.js +329 -0
  115. package/scripts/lib/intervention-guidance.js +57 -0
  116. package/scripts/lib/known-limitations.js +115 -0
  117. package/scripts/lib/l8-path-truth.js +146 -0
  118. package/scripts/lib/launch-hardening-gate.js +436 -0
  119. package/scripts/lib/launch-readiness.js +628 -0
  120. package/scripts/lib/learning-memory.js +686 -0
  121. package/scripts/lib/lifecycle-hooks.js +802 -0
  122. package/scripts/lib/local-package-smoke.js +423 -0
  123. package/scripts/lib/local-pricing.js +299 -0
  124. package/scripts/lib/mcp-enforcement.js +311 -0
  125. package/scripts/lib/mcp-least-privilege-policy.js +303 -0
  126. package/scripts/lib/mcp-tool-inventory.js +388 -0
  127. package/scripts/lib/mcp-tool-risk.js +0 -0
  128. package/scripts/lib/memory.js +335 -0
  129. package/scripts/lib/metrics.js +699 -0
  130. package/scripts/lib/micro-proof.js +133 -0
  131. package/scripts/lib/next-run-context.js +436 -0
  132. package/scripts/lib/operating-value.js +1648 -0
  133. package/scripts/lib/optimization-v3.js +122 -0
  134. package/scripts/lib/orchestration/adapters/_shared.js +49 -0
  135. package/scripts/lib/orchestration/adapters/aider.js +18 -0
  136. package/scripts/lib/orchestration/adapters/claude-code.js +35 -0
  137. package/scripts/lib/orchestration/adapters/codex.js +35 -0
  138. package/scripts/lib/orchestration/adapters/gemini-cli.js +18 -0
  139. package/scripts/lib/orchestration/adapters/git.js +25 -0
  140. package/scripts/lib/orchestration/adapters/index.js +31 -0
  141. package/scripts/lib/orchestration/adapters/lm-studio.js +18 -0
  142. package/scripts/lib/orchestration/adapters/ollama.js +18 -0
  143. package/scripts/lib/orchestration/adapters/opencode.js +18 -0
  144. package/scripts/lib/orchestration/adapters/openrouter.js +18 -0
  145. package/scripts/lib/orchestration/adapters/test-runner.js +25 -0
  146. package/scripts/lib/orchestration/cli.js +438 -0
  147. package/scripts/lib/orchestration/execution-manager.js +279 -0
  148. package/scripts/lib/orchestration/handoff.js +314 -0
  149. package/scripts/lib/orchestration/index.js +456 -0
  150. package/scripts/lib/orchestration/inventory.js +47 -0
  151. package/scripts/lib/orchestration/model-discovery.js +498 -0
  152. package/scripts/lib/orchestration/model-profiler.js +170 -0
  153. package/scripts/lib/orchestration/model-profiles.js +252 -0
  154. package/scripts/lib/orchestration/model-refresh-policy.js +72 -0
  155. package/scripts/lib/orchestration/proof-writer.js +349 -0
  156. package/scripts/lib/orchestration/provider-discovery/aider.js +49 -0
  157. package/scripts/lib/orchestration/provider-discovery/claude-code.js +56 -0
  158. package/scripts/lib/orchestration/provider-discovery/codex.js +49 -0
  159. package/scripts/lib/orchestration/provider-discovery/common.js +186 -0
  160. package/scripts/lib/orchestration/provider-discovery/gemini.js +106 -0
  161. package/scripts/lib/orchestration/provider-discovery/lm-studio.js +118 -0
  162. package/scripts/lib/orchestration/provider-discovery/models-dev.js +12 -0
  163. package/scripts/lib/orchestration/provider-discovery/ollama.js +100 -0
  164. package/scripts/lib/orchestration/provider-discovery/opencode.js +47 -0
  165. package/scripts/lib/orchestration/provider-discovery/openrouter.js +44 -0
  166. package/scripts/lib/orchestration/risk-classifier.js +130 -0
  167. package/scripts/lib/orchestration/routing-policy.js +486 -0
  168. package/scripts/lib/orchestration/settings.js +112 -0
  169. package/scripts/lib/orchestration/state.js +165 -0
  170. package/scripts/lib/orchestration/verification-manager.js +138 -0
  171. package/scripts/lib/output-profiles.js +146 -0
  172. package/scripts/lib/package-content-audit.js +368 -0
  173. package/scripts/lib/package-runtime.js +278 -0
  174. package/scripts/lib/plan-surface.js +53 -0
  175. package/scripts/lib/plans.js +2318 -0
  176. package/scripts/lib/policy-provider.js +27 -0
  177. package/scripts/lib/prelaunch-activation-readiness.js +409 -0
  178. package/scripts/lib/prelaunch-evidence-store.js +816 -0
  179. package/scripts/lib/prelaunch-intelligence.js +869 -0
  180. package/scripts/lib/pricing-experiment.js +118 -0
  181. package/scripts/lib/pro-moment-events.js +77 -0
  182. package/scripts/lib/pro-moment-state.js +227 -0
  183. package/scripts/lib/pro-moments.js +1216 -0
  184. package/scripts/lib/product-learning-events.js +629 -0
  185. package/scripts/lib/project-profile.js +555 -0
  186. package/scripts/lib/prompt-compiler.js +280 -0
  187. package/scripts/lib/prompt-lint.js +32 -0
  188. package/scripts/lib/prompt-suggestions.js +52 -0
  189. package/scripts/lib/proof-canonical.js +398 -0
  190. package/scripts/lib/proof-drilldown.js +383 -0
  191. package/scripts/lib/proof-events.js +342 -0
  192. package/scripts/lib/proof-history.js +243 -0
  193. package/scripts/lib/proof-metrics.js +296 -0
  194. package/scripts/lib/proof-outcome-evidence.js +134 -0
  195. package/scripts/lib/proof-receipt.js +335 -0
  196. package/scripts/lib/proof-record.js +461 -0
  197. package/scripts/lib/public-activation-distribution-gate.js +258 -0
  198. package/scripts/lib/public-cli.js +3891 -0
  199. package/scripts/lib/public-distribution-truth.js +211 -0
  200. package/scripts/lib/public-install-claim-checker.js +294 -0
  201. package/scripts/lib/publish-provenance-readiness.js +283 -0
  202. package/scripts/lib/readiness-delta.js +218 -0
  203. package/scripts/lib/readiness-evidence-closure.js +196 -0
  204. package/scripts/lib/reentry-memory-capture.js +241 -0
  205. package/scripts/lib/reentry-memory-retrieval.js +302 -0
  206. package/scripts/lib/reentry-memory-status.js +146 -0
  207. package/scripts/lib/reentry-memory-store.js +178 -0
  208. package/scripts/lib/reentry-state.js +66 -0
  209. package/scripts/lib/release-candidate-bundle.js +166 -0
  210. package/scripts/lib/remediation.js +81 -0
  211. package/scripts/lib/repo-map.js +391 -0
  212. package/scripts/lib/run-improvements-lifecycle.js +330 -0
  213. package/scripts/lib/run-improvements.js +789 -0
  214. package/scripts/lib/runtime-decision-policy.js +387 -0
  215. package/scripts/lib/safe-path-engine.js +705 -0
  216. package/scripts/lib/safe-run-controller.js +887 -0
  217. package/scripts/lib/score.js +262 -0
  218. package/scripts/lib/seamless-enforcement.js +329 -0
  219. package/scripts/lib/seamless-outcome.js +689 -0
  220. package/scripts/lib/seamless-reality-gate.js +5043 -0
  221. package/scripts/lib/security-risk-classifier.js +511 -0
  222. package/scripts/lib/security-scan.js +384 -0
  223. package/scripts/lib/session-context-optimizer.js +1211 -0
  224. package/scripts/lib/session-timing.js +315 -0
  225. package/scripts/lib/skill-hygiene.js +805 -0
  226. package/scripts/lib/skill-packs.js +161 -0
  227. package/scripts/lib/skills-operating-layer.js +580 -0
  228. package/scripts/lib/smart-work-routing.js +768 -0
  229. package/scripts/lib/source-catalog.js +700 -0
  230. package/scripts/lib/status-value-summary.js +32 -0
  231. package/scripts/lib/support-bundle.js +578 -0
  232. package/scripts/lib/task-continuation.js +440 -0
  233. package/scripts/lib/test-helpers.js +15 -0
  234. package/scripts/lib/tier.js +38 -0
  235. package/scripts/lib/token-context-quality-gate.js +370 -0
  236. package/scripts/lib/token-cost-capture.js +187 -0
  237. package/scripts/lib/token-cost-intelligence.js +358 -0
  238. package/scripts/lib/token-efficiency-evidence.js +213 -0
  239. package/scripts/lib/token-evidence.js +699 -0
  240. package/scripts/lib/tokenish.js +17 -0
  241. package/scripts/lib/tool-output-sandbox.js +304 -0
  242. package/scripts/lib/trust-audit.js +136 -0
  243. package/scripts/lib/unified-events.js +396 -0
  244. package/scripts/lib/upgrade-interruption-recovery.js +407 -0
  245. package/scripts/lib/usage-ledger.js +201 -0
  246. package/scripts/lib/value-ledger.js +130 -0
  247. package/scripts/lib/value-proof-calibration.js +531 -0
  248. package/scripts/lib/visual-qa.js +231 -0
  249. package/scripts/lib/voice-alpha.js +29 -0
  250. package/scripts/lib/work-aware-orchestration.js +976 -0
  251. package/scripts/lib/work-control-receipts.js +577 -0
  252. package/scripts/lib/work-ledger.js +1123 -0
  253. package/scripts/lib/work-panel-preview.js +352 -0
  254. package/scripts/lib/workflow-discipline.js +280 -0
  255. package/scripts/lib/workflow-signals.js +419 -0
  256. package/scripts/lib/workspace-map.js +281 -0
  257. package/scripts/lib/workspace-registry.js +1367 -0
  258. package/scripts/lib/workspace-resolver.js +480 -0
@@ -0,0 +1,407 @@
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
+ };
@@ -0,0 +1,201 @@
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
+ };