SLOPSHOPPER

system1

用 System One 模型(目前 TypeSafe Jev)做判斷的 hook:派 sub-agent 前選 model;grilling 收尾拆題成 context/specs 規格檔(需 TYPESAFE_API_KEY,停用 plugin 即關閉)

guardstatusprompttoolprocessnetwork
v0.4.1MITupdated 2026-10-24cch-agent/claude-mods/system1
A shopper browsing a rack in a slop shop
README

cch

Claude Code mods(hooks plugins)。

  • grill-choices:/grill-with-docs 的提問改成 AskUserQuestion 選擇題,可自行輸入。
  • action-chips:每次回覆後在輸入框上方排出小框框——回覆中的檔案與網址點了開啟(可執行檔只在 Finder 顯示)、指令點了複製;標籤由 haiku 寫成「這是什麼」(如 web demo、部署指令),依回覆順序由左至右、過長換行。
  • system1:hook,派 sub-agent(Agent 工具)前用 System One 模型(目前後端為 TypeSafe Jev)自動決定 model。需環境變數 TYPESAFE_API_KEY(沒有就不動);名稱含 grill 或 plan 的 skill(如 /grilling、/grill-with-docs)收尾時,會問是否把結論拆成原子規格條目,由 system1:planner(opus)寫入 context/specs/<id>.json,經程式與 Jev 檢查、使用者確認後生效。可用 /plugin disable system1@cch 關閉、/plugin enable system1@cch 開啟。隱私:每次派 sub-agent,description 與 prompt 前 6000 字會送到 api.typesafe.ai。

安裝

/plugin marketplace add cch-agent/claude-mods
/plugin install grill-choices@cch
/plugin install action-chips@cch
/plugin install system1@cch
/reload-plugins

marketplace 名稱為 cch(見 .claude-plugin/marketplace.json),安裝與解除安裝都用 @cch。從舊名 my-mods 遷移:先 /plugin uninstall <mod>@my-mods、/plugin marketplace remove my-mods,再依上方步驟重裝。

