ultra-builder-pro-cli 0.25.1 → 0.26.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 (241) hide show
  1. package/.ultra-template/contexts/TEMPLATE.md +87 -0
  2. package/.ultra-template/decisions/.gitkeep +1 -0
  3. package/.ultra-template/evidence/.gitkeep +1 -0
  4. package/.ultra-template/north-star.md +46 -0
  5. package/.ultra-template/research/.gitkeep +1 -0
  6. package/.ultra-template/specs/discovery.md +2 -2
  7. package/.ultra-template/tasks.json +3 -0
  8. package/.ultra-template/test-report.json +27 -0
  9. package/CHANGELOG.md +40 -0
  10. package/README.md +217 -579
  11. package/adapters/_shared/delegate-profiles/kimi-read-only.md +15 -0
  12. package/adapters/_shared/delegate-profiles/kimi-write.md +17 -0
  13. package/adapters/_shared/file-ops.cjs +76 -2
  14. package/adapters/_shared/host-profile.cjs +97 -0
  15. package/adapters/_shared/plugin-core.cjs +204 -0
  16. package/adapters/_shared/runtime-assets.cjs +31 -96
  17. package/adapters/claude.js +92 -291
  18. package/adapters/codex.js +309 -842
  19. package/adapters/grok.js +143 -1469
  20. package/adapters/kimi.js +124 -1053
  21. package/adapters/opencode.js +230 -742
  22. package/bin/delegate-worker.cjs +323 -0
  23. package/bin/delegate.cjs +456 -0
  24. package/bin/install.js +38 -11
  25. package/docs/ARCHITECTURE.md +122 -216
  26. package/docs/ARTIFACT-AUTHORITY.md +90 -268
  27. package/docs/DECISIONS.md +75 -87
  28. package/docs/PHILOSOPHY.md +177 -0
  29. package/docs/PLUGIN-ISOLATION-CONTRACT.md +62 -39
  30. package/docs/RUNTIME-COMPAT-MATRIX.md +99 -156
  31. package/docs/SKILL-AUTHORING.md +94 -73
  32. package/docs/WORKFLOW-LIFECYCLE.md +93 -189
  33. package/hooks/README.md +17 -37
  34. package/hooks/_common.py +113 -0
  35. package/hooks/adapters/codex.py +9 -16
  36. package/hooks/adapters/grok.py +5 -5
  37. package/hooks/adapters/kimi.py +8 -14
  38. package/hooks/block_dangerous_commands.py +95 -0
  39. package/hooks/compact_context.py +65 -0
  40. package/hooks/mid_workflow_recall.py +25 -0
  41. package/hooks/post_edit_guard.py +105 -0
  42. package/hooks/session_context.py +30 -0
  43. package/package.json +17 -52
  44. package/skills/ultra-change/SKILL.md +97 -50
  45. package/skills/ultra-change/references/change-contract.md +40 -1
  46. package/skills/ultra-delegate/SKILL.md +82 -0
  47. package/skills/ultra-delegate/references/delegation-contract.md +51 -0
  48. package/skills/ultra-delegate/scripts/delegate_wait.py +86 -0
  49. package/skills/ultra-deliver/SKILL.md +61 -42
  50. package/skills/ultra-deliver/references/baseline-reconciliation.md +39 -20
  51. package/skills/ultra-dev/SKILL.md +96 -62
  52. package/skills/ultra-dev/references/debugging.md +22 -0
  53. package/skills/ultra-domain-modeling/SKILL.md +79 -0
  54. package/skills/ultra-grilling/SKILL.md +79 -0
  55. package/skills/ultra-init/SKILL.md +94 -37
  56. package/skills/ultra-init/references/brownfield-adoption.md +33 -83
  57. package/skills/ultra-init/scripts/init_project.cjs +84 -0
  58. package/skills/ultra-plan/SKILL.md +88 -68
  59. package/skills/ultra-research/SKILL.md +62 -48
  60. package/skills/ultra-research/references/00-problem-validation.md +5 -5
  61. package/skills/ultra-research/references/01-opportunity-discovery.md +3 -3
  62. package/skills/ultra-research/references/02-market-assessment.md +5 -4
  63. package/skills/ultra-research/references/03-competitive-landscape.md +3 -3
  64. package/skills/ultra-research/references/04-product-strategy.md +3 -3
  65. package/skills/ultra-research/references/05-assumptions-validation.md +5 -5
  66. package/skills/ultra-research/references/10-user-personas.md +3 -2
  67. package/skills/ultra-research/references/11-user-scenarios.md +3 -3
  68. package/skills/ultra-research/references/20-user-stories.md +4 -3
  69. package/skills/ultra-research/references/21-features-scope.md +3 -2
  70. package/skills/ultra-research/references/22-success-metrics.md +3 -3
  71. package/skills/ultra-research/references/30-architecture-context.md +3 -3
  72. package/skills/ultra-research/references/31-solution-strategy.md +3 -3
  73. package/skills/ultra-research/references/32-building-blocks.md +3 -3
  74. package/skills/ultra-research/references/40-deployment.md +3 -3
  75. package/skills/ultra-research/references/41-quality-risks.md +3 -3
  76. package/skills/ultra-research/references/99-synthesis.md +7 -7
  77. package/skills/ultra-review/SKILL.md +59 -32
  78. package/skills/ultra-review/references/code.md +17 -0
  79. package/skills/ultra-review/references/comments.md +12 -0
  80. package/skills/ultra-review/references/design.md +12 -0
  81. package/skills/ultra-review/references/errors.md +13 -0
  82. package/skills/ultra-review/references/spec.md +13 -0
  83. package/skills/ultra-review/references/tests.md +12 -0
  84. package/skills/ultra-review/references/worker-packet.md +40 -0
  85. package/skills/ultra-review/scripts/review_wait.py +26 -15
  86. package/skills/ultra-status/SKILL.md +61 -36
  87. package/skills/ultra-tdd/SKILL.md +81 -0
  88. package/skills/ultra-tdd/references/templates/README.md +20 -0
  89. package/skills/ultra-tdd/references/templates/feature-flag-default-audit.sh +79 -0
  90. package/skills/ultra-tdd/references/templates/persistence-real.ts +78 -0
  91. package/skills/ultra-tdd/references/templates/testcontainer-postgres.py +78 -0
  92. package/skills/ultra-tdd/references/templates/testcontainer-postgres.ts +73 -0
  93. package/skills/ultra-tdd/references/templates/vertical-slice.ts +66 -0
  94. package/skills/ultra-tdd/references/test-execution.md +18 -0
  95. package/skills/ultra-test/SKILL.md +70 -30
  96. package/skills/ultra-test/references/export-syntax.md +18 -0
  97. package/skills/ultra-test/scripts/worktree_digest.cjs +54 -0
  98. package/skills/ultra-think/SKILL.md +49 -27
  99. package/skills/ultra-think/references/autonomy-boundary.md +48 -0
  100. package/skills/ultra-think/references/interaction-boundary.md +18 -33
  101. package/.ultra-template/docs/research/README.md +0 -55
  102. package/.ultra-template/reports/templates/delivery-report.json +0 -17
  103. package/.ultra-template/reports/templates/test-report.json +0 -18
  104. package/.ultra-template/tasks/tasks.json +0 -15
  105. package/.ultra-template/templates/task-context.md +0 -19
  106. package/adapters/_shared/codex-assets.cjs +0 -725
  107. package/adapters/_shared/codex-ultra-tools-entry.cjs +0 -11
  108. package/adapters/_shared/interaction-contract.cjs +0 -129
  109. package/adapters/_shared/path-rewrite.cjs +0 -79
  110. package/adapters/_shared/runtime-native.cjs +0 -132
  111. package/adapters/_shared/settings-merge.cjs +0 -76
  112. package/agents/code-reviewer.md +0 -42
  113. package/agents/debugger.md +0 -40
  114. package/agents/review-code.md +0 -49
  115. package/agents/review-comments.md +0 -38
  116. package/agents/review-coordinator.md +0 -56
  117. package/agents/review-design.md +0 -40
  118. package/agents/review-errors.md +0 -43
  119. package/agents/review-spec.md +0 -39
  120. package/agents/review-tests.md +0 -40
  121. package/agents/tdd-runner.md +0 -38
  122. package/bin/orchestrator.js +0 -383
  123. package/commands/ultra-change.md +0 -10
  124. package/commands/ultra-deliver.md +0 -10
  125. package/commands/ultra-dev.md +0 -10
  126. package/commands/ultra-doctor.md +0 -10
  127. package/commands/ultra-init.md +0 -10
  128. package/commands/ultra-plan.md +0 -10
  129. package/commands/ultra-research.md +0 -10
  130. package/commands/ultra-review.md +0 -10
  131. package/commands/ultra-status.md +0 -10
  132. package/commands/ultra-test.md +0 -10
  133. package/commands/ultra-think.md +0 -10
  134. package/docs/AGENT-CONTEXT.md +0 -191
  135. package/docs/COMMIT-HASH-BACKFILL.md +0 -51
  136. package/docs/LEGACY-CLI-CROSSWALK.md +0 -175
  137. package/docs/ROADMAP.md +0 -101
  138. package/docs/STATE-DB-ACCESS-POLICY.md +0 -161
  139. package/hooks/active_task_context.py +0 -152
  140. package/hooks/context_envelope.py +0 -100
  141. package/hooks/health_check.py +0 -196
  142. package/hooks/pre_stop_check.py +0 -66
  143. package/hooks/runtime_paths.py +0 -396
  144. package/hooks/subagent_tracker.py +0 -88
  145. package/hooks/workflow_checkpoint.py +0 -76
  146. package/hooks/workflow_context.py +0 -48
  147. package/hooks/workflow_resume.py +0 -84
  148. package/mcp-server/hook-context.cjs +0 -38
  149. package/mcp-server/hook-event.cjs +0 -34
  150. package/mcp-server/lib/archive-journal.cjs +0 -1119
  151. package/mcp-server/lib/archive-mutation-worker.py +0 -365
  152. package/mcp-server/lib/artifact-registry.cjs +0 -1232
  153. package/mcp-server/lib/baseline-workflow.cjs +0 -1193
  154. package/mcp-server/lib/canonical-json.cjs +0 -19
  155. package/mcp-server/lib/change-authority.cjs +0 -26
  156. package/mcp-server/lib/change-packet.cjs +0 -790
  157. package/mcp-server/lib/change-workflow.cjs +0 -65
  158. package/mcp-server/lib/context-envelope.cjs +0 -581
  159. package/mcp-server/lib/context-paths.cjs +0 -142
  160. package/mcp-server/lib/decision-records.cjs +0 -423
  161. package/mcp-server/lib/delivery-transaction.cjs +0 -471
  162. package/mcp-server/lib/doctor-backup-worker.cjs +0 -328
  163. package/mcp-server/lib/doctor.cjs +0 -627
  164. package/mcp-server/lib/git-bootstrap.cjs +0 -651
  165. package/mcp-server/lib/init-project.cjs +0 -1021
  166. package/mcp-server/lib/kernel-change-workflow.cjs +0 -2029
  167. package/mcp-server/lib/legacy-change-workflow.cjs +0 -3032
  168. package/mcp-server/lib/managed-file-write.cjs +0 -172
  169. package/mcp-server/lib/plan-checkpoint.cjs +0 -177
  170. package/mcp-server/lib/plan-publication-worker.cjs +0 -830
  171. package/mcp-server/lib/plan-store.cjs +0 -794
  172. package/mcp-server/lib/prd-parser.cjs +0 -83
  173. package/mcp-server/lib/pricing.cjs +0 -44
  174. package/mcp-server/lib/project-context.cjs +0 -178
  175. package/mcp-server/lib/projector.cjs +0 -386
  176. package/mcp-server/lib/provider-refs.cjs +0 -42
  177. package/mcp-server/lib/runtime-paths.cjs +0 -1714
  178. package/mcp-server/lib/runtime-state.cjs +0 -222
  179. package/mcp-server/lib/safe-project-file.cjs +0 -385
  180. package/mcp-server/lib/stage-checkpoints.cjs +0 -463
  181. package/mcp-server/lib/state-authority.cjs +0 -95
  182. package/mcp-server/lib/state-db.cjs +0 -1580
  183. package/mcp-server/lib/state-ops.cjs +0 -1428
  184. package/mcp-server/lib/task-contract.cjs +0 -404
  185. package/mcp-server/lib/task-expander.cjs +0 -105
  186. package/mcp-server/lib/task-ledger.cjs +0 -1964
  187. package/mcp-server/lib/telemetry.cjs +0 -85
  188. package/mcp-server/lib/topo.cjs +0 -131
  189. package/mcp-server/lib/ultra-facade.cjs +0 -2684
  190. package/mcp-server/lib/worker-packet.cjs +0 -358
  191. package/mcp-server/server.cjs +0 -437
  192. package/orchestrator/auto-merge.cjs +0 -128
  193. package/orchestrator/daemon.cjs +0 -264
  194. package/orchestrator/dispatch-rules.cjs +0 -78
  195. package/orchestrator/parallel-orchestrator.cjs +0 -903
  196. package/orchestrator/planner/plan-builder.cjs +0 -125
  197. package/orchestrator/recovery.cjs +0 -188
  198. package/orchestrator/session-close-journal-worker.cjs +0 -5
  199. package/orchestrator/session-close-journal.cjs +0 -1014
  200. package/orchestrator/session-runner.cjs +0 -1153
  201. package/orchestrator/worktree-manager.cjs +0 -282
  202. package/settings.json +0 -7
  203. package/skills/cc-collab/SKILL.md +0 -42
  204. package/skills/code-review-expert/SKILL.md +0 -43
  205. package/skills/code-review-expert/references/correctness-reliability.md +0 -30
  206. package/skills/code-review-expert/references/design-boundaries.md +0 -26
  207. package/skills/code-review-expert/references/removal-plan.md +0 -24
  208. package/skills/codex-collab/SKILL.md +0 -49
  209. package/skills/codex-collab/evals/evals.json +0 -35
  210. package/skills/integration-rules/SKILL.md +0 -32
  211. package/skills/security-rules/SKILL.md +0 -38
  212. package/skills/testing-rules/SKILL.md +0 -32
  213. package/skills/ultra-doctor/SKILL.md +0 -41
  214. package/skills/ultra-plan/references/semantic-preflight.md +0 -20
  215. package/skills/ultra-verify/SKILL.md +0 -46
  216. package/skills/ultra-verify/evals/evals.json +0 -46
  217. package/skills/ultra-verify/references/cross-verify-modes.md +0 -28
  218. package/skills/ultra-verify/references/evidence-status.md +0 -21
  219. package/skills/ultra-verify/scripts/verify_wait.py +0 -94
  220. package/spec/cli-protocol.md +0 -102
  221. package/spec/mcp-tools.yaml +0 -312
  222. package/spec/schemas/baseline-reconciliation.v1.schema.json +0 -73
  223. package/spec/schemas/change-delta.v1.schema.json +0 -153
  224. package/spec/schemas/command-manifest.schema.json +0 -29
  225. package/spec/schemas/context-file.v4.5.schema.json +0 -54
  226. package/spec/schemas/delivery-report.v1.schema.json +0 -66
  227. package/spec/schemas/documentation-reconciliation.v1.schema.json +0 -106
  228. package/spec/schemas/mcp-tools.schema.json +0 -136
  229. package/spec/schemas/skill-manifest.schema.json +0 -24
  230. package/spec/schemas/state-db.sql +0 -641
  231. package/spec/schemas/task-ledger.v2.schema.json +0 -296
  232. package/spec/schemas/tasks.v4.5.schema.json +0 -96
  233. package/spec/schemas/test-report.v1.schema.json +0 -225
  234. package/ultra-tools/cli.cjs +0 -129
  235. package/ultra-tools/commands/db.cjs +0 -226
  236. package/ultra-tools/commands/legacy-memory.cjs +0 -159
  237. package/ultra-tools/commands/migrate.cjs +0 -1386
  238. package/ultra-tools/commands/session.cjs +0 -213
  239. package/ultra-tools/commands/status.cjs +0 -559
  240. package/ultra-tools/commands/system.cjs +0 -498
  241. package/ultra-tools/commands/task.cjs +0 -105
