ultra-builder-pro-cli 0.12.1 → 0.14.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 (88) hide show
  1. package/.ultra-template/docs/research/README.md +21 -44
  2. package/.ultra-template/specs/discovery.md +10 -0
  3. package/CHANGELOG.md +95 -1
  4. package/README.md +31 -16
  5. package/adapters/_shared/codex-assets.cjs +23 -163
  6. package/adapters/_shared/handbook.cjs +2 -2
  7. package/adapters/_shared/runtime-assets.cjs +1 -0
  8. package/adapters/_shared/tests/runtime-assets.test.cjs +18 -0
  9. package/adapters/opencode.js +30 -120
  10. package/adapters/tests/claude.test.cjs +3 -2
  11. package/adapters/tests/codex-hook.test.cjs +34 -7
  12. package/adapters/tests/codex.test.cjs +21 -6
  13. package/adapters/tests/kimi-hook.test.cjs +34 -7
  14. package/adapters/tests/opencode.test.cjs +70 -84
  15. package/commands/ultra-init.md +1 -1
  16. package/docs/AGENT-CONTEXT.md +10 -6
  17. package/docs/ARCHITECTURE.md +40 -17
  18. package/docs/PLAN.zh-CN.md +5 -4
  19. package/docs/ROADMAP.md +2 -2
  20. package/docs/RUNTIME-COMPAT-MATRIX.md +4 -4
  21. package/docs/STATE-DB-ACCESS-POLICY.md +3 -3
  22. package/docs/USER-HANDBOOK-CONTRACT.md +5 -4
  23. package/hooks/active_task_context.py +22 -50
  24. package/hooks/context_spine.py +61 -299
  25. package/hooks/health_check.py +19 -17
  26. package/hooks/pre_stop_check.py +28 -33
  27. package/hooks/subagent_tracker.py +13 -19
  28. package/hooks/workflow_checkpoint.py +39 -47
  29. package/hooks/workflow_context.py +4 -9
  30. package/hooks/workflow_resume.py +48 -128
  31. package/mcp-server/breadcrumb.cjs +22 -0
  32. package/mcp-server/lib/archive-journal.cjs +192 -0
  33. package/mcp-server/lib/archive-journal.test.cjs +35 -0
  34. package/mcp-server/lib/baseline-workflow.cjs +404 -38
  35. package/mcp-server/lib/baseline-workflow.test.cjs +252 -0
  36. package/mcp-server/lib/change-workflow.cjs +249 -75
  37. package/mcp-server/lib/change-workflow.test.cjs +235 -1
  38. package/mcp-server/lib/context-spine.test.cjs +5 -0
  39. package/mcp-server/lib/doctor.cjs +14 -1
  40. package/mcp-server/lib/doctor.test.cjs +42 -4
  41. package/mcp-server/lib/init-project.cjs +292 -9
  42. package/mcp-server/lib/prd-parser.cjs +14 -41
  43. package/mcp-server/lib/prd-parser.test.cjs +49 -138
  44. package/mcp-server/lib/project-breadcrumb.cjs +139 -0
  45. package/mcp-server/lib/project-breadcrumb.test.cjs +112 -0
  46. package/mcp-server/lib/spec-learning.test.cjs +1 -1
  47. package/mcp-server/lib/state-authority.cjs +9 -3
  48. package/mcp-server/lib/state-db.cjs +154 -32
  49. package/mcp-server/lib/state-db.test.cjs +136 -4
  50. package/mcp-server/lib/state-ops.cjs +68 -6
  51. package/mcp-server/lib/task-expander.cjs +14 -37
  52. package/mcp-server/lib/task-expander.test.cjs +80 -164
  53. package/mcp-server/server.cjs +34 -37
  54. package/mcp-server/tests/init-project.test.cjs +162 -1
  55. package/mcp-server/tests/migrate.test.cjs +33 -0
  56. package/mcp-server/tests/server-contract.test.cjs +391 -17
  57. package/mcp-server/tests/state-db.test.cjs +14 -2
  58. package/mcp-server/tests/state-ops.test.cjs +108 -0
  59. package/package.json +2 -4
  60. package/skills/cc-collab/SKILL.md +2 -2
  61. package/skills/codex-collab/SKILL.md +2 -3
  62. package/skills/ultra-change/SKILL.md +18 -10
  63. package/skills/ultra-deliver/SKILL.md +13 -9
  64. package/skills/ultra-dev/SKILL.md +6 -4
  65. package/skills/ultra-doctor/SKILL.md +22 -7
  66. package/skills/ultra-init/SKILL.md +104 -59
  67. package/skills/ultra-init/references/brownfield-adoption.md +65 -37
  68. package/skills/ultra-plan/SKILL.md +20 -7
  69. package/skills/ultra-research/SKILL.md +12 -5
  70. package/skills/ultra-status/SKILL.md +6 -4
  71. package/skills/ultra-verify/SKILL.md +21 -30
  72. package/skills/ultra-verify/scripts/verify_wait.py +54 -54
  73. package/spec/cli-protocol.md +11 -1
  74. package/spec/mcp-tools.yaml +133 -19
  75. package/spec/schemas/state-db.sql +11 -0
  76. package/ultra-tools/cli.cjs +9 -5
  77. package/ultra-tools/commands/migrate.cjs +62 -36
  78. package/ultra-tools/commands/status.cjs +18 -9
  79. package/ultra-tools/commands/system.cjs +340 -6
  80. package/ultra-tools/commands/task.cjs +7 -1
  81. package/ultra-tools/status-command.test.cjs +29 -0
  82. package/ultra-tools/system-command.test.cjs +252 -1
  83. package/mcp-server/lib/llm-client.cjs +0 -157
  84. package/mcp-server/lib/llm-client.test.cjs +0 -156
  85. package/orchestrator/planner/expand-prompt.cjs +0 -62
  86. package/orchestrator/planner/expand-prompt.test.cjs +0 -52
  87. package/orchestrator/planner/prd-prompt.cjs +0 -44
  88. package/orchestrator/planner/prd-prompt.test.cjs +0 -30
