@thincoder/core 0.11.5 → 0.12.1

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 (199) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/abort-provenance.mjs +23 -0
  3. package/advisor/citations.mjs +5 -1
  4. package/advisor/compaction.mjs +13 -10
  5. package/advisor/history.mjs +6 -1
  6. package/advisor/loop.mjs +35 -10
  7. package/advisor/messages.mjs +31 -43
  8. package/advisor/project-context.mjs +49 -45
  9. package/advisor/run.mjs +82 -26
  10. package/advisor.mjs +40 -11
  11. package/agent/assemble.mjs +5 -5
  12. package/agent/chat-call.mjs +21 -1
  13. package/agent/completion.mjs +1 -20
  14. package/agent/dispatch-gates.mjs +8 -3
  15. package/agent/dispatch-run.mjs +131 -20
  16. package/agent/dispatch.mjs +23 -22
  17. package/agent/family-tools.mjs +4 -7
  18. package/agent/goal-judge.mjs +99 -0
  19. package/agent/goal-state.mjs +96 -0
  20. package/agent/helpers.mjs +13 -4
  21. package/agent/offload.mjs +1 -1
  22. package/agent/planning-graph-guardrail.mjs +224 -0
  23. package/agent/planning-prompt.mjs +179 -0
  24. package/agent/planning-step.mjs +460 -173
  25. package/agent/post-turn.mjs +23 -33
  26. package/agent/record-results.mjs +8 -5
  27. package/agent/run-stages.mjs +18 -38
  28. package/agent/run-start.mjs +26 -19
  29. package/agent/setup-reminders.mjs +16 -14
  30. package/agent/setup.mjs +3 -2
  31. package/agent/spawn-child.mjs +17 -4
  32. package/agent/suspension.mjs +42 -21
  33. package/agent/task-lifecycle.mjs +165 -52
  34. package/agent/timers.mjs +9 -1
  35. package/agent/turn-loop.mjs +160 -69
  36. package/agent/turn-projection.mjs +26 -15
  37. package/agent/turn-task-state.mjs +4 -4
  38. package/agent/write-gate-ledger.mjs +1 -1
  39. package/agent/write-gate.mjs +14 -11
  40. package/agent-tools/advisor-async.mjs +2 -0
  41. package/agent-tools/advisor-launch.mjs +27 -13
  42. package/agent-tools/advisor-settle.mjs +19 -18
  43. package/agent-tools/advisor.mjs +90 -13
  44. package/agent-tools/bash-async.mjs +3 -3
  45. package/agent-tools/batch-ledger-bind.mjs +8 -5
  46. package/agent-tools/batch-read.mjs +42 -0
  47. package/agent-tools/batch-record-write.mjs +20 -12
  48. package/agent-tools/batch-segment-vocab.mjs +6 -4
  49. package/agent-tools/batch-skeleton.mjs +43 -12
  50. package/agent-tools/consult.mjs +5 -1
  51. package/agent-tools/context.mjs +5 -4
  52. package/agent-tools/design-slots.mjs +7 -4
  53. package/agent-tools/design-token.mjs +3 -2
  54. package/agent-tools/doc-graph.mjs +257 -95
  55. package/agent-tools/escalate-async.mjs +4 -1
  56. package/agent-tools/goal.mjs +28 -95
  57. package/agent-tools/plan.mjs +1 -1
  58. package/agent-tools/review-facts.mjs +56 -7
  59. package/agent-tools/settings.mjs +35 -1
  60. package/agent-tools/ssh-transport.mjs +23 -22
  61. package/agent-tools/step.mjs +24 -4
  62. package/agent-tools/subagent-actions.mjs +6 -2
  63. package/agent-tools/subagent-async.mjs +4 -2
  64. package/agent-tools/subagent.mjs +1 -1
  65. package/agent-tools/task.mjs +73 -65
  66. package/agent-tools.mjs +3 -3
  67. package/agent.mjs +12 -3
  68. package/auto-think.mjs +16 -3
  69. package/browser/actions.mjs +5 -1
  70. package/browser/cdp.mjs +1 -1
  71. package/browser/pool.mjs +110 -17
  72. package/compaction-work-state.mjs +103 -13
  73. package/compress-form.mjs +29 -3
  74. package/config-defaults.mjs +27 -3
  75. package/config-io.mjs +3 -14
  76. package/config-normalize.mjs +24 -4
  77. package/config-presets.mjs +40 -26
  78. package/config-warn.mjs +30 -0
  79. package/config.mjs +139 -63
  80. package/context-degrade.mjs +4 -4
  81. package/context-push.mjs +20 -9
  82. package/context.mjs +65 -20
  83. package/doc-graph/anchors.mjs +39 -40
  84. package/doc-graph/clusters.mjs +49 -0
  85. package/doc-graph/code-parsers.mjs +494 -0
  86. package/doc-graph/context-pack.mjs +392 -0
  87. package/doc-graph/dir-signals.mjs +228 -0
  88. package/doc-graph/edges.mjs +231 -0
  89. package/doc-graph/format.mjs +70 -0
  90. package/doc-graph/gc-cmd.mjs +104 -0
  91. package/doc-graph/gc.mjs +112 -0
  92. package/doc-graph/glob-work-graph.mjs +307 -0
  93. package/doc-graph/golden-set.mjs +131 -0
  94. package/doc-graph/ls-work-graph.mjs +534 -0
  95. package/doc-graph/outline.mjs +377 -0
  96. package/doc-graph/output-annotations.mjs +85 -0
  97. package/doc-graph/process-docs.mjs +68 -0
  98. package/doc-graph/read-work-graph.mjs +91 -0
  99. package/doc-graph/rebuild-cmd.mjs +75 -0
  100. package/doc-graph/resolvers.mjs +322 -0
  101. package/doc-graph/roots.mjs +86 -0
  102. package/doc-graph/schema.mjs +110 -0
  103. package/doc-graph/search-augment.mjs +418 -0
  104. package/doc-graph/store.mjs +231 -0
  105. package/doc-graph/target-resolve.mjs +352 -0
  106. package/doc-graph/walk.mjs +87 -0
  107. package/doc-graph.mjs +583 -707
  108. package/explore-distill.mjs +52 -17
  109. package/generate-title.mjs +7 -4
  110. package/ledger-close.mjs +6 -6
  111. package/ledger-cmd.mjs +3 -3
  112. package/ledger-consistency.mjs +8 -6
  113. package/ledger-db.mjs +45 -10
  114. package/ledger-migrate.mjs +25 -10
  115. package/ledger-read.mjs +1 -1
  116. package/ledger-write-ops.mjs +6 -6
  117. package/ledger.mjs +2 -2
  118. package/model-context.mjs +54 -18
  119. package/model-specs.mjs +86 -67
  120. package/package.json +1 -1
  121. package/prompt-overlays.mjs +3 -3
  122. package/prompts/advisor-round1.md +6 -5
  123. package/prompts/common.md +16 -6
  124. package/prompts/consult-base.md +2 -1
  125. package/prompts/discipline-engineering.md +1 -1
  126. package/prompts/discipline-normal.md +12 -8
  127. package/prompts/knowledge/doc-lookup.md +2 -2
  128. package/prompts/knowledge/normal-batch-discipline.md +2 -2
  129. package/prompts/knowledge/normal-delivery-collaboration.md +3 -3
  130. package/prompts/knowledge/tool-advisor.md +2 -2
  131. package/prompts/knowledge/tool-apply-patch.md +1 -1
  132. package/prompts/knowledge/tool-bash.md +2 -2
  133. package/prompts/knowledge/tool-batch.md +4 -4
  134. package/prompts/knowledge/tool-glob.md +9 -2
  135. package/prompts/knowledge/tool-goal.md +9 -6
  136. package/prompts/knowledge/tool-grep.md +7 -2
  137. package/prompts/knowledge/tool-ls.md +11 -5
  138. package/prompts/knowledge/tool-lsp.md +1 -1
  139. package/prompts/knowledge/tool-operations.md +3 -2
  140. package/prompts/knowledge/tool-plan.md +1 -1
  141. package/prompts/knowledge/tool-read.md +7 -6
  142. package/prompts/knowledge/tool-repo-graph-read.md +12 -0
  143. package/prompts/knowledge/tool-repo-graph.md +12 -0
  144. package/prompts/knowledge/tool-step.md +1 -1
  145. package/prompts/knowledge/tool-subagent.md +2 -2
  146. package/prompts/knowledge/tool-task.md +10 -9
  147. package/prompts/knowledge/tool-tree.md +7 -1
  148. package/prompts/persona-eng-coder.md +1 -1
  149. package/prompts/persona-eng-designer.md +1 -1
  150. package/prompts/persona-engineering.md +2 -1
  151. package/prompts/persona-explore.md +1 -1
  152. package/prompts/persona-normal.md +7 -6
  153. package/prompts/persona-plan.md +2 -2
  154. package/prompts/planning-next-moves.md +7 -8
  155. package/provider/anthropic.mjs +53 -51
  156. package/provider/core.mjs +85 -34
  157. package/provider/errors.mjs +33 -10
  158. package/provider/google.mjs +244 -37
  159. package/provider/list-models.mjs +28 -14
  160. package/provider/responses-request.mjs +15 -9
  161. package/provider/responses.mjs +10 -8
  162. package/provider/sse.mjs +3 -6
  163. package/proxy-transport.mjs +228 -119
  164. package/rules-file.mjs +79 -0
  165. package/rules.mjs +13 -51
  166. package/session-lifecycle.mjs +32 -20
  167. package/team-ledger.mjs +7 -7
  168. package/think-off.mjs +37 -18
  169. package/token-window.mjs +48 -31
  170. package/tool-args.mjs +8 -8
  171. package/tool-docs/bash.md +1 -1
  172. package/tool-docs/glob.md +3 -1
  173. package/tool-docs/goal.md +2 -2
  174. package/tool-docs/grep.md +3 -1
  175. package/tool-docs/ls.md +7 -1
  176. package/tool-docs/read.md +1 -1
  177. package/tool-docs/repo_graph-read.md +3 -0
  178. package/tool-docs/repo_graph.md +3 -0
  179. package/tool-docs/tree.md +1 -1
  180. package/tools/bash.mjs +53 -8
  181. package/tools/browser.mjs +4 -4
  182. package/tools/file.mjs +34 -7
  183. package/tools/glob-dialect.mjs +57 -7
  184. package/tools/index.mjs +3 -7
  185. package/tools/patch.mjs +8 -7
  186. package/tools/process-doc-mark.mjs +13 -0
  187. package/tools/search.mjs +152 -37
  188. package/tools/shared.mjs +6 -0
  189. package/tools/tree.mjs +211 -8
  190. package/window-policy.mjs +205 -126
  191. package/prompts/knowledge/tool-doc-graph-read.md +0 -20
  192. package/prompts/knowledge/tool-doc-graph.md +0 -49
  193. package/prompts/knowledge/tool-peek.md +0 -10
  194. package/prompts/knowledge/tool-repo-outline.md +0 -4
  195. package/tool-docs/doc_graph-read.md +0 -3
  196. package/tool-docs/doc_graph.md +0 -3
  197. package/tool-docs/peek.md +0 -3
  198. package/tool-docs/repo_outline.md +0 -3
  199. package/tools/peek.mjs +0 -447
