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.
- package/.ultra-template/docs/research/README.md +21 -44
- package/.ultra-template/specs/discovery.md +10 -0
- package/CHANGELOG.md +95 -1
- package/README.md +31 -16
- package/adapters/_shared/codex-assets.cjs +23 -163
- package/adapters/_shared/handbook.cjs +2 -2
- package/adapters/_shared/runtime-assets.cjs +1 -0
- package/adapters/_shared/tests/runtime-assets.test.cjs +18 -0
- package/adapters/opencode.js +30 -120
- package/adapters/tests/claude.test.cjs +3 -2
- package/adapters/tests/codex-hook.test.cjs +34 -7
- package/adapters/tests/codex.test.cjs +21 -6
- package/adapters/tests/kimi-hook.test.cjs +34 -7
- package/adapters/tests/opencode.test.cjs +70 -84
- package/commands/ultra-init.md +1 -1
- package/docs/AGENT-CONTEXT.md +10 -6
- package/docs/ARCHITECTURE.md +40 -17
- package/docs/PLAN.zh-CN.md +5 -4
- package/docs/ROADMAP.md +2 -2
- package/docs/RUNTIME-COMPAT-MATRIX.md +4 -4
- package/docs/STATE-DB-ACCESS-POLICY.md +3 -3
- package/docs/USER-HANDBOOK-CONTRACT.md +5 -4
- package/hooks/active_task_context.py +22 -50
- package/hooks/context_spine.py +61 -299
- package/hooks/health_check.py +19 -17
- package/hooks/pre_stop_check.py +28 -33
- package/hooks/subagent_tracker.py +13 -19
- package/hooks/workflow_checkpoint.py +39 -47
- package/hooks/workflow_context.py +4 -9
- package/hooks/workflow_resume.py +48 -128
- package/mcp-server/breadcrumb.cjs +22 -0
- package/mcp-server/lib/archive-journal.cjs +192 -0
- package/mcp-server/lib/archive-journal.test.cjs +35 -0
- package/mcp-server/lib/baseline-workflow.cjs +404 -38
- package/mcp-server/lib/baseline-workflow.test.cjs +252 -0
- package/mcp-server/lib/change-workflow.cjs +249 -75
- package/mcp-server/lib/change-workflow.test.cjs +235 -1
- package/mcp-server/lib/context-spine.test.cjs +5 -0
- package/mcp-server/lib/doctor.cjs +14 -1
- package/mcp-server/lib/doctor.test.cjs +42 -4
- package/mcp-server/lib/init-project.cjs +292 -9
- package/mcp-server/lib/prd-parser.cjs +14 -41
- package/mcp-server/lib/prd-parser.test.cjs +49 -138
- package/mcp-server/lib/project-breadcrumb.cjs +139 -0
- package/mcp-server/lib/project-breadcrumb.test.cjs +112 -0
- package/mcp-server/lib/spec-learning.test.cjs +1 -1
- package/mcp-server/lib/state-authority.cjs +9 -3
- package/mcp-server/lib/state-db.cjs +154 -32
- package/mcp-server/lib/state-db.test.cjs +136 -4
- package/mcp-server/lib/state-ops.cjs +68 -6
- package/mcp-server/lib/task-expander.cjs +14 -37
- package/mcp-server/lib/task-expander.test.cjs +80 -164
- package/mcp-server/server.cjs +34 -37
- package/mcp-server/tests/init-project.test.cjs +162 -1
- package/mcp-server/tests/migrate.test.cjs +33 -0
- package/mcp-server/tests/server-contract.test.cjs +391 -17
- package/mcp-server/tests/state-db.test.cjs +14 -2
- package/mcp-server/tests/state-ops.test.cjs +108 -0
- package/package.json +2 -4
- package/skills/cc-collab/SKILL.md +2 -2
- package/skills/codex-collab/SKILL.md +2 -3
- package/skills/ultra-change/SKILL.md +18 -10
- package/skills/ultra-deliver/SKILL.md +13 -9
- package/skills/ultra-dev/SKILL.md +6 -4
- package/skills/ultra-doctor/SKILL.md +22 -7
- package/skills/ultra-init/SKILL.md +104 -59
- package/skills/ultra-init/references/brownfield-adoption.md +65 -37
- package/skills/ultra-plan/SKILL.md +20 -7
- package/skills/ultra-research/SKILL.md +12 -5
- package/skills/ultra-status/SKILL.md +6 -4
- package/skills/ultra-verify/SKILL.md +21 -30
- package/skills/ultra-verify/scripts/verify_wait.py +54 -54
- package/spec/cli-protocol.md +11 -1
- package/spec/mcp-tools.yaml +133 -19
- package/spec/schemas/state-db.sql +11 -0
- package/ultra-tools/cli.cjs +9 -5
- package/ultra-tools/commands/migrate.cjs +62 -36
- package/ultra-tools/commands/status.cjs +18 -9
- package/ultra-tools/commands/system.cjs +340 -6
- package/ultra-tools/commands/task.cjs +7 -1
- package/ultra-tools/status-command.test.cjs +29 -0
- package/ultra-tools/system-command.test.cjs +252 -1
- package/mcp-server/lib/llm-client.cjs +0 -157
- package/mcp-server/lib/llm-client.test.cjs +0 -156
- package/orchestrator/planner/expand-prompt.cjs +0 -62
- package/orchestrator/planner/expand-prompt.test.cjs +0 -52
- package/orchestrator/planner/prd-prompt.cjs +0 -44
- package/orchestrator/planner/prd-prompt.test.cjs +0 -30
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env python3
|
|
2
|
-
"""Write a
|
|
2
|
+
"""Write a recovery projection of the canonical DB breadcrumb before compaction."""
|
|
3
3
|
|
|
4
4
|
import json
|
|
5
5
|
import os
|
|
@@ -8,18 +8,12 @@ import tempfile
|
|
|
8
8
|
from datetime import datetime, timezone
|
|
9
9
|
from pathlib import Path
|
|
10
10
|
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
and isinstance(state.get("command"), str)
|
|
18
|
-
and bool(state["command"].strip())
|
|
19
|
-
and state.get("step") is not None
|
|
20
|
-
and isinstance(state.get("status"), str)
|
|
21
|
-
and bool(state["status"].strip())
|
|
22
|
-
)
|
|
11
|
+
from context_spine import (
|
|
12
|
+
ContextSpineError,
|
|
13
|
+
find_root,
|
|
14
|
+
read_breadcrumb,
|
|
15
|
+
render_breadcrumb,
|
|
16
|
+
)
|
|
23
17
|
|
|
24
18
|
|
|
25
19
|
def main() -> None:
|
|
@@ -29,41 +23,39 @@ def main() -> None:
|
|
|
29
23
|
except json.JSONDecodeError as exc:
|
|
30
24
|
print(f"[workflow_checkpoint] invalid hook input: {exc}", file=sys.stderr)
|
|
31
25
|
data = {}
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
break
|
|
42
|
-
if not valid_workflow(state):
|
|
43
|
-
print(f"[workflow_checkpoint] invalid workflow state in {state_file}", file=sys.stderr)
|
|
44
|
-
break
|
|
45
|
-
if state.get("status") in TERMINAL:
|
|
46
|
-
break
|
|
47
|
-
runtime_dir = root / ".ultra" / "runtime"
|
|
48
|
-
runtime_dir.mkdir(parents=True, exist_ok=True)
|
|
49
|
-
checkpoint = {
|
|
50
|
-
"schema": 1,
|
|
51
|
-
"captured_at": datetime.now(timezone.utc).isoformat(),
|
|
52
|
-
"session_id": data.get("session_id", ""),
|
|
53
|
-
"workflow": state,
|
|
54
|
-
}
|
|
55
|
-
fd, temp_name = tempfile.mkstemp(prefix="checkpoint.", suffix=".json", dir=runtime_dir)
|
|
56
|
-
try:
|
|
57
|
-
with os.fdopen(fd, "w", encoding="utf-8") as handle:
|
|
58
|
-
json.dump(checkpoint, handle, ensure_ascii=False, indent=2)
|
|
59
|
-
handle.write("\n")
|
|
60
|
-
os.replace(temp_name, runtime_dir / "checkpoint.json")
|
|
61
|
-
finally:
|
|
62
|
-
if os.path.exists(temp_name):
|
|
63
|
-
os.unlink(temp_name)
|
|
64
|
-
print(json.dumps({"systemMessage": "Ultra workflow checkpoint saved."}))
|
|
26
|
+
root = find_root(Path(data.get("cwd") or Path.cwd()).resolve())
|
|
27
|
+
if root is None:
|
|
28
|
+
print(json.dumps({}))
|
|
29
|
+
return
|
|
30
|
+
try:
|
|
31
|
+
breadcrumb = read_breadcrumb(root)
|
|
32
|
+
except ContextSpineError as exc:
|
|
33
|
+
print(f"[workflow_checkpoint] cannot inspect Context Spine: {exc}", file=sys.stderr)
|
|
34
|
+
print(json.dumps({}))
|
|
65
35
|
return
|
|
66
|
-
|
|
36
|
+
if not breadcrumb or not breadcrumb.get("change_id"):
|
|
37
|
+
print(json.dumps({}))
|
|
38
|
+
return
|
|
39
|
+
|
|
40
|
+
runtime_dir = root / ".ultra" / "runtime"
|
|
41
|
+
runtime_dir.mkdir(parents=True, exist_ok=True)
|
|
42
|
+
checkpoint = {
|
|
43
|
+
"schema": 2,
|
|
44
|
+
"captured_at": datetime.now(timezone.utc).isoformat(),
|
|
45
|
+
"session_id": data.get("session_id", ""),
|
|
46
|
+
"breadcrumb": dict(breadcrumb),
|
|
47
|
+
"rendered": render_breadcrumb(root, breadcrumb),
|
|
48
|
+
}
|
|
49
|
+
fd, temp_name = tempfile.mkstemp(prefix="checkpoint.", suffix=".json", dir=runtime_dir)
|
|
50
|
+
try:
|
|
51
|
+
with os.fdopen(fd, "w", encoding="utf-8") as handle:
|
|
52
|
+
json.dump(checkpoint, handle, ensure_ascii=False, indent=2)
|
|
53
|
+
handle.write("\n")
|
|
54
|
+
os.replace(temp_name, runtime_dir / "checkpoint.json")
|
|
55
|
+
finally:
|
|
56
|
+
if os.path.exists(temp_name):
|
|
57
|
+
os.unlink(temp_name)
|
|
58
|
+
print(json.dumps({"systemMessage": "Ultra workflow checkpoint saved."}))
|
|
67
59
|
|
|
68
60
|
|
|
69
61
|
if __name__ == "__main__":
|
|
@@ -2,11 +2,10 @@
|
|
|
2
2
|
"""Inject one compact Ultra state position without persistent memory."""
|
|
3
3
|
|
|
4
4
|
import json
|
|
5
|
-
import sqlite3
|
|
6
5
|
import sys
|
|
7
6
|
from pathlib import Path
|
|
8
7
|
|
|
9
|
-
from context_spine import find_root, read_breadcrumb, render_breadcrumb
|
|
8
|
+
from context_spine import ContextSpineError, find_root, read_breadcrumb, render_breadcrumb
|
|
10
9
|
|
|
11
10
|
|
|
12
11
|
def payload() -> dict:
|
|
@@ -26,18 +25,14 @@ def main() -> None:
|
|
|
26
25
|
return
|
|
27
26
|
try:
|
|
28
27
|
breadcrumb = read_breadcrumb(root)
|
|
29
|
-
except
|
|
28
|
+
except ContextSpineError as exc:
|
|
30
29
|
print(f"[workflow_context] cannot inspect Context Spine: {exc}", file=sys.stderr)
|
|
31
30
|
breadcrumb = None
|
|
32
31
|
if breadcrumb:
|
|
33
32
|
context = render_breadcrumb(root, breadcrumb)
|
|
34
33
|
else:
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
f"Project: {root}",
|
|
38
|
-
"No active continuous change. Start daily work with the ultra-change workflow.",
|
|
39
|
-
"Authority: .ultra/state.db; JSON/Markdown remain projections or evidence artifacts.",
|
|
40
|
-
])
|
|
34
|
+
print(json.dumps({}))
|
|
35
|
+
return
|
|
41
36
|
print(json.dumps({"hookSpecificOutput": {
|
|
42
37
|
"hookEventName": "SessionStart",
|
|
43
38
|
"additionalContext": context,
|
package/hooks/workflow_resume.py
CHANGED
|
@@ -1,84 +1,53 @@
|
|
|
1
1
|
#!/usr/bin/env python3
|
|
2
|
-
"""
|
|
2
|
+
"""Re-inject live DB authority after compaction; checkpoints are advisory only."""
|
|
3
3
|
|
|
4
4
|
import json
|
|
5
|
-
import os
|
|
6
|
-
import sqlite3
|
|
7
5
|
import sys
|
|
8
|
-
import
|
|
9
|
-
from datetime import datetime, timezone
|
|
6
|
+
from datetime import datetime
|
|
10
7
|
from pathlib import Path
|
|
11
8
|
|
|
12
|
-
from context_spine import
|
|
9
|
+
from context_spine import (
|
|
10
|
+
ContextSpineError,
|
|
11
|
+
find_root,
|
|
12
|
+
read_breadcrumb,
|
|
13
|
+
render_breadcrumb,
|
|
14
|
+
)
|
|
13
15
|
|
|
14
|
-
TERMINAL = {"committed", "completed", "done", "cancelled"}
|
|
15
16
|
|
|
17
|
+
def _hook_output(event: str, text: str) -> dict:
|
|
18
|
+
if event == "SessionStart":
|
|
19
|
+
return {"hookSpecificOutput": {
|
|
20
|
+
"hookEventName": "SessionStart",
|
|
21
|
+
"additionalContext": text,
|
|
22
|
+
}}
|
|
23
|
+
return {"additionalContext": text}
|
|
16
24
|
|
|
17
|
-
def valid_workflow(state: object) -> bool:
|
|
18
|
-
return (
|
|
19
|
-
isinstance(state, dict)
|
|
20
|
-
and isinstance(state.get("command"), str)
|
|
21
|
-
and bool(state["command"].strip())
|
|
22
|
-
and state.get("step") is not None
|
|
23
|
-
and isinstance(state.get("status"), str)
|
|
24
|
-
and bool(state["status"].strip())
|
|
25
|
-
)
|
|
26
25
|
|
|
27
|
-
|
|
28
|
-
|
|
26
|
+
def _checkpoint_advisory(root: Path):
|
|
27
|
+
file = root / ".ultra" / "runtime" / "checkpoint.json"
|
|
29
28
|
if not file.is_file():
|
|
30
29
|
return None
|
|
31
30
|
try:
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
def parse_time(value: object):
|
|
39
|
-
if not isinstance(value, str) or not value.strip():
|
|
40
|
-
return None
|
|
41
|
-
try:
|
|
42
|
-
return datetime.fromisoformat(value.replace("Z", "+00:00")).astimezone(timezone.utc)
|
|
43
|
-
except ValueError:
|
|
44
|
-
return None
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
def newest_time(file: Path, *values: object) -> datetime:
|
|
48
|
-
candidates = [parsed for value in values if (parsed := parse_time(value)) is not None]
|
|
49
|
-
try:
|
|
50
|
-
candidates.append(datetime.fromtimestamp(file.stat().st_mtime, tz=timezone.utc))
|
|
51
|
-
except OSError:
|
|
52
|
-
pass
|
|
53
|
-
return max(candidates, default=datetime.min.replace(tzinfo=timezone.utc))
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
def load_checkpoint(file: Path):
|
|
57
|
-
checkpoint = read_json(file, "checkpoint")
|
|
58
|
-
if checkpoint is None:
|
|
31
|
+
value = json.loads(file.read_text(encoding="utf-8"))
|
|
32
|
+
datetime.fromisoformat(str(value.get("captured_at", "")).replace("Z", "+00:00"))
|
|
33
|
+
except (OSError, json.JSONDecodeError, ValueError, AttributeError) as exc:
|
|
34
|
+
print(f"[workflow_resume] cannot read checkpoint {file}: {exc}", file=sys.stderr)
|
|
59
35
|
return None
|
|
60
|
-
if
|
|
36
|
+
if (
|
|
37
|
+
not isinstance(value, dict)
|
|
38
|
+
or value.get("schema") != 2
|
|
39
|
+
or not isinstance(value.get("breadcrumb"), dict)
|
|
40
|
+
or not isinstance(value.get("rendered"), str)
|
|
41
|
+
or not value["rendered"].strip()
|
|
42
|
+
):
|
|
61
43
|
print(f"[workflow_resume] invalid checkpoint schema in {file}", file=sys.stderr)
|
|
62
44
|
return None
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
def restore_state(file: Path, state: dict) -> None:
|
|
72
|
-
file.parent.mkdir(parents=True, exist_ok=True)
|
|
73
|
-
fd, temp_name = tempfile.mkstemp(prefix="workflow-state.", suffix=".json", dir=file.parent)
|
|
74
|
-
try:
|
|
75
|
-
with os.fdopen(fd, "w", encoding="utf-8") as handle:
|
|
76
|
-
json.dump(state, handle, ensure_ascii=False, indent=2)
|
|
77
|
-
handle.write("\n")
|
|
78
|
-
os.replace(temp_name, file)
|
|
79
|
-
finally:
|
|
80
|
-
if os.path.exists(temp_name):
|
|
81
|
-
os.unlink(temp_name)
|
|
45
|
+
return "\n".join([
|
|
46
|
+
"[Ultra checkpoint advisory]",
|
|
47
|
+
"Live .ultra/state.db could not be read; this checkpoint is not authority.",
|
|
48
|
+
value["rendered"],
|
|
49
|
+
"Run ultra-doctor before mutation.",
|
|
50
|
+
])
|
|
82
51
|
|
|
83
52
|
|
|
84
53
|
def main() -> None:
|
|
@@ -88,72 +57,23 @@ def main() -> None:
|
|
|
88
57
|
except json.JSONDecodeError as exc:
|
|
89
58
|
print(f"[workflow_resume] invalid hook input: {exc}", file=sys.stderr)
|
|
90
59
|
data = {}
|
|
91
|
-
|
|
92
|
-
root
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
breadcrumb = None
|
|
60
|
+
root = find_root(Path(data.get("cwd") or Path.cwd()).resolve())
|
|
61
|
+
if root is None:
|
|
62
|
+
print(json.dumps({}))
|
|
63
|
+
return
|
|
64
|
+
text = None
|
|
65
|
+
try:
|
|
66
|
+
breadcrumb = read_breadcrumb(root)
|
|
99
67
|
if breadcrumb:
|
|
100
68
|
text = render_breadcrumb(root, breadcrumb)
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
}}))
|
|
107
|
-
else:
|
|
108
|
-
print(json.dumps({"additionalContext": text}))
|
|
109
|
-
return
|
|
110
|
-
for root in (start, *start.parents):
|
|
111
|
-
state_file = root / ".ultra" / "workflow-state.json"
|
|
112
|
-
checkpoint_file = root / ".ultra" / "runtime" / "checkpoint.json"
|
|
113
|
-
if not state_file.is_file() and not checkpoint_file.is_file():
|
|
114
|
-
continue
|
|
115
|
-
live = read_json(state_file, "workflow state")
|
|
116
|
-
if live is not None and not valid_workflow(live):
|
|
117
|
-
print(f"[workflow_resume] invalid workflow state in {state_file}", file=sys.stderr)
|
|
118
|
-
live = None
|
|
119
|
-
if live is not None and live.get("status") in TERMINAL:
|
|
120
|
-
break
|
|
121
|
-
checkpoint = load_checkpoint(checkpoint_file)
|
|
122
|
-
checkpoint_state = checkpoint["workflow"] if checkpoint is not None else None
|
|
123
|
-
if checkpoint_state is not None and checkpoint_state.get("status") in TERMINAL:
|
|
124
|
-
checkpoint_state = None
|
|
125
|
-
|
|
126
|
-
source = ".ultra/workflow-state.json"
|
|
127
|
-
state = live
|
|
128
|
-
if checkpoint_state is not None:
|
|
129
|
-
checkpoint_time = newest_time(
|
|
130
|
-
checkpoint_file, checkpoint_state.get("ts"), checkpoint.get("captured_at")
|
|
131
|
-
)
|
|
132
|
-
live_time = newest_time(state_file, live.get("ts")) if live is not None else None
|
|
133
|
-
if live_time is None or checkpoint_time >= live_time:
|
|
134
|
-
state = checkpoint_state
|
|
135
|
-
source = ".ultra/runtime/checkpoint.json"
|
|
136
|
-
restore_state(state_file, state)
|
|
137
|
-
if state is None:
|
|
138
|
-
break
|
|
139
|
-
text = (
|
|
140
|
-
"[Ultra workflow resumed] "
|
|
141
|
-
f"command={state.get('command', 'unknown')}; "
|
|
142
|
-
f"task={state.get('task_id', state.get('task', 'unknown'))}; "
|
|
143
|
-
f"step={state.get('step', 'unknown')}; status={state.get('status', 'active')}. "
|
|
144
|
-
f"source={source}. Continue from the recovered workflow boundary and verify "
|
|
145
|
-
"task/session/change state through .ultra/state.db."
|
|
146
|
-
)
|
|
147
|
-
event = data.get("hook_event_name", "SessionStart")
|
|
148
|
-
if event == "SessionStart":
|
|
149
|
-
print(json.dumps({"hookSpecificOutput": {
|
|
150
|
-
"hookEventName": "SessionStart",
|
|
151
|
-
"additionalContext": text,
|
|
152
|
-
}}))
|
|
153
|
-
else:
|
|
154
|
-
print(json.dumps({"additionalContext": text}))
|
|
69
|
+
except ContextSpineError as exc:
|
|
70
|
+
print(f"[workflow_resume] cannot inspect Context Spine: {exc}", file=sys.stderr)
|
|
71
|
+
text = _checkpoint_advisory(root)
|
|
72
|
+
if not text:
|
|
73
|
+
print(json.dumps({}))
|
|
155
74
|
return
|
|
156
|
-
|
|
75
|
+
event = data.get("hook_event_name", "SessionStart")
|
|
76
|
+
print(json.dumps(_hook_output(event, text)))
|
|
157
77
|
|
|
158
78
|
|
|
159
79
|
if __name__ == "__main__":
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
const fs = require('node:fs');
|
|
5
|
+
const path = require('node:path');
|
|
6
|
+
|
|
7
|
+
const runtime = fs.existsSync(path.join(__dirname, 'index.cjs'))
|
|
8
|
+
? require('./index.cjs')
|
|
9
|
+
: require('./server.cjs');
|
|
10
|
+
|
|
11
|
+
function main() {
|
|
12
|
+
const rootDir = path.resolve(process.argv[2] || process.cwd());
|
|
13
|
+
const breadcrumb = runtime.readProjectBreadcrumb(rootDir);
|
|
14
|
+
process.stdout.write(`${JSON.stringify({
|
|
15
|
+
breadcrumb,
|
|
16
|
+
text: breadcrumb ? runtime.renderProjectBreadcrumb(rootDir, breadcrumb) : null,
|
|
17
|
+
})}\n`);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
if (require.main === module) main();
|
|
21
|
+
|
|
22
|
+
module.exports = { main };
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const fs = require('node:fs');
|
|
4
|
+
const path = require('node:path');
|
|
5
|
+
|
|
6
|
+
const INTENT_FILE = '.archive-intent.json';
|
|
7
|
+
const INTENT_VERSION = '1.0';
|
|
8
|
+
|
|
9
|
+
class ArchiveJournalError extends Error {
|
|
10
|
+
constructor(code, message) {
|
|
11
|
+
super(message);
|
|
12
|
+
this.name = 'ArchiveJournalError';
|
|
13
|
+
this.code = code;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function resolveInside(rootDir, relative, field) {
|
|
18
|
+
if (typeof relative !== 'string' || !relative.trim() || path.isAbsolute(relative)) {
|
|
19
|
+
throw new ArchiveJournalError('ARCHIVE_INTENT_INVALID', `${field} must be project-relative`);
|
|
20
|
+
}
|
|
21
|
+
const root = path.resolve(rootDir);
|
|
22
|
+
const resolved = path.resolve(root, relative);
|
|
23
|
+
if (resolved !== root && !resolved.startsWith(`${root}${path.sep}`)) {
|
|
24
|
+
throw new ArchiveJournalError('ARCHIVE_INTENT_INVALID', `${field} escapes project root`);
|
|
25
|
+
}
|
|
26
|
+
return resolved;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function assertIntent(intent, rootDir) {
|
|
30
|
+
if (!intent || typeof intent !== 'object' || Array.isArray(intent)
|
|
31
|
+
|| intent.schema_version !== INTENT_VERSION
|
|
32
|
+
|| typeof intent.change_id !== 'string' || !intent.change_id
|
|
33
|
+
|| !Array.isArray(intent.baseline_updates)
|
|
34
|
+
|| typeof intent.summary !== 'string' || intent.summary.trim().length < 3) {
|
|
35
|
+
throw new ArchiveJournalError('ARCHIVE_INTENT_INVALID', 'archive intent shape is invalid');
|
|
36
|
+
}
|
|
37
|
+
const source = resolveInside(rootDir, intent.source, 'source');
|
|
38
|
+
const destination = resolveInside(rootDir, intent.destination, 'destination');
|
|
39
|
+
const activeRoot = path.resolve(rootDir, '.ultra', 'changes', 'active');
|
|
40
|
+
const archiveRoot = path.resolve(rootDir, '.ultra', 'changes', 'archive');
|
|
41
|
+
if (path.dirname(source) !== activeRoot || path.basename(source) !== intent.change_id) {
|
|
42
|
+
throw new ArchiveJournalError('ARCHIVE_INTENT_INVALID', 'archive intent source is not the active change root');
|
|
43
|
+
}
|
|
44
|
+
if (path.dirname(destination) !== archiveRoot
|
|
45
|
+
|| !path.basename(destination).endsWith(`-${intent.change_id}`)) {
|
|
46
|
+
throw new ArchiveJournalError('ARCHIVE_INTENT_INVALID', 'archive intent destination is not the change archive root');
|
|
47
|
+
}
|
|
48
|
+
for (const update of intent.baseline_updates) resolveInside(rootDir, update, 'baseline update');
|
|
49
|
+
if (intent.previous_summary !== null && typeof intent.previous_summary !== 'string') {
|
|
50
|
+
throw new ArchiveJournalError('ARCHIVE_INTENT_INVALID', 'previous_summary must be string or null');
|
|
51
|
+
}
|
|
52
|
+
return { intent, source, destination };
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function readIntentFile(file, rootDir) {
|
|
56
|
+
let intent;
|
|
57
|
+
try { intent = JSON.parse(fs.readFileSync(file, 'utf8')); }
|
|
58
|
+
catch (error) {
|
|
59
|
+
throw new ArchiveJournalError('ARCHIVE_INTENT_CORRUPT', `cannot read ${file}: ${error.message}`);
|
|
60
|
+
}
|
|
61
|
+
return assertIntent(intent, rootDir);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function writeJsonAtomic(file, value) {
|
|
65
|
+
const temp = `${file}.${process.pid}.tmp`;
|
|
66
|
+
fs.writeFileSync(temp, `${JSON.stringify(value, null, 2)}\n`, { flag: 'wx' });
|
|
67
|
+
fs.renameSync(temp, file);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function renderSummary(change, summary, baselineUpdates, noBaselineChangeReason) {
|
|
71
|
+
return [
|
|
72
|
+
`# Archived change: ${change.title}`, '', summary.trim(), '',
|
|
73
|
+
'## Baseline reconciliation', '',
|
|
74
|
+
...(baselineUpdates.length > 0
|
|
75
|
+
? baselineUpdates.map((file) => `- ${file}`)
|
|
76
|
+
: [noBaselineChangeReason]), '',
|
|
77
|
+
].join('\n');
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function sameOperation(intent, { change, summary, baselineUpdates, noBaselineChangeReason }) {
|
|
81
|
+
return intent.change_id === change.id
|
|
82
|
+
&& intent.source === change.artifact_root
|
|
83
|
+
&& intent.summary === summary.trim()
|
|
84
|
+
&& JSON.stringify(intent.baseline_updates) === JSON.stringify(baselineUpdates)
|
|
85
|
+
&& (intent.no_baseline_change_reason || null) === (noBaselineChangeReason || null);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function prepareArchiveMove({
|
|
89
|
+
rootDir, change, summary, baselineUpdates, noBaselineChangeReason, now = new Date(),
|
|
90
|
+
}) {
|
|
91
|
+
const date = now.toISOString().slice(0, 10);
|
|
92
|
+
const source = resolveInside(rootDir, change.artifact_root, 'source');
|
|
93
|
+
const destinationRelative = path.join('.ultra', 'changes', 'archive', `${date}-${change.id}`);
|
|
94
|
+
const destination = resolveInside(rootDir, destinationRelative, 'destination');
|
|
95
|
+
const sourceIntentFile = path.join(source, INTENT_FILE);
|
|
96
|
+
const destinationIntentFile = path.join(destination, INTENT_FILE);
|
|
97
|
+
|
|
98
|
+
if (!fs.existsSync(source) && fs.existsSync(destinationIntentFile)) {
|
|
99
|
+
const resumed = readIntentFile(destinationIntentFile, rootDir);
|
|
100
|
+
if (!sameOperation(resumed.intent, {
|
|
101
|
+
change, summary, baselineUpdates, noBaselineChangeReason,
|
|
102
|
+
})) {
|
|
103
|
+
throw new ArchiveJournalError('ARCHIVE_INTENT_CONFLICT', 'existing archive intent differs from retry input');
|
|
104
|
+
}
|
|
105
|
+
return { ...resumed, resumed: true };
|
|
106
|
+
}
|
|
107
|
+
if (!fs.existsSync(source)) {
|
|
108
|
+
throw new ArchiveJournalError('ARCHIVE_SOURCE_MISSING', `active change root missing: ${change.artifact_root}`);
|
|
109
|
+
}
|
|
110
|
+
if (fs.existsSync(destination)) {
|
|
111
|
+
throw new ArchiveJournalError('ARCHIVE_EXISTS', `archive already exists: ${destination}`);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
let prepared;
|
|
115
|
+
if (fs.existsSync(sourceIntentFile)) {
|
|
116
|
+
prepared = readIntentFile(sourceIntentFile, rootDir);
|
|
117
|
+
if (!sameOperation(prepared.intent, {
|
|
118
|
+
change, summary, baselineUpdates, noBaselineChangeReason,
|
|
119
|
+
})) {
|
|
120
|
+
throw new ArchiveJournalError('ARCHIVE_INTENT_CONFLICT', 'prepared archive intent differs from retry input');
|
|
121
|
+
}
|
|
122
|
+
} else {
|
|
123
|
+
const summaryPath = path.join(source, 'archive-summary.md');
|
|
124
|
+
const previousSummary = fs.existsSync(summaryPath) ? fs.readFileSync(summaryPath, 'utf8') : null;
|
|
125
|
+
const intent = {
|
|
126
|
+
schema_version: INTENT_VERSION,
|
|
127
|
+
change_id: change.id,
|
|
128
|
+
source: change.artifact_root,
|
|
129
|
+
destination: destinationRelative,
|
|
130
|
+
summary: summary.trim(),
|
|
131
|
+
baseline_updates: baselineUpdates,
|
|
132
|
+
no_baseline_change_reason: noBaselineChangeReason || null,
|
|
133
|
+
previous_summary: previousSummary,
|
|
134
|
+
created_at: now.toISOString(),
|
|
135
|
+
};
|
|
136
|
+
writeJsonAtomic(sourceIntentFile, intent);
|
|
137
|
+
prepared = assertIntent(intent, rootDir);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
fs.writeFileSync(
|
|
141
|
+
path.join(source, 'archive-summary.md'),
|
|
142
|
+
renderSummary(change, summary, baselineUpdates, noBaselineChangeReason),
|
|
143
|
+
);
|
|
144
|
+
fs.mkdirSync(path.dirname(destination), { recursive: true });
|
|
145
|
+
fs.renameSync(source, destination);
|
|
146
|
+
return { ...prepared, source, destination, resumed: false };
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function listArchiveIntents(rootDir) {
|
|
150
|
+
const roots = [
|
|
151
|
+
path.join(rootDir, '.ultra', 'changes', 'active'),
|
|
152
|
+
path.join(rootDir, '.ultra', 'changes', 'archive'),
|
|
153
|
+
];
|
|
154
|
+
const found = [];
|
|
155
|
+
for (const parent of roots) {
|
|
156
|
+
if (!fs.existsSync(parent)) continue;
|
|
157
|
+
for (const entry of fs.readdirSync(parent, { withFileTypes: true })) {
|
|
158
|
+
if (!entry.isDirectory()) continue;
|
|
159
|
+
const file = path.join(parent, entry.name, INTENT_FILE);
|
|
160
|
+
if (!fs.existsSync(file)) continue;
|
|
161
|
+
try { found.push({ ...readIntentFile(file, rootDir), file, error: null }); }
|
|
162
|
+
catch (error) { found.push({ file, error }); }
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
return found;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function completeArchiveIntent(rootDir, intent) {
|
|
169
|
+
const { destination } = assertIntent(intent, rootDir);
|
|
170
|
+
fs.rmSync(path.join(destination, INTENT_FILE), { force: true });
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function rollbackArchiveIntent(rootDir, intent) {
|
|
174
|
+
const { source, destination } = assertIntent(intent, rootDir);
|
|
175
|
+
if (fs.existsSync(destination) && !fs.existsSync(source)) fs.renameSync(destination, source);
|
|
176
|
+
if (!fs.existsSync(source) || fs.existsSync(destination)) {
|
|
177
|
+
throw new ArchiveJournalError('ARCHIVE_ROLLBACK_FAILED', 'archive roots are not in a recoverable state');
|
|
178
|
+
}
|
|
179
|
+
const summaryPath = path.join(source, 'archive-summary.md');
|
|
180
|
+
if (intent.previous_summary === null) fs.rmSync(summaryPath, { force: true });
|
|
181
|
+
else fs.writeFileSync(summaryPath, intent.previous_summary);
|
|
182
|
+
fs.rmSync(path.join(source, INTENT_FILE), { force: true });
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
module.exports = {
|
|
186
|
+
ArchiveJournalError,
|
|
187
|
+
INTENT_FILE,
|
|
188
|
+
prepareArchiveMove,
|
|
189
|
+
listArchiveIntents,
|
|
190
|
+
completeArchiveIntent,
|
|
191
|
+
rollbackArchiveIntent,
|
|
192
|
+
};
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const test = require('node:test');
|
|
4
|
+
const assert = require('node:assert/strict');
|
|
5
|
+
const fs = require('node:fs');
|
|
6
|
+
const os = require('node:os');
|
|
7
|
+
const path = require('node:path');
|
|
8
|
+
|
|
9
|
+
const journal = require('./archive-journal.cjs');
|
|
10
|
+
|
|
11
|
+
test('archive journal restores the exact active directory when finalization cannot run', () => {
|
|
12
|
+
const rootDir = fs.mkdtempSync(path.join(os.tmpdir(), 'ubp-archive-journal-'));
|
|
13
|
+
const source = path.join(rootDir, '.ultra', 'changes', 'active', 'change-a');
|
|
14
|
+
fs.mkdirSync(source, { recursive: true });
|
|
15
|
+
fs.writeFileSync(path.join(source, 'intent.md'), '# Change A\n');
|
|
16
|
+
try {
|
|
17
|
+
const prepared = journal.prepareArchiveMove({
|
|
18
|
+
rootDir,
|
|
19
|
+
change: { id: 'change-a', title: 'Change A', artifact_root: '.ultra/changes/active/change-a' },
|
|
20
|
+
summary: 'Archive Change A.', baselineUpdates: [],
|
|
21
|
+
noBaselineChangeReason: 'No baseline content changed.',
|
|
22
|
+
now: new Date('2026-07-18T00:00:00.000Z'),
|
|
23
|
+
});
|
|
24
|
+
assert.equal(fs.existsSync(prepared.source), false);
|
|
25
|
+
assert.equal(journal.listArchiveIntents(rootDir).length, 1);
|
|
26
|
+
|
|
27
|
+
journal.rollbackArchiveIntent(rootDir, prepared.intent);
|
|
28
|
+
assert.equal(fs.existsSync(source), true);
|
|
29
|
+
assert.equal(fs.existsSync(path.join(source, 'intent.md')), true);
|
|
30
|
+
assert.equal(fs.existsSync(path.join(source, 'archive-summary.md')), false);
|
|
31
|
+
assert.equal(journal.listArchiveIntents(rootDir).length, 0);
|
|
32
|
+
} finally {
|
|
33
|
+
fs.rmSync(rootDir, { recursive: true, force: true });
|
|
34
|
+
}
|
|
35
|
+
});
|