@@ -59,7 +59,9 @@ test('initStateDb upgrades a pre-10.0 database through Context Spine into baseli
59
59
  assert.ok(columns.includes('change_id'));
60
60
  const eventColumns = upgraded.db.prepare('PRAGMA table_info(events)').all().map((row) => row.name);
61
61
  assert.ok(eventColumns.includes('change_id'));
62
- assert.equal(upgraded.schema_version, '11.0');
62
+ assert.equal(upgraded.schema_version, '12.0');
63
+ assert.ok(upgraded.backup_path);
64
+ assert.ok(fs.existsSync(upgraded.backup_path));
63
65
  assert.ok(upgraded.db.prepare("SELECT 1 FROM schema_version WHERE version = '10.0'").get());
64
66
  const contextColumns = upgraded.db.prepare('PRAGMA table_info(context_snapshots)').all()
65
67
  .map((row) => row.name);
@@ -72,7 +74,7 @@ test('initStateDb upgrades a pre-10.0 database through Context Spine into baseli
72
74
  const baseline = upgraded.db.prepare(
73
75
  "SELECT mode, status FROM baselines WHERE id = 'migrated-baseline'",
74
76
  ).get();
75
- assert.deepEqual(baseline, { mode: 'migrated', status: 'ready' });
77
+ assert.deepEqual(baseline, { mode: 'migrated', status: 'adopting' });
76
78
  const contextMigration = upgraded.db.prepare(
77
79
  "SELECT from_version, to_version, notes FROM migration_history WHERE to_version = '10.0' ORDER BY id DESC LIMIT 1",
78
80
  ).get();
@@ -84,6 +86,16 @@ test('initStateDb upgrades a pre-10.0 database through Context Spine into baseli
84
86
  ).get();
85
87
  assert.equal(baselineMigration.from_version, '10.0');
86
88
  assert.match(baselineMigration.notes, /baseline adoption/i);
89
+ const adoptionMigration = upgraded.db.prepare(
90
+ "SELECT from_version, to_version, notes FROM migration_history WHERE to_version = '12.0' ORDER BY id DESC LIMIT 1",
91
+ ).get();
92
+ assert.equal(adoptionMigration.from_version, '11.0');
93
+ assert.match(adoptionMigration.notes, /gap ledger|re-adoption/i);
94
+ const migrated = upgraded.db.prepare(
95
+ "SELECT gaps_json, worktree_state FROM baselines WHERE id = 'migrated-baseline'",
96
+ ).get();
97
+ assert.equal(migrated.worktree_state, 'unavailable');
98
+ assert.equal(JSON.parse(migrated.gaps_json)[0].category, 'baseline_blocker');
87
99
  assert.ok(upgraded.db.prepare(
88
100
  "SELECT 1 FROM migration_history WHERE from_version = '8A.1' AND to_version = '9.1' AND notes LIKE '%Kimi%'",
89
101
  ).get());
@@ -20,6 +20,13 @@ function freshDb() {
20
20
  return { ...t, db: init.db };
21
21
  }
22
22
 
23
+ function seedChange(db, id, status = 'active') {
24
+ db.prepare(
25
+ `INSERT INTO changes (id, title, kind, status, intent, artifact_root)
26
+ VALUES (?, ?, 'quick', ?, ?, ?)`,
27
+ ).run(id, `Change ${id}`, status, `Intent for ${id}.`, `.ultra/changes/active/${id}`);
28
+ }
29
+
23
30
  test('createTask inserts a row, preserves estimated_days, defaults status=pending, emits task_created', () => {
24
31
  const { dir, db } = freshDb();
25
32
  try {
@@ -65,6 +72,107 @@ test('createTask rejects duplicates with DUPLICATE_TASK_ID', () => {
65
72
  }
66
73
  });
67
74
 
75
+ test('createTask preserves parent change ownership and rejects terminal change targets', () => {
76
+ const { dir, db } = freshDb();
77
+ try {
78
+ seedChange(db, 'change-a');
79
+ seedChange(db, 'change-b');
80
+ seedChange(db, 'change-closed', 'archived');
81
+ ops.createTask(db, {
82
+ id: 'parent-owned', title: 'owned parent', type: 'feature', priority: 'P1',
83
+ change_id: 'change-a',
84
+ });
85
+ const inherited = ops.createTask(db, {
86
+ id: 'child-inherited', title: 'inherited child', type: 'feature', priority: 'P1',
87
+ parent_id: 'parent-owned',
88
+ });
89
+ assert.equal(inherited.change_id, 'change-a');
90
+ assert.throws(
91
+ () => ops.createTask(db, {
92
+ id: 'child-mismatch', title: 'mismatched child', type: 'feature', priority: 'P1',
93
+ parent_id: 'parent-owned', change_id: 'change-b',
94
+ }),
95
+ (error) => error.code === 'TASK_CHANGE_OWNERSHIP_MISMATCH',
96
+ );
97
+ assert.throws(
98
+ () => ops.createTask(db, {
99
+ id: 'child-orphan', title: 'orphan child', type: 'feature', priority: 'P1',
100
+ parent_id: 'missing-parent',
101
+ }),
102
+ (error) => error.code === 'TASK_NOT_FOUND',
103
+ );
104
+ assert.throws(
105
+ () => ops.createTask(db, {
106
+ id: 'closed-change-task', title: 'closed change task', type: 'feature', priority: 'P1',
107
+ change_id: 'change-closed',
108
+ }),
109
+ (error) => error.code === 'CHANGE_NOT_MUTABLE',
110
+ );
111
+ } finally {
112
+ closeStateDb(db);
113
+ fs.rmSync(dir, { recursive: true, force: true });
114
+ }
115
+ });
116
+
117
+ test('patchTask keeps established ownership immutable and rejects terminal-change writes', () => {
118
+ const { dir, db } = freshDb();
119
+ try {
120
+ seedChange(db, 'change-a');
121
+ seedChange(db, 'change-b');
122
+ seedChange(db, 'change-ready', 'ready');
123
+ ops.createTask(db, {
124
+ id: 'patch-parent', title: 'patch parent', type: 'feature', priority: 'P1',
125
+ change_id: 'change-a',
126
+ });
127
+ ops.createTask(db, {
128
+ id: 'patch-child', title: 'patch child', type: 'feature', priority: 'P1',
129
+ parent_id: 'patch-parent',
130
+ });
131
+ assert.throws(
132
+ () => ops.patchTask(db, 'patch-child', { change_id: null }),
133
+ (error) => error.code === 'TASK_CHANGE_OWNERSHIP_MISMATCH',
134
+ );
135
+ assert.throws(
136
+ () => ops.patchTask(db, 'patch-child', { change_id: 'change-b' }),
137
+ (error) => error.code === 'TASK_CHANGE_OWNERSHIP_MISMATCH',
138
+ );
139
+ assert.throws(
140
+ () => ops.patchTask(db, 'patch-parent', { change_id: 'change-b' }),
141
+ (error) => error.code === 'TASK_CHANGE_OWNERSHIP_MISMATCH',
142
+ );
143
+ const root = ops.createTask(db, {
144
+ id: 'patch-root', title: 'owned root', type: 'feature', priority: 'P1',
145
+ change_id: 'change-a',
146
+ });
147
+ assert.equal(root.change_id, 'change-a');
148
+ assert.throws(
149
+ () => ops.patchTask(db, 'patch-root', { change_id: null }),
150
+ (error) => error.code === 'TASK_CHANGE_OWNERSHIP_MISMATCH',
151
+ );
152
+ assert.throws(
153
+ () => ops.patchTask(db, 'patch-root', { change_id: 'change-b' }),
154
+ (error) => error.code === 'TASK_CHANGE_OWNERSHIP_MISMATCH',
155
+ );
156
+ const standalone = ops.createTask(db, {
157
+ id: 'patch-standalone', title: 'patch standalone', type: 'feature', priority: 'P1',
158
+ });
159
+ assert.equal(standalone.change_id, null);
160
+ assert.equal(ops.patchTask(db, 'patch-standalone', { change_id: 'change-b' }).change_id, 'change-b');
161
+ assert.throws(
162
+ () => ops.patchTask(db, 'patch-root', { change_id: 'change-ready' }),
163
+ (error) => error.code === 'TASK_CHANGE_OWNERSHIP_MISMATCH',
164
+ );
165
+ db.prepare("UPDATE changes SET status = 'archived' WHERE id = 'change-a'").run();
166
+ assert.throws(
167
+ () => ops.patchTask(db, 'patch-root', { priority: 'P0' }),
168
+ (error) => error.code === 'CHANGE_NOT_MUTABLE',
169
+ );
170
+ } finally {
171
+ closeStateDb(db);
172
+ fs.rmSync(dir, { recursive: true, force: true });
173
+ }
174
+ });
175
+
68
176
  test('updateTaskStatus enforces the legal transition graph', () => {
69
177
  const { dir, db } = freshDb();
70
178
  try {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ultra-builder-pro-cli",
3
- "version": "0.12.1",
3
+ "version": "0.14.0",
4
4
  "description": "Multi-runtime installer for the Ultra Builder Pro agent engineering system — deploys commands, agents, skills, hooks, and MCP server to Claude Code, OpenCode, Codex CLI, and Kimi Code.",
5
5
  "bin": {
6
6
  "ultra-builder-pro-cli": "bin/install.js",
@@ -98,13 +98,11 @@
98
98
  "install:all": "node bin/install.js --all --local"
99
99
  },
100
100
  "dependencies": {
101
- "@anthropic-ai/sdk": "^0.111.0",
102
101
  "@modelcontextprotocol/sdk": "^1.29.0",
103
102
  "@vercel/ncc": "0.38.4",
104
103
  "ajv": "^8.17.1",
105
104
  "ajv-formats": "^3.0.1",
106
105
  "better-sqlite3": "^11.5.0",
107
- "js-yaml": "^4.1.0",
108
- "openai": "^6.34.0"
106
+ "js-yaml": "^4.1.0"
109
107
  }
110
108
  }
@@ -5,8 +5,8 @@ description: Ask Claude Code for an independent read-only analysis of a bounded
5
5
 
6
6
  # Consult Claude Code read-only
7
7
 
8
- Treat Claude Code as an untrusted advisor. The current host owns scope, evidence,
9
- decisions, edits, and final verification.
8
+ Treat Claude Code as an untrusted advisor. Keep the current host responsible for
9
+ scope, evidence, decisions, edits, and final verification.
10
10
 
11
11
  ## Preconditions
12
12
 
@@ -5,8 +5,8 @@ description: Ask Codex CLI for an independent read-only analysis of a bounded ar
5
5
 
6
6
  # Consult Codex read-only
7
7
 
8
- Treat Codex as an untrusted advisor. The current host owns scope, evidence, edits,
9
- verification, and the final answer.
8
+ Treat Codex as an untrusted advisor. Keep the current host responsible for scope,
9
+ evidence, edits, verification, and the final answer.
10
10
 
11
11
  ## Preconditions
12
12
 
@@ -23,7 +23,6 @@ Create a session directory under `.ultra/collab/`, then run in a read-only sandb
23
23
  SESSION_PATH=".ultra/collab/$(date +%Y%m%d-%H%M%S)-codex"
24
24
  mkdir -p "${SESSION_PATH}"
25
25
  codex exec -s read-only \
26
- -a never \
27
26
  --ephemeral \
28
27
  --ignore-user-config \
29
28
  --ignore-rules \
@@ -16,11 +16,13 @@ own their payloads; Ultra stores only provider references supplied by the user o
16
16
 
17
17
  ## Workflow
18
18
 
19
- 1. Call `baseline.get`. State integrity failure routes to `ultra-doctor`. When no
20
- change is active, a missing, incomplete, or stale baseline routes to `ultra-init`.
21
- An urgent or already active bounded change may proceed with that condition recorded
22
- as a warning. `change.converge` requires an approved `ready` baseline; repository
23
- revision and tracked-spec drift created by the change are reconciled at archive.
19
+ 1. Call `baseline.get`. State integrity failure routes to `ultra-doctor`.
20
+ - Create ordinary work only when the baseline is healthy and `ready`.
21
+ - Resume a change that was already active when baseline drift appears; record the
22
+ condition as a warning and restore baseline readiness before ordinary convergence.
23
+ - Create an `incident` on an unhealthy baseline only with an explicit
24
+ `baseline_bypass` containing the reason and approver.
25
+ - Route every other missing, migrated, incomplete, or stale baseline to `ultra-init`.
24
26
  2. Call `change.list` and `change.breadcrumb`.
25
27
  - Resume the single change that matches the requested outcome.
26
28
  - Require an explicit id when several changes could match.
@@ -30,6 +32,8 @@ own their payloads; Ultra stores only provider references supplied by the user o
30
32
  4. Classify the change as `quick`, `standard`, `major`, or `incident`. Ask only for a
31
33
  material product, risk, or recovery decision that repository evidence cannot answer.
32
34
  5. Call `change.create` with a stable kebab-case id, or `change.update` when resuming.
35
+ For incident break-glass, persist the approved reason in `baseline_bypass`; never
36
+ infer approval from urgency.
33
37
  6. Write the minimum artifact set required by the classification:
34
38
 
35
39
  ```text
@@ -69,8 +73,12 @@ verified.
69
73
  ## Completion gate
70
74
 
71
75
  Do not claim alignment while a material decision is unresolved, documentation impact
72
- is unknown, context is stale, or the next task is not executable. `change.converge`
73
- also requires a `ready` baseline, so incomplete adoption must be resolved before
74
- convergence. Normal HEAD or tracked-spec drift caused by the active change is not a
75
- convergence blocker. Declare every baseline update at archive; archive fails and rolls
76
- back when revision or digest health remains stale after reconciliation.
76
+ is unknown, context is stale, or the next task is not executable. Ordinary change
77
+ convergence requires a non-migrated `ready` baseline. Normal HEAD or tracked-spec drift
78
+ caused by the active change is reconciled at archive.
79
+
80
+ An approved break-glass incident may converge and archive while baseline adoption is
81
+ incomplete. Its archive must add an open `baseline_blocker` reconciliation gap owned by
82
+ the recorded approver. Report the incident as closed and the project baseline as not
83
+ ready until that gap is resolved. Every archive declares baseline updates or an exact
84
+ no-change reason; failed ordinary reconciliation rolls back state and artifacts.
@@ -12,10 +12,10 @@ review, and delivery reports are evidence artifacts.
12
12
 
13
13
  1. Call `baseline.get`, then `change.list`. Bind exactly one relevant change, or the
14
14
  current draft/adopting baseline when this is the initial delivery.
15
- 2. Call `change.breadcrumb`. Context-size warnings are advisory, but delivery blocks
16
- on incomplete baseline adoption, stale execution context, incomplete linked tasks,
17
- or unresolved readiness. HEAD and tracked-spec drift caused by the current change
18
- remain visible warnings until archive reconciliation.
15
+ 2. Call `change.breadcrumb`. Context-size warnings are advisory. Ordinary delivery
16
+ blocks on incomplete baseline adoption, stale execution context, incomplete linked
17
+ tasks, or unresolved readiness. An explicitly approved break-glass incident may
18
+ continue while baseline adoption is incomplete.
19
19
  3. Require a passing test report for the current full HEAD and at least one declared
20
20
  public seam.
21
21
  4. Require current independent `spec_fidelity` and `engineering_standards` review
@@ -59,11 +59,15 @@ delta, documentation, both independent review axes, and incident diagnosis when
59
59
  applicable. Do not collapse review axes or replace exact signal fields with prose.
60
60
 
61
61
  Resolve named blockers, rerun invalidated gates, then call `change.archive` with the
62
- summary and baseline updates. Archive reconciliation refreshes the authoritative
63
- baseline revision and digests. The archive transaction rechecks baseline health and
64
- rolls back the state row, artifacts, and reconciliation events if any tracked digest
65
- or repository revision remains stale. Verify the result with `baseline.get` before
66
- release.
62
+ summary and baseline updates or an exact no-change reason. Ordinary archive
63
+ reconciliation refreshes the authoritative baseline revision and digests, rechecks
64
+ health, and rolls back state and artifacts when any tracked digest or revision remains
65
+ stale.
66
+
67
+ For a break-glass incident, verify that archive returned `baseline_bypass: true` and
68
+ created the open reconciliation gap on the current baseline. Report incident delivery
69
+ separately from project baseline readiness. Resolve that gap through `ultra-init`
70
+ before starting ordinary work.
67
71
 
68
72
  ## Optional release
69
73
 
@@ -17,8 +17,10 @@ Read `change.breadcrumb` when a change is active. Stale context, blocked readine
17
17
  unknown documentation impact, or a HEAD mismatch blocks implementation.
18
18
  Baseline-adoption and context-size warnings do not block an active slice. Address
19
19
  them when practical without dropping required evidence or arbitrarily changing a
20
- threshold. Approved baseline availability is enforced at convergence; revision and
21
- tracked-spec health are reconciled and verified at archive.
20
+ threshold. Ordinary convergence requires approved baseline availability; revision
21
+ and tracked-spec health are reconciled and verified at archive. An approved
22
+ break-glass incident may finish recovery first and must leave a blocking baseline
23
+ reconciliation gap.
22
24
 
23
25
  ## Workflow
24
26
 
@@ -40,8 +42,8 @@ tracked-spec health are reconciled and verified at archive.
40
42
  utilities, keep IO at boundaries, include required errors and recovery, and preserve
41
43
  unrelated worktree changes.
42
44
  7. If the work reveals a stable requirement or public behavior absent from the
43
- baseline, call `change.learning_propose`. Do not edit the baseline silently or store
44
- the discovery as private Ultra memory.
45
+ baseline, call `change.learning_propose`. Do not edit the baseline silently or keep
46
+ the discovery only in transient conversation context.
45
47
  8. Verify in this order:
46
48
  - the original feedback-loop command;
47
49
  - adjacent focused tests;
@@ -15,6 +15,7 @@ Call `system.doctor` with `{ "repair": false }` and inspect:
15
15
  - open structured incidents;
16
16
  - event and projection cursor lag;
17
17
  - failed or interrupted projection jobs;
18
+ - interrupted archive journals;
18
19
  - orphan sessions;
19
20
  - missing active-change artifact roots;
20
21
  - missing, incomplete, or stale project baseline readiness and specification digests;
@@ -36,17 +37,31 @@ delete artifacts, or collect memory during diagnosis.
36
37
  not approve a baseline, accept known-red verification, or invent adoption evidence.
37
38
  Baseline readiness is an advisory workflow check, not state-database corruption and
38
39
  not a reason for doctor repair.
40
+ - A compatibility `migrated` baseline requires explicit brownfield re-adoption and
41
+ cannot authorize ordinary changes.
42
+ - A corrupt SQLite file requires preserving the file, locating a verified backup, and
43
+ an explicit restore-or-rebaseline decision.
39
44
 
40
45
  ## Explicit repair
41
46
 
42
47
  After authorization, call `system.doctor` with `{ "repair": true }` or use the
43
- installed `ultra-tools system doctor --repair` fallback. The runtime must create a
44
- timestamped state database backup before any mechanical repair.
45
-
46
- Repair is limited to documented recovery operations such as reconciling orphan
47
- sessions, consuming staleness events, requeueing interrupted or failed projections,
48
- and regenerating projections from authoritative state. If backup fails, stop. Always
49
- inspect the post-repair report; a completed repair action does not imply healthy state.
48
+ installed `ultra-tools system doctor --repair` fallback. The CLI applies supported
49
+ schema upgrades to the packaged current schema and reports a pre-migration backup path. Doctor then
50
+ creates a second timestamped backup before runtime recovery.
51
+
52
+ Repair is limited to documented schema upgrades, archive-journal completion,
53
+ reconciling orphan sessions, consuming staleness events, requeueing interrupted or
54
+ failed projections, and regenerating projections from authoritative state. If either
55
+ backup fails, stop. Always inspect the post-repair report; a completed repair action
56
+ does not imply healthy state.
57
+
58
+ If SQLite integrity prevents doctor from opening authority, preserve the original
59
+ database, WAL, and SHM. After the owner chooses a recovery path, either run
60
+ `ultra-tools system restore --backup <managed-backup> --confirm
61
+ REPLACE_CORRUPT_ULTRA_STATE` or run `ultra-tools system rebaseline --project-name
62
+ <name> [--scope <path>] --confirm REBASELINE_CORRUPT_ULTRA_STATE`. Both commands
63
+ must report the recovery backup directory. A failed command must restore the
64
+ original authority, sidecars, and task projection before returning an error.
50
65
 
51
66
  ## Installed-plugin failures
52
67
 
@@ -1,66 +1,111 @@
1
1
  ---
2
2
  name: ultra-init
3
- description: Initialize Ultra Builder Pro or resume greenfield and brownfield baseline adoption. Use when a repository lacks Ultra state or its project baseline is missing, draft, adopting, or blocked.
3
+ description: Initialize a new repository, adopt an existing codebase, or upgrade prior Ultra state into an evidence-backed project baseline. Use when `.ultra` is absent, baseline readiness is incomplete, or legacy project state must be migrated.
4
4
  ---
5
5
 
6
- # Initialize or adopt a project
7
-
8
- Create project-local Ultra state, then route the repository according to its actual
9
- baseline status. Do not treat an existing codebase as a new product.
10
-
11
- ## Preflight
12
-
13
- Use the current working directory unless the user names another target. Inspect the
14
- root, project manifests, Git state, and `.ultra/` without mutation.
15
-
16
- If `.ultra/` exists, call `baseline.get` and `system.doctor`:
17
-
18
- - a healthy `ready` baseline routes to `ultra-change` or `ultra-status`;
19
- - `draft`, `adopting`, or baseline-blocked state resumes this workflow;
20
- - state integrity or migration failure routes to `ultra-doctor`;
21
- - recreation requires explicit authorization and must preserve the returned backup.
22
-
23
- Never overwrite `.ultra/` merely because the repository is old or its documents are
24
- incomplete.
6
+ # Establish the project baseline
7
+
8
+ Create or recover project-local Ultra authority, classify the repository, and finish
9
+ the applicable baseline workflow. Keep application source unchanged during adoption.
10
+
11
+ ## Authority rules
12
+
13
+ - Treat `.ultra/state.db` as the only durable Ultra authority.
14
+ - Preserve every existing `.ultra/` tree and migration backup.
15
+ - Require explicit authorization before replacing a healthy baseline or discarding a
16
+ corrupt database.
17
+ - Store only metadata references for external memory and code-graph providers.
18
+ - Create ordinary tasks only after the baseline is ready. Record characterization
19
+ needs and adoption gaps in the gap ledger until convergence.
20
+
21
+ ## Inspect and route
22
+
23
+ 1. Bind the repository root, Git branch and HEAD, worktree status, manifests, package
24
+ scripts, workspace markers, deployment files, and existing `.ultra/` assets.
25
+ 2. When `.ultra/` is absent, run **Bootstrap**.
26
+ 3. When `.ultra/tasks/tasks.json` contains tasks but `state.db` is absent or has no
27
+ tasks, run **Import projection-only state** before ordinary state-backed work.
28
+ 4. When `state.db` exists, run read-only project doctor first. Call `baseline.get`
29
+ only when doctor confirms that the current schema authority is readable. Route an
30
+ old schema to repair and a corrupt database to recovery without another DB read.
31
+ 5. After current authority is readable, call `task.init_project` with `resume: true` to install
32
+ only missing current scaffold files. Verify that existing artifacts were preserved.
33
+ 6. Route the result:
34
+ - healthy `ready` baseline: return `ultra-change` or `ultra-status`;
35
+ - `draft`, `adopting`, or baseline-blocked: resume the matching baseline;
36
+ - `migrated`: start evidence-backed brownfield re-adoption;
37
+ - old schema: run backup-first schema repair;
38
+ - corrupt database: preserve it and stop at the restore-or-rebaseline decision.
25
39
 
26
40
  ## Bootstrap
27
41
 
28
- When `.ultra/` is absent, derive project name, type, and stack from repository evidence,
29
- then call `task.init_project` with `mode: "auto"`. Use an explicit `greenfield` or
30
- `brownfield` mode only when the user has made that classification authoritative.
31
-
32
- Verify the returned mode, baseline id and status, state database path, initial
33
- projection, and copied specification files.
34
-
35
- ## Route by mode
36
-
37
- ### Greenfield
38
-
39
- The new baseline begins as `draft`. Route unresolved product or architecture intent to
40
- `ultra-research`. That workflow records evidence and converges the baseline before
41
- planning. Do not create implementation tasks during initialization.
42
-
43
- ### Brownfield
44
-
45
- Read `references/brownfield-adoption.md` completely. Adopt current behavior from the
46
- checkout, tests, maintained documentation, and runtime evidence. Use `baseline.record`
47
- for the bounded snapshot and `baseline.converge` only after the owner approves the
48
- captured baseline and any accepted known-red verification.
49
-
50
- ## Failure handling
51
-
52
- - `ULTRA_DIR_EXISTS`: inspect and resume; do not retry with overwrite automatically.
53
- - `BASELINE_EXISTS`: keep the ready baseline unless explicit re-adoption is required.
54
- - `BASELINE_IN_PROGRESS`: resume the named baseline rather than creating another.
55
- - `TEMPLATE_MISSING`: report a package-integrity failure and route to installer doctor.
56
- - `TARGET_NOT_DIR`, `VALIDATION_ERROR`, or `IO_ERROR`: correct only the evidenced input;
57
- preserve any backup and partial diagnostic.
58
-
59
- ## Output
60
-
61
- Report target path, detected mode, baseline id/status/revision, state health, known-red
62
- verification, blocking unknowns, and one next action. `.ultra/state.db` is authoritative;
63
- JSON and Markdown projections do not create state.
64
-
65
- Do not browse by default, invent missing behavior, rewrite application code, create
66
- business tasks, stage files, or commit as part of initialization.
42
+ Derive project metadata from repository evidence. Call `task.init_project` with
43
+ `mode: "auto"`. Pass `scope` when the user selected a monorepo boundary; otherwise use
44
+ the repository root. Use an explicit mode only when the user supplied an authoritative
45
+ classification.
46
+
47
+ Verify `repository_profile`, selected scope, detected mode, baseline lifecycle, schema
48
+ version, copied templates, initial projection, and `project_initialized` event.
49
+
50
+ ## Import projection-only state
51
+
52
+ Call `task.init_project` with `resume: true` as the single authority check and run the
53
+ exact supported backup-first import command returned in its structured error. Do not
54
+ infer an import path or edit the projection manually.
55
+
56
+ Verify imported task and event counts, backup path, current schema state, projection
57
+ parity, and the `migrated/adopting` compatibility baseline. Then call `baseline.start` with a
58
+ new id, `mode: "brownfield"`, `replace_migrated: true`, the selected scope, current
59
+ revision, and repository classification. Never treat the compatibility row as owner
60
+ approval.
61
+
62
+ For an older database schema, run `ultra-tools system doctor --repair`; verify both the
63
+ pre-migration backup and post-repair backup plus the current schema before continuing.
64
+ Then resume initialization to merge missing scaffold assets without overwriting the
65
+ project's existing baseline documents.
66
+
67
+ ## Complete the selected mode
68
+
69
+ For `brownfield`, `migrated`, or an incomplete existing adoption, read
70
+ `references/brownfield-adoption.md` completely and execute it through owner approval.
71
+
72
+ For `greenfield`, keep the baseline in `draft` until product and architecture intent is
73
+ evidence-backed. Route unresolved intent through `ultra-research`, record the complete
74
+ baseline snapshot, obtain owner approval, and converge it before planning.
75
+
76
+ ## Recovery handling
77
+
78
+ - `ULTRA_DIR_EXISTS`: inspect and resume the existing state.
79
+ - `LEGACY_STATE_MIGRATION_REQUIRED`: execute the returned migration command.
80
+ - `BASELINE_IN_PROGRESS`: resume the named row; never create a parallel authority.
81
+ - `BASELINE_EXISTS`: return the healthy route. Replacing a ready baseline is outside
82
+ ordinary initialization; stop for owner authorization before calling
83
+ `baseline.start` with a new id, `replace_ready: true`, and
84
+ `replacement_authorization: { approved_by, reason }`. The approval identity and
85
+ rationale must be persisted in the `baseline_started` event.
86
+ - `BASELINE_SCOPE_MISSING`: correct the selected monorepo boundary.
87
+ - `TEMPLATE_MISSING`: run installer doctor and reinstall through the host adapter.
88
+ - `STATE_DB_CORRUPT`: retain the database, inspect `.ultra/backups`, and obtain the
89
+ restore-or-rebaseline decision. Restore only a verified managed backup with
90
+ `ultra-tools system restore --backup <path> --confirm REPLACE_CORRUPT_ULTRA_STATE`.
91
+ When no valid backup exists and the owner explicitly accepts rebuilding authority,
92
+ run `ultra-tools system rebaseline --project-name <name> [--scope <path>] --confirm
93
+ REBASELINE_CORRUPT_ULTRA_STATE`; verify the quarantined database and legacy
94
+ projection paths before continuing adoption.
95
+ - `IO_ERROR`: verify rollback restoration and preserve every reported backup path.
96
+
97
+ ## Completion
98
+
99
+ Initialization is complete only when:
100
+
101
+ - current schema authority is readable;
102
+ - repository classification and scope are recorded;
103
+ - product and architecture baseline files exist;
104
+ - verification, unknowns, gaps, evidence, and provider references are recorded;
105
+ - explicit owner approval has converged the baseline to `ready`;
106
+ - `baseline.get` reports current health and project doctor has no authority failure.
107
+
108
+ Report the target, classification evidence, migration and backup paths, baseline id,
109
+ mode, status, revision, branch, worktree snapshot, verification results, gap summary,
110
+ approval state, and one exact next action. Stop at the approval step when owner consent
111
+ has not yet been provided.