dsh-coding 0.1.1-rc1 → 0.1.1-rc2

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/lib/memory.js ADDED
@@ -0,0 +1,336 @@
1
+ /**
2
+ * 任务交接文档:把一轮 Coding 结束时的有界状态写成一篇 Markdown,落到
3
+ * `<会话 cwd>/.agents/memory/<sessionId>-<YYYYMMDD-HHmmss>.md`。
4
+ *
5
+ * 文档只由状态机与 coding_handoff 记录({@link CodingHandoff})拼出,不回读对话正文,
6
+ * 也不新增 Session 事件:它是本轮状态机与交接记录的存档快照,下一轮继续时仍以
7
+ * coding_handoff 的实时记录为准。拼装部分是纯函数({@link composeMemoryDocument}),
8
+ * 便于单测;写盘只走注入的 fs 服务(`resolve` + `writeText`),从不使用 `node:fs`。
9
+ *
10
+ * 本模块只在 Host 侧使用(依赖 `node:path`),客户端不导入它。
11
+ *
12
+ * @module dsh-coding/memory
13
+ */
14
+ import { join } from 'node:path';
15
+ /** 文档最大字符数;超出后截断到最后一个完整行。 */
16
+ export const MEMORY_LIMIT = 20000;
17
+ /** 交接文档在项目根下的目录。 */
18
+ export const MEMORY_DIR = join('.agents', 'memory');
19
+ /** 文件名里保留的 sessionId 字符;其余一律替换成 `-`。 */
20
+ const SAFE_ID = /[^A-Za-z0-9._-]/gu;
21
+ /**
22
+ * 生成一篇交接文档的文件名:`<清洗后的 sessionId>-<YYYYMMDD-HHmmss>.md`。
23
+ *
24
+ * sessionId 只保留 `[A-Za-z0-9._-]`,其余字符换成 `-`,清洗后为空则退回 `session`;
25
+ * 时间戳取 UTC,非法 `at` 按 epoch 处理而不抛错。
26
+ * @param sessionId - 会话 id。
27
+ * @param at - 时间戳(毫秒)。
28
+ * @returns 文件名,不含目录。
29
+ */
30
+ export function memoryFileName(sessionId, at) {
31
+ const cleaned = sessionId.replace(SAFE_ID, '-');
32
+ const stem = cleaned === '' ? 'session' : cleaned;
33
+ return `${stem}-${utcStamp(at)}.md`;
34
+ }
35
+ /**
36
+ * 组装整篇交接文档。
37
+ *
38
+ * 纯字符串拼接:不读文件、不取时钟(时间来自 {@link MemoryInput.now}),因此可以直接单测。
39
+ * 空数组与缺失字段对应的整节省略,不输出「无」。
40
+ * @param input - 状态机与 handoff 的有界快照。
41
+ * @returns 文档正文,超过 {@link MEMORY_LIMIT} 时截断并标注。
42
+ */
43
+ export function composeMemoryDocument(input) {
44
+ const handoff = input.handoff;
45
+ const cwd = textOf(input.cwd);
46
+ const lines = [
47
+ '# Coding 任务交接文档',
48
+ '',
49
+ `- 会话: ${input.sessionId}`,
50
+ `- 生成时间: ${isoStamp(input.now)}(UTC)`,
51
+ `- 工作目录: ${cwd === '' ? '(unknown)' : cwd}`,
52
+ `- 模式 / 阶段: ${input.mode} / ${input.stage}`,
53
+ `- 轮次: turn ${input.turn}`,
54
+ `- 状态: ${input.blocked ? '阻塞交付(BLOCKED)' : '正常交付'}`,
55
+ ];
56
+ pushText(lines, '目标', handoff?.goal);
57
+ pushList(lines, '约束', handoff?.constraints ?? []);
58
+ pushList(lines, '验收标准', handoff?.acceptance ?? []);
59
+ pushText(lines, '交付记录', handoff?.delivered);
60
+ pushList(lines, '后续跟进', handoff?.followUps ?? []);
61
+ pushList(lines, '决策', handoff?.decisions ?? []);
62
+ pushList(lines, '发现', handoff?.findings ?? []);
63
+ pushList(lines, '待答问题', handoff?.open ?? []);
64
+ pushPlan(lines, input.plan);
65
+ pushTasks(lines, handoff?.tasks ?? []);
66
+ pushChanges(lines, handoff?.changes ?? []);
67
+ pushUnlisted(lines, input.files, handoff?.changes ?? []);
68
+ pushVerification(lines, input.verification);
69
+ pushTransitions(lines, input.transitions);
70
+ pushNextRound(lines);
71
+ return truncateDocument(lines.join('\n'));
72
+ }
73
+ /**
74
+ * 写出本轮的任务交接文档,返回一条可回报给用户的收据。
75
+ *
76
+ * 写盘只走注入的 fs 服务:`resolve` 解析 `.agents/memory` 下的目标,`writeText` 以
77
+ * `createIfAbsent` 语义写入,因此重复点击生成新文件而不覆盖旧文档;目录缺失由 Host 的
78
+ * 原子写入自动创建。任何一步抛错都收成 `{ ok:false, … }` 收据,绝不外泄异常。
79
+ * @param ctx - 插件作用域。
80
+ * @param agent - 触发写入的 lead agent(`agent.ctx` 的作用域优先级更高)。
81
+ * @param state - 本轮结束时的状态机快照。
82
+ * @param options - 取消信号。
83
+ * @returns 成功时给出文件名与展示路径,失败时给出原因与处理办法。
84
+ */
85
+ export async function writeMemoryDocument(ctx, agent, state, options) {
86
+ const signal = options?.signal;
87
+ try {
88
+ const fs = serviceOf(agent?.ctx, ctx, 'fs');
89
+ if (fs === undefined) {
90
+ return {
91
+ ok: false,
92
+ reason: 'this Host does not expose the fs service',
93
+ action: 'keep the Coding preset mounted in a DSH host that provides the filesystem service, '
94
+ + 'then retry /coding memory',
95
+ };
96
+ }
97
+ const cwd = agent?.session?.header?.cwd;
98
+ if (typeof cwd !== 'string' || cwd === '') {
99
+ return {
100
+ ok: false,
101
+ reason: 'the session has no working directory',
102
+ action: 'set a working directory for this session, then retry /coding memory',
103
+ };
104
+ }
105
+ const policy = await sandboxPolicyOf(agent?.ctx, ctx, agent);
106
+ const now = Date.now();
107
+ const name = memoryFileName(state.sessionId, now);
108
+ const display = join(MEMORY_DIR, name);
109
+ const target = await fs.resolve(display, { cwd, signal });
110
+ await fs.writeText(target, composeMemoryDocument({
111
+ sessionId: state.sessionId,
112
+ cwd,
113
+ mode: state.mode,
114
+ stage: state.stage,
115
+ turn: state.turn,
116
+ blocked: state.deliveryBlocked === true,
117
+ ...(state.handoff === undefined ? {} : { handoff: state.handoff }),
118
+ plan: state.plan?.items ?? [],
119
+ ...(state.verification === undefined ? {} : { verification: state.verification }),
120
+ files: [...state.files].sort(),
121
+ transitions: state.transitions,
122
+ now,
123
+ }), { kind: 'createIfAbsent' }, signal, policy);
124
+ const shown = target?.displayPath;
125
+ return {
126
+ ok: true,
127
+ name,
128
+ displayPath: typeof shown === 'string' && shown !== '' ? shown : display,
129
+ };
130
+ }
131
+ catch (error) {
132
+ const raw = (error instanceof Error ? error.message : String(error)).trim();
133
+ return {
134
+ ok: false,
135
+ reason: (raw === '' ? 'unknown error' : raw).slice(0, 600),
136
+ action: 'fix the reported filesystem problem, then retry /coding memory',
137
+ };
138
+ }
139
+ }
140
+ /**
141
+ * 依次在 agent 作用域与插件作用域里找一个宿主服务。
142
+ * agent 作用域在上:预设子作用域看到的服务比插件作用域更全。
143
+ * @param primary - 优先作用域(通常是 `agent?.ctx`)。
144
+ * @param fallback - 兜底作用域(插件 ctx)。
145
+ * @param name - 服务名。
146
+ * @returns 找到的服务,或 undefined。
147
+ */
148
+ function serviceOf(primary, fallback, name) {
149
+ for (const scope of [primary, fallback]) {
150
+ if (scope === undefined || scope === null)
151
+ continue;
152
+ try {
153
+ const service = scope.get?.(name) ?? scope[name];
154
+ if (service !== undefined)
155
+ return service;
156
+ }
157
+ catch {
158
+ // 这个作用域读不到,换下一个。
159
+ }
160
+ }
161
+ return undefined;
162
+ }
163
+ /**
164
+ * 解析沙箱策略。沙箱是可选服务:没有它的宿主照常写盘,解析失败一律当作「没有策略」。
165
+ * @param primary - 优先作用域(通常是 `agent?.ctx`)。
166
+ * @param fallback - 兜底作用域(插件 ctx)。
167
+ * @param agent - 触发写入的 lead agent。
168
+ * @returns 策略值,或 undefined。
169
+ */
170
+ async function sandboxPolicyOf(primary, fallback, agent) {
171
+ const service = serviceOf(primary, fallback, 'sandboxPolicy');
172
+ if (typeof service?.resolve !== 'function')
173
+ return undefined;
174
+ try {
175
+ return await service.resolve(agent === undefined ? {} : { session: agent.session });
176
+ }
177
+ catch {
178
+ return undefined;
179
+ }
180
+ }
181
+ /** UTC 时间戳,格式 `YYYYMMDD-HHmmss`;非法数值按 epoch 处理。 */
182
+ function utcStamp(at) {
183
+ const iso = new Date(Number.isFinite(at) ? at : 0).toISOString();
184
+ return `${iso.slice(0, 10).replace(/-/gu, '')}-${iso.slice(11, 19).replace(/:/gu, '')}`;
185
+ }
186
+ /** 头部时间戳,ISO 8601(UTC);非法数值按 epoch 处理。 */
187
+ function isoStamp(at) {
188
+ return new Date(Number.isFinite(at) ? at : 0).toISOString();
189
+ }
190
+ /** 把一个值修剪成单段文本;非字符串与空白读作空串。 */
191
+ function textOf(value) {
192
+ return typeof value === 'string' ? value.trim() : '';
193
+ }
194
+ /** 一组列表项:修剪、去空、去重(保序)。 */
195
+ function cleanItems(values) {
196
+ const items = [];
197
+ for (const value of values) {
198
+ const item = textOf(value);
199
+ if (item !== '' && !items.includes(item))
200
+ items.push(item);
201
+ }
202
+ return items;
203
+ }
204
+ /** 任务清单的状态标记:`[x]` 已完成、`[~]` 进行中、`[ ]` 待办。 */
205
+ function markOf(status) {
206
+ if (status === 'completed')
207
+ return '[x]';
208
+ if (status === 'in_progress')
209
+ return '[~]';
210
+ return '[ ]';
211
+ }
212
+ /** 追加一个多行文本章节;空内容整节省略,不写「无」。 */
213
+ function pushText(lines, title, body) {
214
+ const value = textOf(body);
215
+ if (value === '')
216
+ return;
217
+ lines.push('', `## ${title}`, value);
218
+ }
219
+ /** 追加一个列表章节;空列表整节省略。 */
220
+ function pushList(lines, title, values) {
221
+ const items = cleanItems(values);
222
+ if (items.length === 0)
223
+ return;
224
+ lines.push('', `## ${title}`, ...items.map(item => `- ${item}`));
225
+ }
226
+ /** 追加任务清单(来自 `todo_write` 的 plan 快照)。 */
227
+ function pushPlan(lines, plan) {
228
+ const rows = [];
229
+ for (const item of plan) {
230
+ const content = textOf(item.content);
231
+ if (content === '')
232
+ continue;
233
+ rows.push(`- ${markOf(item.status)} ${content}`);
234
+ }
235
+ if (rows.length === 0)
236
+ return;
237
+ lines.push('', '## 任务清单', ...rows);
238
+ }
239
+ /** 追加 planner 交接任务:目标、涉及文件、验收标准与避让说明。 */
240
+ function pushTasks(lines, tasks) {
241
+ const rows = [];
242
+ for (const task of tasks) {
243
+ const goal = textOf(task.goal);
244
+ if (goal === '')
245
+ continue;
246
+ const files = cleanItems(task.files);
247
+ const done = textOf(task.acceptance);
248
+ const avoid = textOf(task.avoid);
249
+ rows.push(`- ${goal} — files: ${files.length === 0 ? '(none)' : files.join(', ')}`
250
+ + `;done: ${done === '' ? '(none)' : done}`
251
+ + (avoid === '' ? '' : `;avoid: ${avoid}`));
252
+ }
253
+ if (rows.length === 0)
254
+ return;
255
+ lines.push('', '## 交接任务(planner)', ...rows);
256
+ }
257
+ /** 追加改动文件:每条 `- <path> — <summary>`,空摘要只留路径。 */
258
+ function pushChanges(lines, changes) {
259
+ const rows = [];
260
+ for (const change of changes) {
261
+ const file = textOf(change.file);
262
+ if (file === '')
263
+ continue;
264
+ const summary = textOf(change.summary);
265
+ rows.push(summary === '' ? `- ${file}` : `- ${file} — ${summary}`);
266
+ }
267
+ if (rows.length === 0)
268
+ return;
269
+ lines.push('', '## 改动文件', ...rows);
270
+ }
271
+ /** 追加未并表路径:implement worker 报过的文件里,handoff 的 changes 没覆盖到的部分。 */
272
+ function pushUnlisted(lines, files, changes) {
273
+ const listed = new Set();
274
+ for (const change of changes) {
275
+ const file = textOf(change.file);
276
+ if (file !== '')
277
+ listed.add(file);
278
+ }
279
+ const rows = [];
280
+ for (const file of files) {
281
+ const path = textOf(file);
282
+ if (path === '' || listed.has(path))
283
+ continue;
284
+ rows.push(`- ${path}`);
285
+ }
286
+ if (rows.length === 0)
287
+ return;
288
+ lines.push('', '## 未并表的改动路径', ...rows);
289
+ }
290
+ /** 追加验证结果:结论、类型/范围、命令、退出码、耗时,以及失败测试与错误。 */
291
+ function pushVerification(lines, outcome) {
292
+ if (outcome === undefined)
293
+ return;
294
+ const section = [
295
+ '',
296
+ '## 验证',
297
+ `- 结果: ${outcome.passed ? 'passed' : 'FAILED'}`,
298
+ `- 类型 / 范围: ${outcome.kind} / ${outcome.scope}`,
299
+ `- 命令: \`${outcome.command}\``,
300
+ `- 退出码: ${outcome.exitCode === null ? '(none)' : outcome.exitCode}`,
301
+ `- 耗时: ${outcome.durationMs}ms`,
302
+ ];
303
+ const failed = cleanItems(outcome.failedTests);
304
+ if (failed.length > 0)
305
+ section.push(`- 失败测试: ${failed.join(', ')}`);
306
+ for (const error of cleanItems(outcome.errors))
307
+ section.push(`- 错误: ${error}`);
308
+ lines.push(...section);
309
+ }
310
+ /** 追加阶段轨迹:每条 `- <from> → <to>(<reason>)`,无原因时省略括号。 */
311
+ function pushTransitions(lines, transitions) {
312
+ const rows = [];
313
+ for (const transition of transitions) {
314
+ const from = textOf(transition.from);
315
+ const to = textOf(transition.to);
316
+ if (from === '' || to === '')
317
+ continue;
318
+ const reason = textOf(transition.reason);
319
+ rows.push(reason === '' ? `- ${from} → ${to}` : `- ${from} → ${to}(${reason})`);
320
+ }
321
+ if (rows.length === 0)
322
+ return;
323
+ lines.push('', '## 阶段轨迹', ...rows);
324
+ }
325
+ /** 固定尾节:说明这份文档与 coding_handoff 实时记录的关系,以及续接顺序。 */
326
+ function pushNextRound(lines) {
327
+ lines.push('', '## 下一轮怎么接', '- 这份文档是本轮状态机与 coding_handoff 记录的存档快照;下一轮继续时以 coding_handoff 的实时记录为准。', '- 续接轮请先读「目标 / 验收标准 / 交付记录 / 后续跟进」四节,再决定是否重做上一轮。');
328
+ }
329
+ /** 截断到 {@link MEMORY_LIMIT}:优先切在最后一个完整行,并标注文档已截断。 */
330
+ function truncateDocument(text) {
331
+ if (text.length <= MEMORY_LIMIT)
332
+ return text;
333
+ const cut = text.slice(0, MEMORY_LIMIT);
334
+ const lastBreak = cut.lastIndexOf('\n');
335
+ return `${lastBreak > 0 ? cut.slice(0, lastBreak) : cut}\n…(文档已截断)`;
336
+ }
package/lib/preset.js CHANGED
@@ -19,11 +19,12 @@
19
19
  import { defineTool } from '@deepseek-ai/dsh-tools';
