Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
|----------|-----------|
| Language | TypeScript (strict, ESM) |
| Build | tsup (bundling; inlines the in-repo kernel `kernel/`) |
| Test | Node.js built-in: `node --import tsx --test tests/*.test.ts` |
| Test | Node.js built-in: `node --import ./tests/preload-storage-baseline.mjs --import tsx --test tests/*.test.ts` (preload = storage baseline + XDG sandbox, #5116) |
| Runtime Dep | the in-repo compression kernel (`kernel/`, npm name `acp-kernel`, bundled inline at build time) + `zod` (external, only used by `dist/agent/opencode-native.js` V1 tools; `dist/index.js` stays dependency-free) |

### Repository Info
Expand Down Expand Up @@ -107,7 +107,7 @@ The pi sub-agent surface (`acp_delegate` tools) lives IN THIS REPO under `pi-sub
```bash
npm run build # builds kernel/ + pi-subagents/ first, then tsup bundle (both inlined)
npm run typecheck # tsc --noEmit --project tsconfig.json (src + tests; pre-hooks build kernel/ + pi-subagents/)
npm test # node --import tsx --test tests/*.test.ts (bili suite; kernel suite: npm --prefix kernel test; pi-subagents suite: npm --prefix pi-subagents test) — LOCAL runs are for TARGETED files only; the FULL-suite verdict is the remote CI `test` lanes on the pushed head (§7.2)
npm test # suite lock + preload chain over tests/*.test.ts; targeted single file: `node --import ./tests/preload-storage-baseline.mjs --import tsx --test tests/<file>.test.ts` — the preload is MANDATORY for bare runs (#5116: it pins the storage baseline AND sandboxes the XDG dirs, so no test writes your real $HOME); kernel suite: npm --prefix kernel test; pi-subagents suite: npm --prefix pi-subagents test — LOCAL runs are for TARGETED files only; the FULL-suite verdict is the remote CI `test` lanes on the pushed head (§7.2)
```

### Local Testing & Install
Expand Down Expand Up @@ -247,7 +247,7 @@ Commit convention: `feat:` / `fix:` / `refactor:` / `test:` / `docs:` / `release
### 7.2 Review Discipline

- **Rebase to CURRENT master before claiming mergeable.** Verify against live master, not the PR's original base; after rebase run typecheck + build locally — the FULL-suite verdict comes from remote CI on the pushed head (next bullet). Stale base is the #1 cause of second-round rework (#425 Aug-31 base, #467 43 commits behind, #517).
- **Full regression = remote GitHub CI, not a local full-suite run.** The authoritative green/red for the full suite is the GitHub Actions `test` lane on the pushed head (`scripts/run-ci-tests.mjs`, #2816: hermetic runner, pinned concurrency, ubuntu/windows × node 22/24 × 3 balanced shards (#3143)). Workflow: run the TARGETED suites locally for the area you touched (`node --import tsx --test tests/<changed-area>.test.ts`), push the branch / update the PR, then read the check runs. A local `npm test` full run is environment noise, not evidence — live lanes probing firewalled networks, port collisions with a concurrently running bili instance (e.g. claude-native binding 18787, #394), and cross-file interference all produce failures that CI proves green. Never cite a local full-suite result as the merge verdict, and never chase a local full-suite failure before confirming it reproduces on CI (or in that single file run standalone).
- **Full regression = remote GitHub CI, not a local full-suite run.** The authoritative green/red for the full suite is the GitHub Actions `test` lane on the pushed head (`scripts/run-ci-tests.mjs`, #2816: hermetic runner, pinned concurrency, ubuntu/windows × node 22/24 × 3 balanced shards (#3143)). Workflow: run the TARGETED suites locally for the area you touched (`node --import ./tests/preload-storage-baseline.mjs --import tsx --test tests/<changed-area>.test.ts` — preload mandatory for bare runs, #5116), push the branch / update the PR, then read the check runs. A local `npm test` full run is environment noise, not evidence — live lanes probing firewalled networks, port collisions with a concurrently running bili instance (e.g. claude-native binding 18787, #394), and cross-file interference all produce failures that CI proves green. Never cite a local full-suite result as the merge verdict, and never chase a local full-suite failure before confirming it reproduces on CI (or in that single file run standalone).
- **Watch hot-file contention.** `src/server.ts`, the preflight paths, `src/persist.ts`, and the `src/agent/*` extension types are rewritten by many concurrent PRs — expect semantic (not textual) conflicts; coordinate/sequence, resolve by union of intent, then prove by running tests (#517↔#587, #571↔#558).
- **One linear commit, clean diff.** No diff-exploding rebases, no incidental whitespace re-alignment; every line relates to the PR's purpose (#571 "diff-爆炸", #467).
- **Minor flaws found during review get fixed, not filed.** Per the owner rule "小问题直接修" (§4 Issue & Problem Tracking): when your own review of a PR turns up a small, non-semantic flaw (typo, misaligned indent, log wording), push the one-line fix to the PR branch immediately instead of listing it as a caveat — on ANY PR branch, external contributors included.
Expand Down
2 changes: 1 addition & 1 deletion UNIFIED_LOOP_SPEC.md
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ The transient `systemPrompt` = `buildCompressSystemPrompt()` (or `buildCompressT

### recordUsage semantics (reviewer P1 clarification)
`session.stats.inputTokens` ACCUMULATES across loop rounds (`+=` per round) = total tokens consumed (billing/usage). `session.stats.lastInputTokens` OVERWRITES each round = current context size (used by nudge/compression trigger). Both behaviors are intentional and correct for their respective purposes.
Run via `node --import tsx --test tests/loop-*.test.ts` (node/npm at /home/dog/.local/bin; npx NOT available, use `npm test`).
Run via `node --import ./tests/preload-storage-baseline.mjs --import tsx --test tests/loop-*.test.ts` (preload mandatory for bare runs, #5116; node/npm at /home/dog/.local/bin; npx NOT available, use `npm test`).

## Verification gate (must pass before declaring done)
- `npm run typecheck` (tsc --noEmit) clean.
Expand Down
14 changes: 8 additions & 6 deletions reference/env-vars.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,16 +74,18 @@ precisely so knobs don't bloat the environment. Precedence everywhere:

## Test-infra escape hatches (scripts/-only, never product knobs)

A small class of env vars exists purely for the local test harness — read by
`scripts/*`, NEVER by `src/` or `src/knobs.ts`, and therefore NOT config-file
knobs. They carry no provider/model dimension, are never shipped behavior, and
stay OUT of CONFIGURATION.md (that surface is for user-facing knobs). They are
documented HERE instead so the discipline ("document or don't ship") still
holds without polluting the product config surface.
A small class of env vars exists purely for the local test harness — read or
written by `scripts/*` / `tests/*` only, NEVER by `src/` or `src/knobs.ts`,
and therefore NOT config-file knobs. They carry no provider/model dimension,
are never shipped behavior, and stay OUT of CONFIGURATION.md (that surface is
for user-facing knobs). They are documented HERE instead so the discipline
("document or don't ship") still holds without polluting the product config
surface.

| Var | Read by | Effect | Default |
|-----|---------|--------|---------|
| `BILI_TEST_FORCE` | `scripts/test-suite-lock.mjs` only | Set to `1`/`true`/`yes` to deliberately bypass the per-machine test-suite mutex (#3103) and let a second full `npm test` run share the machine with a live one. Untyped escape hatch for the known limitation the lock cannot cover (orphan daemons from a SIGKILLed suite, cross-clone contention); a normal single run never sets it. | unset = lock enforced |
| `BILI_TEST_XDG_ROOT` | written by `tests/preload-storage-baseline.mjs` (via `tests/test-sandbox-env.mjs`), read by `tests/test-sandbox-env.test.ts` | Reports the per-process temp root the suite sandbox points the four XDG base dirs at when they were unset/empty (#5116) — where a failed run's session/state/cache/config artifacts live for post-mortems. Never overrides an explicitly set XDG var; never read by product code. | unset outside the suite preload |

`BILI_TEST_FORCE` is the escape door the suite lock points at when a sibling
run is detected (`[bili:test] a test suite is already running … to proceed
Expand Down
29 changes: 24 additions & 5 deletions reference/testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,28 @@
```bash
npm run build # tsup bundle (inlines acp-kernel)
npm run typecheck # tsc --noEmit --project tsconfig.json (src + tests)
npm test # node --import tsx --test tests/*.test.ts
npm test # suite lock + preload chain over tests/*.test.ts (see Targeted runs)
```

## Targeted runs (single file / subset) — always with the preload (#5116)

A bare `node --import tsx --test tests/foo.test.ts` skips the suite preload:
every path a suite forgets to pin resolves through your REAL $HOME, so test
sessions land in `~/.local/share/billion-context` (index.db + envelopes),
state files in `~/.local/state/billion-context`, and the live
`~/.config/billion-context` gets read. Always use the same preload chain
`npm test` uses:

```bash
node --import ./tests/preload-storage-baseline.mjs --import tsx --test tests/<file>.test.ts
```

The preload pins `BILI_STORAGE_UNIFIED=legacy` AND sandboxes the four XDG base
dirs into a per-process temp root (`BILI_TEST_XDG_ROOT`, reported for
post-mortems): unset/empty values only — an explicitly set XDG var still wins,
and suites that pin their own mkdtemp homes keep working untouched. Pinned by
`tests/test-sandbox-env.test.ts`.

## CI: test schedule (#2816)

The main CI `test` job does not run the flat `npm test` glob — it runs
Expand Down Expand Up @@ -78,14 +97,14 @@ mechanics: `tests/e2e/README.md`.

```bash
# zero-token preflight (codex binary + dist + upstream reachable)
E2E_CHECK=1 node --import tsx --test tests/e2e/e2e-codex.test.ts
E2E_CHECK=1 node --import ./tests/preload-storage-baseline.mjs --import tsx --test tests/e2e/e2e-codex.test.ts

# full run (defaults to local sglang at http://127.0.0.1:8199/v1, zero cost)
npm run build
ACP_TEST_E2E=1 node --import tsx --test tests/e2e/e2e-codex.test.ts
ACP_TEST_E2E=1 node --import ./tests/preload-storage-baseline.mjs --import tsx --test tests/e2e/e2e-codex.test.ts

# + native-compact interception phase
ACP_TEST_E2E=1 E2E_FORGE=1 node --import tsx --test tests/e2e/e2e-codex.test.ts
ACP_TEST_E2E=1 E2E_FORGE=1 node --import ./tests/preload-storage-baseline.mjs --import tsx --test tests/e2e/e2e-codex.test.ts
```

Rules:
Expand Down Expand Up @@ -168,7 +187,7 @@ to the older target + persistent restart banner, no ping-pong across cycles

```bash
npm run build
ACP_TEST_REGISTRY=1 node --import tsx --test \
ACP_TEST_REGISTRY=1 node --import ./tests/preload-storage-baseline.mjs --import tsx --test \
tests/e2e/e2e-registry.test.ts tests/e2e/e2e-advisory-rollback.test.ts
```

Expand Down
13 changes: 12 additions & 1 deletion tests/preload-storage-baseline.mjs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
// Global test-runner baseline for the unified-storage mode (#2815 rollout).
// Global test-runner baseline for the unified-storage mode (#2815 rollout)
// plus the XDG directory sandbox (#5116).
//
// resolveStorageMode() now defaults to "shadow" when neither the env nor the
// config file says anything (production default flip). The broad wire/e2e
Expand All @@ -14,3 +15,13 @@
//
// ??= keeps an explicit shell/CI env authoritative for ad-hoc experiments.
process.env.BILI_STORAGE_UNIFIED ??= "legacy";

// #5116: sandbox the four XDG base dirs so any suite that forgets to pin them
// resolves paths into a per-run temp root instead of the developer's real
// $HOME (index.db / session envelopes / state files / live config). Unset and
// empty-string values are replaced; an explicitly set value still wins, so
// suites that pin their own mkdtemp homes are untouched. See
// tests/test-sandbox-env.mjs for the full contract + tests/test-sandbox-env.test.ts.
import { sandboxXdgEnv } from "./test-sandbox-env.mjs";

sandboxXdgEnv(process.env);
20 changes: 20 additions & 0 deletions tests/test-sandbox-env.d.mts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// Type declarations for tests/test-sandbox-env.mjs (#5116). The helper stays
// plain .mjs because preload-storage-baseline.mjs loads it BEFORE tsx
// registers; this pairing file keeps TS tests importing it fully typed.

export const SANDBOXED_XDG_KEYS: readonly string[];

interface SandboxXdgOptions {
prefix?: string;
baseDir?: string;
}

interface SandboxXdgResult {
root: string | undefined;
applied: Record<string, string>;
}

export function sandboxXdgEnv(
env: Record<string, string | undefined>,
opts?: SandboxXdgOptions,
): SandboxXdgResult;
56 changes: 56 additions & 0 deletions tests/test-sandbox-env.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
// #5116: sandbox the XDG base dirs for every test-runner process.
//
// Any suite whose file forgets to pin XDG_* resolves paths through
// os.homedir() (src/paths.ts xdg()) and writes straight into the developer's
// REAL ~/.local/share/billion-context (index.db + session envelopes),
// ~/.local/state/billion-context (prefix-affinity.json, rollout-id.json,
// proxy-origin, bili.log) or reads the live ~/.config/billion-context —
// production data polluted with test fingerprints (found while investigating
// #5082). Loaded by tests/preload-storage-baseline.mjs, which npm test /
// scripts/run-ci-tests.mjs / scripts/measure-test-durations.mjs all pass via
// --import; bare targeted runs must use the same preload
// (reference/testing.md).
//
// Semantics: unset OR empty-string values are replaced by fresh per-process
// dirs under one mkdtemp root; an explicitly set non-empty value always wins,
// so every suite that pins its own mkdtemp homes keeps working untouched.
// Each node --test file is its own process, so files also stop sharing state
// dirs with each other. The temp root is deliberately NOT auto-removed: OS
// tmp reaping handles it, and leaving it makes failed runs inspectable. It is
// reported as BILI_TEST_XDG_ROOT so a post-mortem knows where artifacts went.

import { mkdirSync, mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";

/** The four XDG base dirs bili resolves through src/paths.ts. */
export const SANDBOXED_XDG_KEYS = [
"XDG_DATA_HOME",
"XDG_STATE_HOME",
"XDG_CACHE_HOME",
"XDG_CONFIG_HOME",
];

/**
* Point every unset-or-empty XDG base dir in `env` at <root>/<name> under one
* fresh mkdtemp root (default: os.tmpdir()). Explicit non-empty values win
* and are left untouched. Returns { root, applied }; `root` is undefined when
* nothing had to change, and is recorded on env.BILI_TEST_XDG_ROOT when set.
*/
export function sandboxXdgEnv(env, opts = {}) {
const prefix = opts.prefix ?? "bili-test-xdg-";
const baseDir = opts.baseDir ?? tmpdir();
let root;
const applied = {};
for (const key of SANDBOXED_XDG_KEYS) {
const cur = env[key];
if (typeof cur === "string" && cur.length > 0) continue; // explicit setter wins
if (root === undefined) root = mkdtempSync(path.join(baseDir, prefix));
const dir = path.join(root, key.toLowerCase().replace(/^xdg_/, "").replace(/_home$/, ""));
mkdirSync(dir, { recursive: true });
env[key] = dir;
applied[key] = dir;
}
if (root !== undefined) env.BILI_TEST_XDG_ROOT = root;
return { root, applied };
}
Loading
Loading