@miphamai/cli 0.85.8 → 0.85.10

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
1
  # Mipham Code v0.81.7
2
2
 
3
- **Multi-model open-core intelligent coding terminal** — 12 AI providers, 137 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, 138 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
- - **137 Slash Commands** — Interactive command picker (↑↓ Enter Esc), intuitive command interface, zero re-learning
19
+ - **138 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
package/bin/mipham.ts CHANGED
@@ -464,7 +464,9 @@ async function runAttachCLI(): Promise<boolean> {
464
464
  }
465
465
 
466
466
  const { getPort, getDaemonStatus } = await import('../src/daemon/index')
467
+ const { readTokenFile } = await import('../src/daemon/auth')
467
468
  const { join } = await import('node:path')
469
+ // `readFileSync` 后面读 package.json 取版本还要用 —— 去掉的只是 token 那一处内联读法。
468
470
  const { readFileSync, existsSync } = await import('node:fs')
469
471
  const { homedir } = await import('node:os')
470
472
 
@@ -477,10 +479,10 @@ async function runAttachCLI(): Promise<boolean> {
477
479
 
478
480
  const port = getPort()
479
481
  const tokenPath = join(homedir(), '.mipham', 'daemon.token')
480
- let token = ''
481
- if (existsSync(tokenPath)) {
482
- token = readFileSync(tokenPath, 'utf-8').trim()
483
- }
482
+ // 这个文件的读取只有 `auth.ts` 那一个读者 —— 曾经在这里内联过一份同样的
483
+ // `existsSync + readFileSync`,而内联版没有类型闸:token 路径上放个 FIFO,
484
+ // attach 会一声不响地挂住(同 `loadOrCreateToken` 修掉的那个形状)。
485
+ const token = existsSync(tokenPath) ? readTokenFile(tokenPath) : ''
484
486
 
485
487
  // Fetch active sessions from daemon
486
488
  interface SessionInfo {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@miphamai/cli",
3
- "version": "0.85.8",
3
+ "version": "0.85.10",
4
4
  "description": "Mipham Code — Multi-model open-core intelligent coding terminal by MiphamAI",
5
5
  "keywords": [
6
6
  "ai",
@@ -216,8 +216,15 @@ const permissionsCmd: CommandHandler = async (ctx, args) => {
216
216
  // `--user` is matched exactly: a rule fragment may legitimately begin with `--`
217
217
  // (`Bash(--version)`), and dropping it as "a flag" would corrupt the rule.
218
218
  const rest = args.filter((a) => a !== '--user')
219
- const scope: 'project' | 'user' = args.includes('--user') ? 'user' : 'project'
219
+ const wantsUser = args.includes('--user')
220
220
  const verb = rest[0]
221
+ // `allow` ignores the flag and always writes **user** level: an allow rule
222
+ // widens the approval gate, so it must not land in a file that arrives with the
223
+ // repository — the loader withholds a project-level one (`stripProjectPermission`,
224
+ // `loadSettingsJson`), and a command still writing there would be a write path
225
+ // with no reader. `deny` only narrows, so a repository may carry it; `--user`
226
+ // keeps that one local instead. For `remove` this is just the first scope tried.
227
+ const scope: 'project' | 'user' = verb === 'allow' || wantsUser ? 'user' : 'project'
221
228
 
222
229
  if (verb === 'allow' || verb === 'deny' || verb === 'remove') {
223
230
  const { validateRulePattern } = await import('../core/permission-rules')
@@ -228,7 +235,10 @@ const permissionsCmd: CommandHandler = async (ctx, args) => {
228
235
  const usage =
229
236
  `Usage: /permissions <allow|deny|remove> <rule>... [--user]\n\n` +
230
237
  ` rule Tool pattern — "Bash" or "Bash(npm test)". Quote it if it has spaces.\n` +
231
- ` --user Write to ~/.mipham/settings.json instead of .mipham/settings.json.`
238
+ ` allow Written to ~/.mipham/settings.json. An allow rule widens the approval\n` +
239
+ ` gate, so it must not arrive with the repository (\`--user\` is implied).\n` +
240
+ ` deny Written to .mipham/settings.json unless --user is given — denying only\n` +
241
+ ` narrows, so a repository may carry it.`
232
242
 
233
243
  if (unbalanced) {
234
244
  return { content: `Unbalanced quote in rule.\n\n${usage}` }
@@ -251,10 +261,22 @@ const permissionsCmd: CommandHandler = async (ctx, args) => {
251
261
 
252
262
  if (verb === 'remove') {
253
263
  const parts: string[] = []
264
+ // Both scopes, named one first. `remove` does not know which list holds the
265
+ // rule (`allow` is always user level, `deny` defaults to project), so
266
+ // searching only the named scope would answer "No rule" for a rule that is
267
+ // live — the command's own remedy, silently not working.
268
+ const order: ['project' | 'user', 'project' | 'user'] =
269
+ scope === 'user' ? ['user', 'project'] : ['project', 'user']
254
270
  for (const rule of rules) {
255
- const removed = removeSettingsRule(rule, scope)
271
+ let removed: { path: string; key: 'allow' | 'deny' } | null = null
272
+ for (const s of order) {
273
+ removed = removeSettingsRule(rule, s)
274
+ if (removed) break
275
+ }
256
276
  if (!removed) {
257
- parts.push(`No rule "${rule}" in ${settingsPathFor(scope)}.`)
277
+ parts.push(
278
+ `No rule "${rule}" in ${settingsPathFor(order[0])} or ${settingsPathFor(order[1])}.`,
279
+ )
258
280
  continue
259
281
  }
260
282
  perm.removeRule(rule)
@@ -275,7 +297,12 @@ const permissionsCmd: CommandHandler = async (ctx, args) => {
275
297
  `permissions.${verb}:\n${rules.map((r) => ` ${r}`).join('\n')}\n\n` +
276
298
  (rules.length === 1
277
299
  ? `This rule persists across sessions and applies from now on.`
278
- : `These rules persist across sessions and apply from now on.`),
300
+ : `These rules persist across sessions and apply from now on.`) +
301
+ (verb === 'allow'
302
+ ? `\n\nAllow rules are stored at user level: a rule that widens the approval gate\n` +
303
+ `must not arrive with the repository. Use \`/permissions deny\` for rules the\n` +
304
+ `repository itself should carry.`
305
+ : ''),
279
306
  }
280
307
  }
281
308
 
@@ -307,10 +334,15 @@ ${ruleLines('allow', settings.permissions.allow)}
307
334
  ${ruleLines('deny', settings.permissions.deny)}
308
335
 
309
336
  Persist a rule with:
310
- /permissions allow "Bash(npm test)" → .mipham/settings.json
311
- /permissions deny "Bash(rm *)" --user → ~/.mipham/settings.json
337
+ /permissions allow "Bash(npm test)" → ~/.mipham/settings.json
338
+ /permissions deny "Bash(rm *)" → .mipham/settings.json
312
339
  /permissions remove "Bash(npm test)"
313
340
 
341
+ An allow rule widens the approval gate, so it is always user level — a project-level
342
+ one would be a repository choosing its own gate (and is ignored if it ships one). A
343
+ deny rule only narrows, so it may be committed with the repository; add --user to
344
+ keep it local instead.
345
+
314
346
  Current directory permissions:
315
347
  CWD: ${process.cwd()}
316
348
 
@@ -1,5 +1,5 @@
1
1
  import { existsSync, copyFileSync, mkdirSync, readdirSync, unlinkSync, chmodSync } from 'node:fs'
2
- import { join, dirname } from 'node:path'
2
+ import { join, dirname, resolve } from 'node:path'
3
3
  import { parse as parseYaml, stringify as stringifyYaml } from 'yaml'
4
4
  import { atomicWriteFileSync } from '../shared/atomic-write'
5
5
  import { isRegularFile, readRegularFileSync } from '../shared/regular-file'
@@ -11,6 +11,7 @@ import type {
11
11
  CredentialMaskingConfig,
12
12
  BackgroundAgentConfig,
13
13
  CrossSessionConfig,
14
+ PermissionRestrictions,
14
15
  } from '../shared/index.ts'
15
16
  import {
16
17
  DEFAULT_CONFIG,
@@ -21,6 +22,7 @@ import {
21
22
  } from './defaults'
22
23
  import { getCredentialKey, encryptApiKey, decryptApiKey, ENC_PREFIX } from './credential-crypto'
23
24
  import type { SettingsHooks } from '../core/hooks-config'
25
+ import { wideningForbiddenEntries } from '../core/permission-config'
24
26
  import { miphamHome } from '../core/paths.ts'
25
27
  import { MIPHAM_DIR } from '../shared/constants.ts'
26
28
 
@@ -148,16 +150,28 @@ function mergeConfig(
148
150
  }
149
151
 
150
152
  /**
151
- * Drop `permission` from a **project-level** `config.yml` before it is merged,
152
- * reporting it instead of applying it.
153
+ * Drop the **widening** parts of a project-level `config.yml` before it is merged
154
+ * — `permission`, `permissionRules.allow`, and the one member of
155
+ * `permissionRestrictions` that widens — reporting them instead of applying them.
153
156
  *
154
- * `permission` is a ceiling, not a rule: it decides what the approval gate lets
155
- * through without asking. Every other project-level key is a preference that a
156
- * repository may reasonably commit; this one means "and do not ask me about the
157
- * commands in here" — which is a decision about the operator, made by whoever
158
- * wrote the repository. The same reasoning admits project-level `permissions.deny`
159
- * (it narrows) and withholds `permissions.defaultMode` in `settings.json` (it
160
- * widens) — the two files are the same door, so both are closed here.
157
+ * All three answer the same question one level apart: `permission` picks the
158
+ * approval gate, an allow rule is "and do not ask me about the commands in here"
159
+ * inside it, and a mode restriction is the boundary that rule is measured
160
+ * against. Each is a decision about the operator made by whoever wrote the
161
+ * repository, which is why none may arrive with the code.
162
+ *
163
+ * They were not always treated alike: `permission` was refused while `allow` was
164
+ * merged as a mere "rule", on the reasoning that a rule only speaks within the
165
+ * range its ceiling allows. That reasoning needs a ceiling to hold, and the only
166
+ * thing that defines one is `maxAllowedMode` — which is opt-in, so by default
167
+ * there was no range and `allowRuleDecision` returned `bypass` outright. The
168
+ * criterion is the **direction**, not the key it is filed under: what narrows
169
+ * (`permissions.deny`) a repository may ship, what widens it may not.
170
+ *
171
+ * `permissionRestrictions` is where that criterion has to be applied per
172
+ * **member** rather than per key, because the key is the narrowing one by
173
+ * definition and still has one way to widen (`forbiddenModes` minus the strictest
174
+ * rung — see the branch at the end of this function).
161
175
  *
162
176
  * `mergeConfig` has no per-key allowlist, so this has to happen at the two points
163
177
  * the project file enters. Reported rather than dropped silently: a repo whose
@@ -165,15 +179,112 @@ function mergeConfig(
165
179
  * "your config was ignored" looks like from the outside.
166
180
  */
167
181
  function stripProjectPermission(cfg: Partial<MiphamConfig>, path: string): Partial<MiphamConfig> {
168
- if (cfg.permission === undefined) return cfg
169
182
  const { permission, ...rest } = cfg
170
- const shown = typeof permission === 'string' ? permission : JSON.stringify(permission)
171
- process.stderr.write(
172
- `⚠ Mipham Code: ignored permission: ${shown} from project config ${path}\n` +
173
- ` (a repository must not choose the approval gate — set it in ~/.mipham/config.yml,\n` +
174
- ` or pass --permission <mode> for this invocation)\n`,
175
- )
176
- return rest as Partial<MiphamConfig>
183
+
184
+ if (permission !== undefined) {
185
+ const shown = typeof permission === 'string' ? permission : JSON.stringify(permission)
186
+ process.stderr.write(
187
+ `⚠ Mipham Code: ignored permission: ${shown} from project config ${path}\n` +
188
+ ` (a repository must not choose the approval gate — set it in ~/.mipham/config.yml,\n` +
189
+ ` or pass --permission <mode> for this invocation)\n`,
190
+ )
191
+ }
192
+
193
+ // `permissionRules.allow` is the same decision under a second key: an allow
194
+ // rule answers "do not ask me about this command", which is only meaningful
195
+ // when something bounds how far it reaches — and the thing that would
196
+ // (`maxAllowedMode`) is opt-in, so in a stock config nothing does. `deny` is
197
+ // the opposite direction and stays: a repository may narrow its own gate.
198
+ const rules = rest.permissionRules
199
+ if (rules) {
200
+ const kept = { ...rules }
201
+ if (Array.isArray(kept.allow) && kept.allow.some((r) => typeof r === 'string')) {
202
+ process.stderr.write(
203
+ `⚠ Mipham Code: ignored permissionRules.allow from project config ${path}\n` +
204
+ ` (an allow rule widens the approval gate exactly as \`permission\` does — put it in\n` +
205
+ ` ~/.mipham/config.yml, or run /permissions allow <rule>)\n`,
206
+ )
207
+ }
208
+ delete kept.allow
209
+ // An emptied table is dropped rather than merged as `{}`: "this repository
210
+ // mentioned allow" must not change the shape of the user's own table.
211
+ if (Object.keys(kept).length > 0) rest.permissionRules = kept
212
+ else delete rest.permissionRules
213
+ }
214
+
215
+ // `permissionRestrictions` is the third key of this family, and unlike the other
216
+ // two it is *nominally* the narrowing one (the key exists to cap the gate) — which
217
+ // is exactly why it went unguarded. It has one exit, though, and it is in
218
+ // `clampMode`: the walk goes **down** from the requested mode, and when the
219
+ // request and everything below it are forbidden there is nothing left to land on,
220
+ // so it falls back to `allowed[0]` — **wider** than what was asked for. Banning
221
+ // the strictest rung is what creates that case (`[default, acceptEdits, plan]` +
222
+ // a request for `plan` ⇒ `auto`, four rungs up), so the repository may keep every
223
+ // ban but that one. `maxAllowedMode` needs no such treatment: it only drops modes
224
+ // above a cap, and the same downward walk always finds the cap (measured over all
225
+ // 25 cap × request pairs — none widens).
226
+ //
227
+ // This is the F2-2 criterion ("what narrows a repository may ship, what widens it
228
+ // may not") applied one level down, at the *value* rather than the key: the key is
229
+ // kept, the widening member is refused. Measured, not asserted — the sweep in
230
+ // `test/config/loader-merge.test.ts` writes all 32 forbidden subsets (the empty one
231
+ // included) through this function and clamps all 5 requested modes against each.
232
+ const restrictions = rest.permissionRestrictions as Record<string, unknown> | undefined
233
+ if (restrictions && typeof restrictions === 'object' && !Array.isArray(restrictions)) {
234
+ const kept: Record<string, unknown> = {}
235
+ const refused: unknown[] = []
236
+
237
+ for (const [key, value] of Object.entries(restrictions)) {
238
+ if (key === 'forbiddenModes' && Array.isArray(value)) {
239
+ const widening = wideningForbiddenEntries(value)
240
+ if (widening.length > 0) refused.push(...widening)
241
+ const survivors = value.filter((entry) => !widening.includes(entry))
242
+ // Same "emptied means dropped" rule as `allow` above: a ban list that lost
243
+ // its only entry must not merge as `[]` and reshape the user's own table.
244
+ if (survivors.length > 0) kept.forbiddenModes = survivors
245
+ continue
246
+ }
247
+ // Everything else passes through untouched — including a malformed
248
+ // `forbiddenModes` (a string, an object). `normalizeRestrictions` is the one
249
+ // validator and the one warning channel for this key; a second partial
250
+ // validator here would drift from it the day a mode is added.
251
+ kept[key] = value
252
+ }
253
+
254
+ if (refused.length > 0) {
255
+ process.stderr.write(
256
+ `⚠ Mipham Code: ignored permissionRestrictions.forbiddenModes ${JSON.stringify(refused)} from project config ${path}\n` +
257
+ ` (forbidding the strictest mode leaves the fallback nothing below it to land on —\n` +
258
+ ` a request for that mode comes back *wider*; set it in ~/.mipham/config.yml if you mean it)\n`,
259
+ )
260
+ }
261
+
262
+ if (Object.keys(kept).length > 0) {
263
+ rest.permissionRestrictions = kept as PermissionRestrictions
264
+ // The applied half is reported too, and this one is not a courtesy: `permission`
265
+ // and `allow` announce themselves because they are *refused*. A cap or a ban
266
+ // that **does** take effect rewrites the operator's own mode control once, at
267
+ // startup, and nothing afterwards ever names it — the footer just shows a mode
268
+ // they did not choose. `deny` rules can merge silently because each one speaks
269
+ // at the moment it acts (a refusal in the transcript, naming the rule); a mode
270
+ // ceiling never does.
271
+ process.stderr.write(
272
+ `⚠ Mipham Code: permission modes pinned by project config ${path} (${describeRestrictions(kept)})\n` +
273
+ ` (a repository may narrow the gate; change or remove it in ~/.mipham/config.yml)\n`,
274
+ )
275
+ } else {
276
+ delete rest.permissionRestrictions
277
+ }
278
+ }
279
+
280
+ return rest
281
+ }
282
+
283
+ /** One-line rendering of a restriction table for a warning — values as written. */
284
+ function describeRestrictions(source: Record<string, unknown>): string {
285
+ return Object.entries(source)
286
+ .map(([key, value]) => `${key}: ${typeof value === 'string' ? value : JSON.stringify(value)}`)
287
+ .join(', ')
177
288
  }
178
289
 
179
290
  /**
@@ -283,13 +394,19 @@ function loadMcpJson(cwd: string): McpServerConfig[] {
283
394
 
284
395
  /**
285
396
  * Parsed `settings.json` (Claude Code convention): hooks + permissions.
286
- * Hooks are additive across levels; permissions allow/deny are deduped unions —
287
- * and `defaultMode` is the one member that is **not** merged, because it is a
288
- * ceiling rather than a rule (see `loadSettingsJson`).
397
+ * Hooks are additive across levels, and so is `permissions.deny` (a deduped
398
+ * union — it *narrows*, and narrowing needs no gate). What does **not** merge
399
+ * from both levels is anything that *widens*: `defaultMode` and
400
+ * `permissions.allow` are read from the user-level file only. Both are bounded
401
+ * by the same ceiling, and that ceiling is opt-in (see `loadSettingsJson`).
289
402
  */
290
403
  export interface SettingsJson {
291
404
  hooks: SettingsHooks
292
405
  /**
406
+ * `allow` is the **user-level** file's list; a project-level one is withheld
407
+ * (`projectAllowSkipped`) because a rule that widens is the approval gate by
408
+ * another name. `deny` merges from both levels.
409
+ *
293
410
  * `defaultMode` is present only when the **user-level** file named one, and it
294
411
  * is passed through **raw** (not validated here): the accepted spelling is
295
412
  * `ALL_MODES`, and the single place that enforces it — plus the warning for a
@@ -312,6 +429,16 @@ export interface SettingsJson {
312
429
  * move for a file that arrives with the code, trusted workspace or not.
313
430
  */
314
431
  projectModeSkipped?: true
432
+ /**
433
+ * Same shape again, for `permissions.allow`: present only when the
434
+ * project-level file really declared at least one rule and it was **withheld**.
435
+ * Like `projectModeSkipped` this is not conditioned on trust — a rule that
436
+ * widens is the same decision whoever the repository's author is.
437
+ *
438
+ * The two markers are independent and each reports only its own key: a file
439
+ * that declares `allow` but no mode sets this one and not the other.
440
+ */
441
+ projectAllowSkipped?: true
315
442
  /**
316
443
  * The subset of `hooks` that came from the project-level file — the entries
317
444
  * the workspace-trust gate governs. Absent unless the caller vouched for the
@@ -333,25 +460,29 @@ export interface SettingsJson {
333
460
  * repository-controlled and its `hooks` are shell commands this process will
334
461
  * spawn — reading them is an act of trust, not a default. Callers that have
335
462
  * established trust (or that only *display* the configured list) opt in
336
- * explicitly. The flag gates hooks only: `permissions` still merge from both
337
- * levels, since that question is answered by the mode ceiling, not by trust.
463
+ * explicitly. The flag gates hooks only: `permissions.deny` still merges from
464
+ * both levels, because it *narrows* and narrowing needs no gate.
338
465
  *
339
- * **That last sentence is the reason `defaultMode` is the exception.** The
340
- * ceiling only answers the trust question while repository-controlled files
341
- * cannot move it; a repo that ships `.mipham/settings.json` with
342
- * `permissions.defaultMode: "auto"` would otherwise hand itself the approval
343
- * gate. So `defaultMode` is read from the **user-level file only**, and a
344
- * project-level one is withheld and *reported* (`projectModeSkipped`) rather
345
- * than dropped in silence — same treatment as a `plan`/`acceptEdits` value that
346
- * used to be dropped entirely, except that the drop there fell back to the
347
- * *wider* `default`. The upstream convention says the same thing in its own
348
- * words: repo-level settings cannot grant `defaultMode`; adopt it in user
349
- * settings instead.
466
+ * **This doc used to say the rest of `permissions` merges from both levels too,
467
+ * "since that question is answered by the mode ceiling, not by trust". That was
468
+ * wrong, and the wrong half was `allow`.** The ceiling answers the question only
469
+ * while it exists: `maxAllowedMode` is opt-in, and `allowRuleDecision` returns
470
+ * `bypass` outright when it is absent (the default) — so in a stock config there
471
+ * is nothing for a widening rule to be measured against, and a repo that ships
472
+ * `permissions.allow: ["Bash(*)"]` hands itself the approval gate exactly as it
473
+ * would with `defaultMode`. Both widening members are therefore read from the
474
+ * **user-level file only**, and each withheld project-level one is *reported*
475
+ * (`projectModeSkipped` / `projectAllowSkipped`) rather than dropped in silence
476
+ * — the same treatment as a `plan`/`acceptEdits` value that used to be dropped
477
+ * entirely, except that the drop there fell back to the *wider* `default`. The
478
+ * upstream convention says the same thing in its own words: repo-level settings
479
+ * cannot grant `defaultMode`; adopt it in user settings instead.
350
480
  *
351
- * One consequence to keep in mind when reading a merged result: `permissions`
352
- * is still provenance-free for allow/deny, so a caller cannot tell which of
353
- * those two rules came from the repository. That is deliberate (above), and it
354
- * is why the ceiling has to be the thing that repels the repo-controlled half.
481
+ * One consequence to keep in mind when reading a merged result: `permissions.deny`
482
+ * is provenance-free (project and user rules sit in one bucket), so a caller
483
+ * cannot tell which deny rule came from the repository. That is deliberate —
484
+ * the direction that needs provenance is the widening one, and that is the one
485
+ * this function keeps out.
355
486
  */
356
487
  export function loadSettingsJson(
357
488
  cwd: string = process.cwd(),
@@ -364,15 +495,25 @@ export function loadSettingsJson(
364
495
  }
365
496
  let projectHooksSkipped = false
366
497
  let projectModeSkipped = false
498
+ let projectAllowSkipped = false
367
499
  // The project file's entries, kept out of the merge so provenance survives it.
368
500
  const projectHooks: SettingsHooks = {}
369
501
 
502
+ // The project entry is **omitted**, not re-tagged, when it is the user's own file
503
+ // (running from `~` — see `projectFilePath`): the user entry below then reads it
504
+ // with `readHooks: true`, so its `defaultMode` applies and its hooks are trusted,
505
+ // instead of being withheld under a project label.
506
+ const projectSettingsPath = projectFilePath('settings.json', cwd)
370
507
  const searchPaths: Array<{ path: string; readHooks: boolean; isProject?: boolean }> = [
371
- {
372
- path: join(cwd, MIPHAM_DIR, 'settings.json'),
373
- readHooks: options.includeProjectHooks ?? false,
374
- isProject: true,
375
- },
508
+ ...(projectSettingsPath
509
+ ? [
510
+ {
511
+ path: projectSettingsPath,
512
+ readHooks: options.includeProjectHooks ?? false,
513
+ isProject: true,
514
+ },
515
+ ]
516
+ : []),
376
517
  { path: join(MIPHAM_HOME, 'settings.json'), readHooks: true },
377
518
  ]
378
519
 
@@ -427,8 +568,19 @@ export function loadSettingsJson(
427
568
  for (const key of ['allow', 'deny'] as const) {
428
569
  const list = parsed.permissions[key]
429
570
  if (!Array.isArray(list)) continue
430
- for (const p of list) {
431
- if (typeof p === 'string' && !permissions[key].includes(p)) permissions[key].push(p)
571
+ const strings = list.filter((p): p is string => typeof p === 'string')
572
+ // `deny` narrows, so a repository may ship it. `allow` widens — and the
573
+ // question "does it widen past what is permitted?" is **not** answered by
574
+ // the mode ceiling unless someone configured one: `allowRuleDecision`
575
+ // returns `bypass` outright when `maxAllowedMode` is absent, which is the
576
+ // default. A project-level allow rule is therefore a repository choosing
577
+ // the approval gate, and it is withheld here like `defaultMode`.
578
+ if (key === 'allow' && isProject) {
579
+ if (strings.length > 0) projectAllowSkipped = true
580
+ continue
581
+ }
582
+ for (const p of strings) {
583
+ if (!permissions[key].includes(p)) permissions[key].push(p)
432
584
  }
433
585
  }
434
586
  }
@@ -444,6 +596,7 @@ export function loadSettingsJson(
444
596
  const result: SettingsJson = { hooks, permissions }
445
597
  if (projectHooksSkipped) result.projectHooksSkipped = true
446
598
  if (projectModeSkipped) result.projectModeSkipped = true
599
+ if (projectAllowSkipped) result.projectAllowSkipped = true
447
600
  if (Object.values(projectHooks).some((entries) => Array.isArray(entries) && entries.length > 0)) {
448
601
  result.projectHooks = projectHooks
449
602
  }
@@ -459,6 +612,29 @@ export function settingsPathFor(scope: SettingsScope, cwd: string = process.cwd(
459
612
  : join(cwd, MIPHAM_DIR, 'settings.json')
460
613
  }
461
614
 
615
+ /**
616
+ * Resolve a file under the **project** `.mipham` directory, or `null` when there
617
+ * is no project scope at this `cwd`.
618
+ *
619
+ * There is none when the CLI runs from the home directory itself: there
620
+ * `join(cwd, MIPHAM_DIR)` and `MIPHAM_HOME` are the *same directory*, so every
621
+ * "project" path names the user's own file.
622
+ *
623
+ * The guards that call this exist to stop **a repository** from granting
624
+ * telemetry, choosing the approval gate, or supplying hooks — and to report what
625
+ * they withheld. At `~/.mipham` there is no repository to stop: treating the file
626
+ * as project-level would withhold the user's own settings and then name that very
627
+ * file in the warning as the place to set them.
628
+ *
629
+ * The test is "same directory", **not** "under the home directory" — `~/proj` is
630
+ * an ordinary project and must keep every guard (`startsWith(homedir())` would
631
+ * exempt exactly the most common project location).
632
+ */
633
+ export function projectFilePath(name: string, cwd: string = process.cwd()): string | null {
634
+ const dir = join(cwd, MIPHAM_DIR)
635
+ return resolve(dir) === resolve(MIPHAM_HOME) ? null : join(dir, name)
636
+ }
637
+
462
638
  /**
463
639
  * Read a settings.json as a plain object, preserving any key we don't model
464
640
  * (hooks, and anything a future version adds). A malformed file is an error,
@@ -488,6 +664,15 @@ export function writeSettingsDoc(path: string, doc: Record<string, unknown>): vo
488
664
  * Persist one rule into `permissions.<key>` of a scope's settings.json.
489
665
  * Idempotent: re-adding an existing rule leaves the file unchanged.
490
666
  * Returns the path written.
667
+ *
668
+ * ⚠️ `key: 'allow'` with the default `'project'` scope writes a file the loader
669
+ * **withholds** (`loadSettingsJson` — an allow rule widens the approval gate, so
670
+ * only the user level is read). That is a rule nobody reads, which from the
671
+ * outside looks exactly like a rule that works, so callers must pass `'user'`
672
+ * for `allow`; `/permissions allow` does. `deny` is the one that belongs at
673
+ * project level. This function keeps honoring what it is told rather than
674
+ * coercing the scope, so the refusal stays at the reader — one gate, not two
675
+ * that can drift.
491
676
  */
492
677
  export function addSettingsRule(
493
678
  key: 'allow' | 'deny',
@@ -533,37 +718,43 @@ export function removeSettingsRule(
533
718
  }
534
719
 
535
720
  export function loadConfig(cwd: string = process.cwd()): MiphamConfig {
536
- const configPath = join(cwd, MIPHAM_DIR, 'config.yml')
721
+ // `null` when cwd is the home directory, where the "project" config *is* the user
722
+ // config read further down (`MIPHAM_HOME` and `join(cwd, MIPHAM_DIR)` coincide) —
723
+ // see `projectFilePath`. Skipping the block is what lets the user's own
724
+ // `permission` come through the user door instead of being stripped at this one.
725
+ const configPath = projectFilePath('config.yml', cwd)
537
726
  const userConfigPath = join(MIPHAM_HOME, 'config.yml')
538
727
 
539
728
  let config = { ...DEFAULT_CONFIG }
540
729
 
541
- // The project file enters `loadConfig` at **two** points (fresh parse, and the
542
- // parse that follows a restore from backup). Both go through here, so the guard
543
- // on `permission` cannot be present on one path and missing on the other — a
544
- // corrupted config that recovers from a backup is still the same repository's
545
- // file, and "corrupt it once, get the setting honored" would be a bypass of the
546
- // one key that is refused.
547
- const applyProjectConfig = (parsed: Partial<MiphamConfig>): void => {
548
- config = mergeConfig(config, stripProjectPermission(parsed, configPath), false)
549
- }
550
-
551
730
  // ── Load project-level config ──
552
- const projectConfig = safeParseYaml(configPath, 'project config')
553
- if (projectConfig) {
554
- applyProjectConfig(projectConfig)
555
- } else if (isRegularFile(configPath)) {
556
- // A real file is there but failed to parse — try to restore from backup.
557
- // 非普通文件走不到这里:那不是「损坏的配置」,而是根本不该当配置读的东西
558
- // (FIFO/socket/目录),「恢复」对它会变成往 FIFO 里写、又一次挂死。
559
- process.stderr.write(`⚠ Mipham Code: project config is corrupted, attempting recovery...\n`)
560
- if (!tryRestoreFromBackup(configPath)) {
561
- process.stderr.write(`⚠ Mipham Code: no backup available for project config. Skipping.\n`)
562
- } else {
563
- // Retry parsing after restore
564
- const restored = safeParseYaml(configPath, 'restored project config')
565
- if (restored) {
566
- applyProjectConfig(restored)
731
+ if (configPath !== null) {
732
+ // The project file enters `loadConfig` at **two** points (fresh parse, and the
733
+ // parse that follows a restore from backup). Both go through here, so the guard
734
+ // on `permission` cannot be present on one path and missing on the other — a
735
+ // corrupted config that recovers from a backup is still the same repository's
736
+ // file, and "corrupt it once, get the setting honored" would be a bypass of the
737
+ // one key that is refused.
738
+ const applyProjectConfig = (parsed: Partial<MiphamConfig>): void => {
739
+ config = mergeConfig(config, stripProjectPermission(parsed, configPath), false)
740
+ }
741
+
742
+ const projectConfig = safeParseYaml(configPath, 'project config')
743
+ if (projectConfig) {
744
+ applyProjectConfig(projectConfig)
745
+ } else if (isRegularFile(configPath)) {
746
+ // A real file is there but failed to parse — try to restore from backup.
747
+ // 非普通文件走不到这里:那不是「损坏的配置」,而是根本不该当配置读的东西
748
+ // (FIFO/socket/目录),「恢复」对它会变成往 FIFO 里写、又一次挂死。
749
+ process.stderr.write(`⚠ Mipham Code: project config is corrupted, attempting recovery...\n`)
750
+ if (!tryRestoreFromBackup(configPath)) {
751
+ process.stderr.write(`⚠ Mipham Code: no backup available for project config. Skipping.\n`)
752
+ } else {
753
+ // Retry parsing after restore
754
+ const restored = safeParseYaml(configPath, 'restored project config')
755
+ if (restored) {
756
+ applyProjectConfig(restored)
757
+ }
567
758
  }
568
759
  }
569
760
  }