ultra-builder-pro-cli 0.25.1 → 0.26.1

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 (243) hide show
  1. package/.ultra-template/changes/abandoned/.gitkeep +0 -0
  2. package/.ultra-template/contexts/TEMPLATE.md +94 -0
  3. package/.ultra-template/decisions/.gitkeep +1 -0
  4. package/.ultra-template/evidence/.gitkeep +1 -0
  5. package/.ultra-template/north-star.md +46 -0
  6. package/.ultra-template/research/.gitkeep +1 -0
  7. package/.ultra-template/specs/discovery.md +2 -2
  8. package/.ultra-template/tasks.json +3 -0
  9. package/.ultra-template/test-report.json +27 -0
  10. package/CHANGELOG.md +107 -1
  11. package/README.md +217 -579
  12. package/adapters/_shared/delegate-profiles/kimi-read-only.md +15 -0
  13. package/adapters/_shared/delegate-profiles/kimi-write.md +17 -0
  14. package/adapters/_shared/file-ops.cjs +76 -2
  15. package/adapters/_shared/host-profile.cjs +97 -0
  16. package/adapters/_shared/plugin-core.cjs +204 -0
  17. package/adapters/_shared/runtime-assets.cjs +31 -96
  18. package/adapters/claude.js +92 -291
  19. package/adapters/codex.js +309 -842
  20. package/adapters/grok.js +143 -1469
  21. package/adapters/kimi.js +124 -1053
  22. package/adapters/opencode.js +230 -742
  23. package/bin/delegate-worker.cjs +328 -0
  24. package/bin/delegate.cjs +463 -0
  25. package/bin/install.js +38 -11
  26. package/docs/ARCHITECTURE.md +125 -216
  27. package/docs/ARTIFACT-AUTHORITY.md +90 -268
  28. package/docs/DECISIONS.md +77 -87
  29. package/docs/PHILOSOPHY.md +208 -0
  30. package/docs/PLUGIN-ISOLATION-CONTRACT.md +65 -39
  31. package/docs/RUNTIME-COMPAT-MATRIX.md +140 -155
  32. package/docs/SKILL-AUTHORING.md +94 -73
  33. package/docs/WORKFLOW-LIFECYCLE.md +97 -189
  34. package/hooks/README.md +19 -37
  35. package/hooks/_common.py +113 -0
  36. package/hooks/adapters/codex.py +9 -16
  37. package/hooks/adapters/grok.py +5 -5
  38. package/hooks/adapters/kimi.py +8 -14
  39. package/hooks/block_dangerous_commands.py +201 -0
  40. package/hooks/compact_context.py +65 -0
  41. package/hooks/mid_workflow_recall.py +25 -0
  42. package/hooks/post_edit_guard.py +105 -0
  43. package/hooks/session_context.py +30 -0
  44. package/package.json +17 -52
  45. package/skills/ultra-change/SKILL.md +115 -50
  46. package/skills/ultra-change/references/change-contract.md +68 -3
  47. package/skills/ultra-delegate/SKILL.md +89 -0
  48. package/skills/ultra-delegate/references/delegation-contract.md +59 -0
  49. package/skills/ultra-delegate/scripts/delegate_wait.py +86 -0
  50. package/skills/ultra-deliver/SKILL.md +98 -42
  51. package/skills/ultra-deliver/references/baseline-reconciliation.md +39 -20
  52. package/skills/ultra-dev/SKILL.md +115 -62
  53. package/skills/ultra-dev/references/debugging.md +22 -0
  54. package/skills/ultra-domain-modeling/SKILL.md +79 -0
  55. package/skills/ultra-grilling/SKILL.md +118 -0
  56. package/skills/ultra-grilling/references/reframing.md +72 -0
  57. package/skills/ultra-init/SKILL.md +102 -37
  58. package/skills/ultra-init/references/brownfield-adoption.md +33 -83
  59. package/skills/ultra-init/scripts/init_project.cjs +84 -0
  60. package/skills/ultra-plan/SKILL.md +101 -68
  61. package/skills/ultra-research/SKILL.md +68 -48
  62. package/skills/ultra-research/references/00-problem-validation.md +5 -5
  63. package/skills/ultra-research/references/01-opportunity-discovery.md +3 -3
  64. package/skills/ultra-research/references/02-market-assessment.md +5 -4
  65. package/skills/ultra-research/references/03-competitive-landscape.md +3 -3
  66. package/skills/ultra-research/references/04-product-strategy.md +3 -3
  67. package/skills/ultra-research/references/05-assumptions-validation.md +5 -5
  68. package/skills/ultra-research/references/10-user-personas.md +3 -2
  69. package/skills/ultra-research/references/11-user-scenarios.md +3 -3
  70. package/skills/ultra-research/references/20-user-stories.md +4 -3
  71. package/skills/ultra-research/references/21-features-scope.md +3 -2
  72. package/skills/ultra-research/references/22-success-metrics.md +3 -3
  73. package/skills/ultra-research/references/30-architecture-context.md +3 -3
  74. package/skills/ultra-research/references/31-solution-strategy.md +3 -3
  75. package/skills/ultra-research/references/32-building-blocks.md +3 -3
  76. package/skills/ultra-research/references/40-deployment.md +3 -3
  77. package/skills/ultra-research/references/41-quality-risks.md +3 -3
  78. package/skills/ultra-research/references/99-synthesis.md +7 -7
  79. package/skills/ultra-review/SKILL.md +84 -32
  80. package/skills/ultra-review/references/code.md +17 -0
  81. package/skills/ultra-review/references/comments.md +12 -0
  82. package/skills/ultra-review/references/design.md +12 -0
  83. package/skills/ultra-review/references/errors.md +13 -0
  84. package/skills/ultra-review/references/spec.md +13 -0
  85. package/skills/ultra-review/references/tests.md +12 -0
  86. package/skills/ultra-review/references/worker-packet.md +40 -0
  87. package/skills/ultra-review/scripts/review_wait.py +26 -15
  88. package/skills/ultra-status/SKILL.md +61 -36
  89. package/skills/ultra-tdd/SKILL.md +81 -0
  90. package/skills/ultra-tdd/references/templates/README.md +20 -0
  91. package/skills/ultra-tdd/references/templates/feature-flag-default-audit.sh +79 -0
  92. package/skills/ultra-tdd/references/templates/persistence-real.ts +78 -0
  93. package/skills/ultra-tdd/references/templates/testcontainer-postgres.py +78 -0
  94. package/skills/ultra-tdd/references/templates/testcontainer-postgres.ts +73 -0
  95. package/skills/ultra-tdd/references/templates/vertical-slice.ts +66 -0
  96. package/skills/ultra-tdd/references/test-execution.md +18 -0
  97. package/skills/ultra-test/SKILL.md +75 -30
  98. package/skills/ultra-test/references/export-syntax.md +18 -0
  99. package/skills/ultra-test/scripts/worktree_digest.cjs +54 -0
  100. package/skills/ultra-think/SKILL.md +49 -27
  101. package/skills/ultra-think/references/autonomy-boundary.md +48 -0
  102. package/skills/ultra-think/references/interaction-boundary.md +18 -33
  103. package/.ultra-template/docs/research/README.md +0 -55
  104. package/.ultra-template/reports/templates/delivery-report.json +0 -17
  105. package/.ultra-template/reports/templates/test-report.json +0 -18
  106. package/.ultra-template/tasks/tasks.json +0 -15
  107. package/.ultra-template/templates/task-context.md +0 -19
  108. package/adapters/_shared/codex-assets.cjs +0 -725
  109. package/adapters/_shared/codex-ultra-tools-entry.cjs +0 -11
  110. package/adapters/_shared/interaction-contract.cjs +0 -129
  111. package/adapters/_shared/path-rewrite.cjs +0 -79
  112. package/adapters/_shared/runtime-native.cjs +0 -132
  113. package/adapters/_shared/settings-merge.cjs +0 -76
  114. package/agents/code-reviewer.md +0 -42
  115. package/agents/debugger.md +0 -40
  116. package/agents/review-code.md +0 -49
  117. package/agents/review-comments.md +0 -38
  118. package/agents/review-coordinator.md +0 -56
  119. package/agents/review-design.md +0 -40
  120. package/agents/review-errors.md +0 -43
  121. package/agents/review-spec.md +0 -39
  122. package/agents/review-tests.md +0 -40
  123. package/agents/tdd-runner.md +0 -38
  124. package/bin/orchestrator.js +0 -383
  125. package/commands/ultra-change.md +0 -10
  126. package/commands/ultra-deliver.md +0 -10
  127. package/commands/ultra-dev.md +0 -10
  128. package/commands/ultra-doctor.md +0 -10
  129. package/commands/ultra-init.md +0 -10
  130. package/commands/ultra-plan.md +0 -10
  131. package/commands/ultra-research.md +0 -10
  132. package/commands/ultra-review.md +0 -10
  133. package/commands/ultra-status.md +0 -10
  134. package/commands/ultra-test.md +0 -10
  135. package/commands/ultra-think.md +0 -10
  136. package/docs/AGENT-CONTEXT.md +0 -191
  137. package/docs/COMMIT-HASH-BACKFILL.md +0 -51
  138. package/docs/LEGACY-CLI-CROSSWALK.md +0 -175
  139. package/docs/ROADMAP.md +0 -101
  140. package/docs/STATE-DB-ACCESS-POLICY.md +0 -161
  141. package/hooks/active_task_context.py +0 -152
  142. package/hooks/context_envelope.py +0 -100
  143. package/hooks/health_check.py +0 -196
  144. package/hooks/pre_stop_check.py +0 -66
  145. package/hooks/runtime_paths.py +0 -396
  146. package/hooks/subagent_tracker.py +0 -88
  147. package/hooks/workflow_checkpoint.py +0 -76
  148. package/hooks/workflow_context.py +0 -48
  149. package/hooks/workflow_resume.py +0 -84
  150. package/mcp-server/hook-context.cjs +0 -38
  151. package/mcp-server/hook-event.cjs +0 -34
  152. package/mcp-server/lib/archive-journal.cjs +0 -1119
  153. package/mcp-server/lib/archive-mutation-worker.py +0 -365
  154. package/mcp-server/lib/artifact-registry.cjs +0 -1232
  155. package/mcp-server/lib/baseline-workflow.cjs +0 -1193
  156. package/mcp-server/lib/canonical-json.cjs +0 -19
  157. package/mcp-server/lib/change-authority.cjs +0 -26
  158. package/mcp-server/lib/change-packet.cjs +0 -790
  159. package/mcp-server/lib/change-workflow.cjs +0 -65
  160. package/mcp-server/lib/context-envelope.cjs +0 -581
  161. package/mcp-server/lib/context-paths.cjs +0 -142
  162. package/mcp-server/lib/decision-records.cjs +0 -423
  163. package/mcp-server/lib/delivery-transaction.cjs +0 -471
  164. package/mcp-server/lib/doctor-backup-worker.cjs +0 -328
  165. package/mcp-server/lib/doctor.cjs +0 -627
  166. package/mcp-server/lib/git-bootstrap.cjs +0 -651
  167. package/mcp-server/lib/init-project.cjs +0 -1021
  168. package/mcp-server/lib/kernel-change-workflow.cjs +0 -2029
  169. package/mcp-server/lib/legacy-change-workflow.cjs +0 -3032
  170. package/mcp-server/lib/managed-file-write.cjs +0 -172
  171. package/mcp-server/lib/plan-checkpoint.cjs +0 -177
  172. package/mcp-server/lib/plan-publication-worker.cjs +0 -830
  173. package/mcp-server/lib/plan-store.cjs +0 -794
  174. package/mcp-server/lib/prd-parser.cjs +0 -83
  175. package/mcp-server/lib/pricing.cjs +0 -44
  176. package/mcp-server/lib/project-context.cjs +0 -178
  177. package/mcp-server/lib/projector.cjs +0 -386
  178. package/mcp-server/lib/provider-refs.cjs +0 -42
  179. package/mcp-server/lib/runtime-paths.cjs +0 -1714
  180. package/mcp-server/lib/runtime-state.cjs +0 -222
  181. package/mcp-server/lib/safe-project-file.cjs +0 -385
  182. package/mcp-server/lib/stage-checkpoints.cjs +0 -463
  183. package/mcp-server/lib/state-authority.cjs +0 -95
  184. package/mcp-server/lib/state-db.cjs +0 -1580
  185. package/mcp-server/lib/state-ops.cjs +0 -1428
  186. package/mcp-server/lib/task-contract.cjs +0 -404
  187. package/mcp-server/lib/task-expander.cjs +0 -105
  188. package/mcp-server/lib/task-ledger.cjs +0 -1964
  189. package/mcp-server/lib/telemetry.cjs +0 -85
  190. package/mcp-server/lib/topo.cjs +0 -131
  191. package/mcp-server/lib/ultra-facade.cjs +0 -2684
  192. package/mcp-server/lib/worker-packet.cjs +0 -358
  193. package/mcp-server/server.cjs +0 -437
  194. package/orchestrator/auto-merge.cjs +0 -128
  195. package/orchestrator/daemon.cjs +0 -264
  196. package/orchestrator/dispatch-rules.cjs +0 -78
  197. package/orchestrator/parallel-orchestrator.cjs +0 -903
  198. package/orchestrator/planner/plan-builder.cjs +0 -125
  199. package/orchestrator/recovery.cjs +0 -188
  200. package/orchestrator/session-close-journal-worker.cjs +0 -5
  201. package/orchestrator/session-close-journal.cjs +0 -1014
  202. package/orchestrator/session-runner.cjs +0 -1153
  203. package/orchestrator/worktree-manager.cjs +0 -282
  204. package/settings.json +0 -7
  205. package/skills/cc-collab/SKILL.md +0 -42
  206. package/skills/code-review-expert/SKILL.md +0 -43
  207. package/skills/code-review-expert/references/correctness-reliability.md +0 -30
  208. package/skills/code-review-expert/references/design-boundaries.md +0 -26
  209. package/skills/code-review-expert/references/removal-plan.md +0 -24
  210. package/skills/codex-collab/SKILL.md +0 -49
  211. package/skills/codex-collab/evals/evals.json +0 -35
  212. package/skills/integration-rules/SKILL.md +0 -32
  213. package/skills/security-rules/SKILL.md +0 -38
  214. package/skills/testing-rules/SKILL.md +0 -32
  215. package/skills/ultra-doctor/SKILL.md +0 -41
  216. package/skills/ultra-plan/references/semantic-preflight.md +0 -20
  217. package/skills/ultra-verify/SKILL.md +0 -46
  218. package/skills/ultra-verify/evals/evals.json +0 -46
  219. package/skills/ultra-verify/references/cross-verify-modes.md +0 -28
  220. package/skills/ultra-verify/references/evidence-status.md +0 -21
  221. package/skills/ultra-verify/scripts/verify_wait.py +0 -94
  222. package/spec/cli-protocol.md +0 -102
  223. package/spec/mcp-tools.yaml +0 -312
  224. package/spec/schemas/baseline-reconciliation.v1.schema.json +0 -73
  225. package/spec/schemas/change-delta.v1.schema.json +0 -153
  226. package/spec/schemas/command-manifest.schema.json +0 -29
  227. package/spec/schemas/context-file.v4.5.schema.json +0 -54
  228. package/spec/schemas/delivery-report.v1.schema.json +0 -66
  229. package/spec/schemas/documentation-reconciliation.v1.schema.json +0 -106
  230. package/spec/schemas/mcp-tools.schema.json +0 -136
  231. package/spec/schemas/skill-manifest.schema.json +0 -24
  232. package/spec/schemas/state-db.sql +0 -641
  233. package/spec/schemas/task-ledger.v2.schema.json +0 -296
  234. package/spec/schemas/tasks.v4.5.schema.json +0 -96
  235. package/spec/schemas/test-report.v1.schema.json +0 -225
  236. package/ultra-tools/cli.cjs +0 -129
  237. package/ultra-tools/commands/db.cjs +0 -226
  238. package/ultra-tools/commands/legacy-memory.cjs +0 -159
  239. package/ultra-tools/commands/migrate.cjs +0 -1386
  240. package/ultra-tools/commands/session.cjs +0 -213
  241. package/ultra-tools/commands/status.cjs +0 -559
  242. package/ultra-tools/commands/system.cjs +0 -498
  243. package/ultra-tools/commands/task.cjs +0 -105
