atlas-project-harness 0.4.0-beta.1 → 0.4.0-beta.3

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,41 @@
4
4
 
5
5
  ---
6
6
 
7
+ ## [v0.4.0-beta.3] - 2026-11-20
8
+
9
+ ### 🧭 只读上下文预览
10
+
11
+ * 新增 `atlas workflow context`:按文件路径打印会注入的结构规范与约定,只读、不写盘、不改任务状态;
12
+ * `--paths`(改动文件/目录,可多个)与 `--unit`(读任务卡 `paths` / `affected_domains`)二选一,都没有时 exit 2;`--json` 输出命中清单,便于脚本消费;
13
+ * 显式 `--paths` 不回落 `tour.md`,与 `dispatch` 的注入口径一致;
14
+ * 约定规范的排序改为只按**实际命中**的 glob 计具体度:通用指南列了更多目录,也不会挤掉对口的领域约定(如改前端时优先 `conventions/frontend/` 而非 `conventions/guides/`)。
15
+
16
+ ### 🧷 项目接线
17
+
18
+ * `.gitignore` 接线新增 `.atlas` 白名单块:默认 `.atlas/*` 忽略引擎镜像,`!.atlas/tasks/`、`!.atlas/spec/` 放行项目规范与任务账本;带标记幂等,用户已手写任意 `.atlas` 规则时保留其口径不覆盖。
19
+
20
+ ---
21
+
22
+ ## [v0.4.0-beta.2] - 2026-11-20
23
+
24
+ ### 🧭 执行层最小上下文注入
25
+
26
+ * `atlas workflow dispatch` 按 `--paths` / 任务卡 `paths` 匹配 `.atlas/spec/**` 的 `paths:` 索引,只注入命中的结构事实与约定(结构优先、约定至多补 1 份、上限 3 份);无路径时按 `affected_domains` 回退,完全无信号才注入 `tour.md`;
27
+ * glob 语义对齐 Trellis:`**` 跨目录、`*` 不跨目录,目录 scope 与尾斜杠可命中;支持行内数组 / BOM / 行内注释 / 去重,绝对路径按项目根相对化,逃出根不命中;
28
+ * `plan` / `run` 支持 `--paths`;重跑 `plan` 继承已存路径,同具体度下约定不再挤掉域透镜;注入围栏按正文最长反引号串自动加长。
29
+
30
+ ### 🔒 执行层稳定性
31
+
32
+ * `finish` 按完整任务 id 精确匹配审查目录,杜绝 `T-1` 复用 `T-10` 的报告;收口前比对 `review_scope` 摘要,审查后暂存区内容变化会阻断;
33
+ * `dispatch` 拒绝对 completed / 前置依赖未满足的任务重复派发;`finish` 拒绝账本外或越界 unit;`plan` 重跑清理未派发的孤儿子卡;
34
+ * 任务账本改为原子写(tmp + replace),坏卡显式报错而非静默跳过;`run --dry-run` 不再落盘,`verify` 空暂存区提前返回 2,`status --unit` 生效。
35
+
36
+ ### 📚 规范开户口径
37
+
38
+ * 规范开户合并进 `atlas-structure`(开户模式),references 随技能分发;`testid.md` 明确由 E2E 环生成,结构环不双写;
39
+ * `AGENTS.md` 托管段收成 Trellis 式瘦指针:`.atlas/` 知识索引 + 装配≠开户 + plan/dispatch/verify/finish 入口 + §15 上报出口;恢复 Windows `python` 口径;
40
+ * 同步 `docs/map` 计数与命令面(`--paths`、patches 1 族)、README、`shared/layout` 与 `apply/reference` adopt 说明。
41
+
7
42
  ## [v0.4.0-beta.1] - 2026-11-19
8
43
 
9
44
  ### 🧭 执行层自主化:移除 Trellis,Atlas workflow 接管
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.4.0--beta.1-blue.svg" alt="Version" />
4
+ <img src="https://img.shields.io/badge/version-0.4.0--beta.3-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>
@@ -122,7 +122,7 @@ NBER(美国国家经济研究局)2026 年工作论文 35275 追踪了超过
122
122
  1. **项目级(应然资产层)**:定义“这个系统是什么、长什么样、怎么算做对”。包含**结构事实**(适配器 AST / 正则逆向抽取;图谱为可选文件枚举增强)、**项目级 PRD**(业务规则单源)、**E2E 验收用例**(真实靶场可证伪用例),以及跨需求生效的**架构决策记录**(`<资产根>/adr/NNNN-<slug>.md`,默认 `product/adr/...`)。
