@thincoder/core 0.11.2 → 0.11.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.
Files changed (198) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/advisor/compaction.mjs +7 -5
  3. package/advisor/history.mjs +24 -11
  4. package/advisor/loop.mjs +13 -8
  5. package/advisor/messages.mjs +72 -8
  6. package/advisor/run.mjs +24 -13
  7. package/advisor.mjs +7 -3
  8. package/agent/chat-call.mjs +14 -9
  9. package/agent/completion.mjs +28 -40
  10. package/agent/continue-decision.mjs +14 -8
  11. package/agent/digest-account.mjs +133 -59
  12. package/agent/dispatch-run.mjs +1 -1
  13. package/agent/dispatch.mjs +2 -1
  14. package/agent/family-tools.mjs +12 -13
  15. package/agent/helpers.mjs +17 -72
  16. package/agent/image-heal.mjs +18 -4
  17. package/agent/post-turn.mjs +13 -26
  18. package/agent/record-results.mjs +21 -6
  19. package/agent/run-stages.mjs +72 -37
  20. package/agent/run-start.mjs +148 -113
  21. package/agent/setup-reminders.mjs +187 -91
  22. package/agent/setup.mjs +204 -138
  23. package/agent/spawn-child.mjs +2 -2
  24. package/agent/suspension.mjs +43 -15
  25. package/agent/timers.mjs +4 -1
  26. package/agent/turn-domain-text.mjs +105 -0
  27. package/agent/turn-loop.mjs +54 -22
  28. package/agent/turn-projection.mjs +127 -227
  29. package/agent/turn-tool-process.mjs +32 -37
  30. package/agent-tools/advisor-async.mjs +6 -3
  31. package/agent-tools/advisor-launch.mjs +5 -5
  32. package/agent-tools/advisor.mjs +1 -1
  33. package/agent-tools/async-discard.mjs +7 -2
  34. package/agent-tools/async-settle.mjs +18 -12
  35. package/agent-tools/bash-async.mjs +5 -2
  36. package/agent-tools/batch-closeout.mjs +12 -62
  37. package/agent-tools/batch-ledger-bind.mjs +19 -8
  38. package/agent-tools/batch-lifecycle.mjs +37 -11
  39. package/agent-tools/batch-read.mjs +151 -4
  40. package/agent-tools/batch-record-write.mjs +5 -5
  41. package/agent-tools/batch-segment-vocab.mjs +84 -4
  42. package/agent-tools/batch-skeleton.mjs +18 -14
  43. package/agent-tools/batch-supersede.mjs +1 -1
  44. package/agent-tools/batch-tier-gate.mjs +36 -119
  45. package/agent-tools/batch.mjs +30 -20
  46. package/agent-tools/browser-async.mjs +5 -2
  47. package/agent-tools/consult.mjs +10 -7
  48. package/agent-tools/context.mjs +47 -31
  49. package/agent-tools/digest-budget.mjs +10 -9
  50. package/agent-tools/eng.mjs +3 -4
  51. package/agent-tools/escalate-async.mjs +3 -3
  52. package/agent-tools/goal.mjs +5 -2
  53. package/agent-tools/judge-domain.mjs +347 -0
  54. package/agent-tools/manifest.mjs +2 -2
  55. package/agent-tools/parent-channel.mjs +6 -3
  56. package/agent-tools/plan.mjs +11 -10
  57. package/agent-tools/review-facts.mjs +9 -3
  58. package/agent-tools/skill.mjs +7 -8
  59. package/agent-tools/spawn-gates.mjs +5 -16
  60. package/agent-tools/ssh-session.mjs +6 -3
  61. package/agent-tools/ssh-transfer.mjs +1 -1
  62. package/agent-tools/subagent-actions.mjs +2 -2
  63. package/agent-tools/subagent-async.mjs +11 -8
  64. package/agent-tools/subagent-scheduler.mjs +9 -9
  65. package/agent-tools/subagent-spawn.mjs +2 -2
  66. package/agent-tools/subagent.mjs +5 -18
  67. package/agent-tools/task.mjs +0 -8
  68. package/agent.mjs +15 -15
  69. package/auto-think.mjs +5 -2
  70. package/compaction-work-state.mjs +230 -0
  71. package/compress-form.mjs +41 -6
  72. package/config-defaults.mjs +5 -2
  73. package/config.mjs +53 -17
  74. package/context-degrade.mjs +79 -48
  75. package/context-echo.mjs +6 -26
  76. package/context-push.mjs +328 -31
  77. package/context.mjs +203 -141
  78. package/conventions.mjs +1 -1
  79. package/declaration.mjs +95 -17
  80. package/escape.mjs +6 -5
  81. package/explore-distill.mjs +35 -8
  82. package/generate-title.mjs +10 -1
  83. package/knowledge/prompt-resources.md +5 -1
  84. package/ledger-tools.mjs +50 -50
  85. package/ledger-write-ops.mjs +43 -16
  86. package/memory/docs.mjs +51 -15
  87. package/memory/file-list.mjs +6 -0
  88. package/model-specs.mjs +87 -21
  89. package/origin-guard.mjs +190 -0
  90. package/package.json +1 -1
  91. package/prompt-files.mjs +33 -11
  92. package/prompt-overlays.mjs +12 -5
  93. package/prompts/advisor-design.md +55 -36
  94. package/prompts/advisor-round1.md +18 -7
  95. package/prompts/advisor-round2.md +18 -7
  96. package/prompts/advisor-round3.md +18 -7
  97. package/prompts/common.md +89 -51
  98. package/prompts/consult-base.md +2 -3
  99. package/prompts/discipline-engineering.md +474 -440
  100. package/prompts/discipline-normal.md +107 -31
  101. package/prompts/knowledge/business-gates.md +23 -15
  102. package/prompts/knowledge/decision-quality.md +16 -18
  103. package/prompts/knowledge/doc-lookup.md +22 -27
  104. package/prompts/knowledge/document-writing.md +31 -49
  105. package/prompts/knowledge/documentation-evaluation.md +37 -45
  106. package/prompts/knowledge/evidence-discipline.md +36 -55
  107. package/prompts/knowledge/normal-coding-workflow.md +27 -21
  108. package/prompts/knowledge/normal-delivery-collaboration.md +33 -17
  109. package/prompts/knowledge/normal-work-management.md +10 -7
  110. package/prompts/knowledge/product-security.md +22 -17
  111. package/prompts/knowledge/project-records.md +63 -52
  112. package/prompts/knowledge/tool-apply-patch.md +12 -13
  113. package/prompts/knowledge/tool-bash.md +13 -4
  114. package/prompts/knowledge/tool-batch-eng-coder.md +13 -6
  115. package/prompts/knowledge/tool-batch-eng-designer.md +14 -6
  116. package/prompts/knowledge/tool-batch-review.md +12 -6
  117. package/prompts/knowledge/tool-batch.md +76 -62
  118. package/prompts/knowledge/tool-browser.md +45 -34
  119. package/prompts/knowledge/tool-context.md +2 -2
  120. package/prompts/knowledge/tool-delete.md +5 -1
  121. package/prompts/knowledge/tool-doc-check.md +25 -24
  122. package/prompts/knowledge/tool-doc-graph-read.md +3 -3
  123. package/prompts/knowledge/tool-doc-graph.md +15 -15
  124. package/prompts/knowledge/tool-edit.md +26 -23
  125. package/prompts/knowledge/tool-execute.md +9 -4
  126. package/prompts/knowledge/tool-fetch.md +7 -1
  127. package/prompts/knowledge/tool-file-ops.md +6 -1
  128. package/prompts/knowledge/tool-git-read.md +3 -1
  129. package/prompts/knowledge/tool-git.md +1 -1
  130. package/prompts/knowledge/tool-glob.md +3 -1
  131. package/prompts/knowledge/tool-grep.md +5 -2
  132. package/prompts/knowledge/tool-hashline-edit.md +4 -2
  133. package/prompts/knowledge/tool-insert-after.md +3 -1
  134. package/prompts/knowledge/tool-ledger-read.md +6 -13
  135. package/prompts/knowledge/tool-ledger.md +14 -10
  136. package/prompts/knowledge/tool-ls.md +2 -0
  137. package/prompts/knowledge/tool-manifest.md +10 -7
  138. package/prompts/knowledge/tool-memory.md +15 -11
  139. package/prompts/knowledge/tool-operations.md +59 -71
  140. package/prompts/knowledge/tool-plan.md +1 -2
  141. package/prompts/knowledge/tool-process.md +1 -1
  142. package/prompts/knowledge/tool-read-history.md +6 -7
  143. package/prompts/knowledge/tool-read.md +1 -0
  144. package/prompts/knowledge/tool-settings.md +6 -7
  145. package/prompts/knowledge/tool-ssh.md +37 -15
  146. package/prompts/knowledge/tool-subagent.md +37 -39
  147. package/prompts/knowledge/tool-task.md +3 -1
  148. package/prompts/knowledge/tool-team-ledger.md +5 -1
  149. package/prompts/knowledge/tool-tree.md +2 -0
  150. package/prompts/knowledge/tool-wait-for.md +16 -16
  151. package/prompts/knowledge/tool-write.md +4 -1
  152. package/prompts/knowledge/upstream-protocol.md +39 -37
  153. package/prompts/persona-coder.md +1 -3
  154. package/prompts/persona-eng-coder.md +5 -5
  155. package/prompts/persona-eng-designer.md +34 -17
  156. package/prompts/persona-engineering.md +532 -501
  157. package/prompts/persona-explore.md +0 -2
  158. package/prompts/persona-normal.md +17 -9
  159. package/prompts/persona-plan.md +0 -2
  160. package/prompts/persona-tester.md +0 -2
  161. package/prompts/subagent-base.md +0 -2
  162. package/provider/anthropic.mjs +4 -2
  163. package/provider/core.mjs +5 -3
  164. package/provider/errors.mjs +41 -7
  165. package/provider/google.mjs +5 -3
  166. package/provider/reasoning-echo.mjs +16 -0
  167. package/provider/responses.mjs +4 -2
  168. package/provider/sse.mjs +11 -6
  169. package/rules.mjs +11 -10
  170. package/session-lifecycle.mjs +115 -81
  171. package/session-slot-write.mjs +1 -1
  172. package/session.mjs +23 -20
  173. package/shell-identity.mjs +129 -22
  174. package/skip-dirs.mjs +24 -0
  175. package/team-ledger.mjs +22 -22
  176. package/text-budget.mjs +1 -1
  177. package/think-off.mjs +27 -0
  178. package/token-ttl.mjs +1 -1
  179. package/token-window.mjs +278 -88
  180. package/tool-docs/bash.md +0 -2
  181. package/tool-docs/consult_start.md +2 -2
  182. package/tool-docs/consult_stop.md +2 -2
  183. package/tools/browser.mjs +8 -8
  184. package/tools/execute.mjs +2 -2
  185. package/tools/file.mjs +17 -11
  186. package/tools/git.mjs +12 -12
  187. package/tools/ops.mjs +2 -2
  188. package/tools/patch.mjs +1 -1
  189. package/tools/process-doc-mark.mjs +33 -4
  190. package/tools/repomap.mjs +25 -3
  191. package/tools/search.mjs +74 -26
  192. package/tools/shared.mjs +4 -3
  193. package/tools/ssh.mjs +5 -5
  194. package/tools/tree.mjs +32 -10
  195. package/tools/web-deepseek.mjs +1 -1
  196. package/tools/web.mjs +2 -2
  197. package/tools/write-gate-params.mjs +3 -3
  198. package/window-policy.mjs +118 -78