@@ -1,463 +0,0 @@
1
- 'use strict';
2
-
3
- const crypto = require('node:crypto');
4
-
5
- const ops = require('./state-ops.cjs');
6
- const canonical = require('./canonical-json.cjs');
7
-
8
- const STAGES = new Set(['init', 'research', 'change', 'plan', 'dev', 'test', 'review', 'deliver']);
9
- const SCOPE_KEYS = Object.freeze([
10
- ['task_id', 'task'],
11
- ['change_id', 'change'],
12
- ['baseline_id', 'baseline'],
13
- ['project_id', 'project'],
14
- ]);
15
-
16
- class StageCheckpointError extends Error {
17
- constructor(code, message, details) {
18
- super(message);
19
- this.name = 'StageCheckpointError';
20
- this.code = code;
21
- if (details) this.details = details;
22
- }
23
- }
24
-
25
- function parseJson(value, fallback) {
26
- try { return value == null ? fallback : JSON.parse(value); }
27
- catch { return fallback; }
28
- }
29
-
30
- function normalizeScope(scope = {}) {
31
- const matches = SCOPE_KEYS.filter(([key]) => (
32
- typeof scope[key] === 'string' && scope[key].trim()
33
- ));
34
- if (matches.length !== 1) {
35
- throw new StageCheckpointError(
36
- 'VALIDATION_ERROR',
37
- 'checkpoint scope must contain exactly one of project_id, baseline_id, change_id, or task_id',
38
- );
39
- }
40
- const [key, type] = matches[0];
41
- return { type, id: scope[key].trim() };
42
- }
43
-
44
- function validateStage(stage) {
45
- if (!STAGES.has(stage)) {
46
- throw new StageCheckpointError('VALIDATION_ERROR', `unsupported checkpoint stage: ${stage}`);
47
- }
48
- }
49
-
50
- function normalizeDiagnostics(value) {
51
- if (!Array.isArray(value)) {
52
- throw new StageCheckpointError('VALIDATION_ERROR', 'diagnostics must be an array');
53
- }
54
- return value.map((item, index) => {
55
- if (!item || typeof item !== 'object' || Array.isArray(item)) {
56
- throw new StageCheckpointError('VALIDATION_ERROR', `diagnostics[${index}] must be an object`);
57
- }
58
- if (typeof item.code !== 'string' || !item.code.trim()) {
59
- throw new StageCheckpointError('VALIDATION_ERROR', `diagnostics[${index}].code is required`);
60
- }
61
- const code = item.code.trim();
62
- const severity = item.severity || 'needs_attention';
63
- if (!['warning', 'needs_attention', 'hard_conflict'].includes(severity)) {
64
- throw new StageCheckpointError(
65
- 'VALIDATION_ERROR',
66
- `diagnostics[${index}].severity is invalid`,
67
- );
68
- }
69
- if (item.message !== undefined && typeof item.message !== 'string') {
70
- throw new StageCheckpointError(
71
- 'VALIDATION_ERROR',
72
- `diagnostics[${index}].message must be a string`,
73
- );
74
- }
75
- return {
76
- code,
77
- severity,
78
- ...(item.message ? { message: item.message } : {}),
79
- ...(item.details === undefined ? {} : { details: item.details }),
80
- };
81
- });
82
- }
83
-
84
- function normalizePayload(value) {
85
- if (!value || typeof value !== 'object' || Array.isArray(value)) {
86
- throw new StageCheckpointError('VALIDATION_ERROR', 'checkpoint payload must be an object');
87
- }
88
- return value;
89
- }
90
-
91
- function normalizeEvidence(value) {
92
- if (!Array.isArray(value)) {
93
- throw new StageCheckpointError('VALIDATION_ERROR', 'evidence must be an array');
94
- }
95
- return value.map((item, index) => {
96
- if (!item || typeof item !== 'object' || Array.isArray(item)) {
97
- throw new StageCheckpointError('VALIDATION_ERROR', `evidence[${index}] must be an object`);
98
- }
99
- return item;
100
- });
101
- }
102
-
103
- function idempotencyConflict(idempotencyKey, priorDigest, requestedDigest) {
104
- return new StageCheckpointError(
105
- 'IDEMPOTENCY_KEY_CONFLICT',
106
- `idempotency key ${idempotencyKey} was already used for another checkpoint request`,
107
- {
108
- idempotency_key: idempotencyKey,
109
- prior_request_digest: priorDigest,
110
- requested_request_digest: requestedDigest,
111
- },
112
- );
113
- }
114
-
115
- function draftRequestDigest({
116
- stage,
117
- scopeType,
118
- scopeId,
119
- payload,
120
- }) {
121
- const requestPayload = stage === 'plan' && payload && typeof payload === 'object'
122
- ? Object.fromEntries(Object.entries(payload).filter(([key]) => key !== 'plan'))
123
- : payload;
124
- return canonical.digest({
125
- operation: 'checkpoint:draft',
126
- stage,
127
- scope_type: scopeType,
128
- scope_id: scopeId,
129
- payload: requestPayload,
130
- });
131
- }
132
-
133
- function checkpointDraftRequestDigest(checkpoint) {
134
- return draftRequestDigest({
135
- stage: checkpoint.stage,
136
- scopeType: checkpoint.scope_type,
137
- scopeId: checkpoint.scope_id,
138
- payload: checkpoint.payload,
139
- });
140
- }
141
-
142
- function checkpointDigest(value) {
143
- return canonical.digest({
144
- stage: value.stage,
145
- scope_type: value.scope_type,
146
- scope_id: value.scope_id,
147
- revision: value.revision,
148
- payload: value.payload,
149
- evidence: value.evidence,
150
- diagnostics: value.diagnostics,
151
- context_envelope_id: value.context_envelope_id || null,
152
- supersedes_id: value.supersedes_id || null,
153
- });
154
- }
155
-
156
- function rowToCheckpoint(row) {
157
- if (!row) return null;
158
- const checkpoint = {
159
- id: row.id,
160
- stage: row.stage,
161
- scope: { [`${row.scope_type}_id`]: row.scope_id },
162
- scope_type: row.scope_type,
163
- scope_id: row.scope_id,
164
- revision: row.revision,
165
- status: row.status,
166
- payload: parseJson(row.payload_json, {}),
167
- evidence: parseJson(row.evidence_json, []),
168
- diagnostics: parseJson(row.diagnostics_json, []),
169
- context_envelope_id: row.context_envelope_id,
170
- digest: row.digest,
171
- supersedes_id: row.supersedes_id,
172
- idempotency_key: row.idempotency_key,
173
- created_at: row.created_at,
174
- updated_at: row.updated_at,
175
- accepted_at: row.accepted_at,
176
- };
177
- const actual = checkpointDigest(checkpoint);
178
- if (actual !== checkpoint.digest) {
179
- throw new StageCheckpointError(
180
- 'CHECKPOINT_DIGEST_MISMATCH',
181
- `Stage Checkpoint database authority is corrupt: ${checkpoint.id}`,
182
- { expected: checkpoint.digest, actual },
183
- );
184
- }
185
- return checkpoint;
186
- }
187
-
188
- function readCheckpoint(db, id) {
189
- return rowToCheckpoint(db.prepare('SELECT * FROM stage_checkpoints WHERE id = ?').get(id));
190
- }
191
-
192
- function listCheckpoints(db, { stage, scope, status, limit = 100 } = {}) {
193
- const clauses = [];
194
- const params = [];
195
- if (stage) { validateStage(stage); clauses.push('stage = ?'); params.push(stage); }
196
- if (scope) {
197
- const normalized = normalizeScope(scope);
198
- clauses.push('scope_type = ?', 'scope_id = ?');
199
- params.push(normalized.type, normalized.id);
200
- }
201
- if (status) { clauses.push('status = ?'); params.push(status); }
202
- const bounded = Math.min(Math.max(Number(limit) || 100, 1), 500);
203
- return db.prepare(
204
- `SELECT * FROM stage_checkpoints
205
- ${clauses.length ? `WHERE ${clauses.join(' AND ')}` : ''}
206
- ORDER BY stage, scope_type, scope_id, revision DESC
207
- LIMIT ?`,
208
- ).all(...params, bounded).map(rowToCheckpoint);
209
- }
210
-
211
- function existingByIdempotency(db, idempotencyKey) {
212
- if (!idempotencyKey) return null;
213
- return rowToCheckpoint(
214
- db.prepare('SELECT * FROM stage_checkpoints WHERE idempotency_key = ?').get(idempotencyKey),
215
- );
216
- }
217
-
218
- function findIdempotentDraft(db, input = {}) {
219
- validateStage(input.stage);
220
- const scope = normalizeScope(input.scope);
221
- const idempotencyKey = String(input.idempotency_key || '').trim();
222
- if (!idempotencyKey) {
223
- throw new StageCheckpointError('VALIDATION_ERROR', 'idempotency_key is required');
224
- }
225
- const existing = existingByIdempotency(db, idempotencyKey);
226
- if (!existing) return null;
227
- const requestedDigest = draftRequestDigest({
228
- stage: input.stage,
229
- scopeType: scope.type,
230
- scopeId: scope.id,
231
- payload: normalizePayload(input.payload),
232
- });
233
- const priorDigest = checkpointDraftRequestDigest(existing);
234
- if (priorDigest !== requestedDigest) {
235
- throw idempotencyConflict(idempotencyKey, priorDigest, requestedDigest);
236
- }
237
- return existing;
238
- }
239
-
240
- function saveDraft(db, input = {}) {
241
- validateStage(input.stage);
242
- const scope = normalizeScope(input.scope);
243
- const idempotencyKey = String(input.idempotency_key || '').trim();
244
- if (!idempotencyKey) {
245
- throw new StageCheckpointError('VALIDATION_ERROR', 'idempotency_key is required');
246
- }
247
- const payload = normalizePayload(input.payload);
248
- const evidence = normalizeEvidence(input.evidence);
249
- const diagnostics = normalizeDiagnostics(input.diagnostics);
250
- const requestedDigest = draftRequestDigest({
251
- stage: input.stage,
252
- scopeType: scope.type,
253
- scopeId: scope.id,
254
- payload,
255
- });
256
- const existingRetry = existingByIdempotency(db, idempotencyKey);
257
- if (existingRetry) {
258
- const priorDigest = checkpointDraftRequestDigest(existingRetry);
259
- if (priorDigest !== requestedDigest) {
260
- throw idempotencyConflict(idempotencyKey, priorDigest, requestedDigest);
261
- }
262
- return existingRetry;
263
- }
264
- return ops.tx(db, () => {
265
- const draft = db.prepare(
266
- `SELECT * FROM stage_checkpoints
267
- WHERE stage = ? AND scope_type = ? AND scope_id = ? AND status = 'draft'
268
- ORDER BY revision DESC LIMIT 1`,
269
- ).get(input.stage, scope.type, scope.id);
270
- if (draft) {
271
- const value = {
272
- stage: input.stage,
273
- scope_type: scope.type,
274
- scope_id: scope.id,
275
- revision: draft.revision,
276
- payload,
277
- evidence,
278
- diagnostics,
279
- context_envelope_id: input.context_envelope_id || null,
280
- supersedes_id: draft.supersedes_id,
281
- };
282
- const digest = checkpointDigest(value);
283
- db.prepare(
284
- `UPDATE stage_checkpoints
285
- SET payload_json = ?, evidence_json = ?, diagnostics_json = ?,
286
- context_envelope_id = ?, digest = ?, idempotency_key = ?,
287
- updated_at = strftime('%Y-%m-%dT%H:%M:%fZ', 'now')
288
- WHERE id = ?`,
289
- ).run(
290
- JSON.stringify(payload),
291
- JSON.stringify(evidence),
292
- JSON.stringify(diagnostics),
293
- input.context_envelope_id || null,
294
- digest,
295
- idempotencyKey,
296
- draft.id,
297
- );
298
- return readCheckpoint(db, draft.id);
299
- }
300
- const accepted = db.prepare(
301
- `SELECT id, revision FROM stage_checkpoints
302
- WHERE stage = ? AND scope_type = ? AND scope_id = ? AND status = 'accepted'
303
- ORDER BY revision DESC LIMIT 1`,
304
- ).get(input.stage, scope.type, scope.id);
305
- const revision = (accepted?.revision || 0) + 1;
306
- const id = `checkpoint-${crypto.randomUUID()}`;
307
- const value = {
308
- stage: input.stage,
309
- scope_type: scope.type,
310
- scope_id: scope.id,
311
- revision,
312
- payload,
313
- evidence,
314
- diagnostics,
315
- context_envelope_id: input.context_envelope_id || null,
316
- supersedes_id: accepted?.id || null,
317
- };
318
- db.prepare(
319
- `INSERT INTO stage_checkpoints
320
- (id, stage, scope_type, scope_id, revision, payload_json, evidence_json,
321
- diagnostics_json, context_envelope_id, digest, supersedes_id, idempotency_key)
322
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
323
- ).run(
324
- id,
325
- input.stage,
326
- scope.type,
327
- scope.id,
328
- revision,
329
- JSON.stringify(payload),
330
- JSON.stringify(evidence),
331
- JSON.stringify(diagnostics),
332
- input.context_envelope_id || null,
333
- checkpointDigest(value),
334
- accepted?.id || null,
335
- idempotencyKey,
336
- );
337
- return readCheckpoint(db, id);
338
- });
339
- }
340
-
341
- function acceptanceReceipt(db, idempotencyKey) {
342
- if (!idempotencyKey) return null;
343
- const rows = db.prepare(
344
- `SELECT payload_json FROM events
345
- WHERE type = 'ultra_checkpoint_accepted'
346
- ORDER BY id DESC`,
347
- ).all();
348
- for (const row of rows) {
349
- const payload = parseJson(row.payload_json, {});
350
- if (payload.idempotency_key === idempotencyKey) return payload;
351
- }
352
- return null;
353
- }
354
-
355
- function acceptanceReceiptForCheckpoint(db, checkpointId) {
356
- const rows = db.prepare(
357
- `SELECT payload_json FROM events
358
- WHERE type = 'ultra_checkpoint_accepted'
359
- ORDER BY id DESC`,
360
- ).all();
361
- for (const row of rows) {
362
- const payload = parseJson(row.payload_json, {});
363
- if (payload.checkpoint_id === checkpointId && payload.idempotency_key) return payload;
364
- }
365
- return null;
366
- }
367
-
368
- function acceptDraft(db, input = {}) {
369
- const idempotencyKey = String(input.idempotency_key || '').trim();
370
- if (!idempotencyKey) {
371
- throw new StageCheckpointError('VALIDATION_ERROR', 'idempotency_key is required');
372
- }
373
- return ops.tx(db, () => {
374
- const row = db.prepare('SELECT * FROM stage_checkpoints WHERE id = ?').get(input.id);
375
- if (!row) throw new StageCheckpointError('CHECKPOINT_NOT_FOUND', `checkpoint not found: ${input.id}`);
376
- const checkpoint = rowToCheckpoint(row);
377
- const requestedDigest = canonical.digest({
378
- operation: 'checkpoint:accept',
379
- checkpoint_id: checkpoint.id,
380
- checkpoint_digest: checkpoint.digest,
381
- });
382
- const prior = acceptanceReceipt(db, idempotencyKey);
383
- if (prior) {
384
- if (prior.request_digest !== requestedDigest) {
385
- throw idempotencyConflict(
386
- idempotencyKey,
387
- prior.request_digest || null,
388
- requestedDigest,
389
- );
390
- }
391
- return checkpoint;
392
- }
393
- if (row.status === 'accepted') {
394
- const checkpointReceipt = acceptanceReceiptForCheckpoint(db, checkpoint.id);
395
- if (checkpointReceipt) {
396
- throw idempotencyConflict(
397
- idempotencyKey,
398
- checkpointReceipt.request_digest || null,
399
- requestedDigest,
400
- );
401
- }
402
- return checkpoint;
403
- }
404
- if (row.status !== 'draft') {
405
- throw new StageCheckpointError(
406
- 'CHECKPOINT_NOT_MUTABLE',
407
- `checkpoint ${input.id} is ${row.status}`,
408
- );
409
- }
410
- if (row.supersedes_id) {
411
- db.prepare(
412
- `UPDATE stage_checkpoints SET status = 'superseded',
413
- updated_at = strftime('%Y-%m-%dT%H:%M:%fZ', 'now')
414
- WHERE id = ? AND status = 'accepted'`,
415
- ).run(row.supersedes_id);
416
- }
417
- db.prepare(
418
- `UPDATE stage_checkpoints
419
- SET status = 'accepted', accepted_at = strftime('%Y-%m-%dT%H:%M:%fZ', 'now'),
420
- updated_at = strftime('%Y-%m-%dT%H:%M:%fZ', 'now')
421
- WHERE id = ?`,
422
- ).run(row.id);
423
- const accepted = readCheckpoint(db, row.id);
424
- ops.appendEventInTx(db, {
425
- type: 'ultra_checkpoint_accepted',
426
- change_id: accepted.scope_type === 'change' ? accepted.scope_id : null,
427
- task_id: accepted.scope_type === 'task' ? accepted.scope_id : null,
428
- payload: {
429
- checkpoint_id: accepted.id,
430
- stage: accepted.stage,
431
- revision: accepted.revision,
432
- digest: accepted.digest,
433
- idempotency_key: idempotencyKey,
434
- request_digest: requestedDigest,
435
- },
436
- });
437
- return accepted;
438
- });
439
- }
440
-
441
- function currentCheckpoint(db, stage, scope, { includeDraft = true } = {}) {
442
- validateStage(stage);
443
- const normalized = normalizeScope(scope);
444
- const statuses = includeDraft ? "('draft','accepted')" : "('accepted')";
445
- return rowToCheckpoint(db.prepare(
446
- `SELECT * FROM stage_checkpoints
447
- WHERE stage = ? AND scope_type = ? AND scope_id = ? AND status IN ${statuses}
448
- ORDER BY CASE status WHEN 'draft' THEN 0 ELSE 1 END, revision DESC LIMIT 1`,
449
- ).get(stage, normalized.type, normalized.id));
450
- }
451
-
452
- module.exports = {
453
- StageCheckpointError,
454
- STAGES,
455
- normalizeScope,
456
- readCheckpoint,
457
- listCheckpoints,
458
- saveDraft,
459
- findIdempotentDraft,
460
- acceptDraft,
461
- currentCheckpoint,
462
- checkpointDigest,
463
- };
@@ -1,95 +0,0 @@
1
- 'use strict';
2
-
3
- const fs = require('node:fs');
4
- const path = require('node:path');
5
- const taskLedger = require('./task-ledger.cjs');
6
-
7
- class StateAuthorityError extends Error {
8
- constructor(code, message, details) {
9
- super(message);
10
- this.code = code;
11
- this.retriable = false;
12
- this.details = details;
13
- }
14
- }
15
-
16
- function inspectProjection(rootDir) {
17
- const projectionPath = path.join(rootDir, '.ultra', 'tasks', 'tasks.json');
18
- if (!fs.existsSync(projectionPath)) return null;
19
- let projection;
20
- try {
21
- projection = JSON.parse(fs.readFileSync(projectionPath, 'utf8'));
22
- } catch (error) {
23
- throw new StateAuthorityError(
24
- 'STATE_PROJECTION_INVALID',
25
- `cannot validate ${projectionPath}: ${error.message}`,
26
- { projection_path: projectionPath },
27
- );
28
- }
29
- if (!projection || !Array.isArray(projection.tasks)) {
30
- throw new StateAuthorityError(
31
- 'STATE_PROJECTION_INVALID',
32
- `${projectionPath} does not contain a tasks array`,
33
- { projection_path: projectionPath },
34
- );
35
- }
36
- if (projection.kind === taskLedger.LEDGER_KIND) {
37
- const ledger = taskLedger.validateLedger(projection, projectionPath);
38
- return {
39
- path: projectionPath,
40
- version: ledger.schema_version,
41
- kind: ledger.kind,
42
- taskCount: ledger.tasks.length,
43
- };
44
- }
45
- return {
46
- path: projectionPath,
47
- version: String(projection.version || projection.schema_version || 'unknown'),
48
- kind: 'legacy-task-projection',
49
- taskCount: projection.tasks.length,
50
- };
51
- }
52
-
53
- function assertStateAuthority(db, rootDir, { importTeamLedger = false } = {}) {
54
- const authoritativeCount = db.prepare('SELECT COUNT(*) AS count FROM tasks').get().count;
55
- const projection = inspectProjection(rootDir);
56
- if (projection?.kind === taskLedger.LEDGER_KIND) {
57
- return importTeamLedger
58
- ? taskLedger.syncTaskLedger(db, { rootDir })
59
- : taskLedger.inspectTaskLedger(db, { rootDir });
60
- }
61
- if (authoritativeCount > 0 || !projection || projection.taskCount === 0) return null;
62
-
63
- const details = {
64
- authoritative_task_count: authoritativeCount,
65
- legacy_task_count: projection.taskCount,
66
- projection_path: projection.path,
67
- projection_version: projection.version,
68
- projection_kind: projection.kind,
69
- };
70
- const migrationTargets = {
71
- '4.4': '4.5',
72
- '4.5': '12.0',
73
- };
74
- const migrationTarget = migrationTargets[projection.version];
75
- if (migrationTarget) {
76
- throw new StateAuthorityError(
77
- 'LEGACY_STATE_MIGRATION_REQUIRED',
78
- `state.db has no tasks but ${projection.path} contains ${projection.taskCount} v${projection.version} tasks; `
79
- + `run ultra-tools migrate --from=${projection.version} --to=${migrationTarget} `
80
- + '--source-dir <project-root> before using Ultra MCP tools',
81
- details,
82
- );
83
- }
84
- throw new StateAuthorityError(
85
- 'STATE_AUTHORITY_CONFLICT',
86
- `state.db has no tasks but ${projection.path} contains ${projection.taskCount} tasks; refusing projection fallback`,
87
- details,
88
- );
89
- }
90
-
91
- module.exports = {
92
- StateAuthorityError,
93
- inspectProjection,
94
- assertStateAuthority,
95
- };