@morning-start/dsh-code-toolkit 0.28.0 → 0.29.0

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/src/caption.js ADDED
@@ -0,0 +1,149 @@
1
+ /**
2
+ * Reading a caption ledger without owning its format.
3
+ *
4
+ * A ledger is Markdown written by a model: a `# Caption: …` heading, a few
5
+ * `- Field: value` lines, one `## N. title` entry per iteration, and a closing
6
+ * `## Close`. The parser is deliberately tolerant — an older ledger that lacks a
7
+ * field must still list and resume, and a heading that does not match the current
8
+ * habit must not make the file invisible. Anything unreadable degrades to the
9
+ * file name.
10
+ */
11
+
12
+ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
13
+ import { join } from 'node:path'
14
+
15
+ const FIELD = /^\s*-\s*(task|criteria|gate|flow|approved)\s*:\s*(.+)$/i
16
+ const ENTRY = /^##\s+(\d+)\.\s*(.+)$/
17
+ const OUTCOME = /^\s*-\s*outcome\s*:\s*([a-z][a-z -]*)/gim
18
+ const PLAN_HEADING = /^##\s+plan\b/i
19
+ const PLAN_ITEM = /^\s*-\s*\[([ xX~-])\]\s*(.+)$/
20
+
21
+ /**
22
+ * The plan block: `[ ]` open, `[x]` done, `[~]` blocked, `[-]` dropped. Only lines
23
+ * inside the `## Plan` section count, so a checklist quoted in an entry is not
24
+ * mistaken for the plan.
25
+ */
26
+ export function parsePlan(lines) {
27
+ const start = lines.findIndex((line) => PLAN_HEADING.test(line))
28
+ if (start === -1) return { total: 0, done: 0, open: 0, blocked: 0, dropped: 0, items: [] }
29
+
30
+ const items = []
31
+ for (let index = start + 1; index < lines.length; index += 1) {
32
+ if (/^##\s+\S/.test(lines[index])) break
33
+ const match = PLAN_ITEM.exec(lines[index])
34
+ if (!match) continue
35
+ const mark = match[1].toLowerCase()
36
+ items.push({
37
+ status: mark === 'x' ? 'done' : mark === '~' ? 'blocked' : mark === '-' ? 'dropped' : 'open',
38
+ text: match[2].trim(),
39
+ })
40
+ }
41
+
42
+ const count = (status) => items.filter((item) => item.status === status).length
43
+ return {
44
+ total: items.length,
45
+ done: count('done'),
46
+ open: count('open'),
47
+ blocked: count('blocked'),
48
+ dropped: count('dropped'),
49
+ items,
50
+ }
51
+ }
52
+
53
+ /** Pull the head, the entries, and the outcome counts out of one ledger. */
54
+ export function parseLedger(text) {
55
+ // A ledger written by Notepad or Set-Content can start with a BOM, which makes
56
+ // `/^#/` miss the heading and the file look like it has no title.
57
+ const source = String(text ?? '').replace(/^\uFEFF/, '')
58
+ const lines = source.split(/\r?\n/)
59
+
60
+ const heading = lines.find((line) => /^#\s+\S/.test(line)) ?? ''
61
+ const fields = {}
62
+ for (const line of lines) {
63
+ const match = FIELD.exec(line)
64
+ // First wins: the head states the contract, and a closing entry may repeat
65
+ // `- Gate:` with that run's result — listing must show the contract.
66
+ if (match && !(match[1].toLowerCase() in fields)) fields[match[1].toLowerCase()] = match[2].trim()
67
+ }
68
+
69
+ const entries = []
70
+ for (const line of lines) {
71
+ const match = ENTRY.exec(line)
72
+ if (match) entries.push({ number: Number(match[1]), title: match[2].trim() })
73
+ }
74
+
75
+ const outcomes = [...source.matchAll(OUTCOME)].map((match) => match[1].trim().toLowerCase())
76
+ return {
77
+ title: heading.replace(/^#\s+/, '').trim(),
78
+ task: fields.task ?? '',
79
+ criteria: fields.criteria ?? '',
80
+ gate: fields.gate ?? '',
81
+ flow: fields.flow ?? '',
82
+ entries,
83
+ plan: parsePlan(lines),
84
+ done: outcomes.filter((outcome) => outcome === 'done').length,
85
+ unverified: outcomes.filter((outcome) => outcome === 'unverified').length,
86
+ deadEnds: outcomes.filter((outcome) => outcome.startsWith('dead')).length,
87
+ closed: /^##\s*Close\b/im.test(source),
88
+ }
89
+ }
90
+
91
+ /** Every `*.md` in the ledger directory, most recently changed first. */
92
+ export function listLedgers(directory) {
93
+ if (!directory || !existsSync(directory)) return []
94
+ const ledgers = []
95
+ for (const entry of readdirSync(directory, { withFileTypes: true })) {
96
+ if (!entry.isFile() || !entry.name.toLowerCase().endsWith('.md')) continue
97
+ const path = join(directory, entry.name)
98
+ try {
99
+ const text = readFileSync(path, 'utf8')
100
+ ledgers.push({
101
+ slug: entry.name.replace(/\.md$/i, ''),
102
+ path,
103
+ modifiedAt: statSync(path).mtimeMs,
104
+ ...parseLedger(text),
105
+ })
106
+ } catch {
107
+ ledgers.push({ slug: entry.name.replace(/\.md$/i, ''), path, modifiedAt: 0, title: '', entries: [], closed: false })
108
+ }
109
+ }
110
+ return ledgers.sort((a, b) => b.modifiedAt - a.modifiedAt || a.slug.localeCompare(b.slug))
111
+ }
112
+
113
+ /**
114
+ * Find the ledger a person meant: exact slug, then 1-based position in the list,
115
+ * then a unique substring of the slug or the title. Ambiguity is reported rather
116
+ * than resolved by guessing.
117
+ */
118
+ export function resolveLedger(name, ledgers) {
119
+ const wanted = String(name ?? '').trim()
120
+ if (!wanted) return { error: 'missing' }
121
+
122
+ const exact = ledgers.find((ledger) => ledger.slug.toLowerCase() === wanted.toLowerCase())
123
+ if (exact) return { ledger: exact }
124
+
125
+ if (/^\d+$/.test(wanted)) {
126
+ const index = Number(wanted) - 1
127
+ if (index >= 0 && index < ledgers.length) return { ledger: ledgers[index] }
128
+ }
129
+
130
+ const needle = wanted.toLowerCase()
131
+ const matches = ledgers.filter((ledger) =>
132
+ ledger.slug.toLowerCase().includes(needle) || (ledger.title ?? '').toLowerCase().includes(needle))
133
+ if (matches.length === 1) return { ledger: matches[0] }
134
+ if (matches.length > 1) return { error: 'ambiguous', matches }
135
+ return { error: 'unknown' }
136
+ }
137
+
138
+ /**
139
+ * The first word decides the mode: `list` alone, `resume <name>`, or a task.
140
+ * `list` must be the whole input, so a task that starts with the word is not
141
+ * swallowed by mistake.
142
+ */
143
+ export function splitCaptionInput(rawInput) {
144
+ const text = String(rawInput ?? '').trim()
145
+ if (/^list$/i.test(text)) return { mode: 'list' }
146
+ const resume = /^resume\b[\s::]*([\s\S]*)$/i.exec(text)
147
+ if (resume) return { mode: 'resume', name: resume[1].trim() }
148
+ return { mode: 'task', task: text }
149
+ }
package/src/command.js CHANGED
@@ -59,12 +59,16 @@ export class SessionCommand {
59
59
  /** Put text into the session: caption's protocol, pua's flavor. */
60
60
  async inject(agent, rawInput, locale, t) {
61
61
  const { spec, host } = this
62
+ // Commands that read something before injecting (a ledger, a directory) need
63
+ // the session and the shared services; they get the same context the build
64
+ // step does, so a decision made in validate is the one buildText acts on.
65
+ const context = { agent, host, locale }
62
66
  if (spec.validate) {
63
- const failure = spec.validate(rawInput, t)
67
+ const failure = spec.validate(rawInput, t, context)
64
68
  if (failure) return { kind: 'error', text: failure }
65
69
  }
66
70
  if (spec.early) {
67
- const result = spec.early(rawInput, t)
71
+ const result = spec.early(rawInput, t, context)
68
72
  if (result) return result
69
73
  }
70
74
  if (typeof agent?.steer !== 'function') return { kind: 'error', text: t('error.noSteer') }
package/src/i18n.js CHANGED
@@ -21,19 +21,30 @@ const LANGUAGE_NAMES = {
21
21
 
22
22
  const MESSAGES = {
23
23
  zh: {
24
- 'cmd.simplify': '简化代码:功能逐位不变,默认直接改整个项目',
25
- 'cmd.review': '审查代码改动:默认出报告并修复发现的问题,加 report 只出报告',
26
- 'cmd.scrub': '清理隐私信息:密钥、密码、账号、本机路径,默认直接改',
27
- 'cmd.caption': '把难任务装进 caption 循环:一步一验,过程落成台账',
28
- 'hint.caption': '留空即继续当前任务;或写下任务与验收判据',
24
+ 'cmd.simplify': '简化代码,功能不变',
25
+ 'cmd.review': '审查改动并修复问题',
26
+ 'cmd.scrub': '清理密钥与隐私信息',
27
+ 'cmd.caption': '按计划清单跑到完成,过程落台账',
28
+ 'hint.caption': '留空继续当前任务;list 列台账,resume <名字> 接续',
29
29
  'caption.installed': '已装入 caption 循环:台账写到 {dir},每一步都要有命令和它的结果。',
30
30
  'caption.reinstalled': 'caption 循环已在本次会话里,只补了任务:台账 {dir},继续按循环走。',
31
- 'cmd.audit': '审计现有能力:从真实入口追到存储,标出通/半/假/断/无,只读',
32
- 'hint.audit': '留空即审整个项目;读取量大,推荐加 sub 用子 agent',
31
+ 'caption.steps': ' 步',
32
+ 'caption.planProgress': '计划 {done}/{total}',
33
+ 'caption.planBlocked': ' · {count} 项受阻',
34
+ 'caption.closed': ' · 已收口',
35
+ 'caption.listHead': '台账目录:{dir}',
36
+ 'caption.listHint': '用 /code-caption resume <序号|名字> 继续一份。',
37
+ 'caption.listEmpty': '台账目录 {dir} 还是空的:第一次运行会创建。',
38
+ 'caption.noLedgers': '还没有任何台账:先跑一次 /code-caption <任务>。',
39
+ 'caption.unknownLedger': '没有找到台账「{name}」,现有:',
40
+ 'caption.ambiguousLedger': '「{name}」匹配到多份台账,请用序号或完整名字:',
41
+ 'caption.resumed': '已接续台账:{path}。先读头部和最后两条,再走下一步。',
42
+ 'cmd.audit': '审计能力是否真的通(只读)',
43
+ 'hint.audit': '留空即整个项目;加 sub 用隔离子 agent(推荐)',
33
44
  'mode.audit': '只出五态表与证据,不改任何文件;没有走通真实入口的能力标「未确认」,不要标「通」。',
34
45
  'audit.delivery': '你的最终回复会原样作为审计结果发回:一条能力一行,写清状态、证据(文件:行)和链路断在哪一步,以及哪些没有验到。',
35
- 'cmd.design': '场景驱动的需求分析:四张底图、场景卡、批次方案,出文档等你批',
36
- 'hint.design': '留空即按半天深度设计;quick 只出一页结论,full 出完整方案与附录',
46
+ 'cmd.design': '把需求拆成场景与批次方案',
47
+ 'hint.design': '留空按半天设计;quick 一页,full 完整方案',
37
48
  'design.installed': '已装入场景驱动设计协议:设计文档写到 {dir}。方案出完等你批,不会自己动手。',
38
49
  'design.reinstalled': '设计协议已在本次会话里:设计文档 {dir},继续按协议推进。',
39
50
  'error.designDirectory': 'designDirectory 不能为空。',
@@ -43,15 +54,15 @@ const MESSAGES = {
43
54
  'cmd.queuedSub': '已交给独立子 agent,范围:{scope};完成后结果会作为一条消息发回。',
44
55
  'cmd.queuedPlan': '已请它先出方案,范围:{scope},不改任何文件;方案回来后你确认,再执行。',
45
56
  'cmd.queuedPlanSub': '已请独立子 agent 先出方案,范围:{scope},不改任何文件;方案回来后你确认,再执行。',
46
- 'cmd.pua': '给当前会话装上 PUA 协议:失败就换方法、拿证据、别敷衍',
47
- 'hint.pua': '留空用默认风味;或 list / alibaba / huawei / musk 等',
57
+ 'cmd.pua': '装上「不许敷衍」的协议',
58
+ 'hint.pua': '留空用默认风味;list 查看全部',
48
59
  'pua.installed': '已装上 PUA 协议({flavor}):同类尝试失败两次就换方法,说完成必须给出命令和输出。',
49
60
  'pua.list': '可用风味:',
50
- 'cmd.status': '查看代码工具箱任务状态或最近结果',
51
- 'cmd.cancel': '取消当前代码工具箱任务',
52
- 'hint.scope': '留空即整个项目(当前分支);或 --files a.js,b.js / --branch main(对比哪个分支,默认基线)/ --commit <sha> / 自定义说明;加 sub 用子 agent,加 report 只出报告',
53
- 'hint.scrub': '留空即整个项目;或 --files a.js,.env / 自定义说明;加 sub 用子 agent,加 report 只出报告',
54
- 'hint.review': '留空即审未提交的改动(都提交了就审分支相对基线);或 --files / --branch <对比分支> / --commit <sha>;默认出报告并修复,加 report 只出报告,加 sub 用子 agent',
61
+ 'cmd.status': '查看任务状态或最近结果',
62
+ 'cmd.cancel': '取消正在跑的任务',
63
+ 'hint.scope': '留空即整个项目;--files a.js,b.js;sub 隔离,report 只出计划',
64
+ 'hint.scrub': '留空即整个项目;--files <路径>;sub 隔离,report 只出报告',
65
+ 'hint.review': '留空审未提交改动;--files/--branch/--commit;sub 隔离,report 只出报告',
55
66
  'error.noCwd': '当前会话没有工作目录。',
56
67
  'error.noIdentity': '当前会话没有可用的会话标识,无法记录任务状态或做单飞保护。',
57
68
  'error.noProvider': '当前宿主缺少独立上下文的原生 spawn provider,无法运行独立 agent。',
@@ -74,6 +85,9 @@ const MESSAGES = {
74
85
  'status.last': '最近一次:',
75
86
  'status.interrupted': '上次任务有启动记录但没有完成报告,可以重新运行。',
76
87
  'status.submitted': '已提交到当前会话,结果在会话里:',
88
+ 'status.installed': '已装入 {command} 协议,没有后台任务在跑。',
89
+ 'status.ledgers': '台账 {count} 份,最近一份:',
90
+ 'status.noLedgers': '台账:还没有。',
77
91
  'cancel.none': '没有正在运行的代码工具箱任务。',
78
92
  'cancel.done': '已请求取消。',
79
93
  'report.verdict': '结论:',
@@ -99,19 +113,30 @@ const MESSAGES = {
99
113
  'mode.apply': 'apply(已改文件)',
100
114
  },
101
115
  en: {
102
- 'cmd.simplify': 'Simplify code without changing behavior; writes the whole project by default',
103
- 'cmd.review': 'Review a change and fix what it finds; add report for the report only',
104
- 'cmd.scrub': 'Find and redact secrets, credentials, and personal data; writes by default',
105
- 'cmd.caption': 'Run a hard task through the caption loop: one step, one proof, a ledger',
106
- 'hint.caption': 'Leave empty to continue the current task; or state the task and its acceptance criteria',
116
+ 'cmd.simplify': 'Simplify code without changing behavior',
117
+ 'cmd.review': 'Review a change and fix what it finds',
118
+ 'cmd.scrub': 'Remove secrets and personal data',
119
+ 'cmd.caption': 'Work a plan to completion, with a ledger',
120
+ 'hint.caption': 'Empty continues the current task; list shows ledgers, resume <name> continues one',
107
121
  'caption.installed': 'Caption loop installed: keep the ledger in {dir}, with a command and its result for every step.',
108
122
  'caption.reinstalled': 'The caption loop is already installed in this session; only the task was added. Ledger: {dir}.',
109
- 'cmd.audit': 'Audit what actually exists: trace every capability to storage and mark it wired/half/fake/broken/missing; read-only',
110
- 'hint.audit': 'Leave empty to audit the whole project; it reads a lot, so add sub for an isolated agent',
123
+ 'caption.steps': ' steps',
124
+ 'caption.planProgress': 'plan {done}/{total}',
125
+ 'caption.planBlocked': ' · {count} blocked',
126
+ 'caption.closed': ' · closed',
127
+ 'caption.listHead': 'Ledger directory: {dir}',
128
+ 'caption.listHint': 'Continue one with /code-caption resume <number|name>.',
129
+ 'caption.listEmpty': 'The ledger directory {dir} is empty; the first run creates one.',
130
+ 'caption.noLedgers': 'No ledgers yet — run /code-caption <task> first.',
131
+ 'caption.unknownLedger': 'No ledger named "{name}". Existing:',
132
+ 'caption.ambiguousLedger': '"{name}" matches several ledgers; use the number or the full name:',
133
+ 'caption.resumed': 'Continuing the ledger at {path}. Read its head and the last two entries first, then take the next step.',
134
+ 'cmd.audit': 'Audit whether a capability is really wired (read-only)',
135
+ 'hint.audit': 'Empty = whole project; add sub to run in an isolated agent (recommended)',
111
136
  'mode.audit': 'Report the five-state table and its evidence only. Change no files, and mark a capability you did not reach through its real entry point as unverified — never wired.',
112
137
  'audit.delivery': 'Your final reply is delivered as the audit result: one capability per row, with its state, its evidence (file:line), which link of the chain is missing, and what you could not verify.',
113
- 'cmd.design': 'Scenario-driven product design: four base maps, scenario cards, a batched plan; writes docs and stops for approval',
114
- 'hint.design': 'Leave empty for a half-day design; quick gives one page of conclusions, full gives the whole plan and appendix',
138
+ 'cmd.design': 'Turn a need into scenarios and a batched plan',
139
+ 'hint.design': 'Empty = half-day design; quick = one page, full = the whole plan',
115
140
  'design.installed': 'Scenario-driven design protocol installed: write the design documents under {dir}. It stops when the plan is ready and waits for approval — it never starts building by itself.',
116
141
  'design.reinstalled': 'The design protocol is already installed in this session; the documents go under {dir}. Continue under it.',
117
142
  'error.designDirectory': 'designDirectory cannot be empty.',
@@ -121,15 +146,15 @@ const MESSAGES = {
121
146
  'cmd.queuedSub': 'Handed to an isolated agent; scope: {scope}. The result arrives as a message when the run finishes.',
122
147
  'cmd.queuedPlan': 'Asked for a plan first; scope: {scope}, no files will change. Confirm it when it arrives, then run the command again to execute.',
123
148
  'cmd.queuedPlanSub': 'Asked the isolated agent for a plan first; scope: {scope}, no files will change. Confirm it when it arrives, then run the command again to execute.',
124
- 'cmd.pua': 'Install the PUA protocol in this session: change method, bring evidence, stop shrugging',
125
- 'hint.pua': 'Leave empty for the default flavor; or list / alibaba / huawei / musk',
149
+ 'cmd.pua': 'Install the no-shrugging protocol',
150
+ 'hint.pua': 'Empty uses the default flavor; list shows them all',
126
151
  'pua.installed': 'PUA protocol installed ({flavor}): two failures of the same kind mean change the method, and "done" needs a command and its output.',
127
152
  'pua.list': 'Available flavors:',
128
- 'cmd.status': 'Show code-toolkit task status or the latest result',
129
- 'cmd.cancel': 'Cancel the running code-toolkit task',
130
- 'hint.scope': 'Leave empty for the whole project on the current branch; or --files a.js,b.js / --branch main (which branch to compare against; the base by default) / --commit <sha> / custom instructions; add sub for a subagent, report for a plan only',
131
- 'hint.scrub': 'Leave empty for the whole project; or --files a.js,.env / custom instructions; add sub for a subagent, report for a plan only',
132
- 'hint.review': 'Leave empty to review the uncommitted work (or the branch against its base when clean); or --files / --branch <ref> / --commit <sha>; fixes what it finds by default — add report for the report only, sub for a subagent',
153
+ 'cmd.status': 'Show task status or the latest result',
154
+ 'cmd.cancel': 'Cancel the running task',
155
+ 'hint.scope': 'Empty = whole project; --files a.js,b.js; sub isolates, report = plan only',
156
+ 'hint.scrub': 'Empty = whole project; --files <path>; sub isolates, report only',
157
+ 'hint.review': 'Empty = uncommitted work; --files/--branch/--commit; sub isolates, report only',
133
158
  'error.noCwd': 'This session has no working directory.',
134
159
  'error.noIdentity': 'This session has no usable session id, so task state cannot be recorded or guarded.',
135
160
  'error.noProvider': 'This host has no independent-context native spawn provider, so no isolated agent can run.',
@@ -152,6 +177,9 @@ const MESSAGES = {
152
177
  'status.last': 'Last run: ',
153
178
  'status.interrupted': 'The previous run started but never finished; run it again.',
154
179
  'status.submitted': 'Submitted to this session; the result is in the conversation: ',
180
+ 'status.installed': 'Installed: the {command} protocol; nothing is running in the background.',
181
+ 'status.ledgers': '{count} ledger(s), most recent:',
182
+ 'status.noLedgers': 'Ledgers: none yet.',
155
183
  'cancel.none': 'No code-toolkit task is running.',
156
184
  'cancel.done': 'Cancellation requested.',
157
185
  'report.verdict': 'Verdict: ',