20
20
  import { ReasoningController } from './reasoning.js';
21
21
  import { reasoningProjection } from './reasoning-projection.js';
22
+ import { writeMemoryDocument } from './memory.js';
22
23
  import { controlMessage, stageMessage } from './messages.js';
23
24
  import { failureNotice, makeFailure } from './failures.js';
24
25
  import { assertWorkerModel, describeProviders, resolveWorkerRoute, workerPreset, WORKER_ROLES, } from './models.js';
25
26
  import { handoffDigest, handoffForWorker, mergeHandoff, } from './handoff.js';
26
- import { CODING_MODES, CODING_STAGES, TOOL, asCheckpoint, stagePath, toolClass, } from './stages.js';
27
+ import { CODING_MODES, CODING_STAGES, TOOL, WORKER_PRESETS, asCheckpoint, needsWorkspaceInstructions, stagePath, toolClass, } from './stages.js';
27
28
  import { CodingStateStore, applyMode, applyStage, checkAdvance, checkTool, checkpointOf, clearFailure, clearRefusal, isLeadAgent, recordFailure, recordRefusal, recordVerification, resetVerification, restoreFromView, sessionIdOf, statusLine, tableTrim, takeFailureNotice, takeLastRefusal, } from './state.js';
28
29
  import { stageContext } from './contract.js';