@@ -14,7 +14,7 @@
14
14
  * consult / depth-0 不装配);调用**同步返回**(零 await、零等待态——本档不提供任何拉取 /
15
15
  * 轮询 / 等答复动作:D-UC3 非阻塞 = 结构保证)。
16
16
  * - 父侧接收 = 队列 `_childUpstream`(数组;条目 `{seq, from, kind, message, ts}`)+ 单调计数
17
- * `_childUpstreamSeq`——**两字段皆属载体字段集**(AGENT-LOOP.md §2.3,与 `_asyncQueue` /
17
+ * `_childUpstreamSeq`——**两字段皆属载体字段集**(AGENT-LOOP.md §9.1,与 `_asyncQueue` /
18
18
  * `_asyncAdvisorQueue` 同列):读单点 = `async-settle.mjs` 的 `carrierField`,写单点 = 本档的
19
19
  * `upstreamHolder`(父字段优先 / `history` 命中即借用 / 皆无则建在父字段 + 载体别名)。
20
20
  * 生命周期与子代理生命周期**解耦**(settle / cancel 不迁移、不清队列——F3)。
@@ -40,7 +40,7 @@
40
40
  * 登记册导出(`agent-tools.mjs`)→ 家族矩阵装配(`agent/family-tools.mjs` depth>0 段)。
41
41
  */
42
42
  import { carrierField, getAsyncPool, tombstoneOf, wakeAsyncWaiters } from "./async-settle.mjs"
43
- import { pushReal } from "../context.mjs"
43
+ import { pushInject, pushRecord } from "../context.mjs"
44
44
  import { escapeXml } from "../agent/helpers.mjs"
45
45
  import { logEvent } from "../log.mjs"
46
46
  // #15 描述外置:描述文本单点 = tool-docs/notify_parent.md(DESC 单解析面,缺档抛错语义不变)
@@ -172,7 +172,10 @@ export function drainChildUpstream(agent) {
172
172
  : `[System reminder: in-flight message from your subagent ${entries[0].from} — it keeps working on the unaffected parts. `
173
173
  + "Answer with subagent action:'send' (id + message) if the decision is yours; an unanswered ask means the child skips that part and reports it as not done.]"
174
174
  const rows = entries.map((e) => `${many ? "- " : ""}${KIND_MARK[e.kind] ?? e.kind} · ${e.from}: ${escapeXml(e.message)}${endNote(agent, e)}`)
175
- pushReal(agent, { role: "user", content: [header, ...rows].join("\n") })
175
+ const msg = { role: "user", content: [header, ...rows].join("\n") }
176
+ // B 段:一次性投递走待发队,持久写入只落人读线(机读线零触)。
177
+ pushInject(agent, msg)
178
+ pushRecord(agent, msg)
176
179
  return entries.length
177
180
  }
178
181
 
@@ -7,6 +7,7 @@
7
7
  * user sends a new message — so the constraint never fades from context.
8
8
  */
9
9
  import { DESC } from "../tools/shared.mjs"
10
+ import { pushInject } from "../context.mjs"
10
11
 
11
12
  const PLAN_FULL_REMINDER =
12
13
  "[System reminder: plan mode is ON. Workflow: (1) explore/read codebase with read-only tools, " +
@@ -35,12 +36,14 @@ const FULL_INTERVAL = 5
35
36
  export const PLAN_ENGINEERING_REFUSED =
36
37
  "plan mode is disabled in engineering mode — engineering mode already runs design-before-code (design → review → approval → implementation)."
37
38
 
38
- /** ENG-PLAN-EXCLUSION(FR31 ③ · KD10):未注入 plan 提示语判据 = 三条 reminder 常量逐字组成员。 */
39
- const isPlanReminder = (r) => r === PLAN_FULL_REMINDER || r === PLAN_SPARSE_REMINDER || r === PLAN_EXIT_REMINDER
39
+ /** ENG-PLAN-EXCLUSION(FR31 ③ · KD10):未注入 plan 提示语判据 = 三条 reminder 常量逐字组成员。
40
+ * 待发队(B 段)里的条目已升级为消息对象 ⇒ 判据读 `content`(与 `history` 时代同一个逐字面)。 */
41
+ const isPlanReminder = (content) => content === PLAN_FULL_REMINDER || content === PLAN_SPARSE_REMINDER || content === PLAN_EXIT_REMINDER
42
+ const isPlanInject = (m) => isPlanReminder(m?.content)
40
43
 
41
44
  /**
42
45
  * ENG-PLAN-EXCLUSION(FR31 ③ / KD10——单点复用):工程模式 ⇒ `planMode` 恒 false。
43
- * 清 `planMode` + 两 reminder 计数 + **未注入的 plan 提示语**(`_pendingReminders` 中的三条
46
+ * 清 `planMode` + 两 reminder 计数 + **未注入的 plan 提示语**(待发队 `_pendingInject` 中的三条
44
47
  * plan 提醒——否则排队的 `PLAN_EXIT_REMINDER`「Present your plan … wait for their explicit approval …」会在模式翻转后
45
48
  * 落地,与工程链条打架)。五个挂点复用本函数:三翻转(核 `eng` 工具 / CLI `/eng` / VSC 面板开关)
46
49
  * + 两恢复(CLI `applySession` / VSC `applySlotSessionState`)。
@@ -49,13 +52,13 @@ const isPlanReminder = (r) => r === PLAN_FULL_REMINDER || r === PLAN_SPARSE_REMI
49
52
  */
50
53
  export function clearPlanMode(agent) {
51
54
  if (!agent) return false
52
- const queued = Array.isArray(agent._pendingReminders) ? agent._pendingReminders.filter(isPlanReminder).length : 0
55
+ const queued = Array.isArray(agent._pendingInject) ? agent._pendingInject.filter(isPlanInject).length : 0
53
56
  const had = agent.planMode === true || queued > 0
54
57
  agent.planMode = false
55
58
  agent._planTurnsSinceReminder = 0
56
59
  agent._planTurnsSinceSparse = 0
57
- if (Array.isArray(agent._pendingReminders)) {
58
- agent._pendingReminders = agent._pendingReminders.filter((r) => !isPlanReminder(r))
60
+ if (Array.isArray(agent._pendingInject)) {
61
+ agent._pendingInject = agent._pendingInject.filter((m) => !isPlanInject(m))
59
62
  }
60
63
  return had
61
64
  }
@@ -103,8 +106,7 @@ export const planTool = {
103
106
  if (args.action === "exit") {
104
107
  ctx.agent.planMode = false
105
108
  ctx.agent._planTurnsSinceReminder = 0
106
- ctx.agent._pendingReminders = ctx.agent._pendingReminders ?? []
107
- ctx.agent._pendingReminders.push(PLAN_EXIT_REMINDER)
109
+ pushInject(ctx.agent, { role: "user", content: PLAN_EXIT_REMINDER })
108
110
  return "Plan mode exited. Present your plan to the user and wait for their explicit approval before writing any code."
109
111
  }
110
112
  if (args.action !== "enter") {
@@ -112,8 +114,7 @@ export const planTool = {
112
114
  }
113
115
  ctx.agent.planMode = true
114
116
  ctx.agent._planTurnsSinceReminder = 0
115
- ctx.agent._pendingReminders = ctx.agent._pendingReminders ?? []
116
- ctx.agent._pendingReminders.push(PLAN_FULL_REMINDER)
117
+ pushInject(ctx.agent, { role: "user", content: PLAN_FULL_REMINDER })
117
118
  return "Plan mode activated. You are now restricted to READ-ONLY tools. Explore the codebase, understand the architecture, design a solution. Present your plan to the user for approval before writing any code."
118
119
  },
119
120
  }
@@ -128,10 +128,16 @@ export function scopeAdvisorMirror(agent, run) {
128
128
  agent._advisorResponseAnchor = run.historyAnchorIdx ?? null
129
129
  }
130
130
 
131
- /** #949(② 投递水印):响应表取件下界 = 投递刻 history 下标(消费面前向取首表)。
132
- * 调用点:async `injectAsyncResult`(pushReal 后)∥ sync record-results 记账块;
131
+ /** #949(② 投递水印):响应表取件下界 = 投递刻的线尾位置 `{ turn, msg }`(外层最后一个轮元素 + 它内层的长度;
132
+ * 消费面前向取首表)。位置形不存拍平下标——拍平下标在每次结构编辑后全部漂。
133
+ * 调用点:async `injectAsyncResult`(pushInject 后)∥ sync record-results 记账块;
133
134
  * run 缺省 / 非对象(legacy 直调)⇒ 零写(回落全文倒扫)。 */
134
135
  export function noteReviewDelivered(agent, run) {
135
136
  if (!run || typeof run !== "object") return
136
- run.historyAnchorIdx = Array.isArray(agent?.history) ? agent.history.length : 0
137
+ const h = Array.isArray(agent?.history) ? agent.history : []
138
+ const last = h.at(-1)
139
+ run.historyAnchorIdx = {
140
+ turn: h.length - 1,
141
+ msg: Array.isArray(last?.messages) ? last.messages.length : 0,
142
+ }
137
143
  }
@@ -1,6 +1,8 @@
1
1
  import { loadSkills, readSkill } from "../skills.mjs"
2
2
  import { escapeXml } from "../agent.mjs"
3
3
  import { DESC } from "../tools/shared.mjs"
4
+ // C 段(累积内容)载体:按名字追加、同名替换——技能块每请求都在(`CONTEXT-COMPACTION.md` §1.1 注入三段)。
5
+ import { retain } from "../context.mjs"
4
6
 
5
7
  // ─── skill loader 注入缝(#88——「同步 loader 面按核内结构归一」的端侧覆盖范围)──────────
6
8
  /**
@@ -41,9 +43,9 @@ export const skillTool = {
41
43
  return skills.map((s) => `- ${s.name}: ${s.description}`).join("\n")
42
44
  }
43
45
  if (!args.name) return "Error: skill name required for 'load' action."
44
- // Dedup: skip reloading if history already contains an <skill-loaded> block with the same name
45
- // (history is the ledger; if it got compacted away we naturally won't find it here — correct behavior)
46
- if (ctx.agent.history?.some((m) => typeof m.content === "string" && m.content.includes(`<skill-loaded name="${args.name}"`))) {
46
+ // 已加载判据按名字读 C 段(不扫机读线——注入不在线上);压缩后找不到是原语义(块随累积段一直在,
47
+ // 本就与机读线无关)。
48
+ if (ctx.agent._retained?.some?.((e) => e?.name === args.name)) {
47
49
  return `Skill "${args.name}" is already loaded in this conversation — follow the instructions in the existing <skill-loaded> block above. Do not reload it.`
48
50
  }
49
51
  const content = await readSkillFn(ctx.agent.cwd, args.name)
@@ -51,11 +53,8 @@ export const skillTool = {
51
53
  const available = skills.map((s) => s.name).join(", ")
52
54
  return `Error: skill "${args.name}" not found. Available: ${available || "(none)"}`
53
55
  }
54
- // Inject skill content into history (will appear as the next user message)
55
- ctx.agent._pendingReminders = ctx.agent._pendingReminders ?? []
56
- ctx.agent._pendingReminders.push(
57
- `<skill-loaded name="${args.name}" source=".thincoder/skills/${args.name}.md">\n${escapeXml(content)}\n</skill-loaded>\n\nFollow the skill's instructions above for the current task.`
58
- )
56
+ // 技能内容进 C 段累积载体(按名字追加、同名替换——装配时每请求都在)
57
+ retain(ctx.agent, args.name, `<skill-loaded name="${args.name}" source=".thincoder/skills/${args.name}.md">\n${escapeXml(content)}\n</skill-loaded>\n\nFollow the skill's instructions above for the current task.`)
59
58
  return `Skill "${args.name}" loaded. Instructions will appear in the next message.`
60
59
  },
61
60
  }
@@ -164,39 +164,28 @@ export function composeTaskBookBrief(args, role) {
164
164
  return parts.join("\n\n")
165
165
  }
166
166
 
167
- /**
168
- * F6 过程档 basename 族(父侧维护文件——AGENT-LOOP-SUBAGENT.md §6.9 R26 同族扩展):
169
- * CHANGELOG.md。(台账 = 用户数据目录键控库——项目内无文件,不再入族;老台账族 todo.md /
170
- * todo-archive.md / checklist 族随 M2 SQLite 化 + M7 checklist 废除退役。)
171
- * 大小写不敏感全名匹配(路径任意层——归一化在调用点 normalizeFileList 已做)。
172
- */
173
- const PROCESS_BASENAMES = new Set(["changelog.md"])
174
-
175
167
  /**
176
168
  * 写域 basename(**模式无关**——#33 二道防线;`PROJECT-MANIFEST.json` 是项目级状态档,其写门对任何会话生效;设计 docs/core/design/MANIFEST.md §2.5 / KD-M1-14):
177
169
  * PROJECT-MANIFEST.json = M1 项目状态档——写门唯主 agent(`manifest.mjs` `writeManifest` 的
178
170
  * `writer` 闸,fail-closed);本常量 = `files` 声明面**第二道防线**(子代理无法把该路径声明为
179
171
  * 写域)。字面量(匹配前已大小写归一;**不** import `MANIFEST_REL`——保本模块「叶子·零 import」
180
- * 性质;单源指针 = `thincoder-core/manifest.mjs`)。**不入** `PROCESS_BASENAMES`:两族理由不同
181
- * ——过程档 = 父侧对账职责;本档 = 写门唯主 agent。
172
+ * 性质;单源指针 = `thincoder-core/manifest.mjs`)。本谓词唯一的一支。
182
173
  */
183
174
  const MANIFEST_BASENAME = "project-manifest.json"
184
175
 
185
176
  /**
186
- * F6 files 声明面拦截谓词(ENGINEERING-MODE-V2-MODULE-DELEGATION §2.2):过程档(父侧职责)与项目状态档
177
+ * F6 files 声明面拦截谓词(ENGINEERING-MODE-V2-MODULE-DELEGATION §2.2):项目状态档
187
178
  * → 收集全部违规后抛合并错误(fail-closed——错误即工具结果 JSON——无排队残留)。目录声明不在本谓词
188
179
  * (normalizeFileList 循环内先行拒——错误序不变)。调用点 = normalizeFileList(subagent-scheduler.mjs——
189
- * 本谓词在循环后跑——目录错误先于过程档错误)。
180
+ * 本谓词在循环后跑——目录错误先于本谓词错误)。
190
181
  * 产品面路径(含仓根 `scripts/**` · `test/**`)本就该进 `files` 声明面——工程工具面退役后不再有这一臂。
191
182
  */
192
- export function rejectProcessDocPaths(files) {
183
+ export function rejectParentOwnedPaths(files) {
193
184
  const violations = []
194
185
  for (const f of Array.isArray(files) ? files : []) {
195
186
  const segs = String(f).replace(/\\/g, "/").split("/").filter((s) => s)
196
187
  const base = (segs[segs.length - 1] ?? "").toLowerCase()
197
- if (PROCESS_BASENAMES.has(base)) {
198
- violations.push(`Parent-side maintained file ${f} must not be listed in files — reconciliation is the parent's duty; use the design-doc path if you need to edit a design doc`)
199
- } else if (base === MANIFEST_BASENAME) {
188
+ if (base === MANIFEST_BASENAME) {
200
189
  violations.push(`Manifest file ${f} must not be listed in files — PROJECT-MANIFEST.json is the project state manifest and the main agent is its only writer (M1 write gate); this files-domain check is the second line of defense`)
201
190
  }
202
191
  }
@@ -22,7 +22,7 @@
22
22
  import { createWriteStream, mkdirSync, readFileSync, writeFileSync } from "node:fs"
23
23
  import { join } from "node:path"
24
24
  import { cleanupOldToolResults } from "../agent/helpers.mjs"
25
- import { pushReal } from "../context.mjs"
25
+ import { pushInject, pushRecord } from "../context.mjs"
26
26
  import { t } from "../i18n.mjs"
27
27
  import { killProcessTree } from "../tools/process-tree.mjs"
28
28
  import {
@@ -123,10 +123,13 @@ function armIdle(entry) {
123
123
  const parent = entry.parent
124
124
  hardClose(entry, "closed", "consumed")
125
125
  if (parent?.history) {
126
- pushReal(parent, {
126
+ const msg = {
127
127
  role: "user",
128
128
  content: `[System reminder: ssh session ${idLabel(entry)} (${escapeLite(entry.host)}) was closed after ${idleS}s idle (no send/read). Open a new session if you still need it.]`,
129
- })
129
+ }
130
+ // B 段:一次性投递走待发队,持久写入只落人读线(机读线零触)。
131
+ pushInject(parent, msg)
132
+ pushRecord(parent, msg)
130
133
  }
131
134
  }, idleMs())
132
135
  entry.idleTimer.unref?.()
@@ -6,7 +6,7 @@
6
6
  * `-O`;不自动换协议重试(D-TO27:同笔重试把「协议不对」这个可诊断事实埋在两次尝试之后)。
7
7
  * - 凭据 = 与会话面**同一段判定**(`ssh-session.mjs` 的 `resolveSessionSecret`:探连 → 密文库 → 凭据窗),
8
8
  * 零新凭据通道(D-TO25);askpass 包装档 / 环境 / 失败分类族全取 `ssh-transport.mjs` 既有导出。
9
- * - 内容零入上下文(NS8):文件字节只经磁盘;回执 = 会话冠行 + 一行状态句,失败时附 stderr 尾段(≤ 600 字符)。
9
+ * - 内容零入上下文(NS8):文件字节只经磁盘;回执 = 会话冠行 + 一行状态句,失败时附 stderr 尾段(600 characters = UTF-16 code units;截断在转义之前,读到的可能更长)。
10
10
  * - 本地面(⑬ ②):本地路径展开 `~`(单源 `expand-home.mjs`)后解析成绝对路径 ⇒ `spawn` 的 `cwd` = 该档
11
11
  * 所在目录、命令行只传**档名**——Windows 盘符的 `:` 与反斜杠都不进 scp 的参数位(scp 以首个 `:`
12
12
  * 切分本地 / 远端);`get` 的父目录必须已在盘(**零建目录**:建目录即项目内一笔写,绕写门;落点也要
@@ -22,7 +22,7 @@ import {
22
22
  import { logEvent, errText } from "../log.mjs"
23
23
  import { resolveChildProvider, mergeChildMutations } from "./subagent-async.mjs"
24
24
  import { launchEscalateAsync } from "./escalate-async.mjs"
25
- // TUI-OOM-ROOTCAUSE·AGENT-LOOP.md §6.15:子代理人读线窗口常量(单源——store 零依赖)。
25
+ // TUI-OOM-ROOTCAUSE·AGENT-LOOP.md §9.2:子代理人读线窗口常量(单源——store 零依赖)。
26
26
  import { RECORD_WINDOW_MESSAGES } from "../session-store.mjs"
27
27
  // ASYNC-RESULT-CONTAINER.md D1:池 accessor(absorb 双池——advisor 独立池无队列)
28
28
  import { getAsyncPool } from "./async-settle.mjs"
@@ -170,7 +170,7 @@ export async function executeEscalateAction(args, ctx) {
170
170
  memory: parent.memory,
171
171
  role: "coder",
172
172
  })
173
- child._historyWindow = RECORD_WINDOW_MESSAGES // TUI-OOM-ROOTCAUSE·AGENT-LOOP.md §6.15:子代理人读线窗口(四处创建点同置)
173
+ child._historyWindow = RECORD_WINDOW_MESSAGES // TUI-OOM-ROOTCAUSE·AGENT-LOOP.md §9.2:子代理人读线窗口(四处创建点同置)
174
174
  child._logId = escId // LOGGING:子内事件归属(escalate#N)
175
175
  // SUBAGENT-UPSTREAM-CHANNEL(§6.27.4 W2——escalate **sync**:单向;工具返回注走同步形)。
176
176
  child._upstream = { parent, label: escId, sync: true }
@@ -18,11 +18,11 @@ import {
18
18
  MIN_REPORT_CHARS, REPORT_CONTINUATION, DEFAULT_SUBAGENT_TURNS,
19
19
  } from "../agent.mjs"
20
20
  import { runWithContinue, TURN_CAP_MARK } from "../agent/spawn-child.mjs"
21
- import { pushReal } from "../context.mjs"
21
+ import { pushInject, pushRecord } from "../context.mjs"
22
22
  import { offloadToolResult } from "../agent/helpers.mjs"
23
23
  import { logEvent } from "../log.mjs"
24
24
  import { digestBudgetOver, persistOverflowReport, _digestOffloadDirForTest } from "./digest-budget.mjs"
25
- // 群 B 批 B5(AGENT-LOOP.md §6.14 D-DG4):预算单源迁出(digest-budget.mjs)——原处 re-export 保测试
25
+ // 群 B 批 B5(AGENT-LOOP.md §9 D-DG4):预算单源迁出(digest-budget.mjs)——原处 re-export 保测试
26
26
  // 导入面零改(DIGEST_INJECT_BUDGET / _setDigestOffloadDirForTest)。
27
27
  export { DIGEST_INJECT_BUDGET, _setDigestOffloadDirForTest } from "./digest-budget.mjs"
28
28
  import {
@@ -362,7 +362,7 @@ export async function runChildPipeline(child, input, childOpts, childRunOpts, {
362
362
  }
363
363
 
364
364
  // ─── BATCH-3-STRUCTURE F-2:digest 注入批量预算(2026-09-09)───
365
- // AGENT-LOOP.md §6.14 D-DG1(群 B 批 B5):常量 / 判超 / 记账 / 落盘四处合一入 digest-budget.mjs 叶子模块
365
+ // AGENT-LOOP.md §9 D-DG1(群 B 批 B5):常量 / 判超 / 记账 / 落盘四处合一入 digest-budget.mjs 叶子模块
366
366
  // (四族共享单源——D2);本文件保留 re-export(顶部)与经本入口的三族注入器接线。
367
367
 
368
368
  /**
@@ -380,12 +380,12 @@ export async function injectAsyncResult(agent, entry) {
380
380
  // 批 browser-async-fix:后台浏览器动作族(role="browser")同式单列(摘要文法 = ack 族同源)。
381
381
  if (entry.role === "browser") return injectBrowserResult(agent, entry)
382
382
  const body = entry.error ?? entry.report ?? "(no report)"
383
- // F-2(BATCH-3-STRUCTURE)+ AGENT-LOOP.md §6.14 D-DG2(群 B 批 B5):注入前查轮累计(单源)——超限条目不
383
+ // F-2(BATCH-3-STRUCTURE)+ AGENT-LOOP.md §9 D-DG2(群 B 批 B5):注入前查轮累计(单源)——超限条目不
384
384
  // inline 全文,改清单行(全文经 persistOverflowReport 落盘——path 随行)。首条豁免
385
385
  // (used===0 不判超)。
386
386
  const raw = String(body)
387
387
  const over = digestBudgetOver(agent, raw.length)
388
- // TIMEOUT-DIGEST.md §2.2:轮累计超预算 ⇒ 清单行(正文不进请求体);否则无条件落盘——`force` 跳过
388
+ // TIMEOUT-DIGEST.md §2:轮累计超预算 ⇒ 清单行(正文不进请求体);否则无条件落盘——`force` 跳过
389
389
  // 长度门(≤64K 的报告也上盘,父回合丢了还能按路径回读);渲染二分全在 offloadToolResult。
390
390
  const preview = (over && await persistOverflowReport(raw, { tag: `async-subagent-${entry.id}` }))
391
391
  || await offloadToolResult(raw, `async-subagent-${entry.id}`, _digestOffloadDirForTest(), { force: true })
@@ -406,11 +406,14 @@ export async function injectAsyncResult(agent, entry) {
406
406
  } else {
407
407
  label = `[System reminder: async subagent #${entry.id} (${entry.role}) finished]\n${escapeXml(preview)}`
408
408
  }
409
- pushReal(agent, {
409
+ const msg = {
410
410
  role: "user",
411
411
  content: label,
412
- })
413
- // #949:评审族投递水印落点(响应表取件下界 = 投递刻下标;非评审族零写)。
412
+ }
413
+ // B 段:一次性投递走待发队,持久写入只落人读线(机读线零触)。
414
+ pushInject(agent, msg)
415
+ pushRecord(agent, msg)
416
+ // #949:评审族投递水印落点(响应表取件下界 = 投递刻线尾位置;非评审族零写)。
414
417
  if (entry.role === "advisor") noteReviewDelivered(agent, entry.run)
415
418
  // §6.9 D-SD5 终态墓碑:本函数是全部自动注入路径的共享形态(回合尾 collect + 挂起
416
419
  // digest 首行注入)——注入即消费(墓碑落注入时点——依赖满足判据不随销账后移)——容器侧:
@@ -16,9 +16,9 @@ import { existsSync, statSync } from "node:fs"
16
16
  import { logEvent } from "../log.mjs"
17
17
  // M5 F6(ENGINEERING-MODE-V2-MODULE-DELEGATION §2.3):files 声明面拦截谓词本体落
18
18
  // spawn-gates.mjs(纯谓词零依赖——本处只加 import 调用,无环)。
19
- import { rejectProcessDocPaths } from "./spawn-gates.mjs"
19
+ import { rejectParentOwnedPaths } from "./spawn-gates.mjs"
20
20
  // `files` 落点单源 = 统一解析层(`docs/core/design/PATH-RESOLUTION.md` §2.5 的「子代理 `files`(spawn 门)」行:`kind:"none"` /
21
- // `order:"near-first"` ⇒ 恒解析出、只做调度、不校验存在性)。门判(目录声明 / 过程档)
21
+ // `order:"near-first"` ⇒ 恒解析出、只做调度、不校验存在性)。门判(目录声明 / 项目状态档)
22
22
  // 仍吃**原始声明形状**——判据在转绝对之前跑,顺序零改。
23
23
  import { resolvePathTarget } from "../path-resolve.mjs"
24
24
  import { poolLimitsFor, runningPoolCount, ASYNC_POOL_LIMITS } from "./subagent-async.mjs"
@@ -45,10 +45,10 @@ import { carrierField, getAsyncPool, tombstoneOf } from "./async-settle.mjs"
45
45
  * 调用方(subagent.mjs spawn 入口)catch → 错误即工具结果(模型可见——无静默)。
46
46
  * 已知限制(评审 #4):不存在的目录声明(无尾斜杠 + 目录未创建)仍通过——不处理。
47
47
  * R26(2026-09-07):父侧维护文件黑名单——归一化后 basename 全名匹配 +
48
- * 大小写不敏感(todo.md/changelog.md 精确——路径任意层含 docs/、根、.thincoder/)——
48
+ * 大小写不敏感(路径任意层含 docs/、根、.thincoder/)——
49
49
  * 命中 → throw(fail-closed——先于调度器准入——无排队残留——错误即工具结果);
50
50
  * 提示列出全部违规条目——英文模板逐字定稿(AGENT-LOOP-SUBAGENT.md §6.9「父侧文件拦截(R26)」)。
51
- * M5 F6(2026-09-17——2026-10-15 口径随正):黑名单随同迁入 spawn-gates.mjs(族 = 过程档(CHANGELOG)+ 项目状态档(PROJECT-MANIFEST.json);老台账 md 族随 M2 退役)——本函数只留调用(错误文案逐字保留)。 */
51
+ * M5 F6(2026-09-17——2026-10-15 口径随正):黑名单随同迁入 spawn-gates.mjs(族 = 项目状态档(PROJECT-MANIFEST.json))——本函数只留调用(错误文案逐字保留)。 */
52
52
  export function normalizeFileList(files, cwd) {
53
53
  const out = []
54
54
  for (const f of Array.isArray(files) ? files : []) {
@@ -64,11 +64,11 @@ export function normalizeFileList(files, cwd) {
64
64
  }
65
65
  if (!out.includes(abs)) out.push(abs)
66
66
  }
67
- // M5 F6(ENGINEERING-MODE-V2-MODULE-DELEGATION §2.2——2026-10-15 口径随正):过程档 / 项目状态档拦截——
67
+ // M5 F6(ENGINEERING-MODE-V2-MODULE-DELEGATION §2.2——2026-10-15 口径随正):项目状态档拦截——
68
68
  // 谓词本体落 spawn-gates.mjs(收集全部违规 + 抛合并错误);
69
- // 循环内目录声明先行(错误序不变——目录错误先于过程档错误)。父侧维护文件
70
- // basename 族(CHANGELOG——`ledger.db` 随 M2 退役)随同迁入谓词——错误文案逐字保留。
71
- if (files !== undefined && files !== null) rejectProcessDocPaths(files)
69
+ // 循环内目录声明先行(错误序不变——目录错误先于谓词错误)。
70
+ // 错误文案逐字保留。
71
+ if (files !== undefined && files !== null) rejectParentOwnedPaths(files)
72
72
  return out
73
73
  }
74
74
 
@@ -151,7 +151,7 @@ export function describeBlockers(parent, entry) {
151
151
  if (info.state === "pending" || info.state === "unknown") {
152
152
  wait.push(`${info.role ?? "sub"}#${depId}(依赖未完成)`)
153
153
  } else if (info.state === "cancelled" || info.state === "failed") {
154
- if (parent.autoApprove) continue // AUTO 档自动启动(D-SD5——父不在场由 digest 决策)
154
+ if (parent.autoApprove) continue // AUTO 档自动启动(D-SD5——审批已放行:批准档决定问不问用户,与轮型无关)
155
155
  depc.push(`${info.role ?? "sub"}#${depId}`)
156
156
  }
157
157
  }
@@ -29,7 +29,7 @@ import { makeBatchHistoryTool, recordBatchHistoryStart } from "./read-history.mj
29
29
  // 判据单源 = `agent/dispatch-gates.mjs` 的 `readonlyActionOf`)。
30
30
  import { deriveReadonlyTools } from "../agent/helpers.mjs"
31
31
  import { readonlyActionTest } from "../agent/dispatch-gates.mjs"
32
- // TUI-OOM-ROOTCAUSE(AGENT-LOOP.md §6.15):子代理人读线窗口常量单源(store 零依赖)。
32
+ // TUI-OOM-ROOTCAUSE(AGENT-LOOP.md §9.2):子代理人读线窗口常量单源(store 零依赖)。
33
33
  import { RECORD_WINDOW_MESSAGES } from "../session-store.mjs"
34
34
  // 设计令牌门(七态拒句 ∥ 槽解析 ∥ 令牌判定)本体落 `./subagent-design-token.mjs`;本档只吃判定。
35
35
  import { gateDesignToken } from "./subagent-design-token.mjs"
@@ -336,7 +336,7 @@ export function buildSpawnChild(parent, ctx, args, role, wantAsync, files, depen
336
336
  overlay,
337
337
  role,
338
338
  })
339
- // TUI-OOM-ROOTCAUSE(AGENT-LOOP.md §6.15):子代理人读线窗口置位(常量单源
339
+ // TUI-OOM-ROOTCAUSE(AGENT-LOOP.md §9.2):子代理人读线窗口置位(常量单源
340
340
  // session-store.mjs)——机制复用主 agent 同路径(context.mjs pushReal 驱逐);
341
341
  // 每个 child 原先各自一份永不压缩的 _fullHistory(勘察 C2 乘数面)。
342
342
  child._historyWindow = RECORD_WINDOW_MESSAGES
@@ -108,9 +108,9 @@ export function buildSyncStoppedReport(role, capturedOutput, designId) {
108
108
  /**
109
109
  * subagent tool — ONE tool, NINE actions (AGENT-LOOP-SUBAGENT.md §6.7 +
110
110
  * SUBAGENT-OBSERVE-SEND): spawn (default) / status (non-blocking pool query) / observe
111
- * (inspect a running/queued/done async child's recent activity + current tool — docs/cli/design/TUI.md §6.8) /
111
+ * (inspect a running/queued/done async child's recent activity + current tool — AGENT-LOOP-SUBAGENT.md §2.2 observe/send) /
112
112
  * send (inject a direction into a RUNNING async child — consumed at its next turn
113
- * boundary as an ordinary instruction — §6.8) / escalate (飞刀 — hand implementation to
113
+ * boundary as an ordinary instruction — AGENT-LOOP-SUBAGENT.md §2.2 observe/send) / escalate (飞刀 — hand implementation to
114
114
  * a stronger model) / cancel (stop ONE background subagent — AGENT-LOOP-SUBAGENT.md §6.7.2) / panel (view + fix
115
115
  * the live subagent panel — AGENT-LOOP-SUBAGENT.md §6.7.2) / consume-design (parent-side chain-terminal token
116
116
  * consumption — ENGINEERING-MODE.md §2.6, 2026-09-07; selectors designId / designIds / expired /
@@ -138,7 +138,7 @@ export const subagentTool = {
138
138
  parameters: {
139
139
  type: "object",
140
140
  properties: {
141
- action: { type: "string", enum: ["spawn", "status", "escalate", "cancel", "panel", "consume-design", "observe", "send", "design-slots"], description: "Which action — spawn (default) / status / observe / send / escalate / cancel / panel / consume-design / design-slots; semantics per action in the tool description." },
141
+ action: { type: "string", enum: ["spawn", "status", "escalate", "cancel", "panel", "consume-design", "observe", "send", "design-slots"], description: "Which action to run; `spawn` is the default. Semantics per action in the tool description." },
142
142
  view: { type: "boolean", description: "action:'panel' only: true (default) = the live panel blocks as the user sees them; false without freeze = error. Mutually exclusive with freeze (freeze wins)." },
143
143
  freeze: { type: "string", description: "action:'panel' only: block key of a digested-stuck block — reclaims it into the conversation; refused for running/done/unknown blocks or a still-pending report; works on the CLI TUI panel and on the desktop renderer panel (live readback of the blocks as the user sees them)." },
144
144
  task: { type: "string", description: "For action:'spawn': non-engineering roles (explore / plan / coder / tester) — OPTIONAL free-text supplement; the brief itself is the four core parameters (goal / knownFacts / acceptance / reportFormat) + scope. Engineering roles (eng-coder / eng-designer) take NO task-book text parameters — their task book is batch record §2 (batchDoc), read by the child itself. For action:'escalate': the brief (goal, constraints, entry files, acceptance criteria)." },
@@ -183,13 +183,6 @@ export const subagentTool = {
183
183
  if ((ctx.depth ?? 0) > 0 && (ctx.agent?._role === "eng-coder" || ctx.agent?._role === "eng-designer")) {
184
184
  throw new Error(`only action:'spawn' (sync explore children) is available inside an ${ctx.agent._role} — escalate/status/cancel/panel/consume-design/design-slots/observe/send are not`)
185
185
  }
186
- // AGENT-LOOP-ASYNC-POOL.md §6.8 N3/D-S6 spawn gate (manual tier): auto-turn digests may not spawn —
187
- // async OR blocking — the digest must stay organize-only. The escalate
188
- // action spawns a write child too, so the same mechanical refusal applies
189
- // (AUTO tier exempt — user authorized unattended continuation).
190
- if (action === "escalate" && ctx.agent?._inAutoTurn && !ctx.agent?.autoApprove) {
191
- return JSON.stringify({ status: "error", error: "cannot spawn subagents from a manual auto-turn — wait for user input" })
192
- }
193
186
  if (action === "status") return executeStatusAction(args, ctx)
194
187
  if (action === "escalate") return await executeEscalateAction(args, ctx)
195
188
  // AGENT-LOOP-SUBAGENT.md §6.7.2 控制类动作:digest 内放行(D-S7 分类——控制/自省;dispatch 控制类
@@ -269,14 +262,8 @@ export const subagentTool = {
269
262
  throw new Error("Engineering mode is not active — role='eng-designer' is engineering-mode only (it writes the requirements/design documents inside the engineering workflow); use role='explore' or role='plan' for read-only work.")
270
263
  }
271
264
 
272
- // AGENT-LOOP-ASYNC-POOL.md §6.8 N3/D-S6 spawn gate (manual tier): auto-turn digests may not spawn — async
273
- // OR blocking — the digest must stay organize-only. AUTO tier (autoApprove) is
274
- // exempt (推进型 — user authorized unattended continuation). Mechanical refusal
275
- // so the digest never pops a permission panel or chains new background work.
276
- // (escalate 动作的同类拒绝在 action 分流处——本检查只管 spawn 路径。)
277
- if (parent._inAutoTurn && !parent.autoApprove) {
278
- return JSON.stringify({ status: "error", error: "cannot spawn subagents from a manual auto-turn — wait for user input" })
279
- }
265
+ // AGENT-LOOP-ASYNC-POOL.md §8.7「工具面与审批呈递不按轮型改变」:派活只受工具自身准入约束——
266
+ // `_inAutoTurn` 是显示与轨迹标记,不参与准入(两径无轮型门)。
280
267
 
281
268
  // §20 准入(2026-09-05 module-split——prepareScheduling verbatim 迁
282
269
  // subagent-spawn.mjs:参数形态/unknown id/依赖环/阻塞 sync 判定;files 目录声明
@@ -51,13 +51,6 @@ export const taskTool = {
51
51
  },
52
52
  readonly: true,
53
53
  async execute(args, ctx) {
54
- // F10(工程模式机械停用——双层门的 **execute 层兜底**;先例 = escalate `subagent-actions.mjs` 的 `executeEscalateAction`):
55
- // 前置位 = 本行以下全部副作用之前(alias 归一 / `_taskPushbacks` 归零 / `_onTaskUpdate` / 轻推)
56
- // ⇒ 零副作用(列表不变);装配层已摘(`agent/family-tools.mjs` 工程分支不入表,KD8)。
57
- // 普通模式(engineering 非真)逐字走原路径。
58
- if (ctx?.agent?.config?.agent?.engineering) {
59
- return "Error: engineering mode is ON — task is unavailable (the batch record + the ledger are the tracking authority in engineering mode). Update progress in the batch record (§5/§6) or the ledger (`/ledger`); task lists go stale in this mode's parallel structure."
60
- }
61
54
  // Keep only non-done items + the 3 most recently completed (for context reference), max 20 to prevent accumulation
62
55
  const warnings = []
63
56
  const raw = (args.items ?? []).map((it) => {
@@ -80,7 +73,6 @@ export const taskTool = {
80
73
  const recentDone = raw.filter((t) => t.status === "done").slice(-3)
81
74
  const items = [...pending, ...recentDone].slice(0, 20)
82
75
  ctx.agent.tasks = items
83
- ctx.agent._taskPushbacks = 0 // task list changed — the completion gate earns a fresh reminder
84
76
  ctx.agent._onTaskUpdate?.(items)
85
77
  if (ctx.depth === 0) pushContextNudge(ctx.agent) // F-CC4 轻推(§6.16.5——depth-0 门:子代理拿不到 context 工具)
86
78
  const done = items.filter((i) => i.status === "done").length
package/agent.mjs CHANGED
@@ -72,29 +72,31 @@ export function createAgent({
72
72
  _mutationSeq: 0, _mutLog: [], // AGENT-LOOP-ASYNC-POOL.md §6.10 D-24b: mutation log (in-flight review staleness scan)
73
73
  _lastAdvisorOutput: null, // full review output from the most recent advisor call (convergence rounds inject it verbatim)
74
74
  _lastEngState: false,
75
- _pendingReminders: [],
75
+ // 注入三段(CONTEXT-COMPACTION §1.1「注入的三段:按存活期分」):A 固定格位 ∥ B 待发队 ∥ C 累积内容。
76
+ // 三段都不落 `agent.history`——线上每条都是真的用户输入 ∥ 模型回复 ∥ 工具结果。
77
+ _inject: [], _pendingInject: [], _retained: [],
76
78
  _pendingTimers: [],
77
79
  _sessionStart: sessionStart,
78
- _lastPromptTokens: null, _usageAtLen: null,
80
+ _lastPromptTokens: null, _usageAt: null, _usageFixedBase: null,
79
81
  _tok: null, _tokRatio: 1, // §6.17 估算自校准池化比({key,num,den};采样 = turn-loop,清空 = /new)
80
82
  _compressFailures: 0,
81
83
  _emptyRetries: 0, // empty-response retry budget (per-run; reset on a fresh user turn)
82
- // §6.6 `wrote` 判据与注入帽的载体(AGENT-LOOP.md §6.6 · §6.2 resume 保留集):
84
+ // §7.1 `wrote` 判据与注入帽的载体(AGENT-LOOP.md §7.1 · §3 续跑沿用):
83
85
  // `_batchWrites` = `batch` 工具成功写盘的累计数(`onWritten` 各汇聚点自增);`_designTurnNotices` = 本链已注入的设计轮提醒条数。
84
86
  _batchWrites: 0, _designTurnNotices: 0,
85
- _runStartHistoryLen: 0, // machine-line length at the start of the current run — end-of-run exploration distillation slices from here
86
87
  _pendingDistill: null, // in-flight end-of-run exploration distillation (SEND-STALL-DISTILL §2.1) — awaited at next run start / TUI exit flush
87
88
  _currentTurn: 0, _maxTurns: DEFAULT_MAX_TURNS, // turn counter for status bar display
88
- // 跨轮机读投影(CONTEXT-COMPACTION §1.1 ∥ SESSION §2 · 台账 #2395):轮记录 ∥ 活动轮账本 ∥
89
- // 待折叠的完成轮。三件只在轮边界改写(`agent/turn-projection.mjs`),新 agent 从空账起。
90
- _turns: [], _turnLedger: null, _turnPending: null, _turnStartLen: null, _turnResponseEnd: null,
89
+ // 跨轮成形(CONTEXT-COMPACTION §1.1 ∥ SESSION §2):轮记录 ∥ 活动轮账本。
90
+ // 两者只在轮边界改写(`agent/turn-projection.mjs`),新 agent 从空账起;保留窗起点与跨轮清理
91
+ // 不另立账——轮的位置由 `agent.history` 的外层结构给出(在途轮 = 外层最后一个元素)。
92
+ _turns: [], _turnLedger: null,
91
93
  }
92
94
  }
93
95
 
94
96
  /** Run the agent loop: LLM ↔ tool-call cycle until task completion or turn limit. Returns final text content. */
95
- export async function runAgent(agent, input, callbacks = {}, { depth = 0, signal, maxTurns: overrideTurns, resume = false, autoTurn = false, upstreamTurn = false, timerTurn = false, suspDriven = false, consumeInjected = null, consumeQueuedInput = null, streamOutput = false, extraTools = null, injections = null, turnDomainText = null, distillSignal = null, toolDecorate = undefined } = {}) {
97
+ export async function runAgent(agent, input, callbacks = {}, { depth = 0, signal, maxTurns: overrideTurns, resume = false, autoTurn = false, upstreamTurn = false, timerTurn = false, suspDriven = false, consumeInjected = null, consumeQueuedInput = null, streamOutput = false, extraTools = null, injections = null, turnDomainText = null, turnOverlayText = null, distillSignal = null, toolDecorate = undefined } = {}) {
96
98
  const { maxTurns, threshold, toolSchemas, toolByName, systemPrompt } = await beginRun(agent, input, callbacks, {
97
- depth, signal, overrideTurns, resume, autoTurn, upstreamTurn, timerTurn, extraTools, injections, turnDomainText, toolDecorate,
99
+ depth, signal, overrideTurns, resume, autoTurn, upstreamTurn, timerTurn, extraTools, injections, turnDomainText, turnOverlayText, toolDecorate,
98
100
  })
99
101
 
100
102
  let thrownError = null
@@ -102,15 +104,12 @@ export async function runAgent(agent, input, callbacks = {}, { depth = 0, signal
102
104
  try {
103
105
  finalResponse = await runTurnLoop(agent, {
104
106
  maxTurns, threshold, toolSchemas, toolByName, systemPrompt,
105
- depth, signal, autoTurn, suspDriven, streamOutput, consumeInjected, consumeQueuedInput, callbacks, distillSignal,
107
+ depth, signal, autoTurn, upstreamTurn, suspDriven, streamOutput, consumeInjected, consumeQueuedInput, callbacks, distillSignal,
106
108
  })
107
- // 本轮原始机读段的终点(折叠边界):此后回合收尾注入的异步结果不属于本轮的模型过程,
108
- // 折叠时保留(下一个模型请求仍看得见它们)。
109
- agent._turnResponseEnd = agent.history.length
110
109
  return finalResponse
111
110
  } catch (e) {
112
111
  thrownError = e
113
- // 异常面只记账不登记(异常轮不折叠):原因留给同一账本(续跑沿用)。
112
+ // 异常面只记账不登记(异常轮不做跨轮清理):原因留给同一账本(续跑沿用)。
114
113
  noteTurnRunError(agent._turnLedger, e)
115
114
  throw e
116
115
  } finally {
@@ -119,7 +118,8 @@ export async function runAgent(agent, input, callbacks = {}, { depth = 0, signal
119
118
  // CLI 对位 VS run-stages——finally 只剩一行调用 + 骨架注释)。
120
119
  await finalizeAgentTurn(agent, { signal, autoTurn, upstreamTurn, timerTurn, suspDriven, thrownError, depth })
121
120
  // 正常返回 ∧ 收尾成功 ⇒ 登记完成轮(设计 §2:ContinueError / AbortError / 其它异常不登记,
122
- // 续跑沿用同一账本)。登记只置事实与折叠计划——机读线在下一轮起点(`beginRun`)才折叠。
121
+ // 续跑沿用同一账本)。登记同一笔里做两件事:置本轮事实、把窗口外最旧那一轮的工具过程从线上摘掉
122
+ // (`retireTurnToolProcess`)——下一轮起点(`beginRun`)不碰线。
123
123
  if (!thrownError) registerCompletedTurn(agent, { finalResponse })
124
124
  }
125
125
  }
package/auto-think.mjs CHANGED
@@ -16,8 +16,9 @@
16
16
  */
17
17
  import { chat } from "./provider/core.mjs"
18
18
  import { specForModel } from "./config.mjs"
19
- // #860(AGENT-LOOP.md §6.1 ∥ §7 D-AL26):off 形族的单一实现源(写面取形 + 有效 off 路径判据)
19
+ // #860(MODEL-SPECS.md §4 effort 与 off ∥ AGENT-LOOP.md §7 D-AL26):off 形族的单一实现源(写面取形 + 有效 off 路径判据)
20
20
  import { thinkOffPath, thinkOffShape } from "./think-off.mjs"
21
+ import { flattenHistory } from "./context-push.mjs"
21
22
 
22
23
  const CLASSIFY_PROMPT = `Classify this coding task's difficulty: low, medium, or high.
23
24
 
@@ -41,6 +42,8 @@ const warnedClassifyFailure = new Set()
41
42
  * Build classifier input from history: the latest real user message (reminders and
42
43
  * interrupt injections excluded), plus the previous user message as context when the
43
44
  * latest is too short to classify on its own (e.g. "继续" / "还有几个问题").
45
+ * 本函数只收一个消息数组(当场用完)——调用方传拍平视图 `flattenHistory(agent.history)`。
46
+ * 两条前缀判据留着:旧槽装回的注入仍在线上(已知边界),它们仍是真的过滤面。
44
47
  * Exported for tests.
45
48
  */
46
49
  export function buildClassifierInput(history) {
@@ -83,7 +86,7 @@ export async function classifyAndApply(agent, turn) {
83
86
  return null
84
87
  }
85
88
 
86
- const prompt = buildClassifierInput(agent.history)
89
+ const prompt = buildClassifierInput(flattenHistory(agent.history))
87
90
  if (prompt == null) return null
88
91
 
89
92
  // Classification call: use same provider, minimal tokens, no tools, no streaming