${paste.content}diff --git a/.adal/README.md b/.adal/README.md
index 95fb30b5b..f53ce7741 100644
--- a/.adal/README.md
+++ b/.adal/README.md
@@ -20,3 +20,4 @@ bash ./install.sh --target adal --profile minimal
- The `adal` target installs into the project-level `./.adal/` directory.
- AdaL's own config (`~/.adal/settings.json`, MCP servers, plugins) is **not** touched by ECC install.
- Use `npx ecc-universal doctor --target adal` to check install health.
+- use an installed
diff --git a/.agents/plugins/marketplace.json b/.agents/plugins/marketplace.json
index 6da48b541..e730e4eed 100644
--- a/.agents/plugins/marketplace.json
+++ b/.agents/plugins/marketplace.json
@@ -6,7 +6,7 @@
"plugins": [
{
"name": "ecc",
- "version": "2.2.1",
+ "version": "2.2.2",
"source": {
"source": "local",
"path": "./"
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json
index 03b3f9f85..b19c87b8d 100644
--- a/.claude-plugin/marketplace.json
+++ b/.claude-plugin/marketplace.json
@@ -12,7 +12,7 @@
"name": "ecc",
"source": "./",
"description": "Harness-native ECC operator layer - 68 agents, 292 skills, 94 legacy command shims, reusable hooks, rules, selective install profiles, and production-ready workflows for Claude Code, Codex, OpenCode, Cursor, and related agent harnesses",
- "version": "2.2.1",
+ "version": "2.2.2",
"author": {
"name": "Affaan Mustafa",
"email": "me@affaanmustafa.com"
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index 5f1e9a391..072edddfe 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "ecc",
- "version": "2.2.1",
+ "version": "2.2.2",
"description": "Harness-native ECC plugin for engineering teams - 68 agents, 292 skills, 94 legacy command shims, reusable hooks, rules, MCP conventions, and operator workflows for Claude Code plus adjacent agent harnesses",
"author": {
"name": "Affaan Mustafa",
diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json
index 7ad227cac..c1399c129 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "ecc",
- "version": "2.2.1",
+ "version": "2.2.2",
"description": "Harness-native ECC workflows for Codex: shared skills, production-ready MCP configs, and selective-install-aligned conventions for TDD, security scanning, code review, and autonomous development.",
"author": {
"name": "Affaan Mustafa",
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 393b46902..a2f3ae61f 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -20,7 +20,7 @@ jobs:
test:
name: Test (${{ matrix.os }}, Node ${{ matrix.node }}, ${{ matrix.pm }})
runs-on: ${{ matrix.os }}
- timeout-minutes: 20
+ timeout-minutes: 30
strategy:
fail-fast: false
@@ -47,7 +47,7 @@ jobs:
# Package manager setup
- name: Setup pnpm
if: matrix.pm == 'pnpm' && matrix.node != '18.x'
- uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6.0.10
+ uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0
with:
# Keep an explicit pnpm major because this repo's packageManager is Yarn.
version: 10
@@ -267,6 +267,11 @@ jobs:
- name: Run Python tests
run: python -m pytest tests/test_*.py -m "not integration"
+ - name: Test minimum supported OpenAI SDK
+ run: |
+ python -m pip install 'openai==2.34.0'
+ python -m pytest tests/test_provider_tools.py tests/test_atlas_provider.py tests/test_astraflow_provider.py tests/test_resolver.py
+
security:
name: Security Scan
runs-on: ubuntu-latest
diff --git a/.github/workflows/reusable-test.yml b/.github/workflows/reusable-test.yml
index c3d5d0892..f5b97787e 100644
--- a/.github/workflows/reusable-test.yml
+++ b/.github/workflows/reusable-test.yml
@@ -38,7 +38,7 @@ jobs:
- name: Setup pnpm
if: inputs.package-manager == 'pnpm' && inputs.node-version != '18.x'
- uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6.0.10
+ uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0
with:
# Keep an explicit pnpm major because this repo's packageManager is Yarn.
version: 10
diff --git a/.github/workflows/taste-skills.yml b/.github/workflows/taste-skills.yml
index 552adb981..40e68deb3 100644
--- a/.github/workflows/taste-skills.yml
+++ b/.github/workflows/taste-skills.yml
@@ -23,7 +23,7 @@ jobs:
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0
diff --git a/.opencode/index.ts b/.opencode/index.ts
index fa6cadc58..8ee800f80 100644
--- a/.opencode/index.ts
+++ b/.opencode/index.ts
@@ -37,4 +37,4 @@
// Export the main plugin
// opencode's legacy plugin loader iterates every module export and throws if
// any is not a plugin function, so only the plugin function may be exported.
-export { default } from "./plugins/index.js"
+export { default } from "./plugins/index.ts"
diff --git a/.opencode/package-lock.json b/.opencode/package-lock.json
index f6c140bdd..1ea48a9d1 100644
--- a/.opencode/package-lock.json
+++ b/.opencode/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "ecc-universal",
- "version": "2.2.1",
+ "version": "2.2.2",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "ecc-universal",
- "version": "2.2.1",
+ "version": "2.2.2",
"license": "MIT",
"devDependencies": {
"@opencode-ai/plugin": "^1.4.3",
diff --git a/.opencode/package.json b/.opencode/package.json
index 94e8e3f04..e71d5df73 100644
--- a/.opencode/package.json
+++ b/.opencode/package.json
@@ -1,6 +1,6 @@
{
"name": "ecc-universal",
- "version": "2.2.1",
+ "version": "2.2.2",
"description": "ECC plugin for OpenCode - agents, commands, hooks, and skills",
"main": "dist/index.js",
"types": "dist/index.d.ts",
diff --git a/.opencode/plugins/ecc-hooks.ts b/.opencode/plugins/ecc-hooks.ts
index 22b1132f0..bf06c03f8 100644
--- a/.opencode/plugins/ecc-hooks.ts
+++ b/.opencode/plugins/ecc-hooks.ts
@@ -16,8 +16,8 @@
import type { PluginInput } from "@opencode-ai/plugin"
import * as fs from "fs"
import * as path from "path"
-import changedFilesTool from "../tools/changed-files.js"
-import dependencyAnalyzerTool from "../tools/dependency-analyzer.js"
+import changedFilesTool from "../tools/changed-files.ts"
+import dependencyAnalyzerTool from "../tools/dependency-analyzer.ts"
/**
* Type definitions for better type safety
@@ -111,9 +111,9 @@ export const ECCHooksPlugin: ECCHooksPluginFn = async ({
// This plugin is OpenCode's startup entry point, so a static import
// failure here previously crashed the whole plugin -- and with it, the
// entire OpenCode session -- before any hooks could load (see #2530).
- let changedFilesStore: typeof import("./lib/changed-files-store.js") | undefined
+ let changedFilesStore: typeof import("./lib/changed-files-store.ts") | undefined
try {
- const store = await import("./lib/changed-files-store.js")
+ const store = await import("./lib/changed-files-store.ts")
store.initStore(worktreePath)
changedFilesStore = store
} catch {
@@ -481,7 +481,7 @@ export const ECCHooksPlugin: ECCHooksPluginFn = async ({
* Triggers: Before shell command execution
* Action: Sets PROJECT_ROOT, PACKAGE_MANAGER, DETECTED_LANGUAGES, ECC_VERSION
*/
- "shell.env": async () => {
+ "shell.env": async (_input: { cwd: string }, output: { env: Record
' + body + '
${paste.content}`; `expiresAt` is an ISO
+ timestamp. Default TTL is 7 days; `ttlSeconds` must be an integer between
+ 1 and 2592000 (30 days).
+ - Missing/invalid `url` or out-of-range `ttlSeconds` → `400`.
+- `GET /` — `302` with `Location` set to the original URL.
+ Unknown code → `404`. Expired link → `410`.
+- `DELETE /links/` — `204`. Unknown code → `404`.
+
+All error responses follow the envelope in `CONTRIBUTING.md`.
diff --git a/docker/context-profiles/complex-eval/cases3/chained-tickets/files/CONTRIBUTING.md b/docker/context-profiles/complex-eval/cases3/chained-tickets/files/CONTRIBUTING.md
new file mode 100644
index 000000000..7c45e4af2
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases3/chained-tickets/files/CONTRIBUTING.md
@@ -0,0 +1,13 @@
+# Engineering conventions
+
+These conventions apply to every ticket, every route, every change:
+
+- **Errors**: every error response is JSON with the envelope
+ `{ "error": { "code": "", "message": "" } }`
+ and the matching HTTP status. No HTML error pages, no stack traces.
+- **Layering**: HTTP handling in `src/routes.js`, business logic in
+ `src/service.js`, storage in `src/store.js`. `src/app.js` wires them.
+- **Runtime config** comes from environment variables, read at startup.
+- **Every ticket**: add tests under `test/`, add a `CHANGELOG.md` entry
+ describing what shipped, and keep `README.md` accurate.
+- No external dependencies.
diff --git a/docker/context-profiles/complex-eval/cases3/chained-tickets/files/README.md b/docker/context-profiles/complex-eval/cases3/chained-tickets/files/README.md
new file mode 100644
index 000000000..90f4bae61
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases3/chained-tickets/files/README.md
@@ -0,0 +1,9 @@
+# shortlink
+
+Internal link shortener service. Node.js standard library only, CommonJS.
+
+- `API.md` — the HTTP contract.
+- `CONTRIBUTING.md` — engineering conventions. Every ticket follows them.
+- `src/app.js` exports `createApp()` returning an `http.Server` that is not yet
+ listening; `node src/index.js ` starts the service.
+- Run the tests with `npm test`.
diff --git a/docker/context-profiles/complex-eval/cases3/chained-tickets/files/package.json b/docker/context-profiles/complex-eval/cases3/chained-tickets/files/package.json
new file mode 100644
index 000000000..12bbcaf08
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases3/chained-tickets/files/package.json
@@ -0,0 +1,6 @@
+{
+ "name": "shortlink",
+ "private": true,
+ "type": "commonjs",
+ "scripts": { "test": "node --test test/*.test.js" }
+}
diff --git a/docker/context-profiles/complex-eval/cases3/chained-tickets/meta.json b/docker/context-profiles/complex-eval/cases3/chained-tickets/meta.json
new file mode 100644
index 000000000..30eb9fb05
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases3/chained-tickets/meta.json
@@ -0,0 +1,17 @@
+{
+ "id": "chained-tickets",
+ "category": "long-horizon-chain",
+ "manualIds": [],
+ "checkTimeoutMs": 60000,
+ "steps": [
+ { "manualIds": ["skill:backend-patterns"] },
+ { "manualIds": ["skill:backend-patterns"] },
+ { "manualIds": ["skill:security-review"] },
+ { "manualIds": ["skill:api-design"] }
+ ],
+ "selection": {
+ "id": "complex-chained-tickets",
+ "category": "complex-long-horizon",
+ "expectedIds": ["skill:backend-patterns"]
+ }
+}
diff --git a/docker/context-profiles/complex-eval/cases3/chained-tickets/steps/01-core/check.cjs b/docker/context-profiles/complex-eval/cases3/chained-tickets/steps/01-core/check.cjs
new file mode 100644
index 000000000..cda5c3028
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases3/chained-tickets/steps/01-core/check.cjs
@@ -0,0 +1,95 @@
+'use strict';
+// Step 1 grader: core API contract + conventions (envelope, layering, changelog, tests).
+const fs = require('node:fs');
+const path = require('node:path');
+
+const checks = [];
+const record = (name, ok) => checks.push({ name, ok: Boolean(ok) });
+let finished = false;
+function finish() {
+ if (finished) return;
+ finished = true;
+ for (let i = checks.length; i < 10; i++) record(`unreached-${i + 1}`, false);
+ const ok = checks.filter(c => c.ok).length;
+ for (const c of checks) process.stdout.write(`${c.ok ? 'ok' : 'not ok'} - ${c.name}\n`);
+ process.stdout.write(`ECC_EVAL_SCORE ${JSON.stringify({ score: ok / 10, passed: ok, total: 10 })}\n`);
+ process.exit(0);
+}
+// A crashing agent server must not kill the grader: score what completed.
+process.on('uncaughtException', finish);
+process.on('unhandledRejection', finish);
+const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
+const root = process.cwd();
+const hasEnvelope = body => body && body.error && typeof body.error.code === 'string'
+ && /^[A-Z][A-Z0-9_]+$/.test(body.error.code) && typeof body.error.message === 'string';
+
+(async () => {
+ let createApp;
+ try { ({ createApp } = require(path.join(root, 'src', 'app.js'))); } catch { /* scored below */ }
+ if (typeof createApp === 'function') {
+ try {
+ const app = createApp();
+ await new Promise(resolve => app.listen(0, '127.0.0.1', resolve));
+ const port = app.address().port;
+ const post = (body) => fetch(`http://127.0.0.1:${port}/links`, {
+ method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });
+ const get = (p) => fetch(`http://127.0.0.1:${port}${p}`, { redirect: 'manual' });
+
+ const created = await post({ url: 'https://example.com/landing' });
+ const createdBody = await created.json().catch(() => null);
+ record('create-happy-201', created.status === 201 && createdBody
+ && /^[A-Za-z0-9]{6,10}$/.test(createdBody.code || '') && typeof createdBody.shortUrl === 'string'
+ && typeof createdBody.expiresAt === 'string' && !Number.isNaN(Date.parse(createdBody.expiresAt)));
+
+ let code = createdBody && createdBody.code;
+ if (code) {
+ const redirect = await get(`/${code}`);
+ record('redirect-302-location', redirect.status === 302
+ && redirect.headers.get('location') === 'https://example.com/landing');
+ } else record('redirect-302-location', false);
+
+ const unknown = await get('/nope00');
+ record('unknown-code-404-envelope', unknown.status === 404 && hasEnvelope(await unknown.json().catch(() => null)));
+
+ const badUrl = await post({ url: 'notaurl' });
+ record('invalid-url-400-envelope', badUrl.status === 400 && hasEnvelope(await badUrl.json().catch(() => null)));
+ const noBody = await post({});
+ record('missing-url-400-envelope', noBody.status === 400 && hasEnvelope(await noBody.json().catch(() => null)));
+ const badTtl = await post({ url: 'https://example.com', ttlSeconds: 99999999 });
+ record('ttl-bounds-400-envelope', badTtl.status === 400 && hasEnvelope(await badTtl.json().catch(() => null)));
+
+ const expiring = await post({ url: 'https://example.com/gone', ttlSeconds: 1 });
+ const expiringBody = await expiring.json().catch(() => null);
+ if (expiringBody && expiringBody.code) {
+ await sleep(1300);
+ const gone = await get(`/${expiringBody.code}`);
+ record('expired-link-410-envelope', gone.status === 410 && hasEnvelope(await gone.json().catch(() => null)));
+ } else record('expired-link-410-envelope', false);
+
+ if (code) {
+ const del = await fetch(`http://127.0.0.1:${port}/links/${code}`, { method: 'DELETE' });
+ const after = await get(`/${code}`);
+ record('delete-flow-204-then-404', del.status === 204 && after.status === 404);
+ } else record('delete-flow-204-then-404', false);
+ app.close();
+ } catch { /* remaining checks unscored */ }
+ } else {
+ for (const name of ['create-happy-201', 'redirect-302-location', 'unknown-code-404-envelope',
+ 'invalid-url-400-envelope', 'missing-url-400-envelope', 'ttl-bounds-400-envelope',
+ 'expired-link-410-envelope', 'delete-flow-204-then-404']) record(name, false);
+ }
+
+ // Conventions.
+ let changelog = '';
+ try { changelog = fs.readFileSync(path.join(root, 'CHANGELOG.md'), 'utf8'); } catch { /* missing */ }
+ let tests = '';
+ try {
+ for (const f of fs.readdirSync(path.join(root, 'test'))) tests += fs.readFileSync(path.join(root, 'test', f), 'utf8');
+ } catch { /* missing */ }
+ const testCount = (tests.match(/\btest\(/g) || []).length;
+ record('changelog-and-tests', changelog.length > 20 && testCount >= 3);
+ record('layering-files', ['routes.js', 'service.js', 'store.js']
+ .every(f => fs.existsSync(path.join(root, 'src', f))));
+
+ finish();
+})();
diff --git a/docker/context-profiles/complex-eval/cases3/chained-tickets/steps/01-core/query.md b/docker/context-profiles/complex-eval/cases3/chained-tickets/steps/01-core/query.md
new file mode 100644
index 000000000..2c00246ec
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases3/chained-tickets/steps/01-core/query.md
@@ -0,0 +1 @@
+Implement the link shortener described in API.md. Follow CONTRIBUTING.md — every convention applies.
diff --git a/docker/context-profiles/complex-eval/cases3/chained-tickets/steps/02-persistence/check.cjs b/docker/context-profiles/complex-eval/cases3/chained-tickets/steps/02-persistence/check.cjs
new file mode 100644
index 000000000..ce42427f4
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases3/chained-tickets/steps/02-persistence/check.cjs
@@ -0,0 +1,106 @@
+'use strict';
+// Step 2 grader: persistence across a simulated restart (fresh module state,
+// same DATA_FILE), expiry state survives, fresh/corrupt-start tolerance, conventions.
+const fs = require('node:fs');
+const path = require('node:path');
+
+const checks = [];
+const record = (name, ok) => checks.push({ name, ok: Boolean(ok) });
+let finished = false;
+function finish() {
+ if (finished) return;
+ finished = true;
+ for (let i = checks.length; i < 7; i++) record(`unreached-${i + 1}`, false);
+ const ok = checks.filter(c => c.ok).length;
+ for (const c of checks) process.stdout.write(`${c.ok ? 'ok' : 'not ok'} - ${c.name}\n`);
+ process.stdout.write(`ECC_EVAL_SCORE ${JSON.stringify({ score: ok / 7, passed: ok, total: 7 })}\n`);
+ process.exit(0);
+}
+// A crashing agent server must not kill the grader: score what completed.
+process.on('uncaughtException', finish);
+process.on('unhandledRejection', finish);
+const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
+const root = process.cwd();
+const DATA_FILE = path.join(root, '.ecc-data', 'links.json');
+const hasEnvelope = body => body && body.error && typeof body.error.code === 'string'
+ && /^[A-Z][A-Z0-9_]+$/.test(body.error.code) && typeof body.error.message === 'string';
+
+function purgeApp() {
+ for (const key of Object.keys(require.cache)) {
+ if (key.startsWith(path.join(root, 'src') + path.sep)) delete require.cache[key];
+ }
+}
+
+async function start() {
+ purgeApp();
+ const { createApp } = require(path.join(root, 'src', 'app.js'));
+ const app = createApp();
+ await new Promise((resolve, reject) => { app.once('error', reject); app.listen(0, '127.0.0.1', resolve); });
+ return app;
+}
+
+(async () => {
+ process.env.DATA_FILE = DATA_FILE;
+ try {
+ // First boot: create a durable link and a 1s-expiring link.
+ let app = await start();
+ let port = app.address().port;
+ const post = body => fetch(`http://127.0.0.1:${port}/links`, {
+ method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });
+ const durable = await (await post({ url: 'https://example.com/durable' })).json().catch(() => null);
+ const short = await (await post({ url: 'https://example.com/short', ttlSeconds: 1 })).json().catch(() => null);
+ await new Promise(resolve => app.close(resolve));
+
+ // Restart: fresh modules, same DATA_FILE.
+ app = await start();
+ port = app.address().port;
+ const get = p => fetch(`http://127.0.0.1:${port}${p}`, { redirect: 'manual' });
+
+ const after = durable && durable.code ? await get(`/${durable.code}`) : null;
+ record('link-survives-restart', after && after.status === 302
+ && after.headers.get('location') === 'https://example.com/durable');
+
+ await sleep(1300);
+ const expiredAfter = short && short.code ? await get(`/${short.code}`) : null;
+ record('expiry-survives-restart', expiredAfter && expiredAfter.status === 410);
+ await new Promise(resolve => app.close(resolve));
+
+ // Data file is real JSON on disk.
+ let dataOk = false;
+ try { JSON.parse(fs.readFileSync(DATA_FILE, 'utf8')); dataOk = true; } catch { /* missing/invalid */ }
+ record('data-file-is-json', dataOk);
+
+ // Fresh start with no data file present.
+ fs.rmSync(DATA_FILE, { force: true });
+ app = await start();
+ port = app.address().port;
+ const fresh = await fetch(`http://127.0.0.1:${port}/links`, {
+ method: 'POST', headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ url: 'https://example.com/fresh' }) });
+ record('fresh-start-without-data-file', fresh.status === 201);
+ await new Promise(resolve => app.close(resolve));
+
+ // Corrupt data file must not kill the service.
+ fs.mkdirSync(path.dirname(DATA_FILE), { recursive: true });
+ fs.writeFileSync(DATA_FILE, 'garbage{{{');
+ app = await start();
+ port = app.address().port;
+ const afterCorrupt = await get('/anything1');
+ record('corrupt-data-file-tolerated', afterCorrupt.status === 404
+ && hasEnvelope(await afterCorrupt.json().catch(() => null)));
+ await new Promise(resolve => app.close(resolve));
+ fs.rmSync(DATA_FILE, { force: true });
+ } catch { /* remaining checks unscored */ }
+
+ let changelog = '';
+ try { changelog = fs.readFileSync(path.join(root, 'CHANGELOG.md'), 'utf8'); } catch { /* missing */ }
+ let tests = '';
+ try {
+ for (const f of fs.readdirSync(path.join(root, 'test'))) tests += fs.readFileSync(path.join(root, 'test', f), 'utf8');
+ } catch { /* missing */ }
+ const changelogEntries = (changelog.match(/^[-*#]/gm) || []).length;
+ record('changelog-grown', changelogEntries >= 2 && /persist|restart|data/i.test(changelog));
+ record('tests-grown', (tests.match(/\btest\(/g) || []).length >= 6);
+
+ finish();
+})();
diff --git a/docker/context-profiles/complex-eval/cases3/chained-tickets/steps/02-persistence/query.md b/docker/context-profiles/complex-eval/cases3/chained-tickets/steps/02-persistence/query.md
new file mode 100644
index 000000000..544b2f51e
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases3/chained-tickets/steps/02-persistence/query.md
@@ -0,0 +1 @@
+Links need to survive a service restart. Persist them to the JSON file named by the DATA_FILE environment variable (read at startup). Take care of it.
diff --git a/docker/context-profiles/complex-eval/cases3/chained-tickets/steps/03-abuse/check.cjs b/docker/context-profiles/complex-eval/cases3/chained-tickets/steps/03-abuse/check.cjs
new file mode 100644
index 000000000..829abd522
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases3/chained-tickets/steps/03-abuse/check.cjs
@@ -0,0 +1,83 @@
+'use strict';
+// Step 3 grader: abuse handling — URL validation, size limits, rate limiting —
+// plus conventions. Hammer probe runs last so earlier probes stay unthrottled.
+const fs = require('node:fs');
+const path = require('node:path');
+
+const checks = [];
+const record = (name, ok) => checks.push({ name, ok: Boolean(ok) });
+let finished = false;
+function finish() {
+ if (finished) return;
+ finished = true;
+ for (let i = checks.length; i < 8; i++) record(`unreached-${i + 1}`, false);
+ const ok = checks.filter(c => c.ok).length;
+ for (const c of checks) process.stdout.write(`${c.ok ? 'ok' : 'not ok'} - ${c.name}\n`);
+ process.stdout.write(`ECC_EVAL_SCORE ${JSON.stringify({ score: ok / 8, passed: ok, total: 8 })}\n`);
+ process.exit(0);
+}
+// A crashing agent server must not kill the grader: score what completed.
+process.on('uncaughtException', finish);
+process.on('unhandledRejection', finish);
+const root = process.cwd();
+const DATA_FILE = path.join(root, '.ecc-data', 'links-step3.json');
+const hasEnvelope = body => body && body.error && typeof body.error.code === 'string'
+ && /^[A-Z][A-Z0-9_]+$/.test(body.error.code) && typeof body.error.message === 'string';
+
+function purgeApp() {
+ for (const key of Object.keys(require.cache)) {
+ if (key.startsWith(path.join(root, 'src') + path.sep)) delete require.cache[key];
+ }
+}
+
+(async () => {
+ process.env.DATA_FILE = DATA_FILE;
+ try {
+ purgeApp();
+ const { createApp } = require(path.join(root, 'src', 'app.js'));
+ const app = createApp();
+ await new Promise(resolve => app.listen(0, '127.0.0.1', resolve));
+ const port = app.address().port;
+ const post = body => fetch(`http://127.0.0.1:${port}/links`, {
+ method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });
+
+ const okCreate = await post({ url: 'https://example.com/normal' });
+ record('normal-create-still-201', okCreate.status === 201);
+
+ const js = await post({ url: 'javascript:alert(1)' });
+ record('javascript-scheme-400-envelope', js.status === 400 && hasEnvelope(await js.json().catch(() => null)));
+ const ftp = await post({ url: 'ftp://files.example.com/x' });
+ record('non-http-scheme-400-envelope', ftp.status === 400 && hasEnvelope(await ftp.json().catch(() => null)));
+ const huge = await post({ url: `https://example.com/${'a'.repeat(10000)}` });
+ const hugeBody = await huge.json().catch(() => null);
+ record('oversize-url-4xx-envelope', huge.status >= 400 && huge.status < 500 && hasEnvelope(hugeBody));
+
+ // Hammer: 60 rapid creates must trip a 429 with the envelope.
+ const responses = await Promise.all(Array.from({ length: 60 }, (_, i) =>
+ post({ url: `https://example.com/flood-${i}` })));
+ const limited = [];
+ for (const r of responses) if (r.status === 429) limited.push(await r.json().catch(() => null));
+ record('rate-limit-429-envelope', limited.length > 0 && limited.every(hasEnvelope));
+ app.close();
+ } catch { /* remaining checks unscored */ }
+
+ let sources = '';
+ try {
+ for (const f of fs.readdirSync(path.join(root, 'src'))) {
+ if (f.endsWith('.js')) sources += fs.readFileSync(path.join(root, 'src', f), 'utf8');
+ }
+ } catch { /* missing */ }
+ record('rate-limiting-implemented', /429|rate.?limit/i.test(sources));
+
+ let changelog = '';
+ try { changelog = fs.readFileSync(path.join(root, 'CHANGELOG.md'), 'utf8'); } catch { /* missing */ }
+ let tests = '';
+ try {
+ for (const f of fs.readdirSync(path.join(root, 'test'))) tests += fs.readFileSync(path.join(root, 'test', f), 'utf8');
+ } catch { /* missing */ }
+ const changelogEntries = (changelog.match(/^[-*#]/gm) || []).length;
+ record('changelog-grown', changelogEntries >= 3 && /abuse|rate|valid|secur/i.test(changelog));
+ record('tests-grown', (tests.match(/\btest\(/g) || []).length >= 9);
+
+ finish();
+})();
diff --git a/docker/context-profiles/complex-eval/cases3/chained-tickets/steps/03-abuse/query.md b/docker/context-profiles/complex-eval/cases3/chained-tickets/steps/03-abuse/query.md
new file mode 100644
index 000000000..799adaf89
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases3/chained-tickets/steps/03-abuse/query.md
@@ -0,0 +1 @@
+We're seeing abuse — people hammering the API and submitting junk URLs. Deal with it.
diff --git a/docker/context-profiles/complex-eval/cases3/chained-tickets/steps/04-analytics/check.cjs b/docker/context-profiles/complex-eval/cases3/chained-tickets/steps/04-analytics/check.cjs
new file mode 100644
index 000000000..ed2e69364
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases3/chained-tickets/steps/04-analytics/check.cjs
@@ -0,0 +1,88 @@
+'use strict';
+// Step 4 grader: hit analytics consistent with the existing API, conventions,
+// docs and tests. (Runs in a later process than step 3, so rate windows cleared.)
+const fs = require('node:fs');
+const path = require('node:path');
+
+const checks = [];
+const record = (name, ok) => checks.push({ name, ok: Boolean(ok) });
+let finished = false;
+function finish() {
+ if (finished) return;
+ finished = true;
+ for (let i = checks.length; i < 8; i++) record(`unreached-${i + 1}`, false);
+ const ok = checks.filter(c => c.ok).length;
+ for (const c of checks) process.stdout.write(`${c.ok ? 'ok' : 'not ok'} - ${c.name}\n`);
+ process.stdout.write(`ECC_EVAL_SCORE ${JSON.stringify({ score: ok / 8, passed: ok, total: 8 })}\n`);
+ process.exit(0);
+}
+// A crashing agent server must not kill the grader: score what completed.
+process.on('uncaughtException', finish);
+process.on('unhandledRejection', finish);
+const root = process.cwd();
+const DATA_FILE = path.join(root, '.ecc-data', 'links-step4.json');
+const hasEnvelope = body => body && body.error && typeof body.error.code === 'string'
+ && /^[A-Z][A-Z0-9_]+$/.test(body.error.code) && typeof body.error.message === 'string';
+
+function purgeApp() {
+ for (const key of Object.keys(require.cache)) {
+ if (key.startsWith(path.join(root, 'src') + path.sep)) delete require.cache[key];
+ }
+}
+
+(async () => {
+ process.env.DATA_FILE = DATA_FILE;
+ try {
+ purgeApp();
+ const { createApp } = require(path.join(root, 'src', 'app.js'));
+ const app = createApp();
+ await new Promise(resolve => app.listen(0, '127.0.0.1', resolve));
+ const port = app.address().port;
+
+ const created = await fetch(`http://127.0.0.1:${port}/links`, {
+ method: 'POST', headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ url: 'https://example.com/tracked' }) });
+ const body = await created.json().catch(() => null);
+ const code = body && body.code;
+ record('create-still-works', created.status === 201 && Boolean(code));
+
+ if (code) {
+ const before = await fetch(`http://127.0.0.1:${port}/links/${code}/stats`);
+ const beforeBody = await before.json().catch(() => null);
+ record('stats-zero-before-redirects', before.status === 200 && beforeBody && beforeBody.hits === 0);
+
+ for (let i = 0; i < 3; i++) {
+ await fetch(`http://127.0.0.1:${port}/${code}`, { redirect: 'manual' });
+ }
+ const stats = await fetch(`http://127.0.0.1:${port}/links/${code}/stats`);
+ const statsBody = await stats.json().catch(() => null);
+ record('stats-count-three-hits', stats.status === 200 && statsBody && statsBody.hits === 3);
+
+ const redirect = await fetch(`http://127.0.0.1:${port}/${code}`, { redirect: 'manual' });
+ record('redirect-still-302', redirect.status === 302);
+
+ const missing = await fetch(`http://127.0.0.1:${port}/links/zzzzzz/stats`);
+ record('stats-unknown-404-envelope', missing.status === 404
+ && hasEnvelope(await missing.json().catch(() => null)));
+ } else {
+ for (const name of ['stats-zero-before-redirects', 'stats-count-three-hits',
+ 'redirect-still-302', 'stats-unknown-404-envelope']) record(name, false);
+ }
+ app.close();
+ } catch { /* remaining checks unscored */ }
+
+ let readme = '';
+ try { readme = fs.readFileSync(path.join(root, 'README.md'), 'utf8'); } catch { /* missing */ }
+ record('readme-documents-stats', /\/stats|hits|analytics/i.test(readme));
+ let changelog = '';
+ try { changelog = fs.readFileSync(path.join(root, 'CHANGELOG.md'), 'utf8'); } catch { /* missing */ }
+ let tests = '';
+ try {
+ for (const f of fs.readdirSync(path.join(root, 'test'))) tests += fs.readFileSync(path.join(root, 'test', f), 'utf8');
+ } catch { /* missing */ }
+ const changelogEntries = (changelog.match(/^[-*#]/gm) || []).length;
+ record('changelog-grown', changelogEntries >= 4 && /stat|analytic|hit/i.test(changelog));
+ record('tests-grown', (tests.match(/\btest\(/g) || []).length >= 12);
+
+ finish();
+})();
diff --git a/docker/context-profiles/complex-eval/cases3/chained-tickets/steps/04-analytics/query.md b/docker/context-profiles/complex-eval/cases3/chained-tickets/steps/04-analytics/query.md
new file mode 100644
index 000000000..619549068
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases3/chained-tickets/steps/04-analytics/query.md
@@ -0,0 +1 @@
+Track redirect hits per link and expose them at GET /links/:code/stats, consistent with the existing API.
diff --git a/docker/context-profiles/complex-eval/cases3/idempotent-webhooks/check.cjs b/docker/context-profiles/complex-eval/cases3/idempotent-webhooks/check.cjs
new file mode 100644
index 000000000..7882bce07
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases3/idempotent-webhooks/check.cjs
@@ -0,0 +1,119 @@
+'use strict';
+// Hidden grader for idempotent-webhooks: exactly-once under sequential,
+// concurrent, and mixed-concurrent duplicates, plus the documented API,
+// regression coverage, and hygiene. Prints ECC_EVAL_SCORE and always exits 0.
+const fs = require('node:fs');
+const path = require('node:path');
+
+const checks = [];
+const record = (name, ok) => checks.push({ name, ok: Boolean(ok) });
+let finished = false;
+function finish() {
+ if (finished) return;
+ finished = true;
+ for (let i = checks.length; i < 12; i++) record(`unreached-${i + 1}`, false);
+ const ok = checks.filter(c => c.ok).length;
+ for (const c of checks) process.stdout.write(`${c.ok ? 'ok' : 'not ok'} - ${c.name}\n`);
+ process.stdout.write(`ECC_EVAL_SCORE ${JSON.stringify({ score: ok / 12, passed: ok, total: 12 })}\n`);
+ process.exit(0);
+}
+// A crashing agent server must not kill the grader: score what completed.
+process.on('uncaughtException', finish);
+process.on('unhandledRejection', finish);
+const root = process.cwd();
+const hasEnvelope = body => body && body.error && typeof body.error.code === 'string'
+ && /^[A-Z][A-Z0-9_]+$/.test(body.error.code) && typeof body.error.message === 'string';
+
+(async () => {
+ let createApp;
+ let store;
+ try {
+ ({ createApp } = require(path.join(root, 'src', 'app.js')));
+ ({ store } = require(path.join(root, 'src', 'store.js')));
+ } catch { /* scored below */ }
+ if (typeof createApp === 'function' && store && Array.isArray(store.paymentLog)) {
+ try {
+ const app = createApp();
+ await new Promise(resolve => app.listen(0, '127.0.0.1', resolve));
+ const port = app.address().port;
+ const send = (eventId, orderId, amountCents) => fetch(`http://127.0.0.1:${port}/webhooks/payments`, {
+ method: 'POST', headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ eventId, orderId, amountCents, type: 'payment.succeeded' }) });
+ const logsFor = orderId => store.paymentLog.filter(p => p.orderId === orderId).length;
+
+ // 1: single delivery applies once.
+ const single = await send('ev-1', 'o1', 5000);
+ const singleBody = await single.json().catch(() => null);
+ record('single-delivery-processed', single.status === 200 && singleBody
+ && singleBody.status === 'processed' && singleBody.orderId === 'o1' && logsFor('o1') === 1);
+
+ // 2: sequential retry replays without re-applying.
+ const retry = await send('ev-1', 'o1', 5000);
+ const retryBody = await retry.json().catch(() => null);
+ record('sequential-duplicate-inert', retry.status === 200 && retryBody
+ && retryBody.status === 'duplicate' && logsFor('o1') === 1);
+
+ // 3: fifty concurrent identical deliveries apply exactly once.
+ const storm = await Promise.all(Array.from({ length: 50 }, () => send('ev-2', 'o2', 12500)));
+ const stormBodies = [];
+ for (const r of storm) stormBodies.push(await r.json().catch(() => null));
+ const processedCount = stormBodies.filter(b => b && b.status === 'processed').length;
+ const duplicateCount = stormBodies.filter(b => b && b.status === 'duplicate').length;
+ record('concurrent-storm-exactly-once', storm.every(r => r.status === 200)
+ && processedCount === 1 && duplicateCount === 49 && logsFor('o2') === 1
+ && store.orders.get('o2').paymentsApplied === 1);
+
+ // 4: a different event for an already-paid order is already_paid and inert.
+ const second = await send('ev-3', 'o2', 12500);
+ const secondBody = await second.json().catch(() => null);
+ record('already-paid-order-inert', second.status === 200 && secondBody
+ && secondBody.status === 'already_paid' && logsFor('o2') === 1);
+
+ // 5-7: contract errors with envelopes.
+ const unknown = await send('ev-4', 'nope', 100);
+ record('unknown-order-404-envelope', unknown.status === 404 && hasEnvelope(await unknown.json().catch(() => null)));
+ const malformed = await fetch(`http://127.0.0.1:${port}/webhooks/payments`, {
+ method: 'POST', headers: { 'content-type': 'application/json' }, body: '{bad json' });
+ record('malformed-body-400-envelope', malformed.status === 400 && hasEnvelope(await malformed.json().catch(() => null)));
+ const mismatch = await send('ev-5', 'o3', 999999);
+ record('amount-mismatch-422-envelope', mismatch.status === 422
+ && hasEnvelope(await mismatch.json().catch(() => null)) && logsFor('o3') === 0);
+
+ // 8: mixed storm — three orders, three eventIds, ten duplicates each, all concurrent.
+ const mixed = await Promise.all(['o4', 'o5', 'o6'].flatMap(orderId =>
+ Array.from({ length: 10 }, () => send(`ev-${orderId}`, orderId, store.orders.get(orderId).amountCents))));
+ for (const r of mixed) await r.json().catch(() => null);
+ record('mixed-storm-each-order-once', ['o4', 'o5', 'o6'].every(orderId =>
+ logsFor(orderId) === 1 && store.orders.get(orderId).paymentsApplied === 1));
+
+ // 9: order inspection endpoint reflects reality.
+ const orderView = await fetch(`http://127.0.0.1:${port}/orders/o2`);
+ const orderBody = await orderView.json().catch(() => null);
+ record('order-endpoint-accurate', orderView.status === 200 && orderBody
+ && orderBody.status === 'paid' && orderBody.paymentsApplied === 1 && Boolean(orderBody.paidAt));
+
+ app.close();
+ } catch { /* remaining checks unscored */ }
+ } else {
+ for (const name of ['single-delivery-processed', 'sequential-duplicate-inert', 'concurrent-storm-exactly-once',
+ 'already-paid-order-inert', 'unknown-order-404-envelope', 'malformed-body-400-envelope',
+ 'amount-mismatch-422-envelope', 'mixed-storm-each-order-once', 'order-endpoint-accurate']) record(name, false);
+ }
+
+ // Conventions.
+ let tests = '';
+ try {
+ for (const f of fs.readdirSync(path.join(root, 'test'))) tests += fs.readFileSync(path.join(root, 'test', f), 'utf8');
+ } catch { /* missing */ }
+ record('concurrency-regression-tests', (tests.match(/\btest\(/g) || []).length >= 4
+ && /Promise\.all|concurrent|duplicate|retry/i.test(tests));
+ let changelog = '';
+ try { changelog = fs.readFileSync(path.join(root, 'CHANGELOG.md'), 'utf8'); } catch { /* missing */ }
+ record('changelog-entry', /idem|duplicat|retry|inc-104|race/i.test(changelog));
+ try {
+ const pkg = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'));
+ record('no-external-dependencies', !pkg.dependencies && !pkg.devDependencies);
+ } catch { record('no-external-dependencies', false); }
+
+ finish();
+})();
diff --git a/docker/context-profiles/complex-eval/cases3/idempotent-webhooks/files/README.md b/docker/context-profiles/complex-eval/cases3/idempotent-webhooks/files/README.md
new file mode 100644
index 000000000..512c8c059
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases3/idempotent-webhooks/files/README.md
@@ -0,0 +1,12 @@
+# webhook-receiver
+
+Receives payment webhooks. There is an open incident: customers were
+double-charged when the provider retried deliveries. See `SPEC.md` for the
+contract, including the exactly-once rules.
+
+- `src/app.js` exports `createApp()` returning an `http.Server` that is not
+ yet listening; `node src/index.js ` starts the service.
+- `src/store.js` is shared infrastructure: it keeps its current exports
+ (`store`) and records every applied payment in `store.paymentLog`.
+- No external dependencies. `npm test` runs the tests. `CHANGELOG.md` records
+ every shipped change.
diff --git a/docker/context-profiles/complex-eval/cases3/idempotent-webhooks/files/SPEC.md b/docker/context-profiles/complex-eval/cases3/idempotent-webhooks/files/SPEC.md
new file mode 100644
index 000000000..e3dee27b1
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases3/idempotent-webhooks/files/SPEC.md
@@ -0,0 +1,30 @@
+# Payment webhook contract
+
+`POST /webhooks/payments` with JSON body
+`{ "eventId": string, "orderId": string, "amountCents": number, "type": "payment.succeeded" }`.
+
+Exactly-once is the point. The provider retries aggressively and may deliver
+the same event many times, concurrently, or out of order.
+
+- A new, valid `eventId`: apply the payment exactly once → `200`
+ `{ "status": "processed", "orderId" }`.
+- The same `eventId` seen again (any number of times, any interleaving):
+ `200` `{ "status": "duplicate", "orderId" }` — never applied twice.
+- A payment event (new `eventId`) for an order that is already paid:
+ `200` `{ "status": "already_paid", "orderId" }` — an order is paid at most
+ once, ever.
+- `amountCents` not matching the order's amount: `422`, not applied.
+- Unknown `orderId`: `404`. Malformed body (bad JSON, missing/invalid
+ fields): `400`.
+- Error responses use the envelope
+ `{ "error": { "code": "", "message": "..." } }`.
+
+`GET /orders/:id` → `200` `{ "id", "status", "paidAt", "paymentsApplied" }`
+or a `404` envelope.
+
+## Incident note
+
+INC-104: concurrent duplicate deliveries double-applied payments. The naive
+receiver checked "have we seen this event?" and applied the payment in two
+separate steps with an async gap in between, so parallel duplicates both
+passed the check.
diff --git a/docker/context-profiles/complex-eval/cases3/idempotent-webhooks/files/package.json b/docker/context-profiles/complex-eval/cases3/idempotent-webhooks/files/package.json
new file mode 100644
index 000000000..11c26f720
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases3/idempotent-webhooks/files/package.json
@@ -0,0 +1,6 @@
+{
+ "name": "webhook-receiver",
+ "private": true,
+ "type": "commonjs",
+ "scripts": { "test": "node --test test/*.test.js" }
+}
diff --git a/docker/context-profiles/complex-eval/cases3/idempotent-webhooks/files/src/app.js b/docker/context-profiles/complex-eval/cases3/idempotent-webhooks/files/src/app.js
new file mode 100644
index 000000000..6ba0ba755
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases3/idempotent-webhooks/files/src/app.js
@@ -0,0 +1,54 @@
+'use strict';
+const http = require('node:http');
+const { store } = require('./store');
+
+// INC-104 receiver: checks "seen this event?" and applies the payment in two
+// steps with an async gap in between. Concurrent duplicates both pass the
+// check. Do not keep this shape.
+function createApp() {
+ return http.createServer((req, res) => {
+ const url = new URL(req.url, 'http://localhost');
+
+ if (req.method === 'POST' && url.pathname === '/webhooks/payments') {
+ let body = '';
+ req.on('data', chunk => { body += chunk; });
+ req.on('end', async () => {
+ const parsed = JSON.parse(body);
+ const { eventId, orderId } = parsed;
+ if (store.processedEvents.has(eventId)) {
+ res.writeHead(200, { 'content-type': 'application/json' });
+ res.end(JSON.stringify({ status: 'duplicate', orderId }));
+ return;
+ }
+ await new Promise(resolve => setImmediate(resolve)); // async gap
+ const order = store.orders.get(orderId);
+ order.status = 'paid';
+ order.paidAt = new Date().toISOString();
+ order.paymentsApplied++;
+ store.paymentLog.push({ eventId, orderId, amountCents: parsed.amountCents });
+ store.processedEvents.add(eventId);
+ res.writeHead(200, { 'content-type': 'application/json' });
+ res.end(JSON.stringify({ status: 'processed', orderId }));
+ });
+ return;
+ }
+
+ const match = /^\/orders\/([\w-]+)$/.exec(url.pathname);
+ if (req.method === 'GET' && match) {
+ const order = store.orders.get(match[1]);
+ if (!order) {
+ res.writeHead(404, { 'content-type': 'application/json' });
+ res.end(JSON.stringify({ error: { code: 'NOT_FOUND', message: 'no such order' } }));
+ return;
+ }
+ res.writeHead(200, { 'content-type': 'application/json' });
+ res.end(JSON.stringify(order));
+ return;
+ }
+
+ res.writeHead(404, { 'content-type': 'application/json' });
+ res.end(JSON.stringify({ error: { code: 'NOT_FOUND', message: 'not found' } }));
+ });
+}
+
+module.exports = { createApp };
diff --git a/docker/context-profiles/complex-eval/cases3/idempotent-webhooks/files/src/index.js b/docker/context-profiles/complex-eval/cases3/idempotent-webhooks/files/src/index.js
new file mode 100644
index 000000000..90ef9215f
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases3/idempotent-webhooks/files/src/index.js
@@ -0,0 +1,7 @@
+'use strict';
+const { createApp } = require('./app');
+
+const port = Number(process.argv[2] || 8080);
+createApp().listen(port, () => {
+ console.log(`webhook-receiver listening on ${port}`);
+});
diff --git a/docker/context-profiles/complex-eval/cases3/idempotent-webhooks/files/src/store.js b/docker/context-profiles/complex-eval/cases3/idempotent-webhooks/files/src/store.js
new file mode 100644
index 000000000..64a4099a4
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases3/idempotent-webhooks/files/src/store.js
@@ -0,0 +1,18 @@
+'use strict';
+
+// Shared infrastructure. Every applied payment is appended to paymentLog;
+// orders and processedEvents track receiver state. Keep the `store` export.
+const store = {
+ orders: new Map([
+ ['o1', { id: 'o1', amountCents: 5000, status: 'pending', paidAt: null, paymentsApplied: 0 }],
+ ['o2', { id: 'o2', amountCents: 12500, status: 'pending', paidAt: null, paymentsApplied: 0 }],
+ ['o3', { id: 'o3', amountCents: 800, status: 'pending', paidAt: null, paymentsApplied: 0 }],
+ ['o4', { id: 'o4', amountCents: 9999, status: 'pending', paidAt: null, paymentsApplied: 0 }],
+ ['o5', { id: 'o5', amountCents: 250, status: 'pending', paidAt: null, paymentsApplied: 0 }],
+ ['o6', { id: 'o6', amountCents: 7300, status: 'pending', paidAt: null, paymentsApplied: 0 }],
+ ]),
+ paymentLog: [],
+ processedEvents: new Set(),
+};
+
+module.exports = { store };
diff --git a/docker/context-profiles/complex-eval/cases3/idempotent-webhooks/files/test/webhooks.test.js b/docker/context-profiles/complex-eval/cases3/idempotent-webhooks/files/test/webhooks.test.js
new file mode 100644
index 000000000..cf79f83d4
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases3/idempotent-webhooks/files/test/webhooks.test.js
@@ -0,0 +1,21 @@
+'use strict';
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const { createApp } = require('../src/app');
+const { store } = require('../src/store');
+
+test('a single payment event processes', async () => {
+ const server = createApp();
+ await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
+ try {
+ const port = server.address().port;
+ const res = await fetch(`http://127.0.0.1:${port}/webhooks/payments`, {
+ method: 'POST', headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ eventId: 'ev-test-1', orderId: 'o1', amountCents: 5000, type: 'payment.succeeded' }) });
+ assert.equal(res.status, 200);
+ assert.equal((await res.json()).status, 'processed');
+ assert.equal(store.orders.get('o1').status, 'paid');
+ } finally {
+ server.close();
+ }
+});
diff --git a/docker/context-profiles/complex-eval/cases3/idempotent-webhooks/meta.json b/docker/context-profiles/complex-eval/cases3/idempotent-webhooks/meta.json
new file mode 100644
index 000000000..d5d396e74
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases3/idempotent-webhooks/meta.json
@@ -0,0 +1,11 @@
+{
+ "id": "idempotent-webhooks",
+ "category": "concurrency-trap",
+ "manualIds": ["skill:error-handling"],
+ "checkTimeoutMs": 60000,
+ "selection": {
+ "id": "complex-idempotent-webhooks",
+ "category": "complex-concurrency-trap",
+ "expectedIds": ["skill:error-handling"]
+ }
+}
diff --git a/docker/context-profiles/complex-eval/cases3/idempotent-webhooks/query.md b/docker/context-profiles/complex-eval/cases3/idempotent-webhooks/query.md
new file mode 100644
index 000000000..f2902f874
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases3/idempotent-webhooks/query.md
@@ -0,0 +1 @@
+The payments provider retries aggressively and sometimes delivers the same webhook many times concurrently. Our receiver double-charges customers when that happens — see the incident note in SPEC.md. Rework the receiver so the full contract in SPEC.md holds: duplicates must never double-apply under any interleaving, and the documented API and the store contract stay intact. `npm test` must pass, and add regression coverage for the concurrent-duplicate case so INC-104 can't come back.
diff --git a/docker/context-profiles/complex-eval/cases3/production-ready/check.cjs b/docker/context-profiles/complex-eval/cases3/production-ready/check.cjs
new file mode 100644
index 000000000..1320f0e9f
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases3/production-ready/check.cjs
@@ -0,0 +1,133 @@
+'use strict';
+// Hidden grader for production-ready: probes every dimension of the documented
+// production bar. Prints ECC_EVAL_SCORE and always exits 0.
+const fs = require('node:fs');
+const path = require('node:path');
+
+const checks = [];
+const record = (name, ok) => checks.push({ name, ok: Boolean(ok) });
+let finished = false;
+function finish() {
+ if (finished) return;
+ finished = true;
+ for (let i = checks.length; i < 16; i++) record(`unreached-${i + 1}`, false);
+ const ok = checks.filter(c => c.ok).length;
+ for (const c of checks) process.stdout.write(`${c.ok ? 'ok' : 'not ok'} - ${c.name}\n`);
+ process.stdout.write(`ECC_EVAL_SCORE ${JSON.stringify({ score: ok / 16, passed: ok, total: 16 })}\n`);
+ process.exit(0);
+}
+// A crashing agent server must not kill the grader: score what completed.
+process.on('uncaughtException', finish);
+process.on('unhandledRejection', finish);
+const root = process.cwd();
+const hasEnvelope = body => body && body.error && typeof body.error.code === 'string'
+ && /^[A-Z][A-Z0-9_]+$/.test(body.error.code) && typeof body.error.message === 'string';
+
+(async () => {
+ let createApp;
+ try { ({ createApp } = require(path.join(root, 'src', 'app.js'))); } catch { /* scored below */ }
+ if (typeof createApp === 'function') {
+ // Capture console output during the probe run to inspect request logging.
+ const logged = [];
+ const originalLog = console.log;
+ const originalError = console.error;
+ console.log = (...args) => { logged.push(args.join(' ')); };
+ console.error = (...args) => { logged.push(args.join(' ')); };
+ try {
+ const app = createApp();
+ await new Promise(resolve => app.listen(0, '127.0.0.1', resolve));
+ const port = app.address().port;
+ const api = (p, options) => fetch(`http://127.0.0.1:${port}${p}`, options);
+ const post = body => api('/notes', { method: 'POST', headers: { 'content-type': 'application/json' }, body });
+
+ // Documented API still works.
+ const created = await post(JSON.stringify({ title: 'deploy', body: 'checklist' }));
+ const createdBody = await created.json().catch(() => null);
+ record('api-roundtrip-preserved', created.status === 201 && createdBody && createdBody.id
+ && (await (await api(`/notes/${createdBody.id}`)).json().catch(() => ({}))).title === 'deploy'
+ && Array.isArray((await (await api('/notes')).json().catch(() => ({}))).notes));
+
+ // Validation and envelope discipline.
+ const badJson = await post('{not json');
+ record('malformed-json-400-envelope', badJson.status === 400 && hasEnvelope(await badJson.json().catch(() => null)));
+ const missing = await post(JSON.stringify({ body: 'no title' }));
+ record('missing-field-400-envelope', missing.status === 400 && hasEnvelope(await missing.json().catch(() => null)));
+ const wrongType = await post(JSON.stringify({ title: 42, body: 'x' }));
+ record('wrong-type-400-envelope', wrongType.status === 400 && hasEnvelope(await wrongType.json().catch(() => null)));
+ const unknown = await api('/notes/n_999999');
+ const unknownBody = await unknown.text();
+ let unknownParsed = null;
+ try { unknownParsed = JSON.parse(unknownBody); } catch { /* html or text */ }
+ record('unknown-404-json-envelope', unknown.status === 404 && hasEnvelope(unknownParsed));
+
+ // Body limit.
+ const big = await post(JSON.stringify({ title: 'big', body: 'x'.repeat(100 * 1024) }));
+ record('oversize-body-413-envelope', big.status === 413 && hasEnvelope(await big.json().catch(() => null)));
+
+ // Health endpoint.
+ const health = await api('/health');
+ const healthBody = await health.json().catch(() => null);
+ record('health-endpoint', health.status === 200 && healthBody && healthBody.status === 'ok');
+
+ // Security header on a normal response.
+ const headers = await api('/notes');
+ record('nosniff-header', headers.headers.get('x-content-type-options') === 'nosniff');
+
+ // Error responses carry JSON content type.
+ record('errors-are-json', /application\/json/.test(unknown.headers.get('content-type') || ''));
+
+ app.close();
+ } catch { /* remaining checks unscored */ } finally {
+ console.log = originalLog;
+ console.error = originalError;
+ }
+
+ // Structured request logging: at least one JSON line with method/path/status-ish fields.
+ const structured = logged.some(line => {
+ try {
+ const parsed = JSON.parse(line);
+ return parsed && typeof parsed === 'object'
+ && /method/i.test(Object.keys(parsed).join(' '))
+ && /path|url/i.test(Object.keys(parsed).join(' '))
+ && /status/i.test(Object.keys(parsed).join(' '));
+ } catch { return false; }
+ });
+ record('structured-request-logs', structured);
+ } else {
+ for (const name of ['api-roundtrip-preserved', 'malformed-json-400-envelope', 'missing-field-400-envelope',
+ 'wrong-type-400-envelope', 'unknown-404-json-envelope', 'oversize-body-413-envelope', 'health-endpoint',
+ 'nosniff-header', 'errors-are-json', 'structured-request-logs']) record(name, false);
+ }
+
+ // Static dimensions.
+ let sources = '';
+ const walk = directory => {
+ for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
+ const item = path.join(directory, entry.name);
+ if (entry.isDirectory()) walk(item);
+ else if (entry.name.endsWith('.js')) sources += fs.readFileSync(item, 'utf8');
+ }
+ };
+ try { walk(path.join(root, 'src')); } catch { /* none */ }
+ record('sigterm-graceful-shutdown', /SIGTERM/.test(sources));
+ record('env-config-port', /process\.env\.[A-Z_]*PORT/.test(sources));
+
+ let tests = '';
+ try {
+ for (const f of fs.readdirSync(path.join(root, 'test'))) tests += fs.readFileSync(path.join(root, 'test', f), 'utf8');
+ } catch { /* missing */ }
+ const testCount = (tests.match(/\btest\(/g) || []).length;
+ record('tests-cover-error-paths', testCount >= 4 && /400|404|413|invalid|error/i.test(tests));
+
+ let changelog = '';
+ try { changelog = fs.readFileSync(path.join(root, 'CHANGELOG.md'), 'utf8'); } catch { /* missing */ }
+ record('changelog-entry', changelog.length > 20 && /product|harden|valid|health|log/i.test(changelog));
+
+ record('no-leftover-todos', !/TODO|FIXME/.test(sources));
+ try {
+ const pkg = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'));
+ record('no-external-dependencies', !pkg.dependencies && !pkg.devDependencies);
+ } catch { record('no-external-dependencies', false); }
+
+ finish();
+})();
diff --git a/docker/context-profiles/complex-eval/cases3/production-ready/files/README.md b/docker/context-profiles/complex-eval/cases3/production-ready/files/README.md
new file mode 100644
index 000000000..e387bff31
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases3/production-ready/files/README.md
@@ -0,0 +1,19 @@
+# notes-service
+
+Tiny notes API. Hobby prototype state: it works on the happy path and that's
+about all that can be said for it.
+
+## API
+
+- `POST /notes` — body `{ "title": string, "body": string }` → `201` with
+ `{ "id", "title", "body" }`.
+- `GET /notes/:id` — `200` with the note, or `404`.
+- `GET /notes` — `200` with `{ "notes": [...] }`.
+
+`src/app.js` exports `createApp()` returning an `http.Server` that is not yet
+listening; `node src/index.js` starts the service. `npm test` runs the tests.
+
+## Operations
+
+`docs/production-bar.md` lists what every production service here must meet.
+`CHANGELOG.md` records every shipped change.
diff --git a/docker/context-profiles/complex-eval/cases3/production-ready/files/docs/production-bar.md b/docker/context-profiles/complex-eval/cases3/production-ready/files/docs/production-bar.md
new file mode 100644
index 000000000..af3df1c4c
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases3/production-ready/files/docs/production-bar.md
@@ -0,0 +1,21 @@
+# The production bar
+
+Every production service here meets all of the following, all the time:
+
+- **Validation**: malformed JSON, missing fields, and wrong types are rejected
+ with `400` and a structured JSON error body
+ `{ "error": { "code": "", "message": "..." } }`. Unknown
+ resources are `404` in the same envelope. No stack traces, no HTML errors,
+ no hanging connections.
+- **Body limits**: request bodies over 64 KB are rejected with `413`, same
+ envelope.
+- **Health**: `GET /health` returns `200` with `{ "status": "ok" }`.
+- **Logging**: one structured JSON log line per request with at least
+ `method`, `path`, and `status` fields.
+- **Configuration**: runtime configuration (port, limits) comes from
+ environment variables, read at startup. Nothing secret is hardcoded.
+- **Shutdown**: the service closes cleanly on `SIGTERM` (stops accepting,
+ drains, exits).
+- **Headers**: responses carry `X-Content-Type-Options: nosniff`.
+- **Tests**: the suite covers error paths, not just the happy path.
+- **Changelog**: every shipped change has a `CHANGELOG.md` entry.
diff --git a/docker/context-profiles/complex-eval/cases3/production-ready/files/package.json b/docker/context-profiles/complex-eval/cases3/production-ready/files/package.json
new file mode 100644
index 000000000..7cef6f8c0
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases3/production-ready/files/package.json
@@ -0,0 +1,6 @@
+{
+ "name": "notes-service",
+ "private": true,
+ "type": "commonjs",
+ "scripts": { "test": "node --test test/*.test.js" }
+}
diff --git a/docker/context-profiles/complex-eval/cases3/production-ready/files/src/app.js b/docker/context-profiles/complex-eval/cases3/production-ready/files/src/app.js
new file mode 100644
index 000000000..db7fe2695
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases3/production-ready/files/src/app.js
@@ -0,0 +1,50 @@
+'use strict';
+const http = require('node:http');
+
+// Prototype state: happy path only.
+const notes = new Map();
+let nextId = 1;
+
+function createApp() {
+ return http.createServer((req, res) => {
+ console.log('got a request');
+ const url = new URL(req.url, 'http://localhost');
+
+ if (req.method === 'POST' && url.pathname === '/notes') {
+ let body = '';
+ req.on('data', chunk => { body += chunk; });
+ req.on('end', () => {
+ const parsed = JSON.parse(body);
+ const id = `n_${nextId++}`;
+ notes.set(id, { id, title: parsed.title, body: parsed.body });
+ res.writeHead(201, { 'content-type': 'application/json' });
+ res.end(JSON.stringify(notes.get(id)));
+ });
+ return;
+ }
+
+ const match = /^\/notes\/([\w-]+)$/.exec(url.pathname);
+ if (req.method === 'GET' && match) {
+ const note = notes.get(match[1]);
+ if (!note) {
+ res.writeHead(404);
+ res.end('not found');
+ return;
+ }
+ res.writeHead(200, { 'content-type': 'application/json' });
+ res.end(JSON.stringify(note));
+ return;
+ }
+
+ if (req.method === 'GET' && url.pathname === '/notes') {
+ res.writeHead(200, { 'content-type': 'application/json' });
+ res.end(JSON.stringify({ notes: [...notes.values()] }));
+ return;
+ }
+
+ res.writeHead(404);
+ res.end('not found');
+ });
+}
+
+module.exports = { createApp };
diff --git a/docker/context-profiles/complex-eval/cases3/production-ready/files/src/index.js b/docker/context-profiles/complex-eval/cases3/production-ready/files/src/index.js
new file mode 100644
index 000000000..a71330e92
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases3/production-ready/files/src/index.js
@@ -0,0 +1,6 @@
+'use strict';
+const { createApp } = require('./app');
+
+createApp().listen(8080, () => {
+ console.log('notes listening on 8080');
+});
diff --git a/docker/context-profiles/complex-eval/cases3/production-ready/files/test/notes.test.js b/docker/context-profiles/complex-eval/cases3/production-ready/files/test/notes.test.js
new file mode 100644
index 000000000..51babd8fb
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases3/production-ready/files/test/notes.test.js
@@ -0,0 +1,21 @@
+'use strict';
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const { createApp } = require('../src/app');
+
+test('create and read a note', async () => {
+ const server = createApp();
+ await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
+ try {
+ const port = server.address().port;
+ const created = await fetch(`http://127.0.0.1:${port}/notes`, {
+ method: 'POST', headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ title: 'first', body: 'hello' }) });
+ assert.equal(created.status, 201);
+ const { id } = await created.json();
+ const read = await fetch(`http://127.0.0.1:${port}/notes/${id}`);
+ assert.equal((await read.json()).title, 'first');
+ } finally {
+ server.close();
+ }
+});
diff --git a/docker/context-profiles/complex-eval/cases3/production-ready/meta.json b/docker/context-profiles/complex-eval/cases3/production-ready/meta.json
new file mode 100644
index 000000000..21aae2a12
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases3/production-ready/meta.json
@@ -0,0 +1,11 @@
+{
+ "id": "production-ready",
+ "category": "vague-hardening",
+ "manualIds": ["skill:backend-patterns"],
+ "checkTimeoutMs": 60000,
+ "selection": {
+ "id": "complex-production-ready",
+ "category": "complex-vague-hardening",
+ "expectedIds": ["skill:backend-patterns"]
+ }
+}
diff --git a/docker/context-profiles/complex-eval/cases3/production-ready/query.md b/docker/context-profiles/complex-eval/cases3/production-ready/query.md
new file mode 100644
index 000000000..341755315
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases3/production-ready/query.md
@@ -0,0 +1 @@
+This goes to production Monday morning. Get it ready. The bar we hold production services to is in docs/production-bar.md — meet all of it, keep the documented API working, and leave the repo in a state you'd be comfortable being on-call for.
diff --git a/docker/context-profiles/complex-eval/cases4/chained-tickets/files/API.md b/docker/context-profiles/complex-eval/cases4/chained-tickets/files/API.md
new file mode 100644
index 000000000..b916ba80a
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases4/chained-tickets/files/API.md
@@ -0,0 +1,13 @@
+# Shortlink API
+
+- `POST /links` — body `{ "url": string, "ttlSeconds"?: number }`.
+ - `201` → `{ "code", "shortUrl", "expiresAt" }`. `code` is 6–10
+ alphanumeric characters; `shortUrl` is `/`; `expiresAt` is an ISO
+ timestamp. Default TTL is 7 days; `ttlSeconds` must be an integer between
+ 1 and 2592000 (30 days).
+ - Missing/invalid `url` or out-of-range `ttlSeconds` → `400`.
+- `GET /` — `302` with `Location` set to the original URL.
+ Unknown code → `404`. Expired link → `410`.
+- `DELETE /links/` — `204`. Unknown code → `404`.
+
+All error responses follow the envelope in `CONTRIBUTING.md`.
diff --git a/docker/context-profiles/complex-eval/cases4/chained-tickets/files/CONTRIBUTING.md b/docker/context-profiles/complex-eval/cases4/chained-tickets/files/CONTRIBUTING.md
new file mode 100644
index 000000000..7c45e4af2
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases4/chained-tickets/files/CONTRIBUTING.md
@@ -0,0 +1,13 @@
+# Engineering conventions
+
+These conventions apply to every ticket, every route, every change:
+
+- **Errors**: every error response is JSON with the envelope
+ `{ "error": { "code": "", "message": "" } }`
+ and the matching HTTP status. No HTML error pages, no stack traces.
+- **Layering**: HTTP handling in `src/routes.js`, business logic in
+ `src/service.js`, storage in `src/store.js`. `src/app.js` wires them.
+- **Runtime config** comes from environment variables, read at startup.
+- **Every ticket**: add tests under `test/`, add a `CHANGELOG.md` entry
+ describing what shipped, and keep `README.md` accurate.
+- No external dependencies.
diff --git a/docker/context-profiles/complex-eval/cases4/chained-tickets/files/README.md b/docker/context-profiles/complex-eval/cases4/chained-tickets/files/README.md
new file mode 100644
index 000000000..90f4bae61
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases4/chained-tickets/files/README.md
@@ -0,0 +1,9 @@
+# shortlink
+
+Internal link shortener service. Node.js standard library only, CommonJS.
+
+- `API.md` — the HTTP contract.
+- `CONTRIBUTING.md` — engineering conventions. Every ticket follows them.
+- `src/app.js` exports `createApp()` returning an `http.Server` that is not yet
+ listening; `node src/index.js ` starts the service.
+- Run the tests with `npm test`.
diff --git a/docker/context-profiles/complex-eval/cases4/chained-tickets/files/package.json b/docker/context-profiles/complex-eval/cases4/chained-tickets/files/package.json
new file mode 100644
index 000000000..12bbcaf08
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases4/chained-tickets/files/package.json
@@ -0,0 +1,6 @@
+{
+ "name": "shortlink",
+ "private": true,
+ "type": "commonjs",
+ "scripts": { "test": "node --test test/*.test.js" }
+}
diff --git a/docker/context-profiles/complex-eval/cases4/chained-tickets/meta.json b/docker/context-profiles/complex-eval/cases4/chained-tickets/meta.json
new file mode 100644
index 000000000..30eb9fb05
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases4/chained-tickets/meta.json
@@ -0,0 +1,17 @@
+{
+ "id": "chained-tickets",
+ "category": "long-horizon-chain",
+ "manualIds": [],
+ "checkTimeoutMs": 60000,
+ "steps": [
+ { "manualIds": ["skill:backend-patterns"] },
+ { "manualIds": ["skill:backend-patterns"] },
+ { "manualIds": ["skill:security-review"] },
+ { "manualIds": ["skill:api-design"] }
+ ],
+ "selection": {
+ "id": "complex-chained-tickets",
+ "category": "complex-long-horizon",
+ "expectedIds": ["skill:backend-patterns"]
+ }
+}
diff --git a/docker/context-profiles/complex-eval/cases4/chained-tickets/steps/01-core/check.cjs b/docker/context-profiles/complex-eval/cases4/chained-tickets/steps/01-core/check.cjs
new file mode 100644
index 000000000..cda5c3028
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases4/chained-tickets/steps/01-core/check.cjs
@@ -0,0 +1,95 @@
+'use strict';
+// Step 1 grader: core API contract + conventions (envelope, layering, changelog, tests).
+const fs = require('node:fs');
+const path = require('node:path');
+
+const checks = [];
+const record = (name, ok) => checks.push({ name, ok: Boolean(ok) });
+let finished = false;
+function finish() {
+ if (finished) return;
+ finished = true;
+ for (let i = checks.length; i < 10; i++) record(`unreached-${i + 1}`, false);
+ const ok = checks.filter(c => c.ok).length;
+ for (const c of checks) process.stdout.write(`${c.ok ? 'ok' : 'not ok'} - ${c.name}\n`);
+ process.stdout.write(`ECC_EVAL_SCORE ${JSON.stringify({ score: ok / 10, passed: ok, total: 10 })}\n`);
+ process.exit(0);
+}
+// A crashing agent server must not kill the grader: score what completed.
+process.on('uncaughtException', finish);
+process.on('unhandledRejection', finish);
+const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
+const root = process.cwd();
+const hasEnvelope = body => body && body.error && typeof body.error.code === 'string'
+ && /^[A-Z][A-Z0-9_]+$/.test(body.error.code) && typeof body.error.message === 'string';
+
+(async () => {
+ let createApp;
+ try { ({ createApp } = require(path.join(root, 'src', 'app.js'))); } catch { /* scored below */ }
+ if (typeof createApp === 'function') {
+ try {
+ const app = createApp();
+ await new Promise(resolve => app.listen(0, '127.0.0.1', resolve));
+ const port = app.address().port;
+ const post = (body) => fetch(`http://127.0.0.1:${port}/links`, {
+ method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });
+ const get = (p) => fetch(`http://127.0.0.1:${port}${p}`, { redirect: 'manual' });
+
+ const created = await post({ url: 'https://example.com/landing' });
+ const createdBody = await created.json().catch(() => null);
+ record('create-happy-201', created.status === 201 && createdBody
+ && /^[A-Za-z0-9]{6,10}$/.test(createdBody.code || '') && typeof createdBody.shortUrl === 'string'
+ && typeof createdBody.expiresAt === 'string' && !Number.isNaN(Date.parse(createdBody.expiresAt)));
+
+ let code = createdBody && createdBody.code;
+ if (code) {
+ const redirect = await get(`/${code}`);
+ record('redirect-302-location', redirect.status === 302
+ && redirect.headers.get('location') === 'https://example.com/landing');
+ } else record('redirect-302-location', false);
+
+ const unknown = await get('/nope00');
+ record('unknown-code-404-envelope', unknown.status === 404 && hasEnvelope(await unknown.json().catch(() => null)));
+
+ const badUrl = await post({ url: 'notaurl' });
+ record('invalid-url-400-envelope', badUrl.status === 400 && hasEnvelope(await badUrl.json().catch(() => null)));
+ const noBody = await post({});
+ record('missing-url-400-envelope', noBody.status === 400 && hasEnvelope(await noBody.json().catch(() => null)));
+ const badTtl = await post({ url: 'https://example.com', ttlSeconds: 99999999 });
+ record('ttl-bounds-400-envelope', badTtl.status === 400 && hasEnvelope(await badTtl.json().catch(() => null)));
+
+ const expiring = await post({ url: 'https://example.com/gone', ttlSeconds: 1 });
+ const expiringBody = await expiring.json().catch(() => null);
+ if (expiringBody && expiringBody.code) {
+ await sleep(1300);
+ const gone = await get(`/${expiringBody.code}`);
+ record('expired-link-410-envelope', gone.status === 410 && hasEnvelope(await gone.json().catch(() => null)));
+ } else record('expired-link-410-envelope', false);
+
+ if (code) {
+ const del = await fetch(`http://127.0.0.1:${port}/links/${code}`, { method: 'DELETE' });
+ const after = await get(`/${code}`);
+ record('delete-flow-204-then-404', del.status === 204 && after.status === 404);
+ } else record('delete-flow-204-then-404', false);
+ app.close();
+ } catch { /* remaining checks unscored */ }
+ } else {
+ for (const name of ['create-happy-201', 'redirect-302-location', 'unknown-code-404-envelope',
+ 'invalid-url-400-envelope', 'missing-url-400-envelope', 'ttl-bounds-400-envelope',
+ 'expired-link-410-envelope', 'delete-flow-204-then-404']) record(name, false);
+ }
+
+ // Conventions.
+ let changelog = '';
+ try { changelog = fs.readFileSync(path.join(root, 'CHANGELOG.md'), 'utf8'); } catch { /* missing */ }
+ let tests = '';
+ try {
+ for (const f of fs.readdirSync(path.join(root, 'test'))) tests += fs.readFileSync(path.join(root, 'test', f), 'utf8');
+ } catch { /* missing */ }
+ const testCount = (tests.match(/\btest\(/g) || []).length;
+ record('changelog-and-tests', changelog.length > 20 && testCount >= 3);
+ record('layering-files', ['routes.js', 'service.js', 'store.js']
+ .every(f => fs.existsSync(path.join(root, 'src', f))));
+
+ finish();
+})();
diff --git a/docker/context-profiles/complex-eval/cases4/chained-tickets/steps/01-core/query.md b/docker/context-profiles/complex-eval/cases4/chained-tickets/steps/01-core/query.md
new file mode 100644
index 000000000..2c00246ec
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases4/chained-tickets/steps/01-core/query.md
@@ -0,0 +1 @@
+Implement the link shortener described in API.md. Follow CONTRIBUTING.md — every convention applies.
diff --git a/docker/context-profiles/complex-eval/cases4/chained-tickets/steps/02-persistence/check.cjs b/docker/context-profiles/complex-eval/cases4/chained-tickets/steps/02-persistence/check.cjs
new file mode 100644
index 000000000..ce42427f4
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases4/chained-tickets/steps/02-persistence/check.cjs
@@ -0,0 +1,106 @@
+'use strict';
+// Step 2 grader: persistence across a simulated restart (fresh module state,
+// same DATA_FILE), expiry state survives, fresh/corrupt-start tolerance, conventions.
+const fs = require('node:fs');
+const path = require('node:path');
+
+const checks = [];
+const record = (name, ok) => checks.push({ name, ok: Boolean(ok) });
+let finished = false;
+function finish() {
+ if (finished) return;
+ finished = true;
+ for (let i = checks.length; i < 7; i++) record(`unreached-${i + 1}`, false);
+ const ok = checks.filter(c => c.ok).length;
+ for (const c of checks) process.stdout.write(`${c.ok ? 'ok' : 'not ok'} - ${c.name}\n`);
+ process.stdout.write(`ECC_EVAL_SCORE ${JSON.stringify({ score: ok / 7, passed: ok, total: 7 })}\n`);
+ process.exit(0);
+}
+// A crashing agent server must not kill the grader: score what completed.
+process.on('uncaughtException', finish);
+process.on('unhandledRejection', finish);
+const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
+const root = process.cwd();
+const DATA_FILE = path.join(root, '.ecc-data', 'links.json');
+const hasEnvelope = body => body && body.error && typeof body.error.code === 'string'
+ && /^[A-Z][A-Z0-9_]+$/.test(body.error.code) && typeof body.error.message === 'string';
+
+function purgeApp() {
+ for (const key of Object.keys(require.cache)) {
+ if (key.startsWith(path.join(root, 'src') + path.sep)) delete require.cache[key];
+ }
+}
+
+async function start() {
+ purgeApp();
+ const { createApp } = require(path.join(root, 'src', 'app.js'));
+ const app = createApp();
+ await new Promise((resolve, reject) => { app.once('error', reject); app.listen(0, '127.0.0.1', resolve); });
+ return app;
+}
+
+(async () => {
+ process.env.DATA_FILE = DATA_FILE;
+ try {
+ // First boot: create a durable link and a 1s-expiring link.
+ let app = await start();
+ let port = app.address().port;
+ const post = body => fetch(`http://127.0.0.1:${port}/links`, {
+ method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });
+ const durable = await (await post({ url: 'https://example.com/durable' })).json().catch(() => null);
+ const short = await (await post({ url: 'https://example.com/short', ttlSeconds: 1 })).json().catch(() => null);
+ await new Promise(resolve => app.close(resolve));
+
+ // Restart: fresh modules, same DATA_FILE.
+ app = await start();
+ port = app.address().port;
+ const get = p => fetch(`http://127.0.0.1:${port}${p}`, { redirect: 'manual' });
+
+ const after = durable && durable.code ? await get(`/${durable.code}`) : null;
+ record('link-survives-restart', after && after.status === 302
+ && after.headers.get('location') === 'https://example.com/durable');
+
+ await sleep(1300);
+ const expiredAfter = short && short.code ? await get(`/${short.code}`) : null;
+ record('expiry-survives-restart', expiredAfter && expiredAfter.status === 410);
+ await new Promise(resolve => app.close(resolve));
+
+ // Data file is real JSON on disk.
+ let dataOk = false;
+ try { JSON.parse(fs.readFileSync(DATA_FILE, 'utf8')); dataOk = true; } catch { /* missing/invalid */ }
+ record('data-file-is-json', dataOk);
+
+ // Fresh start with no data file present.
+ fs.rmSync(DATA_FILE, { force: true });
+ app = await start();
+ port = app.address().port;
+ const fresh = await fetch(`http://127.0.0.1:${port}/links`, {
+ method: 'POST', headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ url: 'https://example.com/fresh' }) });
+ record('fresh-start-without-data-file', fresh.status === 201);
+ await new Promise(resolve => app.close(resolve));
+
+ // Corrupt data file must not kill the service.
+ fs.mkdirSync(path.dirname(DATA_FILE), { recursive: true });
+ fs.writeFileSync(DATA_FILE, 'garbage{{{');
+ app = await start();
+ port = app.address().port;
+ const afterCorrupt = await get('/anything1');
+ record('corrupt-data-file-tolerated', afterCorrupt.status === 404
+ && hasEnvelope(await afterCorrupt.json().catch(() => null)));
+ await new Promise(resolve => app.close(resolve));
+ fs.rmSync(DATA_FILE, { force: true });
+ } catch { /* remaining checks unscored */ }
+
+ let changelog = '';
+ try { changelog = fs.readFileSync(path.join(root, 'CHANGELOG.md'), 'utf8'); } catch { /* missing */ }
+ let tests = '';
+ try {
+ for (const f of fs.readdirSync(path.join(root, 'test'))) tests += fs.readFileSync(path.join(root, 'test', f), 'utf8');
+ } catch { /* missing */ }
+ const changelogEntries = (changelog.match(/^[-*#]/gm) || []).length;
+ record('changelog-grown', changelogEntries >= 2 && /persist|restart|data/i.test(changelog));
+ record('tests-grown', (tests.match(/\btest\(/g) || []).length >= 6);
+
+ finish();
+})();
diff --git a/docker/context-profiles/complex-eval/cases4/chained-tickets/steps/02-persistence/query.md b/docker/context-profiles/complex-eval/cases4/chained-tickets/steps/02-persistence/query.md
new file mode 100644
index 000000000..544b2f51e
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases4/chained-tickets/steps/02-persistence/query.md
@@ -0,0 +1 @@
+Links need to survive a service restart. Persist them to the JSON file named by the DATA_FILE environment variable (read at startup). Take care of it.
diff --git a/docker/context-profiles/complex-eval/cases4/chained-tickets/steps/03-abuse/check.cjs b/docker/context-profiles/complex-eval/cases4/chained-tickets/steps/03-abuse/check.cjs
new file mode 100644
index 000000000..829abd522
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases4/chained-tickets/steps/03-abuse/check.cjs
@@ -0,0 +1,83 @@
+'use strict';
+// Step 3 grader: abuse handling — URL validation, size limits, rate limiting —
+// plus conventions. Hammer probe runs last so earlier probes stay unthrottled.
+const fs = require('node:fs');
+const path = require('node:path');
+
+const checks = [];
+const record = (name, ok) => checks.push({ name, ok: Boolean(ok) });
+let finished = false;
+function finish() {
+ if (finished) return;
+ finished = true;
+ for (let i = checks.length; i < 8; i++) record(`unreached-${i + 1}`, false);
+ const ok = checks.filter(c => c.ok).length;
+ for (const c of checks) process.stdout.write(`${c.ok ? 'ok' : 'not ok'} - ${c.name}\n`);
+ process.stdout.write(`ECC_EVAL_SCORE ${JSON.stringify({ score: ok / 8, passed: ok, total: 8 })}\n`);
+ process.exit(0);
+}
+// A crashing agent server must not kill the grader: score what completed.
+process.on('uncaughtException', finish);
+process.on('unhandledRejection', finish);
+const root = process.cwd();
+const DATA_FILE = path.join(root, '.ecc-data', 'links-step3.json');
+const hasEnvelope = body => body && body.error && typeof body.error.code === 'string'
+ && /^[A-Z][A-Z0-9_]+$/.test(body.error.code) && typeof body.error.message === 'string';
+
+function purgeApp() {
+ for (const key of Object.keys(require.cache)) {
+ if (key.startsWith(path.join(root, 'src') + path.sep)) delete require.cache[key];
+ }
+}
+
+(async () => {
+ process.env.DATA_FILE = DATA_FILE;
+ try {
+ purgeApp();
+ const { createApp } = require(path.join(root, 'src', 'app.js'));
+ const app = createApp();
+ await new Promise(resolve => app.listen(0, '127.0.0.1', resolve));
+ const port = app.address().port;
+ const post = body => fetch(`http://127.0.0.1:${port}/links`, {
+ method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });
+
+ const okCreate = await post({ url: 'https://example.com/normal' });
+ record('normal-create-still-201', okCreate.status === 201);
+
+ const js = await post({ url: 'javascript:alert(1)' });
+ record('javascript-scheme-400-envelope', js.status === 400 && hasEnvelope(await js.json().catch(() => null)));
+ const ftp = await post({ url: 'ftp://files.example.com/x' });
+ record('non-http-scheme-400-envelope', ftp.status === 400 && hasEnvelope(await ftp.json().catch(() => null)));
+ const huge = await post({ url: `https://example.com/${'a'.repeat(10000)}` });
+ const hugeBody = await huge.json().catch(() => null);
+ record('oversize-url-4xx-envelope', huge.status >= 400 && huge.status < 500 && hasEnvelope(hugeBody));
+
+ // Hammer: 60 rapid creates must trip a 429 with the envelope.
+ const responses = await Promise.all(Array.from({ length: 60 }, (_, i) =>
+ post({ url: `https://example.com/flood-${i}` })));
+ const limited = [];
+ for (const r of responses) if (r.status === 429) limited.push(await r.json().catch(() => null));
+ record('rate-limit-429-envelope', limited.length > 0 && limited.every(hasEnvelope));
+ app.close();
+ } catch { /* remaining checks unscored */ }
+
+ let sources = '';
+ try {
+ for (const f of fs.readdirSync(path.join(root, 'src'))) {
+ if (f.endsWith('.js')) sources += fs.readFileSync(path.join(root, 'src', f), 'utf8');
+ }
+ } catch { /* missing */ }
+ record('rate-limiting-implemented', /429|rate.?limit/i.test(sources));
+
+ let changelog = '';
+ try { changelog = fs.readFileSync(path.join(root, 'CHANGELOG.md'), 'utf8'); } catch { /* missing */ }
+ let tests = '';
+ try {
+ for (const f of fs.readdirSync(path.join(root, 'test'))) tests += fs.readFileSync(path.join(root, 'test', f), 'utf8');
+ } catch { /* missing */ }
+ const changelogEntries = (changelog.match(/^[-*#]/gm) || []).length;
+ record('changelog-grown', changelogEntries >= 3 && /abuse|rate|valid|secur/i.test(changelog));
+ record('tests-grown', (tests.match(/\btest\(/g) || []).length >= 9);
+
+ finish();
+})();
diff --git a/docker/context-profiles/complex-eval/cases4/chained-tickets/steps/03-abuse/query.md b/docker/context-profiles/complex-eval/cases4/chained-tickets/steps/03-abuse/query.md
new file mode 100644
index 000000000..799adaf89
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases4/chained-tickets/steps/03-abuse/query.md
@@ -0,0 +1 @@
+We're seeing abuse — people hammering the API and submitting junk URLs. Deal with it.
diff --git a/docker/context-profiles/complex-eval/cases4/chained-tickets/steps/04-analytics/check.cjs b/docker/context-profiles/complex-eval/cases4/chained-tickets/steps/04-analytics/check.cjs
new file mode 100644
index 000000000..ed2e69364
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases4/chained-tickets/steps/04-analytics/check.cjs
@@ -0,0 +1,88 @@
+'use strict';
+// Step 4 grader: hit analytics consistent with the existing API, conventions,
+// docs and tests. (Runs in a later process than step 3, so rate windows cleared.)
+const fs = require('node:fs');
+const path = require('node:path');
+
+const checks = [];
+const record = (name, ok) => checks.push({ name, ok: Boolean(ok) });
+let finished = false;
+function finish() {
+ if (finished) return;
+ finished = true;
+ for (let i = checks.length; i < 8; i++) record(`unreached-${i + 1}`, false);
+ const ok = checks.filter(c => c.ok).length;
+ for (const c of checks) process.stdout.write(`${c.ok ? 'ok' : 'not ok'} - ${c.name}\n`);
+ process.stdout.write(`ECC_EVAL_SCORE ${JSON.stringify({ score: ok / 8, passed: ok, total: 8 })}\n`);
+ process.exit(0);
+}
+// A crashing agent server must not kill the grader: score what completed.
+process.on('uncaughtException', finish);
+process.on('unhandledRejection', finish);
+const root = process.cwd();
+const DATA_FILE = path.join(root, '.ecc-data', 'links-step4.json');
+const hasEnvelope = body => body && body.error && typeof body.error.code === 'string'
+ && /^[A-Z][A-Z0-9_]+$/.test(body.error.code) && typeof body.error.message === 'string';
+
+function purgeApp() {
+ for (const key of Object.keys(require.cache)) {
+ if (key.startsWith(path.join(root, 'src') + path.sep)) delete require.cache[key];
+ }
+}
+
+(async () => {
+ process.env.DATA_FILE = DATA_FILE;
+ try {
+ purgeApp();
+ const { createApp } = require(path.join(root, 'src', 'app.js'));
+ const app = createApp();
+ await new Promise(resolve => app.listen(0, '127.0.0.1', resolve));
+ const port = app.address().port;
+
+ const created = await fetch(`http://127.0.0.1:${port}/links`, {
+ method: 'POST', headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ url: 'https://example.com/tracked' }) });
+ const body = await created.json().catch(() => null);
+ const code = body && body.code;
+ record('create-still-works', created.status === 201 && Boolean(code));
+
+ if (code) {
+ const before = await fetch(`http://127.0.0.1:${port}/links/${code}/stats`);
+ const beforeBody = await before.json().catch(() => null);
+ record('stats-zero-before-redirects', before.status === 200 && beforeBody && beforeBody.hits === 0);
+
+ for (let i = 0; i < 3; i++) {
+ await fetch(`http://127.0.0.1:${port}/${code}`, { redirect: 'manual' });
+ }
+ const stats = await fetch(`http://127.0.0.1:${port}/links/${code}/stats`);
+ const statsBody = await stats.json().catch(() => null);
+ record('stats-count-three-hits', stats.status === 200 && statsBody && statsBody.hits === 3);
+
+ const redirect = await fetch(`http://127.0.0.1:${port}/${code}`, { redirect: 'manual' });
+ record('redirect-still-302', redirect.status === 302);
+
+ const missing = await fetch(`http://127.0.0.1:${port}/links/zzzzzz/stats`);
+ record('stats-unknown-404-envelope', missing.status === 404
+ && hasEnvelope(await missing.json().catch(() => null)));
+ } else {
+ for (const name of ['stats-zero-before-redirects', 'stats-count-three-hits',
+ 'redirect-still-302', 'stats-unknown-404-envelope']) record(name, false);
+ }
+ app.close();
+ } catch { /* remaining checks unscored */ }
+
+ let readme = '';
+ try { readme = fs.readFileSync(path.join(root, 'README.md'), 'utf8'); } catch { /* missing */ }
+ record('readme-documents-stats', /\/stats|hits|analytics/i.test(readme));
+ let changelog = '';
+ try { changelog = fs.readFileSync(path.join(root, 'CHANGELOG.md'), 'utf8'); } catch { /* missing */ }
+ let tests = '';
+ try {
+ for (const f of fs.readdirSync(path.join(root, 'test'))) tests += fs.readFileSync(path.join(root, 'test', f), 'utf8');
+ } catch { /* missing */ }
+ const changelogEntries = (changelog.match(/^[-*#]/gm) || []).length;
+ record('changelog-grown', changelogEntries >= 4 && /stat|analytic|hit/i.test(changelog));
+ record('tests-grown', (tests.match(/\btest\(/g) || []).length >= 12);
+
+ finish();
+})();
diff --git a/docker/context-profiles/complex-eval/cases4/chained-tickets/steps/04-analytics/query.md b/docker/context-profiles/complex-eval/cases4/chained-tickets/steps/04-analytics/query.md
new file mode 100644
index 000000000..619549068
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases4/chained-tickets/steps/04-analytics/query.md
@@ -0,0 +1 @@
+Track redirect hits per link and expose them at GET /links/:code/stats, consistent with the existing API.
diff --git a/docker/context-profiles/complex-eval/cases4/idempotent-webhooks/check.cjs b/docker/context-profiles/complex-eval/cases4/idempotent-webhooks/check.cjs
new file mode 100644
index 000000000..7882bce07
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases4/idempotent-webhooks/check.cjs
@@ -0,0 +1,119 @@
+'use strict';
+// Hidden grader for idempotent-webhooks: exactly-once under sequential,
+// concurrent, and mixed-concurrent duplicates, plus the documented API,
+// regression coverage, and hygiene. Prints ECC_EVAL_SCORE and always exits 0.
+const fs = require('node:fs');
+const path = require('node:path');
+
+const checks = [];
+const record = (name, ok) => checks.push({ name, ok: Boolean(ok) });
+let finished = false;
+function finish() {
+ if (finished) return;
+ finished = true;
+ for (let i = checks.length; i < 12; i++) record(`unreached-${i + 1}`, false);
+ const ok = checks.filter(c => c.ok).length;
+ for (const c of checks) process.stdout.write(`${c.ok ? 'ok' : 'not ok'} - ${c.name}\n`);
+ process.stdout.write(`ECC_EVAL_SCORE ${JSON.stringify({ score: ok / 12, passed: ok, total: 12 })}\n`);
+ process.exit(0);
+}
+// A crashing agent server must not kill the grader: score what completed.
+process.on('uncaughtException', finish);
+process.on('unhandledRejection', finish);
+const root = process.cwd();
+const hasEnvelope = body => body && body.error && typeof body.error.code === 'string'
+ && /^[A-Z][A-Z0-9_]+$/.test(body.error.code) && typeof body.error.message === 'string';
+
+(async () => {
+ let createApp;
+ let store;
+ try {
+ ({ createApp } = require(path.join(root, 'src', 'app.js')));
+ ({ store } = require(path.join(root, 'src', 'store.js')));
+ } catch { /* scored below */ }
+ if (typeof createApp === 'function' && store && Array.isArray(store.paymentLog)) {
+ try {
+ const app = createApp();
+ await new Promise(resolve => app.listen(0, '127.0.0.1', resolve));
+ const port = app.address().port;
+ const send = (eventId, orderId, amountCents) => fetch(`http://127.0.0.1:${port}/webhooks/payments`, {
+ method: 'POST', headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ eventId, orderId, amountCents, type: 'payment.succeeded' }) });
+ const logsFor = orderId => store.paymentLog.filter(p => p.orderId === orderId).length;
+
+ // 1: single delivery applies once.
+ const single = await send('ev-1', 'o1', 5000);
+ const singleBody = await single.json().catch(() => null);
+ record('single-delivery-processed', single.status === 200 && singleBody
+ && singleBody.status === 'processed' && singleBody.orderId === 'o1' && logsFor('o1') === 1);
+
+ // 2: sequential retry replays without re-applying.
+ const retry = await send('ev-1', 'o1', 5000);
+ const retryBody = await retry.json().catch(() => null);
+ record('sequential-duplicate-inert', retry.status === 200 && retryBody
+ && retryBody.status === 'duplicate' && logsFor('o1') === 1);
+
+ // 3: fifty concurrent identical deliveries apply exactly once.
+ const storm = await Promise.all(Array.from({ length: 50 }, () => send('ev-2', 'o2', 12500)));
+ const stormBodies = [];
+ for (const r of storm) stormBodies.push(await r.json().catch(() => null));
+ const processedCount = stormBodies.filter(b => b && b.status === 'processed').length;
+ const duplicateCount = stormBodies.filter(b => b && b.status === 'duplicate').length;
+ record('concurrent-storm-exactly-once', storm.every(r => r.status === 200)
+ && processedCount === 1 && duplicateCount === 49 && logsFor('o2') === 1
+ && store.orders.get('o2').paymentsApplied === 1);
+
+ // 4: a different event for an already-paid order is already_paid and inert.
+ const second = await send('ev-3', 'o2', 12500);
+ const secondBody = await second.json().catch(() => null);
+ record('already-paid-order-inert', second.status === 200 && secondBody
+ && secondBody.status === 'already_paid' && logsFor('o2') === 1);
+
+ // 5-7: contract errors with envelopes.
+ const unknown = await send('ev-4', 'nope', 100);
+ record('unknown-order-404-envelope', unknown.status === 404 && hasEnvelope(await unknown.json().catch(() => null)));
+ const malformed = await fetch(`http://127.0.0.1:${port}/webhooks/payments`, {
+ method: 'POST', headers: { 'content-type': 'application/json' }, body: '{bad json' });
+ record('malformed-body-400-envelope', malformed.status === 400 && hasEnvelope(await malformed.json().catch(() => null)));
+ const mismatch = await send('ev-5', 'o3', 999999);
+ record('amount-mismatch-422-envelope', mismatch.status === 422
+ && hasEnvelope(await mismatch.json().catch(() => null)) && logsFor('o3') === 0);
+
+ // 8: mixed storm — three orders, three eventIds, ten duplicates each, all concurrent.
+ const mixed = await Promise.all(['o4', 'o5', 'o6'].flatMap(orderId =>
+ Array.from({ length: 10 }, () => send(`ev-${orderId}`, orderId, store.orders.get(orderId).amountCents))));
+ for (const r of mixed) await r.json().catch(() => null);
+ record('mixed-storm-each-order-once', ['o4', 'o5', 'o6'].every(orderId =>
+ logsFor(orderId) === 1 && store.orders.get(orderId).paymentsApplied === 1));
+
+ // 9: order inspection endpoint reflects reality.
+ const orderView = await fetch(`http://127.0.0.1:${port}/orders/o2`);
+ const orderBody = await orderView.json().catch(() => null);
+ record('order-endpoint-accurate', orderView.status === 200 && orderBody
+ && orderBody.status === 'paid' && orderBody.paymentsApplied === 1 && Boolean(orderBody.paidAt));
+
+ app.close();
+ } catch { /* remaining checks unscored */ }
+ } else {
+ for (const name of ['single-delivery-processed', 'sequential-duplicate-inert', 'concurrent-storm-exactly-once',
+ 'already-paid-order-inert', 'unknown-order-404-envelope', 'malformed-body-400-envelope',
+ 'amount-mismatch-422-envelope', 'mixed-storm-each-order-once', 'order-endpoint-accurate']) record(name, false);
+ }
+
+ // Conventions.
+ let tests = '';
+ try {
+ for (const f of fs.readdirSync(path.join(root, 'test'))) tests += fs.readFileSync(path.join(root, 'test', f), 'utf8');
+ } catch { /* missing */ }
+ record('concurrency-regression-tests', (tests.match(/\btest\(/g) || []).length >= 4
+ && /Promise\.all|concurrent|duplicate|retry/i.test(tests));
+ let changelog = '';
+ try { changelog = fs.readFileSync(path.join(root, 'CHANGELOG.md'), 'utf8'); } catch { /* missing */ }
+ record('changelog-entry', /idem|duplicat|retry|inc-104|race/i.test(changelog));
+ try {
+ const pkg = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'));
+ record('no-external-dependencies', !pkg.dependencies && !pkg.devDependencies);
+ } catch { record('no-external-dependencies', false); }
+
+ finish();
+})();
diff --git a/docker/context-profiles/complex-eval/cases4/idempotent-webhooks/files/README.md b/docker/context-profiles/complex-eval/cases4/idempotent-webhooks/files/README.md
new file mode 100644
index 000000000..512c8c059
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases4/idempotent-webhooks/files/README.md
@@ -0,0 +1,12 @@
+# webhook-receiver
+
+Receives payment webhooks. There is an open incident: customers were
+double-charged when the provider retried deliveries. See `SPEC.md` for the
+contract, including the exactly-once rules.
+
+- `src/app.js` exports `createApp()` returning an `http.Server` that is not
+ yet listening; `node src/index.js ` starts the service.
+- `src/store.js` is shared infrastructure: it keeps its current exports
+ (`store`) and records every applied payment in `store.paymentLog`.
+- No external dependencies. `npm test` runs the tests. `CHANGELOG.md` records
+ every shipped change.
diff --git a/docker/context-profiles/complex-eval/cases4/idempotent-webhooks/files/SPEC.md b/docker/context-profiles/complex-eval/cases4/idempotent-webhooks/files/SPEC.md
new file mode 100644
index 000000000..e3dee27b1
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases4/idempotent-webhooks/files/SPEC.md
@@ -0,0 +1,30 @@
+# Payment webhook contract
+
+`POST /webhooks/payments` with JSON body
+`{ "eventId": string, "orderId": string, "amountCents": number, "type": "payment.succeeded" }`.
+
+Exactly-once is the point. The provider retries aggressively and may deliver
+the same event many times, concurrently, or out of order.
+
+- A new, valid `eventId`: apply the payment exactly once → `200`
+ `{ "status": "processed", "orderId" }`.
+- The same `eventId` seen again (any number of times, any interleaving):
+ `200` `{ "status": "duplicate", "orderId" }` — never applied twice.
+- A payment event (new `eventId`) for an order that is already paid:
+ `200` `{ "status": "already_paid", "orderId" }` — an order is paid at most
+ once, ever.
+- `amountCents` not matching the order's amount: `422`, not applied.
+- Unknown `orderId`: `404`. Malformed body (bad JSON, missing/invalid
+ fields): `400`.
+- Error responses use the envelope
+ `{ "error": { "code": "", "message": "..." } }`.
+
+`GET /orders/:id` → `200` `{ "id", "status", "paidAt", "paymentsApplied" }`
+or a `404` envelope.
+
+## Incident note
+
+INC-104: concurrent duplicate deliveries double-applied payments. The naive
+receiver checked "have we seen this event?" and applied the payment in two
+separate steps with an async gap in between, so parallel duplicates both
+passed the check.
diff --git a/docker/context-profiles/complex-eval/cases4/idempotent-webhooks/files/package.json b/docker/context-profiles/complex-eval/cases4/idempotent-webhooks/files/package.json
new file mode 100644
index 000000000..11c26f720
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases4/idempotent-webhooks/files/package.json
@@ -0,0 +1,6 @@
+{
+ "name": "webhook-receiver",
+ "private": true,
+ "type": "commonjs",
+ "scripts": { "test": "node --test test/*.test.js" }
+}
diff --git a/docker/context-profiles/complex-eval/cases4/idempotent-webhooks/files/src/app.js b/docker/context-profiles/complex-eval/cases4/idempotent-webhooks/files/src/app.js
new file mode 100644
index 000000000..6ba0ba755
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases4/idempotent-webhooks/files/src/app.js
@@ -0,0 +1,54 @@
+'use strict';
+const http = require('node:http');
+const { store } = require('./store');
+
+// INC-104 receiver: checks "seen this event?" and applies the payment in two
+// steps with an async gap in between. Concurrent duplicates both pass the
+// check. Do not keep this shape.
+function createApp() {
+ return http.createServer((req, res) => {
+ const url = new URL(req.url, 'http://localhost');
+
+ if (req.method === 'POST' && url.pathname === '/webhooks/payments') {
+ let body = '';
+ req.on('data', chunk => { body += chunk; });
+ req.on('end', async () => {
+ const parsed = JSON.parse(body);
+ const { eventId, orderId } = parsed;
+ if (store.processedEvents.has(eventId)) {
+ res.writeHead(200, { 'content-type': 'application/json' });
+ res.end(JSON.stringify({ status: 'duplicate', orderId }));
+ return;
+ }
+ await new Promise(resolve => setImmediate(resolve)); // async gap
+ const order = store.orders.get(orderId);
+ order.status = 'paid';
+ order.paidAt = new Date().toISOString();
+ order.paymentsApplied++;
+ store.paymentLog.push({ eventId, orderId, amountCents: parsed.amountCents });
+ store.processedEvents.add(eventId);
+ res.writeHead(200, { 'content-type': 'application/json' });
+ res.end(JSON.stringify({ status: 'processed', orderId }));
+ });
+ return;
+ }
+
+ const match = /^\/orders\/([\w-]+)$/.exec(url.pathname);
+ if (req.method === 'GET' && match) {
+ const order = store.orders.get(match[1]);
+ if (!order) {
+ res.writeHead(404, { 'content-type': 'application/json' });
+ res.end(JSON.stringify({ error: { code: 'NOT_FOUND', message: 'no such order' } }));
+ return;
+ }
+ res.writeHead(200, { 'content-type': 'application/json' });
+ res.end(JSON.stringify(order));
+ return;
+ }
+
+ res.writeHead(404, { 'content-type': 'application/json' });
+ res.end(JSON.stringify({ error: { code: 'NOT_FOUND', message: 'not found' } }));
+ });
+}
+
+module.exports = { createApp };
diff --git a/docker/context-profiles/complex-eval/cases4/idempotent-webhooks/files/src/index.js b/docker/context-profiles/complex-eval/cases4/idempotent-webhooks/files/src/index.js
new file mode 100644
index 000000000..90ef9215f
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases4/idempotent-webhooks/files/src/index.js
@@ -0,0 +1,7 @@
+'use strict';
+const { createApp } = require('./app');
+
+const port = Number(process.argv[2] || 8080);
+createApp().listen(port, () => {
+ console.log(`webhook-receiver listening on ${port}`);
+});
diff --git a/docker/context-profiles/complex-eval/cases4/idempotent-webhooks/files/src/store.js b/docker/context-profiles/complex-eval/cases4/idempotent-webhooks/files/src/store.js
new file mode 100644
index 000000000..64a4099a4
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases4/idempotent-webhooks/files/src/store.js
@@ -0,0 +1,18 @@
+'use strict';
+
+// Shared infrastructure. Every applied payment is appended to paymentLog;
+// orders and processedEvents track receiver state. Keep the `store` export.
+const store = {
+ orders: new Map([
+ ['o1', { id: 'o1', amountCents: 5000, status: 'pending', paidAt: null, paymentsApplied: 0 }],
+ ['o2', { id: 'o2', amountCents: 12500, status: 'pending', paidAt: null, paymentsApplied: 0 }],
+ ['o3', { id: 'o3', amountCents: 800, status: 'pending', paidAt: null, paymentsApplied: 0 }],
+ ['o4', { id: 'o4', amountCents: 9999, status: 'pending', paidAt: null, paymentsApplied: 0 }],
+ ['o5', { id: 'o5', amountCents: 250, status: 'pending', paidAt: null, paymentsApplied: 0 }],
+ ['o6', { id: 'o6', amountCents: 7300, status: 'pending', paidAt: null, paymentsApplied: 0 }],
+ ]),
+ paymentLog: [],
+ processedEvents: new Set(),
+};
+
+module.exports = { store };
diff --git a/docker/context-profiles/complex-eval/cases4/idempotent-webhooks/files/test/webhooks.test.js b/docker/context-profiles/complex-eval/cases4/idempotent-webhooks/files/test/webhooks.test.js
new file mode 100644
index 000000000..cf79f83d4
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases4/idempotent-webhooks/files/test/webhooks.test.js
@@ -0,0 +1,21 @@
+'use strict';
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const { createApp } = require('../src/app');
+const { store } = require('../src/store');
+
+test('a single payment event processes', async () => {
+ const server = createApp();
+ await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
+ try {
+ const port = server.address().port;
+ const res = await fetch(`http://127.0.0.1:${port}/webhooks/payments`, {
+ method: 'POST', headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ eventId: 'ev-test-1', orderId: 'o1', amountCents: 5000, type: 'payment.succeeded' }) });
+ assert.equal(res.status, 200);
+ assert.equal((await res.json()).status, 'processed');
+ assert.equal(store.orders.get('o1').status, 'paid');
+ } finally {
+ server.close();
+ }
+});
diff --git a/docker/context-profiles/complex-eval/cases4/idempotent-webhooks/meta.json b/docker/context-profiles/complex-eval/cases4/idempotent-webhooks/meta.json
new file mode 100644
index 000000000..d5d396e74
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases4/idempotent-webhooks/meta.json
@@ -0,0 +1,11 @@
+{
+ "id": "idempotent-webhooks",
+ "category": "concurrency-trap",
+ "manualIds": ["skill:error-handling"],
+ "checkTimeoutMs": 60000,
+ "selection": {
+ "id": "complex-idempotent-webhooks",
+ "category": "complex-concurrency-trap",
+ "expectedIds": ["skill:error-handling"]
+ }
+}
diff --git a/docker/context-profiles/complex-eval/cases4/idempotent-webhooks/query.md b/docker/context-profiles/complex-eval/cases4/idempotent-webhooks/query.md
new file mode 100644
index 000000000..f2902f874
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases4/idempotent-webhooks/query.md
@@ -0,0 +1 @@
+The payments provider retries aggressively and sometimes delivers the same webhook many times concurrently. Our receiver double-charges customers when that happens — see the incident note in SPEC.md. Rework the receiver so the full contract in SPEC.md holds: duplicates must never double-apply under any interleaving, and the documented API and the store contract stay intact. `npm test` must pass, and add regression coverage for the concurrent-duplicate case so INC-104 can't come back.
diff --git a/docker/context-profiles/complex-eval/cases4/production-ready/check.cjs b/docker/context-profiles/complex-eval/cases4/production-ready/check.cjs
new file mode 100644
index 000000000..e08c1efeb
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases4/production-ready/check.cjs
@@ -0,0 +1,156 @@
+'use strict';
+// Hidden grader for production-ready: probes every dimension of the documented
+// production bar. Prints ECC_EVAL_SCORE and always exits 0.
+const fs = require('node:fs');
+const path = require('node:path');
+
+const checks = [];
+const record = (name, ok) => checks.push({ name, ok: Boolean(ok) });
+let finished = false;
+function finish() {
+ if (finished) return;
+ finished = true;
+ for (let i = checks.length; i < 16; i++) record(`unreached-${i + 1}`, false);
+ const ok = checks.filter(c => c.ok).length;
+ for (const c of checks) process.stdout.write(`${c.ok ? 'ok' : 'not ok'} - ${c.name}\n`);
+ process.stdout.write(`ECC_EVAL_SCORE ${JSON.stringify({ score: ok / 16, passed: ok, total: 16 })}\n`);
+ process.exit(0);
+}
+// A crashing agent server must not kill the grader: score what completed.
+process.on('uncaughtException', finish);
+process.on('unhandledRejection', finish);
+const root = process.cwd();
+const hasEnvelope = body => body && body.error && typeof body.error.code === 'string'
+ && /^[A-Z][A-Z0-9_]+$/.test(body.error.code) && typeof body.error.message === 'string';
+
+(async () => {
+ let createApp;
+ try { ({ createApp } = require(path.join(root, 'src', 'app.js'))); } catch { /* scored below */ }
+ if (typeof createApp === 'function') {
+ // Capture console output during the probe run to inspect request logging.
+ const logged = [];
+ const originalLog = console.log;
+ const originalError = console.error;
+ const originalStdoutWrite = process.stdout.write.bind(process.stdout);
+ const originalStderrWrite = process.stderr.write.bind(process.stderr);
+ console.log = (...args) => { logged.push(args.join(' ')); };
+ console.error = (...args) => { logged.push(args.join(' ')); };
+ // Agents may log through an injectable writer straight to the streams
+ // instead of console.*. Capture-then-pass-through: the bytes always reach
+ // the stream untouched, so the grader's own ECC_EVAL_SCORE line (emitted
+ // via process.stdout.write) can never be swallowed or corrupted.
+ const tap = write => (chunk, encoding, callback) => {
+ try { logged.push(Buffer.isBuffer(chunk) ? chunk.toString('utf8') : String(chunk)); } catch { /* capture must never break a write */ }
+ return write(chunk, encoding, callback);
+ };
+ process.stdout.write = tap(originalStdoutWrite);
+ process.stderr.write = tap(originalStderrWrite);
+ try {
+ const app = createApp();
+ await new Promise(resolve => app.listen(0, '127.0.0.1', resolve));
+ const port = app.address().port;
+ const api = (p, options) => fetch(`http://127.0.0.1:${port}${p}`, options);
+ const post = body => api('/notes', { method: 'POST', headers: { 'content-type': 'application/json' }, body });
+
+ // Documented API still works.
+ const created = await post(JSON.stringify({ title: 'deploy', body: 'checklist' }));
+ const createdBody = await created.json().catch(() => null);
+ record('api-roundtrip-preserved', created.status === 201 && createdBody && createdBody.id
+ && (await (await api(`/notes/${createdBody.id}`)).json().catch(() => ({}))).title === 'deploy'
+ && Array.isArray((await (await api('/notes')).json().catch(() => ({}))).notes));
+
+ // Validation and envelope discipline.
+ const badJson = await post('{not json');
+ record('malformed-json-400-envelope', badJson.status === 400 && hasEnvelope(await badJson.json().catch(() => null)));
+ const missing = await post(JSON.stringify({ body: 'no title' }));
+ record('missing-field-400-envelope', missing.status === 400 && hasEnvelope(await missing.json().catch(() => null)));
+ const wrongType = await post(JSON.stringify({ title: 42, body: 'x' }));
+ record('wrong-type-400-envelope', wrongType.status === 400 && hasEnvelope(await wrongType.json().catch(() => null)));
+ const unknown = await api('/notes/n_999999');
+ const unknownBody = await unknown.text();
+ let unknownParsed = null;
+ try { unknownParsed = JSON.parse(unknownBody); } catch { /* html or text */ }
+ record('unknown-404-json-envelope', unknown.status === 404 && hasEnvelope(unknownParsed));
+
+ // Body limit.
+ const big = await post(JSON.stringify({ title: 'big', body: 'x'.repeat(100 * 1024) }));
+ record('oversize-body-413-envelope', big.status === 413 && hasEnvelope(await big.json().catch(() => null)));
+
+ // Health endpoint.
+ const health = await api('/health');
+ const healthBody = await health.json().catch(() => null);
+ record('health-endpoint', health.status === 200 && healthBody && healthBody.status === 'ok');
+
+ // Security header on a normal response.
+ const headers = await api('/notes');
+ record('nosniff-header', headers.headers.get('x-content-type-options') === 'nosniff');
+
+ // Error responses carry JSON content type.
+ record('errors-are-json', /application\/json/.test(unknown.headers.get('content-type') || ''));
+
+ app.close();
+ } catch { /* remaining checks unscored */ } finally {
+ console.log = originalLog;
+ console.error = originalError;
+ process.stdout.write = originalStdoutWrite;
+ process.stderr.write = originalStderrWrite;
+ }
+
+ // Structured request logging: at least one JSON line with method/path/status-ish fields.
+ const structured = logged.flatMap(chunk => String(chunk).split('\n')).some(line => {
+ try {
+ const parsed = JSON.parse(line);
+ return parsed && typeof parsed === 'object'
+ && /method/i.test(Object.keys(parsed).join(' '))
+ && /path|url/i.test(Object.keys(parsed).join(' '))
+ && /status/i.test(Object.keys(parsed).join(' '));
+ } catch { return false; }
+ });
+ record('structured-request-logs', structured);
+ } else {
+ for (const name of ['api-roundtrip-preserved', 'malformed-json-400-envelope', 'missing-field-400-envelope',
+ 'wrong-type-400-envelope', 'unknown-404-json-envelope', 'oversize-body-413-envelope', 'health-endpoint',
+ 'nosniff-header', 'errors-are-json', 'structured-request-logs']) record(name, false);
+ }
+
+ // Static dimensions.
+ let sources = '';
+ const sourceFiles = [];
+ const walk = directory => {
+ for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
+ const item = path.join(directory, entry.name);
+ if (entry.isDirectory()) walk(item);
+ else if (entry.name.endsWith('.js')) {
+ const content = fs.readFileSync(item, 'utf8');
+ sourceFiles.push(content);
+ sources += content;
+ }
+ }
+ };
+ try { walk(path.join(root, 'src')); } catch { /* none */ }
+ record('sigterm-graceful-shutdown', /SIGTERM/.test(sources));
+ // Literal process.env.PORT access, or an injectable-config indirection: a
+ // 'PORT' string literal in a file that also reads process.env (for example a
+ // loadConfig(env = process.env) + readInt(env, 'PORT', default) module).
+ record('env-config-port', sourceFiles.some(content => /process\.env\.[A-Z_]*PORT/.test(content)
+ || (/(['"`])PORT\1/.test(content) && /process\.env/.test(content))));
+
+ let tests = '';
+ try {
+ for (const f of fs.readdirSync(path.join(root, 'test'))) tests += fs.readFileSync(path.join(root, 'test', f), 'utf8');
+ } catch { /* missing */ }
+ const testCount = (tests.match(/\btest\(/g) || []).length;
+ record('tests-cover-error-paths', testCount >= 4 && /400|404|413|invalid|error/i.test(tests));
+
+ let changelog = '';
+ try { changelog = fs.readFileSync(path.join(root, 'CHANGELOG.md'), 'utf8'); } catch { /* missing */ }
+ record('changelog-entry', changelog.length > 20 && /product|harden|valid|health|log/i.test(changelog));
+
+ record('no-leftover-todos', !/TODO|FIXME/.test(sources));
+ try {
+ const pkg = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'));
+ record('no-external-dependencies', !pkg.dependencies && !pkg.devDependencies);
+ } catch { record('no-external-dependencies', false); }
+
+ finish();
+})();
diff --git a/docker/context-profiles/complex-eval/cases4/production-ready/files/README.md b/docker/context-profiles/complex-eval/cases4/production-ready/files/README.md
new file mode 100644
index 000000000..e387bff31
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases4/production-ready/files/README.md
@@ -0,0 +1,19 @@
+# notes-service
+
+Tiny notes API. Hobby prototype state: it works on the happy path and that's
+about all that can be said for it.
+
+## API
+
+- `POST /notes` — body `{ "title": string, "body": string }` → `201` with
+ `{ "id", "title", "body" }`.
+- `GET /notes/:id` — `200` with the note, or `404`.
+- `GET /notes` — `200` with `{ "notes": [...] }`.
+
+`src/app.js` exports `createApp()` returning an `http.Server` that is not yet
+listening; `node src/index.js` starts the service. `npm test` runs the tests.
+
+## Operations
+
+`docs/production-bar.md` lists what every production service here must meet.
+`CHANGELOG.md` records every shipped change.
diff --git a/docker/context-profiles/complex-eval/cases4/production-ready/files/docs/production-bar.md b/docker/context-profiles/complex-eval/cases4/production-ready/files/docs/production-bar.md
new file mode 100644
index 000000000..af3df1c4c
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases4/production-ready/files/docs/production-bar.md
@@ -0,0 +1,21 @@
+# The production bar
+
+Every production service here meets all of the following, all the time:
+
+- **Validation**: malformed JSON, missing fields, and wrong types are rejected
+ with `400` and a structured JSON error body
+ `{ "error": { "code": "", "message": "..." } }`. Unknown
+ resources are `404` in the same envelope. No stack traces, no HTML errors,
+ no hanging connections.
+- **Body limits**: request bodies over 64 KB are rejected with `413`, same
+ envelope.
+- **Health**: `GET /health` returns `200` with `{ "status": "ok" }`.
+- **Logging**: one structured JSON log line per request with at least
+ `method`, `path`, and `status` fields.
+- **Configuration**: runtime configuration (port, limits) comes from
+ environment variables, read at startup. Nothing secret is hardcoded.
+- **Shutdown**: the service closes cleanly on `SIGTERM` (stops accepting,
+ drains, exits).
+- **Headers**: responses carry `X-Content-Type-Options: nosniff`.
+- **Tests**: the suite covers error paths, not just the happy path.
+- **Changelog**: every shipped change has a `CHANGELOG.md` entry.
diff --git a/docker/context-profiles/complex-eval/cases4/production-ready/files/package.json b/docker/context-profiles/complex-eval/cases4/production-ready/files/package.json
new file mode 100644
index 000000000..7cef6f8c0
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases4/production-ready/files/package.json
@@ -0,0 +1,6 @@
+{
+ "name": "notes-service",
+ "private": true,
+ "type": "commonjs",
+ "scripts": { "test": "node --test test/*.test.js" }
+}
diff --git a/docker/context-profiles/complex-eval/cases4/production-ready/files/src/app.js b/docker/context-profiles/complex-eval/cases4/production-ready/files/src/app.js
new file mode 100644
index 000000000..db7fe2695
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases4/production-ready/files/src/app.js
@@ -0,0 +1,50 @@
+'use strict';
+const http = require('node:http');
+
+// Prototype state: happy path only.
+const notes = new Map();
+let nextId = 1;
+
+function createApp() {
+ return http.createServer((req, res) => {
+ console.log('got a request');
+ const url = new URL(req.url, 'http://localhost');
+
+ if (req.method === 'POST' && url.pathname === '/notes') {
+ let body = '';
+ req.on('data', chunk => { body += chunk; });
+ req.on('end', () => {
+ const parsed = JSON.parse(body);
+ const id = `n_${nextId++}`;
+ notes.set(id, { id, title: parsed.title, body: parsed.body });
+ res.writeHead(201, { 'content-type': 'application/json' });
+ res.end(JSON.stringify(notes.get(id)));
+ });
+ return;
+ }
+
+ const match = /^\/notes\/([\w-]+)$/.exec(url.pathname);
+ if (req.method === 'GET' && match) {
+ const note = notes.get(match[1]);
+ if (!note) {
+ res.writeHead(404);
+ res.end('not found');
+ return;
+ }
+ res.writeHead(200, { 'content-type': 'application/json' });
+ res.end(JSON.stringify(note));
+ return;
+ }
+
+ if (req.method === 'GET' && url.pathname === '/notes') {
+ res.writeHead(200, { 'content-type': 'application/json' });
+ res.end(JSON.stringify({ notes: [...notes.values()] }));
+ return;
+ }
+
+ res.writeHead(404);
+ res.end('not found');
+ });
+}
+
+module.exports = { createApp };
diff --git a/docker/context-profiles/complex-eval/cases4/production-ready/files/src/index.js b/docker/context-profiles/complex-eval/cases4/production-ready/files/src/index.js
new file mode 100644
index 000000000..a71330e92
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases4/production-ready/files/src/index.js
@@ -0,0 +1,6 @@
+'use strict';
+const { createApp } = require('./app');
+
+createApp().listen(8080, () => {
+ console.log('notes listening on 8080');
+});
diff --git a/docker/context-profiles/complex-eval/cases4/production-ready/files/test/notes.test.js b/docker/context-profiles/complex-eval/cases4/production-ready/files/test/notes.test.js
new file mode 100644
index 000000000..51babd8fb
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases4/production-ready/files/test/notes.test.js
@@ -0,0 +1,21 @@
+'use strict';
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const { createApp } = require('../src/app');
+
+test('create and read a note', async () => {
+ const server = createApp();
+ await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
+ try {
+ const port = server.address().port;
+ const created = await fetch(`http://127.0.0.1:${port}/notes`, {
+ method: 'POST', headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ title: 'first', body: 'hello' }) });
+ assert.equal(created.status, 201);
+ const { id } = await created.json();
+ const read = await fetch(`http://127.0.0.1:${port}/notes/${id}`);
+ assert.equal((await read.json()).title, 'first');
+ } finally {
+ server.close();
+ }
+});
diff --git a/docker/context-profiles/complex-eval/cases4/production-ready/meta.json b/docker/context-profiles/complex-eval/cases4/production-ready/meta.json
new file mode 100644
index 000000000..21aae2a12
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases4/production-ready/meta.json
@@ -0,0 +1,11 @@
+{
+ "id": "production-ready",
+ "category": "vague-hardening",
+ "manualIds": ["skill:backend-patterns"],
+ "checkTimeoutMs": 60000,
+ "selection": {
+ "id": "complex-production-ready",
+ "category": "complex-vague-hardening",
+ "expectedIds": ["skill:backend-patterns"]
+ }
+}
diff --git a/docker/context-profiles/complex-eval/cases4/production-ready/query.md b/docker/context-profiles/complex-eval/cases4/production-ready/query.md
new file mode 100644
index 000000000..341755315
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases4/production-ready/query.md
@@ -0,0 +1 @@
+This goes to production Monday morning. Get it ready. The bar we hold production services to is in docs/production-bar.md — meet all of it, keep the documented API working, and leave the repo in a state you'd be comfortable being on-call for.
diff --git a/docker/context-profiles/complex-eval/cases4/recurring-incident/files/README.md b/docker/context-profiles/complex-eval/cases4/recurring-incident/files/README.md
new file mode 100644
index 000000000..9c7e5925a
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases4/recurring-incident/files/README.md
@@ -0,0 +1,29 @@
+# payments-lite
+
+A small dependency-free payments service core: refunds to customers and payouts
+to vendors, executed against a fake gateway that records every call in an
+append-only ledger.
+
+## Layout
+
+- `src/charge.js` — the gateway client. `charge()`, `refund()`, and `payout()`
+ simulate network latency and append one JSON line per call to the ledger at
+ `LEDGER_FILE` (default `.data/ledger.jsonl`). `readLedger()` parses it.
+- `src/store.js` — a tiny JSON-file store at `STORE_FILE` (default
+ `.data/store.json`): `get`, `has`, `set`. Reads and writes are synchronous.
+- `src/refunds.js` — `processRefund(req)` for customer refunds.
+- `src/payouts.js` — `processPayout(req)` for vendor payouts.
+
+## API contract
+
+`processRefund({ orderId, amount, idempotencyKey? })` and
+`processPayout({ vendorId, amount, idempotencyKey? })` each return the gateway
+receipt (`{ id, type, amount, ... }`). When the caller supplies an
+`idempotencyKey`, a repeated call with the same key must not hit the gateway
+again; it returns the stored receipt with `duplicate: true`. Keep these
+signatures stable — the dashboard and the finance batch job call them directly.
+
+## Working here
+
+- No external dependencies. `npm test` runs the tests.
+- Incident notes live in `docs/incidents.md`; add an entry when you work one.
diff --git a/docker/context-profiles/complex-eval/cases4/recurring-incident/files/docs/incidents.md b/docker/context-profiles/complex-eval/cases4/recurring-incident/files/docs/incidents.md
new file mode 100644
index 000000000..cde645464
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases4/recurring-incident/files/docs/incidents.md
@@ -0,0 +1,17 @@
+# Incident notes
+
+## INC-201 — duplicate refunds (2026-06-14)
+
+Customers saw two refunds for one order. Traced to the storefront retrying the
+refund call after a gateway timeout. Asked the storefront team to retry less
+aggressively. Closed.
+
+## INC-214 — duplicate refunds, again (2026-07-29)
+
+Same shape as INC-201: a retried refund call landed twice. Reminded the
+storefront team about backoff. Closed.
+
+## INC-227 — duplicate refunds, third time (2026-09-03)
+
+Same shape as INC-201 and INC-214. Third time this quarter. Support is
+escalating refund-credit requests faster than we can explain them.
diff --git a/docker/context-profiles/complex-eval/cases4/recurring-incident/files/package.json b/docker/context-profiles/complex-eval/cases4/recurring-incident/files/package.json
new file mode 100644
index 000000000..c7ce403d0
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases4/recurring-incident/files/package.json
@@ -0,0 +1,6 @@
+{
+ "name": "payments-lite",
+ "private": true,
+ "type": "module",
+ "scripts": { "test": "node --test test/*.test.js" }
+}
diff --git a/docker/context-profiles/complex-eval/cases4/recurring-incident/files/src/charge.js b/docker/context-profiles/complex-eval/cases4/recurring-incident/files/src/charge.js
new file mode 100644
index 000000000..c0192c1f3
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases4/recurring-incident/files/src/charge.js
@@ -0,0 +1,46 @@
+// Fake payment gateway. Every call is recorded as one JSON line in an
+// append-only ledger so side effects can be audited after the fact.
+import fs from 'node:fs';
+import path from 'node:path';
+import crypto from 'node:crypto';
+
+function ledgerPath() {
+ return process.env.LEDGER_FILE || path.join(process.cwd(), '.data', 'ledger.jsonl');
+}
+
+function append(entry) {
+ const file = ledgerPath();
+ fs.mkdirSync(path.dirname(file), { recursive: true });
+ fs.appendFileSync(file, `${JSON.stringify({ ...entry, at: new Date().toISOString() })}\n`);
+}
+
+function latency() {
+ return new Promise(resolve => setTimeout(resolve, 5 + Math.floor(Math.random() * 10)));
+}
+
+export async function charge({ orderId, amount }) {
+ await latency();
+ const receipt = { id: `chg_${crypto.randomUUID()}`, type: 'charge', orderId, amount };
+ append(receipt);
+ return receipt;
+}
+
+export async function refund({ orderId, amount }) {
+ await latency();
+ const receipt = { id: `rfnd_${crypto.randomUUID()}`, type: 'refund', orderId, amount };
+ append(receipt);
+ return receipt;
+}
+
+export async function payout({ vendorId, amount }) {
+ await latency();
+ const receipt = { id: `pay_${crypto.randomUUID()}`, type: 'payout', vendorId, amount };
+ append(receipt);
+ return receipt;
+}
+
+export function readLedger(file = ledgerPath()) {
+ let text = '';
+ try { text = fs.readFileSync(file, 'utf8'); } catch { return []; }
+ return text.split('\n').filter(line => line.trim()).map(line => JSON.parse(line));
+}
diff --git a/docker/context-profiles/complex-eval/cases4/recurring-incident/files/src/payouts.js b/docker/context-profiles/complex-eval/cases4/recurring-incident/files/src/payouts.js
new file mode 100644
index 000000000..4b09b6784
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases4/recurring-incident/files/src/payouts.js
@@ -0,0 +1,14 @@
+import { payout } from './charge.js';
+import * as store from './store.js';
+
+// Processes a vendor payout. Finance's batch job calls this once per payout
+// run and has never retried, so the keyless path has never been exercised.
+export async function processPayout(req) {
+ const key = req.idempotencyKey ? `payout:${req.idempotencyKey}` : null;
+ if (key && store.has(key)) {
+ return { ...store.get(key), duplicate: true };
+ }
+ const receipt = await payout({ vendorId: req.vendorId, amount: req.amount });
+ if (key) store.set(key, receipt);
+ return receipt;
+}
diff --git a/docker/context-profiles/complex-eval/cases4/recurring-incident/files/src/refunds.js b/docker/context-profiles/complex-eval/cases4/recurring-incident/files/src/refunds.js
new file mode 100644
index 000000000..b8217e506
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases4/recurring-incident/files/src/refunds.js
@@ -0,0 +1,14 @@
+import { refund } from './charge.js';
+import * as store from './store.js';
+
+// Processes a customer refund. Callers that have one pass an idempotencyKey;
+// plenty of callers (the storefront retry loop among them) do not.
+export async function processRefund(req) {
+ const key = req.idempotencyKey ? `refund:${req.idempotencyKey}` : null;
+ if (key && store.has(key)) {
+ return { ...store.get(key), duplicate: true };
+ }
+ const receipt = await refund({ orderId: req.orderId, amount: req.amount });
+ if (key) store.set(key, receipt);
+ return receipt;
+}
diff --git a/docker/context-profiles/complex-eval/cases4/recurring-incident/files/src/store.js b/docker/context-profiles/complex-eval/cases4/recurring-incident/files/src/store.js
new file mode 100644
index 000000000..3303c7588
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases4/recurring-incident/files/src/store.js
@@ -0,0 +1,33 @@
+// Tiny JSON-file-backed key/value store. All operations are synchronous so a
+// check-and-set within one event-loop turn cannot interleave.
+import fs from 'node:fs';
+import path from 'node:path';
+
+function storePath() {
+ return process.env.STORE_FILE || path.join(process.cwd(), '.data', 'store.json');
+}
+
+function load() {
+ try { return JSON.parse(fs.readFileSync(storePath(), 'utf8')); } catch { return {}; }
+}
+
+function save(data) {
+ const file = storePath();
+ fs.mkdirSync(path.dirname(file), { recursive: true });
+ fs.writeFileSync(file, JSON.stringify(data, null, 1));
+}
+
+export function get(key) {
+ return load()[key];
+}
+
+export function has(key) {
+ return Object.prototype.hasOwnProperty.call(load(), key);
+}
+
+export function set(key, value) {
+ const data = load();
+ data[key] = value;
+ save(data);
+ return value;
+}
diff --git a/docker/context-profiles/complex-eval/cases4/recurring-incident/files/test/payouts.test.js b/docker/context-profiles/complex-eval/cases4/recurring-incident/files/test/payouts.test.js
new file mode 100644
index 000000000..9b51bd593
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases4/recurring-incident/files/test/payouts.test.js
@@ -0,0 +1,30 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+
+function freshEnv(t) {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'payments-test-'));
+ process.env.LEDGER_FILE = path.join(dir, 'ledger.jsonl');
+ process.env.STORE_FILE = path.join(dir, 'store.json');
+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
+}
+
+test('processPayout pays once and returns the gateway receipt', async (t) => {
+ freshEnv(t);
+ const { processPayout } = await import('../src/payouts.js');
+ const receipt = await processPayout({ vendorId: 'ven-1', amount: 5000 });
+ assert.equal(receipt.type, 'payout');
+ assert.equal(receipt.vendorId, 'ven-1');
+ assert.equal(receipt.amount, 5000);
+});
+
+test('processPayout with an explicit key returns the stored receipt on a repeat call', async (t) => {
+ freshEnv(t);
+ const { processPayout } = await import('../src/payouts.js');
+ const first = await processPayout({ vendorId: 'ven-2', amount: 7000, idempotencyKey: 'key-7' });
+ const second = await processPayout({ vendorId: 'ven-2', amount: 7000, idempotencyKey: 'key-7' });
+ assert.equal(second.duplicate, true);
+ assert.equal(second.id, first.id);
+});
diff --git a/docker/context-profiles/complex-eval/cases4/recurring-incident/files/test/refunds.test.js b/docker/context-profiles/complex-eval/cases4/recurring-incident/files/test/refunds.test.js
new file mode 100644
index 000000000..163dc4a50
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases4/recurring-incident/files/test/refunds.test.js
@@ -0,0 +1,30 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+
+function freshEnv(t) {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'payments-test-'));
+ process.env.LEDGER_FILE = path.join(dir, 'ledger.jsonl');
+ process.env.STORE_FILE = path.join(dir, 'store.json');
+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
+}
+
+test('processRefund refunds once and returns the gateway receipt', async (t) => {
+ freshEnv(t);
+ const { processRefund } = await import('../src/refunds.js');
+ const receipt = await processRefund({ orderId: 'ord-1', amount: 1200 });
+ assert.equal(receipt.type, 'refund');
+ assert.equal(receipt.orderId, 'ord-1');
+ assert.equal(receipt.amount, 1200);
+});
+
+test('processRefund with an explicit key returns the stored receipt on a repeat call', async (t) => {
+ freshEnv(t);
+ const { processRefund } = await import('../src/refunds.js');
+ const first = await processRefund({ orderId: 'ord-2', amount: 900, idempotencyKey: 'key-2' });
+ const second = await processRefund({ orderId: 'ord-2', amount: 900, idempotencyKey: 'key-2' });
+ assert.equal(second.duplicate, true);
+ assert.equal(second.id, first.id);
+});
diff --git a/docker/context-profiles/complex-eval/cases4/recurring-incident/meta.json b/docker/context-profiles/complex-eval/cases4/recurring-incident/meta.json
new file mode 100644
index 000000000..15649835e
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases4/recurring-incident/meta.json
@@ -0,0 +1,16 @@
+{
+ "id": "recurring-incident",
+ "category": "learning-loop-chain",
+ "manualIds": [],
+ "checkTimeoutMs": 60000,
+ "steps": [
+ { "manualIds": ["skill:error-handling"] },
+ { "manualIds": ["skill:error-handling"] },
+ { "manualIds": ["skill:continuous-learning"] }
+ ],
+ "selection": {
+ "id": "complex-recurring-incident",
+ "category": "complex-learning-loop",
+ "expectedIds": ["skill:continuous-learning"]
+ }
+}
diff --git a/docker/context-profiles/complex-eval/cases4/recurring-incident/steps/01-refund-retry/check.cjs b/docker/context-profiles/complex-eval/cases4/recurring-incident/steps/01-refund-retry/check.cjs
new file mode 100644
index 000000000..f1b6e681d
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases4/recurring-incident/steps/01-refund-retry/check.cjs
@@ -0,0 +1,207 @@
+'use strict';
+// Step 1 grader (recurring-incident): a refund retried WITHOUT an idempotency
+// key must refund exactly once — in-process (0.20) and across a module reload
+// with the same store (0.20); a regression test wired into `npm test` must fail
+// when the fix is reverted in a scratch copy (0.30); a durable prevention doc
+// must exist (0.20); the mechanism must live in a shared helper module (0.10).
+// Graders cannot spawn child processes (--permission), so tests are executed
+// in-process via node:test's run({ isolation: 'none' }) with TMPDIR redirected
+// into the workspace.
+const fs = require('node:fs');
+const path = require('node:path');
+const { pathToFileURL } = require('node:url');
+
+const probes = [
+ { name: 'retry-same-process-refunds-once', weight: 0.20 },
+ { name: 'retry-after-reload-refunds-once', weight: 0.20 },
+ { name: 'regression-test-wired-and-bites', weight: 0.30 },
+ { name: 'prevention-doc-exists', weight: 0.20 },
+ { name: 'shared-idempotency-helper', weight: 0.10 },
+];
+const results = new Map();
+let finished = false;
+function finish() {
+ if (finished) return;
+ finished = true;
+ let score = 0;
+ for (const probe of probes) {
+ const ok = results.get(probe.name) === true;
+ if (ok) score += probe.weight;
+ process.stdout.write(`${ok ? 'ok' : 'not ok'} - ${probe.name}\n`);
+ }
+ process.stdout.write(`ECC_EVAL_SCORE ${JSON.stringify({ score: Math.round(score * 1000) / 1000 })}\n`);
+ process.exit(0);
+}
+process.on('uncaughtException', finish);
+process.on('unhandledRejection', finish);
+
+const root = process.cwd();
+const scratch = fs.mkdtempSync(path.join(root, '.ecc-g1-'));
+fs.mkdirSync(path.join(scratch, 'tmp'), { recursive: true });
+process.env.TMPDIR = path.join(scratch, 'tmp');
+
+// The fixture's original buggy refunds.js, embedded so the mutation probe can
+// revert the fix in a scratch copy and check the regression suite notices.
+const ORIGINAL_REFUNDS = [
+ "import { refund } from './charge.js';",
+ "import * as store from './store.js';",
+ '',
+ '// Processes a customer refund. Callers that have one pass an idempotencyKey;',
+ '// plenty of callers (the storefront retry loop among them) do not.',
+ 'export async function processRefund(req) {',
+ ' const key = req.idempotencyKey ? `refund:${req.idempotencyKey}` : null;',
+ ' if (key && store.has(key)) {',
+ ' return { ...store.get(key), duplicate: true };',
+ ' }',
+ ' const receipt = await refund({ orderId: req.orderId, amount: req.amount });',
+ ' if (key) store.set(key, receipt);',
+ ' return receipt;',
+ '}',
+ '',
+].join('\n');
+
+let importCounter = 0;
+function importFresh(relative) {
+ importCounter += 1;
+ return import(`${pathToFileURL(path.join(root, relative)).href}?cb=${importCounter}`);
+}
+
+function readLedger(file) {
+ let text = '';
+ try { text = fs.readFileSync(file, 'utf8'); } catch { return []; }
+ return text.split('\n').filter(line => line.trim()).map(line => {
+ try { return JSON.parse(line); } catch { return null; }
+ }).filter(Boolean);
+}
+
+function copyTree(from, to) {
+ fs.mkdirSync(to, { recursive: true });
+ for (const entry of fs.readdirSync(from, { withFileTypes: true })) {
+ const target = path.join(to, entry.name);
+ if (entry.isDirectory()) copyTree(path.join(from, entry.name), target);
+ else if (entry.isFile()) fs.copyFileSync(path.join(from, entry.name), target);
+ }
+}
+
+function findTestFiles(mustMatch) {
+ const found = [];
+ const walk = dir => {
+ let entries = [];
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return; }
+ for (const entry of entries) {
+ if (entry.name.startsWith('.') || entry.name === 'node_modules') continue;
+ const full = path.join(dir, entry.name);
+ if (entry.isDirectory()) { walk(full); continue; }
+ if (!/\.test\.(js|cjs|mjs)$/.test(entry.name)) continue;
+ let content = '';
+ try { content = fs.readFileSync(full, 'utf8'); } catch { continue; }
+ if (mustMatch.every(re => re.test(content))) found.push(full);
+ }
+ };
+ walk(root);
+ return found.sort();
+}
+
+function npmTestWired() {
+ try {
+ const pkg = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'));
+ const script = (pkg.scripts && pkg.scripts.test) || '';
+ // `node --test test/` silently runs nothing on Node 24; that is not wired.
+ return /--test\b/.test(script) && !/--test\s+test\/?\s*$/.test(script.trim());
+ } catch { return false; }
+}
+
+async function countTestFailures(files) {
+ const { run } = require('node:test');
+ let failures = 0;
+ const stream = run({ files, isolation: 'none', concurrency: 1 });
+ stream.on('test:fail', () => { failures += 1; });
+ await new Promise((resolve, reject) => { stream.on('end', resolve); stream.on('error', reject); stream.resume(); });
+ return failures;
+}
+
+function markdownFiles() {
+ const found = [];
+ const walk = dir => {
+ let entries = [];
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return; }
+ for (const entry of entries) {
+ if (entry.name.startsWith('.') || entry.name === 'node_modules') continue;
+ const full = path.join(dir, entry.name);
+ if (entry.isDirectory()) walk(full);
+ else if (/\.(md|markdown|txt)$/i.test(entry.name)) found.push(full);
+ }
+ };
+ walk(root);
+ return found.sort();
+}
+
+function isPreventionDoc(file) {
+ let content = '';
+ try { content = fs.readFileSync(file, 'utf8'); } catch { return false; }
+ return /idempoten/i.test(content) && /prevent|runbook|playbook|checklist|post-?mortem|procedure/i.test(content);
+}
+
+(async () => {
+ // (a) Functional: a keyless refund retried in-process refunds exactly once.
+ try {
+ const ledger = path.join(scratch, 'ledger-a.jsonl');
+ process.env.LEDGER_FILE = ledger;
+ process.env.STORE_FILE = path.join(scratch, 'store-a.json');
+ const refunds = await importFresh('src/refunds.js');
+ await refunds.processRefund({ orderId: 'ord-g1-retry', amount: 2500 });
+ await refunds.processRefund({ orderId: 'ord-g1-retry', amount: 2500 });
+ const entries = readLedger(ledger).filter(e => e.type === 'refund' && e.orderId === 'ord-g1-retry');
+ results.set('retry-same-process-refunds-once', entries.length === 1);
+
+ // (a2) Durable: a fresh module instance (simulated restart) over the same
+ // store must still not refund again.
+ const reloaded = await importFresh('src/refunds.js');
+ await reloaded.processRefund({ orderId: 'ord-g1-retry', amount: 2500 });
+ const afterReload = readLedger(ledger).filter(e => e.type === 'refund' && e.orderId === 'ord-g1-retry');
+ results.set('retry-after-reload-refunds-once', entries.length === 1 && afterReload.length === 1);
+ } catch { /* both functional probes stay false */ }
+
+ // (b) Regression coverage: a refund/idempotency test exists, npm test is
+ // wired, the suite passes as-is, and it FAILS when the fix is reverted.
+ try {
+ const files = findTestFiles([/refund/i, /idempoten|retry|duplicat/i]);
+ let ok = files.length > 0 && npmTestWired();
+ if (ok) ok = (await countTestFailures(files)) === 0;
+ if (ok) {
+ const mut = path.join(scratch, 'mutation');
+ fs.mkdirSync(mut, { recursive: true });
+ copyTree(path.join(root, 'src'), path.join(mut, 'src'));
+ fs.copyFileSync(path.join(root, 'package.json'), path.join(mut, 'package.json'));
+ for (const file of files) {
+ const target = path.join(mut, path.relative(root, file));
+ fs.mkdirSync(path.dirname(target), { recursive: true });
+ fs.copyFileSync(file, target);
+ }
+ fs.writeFileSync(path.join(mut, 'src', 'refunds.js'), ORIGINAL_REFUNDS);
+ const mutated = files.map(file => path.join(mut, path.relative(root, file)));
+ ok = (await countTestFailures(mutated)) > 0;
+ }
+ results.set('regression-test-wired-and-bites', ok);
+ } catch { /* probe stays false */ }
+
+ // (c) A durable prevention artifact: some doc ties idempotency to a
+ // prevention procedure (runbook/playbook/checklist/postmortem).
+ try {
+ results.set('prevention-doc-exists', markdownFiles().some(isPreventionDoc));
+ } catch { /* probe stays false */ }
+
+ // (d) The mechanism lives in a shared helper module that refunds.js imports,
+ // not inline in refunds.js alone.
+ try {
+ const refundsSrc = fs.readFileSync(path.join(root, 'src', 'refunds.js'), 'utf8');
+ const helpers = fs.readdirSync(path.join(root, 'src'))
+ .filter(name => /idempoten/i.test(name) && /\.(js|cjs|mjs)$/.test(name));
+ const imported = /import[^'"]*from\s*['"][^'"]*idempoten[^'"]*['"]/.test(refundsSrc)
+ || /require\(\s*['"][^'"]*idempoten[^'"]*['"]\s*\)/.test(refundsSrc);
+ results.set('shared-idempotency-helper', helpers.length > 0 && imported);
+ } catch { /* probe stays false */ }
+
+ try { fs.rmSync(scratch, { recursive: true, force: true }); } catch { /* best effort */ }
+ finish();
+})();
diff --git a/docker/context-profiles/complex-eval/cases4/recurring-incident/steps/01-refund-retry/query.md b/docker/context-profiles/complex-eval/cases4/recurring-incident/steps/01-refund-retry/query.md
new file mode 100644
index 000000000..84a617791
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases4/recurring-incident/steps/01-refund-retry/query.md
@@ -0,0 +1 @@
+Customers are reporting duplicate refunds again — see docs/incidents.md. When a refund request comes in without an idempotency key and the caller retries, we refund the customer twice. Fix it, and make sure this stops being a recurring incident — it's the third time this quarter.
diff --git a/docker/context-profiles/complex-eval/cases4/recurring-incident/steps/02-payout-storm/check.cjs b/docker/context-profiles/complex-eval/cases4/recurring-incident/steps/02-payout-storm/check.cjs
new file mode 100644
index 000000000..619414014
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases4/recurring-incident/steps/02-payout-storm/check.cjs
@@ -0,0 +1,208 @@
+'use strict';
+// Step 2 grader (recurring-incident): a concurrent keyless payout retry storm
+// must pay exactly once and stay paid once across a module reload (0.40);
+// payouts.js must REUSE the same shared idempotency helper refunds.js imports,
+// with no second inline implementation (0.30); a payout regression test wired
+// into npm test must fail when the fix is reverted in a scratch copy (0.20);
+// the prevention doc must now cover payouts / this class of bug (0.10).
+const fs = require('node:fs');
+const path = require('node:path');
+const { pathToFileURL } = require('node:url');
+
+const probes = [
+ { name: 'payout-storm-pays-once', weight: 0.40 },
+ { name: 'reuses-shared-helper', weight: 0.30 },
+ { name: 'payout-regression-test-bites', weight: 0.20 },
+ { name: 'prevention-doc-covers-class', weight: 0.10 },
+];
+const results = new Map();
+let finished = false;
+function finish() {
+ if (finished) return;
+ finished = true;
+ let score = 0;
+ for (const probe of probes) {
+ const ok = results.get(probe.name) === true;
+ if (ok) score += probe.weight;
+ process.stdout.write(`${ok ? 'ok' : 'not ok'} - ${probe.name}\n`);
+ }
+ process.stdout.write(`ECC_EVAL_SCORE ${JSON.stringify({ score: Math.round(score * 1000) / 1000 })}\n`);
+ process.exit(0);
+}
+process.on('uncaughtException', finish);
+process.on('unhandledRejection', finish);
+
+const root = process.cwd();
+const scratch = fs.mkdtempSync(path.join(root, '.ecc-g2-'));
+fs.mkdirSync(path.join(scratch, 'tmp'), { recursive: true });
+process.env.TMPDIR = path.join(scratch, 'tmp');
+
+// The fixture's original payouts.js, embedded for the mutation probe.
+const ORIGINAL_PAYOUTS = [
+ "import { payout } from './charge.js';",
+ "import * as store from './store.js';",
+ '',
+ '// Processes a vendor payout. Finance\'s batch job calls this once per payout',
+ '// run and has never retried, so the keyless path has never been exercised.',
+ 'export async function processPayout(req) {',
+ ' const key = req.idempotencyKey ? `payout:${req.idempotencyKey}` : null;',
+ ' if (key && store.has(key)) {',
+ ' return { ...store.get(key), duplicate: true };',
+ ' }',
+ ' const receipt = await payout({ vendorId: req.vendorId, amount: req.amount });',
+ ' if (key) store.set(key, receipt);',
+ ' return receipt;',
+ '}',
+ '',
+].join('\n');
+
+let importCounter = 0;
+function importFresh(relative) {
+ importCounter += 1;
+ return import(`${pathToFileURL(path.join(root, relative)).href}?cb=${importCounter}`);
+}
+
+function readLedger(file) {
+ let text = '';
+ try { text = fs.readFileSync(file, 'utf8'); } catch { return []; }
+ return text.split('\n').filter(line => line.trim()).map(line => {
+ try { return JSON.parse(line); } catch { return null; }
+ }).filter(Boolean);
+}
+
+function copyTree(from, to) {
+ fs.mkdirSync(to, { recursive: true });
+ for (const entry of fs.readdirSync(from, { withFileTypes: true })) {
+ const target = path.join(to, entry.name);
+ if (entry.isDirectory()) copyTree(path.join(from, entry.name), target);
+ else if (entry.isFile()) fs.copyFileSync(path.join(from, entry.name), target);
+ }
+}
+
+function findTestFiles(mustMatch) {
+ const found = [];
+ const walk = dir => {
+ let entries = [];
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return; }
+ for (const entry of entries) {
+ if (entry.name.startsWith('.') || entry.name === 'node_modules') continue;
+ const full = path.join(dir, entry.name);
+ if (entry.isDirectory()) { walk(full); continue; }
+ if (!/\.test\.(js|cjs|mjs)$/.test(entry.name)) continue;
+ let content = '';
+ try { content = fs.readFileSync(full, 'utf8'); } catch { continue; }
+ if (mustMatch.every(re => re.test(content))) found.push(full);
+ }
+ };
+ walk(root);
+ return found.sort();
+}
+
+function npmTestWired() {
+ try {
+ const pkg = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'));
+ const script = (pkg.scripts && pkg.scripts.test) || '';
+ return /--test\b/.test(script) && !/--test\s+test\/?\s*$/.test(script.trim());
+ } catch { return false; }
+}
+
+async function countTestFailures(files) {
+ const { run } = require('node:test');
+ let failures = 0;
+ const stream = run({ files, isolation: 'none', concurrency: 1 });
+ stream.on('test:fail', () => { failures += 1; });
+ await new Promise((resolve, reject) => { stream.on('end', resolve); stream.on('error', reject); stream.resume(); });
+ return failures;
+}
+
+function markdownFiles() {
+ const found = [];
+ const walk = dir => {
+ let entries = [];
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return; }
+ for (const entry of entries) {
+ if (entry.name.startsWith('.') || entry.name === 'node_modules') continue;
+ const full = path.join(dir, entry.name);
+ if (entry.isDirectory()) walk(full);
+ else if (/\.(md|markdown|txt)$/i.test(entry.name)) found.push(full);
+ }
+ };
+ walk(root);
+ return found.sort();
+}
+
+// The idempotency helper module specifier refunds.js imports, if any.
+function helperSpecifier() {
+ try {
+ const refundsSrc = fs.readFileSync(path.join(root, 'src', 'refunds.js'), 'utf8');
+ const match = /(?:from|require\()\s*['"]([^'"]*idempoten[^'"]*)['"]/i.exec(refundsSrc);
+ return match ? match[1] : null;
+ } catch { return null; }
+}
+
+(async () => {
+ // (a) Functional: 20 concurrent keyless retries pay exactly once, and a
+ // fresh module instance over the same store still does not pay again.
+ try {
+ const ledger = path.join(scratch, 'ledger-a.jsonl');
+ process.env.LEDGER_FILE = ledger;
+ process.env.STORE_FILE = path.join(scratch, 'store-a.json');
+ const payouts = await importFresh('src/payouts.js');
+ await Promise.all(Array.from({ length: 20 },
+ () => payouts.processPayout({ vendorId: 'ven-g2-storm', amount: 9000 }).catch(() => null)));
+ const afterStorm = readLedger(ledger).filter(e => e.type === 'payout' && e.vendorId === 'ven-g2-storm');
+ const reloaded = await importFresh('src/payouts.js');
+ await reloaded.processPayout({ vendorId: 'ven-g2-storm', amount: 9000 }).catch(() => null);
+ const afterReload = readLedger(ledger).filter(e => e.type === 'payout' && e.vendorId === 'ven-g2-storm');
+ results.set('payout-storm-pays-once', afterStorm.length === 1 && afterReload.length === 1);
+ } catch { /* probe stays false */ }
+
+ // (b) Reuse: payouts.js imports the SAME helper specifier as refunds.js and
+ // does not carry a second inline implementation (own key hashing or its own
+ // seen/inflight table).
+ try {
+ const specifier = helperSpecifier();
+ const payoutsSrc = fs.readFileSync(path.join(root, 'src', 'payouts.js'), 'utf8');
+ const importsSame = specifier !== null
+ && new RegExp(`(?:from|require\\()\\s*['"]${specifier.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}['"]`).test(payoutsSrc);
+ const inlineImplementation = /createHash|new Map\s*\(|new Set\s*\(|new WeakMap\s*\(/.test(payoutsSrc);
+ results.set('reuses-shared-helper', importsSame && !inlineImplementation);
+ } catch { /* probe stays false */ }
+
+ // (c) Regression coverage for payouts, same discipline as step 1.
+ try {
+ const files = findTestFiles([/payout/i, /idempoten|retry|duplicat|storm|concurrent/i]);
+ let ok = files.length > 0 && npmTestWired();
+ if (ok) ok = (await countTestFailures(files)) === 0;
+ if (ok) {
+ const mut = path.join(scratch, 'mutation');
+ fs.mkdirSync(mut, { recursive: true });
+ copyTree(path.join(root, 'src'), path.join(mut, 'src'));
+ fs.copyFileSync(path.join(root, 'package.json'), path.join(mut, 'package.json'));
+ for (const file of files) {
+ const target = path.join(mut, path.relative(root, file));
+ fs.mkdirSync(path.dirname(target), { recursive: true });
+ fs.copyFileSync(file, target);
+ }
+ fs.writeFileSync(path.join(mut, 'src', 'payouts.js'), ORIGINAL_PAYOUTS);
+ const mutated = files.map(file => path.join(mut, path.relative(root, file)));
+ ok = (await countTestFailures(mutated)) > 0;
+ }
+ results.set('payout-regression-test-bites', ok);
+ } catch { /* probe stays false */ }
+
+ // (d) The prevention doc now covers payouts / the whole class of bug.
+ try {
+ const covered = markdownFiles().some(file => {
+ let content = '';
+ try { content = fs.readFileSync(file, 'utf8'); } catch { return false; }
+ return /idempoten/i.test(content)
+ && /prevent|runbook|playbook|checklist|post-?mortem|procedure/i.test(content)
+ && /payout|vendor|class of|general|every payment|any payment/i.test(content);
+ });
+ results.set('prevention-doc-covers-class', covered);
+ } catch { /* probe stays false */ }
+
+ try { fs.rmSync(scratch, { recursive: true, force: true }); } catch { /* best effort */ }
+ finish();
+})();
diff --git a/docker/context-profiles/complex-eval/cases4/recurring-incident/steps/02-payout-storm/query.md b/docker/context-profiles/complex-eval/cases4/recurring-incident/steps/02-payout-storm/query.md
new file mode 100644
index 000000000..b61f88e6e
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases4/recurring-incident/steps/02-payout-storm/query.md
@@ -0,0 +1 @@
+Finance just flagged that their payout batch job is about to start retrying on timeouts, and payout retries can double-pay vendors. Same family of problem as the refunds — handle it. One hard requirement: a retried payout must never pay a vendor twice, even if the service restarts between the attempts.
diff --git a/docker/context-profiles/complex-eval/cases4/recurring-incident/steps/03-handoff/check.cjs b/docker/context-profiles/complex-eval/cases4/recurring-incident/steps/03-handoff/check.cjs
new file mode 100644
index 000000000..e495c15b0
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases4/recurring-incident/steps/03-handoff/check.cjs
@@ -0,0 +1,104 @@
+'use strict';
+// Step 3 grader (recurring-incident): the handoff note. A handoff doc must
+// exist (0.20); every file path it references must actually exist in the
+// workspace, with at least two concrete references (0.30); it must name the
+// shared idempotency helper and describe the prevention procedure (0.30); it
+// must cover both the refunds and the payouts incidents (0.20). Scored on the
+// best candidate when several handoff files exist.
+const fs = require('node:fs');
+const path = require('node:path');
+
+const probes = [
+ { name: 'handoff-exists', weight: 0.20 },
+ { name: 'referenced-paths-exist', weight: 0.30 },
+ { name: 'names-helper-and-procedure', weight: 0.30 },
+ { name: 'covers-both-incidents', weight: 0.20 },
+];
+const results = new Map();
+let finished = false;
+function finish() {
+ if (finished) return;
+ finished = true;
+ let score = 0;
+ for (const probe of probes) {
+ const ok = results.get(probe.name) === true;
+ if (ok) score += probe.weight;
+ process.stdout.write(`${ok ? 'ok' : 'not ok'} - ${probe.name}\n`);
+ }
+ process.stdout.write(`ECC_EVAL_SCORE ${JSON.stringify({ score: Math.round(score * 1000) / 1000 })}\n`);
+ process.exit(0);
+}
+process.on('uncaughtException', finish);
+process.on('unhandledRejection', finish);
+
+const root = process.cwd();
+
+function handoffFiles() {
+ const found = [];
+ const walk = dir => {
+ let entries = [];
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return; }
+ for (const entry of entries) {
+ if (entry.name.startsWith('.') || entry.name === 'node_modules') continue;
+ const full = path.join(dir, entry.name);
+ if (entry.isDirectory()) { walk(full); continue; }
+ if (/hand[ -]?off/i.test(entry.name) && /\.(md|markdown|txt)$/i.test(entry.name)) found.push(full);
+ }
+ };
+ walk(root);
+ return found.sort();
+}
+
+// Candidate file paths mentioned in prose: at least one path segment and a
+// file extension (src/refunds.js, docs/runbooks/idempotency.md, ...).
+function referencedPaths(content) {
+ const tokens = new Set();
+ for (const match of content.matchAll(/(?:[\w@+.-]+\/)+[\w@+.-]+\.[a-z0-9]{1,8}/gi)) {
+ const token = match[0].replace(/[.,;:'")\]`]+$/, '').replace(/^[^\w@+.-]+/, '');
+ if (token.includes('..') || /^https?/i.test(token)) continue;
+ tokens.add(token);
+ }
+ return [...tokens];
+}
+
+function helperBasename() {
+ try {
+ const refundsSrc = fs.readFileSync(path.join(root, 'src', 'refunds.js'), 'utf8');
+ const match = /(?:from|require\()\s*['"]([^'"]*idempoten[^'"]*)['"]/i.exec(refundsSrc);
+ return match ? path.basename(match[1]) : null;
+ } catch { return null; }
+}
+
+function scoreCandidate(content) {
+ const verdicts = new Map();
+ verdicts.set('handoff-exists', true);
+
+ const paths = referencedPaths(content);
+ verdicts.set('referenced-paths-exist', paths.length >= 2
+ && paths.every(token => fs.existsSync(path.join(root, token))));
+
+ const helper = helperBasename();
+ verdicts.set('names-helper-and-procedure', helper !== null
+ && content.includes(helper)
+ && /prevent|runbook|playbook|checklist|regression|npm test|procedure/i.test(content));
+
+ verdicts.set('covers-both-incidents', /refund/i.test(content) && /payout/i.test(content));
+ return verdicts;
+}
+
+try {
+ const candidates = handoffFiles();
+ if (candidates.length > 0) {
+ let best = null;
+ for (const file of candidates) {
+ let content = '';
+ try { content = fs.readFileSync(file, 'utf8'); } catch { continue; }
+ const verdicts = scoreCandidate(content);
+ const total = [...verdicts.values()].filter(Boolean).length;
+ if (!best || total > best.total) best = { verdicts, total };
+ }
+ if (best) for (const [name, ok] of best.verdicts) results.set(name, ok);
+ }
+} catch { /* everything stays false */ }
+
+finish();
diff --git a/docker/context-profiles/complex-eval/cases4/recurring-incident/steps/03-handoff/query.md b/docker/context-profiles/complex-eval/cases4/recurring-incident/steps/03-handoff/query.md
new file mode 100644
index 000000000..a76859c00
--- /dev/null
+++ b/docker/context-profiles/complex-eval/cases4/recurring-incident/steps/03-handoff/query.md
@@ -0,0 +1 @@
+You're rolling off this area. Write the handoff note for whoever picks this up next.
diff --git a/docker/context-profiles/complex-eval/naive2/keccak-selector/src/selector.js b/docker/context-profiles/complex-eval/naive2/keccak-selector/src/selector.js
new file mode 100644
index 000000000..7d878cce5
--- /dev/null
+++ b/docker/context-profiles/complex-eval/naive2/keccak-selector/src/selector.js
@@ -0,0 +1,11 @@
+'use strict';
+// Deliberately naive control: confuses Keccak-256 with the finalized NIST
+// SHA3-256 (different padding suffix), so every vector is wrong.
+const crypto = require('node:crypto');
+
+function functionSelector(signature) {
+ if (typeof signature !== 'string') throw new TypeError('signature must be a string');
+ return `0x${crypto.createHash('sha3-256').update(signature, 'utf8').digest('hex').slice(0, 8)}`;
+}
+
+module.exports = { functionSelector };
diff --git a/docker/context-profiles/complex-eval/naive4/recurring-incident/HANDOFF.md b/docker/context-profiles/complex-eval/naive4/recurring-incident/HANDOFF.md
new file mode 100644
index 000000000..393321d57
--- /dev/null
+++ b/docker/context-profiles/complex-eval/naive4/recurring-incident/HANDOFF.md
@@ -0,0 +1,3 @@
+# Handoff
+
+Refunds were double-processing when clients retried. Fixed by remembering what we already refunded. — Sam
diff --git a/docker/context-profiles/complex-eval/naive4/recurring-incident/src/payouts.js b/docker/context-profiles/complex-eval/naive4/recurring-incident/src/payouts.js
new file mode 100644
index 000000000..d29a194d5
--- /dev/null
+++ b/docker/context-profiles/complex-eval/naive4/recurring-incident/src/payouts.js
@@ -0,0 +1,15 @@
+import { payout } from './charge.js';
+
+// Track in-flight payouts so a burst of retries only sends one.
+const pendingPayouts = new Map();
+
+export async function processPayout(req) {
+ const tag = `pay-${req.vendorId}-${req.amount}`;
+ if (pendingPayouts.has(tag)) {
+ const receipt = await pendingPayouts.get(tag);
+ return { ...receipt, duplicate: true };
+ }
+ const pending = payout({ vendorId: req.vendorId, amount: req.amount });
+ pendingPayouts.set(tag, pending);
+ return pending;
+}
diff --git a/docker/context-profiles/complex-eval/naive4/recurring-incident/src/refunds.js b/docker/context-profiles/complex-eval/naive4/recurring-incident/src/refunds.js
new file mode 100644
index 000000000..e0cddd01b
--- /dev/null
+++ b/docker/context-profiles/complex-eval/naive4/recurring-incident/src/refunds.js
@@ -0,0 +1,13 @@
+import { refund } from './charge.js';
+
+// Remember which refunds we already sent so we don't send them twice.
+const seenRefunds = new Set();
+
+export async function processRefund(req) {
+ const key = req.idempotencyKey || `${req.orderId}:${req.amount}`;
+ if (seenRefunds.has(key)) {
+ return { id: `dup_${key}`, type: 'refund', orderId: req.orderId, amount: req.amount, duplicate: true };
+ }
+ seenRefunds.add(key);
+ return refund({ orderId: req.orderId, amount: req.amount });
+}
diff --git a/docker/context-profiles/complex-eval/reference/incident-triage/INCIDENT.md b/docker/context-profiles/complex-eval/reference/incident-triage/INCIDENT.md
new file mode 100644
index 000000000..251ea9c51
--- /dev/null
+++ b/docker/context-profiles/complex-eval/reference/incident-triage/INCIDENT.md
@@ -0,0 +1,27 @@
+# Incident 2026-09-24: order totals off by one cent
+
+## Root cause
+
+**C-2** — the totals refactor in `src/totals.js`.
+
+The refactor replaced integer-cent arithmetic with a decimal discount factor
+(`priceCents * quantity * (1 - discountPercent / 100)`). Decimal factors such
+as 0.7 or 0.93 have no exact binary floating-point representation, so for
+line amounts whose exact discounted value lands precisely on a half-cent
+boundary (e.g. 165 cents at 30% off = 115.5), the float result lands just
+below the boundary and `Math.round` rounds down instead of half-up. Every
+affected order is undercharged by exactly one cent, matching the finance
+findings in `evidence/incident.txt`.
+
+## Evidence
+
+- `evidence/incident.txt`: every flagged order is off by exactly one cent in the
+ store's favor, and all of them appeared after the 2026-09-23 deploy.
+- C-1 (logging) and C-3 (inventory timeout) cannot change totals; C-2 touched
+ the totals computation itself.
+
+## Fix
+
+`src/totals.js` now computes line discounts with exact integer arithmetic:
+`floor((priceCents * quantity * (100 - discountPercent) + 50) / 100)`, which
+rounds half-up on exact cent boundaries with no floating-point error.
diff --git a/docker/context-profiles/complex-eval/reference/incident-triage/src/totals.js b/docker/context-profiles/complex-eval/reference/incident-triage/src/totals.js
new file mode 100644
index 000000000..398a1f132
--- /dev/null
+++ b/docker/context-profiles/complex-eval/reference/incident-triage/src/totals.js
@@ -0,0 +1,15 @@
+'use strict';
+
+// Fixed after the 2026-09-24 incident: totals use exact integer-cent
+// arithmetic. Per line: priceCents * quantity * (100 - discountPercent) / 100,
+// rounded half-up via (n + 50) / 100 floored — no floating point anywhere.
+function computeOrderTotal(order) {
+ let total = 0;
+ for (const line of order.lines) {
+ const numerator = line.priceCents * line.quantity * (100 - order.discountPercent);
+ total += Math.floor((numerator + 50) / 100);
+ }
+ return total;
+}
+
+module.exports = { computeOrderTotal };
diff --git a/docker/context-profiles/complex-eval/reference/sentinel-api/src/app.js b/docker/context-profiles/complex-eval/reference/sentinel-api/src/app.js
new file mode 100644
index 000000000..da0f88d96
--- /dev/null
+++ b/docker/context-profiles/complex-eval/reference/sentinel-api/src/app.js
@@ -0,0 +1,120 @@
+'use strict';
+const fs = require('node:fs');
+const path = require('node:path');
+const http = require('node:http');
+const config = require('./config');
+const store = require('./store');
+
+const HTML_ESCAPES = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' };
+const escapeHtml = text => text.replace(/[&<>"']/g, char => HTML_ESCAPES[char]);
+
+function sendJson(res, status, value) {
+ res.writeHead(status, { 'content-type': 'application/json' });
+ res.end(JSON.stringify(value));
+}
+
+function readBody(req, res, callback) {
+ const chunks = [];
+ let bytes = 0;
+ let rejected = false;
+ req.on('data', chunk => {
+ bytes += chunk.length;
+ if (bytes > config.MAX_BODY_BYTES && !rejected) {
+ rejected = true;
+ sendJson(res, 413, { error: 'payload too large' });
+ req.destroy();
+ return;
+ }
+ chunks.push(chunk);
+ });
+ req.on('end', () => { if (!rejected) callback(Buffer.concat(chunks).toString('utf8')); });
+}
+
+function page(paste) {
+ return `paste ${paste.id} `
+ + `${escapeHtml(paste.content)} `;
+}
+
+function createApp() {
+ const adminToken = process.env.ADMIN_TOKEN || null;
+
+ return http.createServer((req, res) => {
+ const url = new URL(req.url, 'http://localhost');
+
+ if (req.method === 'POST' && url.pathname === '/pastes') {
+ readBody(req, res, body => {
+ let parsed;
+ try { parsed = JSON.parse(body); } catch {
+ sendJson(res, 400, { error: 'invalid JSON body' });
+ return;
+ }
+ if (typeof parsed.content !== 'string') {
+ sendJson(res, 400, { error: 'content must be a string' });
+ return;
+ }
+ const paste = store.create(parsed.content);
+ sendJson(res, 201, { id: paste.id, deleteToken: paste.deleteToken });
+ });
+ return;
+ }
+
+ const pasteMatch = /^\/pastes\/([\w-]+)$/.exec(url.pathname);
+ if (pasteMatch && req.method === 'GET') {
+ const paste = store.get(pasteMatch[1]);
+ if (!paste) { sendJson(res, 404, { error: 'not found' }); return; }
+ sendJson(res, 200, { id: paste.id, content: paste.content });
+ return;
+ }
+ if (pasteMatch && req.method === 'DELETE') {
+ const paste = store.get(pasteMatch[1]);
+ if (!paste) { sendJson(res, 404, { error: 'not found' }); return; }
+ if (req.headers['x-delete-token'] !== paste.deleteToken) {
+ sendJson(res, 403, { error: 'bad delete token' });
+ return;
+ }
+ store.remove(paste.id);
+ res.writeHead(204);
+ res.end();
+ return;
+ }
+
+ const pageMatch = /^\/p\/([\w-]+)$/.exec(url.pathname);
+ if (pageMatch && req.method === 'GET') {
+ const paste = store.get(pageMatch[1]);
+ if (!paste) { sendJson(res, 404, { error: 'not found' }); return; }
+ res.writeHead(200, { 'content-type': 'text/html' });
+ res.end(page(paste));
+ return;
+ }
+
+ if (req.method === 'GET' && url.pathname === '/files') {
+ const name = url.searchParams.get('name') || '';
+ const resolved = path.resolve(config.FILES_DIR, name);
+ if (resolved !== config.FILES_DIR && !resolved.startsWith(config.FILES_DIR + path.sep)) {
+ sendJson(res, 400, { error: 'invalid file name' });
+ return;
+ }
+ try {
+ const content = fs.readFileSync(resolved);
+ res.writeHead(200, { 'content-type': 'text/plain' });
+ res.end(content);
+ } catch {
+ sendJson(res, 404, { error: 'not found' });
+ }
+ return;
+ }
+
+ if (req.method === 'GET' && url.pathname === '/admin/stats') {
+ if (!adminToken || req.headers['x-admin-token'] !== adminToken) {
+ sendJson(res, 401, { error: 'unauthorized' });
+ return;
+ }
+ sendJson(res, 200, store.stats());
+ return;
+ }
+
+ sendJson(res, 404, { error: 'not found' });
+ });
+}
+
+module.exports = { createApp };
diff --git a/docker/context-profiles/complex-eval/reference/sentinel-api/src/config.js b/docker/context-profiles/complex-eval/reference/sentinel-api/src/config.js
new file mode 100644
index 000000000..f36468899
--- /dev/null
+++ b/docker/context-profiles/complex-eval/reference/sentinel-api/src/config.js
@@ -0,0 +1,7 @@
+'use strict';
+const path = require('node:path');
+
+module.exports = {
+ MAX_BODY_BYTES: 64 * 1024,
+ FILES_DIR: path.join(__dirname, '..', 'data', 'files'),
+};
diff --git a/docker/context-profiles/complex-eval/reference/sentinel-api/src/store.js b/docker/context-profiles/complex-eval/reference/sentinel-api/src/store.js
new file mode 100644
index 000000000..88f194153
--- /dev/null
+++ b/docker/context-profiles/complex-eval/reference/sentinel-api/src/store.js
@@ -0,0 +1,28 @@
+'use strict';
+const crypto = require('node:crypto');
+
+// In-memory paste store. Delete tokens are cryptographically random and shown
+// once at creation.
+const pastes = new Map();
+let nextId = 1;
+
+function create(content) {
+ const id = `p_${nextId++}`;
+ const paste = { id, content, deleteToken: crypto.randomBytes(16).toString('hex') };
+ pastes.set(id, paste);
+ return paste;
+}
+
+function get(id) {
+ return pastes.get(id) || null;
+}
+
+function remove(id) {
+ return pastes.delete(id);
+}
+
+function stats() {
+ return { pastes: pastes.size, created: nextId - 1 };
+}
+
+module.exports = { create, get, remove, stats };
diff --git a/docker/context-profiles/complex-eval/reference/webhook-relay/src/app.js b/docker/context-profiles/complex-eval/reference/webhook-relay/src/app.js
new file mode 100644
index 000000000..c7c97d267
--- /dev/null
+++ b/docker/context-profiles/complex-eval/reference/webhook-relay/src/app.js
@@ -0,0 +1,73 @@
+'use strict';
+const http = require('node:http');
+const crypto = require('node:crypto');
+
+const MAX_ATTEMPTS = 5;
+const BASE_DELAY_MS = 100;
+
+function createRelay() {
+ const deliveries = new Map();
+
+ async function attempt(record) {
+ record.attempts += 1;
+ try {
+ const response = await fetch(record.url, {
+ method: 'POST', headers: { 'content-type': 'application/json' },
+ body: JSON.stringify(record.payload), signal: AbortSignal.timeout(5000) });
+ if (response.status >= 200 && response.status < 300) {
+ record.status = 'delivered';
+ record.lastError = null;
+ return;
+ }
+ record.lastError = `HTTP ${response.status}`;
+ } catch (error) {
+ record.lastError = error && error.message ? error.message : 'delivery failed';
+ }
+ if (record.attempts >= MAX_ATTEMPTS) {
+ record.status = 'dead';
+ return;
+ }
+ const delay = BASE_DELAY_MS * 2 ** (record.attempts - 1);
+ setTimeout(() => { void attempt(record); }, delay);
+ }
+
+ const server = http.createServer((req, res) => {
+ if (req.method === 'POST' && req.url === '/deliveries') {
+ let body = '';
+ req.on('data', chunk => { body += chunk; });
+ req.on('end', () => {
+ let parsed;
+ try { parsed = JSON.parse(body); } catch {
+ res.writeHead(400, { 'content-type': 'application/json' });
+ res.end(JSON.stringify({ error: 'invalid JSON body' }));
+ return;
+ }
+ const id = crypto.randomUUID();
+ const record = { id, url: parsed.url, payload: parsed.payload,
+ status: 'pending', attempts: 0, lastError: null };
+ deliveries.set(id, record);
+ void attempt(record);
+ res.writeHead(202, { 'content-type': 'application/json' });
+ res.end(JSON.stringify({ id }));
+ });
+ return;
+ }
+ const match = /^\/deliveries\/([0-9a-f-]+)$/.exec(req.url || '');
+ if (req.method === 'GET' && match) {
+ const record = deliveries.get(match[1]);
+ if (!record) {
+ res.writeHead(404, { 'content-type': 'application/json' });
+ res.end(JSON.stringify({ error: 'not found' }));
+ return;
+ }
+ res.writeHead(200, { 'content-type': 'application/json' });
+ res.end(JSON.stringify(record));
+ return;
+ }
+ res.writeHead(404, { 'content-type': 'application/json' });
+ res.end(JSON.stringify({ error: 'not found' }));
+ });
+ return server;
+}
+
+module.exports = { createRelay };
diff --git a/docker/context-profiles/complex-eval/reference2/event-stats-api/src/app.js b/docker/context-profiles/complex-eval/reference2/event-stats-api/src/app.js
new file mode 100644
index 000000000..2abfb2eff
--- /dev/null
+++ b/docker/context-profiles/complex-eval/reference2/event-stats-api/src/app.js
@@ -0,0 +1,87 @@
+'use strict';
+const http = require('node:http');
+const { events } = require('./data');
+
+// Indexed implementation: per-type arrays sorted by timestamp, with prefix
+// sums, built once at startup. Per query the range is located with binary
+// search; only the matching slice is touched.
+function buildIndex() {
+ const byType = new Map();
+ for (const event of events) {
+ if (!byType.has(event.type)) byType.set(event.type, []);
+ byType.get(event.type).push(event);
+ }
+ for (const rows of byType.values()) {
+ rows.sort((a, b) => a.ts - b.ts);
+ const prefix = new Float64Array(rows.length + 1);
+ for (let i = 0; i < rows.length; i++) prefix[i + 1] = prefix[i] + rows[i].value;
+ rows.prefixSums = prefix;
+ }
+ return byType;
+}
+
+function lowerBound(rows, ts) {
+ let lo = 0;
+ let hi = rows.length;
+ while (lo < hi) {
+ const mid = (lo + hi) >> 1;
+ if (rows[mid].ts < ts) lo = mid + 1; else hi = mid;
+ }
+ return lo;
+}
+
+function upperBound(rows, ts) {
+ let lo = 0;
+ let hi = rows.length;
+ while (lo < hi) {
+ const mid = (lo + hi) >> 1;
+ if (rows[mid].ts <= ts) lo = mid + 1; else hi = mid;
+ }
+ return lo;
+}
+
+const EMPTY = { count: 0, sum: 0, avg: null, p50: null, p95: null, p99: null, min: null, max: null };
+
+function summarize(index, type, from, to) {
+ const rows = index.get(type);
+ if (!rows) return EMPTY;
+ const lo = from === null ? 0 : lowerBound(rows, from);
+ const hi = to === null ? rows.length : upperBound(rows, to);
+ const count = hi - lo;
+ if (count <= 0) return EMPTY;
+ const sum = rows.prefixSums[hi] - rows.prefixSums[lo];
+ const values = new Array(count);
+ for (let i = 0; i < count; i++) values[i] = rows[lo + i].value;
+ values.sort((a, b) => a - b);
+ const rank = p => values[Math.ceil((p / 100) * count) - 1];
+ const avgCents = Math.floor((sum * 200 + count) / (count * 2));
+ return { count, sum, avg: avgCents / 100,
+ p50: rank(50), p95: rank(95), p99: rank(99), min: values[0], max: values[count - 1] };
+}
+
+function createApp() {
+ const index = buildIndex();
+ return http.createServer((req, res) => {
+ const url = new URL(req.url, 'http://localhost');
+ if (req.method === 'GET' && url.pathname === '/stats') {
+ const type = url.searchParams.get('type');
+ const hasFrom = url.searchParams.has('from');
+ const hasTo = url.searchParams.has('to');
+ const from = hasFrom ? Number(url.searchParams.get('from')) : null;
+ const to = hasTo ? Number(url.searchParams.get('to')) : null;
+ if ((hasFrom && !Number.isFinite(from)) || (hasTo && !Number.isFinite(to))
+ || (from !== null && to !== null && from > to)) {
+ res.writeHead(400, { 'content-type': 'application/json' });
+ res.end(JSON.stringify({ error: 'invalid bounds' }));
+ return;
+ }
+ res.writeHead(200, { 'content-type': 'application/json' });
+ res.end(JSON.stringify({ type, from, to, ...summarize(index, type, from, to) }));
+ return;
+ }
+ res.writeHead(404, { 'content-type': 'application/json' });
+ res.end(JSON.stringify({ error: 'not found' }));
+ });
+}
+
+module.exports = { createApp };
diff --git a/docker/context-profiles/complex-eval/reference2/forge-cli/src/cli.js b/docker/context-profiles/complex-eval/reference2/forge-cli/src/cli.js
new file mode 100644
index 000000000..58301d426
--- /dev/null
+++ b/docker/context-profiles/complex-eval/reference2/forge-cli/src/cli.js
@@ -0,0 +1,98 @@
+'use strict';
+
+const NAME = /^[a-z0-9][a-z0-9-]*$/;
+const USAGE = 'usage: snippet \n';
+const ADD_USAGE = 'usage: add [--tags t1,t2] \n';
+
+const ok = (stdout = '') => ({ code: 0, stdout, stderr: '' });
+const fail = (code, stderr) => ({ code, stdout: '', stderr });
+
+function snippetsOf(state) {
+ if (!state.snippets || typeof state.snippets !== 'object') state.snippets = {};
+ return state.snippets;
+}
+
+function sortedNames(snippets, filter) {
+ return Object.keys(snippets).filter(filter).sort();
+}
+
+function run(argv, state) {
+ try {
+ const snippets = snippetsOf(state);
+ const [command, ...args] = argv;
+
+ if (command === 'add') {
+ let tags = [];
+ let rest = args;
+ const tagIndex = args.indexOf('--tags');
+ const name = args[0];
+ if (tagIndex !== -1) {
+ if (tagIndex < 1 || !args[tagIndex + 1]) return fail(2, ADD_USAGE);
+ tags = args[tagIndex + 1].split(',').filter(Boolean);
+ rest = [args[0], ...args.slice(tagIndex + 2)];
+ }
+ const text = rest.slice(1).join(' ');
+ if (!name || !text) return fail(2, ADD_USAGE);
+ if (!NAME.test(name)) return fail(2, `error: invalid snippet name '${name}'\n`);
+ if (snippets[name]) return fail(1, `error: snippet '${name}' already exists\n`);
+ snippets[name] = { text, tags: [...tags].sort() };
+ return ok(`created ${name}\n`);
+ }
+
+ if (command === 'get') {
+ const snippet = snippets[args[0]];
+ if (!snippet) return fail(2, `error: no snippet named '${args[0]}'\n`);
+ return ok(`${snippet.text}\n`);
+ }
+
+ if (command === 'remove') {
+ const snippet = snippets[args[0]];
+ if (!snippet) return fail(2, `error: no snippet named '${args[0]}'\n`);
+ delete snippets[args[0]];
+ return ok(`removed ${args[0]}\n`);
+ }
+
+ if (command === 'list') {
+ const tagIndex = args.indexOf('--tag');
+ const tag = tagIndex !== -1 ? args[tagIndex + 1] : null;
+ const names = sortedNames(snippets, name => tag === null || snippets[name].tags.includes(tag));
+ return ok(names.length ? `${names.join('\n')}\n` : 'no snippets\n');
+ }
+
+ if (command === 'search') {
+ const term = (args[0] || '').toLowerCase();
+ const names = sortedNames(snippets, name =>
+ name.toLowerCase().includes(term) || snippets[name].text.toLowerCase().includes(term));
+ return ok(names.length ? `${names.join('\n')}\n` : 'no matches\n');
+ }
+
+ if (command === 'export') {
+ const out = { snippets: {} };
+ for (const name of sortedNames(snippets, () => true)) {
+ out.snippets[name] = { text: snippets[name].text, tags: [...snippets[name].tags].sort() };
+ }
+ return ok(`${JSON.stringify(out)}\n`);
+ }
+
+ if (command === 'import') {
+ let parsed;
+ try { parsed = JSON.parse(args[0]); } catch { return fail(1, 'error: invalid JSON\n'); }
+ const incoming = parsed && typeof parsed === 'object' ? parsed.snippets : null;
+ if (!incoming || typeof incoming !== 'object') return fail(1, 'error: invalid JSON\n');
+ let imported = 0;
+ let skipped = 0;
+ for (const [name, value] of Object.entries(incoming)) {
+ if (snippets[name]) { skipped++; continue; }
+ snippets[name] = { text: value.text, tags: [...(value.tags || [])].sort() };
+ imported++;
+ }
+ return ok(`imported ${imported}, skipped ${skipped}\n`);
+ }
+
+ return fail(2, USAGE);
+ } catch {
+ return fail(2, USAGE);
+ }
+}
+
+module.exports = { run };
diff --git a/docker/context-profiles/complex-eval/reference2/keccak-selector/src/selector.js b/docker/context-profiles/complex-eval/reference2/keccak-selector/src/selector.js
new file mode 100644
index 000000000..0054fc2e0
--- /dev/null
+++ b/docker/context-profiles/complex-eval/reference2/keccak-selector/src/selector.js
@@ -0,0 +1,53 @@
+'use strict';
+// Keccak-256 (original Keccak padding 0x01, NOT the NIST SHA3-256 suffix 0x06).
+// Keccak-f[1600] permutation over 25 64-bit little-endian lanes as BigInts.
+const RC = [0x0000000000000001n, 0x0000000000008082n, 0x800000000000808an, 0x8000000080008000n,
+ 0x000000000000808bn, 0x0000000080000001n, 0x8000000080008081n, 0x8000000000008009n,
+ 0x000000000000008an, 0x0000000000000088n, 0x0000000080008009n, 0x000000008000000an,
+ 0x000000008000808bn, 0x800000000000008bn, 0x8000000000008089n, 0x8000000000008003n,
+ 0x8000000000008002n, 0x8000000000000080n, 0x000000000000800an, 0x800000008000000an,
+ 0x8000000080008081n, 0x8000000000008080n, 0x0000000080000001n, 0x8000000080008008n];
+const ROT = [[0, 36, 3, 41, 18], [1, 44, 10, 45, 2], [62, 6, 43, 15, 61],
+ [28, 55, 25, 21, 56], [27, 20, 39, 8, 14]];
+const MASK = 0xffffffffffffffffn;
+const rotl = (x, n) => n === 0n ? x : ((x << n) | (x >> (64n - n))) & MASK;
+
+function keccakF(s) {
+ for (let round = 0; round < 24; round++) {
+ const c = [];
+ const d = [];
+ for (let x = 0; x < 5; x++) c[x] = s[x] ^ s[x + 5] ^ s[x + 10] ^ s[x + 15] ^ s[x + 20];
+ for (let x = 0; x < 5; x++) d[x] = c[(x + 4) % 5] ^ rotl(c[(x + 1) % 5], 1n);
+ for (let y = 0; y < 5; y++) for (let x = 0; x < 5; x++) s[x + 5 * y] ^= d[x];
+ const b = new Array(25);
+ for (let y = 0; y < 5; y++) {
+ for (let x = 0; x < 5; x++) b[y + 5 * ((2 * x + 3 * y) % 5)] = rotl(s[x + 5 * y], BigInt(ROT[x][y]));
+ }
+ for (let y = 0; y < 5; y++) {
+ for (let x = 0; x < 5; x++) s[x + 5 * y] = b[x + 5 * y] ^ ((~b[(x + 1) % 5 + 5 * y] & MASK) & b[(x + 2) % 5 + 5 * y]);
+ }
+ s[0] ^= RC[round];
+ }
+}
+
+function keccak256(bytes) {
+ const rate = 136; // 1088-bit rate, 512-bit capacity
+ const state = new Array(25).fill(0n);
+ const q = rate - (bytes.length % rate);
+ const padded = Buffer.concat([bytes, Buffer.from([0x01]), Buffer.alloc(q - 1)]);
+ padded[padded.length - 1] |= 0x80;
+ for (let offset = 0; offset < padded.length; offset += rate) {
+ for (let i = 0; i < rate; i++) state[i >> 3] ^= BigInt(padded[offset + i]) << BigInt(8 * (i & 7));
+ keccakF(state);
+ }
+ const out = [];
+ for (let i = 0; i < 32; i++) out.push(Number((state[i >> 3] >> BigInt(8 * (i & 7))) & 0xffn));
+ return Buffer.from(out);
+}
+
+function functionSelector(signature) {
+ if (typeof signature !== 'string') throw new TypeError('signature must be a string');
+ return `0x${keccak256(Buffer.from(signature, 'utf8')).subarray(0, 4).toString('hex')}`;
+}
+
+module.exports = { functionSelector };
diff --git a/docker/context-profiles/complex-eval/reference3/chained-tickets/CHANGELOG.md b/docker/context-profiles/complex-eval/reference3/chained-tickets/CHANGELOG.md
new file mode 100644
index 000000000..e8cad2f0c
--- /dev/null
+++ b/docker/context-profiles/complex-eval/reference3/chained-tickets/CHANGELOG.md
@@ -0,0 +1,6 @@
+# Changelog
+
+- 2026-09-25: Initial shortlink core — create, redirect, expiry, and delete per API.md.
+- 2026-09-25: Persistence — links survive restarts via the DATA_FILE JSON store; missing or corrupt data files start clean.
+- 2026-09-25: Abuse protection — URL validation (http/https only, length cap), request body limits, and per-client rate limiting with 429 responses.
+- 2026-09-25: Analytics — per-link redirect hit counts exposed at GET /links/:code/stats.
diff --git a/docker/context-profiles/complex-eval/reference3/chained-tickets/README.md b/docker/context-profiles/complex-eval/reference3/chained-tickets/README.md
new file mode 100644
index 000000000..3420482fe
--- /dev/null
+++ b/docker/context-profiles/complex-eval/reference3/chained-tickets/README.md
@@ -0,0 +1,14 @@
+# shortlink
+
+Internal link shortener service. Node.js standard library only, CommonJS.
+
+- `API.md` — the HTTP contract.
+- `CONTRIBUTING.md` — engineering conventions. Every ticket follows them.
+- `src/app.js` exports `createApp()` returning an `http.Server` that is not yet
+ listening; `node src/index.js ` starts the service.
+- Links persist to the JSON file named by the `DATA_FILE` environment variable
+ (default `./data/links.json`).
+- `GET /links//stats` returns `{ "code", "hits", "expiresAt" }` —
+ `hits` counts redirects.
+- The API is rate limited per client and validates URLs (http/https only).
+- Run the tests with `npm test`.
diff --git a/docker/context-profiles/complex-eval/reference3/chained-tickets/src/app.js b/docker/context-profiles/complex-eval/reference3/chained-tickets/src/app.js
new file mode 100644
index 000000000..c802a64fd
--- /dev/null
+++ b/docker/context-profiles/complex-eval/reference3/chained-tickets/src/app.js
@@ -0,0 +1,15 @@
+'use strict';
+const http = require('node:http');
+const path = require('node:path');
+const { createStore } = require('./store');
+const { createService } = require('./service');
+const { createRouter } = require('./routes');
+
+function createApp() {
+ const file = process.env.DATA_FILE || path.join(process.cwd(), 'data', 'links.json');
+ const store = createStore(file);
+ const service = createService(store);
+ return http.createServer(createRouter(service));
+}
+
+module.exports = { createApp };
diff --git a/docker/context-profiles/complex-eval/reference3/chained-tickets/src/index.js b/docker/context-profiles/complex-eval/reference3/chained-tickets/src/index.js
new file mode 100644
index 000000000..d37872b76
--- /dev/null
+++ b/docker/context-profiles/complex-eval/reference3/chained-tickets/src/index.js
@@ -0,0 +1,7 @@
+'use strict';
+const { createApp } = require('./app');
+
+const port = Number(process.env.PORT || process.argv[2] || 8080);
+createApp().listen(port, () => {
+ console.log(`shortlink listening on ${port}`);
+});
diff --git a/docker/context-profiles/complex-eval/reference3/chained-tickets/src/routes.js b/docker/context-profiles/complex-eval/reference3/chained-tickets/src/routes.js
new file mode 100644
index 000000000..7344146c6
--- /dev/null
+++ b/docker/context-profiles/complex-eval/reference3/chained-tickets/src/routes.js
@@ -0,0 +1,86 @@
+'use strict';
+const { HttpError } = require('./service');
+
+const MAX_BODY_BYTES = 64 * 1024;
+
+function sendJson(res, status, value) {
+ res.writeHead(status, { 'content-type': 'application/json' });
+ res.end(JSON.stringify(value));
+}
+
+function sendError(res, error) {
+ const known = error instanceof HttpError;
+ sendJson(res, known ? error.status : 500, {
+ error: { code: known ? error.code : 'INTERNAL', message: known ? error.message : 'internal error' },
+ });
+}
+
+function readBody(req) {
+ return new Promise((resolve, reject) => {
+ let body = '';
+ let bytes = 0;
+ let settled = false;
+ req.on('data', chunk => {
+ if (settled) return;
+ bytes += chunk.length;
+ if (bytes > MAX_BODY_BYTES) {
+ settled = true;
+ reject(new HttpError(413, 'PAYLOAD_TOO_LARGE', 'request body too large'));
+ // Drain rather than destroy: the socket must live long enough to send the 413.
+ req.resume();
+ return;
+ }
+ body += chunk;
+ });
+ req.on('end', () => {
+ if (settled) return;
+ settled = true;
+ if (!body) { resolve({}); return; }
+ try { resolve(JSON.parse(body)); } catch { reject(new HttpError(400, 'INVALID_JSON', 'body must be valid JSON')); }
+ });
+ req.on('error', reject);
+ });
+}
+
+function createRouter(service) {
+ return async (req, res) => {
+ try {
+ const url = new URL(req.url, 'http://localhost');
+
+ if (req.method === 'POST' && url.pathname === '/links') {
+ service.assertRateLimit(req.socket.remoteAddress || 'unknown');
+ const link = service.createLink(await readBody(req));
+ sendJson(res, 201, { code: link.code, shortUrl: `/${link.code}`, expiresAt: link.expiresAt });
+ return;
+ }
+
+ const statsMatch = /^\/links\/([A-Za-z0-9]{1,20})\/stats$/.exec(url.pathname);
+ if (req.method === 'GET' && statsMatch) {
+ sendJson(res, 200, service.stats(statsMatch[1]));
+ return;
+ }
+
+ const linkMatch = /^\/links\/([A-Za-z0-9]{1,20})$/.exec(url.pathname);
+ if (req.method === 'DELETE' && linkMatch) {
+ service.deleteLink(linkMatch[1]);
+ res.writeHead(204);
+ res.end();
+ return;
+ }
+
+ const redirectMatch = /^\/([A-Za-z0-9]{1,20})$/.exec(url.pathname);
+ if (req.method === 'GET' && redirectMatch) {
+ const link = service.resolveLink(redirectMatch[1]);
+ res.writeHead(302, { location: link.url });
+ res.end();
+ return;
+ }
+
+ throw new HttpError(404, 'NOT_FOUND', 'not found');
+ } catch (error) {
+ sendError(res, error);
+ }
+ };
+}
+
+module.exports = { createRouter };
diff --git a/docker/context-profiles/complex-eval/reference3/chained-tickets/src/service.js b/docker/context-profiles/complex-eval/reference3/chained-tickets/src/service.js
new file mode 100644
index 000000000..f28167d8a
--- /dev/null
+++ b/docker/context-profiles/complex-eval/reference3/chained-tickets/src/service.js
@@ -0,0 +1,82 @@
+'use strict';
+const crypto = require('node:crypto');
+
+const MAX_URL_LENGTH = 2048;
+const DEFAULT_TTL_SECONDS = 604800;
+const MAX_TTL_SECONDS = 2592000;
+const RATE_LIMIT_WINDOW_MS = 60000;
+const RATE_LIMIT_MAX = 20;
+
+class HttpError extends Error {
+ constructor(status, code, message) {
+ super(message);
+ this.status = status;
+ this.code = code;
+ }
+}
+
+function validateUrl(url) {
+ if (typeof url !== 'string' || !url) throw new HttpError(400, 'INVALID_URL', 'url is required');
+ if (url.length > MAX_URL_LENGTH) throw new HttpError(400, 'INVALID_URL', 'url exceeds 2048 characters');
+ let parsed;
+ try { parsed = new URL(url); } catch { throw new HttpError(400, 'INVALID_URL', 'url must be a valid absolute URL'); }
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
+ throw new HttpError(400, 'INVALID_URL', 'only http and https URLs are allowed');
+ }
+ return url;
+}
+
+function validateTtl(ttlSeconds) {
+ if (ttlSeconds === undefined || ttlSeconds === null) return DEFAULT_TTL_SECONDS;
+ if (!Number.isInteger(ttlSeconds) || ttlSeconds < 1 || ttlSeconds > MAX_TTL_SECONDS) {
+ throw new HttpError(400, 'INVALID_TTL', 'ttlSeconds must be an integer between 1 and 2592000');
+ }
+ return ttlSeconds;
+}
+
+function createService(store) {
+ const buckets = new Map();
+
+ function assertRateLimit(key) {
+ const now = Date.now();
+ const windowHits = (buckets.get(key) || []).filter(at => now - at < RATE_LIMIT_WINDOW_MS);
+ if (windowHits.length >= RATE_LIMIT_MAX) throw new HttpError(429, 'RATE_LIMITED', 'too many requests, slow down');
+ windowHits.push(now);
+ buckets.set(key, windowHits);
+ }
+
+ function freshCode() {
+ let code = crypto.randomBytes(4).toString('hex');
+ while (store.get(code)) code = crypto.randomBytes(4).toString('hex');
+ return code;
+ }
+
+ return {
+ assertRateLimit,
+ createLink({ url, ttlSeconds } = {}) {
+ const validUrl = validateUrl(url);
+ const ttl = validateTtl(ttlSeconds);
+ const link = { code: freshCode(), url: validUrl,
+ expiresAt: new Date(Date.now() + ttl * 1000).toISOString(), hits: 0 };
+ store.set(link.code, link);
+ return link;
+ },
+ resolveLink(code) {
+ const link = store.get(code);
+ if (!link) throw new HttpError(404, 'NOT_FOUND', 'no link with that code');
+ if (Date.parse(link.expiresAt) <= Date.now()) throw new HttpError(410, 'GONE', 'link has expired');
+ store.incrementHits(code);
+ return link;
+ },
+ deleteLink(code) {
+ if (!store.delete(code)) throw new HttpError(404, 'NOT_FOUND', 'no link with that code');
+ },
+ stats(code) {
+ const link = store.get(code);
+ if (!link) throw new HttpError(404, 'NOT_FOUND', 'no link with that code');
+ return { code, hits: link.hits || 0, expiresAt: link.expiresAt };
+ },
+ };
+}
+
+module.exports = { createService, HttpError };
diff --git a/docker/context-profiles/complex-eval/reference3/chained-tickets/src/store.js b/docker/context-profiles/complex-eval/reference3/chained-tickets/src/store.js
new file mode 100644
index 000000000..7d5aa091b
--- /dev/null
+++ b/docker/context-profiles/complex-eval/reference3/chained-tickets/src/store.js
@@ -0,0 +1,28 @@
+'use strict';
+const fs = require('node:fs');
+const path = require('node:path');
+
+// JSON-file-backed link store. Missing or corrupt files start clean; every
+// mutation is flushed synchronously so a restart never loses a committed link.
+function createStore(file) {
+ let links = new Map();
+ try {
+ const raw = JSON.parse(fs.readFileSync(file, 'utf8'));
+ for (const [code, value] of Object.entries(raw.links || {})) links.set(code, value);
+ } catch { /* missing or corrupt: start empty */ }
+ const save = () => {
+ fs.mkdirSync(path.dirname(file), { recursive: true });
+ fs.writeFileSync(file, `${JSON.stringify({ links: Object.fromEntries(links) }, null, 1)}\n`);
+ };
+ return {
+ get: code => links.get(code) || null,
+ set(code, value) { links.set(code, value); save(); },
+ delete(code) { const had = links.delete(code); if (had) save(); return had; },
+ incrementHits(code) {
+ const link = links.get(code);
+ if (link) { link.hits = (link.hits || 0) + 1; save(); }
+ },
+ };
+}
+
+module.exports = { createStore };
diff --git a/docker/context-profiles/complex-eval/reference3/chained-tickets/test/links.test.js b/docker/context-profiles/complex-eval/reference3/chained-tickets/test/links.test.js
new file mode 100644
index 000000000..1a358d43d
--- /dev/null
+++ b/docker/context-profiles/complex-eval/reference3/chained-tickets/test/links.test.js
@@ -0,0 +1,106 @@
+'use strict';
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const { createApp } = require('../src/app');
+
+process.env.DATA_FILE = require('node:path').join(require('node:os').tmpdir(),
+ `shortlink-test-${process.pid}.json`);
+
+let server;
+let port;
+test.before(async () => {
+ server = createApp();
+ await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
+ port = server.address().port;
+});
+test.after(() => server.close());
+
+const post = body => fetch(`http://127.0.0.1:${port}/links`, {
+ method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });
+const get = p => fetch(`http://127.0.0.1:${port}${p}`, { redirect: 'manual' });
+
+test('creates a link with default expiry', async () => {
+ const res = await post({ url: 'https://example.com/a' });
+ assert.equal(res.status, 201);
+ const body = await res.json();
+ assert.match(body.code, /^[A-Za-z0-9]{6,10}$/);
+ assert.ok(Date.parse(body.expiresAt) > Date.now());
+});
+
+test('redirects with 302 and location', async () => {
+ const { code } = await (await post({ url: 'https://example.com/b' })).json();
+ const res = await get(`/${code}`);
+ assert.equal(res.status, 302);
+ assert.equal(res.headers.get('location'), 'https://example.com/b');
+});
+
+test('unknown code is a 404 envelope', async () => {
+ const res = await get('/zzzzzz');
+ assert.equal(res.status, 404);
+ assert.equal((await res.json()).error.code, 'NOT_FOUND');
+});
+
+test('invalid url is a 400 envelope', async () => {
+ const res = await post({ url: 'notaurl' });
+ assert.equal(res.status, 400);
+ assert.equal((await res.json()).error.code, 'INVALID_URL');
+});
+
+test('javascript scheme rejected', async () => {
+ const res = await post({ url: 'javascript:alert(1)' });
+ assert.equal(res.status, 400);
+});
+
+test('ttl bounds enforced', async () => {
+ const res = await post({ url: 'https://example.com', ttlSeconds: 99999999 });
+ assert.equal(res.status, 400);
+ assert.equal((await res.json()).error.code, 'INVALID_TTL');
+});
+
+test('delete flow', async () => {
+ const { code } = await (await post({ url: 'https://example.com/c' })).json();
+ const del = await fetch(`http://127.0.0.1:${port}/links/${code}`, { method: 'DELETE' });
+ assert.equal(del.status, 204);
+ assert.equal((await get(`/${code}`)).status, 404);
+});
+
+test('stats start at zero and count redirects', async () => {
+ const { code } = await (await post({ url: 'https://example.com/d' })).json();
+ const zero = await (await fetch(`http://127.0.0.1:${port}/links/${code}/stats`)).json();
+ assert.equal(zero.hits, 0);
+ await get(`/${code}`);
+ await get(`/${code}`);
+ const two = await (await fetch(`http://127.0.0.1:${port}/links/${code}/stats`)).json();
+ assert.equal(two.hits, 2);
+});
+
+test('stats for unknown code are a 404 envelope', async () => {
+ const res = await fetch(`http://127.0.0.1:${port}/links/zzzzzz/stats`);
+ assert.equal(res.status, 404);
+ assert.equal((await res.json()).error.code, 'NOT_FOUND');
+});
+
+test('expired links are 410', async () => {
+ const { code } = await (await post({ url: 'https://example.com/e', ttlSeconds: 1 })).json();
+ await new Promise(resolve => setTimeout(resolve, 1200));
+ assert.equal((await get(`/${code}`)).status, 410);
+});
+
+test('malformed json is a 400 envelope', async () => {
+ const res = await fetch(`http://127.0.0.1:${port}/links`, {
+ method: 'POST', headers: { 'content-type': 'application/json' }, body: '{nope' });
+ assert.equal(res.status, 400);
+ assert.equal((await res.json()).error.code, 'INVALID_JSON');
+});
+
+test('error responses never leak html', async () => {
+ const res = await get('/zzzzzz');
+ assert.match(res.headers.get('content-type'), /application\/json/);
+});
+
+// Last: the flood exhausts the per-client rate-limit bucket.
+test('rate limiting kicks in under a flood', async () => {
+ const responses = await Promise.all(Array.from({ length: 30 }, (_, i) =>
+ post({ url: `https://example.com/flood-${i}` })));
+ assert.ok(responses.some(r => r.status === 429));
+});
diff --git a/docker/context-profiles/complex-eval/reference3/idempotent-webhooks/CHANGELOG.md b/docker/context-profiles/complex-eval/reference3/idempotent-webhooks/CHANGELOG.md
new file mode 100644
index 000000000..e0560c4a5
--- /dev/null
+++ b/docker/context-profiles/complex-eval/reference3/idempotent-webhooks/CHANGELOG.md
@@ -0,0 +1,6 @@
+# Changelog
+
+- 2026-09-25: Fixed INC-104 — the receiver now claims each event id and applies
+ the payment synchronously in one event-loop turn, so concurrent duplicate
+ deliveries can never both pass the seen-check. Added idempotency regression
+ tests for concurrent duplicates, retries, and already-paid orders.
diff --git a/docker/context-profiles/complex-eval/reference3/idempotent-webhooks/src/app.js b/docker/context-profiles/complex-eval/reference3/idempotent-webhooks/src/app.js
new file mode 100644
index 000000000..57f29c250
--- /dev/null
+++ b/docker/context-profiles/complex-eval/reference3/idempotent-webhooks/src/app.js
@@ -0,0 +1,87 @@
+'use strict';
+const http = require('node:http');
+const { store } = require('./store');
+
+// Fixed after INC-104: all state checks and mutations happen synchronously in
+// one turn of the event loop — an event is claimed the instant its body is
+// parsed, before any await, so concurrent duplicates can never both pass.
+class HttpError extends Error {
+ constructor(status, code, message) {
+ super(message);
+ this.status = status;
+ this.code = code;
+ }
+}
+
+function sendJson(res, status, value) {
+ res.writeHead(status, { 'content-type': 'application/json' });
+ res.end(JSON.stringify(value));
+}
+
+function sendError(res, error) {
+ const known = error instanceof HttpError;
+ sendJson(res, known ? error.status : 500, {
+ error: { code: known ? error.code : 'INTERNAL', message: known ? error.message : 'internal error' },
+ });
+}
+
+function readBody(req) {
+ return new Promise((resolve, reject) => {
+ let body = '';
+ req.on('data', chunk => { body += chunk; });
+ req.on('end', () => {
+ try { resolve(JSON.parse(body)); } catch { reject(new HttpError(400, 'INVALID_JSON', 'body must be valid JSON')); }
+ });
+ req.on('error', reject);
+ });
+}
+
+function validateEvent(parsed) {
+ if (!parsed || typeof parsed.eventId !== 'string' || !parsed.eventId
+ || typeof parsed.orderId !== 'string' || !parsed.orderId
+ || !Number.isInteger(parsed.amountCents) || parsed.amountCents <= 0
+ || parsed.type !== 'payment.succeeded') {
+ throw new HttpError(400, 'INVALID_EVENT', 'body must be a valid payment.succeeded event');
+ }
+ return parsed;
+}
+
+// Synchronous claim-and-apply: no awaits inside, so it is atomic.
+function applyEvent({ eventId, orderId, amountCents }) {
+ if (store.processedEvents.has(eventId)) return { status: 'duplicate', orderId };
+ const order = store.orders.get(orderId);
+ if (!order) throw new HttpError(404, 'NOT_FOUND', 'no such order');
+ if (order.amountCents !== amountCents) throw new HttpError(422, 'AMOUNT_MISMATCH', 'amountCents does not match the order');
+ if (order.status === 'paid') return { status: 'already_paid', orderId };
+ store.processedEvents.add(eventId);
+ order.status = 'paid';
+ order.paidAt = new Date().toISOString();
+ order.paymentsApplied++;
+ store.paymentLog.push({ eventId, orderId, amountCents });
+ return { status: 'processed', orderId };
+}
+
+function createApp() {
+ return http.createServer(async (req, res) => {
+ const url = new URL(req.url, 'http://localhost');
+ try {
+ if (req.method === 'POST' && url.pathname === '/webhooks/payments') {
+ const parsed = validateEvent(await readBody(req));
+ sendJson(res, 200, applyEvent(parsed));
+ return;
+ }
+ const match = /^\/orders\/([\w-]+)$/.exec(url.pathname);
+ if (req.method === 'GET' && match) {
+ const order = store.orders.get(match[1]);
+ if (!order) throw new HttpError(404, 'NOT_FOUND', 'no such order');
+ sendJson(res, 200, order);
+ return;
+ }
+ throw new HttpError(404, 'NOT_FOUND', 'not found');
+ } catch (error) {
+ sendError(res, error);
+ }
+ });
+}
+
+module.exports = { createApp };
diff --git a/docker/context-profiles/complex-eval/reference3/idempotent-webhooks/test/webhooks.test.js b/docker/context-profiles/complex-eval/reference3/idempotent-webhooks/test/webhooks.test.js
new file mode 100644
index 000000000..cdd102f49
--- /dev/null
+++ b/docker/context-profiles/complex-eval/reference3/idempotent-webhooks/test/webhooks.test.js
@@ -0,0 +1,60 @@
+'use strict';
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const { createApp } = require('../src/app');
+const { store } = require('../src/store');
+
+let server;
+let port;
+test.before(async () => {
+ server = createApp();
+ await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
+ port = server.address().port;
+});
+test.after(() => server.close());
+
+const send = (eventId, orderId, amountCents) => fetch(`http://127.0.0.1:${port}/webhooks/payments`, {
+ method: 'POST', headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ eventId, orderId, amountCents, type: 'payment.succeeded' }) });
+
+test('a single payment event processes', async () => {
+ const res = await send('ev-t-1', 'o1', 5000);
+ assert.equal(res.status, 200);
+ assert.equal((await res.json()).status, 'processed');
+ assert.equal(store.orders.get('o1').status, 'paid');
+});
+
+test('a sequential retry is an inert duplicate', async () => {
+ await send('ev-t-2', 'o3', 800);
+ const before = store.paymentLog.filter(p => p.orderId === 'o3').length;
+ const res = await send('ev-t-2', 'o3', 800);
+ assert.equal((await res.json()).status, 'duplicate');
+ assert.equal(store.paymentLog.filter(p => p.orderId === 'o3').length, before);
+});
+
+test('fifty concurrent duplicates apply exactly once (INC-104 regression)', async () => {
+ const storm = await Promise.all(Array.from({ length: 50 }, () => send('ev-t-storm', 'o4', 9999)));
+ const bodies = [];
+ for (const r of storm) bodies.push(await r.json());
+ assert.equal(bodies.filter(b => b.status === 'processed').length, 1);
+ assert.equal(bodies.filter(b => b.status === 'duplicate').length, 49);
+ assert.equal(store.orders.get('o4').paymentsApplied, 1);
+});
+
+test('a second event for a paid order is already_paid', async () => {
+ const res = await send('ev-t-3', 'o4', 9999);
+ assert.equal((await res.json()).status, 'already_paid');
+ assert.equal(store.orders.get('o4').paymentsApplied, 1);
+});
+
+test('amount mismatch is 422 and inert', async () => {
+ const res = await send('ev-t-4', 'o5', 1);
+ assert.equal(res.status, 422);
+ assert.equal(store.orders.get('o5').status, 'pending');
+});
+
+test('unknown order is a 404 envelope', async () => {
+ const res = await send('ev-t-5', 'nope', 100);
+ assert.equal(res.status, 404);
+ assert.equal((await res.json()).error.code, 'NOT_FOUND');
+});
diff --git a/docker/context-profiles/complex-eval/reference3/production-ready/CHANGELOG.md b/docker/context-profiles/complex-eval/reference3/production-ready/CHANGELOG.md
new file mode 100644
index 000000000..e0b0f3c6a
--- /dev/null
+++ b/docker/context-profiles/complex-eval/reference3/production-ready/CHANGELOG.md
@@ -0,0 +1,6 @@
+# Changelog
+
+- 2026-09-25: Production hardening — request validation with structured JSON
+ error envelopes, 64 KB body limit with 413, /health endpoint, structured
+ JSON request logging, PORT from the environment, graceful SIGTERM shutdown,
+ nosniff headers, and error-path test coverage.
diff --git a/docker/context-profiles/complex-eval/reference3/production-ready/src/app.js b/docker/context-profiles/complex-eval/reference3/production-ready/src/app.js
new file mode 100644
index 000000000..ccdecd16e
--- /dev/null
+++ b/docker/context-profiles/complex-eval/reference3/production-ready/src/app.js
@@ -0,0 +1,100 @@
+'use strict';
+const http = require('node:http');
+
+const MAX_BODY_BYTES = Number(process.env.MAX_BODY_BYTES || 64 * 1024);
+
+class HttpError extends Error {
+ constructor(status, code, message) {
+ super(message);
+ this.status = status;
+ this.code = code;
+ }
+}
+
+function sendJson(res, status, value) {
+ res.writeHead(status, { 'content-type': 'application/json', 'x-content-type-options': 'nosniff' });
+ res.end(JSON.stringify(value));
+}
+
+function sendError(res, error) {
+ const known = error instanceof HttpError;
+ sendJson(res, known ? error.status : 500, {
+ error: { code: known ? error.code : 'INTERNAL', message: known ? error.message : 'internal error' },
+ });
+}
+
+function readBody(req) {
+ return new Promise((resolve, reject) => {
+ let body = '';
+ let bytes = 0;
+ let settled = false;
+ req.on('data', chunk => {
+ if (settled) return;
+ bytes += chunk.length;
+ if (bytes > MAX_BODY_BYTES) {
+ settled = true;
+ reject(new HttpError(413, 'PAYLOAD_TOO_LARGE', 'request body exceeds 64 KB'));
+ // Drain rather than destroy: the socket must live long enough to send the 413.
+ req.resume();
+ return;
+ }
+ body += chunk;
+ });
+ req.on('end', () => {
+ if (settled) return;
+ settled = true;
+ try { resolve(JSON.parse(body)); } catch { reject(new HttpError(400, 'INVALID_JSON', 'body must be valid JSON')); }
+ });
+ req.on('error', reject);
+ });
+}
+
+function validateNote(input) {
+ if (!input || typeof input.title !== 'string' || !input.title.trim()) {
+ throw new HttpError(400, 'INVALID_TITLE', 'title must be a non-empty string');
+ }
+ if (typeof input.body !== 'string') throw new HttpError(400, 'INVALID_BODY', 'body must be a string');
+ return { title: input.title, body: input.body };
+}
+
+function createApp() {
+ const notes = new Map();
+ let nextId = 1;
+
+ const server = http.createServer(async (req, res) => {
+ const url = new URL(req.url, 'http://localhost');
+ try {
+ if (req.method === 'GET' && url.pathname === '/health') {
+ sendJson(res, 200, { status: 'ok' });
+ return;
+ }
+ if (req.method === 'POST' && url.pathname === '/notes') {
+ const fields = validateNote(await readBody(req));
+ const id = `n_${nextId++}`;
+ notes.set(id, { id, ...fields });
+ sendJson(res, 201, notes.get(id));
+ return;
+ }
+ const match = /^\/notes\/([\w-]+)$/.exec(url.pathname);
+ if (req.method === 'GET' && match) {
+ const note = notes.get(match[1]);
+ if (!note) throw new HttpError(404, 'NOT_FOUND', 'no note with that id');
+ sendJson(res, 200, note);
+ return;
+ }
+ if (req.method === 'GET' && url.pathname === '/notes') {
+ sendJson(res, 200, { notes: [...notes.values()] });
+ return;
+ }
+ throw new HttpError(404, 'NOT_FOUND', 'not found');
+ } catch (error) {
+ sendError(res, error);
+ } finally {
+ console.log(JSON.stringify({ method: req.method, path: url.pathname,
+ status: res.statusCode, at: new Date().toISOString() }));
+ }
+ });
+ return server;
+}
+
+module.exports = { createApp };
diff --git a/docker/context-profiles/complex-eval/reference3/production-ready/src/index.js b/docker/context-profiles/complex-eval/reference3/production-ready/src/index.js
new file mode 100644
index 000000000..9b1d0a0d7
--- /dev/null
+++ b/docker/context-profiles/complex-eval/reference3/production-ready/src/index.js
@@ -0,0 +1,13 @@
+'use strict';
+const { createApp } = require('./app');
+
+const port = Number(process.env.PORT || 8080);
+const server = createApp();
+server.listen(port, () => {
+ console.log(JSON.stringify({ event: 'listening', port }));
+});
+
+process.on('SIGTERM', () => {
+ server.close(() => process.exit(0));
+ setTimeout(() => process.exit(1), 5000).unref();
+});
diff --git a/docker/context-profiles/complex-eval/reference3/production-ready/test/notes.test.js b/docker/context-profiles/complex-eval/reference3/production-ready/test/notes.test.js
new file mode 100644
index 000000000..65e4ca200
--- /dev/null
+++ b/docker/context-profiles/complex-eval/reference3/production-ready/test/notes.test.js
@@ -0,0 +1,58 @@
+'use strict';
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const { createApp } = require('../src/app');
+
+let server;
+let port;
+test.before(async () => {
+ server = createApp();
+ await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
+ port = server.address().port;
+});
+test.after(() => server.close());
+
+const post = body => fetch(`http://127.0.0.1:${port}/notes`, {
+ method: 'POST', headers: { 'content-type': 'application/json' }, body });
+
+test('create and read a note', async () => {
+ const created = await post(JSON.stringify({ title: 'first', body: 'hello' }));
+ assert.equal(created.status, 201);
+ const { id } = await created.json();
+ const read = await fetch(`http://127.0.0.1:${port}/notes/${id}`);
+ assert.equal((await read.json()).title, 'first');
+});
+
+test('malformed json is a 400 envelope', async () => {
+ const res = await post('{oops');
+ assert.equal(res.status, 400);
+ assert.equal((await res.json()).error.code, 'INVALID_JSON');
+});
+
+test('missing title is a 400 envelope', async () => {
+ const res = await post(JSON.stringify({ body: 'x' }));
+ assert.equal(res.status, 400);
+ assert.equal((await res.json()).error.code, 'INVALID_TITLE');
+});
+
+test('unknown note is a 404 envelope', async () => {
+ const res = await fetch(`http://127.0.0.1:${port}/notes/n_9999`);
+ assert.equal(res.status, 404);
+ assert.equal((await res.json()).error.code, 'NOT_FOUND');
+});
+
+test('oversize body is a 413 envelope', async () => {
+ const res = await post(JSON.stringify({ title: 'x', body: 'y'.repeat(100 * 1024) }));
+ assert.equal(res.status, 413);
+});
+
+test('health endpoint', async () => {
+ const res = await fetch(`http://127.0.0.1:${port}/health`);
+ assert.equal(res.status, 200);
+ assert.equal((await res.json()).status, 'ok');
+});
+
+test('nosniff header present', async () => {
+ const res = await fetch(`http://127.0.0.1:${port}/notes`);
+ assert.equal(res.headers.get('x-content-type-options'), 'nosniff');
+});
diff --git a/docker/context-profiles/complex-eval/reference4/chained-tickets/CHANGELOG.md b/docker/context-profiles/complex-eval/reference4/chained-tickets/CHANGELOG.md
new file mode 100644
index 000000000..e8cad2f0c
--- /dev/null
+++ b/docker/context-profiles/complex-eval/reference4/chained-tickets/CHANGELOG.md
@@ -0,0 +1,6 @@
+# Changelog
+
+- 2026-09-25: Initial shortlink core — create, redirect, expiry, and delete per API.md.
+- 2026-09-25: Persistence — links survive restarts via the DATA_FILE JSON store; missing or corrupt data files start clean.
+- 2026-09-25: Abuse protection — URL validation (http/https only, length cap), request body limits, and per-client rate limiting with 429 responses.
+- 2026-09-25: Analytics — per-link redirect hit counts exposed at GET /links/:code/stats.
diff --git a/docker/context-profiles/complex-eval/reference4/chained-tickets/README.md b/docker/context-profiles/complex-eval/reference4/chained-tickets/README.md
new file mode 100644
index 000000000..3420482fe
--- /dev/null
+++ b/docker/context-profiles/complex-eval/reference4/chained-tickets/README.md
@@ -0,0 +1,14 @@
+# shortlink
+
+Internal link shortener service. Node.js standard library only, CommonJS.
+
+- `API.md` — the HTTP contract.
+- `CONTRIBUTING.md` — engineering conventions. Every ticket follows them.
+- `src/app.js` exports `createApp()` returning an `http.Server` that is not yet
+ listening; `node src/index.js ` starts the service.
+- Links persist to the JSON file named by the `DATA_FILE` environment variable
+ (default `./data/links.json`).
+- `GET /links//stats` returns `{ "code", "hits", "expiresAt" }` —
+ `hits` counts redirects.
+- The API is rate limited per client and validates URLs (http/https only).
+- Run the tests with `npm test`.
diff --git a/docker/context-profiles/complex-eval/reference4/chained-tickets/src/app.js b/docker/context-profiles/complex-eval/reference4/chained-tickets/src/app.js
new file mode 100644
index 000000000..c802a64fd
--- /dev/null
+++ b/docker/context-profiles/complex-eval/reference4/chained-tickets/src/app.js
@@ -0,0 +1,15 @@
+'use strict';
+const http = require('node:http');
+const path = require('node:path');
+const { createStore } = require('./store');
+const { createService } = require('./service');
+const { createRouter } = require('./routes');
+
+function createApp() {
+ const file = process.env.DATA_FILE || path.join(process.cwd(), 'data', 'links.json');
+ const store = createStore(file);
+ const service = createService(store);
+ return http.createServer(createRouter(service));
+}
+
+module.exports = { createApp };
diff --git a/docker/context-profiles/complex-eval/reference4/chained-tickets/src/index.js b/docker/context-profiles/complex-eval/reference4/chained-tickets/src/index.js
new file mode 100644
index 000000000..d37872b76
--- /dev/null
+++ b/docker/context-profiles/complex-eval/reference4/chained-tickets/src/index.js
@@ -0,0 +1,7 @@
+'use strict';
+const { createApp } = require('./app');
+
+const port = Number(process.env.PORT || process.argv[2] || 8080);
+createApp().listen(port, () => {
+ console.log(`shortlink listening on ${port}`);
+});
diff --git a/docker/context-profiles/complex-eval/reference4/chained-tickets/src/routes.js b/docker/context-profiles/complex-eval/reference4/chained-tickets/src/routes.js
new file mode 100644
index 000000000..7344146c6
--- /dev/null
+++ b/docker/context-profiles/complex-eval/reference4/chained-tickets/src/routes.js
@@ -0,0 +1,86 @@
+'use strict';
+const { HttpError } = require('./service');
+
+const MAX_BODY_BYTES = 64 * 1024;
+
+function sendJson(res, status, value) {
+ res.writeHead(status, { 'content-type': 'application/json' });
+ res.end(JSON.stringify(value));
+}
+
+function sendError(res, error) {
+ const known = error instanceof HttpError;
+ sendJson(res, known ? error.status : 500, {
+ error: { code: known ? error.code : 'INTERNAL', message: known ? error.message : 'internal error' },
+ });
+}
+
+function readBody(req) {
+ return new Promise((resolve, reject) => {
+ let body = '';
+ let bytes = 0;
+ let settled = false;
+ req.on('data', chunk => {
+ if (settled) return;
+ bytes += chunk.length;
+ if (bytes > MAX_BODY_BYTES) {
+ settled = true;
+ reject(new HttpError(413, 'PAYLOAD_TOO_LARGE', 'request body too large'));
+ // Drain rather than destroy: the socket must live long enough to send the 413.
+ req.resume();
+ return;
+ }
+ body += chunk;
+ });
+ req.on('end', () => {
+ if (settled) return;
+ settled = true;
+ if (!body) { resolve({}); return; }
+ try { resolve(JSON.parse(body)); } catch { reject(new HttpError(400, 'INVALID_JSON', 'body must be valid JSON')); }
+ });
+ req.on('error', reject);
+ });
+}
+
+function createRouter(service) {
+ return async (req, res) => {
+ try {
+ const url = new URL(req.url, 'http://localhost');
+
+ if (req.method === 'POST' && url.pathname === '/links') {
+ service.assertRateLimit(req.socket.remoteAddress || 'unknown');
+ const link = service.createLink(await readBody(req));
+ sendJson(res, 201, { code: link.code, shortUrl: `/${link.code}`, expiresAt: link.expiresAt });
+ return;
+ }
+
+ const statsMatch = /^\/links\/([A-Za-z0-9]{1,20})\/stats$/.exec(url.pathname);
+ if (req.method === 'GET' && statsMatch) {
+ sendJson(res, 200, service.stats(statsMatch[1]));
+ return;
+ }
+
+ const linkMatch = /^\/links\/([A-Za-z0-9]{1,20})$/.exec(url.pathname);
+ if (req.method === 'DELETE' && linkMatch) {
+ service.deleteLink(linkMatch[1]);
+ res.writeHead(204);
+ res.end();
+ return;
+ }
+
+ const redirectMatch = /^\/([A-Za-z0-9]{1,20})$/.exec(url.pathname);
+ if (req.method === 'GET' && redirectMatch) {
+ const link = service.resolveLink(redirectMatch[1]);
+ res.writeHead(302, { location: link.url });
+ res.end();
+ return;
+ }
+
+ throw new HttpError(404, 'NOT_FOUND', 'not found');
+ } catch (error) {
+ sendError(res, error);
+ }
+ };
+}
+
+module.exports = { createRouter };
diff --git a/docker/context-profiles/complex-eval/reference4/chained-tickets/src/service.js b/docker/context-profiles/complex-eval/reference4/chained-tickets/src/service.js
new file mode 100644
index 000000000..f28167d8a
--- /dev/null
+++ b/docker/context-profiles/complex-eval/reference4/chained-tickets/src/service.js
@@ -0,0 +1,82 @@
+'use strict';
+const crypto = require('node:crypto');
+
+const MAX_URL_LENGTH = 2048;
+const DEFAULT_TTL_SECONDS = 604800;
+const MAX_TTL_SECONDS = 2592000;
+const RATE_LIMIT_WINDOW_MS = 60000;
+const RATE_LIMIT_MAX = 20;
+
+class HttpError extends Error {
+ constructor(status, code, message) {
+ super(message);
+ this.status = status;
+ this.code = code;
+ }
+}
+
+function validateUrl(url) {
+ if (typeof url !== 'string' || !url) throw new HttpError(400, 'INVALID_URL', 'url is required');
+ if (url.length > MAX_URL_LENGTH) throw new HttpError(400, 'INVALID_URL', 'url exceeds 2048 characters');
+ let parsed;
+ try { parsed = new URL(url); } catch { throw new HttpError(400, 'INVALID_URL', 'url must be a valid absolute URL'); }
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
+ throw new HttpError(400, 'INVALID_URL', 'only http and https URLs are allowed');
+ }
+ return url;
+}
+
+function validateTtl(ttlSeconds) {
+ if (ttlSeconds === undefined || ttlSeconds === null) return DEFAULT_TTL_SECONDS;
+ if (!Number.isInteger(ttlSeconds) || ttlSeconds < 1 || ttlSeconds > MAX_TTL_SECONDS) {
+ throw new HttpError(400, 'INVALID_TTL', 'ttlSeconds must be an integer between 1 and 2592000');
+ }
+ return ttlSeconds;
+}
+
+function createService(store) {
+ const buckets = new Map();
+
+ function assertRateLimit(key) {
+ const now = Date.now();
+ const windowHits = (buckets.get(key) || []).filter(at => now - at < RATE_LIMIT_WINDOW_MS);
+ if (windowHits.length >= RATE_LIMIT_MAX) throw new HttpError(429, 'RATE_LIMITED', 'too many requests, slow down');
+ windowHits.push(now);
+ buckets.set(key, windowHits);
+ }
+
+ function freshCode() {
+ let code = crypto.randomBytes(4).toString('hex');
+ while (store.get(code)) code = crypto.randomBytes(4).toString('hex');
+ return code;
+ }
+
+ return {
+ assertRateLimit,
+ createLink({ url, ttlSeconds } = {}) {
+ const validUrl = validateUrl(url);
+ const ttl = validateTtl(ttlSeconds);
+ const link = { code: freshCode(), url: validUrl,
+ expiresAt: new Date(Date.now() + ttl * 1000).toISOString(), hits: 0 };
+ store.set(link.code, link);
+ return link;
+ },
+ resolveLink(code) {
+ const link = store.get(code);
+ if (!link) throw new HttpError(404, 'NOT_FOUND', 'no link with that code');
+ if (Date.parse(link.expiresAt) <= Date.now()) throw new HttpError(410, 'GONE', 'link has expired');
+ store.incrementHits(code);
+ return link;
+ },
+ deleteLink(code) {
+ if (!store.delete(code)) throw new HttpError(404, 'NOT_FOUND', 'no link with that code');
+ },
+ stats(code) {
+ const link = store.get(code);
+ if (!link) throw new HttpError(404, 'NOT_FOUND', 'no link with that code');
+ return { code, hits: link.hits || 0, expiresAt: link.expiresAt };
+ },
+ };
+}
+
+module.exports = { createService, HttpError };
diff --git a/docker/context-profiles/complex-eval/reference4/chained-tickets/src/store.js b/docker/context-profiles/complex-eval/reference4/chained-tickets/src/store.js
new file mode 100644
index 000000000..7d5aa091b
--- /dev/null
+++ b/docker/context-profiles/complex-eval/reference4/chained-tickets/src/store.js
@@ -0,0 +1,28 @@
+'use strict';
+const fs = require('node:fs');
+const path = require('node:path');
+
+// JSON-file-backed link store. Missing or corrupt files start clean; every
+// mutation is flushed synchronously so a restart never loses a committed link.
+function createStore(file) {
+ let links = new Map();
+ try {
+ const raw = JSON.parse(fs.readFileSync(file, 'utf8'));
+ for (const [code, value] of Object.entries(raw.links || {})) links.set(code, value);
+ } catch { /* missing or corrupt: start empty */ }
+ const save = () => {
+ fs.mkdirSync(path.dirname(file), { recursive: true });
+ fs.writeFileSync(file, `${JSON.stringify({ links: Object.fromEntries(links) }, null, 1)}\n`);
+ };
+ return {
+ get: code => links.get(code) || null,
+ set(code, value) { links.set(code, value); save(); },
+ delete(code) { const had = links.delete(code); if (had) save(); return had; },
+ incrementHits(code) {
+ const link = links.get(code);
+ if (link) { link.hits = (link.hits || 0) + 1; save(); }
+ },
+ };
+}
+
+module.exports = { createStore };
diff --git a/docker/context-profiles/complex-eval/reference4/chained-tickets/test/links.test.js b/docker/context-profiles/complex-eval/reference4/chained-tickets/test/links.test.js
new file mode 100644
index 000000000..1a358d43d
--- /dev/null
+++ b/docker/context-profiles/complex-eval/reference4/chained-tickets/test/links.test.js
@@ -0,0 +1,106 @@
+'use strict';
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const { createApp } = require('../src/app');
+
+process.env.DATA_FILE = require('node:path').join(require('node:os').tmpdir(),
+ `shortlink-test-${process.pid}.json`);
+
+let server;
+let port;
+test.before(async () => {
+ server = createApp();
+ await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
+ port = server.address().port;
+});
+test.after(() => server.close());
+
+const post = body => fetch(`http://127.0.0.1:${port}/links`, {
+ method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });
+const get = p => fetch(`http://127.0.0.1:${port}${p}`, { redirect: 'manual' });
+
+test('creates a link with default expiry', async () => {
+ const res = await post({ url: 'https://example.com/a' });
+ assert.equal(res.status, 201);
+ const body = await res.json();
+ assert.match(body.code, /^[A-Za-z0-9]{6,10}$/);
+ assert.ok(Date.parse(body.expiresAt) > Date.now());
+});
+
+test('redirects with 302 and location', async () => {
+ const { code } = await (await post({ url: 'https://example.com/b' })).json();
+ const res = await get(`/${code}`);
+ assert.equal(res.status, 302);
+ assert.equal(res.headers.get('location'), 'https://example.com/b');
+});
+
+test('unknown code is a 404 envelope', async () => {
+ const res = await get('/zzzzzz');
+ assert.equal(res.status, 404);
+ assert.equal((await res.json()).error.code, 'NOT_FOUND');
+});
+
+test('invalid url is a 400 envelope', async () => {
+ const res = await post({ url: 'notaurl' });
+ assert.equal(res.status, 400);
+ assert.equal((await res.json()).error.code, 'INVALID_URL');
+});
+
+test('javascript scheme rejected', async () => {
+ const res = await post({ url: 'javascript:alert(1)' });
+ assert.equal(res.status, 400);
+});
+
+test('ttl bounds enforced', async () => {
+ const res = await post({ url: 'https://example.com', ttlSeconds: 99999999 });
+ assert.equal(res.status, 400);
+ assert.equal((await res.json()).error.code, 'INVALID_TTL');
+});
+
+test('delete flow', async () => {
+ const { code } = await (await post({ url: 'https://example.com/c' })).json();
+ const del = await fetch(`http://127.0.0.1:${port}/links/${code}`, { method: 'DELETE' });
+ assert.equal(del.status, 204);
+ assert.equal((await get(`/${code}`)).status, 404);
+});
+
+test('stats start at zero and count redirects', async () => {
+ const { code } = await (await post({ url: 'https://example.com/d' })).json();
+ const zero = await (await fetch(`http://127.0.0.1:${port}/links/${code}/stats`)).json();
+ assert.equal(zero.hits, 0);
+ await get(`/${code}`);
+ await get(`/${code}`);
+ const two = await (await fetch(`http://127.0.0.1:${port}/links/${code}/stats`)).json();
+ assert.equal(two.hits, 2);
+});
+
+test('stats for unknown code are a 404 envelope', async () => {
+ const res = await fetch(`http://127.0.0.1:${port}/links/zzzzzz/stats`);
+ assert.equal(res.status, 404);
+ assert.equal((await res.json()).error.code, 'NOT_FOUND');
+});
+
+test('expired links are 410', async () => {
+ const { code } = await (await post({ url: 'https://example.com/e', ttlSeconds: 1 })).json();
+ await new Promise(resolve => setTimeout(resolve, 1200));
+ assert.equal((await get(`/${code}`)).status, 410);
+});
+
+test('malformed json is a 400 envelope', async () => {
+ const res = await fetch(`http://127.0.0.1:${port}/links`, {
+ method: 'POST', headers: { 'content-type': 'application/json' }, body: '{nope' });
+ assert.equal(res.status, 400);
+ assert.equal((await res.json()).error.code, 'INVALID_JSON');
+});
+
+test('error responses never leak html', async () => {
+ const res = await get('/zzzzzz');
+ assert.match(res.headers.get('content-type'), /application\/json/);
+});
+
+// Last: the flood exhausts the per-client rate-limit bucket.
+test('rate limiting kicks in under a flood', async () => {
+ const responses = await Promise.all(Array.from({ length: 30 }, (_, i) =>
+ post({ url: `https://example.com/flood-${i}` })));
+ assert.ok(responses.some(r => r.status === 429));
+});
diff --git a/docker/context-profiles/complex-eval/reference4/idempotent-webhooks/CHANGELOG.md b/docker/context-profiles/complex-eval/reference4/idempotent-webhooks/CHANGELOG.md
new file mode 100644
index 000000000..e0560c4a5
--- /dev/null
+++ b/docker/context-profiles/complex-eval/reference4/idempotent-webhooks/CHANGELOG.md
@@ -0,0 +1,6 @@
+# Changelog
+
+- 2026-09-25: Fixed INC-104 — the receiver now claims each event id and applies
+ the payment synchronously in one event-loop turn, so concurrent duplicate
+ deliveries can never both pass the seen-check. Added idempotency regression
+ tests for concurrent duplicates, retries, and already-paid orders.
diff --git a/docker/context-profiles/complex-eval/reference4/idempotent-webhooks/src/app.js b/docker/context-profiles/complex-eval/reference4/idempotent-webhooks/src/app.js
new file mode 100644
index 000000000..57f29c250
--- /dev/null
+++ b/docker/context-profiles/complex-eval/reference4/idempotent-webhooks/src/app.js
@@ -0,0 +1,87 @@
+'use strict';
+const http = require('node:http');
+const { store } = require('./store');
+
+// Fixed after INC-104: all state checks and mutations happen synchronously in
+// one turn of the event loop — an event is claimed the instant its body is
+// parsed, before any await, so concurrent duplicates can never both pass.
+class HttpError extends Error {
+ constructor(status, code, message) {
+ super(message);
+ this.status = status;
+ this.code = code;
+ }
+}
+
+function sendJson(res, status, value) {
+ res.writeHead(status, { 'content-type': 'application/json' });
+ res.end(JSON.stringify(value));
+}
+
+function sendError(res, error) {
+ const known = error instanceof HttpError;
+ sendJson(res, known ? error.status : 500, {
+ error: { code: known ? error.code : 'INTERNAL', message: known ? error.message : 'internal error' },
+ });
+}
+
+function readBody(req) {
+ return new Promise((resolve, reject) => {
+ let body = '';
+ req.on('data', chunk => { body += chunk; });
+ req.on('end', () => {
+ try { resolve(JSON.parse(body)); } catch { reject(new HttpError(400, 'INVALID_JSON', 'body must be valid JSON')); }
+ });
+ req.on('error', reject);
+ });
+}
+
+function validateEvent(parsed) {
+ if (!parsed || typeof parsed.eventId !== 'string' || !parsed.eventId
+ || typeof parsed.orderId !== 'string' || !parsed.orderId
+ || !Number.isInteger(parsed.amountCents) || parsed.amountCents <= 0
+ || parsed.type !== 'payment.succeeded') {
+ throw new HttpError(400, 'INVALID_EVENT', 'body must be a valid payment.succeeded event');
+ }
+ return parsed;
+}
+
+// Synchronous claim-and-apply: no awaits inside, so it is atomic.
+function applyEvent({ eventId, orderId, amountCents }) {
+ if (store.processedEvents.has(eventId)) return { status: 'duplicate', orderId };
+ const order = store.orders.get(orderId);
+ if (!order) throw new HttpError(404, 'NOT_FOUND', 'no such order');
+ if (order.amountCents !== amountCents) throw new HttpError(422, 'AMOUNT_MISMATCH', 'amountCents does not match the order');
+ if (order.status === 'paid') return { status: 'already_paid', orderId };
+ store.processedEvents.add(eventId);
+ order.status = 'paid';
+ order.paidAt = new Date().toISOString();
+ order.paymentsApplied++;
+ store.paymentLog.push({ eventId, orderId, amountCents });
+ return { status: 'processed', orderId };
+}
+
+function createApp() {
+ return http.createServer(async (req, res) => {
+ const url = new URL(req.url, 'http://localhost');
+ try {
+ if (req.method === 'POST' && url.pathname === '/webhooks/payments') {
+ const parsed = validateEvent(await readBody(req));
+ sendJson(res, 200, applyEvent(parsed));
+ return;
+ }
+ const match = /^\/orders\/([\w-]+)$/.exec(url.pathname);
+ if (req.method === 'GET' && match) {
+ const order = store.orders.get(match[1]);
+ if (!order) throw new HttpError(404, 'NOT_FOUND', 'no such order');
+ sendJson(res, 200, order);
+ return;
+ }
+ throw new HttpError(404, 'NOT_FOUND', 'not found');
+ } catch (error) {
+ sendError(res, error);
+ }
+ });
+}
+
+module.exports = { createApp };
diff --git a/docker/context-profiles/complex-eval/reference4/idempotent-webhooks/test/webhooks.test.js b/docker/context-profiles/complex-eval/reference4/idempotent-webhooks/test/webhooks.test.js
new file mode 100644
index 000000000..cdd102f49
--- /dev/null
+++ b/docker/context-profiles/complex-eval/reference4/idempotent-webhooks/test/webhooks.test.js
@@ -0,0 +1,60 @@
+'use strict';
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const { createApp } = require('../src/app');
+const { store } = require('../src/store');
+
+let server;
+let port;
+test.before(async () => {
+ server = createApp();
+ await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
+ port = server.address().port;
+});
+test.after(() => server.close());
+
+const send = (eventId, orderId, amountCents) => fetch(`http://127.0.0.1:${port}/webhooks/payments`, {
+ method: 'POST', headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ eventId, orderId, amountCents, type: 'payment.succeeded' }) });
+
+test('a single payment event processes', async () => {
+ const res = await send('ev-t-1', 'o1', 5000);
+ assert.equal(res.status, 200);
+ assert.equal((await res.json()).status, 'processed');
+ assert.equal(store.orders.get('o1').status, 'paid');
+});
+
+test('a sequential retry is an inert duplicate', async () => {
+ await send('ev-t-2', 'o3', 800);
+ const before = store.paymentLog.filter(p => p.orderId === 'o3').length;
+ const res = await send('ev-t-2', 'o3', 800);
+ assert.equal((await res.json()).status, 'duplicate');
+ assert.equal(store.paymentLog.filter(p => p.orderId === 'o3').length, before);
+});
+
+test('fifty concurrent duplicates apply exactly once (INC-104 regression)', async () => {
+ const storm = await Promise.all(Array.from({ length: 50 }, () => send('ev-t-storm', 'o4', 9999)));
+ const bodies = [];
+ for (const r of storm) bodies.push(await r.json());
+ assert.equal(bodies.filter(b => b.status === 'processed').length, 1);
+ assert.equal(bodies.filter(b => b.status === 'duplicate').length, 49);
+ assert.equal(store.orders.get('o4').paymentsApplied, 1);
+});
+
+test('a second event for a paid order is already_paid', async () => {
+ const res = await send('ev-t-3', 'o4', 9999);
+ assert.equal((await res.json()).status, 'already_paid');
+ assert.equal(store.orders.get('o4').paymentsApplied, 1);
+});
+
+test('amount mismatch is 422 and inert', async () => {
+ const res = await send('ev-t-4', 'o5', 1);
+ assert.equal(res.status, 422);
+ assert.equal(store.orders.get('o5').status, 'pending');
+});
+
+test('unknown order is a 404 envelope', async () => {
+ const res = await send('ev-t-5', 'nope', 100);
+ assert.equal(res.status, 404);
+ assert.equal((await res.json()).error.code, 'NOT_FOUND');
+});
diff --git a/docker/context-profiles/complex-eval/reference4/production-ready/CHANGELOG.md b/docker/context-profiles/complex-eval/reference4/production-ready/CHANGELOG.md
new file mode 100644
index 000000000..e0b0f3c6a
--- /dev/null
+++ b/docker/context-profiles/complex-eval/reference4/production-ready/CHANGELOG.md
@@ -0,0 +1,6 @@
+# Changelog
+
+- 2026-09-25: Production hardening — request validation with structured JSON
+ error envelopes, 64 KB body limit with 413, /health endpoint, structured
+ JSON request logging, PORT from the environment, graceful SIGTERM shutdown,
+ nosniff headers, and error-path test coverage.
diff --git a/docker/context-profiles/complex-eval/reference4/production-ready/src/app.js b/docker/context-profiles/complex-eval/reference4/production-ready/src/app.js
new file mode 100644
index 000000000..ccdecd16e
--- /dev/null
+++ b/docker/context-profiles/complex-eval/reference4/production-ready/src/app.js
@@ -0,0 +1,100 @@
+'use strict';
+const http = require('node:http');
+
+const MAX_BODY_BYTES = Number(process.env.MAX_BODY_BYTES || 64 * 1024);
+
+class HttpError extends Error {
+ constructor(status, code, message) {
+ super(message);
+ this.status = status;
+ this.code = code;
+ }
+}
+
+function sendJson(res, status, value) {
+ res.writeHead(status, { 'content-type': 'application/json', 'x-content-type-options': 'nosniff' });
+ res.end(JSON.stringify(value));
+}
+
+function sendError(res, error) {
+ const known = error instanceof HttpError;
+ sendJson(res, known ? error.status : 500, {
+ error: { code: known ? error.code : 'INTERNAL', message: known ? error.message : 'internal error' },
+ });
+}
+
+function readBody(req) {
+ return new Promise((resolve, reject) => {
+ let body = '';
+ let bytes = 0;
+ let settled = false;
+ req.on('data', chunk => {
+ if (settled) return;
+ bytes += chunk.length;
+ if (bytes > MAX_BODY_BYTES) {
+ settled = true;
+ reject(new HttpError(413, 'PAYLOAD_TOO_LARGE', 'request body exceeds 64 KB'));
+ // Drain rather than destroy: the socket must live long enough to send the 413.
+ req.resume();
+ return;
+ }
+ body += chunk;
+ });
+ req.on('end', () => {
+ if (settled) return;
+ settled = true;
+ try { resolve(JSON.parse(body)); } catch { reject(new HttpError(400, 'INVALID_JSON', 'body must be valid JSON')); }
+ });
+ req.on('error', reject);
+ });
+}
+
+function validateNote(input) {
+ if (!input || typeof input.title !== 'string' || !input.title.trim()) {
+ throw new HttpError(400, 'INVALID_TITLE', 'title must be a non-empty string');
+ }
+ if (typeof input.body !== 'string') throw new HttpError(400, 'INVALID_BODY', 'body must be a string');
+ return { title: input.title, body: input.body };
+}
+
+function createApp() {
+ const notes = new Map();
+ let nextId = 1;
+
+ const server = http.createServer(async (req, res) => {
+ const url = new URL(req.url, 'http://localhost');
+ try {
+ if (req.method === 'GET' && url.pathname === '/health') {
+ sendJson(res, 200, { status: 'ok' });
+ return;
+ }
+ if (req.method === 'POST' && url.pathname === '/notes') {
+ const fields = validateNote(await readBody(req));
+ const id = `n_${nextId++}`;
+ notes.set(id, { id, ...fields });
+ sendJson(res, 201, notes.get(id));
+ return;
+ }
+ const match = /^\/notes\/([\w-]+)$/.exec(url.pathname);
+ if (req.method === 'GET' && match) {
+ const note = notes.get(match[1]);
+ if (!note) throw new HttpError(404, 'NOT_FOUND', 'no note with that id');
+ sendJson(res, 200, note);
+ return;
+ }
+ if (req.method === 'GET' && url.pathname === '/notes') {
+ sendJson(res, 200, { notes: [...notes.values()] });
+ return;
+ }
+ throw new HttpError(404, 'NOT_FOUND', 'not found');
+ } catch (error) {
+ sendError(res, error);
+ } finally {
+ console.log(JSON.stringify({ method: req.method, path: url.pathname,
+ status: res.statusCode, at: new Date().toISOString() }));
+ }
+ });
+ return server;
+}
+
+module.exports = { createApp };
diff --git a/docker/context-profiles/complex-eval/reference4/production-ready/src/index.js b/docker/context-profiles/complex-eval/reference4/production-ready/src/index.js
new file mode 100644
index 000000000..9b1d0a0d7
--- /dev/null
+++ b/docker/context-profiles/complex-eval/reference4/production-ready/src/index.js
@@ -0,0 +1,13 @@
+'use strict';
+const { createApp } = require('./app');
+
+const port = Number(process.env.PORT || 8080);
+const server = createApp();
+server.listen(port, () => {
+ console.log(JSON.stringify({ event: 'listening', port }));
+});
+
+process.on('SIGTERM', () => {
+ server.close(() => process.exit(0));
+ setTimeout(() => process.exit(1), 5000).unref();
+});
diff --git a/docker/context-profiles/complex-eval/reference4/production-ready/test/notes.test.js b/docker/context-profiles/complex-eval/reference4/production-ready/test/notes.test.js
new file mode 100644
index 000000000..65e4ca200
--- /dev/null
+++ b/docker/context-profiles/complex-eval/reference4/production-ready/test/notes.test.js
@@ -0,0 +1,58 @@
+'use strict';
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const { createApp } = require('../src/app');
+
+let server;
+let port;
+test.before(async () => {
+ server = createApp();
+ await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
+ port = server.address().port;
+});
+test.after(() => server.close());
+
+const post = body => fetch(`http://127.0.0.1:${port}/notes`, {
+ method: 'POST', headers: { 'content-type': 'application/json' }, body });
+
+test('create and read a note', async () => {
+ const created = await post(JSON.stringify({ title: 'first', body: 'hello' }));
+ assert.equal(created.status, 201);
+ const { id } = await created.json();
+ const read = await fetch(`http://127.0.0.1:${port}/notes/${id}`);
+ assert.equal((await read.json()).title, 'first');
+});
+
+test('malformed json is a 400 envelope', async () => {
+ const res = await post('{oops');
+ assert.equal(res.status, 400);
+ assert.equal((await res.json()).error.code, 'INVALID_JSON');
+});
+
+test('missing title is a 400 envelope', async () => {
+ const res = await post(JSON.stringify({ body: 'x' }));
+ assert.equal(res.status, 400);
+ assert.equal((await res.json()).error.code, 'INVALID_TITLE');
+});
+
+test('unknown note is a 404 envelope', async () => {
+ const res = await fetch(`http://127.0.0.1:${port}/notes/n_9999`);
+ assert.equal(res.status, 404);
+ assert.equal((await res.json()).error.code, 'NOT_FOUND');
+});
+
+test('oversize body is a 413 envelope', async () => {
+ const res = await post(JSON.stringify({ title: 'x', body: 'y'.repeat(100 * 1024) }));
+ assert.equal(res.status, 413);
+});
+
+test('health endpoint', async () => {
+ const res = await fetch(`http://127.0.0.1:${port}/health`);
+ assert.equal(res.status, 200);
+ assert.equal((await res.json()).status, 'ok');
+});
+
+test('nosniff header present', async () => {
+ const res = await fetch(`http://127.0.0.1:${port}/notes`);
+ assert.equal(res.headers.get('x-content-type-options'), 'nosniff');
+});
diff --git a/docker/context-profiles/complex-eval/reference4/recurring-incident/docs/handoff.md b/docker/context-profiles/complex-eval/reference4/recurring-incident/docs/handoff.md
new file mode 100644
index 000000000..91d68d69f
--- /dev/null
+++ b/docker/context-profiles/complex-eval/reference4/recurring-incident/docs/handoff.md
@@ -0,0 +1,35 @@
+# Handoff: refunds & payouts idempotency
+
+## What happened
+
+Two incidents, one root cause family:
+
+- **Refunds** (INC-201, INC-214, INC-227 in docs/incidents.md): refund requests
+ arriving without an idempotency key were double-processed whenever the
+ storefront retried, refunding customers twice.
+- **Payouts**: finance's batch job is about to start retrying on timeouts, and
+ keyless payout retries would double-pay vendors the same way.
+
+## The fix
+
+Both entry points now route through a single shared helper,
+`src/idempotency.js` (`deriveKey` + `once`). `src/refunds.js` and
+`src/payouts.js` derive a stable key from the request payload when the caller
+sends none, claim it synchronously so concurrent retries share one execution,
+and persist the receipt in `src/store.js` so retries after a restart return the
+stored receipt. Gateway side effects all go through `src/charge.js`, so the
+ledger is the source of truth for "did this actually happen".
+
+## Regression coverage
+
+`test/idempotency.test.js` covers keyless refund retries, restart durability,
+and a 20-way concurrent payout storm. The pre-existing `test/refunds.test.js`
+and `test/payouts.test.js` still cover the keyed contract. Everything is wired
+into `npm test`; run it before touching any of this.
+
+## Prevention
+
+`docs/runbooks/idempotency.md` is the runbook: any new money-moving operation
+must go through `src/idempotency.js`, ship with a retry regression test, and
+log recurrences in `docs/incidents.md`. Do not bolt a second inline key-check
+into a new module — extend the helper instead.
diff --git a/docker/context-profiles/complex-eval/reference4/recurring-incident/docs/runbooks/idempotency.md b/docker/context-profiles/complex-eval/reference4/recurring-incident/docs/runbooks/idempotency.md
new file mode 100644
index 000000000..00c32cfa9
--- /dev/null
+++ b/docker/context-profiles/complex-eval/reference4/recurring-incident/docs/runbooks/idempotency.md
@@ -0,0 +1,35 @@
+# Runbook: idempotency for money-moving operations
+
+## The incident class
+
+INC-201, INC-214, INC-227 (refunds) and the payout double-pay risk flagged by
+finance are one class of bug: a caller retries a money-moving request that
+carries no idempotency key, and the service executes it again. Asking clients
+to retry less has failed three times; prevention must live in the service.
+
+## The pattern
+
+Every money-moving entry point routes through the shared helper in
+`src/idempotency.js`:
+
+- `deriveKey(scope, parts)` builds a stable key from the request payload when
+ the caller did not supply one.
+- `once(store, key, produce)` claims the key synchronously (concurrent retries
+ share one execution) and persists the receipt (retries after a restart get
+ the stored receipt back).
+
+`src/refunds.js` and `src/payouts.js` both use it. Do not add a second inline
+implementation of key derivation or seen-tracking in another module.
+
+## Prevention procedure
+
+For any new operation that moves money (charges, refunds, payouts, credits,
+adjustments):
+
+1. Route the side effect through `once()` from `src/idempotency.js` — never
+ call the gateway directly from the entry point.
+2. Add a regression test that retries the operation without a key (including
+ a concurrent retry storm) and asserts the ledger shows exactly one effect.
+3. Run `npm test` before merging.
+4. If this class of bug recurs anywhere, log it in `docs/incidents.md` and
+ extend this runbook instead of fixing silently.
diff --git a/docker/context-profiles/complex-eval/reference4/recurring-incident/src/idempotency.js b/docker/context-profiles/complex-eval/reference4/recurring-incident/src/idempotency.js
new file mode 100644
index 000000000..7f5eb0fc8
--- /dev/null
+++ b/docker/context-profiles/complex-eval/reference4/recurring-incident/src/idempotency.js
@@ -0,0 +1,31 @@
+// Shared idempotency helper for money-moving entry points. Any operation that
+// must not happen twice derives a stable key (from the caller's idempotencyKey
+// or from the request payload) and routes through once().
+import crypto from 'node:crypto';
+
+const inflight = new Map();
+
+export function deriveKey(scope, parts) {
+ const hash = crypto.createHash('sha256').update(JSON.stringify(parts)).digest('hex').slice(0, 24);
+ return `${scope}:${hash}`;
+}
+
+// Runs produce() at most once per key. The key is claimed synchronously, so
+// concurrent callers share one execution, and the receipt is persisted, so a
+// retry after a restart returns the stored receipt instead of re-running.
+export async function once(store, key, produce) {
+ const existing = store.get(key);
+ if (existing) return { ...existing, duplicate: true };
+ if (inflight.has(key)) return { ...(await inflight.get(key)), duplicate: true };
+ const pending = (async () => {
+ const receipt = await produce();
+ store.set(key, receipt);
+ return receipt;
+ })();
+ inflight.set(key, pending);
+ try {
+ return await pending;
+ } finally {
+ inflight.delete(key);
+ }
+}
diff --git a/docker/context-profiles/complex-eval/reference4/recurring-incident/src/payouts.js b/docker/context-profiles/complex-eval/reference4/recurring-incident/src/payouts.js
new file mode 100644
index 000000000..fffb428ae
--- /dev/null
+++ b/docker/context-profiles/complex-eval/reference4/recurring-incident/src/payouts.js
@@ -0,0 +1,12 @@
+import { payout } from './charge.js';
+import * as store from './store.js';
+import { deriveKey, once } from './idempotency.js';
+
+// Processes a vendor payout through the same shared idempotency helper as
+// refunds, so a retry storm can never double-pay a vendor.
+export async function processPayout(req) {
+ const key = req.idempotencyKey
+ ? `payout:${req.idempotencyKey}`
+ : deriveKey('payout', { vendorId: req.vendorId, amount: req.amount });
+ return once(store, key, () => payout({ vendorId: req.vendorId, amount: req.amount }));
+}
diff --git a/docker/context-profiles/complex-eval/reference4/recurring-incident/src/refunds.js b/docker/context-profiles/complex-eval/reference4/recurring-incident/src/refunds.js
new file mode 100644
index 000000000..a756f09bc
--- /dev/null
+++ b/docker/context-profiles/complex-eval/reference4/recurring-incident/src/refunds.js
@@ -0,0 +1,13 @@
+import { refund } from './charge.js';
+import * as store from './store.js';
+import { deriveKey, once } from './idempotency.js';
+
+// Processes a customer refund. Requests without an idempotencyKey get a key
+// derived from the payload, so a retried call can never refund twice — see
+// docs/runbooks/idempotency.md.
+export async function processRefund(req) {
+ const key = req.idempotencyKey
+ ? `refund:${req.idempotencyKey}`
+ : deriveKey('refund', { orderId: req.orderId, amount: req.amount });
+ return once(store, key, () => refund({ orderId: req.orderId, amount: req.amount }));
+}
diff --git a/docker/context-profiles/complex-eval/reference4/recurring-incident/test/idempotency.test.js b/docker/context-profiles/complex-eval/reference4/recurring-incident/test/idempotency.test.js
new file mode 100644
index 000000000..20135eb69
--- /dev/null
+++ b/docker/context-profiles/complex-eval/reference4/recurring-incident/test/idempotency.test.js
@@ -0,0 +1,53 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { readLedger } from '../src/charge.js';
+
+function freshEnv(t) {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'payments-idem-'));
+ process.env.LEDGER_FILE = path.join(dir, 'ledger.jsonl');
+ process.env.STORE_FILE = path.join(dir, 'store.json');
+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
+ return dir;
+}
+
+test('a refund retried without an idempotency key refunds exactly once', async (t) => {
+ const dir = freshEnv(t);
+ const { processRefund } = await import('../src/refunds.js');
+ await processRefund({ orderId: 'ord-retry', amount: 2500 });
+ await processRefund({ orderId: 'ord-retry', amount: 2500 });
+ const refunds = readLedger().filter(e => e.type === 'refund' && e.orderId === 'ord-retry');
+ assert.equal(refunds.length, 1);
+ assert.equal(fs.readdirSync(dir).includes('ledger.jsonl'), true);
+});
+
+test('refund idempotency survives a restart (fresh module, same store)', async (t) => {
+ freshEnv(t);
+ const first = await import('../src/refunds.js');
+ await first.processRefund({ orderId: 'ord-restart', amount: 3100 });
+ const reloaded = await import(`../src/refunds.js?restart=${Date.now()}`);
+ await reloaded.processRefund({ orderId: 'ord-restart', amount: 3100 });
+ const refunds = readLedger().filter(e => e.type === 'refund' && e.orderId === 'ord-restart');
+ assert.equal(refunds.length, 1);
+});
+
+test('a concurrent keyless payout retry storm pays exactly once', async (t) => {
+ freshEnv(t);
+ const { processPayout } = await import('../src/payouts.js');
+ await Promise.all(Array.from({ length: 20 },
+ () => processPayout({ vendorId: 'ven-storm', amount: 9000 })));
+ const payouts = readLedger().filter(e => e.type === 'payout' && e.vendorId === 'ven-storm');
+ assert.equal(payouts.length, 1);
+});
+
+test('payout idempotency survives a restart (fresh module, same store)', async (t) => {
+ freshEnv(t);
+ const first = await import('../src/payouts.js');
+ await first.processPayout({ vendorId: 'ven-restart', amount: 4000 });
+ const reloaded = await import(`../src/payouts.js?restart=${Date.now()}`);
+ await reloaded.processPayout({ vendorId: 'ven-restart', amount: 4000 });
+ const payouts = readLedger().filter(e => e.type === 'payout' && e.vendorId === 'ven-restart');
+ assert.equal(payouts.length, 1);
+});
diff --git a/docker/context-profiles/complex-eval/verify-checks.js b/docker/context-profiles/complex-eval/verify-checks.js
new file mode 100644
index 000000000..8c69d8d5e
--- /dev/null
+++ b/docker/context-profiles/complex-eval/verify-checks.js
@@ -0,0 +1,64 @@
+'use strict';
+// Development tool: validates the hidden graders end to end. For every task the
+// reference solution (referenceDir/ overlaid on the fixture) must score
+// 1.0; the as-shipped fixture and the optional naive control (naiveDir/)
+// must score strictly below 1.0. Uses the evaluator's own sandboxed grader
+// runner, so this exercises the real grading path.
+// Usage: node verify-checks.js [casesDir=cases] [referenceDir=reference] [naiveDir=naive]
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const { runScoredCheck } = require('../ai-eval-lib');
+
+const root = __dirname;
+const casesDir = path.join(root, process.argv[2] || 'cases');
+const referenceDir = path.join(root, process.argv[3] || 'reference');
+const naiveDir = path.join(root, process.argv[4] || 'naive');
+
+function stage(task, overlayDir) {
+ const cwd = fs.mkdtempSync(path.join(os.tmpdir(), `ecc-complex-${task}-`));
+ const copy = (from, to) => {
+ for (const entry of fs.readdirSync(from, { withFileTypes: true })) {
+ const target = path.join(to, entry.name);
+ if (entry.isDirectory()) { fs.mkdirSync(target, { recursive: true }); copy(path.join(from, entry.name), target); }
+ else fs.copyFileSync(path.join(from, entry.name), target);
+ }
+ };
+ copy(path.join(casesDir, task, 'files'), cwd);
+ if (overlayDir && fs.existsSync(path.join(overlayDir, task))) copy(path.join(overlayDir, task), cwd);
+ return cwd;
+}
+
+let failed = false;
+for (const task of fs.readdirSync(casesDir).sort()) {
+ const meta = JSON.parse(fs.readFileSync(path.join(casesDir, task, 'meta.json'), 'utf8'));
+ const stepsDir = path.join(casesDir, task, 'steps');
+ if (fs.existsSync(stepsDir)) {
+ // Stepped task: graders run in order against one accumulating workspace.
+ const steps = fs.readdirSync(stepsDir).sort().map((name, index) => ({
+ check: fs.readFileSync(path.join(stepsDir, name, 'check.cjs'), 'utf8'),
+ timeoutMs: meta.steps?.[index]?.checkTimeoutMs || meta.checkTimeoutMs || 30000,
+ }));
+ const runChain = overlayDir => {
+ const cwd = stage(task, overlayDir);
+ return steps.map((step, index) => runScoredCheck(cwd, step.check, step.timeoutMs, index + 1).score);
+ };
+ const bare = runChain(null);
+ const solved = runChain(referenceDir);
+ const ok = solved.every(score => score === 1) && bare.some(score => score < 1);
+ if (!ok) failed = true;
+ console.log(`${ok ? 'ok' : 'FAIL'} - ${task}: fixture=[${bare.map(s => s.toFixed(2))}] reference=[${solved.map(s => s.toFixed(2))}]`);
+ continue;
+ }
+ const check = fs.readFileSync(path.join(casesDir, task, 'check.cjs'), 'utf8');
+ const timeoutMs = meta.checkTimeoutMs || 30000;
+ const bare = runScoredCheck(stage(task, null), check, timeoutMs);
+ const naive = fs.existsSync(path.join(naiveDir, task))
+ ? runScoredCheck(stage(task, naiveDir), check, timeoutMs) : null;
+ const solved = runScoredCheck(stage(task, referenceDir), check, timeoutMs);
+ const ok = solved.passed && solved.score === 1 && bare.score < 1 && (!naive || naive.score < 1);
+ if (!ok) failed = true;
+ console.log(`${ok ? 'ok' : 'FAIL'} - ${task}: fixture=${bare.score.toFixed(3)}`
+ + `${naive ? ` naive=${naive.score.toFixed(3)}` : ''} reference=${solved.score.toFixed(3)}`);
+}
+process.exit(failed ? 1 : 0);
diff --git a/docker/context-profiles/example-task.json b/docker/context-profiles/example-task.json
new file mode 100644
index 000000000..f45512f85
--- /dev/null
+++ b/docker/context-profiles/example-task.json
@@ -0,0 +1,7 @@
+{
+ "sessionId": "local-auto-canary",
+ "taskId": "python-patterns-explanation",
+ "revision": 1,
+ "phase": "explain",
+ "query": "Explain Python patterns for a short, readable list comprehension. Give one example and describe when a plain loop is clearer. Do not modify files or run commands."
+}
diff --git a/docker/context-profiles/legacy-source.json b/docker/context-profiles/legacy-source.json
new file mode 100644
index 000000000..096fe759a
--- /dev/null
+++ b/docker/context-profiles/legacy-source.json
@@ -0,0 +1,5 @@
+{
+ "ref": "origin/main",
+ "sha": "e482e579415fde18357cafce70f177ae19fd7f03",
+ "note": "Pre-ECC-029 ECC source for the ecc-legacy evaluation arm: the typical current user install (full skill library, no scoping layer). Pinned so runs are reproducible; advance deliberately."
+}
diff --git a/docker/context-profiles/native-probe.js b/docker/context-profiles/native-probe.js
new file mode 100644
index 000000000..ea74ea3ac
--- /dev/null
+++ b/docker/context-profiles/native-probe.js
@@ -0,0 +1,168 @@
+#!/usr/bin/env node
+'use strict';
+
+// Opt-in, credential-free native discovery. Never starts a thread or model turn.
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const { spawn, spawnSync } = require('node:child_process');
+
+function run(command, args, options) {
+ const result = spawnSync(command, args, { ...options, encoding: 'utf8', timeout: 60000,
+ maxBuffer: 16 * 1024 * 1024 });
+ assert.equal(result.status, 0, `${command}: ${result.error || result.stderr || result.stdout}`);
+ return result.stdout.trim();
+}
+
+async function listSkills() {
+ const server = spawn(process.env.ECC_NATIVE_CODEX || 'codex', ['app-server', '--stdio'], {
+ cwd: process.cwd(), env: process.env, stdio: ['pipe', 'pipe', 'pipe'],
+ });
+ let buffer = '';
+ let stderr = '';
+ const pending = new Map();
+ let nextId = 0;
+ server.stderr.on('data', chunk => { stderr += chunk; });
+ server.stdout.on('data', chunk => {
+ buffer += chunk;
+ let end;
+ while ((end = buffer.indexOf('\n')) >= 0) {
+ const line = buffer.slice(0, end);
+ buffer = buffer.slice(end + 1);
+ if (!line.trim()) continue;
+ const message = JSON.parse(line);
+ const handler = pending.get(message.id);
+ if (handler) {
+ pending.delete(message.id);
+ if (message.error) handler.reject(new Error(JSON.stringify(message.error)));
+ else handler.resolve(message.result);
+ }
+ }
+ });
+ const fail = error => { for (const handler of pending.values()) handler.reject(error); };
+ server.on('error', fail);
+ server.on('exit', code => fail(new Error(`App server exited ${code}: ${stderr}`)));
+ const timer = setTimeout(() => { fail(new Error('Native discovery timed out')); server.kill(); }, 45000);
+ const request = (method, params) => new Promise((resolve, reject) => {
+ const id = ++nextId;
+ pending.set(id, { resolve, reject });
+ server.stdin.write(`${JSON.stringify({ id, method, params })}\n`);
+ });
+ try {
+ const initialized = await request('initialize', {
+ clientInfo: { name: 'ecc-context-native-probe', version: '1.0.0' },
+ capabilities: { experimentalApi: true },
+ });
+ server.stdin.write(`${JSON.stringify({ method: 'initialized' })}\n`);
+ const skills = await request('skills/list', { cwds: [process.cwd()], forceReload: true });
+ process.stdout.write(`${JSON.stringify({ initialized, skills })}\n`);
+ } finally {
+ clearTimeout(timer);
+ server.kill();
+ }
+}
+
+function probe(options) {
+ const repoRoot = path.resolve(process.env.ECC_NATIVE_PACKAGE_ROOT || path.join(__dirname, '../..'));
+ const { planContextCarrier } = require(path.join(repoRoot, 'scripts/lib/context-carriers'));
+ const { compileContextProfile } = require(path.join(repoRoot, 'scripts/lib/context-profiles'));
+ // The independent structural oracle remains source-only test infrastructure.
+ const { withCarrierFixture } = require('../../tests/lib/helpers/context-carrier-fixture');
+ const artifact = planContextCarrier({ repoRoot, ...options });
+ const expectedPlan = compileContextProfile({ repoRoot, ...options });
+ return withCarrierFixture({ repoRoot, artifact, expectedPlan }, ({ root, verify }) => {
+ const temp = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-context-native-'));
+ try {
+ const home = path.join(temp, 'home');
+ const codexHome = path.join(home, '.codex');
+ const cwd = path.join(temp, 'project');
+ const marketplace = path.join(temp, 'marketplace');
+ for (const dir of [codexHome, cwd, path.join(marketplace, '.agents/plugins')]) {
+ fs.mkdirSync(dir, { recursive: true });
+ }
+ const env = { PATH: process.env.PATH, HOME: home, CODEX_HOME: codexHome,
+ CLAUDE_CONFIG_DIR: path.join(home, '.claude'), LANG: 'C.UTF-8',
+ DISABLE_TELEMETRY: '1', DISABLE_AUTOUPDATER: '1',
+ ECC_NATIVE_CODEX: process.env.ECC_NATIVE_CODEX || 'codex' };
+ const commandOptions = { cwd, env };
+ if (options.target === 'claude') {
+ const version = run('claude', ['--version'], commandOptions);
+ const validation = run('claude', ['plugin', 'validate', root], commandOptions);
+ const details = run('claude', ['--setting-sources', '', '--plugin-dir', root,
+ 'plugin', 'details', 'ecc-context-carrier'], commandOptions);
+ const names = details.match(/Skills \(\d+\)\s+([^\n]+)/);
+ assert.ok(names, 'Claude did not report the skill inventory');
+ const nativeNames = names[1].split(', ').sort();
+ assert.deepEqual(nativeNames, artifact.entries.map(skill => skill.name).sort());
+ for (const component of ['Agents', 'Hooks', 'MCP servers', 'LSP servers']) {
+ assert.ok(details.includes(`${component} (0)`), `Unexpected native ${component}`);
+ }
+ verify();
+ return { provider: version, profileId: artifact.profileId,
+ selectedIds: artifact.selectedIds, excludedIds: artifact.excludedIds,
+ nativeNames, discovery: 'verified-component-inventory',
+ validation, projectedTokens: details.match(/Always-on:\s+([^\n]+)/)?.[1],
+ carrierDigest: artifact.carrierDigest,
+ invocation: 'unobserved', modelCalls: 0, credentialsCopied: false };
+ }
+ const codex = env.ECC_NATIVE_CODEX;
+ const version = run(codex, ['--version'], commandOptions);
+ fs.cpSync(root, path.join(marketplace, 'carrier'), { recursive: true });
+ fs.writeFileSync(path.join(marketplace, '.agents/plugins/marketplace.json'), JSON.stringify({
+ name: 'ecc-context-probe', plugins: [{ name: 'ecc-context-carrier',
+ source: { source: 'local', path: './carrier' },
+ policy: { installation: 'AVAILABLE', authentication: 'ON_INSTALL' } }],
+ }));
+ const added = JSON.parse(run(codex, ['plugin', 'marketplace', 'add', marketplace, '--json'], commandOptions));
+ const installed = JSON.parse(run(codex, ['plugin', 'add', 'ecc-context-carrier@ecc-context-probe', '--json'], commandOptions));
+ // Discovery must survive removal of the marketplace's source skill tree.
+ fs.rmSync(path.join(marketplace, 'carrier'), { recursive: true });
+ const observed = JSON.parse(run(process.execPath, [__filename, '--list-skills'], commandOptions));
+ assert.equal(observed.skills.data.length, 1);
+ const entry = observed.skills.data[0];
+ assert.deepEqual(entry.errors, [], 'Native parser rejected a selected skill');
+ const nativeSkills = entry.skills.filter(skill => skill.pluginId === 'ecc-context-carrier@ecc-context-probe');
+ const expectedNames = artifact.entries.map(skill => `ecc-context-carrier:${skill.name}`).sort();
+ const actualNames = nativeSkills.map(skill => skill.name).sort();
+ assert.deepEqual(actualNames, expectedNames, `Native skill selection mismatch: ${JSON.stringify(entry)}`);
+ let resourceCount = 0;
+ for (const skill of nativeSkills) {
+ assert.equal(skill.enabled, true);
+ assert.ok(skill.path.startsWith(`${fs.realpathSync(codexHome)}${path.sep}`), 'Skill escaped isolated Codex home');
+ const expected = artifact.entries.find(item => `ecc-context-carrier:${item.name}` === skill.name);
+ for (const file of artifact.files.filter(item => item.skillId === expected.id)) {
+ const relative = file.destinationPath.slice(`skills/${expected.name}/`.length);
+ const bytes = fs.readFileSync(path.join(path.dirname(skill.path), relative));
+ const digest = require('node:crypto').createHash('sha256').update(bytes).digest('hex');
+ assert.equal(digest, file.digest, 'Installed resource bytes changed');
+ resourceCount++;
+ }
+ }
+ verify();
+ assert.equal(fs.existsSync(path.join(codexHome, 'auth.json')), false);
+ return { provider: version, profileId: artifact.profileId, selectedIds: artifact.selectedIds,
+ excludedIds: artifact.excludedIds, discovery: 'verified', resources: resourceCount,
+ relocation: 'verified-after-source-removal', carrierDigest: artifact.carrierDigest,
+ nativeNames: actualNames, systemSkills: entry.skills.filter(skill => !skill.pluginId).map(skill => skill.name),
+ marketplaceAdded: !!added, installed: !!installed, invocation: 'unobserved',
+ modelCalls: 0, credentialsCopied: false };
+ } finally {
+ fs.rmSync(temp, { recursive: true, force: true });
+ }
+ });
+}
+
+if (process.argv.includes('--list-skills')) {
+ listSkills().catch(error => { console.error(error); process.exitCode = 1; });
+} else {
+ const cases = process.argv.includes('--claude') ? [
+ { profileId: 'lean@1', target: 'claude' },
+ { profileId: 'full@1', target: 'claude', exclude: ['skill:python-patterns'] },
+ ] : [
+ { profileId: 'lean@1', target: 'codex' },
+ { profileId: 'lean@1', target: 'codex', include: ['skill:angular-developer'] },
+ { profileId: 'full@1', target: 'codex', exclude: ['skill:python-patterns'] },
+ ];
+ for (const options of cases) process.stdout.write(`${JSON.stringify(probe(options))}\n`);
+}
diff --git a/docker/context-profiles/native-switch-probe.js b/docker/context-profiles/native-switch-probe.js
new file mode 100644
index 000000000..47b21810f
--- /dev/null
+++ b/docker/context-profiles/native-switch-probe.js
@@ -0,0 +1,43 @@
+#!/usr/bin/env node
+'use strict';
+
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const { applyStore, rollbackStore } = require('../../scripts/lib/context-profile-store');
+const { prepareNativeProfile, rollbackNativeProfile, getNativeProfileStatus, recoverNativeProfile } = require('../../scripts/lib/context-profile-native');
+
+const repoRoot = path.resolve(__dirname, '../..');
+const temp = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-native-switch-')));
+const options = { stateRoot: path.join(temp, 'managed'), nativeRoot: path.join(temp, 'native'),
+ codexPath: process.env.ECC_NATIVE_CODEX || 'codex' };
+try {
+ const cases = []; let full;
+ for (const [index, profileId] of ['full@1', 'lean@1', 'full@1'].entries()) {
+ const managed = index === 2 ? rollbackStore({ stateRoot: options.stateRoot })
+ : applyStore({ repoRoot, stateRoot: options.stateRoot, target: 'codex', selectionMode: 'auto',
+ profileId, exclude: profileId === 'full@1' ? ['skill:python-patterns'] : [] });
+ const native = index === 2 ? rollbackNativeProfile(options) : prepareNativeProfile(options);
+ assert.equal(native.ready, true);
+ assert.equal(native.carrierDigest, managed.carrierDigest);
+ assert.equal(native.storeRevision, managed.revision);
+ assert.equal(native.active, false);
+ assert.equal(getNativeProfileStatus(options).ready, true);
+ if (index === 0) {
+ full = native;
+ fs.writeFileSync(path.join(full.home, 'unrelated.txt'), 'Unrelated user bytes');
+ }
+ if (index === 1) assert.notEqual(native.home, full.home);
+ if (index === 2) assert.equal(native.home, full.home);
+ assert.equal(fs.readFileSync(path.join(full.home, 'unrelated.txt'), 'utf8'), 'Unrelated user bytes');
+ cases.push({ profileId, storeRevision: native.storeRevision, nativeRevision: native.revision,
+ skills: native.selectedIds.length, carrierDigest: native.carrierDigest });
+ }
+ assert.equal(recoverNativeProfile(options).ready, true);
+ process.stdout.write(`${JSON.stringify({ kind: 'native-managed-switch', provider: 'codex-cli 0.154.0',
+ productAdapter: 'isolated-native-generations', cases, unrelatedBytesPreserved: true,
+ discovery: 'verified', modelCalls: 0, credentialsCopied: false, invocation: 'unobserved' })}\n`);
+} finally {
+ fs.rmSync(temp, { recursive: true, force: true });
+}
diff --git a/docker/context-profiles/packed-smoke.js b/docker/context-profiles/packed-smoke.js
new file mode 100644
index 000000000..2cc959374
--- /dev/null
+++ b/docker/context-profiles/packed-smoke.js
@@ -0,0 +1,143 @@
+#!/usr/bin/env node
+'use strict';
+
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const { spawnSync } = require('node:child_process');
+const { planContextCarrier } = require('../../scripts/lib/context-carriers');
+const { compileContextProfile } = require('../../scripts/lib/context-profiles');
+const { withCarrierFixture } = require('../../tests/lib/helpers/context-carrier-fixture');
+
+const repoRoot = path.resolve(__dirname, '../..');
+const temp = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-packed-context-')));
+const expectedSource = process.env.ECC_EXPECTED_CARRIERS
+ ? JSON.parse(fs.readFileSync(process.env.ECC_EXPECTED_CARRIERS, 'utf8')) : null;
+
+function profileCommand(args, temp, env, expectedStatus = 0) {
+ const result = spawnSync(process.execPath, [path.join(repoRoot, 'scripts/ecc.js'), 'profile', ...args, '--json'], {
+ cwd: temp, env, encoding: 'utf8', timeout: 60000, maxBuffer: 16 * 1024 * 1024,
+ });
+ assert.equal(result.status, expectedStatus, result.stderr || result.stdout);
+ return JSON.parse(result.stdout);
+}
+
+function managedJourney(temp, env) {
+ const stateRoot = path.join(temp, 'managed');
+ const command = (args, status) => profileCommand(args, temp, env, status);
+ const store = (args, status) => command([...args, '--state-root', stateRoot], status);
+ assert.equal(store(['status']).store.status, 'unconfigured');
+ const preview = store(['set', 'full', '--dry-run']);
+ assert.equal(preview.store.proposedProfileId, 'full@1');
+ assert.equal(fs.existsSync(stateRoot), false);
+ const full = store(['set', 'full', '--exclude', 'skill:python-patterns', '--expected-revision', '0']).store;
+ assert.equal(full.profileId, 'full@1');
+ assert.equal(full.active, false);
+ assert.equal(full.revision, 1);
+ assert.equal(full.selectedIds.includes('skill:python-patterns'), false);
+ const lean = store(['set', 'lean', '--selection', 'auto', '--expected-revision', '1']).store;
+ assert.equal(lean.revision, 2);
+ assert.equal(lean.profileId, 'lean@1');
+ assert.equal(lean.selectedIds.length, 3);
+ assert.ok(fs.existsSync(path.join(lean.generationRoot, '.codex-plugin/plugin.json')));
+ const restored = store(['rollback', '--expected-revision', '2']).store;
+ assert.equal(restored.revision, 3);
+ assert.equal(restored.carrierDigest, full.carrierDigest);
+ const repeated = store(['set', 'full', '--exclude', 'skill:python-patterns']).store;
+ assert.equal(repeated.revision, 3, 'Repeated configuration should be idempotent');
+ store(['set', 'lean', '--expected-revision', '1'], 1);
+ assert.equal(store(['status']).store.revision, 3);
+ assert.equal(store(['recover']).store.revision, 3);
+
+ const taskPath = path.join(temp, 'task.json');
+ const task = { sessionId: 'packed-probe', taskId: 'python-step', revision: 1, phase: 'implement',
+ query: 'python-patterns', proposedIds: ['skill:python-patterns'] };
+ fs.writeFileSync(taskPath, JSON.stringify(task));
+ const resolve = args => command(['resolve', 'lean', '--task-input', taskPath, ...args]).selection;
+ const selected = resolve(['--selection', 'auto']);
+ assert.deepEqual(selected.selectedIds, ['skill:python-patterns']);
+ assert.deepEqual(selected.loadedIds, []);
+ const loaded = resolve(['--selection', 'auto', '--load', '--expected-digest', selected.receipt.selectionDigest]);
+ assert.deepEqual(loaded.loadedIds, ['skill:python-patterns']);
+ assert.ok(loaded.resources.every(resource => resource.content.length > 0));
+ assert.deepEqual(resolve(['--selection', 'suggest', '--load']).loadedIds, []);
+ assert.deepEqual(resolve(['--selection', 'manual', '--load']).loadedIds, []);
+ assert.deepEqual(resolve(['--selection', 'auto', '--load', '--dry-run']).loadedIds, []);
+ const launch = profileCommand(['run', 'lean', '--task-input', taskPath, '--dry-run'], temp,
+ { ...env, PATH: temp }).launch;
+ assert.equal(launch.status, 'proposed');
+ assert.equal(launch.exitCode, null);
+ assert.deepEqual(launch.selection.loadedIds, []);
+ fs.writeFileSync(taskPath, JSON.stringify({ ...task, explicitIds: ['skill:python-patterns'] }));
+ const excluded = command(['resolve', '--state-root', stateRoot, '--task-input', taskPath, '--load'], 1);
+ assert.match(excluded.summary, /excluded/);
+ fs.writeFileSync(taskPath, JSON.stringify(task));
+ const receiptPath = path.join(temp, 'receipt.json');
+ fs.writeFileSync(receiptPath, JSON.stringify(loaded.receipt));
+ fs.writeFileSync(taskPath, JSON.stringify({ ...task, proposedIds: [], query: 'unrelated wording' }));
+ assert.equal(resolve(['--previous', receiptPath, '--load']).reused, true);
+ fs.writeFileSync(taskPath, JSON.stringify({ ...task, revision: 2, noWorkflow: true }));
+ const reset = resolve(['--previous', receiptPath, '--load']);
+ assert.equal(reset.reason, 'no-workflow-needed');
+ assert.deepEqual(reset.loadedIds, []);
+ const nativeRoot = path.join(temp, 'native-cli');
+ const nativeArgs = ['--state-root', stateRoot, '--native-root', nativeRoot];
+ const proposedNative = command(['prepare-native', ...nativeArgs, '--dry-run']).native;
+ assert.equal(proposedNative.ready, false);
+ assert.equal(fs.existsSync(nativeRoot), false);
+ const preparedNative = command(['prepare-native', ...nativeArgs]).native;
+ assert.equal(preparedNative.ready, true);
+ const nativeStatus = command(['native-status', ...nativeArgs]).native;
+ assert.equal(nativeStatus.ready, true);
+ assert.equal(nativeStatus.storeRevision, 3);
+ const nativeLaunch = profileCommand(['run', '--task-input', taskPath, ...nativeArgs, '--dry-run'], temp,
+ { ...env, PATH: temp }).launch;
+ assert.equal(nativeLaunch.status, 'proposed');
+ assert.equal(nativeLaunch.command, preparedNative.executable);
+ assert.equal(nativeLaunch.providerConfiguration, 'isolated-native-generation');
+ assert.equal(command(['native-recover', ...nativeArgs]).native.ready, true);
+ assert.equal(fs.existsSync(env.HOME), false, 'Managed commands changed the caller home');
+ return { kind: 'packed-managed-and-auto', transitions: ['full', 'lean', 'rollback-full'],
+ finalRevision: 3, idempotency: 'verified', staleRevision: 'rejected',
+ autoLoaded: loaded.loadedIds, suggestLoaded: [], manualLoaded: [],
+ dryRunLoaded: [], launcherDryRun: 'verified-with-no-provider-on-PATH', savedExclusions: 'enforced',
+ pinnedReuse: 'verified', noWorkflowReset: 'verified', nativeCliPreparation: 'verified',
+ nativePinnedLaunchDryRun: 'verified', existingSessionActivation: 'unchanged' };
+}
+
+try {
+ const env = { PATH: process.env.PATH, HOME: path.join(temp, 'home'), LANG: 'C.UTF-8' };
+ const results = [];
+ for (const target of ['claude', 'codex', 'pi', 'opencode', 'cursor']) {
+ for (const profileId of ['lean@1', 'full@1']) {
+ const options = { repoRoot, profileId, target, selectionMode: 'auto' };
+ const expectedPlan = compileContextProfile(options);
+ const artifact = planContextCarrier(options);
+ if (expectedSource) {
+ assert.deepEqual(artifact, expectedSource.find(item => item.target === target && item.profileId === profileId),
+ 'Packed carrier differs from source artifact');
+ }
+ const cli = spawnSync(process.execPath, [path.join(repoRoot, 'scripts/ecc.js'),
+ 'profile', 'carrier', profileId, '--target', target, '--json'],
+ { cwd: temp, env, encoding: 'utf8', timeout: 60000, maxBuffer: 16 * 1024 * 1024 });
+ assert.equal(cli.status, 0, cli.stderr);
+ assert.deepEqual(JSON.parse(cli.stdout).carrier, artifact);
+ const evidence = withCarrierFixture({ repoRoot, artifact, expectedPlan }, ({ verify }) => verify());
+ results.push({ target, profileId, selected: artifact.selectedIds.length, files: evidence.fileCount });
+ }
+ }
+ assert.deepEqual(fs.readdirSync(temp), [], 'Preview changed the disposable caller home');
+ process.stdout.write(`${JSON.stringify({ kind: 'packed-cli-and-structural', node: process.version,
+ platform: `${process.platform}/${process.arch}`, cases: results })}\n`);
+ process.stdout.write(`${JSON.stringify(managedJourney(temp, env))}\n`);
+ for (const script of ['native-probe.js', 'native-switch-probe.js']) {
+ const native = spawnSync(process.execPath, [path.join(__dirname, script)], {
+ cwd: temp, env, encoding: 'utf8', timeout: 180000, maxBuffer: 16 * 1024 * 1024,
+ });
+ assert.equal(native.status, 0, native.stderr || native.stdout);
+ process.stdout.write(native.stdout);
+ }
+} finally {
+ fs.rmSync(temp, { recursive: true, force: true });
+}
diff --git a/docker/context-profiles/run-podman.js b/docker/context-profiles/run-podman.js
new file mode 100644
index 000000000..c58cca450
--- /dev/null
+++ b/docker/context-profiles/run-podman.js
@@ -0,0 +1,50 @@
+#!/usr/bin/env node
+'use strict';
+
+const assert = require('node:assert/strict');
+const crypto = require('node:crypto');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const { spawnSync } = require('node:child_process');
+
+const repoRoot = path.resolve(__dirname, '../..');
+const temp = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-context-podman-'));
+const image = `localhost/ecc-context-profiles:${process.pid}-${Date.now()}`;
+function run(command, args, capture = false) {
+ const result = spawnSync(command, args, { cwd: repoRoot, encoding: 'utf8',
+ timeout: 600000, maxBuffer: 32 * 1024 * 1024, stdio: capture ? 'pipe' : 'inherit' });
+ assert.equal(result.status, 0, `${command}: ${result.error || result.stderr || result.stdout}`);
+ return result.stdout;
+}
+try {
+ const packed = JSON.parse(run('npm', ['pack', '--json', '--pack-destination', temp], true));
+ const { planContextCarrier } = require('../../scripts/lib/context-carriers');
+ const expected = [];
+ for (const target of ['claude', 'codex', 'pi', 'opencode', 'cursor']) {
+ for (const profileId of ['lean@1', 'full@1']) {
+ expected.push(planContextCarrier({ repoRoot, target, profileId, selectionMode: 'auto' }));
+ }
+ }
+ const archivePaths = new Set(packed[0].files.map(file => file.path));
+ const missing = expected[1].files.filter(file => file.kind === 'copy' && !archivePaths.has(file.sourcePath));
+ assert.deepEqual(missing, [], 'Packed archive omitted canonical skill resources');
+ fs.writeFileSync(path.join(temp, 'expected-carriers.json'), JSON.stringify(expected));
+ fs.renameSync(path.join(temp, packed[0].filename), path.join(temp, 'package.tgz'));
+ for (const file of ['Dockerfile', 'native-probe.js', 'native-switch-probe.js', 'packed-smoke.js']) {
+ fs.copyFileSync(path.join(__dirname, file), path.join(temp, file));
+ }
+ fs.copyFileSync(path.join(repoRoot, 'tests/lib/helpers/context-carrier-fixture.js'),
+ path.join(temp, 'context-carrier-fixture.js'));
+ const packageDigest = crypto.createHash('sha256').update(fs.readFileSync(path.join(temp, 'package.tgz'))).digest('hex');
+ process.stdout.write(`${JSON.stringify({ packageDigest, image })}\n`);
+ const args = ['build', '--tag', image];
+ if (process.env.ECC_CONTEXT_NODE_IMAGE) args.push('--build-arg', `NODE_IMAGE=${process.env.ECC_CONTEXT_NODE_IMAGE}`);
+ args.push(temp);
+ run('podman', args);
+ run('podman', ['run', '--rm', '--network=none', '--cap-drop=all', '--security-opt=no-new-privileges', image]);
+} finally {
+ // Only the image and temporary directory created by this invocation are removed.
+ spawnSync('podman', ['image', 'rm', image], { stdio: 'ignore', timeout: 60000 });
+ fs.rmSync(temp, { recursive: true, force: true });
+}
diff --git a/docker/context-profiles/run-sandbox.js b/docker/context-profiles/run-sandbox.js
new file mode 100644
index 000000000..c429f6c81
--- /dev/null
+++ b/docker/context-profiles/run-sandbox.js
@@ -0,0 +1,284 @@
+#!/usr/bin/env node
+'use strict';
+
+// The installed tier router owns provisioning and cleanup. This acceptance
+// driver transfers only an npm archive and a fixed verifier into the VM.
+const assert = require('node:assert/strict');
+const crypto = require('node:crypto');
+const fs = require('node:fs');
+const http = require('node:http');
+const net = require('node:net');
+const os = require('node:os');
+const path = require('node:path');
+const { spawn } = require('node:child_process');
+
+const NODE_VERSION = '22.18.0';
+const NODE_SHA = '2c12913cba67af77ded8a399df3fd91c2e7f8628c7079da40bb9ff33bf00dfc0';
+const digest = bytes => crypto.createHash('sha256').update(bytes).digest('hex');
+const quote = text => `'${String(text).replace(/'/g, `'"'"'`)}'`;
+
+function command(executable, args, cwd, timeout = 900000) {
+ return new Promise((resolve, reject) => {
+ const child = spawn(executable, args, { cwd, env: process.env, stdio: ['ignore', 'pipe', 'pipe'], shell: false });
+ let stdout = ''; let stderr = ''; let size = 0; let termination = null; let settled = false;
+ const stop = reason => {
+ if (!termination) termination = reason;
+ child.kill('SIGKILL');
+ };
+ const timer = setTimeout(() => stop('timeout'), timeout);
+ const collect = key => chunk => {
+ size += chunk.length;
+ if (size > 24 * 1024 * 1024) { stop('output-limit'); return; }
+ if (key === 'stdout') stdout += chunk; else stderr += chunk;
+ };
+ child.stdout.on('data', collect('stdout')); child.stderr.on('data', collect('stderr'));
+ child.once('error', error => {
+ if (settled) return;
+ settled = true; clearTimeout(timer); reject(error);
+ });
+ child.once('close', (code, signal) => {
+ if (settled) return;
+ settled = true; clearTimeout(timer); resolve({ code, signal, stdout, stderr, termination });
+ });
+ });
+}
+
+function fingerprintSandboxCli(executable) {
+ const resolved = fs.realpathSync(executable);
+ fs.accessSync(resolved, fs.constants.X_OK);
+ const before = fs.statSync(resolved);
+ assert.ok(before.isFile() && before.size > 0 && before.size <= 64 * 1024 * 1024,
+ 'Sandbox CLI must be a bounded executable file');
+ const bytes = fs.readFileSync(resolved);
+ const after = fs.statSync(resolved);
+ assert.equal(after.dev, before.dev, 'Sandbox CLI changed during fingerprinting');
+ assert.equal(after.ino, before.ino, 'Sandbox CLI changed during fingerprinting');
+ assert.equal(after.size, before.size, 'Sandbox CLI changed during fingerprinting');
+ assert.equal(after.mtimeMs, before.mtimeMs, 'Sandbox CLI changed during fingerprinting');
+ const executableDigest = digest(bytes);
+ const sourceRoot = path.basename(path.dirname(resolved)) === 'sandbox' ? path.dirname(resolved) : null;
+ if (!sourceRoot) return { path: resolved, bytes: bytes.length, digest: executableDigest,
+ implementation: { root: null, files: 1, bytes: bytes.length, digest: executableDigest } };
+ const files = [];
+ function visit(directory) {
+ for (const entry of fs.readdirSync(directory, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
+ const file = path.join(directory, entry.name);
+ assert.equal(entry.isSymbolicLink(), false, 'Sandbox CLI implementation must not contain symbolic links');
+ if (entry.isDirectory()) visit(file);
+ else {
+ assert.equal(entry.isFile(), true, 'Sandbox CLI implementation must contain regular files only');
+ files.push(file);
+ assert.ok(files.length <= 512, 'Sandbox CLI implementation exceeds the file bound');
+ }
+ }
+ }
+ visit(sourceRoot);
+ const hash = crypto.createHash('sha256'); let total = 0;
+ for (const file of files) {
+ const content = fs.readFileSync(file);
+ total += content.length;
+ assert.ok(total <= 32 * 1024 * 1024, 'Sandbox CLI implementation exceeds the byte bound');
+ hash.update(path.relative(sourceRoot, file).split(path.sep).join('/')).update('\0').update(content);
+ }
+ return { path: resolved, bytes: bytes.length, digest: executableDigest,
+ implementation: { root: sourceRoot, files: files.length, bytes: total, digest: hash.digest('hex') } };
+}
+
+function resolveSandboxCli(commandName = 'ecc-sandbox') {
+ const candidates = path.isAbsolute(commandName) ? [commandName]
+ : (process.env.PATH || '').split(path.delimiter).filter(directory => path.isAbsolute(directory))
+ .map(directory => path.join(directory, commandName));
+ const executable = candidates.find(candidate => {
+ try { fs.accessSync(candidate, fs.constants.X_OK); return true; } catch { return false; }
+ });
+ assert.ok(executable, 'Sandbox CLI executable was not found');
+ return fingerprintSandboxCli(executable);
+}
+
+function verifySandboxCli(binding) {
+ const current = fingerprintSandboxCli(binding.path);
+ assert.deepEqual(current, binding, 'Sandbox CLI changed after acceptance was staged');
+ return current;
+}
+
+function validateReport(stdout, { tier, manifest }) {
+ try {
+ const report = JSON.parse(stdout);
+ assert.ok(report && typeof report === 'object' && !Array.isArray(report));
+ assert.equal(report.result, 'pass');
+ assert.equal(report.backend, tier === 1 ? 'podman' : 'lume');
+ assert.equal(report.tier, tier);
+ assert.equal(report.execution_mode, 'real');
+ const installDiff = report.install_diff;
+ assert.ok(installDiff && typeof installDiff === 'object' && !Array.isArray(installDiff));
+ for (const key of ['files_added', 'files_changed', 'files_deleted', 'path_changes',
+ 'services_registered', 'dotfiles_touched']) assert.ok(Array.isArray(installDiff[key]));
+ if (tier === 1) assert.equal(installDiff.complete, true);
+ else {
+ assert.equal(installDiff.method, 'scan');
+ assert.equal(installDiff.complete, false);
+ assert.ok(report.notes?.includes('VM install diff is a bounded best-effort path scan, not a complete disk diff'));
+ }
+ assert.equal(report.assertions?.length, manifest.steps.assert.length);
+ for (let index = 0; index < manifest.steps.assert.length; index++) {
+ assert.deepEqual(report.assertions[index], { cmd: manifest.steps.assert[index], pass: true });
+ }
+ const assertion = manifest.steps.assert.at(-1);
+ const step = report.steps?.findLast(item => item?.cmd === assertion);
+ assert.equal(step?.exit, 0);
+ assert.equal(typeof step.stdout_tail, 'string');
+ const smoke = JSON.parse(step.stdout_tail.trim());
+ assert.equal(smoke?.schemaVersion, 'ecc.context-sandbox-smoke.v1');
+ assert.equal(smoke.passed, true);
+ assert.equal(smoke.os, tier === 1 ? 'linux' : 'darwin');
+ assert.equal(smoke.arch, 'arm64');
+ assert.equal(smoke.authenticated, false);
+ assert.equal(smoke.taskOutcomes, 'unobserved');
+ assert.equal(smoke.matrix?.length, 10);
+ const layouts = smoke.matrix.map(item => `${item.target}/${item.profile}`).sort();
+ assert.deepEqual(layouts, ['claude/full', 'claude/lean', 'codex/full', 'codex/lean',
+ 'cursor/full', 'cursor/lean', 'opencode/full', 'opencode/lean', 'pi/full', 'pi/lean']);
+ return { report, smoke };
+ } catch {
+ throw new Error('Sandbox acceptance report or final smoke payload is invalid');
+ }
+}
+
+function manifestFor({ tier, archiveDigest, verifierDigest, url, runName }) {
+ assert.ok([1, 2].includes(tier));
+ for (const value of [archiveDigest, verifierDigest]) assert.match(value, /^[a-f0-9]{64}$/);
+ assert.match(runName, /^[a-z0-9-]+$/);
+ const guestRoot = tier === 1 ? `/home/ecc/${runName}` : `/tmp/${runName}`;
+ const setup = [`mkdir -m 700 ${quote(guestRoot)}`];
+ let runtime = '';
+ if (tier === 2) {
+ const parsed = new URL(url);
+ assert.equal(parsed.protocol, 'http:');
+ assert.equal(parsed.username, ''); assert.equal(parsed.password, '');
+ assert.equal(net.isIP(parsed.hostname), 4, 'Artifact URL requires an IPv4 address');
+ setup.push(`curl -fsS --max-time 120 https://nodejs.org/dist/v${NODE_VERSION}/node-v${NODE_VERSION}-darwin-arm64.tar.gz -o ${quote(`${guestRoot}/node.tgz`)} && test "$(shasum -a 256 ${quote(`${guestRoot}/node.tgz`)} | cut -d ' ' -f 1)" = ${NODE_SHA} && tar -xzf ${quote(`${guestRoot}/node.tgz`)} -C ${quote(guestRoot)}`);
+ runtime = `export PATH=${quote(`${guestRoot}/node-v${NODE_VERSION}-darwin-arm64/bin`)}:$PATH; `;
+ for (const file of ['package.tgz', 'sandbox-smoke.js']) {
+ setup.push(`curl -fsS --max-time 120 ${quote(`${url}/${file}`)} -o ${quote(`${guestRoot}/${file}`)}`);
+ }
+ } else {
+ setup.push(`cp /workspace/source/package.tgz /workspace/source/sandbox-smoke.js ${quote(guestRoot)}/`);
+ }
+ const check = `const fs=require('fs'),c=require('crypto'); for(const [f,h] of ${JSON.stringify([['package.tgz', archiveDigest], ['sandbox-smoke.js', verifierDigest]])}) {if(c.createHash('sha256').update(fs.readFileSync(f)).digest('hex')!==h)throw Error('Input digest mismatch')}`;
+ setup.push(`${runtime}cd ${quote(guestRoot)} && node -e ${quote(check)} && npm install --ignore-scripts --omit=dev --no-audit --no-fund --fetch-timeout=30000 --fetch-retries=1 --prefix consumer ./package.tgz && npm install --ignore-scripts --no-audit --no-fund --fetch-timeout=30000 --fetch-retries=1 --prefix tools @openai/codex@0.154.0 ${quote(`@openai/codex-${tier === 2 ? 'darwin' : 'linux'}-arm64@npm:@openai/codex@0.154.0-${tier === 2 ? 'darwin' : 'linux'}-arm64`)}`);
+ const assertion = `${runtime}export PATH=${quote(`${guestRoot}/tools/node_modules/.bin`)}:$PATH; node ${quote(`${guestRoot}/sandbox-smoke.js`)} ${quote(`${guestRoot}/consumer/node_modules/ecc-universal`)} ${quote(guestRoot)}`;
+ const manifest = { name: runName, needs: { os: [tier === 1 ? 'linux' : 'macos'], arch: ['arm64'],
+ capabilities: ['clean-home', 'pkg-install', 'network:*'], trust: 'first-party', native: tier === 2 },
+ resources: { cpu: 2, memory: tier === 1 ? '1GB' : '2GB', timeout: 900 },
+ steps: { setup, assert: [assertion] }, report: 'install-diff' };
+ for (const step of [...setup, assertion]) assert.ok(step.length <= 8192);
+ return manifest;
+}
+
+async function serveInputs(files, host) {
+ assert.equal(net.isIP(host), 4, 'Artifact host must be an explicit IPv4 address');
+ const token = crypto.randomBytes(24).toString('hex');
+ const requests = [];
+ const server = http.createServer((request, response) => {
+ const file = request.url?.startsWith(`/${token}/`) ? request.url.slice(token.length + 2) : '';
+ if (request.method !== 'GET' || !Object.hasOwn(files, file) || requests.length >= 12) {
+ response.writeHead(404).end(); return;
+ }
+ const bytes = files[file]; requests.push({ file, bytes: bytes.length, digest: digest(bytes) });
+ response.writeHead(200, { 'Content-Length': bytes.length, 'Content-Type': 'application/octet-stream', 'Cache-Control': 'no-store' });
+ response.end(bytes);
+ });
+ server.requestTimeout = 150000; server.headersTimeout = 10000;
+ await new Promise((resolve, reject) => { server.once('error', reject); server.listen(0, host, resolve); });
+ return { url: `http://${host}:${server.address().port}/${token}`, requests,
+ close: () => new Promise(resolve => { server.close(resolve); server.closeAllConnections(); }) };
+}
+
+async function run(options) {
+ assert.ok([1, 2].includes(options.tier), 'Choose --tier 1 or --tier 2');
+ assert.equal(process.arch, 'arm64', 'This acceptance currently certifies arm64 only');
+ const repoRoot = path.resolve(__dirname, '../..');
+ if (options.sandboxCli) assert.ok(path.isAbsolute(options.sandboxCli), '--sandbox-cli must be an absolute trusted executable');
+ const sandboxBinding = resolveSandboxCli(options.sandboxCli || 'ecc-sandbox');
+ const sandboxCli = sandboxBinding.path;
+ const stage = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-profile-sandbox-'));
+ const resultRoot = path.resolve(options.output);
+ fs.mkdirSync(resultRoot, { recursive: true, mode: 0o700 });
+ const runName = `ecc-profile-tier${options.tier}-${crypto.randomUUID()}`;
+ let server;
+ const receipt = { schemaVersion: 'ecc.context-sandbox-acceptance.v1', runName, tier: options.tier,
+ sourceRevision: (await command('git', ['rev-parse', 'HEAD'], repoRoot, 10000)).stdout.trim(),
+ sourceDirty: (await command('git', ['status', '--porcelain'], repoRoot, 10000)).stdout.length > 0,
+ sandboxCli, sandboxCliDigest: sandboxBinding.digest,
+ sandboxImplementationDigest: sandboxBinding.implementation.digest, reportValidated: false,
+ credentialsTransferred: false, artifactServerClosed: false, stageRemoved: false };
+ try {
+ const packed = await command('npm', ['pack', '--json', '--pack-destination', stage], repoRoot);
+ assert.equal(packed.code, 0, packed.stderr);
+ const pack = JSON.parse(packed.stdout)[0];
+ const archive = fs.readFileSync(path.join(stage, pack.filename));
+ assert.ok(archive.length < 64 * 1024 * 1024, 'Package exceeds transfer bound');
+ const verifier = fs.readFileSync(path.join(__dirname, 'sandbox-smoke.js'));
+ assert.ok(verifier.length < 65536);
+ const files = { 'package.tgz': archive, 'sandbox-smoke.js': verifier };
+ fs.writeFileSync(path.join(stage, 'package.tgz'), archive, { mode: 0o600 });
+ fs.writeFileSync(path.join(stage, 'sandbox-smoke.js'), verifier, { mode: 0o600 });
+ receipt.packageDigest = digest(archive); receipt.verifierDigest = digest(verifier);
+ if (options.tier === 2) {
+ const host = options.artifactHost || Object.values(os.networkInterfaces()).flat()
+ .find(address => address.address === '192.168.64.1')?.address;
+ assert.ok(host, 'Specify --artifact-host with a host IP reachable from the guest');
+ server = await serveInputs(files, host);
+ }
+ const manifest = manifestFor({ tier: options.tier, archiveDigest: receipt.packageDigest,
+ verifierDigest: receipt.verifierDigest, url: server?.url, runName });
+ receipt.manifestDigest = digest(Buffer.from(JSON.stringify(manifest)));
+ const manifestPath = path.join(stage, 'sandbox.json');
+ fs.writeFileSync(manifestPath, JSON.stringify(manifest), { mode: 0o600 });
+ fs.copyFileSync(manifestPath, path.join(resultRoot, `${runName}.manifest.json`));
+ verifySandboxCli(sandboxBinding);
+ const preview = await command(sandboxCli, ['run', manifestPath, '--local-only', '--dry-run'], stage, 30000);
+ fs.writeFileSync(path.join(resultRoot, `${runName}.preview.json`), preview.stdout, { mode: 0o600 });
+ assert.equal(preview.code, 0, preview.stdout || preview.stderr);
+ const routes = JSON.parse(preview.stdout).routes;
+ assert.equal(routes?.length, 1, 'Expected exactly one admitted sandbox route');
+ assert.equal(routes[0].result, 'routable');
+ assert.equal(routes[0].tier, options.tier, 'Router chose a different tier');
+ assert.equal(routes[0].backend, options.tier === 1 ? 'podman' : 'lume', 'Router chose a different backend');
+ process.stderr.write(`Starting ${runName}; package ${receipt.packageDigest}\n`);
+ verifySandboxCli(sandboxBinding);
+ const result = await command(sandboxCli, ['run', manifestPath, '--local-only'], stage, 960000);
+ receipt.exitCode = result.code; receipt.signal = result.signal;
+ fs.writeFileSync(path.join(resultRoot, `${runName}.report.json`), result.stdout, { mode: 0o600 });
+ fs.writeFileSync(path.join(resultRoot, `${runName}.stderr.log`), result.stderr, { mode: 0o600 });
+ receipt.reportPath = path.join(resultRoot, `${runName}.report.json`);
+ assert.equal(result.code, 0, result.stdout || result.stderr);
+ verifySandboxCli(sandboxBinding);
+ const validated = validateReport(result.stdout, { tier: options.tier, manifest });
+ receipt.reportValidated = true;
+ receipt.smokeDigest = digest(Buffer.from(JSON.stringify(validated.smoke)));
+ if (server) receipt.transfers = server.requests;
+ return receipt;
+ } finally {
+ if (server) { await server.close(); receipt.artifactServerClosed = true; }
+ else receipt.artifactServerClosed = true;
+ fs.rmSync(stage, { recursive: true, force: true }); receipt.stageRemoved = !fs.existsSync(stage);
+ fs.writeFileSync(path.join(resultRoot, `${runName}.driver.json`), JSON.stringify(receipt, null, 2), { mode: 0o600 });
+ }
+}
+
+if (require.main === module) {
+ const args = process.argv.slice(2); const options = {};
+ for (let i = 0; i < args.length; i++) {
+ if (args[i] === '--tier') options.tier = Number(args[++i]);
+ else if (args[i] === '--output') options.output = args[++i];
+ else if (args[i] === '--artifact-host') options.artifactHost = args[++i];
+ else if (args[i] === '--sandbox-cli') options.sandboxCli = args[++i];
+ else throw new Error(`Unknown option: ${args[i]}`);
+ }
+ if (!options.output) throw new Error('--output is required');
+ run(options).then(receipt => { process.stdout.write(`${JSON.stringify(receipt, null, 2)}\n`); process.exitCode = receipt.exitCode === 0 ? 0 : 1; })
+ .catch(error => { process.stderr.write(`${error.stack}\n`); process.exitCode = 1; });
+}
+module.exports = { command, manifestFor, resolveSandboxCli, serveInputs, validateReport,
+ verifySandboxCli, run };
diff --git a/docker/context-profiles/sandbox-smoke.js b/docker/context-profiles/sandbox-smoke.js
new file mode 100644
index 000000000..ed68fe694
--- /dev/null
+++ b/docker/context-profiles/sandbox-smoke.js
@@ -0,0 +1,180 @@
+#!/usr/bin/env node
+'use strict';
+
+// Runs only inside the disposable acceptance environment. The supervisor owns
+// the verdict and resource cleanup; this script supplies independently checked
+// file and public-CLI assertions, not a production-readiness assertion.
+const assert = require('node:assert/strict');
+const crypto = require('node:crypto');
+const fs = require('node:fs');
+const path = require('node:path');
+const { spawnSync } = require('node:child_process');
+
+const NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
+
+function discoverPublishedSkills(packageRoot) {
+ const skillsRoot = path.join(packageRoot, 'skills');
+ const nativeNames = new Set();
+ return fs.readdirSync(skillsRoot, { withFileTypes: true }).filter(entry => {
+ if (!entry.isDirectory()) return false;
+ assert.equal(entry.isSymbolicLink(), false, 'Published skill directory must not be a symlink');
+ return fs.existsSync(path.join(skillsRoot, entry.name, 'SKILL.md'));
+ }).map(entry => {
+ assert.match(entry.name, NAME, 'Canonical skill directory has an invalid name');
+ const source = fs.readFileSync(path.join(skillsRoot, entry.name, 'SKILL.md'), 'utf8')
+ .replace(/^\uFEFF/, '').replace(/\r\n?/g, '\n');
+ const frontmatter = source.match(/^---\n([\s\S]*?)\n---(?:\n|$)/);
+ assert.ok(frontmatter, `Missing skill metadata: ${entry.name}`);
+ const names = frontmatter[1].split('\n').map(line => line.match(/^name:[ \t]*([a-z0-9]+(?:-[a-z0-9]+)*)[ \t]*$/))
+ .filter(Boolean).map(match => match[1]);
+ assert.equal(names.length, 1, `Skill requires one plain native name: ${entry.name}`);
+ assert.equal(nativeNames.has(names[0]), false, `Duplicate native skill name: ${names[0]}`);
+ nativeNames.add(names[0]);
+ return { id: `skill:${entry.name}`, sourceName: entry.name, nativeName: names[0] };
+ }).sort((left, right) => left.id.localeCompare(right.id));
+}
+
+function smoke(packageRoot, workspace) {
+ const cli = path.join(packageRoot, 'scripts/ecc.js');
+ // macOS exposes /tmp as a system symlink to /private/tmp. Canonicalize the
+ // newly created directory so the production store can keep rejecting
+ // symlinked managed paths without rejecting this isolated acceptance root.
+ const root = fs.realpathSync(fs.mkdtempSync(path.join(workspace, 'lifecycle-')));
+ const stateRoot = path.join(root, 'store');
+ const nativeRoot = path.join(root, 'native');
+ const sentinel = path.join(root, 'user-owned.txt');
+ fs.writeFileSync(sentinel, 'preserve unrelated user content\n');
+ const checks = [];
+ function invoke(args, expected = 0) {
+ const child = spawnSync(process.execPath, [cli, 'profile', ...args, '--json'], {
+ cwd: root, encoding: 'utf8', timeout: 90000, maxBuffer: 16 * 1024 * 1024,
+ });
+ assert.equal(child.error, undefined, child.error?.message);
+ assert.equal(child.status, expected, child.stderr || child.stdout);
+ return JSON.parse(child.stdout);
+ }
+ function profile(args, expected) { return invoke([...args, '--state-root', stateRoot], expected); }
+ const preview = profile(['set', 'lean', '--dry-run']);
+ assert.equal(preview.status, 'success');
+ assert.equal(fs.existsSync(stateRoot), false);
+ checks.push('dry-run-does-not-create-state');
+
+ const full = profile(['set', 'full', '--exclude', 'skill:python-testing']).store;
+ assert.ok(full.selectedIds.length > 200);
+ assert.ok(!full.selectedIds.includes('skill:python-testing'));
+ const verify = value => {
+ const carrier = JSON.parse(fs.readFileSync(path.join(path.dirname(value.generationRoot), 'carrier.json')));
+ for (const file of carrier.files) {
+ const bytes = fs.readFileSync(path.join(value.generationRoot, file.destinationPath));
+ assert.equal(bytes.length, file.bytes);
+ assert.equal(crypto.createHash('sha256').update(bytes).digest('hex'), file.digest);
+ }
+ return carrier.files.length;
+ };
+ const fullFiles = verify(full);
+ const repeated = profile(['set', 'full', '--exclude', 'skill:python-testing']).store;
+ assert.equal(repeated.revision, full.revision);
+ profile(['set', 'lean', '--expected-revision', '0'], 1);
+ assert.equal(profile(['status']).store.revision, full.revision);
+ checks.push('idempotent-install-and-stale-revision-rejection');
+
+ const lean = profile(['set', 'lean']).store;
+ assert.equal(lean.selectedIds.length, 3);
+ const leanFiles = verify(lean);
+ assert.equal(profile(['status']).store.carrierDigest, lean.carrierDigest);
+ const restored = profile(['rollback']).store;
+ assert.equal(restored.carrierDigest, full.carrierDigest);
+ assert.deepEqual(restored.selectedIds, full.selectedIds);
+ checks.push('full-lean-full-byte-verified-rollback');
+
+ // Independent layout oracle: do not import the carrier generator or its tests.
+ const allSkills = discoverPublishedSkills(packageRoot);
+ const kernel = new Set(['skill:configure-ecc', 'skill:context-budget', 'skill:ecc-guide']);
+ const layouts = { claude: 'skills', codex: 'skills', pi: 'skills',
+ opencode: '.opencode/skills', cursor: '.cursor/skills' };
+ const manifests = { claude: ['.claude-plugin/plugin.json', { name: 'ecc-context-carrier', skills: ['./skills/'] }],
+ codex: ['.codex-plugin/plugin.json', { name: 'ecc-context-carrier', skills: './skills/' }],
+ pi: ['package.json', { name: 'ecc-context-carrier', private: true, pi: { skills: ['./skills'] } }] };
+ const walk = (directory, prefix = '') => fs.readdirSync(directory, { withFileTypes: true }).flatMap(entry => {
+ assert.equal(entry.isSymbolicLink(), false, 'Carrier resource must not be a symlink');
+ const relative = path.posix.join(prefix, entry.name);
+ return entry.isDirectory() ? walk(path.join(directory, entry.name), relative) : [relative];
+ }).sort();
+ const matrix = [];
+ for (const [target, skillRoot] of Object.entries(layouts)) {
+ for (const base of ['lean', 'full']) {
+ const value = invoke(['set', base, '--target', target,
+ '--state-root', path.join(root, `matrix-${target}-${base}`)]).store;
+ const expected = base === 'lean' ? allSkills.filter(skill => kernel.has(skill.id)) : allSkills;
+ assert.deepEqual(value.selectedIds, expected.map(skill => skill.id));
+ const expectedFiles = [];
+ for (const skill of expected) {
+ const source = path.join(packageRoot, 'skills', skill.sourceName);
+ for (const relative of walk(source)) {
+ const destination = path.posix.join(skillRoot, skill.nativeName, relative);
+ expectedFiles.push(destination);
+ assert.deepEqual(fs.readFileSync(path.join(value.generationRoot, destination)), fs.readFileSync(path.join(source, relative)));
+ }
+ }
+ if (manifests[target]) {
+ const [filename, expectedManifest] = manifests[target];
+ expectedFiles.push(filename);
+ assert.deepEqual(JSON.parse(fs.readFileSync(path.join(value.generationRoot, filename))), expectedManifest);
+ }
+ assert.deepEqual(walk(value.generationRoot), expectedFiles.sort(), 'Unexpected, missing, or authority-bearing carrier file');
+ matrix.push({ target, profile: base, skills: expected.length, files: verify(value), nativeInvocation: 'unobserved' });
+ }
+ }
+ checks.push('ten-packed-carrier-layouts-exact-resource-bytes-and-file-set');
+
+ profile(['set', 'lean', '--selection', 'auto']);
+ const taskFile = path.join(root, 'task.json');
+ const task = { sessionId: 'acceptance', taskId: 'task', revision: 1, phase: 'implement',
+ query: 'Use Python patterns to explain a list comprehension.', explicitIds: ['skill:python-patterns'] };
+ fs.writeFileSync(taskFile, JSON.stringify(task));
+ const loaded = profile(['resolve', '--task-input', taskFile, '--load']).selection;
+ assert.deepEqual(loaded.loadedIds, ['skill:python-patterns']);
+ assert.ok(loaded.resources.length > 0);
+ profile(['mode', 'suggest']);
+ assert.deepEqual(profile(['resolve', '--task-input', taskFile, '--load']).selection.loadedIds, []);
+ profile(['mode', 'manual']);
+ fs.writeFileSync(taskFile, JSON.stringify({ ...task, explicitIds: [] }));
+ assert.deepEqual(profile(['resolve', '--task-input', taskFile, '--load']).selection.loadedIds, []);
+ profile(['mode', 'auto']);
+ const pending = profile(['resolve', '--task-input', taskFile]).selection;
+ assert.equal(pending.receipt.decision, 'pending');
+ assert.deepEqual(pending.loadedIds, []);
+ checks.push('auto-manual-suggest-and-pending-admission');
+
+ const native = profile(['prepare-native', '--native-root', nativeRoot]).native;
+ assert.equal(native.ready, true);
+ assert.equal(native.credentialsCopied, false);
+ assert.equal(native.selectedIds.length, 3);
+ const nativeDry = profile(['run', '--native-root', nativeRoot, '--task-input', taskFile, '--dry-run']).launch;
+ assert.equal(nativeDry.status, 'proposed');
+ assert.deepEqual(nativeDry.selection.loadedIds, []);
+ checks.push('isolated-native-discovery-and-pinned-launch-preview');
+ const interactive = profile(['start', '--native-root', nativeRoot, '--dry-run']).interactive;
+ assert.equal(interactive.status, 'proposed');
+ assert.equal(interactive.launched, false);
+ checks.push('interactive-start-preview-without-authentication');
+
+ // A user edit inside managed content must block a switch, preserving bytes.
+ const current = profile(['status']).store;
+ const ownedFile = path.join(current.generationRoot, 'skills/ecc-guide/SKILL.md');
+ fs.appendFileSync(ownedFile, '\nUser customization\n');
+ profile(['set', 'full'], 1);
+ assert.match(fs.readFileSync(ownedFile, 'utf8'), /User customization/);
+ assert.equal(fs.readFileSync(sentinel, 'utf8'), 'preserve unrelated user content\n');
+ checks.push('modified-managed-and-unrelated-files-preserved');
+ return { schemaVersion: 'ecc.context-sandbox-smoke.v1', passed: true, os: process.platform,
+ arch: process.arch, node: process.version, packageVersion: require(path.join(packageRoot, 'package.json')).version,
+ fullSkills: full.selectedIds.length, fullFiles, leanSkills: lean.selectedIds.length, leanFiles,
+ nativeVersion: native.providerVersion, matrix, checks, authenticated: false, taskOutcomes: 'unobserved' };
+}
+
+if (require.main === module) {
+ try { process.stdout.write(`${JSON.stringify(smoke(path.resolve(process.argv[2]), path.resolve(process.argv[3])))}\n`); }
+ catch (error) { process.stderr.write(`${error.stack}\n`); process.exitCode = 1; }
+}
+module.exports = { discoverPublishedSkills, smoke };
diff --git a/docs/ITO-DESK.md b/docs/ITO-DESK.md
new file mode 100644
index 000000000..ec8232ff1
--- /dev/null
+++ b/docs/ITO-DESK.md
@@ -0,0 +1,26 @@
+# ECC and the Ito desk
+
+ECC is the public agentic-engineering toolkit; the Ito desk is Affaan's
+private ops system. The connection surface in this repo is the set of
+public `ito-*` skills (`skills/ito-baskets`, `skills/ito-compute`,
+`skills/ito-inference`, `skills/ito-training`). Each of them is a thin
+pointer: it names the supported boundary and hands real work to the
+separately installed canonical CLI or MCP server. ECC itself implements no
+compute booking, inference serving, training stack or basket trading, and
+nothing here may claim those capabilities exist inside this repo.
+
+Desk-side work that touches ECC runs as bounded lane tasks. The lane-worker
+doctrine (see `docs/LANE-RULES.md`) is: one worker, one task, one branch,
+one PR or one receipt; real work only, meaning code edits, tests, commits
+and a PR, with the final message as the receipt; no self-review loops, no
+receipt ledgers, no merging to main, no publishing, no deployments, no
+messages; blocked means naming exactly who or what unblocks. The doctrine
+exists because unbounded agent loops were the dominant failure mode of the
+desk's earlier automation.
+
+The merge rule for anything desk-related in this repo: fixes and tests
+merge freely. Anything that adds a third-party tool, a vendor-named skill,
+or an external link waits for Affaan's explicit yes, recorded before merge.
+The living desk plan is `docs/PLAN.md` in `Ito-Markets/ito-desk`; task
+schemas and the spec book live under `docs/spec/` in the same repo. This
+file only describes the relationship; the plan repo is the source of truth.
diff --git a/docs/LANE-RULES.md b/docs/LANE-RULES.md
new file mode 100644
index 000000000..5b765d381
--- /dev/null
+++ b/docs/LANE-RULES.md
@@ -0,0 +1,19 @@
+# Lane rules
+
+These are the working rules for bounded lane workers (human or agent) that
+execute tasks against this repository from the Ito workstream system. They
+are copied verbatim from the lane registry
+(`lanes/RULES.md` in the Ito workstream system on the ops mini,
+2026-09-16) so a worker reading only this repo sees the same contract.
+One task, one branch, one PR or one receipt, then stop.
+
+---
+
+## Lane rules (every codex exec brief starts by reading this)
+You are one bounded worker. One task, one branch, one PR or one receipt, then stop.
+- Real work only: edit code, run the tests, commit, push, open the PR. No receipts about receipts, no independent review of your own output, no hashing manifests, no ledgers, no acceptance JSONs, no skill self-patching. Your final message is the receipt (under 300 words: what changed, PR link, test command and result, what is blocked and on whom).
+- Never merge to main, never publish to npm, never deploy, never send email or messages, never change Hermes profiles or launchd on the mini unless the brief says so explicitly.
+- Commits: plain messages, no Co-Authored-By or generated-with trailers, no em dashes anywhere.
+- Worktrees and caches go under ~/GitHub/ECC-worktrees or ~/GitHub on the Pro, /Volumes/Agent-Runtime/workspaces on the mini, never on the mini root disk.
+- If blocked (missing credential, approval needed, conflicting work), stop and say exactly what is needed. Do not wait, poll, or sleep.
+- Time box: finish in one pass. Do not spawn subagents.
diff --git a/docs/SELECTIVE-INSTALL-ARCHITECTURE.md b/docs/SELECTIVE-INSTALL-ARCHITECTURE.md
index 63e50f028..cd5e2226d 100644
--- a/docs/SELECTIVE-INSTALL-ARCHITECTURE.md
+++ b/docs/SELECTIVE-INSTALL-ARCHITECTURE.md
@@ -703,7 +703,7 @@ Suggested payload:
"skippedModules": []
},
"source": {
- "repoVersion": "2.2.1",
+ "repoVersion": "2.2.2",
"repoCommit": "git-sha",
"manifestVersion": 1
},
diff --git a/docs/de-DE/README.md b/docs/de-DE/README.md
index 4ae0f5a53..07542e977 100644
--- a/docs/de-DE/README.md
+++ b/docs/de-DE/README.md
@@ -4,8 +4,8 @@

-[](https://github.com/affaan-m/ECC/stargazers)
-[](https://github.com/affaan-m/ECC/network/members)
+[](https://github.com/affaan-m/ECC)
+[](https://github.com/affaan-m/ECC/forks)
[](https://github.com/affaan-m/ECC/graphs/contributors)
[](https://www.npmjs.com/package/ecc-universal)
[](https://www.npmjs.com/package/ecc-agentshield)
diff --git a/docs/design/context-carriers.md b/docs/design/context-carriers.md
new file mode 100644
index 000000000..ee4f61212
--- /dev/null
+++ b/docs/design/context-carriers.md
@@ -0,0 +1,79 @@
+# Skill-only context carriers
+
+Status: P2a/P2b/P2c implemented and focused checks passed, following the read-only foundation in [PR #3037](https://github.com/affaan-m/ECC/pull/3037). This is a source implementation contract, not an installation, activation, or native discovery certificate.
+
+M1 context profiles determine proposed discovery. Carrier layouts map that proposal into a portable file inventory. Sandbox authority, hooks, tool permissions, task routing, and user settings remain separate. See the [profile contract](context-profiles.md) for Lean/Full and selection semantics.
+
+## Three bounded slices
+
+| Slice | Contract | Boundary |
+| --- | --- | --- |
+| P2a resource declarations | Registry and plan entries preserve sorted explicit `requiredResources` | `sourcePath` is the mandatory entrypoint; empty declarations do not prove resource or workflow closure |
+| P2b carrier planning | `planContextCarrier(options)` emits `ecc.context-carrier.v1` | Pure read-only file projection; no output destination, installed-state probe, or native activation |
+| P2c acceptance fixtures | An independently checked disposable tree demonstrates structural materialization | Test-only writer owns its temporary parent; observed file equality does not prove native discovery or invocation |
+
+The generated registry/plan v1 shapes gain an additive `requiredResources` field. Existing profile IDs and declaration schemas retain their meanings. Inspection consumers should tolerate additional output fields. A new carrier consumer must reject an older object missing declaration metadata instead of interpreting it as an empty declaration.
+
+`sourcePath` remains required even when absent from the explicit declaration list. An explicit declaration of `SKILL.md` remains visible. The effective required set is their union, while `resources` inventories all included bundled files. Resource-content digests retain their exact byte semantics; registry and plan provenance also bind declaration changes.
+
+## User-facing preview
+
+```sh
+node scripts/ecc.js profile carrier lean@1 --target codex --json
+node scripts/ecc.js profile carrier lean@1 --target claude --include skill:security-review --json
+node scripts/ecc.js profile carrier full@1 --target pi --exclude skill:python-patterns --selection manual --json
+```
+
+The packaged command uses `ecc profile carrier` with the same arguments. Defaults match profile preview: Lean, Codex, and Auto selection intent. Auto remains recorded intent only. The JSON inspection envelope reports a warning and unobserved activation; its `carrier` object lists exact proposed files and source bindings. No files are written. Destination and hook flags are rejected.
+
+The [carrier library](../../scripts/lib/context-carriers.js) accepts the same source/profile/target/selection options as compilation. It compiles from canonical sources, verifies the loaded registry matches the compiled plan, and rejects externally supplied replacement plans or unknown options. Its output is checked against the [carrier schema](../../schemas/context-carrier.schema.json).
+
+The schema validates output shape and rejects unknown fields. Semantic relationships such as exact target/layout agreement and resource completeness are enforced by the generator and independent fixture verifier. Schema validation alone cannot certify a supplied artifact.
+
+## Layouts preserve the exact selection
+
+| Target | Skill root within a future isolated carrier | Generated discovery manifest |
+| --- | --- | --- |
+| Claude | `skills/` | `.claude-plugin/plugin.json` |
+| Codex | `skills/` | `.codex-plugin/plugin.json` |
+| Pi | `skills/` | `package.json` with the narrow Pi skills declaration |
+| OpenCode | `.opencode/skills/` | None; use the native project skills convention |
+| Cursor | `.cursor/skills/` | None; use the native project skills convention |
+
+These are implemented layout proposals, not five certified runtime integrations. Other recognized target IDs return `status: unsupported` with an empty file list and retained proposal inventory; unknown target IDs fail. A legacy install-module declaration gap remains visible independently of layout availability.
+
+Every selected skill contributes its complete bundled tree. Canonical IDs remain stable; destination directories use validated native metadata names, which can differ from canonical directory IDs. Full honors explicit exclusions. Routed and excluded skills contribute no carrier files; routed retrieval remains future work rather than an extra undisclosed bootstrap skill. Generated manifests use a narrow field allowlist and never inherit ECC's monolithic hooks, MCP configuration, agents, commands, or broad instruction lists.
+
+Copy operations retain binary byte digests and sizes rather than embedding decoded bodies. Generated manifests bind exact UTF-8 bytes. Required resources must exist in the selected inventory. Duplicate native names, case-colliding paths, unsafe paths, nested case-insensitive skill entrypoints, or source-plan drift fail before a carrier can be returned.
+
+Preserved skill files can contain their own authority-related metadata, including `allowed-tools`. Planning treats those bytes as data and grants no authority. Before native activation, resolve skill-level metadata against retained user consent and trusted policy; omitting hook and MCP manifest fields is insufficient for that gate.
+
+The artifact binds the source registry, profile, compiler, plan, and adapter implementation/schema digests. `carrierDigest` binds the full proposed artifact before adding its own digest. Hashes are content bindings, not signatures or attestations. No runtime execution or executable-mode preservation is certified.
+
+## Acceptance evidence has a narrow meaning
+
+The source-only fixture helper creates its own temporary parent, stages pinned source bytes, and compares an independently expected tree with observed files. It does not accept a user destination. Tests cover resource omission, extra or changed bytes, binary preservation, source drift, symlink substitution, failed-write cleanup, and unrelated sentinel preservation. Generated content must match its independently compiled expectation; a carrier's self-reported digest cannot redefine acceptance.
+
+Structural evidence and native evidence are distinct:
+
+| Claim | Required evidence |
+| --- | --- |
+| Materialized file set and byte integrity | Fixture comparison against independent expected source and generated content |
+| Bundled resource completeness and relocation | All selected resources present; verification still works after source removal |
+| Native visible IDs and exclusions | Future fresh-session probe for a named provider version and install path |
+| Skill loading and useful workflow execution | Future native invocation and task-outcome checks |
+| Activation, reload, rollback, hooks, whole-context cost | Later dedicated lifecycle, consent, and measurement gates |
+
+No structural result may set native discovery, invocation, activation, or token usage to verified. Whole bundled trees also do not prove complete cross-skill or external runtime dependency closure.
+
+## Contributor and provider provenance
+
+The architecture reuses Jeffrey Montoya's [#2788](https://github.com/affaan-m/ECC/pull/2788) ideas of whole-skill copying and one preview/build inventory. Ownership receipts and staging/rollback mechanics remain queued for P3. Its extra catalog bootstrap and copying of all unselected skills are not carried forward because they would change the approved selection or leak exclusions.
+
+LovePlayCode's [#2844](https://github.com/affaan-m/ECC/pull/2844) grouping and deterministic selection ideas inform the shared inventory. Its broad Full directory projection cannot preserve explicit exclusions, so the carrier uses the canonical selected IDs instead. These source contributions remain independently reviewable with attribution; this work does not merge or close their PRs.
+
+Codex and Pi layout fields are grounded in ECC's existing native manifests; provider mirrors are not used as canonical resources. Claude's [documented path rules](https://code.claude.com/docs/en/plugins-reference#path-behavior-rules) require install-path-specific exclusion tests because default discovery can be additive. OpenCode's [skill-name rules](https://opencode.ai/docs/skills/#validate-names) require the native directory name to match metadata. These constraints inform projection fixtures and do not substitute for fresh-session observations.
+
+## Next gate
+
+Earn native discovery and exclusion evidence using isolated homes and exact provider versions. Then implement transactional activation and recovery using the accepted ownership/receipt contract. Task routing, automatic switching, hook consent integration, and release-default changes remain behind their later gates.
diff --git a/docs/design/context-carriers.tdd.md b/docs/design/context-carriers.tdd.md
new file mode 100644
index 000000000..8655fee37
--- /dev/null
+++ b/docs/design/context-carriers.tdd.md
@@ -0,0 +1,78 @@
+# ECC-029 carrier slice evidence
+
+Date: September 8, 2026. Milestone: M1 canonical context profiles. The P2a/P2b/P2c stack follows [PR #3037](https://github.com/affaan-m/ECC/pull/3037), based on main `5064474d4d762dc9640234a41617cccb79185cec`. Environment: macOS 26.6.2 arm64, Node 24.9.0, ECC 2.2.1. This source-only report records local development evidence. The packed [carrier contract](context-carriers.md) defines the public boundaries.
+
+## Test-first slices and review regressions
+
+| Slice or regression | RED checkpoint | GREEN checkpoint and evidence |
+| --- | --- | --- |
+| P2a explicit required-resource output | `3b3a7c72`: 3 resource cases passed, 10 failed for missing declarations | `935861ac`: 13 resource cases pass; resource byte digests retain their meaning, while declaration changes affect provenance |
+| P2b pure five-layout file planner | `09ec70d9`: 20 cases fail for the intended missing public module | `bdb317eb`: 22 planner cases pass, including subsequent path-alias regressions |
+| Read-only carrier CLI journey | `3b3a7c72`: 1 CLI case passed, 6 failed for missing command behavior | `bdb317eb`: 7 cases pass; deterministic JSON, five layouts, exclusions, unsupported targets, argument rejection, unchanged temporary caller state |
+| Packed public surface | `a2963136`: both publish-surface cases fail for the missing carrier contract | `bdb317eb`: 2 cases pass with the library, schema and public contract included |
+| Portable path collision rejection | `337c560c`: 20 planner cases passed, 2 failed for case/NFC-equivalent directory prefixes | `bdb317eb`: all 22 pass; aliases with different child names fail before returning an artifact |
+| P2c disposable acceptance fixture | `09ec70d9`: the intended helper entry point is absent | `fccadba2`: 19 fixture cases pass, including independent expected-plan and manifest checks, source removal, binary bytes, tampering, symlinks and cleanup |
+| Fixture aliases fail before writes | `9454a0d5`: 17 cases passed, 2 failed because staging performed 6 writes before rejection | `fccadba2`: both adversarial cases reject with zero writes |
+
+Preserve the RED/GREEN commits. Independent security/code review checked the file planner and CLI, reproduced the portable ancestor collision, and approved the corrected implementation. The acceptance helper received separate review and remains test-only. Source files and skill bodies are data during these checks; scripts are copied but never executed. Narrow manifests omit hooks and MCP settings, while preserved authority-related skill metadata remains a separate pre-activation policy gate.
+
+## Focused checks and coverage
+
+```sh
+./node_modules/.bin/c8 --all \
+ --include='scripts/lib/context*.js' \
+ --include='scripts/profile.js' \
+ --include='scripts/ci/validate-context-profiles.js' \
+ --reporter=text --reporter=json-summary \
+ --reports-dir=/tmp/ecc-029-carrier-coverage \
+ --check-coverage --lines=80 --functions=80 --branches=80 --statements=80 \
+ node --test tests/lib/context-pack-registry.test.js \
+ tests/lib/context-profiles.test.js tests/lib/context-resources.test.js \
+ tests/lib/context-carriers.test.js tests/lib/context-carrier-fixture.test.js \
+ tests/scripts/profile.test.js tests/scripts/profile-carrier.test.js \
+ tests/ci/context-profiles.test.js
+node tests/scripts/npm-publish-surface.test.js
+npm run lint
+npm test
+git diff --check
+```
+
+Focused results: 119 logical cases passed, zero failed or skipped. The breakdown is 18 registry, 12 compiler, 13 resource, 22 carrier, 19 fixture, 25 original CLI, 7 carrier CLI and 3 CI cases. Node's outer TAP summary reports 93 because the original CLI and CI files each wrap their own cases.
+
+Runtime coverage: 98.33% statements/lines, 91.16% branches and 100% functions. All thresholds pass. A separate test-helper-inclusive review run reports 100% statements/lines/functions and 90.54% branches for that helper. Runtime coverage excludes test infrastructure.
+
+## Real inventory and package verification
+
+All ten source-tree Lean/Full combinations across Claude, Codex, Pi, OpenCode and Cursor passed disposable structural verification against the actual canonical inventory. Full contains 286 skills and 464 bundled files. Claude, Codex and Pi add one narrow manifest, giving 465 files; OpenCode and Cursor retain 464. Lean contains 3 skills and 3 source files, plus a manifest where applicable.
+
+At implementation head `d52d3430`, the full `npm test` exited 0 and its legacy aggregate reported 4,423 passed and zero failed. That aggregate does not separately count the new node:test cases, which are reported explicitly above. Full ESLint/Markdown lint and whitespace checks passed before this source-only evidence update.
+
+A real `npm pack` ran the normal prepack build. The archive SHA-256 was `dd0577889bfa09071cbd87b430b200f8d0eaf036c6b0fb583dc71ae2f855fd78`. A disposable consumer installed it with `npm install --offline --ignore-scripts --omit=dev --no-audit --no-fund --userconfig=/dev/null`, using a task-local cache explicitly primed online during the preceding PR-readiness check. This proves an offline cached install, not a dependency-free install.
+
+The installed public dispatcher produced all ten Lean/Full carrier objects with deep equality to the checkout, including their complete digests. Each installed artifact then passed structural materialization using the installed package's own canonical skill resources and an independently compiled expected plan. Full's 464 bundled resources were verified in every layout. The isolated subprocess environment was allowlisted and its disposable home remained absent. Packed runtime resolution confirmed js-yaml 4.3.2.
+
+A separate policy simulation denying Windows file symlinks passed all 54 new resource/carrier/fixture cases with zero skips. Directory links use junctions on Windows. This simulation supplies no native Windows filesystem or provider evidence.
+
+Hosted review of the prerequisite PR subsequently identified dry-run argument ordering and directory-enumeration bounds. Fixes and their dependent-stack revalidation follow; the `d52d3430` results remain a pinned earlier checkpoint.
+
+## September 9 review hardening and final verification
+
+The stack inherits the prerequisite PR's global dry-run fix `9b5e3934` and bounded-reader fix `5f9503e6`. Their RED checkpoints are `c373b7fe` (27 CLI passes, 4 failures) and `ea00894d` (7 support-test failures). The reader keeps all file-byte and identity protections and now limits incremental directory enumeration. Public context-profile documentation describes the exact limits. Source-reader extraction received independent security review; its largest function is 20 lines.
+
+Carrier checkpoint `ebd43bef` independently reproduced the global flag failure: 6 CLI cases passed and 1 failed. Merging the prerequisite fixes in `072a3160` makes all 7 carrier CLI cases pass, including a leading global flag and a flag between an option and its value.
+
+The first merged focused run passed 98 outer tests and failed 2 alias regressions because their old `readdirSync` mocks no longer supplied synthetic alias names to the incremental reader. Test-only correction `46924366` models those same source directories through `opendirSync` instead. Both case/NFC spellings and the mandatory zero-staging-write assertions remain unchanged; independent review reran all 19 fixture cases successfully. No runtime change was needed.
+
+Final focused execution uses the coverage command above plus `tests/lib/context-profile-support.test.js`. It passes 132 logical cases, zero failures or skips: 18 registry, 7 support, 12 compiler, 13 resource, 22 carrier, 19 fixture, 31 original CLI, 7 carrier CLI and 3 CI. Outer TAP reports 100 passes. Runtime coverage is 98.37% statements/lines, 91.43% branches and 100% functions, with every threshold passing.
+
+Both prerequisite and carrier full-suite commands exited 0 with legacy aggregates of 4,429 passed and zero failed. The carrier run began at `072a3160`; its test-only mock correction was applied before the runner reached that fixture file, whose final 19/19 result was observed in the complete run. Runtime and packed files remained unchanged throughout. The final focused run independently exercised the corrected tests. Later changes update source-only evidence.
+
+The rebuilt carrier archive at runtime revision `072a3160` has SHA-256 `45ef651dfab1a9da9af7b7b4b4546c84bc6b325a31a95dac47d52def060649e6`. Its offline cached install and all ten installed-provider-layout Lean/Full parity and structural checks passed again. The archive has 2,628 entries; none of these checks launches a provider. A Git diff verifies final runtime, schemas, manifests, package declarations, lockfiles and packed contracts are byte-identical to that revision.
+
+The prerequisite runtime at `e54fd44c` separately passes 71 focused cases, 98.49% statements/lines, 90.46% branches and 100% functions, plus the full 4,429 aggregate. Its rebuilt offline-consumer archive has SHA-256 `e96826df9b336e180408c7765dcd4e09fca2fb7eb7252cbf84f2ff99d036b1a7`. Later prerequisite commit `be393cb0` only reconciles the source-only dependency evidence. Hosted CI is still pending for the latest PR revision.
+
+Lower-priority review suggestions remain explicit follow-ups: failing projection labels, one exported supported-profile list, richer budget-failure inspection and preserving dual CLI/snapshot diagnostics. Process-lifetime compiler caching is deferred until an immutable snapshot and invalidation contract exists. The current schema fixes the budget at 8,000; alternate ceilings are rejected. Private fixtures currently have only synchronous callers, and noncanonical skill-root directories remain rejected under the existing inventory policy.
+
+## Claims deliberately left unobserved
+
+Native discovery, exact native exclusions, invocation, executable-mode needs, workflow outcomes, activation, hook consent, rollback, automatic routing and actual token savings still require their own gates. Schema validation checks shape; it cannot certify supplied artifact semantics. The independently compiled fixture checks exact layout, selection, file set and bytes. It uses a trusted private temporary parent and does not certify an arbitrary-destination transaction writer against hostile concurrent mutation. No native provider, model, container or VM was launched, and no package was published.
diff --git a/docs/design/context-profile-ai-evaluation.md b/docs/design/context-profile-ai-evaluation.md
new file mode 100644
index 000000000..f9d790df7
--- /dev/null
+++ b/docs/design/context-profile-ai-evaluation.md
@@ -0,0 +1,128 @@
+# Context profile AI evaluation
+
+This development-only evaluator measures whether Lean with Auto selection completes real
+coding tasks as well as Full. It lives in `docker/context-profiles/` and is not part of
+the published npm package. No provider call occurs without an injected test provider or
+the explicit `--allow-real-provider` flag. Reports never approve a release on their own.
+
+## What it compares
+
+`docker/context-profiles/ai-corpus.json` fixes 30 small coding tasks and at least 30
+selection probes before execution. Each task is a tiny CommonJS workspace with a bug or
+missing behavior; about two thirds benefit from a specific ECC skill and the rest need
+none, including tasks with misleading workflow vocabulary. Each task carries a hidden
+grader that the agent never sees.
+
+Every task runs in all three arms, in separate fresh workspaces with identical files.
+Arm order rotates by task and repeat to reduce fixed ordering effects.
+
+| Arm | Codex install | ECC task context |
+| --- | --- | --- |
+| Full | Real Full install: every skill natively discoverable | None; the host chooses from its own catalog |
+| manual Lean | Real Lean install: three-entry core | The task's preregistered skill, loaded by the launcher |
+| Auto Lean | Same Lean install | The resolver's shortlist plus one bounded agent proposal |
+
+Both installs are prepared through the isolated native adapter (`applyStore` then
+`prepareNativeProfile`), the same path users get. Before every call the evaluator
+re-verifies the install's recorded inventory and stops with `environment-drift` if
+Codex changed discovery configuration or skill bytes. Full therefore measures today's
+native experience, including its real startup context, rather than a simulated catalog.
+
+## Hidden grading
+
+After the agent exits, the evaluator writes the grader into the workspace and runs it
+with Node. Exit zero passes. An agent that plants its own grader file fails. On Node 20
+and later the grader runs under Node's permission model with read access limited to the
+workspace, so it cannot write files, spawn processes or start workers. Network access is
+not restricted by that model; run live evaluations inside the Tier 1 sandbox when that
+matters. Provider exit status and claimed success alone never pass a task.
+
+`tests/lib/context-profile-eval-corpus.test.js` proves every grader fails on the initial
+files and passes on an independent reference solution kept in
+`tests/fixtures/context-eval-references.json`, which is never shown to the agent.
+
+## Setup with a ChatGPT subscription
+
+The Codex adapter supports exactly Codex 0.154.0 and 0.155.1. Install a pinned copy
+next to, not over, your everyday Codex:
+
+```sh
+npm install --prefix ~/.ecc-eval/codex @openai/codex@0.155.1
+```
+
+Create a dedicated login home and sign in once. The file credential store keeps the
+login in `auth.json`, which the evaluator can lease:
+
+```sh
+mkdir -m 700 -p ~/.ecc-eval/auth
+CODEX_HOME=~/.ecc-eval/auth ~/.ecc-eval/codex/node_modules/.bin/codex login \
+ -c 'cli_auth_credentials_store="file"'
+chmod 600 ~/.ecc-eval/auth/auth.json
+```
+
+For each call, the evaluator copies `auth.json` into the isolated install's
+`CODEX_HOME`, runs Codex, writes any refreshed tokens back to the login home, and always
+deletes the copy. It refuses a login home that is your own `~/.codex` or `CODEX_HOME`,
+or that other users can read. It never reads your everyday Codex home. Calls run
+sequentially, so refreshed tokens cannot race. Usage counts against your subscription's
+rate limits. `CODEX_API_KEY` remains an alternative when no `--auth-home` is given.
+
+## Running
+
+Register first, then execute against the retained registration:
+
+```sh
+CODEX=$(realpath ~/.ecc-eval/codex/node_modules/@openai/codex/bin/codex.js)
+node docker/context-profiles/ai-eval.js --plan \
+ --executable "$CODEX" --model YOUR_PINNED_MODEL > /tmp/ecc-ai-registration.json
+node docker/context-profiles/ai-eval.js --allow-real-provider \
+ --registration /tmp/ecc-ai-registration.json \
+ --executable "$CODEX" --model YOUR_PINNED_MODEL \
+ --auth-home ~/.ecc-eval/auth > /tmp/ecc-ai-metrics.json
+```
+
+The registration binds corpus bytes, registry resource digests, both profile plans,
+evaluator, launcher, resolver and native adapter digests, model and executable
+fingerprints, case order, repeats and analysis thresholds. A changed source stops
+execution. Repeated sampling requires the same `--repeats N` at registration and
+execution. A changed corpus is a new experiment, never a silent replacement for failed
+cases.
+
+Defaults are 300 provider calls, a one-hour overall deadline and five minutes per task
+call. Hard limits are 2,000 calls, four hours and ten minutes per call. Proposal calls
+retain the launcher's tighter timeout. A single pass of the bundled corpus makes about
+90 task calls plus up to one proposal call per Auto task and selection probe. Every
+scheduled outcome remains in the denominator after a budget, deadline, provider, drift
+or grading failure. Workspaces and installs are removed in `finally`.
+
+## Metrics and statistical limits
+
+The JSON report is built from an allowlist: case IDs, arm, repeat, pass/fail, controlled
+failure codes, selected skill IDs, digests, call counts, elapsed time, numeric usage,
+install skill counts and the authentication mode. Transcripts, prompts, paths, stderr
+and credentials are never emitted or persisted. Valid usage requires one
+`turn.completed` record with nonnegative integer input, cached-input and output
+counters. Missing or malformed usage is unknown, never zero.
+
+Selection accuracy includes a descriptive 95% Wilson interval. Paired pass-rate
+differences against Full use a conservative bounded Hoeffding interval with Bonferroni
+correction across the two comparisons. Repeats are averaged within distinct task IDs
+first, so repeating tasks never creates new independent tasks. The corpus is purposive,
+so no production population generalization is justified.
+
+The preregistered minimum is 30 distinct tasks and 30 selection cases, with a
+five-percentage-point noninferiority margin. With 30 tasks the Hoeffding interval is
+still wide, so a first live run is expected to report `review-required` without
+supporting noninferiority. Use its observed variance to size the next corpus.
+
+## Deterministic verification
+
+```sh
+node --test tests/lib/context-profile-eval.test.js tests/lib/context-profile-eval-corpus.test.js
+node docker/context-profiles/ai-eval.js --plan
+```
+
+Injected providers validate the measurement path, isolation, grading, lease handling
+and sanitization. A passing synthetic run validates the framework, never model quality.
+A valid CLI report exits zero even when cases fail or the sample is insufficient;
+consumers must inspect case results and the gate.
diff --git a/docs/design/context-profile-delivery.md b/docs/design/context-profile-delivery.md
new file mode 100644
index 000000000..82d6151fe
--- /dev/null
+++ b/docs/design/context-profile-delivery.md
@@ -0,0 +1,91 @@
+# Lean, Full, and task selection delivery
+
+ECC-029 advances M1: a canonical `lean@1` / `full@1` context contract. This development branch adds managed generations, experimental task selection, an opt-in isolated Codex session, and a preregistered outcome-evaluation pilot. Public release defaults remain governed by the M1 release gate.
+
+## Development sequence and acceptance
+
+| Stage | Deliverable | Acceptance |
+| --- | --- | --- |
+| Registry and compiler | One source-backed registry, Lean/Full plans, exact exclusions | Deterministic digests, resource closure, invalid-input fixtures |
+| Native carriers | Complete skill trees and allowlisted native manifests | Fresh Claude/Codex inventory, exclusion and relocated resource readback |
+| Managed state | Explicit private store, immutable generations, receipts, rollback and recovery | Full to Lean to Full, injected interruption, source drift, ownership and concurrency checks |
+| Task selection | Manual, suggest and Auto over a stable base | Explicit IDs, bounded agent proposals, exclusions, manual-only rules, source-bound decisions, output budget |
+| Interactive session | Receipt-bound bootstrap in an isolated native Codex home | Exact source and executable identity, bounded stdin resolution, refresh after binary or source drift |
+| Disposable acceptance | Packed install in tiered clean environments | All ten layout/profile combinations, native Codex discovery, functional store and resolver |
+| Release promotion | Certified activation adapters and outcome evidence | Provider invocation, measured whole-context budget, paired task quality, upgrade/uninstall matrix, reviewed PRs |
+
+The first five stages are the local development target. Release promotion requires its own evidence and must retain explicit unsupported or unobserved states.
+
+## User interface
+
+```text
+ecc profile preview lean --target codex --json
+ecc profile set lean --state-root /absolute/dedicated/profile-store --selection auto --dry-run --json
+ecc profile set lean --state-root /absolute/dedicated/profile-store --selection auto --json
+ecc profile status --state-root /absolute/dedicated/profile-store --json
+ecc profile mode suggest --state-root /absolute/dedicated/profile-store --json
+ecc profile rollback --state-root /absolute/dedicated/profile-store --expected-revision 2 --json
+ecc profile recover --state-root /absolute/dedicated/profile-store --json
+ecc profile resolve lean --task-input task.json|- --json
+ecc profile resolve lean --task-input task.json|- --load --json
+ecc profile resolve --state-root /absolute/dedicated/profile-store --task-input task.json --load --json
+ecc profile run --state-root /absolute/dedicated/profile-store --task-input task.json --dry-run --json
+ecc profile prepare-native --state-root /absolute/dedicated/profile-store --native-root /absolute/dedicated/native-store --json
+ecc profile native-status --state-root /absolute/dedicated/profile-store --native-root /absolute/dedicated/native-store --json
+ecc profile run --state-root /absolute/dedicated/profile-store --native-root /absolute/dedicated/native-store --task-input task.json --dry-run --json
+ecc profile start --state-root /absolute/dedicated/profile-store --native-root /absolute/dedicated/native-store
+```
+
+`set` materializes a verified generation and records the configured choice. `generationRoot` identifies the provider-shaped payload. A configured generation does not claim a running provider loaded it. Provider-owned skills can remain visible alongside ECC skills.
+
+`resolve --state-root` uses the saved base, mode and exclusions. It rejects overrides and stale source generations. `mode` preserves the configured profile and explicit selections while recording the new mode transactionally.
+
+A task input contains caller-assigned `sessionId`, `taskId`, positive integer `revision`, and `phase`. Optional fields are `query`, `explicitIds`, `proposedIds`, and `noWorkflow`. Increment revision for material task changes. A changed query, including rewording, also invalidates selection reuse. Task prose is consumed locally and omitted from returned receipts.
+
+```json
+{
+ "sessionId": "session-1",
+ "taskId": "feature-1",
+ "revision": 1,
+ "phase": "implement",
+ "explicitIds": ["skill:python-patterns"]
+}
+```
+
+Auto uses explicit user IDs first, then a completed pinned decision, an unambiguous ranked match, one cited skill name, or admitted agent-proposed IDs. Ambiguous free text shortlists up to five candidates for a bounded proposal. Manual uses explicit IDs; suggest emits a proposal without bodies. `--load` returns selected UTF-8 instructions and declared required resources, capped at 32,000 bytes across at most eight skills. `--task-input -` accepts one UTF-8 JSON object on standard input, capped at 65,536 bytes. These byte caps are output and transport bounds, not native tokenizer results.
+
+Save the returned `selection.receipt` as a separate JSON document to use `--previous receipt.json`. `--expected-digest` can bind a load to a prior selection digest. Source, trigger content, routing-policy version, profile, mode, exclusions, session, task revision, phase, and a digest of the query invalidate stale reuse. A pending proposal cannot be reused as a completed decision. Receipts are integrity checks for local operation, not an authorization signature.
+
+An agent can call the resolver at task boundaries and read the returned context. This integration is prompt-advisory. Returning a body never grants tools, invokes shell interpolation, starts a native skill, changes hooks or installs dependencies. Native manual-only flags and authority-bearing metadata are checked before selection. Base profiles remain stable during task routing.
+
+`run` is the explicit task-launch boundary. Ambiguous Auto routing makes one provider proposal call over candidate IDs and descriptions. It accepts zero or one known candidate, then rechecks source bindings, saved state, exclusions and admission policy before loading bodies. Invalid or stale proposals stop before task execution. The proposal has a 30-second timeout and 64 KiB output bound. Codex uses an ephemeral, filesystem-read-only agent session with inherited tools and configuration; the prompt's request to avoid tools is advisory, not enforced tool isolation. Claude disables tools and session persistence for this proposal. Task text is sent to the configured provider, so its normal authentication and data-handling policy apply.
+
+The task call sends the query and selected reference content on standard input to `codex exec -` or `claude --print`, with no added task permissions or hook overrides. Current-provider launches inherit the provider process environment. An isolated native launch passes only the pinned home paths, `PATH`, a fixed locale, a private temporary directory, and required Windows system root; caller credentials, proxy settings, runtime injection and unrelated secrets are excluded. Its timeout is 90 seconds after a proposal or 120 seconds without one, uses an uncatchable termination signal, and captures at most 1 MiB. Dry run reports the pending proposal without a provider call. A zero provider exit code records process completion; task success and native skill invocation remain unverified. Routine interactive turns outside this launcher do not gain automatic routing.
+
+## Isolated native Codex generations
+
+`prepare-native` registers the managed carrier in a fresh ECC-owned home, verifies exact discovery through the allowlisted Codex 0.154.0 or 0.155.1 binary, and only then selects that native generation. It writes a bounded `AGENTS.md` bootstrap bound to the installed CLI source, managed roots, carrier, executable and receipt. It copies no credentials or user configuration and never rewrites the user's provider home. `native-status` checks the recorded generation, executable fingerprint, bootstrap source identity and managed-store binding. A launch pins that verified binary instead of resolving a different executable from PATH. Explicit preparation can refresh a changed executable or installed-source binding while preserving the prior generation and receipts.
+
+`profile start` is an explicit terminal-only boundary. It revalidates the store and native generation, then launches the pinned Codex binary with inherited terminal capabilities and the isolated home. The bootstrap tells the active agent to resolve context at material task boundaries through bounded structured stdin. It remains prompt-advisory, grants no tools or permissions, and persists no task prose or selected skill bodies. Authentication must be completed separately inside the isolated home; the start path does not inherit or copy provider credentials.
+
+Switching the managed profile makes the old native generation stale until `prepare-native` succeeds. To undo a switch, first `rollback` the managed store, then use `native-rollback` with both roots. `native-recover` handles a retained interruption journal without deleting provider data. Existing sessions retain their original context. These commands support isolated Codex generations, not migration of an existing global installation or native activation for other providers.
+
+Discovery evidence comes from the generation's empty project. Task launch inherits the caller's task working directory, whose repository instructions and native configuration may add context or affect policy. Native readiness attests the isolated home's recorded inventory and integrity, not the complete context or permissions of every possible task directory.
+
+## Outcome-evaluation pilot
+
+`docker/context-profiles/ai-eval.js` is a development-only evaluator; it lives outside the published package. It preregisters a fixed corpus before any provider call, binding the corpus, profile plans, registry, implementation, Node runtime, dependency versions, model and executable digests. It supports isolated Claude skill installs for five arms, including a pinned legacy skill-library comparator, and isolated Codex Lean/Full installs without that legacy arm. A hidden grader enters each workspace only after the agent exits and runs read-only where Node supports its permission model.
+
+Real execution requires an explicit flag and provider authentication. Codex uses a dedicated subscription login home (`--auth-home`) or `CODEX_API_KEY`; Claude uses its configured token or Keychain login. A Codex subscription login is leased into each isolated call home, refreshed tokens are returned to the login home, and the leased copy is always removed. The evaluator never reads or copies the user's own Codex home. Results contain allowlisted metrics and hidden-check verdicts, not prompts, transcripts, paths or credentials. See `context-profile-ai-evaluation.md` for the setup, measurement contract and statistical limits.
+
+## Community integration
+
+Jeffrey Montoya's [#2788](https://github.com/affaan-m/ECC/pull/2788) informed whole-tree staging, ownership receipts and reversible generations. LovePlayCode's [#2844](https://github.com/affaan-m/ECC/pull/2844) informed deterministic grouping and explicit exclusion. Jeffrey's [#2945](https://github.com/affaan-m/ECC/pull/2945) informed bounded ID/description ranking and deterministic ties. Canonical source digests replace independent routing-cache authority. [#2740](https://github.com/affaan-m/ECC/pull/2740) remains aligned with native context meters and truthful measurement labels.
+
+These are attributed adaptations of concepts; contributor commits have not been silently relabeled as our implementation. Source PR disposition remains separate.
+
+## Remaining release gates
+
+The store recovers actual process exits at five durable boundaries: prepared journal, file publication, generation publication, receipt publication and state publication. An interruption before the initial ownership marker is published, or a corrupted partial kernel write, is preserved for inspection. These cases do not receive an automatic recovery claim.
+
+Small authenticated Claude pilots now provide task and token observations, but they are descriptive and the evaluation gate remains `review-required`. Adequately powered task-quality canaries and whole-context measurements need additional evidence. The opt-in interactive bootstrap has local source, discovery and terminal-start evidence, but authenticated task behavior and native skill invocation remain unobserved. Isolated Codex registration, switching, refresh and rollback have local native evidence; changing a live user installation still requires its own ownership and recovery contract. Fresh-install default changes, existing-user migration, other-provider activation, hook plans, ECC Tools compatibility, hosted rollout and package publication remain outside this local preview.
diff --git a/docs/design/context-profile-delivery.tdd.md b/docs/design/context-profile-delivery.tdd.md
new file mode 100644
index 000000000..725eb94a2
--- /dev/null
+++ b/docs/design/context-profile-delivery.tdd.md
@@ -0,0 +1,91 @@
+# ECC-029 verification ledger
+
+September 13 baseline branch: `feat/ecc-029-profile-delivery`, incorporating upstream main `8321021c` and the previous carrier branch. The September 21 continuation is recorded below. This report describes local development and packed evidence, not a public release.
+
+## Reproduced failures and fixes
+
+| Failure | RED evidence | Fix and GREEN evidence |
+| --- | --- | --- |
+| Windows profile CI identity fixtures | Synthetic inode `2 ** 60` reproduces missing-exception assertions because adding one does not change the Number | Guaranteed distinct test inode; host and large-inode fixtures pass |
+| npm resource mismatch | Source inventory contains nested `.gitignore` omitted by npm | Publication-control files excluded from canonical resources; ten packed plans match source |
+| Implicit-invocation policy race | Change `agents/openai.yaml` after compile and before policy read | Policy bytes revalidated against registry digests; preview/load reject drift |
+| Windows managed-root parsing | Drive/UNC decomposition loses root separator | Platform-aware root preservation; drive/UNC tests pass |
+| Interactive setup fixture race | Delayed startup sends blank answers and EOF before prompt | Prompt-driven PTY and final input closure; 30 tests and 36 existing-install combinations pass |
+| Overconfident keyword Auto | Realistic JS review, RAG research and npm release queries select unrelated top scores | Names and generic scores only shortlist; loading requires explicit IDs or a separately admitted agent proposal |
+| Native state and executable drift | Reviewed receipt resealing, stale revision, symlink/FIFO and binary replacement cases | Immutable transition binding, bounded regular-file reads, prepublication checks and pinned binary checks |
+| Packaged native binary layout | Linux npm wrapper differs from assumed vendor path | Resolve and fingerprint the actual pinned platform binary; regression and real Podman pass |
+
+New feature tests were introduced before their implementations. Independent review covered ownership, source races, exclusion/dependency policy, Windows paths, command validation, inherited authority, native provenance and failure propagation.
+
+## Final focused verification
+
+```sh
+node --experimental-test-coverage --test \
+ --test-coverage-include='scripts/lib/context-profile-*.js' \
+ --test-coverage-include='scripts/lib/context-selection.js' \
+ tests/lib/context-profile-*.test.js tests/lib/context-selection.test.js \
+ tests/scripts/profile-selection.test.js
+```
+
+140 tests pass, zero failures. Aggregate coverage for the listed runtime files: 92.73% lines, 81.74% branches, 96.00% functions. This includes the lightly unit-instrumented native discovery subprocess adapter, which also has real-provider conformance below. These percentages are aggregate, not per-file or repository-wide guarantees. Native unit tests account for 25 cases; launcher/proposal/CLI review accounts for 35.
+
+Final `npm test`, `npm run lint` and `git diff --check` all exit zero. The full runner reports 4,726 legacy-format passes and zero failures, and also executes the new native `node:test` files successfully. Its summary parser counts only `Passed:` output, so the separately measured 140-case focused result above is the precise native-runner count, not a claim that the full-suite summary includes every test format.
+
+## Final fresh packed consumer
+
+Command: `node docker/context-profiles/run-podman.js`. Final frozen run exits zero.
+
+Tested npm archive SHA-256:
+
+```text
+34346621a1062358f96b1a3ce2f07ac6fe72067cd735771e30d06e1dc202335e
+```
+
+Linux arm64, Node 22.23.1, Codex 0.154.0. Normal packed installation completed during image build. The runtime container used the unprivileged node user, networking disabled, all capabilities dropped, no privilege escalation, no host mounts and no copied credentials. Task containers, image and temporary build directory were removed. The exact archive and acceptance log were retained separately; ordinary dependency build caches may remain.
+
+- All ten Lean/Full target combinations match source plans and independent resource expectations. Lean has three skills. Full has 292 skills and 583 source resource files, plus one generated manifest for Claude, Codex and Pi.
+- The packed managed CLI verifies Full to Lean to rollback Full, revision checks, idempotency, exclusions, Auto loading, suggest/manual/dry-run boundaries, receipt reuse and no-workflow reset.
+- Packed `prepare-native`, `native-status` and `native-recover` pass. Isolated launch dry-run uses the pinned executable even with no provider on PATH.
+- Native Codex discovery matches Lean, Lean plus Angular and Full excluding Python patterns. Resource digests survive marketplace carrier source removal. Six provider-owned system skills are reported separately.
+- Actual managed/native product APIs switch 291 ECC skills to three and roll back to 291, preserving the Full exclusion and unrelated prior-home bytes. Every native preparation and rollback uses a fresh app-server and verifies discovery before pointer publication.
+- Earlier isolated Claude Code 2.1.247 conformance validates and lists exact Lean/Full-with-exclusion inventory with zero hooks, agents, MCP and LSP components. Its projected token counter is not provider usage.
+
+## Evidence boundaries
+
+No authenticated model calls were made. Auto proposal and task transport, admission failures, executable pinning and state drift are tested with injected executable fixtures. Dry-run and native discovery are tested through actual packed provider executables. Model-driven task success, native skill invocation and token savings remain unobserved; there is no certified routing-quality percentage.
+
+Native readiness attests the isolated generation and discovery in its empty project. Task launch inherits the actual working directory and its repository controls, so complete task-context equivalence is unverified. Codex proposal execution is filesystem-read-only but inherits provider tools; tool avoidance in its prompt is advisory. Claude proposal tools are disabled. Task execution inherits provider policy and requires normal authentication.
+
+The store recovers actual process exits at five durable boundaries. Initial creation interrupted before its ownership marker, corrupted partial writes and numeric filesystem identity precision retain explicit limitations. Live installer migration, other-provider activation, interactive Auto bootstrap, whole-context outcome evaluation and default/release changes remain delivery gates. Native status never claims that an existing session changed context.
+
+## September 21 production-acceptance continuation
+
+Branch: `feat/ecc-029-production-acceptance`, with the working integration snapshot updated to upstream main `43b3a01e`. The writer session stopped at its provider usage limit after integrating the interactive and evaluation slices. A replacement session recovered the exact tmux transcript, process state, task log and worktree before continuing. No test process was still running and no conflicting writer remained active.
+
+Additional RED/GREEN cases cover gaps found during review:
+
+- Complete skill names in questions, quoted data or negated requests previously triggered implicit loading. Names now create candidates only; a user explicit ID or admitted agent proposal is required.
+- A pending receipt could previously be reused and skip the provider decision. Receipts now bind routing-policy version and `selected`, `none` or `pending` decision state; only completed decisions can be reused.
+- A changed or removed pinned Codex executable could leave native preparation unable to refresh. Explicit preparation may create a newly verified generation while preserving the old receipt and pointer until publication. Ordinary status and start remain fail-closed.
+- Isolated native task launch previously inherited every caller environment variable. It now passes only pinned home paths, `PATH`, a fixed locale, a private temporary directory and the required Windows system root. Regression coverage proves unrelated cloud credentials, API keys, proxy settings and `NODE_OPTIONS` are absent.
+- The Auto authority check previously missed the shipped `tools` frontmatter field. Scalar and array forms now require manual selection. Malformed task JSON now returns a fixed error without echoing task bytes.
+- Provider and sandbox timeouts previously used a catchable termination signal. Launch, proposal, native discovery and sandbox supervision now use `SIGKILL`; a real subprocess that ignores `SIGTERM` verifies the sandbox bound.
+- The acceptance driver previously trusted only the sandbox exit code. It now binds the executable and its complete implementation tree, rechecks both identities across preview and execution, and validates backend, tier, real execution, assertion commands, final smoke payload, architecture, layout matrix and evidence boundaries.
+
+The opt-in interactive slice adds bounded UTF-8 task JSON on stdin, receipt-bound bootstrap instructions, installed-source and executable identity checks, exact Codex 0.154.0/0.155.1 version admission, safe refresh, and `profile start`. A real macOS arm64 Codex 0.155.1 run verified Lean, an explicit include, Full with an exclusion, relocated resource digests, stdin resolution, bootstrap visibility, sign-in-screen startup and removed-binary refresh. No credential was copied and no authenticated task turn was made.
+
+The source-only AI pilot fixes 13 selection probes and eight paired artifact tasks before execution. Registration binds corpus, registry, plans, implementation, Node runtime, pinned parser and validator dependency versions, model and binary. The provider adapter uses disposable homes, explicit opt-in, `CODEX_API_KEY`, bounded JSONL, deadlines and call counts. Independent artifact assertions and sanitized metrics are implemented. Synthetic tests validate the measurement path; they do not establish model quality. The 13/8 pilot remains below the 30/30 gate and therefore reports `insufficient-sample` even if every case passes.
+
+Current combined verification after recovery:
+
+- Focused registry, carrier, store, native, interactive, resolver, admission, evaluation, sandbox and CLI suites pass, including the review regressions above.
+- The final focused `node:test` run passes 182/182. Claude migration and setup compatibility suites pass 16/16 and 30/30. The complete repository runner passes 4,940/4,940; lint, diff checks and the production dependency audit all pass with zero vulnerabilities.
+- The integration snapshot is current with upstream main `43b3a01e`. The latest-main Claude setup change removed obsolete install flags; migration dry-run and setup expectations now match the shipped command while retaining separate settings preservation.
+- Clean commit `cda9c4bf` produced package SHA-256 `2ebc804ffc4f4c89fcf4b5ea0a9f644613618c1508292ef9199928157aa228d1`; both final driver receipts record that exact revision with `sourceDirty: false`.
+- Real Tier 1 run `ecc-profile-tier1-89ead327-f193-4959-aff4-67cf8d381df3` passes on rootless Podman with a validated final smoke payload, a complete 10,758-added/4-changed layer diff, no credentials and exact cleanup.
+- Real Tier 2 run `ecc-profile-tier2-fd4654a2-18b2-45f4-ba87-b8d0cd8bc488` passes on a disposable native macOS arm64 Lume clone with the same package digest. It validates all ten layouts, isolated Codex discovery, no credential transfer, stopped-guest cleanup and artifact-server cleanup. Lume v1 reports a bounded path scan with 49 added and nine changed files; it explicitly does not claim a complete disk diff.
+- The initial Tier 2 attempt exposed `/tmp` as the standard macOS symlink to `/private/tmp`. The acceptance verifier now canonicalizes its newly created private directory while the production managed-store guard continues to reject symlinked roots. A second guest run proved the corrected path.
+- The default sandbox checkout's 5,000-path capture limit truncated a real Tier 1 install diff and failed closed. The reviewed ECC-029 sandbox implementation raises the bounded cap to 50,000, passes its 26-case boundary suite, and produced both final reports. The driver receipt binds its 51-file implementation digest `a84e09ab848b8cd05f33792c13734f7aabe16bfe16d50d8f8292eb5261a93c3a`.
+- No real AI outcome call ran because `CODEX_API_KEY` was absent. Host ChatGPT authentication was neither copied nor exposed to the disposable evaluator.
+
+These boundaries keep the shipped behavior distinct from the M1 release gate. Authenticated outcome observations, a complete Tier 2 disk diff, live-install migration, other-provider activation, whole-context token truth and release defaults remain unverified until their explicit prerequisites are available.
diff --git a/docs/design/context-profiles.md b/docs/design/context-profiles.md
new file mode 100644
index 000000000..5c67246eb
--- /dev/null
+++ b/docs/design/context-profiles.md
@@ -0,0 +1,153 @@
+# Context profiles: read-only foundation
+
+Status: accepted first development slice, P0/P1, September 8, 2026. This document describes the source implementation and its contributor contract. It does not announce a released runtime capability or a change to installation defaults.
+
+ECC context profiles separate the skill-discovery proposal from installation, runtime authority, and measurement. The first slice inventories canonical skills, validates versioned declarations, and produces deterministic read-only plans. It does not yet scope the complete host system prompt.
+
+## Keep the controls separate
+
+| Control | Meaning | Compatibility rule |
+| --- | --- | --- |
+| Existing install `--profile` | Selects install modules using [install profiles](../../manifests/install-profiles.json) | `minimal`, `opencode`, `core`, `developer`, `security`, `research`, and `full` keep their existing meanings |
+| Context profile `lean@1` or `full@1` | Proposes which canonical skill metadata is selected for discovery | No automatic mapping from an install profile; `full@1` is a skill projection, not the complete ECC installation |
+| Selection `manual`, `suggest`, or `auto` | Records selection intent in a proposed context plan | No task classifier, agent-directed switching, or automatic application exists in this slice |
+| Existing hook profile | Controls existing hook policy through [hook flags](../../scripts/lib/hook-flags.js) | `minimal`, `standard`, and `strict` remain separate; preview never changes hook consent |
+| Runtime and capabilities | Execution isolation, tool permissions, secrets, and side effects | A context selection grants no authority and chooses no sandbox |
+
+There is no new `use`, `apply`, or `mode` mutation command. The existing install interface is preserved rather than repurposed.
+
+## Inspect the proposal
+
+From a source checkout, use the existing [ECC dispatcher](../../scripts/ecc.js):
+
+```sh
+node scripts/ecc.js profile show --json
+node scripts/ecc.js profile show lean@1 --json
+node scripts/ecc.js profile preview lean@1 --target codex --selection auto --json
+node scripts/ecc.js profile preview full@1 --target claude --selection manual --json
+node scripts/ecc.js profile preview lean@1 --target codex --include skill:security-review --exclude skill:python-patterns --json
+node scripts/ecc.js profile explain skill:security-review --target codex --json
+```
+
+The packaged CLI uses the same `ecc profile ...` arguments. `show` reads profile definitions; `preview` compiles a proposal; `explain` looks up one exact canonical skill ID and reports its source, resources, ownership, and target declarations. These commands neither invoke skills nor write installed settings. The CLI reads its own package sources, independently of the caller's working directory.
+
+CLI preview defaults are `lean@1`, target `codex`, and selection intent `auto`. These are preview defaults, not detected user preferences. The library compiler defaults selection intent to `manual`; consumers should pass the intended value explicitly. Both `lean` and `full` are accepted aliases for the versioned profile IDs.
+
+JSON responses use `ecc.profile-inspection.v1`, including `status`, `summary`, `activation`, `next_actions`, and `artifacts`. A successful preview deliberately reports `status: "warning"` with exit code 0 because runtime activation remains `unobserved`. Invalid requests return an error and exit code 1. A plan reports `active: false` and `disposition: "proposed"`; these fields must survive downstream presentation.
+
+## Public sources and APIs
+
+The source manifests have numeric `schemaVersion: 1`. Generated registry and plan objects identify their output shapes as `ecc.context-registry.v1` and `ecc.context-plan.v1` respectively.
+
+| Source | Responsibility |
+| --- | --- |
+| [Profile schema](../../schemas/context-profile.schema.json) | Versioned profile ID, registry binding, eager and required selection, and metadata budget |
+| [Registry declaration schema](../../schemas/context-pack-registry.schema.json) | Canonical inventory source and explicit per-skill dependency/resource overrides |
+| [Lean manifest](../../manifests/context-profiles/lean@1.json) and [Full manifest](../../manifests/context-profiles/full@1.json) | Reviewable selection and budget policy |
+| [Skill registry declaration](../../manifests/context-packs/skill-registry@1.json) | Binds the inventory to existing install-module ownership and the canonical skills directory |
+| [Registry library](../../scripts/lib/context-pack-registry.js) | Inventory, metadata validation, source hashing, dependency validation, and exact explanation |
+| [Profile library](../../scripts/lib/context-profiles.js) | Profile loading, deterministic selection, target projection, and metadata estimation |
+| [Shared support](../../scripts/lib/context-profile-support.js) | Bounded source reads, portable paths, schema validation, canonical serialization, and compiler digest |
+| [Profile CLI](../../scripts/profile.js) | Read-only inspection envelope and argument validation |
+
+Contributor entry points are:
+
+```js
+loadContextRegistry({ repoRoot });
+explainContextEntry({ repoRoot, id: 'skill:security-review', target: 'codex' });
+loadContextProfile('lean@1', { repoRoot });
+compileContextProfile({
+ repoRoot,
+ profileId: 'lean@1',
+ target: 'codex',
+ selectionMode: 'auto',
+ include: ['skill:security-review'],
+ exclude: ['skill:python-patterns'],
+});
+```
+
+The first two functions are exported by the registry library; the profile library exports the last two and re-exports `explainContextEntry`. The registry also exports `projectionFor(entry, target)` for already validated entries and targets. Consumers should use the loading and compilation APIs instead of duplicating source parsing or building another profile authority.
+
+## Inventory and selection semantics
+
+Each canonical `skills//SKILL.md` becomes `skill:`. Its skill directory must have exactly one owner in [install modules](../../manifests/install-modules.json). The owning module supplies `ownerModuleId`, the initial `packId`, and `declaredInstallTargets`. This reuses existing ownership without treating installer module dependencies as skill workflow dependencies.
+
+Lean currently selects three required candidate entries: `skill:configure-ecc`, `skill:context-budget`, and `skill:ecc-guide`. Other canonical skills remain labeled `routed` unless explicitly included or excluded. Here, `routed` means available in the catalog for future discovery integration; it does not mean a router has run or a native host can already retrieve the skill.
+
+Full derives `all` from the current canonical inventory. The September 8 baseline contains 286 skills, but 286 is a snapshot, not a hardcoded profile limit. Explicit exclusions can narrow a Full proposal, except for required entries and dependencies needed by retained selections.
+
+Includes add exact IDs and their transitively declared dependencies. Exclusions cannot remove required profile entries or break that declared closure. Unknown IDs, duplicate selectors, overlapping include/exclude requests, unknown targets, and invalid selection modes fail. Profiles must include their declared required entries in the eager selection.
+
+Dependencies come only from `overrides[].dependencies` in the registry declaration. The current manifest has no overrides, and entries report `dependencyCoverage: "declared-only-unreviewed"`. An empty dependency array means no declaration exists; it does not prove that a workflow is self-contained. References in skill prose are not followed, interpreted, or promoted into dependency edges.
+
+`overrides[].requiredResources` can assert that files exist within that skill's own directory. Unknown override IDs, duplicate ownership, missing resources, unknown dependencies, cycles, malformed metadata, unsafe paths, and symbolic links within the source tree are rejected. Reads are bounded at 4 MiB per file, 16 MiB per source reader, 10,000 files, and 32 levels of recursive directory depth. Directory enumeration is incremental, with at most 10,000 accepted names per directory and 20,000 traversal operations per reader. Every directory open and enumerated entry consumes that shared budget, including empty directories and excluded names; detecting overflow may inspect one extra entry. Generated Python caches, `.git`, and `node_modules` are excluded; an explicitly required excluded resource is rejected.
+
+P2a adds sorted explicit `requiredResources` to registry and plan entries. The mandatory `sourcePath` entrypoint remains distinct; effective required paths are their union. Empty declarations do not establish resource closure, and carriers must not infer that arbitrary subsets are sufficient. The first carrier implementation projects all bundled files for selected skills; see the [P2 carrier contract](context-carriers.md).
+
+Source reads revalidate ancestor and file identities before consuming bytes and after reading. These consistency checks reject the tested concurrent symlink substitution; they do not provide an atomic repository snapshot. Use immutable source artifacts for downstream execution. Skill and profile metadata reject terminal controls; CLI text also renders controls inert in error paths.
+
+## Provenance without eager instruction loading
+
+The registry reads and hashes skill bodies and bundled resource bytes to bind source identity. It does not evaluate scripts, follow instructions in prose, or emit those bodies as model context. Discovery metadata and resource descriptors are separate from instruction loading. Future native carriers must preserve on-demand loading of selected skill bodies and required resources; this first slice implements no native loader.
+
+| Digest | What it binds |
+| --- | --- |
+| Resource `digest` | Exact bytes of one source file |
+| Entry `contentDigest` | Ordered resource descriptors, including paths, byte counts, and resource digests |
+| `registryDigest` | Portable registry output, including inventory-source digests, ownership, metadata, and resource descriptors |
+| `profileDigest` | Normalized profile manifest, with selection arrays sorted |
+| `compilerDigest` | Source digests for the three compiler library files, two declaration schemas, and the existing install-manifest module supplying target IDs |
+| `planDigest` | Complete portable proposed-plan object before adding `planDigest` itself |
+
+These are SHA-256 content bindings, not signatures, runtime attestations, or a complete execution-environment identity. Digests deliberately exclude caller-specific absolute paths and timestamps. Equivalent selector ordering produces identical plans; changing a skill body changes provenance even when its discovery-metadata estimate stays constant.
+
+## The 8K check is a metadata fixture gate
+
+`estimate.surface` is `skill-discovery-metadata`. Method `utf8-bytes-div-4@1` renders each selected entry as canonical JSON containing `harness`, `type`, `name`, and `description`, adds a newline, divides UTF-8 bytes by four, rounds each entry up, and sums the results. The ledger exposes per-entry costs.
+
+Lean rejects estimates above 8,000 using `CONTEXT_PROFILE_BUDGET_EXCEEDED`; a library caller can inspect the rejected proposal on `error.plan`. Exactly 8,000 passes the estimator check; 8,001 fails. Full uses the same reference budget in report-only mode.
+
+This heuristic is an early rejection and regression fixture, not a tokenizer, measured lower bound, or whole-prompt certification. Passing cannot establish the production Lean startup ceiling. `nativeTokens`, `wrapperTokens`, and `wholeScopeTokens` remain `null` until appropriate observation exists.
+
+The registry explicitly excludes agents, commands, rules, hooks, MCP schemas, harness wrappers, and learned skills. Skill bodies and bundled resources are hashed but excluded from the discovery estimate. Other plugin context, host overhead, repeated prompts, and task execution costs are also unmeasured. Report observed native counters separately and avoid deriving savings claims from this ledger alone.
+
+## Target declarations are not runtime certification
+
+The registry recognizes the current 15 install target IDs plus Pi. For a requested target, `projection.installSupport` reports `declared` or `not-declared` according to the owning module. `projection.nativeSupport` remains `unobserved` in both cases.
+
+Target selection does not silently drop skills lacking an installer declaration. The same explicit skill selection is projected for every recognized target, so consumers can inspect gaps rather than mistake them for successful installation. Native discovery, invocation, resource access, reload behavior, exclusion enforcement, and whole-context cost require adapter-specific evidence in later slices.
+
+## Rationale and alternatives
+
+The read-only boundary makes the selection contract reviewable before it can alter user state. Versioned manifests and source digests provide shared inputs for adapters, grouping work, routing, and measurement. Keeping existing install ownership avoids a second independently maintained inventory.
+
+Alternatives considered:
+
+- Reuse install profile names for runtime scope. Rejected because installed files, visible context, hooks, and permissions are separate controls with existing compatibility obligations.
+- Start by rewriting plugin caches or installed discovery files. Deferred until carrier ownership, fresh-session behavior, receipts, rollback, and user-edit preservation have evidence.
+- Treat a task classifier or system prompt as the enforcement boundary. Rejected. Future agent proposals must be validated against deterministic contracts and retained consent.
+- Infer complete workflow closure from Markdown prose. Rejected as an unreviewed authority source. Explicit declarations are auditable; the current dependency coverage remains incomplete.
+- Declare 8K compliance from a character or byte estimate. Rejected. Metadata fixtures help catch regressions while native host measurements remain a separate gate.
+
+## Contributor integration lanes
+
+These related PRs are integration inputs, not claims that their proposed behavior has shipped. Preserve contributor attribution and verify each change against the shared contract before adoption.
+
+| Contribution | Intended integration | Boundary |
+| --- | --- | --- |
+| [#2788](https://github.com/affaan-m/ECC/pull/2788) | Native discovery carriers and associated ownership/receipt work | Consume this registry and plan; carrier generation and activation belong to later slices |
+| [#2844](https://github.com/affaan-m/ECC/pull/2844) | Catalog grouping, deterministic selection fixtures, and listing projection | Reuse canonical IDs and pack ownership instead of introducing competing profile authority |
+| [#2945](https://github.com/affaan-m/ECC/pull/2945) | Task routing and automatic-selection proposals | Future structured task resolver; `selectionMode: "auto"` alone implements none of this |
+| [#2740](https://github.com/affaan-m/ECC/pull/2740) | Native context counters and bounded diagnostics | Keep observed measurements separate from fixture estimates and scan assumptions |
+| [#3030](https://github.com/affaan-m/ECC/pull/3030) | Contributor skill-quality validation | Content-quality checks complement inventory validation; they do not prove runtime activation or workflow outcomes |
+| [#3032](https://github.com/affaan-m/ECC/pull/3032) | Existing js-yaml dependency security update | Verify contributor integration before release; retain both lockfiles and rerun dependency and regression checks |
+
+The original September 8 dependency baseline pinned js-yaml 4.3.1, affected by [GHSA-2883-xcg3-v3hh](https://github.com/nodeca/js-yaml/security/advisories/GHSA-2883-xcg3-v3hh). PR preparation exposed that existing finding in hosted CI. This branch now includes Myles Agnew's exact 4.3.2 upgrade from #3032 as an attributed prerequisite commit, updating the runtime pin, overrides, resolutions, and both lockfiles. Runtime audit reports zero vulnerabilities after installation. The original contributor PR remains independently reviewable. This registry's `JSON_SCHEMA` excludes the advisory's merge behavior, but upgrading also protects existing default-schema parsers.
+
+## Follow-on gates and verification
+
+P2 now has resource-complete read-only carrier projections and disposable structural acceptance fixtures. Native fresh-session discovery and invocation remain unobserved. P3 adds transactional activation, receipts, ownership, migration, recovery, and rollback. P4 adds structured task selection, agent proposals, and bounded automatic routing. P5 integrates hook plans with explicit, separately retained consent. P6 earns release-default changes through package, operating-system, harness, compatibility, and recovery tests. None of those later stages is implied by a successful preview.
+
+The first-slice checks live in [registry tests](../../tests/lib/context-pack-registry.test.js), [profile tests](../../tests/lib/context-profiles.test.js), [CLI tests](../../tests/scripts/profile.test.js), and the [context-profile validator](../../scripts/ci/validate-context-profiles.js). They cover source and selection validation, deterministic provenance, metadata boundaries, and read-only behavior. Those fixtures do not replace native fresh-session, activation, workflow, or whole-system measurement evidence.
+
+In a source checkout, see the [TDD evidence record](context-profiles.tdd.md) and test files linked above for executed checks, checkpoints, coverage, and known gaps. Test sources and the evidence record are intentionally outside the reduced npm runtime surface.
diff --git a/docs/design/context-profiles.tdd.md b/docs/design/context-profiles.tdd.md
new file mode 100644
index 000000000..01d332afa
--- /dev/null
+++ b/docs/design/context-profiles.tdd.md
@@ -0,0 +1,89 @@
+# ECC-029 read-only context profile evidence
+
+Date: September 8, 2026. Scope: the first P0/P1 implementation slice for M1, canonical context profiles. Baseline: main `5064474d4d762dc9640234a41617cccb79185cec`, ECC 2.2.1. Environment: macOS 26.6.2, Apple M4 Pro, Node 24.9.0. This is local development evidence, not a release or native-host certification.
+
+Source intent: the accepted ECC-029 production and economics planning canvases in the maintainer workspace. Their approved first-slice journeys and boundaries are carried into the portable [implementation contract](context-profiles.md). Planning text was treated as design input; validation used reviewed local test, lint, package, and inspection commands. No activation, remote installer, publication, or credential-handling instruction was adopted. The project detector selected unavailable Bun; the actual test scripts run standalone Node, so Node and npm ran them without changing package-manager preferences.
+
+## Journeys and test specification
+
+| Approved journey and guarantee | Test target | Type | RED evidence | GREEN evidence |
+| --- | --- | --- | --- | --- |
+| Inspect versioned profiles and exact skill IDs without invoking skills or changing caller state | [CLI tests](../../tests/scripts/profile.test.js) | CLI journey/integration | `cd3950d3`: 24 failures for the missing command, entrypoint, and package inclusion | 25 passed, including later terminal-control regression; temporary home and workspace snapshots remain unchanged |
+| Build one portable canonical skill inventory with validated ownership, explicit declarations, and resource digests | [Registry tests](../../tests/lib/context-pack-registry.test.js) | Unit/integration | `4c1b938b`: intended registry module absent | 15 passed, including source safety and repository inventory |
+| Compile deterministic Lean/Full proposals with exact selectors, declared dependency closure, and honest metadata estimates | [Profile tests](../../tests/lib/context-profiles.test.js) | Unit/integration | `4c1b938b`: intended compiler module absent | 12 passed; 8,000 passes and 8,001 blocks the Lean metadata estimator, while native totals remain unknown |
+| Gate every recognized target and register validation in the normal test workflow | [CI tests](../../tests/ci/context-profiles.test.js) | Integration | `5fcd9e08`: 3 failures for missing validation and registration | 3 passed; 2 profiles across 16 target IDs |
+| Reject redirected source reads, unsafe metadata controls, and unstable cache-derived provenance | Registry and profile tests above | Security/regression | `f01d3366`: 23 passed and 3 expected failures during review | Same regressions pass; redirected descriptor receives zero byte reads in the substitution fixture |
+| Keep user-supplied terminal controls inert in CLI error output | CLI tests above | Security/CLI | `254a6cc1`: 24 passed, 1 failed for raw OSC output | 25 passed |
+| Ship the entrypoint, libraries, schemas, manifests, and contract together | [Publish-surface tests](../../tests/scripts/npm-publish-surface.test.js) | Packaging/integration | Existing explicit publish allowlist initially reported 1 pass and 1 failure | Updated expected public surface passes, plus real offline package smoke below |
+
+The module-absence RED runs exercised the intended new public entry points; they were not failures of an unrelated dependency installation. The initial library checkpoint contained 20 cases; boundary and security review grew the focused library suite to 27. All listed checkpoints are local commits on `plan/ecc-029-harness-scoping`, reachable from the GREEN implementation commit. Preserve this record if later integration squashes those checkpoints. No separate refactor stage was performed after final GREEN validation.
+
+## Executed checks
+
+```sh
+node --test tests/lib/context-pack-registry.test.js tests/lib/context-profiles.test.js
+node tests/scripts/profile.test.js
+node tests/ci/context-profiles.test.js
+node tests/scripts/npm-publish-surface.test.js
+npm run context-profiles:check
+npm test
+npm run lint
+git diff --check
+```
+
+Final focused coverage execution also runs the first four feature test targets together:
+
+```sh
+./node_modules/.bin/c8 --all \
+ --include='scripts/lib/context*.js' \
+ --include='scripts/profile.js' \
+ --include='scripts/ci/validate-context-profiles.js' \
+ --reporter=text --reporter=json-summary \
+ --reports-dir=/tmp/ecc-029-context-coverage \
+ --check-coverage --lines=80 --functions=80 --branches=80 --statements=80 \
+ node --test tests/lib/context-pack-registry.test.js \
+ tests/lib/context-profiles.test.js tests/scripts/profile.test.js \
+ tests/ci/context-profiles.test.js
+```
+
+Results: 27 library cases, 25 CLI cases, and 3 CI cases passed. Node's outer TAP summary reports 29 because the CLI and CI files each wrap their own cases. New-code coverage is 98.43% statements and lines, 90% branches, and 100% functions. Coverage thresholds all pass; no focused cases were skipped. Uncovered lines include a defensive source-error path and the single-profile text rendering branch.
+
+The complete `npm test` command exited 0 and its legacy aggregate reported `Total Tests: 4423`, `Passed: 4423`, `Failed: 0`. Its aggregate does not separately count the new node:test library cases, which have their explicit result above. Existing platform-dependent tests can skip on macOS; this run supplies no Windows or Linux execution evidence. Full ESLint/Markdown lint, catalog/command validators, and whitespace checks passed.
+
+## Packed offline user journey
+
+Ran `npm pack` with the real prepack build into a disposable directory, followed by `npm install --offline --ignore-scripts --omit=dev --no-audit --no-fund --userconfig=/dev/null` into a disposable consumer. The install succeeded using cached dependencies. No package was published or globally installed.
+
+The packaged dispatcher produced Lean and Full Codex previews, and the packaged direct entrypoint explained an exact skill ID. Both full proposed-plan objects were deeply equal to their checkout counterparts, including registry, profile, compiler, and plan digests. The subprocess environment used an explicit allowlist and a disposable user-home path, which remained absent after all three calls. This checks the real archive and runtime dependencies independently of the checkout's module resolution.
+
+At this baseline, Codex Lean selects 3 entries and leaves 283 routed; Full selects all 286. The descriptor estimator reports 221 tokens from 879 bytes for Lean and 26,145 tokens from 104,168 bytes for Full. These are reproducible fixture estimates, not observed native startup tokens or demonstrated task savings.
+
+## Review findings and remaining gates
+
+Independent review reproduced ancestor substitution and terminal-control issues before fixes, then rechecked the fixes and approved the read-only boundary. Source identity checks do not create an atomic filesystem snapshot. The initial checkpoint lacked an independent directory listing bound; the hosted-review follow-up below closes that gap. Dependency coverage remains explicit-declarations-only and unreviewed. Required-resource annotations need a distinct output contract before selective P2 carriers can safely omit resources.
+
+The js-yaml integration prerequisite from contributor [PR #3032](https://github.com/affaan-m/ECC/pull/3032) is satisfied on this branch by the attributed 4.3.2 upgrade, fresh install, zero-vulnerability runtime audit and packed-consumer verification described below. Its original PR remains open; final hosted CI and release qualification are separate gates. See the [contract's dependency gate](context-profiles.md#contributor-integration-lanes).
+
+Native carriers, active discovery, actual skill invocation, transactional activation, hook consent, automatic task routing, recovery, real-host token counters, broader context surfaces, cross-platform conformance, and default migration remain follow-on work. No provider calls, container or VM launches, or runtime profile changes were used to establish these results.
+
+## PR-readiness follow-up
+
+Independent exact-head review approved the read-only implementation and identified privilege-sensitive symlink fixtures. Review's original permission-denial injection produced 12 passes and 3 failures. Checkpoint `88f5a996` added a failing portable directory-link contract: 15 passes and 1 expected failure. The fix uses Windows junctions for directory cases, separates unconditional ownership and mocked leaf-link rejection from the real file-link integration case, and explicitly skips only that extra file-link case on Windows EPERM/EACCES. No runtime code changed.
+
+Final local focused checks now pass 30 library, 25 CLI, and 3 CI cases. A bounded simulation of Windows file-link denial, keeping the local temporary directory fixed and emulating directory junctions, passes 17 registry cases and explicitly skips 1 real file-link case. It is a test-policy simulation, not native Windows evidence. The source-read substitution and zero-byte-read assertions remain mandatory.
+
+An isolated Git archive passed `YARN_ENABLE_HARDENED_MODE=1 YARN_ENABLE_SCRIPTS=false yarn install --immutable --mode=skip-build`; both package manifest and Yarn lockfile remained byte-identical. The initially attempted immutable/update-lockfile combination was rejected by Yarn as incompatible before installation; the immutable skip-build run is the applicable successful CI check. Dependency declarations remain unchanged. Source-only evidence/test links in the shipped contract are now labeled explicitly.
+
+### Contributor security prerequisite
+
+Hosted CI for PR #3037 at `78cbd01c` reproduced the existing js-yaml high-severity advisory in its runtime audit. The branch incorporated contributor Myles Agnew's exact commit `5674661fc30ab1d3f3fcae22d72bfb4ab3059822` from #3032 using an attributed cherry-pick (`77872972`). No contributor PR was merged or closed. A fresh dependency install resolved js-yaml 4.3.2, and `npm audit --omit=dev --audit-level=high` reports zero vulnerabilities.
+
+The local npm 11 install unexpectedly rewrote the Yarn lock into its legacy format. Only that task-induced rewrite was restored to the committed contributor bytes before subsequent validation. This is installation-tool behavior, not an intended lockfile change. The full test run started on the preceding revision overlapped the dependency update and is excluded from exact-final-head evidence; final PR checks must bind to the updated head.
+
+### Hosted review regressions
+
+The global dry-run parser regression was reproduced before implementation in `c373b7fe`: 27 CLI cases passed and 4 failed. Fix `9b5e3934` removes exact global `--dry-run` flags before command/value parsing, without mutating caller arguments or weakening other validation. All 31 CLI cases and seven independent parser probes pass. Both public entrypoints retain unobserved activation.
+
+Checkpoint `ea00894d` adds seven source-reader regressions for incremental enumeration, the exact per-directory boundary, empty-directory breadth, excluded cache names, handle cleanup and directory identity changes. The corrected reader accepts at most 10,000 names per directory and charges every directory open and enumerated entry against a 20,000-operation reader budget, allowing one lookahead to detect overflow. It retains the file, cumulative-byte and depth bounds. Focused support/registry/compiler checks pass 37/37, including the mandatory ancestor-substitution test with zero redirected file-byte reads.
+
+The source reader was split into focused helpers below 50 lines. Directory handles close in `finally`, and identities are revalidated before and after enumeration. Independent review checked that descriptor no-follow flags, identity checks before the first file byte, post-read checks and exact byte digests survive the extraction. This remains a bounded consistency check, not an atomic filesystem snapshot.
diff --git a/docs/es/AGENTS.md b/docs/es/AGENTS.md
index f19fa7120..c15bf5539 100644
--- a/docs/es/AGENTS.md
+++ b/docs/es/AGENTS.md
@@ -50,13 +50,13 @@ Este es un **plugin de IA para codificación listo para producción** que propor
## Orquestación de Agentes
Usa agentes proactivamente sin prompt del usuario:
-- Solicitudes de features complejas → **planner**
-- Código recién escrito/modificado → **code-reviewer**
-- Corrección de bug o nueva feature → **tdd-guide**
-- Decisión arquitectónica → **architect**
-- Código sensible a la seguridad → **security-reviewer**
-- Bucles autónomos / monitoreo de bucles → **loop-operator**
-- Confiabilidad y costo de la configuración del harness → **harness-optimizer**
+- Solicitudes de features complejas → **ecc:planner**
+- Código recién escrito/modificado → **ecc:code-reviewer**
+- Corrección de bug o nueva feature → **ecc:tdd-guide**
+- Decisión arquitectónica → **ecc:architect**
+- Código sensible a la seguridad → **ecc:security-reviewer**
+- Bucles autónomos / monitoreo de bucles → **ecc:loop-operator**
+- Confiabilidad y costo de la configuración del harness → **ecc:harness-optimizer**
Usa ejecución paralela para operaciones independientes — lanza múltiples agentes simultáneamente.
diff --git a/docs/es/README.md b/docs/es/README.md
index 040b28811..242adb358 100644
--- a/docs/es/README.md
+++ b/docs/es/README.md
@@ -4,13 +4,13 @@

-[](https://github.com/affaan-m/ECC/stargazers)
-[](https://github.com/affaan-m/ECC/network/members)
+[](https://github.com/affaan-m/ECC)
+[](https://github.com/affaan-m/ECC/forks)
[](https://github.com/affaan-m/ECC/graphs/contributors)
[](https://www.npmjs.com/package/ecc-universal)
[](https://www.npmjs.com/package/ecc-agentshield)
[](https://github.com/marketplace/ecc-tools)
-[](LICENSE)
+[](../../LICENSE)



diff --git a/docs/es/rules/common/agents.md b/docs/es/rules/common/agents.md
index 29f25b19e..bb61f7c14 100644
--- a/docs/es/rules/common/agents.md
+++ b/docs/es/rules/common/agents.md
@@ -2,29 +2,36 @@
## Agentes Disponibles
-Ubicados en `~/.claude/agents/`:
+Los agentes de ECC se distribuyen con el plugin `ecc@ecc`, no en `~/.claude/agents/`.
+Se invocan a través de la herramienta Agent con un `subagent_type` con ámbito de plugin:
+
+```text
+Agent(subagent_type: "ecc:planner", prompt: "...")
+```
| Agente | Propósito | Cuándo Usar |
|--------|-----------|-------------|
-| planner | Planificación de implementación | Features complejas, refactoring |
-| architect | Diseño de sistemas | Decisiones arquitectónicas |
-| tdd-guide | Desarrollo guiado por pruebas | Nuevas features, corrección de bugs |
-| code-reviewer | Revisión de código | Después de escribir código |
-| security-reviewer | Análisis de seguridad | Antes de los commits |
-| build-error-resolver | Corrección de errores de build | Cuando el build falla |
-| e2e-runner | Testing E2E | Flujos de usuario críticos |
-| refactor-cleaner | Limpieza de código muerto | Mantenimiento de código |
-| doc-updater | Documentación | Actualización de docs |
-| rust-reviewer | Revisión de código Rust | Proyectos Rust |
-| harmonyos-app-resolver | Desarrollo de apps HarmonyOS | Proyectos HarmonyOS/ArkTS |
+| ecc:planner | Planificación de implementación | Features complejas, refactoring |
+| ecc:architect | Diseño de sistemas | Decisiones arquitectónicas |
+| ecc:tdd-guide | Desarrollo guiado por pruebas | Nuevas features, corrección de bugs |
+| ecc:code-reviewer | Revisión de código | Después de escribir código |
+| ecc:security-reviewer | Análisis de seguridad | Antes de los commits |
+| ecc:build-error-resolver | Corrección de errores de build | Cuando el build falla |
+| ecc:e2e-runner | Testing E2E | Flujos de usuario críticos |
+| ecc:refactor-cleaner | Limpieza de código muerto | Mantenimiento de código |
+| ecc:doc-updater | Documentación | Actualización de docs |
+| ecc:rust-reviewer | Revisión de código Rust | Proyectos Rust |
+| ecc:harmonyos-app-resolver | Desarrollo de apps HarmonyOS | Proyectos HarmonyOS/ArkTS |
+
+Para el roster completo de 68 agentes, ver `/ecc:ecc-guide`.
## Uso Inmediato de Agentes
Sin necesidad de prompt del usuario:
-1. Solicitudes de features complejas - Usar el agente **planner**
-2. Código recién escrito/modificado - Usar el agente **code-reviewer**
-3. Corrección de bug o nueva feature - Usar el agente **tdd-guide**
-4. Decisión arquitectónica - Usar el agente **architect**
+1. Solicitudes de features complejas - Usar el agente **ecc:planner**
+2. Código recién escrito/modificado - Usar el agente **ecc:code-reviewer**
+3. Corrección de bug o nueva feature - Usar el agente **ecc:tdd-guide**
+4. Decisión arquitectónica - Usar el agente **ecc:architect**
## Ejecución Paralela de Tareas
diff --git a/docs/ja-JP/AGENTS.md b/docs/ja-JP/AGENTS.md
index be7370bc0..f32e801b8 100644
--- a/docs/ja-JP/AGENTS.md
+++ b/docs/ja-JP/AGENTS.md
@@ -50,13 +50,13 @@
## エージェントオーケストレーション
ユーザーのプロンプトなしで積極的にエージェントを使用する:
-- 複雑な機能リクエスト → **planner**
-- コードの作成/変更直後 → **code-reviewer**
-- バグ修正または新機能 → **tdd-guide**
-- アーキテクチャの意思決定 → **architect**
-- セキュリティに関わるコード → **security-reviewer**
-- 自律ループ / ループ監視 → **loop-operator**
-- ハーネス設定の信頼性とコスト → **harness-optimizer**
+- 複雑な機能リクエスト → **ecc:planner**
+- コードの作成/変更直後 → **ecc:code-reviewer**
+- バグ修正または新機能 → **ecc:tdd-guide**
+- アーキテクチャの意思決定 → **ecc:architect**
+- セキュリティに関わるコード → **ecc:security-reviewer**
+- 自律ループ / ループ監視 → **ecc:loop-operator**
+- ハーネス設定の信頼性とコスト → **ecc:harness-optimizer**
独立した操作には並列実行を使用する — 複数のエージェントを同時に起動する。
diff --git a/docs/ja-JP/README.md b/docs/ja-JP/README.md
index e01e9c11b..00cc8b62f 100644
--- a/docs/ja-JP/README.md
+++ b/docs/ja-JP/README.md
@@ -1,439 +1,288 @@
-**言語:** [English](../../README.md) | [Português (Brasil)](../pt-BR/README.md) | [简体中文](../../README.zh-CN.md) | [繁體中文](../zh-TW/README.md) | [日本語](README.md) | [한국어](../ko-KR/README.md) | [Türkçe](../tr/README.md) | [Русский](../ru/README.md) | [Tiếng Việt](../vi-VN/README.md) | [ไทย](../th/README.md) | [Deutsch](../de-DE/README.md) | [Українська](../uk-UA/README.md)
+
+
+
-# Everything Claude Code
+
-[](https://github.com/affaan-m/everything-claude-code/stargazers)
-[](https://github.com/affaan-m/everything-claude-code/network/members)
-[](https://github.com/affaan-m/everything-claude-code/graphs/contributors)
-[](LICENSE)
-
-
-
-
-
-
+
+ Language:
+ English |
+ Português (Brasil) |
+ 简体中文 |
+ 繁體中文 |
+ 日本語 |
+ 한국어 |
+ Türkçe |
+ Русский |
+ Tiếng Việt |
+ ไทย |
+ Deutsch |
+ Español |
+ Українська
+
-> **140K+ stars** | **21K+ forks** | **170+ contributors** | **12+ language ecosystems**
+
----
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+> [!WARNING]
+> **公式ソースからのみインストールしてください。** ECC は検証済みのチャネルからのみインストールしてください。GitHub リポジトリ [github.com/affaan-m/ECC](https://github.com/affaan-m/ECC)、npm パッケージ [`ecc-universal`](https://www.npmjs.com/package/ecc-universal) と [`ecc-agentshield`](https://www.npmjs.com/package/ecc-agentshield)、[GitHub App](https://github.com/apps/ecc-tools)、plugin スラッグ `ecc@ecc`、そしてプロジェクト公式サイト [ecc.tools](https://ecc.tools) です。第三者による再アップロードや非公式ミラーはプロジェクトが保守・レビューしておらず、マルウェアを含む可能性があります。
+
+## Claude Code でインストール
+
+[ガイド付きセットアップ](#ecc-のインストール)または[ネイティブ plugin コマンド](#claude-code-の詳細)を使用してください。どちらも同じ `ecc@ecc` plugin をインストールします。どちらか一方を選び、その上にフルの手動 Claude インストールを重ねないでください。
-**言語 / Language / 語言 / Dil / Язык / Ngôn ngữ**
-
-[**English**](../../README.md) | [Português (Brasil)](../pt-BR/README.md) | [简体中文](../../README.zh-CN.md) | [繁體中文](../zh-TW/README.md) | [日本語](README.md) | [한국어](../ko-KR/README.md) | [Türkçe](../tr/README.md) | [Русский](../ru/README.md) | [Tiếng Việt](../vi-VN/README.md) | [ไทย](../th/README.md) | [Deutsch](../de-DE/README.md) | [Українська](../uk-UA/README.md)
-
-
----
-
-**Anthropicハッカソン優勝者による完全なClaude Code設定集。**
-
-10ヶ月以上の集中的な日常使用により、実際のプロダクト構築の過程で進化した、本番環境対応のエージェント、スキル、フック、コマンド、ルール、MCP設定。
-
----
-
-## ガイド
-
-このリポジトリには、原始コードのみが含まれています。ガイドがすべてを説明しています。
-
-
+
-
-
-
-
+
+
+ 
+ ECC Pro + GitHub App
+
+ 無料でインストール · プライベートリポジトリは $19/シート/月から
-
-
-
-
+
+
+ 
+ ECC をスポンサーする
+
+ オープンソースプロジェクトを支援する
+
+
+
+ 
+ コミュニティ
+
+ Discord · Q&A · Show and Tell
-
-
-簡潔ガイド
セットアップ、基礎、哲学。まずこれを読んでください。
-長文ガイド
トークン最適化、メモリ永続化、評価、並列化。
-| トピック | 学べる内容 |
-|-------|-------------------|
-| トークン最適化 | モデル選択、システムプロンプト削減、バックグラウンドプロセス |
-| メモリ永続化 | セッション間でコンテキストを自動保存/読み込みするフック |
-| 継続的学習 | セッションからパターンを自動抽出して再利用可能なスキルに変換 |
-| 検証ループ | チェックポイントと継続的評価、スコアラータイプ、pass@k メトリクス |
-| 並列化 | Git ワークツリー、カスケード方法、スケーリング時期 |
-| サブエージェント オーケストレーション | コンテキスト問題、反復検索パターン |
+
----
+**OSS は今後も無料です。** このリポジトリは永久に MIT ライセンスです。ECC Pro はプライベートリポジトリ向けのホスト型 GitHub App です。スポンサーと Pro 購読者がこの活動を支えています。だからこそ、たった一人のメンテナーが 7 つのハーネスに対して毎週リリースを続けられるのです。
-## 新機能
+
-### v1.4.1 — バグ修正(2026年2月)
+パートナー & スポンサー
-- **instinctインポート時のコンテンツ喪失を修正** — `/instinct-import`実行時に`parse_instinct_file()`がfrontmatter後のすべてのコンテンツ(Action、Evidence、Examplesセクション)を暗黙的に削除していた問題を修正。コミュニティ貢献者@ericcai0814により解決されました([#148](https://github.com/affaan-m/everything-claude-code/issues/148), [#161](https://github.com/affaan-m/everything-claude-code/pull/161))
+
-### v1.4.0 — マルチ言語ルール、インストールウィザード & PM2(2026年2月)
+コミュニティスポンサー: Mike Morgan · @jasonwu513 · @1anter · @massimotodaro · @meadmccabe
-- **インタラクティブインストールウィザード** — 新しい`configure-ecc`スキルがマージ/上書き検出付きガイドセットアップを提供
-- **PM2 & マルチエージェントオーケストレーション** — 複雑なマルチサービスワークフロー管理用の6つの新コマンド(`/pm2`, `/multi-plan`, `/multi-execute`, `/multi-backend`, `/multi-frontend`, `/multi-workflow`)
-- **マルチ言語ルールアーキテクチャ** — ルールをフラットファイルから`common/` + `typescript/` + `python/` + `golang/`ディレクトリに再構成。必要な言語のみインストール可能
-- **中国語(zh-CN)翻訳** — すべてのエージェント、コマンド、スキル、ルールの完全翻訳(80+ファイル)
-- **GitHub Sponsorsサポート** — GitHub Sponsors経由でプロジェクトをスポンサー可能
-- **強化されたCONTRIBUTING.md** — 各貢献タイプ向けの詳細なPRテンプレート
+スポンサーになる · スポンサーティア · スポンサーシッププログラム
-### v1.3.0 — OpenCodeプラグイン対応(2026年2月)
+
-- **フルOpenCode統合** — 20+イベントタイプを通じてOpenCodeのプラグインシステムでフック対応の12エージェント、24コマンド、16スキル
-- **3つのネイティブカスタムツール** — run-tests、check-coverage、security-audit
-- **LLMドキュメンテーション** — 包括的なOpenCodeドキュメント用の`llms.txt`
+
-### v1.2.0 — 統合コマンド & スキル(2026年2月)
+# ECC
-- **Python/Djangoサポート** — Djangoパターン、セキュリティ、TDD、検証スキル
-- **Java Spring Bootスキル** — Spring Boot用パターン、セキュリティ、TDD、検証
-- **セッション管理** — セッション履歴用の`/sessions`コマンド
-- **継続的学習 v2** — 信頼度スコアリング、インポート/エクスポート、進化を伴うinstinctベースの学習
+あなたのエージェントはコードを書けますが、ECC はそこに協調的なエンジニアリングシステムとツールボックスを与えます。構築の前に計画し、テストで変更を検証し、新しいコンテキストから自分の作業をレビューし、重要なことを記憶し、繰り返し成功したことを再利用可能な skills とワークフローに変えていきます。
-完全なチェンジログは[Releases](https://github.com/affaan-m/everything-claude-code/releases)を参照してください。
+```text
+plan -> test -> implement -> review -> verify -> remember -> improve
+```
----
+このプロセスをプロンプトのたびに組み立て直すのではなく、一度インストールしてエージェントの働き方の一部にします。
-## クイックスタート
+> コンテキストウィンドウを最適化し、それ以外はすべて永続化する。
-2分以内に起動できます:
+ECC は MIT ライセンスのオープンソースです。現時点では Claude Code で最もよく機能し、サポート対象の Codex 同期パスを備え、Cursor、OpenCode、Gemini、Zed、GitHub Copilot、Antigravity、Qwen、その他のハーネス向けには機能が限定されたアダプターを提供しています。機能の同等性を前提にする前に、[サポート状況マトリクス](#プラットフォームサポート)を確認してください。
-### ステップ 1:プラグインをインストール
+68 の agents、292 の skills、95 のレガシー command シムに加えて、hooks、rules、メモリ、継続的学習、AgentShield セキュリティスキャンを利用できます。agents は計画、レビュー、ビルド修復、セキュリティ、アーキテクチャ、ドメイン作業に特化しています。
+
+| 含まれるもの | 数 | 得られるもの |
+| ---------------- | ----------: | ------------------------------------------------------------------------------------ |
+| Agents | 68 agents | 計画、レビュー、ビルド修復、セキュリティ、アーキテクチャ、ドメイン作業 |
+| Skills | 292 skills | TDD、リサーチ、セキュリティ、ドキュメント、フロントエンド、データ、ML、運用など |
+| Commands | 95 commands | ECC が skills ファーストの構成へ移行する間の便利なエントリーポイント |
+| Hooks とメモリ | ランタイム | 強制、セッションサマリー、継続的学習、instincts、コンテキスト制御 |
+| Rules | 選択式 | 言語やプロジェクトごとに選ぶ、常時ロードされる標準 |
+| AgentShield | 同梱 | プロンプト、hooks、MCP 設定、パーミッション、シークレット、agent ファイルのスキャン |
+
+
+
+
+
+
+
+
+
+
+## ECC のインストール
+
+> [!IMPORTANT]
+> ECC 2.2 には Claude Code、Codex、Kimi Code 向けのガイド付きパッケージセットアップが含まれています。
+> ユニバーサルパッケージには Node.js 18 以降が必要です。Claude plugin のセットアップには、
+> さらに Git と Claude Code 2.1 以降が `PATH` 上にあることが必要です。
+
+### 推奨: ユニバーサルガイド付きセットアップ
+
+Claude Code plugin のセットアップ、更新、スコープ変更、hook プロファイルの変更には次を使います。
```bash
-# マーケットプレイスを追加
-/plugin marketplace add https://github.com/affaan-m/ECC
+npx ecc-universal@2.2.1 setup
+```
-# プラグインをインストール
+npm がバージョンまたはキャッシュのエラーを報告した場合は、再試行する前にレジストリのバージョンを確認してください。
+
+```bash
+npm view ecc-universal version
+```
+
+ECC 2.2 は、モダンなパッケージランナーでも同じガイド付きセットアップをサポートしています。
+
+| パッケージランナー | ガイド付きセットアップコマンド |
+|---|---|
+| npm / npx | `npx ecc-universal@2.2.1 setup` |
+| pnpm | `pnpm dlx ecc-universal@2.2.1 setup` |
+| Yarn 2+ | `yarn dlx ecc-universal@2.2.1 setup` |
+| Bun | `bunx ecc-universal@2.2.1 setup` |
+
+これらの例では、このリポジトリのリリースバージョンに対応する[公開済みの ECC 2.2.1 リリース](https://www.npmjs.com/package/ecc-universal/v/2.2.1)を指定しています。バージョンのピン留めはセキュリティ監査でも整合性チェックでもありません。パッケージのコードを実行する前にリリースのソースとレジストリの整合性を確認し、未リリースの変更にはレビュー済みのチェックアウトを使用してください。
+
+Yarn Classic 1 には `yarn dlx` がありません。`npx` を使うか、パッケージをグローバルにインストールするか、一時的なワンショット実行のために Yarn をアップグレードしてください。
+
+ウィザードは変更を加える前に公式マーケットプレイスとすべてのネイティブ Claude インストールスコープを棚卸しし、その後、選択したスコープに `ecc@ecc` をインストール、更新、または安全に移動します。ECC を更新したいとき、スコープを変えたいとき、hook プロファイルを変えたいときは、いつでも同じコマンドを再実行してください。このセットアップウィザードが現在設定するのは Claude Code plugin です。Codex や Kimi Code には、下記のマルチハーネスウィザードを使用してください。
+
+複数のコーディングエージェントを一つのレビュー済みフローで設定するには、マルチハーネスウィザードを使用します。
+
+```bash
+npx ecc-universal@2.2.1 install --guided
+```
+
+Claude Code、Codex、Kimi Code の任意の組み合わせを選択でき、各インストールチャネルと配置先を表示し、最初の書き込み前にすべての選択をプリフライトし、最後に一度だけ確認を求めます。
+
+| ハーネス | ガイド付きインストールの動作 |
+|---|---|
+| Claude Code | `user`、`project`、`local` のいずれか一つのスコープと ECC hook プロファイルを持つネイティブ `ecc@ecc` plugin |
+| Codex | ネイティブ Codex マーケットプレイス/plugin ライフサイクル。hook のレビューと信頼は Codex 側が管理 |
+| Kimi Code | `./.kimi-code` 配下の管理されたプロジェクトファイル。ECC hooks、モデル/プロバイダー設定、認証は設定されません |
+
+自動化のためには、プロバイダー固有の選択をすべて明示してください。
+
+```bash
+npx ecc-universal@2.2.1 install --guided \
+ --harness claude --harness codex --harness kimi \
+ --claude-scope local --claude-hooks standard \
+ --profile core --yes
+```
+
+ネイティブのガイド付き Codex パスと管理された Kimi パスを、書き込みなしで先に検証するには次を実行します。
+
+```bash
+npx ecc-universal@2.2.1 install --guided --harness codex --dry-run
+npx ecc-universal@2.2.1 install --profile core --target kimi --dry-run
+```
+
+2.2 エイリアスを通じて、追加のパッケージ名コマンドも利用できます。
+
+```bash
+npx ecc-universal@2.2.1 consult "security reviews" --target claude
+npx ecc-universal@2.2.1 install --profile minimal --target claude --with capability:machine-learning
+npx ecc-universal@2.2.1 doctor --target kimi
+```
+
+`npx ecc-install --profile minimal --target claude` は使用しないでください。`ecc-install` は `ecc-universal` 内のバイナリ名であり、個別に公開された npm パッケージではありません。
+
+ECC は `cursor`、`antigravity`、`gemini`、`opencode`、`codebuddy`、`joycode`、`qwen`、`zed`、`hermes`、`openclaw` 向けの高度な管理アダプターも提供しています。これらのターゲットは、各アダプターがガイド付きの衝突、更新、修復、アンインストールのライフサイクルマトリクスを通過するまで、ドキュメント化された `ecc install --target ...` パスを引き続き使用します。どちらのウィザードも、検出されたすべてのハーネスに黙ってインストールすることはありません。
+
+### パスは一つだけ選ぶ(ハーネスごと)
+
+ECC は Claude Code、Codex、その他のハーネスで同時に使用できます。ハーネスごとに一つのインストール方法を選んでください。
+
+- **推奨デフォルト:** 上記のガイド付き Claude plugin セットアップを実行する
+- **Claude Code でもサポート:** [ネイティブ plugin コマンド](#claude-code-の詳細)を使用する
+- **リリース 2.2 で利用可能:** Claude Code、Codex、Kimi Code 向けのガイド付きパッケージセットアップ
+- **動作します:** Claude Code plugin + Codex ネイティブ plugin
+- **動作します:** Claude Code plugin + レガシー Codex 同期フロー
+- **避けてください:** Claude Code plugin + フル Claude 手動インストール
+- **避けてください:** Codex 同期 + Codex マーケットプレイス plugin
+
+**インストール方法を重ねないでください。** 同じハーネスに ECC を二度インストールすると、skills、commands、hooks、設定が重複することがあります。複数のハーネスにそれぞれ一度ずつインストールする分には問題ありません。
+
+すでに複数のインストールを重ねてしまい、重複しているように見える場合は、[ECC のリセット / アンインストール](#ecc-のリセット--アンインストール)に直接進んでください。
+
+**インストールで困っていますか?** 短い[インストールまたはランタイムの問題フォーム](https://github.com/affaan-m/ECC/issues/new?template=install-problem.yml)を開くか、`ecc feedback` を実行してください。ECC が診断情報を自動でアップロードすることはありません。
+
+### Claude Code の詳細
+
+代わりに、Claude Code 内で Claude Code のネイティブ plugin コマンドを実行することもできます。
+
+```text
+/plugin marketplace add https://github.com/affaan-m/ECC
/plugin install ecc@ecc
```
-### ステップ2:ルールをインストール(必須)
+ネイティブパスは ECC の skills、agents、commands、および plugin 管理の hooks をインストールします。この方法を選んだ場合は、そこで止めてください。Claude Code にフルの手動インストールを追加で実行しないでください。
-> WARNING: **重要:** Claude Codeプラグインは`rules`を自動配布できません。手動でインストールしてください:
+これらの組み込みコマンドは Claude Code が所有しており、マーケットプレイス、plugin、または競合するスコープがすでに存在する場合のエラーも同様です。ECC はそのパーサーに介入できません。いずれかのネイティブコマンドが既存のインストールやスコープの競合を報告した場合は、2.2 のガイド付きセットアップを使用するか、競合している Claude plugin スコープを解決してから再試行してください。その上に手動インストールを重ねないでください。
+
+ECC のインストール後は、`/ecc:configure-ecc` が名前空間付きの Claude 内再設定 skill になります。これは同じ安全なセットアップフローに委譲しますが、plugin のインストール後にのみ利用可能で、初回インストール時に Claude Code 組み込みの `/plugin` コマンドを置き換えることはできません。
+
+Claude Code plugins は `rules` を配布できないため、本当に必要な rule パックだけを追加してください。
```bash
-# まずリポジトリをクローン
-git clone https://github.com/affaan-m/everything-claude-code.git
-
-# 共通ルールをインストール(必須)
-cp -r everything-claude-code/rules/common ~/.claude/rules/common
-
-# 言語固有ルールをインストール(スタックを選択)
-cp -r everything-claude-code/rules/typescript ~/.claude/rules/typescript
-cp -r everything-claude-code/rules/python ~/.claude/rules/python
-cp -r everything-claude-code/rules/golang ~/.claude/rules/golang
+git clone https://github.com/affaan-m/ECC.git
+cd ECC
+mkdir -p ~/.claude/rules/ecc
+cp -R rules/common ~/.claude/rules/ecc/
+cp -R rules/typescript ~/.claude/rules/ecc/ # 使用しているスタックに置き換えてください
```
-### ステップ3:使用開始
+`rules/common` と、実際に使用している言語またはフレームワークのパックを一つ入れるところから始めてください。plugin をインストールした場合は、その後で `./install.sh --profile full` を実行しないでください。
-```bash
-# コマンドを試す(プラグインはネームスペース形式)
-/ecc:plan "ユーザー認証を追加"
+
+settings.json 派ですか?マーケットプレイスを宣言的に追加する
-# 手動インストール(オプション2)は短縮形式:
-# /plan "ユーザー認証を追加"
-
-# 利用可能なコマンドを確認
-/plugin list ecc@ecc
-```
-
-**完了です!** これで13のエージェント、43のスキル、31のコマンドにアクセスできます。
-
----
-
-## クロスプラットフォーム対応
-
-このプラグインは **Windows、macOS、Linux** を完全にサポートしています。すべてのフックとスクリプトが Node.js で書き直され、最大の互換性を実現しています。
-
-### パッケージマネージャー検出
-
-プラグインは、以下の優先順位で、お好みのパッケージマネージャー(npm、pnpm、yarn、bun)を自動検出します:
-
-1. **環境変数**: `CLAUDE_PACKAGE_MANAGER`
-2. **プロジェクト設定**: `.claude/package-manager.json`
-3. **package.json**: `packageManager` フィールド
-4. **ロックファイル**: package-lock.json、yarn.lock、pnpm-lock.yaml、bun.lockb から検出
-5. **グローバル設定**: `~/.claude/package-manager.json`
-6. **フォールバック**: 最初に利用可能なパッケージマネージャー
-
-お好みのパッケージマネージャーを設定するには:
-
-```bash
-# 環境変数経由
-export CLAUDE_PACKAGE_MANAGER=pnpm
-
-# グローバル設定経由
-node scripts/setup-package-manager.js --global pnpm
-
-# プロジェクト設定経由
-node scripts/setup-package-manager.js --project bun
-
-# 現在の設定を検出
-node scripts/setup-package-manager.js --detect
-```
-
-または Claude Code で `/setup-pm` コマンドを使用。
-
----
-
-## 含まれるもの
-
-このリポジトリは**Claude Codeプラグイン**です - 直接インストールするか、コンポーネントを手動でコピーできます。
-
-```
-everything-claude-code/
-|-- .claude-plugin/ # プラグインとマーケットプレイスマニフェスト
-| |-- plugin.json # プラグインメタデータとコンポーネントパス
-| |-- marketplace.json # /plugin marketplace add 用のマーケットプレイスカタログ
-|
-|-- agents/ # 委任用の専門サブエージェント
-| |-- planner.md # 機能実装計画
-| |-- architect.md # システム設計決定
-| |-- tdd-guide.md # テスト駆動開発
-| |-- code-reviewer.md # 品質とセキュリティレビュー
-| |-- security-reviewer.md # 脆弱性分析
-| |-- build-error-resolver.md
-| |-- e2e-runner.md # Playwright E2E テスト
-| |-- refactor-cleaner.md # デッドコード削除
-| |-- doc-updater.md # ドキュメント同期
-| |-- go-reviewer.md # Go コードレビュー
-| |-- go-build-resolver.md # Go ビルドエラー解決
-| |-- python-reviewer.md # Python コードレビュー(新規)
-| |-- database-reviewer.md # データベース/Supabase レビュー(新規)
-|
-|-- skills/ # ワークフロー定義と領域知識
-| |-- coding-standards/ # 言語ベストプラクティス
-| |-- backend-patterns/ # API、データベース、キャッシュパターン
-| |-- frontend-patterns/ # React、Next.js パターン
-| |-- continuous-learning/ # セッションからパターンを自動抽出(長文ガイド)
-| |-- continuous-learning-v2/ # 信頼度スコア付き直感ベース学習
-| |-- iterative-retrieval/ # サブエージェント用の段階的コンテキスト精製
-| |-- strategic-compact/ # 手動圧縮提案(長文ガイド)
-| |-- tdd-workflow/ # TDD 方法論
-| |-- security-review/ # セキュリティチェックリスト
-| |-- eval-harness/ # 検証ループ評価(長文ガイド)
-| |-- verification-loop/ # 継続的検証(長文ガイド)
-| |-- golang-patterns/ # Go イディオムとベストプラクティス
-| |-- golang-testing/ # Go テストパターン、TDD、ベンチマーク
-| |-- cpp-testing/ # C++ テスト GoogleTest、CMake/CTest(新規)
-| |-- django-patterns/ # Django パターン、モデル、ビュー(新規)
-| |-- django-security/ # Django セキュリティベストプラクティス(新規)
-| |-- django-tdd/ # Django TDD ワークフロー(新規)
-| |-- django-verification/ # Django 検証ループ(新規)
-| |-- python-patterns/ # Python イディオムとベストプラクティス(新規)
-| |-- python-testing/ # pytest を使った Python テスト(新規)
-| |-- quarkus-patterns/ # Quarkus アーキテクチャ、Camel、CDI、Panache パターン(新規)
-| |-- quarkus-security/ # Quarkus セキュリティ: JWT/OIDC、RBAC、バリデーション(新規)
-| |-- quarkus-tdd/ # Quarkus TDD: JUnit 5、Mockito、REST Assured(新規)
-| |-- quarkus-verification/ # Quarkus 検証: ビルド、テスト、ネイティブコンパイル(新規)
-| |-- springboot-patterns/ # Java Spring Boot パターン(新規)
-| |-- springboot-security/ # Spring Boot セキュリティ(新規)
-| |-- springboot-tdd/ # Spring Boot TDD(新規)
-| |-- springboot-verification/ # Spring Boot 検証(新規)
-| |-- configure-ecc/ # インタラクティブインストールウィザード(新規)
-| |-- security-scan/ # AgentShield セキュリティ監査統合(新規)
-|
-|-- commands/ # スラッシュコマンド用クイック実行
-| |-- tdd.md # /tdd - テスト駆動開発
-| |-- plan.md # /plan - 実装計画
-| |-- e2e.md # /e2e - E2E テスト生成
-| |-- code-review.md # /code-review - 品質レビュー
-| |-- build-fix.md # /build-fix - ビルドエラー修正
-| |-- refactor-clean.md # /refactor-clean - デッドコード削除
-| |-- learn.md # /learn - セッション中のパターン抽出(長文ガイド)
-| |-- checkpoint.md # /checkpoint - 検証状態を保存(長文ガイド)
-| |-- verify.md # /verify - 検証ループを実行(長文ガイド)
-| |-- setup-pm.md # /setup-pm - パッケージマネージャーを設定
-| |-- go-review.md # /go-review - Go コードレビュー(新規)
-| |-- go-test.md # /go-test - Go TDD ワークフロー(新規)
-| |-- go-build.md # /go-build - Go ビルドエラーを修正(新規)
-| |-- skill-create.md # /skill-create - Git 履歴からスキルを生成(新規)
-| |-- instinct-status.md # /instinct-status - 学習した直感を表示(新規)
-| |-- instinct-import.md # /instinct-import - 直感をインポート(新規)
-| |-- instinct-export.md # /instinct-export - 直感をエクスポート(新規)
-| |-- evolve.md # /evolve - 直感をスキルにクラスタリング
-| |-- pm2.md # /pm2 - PM2 サービスライフサイクル管理(新規)
-| |-- multi-plan.md # /multi-plan - マルチエージェント タスク分解(新規)
-| |-- multi-execute.md # /multi-execute - オーケストレーション マルチエージェント ワークフロー(新規)
-| |-- multi-backend.md # /multi-backend - バックエンド マルチサービス オーケストレーション(新規)
-| |-- multi-frontend.md # /multi-frontend - フロントエンド マルチサービス オーケストレーション(新規)
-| |-- multi-workflow.md # /multi-workflow - 一般的なマルチサービス ワークフロー(新規)
-|
-|-- rules/ # 常に従うべきガイドライン(~/.claude/rules/ にコピー)
-| |-- README.md # 構造概要とインストールガイド
-| |-- common/ # 言語非依存の原則
-| | |-- coding-style.md # イミュータビリティ、ファイル組織
-| | |-- git-workflow.md # コミットフォーマット、PR プロセス
-| | |-- testing.md # TDD、80% カバレッジ要件
-| | |-- performance.md # モデル選択、コンテキスト管理
-| | |-- patterns.md # デザインパターン、スケルトンプロジェクト
-| | |-- hooks.md # フック アーキテクチャ、TodoWrite
-| | |-- agents.md # サブエージェントへの委任時機
-| | |-- security.md # 必須セキュリティチェック
-| |-- typescript/ # TypeScript/JavaScript 固有
-| |-- python/ # Python 固有
-| |-- golang/ # Go 固有
-|
-|-- hooks/ # トリガーベースの自動化
-| |-- hooks.json # すべてのフック設定(PreToolUse、PostToolUse、Stop など)
-| |-- memory-persistence/ # セッションライフサイクルフック(長文ガイド)
-| |-- strategic-compact/ # 圧縮提案(長文ガイド)
-|
-|-- scripts/ # クロスプラットフォーム Node.js スクリプト(新規)
-| |-- lib/ # 共有ユーティリティ
-| | |-- utils.js # クロスプラットフォーム ファイル/パス/システムユーティリティ
-| | |-- package-manager.js # パッケージマネージャー検出と選択
-| |-- hooks/ # フック実装
-| | |-- session-start.js # セッション開始時にコンテキストを読み込む
-| | |-- session-end.js # セッション終了時に状態を保存
-| | |-- pre-compact.js # 圧縮前の状態保存
-| | |-- suggest-compact.js # 戦略的圧縮提案
-| | |-- evaluate-session.js # セッションからパターンを抽出
-| |-- setup-package-manager.js # インタラクティブ PM セットアップ
-|
-|-- tests/ # テストスイート(新規)
-| |-- lib/ # ライブラリテスト
-| |-- hooks/ # フックテスト
-| |-- run-all.js # すべてのテストを実行
-|
-|-- contexts/ # 動的システムプロンプト注入コンテキスト(長文ガイド)
-| |-- dev.md # 開発モード コンテキスト
-| |-- review.md # コードレビューモード コンテキスト
-| |-- research.md # リサーチ/探索モード コンテキスト
-|
-|-- examples/ # 設定例とセッション
-| |-- CLAUDE.md # プロジェクトレベル設定例
-| |-- user-CLAUDE.md # ユーザーレベル設定例
-|
-|-- mcp-configs/ # MCP サーバー設定
-| |-- mcp-servers.json # GitHub、Supabase、Vercel、Railway など
-|
-|-- marketplace.json # 自己ホストマーケットプレイス設定(/plugin marketplace add 用)
-```
-
----
-
-## エコシステムツール
-
-### スキル作成ツール
-
-リポジトリから Claude Code スキルを生成する 2 つの方法:
-
-#### オプション A:ローカル分析(ビルトイン)
-
-外部サービスなしで、ローカル分析に `/skill-create` コマンドを使用:
-
-```bash
-/skill-create # 現在のリポジトリを分析
-/skill-create --instincts # 継続的学習用の直感も生成
-```
-
-これはローカルで Git 履歴を分析し、SKILL.md ファイルを生成します。
-
-#### オプション B:GitHub アプリ(高度な機能)
-
-高度な機能用(10k+ コミット、自動 PR、チーム共有):
-
-[GitHub アプリをインストール](https://github.com/apps/skill-creator) | [ecc.tools](https://ecc.tools)
-
-```bash
-# 任意の Issue にコメント:
-/skill-creator analyze
-
-# またはデフォルトブランチへのプッシュで自動トリガー
-```
-
-両オプションで生成されるもの:
-- **SKILL.mdファイル** - Claude Codeですぐに使えるスキル
-- **instinctコレクション** - continuous-learning-v2用
-- **パターン抽出** - コミット履歴からの学習
-
-### AgentShield — セキュリティ監査ツール
-
-Claude Code 設定の脆弱性、誤設定、インジェクションリスクをスキャンします。
-
-```bash
-# クイックスキャン(インストール不要)
-npx ecc-agentshield scan
-
-# 安全な問題を自動修正
-npx ecc-agentshield scan --fix
-
-# Opus 4.6 による深い分析
-npx ecc-agentshield scan --opus --stream
-
-# ゼロから安全な設定を生成
-npx ecc-agentshield init
-```
-
-CLAUDE.md、settings.json、MCP サーバー、フック、エージェント定義をチェックします。セキュリティグレード(A-F)と実行可能な結果を生成します。
-
-Claude Codeで`/security-scan`を実行、または[GitHub Action](https://github.com/affaan-m/agentshield)でCIに追加できます。
-
-[GitHub](https://github.com/affaan-m/agentshield) | [npm](https://www.npmjs.com/package/ecc-agentshield)
-
-### 継続的学習 v2
-
-instinctベースの学習システムがパターンを自動学習:
-
-```bash
-/instinct-status # 信頼度付きで学習したinstinctを表示
-/instinct-import # 他者のinstinctをインポート
-/instinct-export # instinctをエクスポートして共有
-/evolve # 関連するinstinctをスキルにクラスタリング
-```
-
-完全なドキュメントは`skills/continuous-learning-v2/`を参照してください。
-
----
-
-## 要件
-
-### Claude Code CLI バージョン
-
-**最小バージョン: v2.1.0 以上**
-
-このプラグインは Claude Code CLI v2.1.0+ が必要です。プラグインシステムがフックを処理する方法が変更されたためです。
-
-バージョンを確認:
-```bash
-claude --version
-```
-
-### 重要: フック自動読み込み動作
-
-> WARNING: **貢献者向け:** `.claude-plugin/plugin.json`に`"hooks"`フィールドを追加しないでください。これは回帰テストで強制されます。
-
-Claude Code v2.1+は、インストール済みプラグインの`hooks/hooks.json`(規約)を自動読み込みします。`plugin.json`で明示的に宣言するとエラーが発生します:
-
-```
-Duplicate hook file detected: ./hooks/hooks.json is already resolved to a loaded file
-```
-
-**背景:** これは本リポジトリで複数の修正/リバート循環を引き起こしました([#29](https://github.com/affaan-m/everything-claude-code/issues/29), [#52](https://github.com/affaan-m/everything-claude-code/issues/52), [#103](https://github.com/affaan-m/everything-claude-code/issues/103))。Claude Codeバージョン間で動作が変わったため混乱がありました。今後を防ぐため回帰テストがあります。
-
----
-
-## インストール
-
-### オプション1:プラグインとしてインストール(推奨)
-
-このリポジトリを使用する最も簡単な方法 - Claude Codeプラグインとしてインストール:
-
-```bash
-# このリポジトリをマーケットプレイスとして追加
-/plugin marketplace add https://github.com/affaan-m/ECC
-
-# プラグインをインストール
-/plugin install ecc@ecc
-```
-
-または、`~/.claude/settings.json` に直接追加:
+`~/.claude/settings.json` に直接追加します。
```json
{
@@ -441,7 +290,7 @@ Duplicate hook file detected: ./hooks/hooks.json is already resolved to a loaded
"ecc": {
"source": {
"source": "github",
- "repo": "affaan-m/everything-claude-code"
+ "repo": "affaan-m/ECC"
}
}
},
@@ -451,102 +300,785 @@ Duplicate hook file detected: ./hooks/hooks.json is already resolved to a loaded
}
```
-これで、すべてのコマンド、エージェント、スキル、フックにすぐにアクセスできます。
+これにより、上記の二つの `/plugin` コマンドと同じ結果が得られます。
+
-> **注:** Claude Codeプラグインシステムは`rules`をプラグイン経由で配布できません([アップストリーム制限](https://code.claude.com/docs/en/plugins-reference))。ルールは手動でインストールする必要があります:
->
-> ```bash
-> # まずリポジトリをクローン
-> git clone https://github.com/affaan-m/everything-claude-code.git
->
-> # オプション A:ユーザーレベルルール(すべてのプロジェクトに適用)
-> mkdir -p ~/.claude/rules
-> cp -r everything-claude-code/rules/common ~/.claude/rules/common
-> cp -r everything-claude-code/rules/typescript ~/.claude/rules/typescript # スタックを選択
-> cp -r everything-claude-code/rules/python ~/.claude/rules/python
-> cp -r everything-claude-code/rules/golang ~/.claude/rules/golang
->
-> # オプション B:プロジェクトレベルルール(現在のプロジェクトのみ)
-> mkdir -p .claude/rules
-> cp -r everything-claude-code/rules/common .claude/rules/common
-> cp -r everything-claude-code/rules/typescript .claude/rules/typescript # スタックを選択
-> ```
+
+命名と移行に関する注記(ecc@ecc、affaan-m/ECC、ecc-universal)
----
+ECC には三つの公開識別子があり、これらは互いに置き換えられません。
-### オプション2:手動インストール
+- GitHub ソースリポジトリ: `affaan-m/ECC`
+- Claude マーケットプレイス/plugin 識別子: `ecc@ecc`
+- npm パッケージ: `ecc-universal`
-インストール内容を手動で制御したい場合:
+これは意図的なものです。Anthropic のマーケットプレイス/plugin インストールは正規の plugin 識別子をキーとするため、ECC は厳格な Desktop/API バリデーターに対してツール名とスラッシュコマンドの名前空間を十分に短く保つために `ecc@ecc` を使用しています。古い投稿には以前の長いマーケットプレイス識別子が残っている場合がありますが、それはレガシーエイリアスとしてのみ扱ってください。一方、npm パッケージは `ecc-universal` のままなので、npm インストールとマーケットプレイスインストールは意図的に異なる名前を使用しています。
+
+npm リリースはコミットごとではなくバージョンタグごとに切られるため、`ecc-universal` は `main` へのすべてのプッシュではなく、リリース(2.1、2.2、...)を追跡します。最新の開発版が必要な場合は git からインストールしてください。
+
+ローカルの Claude セットアップが消去またはリセットされた場合でも、何かを買い直す必要があるわけではありません。まず `node scripts/ecc.js list-installed` から始め、次に `node scripts/ecc.js doctor` と `node scripts/ecc.js repair` を実行してから再インストールしてください。通常はこれで、セットアップを組み直すことなく ECC 管理のファイルが復元されます。
+
+
+### Codex App と CLI
+
+現在の Codex リリースでは、ECC をネイティブのリポジトリマーケットプレイス plugin としてインストールできます。マーケットプレイスエントリはリポジトリルートを使用するため、Codex のキャッシュはマニフェストとともに、参照されるすべての skills、MCP 設定、hook ランタイム、スクリプト、アセットを受け取ります。
```bash
-# リポジトリをクローン
-git clone https://github.com/affaan-m/everything-claude-code.git
-
-# エージェントを Claude 設定にコピー
-cp everything-claude-code/agents/*.md ~/.claude/agents/
-
-# ルール(共通 + 言語固有)をコピー
-cp -r everything-claude-code/rules/common ~/.claude/rules/common
-cp -r everything-claude-code/rules/typescript ~/.claude/rules/typescript # スタックを選択
-cp -r everything-claude-code/rules/python ~/.claude/rules/python
-cp -r everything-claude-code/rules/golang ~/.claude/rules/golang
-
-# コマンドをコピー
-cp everything-claude-code/commands/*.md ~/.claude/commands/
-
-# スキルをコピー
-cp -r everything-claude-code/skills/* ~/.claude/skills/
+codex plugin marketplace add affaan-m/ECC
+codex plugin add ecc@ecc
+codex plugin list --json
+node scripts/codex/check-plugin-cache.js
```
-#### settings.json にフックを追加
+どちらの add コマンドも冪等です。後で更新するには、`codex plugin marketplace upgrade ecc` に続けて `codex plugin add ecc@ecc` を実行します。Codex はアクティブな `CODEX_HOME` に一つの有効化された plugin 状態を保存し、Claude の `user`、`project`、`local` スコープは提供しません。そのネイティブ hooks は明示的な信頼の決定を必要とし、Claude の四つの ECC hook プロファイルは使用しません。Codex 内では、ガイド付きのプロバイダー対応フローとして `$configure-ecc` を呼び出してください。
-手動インストール時のみ、`hooks/hooks.json` のフックを `~/.claude/settings.json` にコピーします。
+従来の `scripts/sync-ecc-to-codex.sh` パスは、`~/.codex` にコピーおよびマージされた設定を意図的に必要とするユーザー向けの非推奨互換オプションであり、ネイティブ plugin には不要です。新しい同期の実行では所有権マニフェストを書き出すため、クリーンアップ時に変更されたユーザーファイルを保護できます。まず Codex を一度実行して `~/.codex/config.toml` が存在する状態にしてから、次を実行します。
-`/plugin install` で ECC を導入した場合は、これらのフックを `settings.json` にコピーしないでください。Claude Code v2.1+ はプラグインの `hooks/hooks.json` を自動読み込みするため、二重登録すると重複実行や `${CLAUDE_PLUGIN_ROOT}` の解決失敗が発生します。
+```bash
+git clone https://github.com/affaan-m/ECC.git
+cd ECC
+npm install
+bash scripts/sync-ecc-to-codex.sh
+```
-#### MCP を設定
+Codex の会話やネイティブ plugin キャッシュに触れずに、そのレガシーレイヤーを確認または削除するには次を実行します。
-`mcp-configs/mcp-servers.json` から必要な MCP サーバーを `~/.claude.json` にコピーします。
+```bash
+node scripts/ecc.js uninstall --legacy-codex-sync --dry-run
+node scripts/ecc.js uninstall --legacy-codex-sync
+```
-**重要:** `YOUR_*_HERE`プレースホルダーを実際のAPIキーに置き換えてください。
+マニフェスト以前のインストールは保守的に扱われます。ECC はマークされた `AGENTS.md` ブロックを削除しますが、所有を証明できないコピー済みファイルは保持し、レビュー用に報告します。
----
+プロジェクトローカルのセットアップとして、ECC リポジトリを Codex で直接開くこともできます。Codex はグローバル同期なしで、ルートの `AGENTS.md` と `.codex/` 内の信頼済みプロジェクト設定を読み取ります。同期フローの上にネイティブマーケットプレイス plugin を追加しないでください。
-## 主要概念
+リポジトリのナビゲーション、サーフェスの所有権、PR 差分パケットのガイダンスについては、[Codex ECC Navigation Map](../CODEX-NAVIGATION-GUIDE.md) を参照してください。ネイティブライフサイクルの詳細は [.codex plugin notes](../../.codex-plugin/README.md) を参照してください。
-### エージェント
+### その他のエージェントとエディター
-サブエージェントは限定的な範囲のタスクを処理します。例:
+
+Cursor、OpenCode、Gemini、Zed、Antigravity、Qwen、Hermes、OpenClaw、Kimi、CodeBuddy、JoyCode、Copilot
+
+ECC を一度クローンし、使用しているハーネスに合ったターゲットを選択します。
+
+```bash
+git clone https://github.com/affaan-m/ECC.git
+cd ECC
+```
+
+| ハーネス | インストールまたはセットアップ | 備考 |
+|---|---|---|
+| Cursor | `./install.sh --profile minimal --target cursor` | プロジェクトローカルの `.cursor/` アダプター |
+| OpenCode | `npm install && npm run build:opencode && ./install.sh --profile full --target opencode --enable-hooks` | フルインストールの前に plugin ペイロードをビルド |
+| Gemini CLI | `./install.sh --profile minimal --target gemini` | プロジェクトローカルの `.gemini/` 設定 |
+| Zed | `./install.sh --profile minimal --target zed` | プロジェクトローカルの `.zed/` アダプター |
+| Antigravity | `./install.sh --profile minimal --target antigravity` | [Antigravity ガイド](../ANTIGRAVITY-GUIDE.md)を参照 |
+| Qwen CLI | `./install.sh --profile minimal --target qwen` | [Qwen ガイド](../QWEN-GUIDE.md)を参照 |
+| Hermes | `./install.sh --profile minimal --target hermes` | [Hermes セットアップガイド](../HERMES-SETUP.md)を参照 |
+| OpenClaw | `./install.sh --profile minimal --target openclaw` | 管理されたホームディレクトリインストール |
+| Kimi Code CLI | `./install.sh --profile minimal --target kimi` | プロジェクトローカルの `.kimi-code/` インストール · [Kimi Code を入手](https://www.kimi.ai/code?aff=ecc) |
+| CodeBuddy | `./install.sh --profile minimal --target codebuddy` | プロジェクトローカルの `.codebuddy/` インストール |
+| JoyCode | `./install.sh --profile minimal --target joycode` | プロジェクトローカルの `.joycode/` インストール |
+
+GitHub Copilot のサポートはすでにこのリポジトリに含まれています。`.github/copilot-instructions.md` が指示レイヤーを提供し、`.github/prompts/` には再利用可能な `/plan`、`/tdd`、`/security-review`、`/build-fix`、`/refactor` のプロンプトが含まれ、`.vscode/settings.json` が `chat.promptFiles` を有効にします。
+
+ネイティブの ECC ターゲットがないハーネスには、[手動適用ガイド](../MANUAL-ADAPTATION-GUIDE.md)を使用してください。hooks やネイティブの skill 検出が利用できるふりをせずに、少数の ECC skills とワークフロー指示をチャット型ツールに持ち込む方法を説明しています。
+
+Cursor は agent 定義を `.cursor/agents/ecc-*.md` 配下にインストールします。Cursor ネイティブのロード動作は Cursor のビルドによって異なる場合があります。ECC はルートの `AGENTS.md` を `.cursor/` にインストールしません。このアダプターは Cursor のコンテキストをネイティブの rules と agent サーフェスに限定します。
+
+ハーネスごとの詳細な注記(機能の同等性、hook アダプター、制限事項)は、下記の[プラットフォームサポート](#プラットフォームサポート)にあります。
+
+
+## 高度なインストールオプション
+
+
+hook ランタイムなしの低コンテキストインストール
+
+### 低コンテキスト / hooks なしパス
+
+ランタイム hooks なしで ECC の rules、agents、commands、プラットフォーム設定、コアワークフローを使いたい場合はこちらを使用します。
+
+```bash
+npx ecc-universal@2.2.1 install --profile minimal --target claude
+```
+
+ソースチェックアウトからの同等のコマンドは次のとおりです。
+
+```bash
+./install.sh --profile minimal --target claude
+```
+
+Windows:
+
+```powershell
+.\install.ps1 --profile minimal --target claude
+```
+
+このプロファイルは意図的に `hooks-runtime` を除外しています。
+
+Claude の手動インストールでは、Claude Code が検出できるように各 skill を `~/.claude/skills//`(`claude-project` の場合は `.claude/skills//`)の直下に配置します。古い ECC 手動インストールをアップグレードする場合、インストーラーは ECC のインストール状態に記録されたネストされた `skills/ecc/` ファイルのみを移行します。フラットな skill ディレクトリがユーザー所有の場合、ECC はそれを保持して競合の警告を表示し、ユーザーファイルを上書きする代わりに、古い管理コピーを安全なアンインストールのために追跡し続けます。
+
+hooks を無効にした通常の core プロファイルの場合:
+
+```bash
+./install.sh --profile core --without baseline:hooks --target claude
+./install.sh --profile core --no-hooks --target claude
+```
+
+hook ランタイムが必要になった場合にのみ、後から追加します。
+
+```bash
+./install.sh --target claude --modules hooks-runtime --enable-hooks
+```
+
+プロファイルまたはモジュールによって hook ランタイムが実体化されるインストールでは、
+明示的な決定が必要です。`--enable-hooks` も `--no-hooks` も指定されていない場合、
+インストーラーは hooks でできることを表示し、何も書き込まずに停止します。ガイド付き
+インストーラー(`ecc install --guided`)はこの選択を対話的に尋ねます。
+
+
+
+必要なコンポーネントだけを選ぶ
+
+### まず適切なコンポーネントを見つける
+
+同梱のアドバイザーに、あなたの作業に合うコンポーネントを尋ねてください。
+
+```bash
+node scripts/ecc.js consult "security reviews" --target claude
+```
+
+一致するコンポーネント、関連するプロファイル、プレビュー/インストールコマンドが返されます。正確なファイル計画を確認したい場合は、インストール前にプレビューコマンドを使用してください。
+
+明示的に skills や capability を指定してインストールすることもできます。
+
+```bash
+./install.sh --target claude --skills tdd-workflow,security-review
+node scripts/ecc.js install --profile minimal --target claude --with capability:machine-learning
+```
+
+コンポーネントごとの手動コピーも可能です。各コンポーネントは完全に独立しています。
+
+```bash
+# agents のみ
+cp agents/*.md ~/.claude/agents/
+
+# rules ディレクトリ(common + 言語固有)
+mkdir -p ~/.claude/rules/ecc
+cp -r rules/common ~/.claude/rules/ecc/
+cp -r rules/typescript ~/.claude/rules/ecc/ # 使用しているスタックを選択
+
+# コア/汎用 skills のみ(Claude Code は ~/.claude/skills の直下から skills をロードします。
+# 手動インストールを ~/.claude/skills/ecc/ 配下にネストしないでください)
+mkdir -p ~/.claude/skills
+cp -r .agents/skills/* ~/.claude/skills/
+cp -r skills/search-first ~/.claude/skills/
+
+# オプション: 移行期間中に維持されるスラッシュコマンド互換
+mkdir -p ~/.claude/commands
+cp commands/*.md ~/.claude/commands/
+```
+
+廃止されたシムは `legacy-command-shims/` にあります。`/tdd` などの古い名前がまだ必要な場合にのみ、そこから個別のファイルをコピーしてください。
+
+
+
+グローバル rules の代わりにプロジェクトローカル rules を使う
+
+ECC の標準をすべての Claude Code セッションではなく一つのリポジトリにだけ適用したい場合は、プロジェクトローカル rules を使用します。
+
+```bash
+cd your-project
+mkdir -p .claude/rules/ecc
+cp -R /path/to/ECC/rules/common .claude/rules/ecc/
+cp -R /path/to/ECC/rules/typescript .claude/rules/ecc/
+```
+
+rules は常時ロードされるコンテキストなので、`common` と実際に使用しているスタックのパック一つから始めてください。rules を手動でコピーする際は、相対参照が機能し続け、ファイル名が衝突しないように、中のファイルではなく言語ディレクトリ全体(たとえば `rules/common` や `rules/golang`)をコピーしてください。
+
+
+
+完全手動の Claude インストール
+
+plugin パスを意図的にスキップする場合にのみ使用してください。
+
+```bash
+git clone https://github.com/affaan-m/ECC.git
+cd ECC
+./install.sh --profile full
+```
+
+Windows:
+
+```powershell
+git clone https://github.com/affaan-m/ECC.git
+cd ECC
+.\install.ps1 --profile full
+```
+
+このパスを選んだ場合は、そこで止めてください。`/plugin install` を追加で実行しないでください。
+
+厳選した手動インストールの場合、Claude は `~/.claude/skills/` の直下の子として skills を検出します。`~/.claude/skills/ecc/` 配下にネストしないでください。
+
+#### hooks のインストール
+
+リポジトリの生の `hooks/hooks.json` を `~/.claude/settings.json` や `~/.claude/hooks/hooks.json` にコピーしないでください。そのファイルは plugin/リポジトリ向けのものです。hook コマンドのパスが正しく書き換えられるよう、インストーラーを使用してください。
+
+```bash
+bash ./install.sh --target claude --modules hooks-runtime --enable-hooks
+```
+
+これにより hook スクリプトが `~/.claude/` 配下にインストールされ、解決済みの
+hook エントリが `~/.claude/settings.json` に登録されます。既存のユーザー設定と hooks は
+保持されます。ECC 所有のエントリは安定した ID で追跡されるため、冪等な更新と
+安全なアンインストールが可能です。
+
+`/plugin install` で ECC をインストールした場合は、それらの hooks を `settings.json` にコピーしないでください。Claude Code v2.1+ はすでに plugin の `hooks/hooks.json` を自動ロードしており、`settings.json` に重複させると二重実行やクロスプラットフォームの hook 競合が発生します。
+
+Windows では、Claude の設定ルートは `%USERPROFILE%\.claude` です。hook ランタイムは次のようにインストールしてください。
+
+```powershell
+pwsh -File .\install.ps1 --target claude --modules hooks-runtime --enable-hooks
+```
+
+#### MCP の設定
+
+Claude plugin インストールは、ECC に同梱された MCP サーバー定義を意図的に自動有効化しません。これにより、厳格なサードパーティゲートウェイでの plugin MCP ツール名の長すぎる問題を回避しつつ、手動での MCP セットアップは引き続き可能です。
+
+稼働中の Claude Code サーバー変更には、Claude Code の `/mcp` コマンドまたは CLI 管理の MCP セットアップを使用してください。Claude Code はそれらの選択を `~/.claude.json` に永続化します。リポジトリローカルの MCP アクセスには、`mcp-configs/mcp-servers.json` から必要な MCP サーバー定義をプロジェクトスコープの `.mcp.json` にコピーしてください。
+
+ECC が同梱するデフォルトコネクターはちょうど一つ(`chrome-devtools`)だけです。それ以外はすべて CLI/REST API をラップする skill か、オプトインのカタログエントリです。このルールと、以前の六つのデフォルトを廃止した 2026年6月の監査は [docs/MCP-CONNECTOR-POLICY.md](../MCP-CONNECTOR-POLICY.md) にあります。
+
+ECC 同梱の MCP を自分でも別途実行している場合は、次を設定してください。
+
+```bash
+export ECC_DISABLED_MCPS="chrome-devtools"
+```
+
+ECC 管理のインストールおよび Codex 同期フローは、重複を再追加する代わりに、それらの同梱サーバーをスキップまたは削除します。`ECC_DISABLED_MCPS` は ECC のインストール/同期フィルターであり、稼働中の Claude Code のトグルではありません。
+
+**重要:** `YOUR_*_HERE` プレースホルダーを実際の API キーに置き換えてください。
+
+
+
+マルチモデル commands には追加のセットアップが必要
+
+`multi-*` commands は、基本の plugin/rules インストールには**含まれていません**。
+
+`/multi-plan`、`/multi-execute`、`/multi-backend`、`/multi-frontend`、`/multi-workflow` を使用するには、`ccg-workflow` ランタイムもインストールする必要があります。[上流の CCG インストールガイド](https://github.com/fengshao1227/ccg-workflow#readme)を使って正確なリリースを選択・レビューし、そのインストール済みランタイムを初期化してください。ECC は CCG を同梱しておらず、互換性があり監査済みの CCG リリースを保証するものでもありません。このガイドは、特定されていないレジストリバージョンをブートストラップしません。
+
+このランタイムは、これらの commands が期待する外部依存関係を提供します。たとえば次のものです。
+
+- `~/.claude/bin/codeagent-wrapper`
+- `~/.claude/.ccg/prompts/*`
+
+`ccg-workflow` がない場合、これらの `multi-*` commands は正しく動作しません。
+
+
+
+リセット、修復、またはアンインストール
+
+### ECC のリセット / アンインストール
+
+ユニバーサルパッケージからインストールした場合は、インストール時に使用したのと同じ
+プロジェクトディレクトリから次のコマンドを実行してください。
+
+```bash
+npx ecc-universal@2.2.1 list-installed
+npx ecc-universal@2.2.1 doctor
+npx ecc-universal@2.2.1 repair
+npx ecc-universal@2.2.1 uninstall --dry-run
+npx ecc-universal@2.2.1 uninstall
+```
+
+ソースチェックアウトからの場合は、再インストールの前に管理状態を確認してください。
+
+```bash
+node scripts/ecc.js list-installed
+node scripts/ecc.js doctor
+node scripts/ecc.js repair
+node scripts/ecc.js uninstall --dry-run
+```
+
+ソースチェックアウトから直接アンインストールするには次を実行します。
+
+```bash
+node scripts/uninstall.js --dry-run
+node scripts/uninstall.js
+```
+
+ECC をやめる場合、アンインストールコマンドは任意の[20秒フィードバックフォーム](https://github.com/affaan-m/ECC/issues/new?template=quick-feedback.yml)を表示します。これは公開の GitHub issue であり、アンインストールを妨げることはなく、ECC が診断情報をアップロードすることもありません。問題報告、フィードバック、機能要望の窓口を確認するには、いつでも `ecc feedback` を実行できます。
+
+plugin ユーザーは Claude Code から plugin を削除し、その後、手動でコピーして不要になった rule フォルダーだけを削除してください。ECC はインストール状態に記録されたファイルのみを削除します。ハーネスディレクトリ内の無関係なファイルを自分のものとして扱うことはありません。
+
+複数の方法を重ねてしまった場合は、次の順序でクリーンアップしてください。
+
+1. Claude Code plugin のインストールを削除します。
+2. 管理対象の install-state を含むプロジェクトディレクトリから ECC のアンインストールコマンドを実行します。
+3. 手動でコピーした、もう不要な rules フォルダーを削除します。
+4. 単一の経路を使って一度だけ再インストールします。
+
+
+## ECC を使い始める
+
+カタログ全体ではなく、必要なワークフローから始めましょう。
+
+| やりたいこと | ここから始める |
+|---|---|
+| 機能を構築する | `/ecc:plan "describe the feature"`、その後 `tdd-workflow` |
+| バグを修正する | 失敗するテストで再現してから `tdd-workflow` を使用 |
+| 新しいコードをレビューする | `/code-review` で新しいコンテキストからのレビュー |
+| ビルドを修復する | `/build-fix` |
+| コードベースをクリーンアップする | `/refactor-clean` |
+| コンテキストの圧迫を確認する | `/context-budget` |
+| 長いセッションを終える | `/save-session` または `/learn-eval` |
+| 後で再開する | `/resume-session` |
+| agent 設定を監査する | レビュー済みのスキャナーで `/security-scan`、またはインストール済みの `agentshield scan --path .` |
+
+
+Plugin コマンドと手動コマンド
+
+Claude Code の plugin コマンドはネームスペース付きの形式を使います:
+
+```text
+/ecc:plan "Add authentication"
+```
+
+手動インストールでは、より短い互換形式が使える場合があります:
+
+```text
+/plan "Add authentication"
+```
+
+Skills が主要なワークフローの入口です。コマンドは便利なエントリーポイントおよび互換シムとして残っています。インストール済みの内容は次のコマンドで確認できます:
+
+```bash
+/plugin list ecc@ecc
+```
+
+
+
+どの agent を使えばよいですか?
+
+Skills が正規のワークフローの入口です。メンテナンスされているスラッシュエントリーは、コマンドファーストのワークフロー向けに引き続き利用できます。
+
+| やりたいこと | 使う入口 | 使用される agent |
+|--------------|-----------------|------------|
+| 新機能を計画する | `/ecc:plan "Add auth"` | planner |
+| システムアーキテクチャを設計する | `/ecc:plan` + architect agent | architect |
+| テストファーストでコードを書く | `tdd-workflow` skill | tdd-guide |
+| 書いたばかりのコードをレビューする | `/code-review` | code-reviewer |
+| 失敗するビルドを修正する | `/build-fix` | build-error-resolver |
+| エンドツーエンドテストを実行する | `e2e-testing` skill | e2e-runner |
+| セキュリティ脆弱性を見つける | `/security-scan` | security-reviewer |
+| デッドコードを削除する | `/refactor-clean` | refactor-cleaner |
+| ドキュメントを更新する | `/update-docs` | doc-updater |
+| Go コードをレビューする | `/go-review` | go-reviewer |
+| Python コードをレビューする | `/python-review` | python-reviewer |
+| F# コードをレビューする | *(`fsharp-reviewer` を直接呼び出す)* | fsharp-reviewer |
+| TypeScript/JavaScript コードをレビューする | *(`typescript-reviewer` を直接呼び出す)* | typescript-reviewer |
+| HarmonyOS アプリを開発する | *(`harmonyos-app-resolver` を直接呼び出す)* | harmonyos-app-resolver |
+| データベースクエリを監査する | *(自動委譲)* | database-reviewer |
+| 本番 ML の変更をレビューする | `mle-workflow` skill + `mle-reviewer` agent | mle-reviewer |
+
+
+
+
+よくあるワークフロー
+
+以下のスラッシュ形式は、メンテナンスされているコマンド群に残っているものを示しています。`/tdd` や `/eval` のような廃止された短縮名シムは、明示的なオプトイン専用として `legacy-command-shims/` にあります。
+
+**新機能を始める:**
+```
+/ecc:plan "Add user authentication with OAuth"
+ -> planner creates implementation blueprint
+tdd-workflow skill -> tdd-guide enforces write-tests-first
+/code-review -> code-reviewer checks your work
+```
+
+**バグを修正する:**
+```
+tdd-workflow skill -> tdd-guide: write a failing test that reproduces it
+ -> implement the fix, verify test passes
+/code-review -> code-reviewer: catch regressions
+```
+
+**本番環境に向けた準備:**
+```
+/security-scan -> security-reviewer: OWASP Top 10 audit
+e2e-testing skill -> e2e-runner: critical user flow tests
+/test-coverage -> verify 80%+ coverage
+```
+
+
+## セルフホストモデルとカスタムエンドポイント
+
+ECC は各ハーネスの通常の設定を通じて動作するため、ECC のワークフローを変更することなく、公式プロバイダー、互換性のあるカスタム API エンドポイントやモデルゲートウェイ、あるいはセルフホストモデルを利用できます。
+
+Claude Code について、ECC は Anthropic ホストのトランスポート設定をハードコードしていません。最小限のゲートウェイの例:
+
+```bash
+export ANTHROPIC_BASE_URL=https://your-gateway.example.com
+export ANTHROPIC_AUTH_TOKEN=your-token
+claude
+```
+
+ゲートウェイがモデル名を再マッピングする場合は、ECC ではなく Claude Code 側で設定してください。`claude` CLI がすでに動作している状態であれば、ECC の hooks、skills、コマンド、rules はモデルプロバイダーに依存しません。Anthropic の [LLM ゲートウェイドキュメント](https://docs.anthropic.com/en/docs/claude-code/llm-gateway) と [モデル設定ドキュメント](https://docs.anthropic.com/en/docs/claude-code/model-config) を参照してください。
+
+そのゲートウェイの背後で任意のオープンソースモデルを実行またはセルフホストするには、別途コンピュートとサービングのセットアップが必要です。GPU 容量が必要な場合、[Itô](https://compute.itomarkets.com) は ECC の推奨コンピュートスポンサーですが、どの GPU プロバイダーでも動作します。このスポンサーシップのリンクは受動的なものです。RFQ の発行、容量の予約、コンピュートのプロビジョニング、サービングの設定は行いません。これとは別に、`ecc ito find` は明示的に設定された正規の Itô CLI を呼び出し、認証済みのライブ RFQ を送信しますが、容量の予約は行いません。Itô によるマネージド推論はまだ提供されていません。
+
+### ECC + Itô コンピュートで Kimi をセルフホストする
+
+Kimi Code ハーネスとモデルサービングレイヤーは別物です。ECC は agent ハーネスを設定します。API エンドポイントを用意する([Kimi API キーを取得](https://platform.kimi.ai?aff=ecc))か、自身の GPU 容量でオープンウェイトの Kimi モデルをセルフホストするのはユーザー側です。このアダプターは Kimi Code 0.31.x(`@moonshot-ai/kimi-code`)で検証済みです:
+
+
+
+
+
+ 
+ 1. GPU 容量を確保する
+
+ Itô または任意の GPU プロバイダーを利用します。
+
+
+
+ 
+ 2. Kimi をサーブする
+
+ 選択したチェックポイントを互換エンドポイント経由で公開します。
+
+
+
+ 
+ 3. ECC で Kimi Code を実行する
+
+ プロジェクトの指示と skills をインストールし、Kimi Code を起動します。
+
+
+
+
+Kimi Code の公式プロバイダーガイドに従ってエンドポイントを設定し、ECC をインストールします:
+
+```bash
+bash ./install.sh --target kimi --profile minimal
+node scripts/ecc.js doctor --target kimi
+kimi
+```
+
+Kimi Code はインストールされた `.kimi-code/AGENTS.md` の指示と `.kimi-code/skills/` のワークフローをネイティブに検出します。プロジェクトレベルの `.agents/skills/` も公式の検出場所です。ECC はプロジェクトの MCP エントリーを `.kimi-code/mcp.json` に安全にマージし、ユーザーレベルの `~/.kimi-code/config.toml` は変更しません。Kimi Code はネイティブ hooks をサポートしていますが、ECC の現在のマネージドプロジェクトアダプターはそれらを設定しないため、このインストーラーは Kimi の hook プロファイルを提供しません。インストーラーのドライランと回帰テストスイートにより、マネージドな Kimi への書き込みがすべてプロジェクトローカルの `.kimi-code/` ルート内に収まることが検証されています。
+
+### Itô コンピュート CLI ブリッジ
+
+`ecc ito` は別途インストールされた正規の Itô クライアントに委譲します。ECC は 2 つ目の API クライアントを保守しません。`ecc ito login [--no-browser]` はデバイス認可を実行し、デフォルトで Itô の検証ページを開き、デバイストークンを macOS Keychain に保存します。`--no-browser` はページの引き渡しを抑制します。ECC 自体はブラウザ自動化を行いません。`ecc ito auth` は検証専用で、`--no-browser` を拒否します。利用可能な操作は `ecc ito login`、`ecc ito auth`、`ecc ito find`、`ecc ito status`、および別途ゲートされた `ecc ito evals` です。対応する MCP ツールは引き続き `ito_auth`、`ito_find`、`ito_status` です。`ito_auth` は既存の認証情報を検証し、ノード資格の確認は CLI 専用です。
+
+`ito-compute-cli` パッケージは現在未公開です。Itô ランタイムリポジトリ(デスクの堅牢化が進むまで非公開。デザインパートナーにはアクセス権が提供されます)の `cli/ito-compute-cli` からローカルでビルドし、`npm ci` と `npm run check` を実行してから、`ECC_ITO_CLI_EXECUTABLE` にそのビルドの `dist/bin/ito.js` の絶対パスを設定してください。login は `ITO_API_KEY` を決して継承しません。auth、find、status は設定されていれば `ITO_API_KEY` を直接転送し、`ITO_AUTH_MODE=legacy` は不要です。`ecc ito logout` は現在のデバイス認証情報を失効させ、リモートでの失効が確認できない場合はローカルコピーを保持します。デバイストークンはデフォルトで macOS Keychain を使用します。明示的なファイルフォールバックでは、所有者のみがアクセスできるディレクトリ/ファイルのパーミッションを維持する必要があります。ECC はこの認証情報を持つクライアントを `PATH` 経由で検出しません。RFQ の権限と MCP セットアップの契約の全容については [`ito-compute` skill](../../skills/ito-compute/SKILL.md) を参照してください。
+
+`find` は認証済みのライブ RFQ を送信します。容量の予約は行いません。`evals` には `ITO_ENABLE_SIXTYTWO_LIVE=1` と `--live-sixtytwo` の両方、別途インストールされた `sixtytwo-cli==0.3.33`、明示的なノードリスト、および既存の絶対パスの設定ディレクトリが必要です。レンタル、起動、復旧、修復、購入はできません。ECC は見積もりロック、購入、ワークロード、推論のいずれの経路も公開せず、クライアントの欠如やライブ呼び出しの失敗をローカルの結果で置き換えることも決してありません。
+
+## 新機能
+
+現在のリリース:**2.2.1**(2026-08-31)。2.2 系のハイライト:
+
+- Claude Code、Codex、Kimi Code にわたるガイド付きのマニフェスト駆動セットアップ。install-state の所有権管理、doctor、repair、uninstall を備えています。
+- ネイティブの Antigravity インストール、薄い Pi アダプター、そして Linux、macOS、Windows でテストされたパック済みアーティファクトのリリースゲート。
+- Plan Canvas によるブラウザレビュー、統合メモリボールト(`ecc memory`)、Itô コンピュート skill ファミリー。
+
+完全な履歴:[CHANGELOG.md](../../CHANGELOG.md)。リリースごとのノートとエビデンスは [docs/releases/](../releases/) にあります。
+
+### v2.0.0: Agent Harness Operating System(2026年6月)
+
+2.0 系の安定版への昇格:コントロールペーン基盤、worktree ライフサイクルサービス、`orch-*` オーケストレーターファミリー、Discord コミュニティ。ノート:[docs/releases/2.0.0/release-notes.md](../releases/2.0.0/release-notes.md)。
+
+## 中身
+
+```text
+ECC/
+|-- agents/ # 委譲用の 68 の専門サブエージェント
+|-- skills/ # オンデマンドで読み込まれる 292 の再利用可能なワークフロー
+|-- commands/ # メンテナンスされている 94 のスラッシュコマンドシム
+|-- rules/ # オプトインの共通標準と言語別標準
+|-- hooks/ # ランタイムの自動化と強制
+|-- scripts/ # インストール、修復、同期、オーケストレーション、チェック
+|-- .claude-plugin/ # Claude Code マーケットプレイスマニフェスト
+|-- .codex/ # Codex リファレンス設定と agent ロール
+|-- .opencode/ # OpenCode plugin、コマンド、指示
+|-- .cursor/ # Cursor rules と hook アダプター
+|-- docs/ # 公開されたセットアップ、アーキテクチャ、運用ガイド
+```
+
+ルートが信頼できる唯一の情報源です。プラットフォームアダプターは、別のコピーを保守するのではなく、これらの同じワークフローをパッケージ化またはマッピングします。
+
+
+注釈付きコンポーネントカタログ
+
+```
+ECC/
+|-- .claude-plugin/ # Plugin とマーケットプレイスのマニフェスト
+| |-- plugin.json # Plugin メタデータとコンポーネントパス
+| |-- marketplace.json # /plugin marketplace add 用のマーケットプレイスカタログ
+|
+|-- agents/ # 委譲用の 67 の専門サブエージェント
+| |-- planner.md # 機能実装の計画
+| |-- architect.md # システム設計の意思決定
+| |-- tdd-guide.md # テスト駆動開発
+| |-- code-reviewer.md # 品質とセキュリティのレビュー
+| |-- security-reviewer.md # 脆弱性分析
+| |-- build-error-resolver.md
+| |-- e2e-runner.md # Playwright E2E テスト
+| |-- refactor-cleaner.md # デッドコードのクリーンアップ
+| |-- doc-updater.md # ドキュメントの同期
+| |-- docs-lookup.md # ドキュメント/API の検索
+| |-- chief-of-staff.md # コミュニケーションのトリアージと下書き
+| |-- loop-operator.md # 自律ループの実行
+| |-- harness-optimizer.md # ハーネス設定のチューニング
+| |-- cpp-reviewer.md # C++ コードレビュー
+| |-- cpp-build-resolver.md # C++ ビルドエラーの解決
+| |-- fsharp-reviewer.md # F# 関数型コードレビュー
+| |-- go-reviewer.md # Go コードレビュー
+| |-- go-build-resolver.md # Go ビルドエラーの解決
+| |-- python-reviewer.md # Python コードレビュー
+| |-- database-reviewer.md # データベース/Supabase レビュー
+| |-- typescript-reviewer.md # TypeScript/JavaScript コードレビュー
+| |-- java-reviewer.md # Java/Spring Boot コードレビュー
+| |-- java-build-resolver.md # Java/Maven/Gradle ビルドエラー
+| |-- kotlin-reviewer.md # Kotlin/Android/KMP コードレビュー
+| |-- kotlin-build-resolver.md # Kotlin/Gradle ビルドエラー
+| |-- harmonyos-app-resolver.md # HarmonyOS/ArkTS アプリ開発
+| |-- rust-reviewer.md # Rust コードレビュー
+| |-- rust-build-resolver.md # Rust ビルドエラーの解決
+| |-- pytorch-build-resolver.md # PyTorch/CUDA トレーニングエラー
+| |-- mle-reviewer.md # 本番 ML パイプライン、評価、サービング、監視のレビュー
+|
+|-- skills/ # ワークフロー定義とドメイン知識
+| |-- coding-standards/ # 言語別ベストプラクティス
+| |-- clickhouse-io/ # ClickHouse 分析、クエリ、データエンジニアリング
+| |-- backend-patterns/ # API、データベース、キャッシュのパターン
+| |-- frontend-patterns/ # React、Next.js のパターン
+| |-- frontend-slides/ # HTML スライドデッキと PPTX から Web へのプレゼンテーションワークフロー
+| |-- article-writing/ # 汎用的な AI 口調を避け、指定された文体で書く長文ライティング
+| |-- content-engine/ # マルチプラットフォームのソーシャルコンテンツと再利用ワークフロー
+| |-- market-research/ # 出典を明記した市場、競合、投資家のリサーチ
+| |-- investor-materials/ # ピッチデッキ、ワンページャー、メモ、財務モデル
+| |-- investor-outreach/ # パーソナライズされた資金調達アウトリーチとフォローアップ
+| |-- continuous-learning/ # レガシー v1 の Stop hook によるパターン抽出
+| |-- continuous-learning-v2/ # 信頼度スコアリング付きの instinct ベース学習
+| |-- iterative-retrieval/ # サブエージェント向けの段階的なコンテキスト精緻化
+| |-- strategic-compact/ # 手動コンパクション提案(長文ガイド)
+| |-- tdd-workflow/ # TDD 方法論
+| |-- security-review/ # セキュリティチェックリスト
+| |-- eval-harness/ # 検証ループ評価(長文ガイド)
+| |-- verification-loop/ # 継続的検証(長文ガイド)
+| |-- videodb/ # 動画と音声:取り込み、検索、編集、生成、ストリーミング
+| |-- golang-patterns/ # Go のイディオムとベストプラクティス
+| |-- golang-testing/ # Go のテストパターン、TDD、ベンチマーク
+| |-- cpp-coding-standards/ # C++ Core Guidelines に基づく C++ コーディング標準
+| |-- cpp-testing/ # GoogleTest、CMake/CTest による C++ テスト
+| |-- django-patterns/ # Django のパターン、モデル、ビュー
+| |-- django-security/ # Django セキュリティベストプラクティス
+| |-- django-tdd/ # Django TDD ワークフロー
+| |-- django-verification/ # Django 検証ループ
+| |-- laravel-patterns/ # Laravel アーキテクチャパターン
+| |-- laravel-security/ # Laravel セキュリティベストプラクティス
+| |-- laravel-tdd/ # Laravel TDD ワークフロー
+| |-- laravel-verification/ # Laravel 検証ループ
+| |-- python-patterns/ # Python のイディオムとベストプラクティス
+| |-- python-testing/ # pytest による Python テスト
+| |-- quarkus-patterns/ # Java Quarkus パターン
+| |-- quarkus-security/ # Quarkus セキュリティ
+| |-- quarkus-tdd/ # Quarkus TDD
+| |-- quarkus-verification/ # Quarkus 検証
+| |-- rails-patterns/ # Rails アーキテクチャパターン
+| |-- springboot-patterns/ # Java Spring Boot パターン
+| |-- springboot-security/ # Spring Boot セキュリティ
+| |-- springboot-tdd/ # Spring Boot TDD
+| |-- springboot-verification/ # Spring Boot 検証
+| |-- configure-ecc/ # インタラクティブインストールウィザード
+| |-- security-scan/ # AgentShield セキュリティ監査ツールの統合
+| |-- java-coding-standards/ # Java コーディング標準
+| |-- jpa-patterns/ # JPA/Hibernate パターン
+| |-- postgres-patterns/ # PostgreSQL 最適化パターン
+| |-- nutrient-document-processing/ # Nutrient API によるドキュメント処理
+| |-- database-migrations/ # マイグレーションパターン(Prisma、Drizzle、Django、Go)
+| |-- api-design/ # REST API 設計、ページネーション、エラーレスポンス
+| |-- deployment-patterns/ # CI/CD、Docker、ヘルスチェック、ロールバック
+| |-- docker-patterns/ # Docker Compose、ネットワーキング、ボリューム、コンテナセキュリティ
+| |-- e2e-testing/ # Playwright E2E パターンと Page Object Model
+| |-- content-hash-cache-pattern/ # ファイル処理向けの SHA-256 コンテンツハッシュキャッシュ
+| |-- cost-aware-llm-pipeline/ # LLM コスト最適化、モデルルーティング、予算追跡
+| |-- regex-vs-llm-structured-text/ # 判断フレームワーク:テキスト解析における正規表現 vs LLM
+| |-- swift-actor-persistence/ # actor によるスレッドセーフな Swift データ永続化
+| |-- swift-protocol-di-testing/ # テスト可能な Swift コードのためのプロトコルベース DI
+| |-- search-first/ # コーディング前にリサーチするワークフロー
+| |-- skill-stocktake/ # skills とコマンドの品質監査
+| |-- liquid-glass-design/ # iOS 26 Liquid Glass デザインシステム
+| |-- foundation-models-on-device/ # FoundationModels による Apple オンデバイス LLM
+| |-- swift-concurrency-6-2/ # Swift 6.2 Approachable Concurrency
+| |-- mle-workflow/ # 本番 ML のデータ契約、評価、デプロイ、監視
+| |-- perl-patterns/ # モダン Perl 5.36+ のイディオムとベストプラクティス
+| |-- perl-security/ # Perl セキュリティパターン、taint モード、安全な I/O
+| |-- perl-testing/ # Test2::V0、prove、Devel::Cover による Perl TDD
+| |-- autonomous-loops/ # 自律ループパターン:逐次パイプライン、PR ループ、DAG オーケストレーション
+| |-- plankton-code-quality/ # Plankton hooks による書き込み時のコード品質強制
+| |-- codehealth-mcp/ # オプションの CodeScene Code Health MCP skill(オプトイン)
+| |-- docs/examples/project-guidelines-template.md # プロジェクト固有 skills のテンプレート
+|
+|-- commands/ # メンテナンスされているスラッシュエントリーの互換層。skills/ を優先
+| |-- plan.md # /plan - 実装計画
+| |-- code-review.md # /code-review - 品質レビュー
+| |-- build-fix.md # /build-fix - ビルドエラーの修正
+| |-- refactor-clean.md # /refactor-clean - デッドコードの削除
+| |-- quality-gate.md # /quality-gate - 検証ゲート
+| |-- learn.md # /learn - セッション途中でのパターン抽出(長文ガイド)
+| |-- learn-eval.md # /learn-eval - パターンの抽出、評価、保存
+| |-- checkpoint.md # /checkpoint - 検証状態の保存(長文ガイド)
+| |-- setup-pm.md # /setup-pm - パッケージマネージャーの設定
+| |-- go-review.md # /go-review - Go コードレビュー
+| |-- go-test.md # /go-test - Go TDD ワークフロー
+| |-- go-build.md # /go-build - Go ビルドエラーの修正
+| |-- skill-create.md # /skill-create - git 履歴から skills を生成
+| |-- instinct-status.md # /instinct-status - 学習した instincts の表示
+| |-- instinct-import.md # /instinct-import - instincts のインポート
+| |-- instinct-export.md # /instinct-export - instincts のエクスポート
+| |-- evolve.md # /evolve - instincts をクラスタリングして skills に変換
+| |-- prune.md # /prune - 期限切れの保留中 instincts を削除
+| |-- pm2.md # /pm2 - PM2 サービスライフサイクル管理
+| |-- multi-plan.md # /multi-plan - マルチエージェントのタスク分解
+| |-- multi-execute.md # /multi-execute - オーケストレーションされたマルチエージェントワークフロー
+| |-- multi-backend.md # /multi-backend - バックエンドのマルチサービスオーケストレーション
+| |-- multi-frontend.md # /multi-frontend - フロントエンドのマルチサービスオーケストレーション
+| |-- multi-workflow.md # /multi-workflow - 汎用マルチサービスワークフロー
+| |-- sessions.md # /sessions - セッション履歴管理
+| |-- test-coverage.md # /test-coverage - テストカバレッジ分析
+| |-- update-docs.md # /update-docs - ドキュメントの更新
+| |-- update-codemaps.md # /update-codemaps - codemaps の更新
+| |-- python-review.md # /python-review - Python コードレビュー
+|-- legacy-command-shims/ # /tdd や /eval などの廃止シムのオプトインアーカイブ
+| |-- tdd.md # /tdd - tdd-workflow skill を推奨
+| |-- e2e.md # /e2e - e2e-testing skill を推奨
+| |-- eval.md # /eval - eval-harness skill を推奨
+| |-- verify.md # /verify - verification-loop skill を推奨
+| |-- orchestrate.md # /orchestrate - dmux-workflows または multi-workflow を推奨
+|
+|-- rules/ # 常に従うガイドライン(~/.claude/rules/ecc/ にコピー)
+| |-- README.md # 構成の概要とインストールガイド
+| |-- common/ # 言語非依存の原則
+| | |-- coding-style.md # 不変性、ファイル構成
+| | |-- git-workflow.md # コミット形式、PR プロセス
+| | |-- testing.md # TDD、80% カバレッジ要件
+| | |-- performance.md # モデル選択、コンテキスト管理
+| | |-- patterns.md # デザインパターン、スケルトンプロジェクト
+| | |-- hooks.md # Hook アーキテクチャ、TodoWrite
+| | |-- agents.md # サブエージェントへ委譲するタイミング
+| | |-- security.md # 必須セキュリティチェック
+| |-- typescript/ # TypeScript/JavaScript 固有
+| |-- python/ # Python 固有
+| |-- golang/ # Go 固有
+| |-- swift/ # Swift 固有
+| |-- php/ # PHP 固有
+| |-- arkts/ # HarmonyOS / ArkTS 固有
+|
+|-- hooks/ # トリガーベースの自動化
+| |-- README.md # Hook のドキュメント、レシピ、カスタマイズガイド
+| |-- hooks.json # すべての hooks 設定(PreToolUse、PostToolUse、Stop など)
+| |-- memory-persistence/ # セッションライフサイクル hooks(長文ガイド)
+| |-- strategic-compact/ # コンパクション提案(長文ガイド)
+|
+|-- scripts/ # クロスプラットフォームの Node.js スクリプト
+| |-- lib/ # 共有ユーティリティ
+| | |-- utils.js # クロスプラットフォームのファイル/パス/システムユーティリティ
+| | |-- package-manager.js # パッケージマネージャーの検出と選択
+| |-- hooks/ # Hook の実装
+| | |-- session-start.js # セッション開始時にコンテキストを読み込む
+| | |-- session-end.js # セッション終了時に状態を保存する
+| | |-- pre-compact.js # コンパクション前の状態保存
+| | |-- suggest-compact.js # 戦略的コンパクション提案
+| | |-- evaluate-session.js # セッションからパターンを抽出
+| |-- setup-package-manager.js # インタラクティブなパッケージマネージャー設定
+|
+|-- tests/ # テストスイート
+| |-- lib/ # ライブラリテスト
+| |-- hooks/ # Hook テスト
+| |-- run-all.js # すべてのテストを実行
+|
+|-- contexts/ # 動的システムプロンプト注入コンテキスト(長文ガイド)
+| |-- dev.md # 開発モードコンテキスト
+| |-- review.md # コードレビューモードコンテキスト
+| |-- research.md # リサーチ/探索モードコンテキスト
+|
+|-- examples/ # 設定とセッションの例
+| |-- CLAUDE.md # プロジェクトレベル設定の例
+| |-- user-CLAUDE.md # ユーザーレベル設定の例
+| |-- saas-nextjs-CLAUDE.md # 実際の SaaS(Next.js + Supabase + Stripe)
+| |-- go-microservice-CLAUDE.md # 実際の Go マイクロサービス(gRPC + PostgreSQL)
+| |-- django-api-CLAUDE.md # 実際の Django REST API(DRF + Celery)
+| |-- laravel-api-CLAUDE.md # 実際の Laravel API(PostgreSQL + Redis)
+| |-- rust-api-CLAUDE.md # 実際の Rust API(Axum + SQLx + PostgreSQL)
+|
+|-- mcp-configs/ # MCP サーバー設定
+| |-- mcp-servers.json # GitHub、Supabase、Vercel、Railway など
+|
+|-- ecc_dashboard.py # デスクトップ GUI ダッシュボード(Tkinter)
+|
+|-- marketplace.json # セルフホストマーケットプレイス設定(/plugin marketplace add 用)
+```
+
+
+
+ダッシュボード GUI
+
+デスクトップダッシュボードを起動して、ECC のコンポーネントを視覚的に探索できます:
+
+```bash
+npm run dashboard
+# または
+python3 ./ecc_dashboard.py
+```
+
+**機能:**
+- タブ形式のインターフェース:Agents、Skills、Commands、Rules、Settings
+- ダーク/ライトテーマの切り替え
+- フォントのカスタマイズ(ファミリーとサイズ)
+- ヘッダーとタスクバーのプロジェクトロゴ
+- すべてのコンポーネントを横断した検索とフィルター
+
+
+## 主要な概念
+
+
+Agents、skills、hooks、rules の解説
+
+### Agents
+
+サブエージェントは、限定されたスコープで委譲されたタスクを処理します。例:
```markdown
---
name: code-reviewer
-description: コードの品質、セキュリティ、保守性をレビュー
-tools: ["Read", "Grep", "Glob", "Bash"]
+description: Reviews code for quality, security, and maintainability
+tools: Read, Grep, Glob, Bash
model: opus
---
-あなたは経験豊富なコードレビュアーです...
-
+You are a senior code reviewer...
```
-### スキル
+### Skills
-スキルはコマンドまたはエージェントによって呼び出されるワークフロー定義:
+Skills が主要なワークフローの入口です。直接呼び出すことも、自動的に提案されることも、agents から再利用されることもできます。ECC は移行期間中もメンテナンスされている `commands/` を引き続き同梱しており、廃止された短縮名シムは明示的なオプトイン専用として `legacy-command-shims/` に置かれています。新しいワークフローの開発は、まず `skills/` に置くべきです。
```markdown
-# TDD ワークフロー
+# TDD Workflow
-1. インターフェースを最初に定義
-2. テストを失敗させる (RED)
-3. 最小限のコードを実装 (GREEN)
-4. リファクタリング (IMPROVE)
-5. 80%+ のカバレッジを確認
+1. Define interfaces first
+2. Write failing tests (RED)
+3. Implement minimal code (GREEN)
+4. Refactor (IMPROVE)
+5. Verify 80%+ coverage
```
-### フック
+### Hooks
-フックはツールイベントでトリガーされます。例 - console.log についての警告:
+Hooks はツールイベントで発火します。例:console.log について警告する:
```json
{
@@ -558,25 +1090,851 @@ model: opus
}
```
-### ルール
+### Rules
-ルールは常に従うべきガイドラインで、`common/`(言語非依存)+ 言語固有ディレクトリに組織化:
+Rules は常に従うべきガイドラインで、`common/`(言語非依存)+ 言語固有のディレクトリに整理されています:
```
rules/
common/ # 普遍的な原則(常にインストール)
- typescript/ # TS/JS 固有パターンとツール
- python/ # Python 固有パターンとツール
- golang/ # Go 固有パターンとツール
+ typescript/ # TS/JS 固有のパターンとツール
+ python/ # Python 固有のパターンとツール
+ golang/ # Go 固有のパターンとツール
+ swift/ # Swift 固有のパターンとツール
+ php/ # PHP 固有のパターンとツール
+ arkts/ # HarmonyOS / ArkTS のパターンと制約
```
-インストールと構造の詳細は[`rules/README.md`](rules/README.md)を参照してください。
+インストール方法と構成の詳細は [`rules/README.md`](../../rules/README.md) を参照してください。
+
+## ガイド
+
+このリポジトリは生のコードです。ガイドがすべてを説明しています。
+
+
+
+
+
+
+簡潔ガイド
+
+
セットアップ、基礎、初日からの使い方。まずこれを読んでください。(スレッド)
+
+
+
+
+長文ガイド
+
+
コンテキストの経済性、メモリ、評価、並列エージェント。(スレッド)
+
+
+
+
+セキュリティガイド
+
+
プロンプトインジェクション、hooks、MCP、AgentShield。(スレッド)
+
+
+
+
+| トピック | 学べる内容 |
+|-------|-------------------|
+| トークン最適化 | モデル選択、システムプロンプトの削減、バックグラウンドプロセス |
+| メモリ永続化 | セッション間でコンテキストを自動的に保存/読み込みする hooks |
+| 継続的学習 | セッションからパターンを自動抽出して再利用可能な skills に変換 |
+| 検証ループ | チェックポイント評価と継続的評価、グレーダーの種類、pass@k メトリクス |
+| 並列化 | Git worktree、カスケード方式、インスタンスをスケールすべきタイミング |
+| サブエージェントのオーケストレーション | コンテキスト問題、反復検索パターン |
+
+[コマンド クイックリファレンス](./COMMANDS-QUICK-REF.md) | [手動適用ガイド](../MANUAL-ADAPTATION-GUIDE.md) | [トラブルシューティング FAQ](../../TROUBLESHOOTING.md) | [ロードマップ](../ROADMAP.md)
+
+## なぜ ECC を選ぶのか
+
+| 仕組みがない場合 | ECC がある場合 |
+| ------------------------------------------------------- | --------------------------------------------------------------------- |
+| 計画はチャット履歴の中に消えていく | 計画は実装開始前に編集可能な成果物になる |
+| 「TDD を使ってください」はモデルが忘れるかもしれない指示 | TDD は証拠付きのゲート化された RED -> GREEN -> REFACTOR ワークフローになる |
+| 同じコンテキストがコードを書き、レビューもする | 新しいコンテキストのレビュアーがリグレッションと盲点を探す |
+| メモリとは巨大なトランスクリプトを保存すること | セッションは要約、instincts、再利用可能な skills に蒸留される |
+| 品質チェックはリマインダー頼み | hooks がプロンプトの外側で決定論的なチェックを強制できる |
+| エージェント設定はデフォルトで信頼される | AgentShield がハーネス自体を攻撃対象領域としてスキャンする |
+
+### TDD:テスト駆動開発
+
+```text
+/ecc:plan "Add usage-based billing alerts"
+ -> confirm or edit the plan
+ -> activate tdd-workflow
+ -> capture RED evidence before implementation
+ -> implement until GREEN
+ -> review from fresh context
+ -> fix findings with regression tests
+ -> verify build, lint, types, and tests
+```
+
+成果物は単なるコードではありません。計画、失敗するテスト、成功するテスト、レビューでの指摘、最終検証という証拠の軌跡です。
+
+### Skills がコンテキストを集中させる
+
+rules、skills、agents、hooks はそれぞれ異なる問題を解決します。これらの役割を分離しておくことで、ECC はリポジトリ全体をすべてのセッションに流し込むことなく能力を追加できます。
+
+| 概念 | 何をするか | コンテキストでの振る舞い |
+|---|---|---|
+| Skills | TDD、セキュリティレビュー、ディープリサーチなどの再利用可能なワークフロー | タスクが必要とするときに読み込まれる |
+| Agents | 独自のコンテキストとツール権限を持つスコープ限定のワーカー | 計画、実装、レビューを分離する |
+| Rules | 永続的なプロジェクト標準や言語標準 | 常に読み込まれるため、選択的にインストールする |
+| Hooks | ハーネスのイベントでトリガーされるスクリプト | モデルのコンテキスト外で実行される |
+| Instincts | 実際のセッションから学習された信頼度スコア付きのパターン | 関連するときに呼び出される |
+
+### ハーネス間でコンテキストを共有する
+
+ECC の Memory Vault は、Claude、Codex、Hermes、OpenClaw、Kimi、その他のハーネスに対して、永続的なコンテキストと引き継ぎのための単一のローカルで検査可能な Markdown 形式を提供します。プロジェクトおよびチームのメモリは `.ecc/memory/` に、ユーザーのメモリは `~/.ecc/memory/` に置かれます。
+
+skill のみ、minimal、manual、Claude plugin のインストールでは、Memory Vault ランタイムは `PATH` に配置されません。CLI やオプションの MCP サーバーを使う前に、npm ランタイムを別途インストールしてください:
+
+```bash
+npm install -g ecc-universal@2.2.1
+ecc memory init --scope project
+ecc memory search "authentication migration" --target-harness codex
+ecc memory doctor
+```
+
+メモリは未レビューのコンテキストであり、実行可能なポリシーではありません。重要な主張は権威ある情報源と照合して検証し、受け入れた知識は管理されたプロジェクトドキュメントに昇格させてください。オプションの `ecc-memory-mcp` サーバーは、デフォルトでは自身を有効化することなく、同じ範囲に限定された save、search、read、doctor の機能を公開します。
+
+[Unified Memory ワークフローを開く →](../../skills/unified-memory/SKILL.md)
+
+
+Memory Vault の詳細:スコープ、引き継ぎ、信頼境界
+
+Memory Vault は、ベンダーのトランスクリプトをコピーしたりエージェント間でコンテキストをメールしたりする代わりに、移植可能な `ecc.memory.v1` Markdown ドキュメントを保存します。プロジェクトメモリはフェイルクローズドの `.gitignore` で保護されています。チームスコープは、人間が検査しバージョン管理された共有にのみ使用してください。チームメモリはコミットされた後も未レビューのコンテキストのままです。
+
+上記のランタイムをインストールしたら、CLI とオプションの MCP エントリポイントが利用可能であることを確認してください:
+
+```bash
+ecc memory --help
+command -v ecc-memory-mcp
+```
+
+```bash
+# プロジェクトの vault を初期化する。
+ecc memory init --scope project
+
+# 引き継ぎ本文を通常のファイルに書き、次のハーネスを指定する。
+ecc memory handoff \
+ --from hermes \
+ --target codex \
+ --title "Continue authentication migration" \
+ --body-file ./handoff.md
+
+# 別のハーネスから呼び出す。
+ecc memory search "authentication migration" --target-harness codex
+ecc memory read
+
+# チームメモリを共有する前に vault を検証する。
+ecc memory doctor
+```
+
+メモリ本文は `--stdin` または `--body-file` 経由でのみ受け付けられ、コマンドライン引数の値としては受け付けられません。最初のリリースでは、すべての vault エントリは未レビューかつ作成のみです。人間のレビューは、メモリの信頼度を変えるのではなく、受け入れた知識を管理されたプロジェクトドキュメントに昇格させます。通常の検索による呼び出しは、アクティブなプロジェクトメモリとチームメモリを返します。ID を直接指定した読み取りでは、非アクティブなエントリを検査できます。ユーザースコープの呼び出しは明示的に要求する必要があります。エージェントは重要な主張を権威ある情報源と照合して検証しなければならず、呼び出した本文を実行可能な指示やポリシーとして扱ってはなりません。
+
+オプトインの MCP アクセスには、[`mcp-configs/mcp-servers.json`](../../mcp-configs/mcp-servers.json) の `ecc-memory-vault` エントリを必要な各ハーネスに追加し、`ecc-memory-mcp` を実行してください。サーバーが公開するのは `memory_save`、`memory_search`、`memory_read`、`memory_doctor` のみです。各サーバーは小文字の `ECC_MEMORY_HARNESS` アイデンティティを指定して起動する必要があります。このアイデンティティはサーバーに束縛されており、ツール呼び出し側から指定することはできません。ユーザースコープにはさらに、オペレーターが管理する `ECC_MEMORY_ALLOW_USER_SCOPE=1` のオプトインが必要です。ワークフローと信頼境界については [`skills/unified-memory/SKILL.md`](../../skills/unified-memory/SKILL.md) を、機能契約については [`docs/design/ecc-memory-vault.md`](../design/ecc-memory-vault.md) を参照してください。
+
+
+## プラットフォームサポート
+
+ECC のコアとなる Node.js CLI とマネージドインストーラーは **Windows、macOS、Linux** で動作しますが、オプション機能は完全に同等ではありません。一部の継続的学習、GAN、オーケストレーションのパスは依然として Bash または Python を必要とし、ハーネスごとに公開されている hook、agent、skill の API も異なります。
+
+| プラットフォーム | ステータス | 現在の制限 |
+|---|---|---|
+| Linux | コアをサポート | オプション機能には Bash、Python、またはプロバイダー固有のツールが必要な場合があります。 |
+| macOS | コアをサポート | スタンドアロンの GAN シェルパスはシステムの Bash 3.2 と互換性がなく、現在スコア解析の不具合があります([#2674](https://github.com/affaan-m/ECC/issues/2674))。 |
+| Windows + WSL | コアをサポート | WSL は Linux のパスに従います。Windows ホスト側の統合はハーネスによって異なります。 |
+| Windows ネイティブ | 制限付きでサポート | 継続的学習 v2 のオブザーバーデーモンと memory-vault の書き込みには、ネイティブ Windows での未解決の不具合があります([#2489](https://github.com/affaan-m/ECC/issues/2489)、[#2626](https://github.com/affaan-m/ECC/issues/2626))。シェルに依存するオプション機能には Git Bash/WSL が必要か、利用できません。 |
+
+以下の `stable`、`beta`、`experimental`、`instruction-only` は、マーケティング上の等級ではなく、機能の状態を示すものとして扱ってください。
+
+| ハーネス | ステータス | 推奨される配布方法 | 重要な制限 |
+|---|---|---|---|
+| Claude Code | Stable(主要) | Plugin または選択的インストーラー | plugin はインストール済みカタログをモデルに通知します。コンテキストの占有量が重要な場合は、選択的/manual profile を使用してください。シェルに依存するオプションの skills はすべての OS に移植可能ではありません。 |
+| Codex | ネイティブ plugin をサポート | Codex マーケットプレイス plugin またはリポジトリ設定 | ネイティブ hooks には明示的な信頼の決定が必要で、Claude の hook profile は使用しません。レガシーの sync は互換性維持のみです。 |
+| Cursor | Beta プロジェクトアダプター | `.cursor/` への選択的インストーラー | agent の検出は Cursor のビルドによって異なり、ECC のインストーラーパスはまだ同一の hook セットを公開していません([#2419](https://github.com/affaan-m/ECC/issues/2419))。 |
+| OpenCode | Beta ビルド済み plugin | plugin をビルドしてから選択的インストーラー | ECC はカタログのサブセットを同梱しています。OpenCode でプロバイダーを接続しモデルを選択してください([#2617](https://github.com/affaan-m/ECC/issues/2617))。 |
+| GitHub Copilot | Instruction-only | チェックインされた instructions とプロンプトファイル | ECC の hooks、ランタイム agents、委譲、ネイティブの skill 検出はありません。 |
+| Gemini、Zed、Antigravity、Qwen、Hermes、OpenClaw、Kimi、CodeBuddy、JoyCode | Experimental/最小限のアダプター | ハーネス固有の選択的ターゲット | ファイル配置と instructions の移植性はテスト済みです。Claude との完全な機能同等性は主張していません。 |
+
+
+パッケージマネージャーの検出
+
+plugin は、以下の優先順位でお好みのパッケージマネージャー(npm、pnpm、yarn、bun)を自動検出します:
+
+1. **環境変数**:`CLAUDE_PACKAGE_MANAGER`
+2. **プロジェクト設定**:`.claude/package-manager.json`
+3. **package.json**:`packageManager` フィールド
+4. **ロックファイル**:package-lock.json、yarn.lock、pnpm-lock.yaml、bun.lockb からの検出
+5. **グローバル設定**:`~/.claude/package-manager.json`
+6. **フォールバック**:最初に利用可能なパッケージマネージャー
+
+お好みのパッケージマネージャーを設定するには:
+
+```bash
+# 環境変数で設定
+export CLAUDE_PACKAGE_MANAGER=pnpm
+
+# グローバル設定で設定
+node scripts/setup-package-manager.js --global pnpm
+
+# プロジェクト設定で設定
+node scripts/setup-package-manager.js --project bun
+
+# 現在の設定を検出
+node scripts/setup-package-manager.js --detect
+```
+
+または `/setup-pm` コマンドを使用してください。
+
+
+
+Hook ランタイム制御(環境変数)
+
+ランタイムフラグを使って厳格さを調整したり、特定の hooks を一時的に無効化したりできます:
+
+```bash
+# Hook の厳格さ profile(デフォルト:standard)
+export ECC_HOOK_PROFILE=standard
+
+# 無効化する hook ID をカンマ区切りで指定
+export ECC_DISABLED_HOOKS="pre:bash:tmux-reminder,post:edit:typecheck"
+
+# SessionStart の追加コンテキストの上限(デフォルト:8000 文字)
+export ECC_SESSION_START_MAX_CHARS=4000
+
+# 低コンテキスト/ローカルモデル環境向けに SessionStart の追加コンテキストを完全に無効化
+export ECC_SESSION_START_CONTEXT=off
+
+# セッション一時ファイルの保持期間(日数、デフォルト:30)。
+# 0、off、false、disabled、never、none のいずれかを設定するとすべてのセッションを保持(削除を無効化)。
+export ECC_SESSION_RETENTION_DAYS=14
+
+# SessionStart がコンテキストに注入する学習済み instincts の上限(デフォルト:6)
+export ECC_MAX_INJECTED_INSTINCTS=6
+
+# instinct が注入されるために必要な最小信頼度、0-1(デフォルト:0.7)
+export ECC_INSTINCT_CONFIDENCE_THRESHOLD=0.7
+
+# SessionStart は注入する instincts を信頼度 + プロジェクト/スタックとの関連性で
+# ランク付けする(デフォルト:on)。プロジェクトスコープの instincts、および
+# domain/trigger が検出されたスタック(言語、フレームワーク、加えて terraform/dbt マーカー)に
+# 一致する instincts は、無関係な高信頼度のものより上に表示されるよう
+# 小さなランキングブーストを受ける。off/false/0/no を設定すると信頼度のみでランク付けする。
+export ECC_INSTINCT_RELEVANCE_RANKING=on
+
+# コンテキスト/スコープ/ループの警告は維持しつつ、API 従量課金のコスト見積もりを抑制
+export ECC_CONTEXT_MONITOR_COST_WARNINGS=off
+```
+
+Windows PowerShell:
+
+```powershell
+[Environment]::SetEnvironmentVariable('ECC_CONTEXT_MONITOR_COST_WARNINGS', 'off', 'User')
+[Environment]::SetEnvironmentVariable('ECC_SESSION_RETENTION_DAYS', '14', 'User')
+```
+
+
+
+Agent データホーム(マルチハーネスの分離)
+
+メモリ永続化 hooks(セッション要約、学習済み skills、セッションエイリアス、メトリクス)は、単一の agent データルートの下にデータを保存します。デフォルトではそのルートは `~/.claude` です。同じマシンで Claude Code と Cursor の両方で ECC を使用する場合、2つの環境が互いのセッションファイルを上書きしないように、Cursor 用に別のルートを設定してください:
+
+```bash
+# Cursor 専用の境界(Claude Code はデフォルトの ~/.claude を維持)
+export ECC_AGENT_DATA_HOME="$HOME/.cursor/ecc"
+```
+
+このルートの下で解決されるパスには以下が含まれます:
+
+- `$ECC_AGENT_DATA_HOME/session-data/`:セッション要約
+- `$ECC_AGENT_DATA_HOME/skills/learned/`:evaluate-session による学習済み skills
+- `$ECC_AGENT_DATA_HOME/session-aliases.json`:セッションエイリアス
+- `$ECC_AGENT_DATA_HOME/metrics/`:コストとアクティビティのメトリクス
+
+[affaan-m/ECC#2065](https://github.com/affaan-m/ECC/issues/2065) を参照してください。
+
+
+
+ツール横断の機能マップとハーネスごとの注記
+
+### ツール横断の機能マップ
+
+| 機能 | Claude Code | Codex | Cursor | OpenCode | GitHub Copilot |
+|---|---|---|---|---|---|
+| Instructions | ネイティブ | ネイティブ `AGENTS.md` | プロジェクト rules | Plugin の instructions | ネイティブ instruction ファイル |
+| Skills | ネイティブのインストール済みセット | ネイティブ plugin セット | ビルド依存/プロジェクトセット | ビルド済みサブセット | プロンプト/instruction からの参照のみ |
+| Agents/委譲 | ネイティブ agents | Codex マルチエージェントロール。Claude の agent ファイルはロールとしてインストールされない | ビルド依存のプロジェクト agents | Plugin の agents | 非対応 |
+| ECC hooks | ネイティブ plugin hooks | 明示的な信頼を伴うネイティブのレビュー済みサブセット | Cursor hook アダプター。インストールパスの差異は残る | Plugin イベント | 非対応 |
+| MCP 設定 | 利用可能、明示的な有効化が必要 | ネイティブ plugin マニフェスト。レガシー sync は TOML をマージ可能 | 明示的なプロジェクト/ユーザー設定 | プロバイダー/plugin 設定 | ECC からは提供されない |
+| Claude Code との同等性 | 主要リファレンス | 部分的 | 部分的 | 部分的 | 同等性の対象外 |
+
+**主要なアーキテクチャ上の決定:**
+- ルートの **AGENTS.md** はツール横断の汎用ファイルです(Claude Code、Cursor、Codex、OpenCode が読み込みます。GitHub Copilot は代わりに `.github/copilot-instructions.md` を使用します)
+- **DRY アダプターパターン**により、Cursor は Claude Code の hook スクリプトを重複なく再利用できます
+- **Skills 形式**(YAML frontmatter 付きの SKILL.md)は Claude Code、Codex、OpenCode で共通に機能します
+- Codex のより限定的なネイティブ hook セットは、`AGENTS.md`、オプションの `model_instructions_file` オーバーライド、サンドボックス権限によって補完されます
+
+
+Cursor IDE サポートの詳細
+
+ECC は、Cursor のプロジェクトレイアウトに合わせて調整された hooks、rules、agents、skills、コマンド、MCP 設定による Cursor IDE サポートを提供します。
+
+```bash
+# macOS/Linux
+./install.sh --target cursor typescript
+./install.sh --target cursor python golang swift php
+```
+
+```powershell
+# Windows PowerShell
+.\install.ps1 --target cursor typescript
+.\install.ps1 --target cursor python golang swift php
+```
+
+#### Cursor 向けに含まれるもの
+
+| コンポーネント | 数 | 詳細 |
+|-----------|-------|---------|
+| Hook イベント | 15 | sessionStart、beforeShellExecution、afterFileEdit、beforeMCPExecution、beforeSubmitPrompt、その他 10 個 |
+| Hook スクリプト | 16 | 共有アダプター経由で `scripts/hooks/` に委譲する薄い Node.js スクリプト |
+| Rules | 34 | 共通 9 個(alwaysApply)+ 言語固有 25 個(TypeScript、Python、Go、Swift、PHP) |
+| Agents | 48 | インストール時に `.cursor/agents/ecc-*.md` として配置。ユーザーやマーケットプレイスの agents との衝突を避けるためプレフィックス付き |
+| Skills | 共有 + 同梱 | 翻訳された追加分は `.cursor/skills/` に配置 |
+| コマンド | 共有 | インストール時は `.cursor/commands/` |
+| MCP 設定 | 共有 | インストール時は `.cursor/mcp.json` |
+
+#### Cursor の読み込みに関する注記
+
+ECC はルートの `AGENTS.md` を `.cursor/` にインストールしません。Cursor はネストされた `AGENTS.md` ファイルをディレクトリのコンテキストとして扱うため、ECC のリポジトリのアイデンティティをホストプロジェクトにコピーすると、そのプロジェクトを汚染してしまいます。
+
+Cursor ネイティブの読み込み動作は Cursor のビルドによって異なる場合があります。ECC は agents を `.cursor/agents/ecc-*.md` としてインストールします。お使いの Cursor ビルドがプロジェクト agents を公開していない場合でも、これらのファイルは隠れたグローバルプロンプトコンテキストとしてではなく、明示的なリファレンス定義として機能します。
+
+#### メモリとデータの分離(Cursor + Claude Code)
+
+ECC のメモリ hooks は Claude Code と同じ `scripts/hooks/*.js` を再利用します。Cursor では、ECC はメモリを**自動的に `~/.claude` の外に**保つよう試みます:
+
+1. **Cursor の `sessionStart` hook**(`--target cursor` で `.cursor/hooks.json` にインストール)が、composer セッション全体に `ECC_AGENT_DATA_HOME` を注入します。
+2. **Hook ランタイムのデフォルト**:`CURSOR_VERSION` または `CURSOR_PROJECT_DIR` が存在する場合、環境変数が未設定なら hooks はデフォルトで `~/.cursor/ecc` を使用します。
+3. **プロジェクト設定**:`.cursor/ecc-agent-data.json` がパス(`agentDataHome`)を文書化し、上書きします。
+4. **常時有効な rule**:`.cursor/rules/ecc-agent-data-home.mdc` が、メモリの保存場所を agent に思い出させます。
+
+明示的に上書きすることも引き続き可能です:
+
+```bash
+export ECC_AGENT_DATA_HOME="$HOME/.cursor/ecc"
+```
+
+意図的に Claude Code とメモリを**共有**するには、シェルまたは `.cursor/ecc-agent-data.json` で `ECC_AGENT_DATA_HOME=~/.claude` を設定してください。
+
+継続的学習 v2 の instincts は、引き続き `CLV2_HOMUNCULUS_DIR`(デフォルト `~/.local/share/ecc-homunculus`)の下に別途保存されます。
+
+#### Hook アーキテクチャ(DRY アダプターパターン)
+
+Cursor は **Claude Code より多くの hook イベント**を持っています(20 対 8)。`.cursor/hooks/adapter.js` モジュールが Cursor の stdin JSON を Claude Code の形式に変換するため、既存の `scripts/hooks/*.js` を重複なく再利用できます。
+
+```
+Cursor stdin JSON -> adapter.js -> transforms -> scripts/hooks/*.js
+ (shared with Claude Code)
+```
+
+主要な hooks:
+- **beforeShellExecution**:tmux 外での開発サーバー起動をブロック(exit 2)、git push のレビュー
+- **afterFileEdit**:自動フォーマット + TypeScript チェック + console.log の警告
+- **beforeSubmitPrompt**:プロンプト内のシークレット(sk-、ghp_、AKIA パターン)を検出
+- **beforeTabFileRead**:Tab による .env、.key、.pem ファイルの読み取りをブロック(exit 2)
+- **beforeMCPExecution / afterMCPExecution**:MCP の監査ログ
+
+#### Rules の形式
+
+Cursor の rules は `description`、`globs`、`alwaysApply` を持つ YAML frontmatter を使用します:
+
+```yaml
---
+description: "TypeScript coding style extending common rules"
+globs: ["**/*.ts", "**/*.tsx", "**/*.js", "**/*.jsx"]
+alwaysApply: false
+---
+```
+
-## テストを実行
+
+Codex macOS アプリ + CLI サポートの詳細
-プラグインには包括的なテストスイートが含まれています:
+ECC は、macOS アプリと CLI 向けに、サポート対象のネイティブ Codex マーケットプレイス plugin とリポジトリローカルの設定を提供します。ネイティブ plugin には共有 skills、MCP 設定、レビュー済みの hook サブセットが含まれ、Codex は hook の信頼をユーザーの明示的な管理下に置きます。従来の sync パスは互換性維持のみとして残っています。リポジトリのナビゲーション、各領域の所有権、PR diff パケットのガイダンスについては、[`docs/CODEX-NAVIGATION-GUIDE.md`](../CODEX-NAVIGATION-GUIDE.md) から始めてください。
+
+```bash
+# 現在推奨されるインストール:リポジトリのマーケットプレイスから ECC のネイティブ plugin を追加
+codex plugin marketplace add affaan-m/ECC
+codex plugin add ecc@ecc
+codex plugin list --json
+
+# またはリポジトリ内で Codex CLI を実行:AGENTS.md と .codex/ が自動検出される
+codex
+```
+
+意図的に必要な場合は、レガシーのコピー式設定による互換性も引き続き利用できます:
+
+```bash
+# 互換性維持のみのマネージド sync を ~/.codex に実行
+npm install && bash scripts/sync-ecc-to-codex.sh
+
+# またはリファレンス設定のみを手動でコピー
+cp .codex/config.toml ~/.codex/config.toml
+```
+
+sync スクリプトは、**追加のみ**の戦略を使って ECC の MCP サーバーを既存の `~/.codex/config.toml` に安全にマージします。既存のサーバーを削除したり変更したりすることは決してありません。変更をプレビューするには `--dry-run` を、ECC サーバーを最新の推奨設定に強制的に更新するには `--update-mcp` を付けて実行してください。
+
+Context7 については、ECC は正規の Codex セクション名 `[mcp_servers.context7]` を使用しつつ、引き続き `@upstash/context7-mcp` パッケージを起動します。すでにレガシーの `[mcp_servers.context7-mcp]` エントリがある場合、`--update-mcp` がそれを正規のセクション名に移行します。
+
+Codex macOS アプリ:
+- このリポジトリをワークスペースとして開きます。
+- ルートの `AGENTS.md` は自動検出されます。
+- `.codex/config.toml` と `.codex/agents/*.toml` はプロジェクトローカルに保つのが最適です。
+- リファレンスの `.codex/config.toml` は意図的に `model` や `model_provider` を固定していないため、上書きしない限り Codex は自身の現在のデフォルトを使用します。
+- オプション:グローバルなデフォルトとして `.codex/config.toml` を `~/.codex/config.toml` にコピーできます。`.codex/agents/` もコピーしない限り、マルチエージェントのロールファイルはプロジェクトローカルに保ってください。
+
+#### リポジトリとレガシー設定レイヤーに含まれるもの
+
+| コンポーネント | 数 | 詳細 |
+|-----------|-------|---------|
+| 設定 | 1 | `.codex/config.toml`:トップレベルの approvals/sandbox/web_search、MCP サーバー、通知、profiles |
+| AGENTS.md | 2 | ルート(汎用)+ `.codex/AGENTS.md`(Codex 固有の補足) |
+| Skills | 32 | `.agents/skills/`:skill ごとに SKILL.md + agents/openai.yaml |
+| MCP サーバー | 6 | GitHub、Context7、Exa、Memory、Playwright、Sequential Thinking(`--update-mcp` sync で Supabase を加えると 7) |
+| Profiles | 2 | `strict`(読み取り専用サンドボックス)と `yolo`(完全自動承認) |
+| Agent ロール | 3 | `.codex/agents/`:explorer、reviewer、docs-researcher |
+
+`.agents/skills/` にある skills は Codex によって自動的に読み込まれます。`claude-api`、`frontend-design`、`skill-creator` などの Anthropic 公式の skills は、意図的にここには再同梱していません。公式版が必要な場合は [`anthropics/skills`](https://github.com/anthropics/skills) からインストールしてください。
+
+#### 主要な制限
+
+Codex は **Claude 形式の hook 実行との同等性を提供しません**。ネイティブの ECC plugin には `/hooks` での明示的な信頼を必要とするレビュー済み hook サブセットが含まれ、`AGENTS.md`、オプションの `model_instructions_file` オーバーライド、サンドボックス/承認設定が残りの instruction とポリシーのレイヤーを提供します。
+
+#### マルチエージェントサポート
+
+現在の Codex ビルドは安定したマルチエージェントワークフローをサポートしています。
+
+- `.codex/config.toml` で `features.multi_agent = true` を有効化します
+- `[agents.]` の下でロールを定義します
+- 各ロールを `.codex/agents/` 配下のファイルに向けます
+- CLI で `/agent` を使って子エージェントを確認・操作します
+
+ECC は 3 つのサンプルロール設定を同梱しています:
+
+| ロール | 目的 |
+|------|---------|
+| `explorer` | 編集前の読み取り専用のコードベース証拠収集 |
+| `reviewer` | 正確性、セキュリティ、不足テストのレビュー |
+| `docs_researcher` | リリース/ドキュメント変更前のドキュメントと API の検証 |
+
+
+
+
+Zed サポート
+
+ECC は、プロジェクトローカルの設定、フラット化された rules、agents、コマンド、skills のための保守的な `.zed` アダプターを通じて Zed プロジェクトをサポートします。
+
+```bash
+./install.sh --profile minimal --target zed
+```
+
+```powershell
+.\install.ps1 --profile minimal --target zed
+```
+
+このアダプターは ECC が管理するファイルを `.zed/` の下に書き込み、BYOK/OpenRouter の認証情報をリポジトリの外に保ちます。Zed のアカウントや API キーは、Zed 自身の設定 UI またはローカルのユーザー設定から設定してください。
+
+
+
+OpenCode サポートの詳細
+
+ECC は、instructions、カタログのサブセット、コマンド、カスタムツール、hook イベントを備えた beta 版の OpenCode plugin 統合を提供します。Claude Code との機能同等性は提供しません。リファレンス設定は、プロバイダー固有のモデルを固定するのではなく、ユーザーの OpenCode でのモデル選択を継承します。
+
+```bash
+# リポジトリのルートで、レビュー済みの OpenCode インストールを実行
+opencode
+```
+
+インストールには[公式の OpenCode の手順](https://opencode.ai/docs/)を使用し、正確なリリースを選択して、実行前に検証してください。上流の npm パッケージは `opencode` ではなく `opencode-ai` です。ECC は監査済みの OpenCode ランタイムバージョンを保証するものではありません。
+
+設定は `.opencode/opencode.json` から自動的に検出されます。
+
+#### plugins による hook サポート
+
+OpenCode の plugin システムには 20 種類以上のイベントタイプがあります:
+
+| Claude Code Hook | OpenCode Plugin イベント |
+|-----------------|----------------------|
+| PreToolUse | `tool.execute.before` |
+| PostToolUse | `tool.execute.after` |
+| Stop | `session.idle` |
+| SessionStart | `session.created` |
+| SessionEnd | `session.deleted` |
+
+**追加の OpenCode イベント**:`file.edited`、`file.watcher.updated`、`message.updated`、`lsp.client.diagnostics`、`tui.toast.show` など。
+
+#### Plugin のインストール
+
+**オプション 1:直接使用**
+```bash
+cd ECC
+opencode
+```
+
+**オプション 2:npm パッケージとしてインストール**
+```bash
+npm install ecc-universal@2.2.1
+```
+
+次に `opencode.json` に追加します:
+```json
+{
+ "plugin": ["ecc-universal"]
+}
+```
+
+この npm plugin エントリは、ECC が公開している OpenCode plugin モジュール(hooks/イベントと plugin ツール)を有効化します。ECC の完全なコマンド/agent/instruction カタログをプロジェクト設定に自動的に追加することは**ありません**。
+
+完全な ECC OpenCode セットアップには、次のいずれかを行ってください:
+- このリポジトリ内で OpenCode を実行する
+- 同梱の `.opencode/` 設定アセットをプロジェクトにコピーし、`opencode.json` に `instructions`、`agent`、`command` のエントリを配線する
+
+#### ドキュメント
+
+- **移行ガイド**:`.opencode/MIGRATION.md`
+- **OpenCode Plugin README**:`.opencode/README.md`
+- **統合 Rules**:`.opencode/instructions/INSTRUCTIONS.md`
+- **LLM ドキュメント**:`llms.txt`(LLM 向けの完全な OpenCode ドキュメント)
+
+
+
+GitHub Copilot サポートの詳細
+
+ECC は、Copilot Chat のネイティブな instruction とプロンプトファイルのシステムを通じて、VS Code 向けの **GitHub Copilot サポート**を提供します。追加のツールは必要ありません。
+
+#### GitHub Copilot 向けに含まれるもの
+
+| コンポーネント | ファイル | 目的 |
+|-----------|------|---------|
+| コア instructions | `.github/copilot-instructions.md` | 常時読み込まれる rules:コーディングスタイル、セキュリティ、テスト、git ワークフロー |
+| VS Code 設定 | `.vscode/settings.json` | コード生成、テスト生成、コミットメッセージ向けのタスク別 instruction ファイル |
+| Plan プロンプト | `.github/prompts/plan.prompt.md` | 段階的な実装計画 |
+| TDD プロンプト | `.github/prompts/tdd.prompt.md` | Red-Green-Improve サイクル |
+| セキュリティレビュープロンプト | `.github/prompts/security-review.prompt.md` | OWASP に沿った詳細なセキュリティ分析 |
+| ビルド修正プロンプト | `.github/prompts/build-fix.prompt.md` | 体系的なビルドおよび CI エラーの解決 |
+| リファクタリングプロンプト | `.github/prompts/refactor.prompt.md` | デッドコードの削除と簡素化 |
+
+これらのファイルはすでに配置されています。このプロジェクトを含む任意のリポジトリを開けば、GitHub Copilot Chat は自動的に `.github/copilot-instructions.md` を読み込みます。コミット済みの `.vscode/settings.json` は `chat.promptFiles` を有効化しているため、VS Code は `.github/prompts/` から再利用可能なプロンプトを読み込めます。
+
+Copilot Chat でワークフロープロンプトを使用するには:
+1. VS Code で Copilot Chat パネルを開きます。
+2. **クリップ / 添付**アイコンをクリックして **Prompt...** を選択するか、`/` を入力してプロンプトを選択します。
+3. プロンプト(例:`plan`、`tdd`、`security-review`)を選択します。
+
+#### 機能カバレッジ
+
+| ECC の機能 | Copilot での相当機能 |
+|-------------|-------------------|
+| コーディング標準 | `copilot-instructions.md` 経由で常時有効 |
+| セキュリティチェックリスト | 常時有効 + `security-review` プロンプト |
+| テスト / TDD | 常時有効 + `tdd` プロンプト |
+| 実装計画 | `plan` プロンプト |
+| コードレビュー | CodeRabbit + Greptile による外部 PR レビュー |
+| ビルドエラー解決 | `build-fix` プロンプト |
+| リファクタリング | `refactor` プロンプト |
+| コミットメッセージ形式 | `settings.json` のタスク別 instruction |
+| Hooks / 自動化 | 非対応(Copilot には hook システムがありません) |
+| Agents / 委譲 | 非対応(Copilot にはサブエージェント API がありません) |
+
+#### 制限
+
+GitHub Copilot には hook システムもサブエージェント API もないため、ECC の hook 自動化(自動フォーマット、TypeScript チェック、セッション永続化、開発サーバーガード)と agent 委譲は利用できません。それでも instruction とプロンプトのレイヤーは、ECC のコーディング哲学(標準、セキュリティ、TDD、ワークフロー)をすべての Copilot Chat セッションにもたらします。
+
+
+
+v2.0.0 での変更点
+
+ECC v2.0.0 は、公開された Hermes オペレーターストーリー、281 の skills、67 の agents、94 のコマンドシム、セッションアダプター、MCP インベントリ、worktree ライフサイクルサービス、オーケストレーターワークフロー、ECC Discord コミュニティによって 2.0 系を安定化させます。
+
+- [v2.0.0 リリースノート](../releases/2.0.0/release-notes.md)
+- [ECC 2.0 リファレンスアーキテクチャ](../ECC-2.0-REFERENCE-ARCHITECTURE.md)
+- [Hermes セットアップガイド](../HERMES-SETUP.md)
+- [1.x からの移行ガイド](../MIGRATION-1X-TO-2.0.md)
+
+
+
+## トークン最適化
+
+トークン消費を管理しないと、エージェントの利用は高コストになりがちです。以下の設定は、品質を犠牲にすることなくコストを大幅に削減します。完全なガイド:[docs/token-optimization.md](../token-optimization.md)。
+
+
+推奨設定
+
+`~/.claude/settings.json` に追加してください:
+
+```json
+{
+ "model": "sonnet",
+ "env": {
+ "MAX_THINKING_TOKENS": "10000",
+ "CLAUDE_AUTOCOMPACT_PCT_OVERRIDE": "50",
+ "CLAUDE_CODE_SUBAGENT_MODEL": "haiku"
+ }
+}
+```
+
+| 設定 | デフォルト | 推奨 | 効果 |
+|---------|---------|-------------|--------|
+| `model` | opus | **sonnet** | 約 60% のコスト削減。コーディングタスクの 80% 以上に対応 |
+| `MAX_THINKING_TOKENS` | 31,999 | **10,000** | リクエストごとの隠れた思考コストを約 70% 削減 |
+| `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE` | 95 | **50** | より早くコンパクト化し、長いセッションでの品質が向上 |
+| `ECC_CONTEXT_MONITOR_COST_WARNINGS` | on | **サブスクリプション利用者は off** | コンテキスト/スコープ/ループの警告は維持しつつ、agent 向けの API 従量課金見積もり警告を抑制 |
+
+深いアーキテクチャの推論が必要なときだけ Opus に切り替えてください:
+```
+/model opus
+```
+
+
+
+日常のワークフローコマンド
+
+| コマンド | 使うタイミング |
+|---------|-------------|
+| `/model sonnet` | ほとんどのタスクのデフォルト |
+| `/model opus` | 複雑なアーキテクチャ、デバッグ、深い推論 |
+| `/clear` | 無関係なタスクの間(無料、即時リセット) |
+| `/compact` | タスクの論理的な区切り(調査完了、マイルストーン達成) |
+| `/cost` | セッション中のトークン消費を監視 |
+
+サブスクリプションを利用していて、コンテキストモニターの API 従量課金見積もりが役に立たない場合は、`ECC_CONTEXT_MONITOR_COST_WARNINGS=off` を設定してください。これは agent 向けのコスト警告のみを抑制するもので、コンテキスト枯渇、スコープ、ループの警告は無効化しません。
+
+
+
+戦略的コンパクト化
+
+`strategic-compact` skill は、コンテキスト 95% での自動コンパクト化に頼るのではなく、論理的な区切りで `/compact` を提案します。判断ガイドの全文は `skills/strategic-compact/SKILL.md` を参照してください。
+
+**コンパクト化すべきタイミング:**
+- 調査/探索の後、実装の前
+- マイルストーン完了後、次に取りかかる前
+- デバッグの後、機能開発を続ける前
+- 失敗したアプローチの後、新しいアプローチを試す前
+
+**コンパクト化すべきでないタイミング:**
+- 実装の途中(変数名、ファイルパス、途中の状態が失われます)
+
+
+
+コンテキストウィンドウの管理
+
+**重要:**すべての MCP を一度に有効化しないでください。各 MCP のツール説明は 200k のウィンドウからトークンを消費し、約 70k まで減らしてしまう可能性があります。
+
+- プロジェクトごとに有効化する MCP は 10 未満に抑える
+- アクティブなツールは 80 未満に抑える
+- 使っていない Claude Code の MCP サーバーは `/mcp` で無効化する。これらのランタイムでの選択は `~/.claude.json` に永続化される
+- `ECC_DISABLED_MCPS` は、インストール/sync フロー中に ECC が生成する MCP 設定をフィルタリングする場合にのみ使用する
+- コンテキストが重くなってきたら、`/context-budget` を実行して不要な rules を削除する
+
+**Agent teams のコスト警告:**Agent Teams は複数のコンテキストウィンドウを生成します。各チームメイトは独立してトークンを消費します。並列化が明確な価値をもたらすタスク(複数モジュールの作業、並列レビュー)にのみ使用してください。単純な逐次タスクでは、サブエージェントの方がトークン効率に優れています。
+
+
+## 要件
+
+
+Claude Code CLI のバージョン + hooks の自動読み込み動作
+
+### Claude Code CLI のバージョン
+
+**最小バージョン:v2.1.0 以降。**plugin システムの hooks の扱いが変更されたため、この plugin には Claude Code CLI v2.1.0 以降が必要です。
+
+バージョンを確認してください:
+```bash
+claude --version
+```
+
+### 重要:hooks の自動読み込み動作
+
+> WARNING: **コントリビューター向け:**`.claude-plugin/plugin.json` に `"hooks"` フィールドを追加しないでください。これはリグレッションテストで強制されています。
+
+Claude Code v2.1 以降は、インストールされた任意の plugin の `hooks/hooks.json` を規約により**自動的に読み込みます**。`plugin.json` で明示的に宣言すると重複検出エラーが発生します:
+
+```
+Duplicate hooks file detected: ./hooks/hooks.json resolves to already-loaded file
+```
+
+**経緯:**この問題はこのリポジトリで修正/差し戻しのサイクルを繰り返し引き起こしてきました([#29](https://github.com/affaan-m/ECC/issues/29)、[#52](https://github.com/affaan-m/ECC/issues/52)、[#103](https://github.com/affaan-m/ECC/issues/103))。Claude Code のバージョン間で動作が変わり、混乱を招きました。現在は再発を防ぐためのリグレッションテストがあります。
+
+
+## セキュリティ
+
+ECC は公式ソースからのみインストールしてください:
+
+- GitHub リポジトリ:
+- Claude Code plugin:`ecc@ecc`
+- npm パッケージ:[`ecc-universal`](https://www.npmjs.com/package/ecc-universal) と [`ecc-agentshield`](https://www.npmjs.com/package/ecc-agentshield)
+- GitHub App:
+- Web サイト:
+
+すでにインストール済みのレビュー済み AgentShield バイナリでプロジェクトをスキャンします([ランナーの出所](#agentshield-runner-provenance)を参照):
+
+```bash
+agentshield scan --path .
+```
+
+- **脆弱性の報告。**[SECURITY.md](../../SECURITY.md) に記載の非公開プロセス(GitHub のプライベート脆弱性報告)を使用してください。セキュリティ報告のために公開 issue を開かないでください。
+- **組み込みのガードレール。**GateGuard は破壊的なシェルコマンド(`rm`、force/path 指定の `git checkout`、破壊的な `find -exec` を含む)を実行前にゲートします。サプライチェーン IOC スキャナーは CI で実行され、AgentShield はあなた自身の agent、hook、MCP、権限、シークレットの各領域を監査します(`/security-scan`)。
+
+
+Hooks、MCP サーバー、コンテキスト制御
+
+hooks はシェルコマンドを実行でき、MCP サーバーは認証情報を保持でき、プロジェクトの instructions はエージェントのコンテキストに入り込めます。この 3 つすべてを実行可能な設定として扱ってください。
+
+plugin インストール後に、生の `hooks/hooks.json` を `~/.claude/settings.json` にコピーしないでください。最近の Claude Code バージョンは plugin の hooks を自動的に読み込むため、2 つ目のコピーがあると二重に発火する可能性があります。
+
+Claude Code のランタイムでの無効化には `/mcp` を使用してください。Claude Code はその選択を `~/.claude.json` に永続化します。
+
+`ECC_DISABLED_MCPS` は ECC のインストール/sync フィルターであり、Claude Code のライブなトグルではありません。
+
+コンテキストが重くなってきたら、`/context-budget` を実行し、不要な rules を削除し、使っていない MCP サーバーを無効化してください。[トークン最適化ガイド](../token-optimization.md)を参照してください。
+
+
+セキュリティ関連の参考資料:
+
+- [セキュリティポリシー](../../SECURITY.md)
+- [セキュリティガイド](../../the-security-guide.md)
+- [MCP コネクターポリシー](../MCP-CONNECTOR-POLICY.md)
+- [サプライチェーンインシデント対応](../security/supply-chain-incident-response.md)
+
+## エコシステムツール
+
+
+Skill Creator:git 履歴から skills を生成する
+
+リポジトリから skills を生成する方法は 2 つあります:
+
+### オプション A:ローカル分析(組み込み)
+
+外部サービスを使わないローカル分析には `/skill-create` コマンドを使用してください:
+
+```bash
+/skill-create # 現在のリポジトリを分析
+/skill-create --instincts # continuous-learning-v2 向けの instincts も生成
+```
+
+これは git 履歴をローカルで分析し、SKILL.md ファイルを生成します。
+
+### オプション B:GitHub App(高度)
+
+高度な機能(10k 以上のコミット、自動 PR、チーム共有)には:
+
+[ECC Tools GitHub App をインストール](https://github.com/apps/ecc-tools) | [ecc.tools](https://ecc.tools)
+
+```bash
+# 任意の issue にコメント:
+/ecc-tools analyze
+```
+
+どちらのオプションでも以下が作成されます:
+- **SKILL.md ファイル**:アクティブなハーネスですぐに使える skills
+- **Instinct コレクション**:continuous-learning-v2 向け
+- **パターン抽出**:コミット履歴から学習
+
+
+
+AgentShield:エージェント設定のセキュリティ監査ツール
+
+> Claude Code ハッカソン(Cerebral Valley x Anthropic、2026 年 2 月)で構築。1282 のテスト、98% のカバレッジ、102 の静的解析ルール。
+
+エージェント設定の脆弱性、設定ミス、インジェクションリスクをスキャンします。
+
+
+**ランナーの出所:**これらのコマンドには、`ecc-agentshield` からインストール済みのレビュー済み AgentShield バイナリが必要です。[公式パッケージ](https://www.npmjs.com/package/ecc-agentshield)が `agentshield` CLI を文書化しています。選択したリリース、レビューしたソース、検証済みのパッケージ整合性をインストール記録に残してください。レジストリへの公開だけでは監査済みとは言えません。ECC はここで監査済みの AgentShield のピン留めを提供しません。バージョン指定のないワンショットダウンロードで代用しないでください。`/security-scan` はワークフローのガイダンスであり、同じランナーの前提条件があります。
+
+```bash
+# 意図したプロジェクトディレクトリのみをスキャン
+agentshield scan --path .
+
+# 安全な問題を自動修正
+agentshield scan --path . --fix
+
+# 3 つの Opus 4.6 エージェントによる詳細分析
+agentshield scan --path . --opus --stream
+
+# 安全な設定をゼロから生成
+agentshield init
+```
+
+**スキャン対象:**CLAUDE.md、settings.json、MCP 設定、hooks、agent 定義、skills を 5 つのカテゴリで検査します:シークレット検出(14 パターン)、権限監査、hook インジェクション分析、MCP サーバーのリスクプロファイリング、agent 設定レビュー。
+
+**`--opus` フラグ**は、レッドチーム/ブルーチーム/監査人のパイプラインで 3 つの Claude Opus 4.6 エージェントを実行します。攻撃者がエクスプロイトチェーンを見つけ、防御者が保護を評価し、監査人が両者を統合して優先順位付きのリスク評価を作成します。単なるパターンマッチングではなく、敵対的な推論です。
+
+**出力形式:**ターミナル(A-F の色付き評価)、JSON(CI パイプライン)、Markdown、HTML。ビルドゲート用に、重大な検出があると終了コード 2 を返します。
+
+Claude Code で実行するには `/security-scan` を使うか、[GitHub Action](https://github.com/affaan-m/agentshield) で CI に追加してください。
+
+[GitHub](https://github.com/affaan-m/agentshield) | [npm](https://www.npmjs.com/package/ecc-agentshield)
+
+
+
+継続的学習 v2:instincts
+
+instinct ベースの学習システムは、あなたのパターンを自動的に学習します:
+
+```bash
+/instinct-status # 学習済み instincts を信頼度とともに表示
+/instinct-import # 他の人の instincts をインポート
+/instinct-export # 共有用に自分の instincts をエクスポート
+/evolve # 関連する instincts を skills にクラスタリング
+```
+
+完全なドキュメントは `skills/continuous-learning-v2/` を参照してください。`continuous-learning/` は、レガシーの v1 Stop-hook による学習済み skill フローを明示的に使いたい場合にのみ残してください。
+
+
+## トラブルシューティング
+
+
+ECC が二重に表示される、または hooks が二重に発火する
+
+よくある原因は、Claude plugin をインストールした上に `./install.sh --profile full` を実行することです。
+
+1. Claude Code plugin のインストールを削除します。
+2. ECC のチェックアウトから `node scripts/ecc.js uninstall --dry-run` を実行します。
+3. 手動でコピーした不要な rule フォルダを削除します。
+4. 1 つの方法で一度だけ再インストールします。
+
+hook 固有のチェックについては、[hooks README](../../hooks/README.md) を参照してください。
+
+
+
+hooks が動作しない / "Duplicate hooks file" エラー
+
+**`.claude-plugin/plugin.json` に `"hooks"` フィールドを追加しないでください。**Claude Code v2.1 以降は、インストールされた plugins の `hooks/hooks.json` を自動的に読み込みます。明示的に宣言すると重複検出エラーが発生します。[#29](https://github.com/affaan-m/ECC/issues/29)、[#52](https://github.com/affaan-m/ECC/issues/52)、[#103](https://github.com/affaan-m/ECC/issues/103) を参照してください。
+
+
+
+Codex マーケットプレイスからインストールできるが skills が読み込まれない
+
+ECC のチェックアウトからキャッシュチェックを実行してください:
+
+```bash
+node scripts/codex/check-plugin-cache.js
+```
+
+未解決の親参照が報告された場合は、`codex plugin marketplace upgrade ecc` でネイティブキャッシュを更新し、`codex plugin add ecc@ecc` を再度実行して、Codex を再起動してください。`codex plugin list` への登録はマーケットプレイスのエントリを確認するものであり、キャッシュチェックはインストール済みマニフェストがその skills、MCP 設定、アセットを解決できることを検証します。`bash scripts/sync-ecc-to-codex.sh` は、レガシーのコピー式設定による互換性パスが意図的に必要な場合にのみ使用してください。
+
+
+さらなる回答:[TROUBLESHOOTING.md](../../TROUBLESHOOTING.md) はメモリ、hooks、インストール、パフォーマンス、よくあるエラーメッセージを扱っています。[docs/TROUBLESHOOTING.md](../TROUBLESHOOTING.md) は Claude Code の未解決バグに対する回避策を追跡しています。
+
+## テストの実行
+
+この plugin には包括的なテストスイートが含まれています:
```bash
# すべてのテストを実行
@@ -588,211 +1946,67 @@ node tests/lib/package-manager.test.js
node tests/hooks/hooks.test.js
```
----
-
-## 貢献
-
-**貢献は大歓迎で、奨励されています。**
-
-このリポジトリはコミュニティリソースを目指しています。以下のようなものがあれば:
-- 有用なエージェントまたはスキル
-- 巧妙なフック
-- より良い MCP 設定
-- 改善されたルール
-
-ぜひ貢献してください!ガイドについては[CONTRIBUTING.md](CONTRIBUTING.md)を参照してください。
-
-### 貢献アイデア
-
-- 言語固有のスキル(Rust、C#、Swift、Kotlin) — Go、Python、Javaは既に含まれています
-- フレームワーク固有の設定(Rails、Laravel、FastAPI) — Django、NestJS、Spring Bootは既に含まれています
-- DevOpsエージェント(Kubernetes、Terraform、AWS、Docker)
-- テスト戦略(異なるフレームワーク、ビジュアルリグレッション)
-- 専門領域の知識(ML、データエンジニアリング、モバイル開発)
-
----
-
-## Cursor IDE サポート
-
-ecc-universal は [Cursor IDE](https://cursor.com) の事前翻訳設定を含みます。`.cursor/` ディレクトリには、Cursor フォーマット向けに適応されたルール、エージェント、スキル、コマンド、MCP 設定が含まれています。
-
-### クイックスタート (Cursor)
-
-```bash
-# パッケージをインストール
-npm install ecc-universal
-
-# 言語をインストール
-./install.sh --target cursor typescript
-./install.sh --target cursor python golang
-```
-
-### 翻訳内容
-
-| コンポーネント | Claude Code → Cursor | パリティ |
-|-----------|---------------------|--------|
-| Rules | YAML フロントマター追加、パスフラット化 | 完全 |
-| Agents | モデル ID 展開、ツール → 読み取り専用フラグ | 完全 |
-| Skills | 変更不要(同一の標準) | 同一 |
-| Commands | パス参照更新、multi-* スタブ化 | 部分的 |
-| MCP Config | 環境補間構文更新 | 完全 |
-| Hooks | Cursor相当なし | 別の方法を参照 |
-
-詳細は[.cursor/README.md](.cursor/README.md)および完全な移行ガイドは[.cursor/MIGRATION.md](.cursor/MIGRATION.md)を参照してください。
-
----
-
-## OpenCodeサポート
-
-ECCは**フルOpenCodeサポート**をプラグインとフック含めて提供。
-
-### クイックスタート
-
-```bash
-# OpenCode をインストール
-npm install -g opencode
-
-# リポジトリルートで実行
-opencode
-```
-
-設定は`.opencode/opencode.json`から自動検出されます。
-
-### 機能パリティ
-
-| 機能 | Claude Code | OpenCode | ステータス |
-|---------|-------------|----------|--------|
-| Agents | PASS: 14 エージェント | PASS: 12 エージェント | **Claude Code がリード** |
-| Commands | PASS: 30 コマンド | PASS: 24 コマンド | **Claude Code がリード** |
-| Skills | PASS: 28 スキル | PASS: 16 スキル | **Claude Code がリード** |
-| Hooks | PASS: 3 フェーズ | PASS: 20+ イベント | **OpenCode が多い!** |
-| Rules | PASS: 8 ルール | PASS: 8 ルール | **完全パリティ** |
-| MCP Servers | PASS: 完全 | PASS: 完全 | **完全パリティ** |
-| Custom Tools | PASS: フック経由 | PASS: ネイティブサポート | **OpenCode がより良い** |
-
-### プラグイン経由のフックサポート
-
-OpenCodeのプラグインシステムはClaude Codeより高度で、20+イベントタイプ:
-
-| Claude Code フック | OpenCode プラグインイベント |
-|-----------------|----------------------|
-| PreToolUse | `tool.execute.before` |
-| PostToolUse | `tool.execute.after` |
-| Stop | `session.idle` |
-| SessionStart | `session.created` |
-| SessionEnd | `session.deleted` |
-
-**追加OpenCodeイベント**: `file.edited`, `file.watcher.updated`, `message.updated`, `lsp.client.diagnostics`, `tui.toast.show`など。
-
-### 利用可能なコマンド(24)
-
-| コマンド | 説明 |
-|---------|-------------|
-| `/plan` | 実装計画を作成 |
-| `/tdd` | TDD ワークフロー実行 |
-| `/code-review` | コード変更をレビュー |
-| `/security` | セキュリティレビュー実行 |
-| `/build-fix` | ビルドエラーを修正 |
-| `/e2e` | E2E テストを生成 |
-| `/refactor-clean` | デッドコードを削除 |
-| `/orchestrate` | マルチエージェント ワークフロー |
-| `/learn` | セッションからパターン抽出 |
-| `/checkpoint` | 検証状態を保存 |
-| `/verify` | 検証ループを実行 |
-| `/eval` | 基準に対して評価 |
-| `/update-docs` | ドキュメントを更新 |
-| `/update-codemaps` | コードマップを更新 |
-| `/test-coverage` | カバレッジを分析 |
-| `/go-review` | Go コードレビュー |
-| `/go-test` | Go TDD ワークフロー |
-| `/go-build` | Go ビルドエラーを修正 |
-| `/skill-create` | Git からスキル生成 |
-| `/instinct-status` | 学習した直感を表示 |
-| `/instinct-import` | 直感をインポート |
-| `/instinct-export` | 直感をエクスポート |
-| `/evolve` | 直感をスキルにクラスタリング |
-| `/setup-pm` | パッケージマネージャーを設定 |
-
-### プラグインインストール
-
-**オプション1:直接使用**
-```bash
-cd everything-claude-code
-opencode
-```
-
-**オプション2:npmパッケージとしてインストール**
-```bash
-npm install ecc-universal
-```
-
-その後`opencode.json`に追加:
-```json
-{
- "plugin": ["ecc-universal"]
-}
-```
-
-### ドキュメンテーション
-
-- **移行ガイド**: `.opencode/MIGRATION.md`
-- **OpenCode プラグイン README**: `.opencode/README.md`
-- **統合ルール**: `.opencode/instructions/INSTRUCTIONS.md`
-- **LLM ドキュメンテーション**: `llms.txt`(完全な OpenCode ドキュメント)
-
----
-
## 背景
-実験的なリリース以来、Claude Codeを使用してきました。2025年9月、[@DRodriguezFX](https://x.com/DRodriguezFX)と一緒にClaude Codeで[zenith.chat](https://zenith.chat)を構築し、Anthropic x Forum Venturesハッカソンで優勝しました。
+私は実験的なロールアウトの頃から Claude Code を使ってきました。2025 年 9 月に [@DRodriguezFX](https://x.com/DRodriguezFX) とともに Anthropic x Forum Ventures ハッカソンで優勝し、[zenith.chat](https://zenith.chat) を完全にエージェント型ワークフローで構築しました。
-これらの設定は複数の本番環境アプリケーションで実戦テストされています。
+これらの設定は、複数の本番アプリケーションで実戦検証済みです。
----
+## コミュニティとプロジェクト
-## WARNING: 重要な注記
+
+スポンサーと ECC Pro
-### コンテキストウィンドウ管理
+ECC が無料であり続けられるのは、スポンサーと Pro ユーザーが活動を支えてくれているからです。スポンサーのロゴはこの README の冒頭にあり、完全な一覧とティアは [SPONSORS.md](../../SPONSORS.md) にあります。
-**重要:** すべてのMCPを一度に有効にしないでください。多くのツールを有効にすると、200kのコンテキストウィンドウが70kに縮小される可能性があります。
+ECC Pro は、ホスト型 GitHub App を通じて、プライベートリポジトリの分析、PR トリガーの監査、AgentShield ベースのスキャン、自動 push および PR チェック、チームでの共有利用枠、優先サポートを追加します。
-経験則:
-- 20-30のMCPを設定
-- プロジェクトごとに10未満を有効にしたままにしておく
-- アクティブなツール80未満
+
+
+ECC Pro
プライベートリポジトリ向けホスト型 GitHub App
+ECC をスポンサーする
OSS 活動を支援する
+コミュニティ
Q&A、アイデア、Show and Tell
+GitHub App
PR 監査とホスト型ワークフロー
+
+
-プロジェクト設定で`disabledMcpServers`を使用して、未使用のツールを無効にします。
+[スポンサーになる](https://github.com/sponsors/affaan-m) | [スポンサーティア](../../SPONSORS.md) | [スポンサーシッププログラム](../../SPONSORING.md)
+
-### カスタマイズ
+
+コントリビューション
-これらの設定は私のワークフロー用です。あなたは以下を行うべきです:
-1. 共感できる部分から始める
-2. 技術スタックに合わせて修正
-3. 使用しない部分を削除
-4. 独自のパターンを追加
+skills、agents、rules、hooks、ドキュメント、テスト、アダプター、セキュリティ改善など、あらゆる分野でのコントリビューションを歓迎します。
----
+- [コントリビューションガイド](../../CONTRIBUTING.md)
+- [Skill 開発ガイド](../SKILL-DEVELOPMENT-GUIDE.md)
+- [Skill 配置ポリシー](../SKILL-PLACEMENT-POLICY.md)
+- [コマンド クイックリファレンス](./COMMANDS-QUICK-REF.md)
-## Star 履歴
+要約すると:
+1. リポジトリをフォークします
+2. `skills/your-skill-name/SKILL.md` に skill を作成します(YAML frontmatter 付き)
+3. または `agents/your-agent.md` に agent を作成します
+4. 何をするものか、いつ使うのかを明確に説明した PR を送ります
-[](https://star-history.com/#affaan-m/everything-claude-code&Date)
+**コントリビューションのアイデア:**
----
+- 言語固有の skills(Rust、C#、Kotlin、Java):Go、Python、Perl、Swift、TypeScript、HarmonyOS/ArkTS はすでに含まれています
+- フレームワーク固有の設定(Rails、FastAPI):Django、NestJS、Spring Boot、Laravel はすでに含まれています
+- DevOps agents(Kubernetes、Terraform、AWS、Docker)
+- テスト戦略(さまざまなフレームワーク、ビジュアルリグレッション)
+- ドメイン固有の知識(ML、データエンジニアリング、モバイル)
+
## リンク
-- **簡潔ガイド(まずはこれ):** [Everything Claude Code 簡潔ガイド](https://x.com/affaanmustafa/status/2012378465664745795)
-- **詳細ガイド(高度):** [Everything Claude Code 詳細ガイド](https://x.com/affaanmustafa/status/2014040193557471352)
-- **フォロー:** [@affaanmustafa](https://x.com/affaanmustafa)
-- **zenith.chat:** [zenith.chat](https://zenith.chat)
-- **スキル ディレクトリ:** awesome-agent-skills(コミュニティ管理のエージェントスキル ディレクトリ)
-
----
+- **簡潔ガイド(まずはここから):**[ECC 簡潔ガイド](https://x.com/affaan/status/2012378465664745795)
+- **長文ガイド(上級者向け):**[ECC 長文ガイド](https://x.com/affaan/status/2014040193557471352)
+- **セキュリティガイド:**[セキュリティガイド](../../the-security-guide.md) | [スレッド](https://x.com/affaan/status/2033263813387223421)
+- **フォロー:**[@affaan](https://x.com/affaan)
## ライセンス
-MIT - 自由に使用、必要に応じて修正、可能であれば貢献してください。
+MIT。自由に使い、自分のワークフローに合わせて調整し、できるときには貢献を返してください。
----
-
-**このリポジトリが役に立ったら、Star を付けてください。両方のガイドを読んでください。素晴らしいものを構築してください。**
+**役に立ったらこのリポジトリにスターを。ガイドを読んでください。素晴らしいものを作りましょう。**
diff --git a/docs/ja-JP/rules/common/agents.md b/docs/ja-JP/rules/common/agents.md
index 92137264a..71cd7754e 100644
--- a/docs/ja-JP/rules/common/agents.md
+++ b/docs/ja-JP/rules/common/agents.md
@@ -2,27 +2,34 @@
## 利用可能な Agent
-`~/.claude/agents/` に配置:
+ECC の Agent は `ecc@ecc` プラグインに同梱されており、`~/.claude/agents/` には配置されません。
+Agent ツールではプラグインスコープの `subagent_type` で呼び出します:
+
+```text
+Agent(subagent_type: "ecc:planner", prompt: "...")
+```
| Agent | 目的 | 使用タイミング |
|-------|---------|-------------|
-| planner | 実装計画 | 複雑な機能、リファクタリング |
-| architect | システム設計 | アーキテクチャの意思決定 |
-| tdd-guide | テスト駆動開発 | 新機能、バグ修正 |
-| code-reviewer | コードレビュー | コード記述後 |
-| security-reviewer | セキュリティ分析 | コミット前 |
-| build-error-resolver | ビルドエラー修正 | ビルド失敗時 |
-| e2e-runner | E2Eテスト | 重要なユーザーフロー |
-| refactor-cleaner | デッドコードクリーンアップ | コードメンテナンス |
-| doc-updater | ドキュメント | ドキュメント更新 |
+| ecc:planner | 実装計画 | 複雑な機能、リファクタリング |
+| ecc:architect | システム設計 | アーキテクチャの意思決定 |
+| ecc:tdd-guide | テスト駆動開発 | 新機能、バグ修正 |
+| ecc:code-reviewer | コードレビュー | コード記述後 |
+| ecc:security-reviewer | セキュリティ分析 | コミット前 |
+| ecc:build-error-resolver | ビルドエラー修正 | ビルド失敗時 |
+| ecc:e2e-runner | E2Eテスト | 重要なユーザーフロー |
+| ecc:refactor-cleaner | デッドコードクリーンアップ | コードメンテナンス |
+| ecc:doc-updater | ドキュメント | ドキュメント更新 |
+
+全 68 Agent の一覧は `/ecc:ecc-guide` を参照。
## Agent の即座の使用
ユーザープロンプト不要:
-1. 複雑な機能リクエスト - **planner** agent を使用
-2. コード作成/変更直後 - **code-reviewer** agent を使用
-3. バグ修正または新機能 - **tdd-guide** agent を使用
-4. アーキテクチャの意思決定 - **architect** agent を使用
+1. 複雑な機能リクエスト - **ecc:planner** agent を使用
+2. コード作成/変更直後 - **ecc:code-reviewer** agent を使用
+3. バグ修正または新機能 - **ecc:tdd-guide** agent を使用
+4. アーキテクチャの意思決定 - **ecc:architect** agent を使用
## 並列タスク実行
diff --git a/docs/pt-BR/README.md b/docs/pt-BR/README.md
index c0d9203b6..e33eff641 100644
--- a/docs/pt-BR/README.md
+++ b/docs/pt-BR/README.md
@@ -79,7 +79,7 @@ Este repositório contém apenas o código. Os guias explicam tudo.
## O Que Há de Novo
-### v2.2.1 — Instalação Guiada para Múltiplos Harnesses (Ago 2026)
+### v2.2.2 — Instalação Guiada para Múltiplos Harnesses (Ago 2026)
Adiciona uma instalação revisável para Claude Code, Codex e Kimi Code, com uma entrada de comando npm sincronizada.
diff --git a/docs/tr/AGENTS.md b/docs/tr/AGENTS.md
index c49b9962a..a67004d7b 100644
--- a/docs/tr/AGENTS.md
+++ b/docs/tr/AGENTS.md
@@ -2,7 +2,7 @@
Bu, yazılım geliştirme için 68 özel agent, 292 skill, 94 command ve otomatik hook iş akışları sağlayan **üretime hazır bir AI kodlama eklentisidir**.
-**Sürüm:** 2.2.1
+**Sürüm:** 2.2.2
## Temel İlkeler
@@ -47,14 +47,14 @@ Bu, yazılım geliştirme için 68 özel agent, 292 skill, 94 command ve otomati
## Agent Orkestrasyonu
Agentları kullanıcı istemi olmadan proaktif olarak kullanın:
-- Karmaşık özellik istekleri → **planner**
-- Yeni yazılan/değiştirilen kod → **code-reviewer**
-- Hata düzeltme veya yeni özellik → **tdd-guide**
-- Mimari karar → **architect**
-- Güvenlik açısından hassas kod → **security-reviewer**
-- Çok kanallı iletişim önceliklendirme → **chief-of-staff**
-- Otonom döngüler / döngü izleme → **loop-operator**
-- Harness yapılandırma güvenilirliği ve maliyeti → **harness-optimizer**
+- Karmaşık özellik istekleri → **ecc:planner**
+- Yeni yazılan/değiştirilen kod → **ecc:code-reviewer**
+- Hata düzeltme veya yeni özellik → **ecc:tdd-guide**
+- Mimari karar → **ecc:architect**
+- Güvenlik açısından hassas kod → **ecc:security-reviewer**
+- Çok kanallı iletişim önceliklendirme → **ecc:chief-of-staff**
+- Otonom döngüler / döngü izleme → **ecc:loop-operator**
+- Harness yapılandırma güvenilirliği ve maliyeti → **ecc:harness-optimizer**
Bağımsız işlemler için paralel yürütme kullanın — birden fazla agenti aynı anda başlatın.
diff --git a/docs/tr/README.md b/docs/tr/README.md
index f7546bed7..1fc5e2f5b 100644
--- a/docs/tr/README.md
+++ b/docs/tr/README.md
@@ -79,7 +79,7 @@ Bu repository yalnızca ham kodu içerir. Rehberler her şeyi açıklıyor.
## Yenilikler
-### v2.2.1 — Rehberli Çoklu Harness Kurulumu (Ağu 2026)
+### v2.2.2 — Rehberli Çoklu Harness Kurulumu (Ağu 2026)
Claude Code, Codex ve Kimi Code için incelenebilir çoklu harness kurulumu ve eşitlenmiş npm komut girişi eklendi.
diff --git a/docs/tr/rules/common/agents.md b/docs/tr/rules/common/agents.md
index b40d5897b..d00403e87 100644
--- a/docs/tr/rules/common/agents.md
+++ b/docs/tr/rules/common/agents.md
@@ -2,28 +2,35 @@
## Mevcut Agent'lar
-`~/.claude/agents/` dizininde bulunur:
+ECC agent'ları `ecc@ecc` eklentisiyle birlikte gelir, `~/.claude/agents/` dizininde bulunmaz.
+Agent aracıyla eklenti kapsamlı bir `subagent_type` ile çağrılır:
+
+```text
+Agent(subagent_type: "ecc:planner", prompt: "...")
+```
| Agent | Amaç | Ne Zaman Kullanılır |
|-------|---------|-------------|
-| planner | Uygulama planlaması | Karmaşık özellikler, refactoring |
-| architect | Sistem tasarımı | Mimari kararlar |
-| tdd-guide | Test odaklı geliştirme | Yeni özellikler, hata düzeltmeleri |
-| code-reviewer | Kod incelemesi | Kod yazdıktan sonra |
-| security-reviewer | Güvenlik analizi | Commit'lerden önce |
-| build-error-resolver | Build hatalarını düzeltme | Build başarısız olduğunda |
-| e2e-runner | E2E testleri | Kritik kullanıcı akışları |
-| refactor-cleaner | Ölü kod temizliği | Kod bakımı |
-| doc-updater | Dokümantasyon | Dokümanları güncelleme |
-| rust-reviewer | Rust kod incelemesi | Rust projeleri |
+| ecc:planner | Uygulama planlaması | Karmaşık özellikler, refactoring |
+| ecc:architect | Sistem tasarımı | Mimari kararlar |
+| ecc:tdd-guide | Test odaklı geliştirme | Yeni özellikler, hata düzeltmeleri |
+| ecc:code-reviewer | Kod incelemesi | Kod yazdıktan sonra |
+| ecc:security-reviewer | Güvenlik analizi | Commit'lerden önce |
+| ecc:build-error-resolver | Build hatalarını düzeltme | Build başarısız olduğunda |
+| ecc:e2e-runner | E2E testleri | Kritik kullanıcı akışları |
+| ecc:refactor-cleaner | Ölü kod temizliği | Kod bakımı |
+| ecc:doc-updater | Dokümantasyon | Dokümanları güncelleme |
+| ecc:rust-reviewer | Rust kod incelemesi | Rust projeleri |
+
+68 agent'ın tam listesi için `/ecc:ecc-guide` bölümüne bakın.
## Anlık Agent Kullanımı
Kullanıcı istemi gerekmez:
-1. Karmaşık özellik istekleri - **planner** agent kullan
-2. Kod yeni yazıldı/değiştirildi - **code-reviewer** agent kullan
-3. Hata düzeltmesi veya yeni özellik - **tdd-guide** agent kullan
-4. Mimari karar - **architect** agent kullan
+1. Karmaşık özellik istekleri - **ecc:planner** agent kullan
+2. Kod yeni yazıldı/değiştirildi - **ecc:code-reviewer** agent kullan
+3. Hata düzeltmesi veya yeni özellik - **ecc:tdd-guide** agent kullan
+4. Mimari karar - **ecc:architect** agent kullan
## Paralel Görev Yürütme
diff --git a/docs/tr/the-shortform-guide.md b/docs/tr/the-shortform-guide.md
index eb8a917ba..90519eb48 100644
--- a/docs/tr/the-shortform-guide.md
+++ b/docs/tr/the-shortform-guide.md
@@ -420,7 +420,7 @@ affoon:~ ctx:65% Opus 4.5 19:52
- [Interactive Mode](https://code.claude.com/docs/en/interactive-mode)
- [Memory Sistemi](https://code.claude.com/docs/en/memory)
- [Subagent'lar](https://code.claude.com/docs/en/sub-agents)
-- [MCP Genel Bakış](https://code.claude.com/docs/en/mcp-overview)
+- [MCP Genel Bakış](https://code.claude.com/docs/en/mcp)
---
diff --git a/docs/uk-UA/README.md b/docs/uk-UA/README.md
index 5f5ce627d..7c8f28f88 100644
--- a/docs/uk-UA/README.md
+++ b/docs/uk-UA/README.md
@@ -27,8 +27,8 @@
diff --git a/docs/ur/README.md b/docs/ur/README.md
index a91e4f698..32185989e 100644
--- a/docs/ur/README.md
+++ b/docs/ur/README.md
@@ -4,8 +4,8 @@

-[](https://github.com/affaan-m/ECC/stargazers)
-[](https://github.com/affaan-m/ECC/network/members)
+[](https://github.com/affaan-m/ECC)
+[](https://github.com/affaan-m/ECC/forks)
[](https://github.com/affaan-m/ECC/graphs/contributors)
[](https://www.npmjs.com/package/ecc-universal)
[](https://www.npmjs.com/package/ecc-agentshield)
diff --git a/docs/zh-CN/AGENTS.md b/docs/zh-CN/AGENTS.md
index 2f5a18856..31e1a3817 100644
--- a/docs/zh-CN/AGENTS.md
+++ b/docs/zh-CN/AGENTS.md
@@ -2,7 +2,7 @@
这是一个**生产就绪的 AI 编码插件**,提供 68 个专业代理、292 项技能、94 条命令以及自动化钩子工作流,用于软件开发。
-**版本:** 2.2.1
+**版本:** 2.2.2
## 核心原则
@@ -48,14 +48,14 @@
主动使用智能体,无需用户提示:
-* 复杂功能请求 → **planner**
-* 刚编写/修改的代码 → **code-reviewer**
-* 错误修复或新功能 → **tdd-guide**
-* 架构决策 → **architect**
-* 安全敏感代码 → **security-reviewer**
-* 多渠道沟通分流 → **chief-of-staff**
-* 自主循环 / 循环监控 → **loop-operator**
-* 线束配置可靠性及成本 → **harness-optimizer**
+* 复杂功能请求 → **ecc:planner**
+* 刚编写/修改的代码 → **ecc:code-reviewer**
+* 错误修复或新功能 → **ecc:tdd-guide**
+* 架构决策 → **ecc:architect**
+* 安全敏感代码 → **ecc:security-reviewer**
+* 多渠道沟通分流 → **ecc:chief-of-staff**
+* 自主循环 / 循环监控 → **ecc:loop-operator**
+* 线束配置可靠性及成本 → **ecc:harness-optimizer**
对于独立操作使用并行执行 — 同时启动多个智能体。
diff --git a/docs/zh-CN/README.md b/docs/zh-CN/README.md
index 422f22d5d..3228c6159 100644
--- a/docs/zh-CN/README.md
+++ b/docs/zh-CN/README.md
@@ -81,7 +81,7 @@
## 最新动态
-### v2.2.1 — 引导式多 Harness 安装(2026年8月)
+### v2.2.2 — 引导式多 Harness 安装(2026年8月)
新增可审查的 Claude Code、Codex 与 Kimi Code 多 Harness 安装流程,并提供同步的 npm 命令入口。
@@ -1292,7 +1292,7 @@ ECC 是**第一个最大化利用每个主要 AI 编码工具的插件**。以
| **上下文文件** | CLAUDE.md + AGENTS.md | AGENTS.md | AGENTS.md | AGENTS.md |
| **秘密检测** | 基于钩子 | beforeSubmitPrompt 钩子 | 基于沙箱 | 基于钩子 |
| **自动格式化** | PostToolUse 钩子 | afterFileEdit 钩子 | N/A | file.edited 钩子 |
-| **版本** | 插件 | 插件 | 参考配置 | 2.2.1 |
+| **版本** | 插件 | 插件 | 参考配置 | 2.2.2 |
**关键架构决策:**
diff --git a/docs/zh-CN/rules/common/agents.md b/docs/zh-CN/rules/common/agents.md
index de32b0b56..3f3c2edaa 100644
--- a/docs/zh-CN/rules/common/agents.md
+++ b/docs/zh-CN/rules/common/agents.md
@@ -2,29 +2,36 @@
## 可用智能体
-位于 `~/.claude/agents/` 中:
+ECC 智能体随 `ecc@ecc` 插件一起分发,不在 `~/.claude/agents/` 目录中。
+它们通过 Agent 工具以插件作用域的 `subagent_type` 调用:
+
+```text
+Agent(subagent_type: "ecc:planner", prompt: "...")
+```
| 代理 | 用途 | 使用时机 |
|-------|---------|-------------|
-| planner | 实现规划 | 复杂功能、重构 |
-| architect | 系统设计 | 架构决策 |
-| tdd-guide | 测试驱动开发 | 新功能、错误修复 |
-| code-reviewer | 代码审查 | 编写代码后 |
-| security-reviewer | 安全分析 | 提交前 |
-| build-error-resolver | 修复构建错误 | 构建失败时 |
-| e2e-runner | 端到端测试 | 关键用户流程 |
-| refactor-cleaner | 清理死代码 | 代码维护 |
-| doc-updater | 文档 | 更新文档 |
-| rust-reviewer | Rust 代码审查 | Rust 项目 |
+| ecc:planner | 实现规划 | 复杂功能、重构 |
+| ecc:architect | 系统设计 | 架构决策 |
+| ecc:tdd-guide | 测试驱动开发 | 新功能、错误修复 |
+| ecc:code-reviewer | 代码审查 | 编写代码后 |
+| ecc:security-reviewer | 安全分析 | 提交前 |
+| ecc:build-error-resolver | 修复构建错误 | 构建失败时 |
+| ecc:e2e-runner | 端到端测试 | 关键用户流程 |
+| ecc:refactor-cleaner | 清理死代码 | 代码维护 |
+| ecc:doc-updater | 文档 | 更新文档 |
+| ecc:rust-reviewer | Rust 代码审查 | Rust 项目 |
+
+完整 68 个智能体的清单参见 `/ecc:ecc-guide`。
## 即时智能体使用
无需用户提示:
-1. 复杂的功能请求 - 使用 **planner** 智能体
-2. 刚编写/修改的代码 - 使用 **code-reviewer** 智能体
-3. 错误修复或新功能 - 使用 **tdd-guide** 智能体
-4. 架构决策 - 使用 **architect** 智能体
+1. 复杂的功能请求 - 使用 **ecc:planner** 智能体
+2. 刚编写/修改的代码 - 使用 **ecc:code-reviewer** 智能体
+3. 错误修复或新功能 - 使用 **ecc:tdd-guide** 智能体
+4. 架构决策 - 使用 **ecc:architect** 智能体
## 并行任务执行
diff --git a/docs/zh-CN/the-shortform-guide.md b/docs/zh-CN/the-shortform-guide.md
index e662afa28..f5dcbb55d 100644
--- a/docs/zh-CN/the-shortform-guide.md
+++ b/docs/zh-CN/the-shortform-guide.md
@@ -421,7 +421,7 @@ affoon:~ ctx:65% Opus 4.5 19:52
* [交互模式](https://code.claude.com/docs/en/interactive-mode)
* [记忆系统](https://code.claude.com/docs/en/memory)
* [子代理](https://code.claude.com/docs/en/sub-agents)
-* [MCP 概述](https://code.claude.com/docs/en/mcp-overview)
+* [MCP 概述](https://code.claude.com/docs/en/mcp)
***
diff --git a/ecc2/Cargo.lock b/ecc2/Cargo.lock
index ab4d168cc..67258a667 100644
--- a/ecc2/Cargo.lock
+++ b/ecc2/Cargo.lock
@@ -2375,9 +2375,9 @@ dependencies = [
[[package]]
name = "toml"
-version = "1.1.4+spec-1.1.0"
+version = "1.1.6+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3aace63f4bbcdfc2c965b059de67119c89c4017a70d633be6c104910f67056f5"
+checksum = "920602543f0911ab71da12c50d59701da54c196d1a2bf5cb4b75667f137a406a"
dependencies = [
"indexmap",
"serde_core",
@@ -2528,9 +2528,9 @@ checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
[[package]]
name = "ureq"
-version = "3.4.0"
+version = "3.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "972d7902c8735f2695410b8aed7df6ed12a47394aa1c8d7af49f0497b731a94d"
+checksum = "af5546be8f5378d5414f83733f5c9a2526f4645829edbc1c41790aeef1b38e8b"
dependencies = [
"base64 0.23.1",
"cookie_store",
@@ -2548,9 +2548,9 @@ dependencies = [
[[package]]
name = "ureq-proto"
-version = "0.6.1"
+version = "0.6.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "da5f78b09e6941e1a0f2e30e695e4b120377b54d5e0aec11b594bb57b3971613"
+checksum = "5b0809a01d1ca5a51ca70db32bb2a19157582a526505ef3c19e3b343a59aa5ad"
dependencies = [
"base64 0.23.1",
"http",
@@ -2590,9 +2590,9 @@ checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
[[package]]
name = "uuid"
-version = "1.26.0"
+version = "1.26.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b5772d71c9be8a8a6ac2117d949c5b224c1b72241bb611d9a3012edcf8af7812"
+checksum = "2ef6dac1e96601b4fb3acccccff2139741fcb757cb9a36089bf5be91cfb285ce"
dependencies = [
"atomic",
"getrandom 0.4.2",
diff --git a/ecc2/README.md b/ecc2/README.md
index 71aad6da8..2ea06c961 100644
--- a/ecc2/README.md
+++ b/ecc2/README.md
@@ -14,6 +14,12 @@ It is usable as an alpha for local experimentation, but it is **not** the finish
- worktree-aware session scaffolding
- basic multi-session state and output tracking
+Dashboard output is hydrated from SQLite at startup and after recovery, then
+synchronized with a monotonic database cursor. Because session runners are
+separate processes, the database remains the cross-process source of truth
+while steady-state refreshes read only the rows appended since the previous
+dashboard tick.
+
## What This Is For
ECC 2.0 is the layer above individual harness installs.
diff --git a/ecc2/src/session/output.rs b/ecc2/src/session/output.rs
index d7ac8745f..1edd3f800 100644
--- a/ecc2/src/session/output.rs
+++ b/ecc2/src/session/output.rs
@@ -5,6 +5,8 @@ use serde::{Deserialize, Serialize};
use tokio::sync::broadcast;
pub const OUTPUT_BUFFER_LIMIT: usize = 1000;
+/// Maximum number of cross-process output rows applied during one dashboard refresh.
+pub const OUTPUT_DELTA_BATCH_LIMIT: usize = 4096;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum OutputStream {
@@ -113,16 +115,6 @@ impl SessionOutputStore {
});
}
- pub fn replace_lines(&self, session_id: &str, lines: Vec) {
- let mut buffer: VecDeque = lines.into_iter().collect();
-
- while buffer.len() > self.capacity {
- let _ = buffer.pop_front();
- }
-
- self.lock_buffers().insert(session_id.to_string(), buffer);
- }
-
pub fn lines(&self, session_id: &str) -> Vec {
self.lock_buffers()
.get(session_id)
diff --git a/ecc2/src/session/store.rs b/ecc2/src/session/store.rs
index f71bb3640..de1af81fc 100644
--- a/ecc2/src/session/store.rs
+++ b/ecc2/src/session/store.rs
@@ -28,6 +28,31 @@ pub struct StateStore {
conn: Connection,
}
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub(crate) struct SessionOutputRecord {
+ pub id: i64,
+ pub session_id: String,
+ pub line: OutputLine,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub(crate) struct SessionOutputBatch {
+ pub cursor: i64,
+ pub records: Vec,
+}
+
+/// Converts one persisted output row into the dashboard's typed record.
+fn output_record_from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result {
+ let stream: String = row.get(2)?;
+ let text: String = row.get(3)?;
+ let timestamp: String = row.get(4)?;
+ Ok(SessionOutputRecord {
+ id: row.get(0)?,
+ session_id: row.get(1)?,
+ line: OutputLine::new(OutputStream::from_db_value(&stream), text, timestamp),
+ })
+}
+
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct HarnessAuditEntry {
pub id: i64,
@@ -4000,6 +4025,53 @@ impl StateStore {
Ok(lines)
}
+ /// Returns a bounded recent-output snapshot and its highest persisted row ID.
+ pub(crate) fn get_output_snapshot(
+ &self,
+ limit_per_session: usize,
+ ) -> Result {
+ let limit_per_session = i64::try_from(limit_per_session.max(1)).unwrap_or(i64::MAX);
+ let mut stmt = self.conn.prepare(
+ "SELECT id, session_id, stream, line, timestamp
+ FROM (
+ SELECT id, session_id, stream, line, timestamp,
+ ROW_NUMBER() OVER (PARTITION BY session_id ORDER BY id DESC) AS row_num
+ FROM session_output
+ )
+ WHERE row_num <= ?1
+ ORDER BY id ASC",
+ )?;
+ let records = stmt
+ .query_map(rusqlite::params![limit_per_session], output_record_from_row)?
+ .collect::, _>>()?;
+ let cursor = records.last().map(|record| record.id).unwrap_or(0);
+
+ Ok(SessionOutputBatch { cursor, records })
+ }
+
+ /// Returns at most `limit` output rows newer than `cursor` in insertion order.
+ pub(crate) fn get_output_since(
+ &self,
+ cursor: i64,
+ limit: usize,
+ ) -> Result {
+ let cursor = cursor.max(0);
+ let limit = i64::try_from(limit.max(1)).unwrap_or(i64::MAX);
+ let mut stmt = self.conn.prepare(
+ "SELECT id, session_id, stream, line, timestamp
+ FROM session_output
+ WHERE id > ?1
+ ORDER BY id ASC
+ LIMIT ?2",
+ )?;
+ let records = stmt
+ .query_map(rusqlite::params![cursor, limit], output_record_from_row)?
+ .collect::, _>>()?;
+ let cursor = records.last().map(|record| record.id).unwrap_or(cursor);
+
+ Ok(SessionOutputBatch { cursor, records })
+ }
+
pub fn insert_tool_log(
&self,
session_id: &str,
@@ -7382,6 +7454,69 @@ mod tests {
Ok(())
}
+ #[test]
+ fn output_cursor_reads_a_bounded_snapshot_then_only_new_rows() -> Result<()> {
+ let tempdir = TestDir::new("store-output-cursor")?;
+ let db = StateStore::open(&tempdir.path().join("state.db"))?;
+
+ db.insert_session(&build_session("session-1", SessionState::Running))?;
+ db.insert_session(&build_session("session-2", SessionState::Running))?;
+ db.append_output_line("session-1", OutputStream::Stdout, "one-a")?;
+ db.append_output_line("session-2", OutputStream::Stderr, "two-a")?;
+ db.append_output_line("session-1", OutputStream::Stdout, "one-b")?;
+ db.append_output_line("session-2", OutputStream::Stdout, "two-b")?;
+ db.append_output_line("session-1", OutputStream::Stdout, "one-c")?;
+
+ let snapshot = db.get_output_snapshot(2)?;
+ assert_eq!(snapshot.cursor, 5);
+ assert_eq!(
+ snapshot
+ .records
+ .iter()
+ .map(|record| (record.session_id.as_str(), record.line.text.as_str()))
+ .collect::>(),
+ vec![
+ ("session-2", "two-a"),
+ ("session-1", "one-b"),
+ ("session-2", "two-b"),
+ ("session-1", "one-c"),
+ ]
+ );
+
+ db.append_output_line("session-2", OutputStream::Stderr, "two-c")?;
+ db.append_output_line("session-1", OutputStream::Stdout, "one-d")?;
+ let delta = db.get_output_since(snapshot.cursor, 1)?;
+ assert_eq!(delta.cursor, 6);
+ assert_eq!(delta.records.len(), 1);
+ assert_eq!(delta.records[0].session_id, "session-2");
+ assert_eq!(delta.records[0].line.text, "two-c");
+
+ let next = db.get_output_since(delta.cursor, 1)?;
+ assert_eq!(next.cursor, 7);
+ assert_eq!(next.records.len(), 1);
+ assert_eq!(next.records[0].session_id, "session-1");
+ assert_eq!(next.records[0].line.text, "one-d");
+
+ let empty = db.get_output_since(next.cursor, 1)?;
+ assert_eq!(empty.cursor, next.cursor);
+ assert!(empty.records.is_empty());
+
+ let query_plan = db
+ .conn
+ .prepare(
+ "EXPLAIN QUERY PLAN SELECT id FROM session_output WHERE id > ?1 ORDER BY id ASC",
+ )?
+ .query_map(rusqlite::params![snapshot.cursor], |row| {
+ row.get::<_, String>(3)
+ })?
+ .collect::, _>>()?;
+ assert!(query_plan
+ .iter()
+ .any(|detail| detail.contains("INTEGER PRIMARY KEY") && detail.contains("rowid>?")));
+
+ Ok(())
+ }
+
#[test]
fn message_round_trip_tracks_unread_counts_and_read_state() -> Result<()> {
let tempdir = TestDir::new("store-messages")?;
diff --git a/ecc2/src/tui/dashboard.rs b/ecc2/src/tui/dashboard.rs
index c98b4e2c2..deb34605a 100644
--- a/ecc2/src/tui/dashboard.rs
+++ b/ecc2/src/tui/dashboard.rs
@@ -10,7 +10,6 @@ use ratatui::{
use regex::Regex;
use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
use std::time::UNIX_EPOCH;
-use tokio::sync::broadcast;
use super::widgets::{budget_state, format_currency, format_token_count, BudgetState, TokenMeter};
use crate::comms;
@@ -19,12 +18,12 @@ use crate::notifications::{DesktopNotifier, NotificationEvent, WebhookNotifier};
use crate::observability::ToolLogEntry;
use crate::session::manager;
use crate::session::output::{
- OutputEvent, OutputLine, OutputStream, SessionOutputStore, OUTPUT_BUFFER_LIMIT,
+ OutputLine, OutputStream, OUTPUT_BUFFER_LIMIT, OUTPUT_DELTA_BATCH_LIMIT,
};
-use crate::session::store::{DaemonActivity, FileActivityOverlap, StateStore};
+use crate::session::store::{DaemonActivity, FileActivityOverlap, SessionOutputRecord, StateStore};
use crate::session::{
- ContextObservationPriority, DecisionLogEntry, FileActivityEntry, Session, SessionGrouping,
- SessionBoardMeta, SessionHarnessInfo, SessionMessage, SessionState,
+ ContextObservationPriority, DecisionLogEntry, FileActivityEntry, Session, SessionBoardMeta,
+ SessionGrouping, SessionHarnessInfo, SessionMessage, SessionState,
};
use crate::worktree;
@@ -79,16 +78,42 @@ struct TestRunSummary {
passed: usize,
}
+/// Consumes an output cache and returns a new bounded cache with `records` appended.
+fn append_output_records(
+ mut cache: HashMap>,
+ records: Vec,
+) -> HashMap> {
+ let mut touched_sessions = HashSet::new();
+ for record in records {
+ cache
+ .entry(record.session_id.clone())
+ .or_default()
+ .push(record.line);
+ touched_sessions.insert(record.session_id);
+ }
+
+ for session_id in touched_sessions {
+ if let Some(lines) = cache.get_mut(&session_id) {
+ let overflow = lines.len().saturating_sub(OUTPUT_BUFFER_LIMIT);
+ if overflow > 0 {
+ lines.drain(..overflow);
+ }
+ }
+ }
+
+ cache
+}
+
pub struct Dashboard {
db: StateStore,
cfg: Config,
- output_store: SessionOutputStore,
- output_rx: broadcast::Receiver,
notifier: DesktopNotifier,
webhook_notifier: WebhookNotifier,
sessions: Vec,
session_harnesses: HashMap,
session_output_cache: HashMap>,
+ session_output_generations: HashMap>,
+ output_cursor: Option,
unread_message_counts: HashMap,
approval_queue_counts: HashMap,
approval_queue_preview: Vec,
@@ -502,15 +527,8 @@ fn load_session_harnesses(
}
impl Dashboard {
+ /// Builds the dashboard and hydrates its initial bounded output snapshot.
pub fn new(db: StateStore, cfg: Config) -> Self {
- Self::with_output_store(db, cfg, SessionOutputStore::default())
- }
-
- pub fn with_output_store(
- db: StateStore,
- cfg: Config,
- output_store: SessionOutputStore,
- ) -> Self {
let pane_size_percent = configured_pane_size(&cfg, cfg.pane_layout);
let initial_cost_metrics_signature = metrics_file_signature(&cfg.cost_metrics_path());
let initial_tool_activity_signature =
@@ -528,12 +546,15 @@ impl Dashboard {
.iter()
.map(|session| (session.id.clone(), session.state.clone()))
.collect();
+ let session_output_generations = sessions
+ .iter()
+ .map(|session| (session.id.clone(), session.created_at))
+ .collect();
let initial_approval_message_id = db
.latest_unread_approval_message()
.ok()
.flatten()
.map(|message| message.id);
- let output_rx = output_store.subscribe();
let notifier = DesktopNotifier::new(cfg.desktop_notifications.clone());
let webhook_notifier = WebhookNotifier::new(cfg.webhook_notifications.clone());
let mut session_table_state = TableState::default();
@@ -544,13 +565,13 @@ impl Dashboard {
let mut dashboard = Self {
db,
cfg,
- output_store,
- output_rx,
notifier,
webhook_notifier,
sessions,
session_harnesses,
session_output_cache: HashMap::new(),
+ session_output_generations,
+ output_cursor: None,
unread_message_counts: HashMap::new(),
approval_queue_counts: HashMap::new(),
approval_queue_preview: Vec::new(),
@@ -624,6 +645,7 @@ impl Dashboard {
dashboard.sync_handoff_backlog_counts();
dashboard.sync_board_meta();
dashboard.sync_global_handoff_backlog();
+ dashboard.sync_output_cache();
dashboard.sync_selected_output();
dashboard.sync_selected_diff();
dashboard.sync_selected_messages();
@@ -3211,6 +3233,7 @@ impl Dashboard {
));
}
+ /// Refreshes persisted dashboard state while preserving the output cursor.
pub fn refresh(&mut self) {
self.sync_from_store();
}
@@ -3993,15 +4016,6 @@ impl Dashboard {
}
pub async fn tick(&mut self) {
- loop {
- match self.output_rx.try_recv() {
- Ok(_event) => {}
- Err(broadcast::error::TryRecvError::Empty) => break,
- Err(broadcast::error::TryRecvError::Lagged(_)) => continue,
- Err(broadcast::error::TryRecvError::Closed) => break,
- }
- }
-
if let Err(error) = manager::activate_pending_worktree_sessions(&self.db, &self.cfg).await {
tracing::warn!("Failed to activate queued worktree sessions: {error}");
}
@@ -4073,18 +4087,22 @@ impl Dashboard {
)
}
+ /// Synchronizes dashboard state, deferring output recovery until sessions load.
fn sync_from_store(&mut self) {
let (heartbeat_enforcement, budget_enforcement, conflict_enforcement) =
self.sync_runtime_metrics();
let selected_id = self.selected_session_id().map(ToOwned::to_owned);
- self.sessions = match self.db.list_sessions() {
+ let sessions_refreshed = match self.db.list_sessions() {
Ok(mut sessions) => {
sort_sessions_for_display(&mut sessions);
- sessions
+ self.sessions = sessions;
+ true
}
Err(error) => {
tracing::warn!("Failed to refresh sessions: {error}");
- Vec::new()
+ self.output_cursor = None;
+ self.sessions.clear();
+ false
}
};
self.session_harnesses = load_session_harnesses(&self.db, &self.cfg, &self.sessions);
@@ -4103,7 +4121,9 @@ impl Dashboard {
self.sync_approval_notifications();
self.sync_global_handoff_backlog();
self.sync_daemon_activity();
- self.sync_output_cache();
+ if sessions_refreshed {
+ self.sync_output_cache();
+ }
self.sync_selection_by_id(selected_id.as_deref());
self.ensure_selected_pane_visible();
self.sync_selected_output();
@@ -4481,25 +4501,43 @@ impl Dashboard {
}
fn sync_output_cache(&mut self) {
- let active_session_ids: HashSet<_> = self
+ let active_session_generations: HashMap<_, _> = self
.sessions
.iter()
- .map(|session| session.id.as_str())
+ .map(|session| (session.id.clone(), session.created_at))
.collect();
- self.session_output_cache
- .retain(|session_id, _| active_session_ids.contains(session_id.as_str()));
+ let cached_generations = &self.session_output_generations;
+ self.session_output_cache = std::mem::take(&mut self.session_output_cache)
+ .into_iter()
+ .filter(|(session_id, _)| {
+ active_session_generations.get(session_id) == cached_generations.get(session_id)
+ })
+ .collect();
+ self.session_output_generations = active_session_generations;
- for session in &self.sessions {
- match self.db.get_output_lines(&session.id, OUTPUT_BUFFER_LIMIT) {
- Ok(lines) => {
- self.output_store.replace_lines(&session.id, lines.clone());
- self.session_output_cache.insert(session.id.clone(), lines);
- }
- Err(error) => {
- tracing::warn!("Failed to load session output for {}: {error}", session.id);
- }
+ let batch = match self.output_cursor {
+ Some(cursor) => self
+ .db
+ .get_output_since(cursor, OUTPUT_DELTA_BATCH_LIMIT),
+ None => self.db.get_output_snapshot(OUTPUT_BUFFER_LIMIT),
+ };
+ let batch = match batch {
+ Ok(batch) => batch,
+ Err(error) => {
+ tracing::warn!("Failed to refresh session output cache: {error}");
+ return;
}
+ };
+
+ if self.output_cursor.is_none() {
+ self.session_output_cache = HashMap::new();
}
+ self.output_cursor = Some(batch.cursor);
+
+ self.session_output_cache = append_output_records(
+ std::mem::take(&mut self.session_output_cache),
+ batch.records,
+ );
}
fn ensure_selected_pane_visible(&mut self) {
@@ -5212,6 +5250,7 @@ impl Dashboard {
.map(|session| session.id.as_str())
}
+ /// Returns the selected session's currently cached output window.
fn selected_output_lines(&self) -> &[OutputLine] {
self.selected_session_id()
.and_then(|session_id| self.session_output_cache.get(session_id))
@@ -13147,6 +13186,260 @@ diff --git a/src/lib.rs b/src/lib.rs
Ok(())
}
+ #[test]
+ fn output_cache_appends_rows_written_by_another_process_without_rehydrating() -> Result<()> {
+ let db_path =
+ std::env::temp_dir().join(format!("ecc2-output-cursor-{}.db", Uuid::new_v4()));
+ let db = StateStore::open(&db_path)?;
+ let session = sample_session("session-1", "claude", SessionState::Running, None, 0, 0);
+ db.insert_session(&session)?;
+ db.append_output_line("session-1", OutputStream::Stdout, "persisted-before-open")?;
+
+ let mut dashboard = Dashboard::new(db, Config::default());
+ assert!(dashboard
+ .selected_output_text()
+ .contains("persisted-before-open"));
+ dashboard
+ .session_output_cache
+ .entry("session-1".to_string())
+ .or_default()
+ .push(test_output_line(OutputStream::Stdout, "cache-only"));
+
+ let child = Command::new(std::env::current_exe()?)
+ .args([
+ "--exact",
+ "tui::dashboard::tests::output_cursor_child_writer",
+ "--ignored",
+ "--nocapture",
+ ])
+ .env("ECC2_OUTPUT_CURSOR_CHILD_DB", &db_path)
+ .status()?;
+ assert!(child.success(), "child output writer should succeed");
+ dashboard.refresh();
+
+ let text = dashboard.selected_output_text();
+ assert!(text.contains("persisted-before-open"));
+ assert!(text.contains("cache-only"));
+ assert!(text.contains("persisted-after-open"));
+
+ dashboard.sync_output_cache();
+ assert_eq!(
+ dashboard
+ .selected_output_lines()
+ .iter()
+ .filter(|line| line.text == "persisted-after-open")
+ .count(),
+ 1
+ );
+
+ let _ = std::fs::remove_file(db_path);
+ Ok(())
+ }
+
+ #[test]
+ #[ignore = "helper invoked by output cursor cross-process test"]
+ fn output_cursor_child_writer() -> Result<()> {
+ let Some(db_path) = std::env::var_os("ECC2_OUTPUT_CURSOR_CHILD_DB") else {
+ return Ok(());
+ };
+ StateStore::open(Path::new(&db_path))?.append_output_line(
+ "session-1",
+ OutputStream::Stderr,
+ "persisted-after-open",
+ )
+ }
+
+ #[test]
+ fn output_cache_rehydrates_after_transient_session_list_failure() -> Result<()> {
+ let db_path =
+ std::env::temp_dir().join(format!("ecc2-output-recovery-{}.db", Uuid::new_v4()));
+ let db = StateStore::open(&db_path)?;
+ let session = sample_session("session-1", "claude", SessionState::Running, None, 0, 0);
+ db.insert_session(&session)?;
+ db.append_output_line("session-1", OutputStream::Stdout, "persisted-output")?;
+
+ let mut dashboard = Dashboard::new(db, Config::default());
+ assert!(dashboard
+ .selected_output_text()
+ .contains("persisted-output"));
+ dashboard
+ .session_output_cache
+ .entry("session-1".to_string())
+ .or_default()
+ .push(test_output_line(OutputStream::Stdout, "cache-only"));
+
+ let schema = rusqlite::Connection::open(&db_path)?;
+ schema.execute("ALTER TABLE sessions RENAME TO unavailable_sessions", [])?;
+ dashboard.sync_from_store();
+ assert!(dashboard.sessions.is_empty());
+ assert!(dashboard.session_output_cache["session-1"]
+ .iter()
+ .any(|line| line.text == "cache-only"));
+ assert!(dashboard.output_cursor.is_none());
+
+ dashboard.sync_from_store();
+ assert!(dashboard.session_output_cache["session-1"]
+ .iter()
+ .any(|line| line.text == "cache-only"));
+ assert!(dashboard.output_cursor.is_none());
+
+ schema.execute("ALTER TABLE unavailable_sessions RENAME TO sessions", [])?;
+ dashboard.sync_from_store();
+
+ assert_eq!(dashboard.sessions.len(), 1);
+ assert!(dashboard
+ .selected_output_text()
+ .contains("persisted-output"));
+ assert!(!dashboard.selected_output_text().contains("cache-only"));
+
+ let _ = std::fs::remove_file(db_path);
+ Ok(())
+ }
+
+ #[test]
+ fn output_cache_tracks_session_add_delete_and_same_id_recreation() -> Result<()> {
+ let db_path =
+ std::env::temp_dir().join(format!("ecc2-output-lifecycle-{}.db", Uuid::new_v4()));
+ let db = StateStore::open(&db_path)?;
+ db.insert_session(&sample_session(
+ "session-1",
+ "claude",
+ SessionState::Running,
+ None,
+ 0,
+ 0,
+ ))?;
+ db.append_output_line("session-1", OutputStream::Stdout, "first-session")?;
+
+ let mut dashboard = Dashboard::new(db, Config::default());
+ let external = StateStore::open(&db_path)?;
+ external.insert_session(&sample_session(
+ "session-2",
+ "codex",
+ SessionState::Running,
+ None,
+ 0,
+ 0,
+ ))?;
+ external.append_output_line("session-2", OutputStream::Stderr, "new-session")?;
+ dashboard.sync_from_store();
+
+ assert!(dashboard
+ .sessions
+ .iter()
+ .any(|session| session.id == "session-2"));
+ assert_eq!(
+ dashboard.session_output_cache["session-2"][0].text,
+ "new-session"
+ );
+
+ external.delete_session("session-2")?;
+ let replacement_time = Utc::now() + chrono::Duration::seconds(1);
+ external.insert_session(&Session {
+ created_at: replacement_time,
+ updated_at: replacement_time,
+ last_heartbeat_at: replacement_time,
+ ..sample_session("session-2", "codex", SessionState::Running, None, 0, 0)
+ })?;
+ external.append_output_line("session-2", OutputStream::Stdout, "replacement-session")?;
+ dashboard.sync_from_store();
+
+ let replacement = &dashboard.session_output_cache["session-2"];
+ assert_eq!(replacement.len(), 1);
+ assert_eq!(replacement[0].text, "replacement-session");
+
+ let _ = std::fs::remove_file(db_path);
+ Ok(())
+ }
+
+ #[test]
+ fn output_cache_retries_delta_after_transient_output_query_failure() -> Result<()> {
+ let db_path =
+ std::env::temp_dir().join(format!("ecc2-output-query-retry-{}.db", Uuid::new_v4()));
+ let db = StateStore::open(&db_path)?;
+ db.insert_session(&sample_session(
+ "session-1",
+ "claude",
+ SessionState::Running,
+ None,
+ 0,
+ 0,
+ ))?;
+ db.append_output_line("session-1", OutputStream::Stdout, "persisted-before")?;
+
+ let mut dashboard = Dashboard::new(db, Config::default());
+ dashboard
+ .session_output_cache
+ .get_mut("session-1")
+ .expect("hydrated output")
+ .push(test_output_line(OutputStream::Stdout, "cache-only"));
+ let cursor = dashboard.output_cursor;
+
+ let schema = rusqlite::Connection::open(&db_path)?;
+ schema.execute(
+ "ALTER TABLE session_output RENAME TO unavailable_session_output",
+ [],
+ )?;
+ dashboard.sync_output_cache();
+ assert_eq!(dashboard.output_cursor, cursor);
+ assert!(dashboard.session_output_cache["session-1"]
+ .iter()
+ .any(|line| line.text == "cache-only"));
+
+ schema.execute(
+ "ALTER TABLE unavailable_session_output RENAME TO session_output",
+ [],
+ )?;
+ StateStore::open(&db_path)?.append_output_line(
+ "session-1",
+ OutputStream::Stderr,
+ "persisted-after",
+ )?;
+ dashboard.sync_output_cache();
+
+ let output = &dashboard.session_output_cache["session-1"];
+ assert!(output.iter().any(|line| line.text == "cache-only"));
+ assert_eq!(
+ output
+ .iter()
+ .filter(|line| line.text == "persisted-after")
+ .count(),
+ 1
+ );
+
+ let _ = std::fs::remove_file(db_path);
+ Ok(())
+ }
+
+ #[test]
+ fn append_output_records_bounds_each_session_to_the_latest_window() {
+ let mut cache = HashMap::from([(
+ "session-2".to_string(),
+ vec![test_output_line(OutputStream::Stderr, "other-session")],
+ )]);
+ let records = (0..(OUTPUT_BUFFER_LIMIT + 5))
+ .map(|index| crate::session::store::SessionOutputRecord {
+ id: index as i64 + 1,
+ session_id: "session-1".to_string(),
+ line: test_output_line(OutputStream::Stdout, &format!("line-{index}")),
+ })
+ .collect();
+
+ cache = append_output_records(cache, records);
+
+ let session_lines = cache.get("session-1").expect("session output");
+ assert_eq!(session_lines.len(), OUTPUT_BUFFER_LIMIT);
+ assert_eq!(
+ session_lines.first().map(|line| line.text.as_str()),
+ Some("line-5")
+ );
+ assert_eq!(
+ session_lines.last().map(|line| line.text.as_str()),
+ Some(format!("line-{}", OUTPUT_BUFFER_LIMIT + 4).as_str())
+ );
+ assert_eq!(cache["session-2"][0].text, "other-session");
+ }
+
#[test]
fn submit_search_tracks_matches_and_sets_navigation_note() {
let mut dashboard = test_dashboard(
@@ -14917,8 +15210,10 @@ diff --git a/src/lib.rs b/src/lib.rs
)
})
.collect();
- let output_store = SessionOutputStore::default();
- let output_rx = output_store.subscribe();
+ let session_output_generations = sessions
+ .iter()
+ .map(|session| (session.id.clone(), session.created_at))
+ .collect();
let mut session_table_state = TableState::default();
if !sessions.is_empty() {
session_table_state.select(Some(selected_session));
@@ -14928,13 +15223,13 @@ diff --git a/src/lib.rs b/src/lib.rs
db: StateStore::open(Path::new(":memory:")).expect("open test db"),
pane_size_percent: configured_pane_size(&cfg, cfg.pane_layout),
cfg,
- output_store,
- output_rx,
notifier,
webhook_notifier,
sessions,
session_harnesses,
session_output_cache: HashMap::new(),
+ session_output_generations,
+ output_cursor: None,
unread_message_counts: HashMap::new(),
approval_queue_counts: HashMap::new(),
approval_queue_preview: Vec::new(),
diff --git a/eslint.config.js b/eslint.config.js
index 788a502b5..22f924aff 100644
--- a/eslint.config.js
+++ b/eslint.config.js
@@ -30,5 +30,11 @@ module.exports = [
languageOptions: {
sourceType: 'module'
}
+ },
+ {
+ files: ['docker/context-profiles/complex-eval/**/recurring-incident/**/*.js'],
+ languageOptions: {
+ sourceType: 'module'
+ }
}
];
diff --git a/install.ps1 b/install.ps1
index 752ac2ec4..e04db118f 100644
--- a/install.ps1
+++ b/install.ps1
@@ -35,12 +35,13 @@ $scriptDir = Split-Path -Parent $scriptPath
$installerScript = Join-Path -Path (Join-Path -Path $scriptDir -ChildPath 'scripts') -ChildPath 'install-apply.js'
# Auto-install Node dependencies when running from a git clone
+# SECURITY: --ignore-scripts blocks preinstall/postinstall RCE from a compromised dependency.
$nodeModules = Join-Path -Path $scriptDir -ChildPath 'node_modules'
if (-not (Test-Path -LiteralPath $nodeModules)) {
Write-Host '[ECC] Installing dependencies...'
Push-Location $scriptDir
try {
- & npm install --no-audit --no-fund --loglevel=error
+ & npm install --ignore-scripts --no-audit --no-fund --loglevel=error
if ($LASTEXITCODE -ne 0) {
Write-Error "npm install failed with exit code $LASTEXITCODE"
exit $LASTEXITCODE
diff --git a/install.sh b/install.sh
index f14c057cd..8d6aaa9c5 100755
--- a/install.sh
+++ b/install.sh
@@ -4,6 +4,14 @@
# This wrapper resolves the real repo/package root when invoked through a
# symlinked npm bin, then delegates to the Node-based installer runtime.
+# Re-exec under bash if invoked via a POSIX sh (e.g. `sh install.sh`), since
+# the rest of this script relies on bash features (`set -o pipefail`, `[[`).
+# Probe actual shell capability instead of trusting $BASH_VERSION, which is
+# just an environment variable and could be inherited/spoofed under sh.
+if ! (eval '[[ 1 == 1 ]]' >/dev/null 2>&1); then
+ exec bash "$0" "$@"
+fi
+
set -euo pipefail
SCRIPT_PATH="$0"
@@ -14,16 +22,18 @@ while [ -L "$SCRIPT_PATH" ]; do
done
SCRIPT_DIR="$(cd "$(dirname "$SCRIPT_PATH")" && pwd)"
-# Auto-install Node dependencies when running from a git clone
+# Auto-install Node dependencies when running from a git clone.
+# SECURITY: --ignore-scripts blocks preinstall/postinstall RCE from a
+# compromised dependency. ECC deps are pure JS (no native build step).
if [ ! -d "$SCRIPT_DIR/node_modules" ]; then
echo "[ECC] Installing dependencies..."
- (cd "$SCRIPT_DIR" && npm install --no-audit --no-fund --loglevel=error)
+ (cd "$SCRIPT_DIR" && npm install --ignore-scripts --no-audit --no-fund --loglevel=error)
fi
# On MSYS2/Git Bash, convert the POSIX path to a Windows path so Node.js
# (a native Windows binary) receives a valid path instead of a doubled one
# like G:\g\projects\... that results from Git Bash's auto path conversion.
-if command -v cygpath &>/dev/null; then
+if command -v cygpath >/dev/null 2>&1; then
NODE_SCRIPT="$(cygpath -w "$SCRIPT_DIR/scripts/install-apply.js")"
else
NODE_SCRIPT="$SCRIPT_DIR/scripts/install-apply.js"
diff --git a/manifests/context-packs/skill-registry@1.json b/manifests/context-packs/skill-registry@1.json
new file mode 100644
index 000000000..08f0d6351
--- /dev/null
+++ b/manifests/context-packs/skill-registry@1.json
@@ -0,0 +1,9 @@
+{
+ "schemaVersion": 1,
+ "id": "skill-registry@1",
+ "inventory": {
+ "source": "manifests/install-modules.json",
+ "skillsRoot": "skills"
+ },
+ "overrides": []
+}
diff --git a/manifests/context-packs/skill-triggers@1.json b/manifests/context-packs/skill-triggers@1.json
new file mode 100644
index 000000000..d591dee56
--- /dev/null
+++ b/manifests/context-packs/skill-triggers@1.json
@@ -0,0 +1 @@
+{"coverage":{"skills":292,"withTriggers":32},"generatedAt":"2026-09-24T23:51:22.784Z","id":"skill-triggers@1","model":{"effort":null,"id":"hand-seeded","source":"manual-curation-pending-regeneration"},"registryDigest":"2c24ec8ddbe6837f0187e2c953e17e14d83b45d348850643e9bd806e00efe70c","schemaVersion":1,"triggers":{"skill:api-connector-builder":["add api integration","new provider connector","match existing integration pattern"],"skill:api-design":["rest endpoint design","pagination api","status codes","api versioning","rate limiting api","resource naming","filtering api","api error responses","offset pagination","limit query parameter","pagination defaults"],"skill:backend-patterns":["express api","node backend architecture","nextjs api routes","server side patterns","data access layer","static file server","url path handling","file server"],"skill:browser-qa":["deployed feature test","visual regression screenshots","core web vitals check","axe accessibility audit","ship do not ship","staging verification"],"skill:canary-watch":["post deploy monitoring","smoke test url","production url check","console errors production","sse stream check","after deploy verification"],"skill:code-tour":["onboarding walkthrough","explain subsystem","architecture tour","pr walkthrough","rca tour"],"skill:coding-standards":["code review standards","naming conventions","readability review","immutability conventions","fix naming typo","export naming","consistent exports"],"skill:content-hash-cache-pattern":["cache file processing","content addressed cache","sha256 hash cache"],"skill:database-migrations":["zero downtime migration","schema change production","add column large table","backfill data","expand contract","concurrent index","migration rollback","prisma migration","django migration"],"skill:deployment-patterns":["ci cd setup","dockerize app","health checks","rollback strategy","production readiness","deploy pipeline","containerize application"],"skill:design-system":["design tokens","visual consistency audit","css custom properties","ui audit","design system bootstrap"],"skill:django-patterns":["django orm","drf api","django rest framework","django caching","django signals","django middleware"],"skill:django-security":["django authentication","csrf protection","sql injection prevention","xss prevention","django deployment security","role based access control","authorization middleware","permissions checks"],"skill:docker-patterns":["dockerfile review","docker compose setup","container security","multi service orchestration"],"skill:error-handling":["error types","retry logic","circuit breaker","user facing errors","exception handling patterns","typed errors","error boundaries","go error handling","custom error class","error codes","config validation"],"skill:evm-token-decimals":["token decimals","wei conversion","erc20 balance off","bridge token precision"],"skill:frontend-a11y":["aria attributes","screen reader support","focus management","semantic html","form labeling","keyboard navigation react","a11y lint errors"],"skill:git-workflow":["merge vs rebase","commit conventions","resolve merge conflict","branching strategy","clean up commits","pull request cleanup","git history tidy"],"skill:hexagonal-architecture":["ports and adapters","dependency injection boundaries","decouple domain from io"],"skill:kubernetes-patterns":["kubernetes manifests","kubectl debugging","pod probes","k8s rbac","autoscaling config","configmap secrets"],"skill:orch-fix-defect":["fix a bug","broken behavior","regression fix","reproduce bug","defect repair"],"skill:postgres-patterns":["slow postgres query","query optimization","index design","rls policies","supabase schema","postgres indexing","database performance","schema design postgres","postgres driver","node postgres","query planner"],"skill:python-patterns":["pythonic code","pep 8","type hints python","python code review","idiomatic python"],"skill:python-testing":["pytest fixtures","mocking python","parametrized tests","coverage python","tdd python"],"skill:redis-patterns":["cache aside pattern","distributed lock","redis rate limiting","cache invalidation"],"skill:regex-vs-llm-structured-text":["parse invoice","extract receipt data","text extraction pipeline","parse form fields","cheap document parser","extract table data","parse log lines","parse access logs","common log format","log line parsing"],"skill:rust-patterns":["rust ownership","borrow checker","rust error handling","traits rust","rust concurrency","idiomatic rust"],"skill:search-first":["find existing library","npm package research","before writing custom code","evaluate existing tools","add dependency research"],"skill:security-review":["security audit","authentication review","sanitize user input","secrets handling","payment security checklist","prevent injection attacks","secure api endpoints","authn authz review","vulnerability checklist","input validation security","parameterized queries","sql injection"],"skill:security-scan":["audit claude config","claudemd security","mcp server audit","agentshield scan","hook configuration audit","settings json security"],"skill:tdd-workflow":["write test first","failing test","red green refactor","test driven development","regression test first","write a regression test"],"skill:verification-loop":["pre pr checks","verification report","quality gates","build lint test coverage","before creating a pr"]},"triggersDigest":"25b97a9e06fc336c7cf95ab854ed1a41033a54bcd6e1fb1cf69dc906332462aa"}
diff --git a/manifests/context-profiles/full@1.json b/manifests/context-profiles/full@1.json
new file mode 100644
index 000000000..df8c92f60
--- /dev/null
+++ b/manifests/context-profiles/full@1.json
@@ -0,0 +1,12 @@
+{
+ "schemaVersion": 1,
+ "id": "full@1",
+ "description": "Proposed complete canonical skill discovery projection. Agents, commands, rules, hooks and tool schemas remain outside this projection; native activation is unobserved.",
+ "registryId": "skill-registry@1",
+ "selection": {
+ "eager": "all",
+ "required": ["skill:configure-ecc", "skill:context-budget", "skill:ecc-guide"],
+ "remainder": "routed"
+ },
+ "budget": { "tokens": 8000, "mode": "report-only" }
+}
diff --git a/manifests/context-profiles/lean@1.json b/manifests/context-profiles/lean@1.json
new file mode 100644
index 000000000..8127d6a21
--- /dev/null
+++ b/manifests/context-profiles/lean@1.json
@@ -0,0 +1,12 @@
+{
+ "schemaVersion": 1,
+ "id": "lean@1",
+ "description": "Proposed three-skill ECC discovery kernel. Remaining skills are routed; this profile does not activate or modify a harness.",
+ "registryId": "skill-registry@1",
+ "selection": {
+ "eager": ["skill:configure-ecc", "skill:context-budget", "skill:ecc-guide"],
+ "required": ["skill:configure-ecc", "skill:context-budget", "skill:ecc-guide"],
+ "remainder": "routed"
+ },
+ "budget": { "tokens": 8000, "mode": "blocking" }
+}
diff --git a/manifests/install-assets/claude-project-scripts-package.json b/manifests/install-assets/claude-project-scripts-package.json
new file mode 100644
index 000000000..5bbefffba
--- /dev/null
+++ b/manifests/install-assets/claude-project-scripts-package.json
@@ -0,0 +1,3 @@
+{
+ "type": "commonjs"
+}
diff --git a/package-lock.json b/package-lock.json
index d5b64895a..fff2ca0d0 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "ecc-universal",
- "version": "2.2.1",
+ "version": "2.2.2",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "ecc-universal",
- "version": "2.2.1",
+ "version": "2.2.2",
"license": "MIT",
"dependencies": {
"@iarna/toml": "2.2.5",
diff --git a/package.json b/package.json
index 839f94081..76a3f0290 100644
--- a/package.json
+++ b/package.json
@@ -1,7 +1,18 @@
{
"name": "ecc-universal",
- "version": "2.2.1",
+ "version": "2.2.2",
"description": "Harness-native agent operating system for Codex, OpenCode, Cursor, Gemini, Claude Code, and terminal workflows - skills, hooks, rules, MCP conventions, and operator control-plane patterns",
+ "main": ".opencode/dist/index.js",
+ "types": ".opencode/dist/index.d.ts",
+ "exports": {
+ ".": {
+ "types": "./.opencode/dist/index.d.ts",
+ "import": "./.opencode/dist/index.js",
+ "default": "./.opencode/dist/index.js"
+ },
+ "./package.json": "./package.json",
+ "./*": "./*"
+ },
"publishConfig": {
"access": "public"
},
@@ -51,6 +62,7 @@
".hermes/",
".kimi/",
".opencode/",
+ ".opencode/dist/",
".pi/",
".openclaw/",
".qwen/",
@@ -72,6 +84,9 @@
"docs/COMMAND-AGENT-MAP.md",
"docs/ROADMAP.md",
"docs/design/ecc-memory-vault.md",
+ "docs/design/context-profiles.md",
+ "docs/design/context-carriers.md",
+ "docs/design/context-profile-delivery.md",
"docs/ja-JP/",
"docs/ko-KR/",
"docs/pt-BR/",
@@ -94,6 +109,7 @@
"scripts/ci/scan-supply-chain-iocs.js",
"scripts/ci/supply-chain-advisory-sources.js",
"scripts/consult.js",
+ "scripts/profile.js",
"scripts/auto-update.js",
"scripts/claw.js",
"scripts/control-pane.js",
@@ -456,6 +472,7 @@
"scripts": {
"welcome": "echo '\\n ecc-universal installed!\\n Run: ecc typescript\\n Compat: ecc-install typescript\\n Docs: https://github.com/affaan-m/ECC\\n Run or self-host any open-source model.\\n Compute: Itô is the preferred compute sponsor — https://compute.itomarkets.com\\n Any GPU provider works. This sponsorship link is passive: it does not invoke an RFQ, reserve capacity, provision compute, or configure serving.\\n Separately, the opt-in ecc ito find bridge invokes the explicitly configured canonical Itô CLI and submits a live authenticated RFQ; it does not reserve capacity.\\n Managed inference through Itô is not live yet.\\n'",
"catalog:check": "node scripts/ci/catalog.js --text",
+ "context-profiles:check": "node scripts/ci/validate-context-profiles.js",
"catalog:sync": "node scripts/ci/catalog.js --write --text",
"command-registry:generate": "node scripts/ci/generate-command-registry.js",
"command-registry:write": "node scripts/ci/generate-command-registry.js --write",
@@ -479,7 +496,7 @@
"orchestrate:status": "node scripts/orchestration-status.js",
"orchestrate:worker": "bash scripts/orchestrate-codex-worker.sh",
"orchestrate:tmux": "node scripts/orchestrate-worktrees.js",
- "test": "node scripts/ci/check-unicode-safety.js && node scripts/ci/validate-agents.js && node scripts/ci/validate-commands.js && node scripts/ci/validate-rules.js && node scripts/ci/validate-skills.js && node scripts/ci/validate-hooks.js && node scripts/ci/check-hooks-schema-keys.js && node scripts/ci/validate-install-manifests.js && node scripts/ci/validate-no-personal-paths.js && npm run catalog:check && npm run command-registry:check && node tests/run-all.js",
+ "test": "node scripts/ci/check-unicode-safety.js && node scripts/ci/validate-agents.js && node scripts/ci/validate-commands.js && node scripts/ci/validate-rules.js && node scripts/ci/validate-skills.js && node scripts/ci/validate-hooks.js && node scripts/ci/check-hooks-schema-keys.js && node scripts/ci/validate-install-manifests.js && node scripts/ci/validate-context-profiles.js && node scripts/ci/validate-no-personal-paths.js && npm run catalog:check && npm run command-registry:check && node tests/run-all.js",
"coverage": "c8 --all --include=\"scripts/**/*.js\" --include=\"scripts/**/*.mjs\" --check-coverage --lines 80 --functions 80 --branches 79 --statements 80 --reporter=text --reporter=lcov node tests/run-all.js",
"build:opencode": "node scripts/build-opencode.js",
"prepack": "npm run build:opencode",
diff --git a/plugins/ecc/.codex-plugin/plugin.json b/plugins/ecc/.codex-plugin/plugin.json
index ff95de1b4..07f376cd6 100644
--- a/plugins/ecc/.codex-plugin/plugin.json
+++ b/plugins/ecc/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "ecc",
- "version": "2.2.1",
+ "version": "2.2.2",
"description": "Harness-native ECC workflows for Codex: shared skills, production-ready MCP configs, and selective-install-aligned conventions for TDD, security scanning, code review, and autonomous development.",
"author": {
"name": "Affaan Mustafa",
diff --git a/pyproject.toml b/pyproject.toml
index 2e924826f..5f979c2d2 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -20,7 +20,7 @@ classifiers = [
dependencies = [
"anthropic>=0.120.2",
- "openai>=1.30.0",
+ "openai>=2.34.0",
]
[project.optional-dependencies]
diff --git a/rules/common/agents.md b/rules/common/agents.md
index 4d1dfb4cb..14d9b9005 100644
--- a/rules/common/agents.md
+++ b/rules/common/agents.md
@@ -2,29 +2,36 @@
## Available Agents
-Located in `~/.claude/agents/`:
+ECC agents ship with the `ecc@ecc` plugin, not in `~/.claude/agents/`.
+They are invoked through the Agent tool with a plugin-scoped `subagent_type`:
+
+```text
+Agent(subagent_type: "ecc:planner", prompt: "...")
+```
| Agent | Purpose | When to Use |
|-------|---------|-------------|
-| planner | Implementation planning | Complex features, refactoring |
-| architect | System design | Architectural decisions |
-| tdd-guide | Test-driven development | New features, bug fixes |
-| code-reviewer | Code review | After writing code |
-| security-reviewer | Security analysis | Before commits |
-| build-error-resolver | Fix build errors | When build fails |
-| e2e-runner | E2E testing | Critical user flows |
-| refactor-cleaner | Dead code cleanup | Code maintenance |
-| doc-updater | Documentation | Updating docs |
-| rust-reviewer | Rust code review | Rust projects |
-| harmonyos-app-resolver | HarmonyOS app development | HarmonyOS/ArkTS projects |
+| ecc:planner | Implementation planning | Complex features, refactoring |
+| ecc:architect | System design | Architectural decisions |
+| ecc:tdd-guide | Test-driven development | New features, bug fixes |
+| ecc:code-reviewer | Code review | After writing code |
+| ecc:security-reviewer | Security analysis | Before commits |
+| ecc:build-error-resolver | Fix build errors | When build fails |
+| ecc:e2e-runner | E2E testing | Critical user flows |
+| ecc:refactor-cleaner | Dead code cleanup | Code maintenance |
+| ecc:doc-updater | Documentation | Updating docs |
+| ecc:rust-reviewer | Rust code review | Rust projects |
+| ecc:harmonyos-app-resolver | HarmonyOS app development | HarmonyOS/ArkTS projects |
+
+For the full roster of 68 agents, see `/ecc:ecc-guide`.
## Immediate Agent Usage
No user prompt needed:
-1. Complex feature requests - Use **planner** agent
-2. Code just written/modified - Use **code-reviewer** agent
-3. Bug fix or new feature - Use **tdd-guide** agent
-4. Architectural decision - Use **architect** agent
+1. Complex feature requests - Use **ecc:planner** agent
+2. Code just written/modified - Use **ecc:code-reviewer** agent
+3. Bug fix or new feature - Use **ecc:tdd-guide** agent
+4. Architectural decision - Use **ecc:architect** agent
## Parallel Task Execution
diff --git a/schemas/context-carrier.schema.json b/schemas/context-carrier.schema.json
new file mode 100644
index 000000000..228aadaef
--- /dev/null
+++ b/schemas/context-carrier.schema.json
@@ -0,0 +1,106 @@
+{
+ "$schema": "http://json-schema.org/draft-07/schema#",
+ "title": "ECC read-only skill carrier proposal",
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["schemaVersion", "status", "active", "disposition", "nativeSupport", "target", "profileId", "selectionMode", "registryDigest", "profileDigest", "compilerDigest", "planDigest", "adapterDigest", "carrierDigest", "layout", "selectedIds", "routedIds", "excludedIds", "entries", "files", "limitations"],
+ "properties": {
+ "schemaVersion": { "const": "ecc.context-carrier.v1" },
+ "status": { "enum": ["planned", "unsupported"] },
+ "active": { "const": false },
+ "disposition": { "const": "proposed" },
+ "nativeSupport": { "const": "unobserved" },
+ "target": { "enum": ["adal", "antigravity", "claude", "claude-project", "codebuddy", "codex", "cursor", "gemini", "hermes", "joycode", "kimi", "openclaw", "opencode", "pi", "qwen", "zed"] },
+ "profileId": { "enum": ["lean@1", "full@1"] },
+ "selectionMode": { "enum": ["manual", "suggest", "auto"] },
+ "registryDigest": { "$ref": "#/definitions/digest" },
+ "profileDigest": { "$ref": "#/definitions/digest" },
+ "compilerDigest": { "$ref": "#/definitions/digest" },
+ "planDigest": { "$ref": "#/definitions/digest" },
+ "adapterDigest": { "$ref": "#/definitions/digest" },
+ "carrierDigest": { "$ref": "#/definitions/digest" },
+ "layout": {
+ "oneOf": [
+ { "type": "null" },
+ {
+ "type": "object", "additionalProperties": false,
+ "required": ["id", "skillRoot", "manifestPath"],
+ "properties": {
+ "id": { "enum": ["claude-plugin@1", "codex-plugin@1", "pi-package@1", "opencode-project@1", "cursor-project@1"] },
+ "skillRoot": { "enum": ["skills", ".opencode/skills", ".cursor/skills"] },
+ "manifestPath": { "enum": [null, ".claude-plugin/plugin.json", ".codex-plugin/plugin.json", "package.json"] }
+ }
+ }
+ ]
+ },
+ "selectedIds": { "$ref": "#/definitions/skillIds" },
+ "routedIds": { "$ref": "#/definitions/skillIds" },
+ "excludedIds": { "$ref": "#/definitions/skillIds" },
+ "entries": {
+ "type": "array",
+ "items": {
+ "type": "object", "additionalProperties": false,
+ "required": ["id", "name", "sourcePath", "contentDigest", "requiredResources", "installSupport"],
+ "properties": {
+ "id": { "$ref": "#/definitions/skillId" },
+ "name": { "type": "string", "minLength": 1, "maxLength": 64, "pattern": "^[a-z0-9]+(?:-[a-z0-9]+)*$" },
+ "sourcePath": { "$ref": "#/definitions/path" },
+ "contentDigest": { "$ref": "#/definitions/digest" },
+ "requiredResources": { "type": "array", "uniqueItems": true, "items": { "$ref": "#/definitions/path" } },
+ "installSupport": { "enum": ["declared", "not-declared"] }
+ }
+ }
+ },
+ "files": {
+ "type": "array",
+ "items": {
+ "oneOf": [
+ {
+ "type": "object", "additionalProperties": false,
+ "required": ["kind", "skillId", "sourcePath", "destinationPath", "digest", "bytes"],
+ "properties": {
+ "kind": { "const": "copy" },
+ "skillId": { "$ref": "#/definitions/skillId" },
+ "sourcePath": { "$ref": "#/definitions/path" },
+ "destinationPath": { "$ref": "#/definitions/path" },
+ "digest": { "$ref": "#/definitions/digest" },
+ "bytes": { "$ref": "#/definitions/bytes" }
+ }
+ },
+ {
+ "type": "object", "additionalProperties": false,
+ "required": ["kind", "destinationPath", "content", "encoding", "digest", "bytes"],
+ "properties": {
+ "kind": { "const": "generated" },
+ "destinationPath": { "enum": [".claude-plugin/plugin.json", ".codex-plugin/plugin.json", "package.json"] },
+ "content": { "type": "string", "minLength": 1, "maxLength": 4096 },
+ "encoding": { "const": "utf8" },
+ "digest": { "$ref": "#/definitions/digest" },
+ "bytes": { "$ref": "#/definitions/bytes" }
+ }
+ }
+ ]
+ }
+ },
+ "limitations": { "type": "array", "minItems": 1, "items": { "type": "string", "minLength": 1 } }
+ },
+ "allOf": [
+ {
+ "if": { "properties": { "status": { "const": "unsupported" } } },
+ "then": { "properties": { "layout": { "type": "null" }, "files": { "type": "array", "maxItems": 0 } } },
+ "else": { "properties": { "layout": { "type": "object" } } }
+ },
+ {
+ "if": { "properties": { "target": { "enum": ["claude", "codex", "pi", "opencode", "cursor"] } } },
+ "then": { "properties": { "status": { "const": "planned" } } },
+ "else": { "properties": { "status": { "const": "unsupported" } } }
+ }
+ ],
+ "definitions": {
+ "digest": { "type": "string", "pattern": "^[a-f0-9]{64}$" },
+ "bytes": { "type": "integer", "minimum": 0, "maximum": 4194304 },
+ "skillId": { "type": "string", "pattern": "^skill:[a-z0-9]+(?:-[a-z0-9]+)*$" },
+ "skillIds": { "type": "array", "uniqueItems": true, "items": { "$ref": "#/definitions/skillId" } },
+ "path": { "type": "string", "minLength": 1, "maxLength": 4096, "pattern": "^(?!/)(?!.*(?:^|/)\\.\\.?(?:/|$))(?!.*[\\\\<>:\"|?*\\u0000-\\u001f\\u007f-\\u009f])[^/]+(?:/[^/]+)*$" }
+ }
+}
diff --git a/schemas/context-pack-registry.schema.json b/schemas/context-pack-registry.schema.json
new file mode 100644
index 000000000..df5153e79
--- /dev/null
+++ b/schemas/context-pack-registry.schema.json
@@ -0,0 +1,42 @@
+{
+ "$schema": "http://json-schema.org/draft-07/schema#",
+ "title": "ECC context registry declaration",
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["schemaVersion", "id", "inventory", "overrides"],
+ "properties": {
+ "schemaVersion": { "const": 1 },
+ "id": { "const": "skill-registry@1" },
+ "inventory": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["source", "skillsRoot"],
+ "properties": {
+ "source": { "const": "manifests/install-modules.json" },
+ "skillsRoot": { "const": "skills" }
+ }
+ },
+ "overrides": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["id"],
+ "properties": {
+ "id": { "$ref": "#/definitions/skillId" },
+ "dependencies": {
+ "type": "array", "uniqueItems": true,
+ "items": { "$ref": "#/definitions/skillId" }
+ },
+ "requiredResources": {
+ "type": "array", "uniqueItems": true,
+ "items": { "type": "string", "minLength": 1, "maxLength": 4096 }
+ }
+ }
+ }
+ }
+ },
+ "definitions": {
+ "skillId": { "type": "string", "pattern": "^skill:[a-z0-9]+(?:-[a-z0-9]+)*$" }
+ }
+}
diff --git a/schemas/context-profile.schema.json b/schemas/context-profile.schema.json
new file mode 100644
index 000000000..0760fba11
--- /dev/null
+++ b/schemas/context-profile.schema.json
@@ -0,0 +1,36 @@
+{
+ "$schema": "http://json-schema.org/draft-07/schema#",
+ "title": "ECC read-only context profile",
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["schemaVersion", "id", "description", "registryId", "selection", "budget"],
+ "properties": {
+ "schemaVersion": { "const": 1 },
+ "id": { "enum": ["lean@1", "full@1"] },
+ "description": { "type": "string", "minLength": 1, "maxLength": 2000 },
+ "registryId": { "const": "skill-registry@1" },
+ "selection": {
+ "type": "object", "additionalProperties": false,
+ "required": ["eager", "required", "remainder"],
+ "properties": {
+ "eager": { "oneOf": [{ "const": "all" }, { "$ref": "#/definitions/skillIds" }] },
+ "required": { "$ref": "#/definitions/skillIds" },
+ "remainder": { "const": "routed" }
+ }
+ },
+ "budget": {
+ "type": "object", "additionalProperties": false,
+ "required": ["tokens", "mode"],
+ "properties": {
+ "tokens": { "const": 8000 },
+ "mode": { "enum": ["blocking", "report-only"] }
+ }
+ }
+ },
+ "definitions": {
+ "skillIds": {
+ "type": "array", "uniqueItems": true,
+ "items": { "type": "string", "pattern": "^skill:[a-z0-9]+(?:-[a-z0-9]+)*$" }
+ }
+ }
+}
diff --git a/scripts/ci/validate-context-profiles.js b/scripts/ci/validate-context-profiles.js
new file mode 100644
index 000000000..362d29c6c
--- /dev/null
+++ b/scripts/ci/validate-context-profiles.js
@@ -0,0 +1,56 @@
+#!/usr/bin/env node
+'use strict';
+
+const { loadContextRegistry, loadSkillTriggers } = require('../lib/context-pack-registry');
+const { compileContextProfile } = require('../lib/context-profiles');
+const { digestObject } = require('../lib/context-profile-support');
+
+function validate(repoRoot) {
+ const registry = loadContextRegistry({ repoRoot });
+ const { triggers, manifest } = loadSkillTriggers({ repoRoot });
+ const known = new Set(registry.entries.map(entry => entry.id));
+ const unknown = Object.keys(triggers).filter(id => !known.has(id));
+ if (unknown.length) throw new Error(`Skill triggers reference unknown skills: ${unknown.slice(0, 3).join(', ')}`);
+ if (manifest && manifest.registryDigest && manifest.registryDigest !== registry.registryDigest) {
+ throw new Error('Skill triggers manifest is stale: regenerate with scripts/dev/generate-skill-triggers.js');
+ }
+ if (manifest && manifest.triggersDigest && digestObject(triggers) !== manifest.triggersDigest) {
+ throw new Error('Skill triggers digest mismatch: manifest was edited without updating triggersDigest');
+ }
+ for (const list of Object.values(triggers)) {
+ for (const phrase of list) {
+ if (phrase.length > 80) throw new Error(`Skill trigger exceeds 80 characters: ${phrase.slice(0, 40)}`);
+ }
+ }
+ const profiles = ['lean@1', 'full@1'];
+ for (const profileId of profiles) {
+ for (const target of registry.targets) {
+ compileContextProfile({ repoRoot, profileId, target });
+ }
+ }
+ return {
+ status: 'success', skillCount: registry.entries.length,
+ profileCount: profiles.length, targetCount: registry.targets.length,
+ projectionCount: profiles.length * registry.targets.length,
+ registryDigest: registry.registryDigest, nativeCertification: 'unobserved',
+ triggerCoverage: { skills: manifest ? manifest.coverage.skills : 0, withTriggers: Object.keys(triggers).length },
+ };
+}
+
+function main(args = process.argv.slice(2)) {
+ try {
+ for (const arg of args) {
+ if (arg !== '--json') throw new Error(`Unknown argument: ${arg}`);
+ }
+ const result = validate();
+ console.log(args.includes('--json') ? JSON.stringify(result, null, 2)
+ : `Context profiles valid: ${result.skillCount} skills, ${result.projectionCount} profile/target projections, triggers ${result.triggerCoverage.withTriggers}/${result.triggerCoverage.skills || result.skillCount}. Native certification: unobserved.`);
+ return 0;
+ } catch (error) {
+ console.error(`Context profile validation failed: ${error.message}`);
+ return 1;
+ }
+}
+
+if (require.main === module) process.exitCode = main();
+module.exports = { main, validate };
diff --git a/scripts/claw.js b/scripts/claw.js
index 982ce5c22..74dea0f81 100644
--- a/scripts/claw.js
+++ b/scripts/claw.js
@@ -95,21 +95,54 @@ function askClaude(systemPrompt, history, userMessage, model) {
}
args.push('-p');
- // On Windows the `claude` binary installed via npm is `claude.cmd`/`claude.ps1`,
- // and Node's spawn() cannot resolve those wrappers via PATH without shell: true.
- // But shell mode concatenates args *unescaped*, so a multi-line prompt passed as
- // an arg gets mangled (newlines and the `===` section markers truncate it, and
- // claude receives an empty prompt). Fix: send the prompt over stdin via `input`
- // and keep only the short, safe flags (`--model`, `-p`) as args.
- // 'claude' is a hardcoded literal here (not user input), so shell mode is safe.
- const result = spawnSync('claude', args, {
+ // SECURITY: a model value like `x & calc &` breaks out when Node
+ // concatenates command+args unquoted under cmd.exe (DEP0190), so the model
+ // token is validated and only fixed flags reach the command line.
+ if (model && !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/.test(model)) {
+ return `[Error: invalid model name]`;
+ }
+ // On Windows the `claude` binary is usually a .cmd shim, which Node
+ // >=18.20/20.12 refuses to spawn directly (CVE-2024-27980 mitigation), and
+ // .ps1 shims are not directly executable at all. Resolve a natively
+ // executable target first; only .cmd/.bat go through cmd.exe, using the
+ // same quoted-command-line pattern as scripts/hooks/mcp-health-check.js so
+ // space-containing paths survive as single tokens. .ps1 is never executed
+ // directly — fall through to bare `claude` (pre-change behavior) instead.
+ // cmd.exe expands %NAME% even inside double-quoted strings, so reject
+ // percent-delimited executable paths rather than route them through the shell.
+ function quoteWinToken(token) {
+ if (/%/.test(token)) return null;
+ return /[\s"&|<>^();]/.test(token) ? '"' + token.replace(/"/g, '""') + '"' : token;
+ }
+ let bin = 'claude';
+ let useShell = false;
+ if (process.platform === 'win32') {
+ const { spawnSync: spawnWhere } = require('child_process');
+ for (const ext of ['.exe', '.cmd', '.bat']) {
+ let found = null;
+ try {
+ found = spawnWhere('where', [`claude${ext}`], { encoding: 'utf8' });
+ } catch { /* ignore */ }
+ if (found && found.status === 0 && found.stdout && found.stdout.trim()) {
+ bin = found.stdout.trim().split(/\r?\n/)[0];
+ useShell = /\.(cmd|bat)$/i.test(bin);
+ break;
+ }
+ }
+ if (useShell && quoteWinToken(bin) === null) {
+ useShell = false;
+ }
+ }
+ const spawnOpts = {
input: fullPrompt,
encoding: 'utf8',
stdio: ['pipe', 'pipe', 'pipe'],
env: { ...process.env, CLAUDECODE: '' },
timeout: 300000,
- shell: process.platform === 'win32'
- });
+ };
+ const result = useShell
+ ? spawnSync([bin, ...args].map(quoteWinToken).join(' '), { ...spawnOpts, shell: true })
+ : spawnSync(bin, args, { ...spawnOpts, shell: false });
if (result.error) {
return `[Error: ${result.error.message}]`;
diff --git a/scripts/codex-git-hooks/pre-commit b/scripts/codex-git-hooks/pre-commit
index 98c495fef..b4c608c76 100644
--- a/scripts/codex-git-hooks/pre-commit
+++ b/scripts/codex-git-hooks/pre-commit
@@ -5,12 +5,13 @@ set -euo pipefail
# Blocks commits that add high-signal secrets.
if [[ "${ECC_SKIP_GIT_HOOKS:-0}" == "1" || "${ECC_SKIP_PRECOMMIT:-0}" == "1" ]]; then
+ printf '[ECC pre-commit] WARNING: hook bypassed via env (ECC_SKIP_*=1)\n' >&2
exit 0
fi
-if [[ -f ".ecc-hooks-disable" || -f ".git/ecc-hooks-disable" ]]; then
- exit 0
-fi
+# NOTE: file-based disables (.ecc-hooks-disable) were removed — a malicious
+# repo could ship that file and silently turn off secret scanning exactly
+# where it is most needed. Use the env bypass above (audible warning) instead.
if ! git rev-parse --is-inside-work-tree >/dev/null 2>&1; then
exit 0
diff --git a/scripts/codex-git-hooks/pre-push b/scripts/codex-git-hooks/pre-push
index 2ee23c7f4..10fdd4f4d 100755
--- a/scripts/codex-git-hooks/pre-push
+++ b/scripts/codex-git-hooks/pre-push
@@ -5,12 +5,12 @@ set -euo pipefail
# Runs a lightweight verification flow before pushes.
if [[ "${ECC_SKIP_GIT_HOOKS:-0}" == "1" || "${ECC_SKIP_PREPUSH:-0}" == "1" ]]; then
+ printf '[ECC pre-push] WARNING: hook bypassed via env (ECC_SKIP_*=1)\n' >&2
exit 0
fi
-if [[ -f ".ecc-hooks-disable" || -f ".git/ecc-hooks-disable" ]]; then
- exit 0
-fi
+# NOTE: file-based disables (.ecc-hooks-disable) were removed — a malicious
+# repo could ship that file and silently disable verification.
if ! git rev-parse --is-inside-work-tree >/dev/null 2>&1; then
exit 0
@@ -85,8 +85,14 @@ run_node_script() {
}
if [[ -f "package.json" ]]; then
- pm="$(detect_pm)"
- log "Node project detected (package manager: $pm)"
+ # SECURITY: executing a cloned repo's lint/test/build scripts on push is
+ # arbitrary code execution (package.json scripts run as you). Opt-in only:
+ # set ECC_PREPUSH_RUN_CHECKS=1 for repos you trust.
+ if [[ "${ECC_PREPUSH_RUN_CHECKS:-0}" != "1" ]]; then
+ printf '[ECC pre-push] Node project detected but ECC_PREPUSH_RUN_CHECKS!=1; skipping repo script execution (set =1 to opt in).\n' >&2
+ else
+ pm="$(detect_pm)"
+ log "Node project detected (package manager: $pm)"
for script_name in lint typecheck test build; do
if has_node_script "$script_name"; then
@@ -98,7 +104,9 @@ if [[ -f "package.json" ]]; then
fi
done
+ fi
if [[ "${ECC_PREPUSH_AUDIT:-0}" == "1" ]]; then
+ pm="${pm:-$(detect_pm)}"
ran_any_check=1
log "Running dependency audit (ECC_PREPUSH_AUDIT=1)"
case "$pm" in
@@ -111,21 +119,185 @@ if [[ -f "package.json" ]]; then
fi
fi
+# SECURITY: go test / pytest execute repo-controlled code (TestMain,
+# conftest.py). Same opt-in gate as Node scripts above.
+if [[ "${ECC_PREPUSH_RUN_CHECKS:-0}" == "1" ]]; then
if [[ -f "go.mod" ]] && command -v go >/dev/null 2>&1; then
ran_any_check=1
log "Go project detected. Running: go test ./..."
go test ./... || fail "go test failed"
fi
+# Resolve how this project runs pytest, into PYTEST_CMD as an argv array.
+#
+# Looking only for `pytest` on PATH meant the hook skipped every project that keeps
+# its tools in a virtualenv -- which is most of them -- and reported "pytest is not
+# installed" while sitting next to a .venv with pytest in it. A gate that silently
+# declines to gate is worse than no gate, because the skip line reads like a pass.
+#
+# An array rather than one string, because a virtualenv path may contain spaces:
+# a scalar command splits `/home/me/my env/bin/python` into two paths that do not
+# exist, and the hook then rejects the push for a reason that has nothing to do
+# with the code being pushed.
+#
+# Echoes the command it will run, so the reason for a skip is always visible.
+PYTEST_CMD=()
+
+# Does this command actually run pytest? Accepting `--version` is not evidence --
+# plenty of programs take it and exit 0 -- so the output has to name pytest. The
+# version is captured rather than piped: under `set -o pipefail` a `| grep -q` can
+# report the SIGPIPE of the program it just matched.
+#
+# Only ever called on a command this script composed itself. Probing an arbitrary
+# operator-supplied command is not safe: a wrapper that ignores `--version` and
+# execs pytest runs the entire suite during the probe, and is then rejected for
+# not having printed a version.
+is_pytest() {
+ local version
+ version="$("$@" --version 2>&1)" || return 1
+ grep -qiE 'pytest[[:space:]]+(version[[:space:]]+)?[0-9]' <<<"$version"
+}
+
+# Does the repository itself ship this interpreter?
+#
+# A virtualenv is never committed -- it is platform-specific binaries, and every
+# Python project gitignores it. One that IS tracked is the repository handing this
+# hook an executable and asking it to run. The hook is installed globally, so
+# cloning a hostile repository and pushing it to your own fork would be enough,
+# and on a machine with no pytest on PATH this arm is the only thing that would
+# run at all. A developer's own venv is untracked, so nothing legitimate is lost.
+#
+# The path is resolved through symlinks before git is asked, because `git ls-files`
+# reports paths as indexed and does not follow links. A repository that commits
+# `.venv` as a symlink to `.` next to a tracked `bin/python` would otherwise be
+# queried for `.venv/bin/python`, a path git has never heard of, and the answer
+# would be "untracked". Measured: that shape ran the planted binary twice.
+repo_ships_interpreter() {
+ local bindir real top
+ bindir="$(cd -P -- "$1" 2>/dev/null && pwd -P)" || return 1
+ [[ -n "$bindir" ]] || return 1
+ real="$bindir/python"
+ top="$(git rev-parse --show-toplevel 2>/dev/null)" || return 1
+ top="$(cd -P -- "$top" 2>/dev/null && pwd -P)" || return 1
+ [[ -n "$top" && "$real" == "$top/"* ]] || return 1
+ # `:(icase)` because git matches index pathspecs case-sensitively even where
+ # core.ignorecase is set, while the filesystem underneath does not. On macOS's
+ # APFS -- the platform this hook most often runs on -- a committed
+ # `.venv/bin/Python` is what `$venv/bin/python` opens and executes, but a
+ # case-sensitive query for the lowercase name finds nothing in the index and the
+ # guard waves it through. Measured: that spelling ran the planted binary twice.
+ git ls-files --error-unmatch -- ":(icase)${real#"$top"/}" >/dev/null 2>&1
+}
+
+# `-I` isolates the probe: without it Python puts the working directory first on
+# sys.path, so a repository that commits a `pytest.py` in its root gets that file
+# imported -- and executed -- by a check whose only job is to answer whether pytest
+# exists. Measured: a committed pytest.py ran during the probe. Isolation does not
+# hide a real pytest, which lives in the interpreter's own site-packages.
+resolve_pytest() {
+ # `${VAR+set}` rather than `-n "${VAR:-}"`, so that a variable set to nothing is
+ # still an override: `ECC_PYTEST_CMD=` and `ECC_PYTEST_CMD=" "` now behave
+ # alike, where the first used to fall through to discovery and the second failed
+ # the push. Falling through is the wrong half of that pair -- an override that
+ # evaluated empty (a command substitution that found nothing, say) would silently
+ # run a different runner than the operator asked for, which is the substitution
+ # this resolver refuses to make anywhere else.
+ #
+ # Not `[[ -v ECC_PYTEST_CMD ]]`: that is bash 4.2, and a stock macOS `/bin/bash`
+ # is 3.2, where it is a syntax error rather than a false. This hook ships to
+ # whatever `env bash` finds.
+ if [[ -n "${ECC_PYTEST_CMD+set}" ]]; then
+ # Taken as given. This is a deliberate override, and the hook cannot inspect it
+ # without running it -- a wrapper script may ignore `--version` and run the
+ # suite, so probing costs a duplicate test run and then blocks the push anyway.
+ # Pointing this at something that is not pytest turns the gate off, and that is
+ # the operator's call to make, not a misconfiguration for the hook to second
+ # guess. Word-split, so the command names something on PATH or an interpreter
+ # whose path has no spaces; a venv with spaces is found by the loop below.
+ read -r -a PYTEST_CMD <<<"$ECC_PYTEST_CMD" || true
+ [[ ${#PYTEST_CMD[@]} -gt 0 ]] || fail "ECC_PYTEST_CMD is set but names no command.\
+ Point it at your test runner, or unset it to fall back to discovery."
+ return 0
+ fi
+ local venv
+ for venv in "${VIRTUAL_ENV:-}" .venv venv env; do
+ if [[ -n "$venv" && -x "$venv/bin/python" ]]; then
+ if repo_ships_interpreter "$venv/bin"; then
+ log "Ignoring $venv/bin/python: the repository ships it."
+ log " A committed virtualenv is an executable the repository controls, and"
+ log " this hook runs on every push in every repository."
+ continue
+ fi
+ if "$venv/bin/python" -I -c "import pytest" >/dev/null 2>&1; then
+ PYTEST_CMD=("$venv/bin/python" -m pytest)
+ return 0
+ fi
+ fi
+ done
+ if [[ -f "uv.lock" ]] && command -v uv >/dev/null 2>&1; then
+ if uv run --no-sync python -I -c "import pytest" >/dev/null 2>&1; then
+ PYTEST_CMD=(uv run --no-sync pytest)
+ return 0
+ fi
+ fi
+ if [[ -f "poetry.lock" ]] && command -v poetry >/dev/null 2>&1; then
+ if poetry run python -I -c "import pytest" >/dev/null 2>&1; then
+ PYTEST_CMD=(poetry run pytest)
+ return 0
+ fi
+ fi
+ # `command -v` proves only that a file of that name exists on PATH. This one the
+ # script composed itself, so confirming it costs a harmless `pytest --version`.
+ if command -v pytest >/dev/null 2>&1 && is_pytest pytest; then
+ PYTEST_CMD=(pytest)
+ return 0
+ fi
+ PYTEST_CMD=()
+ return 1
+}
+
if [[ -f "pyproject.toml" || -f "requirements.txt" ]]; then
- if command -v pytest >/dev/null 2>&1; then
+ if resolve_pytest; then
ran_any_check=1
- log "Python project detected. Running: pytest -q"
- pytest -q || fail "pytest failed"
+ log "Python project detected. Running: ${PYTEST_CMD[*]} -q"
+ if [[ -n "${ECC_PYTEST_CMD+set}" ]]; then
+ # resolve_pytest deliberately does not verify the override is pytest, because
+ # probing it can run the operator's suite. What this gate can honestly do
+ # about a stale override is refuse to be quiet about it: a bypass announced
+ # on every push is not the silent gate this resolver exists to prevent.
+ log " via ECC_PYTEST_CMD -- the hook runs what you pointed it at, and does"
+ log " not check that it is pytest. Unset it to gate on the real suite."
+ fi
+ pytest_status=0
+ "${PYTEST_CMD[@]}" -q || pytest_status=$?
+ case "$pytest_status" in
+ 0) ;;
+ # pytest reserves 5 for NO_TESTS_COLLECTED, which is not a red suite. A
+ # pyproject.toml that only configures ruff or black is still a Python project
+ # by this hook's test, and blocking those pushes would make the gate something
+ # people switch off. Never silent, though: a bad rootdir, testpaths or a
+ # conftest that fails to import also collects nothing, and swallowing that is
+ # the same skip-reads-like-a-pass hole this resolver exists to close.
+ 5)
+ log "pytest collected no tests (exit 5). Not gating this push."
+ log " If this repository is supposed to have tests, that is the bug:"
+ log " check rootdir, testpaths, and conftest.py import errors."
+ ;;
+ # The code is in the message because 1 (tests failed) and 4 (usage error)
+ # need different responses, and "pytest failed" alone cannot tell them apart.
+ *) fail "pytest failed (exit $pytest_status)" ;;
+ esac
else
- log "Python project detected but pytest is not installed. Skipping."
+ log "Python project detected but no pytest found (checked \$VIRTUAL_ENV, .venv,"
+ log " venv, env, uv, poetry, PATH). Set ECC_PYTEST_CMD to point at it."
fi
fi
+else
+ if [[ -f "go.mod" || -f "pyproject.toml" || -f "requirements.txt" ]]; then
+ log "Go/Python project detected but ECC_PREPUSH_RUN_CHECKS!=1; skipping test execution."
+ fi
+fi
+
if [[ "$ran_any_check" -eq 0 ]]; then
log "No supported checks found in this repository. Skipping."
diff --git a/scripts/codex/install-global-git-hooks.sh b/scripts/codex/install-global-git-hooks.sh
index ea11d8524..22702a5f5 100755
--- a/scripts/codex/install-global-git-hooks.sh
+++ b/scripts/codex/install-global-git-hooks.sh
@@ -41,6 +41,23 @@ log "Mode: $MODE"
log "Source hooks: $SOURCE_DIR"
log "Global hooks destination: $DEST_DIR"
+prev_hooks_path="$(git config --global core.hooksPath || true)"
+if [[ -n "$prev_hooks_path" && "$prev_hooks_path" != "$DEST_DIR" ]]; then
+ # SECURITY: never silently displace another tool's global hooks — that
+ # turns every commit/push in every repo into ECC code execution and breaks
+ # the user's existing security controls. Require explicit opt-in to replace.
+ if [[ "${ECC_FORCE_GLOBAL_HOOKS:-0}" != "1" ]]; then
+ log "ERROR: global core.hooksPath already set to: $prev_hooks_path"
+ log "Refusing to overwrite. Options:"
+ log " 1) Per-repo install (recommended): git config core.hooksPath \"$DEST_DIR\""
+ log " 2) Force replace: ECC_FORCE_GLOBAL_HOOKS=1 $0"
+ log " 3) Restore afterwards: git config --global core.hooksPath \"$prev_hooks_path\""
+ exit 1
+ fi
+ log "WARNING: replacing previous global hooksPath: $prev_hooks_path (ECC_FORCE_GLOBAL_HOOKS=1)"
+ log "Restore with: git config --global core.hooksPath \"$prev_hooks_path\""
+fi
+
if [[ -d "$DEST_DIR" ]]; then
log "Backing up existing hooks directory to $BACKUP_DIR"
run_or_echo mkdir -p "$BACKUP_DIR"
@@ -51,15 +68,8 @@ run_or_echo mkdir -p "$DEST_DIR"
run_or_echo cp "$SOURCE_DIR/pre-commit" "$DEST_DIR/pre-commit"
run_or_echo cp "$SOURCE_DIR/pre-push" "$DEST_DIR/pre-push"
run_or_echo chmod +x "$DEST_DIR/pre-commit" "$DEST_DIR/pre-push"
-
-if [[ "$MODE" == "apply" ]]; then
- prev_hooks_path="$(git config --global core.hooksPath || true)"
- if [[ -n "$prev_hooks_path" ]]; then
- log "Previous global hooksPath: $prev_hooks_path"
- fi
-fi
run_or_echo git config --global core.hooksPath "$DEST_DIR"
log "Installed ECC global git hooks."
-log "Disable per repo by creating .ecc-hooks-disable in project root."
-log "Temporary bypass: ECC_SKIP_PRECOMMIT=1 or ECC_SKIP_PREPUSH=1"
+log "Per-repo alternative (recommended): git config core.hooksPath \"$DEST_DIR\""
+log "Temporary bypass (audible): ECC_SKIP_GIT_HOOKS=1 (logs a warning to stderr)"
diff --git a/scripts/control-pane.js b/scripts/control-pane.js
index c5b7215f4..dceed7539 100755
--- a/scripts/control-pane.js
+++ b/scripts/control-pane.js
@@ -1,8 +1,6 @@
#!/usr/bin/env node
'use strict';
-const { spawn } = require('child_process');
-
const {
createControlPaneServer,
parseArgs,
@@ -10,16 +8,14 @@ const {
} = require('./lib/control-pane/server');
const { describeMissingDependencyError } = require('./lib/missing-dependency');
+// openBrowser is now in scripts/lib/platform-launch.js — keep a thin wrapper
+// for backwards compatibility, but surface the structured result.
+const { openBrowser: launchOpenBrowser } = require('./lib/platform-launch');
function openBrowser(url) {
- if (process.platform !== 'darwin') return;
- const child = spawn('open', [url], {
- stdio: 'ignore',
- detached: true,
- });
- child.on('error', error => {
- console.error(`[control-pane] failed to open browser: ${error.message}`);
- });
- child.unref();
+ const result = launchOpenBrowser(url);
+ if (!result.opened) {
+ console.error(`[control-pane] failed to open browser: ${result.reason}`);
+ }
}
async function main(argv = process.argv) {
diff --git a/scripts/dev/generate-skill-triggers.js b/scripts/dev/generate-skill-triggers.js
new file mode 100644
index 000000000..44ed6116c
--- /dev/null
+++ b/scripts/dev/generate-skill-triggers.js
@@ -0,0 +1,156 @@
+#!/usr/bin/env node
+'use strict';
+
+// Dev-time generator for manifests/context-packs/skill-triggers@1.json.
+//
+// For every canonical skill, asks the pinned provider for short trigger
+// phrasings a user would type when that skill applies (synonyms, task
+// wordings, related technology names), grounded STRICTLY in the skill's own
+// description. The manifest is checked in, digest-stable, and read by the
+// retrieval index at runtime, so runtime behavior stays deterministic and
+// offline. Rerun this script after adding or re-describing skills.
+//
+// Usage:
+// node scripts/dev/generate-skill-triggers.js --auth-home ~/.ecc-eval/auth \
+// [--model gpt-5.6-sol] [--executable /path/to/codex] [--batch 25] [--dry-run]
+// node scripts/dev/generate-skill-triggers.js --provider claude \
+// [--model claude-sonnet-5] [--executable /path/to/claude] [--batch 40] [--dry-run]
+//
+// Codex requires an isolated executable and a dedicated subscription login
+// home (the same lease rules as the outcome evaluator: never the user's own
+// Codex home). Claude authenticates through CLAUDE_CODE_OAUTH_TOKEN,
+// ANTHROPIC_API_KEY, or the macOS Keychain login, with an isolated
+// CLAUDE_CONFIG_DIR per call. Provider calls: ceil(skills / batch).
+
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const { loadContextRegistry } = require('../lib/context-pack-registry');
+const { createAuthLease, parseCodexJsonl, parseClaudeJson, providerFamily, readClaudeKeychainToken } = require('../../docker/context-profiles/ai-eval-lib');
+const { digestObject, stableStringify } = require('../lib/context-profile-support');
+
+const MANIFEST_PATH = 'manifests/context-packs/skill-triggers@1.json';
+const MAX_TRIGGERS_PER_SKILL = 12;
+const MAX_TRIGGER_CHARS = 80;
+const DEFAULT_MODEL = { codex: 'gpt-5.6-sol', claude: 'claude-sonnet-5' };
+
+function parseFlags(argv) {
+ const flags = { batch: 25 };
+ for (let index = 2; index < argv.length; index += 1) {
+ const arg = argv[index];
+ if (arg === '--dry-run') flags.dryRun = true;
+ else if (['--auth-home', '--model', '--executable', '--batch', '--provider'].includes(arg)) {
+ flags[arg.slice(2).replace(/-([a-z])/g, (_, c) => c.toUpperCase())] = argv[index += 1];
+ } else throw new Error(`Unknown flag: ${arg}`);
+ }
+ if (!/^[1-9][0-9]*$/.test(String(flags.batch)) || !Number.isSafeInteger(Number(flags.batch))) {
+ throw new Error('--batch must be a positive integer');
+ }
+ flags.batch = Number(flags.batch);
+ return flags;
+}
+
+function promptFor(batch) {
+ const lines = batch.map(entry => ({ id: entry.id, name: entry.name, description: entry.description }));
+ return `You generate retrieval triggers for a skills library. For EACH skill below, output a JSON object mapping its id to an array of ${MAX_TRIGGERS_PER_SKILL} short trigger phrases (each under ${MAX_TRIGGER_CHARS} characters): realistic task wordings, synonyms, and related technology names a developer would type when this skill applies. Ground every trigger ONLY in the skill description; never invent capabilities the description does not claim. Prefer concrete task phrasings over category words. Output ONE JSON object and nothing else.\n\n${JSON.stringify(lines, null, 1)}`;
+}
+
+function extractJson(text) {
+ const trimmed = text.trim();
+ const start = trimmed.indexOf('{');
+ const end = trimmed.lastIndexOf('}');
+ if (start < 0 || end <= start) throw new Error('Provider returned no JSON object');
+ return JSON.parse(trimmed.slice(start, end + 1));
+}
+
+function cleanTriggers(value) {
+ if (!Array.isArray(value)) return [];
+ const seen = new Set();
+ return value.map(item => String(item).trim().toLowerCase()).filter(item => {
+ if (!item || item.length > MAX_TRIGGER_CHARS || seen.has(item)) return false;
+ if (!/^[a-z0-9][a-z0-9 +/#.:-]*$/.test(item)) return false;
+ seen.add(item);
+ return true;
+ }).slice(0, MAX_TRIGGERS_PER_SKILL);
+}
+
+function main() {
+ const flags = parseFlags(process.argv);
+ const repoRoot = path.join(__dirname, '..', '..');
+ const registry = loadContextRegistry({ repoRoot });
+ const entries = registry.entries.filter(entry => entry.id.startsWith('skill:'));
+ const executable = flags.executable || (flags.provider === 'claude' ? 'claude' : `${process.env.HOME}/.ecc-eval/codex/node_modules/.bin/codex`);
+ const family = flags.provider || providerFamily(executable);
+ const model = flags.model || DEFAULT_MODEL[family];
+ if (flags.dryRun) {
+ console.log(`would generate triggers for ${entries.length} skills via ${family} (${model}) in ${Math.ceil(entries.length / flags.batch)} provider calls`);
+ return;
+ }
+ if (family === 'codex' && (!flags.authHome || !path.isAbsolute(flags.authHome))) throw new Error('--auth-home with an absolute dedicated login home is required for Codex');
+ const lease = family === 'codex' ? createAuthLease(flags.authHome) : null;
+ const claudeToken = () => process.env.CLAUDE_CODE_OAUTH_TOKEN || readClaudeKeychainToken();
+ const triggers = {};
+ const failed = [];
+ const callProvider = batch => {
+ const home = fs.mkdtempSync(path.join(fs.realpathSync(os.tmpdir()), 'ecc-trigger-gen-'));
+ try {
+ if (family === 'codex') {
+ let parsed = null;
+ lease.run(home, () => {
+ const env = { PATH: process.env.PATH, HOME: home, CODEX_HOME: home, LANG: 'C.UTF-8' };
+ const result = require('node:child_process').spawnSync(executable,
+ ['exec', '--json', '--ephemeral', '--skip-git-repo-check', '--sandbox', 'read-only',
+ '--disable', 'apps', '--disable', 'remote_plugin', '-c', 'approval_policy="never"',
+ '-c', 'model_reasoning_effort="low"', '--model', model, '-'],
+ { input: promptFor(batch), cwd: home, env, encoding: 'utf8', shell: false,
+ timeout: 240000, killSignal: 'SIGKILL', maxBuffer: 1024 * 1024 });
+ if (result.status !== 0) throw new Error(`provider exited ${result.status}`);
+ parsed = extractJson(parseCodexJsonl(result.stdout).text);
+ });
+ return parsed;
+ }
+ const env = { PATH: process.env.PATH, HOME: home, CLAUDE_CONFIG_DIR: home, LANG: 'C.UTF-8',
+ DISABLE_NON_ESSENTIAL_MODEL_CALLS: '1', CLAUDE_CODE_OAUTH_TOKEN: claudeToken() };
+ const result = require('node:child_process').spawnSync(executable,
+ ['--print', '--output-format', 'json', '--tools', '', '--no-session-persistence', '--model', model],
+ { input: promptFor(batch), cwd: home, env, encoding: 'utf8', shell: false,
+ timeout: 240000, killSignal: 'SIGKILL', maxBuffer: 1024 * 1024 });
+ if (result.status !== 0) throw new Error(`provider exited ${result.status}`);
+ return extractJson(parseClaudeJson(result.stdout).text);
+ } finally { fs.rmSync(home, { recursive: true, force: true, maxRetries: 5 }); }
+ };
+ // Model-generated JSON degrades at batch scale: retry each batch once, then halve until singles.
+ const processBatch = batch => {
+ try {
+ const parsed = callProvider(batch);
+ let ok = 0;
+ for (const entry of batch) {
+ const cleaned = cleanTriggers(parsed[entry.id]);
+ if (cleaned.length) { triggers[entry.id] = cleaned; ok += 1; }
+ }
+ if (!ok) throw new Error('provider returned no usable triggers');
+ } catch (error) {
+ if (batch.length === 1) { failed.push(batch[0].id); console.error(`skill ${batch[0].id}: ${error.message}`); return; }
+ const half = Math.ceil(batch.length / 2);
+ processBatch(batch.slice(0, half));
+ processBatch(batch.slice(half));
+ }
+ };
+ for (let index = 0; index < entries.length; index += flags.batch) {
+ processBatch(entries.slice(index, index + flags.batch));
+ console.log(`progress: ${Object.keys(triggers).length}/${entries.length} skills have triggers`);
+ }
+ const manifest = { schemaVersion: 1, id: 'skill-triggers@1', registryDigest: registry.registryDigest,
+ model: { id: model, ...(family === 'codex' ? { effort: 'low' } : {}),
+ source: family === 'codex' ? 'codex-subscription-lease' : 'claude-subscription-login' },
+ generatedAt: new Date().toISOString(),
+ coverage: { skills: entries.length, withTriggers: Object.keys(triggers).length },
+ triggers, triggersDigest: digestObject(triggers) };
+ const target = path.join(repoRoot, MANIFEST_PATH);
+ fs.mkdirSync(path.dirname(target), { recursive: true });
+ fs.writeFileSync(target, `${stableStringify(manifest)}\n`);
+ console.log(`wrote ${MANIFEST_PATH}: ${manifest.coverage.withTriggers}/${manifest.coverage.skills} skills, ${Object.values(triggers).reduce((n, t) => n + t.length, 0)} triggers`);
+ if (failed.length) { console.error(`skills with no usable triggers: ${failed.join(', ')}`); process.exitCode = 1; }
+}
+
+main();
diff --git a/scripts/ecc.js b/scripts/ecc.js
index 6c2aee1a5..04257cba1 100755
--- a/scripts/ecc.js
+++ b/scripts/ecc.js
@@ -31,6 +31,10 @@ const COMMANDS = {
script: 'consult.js',
description: 'Recommend ECC components and profiles from a natural language query',
},
+ profile: {
+ script: 'profile.js',
+ description: 'Inspect Lean/Full profiles, stage managed generations, and resolve task context',
+ },
'control-pane': {
script: 'control-pane.js',
description: 'Run the local ECC2 operator control pane',
@@ -112,6 +116,7 @@ const PRIMARY_COMMANDS = [
'plan',
'catalog',
'consult',
+ 'profile',
'control-pane',
'ito',
'nasiko',
@@ -167,6 +172,7 @@ Examples:
ecc catalog components --family language
ecc catalog show framework:nextjs
ecc consult "security reviews"
+ ecc profile preview lean@1 --target codex --selection auto --json
ecc control-pane --port 8765
ecc ito login [--no-browser]
ecc ito logout
@@ -267,6 +273,7 @@ function runCommand(commandName, args) {
throw new Error(`Unknown command: ${commandName}`);
}
const isItoLogin = commandName === 'ito' && getInvocationCommand(args) === 'login';
+ const isProfileStart = commandName === 'profile' && getInvocationCommand(args) === 'start';
const result = spawnSync(
process.execPath,
[path.join(__dirname, command.script), ...args],
@@ -279,9 +286,9 @@ function runCommand(commandName, args) {
}),
}
: process.env,
- stdio: isItoLogin || commandName === 'setup' || commandName === 'install'
+ stdio: isItoLogin || isProfileStart || commandName === 'setup' || commandName === 'install'
? 'inherit'
- : commandName === 'memory'
+ : commandName === 'memory' || commandName === 'profile'
? ['inherit', 'pipe', 'pipe']
: ['pipe', 'pipe', 'pipe'],
encoding: 'utf8',
diff --git a/scripts/hooks/cost-tracker.js b/scripts/hooks/cost-tracker.js
index 981f67619..cf36168b1 100755
--- a/scripts/hooks/cost-tracker.js
+++ b/scripts/hooks/cost-tracker.js
@@ -4,7 +4,9 @@
*
* Reads transcript_path from Stop hook stdin, sums usage across all
* assistant turns in the session JSONL, and appends one row to
- * ~/.claude/metrics/costs.jsonl.
+ * ~/.claude/metrics/costs.jsonl. It also atomically publishes the latest
+ * cumulative row under metrics/cost-snapshots/ so frequent PostToolUse
+ * hooks do not need to rescan the unbounded history.
*
* Stop hook stdin payload: { session_id, transcript_path, cwd, hook_event_name, ... }
* The Stop payload does NOT include `usage` or `model` directly. The previous
@@ -40,8 +42,12 @@
const fs = require('fs');
const os = require('os');
const path = require('path');
-const { ensureDir, appendFile, getClaudeDir } = require('../lib/utils');
+const { ensureDir, getClaudeDir } = require('../lib/utils');
const { sanitizeSessionId } = require('../lib/session-bridge');
+const {
+ appendSessionCostRow,
+ warnSessionCostSnapshotFailure
+} = require('../lib/session-cost-snapshot');
const HARNESS_COST_MAX_AGE_SECONDS = 300;
@@ -103,7 +109,17 @@ function isSonnet5(model) {
function toNumber(v) {
const n = Number(v);
- return Number.isFinite(n) ? n : 0;
+ return Number.isFinite(n) && n >= 0 ? n : 0;
+}
+
+function normalizeUsageTotals(totals) {
+ return {
+ inputTokens: toNumber(totals.inputTokens),
+ outputTokens: toNumber(totals.outputTokens),
+ cacheWriteTokens: toNumber(totals.cacheWriteTokens),
+ cacheReadTokens: toNumber(totals.cacheReadTokens),
+ model: totals.model
+ };
}
/**
@@ -161,7 +177,9 @@ function sumUsageFromTranscript(transcriptPath) {
cacheReadTokens += toNumber(u.cache_read_input_tokens);
}
- return { inputTokens, outputTokens, cacheWriteTokens, cacheReadTokens, model };
+ return normalizeUsageTotals({
+ inputTokens, outputTokens, cacheWriteTokens, cacheReadTokens, model
+ });
}
// 1MB, matching the other Stop hooks. The Stop payload carries
@@ -242,7 +260,11 @@ process.stdin.on('end', () => {
estimated_cost_usd: estimatedCostUsd
};
- appendFile(path.join(metricsDir, 'costs.jsonl'), `${JSON.stringify(row)}\n`);
+ try {
+ appendSessionCostRow(metricsDir, sessionId, row);
+ } catch (error) {
+ warnSessionCostSnapshotFailure('publication', metricsDir, sessionId, error);
+ }
} catch {
// Non-blocking — never fail the Stop hook.
}
diff --git a/scripts/hooks/ecc-metrics-bridge.js b/scripts/hooks/ecc-metrics-bridge.js
index cbecd4536..31ecad948 100644
--- a/scripts/hooks/ecc-metrics-bridge.js
+++ b/scripts/hooks/ecc-metrics-bridge.js
@@ -14,6 +14,10 @@ const fs = require('fs');
const os = require('os');
const path = require('path');
const { sanitizeSessionId, readBridge, writeBridgeAtomic } = require('../lib/session-bridge');
+const {
+ readSessionCostSnapshot,
+ warnSessionCostSnapshotFailure
+} = require('../lib/session-cost-snapshot');
const { getClaudeDir } = require('../lib/utils');
const MAX_STDIN = 1024 * 1024;
@@ -22,11 +26,6 @@ const RECENT_TOOLS_SIZE = 5;
const HASH_INPUT_LIMIT = 2048;
const WARNING_CACHE_PREFIX = 'ecc-metrics-cost-warnings-';
-function toNumber(value) {
- const n = Number(value);
- return Number.isFinite(n) ? n : 0;
-}
-
function stableStringify(value, depth = 0) {
if (depth > 4) return '[depth-limit]';
if (value === null || typeof value !== 'object') return JSON.stringify(value);
@@ -134,60 +133,51 @@ function writeCostWarningIfChanged(kind, costsPath, signature, message) {
}
/**
- * Read cumulative cost for a session from costs.jsonl.
+ * Read cumulative cost for a session.
*
- * Scans the full file because each row is a cumulative session total
- * (see cost-tracker.js docblock) and the row we need is the last one
- * matching `sessionId`. The previous implementation read only the
- * trailing 8 KiB; any session whose latest cumulative row was pushed
- * past that window by newer rows from other sessions silently dropped
- * to zero — the opposite sign of the double-count bug fixed in the
- * previous commit.
+ * The Stop hook publishes an atomic per-session cursor snapshot, so a stable
+ * PostToolUse path reads O(1) metadata and newly appended data is O(delta)
+ * instead of reparsing unbounded history.
+ * Older ECC installations and damaged/missing snapshots remain compatible:
+ * they fall back to scanning costs.jsonl for the last cumulative row.
*
- * costs.jsonl is append-only and unbounded today (no rotation in
- * cost-tracker.js). At a typical ~150 bytes per row, even 100k rows
- * is ~15 MB and a single sync read on every PostToolUse hook is in
- * the low milliseconds. If rotation lands later, this scan becomes
- * even cheaper.
+ * The fallback deliberately scans the whole file. A fixed tail window loses
+ * sessions whose newest row has been pushed back by other sessions.
*/
function readSessionCost(sessionId) {
let costsPath = path.join('metrics', 'costs.jsonl');
try {
- costsPath = path.join(getClaudeDir(), 'metrics', 'costs.jsonl');
- const content = fs.readFileSync(costsPath, 'utf8');
- const lines = content.split('\n').filter(Boolean);
-
- let totalCost = 0;
- let totalIn = 0;
- let totalOut = 0;
- let malformed = 0;
- const malformedHasher = crypto.createHash('sha256');
- for (const line of lines) {
- try {
- const row = JSON.parse(line);
- if (row.session_id === sessionId) {
- totalCost = toNumber(row.estimated_cost_usd);
- totalIn = toNumber(row.input_tokens);
- totalOut = toNumber(row.output_tokens);
- }
- } catch {
- malformed += 1;
- malformedHasher.update(line).update('\0');
- }
- }
- // One aggregated breadcrumb per call rather than one per bad row, so a
- // log-flooded costs.jsonl stays diagnosable without overwhelming stderr.
- // Suppress repeats for the same malformed-line signature across hook
- // subprocesses, so a persistent bad row should not spam stderr.
- if (malformed > 0) {
+ const metricsDir = path.join(getClaudeDir(), 'metrics');
+ costsPath = path.join(metricsDir, 'costs.jsonl');
+ const snapshotResult = readSessionCostSnapshot(metricsDir, sessionId);
+ if (snapshotResult.malformed > 0) {
writeCostWarningIfChanged(
'malformed',
costsPath,
- `${malformed}:${malformedHasher.digest('hex').slice(0, 16)}`,
- `[ecc-metrics-bridge] skipped ${malformed} malformed line(s) in ${costsPath}\n`
+ `${snapshotResult.malformed}:${snapshotResult.malformedSignature}`,
+ `[ecc-metrics-bridge] skipped ${snapshotResult.malformed} malformed line(s) during the snapshot scan of ${costsPath}\n`
);
}
- return { totalCost, totalIn, totalOut };
+ if (snapshotResult.invalid > 0) {
+ writeCostWarningIfChanged(
+ 'invalid-row',
+ costsPath,
+ `${snapshotResult.invalid}:${snapshotResult.invalidSignature}`,
+ `[ecc-metrics-bridge] skipped ${snapshotResult.invalid} invalid cumulative row(s) for ${sessionId} during the snapshot scan of ${costsPath}\n`
+ );
+ }
+ if (snapshotResult.snapshotError) {
+ warnSessionCostSnapshotFailure(
+ 'repair',
+ metricsDir,
+ sessionId,
+ snapshotResult.snapshotError
+ );
+ }
+ const row = snapshotResult.row;
+ return row
+ ? { totalCost: row.estimated_cost_usd, totalIn: row.input_tokens, totalOut: row.output_tokens }
+ : { totalCost: 0, totalIn: 0, totalOut: 0 };
} catch (err) {
// ENOENT is the common case (no Stop event has fired yet this session)
// and is not actually a failure — stay silent on it. Anything else
@@ -259,7 +249,7 @@ function run(rawInput) {
if (recent.length > RECENT_TOOLS_SIZE) recent.shift();
bridge.recent_tools = recent;
- // Update cost from costs.jsonl tail
+ // Use the O(1) session snapshot, with JSONL compatibility fallback.
const costs = readSessionCost(sessionId);
bridge.total_cost_usd = Math.round(costs.totalCost * 1e6) / 1e6;
bridge.total_input_tokens = costs.totalIn;
diff --git a/scripts/hooks/gateguard-fact-force.js b/scripts/hooks/gateguard-fact-force.js
index bfd2b11c6..6756a0b79 100644
--- a/scripts/hooks/gateguard-fact-force.js
+++ b/scripts/hooks/gateguard-fact-force.js
@@ -359,6 +359,155 @@ function quoteAwareSegments(input) {
const SHELL_WRAPPERS = new Set(['sh', 'bash', 'zsh', 'dash', 'ksh']);
+/**
+ * SQL clients whose `-c`/`-e`/positional arguments carry SQL statements.
+ * Quoted SQL (e.g. `psql -c "drop table users"`) is invisible to the
+ * quote-stripping SQL regex, so it is re-checked here against dequoted
+ * tokens where quoted content is preserved (issue #3024). Restricted to
+ * known clients so `git commit -m "drop table"` and `echo "drop table"`
+ * stay allowed.
+ */
+const SQL_CLIENT_COMMANDS = new Set([
+ 'psql',
+ 'postgres',
+ 'mysql',
+ 'mariadb',
+ 'sqlite3',
+ 'sqlite',
+ 'sqlcmd',
+ 'isql',
+ 'pgcli',
+ 'mycli',
+ 'duckdb',
+ 'bq',
+]);
+
+/**
+ * Strip SQL string literals so phrases inside query data do not trigger
+ * the destructive detector (e.g. `SELECT 'drop table' ...` is a read).
+ * Handles single-quoted literals with '' escapes, double-quoted
+ * identifiers, and dollar-quoted blocks ($$...$$ and $tag$...$tag$).
+ *
+ * @param {string} input
+ * @returns {string}
+ */
+function stripSqlLiterals(input) {
+ return String(input || '')
+ .replace(/'(?:[^']|'')*'/g, "''")
+ .replace(/"(?:[^"\\]|\\.)*"/g, '""')
+ .replace(/(\$[A-Za-z_][A-Za-z0-9_]*\$|\$\$)[\s\S]*?\1/g, '$$$$');
+}
+
+const SUDO_VALUE_FLAGS = new Set([
+ '-u',
+ '--user',
+ '-g',
+ '--group',
+ '-U',
+ '--other-user',
+ '-p',
+ '--prompt',
+ '-C',
+ '--close-from',
+ '-D',
+ '--chdir',
+ '-h',
+ '--host',
+ '-r',
+ '--role',
+ '-t',
+ '--type',
+ '-T',
+ '--command-timeout',
+]);
+
+/**
+ * Advance past `sudo`/`doas`/`env` wrappers including their flags and
+ * `VAR=value` assignments, so `sudo -u postgres psql ...` and
+ * `env PGUSER=postgres psql ...` still resolve to the real command.
+ *
+ * @param {string[]} tokens dequoted tokens for one segment
+ * @returns {number} index of the real command token
+ */
+function unwrapLeadWrappers(tokens) {
+ let index = 0;
+ for (let guard = 0; guard < 4; guard += 1) {
+ if (index >= tokens.length) return index;
+ const base = commandBasename(tokens[index]);
+ if (base === 'sudo' || base === 'doas') {
+ index += 1;
+ while (index < tokens.length) {
+ const flag = tokens[index];
+ if (flag === '--') {
+ index += 1;
+ break;
+ }
+ if (flag === '-' || !flag.startsWith('-')) break;
+ if (SUDO_VALUE_FLAGS.has(flag)) {
+ index += 2;
+ continue;
+ }
+ if (/^--[^=]+=.*$/.test(flag)) {
+ index += 1;
+ continue;
+ }
+ index += 1;
+ }
+ continue;
+ }
+ if (base === 'env') {
+ index += 1;
+ while (index < tokens.length) {
+ const arg = tokens[index];
+ if (arg === '--' || arg === '-' || arg === '-i' || arg === '--ignore-environment') {
+ index += 1;
+ continue;
+ }
+ if (arg === '-u' || arg === '--unset') {
+ index += 2;
+ continue;
+ }
+ if (arg === '-C' || arg === '--chdir') {
+ index += 2;
+ continue;
+ }
+ if (/^--unset=.*$/.test(arg) || /^--chdir=.*$/.test(arg) || /^--argv0=.*$/.test(arg)) {
+ index += 1;
+ continue;
+ }
+ if (arg.startsWith('-') && !/^[A-Za-z_][A-Za-z0-9_]*=/.test(arg)) {
+ index += 1;
+ continue;
+ }
+ if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(arg)) {
+ index += 1;
+ continue;
+ }
+ break;
+ }
+ continue;
+ }
+ break;
+ }
+ return index;
+}
+
+/**
+ * Detect destructive SQL passed as (possibly quoted) arguments to a known
+ * SQL client. Operates on dequoted tokens from `quoteAwareSegments`, so
+ * `psql -c "drop table users"` joins back to matchable text.
+ *
+ * @param {string[]} tokens dequoted tokens for one segment
+ * @returns {boolean}
+ */
+function isDestructiveSqlClient(tokens) {
+ if (!tokens || tokens.length === 0) return false;
+ const start = unwrapLeadWrappers(tokens);
+ if (start >= tokens.length) return false;
+ if (!SQL_CLIENT_COMMANDS.has(commandBasename(tokens[start]))) return false;
+ return DESTRUCTIVE_SQL_DD.test(stripSqlLiterals(tokens.slice(start).join(' ')));
+}
+
/**
* Quote-aware destructive check: catches quoted command words, newline
* separators, quoted `find -exec`, and `sh -c`/`bash -c` wrappers that evade
@@ -374,10 +523,12 @@ function isDestructiveQuoteAware(raw, depth = 0) {
if (tokens.length === 0) continue;
if (isDestructiveRm(tokens)) return true;
if (isDestructiveGit(tokens)) return true;
+ if (isDestructiveSqlClient(tokens)) return true;
if (isDestructiveFindExec(tokens.join(' '))) return true;
- const base = commandBasename(tokens[0]);
+ const wi = unwrapLeadWrappers(tokens);
+ const base = wi < tokens.length ? commandBasename(tokens[wi]) : '';
if (SHELL_WRAPPERS.has(base)) {
- const ci = tokens.indexOf('-c');
+ const ci = tokens.indexOf('-c', wi);
if (ci !== -1 && tokens[ci + 1] && isDestructiveQuoteAware(tokens[ci + 1], depth + 1)) {
return true;
}
@@ -462,10 +613,65 @@ function findGitSubcommand(tokens) {
return null;
}
+/**
+ * Branch names treated as shared history: a forced update of one of
+ * these rewrites commits other clones build on, even when the push is
+ * lease-checked.
+ */
+const SHARED_GIT_BRANCHES = new Set(['main', 'master', 'develop', 'trunk']);
+
+/**
+ * Decide whether the positional arguments of a `git push` name a shared
+ * branch as the destination of a refspec. The first positional token is
+ * the remote (unless the remote came from `--repo`); every later
+ * positional token is a refspec whose destination is the part after
+ * `:` (or the whole token when there is no `:`). A leading `+` force
+ * marker is stripped. When no refspec is given the target is the
+ * current branch, which the hook cannot know, so this returns false.
+ *
+ * @param {string[]} rest tokens after `push`
+ * @returns {boolean}
+ */
+function pushTargetsSharedBranch(rest) {
+ const valueConsuming = new Set(['-o', '--push-option', '--receive-pack', '--exec']);
+ const positional = [];
+ let remoteViaFlag = false;
+ for (let i = 0; i < rest.length; i++) {
+ const t = rest[i];
+ if (t === '--repo') {
+ remoteViaFlag = true;
+ i += 1;
+ continue;
+ }
+ if (t.startsWith('--repo=')) {
+ remoteViaFlag = true;
+ continue;
+ }
+ if (valueConsuming.has(t)) {
+ i += 1;
+ continue;
+ }
+ if (t.startsWith('-')) continue;
+ positional.push(t);
+ }
+ // Unless the remote came from --repo, positional[0] is the remote and
+ // the rest are refspecs.
+ const refspecs = remoteViaFlag ? positional : positional.slice(1);
+ for (const refspec of refspecs) {
+ const cleaned = refspec.startsWith('+') ? refspec.slice(1) : refspec;
+ const dst = cleaned.includes(':') ? cleaned.slice(cleaned.indexOf(':') + 1) : cleaned;
+ const branch = dst.startsWith('refs/heads/') ? dst.slice('refs/heads/'.length) : dst;
+ if (SHARED_GIT_BRANCHES.has(branch)) return true;
+ }
+ return false;
+}
+
/**
* Detect destructive `git` invocations: `reset --hard`, `checkout --`,
- * `clean -f...`, `push --force` (but not `--force-with-lease`),
- * `commit --amend`, `rm -rf`.
+ * `clean -f...`, `push --force` (`--force-with-lease` only to a shared
+ * branch), `commit --amend`, `rm -rf`, `branch -D`, `stash drop` /
+ * `stash clear`, `reflog expire` / `reflog delete`, `update-ref -d`,
+ * and `restore` against the worktree.
*
* @param {string[]} tokens
* @returns {boolean}
@@ -532,7 +738,9 @@ function isDestructiveGit(tokens) {
plusRefspecForce = true;
}
}
- return bareForce || (plusRefspecForce && !withLease);
+ if (bareForce || (plusRefspecForce && !withLease)) return true;
+ // A lease-checked force still rewrites a shared branch's history.
+ return withLease && pushTargetsSharedBranch(rest);
}
if (command === 'commit') {
@@ -563,6 +771,53 @@ function isDestructiveGit(tokens) {
});
}
+ if (command === 'branch') {
+ // `git branch -D` (long spelling: `--delete --force`) deletes a
+ // branch even when it is unmerged, orphaning its commits. Plain
+ // `-d` refuses when unmerged, so it is safe to leave ungated.
+ let del = false;
+ let force = false;
+ for (const t of rest) {
+ if (t === '--delete') { del = true; continue; }
+ if (t === '--force') { force = true; continue; }
+ if (!t.startsWith('-') || t.startsWith('--')) continue;
+ const body = t.slice(1);
+ if (body.includes('D')) return true;
+ if (body.includes('d')) del = true;
+ if (body.includes('f')) force = true;
+ }
+ return del && force;
+ }
+
+ if (command === 'stash') {
+ // `drop` destroys one stash entry, `clear` the entire stash.
+ // `list`, `show`, `pop` and `apply` keep the entries recoverable.
+ return rest[0] === 'drop' || rest[0] === 'clear';
+ }
+
+ if (command === 'reflog') {
+ // `expire` and `delete` remove the recovery net that makes every
+ // other gated git command recoverable.
+ return rest[0] === 'expire' || rest[0] === 'delete';
+ }
+
+ if (command === 'update-ref') {
+ // `git update-ref -d ` deletes a ref directly.
+ return rest.includes('-d') || rest.includes('--delete');
+ }
+
+ if (command === 'restore') {
+ // `git restore ` overwrites the working tree from the index
+ // by default, the modern spelling of gated `git checkout -- `.
+ // Only `--staged` alone is non-destructive (it leaves the file on
+ // disk untouched); `--worktree` (the default target) is destructive.
+ const has = (long, short) => rest.some(t =>
+ t === long || (t.startsWith('-') && !t.startsWith('--') && t.slice(1).includes(short)));
+ const staged = has('--staged', 'S');
+ const worktree = has('--worktree', 'W');
+ return worktree || !staged;
+ }
+
return false;
}
@@ -1007,16 +1262,62 @@ function isChecked(key) {
// --- Sanitize file path against injection ---
+// Unicode policy for sanitizePath, mirroring the repo-wide dangerous set in
+// scripts/ci/check-unicode-safety.js. Named so the ranges stay auditable and
+// drift against the CI policy is visible in one place.
+const ASCII_CONTROL_MAX = 0x1f;
+const ASCII_DELETE = 0x7f;
+const C1_CONTROLS = [0x80, 0x9f]; // Unicode C1 control block (U+0080..U+009F)
+const BIDI_MARKS = [0x200e, 0x200f]; // LRM/RLM
+const BIDI_EMBEDDINGS = [0x202a, 0x202e]; // LRE..PDF
+const BIDI_ISOLATES = [0x2066, 0x2069]; // LRI..PDI
+const ZERO_WIDTHS = [0x200b, 0x200d]; // ZWSP..ZWJ
+const WORD_JOINER = 0x2060;
+const BYTE_ORDER_MARK = 0xfeff;
+const VARIATION_SELECTORS = [0xfe00, 0xfe0f];
+const VARIATION_SUPPLEMENTS = [0xe0100, 0xe01ef]; // MONGOLIAN..TAGS (VS17..VS256)
+const TAG_BLOCK = [0xe0000, 0xe007f]; // ASCII-smuggling tag characters
+const MONGOLIAN_VOWEL_SEPARATOR = 0x180e;
+const HANGUL_CHOSEONG_FILLER = 0x115f;
+const HANGUL_JUNGSEONG_FILLER = 0x1160;
+const HANGUL_FILLER = 0x3164;
+const INVISIBLE_MATH_OPERATORS = [0x2061, 0x2064]; // FUNCTION APPLICATION..INVISIBLE PLUS
+const LINE_SEPARATOR = 0x2028;
+const PARAGRAPH_SEPARATOR = 0x2029;
+const SANITIZED_PATH_MAX_LENGTH = 500;
+
+function inRange(code, [lo, hi]) {
+ return code >= lo && code <= hi;
+}
+
function sanitizePath(filePath) {
- // Strip control chars (including null), bidi overrides, and newlines
+ // Strip control chars (including null), bidi overrides, separators,
+ // and the dangerous invisible characters defined by the constants
+ // above (mirroring scripts/ci/check-unicode-safety.js), so a denial
+ // message cannot carry content a human reviewer cannot see.
let sanitized = '';
for (const char of String(filePath || '')) {
const code = char.codePointAt(0);
- const isAsciiControl = code <= 0x1f || code === 0x7f;
- const isBidiOverride = (code >= 0x200e && code <= 0x200f) || (code >= 0x202a && code <= 0x202e) || (code >= 0x2066 && code <= 0x2069);
- sanitized += isAsciiControl || isBidiOverride ? ' ' : char;
+ const isAsciiControl =
+ code <= ASCII_CONTROL_MAX || code === ASCII_DELETE || inRange(code, C1_CONTROLS);
+ const isBidiOverride =
+ inRange(code, BIDI_MARKS) || inRange(code, BIDI_EMBEDDINGS) || inRange(code, BIDI_ISOLATES);
+ const isUnicodeSeparator = code === LINE_SEPARATOR || code === PARAGRAPH_SEPARATOR;
+ const isDangerousInvisible =
+ inRange(code, ZERO_WIDTHS) ||
+ code === WORD_JOINER ||
+ code === BYTE_ORDER_MARK ||
+ inRange(code, VARIATION_SELECTORS) ||
+ inRange(code, VARIATION_SUPPLEMENTS) ||
+ inRange(code, TAG_BLOCK) ||
+ code === MONGOLIAN_VOWEL_SEPARATOR ||
+ code === HANGUL_CHOSEONG_FILLER ||
+ code === HANGUL_JUNGSEONG_FILLER ||
+ code === HANGUL_FILLER ||
+ inRange(code, INVISIBLE_MATH_OPERATORS);
+ sanitized += isAsciiControl || isBidiOverride || isUnicodeSeparator || isDangerousInvisible ? ' ' : char;
}
- return sanitized.trim().slice(0, 500);
+ return sanitized.trim().slice(0, SANITIZED_PATH_MAX_LENGTH);
}
function normalizeForMatch(value) {
@@ -1101,6 +1402,21 @@ function isReadOnlyGitIntrospection(command) {
// --- Gate messages ---
+/**
+ * Batch-consistency warning (#3136). A first-touch denial marks the file
+ * checked so the retry passes; a parallel batch of edits to one
+ * not-yet-touched file therefore partially applies (first call denied,
+ * siblings allowed). Hooks see calls one at a time and cannot lock a
+ * batch, so the denial must say this out loud: name the file and tell
+ * the agent that siblings may already have been applied.
+ */
+function batchSiblingWarning(safePath) {
+ return (
+ `If this call was sent in a parallel batch, other edits to ${safePath} from that batch ` +
+ 'may already have been applied. Re-read the file before building on them.'
+ );
+}
+
function editGateMsg(filePath) {
const safe = sanitizePath(filePath);
return [
@@ -1113,6 +1429,8 @@ function editGateMsg(filePath) {
'3. If this file reads/writes data files, show field names, structure, and date format (use redacted or synthetic values, not raw production data)',
"4. Quote the user's current instruction verbatim",
'',
+ batchSiblingWarning(safe),
+ '',
'Present the facts, then retry the same operation.'
].join('\n');
}
@@ -1129,6 +1447,8 @@ function writeGateMsg(filePath) {
'3. If this file reads/writes data files, show field names, structure, and date format (use redacted or synthetic values, not raw production data)',
"4. Quote the user's current instruction verbatim",
'',
+ batchSiblingWarning(safe),
+ '',
'Present the facts, then retry the same operation.'
].join('\n');
}
@@ -1143,6 +1463,7 @@ function condensedGateMsg(action, filePath, ordinal) {
return (
`[Fact-Forcing Gate] (denial #${ordinal} this session) First ${action} of ${safe}: ` +
"briefly state importers/callers, affected API, data schemas if any, and the user's verbatim instruction, then retry. " +
+ `${batchSiblingWarning(safe)} ` +
'(Use GATEGUARD_EXEMPT_GLOBS for path-scoped exemptions; ECC_GATEGUARD=off disables this gate.)'
);
}
diff --git a/scripts/hooks/gateguard-heredoc.js b/scripts/hooks/gateguard-heredoc.js
index 31e41b29b..79e2df50f 100644
--- a/scripts/hooks/gateguard-heredoc.js
+++ b/scripts/hooks/gateguard-heredoc.js
@@ -3,16 +3,23 @@
const { extractCommandSubstitutions } = require('../lib/shell-substitution');
/**
- * Recognize the deliberately narrow passive sink supported by this parser.
- * Shell operators and substitutions make the payload's destination ambiguous,
- * so every other form retains the original input for fail-closed checks.
+ * Recognize proven-passive sinks whose heredoc payload is data, not a command
+ * stream. `cat` and `tee` (optionally path-qualified, or wrapped in
+ * `command`/`builtin`/`env`) only write stdin; they do not execute the body.
+ * Shell operators or substitution markers make the destination ambiguous, so
+ * every other form retains the original input for fail-closed checks.
*
* @param {string} line
* @returns {boolean}
*/
function isProvenPassiveHeredocLine(line) {
const trimmed = line.trim();
- return /^cat(?=\s|[<>])/.test(trimmed) && !/[;&|()`]/.test(trimmed);
+ // Fail closed on control operators / grouping / command substitutions.
+ if (/[;&|()`]/.test(trimmed)) return false;
+ // Optional wrapper + optional path prefix + cat|tee, then args or redirect.
+ return /^(?:(?:command|builtin|env)\s+)?(?:(?:\.\/|\/(?:[\w.+-]+\/)*)?(?:cat|tee))(?=\s|[<>])/.test(
+ trimmed
+ );
}
/**
diff --git a/scripts/hooks/mcp-health-check.js b/scripts/hooks/mcp-health-check.js
index b78b5ac57..843a6ec04 100644
--- a/scripts/hooks/mcp-health-check.js
+++ b/scripts/hooks/mcp-health-check.js
@@ -182,6 +182,12 @@ function extractMcpTargetFromRaw(raw) {
}
function resolveServerConfig(serverName) {
+ // SECURITY: serverName flows into env-var lookup and shell-adjacent paths.
+ // Reject anything outside a strict token so config-controlled names cannot
+ // inject shell metachars ($(..), backticks, ;) downstream.
+ if (!/^[A-Za-z0-9_-]{1,64}$/.test(String(serverName || ''))) {
+ return null;
+ }
for (const filePath of configPaths()) {
const data = readJsonFile(filePath);
const server = data?.mcpServers?.[serverName]
@@ -306,9 +312,21 @@ function probeCommandServer(serverName, config) {
const command = config.command;
const args = Array.isArray(config.args) ? config.args.map(arg => String(arg)) : [];
const timeoutMs = envNumber('ECC_MCP_HEALTH_TIMEOUT_MS', DEFAULT_TIMEOUT_MS);
+ // SECURITY: config.env comes from repo-committed MCP configs. Never let it
+ // override process-critical loader vars that turn into code execution
+ // (LD_PRELOAD, DYLD_*, NODE_OPTIONS, PATH tampering, etc.).
+ const BLOCKED_ENV_PREFIXES = ['LD_', 'DYLD_', 'NODE_OPTIONS', 'NODE_PATH', 'PATH', 'PYTHONPATH', 'RUBYLIB', 'PERL5LIB'];
+ const rawEnv = (config.env && typeof config.env === 'object' && !Array.isArray(config.env) ? config.env : {});
+ const safeConfigEnv = {};
+ for (const [k, v] of Object.entries(rawEnv)) {
+ if (BLOCKED_ENV_PREFIXES.some(p => String(k).toUpperCase().startsWith(p))) {
+ continue;
+ }
+ safeConfigEnv[k] = String(v);
+ }
const mergedEnv = {
...process.env,
- ...(config.env && typeof config.env === 'object' && !Array.isArray(config.env) ? config.env : {})
+ ...safeConfigEnv
};
let done = false;
@@ -515,6 +533,38 @@ function probeCommandServer(serverName, config) {
async function probeServer(serverName, resolvedConfig) {
const config = resolvedConfig.config;
+ // SECURITY: cloning a malicious repo must not auto-execute its MCP servers.
+ // Workspace configs (cwd .claude.json / .claude/settings.json) are untrusted
+ // by default; only probe them with explicit operator opt-in.
+ // Home configs (~/.claude.json) and explicit ECC_MCP_CONFIG_PATH remain allowed.
+ try {
+ const src = String(resolvedConfig.source || '');
+ const cwd = process.cwd();
+ const home = require('os').homedir();
+ const pathMod = require('path');
+ // A config file in the user's home directory (~/.claude.json or
+ // ~/.claude/settings.json) is always trusted regardless of cwd.
+ const isHomeSource = src === pathMod.join(home, '.claude.json')
+ || src === pathMod.join(home, '.claude', 'settings.json')
+ || src.startsWith(pathMod.join(home, '.claude') + pathMod.sep);
+ if (!isHomeSource) {
+ const isWorkspaceSource = src === pathMod.join(cwd, '.claude.json')
+ || src === pathMod.join(cwd, '.claude', 'settings.json')
+ || src.startsWith(cwd + pathMod.sep + '.claude' + pathMod.sep);
+ if (isWorkspaceSource && !/^(1|true|yes)$/i.test(String(process.env.ECC_MCP_ALLOW_WORKSPACE_PROBE || ''))) {
+ return {
+ ok: false,
+ failureCode: null,
+ reason: 'untrusted workspace MCP config skipped (set ECC_MCP_ALLOW_WORKSPACE_PROBE=1 to probe)',
+ source: resolvedConfig.source
+ };
+ }
+ }
+ } catch {
+ // Fail closed on path errors for workspace sources is handled below;
+ // continue to normal probing for non-workspace sources.
+ }
+
if (config.type === 'http' || config.url) {
const result = await requestHttp(config.url, config.headers || {}, envNumber('ECC_MCP_HEALTH_TIMEOUT_MS', DEFAULT_TIMEOUT_MS));
@@ -546,6 +596,15 @@ async function probeServer(serverName, resolvedConfig) {
}
function reconnectCommand(serverName) {
+ // SECURITY: reconnect commands are shell strings from env. Disabled by
+ // default; require explicit opt-in so a malicious .env/direnv cannot gain
+ // shell execution through this hook.
+ if (!/^(1|true|yes)$/i.test(String(process.env.ECC_MCP_RECONNECT_ALLOW || ''))) {
+ return null;
+ }
+ if (!/^[A-Za-z0-9_-]{1,64}$/.test(String(serverName || ''))) {
+ return null;
+ }
const key = `ECC_MCP_RECONNECT_${String(serverName).toUpperCase().replace(/[^A-Z0-9]/g, '_')}`;
const command = process.env[key] || process.env.ECC_MCP_RECONNECT_COMMAND || '';
if (!command.trim()) {
@@ -563,8 +622,60 @@ function attemptReconnect(serverName) {
return { attempted: false, success: false, reason: 'no reconnect command configured' };
}
- const result = spawnSync(command, {
- shell: true,
+ // SECURITY: never run reconnect strings through a shell. Split on
+ // whitespace (no glob/expansion/substitution) and spawn directly.
+ // Supports single/double quotes for paths with spaces (e.g. node
+ // "/tmp/dir with space/reconnect.js"). No variable, command, tilde, or
+ // glob expansion is performed. {server} was already validated above.
+ function splitReconnectCommand(s) {
+ const parts = [];
+ let cur = '';
+ let quote = null;
+ let inToken = false;
+ for (let i = 0; i < s.length; i++) {
+ const ch = s[i];
+ if (quote) {
+ if (ch === quote) {
+ quote = null;
+ } else if (ch === '\\' && quote === '"' && i + 1 < s.length && (s[i + 1] === '"' || s[i + 1] === '\\')) {
+ cur += s[i + 1];
+ i++;
+ } else {
+ cur += ch;
+ }
+ } else if (ch === '"' || ch === "'") {
+ quote = ch;
+ inToken = true;
+ } else if (/\s/.test(ch)) {
+ if (inToken) {
+ parts.push(cur);
+ cur = '';
+ inToken = false;
+ }
+ } else {
+ cur += ch;
+ inToken = true;
+ }
+ }
+ if (quote) {
+ return null; // unbalanced quote
+ }
+ if (inToken) {
+ parts.push(cur);
+ }
+ return parts;
+ }
+ const parts = splitReconnectCommand(String(command).trim());
+ if (!parts || parts.length === 0) {
+ return { attempted: false, success: false, reason: 'invalid reconnect command' };
+ }
+ const [bin, ...argv] = parts;
+ if (/[&|<>^%!`$();]/.test(bin) || argv.some(a => /[`$]/.test(a))) {
+ return { attempted: false, success: false, reason: 'reconnect command contains unsafe characters' };
+ }
+
+ const result = spawnSync(bin, argv, {
+ shell: false,
env: process.env,
cwd: process.cwd(),
encoding: 'utf8',
diff --git a/scripts/hooks/pre-bash-commit-quality.js b/scripts/hooks/pre-bash-commit-quality.js
index 400497055..6504a1b56 100644
--- a/scripts/hooks/pre-bash-commit-quality.js
+++ b/scripts/hooks/pre-bash-commit-quality.js
@@ -99,7 +99,7 @@ function findFileIssues(filePath) {
const lineNum = index + 1;
// Check for console.log
- if (line.includes('console.log') && !line.trim().startsWith('//') && !line.trim().startsWith('*')) {
+ if (line.includes('console.log') && !line.trim().startsWith('//') && !line.trim().startsWith('*') && !line.trim().startsWith('#')) {
issues.push({
type: 'console.log',
message: `console.log found at line ${lineNum}`,
@@ -109,7 +109,7 @@ function findFileIssues(filePath) {
}
// Check for debugger statements
- if (/\bdebugger\b/.test(line) && !line.trim().startsWith('//')) {
+ if (/\bdebugger\b/.test(line) && !line.trim().startsWith('//') && !line.trim().startsWith('#')) {
issues.push({
type: 'debugger',
message: `debugger statement at line ${lineNum}`,
@@ -119,7 +119,7 @@ function findFileIssues(filePath) {
}
// Check for TODO/FIXME without issue reference
- const todoMatch = line.match(/\/\/\s*(TODO|FIXME):?\s*(.+)/);
+ const todoMatch = line.match(/(?:\/\/|#)\s*(TODO|FIXME):?\s*(\S.*)/);
if (todoMatch && !todoMatch[2].match(/#\d+|issue/i)) {
issues.push({
type: 'todo',
diff --git a/scripts/hooks/run-with-flags-shell.sh b/scripts/hooks/run-with-flags-shell.sh
index 227b8fc7b..9599e303f 100755
--- a/scripts/hooks/run-with-flags-shell.sh
+++ b/scripts/hooks/run-with-flags-shell.sh
@@ -22,9 +22,31 @@ if [[ "$ENABLED" != "yes" ]]; then
exit 0
fi
-SCRIPT_PATH="${PLUGIN_ROOT}/${REL_SCRIPT_PATH}"
-if [[ ! -f "$SCRIPT_PATH" ]]; then
- echo "[Hook] Script not found for ${HOOK_ID}: ${SCRIPT_PATH}" >&2
+# Reject traversal / absolute / env-escape paths before touching the filesystem.
+# Mirrors the containment check in run-with-flags.js (resolvedRoot prefix).
+case "$REL_SCRIPT_PATH" in
+ /*|\\*|~*|*..*|*\$*|*\`*|*\|*|*\;*|*\&*|*\<*|*\>*|*\"*|*\'*|*\ *|*" "*)
+ echo "[Hook] Path traversal rejected for ${HOOK_ID}: ${REL_SCRIPT_PATH}" >&2
+ printf '%s' "$INPUT"
+ exit 0
+ ;;
+esac
+
+# Canonicalize PLUGIN_ROOT (CLAUDE_PLUGIN_ROOT is env-controlled) and the
+# candidate script path, then enforce containment inside the plugin root.
+PLUGIN_ROOT_CANON="$(realpath -m "$PLUGIN_ROOT" 2>/dev/null || readlink -f "$PLUGIN_ROOT" 2>/dev/null || printf '%s' "$PLUGIN_ROOT")"
+SCRIPT_PATH="${PLUGIN_ROOT_CANON}/${REL_SCRIPT_PATH}"
+SCRIPT_CANON="$(realpath -m "$SCRIPT_PATH" 2>/dev/null || readlink -f "$SCRIPT_PATH" 2>/dev/null || printf '%s' "$SCRIPT_PATH")"
+case "$SCRIPT_CANON" in
+ "$PLUGIN_ROOT_CANON"/*) ;;
+ *)
+ echo "[Hook] Path traversal rejected for ${HOOK_ID}: ${REL_SCRIPT_PATH}" >&2
+ printf '%s' "$INPUT"
+ exit 0
+ ;;
+esac
+if [[ ! -f "$SCRIPT_CANON" ]]; then
+ echo "[Hook] Script not found for ${HOOK_ID}: ${SCRIPT_CANON}" >&2
printf '%s' "$INPUT"
exit 0
fi
@@ -33,4 +55,4 @@ fi
# This is needed by scripts like observe.sh that behave differently for PreToolUse vs PostToolUse
HOOK_PHASE="${HOOK_ID%%:*}"
-printf '%s' "$INPUT" | "$SCRIPT_PATH" "$HOOK_PHASE"
+printf '%s' "$INPUT" | "$SCRIPT_CANON" "$HOOK_PHASE"
diff --git a/scripts/hooks/run-with-flags.js b/scripts/hooks/run-with-flags.js
index c24505adc..4b32bdbe8 100755
--- a/scripts/hooks/run-with-flags.js
+++ b/scripts/hooks/run-with-flags.js
@@ -227,7 +227,18 @@ async function main() {
// which would interfere with the parent process or cause double execution.
let hookModule;
const src = fs.readFileSync(scriptPath, 'utf8');
- const hasRunExport = /\bmodule\.exports\b/.test(src) && /\brun\b/.test(src);
+ // Gate require() on concrete export syntax, not a bare word match: the old
+ // /\bmodule\.exports\b/ && /\brun\b/ test fired on comments, strings, and
+ // unrelated properties, causing require() — and its module-scope side
+ // effects — to run for hooks that export no run(). Still lexical (no parser
+ // dependency), but requires an actual export assignment form.
+ const RUN_EXPORT_PATTERNS = [
+ /module\.exports\s*\.\s*run\s*=/,
+ /exports\s*\.\s*run\s*=/,
+ /module\.exports\s*=\s*\{[^}]*\brun\b/,
+ /module\.exports\s*=\s*(async\s+)?function\s+run\b/,
+ ];
+ const hasRunExport = RUN_EXPORT_PATTERNS.some(re => re.test(src));
if (hasRunExport) {
try {
diff --git a/scripts/hooks/session-end.js b/scripts/hooks/session-end.js
index 9709aa95a..5c31a8e0b 100644
--- a/scripts/hooks/session-end.js
+++ b/scripts/hooks/session-end.js
@@ -11,7 +11,7 @@
const path = require('path');
const fs = require('fs');
-const { getSessionsDir, getDateString, getTimeString, getSessionIdShort, sanitizeSessionId, getProjectName, ensureDir, readFile, writeFile, runCommand, stripAnsi, log } = require('../lib/utils');
+const { getSessionsDir, getDateString, getTimeString, getSessionIdShort, sanitizeSessionId, getProjectName, getRepoIdentity, ensureDir, readFile, writeFile, runCommand, stripAnsi, log } = require('../lib/utils');
const { generateSessionSummary, getContextRemainingPct, getContextThreshold } = require('../lib/llm-summary');
const SUMMARY_START_MARKER = '';
@@ -130,7 +130,8 @@ function getSessionMetadata() {
return {
project: getProjectName() || 'unknown',
branch: branchResult.success ? branchResult.output : 'unknown',
- worktree: process.cwd()
+ worktree: process.cwd(),
+ repo: getRepoIdentity()
};
}
@@ -145,16 +146,20 @@ function buildSessionHeader(today, currentTime, metadata, existingContent = '')
const date = extractHeaderField(existingContent, 'Date') || today;
const started = extractHeaderField(existingContent, 'Started') || currentTime;
- return [
+ const lines = [
heading,
`**Date:** ${date}`,
`**Started:** ${started}`,
`**Last Updated:** ${currentTime}`,
`**Project:** ${metadata.project}`,
`**Branch:** ${metadata.branch}`,
- `**Worktree:** ${metadata.worktree}`,
- ''
- ].join('\n');
+ `**Worktree:** ${metadata.worktree}`
+ ];
+ if (metadata.repo) {
+ lines.push(`**Repo:** ${metadata.repo}`);
+ }
+ lines.push('');
+ return lines.join('\n');
}
function mergeSessionHeader(content, today, currentTime, metadata) {
diff --git a/scripts/hooks/session-start.js b/scripts/hooks/session-start.js
index 63854aff1..9a859565a 100644
--- a/scripts/hooks/session-start.js
+++ b/scripts/hooks/session-start.js
@@ -14,6 +14,8 @@ const {
getSessionSearchDirs,
getLearnedSkillsDir,
getProjectName,
+ getRepoIdentity,
+ sameRepoIdentity,
findFiles,
ensureDir,
readFile,
@@ -254,6 +256,7 @@ function pruneExpiredSessions(searchDirs, retentionDays) {
* Session files written by session-end.js contain header fields like:
* **Project:** my-project
* **Worktree:** /path/to/project
+ * **Repo:** /path/to/main-worktree/.git
*
* This function reads each session file once, caching its content, and
* returns both the selected session object and its already-read content
@@ -261,11 +264,18 @@ function pruneExpiredSessions(searchDirs, retentionDays) {
*
* Priority (highest to lowest):
* 1. Exact worktree (cwd) match — most recent
- * 2. Same project name match for legacy sessions without Worktree metadata
- * 3. No injection when sessions belong to a different worktree/project
+ * 2. Repository identity match: the session was recorded in another
+ * worktree or subdirectory of the same repository. Identity is the
+ * main worktree's common git dir (issue #3160), taken from the
+ * recorded **Repo:** field or resolved from the recorded **Worktree:**
+ * path for older session files. Unrelated repositories never match.
+ * 3. Same project name match for legacy sessions without Worktree/Repo
+ * metadata
+ * 4. No injection when sessions belong to a different repository
*
* Sessions are already sorted newest-first, so the first match in each
- * category wins.
+ * category wins; the scan continues past repository and project matches so
+ * an exact worktree match always takes precedence.
*
* @param {Array