Source 3 files
hooks/register.ts 583 lines
1import type { Register } from 'claude-code'
2
3import {
4  MAX_ITEMS,
5  buildItemRequest,
6  flagSuspicious,
7  formatReport,
8  isGuardedSpecPath,
9  judgeItem,
10  makeSpecId,
11  parseItemAnswer,
12  roundState,
13  validateSpec,
14  type Checks,
15  type Layer3,
16  type Spec,
17} from './plan'
18import { PLANNER_PROMPT, SPEC_TAIL } from './prompts'
19
20export type Model = 'opus' | 'sonnet' | 'haiku'
21export type QuestionId =
22  | 'needs_architecture'
23  | 'needs_deep_reasoning'
24  | 'design_settled'
25  | 'modifies_code'
26  | 'lookup_or_chore'
27export type Nouls = Record<QuestionId, number>
28
29export const HIGH = 0.65
30export const LOW = 0.35
31export const API_URL = 'https://api.typesafe.ai/v1/systemone'
32export const TIMEOUT_MS = 3000
33export const PROMPT_LIMIT = 6000
34
35const QUESTION_TEXT: Record<QuestionId, string> = {
36  needs_architecture: '任務是否需要做架構設計,或在多個方案間做取捨決策?',
37  needs_deep_reasoning: '任務是否需要深度分析或多步推理才能完成?',
38  design_settled: '做法是否已定案,只需照著既定規格執行?',
39  modifies_code: '任務是否需要撰寫或修改程式碼、測試,或審查程式碼?',
40  lookup_or_chore: '任務是否只是查找資料、搜尋檔案、格式化輸出或重複性操作?',
41}
42const IDS = Object.keys(QUESTION_TEXT) as QuestionId[]
43
44const uncertain = (v: number) => v > LOW && v < HIGH
45
46/** 五題 Noul 答案 → model;null 代表不覆寫。判斷順序內只檢查該分支用到的題目是否落在不確定帶 (0.35, 0.65)。 */
47export function decideModel(n: Nouls): Model | null {
48  // opus 分支:max(needs_architecture, needs_deep_reasoning) 與 design_settled
49  const arch = Math.max(n.needs_architecture, n.needs_deep_reasoning)
50  if (uncertain(arch)) return null
51  if (arch >= HIGH) {
52    if (uncertain(n.design_settled)) return null
53    if (n.design_settled < HIGH) return 'opus'
54  }
55  // haiku 分支:lookup_or_chore 與 modifies_code
56  if (uncertain(n.lookup_or_chore)) return null
57  if (n.lookup_or_chore >= HIGH) {
58    if (uncertain(n.modifies_code)) return null
59    if (n.modifies_code <= LOW) return 'haiku'
60  }
61  // sonnet 分支:modifies_code 或 design_settled 明確為是
62  if (n.modifies_code >= HIGH || n.design_settled >= HIGH) return 'sonnet'
63  return null
64}
65
66export function buildRequest(description: string, prompt: string) {
67  const questions: Record<string, unknown> = {}
68  for (const id of IDS) {
69    questions[id] = {
70      type: 'noul',
71      instructions: { task: '`prompt`', question: QUESTION_TEXT[id] },
72    }
73  }
74  return {
75    model: 'jev-latest',
76    state: { description, prompt: prompt.slice(0, PROMPT_LIMIT) },
77    questions,
78  }
79}
80
81/** 解析 API 回應;任何欄位缺漏或格式不對回 null。 */
82export function parseNouls(text: string): Nouls | null {
83  try {
84    const answers = (JSON.parse(text) as { answers?: Record<string, { noul?: unknown }> }).answers
85    if (!answers || typeof answers !== 'object') return null
86    const out = {} as Nouls
87    for (const id of IDS) {
88      const v = answers[id]?.noul
89      if (typeof v !== 'number' || !Number.isFinite(v) || v < 0 || v > 1) return null
90      out[id] = v
91    }
92    return out
93  } catch {
94    return null
95  }
96}
97
98export function statusText(chosen: Model | null, original: string | undefined): string {
99  if (chosen === null) return `保留 ${original ?? '未指定'}`
100  return `${chosen}` + (chosen !== original ? `(原 ${original ?? '未指定'})` : '')
101}
102
103
104const SUBMIT = 'mcp__system1__submit_plan'
105const CONFIRM = 'mcp__system1__confirm_plan'
106export const LAYER3_CONCURRENCY = 4
107export const LAYER3_TIMEOUT_MS = 8000
108const GUARDED_TOOLS = ['Write', 'Edit', 'NotebookEdit'] as const
109
110// skill 名稱(含 plugin 前綴)含 grill 或 plan 即視為需要收尾拆題的規格類 skill,不分大小寫
111export const isSpecSkill = (skill: string) => /grill|plan/i.test(skill)
112
113const SUBMIT_SCHEMA = {
114  type: 'object',
115  properties: {
116    spec_id: { type: 'string', description: '修改既有規格時帶上;第一次送出不要帶' },
117    slug: { type: 'string', description: '英數與連字號的短名稱,用於組成 spec id' },
118    intent: { type: 'string', description: '一句話本意' },
119    requirements: {
120      type: 'array',
121      items: {
122        type: 'object',
123        properties: {
124          id: { type: 'string', description: 'R1、R2…(可加一個小寫字母後綴)' },
125          text: { type: 'string' },
126          verify_by: { type: 'string', enum: ['test', 'jev', 'agent'] },
127        },
128        required: ['id', 'text', 'verify_by'],
129      },
130    },
131    out_of_scope: { type: 'array', items: { type: 'string' } },
132    supersedes: { type: 'array', items: { type: 'string' }, description: '填簡報「取代的舊規格」列出的 spec id;寫「無」時帶 []' },
133    open_questions: {
134      type: 'array',
135      items: {
136        type: 'object',
137        properties: {
138          req_id: { type: 'string' },
139          question: { type: 'string' },
140          options: { type: 'array', items: { type: 'string' } },
141          recommended: { type: 'integer' },
142          why: { type: 'string' },
143        },
144        required: ['req_id', 'question', 'options', 'recommended', 'why'],
145      },
146    },
147  },
148  required: ['slug', 'intent', 'requirements', 'out_of_scope'],
149}
150
151const CONFIRM_SCHEMA = {
152  type: 'object',
153  properties: {
154    spec_ids: { type: 'array', items: { type: 'string' }, description: '要確認的規格 id;一次確認多份時全部列入' },
155    spec_id: { type: 'string', description: '確認單一規格時可用;多份請用 spec_ids' },
156  },
157}
158
159const SPEC_ID_RE = /^[A-Za-z0-9-]+$/
160
161/** 不信任檔案內容的 id:必須合法且等於檔名(去 .json),否則視為無效。 */
162const parseSpec = (text: string, fileId: string): Spec | null => {
163  try {
164    const s = JSON.parse(text) as Spec
165    return s && s.schema === 1 && typeof s.id === 'string' && SPEC_ID_RE.test(s.id) && s.id === fileId ? s : null
166  } catch {
167    return null
168  }
169}
170
171type State = { root: Promise<string> | undefined; written: { seq: number; id: string; report: string } }
172const getRoot = ($: any, st: State): Promise<string> =>
173  (st.root ??= (async () => {
174    try {
175      const r = await $.process.run(['git', 'rev-parse', '--show-toplevel'])
176      const top = String(r.stdout ?? '').trim()
177      if (r.exitCode === 0 && top) return top
178    } catch {
179      // 退回 cwd
180    }
181    return $.session.cwd()
182  })())
183
184const specsDir = (root: string) => `${root}/context/specs`
185
186const listSpecFiles = async ($: any, root: string) => {
187  const dir = specsDir(root)
188  let entries: { name: string; kind: string }[]
189  try {
190    entries = await $.fs.list(dir)
191  } catch {
192    return []
193  }
194  const out: { name: string; text: string }[] = []
195  for (const en of entries) {
196    if (en.kind !== 'file' || !en.name.endsWith('.json')) continue
197    try {
198      out.push({ name: en.name, text: (await $.fs.read(`${dir}/${en.name}`)) as string })
199    } catch {
200      // 讀不到的略過
201    }
202  }
203  return out
204}
205
206const readSpec = async ($: any, root: string, id: string): Promise<Spec | null> => {
207  try {
208    return parseSpec((await $.fs.read(`${specsDir(root)}/${id}.json`)) as string, id)
209  } catch {
210    return null
211  }
212}
213
214const writeSpec = ($: any, root: string, id: string, spec: Spec) =>
215  $.fs.write(`${specsDir(root)}/${id}.json`, JSON.stringify({ ...spec, id }, null, 2) + '\n') as Promise<void>
216
217/** 第 3 層:每條一個請求,併發 4、總逾時 8 秒;失敗只降級,不拋錯。 */
218const runLayer3 = async ($: any, key: string | undefined, reqs: Spec['requirements'], signal: AbortSignal): Promise<Layer3> => {
219  if (!key) return { status: 'skipped:no-key', items: {} }
220  const sent = reqs.slice(0, MAX_ITEMS)
221  const items: Layer3['items'] = {}
222  let errors = 0
223  let stopped = false
224  let cursor = 0
225  const worker = async () => {
226    while (!stopped && cursor < sent.length) {
227      const req = sent[cursor++]!
228      try {
229        const r = await $.http.fetch(API_URL, {
230          method: 'POST',
231          headers: { Authorization: `Bearer ${key}`, 'Content-Type': 'application/json' },
232          body: JSON.stringify(buildItemRequest(req)),
233        })
234        const a = r.ok ? parseItemAnswer(r.text, req.verify_by) : null
235        if (stopped) return
236        if (a) items[req.id] = { ...a, verdict: judgeItem(a) }
237        else errors++
238      } catch {
239        if (!stopped) errors++ // 不記錄 headers/key
240      }
241    }
242  }
243  const abort = new AbortController()
244  const onStop = () => abort.abort()
245  if (signal.aborted) onStop()
246  else signal.addEventListener('abort', onStop)
247  try {
248    const all = Promise.all(Array.from({ length: Math.min(LAYER3_CONCURRENCY, sent.length) }, worker)).then(() => true)
249    const timeout = $.clock.sleep(LAYER3_TIMEOUT_MS, { signal: abort.signal }).then(
250      () => false,
251      () => false,
252    )
253    const finished = await Promise.race([all, timeout])
254    all.catch(() => {})
255    stopped = true
256    const got = Object.keys(items).length
257    const timedOut = !finished
258    if (got === sent.length) return { status: 'ok', items }
259    if (timedOut) return { status: got === 0 ? 'timeout' : 'partial-timeout', items }
260    return { status: 'error', items }
261  } finally {
262    stopped = true
263    abort.abort()
264    signal.removeEventListener('abort', onStop)
265  }
266}
267
268
269// 路徑落點:往上找第一個存在的祖先取 realPath,再接上不存在的剩餘段。
270// 剩餘段含 `..` 時回 'unsafe'(無法判斷落點,呼叫端視為受保護);無法解析回 undefined。
271const placed = async ($: any, path: string): Promise<string | 'unsafe' | undefined> => {
272  const abs = path.startsWith('/') ? path : `${(await $.session.cwd()).replace(/\/$/, '')}/${path}`
273  const segs = abs.split('/').filter((x: string) => x !== '' && x !== '.')
274  const rest: string[] = []
275  while (true) {
276    const cur = '/' + segs.join('/')
277    const st = await $.fs.stat(cur, { resolve: true }).catch(() => undefined)
278    if (st?.realPath) {
279      if (rest.includes('..')) return 'unsafe'
280      const base = (st.realPath as string).replace(/\/$/, '')
281      return rest.length ? `${base}/${rest.join('/')}` : base
282    }
283    if (segs.length === 0) return undefined
284    rest.unshift(segs.pop()!)
285  }
286}
287
288
289export const register: Register = on => {
290  const state: State = { root: undefined, written: { seq: 0, id: '', report: '' } }
291
292  const textResult = (text: string) => ({ result: text })
293
294  on('session.start', async ($, e, next) => {
295    // 三個註冊各自獨立,一個失敗不連帶其他
296    try {
297      await $.tool.register({
298        name: 'submit_plan',
299        description:
300          '送出需求拆題後的規格(唯一寫入路徑):檢查格式與條目品質、寫入 context/specs/<id>.json,回傳檢查報告。只給 system1:planner 使用。',
301        inputSchema: SUBMIT_SCHEMA,
302        isDeferred: false,
303      })
304    } catch {
305      // 略過
306    }
307    try {
308      await $.tool.register({
309        name: 'confirm_plan',
310        description: '請使用者一次確認一或多份規格(spec_ids),只問一次;確認後狀態改為 confirmed。也可用來把誤標 superseded 的規格改回 confirmed。',
311        inputSchema: CONFIRM_SCHEMA,
312        isDeferred: false,
313      })
314    } catch {
315      // 略過
316    }
317    try {
318      await $.agent.register({
319        name: 'planner',
320        description: '把需求簡報拆成原子、可驗證的規格條目並送出檢查(grilling 收尾拆題時使用,傳入需求簡報路徑)。',
321        prompt: PLANNER_PROMPT,
322        tools: ['Read', 'Bash', SUBMIT],
323        model: 'opus',
324        maxTurns: 40,
325      })
326    } catch {
327      // 略過
328    }
329    return next(e)
330  }).catch(($, e, next) => next(e))
331
332  // planner 必須在前景跑,Agent 工具才會等到它結束,hook 才附得上摘要
333  on('agent.spawn', ($, e, next) => (e.subagentType === 'system1:planner' ? next({ ...e, background: false }) : next(e))).catch(
334    ($, e, next) => next(e),
335  )
336
337  on('tool.call', { tool: SUBMIT }, async ($, e: any, next) => {
338    const input = {
339      spec_id: e.spec_id,
340      slug: e.slug,
341      intent: e.intent,
342      requirements: e.requirements,
343      out_of_scope: e.out_of_scope,
344      supersedes: e.supersedes,
345      open_questions: e.open_questions,
346    }
347    const v = validateSpec(input)
348    if (!v.ok) return textResult(`格式錯誤,未寫入:\n${v.errors.map(x => `- ${x}`).join('\n')}\n請修正後重送。`)
349    const root = await getRoot($, state)
350    const files = await listSpecFiles($, root)
351    const existing = new Set(files.map(f => f.name.replace(/\.json$/, '')))
352
353    let prev: Spec | null = null
354    let id: string
355    if (v.value.spec_id !== undefined) {
356      if (!SPEC_ID_RE.test(v.value.spec_id)) return textResult('spec_id 格式不符,未寫入。')
357      prev = await readSpec($, root, v.value.spec_id)
358      if (!prev) return textResult(`找不到 spec_id ${v.value.spec_id},未寫入。第一次送出請不要帶 spec_id。`)
359      id = v.value.spec_id
360    } else {
361      id = makeSpecId(new Date(await $.clock.now()), v.value.slug, existing)
362    }
363
364    const agentKey: string = e.agentId ?? 'main'
365    const st = roundState(prev?.checks, agentKey)
366    if (st.decision === 'reject') {
367      const stop = !st.askAllowed || st.revision >= 4 ? '不再提問;' : ''
368      return textResult(`規格 ${id} 已達重寫上限(第 ${st.round} 輪、revision ${st.revision}),拒絕修改、未寫入。${stop}請回報 spec_id 與未通過條目。`)
369    }
370
371    const layer2: Record<string, string[]> = {}
372    for (const r of v.value.requirements) layer2[r.id] = flagSuspicious(r.text)
373    const key = (await $.env.get('TYPESAFE_API_KEY')) as string | undefined
374    const layer3 = await runLayer3($, key, v.value.requirements, next.signal)
375    const checks: Checks = { round: st.round, revision: st.revision, agent: agentKey, layer2, layer3 }
376
377    // 狀態、時間、base_commit、checks 一律由 mod 決定;修改過的規格(含 confirmed)回到 draft
378    const spec: Spec = {
379      schema: 1,
380      id,
381      status: 'draft',
382      created_at: prev?.created_at ?? new Date(await $.clock.now()).toISOString(),
383      intent: v.value.intent,
384      requirements: v.value.requirements,
385      out_of_scope: v.value.out_of_scope,
386      open_questions: v.value.open_questions ?? [],
387      checks,
388    }
389    const supersedes = v.value.supersedes ?? prev?.supersedes
390    if (supersedes !== undefined) spec.supersedes = supersedes
391    if (next.signal.aborted) return textResult('呼叫已中斷,未寫入。')
392    await writeSpec($, root, id, spec)
393    const report = formatReport(spec, { decision: st.decision, askAllowed: st.askAllowed })
394    state.written = { seq: state.written.seq + 1, id, report }
395    const note = v.value.requirements.length > MAX_ITEMS ? `\n註:超過 ${MAX_ITEMS} 條,後面的條目未送第 3 層檢查。` : ''
396    return textResult(report + note)
397  }).catch(($, e, next) => (next.called ? next(e) : { result: 'submit_plan 內部錯誤,未寫入。' }))
398
399  on('tool.call', { tool: CONFIRM }, async ($, e: any, next) => {
400    const raw: unknown[] = [...(Array.isArray(e.spec_ids) ? e.spec_ids : []), ...(typeof e.spec_id === 'string' && e.spec_id ? [e.spec_id] : [])]
401    const ids = [...new Set(raw.filter((x): x is string => typeof x === 'string'))]
402    const bad = [...new Set(raw.filter(x => typeof x !== 'string').map(x => String(x)))]
403    if (ids.length + bad.length === 0) return textResult('請帶 spec_ids。')
404    const root = await getRoot($, state)
405    const skipped: { id: string; why: string }[] = []
406    const already: string[] = []
407    const targets: Spec[] = []
408    for (const x of bad) skipped.push({ id: x, why: '格式不符' })
409    for (const id of ids) {
410      if (!SPEC_ID_RE.test(id)) {
411        skipped.push({ id, why: '格式不符' })
412        continue
413      }
414      const spec = await readSpec($, root, id)
415      if (!spec) skipped.push({ id, why: '找不到' })
416      else if (spec.status === 'confirmed') already.push(id)
417      else targets.push(spec)
418    }
419    const supList = (spec: Spec) => (Array.isArray(spec.supersedes) ? spec.supersedes.filter((x): x is string => typeof x === 'string') : [])
420    const lines = (head: string, items: string[]) => (items.length ? `${head}\n${items.map(x => `- ${x}`).join('\n')}\n` : '')
421    const summary = (confirmed: string[], marked: string[], base: string | undefined) =>
422      lines('已確認規格:', confirmed) +
423      lines('原本就是 confirmed:', already) +
424      lines('略過:', skipped.map(x => `${x.id}(${x.why})`)) +
425      lines('已標 superseded:', marked) +
426      `base_commit:${base ?? '(無)'}\n實作從使用者下一個指令開始。`
427    if (targets.length === 0) return textResult(summary([], [], undefined).trimEnd())
428
429    const unchanged = targets.map(t => `- ${t.id}(${t.status})`).join('\n')
430    const q =
431      `確認以下 ${targets.length} 份規格?\n` +
432      targets
433        .map(spec => {
434          const flagged = spec.requirements.filter(
435            r => (spec.checks.layer2[r.id]?.length ?? 0) > 0 || (spec.checks.layer3.items[r.id] && spec.checks.layer3.items[r.id]!.verdict !== 'pass'),
436          ).length
437          const sups = supList(spec)
438          const sup = sups.length ? `,將取代 ${sups.join('、')}` : ''
439          return `- ${spec.id}:共 ${spec.requirements.length} 條,${flagged} 條有標記,${spec.open_questions.length} 個未解問題${sup}`
440        })
441        .join('\n')
442    let ans: string
443    try {
444      ans = await $.ui.ask(q, ['確認', '修改', '取消'])
445    } catch {
446      return textResult(`無法詢問使用者(非互動模式或已關閉),以下規格維持原狀態:\n${unchanged}`)
447    }
448    if (ans === '取消') return textResult(`使用者取消,以下規格維持原狀態:\n${unchanged}`)
449    if (ans !== '確認') {
450      const extra = ans === '修改' ? '' : `:${ans}`
451      return textResult(
452        `使用者要求修改${extra}。以下規格維持原狀態:\n${unchanged}\n請依意見調整相關簡報,帶 spec_id 重派 planner 後,再以 spec_ids 帶本次全部規格呼叫一次。`,
453      )
454    }
455
456    // 詢問期間規格可能被改寫:逐份重讀,輪數/revision/agent 有變就整批不確認
457    const changed: string[] = []
458    for (const t of targets) {
459      const fresh = await readSpec($, root, t.id)
460      if (!fresh || fresh.checks.round !== t.checks.round || fresh.checks.revision !== t.checks.revision || fresh.checks.agent !== t.checks.agent) changed.push(t.id)
461    }
462    if (changed.length) return textResult(`規格 ${changed.join('、')} 已更新,請重新確認。`)
463    if (next.signal.aborted) return textResult('呼叫已中斷,規格狀態未變。')
464    let base: string | undefined
465    try {
466      const r = await $.process.run(['git', 'rev-parse', 'HEAD'], { cwd: root })
467      if (r.exitCode === 0 && r.stdout.trim()) base = r.stdout.trim()
468    } catch {
469      // 無 git 時不記 base_commit
470    }
471    const confirmedAt = new Date(await $.clock.now()).toISOString()
472    const done: Spec[] = []
473    const paths: string[] = []
474    for (const t of targets) {
475      try {
476        await writeSpec($, root, t.id, { ...t, status: 'confirmed', confirmed_at: confirmedAt, ...(base ? { base_commit: base } : {}) })
477        done.push(t)
478        paths.push(`${t.id}:${specsDir(root)}/${t.id}.json`)
479      } catch {
480        skipped.push({ id: t.id, why: '寫入失敗' })
481      }
482    }
483    // 只標本次確認成功的規格明確宣告取代的舊規格,排除本批 id;superseded 只是標記,沒有程式依它判斷
484    const batch = new Set(ids)
485    const olds = [...new Set(done.flatMap(supList))].filter(x => !batch.has(x))
486    const marked: string[] = []
487    for (const oldId of olds) {
488      try {
489        if (!SPEC_ID_RE.test(oldId)) continue
490        const old = await readSpec($, root, oldId)
491        if (!old || old.status === 'superseded') continue
492        await writeSpec($, root, oldId, { ...old, status: 'superseded' })
493        marked.push(oldId)
494      } catch {
495        // 略過
496      }
497    }
498    return textResult(summary(paths, marked, base).trimEnd())
499  }).catch(($, e, next) => (next.called ? next(e) : { result: 'confirm_plan 內部錯誤,規格狀態未變。' }))
500
501  // 寫入防護:規格檔只能經 submit_plan 修改
502  for (const tool of GUARDED_TOOLS) {
503    on('tool.call', { tool: tool as 'Write' }, async ($, e: any, next) => {
504      const path: unknown = e.file_path ?? e.notebook_path
505      if (typeof path !== 'string' || !path) return next(e)
506      const root = await getRoot($, state)
507      const real = await placed($, path)
508      if (!real) return next(e)
509      const DENY = { deny: '規格檔只能經 mcp__system1__submit_plan(帶 spec_id)修改;修改後需重新確認' }
510      if (real === 'unsafe') return DENY // 不存在的路徑段含 `..`,落點無法判斷
511      const top = (await $.fs.stat(root, { resolve: true }).catch(() => undefined))?.realPath ?? root
512      // 比對不分大小寫(macOS 預設大小寫不敏感)
513      const lower = real.toLowerCase()
514      if (isGuardedSpecPath(lower, top.toLowerCase()) || isGuardedSpecPath(lower, root.toLowerCase())) return DENY
515      return next(e)
516    }).catch(($, e, next) => next(e))
517  }
518
519  // 同一回合只附加一次(grill-with-docs 會再載入 grilling,兩者都命中)。
520  // 旗標存在閉包內;熱重載會重設為 false,最多多附加一次,可接受。
521  let appendedThisTurn = false
522  on('prompt.submit', ($, e, next) => {
523    appendedThisTurn = false
524    return next(e)
525  }).catch(($, e, next) => next(e))
526
527  on('skill.prompt', ($, e, next) => {
528    if (isSpecSkill(e.skill) && !appendedThisTurn && !e.text.includes(SPEC_TAIL)) {
529      appendedThisTurn = true
530      return next({ ...e, text: e.text + (SPEC_TAIL.startsWith('\n') ? '' : '\n\n') + SPEC_TAIL })
531    }
532    return next(e)
533  }).catch(($, e, next) => next(e))
534
535  on('tool.call', { tool: 'Agent' }, async ($, e, next) => {
536    if (e.subagent_type === 'fork') return next(e)
537    // 本 plugin 自己的 agent:不打 Jev、不改 model;planner 回來後附上最新規格摘要
538    if (typeof e.subagent_type === 'string' && e.subagent_type.startsWith('system1:')) {
539      const before = state.written.seq
540      const res = await next(e)
541      if (e.subagent_type === 'system1:planner' && res.deny === undefined && state.written.seq !== before) {
542        const note = `system1 規格摘要(spec_id ${state.written.id}):\n${state.written.report}`
543        return { ...res, context: [...(res.context ?? []), note] } as typeof res
544      }
545      return res
546    }
547    const key = await $.env.get('TYPESAFE_API_KEY')
548    if (!key) return next(e)
549
550    let chosen: Model | null = null
551    const abort = new AbortController()
552    // 使用者中斷(next.signal)時,逾時等待一起結束;fetch 本身無法取消,只是不再等它
553    const onStop = () => abort.abort()
554    if (next.signal.aborted) onStop()
555    else next.signal.addEventListener('abort', onStop)
556    try {
557      const body = JSON.stringify(buildRequest(e.description, e.prompt))
558      const call = $.http
559        .fetch(API_URL, {
560          method: 'POST',
561          headers: { Authorization: `Bearer ${key}`, 'Content-Type': 'application/json' },
562          body,
563        })
564        .then(r => (r.ok ? parseNouls(r.text) : null))
565      const timeout = $.clock.sleep(TIMEOUT_MS, { signal: abort.signal }).then(
566        () => null,
567        () => null,
568      )
569      const nouls = await Promise.race([call, timeout])
570      call.catch(() => {})
571      if (nouls) chosen = decideModel(nouls)
572    } catch {
573      chosen = null // 不記錄 headers/key
574    } finally {
575      abort.abort()
576      next.signal.removeEventListener('abort', onStop)
577    }
578
579    $.ui.status(statusText(chosen, e.model))
580    return chosen ? next({ ...e, model: chosen }) : next(e)
581  }).catch(($, e, next) => next(e))
582}
583
hooks/plan.ts 258 lines
1// 第 2 階段:grilling 收尾拆題 → 規格檔。本檔全為純函式,不依賴 `$`,方便單元測試。
2
3export const HIGH = 0.65,
4  LOW = 0.35,
5  MAX_ITEMS = 30
6export type VerifyBy = 'test' | 'jev' | 'agent'
7export interface Requirement { id: string; text: string; verify_by: VerifyBy }
8export interface OpenQuestion { req_id: string; question: string; options: string[]; recommended: number; why: string }
9export type Verdict = 'pass' | 'fail' | 'unsure'
10export interface ItemAnswer { single_condition: number; self_contained: number; testable?: number }
11export interface Layer3 { status: 'ok' | 'skipped:no-key' | 'timeout' | 'partial-timeout' | 'error'; items: Record<string, ItemAnswer & { verdict: Verdict }> }
12export interface Checks { round: number; revision: number; agent: string; layer2: Record<string, string[]>; layer3: Layer3 }
13export interface Spec { schema: 1; id: string; status: 'draft' | 'confirmed' | 'superseded'; created_at: string; confirmed_at?: string; base_commit?: string; intent: string; requirements: Requirement[]; out_of_scope: string[]; supersedes?: string[]; open_questions: OpenQuestion[]; checks: Checks }
14export interface SpecInput { spec_id?: string; slug: string; intent: string; requirements: Requirement[]; out_of_scope: string[]; supersedes?: string[]; open_questions?: OpenQuestion[] }
15
16const VERIFY_BY = ['test', 'jev', 'agent']
17const REQ_ID = /^R\d+[a-z]?$/
18const isStr = (v: unknown): v is string => typeof v === 'string'
19const isObj = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v)
20
21/** 驗證 planner 送來的規格輸入;回傳所有錯誤而非只第一個。 */
22export function validateSpec(input: unknown): { ok: true; value: SpecInput } | { ok: false; errors: string[] } {
23  if (!isObj(input)) return { ok: false, errors: ['輸入必須是物件'] }
24  const errors: string[] = []
25
26  if (!isStr(input.intent) || !input.intent.trim()) errors.push('缺少 intent(一句話本意)')
27
28  const ids = new Set<string>()
29  const reqs: Requirement[] = []
30  if (!Array.isArray(input.requirements) || input.requirements.length === 0) {
31    errors.push('requirements 不可為空')
32  } else {
33    for (const [i, r] of input.requirements.entries()) {
34      if (!isObj(r)) {
35        errors.push(`requirements[${i}] 必須是物件`)
36        continue
37      }
38      const label = isStr(r.id) ? r.id : `#${i}`
39      if (!isStr(r.id) || !REQ_ID.test(r.id)) errors.push(`${label}:id 須符合 ^R\\d+[a-z]?$`)
40      else if (ids.has(r.id)) errors.push(`${label}:id 重複`)
41      else ids.add(r.id)
42      if (!isStr(r.text) || !r.text.trim()) errors.push(`${label}:text 不可為空`)
43      if (!isStr(r.verify_by) || !VERIFY_BY.includes(r.verify_by)) errors.push(`${label}:verify_by 須為 test/jev/agent`)
44      reqs.push({ id: r.id as string, text: r.text as string, verify_by: r.verify_by as VerifyBy }) // 只留三個欄位
45    }
46  }
47
48  if (!Array.isArray(input.out_of_scope) || !input.out_of_scope.every(isStr)) errors.push('out_of_scope 須為字串陣列')
49  if (input.supersedes !== undefined && (!Array.isArray(input.supersedes) || !input.supersedes.every(isStr))) errors.push('supersedes 須為字串陣列')
50
51  const oqs: OpenQuestion[] = []
52  if (input.open_questions !== undefined) {
53    if (!Array.isArray(input.open_questions)) errors.push('open_questions 須為陣列')
54    else {
55      for (const [i, q] of input.open_questions.entries()) {
56        const label = `open_questions[${i}]`
57        if (!isObj(q)) {
58          errors.push(`${label} 必須是物件`)
59          continue
60        }
61        if (!isStr(q.req_id) || !ids.has(q.req_id)) errors.push(`${label}:req_id 必須是存在的需求 id`)
62        if (!isStr(q.question) || !q.question.trim()) errors.push(`${label}:question 不可為空`)
63        if (!Array.isArray(q.options) || q.options.length < 2 || q.options.length > 4 || !q.options.every(isStr)) {
64          errors.push(`${label}:options 須為 2–4 個字串`)
65        } else if (!Number.isInteger(q.recommended) || (q.recommended as number) < 0 || (q.recommended as number) >= q.options.length) {
66          errors.push(`${label}:recommended 須為 options 的有效索引`)
67        }
68        if (!isStr(q.why)) errors.push(`${label}:why 須為字串`)
69        oqs.push({ req_id: q.req_id as string, question: q.question as string, options: q.options as string[], recommended: q.recommended as number, why: q.why as string })
70      }
71    }
72  }
73
74  if (input.spec_id !== undefined && !isStr(input.spec_id)) errors.push('spec_id 須為字串')
75  if (input.slug !== undefined && !isStr(input.slug)) errors.push('slug 須為字串')
76
77  if (errors.length) return { ok: false, errors }
78  const value: SpecInput = {
79    slug: isStr(input.slug) ? input.slug : '',
80    intent: input.intent as string,
81    requirements: reqs,
82    out_of_scope: input.out_of_scope as string[],
83    open_questions: oqs,
84  }
85  if (isStr(input.spec_id)) value.spec_id = input.spec_id
86  if (input.supersedes !== undefined) value.supersedes = input.supersedes as string[]
87  return { ok: true, value }
88}
89
90/** 第 2 層:只標記可疑處,不判對錯。 */
91export function flagSuspicious(text: string): string[] {
92  const flags: string[] = []
93  // 較長的詞先比對並從工作字串移除,避免「並且」同時被標成「並」「且」
94  let rest = text
95  for (const w of ['並且', '以及', '同時', '並', '且']) {
96    if (rest.includes(w)) {
97      flags.push(`conjunction:${w}`)
98      rest = rest.split(w).join(' ')
99    }
100  }
101  if (/,\s*and\b/i.test(text)) flags.push('conjunction:, and')
102  for (const w of ['剛才', '上述', '前述', '這個', '那個']) if (text.includes(w)) flags.push(`pronoun:${w}`)
103  if (/(?<!應)該/.test(text)) flags.push('pronoun:該') // 排除「應該」
104  if (/\babove\b/i.test(text)) flags.push('pronoun:above')
105  const len = Array.from(text).length
106  if (len > 80) flags.push(`long:${len}`)
107  return flags
108}
109
110/** 第 3 層:每條需求一個請求,state 只含該條。testable 只在 verify_by === 'test' 時問。 */
111export function buildItemRequest(req: Requirement): { model: 'jev-latest'; state: { requirement: string; verify_by: VerifyBy }; questions: Record<string, unknown> } {
112  const questions: Record<string, unknown> = {
113    single_condition: {
114      type: 'noul',
115      instructions: { question: '`requirement` 是否只描述一個可獨立判斷是否滿足的條件?' },
116      criteria: {
117        true: '只有一個條件,一次檢查即可判定',
118        false: '含兩個以上可分開判斷的條件,例如以「且/並/以及」連接,或同時規定行為與修改範圍',
119      },
120    },
121    self_contained: {
122      type: 'noul',
123      instructions: { question: '只讀 `requirement` 這一句、不看任何其他資料,能否判斷一段程式變更是否滿足它?' },
124      criteria: {
125        true: '寫明具體對象(檔名、函式、數值或行為),可直接比對',
126        false: '需要句外脈絡才知道指什麼(如「剛才、上述、這個」),或描述模糊到無法判定',
127      },
128    },
129  }
130  if (req.verify_by === 'test') {
131    questions.testable = {
132      type: 'noul',
133      instructions: { question: '能否只根據 `requirement` 寫出一個測試:一組明確輸入與一個預期輸出?' },
134      criteria: {
135        true: '寫明輸入或情境,以及單一預期結果',
136        false: '缺輸入、缺預期結果,或需要多個斷言',
137      },
138    }
139  }
140  return { model: 'jev-latest', state: { requirement: req.text, verify_by: req.verify_by }, questions }
141}
142
143/** 解析 API 回應;缺欄位、非數字或超出 [0,1] 回 null。 */
144export function parseItemAnswer(text: string, verifyBy: VerifyBy): ItemAnswer | null {
145  try {
146    const answers = (JSON.parse(text) as { answers?: Record<string, { noul?: unknown }> } | null)?.answers
147    if (!answers || typeof answers !== 'object') return null
148    const get = (id: string): number | null => {
149      const v = answers[id]?.noul
150      return typeof v === 'number' && Number.isFinite(v) && v >= 0 && v <= 1 ? v : null
151    }
152    const single = get('single_condition')
153    const self = get('self_contained')
154    if (single === null || self === null) return null
155    const out: ItemAnswer = { single_condition: single, self_contained: self }
156    if (verifyBy === 'test') {
157      const t = get('testable')
158      if (t === null) return null
159      out.testable = t
160    }
161    return out
162  } catch {
163    return null
164  }
165}
166
167/** 任一題 ≤LOW → fail;否則任一題落在不確定帶 → unsure;否則 pass。 */
168export function judgeItem(a: ItemAnswer): Verdict {
169  const vs = [a.single_condition, a.self_contained]
170  if (a.testable !== undefined) vs.push(a.testable)
171  if (vs.some(v => v <= LOW)) return 'fail'
172  if (vs.some(v => v < HIGH)) return 'unsure'
173  return 'pass'
174}
175
176/** 輪數:同一 agent 再送 → round+1;換 agent → revision+1、round 重算。 */
177export function roundState(prev: Checks | undefined, agentKey: string): { round: number; revision: number; decision: 'write' | 'write-final' | 'reject'; askAllowed: boolean } {
178  let round = 1
179  let revision = 1
180  if (prev) {
181    if (prev.agent === agentKey) {
182      round = prev.round + 1
183      revision = prev.revision
184    } else {
185      revision = prev.revision + 1
186    }
187  }
188  // round 超過 3,或 revision 超過硬上限 3(換 agent 後變 4 以上)一律拒絕
189  const decision = round >= 4 || revision >= 4 ? 'reject' : round === 3 ? 'write-final' : 'write'
190  return { round, revision, decision, askAllowed: revision < 3 }
191}
192
193/** 回給 planner/主 session 的報告:待問題目 → fail → unsure → 第 2 層標記,最後附指示句。 */
194export function formatReport(spec: Spec, state: { decision: 'write' | 'write-final'; askAllowed: boolean }): string {
195  const { checks } = spec
196  const text = new Map(spec.requirements.map(r => [r.id, r.text]))
197  const lines: string[] = [
198    `規格 ${spec.id}(第 ${checks.round} 輪,revision ${checks.revision},共 ${spec.requirements.length} 條)`,
199  ]
200
201  if (spec.open_questions.length) {
202    lines.push('', '待問題目:')
203    for (const q of spec.open_questions) {
204      lines.push(`- ${q.req_id}:${q.question}(選項:${q.options.join(' / ')};建議:${q.options[q.recommended]};理由:${q.why})`)
205    }
206  }
207  const items = checks.layer3.items
208  for (const [verdict, title] of [['fail', '未通過(fail)'], ['unsure', '不確定(unsure)']] as const) {
209    const ids = Object.keys(items).filter(id => items[id]!.verdict === verdict)
210    if (!ids.length) continue
211    lines.push('', `${title}:`)
212    for (const id of ids) {
213      const a = items[id]!
214      const scores = [`single=${a.single_condition}`, `self=${a.self_contained}`, ...(a.testable !== undefined ? [`testable=${a.testable}`] : [])]
215      lines.push(`- ${id}(${scores.join(', ')})${text.get(id) ?? ''}`)
216    }
217  }
218  const flagged = Object.keys(checks.layer2).filter(id => checks.layer2[id]!.length)
219  if (flagged.length) {
220    lines.push('', '第 2 層標記:')
221    for (const id of flagged) lines.push(`- ${id}:${checks.layer2[id]!.join('、')}`)
222  }
223
224  const s = checks.layer3.status
225  if (s === 'partial-timeout') lines.push('', '第 3 層部分逾時:未回來的條目只有第 2 層結果')
226  else if (s !== 'ok') lines.push('', `第 3 層未執行:${s}`)
227
228  lines.push('', `剩餘自動重寫 ${Math.max(0, 3 - checks.round)} 輪;revision ${checks.revision}/3`)
229  // 刻意設計:「全部通過」只看已判定的條目;第 3 層未完整時(未執行/部分逾時)報告另有專行說明,不在此排除
230  // 每個 fail/unsure 條目都已列入 open_questions 時,宣告全部通過(planner 據此結束)
231  const asked = new Set(spec.open_questions.map(q => q.req_id))
232  if (Object.entries(items).every(([id, a]) => a.verdict === 'pass' || asked.has(id))) lines.push('全部通過:沒有待重寫的條目')
233  if (state.decision === 'write-final') lines.push('已達重寫上限:停止修改,回報 spec_id 與未通過條目')
234  else lines.push('寫法問題自行重寫後帶 spec_id 再送出;需求問題列入 open_questions 並保留原條目')
235  if (!state.askAllowed) lines.push('不再提問,剩下的問題留在 open_questions,直接交 confirm')
236  return lines.join('\n')
237}
238
239/** `YYYYMMDD-HHMM-<slug>`(UTC);slug 清理為 [a-z0-9-],撞名加 -2、-3。 */
240export function makeSpecId(now: Date, slug: string, existing: Set<string>): string {
241  const p = (n: number) => String(n).padStart(2, '0')
242  const stamp = `${now.getUTCFullYear()}${p(now.getUTCMonth() + 1)}${p(now.getUTCDate())}-${p(now.getUTCHours())}${p(now.getUTCMinutes())}`
243  const clean = slug.toLowerCase().replace(/[^a-z0-9-]+/g, '-').replace(/-+/g, '-').replace(/^-|-$/g, '').slice(0, 40).replace(/-$/, '') || 'spec'
244  const base = `${stamp}-${clean}`
245  if (!existing.has(base)) return base
246  for (let n = 2; ; n++) if (!existing.has(`${base}-${n}`)) return `${base}-${n}`
247}
248
249/** 僅 `<toplevel>/context/specs/<name>.json`(第一層、無 `..`)為真。 */
250export function isGuardedSpecPath(realPath: string, toplevel: string): boolean {
251  // macOS 預設不分大小寫,`Context/Specs/x.json` 指向同一檔,故前綴不分大小寫比對
252  const prefix = `${toplevel.replace(/\/+$/, '')}/context/specs/`.toLowerCase()
253  if (realPath.split('/').includes('..') || !realPath.toLowerCase().startsWith(prefix)) return false
254  const rest = realPath.slice(prefix.length)
255  if (rest.includes('/') || rest.includes('..')) return false
256  return rest.endsWith('.json') && rest.length > '.json'.length
257}
258
hooks/prompts.ts 56 lines
1// PLANNER_PROMPT:system1:planner 的 system prompt(由 register.ts 以 $.agent.register 註冊);SPEC_TAIL:附加在 grilling 後的收尾流程。
2export const PLANNER_PROMPT = `你是 planner。輸入是一份需求簡報的路徑(\`context/briefs/<檔名>.md\`,內容為本意、限制與決定、已知檔案、不做的事),重派時另附 spec_id;先用 Read 讀簡報全文。你的產出是一份規格檔:一句 intent,加上一組原子條目。你只經 \`mcp__system1__submit_plan\` 寫入規格;簡報之外的決定一律交給使用者。
3
4## 原子條目
5
6每個條目(requirements 的一筆)同時滿足三性質:
7- atomic:只描述一個條件,一次檢查即可判定。行為與修改範圍是兩個條件,各自成條。
8- self-contained:只讀這一句就能判斷一段程式變更是否滿足它。寫明具體對象(檔名、函式、數值、行為),以實名取代「剛才、上述、這個」。
9- observable:寫明如何觀察到它成立,對應 verify_by。
10
11verify_by 依序判斷,取第一個成立的:
121. \`test\`:能寫成一個測試。寫法:一組明確輸入加單一預期輸出。
132. \`jev\`:只看這次變更的 git diff 就能判斷真偽(修改範圍、新增或刪除的檔案與符號、命名、文字內容)。寫法:寫成可判真假的陳述句,寫明比對對象(檔名、符號名、字串)。
143. \`agent\`:需要執行程式,或追蹤跨檔邏輯才能判斷。寫法:寫明要檢查的檔案或行為,以及通過的樣子。
15
16範例。簡報句子「空輸入時回傳空陣列並且只改 extract.ts」含兩個條件、且修改範圍與行為混在一起,拆成:
17- R1 \`test\`:\`extract("")\` 回傳 \`[]\`
18- R2 \`jev\`:變更只涉及 \`extract.ts\`
19
20## 步驟
21
221. 讀相關程式碼:用 Read 讀檔,用 Bash 做唯讀搜尋(如 \`rg\`、\`git grep\`、\`git ls-files\`、\`ls\`);Bash 只用於讀取與搜尋。完成條件:簡報提到的每個檔案與符號都已讀過,條目要用到的檔名、函式名、現況行為都已查證。
232. 寫 intent(一句話本意)與 slug(英文小寫與連字號,概括這份規格)。完成條件:intent 與簡報的本意逐字對得上。
243. 寫條目與 out_of_scope。完成條件:簡報每條限制與決定至少對應一個條目,簡報「不做的事」全部列入 out_of_scope,每個條目都滿足三性質。條目 id 用 R1、R2…。
254. 呼叫 \`mcp__system1__submit_plan\`,帶 slug、intent、requirements、out_of_scope、supersedes、open_questions。supersedes 填簡報「取代的舊規格」列出的 spec id;寫「無」時帶 \`[]\`。重派時簡報會附 spec_id,一併帶上。完成條件:收到回應。
265. 依回應處理每個被點名的條目,分兩類:
27   - 寫法問題:修正所需資訊已在簡報或程式碼中(拆開「且」連接的兩半、補檔名、換掉指代詞、補 test 的輸入與預期、拆過長條目)。自己重寫,必要時再查程式碼,再回到步驟 4(帶回應中的 spec_id)。
28   - 需求問題:修正需要一個簡報與程式碼都沒有答案的決定(數值、邊界行為、兩種解讀擇一、是否納入範圍)。保留原條目,寫進 open_questions,欄位:\`req_id\`(條目 id)、\`question\`、\`options\`(2–4 個互斥選項)、\`recommended\`(建議選項的索引,從 0 起算)、\`why\`(建議理由)。
29   - 回應含「不再提問」:只處理寫法問題(自行重寫後再送出);需求問題保留在原條目,open_questions 維持現有內容。
306. 回報。完成條件:回報包含 spec_id、仍未通過的條目(id 與原因)、open_questions 全文,以及 submit_plan 最後一次回應的完整報告摘要與其中出現的所有關鍵字(全部通過、已達重寫上限、不再提問,逐字轉述),讓主 session 不依賴 hook 也能判斷下一步,包括是否還要提問。
31
32## 結束條件
33
34submit_plan 回應出現以下任一種時,進入步驟 6 並結束:
35- 「全部通過」
36- 「已達重寫上限」`
37
38// 以兩個換行開頭,接在 grilling skill 文字之後。
39export const SPEC_TAIL = `
40
41## 規格拆題(system1 mod)
42
43frontier 清空、使用者確認已有共識之後,依序做以下六步:
44
451. 問使用者是否產出拆題檔,選項:產出(Recommended)、不用。選「不用」即結束,不做後續步驟。完成條件:使用者已選。
462. 寫需求簡報,存到 \`context/briefs/\`。可獨立實作的範圍各寫一份,每份內容:本意、限制與決定(附使用者原話)、已知檔案、不做的事、取代的舊規格。「取代的舊規格」列出內容被本份需求取代、之後不再實作的既有規格 spec id(先 \`ls context/specs/\`,讀候選規格的 intent 對照);沒有就寫「無」。完成條件:每條限制都對應到本次對話的出處,每份簡報脫離對話也讀得懂,且都寫了「取代的舊規格」。
473. 每份簡報各自走第 3–4 步,一次派一個 planner,收到回報再派下一份(hook 附上的摘要只對應最近一次送出的規格)。派 \`system1:planner\`,prompt 為該份簡報的路徑;重派時附上 spec_id(使用者的新答案已併入簡報檔)。完成條件:planner 回報 spec_id。
484. 依 planner 回報(含轉述的關鍵字與報告摘要;hook 附上的摘要若有,以它為準)判斷。planner 回報 open_questions 時,依本 session 的 grilling 提問方式問使用者,把答案併入簡報,回到第 3 步(帶同一 spec_id)。完成條件:最新一次回報沒有 open_questions,或 planner 回應已「不再提問」。
495. 全部簡報都走完第 4 步後,依各份 planner 回報的報告摘要(hook 附上的摘要若有,以它為準),逐份按待問題目、fail、unsure、第 2 層標記、其餘的順序列出全部條目,再呼叫 \`mcp__system1__confirm_plan\`,spec_ids 帶本次全部 spec_id(每次呼叫都帶全部;已確認的會列在「原本就是 confirmed」,不會再問)。依最近一次回傳處理:
50   - 含「略過」:依原因修正 spec_id 或重派該份 planner,再呼叫一次。
51   - 含「使用者要求修改」:把使用者意見併入相關簡報,那幾份回到第 3 步(帶同一 spec_id),再呼叫一次。
52   - 含「已更新,請重新確認」:重新列出條目,再呼叫一次。
53   - 含「使用者取消」或「無法詢問」:跳過第 6 步,回報各份 spec_id 與目前狀態後結束。
54   - 其他回傳:停下,把回傳原文告訴使用者。
55   完成條件:最近一次回傳中,「已確認規格」與「原本就是 confirmed」合起來涵蓋本次每一個 spec_id。
566. 把全部簡報與 \`context/specs/\` 下的變更 commit 成一個 commit(含 confirm_plan 回傳「已標 superseded」列出的舊規格)。完成條件:\`git status\` 中 \`context/briefs/\`、\`context/specs/\` 沒有未提交的變更。回報每份規格的路徑與狀態,以及已標 superseded 的規格;實作從使用者下一個指令開始。`