Просмотр исходного кода

Merge main into config permissions fix

Preserve both config permission and compaction regression suites.
hetaoBackend 2 месяцев назад
Родитель
Сommit
373439dc7d
29 измененных файлов с 1138 добавлено и 36 удалено
  1. 65 0
      .agents/skills/cli-guide/SKILL.md
  2. 58 0
      .agents/skills/cross-layer-drift-sweep/SKILL.md
  3. 50 0
      .agents/skills/retro/SKILL.md
  4. 67 0
      .agents/skills/testing-workflow/SKILL.md
  5. 56 0
      .agents/skills/verify-all-runtime-sinks/SKILL.md
  6. 14 0
      CONTRIBUTING.md
  7. 2 0
      README.md
  8. 2 0
      README_ZH.md
  9. 13 1
      docs/examples.md
  10. 4 3
      packages/agent-core/src/bash-subprocess-env.ts
  11. 71 0
      packages/agent-core/test/unit/bash-subprocess-env.test.ts
  12. 6 7
      packages/agent-modules/context-manager/src/manager.ts
  13. 31 2
      packages/agent-modules/context-manager/src/token-estimator.ts
  14. 15 1
      packages/agent-modules/context-manager/src/types.ts
  15. 287 0
      packages/agent-modules/context-manager/test/compaction-usage.test.ts
  16. 1 0
      packages/agent-modules/permission/src/context.ts
  17. 12 11
      packages/agent-modules/permission/src/tools/bash-permission.ts
  18. 112 0
      packages/agent-modules/permission/test/unit/permission/bash-policy-regressions.test.ts
  19. 72 0
      packages/agent-tools/src/shared/replace-all-edit.test.ts
  20. 2 1
      packages/agent-tools/src/shared/replace-all-edit.ts
  21. 15 1
      packages/tui/src/cli/program.ts
  22. 38 4
      packages/tui/src/cli/provider-command.ts
  23. 2 0
      packages/tui/src/provider/application.ts
  24. 2 0
      packages/tui/src/provider/contract.ts
  25. 5 1
      packages/tui/test/unit/provider-application.test.ts
  26. 9 0
      release/public-source.json
  27. 59 1
      test/byok.test.mjs
  28. 63 2
      test/smoke.test.mjs
  29. 5 1
      test/vitest-suites.json

+ 65 - 0
.agents/skills/cli-guide/SKILL.md

@@ -0,0 +1,65 @@
+---
+name: cli-guide
+description: Navigate and change the MiniMax Code command tree, interactive TUI, headless exec, ACP adapters, or their in-process runtime connection. Use when implementing or debugging CLI behavior in this repository.
+---
+
+# CLI Architecture Guide
+
+Read `docs/architecture.md` and the current command registration before proposing
+a change. The standalone entry point lives in `packages/tui`.
+
+## Entry points
+
+| Path | Responsibility |
+| --- | --- |
+| `packages/tui/src/index.ts` | Process bootstrap and runtime environment |
+| `packages/tui/src/cli/main.ts` | Command execution and process lifecycle |
+| `packages/tui/src/cli/program.ts` | Commander command registration |
+| `packages/tui/src/cli/contract.ts` | Interactive and exec option contracts |
+| `packages/tui/src/tui/` | Interactive terminal UI |
+| `packages/tui/src/headless/` | Exec invocation, output, cancellation and settlement |
+| `packages/tui/src/acp/` | ACP protocol adapter |
+| `packages/tui/src/runtime/adapter.ts` | Adapter to the in-process CliService |
+| `packages/local-runtime-v2/src/local/` | Local product service entry points |
+| `packages/protocol/src/local.ts` | Shared CLI data structures |
+
+The execution path is:
+
+```text
+TUI / exec / ACP
+  -> CliService
+  -> local applications
+  -> session / turn / agent services
+  -> model providers and tools
+```
+
+Preserve that in-process boundary. Shared behavior belongs in the relevant
+application or service; presentation and transport behavior belong in their
+adapters. Trace callers before assuming a fix to one adapter covers the others.
+
+## Implementing changes
+
+- For commands and flags, inspect `cli/program.ts`, `cli/contract.ts`, and the
+  affected command handler together. Check parsing, help, dispatch and errors.
+- For interactive behavior, follow the controller and rendering path under
+  `tui/`. Check session selection, queued input and interruption where affected.
+- For exec, follow invocation through output and settlement. Verify stdout,
+  stderr, exit code and cancellation; help output alone is insufficient.
+- For ACP, check protocol updates and the underlying runtime operation together.
+- For shared runtime changes, identify all affected TUI, exec and ACP consumers.
+
+## Verification
+
+Use [testing-workflow](../testing-workflow/SKILL.md) to select declared tests.
+Build the standalone artifact before inspecting its actual help:
+
+```bash
+pnpm build
+node dist/cli.js --help
+node dist/cli.js exec --help
+node dist/cli.js acp --help
+```
+
+Read current help before documenting flags. Use temporary data directories and
+synthetic inputs for behavior checks, following the existing smoke/BYOK tests.
+Report offline protocol tests separately from live-provider acceptance.

+ 58 - 0
.agents/skills/cross-layer-drift-sweep/SKILL.md

@@ -0,0 +1,58 @@
+---
+name: cross-layer-drift-sweep
+description: Check completed cross-layer changes for stale fields, defaults, types, contracts or wording across storage, runtime, adapters, TUI and documentation. Use after a rename or contract change with downstream consumers, not for unrelated single-file edits.
+---
+
+# Cross-Layer Drift Sweep
+
+Type checking can miss manual mappings, serialized fields and assertions hidden
+behind casts. Sweep the narrow data flow affected by the change before reporting
+completion.
+
+## Establish the change
+
+Record the change axis: type narrowing, field rename, configuration default,
+contract evolution or display wording. Name the old and new expressions and the
+producer and final observable consumer.
+
+Draw the relevant flow, for example:
+
+```text
+storage -> runtime writer -> local service -> adapter -> TUI / exec / ACP -> docs
+```
+
+Only include layers that actually consume the changed value.
+
+## Sweep
+
+1. Search both old and new expressions. Include source, comments, tests,
+   fixtures, snapshots and relevant documentation. Paired searches reveal layers
+   that adopted only part of a change.
+2. Check the likely gaps for the change axis:
+
+   | Axis | Common gaps |
+   | --- | --- |
+   | Type narrowing | Runtime writers, filesystem reads with casts, serializers, adapter mappings |
+   | Field rename | Schema, migrations, inline test DDL, fixtures, mappings, user-visible labels |
+   | Configuration default | Defaults, thresholds, examples, logs, status output and documentation |
+   | Contract evolution | Local protocol types, service exports, call sites and compatibility fixtures |
+   | Display wording | TUI, exec output, logs, screenshots and exact-string assertions |
+
+3. Fix mismatches within the changed data flow. Explain deliberate compatibility
+   remnants in an adjacent comment or regression test. Avoid changing unrelated
+   matches merely because they contain the same token.
+4. Verify an assertion at the final observable layer, such as rendered text,
+   serialized output, a local-service result or a database-backed read. Reuse an
+   existing assertion when it already covers the behavior; add one when there is
+   a meaningful regression gap.
+5. Run affected tests and type checks using
+   [testing-workflow](../testing-workflow/SKILL.md). For runtime inputs with
+   alternate paths or caches, also use
+   [verify-all-runtime-sinks](../verify-all-runtime-sinks/SKILL.md).
+
+## Evidence
+
+Report the axis, data flow, old/new search terms, layers checked, mismatches fixed
+and verification results. Explain remaining old-token matches. If the final
+consumer could not be exercised, state the gap and the nearest contract evidence
+instead of treating a parser-only test as complete validation.

+ 50 - 0
.agents/skills/retro/SKILL.md

@@ -0,0 +1,50 @@
+---
+name: retro
+description: Extract evidence-backed lessons from a completed development session and propose focused improvements to repository guidance. Use when the user asks for a retrospective or to capture reusable lessons.
+---
+
+# Session Retrospective
+
+Turn concrete failures, retries and workflow gaps into a small set of reusable
+improvements. Do not turn one-off preferences into repository-wide rules.
+
+## Review the evidence
+
+For each useful lesson, record:
+
+- **Event:** what happened, with a public-safe file, command, error or commit.
+- **Cause:** the demonstrated reason, separated from hypotheses.
+- **Lesson:** what a future contributor should do differently.
+- **Impact:** safety/data, correctness, efficiency or preference.
+
+Skip unsupported opinions and one-off circumstances. Combine duplicate lessons
+and keep the result focused on the few changes that would prevent recurrence.
+Redact credentials, private service details and real user content from evidence.
+
+## Find the right home
+
+Read existing guidance before proposing additions:
+
+| Lesson | Candidate location |
+| --- | --- |
+| Repository-wide constraint | `AGENTS.md` or `CONTRIBUTING.md` |
+| A specific reusable workflow | The relevant `.agents/skills` entry |
+| Build, release or source-sync procedure | The relevant document under `docs/` |
+| A behavioral defect | A focused code fix and regression test proposal |
+
+Prefer correcting an existing instruction over introducing a parallel process
+or a new notes/proposals directory. Check current source and scripts before
+preserving an explanation that might already be stale.
+
+## Scope and delivery
+
+If the user asks only for a retrospective, return the findings and proposed
+edits. Apply documentation changes when requested, within the established scope.
+Do not treat the retrospective as authorization to create issues, send messages,
+publish changes or modify personal/agent memory. Write memory only when the user
+explicitly asks for that persistence and the environment supports it.
+
+For applied changes, keep public contributor guidance in English. New files
+require publication review and inventory regeneration; content-only changes do
+not. Report the lessons, evidence, proposed or applied destinations, checks run
+and remaining decisions.