@@ -1,142 +0,0 @@
1
- 'use strict';
2
-
3
- const fs = require('node:fs');
4
- const path = require('node:path');
5
-
6
- const CONTEXT_ROOT_RELATIVE = '.ultra/.runtime/projections/contexts';
7
- const LEGACY_CONTEXT_ROOT_RELATIVE = '.ultra/tasks/contexts';
8
- const GENERATED_BY = 'ultra-projector';
9
-
10
- class ContextPathError extends Error {
11
- constructor(message, details = undefined) {
12
- super(message);
13
- this.name = 'ContextPathError';
14
- this.code = 'CONTEXT_PATH_INVALID';
15
- if (details !== undefined) this.details = details;
16
- }
17
- }
18
-
19
- function invalid(value, reason) {
20
- throw new ContextPathError(`invalid task context path ${JSON.stringify(value)}: ${reason}`, {
21
- path: value == null ? null : String(value),
22
- reason,
23
- });
24
- }
25
-
26
- function assertNoSymlinkAncestors(root, relative, original) {
27
- let current = root;
28
- const components = relative.split('/');
29
- for (let index = 0; index < components.length; index += 1) {
30
- current = path.join(current, components[index]);
31
- let stat;
32
- try {
33
- stat = fs.lstatSync(current);
34
- } catch (error) {
35
- if (error.code === 'ENOENT') continue;
36
- invalid(original, `cannot inspect ${components.slice(0, index + 1).join('/')}`);
37
- }
38
- if (stat.isSymbolicLink()) {
39
- invalid(original, `symbolic link ancestor is not allowed: ${components.slice(0, index + 1).join('/')}`);
40
- }
41
- if (index < components.length - 1 && !stat.isDirectory()) {
42
- invalid(original, `non-directory ancestor: ${components.slice(0, index + 1).join('/')}`);
43
- }
44
- }
45
- }
46
-
47
- function assertRealContainment(root, file, original) {
48
- if (!fs.existsSync(root)) return;
49
- const realRoot = fs.realpathSync(root);
50
- let existing = file;
51
- while (!fs.existsSync(existing) && existing !== root) existing = path.dirname(existing);
52
- const realExisting = fs.realpathSync(existing);
53
- if (realExisting !== realRoot && !realExisting.startsWith(`${realRoot}${path.sep}`)) {
54
- invalid(original, 'resolved path escapes the project root');
55
- }
56
- }
57
-
58
- function resolveContextPath(rootDir, value, {
59
- taskId,
60
- allowLegacyAliases = false,
61
- } = {}) {
62
- const root = path.resolve(rootDir || '.');
63
- const defaultValue = taskId == null
64
- ? null
65
- : `${CONTEXT_ROOT_RELATIVE}/task-${taskId}.md`;
66
- const original = value || defaultValue;
67
- if (typeof original !== 'string' || original.trim() === '' || original.includes('\0')) {
68
- invalid(original, 'a non-empty path is required');
69
- }
70
-
71
- let raw;
72
- if (path.isAbsolute(original)) {
73
- raw = path.relative(root, path.resolve(original)).split(path.sep).join('/');
74
- if (raw === '..' || raw.startsWith('../')) invalid(original, 'absolute path escapes the project');
75
- } else {
76
- raw = original.trim().replaceAll('\\', '/').replace(/^\.\//, '');
77
- }
78
- if (raw.split('/').includes('..')) invalid(original, 'parent traversal is not allowed');
79
-
80
- if (allowLegacyAliases && raw.startsWith('contexts/')) {
81
- raw = `${LEGACY_CONTEXT_ROOT_RELATIVE}/${raw.slice('contexts/'.length)}`;
82
- } else if (allowLegacyAliases && !raw.includes('/')) {
83
- raw = `${LEGACY_CONTEXT_ROOT_RELATIVE}/${raw}`;
84
- }
85
- if (raw.startsWith(`${LEGACY_CONTEXT_ROOT_RELATIVE}/`)) {
86
- raw = `${CONTEXT_ROOT_RELATIVE}/${raw.slice(LEGACY_CONTEXT_ROOT_RELATIVE.length + 1)}`;
87
- }
88
-
89
- const relative = path.posix.normalize(raw);
90
- if (!relative.startsWith(`${CONTEXT_ROOT_RELATIVE}/`)
91
- || relative === `${CONTEXT_ROOT_RELATIVE}/`
92
- || relative.endsWith('/')) {
93
- invalid(original, `path must be a file below ${CONTEXT_ROOT_RELATIVE}`);
94
- }
95
- const file = path.resolve(root, ...relative.split('/'));
96
- const contextRoot = path.resolve(root, ...CONTEXT_ROOT_RELATIVE.split('/'));
97
- if (!file.startsWith(`${contextRoot}${path.sep}`)) {
98
- invalid(original, `path escapes ${CONTEXT_ROOT_RELATIVE}`);
99
- }
100
- assertNoSymlinkAncestors(root, relative, original);
101
- assertRealContainment(root, file, original);
102
- return { root, contextRoot, relative, file };
103
- }
104
-
105
- function resolveLegacyContextPath(rootDir, value, { taskId } = {}) {
106
- const root = path.resolve(rootDir || '.');
107
- const original = value || `${LEGACY_CONTEXT_ROOT_RELATIVE}/task-${taskId}.md`;
108
- if (typeof original !== 'string' || original.trim() === '' || original.includes('\0')) {
109
- invalid(original, 'a non-empty legacy path is required');
110
- }
111
- if (path.isAbsolute(original)) invalid(original, 'legacy paths must be project-relative');
112
- const raw = original.trim().replaceAll('\\', '/').replace(/^\.\//, '');
113
- if (raw.split('/').includes('..')) invalid(original, 'parent traversal is not allowed');
114
- const relative = path.posix.normalize(raw);
115
- if (!relative.startsWith(`${LEGACY_CONTEXT_ROOT_RELATIVE}/`)
116
- || relative === `${LEGACY_CONTEXT_ROOT_RELATIVE}/`
117
- || relative.endsWith('/')) {
118
- invalid(original, `legacy path must be a file below ${LEGACY_CONTEXT_ROOT_RELATIVE}`);
119
- }
120
- const file = path.resolve(root, ...relative.split('/'));
121
- const contextRoot = path.resolve(root, ...LEGACY_CONTEXT_ROOT_RELATIVE.split('/'));
122
- if (!file.startsWith(`${contextRoot}${path.sep}`)) {
123
- invalid(original, `legacy path escapes ${LEGACY_CONTEXT_ROOT_RELATIVE}`);
124
- }
125
- assertNoSymlinkAncestors(root, relative, original);
126
- assertRealContainment(root, file, original);
127
- return { root, contextRoot, relative, file };
128
- }
129
-
130
- function isGeneratedContextContents(contents) {
131
- return new RegExp(`^generated_by:\\s*${GENERATED_BY}\\s*$`, 'm').test(String(contents));
132
- }
133
-
134
- module.exports = {
135
- CONTEXT_ROOT_RELATIVE,
136
- LEGACY_CONTEXT_ROOT_RELATIVE,
137
- GENERATED_BY,
138
- ContextPathError,
139
- isGeneratedContextContents,
140
- resolveContextPath,
141
- resolveLegacyContextPath,
142
- };
@@ -1,423 +0,0 @@
1
- 'use strict';
2
-
3
- const canonical = require('./canonical-json.cjs');
4
- const artifactRegistry = require('./artifact-registry.cjs');
5
- const ops = require('./state-ops.cjs');
6
- const {
7
- restoreManagedFile,
8
- snapshotManagedFile,
9
- writeManagedJson,
10
- } = require('./managed-file-write.cjs');
11
- const { readStableProjectFile } = require('./safe-project-file.cjs');
12
-
13
- const DECISION_FIELDS = new Set([
14
- 'id', 'scope', 'question', 'recommendation', 'selection', 'effects',
15
- 'non_goals', 'owner', 'source', 'provenance', 'applied_refs', 'supersedes_id',
16
- ]);
17
-
18
- class DecisionRecordError extends Error {
19
- constructor(code, message, details) {
20
- super(message);
21
- this.name = 'DecisionRecordError';
22
- this.code = code;
23
- if (details) this.details = details;
24
- }
25
- }
26
-
27
- function requiredText(value, field) {
28
- const normalized = typeof value === 'string' ? value.trim() : '';
29
- if (!normalized) throw new DecisionRecordError('VALIDATION_ERROR', `${field} is required`);
30
- return normalized;
31
- }
32
-
33
- function assertExactFields(value, allowed, field) {
34
- if (!value || typeof value !== 'object' || Array.isArray(value)) {
35
- throw new DecisionRecordError('VALIDATION_ERROR', `${field} must be an object`);
36
- }
37
- const unknown = Object.keys(value).filter((key) => !allowed.has(key));
38
- if (unknown.length > 0) {
39
- throw new DecisionRecordError(
40
- 'VALIDATION_ERROR', `${field}.${unknown[0]} is not allowed`,
41
- );
42
- }
43
- }
44
-
45
- function assertJsonValue(value, field, seen = new Set()) {
46
- if (value === null || typeof value === 'string' || typeof value === 'boolean') return;
47
- if (typeof value === 'number') {
48
- if (Number.isFinite(value)) return;
49
- throw new DecisionRecordError('VALIDATION_ERROR', `${field} must contain valid JSON values`);
50
- }
51
- if (typeof value !== 'object') {
52
- throw new DecisionRecordError('VALIDATION_ERROR', `${field} must contain valid JSON values`);
53
- }
54
- if (seen.has(value)) {
55
- throw new DecisionRecordError('VALIDATION_ERROR', `${field} must not contain circular references`);
56
- }
57
- if (!Array.isArray(value)) {
58
- const prototype = Object.getPrototypeOf(value);
59
- if (prototype !== Object.prototype && prototype !== null) {
60
- throw new DecisionRecordError(
61
- 'VALIDATION_ERROR', `${field} must contain only JSON objects`,
62
- );
63
- }
64
- }
65
- seen.add(value);
66
- if (Array.isArray(value)) {
67
- value.forEach((item, index) => assertJsonValue(item, `${field}[${index}]`, seen));
68
- } else {
69
- Object.entries(value).forEach(([key, item]) => (
70
- assertJsonValue(item, `${field}.${key}`, seen)
71
- ));
72
- }
73
- seen.delete(value);
74
- }
75
-
76
- function plainObject(value, field) {
77
- if (value === undefined) return {};
78
- if (!value || typeof value !== 'object' || Array.isArray(value)) {
79
- throw new DecisionRecordError('VALIDATION_ERROR', `${field} must be an object`);
80
- }
81
- assertJsonValue(value, field);
82
- return JSON.parse(JSON.stringify(value));
83
- }
84
-
85
- function stringArray(value, field) {
86
- if (value === undefined) return [];
87
- if (!Array.isArray(value)) {
88
- throw new DecisionRecordError('VALIDATION_ERROR', `${field} must be an array`);
89
- }
90
- return value.map((item, index) => requiredText(item, `${field}[${index}]`));
91
- }
92
-
93
- function normalizeScope(scope = {}) {
94
- assertExactFields(scope, new Set(['baseline_id', 'change_id']), 'scope');
95
- const baseline = typeof scope.baseline_id === 'string' ? scope.baseline_id.trim() : '';
96
- const change = typeof scope.change_id === 'string' ? scope.change_id.trim() : '';
97
- if (Boolean(baseline) === Boolean(change)) {
98
- throw new DecisionRecordError(
99
- 'VALIDATION_ERROR',
100
- 'decision scope must contain exactly one of baseline_id or change_id',
101
- );
102
- }
103
- return baseline
104
- ? { type: 'baseline', id: baseline }
105
- : { type: 'change', id: change };
106
- }
107
-
108
- function parseJson(value, fallback) {
109
- try { return value == null ? fallback : JSON.parse(value); }
110
- catch { return fallback; }
111
- }
112
-
113
- function rowToDecision(row) {
114
- if (!row) return null;
115
- return {
116
- id: row.id,
117
- scope: { [`${row.scope_type}_id`]: row.scope_id },
118
- scope_type: row.scope_type,
119
- scope_id: row.scope_id,
120
- question: row.question,
121
- recommendation: row.recommendation,
122
- selection: row.selection,
123
- effects: parseJson(row.effects_json, {}),
124
- non_goals: parseJson(row.non_goals_json, []),
125
- owner: row.owner,
126
- source: row.source,
127
- provenance: parseJson(row.provenance_json, {}),
128
- applied_refs: parseJson(row.applied_refs_json, []),
129
- status: row.status,
130
- digest: row.digest,
131
- artifact_path: row.artifact_path,
132
- supersedes_id: row.supersedes_id,
133
- created_at: row.created_at,
134
- updated_at: row.updated_at,
135
- };
136
- }
137
-
138
- function readDecision(db, id) {
139
- return rowToDecision(db.prepare('SELECT * FROM decision_records WHERE id = ?').get(id));
140
- }
141
-
142
- function decisionValue(decision) {
143
- return {
144
- schema_version: '1.0',
145
- id: decision.id,
146
- scope: { type: decision.scope_type, id: decision.scope_id },
147
- question: decision.question,
148
- recommendation: decision.recommendation,
149
- selection: decision.selection,
150
- effects: decision.effects,
151
- non_goals: decision.non_goals,
152
- owner: decision.owner,
153
- source: decision.source,
154
- provenance: decision.provenance,
155
- applied_refs: decision.applied_refs,
156
- status: decision.status,
157
- supersedes_id: decision.supersedes_id || null,
158
- };
159
- }
160
-
161
- function readDecisionArtifact(db, id, { rootDir = process.cwd() } = {}) {
162
- const decision = readDecision(db, id);
163
- if (!decision) {
164
- throw new DecisionRecordError('DECISION_NOT_FOUND', `decision not found: ${id}`);
165
- }
166
- const computed = canonical.digest(decisionValue(decision));
167
- if (computed !== decision.digest) {
168
- throw new DecisionRecordError(
169
- 'DECISION_DIGEST_MISMATCH',
170
- `Decision Record database authority is corrupt: ${id}`,
171
- { expected: decision.digest, actual: computed },
172
- );
173
- }
174
- const read = readStableProjectFile(rootDir, decision.artifact_path, { encoding: 'utf8' });
175
- const artifact = db.prepare(
176
- `SELECT digest FROM artifacts
177
- WHERE path = ? AND status <> 'archived'
178
- ORDER BY updated_at DESC, rowid DESC LIMIT 1`,
179
- ).get(decision.artifact_path) || db.prepare(
180
- `SELECT digest FROM artifacts
181
- WHERE path = ? ORDER BY updated_at DESC, rowid DESC LIMIT 1`,
182
- ).get(decision.artifact_path);
183
- if (!artifact?.digest || artifact.digest !== read.digest) {
184
- throw new DecisionRecordError(
185
- 'DECISION_FILE_DRIFT',
186
- `Decision Record bytes no longer match the Artifact Registry: ${id}`,
187
- {
188
- path: decision.artifact_path,
189
- expected: artifact?.digest || null,
190
- actual: read.digest,
191
- },
192
- );
193
- }
194
- let document;
195
- try { document = JSON.parse(read.text); }
196
- catch (cause) {
197
- throw new DecisionRecordError(
198
- 'DECISION_ARTIFACT_INVALID',
199
- `Decision Record is not valid JSON: ${decision.artifact_path}`,
200
- { cause: cause.message },
201
- );
202
- }
203
- const { digest: documentDigest, ...documentValue } = document;
204
- if (documentDigest !== decision.digest
205
- || canonical.digest(documentValue) !== decision.digest) {
206
- throw new DecisionRecordError(
207
- 'DECISION_DIGEST_MISMATCH',
208
- `Decision Record file does not match its accepted authority: ${id}`,
209
- );
210
- }
211
- return { ...decision, file_digest: read.digest };
212
- }
213
-
214
- function listAcceptedDecisions(
215
- db,
216
- scope = {},
217
- { limit = 100, rootDir = null, validateFiles = false } = {},
218
- ) {
219
- const normalized = normalizeScope(scope);
220
- const rows = db.prepare(
221
- `SELECT * FROM decision_records
222
- WHERE scope_type = ? AND scope_id = ? AND status = 'accepted'
223
- ORDER BY updated_at DESC, id ASC LIMIT ?`,
224
- ).all(
225
- normalized.type,
226
- normalized.id,
227
- Math.min(Math.max(Number(limit) || 100, 1), 500),
228
- ).map(rowToDecision);
229
- return validateFiles
230
- ? rows.map((row) => readDecisionArtifact(db, row.id, { rootDir }))
231
- : rows;
232
- }
233
-
234
- function normalizeAppliedRefs(value) {
235
- if (value === undefined) return [];
236
- if (!Array.isArray(value)) {
237
- throw new DecisionRecordError('VALIDATION_ERROR', 'applied_refs must be an array');
238
- }
239
- return value.map((item, index) => {
240
- if (!item || typeof item !== 'object' || Array.isArray(item)) {
241
- throw new DecisionRecordError('VALIDATION_ERROR', `applied_refs[${index}] must be an object`);
242
- }
243
- assertExactFields(
244
- item,
245
- new Set(['ref', 'field', 'digest']),
246
- `applied_refs[${index}]`,
247
- );
248
- return {
249
- ref: requiredText(item.ref, `applied_refs[${index}].ref`),
250
- ...(item.field !== undefined
251
- ? { field: requiredText(item.field, `applied_refs[${index}].field`) }
252
- : {}),
253
- ...(item.digest !== undefined
254
- ? { digest: requiredText(item.digest, `applied_refs[${index}].digest`) }
255
- : {}),
256
- };
257
- });
258
- }
259
-
260
- function artifactPath(scope, id) {
261
- return scope.type === 'baseline'
262
- ? `.ultra/decisions/baseline/${id}.json`
263
- : `.ultra/changes/active/${scope.id}/decisions/${id}.json`;
264
- }
265
-
266
- function acceptDecision(db, input = {}, { rootDir = process.cwd() } = {}) {
267
- assertExactFields(input, DECISION_FIELDS, 'decision');
268
- const scope = normalizeScope(input.scope);
269
- const supersedesId = input.supersedes_id === undefined || input.supersedes_id === null
270
- ? null
271
- : requiredText(input.supersedes_id, 'supersedes_id');
272
- const value = {
273
- schema_version: '1.0',
274
- id: requiredText(input.id, 'id'),
275
- scope: { type: scope.type, id: scope.id },
276
- question: requiredText(input.question, 'question'),
277
- recommendation: requiredText(input.recommendation, 'recommendation'),
278
- selection: requiredText(input.selection, 'selection'),
279
- effects: plainObject(input.effects, 'effects'),
280
- non_goals: stringArray(input.non_goals, 'non_goals'),
281
- owner: requiredText(input.owner, 'owner'),
282
- source: requiredText(input.source, 'source'),
283
- provenance: plainObject(input.provenance, 'provenance'),
284
- applied_refs: normalizeAppliedRefs(input.applied_refs),
285
- status: 'accepted',
286
- supersedes_id: supersedesId,
287
- };
288
- const digest = canonical.digest(value);
289
- const document = { ...value, digest };
290
- const relative = artifactPath(scope, value.id);
291
- const existing = readDecision(db, value.id);
292
- if (existing) {
293
- if (existing.digest !== digest) {
294
- throw new DecisionRecordError(
295
- 'DECISION_ID_CONFLICT',
296
- `decision ${value.id} already exists with different content`,
297
- );
298
- }
299
- return existing;
300
- }
301
- if (value.supersedes_id) {
302
- const prior = readDecision(db, value.supersedes_id);
303
- if (!prior) {
304
- throw new DecisionRecordError(
305
- 'DECISION_NOT_FOUND',
306
- `superseded decision not found: ${value.supersedes_id}`,
307
- );
308
- }
309
- if (prior.scope_type !== scope.type || prior.scope_id !== scope.id) {
310
- throw new DecisionRecordError(
311
- 'DECISION_SCOPE_CONFLICT',
312
- 'a decision can only supersede another decision in the same scope',
313
- );
314
- }
315
- if (prior.status !== 'accepted') {
316
- throw new DecisionRecordError(
317
- 'DECISION_NOT_SUPERSEDEABLE',
318
- `decision ${value.supersedes_id} is ${prior.status}`,
319
- );
320
- }
321
- }
322
- artifactRegistry.assertArtifactOwner(db, scope.type, scope.id);
323
- const snapshot = snapshotManagedFile(rootDir, relative);
324
- const published = writeManagedJson(rootDir, relative, document);
325
- try {
326
- return ops.tx(db, () => {
327
- if (value.supersedes_id) {
328
- db.prepare(
329
- `UPDATE decision_records SET status = 'superseded',
330
- updated_at = strftime('%Y-%m-%dT%H:%M:%fZ', 'now')
331
- WHERE id = ? AND status = 'accepted'`,
332
- ).run(value.supersedes_id);
333
- }
334
- db.prepare(
335
- `INSERT INTO decision_records
336
- (id, scope_type, scope_id, question, recommendation, selection,
337
- effects_json, non_goals_json, owner, source, provenance_json,
338
- applied_refs_json, status, digest, artifact_path, supersedes_id)
339
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'accepted', ?, ?, ?)`,
340
- ).run(
341
- value.id,
342
- scope.type,
343
- scope.id,
344
- value.question,
345
- value.recommendation,
346
- value.selection,
347
- JSON.stringify(value.effects),
348
- JSON.stringify(value.non_goals),
349
- value.owner,
350
- value.source,
351
- JSON.stringify(value.provenance),
352
- JSON.stringify(value.applied_refs),
353
- digest,
354
- relative,
355
- value.supersedes_id,
356
- );
357
- artifactRegistry.recordArtifactInTx(db, {
358
- id: `artifact-decision-${value.id}`,
359
- owner_type: scope.type,
360
- owner_id: scope.id,
361
- change_id: scope.type === 'change' ? scope.id : null,
362
- kind: 'decision_record',
363
- path: relative,
364
- content_digest: published.digest,
365
- source_refs: [{
366
- type: scope.type,
367
- id: scope.id,
368
- relation: 'decided_for',
369
- }],
370
- consumer_refs: [{
371
- type: 'external',
372
- id: 'ultra-context-consumer',
373
- relation: 'consumed_by',
374
- }],
375
- provenance: {
376
- writer: 'decision-records',
377
- decision_digest: digest,
378
- owner: value.owner,
379
- source: value.source,
380
- },
381
- metadata: {
382
- decision_id: value.id,
383
- status: value.status,
384
- supersedes_id: value.supersedes_id,
385
- },
386
- }, { rootDir });
387
- ops.appendEventInTx(db, {
388
- type: 'decision_recorded',
389
- change_id: scope.type === 'change' ? scope.id : null,
390
- payload: {
391
- decision_id: value.id,
392
- scope_type: scope.type,
393
- scope_id: scope.id,
394
- digest,
395
- artifact_path: relative,
396
- supersedes_id: value.supersedes_id,
397
- },
398
- });
399
- return readDecision(db, value.id);
400
- });
401
- } catch (error) {
402
- try {
403
- restoreManagedFile(rootDir, snapshot);
404
- } catch (rollbackError) {
405
- throw new DecisionRecordError(
406
- 'RECORD_FILE_ROLLBACK_REQUIRED',
407
- `decision database mutation failed and managed file recovery also failed: ${relative}`,
408
- { cause: error.message, rollback_error: rollbackError.message },
409
- );
410
- }
411
- throw error;
412
- }
413
- }
414
-
415
- module.exports = {
416
- DecisionRecordError,
417
- normalizeScope,
418
- readDecision,
419
- readDecisionArtifact,
420
- decisionValue,
421
- listAcceptedDecisions,
422
- acceptDecision,
423
- };