@morning-start/dsh-code-toolkit 0.29.0 → 0.31.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/index.js CHANGED
@@ -6,6 +6,7 @@ import { outputLanguage, readHostLocale, resolveLocale, translate } from './src/
6
6
  import { sessionKey } from './src/identity.js'
7
7
  import { Journal } from './src/journal.js'
8
8
  import { parseReport, renderReport } from './src/report.js'
9
+ import { collectMergeFacts, renderMergeFacts } from './src/merge.js'
9
10
  import { buildPua, flavorList, resolveFlavor } from './src/pua.js'
10
11
  import { buildDesignText, resolveDesignInput } from './src/design.js'
11
12
  import { listLedgers, resolveLedger, splitCaptionInput } from './src/caption.js'
@@ -55,6 +56,13 @@ export function apply(ctx, config = {}) {
55
56
  if (config.designDirectory !== undefined && !String(config.designDirectory).trim()) {
56
57
  throw new Error(translate(fallbackLocale, 'error.designDirectory'))
57
58
  }
59
+ // 0 means "do not open a goal"; anything else is the continuation-round cap.
60
+ if (config.goalRounds !== undefined) {
61
+ const rounds = Number(config.goalRounds)
62
+ if (!Number.isInteger(rounds) || rounds < 0) {
63
+ throw new Error(translate(fallbackLocale, 'error.goalRounds'))
64
+ }
65
+ }
58
66
 
59
67
  const journal = new Journal(config.reportDirectory ?? Journal.defaultDirectory())
60
68
  const personas = {
@@ -63,6 +71,7 @@ export function apply(ctx, config = {}) {
63
71
  scrub: loadPersona('scrub'),
64
72
  caption: loadPersona('caption'),
65
73
  audit: loadPersona('audit'),
74
+ merge: loadPersona('merge'),
66
75
  design: loadPersona('design'),
67
76
  pua: loadPersona('pua'),
68
77
  }
@@ -97,13 +106,14 @@ export function apply(ctx, config = {}) {
97
106
 
98
107
  /** One ledger as a list line: what it is, how far the plan got, whether it closed. */
99
108
  const describeLedger = (ledger, t) => {
100
- const plan = ledger.plan ?? { total: 0, done: 0, blocked: 0 }
109
+ const plan = ledger.plan ?? { total: 0, done: 0, blocked: 0, inFlight: 0 }
101
110
  const progress = plan.total
102
111
  ? t('caption.planProgress').replace('{done}', String(plan.done)).replace('{total}', String(plan.total))
103
112
  : `${ledger.entries.length}${t('caption.steps')}`
113
+ const flying = plan.inFlight ? t('caption.planInFlight').replace('{count}', String(plan.inFlight)) : ''
104
114
  const blocked = plan.blocked ? t('caption.planBlocked').replace('{count}', String(plan.blocked)) : ''
105
115
  const name = ledger.title ? `${ledger.slug} — ${ledger.title}` : ledger.slug
106
- return `${name} · ${progress}${blocked}${ledger.closed ? t('caption.closed') : ''}`
116
+ return `${name} · ${progress}${flying}${blocked}${ledger.closed ? t('caption.closed') : ''}`
107
117
  }
108
118
 
109
119
  /** The ledger tail a status answer appends after an injected protocol. */
@@ -121,6 +131,16 @@ export function apply(ctx, config = {}) {
121
131
  running,
122
132
  runTimeoutMs: minutesToMs(config.runTimeoutMinutes, 30, 'error.runTimeout'),
123
133
  planMaxAgeMs: minutesToMs(config.planMaxAgeMinutes, 60, 'error.planMaxAge'),
134
+ /**
135
+ * `ctx.goals` opened rather than required. The goal *tool* refuses a call that did not
136
+ * come from a human turn (`hasDirectHumanInput`), and a plugin-delivered message carries
137
+ * this plugin's own source kind — so caption can never open a goal by asking the model to.
138
+ * The service has no such guard, and the authority here is the person's own `/code-caption`
139
+ * keystroke: the command acts for them. Declaring `goals` in `inject` would make an older
140
+ * host that lacks it refuse to load the plugin, so it is read optionally.
141
+ */
142
+ goals: typeof ctx.get === 'function' ? ctx.get('goals') : undefined,
143
+ goalRounds: config.goalRounds === undefined ? 8 : Number(config.goalRounds),
124
144
  localeNow,
125
145
  ledgerDirectory,
126
146
  designDirectory,
@@ -189,6 +209,35 @@ export function apply(ctx, config = {}) {
189
209
  dryRunKey: 'mode.audit',
190
210
  deliveryKey: 'audit.delivery',
191
211
  }, host),
212
+ new SessionCommand({
213
+ name: 'code-merge',
214
+ command: 'merge',
215
+ descriptionKey: 'cmd.merge',
216
+ hintKey: 'hint.merge',
217
+ persona: personas.merge,
218
+ // Read-only by construction: the deliverable is the analysis and the plan, and a merge
219
+ // resolved by a model without a person reading the plan is exactly the failure this
220
+ // command exists to prevent. No apply path, like the audit.
221
+ forceDryRun: true,
222
+ defaultScope: 'project',
223
+ dryRunKey: 'mode.merge',
224
+ deliveryKey: 'merge.delivery',
225
+ // The conflict set is computed here, from the fork point; the persona judges intent.
226
+ // A branch-vs-branch diff answers the wrong question, so it is never asked for.
227
+ facts: async ({ scope, cwd, signal }) => {
228
+ try {
229
+ return renderMergeFacts(await collectMergeFacts({ cwd, signal, ref: scope?.ref }))
230
+ } catch (error) {
231
+ return [
232
+ '## Merge facts',
233
+ '',
234
+ `- unavailable: ${error.message}`,
235
+ '- There is no merge in progress and no ref was given. Do not guess a baseline: ask',
236
+ ' which ref to analyse (`/code-merge origin/dev`), or say the merge state is unclear.',
237
+ ].join('\n')
238
+ }
239
+ },
240
+ }, host),
192
241
  new SessionCommand({
193
242
  name: 'code-caption',
194
243
  command: 'caption',
@@ -196,6 +245,31 @@ export function apply(ctx, config = {}) {
196
245
  descriptionKey: 'cmd.caption',
197
246
  hintKey: 'hint.caption',
198
247
  persona: personas.caption,
248
+ // The two decisions a caption run makes about itself go into a system section as well as
249
+ // the steered message: a long session compacts the message away, and losing these two
250
+ // rules looks exactly like "it never opens a goal and never splits the work".
251
+ systemNote: () => [
252
+ '## Code toolkit: caption run',
253
+ '',
254
+ 'A caption loop is installed in this session. Two decisions in it are yours, and you take',
255
+ "them from the plan rather than from the person's wording:",
256
+ '',
257
+ '- **The goal.** This command already opened one for the run (`get_goal`). Do not call',
258
+ ' `create_goal` for a second; close it with `update_goal complete` once the criteria are',
259
+ ' proven — even if the work turned out to be a single turn.',
260
+ '- **The wave.** When two or more ready items touch disjoint paths, each with its own gate',
261
+ ' and more than a one-line edit, dispatch them together with `subagent` in one message.',
262
+ '',
263
+ 'The ledger under `docs/caption/` is authoritative: read it before each step, tick an item',
264
+ 'only with the entry that proves it, and keep `todo_write` mirroring it.',
265
+ ].join('\n'),
266
+ // The objective is the person's own task line. The command already carries the human
267
+ // authority a goal needs; the ledger path is where the plan and criteria land.
268
+ goalObjective: ({ rawInput }) => {
269
+ const task = String(rawInput ?? '').trim()
270
+ if (!task) return null
271
+ return `${task}\n\nWork through the caption loop: the plan, the criteria and every proof go in the ledger under docs/caption/.`
272
+ },
199
273
  // A project accumulates ledgers, and "continue the current task" stops
200
274
  // meaning anything once there are five of them. `list` and `resume <name>`
201
275
  // read the ledger directory before anything is injected.
package/locale/en.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "meta": {
3
3
  "title": "Code toolkit",
4
- "description": "Seven commands that work with no arguments: review and fix, simplify, scrub, capability audit, a caption loop with a plan and a ledger, scenario-driven design, and a PUA protocol. Add sub for an isolated agent, report for a report only."
4
+ "description": "Eight commands that work with no arguments: review and fix, simplify, scrub, capability audit, merge-conflict analysis from the fork point, a caption loop with a plan and a ledger, scenario-driven design, and a PUA protocol. Add sub for an isolated agent, report for a report only."
5
5
  }
6
6
  }
package/locale/zh.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "meta": {
3
3
  "title": "代码工具箱",
4
- "description": "七条命令,空输入即可用:审查与修复、精炼、隐私清理、能力审计、caption 循环(计划清单 + 台账)、场景驱动设计、PUA 协议。加 sub 换独立 agent,加 report 只出报告。"
4
+ "description": "八条命令,空输入即可用:审查与修复、精炼、隐私清理、能力审计、合并冲突分析(以分叉点为基线)、caption 循环(计划清单 + 台账)、场景驱动设计、PUA 协议。加 sub 换独立 agent,加 report 只出报告。"
5
5
  }
6
6
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@morning-start/dsh-code-toolkit",
3
- "version": "0.29.0",
3
+ "version": "0.31.0",
4
4
  "private": false,
5
5
  "publishConfig": {
6
6
  "access": "public",
package/src/caption.js CHANGED
@@ -25,7 +25,7 @@ const PLAN_ITEM = /^\s*-\s*\[([ xX~-])\]\s*(.+)$/
25
25
  */
26
26
  export function parsePlan(lines) {
27
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: [] }
28
+ if (start === -1) return { total: 0, done: 0, open: 0, blocked: 0, dropped: 0, inFlight: 0, ready: 0, items: [] }
29
29
 
30
30
  const items = []
31
31
  for (let index = start + 1; index < lines.length; index += 1) {
@@ -33,19 +33,34 @@ export function parsePlan(lines) {
33
33
  const match = PLAN_ITEM.exec(lines[index])
34
34
  if (!match) continue
35
35
  const mark = match[1].toLowerCase()
36
+ const body = match[2].trim()
37
+ // `deps` and `owner` are what make the plan a graph instead of a wish list: ready
38
+ // items are derived from them, not guessed. Both are optional, so old ledgers parse.
39
+ const deps = /(?:^|\|)\s*deps\s*:\s*([\d,\s]+)/i.exec(body)
40
+ const owner = /(?:^|\|)\s*owner\s*:\s*([^|]+)/i.exec(body)
41
+ const number = /^(\d+)\./.exec(body)
36
42
  items.push({
37
43
  status: mark === 'x' ? 'done' : mark === '~' ? 'blocked' : mark === '-' ? 'dropped' : 'open',
38
- text: match[2].trim(),
44
+ number: number ? Number(number[1]) : items.length + 1,
45
+ deps: deps ? deps[1].split(',').map((part) => Number(part.trim())).filter(Number.isFinite) : [],
46
+ owner: owner ? owner[1].trim() : '',
47
+ text: body,
39
48
  })
40
49
  }
41
50
 
42
51
  const count = (status) => items.filter((item) => item.status === status).length
52
+ const done = new Set(items.filter((item) => item.status === 'done').map((item) => item.number))
53
+ const open = items.filter((item) => item.status === 'open')
43
54
  return {
44
55
  total: items.length,
45
56
  done: count('done'),
46
- open: count('open'),
57
+ open: open.length,
47
58
  blocked: count('blocked'),
48
59
  dropped: count('dropped'),
60
+ /** Open items already handed to a child — a resumed run must collect, not re-dispatch. */
61
+ inFlight: open.filter((item) => item.owner).length,
62
+ /** Open items nothing blocks: the next wave, computed rather than felt. */
63
+ ready: open.filter((item) => !item.owner && item.deps.every((dep) => done.has(dep))).length,
49
64
  items,
50
65
  }
51
66
  }
package/src/command.js CHANGED
@@ -3,6 +3,20 @@ import { failureMessage, reportMessage, userMessage, SOURCE_KIND } from './deliv
3
3
  import { outputLanguage } from './i18n.js'
4
4
  import { sessionKey } from './identity.js'
5
5
 
6
+ /**
7
+ * System-prompt section that carries an injected run's decision rules.
8
+ *
9
+ * A child agent gets its persona as a system section (see `src/runtime.js`). An injected run
10
+ * used to get the protocol only as a steered user message, which competes with everything else
11
+ * in a long session and can be summarized away by a compaction. The rules that must not drift —
12
+ * when to open a goal, when to split into a wave — go here; the full protocol stays in the
13
+ * message, where it is readable and auditable.
14
+ */
15
+ const PROTOCOL_SECTION = 'CODE_TOOLKIT_PROTOCOL'
16
+
17
+ /** One section per agent; a second run replaces its own instead of stacking a copy. */
18
+ const PROTOCOL_DISPOSERS = new WeakMap()
19
+
6
20
  /**
7
21
  * The receipt names where the task went and what it will do: the current
8
22
  * session or an isolated agent, a plan or an edit. A bare "submitted" leaves the
@@ -85,6 +99,9 @@ export class SessionCommand {
85
99
  // the next load. Build it the same way every other delivery does.
86
100
  await agent.steer(userMessage(spec.buildText({ rawInput, agent, locale, host, installed })))
87
101
 
102
+ const noteInstalled = this.installSystemNote(agent, { installed })
103
+ const goalOpened = this.armGoal(agent, { rawInput })
104
+
88
105
  if (sessionId) {
89
106
  await host.journal
90
107
  .write(sessionId, {
@@ -95,12 +112,65 @@ export class SessionCommand {
95
112
  .catch(() => undefined)
96
113
  }
97
114
 
115
+ // The suffix is the only way the person can see which carrier the session actually got:
116
+ // a host without the service falls back to the message alone, silently otherwise.
117
+ const carrier = noteInstalled ? t('cmd.systemNoteOn') : ''
118
+ const goal = goalOpened ? t('cmd.goalOpened').replace('{rounds}', String(host.goalRounds)) : ''
98
119
  return {
99
120
  kind: 'success',
100
- text: installed ? spec.receipt(rawInput, t, true, agent) : spec.receipt(rawInput, t, false, agent),
121
+ text: (installed ? spec.receipt(rawInput, t, true, agent) : spec.receipt(rawInput, t, false, agent)) + carrier + goal,
101
122
  }
102
123
  }
103
124
 
125
+ /**
126
+ * Open the run's goal through `ctx.goals`.
127
+ *
128
+ * The goal *tool* is unusable here: it requires a `user/message` whose `source.kind` is
129
+ * `user`, and this plugin's deliveries carry the plugin's own kind. The service has no such
130
+ * guard, and the authority is the person's command — the same authority that lets this shell
131
+ * register the command at all. A failure is not fatal: the ledger still carries the run.
132
+ */
133
+ armGoal(agent, { rawInput }) {
134
+ const { spec, host } = this
135
+ if (typeof spec.goalObjective !== 'function' || !host.goalRounds) return false
136
+ const goals = host.goals
137
+ if (typeof goals?.create !== 'function') return false
138
+ try {
139
+ // One goal per session: the service throws on a second one, and an existing goal is a
140
+ // reason to continue it, not to replace it.
141
+ if (goals.get?.(agent)) return false
142
+ const objective = spec.goalObjective({ rawInput, agent })
143
+ if (!objective) return false
144
+ goals.create(agent, { objective, maxGoalRounds: host.goalRounds })
145
+ return true
146
+ } catch {
147
+ return false
148
+ }
149
+ }
150
+
151
+ /**
152
+ * Put the run's decision rules where they cannot decay: a system section, the same carrier
153
+ * an isolated child gets. A host without the service, or an agent without a context, is left
154
+ * alone — the steered protocol is still there, just weaker.
155
+ */
156
+ installSystemNote(agent, { installed }) {
157
+ const { spec } = this
158
+ if (typeof spec.systemNote !== 'function') return false
159
+ const prompts = agent?.ctx?.systemPrompt
160
+ if (typeof prompts?.section !== 'function') return false
161
+ const text = spec.systemNote({ installed })
162
+ if (!text) return false
163
+ // Replace, never stack: two copies of the same rules is a reason to disagree with itself.
164
+ PROTOCOL_DISPOSERS.get(agent)?.()
165
+ const dispose = prompts.section({
166
+ name: PROTOCOL_SECTION,
167
+ order: prompts.getSectionOrder?.(PROTOCOL_SECTION) ?? 0,
168
+ text,
169
+ })
170
+ PROTOCOL_DISPOSERS.set(agent, typeof dispose === 'function' ? dispose : () => {})
171
+ return true
172
+ }
173
+
104
174
  /** Scope-based task: inline by default, isolated with `sub`. */
105
175
  task(agent, rawInput, signal, locale, t) {
106
176
  const { sub, report, rest } = splitFlags(rawInput)
@@ -339,6 +409,7 @@ export class SessionCommand {
339
409
  personaLine,
340
410
  '',
341
411
  await scopeInstruction(scope, { cwd, signal }),
412
+ ...(spec.facts ? ['', await spec.facts({ scope, cwd, signal, locale })] : []),
342
413
  '',
343
414
  chinese ? `模式:${mode}。` : `Mode: ${mode}.`,
344
415
  modeLine,
package/src/i18n.js CHANGED
@@ -26,11 +26,16 @@ const MESSAGES = {
26
26
  'cmd.scrub': '清理密钥与隐私信息',
27
27
  'cmd.caption': '按计划清单跑到完成,过程落台账',
28
28
  'hint.caption': '留空继续当前任务;list 列台账,resume <名字> 接续',
29
+ 'cmd.merge': '以分叉点为基线分析一次多人合并,出合并方案',
30
+ 'hint.merge': '留空分析正在进行的合并;给一个 ref 则先算它的分叉点,例如 /code-merge origin/dev',
31
+ 'mode.merge': '只出分析和方案:不要改文件、不要解决冲突标记、不要 checkout。方案等人批。',
32
+ 'merge.delivery': '最终回复会原样发给用户:写清分叉点、两侧各自的意图、共享文件每个怎么处置、以及合并之外必须跟进的事(DDL、视图、文档、接口契约)。只写文件数或目录名不算分析。',
29
33
  'caption.installed': '已装入 caption 循环:台账写到 {dir},每一步都要有命令和它的结果。',
30
34
  'caption.reinstalled': 'caption 循环已在本次会话里,只补了任务:台账 {dir},继续按循环走。',
31
35
  'caption.steps': ' 步',
32
36
  'caption.planProgress': '计划 {done}/{total}',
33
37
  'caption.planBlocked': ' · {count} 项受阻',
38
+ 'caption.planInFlight': ' · {count} 项在飞',
34
39
  'caption.closed': ' · 已收口',
35
40
  'caption.listHead': '台账目录:{dir}',
36
41
  'caption.listHint': '用 /code-caption resume <序号|名字> 继续一份。',
@@ -54,6 +59,9 @@ const MESSAGES = {
54
59
  'cmd.queuedSub': '已交给独立子 agent,范围:{scope};完成后结果会作为一条消息发回。',
55
60
  'cmd.queuedPlan': '已请它先出方案,范围:{scope},不改任何文件;方案回来后你确认,再执行。',
56
61
  'cmd.queuedPlanSub': '已请独立子 agent 先出方案,范围:{scope},不改任何文件;方案回来后你确认,再执行。',
62
+ 'cmd.systemNoteOn': ' · 两条决策规则已装进系统提示(不随压缩丢失)',
63
+ 'cmd.goalOpened': ' · 已替你在本会话开目标(最多 {rounds} 轮自动续跑,`update_goal complete` 收口)',
64
+ 'error.goalRounds': 'goalRounds 必须是 0 或正整数(0 表示不自动开目标)。',
57
65
  'cmd.pua': '装上「不许敷衍」的协议',
58
66
  'hint.pua': '留空用默认风味;list 查看全部',
59
67
  'pua.installed': '已装上 PUA 协议({flavor}):同类尝试失败两次就换方法,说完成必须给出命令和输出。',
@@ -118,11 +126,16 @@ const MESSAGES = {
118
126
  'cmd.scrub': 'Remove secrets and personal data',
119
127
  'cmd.caption': 'Work a plan to completion, with a ledger',
120
128
  'hint.caption': 'Empty continues the current task; list shows ledgers, resume <name> continues one',
129
+ 'cmd.merge': 'Analyse a multi-person merge from its fork point, and propose the plan',
130
+ 'hint.merge': 'Empty analyses the merge in progress; a ref computes its fork point, e.g. /code-merge origin/dev',
131
+ 'mode.merge': 'Report the analysis and the plan only: change no file, resolve no marker, check nothing out. The plan waits for a person.',
132
+ 'merge.delivery': 'Your final reply is delivered verbatim: the fork point, each side\'s intent, how each shared file is settled, and what must follow outside git (DDL, views, docs, API contracts). File counts and directory names are not an analysis.',
121
133
  'caption.installed': 'Caption loop installed: keep the ledger in {dir}, with a command and its result for every step.',
122
134
  'caption.reinstalled': 'The caption loop is already installed in this session; only the task was added. Ledger: {dir}.',
123
135
  'caption.steps': ' steps',
124
136
  'caption.planProgress': 'plan {done}/{total}',
125
137
  'caption.planBlocked': ' · {count} blocked',
138
+ 'caption.planInFlight': ' · {count} in flight',
126
139
  'caption.closed': ' · closed',
127
140
  'caption.listHead': 'Ledger directory: {dir}',
128
141
  'caption.listHint': 'Continue one with /code-caption resume <number|name>.',
@@ -146,6 +159,9 @@ const MESSAGES = {
146
159
  'cmd.queuedSub': 'Handed to an isolated agent; scope: {scope}. The result arrives as a message when the run finishes.',
147
160
  '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.',
148
161
  '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.',
162
+ 'cmd.systemNoteOn': ' · both decision rules are now a system section, so a compaction cannot drop them',
163
+ 'cmd.goalOpened': ' · goal opened for this session (up to {rounds} continuation rounds; `update_goal complete` ends it)',
164
+ 'error.goalRounds': 'goalRounds must be 0 or a positive integer (0 disables opening a goal).',
149
165
  'cmd.pua': 'Install the no-shrugging protocol',
150
166
  'hint.pua': 'Empty uses the default flavor; list shows them all',
151
167
  'pua.installed': 'PUA protocol installed ({flavor}): two failures of the same kind mean change the method, and "done" needs a command and its output.',
package/src/merge.js ADDED
@@ -0,0 +1,150 @@
1
+ import { git, mergeBase } from './selection.js'
2
+
3
+ /**
4
+ * Merge analysis with the fork point as the baseline.
5
+ *
6
+ * Comparing "my branch" against "their branch" answers the wrong question: it lists every
7
+ * difference, most of which is not a conflict at all. Two sides that changed different files
8
+ * cannot collide. What matters is three facts, and all three are computed here rather than
9
+ * eyeballed:
10
+ *
11
+ * 1. the merge base (the fork point),
12
+ * 2. what each side changed *relative to that base*,
13
+ * 3. for the files both sides touched, whether their hunks cover the same base lines.
14
+ *
15
+ * Line numbers from `-U0` are base coordinates, so a hunk from each side can be compared
16
+ * directly. Context is what makes git report a conflict next to a change it could not merge,
17
+ * so "adjacent" counts as real: two hunks six lines apart have their context blocks touching.
18
+ */
19
+
20
+ /** Files changed by one diff, as `{ status, path }`, renames resolved to the new path. */
21
+ export function parseNameStatus(text) {
22
+ const files = []
23
+ for (const line of String(text ?? '').split('\n')) {
24
+ if (!line.trim()) continue
25
+ const [status, first, second] = line.split('\t')
26
+ if (!status) continue
27
+ // R100/C100 carry two paths; the new path is the one that exists now.
28
+ files.push({ status: status.trim(), path: (second ?? first ?? '').trim() })
29
+ }
30
+ return files
31
+ }
32
+
33
+ /** Split a `git diff -U0` into `{ path -> [{ start, end }] }` in base-line coordinates. */
34
+ export function parseHunks(text) {
35
+ const hunks = new Map()
36
+ let path = ''
37
+ for (const line of String(text ?? '').split('\n')) {
38
+ if (line.startsWith('+++ b/')) {
39
+ path = line.slice('+++ b/'.length).trim()
40
+ if (!hunks.has(path)) hunks.set(path, [])
41
+ continue
42
+ }
43
+ const header = /^@@ -(\d+)(?:,(\d+))? \+\d+(?:,\d+)? @@/.exec(line)
44
+ if (!header || !path) continue
45
+ const start = Number(header[1])
46
+ const count = header[2] === undefined ? 1 : Number(header[2])
47
+ // A pure deletion reports `-37,0`: it occupies no base line, but it still sits at 37.
48
+ const end = count === 0 ? start : start + count - 1
49
+ hunks.get(path).push({ start, end })
50
+ }
51
+ return hunks
52
+ }
53
+
54
+ /**
55
+ * How two sides' hunks relate, in base coordinates.
56
+ *
57
+ * `same` — they cover common lines: git will conflict and a person must choose.
58
+ * `adjacent` — no shared line, but within one context block (6 lines, both sides): git will
59
+ * still conflict, because the merged context around them overlaps.
60
+ * `separate` — different regions of the same file: git merges them, but the *semantics* are
61
+ * still worth one read, since both sides changed one file for possibly conflicting reasons.
62
+ */
63
+ export function classify(ours, theirs) {
64
+ let verdict = 'separate'
65
+ for (const a of ours) {
66
+ for (const b of theirs) {
67
+ const gap = Math.max(a.start, b.start) - Math.min(a.end, b.end)
68
+ if (gap <= 0) return 'same'
69
+ if (gap <= 6) verdict = 'adjacent'
70
+ }
71
+ }
72
+ return verdict
73
+ }
74
+
75
+ const side = (hunks) => hunks.map((h) => (h.start === h.end ? `${h.start}` : `${h.start}-${h.end}`)).join(', ')
76
+
77
+ /**
78
+ * Collect everything the merge report needs. Throws when there is nothing to merge, because
79
+ * "no merge in progress and no ref given" is a usage error, not an empty report.
80
+ */
81
+ export async function collectMergeFacts({ cwd, ref, signal }) {
82
+ let theirs = ref
83
+ if (!theirs) {
84
+ theirs = (await git(cwd, ['rev-parse', '--verify', 'MERGE_HEAD'], signal)).trim()
85
+ }
86
+ const ours = 'HEAD'
87
+ const base = (await mergeBase(cwd, theirs, signal)).trim()
88
+
89
+ const [oursFiles, theirFiles] = await Promise.all([
90
+ git(cwd, ['diff', '--name-status', `${base}..${ours}`], signal).then(parseNameStatus),
91
+ git(cwd, ['diff', '--name-status', `${base}..${theirs}`], signal).then(parseNameStatus),
92
+ ])
93
+ const ourPaths = new Map(oursFiles.map((file) => [file.path, file.status]))
94
+ const theirPaths = new Map(theirFiles.map((file) => [file.path, file.status]))
95
+ const shared = [...ourPaths.keys()].filter((path) => theirPaths.has(path)).sort()
96
+ const onlyOurs = [...ourPaths.keys()].filter((path) => !theirPaths.has(path)).length
97
+ const onlyTheirs = [...theirPaths.keys()].filter((path) => !ourPaths.has(path)).length
98
+
99
+ const rows = []
100
+ for (const path of shared) {
101
+ const [ourDiff, theirDiff] = await Promise.all([
102
+ git(cwd, ['diff', '-U0', `${base}..${ours}`, '--', path], signal),
103
+ git(cwd, ['diff', '-U0', `${base}..${theirs}`, '--', path], signal),
104
+ ])
105
+ const ourHunks = parseHunks(ourDiff).get(path) ?? []
106
+ const theirHunks = parseHunks(theirDiff).get(path) ?? []
107
+ rows.push({ path, verdict: classify(ourHunks, theirHunks), ours: side(ourHunks), theirs: side(theirHunks) })
108
+ }
109
+
110
+ return {
111
+ ours,
112
+ theirs,
113
+ base,
114
+ counts: { ours: oursFiles.length, theirs: theirFiles.length, shared: shared.length, onlyOurs, onlyTheirs },
115
+ rows,
116
+ real: rows.filter((row) => row.verdict !== 'separate').length,
117
+ auto: rows.filter((row) => row.verdict === 'separate').length,
118
+ }
119
+ }
120
+
121
+ /** The facts block the report is written against; computed, never guessed. */
122
+ export function renderMergeFacts(facts) {
123
+ const { counts } = facts
124
+ const lines = [
125
+ '## Merge facts (computed from the fork point — do not re-derive these by eye)',
126
+ '',
127
+ `- Fork point (merge base): \`${facts.base.slice(0, 12)}\``,
128
+ `- Ours: \`${facts.ours}\`; theirs: \`${facts.theirs}\``,
129
+ `- Ours changed ${counts.ours} files, theirs changed ${counts.theirs}.`,
130
+ `- **Shared: ${counts.shared}** — the only files that can conflict.`,
131
+ `- Ours-only ${counts.onlyOurs}, theirs-only ${counts.onlyTheirs}: disjoint by construction, each side keeps its own; do not propose touching them.`,
132
+ '',
133
+ ]
134
+ if (!facts.rows.length) {
135
+ lines.push('No shared file: this merge has no textual conflict. Say so and stop.')
136
+ return lines.join('\n')
137
+ }
138
+ lines.push(`Real conflicts: **${facts.real}**; same-file-different-region: ${facts.auto}.`, '')
139
+ lines.push('| file | ours (base lines) | theirs (base lines) | verdict |')
140
+ lines.push('| --- | --- | --- | --- |')
141
+ for (const row of facts.rows) {
142
+ const verdict = row.verdict === 'same'
143
+ ? '**conflict — same lines**'
144
+ : row.verdict === 'adjacent'
145
+ ? '**conflict — contexts overlap**'
146
+ : 'auto-merge, confirm semantics'
147
+ lines.push(`| ${row.path} | ${row.ours || '—'} | ${row.theirs || '—'} | ${verdict} |`)
148
+ }
149
+ return lines.join('\n')
150
+ }