+ 67 - 0
.agents/skills/testing-workflow/SKILL.md

@@ -0,0 +1,67 @@
+---
+name: testing-workflow
+description: Select and report verification for MiniMax Code changes using the repository's declared test suites and CI gates. Use when validating code, skills, documentation, build tooling or source-distribution changes.
+---
+
+# Testing Workflow
+
+Start with changed files, then identify the owning runtime, user entry point and
+final observable behavior. Read `AGENTS.md`, `CONTRIBUTING.md` and the applicable
+steps in `scripts/verify.mjs`.
+
+## Focused iteration
+
+Vitest files belong to groups in `test/vitest-suites.json`; aliases and inclusion
+come from `vitest.oss.config.mjs`. Select an existing declared file for a focused
+run, for example:
+
+```bash
+pnpm exec vitest run --config vitest.oss.config.mjs packages/tui/test/unit/headless-contract.test.ts
+```
+
+Register new Vitest files in the suite declaration. Do not add hard-coded file
+lists to package scripts or the Vitest configuration. Vendored upstream test
+suites are outside this distribution's verification.
+
+| Scope | Repository gate |
+| --- | --- |
+| Runtime, TUI, providers, plugins and ACP | `pnpm test:capabilities` |
+| Headless CLI and offline BYOK behavior | `pnpm test:byok` |
+| CLI artifact smoke | `pnpm test:smoke` |
+| Public artifact content | `pnpm test:artifact` |
+| TUI build-mode contract | `pnpm test:status-contract` |
+| Permission facade on macOS/Linux | `pnpm test:policy` |
+| Sandbox on macOS | `pnpm test:sandbox` |
+| Source-sync, workflow and release tools | `pnpm test:release-tools` |
+| Types and standalone build boundary | `pnpm typecheck`, `pnpm build`, `pnpm check:standalone` |
+| Published files and generated paths | `pnpm check:source`, `pnpm check:tsconfig` |
+
+Artifact-dependent tests require a current `pnpm build`. Keep test state and
+reports outside the repository, using synthetic data and temporary directories.
+
+## Delivery verification
+
+Run `git diff --check` and the relevant individual gates while editing. Review
+new or removed files before regenerating `release/public-source.json` with
+`node scripts/source-inventory.mjs --write`.
+
+Before opening a PR, run `pnpm verify` on the reviewed commit with a clean tracked
+working tree. Source export reads committed HEAD and rejects uncommitted tracked
+changes; report that limitation if only iteration checks are possible.
+
+Use `pnpm verify --list` to inspect the current platform's gates. Use the `docs`
+profile only when every changed path qualifies under `scripts/ci-changes.mjs`.
+Skills under `.agents/skills`, unknown paths and inventory changes require the
+full profile. The `archive` profile is for source-archive validation, not a way to
+bypass the clean-commit export requirement.
+
+## Manual evidence and reporting
+
+For CLI behavior, exercise the built `dist/cli.js` and inspect stdout, stderr and
+exit code. For terminal presentation, exercise the relevant interaction when
+feasible. For provider or service changes, distinguish offline fixtures from a
+real endpoint call.
+
+Report scope, commands and results, manual scenarios, and untested boundaries.
+Use PASS/FAIL/BLOCKED for actual checks; mark checks that did not run explicitly.
+Local macOS success does not establish Windows/Linux or live-service acceptance.

+ 56 - 0
.agents/skills/verify-all-runtime-sinks/SKILL.md

@@ -0,0 +1,56 @@
+---
+name: verify-all-runtime-sinks
+description: Verify that runtime-affecting schema, prompt, identity, adapter, cache or rename changes reach every affected consumer. Use before declaring runtime validation complete when alternate entry points or persisted/generated values can retain old behavior.
+---
+
+# Verify All Runtime Sinks
+
+Identify where a changed value is finally consumed, beyond its first parser or
+happy-path test. This skill defines where to verify; use
+[testing-workflow](../testing-workflow/SKILL.md) for commands and gates.
+
+## Procedure
+
+1. Name the changed contract, field, prompt, identity or adapter behavior. Identify
+   the producer and final runtime consumer, and describe the stale behavior that
+   a partial change would leave behind.
+2. Map the affected consumers. Mark each dimension `covered`, `not applicable`
+   or `unknown`, with a reason:
+   - **Parser to runtime:** normalized objects, managers, launch options,
+     serialization boundaries and service inputs.
+   - **Alternate entry points:** TUI, exec, ACP, task/session launches, built-in
+     and project agents, and explicit historical-data importers where relevant.
+   - **Generated or cached values:** bundled prompts, static prompt caches,
+     compiled configuration, persisted state and memoized objects.
+   - **Fixtures and artifacts:** tests, snapshots, example agents/skills and
+     built distribution assets when affected.
+   - **String remnants:** old property names, environment/configuration keys,
+     log labels and documentation used by generation or tests.
+3. Search for both old and new tokens beyond source files. Include ignored build
+   outputs explicitly when checking artifacts; an ordinary repository search may
+   skip them. Inspect raw serialized shapes where types or casts can hide drift.
+4. Exercise the affected runtime paths through their final consumers. Check each
+   adapter that can bypass the tested path. Shared implementation is evidence
+   only after tracing how those adapters reach it. For prompts, check source
+   selection and caching; for identity/schema changes, check agent kinds that
+   parse differently.
+5. Record commands, results, remaining old-token hits and compatibility reasons.
+   Inspect or regenerate caches using isolated test state; do not clear a user's
+   sessions or configuration as part of verification.
+
+## Completion bar
+
+Do not declare complete runtime coverage while a relevant consumer is `unknown`
+or an unexplained old value remains. Report narrower passing checks and the
+remaining gap. Parser tests alone do not establish propagation through launch,
+execution and final presentation.
+
+Example evidence:
+
+```text
+Parser to service: covered by the affected integration test.
+Exec and ACP: covered by adapter tests; interactive TUI: not run.
+Prompt cache: not applicable; the changed value is not cached.
+Old field: retained only in the historical importer and its fixture.
+Result: focused checks pass; interactive acceptance remains unverified.
+```

+ 14 - 0
CONTRIBUTING.md

@@ -18,6 +18,20 @@ Preserve original third-party license text. Localized product strings, multiling
 
 ## Local validation
 
+Repository development skills are available under [`.agents/skills`](.agents/skills):
+
+| Skill | Use |
+| --- | --- |
+| [cli-guide](.agents/skills/cli-guide/SKILL.md) | Navigate TUI, exec, ACP and their runtime boundary |
+| [cross-layer-drift-sweep](.agents/skills/cross-layer-drift-sweep/SKILL.md) | Check renames, defaults and contracts across consumers |
+| [testing-workflow](.agents/skills/testing-workflow/SKILL.md) | Select focused checks and the required delivery gates |
+| [verify-all-runtime-sinks](.agents/skills/verify-all-runtime-sinks/SKILL.md) | Verify alternate runtime paths, caches and artifacts |
+| [retro](.agents/skills/retro/SKILL.md) | Turn demonstrated failures into focused guidance improvements |
+
+These are contributor workflows, separate from bundled product skills. They are
+adapted to this distribution's paths and verification contracts; workflow changes
+should update the relevant skill alongside its source of truth.
+
 ```bash
 pnpm install --frozen-lockfile
 pnpm verify

+ 2 - 0
README.md

@@ -92,6 +92,8 @@ mcode provider add --name my-provider --base-url https://example.com/v1 \
 mcode
 ```
 
