mirror of
https://github.com/affaan-m/ECC.git
synced 2026-11-23 16:25:30 +00:00
Merge pull request #3959 from affaan-m/stewardship/integration-20261116-b
chore: integrate reviewed contributor PRs (2026-11-16 batch B)
This commit is contained in:
115 files changed
+8963
-765
No files matched your search
@@ -9,6 +9,13 @@ updates:
|
||||
labels:
|
||||
- "dependencies"
|
||||
- "npm"
|
||||
ignore:
|
||||
# ECC supports Node 18. @opencode-ai/plugin newer than 1.4.x pulls
|
||||
# effect -> toml@4, which requires Node 20 and fails strict-engine installs.
|
||||
- dependency-name: "@opencode-ai/plugin"
|
||||
update-types:
|
||||
- "version-update:semver-minor"
|
||||
- "version-update:semver-major"
|
||||
groups:
|
||||
npm-minor-and-patch:
|
||||
patterns:
|
||||
|
||||
@@ -21,7 +21,10 @@
|
||||
* Hook Event Mapping (V1 key -> V2 registration):
|
||||
* - tool.execute.before -> ctx.tool.hook("execute.before")
|
||||
* - tool.execute.after -> ctx.tool.hook("execute.after")
|
||||
* - file.edited / file.watcher / session.* / todo.updated
|
||||
* (V2 tool id `shell` is matched as V1 `bash`)
|
||||
* - file.edited -> completed write/edit in execute.after
|
||||
* (V2 publishes no file.edited event)
|
||||
* - file.watcher / session.* / todo.updated
|
||||
* -> ctx.event.subscribe() filtered by type
|
||||
* - shell.env -> ctx.shell.hook("create.before")
|
||||
* - experimental.session.compacting -> ctx.session.hook("compaction")
|
||||
@@ -111,12 +114,31 @@ export const ECCHooksPluginDefinition = {
|
||||
const { hooks, worktreePath } = runtime
|
||||
|
||||
// Normalize a V2 tool-hook event into the V1 ToolInput shape so both
|
||||
// surfaces share one implementation.
|
||||
const toToolInput = (event: LooseRecord): ToolInput => ({
|
||||
tool: String(event.tool ?? event.name ?? ""),
|
||||
callID: event.callID ?? event.id,
|
||||
args: (event.input ?? event.args) as ToolArgs | undefined,
|
||||
})
|
||||
// surfaces share one implementation. OpenCode 2 renamed the V1 `bash`
|
||||
// tool to `shell` and passes `{ path }` to `write`/`edit`, so map both
|
||||
// back to the V1 names the shared runtime matches on.
|
||||
const toToolInput = (event: LooseRecord): ToolInput => {
|
||||
const rawTool = String(event.tool ?? event.name ?? "")
|
||||
const tool = rawTool === "shell" ? "bash" : rawTool
|
||||
let args = (event.input ?? event.args) as ToolArgs | undefined
|
||||
if (
|
||||
(tool === "write" || tool === "edit") &&
|
||||
args && typeof args === "object" &&
|
||||
typeof args.filePath !== "string" && typeof args.path === "string"
|
||||
) {
|
||||
args = { ...args, filePath: args.path }
|
||||
}
|
||||
return { tool, callID: event.callID ?? event.id, args }
|
||||
}
|
||||
|
||||
// OpenCode 2's public event stream has no `file.edited`, so V1's
|
||||
// post-edit hook (formatter, console.log warning, idle audit input) is
|
||||
// driven from the completed write/edit tool call instead.
|
||||
const editedPath = (input: ToolInput): string | null => {
|
||||
if (input.tool !== "write" && input.tool !== "edit") return null
|
||||
const p = input.args?.filePath ?? input.args?.path
|
||||
return typeof p === "string" && p.trim() ? p : null
|
||||
}
|
||||
|
||||
logStartup(directory)
|
||||
|
||||
@@ -147,15 +169,18 @@ export const ECCHooksPluginDefinition = {
|
||||
if (typeof ctx?.tool?.hook === "function") {
|
||||
registrations.push(await ctx.tool.hook("execute.before", safe("execute.before", (event: LooseRecord) => hooks["tool.execute.before"](toToolInput(event), {}))))
|
||||
registrations.push(
|
||||
await ctx.tool.hook("execute.after", safe("execute.after", (event: LooseRecord) =>
|
||||
await ctx.tool.hook("execute.after", safe("execute.after", async (event: LooseRecord) => {
|
||||
const input = toToolInput(event)
|
||||
// R2-1: hand the shared handler the tool output object directly. The
|
||||
// skill tracker reads error fields (isError/is_error/status/error) off
|
||||
// `tool_response` itself; a `{ result: … }` wrapper made failed skill
|
||||
// runs look like successes.
|
||||
hooks["tool.execute.after"](toToolInput(event), event.status === "error"
|
||||
await hooks["tool.execute.after"](input, event.status === "error"
|
||||
? { is_error: true }
|
||||
: event.result ?? event.output),
|
||||
)),
|
||||
: event.result ?? event.output)
|
||||
const edited = event.status === "error" ? null : editedPath(input)
|
||||
if (edited) await hooks["file.edited"]({ path: edited })
|
||||
})),
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -263,7 +263,7 @@ npx ecc-universal@2.2.3 doctor --target kimi
|
||||
|
||||
Do not use `npx ecc-install --profile minimal --target claude`: `ecc-install` is a binary name inside `ecc-universal`, not a separately published npm package.
|
||||
|
||||
ECC also ships advanced managed adapters for `cursor`, `antigravity`, `gemini`, `opencode`, `codebuddy`, `joycode`, `qwen`, `zed`, `hermes`, and `openclaw`. Those targets still use their documented `ecc install --target ...` paths until each adapter has passed the guided collision, update, repair, and uninstall lifecycle matrix. Neither wizard silently installs into every detected harness.
|
||||
ECC also ships advanced managed adapters for `cursor`, `antigravity`, `antigravity-home`, `gemini`, `opencode`, `codebuddy`, `joycode`, `qwen`, `zed`, `hermes`, `openclaw`, and `mistral-vibe`. Those targets still use their documented `ecc install --target ...` paths until each adapter has passed the guided collision, update, repair, and uninstall lifecycle matrix. Neither wizard silently installs into every detected harness.
|
||||
|
||||
### Pick one path only (per harness)
|
||||
|
||||
@@ -413,7 +413,7 @@ the [.qoder-plugin notes](.qoder-plugin/README.md) for the exact boundary.
|
||||
### Other agents and editors
|
||||
|
||||
<details>
|
||||
<summary><strong>Cursor, OpenCode, Gemini, Zed, Antigravity, Qwen, Hermes, OpenClaw, Kimi, CodeBuddy, JoyCode, Copilot</strong></summary>
|
||||
<summary><strong>Cursor, OpenCode, Gemini, Zed, Antigravity, Qwen, Hermes, OpenClaw, Kimi, Mistral Vibe, CodeBuddy, JoyCode, Copilot</strong></summary>
|
||||
|
||||
Clone ECC once, then choose the target that matches your harness:
|
||||
|
||||
@@ -428,11 +428,13 @@ cd ECC
|
||||
| OpenCode | `npm install && npm run build:opencode && ./install.sh --profile full --target opencode --enable-hooks` | Builds the plugin payload before the full install |
|
||||
| Gemini CLI | `./install.sh --profile minimal --target gemini` | Project-local `.gemini/` config |
|
||||
| Zed | `./install.sh --profile minimal --target zed` | Project-local `.zed/` adapter |
|
||||
| Antigravity | `./install.sh --profile minimal --target antigravity` | See the [Antigravity guide](docs/ANTIGRAVITY-GUIDE.md) |
|
||||
| Antigravity (Global Plugin) | `./install.sh --target antigravity-home --profile core --enable-hooks` | Experimental global plugin (`~/.gemini/config/plugins/ecc/`) with lifecycle hooks · [Guide](docs/ANTIGRAVITY-GUIDE.md) |
|
||||
| Antigravity (Project-Local) | `./install.sh --target antigravity --profile minimal` | Project-local `.agents/` adapter · [Guide](docs/ANTIGRAVITY-GUIDE.md) |
|
||||
| Qwen CLI | `./install.sh --profile minimal --target qwen` | See the [Qwen guide](docs/QWEN-GUIDE.md) |
|
||||
| Hermes | `./install.sh --profile minimal --target hermes` | See the [Hermes setup guide](docs/HERMES-SETUP.md) |
|
||||
| OpenClaw | `./install.sh --profile minimal --target openclaw` | Managed home-directory install |
|
||||
| Kimi Code CLI | `./install.sh --profile minimal --target kimi` | Project-local `.kimi-code/` install · [Get Kimi Code](https://www.kimi.ai/code?aff=ecc) |
|
||||
| Mistral Vibe | `./install.sh --target mistral-vibe --skills tdd-workflow` | Project-local `.vibe/skills/` install · [Mistral Vibe guide](docs/MISTRAL-VIBE-GUIDE.md) |
|
||||
| CodeBuddy | `./install.sh --profile minimal --target codebuddy` | Project-local `.codebuddy/` install |
|
||||
| JoyCode | `./install.sh --profile minimal --target joycode` | Project-local `.joycode/` install |
|
||||
| GitHub Copilot | `./install.sh --profile full --target copilot` | Installs skills to `.github/skills/` and agents to `.github/agents/` for Copilot CLI |
|
||||
@@ -1330,12 +1332,13 @@ Treat `stable`, `beta`, `experimental`, and `instruction-only` below as capabili
|
||||
|---|---|---|---|
|
||||
| Claude Code | Stable primary | Plugin or selective installer | The plugin advertises the installed catalog to the model; use a selective/manual profile when context footprint matters. Optional shell-backed skills are not portable to every OS. |
|
||||
| Codex | Supported native plugin | Codex marketplace plugin or repo config | Native hooks require an explicit trust decision and do not use Claude's hook profiles. The legacy sync is compatibility-only. |
|
||||
| Antigravity | Experimental native plugin adapter | Antigravity 2.0/IDE plugin (`~/.gemini/config/plugins/ecc`) or project `.agents/` | Profile-gated lifecycle hooks, rules, workflows, skills, and memory MCP. CLI 1.3.5 validates local import; authenticated native tool and Stop execution remain unverified. |
|
||||
| Qoder | Supported native plugin | Local plugin directory in Qoder CLI or ZIP upload in Qoder IDE | Loads the canonical skills, agents, commands, and MCP config; only the reviewed SessionStart hook is enabled, and Node.js 18+ must be on the non-interactive PATH. |
|
||||
| Cursor | Beta project adapter | Selective installer into `.cursor/` | Agent discovery varies by Cursor build; hook events use profile-gated dispatchers, but full Claude feature parity is not claimed. |
|
||||
| OpenCode | Beta built plugin | Build plugin, then selective installer | ECC ships a subset of the catalog; connect a provider and select a model in OpenCode ([#2617](https://github.com/affaan-m/ECC/issues/2617)). |
|
||||
| GitHub Copilot Chat | Instruction-only | Checked-in instructions and prompt files | ECC hooks are not adapted. |
|
||||
| GitHub Copilot CLI | Beta project adapter | `--target copilot` places skills, adapted agents, and converted rules in `.github/` | ECC hooks and command shims are not installed by this target. |
|
||||
| Gemini, Zed, Antigravity, Qwen, Hermes, OpenClaw, Kimi, CodeBuddy, JoyCode | Experimental/minimal adapters | Harness-specific selective target | File placement and instruction portability are tested; full Claude feature parity is not claimed. |
|
||||
| Gemini, Zed, Qwen, Hermes, OpenClaw, Kimi, Mistral Vibe, CodeBuddy, JoyCode | Experimental/minimal adapters | Harness-specific selective target | File placement and instruction portability are tested; full Claude feature parity is not claimed. |
|
||||
|
||||
<details>
|
||||
<summary><strong>Package manager detection</strong></summary>
|
||||
|
||||
@@ -155,12 +155,107 @@ node "$EccRoot\scripts\uninstall.js" --target antigravity --dry-run
|
||||
- Confirm the files are under `.agents/workflows/`.
|
||||
- Invoke a workflow with `/<workflow-name>` after restarting Antigravity.
|
||||
|
||||
## Native Plugin and Global Installation (`antigravity-home`)
|
||||
|
||||
Antigravity supports global plugins located in `~/.gemini/config/plugins/<name>/`. Installing ECC as a native Antigravity plugin enables:
|
||||
|
||||
1. **Global Scope**: ECC rules, skills, agents, workflows, and memory MCP are active across all projects automatically, without requiring a `.agents/` folder in every repository.
|
||||
2. **Lifecycle Hooks (`hooks.json`)**: Handlers for `PreToolUse` command and file guards, `PostToolUse` edit tracking, and `Stop` formatting and diagnostics using Antigravity's protojson protocol (`{ decision, reason }`).
|
||||
3. **Shared Memory Vault (`mcp_config.json`)**: Direct integration with `ecc-memory-mcp` across all Antigravity sessions.
|
||||
4. **Native Plugin Manifest (`plugin.json`)**: Declares the ECC plugin metadata.
|
||||
|
||||
### Installing Globally
|
||||
|
||||
```bash
|
||||
# Using install.sh from source
|
||||
"$ECC_ROOT/install.sh" --target antigravity-home --profile core --enable-hooks
|
||||
```
|
||||
|
||||
PowerShell:
|
||||
|
||||
```powershell
|
||||
& "$EccRoot\install.ps1" --target antigravity-home --profile core --enable-hooks
|
||||
```
|
||||
|
||||
The installer copies the memory server and its runtime dependencies into the
|
||||
managed target. Only ECC memory is included in the generated MCP configuration;
|
||||
repository `.mcp.json` commands are not imported automatically. Set
|
||||
`ECC_DISABLED_MCPS=ecc-memory` during installation to omit that server.
|
||||
Existing MCP entries are preserved on upgrades, including servers generated by
|
||||
older ECC versions. Review `mcp_config.json` and remove any unwanted existing
|
||||
entries explicitly; installation does not delete user configuration.
|
||||
Generated hook and MCP commands use absolute installed paths,
|
||||
so they also work when Antigravity runs from another workspace.
|
||||
|
||||
Project-local hooks use the same runtime; select `--profile core --enable-hooks`
|
||||
with `--target antigravity`. Use `--no-hooks` to omit automatic hooks.
|
||||
On reinstall, `--no-hooks` also deactivates previously installed ECC hooks,
|
||||
including legacy bridges. Other hook namespaces are preserved. If the managed
|
||||
`ecc-guard` registration was customized, installation refuses the change;
|
||||
review that customization before retrying.
|
||||
Choose a hook profile at installation with the existing environment setting, for
|
||||
example `ECC_HOOK_PROFILE=minimal "$ECC_ROOT/install.sh" --target antigravity-home --profile core --enable-hooks`.
|
||||
The installer retains it in managed `ecc/setup.json` for runtime execution.
|
||||
`ECC_HOOK_PROFILE` overrides that profile; `ECC_DISABLED_HOOKS` disables individual
|
||||
hook IDs, and `ECC_DRY_RUN=1` suppresses hook execution. These controls also apply
|
||||
to the Antigravity bridge.
|
||||
|
||||
### Global Plugin Structure
|
||||
|
||||
```text
|
||||
~/.gemini/config/
|
||||
├── workflows/ # Global slash workflows
|
||||
└── plugins/ecc/
|
||||
├── plugin.json # Antigravity plugin manifest
|
||||
├── hooks.json # PreToolUse, PostToolUse, and Stop hooks
|
||||
├── mcp_config.json # Shared ECC Memory Vault MCP server
|
||||
├── ecc/setup.json # Managed hook enable/profile configuration
|
||||
├── rules/ # Rules applied to all workspaces
|
||||
├── skills/ # Global Agent Skills
|
||||
├── scripts/ # Hook bridge and memory runtime
|
||||
└── node_modules/ # Memory server dependencies
|
||||
```
|
||||
|
||||
### Native validation and limits
|
||||
|
||||
Run the optional native check from the ECC source checkout:
|
||||
|
||||
```bash
|
||||
node tests/scripts/antigravity-native-plugin.test.js
|
||||
```
|
||||
|
||||
The test requires an already installed **Antigravity CLI 1.3.5** and skips with an
|
||||
explicit message if that version is unavailable. It does not download the CLI.
|
||||
It installs ECC into one temporary home, runs `agy plugin validate`, imports the
|
||||
local plugin into a separate disposable CLI home with `agy plugin install`, and
|
||||
checks `agy plugin list --json`.
|
||||
Every CLI subprocess uses disposable home and configuration directories without
|
||||
inheriting authentication credentials. The test makes no model requests.
|
||||
|
||||
This validates the CLI's local plugin importer and component registration.
|
||||
CLI 1.2.9 does not list a manually placed `~/.gemini/config/plugins/ecc` plugin
|
||||
until explicitly imported; its CLI staging location differs from the Antigravity
|
||||
2.0 and IDE global location. Importing directly from the same home plugin directory
|
||||
fails in CLI 1.2.9 because its importer attempts to copy onto the source directory.
|
||||
The test uses separate install and loader homes to exercise the importer without
|
||||
that collision; this does not establish in-place CLI activation of the home target.
|
||||
|
||||
The CLI exposes no standalone tool-event or Stop-event runner. The existing
|
||||
bridge tests check allowed and denied tool payloads and Stop behavior directly;
|
||||
they do **not** establish native loader execution. Automatic IDE discovery,
|
||||
allowed and denied tool execution, and Stop execution still require a real
|
||||
Antigravity session. In Settings > Customizations, verify ECC appears, then use
|
||||
a disposable workspace to verify an ordinary command proceeds, a destructive
|
||||
command is denied before execution, and an edit triggers the expected Stop
|
||||
formatting or diagnostics. Never use valuable files for the denial check.
|
||||
|
||||
## Official Antigravity references
|
||||
|
||||
- [Skills](https://antigravity.google/docs/skills)
|
||||
- [Rules and workflows](https://antigravity.google/docs/rules-workflows)
|
||||
- [Custom agents and subagents](https://antigravity.google/docs/subagents)
|
||||
- [Plugins](https://antigravity.google/docs/plugins)
|
||||
- [Lifecycle hooks](https://antigravity.google/docs/hooks)
|
||||
|
||||
See [CONTRIBUTING.md](../CONTRIBUTING.md) for ECC contribution guidance and
|
||||
[SELECTIVE-INSTALL-ARCHITECTURE.md](SELECTIVE-INSTALL-ARCHITECTURE.md) for the
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
# Mistral Vibe integration
|
||||
|
||||
ECC provides a project-local, skills-first integration for Mistral Vibe. The
|
||||
contract in this guide is verified against **Mistral Vibe v2.25.3** and
|
||||
**Mistral Vibe v3.1.2**.
|
||||
|
||||
## Install a skill
|
||||
|
||||
Run the installer from the project that Vibe will open. Keep the ECC source
|
||||
checkout separate so managed files are written to the target project:
|
||||
|
||||
```bash
|
||||
ECC_ROOT="/absolute/path/to/ECC"
|
||||
"$ECC_ROOT/install.sh" --target mistral-vibe --skills tdd-workflow
|
||||
```
|
||||
|
||||
After a release containing this target is published, verify the registry
|
||||
version and pin that released version:
|
||||
|
||||
```bash
|
||||
npm view ecc-universal version
|
||||
npx ecc-universal@<released-version> install --target mistral-vibe --skills tdd-workflow
|
||||
```
|
||||
|
||||
Install multiple skills with a comma-separated list:
|
||||
|
||||
```bash
|
||||
"$ECC_ROOT/install.sh" --target mistral-vibe --skills tdd-workflow,security-review
|
||||
```
|
||||
|
||||
ECC writes each selected skill to `.vibe/skills/<name>/`. Vibe discovers this
|
||||
directory natively for trusted projects and loads each `SKILL.md` through its
|
||||
Agent Skills implementation. ECC records only its managed files in
|
||||
`.vibe/ecc-install-state.json`; an existing user-owned skill file is preserved.
|
||||
|
||||
## Verify and maintain the install
|
||||
|
||||
```bash
|
||||
node "$ECC_ROOT/scripts/list-installed.js" --target mistral-vibe
|
||||
node "$ECC_ROOT/scripts/doctor.js" --target mistral-vibe
|
||||
node "$ECC_ROOT/scripts/repair.js" --target mistral-vibe
|
||||
node "$ECC_ROOT/scripts/uninstall.js" --target mistral-vibe
|
||||
```
|
||||
|
||||
Use `--dry-run --json` with install, repair, or uninstall to inspect changes
|
||||
before writing them. Repair restores missing or drifted ECC-managed skill files.
|
||||
Uninstall removes unchanged managed files, but preserves modified files and the
|
||||
install-state so they can be reviewed.
|
||||
|
||||
## Compatibility boundary
|
||||
|
||||
This first integration deliberately installs Agent Skills only. It does not
|
||||
configure Vibe model/provider credentials, `.vibe/config.toml`, MCP servers, or
|
||||
`.vibe/hooks.toml`. It also does not translate ECC's Claude-oriented agent
|
||||
Markdown into `.vibe/agents/*.toml`, and it does not claim that ECC command or
|
||||
rule directories are native Vibe surfaces.
|
||||
|
||||
Vibe also discovers project-level `.agents/skills/` and root `AGENTS.md`, but
|
||||
ECC uses `.vibe/skills/` so every managed write and lifecycle action stays
|
||||
inside one project-local ownership boundary.
|
||||
|
||||
Official references:
|
||||
|
||||
- [Mistral Vibe](https://github.com/mistralai/mistral-vibe)
|
||||
- [Agent Skills specification](https://agentskills.io/specification)
|
||||
@@ -23,6 +23,11 @@ working examples, reference-set gaps, and validation commands before a skill
|
||||
amendment can be promoted. A deep-analyzer evidence scenario requires analyzer
|
||||
corpus cases, expected-output comparisons, and risk-taxonomy proof before
|
||||
repository or commit-analysis behavior can change.
|
||||
In an orchestration-efficiency evidence scenario, single-agent controls must be
|
||||
matched, and aggregate controller, worker, verifier, and retry cost, accepted
|
||||
quality, coordination costs, and sequential paired replications are required
|
||||
before parallelism is called faster or cheaper. Per-pair deltas that are
|
||||
mixed-sign or unavailable make the result inconclusive and block the claim.
|
||||
|
||||
## Reference Pressure
|
||||
|
||||
@@ -122,6 +127,12 @@ Current corpus:
|
||||
- `deep-analyzer-evidence`: requires maintained analyzer corpus cases,
|
||||
expected-output comparisons, representative repository/commit histories, and
|
||||
regression commands before deep-analysis behavior can be promoted.
|
||||
- `orchestration-efficiency-evidence`: requires dependency and ownership plans,
|
||||
matched single-agent controls, common acceptance gates, aggregate worker
|
||||
costs, retained failures and coordination overhead, and repeated sequential
|
||||
pairs before an orchestration-efficiency recommendation can be promoted.
|
||||
Per-pair quality, time, and cost deltas must keep one sign across every pair;
|
||||
otherwise the result is `inconclusive` and no candidate is promoted.
|
||||
|
||||
- `connector-diagnostics-gap`: inventories an already-used connector, separates
|
||||
observed gaps from unavailable research, and requires evidence before a new
|
||||
|
||||
@@ -81,7 +81,7 @@ metadata:
|
||||
## 集成
|
||||
|
||||
可与任意浏览器 MCP 配合:
|
||||
- `mChild__claude-in-chrome__*` 工具(推荐,直接使用你的真实 Chrome)
|
||||
- `mcp__claude-in-chrome__*` 工具(推荐,直接使用你的真实 Chrome)
|
||||
- 通过 `mcp__browserbase__*` 使用 Playwright
|
||||
- 直接运行 Puppeteer 脚本
|
||||
|
||||
|
||||
Generated
+11
-11
@@ -162,9 +162,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "block-buffer"
|
||||
version = "0.12.0"
|
||||
version = "0.12.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cdd35008169921d80bc60d3d0ab416eecb028c4cd653352907921d95084790be"
|
||||
checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa"
|
||||
dependencies = [
|
||||
"hybrid-array",
|
||||
]
|
||||
@@ -538,7 +538,7 @@ version = "0.11.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"
|
||||
dependencies = [
|
||||
"block-buffer 0.12.0",
|
||||
"block-buffer 0.12.1",
|
||||
"const-oid",
|
||||
"crypto-common 0.2.2",
|
||||
]
|
||||
@@ -1152,9 +1152,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "libsqlite3-sys"
|
||||
version = "0.38.2"
|
||||
version = "0.39.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f1d20bef17f513b9b3004532233187769cd072d790971f4e4da0e346eb6401e8"
|
||||
checksum = "14a5f01b87b92705d07b433c06f96cbc764637d81a0bffb5734ce17cf0f9a2b3"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"pkg-config",
|
||||
@@ -1834,9 +1834,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rusqlite"
|
||||
version = "0.40.2"
|
||||
version = "0.41.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "23f2a97da3e3873c73cb2a2e71b35c40ff95e0b1eefa8d72d8499a6928c3b5b3"
|
||||
checksum = "da9bba6f3506135e120a6586df05be18b48d18896600646a4bec8f993d91a594"
|
||||
dependencies = [
|
||||
"bitflags 2.13.0",
|
||||
"fallible-iterator",
|
||||
@@ -1858,9 +1858,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustix"
|
||||
version = "1.1.4"
|
||||
version = "1.1.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190"
|
||||
checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa"
|
||||
dependencies = [
|
||||
"bitflags 2.13.0",
|
||||
"errno",
|
||||
@@ -1895,9 +1895,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustls-webpki"
|
||||
version = "0.103.15"
|
||||
version = "0.103.16"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2"
|
||||
checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281"
|
||||
dependencies = [
|
||||
"ring",
|
||||
"rustls-pki-types",
|
||||
|
||||
+1
-1
@@ -20,7 +20,7 @@ crossterm = "0.29"
|
||||
tokio = { version = "1", features = ["full"] }
|
||||
|
||||
# State store
|
||||
rusqlite = { version = "0.40", features = ["bundled"] }
|
||||
rusqlite = { version = "0.41", features = ["bundled"] }
|
||||
|
||||
# Git integration
|
||||
git2 = { version = "0.21", features = ["ssh"] }
|
||||
|
||||
@@ -3437,9 +3437,12 @@ fn read_package_manager_from_package_json(path: &Path) -> Option<&'static str> {
|
||||
fn detect_package_manager_from_lockfile(working_dir: &Path) -> Option<&'static str> {
|
||||
[
|
||||
("pnpm", "pnpm-lock.yaml"),
|
||||
// Bun 1.2+ writes the text bun.lock by default; keep the legacy binary lockfile.
|
||||
("bun", "bun.lock"),
|
||||
("bun", "bun.lockb"),
|
||||
("yarn", "yarn.lock"),
|
||||
("npm", "package-lock.json"),
|
||||
("npm", "npm-shrinkwrap.json"),
|
||||
]
|
||||
.into_iter()
|
||||
.find_map(|(package_manager, lockfile)| {
|
||||
@@ -4859,6 +4862,26 @@ mod tests {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detect_package_manager_from_lockfile_matches_node_lockfile_aliases() -> Result<()> {
|
||||
for (lockfile, expected) in [
|
||||
("bun.lock", "bun"),
|
||||
("bun.lockb", "bun"),
|
||||
("npm-shrinkwrap.json", "npm"),
|
||||
] {
|
||||
let tempdir = TestDir::new("manager-package-manager-lockfile-alias")?;
|
||||
let repo_root = tempdir.path().join("repo");
|
||||
fs::create_dir_all(&repo_root)?;
|
||||
fs::write(repo_root.join(lockfile), "lockfile\n")?;
|
||||
assert_eq!(
|
||||
detect_package_manager_from_lockfile(&repo_root),
|
||||
Some(expected),
|
||||
"{lockfile} should select {expected}"
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_agent_command_prefers_project_package_manager_config_over_lockfile() -> Result<()> {
|
||||
let tempdir = TestDir::new("manager-package-manager-config")?;
|
||||
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
# Orchestration Efficiency Evidence Playbook
|
||||
|
||||
Candidate id: `controlled-paired-orchestration-evaluation`
|
||||
|
||||
Use this playbook before recommending multiple agents for a task class or
|
||||
claiming an orchestrated workflow is faster, cheaper, or more reliable than one
|
||||
agent.
|
||||
|
||||
## Accepted Path
|
||||
|
||||
1. Define the task, acceptance evaluator, and observable evidence requirements.
|
||||
2. Draw the dependency graph and name exclusive write ownership. If workers
|
||||
need the same file or an unsettled interface, keep that work sequential.
|
||||
3. Freeze the controlled fields for both variants:
|
||||
- starting revision and task text;
|
||||
- model and reasoning effort;
|
||||
- permissions and tools;
|
||||
- time limit and machine-load policy;
|
||||
- acceptance evaluator and evidence format.
|
||||
4. Run one `single_agent` candidate and one `orchestrated` candidate
|
||||
sequentially. Alternate run order across later pairs.
|
||||
5. Apply the same evaluator to every attempt. Keep failures in the dataset.
|
||||
6. Record per candidate:
|
||||
- acceptance and evidence completeness;
|
||||
- elapsed time;
|
||||
- total tokens or cost across controller, every worker, the verifier, and
|
||||
retries;
|
||||
- worker count and ownership;
|
||||
- conflicts, integration rework, retries, and human corrections.
|
||||
7. Write `unavailable` for telemetry the harness does not expose. Never estimate
|
||||
missing totals.
|
||||
8. Repeat at least three fresh pairs before recommending a task-class boundary.
|
||||
Report raw receipts before interpretation.
|
||||
9. Compute each pair's quality, time, and cost delta (orchestrated minus
|
||||
single agent) from the retained attempts, then apply the pair consistency
|
||||
rule below.
|
||||
|
||||
## Pair Consistency Rule
|
||||
|
||||
The machine-readable rule is `pair_consistency_rule` in `scenario.json`.
|
||||
|
||||
- A metric has a direction only when every pair reports an available delta and
|
||||
all deltas share one nonzero sign, or all are zero (`no_difference`).
|
||||
- Never average pair deltas. With three pairs, one reversed pair means the
|
||||
metric is `inconclusive`, even when the mean points one way.
|
||||
- The result is `consistent` only when at least three pairs ran, both run orders
|
||||
occur, and every metric has a direction. Otherwise it is `inconclusive`.
|
||||
- An `inconclusive` result blocks every task-class claim and promotes no
|
||||
candidate. Keep the raw attempts and run more fresh pairs if the decision
|
||||
still matters.
|
||||
- A `consistent` claim names its task class and every metric direction,
|
||||
including higher cost or lower quality.
|
||||
|
||||
`pairs-sign-consistent.json` shows an accepted, task-class-scoped claim.
|
||||
`pairs-mixed-sign.json` shows a reversed time delta that blocks the claim. Both
|
||||
use synthetic, illustrative attempts rather than executed runs.
|
||||
|
||||
## Rejected Path
|
||||
|
||||
Do not infer efficiency because workers ran in parallel, the controller context
|
||||
looked smaller, or one orchestrated candidate finished successfully.
|
||||
|
||||
Do not compare candidates with different prompts, revisions, models, tools,
|
||||
permissions, time limits, evaluators, or machine load.
|
||||
|
||||
Do not report controller-only tokens, exclude failed attempts, or hide merge
|
||||
conflicts and integration work outside the result.
|
||||
|
||||
Do not publish a general claim from one pair, overlapping variants, fixed run
|
||||
order, or unavailable aggregate telemetry.
|
||||
|
||||
Do not average opposite-sign or unavailable pair deltas into a recommendation.
|
||||
|
||||
## Minimum Validation
|
||||
|
||||
- `node tests/lib/orchestration-session.test.js`
|
||||
- Task-specific acceptance evaluator for every candidate
|
||||
- Raw run receipts containing all controlled fields and coordination costs
|
||||
- `git diff --check`
|
||||
- At least three sequential pairs with alternated order before a general claim
|
||||
- Per-pair quality, time, and cost deltas with a `consistent` result before any
|
||||
task-class claim
|
||||
- `node tests/docs/evaluator-rag-prototype.test.js`
|
||||
|
||||
Record the evidence source and attribution when an external experiment informs
|
||||
the scenario. Keep publication, agent launch, candidate edits, and repository
|
||||
mutation outside this read-only evaluator pass.
|
||||
+180
@@ -0,0 +1,180 @@
|
||||
{
|
||||
"schema_version": "ecc.evaluator-rag.verifier.v1",
|
||||
"scenario_id": "orchestration-efficiency-evidence",
|
||||
"run_id": "illustrative-mixed-sign-pairs",
|
||||
"read_only": true,
|
||||
"illustrative": true,
|
||||
"evaluation_status": "illustrative_synthetic_attempts_not_executed_runs",
|
||||
"task_class": "parallel repairs across shared test helpers",
|
||||
"raw_attempts": [
|
||||
{
|
||||
"attempt_id": "pair-1-single_agent",
|
||||
"pair": 1,
|
||||
"variant": "single_agent",
|
||||
"run_order": 1,
|
||||
"accepted": true,
|
||||
"quality_score": 1,
|
||||
"elapsed_ms": 900000,
|
||||
"cost_breakdown_usd": {
|
||||
"controller": 1.2,
|
||||
"workers": 0,
|
||||
"verifier": 0.1,
|
||||
"retries": 0
|
||||
},
|
||||
"total_cost_usd": 1.3,
|
||||
"worker_count": 1,
|
||||
"conflicts": 0,
|
||||
"integration_rework": 0,
|
||||
"human_corrections": 0
|
||||
},
|
||||
{
|
||||
"attempt_id": "pair-1-orchestrated",
|
||||
"pair": 1,
|
||||
"variant": "orchestrated",
|
||||
"run_order": 2,
|
||||
"accepted": true,
|
||||
"quality_score": 1,
|
||||
"elapsed_ms": 660000,
|
||||
"cost_breakdown_usd": {
|
||||
"controller": 0.4,
|
||||
"workers": 1.3,
|
||||
"verifier": 0.1,
|
||||
"retries": 0
|
||||
},
|
||||
"total_cost_usd": 1.8,
|
||||
"worker_count": 3,
|
||||
"conflicts": 0,
|
||||
"integration_rework": 0,
|
||||
"human_corrections": 0
|
||||
},
|
||||
{
|
||||
"attempt_id": "pair-2-orchestrated",
|
||||
"pair": 2,
|
||||
"variant": "orchestrated",
|
||||
"run_order": 1,
|
||||
"accepted": true,
|
||||
"quality_score": 1,
|
||||
"elapsed_ms": 1080000,
|
||||
"cost_breakdown_usd": {
|
||||
"controller": 0.45,
|
||||
"workers": 1.5,
|
||||
"verifier": 0.1,
|
||||
"retries": 0.35
|
||||
},
|
||||
"total_cost_usd": 2.4,
|
||||
"worker_count": 3,
|
||||
"conflicts": 1,
|
||||
"integration_rework": 1,
|
||||
"human_corrections": 0
|
||||
},
|
||||
{
|
||||
"attempt_id": "pair-2-single_agent",
|
||||
"pair": 2,
|
||||
"variant": "single_agent",
|
||||
"run_order": 2,
|
||||
"accepted": true,
|
||||
"quality_score": 1,
|
||||
"elapsed_ms": 900000,
|
||||
"cost_breakdown_usd": {
|
||||
"controller": 1.25,
|
||||
"workers": 0,
|
||||
"verifier": 0.1,
|
||||
"retries": 0
|
||||
},
|
||||
"total_cost_usd": 1.35,
|
||||
"worker_count": 1,
|
||||
"conflicts": 0,
|
||||
"integration_rework": 0,
|
||||
"human_corrections": 0
|
||||
},
|
||||
{
|
||||
"attempt_id": "pair-3-single_agent",
|
||||
"pair": 3,
|
||||
"variant": "single_agent",
|
||||
"run_order": 1,
|
||||
"accepted": true,
|
||||
"quality_score": 1,
|
||||
"elapsed_ms": 960000,
|
||||
"cost_breakdown_usd": {
|
||||
"controller": 1.3,
|
||||
"workers": 0,
|
||||
"verifier": 0.1,
|
||||
"retries": 0
|
||||
},
|
||||
"total_cost_usd": 1.4,
|
||||
"worker_count": 1,
|
||||
"conflicts": 0,
|
||||
"integration_rework": 0,
|
||||
"human_corrections": 0
|
||||
},
|
||||
{
|
||||
"attempt_id": "pair-3-orchestrated",
|
||||
"pair": 3,
|
||||
"variant": "orchestrated",
|
||||
"run_order": 2,
|
||||
"accepted": true,
|
||||
"quality_score": 1,
|
||||
"elapsed_ms": 900000,
|
||||
"cost_breakdown_usd": {
|
||||
"controller": 0.4,
|
||||
"workers": 1.2,
|
||||
"verifier": 0.1,
|
||||
"retries": 0
|
||||
},
|
||||
"total_cost_usd": 1.7,
|
||||
"worker_count": 3,
|
||||
"conflicts": 0,
|
||||
"integration_rework": 0,
|
||||
"human_corrections": 0
|
||||
}
|
||||
],
|
||||
"pair_deltas": [
|
||||
{
|
||||
"pair": 1,
|
||||
"order": "single_agent_first",
|
||||
"quality_delta": 0,
|
||||
"time_delta_ms": -240000,
|
||||
"cost_delta_usd": 0.5
|
||||
},
|
||||
{
|
||||
"pair": 2,
|
||||
"order": "orchestrated_first",
|
||||
"quality_delta": 0,
|
||||
"time_delta_ms": 180000,
|
||||
"cost_delta_usd": 1.05
|
||||
},
|
||||
{
|
||||
"pair": 3,
|
||||
"order": "single_agent_first",
|
||||
"quality_delta": 0,
|
||||
"time_delta_ms": -60000,
|
||||
"cost_delta_usd": 0.3
|
||||
}
|
||||
],
|
||||
"metric_directions": {
|
||||
"quality": "no_difference",
|
||||
"time": "inconclusive",
|
||||
"cost": "single_agent_better"
|
||||
},
|
||||
"result": "inconclusive",
|
||||
"rejected_aggregate": {
|
||||
"statistic": "mean_time_delta_ms",
|
||||
"value": -40000,
|
||||
"why_rejected": "a mean of opposite-sign pair deltas hides that one of three pairs reversed direction"
|
||||
},
|
||||
"candidates": [
|
||||
{
|
||||
"candidate_id": "task-class-direction-claim",
|
||||
"decision": "not_promoted",
|
||||
"claim": null,
|
||||
"reasons": [
|
||||
"pair 2 reverses the time direction of pairs 1 and 3, so time has no direction",
|
||||
"averaging the three time deltas would suggest orchestration is faster, which the pair evidence does not support",
|
||||
"pair 2 retains its edit conflict, integration rework, and retry cost instead of dropping it as an outlier",
|
||||
"an inconclusive result blocks any task-class claim, including the cost direction that is consistent"
|
||||
],
|
||||
"rollback": "Make no claim; keep every raw attempt and run more fresh alternated pairs if the decision still matters."
|
||||
}
|
||||
],
|
||||
"promoted_candidate_id": null
|
||||
}
|
||||
+175
@@ -0,0 +1,175 @@
|
||||
{
|
||||
"schema_version": "ecc.evaluator-rag.verifier.v1",
|
||||
"scenario_id": "orchestration-efficiency-evidence",
|
||||
"run_id": "illustrative-sign-consistent-pairs",
|
||||
"read_only": true,
|
||||
"illustrative": true,
|
||||
"evaluation_status": "illustrative_synthetic_attempts_not_executed_runs",
|
||||
"task_class": "independent documentation updates with disjoint file ownership",
|
||||
"raw_attempts": [
|
||||
{
|
||||
"attempt_id": "pair-1-single_agent",
|
||||
"pair": 1,
|
||||
"variant": "single_agent",
|
||||
"run_order": 1,
|
||||
"accepted": true,
|
||||
"quality_score": 1,
|
||||
"elapsed_ms": 1200000,
|
||||
"cost_breakdown_usd": {
|
||||
"controller": 1.5,
|
||||
"workers": 0,
|
||||
"verifier": 0.1,
|
||||
"retries": 0
|
||||
},
|
||||
"total_cost_usd": 1.6,
|
||||
"worker_count": 1,
|
||||
"conflicts": 0,
|
||||
"integration_rework": 0,
|
||||
"human_corrections": 0
|
||||
},
|
||||
{
|
||||
"attempt_id": "pair-1-orchestrated",
|
||||
"pair": 1,
|
||||
"variant": "orchestrated",
|
||||
"run_order": 2,
|
||||
"accepted": true,
|
||||
"quality_score": 1,
|
||||
"elapsed_ms": 720000,
|
||||
"cost_breakdown_usd": {
|
||||
"controller": 0.5,
|
||||
"workers": 1.4,
|
||||
"verifier": 0.1,
|
||||
"retries": 0
|
||||
},
|
||||
"total_cost_usd": 2.0,
|
||||
"worker_count": 3,
|
||||
"conflicts": 0,
|
||||
"integration_rework": 0,
|
||||
"human_corrections": 0
|
||||
},
|
||||
{
|
||||
"attempt_id": "pair-2-orchestrated",
|
||||
"pair": 2,
|
||||
"variant": "orchestrated",
|
||||
"run_order": 1,
|
||||
"accepted": true,
|
||||
"quality_score": 1,
|
||||
"elapsed_ms": 780000,
|
||||
"cost_breakdown_usd": {
|
||||
"controller": 0.5,
|
||||
"workers": 1.5,
|
||||
"verifier": 0.1,
|
||||
"retries": 0
|
||||
},
|
||||
"total_cost_usd": 2.1,
|
||||
"worker_count": 3,
|
||||
"conflicts": 0,
|
||||
"integration_rework": 0,
|
||||
"human_corrections": 0
|
||||
},
|
||||
{
|
||||
"attempt_id": "pair-2-single_agent",
|
||||
"pair": 2,
|
||||
"variant": "single_agent",
|
||||
"run_order": 2,
|
||||
"accepted": true,
|
||||
"quality_score": 1,
|
||||
"elapsed_ms": 1140000,
|
||||
"cost_breakdown_usd": {
|
||||
"controller": 1.45,
|
||||
"workers": 0,
|
||||
"verifier": 0.1,
|
||||
"retries": 0
|
||||
},
|
||||
"total_cost_usd": 1.55,
|
||||
"worker_count": 1,
|
||||
"conflicts": 0,
|
||||
"integration_rework": 0,
|
||||
"human_corrections": 0
|
||||
},
|
||||
{
|
||||
"attempt_id": "pair-3-single_agent",
|
||||
"pair": 3,
|
||||
"variant": "single_agent",
|
||||
"run_order": 1,
|
||||
"accepted": true,
|
||||
"quality_score": 1,
|
||||
"elapsed_ms": 1260000,
|
||||
"cost_breakdown_usd": {
|
||||
"controller": 1.55,
|
||||
"workers": 0,
|
||||
"verifier": 0.1,
|
||||
"retries": 0
|
||||
},
|
||||
"total_cost_usd": 1.65,
|
||||
"worker_count": 1,
|
||||
"conflicts": 0,
|
||||
"integration_rework": 0,
|
||||
"human_corrections": 0
|
||||
},
|
||||
{
|
||||
"attempt_id": "pair-3-orchestrated",
|
||||
"pair": 3,
|
||||
"variant": "orchestrated",
|
||||
"run_order": 2,
|
||||
"accepted": true,
|
||||
"quality_score": 1,
|
||||
"elapsed_ms": 810000,
|
||||
"cost_breakdown_usd": {
|
||||
"controller": 0.55,
|
||||
"workers": 1.45,
|
||||
"verifier": 0.1,
|
||||
"retries": 0
|
||||
},
|
||||
"total_cost_usd": 2.1,
|
||||
"worker_count": 3,
|
||||
"conflicts": 0,
|
||||
"integration_rework": 0,
|
||||
"human_corrections": 0
|
||||
}
|
||||
],
|
||||
"pair_deltas": [
|
||||
{
|
||||
"pair": 1,
|
||||
"order": "single_agent_first",
|
||||
"quality_delta": 0,
|
||||
"time_delta_ms": -480000,
|
||||
"cost_delta_usd": 0.4
|
||||
},
|
||||
{
|
||||
"pair": 2,
|
||||
"order": "orchestrated_first",
|
||||
"quality_delta": 0,
|
||||
"time_delta_ms": -360000,
|
||||
"cost_delta_usd": 0.55
|
||||
},
|
||||
{
|
||||
"pair": 3,
|
||||
"order": "single_agent_first",
|
||||
"quality_delta": 0,
|
||||
"time_delta_ms": -450000,
|
||||
"cost_delta_usd": 0.45
|
||||
}
|
||||
],
|
||||
"metric_directions": {
|
||||
"quality": "no_difference",
|
||||
"time": "orchestrated_better",
|
||||
"cost": "single_agent_better"
|
||||
},
|
||||
"result": "consistent",
|
||||
"candidates": [
|
||||
{
|
||||
"candidate_id": "task-class-direction-claim",
|
||||
"decision": "accepted",
|
||||
"claim": "For this task class only, orchestration finished faster in all three pairs and cost more in all three pairs, with no quality difference.",
|
||||
"reasons": [
|
||||
"every pair reports available quality, time, and cost deltas from retained attempts",
|
||||
"time and cost deltas keep one sign across all three pairs and quality deltas are all zero",
|
||||
"both run orders occur, so a fixed-order effect cannot explain the direction",
|
||||
"the claim states the higher aggregate cost instead of reporting only the faster time"
|
||||
],
|
||||
"rollback": "Withdraw the claim and keep every raw attempt if a later pair reverses any metric direction."
|
||||
}
|
||||
],
|
||||
"promoted_candidate_id": "task-class-direction-claim"
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
{
|
||||
"schema_version": "ecc.evaluator-rag.report.v1",
|
||||
"scenario_id": "orchestration-efficiency-evidence",
|
||||
"run_id": "2026-08-11-orchestration-efficiency-prototype",
|
||||
"result": "prototype_passed",
|
||||
"read_only": true,
|
||||
"scores": {
|
||||
"control_matching": 0.96,
|
||||
"acceptance_first": 1,
|
||||
"aggregate_cost_coverage": 0.94,
|
||||
"coordination_cost_coverage": 0.93,
|
||||
"claim_safety": 1
|
||||
},
|
||||
"findings": [
|
||||
{
|
||||
"id": "quality-before-efficiency",
|
||||
"severity": "warning",
|
||||
"summary": "Elapsed time or token totals are not decision-useful when candidates fail different acceptance gates or evidence requirements."
|
||||
},
|
||||
{
|
||||
"id": "aggregate-worker-cost-required",
|
||||
"severity": "warning",
|
||||
"summary": "Controller-only telemetry understates orchestration cost; totals must include every worker and retry or remain explicitly unavailable."
|
||||
},
|
||||
{
|
||||
"id": "coordination-cost-visible",
|
||||
"severity": "info",
|
||||
"summary": "Conflicts, integration rework, retries, and human corrections are part of the result rather than incidental notes."
|
||||
},
|
||||
{
|
||||
"id": "replication-before-recommendation",
|
||||
"severity": "warning",
|
||||
"summary": "One pair, overlapping variants, or fixed run order can qualify a harness but cannot establish a general orchestration efficiency boundary."
|
||||
},
|
||||
{
|
||||
"id": "pair-consistency-before-direction",
|
||||
"severity": "warning",
|
||||
"summary": "With three pairs, one reversed pair delta makes that metric inconclusive; averaging opposite-sign deltas would publish a direction the evidence does not support."
|
||||
}
|
||||
],
|
||||
"recommended_next_action": {
|
||||
"candidate_id": "controlled-paired-orchestration-evaluation",
|
||||
"action": "Use the promoted playbook to design sequential paired runs, preserve every attempt, and recommend orchestration only for task classes where accepted quality and measured coordination cost justify it."
|
||||
},
|
||||
"evidence_coverage": {
|
||||
"kind": "synthetic_fixture_only",
|
||||
"pair_fixtures": [
|
||||
"pairs-sign-consistent.json",
|
||||
"pairs-mixed-sign.json"
|
||||
],
|
||||
"executed_runs": 0
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
{
|
||||
"schema_version": "ecc.evaluator-rag.scenario.v1",
|
||||
"scenario_id": "orchestration-efficiency-evidence",
|
||||
"title": "Require controlled evidence before claiming orchestration efficiency",
|
||||
"mode": "read_only_prototype",
|
||||
"objective": "Given a proposed multi-agent workflow or completed run, retrieve the dependency graph, ownership boundaries, acceptance evidence, matched single-agent baseline, and aggregate cost telemetry before promoting an orchestration recommendation.",
|
||||
"sources": [
|
||||
{
|
||||
"kind": "repo_skill",
|
||||
"path": "skills/parallel-execution-optimizer/SKILL.md",
|
||||
"purpose": "Defines dependency mapping, isolated write surfaces, and evidence-based integration for parallel work"
|
||||
},
|
||||
{
|
||||
"kind": "repo_skill",
|
||||
"path": "skills/context-budget/SKILL.md",
|
||||
"purpose": "Defines context and token overhead inventory instead of assuming more agents reduce total cost"
|
||||
},
|
||||
{
|
||||
"kind": "repo_source",
|
||||
"path": "scripts/lib/orchestration-session.js",
|
||||
"purpose": "Provides ECC orchestration session state and worker lifecycle evidence"
|
||||
},
|
||||
{
|
||||
"kind": "repo_test",
|
||||
"command": "node tests/lib/orchestration-session.test.js",
|
||||
"purpose": "Regression gate for orchestration session behavior"
|
||||
},
|
||||
{
|
||||
"kind": "external_experiment",
|
||||
"url": "https://github.com/Phelan164/codex-howto/blob/527296fa7d9ba1828d639ec000e0543c42ee2739/examples/measurements/incident-orchestration-smoke-2026-08-11.md",
|
||||
"purpose": "Contributed smoke evidence showing why overlapping runs and unavailable aggregate tokens cannot support an efficiency claim"
|
||||
}
|
||||
],
|
||||
"retrieval_questions": [
|
||||
"Which task dependencies and exclusive write surfaces justify multiple workers?",
|
||||
"Were the single-agent and orchestrated candidates run from the same task, revision, model, reasoning effort, permissions, tools, time limit, and evaluator?",
|
||||
"Did every attempted candidate meet the same acceptance and evidence-quality gates?",
|
||||
"What were total tokens or cost across the controller, all workers, the verifier, and retries, plus elapsed time, conflicts, integration rework, and human corrections?",
|
||||
"Were failures and unavailable telemetry retained rather than estimated or excluded?",
|
||||
"How many sequential paired runs and alternated run orders support the recommendation?",
|
||||
"What were each pair's quality, time, and cost deltas, and do they point the same direction across every pair?"
|
||||
],
|
||||
"forbidden_actions": [
|
||||
"claiming that parallel agents are faster or cheaper without a matched accepted single-agent baseline",
|
||||
"comparing candidates with different tasks, revisions, models, reasoning effort, permissions, tools, time limits, or evaluators",
|
||||
"reporting controller-only tokens or cost while omitting worker totals",
|
||||
"excluding failed candidates, edit conflicts, integration rework, retries, or human corrections",
|
||||
"averaging opposite-sign or unavailable pair deltas into a task-class recommendation",
|
||||
"estimating unavailable telemetry or turning one overlapping smoke run into a general efficiency claim",
|
||||
"launching workers, editing candidate repositories, publishing benchmarks, or posting announcements from this read-only evaluator run"
|
||||
],
|
||||
"acceptance_gates": [
|
||||
"dependency graph and exclusive ownership boundaries are recorded",
|
||||
"single-agent and orchestrated controls are matched",
|
||||
"all attempted candidates use the same acceptance evaluator",
|
||||
"aggregate controller, worker, verifier, and retry cost is recorded or explicitly unavailable",
|
||||
"elapsed time, retries, conflicts, integration rework, and human corrections are retained",
|
||||
"failed candidates remain in the comparison",
|
||||
"at least three fresh sequential pairs with alternated order are completed before promotion",
|
||||
"every raw attempt is retained and each pair reports quality, time, and cost deltas computed from those attempts",
|
||||
"mixed-sign or unavailable pair deltas yield an inconclusive result that blocks any task-class claim",
|
||||
"at least one one-run parallelism claim is rejected"
|
||||
],
|
||||
"pair_consistency_rule": {
|
||||
"delta_definition": "orchestrated minus single_agent for the same pair, computed from the retained raw attempts",
|
||||
"minimum_pairs": 3,
|
||||
"required_orders": [
|
||||
"single_agent_first",
|
||||
"orchestrated_first"
|
||||
],
|
||||
"unavailable_value": "unavailable",
|
||||
"metrics": [
|
||||
{
|
||||
"name": "quality",
|
||||
"attempt_field": "quality_score",
|
||||
"delta_field": "quality_delta",
|
||||
"better_when": "higher"
|
||||
},
|
||||
{
|
||||
"name": "time",
|
||||
"attempt_field": "elapsed_ms",
|
||||
"delta_field": "time_delta_ms",
|
||||
"better_when": "lower"
|
||||
},
|
||||
{
|
||||
"name": "cost",
|
||||
"attempt_field": "total_cost_usd",
|
||||
"delta_field": "cost_delta_usd",
|
||||
"better_when": "lower"
|
||||
}
|
||||
],
|
||||
"aggregate_cost_components": [
|
||||
"controller",
|
||||
"workers",
|
||||
"verifier",
|
||||
"retries"
|
||||
],
|
||||
"metric_direction": "A metric has a direction only when every pair reports an available delta and all deltas are nonzero with the same sign, or all deltas are zero (no_difference). Any other pattern is inconclusive; deltas are never averaged.",
|
||||
"result": "consistent only when the minimum pair count is met, both run orders occur, and every metric has a direction; otherwise inconclusive",
|
||||
"claim_allowed_only_if": "result is consistent; the claim names its task class and every metric direction, including any cost or quality loss",
|
||||
"fixtures": [
|
||||
"pairs-sign-consistent.json",
|
||||
"pairs-mixed-sign.json"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
{
|
||||
"schema_version": "ecc.evaluator-rag.trace.v1",
|
||||
"scenario_id": "orchestration-efficiency-evidence",
|
||||
"run_id": "2026-08-11-orchestration-efficiency-prototype",
|
||||
"read_only": true,
|
||||
"events": [
|
||||
{
|
||||
"phase": "observation",
|
||||
"summary": "A workflow proposes multiple agents or reports an orchestrated result. The evaluator records the task boundary and claims without launching workers or changing candidate repositories.",
|
||||
"evidence": [
|
||||
"skills/parallel-execution-optimizer/SKILL.md",
|
||||
"scripts/lib/orchestration-session.js"
|
||||
]
|
||||
},
|
||||
{
|
||||
"phase": "retrieval",
|
||||
"summary": "Retrieved dependency and ownership plans, matched run controls, acceptance results, aggregate token or cost telemetry, elapsed time, failures, conflicts, integration rework, retries, and human corrections.",
|
||||
"evidence": [
|
||||
"skills/context-budget/SKILL.md",
|
||||
"node tests/lib/orchestration-session.test.js",
|
||||
"https://github.com/Phelan164/codex-howto/blob/527296fa7d9ba1828d639ec000e0543c42ee2739/examples/measurements/incident-orchestration-smoke-2026-08-11.md"
|
||||
]
|
||||
},
|
||||
{
|
||||
"phase": "proposal",
|
||||
"summary": "Generated two candidates: a controlled paired evaluation that preserves all attempts and an intuition-only claim that parallelism implies efficiency.",
|
||||
"candidate_ids": [
|
||||
"controlled-paired-orchestration-evaluation",
|
||||
"parallelism-implies-efficiency"
|
||||
]
|
||||
},
|
||||
{
|
||||
"phase": "verification",
|
||||
"summary": "Accepted the controlled paired evaluation because it matches controls, evaluates quality first, aggregates worker cost, and keeps negative results. Rejected the intuition-only claim because it relies on one overlapping run with unavailable token totals. Applied the pair consistency rule: the sign-consistent fixture permits only a task-class-scoped claim, and the mixed-sign fixture returns inconclusive with no promoted claim.",
|
||||
"evidence": [
|
||||
"examples/evaluator-rag-prototype/orchestration-efficiency-evidence/verifier-result.json",
|
||||
"examples/evaluator-rag-prototype/orchestration-efficiency-evidence/pairs-sign-consistent.json",
|
||||
"examples/evaluator-rag-prototype/orchestration-efficiency-evidence/pairs-mixed-sign.json"
|
||||
]
|
||||
},
|
||||
{
|
||||
"phase": "promotion",
|
||||
"summary": "Promoted only the read-only orchestration evidence playbook. It does not launch agents, edit candidates, publish results, or claim that orchestration is efficient.",
|
||||
"promoted_candidate_id": "controlled-paired-orchestration-evaluation"
|
||||
}
|
||||
]
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
{
|
||||
"schema_version": "ecc.evaluator-rag.verifier.v1",
|
||||
"scenario_id": "orchestration-efficiency-evidence",
|
||||
"run_id": "2026-08-11-orchestration-efficiency-prototype",
|
||||
"read_only": true,
|
||||
"candidates": [
|
||||
{
|
||||
"candidate_id": "controlled-paired-orchestration-evaluation",
|
||||
"decision": "accepted",
|
||||
"score": 0.95,
|
||||
"reasons": [
|
||||
"records a dependency graph and exclusive write ownership before delegation",
|
||||
"matches task, revision, model, reasoning effort, permissions, tools, time limit, and evaluator",
|
||||
"requires acceptance and evidence quality before comparing elapsed time or cost",
|
||||
"aggregates controller, worker, verifier, and retry tokens or cost and marks unavailable telemetry honestly",
|
||||
"retains failed candidates, conflicts, integration rework, retries, and human corrections",
|
||||
"requires repeated sequential pairs and alternated run order before a general recommendation",
|
||||
"derives per-pair quality, time, and cost deltas from retained attempts and returns inconclusive when any metric is mixed-sign or unavailable"
|
||||
],
|
||||
"rollback": "Withdraw the recommendation and retain the raw run receipts if later replications reverse the result; this read-only playbook launches no workers and changes no candidate repository."
|
||||
},
|
||||
{
|
||||
"candidate_id": "parallelism-implies-efficiency",
|
||||
"decision": "rejected",
|
||||
"score": 0.12,
|
||||
"reasons": [
|
||||
"treats more agents as inherently faster and cheaper",
|
||||
"has no matched accepted single-agent baseline",
|
||||
"reports no aggregate worker token or cost total",
|
||||
"ignores overlap, machine contention, conflicts, integration rework, and failed attempts",
|
||||
"turns one smoke run with unavailable telemetry into a general efficiency claim",
|
||||
"would average opposite-sign pair results into one direction"
|
||||
],
|
||||
"rollback": "Do not publish the claim; restart from matched controls, acceptance evidence, complete run receipts, and sequential paired replications."
|
||||
}
|
||||
],
|
||||
"promoted_candidate_id": "controlled-paired-orchestration-evaluation"
|
||||
}
|
||||
@@ -10,7 +10,7 @@
|
||||
"id": "hand-seeded",
|
||||
"source": "manual-curation-pending-regeneration"
|
||||
},
|
||||
"registryDigest": "23bd986cff96ea33424b1a461461a70e3194582ce01927145fd3f956daeebf7f",
|
||||
"registryDigest": "cf9879ff972740a7d2af9b56a0f682870375d3abc75eea9164bd2b1838fd5b81",
|
||||
"schemaVersion": 1,
|
||||
"triggers": {
|
||||
"skill:agent-runtime-gateway-smoke-test": [
|
||||
|
||||
@@ -422,6 +422,14 @@
|
||||
"agents-core"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "agent:spec-miner",
|
||||
"family": "agent",
|
||||
"description": "Behavioral spec extraction agent for brownfield codebases.",
|
||||
"modules": [
|
||||
"agents-core"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "agent:tdd-guide",
|
||||
"family": "agent",
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
"cursor",
|
||||
"copilot",
|
||||
"antigravity",
|
||||
"antigravity-home",
|
||||
"codebuddy",
|
||||
"joycode",
|
||||
"qwen",
|
||||
@@ -42,6 +43,7 @@
|
||||
"claude-project",
|
||||
"cursor",
|
||||
"antigravity",
|
||||
"antigravity-home",
|
||||
"codex",
|
||||
"copilot",
|
||||
"codebuddy",
|
||||
@@ -78,6 +80,7 @@
|
||||
"cursor",
|
||||
"copilot",
|
||||
"antigravity",
|
||||
"antigravity-home",
|
||||
"opencode",
|
||||
"codebuddy",
|
||||
"joycode",
|
||||
@@ -109,7 +112,9 @@
|
||||
"claude-project",
|
||||
"cursor",
|
||||
"opencode",
|
||||
"codebuddy"
|
||||
"codebuddy",
|
||||
"antigravity",
|
||||
"antigravity-home"
|
||||
],
|
||||
"dependencies": [],
|
||||
"defaultInstall": true,
|
||||
@@ -161,6 +166,7 @@
|
||||
"cursor",
|
||||
"copilot",
|
||||
"antigravity",
|
||||
"antigravity-home",
|
||||
"codex",
|
||||
"gemini",
|
||||
"opencode",
|
||||
@@ -267,6 +273,7 @@
|
||||
"claude-project",
|
||||
"cursor",
|
||||
"antigravity",
|
||||
"antigravity-home",
|
||||
"codex",
|
||||
"copilot",
|
||||
"opencode",
|
||||
@@ -309,6 +316,7 @@
|
||||
"claude-project",
|
||||
"cursor",
|
||||
"antigravity",
|
||||
"antigravity-home",
|
||||
"codex",
|
||||
"copilot",
|
||||
"opencode",
|
||||
@@ -336,6 +344,7 @@
|
||||
"claude-project",
|
||||
"cursor",
|
||||
"antigravity",
|
||||
"antigravity-home",
|
||||
"codex",
|
||||
"copilot",
|
||||
"gemini",
|
||||
@@ -368,6 +377,7 @@
|
||||
"claude-project",
|
||||
"cursor",
|
||||
"antigravity",
|
||||
"antigravity-home",
|
||||
"codex",
|
||||
"opencode",
|
||||
"codebuddy",
|
||||
@@ -449,6 +459,7 @@
|
||||
"claude-project",
|
||||
"cursor",
|
||||
"antigravity",
|
||||
"antigravity-home",
|
||||
"codex",
|
||||
"copilot",
|
||||
"opencode",
|
||||
@@ -480,6 +491,7 @@
|
||||
"claude-project",
|
||||
"cursor",
|
||||
"antigravity",
|
||||
"antigravity-home",
|
||||
"codex",
|
||||
"opencode",
|
||||
"codebuddy",
|
||||
@@ -517,6 +529,7 @@
|
||||
"claude-project",
|
||||
"cursor",
|
||||
"antigravity",
|
||||
"antigravity-home",
|
||||
"codex",
|
||||
"copilot",
|
||||
"opencode",
|
||||
@@ -568,6 +581,7 @@
|
||||
"claude-project",
|
||||
"cursor",
|
||||
"antigravity",
|
||||
"antigravity-home",
|
||||
"codex",
|
||||
"copilot",
|
||||
"opencode",
|
||||
@@ -605,6 +619,7 @@
|
||||
"claude-project",
|
||||
"cursor",
|
||||
"antigravity",
|
||||
"antigravity-home",
|
||||
"codex",
|
||||
"copilot",
|
||||
"opencode",
|
||||
@@ -645,6 +660,7 @@
|
||||
"claude-project",
|
||||
"cursor",
|
||||
"antigravity",
|
||||
"antigravity-home",
|
||||
"codex",
|
||||
"copilot",
|
||||
"opencode",
|
||||
@@ -692,6 +708,7 @@
|
||||
"claude-project",
|
||||
"cursor",
|
||||
"antigravity",
|
||||
"antigravity-home",
|
||||
"codex",
|
||||
"copilot",
|
||||
"opencode",
|
||||
@@ -721,6 +738,7 @@
|
||||
"claude-project",
|
||||
"cursor",
|
||||
"antigravity",
|
||||
"antigravity-home",
|
||||
"codex",
|
||||
"copilot",
|
||||
"opencode",
|
||||
@@ -753,6 +771,7 @@
|
||||
"claude-project",
|
||||
"cursor",
|
||||
"antigravity",
|
||||
"antigravity-home",
|
||||
"codex",
|
||||
"opencode",
|
||||
"codebuddy",
|
||||
@@ -768,7 +787,7 @@
|
||||
{
|
||||
"id": "ito-compute",
|
||||
"kind": "skills",
|
||||
"description": "Authenticated It\u00f4 GPU inventory, RFQ, status, device revocation, and explicitly gated node-qualification workflows through the separately installed canonical CLI.",
|
||||
"description": "Authenticated Itô GPU inventory, RFQ, status, device revocation, and explicitly gated node-qualification workflows through the separately installed canonical CLI.",
|
||||
"paths": [
|
||||
"skills/ito-compute",
|
||||
"skills/ito-inference",
|
||||
@@ -779,6 +798,7 @@
|
||||
"claude-project",
|
||||
"cursor",
|
||||
"antigravity",
|
||||
"antigravity-home",
|
||||
"codex",
|
||||
"copilot",
|
||||
"gemini",
|
||||
@@ -811,6 +831,7 @@
|
||||
"claude-project",
|
||||
"cursor",
|
||||
"antigravity",
|
||||
"antigravity-home",
|
||||
"codex",
|
||||
"copilot",
|
||||
"gemini",
|
||||
@@ -845,6 +866,7 @@
|
||||
"claude-project",
|
||||
"cursor",
|
||||
"antigravity",
|
||||
"antigravity-home",
|
||||
"codex",
|
||||
"copilot",
|
||||
"opencode",
|
||||
@@ -943,6 +965,7 @@
|
||||
"claude-project",
|
||||
"cursor",
|
||||
"antigravity",
|
||||
"antigravity-home",
|
||||
"codex",
|
||||
"copilot",
|
||||
"opencode",
|
||||
@@ -1028,6 +1051,7 @@
|
||||
"claude-project",
|
||||
"cursor",
|
||||
"antigravity",
|
||||
"antigravity-home",
|
||||
"codex",
|
||||
"copilot",
|
||||
"opencode",
|
||||
@@ -1073,6 +1097,7 @@
|
||||
"claude-project",
|
||||
"cursor",
|
||||
"antigravity",
|
||||
"antigravity-home",
|
||||
"codex",
|
||||
"copilot",
|
||||
"opencode",
|
||||
@@ -1103,6 +1128,7 @@
|
||||
"claude-project",
|
||||
"cursor",
|
||||
"antigravity",
|
||||
"antigravity-home",
|
||||
"codex",
|
||||
"copilot",
|
||||
"opencode",
|
||||
@@ -1141,6 +1167,7 @@
|
||||
"claude-project",
|
||||
"cursor",
|
||||
"antigravity",
|
||||
"antigravity-home",
|
||||
"codex",
|
||||
"copilot",
|
||||
"opencode",
|
||||
@@ -1169,6 +1196,7 @@
|
||||
"claude-project",
|
||||
"cursor",
|
||||
"antigravity",
|
||||
"antigravity-home",
|
||||
"codex",
|
||||
"copilot",
|
||||
"opencode",
|
||||
@@ -1404,6 +1432,7 @@
|
||||
"claude-project",
|
||||
"cursor",
|
||||
"antigravity",
|
||||
"antigravity-home",
|
||||
"codex",
|
||||
"opencode",
|
||||
"codebuddy",
|
||||
@@ -1464,6 +1493,7 @@
|
||||
"claude-project",
|
||||
"cursor",
|
||||
"antigravity",
|
||||
"antigravity-home",
|
||||
"codex",
|
||||
"opencode",
|
||||
"codebuddy",
|
||||
@@ -1526,6 +1556,7 @@
|
||||
"cursor",
|
||||
"copilot",
|
||||
"antigravity",
|
||||
"antigravity-home",
|
||||
"opencode",
|
||||
"codebuddy",
|
||||
"joycode",
|
||||
|
||||
@@ -484,6 +484,7 @@
|
||||
"developer.android.com",
|
||||
"developer.apple.com",
|
||||
"developers.cloudflare.com",
|
||||
"docs.celeryq.dev",
|
||||
"docs.flutter.dev",
|
||||
"docs.spring.io",
|
||||
"external-secrets.io",
|
||||
|
||||
@@ -225,9 +225,9 @@
|
||||
},
|
||||
"mnemosyne-os": {
|
||||
"command": "npx",
|
||||
"args": ["-y", "-p", "@mnemosyne_os/mcp@2.2.0", "mnemosyne-mcp"],
|
||||
"args": ["-y", "-p", "@mnemosyne_os/mcp@2.4.0", "mnemosyne-mcp"],
|
||||
"env": { "MNEMO_VAULTS": "YOUR_APPROVED_VAULT_NAMES", "MNEMO_DEFAULT_VAULT": "" },
|
||||
"description": "Opt-in Mnemosyne OS desktop-app memory and dashboard. Replace MNEMO_VAULTS with approved vault names before enabling; the app ingests selected folders into persistent vaults, and memory_ingest can save content for later agents. Vault scope does not restrict session tools, which read local coding-agent transcripts. Review folder and transcript access before enabling. Memory tools use the app at ws://127.0.0.1:7799. Tool results, including private memory and session data, go to the MCP client and its model provider. Not enabled by default."
|
||||
"description": "Opt-in Mnemosyne OS desktop-app memory and dashboard. Replace MNEMO_VAULTS with approved vault names before enabling; the app ingests selected folders into persistent vaults, and memory_ingest can save content for later agents. Vault scope does not restrict session tools, which read local coding-agent transcripts. Review folder and transcript access before enabling. Memory tools use the app at ws://127.0.0.1:7799. Tool results, including private memory and session data, go to the MCP client and its model provider. Version 2.4.0 adds mnemosyne_telegram_send, which uploads a local media or PDF file to the Telegram chat configured in the app, and on macOS mnemosyne_mac_update_install, which downloads the latest GitHub release and replaces the installed app; require client approval for both, or deny them if unused. Not enabled by default."
|
||||
}
|
||||
},
|
||||
"_comments": {
|
||||
|
||||
Generated
+119
-86
@@ -12,7 +12,7 @@
|
||||
"@iarna/toml": "2.2.5",
|
||||
"ajv": "8.20.0",
|
||||
"js-yaml": "5.5.0",
|
||||
"sql.js": "1.15.2",
|
||||
"sql.js": "1.16.0",
|
||||
"zod": "4.6.7"
|
||||
},
|
||||
"bin": {
|
||||
@@ -27,14 +27,14 @@
|
||||
"@eslint/js": "9.39.2",
|
||||
"@opencode-ai/plugin": "1.4.3",
|
||||
"@types/node": "26.6.6",
|
||||
"@x402/core": "2.29.0",
|
||||
"@x402/evm": "2.29.0",
|
||||
"@x402/express": "2.29.0",
|
||||
"@x402/core": "2.31.0",
|
||||
"@x402/evm": "2.31.0",
|
||||
"@x402/express": "2.31.0",
|
||||
"c8": "11.0.0",
|
||||
"eslint": "10.13.0",
|
||||
"eslint": "10.15.0",
|
||||
"express": "4.22.3",
|
||||
"globals": "17.13.0",
|
||||
"markdownlint-cli": "0.49.1",
|
||||
"globals": "17.14.0",
|
||||
"markdownlint-cli": "0.50.0",
|
||||
"typescript": "6.0.3"
|
||||
},
|
||||
"engines": {
|
||||
@@ -125,15 +125,15 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@eslint/config-array": {
|
||||
"version": "0.23.5",
|
||||
"resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.23.5.tgz",
|
||||
"integrity": "sha512-Y3kKLvC1dvTOT+oGlqNQ1XLqK6D1HU2YXPc52NmAlJZbMMWDzGYXMiPRJ8TYD39muD/OTjlZmNJ4ib7dvSrMBA==",
|
||||
"version": "0.23.6",
|
||||
"resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.23.6.tgz",
|
||||
"integrity": "sha512-WrTH7nioI9QPY4NZGnsywmecswJdgeq4BCM76qok9VgjTO29ZgUzUvcuJLVPYVQM4uDbaPBU0M33R9DIxI8X3w==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@eslint/object-schema": "^3.0.5",
|
||||
"debug": "^4.3.1",
|
||||
"minimatch": "^10.2.4"
|
||||
"minimatch": "^11.0.5"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^20.19.0 || ^22.13.0 || >=24"
|
||||
@@ -560,9 +560,9 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@x402/core": {
|
||||
"version": "2.29.0",
|
||||
"resolved": "https://registry.npmjs.org/@x402/core/-/core-2.29.0.tgz",
|
||||
"integrity": "sha512-fkS0JqVwHgczteDlwItLRipOlIzm28U9HWLvYnYpnNbfmepoBT/4ux7LjrR0xGD51JHoC8/r+Qo7uCfoAQYeuw==",
|
||||
"version": "2.31.0",
|
||||
"resolved": "https://registry.npmjs.org/@x402/core/-/core-2.31.0.tgz",
|
||||
"integrity": "sha512-7ToCOwHfftfFEERW5Mp6Fc5U1+JrtCLTkbQnEVsBl13IutltP9lWIBYi/J+zy8vQWaLUmACq8A2qywzdt/RRIQ==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
@@ -570,29 +570,29 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@x402/evm": {
|
||||
"version": "2.29.0",
|
||||
"resolved": "https://registry.npmjs.org/@x402/evm/-/evm-2.29.0.tgz",
|
||||
"integrity": "sha512-Gk4bJ6WoRR3jeT2+vERSPMSkSr1nRL5kjtVh14uoynRm8y+fGFH8xmvlGzuwKT0liA6OLjdr9xjZtN8i0WYk9g==",
|
||||
"version": "2.31.0",
|
||||
"resolved": "https://registry.npmjs.org/@x402/evm/-/evm-2.31.0.tgz",
|
||||
"integrity": "sha512-CCOqou/7f0/5kKQXlcVvWbiVnFmk/CqaSCs8YkJ2GPzxDYoQD13iKAjo0Uv7y/dVlkkOH0p/eJVxgcrO6aagbw==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@x402/core": "~2.29.0",
|
||||
"@x402/core": "~2.31.0",
|
||||
"viem": "^2.48.11",
|
||||
"zod": "^4.6.6"
|
||||
}
|
||||
},
|
||||
"node_modules/@x402/express": {
|
||||
"version": "2.29.0",
|
||||
"resolved": "https://registry.npmjs.org/@x402/express/-/express-2.29.0.tgz",
|
||||
"integrity": "sha512-0Ka1740ye02ZjSN3VeiEt3Gt7iINvTCl9nlP6ttGKSsySLMeMuDXJOzSOuzUnkJxy4LBxpG4Z+w3F46mhn6AUA==",
|
||||
"version": "2.31.0",
|
||||
"resolved": "https://registry.npmjs.org/@x402/express/-/express-2.31.0.tgz",
|
||||
"integrity": "sha512-hUumfQGb8mNdwkpLAZuuoHCJ3p5gNtu5/yRaZNRNqQILp155Ur2tJQCizPQZR1XNsZ6mXwJG4+5rE1iW0f/9sg==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@x402/core": "~2.29.0",
|
||||
"@x402/extensions": "~2.29.0"
|
||||
"@x402/core": "~2.31.0",
|
||||
"@x402/extensions": "~2.31.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@x402/paywall": "^2.29.0",
|
||||
"@x402/paywall": "^2.31.0",
|
||||
"express": "^4.22.3 || ^5.3.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
@@ -602,16 +602,16 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@x402/extensions": {
|
||||
"version": "2.29.0",
|
||||
"resolved": "https://registry.npmjs.org/@x402/extensions/-/extensions-2.29.0.tgz",
|
||||
"integrity": "sha512-FCpjZ6QR6ZtHTRZBV7VHMt7tc66LnTrpKDERiL3atXlLu4PlmgiulHt9PWE+Ktm5iUbXr3dAYZu2e7XrVd/XgA==",
|
||||
"version": "2.31.0",
|
||||
"resolved": "https://registry.npmjs.org/@x402/extensions/-/extensions-2.31.0.tgz",
|
||||
"integrity": "sha512-hFq11UtXNWPirZSZjZuWFHvjetYvFQmkQSZcNEMaQYxOz70ZLNFmIdXfG2J/B8YGE2nS2d223Hz9Lnkrxw+Sqw==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@noble/curves": "^1.9.0",
|
||||
"@scure/base": "^1.2.6",
|
||||
"@signinwithethereum/siwe": "^4.1.0",
|
||||
"@x402/core": "~2.29.0",
|
||||
"@x402/core": "~2.31.0",
|
||||
"ajv": "^8.18.0",
|
||||
"jose": "^5.9.6",
|
||||
"tweetnacl": "^1.0.3",
|
||||
@@ -695,9 +695,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/ansi-regex": {
|
||||
"version": "6.3.0",
|
||||
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.3.0.tgz",
|
||||
"integrity": "sha512-WpDfL7NO6j7tH88IDBNVdUJxDh9nmCteAVW9dsep846XdwF4naCBK+/tGLX3KJgcpgMRXCFlTM2hKGoK9FsdrQ==",
|
||||
"version": "6.6.0",
|
||||
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.6.0.tgz",
|
||||
"integrity": "sha512-XZ5apbzreCbXSKwPjJstu8R0zOi247w3XYwWxtwBXgpZrCyc1Ka7p9/xY0A9/diMewmHbEKz+FIraWaEWjlN5g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
@@ -1307,9 +1307,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/eslint": {
|
||||
"version": "10.13.0",
|
||||
"resolved": "https://registry.npmjs.org/eslint/-/eslint-10.13.0.tgz",
|
||||
"integrity": "sha512-UohDjD4zSzEwhf58M3O7vc/ycc8O1I7dNlhtD0WxE8Px8EHNJKtUwzBqrzeGhisRuv2ag4sAYswszCJRgKXYUg==",
|
||||
"version": "10.15.0",
|
||||
"resolved": "https://registry.npmjs.org/eslint/-/eslint-10.15.0.tgz",
|
||||
"integrity": "sha512-+5Wg4p+ze3sG1WErYgUO/3H1IQIfFBymVUA0Fo/XTeBOLS6UQIUekpSJ8sdRkn7O7wjh84b55w/roqavH2aScg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"workspaces": [
|
||||
@@ -1318,11 +1318,11 @@
|
||||
"dependencies": {
|
||||
"@eslint-community/eslint-utils": "^4.8.0",
|
||||
"@eslint-community/regexpp": "^4.12.2",
|
||||
"@eslint/config-array": "^0.23.5",
|
||||
"@eslint/config-array": "^0.23.6",
|
||||
"@eslint/config-helpers": "^0.7.0",
|
||||
"@eslint/core": "^1.2.1",
|
||||
"@eslint/plugin-kit": "^0.7.3",
|
||||
"@humanfs/node": "^0.16.6",
|
||||
"@humanfs/node": "^0.16.8",
|
||||
"@humanwhocodes/module-importer": "^1.0.1",
|
||||
"@humanwhocodes/retry": "^0.4.2",
|
||||
"@types/estree": "^1.0.6",
|
||||
@@ -1343,7 +1343,7 @@
|
||||
"imurmurhash": "^0.1.4",
|
||||
"is-glob": "^4.0.0",
|
||||
"json-stable-stringify-without-jsonify": "^1.0.1",
|
||||
"minimatch": "^10.2.5",
|
||||
"minimatch": "^11.0.5",
|
||||
"natural-compare": "^1.4.0",
|
||||
"optionator": "^0.9.3"
|
||||
},
|
||||
@@ -1760,9 +1760,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/get-east-asian-width": {
|
||||
"version": "1.6.0",
|
||||
"resolved": "https://registry.npmjs.org/get-east-asian-width/-/get-east-asian-width-1.6.0.tgz",
|
||||
"integrity": "sha512-QRbvDIbx6YklUe6RxeTeleMR0yv3cYH6PsPZHcnVn7xv7zO1BHN8r0XETu8n6Ye3Q+ahtSarc3WgtNWmehIBfA==",
|
||||
"version": "1.7.0",
|
||||
"resolved": "https://registry.npmjs.org/get-east-asian-width/-/get-east-asian-width-1.7.0.tgz",
|
||||
"integrity": "sha512-XjH1AECxf0giL2V1aU8vKyRR2ppRUb5c0EvT7zuJTokQ74bNo52zOtghqdWIqrhUD79fo3x0WfKZdOqxF6LG1Q==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
@@ -1843,9 +1843,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/globals": {
|
||||
"version": "17.13.0",
|
||||
"resolved": "https://registry.npmjs.org/globals/-/globals-17.13.0.tgz",
|
||||
"integrity": "sha512-RwMTC61u7hrG3ZJMkZQOK4JLJrKS8QtoTii63EmWvFXHqycY9FObBJQCbsLxSO8kjKhWE5kV1GC+Vb1g3RI0Zg==",
|
||||
"version": "17.14.0",
|
||||
"resolved": "https://registry.npmjs.org/globals/-/globals-17.14.0.tgz",
|
||||
"integrity": "sha512-UtdkTVyAJePQv0J2M9Xe4L0ruNSDV314XiIJsADI2Zf40bcdAonE/D/OhAU8AT99oij9mhLByb+NvA3QWZYgCg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
@@ -2375,21 +2375,22 @@
|
||||
}
|
||||
},
|
||||
"node_modules/markdownlint": {
|
||||
"version": "0.41.1",
|
||||
"resolved": "https://registry.npmjs.org/markdownlint/-/markdownlint-0.41.1.tgz",
|
||||
"integrity": "sha512-qHKeU2E1bdyNAT077go2FVTNXvYcktN5IHtF6XyeD1l0PClxzSp2tUApAV14ORI8DGX4H9bNKZEzelZp4qn8IA==",
|
||||
"version": "0.42.1",
|
||||
"resolved": "https://registry.npmjs.org/markdownlint/-/markdownlint-0.42.1.tgz",
|
||||
"integrity": "sha512-Otolm9JX12iO2NG5cetlKfzGygpiLSlHuqXKxoT6HGhN5HtbxprJPicKZqqCQd88qOvUi/TEs3o1AmcYioVscA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"micromark": "4.0.2",
|
||||
"micromark-core-commonmark": "2.0.3",
|
||||
"micromark": "4.0.3",
|
||||
"micromark-core-commonmark": "2.0.4",
|
||||
"micromark-extension-directive": "4.0.0",
|
||||
"micromark-extension-gfm-autolink-literal": "2.1.0",
|
||||
"micromark-extension-gfm-footnote": "2.1.0",
|
||||
"micromark-extension-gfm-table": "2.1.1",
|
||||
"micromark-extension-gfm-table": "2.1.2",
|
||||
"micromark-extension-math": "3.1.0",
|
||||
"micromark-util-types": "2.0.2",
|
||||
"string-width": "8.2.1"
|
||||
"micromark-util-types": "2.0.3",
|
||||
"re2js": "2.9.1",
|
||||
"string-width": "8.3.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22"
|
||||
@@ -2399,23 +2400,23 @@
|
||||
}
|
||||
},
|
||||
"node_modules/markdownlint-cli": {
|
||||
"version": "0.49.1",
|
||||
"resolved": "https://registry.npmjs.org/markdownlint-cli/-/markdownlint-cli-0.49.1.tgz",
|
||||
"integrity": "sha512-qpYqJbSYf3jv57bdnFmCaZ/Wlu6IYHp2b6SOKrKBJ7OnPrDHIKmx4NERWH49QH9viTI6yO6raVDDn5nrf60VQQ==",
|
||||
"version": "0.50.0",
|
||||
"resolved": "https://registry.npmjs.org/markdownlint-cli/-/markdownlint-cli-0.50.0.tgz",
|
||||
"integrity": "sha512-4GqP/CqpF74ihrlLTOPc3I5b/tZabiiKnIVQ27xTzsS4hjU3oIHKg1YBzWP7fsa9AH48LPF0KcmCqDccpSeMEg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"commander": "~15.0.0",
|
||||
"deep-extend": "~0.6.0",
|
||||
"ignore": "~7.0.6",
|
||||
"js-yaml": "~5.2.1",
|
||||
"ignore": "~7.0.13",
|
||||
"js-yaml": "~5.5.0",
|
||||
"jsonc-parser": "~3.3.1",
|
||||
"jsonpointer": "~5.0.1",
|
||||
"markdown-it": "~14.3.0",
|
||||
"markdownlint": "~0.41.1",
|
||||
"minimatch": "~10.2.5",
|
||||
"markdown-it": "~15.0.3",
|
||||
"markdownlint": "~0.42.0",
|
||||
"minimatch": "~10.2.6",
|
||||
"run-con": "~1.3.3",
|
||||
"smol-toml": "~1.7.0",
|
||||
"smol-toml": "~1.9.1",
|
||||
"tinyglobby": "~0.2.17"
|
||||
},
|
||||
"bin": {
|
||||
@@ -2426,9 +2427,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/markdownlint-cli/node_modules/ignore": {
|
||||
"version": "7.0.8",
|
||||
"resolved": "https://registry.npmjs.org/ignore/-/ignore-7.0.8.tgz",
|
||||
"integrity": "sha512-YYNsSlXBjMk92SKnkwvB5LOVSa6OznlFUGcsvrFgNJbJCd0M1XKeFVRc8ZByeCqz32FivYNHJVooLmdqrmvp/Q==",
|
||||
"version": "7.0.14",
|
||||
"resolved": "https://registry.npmjs.org/ignore/-/ignore-7.0.14.tgz",
|
||||
"integrity": "sha512-wCBiZ77u1tuWde6G/nfOtLaCTYcFDU5yCzARzK10y+rLhzYoL7a7yEemcopcc2Mzow7gZOIjnV2ym1NYmdiJOQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
@@ -2482,9 +2483,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/micromark": {
|
||||
"version": "4.0.2",
|
||||
"resolved": "https://registry.npmjs.org/micromark/-/micromark-4.0.2.tgz",
|
||||
"integrity": "sha512-zpe98Q6kvavpCr1NPVSCMebCKfD7CA2NqZ+rykeNhONIJBpc1tFKt9hucLGwha3jNTNI8lHpctWJWoimVF4PfA==",
|
||||
"version": "4.0.3",
|
||||
"resolved": "https://registry.npmjs.org/micromark/-/micromark-4.0.3.tgz",
|
||||
"integrity": "sha512-oGYfQzHSG5dOMovQcJ3fyTmZlWAWpi0XA0sJwJs+i6OT88o1+Jtw/8z0CmdowSLxGhhFK89rQ/oXph/wN02PNw==",
|
||||
"dev": true,
|
||||
"funding": [
|
||||
{
|
||||
@@ -2508,6 +2509,7 @@
|
||||
"micromark-util-chunked": "^2.0.0",
|
||||
"micromark-util-combine-extensions": "^2.0.0",
|
||||
"micromark-util-decode-numeric-character-reference": "^2.0.0",
|
||||
"micromark-util-edit-map": "^1.0.0",
|
||||
"micromark-util-encode": "^2.0.0",
|
||||
"micromark-util-normalize-identifier": "^2.0.0",
|
||||
"micromark-util-resolve-all": "^2.0.0",
|
||||
@@ -2518,9 +2520,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/micromark-core-commonmark": {
|
||||
"version": "2.0.3",
|
||||
"resolved": "https://registry.npmjs.org/micromark-core-commonmark/-/micromark-core-commonmark-2.0.3.tgz",
|
||||
"integrity": "sha512-RDBrHEMSxVFLg6xvnXmb1Ayr2WzLAWjeSATAoxwKYJV94TeNavgoIdA0a9ytzDSVzBy2YKFK+emCPOEibLeCrg==",
|
||||
"version": "2.0.4",
|
||||
"resolved": "https://registry.npmjs.org/micromark-core-commonmark/-/micromark-core-commonmark-2.0.4.tgz",
|
||||
"integrity": "sha512-wxEeE8v8XVvOrxn1TZj74qYhAtTQsSqufHVS3uNVyT1MupXxhyaHk8/9xDNPh9BmL77QNDgWTkZ3RsYHB2ry7w==",
|
||||
"dev": true,
|
||||
"funding": [
|
||||
{
|
||||
@@ -2538,18 +2540,19 @@
|
||||
"devlop": "^1.0.0",
|
||||
"micromark-factory-destination": "^2.0.0",
|
||||
"micromark-factory-label": "^2.0.0",
|
||||
"micromark-factory-space": "^2.0.0",
|
||||
"micromark-factory-space": "^2.1.0",
|
||||
"micromark-factory-title": "^2.0.0",
|
||||
"micromark-factory-whitespace": "^2.0.0",
|
||||
"micromark-util-character": "^2.0.0",
|
||||
"micromark-util-chunked": "^2.0.0",
|
||||
"micromark-util-classify-character": "^2.0.0",
|
||||
"micromark-util-edit-map": "^1.0.0",
|
||||
"micromark-util-html-tag-name": "^2.0.0",
|
||||
"micromark-util-normalize-identifier": "^2.0.0",
|
||||
"micromark-util-resolve-all": "^2.0.0",
|
||||
"micromark-util-subtokenize": "^2.0.0",
|
||||
"micromark-util-symbol": "^2.0.0",
|
||||
"micromark-util-types": "^2.0.0"
|
||||
"micromark-util-types": "^2.0.3"
|
||||
}
|
||||
},
|
||||
"node_modules/micromark-extension-directive": {
|
||||
@@ -2611,9 +2614,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/micromark-extension-gfm-table": {
|
||||
"version": "2.1.1",
|
||||
"resolved": "https://registry.npmjs.org/micromark-extension-gfm-table/-/micromark-extension-gfm-table-2.1.1.tgz",
|
||||
"integrity": "sha512-t2OU/dXXioARrC6yWfJ4hqB7rct14e8f7m0cbI5hUmDyyIlwv5vEtooptH8INkbLzOatzKuVbQmAYcbWoyz6Dg==",
|
||||
"version": "2.1.2",
|
||||
"resolved": "https://registry.npmjs.org/micromark-extension-gfm-table/-/micromark-extension-gfm-table-2.1.2.tgz",
|
||||
"integrity": "sha512-pRzm4kDTu0MjlmBkxmS9yYhw60nncfcEwu9NNdPFSQEFXS95ZKyIIyTSHu/o3ReBUrLKYEq+7YaXCRn/bPB4MA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
@@ -2694,9 +2697,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/micromark-factory-space": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/micromark-factory-space/-/micromark-factory-space-2.0.1.tgz",
|
||||
"integrity": "sha512-zRkxjtBxxLd2Sc0d+fbnEunsTj46SWXgXciZmHq0kDYGnck/ZSGj9/wULTV95uoeYiK5hRXP2mJ98Uo4cq/LQg==",
|
||||
"version": "2.1.0",
|
||||
"resolved": "https://registry.npmjs.org/micromark-factory-space/-/micromark-factory-space-2.1.0.tgz",
|
||||
"integrity": "sha512-fS8hnLIjnjvdQIj39Geug8wWsR0HrYZ43KShKxNfwT7t2LOHo/LbWZEzEaSOjwtjdCsjoE6syHhonEzW0zv0+Q==",
|
||||
"dev": true,
|
||||
"funding": [
|
||||
{
|
||||
@@ -2864,6 +2867,26 @@
|
||||
"micromark-util-symbol": "^2.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/micromark-util-edit-map": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/micromark-util-edit-map/-/micromark-util-edit-map-1.0.0.tgz",
|
||||
"integrity": "sha512-Pa2ljlsEL6sVwFaYeyrOLSYbQt73JvGbPOYFq+9AElXiSnfI5Q4465RRZ1sHv7lDjDOnGRDDaqPXqClqWK/q1Q==",
|
||||
"dev": true,
|
||||
"funding": [
|
||||
{
|
||||
"type": "GitHub Sponsors",
|
||||
"url": "https://github.com/sponsors/unifiedjs"
|
||||
},
|
||||
{
|
||||
"type": "OpenCollective",
|
||||
"url": "https://opencollective.com/unified"
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"micromark-util-types": "^2.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/micromark-util-encode": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/micromark-util-encode/-/micromark-util-encode-2.0.1.tgz",
|
||||
@@ -3001,9 +3024,9 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/micromark-util-types": {
|
||||
"version": "2.0.2",
|
||||
"resolved": "https://registry.npmjs.org/micromark-util-types/-/micromark-util-types-2.0.2.tgz",
|
||||
"integrity": "sha512-Yw0ECSpJoViF1qTU4DC6NwtC4aWGt1EkzaQB8KPPyCRR8z9TWeV0HbEFGTO+ZY1wB22zmxnJqhPyTpOVCpeHTA==",
|
||||
"version": "2.0.3",
|
||||
"resolved": "https://registry.npmjs.org/micromark-util-types/-/micromark-util-types-2.0.3.tgz",
|
||||
"integrity": "sha512-oxB2Ik03hI0gv+VNn9tnh1t1YEe9MDPptViAEgfdf3YQHsn0pzGTgCdlSCJXcwhqm8phaEuM7zeEu3QQzVBrPg==",
|
||||
"dev": true,
|
||||
"funding": [
|
||||
{
|
||||
@@ -3438,6 +3461,16 @@
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/re2js": {
|
||||
"version": "2.9.1",
|
||||
"resolved": "https://registry.npmjs.org/re2js/-/re2js-2.9.1.tgz",
|
||||
"integrity": "sha512-JIT3bEEUZTOR2YS1walNEIfH4cF/cQeZcBUFq7ldqO6lR6g0X5CBq/S8rsa9omzZcsNf8qc36jCkWpKKtncrZg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=20.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/require-directory": {
|
||||
"version": "2.1.1",
|
||||
"resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz",
|
||||
@@ -3705,9 +3738,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/sql.js": {
|
||||
"version": "1.15.2",
|
||||
"resolved": "https://registry.npmjs.org/sql.js/-/sql.js-1.15.2.tgz",
|
||||
"integrity": "sha512-ZmMYFsZPZWDKIJUh3A5rdnpRV3hB/r7AijwAzSzLnfv/9CSx4obUmDtA8brAjWJWjGtUVh43nIEJ+6nl6HuOUg==",
|
||||
"version": "1.16.0",
|
||||
"resolved": "https://registry.npmjs.org/sql.js/-/sql.js-1.16.0.tgz",
|
||||
"integrity": "sha512-q/JOZuJfmVh8Zf8Eo+cMJvtxAWeWBqTfJ6AQYGXZmcaLGHMwhA2niH3fQYHrBtPeOss1ttzHec07K5+rHaMRMw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/statuses": {
|
||||
@@ -3721,9 +3754,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/string-width": {
|
||||
"version": "8.2.1",
|
||||
"resolved": "https://registry.npmjs.org/string-width/-/string-width-8.2.1.tgz",
|
||||
"integrity": "sha512-IIaP0g3iy9Cyy18w3M9YcaDudujEAVHKt3a3QJg1+sr/oX96TbaGUubG0hJyCjCBThFH+tFpcIyoUHUn1ogaLA==",
|
||||
"version": "8.3.0",
|
||||
"resolved": "https://registry.npmjs.org/string-width/-/string-width-8.3.0.tgz",
|
||||
"integrity": "sha512-ZbmZM0JCihQN91dWnxoipT2KOEyHqEyfRXUyjuRhW8b/xnqPDoq4gWEVApTVa9db2wN8mmoikgFBbjh71+cGeQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
|
||||
+8
-7
@@ -88,6 +88,7 @@
|
||||
"docs/COMMAND-AGENT-MAP.md",
|
||||
"docs/HERMES-HOOKS.md",
|
||||
"docs/ROADMAP.md",
|
||||
"docs/MISTRAL-VIBE-GUIDE.md",
|
||||
"docs/design/ecc-memory-vault.md",
|
||||
"docs/design/context-profiles.md",
|
||||
"docs/design/context-carriers.md",
|
||||
@@ -570,7 +571,7 @@
|
||||
"@iarna/toml": "2.2.5",
|
||||
"ajv": "8.20.0",
|
||||
"js-yaml": "5.5.0",
|
||||
"sql.js": "1.15.2",
|
||||
"sql.js": "1.16.0",
|
||||
"zod": "4.6.7"
|
||||
},
|
||||
"pi": {
|
||||
@@ -588,14 +589,14 @@
|
||||
"@eslint/js": "9.39.2",
|
||||
"@opencode-ai/plugin": "1.4.3",
|
||||
"@types/node": "26.6.6",
|
||||
"@x402/core": "2.29.0",
|
||||
"@x402/evm": "2.29.0",
|
||||
"@x402/express": "2.29.0",
|
||||
"@x402/core": "2.31.0",
|
||||
"@x402/evm": "2.31.0",
|
||||
"@x402/express": "2.31.0",
|
||||
"c8": "11.0.0",
|
||||
"eslint": "10.13.0",
|
||||
"eslint": "10.15.0",
|
||||
"express": "4.22.3",
|
||||
"globals": "17.13.0",
|
||||
"markdownlint-cli": "0.49.1",
|
||||
"globals": "17.14.0",
|
||||
"markdownlint-cli": "0.50.0",
|
||||
"typescript": "6.0.3"
|
||||
},
|
||||
"engines": {
|
||||
|
||||
@@ -70,7 +70,6 @@ CELERY_TASK_TRACK_STARTED = True
|
||||
CELERY_TASK_TIME_LIMIT = 30 * 60 # Hard limit: 30 min
|
||||
CELERY_TASK_SOFT_TIME_LIMIT = 25 * 60 # Soft limit: sends SoftTimeLimitExceeded
|
||||
CELERY_WORKER_PREFETCH_MULTIPLIER = 1 # Prevent worker hoarding long tasks
|
||||
CELERY_TASK_ACKS_LATE = True # Re-queue on worker crash
|
||||
|
||||
# Result persistence
|
||||
CELERY_RESULT_EXPIRES = 60 * 60 * 24 # Keep results 24 hours
|
||||
@@ -199,6 +198,12 @@ def generate_pdf_report(self, report_id: int) -> str:
|
||||
raise
|
||||
```
|
||||
|
||||
### Delivery Guarantees
|
||||
|
||||
Late acknowledgement, worker-loss redelivery, and commit-aware publication are separate
|
||||
choices. Read [Delivery Reliability](references/reliability.md) before
|
||||
changing acknowledgement settings or publishing tasks from a database transaction.
|
||||
|
||||
## Calling Tasks
|
||||
|
||||
```python
|
||||
@@ -219,6 +224,25 @@ sync_contact_to_crm.apply_async(args=[contact.pk], queue='high_priority')
|
||||
result = generate_pdf_report.apply(args=[report.pk])
|
||||
```
|
||||
|
||||
### Publish After the Database Commits
|
||||
|
||||
A task published inside a Django transaction can run before its rows are visible or
|
||||
remain queued after rollback. Use `delay_on_commit()` or `apply_async_on_commit()`
|
||||
with Celery 5.4 or newer; use `transaction.on_commit()` on older versions. See
|
||||
[Delivery Reliability](references/reliability.md#publish-after-the-database-commits)
|
||||
for custom-base, task-ID, and transactional-outbox boundaries. Django's `TestCase`
|
||||
never commits, so these callbacks never run in tests unless captured; see
|
||||
[Test the On-Commit Contract](references/reliability.md#test-the-on-commit-contract).
|
||||
|
||||
```python
|
||||
from django.db import transaction
|
||||
|
||||
@transaction.atomic
|
||||
def create_user(validated_username: str):
|
||||
user = User.objects.create(username=validated_username)
|
||||
send_welcome_email.delay_on_commit(user.pk)
|
||||
```
|
||||
|
||||
## Beat Scheduling (Periodic Tasks)
|
||||
|
||||
### Code-Defined Schedule
|
||||
@@ -266,6 +290,11 @@ PeriodicTask.objects.update_or_create(
|
||||
)
|
||||
```
|
||||
|
||||
Run only one scheduler for a given schedule to avoid duplicate publications, but this
|
||||
does not prevent execution overlap: periodic tasks may overlap. Atomically claim an
|
||||
active-run lease with an owner and expiry or recovery path; a unique schedule row
|
||||
alone does not serialize executions. Keep the task idempotent if the lease expires.
|
||||
|
||||
## Canvas: Chaining and Grouping Tasks
|
||||
|
||||
```python
|
||||
@@ -294,7 +323,7 @@ result = chord(
|
||||
result.delay()
|
||||
```
|
||||
|
||||
## Error Handling and Dead Letter Queue
|
||||
## Failure Monitoring
|
||||
|
||||
```python
|
||||
# apps/core/tasks.py
|
||||
@@ -314,29 +343,8 @@ def on_task_failure(sender, task_id, exception, args, kwargs, traceback, einfo,
|
||||
sentry_sdk.capture_exception(exception)
|
||||
```
|
||||
|
||||
```python
|
||||
# Route failed tasks to dead-letter queue after max retries
|
||||
@shared_task(
|
||||
bind=True,
|
||||
max_retries=3,
|
||||
name='payments.charge_card',
|
||||
)
|
||||
def charge_card(self, order_id: int) -> None:
|
||||
from apps.payments.models import Order, FailedCharge
|
||||
|
||||
try:
|
||||
_do_charge(order_id)
|
||||
except Exception as exc:
|
||||
if self.request.retries >= self.max_retries:
|
||||
# Persist to dead-letter table for manual review
|
||||
FailedCharge.objects.create(
|
||||
order_id=order_id,
|
||||
error=str(exc),
|
||||
task_id=self.request.id,
|
||||
)
|
||||
return # Don't raise — task is permanently failed
|
||||
raise self.retry(exc=exc)
|
||||
```
|
||||
Returning after recording a final error makes Celery record `SUCCESS`; persist and
|
||||
re-raise instead. Broker dead-letter queues are not Django model error logs.
|
||||
|
||||
## Testing Celery Tasks
|
||||
|
||||
@@ -362,7 +370,14 @@ class TestSendWelcomeEmail:
|
||||
send_welcome_email(99999) # Non-existent user — must not raise
|
||||
```
|
||||
|
||||
### Integration Testing with CELERY_TASK_ALWAYS_EAGER
|
||||
### Django Integration Path with Eager Mode
|
||||
|
||||
Eager mode is a worker emulation, not a worker integration test. Use it to verify
|
||||
that a Django request selects the expected task and arguments, but do not use it as
|
||||
evidence for serialization, routing, acknowledgement, retry, or worker-loss behavior.
|
||||
It also does not prove post-commit dispatch: under `django_db` the test transaction
|
||||
never commits, so a view that publishes with `delay_on_commit()` runs nothing unless
|
||||
the request is wrapped in `django_capture_on_commit_callbacks(execute=True)`.
|
||||
|
||||
```python
|
||||
# config/settings/test.py
|
||||
@@ -371,17 +386,26 @@ CELERY_TASK_EAGER_PROPAGATES = True # Re-raise exceptions from tasks
|
||||
|
||||
# tests/test_integration.py
|
||||
@pytest.mark.django_db
|
||||
def test_registration_triggers_welcome_email(client):
|
||||
def test_registration_triggers_welcome_email(client, django_capture_on_commit_callbacks):
|
||||
with patch('apps.notifications.services.EmailService') as mock_email:
|
||||
response = client.post('/api/users/', {
|
||||
'email': 'new@example.com',
|
||||
'password': 'strongpass123',
|
||||
})
|
||||
with django_capture_on_commit_callbacks(execute=True):
|
||||
response = client.post('/api/users/', {
|
||||
'email': 'new@example.com',
|
||||
'password': 'strongpass123',
|
||||
})
|
||||
|
||||
assert response.status_code == 201
|
||||
mock_email.send_welcome.assert_called_once()
|
||||
```
|
||||
|
||||
### Worker Integration with a Real Broker
|
||||
|
||||
Use Celery's `celery_worker` pytest fixture with a real broker and result backend for
|
||||
the delivery boundary. Cover serialization, routing, retry behavior, and any
|
||||
acknowledgement or redelivery options the application enables. Keep this suite
|
||||
separate from fast unit tests so a passing eager-mode test is never mistaken for
|
||||
worker evidence.
|
||||
|
||||
### Testing Retries
|
||||
|
||||
```python
|
||||
@@ -428,14 +452,27 @@ def charge_and_fulfill(order_id):
|
||||
order.charge() # May charge twice if task retries!
|
||||
order.fulfill()
|
||||
|
||||
# GOOD: Idempotent with status guard
|
||||
@shared_task
|
||||
def charge_and_fulfill(order_id):
|
||||
order = Order.objects.select_for_update().get(pk=order_id)
|
||||
if order.status != Order.Status.PENDING:
|
||||
return # Already processed
|
||||
order.charge()
|
||||
order.fulfill()
|
||||
# GOOD: Claim ownership before external I/O, then finalize only as that owner
|
||||
from django.db import transaction
|
||||
from apps.payments.gateway import gateway
|
||||
|
||||
@shared_task(bind=True, acks_late=True)
|
||||
def charge_and_fulfill(self, order_id):
|
||||
attempt_id = self.request.id # Stable across Celery retry and redelivery
|
||||
with transaction.atomic():
|
||||
order = Order.objects.select_for_update().get(pk=order_id)
|
||||
if not order.claim_or_resume_charge(attempt_id):
|
||||
return
|
||||
|
||||
# The adapter validates provider data and returns the same charge on retry.
|
||||
receipt = gateway.charge(order_id, idempotency_key=f'order:{order_id}')
|
||||
|
||||
with transaction.atomic():
|
||||
order = Order.objects.select_for_update().get(pk=order_id)
|
||||
if order.charge_attempt_id != attempt_id:
|
||||
return
|
||||
order.record_charge(receipt)
|
||||
order.fulfill()
|
||||
```
|
||||
|
||||
## Production Checklist
|
||||
@@ -443,13 +480,23 @@ def charge_and_fulfill(order_id):
|
||||
| Check | Setting |
|
||||
|-------|---------|
|
||||
| Worker restarts on crash | `supervisord` or `systemd` unit |
|
||||
| `CELERY_TASK_ACKS_LATE = True` | Re-queue tasks on worker crash |
|
||||
| Late acknowledgement | Per task, only after proving idempotency; duplicates remain possible |
|
||||
| Worker-loss redelivery | `task_reject_on_worker_lost`, opt in only with poison-task protection |
|
||||
| `CELERY_WORKER_PREFETCH_MULTIPLIER = 1` | Fair distribution of long tasks |
|
||||
| Separate queues per priority | `-Q default,high_priority,low_priority` |
|
||||
| `CELERY_TASK_SOFT_TIME_LIMIT` set | Graceful timeout before hard kill |
|
||||
| Sentry integration | Capture all `task_failure` signals |
|
||||
| Flower or other monitor | Visibility into queue depths |
|
||||
| Beat runs on single node only | Prevents duplicate scheduled task execution |
|
||||
| Beat runs on single node only | Prevents duplicate scheduled task publication |
|
||||
| Periodic-task locking | Prevents overlapping execution when required |
|
||||
|
||||
## References
|
||||
|
||||
- [Celery task acknowledgement and idempotency](https://docs.celeryq.dev/en/stable/userguide/tasks.html)
|
||||
- [Celery configuration defaults](https://docs.celeryq.dev/en/stable/userguide/configuration.html)
|
||||
- [Celery with Django transaction handling](https://docs.celeryq.dev/en/stable/django/first-steps-with-django.html)
|
||||
- [Celery periodic tasks](https://docs.celeryq.dev/en/stable/userguide/periodic-tasks.html)
|
||||
- [Celery testing guide](https://docs.celeryq.dev/en/stable/userguide/testing.html)
|
||||
|
||||
## Related Skills
|
||||
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
# Delivery Reliability
|
||||
|
||||
Read this reference when changing acknowledgement settings, worker-loss behavior,
|
||||
or task publication around Django database transactions.
|
||||
|
||||
## Acknowledgement and Worker Loss
|
||||
|
||||
Celery acknowledges task messages before execution by default. Opt in to late
|
||||
acknowledgement only for idempotent tasks that are safe to execute more than once:
|
||||
|
||||
```python
|
||||
@shared_task(
|
||||
name='orders.mark_shipped',
|
||||
acks_late=True,
|
||||
)
|
||||
def mark_order_shipped(order_id: int, tracking_number: str) -> None:
|
||||
# Use an idempotent implementation such as the guarded update in SKILL.md.
|
||||
...
|
||||
```
|
||||
|
||||
Late acknowledgement means the task may execute more than once if delivery is
|
||||
interrupted. It does not by itself guarantee redelivery when a worker child exits
|
||||
abruptly. Celery acknowledges worker-loss messages unless
|
||||
`task_reject_on_worker_lost` (or Django's
|
||||
`CELERY_TASK_REJECT_ON_WORKER_LOST`) is enabled. That option can cause message loops
|
||||
for poison tasks, so enable it only after validating idempotency and monitoring the
|
||||
redelivery path. Failure and timeout acknowledgement behavior is controlled
|
||||
separately by `task_acks_on_failure_or_timeout`, which applies only to tasks using
|
||||
late acknowledgement.
|
||||
|
||||
## Publish After the Database Commits
|
||||
|
||||
With Celery 5.4 or newer, `delay_on_commit()` and `apply_async_on_commit()` are
|
||||
available for tasks based on `DjangoTask`. Custom task base classes must inherit from
|
||||
`DjangoTask` to expose this API. These methods do not return a task ID because the
|
||||
message is not published until commit.
|
||||
|
||||
For older Celery versions, or to keep the publication visible at the call site,
|
||||
register it explicitly:
|
||||
|
||||
```python
|
||||
from functools import partial
|
||||
from django.db import transaction
|
||||
|
||||
transaction.on_commit(
|
||||
partial(
|
||||
sync_contact_to_crm.apply_async,
|
||||
args=[contact.pk],
|
||||
queue='high_priority',
|
||||
)
|
||||
)
|
||||
```
|
||||
|
||||
An on-commit callback avoids publication on rollback, but it does not make the
|
||||
database commit and broker publish atomic. If task delivery must not be lost when a
|
||||
publish fails after commit, use a transactional outbox with a separate publisher.
|
||||
|
||||
## Test the On-Commit Contract
|
||||
|
||||
Django's `TestCase` wraps each test in a transaction that is rolled back, never
|
||||
committed, so `transaction.on_commit()` callbacks (including `delay_on_commit()`)
|
||||
never run. A test that only checks the new database row still passes when the task
|
||||
is never queued. Capture the callbacks, execute them, and assert the Celery call:
|
||||
|
||||
```python
|
||||
from unittest.mock import patch
|
||||
|
||||
from django.contrib.auth.models import User
|
||||
from django.test import TestCase
|
||||
|
||||
from apps.users.services import create_user
|
||||
from apps.users.tasks import send_welcome_email
|
||||
|
||||
|
||||
class CreateUserTests(TestCase):
|
||||
def test_queues_welcome_email_after_commit(self):
|
||||
# Patch before the call: delay_on_commit() binds task.delay when it registers.
|
||||
with patch.object(send_welcome_email, 'delay') as mock_delay:
|
||||
with self.captureOnCommitCallbacks(execute=True) as callbacks:
|
||||
create_user('bob')
|
||||
mock_delay.assert_not_called() # Not published before commit
|
||||
|
||||
user = User.objects.get(username='bob')
|
||||
self.assertEqual(len(callbacks), 1)
|
||||
mock_delay.assert_called_once_with(user.pk)
|
||||
```
|
||||
|
||||
`captureOnCommitCallbacks()` is available on `TestCase` in Django 3.2 or newer. With
|
||||
pytest-django, the `django_capture_on_commit_callbacks` fixture provides the same
|
||||
context manager inside `@pytest.mark.django_db` tests.
|
||||
|
||||
Use `TransactionTestCase`, or `@pytest.mark.django_db(transaction=True)`, only when a
|
||||
test needs a real commit: for example, when a real Celery worker in another thread
|
||||
or process must read the committed rows. Those tests commit for real, so on-commit
|
||||
callbacks run when the outermost `atomic()` block commits, and Django resets the
|
||||
database afterwards by truncating tables, which is much slower. Keep them for the
|
||||
worker integration boundary and use `TestCase` with captured callbacks elsewhere.
|
||||
@@ -10,7 +10,7 @@
|
||||
"active": { "const": false },
|
||||
"disposition": { "const": "proposed" },
|
||||
"nativeSupport": { "const": "unobserved" },
|
||||
"target": { "enum": ["adal", "antigravity", "claude", "claude-project", "codebuddy", "codex", "copilot", "cursor", "gemini", "grok", "hermes", "joycode", "kimi", "openclaw", "opencode", "pi", "qwen", "zed"] },
|
||||
"target": { "enum": ["adal", "antigravity", "antigravity-home", "claude", "claude-project", "codebuddy", "codex", "copilot", "cursor", "gemini", "grok", "hermes", "joycode", "kimi", "mistral-vibe", "openclaw", "opencode", "pi", "qwen", "zed"] },
|
||||
"profileId": { "enum": ["lean@1", "full@1"] },
|
||||
"selectionMode": { "enum": ["manual", "suggest", "auto"] },
|
||||
"registryDigest": { "$ref": "#/definitions/digest" },
|
||||
|
||||
@@ -22,6 +22,7 @@
|
||||
"claude-project",
|
||||
"cursor",
|
||||
"antigravity",
|
||||
"antigravity-home",
|
||||
"codex",
|
||||
"copilot",
|
||||
"gemini",
|
||||
@@ -34,7 +35,8 @@
|
||||
"openclaw",
|
||||
"kimi",
|
||||
"grok",
|
||||
"adal"
|
||||
"adal",
|
||||
"mistral-vibe"
|
||||
]
|
||||
},
|
||||
"profile": {
|
||||
|
||||
@@ -52,6 +52,7 @@
|
||||
"claude-project",
|
||||
"cursor",
|
||||
"antigravity",
|
||||
"antigravity-home",
|
||||
"codex",
|
||||
"copilot",
|
||||
"gemini",
|
||||
@@ -63,7 +64,8 @@
|
||||
"hermes",
|
||||
"openclaw",
|
||||
"kimi",
|
||||
"adal"
|
||||
"adal",
|
||||
"mistral-vibe"
|
||||
]
|
||||
}
|
||||
},
|
||||
|
||||
@@ -0,0 +1,475 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Check OpenSpec freshness at FILE level.
|
||||
*
|
||||
* ── v1 contract ─────────────────────────────────────────────────
|
||||
* For each spec file under <root>/openspec/, parse its `<!-- enforced: -->`
|
||||
* anchors and the `Last verified:` date, then ask git whether the anchor's
|
||||
* TARGET FILE changed after that date. This is a FILE-LEVEL freshness check:
|
||||
* the `::symbol` part of an anchor is recorded but never resolved — verifying
|
||||
* that a symbol exists inside a file is out of scope for v1.
|
||||
*
|
||||
* Truthful verdicts (a spec resolves to the strongest of these):
|
||||
* FRESH every enforced target exists, is inside the project, is
|
||||
* committed, and has not changed since `Last verified`
|
||||
* STALE an enforced target changed after `Last verified`, or the
|
||||
* verification itself is older than ECC_SPEC_STALE_DAYS
|
||||
* ORPHANED an enforced target file is missing from the tree or escapes
|
||||
* the project (via `..` or a symlink out of the root)
|
||||
* UNVERIFIED no git / not a repo / SHALLOW clone / missing or invalid
|
||||
* `Last verified` date / target file never committed — i.e.
|
||||
* evidence is unavailable, NOT a sign of staleness
|
||||
* UNKNOWN an enforced anchor does not parse to path::symbol
|
||||
*
|
||||
* Safety:
|
||||
* - git is always invoked through execFileSync with an argv array. Paths are
|
||||
* passed after `--`; the date is validated to YYYY-MM-DD first and passed
|
||||
* as a single argument. Nothing from spec Markdown reaches a shell.
|
||||
* - the project root must not be a symlink; every enforced target is resolved
|
||||
* through fs.realpathSync and must stay inside the real project root.
|
||||
* - shallow clones report UNVERIFIED — incomplete history is never
|
||||
* mislabelled ORPHANED or STALE.
|
||||
* - code is never declarative: fenced code blocks (``` / ~~~) and inline
|
||||
* code spans (`...`) are stripped before anchor/date sweeps, so an
|
||||
* example showing the anchor syntax never becomes an enforced target.
|
||||
*
|
||||
* Exit contract:
|
||||
* 0 = no stale specs (or ECC_SPEC_STALE_WARN_ONLY === "true")
|
||||
* 1 = at least one stale spec (STALE only; ORPHANED/UNVERIFIED are reported,
|
||||
* not gating failures)
|
||||
* 2 = configuration / input error
|
||||
*
|
||||
* Output: single JSON line to stdout {specs[], staleCount, totalCount}
|
||||
* Diagnostics: all prose to stderr
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { execFileSync } = require('child_process');
|
||||
|
||||
// ── CLI args & env ──────────────────────────────────────────────
|
||||
|
||||
function resolveProjectRoot() {
|
||||
const rootIdx = process.argv.indexOf('--project-root');
|
||||
if (rootIdx !== -1 && rootIdx + 1 < process.argv.length) {
|
||||
return process.argv[rootIdx + 1];
|
||||
}
|
||||
if (process.env.ECC_SPEC_PROJECT_ROOT) {
|
||||
return process.env.ECC_SPEC_PROJECT_ROOT;
|
||||
}
|
||||
return process.cwd();
|
||||
}
|
||||
|
||||
function resolveStaleDays() {
|
||||
const envVal = process.env.ECC_SPEC_STALE_DAYS;
|
||||
if (envVal === undefined || envVal === '') {
|
||||
return 30; // Default
|
||||
}
|
||||
// Strict integer (reject "1.5", "0x10", "+3", etc.), not parseInt coercion.
|
||||
if (!/^\d+$/.test(envVal)) {
|
||||
console.error(`FATAL: ECC_SPEC_STALE_DAYS must be an integer 1-365, got: "${envVal}"`);
|
||||
process.exit(2);
|
||||
}
|
||||
const days = parseInt(envVal, 10);
|
||||
if (days <= 0 || days > 365) {
|
||||
console.error(`FATAL: ECC_SPEC_STALE_DAYS must be an integer 1-365, got: "${envVal}"`);
|
||||
process.exit(2);
|
||||
}
|
||||
return days;
|
||||
}
|
||||
|
||||
const WARN_ONLY = process.env.ECC_SPEC_STALE_WARN_ONLY === 'true';
|
||||
|
||||
function die(message) {
|
||||
console.error(`FATAL: ${message}`);
|
||||
process.exit(2);
|
||||
}
|
||||
|
||||
// ── Root validation (real-path contained) ───────────────────────
|
||||
|
||||
const projectRootArg = resolveProjectRoot();
|
||||
const staleDays = resolveStaleDays();
|
||||
|
||||
let rootStat;
|
||||
try {
|
||||
rootStat = fs.lstatSync(projectRootArg);
|
||||
} catch (err) {
|
||||
die(`Cannot access --project-root: ${projectRootArg} (${err.message})`);
|
||||
}
|
||||
if (!rootStat.isDirectory()) {
|
||||
die(`--project-root is not a directory: ${projectRootArg}`);
|
||||
}
|
||||
if (rootStat.isSymbolicLink()) {
|
||||
die(`--project-root must not be a symlink: ${projectRootArg}`);
|
||||
}
|
||||
|
||||
const projectRoot = fs.realpathSync(projectRootArg);
|
||||
const openspecDir = path.join(projectRoot, 'openspec');
|
||||
|
||||
// ── v1 parsing constants ────────────────────────────────────────
|
||||
|
||||
const ENFORCED_RE = /<!--\s*enforced:\s*(.*?)\s*-->/g;
|
||||
const LAST_VERIFIED_RE = /^[>\s]*last\s+verified:\s*(.*)$/im;
|
||||
|
||||
/** Parse `path::symbol`; reject whitespace, absolute paths, `..`, backslashes. */
|
||||
function parseAnchor(raw) {
|
||||
const trimmed = raw.trim();
|
||||
if (trimmed === '' || /\s/.test(trimmed)) {
|
||||
return { invalid: true, reason: 'must not contain whitespace' };
|
||||
}
|
||||
const sep = trimmed.indexOf('::');
|
||||
if (sep <= 0 || trimmed.slice(sep + 2) === '') {
|
||||
return { invalid: true, reason: 'expected <path>::<symbol>' };
|
||||
}
|
||||
const anchorPath = trimmed.slice(0, sep);
|
||||
const symbol = trimmed.slice(sep + 2);
|
||||
if (anchorPath.startsWith('/')) {
|
||||
return { invalid: true, reason: 'path must be repo-relative (no leading "/")' };
|
||||
}
|
||||
if (anchorPath.includes('\\')) {
|
||||
return { invalid: true, reason: 'path must use forward slashes' };
|
||||
}
|
||||
if (anchorPath.split('/').includes('..')) {
|
||||
return { invalid: true, reason: 'path must not traverse outside the project ("../")' };
|
||||
}
|
||||
return { path: anchorPath, symbol };
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a `Last verified` value as an EXACT YYYY-MM-DD calendar date.
|
||||
*
|
||||
* Strict on purpose: a prefix-extracting regex would accept trailing junk
|
||||
* ("2024-03-01; rm -rf /"), and `new Date("2026-02-30")` silently rolls
|
||||
* impossible dates over into the next month. Both would let malformed or
|
||||
* future evidence look verified. So: full-string match, UTC round-trip of
|
||||
* the components, and no future dates.
|
||||
*/
|
||||
function parseVerifiedDate(rawValue) {
|
||||
const m = rawValue.trim().match(/^(\d{4})-(\d{2})-(\d{2})$/);
|
||||
if (!m) return null;
|
||||
const year = Number(m[1]);
|
||||
const month = Number(m[2]);
|
||||
const day = Number(m[3]);
|
||||
const time = Date.UTC(year, month - 1, day);
|
||||
if (Number.isNaN(time)) return null;
|
||||
const roundTripped = new Date(time);
|
||||
if (
|
||||
roundTripped.getUTCFullYear() !== year ||
|
||||
roundTripped.getUTCMonth() !== month - 1 ||
|
||||
roundTripped.getUTCDate() !== day
|
||||
) {
|
||||
return null; // impossible date (e.g. 2026-02-30 normalized by Date)
|
||||
}
|
||||
if (time > Date.now()) return null; // future evidence cannot be verified
|
||||
return { date: `${m[1]}-${m[2]}-${m[3]}`, time };
|
||||
}
|
||||
|
||||
function isInside(base, candidate) {
|
||||
const rel = path.relative(base, candidate);
|
||||
return rel === '' || (!rel.startsWith(`..${path.sep}`) && rel !== '..' && !path.isAbsolute(rel));
|
||||
}
|
||||
|
||||
// ── Git helpers (argv only, never a shell string) ───────────────
|
||||
|
||||
let gitState = null;
|
||||
|
||||
function gitProbe() {
|
||||
if (gitState !== null) return gitState;
|
||||
gitState = { available: false, repo: false, shallow: false };
|
||||
try {
|
||||
execFileSync('git', ['--version'], { stdio: 'ignore', cwd: projectRoot });
|
||||
gitState.available = true;
|
||||
} catch {
|
||||
return gitState;
|
||||
}
|
||||
try {
|
||||
execFileSync('git', ['rev-parse', '--git-dir'], { stdio: 'ignore', cwd: projectRoot });
|
||||
gitState.repo = true;
|
||||
} catch {
|
||||
return gitState;
|
||||
}
|
||||
try {
|
||||
const out = execFileSync('git', ['rev-parse', '--is-shallow-repository'], {
|
||||
encoding: 'utf8',
|
||||
cwd: projectRoot,
|
||||
stdio: ['pipe', 'pipe', 'pipe'],
|
||||
}).trim();
|
||||
gitState.shallow = out === 'true';
|
||||
} catch {
|
||||
gitState.shallow = false;
|
||||
}
|
||||
return gitState;
|
||||
}
|
||||
|
||||
/** stdout of `git log --format=%H --after=<date> -- <path>` (empty when none). */
|
||||
function gitHashesAfter(date, anchorPath) {
|
||||
const out = execFileSync(
|
||||
'git',
|
||||
['log', '--format=%H', `--after=${date}`, '--', anchorPath],
|
||||
{ encoding: 'utf8', cwd: projectRoot, stdio: ['pipe', 'pipe', 'pipe'] }
|
||||
);
|
||||
return out.trim().split('\n').filter(Boolean);
|
||||
}
|
||||
|
||||
function gitAllHashes(anchorPath) {
|
||||
const out = execFileSync(
|
||||
'git',
|
||||
['log', '--format=%H', '--', anchorPath],
|
||||
{ encoding: 'utf8', cwd: projectRoot, stdio: ['pipe', 'pipe', 'pipe'] }
|
||||
);
|
||||
return out.trim().split('\n').filter(Boolean);
|
||||
}
|
||||
|
||||
/**
|
||||
* File-level freshness for one enforced target.
|
||||
* @returns {{ status: string, reason?: string }}
|
||||
*/
|
||||
function targetFreshness(anchorPath) {
|
||||
const probe = gitProbe();
|
||||
if (!probe.available || !probe.repo) {
|
||||
return { status: 'UNVERIFIED', reason: 'git unavailable or not a repository' };
|
||||
}
|
||||
if (probe.shallow) {
|
||||
return { status: 'UNVERIFIED', reason: 'shallow clone — history incomplete' };
|
||||
}
|
||||
|
||||
const resolved = path.resolve(projectRoot, anchorPath);
|
||||
if (!isInside(projectRoot, resolved)) {
|
||||
return { status: 'ORPHANED', reason: `target escapes project root: ${anchorPath}` };
|
||||
}
|
||||
|
||||
let real;
|
||||
try {
|
||||
real = fs.realpathSync(resolved);
|
||||
} catch {
|
||||
return { status: 'ORPHANED', reason: `target file not found: ${anchorPath}` };
|
||||
}
|
||||
if (!isInside(projectRoot, real)) {
|
||||
return { status: 'ORPHANED', reason: `target resolves outside project (symlink): ${anchorPath}` };
|
||||
}
|
||||
|
||||
let all;
|
||||
try {
|
||||
all = gitAllHashes(anchorPath);
|
||||
} catch (err) {
|
||||
return { status: 'UNVERIFIED', reason: `git error: ${err.message}` };
|
||||
}
|
||||
if (all.length === 0) {
|
||||
return { status: 'UNVERIFIED', reason: `target has no git history: ${anchorPath}` };
|
||||
}
|
||||
return { status: 'FRESH' }; // changed-after is decided by the caller with the date
|
||||
}
|
||||
|
||||
// ── Spec walking & parsing ──────────────────────────────────────
|
||||
|
||||
function walkMdFiles(dir) {
|
||||
const results = [];
|
||||
if (!fs.existsSync(dir)) return results;
|
||||
let stat;
|
||||
try {
|
||||
stat = fs.statSync(dir);
|
||||
} catch {
|
||||
return results;
|
||||
}
|
||||
if (!stat.isDirectory()) return results;
|
||||
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
||||
const fullPath = path.join(dir, entry.name);
|
||||
if (entry.isDirectory()) {
|
||||
results.push(...walkMdFiles(fullPath));
|
||||
} else if (entry.isFile() && entry.name.endsWith('.md')) {
|
||||
results.push(fullPath);
|
||||
}
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove fenced code blocks (``` / ~~~, up to 3 leading spaces) and inline
|
||||
* code spans (`...`, no newlines inside). Content inside code is illustrative
|
||||
* and must never be collected as enforced anchors or a Last verified date.
|
||||
* Fenced blocks are replaced with an equal number of blank lines so that
|
||||
* line-oriented matches downstream keep working on the same line numbers.
|
||||
*/
|
||||
function stripCodeSpans(content) {
|
||||
const withoutFences = content.replace(
|
||||
/^[ \t]{0,3}(`{3,}|~{3,})[^\n]*\n[\s\S]*?^[ \t]{0,3}\1[ \t]*$/gm,
|
||||
(block) => '\n'.repeat(block.split('\n').length - 1)
|
||||
);
|
||||
return withoutFences.replace(/`[^`\n]*`/g, '');
|
||||
}
|
||||
|
||||
function parseSpecFile(filePath) {
|
||||
let content;
|
||||
try {
|
||||
content = fs.readFileSync(filePath, 'utf8');
|
||||
} catch {
|
||||
return { error: 'unreadable' };
|
||||
}
|
||||
|
||||
// Code blocks/spans are illustrative, never declarative.
|
||||
const declarative = stripCodeSpans(content);
|
||||
|
||||
const enforced = [];
|
||||
let m;
|
||||
const re = new RegExp(ENFORCED_RE.source, 'g');
|
||||
while ((m = re.exec(declarative)) !== null) {
|
||||
enforced.push(m[1].trim());
|
||||
}
|
||||
|
||||
const lv = declarative.match(LAST_VERIFIED_RE);
|
||||
const lastVerifiedRaw = lv ? lv[1].trim() : null;
|
||||
|
||||
return { enforced, lastVerifiedRaw, error: null };
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns {{ status, path, lastVerified?, enforced?, reasons? }}
|
||||
*/
|
||||
function evaluateSpec(relPath, parsed) {
|
||||
const { enforced, lastVerifiedRaw } = parsed;
|
||||
const base = { path: relPath };
|
||||
|
||||
if (lastVerifiedRaw === null) {
|
||||
return {
|
||||
...base,
|
||||
status: 'UNVERIFIED',
|
||||
enforced: enforced.length > 0 ? enforced : undefined,
|
||||
reasons: ['missing "Last verified:" date'],
|
||||
};
|
||||
}
|
||||
|
||||
const verified = parseVerifiedDate(lastVerifiedRaw);
|
||||
if (!verified) {
|
||||
return {
|
||||
...base,
|
||||
status: 'UNVERIFIED',
|
||||
enforced: enforced.length > 0 ? enforced : undefined,
|
||||
lastVerified: lastVerifiedRaw,
|
||||
reasons: [`unparseable "Last verified:" value: "${lastVerifiedRaw}"`],
|
||||
};
|
||||
}
|
||||
|
||||
if (enforced.length === 0) {
|
||||
return { ...base, status: 'FRESH', lastVerified: verified.date };
|
||||
}
|
||||
|
||||
// Repository/history availability is decided BEFORE any staleness rule:
|
||||
// an old verification date must never downgrade "evidence unavailable" to
|
||||
// STALE (the weight table could not repair that — STALE outranks UNVERIFIED).
|
||||
const probe = gitProbe();
|
||||
if (!probe.available || !probe.repo || probe.shallow) {
|
||||
const reason = !probe.available
|
||||
? 'git is not available'
|
||||
: !probe.repo
|
||||
? 'project root is not a git repository'
|
||||
: 'shallow clone — history incomplete';
|
||||
return {
|
||||
...base,
|
||||
status: 'UNVERIFIED',
|
||||
enforced,
|
||||
lastVerified: verified.date,
|
||||
reasons: [reason],
|
||||
};
|
||||
}
|
||||
|
||||
const ageDays = (Date.now() - verified.time) / 86400000;
|
||||
const reasons = [];
|
||||
const weights = { STALE: 4, ORPHANED: 3, UNVERIFIED: 2, UNKNOWN: 1, FRESH: 0 };
|
||||
let status = 'FRESH';
|
||||
const bump = (s) => {
|
||||
if (weights[s] > weights[status]) status = s;
|
||||
};
|
||||
|
||||
for (const raw of enforced) {
|
||||
const anchor = parseAnchor(raw);
|
||||
if (anchor.invalid) {
|
||||
bump('UNKNOWN');
|
||||
reasons.push(`invalid enforced anchor "${raw}" (${anchor.reason})`);
|
||||
continue;
|
||||
}
|
||||
// Evidence availability for THIS target comes before the age rule: an
|
||||
// uncommitted target (no history) is UNVERIFIED no matter how old the
|
||||
// date is — missing history is not staleness.
|
||||
const verdict = targetFreshness(anchor.path);
|
||||
if (verdict.status !== 'FRESH') {
|
||||
bump(verdict.status);
|
||||
reasons.push(`"${anchor.path}": ${verdict.reason}`);
|
||||
continue;
|
||||
}
|
||||
// History is complete and the target is committed: now staleness rules
|
||||
// apply — age threshold first, then change-after-verification.
|
||||
if (ageDays > staleDays) {
|
||||
bump('STALE');
|
||||
reasons.push(`Last verified ${Math.round(ageDays)} days ago (threshold: ${staleDays} days)`);
|
||||
}
|
||||
// File exists & is committed: was it changed after the verification date?
|
||||
let changed;
|
||||
try {
|
||||
changed = gitHashesAfter(verified.date, anchor.path).length > 0;
|
||||
} catch (err) {
|
||||
bump('UNVERIFIED');
|
||||
reasons.push(`"${anchor.path}": git error: ${err.message}`);
|
||||
continue;
|
||||
}
|
||||
if (changed) {
|
||||
bump('STALE');
|
||||
reasons.push(`"${anchor.path}" changed after last verified ${verified.date}`);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
...base,
|
||||
status,
|
||||
enforced,
|
||||
lastVerified: verified.date,
|
||||
reasons: reasons.length > 0 ? reasons : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
// ── Main ────────────────────────────────────────────────────────
|
||||
|
||||
function main() {
|
||||
if (!fs.existsSync(openspecDir)) {
|
||||
console.log(JSON.stringify({ specs: [], staleCount: 0, totalCount: 0 }));
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
const mdFiles = walkMdFiles(openspecDir);
|
||||
if (mdFiles.length === 0) {
|
||||
console.log(JSON.stringify({ specs: [], staleCount: 0, totalCount: 0 }));
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
const specs = [];
|
||||
for (const filePath of mdFiles) {
|
||||
const parsed = parseSpecFile(filePath);
|
||||
const relPath = path.relative(openspecDir, filePath);
|
||||
if (parsed.error) {
|
||||
specs.push({ path: relPath, status: 'UNKNOWN' });
|
||||
console.error(`WARNING: could not parse ${relPath}: ${parsed.error}`);
|
||||
continue;
|
||||
}
|
||||
specs.push(evaluateSpec(relPath, parsed));
|
||||
}
|
||||
|
||||
const staleCount = specs.filter((s) => s.status === 'STALE').length;
|
||||
const result = { specs, staleCount, totalCount: specs.length };
|
||||
|
||||
for (const spec of specs) {
|
||||
if (spec.reasons) {
|
||||
console.error(`INFO: ${spec.path}: ${spec.status} — ${spec.reasons.join('; ')}`);
|
||||
}
|
||||
}
|
||||
console.error(`Checked ${specs.length} spec(s): ${staleCount} stale.`);
|
||||
|
||||
console.log(JSON.stringify(result));
|
||||
|
||||
if (staleCount > 0 && !WARN_ONLY) {
|
||||
process.exit(1);
|
||||
}
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -0,0 +1,364 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Validate OpenSpec markdown against the v1 schema contract.
|
||||
*
|
||||
* ── v1 schema contract (source of truth) ─────────────────────────
|
||||
* Baseline spec file (contains Requirement/Invariant blocks):
|
||||
* - `### Requirement: <title>` MUST have at least one
|
||||
* `#### Scenario: <name>` child.
|
||||
* - `### Invariant: <title>` MUST carry an `<!-- enforced: -->` anchor.
|
||||
* - YAML frontmatter is OPTIONAL. When present it is not validated here.
|
||||
* Delta file (contains `<!-- ADDED: -->`, `<!-- MODIFIED: -->`,
|
||||
* `<!-- REMOVED: -->` markers):
|
||||
* - Each DECLARED block MUST be non-empty. An empty block is an error even
|
||||
* when a later block has content.
|
||||
*
|
||||
* Metadata HTML comments — keys are an explicit allowlist:
|
||||
* id, entities, enforced, test, depends_on, triggers, verified_by,
|
||||
* status, removal_reason, deferred, uncertainty
|
||||
* - key on the allowlist → metadata (no value rule beyond non-marker)
|
||||
* - key machine-shaped (`[a-z][a-z0-9_-]*`) but NOT on the allowlist
|
||||
* → ERROR (typo guard)
|
||||
* - everything else (`Note:`, `TODO:`, no colon) → ordinary comment, allowed
|
||||
* ADDED/MODIFIED/REMOVED are structural delta markers, not metadata.
|
||||
*
|
||||
* Code is never declarative:
|
||||
* Content inside fenced code blocks (``` / ~~~) and inline code spans
|
||||
* (`...`) is illustrative. It is stripped before any comment/anchor/marker
|
||||
* sweep, so an example showing the anchor or delta syntax is never
|
||||
* validated as a declaration and never marks a block as non-empty.
|
||||
*
|
||||
* Enforced anchor grammar:
|
||||
* <!-- enforced: <repo-relative/path.ext>::<symbol> -->
|
||||
* relative path + symbol, no whitespace, no leading "/", no "../" or
|
||||
* backslash traversal. This is the FILE-LEVEL anchor; symbol resolution is
|
||||
* out of scope for v1 (freshness checks target the file, not the symbol).
|
||||
*
|
||||
* Output: single JSON line to stdout {valid, errors[]}
|
||||
* Diagnostics: all prose to stderr
|
||||
* Exit: 0 = valid, 1 = one or more validation errors, 2 = config/input error
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
// ── CLI args & env ──────────────────────────────────────────────
|
||||
|
||||
function resolveOpenspecRoot() {
|
||||
const rootIdx = process.argv.indexOf('--openspec-root');
|
||||
if (rootIdx !== -1 && rootIdx + 1 < process.argv.length) {
|
||||
return process.argv[rootIdx + 1];
|
||||
}
|
||||
if (process.env.ECC_OPENSPEC_ROOT) {
|
||||
return process.env.ECC_OPENSPEC_ROOT;
|
||||
}
|
||||
return process.cwd();
|
||||
}
|
||||
|
||||
const openspecRoot = resolveOpenspecRoot();
|
||||
|
||||
function die(message, exitCode) {
|
||||
console.error(`FATAL: ${message}`);
|
||||
process.exit(exitCode);
|
||||
}
|
||||
|
||||
try {
|
||||
const stat = fs.statSync(openspecRoot);
|
||||
if (!stat.isDirectory()) {
|
||||
die(`--openspec-root is not a directory: ${openspecRoot}`, 2);
|
||||
}
|
||||
} catch (err) {
|
||||
die(`Cannot access --openspec-root: ${openspecRoot} (${err.message})`, 2);
|
||||
}
|
||||
|
||||
const openspecDir = path.join(openspecRoot, 'openspec');
|
||||
|
||||
// ── v1 schema constants ─────────────────────────────────────────
|
||||
|
||||
const METADATA_ALLOWLIST = new Set([
|
||||
'id',
|
||||
'entities',
|
||||
'enforced',
|
||||
'test',
|
||||
'depends_on',
|
||||
'triggers',
|
||||
'verified_by',
|
||||
'status',
|
||||
'removal_reason',
|
||||
'deferred',
|
||||
'uncertainty',
|
||||
]);
|
||||
|
||||
const MACHINE_KEY_RE = /^[a-z][a-z0-9_-]*$/;
|
||||
const REQUIREMENT_RE = /^###\s+Requirement:\s*(.+)$/;
|
||||
const INVARIANT_RE = /^###\s+Invariant:\s*(.+)$/;
|
||||
const SCENARIO_RE = /^####\s+Scenario:\s*/m;
|
||||
const HTML_COMMENT_RE = /<!--([\s\S]*?)-->/g;
|
||||
const ENFORCED_RE = /<!--\s*enforced:\s*(.*?)\s*-->/g;
|
||||
const DELTA_MARKER_RE = /<!--\s*(ADDED|MODIFIED|REMOVED)\s*:\s*-->/g;
|
||||
|
||||
// ── Helpers ─────────────────────────────────────────────────────
|
||||
|
||||
function walkMdFiles(dir) {
|
||||
const results = [];
|
||||
if (!fs.existsSync(dir)) return results;
|
||||
let stat;
|
||||
try {
|
||||
stat = fs.statSync(dir);
|
||||
} catch {
|
||||
return results;
|
||||
}
|
||||
if (!stat.isDirectory()) return results;
|
||||
|
||||
const entries = fs.readdirSync(dir, { withFileTypes: true });
|
||||
for (const entry of entries) {
|
||||
const fullPath = path.join(dir, entry.name);
|
||||
if (entry.isDirectory()) {
|
||||
results.push(...walkMdFiles(fullPath));
|
||||
} else if (entry.isFile() && entry.name.endsWith('.md')) {
|
||||
results.push(fullPath);
|
||||
}
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate an enforced anchor string against the v1 grammar.
|
||||
* @returns {{ path: string, symbol: string } | { invalid: true, reason: string }}
|
||||
*/
|
||||
function parseAnchor(raw) {
|
||||
const trimmed = raw.trim();
|
||||
if (trimmed === '' || /\s/.test(trimmed)) {
|
||||
return { invalid: true, reason: 'must not contain whitespace' };
|
||||
}
|
||||
const sep = trimmed.indexOf('::');
|
||||
if (sep <= 0 || trimmed.slice(sep + 2) === '') {
|
||||
return { invalid: true, reason: 'expected <path>::<symbol>' };
|
||||
}
|
||||
const anchorPath = trimmed.slice(0, sep);
|
||||
const symbol = trimmed.slice(sep + 2);
|
||||
if (anchorPath.startsWith('/')) {
|
||||
return { invalid: true, reason: 'path must be repo-relative (no leading "/")' };
|
||||
}
|
||||
if (anchorPath.includes('\\')) {
|
||||
return { invalid: true, reason: 'path must use forward slashes' };
|
||||
}
|
||||
const segments = anchorPath.split('/');
|
||||
if (segments.includes('..')) {
|
||||
return { invalid: true, reason: 'path must not traverse outside the project ("../")' };
|
||||
}
|
||||
return { path: anchorPath, symbol };
|
||||
}
|
||||
|
||||
const INVALID_ANCHOR_MSG = (rel, raw, reason) =>
|
||||
`${rel}: Invalid enforced anchor "${raw}" (${reason}; expected <relative/path.ext>::<symbol>)`;
|
||||
|
||||
/**
|
||||
* Remove fenced code blocks (``` / ~~~, up to 3 leading spaces) and inline
|
||||
* code spans (`...`, no newlines inside). Content inside code is illustrative
|
||||
* and must never be read as enforced anchors, metadata, or delta markers.
|
||||
* Fenced blocks are replaced with an equal number of blank lines so that
|
||||
* line-oriented splitting downstream keeps working on the same line numbers.
|
||||
*/
|
||||
function stripCodeSpans(content) {
|
||||
const withoutFences = content.replace(
|
||||
/^[ \t]{0,3}(`{3,}|~{3,})[^\n]*\n[\s\S]*?^[ \t]{0,3}\1[ \t]*$/gm,
|
||||
(block) => '\n'.repeat(block.split('\n').length - 1)
|
||||
);
|
||||
return withoutFences.replace(/`[^`\n]*`/g, '');
|
||||
}
|
||||
|
||||
/**
|
||||
* Walk every HTML comment in a file and classify it.
|
||||
* Returns { errors, metadata[] } — metadata entries not currently consumed by
|
||||
* structural checks, but presence of an error means the file is invalid.
|
||||
*/
|
||||
function classifyComments(rel, content, errors) {
|
||||
const meta = [];
|
||||
let match;
|
||||
const re = new RegExp(HTML_COMMENT_RE.source, 'g');
|
||||
while ((match = re.exec(content)) !== null) {
|
||||
const body = match[1].trim();
|
||||
if (body === '') continue;
|
||||
const colon = body.indexOf(':');
|
||||
if (colon === -1) continue; // ordinary comment
|
||||
const key = body.slice(0, colon).trim();
|
||||
const value = body.slice(colon + 1).trim();
|
||||
|
||||
// Structural delta markers are not metadata.
|
||||
if (key === 'ADDED' || key === 'MODIFIED' || key === 'REMOVED') continue;
|
||||
|
||||
if (METADATA_ALLOWLIST.has(key)) {
|
||||
meta.push({ key, value });
|
||||
continue;
|
||||
}
|
||||
if (MACHINE_KEY_RE.test(key)) {
|
||||
errors.push(`${rel}: Unknown metadata key "${key}" (not in allowlist)`);
|
||||
continue;
|
||||
}
|
||||
// Uppercase / prose keys (`Note:`, `TODO:`, `PR:`) are ordinary comments.
|
||||
}
|
||||
return meta;
|
||||
}
|
||||
|
||||
/** Collect every enforced anchor string in declarative content (code spans already stripped). */
|
||||
function collectEnforcedAnchors(content) {
|
||||
const anchors = [];
|
||||
let match;
|
||||
const re = new RegExp(ENFORCED_RE.source, 'g');
|
||||
while ((match = re.exec(content)) !== null) {
|
||||
anchors.push(match[1].trim());
|
||||
}
|
||||
return anchors;
|
||||
}
|
||||
|
||||
/**
|
||||
* Split content into top-level sections by `### Requirement:` / `### Invariant:`
|
||||
* headings. Returns [{ type, title, body }]. Text before the first heading is
|
||||
* dropped from block validation (document preamble is allowed).
|
||||
*/
|
||||
function splitBlocks(content) {
|
||||
const blocks = [];
|
||||
const lines = content.split('\n');
|
||||
let current = null;
|
||||
for (const line of lines) {
|
||||
let m = line.match(REQUIREMENT_RE);
|
||||
if (m) {
|
||||
current = { type: 'Requirement', title: m[1].trim(), body: [] };
|
||||
blocks.push(current);
|
||||
continue;
|
||||
}
|
||||
m = line.match(INVARIANT_RE);
|
||||
if (m) {
|
||||
current = { type: 'Invariant', title: m[1].trim(), body: [] };
|
||||
blocks.push(current);
|
||||
continue;
|
||||
}
|
||||
if (current) current.body.push(line);
|
||||
}
|
||||
return blocks;
|
||||
}
|
||||
|
||||
/** Validate a baseline spec file (Requirement/Invariant blocks). */
|
||||
function validateBaseline(rel, content, errors) {
|
||||
const blocks = splitBlocks(content);
|
||||
|
||||
for (const block of blocks) {
|
||||
const body = block.body.join('\n');
|
||||
if (block.type === 'Requirement' && !SCENARIO_RE.test(body)) {
|
||||
errors.push(`${rel}: Requirement "${block.title}" has no Scenario`);
|
||||
}
|
||||
if (block.type === 'Invariant') {
|
||||
const enforcedIn = collectEnforcedAnchors(body);
|
||||
if (enforcedIn.length === 0) {
|
||||
errors.push(`${rel}: Invariant "${block.title}" missing <!-- enforced: --> anchor`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Validate a delta file: every declared ADDED/MODIFIED/REMOVED block is non-empty. */
|
||||
function validateDelta(rel, content, errors) {
|
||||
// Each marker opens a block whose body runs from the END of that marker to
|
||||
// the START of the next marker (or EOF). Using the next marker's end as the
|
||||
// boundary would swallow the next marker's text into the current block.
|
||||
const markers = [];
|
||||
let match;
|
||||
const re = new RegExp(DELTA_MARKER_RE.source, 'g');
|
||||
while ((match = re.exec(content)) !== null) {
|
||||
markers.push({
|
||||
name: match[1],
|
||||
bodyStart: match.index + match[0].length, // end of this marker's "-->"
|
||||
markerStart: match.index, // start of this marker, used as the NEXT block's end
|
||||
});
|
||||
}
|
||||
|
||||
markers.forEach((m, i) => {
|
||||
const blockEnd = i + 1 < markers.length ? markers[i + 1].markerStart : content.length;
|
||||
const body = content.slice(m.bodyStart, blockEnd).trim();
|
||||
if (body === '') {
|
||||
errors.push(`${rel}: Empty ${m.name} block (declared but no content)`);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// ── Per-file validation ─────────────────────────────────────────
|
||||
|
||||
function validateSpecFile(filePath) {
|
||||
const errors = [];
|
||||
const rel = path.relative(openspecDir, filePath);
|
||||
|
||||
let content;
|
||||
try {
|
||||
content = fs.readFileSync(filePath, 'utf8');
|
||||
} catch (err) {
|
||||
return [`${rel}: Cannot read file: ${err.message}`];
|
||||
}
|
||||
|
||||
if (content.trim() === '') {
|
||||
return [`${rel}: Empty spec file`];
|
||||
}
|
||||
|
||||
// Code blocks/spans are illustrative, never declarative: validate the
|
||||
// stripped view so examples cannot inject anchors, metadata, or markers.
|
||||
const declarative = stripCodeSpans(content);
|
||||
|
||||
// Metadata allowlist + typo guard + ordinary-comment handling.
|
||||
classifyComments(rel, declarative, errors);
|
||||
|
||||
// Every enforced anchor anywhere in the file must satisfy the grammar.
|
||||
for (const raw of collectEnforcedAnchors(declarative)) {
|
||||
const parsed = parseAnchor(raw);
|
||||
if (parsed.invalid) {
|
||||
errors.push(INVALID_ANCHOR_MSG(rel, raw, parsed.reason));
|
||||
}
|
||||
}
|
||||
|
||||
// Fresh regex per call: /g regexes are stateful across .test() calls.
|
||||
const isDelta = new RegExp(DELTA_MARKER_RE.source, 'g').test(declarative);
|
||||
if (isDelta) {
|
||||
validateDelta(rel, declarative, errors);
|
||||
return errors;
|
||||
}
|
||||
|
||||
validateBaseline(rel, declarative, errors);
|
||||
return errors;
|
||||
}
|
||||
|
||||
// ── Main ────────────────────────────────────────────────────────
|
||||
|
||||
function main() {
|
||||
if (!fs.existsSync(openspecDir)) {
|
||||
console.log(JSON.stringify({ valid: true, errors: [] }));
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
const mdFiles = walkMdFiles(openspecDir);
|
||||
if (mdFiles.length === 0) {
|
||||
console.log(JSON.stringify({ valid: true, errors: [] }));
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
const allErrors = [];
|
||||
for (const filePath of mdFiles) {
|
||||
const fileErrors = validateSpecFile(filePath);
|
||||
allErrors.push(...fileErrors);
|
||||
}
|
||||
|
||||
if (allErrors.length > 0) {
|
||||
console.error(`Found ${allErrors.length} validation error(s):`);
|
||||
for (const err of allErrors) {
|
||||
console.error(` - ${err}`);
|
||||
}
|
||||
} else {
|
||||
console.error(`Validated ${mdFiles.length} spec file(s): no errors found.`);
|
||||
}
|
||||
|
||||
console.log(JSON.stringify({ valid: allErrors.length === 0, errors: allErrors }));
|
||||
|
||||
process.exit(allErrors.length > 0 ? 1 : 0);
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -242,11 +242,17 @@ function commandFor(kind, id, target) {
|
||||
if (kind === 'profile') {
|
||||
return `npx ecc-universal install --profile ${id} --target ${target}`;
|
||||
}
|
||||
if (target === 'mistral-vibe' && id.startsWith('skill:')) {
|
||||
return `npx ecc-universal install --target mistral-vibe --skills ${id.slice('skill:'.length)}`;
|
||||
}
|
||||
|
||||
return `npx ecc-universal install --profile minimal --target ${target} --with ${id}`;
|
||||
}
|
||||
|
||||
function planCommandFor(componentId, target) {
|
||||
if (target === 'mistral-vibe' && componentId.startsWith('skill:')) {
|
||||
return `npx ecc-universal plan --target mistral-vibe --skills ${componentId.slice('skill:'.length)}`;
|
||||
}
|
||||
return `npx ecc-universal plan --profile minimal --target ${target} --with ${componentId}`;
|
||||
}
|
||||
|
||||
@@ -358,6 +364,7 @@ function rankComponents({ queryTokens, target, limit }) {
|
||||
}
|
||||
|
||||
function rankProfiles({ queryTokens, target, limit }) {
|
||||
if (target === 'mistral-vibe') return [];
|
||||
const manifests = loadInstallManifests();
|
||||
return listInstallProfiles()
|
||||
.map(profile => {
|
||||
|
||||
@@ -0,0 +1,214 @@
|
||||
#!/usr/bin/env node
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Antigravity Lifecycle Hook Bridge
|
||||
*
|
||||
* Bridges Google Antigravity's protojson hook contract (stdin/stdout JSON with
|
||||
* camelCase keys and { decision, reason } responses) to ECC's internal hook
|
||||
* runtime (exit-code/stderr based).
|
||||
*/
|
||||
|
||||
const path = require('path');
|
||||
const { spawnSync } = require('child_process');
|
||||
const { runPreBash } = require('./bash-hook-dispatcher');
|
||||
const { run: runGateGuard } = require('./gateguard-fact-force');
|
||||
const { run: runDocFileWarning } = require('./doc-file-warning');
|
||||
const { run: runPostEditAccumulator } = require('./post-edit-accumulator');
|
||||
const { readStdinRaw, resolveMaxStdin } = require('./hook-input');
|
||||
const { isHookEnabled, isDryRun } = require('../lib/hook-flags');
|
||||
|
||||
function parseArgs(argv) {
|
||||
const options = {
|
||||
mode: 'pre-tool-use',
|
||||
hook: null,
|
||||
};
|
||||
|
||||
for (let i = 2; i < argv.length; i += 1) {
|
||||
if (argv[i] === '--mode') {
|
||||
options.mode = argv[i + 1] || options.mode;
|
||||
i += 1;
|
||||
} else if (argv[i] === '--hook') {
|
||||
options.hook = argv[i + 1] || options.hook;
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
|
||||
return options;
|
||||
}
|
||||
|
||||
function adaptAntigravityInputToEcc(antigravityData) {
|
||||
if (!antigravityData || typeof antigravityData !== 'object') {
|
||||
return { tool_name: '', tool_input: {} };
|
||||
}
|
||||
|
||||
const toolCall = antigravityData.toolCall || {};
|
||||
const toolName = toolCall.name || antigravityData.tool_name || '';
|
||||
const args = toolCall.args || antigravityData.tool_input || {};
|
||||
|
||||
// Normalize Antigravity tools to ECC tool conventions
|
||||
const toolInput = {
|
||||
...args,
|
||||
command: args.CommandLine || args.command || '',
|
||||
file_path: args.TargetFile || args.file_path || args.path || '',
|
||||
};
|
||||
|
||||
return {
|
||||
tool_name: ({ run_command: 'Bash', write_to_file: 'Write', replace_file_content: 'Edit', multi_replace_file_content: 'Edit' })[toolName] || toolName,
|
||||
tool_input: toolInput,
|
||||
session_id: antigravityData.conversationId || antigravityData.session_id || '',
|
||||
cwd: args.Cwd || antigravityData.cwd || antigravityData.workspacePaths?.[0] || '',
|
||||
conversation_id: antigravityData.conversationId || '',
|
||||
workspace_paths: antigravityData.workspacePaths || [],
|
||||
};
|
||||
}
|
||||
|
||||
function writeFailure(mode, reason) {
|
||||
process.stdout.write(JSON.stringify({
|
||||
decision: mode === 'pre-tool-use' ? 'deny' : 'allow',
|
||||
...(mode === 'pre-tool-use' ? { reason } : {}),
|
||||
}));
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const options = parseArgs(process.argv);
|
||||
process.env.ECC_HOOK_CONFIG ||= path.resolve(__dirname, '../../ecc/setup.json');
|
||||
const profiles = options.hook === 'pre:bash:dispatcher' ? 'minimal,standard,strict' : undefined;
|
||||
if (!isHookEnabled(options.hook, { profiles }) || isDryRun()) {
|
||||
process.stdout.write(JSON.stringify(options.mode === 'post-tool-use' ? {} : { decision: 'allow' }));
|
||||
return;
|
||||
}
|
||||
const maxStdin = resolveMaxStdin(process.env.ECC_HOOK_INPUT_MAX_BYTES);
|
||||
|
||||
let raw = '';
|
||||
try {
|
||||
const inputResult = await readStdinRaw(process.stdin, { maxStdin });
|
||||
if (inputResult.truncated) throw new Error('Incomplete hook input');
|
||||
raw = inputResult.raw;
|
||||
} catch (_err) {
|
||||
writeFailure(options.mode, 'ECC hook input could not be read completely');
|
||||
return;
|
||||
}
|
||||
|
||||
let antigravityPayload = {};
|
||||
try {
|
||||
antigravityPayload = JSON.parse(raw);
|
||||
if (!antigravityPayload || typeof antigravityPayload !== 'object' || Array.isArray(antigravityPayload)) {
|
||||
throw new Error('Invalid hook input');
|
||||
}
|
||||
} catch (_parseErr) {
|
||||
writeFailure(options.mode, 'ECC hook input must be a valid JSON object');
|
||||
return;
|
||||
}
|
||||
|
||||
const eccPayload = adaptAntigravityInputToEcc(antigravityPayload);
|
||||
const eccJsonString = JSON.stringify(eccPayload);
|
||||
|
||||
if (options.mode === 'pre-tool-use') {
|
||||
let result = { exitCode: 0, stderr: '' };
|
||||
|
||||
if (options.hook === 'pre:bash:dispatcher') {
|
||||
result = runPreBash(eccJsonString);
|
||||
} else if (options.hook === 'pre:edit-write:gateguard-fact-force') {
|
||||
result = runGateGuard(eccJsonString);
|
||||
} else if (options.hook === 'pre:config-protection') {
|
||||
const child = spawnSync(process.execPath, [path.join(__dirname, 'config-protection.js')], {
|
||||
input: eccJsonString,
|
||||
encoding: 'utf8',
|
||||
timeout: 4000,
|
||||
});
|
||||
result = {
|
||||
exitCode: child.error || child.status === null ? 2 : child.status,
|
||||
stderr: child.stderr || '',
|
||||
stdout: typeof child.stdout === 'string' ? child.stdout : '',
|
||||
};
|
||||
} else if (options.hook === 'pre:write:doc-file-warning') {
|
||||
result = runDocFileWarning(eccJsonString);
|
||||
}
|
||||
|
||||
const output = typeof result?.stdout === 'string'
|
||||
? result.stdout
|
||||
: (typeof result?.output === 'string' ? result.output : null);
|
||||
let hookOutput = null;
|
||||
if (output) {
|
||||
try {
|
||||
const parsed = JSON.parse(output);
|
||||
hookOutput = parsed && typeof parsed === 'object' ? parsed.hookSpecificOutput : null;
|
||||
} catch {
|
||||
hookOutput = null;
|
||||
}
|
||||
}
|
||||
const denied = Boolean(
|
||||
(result && ((result.exitCode !== undefined && result.exitCode !== 0) || result.denied || result.blocked))
|
||||
|| hookOutput?.permissionDecision === 'deny'
|
||||
);
|
||||
const context = result?.additionalContext || hookOutput?.additionalContext;
|
||||
const reason = denied
|
||||
? hookOutput?.permissionDecisionReason || result?.stderr || result?.reason || 'Blocked by ECC safety hook'
|
||||
: (Array.isArray(context) ? context.join(' ') : context);
|
||||
process.stdout.write(JSON.stringify({
|
||||
decision: denied ? 'deny' : 'allow',
|
||||
...(reason ? { reason: String(reason).replace(/\r?\n/g, ' ').trim() } : {}),
|
||||
}));
|
||||
return;
|
||||
}
|
||||
|
||||
// Both accumulator and batch formatter use the same session-scoped temp file.
|
||||
if (eccPayload.session_id) process.env.CLAUDE_SESSION_ID = String(eccPayload.session_id);
|
||||
|
||||
if (options.mode === 'post-tool-use') {
|
||||
if (options.hook === 'post:edit:accumulator' && !antigravityPayload.error) {
|
||||
runPostEditAccumulator(eccJsonString);
|
||||
}
|
||||
process.stdout.write(JSON.stringify({}));
|
||||
return;
|
||||
}
|
||||
|
||||
if (options.mode === 'stop') {
|
||||
if (antigravityPayload.fullyIdle === false) {
|
||||
process.stdout.write(JSON.stringify({ decision: 'allow' }));
|
||||
return;
|
||||
}
|
||||
let stopResult = { exitCode: 0, stderr: '' };
|
||||
|
||||
const stopScript = {
|
||||
'stop:format-typecheck': 'stop-format-typecheck.js',
|
||||
'stop:check-console-log': 'check-console-log.js',
|
||||
}[options.hook];
|
||||
if (stopScript) {
|
||||
const child = spawnSync(process.execPath, [path.join(__dirname, stopScript)], {
|
||||
input: eccJsonString,
|
||||
cwd: eccPayload.cwd || undefined,
|
||||
encoding: 'utf8',
|
||||
timeout: options.hook === 'stop:format-typecheck' ? 280000 : 25000,
|
||||
});
|
||||
stopResult = {
|
||||
stderr: child.stderr || (child.error ? 'ECC stop hook failed: ' + child.error.message : ''),
|
||||
};
|
||||
}
|
||||
|
||||
if (stopResult && stopResult.stderr) {
|
||||
process.stdout.write(JSON.stringify({
|
||||
decision: 'continue',
|
||||
reason: stopResult.stderr.replace(/\r?\n/g, ' ').trim(),
|
||||
}));
|
||||
return;
|
||||
}
|
||||
|
||||
process.stdout.write(JSON.stringify({ decision: 'allow' }));
|
||||
return;
|
||||
}
|
||||
|
||||
// Default passthrough
|
||||
process.stdout.write(JSON.stringify({ decision: 'allow' }));
|
||||
}
|
||||
|
||||
if (require.main === module) {
|
||||
main().catch(() => {
|
||||
writeFailure(parseArgs(process.argv).mode, 'ECC safety hook failed unexpectedly');
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
adaptAntigravityInputToEcc,
|
||||
};
|
||||
@@ -27,6 +27,7 @@
|
||||
|
||||
const path = require('path');
|
||||
const { spawnSync } = require('child_process');
|
||||
const { isDevServerCommand } = require('../lib/dev-command');
|
||||
|
||||
const MAX_STDIN = 1024 * 1024; // 1MB limit
|
||||
let data = '';
|
||||
@@ -36,20 +37,12 @@ function run(rawInput) {
|
||||
const input = typeof rawInput === 'string' ? JSON.parse(rawInput) : rawInput;
|
||||
const cmd = input.tool_input?.command || '';
|
||||
|
||||
// Detect dev server commands: npm run dev, pnpm (run) dev, yarn (run) dev,
|
||||
// bun (run) dev. Trailing (?![\w-]) rather than \b: \b treats a hyphen as a
|
||||
// word boundary, so `dev\b` matches the `dev` prefix of distinct scripts
|
||||
// like `dev-build` / `dev-docs` and would wrongly detach those one-shot
|
||||
// scripts into tmux. The lookahead still matches the dev server (`dev`,
|
||||
// `dev:ssr`, ...) but not a `dev-<suffix>` script. The optional `run` on
|
||||
// yarn/bun mirrors the command shapes in pre-bash-dev-server-block.js
|
||||
// DEV_PATTERN so the two hooks agree on what counts as a dev server.
|
||||
// Flexible whitespace (\s+) and leading \b make this byte-identical to
|
||||
// pre-bash-dev-server-block.js DEV_PATTERN, so a tabbed/multi-space command
|
||||
// the blocker catches is also detached here (they agree exactly).
|
||||
const devServerRegex = /\b(npm\s+run\s+dev|pnpm(?:\s+run)?\s+dev|yarn(?:\s+run)?\s+dev|bun(?:\s+run)?\s+dev)(?![\w-])/;
|
||||
|
||||
if (devServerRegex.test(cmd)) {
|
||||
// Detect dev server commands through the shared classifier
|
||||
// (scripts/lib/dev-command.js) rather than a private regex. This hook and
|
||||
// pre-bash-dev-server-block.js must agree exactly — one refuses the command
|
||||
// outside tmux, the other is what puts it in tmux — and two copies of a
|
||||
// regex asking each other to stay identical is how they drift.
|
||||
if (isDevServerCommand(cmd)) {
|
||||
// Get session name from current directory basename, sanitize for shell safety
|
||||
// e.g., /home/user/Portfolio → "Portfolio", /home/user/my-app-v2 → "my-app-v2"
|
||||
const rawName = path.basename(process.cwd());
|
||||
|
||||
@@ -61,10 +61,47 @@ const COMMIT_OPTIONS_WITH_VALUE = new Set([
|
||||
'--template',
|
||||
'--fixup',
|
||||
'--squash',
|
||||
'--pathspec-from-file'
|
||||
'--pathspec-from-file',
|
||||
// `git commit --trailer --no-verify` adds a trailer whose value is
|
||||
// `--no-verify`; git still runs the hooks.
|
||||
'--trailer'
|
||||
]);
|
||||
|
||||
const COMMIT_OPTIONS_WITH_INLINE_VALUE = ['--message=', '--file=', '--reuse-message=', '--reedit-message=', '--author=', '--date=', '--template=', '--fixup=', '--squash=', '--pathspec-from-file='];
|
||||
const COMMIT_OPTIONS_WITH_INLINE_VALUE = ['--message=', '--file=', '--reuse-message=', '--reedit-message=', '--author=', '--date=', '--template=', '--fixup=', '--squash=', '--pathspec-from-file=', '--trailer='];
|
||||
|
||||
// `git push` options that consume the following token. Their value is sent or
|
||||
// executed verbatim, so `git push --push-option --no-verify` runs pre-push.
|
||||
// `--force-with-lease` is deliberately absent: its value is optional and
|
||||
// inline-only, so the bare form consumes nothing and a following
|
||||
// `--no-verify` is a real flag.
|
||||
const PUSH_OPTIONS_WITH_VALUE = new Set(['-o', '--push-option', '--receive-pack', '--exec', '--repo']);
|
||||
|
||||
/**
|
||||
* Return true when a token is a value-taking option, or an abbreviation that
|
||||
* names exactly one value-taking long option in `optionsWithValue`.
|
||||
*
|
||||
* Git accepts any unambiguous long-option prefix, so `--mes` consumes the next
|
||||
* token just like `--message`. Resolving against value-taking options alone is
|
||||
* safe only because Git refuses a prefix that is ambiguous across its complete
|
||||
* option table: a prefix that is unique here but also matches a boolean option
|
||||
* (`git commit --s`) makes Git exit before any hook decision. Ambiguous
|
||||
* prefixes within this set resolve to nothing, so `--no-verify` after them is
|
||||
* still caught. The inline `--option=value` form is one token and never
|
||||
* consumes the next one.
|
||||
*
|
||||
* @param {string} value
|
||||
* @param {Set<string>} optionsWithValue
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function optionConsumesNextValue(value, optionsWithValue) {
|
||||
if (optionsWithValue.has(value)) return true;
|
||||
if (!value.startsWith('--') || value.length <= 2 || value.includes('=')) return false;
|
||||
let matches = 0;
|
||||
for (const option of optionsWithValue) {
|
||||
if (option.startsWith('--') && option.startsWith(value)) matches++;
|
||||
}
|
||||
return matches === 1;
|
||||
}
|
||||
|
||||
// Short options that take a value. When seen as part of a combined
|
||||
// short-option token (e.g. -tn), git's parser treats the rest of the
|
||||
@@ -88,7 +125,7 @@ function commitOptionConsumesNextValue(value) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (COMMIT_OPTIONS_WITH_VALUE.has(value)) {
|
||||
if (optionConsumesNextValue(value, COMMIT_OPTIONS_WITH_VALUE)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -267,6 +304,7 @@ function findGitBypassFlag(words, budget, start, command) {
|
||||
if (commitOptionConsumesNextValue(value)) { skipNext = true; continue; }
|
||||
if (commitOptionContainsInlineValue(value)) continue;
|
||||
}
|
||||
if (command === 'push' && optionConsumesNextValue(value, PUSH_OPTIONS_WITH_VALUE)) { skipNext = true; continue; }
|
||||
if (isNoVerifyLongFlag(value) || (command === 'commit' && isCommitNoVerifyShortFlag(value))) return true;
|
||||
}
|
||||
return false;
|
||||
|
||||
@@ -19,8 +19,7 @@ const {
|
||||
ensureDir,
|
||||
readFile,
|
||||
countInFile,
|
||||
log,
|
||||
output
|
||||
log
|
||||
} = require('../lib/utils');
|
||||
const { resolveHookSessionId } = require('../lib/hook-session');
|
||||
const {
|
||||
@@ -120,9 +119,12 @@ async function main() {
|
||||
log(`[ContinuousLearning] Session has ${messageCount} messages - evaluate for extractable patterns`);
|
||||
log(`[ContinuousLearning] Save learned skills to: ${learnedSkillsPath}`);
|
||||
|
||||
deliverStopNudge({ input, stdinData, messageCount, learnedSkillsPath, stopNudgeOptIn });
|
||||
|
||||
process.exit(0);
|
||||
// When a nudge was delivered, the process exits from the stdout-write
|
||||
// callback, only after the Stop JSON has flushed. Exiting here instead
|
||||
// would race the flush and could truncate the payload.
|
||||
if (!deliverStopNudge({ input, stdinData, messageCount, learnedSkillsPath, stopNudgeOptIn })) {
|
||||
process.exit(0);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -132,41 +134,48 @@ async function main() {
|
||||
* decision "block" + reason, which continues the turn with the reason as
|
||||
* context. Plain stdout text is not a delivery channel on Stop, so nothing
|
||||
* else is ever written to stdout here. Every gate fails closed.
|
||||
*
|
||||
* Returns true when the Stop JSON was written (the process then exits from
|
||||
* the write callback, once the payload has flushed), false otherwise.
|
||||
*/
|
||||
function deliverStopNudge({ input, stdinData, messageCount, learnedSkillsPath, stopNudgeOptIn }) {
|
||||
if (!stopNudgeOptIn) {
|
||||
log('[ContinuousLearning] Stop nudge opt-in is off, skipping delivery');
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
// A payload that names a different event means this script is running
|
||||
// under the wrong registration; an absent field is tolerated (older
|
||||
// harnesses omit it), a mismatched one is not.
|
||||
if (input && input.hook_event_name && input.hook_event_name !== 'Stop') {
|
||||
log(`[ContinuousLearning] Skipping delivery: hook event is ${input.hook_event_name}, not Stop`);
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
// Stop-loop protection: when a previous Stop already continued this stop,
|
||||
// the hook is re-firing and must pass through, never block again.
|
||||
if (input && input.stop_hook_active === true) {
|
||||
log('[ContinuousLearning] Skipping delivery: Stop hook already fired for this stop');
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
// The payload session id identifies the harness conversation; env ids are
|
||||
// only fallbacks, never preferred over it.
|
||||
const sessionId = resolveSessionId(resolveHookSessionId(stdinData));
|
||||
if (!sessionId) {
|
||||
log('[ContinuousLearning] Skipping delivery: no session id available');
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
if (!hasRegisteredSessionLease(input, sessionId)) {
|
||||
log('[ContinuousLearning] Skipping delivery: no SessionStart lease for this session');
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
if (!claimDeliveryMarker(sessionId)) return;
|
||||
output({
|
||||
if (!claimDeliveryMarker(sessionId)) return false;
|
||||
// Write the Stop JSON with a flush callback and exit from it: a plain
|
||||
// console.log followed by process.exit(0) can truncate the payload when
|
||||
// stdout is a pipe, because the write is asynchronous.
|
||||
process.stdout.write(`${JSON.stringify({
|
||||
decision: 'block',
|
||||
reason: `[ContinuousLearning] Session has ${messageCount} messages - evaluate for extractable patterns. Save learned skills to: ${learnedSkillsPath}`
|
||||
});
|
||||
})}\n`, () => process.exit(0));
|
||||
return true;
|
||||
}
|
||||
|
||||
function claimDeliveryMarker(sessionId) {
|
||||
|
||||
@@ -1051,16 +1051,12 @@ function isDestructiveQuoteAware(raw, depth = 0) {
|
||||
if (isDestructiveSqlClient(tokens)) return true;
|
||||
if (isDestructiveFindExec(tokens)) return true;
|
||||
const argv = unwrapLeadWrappers(tokens, true, true);
|
||||
const base = commandBasename(argv[0]);
|
||||
if (SHELL_WRAPPERS.has(base)) {
|
||||
// `-c`, or a short-option cluster that includes it (`-lc`, `-ec`).
|
||||
const ci = argv.findIndex((arg, i) => i > 0 && /^-[A-Za-z]*c[A-Za-z]*$/.test(arg));
|
||||
if (ci !== -1 && argv[ci + 1] && isDestructiveQuoteAware(argv[ci + 1], depth + 1)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if (base === 'su') {
|
||||
for (const commandLine of suCommandLines(argv)) {
|
||||
// `sudo find . -exec rm {} \;` runs the same actions as a bare find.
|
||||
if (isDestructiveFindExec(argv)) return true;
|
||||
// A shell that find -exec starts runs its -c text like any other.
|
||||
const execShells = findExecArgvs(argv).map(exec => unwrapLeadWrappers(exec, false, true));
|
||||
for (const shellArgv of [argv, ...execShells]) {
|
||||
for (const commandLine of nestedShellCommandLines(shellArgv)) {
|
||||
if (isDestructiveQuoteAware(commandLine, depth + 1)) return true;
|
||||
}
|
||||
}
|
||||
@@ -1069,6 +1065,23 @@ function isDestructiveQuoteAware(raw, depth = 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Command text a resolved argv hands to a nested shell: the `-c` operand of
|
||||
* sh/bash/zsh/dash/ksh (also inside a cluster such as `-lc` or `-ec`), or every
|
||||
* command line of `su`.
|
||||
*
|
||||
* @param {string[]} argv
|
||||
* @returns {string[]}
|
||||
*/
|
||||
function nestedShellCommandLines(argv) {
|
||||
const base = commandBasename(argv[0]);
|
||||
if (SHELL_WRAPPERS.has(base)) {
|
||||
const ci = argv.findIndex((arg, i) => i > 0 && /^-[A-Za-z]*c[A-Za-z]*$/.test(arg));
|
||||
return ci !== -1 && argv[ci + 1] ? [argv[ci + 1]] : [];
|
||||
}
|
||||
return base === 'su' ? suCommandLines(argv) : [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Strip a leading path and trailing `.exe` from a command token so
|
||||
* `/usr/bin/git`, `git.exe`, and `GIT` all normalize to `git`.
|
||||
@@ -1441,8 +1454,19 @@ const FIND_EXEC_ACTIONS = new Set(['-exec', '-execdir', '-ok', '-okdir']);
|
||||
function isDestructiveFindExec(command) {
|
||||
const quoteAware = Array.isArray(command);
|
||||
const tokens = quoteAware ? command : tokenize(String(command || '').trim());
|
||||
if (commandBasename(tokens[0]) !== 'find') return false;
|
||||
return findExecArgvs(tokens).some(argv => isDestructiveFindExecArgv(argv, quoteAware));
|
||||
}
|
||||
|
||||
/**
|
||||
* The argv of every executable action of one find invocation, or [] when the
|
||||
* tokens are not a find command.
|
||||
*
|
||||
* @param {string[]} tokens
|
||||
* @returns {string[][]}
|
||||
*/
|
||||
function findExecArgvs(tokens) {
|
||||
if (commandBasename(tokens[0]) !== 'find') return [];
|
||||
const actions = [];
|
||||
for (let index = 1; index < tokens.length; index += 1) {
|
||||
const action = tokens[index];
|
||||
if (action === '-fprintf') {
|
||||
@@ -1456,9 +1480,9 @@ function isDestructiveFindExec(command) {
|
||||
if (!FIND_EXEC_ACTIONS.has(action)) continue;
|
||||
const exec = readFindExecArgv(tokens, index + 1, action);
|
||||
index = exec.index;
|
||||
if (exec.argv.length && isDestructiveFindExecArgv(exec.argv, quoteAware)) return true;
|
||||
if (exec.argv.length) actions.push(exec.argv);
|
||||
}
|
||||
return false;
|
||||
return actions;
|
||||
}
|
||||
|
||||
// Collect the argv of one find action starting at `start`. Returns the argv
|
||||
@@ -1479,10 +1503,21 @@ function readFindExecArgv(tokens, start, action) {
|
||||
|
||||
function isDestructiveFindExecArgv(argv, quoteAware) {
|
||||
// The legacy raw fallback can split quoted prose into apparent actions.
|
||||
// Preserve its old rm/Git coverage, but classify dd only from real argv.
|
||||
// Preserve its old rm/Git coverage, but classify dd and wrappers only from
|
||||
// real argv.
|
||||
if (quoteAware && isDestructiveDd(argv, false)) return true;
|
||||
if (isDestructiveFindExecCommand(argv)) return true;
|
||||
if (!quoteAware) return false;
|
||||
// find execs argv directly, so `-exec sudo rm {} \;` and
|
||||
// `-exec timeout 5 rm {} \;` run rm just as `-exec rm {} \;` does (#2832).
|
||||
// Shell builtins do not apply: find never runs `command` or `exec` itself.
|
||||
const resolved = unwrapLeadWrappers(argv, false, true);
|
||||
return resolved.length > 0 && isDestructiveFindExecCommand(resolved);
|
||||
}
|
||||
|
||||
// Preserve main's existing find rm/rmdir/unlink and git-reset handling.
|
||||
function isDestructiveFindExecCommand(argv) {
|
||||
const baseCmd = commandBasename(argv[0]);
|
||||
// Preserve main's existing rm/rmdir/unlink and git-reset handling.
|
||||
if (baseCmd === 'rm' || baseCmd === 'rmdir' || baseCmd === 'unlink') return true;
|
||||
if (baseCmd !== 'git') return false;
|
||||
const sub = findGitSubcommand(argv);
|
||||
|
||||
@@ -22,22 +22,52 @@ const MODE_CONFIG = {
|
||||
// A JWT header is base64url JSON, so it starts with `ey` (`{"`, `{ `) or
|
||||
// `ew` (`{` followed by a newline or tab). The common `eyJ` form is always
|
||||
// redacted; other headers must decode to an object with an `alg` field.
|
||||
function redactJwt(token) {
|
||||
if (token.startsWith('eyJ')) return '<REDACTED>';
|
||||
function isJwtHeader(header) {
|
||||
if (header.startsWith('eyJ')) return true;
|
||||
try {
|
||||
const header = JSON.parse(Buffer.from(token.split('.')[0], 'base64url').toString('utf8'));
|
||||
if (header && typeof header === 'object' && typeof header.alg === 'string') return '<REDACTED>';
|
||||
const decoded = JSON.parse(Buffer.from(header, 'base64url').toString('utf8'));
|
||||
return Boolean(decoded && typeof decoded === 'object' && typeof decoded.alg === 'string');
|
||||
} catch {
|
||||
// Not a JWT header; keep the text.
|
||||
return false;
|
||||
}
|
||||
return token;
|
||||
}
|
||||
|
||||
// Constant-time prefilter: the second decoded byte of a JSON object header is
|
||||
// whitespace or `"`. Rejects word prefixes such as `eyewear` without decoding
|
||||
// the whole segment.
|
||||
function mayBeJwtHeader(seg, j) {
|
||||
const bytes = Buffer.from(seg.slice(j, j + 4), 'base64url');
|
||||
return bytes.length >= 2 && (bytes[1] === 0x22 || bytes[1] === 0x20 || bytes[1] === 0x09 || bytes[1] === 0x0a || bytes[1] === 0x0d);
|
||||
}
|
||||
|
||||
// Full header decodes allowed per segment; keeps adversarial `eyAg-eyAg-...`
|
||||
// runs linear while still trying every realistic candidate.
|
||||
const MAX_HEADER_DECODES = 8;
|
||||
|
||||
// Index of the first JWT header in `seg`, starting at its beginning or after a
|
||||
// `-` or `_`, or -1. A candidate that fails validation (e.g. `eyewear` in
|
||||
// `eyewear_session_<JWT>`) does not stop the scan. Once the decode budget is
|
||||
// spent, the next candidate that passes the prefilter is treated as a header
|
||||
// (fail closed), so padding a JWT with decoy candidates cannot hide it.
|
||||
function findJwtHeader(seg) {
|
||||
let decodes = 0;
|
||||
for (let j = 0; j + 10 <= seg.length; j++) {
|
||||
if (!((j === 0 || seg[j - 1] === '-' || seg[j - 1] === '_') && seg[j] === 'e' && (seg[j + 1] === 'y' || seg[j + 1] === 'w'))) continue;
|
||||
if (seg.startsWith('eyJ', j)) return j;
|
||||
if (!mayBeJwtHeader(seg, j)) continue;
|
||||
if (decodes >= MAX_HEADER_DECODES) return j;
|
||||
decodes++;
|
||||
if (isJwtHeader(seg.slice(j))) return j;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Redact JWTs inside one run of `[A-Za-z0-9_.-]` characters. A JWT may follow
|
||||
// a word prefix joined by `-` or `_` (`session=jwt-<JWT>`, `session_<JWT>`), so
|
||||
// each dot-separated segment is checked for a header starting at its beginning
|
||||
// or after a `-` or `_`.
|
||||
// Every segment is scanned once and decoded at most once, keeping long
|
||||
// Every segment is scanned once with a bounded number of decodes, keeping long
|
||||
// `ey-ey-...` runs linear (a `\b`-anchored regex retries at each `-`).
|
||||
function redactJwtsInChain(chain) {
|
||||
if (!chain.includes('.')) return chain;
|
||||
@@ -47,25 +77,11 @@ function redactJwtsInChain(chain) {
|
||||
while (i < segs.length) {
|
||||
const seg = segs[i];
|
||||
if (i + 2 < segs.length && segs[i + 1].length > 0) {
|
||||
let first = -1;
|
||||
let preferred = -1;
|
||||
for (let j = 0; j + 10 <= seg.length; j++) {
|
||||
if ((j === 0 || seg[j - 1] === '-' || seg[j - 1] === '_') && seg[j] === 'e' && (seg[j + 1] === 'y' || seg[j + 1] === 'w')) {
|
||||
if (first < 0) first = j;
|
||||
if (seg.startsWith('eyJ', j)) {
|
||||
preferred = j;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
const start = preferred >= 0 ? preferred : first;
|
||||
const start = findJwtHeader(seg);
|
||||
if (start >= 0) {
|
||||
const token = [seg.slice(start), segs[i + 1], segs[i + 2]].join('.');
|
||||
if (redactJwt(token) !== token) {
|
||||
out.push(`${seg.slice(0, start)}<REDACTED>`);
|
||||
i += 3;
|
||||
continue;
|
||||
}
|
||||
out.push(`${seg.slice(0, start)}<REDACTED>`);
|
||||
i += 3;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
out.push(seg);
|
||||
|
||||
@@ -2,156 +2,7 @@
|
||||
'use strict';
|
||||
|
||||
const MAX_STDIN = 1024 * 1024;
|
||||
const path = require('path');
|
||||
const { splitShellSegments } = require('../lib/shell-split');
|
||||
const {
|
||||
extractCommandSubstitutions,
|
||||
extractSubshellGroups
|
||||
} = require('../lib/shell-substitution');
|
||||
|
||||
const DEV_COMMAND_WORDS = new Set([
|
||||
'npm',
|
||||
'pnpm',
|
||||
'yarn',
|
||||
'bun',
|
||||
'npx',
|
||||
'tmux'
|
||||
]);
|
||||
const SKIPPABLE_PREFIX_WORDS = new Set(['env', 'command', 'builtin', 'exec', 'noglob', 'sudo', 'nohup']);
|
||||
const PREFIX_OPTION_VALUE_WORDS = {
|
||||
env: new Set(['-u', '-C', '-S', '--unset', '--chdir', '--split-string']),
|
||||
sudo: new Set([
|
||||
'-u',
|
||||
'-g',
|
||||
'-h',
|
||||
'-p',
|
||||
'-r',
|
||||
'-t',
|
||||
'-C',
|
||||
'--user',
|
||||
'--group',
|
||||
'--host',
|
||||
'--prompt',
|
||||
'--role',
|
||||
'--type',
|
||||
'--close-from'
|
||||
])
|
||||
};
|
||||
|
||||
function readToken(input, startIndex) {
|
||||
let index = startIndex;
|
||||
while (index < input.length && /\s/.test(input[index])) index += 1;
|
||||
if (index >= input.length) return null;
|
||||
|
||||
let token = '';
|
||||
let quote = null;
|
||||
|
||||
while (index < input.length) {
|
||||
const ch = input[index];
|
||||
|
||||
if (quote) {
|
||||
if (ch === quote) {
|
||||
quote = null;
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Inside double quotes, bash drops a backslash only before $ ` " \ or a
|
||||
// newline, so `"echo ready\;"` keeps its `\;` for tmux.
|
||||
if (ch === '\\' && quote === '"' && index + 1 < input.length && '$`"\\\n'.includes(input[index + 1])) {
|
||||
token += input[index + 1];
|
||||
index += 2;
|
||||
continue;
|
||||
}
|
||||
|
||||
token += ch;
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (ch === '"' || ch === "'") {
|
||||
quote = ch;
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (/\s/.test(ch)) break;
|
||||
|
||||
if (ch === '\\' && index + 1 < input.length) {
|
||||
token += input[index + 1];
|
||||
index += 2;
|
||||
continue;
|
||||
}
|
||||
|
||||
token += ch;
|
||||
index += 1;
|
||||
}
|
||||
|
||||
return { token, end: index };
|
||||
}
|
||||
|
||||
function shouldSkipOptionValue(wrapper, optionToken) {
|
||||
if (!wrapper || !optionToken || optionToken.includes('=')) return false;
|
||||
const optionSet = PREFIX_OPTION_VALUE_WORDS[wrapper];
|
||||
return Boolean(optionSet && optionSet.has(optionToken));
|
||||
}
|
||||
|
||||
function isOptionToken(token) {
|
||||
return token.startsWith('-') && token.length > 1;
|
||||
}
|
||||
|
||||
function normalizeCommandWord(token) {
|
||||
if (!token) return '';
|
||||
const base = path.basename(token).toLowerCase();
|
||||
return base.replace(/\.(cmd|exe|bat)$/i, '');
|
||||
}
|
||||
|
||||
function getLeadingCommand(segment) {
|
||||
let index = 0;
|
||||
let activeWrapper = null;
|
||||
let skipNextValue = false;
|
||||
|
||||
while (index < segment.length) {
|
||||
const parsed = readToken(segment, index);
|
||||
if (!parsed) return null;
|
||||
index = parsed.end;
|
||||
|
||||
const token = parsed.token;
|
||||
if (!token) continue;
|
||||
|
||||
if (skipNextValue) {
|
||||
skipNextValue = false;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (token === '--') {
|
||||
activeWrapper = null;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (token === '{' || token === '}') continue;
|
||||
|
||||
if (/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(token)) continue;
|
||||
|
||||
const normalizedToken = normalizeCommandWord(token);
|
||||
|
||||
if (SKIPPABLE_PREFIX_WORDS.has(normalizedToken)) {
|
||||
activeWrapper = normalizedToken;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (activeWrapper && isOptionToken(token)) {
|
||||
if (shouldSkipOptionValue(activeWrapper, token)) {
|
||||
skipNextValue = true;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
return { word: normalizedToken, end: index };
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
const { isDevServerCommand } = require('../lib/dev-command');
|
||||
|
||||
let raw = '';
|
||||
process.stdin.setEncoding('utf8');
|
||||
@@ -162,118 +13,13 @@ process.stdin.on('data', chunk => {
|
||||
}
|
||||
});
|
||||
|
||||
// tmux commands, and their aliases, that run their shell command in a tmux pane,
|
||||
// where its output stays readable. run-shell and `tmux -c` run it without one.
|
||||
const TMUX_PANE_COMMANDS = new Set([
|
||||
'new-session', 'new',
|
||||
'new-window', 'neww',
|
||||
'split-window', 'splitw',
|
||||
'respawn-pane', 'respawnp',
|
||||
'respawn-window', 'respawnw',
|
||||
'send-keys', 'send'
|
||||
]);
|
||||
// tmux's own options that take a value (`-L work`, `-Lwork`, or the last of a
|
||||
// cluster such as `-vL work`).
|
||||
const TMUX_OPTION_VALUE_LETTERS = new Set(['f', 'L', 'S', 'T']);
|
||||
// Trailing (?![\w-]) rather than \b: \b treats a hyphen as a word boundary, so
|
||||
// `dev\b` matches the `dev` prefix of distinct scripts like `dev-setup` /
|
||||
// `dev-docs` / `dev-build` and wrongly blocks them. The lookahead still matches
|
||||
// the dev server (`dev`, `dev;`, `dev:ssr`, ...) but not a `dev-<suffix>` script.
|
||||
const DEV_PATTERN = /\b(npm\s+run\s+dev|pnpm(?:\s+run)?\s+dev|yarn(?:\s+run)?\s+dev|bun(?:\s+run)?\s+dev)(?![\w-])/;
|
||||
|
||||
/**
|
||||
* Collect every command-line segment we should evaluate. Returns the top-level
|
||||
* segments first, then segments harvested from `$(...)` / backtick command
|
||||
* substitutions and plain `(...)` subshell groups, recursively.
|
||||
*
|
||||
* Without this expansion the leading-command and dev-pattern check below only
|
||||
* sees the outermost command, so wrappers like `$(npm run dev)` and
|
||||
* `(npm run dev)` (which still spawn a dev server) sneak past.
|
||||
*/
|
||||
function collectCheckSegments(cmd) {
|
||||
const segments = [...splitShellSegments(cmd)];
|
||||
// Expanded here-document bodies enter through splitShellSegments, so their
|
||||
// segments must also be scanned for substitutions nested inside them.
|
||||
const queue = [cmd, ...segments];
|
||||
const seen = new Set();
|
||||
|
||||
// Read by index: shift() copies the queue each time, which is quadratic on a long command.
|
||||
for (let head = 0; head < queue.length; head++) {
|
||||
const current = queue[head];
|
||||
if (seen.has(current)) continue;
|
||||
seen.add(current);
|
||||
|
||||
for (const body of [...extractCommandSubstitutions(current), ...extractSubshellGroups(current)]) {
|
||||
const bodySegments = splitShellSegments(body);
|
||||
// One at a time: spreading a long command's segments into push() exceeds the argument limit.
|
||||
queue.push(body);
|
||||
for (const segment of bodySegments) {
|
||||
segments.push(segment);
|
||||
queue.push(segment);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return segments;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return true when the tmux invocation that starts at `index` runs the dev
|
||||
* server in a pane. The tmux commands follow tmux's own options (`-L work`,
|
||||
* `-f conf`), and the executable may come through a path or an env prefix, so
|
||||
* this reads the parsed tokens instead of the start of the segment. A sequence
|
||||
* (`new-session -d \; run-shell ...`) is exempt only when every command in it
|
||||
* that runs the dev server is a pane command.
|
||||
*/
|
||||
function isTmuxPaneLaunch(segment, index) {
|
||||
const tokens = [];
|
||||
for (let parsed = readToken(segment, index); parsed; parsed = readToken(segment, parsed.end)) {
|
||||
if (parsed.token) tokens.push(parsed.token);
|
||||
}
|
||||
|
||||
let next = 0;
|
||||
for (; next < tokens.length && isOptionToken(tokens[next]); next++) {
|
||||
const letters = tokens[next].slice(1);
|
||||
for (let i = 0; i < letters.length; i++) {
|
||||
// -c runs its shell command without a pane.
|
||||
if (letters[i] === 'c') return false;
|
||||
if (TMUX_OPTION_VALUE_LETTERS.has(letters[i])) {
|
||||
if (i === letters.length - 1) next++;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// tmux ends a command at a `;` argument and at a `;` that ends an argument
|
||||
// (`'npm run dev;'`); an escaped `\;` at the end stays literal.
|
||||
const commands = [[]];
|
||||
for (const token of tokens.slice(next)) {
|
||||
const ends = token.endsWith(';') && !token.endsWith('\\;');
|
||||
const value = ends ? token.slice(0, -1) : token;
|
||||
if (value) commands[commands.length - 1].push(value);
|
||||
if (ends) commands.push([]);
|
||||
}
|
||||
const devCommands = commands.filter(command => DEV_PATTERN.test(command.join(' ')));
|
||||
return devCommands.length > 0 && devCommands.every(command => TMUX_PANE_COMMANDS.has(command[0]));
|
||||
}
|
||||
|
||||
function isBlockedDevSegment(segment) {
|
||||
const command = getLeadingCommand(segment);
|
||||
if (!command || !DEV_COMMAND_WORDS.has(command.word)) return false;
|
||||
if (!DEV_PATTERN.test(segment)) return false;
|
||||
return !(command.word === 'tmux' && isTmuxPaneLaunch(segment, command.end));
|
||||
}
|
||||
|
||||
process.stdin.on('end', () => {
|
||||
try {
|
||||
const input = JSON.parse(raw);
|
||||
const cmd = String(input.tool_input?.command || '');
|
||||
|
||||
if (process.platform !== 'win32') {
|
||||
const segments = collectCheckSegments(cmd);
|
||||
const hasBlockedDev = segments.some(isBlockedDevSegment);
|
||||
|
||||
if (hasBlockedDev) {
|
||||
if (isDevServerCommand(cmd)) {
|
||||
console.error('[Hook] BLOCKED: Dev server must run in tmux for log access');
|
||||
console.error('[Hook] Use: tmux new-session -d -s dev "npm run dev"');
|
||||
console.error('[Hook] Then: tmux attach -t dev');
|
||||
|
||||
@@ -51,6 +51,7 @@ Targets:
|
||||
grok - Install through the canonical plan/apply/receipt lifecycle into ~/.grok/plugins/ecc/
|
||||
openclaw - Install shared rules/skills/commands into ~/.openclaw/
|
||||
adal - Install shared rules/skills/commands into ./.adal/
|
||||
mistral-vibe - Install selected skills into ./.vibe/skills/ (Vibe hooks and agents not configured)
|
||||
|
||||
Options:
|
||||
--profile <name> Resolve and install a manifest profile
|
||||
|
||||
@@ -261,6 +261,7 @@ function main() {
|
||||
includeComponentIds: request.includeComponentIds,
|
||||
excludeComponentIds: request.excludeComponentIds,
|
||||
target: request.target,
|
||||
projectRoot: process.cwd(),
|
||||
});
|
||||
|
||||
if (options.json) {
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
'use strict';
|
||||
|
||||
const path = require('path');
|
||||
const { shellQuote } = require('./control-pane/actions');
|
||||
|
||||
/**
|
||||
* Antigravity Hooks Generator
|
||||
*
|
||||
* Generates valid Antigravity hooks.json configuration matching Antigravity's
|
||||
* lifecycle schema (PreToolUse, PostToolUse, Stop) and pointing to the ECC
|
||||
* hook bridge.
|
||||
*/
|
||||
|
||||
function buildAntigravityHooksConfig(options = {}) {
|
||||
const { bridgeScript } = options;
|
||||
if (typeof bridgeScript !== 'string' || !path.isAbsolute(bridgeScript) || bridgeScript.includes('\0')) {
|
||||
throw new Error('bridgeScript must be an absolute path');
|
||||
}
|
||||
let quotedBridgeScript;
|
||||
if (process.platform === 'win32') {
|
||||
if (/[%"!$`\r\n]/.test(bridgeScript)) {
|
||||
throw new Error('bridgeScript contains unsafe shell expansion characters');
|
||||
}
|
||||
quotedBridgeScript = `"${bridgeScript}"`;
|
||||
} else {
|
||||
quotedBridgeScript = shellQuote(bridgeScript);
|
||||
}
|
||||
|
||||
const preToolUseHandlers = [
|
||||
{
|
||||
matcher: 'run_command',
|
||||
hooks: [
|
||||
{
|
||||
type: 'command',
|
||||
command: `node ${quotedBridgeScript} --mode pre-tool-use --hook pre:bash:dispatcher`,
|
||||
timeout: 15,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
matcher: 'write_to_file|replace_file_content|multi_replace_file_content',
|
||||
hooks: [
|
||||
{
|
||||
type: 'command',
|
||||
command: `node ${quotedBridgeScript} --mode pre-tool-use --hook pre:edit-write:gateguard-fact-force`,
|
||||
timeout: 10,
|
||||
},
|
||||
{
|
||||
type: 'command',
|
||||
command: `node ${quotedBridgeScript} --mode pre-tool-use --hook pre:config-protection`,
|
||||
timeout: 5,
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
// Runtime hook flags select the profile, including explicit environment overrides.
|
||||
preToolUseHandlers.push({
|
||||
matcher: 'write_to_file',
|
||||
hooks: [
|
||||
{
|
||||
type: 'command',
|
||||
command: `node ${quotedBridgeScript} --mode pre-tool-use --hook pre:write:doc-file-warning`,
|
||||
timeout: 5,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const stopHandlers = [
|
||||
{
|
||||
type: 'command',
|
||||
command: `node ${quotedBridgeScript} --mode stop --hook stop:format-typecheck`,
|
||||
timeout: 300,
|
||||
},
|
||||
{
|
||||
type: 'command',
|
||||
command: `node ${quotedBridgeScript} --mode stop --hook stop:check-console-log`,
|
||||
timeout: 30,
|
||||
},
|
||||
];
|
||||
|
||||
return {
|
||||
'ecc-guard': {
|
||||
PreToolUse: preToolUseHandlers,
|
||||
PostToolUse: [{
|
||||
matcher: 'write_to_file|replace_file_content|multi_replace_file_content',
|
||||
hooks: [{
|
||||
type: 'command',
|
||||
command: `node ${quotedBridgeScript} --mode post-tool-use --hook post:edit:accumulator`,
|
||||
timeout: 10,
|
||||
}],
|
||||
}],
|
||||
Stop: stopHandlers,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
buildAntigravityHooksConfig,
|
||||
};
|
||||
@@ -0,0 +1,72 @@
|
||||
'use strict';
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { createManagedScaffoldOperation } = require('./install-targets/helpers');
|
||||
const { formatPackageSourcePath } = require('./install/package-source');
|
||||
|
||||
/**
|
||||
* Antigravity MCP Configuration Generator
|
||||
*
|
||||
* Generates valid Antigravity mcp_config.json containing the ECC Memory Vault
|
||||
* stdio server so that Antigravity agents have native access to .ecc/memory/.
|
||||
*/
|
||||
|
||||
function buildAntigravityMcpConfig(options = {}) {
|
||||
const { memoryScript } = options;
|
||||
if (typeof memoryScript !== 'string' || !path.isAbsolute(memoryScript) || memoryScript.includes('\0')) {
|
||||
throw new Error('memoryScript must be an absolute path');
|
||||
}
|
||||
|
||||
return {
|
||||
mcpServers: {
|
||||
'ecc-memory': {
|
||||
command: 'node',
|
||||
args: [memoryScript],
|
||||
env: {
|
||||
ECC_MEMORY_HARNESS: 'antigravity',
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function planAntigravityMemoryRuntime(moduleId, repoRoot, targetRoot) {
|
||||
const sourcePaths = [
|
||||
'package.json',
|
||||
'scripts/memory-mcp.mjs',
|
||||
'scripts/lib/missing-dependency.js',
|
||||
'scripts/lib/memory-vault.js',
|
||||
'scripts/lib/memory-vault-format.js',
|
||||
'scripts/lib/path-safety.js',
|
||||
];
|
||||
const operations = sourcePaths.map(sourcePath => createManagedScaffoldOperation(
|
||||
moduleId, sourcePath, path.join(targetRoot, sourcePath), 'preserve-relative-path'
|
||||
));
|
||||
function addDependency(name, fromRoot, destinationRoot, ancestors = [], packageChain = []) {
|
||||
let manifestPath;
|
||||
try {
|
||||
manifestPath = require.resolve(`${name}/package.json`, { paths: [fromRoot] });
|
||||
} catch (error) {
|
||||
throw new Error(`Cannot install Antigravity memory dependency ${name}. Run npm install in ${repoRoot}: ${error.message}`);
|
||||
}
|
||||
if (ancestors.includes(manifestPath)) return;
|
||||
const packageRoot = path.dirname(manifestPath);
|
||||
const destinationPath = path.join(destinationRoot, 'node_modules', name);
|
||||
const sourceChain = [...packageChain, name];
|
||||
operations.push(createManagedScaffoldOperation(
|
||||
moduleId, formatPackageSourcePath(sourceChain), destinationPath, 'preserve-relative-path'
|
||||
));
|
||||
const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
|
||||
for (const dependency of Object.keys(manifest.dependencies || {})) {
|
||||
addDependency(dependency, packageRoot, destinationPath, [...ancestors, manifestPath], sourceChain);
|
||||
}
|
||||
}
|
||||
addDependency('ajv', repoRoot, targetRoot);
|
||||
return operations;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
buildAntigravityMcpConfig,
|
||||
planAntigravityMemoryRuntime,
|
||||
};
|
||||
@@ -0,0 +1,20 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Antigravity Plugin Manifest Generator
|
||||
*
|
||||
* Generates valid Antigravity plugin.json declaring the ECC plugin.
|
||||
*/
|
||||
|
||||
function buildAntigravityPluginManifest(options = {}) {
|
||||
const version = options.version || require('../../package.json').version;
|
||||
return {
|
||||
name: 'ecc',
|
||||
description: 'ECC - The Agent Harness Operating System for Antigravity',
|
||||
version,
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
buildAntigravityPluginManifest,
|
||||
};
|
||||
@@ -51,6 +51,15 @@ function renameAtomic(tempPath, resolvedPath, options) {
|
||||
}
|
||||
}
|
||||
|
||||
function readExistingFileMode(filePath) {
|
||||
try {
|
||||
return fs.statSync(filePath).mode & 0o777;
|
||||
} catch (error) {
|
||||
if (error.code === 'ENOENT') return undefined;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function writeFileAtomic(filePath, content, options = {}) {
|
||||
const resolvedPath = path.resolve(filePath);
|
||||
const parentDir = path.dirname(resolvedPath);
|
||||
@@ -66,9 +75,12 @@ function writeFileAtomic(filePath, content, options = {}) {
|
||||
let descriptor;
|
||||
try {
|
||||
if (options.validateParent) options.validateParent();
|
||||
descriptor = fs.openSync(tempPath, 'wx', mode);
|
||||
const existingMode = options.preserveExistingMode ? readExistingFileMode(resolvedPath) : undefined;
|
||||
descriptor = fs.openSync(tempPath, 'wx', existingMode ?? mode);
|
||||
if (options.validateParent) options.validateParent();
|
||||
fs.writeFileSync(descriptor, content, { encoding: options.encoding || 'utf8' });
|
||||
// Restore existing permissions after writing, without applying the process umask a second time.
|
||||
if (existingMode !== undefined) fs.fchmodSync(descriptor, existingMode);
|
||||
fs.fsyncSync(descriptor);
|
||||
fs.closeSync(descriptor);
|
||||
descriptor = undefined;
|
||||
|
||||
@@ -0,0 +1,415 @@
|
||||
/**
|
||||
* Shared dev-server command classification.
|
||||
*
|
||||
* Two hooks have to agree on what counts as "starting a dev server":
|
||||
* `pre-bash-dev-server-block.js` refuses it outside tmux, and
|
||||
* `auto-tmux-dev.js` rewrites it into a tmux session. They used to carry a
|
||||
* copy of the same raw-text regex each, with a comment in both asking the
|
||||
* other to stay byte-identical, so widening one silently left the other
|
||||
* behind. The classification lives here now, once.
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
const path = require('path');
|
||||
const { splitShellSegments } = require('./shell-split');
|
||||
const {
|
||||
extractCommandSubstitutions,
|
||||
extractSubshellGroups
|
||||
} = require('./shell-substitution');
|
||||
|
||||
const DEV_COMMAND_WORDS = new Set([
|
||||
'npm',
|
||||
'pnpm',
|
||||
'yarn',
|
||||
'bun',
|
||||
'npx',
|
||||
'tmux'
|
||||
]);
|
||||
const SKIPPABLE_PREFIX_WORDS = new Set(['env', 'command', 'builtin', 'exec', 'noglob', 'sudo', 'nohup']);
|
||||
const PREFIX_OPTION_VALUE_WORDS = {
|
||||
env: new Set(['-u', '-C', '-S', '--unset', '--chdir', '--split-string']),
|
||||
sudo: new Set([
|
||||
'-u',
|
||||
'-g',
|
||||
'-h',
|
||||
'-p',
|
||||
'-r',
|
||||
'-t',
|
||||
'-C',
|
||||
'--user',
|
||||
'--group',
|
||||
'--host',
|
||||
'--prompt',
|
||||
'--role',
|
||||
'--type',
|
||||
'--close-from'
|
||||
])
|
||||
};
|
||||
|
||||
function readToken(input, startIndex) {
|
||||
let index = startIndex;
|
||||
while (index < input.length && /\s/.test(input[index])) index += 1;
|
||||
if (index >= input.length) return null;
|
||||
|
||||
let token = '';
|
||||
let quote = null;
|
||||
|
||||
while (index < input.length) {
|
||||
const ch = input[index];
|
||||
|
||||
if (quote) {
|
||||
if (ch === quote) {
|
||||
quote = null;
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Inside double quotes, bash drops a backslash only before $ ` " \ or a
|
||||
// newline, so `"echo ready\;"` keeps its `\;` for tmux.
|
||||
if (ch === '\\' && quote === '"' && index + 1 < input.length && '$`"\\\n'.includes(input[index + 1])) {
|
||||
token += input[index + 1];
|
||||
index += 2;
|
||||
continue;
|
||||
}
|
||||
|
||||
token += ch;
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (ch === '"' || ch === "'") {
|
||||
quote = ch;
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (/\s/.test(ch)) break;
|
||||
|
||||
if (ch === '\\' && index + 1 < input.length) {
|
||||
token += input[index + 1];
|
||||
index += 2;
|
||||
continue;
|
||||
}
|
||||
|
||||
token += ch;
|
||||
index += 1;
|
||||
}
|
||||
|
||||
return { token, end: index };
|
||||
}
|
||||
|
||||
function shouldSkipOptionValue(wrapper, optionToken) {
|
||||
if (!wrapper || !optionToken || optionToken.includes('=')) return false;
|
||||
const optionSet = PREFIX_OPTION_VALUE_WORDS[wrapper];
|
||||
return Boolean(optionSet && optionSet.has(optionToken));
|
||||
}
|
||||
|
||||
function isOptionToken(token) {
|
||||
return token.startsWith('-') && token.length > 1;
|
||||
}
|
||||
|
||||
function normalizeCommandWord(token) {
|
||||
if (!token) return '';
|
||||
const base = path.basename(token).toLowerCase();
|
||||
return base.replace(/\.(cmd|exe|bat)$/i, '');
|
||||
}
|
||||
|
||||
function getLeadingCommand(segment) {
|
||||
let index = 0;
|
||||
let activeWrapper = null;
|
||||
let skipNextValue = false;
|
||||
|
||||
while (index < segment.length) {
|
||||
const parsed = readToken(segment, index);
|
||||
if (!parsed) return null;
|
||||
index = parsed.end;
|
||||
|
||||
const token = parsed.token;
|
||||
if (!token) continue;
|
||||
|
||||
if (skipNextValue) {
|
||||
skipNextValue = false;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (token === '--') {
|
||||
activeWrapper = null;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (token === '{' || token === '}') continue;
|
||||
|
||||
if (/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(token)) continue;
|
||||
|
||||
const normalizedToken = normalizeCommandWord(token);
|
||||
|
||||
if (SKIPPABLE_PREFIX_WORDS.has(normalizedToken)) {
|
||||
activeWrapper = normalizedToken;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (activeWrapper && isOptionToken(token)) {
|
||||
if (shouldSkipOptionValue(activeWrapper, token)) {
|
||||
skipNextValue = true;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
return { word: normalizedToken, end: index };
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
// tmux commands, and their aliases, that run their shell command in a tmux pane,
|
||||
// where its output stays readable. run-shell and `tmux -c` run it without one.
|
||||
const TMUX_PANE_COMMANDS = new Set([
|
||||
'new-session', 'new',
|
||||
'new-window', 'neww',
|
||||
'split-window', 'splitw',
|
||||
'respawn-pane', 'respawnp',
|
||||
'respawn-window', 'respawnw',
|
||||
'send-keys', 'send'
|
||||
]);
|
||||
// tmux's own options that take a value (`-L work`, `-Lwork`, or the last of a
|
||||
// cluster such as `-vL work`).
|
||||
const TMUX_OPTION_VALUE_LETTERS = new Set(['f', 'L', 'S', 'T']);
|
||||
// Raw-text spelling of a dev server, kept for tmux and npx arguments, where the
|
||||
// shell command is one argument among tmux's own. Trailing (?![\w-]) rather
|
||||
// than \b: `dev-setup` / `dev-docs` / `dev-build` are distinct scripts.
|
||||
const DEV_PATTERN = /\b(npm\s+run\s+dev|pnpm(?:\s+run)?\s+dev|yarn(?:\s+run)?\s+dev|bun(?:\s+run)?\s+dev)(?![\w-])/;
|
||||
|
||||
// The script name is decided from TOKENS, not from a regex over the raw text.
|
||||
// A raw-text `npm\s+run\s+dev` cannot see through the shell's own quoting, so
|
||||
// `npm run "dev"`, `npm run 'dev'` and `npm run de"v"` all reached the shell as
|
||||
// `npm run dev` and started the very server this hook exists to keep in tmux.
|
||||
// An option in between hid it just as well: `npm --silent run dev` and
|
||||
// `yarn --cwd app dev` were not matched either.
|
||||
//
|
||||
// Trailing `(?::|$)` rather than a word boundary: `dev` and `dev:ssr` are the
|
||||
// dev server, while `dev-setup` / `dev-docs` / `dev-build` are distinct scripts
|
||||
// that must keep running.
|
||||
const DEV_SCRIPT_NAME = /^dev(?::|$)/;
|
||||
const RUN_KEYWORDS = new Set(['run', 'run-script']);
|
||||
|
||||
/**
|
||||
* Each package manager's own grammar for the options that may precede a
|
||||
* script. The same short flag means different things per manager (pnpm `-d`
|
||||
* is `--loglevel=info`, bun `-d` is `--define <K:V>`, pnpm `-w` is the boolean
|
||||
* `--workspace-root`), so one shared table either swallows the script after a
|
||||
* boolean flag or reads an option's value as the script.
|
||||
*
|
||||
* - `requiresRun`: npm has no implicit script form (`npm dev` is not a
|
||||
* command), so its script is only ever the token after `run`. That makes
|
||||
* npm's open-ended `--<any-config-key> <value>` surface harmless without a
|
||||
* value table: `npm -d run dev` and `npm --userconfig x run dev` both read
|
||||
* the token after `run`.
|
||||
* - `values`: options that consume the following token (`--opt=value` is one
|
||||
* token and needs no entry).
|
||||
* - `optionalValues`: options whose value is optional, so the next bare token
|
||||
* may be either their value or the script; both readings are checked.
|
||||
*
|
||||
* Sources: pnpm `shorthands.ts` and CLI help, Yarn Classic/Berry global
|
||||
* options, bun `Arguments.rs`.
|
||||
*/
|
||||
const MANAGER_GRAMMARS = {
|
||||
npm: { requiresRun: true, values: new Set(), optionalValues: new Set() },
|
||||
pnpm: {
|
||||
requiresRun: false,
|
||||
values: new Set([
|
||||
'-C', '--dir', '-F', '--filter', '--filter-prod', '--test-pattern',
|
||||
'--changed-files-ignore-pattern', '--loglevel', '--reporter', '--store-dir',
|
||||
'--virtual-store-dir', '--modules-dir', '--lockfile-dir', '--registry',
|
||||
'--workspace-concurrency'
|
||||
]),
|
||||
optionalValues: new Set()
|
||||
},
|
||||
yarn: {
|
||||
requiresRun: false,
|
||||
values: new Set([
|
||||
'--cwd', '--modules-folder', '--cache-folder', '--preferred-cache-folder',
|
||||
'--global-folder', '--link-folder', '--mutex', '--network-timeout',
|
||||
'--network-concurrency', '--child-concurrency', '--registry', '--use-yarnrc'
|
||||
]),
|
||||
optionalValues: new Set()
|
||||
},
|
||||
bun: {
|
||||
requiresRun: false,
|
||||
values: new Set([
|
||||
'--cwd', '--env-file', '-F', '--filter', '-r', '--preload', '-d', '--define',
|
||||
'-l', '--loader', '--tsconfig-override', '--main-fields', '--shell',
|
||||
'--elide-lines', '--install', '--conditions', '--drop', '--feature'
|
||||
]),
|
||||
optionalValues: new Set(['-c', '--config', '--inspect', '--inspect-wait', '--inspect-brk'])
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* True when a package-manager invocation runs the dev script.
|
||||
*
|
||||
* With a `run` keyword the script is the token right after it, and anything
|
||||
* further along is an ARGUMENT to that script: `npm run build dev` runs build.
|
||||
* Without one (`pnpm dev`, `yarn dev`, `bun dev`), the script is the first
|
||||
* bare token, and everything after it, a later `run` included, is its
|
||||
* argument. `--` ends the manager's own arguments.
|
||||
*
|
||||
* Residual gap, stated rather than hidden: an implicit form behind a
|
||||
* value-taking option missing from the manager's table (`pnpm --unknown value
|
||||
* dev`) reads `value` as the script. pnpm, Yarn and bun usually spell such
|
||||
* options `--flag=value`, and npm, the one manager with an open-ended config
|
||||
* surface, has no implicit form at all.
|
||||
*
|
||||
* @param {string} segment
|
||||
* @param {number} start index just past the manager word
|
||||
* @param {string} manager
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function runsDevScript(segment, start, manager) {
|
||||
const grammar = MANAGER_GRAMMARS[manager];
|
||||
let index = start;
|
||||
let seenRunKeyword = false;
|
||||
let skipNextValue = false;
|
||||
let optionalValuePending = false;
|
||||
|
||||
for (let parsed = readToken(segment, index); parsed; parsed = readToken(segment, index)) {
|
||||
index = parsed.end;
|
||||
const token = parsed.token;
|
||||
if (!token) continue;
|
||||
|
||||
if (skipNextValue) {
|
||||
skipNextValue = false;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (token === '--') return false;
|
||||
|
||||
if (isOptionToken(token)) {
|
||||
optionalValuePending = false;
|
||||
if (!seenRunKeyword && grammar.values.has(token)) skipNextValue = true;
|
||||
else if (!seenRunKeyword && grammar.optionalValues.has(token)) optionalValuePending = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!seenRunKeyword && RUN_KEYWORDS.has(token.toLowerCase())) {
|
||||
seenRunKeyword = true;
|
||||
optionalValuePending = false;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (seenRunKeyword || !grammar.requiresRun) {
|
||||
if (DEV_SCRIPT_NAME.test(token)) return true;
|
||||
// Read as an optional option's value, the token is not the script.
|
||||
if (optionalValuePending) {
|
||||
optionalValuePending = false;
|
||||
continue;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return true when the tmux invocation that starts at `index` runs the dev
|
||||
* server outside a pane. The tmux commands follow tmux's own options
|
||||
* (`-L work`, `-f conf`), and the executable may come through a path or an env
|
||||
* prefix, so this reads the parsed tokens instead of the start of the segment.
|
||||
* A sequence (`new-session -d \; run-shell ...`) is exempt only when every
|
||||
* command in it that runs the dev server is a pane command.
|
||||
*/
|
||||
function tmuxRunsDevOutsidePane(segment, index) {
|
||||
const tokens = [];
|
||||
for (let parsed = readToken(segment, index); parsed; parsed = readToken(segment, parsed.end)) {
|
||||
if (parsed.token) tokens.push(parsed.token);
|
||||
}
|
||||
// A shell command passed to tmux as one argument is classified on its own;
|
||||
// the raw pattern keeps the spellings tmux joins from several arguments.
|
||||
const runsDev = words => DEV_PATTERN.test(words.join(' ')) || words.some(isDevServerCommand);
|
||||
const segmentRunsDev = DEV_PATTERN.test(segment) || runsDev(tokens);
|
||||
|
||||
let next = 0;
|
||||
for (; next < tokens.length && isOptionToken(tokens[next]); next++) {
|
||||
const letters = tokens[next].slice(1);
|
||||
for (let i = 0; i < letters.length; i++) {
|
||||
// -c runs its shell command without a pane.
|
||||
if (letters[i] === 'c') return segmentRunsDev;
|
||||
if (TMUX_OPTION_VALUE_LETTERS.has(letters[i])) {
|
||||
if (i === letters.length - 1) next++;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// tmux ends a command at a `;` argument and at a `;` that ends an argument
|
||||
// (`'npm run dev;'`); an escaped `\;` at the end stays literal.
|
||||
const commands = [[]];
|
||||
for (const token of tokens.slice(next)) {
|
||||
const ends = token.endsWith(';') && !token.endsWith('\\;');
|
||||
const value = ends ? token.slice(0, -1) : token;
|
||||
if (value) commands[commands.length - 1].push(value);
|
||||
if (ends) commands.push([]);
|
||||
}
|
||||
const devCommands = commands.filter(command => command.length > 0 && runsDev(command.slice(1)));
|
||||
if (devCommands.length === 0) return segmentRunsDev;
|
||||
return !devCommands.every(command => TMUX_PANE_COMMANDS.has(command[0]));
|
||||
}
|
||||
|
||||
/**
|
||||
* Collect every command-line segment we should evaluate. Returns the top-level
|
||||
* segments first, then segments harvested from `$(...)` / backtick command
|
||||
* substitutions and plain `(...)` subshell groups, recursively.
|
||||
*
|
||||
* Without this expansion the leading-command check only sees the outermost
|
||||
* command, so wrappers like `$(npm run dev)` and `(npm run dev)` (which still
|
||||
* spawn a dev server) sneak past.
|
||||
*/
|
||||
function collectCheckSegments(cmd) {
|
||||
const segments = [...splitShellSegments(cmd)];
|
||||
// Expanded here-document bodies enter through splitShellSegments, so their
|
||||
// segments must also be scanned for substitutions nested inside them.
|
||||
const queue = [cmd, ...segments];
|
||||
const seen = new Set();
|
||||
|
||||
// Read by index: shift() copies the queue each time, which is quadratic on a long command.
|
||||
for (let head = 0; head < queue.length; head++) {
|
||||
const current = queue[head];
|
||||
if (seen.has(current)) continue;
|
||||
seen.add(current);
|
||||
|
||||
for (const body of [...extractCommandSubstitutions(current), ...extractSubshellGroups(current)]) {
|
||||
const bodySegments = splitShellSegments(body);
|
||||
// One at a time: spreading a long command's segments into push() exceeds the argument limit.
|
||||
queue.push(body);
|
||||
for (const segment of bodySegments) {
|
||||
segments.push(segment);
|
||||
queue.push(segment);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return segments;
|
||||
}
|
||||
|
||||
function isDevServerSegment(segment) {
|
||||
const command = getLeadingCommand(segment);
|
||||
if (!command || !DEV_COMMAND_WORDS.has(command.word)) return false;
|
||||
if (command.word === 'tmux') return tmuxRunsDevOutsidePane(segment, command.end);
|
||||
if (Object.prototype.hasOwnProperty.call(MANAGER_GRAMMARS, command.word)) {
|
||||
return runsDevScript(segment, command.end, command.word);
|
||||
}
|
||||
// npx keeps the raw-text match on the package command it launches.
|
||||
return DEV_PATTERN.test(segment);
|
||||
}
|
||||
|
||||
/** True when any segment of `command` starts a dev server outside a tmux pane. */
|
||||
function isDevServerCommand(command) {
|
||||
return collectCheckSegments(String(command || '')).some(isDevServerSegment);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
collectCheckSegments,
|
||||
isDevServerCommand,
|
||||
isDevServerSegment
|
||||
};
|
||||
@@ -103,16 +103,23 @@ const HARNESS_CAPABILITIES = deepFreeze([
|
||||
},
|
||||
{
|
||||
id: 'antigravity',
|
||||
label: 'Antigravity',
|
||||
targetIds: ['antigravity'],
|
||||
channel: 'managed-project',
|
||||
installMode: 'managed-project',
|
||||
label: 'Google Antigravity',
|
||||
targetIds: ['antigravity-home', 'antigravity'],
|
||||
channel: 'native-plugin',
|
||||
installMode: 'native-plugin',
|
||||
guidedReady: false,
|
||||
availability: 'advanced',
|
||||
destination: './.agents',
|
||||
scopes: [scope('project', 'antigravity', './.agents')],
|
||||
hooks: hooks('not-configured', false, 'ECC hooks are not configured by this adapter.'),
|
||||
aliases: ['google-antigravity'],
|
||||
destination: 'Selected Antigravity scope: ~/.gemini/config/plugins/ecc or ./.agents',
|
||||
scopes: [
|
||||
scope('user', 'antigravity-home', '~/.gemini/config/plugins/ecc'),
|
||||
scope('project', 'antigravity', './.agents'),
|
||||
],
|
||||
hooks: hooks(
|
||||
'profile-selection',
|
||||
true,
|
||||
'ECC hooks are configured through Antigravity PreToolUse and Stop lifecycle hooks.'
|
||||
),
|
||||
aliases: ['google-antigravity', 'gemini-antigravity', 'agy'],
|
||||
},
|
||||
{
|
||||
id: 'copilot',
|
||||
@@ -231,6 +238,23 @@ const HARNESS_CAPABILITIES = deepFreeze([
|
||||
hooks: hooks('not-configured', false, 'ECC hooks are not configured by this adapter.'),
|
||||
aliases: ['adal-cli'],
|
||||
},
|
||||
{
|
||||
id: 'mistral-vibe',
|
||||
label: 'Mistral Vibe',
|
||||
targetIds: ['mistral-vibe'],
|
||||
channel: 'managed-project',
|
||||
installMode: 'managed-project',
|
||||
guidedReady: false,
|
||||
availability: 'advanced',
|
||||
destination: './.vibe',
|
||||
scopes: [scope('project', 'mistral-vibe', './.vibe')],
|
||||
hooks: hooks(
|
||||
'not-configured',
|
||||
false,
|
||||
'ECC installs selected Agent Skills only; Vibe hooks, agents, and provider configuration are not configured.'
|
||||
),
|
||||
aliases: ['vibe'],
|
||||
},
|
||||
{
|
||||
id: 'hermes',
|
||||
label: 'Hermes',
|
||||
|
||||
@@ -47,6 +47,12 @@ function validateLegacyTarget(target) {
|
||||
// positional syntax (which is legacy-only). Guide the user to the right mode
|
||||
// instead of implying the target is unknown (#2282).
|
||||
if (SUPPORTED_INSTALL_TARGETS.includes(target)) {
|
||||
if (target === 'mistral-vibe') {
|
||||
throw new Error(
|
||||
"Target 'mistral-vibe' supports explicit Agent Skill installs only. " +
|
||||
"Use `install.sh --target mistral-vibe --skills <id,...>`."
|
||||
);
|
||||
}
|
||||
throw new Error(
|
||||
`Target '${target}' is supported, but the bare-language install syntax only accepts ${LEGACY_INSTALL_TARGETS.join(', ')}. ` +
|
||||
`Install '${target}' with a component selection instead, e.g. \`install.sh --target ${target} --profile full\` ` +
|
||||
|
||||
@@ -7,7 +7,8 @@ const { isDeepStrictEqual } = require('util');
|
||||
|
||||
const { loadInstallManifests } = require('./install-manifests');
|
||||
const { readInstallState, validateInstallState } = require('./install-state');
|
||||
const { assertWithinTrustedRoot } = require('./path-safety');
|
||||
const { assertWithinTrustedRoot, isWithinRoot } = require('./path-safety');
|
||||
const { isPackageSourcePath, resolvePackageSourcePath } = require('./install/package-source');
|
||||
const { createInstallPlanFromRequest } = require('./install/runtime');
|
||||
const { assertNoNewUserOwnedFile, prepareUserOwnedFileGuard } = require('./install/ownership-guard');
|
||||
const { withOpenCodeInstallLocks } = require('./install/opencode-install-lock');
|
||||
@@ -198,6 +199,17 @@ function resolveOperationSourcePath(repoRoot, operation) {
|
||||
throw createUnsafeRepairSourceError();
|
||||
}
|
||||
|
||||
if (isPackageSourcePath(sourceRelativePath)) {
|
||||
let packageSourcePath;
|
||||
try {
|
||||
packageSourcePath = resolvePackageSourcePath(repoRoot, sourceRelativePath);
|
||||
} catch {
|
||||
throw createUnsafeRepairSourceError();
|
||||
}
|
||||
// An unresolvable package reports as a missing source, not an unsafe one.
|
||||
return packageSourcePath || path.resolve(repoRoot, sourceRelativePath);
|
||||
}
|
||||
|
||||
return assertSafeRepairSourcePath(
|
||||
path.resolve(repoRoot, sourceRelativePath),
|
||||
repoRoot
|
||||
@@ -788,13 +800,18 @@ function inspectManagedOperation(repoRoot, trustedRoot, operation, linkIndex = n
|
||||
}
|
||||
}
|
||||
|
||||
function summarizeManagedOperationHealth(repoRoot, trustedRoot, operations, target = null) {
|
||||
function trustedRootForDestination(destinationPath, targetRoot, trustedRoots = [targetRoot]) {
|
||||
const parent = typeof destinationPath === 'string' ? path.dirname(destinationPath) : destinationPath;
|
||||
return trustedRoots.find(root => isWithinRoot(parent, root)) || targetRoot;
|
||||
}
|
||||
|
||||
function summarizeManagedOperationHealth(repoRoot, trustedRoot, operations, target = null, trustedRoots = [trustedRoot]) {
|
||||
const linkIndex = buildLinkIndexForOperations(operations, trustedRoot);
|
||||
return operations.reduce(
|
||||
(summary, operation) => {
|
||||
const inspection = inspectManagedOperation(
|
||||
repoRoot,
|
||||
trustedRoot,
|
||||
trustedRootForDestination(operation.destinationPath, trustedRoot, trustedRoots),
|
||||
operation,
|
||||
linkIndex,
|
||||
target
|
||||
@@ -1110,11 +1127,21 @@ function collectTargetPathIssues(record, state, issues) {
|
||||
}
|
||||
|
||||
function collectOperationHealthIssues(record, context, state, issues) {
|
||||
let trustedRoots;
|
||||
try {
|
||||
trustedRoots = getInstallTargetAdapter(record.adapter.id || record.adapter.target)
|
||||
.resolveTrustedRoots(context);
|
||||
} catch (error) {
|
||||
// Report an unsafe root for this target without aborting the other targets.
|
||||
issues.push(buildIssue('error', 'unsafe-trusted-root', error.message));
|
||||
return;
|
||||
}
|
||||
const operationHealth = summarizeManagedOperationHealth(
|
||||
context.repoRoot,
|
||||
record.targetRoot,
|
||||
getManagedOperations(state),
|
||||
record.adapter.target
|
||||
record.adapter.target,
|
||||
trustedRoots
|
||||
);
|
||||
const destinationPaths = entries => entries.map(entry => entry.destinationPath);
|
||||
|
||||
@@ -1594,7 +1621,8 @@ function planOpencodeBuildRepair(repair, build) {
|
||||
desiredPlan.sourceRoot || context.repoRoot,
|
||||
record.targetRoot,
|
||||
desiredPlan.operations,
|
||||
record.adapter.target
|
||||
record.adapter.target,
|
||||
repair.trustedRoots
|
||||
);
|
||||
const unsafeOperationResult = getUnsafeOperationResult(record, operationHealth);
|
||||
if (unsafeOperationResult) return unsafeOperationResult;
|
||||
@@ -1657,12 +1685,12 @@ function executeGuardedRepairOperation(repair, plan, operation, repairedPaths) {
|
||||
const repairedPath = executeRepairOperation(
|
||||
desiredPlan.sourceRoot || context.repoRoot,
|
||||
operation,
|
||||
record.targetRoot,
|
||||
trustedRootForDestination(operation.destinationPath, record.targetRoot, repair.trustedRoots),
|
||||
{
|
||||
linkIndex: repairLinkIndex,
|
||||
target: record.adapter.target,
|
||||
settingsLockHeld,
|
||||
writeOptions: apply.getOpenCodeActivationWriteOptions(operation, activationSnapshot),
|
||||
linkIndex: repairLinkIndex,
|
||||
target: record.adapter.target,
|
||||
settingsLockHeld,
|
||||
writeOptions: apply.getOpenCodeActivationWriteOptions(operation, activationSnapshot),
|
||||
}
|
||||
);
|
||||
if (repairedPath) {
|
||||
@@ -1749,7 +1777,8 @@ function repairManagedRecord(repair, build) {
|
||||
repairSourceRoot,
|
||||
record.targetRoot,
|
||||
desiredPlan.operations,
|
||||
record.adapter.target
|
||||
record.adapter.target,
|
||||
repair.trustedRoots
|
||||
);
|
||||
|
||||
const unsafeOperationResult = getUnsafeOperationResult(record, operationHealth);
|
||||
@@ -1802,7 +1831,8 @@ function repairManagedRecord(repair, build) {
|
||||
|
||||
// Repair one discovered record. `repair` carries the record, lifecycle
|
||||
// context, caller options, the OpenCode build runner, an optional OpenCode
|
||||
// lease, and whether the Claude settings lock is already held.
|
||||
// lease, whether the Claude settings lock is already held, and the adapter's
|
||||
// trusted roots for destinations outside the target root.
|
||||
function runRecordRepair(repair) {
|
||||
const { record, context, options } = repair;
|
||||
const needsOpencodeBuild = record.adapter.target === 'opencode'
|
||||
@@ -1852,6 +1882,8 @@ function repairInstalledStates(options = {}) {
|
||||
|
||||
let releaseSettingsLock = null;
|
||||
try {
|
||||
const trustedRoots = getInstallTargetAdapter(record.adapter.id || record.adapter.target)
|
||||
.resolveTrustedRoots(context);
|
||||
preflightOpenCodeHookDeactivation(record, context);
|
||||
releaseSettingsLock = acquireRepairSettingsLock(record, options);
|
||||
return runRecordRepair({
|
||||
@@ -1861,6 +1893,7 @@ function repairInstalledStates(options = {}) {
|
||||
buildOpencodeRunner,
|
||||
opencodeLease,
|
||||
settingsLockHeld: Boolean(releaseSettingsLock),
|
||||
trustedRoots,
|
||||
});
|
||||
} catch (error) {
|
||||
return repairErrorResult(record, error.message);
|
||||
@@ -1922,12 +1955,22 @@ function repairInstalledStates(options = {}) {
|
||||
}
|
||||
|
||||
|
||||
function resolveRecordTrustedRoots(record, context) {
|
||||
const adapter = record.adapter && getInstallTargetAdapter(record.adapter.id || record.adapter.target);
|
||||
return adapter && typeof adapter.resolveTrustedRoots === 'function'
|
||||
? adapter.resolveTrustedRoots(context)
|
||||
: [record.targetRoot];
|
||||
}
|
||||
|
||||
function uninstallInstalledStates(options = {}) {
|
||||
const records = discoverInstalledStates({
|
||||
homeDir: options.homeDir,
|
||||
projectRoot: options.projectRoot,
|
||||
targets: options.targets,
|
||||
const context = {
|
||||
homeDir: options.homeDir || process.env.HOME || os.homedir(),
|
||||
projectRoot: options.projectRoot || process.cwd(),
|
||||
env: resolveInvocationEnvironment(options),
|
||||
};
|
||||
const records = discoverInstalledStates({
|
||||
...context,
|
||||
targets: options.targets,
|
||||
}).filter(record => record.exists);
|
||||
|
||||
const results = records.map(record => {
|
||||
@@ -1984,6 +2027,8 @@ function uninstallInstalledStates(options = {}) {
|
||||
);
|
||||
}
|
||||
|
||||
const trustedRoots = resolveRecordTrustedRoots(record, context);
|
||||
|
||||
const { isScriptBoundary, retainScriptBoundary } = require('./install/opencode-script-boundary');
|
||||
// Remove owned script bodies first. Keep their CommonJS scope while any
|
||||
// retained or user-created JavaScript still relies on that boundary.
|
||||
@@ -1996,7 +2041,7 @@ function uninstallInstalledStates(options = {}) {
|
||||
retainedPaths.push(operation.destinationPath);
|
||||
continue;
|
||||
}
|
||||
const outcome = executeUninstallOperation(operation, record.targetRoot, {
|
||||
const outcome = executeUninstallOperation(operation, trustedRootForDestination(operation.destinationPath, record.targetRoot, trustedRoots), {
|
||||
preserveDriftedCopies: true,
|
||||
target: record.adapter.target,
|
||||
settingsLockHeld: Boolean(releaseSettingsLock),
|
||||
@@ -2020,7 +2065,8 @@ function uninstallInstalledStates(options = {}) {
|
||||
}
|
||||
|
||||
for (const cleanupTarget of cleanupTargets) {
|
||||
cleanupEmptyParentDirs(cleanupTarget, record.targetRoot);
|
||||
const matchingRoot = trustedRootForDestination(cleanupTarget, record.targetRoot, trustedRoots);
|
||||
cleanupEmptyParentDirs(cleanupTarget, matchingRoot);
|
||||
}
|
||||
|
||||
return {
|
||||
|
||||
@@ -5,7 +5,7 @@ const { getInstallTargetAdapter, planInstallTargetScaffold } = require('./instal
|
||||
const { resolveInvocationEnvironment } = require('./invocation-environment');
|
||||
|
||||
const DEFAULT_REPO_ROOT = path.join(__dirname, '../..');
|
||||
const SUPPORTED_INSTALL_TARGETS = ['claude', 'claude-project', 'cursor', 'antigravity', 'codex', 'copilot', 'gemini', 'opencode', 'codebuddy', 'joycode', 'qwen', 'zed', 'hermes', 'openclaw', 'kimi', 'adal', 'grok'];
|
||||
const SUPPORTED_INSTALL_TARGETS = ['claude', 'claude-project', 'cursor', 'antigravity', 'antigravity-home', 'codex', 'copilot', 'gemini', 'opencode', 'codebuddy', 'joycode', 'qwen', 'zed', 'hermes', 'openclaw', 'kimi', 'adal', 'grok', 'mistral-vibe'];
|
||||
const COMPONENT_FAMILY_PREFIXES = {
|
||||
baseline: 'baseline:',
|
||||
language: 'lang:',
|
||||
@@ -77,6 +77,14 @@ const LEGACY_COMPAT_BASE_MODULE_IDS_BY_TARGET = Object.freeze({
|
||||
'skill-unified-memory',
|
||||
'workflow-quality',
|
||||
],
|
||||
'antigravity-home': [
|
||||
'rules-core',
|
||||
'agents-core',
|
||||
'commands-core',
|
||||
'hooks-runtime',
|
||||
'platform-configs',
|
||||
'workflow-quality',
|
||||
],
|
||||
zed: [
|
||||
'rules-core',
|
||||
'agents-core',
|
||||
@@ -195,42 +203,58 @@ function listSkillDirectoryIds(repoRoot) {
|
||||
.sort();
|
||||
}
|
||||
|
||||
function addSyntheticSkillComponents({ repoRoot, modules, components }) {
|
||||
const moduleIds = new Set(modules.map(module => module.id));
|
||||
function addSyntheticSkillComponents({ repoRoot, modules, components, target = null }) {
|
||||
const originalModuleIds = new Set(modules.map(module => module.id));
|
||||
const componentIds = new Set(components.map(component => component.id));
|
||||
const syntheticModules = [];
|
||||
const syntheticComponents = [];
|
||||
|
||||
for (const skillId of listSkillDirectoryIds(repoRoot)) {
|
||||
const componentId = `skill:${skillId}`;
|
||||
const needsTargetSpecificModule = target === 'mistral-vibe';
|
||||
if (componentIds.has(componentId) && !needsTargetSpecificModule) {
|
||||
continue;
|
||||
}
|
||||
const moduleId = `skill-${skillId}`;
|
||||
const exactSkillModule = {
|
||||
id: moduleId,
|
||||
kind: 'skills',
|
||||
description: `Single-skill install surface for ${skillId}.`,
|
||||
paths: [`skills/${skillId}`],
|
||||
targets: needsTargetSpecificModule
|
||||
? ['mistral-vibe']
|
||||
: SUPPORTED_INSTALL_TARGETS.slice(),
|
||||
dependencies: [],
|
||||
defaultInstall: false,
|
||||
cost: 'light',
|
||||
stability: 'stable',
|
||||
synthetic: true,
|
||||
};
|
||||
if (needsTargetSpecificModule || !originalModuleIds.has(moduleId)) {
|
||||
syntheticModules.push(exactSkillModule);
|
||||
}
|
||||
|
||||
if (componentIds.has(componentId)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const moduleId = `skill-${skillId}`;
|
||||
if (!moduleIds.has(moduleId)) {
|
||||
modules.push({
|
||||
id: moduleId,
|
||||
kind: 'skills',
|
||||
description: `Single-skill install surface for ${skillId}.`,
|
||||
paths: [`skills/${skillId}`],
|
||||
targets: SUPPORTED_INSTALL_TARGETS.slice(),
|
||||
dependencies: [],
|
||||
defaultInstall: false,
|
||||
cost: 'light',
|
||||
stability: 'stable',
|
||||
synthetic: true,
|
||||
});
|
||||
moduleIds.add(moduleId);
|
||||
}
|
||||
|
||||
components.push({
|
||||
syntheticComponents.push({
|
||||
id: componentId,
|
||||
family: 'skill',
|
||||
description: `Install only the ${skillId} skill directory.`,
|
||||
modules: [moduleId],
|
||||
synthetic: true,
|
||||
});
|
||||
componentIds.add(componentId);
|
||||
}
|
||||
|
||||
const replacementModuleIds = new Set(syntheticModules.map(module => module.id));
|
||||
return {
|
||||
modules: [
|
||||
...modules.filter(module => !replacementModuleIds.has(module.id)),
|
||||
...syntheticModules,
|
||||
],
|
||||
components: [...components, ...syntheticComponents],
|
||||
};
|
||||
}
|
||||
|
||||
function readOptionalStringOption(options, key) {
|
||||
@@ -298,6 +322,21 @@ function intersectTargets(modules) {
|
||||
));
|
||||
}
|
||||
|
||||
function getComponentModuleIds(component, manifests, target = null) {
|
||||
const skillId = component.id.startsWith(COMPONENT_FAMILY_PREFIXES.skill)
|
||||
? component.id.slice(COMPONENT_FAMILY_PREFIXES.skill.length)
|
||||
: null;
|
||||
const exactSkillModuleId = skillId ? `skill-${skillId}` : null;
|
||||
if (
|
||||
target === 'mistral-vibe'
|
||||
&& exactSkillModuleId
|
||||
&& manifests.modulesById.has(exactSkillModuleId)
|
||||
) {
|
||||
return [exactSkillModuleId];
|
||||
}
|
||||
return dedupeStrings(component.modules);
|
||||
}
|
||||
|
||||
function getManifestPaths(repoRoot = DEFAULT_REPO_ROOT) {
|
||||
return {
|
||||
modulesPath: path.join(repoRoot, 'manifests', 'install-modules.json'),
|
||||
@@ -325,9 +364,16 @@ function loadInstallManifests(options = {}) {
|
||||
: {};
|
||||
const components = Array.isArray(componentsData.components) ? componentsData.components.slice() : [];
|
||||
|
||||
addSyntheticSkillComponents({ repoRoot, modules, components });
|
||||
const withSyntheticSkills = addSyntheticSkillComponents({
|
||||
repoRoot,
|
||||
modules,
|
||||
components,
|
||||
target: options.target || null,
|
||||
});
|
||||
const resolvedModules = withSyntheticSkills.modules;
|
||||
const resolvedComponents = withSyntheticSkills.components;
|
||||
|
||||
for (const module of modules) {
|
||||
for (const module of resolvedModules) {
|
||||
readModuleTargetsOrThrow(module);
|
||||
if (module.optionalDependencies !== undefined && (
|
||||
!Array.isArray(module.optionalDependencies)
|
||||
@@ -337,17 +383,17 @@ function loadInstallManifests(options = {}) {
|
||||
}
|
||||
}
|
||||
|
||||
const modulesById = new Map(modules.map(module => [module.id, module]));
|
||||
const componentsById = new Map(components.map(component => [component.id, component]));
|
||||
const modulesById = new Map(resolvedModules.map(module => [module.id, module]));
|
||||
const componentsById = new Map(resolvedComponents.map(component => [component.id, component]));
|
||||
|
||||
return {
|
||||
repoRoot,
|
||||
modulesPath,
|
||||
profilesPath,
|
||||
componentsPath,
|
||||
modules,
|
||||
modules: resolvedModules,
|
||||
profiles,
|
||||
components,
|
||||
components: resolvedComponents,
|
||||
modulesById,
|
||||
componentsById,
|
||||
modulesVersion: modulesData.version,
|
||||
@@ -410,7 +456,7 @@ function listInstallComponents(options = {}) {
|
||||
return manifests.components
|
||||
.filter(component => !family || component.family === family)
|
||||
.map(component => {
|
||||
const moduleIds = dedupeStrings(component.modules);
|
||||
const moduleIds = getComponentModuleIds(component, manifests, target);
|
||||
const modules = moduleIds
|
||||
.map(moduleId => manifests.modulesById.get(moduleId))
|
||||
.filter(Boolean);
|
||||
@@ -441,7 +487,7 @@ function getInstallComponent(componentId, options = {}) {
|
||||
throw new Error(`Unknown install component: ${normalizedComponentId}`);
|
||||
}
|
||||
|
||||
const moduleIds = dedupeStrings(component.modules);
|
||||
const moduleIds = getComponentModuleIds(component, manifests, options.target || null);
|
||||
const modules = moduleIds
|
||||
.map(moduleId => manifests.modulesById.get(moduleId))
|
||||
.filter(Boolean)
|
||||
@@ -467,7 +513,7 @@ function getInstallComponent(componentId, options = {}) {
|
||||
};
|
||||
}
|
||||
|
||||
function expandComponentIdsToModuleIds(componentIds, manifests) {
|
||||
function expandComponentIdsToModuleIds(componentIds, manifests, options = {}) {
|
||||
const expandedModuleIds = [];
|
||||
|
||||
for (const componentId of dedupeStrings(componentIds)) {
|
||||
@@ -475,7 +521,11 @@ function expandComponentIdsToModuleIds(componentIds, manifests) {
|
||||
if (!component) {
|
||||
throw new Error(`Unknown install component: ${componentId}`);
|
||||
}
|
||||
expandedModuleIds.push(...component.modules);
|
||||
expandedModuleIds.push(...getComponentModuleIds(
|
||||
component,
|
||||
manifests,
|
||||
options.target || null
|
||||
));
|
||||
}
|
||||
|
||||
return dedupeStrings(expandedModuleIds);
|
||||
@@ -555,13 +605,19 @@ function resolveLegacyCompatibilitySelection(options = {}) {
|
||||
}
|
||||
|
||||
function resolveInstallPlan(options = {}) {
|
||||
const manifests = loadInstallManifests(options);
|
||||
const target = options.target || null;
|
||||
const manifests = loadInstallManifests({ ...options, target });
|
||||
const requestedProfileId = options.profileId || null;
|
||||
const explicitModuleIds = dedupeStrings(options.moduleIds);
|
||||
const includedComponentIds = dedupeStrings(options.includeComponentIds);
|
||||
const excludedComponentIds = dedupeStrings(options.excludeComponentIds);
|
||||
const requestedModuleIds = [];
|
||||
const target = options.target || null;
|
||||
|
||||
if (target === 'mistral-vibe' && requestedProfileId) {
|
||||
throw new Error(
|
||||
'Mistral Vibe currently supports explicit Agent Skill installs only; use --skills <id,...> instead of a profile.'
|
||||
);
|
||||
}
|
||||
|
||||
if (target && !SUPPORTED_INSTALL_TARGETS.includes(target)) {
|
||||
throw new Error(
|
||||
@@ -589,16 +645,24 @@ function resolveInstallPlan(options = {}) {
|
||||
}
|
||||
|
||||
requestedModuleIds.push(...explicitModuleIds);
|
||||
requestedModuleIds.push(...expandComponentIdsToModuleIds(includedComponentIds, manifests));
|
||||
requestedModuleIds.push(...expandComponentIdsToModuleIds(
|
||||
includedComponentIds,
|
||||
manifests,
|
||||
{ target }
|
||||
));
|
||||
|
||||
const excludedModuleIds = expandComponentIdsToModuleIds(excludedComponentIds, manifests);
|
||||
const excludedModuleIds = expandComponentIdsToModuleIds(
|
||||
excludedComponentIds,
|
||||
manifests,
|
||||
{ target }
|
||||
);
|
||||
const excludedModuleOwners = new Map();
|
||||
for (const componentId of excludedComponentIds) {
|
||||
const component = manifests.componentsById.get(componentId);
|
||||
if (!component) {
|
||||
throw new Error(`Unknown install component: ${componentId}`);
|
||||
}
|
||||
for (const moduleId of component.modules) {
|
||||
for (const moduleId of getComponentModuleIds(component, manifests, target)) {
|
||||
const owners = excludedModuleOwners.get(moduleId) || [];
|
||||
owners.push(componentId);
|
||||
excludedModuleOwners.set(moduleId, owners);
|
||||
@@ -630,6 +694,11 @@ function resolveInstallPlan(options = {}) {
|
||||
);
|
||||
|
||||
if (requestedModuleIds.length === 0) {
|
||||
if (target === 'mistral-vibe') {
|
||||
throw new Error(
|
||||
'Mistral Vibe currently supports explicit Agent Skill installs only; use --skills <id,...>.'
|
||||
);
|
||||
}
|
||||
throw new Error('No install profile, module IDs, or included component IDs were provided');
|
||||
}
|
||||
|
||||
@@ -727,6 +796,11 @@ function resolveInstallPlan(options = {}) {
|
||||
const selectedModules = manifests.modules.filter(module => selectedIds.has(module.id));
|
||||
const skippedModules = manifests.modules.filter(module => skippedTargetIds.has(module.id));
|
||||
const excludedModules = manifests.modules.filter(module => excludedIds.has(module.id));
|
||||
if (target === 'mistral-vibe' && selectedModules.length === 0) {
|
||||
throw new Error(
|
||||
'Mistral Vibe currently supports explicit Agent Skill installs only; use --skills <id,...>.'
|
||||
);
|
||||
}
|
||||
const scaffoldPlan = target
|
||||
? planInstallTargetScaffold({
|
||||
target,
|
||||
@@ -765,6 +839,7 @@ function resolveInstallPlan(options = {}) {
|
||||
targetAdapterId: scaffoldPlan ? scaffoldPlan.adapter.id : null,
|
||||
homeDir: targetPlanningInput ? targetPlanningInput.homeDir : null,
|
||||
targetRoot: scaffoldPlan ? scaffoldPlan.targetRoot : null,
|
||||
trustedRoots: scaffoldPlan ? scaffoldPlan.trustedRoots : (scaffoldPlan?.targetRoot ? [scaffoldPlan.targetRoot] : []),
|
||||
installStatePath: scaffoldPlan ? scaffoldPlan.installStatePath : null,
|
||||
operations: scaffoldPlan ? scaffoldPlan.operations : [],
|
||||
};
|
||||
|
||||
@@ -0,0 +1,207 @@
|
||||
'use strict';
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const {
|
||||
HOME_INSTALL_EXCLUDED_SOURCE_PATHS,
|
||||
createFlatRuleOperations,
|
||||
createInstallTargetAdapter,
|
||||
createManagedOperation,
|
||||
createManagedScaffoldOperation,
|
||||
isForeignPlatformPath,
|
||||
normalizeRelativePath,
|
||||
} = require('./helpers');
|
||||
const { buildAntigravityHooksConfig } = require('../antigravity-hooks');
|
||||
const { buildAntigravityMcpConfig, planAntigravityMemoryRuntime } = require('../antigravity-mcp');
|
||||
const { buildAntigravityPluginManifest } = require('../antigravity-plugin');
|
||||
const { getHookProfile } = require('../hook-flags');
|
||||
const { isWithinRoot } = require('../path-safety');
|
||||
|
||||
module.exports = createInstallTargetAdapter({
|
||||
id: 'antigravity-home',
|
||||
target: 'antigravity-home',
|
||||
kind: 'home',
|
||||
rootSegments: ['.gemini', 'config', 'plugins', 'ecc'],
|
||||
installStatePathSegments: ['ecc-install-state.json'],
|
||||
nativeRootRelativePath: '.gemini',
|
||||
excludedSourcePaths: HOME_INSTALL_EXCLUDED_SOURCE_PATHS,
|
||||
resolveTrustedRoots(input, targetRoot) {
|
||||
const configRoot = path.dirname(path.dirname(targetRoot));
|
||||
const workflowsRoot = path.join(configRoot, 'workflows');
|
||||
if (!isWithinRoot(workflowsRoot, configRoot)) {
|
||||
throw new Error('Refusing Antigravity workflows outside the trusted config root.');
|
||||
}
|
||||
return [targetRoot, workflowsRoot];
|
||||
},
|
||||
planOperations(input, adapter) {
|
||||
const modules = Array.isArray(input.modules)
|
||||
? input.modules
|
||||
: (input.module ? [input.module] : []);
|
||||
const {
|
||||
repoRoot,
|
||||
projectRoot,
|
||||
homeDir,
|
||||
} = input;
|
||||
const planningInput = {
|
||||
repoRoot,
|
||||
projectRoot,
|
||||
homeDir,
|
||||
};
|
||||
const targetRoot = adapter.resolveRoot(planningInput);
|
||||
|
||||
return modules.flatMap(module => {
|
||||
const paths = Array.isArray(module.paths) ? module.paths : [];
|
||||
return paths
|
||||
.filter(p => !isForeignPlatformPath(p, 'antigravity') && !adapter.excludesSourcePath(p))
|
||||
.flatMap(sourceRelativePath => {
|
||||
const normalizedSourcePath = normalizeRelativePath(sourceRelativePath);
|
||||
|
||||
if (
|
||||
normalizedSourcePath === 'rules'
|
||||
|| normalizedSourcePath.startsWith('rules/')
|
||||
) {
|
||||
return createFlatRuleOperations({
|
||||
moduleId: module.id,
|
||||
repoRoot,
|
||||
sourceRelativePath: normalizedSourcePath,
|
||||
destinationDir: path.join(targetRoot, 'rules'),
|
||||
});
|
||||
}
|
||||
|
||||
if (
|
||||
normalizedSourcePath === 'commands'
|
||||
|| normalizedSourcePath.startsWith('commands/')
|
||||
) {
|
||||
const commandRelativePath = normalizedSourcePath === 'commands'
|
||||
? ''
|
||||
: normalizedSourcePath.slice('commands/'.length);
|
||||
const workflowsRoot = path.join(
|
||||
path.dirname(path.dirname(targetRoot)),
|
||||
'workflows'
|
||||
);
|
||||
return [
|
||||
createManagedScaffoldOperation(
|
||||
module.id,
|
||||
normalizedSourcePath,
|
||||
path.join(workflowsRoot, commandRelativePath),
|
||||
'preserve-relative-path'
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
if (
|
||||
normalizedSourcePath === 'agents'
|
||||
|| normalizedSourcePath.startsWith('agents/')
|
||||
) {
|
||||
const agentRelativePath = normalizedSourcePath === 'agents'
|
||||
? ''
|
||||
: normalizedSourcePath.slice('agents/'.length);
|
||||
return [
|
||||
createManagedOperation({
|
||||
moduleId: module.id,
|
||||
sourceRelativePath: normalizedSourcePath,
|
||||
destinationPath: path.join(targetRoot, 'agents', agentRelativePath),
|
||||
strategy: 'preserve-relative-path',
|
||||
contentTransform: 'antigravity-agent-frontmatter',
|
||||
}),
|
||||
];
|
||||
}
|
||||
|
||||
if (
|
||||
normalizedSourcePath === 'skills'
|
||||
|| normalizedSourcePath.startsWith('skills/')
|
||||
) {
|
||||
const skillRelativePath = normalizedSourcePath === 'skills'
|
||||
? ''
|
||||
: normalizedSourcePath.slice('skills/'.length);
|
||||
return [
|
||||
createManagedScaffoldOperation(
|
||||
module.id,
|
||||
normalizedSourcePath,
|
||||
path.join(targetRoot, 'skills', skillRelativePath),
|
||||
'preserve-relative-path'
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
if (
|
||||
module.id === 'hooks-runtime'
|
||||
&& normalizedSourcePath === 'hooks'
|
||||
) {
|
||||
const profile = getHookProfile(input.env);
|
||||
return [
|
||||
createManagedScaffoldOperation(module.id, 'package.json', path.join(targetRoot, 'package.json'), 'preserve-relative-path'),
|
||||
createManagedOperation({
|
||||
kind: 'merge-json',
|
||||
moduleId: module.id,
|
||||
sourceRelativePath: 'hooks/hooks.json',
|
||||
destinationPath: path.join(targetRoot, 'hooks.json'),
|
||||
strategy: 'merge-json',
|
||||
ownership: 'managed',
|
||||
scaffoldOnly: false,
|
||||
mergePayload: buildAntigravityHooksConfig({
|
||||
profile,
|
||||
bridgeScript: path.join(targetRoot, 'scripts', 'hooks', 'antigravity-hook-bridge.js'),
|
||||
}),
|
||||
}),
|
||||
createManagedOperation({
|
||||
kind: 'merge-json',
|
||||
moduleId: module.id,
|
||||
sourceRelativePath: 'hooks/hooks.json',
|
||||
destinationPath: path.join(targetRoot, 'ecc', 'setup.json'),
|
||||
strategy: 'merge-json',
|
||||
ownership: 'managed',
|
||||
scaffoldOnly: false,
|
||||
mergePayload: { hooks: { enabled: true, profile } },
|
||||
}),
|
||||
];
|
||||
}
|
||||
|
||||
if (
|
||||
module.id === 'platform-configs'
|
||||
&& (normalizedSourcePath === 'mcp-configs' || normalizedSourcePath === '.mcp.json')
|
||||
) {
|
||||
const antigravityMcp = buildAntigravityMcpConfig({
|
||||
memoryScript: path.join(targetRoot, 'scripts', 'memory-mcp.mjs'),
|
||||
});
|
||||
|
||||
const operations = [
|
||||
createManagedOperation({
|
||||
kind: 'merge-json',
|
||||
moduleId: module.id,
|
||||
sourceRelativePath: '.mcp.json',
|
||||
destinationPath: path.join(targetRoot, 'mcp_config.json'),
|
||||
strategy: 'merge-json',
|
||||
ownership: 'managed',
|
||||
scaffoldOnly: false,
|
||||
mergePayload: antigravityMcp,
|
||||
}),
|
||||
createManagedOperation({
|
||||
kind: 'merge-json',
|
||||
moduleId: module.id,
|
||||
sourceRelativePath: 'plugin.json',
|
||||
destinationPath: path.join(targetRoot, 'plugin.json'),
|
||||
strategy: 'merge-json',
|
||||
ownership: 'managed',
|
||||
scaffoldOnly: false,
|
||||
mergePayload: buildAntigravityPluginManifest(),
|
||||
}),
|
||||
];
|
||||
|
||||
if (repoRoot && fs.existsSync(path.join(repoRoot, 'scripts', 'memory-mcp.mjs'))) {
|
||||
operations.push(...planAntigravityMemoryRuntime(module.id, repoRoot, targetRoot));
|
||||
}
|
||||
|
||||
return operations;
|
||||
}
|
||||
|
||||
if (normalizedSourcePath === 'scripts/hooks' || normalizedSourcePath === 'scripts/lib') {
|
||||
return [adapter.createScaffoldOperation(module.id, normalizedSourcePath, planningInput)];
|
||||
}
|
||||
|
||||
return [];
|
||||
});
|
||||
});
|
||||
},
|
||||
});
|
||||
@@ -1,3 +1,4 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const {
|
||||
@@ -7,8 +8,22 @@ const {
|
||||
createManagedScaffoldOperation,
|
||||
normalizeRelativePath,
|
||||
} = require('./helpers');
|
||||
const { buildAntigravityHooksConfig } = require('../antigravity-hooks');
|
||||
const { buildAntigravityMcpConfig, planAntigravityMemoryRuntime } = require('../antigravity-mcp');
|
||||
const { buildAntigravityPluginManifest } = require('../antigravity-plugin');
|
||||
const { getHookProfile } = require('../hook-flags');
|
||||
|
||||
const SUPPORTED_SOURCE_PREFIXES = ['rules', 'commands', 'agents', 'skills'];
|
||||
const SUPPORTED_SOURCE_PREFIXES = [
|
||||
'rules',
|
||||
'commands',
|
||||
'agents',
|
||||
'skills',
|
||||
'hooks',
|
||||
'scripts/hooks',
|
||||
'scripts/lib',
|
||||
'mcp-configs',
|
||||
'.mcp.json',
|
||||
];
|
||||
|
||||
function supportsAntigravitySourcePath(sourceRelativePath) {
|
||||
const normalizedPath = normalizeRelativePath(sourceRelativePath);
|
||||
@@ -39,6 +54,7 @@ module.exports = createInstallTargetAdapter({
|
||||
kind: 'project',
|
||||
rootSegments: ['.agents'],
|
||||
installStatePathSegments: ['ecc-install-state.json'],
|
||||
nativeRootRelativePath: '.agents',
|
||||
supportsModule(module) {
|
||||
const paths = Array.isArray(module && module.paths) ? module.paths : [];
|
||||
return paths.length > 0;
|
||||
@@ -130,6 +146,81 @@ module.exports = createInstallTargetAdapter({
|
||||
];
|
||||
}
|
||||
|
||||
if (
|
||||
module.id === 'hooks-runtime'
|
||||
&& normalizedSourcePath === 'hooks'
|
||||
) {
|
||||
const profile = getHookProfile(input.env);
|
||||
return [
|
||||
createManagedScaffoldOperation(module.id, 'package.json', path.join(targetRoot, 'package.json'), 'preserve-relative-path'),
|
||||
createManagedOperation({
|
||||
kind: 'merge-json',
|
||||
moduleId: module.id,
|
||||
sourceRelativePath: 'hooks/hooks.json',
|
||||
destinationPath: path.join(targetRoot, 'hooks.json'),
|
||||
strategy: 'merge-json',
|
||||
ownership: 'managed',
|
||||
scaffoldOnly: false,
|
||||
mergePayload: buildAntigravityHooksConfig({
|
||||
profile,
|
||||
bridgeScript: path.join(targetRoot, 'scripts', 'hooks', 'antigravity-hook-bridge.js'),
|
||||
}),
|
||||
}),
|
||||
createManagedOperation({
|
||||
kind: 'merge-json',
|
||||
moduleId: module.id,
|
||||
sourceRelativePath: 'hooks/hooks.json',
|
||||
destinationPath: path.join(targetRoot, 'ecc', 'setup.json'),
|
||||
strategy: 'merge-json',
|
||||
ownership: 'managed',
|
||||
scaffoldOnly: false,
|
||||
mergePayload: { hooks: { enabled: true, profile } },
|
||||
}),
|
||||
];
|
||||
}
|
||||
|
||||
if (
|
||||
module.id === 'platform-configs'
|
||||
&& (normalizedSourcePath === 'mcp-configs' || normalizedSourcePath === '.mcp.json')
|
||||
) {
|
||||
const antigravityMcp = buildAntigravityMcpConfig({
|
||||
memoryScript: path.join(targetRoot, 'scripts', 'memory-mcp.mjs'),
|
||||
});
|
||||
|
||||
const operations = [
|
||||
createManagedOperation({
|
||||
kind: 'merge-json',
|
||||
moduleId: module.id,
|
||||
sourceRelativePath: '.mcp.json',
|
||||
destinationPath: path.join(targetRoot, 'mcp_config.json'),
|
||||
strategy: 'merge-json',
|
||||
ownership: 'managed',
|
||||
scaffoldOnly: false,
|
||||
mergePayload: antigravityMcp,
|
||||
}),
|
||||
createManagedOperation({
|
||||
kind: 'merge-json',
|
||||
moduleId: module.id,
|
||||
sourceRelativePath: 'plugin.json',
|
||||
destinationPath: path.join(targetRoot, 'plugins', 'ecc', 'plugin.json'),
|
||||
strategy: 'merge-json',
|
||||
ownership: 'managed',
|
||||
scaffoldOnly: false,
|
||||
mergePayload: buildAntigravityPluginManifest(),
|
||||
}),
|
||||
];
|
||||
|
||||
if (repoRoot && fs.existsSync(path.join(repoRoot, 'scripts', 'memory-mcp.mjs'))) {
|
||||
operations.push(...planAntigravityMemoryRuntime(module.id, repoRoot, targetRoot));
|
||||
}
|
||||
|
||||
return operations;
|
||||
}
|
||||
|
||||
if (normalizedSourcePath === 'scripts/hooks' || normalizedSourcePath === 'scripts/lib') {
|
||||
return [adapter.createScaffoldOperation(module.id, normalizedSourcePath, planningInput)];
|
||||
}
|
||||
|
||||
return [];
|
||||
});
|
||||
});
|
||||
|
||||
@@ -66,6 +66,7 @@ const PLATFORM_SOURCE_PATH_OWNERS = Object.freeze({
|
||||
'.hermes': 'hermes',
|
||||
'.kimi': 'kimi',
|
||||
'.kimi-code': 'kimi',
|
||||
'.vibe': 'mistral-vibe',
|
||||
'.joycode': 'joycode',
|
||||
'.opencode': 'opencode',
|
||||
'.openclaw': 'openclaw',
|
||||
@@ -386,6 +387,13 @@ function createInstallTargetAdapter(config) {
|
||||
}
|
||||
return path.join(baseRoot, ...adapter.rootSegments);
|
||||
},
|
||||
resolveTrustedRoots(input = {}) {
|
||||
const root = adapter.resolveRoot(input);
|
||||
if (typeof config.resolveTrustedRoots === 'function') {
|
||||
return config.resolveTrustedRoots(input, root);
|
||||
}
|
||||
return [root];
|
||||
},
|
||||
getInstallStatePath(input = {}) {
|
||||
const root = adapter.resolveRoot(input);
|
||||
return path.join(root, ...adapter.installStatePathSegments);
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
'use strict';
|
||||
|
||||
const path = require('path');
|
||||
|
||||
const {
|
||||
createInstallTargetAdapter,
|
||||
createManagedScaffoldOperation,
|
||||
} = require('./helpers');
|
||||
|
||||
function parseSkillSourcePath(sourceRelativePath) {
|
||||
if (typeof sourceRelativePath !== 'string' || sourceRelativePath.length === 0) {
|
||||
throw new Error('Unsafe Mistral Vibe skill source path: expected skills/<name>');
|
||||
}
|
||||
if (path.isAbsolute(sourceRelativePath) || path.win32.isAbsolute(sourceRelativePath)) {
|
||||
throw new Error(`Unsafe Mistral Vibe skill source path: ${sourceRelativePath}`);
|
||||
}
|
||||
|
||||
const segments = sourceRelativePath.replace(/\\/g, '/').split('/');
|
||||
if (
|
||||
segments.length < 2
|
||||
|| segments[0] !== 'skills'
|
||||
|| segments.some(segment => !segment || segment === '.' || segment === '..' || segment.includes('\0'))
|
||||
) {
|
||||
throw new Error(`Unsafe Mistral Vibe skill source path: ${sourceRelativePath}`);
|
||||
}
|
||||
|
||||
return segments;
|
||||
}
|
||||
|
||||
module.exports = createInstallTargetAdapter({
|
||||
id: 'mistral-vibe-project',
|
||||
target: 'mistral-vibe',
|
||||
kind: 'project',
|
||||
rootSegments: ['.vibe'],
|
||||
installStatePathSegments: ['ecc-install-state.json'],
|
||||
supportsModule(module) {
|
||||
const paths = Array.isArray(module && module.paths) ? module.paths : [];
|
||||
return module && module.kind === 'skills' && paths.length > 0;
|
||||
},
|
||||
planOperations(input, adapter) {
|
||||
const modules = Array.isArray(input.modules)
|
||||
? input.modules
|
||||
: (input.module ? [input.module] : []);
|
||||
const targetRoot = adapter.resolveRoot(input);
|
||||
|
||||
return modules.flatMap(module => {
|
||||
if (!adapter.supportsModule(module, input)) return [];
|
||||
|
||||
return module.paths.map(sourceRelativePath => {
|
||||
const segments = parseSkillSourcePath(sourceRelativePath);
|
||||
return createManagedScaffoldOperation(
|
||||
module.id,
|
||||
sourceRelativePath,
|
||||
path.join(targetRoot, 'skills', ...segments.slice(1)),
|
||||
'preserve-relative-path'
|
||||
);
|
||||
});
|
||||
});
|
||||
},
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
const adalProject = require('./adal-project');
|
||||
const antigravityHome = require('./antigravity-home');
|
||||
const antigravityProject = require('./antigravity-project');
|
||||
const claudeHome = require('./claude-home');
|
||||
const claudeProject = require('./claude-project');
|
||||
@@ -11,6 +12,7 @@ const grokHome = require('./grok-home');
|
||||
const hermesHome = require('./hermes-home');
|
||||
const joycodeProject = require('./joycode-project');
|
||||
const kimiProject = require('./kimi-project');
|
||||
const mistralVibeProject = require('./mistral-vibe-project');
|
||||
const openclawHome = require('./openclaw-home');
|
||||
const opencodeHome = require('./opencode-home');
|
||||
const qwenHome = require('./qwen-home');
|
||||
@@ -21,6 +23,7 @@ const ADAPTERS = Object.freeze([
|
||||
claudeHome,
|
||||
claudeProject,
|
||||
cursorProject,
|
||||
antigravityHome,
|
||||
antigravityProject,
|
||||
codexHome,
|
||||
copilotProject,
|
||||
@@ -32,6 +35,7 @@ const ADAPTERS = Object.freeze([
|
||||
codebuddyProject,
|
||||
joycodeProject,
|
||||
kimiProject,
|
||||
mistralVibeProject,
|
||||
qwenHome,
|
||||
zedProject,
|
||||
adalProject,
|
||||
@@ -73,6 +77,9 @@ function planInstallTargetScaffold(options = {}) {
|
||||
}
|
||||
const targetRoot = adapter.resolveRoot(planningInput);
|
||||
const installStatePath = adapter.getInstallStatePath(planningInput);
|
||||
const trustedRoots = typeof adapter.resolveTrustedRoots === 'function'
|
||||
? adapter.resolveTrustedRoots(planningInput)
|
||||
: [targetRoot];
|
||||
const operations = adapter.planOperations({
|
||||
...planningInput,
|
||||
modules,
|
||||
@@ -85,6 +92,7 @@ function planInstallTargetScaffold(options = {}) {
|
||||
kind: adapter.kind,
|
||||
},
|
||||
targetRoot,
|
||||
trustedRoots,
|
||||
installStatePath,
|
||||
validationIssues,
|
||||
operations,
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
const crypto = require('crypto');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { isDeepStrictEqual } = require('util');
|
||||
|
||||
const {
|
||||
hasExplicitCommitAttributionPreference,
|
||||
@@ -21,6 +22,7 @@ const {
|
||||
getOpenCodeSourceActivationKind,
|
||||
planMaterializesHookRuntime,
|
||||
shouldDisableOpenCodeHooks,
|
||||
shouldDisableAntigravityHooks,
|
||||
} = require('./hook-consent');
|
||||
const {
|
||||
getClaudeSettingsPath,
|
||||
@@ -33,7 +35,7 @@ const {
|
||||
validateRecordedManagedHooks,
|
||||
} = require('./claude-settings');
|
||||
const { filterMcpConfig, parseDisabledMcpServers } = require('../mcp-config');
|
||||
const { assertWithinTrustedRoot } = require('../path-safety');
|
||||
const { assertWithinTrustedRoot, isWithinRoot } = require('../path-safety');
|
||||
const {
|
||||
assertSafeClaudeSkillOperation,
|
||||
prepareClaudeSkillMigration,
|
||||
@@ -86,10 +88,10 @@ function buildLinkIndexForPlan(plan) {
|
||||
return buildInstallIndex(mappings);
|
||||
}
|
||||
|
||||
function readJsonObject(filePath, label) {
|
||||
function readJsonObject(filePath, label, readContent = () => fs.readFileSync(filePath, 'utf8')) {
|
||||
let parsed;
|
||||
try {
|
||||
parsed = JSON.parse(fs.readFileSync(filePath, 'utf8'));
|
||||
parsed = JSON.parse(readContent());
|
||||
} catch (error) {
|
||||
const wrappedError = new Error(`Failed to parse ${label} at ${filePath}: ${error.message}`);
|
||||
wrappedError.code = error.code;
|
||||
@@ -257,7 +259,15 @@ function writeClaudeCommitAttributionPreference(settingsPath, options = {}) {
|
||||
|
||||
function isMcpConfigPath(filePath) {
|
||||
const basename = path.basename(String(filePath || ''));
|
||||
return basename === '.mcp.json' || basename === 'mcp.json';
|
||||
return basename === '.mcp.json' || basename === 'mcp.json' || basename === 'mcp_config.json';
|
||||
}
|
||||
|
||||
function getTrustedRootsForPlan(plan) {
|
||||
if (!plan) return [];
|
||||
if (Array.isArray(plan.trustedRoots) && plan.trustedRoots.length > 0) {
|
||||
return plan.trustedRoots;
|
||||
}
|
||||
return plan.targetRoot ? [plan.targetRoot] : [];
|
||||
}
|
||||
|
||||
function withMcpMergeExclusions(plan, disabledServers) {
|
||||
@@ -291,7 +301,9 @@ function assertSafeInstallOperation(plan, operation) {
|
||||
throw new Error('Refusing to apply install operation: missing destination path.');
|
||||
}
|
||||
|
||||
const targetRoot = plan && plan.targetRoot;
|
||||
const trustedRoots = getTrustedRootsForPlan(plan);
|
||||
const matchingRoot = trustedRoots.find(root => isWithinRoot(operation.destinationPath, root));
|
||||
const targetRoot = matchingRoot || (plan && plan.targetRoot);
|
||||
assertWithinTrustedRoot(operation.destinationPath, targetRoot, 'install ECC file');
|
||||
|
||||
const resolvedRoot = path.resolve(targetRoot);
|
||||
@@ -703,6 +715,68 @@ function preflightClaudeSettingsOperations(plan) {
|
||||
}));
|
||||
}
|
||||
|
||||
function withoutManagedAntigravityHooks(plan, operation) {
|
||||
const content = readInstalledFileNoFollow(plan, operation);
|
||||
const config = content === null ? {} : JSON.parse(content.toString('utf8'));
|
||||
if (!config || typeof config !== 'object' || Array.isArray(config)) {
|
||||
throw new Error(`Invalid Antigravity hooks config: ${operation.destinationPath}`);
|
||||
}
|
||||
if (Object.hasOwn(config, 'ecc-guard')
|
||||
&& !isDeepStrictEqual(config['ecc-guard'], operation.mergePayload?.['ecc-guard'])) {
|
||||
throw new Error(`Refusing to disable modified Antigravity hooks in ${operation.destinationPath}.`);
|
||||
}
|
||||
const userHooks = Object.fromEntries(Object.entries(config).filter(([name]) => name !== 'ecc-guard'));
|
||||
return {
|
||||
content: formatJson(userHooks),
|
||||
expectedContent: content === null ? { kind: 'absent' } : {
|
||||
kind: 'sha256', digest: crypto.createHash('sha256').update(content).digest('hex'),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function prepareAntigravityHookDeactivation(plan, migration, previousState) {
|
||||
if (!shouldDisableAntigravityHooks(plan)) return migration;
|
||||
const hooksPath = path.join(plan.targetRoot, 'hooks.json');
|
||||
const previousHooks = previousState.operations.find(operation => (
|
||||
operation.ownership === 'managed' && operation.kind === 'merge-json'
|
||||
&& operation.moduleId === 'hooks-runtime'
|
||||
&& comparablePath(operation.destinationPath) === comparablePath(hooksPath)
|
||||
));
|
||||
if (!previousHooks) return migration;
|
||||
const removal = { ...previousHooks, kind: 'remove-antigravity-hooks' };
|
||||
// Check before ordinary writes, then re-read at the guarded write boundary.
|
||||
withoutManagedAntigravityHooks(plan, removal);
|
||||
const disabledSetup = {
|
||||
...previousHooks,
|
||||
kind: 'merge-json',
|
||||
destinationPath: path.join(plan.targetRoot, 'ecc', 'setup.json'),
|
||||
mergePayload: { hooks: { enabled: false } },
|
||||
};
|
||||
assertSafeInstallOperation(plan, disabledSetup);
|
||||
readOptionalJsonObject(disabledSetup.destinationPath, 'managed hook setup');
|
||||
const changed = new Set([hooksPath, disabledSetup.destinationPath].map(comparablePath));
|
||||
return {
|
||||
...migration,
|
||||
appliedOperations: [
|
||||
...migration.appliedOperations, removal,
|
||||
{ ...disabledSetup, kind: 'disable-antigravity-hook-setup' },
|
||||
],
|
||||
warnings: [...migration.warnings, 'Disabling previously installed Antigravity hooks; preserving user hook namespaces.'],
|
||||
finalState: {
|
||||
...migration.finalState,
|
||||
operations: [
|
||||
...migration.finalState.operations.filter(operation => !changed.has(comparablePath(operation.destinationPath))),
|
||||
{ ...previousHooks, mergePayload: {} }, disabledSetup,
|
||||
],
|
||||
},
|
||||
bridgeState: {
|
||||
...migration.bridgeState,
|
||||
request: { ...migration.bridgeState.request, hookConsent: getRecordedHookConsent(previousState) },
|
||||
},
|
||||
requiresBridgeState: true,
|
||||
};
|
||||
}
|
||||
|
||||
function prepareHookConsentMigration(plan, migration) {
|
||||
if (shouldDisableOpenCodeHooks(plan) && migration.requiresBridgeState) {
|
||||
const previousState = readPreviousInstallState(plan);
|
||||
@@ -732,6 +806,9 @@ function prepareHookConsentMigration(plan, migration) {
|
||||
if (!previousState) {
|
||||
return migration;
|
||||
}
|
||||
if (shouldDisableAntigravityHooks(plan)) {
|
||||
return prepareAntigravityHookDeactivation(plan, migration, previousState);
|
||||
}
|
||||
|
||||
const removals = (previousState.operations || [])
|
||||
.filter(operation => operation.kind === 'update-claude-settings')
|
||||
@@ -926,6 +1003,32 @@ function applyInstallPlanLocked(rawPlan, dependencies = {}, settingsLockHeld = f
|
||||
}
|
||||
assertOpenCodeActivationUnchanged(appliedPlan, operation, activationSnapshot);
|
||||
|
||||
if (['remove-antigravity-hooks', 'disable-antigravity-hook-setup'].includes(operation.kind)) {
|
||||
const current = operation.kind === 'disable-antigravity-hook-setup'
|
||||
? readInstalledFileNoFollow(appliedPlan, operation) : null;
|
||||
const disabled = operation.kind === 'remove-antigravity-hooks'
|
||||
? withoutManagedAntigravityHooks(appliedPlan, operation)
|
||||
: {
|
||||
content: formatJson(deepMergeJson(
|
||||
readJsonObject(operation.destinationPath, 'managed hook setup', () => current || '{}'),
|
||||
operation.mergePayload
|
||||
)),
|
||||
expectedContent: current === null ? { kind: 'absent' } : {
|
||||
kind: 'sha256', digest: crypto.createHash('sha256').update(current).digest('hex'),
|
||||
},
|
||||
};
|
||||
writeFileNoFollow(operation.destinationPath, disabled.content, {
|
||||
action: 'disable Antigravity hooks',
|
||||
expectedContent: disabled.expectedContent,
|
||||
validateDestination(destinationPath) {
|
||||
assertSafeInstallOperation(appliedPlan, { destinationPath });
|
||||
return destinationPath;
|
||||
},
|
||||
});
|
||||
writtenDestinations.add(operation.destinationPath);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (
|
||||
operation.kind === 'update-claude-settings'
|
||||
|| operation.kind === 'remove-claude-settings-hooks'
|
||||
|
||||
@@ -7,7 +7,7 @@ const { assertWithinTrustedRoot } = require('../path-safety');
|
||||
const { sameFileIdentity } = require('./claude-settings-lock');
|
||||
|
||||
function isCodexUserConfig(plan, operation) {
|
||||
if (!plan.adapter || plan.adapter.id !== 'codex-home' || operation.kind !== 'copy-file') {
|
||||
if (plan?.adapter?.id !== 'codex-home' || operation?.kind !== 'copy-file') {
|
||||
return false;
|
||||
}
|
||||
const relativePath = path.relative(plan.targetRoot, operation.destinationPath);
|
||||
|
||||
@@ -274,6 +274,7 @@ function isHookRuntimeOperation(operation = {}) {
|
||||
|| source.startsWith('.cursor/hooks/')
|
||||
|| source === '.cursor/hooks.json'
|
||||
|| destination.endsWith('/hooks/hooks.json')
|
||||
|| destination.endsWith('/hooks.json')
|
||||
|| destination.endsWith('/.cursor/hooks.json')
|
||||
|| destination.includes('/.cursor/hooks/')
|
||||
);
|
||||
@@ -366,6 +367,11 @@ function shouldDisableOpenCodeHooks(plan = {}) {
|
||||
&& (plan.hookConsent === 'declined' || !planSelectsHookRuntime(plan));
|
||||
}
|
||||
|
||||
function shouldDisableAntigravityHooks(plan = {}) {
|
||||
return ['antigravity', 'antigravity-home'].includes(plan.target)
|
||||
&& plan.hookConsent === 'declined';
|
||||
}
|
||||
|
||||
function setStatePreviewHookConsent(statePreview, hookConsent) {
|
||||
if (!statePreview || !statePreview.request) {
|
||||
return statePreview;
|
||||
@@ -500,5 +506,6 @@ module.exports = {
|
||||
planMaterializesHookRuntime,
|
||||
resolveHookConsentFlags,
|
||||
shouldDisableOpenCodeHooks,
|
||||
shouldDisableAntigravityHooks,
|
||||
withHookConsent,
|
||||
};
|
||||
@@ -0,0 +1,64 @@
|
||||
'use strict';
|
||||
|
||||
const path = require('path');
|
||||
const { assertWithinTrustedRoot } = require('../path-safety');
|
||||
|
||||
// npm may hoist a dependency beside the ECC package instead of nesting it, so
|
||||
// a path relative to the repository would need `..`. Dependency sources are
|
||||
// recorded as `node_modules/<name>[/node_modules/<name>...]/<file>` instead,
|
||||
// mirroring the installed layout, and Node resolves each package from the
|
||||
// repository when the source is read.
|
||||
const PACKAGE_DIR = 'node_modules';
|
||||
const PACKAGE_NAME = /^(?:@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*$/;
|
||||
|
||||
function isPackageSourcePath(sourceRelativePath) {
|
||||
return typeof sourceRelativePath === 'string'
|
||||
&& sourceRelativePath.split(/[/\\]+/)[0] === PACKAGE_DIR;
|
||||
}
|
||||
|
||||
function formatPackageSourcePath(packageChain, relativeFile = '') {
|
||||
const segments = packageChain.flatMap(name => [PACKAGE_DIR, ...name.split('/')]);
|
||||
return path.posix.join(...segments, ...relativeFile.split(/[/\\]+/).filter(Boolean));
|
||||
}
|
||||
|
||||
function parsePackageSourcePath(sourceRelativePath) {
|
||||
const parts = String(sourceRelativePath).split(/[/\\]+/);
|
||||
const packageChain = [];
|
||||
let index = 0;
|
||||
while (parts[index] === PACKAGE_DIR) {
|
||||
const scoped = String(parts[index + 1] || '').startsWith('@');
|
||||
const name = scoped ? `${parts[index + 1]}/${parts[index + 2] || ''}` : parts[index + 1];
|
||||
if (!PACKAGE_NAME.test(String(name || ''))) {
|
||||
throw new Error(`Invalid package source path: ${sourceRelativePath}`);
|
||||
}
|
||||
packageChain.push(name);
|
||||
index += scoped ? 3 : 2;
|
||||
}
|
||||
const relativeFile = parts.slice(index);
|
||||
if (packageChain.length === 0 || relativeFile.some(part => part === '' || part === '.' || part === '..')) {
|
||||
throw new Error(`Invalid package source path: ${sourceRelativePath}`);
|
||||
}
|
||||
return { packageChain, relativeFile };
|
||||
}
|
||||
|
||||
// Returns null when a package in the chain cannot be resolved. Throws when the
|
||||
// path itself is malformed.
|
||||
function resolvePackageSourcePath(repoRoot, sourceRelativePath) {
|
||||
const { packageChain, relativeFile } = parsePackageSourcePath(sourceRelativePath);
|
||||
let packageRoot = repoRoot;
|
||||
for (const name of packageChain) {
|
||||
try {
|
||||
packageRoot = path.dirname(require.resolve(`${name}/package.json`, { paths: [packageRoot] }));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return assertWithinTrustedRoot(path.join(packageRoot, ...relativeFile), packageRoot, 'read package source');
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
formatPackageSourcePath,
|
||||
isPackageSourcePath,
|
||||
parsePackageSourcePath,
|
||||
resolvePackageSourcePath,
|
||||
};
|
||||
@@ -9,6 +9,7 @@ const { getInstallTargetAdapter } = require('../install-targets/registry');
|
||||
const { resolveInvocationEnvironment } = require('../invocation-environment');
|
||||
const { disableUnselectedOpenCodeHooks } = require('./hook-consent');
|
||||
const { readHooksConfig } = require('../hooks-config');
|
||||
const { isPackageSourcePath, resolvePackageSourcePath } = require('./package-source');
|
||||
const {
|
||||
materializeManagedHooks,
|
||||
} = require('./claude-settings');
|
||||
@@ -176,14 +177,18 @@ function materializeScaffoldOperation(sourceRoot, operation) {
|
||||
destinationPath: operation.destinationPath,
|
||||
strategy: operation.strategy || 'merge-json',
|
||||
ownership: operation.ownership || 'managed',
|
||||
scaffoldOnly: Object.hasOwn(operation, 'scaffoldOnly') ? operation.scaffoldOnly : false,
|
||||
mergePayload: readJsonObject(path.join(sourceRoot, operation.sourceRelativePath), operation.sourceRelativePath)
|
||||
scaffoldOnly: typeof operation.scaffoldOnly === 'boolean' ? operation.scaffoldOnly : false,
|
||||
mergePayload: operation.mergePayload !== undefined
|
||||
? JSON.parse(JSON.stringify(operation.mergePayload))
|
||||
: readJsonObject(path.join(sourceRoot, operation.sourceRelativePath), operation.sourceRelativePath)
|
||||
}
|
||||
];
|
||||
}
|
||||
|
||||
const sourcePath = path.join(sourceRoot, operation.sourceRelativePath);
|
||||
if (!fs.existsSync(sourcePath)) {
|
||||
const sourcePath = isPackageSourcePath(operation.sourceRelativePath)
|
||||
? resolvePackageSourcePath(sourceRoot, operation.sourceRelativePath)
|
||||
: path.join(sourceRoot, operation.sourceRelativePath);
|
||||
if (!sourcePath || !fs.existsSync(sourcePath)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
@@ -363,6 +368,7 @@ function createManifestInstallPlan(options = {}) {
|
||||
},
|
||||
homeDir: plan.homeDir,
|
||||
targetRoot: plan.targetRoot,
|
||||
trustedRoots: plan.trustedRoots || (plan.targetRoot ? [plan.targetRoot] : []),
|
||||
installRoot: plan.targetRoot,
|
||||
installStatePath: plan.installStatePath,
|
||||
warnings: Array.isArray(options.warnings) ? [...options.warnings] : [],
|
||||
|
||||
@@ -21,7 +21,7 @@ const LLM_TIMEOUT_MS = 90000;
|
||||
// Leave the Stop hook time to persist its mechanical fallback after a timeout.
|
||||
const HOOK_FINISH_RESERVE_MS = 1000;
|
||||
// Harness notice shown after a safety-classifier stop; it is not a user ask (#3867).
|
||||
const CLASSIFIER_NOTICE = /^Your response above was stopped by a safety classifier\s*[—–-]\s*this is not a tool or API error\.?$/i;
|
||||
const CLASSIFIER_NOTICE = /^Your response above was stopped by a safety classifier\s*[—–-]\s*this is not a tool or API error\.?(?:\s+The rest of it was withheld, and tool calls in it that had not finished did not run\.\s+Do not produce that content again, even reworded\.)?$/i;
|
||||
|
||||
function getLLMModel() {
|
||||
return process.env.ECC_LLM_SUMMARY_MODEL || 'haiku';
|
||||
@@ -35,10 +35,11 @@ function getContextThreshold() {
|
||||
/**
|
||||
* True when a user-turn text is the harness notice left after a
|
||||
* safety-classifier stop. Anchored to the whole message so user text that
|
||||
* quotes or follows the notice is kept.
|
||||
* quotes or follows the notice is kept. Whitespace runs (including
|
||||
* newlines) are collapsed first so every caller matches the same text.
|
||||
*/
|
||||
function isClassifierNotice(text) {
|
||||
return CLASSIFIER_NOTICE.test(text);
|
||||
return CLASSIFIER_NOTICE.test(String(text).replace(/\s+/g, ' ').trim());
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -6,7 +6,7 @@ const os = require('os');
|
||||
const path = require('path');
|
||||
|
||||
const { assertSafeInstallOperation } = require('./install/apply');
|
||||
const { assertWithinTrustedRoot, realpathNearestExisting } = require('./path-safety');
|
||||
const { assertWithinTrustedRoot, isWithinRoot, realpathNearestExisting } = require('./path-safety');
|
||||
|
||||
const VALID_CLAUDE_SCOPES = new Set(['user', 'project', 'local']);
|
||||
const VALID_CLAUDE_HOOKS = new Set(['off', 'minimal', 'standard', 'strict']);
|
||||
@@ -208,7 +208,11 @@ function readOwnedDestinations(plan, dependencies) {
|
||||
);
|
||||
}
|
||||
const destinationPath = operation.destinationPath;
|
||||
assertWithinTrustedRoot(destinationPath, plan.targetRoot, 'trust install-state ownership');
|
||||
const trustedRoots = Array.isArray(plan.trustedRoots) && plan.trustedRoots.length > 0
|
||||
? plan.trustedRoots
|
||||
: [plan.targetRoot];
|
||||
const matchingRoot = trustedRoots.find(root => isWithinRoot(destinationPath, root)) || plan.targetRoot;
|
||||
assertWithinTrustedRoot(destinationPath, matchingRoot, 'trust install-state ownership');
|
||||
const canonicalDestination = canonicalPath(destinationPath);
|
||||
const plannedOperation = plannedByDestination.get(canonicalDestination);
|
||||
if (!plannedOperation) continue;
|
||||
|
||||
@@ -73,7 +73,7 @@ const DEFAULT_SKILL_PROBE = path.join('skills', 'continuous-learning-v2');
|
||||
function resolveEccRoot(options = {}) {
|
||||
const envRoot = options.envRoot !== undefined
|
||||
? options.envRoot
|
||||
: (process.env.CLAUDE_PLUGIN_ROOT || '');
|
||||
: (process.env.CLAUDE_PLUGIN_ROOT || process.env.ANTIGRAVITY_PLUGIN_ROOT || process.env.GEMINI_PLUGIN_ROOT || '');
|
||||
|
||||
if (envRoot && envRoot.trim()) {
|
||||
return envRoot.trim();
|
||||
@@ -110,6 +110,12 @@ function resolveEccRoot(options = {}) {
|
||||
return claudeDir;
|
||||
}
|
||||
|
||||
// Antigravity global plugin install — ~/.gemini/config/plugins/ecc
|
||||
const antigravityPluginDir = path.join(homeDir, '.gemini', 'config', 'plugins', 'ecc');
|
||||
if (isRoot(antigravityPluginDir)) {
|
||||
return antigravityPluginDir;
|
||||
}
|
||||
|
||||
// Exact legacy plugin install locations. These preserve backwards
|
||||
// compatibility without scanning arbitrary plugin trees.
|
||||
const legacyPluginRoots = PLUGIN_ROOT_SEGMENTS.map((segments) =>
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
const fs = require('fs');
|
||||
const os = require('os');
|
||||
const path = require('path');
|
||||
const { readFileWithSharingRetry, writeFileAtomic } = require('../atomic-write');
|
||||
|
||||
const SESSION_SCHEMA_VERSION = 'ecc.session.v1';
|
||||
const SESSION_RECORDING_SCHEMA_VERSION = 'ecc.session.recording.v1';
|
||||
@@ -290,7 +291,7 @@ function readExistingRecording(filePath) {
|
||||
}
|
||||
|
||||
try {
|
||||
return JSON.parse(fs.readFileSync(filePath, 'utf8'));
|
||||
return JSON.parse(readFileWithSharingRetry(filePath, 'utf8'));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
@@ -319,8 +320,10 @@ function writeFallbackSessionRecording(snapshot, options = {}) {
|
||||
: [{ recordedAt, snapshot }]
|
||||
};
|
||||
|
||||
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
||||
fs.writeFileSync(filePath, JSON.stringify(payload, null, 2) + '\n', 'utf8');
|
||||
writeFileAtomic(filePath, JSON.stringify(payload, null, 2) + '\n', {
|
||||
mode: 0o666,
|
||||
preserveExistingMode: true
|
||||
});
|
||||
|
||||
return {
|
||||
backend: 'json-file',
|
||||
|
||||
@@ -228,7 +228,8 @@ function deriveLastActivityMs(records, fallbackPath) {
|
||||
}
|
||||
|
||||
function deriveModel(meta, records) {
|
||||
for (const record of records) {
|
||||
for (let index = records.length - 1; index >= 0; index -= 1) {
|
||||
const record = records[index];
|
||||
if (record && record.type === 'turn_context' && record.payload) {
|
||||
if (typeof record.payload.model === 'string' && record.payload.model.length > 0) {
|
||||
return record.payload.model;
|
||||
|
||||
@@ -20,6 +20,20 @@ function getAliasesPath() {
|
||||
// Current alias storage format version
|
||||
const ALIAS_VERSION = '1.0';
|
||||
|
||||
function getAliasRecord(aliases, name) {
|
||||
return Object.hasOwn(aliases, name) ? aliases[name] : undefined;
|
||||
}
|
||||
|
||||
function setAliasRecord(aliases, name, record) {
|
||||
// Valid names such as __proto__ must become JSON entries, not invoke setters.
|
||||
Object.defineProperty(aliases, name, {
|
||||
value: record,
|
||||
enumerable: true,
|
||||
writable: true,
|
||||
configurable: true
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Default aliases file structure
|
||||
*/
|
||||
@@ -183,7 +197,7 @@ function resolveAlias(alias) {
|
||||
}
|
||||
|
||||
const data = loadAliases();
|
||||
const aliasData = data.aliases[alias];
|
||||
const aliasData = getAliasRecord(data.aliases, alias);
|
||||
|
||||
if (!aliasData) {
|
||||
return null;
|
||||
@@ -234,15 +248,16 @@ function setAliasUnlocked(alias, sessionPath, title = null) {
|
||||
}
|
||||
|
||||
const data = loadAliases();
|
||||
const existing = data.aliases[alias];
|
||||
const existing = getAliasRecord(data.aliases, alias);
|
||||
const isNew = !existing;
|
||||
|
||||
data.aliases[alias] = {
|
||||
const record = {
|
||||
sessionPath,
|
||||
createdAt: existing ? existing.createdAt : new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
title: title || null
|
||||
};
|
||||
setAliasRecord(data.aliases, alias, record);
|
||||
|
||||
if (saveAliasesUnlocked(data)) {
|
||||
return {
|
||||
@@ -250,7 +265,7 @@ function setAliasUnlocked(alias, sessionPath, title = null) {
|
||||
isNew,
|
||||
alias,
|
||||
sessionPath,
|
||||
title: data.aliases[alias].title
|
||||
title: record.title
|
||||
};
|
||||
}
|
||||
|
||||
@@ -303,12 +318,12 @@ function listAliases(options = {}) {
|
||||
*/
|
||||
function deleteAliasUnlocked(alias) {
|
||||
const data = loadAliases();
|
||||
const deleted = getAliasRecord(data.aliases, alias);
|
||||
|
||||
if (!data.aliases[alias]) {
|
||||
if (!deleted) {
|
||||
return { success: false, error: `Alias '${alias}' not found` };
|
||||
}
|
||||
|
||||
const deleted = data.aliases[alias];
|
||||
delete data.aliases[alias];
|
||||
|
||||
if (saveAliasesUnlocked(data)) {
|
||||
@@ -330,8 +345,9 @@ function deleteAliasUnlocked(alias) {
|
||||
*/
|
||||
function renameAliasUnlocked(oldAlias, newAlias) {
|
||||
const data = loadAliases();
|
||||
const aliasData = getAliasRecord(data.aliases, oldAlias);
|
||||
|
||||
if (!data.aliases[oldAlias]) {
|
||||
if (!aliasData) {
|
||||
return { success: false, error: `Alias '${oldAlias}' not found` };
|
||||
}
|
||||
|
||||
@@ -353,15 +369,14 @@ function renameAliasUnlocked(oldAlias, newAlias) {
|
||||
return { success: false, error: `'${newAlias}' is a reserved alias name` };
|
||||
}
|
||||
|
||||
if (data.aliases[newAlias]) {
|
||||
if (getAliasRecord(data.aliases, newAlias)) {
|
||||
return { success: false, error: `Alias '${newAlias}' already exists` };
|
||||
}
|
||||
|
||||
const aliasData = data.aliases[oldAlias];
|
||||
delete data.aliases[oldAlias];
|
||||
|
||||
aliasData.updatedAt = new Date().toISOString();
|
||||
data.aliases[newAlias] = aliasData;
|
||||
setAliasRecord(data.aliases, newAlias, aliasData);
|
||||
|
||||
if (saveAliasesUnlocked(data)) {
|
||||
return {
|
||||
@@ -405,12 +420,13 @@ function updateAliasTitleUnlocked(alias, title) {
|
||||
|
||||
const data = loadAliases();
|
||||
|
||||
if (!data.aliases[alias]) {
|
||||
const aliasData = getAliasRecord(data.aliases, alias);
|
||||
if (!aliasData) {
|
||||
return { success: false, error: `Alias '${alias}' not found` };
|
||||
}
|
||||
|
||||
data.aliases[alias].title = title || null;
|
||||
data.aliases[alias].updatedAt = new Date().toISOString();
|
||||
aliasData.title = title || null;
|
||||
aliasData.updatedAt = new Date().toISOString();
|
||||
|
||||
if (saveAliasesUnlocked(data)) {
|
||||
return {
|
||||
|
||||
@@ -60,23 +60,23 @@ function createGitRunner(repoRoot, runImpl = defaultRunImpl) {
|
||||
return succeeds(['show-ref', '--verify', '--quiet', `refs/heads/${branch}`]);
|
||||
},
|
||||
|
||||
// Porcelain worktree list -> [{ path, branch, head, detached, bare }]
|
||||
// Git 2.36+ NUL-delimited porcelain preserves whitespace within paths.
|
||||
listWorktrees() {
|
||||
const result = run(['worktree', 'list', '--porcelain']);
|
||||
const result = run(['worktree', 'list', '--porcelain', '-z']);
|
||||
if (result.status !== 0) {
|
||||
return [];
|
||||
const reason = (result.stderr || '').trim() || `git exited with status ${result.status}`;
|
||||
throw new Error(`Unable to list worktrees safely (Git 2.36+ required): ${reason}`);
|
||||
}
|
||||
|
||||
const worktrees = [];
|
||||
let current = null;
|
||||
|
||||
for (const rawLine of (result.stdout || '').split('\n')) {
|
||||
const line = rawLine.trim();
|
||||
for (const line of (result.stdout || '').split('\0')) {
|
||||
if (line.startsWith('worktree ')) {
|
||||
if (current) {
|
||||
worktrees.push(current);
|
||||
}
|
||||
current = { path: line.slice('worktree '.length).trim(), branch: null, head: null, detached: false, bare: false };
|
||||
current = { path: line.slice('worktree '.length), branch: null, head: null, detached: false, bare: false };
|
||||
} else if (current && line.startsWith('branch ')) {
|
||||
current.branch = line.slice('branch '.length).replace(/^refs\/heads\//, '').trim();
|
||||
} else if (current && line.startsWith('HEAD ')) {
|
||||
|
||||
@@ -55,6 +55,8 @@ function usage() {
|
||||
'conflicts without touching the working tree (git merge-tree) and proposes',
|
||||
'a safe cleanup plan that never removes dirty or unmerged worktrees.',
|
||||
'',
|
||||
'Requires Git 2.36+ for NUL-delimited worktree paths.',
|
||||
'',
|
||||
'Options:',
|
||||
' --json Print the full ecc.worktree-lifecycle.v1 report as JSON',
|
||||
' --conflicts Only show worktrees that would conflict on merge',
|
||||
|
||||
@@ -98,7 +98,7 @@ credentials/tokens/PII before saving any screenshot.
|
||||
## Integration
|
||||
|
||||
Works with any browser MCP:
|
||||
- `mChild__claude-in-chrome__*` tools (preferred — uses your actual Chrome)
|
||||
- `mcp__claude-in-chrome__*` tools (preferred — uses your actual Chrome)
|
||||
- Playwright via `mcp__browserbase__*`
|
||||
- Direct Puppeteer scripts
|
||||
|
||||
|
||||
@@ -70,7 +70,6 @@ CELERY_TASK_TRACK_STARTED = True
|
||||
CELERY_TASK_TIME_LIMIT = 30 * 60 # Hard limit: 30 min
|
||||
CELERY_TASK_SOFT_TIME_LIMIT = 25 * 60 # Soft limit: sends SoftTimeLimitExceeded
|
||||
CELERY_WORKER_PREFETCH_MULTIPLIER = 1 # Prevent worker hoarding long tasks
|
||||
CELERY_TASK_ACKS_LATE = True # Re-queue on worker crash
|
||||
|
||||
# Result persistence
|
||||
CELERY_RESULT_EXPIRES = 60 * 60 * 24 # Keep results 24 hours
|
||||
@@ -199,6 +198,12 @@ def generate_pdf_report(self, report_id: int) -> str:
|
||||
raise
|
||||
```
|
||||
|
||||
### Delivery Guarantees
|
||||
|
||||
Late acknowledgement, worker-loss redelivery, and commit-aware publication are separate
|
||||
choices. Read [Delivery Reliability](references/reliability.md) before
|
||||
changing acknowledgement settings or publishing tasks from a database transaction.
|
||||
|
||||
## Calling Tasks
|
||||
|
||||
```python
|
||||
@@ -219,6 +224,25 @@ sync_contact_to_crm.apply_async(args=[contact.pk], queue='high_priority')
|
||||
result = generate_pdf_report.apply(args=[report.pk])
|
||||
```
|
||||
|
||||
### Publish After the Database Commits
|
||||
|
||||
A task published inside a Django transaction can run before its rows are visible or
|
||||
remain queued after rollback. Use `delay_on_commit()` or `apply_async_on_commit()`
|
||||
with Celery 5.4 or newer; use `transaction.on_commit()` on older versions. See
|
||||
[Delivery Reliability](references/reliability.md#publish-after-the-database-commits)
|
||||
for custom-base, task-ID, and transactional-outbox boundaries. Django's `TestCase`
|
||||
never commits, so these callbacks never run in tests unless captured; see
|
||||
[Test the On-Commit Contract](references/reliability.md#test-the-on-commit-contract).
|
||||
|
||||
```python
|
||||
from django.db import transaction
|
||||
|
||||
@transaction.atomic
|
||||
def create_user(validated_username: str):
|
||||
user = User.objects.create(username=validated_username)
|
||||
send_welcome_email.delay_on_commit(user.pk)
|
||||
```
|
||||
|
||||
## Beat Scheduling (Periodic Tasks)
|
||||
|
||||
### Code-Defined Schedule
|
||||
@@ -266,6 +290,11 @@ PeriodicTask.objects.update_or_create(
|
||||
)
|
||||
```
|
||||
|
||||
Run only one scheduler for a given schedule to avoid duplicate publications, but this
|
||||
does not prevent execution overlap: periodic tasks may overlap. Atomically claim an
|
||||
active-run lease with an owner and expiry or recovery path; a unique schedule row
|
||||
alone does not serialize executions. Keep the task idempotent if the lease expires.
|
||||
|
||||
## Canvas: Chaining and Grouping Tasks
|
||||
|
||||
```python
|
||||
@@ -294,7 +323,7 @@ result = chord(
|
||||
result.delay()
|
||||
```
|
||||
|
||||
## Error Handling and Dead Letter Queue
|
||||
## Failure Monitoring
|
||||
|
||||
```python
|
||||
# apps/core/tasks.py
|
||||
@@ -314,29 +343,8 @@ def on_task_failure(sender, task_id, exception, args, kwargs, traceback, einfo,
|
||||
sentry_sdk.capture_exception(exception)
|
||||
```
|
||||
|
||||
```python
|
||||
# Route failed tasks to dead-letter queue after max retries
|
||||
@shared_task(
|
||||
bind=True,
|
||||
max_retries=3,
|
||||
name='payments.charge_card',
|
||||
)
|
||||
def charge_card(self, order_id: int) -> None:
|
||||
from apps.payments.models import Order, FailedCharge
|
||||
|
||||
try:
|
||||
_do_charge(order_id)
|
||||
except Exception as exc:
|
||||
if self.request.retries >= self.max_retries:
|
||||
# Persist to dead-letter table for manual review
|
||||
FailedCharge.objects.create(
|
||||
order_id=order_id,
|
||||
error=str(exc),
|
||||
task_id=self.request.id,
|
||||
)
|
||||
return # Don't raise — task is permanently failed
|
||||
raise self.retry(exc=exc)
|
||||
```
|
||||
Returning after recording a final error makes Celery record `SUCCESS`; persist and
|
||||
re-raise instead. Broker dead-letter queues are not Django model error logs.
|
||||
|
||||
## Testing Celery Tasks
|
||||
|
||||
@@ -362,7 +370,14 @@ class TestSendWelcomeEmail:
|
||||
send_welcome_email(99999) # Non-existent user — must not raise
|
||||
```
|
||||
|
||||
### Integration Testing with CELERY_TASK_ALWAYS_EAGER
|
||||
### Django Integration Path with Eager Mode
|
||||
|
||||
Eager mode is a worker emulation, not a worker integration test. Use it to verify
|
||||
that a Django request selects the expected task and arguments, but do not use it as
|
||||
evidence for serialization, routing, acknowledgement, retry, or worker-loss behavior.
|
||||
It also does not prove post-commit dispatch: under `django_db` the test transaction
|
||||
never commits, so a view that publishes with `delay_on_commit()` runs nothing unless
|
||||
the request is wrapped in `django_capture_on_commit_callbacks(execute=True)`.
|
||||
|
||||
```python
|
||||
# config/settings/test.py
|
||||
@@ -371,17 +386,26 @@ CELERY_TASK_EAGER_PROPAGATES = True # Re-raise exceptions from tasks
|
||||
|
||||
# tests/test_integration.py
|
||||
@pytest.mark.django_db
|
||||
def test_registration_triggers_welcome_email(client):
|
||||
def test_registration_triggers_welcome_email(client, django_capture_on_commit_callbacks):
|
||||
with patch('apps.notifications.services.EmailService') as mock_email:
|
||||
response = client.post('/api/users/', {
|
||||
'email': 'new@example.com',
|
||||
'password': 'strongpass123',
|
||||
})
|
||||
with django_capture_on_commit_callbacks(execute=True):
|
||||
response = client.post('/api/users/', {
|
||||
'email': 'new@example.com',
|
||||
'password': 'strongpass123',
|
||||
})
|
||||
|
||||
assert response.status_code == 201
|
||||
mock_email.send_welcome.assert_called_once()
|
||||
```
|
||||
|
||||
### Worker Integration with a Real Broker
|
||||
|
||||
Use Celery's `celery_worker` pytest fixture with a real broker and result backend for
|
||||
the delivery boundary. Cover serialization, routing, retry behavior, and any
|
||||
acknowledgement or redelivery options the application enables. Keep this suite
|
||||
separate from fast unit tests so a passing eager-mode test is never mistaken for
|
||||
worker evidence.
|
||||
|
||||
### Testing Retries
|
||||
|
||||
```python
|
||||
@@ -428,14 +452,27 @@ def charge_and_fulfill(order_id):
|
||||
order.charge() # May charge twice if task retries!
|
||||
order.fulfill()
|
||||
|
||||
# GOOD: Idempotent with status guard
|
||||
@shared_task
|
||||
def charge_and_fulfill(order_id):
|
||||
order = Order.objects.select_for_update().get(pk=order_id)
|
||||
if order.status != Order.Status.PENDING:
|
||||
return # Already processed
|
||||
order.charge()
|
||||
order.fulfill()
|
||||
# GOOD: Claim ownership before external I/O, then finalize only as that owner
|
||||
from django.db import transaction
|
||||
from apps.payments.gateway import gateway
|
||||
|
||||
@shared_task(bind=True, acks_late=True)
|
||||
def charge_and_fulfill(self, order_id):
|
||||
attempt_id = self.request.id # Stable across Celery retry and redelivery
|
||||
with transaction.atomic():
|
||||
order = Order.objects.select_for_update().get(pk=order_id)
|
||||
if not order.claim_or_resume_charge(attempt_id):
|
||||
return
|
||||
|
||||
# The adapter validates provider data and returns the same charge on retry.
|
||||
receipt = gateway.charge(order_id, idempotency_key=f'order:{order_id}')
|
||||
|
||||
with transaction.atomic():
|
||||
order = Order.objects.select_for_update().get(pk=order_id)
|
||||
if order.charge_attempt_id != attempt_id:
|
||||
return
|
||||
order.record_charge(receipt)
|
||||
order.fulfill()
|
||||
```
|
||||
|
||||
## Production Checklist
|
||||
@@ -443,13 +480,23 @@ def charge_and_fulfill(order_id):
|
||||
| Check | Setting |
|
||||
|-------|---------|
|
||||
| Worker restarts on crash | `supervisord` or `systemd` unit |
|
||||
| `CELERY_TASK_ACKS_LATE = True` | Re-queue tasks on worker crash |
|
||||
| Late acknowledgement | Per task, only after proving idempotency; duplicates remain possible |
|
||||
| Worker-loss redelivery | `task_reject_on_worker_lost`, opt in only with poison-task protection |
|
||||
| `CELERY_WORKER_PREFETCH_MULTIPLIER = 1` | Fair distribution of long tasks |
|
||||
| Separate queues per priority | `-Q default,high_priority,low_priority` |
|
||||
| `CELERY_TASK_SOFT_TIME_LIMIT` set | Graceful timeout before hard kill |
|
||||
| Sentry integration | Capture all `task_failure` signals |
|
||||
| Flower or other monitor | Visibility into queue depths |
|
||||
| Beat runs on single node only | Prevents duplicate scheduled task execution |
|
||||
| Beat runs on single node only | Prevents duplicate scheduled task publication |
|
||||
| Periodic-task locking | Prevents overlapping execution when required |
|
||||
|
||||
## References
|
||||
|
||||
- [Celery task acknowledgement and idempotency](https://docs.celeryq.dev/en/stable/userguide/tasks.html)
|
||||
- [Celery configuration defaults](https://docs.celeryq.dev/en/stable/userguide/configuration.html)
|
||||
- [Celery with Django transaction handling](https://docs.celeryq.dev/en/stable/django/first-steps-with-django.html)
|
||||
- [Celery periodic tasks](https://docs.celeryq.dev/en/stable/userguide/periodic-tasks.html)
|
||||
- [Celery testing guide](https://docs.celeryq.dev/en/stable/userguide/testing.html)
|
||||
|
||||
## Related Skills
|
||||
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
# Delivery Reliability
|
||||
|
||||
Read this reference when changing acknowledgement settings, worker-loss behavior,
|
||||
or task publication around Django database transactions.
|
||||
|
||||
## Acknowledgement and Worker Loss
|
||||
|
||||
Celery acknowledges task messages before execution by default. Opt in to late
|
||||
acknowledgement only for idempotent tasks that are safe to execute more than once:
|
||||
|
||||
```python
|
||||
@shared_task(
|
||||
name='orders.mark_shipped',
|
||||
acks_late=True,
|
||||
)
|
||||
def mark_order_shipped(order_id: int, tracking_number: str) -> None:
|
||||
# Use an idempotent implementation such as the guarded update in SKILL.md.
|
||||
...
|
||||
```
|
||||
|
||||
Late acknowledgement means the task may execute more than once if delivery is
|
||||
interrupted. It does not by itself guarantee redelivery when a worker child exits
|
||||
abruptly. Celery acknowledges worker-loss messages unless
|
||||
`task_reject_on_worker_lost` (or Django's
|
||||
`CELERY_TASK_REJECT_ON_WORKER_LOST`) is enabled. That option can cause message loops
|
||||
for poison tasks, so enable it only after validating idempotency and monitoring the
|
||||
redelivery path. Failure and timeout acknowledgement behavior is controlled
|
||||
separately by `task_acks_on_failure_or_timeout`, which applies only to tasks using
|
||||
late acknowledgement.
|
||||
|
||||
## Publish After the Database Commits
|
||||
|
||||
With Celery 5.4 or newer, `delay_on_commit()` and `apply_async_on_commit()` are
|
||||
available for tasks based on `DjangoTask`. Custom task base classes must inherit from
|
||||
`DjangoTask` to expose this API. These methods do not return a task ID because the
|
||||
message is not published until commit.
|
||||
|
||||
For older Celery versions, or to keep the publication visible at the call site,
|
||||
register it explicitly:
|
||||
|
||||
```python
|
||||
from functools import partial
|
||||
from django.db import transaction
|
||||
|
||||
transaction.on_commit(
|
||||
partial(
|
||||
sync_contact_to_crm.apply_async,
|
||||
args=[contact.pk],
|
||||
queue='high_priority',
|
||||
)
|
||||
)
|
||||
```
|
||||
|
||||
An on-commit callback avoids publication on rollback, but it does not make the
|
||||
database commit and broker publish atomic. If task delivery must not be lost when a
|
||||
publish fails after commit, use a transactional outbox with a separate publisher.
|
||||
|
||||
## Test the On-Commit Contract
|
||||
|
||||
Django's `TestCase` wraps each test in a transaction that is rolled back, never
|
||||
committed, so `transaction.on_commit()` callbacks (including `delay_on_commit()`)
|
||||
never run. A test that only checks the new database row still passes when the task
|
||||
is never queued. Capture the callbacks, execute them, and assert the Celery call:
|
||||
|
||||
```python
|
||||
from unittest.mock import patch
|
||||
|
||||
from django.contrib.auth.models import User
|
||||
from django.test import TestCase
|
||||
|
||||
from apps.users.services import create_user
|
||||
from apps.users.tasks import send_welcome_email
|
||||
|
||||
|
||||
class CreateUserTests(TestCase):
|
||||
def test_queues_welcome_email_after_commit(self):
|
||||
# Patch before the call: delay_on_commit() binds task.delay when it registers.
|
||||
with patch.object(send_welcome_email, 'delay') as mock_delay:
|
||||
with self.captureOnCommitCallbacks(execute=True) as callbacks:
|
||||
create_user('bob')
|
||||
mock_delay.assert_not_called() # Not published before commit
|
||||
|
||||
user = User.objects.get(username='bob')
|
||||
self.assertEqual(len(callbacks), 1)
|
||||
mock_delay.assert_called_once_with(user.pk)
|
||||
```
|
||||
|
||||
`captureOnCommitCallbacks()` is available on `TestCase` in Django 3.2 or newer. With
|
||||
pytest-django, the `django_capture_on_commit_callbacks` fixture provides the same
|
||||
context manager inside `@pytest.mark.django_db` tests.
|
||||
|
||||
Use `TransactionTestCase`, or `@pytest.mark.django_db(transaction=True)`, only when a
|
||||
test needs a real commit: for example, when a real Celery worker in another thread
|
||||
or process must read the committed rows. Those tests commit for real, so on-commit
|
||||
callbacks run when the outermost `atomic()` block commits, and Django resets the
|
||||
database afterwards by truncating tables, which is much slower. Keep them for the
|
||||
worker integration boundary and use `TestCase` with captured callbacks elsewhere.
|
||||
@@ -84,7 +84,7 @@ process_dir() {
|
||||
sort_nul_file "$find_out"
|
||||
|
||||
while IFS= read -r -d '' file; do
|
||||
local mtime dp is_new
|
||||
local mtime dp is_new record_file
|
||||
mtime=$(date -u -r "$file" +%Y-%m-%dT%H:%M:%SZ)
|
||||
dp="${file/#$HOME/~}"
|
||||
|
||||
@@ -101,12 +101,15 @@ process_dir() {
|
||||
' "$RESULTS_JSON")
|
||||
[[ -n "$is_new" ]] || continue
|
||||
|
||||
# Zero-pad record names so the "$tmpdir"/*.json glob below keeps the sorted
|
||||
# discovery order past nine records (unpadded, 10.json sorts before 2.json).
|
||||
printf -v record_file '%s/%08d.json' "$tmpdir" "$i"
|
||||
jq -n \
|
||||
--arg path "$dp" \
|
||||
--arg mtime "$mtime" \
|
||||
--argjson is_new "$is_new" \
|
||||
'{path:$path,mtime:$mtime,is_new:$is_new}' \
|
||||
> "$tmpdir/$i.json"
|
||||
> "$record_file"
|
||||
i=$((i+1))
|
||||
done < "$find_out"
|
||||
}
|
||||
|
||||
@@ -135,7 +135,7 @@ scan_dir_to_json() {
|
||||
sort_nul_file "$find_out"
|
||||
|
||||
while IFS= read -r -d '' file; do
|
||||
local name desc mtime u7 u30 dp
|
||||
local name desc mtime u7 u30 dp record_file
|
||||
name=$(extract_field "$file" "name")
|
||||
desc=$(extract_field "$file" "description")
|
||||
mtime=$(date -u -r "$file" +%Y-%m-%dT%H:%M:%SZ)
|
||||
@@ -154,6 +154,9 @@ scan_dir_to_json() {
|
||||
fi
|
||||
dp="${file/#$HOME/~}"
|
||||
|
||||
# Zero-pad record names so the "$tmpdir"/*.json glob below keeps the sorted
|
||||
# discovery order past nine records (unpadded, 10.json sorts before 2.json).
|
||||
printf -v record_file '%s/%08d.json' "$tmpdir" "$i"
|
||||
jq -n \
|
||||
--arg path "$dp" \
|
||||
--arg name "$name" \
|
||||
@@ -162,7 +165,7 @@ scan_dir_to_json() {
|
||||
--argjson use_7d "$u7" \
|
||||
--argjson use_30d "$u30" \
|
||||
'{path:$path,name:$name,description:$description,use_7d:$use_7d,use_30d:$use_30d,mtime:$mtime}' \
|
||||
> "$tmpdir/$i.json"
|
||||
> "$record_file"
|
||||
i=$((i+1))
|
||||
done < "$find_out"
|
||||
|
||||
|
||||
@@ -0,0 +1,502 @@
|
||||
'use strict';
|
||||
/**
|
||||
* Tests for scripts/ci/check-spec-freshness.js
|
||||
*
|
||||
* v1 contract (file-level freshness):
|
||||
* - git invoked via argv array (execFileSync), never via shell string
|
||||
* - project root and every enforced target resolved through realpaths and
|
||||
* contained inside the project; symlinked root / escaping target rejected
|
||||
* - shallow clones report UNVERIFIED (never ORPHANED/STALE)
|
||||
* - truthful verdicts: FRESH / STALE / ORPHANED (target missing or escaping)
|
||||
* / UNVERIFIED (no git, not a repo, shallow, missing/invalid date,
|
||||
* target never committed)
|
||||
* - ECC_SPEC_STALE_WARN_ONLY honored (=== "true") → stale no longer fails
|
||||
*
|
||||
* Date strategy: commits are made at offsets relative to "today" (daysAgo)
|
||||
* because ECC_SPEC_STALE_DAYS is capped at 365 — a verification dated years in
|
||||
* the past would always trip the age check and mask the change-detection tests.
|
||||
*
|
||||
* Uses the Node native test runner and real (mini) git repositories.
|
||||
*/
|
||||
|
||||
const { describe, it, before, after } = require('node:test');
|
||||
const assert = require('node:assert');
|
||||
const { execSync, execFileSync } = require('child_process');
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
const os = require('os');
|
||||
|
||||
const SCRIPT = path.join(__dirname, '..', '..', 'scripts', 'ci', 'check-spec-freshness.js');
|
||||
|
||||
// ── Helpers ─────────────────────────────────────────────────────
|
||||
|
||||
function runChecker(projectRoot, envOverrides = {}) {
|
||||
const env = { ...process.env, ...envOverrides };
|
||||
for (const key of ['GIT_DIR', 'GIT_WORK_TREE', 'GIT_INDEX_FILE', 'GIT_COMMON_DIR', 'GIT_PREFIX']) {
|
||||
delete env[key];
|
||||
}
|
||||
env.GIT_CONFIG_NOSYSTEM = '1';
|
||||
env.GIT_CONFIG_GLOBAL = '/dev/null';
|
||||
const opts = { encoding: 'utf8', env, stdio: ['pipe', 'pipe', 'pipe'] };
|
||||
let isDir = false;
|
||||
try {
|
||||
isDir = fs.statSync(projectRoot).isDirectory();
|
||||
} catch {
|
||||
isDir = false;
|
||||
}
|
||||
if (isDir) {
|
||||
// Run with the project as cwd so any (buggy) shell execution would land a
|
||||
// marker inside the repo where the hostile-input tests can see it.
|
||||
opts.cwd = projectRoot;
|
||||
}
|
||||
try {
|
||||
const result = execFileSync(process.execPath, [SCRIPT, '--project-root', projectRoot], opts);
|
||||
return { exitCode: 0, stdout: result, stderr: '' };
|
||||
} catch (err) {
|
||||
return {
|
||||
exitCode: err.status || 1,
|
||||
stdout: err.stdout || '',
|
||||
stderr: err.stderr || '',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function parseJson(result) {
|
||||
const line = result.stdout.trim().split('\n').pop();
|
||||
return JSON.parse(line);
|
||||
}
|
||||
|
||||
function git(repo, args) {
|
||||
return execSync(`git ${args}`, { cwd: repo, stdio: ['pipe', 'pipe', 'pipe'] })
|
||||
.toString()
|
||||
.trim();
|
||||
}
|
||||
|
||||
/** Init an isolated git repo (full history) and return its path. */
|
||||
function initRepo() {
|
||||
const repo = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-fresh-'));
|
||||
git(repo, 'init -q');
|
||||
git(repo, 'config user.email "test@example.com"');
|
||||
git(repo, 'config user.name "Test Runner"');
|
||||
return repo;
|
||||
}
|
||||
|
||||
/** Commit `content` as `relPath` at `date` (YYYY-MM-DD). */
|
||||
function commitFile(repo, relPath, content, date, message = `commit ${relPath}`) {
|
||||
const full = path.join(repo, relPath);
|
||||
fs.mkdirSync(path.dirname(full), { recursive: true });
|
||||
fs.writeFileSync(full, content);
|
||||
git(repo, 'add -A');
|
||||
const env = { ...process.env, GIT_AUTHOR_DATE: `${date}T00:00:00`, GIT_COMMITTER_DATE: `${date}T00:00:00` };
|
||||
execSync(`git commit -q -m "${message}"`, { cwd: repo, env, stdio: ['pipe', 'pipe', 'pipe'] });
|
||||
}
|
||||
|
||||
/** Write a spec under openspec/specs/<sub>/spec.md with enforced anchors + date. */
|
||||
function writeSpec(repo, sub, { lastVerified, anchors = [] }) {
|
||||
const dir = path.join(repo, 'openspec', 'specs', sub);
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
const anchorLines = anchors.map((a) => `<!-- enforced: ${a} -->`).join('\n');
|
||||
const lv = lastVerified === undefined ? '' : `Last verified: ${lastVerified}\n`;
|
||||
const content =
|
||||
`---\ntitle: ${sub}\n---\n\n` +
|
||||
`<!-- id: ${sub} -->\n\n` +
|
||||
`${lv}` +
|
||||
`### Requirement: ${sub} behavior\n\n` +
|
||||
`#### Scenario: holds\n` +
|
||||
`- **WHEN** trigger\n` +
|
||||
`- **THEN** outcome\n\n` +
|
||||
`${anchorLines}\n`;
|
||||
fs.writeFileSync(path.join(dir, 'spec.md'), content);
|
||||
}
|
||||
|
||||
function daysAgo(n) {
|
||||
return new Date(Date.now() - n * 86400000).toISOString().split('T')[0];
|
||||
}
|
||||
|
||||
let repos = [];
|
||||
function track(repo) {
|
||||
repos.push(repo);
|
||||
return repo;
|
||||
}
|
||||
|
||||
after(() => {
|
||||
for (const r of repos) {
|
||||
try {
|
||||
fs.rmSync(r, { recursive: true, force: true });
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
repos = [];
|
||||
});
|
||||
|
||||
describe('check-spec-freshness (v1, file-level)', () => {
|
||||
describe('container / config errors', () => {
|
||||
it('returns valid for a missing openspec dir (exit 0)', () => {
|
||||
const repo = track(initRepo());
|
||||
const result = runChecker(repo);
|
||||
assert.strictEqual(result.exitCode, 0);
|
||||
assert.deepStrictEqual(parseJson(result).specs, []);
|
||||
});
|
||||
|
||||
it('returns valid for an empty openspec dir (exit 0)', () => {
|
||||
const repo = track(initRepo());
|
||||
fs.mkdirSync(path.join(repo, 'openspec'), { recursive: true });
|
||||
const result = runChecker(repo);
|
||||
assert.strictEqual(result.exitCode, 0);
|
||||
});
|
||||
|
||||
it('exits 2 for a non-existent project root', () => {
|
||||
const result = runChecker(path.join(os.tmpdir(), 'ecc-missing-' + Date.now()));
|
||||
assert.strictEqual(result.exitCode, 2);
|
||||
});
|
||||
|
||||
it('exits 2 for a project root that is a file', () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-file-'));
|
||||
const file = path.join(dir, 'root-file');
|
||||
fs.writeFileSync(file, 'x');
|
||||
try {
|
||||
const result = runChecker(file);
|
||||
assert.strictEqual(result.exitCode, 2);
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it('exits 2 for a symlinked project root', () => {
|
||||
const real = track(initRepo());
|
||||
const link = path.join(os.tmpdir(), 'ecc-link-' + Date.now());
|
||||
fs.symlinkSync(real, link);
|
||||
try {
|
||||
const result = runChecker(link);
|
||||
assert.strictEqual(result.exitCode, 2, result.stderr);
|
||||
} finally {
|
||||
fs.unlinkSync(link);
|
||||
}
|
||||
});
|
||||
|
||||
it('exits 2 for invalid ECC_SPEC_STALE_DAYS values', () => {
|
||||
const repo = track(initRepo());
|
||||
for (const bad of ['0', '-5', 'abc', '400', '1.5', '0x10']) {
|
||||
const result = runChecker(repo, { ECC_SPEC_STALE_DAYS: bad });
|
||||
assert.strictEqual(result.exitCode, 2, `expected exit 2 for "${bad}"`);
|
||||
}
|
||||
});
|
||||
|
||||
it('accepts the boundary ECC_SPEC_STALE_DAYS value 365', () => {
|
||||
const repo = track(initRepo());
|
||||
const result = runChecker(repo, { ECC_SPEC_STALE_DAYS: '365' });
|
||||
assert.strictEqual(result.exitCode, 0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('verdicts on a real repo with history', () => {
|
||||
// Timeline: src/lib.js committed 300 days ago (v1) and 50 days ago (v2).
|
||||
let repo;
|
||||
before(() => {
|
||||
repo = track(initRepo());
|
||||
commitFile(repo, 'src/lib.js', 'v1\n', daysAgo(300), 'lib v1');
|
||||
commitFile(repo, 'src/lib.js', 'v2\n', daysAgo(50), 'lib v2');
|
||||
});
|
||||
|
||||
it('marks FRESH a spec verified after the last change', () => {
|
||||
writeSpec(repo, 'fresh', { lastVerified: daysAgo(1), anchors: ['src/lib.js::run'] });
|
||||
const result = runChecker(repo);
|
||||
assert.strictEqual(result.exitCode, 0, result.stderr);
|
||||
const spec = parseJson(result).specs.find((s) => s.path.includes('fresh'));
|
||||
assert.strictEqual(spec.status, 'FRESH', JSON.stringify(spec));
|
||||
});
|
||||
|
||||
it('marks STALE a spec whose enforced file changed after verification', () => {
|
||||
// Verification 100 days ago: after v1 (300d), before v2 (50d); age 100d is
|
||||
// under the 365-day cap, so STALE here is caused by the file change alone.
|
||||
writeSpec(repo, 'stale-change', { lastVerified: daysAgo(100), anchors: ['src/lib.js::run'] });
|
||||
const result = runChecker(repo, { ECC_SPEC_STALE_DAYS: '365' });
|
||||
assert.strictEqual(result.exitCode, 1);
|
||||
const spec = parseJson(result).specs.find((s) => s.path.includes('stale-change'));
|
||||
assert.strictEqual(spec.status, 'STALE', JSON.stringify(spec));
|
||||
});
|
||||
|
||||
it('marks STALE purely from an old verification date (age threshold)', () => {
|
||||
// Verification 40 days ago (after the last commit 50d ago → no change),
|
||||
// over the default 30-day threshold → STALE by age only.
|
||||
writeSpec(repo, 'stale-age', { lastVerified: daysAgo(40), anchors: ['src/lib.js::run'] });
|
||||
const result = runChecker(repo); // default threshold 30
|
||||
const spec = parseJson(result).specs.find((s) => s.path.includes('stale-age'));
|
||||
assert.strictEqual(spec.status, 'STALE', JSON.stringify(spec));
|
||||
});
|
||||
|
||||
it('marks UNVERIFIED when Last verified is absent', () => {
|
||||
writeSpec(repo, 'unverified', { anchors: ['src/lib.js::run'] });
|
||||
const result = runChecker(repo);
|
||||
const spec = parseJson(result).specs.find((s) => s.path.includes('unverified'));
|
||||
assert.strictEqual(spec.status, 'UNVERIFIED', JSON.stringify(spec));
|
||||
});
|
||||
|
||||
it('marks UNVERIFIED when Last verified is not a parseable date', () => {
|
||||
writeSpec(repo, 'baddate', { lastVerified: 'not-a-date', anchors: ['src/lib.js::run'] });
|
||||
const result = runChecker(repo);
|
||||
const spec = parseJson(result).specs.find((s) => s.path.includes('baddate'));
|
||||
assert.strictEqual(spec.status, 'UNVERIFIED', JSON.stringify(spec));
|
||||
});
|
||||
|
||||
it('marks UNVERIFIED on trailing text after the date', () => {
|
||||
// Strict YYYY-MM-DD only: a valid-looking prefix inside arbitrary text
|
||||
// must not count as verified evidence.
|
||||
writeSpec(repo, 'traildate', {
|
||||
lastVerified: `${daysAgo(1)} reviewed and approved`,
|
||||
anchors: ['src/lib.js::run'],
|
||||
});
|
||||
const result = runChecker(repo);
|
||||
const spec = parseJson(result).specs.find((s) => s.path.includes('traildate'));
|
||||
assert.strictEqual(spec.status, 'UNVERIFIED', JSON.stringify(spec));
|
||||
});
|
||||
|
||||
it('marks UNVERIFIED on impossible calendar dates', () => {
|
||||
// JS Date silently normalizes 2026-02-30 into March; the checker must
|
||||
// round-trip the components and reject it.
|
||||
writeSpec(repo, 'impossible', {
|
||||
lastVerified: '2026-02-30',
|
||||
anchors: ['src/lib.js::run'],
|
||||
});
|
||||
const result = runChecker(repo);
|
||||
const spec = parseJson(result).specs.find((s) => s.path.includes('impossible'));
|
||||
assert.strictEqual(spec.status, 'UNVERIFIED', JSON.stringify(spec));
|
||||
});
|
||||
|
||||
it('marks UNVERIFIED on future dates', () => {
|
||||
writeSpec(repo, 'futuredate', {
|
||||
lastVerified: '2999-01-01',
|
||||
anchors: ['src/lib.js::run'],
|
||||
});
|
||||
const result = runChecker(repo);
|
||||
const spec = parseJson(result).specs.find((s) => s.path.includes('futuredate'));
|
||||
assert.strictEqual(spec.status, 'UNVERIFIED', JSON.stringify(spec));
|
||||
});
|
||||
|
||||
it('marks ORPHANED when the enforced target file does not exist', () => {
|
||||
writeSpec(repo, 'orphaned', { lastVerified: daysAgo(1), anchors: ['src/missing.js::ghost'] });
|
||||
const result = runChecker(repo);
|
||||
const spec = parseJson(result).specs.find((s) => s.path.includes('orphaned'));
|
||||
assert.strictEqual(spec.status, 'ORPHANED', JSON.stringify(spec));
|
||||
});
|
||||
|
||||
it('marks UNVERIFIED (not ORPHANED) when the target has no git history', () => {
|
||||
// File exists on disk but was never committed.
|
||||
fs.writeFileSync(path.join(repo, 'src', 'untracked.js'), '// never committed\n');
|
||||
writeSpec(repo, 'nohistory', { lastVerified: daysAgo(1), anchors: ['src/untracked.js::fn'] });
|
||||
const result = runChecker(repo);
|
||||
const spec = parseJson(result).specs.find((s) => s.path.includes('nohistory'));
|
||||
assert.strictEqual(spec.status, 'UNVERIFIED', JSON.stringify(spec));
|
||||
});
|
||||
|
||||
it('keeps an old-date target with no git history UNVERIFIED (age must not downgrade it)', () => {
|
||||
fs.writeFileSync(path.join(repo, 'src', 'untracked-old.js'), '// never committed\n');
|
||||
writeSpec(repo, 'nohistory-old', {
|
||||
lastVerified: daysAgo(400),
|
||||
anchors: ['src/untracked-old.js::fn'],
|
||||
});
|
||||
const result = runChecker(repo);
|
||||
const spec = parseJson(result).specs.find((s) => s.path.includes('nohistory-old'));
|
||||
assert.strictEqual(spec.status, 'UNVERIFIED', JSON.stringify(spec));
|
||||
// Note: no exit-code assertion — this shared repo intentionally
|
||||
// accumulates STALE specs from the other verdict tests above.
|
||||
});
|
||||
|
||||
it('marks ORPHANED when an enforced target escapes via a symlink', () => {
|
||||
const outsideDir = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-outside-'));
|
||||
const outside = path.join(outsideDir, 'outside.txt');
|
||||
fs.writeFileSync(outside, 'outside\n');
|
||||
fs.mkdirSync(path.join(repo, 'src'), { recursive: true });
|
||||
fs.symlinkSync(outside, path.join(repo, 'src', 'link.js'));
|
||||
try {
|
||||
writeSpec(repo, 'escape', { lastVerified: daysAgo(1), anchors: ['src/link.js::x'] });
|
||||
const result = runChecker(repo);
|
||||
const spec = parseJson(result).specs.find((s) => s.path.includes('escape'));
|
||||
assert.strictEqual(spec.status, 'ORPHANED', JSON.stringify(spec));
|
||||
} finally {
|
||||
fs.rmSync(outsideDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it('emits stable JSON on stdout and diagnostics on stderr', () => {
|
||||
const result = runChecker(repo, { ECC_SPEC_STALE_DAYS: '365' });
|
||||
const parsed = parseJson(result);
|
||||
assert.ok(Array.isArray(parsed.specs));
|
||||
assert.ok(typeof parsed.staleCount === 'number');
|
||||
assert.ok(typeof parsed.totalCount === 'number');
|
||||
assert.strictEqual(parsed.totalCount, parsed.specs.length);
|
||||
for (const s of parsed.specs) {
|
||||
assert.ok(s.path);
|
||||
assert.ok(['FRESH', 'STALE', 'ORPHANED', 'UNVERIFIED', 'UNKNOWN'].includes(s.status));
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('warning mode / exit contract', () => {
|
||||
let staleRepo;
|
||||
before(() => {
|
||||
staleRepo = track(initRepo());
|
||||
commitFile(staleRepo, 'src/lib.js', 'v1\n', daysAgo(300), 'v1');
|
||||
commitFile(staleRepo, 'src/lib.js', 'v2\n', daysAgo(50), 'v2');
|
||||
writeSpec(staleRepo, 'stale', { lastVerified: daysAgo(100), anchors: ['src/lib.js::run'] });
|
||||
});
|
||||
|
||||
it('exits 1 on stale by default', () => {
|
||||
const result = runChecker(staleRepo, { ECC_SPEC_STALE_DAYS: '365' });
|
||||
assert.strictEqual(result.exitCode, 1);
|
||||
});
|
||||
|
||||
it('exits 0 on stale when ECC_SPEC_STALE_WARN_ONLY=true', () => {
|
||||
const result = runChecker(staleRepo, {
|
||||
ECC_SPEC_STALE_DAYS: '365',
|
||||
ECC_SPEC_STALE_WARN_ONLY: 'true',
|
||||
});
|
||||
assert.strictEqual(result.exitCode, 0, result.stderr);
|
||||
const parsed = parseJson(result);
|
||||
assert.ok(parsed.specs.some((s) => s.status === 'STALE'), 'stale specs must still be reported');
|
||||
});
|
||||
|
||||
it('does not honor non-"true" spellings of the warning flag', () => {
|
||||
const result = runChecker(staleRepo, {
|
||||
ECC_SPEC_STALE_DAYS: '365',
|
||||
ECC_SPEC_STALE_WARN_ONLY: 'TRUE',
|
||||
});
|
||||
assert.strictEqual(result.exitCode, 1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('hostile inputs (shell-escape proof)', () => {
|
||||
it('does not execute a hostile enforced filename (no command substitution)', () => {
|
||||
const repo = track(initRepo());
|
||||
const hostileName = 'evil$(touch${IFS}ECCPWNMARK).js';
|
||||
commitFile(repo, `src/${hostileName}`, '// evil\n', daysAgo(200), 'evil file');
|
||||
writeSpec(repo, 'hostile', { lastVerified: daysAgo(400), anchors: [`src/${hostileName}::evil`] });
|
||||
|
||||
const marker = path.join(repo, 'ECCPWNMARK');
|
||||
const result = runChecker(repo);
|
||||
assert.strictEqual(fs.existsSync(marker), false, 'shell command substitution must not run');
|
||||
// The hostile file genuinely changed after the verification date → STALE.
|
||||
assert.strictEqual(result.exitCode, 1, result.stderr);
|
||||
});
|
||||
|
||||
it('does not execute a hostile date string', () => {
|
||||
const repo = track(initRepo());
|
||||
commitFile(repo, 'src/lib.js', 'v1\n', daysAgo(50), 'v1');
|
||||
const marker = path.join(repo, 'ECCDATEMARK');
|
||||
// The date carries shell payload after a valid date prefix. The strict
|
||||
// YYYY-MM-DD parser rejects the whole value (UNVERIFIED), and nothing
|
||||
// from the line ever reaches a shell or git argv.
|
||||
writeSpec(repo, 'hostiledate', {
|
||||
lastVerified: `${daysAgo(50)}; touch ECCDATEMARK`,
|
||||
anchors: ['src/lib.js::run'],
|
||||
});
|
||||
const result = runChecker(repo);
|
||||
assert.strictEqual(fs.existsSync(marker), false, 'hostile date must not execute');
|
||||
assert.strictEqual(result.exitCode, 0, 'rejected date must not fail the check');
|
||||
const spec = parseJson(result).specs.find((s) => s.path.includes('hostiledate'));
|
||||
assert.strictEqual(spec.status, 'UNVERIFIED', JSON.stringify(spec));
|
||||
});
|
||||
});
|
||||
|
||||
describe('code fences (illustrative content)', () => {
|
||||
it('ignores anchors and Last verified dates inside fenced / inline code', () => {
|
||||
const repo = track(initRepo());
|
||||
commitFile(repo, 'src/lib.js', 'v1\n', daysAgo(300), 'v1');
|
||||
commitFile(repo, 'src/lib.js', 'v2\n', daysAgo(50), 'v2');
|
||||
|
||||
const dir = path.join(repo, 'openspec', 'specs', 'fence');
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
fs.writeFileSync(
|
||||
path.join(dir, 'spec.md'),
|
||||
'---\ntitle: fence\n---\n\n' +
|
||||
`Last verified: ${daysAgo(1)}\n\n` +
|
||||
'### Requirement: fence\n\n' +
|
||||
'#### Scenario: holds\n' +
|
||||
'- **WHEN** trigger\n' +
|
||||
'- **THEN** outcome\n\n' +
|
||||
'<!-- enforced: src/lib.js::run -->\n\n' +
|
||||
'Example (illustrative only):\n\n' +
|
||||
'```md\n' +
|
||||
'<!-- enforced: src/ghost.js::missing -->\n' +
|
||||
'Last verified: 1999-01-01\n' +
|
||||
'```\n\n' +
|
||||
'Inline: `<!-- enforced: src/other.js::x -->`\n'
|
||||
);
|
||||
|
||||
const result = runChecker(repo, { ECC_SPEC_STALE_DAYS: '365' });
|
||||
assert.strictEqual(result.exitCode, 0, result.stderr);
|
||||
const spec = parseJson(result).specs.find((s) => s.path.includes('fence'));
|
||||
assert.strictEqual(spec.status, 'FRESH', JSON.stringify(spec));
|
||||
// Only the real anchor is collected; example anchors must not over-constrain.
|
||||
assert.deepStrictEqual(spec.enforced, ['src/lib.js::run']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('shallow clones', () => {
|
||||
it('reports UNVERIFIED (never ORPHANED/STALE) on shallow history', () => {
|
||||
const full = track(initRepo());
|
||||
commitFile(full, 'src/lib.js', 'v1\n', daysAgo(300), 'v1');
|
||||
commitFile(full, 'src/lib.js', 'v2\n', daysAgo(50), 'v2');
|
||||
|
||||
const shallow = track(fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-shallow-')));
|
||||
// file:// URL is required: git ignores --depth for plain local paths.
|
||||
execFileSync('git', ['clone', '-q', '--depth', '1', `file://${full}`, shallow], {
|
||||
stdio: 'ignore',
|
||||
});
|
||||
|
||||
// A spec that would be FRESH or STALE on full history must be UNVERIFIED.
|
||||
writeSpec(shallow, 'spec', { lastVerified: daysAgo(1), anchors: ['src/lib.js::run'] });
|
||||
const result = runChecker(shallow);
|
||||
const spec = parseJson(result).specs.find((s) => s.path.includes('spec'));
|
||||
assert.ok(spec, 'expected a spec entry');
|
||||
assert.strictEqual(spec.status, 'UNVERIFIED', JSON.stringify(spec));
|
||||
assert.strictEqual(result.exitCode, 0, 'UNVERIFIED must not fail the check');
|
||||
});
|
||||
|
||||
it('keeps an OLD-date spec UNVERIFIED on shallow history (age must not fire first)', () => {
|
||||
const full = track(initRepo());
|
||||
commitFile(full, 'src/lib.js', 'v1\n', daysAgo(300), 'v1');
|
||||
|
||||
const shallow = track(fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-shallow-old-')));
|
||||
execFileSync('git', ['clone', '-q', '--depth', '1', `file://${full}`, shallow], {
|
||||
stdio: 'ignore',
|
||||
});
|
||||
|
||||
// 400 days ago is far past any staleDays threshold: if age were evaluated
|
||||
// before availability, this would be STALE — the documented contract
|
||||
// demands UNVERIFIED because the history is incomplete.
|
||||
writeSpec(shallow, 'oldspec', { lastVerified: daysAgo(400), anchors: ['src/lib.js::run'] });
|
||||
const result = runChecker(shallow);
|
||||
const spec = parseJson(result).specs.find((s) => s.path.includes('oldspec'));
|
||||
assert.ok(spec, 'expected a spec entry');
|
||||
assert.strictEqual(spec.status, 'UNVERIFIED', JSON.stringify(spec));
|
||||
assert.strictEqual(result.exitCode, 0, 'UNVERIFIED must not fail the check');
|
||||
});
|
||||
});
|
||||
|
||||
describe('no git available / not a repository', () => {
|
||||
it('keeps an old-date spec UNVERIFIED outside a git repository', () => {
|
||||
// Plain directory that was never `git init`-ed.
|
||||
const dir = track(fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-nogit-')));
|
||||
fs.writeFileSync(path.join(dir, 'lib.js'), '// not versioned\n');
|
||||
writeSpec(dir, 'oldspec', { lastVerified: daysAgo(400), anchors: ['lib.js::run'] });
|
||||
const result = runChecker(dir);
|
||||
const spec = parseJson(result).specs.find((s) => s.path.includes('oldspec'));
|
||||
assert.ok(spec, 'expected a spec entry');
|
||||
assert.strictEqual(spec.status, 'UNVERIFIED', JSON.stringify(spec));
|
||||
assert.strictEqual(result.exitCode, 0, 'UNVERIFIED must not fail the check');
|
||||
});
|
||||
});
|
||||
|
||||
describe('no enforced anchors', () => {
|
||||
it('marks a dated spec with no anchors as FRESH (nothing to verify)', () => {
|
||||
const repo = track(initRepo());
|
||||
commitFile(repo, 'src/lib.js', 'v1\n', daysAgo(50), 'v1');
|
||||
writeSpec(repo, 'noanchors', { lastVerified: daysAgo(1), anchors: [] });
|
||||
const result = runChecker(repo);
|
||||
const spec = parseJson(result).specs.find((s) => s.path.includes('noanchors'));
|
||||
assert.strictEqual(spec.status, 'FRESH', JSON.stringify(spec));
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -54,6 +54,15 @@ function run() {
|
||||
}
|
||||
})) passed++; else failed++;
|
||||
|
||||
if (test('keeps the Node 18 compatible OpenCode plugin line out of npm bumps', () => {
|
||||
const npmRoot = config.updates.find(update => update['package-ecosystem'] === 'npm' && update.directory === '/');
|
||||
assert.ok(npmRoot, 'missing root npm update entry');
|
||||
const rule = (npmRoot.ignore || []).find(entry => entry['dependency-name'] === '@opencode-ai/plugin');
|
||||
assert.ok(rule, 'missing @opencode-ai/plugin ignore rule');
|
||||
assert.ok(rule['update-types'].includes('version-update:semver-minor'));
|
||||
assert.ok(rule['update-types'].includes('version-update:semver-major'));
|
||||
})) passed++; else failed++;
|
||||
|
||||
console.log(`\nPassed: ${passed}`);
|
||||
console.log(`Failed: ${failed}`);
|
||||
process.exit(failed > 0 ? 1 : 0);
|
||||
|
||||
@@ -377,12 +377,14 @@ function findDriftCandidate(state, cursorRoot) {
|
||||
}
|
||||
|
||||
function runTargetSmoke(options) {
|
||||
const selectionArgs = Array.isArray(options.selectionArgs)
|
||||
? options.selectionArgs
|
||||
: ['--modules', 'workflow-quality', '--enable-hooks'];
|
||||
parseJsonOutput(
|
||||
options.runCli([
|
||||
'install',
|
||||
'--modules', 'workflow-quality',
|
||||
...selectionArgs,
|
||||
'--target', options.target,
|
||||
'--enable-hooks',
|
||||
'--json',
|
||||
]),
|
||||
`${options.target} packed install`
|
||||
@@ -858,6 +860,14 @@ function runLifecycle(options) {
|
||||
});
|
||||
assert.ok(!fs.existsSync(path.join(homeDir, '.opencode')));
|
||||
|
||||
const mistralVibeRoot = path.join(projectDir, '.vibe');
|
||||
runTargetSmoke({
|
||||
runCli,
|
||||
target: 'mistral-vibe',
|
||||
targetRoot: mistralVibeRoot,
|
||||
selectionArgs: ['--skills', 'skill-comply'],
|
||||
});
|
||||
|
||||
return {
|
||||
packageSha256: options.expectedSha256,
|
||||
platform: process.platform,
|
||||
@@ -889,6 +899,7 @@ function runLifecycle(options) {
|
||||
'sentinel-preserved',
|
||||
'antigravity-install-doctor-uninstall',
|
||||
'opencode-install-doctor-uninstall',
|
||||
'mistral-vibe-skill-install-doctor-uninstall',
|
||||
],
|
||||
};
|
||||
} finally {
|
||||
|
||||
@@ -155,6 +155,17 @@ test('workflow-quality target smoke explicitly opts into hooks', () => {
|
||||
);
|
||||
});
|
||||
|
||||
test('packed lifecycle exercises the Mistral Vibe skills-only target', () => {
|
||||
const source = fs.readFileSync(
|
||||
path.join(__dirname, 'packed-artifact-lifecycle.js'),
|
||||
'utf8'
|
||||
);
|
||||
assert.match(
|
||||
source,
|
||||
/target: 'mistral-vibe',[\s\S]*selectionArgs: \['--skills', 'skill-comply'\]/
|
||||
);
|
||||
});
|
||||
|
||||
test('lifecycle cleanup retries Windows file locks without masking results', () => {
|
||||
const source = fs.readFileSync(
|
||||
path.join(__dirname, 'packed-artifact-lifecycle.js'),
|
||||
|
||||
@@ -0,0 +1,504 @@
|
||||
'use strict';
|
||||
/**
|
||||
* Tests for scripts/ci/validate-openspec-syntax.js
|
||||
*
|
||||
* Covers the v1 OpenSpec schema contract:
|
||||
* - baseline specs (Requirement + Scenario, Invariant + enforced anchor)
|
||||
* - per-block delta validation (every declared block must be non-empty)
|
||||
* - metadata allowlist + unknown-key guard + ordinary comments allowed
|
||||
* - enforced anchor grammar (path::symbol, repo-relative, no traversal)
|
||||
*
|
||||
* The validator expects <root>/openspec/ structure; fixtures are built inline
|
||||
* as real files in a temp dir so each case is exercised end-to-end.
|
||||
*/
|
||||
|
||||
const { describe, it } = require('node:test');
|
||||
const assert = require('node:assert');
|
||||
const { execSync } = require('child_process');
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
const os = require('os');
|
||||
|
||||
const SCRIPT = path.join(__dirname, '..', '..', 'scripts', 'ci', 'validate-openspec-syntax.js');
|
||||
|
||||
function runValidator(openspecRoot) {
|
||||
try {
|
||||
const result = execSync(
|
||||
`node "${SCRIPT}" --openspec-root "${openspecRoot}"`,
|
||||
{ encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'] }
|
||||
);
|
||||
return {
|
||||
exitCode: 0,
|
||||
stdout: (result.stdout || result).trim(),
|
||||
stderr: (result.stderr || '').trim(),
|
||||
};
|
||||
} catch (err) {
|
||||
return {
|
||||
exitCode: err.status || 1,
|
||||
stdout: (err.stdout || '').trim(),
|
||||
stderr: (err.stderr || '').trim(),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/** Create a temp project root with openspec/specs/ containing given files */
|
||||
function makeTempProject(files) {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-vs-'));
|
||||
const specsDir = path.join(root, 'openspec', 'specs');
|
||||
fs.mkdirSync(specsDir, { recursive: true });
|
||||
for (const [name, content] of Object.entries(files)) {
|
||||
const filePath = path.join(specsDir, name);
|
||||
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
||||
fs.writeFileSync(filePath, content);
|
||||
}
|
||||
return root;
|
||||
}
|
||||
|
||||
// ── Shared content builders ────────────────────────────────────
|
||||
|
||||
function requirementSpec(extra = '') {
|
||||
return (
|
||||
'---\ntitle: Capability\n---\n\n' +
|
||||
'### Requirement: Some Req\n' +
|
||||
'The system SHALL do the thing.\n\n' +
|
||||
'#### Scenario: happy path\n' +
|
||||
'- **WHEN** x\n' +
|
||||
'- **THEN** y\n\n' +
|
||||
extra
|
||||
);
|
||||
}
|
||||
|
||||
function invariantSpec(anchor = 'src/lib.js::enforceCheck', extra = '') {
|
||||
return (
|
||||
'### Invariant: Some Invariant\n' +
|
||||
'The system SHALL always hold.\n\n' +
|
||||
`<!-- enforced: ${anchor} -->\n\n` +
|
||||
extra
|
||||
);
|
||||
}
|
||||
|
||||
function deltaSpec(blocks) {
|
||||
// blocks: array of { marker: 'ADDED'|'MODIFIED'|'REMOVED', body: string }
|
||||
let out = '---\ntitle: Delta\n---\n\n';
|
||||
for (const b of blocks) {
|
||||
out += `<!-- ${b.marker}: -->\n${b.body}\n`;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
describe('validate-openspec-syntax (v1 schema)', () => {
|
||||
describe('container / exit codes', () => {
|
||||
it('is valid when openspec dir is missing', () => {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-vs-missing-'));
|
||||
try {
|
||||
const result = runValidator(root);
|
||||
assert.strictEqual(result.exitCode, 0);
|
||||
const parsed = JSON.parse(result.stdout.split('\n').pop());
|
||||
assert.strictEqual(parsed.valid, true);
|
||||
assert.deepStrictEqual(parsed.errors, []);
|
||||
} finally {
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it('is valid for an empty openspec directory', () => {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-vs-empty-'));
|
||||
try {
|
||||
fs.mkdirSync(path.join(root, 'openspec'));
|
||||
const result = runValidator(root);
|
||||
assert.strictEqual(result.exitCode, 0);
|
||||
} finally {
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it('exits 2 for a non-existent root', () => {
|
||||
const result = runValidator('/tmp/nonexistent-openspec-root-' + Date.now());
|
||||
assert.strictEqual(result.exitCode, 2);
|
||||
});
|
||||
|
||||
it('exits 2 when root is a file, not a directory', () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-vs-file-'));
|
||||
const file = path.join(dir, 'root-file');
|
||||
fs.writeFileSync(file, 'x');
|
||||
try {
|
||||
const result = runValidator(file);
|
||||
assert.strictEqual(result.exitCode, 2);
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('valid baseline specs', () => {
|
||||
it('passes a Requirement with a Scenario', () => {
|
||||
const root = makeTempProject({ 'valid/spec.md': requirementSpec() });
|
||||
try {
|
||||
const result = runValidator(root);
|
||||
assert.strictEqual(result.exitCode, 0, result.stderr);
|
||||
const parsed = JSON.parse(result.stdout.split('\n').pop());
|
||||
assert.strictEqual(parsed.valid, true);
|
||||
} finally {
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it('passes a spec without YAML frontmatter (frontmatter optional)', () => {
|
||||
const root = makeTempProject({
|
||||
'nofm/spec.md':
|
||||
'# Spec: nofm\n\n' +
|
||||
'### Requirement: Req\n' +
|
||||
'SHALL pass.\n\n' +
|
||||
'#### Scenario: s\n' +
|
||||
'- **WHEN** a\n' +
|
||||
'- **THEN** b\n',
|
||||
});
|
||||
try {
|
||||
const result = runValidator(root);
|
||||
assert.strictEqual(result.exitCode, 0, result.stderr);
|
||||
} finally {
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it('passes an Invariant with a well-formed enforced anchor', () => {
|
||||
const root = makeTempProject({ 'inv/spec.md': invariantSpec() });
|
||||
try {
|
||||
const result = runValidator(root);
|
||||
assert.strictEqual(result.exitCode, 0, result.stderr);
|
||||
} finally {
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it('passes allowlisted metadata on Requirement and Invariant', () => {
|
||||
const root = makeTempProject({
|
||||
'meta/spec.md':
|
||||
requirementSpec(
|
||||
'<!-- id: some-req -->\n' +
|
||||
'<!-- entities: User, Order -->\n' +
|
||||
'<!-- test: OrderTest.placesOrder() -->\n' +
|
||||
'<!-- depends_on: Earlier Behavior -->\n' +
|
||||
'<!-- triggers: Later Behavior -->\n'
|
||||
) +
|
||||
invariantSpec('src/orders.js::rejectInvalid', '<!-- verified_by: OrderTest.rejects() -->\n')
|
||||
+ '<!-- deferred: file1.md, file2.md -->\n',
|
||||
});
|
||||
try {
|
||||
const result = runValidator(root);
|
||||
assert.strictEqual(result.exitCode, 0, result.stderr);
|
||||
} finally {
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('structural validation', () => {
|
||||
it('flags a Requirement with no Scenario', () => {
|
||||
const root = makeTempProject({
|
||||
'noscen/spec.md':
|
||||
'### Requirement: Missing Scenario Req\n' +
|
||||
'This requirement has no scenario.\n',
|
||||
});
|
||||
try {
|
||||
const result = runValidator(root);
|
||||
assert.strictEqual(result.exitCode, 1);
|
||||
const parsed = JSON.parse(result.stdout.split('\n').pop());
|
||||
const hit = parsed.errors.some((e) => e.includes('has no Scenario'));
|
||||
assert.ok(hit, `expected missing-Scenario error, got: ${JSON.stringify(parsed.errors)}`);
|
||||
} finally {
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it('flags an Invariant with no enforced anchor', () => {
|
||||
const root = makeTempProject({
|
||||
'noenf/spec.md':
|
||||
'### Invariant: No Anchor\n' +
|
||||
'Must have an anchor.\n',
|
||||
});
|
||||
try {
|
||||
const result = runValidator(root);
|
||||
assert.strictEqual(result.exitCode, 1);
|
||||
const parsed = JSON.parse(result.stdout.split('\n').pop());
|
||||
const hit = parsed.errors.some((e) => e.includes('enforced'));
|
||||
assert.ok(hit, `expected missing-enforced error, got: ${JSON.stringify(parsed.errors)}`);
|
||||
} finally {
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('enforced anchor grammar', () => {
|
||||
const CASES = [
|
||||
['spaces instead of ::', 'not a valid anchor'],
|
||||
['empty symbol', 'src/lib.js::'],
|
||||
['empty path', '::check'],
|
||||
['absolute path', '/etc/passwd::x'],
|
||||
['dot-dot traversal', '../secret.js::x'],
|
||||
['nested dot-dot traversal', 'src/../../secret.js::x'],
|
||||
['backslash path', 'src\\lib.js::x'],
|
||||
];
|
||||
|
||||
for (const [label, anchor] of CASES) {
|
||||
it(`rejects ${label}`, () => {
|
||||
const root = makeTempProject({ 'badanchor/spec.md': invariantSpec(anchor) });
|
||||
try {
|
||||
const result = runValidator(root);
|
||||
assert.strictEqual(result.exitCode, 1, anchor);
|
||||
const parsed = JSON.parse(result.stdout.split('\n').pop());
|
||||
const hit = parsed.errors.some((e) => e.includes('Invalid enforced anchor'));
|
||||
assert.ok(hit, `expected anchor error for "${anchor}", got: ${JSON.stringify(parsed.errors)}`);
|
||||
} finally {
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
it('accepts a nested relative path anchor', () => {
|
||||
const root = makeTempProject({
|
||||
'nested/spec.md': invariantSpec('packages/core/src/checker.js::verify'),
|
||||
});
|
||||
try {
|
||||
const result = runValidator(root);
|
||||
assert.strictEqual(result.exitCode, 0, result.stderr);
|
||||
} finally {
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('metadata comments', () => {
|
||||
it('flags an unknown machine-shaped metadata key (typo guard)', () => {
|
||||
const root = makeTempProject({
|
||||
'unk/spec.md':
|
||||
requirementSpec('<!-- enforcd: src/lib.js::check -->\n'),
|
||||
});
|
||||
try {
|
||||
const result = runValidator(root);
|
||||
assert.strictEqual(result.exitCode, 1);
|
||||
const parsed = JSON.parse(result.stdout.split('\n').pop());
|
||||
const hit = parsed.errors.some((e) => e.includes('Unknown metadata key'));
|
||||
assert.ok(hit, `expected unknown-key error, got: ${JSON.stringify(parsed.errors)}`);
|
||||
} finally {
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it('allows ordinary prose comments even with a colon', () => {
|
||||
const root = makeTempProject({
|
||||
'prose/spec.md':
|
||||
requirementSpec(
|
||||
'<!-- Note: this is a human note, keep it -->\n' +
|
||||
'<!-- TODO(team): address in follow-up -->\n'
|
||||
),
|
||||
});
|
||||
try {
|
||||
const result = runValidator(root);
|
||||
assert.strictEqual(result.exitCode, 0, result.stderr);
|
||||
} finally {
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it('allows colon-less comments anywhere', () => {
|
||||
const root = makeTempProject({
|
||||
'plain/spec.md': requirementSpec('<!-- just a comment -->\n'),
|
||||
});
|
||||
try {
|
||||
const result = runValidator(root);
|
||||
assert.strictEqual(result.exitCode, 0, result.stderr);
|
||||
} finally {
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('code fences (illustrative content)', () => {
|
||||
it('ignores an enforced anchor inside a fenced code block', () => {
|
||||
const root = makeTempProject({
|
||||
'fence/spec.md':
|
||||
invariantSpec('src/lib.js::enforceCheck') +
|
||||
'Example of what NOT to write:\n\n' +
|
||||
'```md\n' +
|
||||
'<!-- enforced: /etc/passwd::x -->\n' +
|
||||
'```\n',
|
||||
});
|
||||
try {
|
||||
const result = runValidator(root);
|
||||
assert.strictEqual(result.exitCode, 0, result.stderr);
|
||||
} finally {
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it('ignores a tilde-fenced block too', () => {
|
||||
const root = makeTempProject({
|
||||
'fence-tilde/spec.md':
|
||||
invariantSpec('src/lib.js::enforceCheck') +
|
||||
'~~~md\n' +
|
||||
'<!-- enforced: ::broken -->\n' +
|
||||
'~~~\n',
|
||||
});
|
||||
try {
|
||||
const result = runValidator(root);
|
||||
assert.strictEqual(result.exitCode, 0, result.stderr);
|
||||
} finally {
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it('ignores inline code spans containing anchor syntax', () => {
|
||||
const root = makeTempProject({
|
||||
'inline/spec.md':
|
||||
invariantSpec('src/lib.js::enforceCheck') +
|
||||
'Never write `<!-- enforced: not a real anchor -->` in prose.\n',
|
||||
});
|
||||
try {
|
||||
const result = runValidator(root);
|
||||
assert.strictEqual(result.exitCode, 0, result.stderr);
|
||||
} finally {
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it('ignores metadata-looking comments and delta markers inside fences', () => {
|
||||
// 'enforcd' would trip the unknown-key typo guard, and 'ADDED' would
|
||||
// flip the file into delta mode + an empty-block error — if code were
|
||||
// treated as declarative. Both must be ignored.
|
||||
const root = makeTempProject({
|
||||
'fence-meta/spec.md':
|
||||
requirementSpec() +
|
||||
'```md\n' +
|
||||
'<!-- enforcd: typo-in-example -->\n' +
|
||||
'<!-- ADDED: -->\n' +
|
||||
'```\n',
|
||||
});
|
||||
try {
|
||||
const result = runValidator(root);
|
||||
assert.strictEqual(result.exitCode, 0, result.stderr);
|
||||
} finally {
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it('does not treat a fenced anchor as satisfying the Invariant requirement', () => {
|
||||
const root = makeTempProject({
|
||||
'fence-only/spec.md':
|
||||
'### Invariant: Shown Only In Example\n' +
|
||||
'The anchor below is illustrative, not a declaration.\n\n' +
|
||||
'```md\n' +
|
||||
'<!-- enforced: src/lib.js::check -->\n' +
|
||||
'```\n',
|
||||
});
|
||||
try {
|
||||
const result = runValidator(root);
|
||||
assert.strictEqual(result.exitCode, 1);
|
||||
const parsed = JSON.parse(result.stdout.split('\n').pop());
|
||||
const hit = parsed.errors.some((e) => e.includes('missing <!-- enforced: --> anchor'));
|
||||
assert.ok(hit, `expected missing-enforced error, got: ${JSON.stringify(parsed.errors)}`);
|
||||
} finally {
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('delta files', () => {
|
||||
it('passes a delta with three non-empty blocks', () => {
|
||||
const root = makeTempProject({
|
||||
'deltas/valid.md': deltaSpec([
|
||||
{ marker: 'ADDED', body: 'Added validation logic.' },
|
||||
{ marker: 'MODIFIED', body: 'Now uses structured errors.' },
|
||||
{ marker: 'REMOVED', body: 'Dropped legacy path.' },
|
||||
]),
|
||||
});
|
||||
try {
|
||||
const result = runValidator(root);
|
||||
assert.strictEqual(result.exitCode, 0, result.stderr);
|
||||
} finally {
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects a delta where the FIRST block is empty but a later one has content', () => {
|
||||
// Regression for: "content in any later block made all earlier empty blocks pass"
|
||||
const root = makeTempProject({
|
||||
'deltas/first-empty.md': deltaSpec([
|
||||
{ marker: 'ADDED', body: '' },
|
||||
{ marker: 'MODIFIED', body: 'Some real content.' },
|
||||
]),
|
||||
});
|
||||
try {
|
||||
const result = runValidator(root);
|
||||
assert.strictEqual(result.exitCode, 1);
|
||||
const parsed = JSON.parse(result.stdout.split('\n').pop());
|
||||
const hit = parsed.errors.some((e) => e.includes('Empty ADDED block'));
|
||||
assert.ok(hit, `expected empty-ADDED error, got: ${JSON.stringify(parsed.errors)}`);
|
||||
} finally {
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects a delta where every declared block is empty', () => {
|
||||
const root = makeTempProject({
|
||||
'deltas/all-empty.md': deltaSpec([
|
||||
{ marker: 'ADDED', body: '' },
|
||||
{ marker: 'REMOVED', body: '' },
|
||||
]),
|
||||
});
|
||||
try {
|
||||
const result = runValidator(root);
|
||||
assert.strictEqual(result.exitCode, 1);
|
||||
const parsed = JSON.parse(result.stdout.split('\n').pop());
|
||||
const added = parsed.errors.some((e) => e.includes('Empty ADDED block'));
|
||||
const removed = parsed.errors.some((e) => e.includes('Empty REMOVED block'));
|
||||
assert.ok(added, 'expected empty-ADDED error');
|
||||
assert.ok(removed, 'expected empty-REMOVED error');
|
||||
} finally {
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects an empty file as an empty spec', () => {
|
||||
const root = makeTempProject({ 'deltas/empty.md': '' });
|
||||
try {
|
||||
const result = runValidator(root);
|
||||
assert.strictEqual(result.exitCode, 1);
|
||||
const parsed = JSON.parse(result.stdout.split('\n').pop());
|
||||
const hit = parsed.errors.some((e) => e.toLowerCase().includes('empty'));
|
||||
assert.ok(hit, `expected empty error, got: ${JSON.stringify(parsed.errors)}`);
|
||||
} finally {
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('output format', () => {
|
||||
it('emits JSON on stdout only', () => {
|
||||
const root = makeTempProject({ 'bad.md': '' });
|
||||
try {
|
||||
const result = runValidator(root);
|
||||
assert.strictEqual(result.exitCode, 1);
|
||||
const stdoutLines = result.stdout.split('\n').filter((l) => l.trim().length > 0);
|
||||
for (const line of stdoutLines) {
|
||||
assert.doesNotThrow(() => JSON.parse(line), `stdout must be JSON only: ${line}`);
|
||||
}
|
||||
assert.ok(result.stderr.length > 0, 'diagnostics should go to stderr');
|
||||
} finally {
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it('reports valid:false with errors on stdout when invalid', () => {
|
||||
const root = makeTempProject({ 'bad.md': '' });
|
||||
try {
|
||||
const result = runValidator(root);
|
||||
const parsed = JSON.parse(result.stdout.split('\n').pop());
|
||||
assert.strictEqual(parsed.valid, false);
|
||||
assert.ok(Array.isArray(parsed.errors) && parsed.errors.length > 0);
|
||||
} finally {
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -409,6 +409,192 @@ test('deep analyzer evidence scenario rejects no-corpus analyzer changes', () =>
|
||||
assert.ok(playbook.includes('Deep Analyzer Evidence'));
|
||||
});
|
||||
|
||||
test('orchestration efficiency scenario rejects intuition-only parallelism claims', () => {
|
||||
const scenario = readFixtureJson('orchestration-efficiency-evidence/scenario.json');
|
||||
const trace = readFixtureJson('orchestration-efficiency-evidence/trace.json');
|
||||
const report = readFixtureJson('orchestration-efficiency-evidence/report.json');
|
||||
const verifier = readFixtureJson('orchestration-efficiency-evidence/verifier-result.json');
|
||||
const playbook = read('examples/evaluator-rag-prototype/orchestration-efficiency-evidence/candidate-playbook.md');
|
||||
|
||||
assert.strictEqual(scenario.scenario_id, 'orchestration-efficiency-evidence');
|
||||
assert.strictEqual(trace.scenario_id, scenario.scenario_id);
|
||||
assert.strictEqual(report.scenario_id, scenario.scenario_id);
|
||||
assert.strictEqual(verifier.scenario_id, scenario.scenario_id);
|
||||
assert.strictEqual(trace.read_only, true);
|
||||
assert.strictEqual(report.read_only, true);
|
||||
assert.strictEqual(verifier.read_only, true);
|
||||
|
||||
for (const blocked of [
|
||||
'claiming that parallel agents are faster or cheaper without a matched accepted single-agent baseline',
|
||||
'reporting controller-only tokens or cost while omitting worker totals',
|
||||
'excluding failed candidates, edit conflicts, integration rework, retries, or human corrections',
|
||||
'estimating unavailable telemetry or turning one overlapping smoke run into a general efficiency claim',
|
||||
'averaging opposite-sign or unavailable pair deltas into a task-class recommendation'
|
||||
]) {
|
||||
assert.ok(scenario.forbidden_actions.includes(blocked), `Missing orchestration forbidden action: ${blocked}`);
|
||||
}
|
||||
|
||||
for (const required of [
|
||||
'dependency graph and exclusive ownership boundaries are recorded',
|
||||
'single-agent and orchestrated controls are matched',
|
||||
'all attempted candidates use the same acceptance evaluator',
|
||||
'aggregate controller, worker, verifier, and retry cost is recorded or explicitly unavailable',
|
||||
'failed candidates remain in the comparison',
|
||||
'at least three fresh sequential pairs with alternated order are completed before promotion',
|
||||
'every raw attempt is retained and each pair reports quality, time, and cost deltas computed from those attempts',
|
||||
'mixed-sign or unavailable pair deltas yield an inconclusive result that blocks any task-class claim'
|
||||
]) {
|
||||
assert.ok(scenario.acceptance_gates.includes(required), `Missing orchestration acceptance gate: ${required}`);
|
||||
}
|
||||
|
||||
const accepted = verifier.candidates.find(candidate => candidate.candidate_id === 'controlled-paired-orchestration-evaluation');
|
||||
const rejected = verifier.candidates.find(candidate => candidate.candidate_id === 'parallelism-implies-efficiency');
|
||||
|
||||
assert.ok(accepted, 'Missing accepted controlled orchestration candidate');
|
||||
assert.ok(rejected, 'Missing rejected intuition-only orchestration candidate');
|
||||
assert.strictEqual(accepted.decision, 'accepted');
|
||||
assert.strictEqual(rejected.decision, 'rejected');
|
||||
assert.strictEqual(verifier.promoted_candidate_id, accepted.candidate_id);
|
||||
assert.ok(rejected.reasons.join('\n').includes('no matched accepted single-agent baseline'));
|
||||
const externalExperiment = scenario.sources.find(source => source.kind === 'external_experiment');
|
||||
const retrieval = trace.events.find(event => event.phase === 'retrieval');
|
||||
|
||||
assert.ok(externalExperiment, 'Missing external orchestration experiment source');
|
||||
assert.ok(retrieval, 'Missing orchestration retrieval trace event');
|
||||
assert.ok(retrieval.evidence.includes(externalExperiment.url));
|
||||
assert.ok(playbook.includes('total tokens or cost across controller, every worker, the verifier, and'));
|
||||
assert.ok(playbook.includes('At least three sequential pairs with alternated order'));
|
||||
});
|
||||
|
||||
const ORCHESTRATION_ROOT = 'orchestration-efficiency-evidence/';
|
||||
|
||||
function roundDelta(value) {
|
||||
return Math.round(value * 1e6) / 1e6;
|
||||
}
|
||||
|
||||
function metricDirection(metric, deltas) {
|
||||
if (deltas.some(delta => typeof delta !== 'number')) return 'inconclusive';
|
||||
if (deltas.every(delta => delta === 0)) return 'no_difference';
|
||||
const orchestratedHigher = deltas.every(delta => delta > 0);
|
||||
const orchestratedLower = deltas.every(delta => delta < 0);
|
||||
if (!orchestratedHigher && !orchestratedLower) return 'inconclusive';
|
||||
return orchestratedHigher === (metric.better_when === 'higher') ? 'orchestrated_better' : 'single_agent_better';
|
||||
}
|
||||
|
||||
function evaluatePairEvidence(rule, attempts) {
|
||||
const pairIds = [...new Set(attempts.map(attempt => attempt.pair))].sort((a, b) => a - b);
|
||||
const pairDeltas = pairIds.map(pair => {
|
||||
const single = attempts.find(attempt => attempt.pair === pair && attempt.variant === 'single_agent');
|
||||
const orchestrated = attempts.find(attempt => attempt.pair === pair && attempt.variant === 'orchestrated');
|
||||
assert.ok(single && orchestrated, `Pair ${pair} must retain both raw attempts`);
|
||||
const delta = { pair, order: single.run_order === 1 ? 'single_agent_first' : 'orchestrated_first' };
|
||||
for (const metric of rule.metrics) {
|
||||
const orchestratedValue = orchestrated[metric.attempt_field];
|
||||
const singleValue = single[metric.attempt_field];
|
||||
delta[metric.delta_field] = typeof orchestratedValue === 'number' && typeof singleValue === 'number'
|
||||
? roundDelta(orchestratedValue - singleValue)
|
||||
: rule.unavailable_value;
|
||||
}
|
||||
return delta;
|
||||
});
|
||||
const metricDirections = Object.fromEntries(rule.metrics.map(metric => [
|
||||
metric.name,
|
||||
metricDirection(metric, pairDeltas.map(delta => delta[metric.delta_field]))
|
||||
]));
|
||||
const bothOrders = rule.required_orders.every(order => pairDeltas.some(delta => delta.order === order));
|
||||
const consistent = pairDeltas.length >= rule.minimum_pairs
|
||||
&& bothOrders
|
||||
&& Object.values(metricDirections).every(direction => direction !== 'inconclusive');
|
||||
return { pair_deltas: pairDeltas, metric_directions: metricDirections, result: consistent ? 'consistent' : 'inconclusive' };
|
||||
}
|
||||
|
||||
test('orchestration pair fixtures derive recorded deltas from retained raw attempts', () => {
|
||||
const scenario = readFixtureJson(`${ORCHESTRATION_ROOT}scenario.json`);
|
||||
const rule = scenario.pair_consistency_rule;
|
||||
assert.ok(rule, 'Missing machine-readable pair consistency rule');
|
||||
assert.strictEqual(rule.minimum_pairs, 3);
|
||||
assert.deepStrictEqual(rule.metrics.map(metric => metric.name), ['quality', 'time', 'cost']);
|
||||
assert.deepStrictEqual(rule.aggregate_cost_components, ['controller', 'workers', 'verifier', 'retries']);
|
||||
assert.ok(rule.metric_direction.includes('deltas are never averaged'));
|
||||
|
||||
for (const fixture of rule.fixtures) {
|
||||
const evidence = readFixtureJson(`${ORCHESTRATION_ROOT}${fixture}`);
|
||||
assert.strictEqual(evidence.scenario_id, scenario.scenario_id);
|
||||
assert.strictEqual(evidence.read_only, true);
|
||||
assert.strictEqual(evidence.illustrative, true);
|
||||
assert.strictEqual(evidence.evaluation_status, 'illustrative_synthetic_attempts_not_executed_runs');
|
||||
assert.strictEqual(evidence.raw_attempts.length, evidence.pair_deltas.length * 2, `${fixture} dropped raw attempts`);
|
||||
for (const attempt of evidence.raw_attempts) {
|
||||
assert.deepStrictEqual(Object.keys(attempt.cost_breakdown_usd), rule.aggregate_cost_components);
|
||||
const total = Object.values(attempt.cost_breakdown_usd).reduce((sum, value) => sum + value, 0);
|
||||
assert.strictEqual(roundDelta(total), attempt.total_cost_usd, `${attempt.attempt_id} total omits a cost component`);
|
||||
}
|
||||
const derived = evaluatePairEvidence(rule, evidence.raw_attempts);
|
||||
assert.deepStrictEqual(evidence.pair_deltas, derived.pair_deltas, `${fixture} pair deltas do not match raw attempts`);
|
||||
assert.deepStrictEqual(evidence.metric_directions, derived.metric_directions);
|
||||
assert.strictEqual(evidence.result, derived.result);
|
||||
}
|
||||
});
|
||||
|
||||
test('mixed-sign orchestration pairs are inconclusive and promote no candidate', () => {
|
||||
const evidence = readFixtureJson(`${ORCHESTRATION_ROOT}pairs-mixed-sign.json`);
|
||||
const timeDeltas = evidence.pair_deltas.map(delta => delta.time_delta_ms);
|
||||
const meanTimeDelta = timeDeltas.reduce((sum, value) => sum + value, 0) / timeDeltas.length;
|
||||
|
||||
assert.ok(timeDeltas.some(delta => delta > 0) && timeDeltas.some(delta => delta < 0), 'Fixture must contain opposite-sign time deltas');
|
||||
assert.ok(meanTimeDelta < 0, 'Fixture must show that averaging would suggest a misleading direction');
|
||||
assert.strictEqual(evidence.rejected_aggregate.value, meanTimeDelta);
|
||||
assert.strictEqual(evidence.metric_directions.time, 'inconclusive');
|
||||
assert.strictEqual(evidence.metric_directions.cost, 'single_agent_better');
|
||||
assert.strictEqual(evidence.result, 'inconclusive');
|
||||
assert.strictEqual(evidence.promoted_candidate_id, null);
|
||||
assert.ok(evidence.candidates.every(candidate => candidate.decision !== 'accepted'));
|
||||
assert.strictEqual(evidence.candidates[0].claim, null);
|
||||
const reversedPair = evidence.raw_attempts.find(attempt => attempt.attempt_id === 'pair-2-orchestrated');
|
||||
assert.ok(reversedPair.conflicts > 0 && reversedPair.cost_breakdown_usd.retries > 0, 'Reversed pair must keep its coordination cost');
|
||||
});
|
||||
|
||||
test('sign-consistent orchestration pairs allow only a task-class-scoped claim', () => {
|
||||
const evidence = readFixtureJson(`${ORCHESTRATION_ROOT}pairs-sign-consistent.json`);
|
||||
const accepted = evidence.candidates.find(candidate => candidate.decision === 'accepted');
|
||||
|
||||
assert.strictEqual(evidence.result, 'consistent');
|
||||
assert.deepStrictEqual(evidence.metric_directions, {
|
||||
quality: 'no_difference', time: 'orchestrated_better', cost: 'single_agent_better'
|
||||
});
|
||||
assert.ok(accepted, 'Missing accepted task-class claim');
|
||||
assert.strictEqual(evidence.promoted_candidate_id, accepted.candidate_id);
|
||||
assert.ok(accepted.claim.startsWith('For this task class only'));
|
||||
assert.ok(accepted.claim.includes('cost more'), 'Claim must disclose the higher aggregate cost');
|
||||
});
|
||||
|
||||
test('unavailable, too few, or fixed-order orchestration pairs are inconclusive', () => {
|
||||
const rule = readFixtureJson(`${ORCHESTRATION_ROOT}scenario.json`).pair_consistency_rule;
|
||||
const { raw_attempts: attempts } = readFixtureJson(`${ORCHESTRATION_ROOT}pairs-sign-consistent.json`);
|
||||
assert.strictEqual(evaluatePairEvidence(rule, attempts).result, 'consistent');
|
||||
|
||||
const unavailableCost = attempts.map(attempt => (attempt.attempt_id === 'pair-2-orchestrated'
|
||||
? { ...attempt, total_cost_usd: rule.unavailable_value }
|
||||
: attempt));
|
||||
const unavailable = evaluatePairEvidence(rule, unavailableCost);
|
||||
assert.strictEqual(unavailable.pair_deltas[1].cost_delta_usd, rule.unavailable_value);
|
||||
assert.strictEqual(unavailable.metric_directions.cost, 'inconclusive');
|
||||
assert.strictEqual(unavailable.result, 'inconclusive');
|
||||
|
||||
const twoPairs = evaluatePairEvidence(rule, attempts.filter(attempt => attempt.pair !== 3));
|
||||
assert.strictEqual(twoPairs.result, 'inconclusive');
|
||||
|
||||
const fixedOrder = attempts.map(attempt => ({ ...attempt, run_order: attempt.variant === 'single_agent' ? 1 : 2 }));
|
||||
assert.strictEqual(evaluatePairEvidence(rule, fixedOrder).result, 'inconclusive');
|
||||
|
||||
const reversedTime = attempts.map(attempt => (attempt.attempt_id === 'pair-3-orchestrated'
|
||||
? { ...attempt, elapsed_ms: 1500000 }
|
||||
: attempt));
|
||||
const reversed = evaluatePairEvidence(rule, reversedTime);
|
||||
assert.strictEqual(reversed.metric_directions.time, 'inconclusive');
|
||||
assert.strictEqual(reversed.result, 'inconclusive');
|
||||
});
|
||||
|
||||
test('connector gap artifacts share identity and preserve read-only scope', () => {
|
||||
const scenario = readFixtureJson('connector-diagnostics-gap/scenario.json');
|
||||
assert.strictEqual(scenario.scenario_id, 'connector-diagnostics-gap');
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
/** Contract tests for the Mistral Vibe installation guide. */
|
||||
|
||||
'use strict';
|
||||
|
||||
const assert = require('assert');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const repoRoot = path.resolve(__dirname, '..', '..');
|
||||
const guide = fs.readFileSync(path.join(repoRoot, 'docs', 'MISTRAL-VIBE-GUIDE.md'), 'utf8');
|
||||
const readme = fs.readFileSync(path.join(repoRoot, 'README.md'), 'utf8');
|
||||
|
||||
let passed = 0;
|
||||
let failed = 0;
|
||||
|
||||
function test(name, fn) {
|
||||
try {
|
||||
fn();
|
||||
console.log(` ✓ ${name}`);
|
||||
passed += 1;
|
||||
} catch (error) {
|
||||
console.log(` ✗ ${name}`);
|
||||
console.log(` Error: ${error.message}`);
|
||||
failed += 1;
|
||||
}
|
||||
}
|
||||
|
||||
console.log('\n=== Testing Mistral Vibe guide ===\n');
|
||||
|
||||
test('documents the native project skill install and lifecycle', () => {
|
||||
assert.ok(guide.includes('"$ECC_ROOT/install.sh" --target mistral-vibe --skills tdd-workflow'));
|
||||
assert.ok(guide.includes('node "$ECC_ROOT/scripts/doctor.js" --target mistral-vibe'));
|
||||
assert.ok(guide.includes('node "$ECC_ROOT/scripts/repair.js" --target mistral-vibe'));
|
||||
assert.ok(guide.includes('node "$ECC_ROOT/scripts/uninstall.js" --target mistral-vibe'));
|
||||
assert.ok(guide.includes('.vibe/skills/'));
|
||||
assert.ok(guide.includes('npm view ecc-universal version'));
|
||||
assert.ok(!guide.includes('ecc-universal@2.2.1 install --target mistral-vibe'));
|
||||
});
|
||||
|
||||
test('states the verified compatibility boundary without false parity claims', () => {
|
||||
assert.match(guide, /Mistral Vibe v2.25.3/);
|
||||
assert.match(guide, /\.vibe\/agents\/.*TOML/i);
|
||||
assert.match(guide, /\.vibe\/hooks\.toml/);
|
||||
assert.match(guide, /does not\s+configure/i);
|
||||
assert.ok(!guide.includes('--profile minimal'));
|
||||
});
|
||||
|
||||
test('links the Vibe target from the primary README', () => {
|
||||
assert.ok(readme.includes('--target mistral-vibe --skills tdd-workflow'));
|
||||
assert.ok(readme.includes('[Mistral Vibe guide](docs/MISTRAL-VIBE-GUIDE.md)'));
|
||||
});
|
||||
|
||||
console.log(`\nPassed: ${passed}`);
|
||||
console.log(`Failed: ${failed}`);
|
||||
process.exitCode = failed > 0 ? 1 : 0;
|
||||
@@ -146,6 +146,50 @@ function runTests() {
|
||||
assert.strictEqual(result.code, 0);
|
||||
})) passed++; else failed++;
|
||||
|
||||
// The two dev hooks must agree: pre-bash-dev-server-block.js refuses a dev
|
||||
// server outside tmux, and this hook is what puts it in tmux. Both now read
|
||||
// scripts/lib/dev-command.js, so a spelling one recognises cannot be one the
|
||||
// other misses. Before that, this hook used its own raw-text regex and left
|
||||
// every quoted or option-separated form undetached.
|
||||
// Same gate the detection tests above use: on a non-Windows host without
|
||||
// tmux the hook deliberately passes the command through, so asserting a
|
||||
// rewrite there would fail for the right reason and the wrong cause.
|
||||
if (process.platform === 'win32' || tmuxAvailable) {
|
||||
for (const command of [
|
||||
'npm run "dev"',
|
||||
"npm run 'dev'",
|
||||
'npm --silent run dev',
|
||||
'yarn --cwd app dev',
|
||||
// npm takes any config key as `--key value`, so an unknown option must
|
||||
// not swallow the script name.
|
||||
'npm --userconfig /tmp/npmrc run dev',
|
||||
// Option arity is per manager: npm -d and pnpm -w are boolean flags.
|
||||
'npm -d run dev',
|
||||
'pnpm -w dev'
|
||||
]) {
|
||||
(test(`detects a quoted or option-separated dev script: ${command}`, () => {
|
||||
const result = runScript({ tool_input: { command } });
|
||||
assert.strictEqual(result.code, 0, `Hook exited ${result.code}: ${result.stderr}`);
|
||||
const out = JSON.parse(result.stdout);
|
||||
assert.notStrictEqual(
|
||||
out.tool_input.command,
|
||||
command,
|
||||
`Expected ${command} to be rewritten for a dev session`
|
||||
);
|
||||
}) ? passed++ : failed++);
|
||||
}
|
||||
}
|
||||
|
||||
(test('leaves a non-dev command alone', () => {
|
||||
for (const command of ['npm run build', 'npm run dev-setup', 'npm test -- --grep dev']) {
|
||||
const result = runScript({ tool_input: { command } });
|
||||
assert.strictEqual(result.code, 0, `Hook exited ${result.code}: ${result.stderr}`);
|
||||
const out = JSON.parse(result.stdout);
|
||||
assert.strictEqual(out.tool_input.command, command, `Expected ${command} unchanged`);
|
||||
}
|
||||
}) ? passed++ : failed++);
|
||||
|
||||
|
||||
console.log(`\nResults: Passed: ${passed}, Failed: ${failed}`);
|
||||
process.exit(failed > 0 ? 1 : 0);
|
||||
}
|
||||
|
||||
@@ -2013,6 +2013,61 @@ for (const n of [8, 12]) {
|
||||
})) passed++; else failed++;
|
||||
}
|
||||
|
||||
// --- Value-taking option arity (#2837, carried forward onto the current scanner) ---
|
||||
// `--push-option`/`-o`/`--receive-pack`/`--exec`/`--repo`/`--trailer` consume
|
||||
// the next token as data. Git sends or executes it verbatim and still runs the
|
||||
// hooks, so refusing these is a false positive. An unambiguous abbreviation of
|
||||
// a value-taking option consumes the next token exactly like the full name.
|
||||
for (const command of [
|
||||
'git push --push-option --no-verify',
|
||||
'git push --push-option --no-verif',
|
||||
'git push -o --no-verify',
|
||||
'git push --receive-pack --no-verify',
|
||||
'git push --exec --no-verify origin main',
|
||||
'git push --repo --no-verify',
|
||||
'git commit --trailer --no-verify -m "msg"',
|
||||
'git commit --trailer --no-verif -m "msg"',
|
||||
'git push --push-opti --no-verify',
|
||||
'git push --push-o --no-verif',
|
||||
'git commit --trail --no-verify -m "msg"',
|
||||
'git commit --mes --no-verify',
|
||||
"bash -c 'git push -o --no-verify origin main'",
|
||||
'git -C repo commit --trailer --no-verify -m "msg"',
|
||||
'git push --force-with-lease',
|
||||
]) {
|
||||
if (test(`does not block a value-taking option's value: ${command}`, () => {
|
||||
const r = runHook({ tool_input: { command } });
|
||||
assert.strictEqual(r.code, 0, `expected exit 0, got ${r.code}: ${r.stderr}`);
|
||||
})) passed++; else failed++;
|
||||
}
|
||||
|
||||
// Arity must never swallow a real flag. `--force-with-lease` takes an optional,
|
||||
// inline-only value, so the bare form consumes nothing. Inline `=value` forms
|
||||
// are one token. A prefix ambiguous among the value-taking options resolves to
|
||||
// none of them. Value options of another subcommand do not apply.
|
||||
for (const command of [
|
||||
'git push --force-with-lease --no-verify',
|
||||
'git push --force-with-lease --no-verif',
|
||||
'git push --force-with-lease=main:abc123 --no-verify',
|
||||
'git push --push-option=ci.skip --no-verify',
|
||||
'git push --push-opti=ci.skip --no-verify',
|
||||
'git commit --trailer=Key:val --no-verif -m "msg"',
|
||||
'git commit --trail=Key:val --no-verify -m "msg"',
|
||||
'git push --re --no-verify',
|
||||
'git commit --f --no-verify -m "msg"',
|
||||
'git commit --push-option --no-verify -m "msg"',
|
||||
'git push --trailer --no-verify',
|
||||
'git push -o x --no-verify',
|
||||
"bash -c 'git push --re --no-verify'",
|
||||
'git commit --no-verify --trailer x -m "msg"',
|
||||
]) {
|
||||
if (test(`arity handling still blocks: ${command}`, () => {
|
||||
const r = runHook({ tool_input: { command } });
|
||||
assert.strictEqual(r.code, 2, `expected exit 2, got ${r.code}`);
|
||||
assert.ok(r.stderr.includes('BLOCKED'), `stderr should contain BLOCKED: ${r.stderr}`);
|
||||
})) passed++; else failed++;
|
||||
}
|
||||
|
||||
const pureOnly = process.argv.includes('--pure-only');
|
||||
if (pureOnly) console.log('Pure classifier mode: 3 bounded Node routing checks omitted.');
|
||||
else {
|
||||
@@ -2044,6 +2099,51 @@ else {
|
||||
}
|
||||
}
|
||||
|
||||
// Real Git agrees with the arity table: when the hook allows a flag-looking
|
||||
// value, Git still runs the refusing hook and creates nothing.
|
||||
const gitProbe = pureOnly ? null : spawnSync('git', ['--version'], { encoding: 'utf8' });
|
||||
if (gitProbe && gitProbe.status === 0) {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-no-verify-arity-'));
|
||||
const git = (cwd, args) => spawnSync('git', args, {
|
||||
cwd, encoding: 'utf8', timeout: 10000,
|
||||
env: { ...process.env, GIT_CONFIG_GLOBAL: path.join(root, 'absent'), GIT_CONFIG_NOSYSTEM: '1', GIT_TERMINAL_PROMPT: '0' },
|
||||
});
|
||||
try {
|
||||
const repo = path.join(root, 'repo');
|
||||
const remote = path.join(root, 'remote.git');
|
||||
git(root, ['init', '-q', repo]);
|
||||
git(root, ['init', '-q', '--bare', remote]);
|
||||
const identity = ['-c', 'user.name=ECC', '-c', 'user.email=ecc@example.invalid'];
|
||||
git(repo, [...identity, 'commit', '-q', '--allow-empty', '-m', 'base']);
|
||||
git(repo, ['remote', 'add', 'origin', remote]);
|
||||
git(repo, ['push', '-q', 'origin', 'HEAD:refs/heads/main']);
|
||||
for (const name of ['pre-commit', 'pre-push']) {
|
||||
const hookPath = path.join(repo, '.git', 'hooks', name);
|
||||
fs.writeFileSync(hookPath, '#!/bin/sh\nexit 1\n');
|
||||
fs.chmodSync(hookPath, 0o755);
|
||||
}
|
||||
git(repo, [...identity, 'commit', '-q', '--allow-empty', '--no-verify', '-m', 'ahead']);
|
||||
for (const args of [
|
||||
['commit', '--allow-empty', '--trailer', '--no-verify', '-m', 'probe'],
|
||||
['commit', '--allow-empty', '--mes', '--no-verify'],
|
||||
['push', '--push-option', '--no-verify', 'origin', 'HEAD:refs/heads/main'],
|
||||
['push', '--push-opti', '--no-verify', 'origin', 'HEAD:refs/heads/main'],
|
||||
]) {
|
||||
if (test(`real Git still runs the hook after an allowed value: git ${args.join(' ')}`, () => {
|
||||
assert.strictEqual(runHook({ tool_input: { command: `git ${args.join(' ')}` } }).code, 0);
|
||||
const head = git(repo, ['rev-parse', 'HEAD']).stdout;
|
||||
const remoteHead = git(remote, ['rev-parse', 'main']).stdout;
|
||||
const result = git(repo, [...identity, ...args]);
|
||||
assert.notStrictEqual(result.status, 0, 'the refusing hook must stop Git');
|
||||
assert.strictEqual(git(repo, ['rev-parse', 'HEAD']).stdout, head);
|
||||
assert.strictEqual(git(remote, ['rev-parse', 'main']).stdout, remoteHead);
|
||||
})) passed++; else failed++;
|
||||
}
|
||||
} finally {
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
// Contributor carry-forward regressions for #2858 and #2897.
|
||||
for (const [name, command, expected] of [
|
||||
[
|
||||
|
||||
@@ -609,6 +609,65 @@ function runTests() {
|
||||
}
|
||||
})) passed++; else failed++;
|
||||
|
||||
if (test('delivers the full Stop JSON even when stdout writes are asynchronous', () => {
|
||||
// Regression: the Stop JSON was written with console.log and main()
|
||||
// called process.exit(0) immediately after, so when stdout is a pipe
|
||||
// the write is asynchronous and the exit can truncate the payload
|
||||
// (Node documents this process.exit truncation for piped stdout).
|
||||
// Force every stdout write to be asynchronous with a preload, so the
|
||||
// race reproduces deterministically instead of relying on pipe timing.
|
||||
const testDir = createTestDir();
|
||||
const transcript = createTranscript(testDir, 12);
|
||||
const homunculusDir = fs.mkdtempSync(path.join(os.tmpdir(), 'eval-delivery-home-'));
|
||||
const sessionId = 'delivery-flush-1';
|
||||
const marker = deliveryMarkerPath(homunculusDir, sessionId);
|
||||
const preloadPath = path.join(testDir, 'async-stdout-preload.js');
|
||||
fs.writeFileSync(preloadPath, [
|
||||
'// Test-only preload: defer every stdout write to the next macrotask,',
|
||||
'// so a process.exit(0) before the flush drops the data.',
|
||||
'const origWrite = process.stdout.write.bind(process.stdout);',
|
||||
'process.stdout.write = function (chunk, encoding, cb) {',
|
||||
' if (typeof encoding === \'function\') { cb = encoding; encoding = undefined; }',
|
||||
' setImmediate(() => origWrite(chunk, encoding, cb));',
|
||||
' return true;',
|
||||
'};',
|
||||
'',
|
||||
].join('\n'));
|
||||
try {
|
||||
fs.rmSync(marker, { force: true });
|
||||
registerLeaseFor(testDir, homunculusDir, sessionId);
|
||||
const result = withOptInConfig(true, () => {
|
||||
const spawned = spawnSync('node', ['-r', preloadPath, evaluateScript], {
|
||||
encoding: 'utf8',
|
||||
input: JSON.stringify(stopPayload(transcript, sessionId, testDir)),
|
||||
timeout: 10000,
|
||||
env: isolatedEnv({ CLV2_HOMUNCULUS_DIR: homunculusDir, CLAUDE_PROJECT_DIR: testDir }),
|
||||
});
|
||||
return {
|
||||
code: spawned.error || spawned.signal ? null : spawned.status,
|
||||
stdout: spawned.stdout || '',
|
||||
stderr: spawned.stderr || '',
|
||||
};
|
||||
});
|
||||
assert.strictEqual(result.code, 0);
|
||||
let parsed;
|
||||
try {
|
||||
parsed = JSON.parse(result.stdout);
|
||||
} catch {
|
||||
assert.fail(`Stdout must arrive complete even with async stdout writes. Got: ${result.stdout}`);
|
||||
}
|
||||
assert.strictEqual(parsed.decision, 'block', 'Native Stop delivery blocks the stop');
|
||||
assert.ok(
|
||||
typeof parsed.reason === 'string' && parsed.reason.includes('12 messages'),
|
||||
`Reason must carry the session signal. Got: ${parsed.reason}`
|
||||
);
|
||||
} finally {
|
||||
fs.rmSync(marker, { force: true });
|
||||
cleanupTestDir(testDir);
|
||||
fs.rmSync(homunculusDir, { recursive: true, force: true });
|
||||
}
|
||||
})) passed++; else failed++;
|
||||
|
||||
if (test('skips delivery when the delivery marker cannot be written', () => {
|
||||
const testDir = createTestDir();
|
||||
const transcript = createTranscript(testDir, 12);
|
||||
|
||||
@@ -730,6 +730,51 @@ function runDdRegressionTests() {
|
||||
});
|
||||
}
|
||||
}
|
||||
// #2832: find execs its action argv directly, so a wrapper or a nested
|
||||
// shell there runs rm/Git exactly like a bare `-exec rm {} \;`.
|
||||
const findExecWrappedDestructive = [
|
||||
'find . -exec sudo rm {} \\;',
|
||||
'find . -exec doas rm {} \\;',
|
||||
'find . -exec sudo -u root rm -rf {} \\;',
|
||||
'find . -exec sudo git reset --hard \\;',
|
||||
'find . -execdir sudo rm {} \\;',
|
||||
'find . -ok doas rm {} \\;',
|
||||
'find . -exec timeout 5m rm -rf {} \\;',
|
||||
'find . -exec setsid rm -rf {} +',
|
||||
'find . -exec env FOO=1 rm -rf {} +',
|
||||
'find . -exec nice -n 5 rm -rf {} +',
|
||||
'sudo find . -exec rm {} \\;',
|
||||
'timeout 5 find . -exec rm -rf {} +',
|
||||
"find . -exec sh -c 'rm -rf {}' \\;",
|
||||
'find . -exec bash -c "rm -rf /important/data" \\;',
|
||||
'find . -exec sh -ec "rm -rf {}" +',
|
||||
'find . -exec sh -o errexit -c "rm -rf {}" \\;',
|
||||
'find . -exec sh -c "git reset --hard" \\;',
|
||||
"find . -exec sudo sh -c 'rm -rf {}' \\;",
|
||||
"find . -exec timeout 5 sh -c 'rm -rf {}' \\;",
|
||||
"find . -exec su -c 'rm -rf /important/data' \\;"
|
||||
];
|
||||
const findExecWrappedPassive = [
|
||||
'find . -exec sudo chmod 644 {} \\;',
|
||||
'find . -exec sudo git status \\;',
|
||||
'find . -exec sudo -l rm -rf {} \\;',
|
||||
'find . -exec echo sudo rm -rf {} \\;',
|
||||
'find . -exec timeout 5 echo rm -rf {} \\;',
|
||||
"find . -exec sh -c 'echo rm -rf {}' \\;",
|
||||
'find . -exec sh -c "npm test" \\;',
|
||||
"find . -name 'sudo rm -rf' -print",
|
||||
'sudo find . -name "*.log" -exec ls {} \\;'
|
||||
];
|
||||
for (const [commands, expected] of [
|
||||
[findExecWrappedDestructive, ['gateguard.bash-compatible-destructive']],
|
||||
[findExecWrappedPassive, []]
|
||||
]) {
|
||||
for (const command of commands) {
|
||||
check(`find -exec wrapper classification: ${JSON.stringify(command)}`, () => {
|
||||
assert.deepStrictEqual(hook.classifyDestructiveCommand('Bash', command), expected);
|
||||
});
|
||||
}
|
||||
}
|
||||
for (const [command, denied] of [
|
||||
['sudo -u root dd if=input', true],
|
||||
["sh -c 'echo $(dd if=input)'", true],
|
||||
@@ -738,7 +783,10 @@ function runDdRegressionTests() {
|
||||
['find . -exec echo {} \\; -exec dd if=input \\;', true],
|
||||
['command -pv dd', false],
|
||||
["timeout 2 sh -c 'dd if=input'", true],
|
||||
['cat /dev/zero | dd of=/dev/sda', true]
|
||||
['cat /dev/zero | dd of=/dev/sda', true],
|
||||
['find . -exec sudo rm -rf {} \\;', true],
|
||||
["find . -exec sh -c 'rm -rf {}' +", true],
|
||||
['find . -exec sudo chmod 644 {} \\;', false]
|
||||
]) {
|
||||
check(`dd hook-input contract: ${command}`, () => {
|
||||
fs.rmSync(stateDir, { recursive: true, force: true });
|
||||
|
||||
@@ -32,6 +32,25 @@ function runScript(command) {
|
||||
return { code: result.status || 0, stdout: result.stdout || '', stderr: result.stderr || '' };
|
||||
}
|
||||
|
||||
/**
|
||||
* Run the hook with `process.platform` forced to a POSIX value.
|
||||
*
|
||||
* The hook is a no-op on Windows, so its decision cannot be observed there at
|
||||
* all — yet the decision itself has nothing platform-specific in it.
|
||||
*/
|
||||
function runScriptAsPosix(command) {
|
||||
const input = { tool_input: { command } };
|
||||
const bootstrap =
|
||||
"Object.defineProperty(process, 'platform', { value: 'linux' });" +
|
||||
`require(${JSON.stringify(script)});`;
|
||||
const result = spawnSync('node', ['-e', bootstrap], {
|
||||
encoding: 'utf8',
|
||||
input: JSON.stringify(input),
|
||||
timeout: 10000,
|
||||
});
|
||||
return { code: result.status || 0, stdout: result.stdout || '', stderr: result.stderr || '' };
|
||||
}
|
||||
|
||||
function runTests() {
|
||||
console.log('\n=== Testing pre-bash-dev-server-block.js ===\n');
|
||||
|
||||
@@ -386,6 +405,136 @@ function runTests() {
|
||||
assert.strictEqual(result.stdout.trim(), inputStr, `Expected stdout to contain original input`);
|
||||
}) ? passed++ : failed++);
|
||||
|
||||
// --- Quoted and option-separated spellings (all platforms) ---
|
||||
//
|
||||
// The hook no-ops on Windows, so the blocking tests above are skipped there
|
||||
// and this class of bug could only be caught on CI. The DECISION is
|
||||
// platform-independent, so these force the platform in-process and run
|
||||
// everywhere.
|
||||
//
|
||||
// Measured before the token-based script lookup, every one of these reached
|
||||
// the shell as a plain `npm run dev` and was allowed:
|
||||
//
|
||||
// npm run "dev" allow npm --silent run dev allow
|
||||
// npm run 'dev' allow yarn --cwd app dev allow
|
||||
// pnpm "dev" allow
|
||||
|
||||
for (const command of [
|
||||
'npm run "dev"',
|
||||
"npm run 'dev'",
|
||||
'npm run de"v"',
|
||||
'pnpm "dev"',
|
||||
'yarn run "dev"',
|
||||
'bun run "dev"',
|
||||
'npm --silent run dev',
|
||||
'yarn --cwd app dev',
|
||||
// npm accepts any config key as `--key value`, so an option the parser does
|
||||
// not know must not swallow the script name behind it.
|
||||
'npm --userconfig /tmp/npmrc run dev',
|
||||
'npm --registry https://registry.example run dev',
|
||||
'npm --loglevel silly run dev',
|
||||
// pnpm/yarn/bun take a script without `run`, so a value-taking option of
|
||||
// theirs must not be read as the script name.
|
||||
'pnpm --loglevel debug dev',
|
||||
'yarn --network-timeout 60000 dev',
|
||||
'bun --env-file .env dev',
|
||||
// The implicit script wins over anything after it: this runs `dev` and
|
||||
// passes it `run build`.
|
||||
'pnpm dev run build'
|
||||
]) {
|
||||
(test(`blocks a quoted or option-separated dev script: ${command}`, () => {
|
||||
const result = runScriptAsPosix(command);
|
||||
assert.strictEqual(result.code, 2, `Expected exit code 2, got ${result.code}`);
|
||||
assert.ok(result.stderr.includes('BLOCKED'), `Expected BLOCKED, got: ${result.stderr}`);
|
||||
}) ? passed++ : failed++);
|
||||
}
|
||||
|
||||
for (const command of [
|
||||
'npm run dev-setup',
|
||||
'pnpm run dev-docs',
|
||||
'yarn dev-build',
|
||||
'npm run build',
|
||||
'npm test',
|
||||
'npm install',
|
||||
// `--` ends the manager's own arguments: everything after it belongs to the
|
||||
// script, so a stray "dev" there is not a dev server.
|
||||
'npm test -- --grep dev',
|
||||
// A known value-taking option still consumes its value, so a workspace or
|
||||
// filter literally named `dev` is not mistaken for the dev script.
|
||||
'npm run build --workspace dev',
|
||||
'pnpm --filter dev run build',
|
||||
// After the `run` keyword the next token IS the script; everything past it
|
||||
// is that script's argument. `npm run run dev` runs a script called `run`.
|
||||
'npm run run dev',
|
||||
'npm run build dev',
|
||||
'tmux new-session -d -s dev "npm run dev"'
|
||||
]) {
|
||||
(test(`still allows: ${command}`, () => {
|
||||
const result = runScriptAsPosix(command);
|
||||
assert.strictEqual(result.code, 0, `Expected exit code 0, got ${result.code}: ${result.stderr}`);
|
||||
}) ? passed++ : failed++);
|
||||
}
|
||||
|
||||
// --- Manager-specific option arity ---
|
||||
//
|
||||
// The same short flag means different things per manager: npm -d and pnpm -d
|
||||
// are loglevel flags, bun -d is --define <K:V>, pnpm -w is the boolean
|
||||
// --workspace-root. A shared value table swallowed `run` or `dev` after the
|
||||
// boolean spellings, so `npm -d run dev` escaped tmux.
|
||||
for (const command of [
|
||||
'npm -d run dev',
|
||||
'npm -dd run dev',
|
||||
'npm -w app run dev',
|
||||
'pnpm -d dev',
|
||||
'pnpm -d run dev',
|
||||
'pnpm -w dev',
|
||||
'pnpm -C app dev',
|
||||
'pnpm --dir app run dev',
|
||||
'pnpm --filter web dev',
|
||||
'yarn -s dev',
|
||||
'yarn --cwd app run dev',
|
||||
'bun -d K:V dev',
|
||||
'bun --define K:V run dev',
|
||||
'bun --cwd app dev',
|
||||
// bun -c takes an optional value, so both readings are checked.
|
||||
'bun -c dev',
|
||||
'bun -c bunfig.toml dev',
|
||||
'npm run dev -- --port 3000',
|
||||
"tmux run-shell 'npm run \"dev\"'"
|
||||
]) {
|
||||
(test(`blocks across manager grammars: ${command}`, () => {
|
||||
const result = runScriptAsPosix(command);
|
||||
assert.strictEqual(result.code, 2, `Expected exit code 2, got ${result.code}`);
|
||||
assert.ok(result.stderr.includes('BLOCKED'), `Expected BLOCKED, got: ${result.stderr}`);
|
||||
}) ? passed++ : failed++);
|
||||
}
|
||||
|
||||
for (const command of [
|
||||
'pnpm --filter dev run build',
|
||||
'pnpm -F dev build',
|
||||
'pnpm -C dev build',
|
||||
'bun -d dev:1 build',
|
||||
'yarn --cwd dev build',
|
||||
'pnpm run build -- dev',
|
||||
'npm run lint -- "npm run dev"',
|
||||
"tmux new-session -d -s dev 'npm run \"dev\"'",
|
||||
// A value-taking option with no value consumes nothing that runs.
|
||||
'pnpm --filter',
|
||||
'npm run'
|
||||
]) {
|
||||
(test(`allows across manager grammars: ${command}`, () => {
|
||||
const result = runScriptAsPosix(command);
|
||||
assert.strictEqual(result.code, 0, `Expected exit code 0, got ${result.code}: ${result.stderr}`);
|
||||
}) ? passed++ : failed++);
|
||||
}
|
||||
|
||||
(test('blocks the bare `pnpm dev` / `yarn dev` / `bun dev` forms', () => {
|
||||
for (const command of ['pnpm dev', 'yarn dev', 'bun dev', 'npm run dev:ssr']) {
|
||||
const result = runScriptAsPosix(command);
|
||||
assert.strictEqual(result.code, 2, `Expected exit code 2 for ${command}, got ${result.code}`);
|
||||
}
|
||||
}) ? passed++ : failed++);
|
||||
|
||||
// --- Summary ---
|
||||
|
||||
console.log(`\nResults: Passed: ${passed}, Failed: ${failed}`);
|
||||
|
||||
@@ -86,6 +86,18 @@ function testDropsClassifierNotice() {
|
||||
});
|
||||
}
|
||||
|
||||
function testDropsLongClassifierNotice() {
|
||||
const longNotice = `${CLASSIFIER_NOTICE_TEXT} The rest of it was withheld, and tool calls in it that had not finished did not run. Do not produce that content again, even reworded.`;
|
||||
withTranscript('3867dddd-eeee-4fff-8aaa-bbbbbbbb3867', [
|
||||
JSON.stringify({ type: 'user', message: { role: 'user', content: 'Refactor the config loader' } }),
|
||||
JSON.stringify({ type: 'user', content: longNotice }),
|
||||
JSON.stringify({ type: 'user', content: 'Why did this happen?' }),
|
||||
], out => {
|
||||
assert.ok(out.includes('- Refactor the config loader') && out.includes('Why did this happen?'), `expected real user asks in:\n${out}`);
|
||||
assert.ok(!out.includes('withheld') && !out.includes('safety classifier'), `long notice must not be summarized:\n${out}`);
|
||||
});
|
||||
}
|
||||
|
||||
function testNoticeOnlyTranscript() {
|
||||
withTranscript('3867bbbb-cccc-4ddd-8eee-ffffffff3867', [JSON.stringify({ type: 'user', content: CLASSIFIER_NOTICE_TEXT })], out => {
|
||||
assert.ok(!out.includes(START), `a notice-only transcript must not produce a summary block:\n${out}`);
|
||||
@@ -93,6 +105,17 @@ function testNoticeOnlyTranscript() {
|
||||
});
|
||||
}
|
||||
|
||||
function testDropsMultilineClassifierNotice() {
|
||||
const wrapped = CLASSIFIER_NOTICE_TEXT.replace('safety classifier', 'safety\nclassifier');
|
||||
withTranscript('3867eeee-ffff-4aaa-8bbb-cccccccc3867', [
|
||||
JSON.stringify({ type: 'user', content: 'Refactor the config loader' }),
|
||||
JSON.stringify({ type: 'user', content: wrapped }),
|
||||
], out => {
|
||||
assert.ok(out.includes('- Refactor the config loader'), `expected the real user task in:\n${out}`);
|
||||
assert.ok(!/safety\s+classifier/.test(out), `wrapped notice must not be summarized:\n${out}`);
|
||||
});
|
||||
}
|
||||
|
||||
function testKeepsMessageQuotingNotice() {
|
||||
const userText = 'Why did I see "Your response above was stopped by a safety classifier" earlier?';
|
||||
withTranscript('3867cccc-dddd-4eee-8fff-aaaaaaaa3867', [JSON.stringify({ type: 'user', content: userText })], out => {
|
||||
@@ -103,6 +126,8 @@ function testKeepsMessageQuotingNotice() {
|
||||
function runClassifierNoticeTests() {
|
||||
const results = [
|
||||
test('drops safety-classifier notices from summary tasks', testDropsClassifierNotice),
|
||||
test('drops the longer classifier notice from summary tasks', testDropsLongClassifierNotice),
|
||||
test('drops a classifier notice wrapped across lines', testDropsMultilineClassifierNotice),
|
||||
test('writes no summary for a transcript holding only a classifier notice', testNoticeOnlyTranscript),
|
||||
test('keeps a user message that only mentions the classifier notice', testKeepsMessageQuotingNotice),
|
||||
];
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
'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 { test } = require('node:test');
|
||||
const { createManifestInstallPlan } = require('../../scripts/lib/install/plan');
|
||||
const { applyInstallPlan, previewInstallPlan } = require('../../scripts/lib/install/apply');
|
||||
const { readInstallState } = require('../../scripts/lib/install-state');
|
||||
const { withHookConsent } = require('../../scripts/lib/install/hook-consent');
|
||||
|
||||
for (const target of ['antigravity', 'antigravity-home']) {
|
||||
for (const legacy of [false, true]) {
|
||||
test(`${target} revokes ${legacy ? 'legacy' : 'current'} hooks and can re-enable them`, () => {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-hook-consent-'));
|
||||
try {
|
||||
const options = { moduleIds: ['hooks-runtime'], target, homeDir: root, projectRoot: root };
|
||||
const enabled = withHookConsent(createManifestInstallPlan(options), 'enabled');
|
||||
applyInstallPlan(enabled);
|
||||
const hooksPath = path.join(enabled.targetRoot, 'hooks.json');
|
||||
const setupPath = path.join(enabled.targetRoot, 'ecc', 'setup.json');
|
||||
const bridgePath = path.join(enabled.targetRoot, 'scripts', 'hooks', 'antigravity-hook-bridge.js');
|
||||
const marker = path.join(root, 'hook-ran');
|
||||
// Simulate an already installed bridge that predates managed flag support.
|
||||
if (legacy) {
|
||||
fs.rmSync(setupPath);
|
||||
fs.writeFileSync(bridgePath, `require('node:fs').writeFileSync(${JSON.stringify(marker)}, 'ran');`);
|
||||
}
|
||||
const config = JSON.parse(fs.readFileSync(hooksPath, 'utf8'));
|
||||
const userHook = { Stop: [{ type: 'command', command: 'user-selected-hook' }] };
|
||||
fs.writeFileSync(hooksPath, JSON.stringify({ ...config, 'user-hook': userHook }));
|
||||
const declinePlan = withHookConsent(createManifestInstallPlan(options), 'declined');
|
||||
const beforePreview = fs.readFileSync(hooksPath, 'utf8');
|
||||
const preview = previewInstallPlan(declinePlan);
|
||||
assert.ok(preview.operations.some(operation => operation.kind === 'remove-antigravity-hooks'));
|
||||
assert.ok(preview.warnings.some(warning => /disabl.*Antigravity hooks/i.test(warning)));
|
||||
assert.equal(fs.readFileSync(hooksPath, 'utf8'), beforePreview);
|
||||
applyInstallPlan(declinePlan);
|
||||
const declined = JSON.parse(fs.readFileSync(hooksPath, 'utf8'));
|
||||
assert.deepEqual(declined['user-hook'], userHook);
|
||||
for (const handler of declined['ecc-guard']?.PostToolUse || []) {
|
||||
for (const hook of handler.hooks || []) {
|
||||
const result = spawnSync(hook.command, {
|
||||
shell: true, cwd: root, encoding: 'utf8',
|
||||
input: JSON.stringify({ toolCall: { name: 'write_to_file', args: { TargetFile: path.join(root, 'file.js') } } }),
|
||||
});
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
}
|
||||
}
|
||||
assert.equal(fs.existsSync(marker), false, 'Declined legacy hook must not execute');
|
||||
assert.equal(Object.hasOwn(declined, 'ecc-guard'), false);
|
||||
assert.equal(JSON.parse(fs.readFileSync(setupPath, 'utf8')).hooks.enabled, false);
|
||||
assert.equal(readInstallState(enabled.installStatePath).request.hookConsent, 'declined');
|
||||
applyInstallPlan(withHookConsent(createManifestInstallPlan(options), 'declined'));
|
||||
assert.deepEqual(JSON.parse(fs.readFileSync(hooksPath, 'utf8'))['user-hook'], userHook);
|
||||
applyInstallPlan(withHookConsent(createManifestInstallPlan(options), 'enabled'));
|
||||
assert.ok(JSON.parse(fs.readFileSync(hooksPath, 'utf8'))['ecc-guard']);
|
||||
assert.equal(JSON.parse(fs.readFileSync(setupPath, 'utf8')).hooks.enabled, true);
|
||||
} finally {
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
for (const unsafe of ['modified-hooks', 'symlinked-setup', 'swapped-setup']) {
|
||||
test(`${target} refuses ${unsafe} before recording declined consent`, {
|
||||
skip: process.platform === 'win32' && unsafe !== 'modified-hooks'
|
||||
? 'Creating file symlinks requires Windows developer mode or elevation' : false,
|
||||
}, () => {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-unsafe-revocation-'));
|
||||
try {
|
||||
const options = { moduleIds: ['hooks-runtime'], target, homeDir: root, projectRoot: root };
|
||||
const enabled = withHookConsent(createManifestInstallPlan(options), 'enabled');
|
||||
applyInstallPlan(enabled);
|
||||
const hooksPath = path.join(enabled.targetRoot, 'hooks.json');
|
||||
const setupPath = path.join(enabled.targetRoot, 'ecc', 'setup.json');
|
||||
const original = fs.readFileSync(hooksPath, 'utf8');
|
||||
if (unsafe === 'modified-hooks') {
|
||||
const hooks = JSON.parse(original);
|
||||
fs.writeFileSync(hooksPath, JSON.stringify({
|
||||
...hooks, 'ecc-guard': { ...hooks['ecc-guard'], Stop: [{ command: 'user-customized-hook' }] },
|
||||
}));
|
||||
} else if (unsafe === 'symlinked-setup') {
|
||||
fs.rmSync(setupPath);
|
||||
fs.symlinkSync(path.join(root, 'outside.json'), setupPath);
|
||||
}
|
||||
const before = fs.readFileSync(hooksPath, 'utf8');
|
||||
assert.throws(() => applyInstallPlan(withHookConsent(createManifestInstallPlan(options), 'declined'), {
|
||||
beforeOperationWrite({ operation }) {
|
||||
if (unsafe === 'swapped-setup' && operation.destinationPath === setupPath) {
|
||||
fs.rmSync(setupPath);
|
||||
fs.symlinkSync(path.join(root, 'outside.json'), setupPath);
|
||||
}
|
||||
},
|
||||
}),
|
||||
/modified Antigravity hooks|symlink|outside the install root/i);
|
||||
if (unsafe !== 'swapped-setup') assert.equal(fs.readFileSync(hooksPath, 'utf8'), before);
|
||||
assert.equal(fs.existsSync(path.join(root, 'outside.json')), false);
|
||||
assert.equal(JSON.parse(fs.readFileSync(enabled.installStatePath, 'utf8')).request.hookConsent, 'enabled');
|
||||
} finally {
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
test(`${target} fresh declined installation creates no hook runtime`, () => {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-fresh-declined-'));
|
||||
try {
|
||||
const plan = withHookConsent(createManifestInstallPlan({ moduleIds: ['hooks-runtime'], target, homeDir: root, projectRoot: root }), 'declined');
|
||||
applyInstallPlan(plan);
|
||||
assert.equal(fs.existsSync(path.join(plan.targetRoot, 'hooks.json')), false);
|
||||
assert.equal(fs.existsSync(path.join(plan.targetRoot, 'ecc', 'setup.json')), false);
|
||||
assert.equal(fs.existsSync(path.join(plan.targetRoot, 'scripts', 'hooks')), false);
|
||||
} finally {
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test(`${target} failed deactivation does not record declined consent`, () => {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-decline-failure-'));
|
||||
try {
|
||||
const options = { moduleIds: ['hooks-runtime'], target, homeDir: root, projectRoot: root };
|
||||
const enabled = withHookConsent(createManifestInstallPlan(options), 'enabled');
|
||||
applyInstallPlan(enabled);
|
||||
const declined = withHookConsent(createManifestInstallPlan(options), 'declined');
|
||||
assert.throws(() => applyInstallPlan(declined, {
|
||||
beforeOperationWrite({ operation }) {
|
||||
if (operation.destinationPath === path.join(enabled.targetRoot, 'ecc', 'setup.json')) {
|
||||
throw new Error('injected setup write failure');
|
||||
}
|
||||
},
|
||||
}), /injected setup write failure/);
|
||||
assert.equal(readInstallState(enabled.installStatePath).request.hookConsent, 'enabled');
|
||||
applyInstallPlan(declined);
|
||||
assert.equal(readInstallState(enabled.installStatePath).request.hookConsent, 'declined');
|
||||
} finally {
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
'use strict';
|
||||
|
||||
const assert = require('assert');
|
||||
const fs = require('fs');
|
||||
const os = require('os');
|
||||
const path = require('path');
|
||||
|
||||
const { createManifestInstallPlan } = require('../../scripts/lib/install/plan');
|
||||
const { applyInstallPlan } = require('../../scripts/lib/install/apply');
|
||||
const { withHookConsent } = require('../../scripts/lib/install/hook-consent');
|
||||
const { buildDoctorReport, repairInstalledStates, uninstallInstalledStates } = require('../../scripts/lib/install-lifecycle');
|
||||
|
||||
const repoRoot = path.join(__dirname, '..', '..');
|
||||
const fixtureRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'antigravity-lifecycle-'));
|
||||
const homeDir = path.join(fixtureRoot, 'home');
|
||||
const projectRoot = path.join(fixtureRoot, 'project');
|
||||
|
||||
try {
|
||||
fs.mkdirSync(homeDir);
|
||||
fs.mkdirSync(projectRoot);
|
||||
const plan = withHookConsent(createManifestInstallPlan({
|
||||
profileId: 'core',
|
||||
target: 'antigravity-home',
|
||||
homeDir,
|
||||
projectRoot,
|
||||
}), 'enabled');
|
||||
const workflowPath = path.join(homeDir, '.gemini', 'config', 'workflows', 'plan.md');
|
||||
applyInstallPlan(plan);
|
||||
|
||||
const original = fs.readFileSync(workflowPath, 'utf8');
|
||||
fs.unlinkSync(workflowPath);
|
||||
|
||||
const doctor = buildDoctorReport({
|
||||
repoRoot,
|
||||
homeDir,
|
||||
projectRoot,
|
||||
targets: ['antigravity-home'],
|
||||
}).results[0];
|
||||
assert.ok(!doctor.issues.some(issue => issue.code === 'unsafe-managed-destination'));
|
||||
|
||||
const repaired = repairInstalledStates({
|
||||
repoRoot,
|
||||
homeDir,
|
||||
projectRoot,
|
||||
targets: ['antigravity-home'],
|
||||
}).results[0];
|
||||
assert.strictEqual(repaired.status, 'repaired', repaired.error);
|
||||
assert.strictEqual(fs.readFileSync(workflowPath, 'utf8'), original);
|
||||
|
||||
const outsidePath = path.join(homeDir, 'outside.md');
|
||||
fs.writeFileSync(outsidePath, 'user content');
|
||||
fs.unlinkSync(workflowPath);
|
||||
fs.symlinkSync(outsidePath, workflowPath);
|
||||
const refused = repairInstalledStates({
|
||||
repoRoot,
|
||||
homeDir,
|
||||
projectRoot,
|
||||
targets: ['antigravity-home'],
|
||||
}).results[0];
|
||||
assert.strictEqual(refused.status, 'error');
|
||||
assert.match(refused.error, /unsafe managed destination|symlink/i);
|
||||
assert.strictEqual(fs.readFileSync(outsidePath, 'utf8'), 'user content');
|
||||
|
||||
const uninstalled = uninstallInstalledStates({
|
||||
homeDir,
|
||||
projectRoot,
|
||||
targets: ['antigravity-home'],
|
||||
}).results[0];
|
||||
assert.strictEqual(uninstalled.status, 'partial', uninstalled.error);
|
||||
assert.ok(uninstalled.retainedPaths.includes(workflowPath));
|
||||
assert.ok(fs.lstatSync(workflowPath).isSymbolicLink());
|
||||
assert.strictEqual(fs.readFileSync(outsidePath, 'utf8'), 'user content');
|
||||
|
||||
const symlinkHome = path.join(fixtureRoot, 'symlink-home');
|
||||
const symlinkProject = path.join(fixtureRoot, 'symlink-project');
|
||||
fs.mkdirSync(symlinkHome);
|
||||
fs.mkdirSync(symlinkProject);
|
||||
const symlinkPlan = withHookConsent(createManifestInstallPlan({
|
||||
profileId: 'core',
|
||||
target: 'antigravity-home',
|
||||
homeDir: symlinkHome,
|
||||
projectRoot: symlinkProject,
|
||||
}), 'enabled');
|
||||
applyInstallPlan(symlinkPlan);
|
||||
const workflowsRoot = path.join(symlinkHome, '.gemini', 'config', 'workflows');
|
||||
const externalRoot = path.join(fixtureRoot, 'external-workflows');
|
||||
fs.renameSync(workflowsRoot, externalRoot);
|
||||
fs.symlinkSync(externalRoot, workflowsRoot, 'dir');
|
||||
const externalWorkflow = path.join(externalRoot, 'plan.md');
|
||||
const externalContent = fs.readFileSync(externalWorkflow, 'utf8');
|
||||
|
||||
assert.throws(() => applyInstallPlan(symlinkPlan), /outside|symlink|trusted/i);
|
||||
// One unsafe target root must not hide doctor results for other targets.
|
||||
applyInstallPlan(withHookConsent(createManifestInstallPlan({
|
||||
profileId: 'core',
|
||||
target: 'antigravity',
|
||||
homeDir: symlinkHome,
|
||||
projectRoot: symlinkProject,
|
||||
}), 'enabled'));
|
||||
const unsafeRootDoctor = buildDoctorReport({
|
||||
repoRoot,
|
||||
homeDir: symlinkHome,
|
||||
projectRoot: symlinkProject,
|
||||
targets: ['antigravity-home', 'antigravity'],
|
||||
}).results;
|
||||
const homeDoctor = unsafeRootDoctor.find(result => result.adapter.target === 'antigravity-home');
|
||||
const projectDoctor = unsafeRootDoctor.find(result => result.adapter.target === 'antigravity');
|
||||
assert.strictEqual(homeDoctor.status, 'error');
|
||||
assert.ok(homeDoctor.issues.some(issue => issue.code === 'unsafe-trusted-root'));
|
||||
assert.ok(projectDoctor, 'project target must still be reported');
|
||||
assert.notStrictEqual(projectDoctor.status, 'error');
|
||||
const rootSymlinkRepair = repairInstalledStates({
|
||||
repoRoot,
|
||||
homeDir: symlinkHome,
|
||||
projectRoot: symlinkProject,
|
||||
targets: ['antigravity-home'],
|
||||
}).results[0];
|
||||
const rootSymlinkUninstall = uninstallInstalledStates({
|
||||
homeDir: symlinkHome,
|
||||
projectRoot: symlinkProject,
|
||||
targets: ['antigravity-home'],
|
||||
}).results[0];
|
||||
assert.strictEqual(rootSymlinkRepair.status, 'error');
|
||||
assert.strictEqual(rootSymlinkUninstall.status, 'error');
|
||||
assert.strictEqual(fs.readFileSync(externalWorkflow, 'utf8'), externalContent);
|
||||
|
||||
const defaultHome = path.join(fixtureRoot, 'default-home');
|
||||
const defaultProject = path.join(fixtureRoot, 'default-project');
|
||||
fs.mkdirSync(defaultHome);
|
||||
fs.mkdirSync(defaultProject);
|
||||
applyInstallPlan(withHookConsent(createManifestInstallPlan({
|
||||
profileId: 'core',
|
||||
target: 'antigravity',
|
||||
homeDir: defaultHome,
|
||||
projectRoot: defaultProject,
|
||||
}), 'enabled'));
|
||||
const previousHome = process.env.HOME;
|
||||
const previousCwd = process.cwd();
|
||||
try {
|
||||
process.env.HOME = defaultHome;
|
||||
process.chdir(defaultProject);
|
||||
const defaultUninstall = uninstallInstalledStates({ targets: ['antigravity'] }).results[0];
|
||||
assert.strictEqual(defaultUninstall.status, 'uninstalled', defaultUninstall.error);
|
||||
assert.ok(!fs.existsSync(path.join(defaultProject, '.agents', 'ecc-install-state.json')));
|
||||
} finally {
|
||||
process.chdir(previousCwd);
|
||||
if (previousHome === undefined) delete process.env.HOME;
|
||||
else process.env.HOME = previousHome;
|
||||
}
|
||||
console.log('Results: Passed: 7, Failed: 0');
|
||||
} finally {
|
||||
fs.rmSync(fixtureRoot, { recursive: true, force: true });
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
'use strict';
|
||||
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
const { test } = require('node:test');
|
||||
const { getInstallTargetAdapter } = require('../../scripts/lib/install-targets/registry');
|
||||
const { createManifestInstallPlan } = require('../../scripts/lib/install/plan');
|
||||
const { applyInstallPlan } = require('../../scripts/lib/install/apply');
|
||||
|
||||
for (const target of ['antigravity', 'antigravity-home']) {
|
||||
test(`${target} persists the selected hook profile in managed setup`, () => {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-hook-profile-'));
|
||||
try {
|
||||
const operations = getInstallTargetAdapter(target).planOperations({
|
||||
repoRoot: root, projectRoot: root, homeDir: root,
|
||||
env: { ECC_HOOK_PROFILE: 'minimal' },
|
||||
modules: [{ id: 'hooks-runtime', paths: ['hooks'] }],
|
||||
});
|
||||
const setup = operations.find(op => op.destinationPath.endsWith(path.join('ecc', 'setup.json')));
|
||||
assert.ok(setup, 'Hook installation must persist its runtime profile');
|
||||
assert.deepEqual(setup.mergePayload, { hooks: { enabled: true, profile: 'minimal' } });
|
||||
} finally {
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test(`${target} does not promote executable repository MCP definitions`, () => {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-mcp-policy-'));
|
||||
try {
|
||||
fs.writeFileSync(path.join(root, '.mcp.json'), JSON.stringify({
|
||||
mcpServers: { untrusted: { command: 'untrusted-command', args: ['run'], env: { SOURCE_ONLY: 'value' } } },
|
||||
}));
|
||||
const operations = getInstallTargetAdapter(target).planOperations({
|
||||
repoRoot: root, projectRoot: root, homeDir: root,
|
||||
modules: [{ id: 'platform-configs', paths: ['.mcp.json'] }],
|
||||
});
|
||||
const config = operations.find(op => path.basename(op.destinationPath) === 'mcp_config.json');
|
||||
assert.deepEqual(Object.keys(config.mergePayload.mcpServers), ['ecc-memory']);
|
||||
} finally {
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
for (const disabled of [false, true]) {
|
||||
test(`${target} preserves user servers and ${disabled ? 'suppresses disabled' : 'adds'} ECC memory`, () => {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-mcp-install-policy-'));
|
||||
const previous = process.env.ECC_DISABLED_MCPS;
|
||||
try {
|
||||
if (disabled) process.env.ECC_DISABLED_MCPS = 'ecc-memory';
|
||||
else delete process.env.ECC_DISABLED_MCPS;
|
||||
const projectRoot = path.join(root, 'project');
|
||||
fs.mkdirSync(projectRoot);
|
||||
const plan = createManifestInstallPlan({
|
||||
moduleIds: ['platform-configs'], target, homeDir: root, projectRoot,
|
||||
});
|
||||
const configPath = path.join(plan.targetRoot, 'mcp_config.json');
|
||||
const userServer = { command: 'user-selected-server', args: ['--user-option'] };
|
||||
fs.mkdirSync(plan.targetRoot, { recursive: true });
|
||||
fs.writeFileSync(configPath, JSON.stringify({ mcpServers: { 'user-server': userServer } }));
|
||||
applyInstallPlan(plan);
|
||||
const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
|
||||
assert.deepEqual(config.mcpServers['user-server'], userServer);
|
||||
assert.equal(Object.hasOwn(config.mcpServers, 'ecc-memory'), !disabled);
|
||||
assert.deepEqual(Object.keys(config.mcpServers).sort(), disabled
|
||||
? ['user-server'] : ['ecc-memory', 'user-server']);
|
||||
} finally {
|
||||
if (previous === undefined) delete process.env.ECC_DISABLED_MCPS;
|
||||
else process.env.ECC_DISABLED_MCPS = previous;
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,610 @@
|
||||
'use strict';
|
||||
|
||||
const assert = require('assert');
|
||||
const fs = require('fs');
|
||||
const os = require('os');
|
||||
const path = require('path');
|
||||
const { spawnSync } = require('child_process');
|
||||
|
||||
const { adaptAntigravityInputToEcc } = require('../../scripts/hooks/antigravity-hook-bridge');
|
||||
const { buildAntigravityHooksConfig } = require('../../scripts/lib/antigravity-hooks');
|
||||
const { buildAntigravityMcpConfig } = require('../../scripts/lib/antigravity-mcp');
|
||||
const { buildAntigravityPluginManifest } = require('../../scripts/lib/antigravity-plugin');
|
||||
const { getInstallTargetAdapter } = require('../../scripts/lib/install-targets/registry');
|
||||
const { resolveInstallPlan } = require('../../scripts/lib/install-manifests');
|
||||
const { resolveEccRoot } = require('../../scripts/lib/resolve-ecc-root');
|
||||
|
||||
let passed = 0;
|
||||
let failed = 0;
|
||||
|
||||
function test(name, fn) {
|
||||
try {
|
||||
fn();
|
||||
console.log(` ✓ ${name}`);
|
||||
passed += 1;
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.log(` ✗ ${name}`);
|
||||
console.log(` Error: ${error.message}`);
|
||||
failed += 1;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function createTempDir(prefix) {
|
||||
return fs.mkdtempSync(path.join(os.tmpdir(), prefix));
|
||||
}
|
||||
|
||||
function cleanup(dirPath) {
|
||||
fs.rmSync(dirPath, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
function runTests() {
|
||||
console.log('\n=== Testing Antigravity Tier 1 Parity ===\n');
|
||||
|
||||
test('adaptAntigravityInputToEcc normalizes run_command tool calls', () => {
|
||||
const rawInput = {
|
||||
conversationId: 'conv-1234',
|
||||
workspacePaths: ['/workspace/app'],
|
||||
stepIdx: 5,
|
||||
toolCall: {
|
||||
name: 'run_command',
|
||||
args: {
|
||||
CommandLine: 'npm test',
|
||||
Cwd: '/workspace/app',
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const adapted = adaptAntigravityInputToEcc(rawInput);
|
||||
assert.strictEqual(adapted.tool_name, 'Bash');
|
||||
assert.strictEqual(adapted.tool_input.command, 'npm test');
|
||||
assert.strictEqual(adapted.tool_input.CommandLine, 'npm test');
|
||||
assert.strictEqual(adapted.conversation_id, 'conv-1234');
|
||||
assert.deepStrictEqual(adapted.workspace_paths, ['/workspace/app']);
|
||||
});
|
||||
|
||||
test('adaptAntigravityInputToEcc normalizes write_to_file and replace_file_content tool calls', () => {
|
||||
const writeInput = {
|
||||
toolCall: {
|
||||
name: 'write_to_file',
|
||||
args: {
|
||||
TargetFile: '/workspace/app/src/index.js',
|
||||
CodeContent: 'console.log("hello");',
|
||||
},
|
||||
},
|
||||
};
|
||||
const adaptedWrite = adaptAntigravityInputToEcc(writeInput);
|
||||
assert.strictEqual(adaptedWrite.tool_name, 'Write');
|
||||
assert.strictEqual(adaptedWrite.tool_input.file_path, '/workspace/app/src/index.js');
|
||||
|
||||
const replaceInput = {
|
||||
toolCall: {
|
||||
name: 'replace_file_content',
|
||||
args: {
|
||||
TargetFile: '/workspace/app/src/index.js',
|
||||
TargetContent: 'hello',
|
||||
ReplacementContent: 'world',
|
||||
},
|
||||
},
|
||||
};
|
||||
const adaptedReplace = adaptAntigravityInputToEcc(replaceInput);
|
||||
assert.strictEqual(adaptedReplace.tool_name, 'Edit');
|
||||
assert.strictEqual(adaptedReplace.tool_input.file_path, '/workspace/app/src/index.js');
|
||||
});
|
||||
|
||||
test('adaptAntigravityInputToEcc handles malformed or empty payloads safely', () => {
|
||||
const emptyAdapted = adaptAntigravityInputToEcc(null);
|
||||
assert.strictEqual(emptyAdapted.tool_name, '');
|
||||
assert.deepStrictEqual(emptyAdapted.tool_input, {});
|
||||
|
||||
const emptyObjAdapted = adaptAntigravityInputToEcc({});
|
||||
assert.strictEqual(emptyObjAdapted.tool_name, '');
|
||||
assert.deepStrictEqual(emptyObjAdapted.tool_input, { command: '', file_path: '' });
|
||||
});
|
||||
|
||||
test('buildAntigravityHooksConfig generates valid Antigravity hooks specification', () => {
|
||||
const config = buildAntigravityHooksConfig({ profile: 'standard', bridgeScript: path.resolve('scripts/hooks/antigravity-hook-bridge.js') });
|
||||
assert.ok(config['ecc-guard'], 'Should have ecc-guard hook entry');
|
||||
const guard = config['ecc-guard'];
|
||||
|
||||
assert.ok(Array.isArray(guard.PreToolUse), 'PreToolUse should be an array');
|
||||
assert.ok(Array.isArray(guard.Stop), 'Stop should be an array');
|
||||
assert.ok(guard.PostToolUse.some(entry => entry.matcher.includes('multi_replace_file_content') && entry.hooks.some(hook => hook.command.includes('post:edit:accumulator'))));
|
||||
assert.ok(guard.Stop.find(hook => hook.command.includes('stop:format-typecheck')).timeout >= 270);
|
||||
|
||||
const commandMatcher = guard.PreToolUse.find(entry => entry.matcher === 'run_command');
|
||||
assert.ok(commandMatcher, 'Should have run_command matcher in PreToolUse');
|
||||
assert.ok(
|
||||
commandMatcher.hooks.some(h => h.command.includes('pre:bash:dispatcher')),
|
||||
'Should invoke pre:bash:dispatcher on run_command'
|
||||
);
|
||||
|
||||
const editMatcher = guard.PreToolUse.find(entry => entry.matcher === 'write_to_file|replace_file_content|multi_replace_file_content');
|
||||
assert.ok(editMatcher, 'Should have write_to_file|replace_file_content matcher');
|
||||
assert.ok(
|
||||
editMatcher.hooks.some(h => h.command.includes('pre:edit-write:gateguard-fact-force')),
|
||||
'Should invoke GateGuard on write operations'
|
||||
);
|
||||
});
|
||||
|
||||
test('buildAntigravityMcpConfig generates valid stdio MCP configuration for ecc-memory', () => {
|
||||
const config = buildAntigravityMcpConfig({ memoryScript: path.resolve('scripts/memory-mcp.mjs') });
|
||||
assert.ok(config.mcpServers, 'Should declare mcpServers');
|
||||
assert.ok(config.mcpServers['ecc-memory'], 'Should declare ecc-memory server');
|
||||
const memoryServer = config.mcpServers['ecc-memory'];
|
||||
assert.strictEqual(memoryServer.command, 'node');
|
||||
assert.strictEqual(memoryServer.env.ECC_MEMORY_HARNESS, 'antigravity');
|
||||
});
|
||||
|
||||
test('buildAntigravityPluginManifest generates valid Antigravity plugin manifest', () => {
|
||||
const manifest = buildAntigravityPluginManifest({ version: '2.2.2' });
|
||||
assert.strictEqual(manifest.name, 'ecc');
|
||||
assert.strictEqual(manifest.version, '2.2.2');
|
||||
assert.ok(manifest.description.includes('Antigravity'));
|
||||
});
|
||||
|
||||
test('generators reject missing, relative, and malformed executable paths', () => {
|
||||
for (const value of [undefined, '', 'relative/script.js', 7, '/tmp/bad\0path']) {
|
||||
assert.throws(() => buildAntigravityHooksConfig({ bridgeScript: value }), /absolute path/);
|
||||
assert.throws(() => buildAntigravityMcpConfig({ memoryScript: value }), /absolute path/);
|
||||
}
|
||||
assert.strictEqual(buildAntigravityPluginManifest().version, require('../../package.json').version);
|
||||
});
|
||||
|
||||
test('hook commands preserve shell metacharacters in the installed path', () => {
|
||||
if (process.platform === 'win32') return;
|
||||
const dir = createTempDir("ecc space ' $HOME `echo x` ");
|
||||
try {
|
||||
const script = path.join(dir, 'bridge.js');
|
||||
fs.writeFileSync(script, 'process.stdout.write(JSON.stringify(process.argv.slice(2)))');
|
||||
const config = buildAntigravityHooksConfig({ bridgeScript: script });
|
||||
const command = config['ecc-guard'].PreToolUse[0].hooks[0].command;
|
||||
const run = spawnSync(command, { shell: true, encoding: 'utf8' });
|
||||
assert.strictEqual(run.status, 0, run.stderr);
|
||||
assert.deepStrictEqual(JSON.parse(run.stdout), ['--mode', 'pre-tool-use', '--hook', 'pre:bash:dispatcher']);
|
||||
} finally {
|
||||
cleanup(dir);
|
||||
}
|
||||
});
|
||||
|
||||
for (const target of ['antigravity', 'antigravity-home']) {
|
||||
test(`${target} installed memory server starts outside the source checkout`, () => {
|
||||
const root = createTempDir('ecc-memory-install-');
|
||||
try {
|
||||
const projectRoot = path.join(root, 'project');
|
||||
fs.mkdirSync(projectRoot);
|
||||
fs.writeFileSync(path.join(projectRoot, 'package.json'), '{"type":"module"}');
|
||||
const { createManifestInstallPlan } = require('../../scripts/lib/install/plan');
|
||||
const { applyInstallPlan } = require('../../scripts/lib/install/apply');
|
||||
const plan = createManifestInstallPlan({ moduleIds: ['platform-configs'], target, homeDir: root, projectRoot });
|
||||
applyInstallPlan(plan);
|
||||
const config = JSON.parse(fs.readFileSync(path.join(plan.targetRoot, 'mcp_config.json'), 'utf8'));
|
||||
const server = config.mcpServers['ecc-memory'];
|
||||
assert.strictEqual(server.args[0], path.join(plan.targetRoot, 'scripts', 'memory-mcp.mjs'));
|
||||
const run = spawnSync(process.execPath, server.args, {
|
||||
cwd: root,
|
||||
env: { ...process.env, ...server.env, NODE_PATH: '' },
|
||||
input: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2025-11-25', capabilities: {}, clientInfo: { name: 'test', version: '1' } } }) + '\n',
|
||||
encoding: 'utf8',
|
||||
timeout: 10000,
|
||||
});
|
||||
assert.strictEqual(run.status, 0, run.stderr);
|
||||
assert.strictEqual(JSON.parse(run.stdout.trim()).id, 1);
|
||||
} finally {
|
||||
cleanup(root);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
test('project hooks install and run with explicit consent in an ESM project', () => {
|
||||
const root = createTempDir('ecc-project-hooks-');
|
||||
try {
|
||||
fs.writeFileSync(path.join(root, 'package.json'), '{"type":"module"}');
|
||||
const { createManifestInstallPlan } = require('../../scripts/lib/install/plan');
|
||||
const { applyInstallPlan } = require('../../scripts/lib/install/apply');
|
||||
const { withHookConsent } = require('../../scripts/lib/install/hook-consent');
|
||||
const plan = withHookConsent(createManifestInstallPlan({ moduleIds: ['hooks-runtime'], target: 'antigravity', projectRoot: root }), 'enabled');
|
||||
applyInstallPlan(plan);
|
||||
const config = JSON.parse(fs.readFileSync(path.join(plan.targetRoot, 'hooks.json'), 'utf8'));
|
||||
const run = spawnSync(config['ecc-guard'].PreToolUse[0].hooks[0].command, {
|
||||
cwd: root,
|
||||
shell: true,
|
||||
env: { ...process.env, GATEGUARD_BASH_ROUTINE_DISABLED: '1' },
|
||||
input: JSON.stringify({ workspacePaths: [root], toolCall: { name: 'run_command', args: { CommandLine: 'pwd' } } }),
|
||||
encoding: 'utf8',
|
||||
timeout: 10000,
|
||||
});
|
||||
assert.strictEqual(run.status, 0, run.stderr);
|
||||
assert.strictEqual(JSON.parse(run.stdout).decision, 'allow', run.stdout);
|
||||
} finally {
|
||||
cleanup(root);
|
||||
}
|
||||
});
|
||||
|
||||
test('memory runtime installs from npm-hoisted dependencies', () => {
|
||||
const root = createTempDir('ecc-hoisted-memory-');
|
||||
try {
|
||||
const sourceRoot = path.join(root, 'node_modules', 'ecc-universal');
|
||||
const repoRoot = path.resolve(__dirname, '../..');
|
||||
for (const relative of ['package.json', 'scripts/memory-mcp.mjs', 'scripts/lib/missing-dependency.js', 'scripts/lib/memory-vault.js', 'scripts/lib/memory-vault-format.js', 'scripts/lib/path-safety.js']) {
|
||||
const destination = path.join(sourceRoot, relative);
|
||||
fs.mkdirSync(path.dirname(destination), { recursive: true });
|
||||
fs.copyFileSync(path.join(repoRoot, relative), destination);
|
||||
}
|
||||
const ajvManifest = require('ajv/package.json');
|
||||
for (const name of ['ajv', ...Object.keys(ajvManifest.dependencies)]) {
|
||||
fs.cpSync(path.dirname(require.resolve(`${name}/package.json`)), path.join(root, 'node_modules', name), { recursive: true });
|
||||
}
|
||||
fs.cpSync(path.join(repoRoot, 'manifests'), path.join(sourceRoot, 'manifests'), { recursive: true });
|
||||
const projectRoot = path.join(root, 'app');
|
||||
const { createManifestInstallPlan } = require('../../scripts/lib/install/plan');
|
||||
const { applyInstallPlan } = require('../../scripts/lib/install/apply');
|
||||
const plan = createManifestInstallPlan({ sourceRoot, moduleIds: ['platform-configs'], target: 'antigravity', projectRoot });
|
||||
applyInstallPlan(plan);
|
||||
|
||||
const state = JSON.parse(fs.readFileSync(plan.installStatePath, 'utf8'));
|
||||
const dependencySources = state.operations
|
||||
.map(operation => operation.sourceRelativePath || '')
|
||||
.filter(source => source.split(/[/\\]+/)[0] === 'node_modules');
|
||||
assert.ok(dependencySources.length > 0);
|
||||
assert.ok(state.operations.every(operation => !String(operation.sourceRelativePath || '').split(/[/\\]+/).includes('..')));
|
||||
|
||||
const { buildDoctorReport, repairInstalledStates } = require('../../scripts/lib/install-lifecycle');
|
||||
const lifecycleOptions = { repoRoot: sourceRoot, homeDir: path.join(root, 'home'), projectRoot, targets: ['antigravity'] };
|
||||
const doctor = buildDoctorReport(lifecycleOptions).results[0];
|
||||
assert.ok(!doctor.issues.some(issue => issue.code === 'unsafe-repair-source'), JSON.stringify(doctor.issues));
|
||||
const installedAjv = path.join(plan.targetRoot, 'node_modules', 'ajv', 'package.json');
|
||||
const originalAjv = fs.readFileSync(installedAjv, 'utf8');
|
||||
fs.unlinkSync(installedAjv);
|
||||
const repaired = repairInstalledStates(lifecycleOptions).results[0];
|
||||
assert.strictEqual(repaired.status, 'repaired', repaired.error);
|
||||
assert.strictEqual(fs.readFileSync(installedAjv, 'utf8'), originalAjv);
|
||||
|
||||
fs.rmSync(path.join(root, 'node_modules'), { recursive: true });
|
||||
const run = spawnSync(process.execPath, [path.join(plan.targetRoot, 'scripts/memory-mcp.mjs')], {
|
||||
cwd: root,
|
||||
env: { ...process.env, ECC_MEMORY_HARNESS: 'antigravity', NODE_PATH: '' },
|
||||
input: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2025-11-25', capabilities: {}, clientInfo: { name: 'test', version: '1' } } }) + '\n',
|
||||
encoding: 'utf8',
|
||||
timeout: 10000,
|
||||
});
|
||||
assert.strictEqual(run.status, 0, run.stderr);
|
||||
assert.strictEqual(JSON.parse(run.stdout.trim()).id, 1);
|
||||
} finally {
|
||||
cleanup(root);
|
||||
}
|
||||
});
|
||||
|
||||
test('missing memory dependencies give installation instructions', () => {
|
||||
const root = createTempDir('ecc-missing-memory-dependency-');
|
||||
try {
|
||||
const ajvRoot = path.join(root, 'node_modules', 'ajv');
|
||||
fs.mkdirSync(ajvRoot, { recursive: true });
|
||||
fs.writeFileSync(path.join(ajvRoot, 'package.json'), JSON.stringify({ dependencies: { 'ecc-test-nonexistent-dependency': '1.0.0' } }));
|
||||
const { planAntigravityMemoryRuntime } = require('../../scripts/lib/antigravity-mcp');
|
||||
assert.throws(() => planAntigravityMemoryRuntime('platform-configs', root, path.join(root, 'target')), /Run npm install/);
|
||||
} finally {
|
||||
cleanup(root);
|
||||
}
|
||||
});
|
||||
|
||||
test('Windows hook commands quote spaces and reject shell expansion characters', () => {
|
||||
const descriptor = Object.getOwnPropertyDescriptor(process, 'platform');
|
||||
try {
|
||||
Object.defineProperty(process, 'platform', { value: 'win32' });
|
||||
const bridgeScript = path.resolve('folder with spaces/bridge.js');
|
||||
const config = buildAntigravityHooksConfig({ bridgeScript });
|
||||
assert.ok(config['ecc-guard'].PreToolUse[0].hooks[0].command.startsWith(`node "${bridgeScript}" `));
|
||||
for (const character of ['"', '%', '!', '$', '`', '\r', '\n']) {
|
||||
assert.throws(() => buildAntigravityHooksConfig({ bridgeScript: bridgeScript + character }), /shell/);
|
||||
}
|
||||
} finally {
|
||||
Object.defineProperty(process, 'platform', descriptor);
|
||||
}
|
||||
});
|
||||
|
||||
test('antigravity-home adapter resolves root to ~/.gemini/config/plugins/ecc', () => {
|
||||
const homeDir = '/home/testuser';
|
||||
const adapter = getInstallTargetAdapter('antigravity-home');
|
||||
assert.strictEqual(adapter.id, 'antigravity-home');
|
||||
assert.strictEqual(adapter.kind, 'home');
|
||||
assert.strictEqual(
|
||||
adapter.resolveRoot({ homeDir }),
|
||||
path.join(homeDir, '.gemini', 'config', 'plugins', 'ecc')
|
||||
);
|
||||
});
|
||||
|
||||
test('antigravity-home plans complete native plugin structure for core profile', () => {
|
||||
const homeDir = createTempDir('antigravity-home-test-');
|
||||
const projectRoot = createTempDir('antigravity-proj-test-');
|
||||
|
||||
try {
|
||||
const plan = resolveInstallPlan({
|
||||
profileId: 'core',
|
||||
target: 'antigravity-home',
|
||||
homeDir,
|
||||
projectRoot,
|
||||
});
|
||||
|
||||
assert.strictEqual(plan.targetAdapterId, 'antigravity-home');
|
||||
assert.strictEqual(
|
||||
plan.targetRoot,
|
||||
path.join(homeDir, '.gemini', 'config', 'plugins', 'ecc')
|
||||
);
|
||||
|
||||
const targetRoot = plan.targetRoot;
|
||||
|
||||
// Check plugin.json
|
||||
assert.ok(
|
||||
plan.operations.some(op => (
|
||||
op.destinationPath === path.join(targetRoot, 'plugin.json')
|
||||
&& op.kind === 'merge-json'
|
||||
)),
|
||||
'Should plan plugin.json merge'
|
||||
);
|
||||
|
||||
// Check mcp_config.json
|
||||
assert.ok(
|
||||
plan.operations.some(op => (
|
||||
op.destinationPath === path.join(targetRoot, 'mcp_config.json')
|
||||
&& op.kind === 'merge-json'
|
||||
)),
|
||||
'Should plan mcp_config.json merge'
|
||||
);
|
||||
|
||||
// Check hooks.json
|
||||
assert.ok(
|
||||
plan.operations.some(op => (
|
||||
op.destinationPath === path.join(targetRoot, 'hooks.json')
|
||||
&& op.kind === 'merge-json'
|
||||
)),
|
||||
'Should plan hooks.json merge'
|
||||
);
|
||||
|
||||
// Check rules
|
||||
assert.ok(
|
||||
plan.operations.some(op => (
|
||||
op.destinationPath.startsWith(path.join(targetRoot, 'rules'))
|
||||
)),
|
||||
'Should plan rules into plugin rules directory'
|
||||
);
|
||||
|
||||
// Check workflows
|
||||
assert.ok(
|
||||
plan.operations.some(op => (
|
||||
op.destinationPath.startsWith(path.join(homeDir, '.gemini', 'config', 'workflows'))
|
||||
)),
|
||||
'Should plan workflows'
|
||||
);
|
||||
} finally {
|
||||
cleanup(homeDir);
|
||||
cleanup(projectRoot);
|
||||
}
|
||||
});
|
||||
|
||||
test('antigravity-hook-bridge handles allow decision for safe command', () => {
|
||||
const bridgePath = path.join(__dirname, '..', '..', 'scripts', 'hooks', 'antigravity-hook-bridge.js');
|
||||
const input = JSON.stringify({
|
||||
conversationId: 'test-conv',
|
||||
workspacePaths: ['/tmp'],
|
||||
toolCall: {
|
||||
name: 'run_command',
|
||||
args: {
|
||||
CommandLine: 'pwd',
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const run = spawnSync(process.execPath, [bridgePath, '--mode', 'pre-tool-use', '--hook', 'pre:bash:dispatcher'], {
|
||||
input,
|
||||
encoding: 'utf8',
|
||||
env: { ...process.env, GATEGUARD_BASH_ROUTINE_DISABLED: '1' },
|
||||
});
|
||||
|
||||
assert.strictEqual(run.status, 0);
|
||||
const output = JSON.parse(run.stdout);
|
||||
assert.strictEqual(output.decision, 'allow');
|
||||
});
|
||||
|
||||
test('antigravity-hook-bridge returns deny for blocked git push --no-verify', () => {
|
||||
const bridgePath = path.join(__dirname, '..', '..', 'scripts', 'hooks', 'antigravity-hook-bridge.js');
|
||||
const input = JSON.stringify({
|
||||
conversationId: 'test-conv',
|
||||
workspacePaths: ['/tmp'],
|
||||
toolCall: {
|
||||
name: 'run_command',
|
||||
args: {
|
||||
CommandLine: 'git push origin main --no-verify',
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const run = spawnSync(process.execPath, [bridgePath, '--mode', 'pre-tool-use', '--hook', 'pre:bash:dispatcher'], {
|
||||
input,
|
||||
encoding: 'utf8',
|
||||
});
|
||||
|
||||
assert.strictEqual(run.status, 0);
|
||||
const output = JSON.parse(run.stdout);
|
||||
assert.strictEqual(output.decision, 'deny');
|
||||
assert.match(output.reason, /no-verify/i);
|
||||
});
|
||||
|
||||
test('antigravity-hook-bridge returns deny for GateGuard write_to_file on first touch', () => {
|
||||
const bridgePath = path.join(__dirname, '..', '..', 'scripts', 'hooks', 'antigravity-hook-bridge.js');
|
||||
const root = createTempDir('ecc-bridge-deny-');
|
||||
try {
|
||||
const targetFile = path.join(root, 'index.js');
|
||||
const input = JSON.stringify({
|
||||
conversationId: path.basename(root),
|
||||
workspacePaths: [root],
|
||||
toolCall: {
|
||||
name: 'write_to_file',
|
||||
args: {
|
||||
TargetFile: targetFile,
|
||||
CodeContent: 'console.log("hello");',
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const run = spawnSync(process.execPath, [bridgePath, '--mode', 'pre-tool-use', '--hook', 'pre:edit-write:gateguard-fact-force'], {
|
||||
input,
|
||||
encoding: 'utf8',
|
||||
env: {
|
||||
...process.env,
|
||||
GATEGUARD_STATE_DIR: root,
|
||||
GATEGUARD_DISABLED: '0',
|
||||
GATEGUARD_EXEMPT_PATHS: '',
|
||||
GATEGUARD_EXEMPT_GLOBS: '',
|
||||
},
|
||||
});
|
||||
|
||||
assert.strictEqual(run.status, 0);
|
||||
const output = JSON.parse(run.stdout);
|
||||
assert.strictEqual(output.decision, 'deny');
|
||||
assert.ok(output.reason);
|
||||
} finally {
|
||||
cleanup(root);
|
||||
}
|
||||
});
|
||||
|
||||
test('antigravity-hook-bridge returns deny for oversized input in pre-tool-use', () => {
|
||||
const bridgePath = path.join(__dirname, '..', '..', 'scripts', 'hooks', 'antigravity-hook-bridge.js');
|
||||
const input = JSON.stringify({
|
||||
conversationId: 'test-oversized',
|
||||
workspacePaths: ['/tmp'],
|
||||
toolCall: {
|
||||
name: 'run_command',
|
||||
args: {
|
||||
CommandLine: 'echo ' + 'x'.repeat(100),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const run = spawnSync(process.execPath, [bridgePath, '--mode', 'pre-tool-use', '--hook', 'pre:bash:dispatcher'], {
|
||||
input,
|
||||
encoding: 'utf8',
|
||||
env: {
|
||||
...process.env,
|
||||
ECC_HOOK_INPUT_MAX_BYTES: '10',
|
||||
},
|
||||
});
|
||||
|
||||
assert.strictEqual(run.status, 0);
|
||||
const output = JSON.parse(run.stdout);
|
||||
assert.strictEqual(output.decision, 'deny');
|
||||
assert.match(output.reason, /completely|input/i);
|
||||
});
|
||||
|
||||
test('antigravity-hook-bridge safely ignores non-JSON hook stdout and allows safe tool call', () => {
|
||||
const bridgePath = path.join(__dirname, '..', '..', 'scripts', 'hooks', 'antigravity-hook-bridge.js');
|
||||
const input = JSON.stringify({
|
||||
conversationId: 'test-conv',
|
||||
workspacePaths: ['/tmp'],
|
||||
toolCall: {
|
||||
name: 'run_command',
|
||||
args: {
|
||||
CommandLine: 'echo safe',
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const run = spawnSync(process.execPath, [bridgePath, '--mode', 'pre-tool-use', '--hook', 'pre:write:doc-file-warning'], {
|
||||
input,
|
||||
encoding: 'utf8',
|
||||
});
|
||||
|
||||
assert.strictEqual(run.status, 0);
|
||||
const output = JSON.parse(run.stdout);
|
||||
assert.strictEqual(output.decision, 'allow');
|
||||
});
|
||||
|
||||
test('antigravity-project plans mcp_config.json when platform configs are selected', () => {
|
||||
const projectRoot = createTempDir('antigravity-proj-mcp-');
|
||||
try {
|
||||
const plan = resolveInstallPlan({
|
||||
moduleIds: ['platform-configs'],
|
||||
target: 'antigravity',
|
||||
projectRoot,
|
||||
});
|
||||
|
||||
assert.strictEqual(plan.targetAdapterId, 'antigravity-project');
|
||||
const targetRoot = path.join(projectRoot, '.agents');
|
||||
|
||||
assert.ok(
|
||||
plan.operations.some(op => op.destinationPath === path.join(targetRoot, 'mcp_config.json') && op.kind === 'merge-json'),
|
||||
'Should plan mcp_config.json in project .agents'
|
||||
);
|
||||
} finally {
|
||||
cleanup(projectRoot);
|
||||
}
|
||||
});
|
||||
|
||||
test('antigravity-home end-to-end install applies complete plugin directory and install state', () => {
|
||||
const homeDir = createTempDir('antigravity-home-e2e-');
|
||||
const projectDir = createTempDir('antigravity-proj-e2e-');
|
||||
|
||||
try {
|
||||
const { createManifestInstallPlan } = require('../../scripts/lib/install/plan');
|
||||
const { applyInstallPlan } = require('../../scripts/lib/install/apply');
|
||||
const { withHookConsent } = require('../../scripts/lib/install/hook-consent');
|
||||
const plan = withHookConsent(createManifestInstallPlan({
|
||||
profileId: 'core',
|
||||
target: 'antigravity-home',
|
||||
homeDir,
|
||||
projectRoot: projectDir,
|
||||
}), 'enabled');
|
||||
|
||||
applyInstallPlan(plan);
|
||||
const pluginDir = path.join(homeDir, '.gemini', 'config', 'plugins', 'ecc');
|
||||
|
||||
assert.ok(fs.existsSync(path.join(pluginDir, 'plugin.json')), 'plugin.json should exist');
|
||||
assert.ok(fs.existsSync(path.join(pluginDir, 'hooks.json')), 'hooks.json should exist');
|
||||
assert.ok(fs.existsSync(path.join(pluginDir, 'mcp_config.json')), 'mcp_config.json should exist');
|
||||
assert.ok(fs.existsSync(path.join(pluginDir, 'ecc-install-state.json')), 'install-state should exist');
|
||||
assert.ok(fs.existsSync(path.join(pluginDir, 'rules', 'common-coding-style.md')), 'rules should exist');
|
||||
assert.ok(fs.existsSync(path.join(pluginDir, 'skills', 'tdd-workflow', 'SKILL.md')), 'skills should exist');
|
||||
assert.ok(fs.existsSync(path.join(pluginDir, 'scripts', 'hooks', 'antigravity-hook-bridge.js')), 'hook bridge should exist');
|
||||
assert.ok(fs.existsSync(path.join(homeDir, '.gemini', 'config', 'workflows', 'plan.md')), 'workflow plan.md should exist in global workflows dir');
|
||||
|
||||
const pluginJson = JSON.parse(fs.readFileSync(path.join(pluginDir, 'plugin.json'), 'utf8'));
|
||||
assert.strictEqual(pluginJson.name, 'ecc');
|
||||
|
||||
const hooksJson = JSON.parse(fs.readFileSync(path.join(pluginDir, 'hooks.json'), 'utf8'));
|
||||
assert.ok(hooksJson['ecc-guard']);
|
||||
assert.ok(Array.isArray(hooksJson['ecc-guard'].PreToolUse));
|
||||
assert.ok(Array.isArray(hooksJson['ecc-guard'].Stop));
|
||||
|
||||
const mcpConfig = JSON.parse(fs.readFileSync(path.join(pluginDir, 'mcp_config.json'), 'utf8'));
|
||||
assert.ok(mcpConfig.mcpServers['ecc-memory']);
|
||||
const hookCommand = hooksJson['ecc-guard'].PreToolUse[0].hooks[0].command;
|
||||
assert.ok(hookCommand.includes(path.join(pluginDir, 'scripts', 'hooks', 'antigravity-hook-bridge.js')));
|
||||
} finally {
|
||||
cleanup(homeDir);
|
||||
cleanup(projectDir);
|
||||
}
|
||||
});
|
||||
|
||||
test('resolveEccRoot recognizes Antigravity global plugin install', () => {
|
||||
const tempHome = createTempDir('ecc-root-test-');
|
||||
try {
|
||||
const pluginDir = path.join(tempHome, '.gemini', 'config', 'plugins', 'ecc');
|
||||
fs.mkdirSync(path.join(pluginDir, 'scripts', 'lib'), { recursive: true });
|
||||
fs.mkdirSync(path.join(pluginDir, 'skills', 'continuous-learning-v2'), { recursive: true });
|
||||
fs.writeFileSync(path.join(pluginDir, 'scripts', 'lib', 'utils.js'), '// utils');
|
||||
|
||||
const resolved = resolveEccRoot({ homeDir: tempHome });
|
||||
assert.strictEqual(resolved, pluginDir);
|
||||
} finally {
|
||||
cleanup(tempHome);
|
||||
}
|
||||
});
|
||||
|
||||
console.log(`\nResults: Passed: ${passed}, Failed: ${failed}\n`);
|
||||
if (failed > 0) {
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
runTests();
|
||||
@@ -0,0 +1,94 @@
|
||||
/**
|
||||
* Tests for scripts/lib/dev-command.js, the dev-server classifier shared by
|
||||
* pre-bash-dev-server-block.js and auto-tmux-dev.js.
|
||||
*/
|
||||
|
||||
const assert = require('assert');
|
||||
const { isDevServerCommand, isDevServerSegment } = require('../../scripts/lib/dev-command');
|
||||
|
||||
let passed = 0;
|
||||
let failed = 0;
|
||||
|
||||
function test(name, fn) {
|
||||
try {
|
||||
fn();
|
||||
console.log(` ✓ ${name}`);
|
||||
passed++;
|
||||
} catch (error) {
|
||||
console.log(` ✗ ${name}`);
|
||||
console.log(` Error: ${error.message}`);
|
||||
failed++;
|
||||
}
|
||||
}
|
||||
|
||||
console.log('\n=== Testing dev-command.js ===\n');
|
||||
|
||||
// Each row was compared with real npm 11 / Yarn 4 runs of a scratch project
|
||||
// whose `dev` script writes a marker: blocked exactly when the dev script ran.
|
||||
for (const [command, expected] of [
|
||||
['npm run dev', true],
|
||||
['npm run "dev"', true],
|
||||
['npm run de"v"', true],
|
||||
['npm -d run dev', true],
|
||||
['npm -s run dev', true],
|
||||
['npm --userconfig /dev/null run dev', true],
|
||||
['npm --prefix app run dev', true],
|
||||
['npm -w app run dev', true],
|
||||
['npm run-script dev', true],
|
||||
['npm run dev:ssr', true],
|
||||
['npm run build dev', false],
|
||||
['npm run run dev', false],
|
||||
['npm run dev-setup', false],
|
||||
['npm test -- --grep dev', false],
|
||||
['npm run build -- dev', false],
|
||||
['yarn dev', true],
|
||||
['yarn "dev"', true],
|
||||
['yarn --cwd app dev', true],
|
||||
['yarn run build dev', false],
|
||||
['yarn build dev', false],
|
||||
['yarn test -- dev', false],
|
||||
['yarn --cwd app run build', false]
|
||||
]) {
|
||||
test(`${expected ? 'detects' : 'ignores'}: ${command}`, () => {
|
||||
assert.strictEqual(isDevServerCommand(command), expected);
|
||||
});
|
||||
}
|
||||
|
||||
// Grammar-derived rows for managers not installed in the verification run.
|
||||
for (const [command, expected] of [
|
||||
['pnpm -d dev', true],
|
||||
['pnpm -w dev', true],
|
||||
['pnpm -C app dev', true],
|
||||
['pnpm --filter dev run build', false],
|
||||
['bun -d K:V dev', true],
|
||||
['bun -c dev', true],
|
||||
['bun -c bunfig.toml dev', true],
|
||||
['bun -d dev:1 build', false]
|
||||
]) {
|
||||
test(`${expected ? 'detects' : 'ignores'} by documented grammar: ${command}`, () => {
|
||||
assert.strictEqual(isDevServerCommand(command), expected);
|
||||
});
|
||||
}
|
||||
|
||||
test('tmux pane launches are exempt, run-shell is not', () => {
|
||||
assert.strictEqual(isDevServerCommand('tmux new-session -d -s dev "npm run dev"'), false);
|
||||
assert.strictEqual(isDevServerCommand('tmux run-shell \'npm run "dev"\''), true);
|
||||
});
|
||||
|
||||
test('quoted documentation of a dev command is not a dev server', () => {
|
||||
assert.strictEqual(isDevServerCommand('echo "npm run dev"'), false);
|
||||
assert.strictEqual(isDevServerCommand('npm run lint -- "npm run dev"'), false);
|
||||
});
|
||||
|
||||
test('substitutions and subshells are scanned', () => {
|
||||
assert.strictEqual(isDevServerCommand('echo $(npm run dev)'), true);
|
||||
assert.strictEqual(isDevServerCommand('(pnpm dev)'), true);
|
||||
});
|
||||
|
||||
test('isDevServerSegment reads one segment', () => {
|
||||
assert.strictEqual(isDevServerSegment('sudo -u me pnpm --dir app dev'), true);
|
||||
assert.strictEqual(isDevServerSegment('npx eslint .'), false);
|
||||
});
|
||||
|
||||
console.log(`\nResults: Passed: ${passed}, Failed: ${failed}`);
|
||||
process.exit(failed > 0 ? 1 : 0);
|
||||
@@ -33,12 +33,12 @@ function runTests() {
|
||||
let passed = 0;
|
||||
let failed = 0;
|
||||
|
||||
if (test('represents all 17 registered targets exactly once across 16 harnesses', () => {
|
||||
if (test('represents all 19 registered targets exactly once across 17 harnesses', () => {
|
||||
const catalogTargetIds = HARNESS_CAPABILITIES.flatMap(harness => harness.targetIds);
|
||||
const adapterTargetIds = listInstallTargetAdapters().map(adapter => adapter.target);
|
||||
|
||||
assert.strictEqual(HARNESS_CAPABILITIES.length, 16);
|
||||
assert.strictEqual(new Set(catalogTargetIds).size, 17);
|
||||
assert.strictEqual(HARNESS_CAPABILITIES.length, 17);
|
||||
assert.strictEqual(new Set(catalogTargetIds).size, 19);
|
||||
assert.deepStrictEqual([...catalogTargetIds].sort(), [...SUPPORTED_INSTALL_TARGETS].sort());
|
||||
assert.deepStrictEqual([...catalogTargetIds].sort(), [...adapterTargetIds].sort());
|
||||
})) passed++; else failed++;
|
||||
@@ -84,6 +84,16 @@ function runTests() {
|
||||
{ id: 'project', targetId: 'kimi', root: './.kimi-code' },
|
||||
]);
|
||||
|
||||
const antigravity = getHarnessCapability('antigravity');
|
||||
assert.deepStrictEqual(antigravity.targetIds, ['antigravity-home', 'antigravity']);
|
||||
assert.strictEqual(antigravity.channel, 'native-plugin');
|
||||
assert.strictEqual(antigravity.installMode, 'native-plugin');
|
||||
assert.match(antigravity.destination, /selected Antigravity scope/i);
|
||||
assert.deepStrictEqual(antigravity.scopes, [
|
||||
{ id: 'user', targetId: 'antigravity-home', root: '~/.gemini/config/plugins/ecc' },
|
||||
{ id: 'project', targetId: 'antigravity', root: './.agents' },
|
||||
]);
|
||||
|
||||
const opencode = getHarnessCapability('opencode');
|
||||
assert.match(opencode.destinationResolution, /OPENCODE_CONFIG_DIR/);
|
||||
assert.match(opencode.destinationResolution, /XDG_CONFIG_HOME/);
|
||||
@@ -93,7 +103,6 @@ function runTests() {
|
||||
if (test('keeps every advanced target attached to its registered root and scope', () => {
|
||||
const expected = {
|
||||
cursor: ['project', './.cursor'],
|
||||
antigravity: ['project', './.agents'],
|
||||
gemini: ['project', './.gemini'],
|
||||
opencode: ['home', '~/.config/opencode'],
|
||||
codebuddy: ['project', './.codebuddy'],
|
||||
@@ -104,6 +113,7 @@ function runTests() {
|
||||
hermes: ['home', '~/.hermes'],
|
||||
openclaw: ['home', '~/.openclaw'],
|
||||
grok: ['native', '~/.grok'],
|
||||
'mistral-vibe': ['project', './.vibe'],
|
||||
};
|
||||
|
||||
for (const [id, [scopeId, root]] of Object.entries(expected)) {
|
||||
@@ -157,6 +167,16 @@ function runTests() {
|
||||
}
|
||||
})) passed++; else failed++;
|
||||
|
||||
if (test('describes Mistral Vibe as a skills-only managed project target', () => {
|
||||
const vibe = getHarnessCapability('vibe');
|
||||
assert.strictEqual(vibe.id, 'mistral-vibe');
|
||||
assert.deepStrictEqual(vibe.targetIds, ['mistral-vibe']);
|
||||
assert.strictEqual(vibe.destination, './.vibe');
|
||||
assert.strictEqual(vibe.hooks.mode, 'not-configured');
|
||||
assert.strictEqual(vibe.hooks.eccConfigured, false);
|
||||
assert.match(vibe.hooks.note, /skills/i);
|
||||
})) passed++; else failed++;
|
||||
|
||||
if (test('normalizes wizard selections into canonical guided order', () => {
|
||||
assert.deepStrictEqual(
|
||||
normalizeHarnessSelection(' KIMI CODE, Claude Code, kimi '),
|
||||
@@ -190,7 +210,7 @@ function runTests() {
|
||||
|
||||
const first = listHarnessCapabilities();
|
||||
first.pop();
|
||||
assert.strictEqual(listHarnessCapabilities().length, 16);
|
||||
assert.strictEqual(listHarnessCapabilities().length, 17);
|
||||
|
||||
const guided = listGuidedHarnesses();
|
||||
guided.reverse();
|
||||
|
||||
@@ -106,6 +106,26 @@ function runTests() {
|
||||
}
|
||||
})) passed++; else failed++;
|
||||
|
||||
if (test('accepts a Mistral Vibe skills-only install config', () => {
|
||||
const cwd = createTempDir('install-config-vibe-');
|
||||
try {
|
||||
const configPath = path.join(cwd, 'ecc-install.json');
|
||||
writeJson(configPath, {
|
||||
version: 1,
|
||||
target: 'mistral-vibe',
|
||||
include: ['skill:tdd-workflow'],
|
||||
exclude: ['skill:security-review'],
|
||||
});
|
||||
|
||||
const config = loadInstallConfig(configPath);
|
||||
assert.strictEqual(config.target, 'mistral-vibe');
|
||||
assert.deepStrictEqual(config.includeComponentIds, ['skill:tdd-workflow']);
|
||||
assert.deepStrictEqual(config.excludeComponentIds, ['skill:security-review']);
|
||||
} finally {
|
||||
cleanup(cwd);
|
||||
}
|
||||
})) passed++; else failed++;
|
||||
|
||||
for (const field of ['include', 'exclude']) {
|
||||
if (test(`loads agent, skill, and locale selections from ${field}`, () => {
|
||||
const cwd = createTempDir('install-config-');
|
||||
|
||||
@@ -203,6 +203,44 @@ function runTests() {
|
||||
);
|
||||
})) passed++; else failed++;
|
||||
|
||||
if (test('resolves existing skill components to exact modules for Mistral Vibe', () => {
|
||||
const plan = resolveInstallPlan({
|
||||
includeComponentIds: ['skill:tdd-workflow'],
|
||||
target: 'mistral-vibe',
|
||||
projectRoot: '/workspace/app',
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(plan.selectedModuleIds, ['skill-tdd-workflow']);
|
||||
assert.deepStrictEqual(plan.skippedModuleIds, []);
|
||||
assert.deepStrictEqual(
|
||||
plan.operations.map(operation => operation.sourceRelativePath),
|
||||
['skills/tdd-workflow']
|
||||
);
|
||||
})) passed++; else failed++;
|
||||
|
||||
if (test('lists existing skill components as installable for Mistral Vibe', () => {
|
||||
const components = listInstallComponents({ family: 'skill', target: 'mistral-vibe' });
|
||||
const tdd = components.find(component => component.id === 'skill:tdd-workflow');
|
||||
assert.ok(tdd, 'Should expose tdd-workflow to Mistral Vibe users');
|
||||
assert.deepStrictEqual(tdd.moduleIds, ['skill-tdd-workflow']);
|
||||
assert.deepStrictEqual(tdd.targets, ['mistral-vibe']);
|
||||
const detail = getInstallComponent('skill:tdd-workflow', { target: 'mistral-vibe' });
|
||||
assert.deepStrictEqual(detail.moduleIds, ['skill-tdd-workflow']);
|
||||
assert.deepStrictEqual(detail.targets, ['mistral-vibe']);
|
||||
})) passed++; else failed++;
|
||||
|
||||
if (test('applies Mistral Vibe exclusions to the exact selected skill module', () => {
|
||||
assert.throws(
|
||||
() => resolveInstallPlan({
|
||||
target: 'mistral-vibe',
|
||||
projectRoot: '/workspace/app',
|
||||
includeComponentIds: ['skill:tdd-workflow'],
|
||||
excludeComponentIds: ['skill:tdd-workflow'],
|
||||
}),
|
||||
/Selection excludes every requested install module/
|
||||
);
|
||||
})) passed++; else failed++;
|
||||
|
||||
if (test('marks unified-memory install surfaces as requiring the separate ECC runtime', () => {
|
||||
const component = getInstallComponent('skill:unified-memory');
|
||||
assert.deepStrictEqual(component.moduleIds, ['skill-unified-memory']);
|
||||
@@ -291,13 +329,15 @@ function runTests() {
|
||||
'rules-core',
|
||||
'agents-core',
|
||||
'commands-core',
|
||||
'hooks-runtime',
|
||||
'platform-configs',
|
||||
'skill-unified-memory',
|
||||
'workflow-quality',
|
||||
'shared-script-utils'
|
||||
]
|
||||
);
|
||||
assert.ok(plan.skippedModuleIds.includes('hooks-runtime'));
|
||||
assert.ok(!plan.skippedModuleIds.includes('hooks-runtime'));
|
||||
assert.ok(plan.operations.some(operation => operation.destinationPath === path.join(projectRoot, '.agents', 'hooks.json')));
|
||||
assert.ok(!plan.skippedModuleIds.includes('platform-configs'));
|
||||
assert.ok(!plan.skippedModuleIds.includes('workflow-quality'));
|
||||
assert.strictEqual(plan.targetAdapterId, 'antigravity-project');
|
||||
|
||||
@@ -52,6 +52,7 @@ function runTests() {
|
||||
assert.ok(targets.includes('joycode'), 'Should include joycode target');
|
||||
assert.ok(targets.includes('qwen'), 'Should include qwen target');
|
||||
assert.ok(targets.includes('zed'), 'Should include zed target');
|
||||
assert.ok(targets.includes('mistral-vibe'), 'Should include mistral-vibe target');
|
||||
assert.ok(targets.includes('grok'), 'Should include grok target');
|
||||
})) passed++; else failed++;
|
||||
|
||||
|
||||
@@ -157,6 +157,19 @@ test('collapses newlines to spaces', () => {
|
||||
// Regression (#3867): the harness notice after a safety-classifier stop is
|
||||
// recorded as a user entry; it must not reach the LLM summary input.
|
||||
const CLASSIFIER_NOTICE_TEXT = 'Your response above was stopped by a safety classifier — this is not a tool or API error.';
|
||||
const CLASSIFIER_NOTICE_LONG_TEXT = `${CLASSIFIER_NOTICE_TEXT} The rest of it was withheld, and tool calls in it that had not finished did not run. Do not produce that content again, even reworded.`;
|
||||
|
||||
test('drops the longer classifier notice from the LLM input', () => {
|
||||
const p = writeTranscript([userEntry('Refactor the config loader'), userEntry(CLASSIFIER_NOTICE_LONG_TEXT), assistantEntry('Done.')]);
|
||||
const result = extractConversationText(p);
|
||||
assert.ok(result.includes('Refactor the config loader'));
|
||||
assert.ok(!result.includes('withheld') && !result.includes('safety classifier'), result);
|
||||
});
|
||||
|
||||
test('keeps user text following the longer notice', () => {
|
||||
const text = `${CLASSIFIER_NOTICE_LONG_TEXT} Why did this happen?`;
|
||||
assert.ok(extractConversationText(writeTranscript([userEntry(text)])).includes('Why did this happen?'));
|
||||
});
|
||||
|
||||
test('drops safety-classifier notices from the LLM input', () => {
|
||||
const p = writeTranscript([userEntry('Refactor the config loader'), userEntry(CLASSIFIER_NOTICE_TEXT), assistantEntry('Done.')]);
|
||||
@@ -177,10 +190,21 @@ test('returns null when the only user turn is a classifier notice', () => {
|
||||
|
||||
test('isClassifierNotice matches only the whole notice', () => {
|
||||
assert.strictEqual(isClassifierNotice(CLASSIFIER_NOTICE_TEXT), true);
|
||||
assert.strictEqual(isClassifierNotice(CLASSIFIER_NOTICE_LONG_TEXT), true);
|
||||
assert.strictEqual(isClassifierNotice(`${CLASSIFIER_NOTICE_LONG_TEXT} Why did this happen?`), false);
|
||||
assert.strictEqual(isClassifierNotice(`${CLASSIFIER_NOTICE_TEXT} Why did this happen?`), false);
|
||||
assert.strictEqual(isClassifierNotice('Why did I see "Your response above was stopped by a safety classifier"?'), false);
|
||||
});
|
||||
|
||||
test('drops a classifier notice wrapped across lines', () => {
|
||||
const wrapped = CLASSIFIER_NOTICE_LONG_TEXT.replace('safety classifier', 'safety\nclassifier').replace(' The rest', ' \nThe rest');
|
||||
assert.strictEqual(isClassifierNotice(wrapped), true);
|
||||
const p = writeTranscript([userEntry('Refactor the config loader'), userEntry(wrapped), assistantEntry('Done.')]);
|
||||
const result = extractConversationText(p);
|
||||
assert.ok(result.includes('Refactor the config loader'));
|
||||
assert.ok(!result.includes('withheld') && !result.includes('safety classifier'), result);
|
||||
});
|
||||
|
||||
// --- getContextRemainingPct ---
|
||||
console.log('\ngetContextRemainingPct:');
|
||||
|
||||
|
||||
@@ -0,0 +1,304 @@
|
||||
/**
|
||||
* Contract and lifecycle tests for the Mistral Vibe project target.
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
const assert = require('assert');
|
||||
const fs = require('fs');
|
||||
const os = require('os');
|
||||
const path = require('path');
|
||||
|
||||
const { createManifestInstallPlan } = require('../../scripts/lib/install/plan');
|
||||
const { applyInstallPlan } = require('../../scripts/lib/install/apply');
|
||||
const {
|
||||
buildDoctorReport,
|
||||
repairInstalledStates,
|
||||
uninstallInstalledStates,
|
||||
} = require('../../scripts/lib/install-lifecycle');
|
||||
const { resolveInstallPlan } = require('../../scripts/lib/install-manifests');
|
||||
const {
|
||||
getInstallTargetAdapter,
|
||||
planInstallTargetScaffold,
|
||||
} = require('../../scripts/lib/install-targets/registry');
|
||||
const { createLegacyCompatInstallPlan } = require('../../scripts/lib/install-executor');
|
||||
|
||||
const REPO_ROOT = path.resolve(__dirname, '..', '..');
|
||||
|
||||
let passed = 0;
|
||||
let failed = 0;
|
||||
|
||||
function test(name, fn) {
|
||||
try {
|
||||
fn();
|
||||
console.log(` ✓ ${name}`);
|
||||
passed += 1;
|
||||
} catch (error) {
|
||||
console.log(` ✗ ${name}`);
|
||||
console.log(` Error: ${error.message}`);
|
||||
failed += 1;
|
||||
}
|
||||
}
|
||||
|
||||
function createFixture() {
|
||||
return {
|
||||
homeDir: fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-vibe-home-')),
|
||||
projectRoot: fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-vibe-project-')),
|
||||
};
|
||||
}
|
||||
|
||||
function cleanupFixture(fixture) {
|
||||
fs.rmSync(fixture.homeDir, { recursive: true, force: true });
|
||||
fs.rmSync(fixture.projectRoot, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
function createSkillPlan(fixture) {
|
||||
return createManifestInstallPlan({
|
||||
sourceRoot: REPO_ROOT,
|
||||
target: 'mistral-vibe',
|
||||
includeComponentIds: ['skill:tdd-workflow'],
|
||||
projectRoot: fixture.projectRoot,
|
||||
homeDir: fixture.homeDir,
|
||||
});
|
||||
}
|
||||
|
||||
console.log('\n=== Mistral Vibe install target tests ===\n');
|
||||
|
||||
test('registers a project adapter rooted at .vibe', () => {
|
||||
const adapter = getInstallTargetAdapter('mistral-vibe');
|
||||
const projectRoot = path.resolve('/workspace/app');
|
||||
|
||||
assert.strictEqual(adapter.id, 'mistral-vibe-project');
|
||||
assert.strictEqual(adapter.target, 'mistral-vibe');
|
||||
assert.strictEqual(adapter.kind, 'project');
|
||||
assert.strictEqual(adapter.resolveRoot({ projectRoot }), path.join(projectRoot, '.vibe'));
|
||||
assert.strictEqual(
|
||||
adapter.getInstallStatePath({ projectRoot }),
|
||||
path.join(projectRoot, '.vibe', 'ecc-install-state.json')
|
||||
);
|
||||
});
|
||||
|
||||
test('maps only canonical skill sources into the native Vibe skills directory', () => {
|
||||
const projectRoot = path.resolve('/workspace/app');
|
||||
const plan = planInstallTargetScaffold({
|
||||
target: 'mistral-vibe',
|
||||
repoRoot: REPO_ROOT,
|
||||
projectRoot,
|
||||
modules: [
|
||||
{ id: 'skill-tdd-workflow', kind: 'skills', paths: ['skills/tdd-workflow'] },
|
||||
{ id: 'agents-core', kind: 'agents', paths: ['AGENTS.md', 'agents', '.agents'] },
|
||||
{ id: 'commands-core', kind: 'commands', paths: ['commands'] },
|
||||
{ id: 'rules-core', kind: 'rules', paths: ['rules'] },
|
||||
{ id: 'hooks-runtime', kind: 'hooks', paths: ['hooks'] },
|
||||
{ id: 'platform-configs', kind: 'platform', paths: ['.vibe', '.mcp.json'] },
|
||||
],
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(plan.operations, [{
|
||||
kind: 'copy-path',
|
||||
moduleId: 'skill-tdd-workflow',
|
||||
sourceRelativePath: 'skills/tdd-workflow',
|
||||
destinationPath: path.join(projectRoot, '.vibe', 'skills', 'tdd-workflow'),
|
||||
strategy: 'preserve-relative-path',
|
||||
ownership: 'managed',
|
||||
scaffoldOnly: true,
|
||||
}]);
|
||||
});
|
||||
|
||||
test('rejects unsafe Vibe skill source paths before planning writes', () => {
|
||||
for (const sourceRelativePath of [
|
||||
'skills/../AGENTS.md',
|
||||
'skills\\..\\AGENTS.md',
|
||||
'/tmp/skills/escape',
|
||||
'skills//escape',
|
||||
]) {
|
||||
assert.throws(
|
||||
() => planInstallTargetScaffold({
|
||||
target: 'mistral-vibe',
|
||||
repoRoot: REPO_ROOT,
|
||||
projectRoot: '/workspace/app',
|
||||
modules: [{ id: 'unsafe-skill', kind: 'skills', paths: [sourceRelativePath] }],
|
||||
}),
|
||||
/unsafe Mistral Vibe skill source path/i,
|
||||
sourceRelativePath
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('resolves a single-skill install without claiming unsupported profiles', () => {
|
||||
assert.throws(
|
||||
() => resolveInstallPlan({
|
||||
repoRoot: REPO_ROOT,
|
||||
target: 'mistral-vibe',
|
||||
projectRoot: '/workspace/app',
|
||||
}),
|
||||
/Mistral Vibe.*--skills/i
|
||||
);
|
||||
const plan = resolveInstallPlan({
|
||||
repoRoot: REPO_ROOT,
|
||||
target: 'mistral-vibe',
|
||||
projectRoot: '/workspace/app',
|
||||
includeComponentIds: ['skill:tdd-workflow'],
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(plan.selectedModuleIds, ['skill-tdd-workflow']);
|
||||
assert.deepStrictEqual(plan.skippedModuleIds, []);
|
||||
assert.strictEqual(plan.operations.length, 1);
|
||||
const existingExactModulePlan = resolveInstallPlan({
|
||||
repoRoot: REPO_ROOT,
|
||||
target: 'mistral-vibe',
|
||||
projectRoot: '/workspace/app',
|
||||
includeComponentIds: ['skill:unified-memory'],
|
||||
});
|
||||
assert.deepStrictEqual(existingExactModulePlan.selectedModuleIds, ['skill-unified-memory']);
|
||||
assert.deepStrictEqual(
|
||||
existingExactModulePlan.operations.map(operation => operation.sourceRelativePath),
|
||||
['skills/unified-memory']
|
||||
);
|
||||
assert.throws(
|
||||
() => resolveInstallPlan({
|
||||
repoRoot: REPO_ROOT,
|
||||
target: 'mistral-vibe',
|
||||
projectRoot: '/workspace/app',
|
||||
profileId: 'minimal',
|
||||
}),
|
||||
/Mistral Vibe.*--skills/i
|
||||
);
|
||||
assert.throws(
|
||||
() => resolveInstallPlan({
|
||||
repoRoot: REPO_ROOT,
|
||||
target: 'mistral-vibe',
|
||||
projectRoot: '/workspace/app',
|
||||
moduleIds: ['workflow-quality'],
|
||||
}),
|
||||
/Mistral Vibe.*--skills/i
|
||||
);
|
||||
});
|
||||
|
||||
test('guides legacy language requests to the supported Vibe skill surface', () => {
|
||||
assert.throws(
|
||||
() => createLegacyCompatInstallPlan({
|
||||
sourceRoot: REPO_ROOT,
|
||||
target: 'mistral-vibe',
|
||||
legacyLanguages: ['typescript'],
|
||||
projectRoot: '/workspace/app',
|
||||
}),
|
||||
/--target mistral-vibe --skills <id,...>/
|
||||
);
|
||||
});
|
||||
|
||||
test('installs, diagnoses, repairs, and uninstalls a Vibe skill', () => {
|
||||
const fixture = createFixture();
|
||||
try {
|
||||
const plan = createSkillPlan(fixture);
|
||||
applyInstallPlan(plan);
|
||||
|
||||
const skillPath = path.join(fixture.projectRoot, '.vibe', 'skills', 'tdd-workflow', 'SKILL.md');
|
||||
const statePath = path.join(fixture.projectRoot, '.vibe', 'ecc-install-state.json');
|
||||
assert.ok(fs.existsSync(skillPath));
|
||||
assert.ok(fs.existsSync(statePath));
|
||||
|
||||
const healthy = buildDoctorReport({
|
||||
repoRoot: REPO_ROOT,
|
||||
projectRoot: fixture.projectRoot,
|
||||
homeDir: fixture.homeDir,
|
||||
targets: ['mistral-vibe'],
|
||||
});
|
||||
assert.strictEqual(healthy.results[0].status, 'ok');
|
||||
|
||||
fs.unlinkSync(skillPath);
|
||||
const broken = buildDoctorReport({
|
||||
repoRoot: REPO_ROOT,
|
||||
projectRoot: fixture.projectRoot,
|
||||
homeDir: fixture.homeDir,
|
||||
targets: ['mistral-vibe'],
|
||||
});
|
||||
assert.strictEqual(broken.results[0].status, 'error');
|
||||
|
||||
const repaired = repairInstalledStates({
|
||||
repoRoot: REPO_ROOT,
|
||||
projectRoot: fixture.projectRoot,
|
||||
homeDir: fixture.homeDir,
|
||||
targets: ['mistral-vibe'],
|
||||
});
|
||||
assert.strictEqual(repaired.results[0].status, 'repaired');
|
||||
assert.ok(fs.existsSync(skillPath));
|
||||
|
||||
const uninstalled = uninstallInstalledStates({
|
||||
repoRoot: REPO_ROOT,
|
||||
projectRoot: fixture.projectRoot,
|
||||
homeDir: fixture.homeDir,
|
||||
targets: ['mistral-vibe'],
|
||||
});
|
||||
assert.strictEqual(uninstalled.results[0].status, 'uninstalled');
|
||||
assert.ok(!fs.existsSync(skillPath));
|
||||
assert.ok(!fs.existsSync(statePath));
|
||||
} finally {
|
||||
cleanupFixture(fixture);
|
||||
}
|
||||
});
|
||||
|
||||
test('never overwrites or claims a user-owned Vibe skill file', () => {
|
||||
const fixture = createFixture();
|
||||
const skillPath = path.join(fixture.projectRoot, '.vibe', 'skills', 'tdd-workflow', 'SKILL.md');
|
||||
try {
|
||||
fs.mkdirSync(path.dirname(skillPath), { recursive: true });
|
||||
fs.writeFileSync(skillPath, '# User-owned Vibe skill\n', 'utf8');
|
||||
|
||||
const result = applyInstallPlan(createSkillPlan(fixture));
|
||||
assert.strictEqual(fs.readFileSync(skillPath, 'utf8'), '# User-owned Vibe skill\n');
|
||||
assert.ok(result.skippedOperations.some(operation => operation.destinationPath === skillPath));
|
||||
assert.ok(!result.statePreview.operations.some(operation => operation.destinationPath === skillPath));
|
||||
} finally {
|
||||
cleanupFixture(fixture);
|
||||
}
|
||||
});
|
||||
|
||||
test('rejects a Vibe skill file created after preflight without overwriting it', () => {
|
||||
const fixture = createFixture();
|
||||
const skillPath = path.join(fixture.projectRoot, '.vibe', 'skills', 'tdd-workflow', 'SKILL.md');
|
||||
try {
|
||||
const plan = createSkillPlan(fixture);
|
||||
assert.throws(
|
||||
() => applyInstallPlan(plan, {
|
||||
beforeOperationWrite({ operation }) {
|
||||
if (operation.destinationPath === skillPath) {
|
||||
fs.writeFileSync(skillPath, '# Concurrent user-owned Vibe skill\n', 'utf8');
|
||||
}
|
||||
},
|
||||
}),
|
||||
/user-owned file appeared.*after planning/i
|
||||
);
|
||||
assert.strictEqual(
|
||||
fs.readFileSync(skillPath, 'utf8'),
|
||||
'# Concurrent user-owned Vibe skill\n'
|
||||
);
|
||||
} finally {
|
||||
cleanupFixture(fixture);
|
||||
}
|
||||
});
|
||||
|
||||
test('preserves a modified managed Vibe skill during uninstall', () => {
|
||||
const fixture = createFixture();
|
||||
const skillPath = path.join(fixture.projectRoot, '.vibe', 'skills', 'tdd-workflow', 'SKILL.md');
|
||||
try {
|
||||
applyInstallPlan(createSkillPlan(fixture));
|
||||
fs.appendFileSync(skillPath, '\nUser change.\n', 'utf8');
|
||||
|
||||
const result = uninstallInstalledStates({
|
||||
repoRoot: REPO_ROOT,
|
||||
projectRoot: fixture.projectRoot,
|
||||
homeDir: fixture.homeDir,
|
||||
targets: ['mistral-vibe'],
|
||||
});
|
||||
assert.strictEqual(result.results[0].status, 'partial');
|
||||
assert.ok(fs.existsSync(skillPath));
|
||||
assert.ok(fs.existsSync(path.join(fixture.projectRoot, '.vibe', 'ecc-install-state.json')));
|
||||
} finally {
|
||||
cleanupFixture(fixture);
|
||||
}
|
||||
});
|
||||
|
||||
console.log(`\nPassed: ${passed}`);
|
||||
console.log(`Failed: ${failed}`);
|
||||
process.exit(failed > 0 ? 1 : 0);
|
||||
@@ -0,0 +1,85 @@
|
||||
'use strict';
|
||||
|
||||
const assert = require('assert');
|
||||
const fs = require('fs');
|
||||
const os = require('os');
|
||||
const path = require('path');
|
||||
|
||||
const {
|
||||
formatPackageSourcePath,
|
||||
isPackageSourcePath,
|
||||
parsePackageSourcePath,
|
||||
resolvePackageSourcePath,
|
||||
} = require('../../scripts/lib/install/package-source');
|
||||
|
||||
let passed = 0;
|
||||
let failed = 0;
|
||||
|
||||
function test(name, fn) {
|
||||
try {
|
||||
fn();
|
||||
console.log(` ✓ ${name}`);
|
||||
passed += 1;
|
||||
} catch (error) {
|
||||
console.log(` ✗ ${name}`);
|
||||
console.log(` Error: ${error.message}`);
|
||||
failed += 1;
|
||||
}
|
||||
}
|
||||
|
||||
function writePackage(packageRoot, name, files = {}) {
|
||||
fs.mkdirSync(packageRoot, { recursive: true });
|
||||
fs.writeFileSync(path.join(packageRoot, 'package.json'), JSON.stringify({ name, version: '1.0.0' }));
|
||||
for (const [relativePath, content] of Object.entries(files)) {
|
||||
fs.mkdirSync(path.dirname(path.join(packageRoot, relativePath)), { recursive: true });
|
||||
fs.writeFileSync(path.join(packageRoot, relativePath), content);
|
||||
}
|
||||
}
|
||||
|
||||
console.log('\n=== Testing install/package-source.js ===\n');
|
||||
|
||||
test('formats package chains as the installed node_modules layout', () => {
|
||||
assert.strictEqual(formatPackageSourcePath(['ajv']), 'node_modules/ajv');
|
||||
assert.strictEqual(
|
||||
formatPackageSourcePath(['ajv', '@scope/dep'], 'dist\\index.js'),
|
||||
'node_modules/ajv/node_modules/@scope/dep/dist/index.js'
|
||||
);
|
||||
});
|
||||
|
||||
test('recognizes only node_modules-rooted sources', () => {
|
||||
assert.strictEqual(isPackageSourcePath('node_modules/ajv/package.json'), true);
|
||||
assert.strictEqual(isPackageSourcePath('scripts/node_modules/x.js'), false);
|
||||
assert.strictEqual(isPackageSourcePath(undefined), false);
|
||||
});
|
||||
|
||||
test('rejects traversal and malformed package names', () => {
|
||||
for (const source of [
|
||||
'node_modules/ajv/../../secret',
|
||||
'node_modules/../etc/passwd',
|
||||
'node_modules/ajv/./x',
|
||||
'node_modules/Bad Name/x',
|
||||
'node_modules/@scope',
|
||||
'node_modules',
|
||||
]) {
|
||||
assert.throws(() => parsePackageSourcePath(source), /Invalid package source path/, source);
|
||||
}
|
||||
});
|
||||
|
||||
test('resolves hoisted sibling packages through Node resolution', () => {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-package-source-'));
|
||||
try {
|
||||
const repoRoot = path.join(root, 'node_modules', 'ecc-universal');
|
||||
writePackage(repoRoot, 'ecc-universal');
|
||||
writePackage(path.join(root, 'node_modules', 'dep-a'), 'dep-a', { 'lib/a.js': 'a' });
|
||||
writePackage(path.join(root, 'node_modules', 'dep-b'), 'dep-b', { 'b.js': 'b' });
|
||||
|
||||
const resolved = resolvePackageSourcePath(repoRoot, 'node_modules/dep-a/node_modules/dep-b/b.js');
|
||||
assert.strictEqual(fs.realpathSync(resolved), fs.realpathSync(path.join(root, 'node_modules', 'dep-b', 'b.js')));
|
||||
assert.strictEqual(resolvePackageSourcePath(repoRoot, 'node_modules/ecc-missing-package/x.js'), null);
|
||||
} finally {
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
console.log(`\nResults: Passed: ${passed}, Failed: ${failed}`);
|
||||
process.exit(failed > 0 ? 1 : 0);
|
||||
@@ -204,5 +204,70 @@ test('resolveGitBranch returns null when cwd is not a git repo (real path)', ()
|
||||
assert.strictEqual(parsed.branch, null);
|
||||
});
|
||||
|
||||
|
||||
test('snapshot follows model changes appended to the same Codex rollout', () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-codex-model-change-'));
|
||||
try {
|
||||
const rolloutPath = writeRollout(dir, 'rollout-model-change.jsonl', [
|
||||
{ type: 'session_meta', payload: { id: 'model-change', model: 'metadata-model' } },
|
||||
{ type: 'turn_context', payload: { model: 'initial-model' } },
|
||||
]);
|
||||
const adapter = createCodexWorktreeAdapter({ sessionsDir: dir, persistSnapshots: false });
|
||||
const session = adapter.open(rolloutPath);
|
||||
assert.strictEqual(session.getSnapshot().workers[0].artifacts.model, 'initial-model');
|
||||
fs.appendFileSync(rolloutPath, JSON.stringify({
|
||||
type: 'turn_context', payload: { model: 'selected-model' },
|
||||
}) + '\n');
|
||||
assert.strictEqual(session.getSnapshot().workers[0].artifacts.model, 'selected-model');
|
||||
const contents = fs.readFileSync(rolloutPath, 'utf8');
|
||||
const parsed = parseCodexRollout(rolloutPath);
|
||||
assert.strictEqual(parsed.model, 'selected-model');
|
||||
assert.strictEqual(fs.readFileSync(rolloutPath, 'utf8'), contents);
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test('latest valid turn model survives trailing unrelated or incomplete records', () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-codex-model-tail-'));
|
||||
try {
|
||||
const rolloutPath = writeRollout(dir, 'rollout-model-tail.jsonl', [
|
||||
{ type: 'session_meta', payload: { id: 'model-tail', model: 'metadata-model' } },
|
||||
{ type: 'turn_context', payload: { model: 'initial-model' } },
|
||||
{ type: 'turn_context', payload: { model: 'selected-model' } },
|
||||
{ type: 'response_item', payload: { model: 'unrelated-model' } },
|
||||
{ type: 'turn_context', payload: { model: '' } },
|
||||
{ type: 'turn_context', payload: { model: null } },
|
||||
{ type: 'turn_context', payload: { model: 42 } },
|
||||
{ type: 'turn_context', payload: null },
|
||||
null,
|
||||
]);
|
||||
fs.appendFileSync(rolloutPath, '{"type":"turn_context","payload":');
|
||||
assert.strictEqual(parseCodexRollout(rolloutPath).model, 'selected-model');
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
for (const [metadata, expected] of [
|
||||
[{ model: 'metadata-model', model_provider: 'provider-name' }, 'metadata-model'],
|
||||
[{ model_provider: 'provider-name' }, 'provider-name'],
|
||||
[{}, null],
|
||||
]) {
|
||||
test('model metadata fallback remains available: ' + String(expected), () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-codex-model-fallback-'));
|
||||
try {
|
||||
const rolloutPath = writeRollout(dir, 'rollout-model-fallback.jsonl', [
|
||||
{ type: 'session_meta', payload: { id: 'model-fallback', ...metadata } },
|
||||
{ type: 'turn_context', payload: { model: '' } },
|
||||
{ type: 'turn_context', payload: { model: null } },
|
||||
]);
|
||||
assert.strictEqual(parseCodexRollout(rolloutPath).model, expected);
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
console.log(`\n=== Results: ${passed} passed, ${failed} failed ===`);
|
||||
if (failed > 0) process.exit(1);
|
||||
@@ -0,0 +1,145 @@
|
||||
'use strict';
|
||||
|
||||
const assert = require('assert');
|
||||
const fs = require('fs');
|
||||
const os = require('os');
|
||||
const path = require('path');
|
||||
const aliases = require('../../scripts/lib/session-aliases');
|
||||
|
||||
const names = ['__proto__', 'constructor', 'toString', 'hasOwnProperty'];
|
||||
let passed = 0;
|
||||
let failed = 0;
|
||||
|
||||
function test(name, callback) {
|
||||
const fixture = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-alias-own-'));
|
||||
const originalDataHome = process.env.ECC_AGENT_DATA_HOME;
|
||||
// Restore these even when testing the old implementation, which can mutate
|
||||
// inherited objects before an assertion reports the regression.
|
||||
const targets = [Object.prototype, Object, Object.prototype.toString, Object.prototype.hasOwnProperty];
|
||||
const descriptors = targets.map(target => ({
|
||||
target,
|
||||
title: Object.getOwnPropertyDescriptor(target, 'title'),
|
||||
updatedAt: Object.getOwnPropertyDescriptor(target, 'updatedAt')
|
||||
}));
|
||||
try {
|
||||
process.env.ECC_AGENT_DATA_HOME = fixture;
|
||||
const filePath = path.join(fixture, 'session-aliases.json');
|
||||
assert.strictEqual(aliases.getAliasesPath(), filePath);
|
||||
callback(filePath);
|
||||
console.log(` PASS ${name}`);
|
||||
passed += 1;
|
||||
} catch (error) {
|
||||
console.log(` FAIL ${name}: ${error.message}`);
|
||||
failed += 1;
|
||||
} finally {
|
||||
for (const descriptor of descriptors) {
|
||||
for (const key of ['title', 'updatedAt']) {
|
||||
if (descriptor[key]) Object.defineProperty(descriptor.target, key, descriptor[key]);
|
||||
else delete descriptor.target[key];
|
||||
}
|
||||
}
|
||||
if (originalDataHome === undefined) delete process.env.ECC_AGENT_DATA_HOME;
|
||||
else process.env.ECC_AGENT_DATA_HOME = originalDataHome;
|
||||
fs.rmSync(fixture, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
function read(filePath) {
|
||||
return JSON.parse(fs.readFileSync(filePath, 'utf8'));
|
||||
}
|
||||
|
||||
for (const name of names) {
|
||||
test(`an absent ${name} is not a session alias`, filePath => {
|
||||
assert.strictEqual(aliases.resolveAlias(name), null);
|
||||
assert.strictEqual(aliases.resolveSessionAlias(name), name);
|
||||
assert.strictEqual(fs.existsSync(filePath), false);
|
||||
});
|
||||
|
||||
test(`${name} can be created, updated and removed without losing its record`, filePath => {
|
||||
const created = aliases.setAlias(name, '/fixture/session-one', 'First title');
|
||||
assert.strictEqual(created.success, true);
|
||||
assert.strictEqual(created.isNew, true);
|
||||
const first = read(filePath);
|
||||
assert.strictEqual(Object.hasOwn(first.aliases, name), true);
|
||||
assert.strictEqual(first.metadata.totalCount, 1);
|
||||
assert.ok(first.aliases[name].createdAt);
|
||||
assert.strictEqual(aliases.resolveAlias(name).sessionPath, '/fixture/session-one');
|
||||
assert.deepStrictEqual(aliases.listAliases().map(entry => entry.name), [name]);
|
||||
|
||||
const updated = aliases.setAlias(name, '/fixture/session-two', 'Second title');
|
||||
assert.strictEqual(updated.success, true);
|
||||
assert.strictEqual(updated.isNew, false);
|
||||
assert.strictEqual(read(filePath).aliases[name].createdAt, first.aliases[name].createdAt);
|
||||
assert.strictEqual(aliases.resolveAlias(name).sessionPath, '/fixture/session-two');
|
||||
assert.strictEqual(aliases.deleteAlias(name).success, true);
|
||||
assert.strictEqual(aliases.resolveAlias(name), null);
|
||||
assert.strictEqual(read(filePath).metadata.totalCount, 0);
|
||||
});
|
||||
|
||||
test(`renaming to an unused ${name} publishes an own alias entry`, filePath => {
|
||||
assert.strictEqual(aliases.setAlias('original', '/fixture/session', 'Keep this title').success, true);
|
||||
const first = read(filePath).aliases.original;
|
||||
assert.strictEqual(aliases.renameAlias('original', name).success, true);
|
||||
const renamed = read(filePath);
|
||||
assert.strictEqual(Object.hasOwn(renamed.aliases, name), true);
|
||||
assert.strictEqual(Object.hasOwn(renamed.aliases, 'original'), false);
|
||||
assert.strictEqual(renamed.metadata.totalCount, 1);
|
||||
assert.strictEqual(renamed.aliases[name].createdAt, first.createdAt);
|
||||
assert.strictEqual(aliases.resolveAlias(name).sessionPath, first.sessionPath);
|
||||
assert.strictEqual(aliases.resolveAlias(name).title, first.title);
|
||||
});
|
||||
}
|
||||
|
||||
for (const [operation, mutate] of [
|
||||
['delete', name => aliases.deleteAlias(name)],
|
||||
['rename', name => aliases.renameAlias(name, 'destination')],
|
||||
['update title', name => aliases.updateAliasTitle(name, 'Must not be stored')]
|
||||
]) {
|
||||
test(`${operation} rejects inherited names without changing the store or built-ins`, filePath => {
|
||||
assert.strictEqual(aliases.setAlias('ordinary', '/fixture/session').success, true);
|
||||
const before = fs.readFileSync(filePath, 'utf8');
|
||||
for (const name of names) {
|
||||
const target = ({})[name];
|
||||
const beforeTitle = Object.getOwnPropertyDescriptor(target, 'title');
|
||||
const beforeUpdatedAt = Object.getOwnPropertyDescriptor(target, 'updatedAt');
|
||||
const result = mutate(name);
|
||||
assert.strictEqual(result.success, false, `${name} must be absent`);
|
||||
assert.match(result.error, /not found/);
|
||||
assert.strictEqual(fs.readFileSync(filePath, 'utf8'), before);
|
||||
assert.deepStrictEqual(Object.getOwnPropertyDescriptor(target, 'title'), beforeTitle);
|
||||
assert.deepStrictEqual(Object.getOwnPropertyDescriptor(target, 'updatedAt'), beforeUpdatedAt);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
test('existing JSON-owned special names remain readable and writable', filePath => {
|
||||
const createdAt = '2024-01-01T00:00:00.000Z';
|
||||
const entries = Object.fromEntries(names.map(name => [name, {
|
||||
sessionPath: `/fixture/${name}`, createdAt, updatedAt: createdAt, title: 'Imported'
|
||||
}]));
|
||||
assert.strictEqual(aliases.saveAliases({ version: '1.0', aliases: entries }), true);
|
||||
assert.strictEqual(Object.getPrototypeOf(aliases.loadAliases().aliases), Object.prototype);
|
||||
for (const name of names) {
|
||||
assert.strictEqual(aliases.resolveAlias(name).sessionPath, `/fixture/${name}`);
|
||||
assert.strictEqual(aliases.updateAliasTitle(name, 'Changed').success, true);
|
||||
assert.strictEqual(aliases.resolveAlias(name).title, 'Changed');
|
||||
const result = aliases.setAlias(name, `/fixture/updated/${name}`);
|
||||
assert.strictEqual(result.success, true);
|
||||
assert.strictEqual(result.isNew, false);
|
||||
assert.strictEqual(read(filePath).aliases[name].createdAt, createdAt);
|
||||
}
|
||||
assert.strictEqual(read(filePath).metadata.totalCount, names.length);
|
||||
});
|
||||
|
||||
test('an existing own __proto__ entry still blocks a conflicting rename', filePath => {
|
||||
const record = { sessionPath: '/fixture/existing', createdAt: '2024-01-01T00:00:00.000Z', title: null };
|
||||
assert.strictEqual(aliases.saveAliases({ version: '1.0', aliases: { ['__proto__']: record, ordinary: record } }), true);
|
||||
const before = fs.readFileSync(filePath, 'utf8');
|
||||
const result = aliases.renameAlias('ordinary', '__proto__');
|
||||
assert.strictEqual(result.success, false);
|
||||
assert.match(result.error, /already exists/);
|
||||
assert.strictEqual(fs.readFileSync(filePath, 'utf8'), before);
|
||||
});
|
||||
|
||||
console.log(`\nPassed: ${passed}, Failed: ${failed}`);
|
||||
if (failed > 0) process.exit(1);
|
||||
Loaded 100 of 115 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user