123
123
  2. **需求级(小需求执行层)**:定义“这次改动改什么、怎么写代码”。由内置的 **`atlas workflow`** 执行层承担,Atlas 本身**不侵入业务代码实现**。
124
124
  3. **`apply` 单向衔接**:需求在进入实现前,先由 Agent 唤起 `atlas-apply <需求ID>` 技能将需求增量合并入项目级应然资产,坚决杜绝“先写代码、事后补文档”的失控循环。
125
- 4. **执行层命令**:`atlas workflow plan --unit <ID>`(建卡)→ `atlas workflow dispatch`(出派工单)→ `atlas workflow verify --unit <ID>`(独立审查)→ `atlas workflow finish --unit <ID>`(收口);`atlas workflow status` / `atlas workflow run` 负责查账与串联。任务账本落 `.atlas/tasks/`。
125
+ 4. **执行层命令**:`atlas workflow plan --unit <ID> [--paths <glob...>]`(建卡)→ `atlas workflow dispatch [--paths <file...>]`(出派工单 + 按 `paths:` 只注入命中的结构事实与约定规范)→ `atlas workflow verify --unit <ID>`(独立审查)→ `atlas workflow finish --unit <ID>`(收口);`atlas workflow status` / `atlas workflow run` 负责查账与串联;中途范围变化时用只读的 `atlas workflow context --paths <file...>` 预览命中规范(不写盘、不改状态)。任务账本落 `.atlas/tasks/`。
126
126
 
127
127
  ### 2. 核心武器库:三环资产体系(Rings)
128
128
 