+`--use` tests the first listed model before saving and selecting it. A failed connection test saves nothing. Omit `--use` to save without testing or changing the default model. For custom/local models, add `--context-limit 32768 --output-limit 4096` (use your server's actual limits). Each value must be a positive safe integer and applies to every repeated `--model`. Inspect configured limits with `mcode provider list --json`. Omitting these flags preserves the existing model-limit defaults.
+
 Supported API formats: `openai-completions`, `openai-responses`, and `anthropic-messages`. See the [model examples](docs/examples.md#2-choose-your-own-model) for environment variable setup, connection checks, and model overrides for a single run.
 
 </details>

+ 2 - 0
README_ZH.md

@@ -92,6 +92,8 @@ mcode provider add --name my-provider --base-url https://example.com/v1 \
 mcode
 ```
 
+`--use` 会先测试第一个模型,成功后保存并设为默认模型;连接测试失败时不保存。省略 `--use` 则仅保存,不测试,也不改变默认模型。对于自定义或本地模型,可添加 `--context-limit 32768 --output-limit 4096`(请填写服务器的实际限制)。两个值都必须是正安全整数,并应用于所有重复指定的 `--model`。可通过 `mcode provider list --json` 查看已配置的限制。省略这两个参数时保持现有的模型限制默认值。
+
 支持 `openai-completions`、`openai-responses` 和 `anthropic-messages`。连接测试、单次模型切换及环境变量设置见 [模型示例](docs/examples.md#2-choose-your-own-model)。
 
 </details>

+ 13 - 1
docs/examples.md

@@ -50,7 +50,19 @@ pnpm mcode provider test <provider-id> --model <model-id>
 pnpm mcode exec "Explain this project's test entry points" --model <provider-id>/<model-id>
 ```
 
-Replace the example URL, model name, and IDs with your configuration and the IDs returned by the list command. `--use` sets the default model; `exec --model` overrides only the current run. Backslash line continuations are for POSIX shells; use a single line in PowerShell.
+Replace the example URL, model name, and IDs with your configuration and the IDs returned by the list command. `--use` tests the first listed model, then saves the provider and selects that model as the default. A failed connection test exits nonzero without saving or changing the default; correct the URL, key, or first model ID and retry. Omit `--use` to save without a connection test or default-model change. `exec --model` overrides only the current run. Backslash line continuations are for POSIX shells; use a single line in PowerShell.
+
+For a local server, configure its actual token limits explicitly:
+
+```bash
+pnpm mcode provider add --name local-models --base-url http://localhost:8080/v1 \
+  --api-format openai-completions --model local-model --model another-model \
+  --api-key-env MCODE_PROVIDER_API_KEY \
+  --context-limit 32768 --output-limit 4096 --use
+pnpm mcode provider list --json
+```
+
+`--context-limit` and `--output-limit` each accept a positive safe integer (at most `9007199254740991`). Either flag can be used independently. The same limits apply to every repeated `--model`; only the first model is tested and selected by `--use`. The JSON list shows the configured values as `contextLimit` and `maxOutputTokens`. Without these flags, the existing defaults remain unchanged (unknown custom models currently fall back to 200,000 context tokens and 16,384 output tokens). Model discovery does not infer your local server's context size.
 
 `--api-key-env` reads the current environment variable value and stores that value in the active profile's `config.yaml`; it does not save an environment-variable reference. The file still contains plaintext credentials. On POSIX systems, MCode restricts the config and its migration backups to mode `0600`, including existing files when loaded. Config writes and temporary copies also use `0600`. Windows file modes do not provide equivalent ACL protection; restrict access to the profile directory using Windows permissions.
 

+ 4 - 3
packages/agent-core/src/bash-subprocess-env.ts

@@ -11,8 +11,8 @@
  *   parent session against the runtime API, or a nested `mavis` CLI inside
  *   bash would silently bind to the parent runtime's profile.
  *
- * Layer B — third-party secret scrub. GATED, mirroring the reference CLI's
- *   `subprocessEnv()` design (src/utils/subprocessEnv.ts):
+ * Layer B — provider and integration secret scrub. GATED, mirroring the
+ *   reference CLI's `subprocessEnv()` design (src/utils/subprocessEnv.ts):
  *     - `off`    (interactive default): do not strip user secrets. CC parity —
  *                interactive users rely on env credentials (gh, npm, ...).
  *     - `scrub`  (auto in CI / non-interactive): precise blocklist of
@@ -74,6 +74,7 @@ export interface BashEnvSanitizeResult {
  */
 export const BASH_SUBPROCESS_SCRUB: readonly string[] = [
   // Provider / LLM auth — the runtime re-reads these per-request itself
+  'MCODE_PROVIDER_API_KEY',
   'ANTHROPIC_API_KEY',
   'ANTHROPIC_AUTH_TOKEN',
   'CLAUDE_CODE_OAUTH_TOKEN',
@@ -197,7 +198,7 @@ export function sanitizeBashSubprocessEnv(
   // Layer A — MCode boundary strip. Always on; allowlist deliberately ignored.
   removed.push(...stripRuntimeBoundaryKeysFrom(out, 'agent-runtime'));
 
-  // Layer B — third-party secret scrub, gated by mode.
+  // Layer B — provider and integration secret scrub, gated by mode.
   if (policy.mode === 'scrub') {
     for (const key of BASH_SUBPROCESS_SCRUB) {
       for (const name of [key, `INPUT_${key}`]) {

+ 71 - 0
packages/agent-core/test/unit/bash-subprocess-env.test.ts

@@ -0,0 +1,71 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+  createBashEnvSpawnHook,
+  resolveBashEnvPolicy,
+  sanitizeBashSubprocessEnv,
+} from '../../src/bash-subprocess-env.js';
+
+const providerEnv = {
+  MCODE_PROVIDER_API_KEY: 'synthetic-provider-value',
+  INPUT_MCODE_PROVIDER_API_KEY: 'synthetic-input-value',
+  MCODE_PROVIDER_BASE_URL: 'https://provider.example.invalid',
+  MCODE_PROVIDER_MODEL: 'synthetic-model',
+  CUSTOM_PROVIDER_API_KEY: 'synthetic-custom-value',
+  GH_TOKEN: 'synthetic-gh-value',
+  GITHUB_TOKEN: 'synthetic-github-value',
+  NPM_TOKEN: 'synthetic-npm-value',
+};
+
+describe('bash subprocess default provider credentials', () => {
+  it.each([{ CI: 'true' }, { GITHUB_ACTIONS: 'true' }, { MAVIS_BASH_ENV_SANITIZE: 'scrub' }])(
+    'scrubs both provider key names using policy %j',
+    (markers) => {
+      const original = { ...providerEnv, ...markers };
+      const policy = resolveBashEnvPolicy(undefined, original);
+      expect(policy.mode).toBe('scrub');
+      const { env, removed } = sanitizeBashSubprocessEnv(original, policy);
+      const { MCODE_PROVIDER_API_KEY, INPUT_MCODE_PROVIDER_API_KEY, ...preserved } = original;
+      expect(env).toEqual(preserved);
+      expect(removed).toEqual(['INPUT_MCODE_PROVIDER_API_KEY', 'MCODE_PROVIDER_API_KEY']);
+      expect(original.MCODE_PROVIDER_API_KEY).toBe(MCODE_PROVIDER_API_KEY);
+      expect(original.INPUT_MCODE_PROVIDER_API_KEY).toBe(INPUT_MCODE_PROVIDER_API_KEY);
+    },
+  );
+
+  it('applies scrub to the actual spawn-hook environment without mutating its input', () => {
+    const original = { command: 'echo synthetic', cwd: '.', env: { ...providerEnv } };
+    const result = createBashEnvSpawnHook({ mode: 'scrub' })(original);
+    expect(result.env).not.toHaveProperty('MCODE_PROVIDER_API_KEY');
+    expect(result.env).not.toHaveProperty('INPUT_MCODE_PROVIDER_API_KEY');
+    expect(result.command).toBe(original.command);
+    expect(original.env).toEqual(providerEnv);
+  });
+
+  it('preserves credentials when off is explicitly selected, including in CI', () => {
+    const policy = resolveBashEnvPolicy({ mode: 'off' }, { CI: 'true' });
+    expect(sanitizeBashSubprocessEnv(providerEnv, policy)).toEqual({
+      env: providerEnv,
+      removed: [],
+    });
+  });
+
+  it('continues to strip both provider names in strict mode', () => {
+    const { env, removed } = sanitizeBashSubprocessEnv(providerEnv, { mode: 'strict' });
+    expect(env).not.toHaveProperty('MCODE_PROVIDER_API_KEY');
+    expect(env).not.toHaveProperty('INPUT_MCODE_PROVIDER_API_KEY');
+    expect(removed).toContain('MCODE_PROVIDER_API_KEY');
+    expect(removed).toContain('INPUT_MCODE_PROVIDER_API_KEY');
+    expect(env.MCODE_PROVIDER_MODEL).toBe(providerEnv.MCODE_PROVIDER_MODEL);
+    expect(env.MCODE_PROVIDER_BASE_URL).toBe(providerEnv.MCODE_PROVIDER_BASE_URL);
+  });
+
+  it('retains the explicit strict allowlist escape hatch', () => {
+    const { env } = sanitizeBashSubprocessEnv(providerEnv, {
+      mode: 'strict',
+      allowlist: ['MCODE_PROVIDER_API_KEY', 'INPUT_MCODE_PROVIDER_API_KEY'],
+    });
+    expect(env.MCODE_PROVIDER_API_KEY).toBe(providerEnv.MCODE_PROVIDER_API_KEY);
+    expect(env.INPUT_MCODE_PROVIDER_API_KEY).toBe(providerEnv.INPUT_MCODE_PROVIDER_API_KEY);
+  });
+});

+ 6 - 7
packages/agent-modules/context-manager/src/manager.ts

@@ -1,8 +1,4 @@
-import {
-  generateSummary,
-  type AgentMessage,
-  type CompactionSummaryMessage,
-} from '@earendil-works/pi-agent-core';
+import { generateSummary, type AgentMessage } from '@earendil-works/pi-agent-core';
 import type {
   PiBeforeLlmCallHook,
   PiBeforeLlmCallHookDecision,
@@ -13,6 +9,7 @@ import { computeCompactionTriggerAt, DEFAULT_CONTEXT_MANAGER_SETTINGS } from './
 import { createDefaultContextTokenEstimator, type TokenEstimator } from './token-estimator.js';
 import type {
   ContextCompactionPlan,
+  ContextCompactionSummaryMessage,
   ContextManagerCheckpointOptions,
   ContextManagerLock,
   ContextManagerObserver,
@@ -116,7 +113,7 @@ export class ContextManager {
 
     const replacementId = this.idGenerator();
     const replacementMessages = [
-      createCompactionSummary(summary, plan.tokensBefore, this.nowMs()),
+      createCompactionSummary(summary, plan.tokensBefore, this.nowMs(), plan.keptMessages.length),
       ...plan.keptMessages,
     ];
     const tokensAfter = this.tokenEstimator.estimateContextTokens(replacementMessages).tokens;
@@ -510,12 +507,14 @@ function createCompactionSummary(
   summary: string,
   tokensBefore: number,
   timestamp: number,
-): CompactionSummaryMessage {
+  keptMessageCount: number,
+): ContextCompactionSummaryMessage {
   return {
     role: 'compactionSummary',
     summary,
     tokensBefore,
     timestamp,
+    keptMessageCount,
   };
 }
 

+ 31 - 2
packages/agent-modules/context-manager/src/token-estimator.ts

@@ -20,7 +20,7 @@
  * Ground-truth-aware estimate
  * ---------------------------
  * `estimateContextTokens` preserves pi-agent-core's good pattern:
- *  1. Find the last successful assistant message with a usage block;
+ *  1. Find the last successful assistant message with usage for the current context;
  *  2. Trust its provider-reported total as the prefix sum;
  *  3. Estimate only the trailing messages after that point.
  * This bounds estimator error to the trailing window — typically a handful of
@@ -48,6 +48,7 @@
 import type { AgentMessage } from '@earendil-works/pi-agent-core';
 import { Buffer } from 'node:buffer';
 import { countTokens as countO200kBase } from 'gpt-tokenizer/model/gpt-4o';
+import type { ContextCompactionSummaryMessage } from './types.js';
 
 export interface ContextTokenEstimate {
   /** Estimated total tokens consumed by `messages`. */
@@ -163,8 +164,36 @@ function getAssistantUsage(message: AgentMessage): AssistantUsageRef | undefined
 function getLastAssistantUsageInfo(
   messages: AgentMessage[],
 ): { usage: AssistantUsageRef; index: number } | undefined {
+  let firstFreshIndex = 0;
+  let compactedAt: number | undefined;
   for (let i = messages.length - 1; i >= 0; i -= 1) {
-    const usage = getAssistantUsage(messages[i]!);
+    if (messages[i]!.role !== 'compactionSummary') continue;
+    const summary = messages[i] as ContextCompactionSummaryMessage;
+    const keptCount = summary.keptMessageCount;
+    if (keptCount !== undefined) {
+      // Kept assistants appear AFTER the summary too. Only appended responses
+      // describe the replacement context; their wall-clock timestamps may tie
+      // or precede the summary if the clock changed.
+      if (!Number.isSafeInteger(keptCount) || keptCount < 0) return undefined;
+      firstFreshIndex = i + 1 + keptCount;
+    } else {
+      // Legacy persisted transcripts have no explicit retained-tail boundary.
+      // Match the local runtime's conservative timestamp freshness rule.
+      if (!Number.isFinite(summary.timestamp)) return undefined;
+      compactedAt = summary.timestamp;
+      firstFreshIndex = i + 1;
+    }
+    break;
+  }
+  for (let i = messages.length - 1; i >= firstFreshIndex; i -= 1) {
+    const message = messages[i]!;
+    if (
+      compactedAt !== undefined &&
+      (!Number.isFinite(message.timestamp) || message.timestamp <= compactedAt)
+    ) {
+      continue;
+    }
+    const usage = getAssistantUsage(message);
     if (usage) return { usage, index: i };
   }
   return undefined;

+ 15 - 1
packages/agent-modules/context-manager/src/types.ts

@@ -1,6 +1,20 @@
-import type { AgentMessage, StreamFn, ThinkingLevel } from '@earendil-works/pi-agent-core';
+import type {
+  AgentMessage,
+  CompactionSummaryMessage,
+  StreamFn,
+  ThinkingLevel,
+} from '@earendil-works/pi-agent-core';
 import type { Api, Model, Tool } from '@earendil-works/pi-ai';
 
+export interface ContextCompactionSummaryMessage extends CompactionSummaryMessage {
+  /**
+   * Number of following messages retained from the old context, whose usage is stale.
+   * Persist this with the summary so a restored transcript has the same usage boundary.
+   * Absent on legacy summaries, which must use timestamp-based freshness instead.
+   */
+  keptMessageCount?: number;
+}
+
 export interface ContextManagerSettings {
   enabled: boolean;
   reserveTokens: number;

+ 287 - 0
packages/agent-modules/context-manager/test/compaction-usage.test.ts

@@ -0,0 +1,287 @@
+import type {
+  AgentMessage,
+  CompactionSummaryMessage,
+} from "@earendil-works/pi-agent-core";
+import type { AssistantMessage } from "@earendil-works/pi-ai";
+import type { PiBeforeLlmCallHookInput } from "@mavis/agent-core/pi-turn-runner";
+import { describe, expect, it, vi } from "vitest";
+import { ContextManager } from "../src/manager.js";
+import { BpeTokenEstimator } from "../src/token-estimator.js";
+
+const estimator = new BpeTokenEstimator();
+function assistant(tokens = 180_100, timestamp = 10): AssistantMessage {
+  return {
+    role: "assistant",
+    content: [{ type: "text", text: "Retained reply." }],
+    api: "anthropic-messages",
+    provider: "test",
+    model: "test",
+    stopReason: "stop",
+    timestamp,
+    usage: {
+      input: tokens - 100,
+      output: 100,
+      cacheRead: 0,
+      cacheWrite: 0,
+      totalTokens: tokens,
+      cost: { input: 1, output: 2, cacheRead: 0, cacheWrite: 0, total: 3 },
+    },
+  };
+}
+function user(content = "Continue."): AgentMessage {
+  return { role: "user", content, timestamp: 10 };
+}
+function summary(timestamp = 20): CompactionSummaryMessage {
+  return {
+    role: "compactionSummary",
+    summary: "Small summary.",
+    tokensBefore: 180_100,
+    timestamp,
+  };
+}
+function input(messages: AgentMessage[]): PiBeforeLlmCallHookInput {
+  return {
+    sessionId: "synthetic-session",
+    turnId: "synthetic-turn",
+    phase: "iteration",
+    messages,
+    canonicalMessages: messages,
+    thinkingLevel: "off",
+    model: {
+      id: "test",
+      name: "test",
+      api: "anthropic-messages",
+      provider: "test",
+      baseUrl: "https://example.invalid",
+      reasoning: false,
+      input: ["text"],
+      cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
+      contextWindow: 128_000,
+      maxTokens: 1024,
+    },
+  };
+}
+function history(): AgentMessage[] {
+  return [
+    user("Old request."),
+    assistant(),
+    user("Old follow-up."),
+    assistant(),
+    user("Latest request."),
+    assistant(),
+  ];
+}
+
+describe("compaction usage provenance", () => {
+  it("locally counts a restored legacy summary and retained pre-compaction reply", () => {
+    const messages = JSON.parse(JSON.stringify([summary(), assistant()]));
+    const estimate = estimator.estimateContextTokens(messages);
+    expect(estimate.tokens).toBe(estimator.estimateMessages(messages));
+    expect(estimate.tokens).toBeLessThan(100);
+    expect(estimate.lastUsageIndex).toBeNull();
+    expect(messages[1].usage.totalTokens).toBe(180_100);
+  });
+
+  it("uses fresh legacy usage and estimates only its trailing messages", () => {
+    const messages = [summary(), assistant(), assistant(2100, 21), user()];
+    expect(estimator.estimateContextTokens(messages)).toMatchObject({
+      tokens: 2100 + estimator.estimateMessage(messages[3]!),
+      usageTokens: 2100,
+      lastUsageIndex: 2,
+    });
+  });
+
+  it.each([undefined, NaN, 20])(
+    "rejects legacy usage with ambiguous timestamp %s",
+    (timestamp) => {
+      const retained = { ...assistant(), timestamp } as AgentMessage;
+      expect(
+        estimator.estimateContextTokens([summary(), retained]).lastUsageIndex,
+      ).toBeNull();
+    },
+  );
+
+  it("does not trust any usage when the latest legacy summary lacks a timestamp", () => {
+    const messages = [
+      assistant(),
+      { role: "compactionSummary", summary: "Restored." },
+      assistant(2100, 30),
+    ];
+    expect(
+      estimator.estimateContextTokens(messages as AgentMessage[])
+        .lastUsageIndex,
+    ).toBeNull();
+  });
+
+  it("leaves uncompacted usage and unsuccessful-response filtering unchanged", () => {
+    const messages = [
+      user(),
+      assistant(2100),
+      { ...assistant(), stopReason: "error" as const },
+      { ...assistant(), stopReason: "aborted" as const },
+    ];
+    expect(estimator.estimateContextTokens(messages)).toMatchObject({
+      usageTokens: 2100,
+      lastUsageIndex: 1,
+      tokens: 2100 + estimator.estimateMessages(messages.slice(2)),
+    });
+  });
+
+  it("uses the latest summary boundary and counts an unanchored trailing window", () => {
+    const messages = [
+      summary(1),
+      assistant(),
+      { ...summary(20), keptMessageCount: 2 },
+      user(),
+      assistant(180_100, 50),
+      { ...assistant(2000, 51), stopReason: "error" as const },
+      user(),
+    ];
+    expect(estimator.estimateContextTokens(messages)).toEqual({
+      tokens: estimator.estimateMessages(messages),
+      usageTokens: 0,
+      trailingTokens: estimator.estimateMessages(messages),
+      lastUsageIndex: null,
+    });
+    messages.push(assistant(2100, 20), user());
+    expect(estimator.estimateContextTokens(messages)).toMatchObject({
+      tokens: 2100 + estimator.estimateMessage(messages[8]!),
+      lastUsageIndex: 7,
+    });
+  });
+
+  it.each([-1, 0.5, Infinity, 100])(
+    "falls back locally for an unusable retained count %s",
+    (keptMessageCount) => {
+      const messages = [
+        { ...summary(), keptMessageCount },
+        assistant(2100, 30),
+      ];
+      expect(
+        estimator.estimateContextTokens(messages).lastUsageIndex,
+      ).toBeNull();
+    },
+  );
+
+  it("recounts replacements, skips the next checkpoint, and retains historical usage across restore", async () => {
+    const generateSummary = vi.fn(async () => "Small summary.");
+    const committed = vi.fn();
+    const options = {
+      settings: { keepRecentTokens: 1 },
+      summaryGenerator: { generateSummary },
+      nowMs: () => 5,
+      observer: { onCompactionCommitted: committed },
+    };
+    const original = history();
+    const before = structuredClone(original);
+    const decision = await new ContextManager(options).checkpoint(
+      input(original),
+    );
+    expect(decision.type).toBe("replaceMessages");
+    if (decision.type !== "replaceMessages")
+      throw new Error("Expected compaction");
+    expect(decision.metadata.tokensBefore).toBe(180_100);
+    expect(decision.metadata.tokensAfter).toBe(
+      estimator.estimateMessages(decision.messages),
+    );
+    expect(decision.metadata.tokensAfter).toBeLessThan(100);
+    expect(committed).toHaveBeenCalledWith(
+      expect.objectContaining({ tokensAfter: decision.metadata.tokensAfter }),
+    );
+    expect(original).toEqual(before);
+    expect(decision.messages[1]).toEqual(original[5]);
+    expect(decision.metadata.keptMessages).toEqual([original[5]]);
+
+    const restored: AgentMessage[] = JSON.parse(
+      JSON.stringify(decision.messages),
+    );
+    const manager = new ContextManager(options);
+    // Enough messages for trigger evaluation, with no new provider usage yet.
+    const next = await manager.checkpoint(input([...restored, user(), user()]));
+    expect(next).toEqual({
+      type: "skip",
+      reason: "context_manager_below_threshold",
+    });
+    expect(generateSummary).toHaveBeenCalledTimes(1);
+    // Explicit provenance also works when the clock moved backwards or ties the summary.
+    expect(
+      estimator.estimateContextTokens([...restored, assistant(2100, 5)]),
+    ).toMatchObject({
+      usageTokens: 2100,
+      lastUsageIndex: 2,
+    });
+    expect(
+      estimator.estimateContextTokens([...restored, assistant(2100, 1)]),
+    ).toMatchObject({
+      usageTokens: 2100,
+      lastUsageIndex: 2,
+    });
+  });
+
+  it("invalidates fresh usage again on a subsequent compaction", async () => {
+    const manager = new ContextManager({
+      settings: { keepRecentTokens: 1 },
+      summaryGenerator: { generateSummary: async () => "Small summary." },
+      nowMs: () => 20,
+    });
+    const first = await manager.checkpoint(input(history()));
+    if (first.type !== "replaceMessages")
+      throw new Error("Expected compaction");
+    const second = await manager.checkpoint(
+      input([...first.messages, ...history()]),
+    );
+    if (second.type !== "replaceMessages")
+      throw new Error("Expected second compaction");
+    expect(second.metadata.tokensBefore).toBe(180_100);
+    expect(second.metadata.tokensAfter).toBeLessThan(100);
+    expect(
+      estimator.estimateContextTokens(second.messages).lastUsageIndex,
+    ).toBeNull();
+  });
+
+  it("preserves the remote counter decision and payload after compaction", async () => {
+    const countContextTokens = vi
+      .fn()
+      .mockResolvedValueOnce({ tokens: 190_000, source: "remote_count_tokens" })
+      .mockResolvedValueOnce({ tokens: 40, source: "remote_count_tokens" });
+    const onTriggerEvaluated = vi.fn();
+    const manager = new ContextManager({
+      settings: { keepRecentTokens: 1 },
+      tokenCounter: { countContextTokens },
+      observer: { onTriggerEvaluated },
+      summaryGenerator: { generateSummary: async () => "Small summary." },
+    });
+    const decision = await manager.checkpoint(input(history()));
+    if (decision.type !== "replaceMessages")
+      throw new Error("Expected compaction");
+    expect(decision.metadata.tokensBefore).toBe(190_000);
+    expect(decision.metadata.tokensAfter).toBeLessThan(100);
+    const nextInput = {
+      ...input([...decision.messages, user(), user()]),
+      apiKey: "synthetic-test-key",
+      headers: { "x-test": "synthetic" },
+      systemPrompt: "Test system.",
+      tools: [],
+    };
+    expect(await manager.checkpoint(nextInput)).toEqual({
+      type: "skip",
+      reason: "context_manager_below_threshold",
+    });
+    expect(countContextTokens).toHaveBeenLastCalledWith(
+      expect.objectContaining({
+        messages: nextInput.messages,
+        apiKey: nextInput.apiKey,
+        headers: nextInput.headers,
+        systemPrompt: nextInput.systemPrompt,
+        tools: nextInput.tools,
+      }),
+    );
+    expect(onTriggerEvaluated).toHaveBeenLastCalledWith(
+      expect.objectContaining({
+        tokens: 40,
+        source: "remote_count_tokens",
+        shouldCompact: false,
+      }),
+    );
+  });
+});

+ 1 - 0
packages/agent-modules/permission/src/context.ts

@@ -224,6 +224,7 @@ function cloneContextWith(
     trustedExactWritePaths: ctx.trustedExactWritePaths,
     dataDir: ctx.dataDir,
     homeDir: ctx.homeDir,
+    isFile: ctx.isFile,
     agentName: ctx.agentName,
     sessionId: ctx.sessionId,
     allowManagedPermissionRulesOnly: ctx.allowManagedPermissionRulesOnly,

+ 12 - 11
packages/agent-modules/permission/src/tools/bash-permission.ts

@@ -1133,13 +1133,21 @@ function evaluateSingleSubcommand(
 
   // -------- COMMON LAYER --------
 
+  // Every rule behavior sees the same raw and transparent-wrapper-stripped
+  // forms. Otherwise a wrapped command could skip deny/ask and match allow.
+  const wrapperStrippedCommand = stripTransparentWrappersForRuleMatch(command);
+  const matchesUserRule = (parsedRule: CompiledShellPermissionRule | undefined): boolean =>
+    !!parsedRule &&
+    (matchShellRule(command, parsedRule) ||
+      (!!wrapperStrippedCommand && matchShellRule(wrapperStrippedCommand, parsedRule)));
+
   // Step 1: user deny rule
   for (const { rule, parsedRule } of bashRules) {
     if (rule.ruleBehavior !== 'deny') continue;
     if (!rule.ruleValue.ruleContent) {
       return logLayer('user-deny', { verdict: 'deny', reason: { type: 'rule', rule } });
     }
-    if (parsedRule && matchShellRule(command, parsedRule)) {
+    if (matchesUserRule(parsedRule)) {
       return logLayer('user-deny', { verdict: 'deny', reason: { type: 'rule', rule } });
     }
   }
@@ -1150,7 +1158,7 @@ function evaluateSingleSubcommand(
     if (!rule.ruleValue.ruleContent) {
       return logLayer('user-ask', { verdict: 'ask', reason: { type: 'rule', rule } });
     }
-    if (parsedRule && matchShellRule(command, parsedRule)) {
+    if (matchesUserRule(parsedRule)) {
       return logLayer('user-ask', { verdict: 'ask', reason: { type: 'rule', rule } });
     }
   }
@@ -1301,20 +1309,13 @@ function evaluateSingleSubcommand(
     });
   }
 
-  // Step 5: user allow rule. Match against the original command first;
-  // if a transparent wrapper prefixes the line (nohup/setsid/timeout/xargs/...),
-  // also match the stripped form so `pnpm:*` covers `nohup pnpm install`.
-  // Privilege wrappers (sudo / bash -c / env K=V) are not stripped.
-  const wrapperStrippedCommand = stripTransparentWrappersForRuleMatch(command);
+  // Step 5: user allow rule, using the same command forms as deny/ask above.
   for (const { rule, parsedRule } of bashRules) {
     if (rule.ruleBehavior !== 'allow') continue;
     if (!rule.ruleValue.ruleContent) {
       return logLayer('user-allow', { verdict: 'allow', reason: { type: 'rule', rule } });
     }
-    if (
-      (parsedRule && matchShellRule(command, parsedRule)) ||
-      (wrapperStrippedCommand && parsedRule && matchShellRule(wrapperStrippedCommand, parsedRule))
-    ) {
+    if (matchesUserRule(parsedRule)) {
       return logLayer('user-allow', { verdict: 'allow', reason: { type: 'rule', rule } });
     }
   }

+ 112 - 0
packages/agent-modules/permission/test/unit/permission/bash-policy-regressions.test.ts

@@ -0,0 +1,112 @@
+import path from 'node:path';
+import { describe, expect, it, vi } from 'vitest';
+
+import { applyPermissionUpdate, createToolPermissionContext } from '../../../src/context.js';
+import { BashToolPermissionChecker } from '../../../src/tools/bash-checker.js';
+import { evaluateBashStatic } from '../../../src/tools/bash-permission.js';
+import type { PermissionBehavior, PermissionRule } from '../../../src/types.js';
+
+function bashRule(behavior: PermissionBehavior, content?: string): PermissionRule {
+  return {
+    source: 'session',
+    ruleBehavior: behavior,
+    ruleValue: { toolName: 'bash', ruleContent: content },
+  };
+}
+
+describe.each(['default', 'auto', 'bypass'] as const)('bash rule precedence in %s mode', (mode) => {
+  const commands = [
+    'npm publish',
+    'nohup npm publish',
+    'timeout 30 npm publish',
+    'nice -n 5 npm publish',
+    'setsid npm publish',
+    'xargs npm publish',
+    'nohup timeout 30 npm publish',
+    'CI=1 npm publish',
+    'env CI=1 npm publish',
+    'nohup /usr/bin/npm publish',
+    'echo ready && nohup npm publish',
+  ];
+
+  describe.each(['deny', 'ask'] as const)('%s before allow', (behavior) => {
+    it.each(commands)('enforces the restricted prefix for %s', (command) => {
+      const rules = [bashRule('allow', 'npm:*'), bashRule(behavior, 'npm publish:*')];
+      expect(evaluateBashStatic(command, rules, undefined, mode).verdict).toBe(behavior);
+    });
+
+    it.each(['npm publish', 'npm pub*'])('matches stripped exact/wildcard rule %s', (content) => {
+      const rules = [bashRule('allow', 'npm:*'), bashRule(behavior, content)];
+      expect(evaluateBashStatic('nohup npm publish', rules, undefined, mode).verdict).toBe(
+        behavior,
+      );
+    });
+
+    it('still matches raw wrapper rules', () => {
+      const rules = [bashRule('allow', 'npm:*'), bashRule(behavior, 'nohup npm:*')];
+      expect(evaluateBashStatic('nohup npm publish', rules, undefined, mode).verdict).toBe(
+        behavior,
+      );
+    });
+
+    it('still matches whole-tool rules', () => {
+      const rules = [bashRule('allow', 'npm:*'), bashRule(behavior)];
+      expect(evaluateBashStatic('nohup npm publish', rules, undefined, mode).verdict).toBe(
+        behavior,
+      );
+    });
+  });
+
+  it('allows an unrestricted wrapped command in the same prefix family', () => {
+    const rules = [bashRule('allow', 'npm:*'), bashRule('deny', 'npm publish:*')];
+    expect(evaluateBashStatic('nohup npm install', rules, undefined, mode).verdict).toBe('allow');
+  });
+
+  it('keeps deny stronger than ask regardless of rule order', () => {
+    const rules = [
+      bashRule('ask', 'npm:*'),
+      bashRule('allow', 'npm:*'),
+      bashRule('deny', 'npm publish:*'),
+    ];
+    expect(evaluateBashStatic('nohup npm publish', rules, undefined, mode).verdict).toBe('deny');
+  });
+});
+
+describe('permission context rule updates', () => {
+  it.each(['addRules', 'replaceRules', 'removeRules'] as const)(
+    '%s preserves local-script classification and the host file probe',
+    (type) => {
+      const workingDirectory = path.resolve('synthetic-workspace');
+      const isFile = vi.fn((file: string) => file === path.join(workingDirectory, 'build.js'));
+      const ctx = createToolPermissionContext({
+        workingDirectory,
+        dataDir: path.join(workingDirectory, 'data'),
+        homeDir: path.join(workingDirectory, 'home'),
+        platform: 'linux',
+        shellFamily: 'posix',
+        isFile,
+        rules: [{ source: 'session', ruleBehavior: 'allow', ruleValue: { toolName: 'read' } }],
+      });
+      const checker = new BashToolPermissionChecker();
+      const input = { command: 'echo ready && node ./build.js' };
+      const before = checker.checkPermissions('bash', input, ctx);
+      expect(isFile).toHaveBeenCalledWith(path.join(workingDirectory, 'build.js'));
+      isFile.mockClear();
+
+      const updated = applyPermissionUpdate(ctx, {
+        type,
+        source: 'session',
+        destination: 'session',
+        behavior: 'allow',
+        rules: [{ toolName: 'read' }],
+      });
+      expect(checker.checkPermissions('bash', input, updated)).toEqual(before);
+      expect(isFile).toHaveBeenCalledWith(path.join(workingDirectory, 'build.js'));
+      expect(updated.isFile).toBe(isFile);
+      expect(updated).not.toBe(ctx);
+      expect(Object.isFrozen(updated)).toBe(true);
+      expect(Object.isFrozen(updated.rules)).toBe(true);
+      expect(ctx.rules).toHaveLength(1);
+    },
+  );
+});

+ 72 - 0
packages/agent-tools/src/shared/replace-all-edit.test.ts

@@ -0,0 +1,72 @@
+import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { LocalEditTool } from '../desktop/local-pi-tools.js';
+import { buildReplaceAllEdit } from './replace-all-edit.js';
+
+const replacements = ['$$', '$&', '$`', "$'"];
+
+describe('literal edit replacement text', () => {
+  let directory: string;
+  let file: string;
+
+  beforeEach(async () => {
+    directory = await mkdtemp(join(tmpdir(), 'literal-edit-'));
+    file = join(directory, 'example.txt');
+  });
+
+  afterEach(async () => {
+    await rm(directory, { recursive: true, force: true });
+  });
+
+  it.each(replacements)(
+    'builds a literal full-file replacement for %s',
+    async (replacement) => {
+      const original = 'before TOKEN after\nTOKEN\n';
+      await writeFile(file, original);
+
+      const result = await buildReplaceAllEdit(file, 'TOKEN', replacement);
+
+      expect(result).toEqual({
+        path: file,
+        edits: [
+          {
+            oldText: original,
+            newText: `before ${replacement} after\n${replacement}\n`,
+          },
+        ],
+        replacedCount: 2,
+      });
+      expect(await readFile(file, 'utf8')).toBe(original);
+    },
+  );
+
+  describe.each([true, false])('LocalEditTool with replace_all=%s', (replaceAll) => {
+    it.each(replacements)('writes %s literally to disk', async (replacement) => {
+      await writeFile(
+        file,
+        replaceAll ? 'before TOKEN after\nTOKEN\n' : 'before TOKEN after\n',
+      );
+
+      const result = await new LocalEditTool(directory).execute(
+        { sessionId: 'literal-edit-session', turnId: 'literal-edit-turn' },
+        {
+          file_path: 'example.txt',
+          old_string: 'TOKEN',
+          new_string: replacement,
+          replace_all: replaceAll,
+        },
+      );
+
+      expect(await readFile(file, 'utf8')).toBe(
+        replaceAll
+          ? `before ${replacement} after\n${replacement}\n`
+          : `before ${replacement} after\n`,
+      );
+      expect(result.text).toContain('Successfully replaced');
+    });
+  });
+});

+ 2 - 1
packages/agent-tools/src/shared/replace-all-edit.ts

@@ -93,7 +93,8 @@ export async function buildReplaceAllEdit(
  */
 function rawStringReplaceAll(haystack: string, needle: string, replacement: string): string {
   if (typeof haystack.replaceAll === 'function') {
-    return haystack.replaceAll(needle, replacement);
+    // A callback keeps replacement text literal instead of expanding $ sequences.
+    return haystack.replaceAll(needle, () => replacement);
   }
   return haystack.split(needle).join(replacement);
 }

+ 15 - 1
packages/tui/src/cli/program.ts

@@ -192,13 +192,17 @@ export function createTuiProgram(options: CreateTuiProgramOptions): Command {
     )
     .option('--model <id>', 'model ID (repeatable)', collectOptionValue, [])
     .option('--api-key-env <name>', 'environment variable containing the API key')
-    .option('--use', 'select the first model as the default')
+    .option('--context-limit <tokens>', 'context limit for every listed model', parsePositiveSafeInteger)
+    .option('--output-limit <tokens>', 'output limit for every listed model', parsePositiveSafeInteger)
+    .option('--use', 'test the first model, then save and select it as the default')
     .action(
       (commandOptions: {
         name: string;
         baseUrl: string;
         apiFormat: McodeProviderApiFormat;
         model: string[];
+        contextLimit?: number;
+        outputLimit?: number;
         apiKeyEnv?: string;
         use?: boolean;
       }) => {
@@ -211,6 +215,8 @@ export function createTuiProgram(options: CreateTuiProgramOptions): Command {
           baseUrl: commandOptions.baseUrl,
           apiFormat: commandOptions.apiFormat,
           models: commandOptions.model,
+          contextLimit: commandOptions.contextLimit,
+          outputLimit: commandOptions.outputLimit,
           apiKeyEnv: commandOptions.apiKeyEnv,
           saveAndUse: commandOptions.use,
         });
@@ -415,3 +421,11 @@ function requireTelemetryRunner(options: CreateTuiProgramOptions) {
   if (!options.runTelemetry) throw new Error('Telemetry inspection is unavailable.');
   return options.runTelemetry;
 }
+
+function parsePositiveSafeInteger(value: string): number {
+  const number = Number(value);
+  if (!Number.isSafeInteger(number) || number <= 0) {
+    throw new InvalidArgumentError('expected a positive safe integer');
+  }
+  return number;
+}

+ 38 - 4
packages/tui/src/cli/provider-command.ts

@@ -12,6 +12,8 @@ export type McodeProviderCliRequest =
       readonly baseUrl: string;
       readonly apiFormat: McodeProviderApiFormat;
       readonly models: readonly string[];
+      readonly contextLimit?: number;
+      readonly outputLimit?: number;
       readonly apiKeyEnv?: string;
       readonly saveAndUse?: boolean;
     }
@@ -58,14 +60,46 @@ export async function runMcodeProviderCommand(
           `Provider API key is missing. Set ${envName} or pass --api-key-env <name>.`,
         );
       }
-      await context.application.create({
+      const input = {
         name: request.name,
         baseUrl: request.baseUrl,
         apiKey,
         apiFormat: request.apiFormat,
-        models: request.models.map((modelId) => ({ modelId })),
-        saveAndUse: request.saveAndUse,
-      });
+        models: request.models.map((modelId) => ({
+          modelId,
+          ...(request.contextLimit !== undefined || request.outputLimit !== undefined
+            ? {
+                limit: {
+                  ...(request.contextLimit !== undefined ? { context: request.contextLimit } : {}),
+                  ...(request.outputLimit !== undefined ? { output: request.outputLimit } : {}),
+                },
+              }
+            : {}),
+        })),
+      };
+      if (request.saveAndUse) {
+        const modelId = request.models[0];
+        if (!modelId) throw new Error('At least one --model <id> is required.');
+        const result = await context.application.saveCandidate({
+          ...input,
+          modelId,
+          saveAndUse: true,
+        });
+        if (!result.success) {
+          throw new Error(
+            formatTuiActionFailure(
+              result.status?.lastErrorMessage ?? result.status?.state ?? 'Connection unavailable',
+              {
+                summary: 'Provider connection test failed. Nothing was saved or selected.',
+                nextStep:
+                  'Check the URL, API key, and first model ID, then retry; omit --use to save without testing.',
+              },
+            ),
+          );
+        }
+        return `Provider added and selected: ${request.name}`;
+      }
+      await context.application.create(input);
       return `Provider added: ${request.name}`;
     }
     if (request.action === 'remove') {

+ 2 - 0
packages/tui/src/provider/application.ts

@@ -189,6 +189,8 @@ function normalizeCustomProvider(provider: McodeRuntimeProviderView): McodeProvi
       modelId: model.modelId,
       ...(model.displayName ? { displayName: model.displayName } : {}),
       ...(model.selected !== undefined ? { selected: model.selected } : {}),
+      ...(model.contextLimit !== undefined ? { contextLimit: model.contextLimit } : {}),
+      ...(model.maxOutputTokens !== undefined ? { maxOutputTokens: model.maxOutputTokens } : {}),
       ...(model.status ? { status: model.status } : {}),
     })),
     ...(provider.status ? { status: provider.status } : {}),

+ 2 - 0
packages/tui/src/provider/contract.ts

@@ -24,6 +24,8 @@ export interface McodeProviderModel {
   readonly modelId: string;
   readonly displayName?: string;
   readonly selected?: boolean;
+  readonly contextLimit?: number;
+  readonly maxOutputTokens?: number;
   readonly status?: McodeProviderStatus;
 }
 

+ 5 - 1
packages/tui/test/unit/provider-application.test.ts

@@ -28,7 +28,7 @@ function createPort() {
         configRevision: 'rev-1',
         maskedApiKey: 'sk-****1234',
         rawApiKey: 'must-never-cross-the-cli-boundary',
-        models: [{ modelId: 'gpt-4.1', displayName: 'GPT-4.1' }],
+        models: [{ modelId: 'gpt-4.1', displayName: 'GPT-4.1', contextLimit: 32768, maxOutputTokens: 4096 }],
       },
     ]),
     getMiniMaxApiKeyStatus: vi.fn(async () => ({
@@ -118,6 +118,10 @@ describe('McodeProviderApplication', () => {
     expect(JSON.stringify(snapshot)).toContain('MiniMax OAuth');
     expect(JSON.stringify(snapshot)).not.toContain('must-never-cross-the-cli-boundary');
     expect(snapshot.providers[2]).not.toHaveProperty('rawApiKey');
+    expect(snapshot.providers[2]?.models[0]).toMatchObject({
+      contextLimit: 32768,
+      maxOutputTokens: 4096,
+    });
     expect(port.getCodexOAuthStatus).not.toHaveBeenCalled();
   });
 

+ 9 - 0
release/public-source.json

@@ -1,6 +1,11 @@
 {
   "schemaVersion": 1,
   "files": [
+    ".agents/skills/cli-guide/SKILL.md",
+    ".agents/skills/cross-layer-drift-sweep/SKILL.md",
+    ".agents/skills/retro/SKILL.md",
+    ".agents/skills/testing-workflow/SKILL.md",
+    ".agents/skills/verify-all-runtime-sinks/SKILL.md",
     ".gitattributes",
     ".github/CODEOWNERS",
     ".github/ISSUE_TEMPLATE/01-bug-report.yml",
@@ -99,6 +104,7 @@
     "packages/agent-core/src/tools/index.ts",
     "packages/agent-core/src/tools/input-validation.ts",
     "packages/agent-core/src/tools/types.ts",
+    "packages/agent-core/test/unit/bash-subprocess-env.test.ts",
     "packages/agent-core/test/unit/event-bridge/converters.test.ts",
     "packages/agent-core/test/unit/image-dimensions.test.ts",
     "packages/agent-core/test/unit/image-fixtures.ts",
@@ -139,6 +145,7 @@
     "packages/agent-modules/context-manager/src/settings.ts",
     "packages/agent-modules/context-manager/src/token-estimator.ts",
     "packages/agent-modules/context-manager/src/types.ts",
+    "packages/agent-modules/context-manager/test/compaction-usage.test.ts",
     "packages/agent-modules/conversation-contract/package.json",
     "packages/agent-modules/conversation-contract/src/index.ts",
     "packages/agent-modules/conversation-contract/src/process-local.ts",
@@ -233,6 +240,7 @@
     "packages/agent-modules/permission/src/types.ts",
     "packages/agent-modules/permission/src/windows-trash-execution.ts",
     "packages/agent-modules/permission/src/written-files-registry.ts",
+    "packages/agent-modules/permission/test/unit/permission/bash-policy-regressions.test.ts",
     "packages/agent-modules/permission/test/unit/permission/cloud-classify-client.test.ts",
     "packages/agent-modules/plugin-hooks/package.json",
     "packages/agent-modules/plugin-hooks/src/command-invocation.ts",
@@ -381,6 +389,7 @@
     "packages/agent-tools/src/shared/read-postprocess.ts",
     "packages/agent-tools/src/shared/read-result.ts",
     "packages/agent-tools/src/shared/read-video.ts",
+    "packages/agent-tools/src/shared/replace-all-edit.test.ts",
     "packages/agent-tools/src/shared/replace-all-edit.ts",
     "packages/agent-tools/src/shared/rg-scan-policy.ts",
     "packages/agent-tools/src/shared/rg-sensitive.ts",

+ 59 - 1
test/byok.test.mjs

@@ -14,6 +14,7 @@ import { tmpdir } from "node:os";
 import path from "node:path";
 import { fileURLToPath } from "node:url";
 import Database from "better-sqlite3";
+import { parse as parseYaml } from "yaml";
 
 const cli = fileURLToPath(new URL("../dist/cli.js", import.meta.url));
 // This fixture validates BYOK transport and real Runtime persistence, not model quality.
@@ -38,6 +39,7 @@ test(
     const readMarker = `ACTUAL_FILE_CONTENT_${Date.now()}`;
     writeFileSync(path.join(dataDir, "read-fixture.txt"), readMarker);
     let toolRequested = false;
+    let rejectConnection = false;
     const networkAudit = path.join(dataDir, "network-audit.log");
     const server = createServer(async (req, res) => {
       let raw = "";
@@ -48,6 +50,12 @@ test(
         res.writeHead(404).end();
         return;
       }
+      if (rejectConnection) {
+        res.writeHead(401, { "content-type": "application/json" }).end(
+          JSON.stringify({ error: { message: "Synthetic invalid credential" } }),
+        );
+        return;
+      }
       if (!body.stream) {
         res.writeHead(200, { "content-type": "application/json" }).end(
           JSON.stringify({
@@ -229,6 +237,7 @@ test(
       "--model",
       "fixture-model",
     ]);
+    assert.equal(requests.length, 0, "Adding without --use must not test or activate");
     const snapshot = JSON.parse(await run(["provider", "list", "--json"]));
     assert.equal(
       snapshot.providers.some((p) => p.kind === "minimax-oauth"),
@@ -245,11 +254,60 @@ test(
       "--model",
       "fixture-model",
     ]);
+    const configPath = path.join(dataDir, "config.yaml");
+    const savedConfig = () => parseYaml(readFileSync(configPath, "utf8"));
+    assert.equal(savedConfig().defaultModel, "minimax/MiniMax-M3");
+    assert.equal(savedConfig().custom_provider.fixture.models["fixture-model"].limit, undefined);
+    assert.equal(selected.active, false);
+    assert.equal(selected.models[0].contextLimit, undefined);
+    assert.equal(selected.models[0].maxOutputTokens, undefined);
+
+    const addArgs = [
+      "provider", "add", "--name", "Limited", "--base-url", baseUrl,
+      "--api-format", "openai-completions", "--model", "fixture-model",
+      "--model", "second-model", "--context-limit", "32768", "--output-limit", "4096", "--use",
+    ];
+    const beforeFailure = readFileSync(configPath, "utf8");
+    rejectConnection = true;
+    await assert.rejects(run(addArgs), /Provider connection test failed.*Nothing was saved/s);
+    assert.equal(readFileSync(configPath, "utf8"), beforeFailure);
+    rejectConnection = false;
+    const beforeAdd = requests.length;
+    assert.match(await run(addArgs), /Provider added and selected: Limited/);
+    assert.ok(requests.length > beforeAdd, "Activation must test the candidate before saving");
+    assert.equal(requests[beforeAdd].body.model, "fixture-model");
+    const config = savedConfig();
+    assert.equal(config.defaultModel, "custom_provider:limited/fixture-model");
+    for (const model of ["fixture-model", "second-model"]) {
+      assert.deepEqual(config.custom_provider.limited.models[model].limit, { context: 32768, output: 4096 });
+    }
+    const configured = JSON.parse(await run(["provider", "list", "--json"])).providers.find(
+      (provider) => provider.name === "Limited",
+    );
+    assert.equal(configured.active, true);
+    assert.equal(configured.models[0].selected, true);
+    for (const model of configured.models) {
+      assert.equal(model.contextLimit, 32768);
+      assert.equal(model.maxOutputTokens, 4096);
+    }
+    const beforeSaveOnly = requests.length;
+    for (const [name, flag, limit] of [
+      ["context-only", "--context-limit", { context: 32768 }],
+      ["output-only", "--output-limit", { output: 32768 }],
+    ]) {
+      await run([
+        "provider", "add", "--name", name, "--base-url", baseUrl,
+        "--api-format", "openai-completions", "--model", "fixture-model", flag, "32768",
+      ]);
+      assert.deepEqual(savedConfig().custom_provider[name].models["fixture-model"].limit, limit);
+      assert.equal(savedConfig().defaultModel, config.defaultModel);
+    }
+    assert.equal(requests.length, beforeSaveOnly, "Limits alone must not test or select a model");
     const modelArgs = ["--model", `${selected.providerId}/fixture-model`];
+    // The first run must work through the saved default, without --model or managed login.
     const first = await run([
       "exec",
       "Remember this marker: SOURCE_REPOSITORY_TEST",
-      ...modelArgs,
       "--timeout",
       "20s",
       "--max-steps",

+ 63 - 2
test/smoke.test.mjs

@@ -12,7 +12,7 @@ const cli = path.join(root, "dist/cli.js");
 const version = JSON.parse(
   readFileSync(path.join(root, "packages/tui/package.json"), "utf8"),
 ).version;
-function fixture(t) {
+function fixture(t, environment = process.env) {
   const dataDir = mkdtempSync(path.join(tmpdir(), "minimax-code-smoke-"));
   const audit = path.join(dataDir, "network-attempts.log");
   t.after(() => {
@@ -31,7 +31,17 @@ function fixture(t) {
   return {
     cwd: dataDir,
     env: {
-      ...process.env,
+      ...environment,
+      // Proxy setup installs undici.fetch over the preloaded offline mock.
+      // Keep host proxy settings out of these isolated test children.
+      HTTP_PROXY: "",
+      HTTPS_PROXY: "",
+      ALL_PROXY: "",
+      NO_PROXY: "",
+      http_proxy: "",
+      https_proxy: "",
+      all_proxy: "",
+      no_proxy: "",
       MINIMAX_DATA_DIR: dataDir,
       MAVIS_DATA_DIR: dataDir,
       MCODE_TEST_NETWORK_AUDIT: audit,
@@ -67,6 +77,38 @@ test("provider configuration loads from an isolated data directory", (t) => {
 
   assert.doesNotMatch(result.stdout, /custom_provider:/);
 });
+test("offline smoke children ignore ambient proxy variables", async (t) => {
+  const proxyNames = [
+    "HTTP_PROXY",
+    "HTTPS_PROXY",
+    "ALL_PROXY",
+    "http_proxy",
+    "https_proxy",
+    "all_proxy",
+  ];
+  for (const name of proxyNames) {
+    await t.test(name, (t) => {
+      const environment = {
+        ...process.env,
+        ...Object.fromEntries(proxyNames.map((key) => [key, ""])),
+        [name]: "http://127.0.0.1:9",
+      };
+      const options = fixture(t, environment);
+      const result = spawnSync(process.execPath, [cli, "provider", "list"], {
+        ...options,
+        encoding: "utf8",
+        timeout: 15000,
+      });
+      assert.equal(result.status, 0, result.stderr);
+      assert.match(result.stdout, /minimax/);
+      assert.match(
+        readFileSync(options.env.MCODE_TEST_NETWORK_AUDIT + ".managed", "utf8"),
+        /https:\/\/models\.dev\/api\.json|\/mavis\/api\/v1\/models-dev\/catalog/,
+      );
+      assert.equal(environment[name], "http://127.0.0.1:9");
+    });
+  }
+});
 test("native SQLite binding opens and reads a real database", () => {
   const db = new Database(":memory:");
   try {
@@ -199,3 +241,22 @@ test("local plugin browsing remains available with managed services offline", (t
     assert.match(result.stdout, /Usage:/);
   }
 });
+
+test("provider add validates token limits before opening the runtime", (t) => {
+  const options = fixture(t);
+  const args = [
+    "provider", "add", "--name", "Invalid limits", "--base-url", "http://127.0.0.1:1/v1",
+    "--model", "synthetic-model",
+  ];
+  for (const flag of ["--context-limit", "--output-limit"]) {
+    for (const value of ["0", "-1", "1.5", "NaN", "Infinity", "9007199254740992"]) {
+      const result = spawnSync(process.execPath, [cli, ...args, `${flag}=${value}`], {
+        ...options, encoding: "utf8", timeout: 15000,
+      });
+      assert.equal(result.status, 1, result.stderr);
+      assert.match(result.stderr, /positive safe integer/);
+      assert.ok(result.stderr.includes(flag), result.stderr);
+    }
+  }
+  assert.equal(existsSync(path.join(options.cwd, "config.yaml")), false);
+});

+ 5 - 1
test/vitest-suites.json

@@ -2,6 +2,9 @@
   "comment": "Vitest suites for the standalone distribution, grouped by the gate that runs them. `vitest.oss.config.mjs` includes every group; `scripts/run-vitest-suite.mjs <group>` runs one. Add a test file here rather than in package.json or the Vitest config.",
   "suites": {
     "capability": [
+      "packages/agent-core/test/unit/bash-subprocess-env.test.ts",
+      "packages/agent-modules/permission/test/unit/permission/bash-policy-regressions.test.ts",
+      "packages/agent-tools/src/shared/replace-all-edit.test.ts",
       "packages/local-runtime-v2/test/unit/agent/agent-import.test.ts",
       "packages/tui/test/unit/auth-application.test.ts",
       "packages/tui/test/unit/business-telemetry-privacy.test.ts",
@@ -134,7 +137,8 @@
       "packages/tui/test/unit/tui/controller/product/feature-flow.test.ts",
       "packages/tui/test/unit/tui/features/settings/hotkeys-picker.test.ts",
       "packages/tui/test/unit/incident-reporter-privacy.test.ts",
-      "packages/config/test/config-file-permissions.test.ts"
+      "packages/config/test/config-file-permissions.test.ts",
+      "packages/agent-modules/context-manager/test/compaction-usage.test.ts"
     ],
     "status-contract": [
       "packages/tui/test/unit/tui-build-mode-contract.test.ts"