@quickback-dev/cli 0.72.9 → 0.72.11

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 (212) hide show
  1. package/dist/commands/build.d.ts.map +1 -1
  2. package/dist/commands/build.js +8 -1
  3. package/dist/commands/build.js.map +1 -1
  4. package/dist/commands/db-explain.d.ts +67 -0
  5. package/dist/commands/db-explain.d.ts.map +1 -0
  6. package/dist/commands/db-explain.js +141 -0
  7. package/dist/commands/db-explain.js.map +1 -0
  8. package/dist/commands/db-export.d.ts +34 -0
  9. package/dist/commands/db-export.d.ts.map +1 -0
  10. package/dist/commands/db-export.js +250 -0
  11. package/dist/commands/db-export.js.map +1 -0
  12. package/dist/commands/db-insights.d.ts +60 -0
  13. package/dist/commands/db-insights.d.ts.map +1 -0
  14. package/dist/commands/db-insights.js +106 -0
  15. package/dist/commands/db-insights.js.map +1 -0
  16. package/dist/commands/db-recovery.d.ts +98 -0
  17. package/dist/commands/db-recovery.d.ts.map +1 -0
  18. package/dist/commands/db-recovery.js +558 -0
  19. package/dist/commands/db-recovery.js.map +1 -0
  20. package/dist/commands/db-target.d.ts +27 -0
  21. package/dist/commands/db-target.d.ts.map +1 -0
  22. package/dist/commands/db-target.js +83 -0
  23. package/dist/commands/db-target.js.map +1 -0
  24. package/dist/commands/db.d.ts +3 -0
  25. package/dist/commands/db.d.ts.map +1 -0
  26. package/dist/commands/db.js +43 -0
  27. package/dist/commands/db.js.map +1 -0
  28. package/dist/commands/effects.d.ts +8 -0
  29. package/dist/commands/effects.d.ts.map +1 -0
  30. package/dist/commands/effects.js +48 -0
  31. package/dist/commands/effects.js.map +1 -0
  32. package/dist/commands/platform-budget.d.ts +143 -0
  33. package/dist/commands/platform-budget.d.ts.map +1 -0
  34. package/dist/commands/platform-budget.js +619 -0
  35. package/dist/commands/platform-budget.js.map +1 -0
  36. package/dist/commands/preview.d.ts +57 -0
  37. package/dist/commands/preview.d.ts.map +1 -0
  38. package/dist/commands/preview.js +268 -0
  39. package/dist/commands/preview.js.map +1 -0
  40. package/dist/commands/search.d.ts +20 -0
  41. package/dist/commands/search.d.ts.map +1 -0
  42. package/dist/commands/search.js +133 -0
  43. package/dist/commands/search.js.map +1 -0
  44. package/dist/index.js +35 -1
  45. package/dist/index.js.map +1 -1
  46. package/dist/lib/api-client.d.ts +4 -0
  47. package/dist/lib/api-client.d.ts.map +1 -1
  48. package/dist/lib/api-client.js.map +1 -1
  49. package/dist/lib/cloudflare-spend-policies.d.ts +92 -0
  50. package/dist/lib/cloudflare-spend-policies.d.ts.map +1 -0
  51. package/dist/lib/cloudflare-spend-policies.js +289 -0
  52. package/dist/lib/cloudflare-spend-policies.js.map +1 -0
  53. package/dist/lib/compiler-stubs.d.ts +2 -0
  54. package/dist/lib/compiler-stubs.d.ts.map +1 -1
  55. package/dist/lib/compiler-stubs.js +2 -0
  56. package/dist/lib/compiler-stubs.js.map +1 -1
  57. package/dist/lib/d1-fingerprint.d.ts +8 -0
  58. package/dist/lib/d1-fingerprint.d.ts.map +1 -0
  59. package/dist/lib/d1-fingerprint.js +113 -0
  60. package/dist/lib/d1-fingerprint.js.map +1 -0
  61. package/dist/lib/file-loader.d.ts +12 -0
  62. package/dist/lib/file-loader.d.ts.map +1 -1
  63. package/dist/lib/file-loader.js +27 -1
  64. package/dist/lib/file-loader.js.map +1 -1
  65. package/dist/lib/migrations/plan.js +3 -0
  66. package/dist/lib/migrations/plan.js.map +1 -1
  67. package/dist/lib/migrations/postprocessors/index.d.ts +6 -5
  68. package/dist/lib/migrations/postprocessors/index.d.ts.map +1 -1
  69. package/dist/lib/migrations/postprocessors/index.js +24 -12
  70. package/dist/lib/migrations/postprocessors/index.js.map +1 -1
  71. package/dist/lib/migrations/postprocessors/search.d.ts +49 -0
  72. package/dist/lib/migrations/postprocessors/search.d.ts.map +1 -0
  73. package/dist/lib/migrations/postprocessors/search.js +160 -0
  74. package/dist/lib/migrations/postprocessors/search.js.map +1 -0
  75. package/dist/lib/migrations/prior-state.d.ts +7 -0
  76. package/dist/lib/migrations/prior-state.d.ts.map +1 -1
  77. package/dist/lib/migrations/prior-state.js +3 -0
  78. package/dist/lib/migrations/prior-state.js.map +1 -1
  79. package/dist/lib/migrations/types.d.ts +1 -1
  80. package/dist/lib/migrations/types.d.ts.map +1 -1
  81. package/dist/lib/migrations/types.js +1 -0
  82. package/dist/lib/migrations/types.js.map +1 -1
  83. package/dist/lib/preview-lifecycle.d.ts +139 -0
  84. package/dist/lib/preview-lifecycle.d.ts.map +1 -0
  85. package/dist/lib/preview-lifecycle.js +429 -0
  86. package/dist/lib/preview-lifecycle.js.map +1 -0
  87. package/dist/lib/preview.d.ts +146 -0
  88. package/dist/lib/preview.d.ts.map +1 -0
  89. package/dist/lib/preview.js +417 -0
  90. package/dist/lib/preview.js.map +1 -0
  91. package/dist/lib/wrangler-resources.d.ts.map +1 -1
  92. package/dist/lib/wrangler-resources.js +4 -2
  93. package/dist/lib/wrangler-resources.js.map +1 -1
  94. package/dist/skill/SKILL.md +9 -3
  95. package/dist/skill/agents/quickback-specialist/AGENT.md +9 -11
  96. package/dist/skill/docs/api/batch-operations.md +19 -0
  97. package/dist/skill/docs/api/caching.md +17 -0
  98. package/dist/skill/docs/api/crud.md +9 -0
  99. package/dist/skill/docs/api/errors.md +31 -2
  100. package/dist/skill/docs/api/query-params.md +6 -0
  101. package/dist/skill/docs/changelog/index.md +1 -0
  102. package/dist/skill/docs/configure/agents.md +1 -1
  103. package/dist/skill/docs/configure/bindings.md +177 -1
  104. package/dist/skill/docs/configure/cloudflare-access.md +43 -0
  105. package/dist/skill/docs/configure/domains.md +1 -1
  106. package/dist/skill/docs/configure/providers.md +5 -0
  107. package/dist/skill/docs/configure/tenant-databases.md +627 -14
  108. package/dist/skill/docs/define/access.md +26 -0
  109. package/dist/skill/docs/define/actions/defining.md +7 -1
  110. package/dist/skill/docs/define/actions/index.md +5 -0
  111. package/dist/skill/docs/define/actions/scoped-db.md +127 -1
  112. package/dist/skill/docs/define/authoring-basics.md +92 -0
  113. package/dist/skill/docs/define/changesets.md +8 -0
  114. package/dist/skill/docs/define/encryption.md +48 -2
  115. package/dist/skill/docs/define/feature.md +17 -2
  116. package/dist/skill/docs/define/guards.md +11 -3
  117. package/dist/skill/docs/define/index.md +1 -1
  118. package/dist/skill/docs/define/invariants.md +321 -0
  119. package/dist/skill/docs/define/issue-tracker-example.md +225 -0
  120. package/dist/skill/docs/define/masking.md +3 -3
  121. package/dist/skill/docs/define/rate-limit.md +78 -30
  122. package/dist/skill/docs/define/read.md +332 -5
  123. package/dist/skill/docs/define/relationships.md +10 -0
  124. package/dist/skill/docs/define/schema.md +137 -10
  125. package/dist/skill/docs/define/scopes.md +1 -0
  126. package/dist/skill/docs/define/transitions.md +9 -0
  127. package/dist/skill/docs/define/triggers.md +127 -1
  128. package/dist/skill/docs/platform/api-contract/index.md +35 -4
  129. package/dist/skill/docs/platform/auth/api-keys.md +26 -3
  130. package/dist/skill/docs/platform/auth/index.md +5 -2
  131. package/dist/skill/docs/platform/auth/plugins/index.md +1 -1
  132. package/dist/skill/docs/platform/database/d1.md +73 -1
  133. package/dist/skill/docs/platform/database/durable-effects.md +224 -0
  134. package/dist/skill/docs/platform/database/neon.md +8 -5
  135. package/dist/skill/docs/platform/database/read-replication.md +9 -0
  136. package/dist/skill/docs/platform/database/recovery.md +292 -0
  137. package/dist/skill/docs/platform/database/using-d1.md +152 -2
  138. package/dist/skill/docs/platform/index.md +1 -0
  139. package/dist/skill/docs/platform/operations/budgets.md +224 -0
  140. package/dist/skill/docs/platform/queues/handlers.md +1 -0
  141. package/dist/skill/docs/platform/queues/index.md +18 -0
  142. package/dist/skill/docs/platform/realtime/table-changes.md +1 -0
  143. package/dist/skill/docs/platform/storage/using-r2.md +13 -0
  144. package/dist/skill/docs/platform/vector/embeddings.md +28 -4
  145. package/dist/skill/docs/platform/vector/using-embeddings.md +17 -0
  146. package/dist/skill/docs/platform/workflows/index.md +385 -0
  147. package/dist/skill/docs/start/deploy-browser.md +51 -0
  148. package/dist/skill/docs/start/deploy.md +97 -1
  149. package/dist/skill/docs/tooling/cli.md +117 -0
  150. package/dist/skill/docs/tooling/cloud-compiler/index.md +15 -0
  151. package/dist/skill/docs/ui/account/customization.md +4 -0
  152. package/dist/skill/docs/ui/admin/record-layouts.md +3 -3
  153. package/package.json +1 -1
  154. package/src/skill/SKILL.md +9 -3
  155. package/src/skill/agents/quickback-specialist/AGENT.md +9 -11
  156. package/src/skill/docs/api/batch-operations.md +19 -0
  157. package/src/skill/docs/api/caching.md +17 -0
  158. package/src/skill/docs/api/crud.md +9 -0
  159. package/src/skill/docs/api/errors.md +31 -2
  160. package/src/skill/docs/api/query-params.md +6 -0
  161. package/src/skill/docs/changelog/index.md +1 -0
  162. package/src/skill/docs/configure/agents.md +1 -1
  163. package/src/skill/docs/configure/bindings.md +177 -1
  164. package/src/skill/docs/configure/cloudflare-access.md +43 -0
  165. package/src/skill/docs/configure/domains.md +1 -1
  166. package/src/skill/docs/configure/providers.md +5 -0
  167. package/src/skill/docs/configure/tenant-databases.md +627 -14
  168. package/src/skill/docs/define/access.md +26 -0
  169. package/src/skill/docs/define/actions/defining.md +7 -1
  170. package/src/skill/docs/define/actions/index.md +5 -0
  171. package/src/skill/docs/define/actions/scoped-db.md +127 -1
  172. package/src/skill/docs/define/authoring-basics.md +92 -0
  173. package/src/skill/docs/define/changesets.md +8 -0
  174. package/src/skill/docs/define/encryption.md +48 -2
  175. package/src/skill/docs/define/feature.md +17 -2
  176. package/src/skill/docs/define/guards.md +11 -3
  177. package/src/skill/docs/define/index.md +1 -1
  178. package/src/skill/docs/define/invariants.md +321 -0
  179. package/src/skill/docs/define/issue-tracker-example.md +225 -0
  180. package/src/skill/docs/define/masking.md +3 -3
  181. package/src/skill/docs/define/rate-limit.md +78 -30
  182. package/src/skill/docs/define/read.md +332 -5
  183. package/src/skill/docs/define/relationships.md +10 -0
  184. package/src/skill/docs/define/schema.md +137 -10
  185. package/src/skill/docs/define/scopes.md +1 -0
  186. package/src/skill/docs/define/transitions.md +9 -0
  187. package/src/skill/docs/define/triggers.md +127 -1
  188. package/src/skill/docs/platform/api-contract/index.md +35 -4
  189. package/src/skill/docs/platform/auth/api-keys.md +26 -3
  190. package/src/skill/docs/platform/auth/index.md +5 -2
  191. package/src/skill/docs/platform/auth/plugins/index.md +1 -1
  192. package/src/skill/docs/platform/database/d1.md +73 -1
  193. package/src/skill/docs/platform/database/durable-effects.md +224 -0
  194. package/src/skill/docs/platform/database/neon.md +8 -5
  195. package/src/skill/docs/platform/database/read-replication.md +9 -0
  196. package/src/skill/docs/platform/database/recovery.md +292 -0
  197. package/src/skill/docs/platform/database/using-d1.md +152 -2
  198. package/src/skill/docs/platform/index.md +1 -0
  199. package/src/skill/docs/platform/operations/budgets.md +224 -0
  200. package/src/skill/docs/platform/queues/handlers.md +1 -0
  201. package/src/skill/docs/platform/queues/index.md +18 -0
  202. package/src/skill/docs/platform/realtime/table-changes.md +1 -0
  203. package/src/skill/docs/platform/storage/using-r2.md +13 -0
  204. package/src/skill/docs/platform/vector/embeddings.md +28 -4
  205. package/src/skill/docs/platform/vector/using-embeddings.md +17 -0
  206. package/src/skill/docs/platform/workflows/index.md +385 -0
  207. package/src/skill/docs/start/deploy-browser.md +51 -0
  208. package/src/skill/docs/start/deploy.md +97 -1
  209. package/src/skill/docs/tooling/cli.md +117 -0
  210. package/src/skill/docs/tooling/cloud-compiler/index.md +15 -0
  211. package/src/skill/docs/ui/account/customization.md +4 -0
  212. package/src/skill/docs/ui/admin/record-layouts.md +3 -3
