atlas-project-harness 0.3.0-beta.3 → 0.3.0-beta.4

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/CHANGELOG.md CHANGED
@@ -4,6 +4,12 @@
4
4
 
5
5
  ---
6
6
 
7
+ ## [v0.3.0-beta.4] - 2026-11-17
8
+
9
+ ### 🧭 `atlas upgrade` 跟着运行路径装,不再诱导 sudo
10
+
11
+ * 机器上有两份安装时(例如用户 prefix `~/n` 与系统 `/usr/local`),`upgrade` 原先固定按 npm 默认 prefix 安装,撞上 root 所有的目录报 EACCES,并建议 `sudo npm install -g`。现在优先升级**正在运行的那份**(按它所在的 prefix 传 `--prefix`);检测到默认 prefix 不一致时打印两份路径、标明哪份生效,只动正在运行的那份;目标不可写时给出非 sudo 处置(用户级 prefix / nvm/fnm / install.sh)。源码树运行时明确提示会按 npm 默认 prefix 新增一份。
12
+
7
13
  ## [v0.3.0-beta.3] - 2026-11-17
8
14
 
9
15
  ### 🛡 清单版本门:0.3.0 预发布不再被误判成旧读者
package/README.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # Atlas — 践行 Project Harness 的全流程 AI 编程工作流
2
2
 
3
3
  <p align="left">
4
- <img src="https://img.shields.io/badge/version-0.3.0--beta.3-blue.svg" alt="Version" />
4
+ <img src="https://img.shields.io/badge/version-0.3.0--beta.4-blue.svg" alt="Version" />
5
5
  <img src="https://img.shields.io/badge/license-Apache--2.0-blue.svg" alt="License" />
6
6
  <img src="https://img.shields.io/badge/tests-passing-success.svg" alt="Tests" />
7
7
  <a href="https://sunwenzhe-git.github.io/atlas/"><img src="https://img.shields.io/badge/docs-VitePress-green.svg" alt="Docs" /></a>
