@morning-start/dsh-code-toolkit 0.28.1 → 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.
@@ -0,0 +1,71 @@
1
+ # The four steps, with the commands
2
+
3
+ ## Step 1 — the fork point
4
+
5
+ The facts block already carries it. To check it by hand:
6
+
7
+ ```powershell
8
+ git merge-base HEAD MERGE_HEAD # during a merge
9
+ git merge-base HEAD origin/dev # analysing a ref without merging
10
+ git log --oneline -1 $(git merge-base HEAD origin/dev)
11
+ ```
12
+
13
+ Two branches with no common ancestor have no baseline; say that and stop. `git merge-base
14
+ --fork-point` is about reflog drift, not about merges — do not use it here.
15
+
16
+ ## Step 2 — each side, from the base
17
+
18
+ ```powershell
19
+ git log --oneline --no-merges <base>..HEAD
20
+ git log --oneline --no-merges <base>..<theirs>
21
+ git diff --name-status <base>..HEAD
22
+ git diff --name-status <base>..<theirs>
23
+ ```
24
+
25
+ `--name-status` gives `M`/`A`/`D`/`R100`; a rename appears as two paths, and the new one is what
26
+ exists now. Do not use `git diff HEAD...<theirs>` here: the three-dot form already picks the base,
27
+ but it only shows one side, and it is easy to read as the whole story.
28
+
29
+ Read a patch with the base on the left, so both sides are in the same coordinates:
30
+
31
+ ```powershell
32
+ git diff -U3 <base>..HEAD -- <file>
33
+ git diff -U3 <base>..<theirs> -- <file>
34
+ ```
35
+
36
+ ## Step 3 — intent
37
+
38
+ Intent lives in two places and they disagree often:
39
+
40
+ - the commits (`git show --stat <sha>`) — what the author believed they were doing;
41
+ - the patch — what actually changed, including the parts the message forgot.
42
+
43
+ A commit that mixes three concerns is common ("task management + a new endpoint + column
44
+ rename"). Split it: name each concern and say which files it owns. That split is what makes the
45
+ next step decidable, because two sides usually collide on one concern and share nothing else.
46
+
47
+ ## Step 4 — comparing hunks in base coordinates
48
+
49
+ The facts block does this for you with `-U0`. If you need to redo it for one file:
50
+
51
+ ```powershell
52
+ git diff -U0 <base>..HEAD -- <file> | Select-String '^@@'
53
+ git diff -U0 <base>..<theirs> -- <file> | Select-String '^@@'
54
+ ```
55
+
56
+ `@@ -37,15 +37,20 @@` means: base lines 37–51 were replaced by 15 new lines from line 37. The numbers
57
+ after `-` are the only ones comparable across sides. Two hunks conflict when their base ranges
58
+ touch; they very often also conflict when they are *within six lines*, because each side's three
59
+ lines of context overlap the other's change.
60
+
61
+ ## After the plan is approved — proving the resolution
62
+
63
+ ```powershell
64
+ git diff --check # no leftover markers
65
+ git status --short # nothing still in UU/AA/DD
66
+ <the project's own gate> # the merge is not done because the markers are gone
67
+ ```
68
+
69
+ Resolving markers makes a tree that compiles; it does not make one that behaves. The gate is
70
+ whatever the repository already uses, and it has to run **after** the merge — a file can merge
71
+ cleanly and still be wrong, which is the next section's point.
@@ -0,0 +1,57 @@
1
+ # Reading the verdicts
2
+
3
+ ## conflict — same lines
4
+
5
+ Both sides replaced the same base lines. One of them wins on the page; the other must not lose
6
+ its intent. Write the resolution as three facts:
7
+
8
+ - what ours was doing here,
9
+ - what theirs was doing here,
10
+ - which one the merged file implements, and where the other intent goes (the other side's column
11
+ name kept, our structure kept; their endpoint, our validation).
12
+
13
+ If the two intents genuinely cannot coexist, that is not a merge decision — it is a product
14
+ decision. Stop, name the fork in one sentence, and ask.
15
+
16
+ ## conflict — contexts overlap
17
+
18
+ Neither side touched the same line, and git still conflicts because the context blocks collide.
19
+ This is the case people resolve by deleting the other side's hunk because the file "looked like
20
+ ours". It is also the case where both intents usually can coexist: merge by hand, keep both,
21
+ and reread the joined region as a whole — the seam is where the bug goes.
22
+
23
+ ## auto-merge, confirm semantics
24
+
25
+ Git merges it and nobody looks. The failure is semantic, not textual, and it has a signature:
26
+ **one side renames or re-scopes something the other side now depends on.** Examples from real
27
+ merges:
28
+
29
+ - they renamed a column `amm_doc_id → amm_version`; we added code that reads `amm_doc_id`;
30
+ - they changed a response shape; we added a field to the old shape;
31
+ - they moved a directory; our new imports point at the old path.
32
+
33
+ Check the shared file's *interface*, not its body: function signatures, column lists, request
34
+ schemas, exported names. If one side's change is only meaningful under the other's rename, it is a
35
+ real conflict and the report has to say so even though git stayed quiet.
36
+
37
+ ## Both sides rewrote one file
38
+
39
+ Take neither version. Reconstruct from the base:
40
+
41
+ ```powershell
42
+ git show <base>:<file> > base.tmp
43
+ git diff base.tmp <ours> <theirs> # three-way, by hand
44
+ ```
45
+
46
+ Then write the result by intent: every kept line should trace to one side's intent, and every
47
+ dropped line should be named in the report as dropped on purpose. A file that ends up as one
48
+ side's version with the other side's lines pasted in is the usual outcome, and it is fine — as
49
+ long as the report says which is which.
50
+
51
+ ## What is never a resolution
52
+
53
+ - `git checkout --ours <file>` on a file whose other-side content you have not read;
54
+ - deleting a hunk because "we didn't need it" without naming the intent it served;
55
+ - resolving markers and calling it done before the repository's gate has run on the merged tree;
56
+ - dropping a side's commit or file wholesale because the two branches "changed everything" — with
57
+ a fork-point baseline, that claim is almost always false.
@@ -9,8 +9,11 @@ The task tells you which mode you are in.
9
9
 
10
10
  - **dry-run** — report only. Change no files; the report is the product.
11
11
  - **apply** — report **and** fix. Review first, then fix the findings you are sure of,
12
- one at a time, re-running the gate after each. A finding you cannot prove stays a
13
- finding; a fix that turns the gate red is reverted and reported as unfixed.
12
+ one at a time, re-running the gate after each.
13
+
14
+ **Every fix has a written finding behind it** — an edit with no finding is an unreviewed
15
+ change, however obvious it looks. A finding you cannot prove stays a finding; a fix that
16
+ turns the gate red is reverted and reported as unfixed.
14
17
 
15
18
  In apply mode the report still comes first: the person reads what you found before what
16
19
  you changed. Fixes go under `fixed`, everything you left alone stays under `findings`.
@@ -103,9 +103,11 @@ reads oddly for a scrub, but the renderer only shows the verdict and the finding
103
103
  **In-session** (the brief says so): write the same rows as a Markdown table instead —
104
104
  masked value, `path:line`, priority, one-line reason. Do not send both.
105
105
 
106
- **Apply** — produce the dry-run JSON first, make the redactions described in
107
- `references/redaction.md`, then return a Markdown report: what was redacted (was →
108
- now → verified by), the verification command and result, and what was not handled.
106
+ **Apply** — the plan first: the dry-run JSON and the redaction list it implies, with each
107
+ masked value. Then make them (`references/redaction.md`), and return a Markdown report:
108
+ what was redacted (was → masked → verified by), the verification command and result, and
109
+ what was not handled. While you work, `todo_write` mirrors the redaction list — one entry per
110
+ secret, `in_progress` for the one you are on — when the session has that tool.
109
111
 
110
112
  Rotating a leaked credential is not something you can do from here. Say so in every
111
113
  report that contains one: redaction fixes the working tree, not the history and not the
@@ -73,11 +73,14 @@ The task tells you which mode you are in.
73
73
 
74
74
  - **dry-run** — change no files. Produce the plan and the argument that behaviour is
75
75
  unchanged.
76
- - **apply** — establish the gate **before the first edit**: the project's tests, or a
77
- characterization baseline when there are none (`references/verification.md`). Apply
78
- one item or file group at a time, re-run the gate after each, revert that batch if it
79
- fails. If no gate can be established, **do not apply** — return the plan and say
80
- exactly what is missing.
76
+ - **apply** — **the plan comes first and in writing**: for each item, what it is now, what
77
+ it becomes, and the argument that behaviour is unchanged. Then establish the gate (the
78
+ project's tests, or a characterization baseline when there are none —
79
+ `references/verification.md`), and only then edit. Apply one item or file group at a
80
+ time, re-run the gate after each, revert that batch if it fails. If no gate can be
81
+ established, **do not apply** — return the plan and say exactly what is missing. Keep the
82
+ person's list current while you work: `todo_write` from the plan, one item `in_progress`, when
83
+ the session has that tool.
81
84
 
82
85
  ## Editing
83
86
 
@@ -103,8 +106,9 @@ Follow the structure the examples use; the fields below are the contract.
103
106
  - **Plan (dry-run)**: scope, **`Files read in full`** and `searched only` counts, a gate
104
107
  or "none available", then one entry per point — `type`, `now`, `change to`, `why
105
108
  behaviour is unchanged`, `risk`. A file you only grepped is never "read in full".
106
- - **Apply**: one entry per change — `type`, `change`, `verified by` — then the gate and
107
- its result.
109
+ - **Apply**: the plan you executed — one entry per item with `now`, `change to`, and why
110
+ behaviour is unchanged — then what was actually done (`change`, `verified by`), then the
111
+ gate and its result. A change with no plan entry above it is drift.
108
112
  - **Not handled** (both): `defect`, **`behaviour-risk`**, `too-big`, `intentional`, each
109
113
  with its file:line and why it is not this task.
110
114
 
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.28.1",
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.',