Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

feat(headless): 新增容器化 Benchmark CLI 与 Linux 打包流程 (#4750)

ganlingyaod826f05738af
diff --git a/.gitignore b/.gitignore
index 4b8ff47058..964b8cee9c 100644
--- a/.gitignore
+++ b/.gitignore
@@ -193,5 +193,9 @@ github-result-*.json
# 内置插件种子已废弃(改走 plugin-store 安装);历史克隆含私有插件与凭证,永不入仓。
apps/desktop/resources/builtin-ghosts/
+# Cindy Headless local plans and gateway configuration
+.cindy-headless/
+.cindy-headless.json
+
# 本地验收截图与设计稿等任务产物(只在本地保存,不入仓)。
artifacts/
diff --git a/apps/cindy-headless/.gitattributes b/apps/cindy-headless/.gitattributes
new file mode 100644
index 0000000000..965eac4d69
--- /dev/null
+++ b/apps/cindy-headless/.gitattributes
@@ -0,0 +1,2 @@
+**/*.json text eol=lf
+**/*.md text eol=lf
diff --git a/apps/cindy-headless/.gitignore b/apps/cindy-headless/.gitignore
new file mode 100644
index 0000000000..f81c6373cf
--- /dev/null
+++ b/apps/cindy-headless/.gitignore
@@ -0,0 +1,4 @@
+/.cache/
+/bundle/
+/release/
+/config.local.json
diff --git a/apps/cindy-headless/AGENTS.md b/apps/cindy-headless/AGENTS.md
new file mode 100644
index 0000000000..607d621e17
--- /dev/null
+++ b/apps/cindy-headless/AGENTS.md
@@ -0,0 +1,6 @@
+# Cindy Headless
+
+修改、同步或出包本模块前先读 UPDATE_AND_PACKAGE.zh-CN.md。
+默认出包入口为 pnpm --filter cindy-headless package:release,生成 Linux x64 formal full package。
+生成的 bundle、release、runtime binaries、凭证和运行记录不提交源码仓库;分发时保留归档与 manifest/SHA256。
+日常迭代可先运行 pnpm --filter cindy-headless verify;提交/PR 门禁遵循根 AGENTS.md 和 development-workflow.md,不豁免涉及依赖锁或测试调度的全量门禁。
diff --git a/apps/cindy-headless/CINDY_FEATURE_PARITY.md b/apps/cindy-headless/CINDY_FEATURE_PARITY.md
new file mode 100644
index 0000000000..9a617a9943
--- /dev/null
+++ b/apps/cindy-headless/CINDY_FEATURE_PARITY.md
@@ -0,0 +1,166 @@
+# Cindy to Headless feature parity
+
+This inventory applies to Cindy Headless `0.4.3`, based on Cindy upstream commit
+`fa3fc88d37d205ea993a67d85612fa9a5436fae5`. A feature is considered available
+only when the Headless CLI or Harbor adapter can exercise it; vendored source
+alone is not sufficient.
+
+## Upstream integration audit: 2026-10-12
+
+PR #4750 is synchronized with `fa3fc88d37d205ea993a67d85612fa9a5436fae5`
+without rewriting its original commits. This is a compatibility update, not a
+new benchmark capability or a live-model validation result.
+
+| Classification | Upstream area | Headless impact and verification |
+|---|---|---|
+| COMPATIBLE | `Maker`, `Session`, continuation and close lifecycle | Existing local session calls remain type-compatible. The real-Session Headless regression covers intermediate continuation events and a subsequent result-only turn. New optional remote-device hooks are not supplied. |
+| COMPATIBLE | Core tool-loop detection, asynchronous questions and event projection | Core behavior is inherited. Headless does not inject an auxiliary loop reviewer or an interactive UI; these are not exposed as new Profile switches. |
+| COMPATIBLE | Memory storage serialization and versioned edits | The existing isolated Memory provider uses the shared implementation; no new storage API or Desktop editing interface is introduced. |
+| HEADLESS_UPDATE | Shared host prompt | Refresh all three frozen production prompts from the already merged Desktop templates and regenerate their digests/locks. The upstream application-update instruction is preserved verbatim for prompt parity; it does not install updater tools in Headless. |
+| HEADLESS_UPDATE | `tools/{claude,codex,pi}/latest.json` | Align example Profile versions with the repository's existing pins (Claude Code 2.1.280, Codex 0.159.2, Pi 1.0.2). No upstream runtime pin is changed. |
+| HEADLESS_UPDATE | Bundled ESM dependency initialization | Both CJS build entrypoints preserve `import.meta.url` using the delivered file URL. An actual Node subprocess starts each CLI outside the checkout; source-only tests did not catch the previous `createRequire(undefined)` startup failure. |
+| UNSUPPORTED | Device-hosted/shared providers, Desktop updater, UI and account flows | No remote-device host, updater or UI integration is added. A merged Core implementation does not imply Headless support for these host-owned capabilities. |
+
+Profile, catalog and artifact schemas and the Harbor adapter contract are unchanged.
+The Headless version and synchronization baseline identify the new source state;
+live-model benchmarks and a formal Linux distribution still require separate validation.
+
+## Upstream sync audit: 2026-09-20
+
+Range: `14a7eea52703bc211f10d43b4b5af1658382899c..e2089e1e0d9f6f5aceed73b1d3550656d5f72359`.
+
+| Classification | Upstream files / symbols | Headless impact and verification |
+|---|---|---|
+| COMPATIBLE | `agents/codex/index.ts`: host-operation leases, MCP refresh admission, reconnect/compaction settlement | Shared Core fixes apply directly; existing headless host, terminal, timeout and Codex tests cover the unchanged caller contract. |
+| COMPATIBLE | `agents/pi/transport.ts`, `rpc-client.ts`, `session-jsonl-scan.ts`, `translator.ts` | Oversized JSONL recovery, local history scanning and event projection are inherited; verify Pi transport, RPC, translator and history tests alongside Headless regression tests. |
+| COMPATIBLE | `base-agent.ts`, `session.ts`, three agent implementations: optional `toolsDisabled`, pinned Skill invocation, structured auto-review intent, Library read context | These are optional host-owned inputs. Headless retains its frozen Profile, container Full Access and approved Pi Skill path; it does not expose new switches or pretend to supply a Desktop policy proxy. |
+| COMPATIBLE | `memory/manager.ts`: independent Bot scopes and legacy reset ownership | Headless uses isolated runtime state and project Memory; no Bot scope or global Desktop reset is exposed. Existing Headless Memory regression tests cover the current contract. |
+| COMPATIBLE | `agents/pi/cindy-bridge-source.ts`: control-plane writes require explicit decisions | Inherited runtime policy remains in force; unattended profiles do not grant interactive changes to runtime control files. This is not a new capability. |
+| UNSUPPORTED | Desktop `built-in-skills.ts`, account/catalog refresh, oversized-attachment continuation, remote transport, Library host integration | Desktop installation, interactive authorization, account/remote host lifecycle and recovery orchestration are not exposed by the Headless CLI. Core Skill discovery does not imply built-in Skill installation parity. |
+| COMPATIBLE | `packages/model-providers`: Kimi K2.8 metadata/default effort, official Vertex/Azure endpoint matching and preset binding | Core catalog fixes are inherited; Headless keeps explicit profile model, effort, context and endpoint values. Verify model-provider tests; no new model choice is added to the benchmark registry. |
+| COMPATIBLE | Shared prompt sources, `tools/{claude,codex,pi}/latest.json`, dependency lock | Shared production prompt templates and runtime version pins are unchanged. Dependencies use the merged frozen lock; prompt parity and formal bundle/distribution verification remain required. |
+| UNSUPPORTED | Remaining Desktop/Mobile, device-link, UI, updater and packaging changes | Host-specific changes are retained in the checkout but do not become Headless benchmark capabilities. |
+
+No Profile, capability catalog, artifact schema or Adapter contract change is
+introduced by this patch release. Targeted validation uses `cindy-headless verify`
+and the directly affected Maker Core agent/Memory tests. Formal archive and Linux
+binary checks run through `package:release`; no live model benchmark is implied.
+
+## Available in Headless
+
+| Cindy capability | Claude Code | Codex | Pi | Headless evidence |
+|---|---:|---:|---:|---|
+| Multi-turn Maker session | Yes | Yes | Yes | `run --turns-file`, structured terminal events |
+| Cindy production system prompt | Yes | Yes | Yes | Prompt parity tests against Desktop sources |
+| Project context injection | Yes | Yes | Yes | Profile-controlled TOC injection |
+| Cindy Maker Memory | Yes | Yes | Yes | In-process MCP for Claude; authenticated loopback MCP bridge for Codex and Pi |
+| Model identity pinning | Yes | Yes | Yes | Frozen profile and identity artifacts |
+| Explicit context-window pinning | Yes | Yes | Yes | Profile model metadata is passed to each harness context resolver |
+| Explicit effort pinning | Yes | Yes | Yes | Production and generated profiles pin `high`; Pi rejects unsupported `ultra` |
+| Abort, deadline, and bounded cleanup | Yes | Yes | Yes | Signal/deadline handling and result classification |
+| Structured text, thinking, tool, status, and terminal events | Yes | Yes | Yes | Raw and normalized trace artifacts |
+| Token, cache, context, and cost evidence | Yes | Yes | Yes | Backend-specific usage normalization |
+| Container-sandboxed unattended execution | Yes | Yes | Yes | Formal profiles require `containerSandbox=true` |
+| Pinned runtime supply chain | Yes | Yes | Yes | SHA-256 download pins and bundle validation; Pi validates its complete runtime tree |
+| Workspace file/image attachments | Yes | Yes | Yes | Structured `--turns-file`; canonical workspace containment and size/count limits |
+| Frozen remote HTTP MCP | Yes | Yes | Yes | Profile-pinned HTTPS/loopback endpoints; secret values supplied only through named environment variables |
+| BYOM/native provider routing | No | No | Yes | Pi `models.json` native-provider route; exact provider/model/API metadata in the profile and artifacts |
+| Approved project Skills | No | No | Yes | Profile allowlisted roots, Git-root/canonical-path checks, immutable per-session Pi snapshot, per-session denial of every unapproved in-repo Skill, revision/paths and the effective in-repo resource set in artifacts |
+
+Pi is connected through its native RPC and `models.json` compatibility layer.
+Headless does not translate Pi traffic through Claude Code. The bundled Pi
+version is `0.85.1`; its complete runtime directory is required because the
+standalone executable depends on sibling themes and native assets.
+
+## Present in Maker Core but not exposed by the Headless CLI
+
+These capabilities are available to Cindy Desktop through the same current
+`maker-core`, but need a stable Headless command/artifact contract before they
+can be claimed for benchmark runs:
+
+- model and permission changes during a running task;
+- fork, rewind, Pi session-tree navigation, and HTML export;
+- manual compact and runtime extension/command discovery;
+- managed Pi packages and runtime extensions;
+- vision-bridge routing;
+- Orca worker creation and subagent control APIs.
+
+The `a28f9762..b91b78c5` audit identified two runtime candidates that still need
+a separate Headless contract before parity can be claimed: Cindy-provider
+Codex remote compaction/encrypted-context recovery, and the dynamic Pi gateway
+model-catalog metadata surface (`thinkingLevelMap`, compatibility flags, and
+sampling parameters). Codex native compaction remains available, but Headless
+does not falsely advertise the Cindy proxy as active, so the Cindy-provider
+recovery path is not configured. The current Pi gateway baseline is an explicit
+Anthropic-Messages-compatible route; Pi BYOM uses exact API metadata from its
+profile.
+
+The `b91b78c5..abcf92c2b` audit classified the new Maker startup-cleanup
+barriers, Git-normalized Memory scope resolution, per-session disabled-Skill
+snapshots, Pi native package command handling, and Codex/Pi lifecycle fixes as
+compatible internal runtime updates. Existing Headless profiles already pass
+the required working directory, Memory, MCP, permission, and runtime inputs, so
+no new profile field, capability switch, artifact field, or Adapter contract is
+claimed for this release. Desktop account routing, routine triggers, worktree
+recycling, and interactive approval presentation remain host-owned behavior.
+
+The `abcf92c2b..14a7eea52` audit moved Pi project-resource handling into the
+runtime itself: local root tasks now collect `<workspace>/.pi/skills`,
+ancestor `.agents/skills` up to the Git root, `.pi/prompts/*.md`, and
+`.pi/extensions` in place instead of a staged copy, and Pi reports a runtime
+capability manifest. Headless therefore inspects the workspace itself before
+every Pi run: Skills the profile did not approve are denied per session through
+the runtime's disabled-Skill hook, the effective in-repo resource set
+(`piProjectResources` in `identity.json` and `config.json`) is recorded, and the
+Pi binary pin moves to `0.85.1`. The remaining upstream deltas are compatible:
+Pi bot runtime profiles, Pi extension-UI capability export, Codex control-plane
+external auth, and Claude provider-id plumbing are host-owned or unused by
+Headless, and the Desktop/mobile commits since the previous baseline are not
+runtime surface. Prompt templates and extensions have no Headless profile
+field, so they are evidence-only: a frozen profile cannot forbid them, and the
+artifact tells the reviewer exactly which ones the run received.
+
+They remain fail-closed. Headless does not read a user's Desktop configuration,
+Pi home, plugins, extensions, credentials, or approval state. In-repo Pi
+project resources are loaded in place by the runtime, so Headless inspects them
+first, denies unapproved project Skills, and records the exact set the run
+received instead of leaving it implicit.
+
+## Host-specific and intentionally excluded
+
+The following require an Electron, mobile, account, device, or interactive UI
+host and are not Headless runtime features:
+
+- windows, renderer panels, tray, menus, notifications, voice input, and OS
+ permission guides;
+- login/account lifecycle, updater UI, analytics, and desktop settings stores;
+- mobile UI, device-link control, IM presentation, and conversation sharing;
+- plugin panels, OAuth/setup dialogs, media galleries, and user confirmation UI;
+- browser/computer/phone UI control and local app integrations;
+- SSH workspace management and Desktop-owned remote daemon lifecycle.
+
+Headless Pi therefore supports only container-sandboxed
+`bypassPermissions`. `ask` and `auto` are rejected because Harbor has no
+interactive approval channel; accepting them would either hang or weaken the
+Pi permission contract.
+
+## Frozen production profiles
+
+`cindy-production-pi` is the canonical Pi production baseline. It pins Pi
+`0.85.1`, the production prompt digest, attachment policy, project Skill roots,
+and an empty custom-MCP set. BYOM and custom MCP are supported profile fields,
+but remain empty in this baseline so endpoint/tool changes cannot silently alter
+scores. Create a separately named derived profile and freeze its profile digest
+when evaluating either dimension.
+
+`cindy-production-claude` is the Claude Code production baseline and is the
+canonical meaning of “cindy-production-cc”. A second `cindy-production-cc`
+profile is intentionally not created because two names for the same executable,
+prompt, and policy would create ambiguous benchmark identity.
+
+## Update rule
+
+For each Cindy update, inspect `maker-core`, prompt sources, runtime pins,
+Agent translators, usage events, and MCP contracts. Update this inventory and
+add a contract test whenever a capability moves between categories. Historical
+benchmark results remain immutable.
diff --git a/apps/cindy-headless/README.md b/apps/cindy-headless/README.md
new file mode 100644
index 0000000000..ba4c9e1b57
--- /dev/null
+++ b/apps/cindy-headless/README.md
@@ -0,0 +1,407 @@
+# Cindy Headless
+
+Cindy Headless is Cindy's container-friendly runtime. It reuses Cindy's `maker-core` and MCP contracts, then exposes the Claude Code, Codex, and Pi harnesses through a CLI and a Harbor `BaseAgent` adapter. It does not recreate Cindy Desktop, Electron UI, or the Agent binaries.
+
+Version `0.4.3` is based on Cindy upstream commit `fa3fc88d37d205ea993a67d85612fa9a5436fae5`. The CLI compatibility report and bundle manifest expose this revision so source, prompt, and benchmark evidence can be frozen together.
+
+The current feature-by-feature parity inventory is maintained in
+[`CINDY_FEATURE_PARITY.md`](CINDY_FEATURE_PARITY.md).
+
+For the complete Chinese maintenance procedure, including how to diff a user's
+local Cindy checkout from the last synchronized Cindy revision, exclude
+Desktop-only changes, port runtime capabilities, and build a formal bundle,
+see [`UPDATE_AND_PACKAGE.zh-CN.md`](UPDATE_AND_PACKAGE.zh-CN.md).
+
+## Create an upload-ready bundle
+
+For ordinary users, the recommended workflow is one command from a clean,
+committed Cindy checkout:
+
+```powershell
+pnpm --filter cindy-headless package:release
+```
+
+It builds the Linux x64 bundle, verifies it, creates the self-contained `full`
+archive, verifies the archive, and prints its exact path and SHA256. Upload the
+reported `apps/cindy-headless/release/cindy-headless-linux-x64-full-<version>.tar.gz`
+file to Headless Benchmark Tool. Users do not need to create a development
+bundle first.
+
+When only `apps/cindy-headless` contains source changes, the command keeps the
+version synchronized, automatically increments the patch version when needed,
+and creates a signed local checkpoint commit before building. It refuses to
+auto-commit when other Cindy paths are dirty. It may safely reuse the sole
+generated formal manifest when that manifest already identifies the current
+HEAD.
+
+Generated `bundle/` and `release/` directories are ignored. A fresh checkout builds them from source; release manifests and checksums are retained alongside the archive, not committed to Git.
+
+## Local development quick start
+
+From a source checkout on Windows:
+
+```powershell
+# Supply CINDY_HEADLESS_BASE_URL and CINDY_HEADLESS_API_KEY through your environment.
+./apps/cindy-headless/scripts/setup.ps1
+cd <your-harbor-checkout>
+uv run harbor eval execute <freeze-id> --workspace-root . --approve
+```
+
+The bundle directory is useful for local development and direct Harbor work.
+For web upload, use the verified `full` release archive produced by
+`package:release`.
+
+`package:public-runtime` is a separate public-distribution workflow. It creates
+only `cindy-headless-linux-x64-public-runtime-no-vendor-<version>.tar.gz`, which
+does not contain the Claude Code, Codex, or Pi harness binaries. It is not the
+default upload package and must be used only when a no-vendor artifact is
+explicitly requested. The low-level `package:full` command exists for release
+pipeline diagnostics; ordinary formal delivery should use `package:release`.
+
+## Layout
+
+```text
+apps/cindy-headless/src/ Runtime, profiles, benchmark and artifact code
+apps/cindy-headless/profiles/ Pinned backend/model/profile definitions
+apps/cindy-headless/scripts/ Bundle and compatibility verification scripts
+apps/cindy-headless/bundle/ Reproducible Linux x64 bundle output
+apps/cindy-headless/harbor-compatibility.json Harbor adapter contract and pinned features
+```
+
+## Prerequisites
+
+- Node.js 22 and the repository dependencies installed with pnpm.
+- Pinned Linux x64 Claude Code, Codex, and complete Pi runtime distributions for bundle creation.
+- Harbor 0.20 for container tests.
+- Either a temporary isolated Codex home or the unified gateway configuration.
+
+Never put an API key in a profile, manifest, bundle, Git-tracked file or result artifact. Use environment variables or a configuration file outside the repository.
+
+## Local configuration
+
+```powershell
+# Set CINDY_HEADLESS_BASE_URL and CINDY_HEADLESS_API_KEY in your process environment.
+# Alternatively point CINDY_HEADLESS_CONFIG_FILE to a config outside this repository.
+```
+
+The config file is ignored. It supports an Anthropic-compatible gateway for Claude and Pi, and an OpenAI Responses-compatible `/v1` route for Codex. Offline commands such as `version`, `plan` and `report` do not load gateway credentials.
+
+## Build and verify
+
+Run the normal checks:
+
+```powershell
+npm --prefix apps/cindy-headless run typecheck
+npm --prefix apps/cindy-headless test -- --run
+npm --prefix apps/cindy-headless run build
+```
+
+Build the scored Linux bundle with pinned binaries:
+
+```powershell
+$env:CINDY_CLAUDE_BINARY = 'D:\path\to\pinned\claude'
+$env:CINDY_CODEX_BINARY = 'D:\path\to\pinned\codex'
+$env:CINDY_PI_BINARY = 'D:\path\to\pinned\pi-runtime\pi'
+npm --prefix apps/cindy-headless run bundle:linux
+npm --prefix apps/cindy-headless run verify:bundle
+```
+
+One bundle contains Claude Code, Codex, and Pi. Harbor discovers all three from
+`bundle-manifest.json` and selects exactly one harness for each Trial through
+the effective profile. Harness protocols remain independent and are never
+translated into one another.
+
+`bundle-manifest.json` records the vendored source commit, upstream Cindy commit, prompt digests, binary digests, observed versions and Headless contract version. Rebuild it whenever runtime source or pinned binaries change.
+
+The bundle does not contain a Harbor adapter. Scored Benchmark runs
+use the adapter maintained in the pinned Harbor checkout:
+`harbor.agents.installed.cindy_headless:CindyHeadlessAgent`. Run Harbor from
+its own checkout and pass `--workspace-root` there. Keep `bundle_dir` and
+`profile_path` relative to that root; never copy an adapter into this repo or
+put a maintainer's local path in a job file. The required adapter contract is
+recorded in `harbor-compatibility.json`.
+
+`bundleMode: "formal"` means only that the bundle was built from a clean,
+committed source state. `bundleMode: "development"` identifies a dirty local
+build. It is an identity field in the same bundle format, not a second package
+or archive workflow.
+
+Do not weaken this boundary for convenience. The normal user workflow produces
+a formal bundle from a local checkpoint commit; that commit does not need to be
+pushed or merged. A dirty checkout is supported only for diagnostic builds by
+setting `CINDY_HEADLESS_ALLOW_DIRTY_BUNDLE=1`, but a scored bundle must remain
+clean.
+
+## CLI
+
+Inspect a bundle's credential-free web capability catalog:
+
+```powershell
+node apps/cindy-headless/dist/cli.cjs capabilities --manifest apps/cindy-headless/bundle/linux-x64/bundle-manifest.json
+```
+
+New bundles publish `capabilityCatalog` in `bundle-manifest.json`. It declares
+all packaged harnesses, the deliberately maintained set of profile-controlled
+feature switches, and explicit defaults used by upload services to render
+configuration choices. It is not an automatic inventory of every Cindy feature. This catalog
+describes what the package offers; the effective profile and runtime evidence
+record what a particular Run actually enabled.
+
+The single source of truth is `capability-registry.json`, maintained explicitly
+by the Headless maintainers. Every Cindy update still requires a source diff and
+feature-parity review, but a discovered Cindy change is added to `features` only
+when it is intended to become a user-selectable evaluation switch. The build copies the registry into
+`capabilityCatalog` automatically; no second feature list in the build script
+or web client should be maintained. Registry entries describe controls and
+declared adapter coverage only. Route support, proxy enforcement, and runtime
+evidence must still be checked before a capability is reported as enforced.
+
+This README is a quick reference, not a replacement for the operating manual.
+For the required registration fields, feature/control distinction, harness
+mapping, security rules, contract tests, and formal-bundle procedure, follow
+[`UPDATE_AND_PACKAGE.zh-CN.md`](UPDATE_AND_PACKAGE.zh-CN.md), section 5.1.
+
+Generate a portable profile directly from the bundle manifest, then validate it:
+
+```powershell
+node apps/cindy-headless/dist/cli.cjs profile generate --manifest apps/cindy-headless/bundle/linux-x64/bundle-manifest.json --harness codex --output apps/cindy-headless/bundle/linux-x64/effective-profiles/codex.json
+node apps/cindy-headless/dist/cli.cjs profile validate --profile apps/cindy-headless/bundle/linux-x64/effective-profiles/codex.json
+```
+
+Use `--features` with a comma-separated list to opt into declared boolean switches.
+Compaction and the packaged Cindy system prompt currently follow the maintained
+profile defaults and are not exposed as web switches. A
+custom Pi model additionally requires `--provider`, `--base-url`, `--api`,
+`--context-limit`, and `--max-output-tokens`; the generator writes the matching
+`nativeProviders` entry so the result remains valid and reproducible.
+Keep generated profiles inside the bundle before upload. Their binary and
+prompt paths are intentionally relative to the profile location so the whole
+bundle remains relocatable in the Harbor task container.
+
+Validate a profile and inspect compatibility:
+
+```powershell
+node apps/cindy-headless/dist/cli.cjs profile validate --profile apps/cindy-headless/profiles/cindy-production-codex/profile.example.json
+node apps/cindy-headless/dist/cli.cjs compatibility-report --profile apps/cindy-headless/profiles/cindy-production-codex/profile.example.json
+node apps/cindy-headless/dist/cli.cjs doctor --profile apps/cindy-headless/profiles/cindy-production-codex/profile.example.json
+node apps/cindy-headless/dist/cli.cjs doctor --profile apps/cindy-headless/profiles/cindy-production-pi/profile.example.json
+```
+
+Run a local task:
+
+```powershell
+node apps/cindy-headless/dist/cli.cjs run --profile <profile.json> --task "Inspect the repository and report the result" --working-dir . --output-dir results
+```
+
+The output directory contains identity, config, trace, usage and result artifacts. Prompt bodies and secrets are excluded. Usage artifacts use schema 2 and explicitly report `COMPLETE`, `PARTIAL` or `MISSING`; timeout results must not be interpreted as exact zero token or cost. They also expose `usageCompleteness`: `exact` for a complete provider event, `lower-bound` for observed partial usage, and `incomplete` when no trustworthy count exists. Reports count these categories separately. Evaluation report schema 2 sets `totals.costUsd` to `null` when any trial has unknown cost; `knownCostUsd`, `costKnownCount` and `costMissingCount` expose the auditable known subtotal. A configured cost budget fails closed with `cost-unknown` instead of silently treating missing cost as zero. A disconnected provider stream is infrastructure failure; it is not converted into an agent failure or an estimated token count.
+
+Harbor's token fields overlap by design: `n_input_tokens = inputTokens + cacheCreationTokens + cacheReadTokens`, `n_cache_tokens = cacheReadTokens`, and `n_output_tokens = outputTokens`. Do not add `n_cache_tokens` to `n_input_tokens` a second time. The original components and completeness flags remain in `usage.json`.
+
+`identity.json.identityEvidence` identifies whether each actual-identity field came from a provider event, configuration, an operator assertion, or is unknown. These are provenance labels, not independent gateway attestation. Unless a gateway supplies a request-ID lookup or signed billing record, Headless cannot independently prove the actual upstream provider/model and records `gatewayAttested: false`.
+
+`trace.raw.jsonl` is the lossless native Cindy event stream. `trace.jsonl` is
+the normalized analysis stream: when a provider emits incremental `text` or
+`thinking` deltas followed by an `isFinal` snapshot, the earlier deltas are
+removed from the normalized stream so downstream analysis does not count the
+same content twice. Headless itself does not emit Harbor's `trajectory.json`;
+the current Cindy Harbor adapter preserves it as a Cindy-native artifact and
+declares `SUPPORTS_ATIF = False` rather than claiming an unimplemented
+conversion.
+
+## Harbor smoke test
+
+Run the Harbor workspace's hello-world smoke/freeze workflow from its own
+repository. Set `--workspace-root` to the Harbor workspace root; job paths must
+be relative to that root. Use a unique `run_id` and frozen `manifest_digest`.
+
+## Collect and report results
+
+Harbor writes the raw trial artifacts under its configured jobs/evaluation
+output directory. Use the Harbor viewer or its report tooling from the Harbor
+checkout to inspect those artifacts, then pass a normalized results file to:
+
+```powershell
+node apps/cindy-headless/dist/cli.cjs report --manifest <manifest.json> --results <results.json> > report.json
+```
+
+Reports include per-agent and per-benchmark pass rates, paired outcomes, four-state statuses, tokens, cost, duration, provider routing, unsupported combinations and Wilson 95% intervals. A hard-30 list is publishable only after freezing at least 30 independent historical task records with `freeze-hard-30`.
+
+Report input is checked against the manifest's supported variant/model/task/repetition
+cells. Duplicate cells, conflicting arm indices, rewards outside [0, 1], and invalid
+usage/cost values are rejected before aggregation. Missing arm indices follow the
+manifest's variant order. Paired outcome counts apply only to a two-variant manifest;
+other reports retain per-agent totals without inventing binary comparisons. Pair IDs
+are JSON-encoded task/model/repetition tuples so colons inside IDs cannot collide.
+
+Headless waits for Session's product-turn terminal for the current attempt, including
+automatic continuations; an intermediate SDK `done` or idle status does not end a run.
+Low-level packaging requires the bundle's digest-matched CLI files and uses its frozen
+profiles. It never falls back to the separate development `dist/` directory.
+
+
+The adapter is intentionally maintained in Harbor, not here. To run a local
+smoke from a source checkout:
+
+```powershell
+$root = (Resolve-Path ..\harbor).Path # any Harbor checkout; do not hard-code a maintainer path
+uv run --project $root harbor eval execute <freeze-id> --workspace-root $root --approve
+```
+
+The `<freeze-id>` job must use the registered `cindy-production` agent backed
+by `harbor.agents.installed.cindy_headless:CindyHeadlessAgent`. Harbor resolves
+the bundle and profile paths relative to `--workspace-root`, so the same job
+works after cloning to another directory. Use `harbor-compatibility.json` to
+check the required Harbor commit and adapter contract before a scored run.
+
+The `cindy-claude-parity-all-off` profile is a whole-surface parity control. Because it changes Maker Memory, project context, compaction and the Cindy system prompt together, it cannot attribute an outcome to any one dimension. Use a derived profile with exactly one declared `changedDimensions` entry for causal comparisons.
+
+## Maintenance after Cindy updates
+
+The checklist below is the short policy summary. Follow
+[`UPDATE_AND_PACKAGE.zh-CN.md`](UPDATE_AND_PACKAGE.zh-CN.md) for exact commands,
+decision points, expected outputs, upload layout, and rollback rules.
+
+Treat Headless as a compatibility surface, not a floating checkout:
+
+1. Update/rebase the Cindy source and inspect changes to `maker-core`, Agent event types, usage, Memory/MCP and Desktop prompt sources.
+2. Run typecheck, all tests, prompt parity and compatibility tests.
+3. Rebuild the Linux bundle with pinned binaries and run `verify:bundle`.
+4. Run the Harbor hello-world smoke test, then a small multi-task pilot before a scored benchmark.
+5. Retain the new bundle manifest and checksums with the release archive; generated bundle output is not committed.
+
+Classify changes as `COMPATIBLE` (rebuild only), `REQUIRES_ADAPTER_UPDATE` (Headless or Harbor code changes), or `UNSUPPORTED` (Desktop-only capability). Do not silently enable new permissions, providers or throughput caps in a scored run.
+
+By default the bundle builder refuses a dirty worktree. Local development can
+set `CINDY_HEADLESS_ALLOW_DIRTY_BUNDLE=1`; the resulting manifest is marked
+`bundleMode: "development"` and must not be used for a scored run. In both
+modes, `generatedAt`, `cindyCommit`, `cindyUpstreamCommit`, and the digests bind
+the artifact to its inputs.
+
+### When upstream changed before a smoke test
+
+Do not silently run newly updated Cindy sources with an old Headless bundle. Before the smoke test, compare the vendored source commit and `package.json.cindyUpstreamCommit` with `bundle/linux-x64/bundle-manifest.json.cindyCommit` and `.cindyUpstreamCommit`, then choose one of these paths:
+
+1. **Test the previous frozen bundle:** keep the old Cindy checkout and bundle together, record both revisions, and state that the smoke test covers the previous frozen bundle. This is valid for regression checks, but it does not validate the new upstream commit.
+2. **Upstream change is `COMPATIBLE`:** sync/rebase the change, run all Headless tests, rebuild and verify the bundle, update the frozen manifest digest, then run Harbor smoke. Typical examples are internal `maker-core` fixes that preserve public contracts.
+3. **Change is `REQUIRES_ADAPTER_UPDATE`:** stop the scored run. Update Headless and/or the Harbor adapter, add contract regression tests, rebuild the bundle, run smoke and a small pilot, then freeze new revisions. This applies to changes in Agent APIs, event/usage schemas, Memory/MCP behavior, profiles, permissions or provider routing.
+4. **Change is `UNSUPPORTED`:** do not imitate or partially enable it in Headless. Record the Desktop-only capability and applicable scope in the compatibility/report output.
+
+Before any scored benchmark, freeze and verify the Cindy commit, Headless commit, bundle manifest digest, Agent binary versions, prompt digests, profile digest, model/endpoint and Benchmark revision. If any one of these differs from the planned run, regenerate the plan or stop the run; never mix a new source checkout with artifacts from an older bundle.
+
+The canonical Pi baseline is `cindy-production-pi`. Its profile enables
+workspace-confined file/image turns and Cindy-approved project Skills from
+`.pi/skills` and `.agents/skills`; the exact discovered Skills are snapshotted
+per session. Pi loads local root task project resources in place, so Headless
+inspects the workspace before every run: Skills the profile did not approve are
+denied for that session, and `identity.json.piProjectResources` (mirrored in
+`config.json`) records the effective in-repo Skills, prompt templates, and
+extensions the run received. Prompt templates and extensions have no profile
+switch yet, so they are evidence-only. Its custom MCP list is deliberately frozen empty. The canonical
+Claude Code baseline remains `cindy-production-claude` (also referred to as
+“CC”); do not create a duplicate `cindy-production-cc` identity.
+
+The Pi gateway route in this baseline is deliberately fixed to the
+Anthropic-Messages-compatible Claude model declared by the manifest. Pi BYOM
+profiles carry their own exact API and model metadata. Headless does not yet
+claim Cindy Desktop's dynamic Pi gateway catalog resolution for arbitrary
+Gateway models (`compat`, `samplingParams`, or custom `thinkingLevelMap`).
+
+Structured turns preserve the old string-array format and add attachments:
+
+```json
+[
+ {
+ "text": "Inspect the attached fixture.",
+ "attachments": [
+ { "type": "file", "path": "fixtures/input.txt", "mimeType": "text/plain" }
+ ]
+ }
+]
+```
+
+Attachment paths are relative to `--working-dir`; absolute paths, parent
+traversal, symlink escapes, non-files, and policy limit violations fail closed.
+Remote MCP and Pi BYOM declarations live in the profile. They pin endpoint,
+transport/API and exact model metadata, while bearer/header/API-key values are
+read only from the environment-variable names declared by that profile.
+
+## Profiles
+
+`model.contextLimit` is optional for Claude Code and Codex, and required for Pi. When present, Headless injects that exact
+context window into Maker Core for the selected model; when omitted, the
+underlying Agent/model capability remains authoritative. This setting controls
+Headless context accounting and compaction thresholds, but does not increase an
+upstream model or gateway's actual context capacity.
+
+`run` defaults to `--timeout-owner headless`. In this standalone mode,
+`--timeout-ms` is enforced by Headless and defaults to **1800 seconds
+(1,800,000 ms)**. Headless derives the Maker turn-stall watchdog from that
+deadline and records `timeoutOwner`, `timeoutMs`, and `turnStallMs` in
+`config.json`.
+
+When Harbor owns the run, the Cindy adapter must pass
+`--timeout-owner external` and must not pass `--timeout-ms`. External mode does
+not create a Headless scoring deadline and disables Headless-injected turn and
+upstream-idle watchdogs. Harbor gives the Agent the complete task budget, marks
+the timeout at its own deadline, and signals Headless during the non-scoring
+cleanup grace period. Headless keeps its signal handlers installed until result,
+usage, identity, and trace artifacts have been persisted.
+
+The five-second session-close bound applies only after execution has ended or
+been interrupted. It protects artifact persistence from a stuck SDK close and
+does not subtract time from the Agent's scoring budget.
+
+## Building a usable Harbor bundle
+
+Build the scored bundle from a clean, committed feature branch. It must be
+Linux x64 and include `dist/cli.cjs`, `dist/eval-cli.cjs`, Node, all three
+harness runtimes, all three prompts, profiles, and `bundle-manifest.json`.
+Never mix a newly built bundle with an older profile or upload an unverified
+directory.
+
+Minimum bundle checks:
+
+```powershell
+pnpm --filter cindy-headless typecheck
+pnpm --filter cindy-headless test
+pnpm --filter cindy-headless build
+pnpm --filter cindy-headless bundle:linux
+pnpm --filter cindy-headless verify:bundle
+```
+
+Register the resulting runtime in Headless Benchmark Tool, run package
+verification, and require `READY` before a Harbor benchmark. A one-task Harbor
+smoke should verify `config.json`, `identity.json`, `result.json`, `usage.json`,
+`trace.jsonl`, and `trace.raw.jsonl`; only then admit the bundle for scored
+runs. Preserve its exact manifest and the command used to reproduce it.
+
+The Kimi gateway examples are
+`profiles/cindy-production-claude/profile.kimi-k3.example.json` and
+`profiles/cindy-claude-parity-all-off/profile.kimi-k3.example.json`. They pin a
+1M declared context window; supply gateway credentials through the ignored
+local config file, never by editing these tracked profiles.
+
+For the DeepSeek smoke campaign, use
+ `profiles/cindy-production-claude/profile.deepseek-v4-flash.example.json`.
+It pins `deepseek/deepseek-v4-flash` and a 1,048,576-token declared context
+window. The gateway must actually advertise/support this model; the profile
+does not turn a gateway route into an independent model attestation.
+
+For the production Pi benchmark, use
+`profiles/cindy-production-pi/profile.deepseek-v4-flash.example.json`. It uses
+the neutral `example-gateway` native provider while preserving the complete
+`deepseek/deepseek-v4-flash` model ID on the OpenAI-compatible request. Do not
+rename that provider to `deepseek`: Pi's built-in provider handling would send
+the bare `deepseek-v4-flash` ID, which the benchmark gateway rejects.
+
+Production profiles are pinned and should be changed only for an explicit experiment:
+
+- `cindy-production-claude`
+- `cindy-production-codex`
+- `cindy-production-pi`
+- `cindy-native-memory`
+- `cindy-planning`
+- `cindy-no-compaction`
+- `cindy-tool-surface`
+
+Keep `profile.local-smoke.json` restricted to local testing. In particular, unsandboxed bypass permission is explicitly unsafe and must never be used for untrusted benchmark tasks.
diff --git a/apps/cindy-headless/UPDATE_AND_PACKAGE.zh-CN.md b/apps/cindy-headless/UPDATE_AND_PACKAGE.zh-CN.md
new file mode 100644
index 0000000000..54b3d21289
--- /dev/null
+++ b/apps/cindy-headless/UPDATE_AND_PACKAGE.zh-CN.md
@@ -0,0 +1,461 @@
+# Cindy Headless 同步与正式出包手册
+
+本文用于从用户已经更新完毕的本地 Cindy 仓库中识别产品变化、同步 Headless 能力,
+并直接生成可上传的 Linux x64 formal bundle。执行者可以是开发者,也可以是读取本文
+后操作仓库的 AI。
+
+Headless 必须保留在完整 Cindy checkout 的 `apps/cindy-headless` 中,因为构建会直接
+读取 `packages/maker-core`、MCP 契约和 Desktop 的共享 prompt 源。不要把该目录单独
+复制到一个脱离 Cindy 的空仓库中构建。
+
+## 1. 版本与同步基线
+
+Headless 记录两个不同版本:
+
+| 字段 | 位置 | 含义 |
+|---|---|---|
+| Headless 版本 | `apps/cindy-headless/package.json.version` | Headless CLI、Profile 和 artifact 契约版本 |
+| Cindy 同步基线 | `apps/cindy-headless/package.json.cindyUpstreamCommit` | 上一次完成 Headless 适配的 Cindy 产品代码 commit |
+
+`cindyUpstreamCommit` 是快速检测 Cindy diff 的唯一机器可读游标,必须是完整 40 位
+Git SHA。不要只记录分支名、日期或语义版本;它们不能唯一标识源码。发布说明可以
+额外记录 Cindy tag,但 commit SHA 才是构建与审计依据。
+
+bundle manifest 还记录构建时整个 checkout 的 `cindyCommit`、Headless 版本、dirty
+状态,以及 CLI、prompt、profile、lockfile 和 binary 摘要。因此不需要再创建第二份
+容易漂移的“上次同步版本”文件。
+
+## 2. 准备用户的 Cindy checkout
+
+用户可以在任意本地功能分支操作,不要求先合并或 push。在仓库根目录执行:
+
+```powershell
+$headlessPackage = Get-Content apps/cindy-headless/package.json | ConvertFrom-Json
+$oldCindy = $headlessPackage.cindyUpstreamCommit
+$newCindy = git rev-parse HEAD
+
+git status --short
+git branch --show-current
+git show -s --format='%H %cI %s' $oldCindy
+git show -s --format='%H %cI %s' $newCindy
+node --version
+pnpm --version
+```
+
+前置要求:
+
+- Node.js 22 或更高版本;
+- `oldCindy` 和 `newCindy` 都能由 Git 解析;
+- 明确当前未提交修改属于谁,不得 reset、checkout 或覆盖用户文件;
+- `apps/cindy-headless`、`packages/maker-core`、Desktop prompt 源存在;
+- 已执行 `pnpm install --frozen-lockfile`,或已审查用户主动更新的 lockfile;
+- 构建机器能取得锁定版本的 Linux x64 Node、Claude Code、Codex 和完整 Pi runtime。
+
+如果 Cindy 新功能尚未提交,先创建本地 checkpoint commit。它不需要推送:
+
+```powershell
+git add <本次已审查的-Cindy-文件>
+git commit -s -m "feat: checkpoint Cindy changes for Headless sync"
+$newCindy = git rev-parse HEAD
+```
+
+不要使用 `git add -A`,避免把其他工作一并提交。
+
+## 3. 生成 Cindy 更新清单
+
+先确认提交关系。如果旧基线不是新提交的祖先,通常表示 rebase、切错分支或基线填写
+错误,不能直接继续:
+
+```powershell
+git merge-base --is-ancestor $oldCindy $newCindy
+if ($LASTEXITCODE -ne 0) {
+ throw '旧 Cindy 基线不是当前 Cindy 的祖先,请确认分支或使用 merge-base 人工审计'
+}
+```
+
+生成提交和文件总览:
+
+```powershell
+git log --oneline --decorate $oldCindy..$newCindy
+git diff --stat $oldCindy..$newCindy
+git diff --name-status $oldCindy..$newCindy > cindy-headless-sync-files.txt
+```
+
+再按影响面分组检查:
+
+```powershell
+# Agent API、事件、usage、compaction、模型和运行行为
+git diff $oldCindy..$newCindy -- packages/maker-core/src/agents
+
+# Memory、MCP、project context 和共享协议
+git diff $oldCindy..$newCindy -- `
+ packages/maker-core/src/memory `
+ packages/maker-core/src/mcp `
+ packages/mcps
+
+# Headless 使用的 Desktop prompt 与 host 编排线索
+git diff $oldCindy..$newCindy -- apps/desktop/src/main/maker-host
+
+# Harness binary 版本、下载地址和 SHA256
+git diff $oldCindy..$newCindy -- tools/claude tools/codex tools/pi
+
+# 依赖和 workspace 契约
+git diff $oldCindy..$newCindy -- package.json pnpm-lock.yaml pnpm-workspace.yaml
+```
+
+路径可能随 Cindy 演进变化。如果路径不存在或 diff 为空,用符号搜索继续定位:
+
+```powershell
+rg -n "AgentEvent|Usage|compaction|projectContext|makerMemory|nativeMemory" `
+ packages apps/desktop/src/main
+rg -n "system-prompt|Mcp|attachment|provider|contextLimit|effort" `
+ packages apps/desktop/src/main
+```
+
+审计记录至少包含:commit、变更文件、相关符号、Headless 分类、修改位置和测试。临时
+`cindy-headless-sync-files.txt` 在审计结束后删除,不应提交。
+
+## 4. 判断哪些内容进入 Headless
+
+不要按“文件位于 Desktop”机械判断。应按能力能否在无 UI、无人值守容器中表达判断。
+
+### 直接同步或适配
+
+- Agent 构造参数、生命周期、事件和 terminal status;
+- 模型/provider/effort/context limit 与 compaction;
+- token、cache、cost 和错误分类;
+- Maker Memory、MCP、project context;
+- Claude Code、Codex、Pi 的启动和协议;
+- 系统 prompt 的产品行为约束;
+- attachment、Skills、remote MCP 等可冻结的非交互能力。
+
+Headless 应直接调用更新后的 `maker-core` API,不要复制一套 core 实现。
+
+### 提取语义后适配
+
+以下内容可能位于 Desktop,但不能直接丢弃:共享系统 prompt;UI 操作最终传给 Agent
+的配置、模型或权限;影响 Agent 行为的默认值;Desktop 组装的 Memory、MCP 或
+project-context 输入。
+
+只提取“最终传给 Agent 的数据和规则”,在 Profile/Headless host 中用确定、可冻结、
+无交互的形式表达。不要复制 Electron IPC、React state 或窗口生命周期。
+
+### 直接剔除
+
+- React 页面、窗口、面板、菜单、托盘和通知;
+- Electron IPC、渲染进程状态和 OS UI 权限向导;
+- 登录界面、OAuth 弹窗、更新器和埋点展示;
+- 手机、语音、媒体预览和人工确认交互;
+- 仅用于展示且不改变 Agent 输入或执行的格式化逻辑。
+
+剔除不等于忘记。若它被视为 Cindy 功能,应在 `CINDY_FEATURE_PARITY.md` 的
+Desktop-only 区域记录原因。
+
+### 分类结论
+
+| 分类 | 判断 | 操作 |
+|---|---|---|
+| `COMPATIBLE` | 现有 Headless 已覆盖,契约不变 | 更新基线并回归测试 |
+| `HEADLESS_UPDATE` | 可无 UI 使用,但 Headless 尚未暴露或记录 | 修改 Headless 并添加测试 |
+| `ADAPTER_UPDATE` | 启动参数、挂载、环境变量或 artifact schema 变化 | 同步 Adapter 后才能跑测 |
+| `UNSUPPORTED` | 无法脱离 UI、账号、设备或人工批准 | 不实现,记录限制 |
+
+每次更新 Cindy 都必须扫描源码差异、判断 Headless 影响并更新 parity;但 Cindy 新增功能
+不会因此自动注册或出现在上传服务。只有维护者明确决定将其作为跑测变量,并同时满足
+以下条件时,才成为网页可选择能力:
+
+1. Headless 能开启或关闭;
+2. Profile schema 能表达并 fail closed;
+3. `capabilityCatalog` 声明 harness 支持范围和默认值;
+4. Adapter 能传递所需数据;
+5. identity/config/result/trace 能证明实际状态;
+6. 存在 on、off 和非法组合的契约测试。
+
+## 5. 根据 Cindy 变化更新 Headless
+
+| 位置 | 责任 |
+|---|---|
+| `src/host.ts` | 建立会话、注入能力、执行和 evidence |
+| `src/profile.ts` | Profile schema、默认值、互斥关系和 fail-closed 校验 |
+| `src/profile-generation.ts` | capability 选择到动态 Profile 的确定性映射 |
+| `src/compatibility.ts` | 支持状态和不兼容原因 |
+| `scripts/build-linux-bundle.mjs` | bundle 内容与 `capabilityCatalog` |
+| `profiles/**` | 少量长期生产基线,不为每种组合创建静态 Profile |
+| `CINDY_FEATURE_PARITY.md` | 已支持、待适配和 Desktop-only 清单 |
+| `harbor-compatibility.json` | Adapter 契约版本和摘要 |
+
+实现顺序:
+
+1. 更新 `maker-core` 调用,使已有 Headless 行为恢复正确;
+2. 判断变化属于内部兼容更新、长期 Profile 配置,还是需要公开的新跑测变量;
+3. 必要时增加 Profile 字段和严格校验,并在 host 中映射到实际 Cindy API;
+4. 在 artifact 中记录影响跑测复核的 requested 与 effective 状态;
+5. 仅当它是明确的网页开关时,加入对应 harness 的 catalog feature;
+6. 为公开开关增加开启、关闭和非法组合测试;
+7. 更新 parity 文档;
+8. 只有外部执行契约变化时才更新 Adapter。
+
+普通 bundle、prompt 或现有 Profile 字段更新不要求修改 Adapter。新 harness 协议,或
+需要新挂载、secret、参数、artifact 的 feature,通常必须修改 Adapter。
+
+### 5.1 能力注册表由维护者显式维护
+
+能力注册表的唯一正本是 `apps/cindy-headless/capability-registry.json`。不要在
+`compatibility.ts`、`build-linux-bundle.mjs`、网页代码或 manifest 中另外维护一份
+feature 列表。构建脚本只负责读取维护者确认过的注册表,并把它复制/编译到 bundle 的
+`bundle-manifest.json.capabilityCatalog`;它不会扫描 Cindy 源码并自动注册功能。
+
+扫描 Cindy 源码仍是每次同步上游的必做步骤。扫描的目标是发现 API、运行行为、默认值、
+证据和兼容性变化,以便正确更新 Headless;扫描结果默认记录在实现、测试或
+`CINDY_FEATURE_PARITY.md`,并不默认进入网页功能列表。
+
+先判断新内容属于 `features` 还是 `controls`:
+
+| 区域 | 用途 | 例子 | 是否直接驱动 Profile `--features` |
+|---|---|---|---|
+| `features` | 维护者明确开放、可由 Headless Profile 独立开启/关闭的布尔跑测变量 | `projectContext`、`makerMemory`、`attachments` | 是 |
+| `controls` | 结构化配置、路由或执行层控制面,不作为普通功能开关 | `nativeProviders`、`remoteHttpMcp`、`permissionMode`、`contextLimit` | 否 |
+
+新增一个 Profile 功能时,至少完成以下登记:
+
+```json
+{
+ "features": {
+ "exampleFeature": {
+ "type": "boolean",
+ "control": "profile",
+ "default": false,
+ "label": "Example Feature",
+ "description": "Credential-free description for discovery"
+ }
+ },
+ "harnesses": {
+ "claude-code": {
+ "features": ["exampleFeature"]
+ }
+ }
+}
+```
+
+实际编辑时必须保留对应 harness 原有字段(`id`、模型和已有 features),上面的片段
+只是字段形状示例。`features` 当前只接受适合网页直接勾选的布尔变量;对象、数组、
+整数和枚举配置应放入 `controls`,不能为了显示在网页上而伪装成 boolean。需要互斥或安全约束时,在顶层 `constraints` 增加声明,
+并在 `src/profile.ts` 中实现 fail-closed 校验。约束只适用于部分 Harness 时必须填写
+`harnesses`,不能扩大成全局限制。例如 Cindy 的 Claude Code/Codex 在启用 Maker
+Memory 时会关闭 Native Memory,但 Pi 允许 Maker Memory 与 Pi Auto Memory 同时开启,
+因此该互斥约束只登记 `harnesses: ["claude-code", "codex"]`。
+
+新增配置/路由/执行控制时,登记在 `controls`,并写清楚控制层和证据要求:
+
+```json
+{
+ "controls": {
+ "exampleLimit": {
+ "type": "integer",
+ "control": "model-route",
+ "minimum": 1,
+ "enforcement": "client-request"
+ }
+ }
+}
+```
+
+`controls` 只表示 Headless 可以发现和描述该控制,不表示上游模型或外部 Proxy 已执行。
+涉及密钥的 MCP、Proxy 或 Provider 只能登记模板、环境变量名和
+`credentialSafe: true` 等元数据,禁止写入 URL 中的 token、API key 或本地路径。
+`throughputCap` 必须同时要求外部执行和运行证据;没有证据时只能报告
+`DETECTED_BUT_NOT_ENFORCED`。
+
+登记完成后按以下顺序验证:
+
+```powershell
+Get-Content apps/cindy-headless/capability-registry.json | ConvertFrom-Json
+pnpm --filter cindy-headless typecheck
+pnpm --filter cindy-headless test
+$env:CINDY_HEADLESS_ALLOW_DIRTY_BUNDLE = '1'
+pnpm --filter cindy-headless bundle:linux
+Remove-Item Env:CINDY_HEADLESS_ALLOW_DIRTY_BUNDLE
+pnpm --filter cindy-headless verify:bundle
+node apps/cindy-headless/dist/cli.cjs capabilities --manifest apps/cindy-headless/bundle/linux-x64/bundle-manifest.json
+```
+
+对新增网页开关至少增加三类契约测试:功能开启、功能关闭、非法组合/不支持 harness。检查输出时确认
+新能力同时出现在注册表、生成的 manifest 和 capabilities CLI;不要手工编辑生成的
+manifest。正式出包前必须按本手册第 8、9 节创建 clean commit 并重新构建 formal bundle。
+
+## 6. 更新版本记录
+
+完成审计和适配后,把 `package.json.cindyUpstreamCommit` 更新为 `$newCindy`。该 SHA
+应指向用户 Cindy 功能完成的 commit,通常是 Headless 适配提交的父提交或祖先。使用
+结构化 JSON 工具或补丁修改,不要用不受控字符串替换。
+
+Headless `version` 的建议:
+
+- 仅同步内部 Cindy 修复且对外契约不变:至少 bump patch 后发布;
+- Profile、catalog 或 artifact 增加向后兼容字段:bump minor;
+- 删除、重命名或改变现有 CLI/Profile/artifact 语义:bump major;
+- 每一个新的正式源码状态都必须使用新的 Headless version;日常查看和选择包以版本号为主,
+ SHA256 用于确认同一版本文件是否完全一致;
+- 同一 Headless version 不应对应多个进入正式跑测的不同 bundle;同一 commit 的同一正式包
+ 可以重复生成或重复上传,不需要再次升版本;
+- `package:release` 检测到 Headless 有新改动但版本仍与上一个 bundle 相同时,会自动提升
+ patch 版本,并同步 package、兼容性契约、运行时常量和版本说明。
+
+确认没有残留旧基线:
+
+```powershell
+rg -n $oldCindy apps/cindy-headless
+rg -n 'cindyUpstreamCommit' apps/cindy-headless
+```
+
+更新源码中的 package metadata、profile lock、compatibility 和文档;不要手工修改生成
+的 `bundle-manifest.json`。
+
+## 7. 定向验证
+
+日常 Headless 迭代先执行定向验证;提交与 PR 仍须遵循根 AGENTS.md 的
+`test:unit:related` 门禁。涉及锁文件、workspace 或测试调度时不得跳过其全量回退。
+定向入口:
+
+```powershell
+pnpm --filter cindy-headless verify
+```
+
+若 Cindy 变化影响共享 `maker-core`,再补充运行直接受影响 package 的定向测试,不要
+默认执行所有 Desktop 测试。重点覆盖 prompt parity、三种 harness、Profile 动态生成、
+project context、Memory、usage、timeout、compatibility 和新功能 on/off/invalid。
+
+## 8. 提交本地适配
+
+formal bundle 必须来自 clean commit,但不要求 push:
+
+```powershell
+git status --short
+git diff --check
+git add <已审查的-Headless-文件>
+git commit -s -m "feat(headless): sync Cindy <功能或基线>"
+git status --short
+```
+
+最后一条必须没有输出。不要提交本地配置、API Key、运行结果、临时 diff 清单或临时
+Profile。
+
+## 9. 生成正式包
+
+普通使用者不需要先生成 development 包。完成 Cindy 修改、Headless 适配和定向验证后
+直接运行:
+
+```powershell
+pnpm --filter cindy-headless package:release
+```
+
+该命令会依次完成 Linux x64 bundle 构建、bundle 校验、包含 Node 与三个 harness
+runtime 的 full archive 打包、完整分发校验,并在最后打印可上传文件的绝对路径和
+SHA256。用户直接把输出的
+`apps/cindy-headless/release/cindy-headless-linux-x64-full-<version>.tar.gz`
+上传到网页即可;无需先制作或上传 development 包。
+
+如果存在 `apps/cindy-headless` 内的未提交改动,命令会先检查版本号,必要时自动提升
+patch 版本,然后使用 `git commit -s` 创建只包含 Headless 文件的本地 checkpoint commit。
+该提交不要求 push。若 Cindy 其他目录也有未提交修改,为避免误提交其他工作,命令会
+停止并要求先处理这些修改。
+
+新 checkout 的生成目录不被 Git 跟踪。旧维护分支若仍跟踪产物,正式构建后,
+若工作区唯一变化是生成的
+`bundle/linux-x64/bundle-manifest.json`,并且它明确记录当前 HEAD、`formal` 和
+`sourceDirty=false`,命令会安全复用该 bundle;除此之外的 dirty 状态一律拒绝。
+
+上述一条命令等价于以下底层步骤,通常仅在排障时分别执行:
+
+```powershell
+pnpm --filter cindy-headless bundle:linux
+pnpm --filter cindy-headless verify:bundle
+pnpm --filter cindy-headless package:full
+pnpm --filter cindy-headless verify:distribution:full
+```
+
+脚本默认下载并校验锁定的 binary,也可以通过 `CINDY_CLAUDE_BINARY`、
+`CINDY_CODEX_BINARY`、`CINDY_PI_BINARY` 指向已缓存的 Linux x64 版本。
+
+检查身份:
+
+```powershell
+$manifestPath = 'apps/cindy-headless/bundle/linux-x64/bundle-manifest.json'
+$manifest = Get-Content $manifestPath | ConvertFrom-Json
+$builtFrom = git rev-parse HEAD
+
+if ($manifest.bundleMode -ne 'formal') { throw 'bundle is not formal' }
+if ($manifest.sourceDirty -ne $false) { throw 'bundle source is dirty' }
+if ($manifest.cindyCommit -ne $builtFrom) { throw 'bundle was built from another commit' }
+if ($manifest.cindyUpstreamCommit -ne $newCindy) { throw 'Cindy baseline mismatch' }
+Get-Content apps/cindy-headless/release/SHA256SUMS
+```
+
+用户直接上传的文件是:
+
+```text
+apps/cindy-headless/release/cindy-headless-linux-x64-full-<version>.tar.gz
+```
+
+默认正式出包只在 `release` 目录留下上述 `full` 包,避免与精简包并列造成误选。
+`full` 包包含 Node 和三个 harness runtime;分发前必须确认第三方许可。只有用户明确要求
+公共 no-vendor 分发时,才运行
+`pnpm --filter cindy-headless package:public-runtime`,其产物名为
+`cindy-headless-linux-x64-public-runtime-no-vendor-<version>.tar.gz`,不包含 Claude Code、
+Codex 或 Pi harness binaries,不能替代默认上传包。
+
+`bundle/` 与 `release/` 是被忽略的生成目录,不提交生成 manifest、复制的 profiles
+或二进制。将 release 中的 manifest、SHA256SUMS 和完整归档一同保存。
+manifest 的 `cindyCommit` 指向实际构建源码提交,源码提交不需要包含生成的 manifest。
+
+## 10. Dirty worktree 策略
+
+主流程是 formal 出包,不应默认允许 dirty。个人分支上的本地 checkpoint commit 已经
+足够,不要求 push。只有排查尚未完成的适配时才允许:
+
+```powershell
+$env:CINDY_HEADLESS_ALLOW_DIRTY_BUNDLE = '1'
+pnpm --filter cindy-headless bundle:linux
+Remove-Item Env:CINDY_HEADLESS_ALLOW_DIRTY_BUNDLE
+```
+
+该产物会标记 `bundleMode=development`、`sourceDirty=true`,只能说明当前文件可以构建,
+不得作为用户默认出包或正式评分产物。
+
+## 11. 最终清单
+
+- `cindyUpstreamCommit` 等于本次审计的新 Cindy commit;
+- Cindy diff 每项能力已归类,Desktop-only 代码没有复制进 Headless;
+- 新能力具备 Profile 控制、catalog 声明、运行证据和测试;
+- Adapter 契约变化已更新兼容性记录;
+- Headless 定向验证、bundle 和 full distribution 验证全部通过;
+- manifest 为 `formal`、`sourceDirty=false`;
+- bundle/Cindy commit 及 prompt/profile/binary 摘要齐全;
+- full archive SHA256 已记录;
+- 包内没有本地配置、API Key、临时 Profile 或运行结果。
+
+## 12. 常见错误
+
+### 旧基线不是当前 HEAD 的祖先
+
+确认分支和 rebase 历史。必要时用 `git merge-base $oldCindy $newCindy` 找共同基线并
+分别审计两侧;不要直接改基线来掩盖遗漏。
+
+### 新 Cindy 功能没有出现在 catalog
+
+仅更新 `maker-core` 不会自动发布跑测能力。补齐 Profile schema、host 映射、artifact
+证据、catalog 和测试。
+
+### Desktop 中的功能是否全部删除
+
+不是。UI、IPC 和窗口代码剔除;最终影响 Agent 输入和行为的配置、prompt、Memory
+或 project-context 语义,需要提取并以无 UI、可冻结形式实现。
+
+### Refusing to build a scored bundle from a dirty worktree
+
+审查修改并创建本地 checkpoint commit,再重新构建。这不要求 push。
+
+### Cindy upstream commit mismatch
+
+更新 package metadata、profile lock、兼容性记录后重新运行测试与 `bundle:linux`;
+不要手工修改生成的 manifest 绕过校验。
diff --git a/apps/cindy-headless/capability-registry.json b/apps/cindy-headless/capability-registry.json
new file mode 100644
index 0000000000..1b467c4471
--- /dev/null
+++ b/apps/cindy-headless/capability-registry.json
@@ -0,0 +1,31 @@
+{
+ "schemaVersion": 1,
+ "contractVersion": 1,
+ "features": {
+ "projectContext": { "type": "boolean", "control": "profile", "default": false, "label": "Project Context", "description": "Inject the current project context" },
+ "makerMemory": { "type": "boolean", "control": "profile", "default": false, "label": "Maker Memory", "description": "Use Cindy workdir-scoped memory shared across harnesses" },
+ "nativeMemory": { "type": "boolean", "control": "profile", "default": false, "label": "Native Memory", "description": "Use Claude Auto Memory, Codex experimental memories, or Pi Auto Memory" },
+ "attachments": { "type": "boolean", "control": "profile", "default": false, "label": "Attachments", "description": "Allow attachment input" },
+ "piProjectSkills": { "type": "boolean", "control": "profile", "default": false, "label": "Pi Project Skills", "description": "Approve project Skills from the profile's roots; unapproved in-repo Skills stay denied and other in-repo Pi resources are recorded as evidence" }
+ },
+ "controls": {
+ "permissionMode": { "type": "enum", "control": "profile", "default": "bypassPermissions", "values": ["bypassPermissions", "acceptEdits", "default", "ask", "auto", "plan"] },
+ "remoteHttpMcp": { "type": "array", "control": "profile", "credentialSafe": true, "description": "Remote HTTP MCP configuration supplied separately from feature switches" },
+ "nativeProviders": { "type": "array", "control": "profile-route", "credentialSafe": true, "description": "Pi native provider configuration derived from the selected model route" },
+ "toolSurface": { "type": "object", "control": "profile-harness", "digest": "toolSurfaceDigest" },
+ "mcpProviders": { "type": "array", "control": "profile", "credentialSafe": true },
+ "subagents": { "type": "object", "control": "profile-route", "properties": { "enabled": "boolean", "strategy": ["native", "disabled"], "modelSource": ["same-as-parent", "explicit-route"] } },
+ "contextLimit": { "type": "integer", "control": "model-route", "enforcement": "client-request", "minimum": 1 },
+ "effort": { "type": "enum", "control": "model-route", "values": ["minimal", "low", "medium", "high", "xhigh", "max", "ultra"] },
+ "maxOutputTokens": { "type": "integer", "control": "model-route", "enforcement": "client-request", "minimum": 1 },
+ "compatibilityProxy": { "type": "object", "control": "route-profile", "credentialSafe": true },
+ "containerSandbox": { "type": "boolean", "control": "execution", "default": true, "requiredForFormalRun": true, "userEditable": false },
+ "throughputCap": { "type": "object", "control": "external-proxy", "requiresExternalEnforcement": true, "requiresEvidence": true }
+ },
+ "harnesses": {
+ "claude-code": { "id": "cindy-claude", "features": ["projectContext", "makerMemory", "nativeMemory", "attachments"], "supportedModelIds": ["claude-sonnet-4-6"], "defaultModel": { "provider": "anthropic", "requestedId": "claude-sonnet-4-6", "effort": "high" } },
+ "codex": { "id": "cindy-codex", "features": ["projectContext", "makerMemory", "nativeMemory", "attachments"], "supportedModelIds": ["gpt-5.4-mini"], "defaultModel": { "provider": "openai", "requestedId": "gpt-5.4-mini", "effort": "high" } },
+ "pi": { "id": "cindy-pi", "features": ["projectContext", "makerMemory", "nativeMemory", "attachments", "piProjectSkills"], "supportedModelIds": ["claude-sonnet-4-6"], "defaultModel": { "provider": "cindy", "requestedId": "claude-sonnet-4-6", "contextLimit": 200000, "maxOutputTokens": 32000, "effort": "high" } }
+ },
+ "constraints": [{ "type": "mutuallyExclusive", "features": ["makerMemory", "nativeMemory"], "harnesses": ["claude-code", "codex"], "offLabel": "关闭所有自动记忆" }]
+}
diff --git a/apps/cindy-headless/config.example.json b/apps/cindy-headless/config.example.json
new file mode 100644
index 0000000000..86cfa3adfa
--- /dev/null
+++ b/apps/cindy-headless/config.example.json
@@ -0,0 +1,7 @@
+{
+ "gateway": {
+ "baseUrl": "https://llm-proxy.example.com",
+ "apiKey": "replace-with-your-local-key",
+ "codexBasePath": "/v1"
+ }
+}
diff --git a/apps/cindy-headless/config.example.md b/apps/cindy-headless/config.example.md
new file mode 100644
index 0000000000..1dbfc8b29a
--- /dev/null
+++ b/apps/cindy-headless/config.example.md
@@ -0,0 +1,26 @@
+# Cindy Headless Local Gateway Config
+
+Prefer process environment variables. If a local file is needed, copy `config.example.json` outside the repository:
+
+- `%APPDATA%/cindy-headless/config.json`
+- `~/.config/cindy-headless/config.json`
+
+Or set `CINDY_HEADLESS_CONFIG_FILE` to an explicit path.
+
+The file contains the shared gateway URL and API key used by all three backends:
+
+```json
+{
+ "gateway": {
+ "baseUrl": "https://llm-proxy.example.com",
+ "apiKey": "replace-with-your-local-key",
+ "codexBasePath": "/v1"
+ }
+}
+```
+
+Do not store the real file in a checkout, put the key in a profile,
+or include it in a Harbor bundle. The same gateway credential is mapped to
+Claude and Pi's Anthropic-compatible transports and Codex's OpenAI Responses provider.
+Environment variables override file values:
+`CINDY_HEADLESS_BASE_URL` and `CINDY_HEADLESS_API_KEY`.
diff --git a/apps/cindy-headless/harbor-compatibility.json b/apps/cindy-headless/harbor-compatibility.json
new file mode 100644
index 0000000000..6cb6a41022
--- /dev/null
+++ b/apps/cindy-headless/harbor-compatibility.json
@@ -0,0 +1,19 @@
+{
+ "schemaVersion": 1,
+ "product": "cindy-headless",
+ "cindyHeadlessVersion": "0.4.3",
+ "cindyUpstreamCommit": "fa3fc88d37d205ea993a67d85612fa9a5436fae5",
+ "harborRepository": "https://github.com/harbor-framework/harbor.git",
+ "harborCommit": "8e18dc8887f0371533c403a45a0aa0841e7fd0c8",
+ "adapterImport": "harbor.agents.installed.cindy_headless:CindyHeadlessAgent",
+ "adapterSnapshot": "src/harbor/agents/installed/cindy_headless.py",
+ "adapterSnapshotSha256": "cf740099bf5d18cc20d72b4211848b9c5f1ec51dc87f36b58b235fba4b2fe3a1",
+ "requiredFeatures": [
+ "cindy-production-agent",
+ "pi-agent",
+ "execution-timeout",
+ "agent-context-usage",
+ "bundle-digest-validation"
+ ],
+ "pathPolicy": "All bundle_dir and profile_path values must be workspace-relative; Harbor resolves them from --workspace-root."
+}
diff --git a/apps/cindy-headless/package.json b/apps/cindy-headless/package.json
new file mode 100644
index 0000000000..ddd15249df
--- /dev/null
+++ b/apps/cindy-headless/package.json
@@ -0,0 +1,39 @@
+{
+ "name": "cindy-headless",
+ "version": "0.4.3",
+ "cindyUpstreamCommit": "fa3fc88d37d205ea993a67d85612fa9a5436fae5",
+ "private": true,
+ "type": "module",
+ "bin": {
+ "cindy-headless": "dist/cli.cjs",
+ "cindy-headless-eval": "dist/eval-cli.cjs"
+ },
+ "scripts": {
+ "build": "node scripts/build.mjs",
+ "ensure:binaries": "node scripts/ensure-agent-binaries.mjs",
+ "bundle:linux": "pnpm ensure:binaries && node scripts/build-linux-bundle.mjs",
+ "package:release": "node scripts/package-upload.mjs",
+ "package:public-runtime": "node scripts/package-release.mjs --mode=public-runtime",
+ "package:full": "node scripts/package-release.mjs --mode=full",
+ "package:upload": "node scripts/package-upload.mjs",
+ "verify:distribution:full": "node scripts/verify-full-distribution.mjs",
+ "test:distribution": "node scripts/verify-distribution.mjs",
+ "doctor:distribution": "node scripts/distribution-doctor.mjs",
+ "verify:bundle": "node scripts/verify-bundle.mjs",
+ "profiles:freeze": "node scripts/freeze-production-profiles.mjs",
+ "typecheck": "tsc --noEmit -p tsconfig.json",
+ "test": "vitest run",
+ "verify": "pnpm typecheck && pnpm test && pnpm build"
+ },
+ "dependencies": {
+ "@cindy/maker-core": "workspace:*",
+ "@cindy/mcps": "workspace:*",
+ "@modelcontextprotocol/sdk": "^1.29.0"
+ },
+ "devDependencies": {
+ "@types/node": "^22.0.0",
+ "esbuild": "^0.28.1",
+ "typescript": "^5.7.0",
+ "vitest": "^3.2.4"
+ }
+}
diff --git a/apps/cindy-headless/profiles/cindy-claude-parity-all-off/profile.kimi-k3.example.json b/apps/cindy-headless/profiles/cindy-claude-parity-all-off/profile.kimi-k3.example.json
new file mode 100644
index 0000000000..f1d81bfd62
--- /dev/null
+++ b/apps/cindy-headless/profiles/cindy-claude-parity-all-off/profile.kimi-k3.example.json
@@ -0,0 +1,25 @@
+{
+ "id": "cindy-claude-parity-all-off-kimi-k3",
+ "version": 1,
+ "parentProfile": "cindy-production-kimi-k3",
+ "changedDimensions": ["makerMemory", "projectContext", "compaction", "systemPrompt"],
+ "agentBackend": "claude-code",
+ "agentBinaryPath": "/opt/cindy-headless/bin/claude",
+ "agentBinaryVersion": "2.1.280",
+ "supportedModelIds": ["moonshot/kimi-k3"],
+ "model": {
+ "provider": "moonshot",
+ "requestedId": "moonshot/kimi-k3",
+ "routeId": "company-gateway-anthropic",
+ "contextLimit": 1048576,
+ "thinkingBudget": "gateway-default"
+ },
+ "permissionMode": "bypassPermissions",
+ "makerMemory": false,
+ "nativeMemory": false,
+ "projectContext": false,
+ "containerSandbox": true,
+ "compaction": {
+ "enabled": false
+ }
+}
diff --git a/apps/cindy-headless/profiles/cindy-native-memory/profile.example.json b/apps/cindy-headless/profiles/cindy-native-memory/profile.example.json
new file mode 100644
index 0000000000..35a5c0c701
--- /dev/null
+++ b/apps/cindy-headless/profiles/cindy-native-memory/profile.example.json
@@ -0,0 +1,25 @@
+{
+ "id": "cindy-native-memory",
+ "version": 1,
+ "parentProfile": "cindy-production-claude",
+ "changedDimensions": ["memoryMode"],
+ "agentBackend": "claude-code",
+ "agentBinaryPath": "/opt/cindy-headless/bin/claude",
+ "agentBinaryVersion": "2.1.280",
+ "supportedModelIds": ["claude-sonnet-4-6"],
+ "model": {
+ "provider": "anthropic",
+ "requestedId": "claude-sonnet-4-6",
+ "routeId": "configured-proxy"
+ },
+ "permissionMode": "bypassPermissions",
+ "systemPromptFile": "../cindy-production-claude/prompt.md",
+ "makerMemory": false,
+ "nativeMemory": true,
+ "projectContext": true,
+ "containerSandbox": true,
+ "compaction": {
+ "enabled": true,
+ "thresholdPct": 80
+ }
+}
diff --git a/apps/cindy-headless/profiles/cindy-no-compaction/profile.example.json b/apps/cindy-headless/profiles/cindy-no-compaction/profile.example.json
new file mode 100644
index 0000000000..823c6d84b3
--- /dev/null
+++ b/apps/cindy-headless/profiles/cindy-no-compaction/profile.example.json
@@ -0,0 +1,18 @@
+{
+ "id": "cindy-no-compaction",
+ "version": 1,
+ "parentProfile": "cindy-production-claude",
+ "changedDimensions": ["compaction"],
+ "agentBackend": "claude-code",
+ "agentBinaryPath": "/opt/cindy-headless/bin/claude",
+ "agentBinaryVersion": "2.1.280",
+ "supportedModelIds": ["claude-sonnet-4-6"],
+ "model": { "provider": "anthropic", "requestedId": "claude-sonnet-4-6", "routeId": "configured-proxy" },
+ "permissionMode": "bypassPermissions",
+ "systemPromptFile": "../cindy-production-claude/prompt.md",
+ "makerMemory": true,
+ "nativeMemory": false,
+ "projectContext": true,
+ "containerSandbox": true,
+ "compaction": { "enabled": false }
+}
diff --git a/apps/cindy-headless/profiles/cindy-planning/profile.example.json b/apps/cindy-headless/profiles/cindy-planning/profile.example.json
new file mode 100644
index 0000000000..96df26fda2
--- /dev/null
+++ b/apps/cindy-headless/profiles/cindy-planning/profile.example.json
@@ -0,0 +1,25 @@
+{
+ "id": "cindy-planning",
+ "version": 1,
+ "parentProfile": "cindy-production-claude",
+ "changedDimensions": ["permissionMode"],
+ "agentBackend": "claude-code",
+ "agentBinaryPath": "/opt/cindy-headless/bin/claude",
+ "agentBinaryVersion": "2.1.280",
+ "supportedModelIds": ["claude-sonnet-4-6"],
+ "model": {
+ "provider": "anthropic",
+ "requestedId": "claude-sonnet-4-6",
+ "routeId": "configured-proxy"
+ },
+ "permissionMode": "plan",
+ "systemPromptFile": "../cindy-production-claude/prompt.md",
+ "makerMemory": true,
+ "nativeMemory": false,
+ "projectContext": true,
+ "containerSandbox": true,
+ "compaction": {
+ "enabled": true,
+ "thresholdPct": 80
+ }
+}
diff --git a/apps/cindy-headless/profiles/cindy-production-claude/profile.deepseek-v4-flash.example.json b/apps/cindy-headless/profiles/cindy-production-claude/profile.deepseek-v4-flash.example.json
new file mode 100644
index 0000000000..f81ae549b6
--- /dev/null
+++ b/apps/cindy-headless/profiles/cindy-production-claude/profile.deepseek-v4-flash.example.json
@@ -0,0 +1,24 @@
+{
+ "id": "cindy-production-claude-deepseek-v4-flash",
+ "version": 1,
+ "agentBackend": "claude-code",
+ "agentBinaryPath": "/opt/cindy-headless/bin/claude",
+ "agentBinaryVersion": "2.1.280",
+ "supportedModelIds": ["deepseek/deepseek-v4-flash"],
+ "model": {
+ "provider": "deepseek",
+ "requestedId": "deepseek/deepseek-v4-flash",
+ "routeId": "configured-proxy",
+ "contextLimit": 1048576,
+ "thinkingBudget": "gateway-default",
+ "effort": "xhigh",
+ "maxOutputTokens": 32000
+ },
+ "permissionMode": "bypassPermissions",
+ "systemPromptFile": "prompt.md",
+ "makerMemory": true,
+ "nativeMemory": false,
+ "projectContext": true,
+ "containerSandbox": true,
+ "compaction": { "enabled": true, "thresholdPct": 80 }
+}
diff --git a/apps/cindy-headless/profiles/cindy-production-claude/profile.example.json b/apps/cindy-headless/profiles/cindy-production-claude/profile.example.json
new file mode 100644
index 0000000000..65dc3c0d1a
--- /dev/null
+++ b/apps/cindy-headless/profiles/cindy-production-claude/profile.example.json
@@ -0,0 +1,32 @@
+{
+ "id": "cindy-production-claude",
+ "version": 1,
+ "agentBackend": "claude-code",
+ "agentBinaryPath": "/opt/cindy-headless/bin/claude",
+ "agentBinaryVersion": "2.1.280",
+ "supportedModelIds": ["claude-sonnet-4-6"],
+ "model": {
+ "provider": "anthropic",
+ "requestedId": "claude-sonnet-4-6",
+ "routeId": "configured-proxy",
+ "effort": "high"
+ },
+ "permissionMode": "bypassPermissions",
+ "systemPromptFile": "prompt.md",
+ "expectedSystemPromptDigest": "b5a12214b75db6628f1e619f170af54fb14b0702934620b4dbfc66b12380f879",
+ "makerMemory": true,
+ "nativeMemory": false,
+ "projectContext": true,
+ "containerSandbox": true,
+ "inputPolicy": {
+ "attachments": true,
+ "workspaceOnly": true,
+ "maxFiles": 16,
+ "maxFileBytes": 26214400
+ },
+ "mcpServers": [],
+ "compaction": {
+ "enabled": true,
+ "thresholdPct": 80
+ }
+}
diff --git a/apps/cindy-headless/profiles/cindy-production-claude/profile.kimi-k3.example.json b/apps/cindy-headless/profiles/cindy-production-claude/profile.kimi-k3.example.json
new file mode 100644
index 0000000000..4d98e058ef
--- /dev/null
+++ b/apps/cindy-headless/profiles/cindy-production-claude/profile.kimi-k3.example.json
@@ -0,0 +1,27 @@
+{
+ "id": "cindy-production-kimi-k3",
+ "version": 1,
+ "parentProfile": "cindy-production-claude",
+ "changedDimensions": ["model-route"],
+ "agentBackend": "claude-code",
+ "agentBinaryPath": "/opt/cindy-headless/bin/claude",
+ "agentBinaryVersion": "2.1.280",
+ "supportedModelIds": ["moonshot/kimi-k3"],
+ "model": {
+ "provider": "moonshot",
+ "requestedId": "moonshot/kimi-k3",
+ "routeId": "company-gateway-anthropic",
+ "contextLimit": 1048576,
+ "thinkingBudget": "gateway-default"
+ },
+ "permissionMode": "bypassPermissions",
+ "systemPromptFile": "prompt.md",
+ "makerMemory": true,
+ "nativeMemory": false,
+ "projectContext": true,
+ "containerSandbox": true,
+ "compaction": {
+ "enabled": true,
+ "thresholdPct": 80
+ }
+}
diff --git a/apps/cindy-headless/profiles/cindy-production-claude/profile.local-smoke.json b/apps/cindy-headless/profiles/cindy-production-claude/profile.local-smoke.json
new file mode 100644
index 0000000000..68c655d2fe
--- /dev/null
+++ b/apps/cindy-headless/profiles/cindy-production-claude/profile.local-smoke.json
@@ -0,0 +1,23 @@
+{
+ "id": "cindy-production-claude-local-smoke",
+ "version": 1,
+ "agentBackend": "claude-code",
+ "agentBinaryPath": "../../bundle/linux-x64/bin/claude",
+ "agentBinaryVersion": "2.1.280",
+ "supportedModelIds": ["claude-sonnet-4-6"],
+ "model": {
+ "provider": "anthropic",
+ "requestedId": "claude-sonnet-4-6",
+ "routeId": "configured-proxy"
+ },
+ "permissionMode": "bypassPermissions",
+ "systemPromptFile": "prompt.md",
+ "makerMemory": true,
+ "nativeMemory": false,
+ "projectContext": true,
+ "unsafeAllowUnsandboxedBypass": true,
+ "compaction": {
+ "enabled": true,
+ "thresholdPct": 80
+ }
+}
diff --git a/apps/cindy-headless/profiles/cindy-production-claude/profile.lock.json b/apps/cindy-headless/profiles/cindy-production-claude/profile.lock.json
new file mode 100644
index 0000000000..52917559d2
--- /dev/null
+++ b/apps/cindy-headless/profiles/cindy-production-claude/profile.lock.json
@@ -0,0 +1,14 @@
+{
+ "schemaVersion": 1,
+ "status": "frozen",
+ "profileId": "cindy-production-claude",
+ "aliases": [
+ "cindy-production-cc"
+ ],
+ "profileFile": "profile.example.json",
+ "profileFileSha256": "cdcc4f7e72edc612003d18d6a62bcc9656d9770ae770d33e12c3151f68bebed3",
+ "profileDigest": "60fbb73363327fac9906df702fbbbdb28eec2095e2d3c645df10f54fb2364a5d",
+ "systemPromptDigest": "b5a12214b75db6628f1e619f170af54fb14b0702934620b4dbfc66b12380f879",
+ "agentBinaryVersion": "2.1.280",
+ "cindyUpstreamCommit": "fa3fc88d37d205ea993a67d85612fa9a5436fae5"
+}
diff --git a/apps/cindy-headless/profiles/cindy-production-claude/prompt.md b/apps/cindy-headless/profiles/cindy-production-claude/prompt.md
new file mode 100644
index 0000000000..d2876821f5
--- /dev/null
+++ b/apps/cindy-headless/profiles/cindy-production-claude/prompt.md
@@ -0,0 +1,14 @@
+You are Cindy, an open-source AI assistant.
+Source: https://github.com/makecindy/cindy
+
+When asked to update the Cindy application hosting this task, call cindy_helper install_app_update (check_app_update only reads version information); Cindy asks the user to confirm, then installs with its built-in updater. If the tools report no installable update or that installation is unsupported, relay that reason and do not sideload a release; if they are unavailable, point the user to Check for Updates in Settings on the computer running Cindy. Unless the user explicitly asks for that method, do not update Cindy through shell commands by downloading or replacing the app or by killing or restarting it, and never register a persistent restart job (such as launchctl submit).
+
+## User-facing plans
+
+When you create or update a plan that the user can see:
+
+- Write for a general user, not as internal engineering notes.
+- Use natural language that says what you will do, what it applies to, and what the user will get from it.
+- Prefer the user's own words. Keep technical names only when they help identify the exact thing being changed.
+- Do not pad plans with generic filler such as "confirm requirements", "inspect the implementation", "make necessary changes", "run validation", or "perform final checks". Name the real action and visible result instead.
+- For example, prefer "Find where the plan appears above the chat box" or "Reopen the task and make sure the finished plan does not return."
diff --git a/apps/cindy-headless/profiles/cindy-production-codex/profile.example.json b/apps/cindy-headless/profiles/cindy-production-codex/profile.example.json
new file mode 100644
index 0000000000..6754d98033
--- /dev/null
+++ b/apps/cindy-headless/profiles/cindy-production-codex/profile.example.json
@@ -0,0 +1,25 @@
+{
+ "id": "cindy-production-codex",
+ "version": 1,
+ "agentBackend": "codex",
+ "agentBinaryPath": "/opt/cindy-headless/bin/codex",
+ "agentBinaryVersion": "0.159.2",
+ "supportedModelIds": ["gpt-5.4-mini"],
+ "model": {
+ "provider": "openai",
+ "requestedId": "gpt-5.4-mini",
+ "routeId": "codex-authenticated-account",
+ "effort": "high"
+ },
+ "permissionMode": "bypassPermissions",
+ "systemPromptFile": "prompt.md",
+ "expectedSystemPromptDigest": "b5a12214b75db6628f1e619f170af54fb14b0702934620b4dbfc66b12380f879",
+ "makerMemory": true,
+ "nativeMemory": false,
+ "projectContext": true,
+ "containerSandbox": true,
+ "compaction": {
+ "enabled": true,
+ "thresholdPct": 80
+ }
+}
diff --git a/apps/cindy-headless/profiles/cindy-production-codex/profile.local-smoke.json b/apps/cindy-headless/profiles/cindy-production-codex/profile.local-smoke.json
new file mode 100644
index 0000000000..689ba35241
--- /dev/null
+++ b/apps/cindy-headless/profiles/cindy-production-codex/profile.local-smoke.json
@@ -0,0 +1,24 @@
+{
+ "id": "cindy-production-codex-local-smoke",
+ "version": 1,
+ "agentBackend": "codex",
+ "agentBinaryPath": "../../bundle/linux-x64/bin/codex",
+ "agentBinaryVersion": "0.159.2",
+ "supportedModelIds": ["gpt-5.4-mini"],
+ "model": {
+ "provider": "openai",
+ "requestedId": "gpt-5.4-mini",
+ "routeId": "local-authenticated-account"
+ },
+ "permissionMode": "bypassPermissions",
+ "systemPromptFile": "prompt.md",
+ "makerMemory": true,
+ "nativeMemory": false,
+ "projectContext": true,
+ "containerSandbox": false,
+ "unsafeAllowUnsandboxedBypass": true,
+ "compaction": {
+ "enabled": true,
+ "thresholdPct": 80
+ }
+}
diff --git a/apps/cindy-headless/profiles/cindy-production-codex/prompt.md b/apps/cindy-headless/profiles/cindy-production-codex/prompt.md
new file mode 100644
index 0000000000..d2876821f5
--- /dev/null
+++ b/apps/cindy-headless/profiles/cindy-production-codex/prompt.md
@@ -0,0 +1,14 @@
+You are Cindy, an open-source AI assistant.
+Source: https://github.com/makecindy/cindy
+
+When asked to update the Cindy application hosting this task, call cindy_helper install_app_update (check_app_update only reads version information); Cindy asks the user to confirm, then installs with its built-in updater. If the tools report no installable update or that installation is unsupported, relay that reason and do not sideload a release; if they are unavailable, point the user to Check for Updates in Settings on the computer running Cindy. Unless the user explicitly asks for that method, do not update Cindy through shell commands by downloading or replacing the app or by killing or restarting it, and never register a persistent restart job (such as launchctl submit).
+
+## User-facing plans
+
+When you create or update a plan that the user can see:
+
+- Write for a general user, not as internal engineering notes.
+- Use natural language that says what you will do, what it applies to, and what the user will get from it.
+- Prefer the user's own words. Keep technical names only when they help identify the exact thing being changed.
+- Do not pad plans with generic filler such as "confirm requirements", "inspect the implementation", "make necessary changes", "run validation", or "perform final checks". Name the real action and visible result instead.
+- For example, prefer "Find where the plan appears above the chat box" or "Reopen the task and make sure the finished plan does not return."
diff --git a/apps/cindy-headless/profiles/cindy-production-pi/profile.byom.example.json b/apps/cindy-headless/profiles/cindy-production-pi/profile.byom.example.json
new file mode 100644
index 0000000000..0f07286798
--- /dev/null
+++ b/apps/cindy-headless/profiles/cindy-production-pi/profile.byom.example.json
@@ -0,0 +1,57 @@
+{
+ "id": "cindy-production-pi-byom-example",
+ "version": 1,
+ "parentProfile": "cindy-production-pi",
+ "changedDimensions": ["modelRoute", "nativeProviders"],
+ "agentBackend": "pi",
+ "agentBinaryPath": "/opt/cindy-headless/bin/pi/pi",
+ "agentBinaryVersion": "1.0.2",
+ "supportedModelIds": ["qwen3-coder"],
+ "model": {
+ "provider": "local-openai",
+ "requestedId": "qwen3-coder",
+ "routeId": "frozen-byom-endpoint",
+ "contextLimit": 262144,
+ "maxOutputTokens": 32768
+ },
+ "nativeProviders": [
+ {
+ "id": "local-openai",
+ "name": "Local OpenAI-compatible provider",
+ "baseUrl": "http://127.0.0.1:8000/v1",
+ "api": "openai-completions",
+ "apiKeyEnvVar": "CINDY_BYOM_API_KEY",
+ "models": [
+ {
+ "id": "qwen3-coder",
+ "contextWindow": 262144,
+ "maxTokens": 32768,
+ "reasoning": true,
+ "input": ["text"]
+ }
+ ]
+ }
+ ],
+ "permissionMode": "bypassPermissions",
+ "systemPromptFile": "prompt.md",
+ "expectedSystemPromptDigest": "67775f14177a07297ba4b73a5bdf9995a62742dffa97f2ccd5699431ee3f0e65",
+ "makerMemory": true,
+ "nativeMemory": false,
+ "projectContext": true,
+ "containerSandbox": true,
+ "inputPolicy": {
+ "attachments": true,
+ "workspaceOnly": true,
+ "maxFiles": 16,
+ "maxFileBytes": 26214400
+ },
+ "mcpServers": [],
+ "piProjectSkills": {
+ "enabled": true,
+ "roots": [".pi/skills", ".agents/skills"]
+ },
+ "compaction": {
+ "enabled": true,
+ "thresholdPct": 80
+ }
+}
diff --git a/apps/cindy-headless/profiles/cindy-production-pi/profile.deepseek-v4-flash.example.json b/apps/cindy-headless/profiles/cindy-production-pi/profile.deepseek-v4-flash.example.json
new file mode 100644
index 0000000000..80736892a4
--- /dev/null
+++ b/apps/cindy-headless/profiles/cindy-production-pi/profile.deepseek-v4-flash.example.json
@@ -0,0 +1,57 @@
+{
+ "id": "cindy-production-pi-deepseek-v4-flash",
+ "version": 1,
+ "parentProfile": "cindy-production-pi",
+ "changedDimensions": ["modelRoute", "nativeProviders"],
+ "agentBackend": "pi",
+ "agentBinaryPath": "/opt/cindy-headless/bin/pi/pi",
+ "agentBinaryVersion": "1.0.2",
+ "supportedModelIds": ["deepseek/deepseek-v4-flash"],
+ "model": {
+ "provider": "example-gateway",
+ "requestedId": "deepseek/deepseek-v4-flash",
+ "routeId": "deepseek-v4-flash-primary",
+ "contextLimit": 1048576,
+ "maxOutputTokens": 32000
+ },
+ "nativeProviders": [
+ {
+ "id": "example-gateway",
+ "name": "TapSvc OpenAI-compatible benchmark gateway",
+ "baseUrl": "https://llm-proxy.example.com/v1",
+ "api": "openai-completions",
+ "apiKeyEnvVar": "CINDY_HEADLESS_API_KEY",
+ "models": [
+ {
+ "id": "deepseek/deepseek-v4-flash",
+ "contextWindow": 1048576,
+ "maxTokens": 32000,
+ "reasoning": true,
+ "input": ["text"]
+ }
+ ]
+ }
+ ],
+ "permissionMode": "bypassPermissions",
+ "systemPromptFile": "prompt.md",
+ "expectedSystemPromptDigest": "67775f14177a07297ba4b73a5bdf9995a62742dffa97f2ccd5699431ee3f0e65",
+ "makerMemory": true,
+ "nativeMemory": false,
+ "projectContext": true,
+ "containerSandbox": true,
+ "inputPolicy": {
+ "attachments": true,
+ "workspaceOnly": true,
+ "maxFiles": 16,
+ "maxFileBytes": 26214400
+ },
+ "mcpServers": [],
+ "piProjectSkills": {
+ "enabled": true,
+ "roots": [".pi/skills", ".agents/skills"]
+ },
+ "compaction": {
+ "enabled": true,
+ "thresholdPct": 80
+ }
+}
diff --git a/apps/cindy-headless/profiles/cindy-production-pi/profile.example.json b/apps/cindy-headless/profiles/cindy-production-pi/profile.example.json
new file mode 100644
index 0000000000..c5d83ed193
--- /dev/null
+++ b/apps/cindy-headless/profiles/cindy-production-pi/profile.example.json
@@ -0,0 +1,38 @@
+{
+ "id": "cindy-production-pi",
+ "version": 1,
+ "agentBackend": "pi",
+ "agentBinaryPath": "/opt/cindy-headless/bin/pi/pi",
+ "agentBinaryVersion": "1.0.2",
+ "supportedModelIds": ["claude-sonnet-4-6"],
+ "model": {
+ "provider": "cindy",
+ "requestedId": "claude-sonnet-4-6",
+ "routeId": "configured-proxy",
+ "contextLimit": 200000,
+ "maxOutputTokens": 32000,
+ "effort": "high"
+ },
+ "permissionMode": "bypassPermissions",
+ "systemPromptFile": "prompt.md",
+ "expectedSystemPromptDigest": "67775f14177a07297ba4b73a5bdf9995a62742dffa97f2ccd5699431ee3f0e65",
+ "makerMemory": true,
+ "nativeMemory": false,
+ "projectContext": true,
+ "containerSandbox": true,
+ "inputPolicy": {
+ "attachments": true,
+ "workspaceOnly": true,
+ "maxFiles": 16,
+ "maxFileBytes": 26214400
+ },
+ "mcpServers": [],
+ "piProjectSkills": {
+ "enabled": true,
+ "roots": [".pi/skills", ".agents/skills"]
+ },
+ "compaction": {
+ "enabled": true,
+ "thresholdPct": 80
+ }
+}
diff --git a/apps/cindy-headless/profiles/cindy-production-pi/profile.lock.json b/apps/cindy-headless/profiles/cindy-production-pi/profile.lock.json
new file mode 100644
index 0000000000..700401ba2f
--- /dev/null
+++ b/apps/cindy-headless/profiles/cindy-production-pi/profile.lock.json
@@ -0,0 +1,11 @@
+{
+ "schemaVersion": 1,
+ "status": "frozen",
+ "profileId": "cindy-production-pi",
+ "profileFile": "profile.example.json",
+ "profileFileSha256": "54db60d2d48a4eb72ae6411dfb3aff2be774f0da7948280f7c8d2f87879906dc",
+ "profileDigest": "0f1ee008f36b747985b46098e8ceb43e8ee7465011674dd29388aba6c25b2669",
+ "systemPromptDigest": "67775f14177a07297ba4b73a5bdf9995a62742dffa97f2ccd5699431ee3f0e65",
+ "agentBinaryVersion": "1.0.2",
+ "cindyUpstreamCommit": "fa3fc88d37d205ea993a67d85612fa9a5436fae5"
+}
diff --git a/apps/cindy-headless/profiles/cindy-production-pi/prompt.md b/apps/cindy-headless/profiles/cindy-production-pi/prompt.md
new file mode 100644
index 0000000000..fac4c25ac9
--- /dev/null
+++ b/apps/cindy-headless/profiles/cindy-production-pi/prompt.md
@@ -0,0 +1,8 @@
+You are Cindy, an open-source AI assistant.
+Source: https://github.com/makecindy/cindy
+
+When asked to update the Cindy application hosting this task, call cindy_helper install_app_update (check_app_update only reads version information); Cindy asks the user to confirm, then installs with its built-in updater. If the tools report no installable update or that installation is unsupported, relay that reason and do not sideload a release; if they are unavailable, point the user to Check for Updates in Settings on the computer running Cindy. Unless the user explicitly asks for that method, do not update Cindy through shell commands by downloading or replacing the app or by killing or restarting it, and never register a persistent restart job (such as launchctl submit).
+
+Infer the user's primary language from the conversation and any explicit language preference. Whenever practical, use that language by default for reasoning, planning, explanations, and user-facing content. Preserve the language required by code, commands, identifiers, quoted material, external interfaces, or an explicit user request.
+
+Use the dedicated grep tool for content search, the find tool for file discovery, the ls tool for directory listings, and the read tool for examining files. Use Bash for Git, builds, tests, package managers, and shell operations not covered by a dedicated tool. After locating a target, read only the relevant range when practical.
diff --git a/apps/cindy-headless/profiles/cindy-tool-surface/profile.example.json b/apps/cindy-headless/profiles/cindy-tool-surface/profile.example.json
new file mode 100644
index 0000000000..307156cbf2
--- /dev/null
+++ b/apps/cindy-headless/profiles/cindy-tool-surface/profile.example.json
@@ -0,0 +1,18 @@
+{
+ "id": "cindy-tool-surface",
+ "version": 1,
+ "parentProfile": "cindy-production-claude",
+ "changedDimensions": ["cindyToolSurface"],
+ "agentBackend": "claude-code",
+ "agentBinaryPath": "/opt/cindy-headless/bin/claude",
+ "agentBinaryVersion": "2.1.280",
+ "supportedModelIds": ["claude-sonnet-4-6"],
+ "model": { "provider": "anthropic", "requestedId": "claude-sonnet-4-6", "routeId": "configured-proxy" },
+ "permissionMode": "bypassPermissions",
+ "systemPromptFile": "../cindy-production-claude/prompt.md",
+ "makerMemory": false,
+ "nativeMemory": false,
+ "projectContext": false,
+ "containerSandbox": true,
+ "compaction": { "enabled": true, "thresholdPct": 80 }
+}
diff --git a/apps/cindy-headless/runtime/node-linux-x64.json b/apps/cindy-headless/runtime/node-linux-x64.json
new file mode 100644
index 0000000000..689e4440fb
--- /dev/null
+++ b/apps/cindy-headless/runtime/node-linux-x64.json
@@ -0,0 +1,5 @@
+{
+ "version": "22.22.0",
+ "url": "https://nodejs.org/dist/v22.22.0/node-v22.22.0-linux-x64.tar.xz",
+ "sha256": "9aa8e9d2298ab68c600bd6fb86a6c13bce11a4eca1ba9b39d79fa021755d7c37"
+}
diff --git a/apps/cindy-headless/scripts/build-linux-bundle.mjs b/apps/cindy-headless/scripts/build-linux-bundle.mjs
new file mode 100644
index 0000000000..a748db3f89
--- /dev/null
+++ b/apps/cindy-headless/scripts/build-linux-bundle.mjs
@@ -0,0 +1,141 @@
+import { createHash } from 'node:crypto';
+import { execFile } from 'node:child_process';
+import { copyFile, cp, mkdir, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { promisify } from 'node:util';
+import { build } from 'esbuild';
+import { headlessBuildOptions } from './build-options.mjs';
+
+const appDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const repoRoot = path.resolve(appDir, '..', '..');
+const outputDir = path.join(appDir, 'bundle', 'linux-x64');
+const binaryCache = path.resolve(process.env.CINDY_HEADLESS_BINARY_CACHE ?? path.join(appDir, '.cache', 'bin', 'linux-x64'));
+const binary = process.env.CINDY_CLAUDE_BINARY ?? path.join(binaryCache, 'claude');
+const codexBinary = process.env.CINDY_CODEX_BINARY ?? path.join(binaryCache, 'codex');
+const piBinary = process.env.CINDY_PI_BINARY ?? path.join(binaryCache, 'pi', 'pi');
+const piRuntimeDir = path.dirname(piBinary);
+const nodeMetadata = JSON.parse(await readFile(path.join(appDir, 'runtime', 'node-linux-x64.json'), 'utf8'));
+const nodeBinary = process.env.CINDY_NODE_BINARY ?? path.join(binaryCache, 'node');
+const execFileAsync = promisify(execFile);
+const sha256 = (value) => createHash('sha256').update(value).digest('hex');
+const { stdout: worktreeStatus } = await execFileAsync('git', ['status', '--porcelain=v1', '--untracked-files=all'], { cwd: repoRoot });
+const sourceDirty = Boolean(worktreeStatus.trim());
+if (sourceDirty && process.env.CINDY_HEADLESS_ALLOW_DIRTY_BUNDLE !== '1') throw new Error('Refusing to build a scored bundle from a dirty worktree; commit the reviewed source first');
+
+async function ensureNodeRuntime() {
+ const existing = await stat(nodeBinary).catch(() => null);
+ if (existing) {
+ const { stdout } = await readBinaryVersion(nodeBinary);
+ if (stdout.trim() === `v${nodeMetadata.version}`) return;
+ }
+ const archive = path.join(binaryCache, `node-v${nodeMetadata.version}-linux-x64.tar.xz`);
+ const response = await fetch(nodeMetadata.url, { redirect: 'follow' });
+ if (!response.ok) throw new Error(`Node runtime download failed: ${response.status}`);
+ const bytes = Buffer.from(await response.arrayBuffer());
+ if (sha256(bytes) !== nodeMetadata.sha256) throw new Error('Node runtime archive digest mismatch');
+ await mkdir(binaryCache, { recursive: true });
+ await writeFile(archive, bytes);
+ const extractDir = path.join(binaryCache, '.node-extract');
+ await rm(extractDir, { recursive: true, force: true });
+ await mkdir(extractDir, { recursive: true });
+ await execFileAsync('tar', ['-xJf', path.basename(archive), '-C', path.basename(extractDir)], { cwd: binaryCache });
+ await rm(nodeBinary, { force: true });
+ await rename(path.join(extractDir, `node-v${nodeMetadata.version}-linux-x64`, 'bin', 'node'), nodeBinary);
+ await rm(extractDir, { recursive: true, force: true });
+}
+
+async function readBinaryVersion(binaryPath) {
+ try {
+ return await execFileAsync(binaryPath, ['--version'], { timeout: 30_000 });
+ } catch (error) {
+ if (process.platform !== 'win32') throw error;
+ const { stdout: linuxPath } = await execFileAsync('wsl.exe', ['-e', 'wslpath', '-a', binaryPath], { timeout: 30_000 });
+ return execFileAsync('wsl.exe', ['-e', linuxPath.trim(), '--version'], { timeout: 30_000 });
+ }
+}
+
+const latest = JSON.parse(await readFile(path.resolve(appDir, '..', '..', 'tools', 'claude', 'latest.json'), 'utf8'));
+const codexLatest = JSON.parse(await readFile(path.resolve(appDir, '..', '..', 'tools', 'codex', 'latest.json'), 'utf8'));
+const piLatest = JSON.parse(await readFile(path.resolve(appDir, '..', '..', 'tools', 'pi', 'latest.json'), 'utf8'));
+await ensureNodeRuntime();
+const [{ stdout: claudeStdout, stderr: claudeStderr }, { stdout: codexStdout, stderr: codexStderr }, { stdout: piStdout, stderr: piStderr }] = await Promise.all([
+ readBinaryVersion(binary),
+ readBinaryVersion(codexBinary),
+ readBinaryVersion(piBinary),
+]);
+const observedClaudeVersion = `${claudeStdout} ${claudeStderr}`.trim();
+const observedCodexVersion = `${codexStdout} ${codexStderr}`.trim();
+const observedPiVersion = `${piStdout} ${piStderr}`.trim();
+if (!observedClaudeVersion.includes(latest.version)) throw new Error(`Claude binary version mismatch: expected ${latest.version}, observed ${observedClaudeVersion}`);
+if (!observedCodexVersion.includes(codexLatest.version)) throw new Error(`Codex binary version mismatch: expected ${codexLatest.version}, observed ${observedCodexVersion}`);
+if (!observedPiVersion.includes(piLatest.version)) throw new Error(`Pi binary version mismatch: expected ${piLatest.version}, observed ${observedPiVersion}`);
+
+await rm(outputDir, { recursive: true, force: true });
+await mkdir(path.join(outputDir, 'dist'), { recursive: true });
+await mkdir(path.join(outputDir, 'bin'), { recursive: true });
+await build({ ...headlessBuildOptions, entryPoints: { cli: path.join(appDir, 'src', 'cli.ts'), 'eval-cli': path.join(appDir, 'src', 'eval-cli.ts') }, outdir: path.join(outputDir, 'dist') });
+await copyFile(binary, path.join(outputDir, 'bin', 'claude'));
+await copyFile(codexBinary, path.join(outputDir, 'bin', 'codex'));
+await cp(piRuntimeDir, path.join(outputDir, 'bin', 'pi'), { recursive: true });
+await copyFile(nodeBinary, path.join(outputDir, 'bin', 'node'));
+const desktopPromptDir = path.resolve(appDir, '..', 'desktop', 'src', 'main', 'maker-host');
+const desktopHost = await readFile(path.join(desktopPromptDir, 'host-system-prompt.md'), 'utf8');
+const desktopClaude = await readFile(path.join(desktopPromptDir, 'claude-system-prompt.md'), 'utf8');
+const desktopCodex = await readFile(path.join(desktopPromptDir, 'codex-system-prompt.md'), 'utf8');
+const desktopPi = await readFile(path.join(desktopPromptDir, 'pi-system-prompt.md'), 'utf8');
+const composePrompt = (...parts) => parts
+ .map((part) => part.replace(/\r\n?/g, '\n').trim())
+ .filter(Boolean)
+ .join('\n\n') + '\n';
+const productionPrompt = composePrompt(desktopHost, desktopClaude);
+const codexPrompt = composePrompt(desktopHost, desktopCodex);
+const piPrompt = composePrompt(desktopHost, desktopPi);
+await writeFile(path.join(outputDir, 'prompt.md'), productionPrompt, 'utf8');
+await writeFile(path.join(outputDir, 'codex-prompt.md'), codexPrompt, 'utf8');
+await writeFile(path.join(outputDir, 'pi-prompt.md'), piPrompt, 'utf8');
+await cp(path.join(appDir, 'profiles'), path.join(outputDir, 'profiles'), { recursive: true });
+const packageJson = JSON.parse(await readFile(path.join(appDir, 'package.json'), 'utf8'));
+const capabilityRegistryBytes = await readFile(path.join(appDir, 'capability-registry.json'));
+const capabilityRegistry = JSON.parse(capabilityRegistryBytes.toString('utf8'));
+await writeFile(path.join(outputDir, 'capability-registry.json'), capabilityRegistryBytes);
+if (!/^[0-9a-f]{40}$/.test(packageJson.cindyUpstreamCommit ?? '')) throw new Error('package.json must declare a full cindyUpstreamCommit');
+async function digestTree(directory) {
+ const hash = createHash('sha256');
+ async function walk(current, prefix = '') {
+ const entries = await readdir(current, { withFileTypes: true });
+ entries.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
+ for (const entry of entries) {
+ const relative = prefix ? `${prefix}/${entry.name}` : entry.name;
+ if (entry.isDirectory()) await walk(path.join(current, entry.name), relative);
+ else if (entry.isFile()) { hash.update(relative); hash.update('\0'); hash.update(await readFile(path.join(current, entry.name))); hash.update('\0'); }
+ else throw new Error(`unsupported Pi runtime entry: ${relative}`);
+ }
+ }
+ await walk(directory);
+ return hash.digest('hex');
+}
+const [{ stdout: commit }, { stdout: commitDate }, lockfile, cliBytes, evalCliBytes, binaryBytes, codexBinaryBytes, piBinaryBytes, nodeBinaryBytes, piRuntimeDigest, profilesDigest] = await Promise.all([
+ execFileAsync('git', ['rev-parse', 'HEAD'], { cwd: repoRoot }),
+ execFileAsync('git', ['show', '-s', '--format=%cI', 'HEAD'], { cwd: repoRoot }),
+ readFile(path.join(repoRoot, 'pnpm-lock.yaml')),
+ readFile(path.join(outputDir, 'dist', 'cli.cjs')),
+ readFile(path.join(outputDir, 'dist', 'eval-cli.cjs')),
+ readFile(binary),
+ readFile(codexBinary),
+ readFile(piBinary),
+ readFile(nodeBinary),
+ digestTree(piRuntimeDir),
+ digestTree(path.join(outputDir, 'profiles')),
+]);
+const supportedFeatures = Object.keys(capabilityRegistry.features);
+const capabilityCatalog = {
+ schemaVersion: capabilityRegistry.schemaVersion,
+ contractVersion: capabilityRegistry.contractVersion,
+ harnesses: Object.entries(capabilityRegistry.harnesses).map(([backend, definition]) => ({ ...definition, backend, adapterSupported: true })),
+ features: capabilityRegistry.features,
+ controls: capabilityRegistry.controls,
+ defaultValues: Object.fromEntries(supportedFeatures.map((id) => [id, capabilityRegistry.features[id].default])),
+ constraints: capabilityRegistry.constraints,
+};
+await writeFile(path.join(outputDir, 'bundle-manifest.json'), JSON.stringify({ schemaVersion: 5, headlessContractVersion: 1, bundleMode: sourceDirty ? 'development' : 'formal', capabilityCatalog, capabilityRegistryDigest: sha256(capabilityRegistryBytes), cindyHeadlessVersion: packageJson.version, cindyUpstreamCommit: packageJson.cindyUpstreamCommit, cindyCommit: commit.trim(), sourceDirty, lockfileDigest: sha256(lockfile), cliDigest: sha256(cliBytes), evalCliDigest: sha256(evalCliBytes), profilesDigest, systemPromptDigest: sha256(productionPrompt), codexSystemPromptDigest: sha256(codexPrompt), piSystemPromptDigest: sha256(piPrompt), nodeBinaryDigest: sha256(nodeBinaryBytes), nodeVersion: nodeMetadata.version, claudeBinaryDigest: sha256(binaryBytes), codexBinaryDigest: sha256(codexBinaryBytes), piBinaryDigest: sha256(piBinaryBytes), piRuntimeDigest, claudeCodeVersion: latest.version, codexVersion: codexLatest.version, piVersion: piLatest.version, observedClaudeVersion, observedCodexVersion, observedPiVersion, platform: 'linux-x64', generatedAt: commitDate.trim() }, null, 2) + '\n');
diff --git a/apps/cindy-headless/scripts/build-options.mjs b/apps/cindy-headless/scripts/build-options.mjs
new file mode 100644
index 0000000000..edfa534c12
--- /dev/null
+++ b/apps/cindy-headless/scripts/build-options.mjs
@@ -0,0 +1,14 @@
+/** Shared by development and Linux distribution builds. */
+export const headlessBuildOptions = {
+ outExtension: { '.js': '.cjs' },
+ bundle: true,
+ platform: 'node',
+ format: 'cjs',
+ target: 'node22',
+ sourcemap: true,
+ loader: { '.md': 'text' },
+ // Bundled ESM dependencies call createRequire(import.meta.url) on startup.
+ // Resolve relative to the delivered CLI, not the build machine or its cwd.
+ define: { 'import.meta.url': '__headlessModuleUrl' },
+ banner: { js: 'const __headlessModuleUrl = require("node:url").pathToFileURL(__filename).href;' },
+};
diff --git a/apps/cindy-headless/scripts/build.mjs b/apps/cindy-headless/scripts/build.mjs
new file mode 100644
index 0000000000..1ff5fc0d27
--- /dev/null
+++ b/apps/cindy-headless/scripts/build.mjs
@@ -0,0 +1,18 @@
+import { mkdir, rm } from 'node:fs/promises';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { build } from 'esbuild';
+import { headlessBuildOptions } from './build-options.mjs';
+
+const appDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const distDir = path.join(appDir, 'dist');
+await rm(distDir, { recursive: true, force: true });
+await mkdir(distDir, { recursive: true });
+await build({
+ ...headlessBuildOptions,
+ entryPoints: {
+ cli: path.join(appDir, 'src', 'cli.ts'),
+ 'eval-cli': path.join(appDir, 'src', 'eval-cli.ts'),
+ },
+ outdir: distDir,
+});
diff --git a/apps/cindy-headless/scripts/bundle-dist.mjs b/apps/cindy-headless/scripts/bundle-dist.mjs
new file mode 100644
index 0000000000..4389b6f0f4
--- /dev/null
+++ b/apps/cindy-headless/scripts/bundle-dist.mjs
@@ -0,0 +1,16 @@
+import { createHash } from 'node:crypto';
+import { lstat, readFile } from 'node:fs/promises';
+import path from 'node:path';
+
+/** A release can only use the CLI files bound to its bundle manifest. */
+export async function requireBundleDist(bundleDir, manifest) {
+ const directory = path.join(bundleDir, 'dist');
+ if (!(await lstat(directory)).isDirectory()) throw new Error('bundle dist must be a regular directory; rebuild the bundle');
+ for (const [name, field] of [['cli.cjs', 'cliDigest'], ['eval-cli.cjs', 'evalCliDigest']]) {
+ const file = path.join(directory, name);
+ if (!(await lstat(file)).isFile()) throw new Error(`bundle ${name} must be a regular file`);
+ const digest = createHash('sha256').update(await readFile(file)).digest('hex');
+ if (typeof manifest[field] !== 'string' || digest !== manifest[field]) throw new Error(`bundle ${name} digest mismatch; rebuild the bundle`);
+ }
+ return directory;
+}
diff --git a/apps/cindy-headless/scripts/distribution-doctor.mjs b/apps/cindy-headless/scripts/distribution-doctor.mjs
new file mode 100644
index 0000000000..b24bba72bb
--- /dev/null
+++ b/apps/cindy-headless/scripts/distribution-doctor.mjs
@@ -0,0 +1,30 @@
+import { execFile } from 'node:child_process';
+import { access, readFile } from 'node:fs/promises';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { promisify } from 'node:util';
+
+const execFileAsync = promisify(execFile);
+const appDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const repoRoot = path.resolve(appDir, '..', '..');
+const checks = [];
+async function command(name, args = ['--version']) {
+ try { const result = await execFileAsync(name, args, { timeout: 30_000 }); checks.push({ name, ok: true, detail: `${result.stdout} ${result.stderr}`.trim().split('\n')[0] }); }
+ catch { checks.push({ name, ok: false, detail: 'not available' }); }
+}
+await command('node');
+await command('pnpm');
+await command('docker');
+await command(process.env.HARBOR_BIN ?? 'harbor');
+try {
+ const manifest = JSON.parse(await readFile(path.join(appDir, 'bundle', 'linux-x64', 'bundle-manifest.json'), 'utf8'));
+ const harnesses = manifest.capabilityCatalog?.harnesses?.map((item) => item.backend) ?? [];
+ checks.push({ name: 'bundle', ok: manifest.schemaVersion === 5 && manifest.headlessContractVersion === 1 && ['claude-code', 'codex', 'pi'].every((backend) => harnesses.includes(backend)) && /^[0-9a-f]{40}$/.test(manifest.cindyUpstreamCommit ?? '') && Boolean(manifest.cliDigest && manifest.evalCliDigest && manifest.profilesDigest && manifest.nodeBinaryDigest && manifest.nodeVersion && manifest.piRuntimeDigest), detail: `${manifest.cindyHeadlessVersion ?? 'unknown'} / ${manifest.cindyUpstreamCommit ?? 'unknown'}` });
+} catch { checks.push({ name: 'bundle', ok: false, detail: 'missing or invalid manifest' }); }
+const configCandidates = [path.join(appDir, 'config.local.json'), process.env.CINDY_HEADLESS_CONFIG_FILE].filter(Boolean);
+let configured = Boolean(process.env.CINDY_HEADLESS_API_KEY && process.env.CINDY_HEADLESS_BASE_URL);
+for (const file of configCandidates) { try { await access(file); configured = true; break; } catch { /* continue */ } }
+checks.push({ name: 'gateway', ok: configured, detail: configured ? 'configured (secret not read)' : 'missing' });
+const failed = checks.filter((check) => !check.ok);
+console.log(JSON.stringify({ status: failed.length ? 'MISSING_DEPENDENCY' : 'READY', repoRoot, checks }, null, 2));
+if (failed.length) process.exitCode = 1;
diff --git a/apps/cindy-headless/scripts/ensure-agent-binaries.mjs b/apps/cindy-headless/scripts/ensure-agent-binaries.mjs
new file mode 100644
index 0000000000..f97ec0e98e
--- /dev/null
+++ b/apps/cindy-headless/scripts/ensure-agent-binaries.mjs
@@ -0,0 +1,98 @@
+import { createHash } from 'node:crypto';
+import { createReadStream, createWriteStream } from 'node:fs';
+import { chmod, cp, mkdir, readFile, rename, rm, stat } from 'node:fs/promises';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { pipeline } from 'node:stream/promises';
+import { Readable } from 'node:stream';
+import { execFile } from 'node:child_process';
+import { promisify } from 'node:util';
+
+const execFileAsync = promisify(execFile);
+const appDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const repoRoot = path.resolve(appDir, '..', '..');
+const cacheDir = path.resolve(process.env.CINDY_HEADLESS_BINARY_CACHE ?? path.join(appDir, '.cache', 'bin', 'linux-x64'));
+const metadataRoot = process.env.CINDY_HEADLESS_METADATA_ROOT ?? repoRoot;
+const claudeMeta = JSON.parse(await readFile(path.join(metadataRoot, 'tools', 'claude', 'latest.json'), 'utf8'));
+const codexMeta = JSON.parse(await readFile(path.join(metadataRoot, 'tools', 'codex', 'latest.json'), 'utf8'));
+const piMeta = JSON.parse(await readFile(path.join(metadataRoot, 'tools', 'pi', 'latest.json'), 'utf8'));
+
+async function digest(file) {
+ const hash = createHash('sha256');
+ for await (const chunk of createReadStream(file)) hash.update(chunk);
+ return hash.digest('hex');
+}
+
+async function download(url, output) {
+ const response = await fetch(url, { redirect: 'follow' });
+ if (!response.ok || !response.body) throw new Error(`download failed (${response.status}) for ${url}`);
+ const temporary = `${output}.download`;
+ await rm(temporary, { force: true });
+ await pipeline(Readable.fromWeb(response.body), createWriteStream(temporary));
+ await rename(temporary, output);
+}
+
+async function ensureClaude() {
+ const asset = claudeMeta.runtimeAssets['linux-x64'];
+ const output = path.join(cacheDir, 'claude');
+ try { if ((await stat(output)).size === asset.size && await digest(output) === asset.sha256) return output; } catch { /* download */ }
+ await download(asset.url, output);
+ if (await digest(output) !== asset.sha256) throw new Error('downloaded Claude binary digest mismatch');
+ await chmod(output, 0o755);
+ return output;
+}
+
+async function ensureCodex() {
+ const asset = codexMeta.runtimeAssets['linux-x64'];
+ const archive = path.join(cacheDir, 'codex.tar.gz');
+ const output = path.join(cacheDir, 'codex');
+ if (!(await stat(archive).catch(() => null)) || await digest(archive) !== asset.sha256) {
+ await download(asset.url, archive);
+ if (await digest(archive) !== asset.sha256) throw new Error('downloaded Codex archive digest mismatch');
+ }
+ const extractDir = path.join(cacheDir, '.codex-extract');
+ await rm(extractDir, { recursive: true, force: true });
+ await mkdir(extractDir, { recursive: true });
+ await execFileAsync('tar', ['-xzf', path.basename(archive), '-C', path.basename(extractDir)], { cwd: cacheDir });
+ const candidates = ['codex-x86_64-unknown-linux-musl', 'codex'];
+ let source;
+ for (const candidate of candidates) {
+ const file = path.join(extractDir, candidate);
+ if (await stat(file).catch(() => null)) { source = file; break; }
+ }
+ if (!source) throw new Error('Codex archive did not contain the expected binary');
+ await rm(output, { force: true });
+ await rename(source, output);
+ await chmod(output, 0o755);
+ await rm(extractDir, { recursive: true, force: true });
+ return output;
+}
+
+async function ensurePi() {
+ const asset = piMeta.runtimeAssets['linux-x64'];
+ const archive = path.join(cacheDir, 'pi.tar.gz');
+ const outputDir = path.join(cacheDir, 'pi');
+ const output = path.join(outputDir, 'pi');
+ // Pi is a directory distribution. Re-extract the pinned archive on every
+ // preparation so a present executable cannot hide missing or modified
+ // sibling themes/native assets.
+ if (!(await stat(archive).catch(() => null)) || await digest(archive) !== asset.sha256) {
+ await download(asset.url, archive);
+ if (await digest(archive) !== asset.sha256) throw new Error('downloaded Pi archive digest mismatch');
+ }
+ const extractDir = path.join(cacheDir, '.pi-extract');
+ await rm(extractDir, { recursive: true, force: true });
+ await mkdir(extractDir, { recursive: true });
+ await execFileAsync('tar', ['-xzf', path.basename(archive), '-C', path.basename(extractDir)], { cwd: cacheDir });
+ const nested = path.join(extractDir, 'pi');
+ const source = (await stat(path.join(nested, 'pi')).catch(() => null)) ? nested : extractDir;
+ await rm(outputDir, { recursive: true, force: true });
+ await cp(source, outputDir, { recursive: true });
+ await chmod(output, 0o755);
+ await rm(extractDir, { recursive: true, force: true });
+ return output;
+}
+
+await mkdir(cacheDir, { recursive: true });
+const [claude, codex, pi] = await Promise.all([ensureClaude(), ensureCodex(), ensurePi()]);
+console.log(JSON.stringify({ ok: true, cacheDir, claude, codex, pi, claudeVersion: claudeMeta.version, codexVersion: codexMeta.version, piVersion: piMeta.version }, null, 2));
diff --git a/apps/cindy-headless/scripts/freeze-production-profiles.mjs b/apps/cindy-headless/scripts/freeze-production-profiles.mjs
new file mode 100644
index 0000000000..1884de5f37
--- /dev/null
+++ b/apps/cindy-headless/scripts/freeze-production-profiles.mjs
@@ -0,0 +1,41 @@
+import { createHash } from 'node:crypto';
+import { readFile, writeFile } from 'node:fs/promises';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const appDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const packageJson = JSON.parse(await readFile(path.join(appDir, 'package.json'), 'utf8'));
+const sha256 = (value) => createHash('sha256').update(value).digest('hex');
+
+function canonicalize(value) {
+ if (Array.isArray(value)) return value.map(canonicalize);
+ if (!value || typeof value !== 'object') return value;
+ return Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, child]) => [key, canonicalize(child)]));
+}
+
+for (const target of [
+ { directory: 'cindy-production-claude', aliases: ['cindy-production-cc'] },
+ { directory: 'cindy-production-pi' },
+]) {
+ const directory = path.join(appDir, 'profiles', target.directory);
+ const profileFile = 'profile.example.json';
+ const rawProfile = await readFile(path.join(directory, profileFile), 'utf8');
+ const profile = JSON.parse(rawProfile);
+ const prompt = profile.systemPromptFile ? await readFile(path.join(directory, profile.systemPromptFile)) : null;
+ const lock = {
+ schemaVersion: 1,
+ status: 'frozen',
+ profileId: profile.id,
+ ...(target.aliases ? { aliases: target.aliases } : {}),
+ profileFile,
+ profileFileSha256: sha256(rawProfile),
+ profileDigest: sha256(JSON.stringify(canonicalize(profile))),
+ systemPromptDigest: prompt ? sha256(prompt) : null,
+ agentBinaryVersion: profile.agentBinaryVersion,
+ cindyUpstreamCommit: packageJson.cindyUpstreamCommit,
+ };
+ if (profile.expectedSystemPromptDigest && profile.expectedSystemPromptDigest !== lock.systemPromptDigest) {
+ throw new Error(`${target.directory} expectedSystemPromptDigest does not match ${profile.systemPromptFile}`);
+ }
+ await writeFile(path.join(directory, 'profile.lock.json'), JSON.stringify(lock, null, 2) + '\n');
+}
diff --git a/apps/cindy-headless/scripts/package-release.mjs b/apps/cindy-headless/scripts/package-release.mjs
new file mode 100644
index 0000000000..fa8fb0cf9d
--- /dev/null
+++ b/apps/cindy-headless/scripts/package-release.mjs
@@ -0,0 +1,87 @@
+import { requireBundleDist } from './bundle-dist.mjs';
+import { createHash } from 'node:crypto';
+import { createReadStream } from 'node:fs';
+import { cp, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { execFile } from 'node:child_process';
+import { promisify } from 'node:util';
+
+const execFileAsync = promisify(execFile);
+const appDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const repoRoot = path.resolve(appDir, '..', '..');
+const bundleDir = path.join(appDir, 'bundle', 'linux-x64');
+const releaseDir = path.resolve(process.env.CINDY_HEADLESS_RELEASE_DIR ?? path.join(appDir, 'release'));
+const mode = process.argv.find((arg) => arg.startsWith('--mode='))?.slice('--mode='.length);
+if (mode !== 'full' && mode !== 'public-runtime') {
+ throw new Error('package-release.mjs requires explicit --mode=full or --mode=public-runtime');
+}
+const includesVendorBinaries = mode === 'full';
+const packageJson = JSON.parse(await readFile(path.join(appDir, 'package.json'), 'utf8'));
+const bundleManifest = JSON.parse(await readFile(path.join(bundleDir, 'bundle-manifest.json'), 'utf8'));
+const version = packageJson.version;
+if (bundleManifest.cindyHeadlessVersion !== version) throw new Error('bundle manifest version does not match package version; rebuild the bundle first');
+if (bundleManifest.cindyUpstreamCommit !== packageJson.cindyUpstreamCommit) throw new Error('bundle manifest Cindy upstream commit does not match package metadata; rebuild the bundle first');
+const bundleDist = await requireBundleDist(bundleDir, bundleManifest);
+
+async function sha(file) {
+ const hash = createHash('sha256');
+ for await (const chunk of createReadStream(file)) hash.update(chunk);
+ return hash.digest('hex');
+}
+async function archive(name, staging) {
+ const output = path.join(releaseDir, `${name}.tar.gz`);
+ // Keep drive-letter paths out of tar arguments so both BSD tar and GNU tar
+ // behave consistently on Windows.
+ await execFileAsync('tar', ['-czf', path.basename(output), '-C', path.relative(releaseDir, staging), 'cindy-headless'], { cwd: releaseDir });
+ return output;
+}
+
+await rm(releaseDir, { recursive: true, force: true });
+await mkdir(releaseDir, { recursive: true });
+const runtimeStage = path.join(releaseDir, '.runtime');
+const runtimeRoot = path.join(runtimeStage, 'cindy-headless');
+await mkdir(runtimeRoot, { recursive: true });
+await cp(bundleDist, path.join(runtimeRoot, 'dist'), { recursive: true });
+await mkdir(path.join(runtimeRoot, 'bin'), { recursive: true });
+await cp(path.join(bundleDir, 'bin', 'node'), path.join(runtimeRoot, 'bin', 'node'));
+for (const item of ['prompt.md', 'codex-prompt.md', 'pi-prompt.md', 'bundle-manifest.json', 'capability-registry.json']) await cp(path.join(bundleDir, item), path.join(runtimeRoot, item), { recursive: true });
+await cp(path.join(bundleDir, 'profiles'), path.join(runtimeRoot, 'profiles'), { recursive: true });
+await cp(path.join(appDir, 'README.md'), path.join(runtimeRoot, 'README.md'));
+await cp(path.join(appDir, 'CINDY_FEATURE_PARITY.md'), path.join(runtimeRoot, 'CINDY_FEATURE_PARITY.md'));
+await cp(path.join(appDir, 'UPDATE_AND_PACKAGE.zh-CN.md'), path.join(runtimeRoot, 'UPDATE_AND_PACKAGE.zh-CN.md'));
+await cp(path.join(appDir, 'config.example.json'), path.join(runtimeRoot, 'config.example.json'));
+await mkdir(path.join(runtimeRoot, 'scripts'), { recursive: true });
+await cp(path.join(appDir, 'scripts', 'ensure-agent-binaries.mjs'), path.join(runtimeRoot, 'scripts', 'ensure-agent-binaries.mjs'));
+await mkdir(path.join(runtimeRoot, 'tools', 'claude'), { recursive: true });
+await mkdir(path.join(runtimeRoot, 'tools', 'codex'), { recursive: true });
+await mkdir(path.join(runtimeRoot, 'tools', 'pi'), { recursive: true });
+await cp(path.join(repoRoot, 'tools', 'claude', 'latest.json'), path.join(runtimeRoot, 'tools', 'claude', 'latest.json'));
+await cp(path.join(repoRoot, 'tools', 'codex', 'latest.json'), path.join(runtimeRoot, 'tools', 'codex', 'latest.json'));
+await cp(path.join(repoRoot, 'tools', 'pi', 'latest.json'), path.join(runtimeRoot, 'tools', 'pi', 'latest.json'));
+await cp(path.join(appDir, 'harbor-compatibility.json'), path.join(runtimeRoot, 'harbor-compatibility.json'));
+await writeFile(path.join(runtimeRoot, 'prepare-binaries.sh'), '#!/usr/bin/env sh\nset -eu\nROOT=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)\nCINDY_HEADLESS_METADATA_ROOT="$ROOT" CINDY_HEADLESS_BINARY_CACHE="$ROOT/bin" "$ROOT/bin/node" "$ROOT/scripts/ensure-agent-binaries.mjs"\n');
+await writeFile(path.join(runtimeRoot, 'prepare-binaries.ps1'), "$ErrorActionPreference = 'Stop'\n$root = $PSScriptRoot\n$env:CINDY_HEADLESS_METADATA_ROOT = $root\n$env:CINDY_HEADLESS_BINARY_CACHE = Join-Path $root 'bin'\nnode (Join-Path $root 'scripts\\ensure-agent-binaries.mjs')\n");
+const files = [];
+
+if (mode === 'public-runtime') {
+ files.push(await archive(`cindy-headless-linux-x64-public-runtime-no-vendor-${version}`, runtimeStage));
+} else {
+ const fullStage = path.join(releaseDir, '.full');
+ const fullRoot = path.join(fullStage, 'cindy-headless');
+ await cp(runtimeRoot, fullRoot, { recursive: true });
+ await cp(path.join(bundleDir, 'bin'), path.join(fullRoot, 'bin'), { recursive: true });
+ await writeFile(path.join(fullRoot, 'VENDOR-BINARIES-NOTICE.txt'), 'This package contains separately licensed Claude Code, Codex, and Pi runtimes. Distribution requires explicit confirmation of their applicable license terms.\n');
+ files.push(await archive(`cindy-headless-linux-x64-full-${version}`, fullStage));
+}
+
+const sums = [];
+for (const file of files) sums.push(`${await sha(file)} ${path.basename(file)}`);
+await cp(path.join(bundleDir, 'bundle-manifest.json'), path.join(releaseDir, 'bundle-manifest.json'));
+sums.push(`${await sha(path.join(releaseDir, 'bundle-manifest.json'))} bundle-manifest.json`);
+await writeFile(path.join(releaseDir, 'SHA256SUMS'), `${sums.join('\n')}\n`);
+const { stdout: sourceCommit } = await execFileAsync('git', ['rev-parse', 'HEAD'], { cwd: repoRoot });
+await writeFile(path.join(releaseDir, 'release-manifest.json'), JSON.stringify({ schemaVersion: 1, product: 'cindy-headless', version, packageMode: mode, cindyUpstreamCommit: bundleManifest.cindyUpstreamCommit, platform: 'linux-x64', sourceCommit: sourceCommit.trim(), bundleCommit: bundleManifest.cindyCommit, includesVendorBinaries, assets: files.map((file) => path.basename(file)) }, null, 2) + '\n');
+await rm(runtimeStage, { recursive: true, force: true });
+await rm(path.join(releaseDir, '.full'), { recursive: true, force: true });
+console.log(JSON.stringify({ ok: true, releaseDir, packageMode: mode, assets: files.map((file) => path.basename(file)), includesVendorBinaries }, null, 2));
diff --git a/apps/cindy-headless/scripts/package-upload.mjs b/apps/cindy-headless/scripts/package-upload.mjs
new file mode 100644
index 0000000000..8611647874
--- /dev/null
+++ b/apps/cindy-headless/scripts/package-upload.mjs
@@ -0,0 +1,131 @@
+import { createHash } from 'node:crypto';
+import { createReadStream } from 'node:fs';
+import { access, readFile, writeFile } from 'node:fs/promises';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { execFile, spawn } from 'node:child_process';
+import { promisify } from 'node:util';
+
+const execFileAsync = promisify(execFile);
+const appDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const repoRoot = path.resolve(appDir, '..', '..');
+const manifestPath = path.join(appDir, 'bundle', 'linux-x64', 'bundle-manifest.json');
+const manifestRelativePath = 'apps/cindy-headless/bundle/linux-x64/bundle-manifest.json';
+const appRelativePrefix = 'apps/cindy-headless/';
+
+async function capture(command, args, options = {}) {
+ console.log(`> ${command} ${args.join(' ')}`);
+ return execFileAsync(command, args, { cwd: repoRoot, maxBuffer: 20 * 1024 * 1024, ...options });
+}
+
+async function runPnpm(args) {
+ const pnpmScript = process.env.npm_execpath;
+ const scriptEntrypoint = pnpmScript && /\.(?:cjs|mjs|js)$/i.test(pnpmScript);
+ const command = scriptEntrypoint ? process.execPath : (pnpmScript || (process.platform === 'win32' ? 'pnpm.cmd' : 'pnpm'));
+ const commandArgs = scriptEntrypoint ? [pnpmScript, ...args] : args;
+ console.log(`> pnpm ${args.join(' ')}`);
+ await new Promise((resolve, reject) => {
+ const child = spawn(command, commandArgs, { cwd: repoRoot, stdio: 'inherit' });
+ child.once('error', reject);
+ child.once('exit', (code, signal) => {
+ if (code === 0) resolve();
+ else reject(new Error(`pnpm ${args.join(' ')} failed with ${signal ?? `exit code ${code}`}`));
+ });
+ });
+}
+
+async function sha256(file) {
+ const hash = createHash('sha256');
+ for await (const chunk of createReadStream(file)) hash.update(chunk);
+ return hash.digest('hex');
+}
+
+let { stdout: headOutput } = await capture('git', ['rev-parse', 'HEAD']);
+let head = headOutput.trim();
+const { stdout: statusOutput } = await capture('git', ['status', '--porcelain=v1', '--untracked-files=all']);
+const changed = statusOutput.split(/\r?\n/).filter(Boolean);
+let reuseExistingFormalBundle = false;
+
+const sourceChanges = changed.filter((line) => line.slice(3).replaceAll('\\', '/') !== manifestRelativePath);
+if (sourceChanges.length > 0) {
+ const outsideHeadless = sourceChanges
+ .map((line) => line.slice(3).replaceAll('\\', '/'))
+ .filter((file) => !file.startsWith(appRelativePrefix));
+ if (outsideHeadless.length > 0) {
+ throw new Error(`cannot create an automatic Headless checkpoint while other Cindy paths are dirty:\n${outsideHeadless.join('\n')}`);
+ }
+
+ let previousManifest;
+ try { previousManifest = JSON.parse(await readFile(manifestPath, 'utf8')); } catch { previousManifest = undefined; }
+ const packagePath = path.join(appDir, 'package.json');
+ const packageMetadata = JSON.parse(await readFile(packagePath, 'utf8'));
+ if (previousManifest?.cindyHeadlessVersion === packageMetadata.version) {
+ const parts = packageMetadata.version.split('.').map(Number);
+ if (parts.length !== 3 || parts.some((part) => !Number.isInteger(part) || part < 0)) {
+ throw new Error(`cannot automatically increment non-semver Headless version: ${packageMetadata.version}`);
+ }
+ const oldVersion = packageMetadata.version;
+ const newVersion = `${parts[0]}.${parts[1]}.${parts[2] + 1}`;
+ packageMetadata.version = newVersion;
+ await writeFile(packagePath, `${JSON.stringify(packageMetadata, null, 2)}\n`);
+ const replacements = [
+ ['harbor-compatibility.json', `"cindyHeadlessVersion": "${oldVersion}"`, `"cindyHeadlessVersion": "${newVersion}"`],
+ ['src/compatibility.ts', `CINDY_HEADLESS_VERSION = '${oldVersion}'`, `CINDY_HEADLESS_VERSION = '${newVersion}'`],
+ ['README.md', `Version \`${oldVersion}\``, `Version \`${newVersion}\``],
+ ['CINDY_FEATURE_PARITY.md', `Cindy Headless \`${oldVersion}\``, `Cindy Headless \`${newVersion}\``],
+ ];
+ for (const [relative, expected, replacement] of replacements) {
+ const file = path.join(appDir, relative);
+ const content = await readFile(file, 'utf8');
+ if (!content.includes(expected)) throw new Error(`version reference is not synchronized in ${relative}`);
+ await writeFile(file, content.replace(expected, replacement));
+ }
+ console.log(`Automatically incremented Cindy Headless ${oldVersion} -> ${newVersion}.`);
+ }
+
+ const { stdout: trackedManifest } = await capture('git', ['ls-files', '--', manifestRelativePath]);
+ if (trackedManifest.trim()) await capture('git', ['restore', '--', manifestRelativePath]);
+ await capture('git', ['add', '--', appRelativePrefix]);
+ const refreshedPackage = JSON.parse(await readFile(packagePath, 'utf8'));
+ await capture('git', ['commit', '-s', '-m', `chore(headless): prepare upload bundle ${refreshedPackage.version}`]);
+ ({ stdout: headOutput } = await capture('git', ['rev-parse', 'HEAD']));
+ head = headOutput.trim();
+ console.log(`Created local Headless packaging checkpoint ${head}.`);
+} else if (changed.length > 0) {
+ const onlyGeneratedManifestChanged = changed.length === 1
+ && changed[0].slice(3).replaceAll('\\', '/') === manifestRelativePath;
+ if (!onlyGeneratedManifestChanged) throw new Error('unexpected dirty worktree state');
+
+ const manifest = JSON.parse(await readFile(manifestPath, 'utf8'));
+ if (manifest.bundleMode !== 'formal' || manifest.sourceDirty !== false || manifest.cindyCommit !== head) {
+ throw new Error('the only changed file is a stale or development bundle manifest; commit or restore it before packaging');
+ }
+ reuseExistingFormalBundle = true;
+ console.log('Reusing the verified formal bundle already generated from the current HEAD.');
+}
+
+if (!reuseExistingFormalBundle) {
+ await runPnpm(['--filter', 'cindy-headless', 'bundle:linux']);
+}
+await runPnpm(['--filter', 'cindy-headless', 'verify:bundle']);
+await runPnpm(['--filter', 'cindy-headless', 'package:full']);
+await runPnpm(['--filter', 'cindy-headless', 'verify:distribution:full']);
+
+const releaseManifest = JSON.parse(await readFile(path.join(appDir, 'release', 'release-manifest.json'), 'utf8'));
+const fullAsset = releaseManifest.assets.find((asset) => /-full-/.test(asset));
+if (!fullAsset) throw new Error('full upload asset was not produced');
+const uploadPath = path.join(appDir, 'release', fullAsset);
+await access(uploadPath);
+const bundleManifest = JSON.parse(await readFile(manifestPath, 'utf8'));
+if (bundleManifest.bundleMode !== 'formal' || bundleManifest.sourceDirty !== false || bundleManifest.cindyCommit !== head) {
+ throw new Error('refusing upload: bundle identity is not a clean formal build of current HEAD');
+}
+
+console.log(JSON.stringify({
+ ok: true,
+ uploadPath,
+ sha256: await sha256(uploadPath),
+ sourceCommit: head,
+ bundleMode: bundleManifest.bundleMode,
+ sourceDirty: bundleManifest.sourceDirty,
+}, null, 2));
diff --git a/apps/cindy-headless/scripts/setup.ps1 b/apps/cindy-headless/scripts/setup.ps1
new file mode 100644
index 0000000000..443a531d78
--- /dev/null
+++ b/apps/cindy-headless/scripts/setup.ps1
@@ -0,0 +1,32 @@
+param(
+ [ValidateSet('claude', 'codex', 'all')][string]$Backend = 'all',
+ [switch]$SkipInstall,
+ [switch]$SkipBundle
+)
+$ErrorActionPreference = 'Stop'
+$appDir = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path
+$repoRoot = (Resolve-Path (Join-Path $appDir '..\..')).Path
+function Require-Command([string]$Name, [string]$Hint) {
+ if (-not (Get-Command $Name -ErrorAction SilentlyContinue)) { throw "MISSING_DEPENDENCY: $Name. $Hint" }
+ Write-Host "PASS $Name"
+}
+Require-Command node 'Install Node.js 22.'
+Require-Command pnpm 'Enable Corepack or install pnpm.'
+if (Get-Command docker -ErrorAction SilentlyContinue) { Write-Host 'PASS docker' } else { Write-Warning 'Docker is required only for Harbor smoke tests.' }
+$nodeMajor = [int]((& node --version).TrimStart('v').Split('.')[0])
+if ($nodeMajor -lt 22) { throw 'MISSING_DEPENDENCY: Node.js 22 or newer is required' }
+if (-not $SkipInstall) { & pnpm install --frozen-lockfile; if ($LASTEXITCODE -ne 0) { throw 'pnpm install failed' } }
+& npm --prefix $appDir run ensure:binaries
+if ($LASTEXITCODE -ne 0) { throw 'Agent binary preparation failed' }
+if (-not $SkipBundle) {
+ & npm --prefix $appDir run typecheck
+ & npm --prefix $appDir test -- --run
+ & npm --prefix $appDir run bundle:linux
+ & npm --prefix $appDir run verify:bundle
+ if ($LASTEXITCODE -ne 0) { throw 'Headless bundle verification failed' }
+}
+$config = Join-Path $appDir 'config.local.json'
+if (-not (Test-Path -LiteralPath $config) -and -not $env:CINDY_HEADLESS_API_KEY) {
+ Write-Warning 'Gateway config is not set. Set CINDY_HEADLESS_API_KEY through your environment before a live smoke test.'
+}
+Write-Host "READY Cindy Headless ($Backend)"
diff --git a/apps/cindy-headless/scripts/setup.sh b/apps/cindy-headless/scripts/setup.sh
new file mode 100644
index 0000000000..84ab05a8cc
--- /dev/null
+++ b/apps/cindy-headless/scripts/setup.sh
@@ -0,0 +1,13 @@
+#!/usr/bin/env sh
+set -eu
+APP_DIR=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
+command -v node >/dev/null 2>&1 || { echo 'MISSING_DEPENDENCY: Node.js 22'; exit 1; }
+command -v pnpm >/dev/null 2>&1 || { echo 'MISSING_DEPENDENCY: pnpm'; exit 1; }
+command -v docker >/dev/null 2>&1 || echo 'WARN Docker is required only for Harbor smoke tests.'
+pnpm install --frozen-lockfile
+npm --prefix "$APP_DIR" run ensure:binaries
+npm --prefix "$APP_DIR" run typecheck
+npm --prefix "$APP_DIR" test -- --run
+npm --prefix "$APP_DIR" run bundle:linux
+npm --prefix "$APP_DIR" run verify:bundle
+echo 'READY Cindy Headless'
diff --git a/apps/cindy-headless/scripts/verify-bundle.mjs b/apps/cindy-headless/scripts/verify-bundle.mjs
new file mode 100644
index 0000000000..d91b966bb6
--- /dev/null
+++ b/apps/cindy-headless/scripts/verify-bundle.mjs
@@ -0,0 +1,90 @@
+import { createHash } from 'node:crypto';
+import { execFile } from 'node:child_process';
+import { readFile, readdir, rm } from 'node:fs/promises';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { promisify } from 'node:util';
+
+const execFileAsync = promisify(execFile);
+const appDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const bundleDir = path.join(appDir, 'bundle', 'linux-x64');
+const manifest = JSON.parse(await readFile(path.join(bundleDir, 'bundle-manifest.json'), 'utf8'));
+if (manifest.schemaVersion !== 5 || manifest.headlessContractVersion !== 1) throw new Error('unsupported bundle manifest schema or contract');
+if (!Array.isArray(manifest.capabilityCatalog?.harnesses) || manifest.capabilityCatalog.harnesses.length !== 3) throw new Error('bundle manifest must declare all three harnesses');
+if (new Set(manifest.capabilityCatalog.harnesses.map((item) => item.backend)).size !== 3 || !['claude-code', 'codex', 'pi'].every((backend) => manifest.capabilityCatalog.harnesses.some((item) => item.backend === backend))) throw new Error('bundle manifest harness identities are invalid');
+if (!/^[0-9a-f]{40}$/.test(manifest.cindyUpstreamCommit ?? '')) throw new Error('bundle manifest must declare cindyUpstreamCommit');
+const registryBytes = await readFile(path.join(bundleDir, 'capability-registry.json'));
+if (!/^[a-f0-9]{64}$/.test(manifest.capabilityRegistryDigest ?? '') || createHash('sha256').update(registryBytes).digest('hex') !== manifest.capabilityRegistryDigest) throw new Error('capability registry digest mismatch');
+for (const [relativePath, expected] of [
+ ['dist/cli.cjs', manifest.cliDigest],
+ ['dist/eval-cli.cjs', manifest.evalCliDigest],
+ ['prompt.md', manifest.systemPromptDigest],
+ ['codex-prompt.md', manifest.codexSystemPromptDigest],
+ ['pi-prompt.md', manifest.piSystemPromptDigest],
+ ['bin/node', manifest.nodeBinaryDigest],
+ ['bin/claude', manifest.claudeBinaryDigest],
+ ['bin/codex', manifest.codexBinaryDigest],
+ ['bin/pi/pi', manifest.piBinaryDigest],
+]) {
+ if (typeof expected !== 'string' || !/^[a-f0-9]{64}$/.test(expected)) throw new Error(`missing or invalid digest for ${relativePath}`);
+ const bytes = await readFile(path.join(bundleDir, relativePath));
+ const actual = createHash('sha256').update(bytes).digest('hex');
+ if (actual !== expected) throw new Error(`${relativePath} digest mismatch`);
+}
+async function digestTree(directory) {
+ const hash = createHash('sha256');
+ async function walk(current, prefix = '') {
+ const entries = await readdir(current, { withFileTypes: true });
+ entries.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
+ for (const entry of entries) {
+ const relative = prefix ? `${prefix}/${entry.name}` : entry.name;
+ if (entry.isDirectory()) await walk(path.join(current, entry.name), relative);
+ else if (entry.isFile()) { hash.update(relative); hash.update('\0'); hash.update(await readFile(path.join(current, entry.name))); hash.update('\0'); }
+ else throw new Error(`unsupported Pi runtime entry: ${relative}`);
+ }
+ }
+ await walk(directory);
+ return hash.digest('hex');
+}
+if (await digestTree(path.join(bundleDir, 'bin', 'pi')) !== manifest.piRuntimeDigest) throw new Error('Pi runtime digest mismatch');
+if (await digestTree(path.join(bundleDir, 'profiles')) !== manifest.profilesDigest) throw new Error('profiles digest mismatch');
+const run = async (command, args) => execFileAsync(command, args, { cwd: bundleDir, timeout: 30_000 });
+const runBundleBinary = async (name, args) => {
+ if (process.platform !== 'win32') return execFileAsync(path.join(bundleDir, 'bin', name), args, { cwd: bundleDir, timeout: 30_000 });
+ const { stdout: linuxBundle } = await execFileAsync('wsl.exe', ['-e', 'wslpath', '-a', bundleDir], { timeout: 30_000 });
+ return execFileAsync('wsl.exe', ['--cd', linuxBundle.trim(), '-e', `./bin/${name}`, ...args], { timeout: 30_000 });
+};
+const version = await runBundleBinary('node', ['dist/cli.cjs', 'version']);
+if (typeof manifest.cindyHeadlessVersion !== 'string' || !version.stdout.includes(manifest.cindyHeadlessVersion)) throw new Error('Cindy CLI version mismatch');
+if (!version.stdout.includes(manifest.cindyUpstreamCommit)) throw new Error('Cindy upstream commit mismatch');
+const capabilities = await runBundleBinary('node', ['dist/cli.cjs', 'capabilities', '--manifest', 'bundle-manifest.json']);
+const discovered = JSON.parse(capabilities.stdout);
+if (discovered.adapter?.detected?.some((item) => item.status !== 'SUPPORTED')) throw new Error('bundle contains capabilities unsupported by this Adapter');
+if (discovered.harnesses?.some((item) => item.status !== 'SUPPORTED')) throw new Error('bundle contains a harness unsupported by this Adapter');
+for (const harness of ['claude-code', 'codex', 'pi']) {
+ const generated = `.verify/profile-${harness}.json`;
+ await runBundleBinary('node', ['dist/cli.cjs', 'profile', 'generate', '--manifest', 'bundle-manifest.json', '--harness', harness, '--output', generated]);
+ await runBundleBinary('node', ['dist/cli.cjs', 'profile', 'validate', '--profile', generated, '--bundle-dir', '.']);
+ await runBundleBinary('node', ['dist/cli.cjs', 'compatibility-report', '--profile', generated, '--bundle-dir', '.']);
+}
+await rm(path.join(bundleDir, '.verify'), { recursive: true, force: true });
+for (const profile of [
+ 'profiles/cindy-production-claude/profile.example.json',
+ 'profiles/cindy-production-codex/profile.example.json',
+ 'profiles/cindy-production-pi/profile.example.json',
+]) {
+ await runBundleBinary('node', ['dist/cli.cjs', 'profile', 'validate', '--profile', profile, '--bundle-dir', '.']);
+}
+await runBundleBinary('node', ['dist/eval-cli.cjs']).catch((error) => {
+ if (error.code !== 2 && error.status !== 2) throw error;
+});
+const claudeVersion = await runBundleBinary('claude', ['--version']);
+if (!claudeVersion.stdout.includes(manifest.claudeCodeVersion)) throw new Error('Claude bundle version mismatch');
+const codexVersion = await runBundleBinary('codex', ['--version']);
+if (!codexVersion.stdout.includes(manifest.codexVersion)) throw new Error('Codex bundle version mismatch');
+await runBundleBinary('codex', ['app-server', '--help']);
+const piVersion = await runBundleBinary('pi/pi', ['--version']);
+if (!`${piVersion.stdout} ${piVersion.stderr}`.includes(manifest.piVersion)) throw new Error('Pi bundle version mismatch');
+const nodeVersion = await runBundleBinary('node', ['--version']);
+if (!nodeVersion.stdout.includes(manifest.nodeVersion)) throw new Error('Node bundle version mismatch');
+console.log(JSON.stringify({ ok: true, manifestSchema: manifest.schemaVersion, headlessContractVersion: manifest.headlessContractVersion, cindyHeadlessVersion: manifest.cindyHeadlessVersion, cindyUpstreamCommit: manifest.cindyUpstreamCommit, nodeVersion: manifest.nodeVersion, claudeCodeVersion: manifest.claudeCodeVersion, codexVersion: manifest.codexVersion, piVersion: manifest.piVersion }, null, 2));
diff --git a/apps/cindy-headless/scripts/verify-clean-install.ps1 b/apps/cindy-headless/scripts/verify-clean-install.ps1
new file mode 100644
index 0000000000..5f0b014a54
--- /dev/null
+++ b/apps/cindy-headless/scripts/verify-clean-install.ps1
@@ -0,0 +1,27 @@
+param(
+ [string]$Repository = 'https://github.com/makecindy/cindy.git',
+ [string]$Branch = 'main'
+)
+$ErrorActionPreference = 'Stop'
+$root = Join-Path ([System.IO.Path]::GetTempPath()) "cindy-headless-clean-$([guid]::NewGuid().ToString('N'))"
+try {
+ git clone --depth 1 --branch $Branch $Repository $root
+ if ($LASTEXITCODE -ne 0) { throw 'Clean clone failed' }
+ Push-Location $root
+ try {
+ pnpm install --frozen-lockfile
+ if ($LASTEXITCODE -ne 0) { throw 'Frozen install failed' }
+ foreach ($script in @('verify', 'bundle:linux', 'verify:bundle', 'test:distribution')) {
+ pnpm --filter cindy-headless run $script
+ if ($LASTEXITCODE -ne 0) { throw "Headless $script failed" }
+ }
+ } finally { Pop-Location }
+ Write-Host 'PASS clean clone verification'
+} finally {
+ if (Test-Path -LiteralPath $root) {
+ Get-ChildItem -LiteralPath $root -Recurse -Force -File -ErrorAction SilentlyContinue | ForEach-Object { $_.IsReadOnly = $false }
+ for ($attempt = 0; $attempt -lt 3; $attempt++) {
+ try { [System.IO.Directory]::Delete($root, $true); break } catch { if ($attempt -eq 2) { Write-Warning "Could not remove clean-test directory: $root" } else { Start-Sleep -Seconds 1 } }
+ }
+ }
+}
diff --git a/apps/cindy-headless/scripts/verify-distribution.mjs b/apps/cindy-headless/scripts/verify-distribution.mjs
new file mode 100644
index 0000000000..1b52774e3a
--- /dev/null
+++ b/apps/cindy-headless/scripts/verify-distribution.mjs
@@ -0,0 +1,56 @@
+import assert from 'node:assert/strict';
+import { execFile } from 'node:child_process';
+import { mkdtemp, readFile, readdir, rm } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import { promisify } from 'node:util';
+
+const execFileAsync = promisify(execFile);
+const repoRoot = path.resolve(import.meta.dirname, '..', '..', '..');
+const temporary = await mkdtemp(path.join(os.tmpdir(), 'cindy-headless-distribution-'));
+try {
+ const bundleManifest = JSON.parse(await readFile(path.join(repoRoot, 'apps', 'cindy-headless', 'bundle', 'linux-x64', 'bundle-manifest.json'), 'utf8'));
+ const packageScript = path.join(repoRoot, 'apps', 'cindy-headless', 'scripts', 'package-release.mjs');
+ await assert.rejects(
+ execFileAsync('node', [packageScript], { env: { ...process.env, CINDY_HEADLESS_RELEASE_DIR: path.join(temporary, 'implicit-release') } }),
+ /requires explicit --mode=full or --mode=public-runtime/,
+ );
+ await execFileAsync('node', [packageScript, '--mode=public-runtime'], { env: { ...process.env, CINDY_HEADLESS_RELEASE_DIR: path.join(temporary, 'release') } });
+ const release = JSON.parse(await readFile(path.join(temporary, 'release', 'release-manifest.json'), 'utf8'));
+ assert.equal(release.product, 'cindy-headless');
+ assert.equal(release.packageMode, 'public-runtime');
+ assert.equal(release.cindyUpstreamCommit, bundleManifest.cindyUpstreamCommit);
+ assert.equal(release.includesVendorBinaries, false);
+ assert.equal(release.assets.length, 1);
+ const sums = await readFile(path.join(temporary, 'release', 'SHA256SUMS'), 'utf8');
+ assert.match(sums, /cindy-headless-linux-x64-public-runtime-no-vendor-/);
+ assert.doesNotMatch(sums, /cindy-headless-linux-x64-full-/);
+ assert.doesNotMatch(sums, /codex\.tar|bin\/claude/);
+ const archive = path.join(temporary, 'release', release.assets[0]);
+ await execFileAsync('tar', ['-xzf', path.relative(temporary, archive)], { cwd: temporary });
+ const releaseRoot = path.join(temporary, 'cindy-headless');
+ await readFile(path.join(releaseRoot, 'dist', 'cli.cjs'));
+ await readFile(path.join(releaseRoot, 'harbor-compatibility.json'));
+ await assert.rejects(readFile(path.join(releaseRoot, 'cindy_harbor', 'cindy_headless_agent.py')));
+ await readFile(path.join(releaseRoot, 'prepare-binaries.sh'));
+ await assert.rejects(readFile(path.join(releaseRoot, 'bin', 'claude')));
+ const readme = await readFile(path.join(releaseRoot, 'README.md'), 'utf8');
+ assert.doesNotMatch(readme, /sk-[A-Za-z0-9_-]{12,}|github_pat_|gho_/);
+ async function scan(directory) {
+ for (const entry of await readdir(directory, { withFileTypes: true })) {
+ const file = path.join(directory, entry.name);
+ if (entry.isDirectory()) { await scan(file); continue; }
+ assert.doesNotMatch(entry.name, /auth\.json|config\.local\.json/i);
+ if (/\.(?:json|md|mjs|py|ps1|sh|toml|txt)$/.test(entry.name)) {
+ assert.doesNotMatch(await readFile(file, 'utf8'), /sk-[A-Za-z0-9_-]{12,}|github_pat_|gho_/);
+ }
+ }
+ }
+ await scan(releaseRoot);
+ const compatibility = JSON.parse(await readFile(path.join(releaseRoot, 'harbor-compatibility.json'), 'utf8'));
+ assert.equal(typeof compatibility.harborCommit, 'string');
+ assert.equal(compatibility.cindyUpstreamCommit, bundleManifest.cindyUpstreamCommit);
+ console.log(JSON.stringify({ ok: true }));
+} finally {
+ await rm(temporary, { recursive: true, force: true });
+}
diff --git a/apps/cindy-headless/scripts/verify-full-distribution.mjs b/apps/cindy-headless/scripts/verify-full-distribution.mjs
new file mode 100644
index 0000000000..1013a660d5
--- /dev/null
+++ b/apps/cindy-headless/scripts/verify-full-distribution.mjs
@@ -0,0 +1,115 @@
+import assert from 'node:assert/strict';
+import { createHash } from 'node:crypto';
+import { execFile } from 'node:child_process';
+import { createReadStream } from 'node:fs';
+import { mkdtemp, readFile, readdir, rm, stat } from 'node:fs/promises';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { promisify } from 'node:util';
+
+const execFileAsync = promisify(execFile);
+const appDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const releaseDir = path.resolve(process.env.CINDY_HEADLESS_RELEASE_DIR ?? path.join(appDir, 'release'));
+
+async function digest(file) {
+ const hash = createHash('sha256');
+ for await (const chunk of createReadStream(file)) hash.update(chunk);
+ return hash.digest('hex');
+}
+
+async function digestTree(directory) {
+ const hash = createHash('sha256');
+ async function walk(current, prefix = '') {
+ const entries = await readdir(current, { withFileTypes: true });
+ entries.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
+ for (const entry of entries) {
+ const relative = prefix ? `${prefix}/${entry.name}` : entry.name;
+ if (entry.isDirectory()) await walk(path.join(current, entry.name), relative);
+ else if (entry.isFile()) { hash.update(relative); hash.update('\0'); hash.update(await readFile(path.join(current, entry.name))); hash.update('\0'); }
+ else throw new Error(`unsupported Pi runtime entry: ${relative}`);
+ }
+ }
+ await walk(directory);
+ return hash.digest('hex');
+}
+
+const release = JSON.parse(await readFile(path.join(releaseDir, 'release-manifest.json'), 'utf8'));
+assert.equal(release.product, 'cindy-headless');
+assert.equal(release.packageMode, 'full');
+assert.match(release.cindyUpstreamCommit, /^[0-9a-f]{40}$/);
+assert.equal(release.includesVendorBinaries, true, 'release manifest must identify the vendor binaries');
+const fullAsset = release.assets.find((asset) => /-full-/.test(asset));
+assert.ok(fullAsset, 'release manifest does not list a full package');
+assert.deepEqual(release.assets, [fullAsset], 'full release directory must contain only the upload-ready full package');
+
+const sums = new Map();
+for (const line of (await readFile(path.join(releaseDir, 'SHA256SUMS'), 'utf8')).trim().split('\n')) {
+ const match = line.match(/^([a-f0-9]{64})\s+(.+)$/);
+ assert.ok(match, `invalid SHA256SUMS line: ${line}`);
+ sums.set(match[2], match[1]);
+}
+for (const asset of [...release.assets, 'bundle-manifest.json']) {
+ assert.equal(await digest(path.join(releaseDir, asset)), sums.get(asset), `${asset} checksum mismatch`);
+}
+
+const temporary = await mkdtemp(path.join(releaseDir, '.verify-full-'));
+try {
+ await execFileAsync('tar', ['-xzf', fullAsset, '-C', path.basename(temporary)], { cwd: releaseDir });
+ const root = path.join(temporary, 'cindy-headless');
+ const bundle = JSON.parse(await readFile(path.join(root, 'bundle-manifest.json'), 'utf8'));
+ assert.equal(await digest(path.join(root, 'dist', 'cli.cjs')), bundle.cliDigest, 'CLI digest mismatch');
+ assert.equal(await digest(path.join(root, 'dist', 'eval-cli.cjs')), bundle.evalCliDigest, 'Eval CLI digest mismatch');
+ assert.equal(await digest(path.join(root, 'bin', 'node')), bundle.nodeBinaryDigest, 'Node binary digest mismatch');
+ assert.equal(await digest(path.join(root, 'bin', 'claude')), bundle.claudeBinaryDigest, 'Claude binary digest mismatch');
+ assert.equal(await digest(path.join(root, 'bin', 'codex')), bundle.codexBinaryDigest, 'Codex binary digest mismatch');
+ assert.equal(await digest(path.join(root, 'bin', 'pi', 'pi')), bundle.piBinaryDigest, 'Pi binary digest mismatch');
+ assert.equal(await digestTree(path.join(root, 'bin', 'pi')), bundle.piRuntimeDigest, 'Pi runtime digest mismatch');
+ assert.equal(await digestTree(path.join(root, 'profiles')), bundle.profilesDigest, 'profiles digest mismatch');
+ assert.ok((await stat(path.join(root, 'bin', 'claude'))).size > 0);
+ assert.ok((await stat(path.join(root, 'bin', 'codex'))).size > 0);
+ assert.ok((await stat(path.join(root, 'bin', 'pi', 'pi'))).size > 0);
+ assert.ok((await stat(path.join(root, 'bin', 'node'))).size > 0);
+ await readFile(path.join(root, 'VENDOR-BINARIES-NOTICE.txt'));
+ await readFile(path.join(root, 'UPDATE_AND_PACKAGE.zh-CN.md'));
+ await readFile(path.join(root, 'prepare-binaries.sh'));
+ let cliPath = path.join(root, 'dist', 'cli.cjs');
+ if (process.platform === 'win32') {
+ const { stdout: linuxRoot } = await execFileAsync('wsl.exe', ['-e', 'wslpath', '-a', root], { timeout: 30_000 });
+ cliPath = path.posix.join(linuxRoot.trim(), 'dist/cli.cjs');
+ }
+ const { stdout } = await runBinary('node', [cliPath, 'version']);
+ const version = JSON.parse(stdout);
+ assert.equal(version.name, 'cindy-headless');
+ assert.equal(version.version, release.version);
+ assert.equal(version.cindyUpstreamCommit, release.cindyUpstreamCommit);
+ assert.equal(bundle.cindyUpstreamCommit, release.cindyUpstreamCommit);
+ async function runBinary(name, args) {
+ if (process.platform !== 'win32') return execFileAsync(path.join(root, 'bin', name), args, { timeout: 30_000 });
+ const { stdout: linuxRoot } = await execFileAsync('wsl.exe', ['-e', 'wslpath', '-a', root], { timeout: 30_000 });
+ return execFileAsync('wsl.exe', ['-e', path.posix.join(linuxRoot.trim(), `bin/${name}`), ...args], { timeout: 30_000 });
+ }
+ const nodeVersion = await runBinary('node', ['--version']);
+ const claudeVersion = await runBinary('claude', ['--version']);
+ const codexVersion = await runBinary('codex', ['--version']);
+ const piVersion = await runBinary('pi/pi', ['--version']);
+ assert.match(`${claudeVersion.stdout} ${claudeVersion.stderr}`, new RegExp(bundle.claudeCodeVersion.replaceAll('.', '\\.')));
+ assert.match(`${codexVersion.stdout} ${codexVersion.stderr}`, new RegExp(bundle.codexVersion.replaceAll('.', '\\.')));
+ assert.match(`${piVersion.stdout} ${piVersion.stderr}`, new RegExp(bundle.piVersion.replaceAll('.', '\\.')));
+ assert.match(`${nodeVersion.stdout} ${nodeVersion.stderr}`, new RegExp(bundle.nodeVersion.replaceAll('.', '\\.')));
+ await runBinary('codex', ['app-server', '--help']);
+
+ async function scan(directory) {
+ for (const entry of await readdir(directory, { withFileTypes: true })) {
+ const file = path.join(directory, entry.name);
+ if (entry.isDirectory()) { await scan(file); continue; }
+ assert.doesNotMatch(entry.name, /auth\.json|config\.local\.json/i);
+ if (/\.(?:json|md|mjs|py|ps1|sh|toml|txt)$/.test(entry.name)) {
+ assert.doesNotMatch(await readFile(file, 'utf8'), /sk-[A-Za-z0-9_-]{12,}|github_pat_|gho_/);
+ }
+ }
+ }
+ await scan(root);
+ console.log(JSON.stringify({ ok: true, version: release.version, asset: fullAsset, claudeCodeVersion: bundle.claudeCodeVersion, codexVersion: bundle.codexVersion, piVersion: bundle.piVersion }));
+} finally {
+ await rm(temporary, { recursive: true, force: true });
+}
diff --git a/apps/cindy-headless/src/benchmark.test.ts b/apps/cindy-headless/src/benchmark.test.ts
new file mode 100644
index 0000000000..87fdfdc9cd
--- /dev/null
+++ b/apps/cindy-headless/src/benchmark.test.ts
@@ -0,0 +1,108 @@
+import { describe, expect, it } from 'vitest';
+import { createEvaluationReport, expandPairedPlan, expandPlan, freezeHard30, schedulePlan, shouldRetry, shouldStop, summarizePairedResults, validateManifest, validateOracleGate, validatePairedManifest } from './benchmark.js';
+
+const manifest = { schemaVersion: 1, board: 'same-model-harness', dataset: { name: 'terminal-bench/terminal-bench-2-1', revision: '6', taskIds: ['e', 'd', 'c', 'b', 'a'] }, modelIds: ['model-1'], repetitions: 2, variants: [{ id: 'raw', supportedModelIds: ['model-1'] }, { id: 'cindy', supportedModelIds: ['model-1'] }], seed: 127 } as const;
+
+describe('benchmark plan', () => {
+ it('expands the full variant x model x task x repetition matrix', () => expect(expandPlan(validateManifest(manifest)).cells).toHaveLength(20));
+ it('rejects unsupported same-model cells', () => expect(() => validateManifest({ ...manifest, variants: [{ id: 'raw', supportedModelIds: [] }] })).toThrow(/unsupported/));
+ it('requires all sorted first-five Oracle rewards to pass', () => {
+ const results = ['a', 'b', 'c', 'd', 'e'].map((taskId) => ({ taskId, reward: 1 }));
+ expect(validateOracleGate([...manifest.dataset.taskIds], results).ok).toBe(true);
+ expect(() => validateOracleGate([...manifest.dataset.taskIds], results.slice(1))).toThrow(/a/);
+ });
+ it('expands paired cells with a stable pair id and two arms', () => {
+ const plan = expandPairedPlan(validatePairedManifest(validateManifest(manifest)));
+ expect(plan.cells).toHaveLength(20);
+ expect(new Set(plan.cells.map((cell) => cell.pairId)).size).toBe(10);
+ expect(plan.cells.filter((cell) => cell.pairId === JSON.stringify(['a', 'model-1', 1]))).toHaveLength(2);
+ expect(plan.cells[0].cellId).toMatch(/^[a-f0-9]{64}$/);
+ expect(plan.cells[0].cellId).toBe(expandPairedPlan(validatePairedManifest(validateManifest(manifest))).cells[0].cellId);
+ });
+ it('summarizes complete, incomplete and asymmetric pairs plus usage', () => {
+ const summary = summarizePairedResults([
+ { variantId: 'raw', armIndex: 0, modelId: 'model-1', taskId: 'a', repetition: 1, reward: 1, costUsd: 0.1, inputTokens: 10, cacheTokens: 2, outputTokens: 5 },
+ { variantId: 'cindy', armIndex: 1, modelId: 'model-1', taskId: 'a', repetition: 1, reward: 1, costUsd: 0.2, inputTokens: 11, cacheTokens: 3, outputTokens: 6 },
+ { variantId: 'raw', armIndex: 0, modelId: 'model-1', taskId: 'b', repetition: 1, reward: 1 },
+ { variantId: 'cindy', armIndex: 1, modelId: 'model-1', taskId: 'b', repetition: 1, reward: 0 },
+ { variantId: 'raw', armIndex: 0, modelId: 'model-1', taskId: 'c', repetition: 1, reward: 0, resultClass: 'FAILED_AGENT', benchmark: 'terminal-bench', durationMs: 12, upstreamProvider: 'anthropic' },
+ ]);
+ expect(summary).toMatchObject({ pairCount: 3, completePairCount: 2, incompletePairCount: 1, bothPass: 1, bothFail: 0, firstArmOnlyPass: 1, secondArmOnlyPass: 0, totalInputTokens: 21, totalCacheTokens: 5, totalOutputTokens: 11 });
+ expect(summary.totalCostUsd).toBeNull();
+ expect(summary.knownCostUsd).toBeCloseTo(0.3);
+ expect(summary.costKnownCount).toBe(2);
+ expect(summary.costMissingCount).toBe(3);
+ expect(summary.byAgent.raw.trials).toBe(3);
+ expect(summary.resultClasses.FAILED_AGENT).toBe(1);
+ expect(summary.upstreamProviders.anthropic).toBe(1);
+ expect(summary.totalDurationMs).toBe(12);
+ expect(summary.usageCompleteness).toEqual({ exact: 0, 'lower-bound': 0, incomplete: 5 });
+ });
+ it('rejects manifests that do not define exactly two paired arms', () => expect(() => validatePairedManifest(validateManifest({ ...manifest, variants: [{ id: 'only', supportedModelIds: ['model-1'] }] }))).toThrow(/exactly two/));
+ it('creates a reproducible interleaved schedule and enforces retry/stop policy', () => {
+ const configured = validateManifest({ ...manifest, retry: { agent: 0, infra: 1 }, budget: { maxCostUsd: 1, stopAfterFailures: 2 } });
+ const cells = expandPlan(configured).cells;
+ expect(schedulePlan(cells, configured).map((cell) => cell.cellId)).toEqual(schedulePlan(cells, configured).map((cell) => cell.cellId));
+ expect(shouldRetry('ERRORED_INFRA', 1, configured).retry).toBe(true);
+ expect(shouldRetry('FAILED_AGENT', 1, configured).retry).toBe(false);
+ expect(shouldStop([{ ...results('a'), resultClass: 'FAILED_AGENT' }, { ...results('b'), resultClass: 'ERRORED_INFRA' }], configured).stop).toBe(true);
+ expect(shouldStop([{ ...results('a') }], configured)).toMatchObject({ stop: true, reason: 'cost-unknown' });
+ expect(shouldStop([{ ...results('a'), costUsd: 1 }], configured)).toMatchObject({ stop: true, reason: 'cost-limit' });
+ });
+ it('creates an auditable report and freezes hard-30 only from independent history', () => {
+ const report = createEvaluationReport(validateManifest(manifest), [{ ...results('a'), reward: 1, resultClass: 'PASSED', benchmark: 'tb' }]);
+ expect(report.trialCount).toBe(1);
+ expect(report.schemaVersion).toBe(2);
+ expect(report.manifestDigest).toMatch(/^[a-f0-9]{64}$/);
+ expect(report.totals).toMatchObject({ costUsd: null, knownCostUsd: 0, costKnownCount: 0, costMissingCount: 1 });
+ expect(() => freezeHard30([{ taskId: 'only', solveRate: 0.1 }])).toThrow(/independent/);
+ const frozen = freezeHard30(Array.from({ length: 30 }, (_, i) => ({ taskId: `task-${i}`, solveRate: i / 30 })));
+ expect(frozen.taskIds).toHaveLength(30);
+ expect(frozen.taskListDigest).toMatch(/^[a-f0-9]{64}$/);
+ });
+});
+
+function results(taskId: string) { return { variantId: 'raw', modelId: 'model-1', taskId, repetition: 1, reward: 0 }; }
+
+
+describe('benchmark report input validation', () => {
+ it.each([
+ { taskId: 'outside' }, { modelId: 'outside' }, { variantId: 'outside' },
+ { repetition: 0 }, { repetition: 3 }, { repetition: 1.5 },
+ { armIndex: 1 }, { armIndex: -1 }, { reward: -0.1 }, { reward: 1.1 },
+ { reward: Number.NaN }, { reward: Number.POSITIVE_INFINITY }, { costUsd: -1 },
+ { inputTokens: Number.NaN }, { durationMs: -1 },
+ ])('rejects a malformed or foreign result cell: %j', (change) => {
+ expect(() => createEvaluationReport(validateManifest(manifest), [{ ...results('a'), ...change }])).toThrow();
+ });
+ it('rejects duplicate trials and conflicting arm ownership before aggregation', () => {
+ expect(() => createEvaluationReport(validateManifest(manifest), [results('a'), results('a')])).toThrow(/duplicate result cell/);
+ expect(() => summarizePairedResults([{ ...results('a'), armIndex: 0 }, { ...results('a'), variantId: 'cindy', armIndex: 0 }])).toThrow(/conflicting result arms/);
+ expect(() => summarizePairedResults([{ ...results('a'), armIndex: 0 }, { ...results('b'), armIndex: 1 }])).toThrow(/conflicting result arms/);
+ });
+ it('assigns omitted arms from manifest order without mutating input', () => {
+ const input = [{ ...results('a'), variantId: 'cindy', reward: 0 }, { ...results('a'), reward: 1 }];
+ const report = createEvaluationReport(validateManifest(manifest), input);
+ expect(report.paired).toMatchObject({ completePairCount: 1, firstArmOnlyPass: 1, secondArmOnlyPass: 0 });
+ expect(input[0]).not.toHaveProperty('armIndex');
+ });
+ it('rejects unsupported product-board cells and does not invent pairs across three variants', () => {
+ const product = validateManifest({ ...manifest, board: 'default-model-product', variants: [{ id: 'raw', supportedModelIds: [] }] });
+ expect(() => createEvaluationReport(product, [results('a')])).toThrow(/supported manifest cell/);
+ const multi = validateManifest({ ...manifest, variants: [...manifest.variants, { id: 'third', supportedModelIds: ['model-1'] }] });
+ const report = createEvaluationReport(multi, multi.variants.map((v) => ({ ...results('a'), variantId: v.id })));
+ expect(report.trialCount).toBe(3);
+ expect(report.paired).toMatchObject({ pairCount: 0, completePairCount: 0 });
+ });
+ it('keeps colon-containing pair keys distinct', () => {
+ const rows = [{ ...results('a:b'), modelId: 'c' }, { ...results('a'), modelId: 'b:c' }];
+ expect(summarizePairedResults(rows).pairCount).toBe(2);
+ });
+ it('supports reserved property names without corrupting counters', () => {
+ const m = validateManifest({ ...manifest, variants: [{ id: '__proto__', supportedModelIds: ['model-1'] }] });
+ const report = createEvaluationReport(m, [{ ...results('a'), variantId: '__proto__', benchmark: '__proto__' }]);
+ expect(report.byAgent['__proto__'].trials).toBe(1);
+ expect(report.byBenchmark['__proto__'].trials).toBe(1);
+ expect(Object.prototype).not.toHaveProperty('trials');
+ });
+});
diff --git a/apps/cindy-headless/src/benchmark.ts b/apps/cindy-headless/src/benchmark.ts
new file mode 100644
index 0000000000..bab96198a7
--- /dev/null
+++ b/apps/cindy-headless/src/benchmark.ts
@@ -0,0 +1,357 @@
+import { readFile, writeFile } from 'node:fs/promises';
+import { sha256 } from './profile.js';
+
+export interface BenchmarkManifest {
+ schemaVersion: 1;
+ board: 'same-model-harness' | 'default-model-product';
+ dataset: { name: string; revision: string; taskIds: string[] };
+ modelIds: string[];
+ repetitions: number;
+ variants: Array<{ id: string; supportedModelIds: string[] }>;
+ seed: number;
+ concurrency?: number;
+ agentOrder?: string[];
+ runtime?: { timeoutMs?: number; cpu?: number; memoryMb?: number; network?: string; permissions?: string };
+ retry?: { agent: 0; infra: 0 | 1 };
+ budget?: { maxCostUsd?: number; stopAfterFailures?: number };
+ throughputCap?: { outputTokensPerSecond: number; enabled: boolean };
+}
+
+export interface BenchmarkCell {
+ cellId: string;
+ variantId: string;
+ modelId: string;
+ taskId: string;
+ repetition: number;
+}
+
+export interface PairedBenchmarkCell extends BenchmarkCell {
+ pairId: string;
+ armIndex: number;
+}
+
+export interface PairedRunResult {
+ variantId: string;
+ armIndex?: number;
+ modelId: string;
+ taskId: string;
+ repetition: number;
+ reward: number;
+ status?: string;
+ costUsd?: number;
+ inputTokens?: number;
+ cacheTokens?: number;
+ outputTokens?: number;
+ benchmark?: string;
+ resultClass?: 'PASSED' | 'FAILED_AGENT' | 'ERRORED_INFRA' | 'INVALID_TASK';
+ durationMs?: number;
+ upstreamProvider?: string;
+ usageStatus?: 'COMPLETE' | 'PARTIAL' | 'MISSING';
+ usageCompleteness?: 'exact' | 'lower-bound' | 'incomplete';
+}
+
+export interface EvaluationReport {
+ schemaVersion: 2;
+ manifestDigest: string;
+ trialCount: number;
+ byBenchmark: PairedSummary['byBenchmark'];
+ byAgent: PairedSummary['byAgent'];
+ resultClasses: PairedSummary['resultClasses'];
+ confidenceIntervals: PairedSummary['confidenceIntervals'];
+ paired: Pick<PairedSummary, 'pairCount' | 'completePairCount' | 'incompletePairCount' | 'bothPass' | 'bothFail' | 'firstArmOnlyPass' | 'secondArmOnlyPass'>;
+ unsupported: Array<{ variantId: string; modelId: string; reason: string }>;
+ totals: { costUsd: number | null; knownCostUsd: number; costKnownCount: number; costMissingCount: number; inputTokens: number; cacheTokens: number; outputTokens: number; durationMs: number };
+ upstreamProviders: Record<string, number>;
+ usageCompleteness: Record<'exact' | 'lower-bound' | 'incomplete', number>;
+}
+
+export interface PairedSummary {
+ pairCount: number;
+ completePairCount: number;
+ incompletePairCount: number;
+ bothPass: number;
+ bothFail: number;
+ firstArmOnlyPass: number;
+ secondArmOnlyPass: number;
+ totalCostUsd: number | null;
+ knownCostUsd: number;
+ costKnownCount: number;
+ costMissingCount: number;
+ totalInputTokens: number;
+ totalCacheTokens: number;
+ totalOutputTokens: number;
+ byBenchmark: Record<string, { trials: number; passed: number; passRate: number }>;
+ byAgent: Record<string, { trials: number; passed: number; passRate: number }>;
+ resultClasses: Record<'PASSED' | 'FAILED_AGENT' | 'ERRORED_INFRA' | 'INVALID_TASK', number>;
+ totalDurationMs: number;
+ upstreamProviders: Record<string, number>;
+ usageCompleteness: Record<'exact' | 'lower-bound' | 'incomplete', number>;
+ confidenceIntervals: Record<string, { successes: number; trials: number; lower95: number; upper95: number }>;
+}
+
+export interface RetryDecision { retry: boolean; reason: 'agent-failure' | 'infra-error' | 'invalid-task' | 'passed' | 'retry-exhausted'; nextAttempt: number; }
+
+export function shouldRetry(resultClass: PairedRunResult['resultClass'], attemptNumber: number, manifest: BenchmarkManifest): RetryDecision {
+ if (resultClass === 'ERRORED_INFRA' && attemptNumber <= (manifest.retry?.infra ?? 1)) return { retry: true, reason: 'infra-error', nextAttempt: attemptNumber + 1 };
+ if (resultClass === 'ERRORED_INFRA') return { retry: false, reason: 'retry-exhausted', nextAttempt: attemptNumber };
+ if (resultClass === 'FAILED_AGENT') return { retry: false, reason: 'agent-failure', nextAttempt: attemptNumber };
+ if (resultClass === 'INVALID_TASK') return { retry: false, reason: 'invalid-task', nextAttempt: attemptNumber };
+ return { retry: false, reason: 'passed', nextAttempt: attemptNumber };
+}
+
+export function shouldStop(results: PairedRunResult[], manifest: BenchmarkManifest): { stop: boolean; reason: 'cost-limit' | 'cost-unknown' | 'failure-limit' | null } {
+ const knownCosts = results.filter((result): result is PairedRunResult & { costUsd: number } => Number.isFinite(result.costUsd));
+ const cost = knownCosts.reduce((sum, result) => sum + result.costUsd, 0);
+ if (manifest.budget?.maxCostUsd !== undefined && cost >= manifest.budget.maxCostUsd) return { stop: true, reason: 'cost-limit' };
+ if (manifest.budget?.maxCostUsd !== undefined && knownCosts.length !== results.length) return { stop: true, reason: 'cost-unknown' };
+ const failures = results.filter((result) => result.resultClass === 'FAILED_AGENT' || result.resultClass === 'ERRORED_INFRA').length;
+ if (manifest.budget?.stopAfterFailures !== undefined && failures >= manifest.budget.stopAfterFailures) return { stop: true, reason: 'failure-limit' };
+ return { stop: false, reason: null };
+}
+
+function seededShuffle<T>(items: T[], seed: number): T[] {
+ const output = [...items]; let state = seed >>> 0;
+ for (let i = output.length - 1; i > 0; i -= 1) { state = (1664525 * state + 1013904223) >>> 0; const j = state % (i + 1); [output[i], output[j]] = [output[j], output[i]]; }
+ return output;
+}
+
+export function schedulePlan(cells: BenchmarkCell[], manifest: BenchmarkManifest): BenchmarkCell[] {
+ const ordered = manifest.agentOrder?.length ? [...manifest.agentOrder, ...manifest.variants.map((v) => v.id).filter((id) => !manifest.agentOrder?.includes(id))] : manifest.variants.map((v) => v.id);
+ const rank = new Map(ordered.map((id, index) => [id, index]));
+ const grouped = new Map<string, BenchmarkCell[]>();
+ for (const cell of cells) { const key = pairKey(cell); grouped.set(key, [...(grouped.get(key) ?? []), cell]); }
+ const pairs = seededShuffle([...grouped.values()], manifest.seed);
+ return pairs.flatMap((pair) => [...pair].sort((a, b) => (rank.get(a.variantId) ?? 999) - (rank.get(b.variantId) ?? 999)));
+}
+
+function wilson(successes: number, trials: number): { lower95: number; upper95: number } {
+ if (!trials) return { lower95: 0, upper95: 0 };
+ const p = successes / trials; const z = 1.96; const denominator = 1 + z * z / trials;
+ const centre = p + z * z / (2 * trials); const spread = z * Math.sqrt((p * (1 - p) + z * z / (4 * trials)) / trials);
+ return { lower95: Math.max(0, (centre - spread) / denominator), upper95: Math.min(1, (centre + spread) / denominator) };
+}
+
+export function validateManifest(value: unknown): BenchmarkManifest {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('manifest must be an object');
+ const manifest = value as Partial<BenchmarkManifest>;
+ if (manifest.schemaVersion !== 1) throw new Error('manifest.schemaVersion must be 1');
+ if (!['same-model-harness', 'default-model-product'].includes(manifest.board ?? '')) throw new Error('manifest.board is invalid');
+ if (!manifest.dataset?.name || !manifest.dataset.revision || !Array.isArray(manifest.dataset.taskIds) || manifest.dataset.taskIds.length === 0) throw new Error('dataset name, revision and taskIds are required');
+ if (new Set(manifest.dataset.taskIds).size !== manifest.dataset.taskIds.length) throw new Error('dataset.taskIds contains duplicates');
+ if (!Number.isInteger(manifest.repetitions) || (manifest.repetitions ?? 0) < 1) throw new Error('repetitions must be a positive integer');
+ if (manifest.concurrency !== undefined && (!Number.isInteger(manifest.concurrency) || manifest.concurrency < 1)) throw new Error('concurrency must be a positive integer');
+ if (manifest.agentOrder !== undefined && (!Array.isArray(manifest.agentOrder) || new Set(manifest.agentOrder).size !== manifest.agentOrder.length)) throw new Error('agentOrder must be a duplicate-free array');
+ if (manifest.retry && (manifest.retry.agent !== 0 || ![0, 1].includes(manifest.retry.infra))) throw new Error('retry must be agent=0 and infra=0|1');
+ if (manifest.budget?.maxCostUsd !== undefined && (!Number.isFinite(manifest.budget.maxCostUsd) || manifest.budget.maxCostUsd <= 0)) throw new Error('budget.maxCostUsd must be positive');
+ if (manifest.budget?.stopAfterFailures !== undefined && (!Number.isInteger(manifest.budget.stopAfterFailures) || manifest.budget.stopAfterFailures < 1)) throw new Error('budget.stopAfterFailures must be positive');
+ if (manifest.throughputCap && (!Number.isFinite(manifest.throughputCap.outputTokensPerSecond) || manifest.throughputCap.outputTokensPerSecond <= 0)) throw new Error('throughputCap rate must be positive');
+ if (!Array.isArray(manifest.modelIds) || manifest.modelIds.length === 0 || !Array.isArray(manifest.variants) || manifest.variants.length < 1) throw new Error('modelIds and variants must be non-empty');
+ if (manifest.modelIds.some((id) => typeof id !== 'string' || !id.trim()) || new Set(manifest.modelIds).size !== manifest.modelIds.length) throw new Error('modelIds must contain unique non-empty strings');
+ if (manifest.dataset.taskIds.some((id) => typeof id !== 'string' || !id.trim())) throw new Error('taskIds must contain non-empty strings');
+ if (manifest.variants.some((variant) => !variant || !Array.isArray(variant.supportedModelIds))) throw new Error('variant supportedModelIds must be an array');
+ const variantIds = manifest.variants.map((variant) => variant.id);
+ if (variantIds.some((id) => typeof id !== 'string' || id.trim() === '')) throw new Error('variant IDs must be non-empty');
+ if (new Set(variantIds).size !== variantIds.length) throw new Error('variants contains duplicate IDs');
+ if (manifest.board === 'same-model-harness') {
+ for (const modelId of manifest.modelIds) {
+ const unsupported = manifest.variants.filter((variant) => !variant.supportedModelIds.includes(modelId)).map((variant) => variant.id);
+ if (unsupported.length) throw new Error(`same-model cell unsupported for ${modelId}: ${unsupported.join(', ')}`);
+ }
+ }
+ return manifest as BenchmarkManifest;
+}
+
+export function validatePairedManifest(manifest: BenchmarkManifest): BenchmarkManifest {
+ if (manifest.variants.length !== 2) throw new Error('paired runs require exactly two variants');
+ if (manifest.board !== 'same-model-harness') throw new Error('paired runs require the same-model-harness board');
+ return manifest;
+}
+
+export function expandPairedPlan(manifest: BenchmarkManifest): { schemaVersion: 1; manifestDigest: string; cells: PairedBenchmarkCell[] } {
+ validatePairedManifest(manifest);
+ const cells: PairedBenchmarkCell[] = [];
+ for (const taskId of manifest.dataset.taskIds) for (const modelId of manifest.modelIds) for (let repetition = 1; repetition <= manifest.repetitions; repetition += 1) {
+ manifest.variants.forEach((variant, armIndex) => {
+ if (variant.supportedModelIds.includes(modelId)) {
+ const cellId = sha256(JSON.stringify({ dataset: manifest.dataset, taskId, variant: variant.id, modelId, repetition }));
+ cells.push({ cellId, pairId: pairKey({ taskId, modelId, repetition }), armIndex, variantId: variant.id, modelId, taskId, repetition });
+ }
+ });
+ }
+ return { schemaVersion: 1, manifestDigest: sha256(JSON.stringify(manifest)), cells };
+}
+
+function passed(result: PairedRunResult | undefined): boolean {
+ return result?.reward === 1;
+}
+
+function pairKey(result: Pick<PairedRunResult, 'taskId' | 'modelId' | 'repetition'>): string {
+ return JSON.stringify([result.taskId, result.modelId, result.repetition]);
+}
+
+function validateResultRows(results: PairedRunResult[]): void {
+ if (!Array.isArray(results)) throw new Error('results must be an array');
+ const seen = new Set<string>();
+ const variantArms = new Map<string, number>();
+ const armVariants = new Map<number, string>();
+ for (const result of results) {
+ if (!result || typeof result !== 'object' || Array.isArray(result)) throw new Error('result must be an object');
+ if ([result.variantId, result.modelId, result.taskId].some((id) => typeof id !== 'string' || !id.trim())) throw new Error('result IDs must be non-empty strings');
+ if (!Number.isSafeInteger(result.repetition) || result.repetition < 1) throw new Error('invalid result repetition');
+ if (!Number.isFinite(result.reward) || result.reward < 0 || result.reward > 1) throw new Error(`invalid reward for ${result.taskId}`);
+ for (const field of ['costUsd', 'durationMs', 'inputTokens', 'cacheTokens', 'outputTokens'] as const) {
+ const value = result[field];
+ if (value != null && (!Number.isFinite(value) || value < 0)) throw new Error(`invalid result ${field}`);
+ }
+ for (const field of ['benchmark', 'upstreamProvider'] as const) {
+ if (result[field] != null && typeof result[field] !== 'string') throw new Error(`invalid result ${field}`);
+ }
+ if (result.resultClass !== undefined && !['PASSED', 'FAILED_AGENT', 'ERRORED_INFRA', 'INVALID_TASK'].includes(result.resultClass)) throw new Error('invalid result class');
+ if (result.usageStatus !== undefined && !['COMPLETE', 'PARTIAL', 'MISSING'].includes(result.usageStatus)) throw new Error('invalid usage status');
+ if (result.usageCompleteness !== undefined && !['exact', 'lower-bound', 'incomplete'].includes(result.usageCompleteness)) throw new Error('invalid usage completeness');
+ const key = JSON.stringify([result.variantId, result.taskId, result.modelId, result.repetition]);
+ if (seen.has(key)) throw new Error('duplicate result cell');
+ seen.add(key);
+ if (result.armIndex !== undefined) {
+ if (!Number.isSafeInteger(result.armIndex) || result.armIndex < 0) throw new Error('invalid arm index');
+ if ((variantArms.has(result.variantId) && variantArms.get(result.variantId) !== result.armIndex)
+ || (armVariants.has(result.armIndex) && armVariants.get(result.armIndex) !== result.variantId)) throw new Error('conflicting result arms');
+ variantArms.set(result.variantId, result.armIndex);
+ armVariants.set(result.armIndex, result.variantId);
+ }
+ }
+}
+
+function validateReportResults(manifest: BenchmarkManifest, results: PairedRunResult[]): PairedRunResult[] {
+ validateResultRows(results);
+ const tasks = new Set(manifest.dataset.taskIds);
+ const models = new Set(manifest.modelIds);
+ return results.map((result) => {
+ const armIndex = manifest.variants.findIndex((variant) => variant.id === result.variantId);
+ if (!tasks.has(result.taskId) || !models.has(result.modelId) || result.repetition > manifest.repetitions || armIndex < 0
+ || !manifest.variants[armIndex].supportedModelIds.includes(result.modelId)) throw new Error('result does not belong to a supported manifest cell');
+ if (result.armIndex !== undefined && result.armIndex !== armIndex) throw new Error('result arm does not match manifest variant');
+ return { ...result, armIndex };
+ });
+}
+
+export function summarizePairedResults(results: PairedRunResult[], paired = true): PairedSummary {
+ validateResultRows(results);
+ if (paired && (new Set(results.map((result) => result.variantId)).size > 2 || results.some((result) => (result.armIndex ?? 0) > 1))) throw new Error('paired results require at most two distinct arms');
+ const pairs = new Map<string, PairedRunResult[]>();
+ let knownCostUsd = 0;
+ let costKnownCount = 0;
+ let costMissingCount = 0;
+ let totalInputTokens = 0;
+ let totalCacheTokens = 0;
+ let totalOutputTokens = 0;
+ let totalDurationMs = 0;
+ const byBenchmark: PairedSummary['byBenchmark'] = Object.create(null);
+ const byAgent: PairedSummary['byAgent'] = Object.create(null);
+ const resultClasses: PairedSummary['resultClasses'] = { PASSED: 0, FAILED_AGENT: 0, ERRORED_INFRA: 0, INVALID_TASK: 0 };
+ const upstreamProviders: Record<string, number> = Object.create(null);
+ const confidenceIntervals: PairedSummary['confidenceIntervals'] = Object.create(null);
+ const usageCompleteness: PairedSummary['usageCompleteness'] = { exact: 0, 'lower-bound': 0, incomplete: 0 };
+ for (const result of results) {
+ if (!Number.isFinite(result.reward)) throw new Error(`invalid reward for ${result.taskId}`);
+ const key = pairKey(result);
+ const pair = pairs.get(key) ?? [];
+ pair.push(result);
+ pairs.set(key, pair);
+ if (Number.isFinite(result.costUsd)) {
+ knownCostUsd += result.costUsd as number;
+ costKnownCount += 1;
+ } else {
+ costMissingCount += 1;
+ }
+ totalInputTokens += result.inputTokens ?? 0;
+ totalCacheTokens += result.cacheTokens ?? 0;
+ totalOutputTokens += result.outputTokens ?? 0;
+ totalDurationMs += result.durationMs ?? 0;
+ const benchmark = result.benchmark ?? 'unknown';
+ const agent = result.variantId;
+ const b = byBenchmark[benchmark] ?? { trials: 0, passed: 0, passRate: 0 };
+ b.trials += 1; b.passed += passed(result) ? 1 : 0; b.passRate = b.passed / b.trials; byBenchmark[benchmark] = b;
+ const a = byAgent[agent] ?? { trials: 0, passed: 0, passRate: 0 };
+ a.trials += 1; a.passed += passed(result) ? 1 : 0; a.passRate = a.passed / a.trials; byAgent[agent] = a;
+ if (result.resultClass) resultClasses[result.resultClass] += 1;
+ if (result.upstreamProvider) upstreamProviders[result.upstreamProvider] = (upstreamProviders[result.upstreamProvider] ?? 0) + 1;
+ const completeness = result.usageCompleteness ?? (result.usageStatus === 'COMPLETE' ? 'exact' : result.usageStatus === 'PARTIAL' ? 'lower-bound' : 'incomplete');
+ usageCompleteness[completeness] += 1;
+ }
+ let completePairCount = 0;
+ let bothPass = 0;
+ let bothFail = 0;
+ let firstArmOnlyPass = 0;
+ let secondArmOnlyPass = 0;
+ for (const pair of paired ? pairs.values() : []) {
+ const ordered = [...pair].sort((a, b) => (a.armIndex ?? Number.MAX_SAFE_INTEGER) - (b.armIndex ?? Number.MAX_SAFE_INTEGER) || a.variantId.localeCompare(b.variantId));
+ if (ordered.length !== 2) continue;
+ completePairCount += 1;
+ const first = passed(ordered[0]);
+ const second = passed(ordered[1]);
+ if (first && second) bothPass += 1;
+ else if (!first && !second) bothFail += 1;
+ else if (first) firstArmOnlyPass += 1;
+ else secondArmOnlyPass += 1;
+ }
+ for (const [agent, stats] of Object.entries(byAgent)) confidenceIntervals[agent] = { successes: stats.passed, trials: stats.trials, ...wilson(stats.passed, stats.trials) };
+ const totalCostUsd = costMissingCount === 0 ? knownCostUsd : null;
+ return { pairCount: paired ? pairs.size : 0, completePairCount, incompletePairCount: paired ? pairs.size - completePairCount : 0, bothPass, bothFail, firstArmOnlyPass, secondArmOnlyPass, totalCostUsd, knownCostUsd, costKnownCount, costMissingCount, totalInputTokens, totalCacheTokens, totalOutputTokens, byBenchmark, byAgent, resultClasses, totalDurationMs, upstreamProviders, usageCompleteness, confidenceIntervals };
+}
+
+export function expandPlan(manifest: BenchmarkManifest): { schemaVersion: 1; manifestDigest: string; cells: BenchmarkCell[] } {
+ const cells: BenchmarkCell[] = [];
+ for (const taskId of manifest.dataset.taskIds) for (const modelId of manifest.modelIds) for (let repetition = 1; repetition <= manifest.repetitions; repetition += 1) for (const variant of manifest.variants) {
+ if (variant.supportedModelIds.includes(modelId)) cells.push({ cellId: sha256(JSON.stringify({ dataset: manifest.dataset, taskId, variant: variant.id, modelId, repetition })), variantId: variant.id, modelId, taskId, repetition });
+ }
+ return { schemaVersion: 1, manifestDigest: sha256(JSON.stringify(manifest)), cells };
+}
+
+export function expandScheduledPlan(manifest: BenchmarkManifest): { schemaVersion: 1; manifestDigest: string; cells: BenchmarkCell[] } {
+ const plan = expandPlan(manifest);
+ return { ...plan, cells: schedulePlan(plan.cells, manifest) };
+}
+
+export function createEvaluationReport(manifest: BenchmarkManifest, results: PairedRunResult[]): EvaluationReport {
+ validateManifest(manifest);
+ const validatedResults = validateReportResults(manifest, results);
+ const summary = summarizePairedResults(validatedResults, manifest.variants.length === 2);
+ const supported = new Set(manifest.variants.flatMap((variant) => manifest.modelIds.filter((model) => variant.supportedModelIds.includes(model)).map((model) => `${variant.id}:${model}`)));
+ const unsupported = manifest.variants.flatMap((variant) => manifest.modelIds.filter((model) => !supported.has(`${variant.id}:${model}`)).map((model) => ({ variantId: variant.id, modelId: model, reason: 'variant does not declare support for exact model' })));
+ return {
+ schemaVersion: 2,
+ manifestDigest: sha256(JSON.stringify(manifest)),
+ trialCount: results.length,
+ byBenchmark: summary.byBenchmark,
+ byAgent: summary.byAgent,
+ resultClasses: summary.resultClasses,
+ confidenceIntervals: summary.confidenceIntervals,
+ paired: { pairCount: summary.pairCount, completePairCount: summary.completePairCount, incompletePairCount: summary.incompletePairCount, bothPass: summary.bothPass, bothFail: summary.bothFail, firstArmOnlyPass: summary.firstArmOnlyPass, secondArmOnlyPass: summary.secondArmOnlyPass },
+ unsupported,
+ totals: { costUsd: summary.totalCostUsd, knownCostUsd: summary.knownCostUsd, costKnownCount: summary.costKnownCount, costMissingCount: summary.costMissingCount, inputTokens: summary.totalInputTokens, cacheTokens: summary.totalCacheTokens, outputTokens: summary.totalOutputTokens, durationMs: summary.totalDurationMs },
+ upstreamProviders: summary.upstreamProviders,
+ usageCompleteness: summary.usageCompleteness,
+ };
+}
+
+export function freezeHard30(historical: Array<{ taskId: string; solveRate: number }>, taskCount = 30): { schemaVersion: 1; source: 'independent-historical-data'; taskIds: string[]; taskListDigest: string } {
+ if (historical.length < taskCount) throw new Error(`hard-30 requires at least ${taskCount} independent historical tasks`);
+ const sorted = [...historical].sort((a, b) => a.solveRate - b.solveRate || a.taskId.localeCompare(b.taskId));
+ const taskIds = sorted.slice(0, taskCount).map((item) => item.taskId);
+ return { schemaVersion: 1, source: 'independent-historical-data', taskIds, taskListDigest: sha256(JSON.stringify(taskIds)) };
+}
+
+export async function writePlan(manifestPath: string, outputPath: string): Promise<void> {
+ const manifest = validateManifest(JSON.parse(await readFile(manifestPath, 'utf8')));
+ await writeFile(outputPath, JSON.stringify(expandPlan(manifest), null, 2) + '\n', 'utf8');
+}
+
+export function validateOracleGate(taskIds: string[], results: Array<{ taskId: string; reward: number }>): { ok: true; taskIds: string[] } {
+ const expected = [...taskIds].sort().slice(0, 5);
+ if (expected.length !== 5) throw new Error('Oracle gate requires at least five frozen task IDs');
+ const resultMap = new Map(results.map((result) => [result.taskId, result.reward]));
+ const failed = expected.filter((taskId) => resultMap.get(taskId) !== 1);
+ if (failed.length) throw new Error(`Oracle gate failed or missing: ${failed.join(', ')}`);
+ return { ok: true, taskIds: expected };
+}
diff --git a/apps/cindy-headless/src/built-cli.test.mjs b/apps/cindy-headless/src/built-cli.test.mjs
new file mode 100644
index 0000000000..1b8942afe9
--- /dev/null
+++ b/apps/cindy-headless/src/built-cli.test.mjs
@@ -0,0 +1,50 @@
+import { execFile } from 'node:child_process';
+import { mkdtemp, rm, writeFile } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import { promisify } from 'node:util';
+import { fileURLToPath } from 'node:url';
+import { build } from 'esbuild';
+import { afterAll, beforeAll, describe, expect, it } from 'vitest';
+import { headlessBuildOptions } from '../scripts/build-options.mjs';
+
+const execFileAsync = promisify(execFile);
+const appDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+let output;
+
+beforeAll(async () => {
+ output = await mkdtemp(path.join(os.tmpdir(), 'cindy-headless-cli-'));
+ await build({
+ ...headlessBuildOptions,
+ entryPoints: {
+ cli: path.join(appDir, 'src/cli.ts'),
+ 'eval-cli': path.join(appDir, 'src/eval-cli.ts'),
+ },
+ outdir: output,
+ });
+}, 30_000);
+
+afterAll(async () => {
+ if (output) await rm(output, { recursive: true, force: true });
+});
+
+describe('standalone CommonJS CLI artifacts', () => {
+ it('starts the bundled runtime outside the checkout without gateway configuration', async () => {
+ const { stdout } = await execFileAsync(process.execPath, [path.join(output, 'cli.cjs'), 'version'], {
+ cwd: output,
+ timeout: 15_000,
+ env: { ...process.env, CINDY_HEADLESS_CONFIG_FILE: path.join(output, 'missing-config.json') },
+ });
+ expect(JSON.parse(stdout)).toMatchObject({ name: 'cindy-headless', backends: ['claude-code', 'codex', 'pi'] });
+ }, 20_000);
+
+ it('runs the bundled evaluation CLI on local results', async () => {
+ const results = path.join(output, 'results.json');
+ await writeFile(results, '[]');
+ const { stdout } = await execFileAsync(process.execPath, [path.join(output, 'eval-cli.cjs'), 'paired-summary', '--results', results], {
+ cwd: output,
+ timeout: 15_000,
+ });
+ expect(JSON.parse(stdout)).toMatchObject({ pairCount: 0, completePairCount: 0 });
+ }, 20_000);
+});
diff --git a/apps/cindy-headless/src/bundle-dist.test.mjs b/apps/cindy-headless/src/bundle-dist.test.mjs
new file mode 100644
index 0000000000..d9ef4fced8
--- /dev/null
+++ b/apps/cindy-headless/src/bundle-dist.test.mjs
@@ -0,0 +1,45 @@
+import { createHash } from 'node:crypto';
+import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import { afterEach, describe, expect, it } from 'vitest';
+import { requireBundleDist } from '../scripts/bundle-dist.mjs';
+
+const roots = [];
+afterEach(async () => { await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))); });
+async function fixture() {
+ const root = await mkdtemp(path.join(os.tmpdir(), 'headless-bundle-dist-'));
+ roots.push(root);
+ const bundle = path.join(root, 'bundle');
+ const dist = path.join(bundle, 'dist');
+ await mkdir(dist, { recursive: true });
+ await writeFile(path.join(dist, 'cli.cjs'), 'frozen-cli');
+ await writeFile(path.join(dist, 'eval-cli.cjs'), 'frozen-eval');
+ const digest = (text) => createHash('sha256').update(text).digest('hex');
+ return { root, bundle, dist, manifest: { cliDigest: digest('frozen-cli'), evalCliDigest: digest('frozen-eval') } };
+}
+
+describe('release bundle dist binding', () => {
+ it('accepts only the CLI files matching the frozen manifest', async () => {
+ const f = await fixture();
+ await expect(requireBundleDist(f.bundle, f.manifest)).resolves.toBe(f.dist);
+ });
+ it('rejects a missing bundle dist even when a development dist exists', async () => {
+ const f = await fixture();
+ await mkdir(path.join(f.root, 'dist'));
+ await writeFile(path.join(f.root, 'dist', 'cli.cjs'), 'unbound-development-cli');
+ await rm(f.dist, { recursive: true });
+ await expect(requireBundleDist(f.bundle, f.manifest)).rejects.toThrow();
+ });
+ it.each(['cli.cjs', 'eval-cli.cjs'])('rejects changed %s bytes', async (name) => {
+ const f = await fixture();
+ await writeFile(path.join(f.dist, name), 'tampered');
+ await expect(requireBundleDist(f.bundle, f.manifest)).rejects.toThrow(/digest mismatch/);
+ });
+ it('rejects a partial bundle and a missing manifest digest', async () => {
+ const f = await fixture();
+ await expect(requireBundleDist(f.bundle, {})).rejects.toThrow(/digest mismatch/);
+ await rm(path.join(f.dist, 'eval-cli.cjs'));
+ await expect(requireBundleDist(f.bundle, f.manifest)).rejects.toThrow();
+ });
+});
diff --git a/apps/cindy-headless/src/cli.test.ts b/apps/cindy-headless/src/cli.test.ts
new file mode 100644
index 0000000000..7de4601421
--- /dev/null
+++ b/apps/cindy-headless/src/cli.test.ts
@@ -0,0 +1,35 @@
+import { describe, expect, it } from 'vitest';
+import { DEFAULT_HEADLESS_TIMEOUT_MS, resolveHeadlessTimeout } from './defaults.js';
+
+describe('Headless CLI defaults', () => {
+ it('uses an 1800-second standalone deadline', () => {
+ expect(DEFAULT_HEADLESS_TIMEOUT_MS).toBe(1_800_000);
+ expect(resolveHeadlessTimeout(undefined, undefined)).toEqual({
+ owner: 'headless',
+ timeoutMs: 1_800_000,
+ });
+ });
+
+ it('allows an external owner to disable Headless timing explicitly', () => {
+ expect(resolveHeadlessTimeout('external', undefined)).toEqual({
+ owner: 'external',
+ timeoutMs: null,
+ });
+ expect(() => resolveHeadlessTimeout('external', '1000')).toThrow(
+ '--timeout-ms cannot be used with --timeout-owner external',
+ );
+ });
+
+ it('validates owner and explicit Headless deadlines', () => {
+ expect(resolveHeadlessTimeout('headless', '2500')).toEqual({
+ owner: 'headless',
+ timeoutMs: 2500,
+ });
+ expect(() => resolveHeadlessTimeout('invalid', undefined)).toThrow(
+ '--timeout-owner must be headless or external',
+ );
+ expect(() => resolveHeadlessTimeout('headless', '0')).toThrow(
+ '--timeout-ms must be a positive number',
+ );
+ });
+});
diff --git a/apps/cindy-headless/src/cli.ts b/apps/cindy-headless/src/cli.ts
new file mode 100644
index 0000000000..cae28f7d14
--- /dev/null
+++ b/apps/cindy-headless/src/cli.ts
@@ -0,0 +1,138 @@
+#!/usr/bin/env node
+import { capabilities, doctor, readProfile, type HeadlessProfile } from './profile.js';
+import { runTask } from './host.js';
+import { validateTurnInput } from './headless-integrations.js';
+import { mkdir, readFile, writeFile } from 'node:fs/promises';
+import path from 'node:path';
+import { createEvaluationReport, expandPairedPlan, expandPlan, expandScheduledPlan, freezeHard30, summarizePairedResults, validateManifest, validateOracleGate, validatePairedManifest, writePlan } from './benchmark.js';
+import { capabilityCatalog, compatibilityReport, CINDY_HEADLESS_VERSION, CINDY_UPSTREAM_COMMIT, discoverCapabilityCatalog } from './compatibility.js';
+import { generateProfileFromManifest } from './profile-generation.js';
+import { applyGatewayConfig, loadGatewayConfig } from './gateway-config.js';
+import { resolveHeadlessTimeout } from './defaults.js';
+
+const args = process.argv.slice(2);
+const command = args[0] ?? 'help';
+function flag(name: string): string | undefined { const index = args.indexOf(name); return index >= 0 ? args[index + 1] : undefined; }
+function requireFlag(name: string): string { const value = flag(name); if (!value) throw new Error(`${name} is required`); return value; }
+function positiveNumberFlag(name: string): number | undefined {
+ const raw = flag(name);
+ if (raw === undefined) return undefined;
+ const value = Number(raw);
+ if (!Number.isFinite(value) || value <= 0) throw new Error(`${name} must be a positive number`);
+ return value;
+}
+function providerApiFlag(): 'anthropic-messages' | 'openai-responses' | 'openai-completions' | 'google-generative-ai' | undefined {
+ const value = flag('--api');
+ if (value === undefined) return undefined;
+ if (!['anthropic-messages', 'openai-responses', 'openai-completions', 'google-generative-ai'].includes(value)) throw new Error('--api is not supported');
+ return value as 'anthropic-messages' | 'openai-responses' | 'openai-completions' | 'google-generative-ai';
+}
+function effortFlag(): HeadlessProfile['model']['effort'] | undefined {
+ const value = flag('--effort');
+ if (value === undefined) return undefined;
+ if (!['minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra'].includes(value)) throw new Error('--effort is not supported');
+ return value as HeadlessProfile['model']['effort'];
+}
+
+async function main(): Promise<void> {
+ if (command === 'doctor' || command === 'verify-agent' || command === 'run') {
+ applyGatewayConfig(await loadGatewayConfig());
+ }
+ if (command === 'version') { console.log(JSON.stringify({ name: 'cindy-headless', version: CINDY_HEADLESS_VERSION, cindyUpstreamCommit: CINDY_UPSTREAM_COMMIT, phase: 5, backends: ['claude-code', 'codex', 'pi'] })); return; }
+ if (command === 'capabilities' && flag('--manifest')) {
+ const manifest = JSON.parse(await readFile(requireFlag('--manifest'), 'utf8')) as Record<string, unknown>;
+ console.log(JSON.stringify(discoverCapabilityCatalog(manifest.capabilityCatalog), null, 2));
+ return;
+ }
+ if (command === 'profile' && args[1] === 'generate') {
+ const manifestPath = requireFlag('--manifest');
+ const manifest = JSON.parse(await readFile(manifestPath, 'utf8')) as Record<string, unknown>;
+ const output = requireFlag('--output');
+ const mcpConfigPath = flag('--mcp-config');
+ const mcpServers = mcpConfigPath
+ ? JSON.parse(await readFile(mcpConfigPath, 'utf8')) as HeadlessProfile['mcpServers']
+ : undefined;
+ if (mcpConfigPath && !Array.isArray(mcpServers)) throw new Error('--mcp-config must contain a JSON array');
+ const profile = generateProfileFromManifest(manifest, {
+ manifestPath,
+ outputPath: output,
+ harness: requireFlag('--harness'),
+ features: (flag('--features') ?? '').split(',').map((item) => item.trim()).filter(Boolean),
+ modelId: flag('--model'), providerId: flag('--provider'), providerName: flag('--provider-name'),
+ providerBaseUrl: flag('--base-url'), providerApi: providerApiFlag(),
+ apiKeyEnvVar: flag('--api-key-env-var'), contextLimit: positiveNumberFlag('--context-limit'),
+ maxOutputTokens: positiveNumberFlag('--max-output-tokens'),
+ mcpServers,
+ effort: effortFlag(),
+ gatewayModel: args.includes('--gateway-model'),
+ exactFeatures: args.includes('--exact-features'),
+ });
+ await mkdir(path.dirname(path.resolve(output)), { recursive: true });
+ await writeFile(output, JSON.stringify(profile, null, 2) + '\n', 'utf8');
+ console.log(JSON.stringify({ ok: true, profile, output }, null, 2));
+ return;
+ }
+ if (command === 'doctor' || command === 'verify-agent' || command === 'compatibility-report' || command === 'capabilities' || command === 'profile') {
+ if (command === 'profile' && args[1] !== 'validate') throw new Error('usage: profile validate --profile <file> or profile generate --manifest <file> --harness <name> --output <file>');
+ const resolved = await readProfile(requireFlag('--profile'), flag('--bundle-dir'));
+ if (command === 'capabilities') console.log(JSON.stringify({ ...capabilities(resolved.profile), capabilityCatalog: capabilityCatalog(resolved.profile.agentBackend), profileDigest: resolved.profileDigest, systemPromptDigest: resolved.systemPromptDigest }, null, 2));
+ else if (command === 'compatibility-report') console.log(JSON.stringify({ ...compatibilityReport(resolved.profile), profileDigest: resolved.profileDigest, systemPromptDigest: resolved.systemPromptDigest }, null, 2));
+ else if (command === 'doctor' || command === 'verify-agent') console.log(JSON.stringify(await doctor(resolved, flag('--output-dir')), null, 2));
+ else console.log(JSON.stringify({ ok: true, profileId: resolved.profile.id, profileDigest: resolved.profileDigest, systemPromptDigest: resolved.systemPromptDigest }, null, 2));
+ return;
+ }
+ if (command === 'run') {
+ const task = flag('--task') ?? process.env.CINDY_HEADLESS_TASK ?? '';
+ if (!task) throw new Error('--task or CINDY_HEADLESS_TASK is required');
+ const turnsFile = flag('--turns-file');
+ const turns = turnsFile ? JSON.parse(await readFile(turnsFile, 'utf8')) : [task];
+ if (!Array.isArray(turns) || turns.length === 0) throw new Error('--turns-file must contain a non-empty turn array');
+ turns.forEach(validateTurnInput);
+ const timeout = resolveHeadlessTimeout(flag('--timeout-owner'), flag('--timeout-ms'));
+ const result = await runTask(await readProfile(requireFlag('--profile'), flag('--bundle-dir')), task, flag('--working-dir') ?? process.cwd(), flag('--output-dir') ?? './results', timeout.timeoutMs, turns);
+ console.log(JSON.stringify(result, null, 2));
+ if (String(result.status ?? '').startsWith('infra-')) process.exitCode = 1;
+ return;
+ }
+ if (command === 'plan') {
+ const manifestPath = requireFlag('--manifest');
+ const outputPath = requireFlag('--output');
+ if (args.includes('--paired')) {
+ const manifest = validatePairedManifest(validateManifest(JSON.parse(await readFile(manifestPath, 'utf8'))));
+ const { writeFile } = await import('node:fs/promises');
+ await writeFile(outputPath, JSON.stringify(expandPairedPlan(manifest), null, 2) + '\n', 'utf8');
+ } else {
+ const manifest = validateManifest(JSON.parse(await readFile(manifestPath, 'utf8')));
+ const { writeFile } = await import('node:fs/promises');
+ await writeFile(outputPath, JSON.stringify(args.includes('--scheduled') ? expandScheduledPlan(manifest) : expandPlan(manifest), null, 2) + '\n');
+ }
+ console.log(JSON.stringify({ ok: true, output: requireFlag('--output') }));
+ return;
+ }
+ if (command === 'paired-summary') {
+ const results = JSON.parse(await readFile(requireFlag('--results'), 'utf8'));
+ console.log(JSON.stringify(summarizePairedResults(results), null, 2));
+ return;
+ }
+ if (command === 'report') {
+ const manifest = validateManifest(JSON.parse(await readFile(requireFlag('--manifest'), 'utf8')));
+ const results = JSON.parse(await readFile(requireFlag('--results'), 'utf8'));
+ console.log(JSON.stringify(createEvaluationReport(manifest, results), null, 2));
+ return;
+ }
+ if (command === 'freeze-hard-30') {
+ const historical = JSON.parse(await readFile(requireFlag('--historical'), 'utf8')) as Array<{ taskId: string; solveRate: number }>;
+ console.log(JSON.stringify(freezeHard30(historical), null, 2));
+ return;
+ }
+ if (command === 'oracle-gate') {
+ const manifest = validateManifest(JSON.parse(await readFile(requireFlag('--manifest'), 'utf8')));
+ const results = JSON.parse(await readFile(requireFlag('--results'), 'utf8')) as Array<{ taskId: string; reward: number }>;
+ console.log(JSON.stringify(validateOracleGate(manifest.dataset.taskIds, results), null, 2));
+ return;
+ }
+ console.error('cindy-headless commands: version, doctor, verify-agent, compatibility-report, profile validate, capabilities [--manifest <bundle-manifest.json>], run [--turns-file] [--timeout-owner headless|external] [--timeout-ms N], plan [--paired|--scheduled], paired-summary, report, freeze-hard-30, oracle-gate');
+ process.exitCode = 2;
+}
+
+main().catch((error) => { console.error(JSON.stringify({ ok: false, error: error instanceof Error ? error.message : String(error) })); process.exitCode = 1; });
diff --git a/apps/cindy-headless/src/codex-memory-bridge.test.ts b/apps/cindy-headless/src/codex-memory-bridge.test.ts
new file mode 100644
index 0000000000..7c11114221
--- /dev/null
+++ b/apps/cindy-headless/src/codex-memory-bridge.test.ts
@@ -0,0 +1,37 @@
+import { describe, expect, it } from 'vitest';
+import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
+import type { Logger, McpProvider } from '@cindy/maker-core';
+import { startCodexMemoryBridge } from './codex-memory-bridge.js';
+
+const logger: Logger = {
+ trace() {}, debug() {}, info() {}, warn() {}, error() {}, fatal() {}, child: () => logger,
+};
+
+describe('Codex Maker Memory bridge', () => {
+ it('requires the per-run token and accepts a stateful MCP initialize', async () => {
+ const provider: McpProvider = {
+ name: 'cindy_memory',
+ toClaudeSdkConfig: () => ({ type: 'sdk', name: 'cindy_memory', instance: new McpServer({ name: 'cindy_memory', version: '0.1.0' }) }),
+ };
+ const bridge = await startCodexMemoryBridge({ provider, workingDir: process.cwd(), logger });
+ try {
+ const url = `http://127.0.0.1:${bridge.port}/mcp/cindy_memory`;
+ const init = {
+ jsonrpc: '2.0', id: 1, method: 'initialize',
+ params: { protocolVersion: '2025-03-26', capabilities: {}, clientInfo: { name: 'test', version: '1' } },
+ };
+ const unauthorized = await fetch(url, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(init) });
+ expect(unauthorized.status).toBe(401);
+ const token = bridge.extraEnv.CINDY_HEADLESS_MCP_TOKEN;
+ const response = await fetch(url, {
+ method: 'POST',
+ headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json', accept: 'application/json, text/event-stream' },
+ body: JSON.stringify(init),
+ });
+ expect(response.status).toBe(200);
+ expect(response.headers.get('mcp-session-id')).toBeTruthy();
+ } finally {
+ await bridge.shutdown();
+ }
+ });
+});
diff --git a/apps/cindy-headless/src/codex-memory-bridge.ts b/apps/cindy-headless/src/codex-memory-bridge.ts
new file mode 100644
index 0000000000..0328e72ba5
--- /dev/null
+++ b/apps/cindy-headless/src/codex-memory-bridge.ts
@@ -0,0 +1,164 @@
+import { randomBytes, randomUUID } from 'node:crypto';
+import http from 'node:http';
+import type { AddressInfo, Socket } from 'node:net';
+import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
+import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
+import { isInitializeRequest } from '@modelcontextprotocol/sdk/types.js';
+import type { Logger, McpProvider, McpProviderContext } from '@cindy/maker-core';
+
+const TOKEN_ENV = 'CINDY_HEADLESS_MCP_TOKEN';
+const SERVER_NAME = 'cindy_memory';
+const MAX_INIT_BODY_BYTES = 1024 * 1024;
+const MCP_TIMEOUT_SECONDS = 10 * 60;
+
+interface ActiveTransport {
+ server: McpServer;
+ transport: StreamableHTTPServerTransport;
+}
+
+export interface CodexMemoryBridge {
+ extraArgs: string[];
+ extraEnv: Record<string, string>;
+ port: number;
+ token: string;
+ url: string;
+ shutdown(): Promise<void>;
+}
+
+async function readJsonBody(req: http.IncomingMessage, limit = Number.POSITIVE_INFINITY): Promise<unknown> {
+ const chunks: Buffer[] = [];
+ let received = 0;
+ for await (const chunk of req) {
+ const buffer = typeof chunk === 'string' ? Buffer.from(chunk) : chunk as Buffer;
+ received += buffer.length;
+ if (received > limit) throw new Error('BODY_TOO_LARGE');
+ chunks.push(buffer);
+ }
+ if (chunks.length === 0) return undefined;
+ const body = Buffer.concat(chunks).toString('utf8');
+ return body.trim() ? JSON.parse(body) : undefined;
+}
+
+function createServerFactory(provider: McpProvider, workingDir: string): () => McpServer {
+ const context: McpProviderContext = { agentKind: 'codex', workingDir, vendorOptions: {} };
+ if (provider.name !== SERVER_NAME || !provider.toClaudeSdkConfig) {
+ throw new Error('Codex Maker Memory bridge requires the cindy_memory SDK provider');
+ }
+ return () => {
+ const config = provider.toClaudeSdkConfig!(context) as { type?: string; instance?: unknown } | null;
+ if (config?.type !== 'sdk' || !config.instance) {
+ throw new Error('cindy_memory did not return an SDK MCP server');
+ }
+ return config.instance as McpServer;
+ };
+}
+
+export async function startCodexMemoryBridge(options: {
+ provider: McpProvider;
+ workingDir: string;
+ logger: Logger;
+}): Promise<CodexMemoryBridge> {
+ const logger = options.logger.child('codex-memory-bridge');
+ const createServer = createServerFactory(options.provider, options.workingDir);
+ const token = randomBytes(32).toString('hex');
+ const sessions = new Map<string, ActiveTransport>();
+ const sockets = new Set<Socket>();
+
+ const server = http.createServer(async (req, res) => {
+ try {
+ const remote = req.socket.remoteAddress;
+ if (remote !== '127.0.0.1' && remote !== '::1' && remote !== '::ffff:127.0.0.1') {
+ res.writeHead(403).end();
+ return;
+ }
+ if (req.headers.authorization !== `Bearer ${token}`) {
+ res.writeHead(401, { 'www-authenticate': 'Bearer' }).end();
+ return;
+ }
+ if (new URL(req.url ?? '/', 'http://127.0.0.1').pathname !== `/mcp/${SERVER_NAME}`) {
+ res.writeHead(404).end();
+ return;
+ }
+
+ const sessionHeader = req.headers['mcp-session-id'];
+ const sessionId = typeof sessionHeader === 'string' ? sessionHeader : undefined;
+ if (sessionId) {
+ const active = sessions.get(sessionId);
+ if (!active) {
+ res.writeHead(404).end('Unknown session');
+ return;
+ }
+ const body = req.method === 'POST' ? await readJsonBody(req) : undefined;
+ await active.transport.handleRequest(req, res, body);
+ return;
+ }
+
+ if (req.method !== 'POST') {
+ res.writeHead(400).end('Missing mcp-session-id');
+ return;
+ }
+ const body = await readJsonBody(req, MAX_INIT_BODY_BYTES);
+ if (!isInitializeRequest(body)) {
+ res.writeHead(400).end('Expected initialize request');
+ return;
+ }
+
+ const mcpServer = createServer();
+ let transport!: StreamableHTTPServerTransport;
+ transport = new StreamableHTTPServerTransport({
+ sessionIdGenerator: () => randomUUID(),
+ onsessioninitialized: (id: string): void => { sessions.set(id, { server: mcpServer, transport }); },
+ });
+ transport.onclose = () => {
+ if (transport.sessionId) sessions.delete(transport.sessionId);
+ };
+ await mcpServer.connect(transport);
+ await transport.handleRequest(req, res, body);
+ } catch (error) {
+ logger.error('Codex memory bridge request failed', {
+ message: error instanceof Error ? error.message : String(error),
+ });
+ if (!res.headersSent) res.writeHead(error instanceof Error && error.message === 'BODY_TOO_LARGE' ? 413 : 500);
+ if (!res.writableEnded) res.end();
+ }
+ });
+ server.keepAliveTimeout = 0;
+ server.headersTimeout = 0;
+ server.requestTimeout = 0;
+ server.on('connection', (socket) => {
+ sockets.add(socket);
+ socket.once('close', () => sockets.delete(socket));
+ });
+ await new Promise<void>((resolve, reject) => {
+ server.once('error', reject);
+ server.listen(0, '127.0.0.1', () => {
+ server.removeListener('error', reject);
+ resolve();
+ });
+ });
+
+ const port = (server.address() as AddressInfo).port;
+ const url = `http://127.0.0.1:${port}/mcp/${SERVER_NAME}`;
+ logger.info('Codex memory bridge listening', { port, server: SERVER_NAME });
+ return {
+ port,
+ token,
+ url,
+ extraEnv: { [TOKEN_ENV]: token },
+ extraArgs: [
+ // Do not inherit Desktop/plugin MCP entries from a user's CODEX_HOME.
+ '-c', 'mcp_servers={}',
+ '-c', `mcp_servers.${SERVER_NAME}.url="${url}"`,
+ '-c', `mcp_servers.${SERVER_NAME}.bearer_token_env_var="${TOKEN_ENV}"`,
+ '-c', `mcp_servers.${SERVER_NAME}.startup_timeout_sec=${MCP_TIMEOUT_SECONDS}`,
+ '-c', `mcp_servers.${SERVER_NAME}.tool_timeout_sec=${MCP_TIMEOUT_SECONDS}`,
+ ],
+ async shutdown() {
+ for (const active of sessions.values()) await active.transport.close().catch(() => undefined);
+ sessions.clear();
+ for (const socket of sockets) socket.destroy();
+ sockets.clear();
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ },
+ };
+}
diff --git a/apps/cindy-headless/src/compatibility.test.ts b/apps/cindy-headless/src/compatibility.test.ts
new file mode 100644
index 0000000000..529660216e
--- /dev/null
+++ b/apps/cindy-headless/src/compatibility.test.ts
@@ -0,0 +1,105 @@
+import { readFileSync } from 'node:fs';
+import { describe, expect, it } from 'vitest';
+import registry from '../capability-registry.json';
+import { assertSafeExecutionProfile, capabilityCatalog, CINDY_HEADLESS_VERSION, CINDY_UPSTREAM_COMMIT, compatibilityReport, discoverCapabilityCatalog, validateCapabilityRegistry } from './compatibility.js';
+import { validateProfile } from './profile.js';
+
+const packageMetadata = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
+
+const base = {
+ id: 'compatibility-test',
+ version: 1,
+ agentBackend: 'codex',
+ agentBinaryPath: '/opt/codex',
+ agentBinaryVersion: '1.2.3',
+ supportedModelIds: ['gpt-test'],
+ model: { provider: 'openai', requestedId: 'gpt-test' },
+ permissionMode: 'auto',
+ makerMemory: true,
+ nativeMemory: false,
+ projectContext: true,
+} as const;
+
+describe('headless compatibility contract', () => {
+ it('validates the single-source capability registry and rejects dangling harness features', () => {
+ expect(() => validateCapabilityRegistry(registry)).not.toThrow();
+ const invalid = structuredClone(registry) as unknown as { harnesses: { codex: { features: string[] } } };
+ invalid.harnesses.codex.features.push('unregisteredFeature');
+ expect(() => validateCapabilityRegistry(invalid)).toThrow('invalid capability registry harness');
+ });
+ it('publishes a stable web-discovery capability catalog', () => {
+ const catalog = capabilityCatalog('claude-code');
+ expect(catalog.contractVersion).toBe(1);
+ expect(catalog.harnesses).toEqual([{ id: 'cindy-claude', backend: 'claude-code', features: ['projectContext', 'makerMemory', 'nativeMemory', 'attachments'], adapterSupported: true }]);
+ expect(catalog.features.projectContext).toMatchObject({ type: 'boolean', control: 'profile', default: false, label: 'Project Context' });
+ expect(catalog.constraints).toEqual([{ type: 'mutuallyExclusive', features: ['makerMemory', 'nativeMemory'], harnesses: ['claude-code', 'codex'], offLabel: '关闭所有自动记忆' }]);
+ });
+
+ it('advertises Cindy memory controls for Pi while keeping the backend identity', () => {
+ const catalog = capabilityCatalog('pi');
+ expect(catalog.harnesses[0]).toMatchObject({ id: 'cindy-pi', backend: 'pi' });
+ expect(catalog.harnesses[0].features).toEqual(['projectContext', 'makerMemory', 'nativeMemory', 'attachments', 'piProjectSkills']);
+ expect(catalog.features.makerMemory).toBeDefined();
+ });
+
+ it('reports unknown features and harnesses instead of hiding them', () => {
+ const catalog = capabilityCatalog();
+ catalog.features.futureFeature = { type: 'boolean', control: 'profile', default: false };
+ catalog.harnesses.push({ id: 'future', backend: 'future-agent', features: ['futureFeature'], adapterSupported: true });
+ const discovered = discoverCapabilityCatalog(catalog);
+ expect(discovered.support.futureFeature).toBe('DETECTED_BUT_UNSUPPORTED');
+ expect(discovered.harnesses.at(-1)).toMatchObject({ backend: 'future-agent', adapterSupported: false, status: 'DETECTED_BUT_UNSUPPORTED' });
+ });
+
+ it('rejects a manifest without a capability catalog', () => {
+ expect(() => discoverCapabilityCatalog(undefined)).toThrow('bundle manifest does not contain capabilityCatalog');
+ });
+
+ it('reflects explicit adapter support and profile feature coverage', () => {
+ const catalog = capabilityCatalog();
+ catalog.harnesses[1].adapterSupported = false;
+ const discovered = discoverCapabilityCatalog(catalog);
+ expect(discovered.harnesses.find((item) => item.backend === 'codex')?.status).toBe('DETECTED_BUT_UNSUPPORTED');
+ for (const harness of discovered.harnesses.filter((item) => item.status === 'SUPPORTED')) {
+ expect(harness.features.every((id) => discovered.support[id] === 'SUPPORTED')).toBe(true);
+ }
+ });
+
+ it('keeps the runtime and package versions aligned', () => {
+ expect(CINDY_HEADLESS_VERSION).toBe(packageMetadata.version);
+ expect(CINDY_UPSTREAM_COMMIT).toBe(packageMetadata.cindyUpstreamCommit);
+ });
+
+ it('describes the backend transport and required capabilities', () => {
+ expect(compatibilityReport(validateProfile(base))).toMatchObject({
+ schemaVersion: 1,
+ contractVersion: 1,
+ cindyUpstreamCommit: CINDY_UPSTREAM_COMMIT,
+ transport: 'codex-app-server-jsonrpc',
+ requiredCapabilities: expect.arrayContaining(['multi-turn-session', 'mcp']),
+ });
+ });
+
+ it('describes the Pi RPC transport', () => {
+ const pi = validateProfile({
+ ...base,
+ agentBackend: 'pi',
+ agentBinaryPath: '/opt/pi/pi',
+ agentBinaryVersion: '0.83.0',
+ model: { ...base.model, contextLimit: 200_000 },
+ permissionMode: 'bypassPermissions',
+ containerSandbox: true,
+ });
+ expect(compatibilityReport(pi).transport).toBe('pi-rpc-jsonl');
+ });
+
+ it('rejects unsandboxed permission bypass by default', () => {
+ const profile = validateProfile({ ...base, permissionMode: 'bypassPermissions' });
+ expect(() => assertSafeExecutionProfile(profile)).toThrow(/containerSandbox=true/);
+ });
+
+ it('accepts permission bypass inside an explicit container sandbox', () => {
+ const profile = validateProfile({ ...base, permissionMode: 'bypassPermissions', containerSandbox: true });
+ expect(() => assertSafeExecutionProfile(profile)).not.toThrow();
+ });
+});
diff --git a/apps/cindy-headless/src/compatibility.ts b/apps/cindy-headless/src/compatibility.ts
new file mode 100644
index 0000000000..9fc67f463a
--- /dev/null
+++ b/apps/cindy-headless/src/compatibility.ts
@@ -0,0 +1,200 @@
+import type { HeadlessProfile } from './profile.js';
+import registry from '../capability-registry.json';
+
+export const HEADLESS_CONTRACT_VERSION = 1;
+export const CINDY_HEADLESS_VERSION = '0.4.3';
+export const CINDY_UPSTREAM_COMMIT = 'fa3fc88d37d205ea993a67d85612fa9a5436fae5';
+
+export interface HeadlessFeatureCapability {
+ type: 'boolean' | 'object' | 'array';
+ control: 'profile';
+ default: boolean | Record<string, unknown> | unknown[];
+ label?: string;
+ description?: string;
+}
+
+export interface HeadlessControlCapability {
+ type: string;
+ control: string;
+ [key: string]: unknown;
+}
+
+export interface HeadlessCapabilityConstraint {
+ type: 'mutuallyExclusive';
+ features: string[];
+ harnesses?: string[];
+ offLabel?: string;
+}
+
+export interface HeadlessHarnessCapability {
+ id: string;
+ backend: string;
+ features: string[];
+ adapterSupported: boolean;
+ supportedModelIds?: string[];
+ defaultModel?: HeadlessProfile['model'];
+}
+
+export interface HeadlessCapabilityCatalog {
+ schemaVersion: 1;
+ contractVersion: number;
+ harnesses: HeadlessHarnessCapability[];
+ features: Record<string, HeadlessFeatureCapability>;
+ controls: Record<string, HeadlessControlCapability>;
+ defaultValues: Record<string, boolean | Record<string, unknown> | unknown[]>;
+ constraints?: HeadlessCapabilityConstraint[];
+}
+
+const FEATURE_CAPABILITIES = registry.features as Record<string, HeadlessFeatureCapability>;
+const CONTROL_CAPABILITIES = registry.controls as Record<string, HeadlessControlCapability>;
+
+export function validateCapabilityRegistry(value: unknown): asserts value is typeof registry {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('capability registry must be an object');
+ const candidate = value as Record<string, unknown>;
+ if (candidate.schemaVersion !== 1 || candidate.contractVersion !== HEADLESS_CONTRACT_VERSION) throw new Error('unsupported capability registry schema or contract');
+ if (!candidate.features || typeof candidate.features !== 'object' || Array.isArray(candidate.features)) throw new Error('capability registry features must be an object');
+ if (!candidate.controls || typeof candidate.controls !== 'object' || Array.isArray(candidate.controls)) throw new Error('capability registry controls must be an object');
+ if (!candidate.harnesses || typeof candidate.harnesses !== 'object' || Array.isArray(candidate.harnesses)) throw new Error('capability registry harnesses must be an object');
+ const features = candidate.features as Record<string, unknown>;
+ for (const [id, raw] of Object.entries(features)) {
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw new Error(`invalid capability registry feature: ${id}`);
+ const feature = raw as Record<string, unknown>;
+ if (!['boolean', 'object', 'array'].includes(String(feature.type)) || feature.control !== 'profile' || !Object.hasOwn(feature, 'default')) throw new Error(`invalid capability registry feature: ${id}`);
+ }
+ for (const [backend, raw] of Object.entries(candidate.harnesses as Record<string, unknown>)) {
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw new Error(`invalid capability registry harness: ${backend}`);
+ const harness = raw as Record<string, unknown>;
+ if (typeof harness.id !== 'string' || !Array.isArray(harness.features) || harness.features.some((id) => typeof id !== 'string' || !(id in features))) throw new Error(`invalid capability registry harness: ${backend}`);
+ }
+ if (!Array.isArray(candidate.constraints)) throw new Error('capability registry constraints must be an array');
+ for (const raw of candidate.constraints) {
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw new Error('invalid capability registry constraint');
+ const constraint = raw as Record<string, unknown>;
+ if (constraint.type !== 'mutuallyExclusive' || !Array.isArray(constraint.features) || constraint.features.length < 2 || constraint.features.some((id) => typeof id !== 'string' || !(id in features))) throw new Error('invalid capability registry constraint');
+ }
+}
+
+validateCapabilityRegistry(registry);
+
+export const ADAPTER_FEATURES = new Set(Object.keys(FEATURE_CAPABILITIES));
+export const ADAPTER_HARNESSES = new Set<HeadlessProfile['agentBackend']>(['claude-code', 'codex', 'pi']);
+
+export function capabilityCatalog(backend?: HeadlessProfile['agentBackend']): HeadlessCapabilityCatalog {
+ const backends = backend ? [backend] : [...ADAPTER_HARNESSES];
+ return {
+ schemaVersion: 1,
+ contractVersion: registry.contractVersion,
+ harnesses: backends.map((item) => ({
+ id: registry.harnesses[item].id,
+ backend: item,
+ features: registry.harnesses[item].features,
+ adapterSupported: true,
+ })),
+ features: { ...FEATURE_CAPABILITIES },
+ controls: { ...CONTROL_CAPABILITIES },
+ defaultValues: Object.fromEntries(Object.entries(FEATURE_CAPABILITIES).map(([id, feature]) => [id, feature.default])),
+ constraints: registry.constraints as HeadlessCapabilityConstraint[],
+ };
+}
+
+export interface CapabilityDetection {
+ schemaVersion: 1;
+ contractVersion: number;
+ harnesses: Array<HeadlessHarnessCapability & { status: 'SUPPORTED' | 'DETECTED_BUT_UNSUPPORTED' }>;
+ features: Record<string, HeadlessFeatureCapability>;
+ controls: Record<string, HeadlessControlCapability>;
+ defaultValues: Record<string, boolean | Record<string, unknown> | unknown[]>;
+ constraints?: HeadlessCapabilityConstraint[];
+ adapter: {
+ understoodFeatures: string[];
+ understoodHarnesses: string[];
+ detected: Array<{ id: string; status: 'SUPPORTED' | 'DETECTED_BUT_UNSUPPORTED' }>;
+ };
+ support: Record<string, 'SUPPORTED' | 'DETECTED_BUT_UNSUPPORTED'>;
+}
+
+export function discoverCapabilityCatalog(value: unknown): CapabilityDetection {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('bundle manifest does not contain capabilityCatalog');
+ const catalog = value as Partial<HeadlessCapabilityCatalog>;
+ if (catalog.schemaVersion !== 1 || typeof catalog.contractVersion !== 'number') throw new Error('unsupported capabilityCatalog schema or contract');
+ if (!catalog.features || typeof catalog.features !== 'object' || Array.isArray(catalog.features)) throw new Error('capabilityCatalog.features must be an object');
+ if (!catalog.controls || typeof catalog.controls !== 'object' || Array.isArray(catalog.controls)) throw new Error('capabilityCatalog.controls must be an object');
+ if (!Array.isArray(catalog.harnesses)) throw new Error('capabilityCatalog.harnesses must be an array');
+ const detected = Object.keys(catalog.features).map((id) => ({
+ id,
+ status: ADAPTER_FEATURES.has(id) ? 'SUPPORTED' as const : 'DETECTED_BUT_UNSUPPORTED' as const,
+ }));
+ const harnesses = catalog.harnesses.map((harness) => {
+ if (!harness || typeof harness !== 'object' || typeof harness.id !== 'string' || typeof harness.backend !== 'string' || !Array.isArray(harness.features)) {
+ throw new Error('capabilityCatalog contains an invalid harness');
+ }
+ const understood = ADAPTER_HARNESSES.has(harness.backend as HeadlessProfile['agentBackend']);
+ const featuresSupported = harness.features.every((id) => ADAPTER_FEATURES.has(id));
+ const status = understood && harness.adapterSupported !== false && featuresSupported ? 'SUPPORTED' as const : 'DETECTED_BUT_UNSUPPORTED' as const;
+ return { ...harness, adapterSupported: status === 'SUPPORTED', status };
+ });
+ return {
+ schemaVersion: 1,
+ contractVersion: catalog.contractVersion,
+ harnesses,
+ features: catalog.features,
+ controls: catalog.controls,
+ defaultValues: catalog.defaultValues ?? {},
+ constraints: catalog.constraints ?? [],
+ adapter: { understoodFeatures: [...ADAPTER_FEATURES], understoodHarnesses: [...ADAPTER_HARNESSES], detected },
+ support: Object.fromEntries(detected.map((item) => [item.id, item.status])),
+ };
+}
+
+export interface CompatibilityReport {
+ schemaVersion: 1;
+ contractVersion: number;
+ cindyUpstreamCommit: string;
+ backend: HeadlessProfile['agentBackend'];
+ binaryVersion: string;
+ transport: 'claude-agent-sdk' | 'codex-app-server-jsonrpc' | 'pi-rpc-jsonl';
+ requiredCapabilities: string[];
+ security: {
+ permissionMode: HeadlessProfile['permissionMode'];
+ containerSandbox: boolean;
+ safeForUntrustedWorkloads: boolean;
+ };
+}
+
+export function compatibilityReport(profile: HeadlessProfile): CompatibilityReport {
+ const codex = profile.agentBackend === 'codex';
+ const pi = profile.agentBackend === 'pi';
+ const isolated = profile.containerSandbox === true;
+ const bypass = profile.permissionMode === 'bypassPermissions';
+ return {
+ schemaVersion: 1,
+ contractVersion: HEADLESS_CONTRACT_VERSION,
+ cindyUpstreamCommit: CINDY_UPSTREAM_COMMIT,
+ backend: profile.agentBackend,
+ binaryVersion: profile.agentBinaryVersion,
+ transport: pi ? 'pi-rpc-jsonl' : codex ? 'codex-app-server-jsonrpc' : 'claude-agent-sdk',
+ requiredCapabilities: [
+ 'multi-turn-session',
+ 'structured-agent-events',
+ 'abort-and-close',
+ 'usage-reporting',
+ ...(profile.makerMemory ? ['mcp'] : []),
+ ],
+ security: {
+ permissionMode: profile.permissionMode,
+ containerSandbox: isolated,
+ safeForUntrustedWorkloads: !bypass || isolated,
+ },
+ };
+}
+
+export function assertSafeExecutionProfile(profile: HeadlessProfile): void {
+ if (
+ profile.permissionMode === 'bypassPermissions'
+ && profile.containerSandbox !== true
+ && profile.unsafeAllowUnsandboxedBypass !== true
+ && process.env.CINDY_HEADLESS_ALLOW_UNSANDBOXED_BYPASS !== '1'
+ ) {
+ throw new Error('bypassPermissions requires containerSandbox=true; set CINDY_HEADLESS_ALLOW_UNSANDBOXED_BYPASS=1 only in a controlled environment');
+ }
+}
diff --git a/apps/cindy-headless/src/defaults.ts b/apps/cindy-headless/src/defaults.ts
new file mode 100644
index 0000000000..3a80cf4775
--- /dev/null
+++ b/apps/cindy-headless/src/defaults.ts
@@ -0,0 +1,29 @@
+export const DEFAULT_HEADLESS_TIMEOUT_MS = 1_800_000;
+
+export type TimeoutOwner = 'headless' | 'external';
+
+export interface HeadlessTimeoutConfig {
+ owner: TimeoutOwner;
+ timeoutMs: number | null;
+}
+
+export function resolveHeadlessTimeout(
+ ownerValue: string | undefined,
+ timeoutValue: string | undefined,
+): HeadlessTimeoutConfig {
+ const owner = ownerValue ?? 'headless';
+ if (owner !== 'headless' && owner !== 'external') {
+ throw new Error('--timeout-owner must be headless or external');
+ }
+ if (owner === 'external') {
+ if (timeoutValue !== undefined) {
+ throw new Error('--timeout-ms cannot be used with --timeout-owner external');
+ }
+ return { owner, timeoutMs: null };
+ }
+ const timeoutMs = Number(timeoutValue ?? String(DEFAULT_HEADLESS_TIMEOUT_MS));
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
+ throw new Error('--timeout-ms must be a positive number');
+ }
+ return { owner, timeoutMs };
+}
diff --git a/apps/cindy-headless/src/eval-cli.ts b/apps/cindy-headless/src/eval-cli.ts
new file mode 100644
index 0000000000..0a10187e14
--- /dev/null
+++ b/apps/cindy-headless/src/eval-cli.ts
@@ -0,0 +1,58 @@
+#!/usr/bin/env node
+import { readFile, writeFile } from 'node:fs/promises';
+import {
+ createEvaluationReport,
+ expandPairedPlan,
+ expandPlan,
+ expandScheduledPlan,
+ freezeHard30,
+ summarizePairedResults,
+ validateManifest,
+ validateOracleGate,
+ validatePairedManifest,
+} from './benchmark.js';
+
+const args = process.argv.slice(2);
+const command = args[0] ?? 'help';
+function flag(name: string): string | undefined { const index = args.indexOf(name); return index >= 0 ? args[index + 1] : undefined; }
+function requireFlag(name: string): string { const value = flag(name); if (!value) throw new Error(`${name} is required`); return value; }
+
+async function main(): Promise<void> {
+ if (command === 'plan') {
+ const outputPath = requireFlag('--output');
+ const manifest = validateManifest(JSON.parse(await readFile(requireFlag('--manifest'), 'utf8')));
+ const plan = args.includes('--paired')
+ ? expandPairedPlan(validatePairedManifest(manifest))
+ : args.includes('--scheduled') ? expandScheduledPlan(manifest) : expandPlan(manifest);
+ await writeFile(outputPath, JSON.stringify(plan, null, 2) + '\n', 'utf8');
+ console.log(JSON.stringify({ ok: true, output: outputPath }));
+ return;
+ }
+ if (command === 'paired-summary') {
+ console.log(JSON.stringify(summarizePairedResults(JSON.parse(await readFile(requireFlag('--results'), 'utf8'))), null, 2));
+ return;
+ }
+ if (command === 'report') {
+ const manifest = validateManifest(JSON.parse(await readFile(requireFlag('--manifest'), 'utf8')));
+ console.log(JSON.stringify(createEvaluationReport(manifest, JSON.parse(await readFile(requireFlag('--results'), 'utf8'))), null, 2));
+ return;
+ }
+ if (command === 'freeze-hard-30') {
+ const historical = JSON.parse(await readFile(requireFlag('--historical'), 'utf8')) as Array<{ taskId: string; solveRate: number }>;
+ console.log(JSON.stringify(freezeHard30(historical), null, 2));
+ return;
+ }
+ if (command === 'oracle-gate') {
+ const manifest = validateManifest(JSON.parse(await readFile(requireFlag('--manifest'), 'utf8')));
+ const results = JSON.parse(await readFile(requireFlag('--results'), 'utf8')) as Array<{ taskId: string; reward: number }>;
+ console.log(JSON.stringify(validateOracleGate(manifest.dataset.taskIds, results), null, 2));
+ return;
+ }
+ console.error('cindy-headless-eval commands: plan [--paired|--scheduled], paired-summary, report, freeze-hard-30, oracle-gate');
+ process.exitCode = 2;
+}
+
+main().catch((error) => {
+ console.error(JSON.stringify({ ok: false, error: error instanceof Error ? error.message : String(error) }));
+ process.exitCode = 1;
+});
diff --git a/apps/cindy-headless/src/gateway-config.test.ts b/apps/cindy-headless/src/gateway-config.test.ts
new file mode 100644
index 0000000000..276d87b4cf
--- /dev/null
+++ b/apps/cindy-headless/src/gateway-config.test.ts
@@ -0,0 +1,49 @@
+import { describe, expect, it } from 'vitest';
+import { mkdtemp, writeFile } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import { buildCodexGatewayArgs, gatewayConfigCandidates, loadGatewayConfig } from './gateway-config.js';
+
+describe('gateway config', () => {
+ it('searches the documented repository-local config path', () => {
+ expect(gatewayConfigCandidates()).toContain(path.join(process.cwd(), 'apps', 'cindy-headless', 'config.local.json'));
+ });
+ it('builds an API-key Codex Responses provider without placing the secret in argv', () => {
+ const args = buildCodexGatewayArgs({ baseUrl: 'https://gateway.example.com', apiKey: 'secret' });
+ expect(args).toContain('model_provider="cindy_gateway"');
+ expect(args).toContain('model_providers.cindy_gateway.base_url="https://gateway.example.com/v1"');
+ expect(args).toContain('model_providers.cindy_gateway.env_key="CINDY_CODEX_API_KEY"');
+ expect(args.join(' ')).not.toContain('secret');
+ });
+
+ it('loads the shared gateway config from an explicit local file', async () => {
+ const dir = await mkdtemp(path.join(os.tmpdir(), 'cindy-headless-config-'));
+ const file = path.join(dir, 'config.json');
+ await writeFile(file, JSON.stringify({ gateway: { baseUrl: 'https://gateway.example.com', apiKey: 'file-secret' } }), 'utf8');
+ const previous = {
+ config: process.env.CINDY_HEADLESS_CONFIG_FILE,
+ key: process.env.CINDY_HEADLESS_API_KEY,
+ anthropicKey: process.env.ANTHROPIC_API_KEY,
+ codexKey: process.env.CINDY_CODEX_API_KEY,
+ baseUrl: process.env.CINDY_HEADLESS_BASE_URL,
+ anthropicBaseUrl: process.env.ANTHROPIC_BASE_URL,
+ };
+ process.env.CINDY_HEADLESS_CONFIG_FILE = file;
+ delete process.env.CINDY_HEADLESS_API_KEY;
+ delete process.env.ANTHROPIC_API_KEY;
+ delete process.env.CINDY_CODEX_API_KEY;
+ delete process.env.CINDY_HEADLESS_BASE_URL;
+ delete process.env.ANTHROPIC_BASE_URL;
+ try {
+ await expect(loadGatewayConfig()).resolves.toMatchObject({ baseUrl: 'https://gateway.example.com', apiKey: 'file-secret' });
+ } finally {
+ const restore = (name: string, value: string | undefined) => value === undefined ? delete process.env[name] : process.env[name] = value;
+ restore('CINDY_HEADLESS_CONFIG_FILE', previous.config);
+ restore('CINDY_HEADLESS_API_KEY', previous.key);
+ restore('ANTHROPIC_API_KEY', previous.anthropicKey);
+ restore('CINDY_CODEX_API_KEY', previous.codexKey);
+ restore('CINDY_HEADLESS_BASE_URL', previous.baseUrl);
+ restore('ANTHROPIC_BASE_URL', previous.anthropicBaseUrl);
+ }
+ });
+});
diff --git a/apps/cindy-headless/src/gateway-config.ts b/apps/cindy-headless/src/gateway-config.ts
new file mode 100644
index 0000000000..446052facc
--- /dev/null
+++ b/apps/cindy-headless/src/gateway-config.ts
@@ -0,0 +1,87 @@
+import { chmod, readFile } from 'node:fs/promises';
+import { existsSync } from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+
+export interface GatewayConfig {
+ baseUrl: string;
+ apiKey: string;
+ codexBasePath?: string;
+}
+
+const ENV_CONFIG = 'CINDY_HEADLESS_CONFIG_FILE';
+const CODEX_ENV_KEY = 'CINDY_CODEX_API_KEY';
+
+function validateBaseUrl(value: unknown): string {
+ if (typeof value !== 'string' || value.trim() === '') throw new Error('gateway.baseUrl must be a non-empty string');
+ let url: URL;
+ try { url = new URL(value); } catch { throw new Error('gateway.baseUrl must be a valid URL'); }
+ if (!['https:', 'http:'].includes(url.protocol)) throw new Error('gateway.baseUrl must use http or https');
+ if (url.protocol === 'http:' && !['127.0.0.1', 'localhost', '::1'].includes(url.hostname)) throw new Error('gateway.baseUrl must use https except for loopback');
+ if (url.username || url.password) throw new Error('gateway.baseUrl must not contain credentials');
+ return value.replace(/\/+$/, '');
+}
+
+function parseConfig(raw: unknown): GatewayConfig {
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw new Error('gateway config must be an object');
+ const value = raw as { gateway?: { baseUrl?: unknown; apiKey?: unknown; codexBasePath?: unknown } };
+ const gateway = value.gateway;
+ if (!gateway || typeof gateway !== 'object') throw new Error('gateway section is required');
+ if (typeof gateway.apiKey !== 'string' || gateway.apiKey.trim() === '') throw new Error('gateway.apiKey must be a non-empty string');
+ const codexBasePath = gateway.codexBasePath ?? '/v1';
+ if (typeof codexBasePath !== 'string' || !codexBasePath.startsWith('/')) throw new Error('gateway.codexBasePath must start with /');
+ return { baseUrl: validateBaseUrl(gateway.baseUrl), apiKey: gateway.apiKey, codexBasePath: codexBasePath.replace(/\/+$/, '') };
+}
+
+export function gatewayConfigCandidates(): string[] {
+ return [
+ process.env[ENV_CONFIG],
+ path.join(process.cwd(), 'config.local.json'),
+ path.join(process.cwd(), 'apps', 'cindy-headless', 'config.local.json'),
+ path.join(process.cwd(), '.cindy-headless.json'),
+ path.join(process.env.APPDATA ?? path.join(os.homedir(), 'AppData', 'Roaming'), 'cindy-headless', 'config.json'),
+ path.join(os.homedir(), '.config', 'cindy-headless', 'config.json'),
+ ].filter((value): value is string => Boolean(value));
+}
+
+export async function loadGatewayConfig(): Promise<GatewayConfig | null> {
+ const envBaseUrl = process.env.CINDY_HEADLESS_BASE_URL ?? process.env.ANTHROPIC_BASE_URL;
+ const envKey = process.env.CINDY_HEADLESS_API_KEY ?? process.env.ANTHROPIC_API_KEY ?? process.env.CINDY_CODEX_API_KEY;
+ const configuredPath = gatewayConfigCandidates().find((candidate) => {
+ try { return existsSync(candidate); } catch { return false; }
+ });
+ if (!configuredPath) {
+ if (!envBaseUrl || !envKey) return null;
+ return parseConfig({ gateway: { baseUrl: envBaseUrl, apiKey: envKey } });
+ }
+ await assertConfigFilePermissions(configuredPath);
+ const config = parseConfig(JSON.parse(await readFile(configuredPath, 'utf8')));
+ return { ...config, baseUrl: envBaseUrl ? validateBaseUrl(envBaseUrl) : config.baseUrl, apiKey: envKey ?? config.apiKey };
+}
+
+export function applyGatewayConfig(config: GatewayConfig | null): void {
+ if (!config) return;
+ process.env.CINDY_HEADLESS_API_KEY = config.apiKey;
+ process.env.ANTHROPIC_API_KEY = config.apiKey;
+ process.env.CINDY_HEADLESS_BASE_URL = config.baseUrl;
+ process.env.ANTHROPIC_BASE_URL = config.baseUrl;
+ process.env.CINDY_CODEX_API_KEY = config.apiKey;
+ process.env.CINDY_CODEX_BASE_URL = `${config.baseUrl}${config.codexBasePath ?? '/v1'}`;
+}
+
+export function buildCodexGatewayArgs(config: GatewayConfig): string[] {
+ const provider = 'cindy_gateway';
+ const baseUrl = process.env.CINDY_CODEX_BASE_URL ?? `${config.baseUrl}${config.codexBasePath ?? '/v1'}`;
+ return [
+ '-c', `model_provider="${provider}"`,
+ '-c', `model_providers.${provider}.name="Cindy Gateway"`,
+ '-c', `model_providers.${provider}.base_url="${baseUrl}"`,
+ '-c', `model_providers.${provider}.wire_api="responses"`,
+ '-c', `model_providers.${provider}.env_key="${CODEX_ENV_KEY}"`,
+ '-c', `model_providers.${provider}.supports_websockets=false`,
+ ];
+}
+
+export async function assertConfigFilePermissions(filePath: string): Promise<void> {
+ if (process.platform !== 'win32') await chmod(filePath, 0o600);
+}
diff --git a/apps/cindy-headless/src/headless-integrations.test.ts b/apps/cindy-headless/src/headless-integrations.test.ts
new file mode 100644
index 0000000000..d8ad779a0d
--- /dev/null
+++ b/apps/cindy-headless/src/headless-integrations.test.ts
@@ -0,0 +1,98 @@
+import { execFile } from 'node:child_process';
+import { mkdir, mkdtemp, realpath, writeFile } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import { promisify } from 'node:util';
+import { describe, expect, it } from 'vitest';
+import { inspectPiProjectWorkspaceResources, piProjectResourcesEvidence, piProjectSkillDenials, resolvePiProjectTrust, resolveTurns, validateTurnInput } from './headless-integrations.js';
+
+const execFileAsync = promisify(execFile);
+
+describe('headless capability inputs', () => {
+ it('keeps string turns compatible and accepts structured attachments', () => {
+ expect(validateTurnInput('hello')).toBe('hello');
+ expect(validateTurnInput({ text: 'inspect', attachments: [{ type: 'file', path: 'fixture.txt' }] })).toMatchObject({ text: 'inspect' });
+ });
+
+ it('resolves workspace attachments and rejects traversal', async () => {
+ const workspace = await mkdtemp(path.join(os.tmpdir(), 'headless-input-'));
+ await writeFile(path.join(workspace, 'fixture.txt'), 'fixture');
+ const turns = await resolveTurns([{ text: 'inspect', attachments: [{ type: 'file', path: 'fixture.txt' }] }], workspace, { attachments: true, workspaceOnly: true });
+ expect(turns[0]).toMatchObject({ type: 'user', content: [{ type: 'text' }, { type: 'file', path: await realpath(path.join(workspace, 'fixture.txt')) }] });
+ expect(() => validateTurnInput({ text: 'bad', attachments: [{ type: 'file', path: '../outside' }] })).toThrow(/workspace-relative/);
+ });
+
+ it('fails closed when attachments are disabled', async () => {
+ const workspace = await mkdtemp(path.join(os.tmpdir(), 'headless-input-off-'));
+ await mkdir(path.join(workspace, 'files'));
+ await writeFile(path.join(workspace, 'files', 'fixture.txt'), 'fixture');
+ await expect(resolveTurns([{ text: 'inspect', attachments: [{ type: 'file', path: 'files/fixture.txt' }] }], workspace, undefined)).rejects.toThrow(/does not enable attachments/);
+ });
+
+ it('builds a scoped Pi approval snapshot for current and ancestor project skills', async () => {
+ const repo = await mkdtemp(path.join(os.tmpdir(), 'headless-pi-skills-'));
+ const workspace = path.join(repo, 'packages', 'app');
+ await mkdir(path.join(workspace, '.pi', 'skills', 'local'), { recursive: true });
+ await mkdir(path.join(repo, '.agents', 'skills', 'shared'), { recursive: true });
+ await writeFile(path.join(workspace, '.pi', 'skills', 'local', 'SKILL.md'), '# Local');
+ await writeFile(path.join(repo, '.agents', 'skills', 'shared', 'SKILL.md'), '# Shared');
+ await execFileAsync('git', ['init', repo]);
+ const snapshot = await resolvePiProjectTrust(workspace, { enabled: true, roots: ['.pi/skills', '.agents/skills'] });
+ expect(snapshot?.approval).toMatchObject({ status: 'approved', scope: 'working-dir' });
+ expect(snapshot?.discovered.skills).toHaveLength(2);
+ expect(snapshot?.discovered.packages).toEqual([]);
+ expect(snapshot?.discovered.extensions).toEqual([]);
+ });
+});
+
+describe('pi project workspace resources', () => {
+ it('mirrors upstream in-place collection and denies unapproved Skills', async () => {
+ const repo = await mkdtemp(path.join(os.tmpdir(), 'headless-pi-resources-'));
+ const workspace = path.join(repo, 'packages', 'app');
+ await mkdir(path.join(workspace, '.pi', 'skills', 'local'), { recursive: true });
+ await mkdir(path.join(workspace, '.pi', 'skills', '.hidden'), { recursive: true });
+ await mkdir(path.join(workspace, '.pi', 'skills', 'nomarker'), { recursive: true });
+ await mkdir(path.join(repo, '.agents', 'skills', 'shared'), { recursive: true });
+ await writeFile(path.join(workspace, '.pi', 'skills', 'local', 'SKILL.md'), '# Local');
+ await writeFile(path.join(workspace, '.pi', 'skills', '.hidden', 'SKILL.md'), '# Hidden');
+ await writeFile(path.join(workspace, '.pi', 'skills', 'nomarker', 'readme.md'), '# None');
+ await writeFile(path.join(repo, '.agents', 'skills', 'shared', 'skill.md'), '# Shared');
+ await mkdir(path.join(workspace, '.pi', 'prompts'), { recursive: true });
+ await writeFile(path.join(workspace, '.pi', 'prompts', 'review.md'), '# Review');
+ await writeFile(path.join(workspace, '.pi', 'prompts', 'notes.txt'), 'ignored');
+ await writeFile(path.join(workspace, '.pi', 'prompts', 'SHOUT.MD'), 'ignored by upstream suffix rule');
+ await mkdir(path.join(workspace, '.pi', 'extensions', 'pack'), { recursive: true });
+ await writeFile(path.join(workspace, '.pi', 'extensions', 'single.ts'), 'export {};');
+ await writeFile(path.join(workspace, '.pi', 'extensions', 'pack', 'index.ts'), 'export {};');
+ await writeFile(path.join(workspace, '.pi', 'extensions', 'pack', 'helper.ts'), 'export {};');
+ await execFileAsync('git', ['init', repo]);
+ const resources = await inspectPiProjectWorkspaceResources(workspace);
+ const relative = (target: string) => path.relative(resources.canonicalRepoRoot, target).replaceAll('\\', '/');
+ expect(resources.canonicalRepoRoot).toBe(await realpath(repo));
+ expect(resources.skills.map(relative).sort()).toEqual(['.agents/skills/shared', 'packages/app/.pi/skills/local']);
+ expect(resources.promptTemplates.map(relative)).toEqual(['packages/app/.pi/prompts/review.md']);
+ expect(resources.extensions.map(relative).sort()).toEqual(['packages/app/.pi/extensions/pack/index.ts', 'packages/app/.pi/extensions/single.ts']);
+
+ const approved = await resolvePiProjectTrust(workspace, { enabled: true, roots: ['.agents/skills'] });
+ const denials = piProjectSkillDenials(resources, approved?.discovered.skills ?? []);
+ expect(denials.map(relative)).toEqual(['packages/app/.pi/skills/local']);
+ expect(piProjectSkillDenials(resources, []).map(relative).sort()).toEqual(['.agents/skills/shared', 'packages/app/.pi/skills/local']);
+ expect(piProjectResourcesEvidence(resources, denials)).toMatchObject({
+ inPlace: true,
+ approvedSkillRootsEnforced: true,
+ presentSkills: expect.arrayContaining(['packages/app/.pi/skills/local']),
+ deniedSkills: ['packages/app/.pi/skills/local'],
+ extensions: expect.arrayContaining(['packages/app/.pi/extensions/single.ts']),
+ });
+ });
+
+ it('reports an empty workspace without failing closed on a missing Git root', async () => {
+ const workspace = await mkdtemp(path.join(os.tmpdir(), 'headless-pi-plain-'));
+ const resources = await inspectPiProjectWorkspaceResources(workspace);
+ expect(resources.canonicalRepoRoot).toBe(resources.canonicalWorkingDir);
+ expect(resources.skills).toEqual([]);
+ expect(resources.promptTemplates).toEqual([]);
+ expect(resources.extensions).toEqual([]);
+ expect(piProjectResourcesEvidence(null, [])).toBeNull();
+ });
+});
diff --git a/apps/cindy-headless/src/headless-integrations.ts b/apps/cindy-headless/src/headless-integrations.ts
new file mode 100644
index 0000000000..ee5e04d28d
--- /dev/null
+++ b/apps/cindy-headless/src/headless-integrations.ts
@@ -0,0 +1,367 @@
+import { createHash } from 'node:crypto';
+import { execFile } from 'node:child_process';
+import { lstat, readdir, readFile, realpath, stat } from 'node:fs/promises';
+import path from 'node:path';
+import { promisify } from 'node:util';
+import type {
+ McpProvider,
+ McpProviderContext,
+ PiNativeProvidersResult,
+ PiProjectTrustInputSnapshot,
+ UserMessage,
+} from '@cindy/maker-core';
+import type { HeadlessProfile } from './profile.js';
+
+const execFileAsync = promisify(execFile);
+
+export interface HeadlessTurnInput {
+ text: string;
+ attachments?: Array<{ type: 'file' | 'image'; path: string; mimeType?: string }>;
+}
+
+function isWithin(root: string, candidate: string): boolean {
+ const relative = path.relative(root, candidate);
+ return relative === '' || (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative));
+}
+
+export function validateTurnInput(value: unknown): string | HeadlessTurnInput {
+ if (typeof value === 'string' && value.trim()) return value;
+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('each turn must be a non-empty string or structured turn');
+ const turn = value as Partial<HeadlessTurnInput>;
+ if (typeof turn.text !== 'string' || !turn.text.trim()) throw new Error('structured turn.text must be non-empty');
+ if (turn.attachments !== undefined && !Array.isArray(turn.attachments)) throw new Error('structured turn.attachments must be an array');
+ for (const attachment of turn.attachments ?? []) {
+ if (!attachment || !['file', 'image'].includes(attachment.type) || typeof attachment.path !== 'string' || !attachment.path.trim()) throw new Error('attachment requires type=file|image and a non-empty path');
+ if (path.isAbsolute(attachment.path) || attachment.path.split(/[\\/]/).includes('..')) throw new Error('attachment paths must be workspace-relative without parent traversal');
+ }
+ return turn as HeadlessTurnInput;
+}
+
+export async function resolveTurns(
+ rawTurns: unknown[],
+ workingDir: string,
+ policy: HeadlessProfile['inputPolicy'],
+): Promise<Array<string | UserMessage>> {
+ const workspace = await realpath(workingDir);
+ return Promise.all(rawTurns.map(async (raw) => {
+ const turn = validateTurnInput(raw);
+ if (typeof turn === 'string') return turn;
+ const attachments = turn.attachments ?? [];
+ if (attachments.length > 0 && !policy?.attachments) throw new Error('profile does not enable attachments');
+ if (attachments.length > (policy?.maxFiles ?? 16)) throw new Error('turn exceeds inputPolicy.maxFiles');
+ const content: Exclude<UserMessage['content'], string> = [{ type: 'text', text: turn.text }];
+ for (const attachment of attachments) {
+ const lexical = path.resolve(workspace, attachment.path);
+ const canonical = await realpath(lexical);
+ if (!isWithin(workspace, canonical)) throw new Error(`attachment escapes working directory: ${attachment.path}`);
+ const metadata = await stat(canonical);
+ if (!metadata.isFile()) throw new Error(`attachment is not a file: ${attachment.path}`);
+ if (metadata.size > (policy?.maxFileBytes ?? 25 * 1024 * 1024)) throw new Error(`attachment exceeds inputPolicy.maxFileBytes: ${attachment.path}`);
+ content.push({ type: attachment.type, path: canonical, ...(attachment.mimeType ? { mimeType: attachment.mimeType } : {}) });
+ }
+ return { type: 'user', content } satisfies UserMessage;
+ }));
+}
+
+export class HeadlessRemoteMcpProvider implements McpProvider {
+ readonly name: string;
+
+ constructor(private readonly config: NonNullable<HeadlessProfile['mcpServers']>[number]) {
+ this.name = config.id;
+ }
+
+ private environment(): Record<string, string> {
+ const names = [this.config.bearerTokenEnvVar, ...Object.values(this.config.headerEnvVars ?? {})].filter((name): name is string => Boolean(name));
+ return Object.fromEntries(names.map((name) => {
+ const value = process.env[name];
+ if (!value) throw new Error(`custom MCP ${this.name} requires environment variable ${name}`);
+ return [name, value];
+ }));
+ }
+
+ toClaudeSdkConfig(_context: McpProviderContext): unknown {
+ const env = this.environment();
+ const headers = Object.fromEntries(Object.entries(this.config.headerEnvVars ?? {}).map(([header, envName]) => [header, env[envName]!])) as Record<string, string>;
+ if (this.config.bearerTokenEnvVar && !Object.keys(headers).some((header) => header.toLowerCase() === 'authorization')) headers.Authorization = `Bearer ${env[this.config.bearerTokenEnvVar]}`;
+ return { type: 'http', url: this.config.url, ...(Object.keys(headers).length ? { headers } : {}) };
+ }
+
+ toCodexMcpConfig(_context: McpProviderContext) {
+ return {
+ type: 'http' as const,
+ url: new URL(this.config.url).href.replace(/\\/g, '%5C'),
+ ...(this.config.bearerTokenEnvVar ? { bearerTokenEnvVar: this.config.bearerTokenEnvVar } : {}),
+ ...(this.config.headerEnvVars && Object.keys(this.config.headerEnvVars).length ? { envHttpHeaders: this.config.headerEnvVars } : {}),
+ };
+ }
+
+ getExtraEnv(_context: McpProviderContext): Record<string, string> {
+ return this.environment();
+ }
+}
+
+export function resolveNativeProviders(profile: HeadlessProfile): PiNativeProvidersResult {
+ const providers = (profile.nativeProviders ?? []).map((provider) => ({ ...provider }));
+ const env: Record<string, string> = {};
+ for (const provider of providers) {
+ if (!provider.apiKeyEnvVar) continue;
+ const value = process.env[provider.apiKeyEnvVar];
+ if (!value) throw new Error(`native provider ${provider.id} requires environment variable ${provider.apiKeyEnvVar}`);
+ env[provider.apiKeyEnvVar] = value;
+ }
+ return { providers, env };
+}
+
+async function hashTree(entryPath: string, root: string, hash: ReturnType<typeof createHash>): Promise<void> {
+ const metadata = await lstat(entryPath);
+ if (metadata.isSymbolicLink()) throw new Error(`Pi skill tree contains a symbolic link: ${entryPath}`);
+ const relative = path.relative(root, entryPath).replaceAll('\\', '/');
+ if (metadata.isFile()) {
+ hash.update(`f\0${relative}\0`);
+ hash.update(await readFile(entryPath));
+ return;
+ }
+ if (!metadata.isDirectory()) throw new Error(`Pi skill tree contains a special file: ${entryPath}`);
+ hash.update(`d\0${relative}\0`);
+ const children = await readdir(entryPath);
+ children.sort();
+ for (const child of children) await hashTree(path.join(entryPath, child), root, hash);
+}
+
+export async function resolvePiProjectTrust(
+ workingDir: string,
+ config: NonNullable<HeadlessProfile['piProjectSkills']>,
+): Promise<PiProjectTrustInputSnapshot | null> {
+ if (!config.enabled) return null;
+ const canonicalWorkingDir = await realpath(workingDir);
+ const { stdout } = await execFileAsync('git', ['-C', canonicalWorkingDir, 'rev-parse', '--show-toplevel'], { timeout: 10_000 });
+ const canonicalRepoRoot = await realpath(stdout.trim());
+ if (!isWithin(canonicalRepoRoot, canonicalWorkingDir)) throw new Error('Pi project working directory is outside its Git root');
+ const skills: string[] = [];
+ const configuredRoots: string[] = [];
+ for (const relativeRoot of config.roots) {
+ const normalizedRoot = relativeRoot.replaceAll('\\', '/');
+ if (normalizedRoot === '.pi/skills') configuredRoots.push(path.join(canonicalWorkingDir, '.pi', 'skills'));
+ else if (normalizedRoot === '.agents/skills') {
+ let cursor = canonicalWorkingDir;
+ while (true) {
+ configuredRoots.push(path.join(cursor, '.agents', 'skills'));
+ if (path.resolve(cursor) === path.resolve(canonicalRepoRoot)) break;
+ cursor = path.dirname(cursor);
+ }
+ } else configuredRoots.push(path.resolve(canonicalRepoRoot, relativeRoot));
+ }
+ for (const rootPath of [...new Set(configuredRoots)]) {
+ let entries;
+ try { entries = await readdir(rootPath, { withFileTypes: true }); } catch { continue; }
+ for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
+ if (!entry.isDirectory() && !entry.isFile()) throw new Error(`Pi skill root contains a non-regular entry: ${entry.name}`);
+ const candidate = await realpath(path.join(rootPath, entry.name));
+ if (!isWithin(canonicalRepoRoot, candidate)) throw new Error(`Pi skill escapes repository: ${candidate}`);
+ if (entry.isDirectory()) {
+ const marker = await fileOrNull(path.join(candidate, 'SKILL.md'))
+ ?? await fileOrNull(path.join(candidate, 'skill.md'));
+ if (!marker) continue;
+ if (!isWithin(canonicalRepoRoot, marker)) throw new Error(`Pi skill marker escapes repository: ${marker}`);
+ } else if (!entry.name.toLowerCase().endsWith('.md')) continue;
+ skills.push(candidate);
+ }
+ }
+ const revisionHash = createHash('sha256');
+ for (const skill of skills) {
+ revisionHash.update(`skill\0${path.relative(canonicalRepoRoot, skill).replaceAll('\\', '/')}\0`);
+ await hashTree(skill, skill, revisionHash);
+ }
+ const revision = revisionHash.digest('hex');
+ const platform = process.platform === 'win32' ? 'win32' as const : 'posix' as const;
+ const identity = {
+ workingDir: path.resolve(workingDir),
+ canonicalWorkingDir,
+ canonicalRepoRoot,
+ repoRootStatus: 'resolved' as const,
+ platform,
+ canonicalPathEncoding: platform === 'win32' ? 'utf16-lossless' as const : 'utf8-lossless' as const,
+ ...(platform === 'win32' ? { windowsCaseComparison: 'ordinal-insensitive' as const } : {}),
+ };
+ return {
+ identity,
+ approval: { status: 'approved', scope: 'working-dir', scopeKey: `${canonicalRepoRoot}\0${canonicalWorkingDir}`, revision: `headless-profile:${revision}` },
+ discovered: {
+ skills,
+ canonicalSkillEvidence: skills.map((skill) => ({ discoveredPath: skill, canonicalPath: skill })),
+ settings: [],
+ packages: [],
+ extensions: [],
+ },
+ };
+}
+
+/**
+ * Pi project resources that a local root task loads in place.
+ *
+ * Cindy `05d5e4209` (Pi 0.85.x) makes every local root task hand the workspace's
+ * own Skill folders, prompt templates and extensions to Pi as explicit CLI paths
+ * (`packages/maker-core/src/agents/pi/project-resource-cli.ts`), so
+ * `--no-approve` alone no longer keeps them out of the runtime. Headless keeps
+ * the approved-Skill contract of its frozen profiles by denying every Skill the
+ * profile did not approve, and records the remaining resources in the artifact
+ * because no profile field can freeze them yet.
+ *
+ * Collection mirrors the upstream rules: non-dot Skill folders that contain
+ * `SKILL.md` or `skill.md`, `.agents/skills` from the working directory up to the
+ * Git root, `.pi/prompts/*.md`, and `.pi/extensions/<file>.ts` or
+ * `<folder>/index.ts`. Every candidate must resolve inside the Git root.
+ */
+export interface PiProjectWorkspaceResources {
+ readonly canonicalWorkingDir: string;
+ readonly canonicalRepoRoot: string;
+ readonly skills: readonly string[];
+ readonly promptTemplates: readonly string[];
+ readonly extensions: readonly string[];
+}
+
+async function realpathOrNull(target: string): Promise<string | null> {
+ try { return await realpath(target); } catch { return null; }
+}
+
+async function directoryOrNull(target: string): Promise<string | null> {
+ const canonical = await realpathOrNull(target);
+ if (!canonical) return null;
+ try { return (await stat(canonical)).isDirectory() ? canonical : null; } catch { return null; }
+}
+
+async function fileOrNull(target: string): Promise<string | null> {
+ const canonical = await realpathOrNull(target);
+ if (!canonical) return null;
+ try { return (await stat(canonical)).isFile() ? canonical : null; } catch { return null; }
+}
+
+async function findNearestGitRoot(start: string): Promise<string | null> {
+ let current = start;
+ while (true) {
+ let markerFound = false;
+ try {
+ const marker = await stat(path.join(current, '.git'));
+ markerFound = marker.isDirectory() || marker.isFile();
+ } catch (error) {
+ const code = (error as NodeJS.ErrnoException).code;
+ // Mirrors maker-core: anything other than a clean miss stays fail-closed.
+ markerFound = code !== 'ENOENT' && code !== 'ENOTDIR';
+ }
+ if (markerFound) return current;
+ const parent = path.dirname(current);
+ if (parent === current) return null;
+ current = parent;
+ }
+}
+
+async function collectSkillDirs(repoRoot: string, skillsDir: string, bucket: Set<string>): Promise<void> {
+ const resolvedDir = await directoryOrNull(skillsDir);
+ if (!resolvedDir || !isWithin(repoRoot, resolvedDir)) return;
+ const entries = await readdir(resolvedDir, { withFileTypes: true }).catch(() => []);
+ for (const entry of entries) {
+ if (entry.name.startsWith('.')) continue;
+ const realFolder = await directoryOrNull(path.join(resolvedDir, entry.name));
+ if (!realFolder || !isWithin(repoRoot, realFolder)) continue;
+ const upper = await fileOrNull(path.join(realFolder, 'SKILL.md'));
+ const marker = upper ?? await fileOrNull(path.join(realFolder, 'skill.md'));
+ if (!marker || !isWithin(repoRoot, marker)) continue;
+ bucket.add(realFolder);
+ }
+}
+
+export async function inspectPiProjectWorkspaceResources(workingDir: string): Promise<PiProjectWorkspaceResources> {
+ const canonicalWorkingDir = await realpathOrNull(path.resolve(workingDir)) ?? path.resolve(workingDir);
+ const canonicalRepoRoot = await findNearestGitRoot(canonicalWorkingDir) ?? canonicalWorkingDir;
+ const skills = new Set<string>();
+ await collectSkillDirs(canonicalRepoRoot, path.join(canonicalWorkingDir, '.pi', 'skills'), skills);
+ let cursor = canonicalWorkingDir;
+ while (true) {
+ await collectSkillDirs(canonicalRepoRoot, path.join(cursor, '.agents', 'skills'), skills);
+ if (cursor === canonicalRepoRoot) break;
+ const parent = path.dirname(cursor);
+ if (parent === cursor) break;
+ cursor = parent;
+ }
+
+ const promptTemplates = new Set<string>();
+ const promptsDir = await directoryOrNull(path.join(canonicalWorkingDir, '.pi', 'prompts'));
+ if (promptsDir && isWithin(canonicalRepoRoot, promptsDir)) {
+ const entries = await readdir(promptsDir, { withFileTypes: true }).catch(() => []);
+ for (const entry of entries) {
+ if (entry.name.startsWith('.') || !entry.name.endsWith('.md')) continue;
+ const candidate = await fileOrNull(path.join(promptsDir, entry.name));
+ if (candidate && isWithin(canonicalRepoRoot, candidate)) promptTemplates.add(candidate);
+ }
+ }
+
+ const extensions = new Set<string>();
+ const extensionsDir = await directoryOrNull(path.join(canonicalWorkingDir, '.pi', 'extensions'));
+ if (extensionsDir && isWithin(canonicalRepoRoot, extensionsDir)) {
+ const entries = await readdir(extensionsDir, { withFileTypes: true }).catch(() => []);
+ for (const entry of entries) {
+ if (entry.name.startsWith('.')) continue;
+ const candidate = await realpathOrNull(path.join(extensionsDir, entry.name));
+ if (!candidate || !isWithin(canonicalRepoRoot, candidate)) continue;
+ const index = await fileOrNull(path.join(candidate, 'index.ts'));
+ if (index && isWithin(canonicalRepoRoot, index)) { extensions.add(index); continue; }
+ if (candidate.endsWith('.ts') && await fileOrNull(candidate)) extensions.add(candidate);
+ }
+ }
+
+ return Object.freeze({
+ canonicalWorkingDir,
+ canonicalRepoRoot,
+ skills: Object.freeze([...skills].sort()),
+ promptTemplates: Object.freeze([...promptTemplates].sort()),
+ extensions: Object.freeze([...extensions].sort()),
+ });
+}
+
+/** Windows resolves the same project path under several letter cases. */
+function canonicalResourceKey(target: string): string {
+ const resolved = path.resolve(target);
+ return process.platform === 'win32' ? resolved.toLowerCase() : resolved;
+}
+
+/**
+ * Skills Pi would load in place that this profile did not approve.
+ *
+ * A disabled `piProjectSkills` approves nothing, so every discovered project
+ * Skill is denied instead of silently entering the runtime.
+ */
+export function piProjectSkillDenials(
+ resources: PiProjectWorkspaceResources,
+ approvedSkills: readonly string[],
+): readonly string[] {
+ const approved = new Set(approvedSkills.map(canonicalResourceKey));
+ return Object.freeze(resources.skills.filter((skill) => !approved.has(canonicalResourceKey(skill))));
+}
+
+export interface PiProjectResourcesEvidence {
+ /** Local root tasks load project resources from the workspace instead of a staged copy. */
+ readonly inPlace: true;
+ /** The profile's approved Skill roots remain the only Skills Pi may load. */
+ readonly approvedSkillRootsEnforced: true;
+ readonly presentSkills: readonly string[];
+ readonly deniedSkills: readonly string[];
+ readonly promptTemplates: readonly string[];
+ readonly extensions: readonly string[];
+}
+
+/** Repo-root-relative evidence so reviewers can see what the runtime actually received. */
+export function piProjectResourcesEvidence(
+ resources: PiProjectWorkspaceResources | null,
+ deniedSkills: readonly string[],
+): PiProjectResourcesEvidence | null {
+ if (!resources) return null;
+ const relative = (target: string) => path.relative(resources.canonicalRepoRoot, target).replaceAll('\\', '/');
+ return Object.freeze({
+ inPlace: true as const,
+ approvedSkillRootsEnforced: true as const,
+ presentSkills: Object.freeze(resources.skills.map(relative)),
+ deniedSkills: Object.freeze([...deniedSkills].map(relative)),
+ promptTemplates: Object.freeze(resources.promptTemplates.map(relative)),
+ extensions: Object.freeze(resources.extensions.map(relative)),
+ });
+}
diff --git a/apps/cindy-headless/src/host.test.ts b/apps/cindy-headless/src/host.test.ts
new file mode 100644
index 0000000000..d75be6435c
--- /dev/null
+++ b/apps/cindy-headless/src/host.test.ts
@@ -0,0 +1,173 @@
+import path from 'node:path';
+import { describe, expect, it } from 'vitest';
+import { classifyFailure, isHeadlessTerminalEvent, codexMcpArgs, deriveTurnStallMs, extractProviderUsage, modelCapabilityAdditions, normalizeTraceEvents, piProjectSkillsEvidence } from './host.js';
+import { HeadlessRemoteMcpProvider } from './headless-integrations.js';
+import type { HeadlessProfile } from './profile.js';
+
+describe('Headless result classification', () => {
+ it('derives a watchdog below the outer deadline', () => {
+ expect(deriveTurnStallMs(5_000_000)).toBe(4_000_000);
+ expect(deriveTurnStallMs(1_800_000)).toBe(1_440_000);
+ expect(deriveTurnStallMs(5_000)).toBe(1_000);
+ });
+
+ it('normalizes final snapshots without double-counting deltas', () => {
+ const events = normalizeTraceEvents([
+ { type: 'text', data: { text: 'hel', isFinal: false }, turnAttemptToken: 1 },
+ { type: 'text', data: { text: 'hello', isFinal: true }, turnAttemptToken: 1 },
+ { type: 'done', data: {}, turnAttemptToken: 1 },
+ ]);
+ expect(events).toHaveLength(2);
+ expect(events[0].data).toMatchObject({ text: 'hello', isFinal: true });
+ });
+
+ it('classifies a terminal-free successful turn as completed', () => {
+ expect(classifyFailure(undefined, undefined, false)).toBe('valid-completed');
+ });
+
+ it('keeps deadline and authentication failures distinct', () => {
+ expect(classifyFailure('HEADLESS_DEADLINE_EXCEEDED', undefined, true)).toBe('valid-deadline-killed');
+ expect(classifyFailure('401 unauthorized', undefined, false)).toBe('infra-invalid-auth');
+ expect(classifyFailure('stream disconnected before completion', undefined, false)).toBe('infra-invalid-provider');
+ expect(classifyFailure('Claude Code native binary not found at /opt/cindy-headless/bin/claude', undefined, false)).toBe('infra-agent-setup');
+ expect(classifyFailure("Input tag 'document' does not match expected tags", undefined, false)).toBe('infra-invalid-request');
+ expect(classifyFailure('Connection closed mid-response', undefined, false)).toBe('infra-invalid-provider');
+ expect(classifyFailure('sdk_stream_crashed: upstream ended', undefined, false)).toBe('infra-invalid-provider');
+ expect(classifyFailure('HTTP 502 from gateway', undefined, false)).toBe('infra-invalid-provider');
+ expect(classifyFailure('killed by signal SIGKILL', undefined, false)).toBe('infra-invalid-provider');
+ expect(classifyFailure('HEADLESS_TERMINATED_SIGTERM', undefined, false)).toBe('infra-terminated-signal');
+ });
+
+ it('normalizes provider usage without double-counting cache tokens', () => {
+ const usage = extractProviderUsage([{ type: 'done', data: { usage: { input_tokens: 3, cache_read_input_tokens: 10, cache_creation_input_tokens: 5, output_tokens: 7 }, total_cost_usd: 0.25, modelUsageCumulativeStartsAtZero: true } }]);
+ expect(usage.normalizedUsage).toEqual({ inputTokens: 3, cacheReadTokens: 10, cacheCreationTokens: 5, outputTokens: 7, costUsd: 0.25 });
+ });
+
+ it('derives and aggregates Claude multi-turn usage from cumulative snapshots', () => {
+ const usage = extractProviderUsage([
+ { type: 'done', turnAttemptToken: 1, data: { usage: { input_tokens: 3, cache_read_input_tokens: 10, cache_creation_input_tokens: 5, output_tokens: 7 }, total_cost_usd: 0.25, modelUsageCumulativeStartsAtZero: true } },
+ { type: 'done', turnAttemptToken: 2, data: { usage: { input_tokens: 8, cache_read_input_tokens: 21, cache_creation_input_tokens: 7, output_tokens: 16 }, total_cost_usd: 0.6, modelUsageCumulativeStartsAtZero: true } },
+ ]);
+ expect(usage.normalizedUsage).toEqual({ inputTokens: 8, cacheReadTokens: 21, cacheCreationTokens: 7, outputTokens: 16, costUsd: 0.6 });
+ expect(usage.rawProviderUsage).toMatchObject({ aggregation: 'cumulative-delta', turns: [{ turnAttemptToken: 1 }, { turnAttemptToken: 2 }] });
+ expect(usage.usageComplete).toBe(true);
+ });
+
+ it('prefers complete Claude request segments when a resumed cumulative baseline is unknown', () => {
+ const usage = extractProviderUsage([{ type: 'done', data: {
+ usage: { input_tokens: 1003, cache_read_input_tokens: 2010, cache_creation_input_tokens: 305, output_tokens: 407 },
+ usageSegments: [{ inputTokens: 3, cacheReadTokens: 10, cacheCreateTokens: 5, outputTokens: 7 }],
+ usageSegmentsComplete: true,
+ modelUsageCumulativeStartsAtZero: false,
+ total_cost_usd: 1.25,
+ } }]);
+ expect(usage.normalizedUsage).toEqual({ inputTokens: 3, cacheReadTokens: 10, cacheCreationTokens: 5, outputTokens: 7, costUsd: 0 });
+ expect(usage.usageComplete).toBe(false);
+ });
+
+ it('reconstructs current Claude usage from request metadata and terminal status', () => {
+ const usage = extractProviderUsage([
+ { type: 'thinking', data: {}, agentMeta: { requestId: 'request-1', usage: { inputTokens: 2, outputTokens: 0, cacheReadInputTokens: 0, cacheCreationInputTokens: 33054 } } },
+ { type: 'text', data: {}, agentMeta: { requestId: 'request-1', usage: { inputTokens: 2, outputTokens: 0, cacheReadInputTokens: 0, cacheCreationInputTokens: 33054 } } },
+ { type: 'text', data: {}, agentMeta: { requestId: 'request-2', usage: { inputTokens: 1, outputTokens: 1, cacheReadInputTokens: 33054, cacheCreationInputTokens: 163 } } },
+ { type: 'status', data: { status: 'Done', tokenUsage: 151, contextTokens: 33218, contextWindow: 1_000_000, costUsd: 0.138, isRunning: false } },
+ ]);
+ expect(usage.normalizedUsage).toEqual({ inputTokens: 3, cacheReadTokens: 33054, cacheCreationTokens: 33217, outputTokens: 148, costUsd: 0.138 });
+ expect(usage.rawProviderUsage).toMatchObject({ reconstructed_from: 'agentMeta+terminalStatus' });
+ });
+
+ it('normalizes Codex per-turn usage', () => {
+ const usage = extractProviderUsage([{ type: 'done', data: { usage: { promptTokens: 11, cachedTokens: 13, completionTokens: 17, reasoningTokens: 5 } } }], 'codex');
+ expect(usage.normalizedUsage).toEqual({ inputTokens: 11, cacheReadTokens: 13, cacheCreationTokens: 0, outputTokens: 17, costUsd: 0 });
+ });
+
+ it('aggregates Codex multi-turn usage including cache tokens', () => {
+ const usage = extractProviderUsage([
+ { type: 'done', turnAttemptToken: 1, data: { usage: { promptTokens: 11, cachedTokens: 13, completionTokens: 17, reasoningTokens: 5 } } },
+ { type: 'done', turnAttemptToken: 2, data: { usage: { promptTokens: 19, cachedTokens: 23, completionTokens: 29, reasoningTokens: 7 } } },
+ ], 'codex');
+ expect(usage.normalizedUsage).toEqual({ inputTokens: 30, cacheReadTokens: 36, cacheCreationTokens: 0, outputTokens: 46, costUsd: 0 });
+ expect(usage.rawProviderUsage).toMatchObject({ aggregation: 'per-turn', turns: [{ turnAttemptToken: 1 }, { turnAttemptToken: 2 }] });
+ });
+
+ it('normalizes Pi per-turn usage and cost', () => {
+ const usage = extractProviderUsage([{ type: 'done', data: { usage: { inputTokens: 11, cacheReadTokens: 13, cacheCreationTokens: 2, outputTokens: 17 }, totalCostUsd: 0.42 } }], 'pi');
+ expect(usage.normalizedUsage).toEqual({ inputTokens: 11, cacheReadTokens: 13, cacheCreationTokens: 2, outputTokens: 17, costUsd: 0.42 });
+ });
+
+ it('aggregates Pi multi-turn usage, cache, and cost', () => {
+ const usage = extractProviderUsage([
+ { type: 'done', turnAttemptToken: 1, data: { usage: { inputTokens: 11, cacheReadTokens: 13, cacheCreationTokens: 2, outputTokens: 17, segments: [{ costUsd: 0.42 }] } } },
+ { type: 'done', turnAttemptToken: 2, data: { usage: { inputTokens: 19, cacheReadTokens: 23, cacheCreationTokens: 3, outputTokens: 29, segments: [{ costUsd: 0.58 }] } } },
+ ], 'pi');
+ expect(usage.normalizedUsage).toEqual({ inputTokens: 30, cacheReadTokens: 36, cacheCreationTokens: 5, outputTokens: 46, costUsd: 1 });
+ expect(usage.rawProviderUsage).toMatchObject({ aggregation: 'per-turn', turns: [{ turnAttemptToken: 1 }, { turnAttemptToken: 2 }] });
+ });
+
+ it('injects an explicit context limit and preserves the agent default when omitted', () => {
+ const profile = {
+ model: { provider: 'moonshot', requestedId: 'moonshot/kimi-k3', contextLimit: 1_048_576, effort: 'high' },
+ } as HeadlessProfile;
+ expect(modelCapabilityAdditions(profile)?.availableModels[0]).toMatchObject({
+ id: 'moonshot/kimi-k3',
+ contextWindow: 1_048_576,
+ efforts: ['high'],
+ defaultEffort: 'high',
+ });
+ expect(modelCapabilityAdditions({ ...profile, model: { ...profile.model, contextLimit: undefined } })).toBeUndefined();
+ });
+
+ it('projects deterministic Pi project Skills evidence into artifacts', () => {
+ expect(piProjectSkillsEvidence(null)).toEqual({ revision: null, count: 0, discoveredSkills: [] });
+ const repo = path.resolve('fixture-repo');
+ expect(piProjectSkillsEvidence({
+ identity: { canonicalRepoRoot: repo },
+ approval: { revision: 'headless-profile:abc123' },
+ discovered: { skills: [path.join(repo, '.pi', 'skills', 'review'), path.join(repo, '.agents', 'skills', 'test.md')] },
+ } as never)).toEqual({
+ revision: 'headless-profile:abc123',
+ count: 2,
+ discoveredSkills: ['.pi/skills/review', '.agents/skills/test.md'],
+ });
+ });
+
+ it('serializes custom Codex MCP headers as secret environment references', () => {
+ process.env.TEST_MCP_TOKEN = 'secret';
+ process.env.TEST_MCP_HEADER = 'header-secret';
+ try {
+ const provider = new HeadlessRemoteMcpProvider({ id: 'docs', transport: 'http', url: 'https://mcp.example.test', bearerTokenEnvVar: 'TEST_MCP_TOKEN', headerEnvVars: { 'X-Api.Key': 'TEST_MCP_HEADER' } });
+ const config = codexMcpArgs([provider], '/workspace');
+ expect(config.extraArgs).toContain('mcp_servers.docs.env_http_headers."X-Api.Key"="TEST_MCP_HEADER"');
+ expect(config.extraArgs.join(' ')).not.toContain('secret');
+ expect(config.extraEnv).toMatchObject({ TEST_MCP_TOKEN: 'secret', TEST_MCP_HEADER: 'header-secret' });
+ } finally {
+ delete process.env.TEST_MCP_TOKEN;
+ delete process.env.TEST_MCP_HEADER;
+ }
+ });
+});
+
+
+describe('Headless product-turn completion', () => {
+ it('waits across SDK done, idle and cancelled claims until the product terminal', () => {
+ let kind: 'none' | 'done' | 'error' = 'none';
+ const session = { getObservedCurrentTurnTerminal: () => ({ kind }) };
+ const event = { type: 'done' as const, data: {}, turnAttemptToken: 1, turnContinuationId: 7 };
+ expect(isHeadlessTerminalEvent(event, session, 1)).toBe(false);
+ expect(isHeadlessTerminalEvent({ type: 'status', data: { isRunning: false }, turnAttemptToken: 1 }, session, 1)).toBe(false);
+ // Even a cancelled claim keeps its SDK boundary nonterminal until Core's ordered terminal.
+ expect(isHeadlessTerminalEvent(event, session, 1)).toBe(false);
+ kind = 'done';
+ expect(isHeadlessTerminalEvent({ type: 'done', data: {}, turnAttemptToken: 1 }, session, 1)).toBe(true);
+ });
+ it('ignores background and old-turn terminals, and distinguishes retrying errors', () => {
+ const done = { getObservedCurrentTurnTerminal: () => ({ kind: 'done' as const }) };
+ expect(isHeadlessTerminalEvent({ type: 'done', data: {}, turnScope: 'background' }, done, 2)).toBe(false);
+ expect(isHeadlessTerminalEvent({ type: 'done', data: {}, turnAttemptToken: 1 }, done, 2)).toBe(false);
+ expect(isHeadlessTerminalEvent({ type: 'status', data: { isRunning: false } }, done, 2)).toBe(false);
+ expect(isHeadlessTerminalEvent({ type: 'done', data: {} }, done, undefined)).toBe(false);
+ const error = { getObservedCurrentTurnTerminal: () => ({ kind: 'error' as const }) };
+ expect(isHeadlessTerminalEvent({ type: 'error', data: { willRetry: true }, turnAttemptToken: 2 }, error, 2)).toBe(false);
+ expect(isHeadlessTerminalEvent({ type: 'error', data: { isTerminal: true }, turnAttemptToken: 2 }, error, 2)).toBe(true);
+ });
+});
diff --git a/apps/cindy-headless/src/host.ts b/apps/cindy-headless/src/host.ts
new file mode 100644
index 0000000000..36d7cba91e
--- /dev/null
+++ b/apps/cindy-headless/src/host.ts
@@ -0,0 +1,665 @@
+import { access, appendFile, mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import { createMemoryMcpProvider } from './memory-provider.js';
+import { ClaudeCodeAgent, CodexAgent, PiAgent, Maker, MakerMemoryManager, isTerminalTurnEvent, type AgentEvent, type AgentKind, type AgentRuntimeConfig, type AuthAdapter, type BaseAgent, type Logger, type McpProvider, type UserMessage } from '@cindy/maker-core';
+import { startCodexMemoryBridge, type CodexMemoryBridge } from './codex-memory-bridge.js';
+import { sha256, type HeadlessProfile, type ResolvedProfile } from './profile.js';
+import { readProjectContext } from './project-context.js';
+import { openHeadlessSqlite } from './sqlite.js';
+import { createUsageArtifact, type NormalizedUsage } from './usage.js';
+import { SqliteSessionStorage } from './session-storage.js';
+import { assertSafeExecutionProfile, CINDY_HEADLESS_VERSION, CINDY_UPSTREAM_COMMIT } from './compatibility.js';
+import { buildCodexGatewayArgs } from './gateway-config.js';
+import { HeadlessRemoteMcpProvider, inspectPiProjectWorkspaceResources, piProjectResourcesEvidence, piProjectSkillDenials, resolveNativeProviders, resolvePiProjectTrust, resolveTurns, type HeadlessTurnInput, type PiProjectWorkspaceResources } from './headless-integrations.js';
+
+/** Use Session's product-turn boundary, not an intermediate SDK done/idle. */
+export function isHeadlessTerminalEvent(
+ event: AgentEvent,
+ session: { getObservedCurrentTurnTerminal(): { kind: 'none' | 'done' | 'error' } },
+ turnAttemptToken: number | undefined,
+): boolean {
+ if (turnAttemptToken === undefined || event.turnScope === 'background') return false;
+ // Session tags the current foreground attempt; untagged tails may belong to the previous turn.
+ if (event.turnAttemptToken !== turnAttemptToken) return false;
+ return isTerminalTurnEvent(event) && session.getObservedCurrentTurnTerminal().kind !== 'none';
+}
+
+let environmentQueue = Promise.resolve();
+
+const MIN_TURN_STALL_MS = 1_000;
+const HEADLESS_CLEANUP_RESERVE_MS = 10_000;
+
+export function deriveTurnStallMs(timeoutMs: number): number {
+ const beforeDeadline = Math.max(MIN_TURN_STALL_MS, timeoutMs - HEADLESS_CLEANUP_RESERVE_MS);
+ return Math.min(beforeDeadline, Math.max(MIN_TURN_STALL_MS, Math.floor(timeoutMs * 0.8)));
+}
+
+function eventData(event: AgentEvent): Record<string, unknown> | undefined {
+ return event.data && typeof event.data === 'object' && !Array.isArray(event.data)
+ ? event.data as Record<string, unknown>
+ : undefined;
+}
+
+export function normalizeTraceEvents(events: AgentEvent[]): AgentEvent[] {
+ const output: Array<AgentEvent | undefined> = [];
+ const deltas = new Map<string, number[]>();
+ let fallbackTurn = 0;
+
+ for (const event of events) {
+ if (event.type === 'done' || (event.type === 'error' && isTerminalTurnEvent(event))) {
+ fallbackTurn += 1;
+ }
+ if (event.type !== 'text' && event.type !== 'thinking') {
+ output.push(event);
+ continue;
+ }
+ const data = eventData(event);
+ const turn = event.turnAttemptToken ?? fallbackTurn;
+ const key = `${turn}:${event.type}`;
+ if (data?.isFinal === true) {
+ for (const index of deltas.get(key) ?? []) output[index] = undefined;
+ deltas.delete(key);
+ output.push(event);
+ continue;
+ }
+ const index = output.push(event) - 1;
+ const indexes = deltas.get(key) ?? [];
+ indexes.push(index);
+ deltas.set(key, indexes);
+ }
+ return output.filter((event): event is AgentEvent => event !== undefined);
+}
+
+async function acquireEnvironmentLease(): Promise<() => void> {
+ let release!: () => void;
+ const previous = environmentQueue;
+ environmentQueue = new Promise<void>((resolve) => { release = resolve; });
+ await previous;
+ return release;
+}
+
+function claudeAuth(): AuthAdapter {
+ return { async getState() { const key = process.env.CINDY_HEADLESS_API_KEY ?? process.env.ANTHROPIC_API_KEY; return { authenticated: Boolean(key), authSource: key ? 'api-key' : undefined }; }, async triggerLogin() { return this.getState(); }, async logout() {}, async getAuthEnv(): Promise<Record<string, string>> { const key = process.env.CINDY_HEADLESS_API_KEY ?? process.env.ANTHROPIC_API_KEY; return key ? { ANTHROPIC_API_KEY: key } : {}; } };
+}
+
+function codexAuth(stateDir: string): AuthAdapter {
+ const configuredHome = process.env.CINDY_HEADLESS_CODEX_HOME ?? process.env.CODEX_HOME;
+ const apiKey = process.env.CINDY_CODEX_API_KEY;
+ const codexHome = configuredHome ? path.resolve(configuredHome) : path.resolve(stateDir);
+ return {
+ async getState() { return { authenticated: Boolean(apiKey || configuredHome), authSource: apiKey ? 'api-key' : configuredHome ? 'oauth' : undefined, errorReason: apiKey || configuredHome ? undefined : 'missing_codex_home_or_api_key' }; },
+ async triggerLogin() { return this.getState(); },
+ async logout() {},
+ async getAuthEnv(): Promise<Record<string, string>> { return { CODEX_HOME: codexHome, ...(apiKey ? { CINDY_CODEX_API_KEY: apiKey } : {}) }; },
+ };
+}
+
+function piAuth(profile: HeadlessProfile): AuthAdapter {
+ return {
+ async getState() { const key = process.env.CINDY_HEADLESS_API_KEY ?? process.env.ANTHROPIC_API_KEY ?? profile.nativeProviders?.map((provider) => provider.apiKeyEnvVar && process.env[provider.apiKeyEnvVar]).find(Boolean) ?? (profile.nativeProviders?.some((provider) => !provider.apiKeyEnvVar) ? 'keyless-native-provider' : undefined); return { authenticated: Boolean(key), authSource: key ? 'api-key' : undefined }; },
+ async triggerLogin() { return this.getState(); },
+ async logout() {},
+ async getAuthEnv(): Promise<Record<string, string>> { const key = process.env.CINDY_HEADLESS_API_KEY ?? process.env.ANTHROPIC_API_KEY; return key ? { CINDY_PI_API_KEY: key } : { CINDY_PI_API_KEY: 'headless-native-provider' }; },
+ };
+}
+
+function jsonLogger(): Logger {
+ const write = (level: string, message: string, context?: Record<string, unknown>) => process.stderr.write(`${JSON.stringify({ level, message, ...context })}\n`);
+ const result: Logger = { trace: (m, c) => write('trace', m, c), debug: (m, c) => write('debug', m, c), info: (m, c) => write('info', m, c), warn: (m, c) => write('warn', m, c), error: (m, c) => write('error', m, c), fatal: (m, c) => write('fatal', m, c), child: () => result };
+ return result;
+}
+
+export function modelCapabilityAdditions(profile: HeadlessProfile) {
+ return profile.model.contextLimit
+ ? {
+ availableModels: [{
+ id: profile.model.requestedId,
+ displayName: profile.model.requestedId,
+ contextWindow: profile.model.contextLimit,
+ efforts: profile.model.effort ? [profile.model.effort] : [],
+ defaultEffort: profile.model.effort ?? null,
+ maxOutputTokens: profile.model.maxOutputTokens,
+ }],
+ }
+ : undefined;
+}
+
+export function codexMcpArgs(providers: McpProvider[], workingDir: string): { extraArgs: string[]; extraEnv: Record<string, string> } {
+ const context = { agentKind: 'codex' as const, workingDir, vendorOptions: {} };
+ const extraArgs: string[] = providers.length ? ['-c', 'mcp_servers={}'] : [];
+ const extraEnv: Record<string, string> = {};
+ for (const provider of providers) {
+ const config = provider.toCodexMcpConfig?.(context);
+ if (!config) continue;
+ Object.assign(extraEnv, provider.getExtraEnv?.(context) ?? {});
+ extraArgs.push('-c', `mcp_servers.${provider.name}.url=${JSON.stringify(config.url)}`);
+ if (config.bearerTokenEnvVar) extraArgs.push('-c', `mcp_servers.${provider.name}.bearer_token_env_var=${JSON.stringify(config.bearerTokenEnvVar)}`);
+ for (const [header, envName] of Object.entries(config.envHttpHeaders ?? {})) {
+ extraArgs.push('-c', `mcp_servers.${provider.name}.env_http_headers.${JSON.stringify(header)}=${JSON.stringify(envName)}`);
+ }
+ extraArgs.push('-c', `mcp_servers.${provider.name}.startup_timeout_sec=600`, '-c', `mcp_servers.${provider.name}.tool_timeout_sec=600`);
+ }
+ return { extraArgs, extraEnv };
+}
+
+function piRemoteMcpConfig(profile: HeadlessProfile) {
+ const servers: Array<{ name: string; url: string; remote: { headerEnvVars: Record<string, string>; startupTimeoutMs: number; requestTimeoutMs: number } }> = [];
+ const env: Record<string, string> = {};
+ for (const server of profile.mcpServers ?? []) {
+ const headerEnvVars = { ...(server.headerEnvVars ?? {}) };
+ if (server.bearerTokenEnvVar && !Object.keys(headerEnvVars).some((header) => header.toLowerCase() === 'authorization')) headerEnvVars.Authorization = server.bearerTokenEnvVar;
+ for (const [header, envName] of Object.entries(headerEnvVars)) {
+ const raw = process.env[envName];
+ if (!raw) throw new Error(`custom MCP ${server.id} requires environment variable ${envName}`);
+ env[envName] = header.toLowerCase() === 'authorization' && server.bearerTokenEnvVar === envName ? `Bearer ${raw}` : raw;
+ }
+ servers.push({ name: server.id, url: server.url, remote: { headerEnvVars, startupTimeoutMs: server.startupTimeoutMs ?? 10_000, requestTimeoutMs: server.requestTimeoutMs ?? 600_000 } });
+ }
+ return { servers, env };
+}
+
+type PiProjectTrustSnapshot = Awaited<ReturnType<typeof resolvePiProjectTrust>>;
+
+export function piProjectSkillsEvidence(snapshot: PiProjectTrustSnapshot) {
+ const canonicalRepoRoot = snapshot?.identity.canonicalRepoRoot;
+ return {
+ revision: snapshot?.approval?.revision ?? null,
+ count: snapshot?.discovered.skills.length ?? 0,
+ discoveredSkills: snapshot && typeof canonicalRepoRoot === 'string'
+ ? snapshot.discovered.skills.map((skill) => path.relative(canonicalRepoRoot, skill).replaceAll('\\', '/'))
+ : [],
+ };
+}
+
+function createHeadlessMaker(resolved: ResolvedProfile, stateDir: string, workingDir: string, piProjectTrust: PiProjectTrustSnapshot, piSkillDenials: readonly string[]): { maker: Maker; makerMemory: MakerMemoryManager; sessionStorage: SqliteSessionStorage; shutdownBridge(): Promise<void> } {
+ const profile = resolved.profile;
+ const logger = jsonLogger();
+ const makerMemory = new MakerMemoryManager({
+ basePath: stateDir,
+ sqliteFactory: (filePath) => {
+ const db = openHeadlessSqlite(filePath);
+ db.pragma('journal_mode = WAL');
+ db.pragma('busy_timeout = 5000');
+ return db;
+ },
+ agents: {},
+ logger: logger.child('maker-memory'),
+ initialEnabled: profile.makerMemory,
+ reviewAgent: profile.agentBackend,
+ });
+ const behaviorFlags = { ...(profile.containerSandbox ? { IS_SANDBOX: '1' } : {}), ...(profile.agentBackend === 'claude-code' && profile.model.maxOutputTokens ? { CLAUDE_CODE_MAX_OUTPUT_TOKENS: String(profile.model.maxOutputTokens) } : {}) };
+ const compactThresholdPct = profile.compaction?.enabled ? profile.compaction.thresholdPct : undefined;
+ const runtimeConfig: AgentRuntimeConfig = {
+ endpoint: profile.endpoint,
+ systemPrompt: resolved.systemPrompt,
+ userDataPath: stateDir,
+ memoryEnabled: profile.nativeMemory,
+ makerMemoryEnabled: profile.makerMemory,
+ behaviorFlags: Object.keys(behaviorFlags).length > 0 ? behaviorFlags : undefined,
+ autoCompactThresholdPct: profile.agentBackend === 'claude-code' ? compactThresholdPct : undefined,
+ piAutoCompactThresholdPct: profile.agentBackend === 'pi' ? compactThresholdPct : undefined,
+ };
+ const memoryProvider = createMemoryMcpProvider({ getManager: () => makerMemory, logger: logger.child('cindy-memory-mcp') });
+ const memoryProviders = profile.makerMemory ? [memoryProvider] : [];
+ const remoteMcpProviders = (profile.mcpServers ?? []).map((server) => new HeadlessRemoteMcpProvider(server));
+ const mcpProviders: McpProvider[] = [...memoryProviders, ...remoteMcpProviders];
+ const capabilityAdditions = modelCapabilityAdditions(profile);
+ const resolveModelContextLimit = (_providerId: string | null | undefined, modelId: string) =>
+ profile.model.contextLimit && profile.supportedModelIds.includes(modelId) ? profile.model.contextLimit : null;
+ let bridge: CodexMemoryBridge | undefined;
+ let bridgePromise: Promise<CodexMemoryBridge> | undefined;
+ let agent: BaseAgent;
+ if (profile.agentBackend === 'claude-code') {
+ agent = new ClaudeCodeAgent({ auth: claudeAuth(), runtimeConfig, binaryPath: profile.agentBinaryPath, logger, mcpProviders, makerMemory, capabilityAdditions, resolveModelContextLimit });
+ } else if (profile.agentBackend === 'codex') {
+ agent = new CodexAgent({
+ auth: codexAuth(stateDir),
+ runtimeConfig,
+ binaryPath: profile.agentBinaryPath,
+ logger,
+ mcpProviders,
+ makerMemory,
+ capabilityAdditions,
+ resolveModelContextLimit,
+ resolveCodexThreadContextWindow: async (_providerId, modelId) => resolveModelContextLimit(_providerId, modelId),
+ prepareCodexExtraSpawnConfig: async () => {
+ let extraArgs = process.env.CINDY_CODEX_API_KEY && process.env.CINDY_HEADLESS_BASE_URL
+ ? buildCodexGatewayArgs({ baseUrl: process.env.CINDY_HEADLESS_BASE_URL, apiKey: process.env.CINDY_CODEX_API_KEY })
+ : [];
+ let extraEnv: Record<string, string> = process.env.CINDY_CODEX_API_KEY ? { CINDY_CODEX_API_KEY: process.env.CINDY_CODEX_API_KEY } : {};
+ const remote = codexMcpArgs(remoteMcpProviders, workingDir);
+ extraArgs = [...extraArgs, ...remote.extraArgs];
+ extraEnv = { ...extraEnv, ...remote.extraEnv };
+ if (memoryProviders.length > 0) {
+ bridgePromise ??= startCodexMemoryBridge({ provider: memoryProvider, workingDir, logger });
+ bridge = await bridgePromise;
+ extraArgs = [...extraArgs, ...(remoteMcpProviders.length > 0 ? bridge.extraArgs.slice(2) : bridge.extraArgs)];
+ extraEnv = { ...extraEnv, ...bridge.extraEnv };
+ }
+ return { extraArgs, extraEnv };
+ },
+ });
+ } else {
+ agent = new PiAgent({
+ auth: piAuth(profile),
+ runtimeConfig,
+ binaryPath: profile.agentBinaryPath,
+ logger,
+ mcpProviders,
+ makerMemory,
+ capabilityAdditions,
+ resolveModelContextLimit,
+ resolvePiGatewayModelApi: () => 'anthropic-messages',
+ resolvePiAgentHome: () => path.join(stateDir, 'pi-agent-home'),
+ ...(profile.nativeProviders ? { resolvePiNativeProviders: async () => resolveNativeProviders(profile) } : {}),
+ ...(profile.piProjectSkills?.enabled ? { resolvePiProjectTrustInput: async () => piProjectTrust } : {}),
+ // Pi 0.85.x loads in-repo project Skills in place for local root tasks. A
+ // profile that did not approve a Skill must still not see it.
+ ...(piSkillDenials.length > 0 ? { getDisabledSkillPaths: () => piSkillDenials } : {}),
+ preparePiExtraSpawnConfig: async () => {
+ const remote = piRemoteMcpConfig(profile);
+ if (memoryProviders.length === 0 && remote.servers.length === 0) return null;
+ if (memoryProviders.length > 0) {
+ bridgePromise ??= startCodexMemoryBridge({ provider: memoryProvider, workingDir, logger });
+ bridge = await bridgePromise;
+ }
+ return {
+ mcpBridge: { token: bridge?.token ?? '', servers: [...(bridge ? [{ name: 'cindy_memory', url: bridge.url }] : []), ...remote.servers] },
+ ...(Object.keys(remote.env).length ? { mcpEnv: remote.env } : {}),
+ disposeSessionCtx: () => undefined,
+ };
+ },
+ });
+ }
+ const agents = { [profile.agentBackend]: agent } as Record<AgentKind, BaseAgent>;
+ makerMemory.setAgents(agents);
+ const sessionStorage = new SqliteSessionStorage(path.join(stateDir, 'headless-sessions.sqlite'));
+ return {
+ maker: new Maker({ agents, storage: sessionStorage, logger, makerMemory }),
+ makerMemory,
+ sessionStorage,
+ async shutdownBridge() {
+ if (!bridge && bridgePromise) bridge = await bridgePromise.catch(() => undefined);
+ await bridge?.shutdown();
+ },
+ };
+}
+
+export function classifyFailure(error: string | undefined, terminalError: AgentEvent | undefined, deadlineKilled: boolean): string {
+ if (deadlineKilled) return 'valid-deadline-killed';
+ if (error?.startsWith('HEADLESS_TERMINATED_')) return 'infra-terminated-signal';
+ if (!error && !terminalError) return 'valid-completed';
+ const text = `${error ?? ''} ${terminalError ? JSON.stringify(terminalError.data) : ''}`.toLowerCase();
+ if (/native binary not found|executable.*not found|enoent|no such file or directory/.test(text)) return 'infra-agent-setup';
+ if (/auth|api.?key|unauthorized|401/.test(text)) return 'infra-invalid-auth';
+ if (/invalid_request_error|input tag .* does not match|unsupported content|bad request|\b4\d\d\b/.test(text)) return 'infra-invalid-request';
+ if (/model.*(not found|unsupported)|route|requested.*effective/.test(text)) return 'infra-invalid-route';
+ if (/\b5\d\d\b|rate.?limit|overload|provider|network|econn|timeout|stream disconnected|sdk[_ -]?stream[_ -]?crashed|broken pipe|connection reset|connection aborted|socket hang up|connection closed mid-response|sigkill|killed by signal/.test(text)) return 'infra-invalid-provider';
+ return 'valid-agent-error';
+}
+
+function standardResult(status: string, reward: number | null): 'PASSED' | 'FAILED_AGENT' | 'ERRORED_INFRA' | 'INVALID_TASK' | null {
+ if (status === 'valid-completed') return reward === null ? null : reward === 1 ? 'PASSED' : 'FAILED_AGENT';
+ if (status === 'valid-agent-error' || status === 'valid-deadline-killed') return 'FAILED_AGENT';
+ if (status.includes('invalid-task')) return 'INVALID_TASK';
+ return 'ERRORED_INFRA';
+}
+
+type ExtractedProviderUsage = {
+ rawProviderUsage: Record<string, unknown> | null;
+ normalizedUsage: NormalizedUsage;
+ usageComplete: boolean;
+};
+
+const EMPTY_NORMALIZED_USAGE: NormalizedUsage = {
+ inputTokens: 0,
+ cacheReadTokens: 0,
+ cacheCreationTokens: 0,
+ outputTokens: 0,
+ costUsd: 0,
+};
+
+function usageNumber(value: Record<string, unknown> | undefined | null, key: string): number {
+ const candidate = value?.[key];
+ return typeof candidate === 'number' && Number.isFinite(candidate) ? candidate : 0;
+}
+
+function sumNormalizedUsage(values: NormalizedUsage[]): NormalizedUsage {
+ return values.reduce<NormalizedUsage>((total, value) => ({
+ inputTokens: total.inputTokens + value.inputTokens,
+ cacheReadTokens: total.cacheReadTokens + value.cacheReadTokens,
+ cacheCreationTokens: total.cacheCreationTokens + value.cacheCreationTokens,
+ outputTokens: total.outputTokens + value.outputTokens,
+ costUsd: total.costUsd + value.costUsd,
+ }), { ...EMPTY_NORMALIZED_USAGE });
+}
+
+export function extractProviderUsage(events: AgentEvent[], agentBackend: AgentKind = 'claude-code'): ExtractedProviderUsage {
+ const doneRecords = events.flatMap((event, eventIndex) => {
+ if (event.type !== 'done' || !event.data || typeof event.data !== 'object') return [];
+ const data = event.data as Record<string, unknown>;
+ const usage = data.usage && typeof data.usage === 'object' ? data.usage as Record<string, unknown> : null;
+ if (!usage) return [];
+ return [{ event, eventIndex, data, usage }];
+ });
+ if (agentBackend === 'codex') {
+ if (doneRecords.length === 0) {
+ const terminal = [...events].reverse().find((event) => event.type === 'status' && event.data && typeof event.data === 'object' && typeof (event.data as Record<string, unknown>).tokenUsage === 'number');
+ const tokenUsage = terminal?.data && typeof terminal.data === 'object' ? Number((terminal.data as Record<string, unknown>).tokenUsage ?? 0) : 0;
+ return {
+ rawProviderUsage: tokenUsage > 0 ? { tokenUsage, reconstructed_from: 'terminalStatus' } : null,
+ normalizedUsage: { ...EMPTY_NORMALIZED_USAGE },
+ usageComplete: false,
+ };
+ }
+ const turns = doneRecords.map(({ event, eventIndex, usage }) => ({
+ eventIndex,
+ turnAttemptToken: event.turnAttemptToken ?? null,
+ usage,
+ }));
+ const normalizedUsage = sumNormalizedUsage(doneRecords.map(({ usage }) => ({
+ inputTokens: usageNumber(usage, 'promptTokens'),
+ cacheReadTokens: usageNumber(usage, 'cachedTokens'),
+ cacheCreationTokens: 0,
+ outputTokens: usageNumber(usage, 'completionTokens'),
+ costUsd: 0,
+ })));
+ return {
+ rawProviderUsage: { aggregation: 'per-turn', backend: agentBackend, turns, totals: normalizedUsage },
+ normalizedUsage,
+ usageComplete: true,
+ };
+ }
+ if (agentBackend === 'pi') {
+ if (doneRecords.length === 0) return { rawProviderUsage: null, normalizedUsage: { ...EMPTY_NORMALIZED_USAGE }, usageComplete: false };
+ const turns = doneRecords.map(({ event, eventIndex, data, usage }) => ({
+ eventIndex,
+ turnAttemptToken: event.turnAttemptToken ?? null,
+ usage,
+ totalCostUsd: typeof data.totalCostUsd === 'number' ? data.totalCostUsd : null,
+ }));
+ const normalizedUsage = sumNormalizedUsage(doneRecords.map(({ data, usage }) => {
+ const segments = Array.isArray(usage.segments)
+ ? usage.segments.filter((segment): segment is Record<string, unknown> => Boolean(segment) && typeof segment === 'object')
+ : [];
+ return {
+ inputTokens: usageNumber(usage, 'inputTokens'),
+ cacheReadTokens: usageNumber(usage, 'cacheReadTokens'),
+ cacheCreationTokens: usageNumber(usage, 'cacheCreationTokens'),
+ outputTokens: usageNumber(usage, 'outputTokens'),
+ costUsd: typeof data.totalCostUsd === 'number'
+ ? data.totalCostUsd
+ : segments.reduce((total, segment) => total + usageNumber(segment, 'costUsd'), 0),
+ };
+ }));
+ return {
+ rawProviderUsage: { aggregation: 'per-turn', backend: agentBackend, turns, totals: normalizedUsage },
+ normalizedUsage,
+ usageComplete: true,
+ };
+ }
+ if (doneRecords.length === 0) {
+ const byRequest = new Map<string, Record<string, unknown>>();
+ for (const event of events) {
+ const requestId = typeof event.agentMeta?.requestId === 'string' ? event.agentMeta.requestId : undefined;
+ const eventUsage = event.agentMeta?.usage;
+ if (requestId && eventUsage && typeof eventUsage === 'object') byRequest.set(requestId, eventUsage as Record<string, unknown>);
+ }
+ const sum = (key: string): number => [...byRequest.values()].reduce((total, usage) => total + (typeof usage[key] === 'number' ? usage[key] as number : 0), 0);
+ const terminal = [...events].reverse().find((event) => event.type === 'status' && event.data && typeof event.data === 'object' && (event.data as Record<string, unknown>).isRunning === false);
+ const terminalData = terminal?.data as Record<string, unknown> | undefined;
+ const inputTokens = sum('inputTokens');
+ const tokenUsage = typeof terminalData?.tokenUsage === 'number' ? terminalData.tokenUsage : inputTokens;
+ const reconstructed = {
+ input_tokens: inputTokens,
+ cache_read_input_tokens: sum('cacheReadInputTokens'),
+ cache_creation_input_tokens: sum('cacheCreationInputTokens'),
+ output_tokens: Math.max(0, tokenUsage - inputTokens),
+ reconstructed_from: 'agentMeta+terminalStatus',
+ };
+ return {
+ rawProviderUsage: reconstructed,
+ normalizedUsage: {
+ inputTokens: reconstructed.input_tokens,
+ cacheReadTokens: reconstructed.cache_read_input_tokens,
+ cacheCreationTokens: reconstructed.cache_creation_input_tokens,
+ outputTokens: reconstructed.output_tokens,
+ costUsd: typeof terminalData?.costUsd === 'number' ? terminalData.costUsd : 0,
+ },
+ usageComplete: false,
+ };
+ }
+
+ let previousUsage: Record<string, unknown> | null = null;
+ let previousCost = 0;
+ let usageComplete = true;
+ const turns = doneRecords.map(({ event, eventIndex, data, usage }) => {
+ const segments = Array.isArray(data.usageSegments) ? data.usageSegments.filter((segment): segment is Record<string, unknown> => Boolean(segment) && typeof segment === 'object') : [];
+ const segmentsComplete = data.usageSegmentsComplete === true;
+ const fromSegments = segmentsComplete && segments.length > 0 ? {
+ inputTokens: segments.reduce((total, segment) => total + usageNumber(segment, 'inputTokens'), 0),
+ cacheReadTokens: segments.reduce((total, segment) => total + usageNumber(segment, 'cacheReadTokens'), 0),
+ cacheCreationTokens: segments.reduce((total, segment) => total + usageNumber(segment, 'cacheCreateTokens'), 0),
+ outputTokens: segments.reduce((total, segment) => total + usageNumber(segment, 'outputTokens'), 0),
+ } : null;
+ const delta = (key: string): number => {
+ const current = usageNumber(usage, key);
+ const prior = usageNumber(previousUsage, key);
+ return previousUsage && current >= prior ? current - prior : current;
+ };
+ const cumulativeCost = typeof data.total_cost_usd === 'number' ? data.total_cost_usd : 0;
+ const baselineKnown = previousUsage !== null || data.modelUsageCumulativeStartsAtZero === true;
+ const costUsd = baselineKnown
+ ? previousUsage && cumulativeCost >= previousCost ? cumulativeCost - previousCost : cumulativeCost
+ : 0;
+ const normalized: NormalizedUsage = {
+ inputTokens: fromSegments?.inputTokens ?? delta('input_tokens'),
+ cacheReadTokens: fromSegments?.cacheReadTokens ?? delta('cache_read_input_tokens'),
+ cacheCreationTokens: fromSegments?.cacheCreationTokens ?? delta('cache_creation_input_tokens'),
+ outputTokens: fromSegments?.outputTokens ?? delta('output_tokens'),
+ costUsd,
+ };
+ if (data.modelUsageCumulativeStartsAtZero === false && previousUsage === null) usageComplete = false;
+ previousUsage = usage;
+ previousCost = cumulativeCost;
+ return {
+ eventIndex,
+ turnAttemptToken: event.turnAttemptToken ?? null,
+ cumulativeUsage: usage,
+ usageSegments: segments,
+ usageSegmentsComplete: segmentsComplete,
+ normalized,
+ };
+ });
+ const normalizedUsage = sumNormalizedUsage(turns.map((turn) => turn.normalized));
+ return {
+ rawProviderUsage: { aggregation: 'cumulative-delta', backend: agentBackend, turns, totals: normalizedUsage },
+ normalizedUsage,
+ usageComplete,
+ };
+}
+
+export async function runTask(resolved: ResolvedProfile, task: string, workingDir: string, outputDir: string, timeoutMs: number | null, turns: Array<string | HeadlessTurnInput> = [task]): Promise<Record<string, unknown>> {
+ assertSafeExecutionProfile(resolved.profile);
+ const releaseEnvironment = await acquireEnvironmentLease();
+ try {
+ return await runTaskWithIsolatedEnvironment(resolved, task, workingDir, outputDir, timeoutMs, turns);
+ } finally {
+ releaseEnvironment();
+ }
+}
+
+async function runTaskWithIsolatedEnvironment(resolved: ResolvedProfile, task: string, workingDir: string, outputDir: string, timeoutMs: number | null, turns: Array<string | HeadlessTurnInput> = [task]): Promise<Record<string, unknown>> {
+ const profile = resolved.profile;
+ const absoluteOutputDir = path.resolve(outputDir);
+ const absoluteWorkingDir = path.resolve(workingDir);
+ await mkdir(absoluteOutputDir, { recursive: true });
+ const cleanHome = await mkdtemp(path.join(os.tmpdir(), 'cindy-headless-'));
+ const previous = {
+ HOME: process.env.HOME,
+ USERPROFILE: process.env.USERPROFILE,
+ CLAUDE_CONFIG_DIR: process.env.CLAUDE_CONFIG_DIR,
+ XDT_SESSION_TURN_STALL_MS: process.env.XDT_SESSION_TURN_STALL_MS,
+ XDT_CC_SSE_IDLE_TIMEOUT_MS: process.env.XDT_CC_SSE_IDLE_TIMEOUT_MS,
+ XDT_CODEX_IDLE_TIMEOUT_MS: process.env.XDT_CODEX_IDLE_TIMEOUT_MS,
+ };
+ const timeoutOwner = timeoutMs === null ? 'external' : 'headless';
+ const turnStallMs = timeoutMs === null ? null : deriveTurnStallMs(timeoutMs);
+ process.env.HOME = cleanHome;
+ process.env.USERPROFILE = cleanHome;
+ process.env.CLAUDE_CONFIG_DIR = path.join(cleanHome, '.claude');
+ if (turnStallMs === null) {
+ process.env.XDT_SESSION_TURN_STALL_MS = '0';
+ process.env.XDT_CC_SSE_IDLE_TIMEOUT_MS = '0';
+ process.env.XDT_CODEX_IDLE_TIMEOUT_MS = '0';
+ } else {
+ process.env.XDT_SESSION_TURN_STALL_MS = String(turnStallMs);
+ }
+ let onSigterm: (() => void) | undefined;
+ let onSigint: (() => void) | undefined;
+ try {
+ const events: AgentEvent[] = [];
+ let session: Awaited<ReturnType<Maker['createSession']>> | undefined;
+ let runtime: ReturnType<typeof createHeadlessMaker> | undefined;
+ const startedAt = Date.now();
+ let error: string | undefined;
+ let deadlineKilled = false;
+ let timeoutReachedAtMs: number | null = null;
+ let terminationSignal: NodeJS.Signals | undefined;
+ let terminalError: AgentEvent | undefined;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ let rejectTermination!: (cause: Error) => void;
+ const termination = new Promise<void>((_, reject) => { rejectTermination = reject; });
+ const terminate = (signal: NodeJS.Signals) => {
+ if (terminationSignal) return;
+ terminationSignal = signal;
+ rejectTermination(new Error(`HEADLESS_TERMINATED_${signal}`));
+ void session?.abort().catch(() => undefined);
+ };
+ onSigterm = () => terminate('SIGTERM');
+ onSigint = () => terminate('SIGINT');
+ process.on('SIGTERM', onSigterm);
+ process.on('SIGINT', onSigint);
+ const projectContext = await readProjectContext(absoluteWorkingDir, profile.projectContext);
+ const resolvedTurns = await resolveTurns(turns.length > 0 ? turns : [task], absoluteWorkingDir, profile.inputPolicy);
+ const piProjectTrust = profile.agentBackend === 'pi' && profile.piProjectSkills?.enabled
+ ? await resolvePiProjectTrust(absoluteWorkingDir, profile.piProjectSkills)
+ : null;
+ // Pi 0.85.x loads local root task project resources in place, so Headless
+ // inspects the workspace itself to keep the frozen profile decisive.
+ const piProjectResources: PiProjectWorkspaceResources | null = profile.agentBackend === 'pi'
+ ? await inspectPiProjectWorkspaceResources(absoluteWorkingDir)
+ : null;
+ const piSkillDenials = piProjectResources
+ ? piProjectSkillDenials(piProjectResources, piProjectTrust?.discovered.skills ?? [])
+ : [];
+ const stateDir = path.resolve(process.env.CINDY_HEADLESS_STATE_DIR ?? path.join(absoluteOutputDir, 'state'));
+ try {
+ await mkdir(stateDir, { recursive: true });
+ await access(profile.agentBinaryPath);
+ runtime = createHeadlessMaker(resolved, stateDir, absoluteWorkingDir, piProjectTrust, piSkillDenials);
+ session = await runtime.maker.createSession({ agentKind: profile.agentBackend, workingDir: absoluteWorkingDir, model: profile.model.requestedId, providerId: profile.model.provider, effort: profile.model.effort, permissionMode: profile.permissionMode, makerMemoryEnabled: profile.makerMemory, userPrompt: projectContext.content, vendorOptions: { onStderrLine: (line: string) => { void appendFile(path.join(absoluteOutputDir, 'stderr.log'), `${line}\n`, 'utf8'); } }, id: `headless-${Date.now()}` });
+ let resolveTerminal: (() => void) | undefined;
+ let terminal = Promise.resolve();
+ let activeTurnAttemptToken: number | undefined;
+ session.onEvent((event) => {
+ events.push(event);
+ if (!session || !isHeadlessTerminalEvent(event, session, activeTurnAttemptToken)) return;
+ if (event.type === 'error') terminalError = event;
+ resolveTerminal?.();
+ });
+ for (const [turnIndex, turn] of resolvedTurns.entries()) {
+ activeTurnAttemptToken = turnIndex + 1;
+ terminal = new Promise<void>((resolve) => { resolveTerminal = resolve; });
+ const sent = await session.send(turn, { turnAttemptToken: turnIndex + 1 });
+ if (!sent.accepted) throw new Error(terminationSignal ? `HEADLESS_TERMINATED_${terminationSignal}` : `HEADLESS_SEND_NOT_ACCEPTED: ${sent.reason}`);
+ const completion: Promise<void>[] = [terminal, termination];
+ if (timeoutMs !== null) completion.push(new Promise<void>((_, reject) => {
+ timer = setTimeout(() => reject(new Error('HEADLESS_DEADLINE_EXCEEDED')), timeoutMs);
+ }));
+ await Promise.race(completion);
+ if (timer) { clearTimeout(timer); timer = undefined; }
+ if (terminalError) break;
+ }
+ } catch (cause) {
+ error = cause instanceof Error ? cause.message : String(cause);
+ deadlineKilled = error === 'HEADLESS_DEADLINE_EXCEEDED';
+ if (deadlineKilled) timeoutReachedAtMs = Date.now() - startedAt;
+ if ((deadlineKilled || terminationSignal) && session) {
+ await session.abort().catch(() => undefined);
+ // If the deadline fired, the agent binary may be stuck in a streaming
+ // HTTP request that never checks abort signals. Force-kill the maker
+ // process immediately so resources are freed without waiting.
+ try { await runtime?.maker.shutdown(); } catch { /* best-effort force kill */ }
+ }
+ } finally {
+ if (timer) clearTimeout(timer);
+ }
+ // Claude may emit the final `done` event while closing the SDK session. Flush
+ // it before extracting provider usage so Harbor receives real token counts.
+ // Cleanup is outside the scoring budget, but it must remain bounded so
+ // artifact persistence can finish during the outer harness grace period.
+ const CLOSE_DEADLINE_MS = 5_000;
+ try { await Promise.race([session?.close(), new Promise((_, reject) => setTimeout(() => reject(new Error('CLOSE_TIMEOUT')), CLOSE_DEADLINE_MS))]); } catch { /* artifact writing must still run */ }
+ const usage = session?.getUsageSnapshot() ?? { tokenUsage: 0, contextTokens: 0, contextWindow: 0, costUsd: 0 };
+ const providerUsage = extractProviderUsage(events, profile.agentBackend);
+ if (providerUsage.normalizedUsage.costUsd === 0 && usage.costUsd > 0) providerUsage.normalizedUsage.costUsd = usage.costUsd;
+ const hasObservedUsage = providerUsage.rawProviderUsage !== null || usage.tokenUsage > 0;
+ const interrupted = deadlineKilled || terminationSignal !== undefined;
+ const usageStatus = interrupted ? (hasObservedUsage ? 'PARTIAL' : 'MISSING') : (providerUsage.rawProviderUsage && providerUsage.usageComplete ? 'COMPLETE' : hasObservedUsage ? 'PARTIAL' : 'MISSING');
+ const usageCompleteness = usageStatus === 'COMPLETE' ? 'exact' : usageStatus === 'PARTIAL' ? 'lower-bound' : 'incomplete';
+ const usageSource = [providerUsage.rawProviderUsage ? 'provider-events' : '', usage.tokenUsage > 0 ? 'session-snapshot' : ''].filter(Boolean);
+ const missingFields = usageStatus === 'COMPLETE' ? [] : ['inputTokens', 'cacheReadTokens', 'cacheCreationTokens', 'outputTokens', 'costUsd'].filter((field) => providerUsage.normalizedUsage[field as keyof typeof providerUsage.normalizedUsage] === 0);
+ const terminalMessage = terminalError?.data && typeof terminalError.data === 'object' && typeof (terminalError.data as Record<string, unknown>).message === 'string'
+ ? String((terminalError.data as Record<string, unknown>).message) : undefined;
+ const effectiveError = error ?? terminalMessage;
+ const status = classifyFailure(effectiveError, terminalError, deadlineKilled);
+ const reward = typeof process.env.CINDY_HEADLESS_REWARD === 'string' ? Number(process.env.CINDY_HEADLESS_REWARD) : null;
+ const benchmark = process.env.CINDY_BENCHMARK ?? null;
+ const taskId = process.env.CINDY_TASK_ID ?? null;
+ const repetition = Number(process.env.CINDY_REPETITION ?? '0') || null;
+ const runId = process.env.CINDY_RUN_ID ?? `local-${startedAt}`;
+ const cellId = process.env.CINDY_CELL_ID ?? sha256(JSON.stringify({ benchmark, revision: process.env.CINDY_BENCHMARK_REVISION ?? null, taskId, agent: profile.id, model: profile.model.requestedId, repetition }));
+ const attemptId = process.env.CINDY_ATTEMPT_ID ?? `${cellId}-${startedAt}`;
+ const manifestDigest = process.env.CINDY_MANIFEST_DIGEST ?? null;
+ const standard = standardResult(status, reward);
+ const actualEndpoint = profile.agentBackend === 'codex'
+ ? process.env.CINDY_CODEX_BASE_URL ?? process.env.CINDY_HEADLESS_BASE_URL ?? null
+ : profile.nativeProviders?.find((provider) => provider.id === profile.model.provider)?.baseUrl ?? process.env.CINDY_HEADLESS_BASE_URL ?? profile.endpoint ?? null;
+ const observedModels = [...new Set(events.map((event) => event.agentMeta?.model).filter((model): model is string => typeof model === 'string' && model !== '<synthetic>'))];
+ const actualModelId = process.env.CINDY_ACTUAL_MODEL ?? (observedModels.length === 1 ? observedModels[0] : null);
+ const upstreamProvider = process.env.CINDY_UPSTREAM_PROVIDER ?? null;
+ const requestIds = [...new Set(events.map((event) => event.agentMeta?.requestId).filter((id): id is string => typeof id === 'string'))];
+ const piSkillsEvidence = piProjectSkillsEvidence(piProjectTrust);
+ const piResourcesEvidence = piProjectResourcesEvidence(piProjectResources, piSkillDenials);
+ const identityEvidence = {
+ actualModelId: process.env.CINDY_ACTUAL_MODEL ? 'operator-asserted' : observedModels.length === 1 ? 'provider-event' : 'unknown',
+ actualEndpoint: actualEndpoint ? 'configured' : 'unknown',
+ upstreamProvider: process.env.CINDY_UPSTREAM_PROVIDER ? 'operator-asserted' : 'unknown',
+ requestIds: requestIds.length > 0 ? 'provider-event' : 'unknown',
+ gatewayAttested: false,
+ };
+ const identity = { schemaVersion: 2, runId, cellId, attemptId, manifestDigest, benchmark, benchmarkRevision: process.env.CINDY_BENCHMARK_REVISION ?? null, taskId, repetition, profileId: profile.id, profileDigest: resolved.profileDigest, systemPromptDigest: resolved.systemPromptDigest, agentBackend: profile.agentBackend, agentBinaryVersion: profile.agentBinaryVersion, cindyCliVersion: CINDY_HEADLESS_VERSION, cindyUpstreamCommit: CINDY_UPSTREAM_COMMIT, harborVersion: process.env.HARBOR_VERSION ?? null, litellmVersion: process.env.LITELLM_VERSION ?? null, requestedModelId: profile.model.requestedId, actualModelId, provider: profile.model.provider, actualEndpoint, upstreamProvider, routeId: profile.model.routeId ?? null, observedModels, requestIds, identityEvidence, containerSandbox: profile.containerSandbox ?? false, projectContext: profile.projectContext, projectContextInjected: projectContext.injected, projectContextDigest: projectContext.digest, makerMemory: profile.makerMemory, nativeMemory: profile.nativeMemory, attachments: profile.inputPolicy?.attachments ?? false, customMcpServers: profile.mcpServers?.map((server) => server.id) ?? [], nativeProviders: profile.nativeProviders?.map((provider) => provider.id) ?? [], piProjectSkills: profile.piProjectSkills?.enabled ?? false, piProjectSkillsRevision: piSkillsEvidence.revision, piProjectSkillsCount: piSkillsEvidence.count, piProjectResources: piResourcesEvidence };
+ const result = { schemaVersion: 2, status, resultClass: standard, reward, runId, cellId, attemptId, manifestDigest, cindyUpstreamCommit: CINDY_UPSTREAM_COMMIT, benchmark, benchmarkRevision: process.env.CINDY_BENCHMARK_REVISION ?? null, taskId, repetition, sessionId: session?.id ?? null, turnsCount: turns.length > 0 ? turns.length : 1, durationMs: Date.now() - startedAt, timedOut: deadlineKilled, timeoutOwner, timeoutMs, timeoutReachedAtMs, error: effectiveError ?? null, terminalError: terminalError?.data ?? null, eventsCount: events.length, retries: Number(process.env.CINDY_RETRY_COUNT ?? '0') || 0, replacesAttemptId: process.env.CINDY_REPLACES_ATTEMPT_ID ?? null };
+ try { await runtime?.maker.shutdown(); } catch { /* best effort cleanup */ }
+ try { await runtime?.shutdownBridge(); } catch { /* best effort cleanup */ }
+ try { runtime?.sessionStorage.close(); } catch { /* best effort cleanup */ }
+ const normalizedEvents = normalizeTraceEvents(events);
+ await Promise.all([
+ writeFile(path.join(absoluteOutputDir, 'stderr.log'), '', { encoding: 'utf8', flag: 'a' }),
+ writeFile(path.join(absoluteOutputDir, 'identity.json'), JSON.stringify(identity, null, 2) + '\n', 'utf8'),
+ writeFile(path.join(absoluteOutputDir, 'config.json'), JSON.stringify({ profilePath: resolved.profilePath, workingDir: absoluteWorkingDir, stateDir, timeoutOwner, timeoutMs, turnStallMs, projectContext: { injected: projectContext.injected, reason: projectContext.reason ?? null, tocPath: projectContext.tocPath, digest: projectContext.digest }, capabilities: { attachments: profile.inputPolicy?.attachments ?? false, customMcpServers: profile.mcpServers?.map((server) => ({ id: server.id, transport: server.transport, url: server.url, bearerTokenEnvVar: server.bearerTokenEnvVar ?? null, headerEnvVars: server.headerEnvVars ?? {} })) ?? [], nativeProviders: profile.nativeProviders?.map((provider) => ({ id: provider.id, api: provider.api, baseUrl: provider.baseUrl, apiKeyEnvVar: provider.apiKeyEnvVar ?? null, models: provider.models.map((model) => model.id) })) ?? [], piProjectSkills: { ...(profile.piProjectSkills ?? { enabled: false, roots: [] }), revision: piSkillsEvidence.revision, discoveredSkills: piSkillsEvidence.discoveredSkills }, piProjectResources: piResourcesEvidence } }, null, 2) + '\n', 'utf8'),
+ writeFile(path.join(absoluteOutputDir, 'trace.raw.jsonl'), events.map((event) => JSON.stringify(event)).join('\n') + (events.length ? '\n' : ''), 'utf8'),
+ writeFile(path.join(absoluteOutputDir, 'trace.jsonl'), normalizedEvents.map((event) => JSON.stringify(event)).join('\n') + (normalizedEvents.length ? '\n' : ''), 'utf8'),
+ writeFile(path.join(absoluteOutputDir, 'usage.json'), JSON.stringify(createUsageArtifact({ ...providerUsage, sessionSnapshot: usage, usageStatus, usageCompleteness, usageSource, missingFields, termination: deadlineKilled ? 'HEADLESS_DEADLINE' : terminationSignal ?? null, observedTokenTotal: usage.tokenUsage > 0 ? usage.tokenUsage : null }), null, 2) + '\n', 'utf8'),
+ writeFile(path.join(absoluteOutputDir, 'result.json'), JSON.stringify(result, null, 2) + '\n', 'utf8'),
+ ]);
+ return { ...result, usage };
+ } finally {
+ if (onSigterm) process.off('SIGTERM', onSigterm);
+ if (onSigint) process.off('SIGINT', onSigint);
+ for (const [key, value] of Object.entries(previous)) value === undefined ? delete process.env[key] : process.env[key] = value;
+ await rm(cleanHome, { recursive: true, force: true });
+ }
+}
diff --git a/apps/cindy-headless/src/memory-contract.test.ts b/apps/cindy-headless/src/memory-contract.test.ts
new file mode 100644
index 0000000000..6f3a93db9d
--- /dev/null
+++ b/apps/cindy-headless/src/memory-contract.test.ts
@@ -0,0 +1,29 @@
+import { MakerMemoryManager } from '@cindy/maker-core';
+import { mkdtemp } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import { describe, expect, it } from 'vitest';
+import { openHeadlessSqlite } from './sqlite.js';
+
+const logger = {
+ trace() {}, debug() {}, info() {}, warn() {}, error() {}, child() { return this; },
+} as never;
+
+describe('Cindy Maker Memory contract', () => {
+ it('persists a workdir-scoped record and indexes it for search', async () => {
+ const root = await mkdtemp(path.join(os.tmpdir(), 'cindy-headless-memory-'));
+ const manager = new MakerMemoryManager({
+ basePath: root,
+ sqliteFactory: openHeadlessSqlite,
+ agents: {},
+ initialEnabled: true,
+ logger,
+ reviewAgent: 'claude-code',
+ });
+ const store = await manager.getStore(path.join(root, 'workspace'));
+ await store.write({ type: 'project', name: 'headless-contract', title: 'Headless contract', description: 'Cindy parity', body: 'Maker Memory persists project facts.' });
+ expect((await store.list()).map((record) => record.frontmatter.title)).toContain('Headless contract');
+ expect((await store.search('project facts')).length).toBeGreaterThan(0);
+ manager.dispose();
+ });
+});
diff --git a/apps/cindy-headless/src/memory-provider.ts b/apps/cindy-headless/src/memory-provider.ts
new file mode 100644
index 0000000000..7660797558
--- /dev/null
+++ b/apps/cindy-headless/src/memory-provider.ts
@@ -0,0 +1,24 @@
+import type { Logger, MakerMemoryManager, McpProvider } from '@cindy/maker-core';
+import { createCindyMemoryMcpServer } from '../../../packages/lizi-mcps/src/cindy_memoryMcpServer.js';
+
+export interface MemoryMcpProviderOptions {
+ getManager(): MakerMemoryManager;
+ logger?: Logger;
+}
+
+/** Headless-only adapter around Cindy's existing Maker Memory MCP factory. */
+export function createMemoryMcpProvider(options: MemoryMcpProviderOptions): McpProvider {
+ return {
+ name: 'cindy_memory',
+ isEnabled: () => options.getManager().isEnabled(),
+ toClaudeSdkConfig: (context) => ({
+ type: 'sdk',
+ name: 'cindy_memory',
+ instance: createCindyMemoryMcpServer({
+ getManager: options.getManager,
+ workdir: context.workingDir,
+ ...(options.logger ? { logger: options.logger } : {}),
+ }),
+ }),
+ };
+}
diff --git a/apps/cindy-headless/src/production-profile-parity.test.ts b/apps/cindy-headless/src/production-profile-parity.test.ts
new file mode 100644
index 0000000000..d0c9134c3d
--- /dev/null
+++ b/apps/cindy-headless/src/production-profile-parity.test.ts
@@ -0,0 +1,20 @@
+import { readFile, readdir } from 'node:fs/promises';
+import path from 'node:path';
+import { describe, expect, it } from 'vitest';
+
+describe('example profiles match the packaged runtime pins', () => {
+ it('keeps every example and smoke profile aligned with the repository runtime versions', async () => {
+ const tools = { 'claude-code': 'claude', codex: 'codex', pi: 'pi' } as const;
+ const versions = Object.fromEntries(await Promise.all(Object.entries(tools).map(async ([backend, tool]) => {
+ const metadata = JSON.parse(await readFile(path.resolve('../../tools', tool, 'latest.json'), 'utf8'));
+ return [backend, metadata.version];
+ })));
+ const entries = await readdir('profiles', { recursive: true });
+ const profiles = entries.filter((entry) => entry.endsWith('.json') && !entry.endsWith('profile.lock.json'));
+ expect(profiles.length).toBeGreaterThan(0);
+ for (const entry of profiles) {
+ const profile = JSON.parse(await readFile(path.join('profiles', entry), 'utf8'));
+ expect(profile.agentBinaryVersion, entry).toBe(versions[profile.agentBackend]);
+ }
+ });
+});
diff --git a/apps/cindy-headless/src/profile-generation.test.ts b/apps/cindy-headless/src/profile-generation.test.ts
new file mode 100644
index 0000000000..4ee973826a
--- /dev/null
+++ b/apps/cindy-headless/src/profile-generation.test.ts
@@ -0,0 +1,114 @@
+import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import { afterEach, describe, expect, it } from 'vitest';
+import { capabilityCatalog } from './compatibility.js';
+import { generateProfileFromManifest, PROFILE_GENERATION_FEATURES } from './profile-generation.js';
+import { readProfile, sha256 } from './profile.js';
+
+const temporaryDirectories: string[] = [];
+
+async function fixture() {
+ const root = await mkdtemp(path.join(os.tmpdir(), 'cindy-profile-generate-'));
+ temporaryDirectories.push(root);
+ await mkdir(path.join(root, 'bin', 'pi'), { recursive: true });
+ const prompts = { 'prompt.md': 'claude prompt\n', 'codex-prompt.md': 'codex prompt\n', 'pi-prompt.md': 'pi prompt\n' };
+ await Promise.all(Object.entries(prompts).map(([name, body]) => writeFile(path.join(root, name), body)));
+ const catalog = capabilityCatalog();
+ const models = {
+ 'claude-code': { supportedModelIds: ['claude-test'], defaultModel: { provider: 'anthropic', requestedId: 'claude-test' } },
+ codex: { supportedModelIds: ['gpt-test'], defaultModel: { provider: 'openai', requestedId: 'gpt-test' } },
+ pi: { supportedModelIds: ['pi-test'], defaultModel: { provider: 'cindy', requestedId: 'pi-test', contextLimit: 100_000, maxOutputTokens: 8_000 } },
+ };
+ for (const entry of catalog.harnesses) Object.assign(entry, models[entry.backend as keyof typeof models]);
+ const manifest = {
+ capabilityCatalog: catalog,
+ claudeCodeVersion: '1.0.0', codexVersion: '2.0.0', piVersion: '3.0.0',
+ systemPromptDigest: sha256(prompts['prompt.md']), codexSystemPromptDigest: sha256(prompts['codex-prompt.md']), piSystemPromptDigest: sha256(prompts['pi-prompt.md']),
+ };
+ const manifestPath = path.join(root, 'bundle-manifest.json');
+ await writeFile(manifestPath, JSON.stringify(manifest));
+ return { root, manifest, manifestPath };
+}
+
+afterEach(async () => Promise.all(temporaryDirectories.splice(0).map((directory) => rm(directory, { recursive: true, force: true }))));
+
+describe('profile generation', () => {
+ it('has an explicit implementation for every registered feature', () => {
+ expect([...PROFILE_GENERATION_FEATURES].sort()).toEqual(Object.keys(capabilityCatalog().features).sort());
+ });
+
+ it('fails closed when a manifest advertises a feature without a generator implementation', async () => {
+ const { manifest, manifestPath } = await fixture();
+ manifest.capabilityCatalog.features.futureFeature = { type: 'boolean', control: 'profile', default: false };
+ manifest.capabilityCatalog.defaultValues.futureFeature = false;
+ manifest.capabilityCatalog.harnesses[0]!.features.push('futureFeature');
+ expect(() => generateProfileFromManifest(manifest, { manifestPath, outputPath: 'unused.json', harness: 'claude-code', features: ['futureFeature'] })).toThrow('profile generator has no implementation');
+ });
+ for (const harness of ['claude-code', 'codex', 'pi'] as const) {
+ it(`generates and validates a ${harness} profile using bundle-relative assets`, async () => {
+ const { root, manifest, manifestPath } = await fixture();
+ const outputPath = path.join(root, 'generated', harness, 'profile.json');
+ const profile = generateProfileFromManifest(manifest, { manifestPath, outputPath, harness });
+ await mkdir(path.dirname(outputPath), { recursive: true });
+ await writeFile(outputPath, JSON.stringify(profile, null, 2) + '\n');
+ const resolved = await readProfile(outputPath, root);
+ expect(resolved.profile.agentBackend).toBe(harness);
+ expect(resolved.profile.model.effort).toBe('high');
+ expect(resolved.systemPromptDigest).toBe(profile.expectedSystemPromptDigest);
+ expect(profile.agentBinaryPath).toBe(`bundle:bin/${harness === 'pi' ? 'pi/pi' : harness === 'claude-code' ? 'claude' : 'codex'}`);
+ expect(path.isAbsolute(resolved.profile.agentBinaryPath)).toBe(true);
+ });
+ }
+
+ it('generates a valid native provider for a custom Pi model', async () => {
+ const { root, manifest, manifestPath } = await fixture();
+ const outputPath = path.join(root, 'generated-pi.json');
+ const profile = generateProfileFromManifest(manifest, {
+ manifestPath, outputPath, harness: 'pi', modelId: 'custom-model', providerId: 'custom', providerBaseUrl: 'https://models.example.test',
+ providerApi: 'openai-responses', contextLimit: 128_000, maxOutputTokens: 16_000,
+ });
+ expect(profile.nativeProviders?.[0]).toMatchObject({ id: 'custom', models: [{ id: 'custom-model', contextWindow: 128_000, maxTokens: 16_000 }] });
+ expect(profile.supportedModelIds).toContain('custom-model');
+ });
+
+ it('allows an explicitly configured gateway model without weakening default validation', async () => {
+ const { manifest, manifestPath } = await fixture();
+ const outputPath = path.join(path.dirname(manifestPath), 'gateway.json');
+ const options = { manifestPath, outputPath, harness: 'claude-code', modelId: 'deepseek/model' };
+ expect(() => generateProfileFromManifest(manifest, options)).toThrow('is not supported');
+ const profile = generateProfileFromManifest(manifest, {
+ ...options, gatewayModel: true, providerId: 'deepseek', providerBaseUrl: 'https://gateway.example.test', providerApi: 'anthropic-messages',
+ });
+ expect(profile.model).toMatchObject({ provider: 'deepseek', requestedId: 'deepseek/model' });
+ expect(profile.supportedModelIds).toContain('deepseek/model');
+ });
+
+ it('generates a validated remote HTTP MCP configuration', async () => {
+ const { root, manifest, manifestPath } = await fixture();
+ const outputPath = path.join(root, 'generated-claude.json');
+ const profile = generateProfileFromManifest(manifest, {
+ manifestPath,
+ outputPath,
+ harness: 'claude-code',
+ mcpServers: [{ id: 'docs', transport: 'http', url: 'https://mcp.example.test', bearerTokenEnvVar: 'MCP_TOKEN' }],
+ });
+ expect(profile.mcpServers).toEqual([{ id: 'docs', transport: 'http', url: 'https://mcp.example.test', bearerTokenEnvVar: 'MCP_TOKEN' }]);
+ });
+
+ it('supports an exact empty feature selection instead of applying manifest defaults', async () => {
+ const { manifest, manifestPath } = await fixture();
+ const profile = generateProfileFromManifest(manifest, { manifestPath, outputPath: 'unused.json', harness: 'claude-code', features: [], exactFeatures: true });
+ expect(profile).toMatchObject({ projectContext: false, makerMemory: false, nativeMemory: false });
+ });
+
+ it('rejects unsupported features, harnesses and unconfigured custom models', async () => {
+ const { root, manifest, manifestPath } = await fixture();
+ const outputPath = path.join(root, 'profile.json');
+ expect(() => generateProfileFromManifest(manifest, { manifestPath, outputPath, harness: 'future' })).toThrow('bundle does not provide harness');
+ expect(() => generateProfileFromManifest(manifest, { manifestPath, outputPath, harness: 'codex', features: ['piProjectSkills'] })).toThrow('DETECTED_BUT_UNSUPPORTED');
+ expect(() => generateProfileFromManifest(manifest, { manifestPath, outputPath, harness: 'pi', modelId: 'custom' })).toThrow('custom Pi models require');
+ expect(() => generateProfileFromManifest(manifest, { manifestPath, outputPath, harness: 'claude-code', features: ['remoteHttpMcp'] })).toThrow('DETECTED_BUT_UNSUPPORTED');
+ expect(() => generateProfileFromManifest(manifest, { manifestPath, outputPath, harness: 'pi', effort: 'ultra' })).toThrow('ultra effort is not supported');
+ });
+});
diff --git a/apps/cindy-headless/src/profile-generation.ts b/apps/cindy-headless/src/profile-generation.ts
new file mode 100644
index 0000000000..6028aff85c
--- /dev/null
+++ b/apps/cindy-headless/src/profile-generation.ts
@@ -0,0 +1,132 @@
+import type { HeadlessCapabilityCatalog, HeadlessHarnessCapability } from './compatibility.js';
+import { ADAPTER_HARNESSES, discoverCapabilityCatalog } from './compatibility.js';
+import type { HeadlessProfile } from './profile.js';
+import { validateProfile } from './profile.js';
+
+export interface ProfileGenerationOptions {
+ manifestPath: string;
+ outputPath: string;
+ harness: string;
+ features?: string[];
+ modelId?: string;
+ providerId?: string;
+ providerName?: string;
+ providerBaseUrl?: string;
+ providerApi?: 'anthropic-messages' | 'openai-responses' | 'openai-completions' | 'google-generative-ai';
+ apiKeyEnvVar?: string;
+ contextLimit?: number;
+ maxOutputTokens?: number;
+ mcpServers?: HeadlessProfile['mcpServers'];
+ effort?: HeadlessProfile['model']['effort'];
+ gatewayModel?: boolean;
+ exactFeatures?: boolean;
+}
+
+type BundleManifest = Record<string, unknown> & { capabilityCatalog?: HeadlessCapabilityCatalog };
+
+const HARNESS_FILES = {
+ 'claude-code': { binary: 'bin/claude', prompt: 'prompt.md', version: 'claudeCodeVersion', digest: 'systemPromptDigest' },
+ codex: { binary: 'bin/codex', prompt: 'codex-prompt.md', version: 'codexVersion', digest: 'codexSystemPromptDigest' },
+ pi: { binary: 'bin/pi/pi', prompt: 'pi-prompt.md', version: 'piVersion', digest: 'piSystemPromptDigest' },
+} as const;
+
+const DEFAULT_MODELS: Record<keyof typeof HARNESS_FILES, HeadlessProfile['model']> = {
+ 'claude-code': { provider: 'anthropic', requestedId: 'claude-sonnet-4-6', effort: 'high' },
+ codex: { provider: 'openai', requestedId: 'gpt-5.4-mini', effort: 'high' },
+ pi: { provider: 'cindy', requestedId: 'claude-sonnet-4-6', contextLimit: 200_000, maxOutputTokens: 32_000, effort: 'high' },
+};
+
+// This is implementation coverage, not a second capability catalog. Adding a
+// registry entry without teaching the generator how to materialize it must fail
+// closed instead of being advertised and silently ignored.
+export const PROFILE_GENERATION_FEATURES = new Set([
+ 'projectContext', 'makerMemory', 'nativeMemory', 'attachments', 'piProjectSkills',
+]);
+
+function assertGeneratorCoverage(catalog: HeadlessCapabilityCatalog): void {
+ const missing = Object.keys(catalog.features).filter((id) => !PROFILE_GENERATION_FEATURES.has(id));
+ if (missing.length) throw new Error(`DETECTED_BUT_UNSUPPORTED: profile generator has no implementation for ${missing.join(', ')}`);
+}
+
+function requireManifestString(manifest: BundleManifest, field: string): string {
+ const value = manifest[field];
+ if (typeof value !== 'string' || value.trim() === '') throw new Error(`bundle manifest is missing ${field}`);
+ return value;
+}
+
+function harnessEntry(catalog: HeadlessCapabilityCatalog, harness: string): HeadlessHarnessCapability {
+ const entry = catalog.harnesses.find((item) => item.backend === harness);
+ if (!entry) throw new Error(`bundle does not provide harness: ${harness}`);
+ if (!ADAPTER_HARNESSES.has(harness as HeadlessProfile['agentBackend']) || entry.adapterSupported === false) {
+ throw new Error(`DETECTED_BUT_UNSUPPORTED: harness ${harness}`);
+ }
+ return entry;
+}
+
+export function generateProfileFromManifest(manifest: BundleManifest, options: ProfileGenerationOptions): HeadlessProfile {
+ const discovered = discoverCapabilityCatalog(manifest.capabilityCatalog);
+ const catalog = manifest.capabilityCatalog as HeadlessCapabilityCatalog;
+ assertGeneratorCoverage(catalog);
+ const entry = harnessEntry(catalog, options.harness);
+ const harness = options.harness as keyof typeof HARNESS_FILES;
+ const selected = new Set(options.features ?? []);
+ const unsupported = [...selected].filter((id) => discovered.support[id] !== 'SUPPORTED' || !entry.features.includes(id));
+ if (unsupported.length) throw new Error(`DETECTED_BUT_UNSUPPORTED: ${unsupported.join(', ')}`);
+
+ const files = HARNESS_FILES[harness];
+ const defaults = catalog.defaultValues ?? {};
+ const enabled = (id: string) => selected.has(id) || (!options.exactFeatures && selected.size === 0 && defaults[id] === true);
+ const defaultModel = entry.defaultModel ?? DEFAULT_MODELS[harness];
+ const supportedModelIds = entry.supportedModelIds?.length ? [...entry.supportedModelIds] : [defaultModel.requestedId];
+ const requestedId = options.modelId ?? defaultModel.requestedId;
+ const customModel = !supportedModelIds.includes(requestedId);
+ const customPiModel = harness === 'pi' && customModel;
+ if (harness !== 'pi' && customModel && !options.gatewayModel) throw new Error(`model ${requestedId} is not supported by harness ${harness}`);
+ if (options.gatewayModel && (!options.modelId || !options.providerId || !options.providerBaseUrl || !options.providerApi)) {
+ throw new Error('gateway models require --model, --provider, --base-url and --api');
+ }
+
+ let nativeProviders: HeadlessProfile['nativeProviders'];
+ let model: HeadlessProfile['model'] = { ...defaultModel, requestedId, effort: options.effort ?? defaultModel.effort ?? 'high' };
+ if (customPiModel) {
+ if (!options.providerId || !options.providerBaseUrl || !options.providerApi || !options.contextLimit || !options.maxOutputTokens) {
+ throw new Error('custom Pi models require --provider, --base-url, --api, --context-limit and --max-output-tokens');
+ }
+ model = { provider: options.providerId, requestedId, contextLimit: options.contextLimit, maxOutputTokens: options.maxOutputTokens, effort: options.effort ?? defaultModel.effort ?? 'high' };
+ nativeProviders = [{
+ id: options.providerId,
+ name: options.providerName ?? options.providerId,
+ baseUrl: options.providerBaseUrl,
+ api: options.providerApi,
+ ...(options.apiKeyEnvVar ? { apiKeyEnvVar: options.apiKeyEnvVar } : {}),
+ models: [{ id: requestedId, contextWindow: options.contextLimit, maxTokens: options.maxOutputTokens }],
+ }];
+ supportedModelIds.push(requestedId);
+ }
+ if (customModel && harness !== 'pi') {
+ model = { ...model, provider: options.providerId!, requestedId };
+ supportedModelIds.push(requestedId);
+ }
+ const compaction = defaults.compaction;
+ return validateProfile({
+ id: `generated-${harness}`,
+ version: 1,
+ agentBackend: harness,
+ agentBinaryPath: `bundle:${files.binary}`,
+ agentBinaryVersion: requireManifestString(manifest, files.version),
+ supportedModelIds,
+ model,
+ permissionMode: 'bypassPermissions',
+ systemPromptFile: `bundle:${files.prompt}`,
+ expectedSystemPromptDigest: requireManifestString(manifest, files.digest),
+ makerMemory: enabled('makerMemory'),
+ nativeMemory: enabled('nativeMemory'),
+ projectContext: enabled('projectContext'),
+ containerSandbox: true,
+ ...(enabled('attachments') ? { inputPolicy: { attachments: true, workspaceOnly: true } } : {}),
+ ...(enabled('piProjectSkills') ? { piProjectSkills: { enabled: true, roots: ['.pi/skills', '.agents/skills'] } } : {}),
+ ...(compaction && typeof compaction === 'object' ? { compaction } : {}),
+ ...(nativeProviders ? { nativeProviders } : {}),
+ ...(options.mcpServers?.length ? { mcpServers: options.mcpServers } : {}),
+ });
+}
diff --git a/apps/cindy-headless/src/profile.test.ts b/apps/cindy-headless/src/profile.test.ts
new file mode 100644
index 0000000000..d092b4fe5d
--- /dev/null
+++ b/apps/cindy-headless/src/profile.test.ts
@@ -0,0 +1,106 @@
+import { mkdtemp, readFile, writeFile } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import { describe, expect, it } from 'vitest';
+import { capabilities, profileDigest, readProfile, sha256, validateProfile } from './profile.js';
+import { CINDY_UPSTREAM_COMMIT } from './compatibility.js';
+
+const profile = { id: 'cindy-production-claude', version: 1, agentBackend: 'claude-code', agentBinaryPath: '/opt/cindy/bin/claude', agentBinaryVersion: '2.1.219', supportedModelIds: ['claude-sonnet-4-5'], model: { provider: 'anthropic', requestedId: 'claude-sonnet-4-5' }, permissionMode: 'bypassPermissions', makerMemory: false, nativeMemory: false, projectContext: false } as const;
+const codexProfile = { ...profile, id: 'cindy-production-codex', agentBackend: 'codex', agentBinaryPath: '/opt/cindy/bin/codex', agentBinaryVersion: '0.145.0', supportedModelIds: ['gpt-5.4-mini'], model: { provider: 'openai', requestedId: 'gpt-5.4-mini' }, permissionMode: 'auto' } as const;
+const piProfile = { ...profile, id: 'cindy-production-pi', agentBackend: 'pi', agentBinaryPath: '/opt/cindy/bin/pi', agentBinaryVersion: '0.83.0', model: { ...profile.model, contextLimit: 200_000 }, permissionMode: 'bypassPermissions' } as const;
+
+describe('headless profile', () => {
+ it('rejects model fallback and aliases', () => {
+ expect(() => validateProfile({ ...profile, model: { ...profile.model, requestedId: 'other' } })).toThrow(/not supported/);
+ expect(() => validateProfile({ ...profile, supportedModelIds: ['latest'], model: { ...profile.model, requestedId: 'latest' } })).toThrow(/exact/);
+ });
+ it('requires single-variable metadata for derived profiles', () => expect(() => validateProfile({ ...profile, parentProfile: 'base' })).toThrow(/changedDimensions/));
+ it('keeps Cindy Maker Memory mutually exclusive with native memory for Claude and Codex', () => {
+ expect(() => validateProfile({ ...profile, makerMemory: true, nativeMemory: true })).toThrow(/mutually exclusive/);
+ expect(() => validateProfile({ ...codexProfile, makerMemory: true, nativeMemory: true })).toThrow(/mutually exclusive/);
+ });
+ it('allows Pi Maker Memory and Pi Auto Memory together like Cindy Desktop', () => {
+ expect(validateProfile({ ...piProfile, makerMemory: true, nativeMemory: true })).toMatchObject({ makerMemory: true, nativeMemory: true });
+ });
+ it('reports the original Cindy harness switches in capabilities', () => expect(capabilities(validateProfile({ ...profile, makerMemory: true, projectContext: true }))).toMatchObject({ makerMemory: true, nativeMemory: false, projectContext: true, nativeToolSurface: 'claude-code-default', cindyMcpProviders: ['cindy_memory'], desktopOnlyProviders: [], multiTurnSession: true }));
+ it('reports Cindy Codex app-server capabilities', () => expect(capabilities(validateProfile({ ...codexProfile, makerMemory: true }))).toMatchObject({ agentBackend: 'codex', nativeToolSurface: 'codex-app-server-default', supportedPermissionModes: ['bypassPermissions', 'ask', 'auto', 'plan'], cindyMcpProviders: ['cindy_memory'] }));
+ it('reports Cindy Pi RPC capabilities', () => expect(capabilities(validateProfile({ ...piProfile, makerMemory: true }))).toMatchObject({ agentBackend: 'pi', nativeToolSurface: 'pi-rpc-default', supportedPermissionModes: ['bypassPermissions'], cindyMcpProviders: ['cindy_memory'] }));
+ it('rejects backend-specific permission modes', () => {
+ expect(() => validateProfile({ ...profile, permissionMode: 'auto' })).toThrow(/only supported by codex/);
+ expect(() => validateProfile({ ...codexProfile, permissionMode: 'acceptEdits' })).toThrow(/not supported by codex/);
+ expect(() => validateProfile({ ...piProfile, permissionMode: 'ask' })).toThrow(/no interactive approval channel/);
+ });
+ it('requires an explicit Pi context limit', () => expect(() => validateProfile({ ...piProfile, model: profile.model })).toThrow(/contextLimit/));
+ it('accepts Cindy planning permission mode', () => expect(validateProfile({ ...profile, permissionMode: 'plan' }).permissionMode).toBe('plan'));
+ it('requires unsafe bypass exceptions to be explicit and relevant', () => {
+ expect(() => validateProfile({ ...profile, permissionMode: 'ask', unsafeAllowUnsandboxedBypass: true })).toThrow(/requires bypassPermissions/);
+ expect(validateProfile({ ...profile, unsafeAllowUnsandboxedBypass: true }).unsafeAllowUnsandboxedBypass).toBe(true);
+ });
+ it('returns stable capabilities and canonical digest', () => {
+ const valid = validateProfile(profile);
+ expect(capabilities(valid).artifactContract).toEqual([
+ 'identity.json',
+ 'config.json',
+ 'trace.raw.jsonl',
+ 'trace.jsonl',
+ 'stderr.log',
+ 'usage.json',
+ 'result.json',
+ ]);
+ expect(profileDigest(valid)).toBe(profileDigest({ ...valid, supportedModelIds: [...valid.supportedModelIds] }));
+ });
+ it('accepts the no-compaction and tool-surface profile dimensions', () => {
+ expect(validateProfile({ ...profile, parentProfile: 'cindy-production-claude', changedDimensions: ['compaction'], compaction: { enabled: false } }).compaction?.enabled).toBe(false);
+ expect(validateProfile({ ...profile, parentProfile: 'cindy-production-claude', changedDimensions: ['cindyToolSurface'], makerMemory: false, projectContext: false }).projectContext).toBe(false);
+ });
+ it('verifies the system prompt digest', async () => {
+ const dir = await mkdtemp(path.join(os.tmpdir(), 'headless-profile-'));
+ await writeFile(path.join(dir, 'prompt.md'), 'prompt\n');
+ await writeFile(path.join(dir, 'profile.json'), JSON.stringify({ ...profile, systemPromptFile: 'prompt.md', expectedSystemPromptDigest: '0'.repeat(64) }));
+ await expect(readProfile(path.join(dir, 'profile.json'))).rejects.toThrow(/digest/);
+ });
+ it('validates explicit effort and output limits', () => {
+ expect(validateProfile({ ...profile, model: { ...profile.model, effort: 'xhigh', maxOutputTokens: 32000 } }).model.effort).toBe('xhigh');
+ expect(validateProfile({ ...profile, model: { ...profile.model, effort: 'ultra' } }).model.effort).toBe('ultra');
+ expect(validateProfile({ ...piProfile, model: { ...piProfile.model, effort: 'minimal' } }).model.effort).toBe('minimal');
+ expect(() => validateProfile({ ...piProfile, model: { ...piProfile.model, effort: 'ultra' } })).toThrow(/not supported by the pi backend/);
+ expect(() => validateProfile({ ...profile, model: { ...profile.model, effort: 'unknown' as never } })).toThrow(/effort/);
+ expect(() => validateProfile({ ...profile, model: { ...profile.model, maxOutputTokens: 0 } })).toThrow(/maxOutputTokens/);
+ expect(() => validateProfile({ ...codexProfile, model: { ...codexProfile.model, maxOutputTokens: 32000 } })).toThrow(/not supported by the codex backend/);
+ });
+ it('enforces a colocated frozen profile lock', async () => {
+ const dir = await mkdtemp(path.join(os.tmpdir(), 'headless-profile-lock-'));
+ const raw = JSON.stringify(profile, null, 2);
+ await writeFile(path.join(dir, 'profile.json'), raw);
+ await writeFile(path.join(dir, 'profile.lock.json'), JSON.stringify({ schemaVersion: 1, status: 'frozen', profileId: profile.id, profileFile: 'profile.json', profileFileSha256: sha256(raw), profileDigest: profileDigest(validateProfile(profile)), systemPromptDigest: null, agentBinaryVersion: profile.agentBinaryVersion, cindyUpstreamCommit: CINDY_UPSTREAM_COMMIT }));
+ await expect(readProfile(path.join(dir, 'profile.json'))).resolves.toMatchObject({ profile: { id: profile.id } });
+ await writeFile(path.join(dir, 'profile.json'), `${raw}\n`);
+ await expect(readProfile(path.join(dir, 'profile.json'))).rejects.toThrow(/profile file/);
+ });
+ it('validates frozen attachment, MCP, BYOM, and Pi skill declarations', () => {
+ expect(validateProfile({ ...profile, inputPolicy: { attachments: true, workspaceOnly: true }, mcpServers: [{ id: 'docs', transport: 'http', url: 'https://mcp.example.test', bearerTokenEnvVar: 'DOCS_TOKEN' }] }).mcpServers).toHaveLength(1);
+ expect(() => validateProfile({ ...profile, mcpServers: [{ id: 'bad', transport: 'http', url: 'http://public.example.test' }] })).toThrow(/HTTPS/);
+ expect(() => validateProfile({ ...profile, piProjectSkills: { enabled: true, roots: ['.agents/skills'] } })).toThrow(/pi backend/);
+ const byom = validateProfile({ ...piProfile, model: { ...piProfile.model, provider: 'local' }, nativeProviders: [{ id: 'local', name: 'Local', baseUrl: 'http://127.0.0.1:11434/v1', api: 'openai-completions', models: [{ id: piProfile.model.requestedId, contextWindow: 200_000, maxTokens: 32_000 }] }], piProjectSkills: { enabled: true, roots: ['.pi/skills', '.agents/skills'] } });
+ expect(capabilities(byom)).toMatchObject({ byomProviders: ['local'], piProjectSkills: true });
+ });
+ it('preserves the full DeepSeek model id through a neutral Pi gateway provider', async () => {
+ const candidate = JSON.parse(await readFile(path.resolve('profiles/cindy-production-pi/profile.deepseek-v4-flash.example.json'), 'utf8'));
+ const validated = validateProfile(candidate);
+ expect(validated.model).toMatchObject({ provider: 'example-gateway', requestedId: 'deepseek/deepseek-v4-flash' });
+ expect(validated.nativeProviders).toEqual([
+ expect.objectContaining({
+ id: 'example-gateway',
+ api: 'openai-completions',
+ models: [expect.objectContaining({ id: 'deepseek/deepseek-v4-flash' })],
+ }),
+ ]);
+ });
+ it('resolves a bundled binary relative to the profile file', async () => {
+ const dir = await mkdtemp(path.join(os.tmpdir(), 'headless-profile-relative-'));
+ await writeFile(path.join(dir, 'bin'), 'binary');
+ await writeFile(path.join(dir, 'profile.json'), JSON.stringify({ ...profile, agentBinaryPath: 'bin' }));
+ const resolved = await readProfile(path.join(dir, 'profile.json'));
+ expect(resolved.profile.agentBinaryPath).toBe(path.join(dir, 'bin'));
+ });
+});
diff --git a/apps/cindy-headless/src/profile.ts b/apps/cindy-headless/src/profile.ts
new file mode 100644
index 0000000000..7af8c5e196
--- /dev/null
+++ b/apps/cindy-headless/src/profile.ts
@@ -0,0 +1,322 @@
+import { createHash } from 'node:crypto';
+import { execFile } from 'node:child_process';
+import { access, mkdir, readFile } from 'node:fs/promises';
+import path from 'node:path';
+import { promisify } from 'node:util';
+import { assertSafeExecutionProfile, CINDY_UPSTREAM_COMMIT, compatibilityReport } from './compatibility.js';
+
+const execFileAsync = promisify(execFile);
+
+export interface HeadlessProfile {
+ id: string;
+ version: 1;
+ parentProfile?: string;
+ changedDimensions?: string[];
+ agentBackend: 'claude-code' | 'codex' | 'pi';
+ agentBinaryPath: string;
+ agentBinaryVersion: string;
+ supportedModelIds: string[];
+ model: {
+ provider: string;
+ requestedId: string;
+ routeId?: string;
+ contextLimit?: number;
+ thinkingBudget?: number | string;
+ effort?: 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max' | 'ultra';
+ maxOutputTokens?: number;
+ };
+ endpoint?: string;
+ permissionMode: 'bypassPermissions' | 'acceptEdits' | 'default' | 'ask' | 'auto' | 'plan';
+ systemPromptFile?: string;
+ expectedSystemPromptDigest?: string;
+ makerMemory: boolean;
+ nativeMemory: boolean;
+ projectContext: boolean;
+ containerSandbox?: boolean;
+ unsafeAllowUnsandboxedBypass?: boolean;
+ compaction?: { enabled: boolean; thresholdPct?: number };
+ throughputCap?: { outputTokensPerSecond: number; enforcement: 'external-proxy' };
+ inputPolicy?: { attachments: boolean; workspaceOnly: true; maxFiles?: number; maxFileBytes?: number };
+ mcpServers?: Array<{
+ id: string;
+ transport: 'http';
+ url: string;
+ bearerTokenEnvVar?: string;
+ headerEnvVars?: Record<string, string>;
+ startupTimeoutMs?: number;
+ requestTimeoutMs?: number;
+ }>;
+ nativeProviders?: Array<{
+ id: string;
+ name: string;
+ baseUrl: string;
+ api: 'anthropic-messages' | 'openai-responses' | 'openai-completions' | 'google-generative-ai';
+ apiKeyEnvVar?: string;
+ models: Array<{
+ id: string;
+ wireId?: string;
+ name?: string;
+ reasoning?: boolean;
+ contextWindow: number;
+ maxTokens: number;
+ input?: Array<'text' | 'image'>;
+ cost?: { input: number; output: number; cacheRead: number; cacheWrite: number };
+ }>;
+ }>;
+ piProjectSkills?: { enabled: boolean; roots: string[] };
+}
+
+export interface ResolvedProfile {
+ profile: HeadlessProfile;
+ profilePath: string;
+ systemPrompt?: string;
+ profileDigest: string;
+ systemPromptDigest: string | null;
+}
+
+export interface ProfileCapabilities {
+ schemaVersion: 1;
+ contractVersion: number;
+ profileId: string;
+ agentBackend: 'claude-code' | 'codex' | 'pi';
+ supportedModelIds: string[];
+ supportedPermissionModes: string[];
+ projectContext: boolean;
+ makerMemory: boolean;
+ nativeMemory: boolean;
+ nativeToolSurface: 'claude-code-default' | 'codex-app-server-default' | 'pi-rpc-default';
+ cindyMcpProviders: string[];
+ desktopOnlyProviders: string[];
+ multiTurnSession: true;
+ artifactContract: string[];
+ attachments: boolean;
+ customMcpServers: string[];
+ byomProviders: string[];
+ piProjectSkills: boolean;
+}
+
+function nonEmptyString(value: unknown, field: string): asserts value is string {
+ if (typeof value !== 'string' || value.trim() === '') throw new Error(`${field} must be a non-empty string`);
+}
+
+export function validateProfile(profile: unknown): HeadlessProfile {
+ if (!profile || typeof profile !== 'object' || Array.isArray(profile)) throw new Error('profile must be an object');
+ const value = profile as Partial<HeadlessProfile>;
+ nonEmptyString(value.id, 'profile.id');
+ nonEmptyString(value.agentBinaryPath, 'agentBinaryPath');
+ nonEmptyString(value.agentBinaryVersion, 'agentBinaryVersion');
+ if (value.version !== 1) throw new Error('profile.version must be 1');
+ if (!['claude-code', 'codex', 'pi'].includes(value.agentBackend ?? '')) throw new Error('agentBackend must be claude-code, codex or pi');
+ if (!Array.isArray(value.supportedModelIds) || value.supportedModelIds.length === 0) throw new Error('supportedModelIds must be non-empty');
+ if (value.supportedModelIds.some((id) => typeof id !== 'string' || id.trim() === '' || id === '*' || id === 'latest')) throw new Error('supportedModelIds must contain exact non-empty model IDs');
+ if (new Set(value.supportedModelIds).size !== value.supportedModelIds.length) throw new Error('supportedModelIds must not contain duplicates');
+ if (!value.model || typeof value.model !== 'object') throw new Error('model is required');
+ nonEmptyString(value.model.provider, 'model.provider');
+ nonEmptyString(value.model.requestedId, 'model.requestedId');
+ if (!value.supportedModelIds.includes(value.model.requestedId)) throw new Error(`model ${value.model.requestedId} is not supported by this profile`);
+ if (value.model.effort !== undefined && !['minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra'].includes(value.model.effort)) throw new Error('model.effort must be minimal, low, medium, high, xhigh, max or ultra');
+ if (value.model.maxOutputTokens !== undefined && (!Number.isInteger(value.model.maxOutputTokens) || value.model.maxOutputTokens <= 0)) throw new Error('model.maxOutputTokens must be a positive integer');
+ if (value.agentBackend === 'codex' && value.model.maxOutputTokens !== undefined) throw new Error('model.maxOutputTokens is not supported by the codex backend');
+ if (value.agentBackend === 'pi' && (!Number.isInteger(value.model.contextLimit) || (value.model.contextLimit ?? 0) <= 0)) throw new Error('pi profiles require a positive model.contextLimit');
+ if (value.agentBackend === 'pi' && value.model.effort === 'ultra') throw new Error('ultra effort is not supported by the pi backend');
+ if (!['bypassPermissions', 'acceptEdits', 'default', 'ask', 'auto', 'plan'].includes(value.permissionMode ?? '')) throw new Error('unsupported permissionMode');
+ if (value.agentBackend === 'claude-code' && value.permissionMode === 'auto') throw new Error('auto permissionMode is only supported by codex and pi');
+ if (value.agentBackend === 'codex' && (value.permissionMode === 'acceptEdits' || value.permissionMode === 'default')) throw new Error(`${value.permissionMode} permissionMode is not supported by codex`);
+ if (value.agentBackend === 'pi' && value.permissionMode !== 'bypassPermissions') throw new Error('headless pi requires bypassPermissions because no interactive approval channel is available');
+ if (typeof value.makerMemory !== 'boolean' || typeof value.nativeMemory !== 'boolean' || typeof value.projectContext !== 'boolean') throw new Error('makerMemory, nativeMemory and projectContext must be boolean');
+ if (value.agentBackend !== 'pi' && value.makerMemory && value.nativeMemory) throw new Error('makerMemory and nativeMemory are mutually exclusive for claude-code and codex');
+ if (value.containerSandbox !== undefined && typeof value.containerSandbox !== 'boolean') throw new Error('containerSandbox must be boolean');
+ if (value.unsafeAllowUnsandboxedBypass !== undefined && typeof value.unsafeAllowUnsandboxedBypass !== 'boolean') throw new Error('unsafeAllowUnsandboxedBypass must be boolean');
+ if (value.unsafeAllowUnsandboxedBypass && value.permissionMode !== 'bypassPermissions') throw new Error('unsafeAllowUnsandboxedBypass requires bypassPermissions');
+ if (value.parentProfile && (!value.changedDimensions || value.changedDimensions.length === 0)) throw new Error('derived profiles require changedDimensions');
+ if (!value.parentProfile && value.changedDimensions?.length) throw new Error('changedDimensions requires parentProfile');
+ if (value.compaction?.enabled && (!Number.isFinite(value.compaction.thresholdPct) || (value.compaction.thresholdPct ?? 0) < 50 || (value.compaction.thresholdPct ?? 0) > 95)) throw new Error('enabled compaction thresholdPct must be between 50 and 95');
+ if (value.throughputCap && (!Number.isFinite(value.throughputCap.outputTokensPerSecond) || value.throughputCap.outputTokensPerSecond <= 0 || value.throughputCap.enforcement !== 'external-proxy')) throw new Error('throughputCap requires a positive rate and external-proxy enforcement');
+ if (value.inputPolicy) {
+ if (typeof value.inputPolicy.attachments !== 'boolean' || value.inputPolicy.workspaceOnly !== true) throw new Error('inputPolicy requires attachments boolean and workspaceOnly=true');
+ if (value.inputPolicy.maxFiles !== undefined) positiveInteger(value.inputPolicy.maxFiles, 'inputPolicy.maxFiles');
+ if (value.inputPolicy.maxFileBytes !== undefined) positiveInteger(value.inputPolicy.maxFileBytes, 'inputPolicy.maxFileBytes');
+ }
+ if (value.mcpServers !== undefined) {
+ if (!Array.isArray(value.mcpServers)) throw new Error('mcpServers must be an array');
+ const ids = new Set<string>();
+ for (const [index, server] of value.mcpServers.entries()) {
+ if (!server || typeof server !== 'object') throw new Error(`mcpServers[${index}] must be an object`);
+ if (!PROFILE_ID_RE.test(server.id) || ['__proto__', 'constructor', 'prototype', 'cindy_memory'].includes(server.id)) throw new Error(`mcpServers[${index}].id is invalid or reserved`);
+ if (ids.has(server.id)) throw new Error(`duplicate MCP server id: ${server.id}`);
+ ids.add(server.id);
+ if (server.transport !== 'http') throw new Error('headless custom MCP supports streamable HTTP only');
+ validateEndpoint(server.url, `mcpServers[${index}].url`);
+ if (server.bearerTokenEnvVar && !ENV_NAME_RE.test(server.bearerTokenEnvVar)) throw new Error(`mcpServers[${index}].bearerTokenEnvVar is invalid`);
+ for (const [header, envName] of Object.entries(server.headerEnvVars ?? {})) {
+ if (!/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(header) || !ENV_NAME_RE.test(envName)) throw new Error(`mcpServers[${index}].headerEnvVars is invalid`);
+ }
+ if (server.startupTimeoutMs !== undefined) positiveInteger(server.startupTimeoutMs, `mcpServers[${index}].startupTimeoutMs`);
+ if (server.requestTimeoutMs !== undefined) positiveInteger(server.requestTimeoutMs, `mcpServers[${index}].requestTimeoutMs`);
+ }
+ }
+ if (value.nativeProviders !== undefined) {
+ if (value.agentBackend !== 'pi') throw new Error('nativeProviders are supported only by the pi backend');
+ if (!Array.isArray(value.nativeProviders) || value.nativeProviders.length === 0) throw new Error('nativeProviders must be a non-empty array');
+ const ids = new Set<string>();
+ for (const [index, provider] of value.nativeProviders.entries()) {
+ nonEmptyString(provider.id, `nativeProviders[${index}].id`);
+ nonEmptyString(provider.name, `nativeProviders[${index}].name`);
+ if (!PROFILE_ID_RE.test(provider.id) || provider.id === 'cindy' || ids.has(provider.id)) throw new Error(`nativeProviders[${index}].id is invalid, reserved or duplicated`);
+ ids.add(provider.id);
+ validateEndpoint(provider.baseUrl, `nativeProviders[${index}].baseUrl`);
+ if (!['anthropic-messages', 'openai-responses', 'openai-completions', 'google-generative-ai'].includes(provider.api)) throw new Error(`nativeProviders[${index}].api is invalid`);
+ if (provider.apiKeyEnvVar && !ENV_NAME_RE.test(provider.apiKeyEnvVar)) throw new Error(`nativeProviders[${index}].apiKeyEnvVar is invalid`);
+ if (!Array.isArray(provider.models) || provider.models.length === 0) throw new Error(`nativeProviders[${index}].models must be non-empty`);
+ for (const [modelIndex, model] of provider.models.entries()) {
+ nonEmptyString(model.id, `nativeProviders[${index}].models[${modelIndex}].id`);
+ positiveInteger(model.contextWindow, `nativeProviders[${index}].models[${modelIndex}].contextWindow`);
+ positiveInteger(model.maxTokens, `nativeProviders[${index}].models[${modelIndex}].maxTokens`);
+ }
+ }
+ if (!value.nativeProviders.some((provider) => provider.id === value.model?.provider && provider.models.some((model) => model.id === value.model?.requestedId))) throw new Error('selected Pi BYOM model must exist in nativeProviders');
+ }
+ if (value.piProjectSkills !== undefined) {
+ if (value.agentBackend !== 'pi') throw new Error('piProjectSkills are supported only by the pi backend');
+ if (typeof value.piProjectSkills.enabled !== 'boolean' || !Array.isArray(value.piProjectSkills.roots)) throw new Error('piProjectSkills requires enabled and roots');
+ if (value.piProjectSkills.enabled && value.piProjectSkills.roots.length === 0) throw new Error('enabled piProjectSkills requires at least one root');
+ for (const root of value.piProjectSkills.roots) {
+ nonEmptyString(root, 'piProjectSkills.roots[]');
+ if (path.isAbsolute(root) || root.split(/[\\/]/).includes('..')) throw new Error('piProjectSkills roots must be workspace-relative without parent traversal');
+ }
+ }
+ if (value.expectedSystemPromptDigest && !/^[a-f0-9]{64}$/.test(value.expectedSystemPromptDigest)) throw new Error('expectedSystemPromptDigest must be a lowercase sha256 digest');
+ return value as HeadlessProfile;
+}
+
+export function sha256(value: string | Buffer): string {
+ return createHash('sha256').update(value).digest('hex');
+}
+
+function canonicalize(value: unknown): unknown {
+ if (Array.isArray(value)) return value.map(canonicalize);
+ if (!value || typeof value !== 'object') return value;
+ return Object.fromEntries(Object.entries(value as Record<string, unknown>).sort(([a], [b]) => a.localeCompare(b)).map(([key, child]) => [key, canonicalize(child)]));
+}
+
+export function profileDigest(profile: HeadlessProfile): string {
+ return sha256(JSON.stringify(canonicalize(profile)));
+}
+
+function resolveProfileResource(value: string, profileDir: string, bundleRoot?: string): string {
+ if (!value.startsWith('bundle:')) return path.isAbsolute(value) ? value : path.resolve(profileDir, value);
+ if (!bundleRoot) throw new Error('bundle: profile resources require an explicit bundle root');
+ const logicalPath = value.slice('bundle:'.length);
+ if (!logicalPath || logicalPath.startsWith('/') || logicalPath.startsWith('\\') || /^[A-Za-z]:/.test(logicalPath)) {
+ throw new Error('bundle: resource must use a relative bundle path');
+ }
+ const segments = logicalPath.split(/[\\/]/);
+ if (segments.some((segment) => segment === '' || segment === '.' || segment === '..')) {
+ throw new Error('bundle: resource path contains an invalid segment');
+ }
+ const root = path.resolve(bundleRoot);
+ const resolved = path.resolve(root, ...segments);
+ if (resolved !== root && !resolved.startsWith(`${root}${path.sep}`)) throw new Error('bundle: resource escapes the bundle root');
+ return resolved;
+}
+
+export async function readProfile(profilePath: string, bundleRoot?: string): Promise<ResolvedProfile> {
+ const absolutePath = path.resolve(profilePath);
+ const rawProfile = await readFile(absolutePath, 'utf8');
+ const profile = validateProfile(JSON.parse(rawProfile));
+ const canonicalProfileDigest = profileDigest(profile);
+ const lockPath = path.join(path.dirname(absolutePath), 'profile.lock.json');
+ const lock = await readFile(lockPath, 'utf8').then((raw) => JSON.parse(raw) as Record<string, unknown>, (error: NodeJS.ErrnoException) => {
+ if (error.code === 'ENOENT') return null;
+ throw error;
+ });
+ const activeLock = lock?.profileFile === path.basename(absolutePath) ? lock : null;
+ if (activeLock) {
+ if (activeLock.schemaVersion !== 1 || activeLock.status !== 'frozen' || activeLock.profileId !== profile.id) throw new Error('profile lock identity is invalid');
+ if (activeLock.profileFileSha256 !== sha256(rawProfile)) throw new Error('profile file does not match profile.lock.json');
+ if (activeLock.profileDigest !== canonicalProfileDigest) throw new Error('profile digest does not match profile.lock.json');
+ if (activeLock.agentBinaryVersion !== profile.agentBinaryVersion) throw new Error('profile Agent version does not match profile.lock.json');
+ if (activeLock.cindyUpstreamCommit !== CINDY_UPSTREAM_COMMIT) throw new Error('profile lock Cindy upstream commit is stale');
+ }
+ // Profiles may travel with a release or checkout. Resolve relative binaries
+ // beside the profile instead of depending on the caller's current directory.
+ profile.agentBinaryPath = resolveProfileResource(profile.agentBinaryPath, path.dirname(absolutePath), bundleRoot);
+ const endpointOverride = profile.agentBackend === 'claude-code' || profile.agentBackend === 'pi'
+ ? process.env.CINDY_HEADLESS_BASE_URL ?? process.env.ANTHROPIC_BASE_URL
+ : undefined;
+ if (!profile.endpoint && endpointOverride) profile.endpoint = endpointOverride;
+ let systemPrompt: string | undefined;
+ let systemPromptDigest: string | null = null;
+ if (profile.systemPromptFile) {
+ const promptPath = resolveProfileResource(profile.systemPromptFile, path.dirname(absolutePath), bundleRoot);
+ systemPrompt = await readFile(promptPath, 'utf8');
+ systemPromptDigest = sha256(systemPrompt);
+ if (profile.expectedSystemPromptDigest && profile.expectedSystemPromptDigest !== systemPromptDigest) throw new Error('system prompt digest does not match expectedSystemPromptDigest');
+ } else if (profile.expectedSystemPromptDigest) {
+ throw new Error('expectedSystemPromptDigest requires systemPromptFile');
+ }
+ if (activeLock && activeLock.systemPromptDigest !== systemPromptDigest) throw new Error('system prompt does not match profile.lock.json');
+ return { profile, profilePath: absolutePath, systemPrompt, profileDigest: canonicalProfileDigest, systemPromptDigest };
+}
+
+export async function doctor(resolved: ResolvedProfile, outputDir?: string): Promise<{ ok: true; checks: Record<string, string | boolean> }> {
+ assertSafeExecutionProfile(resolved.profile);
+ await access(resolved.profile.agentBinaryPath);
+ const codexHome = process.env.CINDY_HEADLESS_CODEX_HOME ?? process.env.CODEX_HOME;
+ const nativeProviderAuth = resolved.profile.nativeProviders?.every((provider) => !provider.apiKeyEnvVar || Boolean(process.env[provider.apiKeyEnvVar]));
+ if ((resolved.profile.agentBackend === 'claude-code' || resolved.profile.agentBackend === 'pi') && !(process.env.CINDY_HEADLESS_API_KEY ?? process.env.ANTHROPIC_API_KEY) && !nativeProviderAuth) {
+ throw new Error('CINDY_HEADLESS_API_KEY or ANTHROPIC_API_KEY is required');
+ }
+ for (const server of resolved.profile.mcpServers ?? []) {
+ for (const envName of [server.bearerTokenEnvVar, ...Object.values(server.headerEnvVars ?? {})]) {
+ if (envName && !process.env[envName]) throw new Error(`custom MCP ${server.id} requires environment variable ${envName}`);
+ }
+ }
+ if (resolved.profile.agentBackend === 'codex' && !codexHome && !process.env.CINDY_CODEX_API_KEY) {
+ throw new Error('CINDY_HEADLESS_CODEX_HOME, CODEX_HOME, or gateway API key is required for codex');
+ }
+ if (codexHome) await access(path.resolve(codexHome));
+ const env = resolved.profile.agentBackend === 'codex' && codexHome
+ ? { ...process.env, CODEX_HOME: path.resolve(codexHome) }
+ : process.env;
+ const versionResult = await execFileAsync(resolved.profile.agentBinaryPath, ['--version'], { timeout: 30_000, env });
+ const observedVersion = `${versionResult.stdout} ${versionResult.stderr}`.trim();
+ if (!observedVersion.includes(resolved.profile.agentBinaryVersion)) throw new Error(`agent binary version mismatch: expected ${resolved.profile.agentBinaryVersion}, observed ${observedVersion}`);
+ if (resolved.profile.agentBackend === 'codex') {
+ if (!process.env.CINDY_CODEX_API_KEY) {
+ const login = await execFileAsync(resolved.profile.agentBinaryPath, ['login', 'status'], { timeout: 30_000, env });
+ if (!`${login.stdout} ${login.stderr}`.toLowerCase().includes('logged in')) throw new Error('codex login status did not report an authenticated account');
+ }
+ }
+ if (outputDir) {
+ await mkdir(path.resolve(outputDir), { recursive: true });
+ await access(path.resolve(outputDir));
+ }
+ const compatibility = compatibilityReport(resolved.profile);
+ const endpointConfigured = resolved.profile.agentBackend === 'claude-code' || resolved.profile.agentBackend === 'pi'
+ ? Boolean(resolved.profile.endpoint)
+ : Boolean(process.env.CINDY_CODEX_BASE_URL ?? process.env.CINDY_HEADLESS_BASE_URL);
+ return { ok: true, checks: { profile: true, contractVersion: String(compatibility.contractVersion), transport: compatibility.transport, securityIsolation: compatibility.security.safeForUntrustedWorkloads, agentBinary: resolved.profile.agentBinaryPath, agentBinaryVersion: observedVersion, authEnvironment: true, endpointConfigured, outputDirectory: outputDir ? path.resolve(outputDir) : 'not-requested', systemPromptDigest: resolved.systemPromptDigest ?? 'none' } };
+}
+
+export function capabilities(profile: HeadlessProfile): ProfileCapabilities {
+ const codex = profile.agentBackend === 'codex';
+ const pi = profile.agentBackend === 'pi';
+ return { schemaVersion: 1, contractVersion: compatibilityReport(profile).contractVersion, profileId: profile.id, agentBackend: profile.agentBackend, supportedModelIds: [...profile.supportedModelIds], supportedPermissionModes: pi ? ['bypassPermissions'] : codex ? ['bypassPermissions', 'ask', 'auto', 'plan'] : ['bypassPermissions', 'acceptEdits', 'default', 'ask', 'plan'], projectContext: profile.projectContext, makerMemory: profile.makerMemory, nativeMemory: profile.nativeMemory, nativeToolSurface: pi ? 'pi-rpc-default' : codex ? 'codex-app-server-default' : 'claude-code-default', cindyMcpProviders: profile.makerMemory ? ['cindy_memory'] : [], desktopOnlyProviders: [], multiTurnSession: true, artifactContract: ['identity.json', 'config.json', 'trace.raw.jsonl', 'trace.jsonl', 'stderr.log', 'usage.json', 'result.json'], attachments: profile.inputPolicy?.attachments ?? false, customMcpServers: profile.mcpServers?.map((server) => server.id) ?? [], byomProviders: profile.nativeProviders?.map((provider) => provider.id) ?? [], piProjectSkills: profile.piProjectSkills?.enabled ?? false };
+}
+
+const ENV_NAME_RE = /^[A-Z_][A-Z0-9_]*$/;
+const PROFILE_ID_RE = /^[a-z0-9][a-z0-9_-]{0,39}$/;
+
+function positiveInteger(value: unknown, field: string): asserts value is number {
+ if (!Number.isInteger(value) || Number(value) <= 0) throw new Error(`${field} must be a positive integer`);
+}
+
+function validateEndpoint(raw: unknown, field: string): void {
+ nonEmptyString(raw, field);
+ const url = new URL(raw);
+ const loopback = url.hostname === '127.0.0.1' || url.hostname === '[::1]' || url.hostname === 'localhost';
+ if (url.username || url.password || (url.protocol !== 'https:' && !(url.protocol === 'http:' && loopback))) {
+ throw new Error(`${field} must be HTTPS or loopback HTTP and must not contain credentials`);
+ }
+}
diff --git a/apps/cindy-headless/src/project-context.test.ts b/apps/cindy-headless/src/project-context.test.ts
new file mode 100644
index 0000000000..f3b51966b6
--- /dev/null
+++ b/apps/cindy-headless/src/project-context.test.ts
@@ -0,0 +1,23 @@
+import { mkdtemp, mkdir, writeFile } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import { describe, expect, it } from 'vitest';
+import { readProjectContext } from './project-context.js';
+
+describe('project context parity', () => {
+ it('wraps the same TOC source used by Cindy Desktop', async () => {
+ const root = await mkdtemp(path.join(os.tmpdir(), 'headless-project-context-'));
+ const knowledge = path.join(root, '.cindy', 'project-knowledge');
+ await mkdir(knowledge, { recursive: true });
+ await writeFile(path.join(knowledge, 'TOC.md'), '# Project\n\n- [Core](modules/core.md)\n');
+ const result = await readProjectContext(root, true);
+ expect(result.injected).toBe(true);
+ expect(result.content).toBe('<project-context-toc>\n# Project\n\n- [Core](modules/core.md)\n</project-context-toc>');
+ expect(result.digest).toMatch(/^[a-f0-9]{64}$/);
+ });
+
+ it('does not read project knowledge when the profile disables it', async () => {
+ const result = await readProjectContext('missing', false);
+ expect(result).toMatchObject({ injected: false, reason: 'disabled', digest: null });
+ });
+});
diff --git a/apps/cindy-headless/src/project-context.ts b/apps/cindy-headless/src/project-context.ts
new file mode 100644
index 0000000000..9dbd050d27
--- /dev/null
+++ b/apps/cindy-headless/src/project-context.ts
@@ -0,0 +1,25 @@
+import { readFile } from 'node:fs/promises';
+import path from 'node:path';
+import { sha256 } from './profile.js';
+
+export interface ProjectContextSnapshot {
+ injected: boolean;
+ reason?: 'disabled' | 'no-toc-file' | 'empty-toc-file';
+ content?: string;
+ tocPath: string;
+ digest: string | null;
+}
+
+export async function readProjectContext(workingDir: string, enabled: boolean): Promise<ProjectContextSnapshot> {
+ const tocPath = path.join(path.resolve(workingDir), '.cindy', 'project-knowledge', 'TOC.md');
+ if (!enabled) return { injected: false, reason: 'disabled', tocPath, digest: null };
+ let raw: string;
+ try {
+ raw = await readFile(tocPath, 'utf8');
+ } catch {
+ return { injected: false, reason: 'no-toc-file', tocPath, digest: null };
+ }
+ const trimmed = raw.trim();
+ if (!trimmed) return { injected: false, reason: 'empty-toc-file', tocPath, digest: sha256(raw) };
+ return { injected: true, content: `<project-context-toc>\n${trimmed}\n</project-context-toc>`, tocPath, digest: sha256(raw) };
+}
diff --git a/apps/cindy-headless/src/prompt-parity.test.ts b/apps/cindy-headless/src/prompt-parity.test.ts
new file mode 100644
index 0000000000..df87618320
--- /dev/null
+++ b/apps/cindy-headless/src/prompt-parity.test.ts
@@ -0,0 +1,31 @@
+import { readFile } from 'node:fs/promises';
+import path from 'node:path';
+import { describe, expect, it } from 'vitest';
+
+const composePrompt = (...parts: string[]) => parts
+ .map((part) => part.replace(/\r\n?/g, '\n').trim())
+ .filter(Boolean)
+ .join('\n\n') + '\n';
+
+describe('production prompt parity', () => {
+ it('matches the Desktop Claude host prompt after cross-platform newline normalization', async () => {
+ const headless = await readFile(path.resolve('profiles/cindy-production-claude/prompt.md'), 'utf8');
+ const desktopHost = await readFile(path.resolve('../../apps/desktop/src/main/maker-host/host-system-prompt.md'), 'utf8');
+ const desktopClaude = await readFile(path.resolve('../../apps/desktop/src/main/maker-host/claude-system-prompt.md'), 'utf8');
+ expect(headless.replace(/\r\n?/g, '\n')).toBe(composePrompt(desktopHost, desktopClaude));
+ });
+
+ it('matches the Desktop Codex host prompt after cross-platform newline normalization', async () => {
+ const headless = await readFile(path.resolve('profiles/cindy-production-codex/prompt.md'), 'utf8');
+ const desktopHost = await readFile(path.resolve('../../apps/desktop/src/main/maker-host/host-system-prompt.md'), 'utf8');
+ const desktopCodex = await readFile(path.resolve('../../apps/desktop/src/main/maker-host/codex-system-prompt.md'), 'utf8');
+ expect(headless.replace(/\r\n?/g, '\n')).toBe(composePrompt(desktopHost, desktopCodex));
+ });
+
+ it('matches the Desktop Pi host prompt after cross-platform newline normalization', async () => {
+ const headless = await readFile(path.resolve('profiles/cindy-production-pi/prompt.md'), 'utf8');
+ const desktopHost = await readFile(path.resolve('../../apps/desktop/src/main/maker-host/host-system-prompt.md'), 'utf8');
+ const desktopPi = await readFile(path.resolve('../../apps/desktop/src/main/maker-host/pi-system-prompt.md'), 'utf8');
+ expect(headless.replace(/\r\n?/g, '\n')).toBe(composePrompt(desktopHost, desktopPi));
+ });
+});
diff --git a/apps/cindy-headless/src/raw-modules.d.ts b/apps/cindy-headless/src/raw-modules.d.ts
new file mode 100644
index 0000000000..7e490d0fa9
--- /dev/null
+++ b/apps/cindy-headless/src/raw-modules.d.ts
@@ -0,0 +1,11 @@
+declare module '*?raw' {
+ const content: string;
+ export default content;
+}
+
+interface ImportMeta {
+ glob<T = unknown>(
+ pattern: string | string[],
+ options?: { eager?: boolean; query?: string; import?: string },
+ ): Record<string, T>;
+}
diff --git a/apps/cindy-headless/src/session-storage.test.ts b/apps/cindy-headless/src/session-storage.test.ts
new file mode 100644
index 0000000000..e68ed49703
--- /dev/null
+++ b/apps/cindy-headless/src/session-storage.test.ts
@@ -0,0 +1,23 @@
+import { mkdtemp } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import { describe, expect, it } from 'vitest';
+import { SqliteSessionStorage } from './session-storage.js';
+
+describe('SqliteSessionStorage', () => {
+ it('persists session metadata and clears the expected SDK id atomically', async () => {
+ const dir = await mkdtemp(path.join(os.tmpdir(), 'cindy-headless-session-'));
+ const file = path.join(dir, 'sessions.sqlite');
+ const first = new SqliteSessionStorage(file);
+ await first.create({ id: 'session-1', agentKind: 'codex', workDir: dir, title: 'test', model: 'gpt-test', sdkSessionId: 'sdk-1' });
+ first.close();
+
+ const reopened = new SqliteSessionStorage(file);
+ expect((await reopened.get('session-1'))?.sdkSessionId).toBe('sdk-1');
+ expect(await reopened.compareAndClearSdkSessionId('session-1', 'wrong')).toBe(false);
+ expect(await reopened.compareAndClearSdkSessionId('session-1', 'sdk-1')).toBe(true);
+ expect(await reopened.compareAndClearSdkSessionId('session-1', 'sdk-1')).toBe(false);
+ expect((await reopened.get('session-1'))?.sdkSessionId).toBeUndefined();
+ reopened.close();
+ });
+});
diff --git a/apps/cindy-headless/src/session-storage.ts b/apps/cindy-headless/src/session-storage.ts
new file mode 100644
index 0000000000..f3f81bfbd7
--- /dev/null
+++ b/apps/cindy-headless/src/session-storage.ts
@@ -0,0 +1,70 @@
+import type { SessionMeta, SessionStorage } from '@cindy/maker-core';
+import type Database from 'better-sqlite3';
+import { openHeadlessSqlite } from './sqlite.js';
+
+interface SessionRow {
+ id: string;
+ data: string;
+}
+
+export class SqliteSessionStorage implements SessionStorage {
+ private readonly db: Database.Database;
+
+ constructor(filePath: string) {
+ this.db = openHeadlessSqlite(filePath);
+ this.db.pragma('journal_mode = WAL');
+ this.db.pragma('busy_timeout = 5000');
+ this.db.exec(`
+ CREATE TABLE IF NOT EXISTS headless_sessions (
+ id TEXT PRIMARY KEY,
+ data TEXT NOT NULL,
+ updated_at INTEGER NOT NULL
+ )
+ `);
+ }
+
+ async create(meta: Omit<SessionMeta, 'createdAt' | 'updatedAt'>): Promise<SessionMeta> {
+ const now = Date.now();
+ const row: SessionMeta = { ...meta, createdAt: now, updatedAt: now };
+ this.db.prepare('INSERT INTO headless_sessions (id, data, updated_at) VALUES (?, ?, ?)').run(row.id, JSON.stringify(row), now);
+ return row;
+ }
+
+ async get(id: string): Promise<SessionMeta | null> {
+ const row = this.db.prepare('SELECT id, data FROM headless_sessions WHERE id = ?').get(id) as SessionRow | undefined;
+ return row ? JSON.parse(row.data) as SessionMeta : null;
+ }
+
+ async list(): Promise<SessionMeta[]> {
+ const rows = this.db.prepare('SELECT id, data FROM headless_sessions ORDER BY updated_at DESC').all() as unknown as SessionRow[];
+ return rows.map((row) => JSON.parse(row.data) as SessionMeta);
+ }
+
+ async update(id: string, patch: Partial<SessionMeta>): Promise<SessionMeta> {
+ const current = await this.get(id);
+ if (!current) throw new Error(`unknown session ${id}`);
+ const row: SessionMeta = { ...current, ...patch, id: current.id, updatedAt: Date.now() };
+ this.db.prepare('UPDATE headless_sessions SET data = ?, updated_at = ? WHERE id = ?').run(JSON.stringify(row), row.updatedAt, id);
+ return row;
+ }
+
+ async compareAndClearSdkSessionId(id: string, expectedSdkSessionId: string): Promise<boolean> {
+ return this.db.transaction(() => {
+ const stored = this.db.prepare('SELECT id, data FROM headless_sessions WHERE id = ?').get(id) as SessionRow | undefined;
+ if (!stored) return false;
+ const current = JSON.parse(stored.data) as SessionMeta;
+ if (current.sdkSessionId !== expectedSdkSessionId) return false;
+ const row: SessionMeta = { ...current, sdkSessionId: undefined, updatedAt: Date.now() };
+ const update = this.db.prepare('UPDATE headless_sessions SET data = ?, updated_at = ? WHERE id = ?').run(JSON.stringify(row), row.updatedAt, id);
+ return update.changes === 1;
+ })();
+ }
+
+ async delete(id: string): Promise<void> {
+ this.db.prepare('DELETE FROM headless_sessions WHERE id = ?').run(id);
+ }
+
+ close(): void {
+ this.db.close();
+ }
+}
diff --git a/apps/cindy-headless/src/sqlite.ts b/apps/cindy-headless/src/sqlite.ts
new file mode 100644
index 0000000000..dceb7c496c
--- /dev/null
+++ b/apps/cindy-headless/src/sqlite.ts
@@ -0,0 +1,34 @@
+import { DatabaseSync } from 'node:sqlite';
+import type Database from 'better-sqlite3';
+
+/** Adapter for Maker Core's small better-sqlite3-compatible surface. */
+export function openHeadlessSqlite(filePath: string): Database.Database {
+ const database = new DatabaseSync(filePath);
+ const compatible = {
+ exec(sql: string) { database.exec(sql); },
+ pragma(sql: string) { database.exec(`PRAGMA ${sql}`); },
+ prepare(sql: string) {
+ const statement = database.prepare(sql);
+ return {
+ run(...params: unknown[]) { return statement.run(...params as never[]); },
+ get(...params: unknown[]) { return statement.get(...params as never[]); },
+ all(...params: unknown[]) { return statement.all(...params as never[]); },
+ };
+ },
+ transaction<T>(fn: (...args: never[]) => T) {
+ return (...args: never[]) => {
+ database.exec('BEGIN');
+ try {
+ const result = fn(...args);
+ database.exec('COMMIT');
+ return result;
+ } catch (error) {
+ database.exec('ROLLBACK');
+ throw error;
+ }
+ };
+ },
+ close() { database.close(); },
+ } as unknown as Database.Database;
+ return compatible;
+}
diff --git a/apps/cindy-headless/src/turn-completion.test.ts b/apps/cindy-headless/src/turn-completion.test.ts
new file mode 100644
index 0000000000..d29a6d3fad
--- /dev/null
+++ b/apps/cindy-headless/src/turn-completion.test.ts
@@ -0,0 +1,67 @@
+import path from 'node:path';
+import { describe, expect, it, vi } from 'vitest';
+import { Session, type AgentEvent, type AgentSessionHandle } from '@cindy/maker-core';
+import { isHeadlessTerminalEvent } from './host.js';
+
+describe('Headless observer with the real Session event lifecycle', () => {
+ it.each(['claude-code', 'codex'] as const)('waits for %s continuation and then accepts a result-only next turn', async (agentKind) => {
+ const pending: Array<AgentEvent | null> = [];
+ let waiter: ((event: AgentEvent | null) => void) | undefined;
+ let running = false;
+ const claims = new Map<number, 'awaiting' | 'active' | 'cancelled'>();
+ const deliver = (event: AgentEvent | null) => {
+ if (waiter) { const resolve = waiter; waiter = undefined; resolve(event); }
+ else pending.push(event);
+ };
+ const handle = {
+ id: 'headless-test-thread', agentKind, model: 'fixture-model',
+ async send() { if (running) throw new Error('SESSION_RUNNING'); running = true; },
+ async steer() {}, async abort() { running = false; },
+ async close() { running = false; deliver(null); },
+ async *events() {
+ for (;;) {
+ const event = pending.length ? pending.shift()! : await new Promise<AgentEvent | null>((resolve) => { waiter = resolve; });
+ if (event === null) return;
+ yield event;
+ }
+ },
+ isTurnRunning: () => running,
+ setInteractionResolver() {},
+ beginTurnContinuationWait: (id?: number) => id === undefined ? null : claims.get(id) ?? null,
+ getUsageSnapshot: () => ({ tokenUsage: 0, contextTokens: 0, contextWindow: 0, costUsd: 0 }),
+ } as unknown as AgentSessionHandle;
+ const logger = { trace() {}, debug() {}, info() {}, warn() {}, error() {}, fatal() {}, child() { return logger; } };
+ const session = new Session({ id: 'headless-test-session', agentKind, workDir: path.resolve('fixture-repo'), handle, capabilities: {} as never, logger });
+ const seen: AgentEvent[] = [];
+ const terminals: AgentEvent[] = [];
+ let attempt = 1;
+ session.onEvent((event) => {
+ seen.push(event);
+ if (isHeadlessTerminalEvent(event, session, attempt)) terminals.push(event);
+ });
+ const emit = async (event: AgentEvent, keepRunning = true) => {
+ if (!keepRunning) running = false;
+ const count = seen.length;
+ deliver(event);
+ await vi.waitFor(() => expect(seen.length).toBeGreaterThan(count));
+ };
+ try {
+ expect(await session.send('first', { turnAttemptToken: attempt })).toEqual({ accepted: true });
+ claims.set(7, 'awaiting');
+ await emit({ type: 'done', data: {}, turnContinuationId: 7 });
+ await emit({ type: 'status', data: { isRunning: false } });
+ expect(terminals).toHaveLength(0);
+ await emit({ type: 'text', data: { text: 'continuation output', isFinal: true } });
+ claims.set(7, 'active');
+ await emit({ type: 'done', data: {} }, false);
+ expect(terminals).toHaveLength(1);
+ expect(seen.some((event) => event.type === 'text' && event.turnAttemptToken === 1)).toBe(true);
+ attempt = 2;
+ await emit({ type: 'status', data: { isRunning: false } }, false);
+ expect(terminals).toHaveLength(1);
+ expect(await session.send('second', { turnAttemptToken: attempt })).toEqual({ accepted: true });
+ await emit({ type: 'done', data: {} }, false);
+ expect(terminals.map((event) => event.turnAttemptToken)).toEqual([1, 2]);
+ } finally { await session.close(); }
+ });
+});
diff --git a/apps/cindy-headless/src/usage.test.ts b/apps/cindy-headless/src/usage.test.ts
new file mode 100644
index 0000000000..52d3973328
--- /dev/null
+++ b/apps/cindy-headless/src/usage.test.ts
@@ -0,0 +1,34 @@
+import { describe, expect, it } from 'vitest';
+import { createUsageArtifact, USAGE_SCHEMA_VERSION } from './usage.js';
+
+describe('usage artifact schema', () => {
+ it('keeps provider usage and session snapshot separate', () => {
+ const artifact = createUsageArtifact({
+ rawProviderUsage: { input_tokens: 3 },
+ normalizedUsage: { inputTokens: 3, cacheReadTokens: 10, cacheCreationTokens: 5, outputTokens: 7, costUsd: 0.25 },
+ sessionSnapshot: { tokenUsage: 20, contextTokens: 18, contextWindow: 1000, costUsd: 0.25 },
+ });
+ expect(artifact.schemaVersion).toBe(USAGE_SCHEMA_VERSION);
+ expect(artifact.usageStatus).toBe('COMPLETE');
+ expect(artifact.usageCompleteness).toBe('exact');
+ expect(artifact.normalizedUsage).toEqual({ inputTokens: 3, cacheReadTokens: 10, cacheCreationTokens: 5, outputTokens: 7, costUsd: 0.25 });
+ expect(artifact.sessionSnapshot.contextTokens).toBe(18);
+ });
+
+ it('records incomplete usage without turning it into a precise zero', () => {
+ const artifact = createUsageArtifact({
+ rawProviderUsage: null,
+ normalizedUsage: { inputTokens: 0, cacheReadTokens: 0, cacheCreationTokens: 0, outputTokens: 0, costUsd: 0 },
+ sessionSnapshot: { tokenUsage: 128, contextTokens: 128, contextWindow: 1000, costUsd: 0 },
+ usageStatus: 'PARTIAL',
+ usageSource: ['session-snapshot'],
+ missingFields: ['inputTokens', 'outputTokens', 'costUsd'],
+ termination: 'HEADLESS_DEADLINE',
+ observedTokenTotal: 128,
+ });
+ expect(artifact.usageStatus).toBe('PARTIAL');
+ expect(artifact.usageCompleteness).toBe('lower-bound');
+ expect(artifact.observedTokenTotal).toBe(128);
+ expect(artifact.missingFields).toContain('costUsd');
+ });
+});
diff --git a/apps/cindy-headless/src/usage.ts b/apps/cindy-headless/src/usage.ts
new file mode 100644
index 0000000000..92487b9dd8
--- /dev/null
+++ b/apps/cindy-headless/src/usage.ts
@@ -0,0 +1,52 @@
+export const USAGE_SCHEMA_VERSION = 2 as const;
+export type UsageStatus = 'COMPLETE' | 'PARTIAL' | 'MISSING';
+export type UsageCompleteness = 'exact' | 'lower-bound' | 'incomplete';
+
+export interface NormalizedUsage {
+ inputTokens: number;
+ cacheReadTokens: number;
+ cacheCreationTokens: number;
+ outputTokens: number;
+ costUsd: number;
+}
+
+export interface UsageArtifact {
+ schemaVersion: typeof USAGE_SCHEMA_VERSION;
+ rawProviderUsage: Record<string, unknown> | null;
+ normalizedUsage: NormalizedUsage;
+ usageStatus: UsageStatus;
+ usageCompleteness: UsageCompleteness;
+ usageSource: string[];
+ missingFields: string[];
+ termination: string | null;
+ observedTokenTotal: number | null;
+ sessionSnapshot: {
+ tokenUsage: number;
+ contextTokens: number;
+ contextWindow: number;
+ costUsd: number;
+ };
+}
+
+export function createUsageArtifact(input: {
+ rawProviderUsage: Record<string, unknown> | null;
+ normalizedUsage: NormalizedUsage;
+ sessionSnapshot: UsageArtifact['sessionSnapshot'];
+ usageStatus?: UsageStatus;
+ usageCompleteness?: UsageCompleteness;
+ usageSource?: string[];
+ missingFields?: string[];
+ termination?: string | null;
+ observedTokenTotal?: number | null;
+}): UsageArtifact {
+ return {
+ ...input,
+ schemaVersion: USAGE_SCHEMA_VERSION,
+ usageStatus: input.usageStatus ?? 'COMPLETE',
+ usageCompleteness: input.usageCompleteness ?? (input.usageStatus === 'PARTIAL' ? 'lower-bound' : input.usageStatus === 'MISSING' ? 'incomplete' : 'exact'),
+ usageSource: input.usageSource ?? ['provider'],
+ missingFields: input.missingFields ?? [],
+ termination: input.termination ?? null,
+ observedTokenTotal: input.observedTokenTotal ?? null,
+ };
+}
diff --git a/apps/cindy-headless/tsconfig.json b/apps/cindy-headless/tsconfig.json
new file mode 100644
index 0000000000..6e321dbbed
--- /dev/null
+++ b/apps/cindy-headless/tsconfig.json
@@ -0,0 +1,15 @@
+{
+ "compilerOptions": {
+ "target": "ESNext",
+ "module": "ESNext",
+ "moduleResolution": "bundler",
+ "strict": true,
+ "skipLibCheck": true,
+ "esModuleInterop": true,
+ "resolveJsonModule": true,
+ "noEmit": true,
+ "isolatedModules": true,
+ "sourceMap": true
+ },
+ "include": ["src/**/*.ts"]
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 9547b79fa4..249955f78e 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -71,6 +71,31 @@ importers:
specifier: ^8.18.3
version: 8.21.1
+ apps/cindy-headless:
+ dependencies:
+ '@cindy/maker-core':
+ specifier: workspace:*
+ version: link:../../packages/maker-core
+ '@cindy/mcps':
+ specifier: workspace:*
+ version: link:../../packages/lizi-mcps
+ '@modelcontextprotocol/sdk':
+ specifier: ^1.29.0
+ version: 1.29.0([email protected])
+ devDependencies:
+ '@types/node':
+ specifier: ^22.0.0
+ version: 22.20.1
+ esbuild:
+ specifier: ^0.28.1
+ version: 0.28.1
+ typescript:
+ specifier: ^5.7.0
+ version: 5.9.3
+ vitest:
+ specifier: ^3.2.4
+
apps/desktop:
dependencies:
'@babel/parser':
@@ -15698,6 +15723,14 @@ snapshots:
chai: 5.3.3
tinyrainbow: 2.0.0
+ dependencies:
+ '@vitest/spy': 3.2.7
+ estree-walker: 3.0.3
+ magic-string: 0.30.21
+ optionalDependencies:
+
dependencies:
'@vitest/spy': 3.2.7
@@ -22531,6 +22564,27 @@ snapshots:
'@types/unist': 3.0.3
vfile-message: 4.0.3
+ dependencies:
+ cac: 6.7.14
+ debug: 4.4.3
+ es-module-lexer: 1.7.0
+ pathe: 2.0.3
+ transitivePeerDependencies:
+ - '@types/node'
+ - jiti
+ - less
+ - lightningcss
+ - sass
+ - sass-embedded
+ - stylus
+ - sugarss
+ - supports-color
+ - terser
+ - tsx
+ - yaml
+
dependencies:
cac: 6.7.14
@@ -22594,6 +22648,23 @@ snapshots:
- tsx
- yaml
+ dependencies:
+ esbuild: 0.25.12
+ fdir: 6.5.0([email protected])
+ picomatch: 4.0.5
+ postcss: 8.5.19
+ rollup: 4.62.2(patch_hash=7ef53ca5a7e44d41cdbc0e10ea0475c928bddf13ad769cf15628579d0c4bfc98)
+ tinyglobby: 0.2.17
+ optionalDependencies:
+ '@types/node': 22.20.1
+ fsevents: 2.3.3
+ jiti: 2.7.0
+ lightningcss: 1.33.0
+ terser: 5.49.0
+ tsx: 4.23.1
+ yaml: 2.9.0
+
dependencies:
esbuild: 0.25.12
@@ -22644,6 +22715,49 @@ snapshots:
tsx: 4.23.1
yaml: 2.9.0
+ dependencies:
+ '@types/chai': 5.2.3
+ '@vitest/expect': 3.2.7
+ '@vitest/pretty-format': 3.2.7
+ '@vitest/runner': 3.2.7
+ '@vitest/snapshot': 3.2.7
+ '@vitest/spy': 3.2.7
+ '@vitest/utils': 3.2.7
+ chai: 5.3.3
+ debug: 4.4.3
+ expect-type: 1.4.0
+ magic-string: 0.30.21
+ pathe: 2.0.3
+ picomatch: 4.0.5
+ std-env: 3.10.0
+ tinybench: 2.9.0
+ tinyexec: 0.3.2
+ tinyglobby: 0.2.17
+ tinypool: 1.1.1
+ tinyrainbow: 2.0.0
+ why-is-node-running: 2.3.0
+ optionalDependencies:
+ '@types/debug': 4.1.13
+ '@types/node': 22.20.1
+ jsdom: 29.1.1(@noble/[email protected])
+ transitivePeerDependencies:
+ - jiti
+ - less
+ - lightningcss
+ - msw
+ - sass
+ - sass-embedded
+ - stylus
+ - sugarss
+ - supports-color
+ - terser
+ - tsx
+ - yaml
+
dependencies:
'@types/chai': 5.2.3
diff --git a/scripts/test-workspaces.config.mjs b/scripts/test-workspaces.config.mjs
index 61c68a13da..eaae4f510c 100644
--- a/scripts/test-workspaces.config.mjs
+++ b/scripts/test-workspaces.config.mjs
@@ -129,6 +129,7 @@ const requiredUnitWorkspace = (name, cwd, { workers = 1, execution, pool, exclud
export default {
workspaces: [
+ requiredUnitWorkspace('cindy-headless', 'apps/cindy-headless'),
{
name: 'desktop',
cwd: 'apps/desktop',