29
30
  import { registerVerificationTool } from './verification-tool.js';
@@ -214,6 +215,7 @@ function implementPrompt(task, files, acceptance, state) {
214
215
  return [
215
216
  'You are the implement worker of the DSH Coding runtime. You have a fresh context: this task is complete on its own.',
216
217
  'Rules:',
218
+ '- The repository instructions (AGENTS.md) are already injected into this session: follow them; do not read the file again.',
217
219
  '- Read a file before editing it. Prefer apply_patch for multi-file or multi-hunk changes; use edit for one literal replacement and write for a new file.',
218
220
  '- Change only what the task needs: no drive-by refactor, no unrelated reformatting, no new dependency.',
219
221
  '- `acceptance` is the standard this change is measured against: satisfy it. Do not edit files outside the handoff.',
@@ -229,10 +231,13 @@ function implementPrompt(task, files, acceptance, state) {
229
231
  ].join('\n');
230
232
  }
231
233
  /** Verify-worker prompt: read-only investigation of one check. */
232
- function verifyPrompt(task, state) {
234
+ function verifyPrompt(task, state, withInstructions = false) {
233
235
  return [
234
236
  'You are the verify worker of the DSH Coding runtime. You cannot edit files; you run checks and report evidence.',
235
237
  'Rules:',
238
+ ...withInstructions
239
+ ? ['- The repository instructions (AGENTS.md) are already injected into this session: follow them; do not read the file again.']
240
+ : [],
236
241
  '- Use run_verification to execute a check; inspect the failing output it returns.',
237
242
  '- Report findings with file:line and a reproducible scenario, ordered by impact.',
238
243
  '- Report the command you actually ran, and put every conclusion about the acceptance criteria into findings.',
@@ -273,6 +278,27 @@ function plannerPrompt(task, state) {
273
278
  export async function apply(ctx) {
274
279
  const settings = ctx.dshCodingRuntime;
275
280
  const config = () => settings.options;
281
+ /**
282
+ * 主 Agent 自身是否就是配置的 planner 路由:这时 planner worker 是多余的,
283
+ * 门禁直接放行。读不到模型选择时按“不是”处理,门禁照常生效。
284
+ */
285
+ const leadIsPlanner = (agent) => {
286
+ try {
287
+ const current = agent?.model?.current?.();
288
+ if (typeof current?.provider !== 'string' || typeof current?.model !== 'string')
289
+ return false;
290
+ const route = resolveWorkerRoute(config(), 'plan');
291
+ return current.provider === route.provider && current.model === route.model;
292
+ }
293
+ catch {
294
+ return false;
295
+ }
296
+ };
297
+ /** 门禁需要的运行时事实:主 Agent 的路由,以及 `requirePlanner` 开关。 */
298
+ const advanceOptions = (agent) => ({
299
+ leadIsPlanner: leadIsPlanner(agent),
300
+ plannerGate: config().requirePlanner !== 'off',
301
+ });
276
302
  const store = new CodingStateStore(config);
277
303
  /** Current conversation language, used for the user-facing failure notice. */
278
304
  const currentLanguage = () => resolveHostLanguage({
@@ -674,7 +700,7 @@ export async function apply(ctx) {
674
700
  checkpoint: checkpointOf(state),
675
701
  };
676
702
  }
677
- const check = checkAdvance(state, args.stage);
703
+ const check = checkAdvance(state, args.stage, advanceOptions(exec.agent));
678
704
  if (!check.ok) {
679
705
  const reason = check.reason ?? 'the stage gate refused this move';
680
706
  // Auto's workflow choice is a decision, not a skipped gate: report it
@@ -853,6 +879,8 @@ export async function apply(ctx) {
853
879
  'decisions and the acceptance checks. Any stage may add findings and open questions as evidence.',
854
880
  '`goal` replaces the recorded goal; every list field appends (de-duplicated, capped by the plugin).',
855
881
  'Record only what this stage adds or corrects; there is no need to repeat the whole history.',
882
+ 'In deliver write the delivery record back first (`delivered` / `followUps`): the next turn and a',
883
+ 'resumed session read that record, not this turn\'s message.',
856
884
  ].join(' '),
857
885
  parameters: {
858
886
  goal: {
@@ -884,6 +912,16 @@ export async function apply(ctx) {
884
912
  items: { type: 'string' },
885
913
  description: 'Questions still unanswered; appended.',
886
914
  },
915
+ delivered: {
916
+ type: 'string',
917
+ description: '一条紧凑的交付记录:交付了什么、改了哪些文件、跑了哪个检查;覆盖已记录的交付。'
918
+ + '在 deliver 阶段写入,下一轮对话与重开会话都读它。',
919
+ },
920
+ followUps: {
921
+ type: 'array',
922
+ items: { type: 'string' },
923
+ description: '残余风险或后续跟进项;追加。',
924
+ },
887
925
  reset: {
888
926
  type: 'boolean',
889
927
  description: 'Reset the verification retry budget; the handoff itself is kept.',
@@ -923,6 +961,8 @@ export async function apply(ctx) {
923
961
  const findings = list(args?.findings);
924
962
  const decisions = list(args?.decisions);
925
963
  const open = list(args?.open);
964
+ const delivered = typeof args?.delivered === 'string' ? args.delivered : undefined;
965
+ const followUps = list(args?.followUps);
926
966
  const patch = {
927
967
  ...goal === undefined ? {} : { goal },
928
968
  ...constraints === undefined ? {} : { constraints },
@@ -930,6 +970,8 @@ export async function apply(ctx) {
930
970
  ...findings === undefined ? {} : { findings },
931
971
  ...decisions === undefined ? {} : { decisions },
932
972
  ...open === undefined ? {} : { open },
973
+ ...delivered === undefined ? {} : { delivered },
974
+ ...followUps === undefined ? {} : { followUps },
933
975
  };
934
976
  if (Object.keys(patch).length > 0) {
935
977
  try {
@@ -989,6 +1031,10 @@ export async function apply(ctx) {
989
1031
  // still in flight, or both calls pass the guard and race for the result.
990
1032
  state.worker = { role, status: 'running', startedAt };
991
1033
  state.updatedAt = startedAt;
1034
+ // planner 尝试一进入就记为失败:worker 路由不可用时门禁仍然打开,避免一次
1035
+ // 失败的派发锁死整个 codex 流程;派发结束再按实际结果改写。
1036
+ if (role === 'plan')
1037
+ state.planner = { route: route.text, outcome: 'failed', at: startedAt };
992
1038
  try {
993
1039
  await assertWorkerModel(ctx, route, exec.signal);
994
1040
  }
@@ -999,18 +1045,23 @@ export async function apply(ctx) {
999
1045
  state.updatedAt = Date.now();
1000
1046
  throw new Error(`${text} Fix the route and call delegate_${role} again; retrying the same route will fail identically.`);
1001
1047
  }
1048
+ // verify 只有在 codex 且任务复杂时才值得付出整份 AGENTS.md 的上下文:
1049
+ // 多子任务意味着跨任务依赖,改动面大意味着需要仓库规则。
1050
+ const taskCount = Math.max(state.handoff?.tasks.length ?? 0, state.plan?.items.length ?? 0);
1051
+ const withInstructions = role === 'verify'
1052
+ && needsWorkspaceInstructions({ mode: state.mode, taskCount, changedFiles: state.files.size });
1002
1053
  let started;
1003
1054
  try {
1004
1055
  started = await ctx.subagents.startActivation({
1005
1056
  provider: 'spawn',
1006
- agentPreset: workerPreset(role),
1057
+ agentPreset: withInstructions ? WORKER_PRESETS.verifyWithInstructions : workerPreset(role),
1007
1058
  name: workerName,
1008
1059
  label: workerLabel(role, task),
1009
1060
  prompt: [{
1010
1061
  type: 'text',
1011
1062
  text: role === 'plan'
1012
1063
  ? plannerPrompt(task, state)
1013
- : role === 'implement' ? implementPrompt(task, files, args.acceptance, state) : verifyPrompt(task, state),
1064
+ : role === 'implement' ? implementPrompt(task, files, args.acceptance, state) : verifyPrompt(task, state, withInstructions),
1014
1065
  }],
1015
1066
  parent: exec.agent,
1016
1067
  signal: exec.signal,
@@ -1051,6 +1102,9 @@ export async function apply(ctx) {
1051
1102
  : { summary: report.summary, ...report.files.length === 0 ? {} : { files: report.files } },
1052
1103
  };
1053
1104
  state.updatedAt = Date.now();
1105
+ if (role === 'plan') {
1106
+ state.planner = { route: route.text, outcome: ok ? 'completed' : 'failed', at: state.updatedAt };
1107
+ }
1054
1108
  // The dispatch is the failure point either way: a worker that ran but did
1055
1109
  // not complete is the same interruption, and a completed one clears it.
1056
1110
  if (ok)
@@ -1328,7 +1382,7 @@ export async function apply(ctx) {
1328
1382
  // ── Control channel for the UI and the user ──────────────────────────────
1329
1383
  // The body is extracted so an exception becomes a reported failure with a
1330
1384
  // next move: `/coding` is the operator's own recovery path.
1331
- const handleCodingCommand = ({ agent, rawInput }) => {
1385
+ const handleCodingCommand = async ({ agent, rawInput, signal }) => {
1332
1386
  const state = stateOf(agent);
1333
1387
  if (state === undefined) {
1334
1388
  return { kind: 'error', text: 'this session is not running the dsh-coding preset' };
@@ -1343,12 +1397,22 @@ export async function apply(ctx) {
1343
1397
  resetVerification(state);
1344
1398
  return { kind: 'success', text: `verification retry budget reset; ${statusLine(state)}` };
1345
1399
  }
1400
+ if (text === 'memory') {
1401
+ // 交接文档由 Host 写盘:浏览器半只发这一行命令,不直接写文件。
1402
+ const written = await writeMemoryDocument(ctx, agent, state, { signal });
1403
+ if (!written.ok)
1404
+ return { kind: 'error', text: `${written.reason} — ${written.action}` };
1405
+ return {
1406
+ kind: 'success',
1407
+ text: `handoff document written: ${written.displayPath} (session ${state.sessionId})`,
1408
+ };
1409
+ }
1346
1410
  if (text.startsWith('stage')) {
1347
1411
  const target = text.slice('stage'.length).trim();
1348
1412
  if (!CODING_STAGES.includes(target)) {
1349
1413
  return { kind: 'error', text: `unknown stage "${target}"; use ${CODING_STAGES.join(', ')}` };
1350
1414
  }
1351
- const check = checkAdvance(state, target);
1415
+ const check = checkAdvance(state, target, advanceOptions(agent));
1352
1416
  if (!check.ok) {
1353
1417
  // A user-issued move reports the gate but never arms the
1354
1418
  // step-blocking refusal meant for a model that tried to skip it.
@@ -1393,11 +1457,11 @@ export async function apply(ctx) {
1393
1457
  ctx.inject(['commands'], (child) => {
1394
1458
  child.commands.register({
1395
1459
  name: 'coding',
1396
- description: 'Show or set this session\'s Coding mode or stage: /coding <auto|consult|review|codex>, /coding set <mode> (silent, no Turn), or /coding stage <name>.',
1397
- input: { hint: 'auto | consult | review | codex | set <auto|consult|review|codex> | stage <requirements|plan|implement|verify|deliver> | reset' },
1398
- handler: (payload) => {
1460
+ description: 'Show or set this session\'s Coding mode or stage: /coding <auto|consult|review|codex>, /coding set <mode> (silent, no Turn), or /coding stage <name>. /coding memory writes a handoff document for this turn under .agents/memory at the project root.',
1461
+ input: { hint: 'auto | consult | review | codex | set <auto|consult|review|codex> | stage <requirements|plan|implement|verify|deliver> | reset | memory' },
1462
+ handler: async (payload) => {
1399
1463
  try {
1400
- return handleCodingCommand(payload);
1464
+ return await handleCodingCommand(payload);
1401
1465
  }
1402
1466
  catch (error) {
1403
1467
  const state = stateOf(payload.agent);
package/lib/stages.js CHANGED
@@ -98,13 +98,14 @@ const STAGE_CLASSES = {
98
98
  requirements: ['read', 'exec', 'stage', 'mode', 'reasoning'],
99
99
  // Planning may inspect and must author the structured task list.
100
100
  plan: ['read', 'exec', 'plan', 'delegate', 'stage', 'mode', 'reasoning'],
101
- // Implementation is delegated: the lead keeps only the task list and the verbs.
102
- implement: ['delegate', 'plan', 'stage', 'mode', 'reasoning'],
103
- // Verification is read + a structured check; delegation stays available, and
104
- // the task list must be closable so a finished check does not stay running.
105
- verify: ['read', 'verify', 'plan', 'stage', 'mode', 'reasoning'],
106
- // Delivery reports and closes the task list; nothing may mutate source or
107
- // start a fresh verification.
101
+ // Implementation is delegated: the lead keeps the task list, the shell it needs
102
+ // for installs and one-off commands, and the verbs. Editing stays the worker's.
103
+ implement: ['delegate', 'plan', 'exec', 'stage', 'mode', 'reasoning'],
104
+ // Verification is read + a structured check, plus ad-hoc commands to reproduce a
105
+ // failure; delegation stays available and the task list must be closable.
106
+ verify: ['read', 'verify', 'exec', 'plan', 'stage', 'mode', 'reasoning'],
107
+ // Delivery reports and closes the task list; nothing may mutate source, run a
108
+ // command, or start a fresh verification.
108
109
  deliver: ['read', 'plan', 'stage', 'mode', 'reasoning'],
109
110
  };
110
111
  /** Whether `stage` admits the tool class `kind`. */
@@ -119,11 +120,16 @@ export function stageAdmissions(stage) {
119
120
  * The lead's tool table during `implement`: exactly these names remain visible.
120
121
  * Naming the allow-list (rather than denying individual tools) is what makes the
121
122
  * trim total, including tools a later plugin registers.
123
+ * `bash` and `pwsh` are both listed because only one exists per platform;
124
+ * `syncTable` drops the absent one, since `tools.restrict` rejects names the
125
+ * scope does not register.
122
126
  */
123
127
  export const IMPLEMENT_TABLE = [
124
128
  TOOL.implement,
125
129
  TOOL.handoff,
126
130
  'todo_write',
131
+ 'bash',
132
+ 'pwsh',
127
133
  TOOL.stage,
128
134
  TOOL.mode,
129
135
  TOOL.reasoning,
@@ -133,7 +139,22 @@ export const WORKER_PRESETS = {
133
139
  planner: 'dsh-coding-planner',
134
140
  implement: 'dsh-coding-implement',
135
141
  verify: 'dsh-coding-verify',
142
+ verifyWithInstructions: 'dsh-coding-verify-instructions',
136
143
  };
144
+ /** 触发 verify 注入仓库指令的最小子任务数:多个子任务意味着跨任务依赖。 */
145
+ export const VERIFY_INSTRUCTION_TASK_THRESHOLD = 2;
146
+ /** 触发 verify 注入仓库指令的最小改动文件数:改动面大时需要仓库规则。 */
147
+ export const VERIFY_INSTRUCTION_FILE_THRESHOLD = 3;
148
+ /**
149
+ * verify 是否应加载仓库指令:仅 codex 模式,且(多子任务)或(改动文件多)。
150
+ * 单任务单文件的核查不注入,避免为一次检查付出整份 AGENTS.md 的上下文。
151
+ */
152
+ export function needsWorkspaceInstructions(demand) {
153
+ if (demand.mode !== 'codex')
154
+ return false;
155
+ return demand.taskCount >= VERIFY_INSTRUCTION_TASK_THRESHOLD
156
+ || demand.changedFiles >= VERIFY_INSTRUCTION_FILE_THRESHOLD;
157
+ }
137
158
  /** The stable route identity a session's coding run is checkpointed under. */
138
159
  export const CHECKPOINT_VERSION = 1;
139
160
  /**
@@ -187,6 +208,10 @@ export function asCheckpoint(value) {
187
208
  const verifyBlocked = asVerifyBlocked(blockedValue);
188
209
  if (blockedValue !== undefined && verifyBlocked === undefined)
189
210
  return undefined;
211
+ const plannerValue = v['planner'];
212
+ const planner = asPlanner(plannerValue);
213
+ if (plannerValue !== undefined && planner === undefined)
214
+ return undefined;
190
215
  return {
191
216
  v: CHECKPOINT_VERSION,
192
217
  runId: v['runId'],
@@ -204,6 +229,7 @@ export function asCheckpoint(value) {
204
229
  ...verifyAttempts === undefined ? {} : { verifyAttempts },
205
230
  ...verifyBlocked === undefined ? {} : { verifyBlocked },
206
231
  ...worker === undefined ? {} : { worker },
232
+ ...planner === undefined ? {} : { planner },
207
233
  ...refusal === undefined ? {} : { refusal },
208
234
  ...failure === undefined ? {} : { failure },
209
235
  updatedAt: v['updatedAt'],
@@ -284,6 +310,18 @@ function asWorker(value) {
284
310
  ...isFiniteNumber(v['finishedAt']) ? { finishedAt: v['finishedAt'] } : {},
285
311
  };
286
312
  }
313
+ function asPlanner(value) {
314
+ if (typeof value !== 'object' || value === null)
315
+ return undefined;
316
+ const v = value;
317
+ if (typeof v['route'] !== 'string' || v['route'] === '')
318
+ return undefined;
319
+ if (v['outcome'] !== 'completed' && v['outcome'] !== 'failed')
320
+ return undefined;
321
+ if (!isFiniteNumber(v['at']))
322
+ return undefined;
323
+ return { route: v['route'], outcome: v['outcome'], at: v['at'] };
324
+ }
287
325
  function asRefusal(value) {
288
326
  if (typeof value !== 'object' || value === null)
289
327
  return undefined;