@@ -0,0 +1,619 @@
1
+ /**
2
+ * `quickback platform budget` — account-level Cloudflare spend policies
3
+ * (plan 050).
4
+ *
5
+ * These are ACCOUNT-WIDE, product-wide controls (all Workers, or all Durable
6
+ * Objects, on one account). They are not per-Worker, per-tenant or per-request
7
+ * quotas, and a limit is not an invoice cap: metering and enforcement lag, and
8
+ * some charges continue during a pause. Every command says so.
9
+ *
10
+ * status read-only: policies (owned and foreign), threshold events
11
+ * plan read-only: desired document → reviewed plan file + digest
12
+ * apply execute a reviewed plan; requires --confirm <digest>
13
+ * history configuration activity, or one policy's threshold events
14
+ * rollback-plan build a new reviewed plan restoring an applied plan's before-state
15
+ *
16
+ * The target account is always explicit (--account or --env) and printed
17
+ * first. Nothing here reads the account from the ambient cf profile, and
18
+ * `quickback build` / `deploy` never apply account policies.
19
+ *
20
+ * Operator state (ownership manifest + append-only receipts) lives in
21
+ * --state (default .quickback/platform-budget), written 0600.
22
+ */
23
+ import { createHash } from 'crypto';
24
+ import fs from 'fs/promises';
25
+ import { join, dirname } from 'path';
26
+ import pc from 'picocolors';
27
+ import { runCommandCapture } from '../lib/shell.js';
28
+ import { findConfigPath, loadConfig } from '../lib/file-loader.js';
29
+ import { deploymentEnvironments, resolveDeploymentTarget } from '../lib/deployment-target.js';
30
+ import { ACCOUNT_ID_RE, SpendPolicyClient, SpendPolicyError, desiredInput, formatCents, inputOf, redact, validateBudgetDocument, } from '../lib/cloudflare-spend-policies.js';
31
+ export const SCOPE_NOTICE = 'Scope: account-wide, product-wide Cloudflare controls (all Workers or all Durable Objects on this account). ' +
32
+ 'Not per-tenant or per-Worker quotas, and not an invoice cap — reporting and blocking lag, and some charges continue during a pause.';
33
+ export const OUTSIDE_CONTROLS = 'Not covered by any spend policy: the Workers Paid subscription fee, Workers KV, R2, D1, Queues, Workers AI, ' +
34
+ 'Vectorize, and Durable Objects stored data. Use the dashboard budget alert (account-wide, email only) for those.';
35
+ // ─── Canonical hashing / atomic state ──────────────────────────────────
36
+ export function canonicalJson(value) {
37
+ if (Array.isArray(value))
38
+ return `[${value.map(canonicalJson).join(',')}]`;
39
+ if (value && typeof value === 'object') {
40
+ return `{${Object.keys(value).filter((k) => value[k] !== undefined).sort()
41
+ .map((k) => `${JSON.stringify(k)}:${canonicalJson(value[k])}`).join(',')}}`;
42
+ }
43
+ return JSON.stringify(value);
44
+ }
45
+ const sha256 = (s) => createHash('sha256').update(s).digest('hex');
46
+ export const configHash = (input) => sha256(canonicalJson(input));
47
+ export function planDigest(plan) {
48
+ const { digest: _ignored, ...body } = plan;
49
+ return sha256(canonicalJson(body));
50
+ }
51
+ export const nodeStateIO = {
52
+ readFile: (path) => fs.readFile(path, 'utf8'),
53
+ async writeFileAtomic(path, content) {
54
+ await fs.mkdir(dirname(path), { recursive: true, mode: 0o700 });
55
+ const tmp = `${path}.${process.pid}.tmp`;
56
+ await fs.writeFile(tmp, content, { mode: 0o600 });
57
+ await fs.rename(tmp, path);
58
+ },
59
+ async appendFile(path, content) {
60
+ await fs.mkdir(dirname(path), { recursive: true, mode: 0o700 });
61
+ const handle = await fs.open(path, 'a', 0o600);
62
+ try {
63
+ await handle.write(content);
64
+ await handle.sync();
65
+ }
66
+ finally {
67
+ await handle.close();
68
+ }
69
+ },
70
+ };
71
+ async function readJsonOr(io, path, fallback) {
72
+ try {
73
+ return JSON.parse(await io.readFile(path));
74
+ }
75
+ catch (err) {
76
+ if (err.code === 'ENOENT')
77
+ return fallback;
78
+ throw new Error(`Cannot read ${path}: ${err.message}`);
79
+ }
80
+ }
81
+ async function readReceipts(io, stateDir) {
82
+ let text;
83
+ try {
84
+ text = await io.readFile(join(stateDir, 'receipts.jsonl'));
85
+ }
86
+ catch (err) {
87
+ if (err.code === 'ENOENT')
88
+ return [];
89
+ throw err;
90
+ }
91
+ return text.split('\n').filter(Boolean).map((line) => JSON.parse(line));
92
+ }
93
+ // ─── Planning (pure) ───────────────────────────────────────────────────
94
+ const same = (a, b) => canonicalJson(a) === canonicalJson(b);
95
+ function consequencesFor(before, after) {
96
+ const out = [];
97
+ const product = after.productId === 'workers' ? 'every Worker invocation (HTTP, cron, queues) on this account' : 'Durable Objects requests on this account';
98
+ const blocks = (p) => p?.enabled === true && p.action === 'usage_block';
99
+ if (blocks(after) && (!blocks(before) || after.thresholdCents < (before?.thresholdCents ?? Infinity))) {
100
+ out.push(`Can block ${product} as soon as Cloudflare evaluates it if recorded spend this period is already ≥ ${formatCents(after.thresholdCents)}. Current spend is unknown to Quickback.`);
101
+ }
102
+ if (blocks(before) && (!blocks(after) || after.thresholdCents > before.thresholdCents)) {
103
+ out.push('Raises, turns off or converts a spending limit: lifts any block and permits further spending.');
104
+ }
105
+ if (before && after.thresholdCents < before.thresholdCents)
106
+ out.push(`Lowers the threshold ${formatCents(before.thresholdCents)} → ${formatCents(after.thresholdCents)}.`);
107
+ if (before?.notificationEmail && !after.notificationEmail)
108
+ out.push('Removes the notification email: this policy will send no email.');
109
+ if (after.action === 'usage_block' && !after.notificationEmail)
110
+ out.push('A limit without an email address sends no notification.');
111
+ return out;
112
+ }
113
+ export function buildPlan(inputs) {
114
+ const doc = validateBudgetDocument(inputs.document);
115
+ const errors = [];
116
+ const warnings = [];
117
+ const operations = [];
118
+ const unchanged = [];
119
+ const byId = new Map(inputs.observed.map((p) => [p.id, p]));
120
+ const owned = inputs.ownership.entries.filter((e) => e.accountId === doc.accountId && e.owner === doc.owner);
121
+ const ownedByKey = new Map(owned.map((e) => [e.key, e]));
122
+ const ownedIds = new Set(inputs.ownership.entries.filter((e) => e.accountId === doc.accountId).map((e) => e.policyId));
123
+ for (const desired of doc.policies) {
124
+ const input = desiredInput(doc.owner, desired);
125
+ const entry = ownedByKey.get(desired.key);
126
+ if (entry && desired.adoptPolicyId && desired.adoptPolicyId !== entry.policyId) {
127
+ errors.push(`${desired.key}: already owned as policy ${entry.policyId}; remove adoptPolicyId or the ownership entry first.`);
128
+ continue;
129
+ }
130
+ const currentId = entry?.policyId ?? desired.adoptPolicyId;
131
+ const current = currentId ? byId.get(currentId) : undefined;
132
+ if (desired.adoptPolicyId && !entry) {
133
+ if (!current) {
134
+ errors.push(`${desired.key}: adoptPolicyId ${desired.adoptPolicyId} does not exist on account ${doc.accountId}.`);
135
+ continue;
136
+ }
137
+ if (ownedIds.has(current.id)) {
138
+ errors.push(`${desired.key}: policy ${current.id} is already owned by another Quickback key or owner.`);
139
+ continue;
140
+ }
141
+ if (current.productId !== input.productId) {
142
+ errors.push(`${desired.key}: policy ${current.id} is for ${current.productId}, not ${input.productId}.`);
143
+ continue;
144
+ }
145
+ const before = inputOf(current);
146
+ operations.push(same(before, input)
147
+ ? { op: 'adopt', key: desired.key, policyId: current.id, expectedVersion: current.version, before, consequences: ['Records ownership only; no Cloudflare change.'] }
148
+ : { op: 'update', key: desired.key, policyId: current.id, expectedVersion: current.version, before, input, adopt: true, reason: 'change', consequences: ['Takes ownership of a policy Quickback did not create.', ...consequencesFor(before, input)] });
149
+ continue;
150
+ }
151
+ if (entry && !current) {
152
+ warnings.push(`${desired.key}: owned policy ${entry.policyId} no longer exists on Cloudflare (deleted outside Quickback); it will be created again.`);
153
+ }
154
+ if (!current) {
155
+ operations.push({ op: 'create', key: desired.key, input, consequences: consequencesFor(undefined, input) });
156
+ continue;
157
+ }
158
+ const before = inputOf(current);
159
+ if (configHash(before) !== entry.configHash) {
160
+ warnings.push(`${desired.key}: policy ${current.id} was changed outside Quickback since the last apply (version ${entry.observedVersion} → ${current.version}). Review before applying.`);
161
+ }
162
+ if (current.unknownFields.length) {
163
+ warnings.push(`${desired.key}: Cloudflare returned fields Quickback does not manage (${current.unknownFields.join(', ')}); an update resends only the documented options.`);
164
+ }
165
+ if (same(before, input)) {
166
+ unchanged.push(desired.key);
167
+ continue;
168
+ }
169
+ if (current.productId !== input.productId) {
170
+ errors.push(`${desired.key}: product cannot change (${current.productId} → ${input.productId}); use a new key.`);
171
+ continue;
172
+ }
173
+ operations.push({ op: 'update', key: desired.key, policyId: current.id, expectedVersion: current.version, before, input, reason: 'change', consequences: consequencesFor(before, input) });
174
+ }
175
+ // Owned policies the document no longer lists are turned off — never deleted, never left silently enforcing.
176
+ const listed = new Set(doc.policies.map((p) => p.key));
177
+ for (const entry of owned) {
178
+ if (listed.has(entry.key))
179
+ continue;
180
+ const current = byId.get(entry.policyId);
181
+ if (!current || !current.enabled)
182
+ continue;
183
+ const before = inputOf(current);
184
+ const input = { ...before, enabled: false };
185
+ operations.push({ op: 'update', key: entry.key, policyId: current.id, expectedVersion: current.version, before, input, reason: 'removed-from-document', consequences: ['Removed from the document: turned off (not deleted).', ...consequencesFor(before, input)] });
186
+ }
187
+ // One enabled spending limit per product. Never displace a foreign one.
188
+ const after = new Map(inputs.observed.map((p) => [p.id, inputOf(p)]));
189
+ for (const op of operations)
190
+ if (op.op !== 'adopt')
191
+ after.set(op.op === 'create' ? `new:${op.key}` : op.policyId, op.input);
192
+ for (const product of ['workers', 'durable_objects']) {
193
+ const limits = [...after.entries()].filter(([, p]) => p.productId === product && p.enabled && p.action === 'usage_block');
194
+ if (limits.length > 1) {
195
+ errors.push(`More than one enabled ${product} spending limit would exist (${limits.map(([id]) => id).join(', ')}). ` +
196
+ 'Cloudflare allows one. Turn off or adopt the existing one explicitly — Quickback never replaces a foreign limit.');
197
+ }
198
+ }
199
+ const foreign = inputs.observed.filter((p) => !ownedIds.has(p.id) && !doc.policies.some((d) => d.adoptPolicyId === p.id));
200
+ if (foreign.length)
201
+ warnings.push(`${foreign.length} policy(ies) on this account are not owned by Quickback and will not be changed: ${foreign.map((p) => `${p.id} (${p.productId} ${p.action} ${formatCents(p.thresholdCents)})`).join('; ')}.`);
202
+ if (inputs.sharedTargets?.length)
203
+ warnings.push(`This account also hosts deployment targets: ${inputs.sharedTargets.join(', ')}. A spending limit stops all of them.`);
204
+ if (errors.length)
205
+ throw new Error(`Cannot plan:\n - ${errors.join('\n - ')}`);
206
+ const body = {
207
+ kind: 'quickback-platform-budget-plan',
208
+ version: 1,
209
+ source: 'document',
210
+ accountId: doc.accountId,
211
+ owner: doc.owner,
212
+ createdAt: (inputs.now ?? new Date()).toISOString(),
213
+ cfVersion: inputs.cfVersion,
214
+ observed: {
215
+ policies: inputs.observed.map((p) => {
216
+ const e = inputs.ownership.entries.find((o) => o.accountId === doc.accountId && o.policyId === p.id);
217
+ return e ? { ...p, ownedKey: `${e.owner}/${e.key}` } : p;
218
+ }),
219
+ spend: { status: 'unknown', reason: 'The cf CLI exposes no current-spend read. See `status` for recorded 80%/100% threshold events.' },
220
+ },
221
+ unchanged,
222
+ operations,
223
+ warnings,
224
+ };
225
+ return { ...body, digest: planDigest(body) };
226
+ }
227
+ /** Rollback = a new reviewed plan restoring each applied operation's before-state. */
228
+ export function buildRollbackPlan(applied, receipts, observed, ownership, cfVersion, now = new Date()) {
229
+ const errors = [];
230
+ const operations = [];
231
+ const byId = new Map(observed.map((p) => [p.id, p]));
232
+ const done = receipts.filter((r) => r.planDigest === applied.digest && (r.phase === 'done' || r.phase === 'reconciled'));
233
+ if (!done.length)
234
+ throw new Error(`No completed operations recorded for plan ${applied.digest}; nothing to roll back.`);
235
+ for (const r of [...done].reverse()) {
236
+ if (r.op === 'adopt')
237
+ continue; // ownership-only; no Cloudflare state to restore
238
+ const current = r.policyId ? byId.get(r.policyId) : undefined;
239
+ if (!current) {
240
+ errors.push(`${r.key}: policy ${r.policyId} no longer exists.`);
241
+ continue;
242
+ }
243
+ if (current.version !== r.returnedVersion) {
244
+ errors.push(`${r.key}: policy ${current.id} changed after this plan applied (version ${r.returnedVersion} → ${current.version}). Refusing to overwrite an intervening edit.`);
245
+ continue;
246
+ }
247
+ const owner = ownership.entries.find((e) => e.accountId === applied.accountId && e.policyId === current.id);
248
+ if (!owner || owner.owner !== applied.owner || owner.key !== r.key) {
249
+ errors.push(`${r.key}: ownership of ${current.id} no longer matches the receipt.`);
250
+ continue;
251
+ }
252
+ const before = inputOf(current);
253
+ // A created policy is turned off, not deleted: the receipt identity still matches, and off is reversible.
254
+ const input = r.op === 'create' ? { ...before, enabled: false } : r.before;
255
+ if (same(before, input))
256
+ continue;
257
+ operations.push({ op: 'update', key: r.key, policyId: current.id, expectedVersion: current.version, before, input, reason: 'rollback', consequences: consequencesFor(before, input) });
258
+ }
259
+ if (errors.length)
260
+ throw new Error(`Cannot build a rollback plan:\n - ${errors.join('\n - ')}`);
261
+ const body = {
262
+ kind: 'quickback-platform-budget-plan',
263
+ version: 1,
264
+ source: 'rollback',
265
+ accountId: applied.accountId,
266
+ owner: applied.owner,
267
+ createdAt: now.toISOString(),
268
+ cfVersion,
269
+ observed: { policies: observed, spend: { status: 'unknown', reason: 'The cf CLI exposes no current-spend read.' } },
270
+ unchanged: [],
271
+ operations,
272
+ warnings: [`Rolls back plan ${applied.digest}.`],
273
+ };
274
+ return { ...body, digest: planDigest(body) };
275
+ }
276
+ function upsertOwnership(m, entry) {
277
+ const entries = m.entries.filter((e) => !(e.accountId === entry.accountId && e.owner === entry.owner && e.key === entry.key));
278
+ return { version: 1, entries: [...entries, entry].sort((a, b) => `${a.accountId}/${a.owner}/${a.key}`.localeCompare(`${b.accountId}/${b.owner}/${b.key}`)) };
279
+ }
280
+ export async function applyPlan(plan, confirm, client, stateDir, io = nodeStateIO, log = () => { }) {
281
+ if (plan.kind !== 'quickback-platform-budget-plan' || plan.version !== 1)
282
+ throw new Error(`Not a Quickback platform budget plan: kind ${String(plan.kind)} version ${String(plan.version)} (expected quickback-platform-budget-plan version 1).`);
283
+ const computed = planDigest(plan);
284
+ if (computed !== plan.digest)
285
+ throw new Error(`Plan digest ${plan.digest} does not match its contents (${computed}) — the file was edited after review. Re-plan.`);
286
+ if (!confirm)
287
+ throw new Error(`Refusing to apply without --confirm ${plan.digest}.`);
288
+ if (confirm !== plan.digest)
289
+ throw new Error(`--confirm ${confirm} does not match the reviewed plan digest ${plan.digest}.`);
290
+ if (client.accountId !== plan.accountId)
291
+ throw new Error(`Plan targets account ${plan.accountId}, but the selected account is ${client.accountId}.`);
292
+ const ownershipPath = join(stateDir, 'ownership.json');
293
+ const receiptsPath = join(stateDir, 'receipts.jsonl');
294
+ let ownership = await readJsonOr(io, ownershipPath, { version: 1, entries: [] });
295
+ const receipts = (await readReceipts(io, stateDir)).filter((r) => r.planDigest === plan.digest);
296
+ const completed = new Map(receipts.filter((r) => r.phase === 'done' || r.phase === 'reconciled').map((r) => [r.key, r]));
297
+ // The latest receipt per key decides: a trailing `intent` is a mutation whose outcome is unknown.
298
+ const lastPhase = new Map(receipts.map((r) => [r.key, r.phase]));
299
+ const writeReceipt = async (r) => {
300
+ await io.appendFile(receiptsPath, `${JSON.stringify({ at: new Date().toISOString(), planDigest: plan.digest, accountId: plan.accountId, ...r })}\n`);
301
+ };
302
+ const recordOwnership = async (key, p) => {
303
+ ownership = upsertOwnership(ownership, { accountId: plan.accountId, owner: plan.owner, key, policyId: p.id, observedVersion: p.version, configHash: configHash(inputOf(p)) });
304
+ await io.writeFileAtomic(ownershipPath, `${JSON.stringify(ownership, null, 2)}\n`);
305
+ };
306
+ // Re-read every precondition before the first mutation.
307
+ const live = await client.list();
308
+ const byId = new Map(live.map((p) => [p.id, p]));
309
+ const result = { applied: [], skipped: [], remaining: [] };
310
+ const reconciled = new Map();
311
+ for (const op of plan.operations) {
312
+ const done = completed.get(op.key);
313
+ if (op.op === 'create') {
314
+ if (done)
315
+ continue;
316
+ if (lastPhase.get(op.key) === 'intent') {
317
+ // A create whose acknowledgement was lost: find it before retrying, or we would create a duplicate.
318
+ const ownedIds = new Set(ownership.entries.map((e) => e.policyId));
319
+ const matches = live.filter((p) => !ownedIds.has(p.id) && same(inputOf(p), op.input));
320
+ if (matches.length > 1)
321
+ throw new Error(`${op.key}: an earlier create has an unknown outcome and ${matches.length} matching policies exist (${matches.map((p) => p.id).join(', ')}). Reconcile with \`history\` before retrying.`);
322
+ if (matches.length === 1)
323
+ reconciled.set(op.key, matches[0]);
324
+ }
325
+ continue;
326
+ }
327
+ const current = byId.get(op.policyId);
328
+ if (done && current && current.version === done.returnedVersion)
329
+ continue; // already applied by this plan
330
+ if (!current)
331
+ throw new Error(`${op.key}: policy ${op.policyId} no longer exists. The plan is stale — re-plan.`);
332
+ if (current.version !== op.expectedVersion)
333
+ throw new Error(`${op.key}: policy ${op.policyId} is at version ${current.version}, the plan expected ${op.expectedVersion}. The plan is stale — re-plan and review.`);
334
+ const owner = ownership.entries.find((e) => e.accountId === plan.accountId && e.policyId === op.policyId);
335
+ const adopting = op.op === 'adopt' || (op.op === 'update' && op.adopt);
336
+ if (owner && (owner.owner !== plan.owner || owner.key !== op.key))
337
+ throw new Error(`${op.key}: policy ${op.policyId} is owned by ${owner.owner}/${owner.key}.`);
338
+ if (!owner && !adopting)
339
+ throw new Error(`${op.key}: policy ${op.policyId} is not owned by Quickback; refusing to change it.`);
340
+ }
341
+ for (const [index, op] of plan.operations.entries()) {
342
+ const done = completed.get(op.key);
343
+ if (done && (op.op === 'create' || byId.get(op.policyId)?.version === done.returnedVersion)) {
344
+ result.skipped.push(op.key);
345
+ continue;
346
+ }
347
+ const found = reconciled.get(op.key);
348
+ if (found) {
349
+ await writeReceipt({ key: op.key, op: op.op, phase: 'reconciled', policyId: found.id, after: inputOf(found), returnedVersion: found.version });
350
+ await recordOwnership(op.key, found);
351
+ log(`${pc.yellow('↺')} ${op.key}: earlier create found as ${found.id}; recorded, not re-created.`);
352
+ result.applied.push(op.key);
353
+ continue;
354
+ }
355
+ // Intent first: if this write fails, nothing has been sent to Cloudflare.
356
+ await writeReceipt({ key: op.key, op: op.op, phase: 'intent', ...(op.op !== 'create' ? { policyId: op.policyId, before: op.before } : {}), ...(op.op !== 'adopt' ? { after: op.input } : {}) });
357
+ let returned;
358
+ try {
359
+ returned = op.op === 'create'
360
+ ? await client.create(op.input)
361
+ : op.op === 'update'
362
+ ? await client.update(op.policyId, op.expectedVersion, op.input)
363
+ : byId.get(op.policyId);
364
+ }
365
+ catch (err) {
366
+ const message = redact(err.message);
367
+ // A create that failed with a clear HTTP error did not happen; anything else is unknown and reconciled next run.
368
+ const definite = err instanceof SpendPolicyError && err.kind !== 'unknown' && err.kind !== 'not_installed';
369
+ if (op.op !== 'create' || definite)
370
+ await writeReceipt({ key: op.key, op: op.op, phase: 'failed', error: message }).catch(() => { });
371
+ result.failed = { key: op.key, error: message };
372
+ result.remaining = plan.operations.slice(index + 1).map((o) => o.key);
373
+ return result;
374
+ }
375
+ try {
376
+ await writeReceipt({ key: op.key, op: op.op, phase: 'done', policyId: returned.id, ...(op.op !== 'create' ? { before: op.before } : {}), after: inputOf(returned), returnedVersion: returned.version });
377
+ await recordOwnership(op.key, returned);
378
+ }
379
+ catch (err) {
380
+ throw new Error(`${op.key}: Cloudflare ACCEPTED the change (policy ${returned.id}, version ${returned.version}) but the local receipt/ownership write failed: ` +
381
+ `${err.message}. Do not re-run until ${stateDir} is writable; the next apply reconciles from Cloudflare state.`);
382
+ }
383
+ log(`${pc.green('✓')} ${op.op} ${op.key} → ${returned.id} (version ${returned.version})`);
384
+ result.applied.push(op.key);
385
+ }
386
+ return result;
387
+ }
388
+ // ─── Rendering ─────────────────────────────────────────────────────────
389
+ const describe = (p) => `${p.productId} ${p.action === 'usage_block' ? 'LIMIT' : 'alert'} ${formatCents(p.thresholdCents)} ${p.enabled ? 'on' : 'off'}` +
390
+ `${p.notificationEmail ? ` → ${p.notificationEmail}` : ' (no email)'}`;
391
+ export function renderPlan(plan) {
392
+ const lines = [
393
+ `${pc.bold('Account')} ${plan.accountId} ${pc.bold('Owner')} ${plan.owner} ${pc.gray(`cf ${plan.cfVersion}`)}`,
394
+ pc.gray(SCOPE_NOTICE),
395
+ `Recorded spend: ${pc.yellow('unknown')} (${plan.observed.spend.reason})`,
396
+ '',
397
+ pc.bold('Existing policies on this account'),
398
+ ...(plan.observed.policies.length
399
+ ? plan.observed.policies.map((p) => ` ${p.id} v${p.version} ${describe(inputOf(p))} ${p.ownedKey ? pc.cyan(`owned ${p.ownedKey}`) : pc.yellow('not owned')}`)
400
+ : [' (none)']),
401
+ '',
402
+ pc.bold('Operations'),
403
+ ];
404
+ if (!plan.operations.length)
405
+ lines.push(' No changes.');
406
+ for (const op of plan.operations) {
407
+ if (op.op === 'create')
408
+ lines.push(` ${pc.green('+ create')} ${op.key}: ${describe(op.input)}`);
409
+ else if (op.op === 'adopt')
410
+ lines.push(` ${pc.cyan('= adopt')} ${op.key}: ${op.policyId} v${op.expectedVersion} ${describe(op.before)}`);
411
+ else
412
+ lines.push(` ${pc.yellow('~ update')} ${op.key}${op.adopt ? ' (adopt)' : ''} [${op.reason}]: ${op.policyId} v${op.expectedVersion}\n before ${describe(op.before)}\n after ${describe(op.input)}`);
413
+ for (const c of op.consequences)
414
+ lines.push(` ${pc.red('!')} ${c}`);
415
+ }
416
+ if (plan.unchanged.length)
417
+ lines.push(` unchanged: ${plan.unchanged.join(', ')}`);
418
+ for (const w of plan.warnings)
419
+ lines.push(`${pc.yellow('warning')} ${w}`);
420
+ lines.push('', `${pc.bold('Digest')} ${plan.digest}`);
421
+ return lines.join('\n');
422
+ }
423
+ const defaultCfRunner = (args, env) => runCommandCapture('cf', args, { env });
424
+ function printHelp(out) {
425
+ out(`
426
+ ${pc.bold('quickback platform budget')} — account-level Cloudflare spend policies
427
+
428
+ ${pc.bold('USAGE')}
429
+ quickback platform budget status (--account <id> | --env <target>) [--json]
430
+ quickback platform budget plan <budget.json> --out <plan.json> (--account <id> | --env <target>)
431
+ quickback platform budget apply <plan.json> --confirm <digest> (--account <id> | --env <target>)
432
+ quickback platform budget history (--account <id> | --env <target>) [--policy <id>] [--limit n] [--cursor c] [--json]
433
+ quickback platform budget rollback-plan <applied-plan.json> --out <plan.json> (--account <id> | --env <target>)
434
+
435
+ ${pc.bold('OPTIONS')}
436
+ ${pc.cyan('--state <dir>')} Operator state: ownership manifest + receipts (default .quickback/platform-budget)
437
+
438
+ ${SCOPE_NOTICE}
439
+ Requires the cf CLI with Account > Billing > Read (status/plan/history) or Edit (apply).
440
+ `);
441
+ }
442
+ function parseFlags(args) {
443
+ const valued = ['--account', '--env', '--out', '--confirm', '--state', '--policy', '--limit', '--cursor'];
444
+ const flags = { positional: [], values: {}, bools: new Set() };
445
+ for (let i = 0; i < args.length; i++) {
446
+ const a = args[i];
447
+ if (valued.includes(a)) {
448
+ if (flags.values[a] !== undefined || !args[i + 1] || args[i + 1].startsWith('-'))
449
+ throw new Error(`Provide one ${a} <value>.`);
450
+ flags.values[a] = args[++i];
451
+ }
452
+ else if (a === '--json' || a === '--help' || a === '-h')
453
+ flags.bools.add(a);
454
+ else if (a.startsWith('-'))
455
+ throw new Error(`Unknown platform budget option: ${a}`);
456
+ else
457
+ flags.positional.push(a);
458
+ }
459
+ return flags;
460
+ }
461
+ /** Resolve the account from an explicit flag only. Never the ambient profile. */
462
+ async function resolveAccount(flags, deps) {
463
+ const explicit = flags.values['--account'];
464
+ const env = flags.values['--env'];
465
+ if (explicit && env)
466
+ throw new Error('Pass --account or --env, not both.');
467
+ if (!explicit && !env) {
468
+ throw new Error('Refusing to run without an explicit account: pass --account <id> or --env <target>. ' +
469
+ 'Quickback never takes the account from your ambient cf/Wrangler login.');
470
+ }
471
+ if (explicit) {
472
+ if (!ACCOUNT_ID_RE.test(explicit))
473
+ throw new Error(`--account "${explicit}" is not a 32-character lowercase hex Cloudflare account id.`);
474
+ return { accountId: explicit, source: '--account', sharedTargets: [] };
475
+ }
476
+ const configPath = await (deps.findConfigPath ?? findConfigPath)();
477
+ if (!configPath)
478
+ throw new Error('--env needs a Quickback project (quickback.config.ts not found).');
479
+ const config = await (deps.loadConfig ?? loadConfig)(configPath);
480
+ const target = resolveDeploymentTarget(config, env);
481
+ if (!target.accountId)
482
+ throw new Error(`Target "${env}" declares no accountId (environments.${env}.accountId or providers.runtime.config.accountId). Pass --account explicitly.`);
483
+ if (!ACCOUNT_ID_RE.test(target.accountId))
484
+ throw new Error(`Target "${env}" accountId "${target.accountId}" is not a Cloudflare account id.`);
485
+ const sharedTargets = Object.entries(deploymentEnvironments(config) ?? {})
486
+ .filter(([name, e]) => name !== env && (e?.accountId ?? config.providers?.runtime?.config?.accountId) === target.accountId)
487
+ .map(([name]) => name);
488
+ return { accountId: target.accountId, source: `quickback.config.ts target "${env}"`, sharedTargets };
489
+ }
490
+ export async function platformBudget(args, deps = {}) {
491
+ const out = deps.out ?? ((s) => console.log(s));
492
+ const err = deps.err ?? ((s) => console.error(s));
493
+ const io = deps.io ?? nodeStateIO;
494
+ const flags = parseFlags(args);
495
+ const [sub, file] = flags.positional;
496
+ if (!sub || flags.bools.has('--help') || flags.bools.has('-h')) {
497
+ printHelp(out);
498
+ return 0;
499
+ }
500
+ if (!['status', 'plan', 'apply', 'history', 'rollback-plan'].includes(sub))
501
+ throw new Error(`Unknown platform budget command: ${sub}`);
502
+ const { accountId, source, sharedTargets } = await resolveAccount(flags, deps);
503
+ const json = flags.bools.has('--json');
504
+ // Target first, on stderr when stdout is JSON.
505
+ (json ? err : out)(`${pc.bold('Target account')} ${accountId} ${pc.gray(`(from ${source})`)}`);
506
+ const ambient = (deps.env ?? process.env).CLOUDFLARE_ACCOUNT_ID;
507
+ if (ambient && ambient !== accountId)
508
+ err(pc.yellow(`Ignoring ambient CLOUDFLARE_ACCOUNT_ID=${ambient}; every cf call is pinned to ${accountId}.`));
509
+ const client = new SpendPolicyClient(deps.cfRunner ?? defaultCfRunner, accountId, deps.env ?? process.env);
510
+ const stateDir = flags.values['--state'] ?? join('.quickback', 'platform-budget');
511
+ const readJson = async (path, what) => {
512
+ if (!path)
513
+ throw new Error(`Provide the ${what} file.`);
514
+ return JSON.parse(await io.readFile(path));
515
+ };
516
+ const writeOut = async (plan) => {
517
+ const outPath = flags.values['--out'];
518
+ if (!outPath)
519
+ throw new Error('Provide --out <plan.json>.');
520
+ await io.writeFileAtomic(outPath, `${JSON.stringify(plan, null, 2)}\n`);
521
+ out(renderPlan(plan));
522
+ out(`\nWrote ${outPath}. Review it, then:\n quickback platform budget apply ${outPath} --confirm ${plan.digest} --account ${accountId}`);
523
+ };
524
+ if (sub === 'status') {
525
+ const [cfVersion, policies] = [await client.version(), await client.list()];
526
+ const ownership = await readJsonOr(io, join(stateDir, 'ownership.json'), { version: 1, entries: [] });
527
+ const rows = [];
528
+ for (const p of policies) {
529
+ const owner = ownership.entries.find((e) => e.accountId === accountId && e.policyId === p.id);
530
+ const events = await client.audit(p.id, 5);
531
+ rows.push({ ...p, ownedKey: owner ? `${owner.owner}/${owner.key}` : undefined, latestThresholdEvent: events[0] ?? null });
532
+ }
533
+ const report = { accountId, cfVersion, spend: 'unknown', policies: rows, scope: SCOPE_NOTICE, outsideControls: OUTSIDE_CONTROLS,
534
+ note: 'Threshold events record evaluation (80% approaching_limit, 100% limit_reached), not confirmed blocking or email delivery. Enabled does not mean the product is running.' };
535
+ if (json) {
536
+ out(JSON.stringify(report, null, 2));
537
+ return 0;
538
+ }
539
+ out(pc.gray(SCOPE_NOTICE));
540
+ out(`Recorded spend: ${pc.yellow('unknown')} — cf exposes no current-spend read; latest threshold event per policy shown.`);
541
+ if (!rows.length)
542
+ out(' No spend policies on this account.');
543
+ for (const r of rows) {
544
+ out(` ${r.id} v${r.version} ${describe(inputOf(r))} ${r.ownedKey ? pc.cyan(`owned ${r.ownedKey}`) : pc.yellow('not owned')}`);
545
+ out(` latest threshold event: ${r.latestThresholdEvent ? JSON.stringify(r.latestThresholdEvent) : 'none recorded this period'}`);
546
+ }
547
+ out(pc.gray(report.note));
548
+ out(pc.gray(OUTSIDE_CONTROLS));
549
+ return 0;
550
+ }
551
+ if (sub === 'history') {
552
+ const policy = flags.values['--policy'];
553
+ const limit = flags.values['--limit'] ? Number(flags.values['--limit']) : undefined;
554
+ if (limit !== undefined && (!Number.isInteger(limit) || limit < 1 || limit > 100))
555
+ throw new Error('--limit must be 1-100.');
556
+ const result = policy
557
+ ? { kind: 'threshold-events', policyId: policy, entries: await client.audit(policy, limit) }
558
+ : { kind: 'configuration-changes', ...(await client.activity({ limit, cursor: flags.values['--cursor'] })) };
559
+ if (json) {
560
+ out(JSON.stringify(result, null, 2));
561
+ return 0;
562
+ }
563
+ out(policy ? `Threshold events for ${policy} (evaluations, not confirmed enforcement):` : 'Configuration changes (actor, before/after):');
564
+ for (const e of result.entries)
565
+ out(` ${JSON.stringify(e)}`);
566
+ if (!result.entries.length)
567
+ out(' (none)');
568
+ if ('cursor' in result && result.cursor)
569
+ out(`More: --cursor '${result.cursor}'`);
570
+ return 0;
571
+ }
572
+ if (sub === 'plan') {
573
+ const document = await readJson(file, 'budget document (budget.json)');
574
+ const doc = validateBudgetDocument(document);
575
+ if (doc.accountId !== accountId)
576
+ throw new Error(`The document targets account ${doc.accountId}, but the selected account is ${accountId}.`);
577
+ const ownership = await readJsonOr(io, join(stateDir, 'ownership.json'), { version: 1, entries: [] });
578
+ const plan = buildPlan({ document, observed: await client.list(), ownership, cfVersion: await client.version(), now: deps.now?.(), sharedTargets });
579
+ await writeOut(plan);
580
+ return 0;
581
+ }
582
+ if (sub === 'rollback-plan') {
583
+ const applied = await readJson(file, 'applied plan');
584
+ if (planDigest(applied) !== applied.digest)
585
+ throw new Error('The applied plan file does not match its digest.');
586
+ if (applied.accountId !== accountId)
587
+ throw new Error(`The plan targets account ${applied.accountId}, but the selected account is ${accountId}.`);
588
+ const ownership = await readJsonOr(io, join(stateDir, 'ownership.json'), { version: 1, entries: [] });
589
+ const plan = buildRollbackPlan(applied, await readReceipts(io, stateDir), await client.list(), ownership, await client.version(), deps.now?.());
590
+ await writeOut(plan);
591
+ return 0;
592
+ }
593
+ // apply
594
+ const plan = await readJson(file, 'plan');
595
+ out(pc.gray(SCOPE_NOTICE));
596
+ const result = await applyPlan(plan, flags.values['--confirm'], client, stateDir, io, out);
597
+ if (result.skipped.length)
598
+ out(`Already applied by this plan (skipped): ${result.skipped.join(', ')}`);
599
+ if (result.failed) {
600
+ err(pc.red(`✖ ${result.failed.key} failed: ${result.failed.error}`));
601
+ if (result.applied.length)
602
+ err(`Applied before the failure: ${result.applied.join(', ')}`);
603
+ if (result.remaining.length)
604
+ err(`Not attempted: ${result.remaining.join(', ')}`);
605
+ err('Re-run the same apply to resume (completed operations are skipped), or re-plan if the failure was a version conflict.');
606
+ return 1;
607
+ }
608
+ out(`Applied ${result.applied.length} operation(s). Read-back confirms configuration only; enforcement and email delivery are observed separately (status/history).`);
609
+ return 0;
610
+ }
611
+ /** `quickback platform <area> ...` */
612
+ export async function platform(args, deps = {}) {
613
+ const [area, ...rest] = args;
614
+ if (area === 'budget')
615
+ return platformBudget(rest, deps);
616
+ (deps.out ?? console.log)(`Usage: quickback platform budget <status|plan|apply|history|rollback-plan>`);
617
+ return area && area !== '--help' && area !== '-h' ? 1 : 0;
618
+ }
619
+ //# sourceMappingURL=platform-budget.js.map