@@ -28,7 +28,7 @@ CI 按锁还原由流水线自行 clone + checkout 承担(见 `shared/solution
28
28
  §7 status status / 锁成员与 acceptance_cutover 检查
29
29
  §8 B-0 ⓪ 层错误类型 / path_at / 历史前缀纯函数
30
30
  §9 D 批 check_solution / AC crosswalk / 契约检查
31
- §10 封条写侧 select_seal_path / freeze_seal / render_*
31
+ §10 封条写侧 已迁出 `solution_seal_ops.py`(select_seal_path / freeze_seal / render_*,本文件只做注入装配)
32
32
  """
33
33
  from __future__ import annotations
34
34
 
@@ -3815,202 +3815,30 @@ def has_apply_seal(root: Path) -> bool:
3815
3815
  return any(base.rglob("*.seal.json"))
3816
3816
 
3817
3817
 
3818
- # ---------------------------------------------------------------- 封条写侧(C 批)
3819
-
3820
- def select_seal_path(root: Path, requested: str | None = None) -> str:
3821
- """多封条选择:`--seal` 显式;否则唯一 HEAD 封条;多枚 ⇒ exit 2 候选。"""
3822
- lock = read_lock(root)
3823
- anchors = (lock or {}).get("seal_anchors")
3824
- by_path = {k: v for k, v in anchors.items()
3825
- if isinstance(v, dict)} if isinstance(anchors, dict) else {}
3826
- asset_root = (lock or {}).get("layout_assets_root") or _assets_root(root)
3827
- heads = _SEAL.head_seals(root, [asset_root])
3828
- try:
3829
- return _SEAL.select_seal(root, by_path, requested, heads)
3830
- except _SEAL.SealError as exc:
3831
- raise SolutionError(str(exc)) from exc
3832
-
3833
-
3834
- def _write_lock_doc(root: Path, doc: dict) -> Path:
3835
- path = lock_path(root)
3836
- tmp = path.with_suffix(path.suffix + ".tmp")
3837
- tmp.write_text(json.dumps(doc, ensure_ascii=False, indent=2) + "\n",
3838
- encoding="utf-8")
3839
- tmp.replace(path)
3840
- return path
3841
-
3842
-
3843
- def freeze_seal(root: Path, seal_path: str, at: str) -> dict:
3844
- """`seal freeze`:只写锁的 `state` / `frozen_at`,不碰封条字节(S-38)。"""
3845
- path = select_seal_path(root, seal_path)
3846
- if not _SEAL.is_seal_path(path):
3847
- raise SolutionError(f"--seal 不是合法封条路径: {path}")
3848
- if _SEAL.head_blob(root, path) is None:
3849
- raise SolutionError(f"HEAD 无封条文件: {path}")
3850
- hist = _SEAL.seal_history(root, path)
3851
- if hist["error"] or at not in hist["commits"]:
3852
- raise SolutionError(f"--at={at} 不是 {path} 的封条提交")
3853
- if at != hist["commits"][-1]:
3854
- raise SolutionError(
3855
- f"--at 必须是该路径最后一枚封条提交 L[-1]={hist['commits'][-1]}")
3856
- lock = read_lock(root)
3857
- if lock is None:
3858
- raise SolutionError(f"缺少 {LOCK_NAME};先 lock --update")
3859
- anchors = lock.get("seal_anchors")
3860
- if not isinstance(anchors, dict) or path not in anchors:
3861
- raise SolutionError(f"锁内没有该路径键(先 lock --update): {path}")
3862
- anchor = dict(anchors[path])
3863
- anchor["state"] = "frozen"
3864
- anchor["frozen_at"] = at
3865
- anchors[path] = anchor
3866
- lock["seal_anchors"] = anchors
3867
- _write_lock_doc(root, lock)
3868
- return {"seal": path, "state": "frozen", "frozen_at": at}
3869
-
3870
-
3871
- def reanchor_seal(root: Path, seal_path: str, review: str, from_a: str) -> dict:
3872
- """`seal reanchor`:重写纪元起点 + 同步 `exemption_started_at` + append 审计项。"""
3873
- cause, detail = _SEAL.repo_shape(root)
3874
- if cause:
3875
- raise SolutionError(f"拒绝 reanchor:{detail}({cause})")
3876
- path = select_seal_path(root, seal_path)
3877
- if not _SEAL.is_seal_path(path):
3878
- raise SolutionError(f"--seal 不是合法封条路径: {path}")
3879
- raw = _SEAL.head_blob(root, path)
3880
- if raw is None:
3881
- raise SolutionError(f"HEAD 无封条文件: {path}")
3882
- try:
3883
- head_doc = _SEAL.parse_seal(raw)
3884
- except _SEAL.SealError as exc:
3885
- raise SolutionError(str(exc)) from exc
3886
- if not re.fullmatch(r"[0-9a-f]{40}", str(from_a or "")):
3887
- raise SolutionError(f"--from-a 必须是 40 位提交 SHA: {from_a!r}")
3888
- if _SEAL._has_object(root, from_a):
3889
- raise SolutionError(
3890
- f"reanchor_not_allowed: from_a={from_a[:12]} 仍可达;"
3891
- "唯一可用路径是在未拉过旧历史的 fresh clone 上执行")
3892
- lock = read_lock(root)
3893
- if lock is None:
3894
- raise SolutionError(f"缺少 {LOCK_NAME};先 lock --update")
3895
- anchors = lock.get("seal_anchors")
3896
- if not isinstance(anchors, dict) or path not in anchors:
3897
- raise SolutionError(f"reanchor_anchor_missing: 锁内没有该路径键 {path}")
3898
- anchor = dict(anchors[path])
3899
- # v49/项 1:`moved_to` 与 `reanchor` 互斥——键已 `retired`(带 `moved_to`)或
3900
- # 封条本身带 `moved_to` 时,写侧拒绝、exit 2、不写任何文件。
3901
- if "moved_to" in anchor or "moved_to" in head_doc:
3902
- raise SolutionError(
3903
- "seal_move_reanchor_conflict: 该键 / 封条已带 moved_to(retired),"
3904
- "不得再写 reanchor")
3905
- hist = _SEAL.seal_history(root, path)
3906
- N = hist["N"]
3907
- if anchor.get("renewal_seq") != head_doc.get("renewal_seq") \
3908
- or anchor.get("n") != N:
3909
- raise SolutionError(
3910
- "seal_anchor_stale: 锁锚与 HEAD 封条 / N 不同步;先 lock --update")
3911
- if anchor.get("epoch_origin") != from_a:
3912
- raise SolutionError(
3913
- "reanchor_anchor_mismatch: from_a != seal_anchors[S].epoch_origin")
3914
- try:
3915
- payload = _SEAL.reanchor_payload(head_doc, from_a=from_a, review=review)
3916
- except _SEAL.SealError as exc:
3917
- raise SolutionError(str(exc)) from exc
3918
- payload["reanchor"]["base_seq"] = int(anchor.get("renewal_seq") or 0) + 1
3919
- payload["reanchor"]["base_n"] = int(anchor.get("n") or 0)
3920
- # 先验后写:审计链必须可从当前 origin 接续
3921
- chain = list(anchor.get("exemption_start_history") or [])
3922
- origin = anchor.get("exemption_start_origin")
3923
- old_started = anchor.get("exemption_started_at")
3924
- if chain:
3925
- if chain[-1].get("to") != old_started:
3926
- raise SolutionError(
3927
- "exemption_start_history_broken: 末项 to 与 exemption_started_at 不等")
3928
- prev_to = chain[-1].get("to")
3929
- else:
3930
- if origin != old_started:
3931
- raise SolutionError(
3932
- "exemption_start_history_broken: 无重指时 origin 必须等于 started_at")
3933
- prev_to = origin
3934
- target = Path(root) / path
3935
- target.parent.mkdir(parents=True, exist_ok=True)
3936
- target.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n",
3937
- encoding="utf-8")
3938
- new_started = payload["signed_at"]
3939
- chain.append({"from": prev_to, "to": new_started, "commit": _head(root)})
3940
- anchor["exemption_started_at"] = new_started
3941
- anchor["exemption_start_history"] = chain
3942
- anchor["renewal_seq"] = payload["renewal_seq"]
3943
- anchors[path] = anchor
3944
- lock["seal_anchors"] = anchors
3945
- _write_lock_doc(root, lock)
3946
- return {"seal": path, "renewal_seq": payload["renewal_seq"],
3947
- "reanchor": payload["reanchor"],
3948
- "exemption_started_at": new_started,
3949
- "next": "提交封条与本锁(reanchor 提交 R),再独立跑 lock --update 并提交 R2"}
3950
-
3951
-
3952
- def render_status(data: dict) -> str:
3953
- lines = [f"solution: {data['solution']} ({data['mode']})", "members:"]
3954
- for s in data["members"]:
3955
- head = (s.get("head") or "—")[:12]
3956
- dirty_n = s.get("dirty_count")
3957
- dirty = "clean" if dirty_n == 0 else (f"dirty:{dirty_n}" if dirty_n else "n/a")
3958
- ignored = "ignored" if s.get("ignored") else "ok"
3959
- if s.get("head_drift"):
3960
- drift = "drift"
3961
- elif s.get("locked_head"):
3962
- drift = "locked"
3963
- else:
3964
- drift = "no-lock"
3965
- lines.append(
3966
- f" {s['name']:<16} {s['path']:<20} git={str(s['git']).lower():<5} "
3967
- f"branch={s.get('branch') or '—':<12} head={head:<12} {dirty:<8} "
3968
- f"{drift:<7} atlas={'yes' if s['atlas_assets'] else 'no':<3} {ignored}")
3969
- lines.append(f"lock: {'present' if data['lock']['present'] else 'missing'}"
3970
- + (f" ({data['lock']['locked_at']})" if data['lock'].get('locked_at') else ""))
3971
- return "\n".join(lines)
3972
-
3818
+ # ---------------------------------------------------------------- 封条写侧装配(§10 已迁出)
3819
+ # 2026-11-17 P4/§10:`select_seal_path` / `freeze_seal` / `reanchor_seal` / `render_*`
3820
+ # 无入边,迁到 `solution_seal_ops.py`。它需要的辅助函数仍在本模块,故在本文件定义完成后
3821
+ # 加载并注入依赖(不反向 import,避免环)。模块名带本实例名,避免同一进程内不同加载器
3822
+ # (`_atlas_solution_core` / `_atlas_solution_test`)互相覆盖。
3823
+ def _install_seal_ops():
3824
+ name = f"{__name__}__seal_ops"
3825
+ spec = importlib.util.spec_from_file_location(
3826
+ name, Path(__file__).with_name("solution_seal_ops.py"))
3827
+ mod = importlib.util.module_from_spec(spec)
3828
+ sys.modules[name] = mod
3829
+ spec.loader.exec_module(mod)
3830
+ for dep in ("SolutionError", "_assets_root", "_SEAL", "read_lock", "lock_path",
3831
+ "LOCK_NAME", "_head"):
3832
+ setattr(mod, dep, globals()[dep])
3833
+ return mod
3973
3834
 
3974
- def render_check(data: dict) -> str:
3975
- lines = [f"solution check: {data['overall']}"]
3976
- for r in data["checks"]:
3977
- lines.append(f" [{r['status']}] {r['check']}: {r['detail']}")
3978
- return "\n".join(lines)
3979
3835
 
3836
+ _SEAL_OPS = _install_seal_ops()
3980
3837
 
3981
- def render_diff(data: dict) -> str:
3982
- lines = [f"solution diff: {data['solution']} ({data['mode']})"]
3983
- for m in data["members"]:
3984
- if not m["git"]:
3985
- lines.append(f" [{m['name']}] {m['path']} ! 不是 git 仓")
3986
- continue
3987
- locked = (m.get("locked_head") or "—")[:12]
3988
- lines.append(
3989
- f" [{m['name']}] {m['path']} branch={m.get('branch') or '—'} "
3990
- f"head={(m.get('head') or '—')[:12]} locked={locked}")
3991
- if not m.get("locked_head"):
3992
- lines.append(" lock=—(未锁定,仅显示工作区)")
3993
- elif m.get("lock_commit_present") is False:
3994
- lines.append(" ! 锁中 commit 不在本地;请先 fetch 对应成员")
3995
- elif m["commits"]:
3996
- lines.append(f" 自锁以来提交 {len(m['commits'])} 条:")
3997
- lines += [f" {c}" for c in m["commits"]]
3998
- if m["diffstat"]:
3999
- lines.append(" 自锁以来 diffstat:")
4000
- lines += [f" {c}" for c in m["diffstat"]]
4001
- if m["staged"]:
4002
- lines.append(" 已暂存:")
4003
- lines += [f" {c}" for c in m["staged"]]
4004
- if m["unstaged"]:
4005
- lines.append(" 未暂存:")
4006
- lines += [f" {c}" for c in m["unstaged"]]
4007
- if m["worktree"]:
4008
- lines.append(f" 工作区 {len(m['worktree'])} 项:")
4009
- lines += [f" {c}" for c in m["worktree"][:30]]
4010
- if len(m["worktree"]) > 30:
4011
- lines.append(f" …(其余 {len(m['worktree']) - 30} 项省略)")
4012
- if m.get("worktree_ok") is False:
4013
- lines.append(" ! git status 失败,无法判断工作区")
4014
- if not any((m["commits"], m["staged"], m["unstaged"], m["worktree"])):
4015
- lines.append(" clean(相对锁无差异)")
4016
- return "\n".join(lines)
3838
+ select_seal_path = _SEAL_OPS.select_seal_path
3839
+ _write_lock_doc = _SEAL_OPS._write_lock_doc
3840
+ freeze_seal = _SEAL_OPS.freeze_seal
3841
+ reanchor_seal = _SEAL_OPS.reanchor_seal
3842
+ render_status = _SEAL_OPS.render_status
3843
+ render_check = _SEAL_OPS.render_check
3844
+ render_diff = _SEAL_OPS.render_diff
@@ -0,0 +1,215 @@
1
+ """封条写侧(§10,2026-11-17 从 `solution.py` 迁出)。
2
+
3
+ 职责:多封条选择、`seal freeze` / `seal reanchor` 的锁写入,以及 status / check / diff
4
+ 的文本渲染。对外入口:`select_seal_path` / `freeze_seal` / `reanchor_seal` /
5
+ `render_status` / `render_check` / `render_diff`。
6
+
7
+ 依赖由 `solution.py` 在加载后注入(`SolutionError` / `_assets_root` / `_SEAL` /
8
+ `read_lock` / `lock_path` / `LOCK_NAME` / `_head`);本模块**不得反向 import** `solution.py`,
9
+ 否则形成环。
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import json
15
+ import re
16
+ from pathlib import Path
17
+
18
+
19
+ def select_seal_path(root: Path, requested: str | None = None) -> str:
20
+ """多封条选择:`--seal` 显式;否则唯一 HEAD 封条;多枚 ⇒ exit 2 候选。"""
21
+ lock = read_lock(root)
22
+ anchors = (lock or {}).get("seal_anchors")
23
+ by_path = {k: v for k, v in anchors.items()
24
+ if isinstance(v, dict)} if isinstance(anchors, dict) else {}
25
+ asset_root = (lock or {}).get("layout_assets_root") or _assets_root(root)
26
+ heads = _SEAL.head_seals(root, [asset_root])
27
+ try:
28
+ return _SEAL.select_seal(root, by_path, requested, heads)
29
+ except _SEAL.SealError as exc:
30
+ raise SolutionError(str(exc)) from exc
31
+
32
+
33
+ def _write_lock_doc(root: Path, doc: dict) -> Path:
34
+ path = lock_path(root)
35
+ tmp = path.with_suffix(path.suffix + ".tmp")
36
+ tmp.write_text(json.dumps(doc, ensure_ascii=False, indent=2) + "\n",
37
+ encoding="utf-8")
38
+ tmp.replace(path)
39
+ return path
40
+
41
+
42
+ def freeze_seal(root: Path, seal_path: str, at: str) -> dict:
43
+ """`seal freeze`:只写锁的 `state` / `frozen_at`,不碰封条字节(S-38)。"""
44
+ path = select_seal_path(root, seal_path)
45
+ if not _SEAL.is_seal_path(path):
46
+ raise SolutionError(f"--seal 不是合法封条路径: {path}")
47
+ if _SEAL.head_blob(root, path) is None:
48
+ raise SolutionError(f"HEAD 无封条文件: {path}")
49
+ hist = _SEAL.seal_history(root, path)
50
+ if hist["error"] or at not in hist["commits"]:
51
+ raise SolutionError(f"--at={at} 不是 {path} 的封条提交")
52
+ if at != hist["commits"][-1]:
53
+ raise SolutionError(
54
+ f"--at 必须是该路径最后一枚封条提交 L[-1]={hist['commits'][-1]}")
55
+ lock = read_lock(root)
56
+ if lock is None:
57
+ raise SolutionError(f"缺少 {LOCK_NAME};先 lock --update")
58
+ anchors = lock.get("seal_anchors")
59
+ if not isinstance(anchors, dict) or path not in anchors:
60
+ raise SolutionError(f"锁内没有该路径键(先 lock --update): {path}")
61
+ anchor = dict(anchors[path])
62
+ anchor["state"] = "frozen"
63
+ anchor["frozen_at"] = at
64
+ anchors[path] = anchor
65
+ lock["seal_anchors"] = anchors
66
+ _write_lock_doc(root, lock)
67
+ return {"seal": path, "state": "frozen", "frozen_at": at}
68
+
69
+
70
+ def reanchor_seal(root: Path, seal_path: str, review: str, from_a: str) -> dict:
71
+ """`seal reanchor`:重写纪元起点 + 同步 `exemption_started_at` + append 审计项。"""
72
+ cause, detail = _SEAL.repo_shape(root)
73
+ if cause:
74
+ raise SolutionError(f"拒绝 reanchor:{detail}({cause})")
75
+ path = select_seal_path(root, seal_path)
76
+ if not _SEAL.is_seal_path(path):
77
+ raise SolutionError(f"--seal 不是合法封条路径: {path}")
78
+ raw = _SEAL.head_blob(root, path)
79
+ if raw is None:
80
+ raise SolutionError(f"HEAD 无封条文件: {path}")
81
+ try:
82
+ head_doc = _SEAL.parse_seal(raw)
83
+ except _SEAL.SealError as exc:
84
+ raise SolutionError(str(exc)) from exc
85
+ if not re.fullmatch(r"[0-9a-f]{40}", str(from_a or "")):
86
+ raise SolutionError(f"--from-a 必须是 40 位提交 SHA: {from_a!r}")
87
+ if _SEAL._has_object(root, from_a):
88
+ raise SolutionError(
89
+ f"reanchor_not_allowed: from_a={from_a[:12]} 仍可达;"
90
+ "唯一可用路径是在未拉过旧历史的 fresh clone 上执行")
91
+ lock = read_lock(root)
92
+ if lock is None:
93
+ raise SolutionError(f"缺少 {LOCK_NAME};先 lock --update")
94
+ anchors = lock.get("seal_anchors")
95
+ if not isinstance(anchors, dict) or path not in anchors:
96
+ raise SolutionError(f"reanchor_anchor_missing: 锁内没有该路径键 {path}")
97
+ anchor = dict(anchors[path])
98
+ # v49/项 1:`moved_to` 与 `reanchor` 互斥——键已 `retired`(带 `moved_to`)或
99
+ # 封条本身带 `moved_to` 时,写侧拒绝、exit 2、不写任何文件。
100
+ if "moved_to" in anchor or "moved_to" in head_doc:
101
+ raise SolutionError(
102
+ "seal_move_reanchor_conflict: 该键 / 封条已带 moved_to(retired),"
103
+ "不得再写 reanchor")
104
+ hist = _SEAL.seal_history(root, path)
105
+ N = hist["N"]
106
+ if anchor.get("renewal_seq") != head_doc.get("renewal_seq") \
107
+ or anchor.get("n") != N:
108
+ raise SolutionError(
109
+ "seal_anchor_stale: 锁锚与 HEAD 封条 / N 不同步;先 lock --update")
110
+ if anchor.get("epoch_origin") != from_a:
111
+ raise SolutionError(
112
+ "reanchor_anchor_mismatch: from_a != seal_anchors[S].epoch_origin")
113
+ try:
114
+ payload = _SEAL.reanchor_payload(head_doc, from_a=from_a, review=review)
115
+ except _SEAL.SealError as exc:
116
+ raise SolutionError(str(exc)) from exc
117
+ payload["reanchor"]["base_seq"] = int(anchor.get("renewal_seq") or 0) + 1
118
+ payload["reanchor"]["base_n"] = int(anchor.get("n") or 0)
119
+ # 先验后写:审计链必须可从当前 origin 接续
120
+ chain = list(anchor.get("exemption_start_history") or [])
121
+ origin = anchor.get("exemption_start_origin")
122
+ old_started = anchor.get("exemption_started_at")
123
+ if chain:
124
+ if chain[-1].get("to") != old_started:
125
+ raise SolutionError(
126
+ "exemption_start_history_broken: 末项 to 与 exemption_started_at 不等")
127
+ prev_to = chain[-1].get("to")
128
+ else:
129
+ if origin != old_started:
130
+ raise SolutionError(
131
+ "exemption_start_history_broken: 无重指时 origin 必须等于 started_at")
132
+ prev_to = origin
133
+ target = Path(root) / path
134
+ target.parent.mkdir(parents=True, exist_ok=True)
135
+ target.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n",
136
+ encoding="utf-8")
137
+ new_started = payload["signed_at"]
138
+ chain.append({"from": prev_to, "to": new_started, "commit": _head(root)})
139
+ anchor["exemption_started_at"] = new_started
140
+ anchor["exemption_start_history"] = chain
141
+ anchor["renewal_seq"] = payload["renewal_seq"]
142
+ anchors[path] = anchor
143
+ lock["seal_anchors"] = anchors
144
+ _write_lock_doc(root, lock)
145
+ return {"seal": path, "renewal_seq": payload["renewal_seq"],
146
+ "reanchor": payload["reanchor"],
147
+ "exemption_started_at": new_started,
148
+ "next": "提交封条与本锁(reanchor 提交 R),再独立跑 lock --update 并提交 R2"}
149
+
150
+
151
+ def render_status(data: dict) -> str:
152
+ lines = [f"solution: {data['solution']} ({data['mode']})", "members:"]
153
+ for s in data["members"]:
154
+ head = (s.get("head") or "—")[:12]
155
+ dirty_n = s.get("dirty_count")
156
+ dirty = "clean" if dirty_n == 0 else (f"dirty:{dirty_n}" if dirty_n else "n/a")
157
+ ignored = "ignored" if s.get("ignored") else "ok"
158
+ if s.get("head_drift"):
159
+ drift = "drift"
160
+ elif s.get("locked_head"):
161
+ drift = "locked"
162
+ else:
163
+ drift = "no-lock"
164
+ lines.append(
165
+ f" {s['name']:<16} {s['path']:<20} git={str(s['git']).lower():<5} "
166
+ f"branch={s.get('branch') or '—':<12} head={head:<12} {dirty:<8} "
167
+ f"{drift:<7} atlas={'yes' if s['atlas_assets'] else 'no':<3} {ignored}")
168
+ lines.append(f"lock: {'present' if data['lock']['present'] else 'missing'}"
169
+ + (f" ({data['lock']['locked_at']})" if data['lock'].get('locked_at') else ""))
170
+ return "\n".join(lines)
171
+
172
+
173
+ def render_check(data: dict) -> str:
174
+ lines = [f"solution check: {data['overall']}"]
175
+ for r in data["checks"]:
176
+ lines.append(f" [{r['status']}] {r['check']}: {r['detail']}")
177
+ return "\n".join(lines)
178
+
179
+
180
+ def render_diff(data: dict) -> str:
181
+ lines = [f"solution diff: {data['solution']} ({data['mode']})"]
182
+ for m in data["members"]:
183
+ if not m["git"]:
184
+ lines.append(f" [{m['name']}] {m['path']} ! 不是 git 仓")
185
+ continue
186
+ locked = (m.get("locked_head") or "—")[:12]
187
+ lines.append(
188
+ f" [{m['name']}] {m['path']} branch={m.get('branch') or '—'} "
189
+ f"head={(m.get('head') or '—')[:12]} locked={locked}")
190
+ if not m.get("locked_head"):
191
+ lines.append(" lock=—(未锁定,仅显示工作区)")
192
+ elif m.get("lock_commit_present") is False:
193
+ lines.append(" ! 锁中 commit 不在本地;请先 fetch 对应成员")
194
+ elif m["commits"]:
195
+ lines.append(f" 自锁以来提交 {len(m['commits'])} 条:")
196
+ lines += [f" {c}" for c in m["commits"]]
197
+ if m["diffstat"]:
198
+ lines.append(" 自锁以来 diffstat:")
199
+ lines += [f" {c}" for c in m["diffstat"]]
200
+ if m["staged"]:
201
+ lines.append(" 已暂存:")
202
+ lines += [f" {c}" for c in m["staged"]]
203
+ if m["unstaged"]:
204
+ lines.append(" 未暂存:")
205
+ lines += [f" {c}" for c in m["unstaged"]]
206
+ if m["worktree"]:
207
+ lines.append(f" 工作区 {len(m['worktree'])} 项:")
208
+ lines += [f" {c}" for c in m["worktree"][:30]]
209
+ if len(m["worktree"]) > 30:
210
+ lines.append(f" …(其余 {len(m['worktree']) - 30} 项省略)")
211
+ if m.get("worktree_ok") is False:
212
+ lines.append(" ! git status 失败,无法判断工作区")
213
+ if not any((m["commits"], m["staged"], m["unstaged"], m["worktree"])):
214
+ lines.append(" clean(相对锁无差异)")
215
+ return "\n".join(lines)
package/bin/atlas.js CHANGED
@@ -109,6 +109,48 @@ function exitWithResult(res, tool) {
109
109
  process.exit(typeof res.status === 'number' ? res.status : 1);
110
110
  }
111
111
 
112
+ /**
113
+ * 从正在运行的安装路径反推 npm 全局 prefix。
114
+ * POSIX: `<prefix>/lib/node_modules/<pkg>`;Windows: `<prefix>/node_modules/<pkg>`。
115
+ * 源码树(不在 node_modules 下)返回 null。
116
+ */
117
+ function installPrefixFrom(pkgRoot) {
118
+ const marker = `${path.sep}node_modules${path.sep}`;
119
+ const idx = pkgRoot.lastIndexOf(marker);
120
+ if (idx < 0) return null;
121
+ const parts = pkgRoot.slice(0, idx).split(path.sep);
122
+ if (parts[parts.length - 1] === 'lib') parts.pop();
123
+ const prefix = parts.join(path.sep);
124
+ return prefix || path.sep;
125
+ }
126
+
127
+ function npmGlobalPrefix(npmCmd) {
128
+ const res = spawnSync(npmCmd, ['config', 'get', 'prefix'], {
129
+ encoding: 'utf8',
130
+ env: process.env,
131
+ });
132
+ if (res.status !== 0 || !res.stdout) return null;
133
+ const out = res.stdout.trim();
134
+ return out || null;
135
+ }
136
+
137
+ function samePath(a, b) {
138
+ try {
139
+ return fs.realpathSync(a) === fs.realpathSync(b);
140
+ } catch (_) {
141
+ return path.resolve(a) === path.resolve(b);
142
+ }
143
+ }
144
+
145
+ function isWritableDir(dir) {
146
+ try {
147
+ fs.accessSync(dir, fs.constants.W_OK);
148
+ return true;
149
+ } catch (_) {
150
+ return false;
151
+ }
152
+ }
153
+
112
154
  switch (command) {
113
155
  case 'init': {
114
156
  const passthroughArgs = args.slice(1);
@@ -286,7 +328,8 @@ Atlas upgrade — 自动拉取 npm 最新全局包升级全局 Atlas CLI
286
328
  -h, --help 查看帮助信息
287
329
 
288
330
  说明:
289
- atlas upgrade 会调用 npm install -g 升级全局包 atlas-project-harness。
331
+ atlas upgrade 默认升级"当前正在运行的那份"安装(按它所在的 npm prefix 安装),
332
+ 不会因为机器上另有一份全局包就去改系统目录;不会建议或要求 sudo。
290
333
  升级成功后,可进入项目目录运行 atlas update 刷新项目内的工程线束与模板。
291
334
  `);