@@ -0,0 +1,397 @@
1
+ #!/usr/bin/env python3
2
+ """Atlas Workflow Context —— 按改动路径选取最小结构上下文。
3
+
4
+ Trellis 的 spec 注入模型:任务涉及哪些文件,就只注入这些文件命中的规范。
5
+ Atlas 的同构实现:
6
+
7
+ - 规范 = `.atlas/spec/**/*.md` 里**带 `paths:` frontmatter** 的文件
8
+ (结构环 `tour.md` / `domains/<domain>.md`、约定薄桩 `conventions/*.md`);
9
+ - 命中 = 任务改动路径对任一 glob 成立;`**` 跨目录、`*` 不跨目录;
10
+ - 最小化 = 显式改动路径存在时**不注入** `**` 兜底规范;结构规范优先,
11
+ 约定规范至多补 1 份;最多 3 份;
12
+ - 域回退 = 无改动路径时,用任务卡的 `affected_domains` 匹配 `domains/<domain>.md`;
13
+ - 完全无信号时,只注入 `**` 兜底规范(如 `tour.md`)供导航。
14
+
15
+ 纯标准库实现。
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import posixpath
20
+ import re
21
+ from functools import lru_cache
22
+ from pathlib import Path
23
+
24
+ SPEC_DIRS = (".atlas/spec/structure", ".atlas/spec/conventions")
25
+ MAX_SPECS = 3
26
+ MAX_LINES_PER_SPEC = 80
27
+ MAX_CHARS_PER_SPEC = 4000
28
+ MAX_FILE_BYTES = 1_000_000
29
+
30
+ _FM_RE = re.compile(r"\A---\s*\n(.*?)\n---\s*\n?", re.S)
31
+ _PATH_ITEM_RE = re.compile(r"^\s*-\s*(.+?)\s*$")
32
+ _PATHS_KEY_RE = re.compile(r"^paths\s*:(.*)$")
33
+ _WILDCARDS = ("**", "**/*", "*")
34
+
35
+
36
+ class ContextError(ValueError):
37
+ """结构上下文选取异常。"""
38
+
39
+
40
+ # ---------------------------------------------------------------- frontmatter
41
+
42
+ def _strip_comment(raw: str) -> str:
43
+ """去掉引号外的行内注释(`- apps/web/** # 前端`)。"""
44
+ out: list[str] = []
45
+ quote = ""
46
+ for ch in raw:
47
+ if quote:
48
+ if ch == quote:
49
+ quote = ""
50
+ out.append(ch)
51
+ elif ch in ("'", '"'):
52
+ quote = ch
53
+ out.append(ch)
54
+ elif ch == "#":
55
+ break
56
+ else:
57
+ out.append(ch)
58
+ return "".join(out).strip()
59
+
60
+
61
+ def _unquote(raw: str) -> str:
62
+ s = raw.strip()
63
+ if len(s) >= 2 and s[0] == s[-1] and s[0] in ("'", '"'):
64
+ return s[1:-1]
65
+ return s
66
+
67
+
68
+ def _split_flow_items(raw: str) -> list[str]:
69
+ """解析 `["a", 'b']` 的内部;引号内的逗号不切。"""
70
+ items: list[str] = []
71
+ buf: list[str] = []
72
+ quote = ""
73
+ for ch in raw:
74
+ if quote:
75
+ if ch == quote:
76
+ quote = ""
77
+ buf.append(ch)
78
+ elif ch in ("'", '"'):
79
+ quote = ch
80
+ buf.append(ch)
81
+ elif ch == ",":
82
+ items.append("".join(buf))
83
+ buf = []
84
+ else:
85
+ buf.append(ch)
86
+ if "".join(buf).strip():
87
+ items.append("".join(buf))
88
+ return [_unquote(_strip_comment(i)) for i in items]
89
+
90
+
91
+ def _dedupe(items: list[str]) -> list[str]:
92
+ seen: set[str] = set()
93
+ out: list[str] = []
94
+ for item in items:
95
+ if item and item not in seen:
96
+ seen.add(item)
97
+ out.append(item)
98
+ return out
99
+
100
+
101
+ def _split_frontmatter(text: str) -> tuple[dict, str]:
102
+ text = text.lstrip("\ufeff")
103
+ m = _FM_RE.match(text)
104
+ if not m:
105
+ return {}, text
106
+ paths: list[str] = []
107
+ lines = m.group(1).splitlines()
108
+ in_paths = False
109
+ i = 0
110
+ while i < len(lines):
111
+ line = lines[i]
112
+ stripped = line.strip()
113
+ key = _PATHS_KEY_RE.match(stripped)
114
+ if key:
115
+ rest = key.group(1).strip()
116
+ if rest.startswith("["):
117
+ buf = rest
118
+ while "]" not in buf and i + 1 < len(lines):
119
+ i += 1
120
+ buf += " " + lines[i].strip()
121
+ inner = buf[1:buf.index("]")] if "]" in buf else buf[1:]
122
+ paths.extend(_split_flow_items(inner))
123
+ in_paths = False
124
+ elif rest:
125
+ paths.append(_unquote(_strip_comment(rest)))
126
+ in_paths = False
127
+ else:
128
+ in_paths = True
129
+ i += 1
130
+ continue
131
+ if in_paths:
132
+ item = _PATH_ITEM_RE.match(line)
133
+ if item:
134
+ paths.append(_unquote(_strip_comment(item.group(1))))
135
+ elif stripped:
136
+ in_paths = False
137
+ i += 1
138
+ paths = _dedupe(paths)
139
+ return ({"paths": paths} if paths else {}), text[m.end():]
140
+
141
+
142
+ def load_specs(root: Path) -> list[dict]:
143
+ """读取全部带 `paths:` 的规范文件(相对路径 + globs + 去 frontmatter 正文)。"""
144
+ root = root.resolve()
145
+ specs: list[dict] = []
146
+ for rel_dir in SPEC_DIRS:
147
+ base = root / rel_dir
148
+ if not base.is_dir():
149
+ continue
150
+ for p in sorted(base.rglob("*.md")):
151
+ try:
152
+ if p.stat().st_size > MAX_FILE_BYTES:
153
+ continue
154
+ text = p.read_text(encoding="utf-8", errors="replace")
155
+ except OSError:
156
+ continue
157
+ meta, body = _split_frontmatter(text)
158
+ if not meta.get("paths"):
159
+ continue
160
+ specs.append({
161
+ "rel": p.relative_to(root).as_posix(),
162
+ "name": p.stem,
163
+ "paths": meta["paths"],
164
+ "body": body.strip(),
165
+ })
166
+ return specs
167
+
168
+
169
+ # ---------------------------------------------------------------- path / glob
170
+
171
+ def _norm_glob(raw: str) -> str:
172
+ """glob 只做斜杠归一与 `./` 清理;**不做** normpath(会吃掉尾 `/`)。"""
173
+ g = str(raw).strip().replace("\\", "/")
174
+ while g.startswith("./"):
175
+ g = g[2:]
176
+ if g.endswith("/"):
177
+ g += "**"
178
+ return g
179
+
180
+
181
+ def _is_wildcard(glob: str) -> bool:
182
+ return _norm_glob(glob) in _WILDCARDS
183
+
184
+
185
+ @lru_cache(maxsize=512)
186
+ def _glob_regex(glob: str) -> re.Pattern[str]:
187
+ """`**` 跨目录、`*` 不跨目录;`a/**` 允许零段;`[!x]` 取反。"""
188
+ g = _norm_glob(glob)
189
+ out: list[str] = []
190
+ i, n = 0, len(g)
191
+ while i < n:
192
+ ch = g[i]
193
+ if ch == "*":
194
+ if i + 1 < n and g[i + 1] == "*":
195
+ if i + 2 < n and g[i + 2] == "/":
196
+ out.append("(?:.*/)?")
197
+ i += 3
198
+ elif out and out[-1] == "/":
199
+ out.pop()
200
+ out.append("(?:/.*)?")
201
+ i += 2
202
+ else:
203
+ out.append(".*")
204
+ i += 2
205
+ else:
206
+ out.append("[^/]*")
207
+ i += 1
208
+ elif ch == "?":
209
+ out.append("[^/]")
210
+ i += 1
211
+ elif ch == "[":
212
+ j = i + 1
213
+ if j < n and g[j] in ("!", "^"):
214
+ j += 1
215
+ if j < n and g[j] == "]":
216
+ j += 1
217
+ while j < n and g[j] != "]":
218
+ j += 1
219
+ if j >= n:
220
+ out.append(r"\[")
221
+ i += 1
222
+ else:
223
+ content = g[i + 1:j]
224
+ if content.startswith("!"):
225
+ content = "^" + content[1:]
226
+ out.append("[" + content.replace("\\", r"\\") + "]")
227
+ i = j + 1
228
+ else:
229
+ out.append(re.escape(ch))
230
+ i += 1
231
+ return re.compile("".join(out))
232
+
233
+
234
+ def _scope_path(root: Path, raw: str) -> str:
235
+ """改动路径归一:相对项目根;绝对路径尝试相对化;逃出根 ⇒ 空(不可命中)。"""
236
+ s = str(raw).strip().replace("\\", "/")
237
+ while s.startswith("./"):
238
+ s = s[2:]
239
+ if not s:
240
+ return ""
241
+ if re.match(r"^[A-Za-z]:/", s) or s.startswith("/"):
242
+ try:
243
+ return Path(s).resolve().relative_to(root.resolve()).as_posix()
244
+ except (ValueError, OSError):
245
+ return ""
246
+ s = posixpath.normpath(s)
247
+ if s in (".", "..") or s.startswith("../"):
248
+ return ""
249
+ return s
250
+
251
+
252
+ def _hit(path: str, glob: str) -> bool:
253
+ if not path:
254
+ return False
255
+ if _is_wildcard(glob):
256
+ return True
257
+ if _glob_regex(glob).fullmatch(path):
258
+ return True
259
+ # 目录型 scope(无通配符)按前缀命中;目录型 glob 同理由 `a/**` 覆盖
260
+ g = _norm_glob(glob)
261
+ if not any(ch in g for ch in "*?["):
262
+ return path == g.rstrip("/") or path.startswith(g.rstrip("/") + "/")
263
+ return False
264
+
265
+
266
+ def _specificity(spec: dict, scopes: list[str] | None = None) -> int:
267
+ """命中的最长非兜底 glob 越具体,越优先。
268
+
269
+ 限定只计**实际命中**的 glob:一份通用指南列了很多目录时,不得凭一条更长的
270
+ 无关 glob 挤掉真正对口的领域约定。
271
+ """
272
+ concrete = [len(_norm_glob(g)) for g in spec["paths"]
273
+ if not _is_wildcard(g)
274
+ and (scopes is None or any(_hit(p, g) for p in scopes))]
275
+ return max(concrete, default=0)
276
+
277
+
278
+ def _is_wildcard_only(spec: dict) -> bool:
279
+ return all(_is_wildcard(g) for g in spec["paths"])
280
+
281
+
282
+ def _is_conventions(spec: dict) -> bool:
283
+ return spec["rel"].split("/")[2:3] == ["conventions"]
284
+
285
+
286
+ def _domain_hit(spec: dict, domains: list[str]) -> bool:
287
+ if not domains:
288
+ return False
289
+ stem = spec["name"].lower()
290
+ for raw in domains:
291
+ d = str(raw).strip().lower()
292
+ if not d:
293
+ continue
294
+ if stem == d or stem.startswith(d + "-") or stem.startswith(d + "_"):
295
+ return True
296
+ return False
297
+
298
+
299
+ def select_specs(root: Path, paths: list[str] | None = None,
300
+ domains: list[str] | None = None) -> list[dict]:
301
+ """按改动路径 / 受影响域选取最小规范集。
302
+
303
+ 规则(顺序即优先级):
304
+ 1. 显式改动路径命中 → 只取命中项,**不**混入 `**` 兜底;
305
+ 结构规范优先,约定规范至多补 1 份;
306
+ 2. 无改动路径但给了域 → 取 `domains/<domain>.md`;
307
+ 3. 两者都无 → 只取 `**` 兜底(如 `tour.md`),最多 1 份。
308
+ """
309
+ specs = load_specs(root)
310
+ doms = [d for d in (domains or []) if str(d).strip()]
311
+
312
+ if paths is not None:
313
+ scopes = [s for s in (_scope_path(root, p) for p in paths if str(p).strip()) if s]
314
+ if not scopes:
315
+ return [] # 显式范围为空 ⇒ 不回落兜底
316
+ hits = [s for s in specs
317
+ if not _is_wildcard_only(s)
318
+ and any(_hit(p, g) for p in scopes for g in s["paths"])]
319
+ hits.sort(key=lambda s: (-_specificity(s, scopes), s["rel"]))
320
+ structure = [s for s in hits if not _is_conventions(s)]
321
+ conventions = [s for s in hits if _is_conventions(s)]
322
+ if structure:
323
+ picked = structure[:MAX_SPECS]
324
+ if conventions and len(picked) < MAX_SPECS:
325
+ picked.append(conventions[0])
326
+ return picked
327
+ return conventions[:MAX_SPECS]
328
+
329
+ if doms:
330
+ picked = [s for s in specs
331
+ if not _is_wildcard_only(s) and _domain_hit(s, doms)]
332
+ picked.sort(key=lambda s: (-_specificity(s), s["rel"]))
333
+ if picked:
334
+ return picked[:MAX_SPECS]
335
+
336
+ wild = [s for s in specs if _is_wildcard_only(s)]
337
+ wild.sort(key=lambda s: s["rel"])
338
+ return wild[:1]
339
+
340
+
341
+ # ---------------------------------------------------------------- rendering
342
+
343
+ def _excerpt(body: str) -> str:
344
+ lines = body.splitlines()
345
+ out = lines[:MAX_LINES_PER_SPEC]
346
+ text = "\n".join(out).strip()
347
+ if len(text) > MAX_CHARS_PER_SPEC:
348
+ text = text[:MAX_CHARS_PER_SPEC].rstrip() + "\n…(已截断,全文请按需 Read)"
349
+ elif len(lines) > MAX_LINES_PER_SPEC:
350
+ text += "\n…(已截断,全文请按需 Read)"
351
+ return text
352
+
353
+
354
+ def _fence(body: str) -> str:
355
+ longest = max((len(run) for run in re.findall(r"`+", body)), default=0)
356
+ return "`" * max(3, longest + 1)
357
+
358
+
359
+ def render_specs(specs: list[dict], scope_paths: list[str] | None = None,
360
+ domains: list[str] | None = None) -> str:
361
+ """渲染派工单的「最小结构上下文」段。"""
362
+ scope = ", ".join(f"`{p}`" for p in (scope_paths or []))
363
+ dom = ", ".join(f"`{d}`" for d in (domains or []))
364
+
365
+ lines = ["## 4. 最小结构上下文(按改动路径自动注入)"]
366
+ if scope or dom:
367
+ lines.append(f"> 本次范围:{scope or ''}{(' · 域 ' + dom) if dom else ''};"
368
+ "只注入命中规范,未命中的请按需 Read。")
369
+ else:
370
+ lines.append("> 未提供改动路径;仅注入导航兜底规范。要更精准请用 "
371
+ "`atlas workflow dispatch --paths <file...>`。")
372
+ lines.append("")
373
+
374
+ if not specs:
375
+ lines.append("(未匹配到带 `paths:` 的规范;请确认 `.atlas/spec/structure/` 已开户)")
376
+ lines.append("")
377
+ return "\n".join(lines)
378
+
379
+ emitted = 0
380
+ for s in specs:
381
+ body = _excerpt(s["body"])
382
+ if not body:
383
+ continue
384
+ fence = _fence(body)
385
+ globs = ", ".join(f"`{g}`" for g in s["paths"])
386
+ lines.append(f"### 命中 {globs} → `{s['rel']}`")
387
+ lines.append("")
388
+ lines.append(f"{fence}md")
389
+ lines.append(body)
390
+ lines.append(fence)
391
+ lines.append("")
392
+ emitted += 1
393
+
394
+ if not emitted:
395
+ lines.append("(命中的规范暂无正文)")
396
+ lines.append("")
397
+ return "\n".join(lines)
@@ -15,7 +15,8 @@ from __future__ import annotations
15
15
  import json
16
16
  from pathlib import Path
17
17
 
18
- from _support.workflow_plan import load_tasks, PlanError
18
+ from _support.workflow_plan import load_tasks, PlanError, atomic_write_json
19
+ from _support.workflow_context import render_specs, select_specs
19
20
 
20
21
 
21
22
  class DispatchError(ValueError):
@@ -41,11 +42,31 @@ def get_next_runnable_task(tasks_root: Path) -> dict | None:
41
42
  return None
42
43
 
43
44
 
44
- def assemble_curated_context(root: Path, task: dict) -> str:
45
- """组装当前任务的最小上下文注入包。"""
45
+ def _as_list(value) -> list[str]:
46
+ """路径 / 域字段既可能是 list 也可能是单个字符串;空值归一为空列表。"""
47
+ if value is None:
48
+ return []
49
+ if isinstance(value, str):
50
+ return [value] if value.strip() else []
51
+ return [str(v) for v in value if str(v).strip()]
52
+
53
+
54
+ def assemble_curated_context(root: Path, task: dict,
55
+ scope_paths: list[str] | None = None) -> str:
56
+ """组装当前任务的最小上下文注入包。
57
+
58
+ `scope_paths` = 本次改动文件/目录;缺省回落到任务卡的 `paths` 字段。
59
+ 只注入命中 `paths:` 的规范(最多 3 份),不注入全仓无关 spec。
60
+ """
46
61
  root = root.resolve()
47
62
  t_id = task["id"]
48
63
  t_dir = Path(task.get("_dir") or (root / ".atlas" / "tasks" / t_id))
64
+ # 显式 `--paths`(含空串)与「任务卡没有路径」要区分:前者不回落兜底,
65
+ # 后者才允许走 `**` 导航兜底。
66
+ if scope_paths is not None:
67
+ scopes: list[str] | None = _as_list(scope_paths)
68
+ else:
69
+ scopes = _as_list(task.get("paths")) or None
49
70
 
50
71
  lines = [
51
72
  f"# 任务派发执行单 (Task Dispatch) — {task.get('title')}",
@@ -74,7 +95,7 @@ def assemble_curated_context(root: Path, task: dict) -> str:
74
95
  lines.append("- (无直接关联的业务 AC,遵循常规代码规范及单元测试)")
75
96
 
76
97
  # 关联受影响域 PRD 指针
77
- domains = task.get("affected_domains") or []
98
+ domains = _as_list(task.get("affected_domains"))
78
99
  lines.extend([
79
100
  "",
80
101
  "## 3. 受影响域架构透镜 (Domain Focus)",
@@ -89,9 +110,16 @@ def assemble_curated_context(root: Path, task: dict) -> str:
89
110
  else:
90
111
  lines.append("- 通用基础设施 / 跨域")
91
112
 
113
+ # 最小结构上下文:按改动路径 / 受影响域自动注入
114
+ spec_set = select_specs(root, paths=scopes, domains=domains)
115
+ lines.extend([
116
+ "",
117
+ render_specs(spec_set, scope_paths=scopes, domains=domains),
118
+ ])
119
+
92
120
  lines.extend([
93
121
  "",
94
- "## 4. 执行规范与完成定义 (Instructions for Agent)",
122
+ "## 5. 执行规范与完成定义 (Instructions for Agent)",
95
123
  "1. 请依据上述需求卡与 AC 断言完成代码修改;",
96
124
  "2. 修改完成后,请执行 `git add <改动文件>` 暂存修改;",
97
125
  "3. 运行暂存区独立审查与测试:",
@@ -105,7 +133,7 @@ def assemble_curated_context(root: Path, task: dict) -> str:
105
133
  return "\n".join(lines)
106
134
 
107
135
 
108
- def dispatch_task(root: Path, task: dict) -> Path:
136
+ def dispatch_task(root: Path, task: dict, scope_paths: list[str] | None = None) -> Path:
109
137
  """执行派单流转:写入 dispatch.md 并将状态置为 in_progress。"""
110
138
  root = root.resolve()
111
139
  t_id = task["id"]
@@ -113,7 +141,7 @@ def dispatch_task(root: Path, task: dict) -> Path:
113
141
  t_dir.mkdir(parents=True, exist_ok=True)
114
142
 
115
143
  # 写入上下文派单包
116
- ctx_text = assemble_curated_context(root, task)
144
+ ctx_text = assemble_curated_context(root, task, scope_paths=scope_paths)
117
145
  dispatch_file = t_dir / "dispatch.md"
118
146
  dispatch_file.write_text(ctx_text, encoding="utf-8")
119
147
 
@@ -128,6 +156,9 @@ def dispatch_task(root: Path, task: dict) -> Path:
128
156
  meta = task
129
157
 
130
158
  meta["status"] = "in_progress"
131
- task_json_file.write_text(json.dumps(meta, ensure_ascii=False, indent=2), encoding="utf-8")
159
+ paths = [str(p) for p in (scope_paths or []) if str(p).strip()]
160
+ if paths:
161
+ meta["paths"] = paths
162
+ atomic_write_json(task_json_file, meta)
132
163
 
133
164
  return dispatch_file
@@ -12,15 +12,51 @@
12
12
  from __future__ import annotations
13
13
 
14
14
  import json
15
+ import re
16
+ import subprocess
15
17
  from pathlib import Path
16
18
 
17
- from _support.workflow_plan import load_tasks
19
+ from _support import review_scope_core as scope_core
20
+ from _support.workflow_plan import load_tasks, atomic_write_json, UNIT_RE
18
21
 
19
22
 
20
23
  class FinishError(ValueError):
21
24
  """收口校验异常。"""
22
25
 
23
26
 
27
+ REVIEW_DIR_PREFIX_RE = r"^\d{4}-\d{2}-\d{2}-impl-review-"
28
+
29
+
30
+ def _staged_files(root: Path) -> list[str] | None:
31
+ try:
32
+ pr = subprocess.run(
33
+ ["git", "diff", "--cached", "--name-only", "--diff-filter=ACMR"],
34
+ cwd=str(root), capture_output=True, text=True, timeout=15,
35
+ )
36
+ except (OSError, subprocess.SubprocessError):
37
+ return None
38
+ if pr.returncode != 0:
39
+ return None
40
+ return [line.strip() for line in pr.stdout.splitlines() if line.strip()]
41
+
42
+
43
+ def _scope_matches(root: Path, data: dict) -> tuple[bool, str]:
44
+ """检查报告落盘后暂存区内容未被替换(v4 内容封口)。"""
45
+ scope = data.get("review_scope")
46
+ if not isinstance(scope, dict) or not scope.get("sha256"):
47
+ return True, "" # 旧报告兼容:无内容锚,无法比对
48
+ staged = _staged_files(root)
49
+ if staged is None:
50
+ return False, "无法读取暂存区,不能确认审查内容未被替换(请在 git 仓库内重跑 verify)"
51
+ try:
52
+ manifest = scope_core.build_manifest(root, staged)
53
+ except Exception as exc: # noqa: BLE001 —— 路径/状态异常一律视为不可封口
54
+ return False, f"暂存区内容无法重算摘要:{exc}"
55
+ if manifest.get("scope_sha256") != scope.get("sha256"):
56
+ return False, "审查后暂存区内容已变化(review_scope 摘要不一致);请重新运行 verify"
57
+ return True, ""
58
+
59
+
24
60
  def check_task_review_passed(root: Path, unit: str) -> tuple[bool, str]:
25
61
  """检查指定任务是否已产出合规的 review.json 且未被拦截。"""
26
62
  root = root.resolve()
@@ -29,7 +65,11 @@ def check_task_review_passed(root: Path, unit: str) -> tuple[bool, str]:
29
65
  if not reviews_dir.is_dir():
30
66
  return False, "未找到 product/reviews 目录(尚未执行独立审查)"
31
67
 
32
- candidates = sorted(reviews_dir.glob(f"*-impl-review-{unit}"))
68
+ candidates = sorted(
69
+ p for p in reviews_dir.iterdir()
70
+ if p.is_dir() and re.fullmatch(
71
+ REVIEW_DIR_PREFIX_RE + re.escape(unit) + "$", p.name)
72
+ )
33
73
  if not candidates:
34
74
  return False, f"未找到任务 {unit} 的审查报告(须先执行 atlas review --unit {unit} --staged)"
35
75
 
@@ -52,6 +92,10 @@ def check_task_review_passed(root: Path, unit: str) -> tuple[bool, str]:
52
92
  if data.get("ok") is False:
53
93
  return False, "审查报告 ok=false(存在未解决的阻断问题)"
54
94
 
95
+ matched, why = _scope_matches(root, data)
96
+ if not matched:
97
+ return False, why
98
+
55
99
  return True, str(latest_dir)
56
100
 
57
101
 
@@ -59,8 +103,15 @@ def finish_task(root: Path, task: dict, *, force: bool = False) -> dict:
59
103
  """完成单个任务的收口流转。"""
60
104
  root = root.resolve()
61
105
  t_id = task["id"]
62
- t_dir = Path(task.get("_dir") or (root / ".atlas" / "tasks" / t_id))
63
-
106
+ if not UNIT_RE.match(t_id):
107
+ raise FinishError(f"非法任务标识:{t_id!r}")
108
+ tasks_root = (root / ".atlas" / "tasks").resolve()
109
+ t_dir = Path(task.get("_dir") or (tasks_root / t_id)).resolve()
110
+ if t_dir != tasks_root and tasks_root not in t_dir.parents:
111
+ raise FinishError(f"任务目录越界:{t_dir}(必须在 {tasks_root} 之内)")
112
+
113
+ if not t_dir.is_dir():
114
+ raise FinishError(f"任务目录不存在:{t_dir}")
64
115
  if not force:
65
116
  passed, reason = check_task_review_passed(root, t_id)
66
117
  if not passed:
@@ -77,7 +128,7 @@ def finish_task(root: Path, task: dict, *, force: bool = False) -> dict:
77
128
  meta = task
78
129
 
79
130
  meta["status"] = "completed"
80
- task_json_file.write_text(json.dumps(meta, ensure_ascii=False, indent=2), encoding="utf-8")
131
+ atomic_write_json(task_json_file, meta)
81
132
 
82
133
  # 检查整体工作流是否全部收工
83
134
  all_tasks = load_tasks(t_dir.parent)