@@ -1,140 +1,302 @@
1
1
  /**
2
- * agent-tools/doc-graph.mjs — `doc_graph` 工具面:入参校验 ∥ 动作分派 ∥ 文本回执。
2
+ * agent-tools/doc-graph.mjs — `repo_graph` 工具面(Context Graph v2,统一项目知识与架构图谱)。
3
3
  *
4
- * 设计单源 = `docs/core/design/DOC-GRAPH.md` §2.5(工具面)∥ §2.5.5(两变体契约)∥ §3(登记面);机制单源 =
5
- * `../doc-graph.mjs`。工具形与同族(`ledger` ∥ `team_ledger` ∥ `doc_check`)同构:**一个工具 + `action` 枚举**
6
- * 四种问法(`scan` 扫 ∥ `forward` 正向 ∥ `reverse` 反向 ∥ `chain` 链路)——`doc_check` 那边是「判决」的两种问法,
7
- * 两者判的东西不同,故不并成一个工具(KD-2)。
4
+ * 六动作全只读、按 mtime 自动懒增量同步,无需手工 `scan`、不强绑 `PROJECT-MANIFEST.json`:
5
+ * - `context`:按文件路径/符号名/文档/关键词一键生成「动笔前必读上下文包」(需求/设计档 + 上游调用方 + 同级兄弟 + 下游依赖 + 关联测试 + 每档行数),并将核心必读清单记入 `agent._graphReadingPack` 供 Planning next moves 对账;
6
+ * - `impact`:改签名/删文件/重构前的 1–4 跳全仓反向影响面(源码 + 文档 + 测试);
7
+ * - `overview`:全仓架构骨架(语言统计 + Top Hub + 目录依赖 + 入口文件);
8
+ * - `outline`:批量文档 H1–H4 章节树 / 按标题抽节 / 源码顶层签名大纲(收编原 `peek` 精华);
9
+ * - `refs`:单档出入引用与断链反查(`edgeType` 按 kind 过滤、`offset` 翻页);
10
+ * - `symbol`:单个导出符号的定义档与全部引用方(按边 kind 分组),便于查「这个符号还有谁在用」。
8
11
  *
9
- * **两变体同体、动作集一处字面**(构造单源 = `docs/core/design/AGENT-LOOP-SUBAGENT.md` §6.60.2 ②):参数化工厂
10
- * `makeDocGraphTool(actions, { readonly, docName, unscanned })` 产出两形——全量 `docGraphTool`(四动作,depth-0 主 agent 段)
11
- * ∥ 只读 `docGraphReadTool`(三动作、无 `scan`,全部 depth>0 角色段与 advisor 面)。动作集一处字面 `ALL_ACTIONS`、
12
- * 只读集由它派生 ⇒ schema 的 `enum` ∥ execute 的护栏 ∥ 拒文里的取值集三处取同一个 `actions` 参数,变体不写第二份
13
- * 字面对象(先例 = `../ledger-tools.mjs` 的 `makeLedgerTool`)。描述从同一 `actions` 生成(`ACTION_CLAUSES`)、
14
- * 各自一份描述档;未建图策略(`unscanned`)由只读变体传 `readonly-empty`(TOOLS.md §6.29 ③)。
15
- *
16
- * **子代理段为什么不给 `scan`**:`scan` 把边落进台账库(`doc_edges` 表)——一次显式动作,没有常驻进程、没有 watch
17
- * (需求 §3);而 depth>0 段拿到的台账是**只读**变体 ⇒ 同一段里没有可依的写面,多个子代理并发扫还会重写同一张共享
18
- * 边表(D-DT1)。父侧扫一次、子代理查同一份库。只读性按 action 判(`isReadonlyAction`,与 `ledger` 同形):三个
19
- * 查询走只读句柄、免审批;`scan` 走写面。
20
- *
21
- * **参数零默认**(设计 §2.5):`target` 恒必填;`forward` ∥ `reverse` ∥ `chain` 的 `node`、`chain` 的 `depth` 缺一即拒
22
- * 并**点名**那一个——给默认值就是替调用方做决定。两个可选参数(`scan` 的 `scope` ∥ 三个读动作的 `kind`)缺席的含义
23
- * 都由回执首行印出来(`全仓` / `范围 K 档` ∥ 本次生效的 kind 集合),不靠调用方记。
24
- * `kind` 的**闭集校验住在核里**(`doc-graph.mjs` 的 `kindFilterOf`,闭集单源 = `ledger-db.mjs` 的 `DOC_EDGE_KINDS`):
25
- * 本档只判形(必为字符串),闭集外拒并点名那个值由核做——一处校验,两个入口(工具 ∥ 直调核)。
26
- *
27
- * W8 契约②:本档只**动态** import `../doc-graph.mjs`(它自己再动态 import 台账库)——端壳静态闭包零 `node:sqlite`。
28
- * 描述外置:模型可见文本单点 = `tool-docs/{doc_graph,doc_graph-read}.md`(`DESC` 单一解析面)——
29
- * 两变体各一份描述档(TOOLS.md §6.29「描述面也分两份」:只读变体的字面里没有它执行不到的 `scan` 段)。
12
+ * 导出 `repoGraphTool` / `repoGraphReadTool` 及向后兼容别名 `docGraphTool` / `docGraphReadTool`(同体全只读)。
13
+ * W8 契约②:本档仅动态 import `../doc-graph.mjs` 与 `../doc-graph/outline.mjs`,端壳静态闭包零命中 `node:sqlite`。
30
14
  */
