@miphamai/cli 0.85.34 → 0.85.36

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/README.md CHANGED
@@ -1,6 +1,6 @@
1
- # Mipham Code v0.85.34
1
+ # Mipham Code v0.85.36
2
2
 
3
- **Multi-model open-core intelligent coding terminal** — 12 AI providers, 138 commands, 31 tools, 28 skills + marketplace, self-update. AI-assisted code generation, security auditing, MCP protocol, and extensible skills — in a single CLI.
3
+ **Multi-model open-core intelligent coding terminal** — 12 AI providers, 139 commands, 31 tools, 28 skills + marketplace, self-update. AI-assisted code generation, security auditing, MCP protocol, and extensible skills — in a single CLI.
4
4
 
5
5
  Built by [One Mipham Corporation](https://onemipham.com) (北京华安麦逄科技有限公司) | Brand: MiphamAI
6
6
 
@@ -16,7 +16,7 @@ Requirements: **Bun 1.2+** (recommended) or **Node.js 22+**
16
16
  ## Features
17
17
 
18
18
  - **12 AI Providers** — Anthropic Claude · OpenAI GPT · DeepSeek · Kimi (Moonshot) · Google Gemini · Doubao 豆包 · Tencent Hunyuan 混元 · Qwen 通义千问 · MiniMax(国内 / 国际)· Ollama(本地)· MiphamAI
19
- - **138 Slash Commands** — Interactive command picker (↑↓ Enter Esc), intuitive command interface, zero re-learning
19
+ - **139 Slash Commands** — Interactive command picker (↑↓ Enter Esc), intuitive command interface, zero re-learning
20
20
  - **31 Built-in Tools** — File ops, shell execution, agent dispatch, MCP integration, web search
21
21
  - **28 Skills + Marketplace** — 22 standard + 6 Mipham-exclusive skills. `/browse-skills` `/install-skill` community marketplace
22
22
  - **Self-Update** — `mipham update` / `/upgrade` — one command to check, backup config, upgrade, restore. API keys preserved
@@ -59,7 +59,7 @@ mipham update
59
59
  | Category | Commands |
60
60
  | -------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
61
61
  | Session | `/help` `/version` `/clear` `/exit` `/quit` `/compact` `/context` `/status` `/cost` `/rename` `/goal` `/recap` `/export` `/doctor` `/resume` |
62
- | Model | `/pick` `/model` `/models` `/provider` `/providers` `/switch` `/effort` `/theme` `/upgrade` |
62
+ | Model | `/pick` `/model` `/models` `/provider` `/providers` `/switch` `/effort` `/upgrade` |
63
63
  | Skills | `/skills` `/browse-skills` `/install-skill` `/remove-skill` `/reload-skills` |
64
64
  | Tools | `/tools` `/commands` `/mcp` |
65
65
  | Workflow | `/plan` `/no-plan` `/review` `/diff` `/todos` `/tasks` `/workflows` `/loop` `/agents` |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@miphamai/cli",
3
- "version": "0.85.34",
3
+ "version": "0.85.36",
4
4
  "description": "Mipham Code — Multi-model open-core intelligent coding terminal by MiphamAI",
5
5
  "keywords": [
6
6
  "ai",
@@ -2,44 +2,13 @@
2
2
  * Mipham Code — Environment Slash Commands
3
3
  *
4
4
  * Extracted from ui/commands.ts (2026-08-06).
5
- * Handlers for: /theme, /release-notes, /ide, /terminal-setup
5
+ * Handlers for: /release-notes, /ide, /terminal-setup
6
6
  */
7
7
  import type { CommandHandler } from '../ui/commands.js'
8
- import { NPM_INSTALL_COMMAND } from '../shared/index.ts'
8
+ import { NPM_INSTALL_COMMAND, PACKAGE_VERSION } from '../shared/index.ts'
9
9
  import { miphamHome } from '../core/paths.ts'
10
10
 
11
- export { themeCmd, releaseNotesCmd, ideCmd, terminalSetupCmd }
12
-
13
- const themeCmd: CommandHandler = (_ctx, args) => {
14
- const theme = args[0]?.toLowerCase()
15
- const validThemes = ['dark', 'light', 'auto'] as const
16
-
17
- if (!theme || !validThemes.includes(theme as (typeof validThemes)[number])) {
18
- return {
19
- content: `── Theme ──
20
-
21
- Terminal color themes (set in .mipham/config.yml):
22
-
23
- theme: dark — dark background (default, recommended for terminals)
24
- theme: light — light background
25
- theme: auto — follow system preference
26
-
27
- Usage: /theme dark | light | auto
28
-
29
- Current: auto (follows terminal)`,
30
- }
31
- }
32
-
33
- return {
34
- content: `✓ Theme set to "${theme}".
35
-
36
- Add to ~/.mipham/config.yml to persist:
37
- theme: ${theme}
38
-
39
- Terminal themes affect syntax highlighting and UI accents.
40
- Full theme customization is available in the Web UI at https://mipham.ai/code/dashboard`,
41
- }
42
- }
11
+ export { releaseNotesCmd, ideCmd, terminalSetupCmd }
43
12
 
44
13
  // ═══════════════════════════════════════════════════════════════
45
14
  // Add-Dir — add a directory to workspace permissions
@@ -56,32 +25,13 @@ Full theme customization is available in the Web UI at https://mipham.ai/code/da
56
25
  const releaseNotesCmd: CommandHandler = () => ({
57
26
  content: `── Release Notes ──
58
27
 
59
- v0.1.2 (2026-06-09) — Current
60
- • 48 slash commands (up from 20)
61
- • /setup guided project initialization wizard
62
- • Checkpoint/rewind mechanism
63
- • Focus mode (last exchange view)
64
- • 3-level MIPHAM.md architecture
65
- • /doctor system diagnostics
66
- • /export conversation to file
67
- • /review and /pr-comments code review workflows
68
- • /memory management
69
- • /upgrade instructions
70
- • Clipboard support (macOS/Windows)
28
+ Current: Mipham Code v${PACKAGE_VERSION}
71
29
 
72
- v0.1.1 (2026-06-02)
73
- • Inline shared module for standalone builds
74
- • Bin path fix for npm compatibility
30
+ This build does not embed the full changelog. See:
31
+ • /changelog recent release tags in this clone
32
+ • https://mipham.ai/code/releases full release notes
75
33
 
76
- v0.1.0 (2026-06-01)
77
- • Initial release
78
- • Multi-model support (7 providers)
79
- • 16 built-in tools
80
- • 11 skills (9 standard + 2 mipham)
81
- • Ctrl+P interactive model picker
82
- • SSE streaming support
83
-
84
- Full changelog: https://mipham.ai/code/releases`,
34
+ Install / upgrade: ${NPM_INSTALL_COMMAND}`,
85
35
  })
86
36
 
87
37
  // ═══════════════════════════════════════════════════════════════
@@ -111,23 +61,46 @@ const ideCmd: CommandHandler = async (_ctx) => {
111
61
  // Use default
112
62
  }
113
63
 
64
+ // Write helpers that MERGE instead of clobbering. These are the user's editor
65
+ // settings: overwriting the file to add one profile destroys every other key
66
+ // (and `keybindings.json` is commonly JSONC, so an unparseable file must be
67
+ // left alone rather than replaced).
68
+ const { readRegularFileSync } = await import('../shared/regular-file')
69
+ const readJson = (path: string): unknown => {
70
+ const raw = readRegularFileSync(path)
71
+ if (raw === null) return undefined
72
+ try {
73
+ return JSON.parse(raw)
74
+ } catch {
75
+ return undefined // JSONC / hand-edited — refuse to rewrite
76
+ }
77
+ }
78
+ const isObject = (v: unknown): v is Record<string, unknown> =>
79
+ v !== null && typeof v === 'object' && !Array.isArray(v)
80
+
114
81
  // ── settings.json: terminal profile ──
115
82
  const settingsPath = join(vscodeDir, 'settings.json')
116
- const settings = {
117
- 'terminal.integrated.profiles.osx': {
118
- mipham: {
119
- path: bunPath,
120
- args: ['run', 'mipham'],
121
- cwd: '${workspaceFolder}',
122
- },
123
- },
83
+ const existingSettings = readJson(settingsPath)
84
+ const settings: Record<string, unknown> = isObject(existingSettings) ? existingSettings : {}
85
+ const profiles = isObject(settings['terminal.integrated.profiles.osx'])
86
+ ? (settings['terminal.integrated.profiles.osx'] as Record<string, unknown>)
87
+ : {}
88
+ profiles.mipham = {
89
+ path: bunPath,
90
+ args: ['run', 'mipham'],
91
+ cwd: '${workspaceFolder}',
124
92
  }
93
+ settings['terminal.integrated.profiles.osx'] = profiles
125
94
  atomicWriteFileSync(settingsPath, JSON.stringify(settings, null, 2) + '\n', { mode: 0o644 })
126
95
  files.push('.vscode/settings.json')
127
96
 
128
97
  // ── keybindings.json: Cmd+Esc launch ──
129
98
  const keybindingsPath = join(vscodeDir, 'keybindings.json')
130
- const keybindings = [
99
+ const existingKeybindings = readJson(keybindingsPath)
100
+ const keybindings: Record<string, unknown>[] = Array.isArray(existingKeybindings)
101
+ ? (existingKeybindings as Record<string, unknown>[])
102
+ : []
103
+ const wanted = [
131
104
  {
132
105
  key: 'cmd+escape',
133
106
  command: 'workbench.action.terminal.focus',
@@ -138,14 +111,25 @@ const ideCmd: CommandHandler = async (_ctx) => {
138
111
  command: 'workbench.action.terminal.new',
139
112
  },
140
113
  ]
114
+ for (const entry of wanted) {
115
+ if (!keybindings.some((k) => k.key === entry.key && k.command === entry.command)) {
116
+ keybindings.push(entry)
117
+ }
118
+ }
141
119
  atomicWriteFileSync(keybindingsPath, JSON.stringify(keybindings, null, 2) + '\n', { mode: 0o644 })
142
120
  files.push('.vscode/keybindings.json')
143
121
 
144
122
  // ── extensions.json: recommended ──
145
123
  const extensionsPath = join(vscodeDir, 'extensions.json')
146
- const extensions = {
147
- recommendations: ['miphamai.mipham-code'],
124
+ const existingExtensions = readJson(extensionsPath)
125
+ const extensions: Record<string, unknown> = isObject(existingExtensions) ? existingExtensions : {}
126
+ const recommendations = Array.isArray(extensions.recommendations)
127
+ ? (extensions.recommendations as unknown[])
128
+ : []
129
+ if (!recommendations.includes('miphamai.mipham-code')) {
130
+ recommendations.push('miphamai.mipham-code')
148
131
  }
132
+ extensions.recommendations = recommendations
149
133
  atomicWriteFileSync(extensionsPath, JSON.stringify(extensions, null, 2) + '\n', { mode: 0o644 })
150
134
  files.push('.vscode/extensions.json')
151
135
 
@@ -34,6 +34,15 @@ async function git(args: string[], timeoutMs = 5000): Promise<string> {
34
34
  return exitCode === 0 ? stdout.trim() : ''
35
35
  }
36
36
 
37
+ /** Diffs can be arbitrarily large; the prompt carries a bounded prefix. */
38
+ const MAX_PROMPT_DIFF = 12_000
39
+
40
+ function promptWithDiff(intro: string, diff: string): string {
41
+ const body =
42
+ diff.length > MAX_PROMPT_DIFF ? `${diff.slice(0, MAX_PROMPT_DIFF)}\n… (truncated)` : diff
43
+ return `${intro}\n\n${body}`
44
+ }
45
+
37
46
  const commitCmd: CommandHandler = async () => {
38
47
  try {
39
48
  const diff = await git(['diff', '--cached', '--stat'])
@@ -50,11 +59,13 @@ const commitCmd: CommandHandler = async () => {
50
59
  .join('\n') +
51
60
  '\n\n'
52
61
  }
53
- msg +=
54
- 'Run: git add <files> to stage changes first.\nOr type: "commit these changes" for AI assistance.'
62
+ msg += 'Run: git add <files> to stage changes first.'
55
63
  return { content: msg }
56
64
  }
57
65
 
66
+ // The command says "generate a commit message", so it must actually
67
+ // generate one. It used to print instructions to type a sentence in chat.
68
+ const full = await git(['diff', '--cached'], 8000)
58
69
  return {
59
70
  content: [
60
71
  '── Git Commit ──',
@@ -62,11 +73,13 @@ const commitCmd: CommandHandler = async () => {
62
73
  'Staged changes:',
63
74
  diff,
64
75
  '',
65
- 'To generate a commit message, type: "write a commit message for these changes"',
66
- 'To commit: git commit -m "your message"',
67
- '',
68
- 'Tip: Use Conventional Commits format (feat:, fix:, chore:, docs:)',
76
+ 'Drafting a Conventional Commits message from these changes.',
77
+ 'To commit: git commit -m "<the message>"',
69
78
  ].join('\n'),
79
+ forwardToAI: promptWithDiff(
80
+ 'Write a Conventional Commits message for the staged diff below. Output only the commit message (subject ≤72 chars, then a blank line and a body if useful). Do not run git.',
81
+ full,
82
+ ),
70
83
  }
71
84
  } catch {
72
85
  return { content: '── Git Commit ──\n\nCould not run git. Are you in a git repository?' }
@@ -90,7 +103,10 @@ const pushCmd: CommandHandler = async () => {
90
103
  ? `Ready to push ${ahead} commit(s). Run: git push origin ${branch}`
91
104
  : 'Nothing to push (up to date).',
92
105
  '',
93
- 'Or type: "push my changes" for AI assistance.',
106
+ // Pushing is an outward-facing action and slash commands bypass the
107
+ // permission layer, so this command only reports. Saying that out loud
108
+ // is the difference between a status view and a fake "push".
109
+ 'This command only reports; it never pushes.',
94
110
  ].join('\n'),
95
111
  }
96
112
  } catch {
@@ -112,6 +128,10 @@ const prCmd: CommandHandler = async () => {
112
128
  (await git(['log', '--oneline', `origin/${mainBranch}..HEAD`], 5000)) ||
113
129
  (await git(['log', '--oneline', `${mainBranch}..HEAD`], 5000))
114
130
 
131
+ const fullDiff =
132
+ (await git(['diff', `origin/${mainBranch}...HEAD`], 8000)) ||
133
+ (await git(['diff', `${mainBranch}...HEAD`], 8000))
134
+
115
135
  return {
116
136
  content: [
117
137
  '── Create Pull Request ──',
@@ -127,28 +147,45 @@ const prCmd: CommandHandler = async () => {
127
147
  '',
128
148
  diff ? `Changes:\n${diff}` : '',
129
149
  '',
130
- 'To create PR: type "create a pull request" for AI assistance.',
131
- 'Or use: gh pr create --base ' + mainBranch + ' --head ' + branch,
150
+ 'Drafting a PR title and body from these commits.',
151
+ 'To open it: gh pr create --base ' + mainBranch + ' --head ' + branch,
132
152
  ].join('\n'),
153
+ forwardToAI: promptWithDiff(
154
+ `Draft a pull request title and body for the branch "${branch}" targeting "${mainBranch}". Commits:\n${commits || '(none)'}\n\nOutput only the title and body. Do not run gh or create the PR.`,
155
+ fullDiff,
156
+ ),
133
157
  }
134
158
  } catch {
135
159
  return { content: '── Create Pull Request ──\n\nCould not determine PR context.' }
136
160
  }
137
161
  }
138
162
 
139
- const issueCmd: CommandHandler = async () => {
163
+ const issueCmd: CommandHandler = async (_ctx, args) => {
164
+ const description = args.join(' ').trim()
165
+ if (!description) {
166
+ return {
167
+ content: [
168
+ '── GitHub Issues ──',
169
+ '',
170
+ 'Describe the issue after the command:',
171
+ ' /issue <what went wrong and what you expected>',
172
+ '',
173
+ 'Quick commands:',
174
+ ' gh issue create --title "..." --body "..."',
175
+ ' gh issue list',
176
+ ].join('\n'),
177
+ }
178
+ }
179
+
140
180
  return {
141
181
  content: [
142
182
  '── GitHub Issues ──',
143
183
  '',
144
- 'To file an issue, type: "create a GitHub issue for [description]"',
145
- '',
146
- 'Quick commands:',
147
- ' gh issue create --title "..." --body "..."',
148
- ' gh issue list',
184
+ 'Drafting an issue from your description.',
149
185
  '',
150
- 'Use /github-ops skill for advanced GitHub automation.',
186
+ 'To file it: gh issue create --title "..." --body "..."',
151
187
  ].join('\n'),
188
+ forwardToAI: `Draft a GitHub issue title and body for: ${description}\n\nOutput only the title and body. Do not run gh or create the issue.`,
152
189
  }
153
190
  }
154
191
 
@@ -14,24 +14,35 @@ export const keysCmd: CommandHandler = async (_ctx, args) => {
14
14
  content: 'Usage: /keys rotate <provider>\n\nExample: /keys rotate deepseek',
15
15
  }
16
16
  }
17
- // Interactive: prompt user to provide new key via follow-up chat message
18
- return {
19
- content: [
20
- '── Key Rotation ──',
21
- '',
22
- `Provider: ${provider}`,
23
- '',
24
- 'To complete rotation, the new API key must be provided.',
25
- 'Type your new key in chat and the AI will handle rotation securely.',
26
- '',
27
- 'The old key will be backed up to ~/.mipham/keys/<provider>.backup (chmod 600).',
28
- ].join('\n'),
29
- forwardToAI: `The user wants to rotate the API key for provider "${provider}". Ask them to provide the new key value, then:
30
- 1. Call KeyManager.rotate("${provider}", newKey) with the provided key
31
- 2. The new key should be stored in ~/.mipham/config.json (or appropriate config)
32
- 3. Confirm rotation count and backup location
33
- 4. Remind them the old key is backed up at ~/.mipham/keys/${provider}.backup`,
17
+
18
+ // The key is read from the environment, never from chat: a key typed into
19
+ // the prompt becomes part of the conversation transcript and the model
20
+ // context. Per-provider variable first, generic one as the fallback.
21
+ const envName = `MIPHAM_ROTATE_KEY_${provider.toUpperCase().replace(/[^A-Z0-9]+/g, '_')}`
22
+ const newKey = process.env[envName] ?? process.env.MIPHAM_ROTATE_KEY
23
+ if (!newKey) {
24
+ return {
25
+ content: [
26
+ '── Key Rotation ──',
27
+ '',
28
+ `Provider: ${provider}`,
29
+ '',
30
+ 'No key supplied.',
31
+ `Set ${envName} (or MIPHAM_ROTATE_KEY) and rerun:`,
32
+ '',
33
+ ` ${envName}=... /keys rotate ${provider}`,
34
+ '',
35
+ 'The key is read from the environment so it never enters the conversation transcript.',
36
+ 'The old rotation metadata is backed up to ~/.mipham/keys/<provider>.backup (chmod 600).',
37
+ ].join('\n'),
38
+ }
39
+ }
40
+
41
+ const result = manager.rotate(provider, newKey)
42
+ if (!result.success) {
43
+ return { content: `── Key Rotation ──\n\n✗ ${result.message}` }
34
44
  }
45
+ return { content: `── Key Rotation ──\n\n✅ ${result.message}` }
35
46
  }
36
47
 
37
48
  // /keys audit
@@ -806,10 +806,9 @@ Built-in skills (${counts.total} total):
806
806
  Mipham (${counts.mipham}): ${miphamNames.join(', ')}
807
807
 
808
808
  Community skills:
809
- Coming soon — the Mipham Code skills marketplace will let you
810
- browse and install community-contributed skills.
809
+ Browse and install with /browse-skills and /install-skill.
811
810
 
812
- For now, add custom skills manually:
811
+ Or add custom skills manually:
813
812
  1. Create a .SKILL.md file in .mipham/skills/
814
813
  2. Use /reload-skills to load it
815
814
 
@@ -845,12 +844,7 @@ To persist one for a project, .mipham/config.yml:
845
844
  allow: ["Bash(npm test)"] # or: /permissions allow "Bash(npm test)"
846
845
  deny: ["Bash(rm *)"]
847
846
 
848
- Available tools (${ctx.engine.getTools().size}):
849
- File: read, write, edit, glob, grep
850
- Exec: bash, git, task
851
- Agent: agent, memory, plan, skill
852
- Net: web-fetch, web-search
853
- Sys: config, mcp
847
+ Available tools (${ctx.engine.getTools().size}) — run /tools for the full list.
854
848
 
855
849
  Next: /setup 6 for shell integration`,
856
850
  }
@@ -869,8 +863,8 @@ Add Mipham Code to your shell:
869
863
  alias mipham='mipham'
870
864
 
871
865
  IDE Integration:
872
- VS Code — coming soon (extension marketplace)
873
- JetBrains — coming soon (plugin)
866
+ VS Code — extension published (search "Mipham Code" in the marketplace)
867
+ JetBrains — plugin published (search "Mipham Code")
874
868
  Terminal — run \`mipham\` in any terminal
875
869
 
876
870
  Quick launch:
@@ -1252,19 +1246,18 @@ const securityCmd: CommandHandler = async () => {
1252
1246
  }
1253
1247
  }
1254
1248
 
1255
- // 3. Check for TLS in dependencies
1256
- if (existsSync(join(cwd, 'package.json'))) {
1257
- ok.push('package.json present — dependencies manageable')
1258
- }
1249
+ // Note: there is deliberately no "TLS in dependencies" step. The old check was
1250
+ // `existsSync(package.json)` — it reported a security pass for the presence of
1251
+ // a file, not for TLS. A scan that cannot answer the question must not claim it.
1259
1252
 
1260
- // 4. Check for license
1253
+ // 3. Check for license
1261
1254
  if (existsSync(join(cwd, 'LICENSE'))) {
1262
1255
  ok.push('LICENSE file present')
1263
1256
  } else {
1264
1257
  findings.push('No LICENSE file — add Apache 2.0 or appropriate license')
1265
1258
  }
1266
1259
 
1267
- // 5. CI/CD
1260
+ // 4. CI/CD
1268
1261
  if (existsSync(join(cwd, '.github', 'workflows'))) {
1269
1262
  ok.push('CI/CD workflows configured')
1270
1263
  } else {
@@ -1,5 +1,6 @@
1
1
  import type { CommandHandler } from '../ui/commands.js'
2
2
  import { listRuns, loadJournal } from '../workflow/journal.js'
3
+ import { getEventBus } from '../workflow/event-bus.js'
3
4
 
4
5
  export const workflowViewCmd: CommandHandler = async (_ctx, args) => {
5
6
  const runId = args[0]
@@ -57,15 +58,32 @@ export const workflowViewCmd: CommandHandler = async (_ctx, args) => {
57
58
  }
58
59
 
59
60
  export const workflowWatchCmd: CommandHandler = async (_ctx, _args) => {
60
- // /workflow watch — monitor the currently active workflow
61
- // This is a hint: the actual rendering is handled by WorkflowProgress component
62
- // which auto-detects active workflows. This command just confirms watch mode.
61
+ // The event bus is the only place that knows whether a run is live in this
62
+ // process. Reading it makes the answer a fact instead of a fixed sentence.
63
+ const active = getEventBus().getActiveRunId()
64
+ const runs = listRuns().sort()
65
+
66
+ if (active) {
67
+ return {
68
+ content: [
69
+ '── Workflow Watch ──',
70
+ '',
71
+ `Active run: ${active}`,
72
+ 'Progress streams automatically in the workflow panel.',
73
+ '',
74
+ `Replay so far: /workflow view ${active}`,
75
+ ].join('\n'),
76
+ }
77
+ }
78
+
63
79
  return {
64
80
  content: [
65
- '── Workflow Watch Mode ──',
81
+ '── Workflow Watch ──',
66
82
  '',
67
- 'Workflow progress is displayed automatically when a workflow is running.',
68
- 'No active workflow detected.',
83
+ 'No workflow is running in this process.',
84
+ runs.length > 0
85
+ ? `Recorded runs: ${runs.length} (latest: ${runs[runs.length - 1]})`
86
+ : 'No recorded runs yet.',
69
87
  '',
70
88
  'Use /workflow list to see past runs.',
71
89
  'Use /workflow view <id> to replay a completed run.',
@@ -176,9 +176,24 @@ export class ContextManager {
176
176
 
177
177
  private log?: SessionLog
178
178
 
179
+ /**
180
+ * 这份日志是不是**完整历史**(默认是;CLI 的 `--resume` 语义依赖它为真)。
181
+ *
182
+ * `false` 只有一个场景:daemon 的会话日志是**审计增量** —— 历史的真源在 SQLite,
183
+ * 日志只记本进程窗口内发生的事。此时「model-visible means logged」这条不变量
184
+ * **按构造不成立**(回灌的旧消息从来没进过日志),故运行时断言必须跟着关掉,
185
+ * 否则它会在每次 `addMessage` 上抛一条「有消息没被记录」的错,而那不是缺陷。
186
+ *
187
+ * 关掉的是**断言**,不是写通:新事件照常落盘。两者不要混为一谈 ——
188
+ * 断言的价值是「能发现漏记」,而在一个从不记录历史投影的日志上,
189
+ * 它对每一行历史都会报警,于是报警这件事本身失效。
190
+ */
191
+ private logAuthoritative = true
192
+
179
193
  /** 附加一个 append-only 会话日志;addMessage/seedMessages 将写通镜像到日志。 */
180
- setLog(log?: SessionLog): void {
194
+ setLog(log?: SessionLog, opts?: { authoritative?: boolean }): void {
181
195
  this.log = log
196
+ this.logAuthoritative = opts?.authoritative ?? true
182
197
  }
183
198
 
184
199
  getLog(): SessionLog | undefined {
@@ -188,6 +203,8 @@ export class ContextManager {
188
203
  /** 从已持久化的日志恢复:设 log 为源,messages 为投影(不重复写通)。 */
189
204
  restoreLog(log: SessionLog): void {
190
205
  this.log = log
206
+ // 恢复出来的这份**就是完整历史**(`messages` 正是由它派生的),故断言重新生效。
207
+ this.logAuthoritative = true
191
208
  // 盘上那份历史可能以一条**没有结果**的调用收尾(写盘写到一半被打断,末尾那行半截
192
209
  // 结果被 `open()` 静默丢掉 —— 引擎自己的日志顺序到不了这个形状,见下面那个函数的
193
210
  // 注释)。挂着 `tool_calls` 却没有结果回应的请求会被 provider 整条拒收,用户看到的
@@ -320,7 +337,7 @@ export class ContextManager {
320
337
  for (const e of messageToEvents(msg, Date.now())) this.log.append(e)
321
338
  }
322
339
 
323
- if (this.log && isAssertModelVisibleDebug()) {
340
+ if (this.log && this.logAuthoritative && isAssertModelVisibleDebug()) {
324
341
  assertModelVisible(this.log.events(), this.messages)
325
342
  }
326
343
 
@@ -345,7 +362,7 @@ export class ContextManager {
345
362
  this.log.append({ type: 'context/inject', at: Date.now(), source, text })
346
363
  }
347
364
 
348
- if (this.log && isAssertModelVisibleDebug()) {
365
+ if (this.log && this.logAuthoritative && isAssertModelVisibleDebug()) {
349
366
  assertModelVisible(this.log.events(), this.messages)
350
367
  }
351
368
 
@@ -391,7 +408,7 @@ export class ContextManager {
391
408
  }
392
409
  this.recountMessageTokens()
393
410
 
394
- if (this.log && isAssertModelVisibleDebug()) {
411
+ if (this.log && this.logAuthoritative && isAssertModelVisibleDebug()) {
395
412
  assertModelVisible(this.log.events(), this.messages)
396
413
  }
397
414
  }
@@ -655,7 +672,7 @@ export class ContextManager {
655
672
  // 之后对 `this.messages` 的原地修改回写进已入队的事件里。
656
673
  if (this.log) {
657
674
  this.log.append({ type: 'rewind', at: Date.now(), messages: structuredClone(this.messages) })
658
- if (isAssertModelVisibleDebug()) {
675
+ if (this.logAuthoritative && isAssertModelVisibleDebug()) {
659
676
  assertModelVisible(this.log.events(), this.messages)
660
677
  }
661
678
  }
@@ -125,6 +125,17 @@ export function filterExpiredMessages(
125
125
  return messages.filter((m) => now - new Date(m.timestamp).getTime() <= maxAgeMs)
126
126
  }
127
127
 
128
+ const ULTRACODE_INSTRUCTION = `## Ultracode mode is ON
129
+
130
+ For every substantive task, prefer the Workflow tool: fan out independent work to
131
+ parallel agents where it helps, then synthesize. Keep one-shot trivia direct.
132
+ This instruction persists for the session until /ultracode off.`
133
+
134
+ /** Append the mode instruction to a system prompt (pure, so it is testable). */
135
+ export function applyUltracodeMode(prompt: string, on: boolean): string {
136
+ return on ? `${prompt}\n\n${ULTRACODE_INSTRUCTION}` : prompt
137
+ }
138
+
128
139
  export class QueryEngine {
129
140
  /**
130
141
  * `false` for the local engine; `true` for the attach-mode `RemoteEngine`.
@@ -163,6 +174,13 @@ export class QueryEngine {
163
174
  private lastAssistantContent?: string
164
175
  /** Reasoning effort (low|medium|high|xhigh|max) — scales the provider idle timeout. */
165
176
  private effort: string = 'high'
177
+
178
+ /**
179
+ * Ultracode mode is a **persistent instruction**, not a one-turn prompt.
180
+ * `/ultracode on` used to set a React state nobody read, and its effect ended
181
+ * with the current turn's injected prompt.
182
+ */
183
+ private ultracode = false
166
184
  /** Custom verification shell script path for goal checking. */
167
185
  private goalVerifyScript?: string
168
186
  /** Custom verification skill name for goal checking. */
@@ -271,6 +289,15 @@ export class QueryEngine {
271
289
  this.effort = level
272
290
  }
273
291
 
292
+ /** Toggle ultracode mode; the instruction is re-applied to every request. */
293
+ setUltracodeMode(on: boolean): void {
294
+ this.ultracode = on
295
+ }
296
+
297
+ getUltracodeMode(): boolean {
298
+ return this.ultracode
299
+ }
300
+
274
301
  /**
275
302
  * Forget which files the Read tool has loaded.
276
303
  *
@@ -456,9 +483,9 @@ export class QueryEngine {
456
483
  /**
457
484
  * Register the instruction loader — the recall nudge's text source.
458
485
  *
459
- * daemon 侧有意不接:daemon **从不设置系统提示**(`setSystemPrompt` 在 `daemon/`
460
- * 下零调用点),因此那条路径上既没有常驻块、也没有指针 —— 接上去只会让扳机指向
461
- * 一个该会话从未被告知过的文件。见守卫的 `daemon:setInstructions` 豁免条目。
486
+ * 两个入口都接(`index.tsx:848` / `daemon/engine-capabilities.ts`):扳机只有在会话
487
+ * **已经被告知过**那份文件时才有意义,而 daemon 现在也会组装系统提示 —— 指针与常驻块
488
+ * 出自同一个 loader 实例,不存在「两边选了不同的文件」这种分叉。
462
489
  */
463
490
  setInstructions(loader: InstructionsLoader): void {
464
491
  this.instructionsLoader = loader
@@ -771,7 +798,7 @@ export class QueryEngine {
771
798
  await this.compactWithHooks('conversation summary', signal)
772
799
  }
773
800
 
774
- const systemPrompt = this.context.getSystemPrompt()
801
+ const systemPrompt = applyUltracodeMode(this.context.getSystemPrompt(), this.ultracode)
775
802
  const messages = this.context.getMessages()
776
803
  const toolDefs = this.getToolDefinitions()
777
804
 
@@ -1229,7 +1256,7 @@ export class QueryEngine {
1229
1256
  yield { type: 'stop' }
1230
1257
  return
1231
1258
  }
1232
- const systemPrompt = this.context.getSystemPrompt()
1259
+ const systemPrompt = applyUltracodeMode(this.context.getSystemPrompt(), this.ultracode)
1233
1260
  const messages = this.context.getMessages()
1234
1261
 
1235
1262
  // ── PreInference DLP checkpoint (every tool-calling turn) ──