292
335
  process.exit(0);
@@ -301,13 +344,44 @@ Atlas upgrade — 自动拉取 npm 最新全局包升级全局 Atlas CLI
301
344
 
302
345
  const pkg = require(path.join(PKG_ROOT, 'package.json'));
303
346
  const targetPkg = `${pkg.name}@${tag}`;
347
+ const npmCmd = process.platform === 'win32' ? 'npm.cmd' : 'npm';
348
+
349
+ // 目标 prefix 以「正在运行的这份」为准;npm 默认 prefix 只用于诊断,
350
+ // 避免机器上有两份安装时把包装到另一份(常见是 root 所有的 /usr/local)。
351
+ const ownPrefix = installPrefixFrom(PKG_ROOT);
352
+ const npmPrefix = npmGlobalPrefix(npmCmd);
304
353
 
305
354
  console.log(`\n[Atlas Upgrade] 准备升级全局 CLI (${pkg.name})...`);
306
355
  console.log(` 当前版本 : v${pkg.version}`);
307
356
  console.log(` 目标包 : ${targetPkg}`);
357
+ console.log(` 安装路径 : ${PKG_ROOT}`);
358
+ if (ownPrefix) {
359
+ console.log(` 生效 prefix: ${ownPrefix}`);
360
+ if (npmPrefix && !samePath(npmPrefix, ownPrefix)) {
361
+ console.log(` 注意: npm 默认 prefix 是 ${npmPrefix},与正在运行的这份不一致(可能有两份安装)。`);
362
+ console.log(` 本次只升级正在运行的那份,不动 ${npmPrefix}。`);
363
+ }
364
+ } else {
365
+ console.log(` 注意: 当前运行的是源码树而非 npm 全局安装;将按 npm 默认 prefix`
366
+ + `${npmPrefix ? `(${npmPrefix})` : ''}安装,可能新增一份。`);
367
+ }
308
368
 