31
- import { isAbsolute, resolve } from "node:path"
32
- import { DESC } from "../tools/shared.mjs"
15
+ import { existsSync } from "node:fs"
16
+ import { isAbsolute, relative, resolve } from "node:path"
17
+ import { DESC, firstAbsoluteGlobPattern, absoluteGlobRejection, looksLikeGlob } from "../tools/shared.mjs"
33
18
 
34
- /** `target` 归一:相对路径按会话锚解析(锚缺位 + 相对形 ⇒ 拒、点名锚——不落 `process.cwd()`)。 */
35
- function targetOf(args, ctx) {
19
+ const ACTIONS = ["context", "impact", "overview", "outline", "refs", "symbol"]
20
+
21
+ function resolveTargetInput(args, ctx) {
36
22
  const anchor = ctx?.agent?.cwd ?? ctx?.cwd
37
- const given = args?.target
38
- if (typeof given !== "string" || given.trim() === "") {
39
- throw new Error("doc_graph:target 缺失(必填)——请给项目根(带 PROJECT-MANIFEST.json 的那个目录)")
23
+ const given = typeof args?.target === "string" ? args.target.trim() : ""
24
+ if (!given) {
25
+ if (!anchor) throw new Error("repo_graph:target 缺失且会话锚不可用,请传入绝对项目根路径")
26
+ return resolve(anchor)
40
27
  }
41
28
  if (!isAbsolute(given) && !anchor) {
42
- throw new Error("doc_graph:会话锚不可用(`ctx.agent.cwd` / `ctx.cwd` 都空)——请把 target 写成绝对路径;相对 target 没有基根,本工具不落 `process.cwd()`")
29
+ throw new Error("repo_graph:会话锚不可用,相对 target 无法解析,请传入绝对路径")
43
30
  }
44
31
  return resolve(anchor ?? ".", given)
45
32
  }
46
33
 
47
- /** 全量动作集——本档唯一字面。 */
48
- const ALL_ACTIONS = ["scan", "forward", "reverse", "chain"]
49
- /** 只读动作集——由上一行派生,不写第二份字面(`scan` 归主 agent,见文件头)。 */
50
- const READ_ACTIONS = ALL_ACTIONS.filter((a) => a !== "scan")
34
+ /**
35
+ * P0-3 `target` 上溯 + 父工作区分流:`targetAbs` 经 `resolveQueryRoot` 判根 ——
36
+ * 子目录入参上溯到最近的项目根(不按子目录建图);不存在的目标直接报错;
37
+ * 多项目父工作区:`overview` 放行(列子仓清单,需求 F4「多项目父工作区自动列子仓清单」),
38
+ * 其余五动作扇出(逐子仓各查各的、按仓分组),绝不当一棵树建图。显式与不显式 `target` 同此分流。
39
+ * 扇出不设子仓数上限;逐仓 `syncGraph` 懒增量,未缓存超大仓照常全量冷建图(用户拍板接受首次建图成本,不跳 `skippedCold`)。
40
+ * 三态返回:单仓 `{root}` / `overview` 父工作区 `{root}` / 五动作父工作区 `{fanout, candidates}`。
41
+ */
42
+ function resolveQueryRootFanout(targetAbs, action, mod) {
43
+ const r = mod.resolveQueryRoot(targetAbs)
44
+ if (r.ok) return { root: r.root }
45
+ if (r.reason === "missing") throw new Error(`repo_graph:target 不存在:${r.abs}`)
46
+ if (action === "overview") return { root: r.abs }
47
+ return { fanout: true, candidates: r.candidates }
48
+ }
49
+
50
+ /** 候选子仓名单的展示串:仓名并列,>10 截断为「前 10 名 …(共 N 仓)」(防超大父工作区刷屏;仓名相对父工作区已够定位,`target` 点名可用)。 */
51
+ function formatCandidateNames(candidates) {
52
+ const names = candidates.map((c) => c.name)
53
+ return names.length <= 10 ? names.join(" · ") : `${names.slice(0, 10).join(" · ")} …(共 ${names.length} 仓)`
54
+ }
51
55
 
52
- /** 逐动作的一句话(`action` 参数描述的唯一措辞来源:描述从**本变体的动作集**生成——只读变体的字面
53
- * 因此不含 `scan`,而两变体的措辞只有这一份,漂移由「同一张表同时派生动作与描述」挡住)。 */
54
- const ACTION_CLAUSES = {
55
- scan: "collects the edges into the ledger database (one explicit pass, no background index)",
56
- forward: "lists the edges leaving a node",
57
- reverse: "lists the edges pointing at a node",
58
- chain: "walks outward from a node layer by layer, one layer per edge count",
56
+ /**
57
+ * 父工作区相对形 → 子仓相对:相对形的首段恰好等于本子仓名时剥掉那一段。
58
+ * 首段不点名任何子仓的相对形(如 `docs/**`)原样下传 —— 那是既有的「逐子仓各扫自己那份」用法。
59
+ * 绝对路径不动。只有扇出那一层知道子仓名,所以重基住在这里,不住 `outline.mjs`。
60
+ */
61
+ function rebaseWorkspacePath(value, name) {
62
+ const s = String(value ?? "").trim()
63
+ if (!s || isAbsolute(s)) return value
64
+ const prefix = `${name}/`
65
+ // win32 下按小写比对,与 `outline.mjs` 的 `underRoot` 同一口径 —— 否则 `Thincoder/docs/...`
66
+ // 会被 `underRoot` 认作本仓内、却被这里判为「不点名本仓」,两处对同一入参给出相反结论。
67
+ const [hay, needle] = process.platform === "win32" ? [s.toLowerCase(), prefix.toLowerCase()] : [s, prefix]
68
+ return hay.startsWith(needle) ? s.slice(prefix.length) : value
59
69
  }
60
- /** `action` 参数描述(按本变体动作集生成;全量四个动作时与旧字面逐字相同)。 */
61
- const actionDescOf = (actions) => `The question to ask: ${actions.map((a) => `\`${a}\` ${ACTION_CLAUSES[a]}`).join(" · ")}.`
62
70
 
63
71
  /**
64
- * 工具工厂:两个装配面同体,只有 `actions` ∥ `readonly` ∥ `docName` ∥ `unscanned` 四个参数不同。
65
- * @param {string[]} actions — 本变体的 action 闭集(schema `enum` ∥ execute 护栏 ∥ 拒文取值集三处同取本参数)。
66
- * @param {{readonly?: boolean, docName?: string, unscanned?: 'throw'|'readonly-empty'}} [opts] — `readonly` 缺省 false
67
- * (全量);`docName` = 该变体的描述档名(`tool-docs/<docName>.md`);`unscanned` = 未建图策略(B5:
68
- * 只读变体传 `readonly-empty`,全量保持抛既有指引)。
72
+ * 逐候选子仓各查一次(各自 `syncGraph` 建图、互不混边),结果按子仓分组并列。
73
+ * 空仓(按各动作未命中文案 / 结构信号判,均产自 `doc-graph.mjs` / `outline.mjs`,本仓可控)跳过;
74
+ * 单仓查询抛错捕获为该组一行错误、不中断其余仓;全部空仓回一行汇总。
75
+ * `context` 的 `ambiguous`(多候选需精化)不算空仓——它给候选清单,仍收录。
69
76
  */
70
- function makeDocGraphTool(actions, { readonly = false, docName = "doc_graph", unscanned = "throw" } = {}) {
71
- const readOnlyVariant = readonly
77
+ async function runWorkspaceFanout(action, candidates, q, args, mod, queryOutlineImpl) {
78
+ // outline 的 paths/glob/query 三者全空是「调用方用法错」,与具体哪个仓无关——进扇出循环前一次性抛出原生报错,
79
+ // 不降级成 N 段「该子仓查询失败」。queryOutline 不走图谱库、零输入在扫盘前即抛,成本低。
80
+ if (action === "outline") {
81
+ const hasPaths = Array.isArray(args?.paths) && args.paths.length > 0
82
+ const hasGlob = typeof args?.glob === "string" && args.glob.trim() !== ""
83
+ const hasQuery = typeof args?.query === "string" && args.query.trim() !== ""
84
+ if (!hasPaths && !hasGlob && !hasQuery) await queryOutlineImpl(candidates[0].root, {})
85
+ // 绝对 glob 同理是与具体哪个仓无关的「调用方用法错」:它一律命中不了任何 rel,先抛一次,
86
+ // 不降级成 N 段「该子仓查询失败」再让模型从重复行里自己拼出原因。
87
+ // glob 形的 `query` 会被 `outline.mjs` 的便捷路由当成 `effectiveGlob`(无 paths、无 glob 时),
88
+ // 所以这条预检必须一并盖住它 —— 否则它绕过这里,同样退化成 N 段重复行。
89
+ if (hasGlob || (!hasPaths && hasQuery && looksLikeGlob(args.query))) {
90
+ const absPattern = firstAbsoluteGlobPattern(hasGlob ? args.glob : args.query)
91
+ if (absPattern) throw absoluteGlobRejection(absPattern)
92
+ }
93
+ }
94
+ const sections = []
95
+ for (const c of candidates) {
96
+ let body = ""
97
+ let empty = false
98
+ try {
99
+ if (action === "context") {
100
+ const res = await mod.queryContextPack(c.root, q)
101
+ body = res?.text ?? ""
102
+ empty = !(res?.ok || res?.ambiguous)
103
+ } else if (action === "impact") {
104
+ body = await mod.queryImpact(c.root, q, { depth: args?.depth })
105
+ empty = body.startsWith("repo_graph(impact):未找到与")
106
+ } else if (action === "symbol") {
107
+ body = await mod.querySymbol(c.root, q)
108
+ empty = body.includes(":无命中(exports.symbol")
109
+ } else if (action === "refs") {
110
+ body = await mod.queryRefs(c.root, q, { edgeType: args?.edgeType, offset: args?.offset })
111
+ empty = body.startsWith("repo_graph(refs):未找到与")
112
+ } else {
113
+ // 父工作区相对形按仓重基(见 `rebaseWorkspacePath`):从会话锚写的 `<子仓>/docs/...` 先剥成子仓相对,
114
+ // 首段不点名本仓的形原样下传 —— 同一次调用里只有名字对上的那个仓会命中,其余仓照常落空被空仓过滤。
115
+ const cPaths = Array.isArray(args?.paths)
116
+ ? args.paths.map((p) => (typeof p === "string" ? rebaseWorkspacePath(p, c.name) : p))
117
+ : args?.paths
118
+ const cGlob = typeof args?.glob === "string" ? rebaseWorkspacePath(args.glob, c.name) : args?.glob
119
+ const cQuery = typeof args?.query === "string" ? rebaseWorkspacePath(args.query, c.name) : args?.query
120
+ // 路径形 query 在该仓不存在时 queryOutline 会按「无 glob/paths/有效 query」抛错;
121
+ // 扇出语义里这是空仓,先判掉再落到文本识别,免得空仓被记成「查询失败」。
122
+ const oq = typeof cQuery === "string" ? cQuery.trim() : ""
123
+ if (oq && !cPaths && !cGlob && !looksLikeGlob(oq) && !existsSync(resolve(c.root, oq))) {
124
+ empty = true
125
+ } else {
126
+ body = await queryOutlineImpl(c.root, { paths: cPaths, glob: cGlob, query: cQuery, depth: args?.depth, includeProcessDocs: args?.includeProcessDocs === true })
127
+ empty = body.startsWith("[Outline] 未匹配到任何文件")
128
+ }
129
+ }
130
+ } catch (e) {
131
+ sections.push(`### 子仓 ${c.name}(${c.root})\n\n(该子仓查询失败:${e.message})`)
132
+ continue
133
+ }
134
+ if (empty || !body.trim()) continue
135
+ sections.push(`### 子仓 ${c.name}(${c.root})\n\n${body}`)
136
+ }
137
+ if (sections.length === 0) {
138
+ const shown = formatCandidateNames(candidates)
139
+ const target = [q || args?.query, args?.glob, ...(Array.isArray(args?.paths) ? args.paths : [])].filter((s) => typeof s === "string" && s.trim()).join(" ")
140
+ // 基准说明必须按动作分叉:重基只发生在 `outline` 支(见循环内对 `cPaths` / `cGlob` / `cQuery` 的处理),
141
+ // 其余四动作从未重基 —— 对它们宣称「已剥过前缀」是不实陈述(评审轮次 1 #1)。
142
+ const baseNote = action === "outline"
143
+ ? "`paths`/`glob`/`query` 按各子仓根解析;从会话锚写的 `<子仓名>/...` 会落到它点名的那个子仓。"
144
+ : "`query` 按各子仓根解析。"
145
+ return `repo_graph(${action}):在父工作区各子仓均未命中 ${JSON.stringify(target)}(已查 ${candidates.length} 个子仓:${shown})。${baseNote}可换关键词重查,或用 target 指名子仓配合 overview 定位。`
146
+ }
147
+ return sections.join("\n\n")
148
+ }
149
+
150
+ function makeRepoGraphTool(docName) {
72
151
  return {
73
- name: "doc_graph",
152
+ name: "repo_graph",
74
153
  description: DESC(docName),
75
154
  parameters: {
76
155
  type: "object",
77
156
  required: ["action"],
78
157
  properties: {
79
- action: { type: "string", enum: actions, description: actionDescOf(actions) },
80
- target: {
158
+ action: {
159
+ type: "string",
160
+ enum: ACTIONS,
161
+ description: "Query mode: `context` (must-read pack for a file/symbol/doc or topic keywords: requirements, design, callers, siblings, deps, tests with line counts), `impact` (1-4 hop reverse impact across code, docs, tests), `overview` (repo architecture hubs and directory deps), `outline` (batch Markdown heading trees / section extraction by title / top-level code outline), `refs` (all incoming/outgoing refs and broken links for one file/doc), `symbol` (who defines one exported symbol and who imports/cites it — grouped by edge kind; exact symbol match only).",
162
+ },
163
+ query: {
164
+ type: "string",
165
+ description: "For `context`/`impact`/`refs`/`symbol` (required): file path, filename, exported symbol, or Chinese/English topic keywords (space-separated multi-keywords matched against Markdown H1-H4 headings, file paths, and exported symbols; plain strings, no prefix). `symbol` takes exactly one exported symbol name. For `outline` (optional): comma-separated heading title terms to extract matching Markdown sections, or a single file/directory path shortcut (resolved against `target`, defaults to the session cwd).",
166
+ },
167
+ paths: {
168
+ type: "array",
169
+ items: { type: "string" },
170
+ description: "For `outline`: explicit file or directory paths to inspect. Resolved against `target` (defaults to the session cwd).",
171
+ },
172
+ glob: {
81
173
  type: "string",
82
- description: "The project root this call is about (the directory carrying PROJECT-MANIFEST.json; a relative path resolves against the session anchor). Required for every action — there is no default: the session anchor is the base for a relative path, never a substitute for `target`.",
174
+ description: "For `outline`: glob pattern for batch inspection (e.g. `docs/core/design/*.md`, supports `**`, `{a,b}`, `!exclude`). Resolved against `target` (defaults to the session cwd).",
83
175
  },
84
- node: {
176
+ target: {
85
177
  type: "string",
86
- description: "The node to start from, written in the identity form: `req:F16` · `doc:<path>` · `doc:<path>#<section>` · `case:CLI 41-1` · `symbol:editTool` · `ledger:#2236`. Required for forward / reverse / chain — a missing node is refused by name, never answered with an empty result.",
178
+ description: "High-leverage — one call replaces many rounds of grep/read. Optional project root directory (defaults to the current session cwd). Works at any level — a multi-project workspace needs no special handling.",
87
179
  },
88
180
  depth: {
89
181
  type: "number",
90
- description: "How many edge steps to walk (`chain` only, required there): depth 1 = the immediate neighbours, depth 2 = their neighbours, and so on. Hops are counted in edges, not nodes. There is no default — a missing depth is refused by name.",
182
+ description: "Optional depth (1-4). For `impact`: reverse hop depth (default 2). For `outline`: Markdown heading level cap (auto-adapts by batch size when omitted: H1-H4 for <=5 files, compact H1-H2 for large batches).",
91
183
  },
92
- // `scope` 只服务 `scan` ⇒ 只存在全量 schema(B6:只读角色面不出现它执行不了的参数)
93
- ...(readOnlyVariant ? {} : {
94
- scope: {
95
- type: "array",
96
- items: { type: "string" },
97
- description: "`scan` only, optional: re-scan just these documents (project-root-relative or absolute). Their edges are deleted and rebuilt; every other document's edges stay untouched. Omit it to scan the whole repository — the receipt's first field always says which of the two it did (`全仓` / `范围 K 档`).",
98
- },
99
- }),
100
- kind: {
184
+ includeProcessDocs: {
185
+ type: "boolean",
186
+ description: "For `outline`: include process-layer docs (batch records/archived material); omitted = excluded by default.",
187
+ },
188
+ edgeType: {
101
189
  type: "string",
102
- description: "`forward` / `reverse` / `chain` only, optional: a comma-separated subset of edge kinds to read — `cites`, `cites-req`, `mentions-case`, `case-file`, `cites-symbol`, `imports`. The edges are filtered before sorting and layering, so a narrowed run is a complete run, not a few lines pulled out of a big receipt. Omit it to read every kind (ledger projections included); the receipt's first line always prints the set in force. A value outside that closed set is refused by name — it is never treated as an empty set.",
190
+ description: "For `refs`: filter edges by kind — one of imports / code-cites / doc-covers / doc-cites / doc-symbol. Omit = all kinds.",
191
+ },
192
+ offset: {
193
+ type: "number",
194
+ description: "For `refs`: 0-based page offset (page size 40) into the incoming/outgoing edge lists; the truncation note carries the next offset when more pages remain.",
103
195
  },
104
196
  },
105
197
  additionalProperties: false,
106
198
  },
107
- readonly,
108
- /** 只读性按 action(先例 = `ledger` 的 `isReadonlyAction`):三查询免审批,`scan` 走侧效门。
109
- * 只读变体的动作集不含 `scan` ⇒ 它恒为真,与 `readonly: true` 同向,不需要第二份实现。 */
110
- isReadonlyAction(args) { return args?.action !== "scan" },
199
+ readonly: true,
200
+ isReadonlyAction() { return true },
111
201
  async execute(args, ctx) {
112
202
  const action = args?.action
113
- // schema 的 enum 是建议性的(provider 不强制)——枚举外的值必须由入口拒,且只印本变体的取值集。
114
- if (!actions.includes(action)) {
115
- throw new Error(`doc_graph:action 非法(${JSON.stringify(action ?? null)})——取值 ∈ {${actions.join(", ")}}`)
116
- }
117
- const target = targetOf(args, ctx)
118
- const boundary = ctx?.agent?.cwd ?? ctx?.cwd
119
- const kindArg = args?.kind
120
- if (kindArg !== undefined && typeof kindArg !== "string") {
121
- throw new Error(`doc_graph:kind 须为逗号分隔的字符串(收到 ${typeof kindArg})——如 "cites,imports";闭集外拒并点名那一个值(由核校验)`)
203
+ if (!ACTIONS.includes(action)) {
204
+ throw new Error(`repo_graph:action 非法(${JSON.stringify(action ?? null)})——取值 ∈ {${ACTIONS.join(", ")}}`)
122
205
  }
206
+ const explicitTarget = typeof args?.target === "string" && args.target.trim() !== ""
207
+ const targetAbs = resolveTargetInput(args, ctx)
123
208
  const mod = await import("../doc-graph.mjs")
124
- if (action === "scan") {
125
- const scope = args?.scope
126
- if (scope !== undefined && !Array.isArray(scope)) {
127
- throw new Error(`doc_graph:scope 须为路径数组(收到 ${typeof scope})——只重扫几档就给 ["<path>"];给空数组等号于全仓`)
209
+ // 显式 target ⇒ 立即判根分流(子目录上溯 / 父工作区扇出);未显式传 ⇒ 先保留会话锚,
210
+ // 给下面的「query 指向子仓内档自动落仓」让路(既有已验收能力),落不到才判根分流。
211
+ const dr = explicitTarget ? resolveQueryRootFanout(targetAbs, action, mod) : null
212
+
213
+ if (action === "outline") {
214
+ const { queryOutline } = await import("../doc-graph/outline.mjs")
215
+ const outlineArgs = {
216
+ paths: args?.paths,
217
+ glob: args?.glob,
218
+ query: args?.query,
219
+ depth: args?.depth,
220
+ includeProcessDocs: args?.includeProcessDocs === true,
221
+ }
222
+ if (explicitTarget) {
223
+ if (dr.fanout) return runWorkspaceFanout(action, dr.candidates, "", args, mod, queryOutline)
224
+ return queryOutline(dr.root, outlineArgs)
225
+ }
226
+ const d = resolveQueryRootFanout(targetAbs, action, mod)
227
+ if (d.fanout) return runWorkspaceFanout(action, d.candidates, "", args, mod, queryOutline)
228
+ return queryOutline(d.root, outlineArgs)
229
+ }
230
+
231
+ if (action === "overview") return mod.queryOverview(explicitTarget ? dr.root : targetAbs)
232
+
233
+ let q = typeof args?.query === "string" ? args.query.trim() : ""
234
+ if (!q) {
235
+ throw new Error(`repo_graph(${action}):query 缺失(必填,请传源码路径、符号名、文档路径或关键词)`)
236
+ }
237
+
238
+ // 多项目父工作区便捷落仓:未显式传 target 但 query 指向子仓内具体文件时,自动落到该子仓根
239
+ let effectiveRoot = explicitTarget ? dr.root : targetAbs
240
+ if (!explicitTarget) {
241
+ const candAbs = isAbsolute(q) ? resolve(q) : resolve(targetAbs, q)
242
+ if (existsSync(candAbs)) {
243
+ const subRoot = mod.resolveProjectRootForFile(candAbs, targetAbs)
244
+ if (subRoot !== targetAbs) {
245
+ const rel = relative(subRoot, candAbs).replace(/\\/g, "/")
246
+ if (rel && !rel.startsWith("..")) {
247
+ effectiveRoot = subRoot
248
+ q = rel
249
+ }
250
+ }
128
251
  }
129
- return mod.scanDocGraph({ target, scope, boundary })
130
252
  }
131
- return mod.queryDocGraph({ action, target, node: args?.node, depth: args?.depth, kind: kindArg, boundary, unscanned })
253
+
254
+ if (action === "context") {
255
+ if (explicitTarget) {
256
+ if (dr.fanout) return runWorkspaceFanout(action, dr.candidates, q, args, mod, null)
257
+ } else if (effectiveRoot === targetAbs) {
258
+ const d = resolveQueryRootFanout(targetAbs, action, mod)
259
+ if (d.fanout) return runWorkspaceFanout(action, d.candidates, q, args, mod, null)
260
+ effectiveRoot = d.root
261
+ }
262
+ const res = await mod.queryContextPack(effectiveRoot, q)
263
+ if (res?.ok && Array.isArray(res.readingPack) && ctx?.agent) {
264
+ if (!Array.isArray(ctx.agent._graphReadingPack)) ctx.agent._graphReadingPack = []
265
+ for (const item of res.readingPack) {
266
+ const fullPath = resolve(effectiveRoot, item.path)
267
+ const display = relative(resolve(ctx.agent.cwd ?? effectiveRoot), fullPath).replace(/\\/g, "/") || item.path
268
+ if (!ctx.agent._graphReadingPack.some((x) => x.path === display)) {
269
+ ctx.agent._graphReadingPack.push({ ...item, path: display })
270
+ }
271
+ }
272
+ }
273
+ return res.text
274
+ }
275
+ if (action === "impact") {
276
+ if (explicitTarget) {
277
+ if (dr.fanout) return runWorkspaceFanout(action, dr.candidates, q, args, mod, null)
278
+ } else if (effectiveRoot === targetAbs) {
279
+ const d = resolveQueryRootFanout(targetAbs, action, mod)
280
+ if (d.fanout) return runWorkspaceFanout(action, d.candidates, q, args, mod, null)
281
+ return mod.queryImpact(d.root, q, { depth: args?.depth })
282
+ }
283
+ return mod.queryImpact(effectiveRoot, q, { depth: args?.depth })
284
+ }
285
+ if (explicitTarget) {
286
+ if (dr.fanout) return runWorkspaceFanout(action, dr.candidates, q, args, mod, null)
287
+ } else if (effectiveRoot === targetAbs) {
288
+ const d = resolveQueryRootFanout(targetAbs, action, mod)
289
+ if (d.fanout) return runWorkspaceFanout(action, d.candidates, q, args, mod, null)
290
+ if (action === "symbol") return mod.querySymbol(d.root, q)
291
+ return mod.queryRefs(d.root, q, { edgeType: args?.edgeType, offset: args?.offset })
292
+ }
293
+ if (action === "symbol") return mod.querySymbol(effectiveRoot, q)
294
+ return mod.queryRefs(effectiveRoot, q, { edgeType: args?.edgeType, offset: args?.offset })
132
295
  },
133
296
  }
134
297
  }
135
298
 
136
- /** 全量变体(depth-0 主 agent 段):四动作,含 `scan`;未建图仍抛既有指引(逐字不变)。 */
137
- export const docGraphTool = makeDocGraphTool(ALL_ACTIONS, { readonly: false })
138
- /** 只读变体(全部 depth>0 角色段与 advisor 面):三动作、无 `scan`;同名不塌缩——两变体互斥装配。
139
- * 未建图返可读空态(不要求父代跑 scan、不隐式写共享边表)。 */
140
- export const docGraphReadTool = makeDocGraphTool(READ_ACTIONS, { readonly: true, docName: "doc_graph-read", unscanned: "readonly-empty" })
299
+ export const repoGraphTool = makeRepoGraphTool("repo_graph")
300
+ export const repoGraphReadTool = makeRepoGraphTool("repo_graph-read")
301
+ export const docGraphTool = repoGraphTool
302
+ export const docGraphReadTool = repoGraphReadTool
@@ -151,7 +151,7 @@ export function classifyEscalateSettle(parent, entry) {
151
151
  * entry.start() (immediately, or later via maybeRefillAsync when a slot frees).
152
152
  */
153
153
  export function launchEscalateAsync(parent, ctx, launch) {
154
- const { task, provider, tag, effortNote } = launch
154
+ const { task, provider, tag, effortNote, modelParams } = launch
155
155
  parent._asyncSubagents ??= new Map()
156
156
  parent._asyncQueue ??= []
157
157
  // Async id allocation (AGENT-LOOP-SUBAGENT.md §6.7.3 precedent): reserve the relay
@@ -206,6 +206,9 @@ export function launchEscalateAsync(parent, ctx, launch) {
206
206
  role: "coder",
207
207
  })
208
208
  entry.childAgent = child // settle 分类/status touched 摘要绑定(start 时刻)
209
+ // 2026-12-03 批(台账 #133):escalate 池的 effort 覆盖(已钳制)住子 agent 会话视图
210
+ //(`modelParams` 不再是 provider 条目属性;不传 ⇒ 沿用 `createAgent` 给的父会话视图)。
211
+ if (modelParams) child.modelParams = modelParams
209
212
  child._historyWindow = RECORD_WINDOW_MESSAGES // TUI-OOM-ROOTCAUSE·AGENT-LOOP.md §9.2:子代理人读线窗口(四处创建点同置)
210
213
  child._logId = relayPrefix.slice(0, -1)
211
214
  // SUBAGENT-UPSTREAM-CHANNEL(§6.27.4 W3——escalate **async**:工具返回注走异步形)。
@@ -1,11 +1,12 @@
1
1
  // F-CC4(CONTEXT-COMPACTION.md §6.16.5):goal 任一状态变更 ⇒ 方向转换轻推(本档只调用;文案/去重单源 = agent-tools/context.mjs)
2
2
  import { pushContextNudge } from "./context.mjs"
3
- import { flattenHistory } from "../context.mjs"
4
3
  import { DESC } from "../tools/shared.mjs"
4
+ import { setGoal, clearGoal, GOAL_CONDITION_MAX } from "../agent/goal-state.mjs"
5
5
 
6
6
  /**
7
- * goal tool: lifecycle management for long-running autonomous goals (completion contract).
8
- * 描述面 = `tool-docs/goal.md`(DESC() 加载);完成阈 / 阻塞计次 / 每回合注入 = execute 内实现注。
7
+ * goal tool: 模型代用户设 / 取消 / 查看长期目标。
8
+ * 设计 = `docs/core/design/GOAL.md` §4;需求 = `docs/core/requirements/GOAL.md` §2。
9
+ * 完成判定归独立裁判(`agent/goal-judge.mjs`),本工具不自判完成——`complete` / `blocked` 已退役。
9
10
  */
10
11
  export const goalTool = {
11
12
  name: "goal",
@@ -13,110 +14,42 @@ export const goalTool = {
13
14
  parameters: {
14
15
  type: "object",
15
16
  properties: {
16
- action: { type: "string", enum: ["set", "complete", "blocked", "cancel"], description: "Goal lifecycle action" },
17
- objective: { type: "string", description: "What you are trying to accomplish (for 'set')" },
18
- criteria: { type: "string", description: "How completion is PROVEN: the exact check to run, e.g. 'npm test passes', 'grep finds no TODO marker' (required for 'set')" },
19
- reason: { type: "string", description: "The blocking condition (required for 'blocked')" },
17
+ action: { type: "string", enum: ["set", "cancel", "view"], description: "Goal lifecycle action" },
18
+ condition: { type: "string", description: `What counts as done — the goal and its completion criterion in one string (required for 'set', max ${GOAL_CONDITION_MAX} chars)` },
20
19
  },
21
20
  required: ["action"],
22
21
  },
23
22
  readonly: true,
24
23
  async execute(args, ctx) {
25
24
  const agent = ctx.agent
25
+ if (args.action === "view") {
26
+ if (!agent.goal) return "No goal set."
27
+ const g = agent.goal
28
+ return [
29
+ `Goal: ${g.condition}`,
30
+ `Status: ${g.status}`,
31
+ `Source: ${g.source}`,
32
+ `Turns evaluated: ${g.turnsEvaluated ?? 0}`,
33
+ `Tokens spent: ${g.tokensSpent ?? 0}`,
34
+ `Last verdict: ${g.lastVerdict ?? "(none)"}`,
35
+ `Last reason: ${g.lastReason ?? "(none)"}`,
36
+ ].join("\n")
37
+ }
26
38
  if (args.action === "cancel") {
27
- agent.goal = null
39
+ if (!agent.goal) return "No goal to cancel."
40
+ clearGoal(agent)
28
41
  if (ctx.depth === 0) pushContextNudge(agent) // F-CC4(depth-0 门)
29
- return "Goal cancelled. If the goal was blocked or impossible, explain why in your next message — the user can clarify, adjust scope, or confirm cancellation."
42
+ return "Goal cleared. The loop stops at the next exit point."
30
43
  }
31
44
  if (args.action === "set") {
32
- if (!args.objective) return "Error: 'objective' required for 'set' action."
33
- if (!args.criteria) {
34
- return "Error: 'criteria' required for 'set' — a goal without a machine-checkable proof of completion is a wish, not a goal. Name the exact check (tests, command output, search result) that proves it's done."
35
- }
36
- agent.goal = {
37
- objective: String(args.objective).slice(0, 500),
38
- criteria: String(args.criteria).slice(0, 500),
39
- setAt: Date.now(),
40
- status: "active",
41
- turnsUsed: 0,
42
- _blockTally: null, // { reason, count } — consecutive count of the same blocking condition (for blocked audit)
43
- }
44
- if (ctx.depth === 0) pushContextNudge(agent) // F-CC4(depth-0 门)
45
- return `Goal set: ${agent.goal.objective}\nDone when: ${agent.goal.criteria}\nThe system will inject goal status every turn. Completion and blocked claims are audited — see the reminders.`
46
- }
47
- if (!agent.goal || agent.goal.status !== "active") {
48
- return `Error: no active goal to '${args.action}' (current: ${agent.goal?.status ?? "none"}). Set one first.`
49
- }
50
- if (args.action === "complete") {
51
- // Evidence chain threshold: files were mutated this run without verify — refuse completion (aligns with completion guard)
52
- if (agent._mutatedThisRun && !agent._verifiedThisRun) {
53
- return "Error: files were modified but verify has not run. Run the check your criteria names AND the verify tool before marking the goal complete — false completion is the worst outcome of autonomous work."
54
- }
55
-
56
- // Independent judge: verify the goal was actually achieved
57
- // Only applies when the agent is at depth 0 (not a subagent) and has history to review
58
- // 机读线按轮嵌套:判据与取数都在拍平视图上(外层条数是轮数,不是消息数)。
59
- const flat = flattenHistory(agent.history)
60
- if (ctx.depth === 0 && flat.length > 2) {
61
- try {
62
- // Extract recent activity: last 4 assistant messages (summarizing what was done)
63
- const recent = flat.filter(m => m.role === "assistant").slice(-4)
64
- const activity = recent.map(m => (m.content ?? "").slice(0, 500)).join("\n---\n")
65
- const { chat } = await import("../provider/index.mjs")
66
- const judgeRes = await chat(agent.provider, {
67
- messages: [{
68
- role: "user",
69
- content: `You are an independent goal judge. Evaluate whether this goal has been achieved based on the agent's activity.
70
-
71
- Goal: ${agent.goal.objective}
72
- Success criteria: ${agent.goal.criteria}
73
-
74
- Recent agent activity:
75
- ${activity || "(no activity recorded)"}
76
-
77
- Has this goal been achieved? Answer ONLY "YES" or "NO" followed by a one-sentence reason.`,
78
- }],
79
- tools: [],
80
- signal: AbortSignal.timeout(10_000),
81
- // §18.6 D-TR4/D-TR6(2026-09-04 fix round1):goal 独立评审调用经 chat()
82
- // 唯一采集点——补轨迹元数据 + traces 开关透传(agent.config.traces.enabled
83
- // ——关=不落盘必须全覆盖——与 agent.mjs/context.mjs 同模式)
84
- logCtx: {
85
- stage: "goal", kind: "goal",
86
- role: agent._role ?? null, depth: ctx.depth,
87
- session: agent._sessionStart ?? null, cwd: agent.cwd,
88
- traces: agent.config?.traces?.enabled !== false,
89
- },
90
- })
91
- const verdict = (judgeRes.content ?? "").trim()
92
- if (verdict.toUpperCase().startsWith("NO")) {
93
- return `Goal NOT complete (judge says NO): ${verdict.slice(2).trim()}\n\nContinue working or report blocked if this is a true impasse.`
94
- }
95
- if (!verdict.toUpperCase().startsWith("YES")) {
96
- return `Goal completion unverified — judge response ambiguous: "${verdict.slice(0, 200)}". Re-check your criteria and try again with clear evidence.`
97
- }
98
- } catch {
99
- // Judge unavailable — allow completion but note it
100
- }
101
- }
102
-
103
- agent.goal.status = "complete"
104
- if (ctx.depth === 0) pushContextNudge(agent) // F-CC4(depth-0 门)
105
- return `Goal verified complete ✓: ${agent.goal.objective}\nIn your next message, summarize the evidence (what check ran, what it showed) — the user should be able to audit this claim.`
106
- }
107
- if (args.action === "blocked") {
108
- if (!args.reason) return "Error: 'reason' required for 'blocked' action."
109
- // Blocked audit: same condition must appear 3 consecutive times (only counts as real blocking if different approaches still hit the same wall)
110
- const tally = agent.goal._blockTally
111
- const count = tally?.reason === args.reason ? tally.count + 1 : 1
112
- agent.goal._blockTally = { reason: args.reason, count }
113
- if (count < 3) {
114
- return `Blocked not accepted yet (${count}/3 for this condition). Try a genuinely different approach first; report blocked only if the same condition stops you ${3 - count} more time(s).`
45
+ try {
46
+ setGoal(agent, { condition: args.condition, source: "model" })
47
+ } catch (e) {
48
+ return `Error: ${e.message}`
115
49
  }
116
- agent.goal.status = "blocked"
117
50
  if (ctx.depth === 0) pushContextNudge(agent) // F-CC4(depth-0 门)
118
- return `Goal marked blocked after 3 attempts: ${args.reason}\nExplain the blocker to the user in your next message — what you tried, and what you need (clarification, permission, a decision).`
51
+ return `Goal set: ${agent.goal.condition}\nThe loop keeps running until an independent judge says the condition holds, or the turn budget runs out.`
119
52
  }
120
53
  return `Error: unknown action '${args.action}'.`
121
54
  },
122
- }
55
+ }
@@ -20,7 +20,7 @@ export const PLAN_REVISE_OPTION = "Keep planning (revise)"
20
20
  export const PLAN_MODE_POLICY =
21
21
  "[System reminder: plan mode is ON (read-only). Stay in plan mode until the user approves your plan via plan(action='exit', plan=...) or manually turns plan mode off.\n" +
22
22
  "- Oral confirmation is NOT approval: a user's casual 'ok/yes' or answer to a clarifying question does not exit plan mode — fold it into the plan and submit via plan(action='exit', plan=...).\n" +
23
- "- Read-only verification (4 steps before finalizing): (1) break down every requirement and side condition; (2) inspect authoritative docs and in-repo precedents in parallel (read/grep/glob/peek/step(readonly=true)/explore); (3) scan callers and sibling logic repo-wide so nothing is missed; (4) verify exclusions (what NOT to touch), edge cases/fallbacks, and targeted verification commands.\n" +
23
+ "- Read-only verification (4 steps before finalizing): (1) break down every requirement and side condition; (2) inspect authoritative docs and in-repo precedents in parallel (read/grep/glob/repo_graph/step(readonly=true)/explore); (3) scan callers and sibling logic repo-wide so nothing is missed; (4) verify exclusions (what NOT to touch), edge cases/fallbacks, and targeted verification commands.\n" +
24
24
  "- Do not mutate files or pre-fill the task list during planning (the plan itself covers the steps; track execution with task only after approval).\n" +
25
25
  "- Decision-complete plan: submit a complete Markdown plan starting with a `# <Title>` heading covering goal & criteria, affected files (including docs to sync) & explicit exclusions, dependency-ordered concrete steps (cite real paths/symbols, never line numbers), edge cases/fallbacks/assumptions, and targeted verification commands.\n" +
26
26
  "- Single exit: call plan(action='exit', plan='<full markdown plan>') as your final review submission. Do not paste the final plan as plain text and ask 'should I proceed?'. If the user requests revisions, stay in plan mode, update the plan, and call plan(action='exit', plan=...) again.]"