309
- const npmCmd = process.platform === 'win32' ? 'npm.cmd' : 'npm';
310
- const installArgs = ['install', '-g', targetPkg];
369
+ const installArgs = ['install', '-g'];
370
+ if (ownPrefix) {
371
+ const modulesDir = path.dirname(PKG_ROOT);
372
+ if (!isWritableDir(modulesDir)) {
373
+ console.error(`\n[Atlas Upgrade] ❌ 目标目录不可写: ${modulesDir}`);
374
+ console.error(` 不要用 sudo:那会把包装进系统目录,和当前运行的这份形成两份安装。`);
375
+ console.error(` 可选处置:`);
376
+ console.error(` 1) 若用 nvm/fnm 管理 node,重装后直接执行: ${npmCmd} install -g ${targetPkg}`);
377
+ console.error(` 2) 改用用户级 prefix: npm config set prefix ~/.npm-global,`
378
+ + `并把 ~/.npm-global/bin 加入 PATH 后重装`);
379
+ console.error(` 3) 若这份由 install.sh 安装,改用 install.sh 更新\n`);
380
+ process.exit(2);
381
+ }
382
+ installArgs.push('--prefix', ownPrefix);
383
+ }
384
+ installArgs.push(targetPkg);
311
385
 
312
386
  if (isDryRun) {
313
387
  console.log(` [dry-run] 将执行命令: ${npmCmd} ${installArgs.join(' ')}\n`);
@@ -327,7 +401,8 @@ Atlas upgrade — 自动拉取 npm 最新全局包升级全局 Atlas CLI
327
401
  } else {
328
402
  console.error(`\n[Atlas Upgrade] ❌ 升级失败 (退出码: ${res.status})。`);
329
403
  console.error(`常见原因与排查建议:`);
330
- console.error(` 1. 权限不足: 全局安装可能需要管理员权限,可尝试: sudo npm install -g ${targetPkg}`);
404
+ console.error(` 1. 权限不足: 不要用 sudo(会装到系统目录、与当前运行的那份并存);`
405
+ + `改用用户级 prefix(npm config set prefix ~/.npm-global)或 nvm/fnm 后重试`);
331
406
  console.error(` 2. 网络或代理问题: 请检查 npm 源或网络代理设置(如 http_proxy)\n`);
332
407
  }
333
408
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "atlas-project-harness",
3
- "version": "0.3.0-beta.3",
3
+ "version": "0.3.0-beta.4",
4
4
  "description": "践行 Project Harness 的全流程 AI 编程工作流治理引擎",
5
5
  "bin": {
6
6
  "atlas": "bin/atlas.js"