Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
make AGENTS.md the canonical agent-instructions file (#4852)
[._.]/ Adam Eivydf617854a801
diff --git a/.claude/skills/portos-add-page/SKILL.md b/.claude/skills/portos-add-page/SKILL.mdindex 0722f30d04..5d34bdb238 100644--- a/.claude/skills/portos-add-page/SKILL.md+++ b/.claude/skills/portos-add-page/SKILL.md@@ -31,7 +31,7 @@ Fail-fast guards at module load catch missing fields, non-slash paths, and dupli## Also required for a new page-See `client/src/CLAUDE.md` for the two client-side rules that go with this:+See `client/src/AGENTS.md` for the two client-side rules that go with this:- **ID-based deep linking** — any selection lives in the URL via a route param, never in local `useState`.- **Layout scroll mode** — decide whether the route belongs in `Layout.jsx`'s `isFullWidth` list (page owns its own `overflow-y-auto`) or takes the default scrolling+padded `<main>`.diff --git a/AGENTS.md b/AGENTS.mddeleted file mode 120000index 681311eb9c..0000000000--- a/AGENTS.md+++ /dev/null@@ -1 +0,0 @@-CLAUDE.md\ No newline at end of filediff --git a/AGENTS.md b/AGENTS.mdnew file mode 100644index 0000000000..800ad9fae6--- /dev/null+++ b/AGENTS.md@@ -0,0 +1,209 @@+# AGENTS.md++This file provides guidance to every AI coding agent working in this repository — Claude Code, Codex, Antigravity (`agy`), grok, cursor-agent, OpenCode, and the local-model providers that front them.++`AGENTS.md` is the canonical file. The `CLAUDE.md` beside it is a one-line `@AGENTS.md` import, because Claude Code's memory discovery hardcodes `CLAUDE.md` and has no configurable filename — an import rather than a symlink so it survives a Windows checkout without symlink support, and so a CLI that reads both names doesn't ingest the body twice. Both files exist at the root and at each nested location below. **Edit `AGENTS.md`; never put content in a `CLAUDE.md`.**++## Commands++Non-obvious invocations only — everything else is in `package.json` scripts.++```bash+npm run install:all # includes git submodule update --init --recursive++# Root `npm test` runs both workspaces in sequence (server, then client). Run them+# per workspace to scope to one — both are Vitest, with different environments:+cd server && npm test # Vitest (node) — ALSO globs ../scripts, ../lib, ../autofixer+cd client && npm test # Vitest (jsdom) — component/unit tests+# No NODE_ENV prefix needed: server/vitest.config.js FORCES NODE_ENV=test (#4554).+# Vitest only defaults it when unset, and PortOS runs under PM2 with+# NODE_ENV=development — a suite run that inherits that aims at the real Postgres.+npm run test:db # DB-backed suites → portos_test ONLY (see Security Model)+```++## Security Model++**Trust model (within one install).** Each PortOS install serves exactly one human user, on a private network behind Tailscale VPN, never exposed to the public internet. Within an install there is one server process and one user — so concurrent *request* races, mutex locking on file I/O, and atomic write patterns are unnecessary as defenses against competing actors and should not be added or flagged as concerns. Simple re-entrancy guards (per-account sync locks preventing duplicate in-flight operations; serializing two write paths that mutate the same record) are fine and expected. PortOS intentionally omits CORS restrictions, rate limiting, and full concurrency controls by default — non-issues for a single-user private-network deployment. Do not add them or flag their absence. **"Single-user" means: do not defend against multiple competing humans inside one install. It does NOT mean "assume only one install exists."**++**Authentication and HTTPS exist, but are OPT-IN and OFF by default.** Do not assume they are absent:++- **Auth** — an optional instance password (`server/services/auth.js`, enforced by `server/lib/authGate.js`) gates all of `/api/*` and `/data/*` when set, with a small always-public set (`/api/auth/status`, `/api/system/health`). Peers reach a password-gated instance via a per-peer Basic credential on the peer record, attached to every outbound hop by `peerFetch` (`server/lib/peerHttpClient.js`).+- **HTTPS** — provisioned by `npm run setup:cert`; `:5555` flips to TLS with a loopback-only HTTP mirror on `:5553`. Peer hops set `rejectUnauthorized: false` ("Tailnet is the trust boundary") — between two tailnet nodes WireGuard already supplies mutual auth, but a non-tailnet peer (plain LAN IP / non-`.ts.net` host, see `peerRequiresTailscale()`) gets no server authentication.++Because both are off by default, **never treat "the password is set" as an available guarantee** when designing a feature — gate on it explicitly, or design for the default posture. **PII must not ride the federation layer at all** — see ADR [privacy records machine-local](docs/decisions/2026-08-08-privacy-records-machine-local.md). That rule governs *records* and *status/capability payloads*; its one scoped carve-out is a submitted job body carrying the conditioning an allowlisted peer is being asked to render — the prompt (ADR [federated visual prompts](docs/decisions/2026-08-20-federated-visual-prompts.md)), and, under the same gate, lyrics and conditioning images (ADR [conditioning crosses to an allowlisted peer](docs/decisions/2026-08-22-federated-media-input-assets.md), which also records what stays refused: model weights and multi-step chain state).++**Distribution model (across installs).** PortOS is distributed software: many independent people each run their own install, on their own machine(s), each upgrading on their own schedule — and a single user commonly runs **several machines federated as sync peers**. Backward/forward compatibility across installs and versions is first-class, NOT optional:++- **Never delete or skip migration / compatibility code on the grounds that "there's only one install."** There isn't — other people and other machines run this code and update it independently.+- On-disk format changes need a migration in `scripts/migrations/` (applied-list tracked per install in `data/migrations.applied.json`). Seed files must ship in `data.reference/`.+- Prompt-default changes need a `PROMPT_VERSIONS` bump AND the prior default preserved in `PREVIOUS_DEFAULT_PROMPTS`, so other installs recognize their stored prompt and auto-upgrade it (`server/services/taskSchedule.js`).+- Cross-machine sync payloads stay version-gated (`server/lib/schemaVersions.js`) so a newer peer can't corrupt an older one.+- The self-update path stays fork-aware — other users run forks, not just upstream. **Never add `--force` to the server-side `gh repo sync`** (it would discard a user's fork commits; the 409 `FORK_DIVERGED` message points them at running it themselves). Don't re-hardcode the upstream slug outside `server/lib/gitRemote.js`, and new UI claiming "you are running PortOS" must read `remoteInfo.isUpstream`, not just `currentVersion`, or it lies to fork users. Mechanism: [docs/SELF_UPDATE.md](docs/SELF_UPDATE.md).++**The default database password `portos`** (in `ecosystem.config.cjs`, `docker-compose.yml`, `.env.example`) is an intentional backward-compatible fallback for local development. Do not remove it or flag it as a security concern. Production overrides it via `PGPASSWORD`.++**Storage backend policy.** PostgreSQL (system `:5432` or Docker `:5561`) is a **mandatory** dependency for every install and every federated peer — provisioned by `npm run setup:db` (ADR `docs/decisions/2026-06-07-postgres-as-primary-datastore.md`, `docs/STORAGE.md`). **`MEMORY_BACKEND=file` is a development/test-only escape hatch, NOT a supported deployment mode** — the creative catalog/pgvector, federation, and backup all assume Postgres with no file-backed equivalent. When `MEMORY_BACKEND` is unset, `server/services/memoryBackend.js` requires a healthy DB and fails fast with no silent fallback. That is **intentional**: do not "fix" the no-fallback behavior, re-add a file menu choice in `scripts/setup-db.js`, or treat the file backend as a fallback for real installs. The file path stays runnable only because `NODE_ENV=test` selects it — guarded from bitrot by the suite, not promoted to a deployment option.++**Third-party API keys for free, non-monetary services are not security findings.** PortOS calls a few free external APIs (e.g. CivitAI model downloads) with an API key in a query parameter or header. Proposals to host-allowlist the download URL before attaching the key, strip the key across redirects, or similar are won't-fix: leaking that key **to an unintended host** has no monetary loss and no meaningful security consequence — worst case is quota abuse against a free service, borne by that service. (This exempts only that class of finding; the key is still a secret under Sensitive Data & Privacy below — never commit or log it.) This does NOT extend to paid/quota-billed providers (LLM API keys, payment gateways) or keys gating money-bearing or destructive actions, which retain full hardening requirements. Precedent: issue #2200, closed 2026-07-04 (`applyDownloadToken` in `server/services/loras.js#installFromCivitai`).++**Never run DB-backed tests against the real `portos` database.** There is ONE Postgres per install, shared by every git worktree (including CoS-agent worktrees). The `*.db.test.js` suites `DELETE FROM`/`INSERT` whole tables, so running them against `portos` corrupts the user's real universes/series/writers-room/catalog. They are gated to skip on a non-test DB and run only via `npm run test:db` (→ `portos_test`, provisioned by `npm run setup:db:test`). The gate in `server/lib/db.js` keys on `isTestRunner()` (`NODE_ENV==='test'` **OR** `process.env.VITEST` — not bare `NODE_ENV`, so a wrapper that drops `NODE_ENV` can't disarm it), and the `query()` backstop refuses ALL row writes (`INSERT`/`UPDATE`/`DELETE`/`TRUNCATE`) to a non-test DB under the runner. Do not weaken either to "just `NODE_ENV`" or "DELETE-only" — that's exactly the hole that wiped real data on 2026-06-13/14. See `server/lib/db.guards.test.js`.++## AI Provider Usage Policy++**No cold-bootstrap LLM calls.** PortOS must never queue up AI provider calls a user hasn't knowingly triggered. A new install (or a freshly merged feature) coming online should be silent on the LLM front until the user actually asks for AI-backed work. This rules out:++- Firing LLM calls from server boot / `server/index.js` init sequences (cache warm-ups, pre-generation, startup backfills).+- Any background job that silently expands from "generate the one thing the user asked for" into "generate a whole batch for later," without the user having opted into that batch.++**Scheduled automations are the one sanctioned exception** — a cron-style task, autopilot, or CoS agent the user explicitly configured (`taskSchedule.js`, `backupScheduler.js`, autopilot gates) is expected to call AI providers on its own schedule, because the user set it up and knows it's running. Anything else touching an AI provider needs either a direct user action in the same request, or an explicit consent/config step first.++**Pattern for background pre-generation (e.g. caches):**++1. Boot-time init loads only what's already on disk — zero LLM calls.+2. The bulk/cold fill runs only from an explicit user-triggered endpoint, gated behind a UI prompt that names the provider/model about to be used and lets the user change it (or decline and get a single on-demand generation instead).+3. Incremental top-ups after the user has already engaged with the feature (replenishing one item after they consumed one from a primed cache) are fine to run silently — the user consented once, and a small top-up doesn't route through a slow provider unannounced the way a from-zero batch does.++Reference implementation: `server/services/meatspacePostDrillCache.js` (`initDrillCache` / `requestCacheFill` split) and `client/src/components/meatspace/post/WordplayTrainer.jsx` (`CacheFillConsentModal`) — added after a fresh MeatSpace POST install triggered an unannounced 40-call sequential TUI backfill on first boot.++## Architecture++The server is always user-facing on `:5555` (HTTP or HTTPS). The client runs on the Vite dev server at `:5554` under `npm run dev`; under `npm start` the built client is served from `:5555` directly. PM2 manages app lifecycles. Where a given record persists (Postgres vs a `data/` file) is decided by the storage-classification contract in `docs/STORAGE.md`.++**Ports.** PortOS uses 5553–5561 (system PostgreSQL on 5432, Docker PostgreSQL on 5561). When HTTPS is on, the loopback-only HTTP mirror on `:5553` is what local curl/scripts should hit to skip the cert warning. Define ports in the top-level `PORTS` object in `ecosystem.config.cjs` (canonical re-export at `server/lib/ports.js`). Full guide and diagram: `docs/PORTS.md`.++**Backup excludes.** `DEFAULT_EXCLUDES` in `server/services/backup.js` is **rsync filter syntax — every path must be anchored with a leading `/`.** An unanchored pattern matches at any depth and silently drops unrelated user data; that is a data-loss bug, not a style nit. See `docs/BACKUP.md` for the failure mode, the `overridable` tiers, and `computeEffectiveExcludes()`.++### Per-directory conventions++Client- and server-specific conventions live in nested memory files that load when you work in those trees (each is an `AGENTS.md` with a bridge `CLAUDE.md` beside it):++- `client/src/AGENTS.md` — UI conventions, routing/deep-linking, API error/save gating, the shared `Drawer` convention+- `client/src/components/dashboard/AGENTS.md` — widget registration, grid/arrange mechanics, ⌘K layout wiring+- `server/AGENTS.md` — schema parity, write serialization, peer fan-out in tests, prompt-template migrations+- `server/lib/aiToolkit/AGENTS.md` — the override-consistency contract for the vendored provider/runner/prompt toolkit (self-contained: no imports out to other PortOS modules). PortOS overrides `executeCliRun`/`stopRun`/`isRunActive` and mirrors time-based provider-status recovery on read — read it before editing the runner or provider config.++**Nested files reach API-provider agents too — but the walk is bounded.** Nested instruction files load on demand in the agent CLIs, and `getAgentInstructionsContext()` in `server/services/agentPromptBuilder.js` splices them into the prompts PortOS builds for its own API-provider agents as well (`~/.claude/CLAUDE.md` — Claude Code's user-level memory, which keeps that name — then the workspace-root file, then every nested one as its own labeled section). It matches `AGENTS.md` and `CLAUDE.md`, prefers `AGENTS.md`, contributes ONE entry per directory when both are present, and skips a bridge `CLAUDE.md` whose whole body is the `@AGENTS.md` import. The walk is capped at depth 5 / 10 files and skips dot-dirs, `node_modules/`, `data/`, build output, and any subdirectory carrying its own `.git` (submodules and vendored checkouts, e.g. `lib/slashdo/`). Two consequences: **a rule that must reach every agent has to sit inside that budget** — if the repo ever exceeds 10 nested files, the overflow is silently dropped, so raise the cap in the same change rather than assuming coverage; and **the root file is the only guaranteed-first slot**, so a rule guarding data loss, a destructive action, privacy, or spend still belongs here when it must outrank a subtree convention (that is why the backup-exclude anchoring rule above sits in root rather than `server/AGENTS.md`).++### Command Palette & Voice Nav — shared backbone++`server/lib/navManifest.js` is the single source of truth for navigation: `NAV_COMMANDS` + `resolveNavCommand()`, consumed by both the `⌘K` palette and the voice agent's `ui_navigate` tool. **Adding a `<Route>` without a `NAV_COMMANDS` entry leaves the page unreachable from `⌘K` and un-navigable by voice.** Invoke the `portos-add-page` skill for the entry shape, palette-action wiring, and the fail-fast guards.++### Slashdo Commands (`lib/slashdo`)++PortOS bundles [slashdo](https://github.com/atomantic/slashdo) as a git submodule at `lib/slashdo`, providing slash commands (`/do:next`, `/do:review`, `/do:pr`, `/do:push`, `/do:release`, …) without a separate global install. The `.claude/commands/do/` symlinks expose them as project-level slash commands. `/do:next` claims the next PLAN.md item (or GitHub issue with `--issues`) in an isolated worktree and ships a PR. CoS agents can inline a command's content into a prompt via `loadSlashdoCommand(name)` from `server/services/subAgentSpawner.js` (it resolves `!cat` lib includes automatically).++## Module Organization++PortOS has reached the size where re-implementing a helper is cheaper to *start* than finding what already exists. To keep that pressure off, every directory holding reusable code carries a catalog `README.md` and an enumerable `index.js` barrel. **Before writing a helper, grep the catalog.**++### Where new code lives++- **Pure / side-effect-free helpers** → `server/lib/` or `client/src/lib/`+- **React hooks (state + lifecycle)** → `client/src/hooks/`. Names start with `use`.+- **Formatting helpers (pure, no React)** → `client/src/utils/` (`formatters.js`, `cronHelpers.js`, …)+- **HTTP / Socket / browser clients** → `client/src/services/`. API wrappers start with `api*`.+- **Express handlers** → `server/routes/`. Use `validateRequest` + `lib/validation.js` schemas.+- **Domain orchestration (multi-step business logic over models + services)** → `server/services/`+- **Persisted data (PostgreSQL vs a `data/` file)** → decide via the storage-classification contract in `docs/STORAGE.md` *before* defaulting to a new `data/*.json`. App-native relational records are `db-primary`; that doc's "Adding a new data store?" checklist is required in PR review.++One concern per file. Tests live next to their source as `<name>.test.js`. Naming is camelCase with a domain prefix (`brainValidation.js`, `creativeDirectorPrompts.js`).++### Discovery rule (BEFORE writing a helper)++Grep the catalog for the directory most likely to hold it:++```bash+grep -i "what you want to do" server/lib/README.md+grep -i "what you want to do" client/src/lib/README.md+grep -i "what you want to do" client/src/hooks/README.md+grep -i "what you want to do" client/src/services/README.md+```++If a close match exists, **extend it or use it**. Only add a new module when none fits. Pre-existing helpers that are easy to miss:++- `tryReadFile` (`server/lib/fileUtils.js`) — collapses `readFile(path).catch(() => null)`.+- `atomicWrite` (`server/lib/fileUtils.js`) — `ensureDir + writeFile + JSON.stringify` in one call.+- `createCollectionStore` (`server/lib/collectionStore.js`) — when a service outgrows its monolithic single-JSON-file shape (large per-record payload, frequent mutations), use this instead of rolling another `readJSONFile` + `atomicWrite` + `createFileWriteQueue`. Lays out `data/{type}/{id}/index.json` with a type-level `data/{type}/index.json` stamping `schemaVersion` (the storage-layout version, distinct from any per-record-shape `schemaVersion` the sanitizer carries). Includes a per-id write queue and a `verifySchemaVersion` hook used by the boot-time verifier in `server/index.js`. Worked example: `server/services/universeBuilder.js` (migration 034 splits the legacy `universe-builder.json` into this shape).+- `optionalBooleanMap(keys)` (`server/lib/validation.js`) — collapses `z.object(Object.fromEntries(KEYS.map(k => [k, z.boolean().optional()])))`.+- `flattenCanonDescriptorFragments` / `mapCanonDescriptorFragments` (`server/lib/canonPrompt.js`, mirrored to client) — render `[{ prefix?, value }]` fragments to a sentence or array.+- `copyToClipboard` / `writeClipboardSilently` / `readClipboard` (`client/src/lib/clipboard.js`) — safe on insecure-origin contexts. Never use `navigator.clipboard.writeText` inline.+- `useLockToggle` (`client/src/hooks/useLockToggle.js`) — optimistic-PATCH lock toggle for any new lock button.+- `useSseProgress` (`client/src/hooks/useSseProgress.js`) — generic JSON-frame EventSource subscriber; build new progress hooks on top of it.+- `formatBytes` / `formatTimecode` / `formatDateShort` / `formatDurationMs` / `timeAgo` (`client/src/utils/formatters.js`) — never re-define formatters inside components.++### Maintenance rule (WHEN adding a public module)++Any new file in `server/lib/`, `client/src/lib/`, `client/src/hooks/`, `client/src/utils/`, or a new `apiX.js` in `client/src/services/` **MUST**:++1. Be re-exported from the same-directory `index.js` barrel (or, for `services/`, from `api.js`).+2. Get a one-line row in the same-directory `README.md`.++This is the one rule that keeps catalogs from rotting, and it is enforced: `server/lib/index.test.js` and its client counterparts fail when a non-test `.js` file is missing from either the barrel or the README.++**Name collisions.** When two modules in one directory export the same identifier (e.g. `settingsUpdateInputSchema` in both `brainValidation.js` and `digitalTwinValidation.js`), the barrel uses `export * as <name>` namespace exports so callers reach for `brainValidation.settingsUpdateInputSchema` explicitly. Catch-all modules like `validation.js` stay flat. The collision-detector test fails if two flat-`export *` modules ever share an identifier, forcing namespace resolution where the conflict is introduced.++Existing deep imports (`import { x } from '../lib/foo.js'`) keep working — the barrel exists for *discovery*, not to force a re-import. New code may use either form. The worked example for "barrel + documented exports" is `server/lib/aiToolkit/index.js`.++## Scope Boundary++When CoS agents or AI tools work on managed apps outside PortOS, all research, plans, docs, and code for those apps must be written to the target app's own repository/directory — never to this repo. PortOS stores only its own features, plans, and documentation. A PLAN.md, research doc, or feature spec generated for another app goes in that app's directory.++## Sensitive Data & Privacy (developing on a live instance)++**This code is written and reviewed on a live install holding one real user's data.** Machine identity, network topology, personal records, and app-specific names read out of the running instance are the user's private data — they must never leak into anything committed, pushed, or published. Treat every artifact an agent produces (source, comments, test fixtures, docs, changelog, commit messages, PR titles/descriptions/review comments, issue text) as world-readable the moment it lands on a branch.++**Never commit, log to a shared file, or write into a PR/issue/commit any of:**++- **Machine identity** — hostnames, machine names, Tailscale node / MagicDNS names, device IDs, OS usernames, home-directory paths embedding a username (`/Users/<name>/…`, `/home/<name>/…`), user email addresses, account IDs, license keys, serial numbers.+- **Network info** — LAN/Tailscale/public IPs, MAC addresses, subnet layouts, port-forwarding maps, router/gateway addresses, VPN keys, `.env` secrets, DB passwords other than the documented `portos` dev fallback, API tokens, session cookies, auth headers.+- **PII** — real names, physical addresses, phone numbers, birthdays, government IDs, payment details, GPS coordinates, biometric data — the user's or anyone in their data.+- **Personal app data** — the actual contents of the running instance: real universe/series/writers-room/catalog records, brain/journal entries, MeatSpace/POST data, media project names, scheduled-task payloads, chat/voice transcripts, or any record pulled from `data/`, the live DB, or a running screen. Never paste a real record into a test fixture, a doc example, or a bug report.++**Rules for agents:**++- **Placeholders, not observations.** When code, a test, a comment, or a doc needs an example value, invent an obviously-fake one (`example.com`, `[email protected]`, `192.0.2.10` (TEST-NET-1), `Acme Corp`, `Example Universe`, `host-XXXX`). Never transcribe a value observed in the live instance or environment.+- **Reproduce with redaction.** When a bug repro, log excerpt, or stack trace legitimately needs real state, redact the sensitive fields (`<hostname>`, `<user-email>`, `<tailscale-ip>`, `<record-id>`) before it goes into a commit, PR, issue, or review comment. The point is the shape of the data, not its contents.+- **No environment scraping into artifacts.** Do not run `hostname`, `whoami`, `ifconfig`/`ip addr`, `tailscale status`, `env`, `git config user.*` and paste the output into anything committed or published. Read them only for transient in-session logic; never persist them.+- **Scrub before you ship.** Before `git add`/commit and before opening or commenting on a PR/issue, scan your own diff and prose for the categories above. If real data slipped in, replace it with a placeholder; if it was already committed, amend/rewrite the branch before pushing rather than layering a "redaction" commit on top (the history still leaks).+- **Absolute paths.** Prefer repo-relative paths in committed text; when an absolute path is unavoidable, strip the user segment (`~/…` or `<repo-root>/…`).++This complements the Security Model (which governs the deployed product) — this section governs what agents may *write down* while working against real data.++## Code Conventions++- **No try/catch** — errors bubble to centralized middleware. **Exception:** PTY/child-process/`setTimeout`/`setInterval` callbacks and any code running *outside* the Express request lifecycle. An uncaught throw there crashes the Node process (there is no `next(err)` to bubble to). At those boundaries, wrap hook invocation in try/catch and log via the emoji-prefixed `console.error` style. Async event handlers that mutate shared module-level state (e.g. the TUI spawner's `handleData`) must also be serialized — chain them onto a per-session/per-actor `Promise.resolve()` queue rather than firing concurrently, or interleaved awaits race on shared buffers.+- **Functional programming** — no classes; use hooks in React.+- **Zod validation** — all route inputs validated via `lib/validation.js`.+- **Command allowlist** — shell execution restricted to approved commands only.+- **Every new page registers in the nav manifest** — adding a `<Route>` + sidebar link also means a `NAV_COMMANDS` entry in `server/lib/navManifest.js`, which makes the page reachable via `⌘K` and voice (`ui_navigate`). Invoke the `portos-add-page` skill for the entry shape.+- **Selection lives in the URL, never in local state** — any view that opens/selects a specific record encodes it as a route param, so it's shareable, bookmarkable, and reachable from ⌘K and voice. Full contract in `client/src/AGENTS.md`.+- **Client UI conventions** (`client/src/AGENTS.md`) — no `alert`/`confirm`, `htmlFor`/`id` label pairing, mobile responsive, above the fold, no hardcoded localhost, alphabetical nav, reactive local-state updates after mutations, silent-vs-toasting API errors, save gating for "Run Now" actions, and the shared tabbed `Drawer` convention.+- **Server conventions** (`server/AGENTS.md`) — schema parity when adding fields, serializing async PATCH races on shared records, batching high-frequency state writes, peer fan-out in record-creating tests, backup exclude anchoring, and stage-prompt template migrations.+- **Socket-driven UI** — invoke the `portos-socket-ui` skill before wiring or debugging a socket-driven view (event-driven state swaps, single-subscriber resources, pending-request tracking, deferred-work guards).+- **Single-line logging** — emoji prefixes and string interpolation; never log full JSON blobs or arrays.+ ```js+ console.log(`🚀 Server started on port ${PORT}`);+ console.log(`📜 Processing ${items.length} items`);+ console.error(`❌ Failed to connect: ${err.message}`);+ ```+- **LLM response merging — distinguish absent vs intentionally empty.** When merging an LLM response into existing state, "key absent" must preserve the original while "key present with empty value" must apply the intentional clear. Don't use `.length` truthiness as the signal — it conflates the two and silently restores values the user (or LLM) just cleared.+ - Strings: `null`/`undefined` = absent, `""` = a clear. Server helpers like `universeBuilderExpand.trimField` return `null` for non-strings, not `""`.+ - Arrays/objects: gate on `Array.isArray(parsed?.field)` / `typeof parsed?.field === 'object'` before falling back to the original.+ - Keep server-side merges and the client's `pick` helpers mirrored — a one-sided change breaks the round-trip.+- **Sentinel + validate to distinguish "not set / failed" from "present-but-empty / valid".** The `.length`-truthiness footgun above is one instance of a broader rule: never let *absent*, *failed-to-fetch*, or *invalid* collapse into the same value as *fetched-and-legitimately-empty* or *valid*. Use an explicit sentinel and validate before falling through — not `x.length` or `x || fallback`-on-mere-presence. Canonical examples in the local-LLM backends: model-list caches use `null = not fetched` vs `[] = cached-empty`, so a zero-model backend still caches instead of re-hitting the API every call (`ollamaManager.js` `installedModels`, `lmStudioManager.js` `availableModels`); `getBackend()` validates the `.env` marker first and only then falls back to `process.env`, so a stale `.env` value can't mask a valid runtime env override (`server/services/localLlm.js`); and a reachable-but-list-failed backend surfaces an explicit `modelsError` rather than reporting `0 models` (`lmStudioManager.js` `getLastListError`).++## Git Workflow++- **main**: active development. **release**: push `main` to `release` to trigger the GitHub Release workflow.+- **Push pattern**: `git pull --rebase --autostash && git push`+- **No per-branch changelog entries.** Individual PRs do not write a changelog file or fragment — commit messages are the record. `/do:release` synthesizes the release notes from the commit log since the last tag (grouped by feature/theme) when it runs, and writes the result to `.changelog/v{version}.md`. This replaced an earlier per-branch fragment workflow (`.changelog/next/*.md` + `npm run changelog:add`), which existed to avoid parallel branches conflicting on a shared `NEXT.md` — deriving notes from commits at release time sidesteps that problem entirely, since no branch writes to `.changelog/` anymore. Consequence: **write commit subjects/bodies for a human release-note reader**, not just for `git log` — see "Git commits and PRs" in the global instructions. Full rationale: `.changelog/README.md`.+- **Versioning**: the version in `package.json` reflects the last release. Do not bump during development — `/do:release` handles it.+- After each feature or bug fix, run `/simplify`, then commit and push.+- **Capture deferred work, and decide rather than park it.** Deferred refactors/cleanups go into a filed GitHub issue labeled `plan`, specific enough to pick up cold — never left only in chat. When the sole obstacle is an undecided design choice, **make the call yourself** and file it ready-to-work; `future` / `needs-input` are last resorts. Invoke the `portos-file-issue` skill for the full labeling contract. Add independent slashdo dispatch hints (`model:light|medium|heavy`, `effort:low|medium|high|xhigh|max`) and contributor labels (`good first issue`, `help wanted`) only when the work you just inspected justifies them — omit an axis rather than guessing, never stamp `medium` on both, and never mark a wide mechanical sweep as a good first issue. Create missing labels lazily with slashdo/GitHub colors before `gh issue create`, use repeated `--label` flags, and keep category labels (`plan`, `ux`, `bug`, `tests`) intact.+- **Never link to AI conversation sessions.** Do not paste `claude.ai`, `chatgpt.com`/`chat.openai.com`, or any other AI chat/session share URL (or a "generated by / view this conversation" link) into a PR description, commit message, issue, or review comment. These leak session context, aren't durable references, and read as AI attribution — the PR must stand on its own with a Summary and a Test plan. Reference durable artifacts instead: issue/PR numbers, commit SHAs, file paths.+- If enough commits have accumulated to warrant a production release, pull the latest `main` and `release`, then run `/do:release` from `main`.+- **Archive approved design plans.** When a plan is approved out of plan mode, copy the finalized plan from `~/.claude/plans/` to `./docs/plans/YYYY-MM-DD-<slug>.md` (date of approval) as a design record before implementing. See `docs/plans/README.md`.++## Documentation++`docs/README.md` indexes everything under `docs/` — guides, feature deep dives, ADRs (`docs/decisions/`), and design records (`docs/plans/`). The contracts referenced most often from code review: `docs/STORAGE.md` (where a record lives), `docs/PORTS.md`, `docs/BACKUP.md`, `docs/SELF_UPDATE.md`, `docs/ARCHITECTURE.md`, `docs/API.md`.diff --git a/CLAUDE.md b/CLAUDE.mdindex 06339bd355..43c994c2d3 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -1,207 +1 @@-# CLAUDE.md--This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.--## Commands--Non-obvious invocations only — everything else is in `package.json` scripts.--```bash-npm run install:all # includes git submodule update --init --recursive--# Root `npm test` runs both workspaces in sequence (server, then client). Run them-# per workspace to scope to one — both are Vitest, with different environments:-cd server && npm test # Vitest (node) — ALSO globs ../scripts, ../lib, ../autofixer-cd client && npm test # Vitest (jsdom) — component/unit tests-# No NODE_ENV prefix needed: server/vitest.config.js FORCES NODE_ENV=test (#4554).-# Vitest only defaults it when unset, and PortOS runs under PM2 with-# NODE_ENV=development — a suite run that inherits that aims at the real Postgres.-npm run test:db # DB-backed suites → portos_test ONLY (see Security Model)-```--## Security Model--**Trust model (within one install).** Each PortOS install serves exactly one human user, on a private network behind Tailscale VPN, never exposed to the public internet. Within an install there is one server process and one user — so concurrent *request* races, mutex locking on file I/O, and atomic write patterns are unnecessary as defenses against competing actors and should not be added or flagged as concerns. Simple re-entrancy guards (per-account sync locks preventing duplicate in-flight operations; serializing two write paths that mutate the same record) are fine and expected. PortOS intentionally omits CORS restrictions, rate limiting, and full concurrency controls by default — non-issues for a single-user private-network deployment. Do not add them or flag their absence. **"Single-user" means: do not defend against multiple competing humans inside one install. It does NOT mean "assume only one install exists."**--**Authentication and HTTPS exist, but are OPT-IN and OFF by default.** Do not assume they are absent:--- **Auth** — an optional instance password (`server/services/auth.js`, enforced by `server/lib/authGate.js`) gates all of `/api/*` and `/data/*` when set, with a small always-public set (`/api/auth/status`, `/api/system/health`). Peers reach a password-gated instance via a per-peer Basic credential on the peer record, attached to every outbound hop by `peerFetch` (`server/lib/peerHttpClient.js`).-- **HTTPS** — provisioned by `npm run setup:cert`; `:5555` flips to TLS with a loopback-only HTTP mirror on `:5553`. Peer hops set `rejectUnauthorized: false` ("Tailnet is the trust boundary") — between two tailnet nodes WireGuard already supplies mutual auth, but a non-tailnet peer (plain LAN IP / non-`.ts.net` host, see `peerRequiresTailscale()`) gets no server authentication.--Because both are off by default, **never treat "the password is set" as an available guarantee** when designing a feature — gate on it explicitly, or design for the default posture. **PII must not ride the federation layer at all** — see ADR [privacy records machine-local](docs/decisions/2026-08-08-privacy-records-machine-local.md). That rule governs *records* and *status/capability payloads*; its one scoped carve-out is a submitted job body carrying the conditioning an allowlisted peer is being asked to render — the prompt (ADR [federated visual prompts](docs/decisions/2026-08-20-federated-visual-prompts.md)), and, under the same gate, lyrics and conditioning images (ADR [conditioning crosses to an allowlisted peer](docs/decisions/2026-08-22-federated-media-input-assets.md), which also records what stays refused: model weights and multi-step chain state).--**Distribution model (across installs).** PortOS is distributed software: many independent people each run their own install, on their own machine(s), each upgrading on their own schedule — and a single user commonly runs **several machines federated as sync peers**. Backward/forward compatibility across installs and versions is first-class, NOT optional:--- **Never delete or skip migration / compatibility code on the grounds that "there's only one install."** There isn't — other people and other machines run this code and update it independently.-- On-disk format changes need a migration in `scripts/migrations/` (applied-list tracked per install in `data/migrations.applied.json`). Seed files must ship in `data.reference/`.-- Prompt-default changes need a `PROMPT_VERSIONS` bump AND the prior default preserved in `PREVIOUS_DEFAULT_PROMPTS`, so other installs recognize their stored prompt and auto-upgrade it (`server/services/taskSchedule.js`).-- Cross-machine sync payloads stay version-gated (`server/lib/schemaVersions.js`) so a newer peer can't corrupt an older one.-- The self-update path stays fork-aware — other users run forks, not just upstream. **Never add `--force` to the server-side `gh repo sync`** (it would discard a user's fork commits; the 409 `FORK_DIVERGED` message points them at running it themselves). Don't re-hardcode the upstream slug outside `server/lib/gitRemote.js`, and new UI claiming "you are running PortOS" must read `remoteInfo.isUpstream`, not just `currentVersion`, or it lies to fork users. Mechanism: [docs/SELF_UPDATE.md](docs/SELF_UPDATE.md).--**The default database password `portos`** (in `ecosystem.config.cjs`, `docker-compose.yml`, `.env.example`) is an intentional backward-compatible fallback for local development. Do not remove it or flag it as a security concern. Production overrides it via `PGPASSWORD`.--**Storage backend policy.** PostgreSQL (system `:5432` or Docker `:5561`) is a **mandatory** dependency for every install and every federated peer — provisioned by `npm run setup:db` (ADR `docs/decisions/2026-06-07-postgres-as-primary-datastore.md`, `docs/STORAGE.md`). **`MEMORY_BACKEND=file` is a development/test-only escape hatch, NOT a supported deployment mode** — the creative catalog/pgvector, federation, and backup all assume Postgres with no file-backed equivalent. When `MEMORY_BACKEND` is unset, `server/services/memoryBackend.js` requires a healthy DB and fails fast with no silent fallback. That is **intentional**: do not "fix" the no-fallback behavior, re-add a file menu choice in `scripts/setup-db.js`, or treat the file backend as a fallback for real installs. The file path stays runnable only because `NODE_ENV=test` selects it — guarded from bitrot by the suite, not promoted to a deployment option.--**Third-party API keys for free, non-monetary services are not security findings.** PortOS calls a few free external APIs (e.g. CivitAI model downloads) with an API key in a query parameter or header. Proposals to host-allowlist the download URL before attaching the key, strip the key across redirects, or similar are won't-fix: leaking that key **to an unintended host** has no monetary loss and no meaningful security consequence — worst case is quota abuse against a free service, borne by that service. (This exempts only that class of finding; the key is still a secret under Sensitive Data & Privacy below — never commit or log it.) This does NOT extend to paid/quota-billed providers (LLM API keys, payment gateways) or keys gating money-bearing or destructive actions, which retain full hardening requirements. Precedent: issue #2200, closed 2026-07-04 (`applyDownloadToken` in `server/services/loras.js#installFromCivitai`).--**Never run DB-backed tests against the real `portos` database.** There is ONE Postgres per install, shared by every git worktree (including CoS-agent worktrees). The `*.db.test.js` suites `DELETE FROM`/`INSERT` whole tables, so running them against `portos` corrupts the user's real universes/series/writers-room/catalog. They are gated to skip on a non-test DB and run only via `npm run test:db` (→ `portos_test`, provisioned by `npm run setup:db:test`). The gate in `server/lib/db.js` keys on `isTestRunner()` (`NODE_ENV==='test'` **OR** `process.env.VITEST` — not bare `NODE_ENV`, so a wrapper that drops `NODE_ENV` can't disarm it), and the `query()` backstop refuses ALL row writes (`INSERT`/`UPDATE`/`DELETE`/`TRUNCATE`) to a non-test DB under the runner. Do not weaken either to "just `NODE_ENV`" or "DELETE-only" — that's exactly the hole that wiped real data on 2026-06-13/14. See `server/lib/db.guards.test.js`.--## AI Provider Usage Policy--**No cold-bootstrap LLM calls.** PortOS must never queue up AI provider calls a user hasn't knowingly triggered. A new install (or a freshly merged feature) coming online should be silent on the LLM front until the user actually asks for AI-backed work. This rules out:--- Firing LLM calls from server boot / `server/index.js` init sequences (cache warm-ups, pre-generation, startup backfills).-- Any background job that silently expands from "generate the one thing the user asked for" into "generate a whole batch for later," without the user having opted into that batch.--**Scheduled automations are the one sanctioned exception** — a cron-style task, autopilot, or CoS agent the user explicitly configured (`taskSchedule.js`, `backupScheduler.js`, autopilot gates) is expected to call AI providers on its own schedule, because the user set it up and knows it's running. Anything else touching an AI provider needs either a direct user action in the same request, or an explicit consent/config step first.--**Pattern for background pre-generation (e.g. caches):**--1. Boot-time init loads only what's already on disk — zero LLM calls.-2. The bulk/cold fill runs only from an explicit user-triggered endpoint, gated behind a UI prompt that names the provider/model about to be used and lets the user change it (or decline and get a single on-demand generation instead).-3. Incremental top-ups after the user has already engaged with the feature (replenishing one item after they consumed one from a primed cache) are fine to run silently — the user consented once, and a small top-up doesn't route through a slow provider unannounced the way a from-zero batch does.--Reference implementation: `server/services/meatspacePostDrillCache.js` (`initDrillCache` / `requestCacheFill` split) and `client/src/components/meatspace/post/WordplayTrainer.jsx` (`CacheFillConsentModal`) — added after a fresh MeatSpace POST install triggered an unannounced 40-call sequential TUI backfill on first boot.--## Architecture--The server is always user-facing on `:5555` (HTTP or HTTPS). The client runs on the Vite dev server at `:5554` under `npm run dev`; under `npm start` the built client is served from `:5555` directly. PM2 manages app lifecycles. Where a given record persists (Postgres vs a `data/` file) is decided by the storage-classification contract in `docs/STORAGE.md`.--**Ports.** PortOS uses 5553–5561 (system PostgreSQL on 5432, Docker PostgreSQL on 5561). When HTTPS is on, the loopback-only HTTP mirror on `:5553` is what local curl/scripts should hit to skip the cert warning. Define ports in the top-level `PORTS` object in `ecosystem.config.cjs` (canonical re-export at `server/lib/ports.js`). Full guide and diagram: `docs/PORTS.md`.--**Backup excludes.** `DEFAULT_EXCLUDES` in `server/services/backup.js` is **rsync filter syntax — every path must be anchored with a leading `/`.** An unanchored pattern matches at any depth and silently drops unrelated user data; that is a data-loss bug, not a style nit. See `docs/BACKUP.md` for the failure mode, the `overridable` tiers, and `computeEffectiveExcludes()`.--### Per-directory conventions--Client- and server-specific conventions live in nested memory files that load when you work in those trees:--- `client/src/CLAUDE.md` — UI conventions, routing/deep-linking, API error/save gating, the shared `Drawer` convention-- `client/src/components/dashboard/CLAUDE.md` — widget registration, grid/arrange mechanics, ⌘K layout wiring-- `server/CLAUDE.md` — schema parity, write serialization, peer fan-out in tests, prompt-template migrations-- `server/lib/aiToolkit/CLAUDE.md` — the override-consistency contract for the vendored provider/runner/prompt toolkit (self-contained: no imports out to other PortOS modules). PortOS overrides `executeCliRun`/`stopRun`/`isRunActive` and mirrors time-based provider-status recovery on read — read it before editing the runner or provider config.--**Nested files reach API-provider agents too — but the walk is bounded.** Nested `CLAUDE.md` files load on demand in Claude Code, and `getClaudeMdContext()` in `server/services/agentPromptBuilder.js` splices them into the prompts PortOS builds for its own API-provider agents as well (`~/.claude/CLAUDE.md`, then the workspace-root file, then every nested one as its own labeled section). The walk is capped at depth 5 / 10 files and skips dot-dirs, `node_modules/`, `data/`, build output, and any subdirectory carrying its own `.git` (submodules and vendored checkouts, e.g. `lib/slashdo/`). Two consequences: **a rule that must reach every agent has to sit inside that budget** — if the repo ever exceeds 10 nested files, the overflow is silently dropped, so raise the cap in the same change rather than assuming coverage; and **the root file is the only guaranteed-first slot**, so a rule guarding data loss, a destructive action, privacy, or spend still belongs here when it must outrank a subtree convention (that is why the backup-exclude anchoring rule above sits in root rather than `server/CLAUDE.md`).--### Command Palette & Voice Nav — shared backbone--`server/lib/navManifest.js` is the single source of truth for navigation: `NAV_COMMANDS` + `resolveNavCommand()`, consumed by both the `⌘K` palette and the voice agent's `ui_navigate` tool. **Adding a `<Route>` without a `NAV_COMMANDS` entry leaves the page unreachable from `⌘K` and un-navigable by voice.** Invoke the `portos-add-page` skill for the entry shape, palette-action wiring, and the fail-fast guards.--### Slashdo Commands (`lib/slashdo`)--PortOS bundles [slashdo](https://github.com/atomantic/slashdo) as a git submodule at `lib/slashdo`, providing slash commands (`/do:next`, `/do:review`, `/do:pr`, `/do:push`, `/do:release`, …) without a separate global install. The `.claude/commands/do/` symlinks expose them as project-level slash commands. `/do:next` claims the next PLAN.md item (or GitHub issue with `--issues`) in an isolated worktree and ships a PR. CoS agents can inline a command's content into a prompt via `loadSlashdoCommand(name)` from `server/services/subAgentSpawner.js` (it resolves `!cat` lib includes automatically).--## Module Organization--PortOS has reached the size where re-implementing a helper is cheaper to *start* than finding what already exists. To keep that pressure off, every directory holding reusable code carries a catalog `README.md` and an enumerable `index.js` barrel. **Before writing a helper, grep the catalog.**--### Where new code lives--- **Pure / side-effect-free helpers** → `server/lib/` or `client/src/lib/`-- **React hooks (state + lifecycle)** → `client/src/hooks/`. Names start with `use`.-- **Formatting helpers (pure, no React)** → `client/src/utils/` (`formatters.js`, `cronHelpers.js`, …)-- **HTTP / Socket / browser clients** → `client/src/services/`. API wrappers start with `api*`.-- **Express handlers** → `server/routes/`. Use `validateRequest` + `lib/validation.js` schemas.-- **Domain orchestration (multi-step business logic over models + services)** → `server/services/`-- **Persisted data (PostgreSQL vs a `data/` file)** → decide via the storage-classification contract in `docs/STORAGE.md` *before* defaulting to a new `data/*.json`. App-native relational records are `db-primary`; that doc's "Adding a new data store?" checklist is required in PR review.--One concern per file. Tests live next to their source as `<name>.test.js`. Naming is camelCase with a domain prefix (`brainValidation.js`, `creativeDirectorPrompts.js`).--### Discovery rule (BEFORE writing a helper)--Grep the catalog for the directory most likely to hold it:--```bash-grep -i "what you want to do" server/lib/README.md-grep -i "what you want to do" client/src/lib/README.md-grep -i "what you want to do" client/src/hooks/README.md-grep -i "what you want to do" client/src/services/README.md-```--If a close match exists, **extend it or use it**. Only add a new module when none fits. Pre-existing helpers that are easy to miss:--- `tryReadFile` (`server/lib/fileUtils.js`) — collapses `readFile(path).catch(() => null)`.-- `atomicWrite` (`server/lib/fileUtils.js`) — `ensureDir + writeFile + JSON.stringify` in one call.-- `createCollectionStore` (`server/lib/collectionStore.js`) — when a service outgrows its monolithic single-JSON-file shape (large per-record payload, frequent mutations), use this instead of rolling another `readJSONFile` + `atomicWrite` + `createFileWriteQueue`. Lays out `data/{type}/{id}/index.json` with a type-level `data/{type}/index.json` stamping `schemaVersion` (the storage-layout version, distinct from any per-record-shape `schemaVersion` the sanitizer carries). Includes a per-id write queue and a `verifySchemaVersion` hook used by the boot-time verifier in `server/index.js`. Worked example: `server/services/universeBuilder.js` (migration 034 splits the legacy `universe-builder.json` into this shape).-- `optionalBooleanMap(keys)` (`server/lib/validation.js`) — collapses `z.object(Object.fromEntries(KEYS.map(k => [k, z.boolean().optional()])))`.-- `flattenCanonDescriptorFragments` / `mapCanonDescriptorFragments` (`server/lib/canonPrompt.js`, mirrored to client) — render `[{ prefix?, value }]` fragments to a sentence or array.-- `copyToClipboard` / `writeClipboardSilently` / `readClipboard` (`client/src/lib/clipboard.js`) — safe on insecure-origin contexts. Never use `navigator.clipboard.writeText` inline.-- `useLockToggle` (`client/src/hooks/useLockToggle.js`) — optimistic-PATCH lock toggle for any new lock button.-- `useSseProgress` (`client/src/hooks/useSseProgress.js`) — generic JSON-frame EventSource subscriber; build new progress hooks on top of it.-- `formatBytes` / `formatTimecode` / `formatDateShort` / `formatDurationMs` / `timeAgo` (`client/src/utils/formatters.js`) — never re-define formatters inside components.--### Maintenance rule (WHEN adding a public module)--Any new file in `server/lib/`, `client/src/lib/`, `client/src/hooks/`, `client/src/utils/`, or a new `apiX.js` in `client/src/services/` **MUST**:--1. Be re-exported from the same-directory `index.js` barrel (or, for `services/`, from `api.js`).-2. Get a one-line row in the same-directory `README.md`.--This is the one rule that keeps catalogs from rotting, and it is enforced: `server/lib/index.test.js` and its client counterparts fail when a non-test `.js` file is missing from either the barrel or the README.--**Name collisions.** When two modules in one directory export the same identifier (e.g. `settingsUpdateInputSchema` in both `brainValidation.js` and `digitalTwinValidation.js`), the barrel uses `export * as <name>` namespace exports so callers reach for `brainValidation.settingsUpdateInputSchema` explicitly. Catch-all modules like `validation.js` stay flat. The collision-detector test fails if two flat-`export *` modules ever share an identifier, forcing namespace resolution where the conflict is introduced.--Existing deep imports (`import { x } from '../lib/foo.js'`) keep working — the barrel exists for *discovery*, not to force a re-import. New code may use either form. The worked example for "barrel + documented exports" is `server/lib/aiToolkit/index.js`.--## Scope Boundary--When CoS agents or AI tools work on managed apps outside PortOS, all research, plans, docs, and code for those apps must be written to the target app's own repository/directory — never to this repo. PortOS stores only its own features, plans, and documentation. A PLAN.md, research doc, or feature spec generated for another app goes in that app's directory.--## Sensitive Data & Privacy (developing on a live instance)--**This code is written and reviewed on a live install holding one real user's data.** Machine identity, network topology, personal records, and app-specific names read out of the running instance are the user's private data — they must never leak into anything committed, pushed, or published. Treat every artifact an agent produces (source, comments, test fixtures, docs, changelog, commit messages, PR titles/descriptions/review comments, issue text) as world-readable the moment it lands on a branch.--**Never commit, log to a shared file, or write into a PR/issue/commit any of:**--- **Machine identity** — hostnames, machine names, Tailscale node / MagicDNS names, device IDs, OS usernames, home-directory paths embedding a username (`/Users/<name>/…`, `/home/<name>/…`), user email addresses, account IDs, license keys, serial numbers.-- **Network info** — LAN/Tailscale/public IPs, MAC addresses, subnet layouts, port-forwarding maps, router/gateway addresses, VPN keys, `.env` secrets, DB passwords other than the documented `portos` dev fallback, API tokens, session cookies, auth headers.-- **PII** — real names, physical addresses, phone numbers, birthdays, government IDs, payment details, GPS coordinates, biometric data — the user's or anyone in their data.-- **Personal app data** — the actual contents of the running instance: real universe/series/writers-room/catalog records, brain/journal entries, MeatSpace/POST data, media project names, scheduled-task payloads, chat/voice transcripts, or any record pulled from `data/`, the live DB, or a running screen. Never paste a real record into a test fixture, a doc example, or a bug report.--**Rules for agents:**--- **Placeholders, not observations.** When code, a test, a comment, or a doc needs an example value, invent an obviously-fake one (`example.com`, `[email protected]`, `192.0.2.10` (TEST-NET-1), `Acme Corp`, `Example Universe`, `host-XXXX`). Never transcribe a value observed in the live instance or environment.-- **Reproduce with redaction.** When a bug repro, log excerpt, or stack trace legitimately needs real state, redact the sensitive fields (`<hostname>`, `<user-email>`, `<tailscale-ip>`, `<record-id>`) before it goes into a commit, PR, issue, or review comment. The point is the shape of the data, not its contents.-- **No environment scraping into artifacts.** Do not run `hostname`, `whoami`, `ifconfig`/`ip addr`, `tailscale status`, `env`, `git config user.*` and paste the output into anything committed or published. Read them only for transient in-session logic; never persist them.-- **Scrub before you ship.** Before `git add`/commit and before opening or commenting on a PR/issue, scan your own diff and prose for the categories above. If real data slipped in, replace it with a placeholder; if it was already committed, amend/rewrite the branch before pushing rather than layering a "redaction" commit on top (the history still leaks).-- **Absolute paths.** Prefer repo-relative paths in committed text; when an absolute path is unavoidable, strip the user segment (`~/…` or `<repo-root>/…`).--This complements the Security Model (which governs the deployed product) — this section governs what agents may *write down* while working against real data.--## Code Conventions--- **No try/catch** — errors bubble to centralized middleware. **Exception:** PTY/child-process/`setTimeout`/`setInterval` callbacks and any code running *outside* the Express request lifecycle. An uncaught throw there crashes the Node process (there is no `next(err)` to bubble to). At those boundaries, wrap hook invocation in try/catch and log via the emoji-prefixed `console.error` style. Async event handlers that mutate shared module-level state (e.g. the TUI spawner's `handleData`) must also be serialized — chain them onto a per-session/per-actor `Promise.resolve()` queue rather than firing concurrently, or interleaved awaits race on shared buffers.-- **Functional programming** — no classes; use hooks in React.-- **Zod validation** — all route inputs validated via `lib/validation.js`.-- **Command allowlist** — shell execution restricted to approved commands only.-- **Every new page registers in the nav manifest** — adding a `<Route>` + sidebar link also means a `NAV_COMMANDS` entry in `server/lib/navManifest.js`, which makes the page reachable via `⌘K` and voice (`ui_navigate`). Invoke the `portos-add-page` skill for the entry shape.-- **Selection lives in the URL, never in local state** — any view that opens/selects a specific record encodes it as a route param, so it's shareable, bookmarkable, and reachable from ⌘K and voice. Full contract in `client/src/CLAUDE.md`.-- **Client UI conventions** (`client/src/CLAUDE.md`) — no `alert`/`confirm`, `htmlFor`/`id` label pairing, mobile responsive, above the fold, no hardcoded localhost, alphabetical nav, reactive local-state updates after mutations, silent-vs-toasting API errors, save gating for "Run Now" actions, and the shared tabbed `Drawer` convention.-- **Server conventions** (`server/CLAUDE.md`) — schema parity when adding fields, serializing async PATCH races on shared records, batching high-frequency state writes, peer fan-out in record-creating tests, backup exclude anchoring, and stage-prompt template migrations.-- **Socket-driven UI** — invoke the `portos-socket-ui` skill before wiring or debugging a socket-driven view (event-driven state swaps, single-subscriber resources, pending-request tracking, deferred-work guards).-- **Single-line logging** — emoji prefixes and string interpolation; never log full JSON blobs or arrays.- ```js- console.log(`🚀 Server started on port ${PORT}`);- console.log(`📜 Processing ${items.length} items`);- console.error(`❌ Failed to connect: ${err.message}`);- ```-- **LLM response merging — distinguish absent vs intentionally empty.** When merging an LLM response into existing state, "key absent" must preserve the original while "key present with empty value" must apply the intentional clear. Don't use `.length` truthiness as the signal — it conflates the two and silently restores values the user (or LLM) just cleared.- - Strings: `null`/`undefined` = absent, `""` = a clear. Server helpers like `universeBuilderExpand.trimField` return `null` for non-strings, not `""`.- - Arrays/objects: gate on `Array.isArray(parsed?.field)` / `typeof parsed?.field === 'object'` before falling back to the original.- - Keep server-side merges and the client's `pick` helpers mirrored — a one-sided change breaks the round-trip.-- **Sentinel + validate to distinguish "not set / failed" from "present-but-empty / valid".** The `.length`-truthiness footgun above is one instance of a broader rule: never let *absent*, *failed-to-fetch*, or *invalid* collapse into the same value as *fetched-and-legitimately-empty* or *valid*. Use an explicit sentinel and validate before falling through — not `x.length` or `x || fallback`-on-mere-presence. Canonical examples in the local-LLM backends: model-list caches use `null = not fetched` vs `[] = cached-empty`, so a zero-model backend still caches instead of re-hitting the API every call (`ollamaManager.js` `installedModels`, `lmStudioManager.js` `availableModels`); `getBackend()` validates the `.env` marker first and only then falls back to `process.env`, so a stale `.env` value can't mask a valid runtime env override (`server/services/localLlm.js`); and a reachable-but-list-failed backend surfaces an explicit `modelsError` rather than reporting `0 models` (`lmStudioManager.js` `getLastListError`).--## Git Workflow--- **main**: active development. **release**: push `main` to `release` to trigger the GitHub Release workflow.-- **Push pattern**: `git pull --rebase --autostash && git push`-- **No per-branch changelog entries.** Individual PRs do not write a changelog file or fragment — commit messages are the record. `/do:release` synthesizes the release notes from the commit log since the last tag (grouped by feature/theme) when it runs, and writes the result to `.changelog/v{version}.md`. This replaced an earlier per-branch fragment workflow (`.changelog/next/*.md` + `npm run changelog:add`), which existed to avoid parallel branches conflicting on a shared `NEXT.md` — deriving notes from commits at release time sidesteps that problem entirely, since no branch writes to `.changelog/` anymore. Consequence: **write commit subjects/bodies for a human release-note reader**, not just for `git log` — see "Git commits and PRs" in the global instructions. Full rationale: `.changelog/README.md`.-- **Versioning**: the version in `package.json` reflects the last release. Do not bump during development — `/do:release` handles it.-- After each feature or bug fix, run `/simplify`, then commit and push.-- **Capture deferred work, and decide rather than park it.** Deferred refactors/cleanups go into a filed GitHub issue labeled `plan`, specific enough to pick up cold — never left only in chat. When the sole obstacle is an undecided design choice, **make the call yourself** and file it ready-to-work; `future` / `needs-input` are last resorts. Invoke the `portos-file-issue` skill for the full labeling contract. Add independent slashdo dispatch hints (`model:light|medium|heavy`, `effort:low|medium|high|xhigh|max`) and contributor labels (`good first issue`, `help wanted`) only when the work you just inspected justifies them — omit an axis rather than guessing, never stamp `medium` on both, and never mark a wide mechanical sweep as a good first issue. Create missing labels lazily with slashdo/GitHub colors before `gh issue create`, use repeated `--label` flags, and keep category labels (`plan`, `ux`, `bug`, `tests`) intact.-- **Never link to AI conversation sessions.** Do not paste `claude.ai`, `chatgpt.com`/`chat.openai.com`, or any other AI chat/session share URL (or a "generated by / view this conversation" link) into a PR description, commit message, issue, or review comment. These leak session context, aren't durable references, and read as AI attribution — the PR must stand on its own with a Summary and a Test plan. Reference durable artifacts instead: issue/PR numbers, commit SHAs, file paths.-- If enough commits have accumulated to warrant a production release, pull the latest `main` and `release`, then run `/do:release` from `main`.-- **Archive approved design plans.** When a plan is approved out of plan mode, copy the finalized plan from `~/.claude/plans/` to `./docs/plans/YYYY-MM-DD-<slug>.md` (date of approval) as a design record before implementing. See `docs/plans/README.md`.--## Documentation--`docs/README.md` indexes everything under `docs/` — guides, feature deep dives, ADRs (`docs/decisions/`), and design records (`docs/plans/`). The contracts referenced most often from code review: `docs/STORAGE.md` (where a record lives), `docs/PORTS.md`, `docs/BACKUP.md`, `docs/SELF_UPDATE.md`, `docs/ARCHITECTURE.md`, `docs/API.md`.diff --git a/README.md b/README.mdindex 66c125338a..b2b81c5dde 100644--- a/README.md+++ b/README.md@@ -143,7 +143,7 @@ An identity scaffolding system for building a quantified AI representation of yo- **Personas** — Named variants of the twin (work voice, public voice) that can be swapped into any prompt or test run- **Avatar Bio** — Generated headshot + bio pair for wherever the twin needs a face and a paragraph- **Accounts** — Aggregate external accounts (Spotify, Google, etc.) that feed identity signals-- **Import/Export** — Import from Spotify and other sources; export as system prompt, CLAUDE.md, JSON, or individual files+- **Import/Export** — Import from Spotify and other sources; export as system prompt, AGENTS.md, JSON, or individual files- **Legacy Bundle** — Package the twin and its supporting documents into a single archive to hand forward- **Creation Wizard** — 5-step guided setup for building a new digital twin from scratch@@ -459,8 +459,8 @@ Pull requests are welcome. This is a personal project, so:- **Breakage happens.** Major version bumps (e.g. v2.0.0) may rename pages, reorganize data directories, or change schemas in ways that require a migration pass on your local data. Check the relevant `.changelog/vX.Y.Z.md` for what changed.- **Data migration.** If something stops working after an update, the fastest fix is to point your coding agent at the changelog: `"Read .changelog/vX.Y.Z.md and fix any migration issues in my PortOS data/ directory."` Most data issues are trivially auto-fixable this way.-- **Opinionated by design.** Architecture decisions (single-user, auth optional and off by default, PostgreSQL + flat files over a heavy ORM, Tailscale-only networking) are intentional and will not change. PRs that add multi-user support or general-purpose hardening — CORS restrictions, rate limiting, request-level concurrency controls — will not be merged. See the Security Model section of [CLAUDE.md](./CLAUDE.md) for what that trust model does and does not assume.-- **Style.** Match the existing conventions in [CLAUDE.md](./CLAUDE.md) before opening a PR — especially the no-try/catch route convention, emoji-prefixed logging, and Zod validation on all inputs.+- **Opinionated by design.** Architecture decisions (single-user, auth optional and off by default, PostgreSQL + flat files over a heavy ORM, Tailscale-only networking) are intentional and will not change. PRs that add multi-user support or general-purpose hardening — CORS restrictions, rate limiting, request-level concurrency controls — will not be merged. See the Security Model section of [AGENTS.md](./AGENTS.md) for what that trust model does and does not assume.+- **Style.** Match the existing conventions in [AGENTS.md](./AGENTS.md) before opening a PR — especially the no-try/catch route convention, emoji-prefixed logging, and Zod validation on all inputs.## Licensediff --git a/client/src/AGENTS.md b/client/src/AGENTS.mdnew file mode 100644index 0000000000..c2ef406c94--- /dev/null+++ b/client/src/AGENTS.md@@ -0,0 +1,46 @@+# Client conventions (`client/src/`)++These apply to React/Vite client code. Universal constraints (functional programming, no try/catch, single-line logging, Zod validation, the Security Model, and the Sensitive Data & Privacy rules) live in the root `AGENTS.md` and always apply.++## UI conventions++- **No window.alert/confirm** - use inline confirmations or toast notifications+- **Form labels need `htmlFor`/`id` pairing** - when adding a settings/config form field, wire `<label htmlFor="...">` to an `id="..."` on the input — screen readers and click-to-focus both depend on the association. The visual `block`/`mb-1` styling alone doesn't establish it.+- **Mobile responsive** - all pages should be mobile responsive friendly+- **Above the fold** - keep actionable content and info above the fold and design pages for maximum information and access without scrolling+- **No hardcoded localhost** - use `window.location.hostname` for URLs; app accessed via Tailscale remotely+- **Chrome floating over media uses `.port-media-overlay`** - a label, status bar, badge, or control panel sitting on top of an image, a video, or a 3D canvas takes its surface and ink from the theme (`.port-media-overlay`, or `.port-media-overlay-strong` for a small label directly on photography; `.port-media-overlay-item` for its buttons, `.port-media-overlay-divider` for its separators — all defined in `index.css`, which carries the mechanism and the rule for picking between this, `.always-dark`, and the OpenWorld HUD remap). **Don't write `bg-black/NN` + `text-white`/`text-gray-N00` for this** — day mode remaps the text to the theme's dark ink while the black scrim stays black, so the label renders dark-on-black. Older overlays outside the 3D/Three.js pages still carry that idiom (migration tracked in #3796), so match the new convention rather than the nearest neighbor.+- **Alphabetical navigation** - sidebar nav items in `Layout.jsx` are alphabetically ordered after the Dashboard+OpenWorld top section and separator; children within collapsible sections are also alphabetical+- **OpenWorld's internal names match the user-facing area.** The scene tree lives under `components/openworld/`, its pure helpers are `utils/openWorld*.js`, its hooks are `useOpenWorld*.js`, and its CSS scope is `.openworld-themed`. The legacy OpenWorld command ids remain deliberately frozen because they are opaque values persisted in ⌘K history. Keep the persisted `portos-city-settings` key unchanged when adding settings migrations.+- **Space is an app-global hotkey** - the voice widget binds Space for push-to-talk. A surface that owns Space itself (a timed drill, a keyer, a transport control) must claim it with `useKeyCapture` (capture phase + `stopImmediatePropagation`), or the mic opens on every press. Conversely, a global single-key handler stands down when the browser is about to activate a focused button. All three global key paths — `useKeyCapture`, `useKeyboardShortcuts`, and the voice widget's own hotkey listener — decide that through the one shared `shouldIgnoreGlobalKey(event, opts)` predicate in `lib/a11yKeyboard.js`, so a new guard goes THERE, never at one caller (that drift is what let `useKeyCapture` swallow button activation, #4748). The corollary: a surface that OWNS a key spreads `noPointerFocusSurfaceProps` on its ROOT — a mouse click that parks focus on any button inside silently takes that key over, because the global handler correctly stands down for native activation. Put it on the root, not on each button, so controls added later are covered without anyone having to remember.+- **Reactive UI updates** - after mutations (delete, create, update), update local state directly instead of refetching the entire list from the server. Use `setState(prev => prev.filter(...))` or similar patterns for immediate feedback++## API errors and save gating++- **Silent vs. toasting API requests.** The `request()` helper in `client/src/services/apiCore.js` toasts errors by default. When a caller already owns its error UI — via `useAsyncAction` (which toasts on throw) or a `.catch(() => fallback)` that intentionally swallows the failure — pass `{ silent: true }` so the toast fires from one layer only. Give new API wrappers an `options` parameter so callers can opt in. **Custom catch ⇒ `silent: true`**, or the user sees two toasts back to back; no custom toast ⇒ omit `silent` and let the helper handle it.+- **"Run Now" actions gate on saved state, not the form input.** When a settings page has a companion "Run this now" button that triggers server work reading *server-side* settings, gate the button on the *saved* value: track a parallel `saved*` state per dependent setting, update it on successful save, and disable the action while the form is dirty or a save is in flight. A tooltip-only warning is missed on touch and produces "I edited X and ran, but X didn't apply" bugs.+- **In-flight saves gate dependent actions, not just the form.** When a field's PATCH is async and a button triggers server work that reads that field (auto-run, regenerate), disable the button while the PATCH is in flight — not merely while the input is dirty. Otherwise the user picks a value, the input clears, and they click before the server has persisted it. Track a `<field>Saving` boolean, set it before the PATCH, clear it in `.finally()`. Canonical example: `lengthProfileSaving` in `client/src/pages/PipelineIssue.jsx`.++## Routing and deep linking++- **Linkable routes for all views** - tabbed pages use URL params, not local state (e.g., `/devtools/history` not `/devtools` with tab state)+- **ID-based deep linking for every selectable UI element** - any view that opens/selects a specific record (a project, item, scene, detail, editor, or master-detail selection) MUST encode that selection in the URL via a route param (`/music-video/:projectId`, `/media/timeline/:projectId`, `/media/creative-director/:id/:tab`) — never in local `useState`/`selectedId`. The URL is the single source of truth for "what is open," so every element is directly shareable, bookmarkable, and reachable from ⌘K, voice nav, and media job-completion hooks. Selection handlers `navigate()` to the id'd route; deletes/clears `navigate()` back to the index; render a "not found" fallback for stale/deleted ids. Add both the bare index route and the `:id` detail route in `App.jsx`, and keep the base path registered in `NAV_COMMANDS`.+- **New page → pick the right Layout scroll mode.** `Layout.jsx` has an `isFullWidth` route list: matched routes get a bare `relative overflow-hidden` `<main>` (the PAGE must own an internal `overflow-y-auto`, like the editor's `<section>`); unmatched routes get the default `overflow-auto p-4 md:p-6` scrolling+padded main. A list/index page (e.g. `/universes`, `/pipeline`) should usually be a plain `<div>` and stay OUT of `isFullWidth` so the main scrolls it; only full-bleed editors that manage their own scroll belong in the list. Match `/route/` (trailing slash) to scope full-width to detail/editor sub-routes without catching the bare index. A full-width page with no internal scroll container silently clips below the fold.++For the full "adding a new page" checklist (nav manifest entry shape, palette actions, voice aliases), invoke the `portos-add-page` skill.++## Config drawers++- **Config drawers → the shared tabbed `Drawer` convention.** Slide-in "settings over a feature page" surfaces use the shared `client/src/components/Drawer.jsx` primitive — never a hand-rolled `fixed inset-y-0 right-0` clone. Follow this convention instead of dumping another page-length flat scroll into a narrow panel (the epic #1966 redesign):+ - **Size.** Pass `size` (`sm` 520px · `md` 640px · `lg` 720→880px · `xl` up to 1100px). Widen for genuinely large forms so they can lay out in columns on desktop; keep small dialogs at `sm`. Mobile is always `w-full` (full-screen sheet) regardless of `size` — mobile-responsive is non-negotiable. `widthClass` is a back-compat escape hatch that overrides `size`.+ - **When to tab.** A large config surface (many fields / logical groups, e.g. Edit App's ~25 fields) should group its fields into `tabs={[{ id, label, icon?, count? }]}` + `activeTab` / `onTabChange` and render only the active tab's fields as `children` — not one page-length scroll. A *medium* form that should stay fully visible above the fold uses the child's own labeled sections instead (e.g. `ImageGenSettingsForm`'s `grouped` prop in the pipeline image-gen drawers), because tabs hide inactive fields behind a click.+ - **Per-tab scroll.** The drawer gives each tab its own scroll region that resets on switch (`key={currentTab}` remounts the panel) — so no single tab is ever page-length. Because the body remounts per tab, **all mutable form state must live above the Drawer body** in the parent component, never in an uncontrolled input inside the form, or it resets on tab switch (see `EditAppDrawer.jsx`'s state-hoisting comment). Validate fields on tabs that may be unmounted at Save time explicitly, and `setActiveTab()` to the offending tab to surface the error.+ - **Mobile `<select>` fallback + `TabPills`.** The tab bar is `client/src/components/ui/TabPills.jsx` (`mobileDropdown` collapses it to a `<select>` under `sm`) — **reuse it, never roll a new tab bar.** The `Drawer tabs` layout wires TabPills for you; a surface hosted in *both* a drawer and a page (like `ImageGenTab`) renders its own internal `<TabPills variant="pills" mobileDropdown>` instead so the same grouping works in either host.+ - **Deep-linkable active tab.** Drive `activeTab` from a URL search param via `useDrawerTab(paramName, defaultTab, tabIds)` (`client/src/hooks/useDrawerTab.js`) so the open section is shareable/bookmarkable/reload-safe — the same "URL is the source of truth for what's open" rule as routed views. The caller owns the param name (`appTab`, `mediaTab`, …) so a page can host more than one drawer; pass the id list so a stale deep link degrades to `defaultTab` instead of a blank panel.+ - **Long-lived forms** opt out of accidental dismissal with `closeOnEsc={false}` / `closeOnBackdrop={false}` so an Esc keystroke mid-edit doesn't discard the form.+ - **The overlay is always portaled to `<body>` — never re-nest it.** The backdrop and panel are both `position:fixed`, and a `filter` / `backdrop-filter` / `transform` ancestor becomes their containing block; on the "glass" themes `index.css` gives every bordered/rounded `.bg-port-card` a `backdrop-filter`, so an inline drawer nested under a card was sized to the *card*, not the viewport (issue #4150). Portaling is unconditional rather than an opt-in flag, so no call site has to remember it — React still routes events and context through the React tree. The one thing the portal leaves behind is a **page-scoped CSS theming root written as descendant selectors** (`.openworld-themed` in `index.css`): a caller inside one must pass that class as `portalClassName` (see `OpenWorldSettingsDrawer.jsx`). Same trap, same fix, for any new hand-rolled `fixed inset-0` overlay — portal it (`Modal`'s `usePortal`, `GalleryImagePicker.jsx`).+ - **Worked examples:** `client/src/components/apps/EditAppDrawer.jsx` (built-in `tabs` layout, `size="lg"`, `useDrawerTab('appTab', …)`) and `client/src/components/settings/ImageGenTab.jsx` (internal `TabPills variant="pills"` sub-tabs, `useDrawerTab('mediaTab', …)`). The primitive is `Drawer.jsx`; the design record is `docs/plans/2026-07-01-drawer-ux-redesign.md`.++## Socket-driven UI++Socket lifecycle conventions (event-driven state swaps, single-subscriber resources, pending-request tracking, deferred-work guards) are in the `portos-socket-ui` skill — invoke it before wiring a new socket-driven view.diff --git a/client/src/CLAUDE.md b/client/src/CLAUDE.mdindex 33481e9b27..43c994c2d3 100644--- a/client/src/CLAUDE.md+++ b/client/src/CLAUDE.md@@ -1,46 +1 @@-# Client conventions (`client/src/`)--These apply to React/Vite client code. Universal constraints (functional programming, no try/catch, single-line logging, Zod validation, the Security Model, and the Sensitive Data & Privacy rules) live in the root `CLAUDE.md` and always apply.--## UI conventions--- **No window.alert/confirm** - use inline confirmations or toast notifications-- **Form labels need `htmlFor`/`id` pairing** - when adding a settings/config form field, wire `<label htmlFor="...">` to an `id="..."` on the input — screen readers and click-to-focus both depend on the association. The visual `block`/`mb-1` styling alone doesn't establish it.-- **Mobile responsive** - all pages should be mobile responsive friendly-- **Above the fold** - keep actionable content and info above the fold and design pages for maximum information and access without scrolling-- **No hardcoded localhost** - use `window.location.hostname` for URLs; app accessed via Tailscale remotely-- **Chrome floating over media uses `.port-media-overlay`** - a label, status bar, badge, or control panel sitting on top of an image, a video, or a 3D canvas takes its surface and ink from the theme (`.port-media-overlay`, or `.port-media-overlay-strong` for a small label directly on photography; `.port-media-overlay-item` for its buttons, `.port-media-overlay-divider` for its separators — all defined in `index.css`, which carries the mechanism and the rule for picking between this, `.always-dark`, and the OpenWorld HUD remap). **Don't write `bg-black/NN` + `text-white`/`text-gray-N00` for this** — day mode remaps the text to the theme's dark ink while the black scrim stays black, so the label renders dark-on-black. Older overlays outside the 3D/Three.js pages still carry that idiom (migration tracked in #3796), so match the new convention rather than the nearest neighbor.-- **Alphabetical navigation** - sidebar nav items in `Layout.jsx` are alphabetically ordered after the Dashboard+OpenWorld top section and separator; children within collapsible sections are also alphabetical-- **OpenWorld's internal names match the user-facing area.** The scene tree lives under `components/openworld/`, its pure helpers are `utils/openWorld*.js`, its hooks are `useOpenWorld*.js`, and its CSS scope is `.openworld-themed`. The legacy OpenWorld command ids remain deliberately frozen because they are opaque values persisted in ⌘K history. Keep the persisted `portos-city-settings` key unchanged when adding settings migrations.-- **Space is an app-global hotkey** - the voice widget binds Space for push-to-talk. A surface that owns Space itself (a timed drill, a keyer, a transport control) must claim it with `useKeyCapture` (capture phase + `stopImmediatePropagation`), or the mic opens on every press. Conversely, a global single-key handler stands down when the browser is about to activate a focused button. All three global key paths — `useKeyCapture`, `useKeyboardShortcuts`, and the voice widget's own hotkey listener — decide that through the one shared `shouldIgnoreGlobalKey(event, opts)` predicate in `lib/a11yKeyboard.js`, so a new guard goes THERE, never at one caller (that drift is what let `useKeyCapture` swallow button activation, #4748). The corollary: a surface that OWNS a key spreads `noPointerFocusSurfaceProps` on its ROOT — a mouse click that parks focus on any button inside silently takes that key over, because the global handler correctly stands down for native activation. Put it on the root, not on each button, so controls added later are covered without anyone having to remember.-- **Reactive UI updates** - after mutations (delete, create, update), update local state directly instead of refetching the entire list from the server. Use `setState(prev => prev.filter(...))` or similar patterns for immediate feedback--## API errors and save gating--- **Silent vs. toasting API requests.** The `request()` helper in `client/src/services/apiCore.js` toasts errors by default. When a caller already owns its error UI — via `useAsyncAction` (which toasts on throw) or a `.catch(() => fallback)` that intentionally swallows the failure — pass `{ silent: true }` so the toast fires from one layer only. Give new API wrappers an `options` parameter so callers can opt in. **Custom catch ⇒ `silent: true`**, or the user sees two toasts back to back; no custom toast ⇒ omit `silent` and let the helper handle it.-- **"Run Now" actions gate on saved state, not the form input.** When a settings page has a companion "Run this now" button that triggers server work reading *server-side* settings, gate the button on the *saved* value: track a parallel `saved*` state per dependent setting, update it on successful save, and disable the action while the form is dirty or a save is in flight. A tooltip-only warning is missed on touch and produces "I edited X and ran, but X didn't apply" bugs.-- **In-flight saves gate dependent actions, not just the form.** When a field's PATCH is async and a button triggers server work that reads that field (auto-run, regenerate), disable the button while the PATCH is in flight — not merely while the input is dirty. Otherwise the user picks a value, the input clears, and they click before the server has persisted it. Track a `<field>Saving` boolean, set it before the PATCH, clear it in `.finally()`. Canonical example: `lengthProfileSaving` in `client/src/pages/PipelineIssue.jsx`.--## Routing and deep linking--- **Linkable routes for all views** - tabbed pages use URL params, not local state (e.g., `/devtools/history` not `/devtools` with tab state)-- **ID-based deep linking for every selectable UI element** - any view that opens/selects a specific record (a project, item, scene, detail, editor, or master-detail selection) MUST encode that selection in the URL via a route param (`/music-video/:projectId`, `/media/timeline/:projectId`, `/media/creative-director/:id/:tab`) — never in local `useState`/`selectedId`. The URL is the single source of truth for "what is open," so every element is directly shareable, bookmarkable, and reachable from ⌘K, voice nav, and media job-completion hooks. Selection handlers `navigate()` to the id'd route; deletes/clears `navigate()` back to the index; render a "not found" fallback for stale/deleted ids. Add both the bare index route and the `:id` detail route in `App.jsx`, and keep the base path registered in `NAV_COMMANDS`.-- **New page → pick the right Layout scroll mode.** `Layout.jsx` has an `isFullWidth` route list: matched routes get a bare `relative overflow-hidden` `<main>` (the PAGE must own an internal `overflow-y-auto`, like the editor's `<section>`); unmatched routes get the default `overflow-auto p-4 md:p-6` scrolling+padded main. A list/index page (e.g. `/universes`, `/pipeline`) should usually be a plain `<div>` and stay OUT of `isFullWidth` so the main scrolls it; only full-bleed editors that manage their own scroll belong in the list. Match `/route/` (trailing slash) to scope full-width to detail/editor sub-routes without catching the bare index. A full-width page with no internal scroll container silently clips below the fold.--For the full "adding a new page" checklist (nav manifest entry shape, palette actions, voice aliases), invoke the `portos-add-page` skill.--## Config drawers--- **Config drawers → the shared tabbed `Drawer` convention.** Slide-in "settings over a feature page" surfaces use the shared `client/src/components/Drawer.jsx` primitive — never a hand-rolled `fixed inset-y-0 right-0` clone. Follow this convention instead of dumping another page-length flat scroll into a narrow panel (the epic #1966 redesign):- - **Size.** Pass `size` (`sm` 520px · `md` 640px · `lg` 720→880px · `xl` up to 1100px). Widen for genuinely large forms so they can lay out in columns on desktop; keep small dialogs at `sm`. Mobile is always `w-full` (full-screen sheet) regardless of `size` — mobile-responsive is non-negotiable. `widthClass` is a back-compat escape hatch that overrides `size`.- - **When to tab.** A large config surface (many fields / logical groups, e.g. Edit App's ~25 fields) should group its fields into `tabs={[{ id, label, icon?, count? }]}` + `activeTab` / `onTabChange` and render only the active tab's fields as `children` — not one page-length scroll. A *medium* form that should stay fully visible above the fold uses the child's own labeled sections instead (e.g. `ImageGenSettingsForm`'s `grouped` prop in the pipeline image-gen drawers), because tabs hide inactive fields behind a click.- - **Per-tab scroll.** The drawer gives each tab its own scroll region that resets on switch (`key={currentTab}` remounts the panel) — so no single tab is ever page-length. Because the body remounts per tab, **all mutable form state must live above the Drawer body** in the parent component, never in an uncontrolled input inside the form, or it resets on tab switch (see `EditAppDrawer.jsx`'s state-hoisting comment). Validate fields on tabs that may be unmounted at Save time explicitly, and `setActiveTab()` to the offending tab to surface the error.- - **Mobile `<select>` fallback + `TabPills`.** The tab bar is `client/src/components/ui/TabPills.jsx` (`mobileDropdown` collapses it to a `<select>` under `sm`) — **reuse it, never roll a new tab bar.** The `Drawer tabs` layout wires TabPills for you; a surface hosted in *both* a drawer and a page (like `ImageGenTab`) renders its own internal `<TabPills variant="pills" mobileDropdown>` instead so the same grouping works in either host.- - **Deep-linkable active tab.** Drive `activeTab` from a URL search param via `useDrawerTab(paramName, defaultTab, tabIds)` (`client/src/hooks/useDrawerTab.js`) so the open section is shareable/bookmarkable/reload-safe — the same "URL is the source of truth for what's open" rule as routed views. The caller owns the param name (`appTab`, `mediaTab`, …) so a page can host more than one drawer; pass the id list so a stale deep link degrades to `defaultTab` instead of a blank panel.- - **Long-lived forms** opt out of accidental dismissal with `closeOnEsc={false}` / `closeOnBackdrop={false}` so an Esc keystroke mid-edit doesn't discard the form.- - **The overlay is always portaled to `<body>` — never re-nest it.** The backdrop and panel are both `position:fixed`, and a `filter` / `backdrop-filter` / `transform` ancestor becomes their containing block; on the "glass" themes `index.css` gives every bordered/rounded `.bg-port-card` a `backdrop-filter`, so an inline drawer nested under a card was sized to the *card*, not the viewport (issue #4150). Portaling is unconditional rather than an opt-in flag, so no call site has to remember it — React still routes events and context through the React tree. The one thing the portal leaves behind is a **page-scoped CSS theming root written as descendant selectors** (`.openworld-themed` in `index.css`): a caller inside one must pass that class as `portalClassName` (see `OpenWorldSettingsDrawer.jsx`). Same trap, same fix, for any new hand-rolled `fixed inset-0` overlay — portal it (`Modal`'s `usePortal`, `GalleryImagePicker.jsx`).- - **Worked examples:** `client/src/components/apps/EditAppDrawer.jsx` (built-in `tabs` layout, `size="lg"`, `useDrawerTab('appTab', …)`) and `client/src/components/settings/ImageGenTab.jsx` (internal `TabPills variant="pills"` sub-tabs, `useDrawerTab('mediaTab', …)`). The primitive is `Drawer.jsx`; the design record is `docs/plans/2026-07-01-drawer-ux-redesign.md`.--## Socket-driven UI--Socket lifecycle conventions (event-driven state swaps, single-subscriber resources, pending-request tracking, deferred-work guards) are in the `portos-socket-ui` skill — invoke it before wiring a new socket-driven view.diff --git a/client/src/components/KanbanBoard.jsx b/client/src/components/KanbanBoard.jsxindex 001ee3eec5..c3880db206 100644--- a/client/src/components/KanbanBoard.jsx+++ b/client/src/components/KanbanBoard.jsx@@ -49,7 +49,7 @@ const DraggableTicket = memo(function DraggableTicket({ ticket, disabled, appId,const handleQueue = async () => {setQueuing(true);- // silent: this caller owns its own success/error toasts (see CLAUDE.md).+ // silent: this caller owns its own success/error toasts (see AGENTS.md).await api.createJiraTicketTask(appId, ticket.key, { silent: true }).then(() => toast.success(`Queued agent task for ${ticket.key}`)).catch((err) => toast.error(`Failed to queue ${ticket.key}: ${err.message}`))diff --git a/client/src/components/WhileAwayWidget.jsx b/client/src/components/WhileAwayWidget.jsxindex f83e611012..ee9775e283 100644--- a/client/src/components/WhileAwayWidget.jsx+++ b/client/src/components/WhileAwayWidget.jsx@@ -68,7 +68,7 @@ export default function WhileAwayWidget() {// reflect the window we actually queried (not a value that drifted since).const sinceRef = useRef(null);// A socket-driven refresh can land after the widget unmounts — guard the- // async setState so it doesn't fire into the void (CLAUDE.md unmount rule).+ // async setState so it doesn't fire into the void (AGENTS.md unmount rule).const mountedRef = useMounted();const load = useCallback(() => {diff --git a/client/src/components/apps/ReferenceReposPanel.jsx b/client/src/components/apps/ReferenceReposPanel.jsxindex 2a251a7edd..1bc47f996b 100644--- a/client/src/components/apps/ReferenceReposPanel.jsx+++ b/client/src/components/apps/ReferenceReposPanel.jsx@@ -96,7 +96,7 @@ export default function ReferenceReposPanel({ appId, appName }) {fetch();};- // Two-click delete per CLAUDE.md "no window.confirm". First click arms the+ // Two-click delete per AGENTS.md "no window.confirm". First click arms the// row, second click within 4s actually deletes.const pendingDeleteRef = useRef({ id: null, expiresAt: 0 });const handleDelete = async (ref) => {diff --git a/client/src/components/apps/constants.js b/client/src/components/apps/constants.jsindex 38ac3aa3b4..f369f153c5 100644--- a/client/src/components/apps/constants.js+++ b/client/src/components/apps/constants.js@@ -102,7 +102,7 @@ export const workItemNoun = (tracker) =>// Overview first, then alphabetical. Every id is a real route segment// (`/apps/:appId/:tab`) so each tab is linkable, bookmarkable, and reachable-// from ⌘K — see the routing rules in client/src/CLAUDE.md.+// from ⌘K — see the routing rules in client/src/AGENTS.md.//// `visibleWhen(app)` gates a tab that only some apps earn; omit it for the tabs// every app gets. Keeping the predicate on the entry means adding a conditionaldiff --git a/client/src/components/brain/tabs/BrainGraph.jsx b/client/src/components/brain/tabs/BrainGraph.jsxindex 7834071ca0..b0a7cac89b 100644--- a/client/src/components/brain/tabs/BrainGraph.jsx+++ b/client/src/components/brain/tabs/BrainGraph.jsx@@ -428,7 +428,7 @@ export default function BrainGraph() {: 'Syncing brain data to memory…',{ id: toastId });- // silent:true — this catch owns the error toast (CLAUDE.md: custom catch ⇒ silent).+ // silent:true — this catch owns the error toast (AGENTS.md: custom catch ⇒ silent).const stats = await api.syncBrainData({ refresh, onlyMissing }, { silent: true }).catch(err => {toast.error(err.message || 'Sync failed', { id: toastId });return null;diff --git a/client/src/components/cos/tabs/schedule/GlobalConfigControls.jsx b/client/src/components/cos/tabs/schedule/GlobalConfigControls.jsxindex 51ee0b2960..89fa9b7329 100644--- a/client/src/components/cos/tabs/schedule/GlobalConfigControls.jsx+++ b/client/src/components/cos/tabs/schedule/GlobalConfigControls.jsx@@ -57,7 +57,7 @@ export default function GlobalConfigControls({ taskType, config, onUpdate, onTriconst [promptValue, setPromptValue] = useState(config.prompt || '');// Comma-separated free text, committed to taskMetadata.issueExcludeLabels// (an array) on blur. Routes through setUpdating like every other handler- // in this file so RunTaskButton (client/src/CLAUDE.md's "gate on in-flight+ // in this file so RunTaskButton (client/src/AGENTS.md's "gate on in-flight// saves, not just the form" rule) can't fire against the pre-edit list// while this PATCH is still in flight.const excludeLabelsDraft = useFieldDraft(diff --git a/client/src/components/creative-director/DirectiveComposer.jsx b/client/src/components/creative-director/DirectiveComposer.jsxindex bb73b04215..b1b418f004 100644--- a/client/src/components/creative-director/DirectiveComposer.jsx+++ b/client/src/components/creative-director/DirectiveComposer.jsx@@ -6,7 +6,7 @@ import { CREATIVE_DIRECTOR_GOAL_MAX, DELIVERABLE_OPTIONS } from '../../lib/creat* universe/series pickers, and a budget cap. Controlled + presentational: all* state is hoisted into the host (the list-page create form or the detail-page* "convert to directive" Drawer) so the Drawer's per-tab remount can't reset it- * (the CLAUDE.md Drawer state-hoisting rule), and the host owns the submit+ * (the AGENTS.md Drawer state-hoisting rule), and the host owns the submit* affordances (Create / Preview plan / Cancel).** `directive` shape mirrors the server schema:diff --git a/client/src/components/dashboard/AGENTS.md b/client/src/components/dashboard/AGENTS.mdnew file mode 100644index 0000000000..4340149234--- /dev/null+++ b/client/src/components/dashboard/AGENTS.md@@ -0,0 +1,26 @@+# Dashboard Widgets & Layouts (`client/src/components/dashboard/`)++Dashboard widgets are registered in `widgetRegistry.jsx` — each entry has `{ id, label, Component, width, defaultH?, gate? }`. The Dashboard page renders the active layout's widget list from this registry; named layouts persist in `data/dashboard-layouts.json` and are managed via `GET/PUT/DELETE /api/dashboard/layouts`. Built-in layouts (`default`, `focus`, `morning-review`, `ops`) are seeded on first read and cannot be deleted.++**Grid positions:** layouts also carry a `grid: [{ id, x, w, order, h?, fixedH? }]` array — column placement on a 12-column grid plus a reading/packing sequence. When `grid` is empty (legacy/unmigrated layouts) the renderer auto-flows widgets using `synthesizeGrid` based on each widget's `width` keyword and `defaultH`. The "Arrange" button on the Dashboard enters edit mode where every widget exposes a move (top-right) and resize (bottom-right) handle; a move snaps horizontally to columns and re-inserts the cell into the sequence at the rank its dropped pixel position implies (`rankAtPixel` → `insertAtOrder`), renumbering `order` densely. Save persists to the active layout's `grid`. The grid renderer collapses to a single-column stack below 640px container width, rendered in reading order (`order`, then `x` as a tiebreak) — never grid-array order, which nothing keeps sorted.++**One vertical coordinate (#4133).** There is no stored row position. Horizontal placement is declared (`x`/`w`); vertical placement belongs entirely to `packVertically`, which lays cells out in pixels, and `order` says only which cell packs first. That is why a gesture never has to reconcile "where the cell says it is" with "where it is drawn" — only one of those exists. Persisted layouts predating this carried `{ x, y, w, h }`; `sanitizeGridItem`/`sequenceGrid` in `server/services/dashboardLayouts.js` still derive `order` from a legacy `y` on read (shape-probed, not version-flagged), and `scripts/migrations/269-dashboard-grid-order.js` rewrites the file on disk. **A new widget-seeding migration must append `{ id, x, w, order, h }`, not `{ x, y, w, h }`** — the older seed migrations (029/030/033/070/145/156/191) still compute `y` because they only ever run on pre-269 files.++**Height is measured, not declared.** `h` is NOT the rendered height. A cell measures its widget's natural height with a `ResizeObserver` and `packVertically` positions everything in pixels — each cell floats up to just below the nearest already-placed cell that shares a column. That's what stops an 80px card from reserving a 400px slot and leaving a band of dead whitespace across the row. `h` survives as the pre-measurement fallback (first paint) and as what an older client — which knows nothing about `fixedH` — reads out of a saved layout, so every drag commit refreshes it from the measurement via `withMeasuredHeights`. A cell whose height the user actually dragged carries `fixedH: true` and keeps `h` exactly, clipping content the way the whole grid used to; the ⌃⌄ handle (edit mode, pinned cells only) hands the height back to the content. `defaultH` in the registry is likewise only a first-paint ballpark.++**Mobile editing.** Free-form move/resize is desktop-only (a phone has no room for positional editing), but *reordering* works on mobile: edit mode swaps the two grid handles for a single reorder handle. The 1-D sort goes through **`@dnd-kit/sortable`** — the same `PointerSensor` + `KeyboardSensor` + `verticalListSortingStrategy` pairing as `cos/tabs/TasksTab.jsx` and `universeBuilder/InfluenceChipsInput.jsx` — which is what supplies touch, keyboard (space to lift, arrows to move), multi-pointer safety, screen-reader announcements and edge auto-scroll. **Do not hand-roll a pointer gesture for this**; the free-form 2-D drag stays hand-rolled only because arbitrary grid placement is not what a sortable list does. Use `dndTransformToCss` from `client/src/lib/dndTransform.js` in the style object, never `@dnd-kit/utilities`.++On drop, `onDragEnd` re-flows the whole grid through `reflowToOrder` so its reading order matches the new stack order, preserving each widget's `w`/`h`. That means a mobile reorder re-packs the desktop layout into row-flow — the only coherent way to express a one-dimensional edit as column placement, and the edit-mode hint says so. `synthesizeGrid` is built on the same helper. The handle keeps `touch-action: none`; without it the browser claims the pointer stream for scrolling and the gesture never starts.++**One source of truth for the mobile/desktop seam.** `DashboardGrid` measures its own *container* (`useContainerWidth`), which page padding makes narrower than the viewport — so a Tailwind `sm:` breakpoint disagrees with it in a ~30px band. Anything outside the grid that needs to know which affordance is live (the Dashboard's edit-mode hint) reads it from the `onLayoutModeChange` callback, never from a CSS breakpoint.++**Widget order lives in the grid.** `saveGridEdit` rewrites the layout's `widgets` array into `readingOrderIds(grid)` so LayoutEditor lists widgets in the order the dashboard actually shows them. By default `reconcileGrid` iterates the *grid* and uses `widgets` only for membership — position edits survive a widget toggle or a rename. LayoutEditor's Move up/down buttons therefore have to say so explicitly: `save`/`commitDuplicate` pass `reordered`, which `isReordered()` derives by comparing the draft list against the `unmovedOrder` ref — the order the draft would have had if the user had never pressed Move (`add` appends to it, `remove` filters it, `move` deliberately doesn't touch it). That baseline can't be reconstructed from the widget list after the fact, since nothing in it records which widgets were added this session or in what order; keeping it means a move-up-then-back nets out to `false` while a just-added widget being moved, or any reorder in a layout that started empty, still reads as `true`, and `Dashboard.jsx` forwards it as `reconcileGrid(base, widgets, { reorder })`, which re-flows the reconciled grid to the list order. **Never infer that flag by comparing `widgets` to `readingOrderIds(grid)`** — layouts arranged before `saveGridEdit` started syncing the two can already disagree, so inferring would re-pack a carefully arranged desktop layout on the first unrelated save (#4132).++**When adding a new dashboard widget:**+1. Add a `{ id, label, Component, width, defaultH?, gate? }` entry to `WIDGETS` in `widgetRegistry.jsx`. Use a stable `id` (kebab-case) — it's the contract stored in layouts. Pick `defaultH` from the widget's rough content height (default `4`); it only has to be close, since the cell measures itself once painted.+2. If the widget needs dashboard data (apps/usage/health), read it from the `dashboardState` prop — do NOT issue a duplicate fetch from inside the widget.+3. If the widget only makes sense in some cases (e.g. only when apps exist), add a `gate: (state) => boolean` predicate.+4. Add the widget id to the built-in `default` layout in `server/services/dashboardLayouts.js` if it should appear out of the box.+5. Users can toggle widgets on/off per layout via the Dashboard's layout picker → Edit, and arrange/resize them via the "Arrange" button.++Switching layouts is also wired into the `⌘K` palette — it synthesizes a `Dashboard: <name>` command per layout at palette-open time, so any layout the user creates is instantly keyboard-reachable without further registration.diff --git a/client/src/components/dashboard/CLAUDE.md b/client/src/components/dashboard/CLAUDE.mdindex 4340149234..43c994c2d3 100644--- a/client/src/components/dashboard/CLAUDE.md+++ b/client/src/components/dashboard/CLAUDE.md@@ -1,26 +1 @@-# Dashboard Widgets & Layouts (`client/src/components/dashboard/`)--Dashboard widgets are registered in `widgetRegistry.jsx` — each entry has `{ id, label, Component, width, defaultH?, gate? }`. The Dashboard page renders the active layout's widget list from this registry; named layouts persist in `data/dashboard-layouts.json` and are managed via `GET/PUT/DELETE /api/dashboard/layouts`. Built-in layouts (`default`, `focus`, `morning-review`, `ops`) are seeded on first read and cannot be deleted.--**Grid positions:** layouts also carry a `grid: [{ id, x, w, order, h?, fixedH? }]` array — column placement on a 12-column grid plus a reading/packing sequence. When `grid` is empty (legacy/unmigrated layouts) the renderer auto-flows widgets using `synthesizeGrid` based on each widget's `width` keyword and `defaultH`. The "Arrange" button on the Dashboard enters edit mode where every widget exposes a move (top-right) and resize (bottom-right) handle; a move snaps horizontally to columns and re-inserts the cell into the sequence at the rank its dropped pixel position implies (`rankAtPixel` → `insertAtOrder`), renumbering `order` densely. Save persists to the active layout's `grid`. The grid renderer collapses to a single-column stack below 640px container width, rendered in reading order (`order`, then `x` as a tiebreak) — never grid-array order, which nothing keeps sorted.--**One vertical coordinate (#4133).** There is no stored row position. Horizontal placement is declared (`x`/`w`); vertical placement belongs entirely to `packVertically`, which lays cells out in pixels, and `order` says only which cell packs first. That is why a gesture never has to reconcile "where the cell says it is" with "where it is drawn" — only one of those exists. Persisted layouts predating this carried `{ x, y, w, h }`; `sanitizeGridItem`/`sequenceGrid` in `server/services/dashboardLayouts.js` still derive `order` from a legacy `y` on read (shape-probed, not version-flagged), and `scripts/migrations/269-dashboard-grid-order.js` rewrites the file on disk. **A new widget-seeding migration must append `{ id, x, w, order, h }`, not `{ x, y, w, h }`** — the older seed migrations (029/030/033/070/145/156/191) still compute `y` because they only ever run on pre-269 files.--**Height is measured, not declared.** `h` is NOT the rendered height. A cell measures its widget's natural height with a `ResizeObserver` and `packVertically` positions everything in pixels — each cell floats up to just below the nearest already-placed cell that shares a column. That's what stops an 80px card from reserving a 400px slot and leaving a band of dead whitespace across the row. `h` survives as the pre-measurement fallback (first paint) and as what an older client — which knows nothing about `fixedH` — reads out of a saved layout, so every drag commit refreshes it from the measurement via `withMeasuredHeights`. A cell whose height the user actually dragged carries `fixedH: true` and keeps `h` exactly, clipping content the way the whole grid used to; the ⌃⌄ handle (edit mode, pinned cells only) hands the height back to the content. `defaultH` in the registry is likewise only a first-paint ballpark.--**Mobile editing.** Free-form move/resize is desktop-only (a phone has no room for positional editing), but *reordering* works on mobile: edit mode swaps the two grid handles for a single reorder handle. The 1-D sort goes through **`@dnd-kit/sortable`** — the same `PointerSensor` + `KeyboardSensor` + `verticalListSortingStrategy` pairing as `cos/tabs/TasksTab.jsx` and `universeBuilder/InfluenceChipsInput.jsx` — which is what supplies touch, keyboard (space to lift, arrows to move), multi-pointer safety, screen-reader announcements and edge auto-scroll. **Do not hand-roll a pointer gesture for this**; the free-form 2-D drag stays hand-rolled only because arbitrary grid placement is not what a sortable list does. Use `dndTransformToCss` from `client/src/lib/dndTransform.js` in the style object, never `@dnd-kit/utilities`.--On drop, `onDragEnd` re-flows the whole grid through `reflowToOrder` so its reading order matches the new stack order, preserving each widget's `w`/`h`. That means a mobile reorder re-packs the desktop layout into row-flow — the only coherent way to express a one-dimensional edit as column placement, and the edit-mode hint says so. `synthesizeGrid` is built on the same helper. The handle keeps `touch-action: none`; without it the browser claims the pointer stream for scrolling and the gesture never starts.--**One source of truth for the mobile/desktop seam.** `DashboardGrid` measures its own *container* (`useContainerWidth`), which page padding makes narrower than the viewport — so a Tailwind `sm:` breakpoint disagrees with it in a ~30px band. Anything outside the grid that needs to know which affordance is live (the Dashboard's edit-mode hint) reads it from the `onLayoutModeChange` callback, never from a CSS breakpoint.--**Widget order lives in the grid.** `saveGridEdit` rewrites the layout's `widgets` array into `readingOrderIds(grid)` so LayoutEditor lists widgets in the order the dashboard actually shows them. By default `reconcileGrid` iterates the *grid* and uses `widgets` only for membership — position edits survive a widget toggle or a rename. LayoutEditor's Move up/down buttons therefore have to say so explicitly: `save`/`commitDuplicate` pass `reordered`, which `isReordered()` derives by comparing the draft list against the `unmovedOrder` ref — the order the draft would have had if the user had never pressed Move (`add` appends to it, `remove` filters it, `move` deliberately doesn't touch it). That baseline can't be reconstructed from the widget list after the fact, since nothing in it records which widgets were added this session or in what order; keeping it means a move-up-then-back nets out to `false` while a just-added widget being moved, or any reorder in a layout that started empty, still reads as `true`, and `Dashboard.jsx` forwards it as `reconcileGrid(base, widgets, { reorder })`, which re-flows the reconciled grid to the list order. **Never infer that flag by comparing `widgets` to `readingOrderIds(grid)`** — layouts arranged before `saveGridEdit` started syncing the two can already disagree, so inferring would re-pack a carefully arranged desktop layout on the first unrelated save (#4132).--**When adding a new dashboard widget:**-1. Add a `{ id, label, Component, width, defaultH?, gate? }` entry to `WIDGETS` in `widgetRegistry.jsx`. Use a stable `id` (kebab-case) — it's the contract stored in layouts. Pick `defaultH` from the widget's rough content height (default `4`); it only has to be close, since the cell measures itself once painted.-2. If the widget needs dashboard data (apps/usage/health), read it from the `dashboardState` prop — do NOT issue a duplicate fetch from inside the widget.-3. If the widget only makes sense in some cases (e.g. only when apps exist), add a `gate: (state) => boolean` predicate.-4. Add the widget id to the built-in `default` layout in `server/services/dashboardLayouts.js` if it should appear out of the box.-5. Users can toggle widgets on/off per layout via the Dashboard's layout picker → Edit, and arrange/resize them via the "Arrange" button.--Switching layouts is also wired into the `⌘K` palette — it synthesizes a `Dashboard: <name>` command per layout at palette-open time, so any layout the user creates is instantly keyboard-reachable without further registration.diff --git a/client/src/components/dashboard/builtins/DailyDriverWidget.jsx b/client/src/components/dashboard/builtins/DailyDriverWidget.jsxindex cf96a3fe74..071f97cb03 100644--- a/client/src/components/dashboard/builtins/DailyDriverWidget.jsx+++ b/client/src/components/dashboard/builtins/DailyDriverWidget.jsx@@ -31,7 +31,7 @@ export default function DailyDriverWidget({ dashboardState }) {const [goals, setGoals] = useState([]);// Sentinel: distinguish "goals failed to load" from "no goals exist" so a// transient fetch failure doesn't show the "Define your goals" CTA to a user- // who already has goals (CLAUDE.md "absent/failed vs legitimately-empty").+ // who already has goals (AGENTS.md "absent/failed vs legitimately-empty").const [goalsFailed, setGoalsFailed] = useState(false);const [loaded, setLoaded] = useState(false);const [dismissing, setDismissing] = useState(false);diff --git a/client/src/components/digital-twin/constants.js b/client/src/components/digital-twin/constants.jsindex 56fef9973f..22d9c24be2 100644--- a/client/src/components/digital-twin/constants.js+++ b/client/src/components/digital-twin/constants.js@@ -356,10 +356,10 @@ export const EXPORT_FORMATS = {label: 'System Prompt',description: 'Combined markdown for direct injection into LLM system prompts'},- claude_md: {- id: 'claude_md',- label: 'CLAUDE.md',- description: 'Format optimized for Claude Code integration'+ agents_md: {+ id: 'agents_md',+ label: 'AGENTS.md',+ description: 'Format for agent-instructions files (AGENTS.md / CLAUDE.md)'},json: {id: 'json',diff --git a/client/src/components/digital-twin/tabs/AutobiographyTab.jsx b/client/src/components/digital-twin/tabs/AutobiographyTab.jsxindex b84b65c6cc..3b78526efc 100644--- a/client/src/components/digital-twin/tabs/AutobiographyTab.jsx+++ b/client/src/components/digital-twin/tabs/AutobiographyTab.jsx@@ -163,7 +163,7 @@ export default function AutobiographyTab({ onRefresh }) {const handleWeaveNarrative = async (storyId) => {setWeavingStoryId(storyId);// request() already toasts on failure; the catch only swallows so the- // loading state still resets (avoids the double-toast in CLAUDE.md).+ // loading state still resets (avoids the double-toast in AGENTS.md).const result = await api.weaveAutobiographyNarrative(storyId).catch(() => null);if (result?.narrative) {setNarrative({ storyId, text: result.narrative, storyCount: result.storyCount });diff --git a/client/src/components/digital-twin/tabs/ExportTab.jsx b/client/src/components/digital-twin/tabs/ExportTab.jsxindex a3362d95e9..de4fcec427 100644--- a/client/src/components/digital-twin/tabs/ExportTab.jsx+++ b/client/src/components/digital-twin/tabs/ExportTab.jsx@@ -102,6 +102,8 @@ export default function ExportTab({ onRefresh: _onRefresh }) {switch (formatId) {case 'system_prompt':return FileText;+ case 'agents_md':+ // Pre-#4852 id, still resolvable from a persisted preference.case 'claude_md':return Code;case 'json':@@ -307,11 +309,11 @@ export default function ExportTab({ onRefresh: _onRefresh }) {</div>)}- {selectedFormat === 'claude_md' && (+ {(selectedFormat === 'agents_md' || selectedFormat === 'claude_md') && (<div className="text-sm text-gray-400 space-y-2"><p>1. Download or copy the export</p>- <p>2. Add to your project as <code className="bg-port-bg px-1 rounded">CLAUDE.md</code></p>- <p>3. Claude Code will automatically read and apply these instructions</p>+ <p>2. Add to your project as <code className="bg-port-bg px-1 rounded">AGENTS.md</code>, with a <code className="bg-port-bg px-1 rounded">CLAUDE.md</code> next to it containing just <code className="bg-port-bg px-1 rounded">@AGENTS.md</code></p>+ <p>3. Every agent CLI — Claude Code included — will read and apply these instructions</p></div>)}diff --git a/client/src/components/goals/goalConstants.js b/client/src/components/goals/goalConstants.jsindex 12868bc27b..c57f248c33 100644--- a/client/src/components/goals/goalConstants.js+++ b/client/src/components/goals/goalConstants.js@@ -3,7 +3,7 @@ import {} from 'lucide-react';// Canonical goals routes. Which goal is open lives in the URL, never in local state-// (see client/src/CLAUDE.md), so a specific goal is shareable, bookmarkable, and+// (see client/src/AGENTS.md), so a specific goal is shareable, bookmarkable, and// linkable from other surfaces — e.g. the Character sheet's Life Goals card.export const GOALS_LIST_PATH = '/goals/list';export const goalDetailPath = (goalId) => `${GOALS_LIST_PATH}/${encodeURIComponent(goalId)}`;diff --git a/client/src/components/imageGen/HfTokenBanner.jsx b/client/src/components/imageGen/HfTokenBanner.jsxindex 277e3356f8..9401c7576d 100644--- a/client/src/components/imageGen/HfTokenBanner.jsx+++ b/client/src/components/imageGen/HfTokenBanner.jsx@@ -5,7 +5,7 @@* settings.json (which the local-image worker reads when spawning mflux /* flux2_macos.py).*- * Single-user app behind Tailscale — see CLAUDE.md security model — so a+ * Single-user app behind Tailscale — see AGENTS.md security model — so a* plaintext settings entry is the appropriate trade-off vs. a separate* keystore.*/diff --git a/client/src/components/meatspace/post/CognitiveDrillTutorial.jsx b/client/src/components/meatspace/post/CognitiveDrillTutorial.jsxindex 9df6a6dd54..4cc2ecdc13 100644--- a/client/src/components/meatspace/post/CognitiveDrillTutorial.jsx+++ b/client/src/components/meatspace/post/CognitiveDrillTutorial.jsx@@ -281,7 +281,7 @@ export function CognitiveDrillTutorialPreview({ type, drillConfig, cognitiveProg);}return (- // `usePortal` per the overlay convention in client/src/CLAUDE.md: this is+ // `usePortal` per the overlay convention in client/src/AGENTS.md: this is// rendered mid-tree inside two long settings/launcher pages, and a// `backdrop-filter` ancestor (every bordered `.bg-port-card` on the glass// themes) would otherwise become the fixed overlay's containing block.diff --git a/client/src/components/meatspace/post/ElementsSong.jsx b/client/src/components/meatspace/post/ElementsSong.jsxindex 62c5ea8464..fd80bcaa5d 100644--- a/client/src/components/meatspace/post/ElementsSong.jsx+++ b/client/src/components/meatspace/post/ElementsSong.jsx@@ -109,7 +109,7 @@ export default function ElementsSong({ item: itemProp, onBack, loadItemOnMount,// Sum `{ attempts, correct }` mastery buckets into a single accuracy in [0,1].// Returns null when nothing has been attempted, so "never practiced" stays// distinguishable from "practiced and scored zero" (the sentinel rule in-// CLAUDE.md) — the caller routes those two to different modes.+// AGENTS.md) — the caller routes those two to different modes.function bucketAccuracy(buckets) {const attempted = Object.values(buckets || {}).map(stat => {diff --git a/client/src/components/meatspace/post/MemoryPractice.jsx b/client/src/components/meatspace/post/MemoryPractice.jsxindex 473612d541..10d746bb75 100644--- a/client/src/components/meatspace/post/MemoryPractice.jsx+++ b/client/src/components/meatspace/post/MemoryPractice.jsx@@ -26,7 +26,7 @@ export const MEMORY_PRACTICE_MODE_IDS = MODES.map(m => m.id);* practice runner. `item` is an optional seed the caller already has in hand (a* fresh navigation from the list) — a cold deep link has none, so the item is* fetched. An id that doesn't resolve renders a not-found fallback rather than a- * blank panel, per the deep-link contract in CLAUDE.md.+ * blank panel, per the deep-link contract in AGENTS.md.*/export default function MemoryPractice({ itemId, item: seedItem, mode, onSelectMode, onExitMode, onBack, onContinue }) {const [loadedItem, setLoadedItem] = useState(null);diff --git a/client/src/components/meatspace/post/PostSessionLauncher.jsx b/client/src/components/meatspace/post/PostSessionLauncher.jsxindex 7413537702..11d3683de7 100644--- a/client/src/components/meatspace/post/PostSessionLauncher.jsx+++ b/client/src/components/meatspace/post/PostSessionLauncher.jsx@@ -359,7 +359,7 @@ export default function PostSessionLauncher({// (mental-math + cognitive) excludes Memory and LLM drills, so both remain// deliberate opt-ins and wit/verbal work// is never auto-added to a default session — provider-cost consent stays- // opt-in (CLAUDE.md AI-provider policy). An empty/absent list means "all+ // opt-in (AGENTS.md AI-provider policy). An empty/absent list means "all// enabled" (back-compat). Focus-practice on a specific weak domain bypasses// this filter (it's an explicit user choice, not a default composition).// `null` = no sessionModules set (legacy/absent) → include all enableddiff --git a/client/src/components/meatspace/post/WordplayTrainer.jsx b/client/src/components/meatspace/post/WordplayTrainer.jsxindex e788b37a5b..657264657d 100644--- a/client/src/components/meatspace/post/WordplayTrainer.jsx+++ b/client/src/components/meatspace/post/WordplayTrainer.jsx@@ -73,7 +73,7 @@ export default function WordplayTrainer({ onBack, onContinue, config, onConfigUp// Which mode we've already kicked off generation for, so the URL-driven// effect below doesn't regenerate on every render.const initiatedRef = useRef(null);- // Per-run generation token (CLAUDE.md's {target, generation} pattern). Every+ // Per-run generation token (AGENTS.md's {target, generation} pattern). Every// generation start bumps it; a completing runMode aborts unless its captured// token is still current — so a superseded run (re-enter the same mode, or a// direct mode→mode URL change mid-generation) can't land a stale drill ordiff --git a/client/src/components/meatspace/tabs/SettingsTab.jsx b/client/src/components/meatspace/tabs/SettingsTab.jsxindex 08527a69e4..739f8bf039 100644--- a/client/src/components/meatspace/tabs/SettingsTab.jsx+++ b/client/src/components/meatspace/tabs/SettingsTab.jsx@@ -94,7 +94,7 @@ export default function SettingsTab({ onRefresh }) {setXmlImporting(true);// Owns its own error UI (xmlError) so suppress the helper's toast — per- // CLAUDE.md "custom catch ⇒ silent: true" convention.+ // AGENTS.md "custom catch ⇒ silent: true" convention.api.uploadAppleHealthXml(file, { silent: true }).catch(err => {setXmlError(err.message);setXmlImporting(false);diff --git a/client/src/components/music/MusicDesigner.jsx b/client/src/components/music/MusicDesigner.jsxindex 80210c9c6e..af388a7922 100644--- a/client/src/components/music/MusicDesigner.jsx+++ b/client/src/components/music/MusicDesigner.jsx@@ -13,7 +13,7 @@** Two constraints shape this component:*- * - **No cold-bootstrap LLM calls** (root CLAUDE.md). Both provider calls fire+ * - **No cold-bootstrap LLM calls** (root AGENTS.md). Both provider calls fire* only from an explicit button press in the same interaction — nothing runs* on mount, on blur, or ahead of the user.* - **Selection lives in the URL.** The active step is the `:id` slot of thediff --git a/client/src/components/pipeline/stages/AudioStage.jsx b/client/src/components/pipeline/stages/AudioStage.jsxindex af9d61b54c..5f884fe18f 100644--- a/client/src/components/pipeline/stages/AudioStage.jsx+++ b/client/src/components/pipeline/stages/AudioStage.jsx@@ -64,7 +64,7 @@ export default function AudioStage({ issue, onStageUpdate }) {// even though we PATCH only on blur (or before render).const [drafts, setDrafts] = useState({});// Pending PATCH promises by line index so handleRender can await every- // outstanding save before kicking off the synth (CLAUDE.md "In-flight+ // outstanding save before kicking off the synth (AGENTS.md "In-flight// saves must gate dependent actions"). Refs not state — we never// re-render because of this and we want the latest value inside async// handlers. Stored as `Map<lineIdx, Set<Promise>>` because a single@@ -94,7 +94,7 @@ export default function AudioStage({ issue, onStageUpdate }) {// behind an install hint so a 503 never surprises them mid-prompt.const [genPanelOpen, setGenPanelOpen] = useState(false);const [generators, setGenerators] = useState(null);- // Sentinel discipline (CLAUDE.md "distinguish not-fetched from failed"):+ // Sentinel discipline (AGENTS.md "distinguish not-fetched from failed"):// generators === null is "not fetched yet"; generatorsError !== null means a// fetch failed, so the cue panel can offer a Retry instead of showing a// perpetual "Checking engine…" that never resolves.@@ -129,7 +129,7 @@ export default function AudioStage({ issue, onStageUpdate }) {// Whole-episode audio mode (#863). Persists via the existing PATCH /issues/:id// route. `audioModeSaving` gates the mode-dependent cue actions while the- // PATCH is in flight (CLAUDE.md "in-flight saves must gate dependent actions").+ // PATCH is in flight (AGENTS.md "in-flight saves must gate dependent actions").const [audioModeSaving, setAudioModeSaving] = useState(false);// Generated-cue state: deriving the list, rendering each / all cues, and// per-cue prompt drafts (committed on blur via the cue write queue below).@@ -437,7 +437,7 @@ export default function AudioStage({ issue, onStageUpdate }) {if (!file) return;setMusicUploading(true);// Owns its own error UI (toast.error below) so suppress the helper's toast- // — per CLAUDE.md "custom catch ⇒ silent: true" convention.+ // — per AGENTS.md "custom catch ⇒ silent: true" convention.const result = await uploadPipelineMusicTrack(issue.id, file, {}, { silent: true }).catch((err) => {toast.error(err.message || 'Upload failed');return null;diff --git a/client/src/components/pipeline/stages/StoryboardsStage.jsx b/client/src/components/pipeline/stages/StoryboardsStage.jsxindex 160809789b..f8316746be 100644--- a/client/src/components/pipeline/stages/StoryboardsStage.jsx+++ b/client/src/components/pipeline/stages/StoryboardsStage.jsx@@ -217,7 +217,7 @@ export default function StoryboardsStage({ issue, series, onStageUpdate, actionsreturn;}// Flush any pending local edits to the server before rendering — otherwise- // the server reads the pre-edit shot.description (CLAUDE.md "In-flight+ // the server reads the pre-edit shot.description (AGENTS.md "In-flight// saves must gate dependent actions"). persist() returns when the PATCH// has settled, so the next read by the enqueue route sees the latest text.await persist(scenes);@@ -243,7 +243,7 @@ export default function StoryboardsStage({ issue, series, onStageUpdate, actions};// Replacing existing scenes shows an inline confirm near the buttons (no- // window.confirm per CLAUDE.md, no two-click-arm — the user disliked it). A+ // window.confirm per AGENTS.md, no two-click-arm — the user disliked it). A// fresh stage (no scenes yet) extracts immediately.const onExtractClick = (from) => {if (scenes.length > 0) {diff --git a/client/src/components/settings/AssessmentSweepPanel.jsx b/client/src/components/settings/AssessmentSweepPanel.jsxindex d6d1861d07..041fe54948 100644--- a/client/src/components/settings/AssessmentSweepPanel.jsx+++ b/client/src/components/settings/AssessmentSweepPanel.jsx@@ -9,7 +9,7 @@* reloading, must not stop or lose an overnight run — so there is no abort* controller here and no in-flight request to hold open.* 2. **Consent names real numbers.** The AI Provider Usage Policy (root- * CLAUDE.md) requires that a batch of provider calls be preceded by a gate+ * AGENTS.md) requires that a batch of provider calls be preceded by a gate* that says exactly what will run. The counts come from the server's own* target selector and its own tuning grid, not from a client-side estimate,* so the number shown is the number that executes.@@ -58,7 +58,7 @@ const measuredUnit = (status) => (status?.mode === 'tunings' ? 'tuning' : 'model/*** The Cancel/Start footer both sweeps share.*- * The AI Provider Usage Policy (root CLAUDE.md) demands the same three things of+ * The AI Provider Usage Policy (root AGENTS.md) demands the same three things of* either sweep — say what will run, say how many generations that is, and let* the user decline. The two gates differ in their container (the batch gate* targets no record, so it stays a modal; the per-model gate is a routablediff --git a/client/src/components/settings/BackupTab.test.jsx b/client/src/components/settings/BackupTab.test.jsxindex 63a1affbe3..6bbb0762af 100644--- a/client/src/components/settings/BackupTab.test.jsx+++ b/client/src/components/settings/BackupTab.test.jsx@@ -186,7 +186,7 @@ describe('BackupTab', () => {});describe('Run Now gating (saved state)', () => {- // The CLAUDE.md invariant: "Run Now must gate on saved state, not the form+ // The AGENTS.md invariant: "Run Now must gate on saved state, not the form// input." `canRun` keys off `savedDestPath` + `dirty`, never the live input.it('disables Run Backup Now when no destination is saved', async () => {getSettings.mockResolvedValue({ backup: { destPath: '', enabled: false, cronExpression: '0 2 * * *', excludePaths: [], disabledDefaultExcludes: [] } });diff --git a/client/src/components/settings/LocalModelAssessments.jsx b/client/src/components/settings/LocalModelAssessments.jsxindex ced4485137..3f764971bc 100644--- a/client/src/components/settings/LocalModelAssessments.jsx+++ b/client/src/components/settings/LocalModelAssessments.jsx@@ -8,7 +8,7 @@** ## Two rules this panel exists to honour*- * 1. **No cold-bootstrap LLM calls** (root CLAUDE.md). Reading assessments hits+ * 1. **No cold-bootstrap LLM calls** (root AGENTS.md). Reading assessments hits* disk only, so it loads with the tab. Running one calls a provider, so it* fires only from an explicit click AND a consent modal that names the* backend, the model, and how many generations are about to happen. The@@ -728,7 +728,7 @@ export function LocalModelAssessments() {const load = useCallback(async (nextIntent) => {setLoading(true);// The panel owns its own empty/error rendering, so silence the default toast- // (client/src/CLAUDE.md: custom catch ⇒ silent).+ // (client/src/AGENTS.md: custom catch ⇒ silent).const data = await getLocalLlmAssessments(nextIntent, { silent: true }).catch(() => null);setReport(data);setLoading(false);@@ -738,7 +738,7 @@ export function LocalModelAssessments() {const loadCapabilities = useCallback(async () => {setCapabilityLoading(true);- // The panel renders its own empty/error state (client/src/CLAUDE.md: custom+ // The panel renders its own empty/error state (client/src/AGENTS.md: custom// catch ⇒ silent).const data = await getModelCapabilityTests({ silent: true }).catch(() => null);setCapabilityReport(data);diff --git a/client/src/components/settings/MemoryManagement.jsx b/client/src/components/settings/MemoryManagement.jsxindex d57a9b71e5..4f389ca735 100644--- a/client/src/components/settings/MemoryManagement.jsx+++ b/client/src/components/settings/MemoryManagement.jsx@@ -18,7 +18,7 @@// fallbacks in `refresh()` (for poll failures, which must NOT toast — the// panel would otherwise spam an error toast every 5s during a transient// Ollama outage). Every API helper is called with `{ silent: true }` so-// apiCore's default toast doesn't fire underneath; per the CLAUDE.md+// apiCore's default toast doesn't fire underneath; per the AGENTS.md// "Silent vs. toasting API requests" rule, custom catch ⇒ silent: true.import { useState, useEffect, useCallback, useRef } from 'react';diff --git a/client/src/components/settings/ModelCapabilityTests.jsx b/client/src/components/settings/ModelCapabilityTests.jsxindex 91754fce43..4f88e1708d 100644--- a/client/src/components/settings/ModelCapabilityTests.jsx+++ b/client/src/components/settings/ModelCapabilityTests.jsx@@ -12,7 +12,7 @@* 1. **An unclaimed capability is not a failure.** A model with no `vision`* badge shows "not applicable" on the image test, in muted grey, never a red* X. A red cell always means "it said it could, and it could not".- * 2. **No cold-bootstrap LLM calls** (root CLAUDE.md). The report loads with the+ * 2. **No cold-bootstrap LLM calls** (root AGENTS.md). The report loads with the* tab and calls nothing. Running a test goes through a consent gate that* names the runtime, the model, the test and the prompt first.* 3. **Show the output.** Every result view leads with what the model actually@@ -693,7 +693,7 @@ export default function ModelCapabilityTests({ report, loading, onReload, disablif (!open || !slot?.result) { setFullResult(null); return undefined; }let live = true;// The drawer renders its own empty state, so the default toast is silenced- // (client/src/CLAUDE.md: custom catch ⇒ silent).+ // (client/src/AGENTS.md: custom catch ⇒ silent).getModelCapabilityTestResult(backend, modelId, testId, { silent: true }).then((record) => { if (live) setFullResult(record); }).catch(() => { if (live) setFullResult(null); });@@ -728,7 +728,7 @@ export default function ModelCapabilityTests({ report, loading, onReload, disablsetRunning(true);// The panel renders its own progress and error state, so the default toast- // is silenced (client/src/CLAUDE.md: custom catch ⇒ silent).+ // is silenced (client/src/AGENTS.md: custom catch ⇒ silent).const result = await runModelCapabilityTest({ backend: runBackend, modelId: runModel, testId: id },{ signal: controller.signal, silent: true },diff --git a/client/src/components/sharing/SyncToPeerButton.jsx b/client/src/components/sharing/SyncToPeerButton.jsxindex ecaf9c8711..f69d20bf56 100644--- a/client/src/components/sharing/SyncToPeerButton.jsx+++ b/client/src/components/sharing/SyncToPeerButton.jsx@@ -120,7 +120,7 @@ export default function SyncToPeerButton({const existing = subscriptionForPeer(peer.instanceId);if (existing) {// silent:true — the catch below already owns the error toast, so the- // apiCore helper must not fire its own (per CLAUDE.md "Custom catch ⇒+ // apiCore helper must not fire its own (per AGENTS.md "Custom catch ⇒// silent: true" rule). Otherwise the user sees two toasts on failure.const ok = await unsubscribeFromPeer(existing.id, { silent: true }).catch((err) => {toast.error(err.message || `Unsync from ${peer.name} failed`);diff --git a/client/src/components/songbook/PracticeLogger.jsx b/client/src/components/songbook/PracticeLogger.jsxindex a0e2cd5837..3688bced8e 100644--- a/client/src/components/songbook/PracticeLogger.jsx+++ b/client/src/components/songbook/PracticeLogger.jsx@@ -22,7 +22,7 @@ import {export default function PracticeLogger({ song, onLogged, className = '' }) {// `useAsyncAction` owns the error toast, so the request itself stays silent —- // one error layer only (client/src/CLAUDE.md).+ // one error layer only (client/src/AGENTS.md).const [logPractice, logging] = useAsyncAction(async (quality) => {const updated = await practiceSong(song.id, quality, { silent: true });onLogged?.(updated);diff --git a/client/src/components/songs/PitchTuner.jsx b/client/src/components/songs/PitchTuner.jsxindex 3e43a2ca1e..598ba0cfb7 100644--- a/client/src/components/songs/PitchTuner.jsx+++ b/client/src/components/songs/PitchTuner.jsx@@ -13,7 +13,7 @@* The needle/note are colored by `tuningQuality` (green in-tune, yellow close,* red off) using `--port-*` tokens only. The AnalyserNode + the pitch tracker's* rAF loop are torn down on stop, on stream-change, and on unmount (the- * deferred-work teardown rule in CLAUDE.md) so no audio graph or loop dangles.+ * deferred-work teardown rule in AGENTS.md) so no audio graph or loop dangles.*/import { useCallback, useEffect, useRef, useState } from 'react';diff --git a/client/src/components/sprites/WalkSourceFrames.jsx b/client/src/components/sprites/WalkSourceFrames.jsxindex e2c16c77ef..c54407bef2 100644--- a/client/src/components/sprites/WalkSourceFrames.jsx+++ b/client/src/components/sprites/WalkSourceFrames.jsx@@ -121,7 +121,7 @@ function WalkSourceFrames({ recordId, runId, onSaved = () => {} }) {const [confirming, setConfirming] = useState(false);// The cycle target's PUT is its own request; the re-derive below reads the// target server-side, so it must not fire against a value the server has not- // persisted yet (CLAUDE.md: "in-flight saves must gate dependent actions").+ // persisted yet (AGENTS.md: "in-flight saves must gate dependent actions").const [targetSaving, setTargetSaving] = useState(false);const load = useCallback(async () => {diff --git a/client/src/components/sprites/WalkSourceFrames.test.jsx b/client/src/components/sprites/WalkSourceFrames.test.jsxindex 88cd717aff..b4a3727647 100644--- a/client/src/components/sprites/WalkSourceFrames.test.jsx+++ b/client/src/components/sprites/WalkSourceFrames.test.jsx@@ -170,7 +170,7 @@ describe('WalkSourceFrames', () => {});// The dependent action must not fire against a target the server has not- // persisted yet (CLAUDE.md: in-flight saves gate dependent actions).+ // persisted yet (AGENTS.md: in-flight saves gate dependent actions).it('disables the re-derive while the target PUT is in flight', async () => {let release;setSpriteWalkTarget.mockReturnValue(new Promise((resolve) => { release = resolve; }));diff --git a/client/src/components/ui/README.md b/client/src/components/ui/README.mdindex 9ad2e11e60..1b7c216e15 100644--- a/client/src/components/ui/README.md+++ b/client/src/components/ui/README.md@@ -43,7 +43,7 @@ accessibility). Feature-specific components live under their own feature directoThere is no `index.js` barrel here — components are imported by path(`import ProgressBar from '../ui/ProgressBar'`), matching the rest of `components/`. The-barrel + README rule in the root `CLAUDE.md` covers `lib/`, `hooks/`, `utils/`, and+barrel + README rule in the root `AGENTS.md` covers `lib/`, `hooks/`, `utils/`, and`services/`; this catalog exists for discovery only. **Adding a primitive here meansadding its row above** — a catalog nobody updates is the reason six copies of theprogress meter existed in the first place.diff --git a/client/src/components/ui/RouteTabsHeader.jsx b/client/src/components/ui/RouteTabsHeader.jsxindex 27f6eb5f81..8ed84868ae 100644--- a/client/src/components/ui/RouteTabsHeader.jsx+++ b/client/src/components/ui/RouteTabsHeader.jsx@@ -14,7 +14,7 @@ const selectIdFor = (ariaLabel) => `${String(ariaLabel || 'section').toLowerCase* the "tab bar" is really a navigation control: selecting one navigates instead* of swapping state. That is what makes each tab deep-linkable and reachable* from ⌘K and voice — the URL is the source of truth for what is open- * (`client/src/CLAUDE.md`).+ * (`client/src/AGENTS.md`).** Each section owns its own `TABS` array (`{ id, label, to }`) and passes it in;* the navigation shim is the same for all of them. Sections may include a tabdiff --git a/client/src/components/universeBuilder/UniverseBuilderPage.jsx b/client/src/components/universeBuilder/UniverseBuilderPage.jsxindex 52cf82f265..0728440e6c 100644--- a/client/src/components/universeBuilder/UniverseBuilderPage.jsx+++ b/client/src/components/universeBuilder/UniverseBuilderPage.jsx@@ -191,7 +191,7 @@ export default function UniverseBuilder() {clearPendingCanonAdditions,setRenderOpts,});- // URL-driven tab + bucket state (per CLAUDE.md "Linkable routes for all+ // URL-driven tab + bucket state (per AGENTS.md "Linkable routes for all// views"), including the self-healing effects that strip a `?tab=`/`?bucket=`// the current categories no longer support.const {diff --git a/client/src/hooks/index.js b/client/src/hooks/index.jsindex 618734d74b..90d54cd1e7 100644--- a/client/src/hooks/index.js+++ b/client/src/hooks/index.js@@ -1,6 +1,6 @@// Barrel for client/src/hooks/ — discovery surface, not a forced import path.// See client/src/hooks/README.md for the human-readable catalog and-// CLAUDE.md "Module organization" for the maintenance convention.+// AGENTS.md "Module organization" for the maintenance convention.//// Hooks export shape: most are named exports (`export function useX`), but a// handful default-export (`export default function useX`). The barreldiff --git a/client/src/hooks/useAutoscroll.js b/client/src/hooks/useAutoscroll.jsindex 42db19c839..9a558a753d 100644--- a/client/src/hooks/useAutoscroll.js+++ b/client/src/hooks/useAutoscroll.js@@ -32,7 +32,7 @@ export default function useAutoscroll(pxPerSecRef.current = pxPerSec;// Gates the auto-stop setState so a rAF frame that lands after unmount is- // inert. (The CLAUDE.md "never reset to true" rule is for deferred network+ // inert. (The AGENTS.md "never reset to true" rule is for deferred network// emits, where staying false is the safe direction — here it gates live UI.)const mountedRef = useMounted();diff --git a/client/src/hooks/useCanonPatch.js b/client/src/hooks/useCanonPatch.jsindex 3b336dea56..0e73ecaaa3 100644--- a/client/src/hooks/useCanonPatch.js+++ b/client/src/hooks/useCanonPatch.js@@ -38,7 +38,7 @@ export function useCanonPatch({ universe, apply, mountedRef }) {apply({ ...universe, [kindKey]: list });// `{ silent: true }` because the .catch below owns the failure toast —// without it the apiCore request() helper fires a second, duplicate one- // (CLAUDE.md "Custom catch ⇒ silent: true").+ // (AGENTS.md "Custom catch ⇒ silent: true").const updated = await updateUniverse(capturedId, { [kindKey]: list }, { silent: true }).catch((err) => { toast.error(`Save failed: ${err.message}`); return null; });if (updated && mountedRef.current && currentUniverseIdRef.current === capturedId) {diff --git a/client/src/hooks/useColorMatch.js b/client/src/hooks/useColorMatch.jsindex aa803d15ba..d3d652ebb0 100644--- a/client/src/hooks/useColorMatch.js+++ b/client/src/hooks/useColorMatch.js@@ -14,7 +14,7 @@// downbeat — kicks a rAF loop that reads elapsed audio time, finds the active// note, grades it, and accumulates the best grade per note (a note "wins" its// best attempt across the frames it's active). Everything tears down on stop and-// on unmount (the deferred-work teardown rule in CLAUDE.md).+// on unmount (the deferred-work teardown rule in AGENTS.md).import { useCallback, useEffect, useRef, useState } from 'react';import { createStreamAnalyser } from '../lib/audioRecorder.js';diff --git a/client/src/hooks/useHfTokenStatus.js b/client/src/hooks/useHfTokenStatus.jsindex 0f56eb40ed..c4a1114410 100644--- a/client/src/hooks/useHfTokenStatus.js+++ b/client/src/hooks/useHfTokenStatus.js@@ -10,7 +10,7 @@* `present` is deliberately tri-state: `null` means "not fetched yet or the fetch* failed", NOT "absent". Callers must branch on all three, or a slow status call* flashes "add a token" at a user who already has one (the absent-vs-unknown rule in- * CLAUDE.md). A surface that would rather offer the paste form on a failed fetch opts+ * AGENTS.md). A surface that would rather offer the paste form on a failed fetch opts* in explicitly with `errorAs: 'absent'`.*/diff --git a/client/src/hooks/useOpenWorldPlayback.js b/client/src/hooks/useOpenWorldPlayback.jsindex 9901a4fb0f..7bb639072b 100644--- a/client/src/hooks/useOpenWorldPlayback.js+++ b/client/src/hooks/useOpenWorldPlayback.js@@ -23,7 +23,7 @@ export function useOpenWorldPlayback() {// load" vs "nothing recorded yet" — the absent-vs-empty rule.const [error, setError] = useState(false);- // Guards a deferred/interval callback against firing after unmount (CLAUDE.md+ // Guards a deferred/interval callback against firing after unmount (AGENTS.md// deferred-work rule).const mountedRef = useMounted();diff --git a/client/src/hooks/useSingToScore.js b/client/src/hooks/useSingToScore.jsindex 945ba4920c..eba01280ae 100644--- a/client/src/hooks/useSingToScore.js+++ b/client/src/hooks/useSingToScore.js@@ -10,7 +10,7 @@//// All Web Audio + rAF resources (mic stream, analyser graph, tracker loop,// metronome) tear down on stop AND on unmount (the deferred-work teardown rule-// in CLAUDE.md) so nothing dangles after navigation-away.+// in AGENTS.md) so nothing dangles after navigation-away.import { useCallback, useEffect, useRef, useState } from 'react';import { createStreamAnalyser } from '../lib/audioRecorder.js';diff --git a/client/src/hooks/useSongTraining.js b/client/src/hooks/useSongTraining.jsindex bdc6a860e4..0426627367 100644--- a/client/src/hooks/useSongTraining.js+++ b/client/src/hooks/useSongTraining.js@@ -96,7 +96,7 @@ export default function useSongTraining({// Cancel a pending loop relaunch on stop / unmount / loop-off so a deferred// restart can't fire after the user stopped (the deferred-work staleness +- // unmount guard from CLAUDE.md).+ // unmount guard from AGENTS.md).const clearRelaunch = useCallback(() => {if (relaunchRef.current != null) { clearTimeout(relaunchRef.current); relaunchRef.current = null; }}, []);diff --git a/client/src/hooks/useUniverseAction.js b/client/src/hooks/useUniverseAction.jsindex 0a9081eb5d..330a891de5 100644--- a/client/src/hooks/useUniverseAction.js+++ b/client/src/hooks/useUniverseAction.js@@ -12,7 +12,7 @@ import { upsertByIdPrepend } from '../lib/upsertByIdPrepend';// would warp it for almost no shared scaffolding.//// `action(capturedId)` must pass `{ silent: true }` to its API helper so-// toasts only fire from this hook (per CLAUDE.md "Custom catch ⇒ silent").+// toasts only fire from this hook (per AGENTS.md "Custom catch ⇒ silent").// `onFreshResult(result, { capturedId })` runs only when the user is still// on the same universe; return a string to use as the success toast.// `preflight()` runs AFTER the ref/savedId guards (so duplicate clicks short-diff --git a/client/src/hooks/useUniverseAction.test.jsx b/client/src/hooks/useUniverseAction.test.jsxindex d612c3014f..c9f315ed60 100644--- a/client/src/hooks/useUniverseAction.test.jsx+++ b/client/src/hooks/useUniverseAction.test.jsx@@ -209,7 +209,7 @@ describe('useUniverseAction', () => {return { universe: { id } };});await run({ ref, setBusy, action });- // CLAUDE.md "Deferred work must respect both staleness and unmount" —+ // AGENTS.md "Deferred work must respect both staleness and unmount" —// hook intentionally skips ref/busy reset when unmounted to avoid// post-unmount setState.expect(ref.current).toBe(true);diff --git a/client/src/hooks/useUniverseTabs.js b/client/src/hooks/useUniverseTabs.jsindex e7954be2a3..83ef6ade47 100644--- a/client/src/hooks/useUniverseTabs.js+++ b/client/src/hooks/useUniverseTabs.js@@ -14,7 +14,7 @@ import {} from '../lib/universeBuilderShared';/**- * URL-driven tab + bucket state for the Universe Builder (per CLAUDE.md+ * URL-driven tab + bucket state for the Universe Builder (per AGENTS.md* "Linkable routes for all views"). `?tab=cast&bucket=heroes` deep-links into* a sub-bucket; both fall back to bible / "" (All) on first load. Existing* params (e.g. `?series=` on the embedded Canon section) are forwardeddiff --git a/client/src/hooks/useUnsavedChangesGuard.js b/client/src/hooks/useUnsavedChangesGuard.jsindex ff4e74300a..34fd3afeb6 100644--- a/client/src/hooks/useUnsavedChangesGuard.js+++ b/client/src/hooks/useUnsavedChangesGuard.js@@ -16,7 +16,7 @@ import { useBlocker } from 'react-router';// `createMemoryRouter` + `<RouterProvider>`, not `<MemoryRouter>`.//// The caller renders its OWN confirm UI from `blocked` — an `InlineConfirmRow`,-// never `window.confirm` (see client/src/CLAUDE.md).+// never `window.confirm` (see client/src/AGENTS.md).//// const { blocked, proceed, reset } = useUnsavedChangesGuard(isDirty);// {blocked && <InlineConfirmRow onConfirm={discardAndProceed} onCancel={reset} … />}diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex d55a1036d9..27b52db640 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -1,6 +1,6 @@// Barrel for client/src/lib/ — discovery surface, not a forced import path.// See client/src/lib/README.md for the human-readable catalog and-// CLAUDE.md "Module organization" for the maintenance convention.+// AGENTS.md "Module organization" for the maintenance convention.// === Prompt & rendering (mirror server/lib/ — keep byte-for-byte in sync) ===export * from './canonPrompt.js';diff --git a/client/src/lib/metronome.js b/client/src/lib/metronome.jsindex aba6d0703d..3921e81840 100644--- a/client/src/lib/metronome.js+++ b/client/src/lib/metronome.js@@ -149,7 +149,7 @@ export function createMetronome({const id = setTimeout(() => {pendingTimeouts.delete(id);// setTimeout runs outside the request lifecycle — a throwing consumer- // callback must not crash the process (CLAUDE.md deferred-work boundary).+ // callback must not crash the process (AGENTS.md deferred-work boundary).try {if (firstMusicBeat && onCountInComplete) onCountInComplete(info);if (onBeat) onBeat(info);diff --git a/client/src/lib/pitchDetect.js b/client/src/lib/pitchDetect.jsindex 832e8cffe4..f34b8ed2e9 100644--- a/client/src/lib/pitchDetect.js+++ b/client/src/lib/pitchDetect.js@@ -242,7 +242,7 @@ const median = (values) => {// fallback.//// Returns `{ stop }`. `stop()` cancels the loop — call it on stop/unmount so no-// rAF or timer dangles (the deferred-work teardown rule in CLAUDE.md). The loop+// rAF or timer dangles (the deferred-work teardown rule in AGENTS.md). The loop// body is wrapped so a throw inside an animation-frame callback (which has no// Express `next(err)` to bubble to) can't crash the tab.export const createPitchTracker = (analyser, opts = {}) => {diff --git a/client/src/lib/scorePlayback.js b/client/src/lib/scorePlayback.jsindex 744d985313..cd2f32e74c 100644--- a/client/src/lib/scorePlayback.js+++ b/client/src/lib/scorePlayback.js@@ -88,7 +88,7 @@ export const buildSchedule = (score, bpmOverride) => {// Guard a UI callback that fires from a setInterval tick — an uncaught throw// there has no request boundary to bubble to and would leave the scheduler-// interval orphaned. (CLAUDE.md: wrap non-request-lifecycle callbacks.)+// interval orphaned. (AGENTS.md: wrap non-request-lifecycle callbacks.)// Exported as a factory so midiPlayback.js shares the guard with its own// log prefix instead of duplicating the body.export const makeSafeCall = (label) => (cb, ...args) => {diff --git a/client/src/lib/syncCounts.js b/client/src/lib/syncCounts.jsindex c5643671a3..366590825a 100644--- a/client/src/lib/syncCounts.js+++ b/client/src/lib/syncCounts.js@@ -10,7 +10,7 @@// Sequences arrive as numbers (brain) or numeric strings (memory BIGSERIAL),// so compare as BigInt to stay exact past Number.MAX_SAFE_INTEGER.//-// Sentinel discipline (see CLAUDE.md): a MISSING input must NOT collapse to 0.+// Sentinel discipline (see AGENTS.md): a MISSING input must NOT collapse to 0.// - For pull, an absent `ourCursor` legitimately means "pulled nothing" → treat// as 0 (the caller passes `ourCursor ?? 0`). An absent `peerMax` means the// peer hasn't been probed yet → unknown (null).diff --git a/client/src/pages/Apps.jsx b/client/src/pages/Apps.jsxindex 6b6583a502..1daae398cb 100644--- a/client/src/pages/Apps.jsx+++ b/client/src/pages/Apps.jsx@@ -135,7 +135,7 @@ export default function Apps() {// Retry and a re-expand re-issue the request; a genuine `[]` is still cached.// Per-app request generation, so a slow earlier fetch can't land after a newer// one and overwrite a good board with its stale error (the pending-request- // convention in client/src/CLAUDE.md).+ // convention in client/src/AGENTS.md).const loadSprintTickets = useCallback(async (app) => {const key = sprintKey(app);const generation = (ticketRequestsRef.current[key]?.generation || 0) + 1;diff --git a/client/src/pages/Catalog.jsx b/client/src/pages/Catalog.jsxindex 42ddd69da9..571ada031e 100644--- a/client/src/pages/Catalog.jsx+++ b/client/src/pages/Catalog.jsx@@ -62,7 +62,7 @@ export default function Catalog() {// chips + the New-form dropdown; `getType` resolves badge/primary-content.const { types: TYPES, getType } = useCatalogTypes();- // ── URL-synced filter state (linkable routes per CLAUDE.md) ────────────────+ // ── URL-synced filter state (linkable routes per AGENTS.md) ────────────────// `updateParams` merges a patch and drops keys set to '' so a cleared filter// leaves the URL clean; `replace` avoids history spam while typing.const [searchParams, updateParams] = useUrlParams();diff --git a/client/src/pages/CreativeCommissionDetail.jsx b/client/src/pages/CreativeCommissionDetail.jsxindex 8d5a2dd876..de8457816b 100644--- a/client/src/pages/CreativeCommissionDetail.jsx+++ b/client/src/pages/CreativeCommissionDetail.jsx@@ -105,7 +105,7 @@ export default function CreativeCommissionDetail() {if (cancelled) return;// Only a real 404 means the commission is gone. A transient failure// (network, 5xx, auth) must NOT be misreported as "deleted" — surface it- // as a retryable error instead (absent-vs-unreachable, per CLAUDE.md).+ // as a retryable error instead (absent-vs-unreachable, per AGENTS.md).if (err?.status === 404) { setNotFound(true); setLoadError(null); }else setLoadError(err?.message || 'Failed to load commission');})diff --git a/client/src/pages/CreativeDirector.jsx b/client/src/pages/CreativeDirector.jsxindex 2f9cc56adc..b627f9ebee 100644--- a/client/src/pages/CreativeDirector.jsx+++ b/client/src/pages/CreativeDirector.jsx@@ -208,7 +208,7 @@ export default function CreativeDirector() {};// Optimistic-update the row in place rather than refetching the whole list- // (per CLAUDE.md "Reactive UI updates"). The detail page's poll picks up the+ // (per AGENTS.md "Reactive UI updates"). The detail page's poll picks up the// server's authoritative status within 5s if anything diverges.const handleStart = async (id) => {try {diff --git a/client/src/pages/Models.jsx b/client/src/pages/Models.jsxindex 063100f157..2b5db9ab14 100644--- a/client/src/pages/Models.jsx+++ b/client/src/pages/Models.jsx@@ -42,7 +42,7 @@ const MediaModels = lazyWithReload(() => import('./MediaModels'));* `docs/plans/2026-08-21-models-navigation.md`.** `?tab` is a route param, not local state, so every one is deep-linkable and- * reachable from ⌘K and voice (`client/src/CLAUDE.md`).+ * reachable from ⌘K and voice (`client/src/AGENTS.md`).*/const TAB_CONTENT = {'3d': Image3dRuntimes,diff --git a/client/src/pages/Pipeline.jsx b/client/src/pages/Pipeline.jsxindex b660d16fc9..c87ca965e1 100644--- a/client/src/pages/Pipeline.jsx+++ b/client/src/pages/Pipeline.jsx@@ -240,7 +240,7 @@ export default function Pipeline() {});setCreating(false);if (!created) return;- // Reactive insert — no full refetch (CLAUDE.md convention).+ // Reactive insert — no full refetch (AGENTS.md convention).setSeries((prev) => [created, ...prev]);setForm(emptyForm());clearCandidates();@@ -269,7 +269,7 @@ export default function Pipeline() {// Inline delete confirm: the trash button arms the row (one at a time) and an// explicit Delete?/Cancel row fires it. Avoids window.confirm (banned per- // CLAUDE.md) and the non-discoverable two-click-arm pattern.+ // AGENTS.md) and the non-discoverable two-click-arm pattern.const { isConfirming, requestDelete, cancelDelete, confirmDelete } = useConfirmDelete();const handleDelete = (s) => confirmDelete(() => {const prior = series;diff --git a/client/src/pages/PromptManager.jsx b/client/src/pages/PromptManager.jsxindex 1f88fd3411..f9b31c2650 100644--- a/client/src/pages/PromptManager.jsx+++ b/client/src/pages/PromptManager.jsx@@ -340,7 +340,7 @@ export default function PromptManager() {// A failed save must say so: the button re-enabling on its own reads as// "saved" and the edit is silently lost. `silent: true` + an explicit toast- // keeps the notification to one layer (see client/src/CLAUDE.md).+ // keeps the notification to one layer (see client/src/AGENTS.md).const saveJobSkill = async () => {setSaving(true);// Snapshot what we actually sent — the textarea may change while the PATCHdiff --git a/client/src/pages/QuotaBurn.jsx b/client/src/pages/QuotaBurn.jsxindex 4c977cec16..3cfcbb6d2f 100644--- a/client/src/pages/QuotaBurn.jsx+++ b/client/src/pages/QuotaBurn.jsx@@ -8,7 +8,7 @@* programmatic PortOS job like rendering the universe bible entries that have* no image yet.*- * The master switch is the consent gate for the whole feature (CLAUDE.md's AI+ * The master switch is the consent gate for the whole feature (AGENTS.md's AI* provider policy): with it off nothing here contacts a provider, and the page* names the family, provider, model, and work before it can be turned on.*/@@ -147,7 +147,7 @@ export default function QuotaBurn() {const seq = editSeqRef.current;const requestSeq = ++loadSeqRef.current;// `silent: true` because the failure is rendered by this page's own banner- // rather than the request helper's toast — see client/src/CLAUDE.md's+ // rather than the request helper's toast — see client/src/AGENTS.md's// silent-vs-toasting rule.const data = await api.getQuotaBurn(refresh, { silent: true }).catch((err) => {diff --git a/client/src/pages/SongBook.jsx b/client/src/pages/SongBook.jsxindex 90db6540a9..98a62929b1 100644--- a/client/src/pages/SongBook.jsx+++ b/client/src/pages/SongBook.jsx@@ -66,7 +66,7 @@ export default function SongBook() {setLoading(true);setLoadError(null);// The banner below owns the error UI, so the request stays silent — one- // error layer only (client/src/CLAUDE.md "custom catch ⇒ silent: true").+ // error layer only (client/src/AGENTS.md "custom catch ⇒ silent: true").listSongs({ silent: true }).then((data) => {if (cancelled) return;diff --git a/client/src/pages/StackerNews.jsx b/client/src/pages/StackerNews.jsxindex 64f9e8f739..fefbcbd2ab 100644--- a/client/src/pages/StackerNews.jsx+++ b/client/src/pages/StackerNews.jsx@@ -25,7 +25,7 @@ const TABS = [{ id: 'accounts', label: 'Automation & accounts', icon: ShieldAlert },];// The account form is a broad config surface, so it lives in the shared-// tabbed Drawer rather than a page-length flat scroll (client/src/CLAUDE.md).+// tabbed Drawer rather than a page-length flat scroll (client/src/AGENTS.md).const ACCOUNT_TABS = [{ id: 'identity', label: 'Identity' },{ id: 'monitoring', label: 'Monitoring & models' },diff --git a/client/src/pages/StartStory.jsx b/client/src/pages/StartStory.jsxindex e992f52655..26b0162de6 100644--- a/client/src/pages/StartStory.jsx+++ b/client/src/pages/StartStory.jsx@@ -52,7 +52,7 @@ export default function StartStory() {useEffect(() => {let cancelled = false;- // silent: the custom catch below owns the toast (CLAUDE.md). A failed load+ // silent: the custom catch below owns the toast (AGENTS.md). A failed load// just leaves the "use an existing universe" option empty — the onramp// still works in "start fresh" mode.listUniverses({ silent: true })diff --git a/client/src/pages/Universes.jsx b/client/src/pages/Universes.jsxindex 261735fd6f..e68584f7fd 100644--- a/client/src/pages/Universes.jsx+++ b/client/src/pages/Universes.jsx@@ -132,7 +132,7 @@ export default function Universes() {let cancelled = false;// Universes drive the page; resolve `loading` as soon as they land so a// slow/hung series fetch can't keep the list stuck on "Loading…".- // silent: the custom catch below owns the error toast (CLAUDE.md).+ // silent: the custom catch below owns the error toast (AGENTS.md).listUniverses({ silent: true }).catch((err) => {toast.error(err.message || 'Failed to load universes');@@ -204,11 +204,11 @@ export default function Universes() {// Inline delete confirm: the trash button arms the row (one at a time) and an// explicit Delete?/Cancel row fires it. Avoids window.confirm (banned per- // CLAUDE.md) and the non-discoverable two-click-arm pattern.+ // AGENTS.md) and the non-discoverable two-click-arm pattern.const { isConfirming, requestDelete, cancelDelete, confirmDelete } = useConfirmDelete();const handleDelete = (u) => confirmDelete(async () => {setUniverses((prev) => prev.filter((x) => x.id !== u.id));- // silent: the custom catch below owns the error toast (CLAUDE.md).+ // silent: the custom catch below owns the error toast (AGENTS.md).await deleteUniverse(u.id, { silent: true }).catch((err) => {toast.error(err.message || 'Delete failed');// Roll back only this row (re-insert if still missing) so a concurrentdiff --git a/client/src/services/apiCreativeCommission.js b/client/src/services/apiCreativeCommission.jsindex 90908ef6c8..aae47a56dc 100644--- a/client/src/services/apiCreativeCommission.js+++ b/client/src/services/apiCreativeCommission.js@@ -5,7 +5,7 @@ import { request } from './apiCore.js';// directive pipeline.//// `options` lets a caller that owns its own error toast pass `{ silent: true }`-// so request() doesn't also toast — see CLAUDE.md "Custom catch ⇒ silent: true".+// so request() doesn't also toast — see AGENTS.md "Custom catch ⇒ silent: true".export const listCommissions = (options = {}) => request('/creative-commission', options);diff --git a/client/src/services/apiLocalLlm.js b/client/src/services/apiLocalLlm.jsindex 3c4326c271..fea81ceb62 100644--- a/client/src/services/apiLocalLlm.js+++ b/client/src/services/apiLocalLlm.js@@ -228,7 +228,7 @@ export async function streamLocalLlmTest(payload, { signal, onToken } = {}) {// The catalog fit badge is a size estimate; these run the model and record what// it actually did. GET is disk-only and safe to call on mount; the run endpoint// calls a provider and must only fire from a deliberate user action (root-// CLAUDE.md, "AI Provider Usage Policy").+// AGENTS.md, "AI Provider Usage Policy").// Persisted assessments + the intent-ranked recommendation + which installed// models have no evidence yet. Zero LLM calls, so it's safe to load with the tab.diff --git a/client/src/services/apiMeatspace.js b/client/src/services/apiMeatspace.jsindex 2d4666dae9..6c29d954e3 100644--- a/client/src/services/apiMeatspace.js+++ b/client/src/services/apiMeatspace.js@@ -176,7 +176,7 @@ export const removeEyeExam = (index) => request(`/meatspace/eyes/${index}`, {export const getPostConfig = () => request('/meatspace/post/config');export const getPostBenchmarkProtocol = (options = {}) => request('/meatspace/post/benchmark/protocol', options);// `options` lets a caller that owns its own error UI pass `{ silent: true }` so-// the failure only toasts once (see CLAUDE.md's silent-vs-toasting convention).+// the failure only toasts once (see AGENTS.md's silent-vs-toasting convention).export const updatePostConfig = (data, options = {}) => request('/meatspace/post/config', {method: 'PUT',body: JSON.stringify(data),diff --git a/client/src/services/apiPipeline.js b/client/src/services/apiPipeline.jsindex cb49fb331c..aa9235f227 100644--- a/client/src/services/apiPipeline.js+++ b/client/src/services/apiPipeline.js@@ -72,7 +72,7 @@ export const getPipelineConfig = (options = {}) => request('/pipeline/config', o// ---- Series ----// `options` lets a caller suppress request()'s auto-toast with `{ silent: true }`-// (e.g. an optional join that should fail quietly) — see CLAUDE.md.+// (e.g. an optional join that should fail quietly) — see AGENTS.md.export const listPipelineSeries = (options = {}) => request('/pipeline/series', options);export const getPipelineSeries = (id, options = {}) => request(`/pipeline/series/${encodeURIComponent(id)}`, options);export const createPipelineSeries = (data, options = {}) => request('/pipeline/series', {diff --git a/client/src/services/apiUniverseBuilder.js b/client/src/services/apiUniverseBuilder.jsindex 68eb21da1c..54daa3b3a1 100644--- a/client/src/services/apiUniverseBuilder.js+++ b/client/src/services/apiUniverseBuilder.js@@ -16,7 +16,7 @@ export const WORLD_INFLUENCES_PER_LIST_MAX = 30;export const WORLD_STYLE_REFERENCES_MAX = 20;// `options` lets a caller that owns its own error toast pass `{ silent: true }`-// so request() doesn't also toast — see CLAUDE.md "Custom catch ⇒ silent: true".+// so request() doesn't also toast — see AGENTS.md "Custom catch ⇒ silent: true".export const listUniverses = (options = {}) => request('/universe-builder', options);export const getUniverse = (id, options = {}) => request(`/universe-builder/${encodeURIComponent(id)}`, options);@@ -40,7 +40,7 @@ export const updateUniverse = (id, patch, options = {}) => request(`/universe-bu// `options` lets callers that own their own error toast (a custom `.catch`)// pass `{ silent: true }` so the request() helper doesn't also toast — see-// CLAUDE.md "Custom catch ⇒ silent: true". Mirrors updateUniverse's signature.+// AGENTS.md "Custom catch ⇒ silent: true". Mirrors updateUniverse's signature.export const deleteUniverse = (id, options = {}) => request(`/universe-builder/${encodeURIComponent(id)}`, {method: 'DELETE',...options,@@ -396,7 +396,7 @@ export const setUniverseVariationsLockAll = (universeId, { locked, category = nu// Promote a category variation into a full canon entry. `targetKind` is// required only when the source bucket's `kind` is 'other' (otherwise the// server derives it from the bucket). Pass `{ silent: true }` in `options`-// when the caller owns its own error toast (per CLAUDE.md).+// when the caller owns its own error toast (per AGENTS.md).export const promoteVariationToCanon = (universeId, {category, label, targetKind, providerId, model,} = {}, options = {}) =>diff --git a/client/src/utils/formatters.js b/client/src/utils/formatters.jsindex cb5bfd4334..7d2f621662 100644--- a/client/src/utils/formatters.js+++ b/client/src/utils/formatters.js@@ -531,7 +531,7 @@ export function formatDateShort(value) {// Per-call LLM timeout bounds. Client-side mirror of the canonical// MIN_TIMEOUT / MAX_TIMEOUT in server/lib/aiToolkit/constants.js — the// client can't import across the server boundary (Vite vs Node, plus the-// aiToolkit directory is kept self-contained per CLAUDE.md). The server+// aiToolkit directory is kept self-contained per AGENTS.md). The server// validators (validation.js, stageRunner.js) and aiToolkit's own// provider/run schemas all import from constants.js; this file is the// only known mirror. Bumping these here without the server constants —diff --git a/client/src/utils/index.js b/client/src/utils/index.jsindex 06a893cc0c..77296e59f2 100644--- a/client/src/utils/index.js+++ b/client/src/utils/index.js@@ -1,6 +1,6 @@// Barrel for client/src/utils/ — discovery surface, not a forced import path.// See client/src/utils/README.md for the human-readable catalog and-// CLAUDE.md "Module organization" for the maintenance convention.+// AGENTS.md "Module organization" for the maintenance convention.//// Every module here exports named (no defaults), so a flat `export * from`// surfaces each helper under its own name. The barrel exists so helpers arediff --git a/client/src/utils/index.test.js b/client/src/utils/index.test.jsindex cf9c8a4647..f52d925cc8 100644--- a/client/src/utils/index.test.js+++ b/client/src/utils/index.test.js@@ -14,7 +14,7 @@ const sourceFiles = readdirSync(HERE).filter(// Collect every top-level named export per module so we can prove no two flat// `export * from` modules collide (a collision would silently shadow under the-// barrel — see CLAUDE.md "Name collisions").+// barrel — see AGENTS.md "Name collisions").const EXPORT_RE = /^export\s+(?:const|let|function|async function|class)\s+([A-Za-z0-9_$]+)/gm;const exportsByName = new Map();for (const f of sourceFiles) {diff --git a/docs/COMPANION_APP_API.md b/docs/COMPANION_APP_API.mdindex 9e82b30a99..0c90f20335 100644--- a/docs/COMPANION_APP_API.md+++ b/docs/COMPANION_APP_API.md@@ -6,7 +6,7 @@ or more PortOS instances across a Tailscale tailnet.> **Scope.** This documents the **PortOS-side** contract only. The iOS app itself> (Swift/SwiftUI, Keychain, iCloud store, UI) lives in its own repository per the-> Scope Boundary rule in `CLAUDE.md` — its code, plan, and docs never land in this+> Scope Boundary rule in `AGENTS.md` — its code, plan, and docs never land in this> repo. Everything below already exists in PortOS today unless explicitly marked.## Deployment shape the app targetsdiff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex 99856fecf5..e76323fb35 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -155,7 +155,7 @@ The escape hatch is **guarded from bitrot by the test suite** (tests boot with `3. **`PGMODE=native`:** runs `scripts/db.sh setup-native` (idempotent: brew install, role, db, extensions, schema) and verifies at the domain level (role can auth + schema present) before reporting ready on `:5432`.4. **Failure is non-zero exit.** A started-but-unresponsive container, a failed native bootstrap, or a non-interactive context with no usable DB exits non-zero with an actionable message — so the `&&`-chained `npm start` halts here instead of crash-looping under PM2 against an unready database.-`PGPASSWORD`/`PGUSER`/`PGDATABASE`/`PGPORT` are resolved from `process.env` first, then `.env`, then the backward-compatible defaults (`portos`/`portos`/`portos`/`5432`). The default `portos` password is an **intentional** local-development fallback (see the Distribution model note in [`CLAUDE.md`](../CLAUDE.md)); production deployments override it via `PGPASSWORD`.+`PGPASSWORD`/`PGUSER`/`PGDATABASE`/`PGPORT` are resolved from `process.env` first, then `.env`, then the backward-compatible defaults (`portos`/`portos`/`portos`/`5432`). The default `portos` password is an **intentional** local-development fallback (see the Distribution model note in [`AGENTS.md`](../AGENTS.md)); production deployments override it via `PGPASSWORD`.### Boot schema upgrades & the CREATE INDEX lock window@@ -178,7 +178,7 @@ Apply this checklist to **every new feature that persists data**, and require it- [ ] **Does it need search?** Full-text or vector search → PostgreSQL (`search_tsv` / pgvector), not an app-level scan over JSON files.- [ ] **If you chose a new `data/*.json`, why not the DB?** Acceptable reasons: large binary bytes (`asset-file-db-indexed` — index the metadata, keep bytes on disk), long externally-editable prose, an iCloud/file-sync workflow PortOS does not own, or genuinely transient runtime state (`ephemeral-file`). "It was faster to write a JSON file" is **not** acceptable for app-native relational records.- [ ] **Bytes vs. pointer.** If binary assets are involved, confirm bytes stay on disk and the DB holds only an `asset_key` / `media_key` row + integrity metadata. Never store bytes in a column.-- [ ] **Federation.** If the record syncs to peers, does it have a per-table/per-record sequence cursor and tombstone strategy? (See `server/lib/schemaVersions.js`, `server/lib/syncWire.js`.) Cross-machine sync is first-class — see the Distribution model in [`CLAUDE.md`](../CLAUDE.md).+- [ ] **Federation.** If the record syncs to peers, does it have a per-table/per-record sequence cursor and tombstone strategy? (See `server/lib/schemaVersions.js`, `server/lib/syncWire.js`.) Cross-machine sync is first-class — see the Distribution model in [`AGENTS.md`](../AGENTS.md).- [ ] **Migration.** On-disk/DB format changes need a migration in `scripts/migrations/` (applied-list tracked per install in `data/migrations.applied.json`) and seed files in `data.reference/`. Other installs and other federated machines upgrade independently.- [ ] **Backup coverage.** Will the new store be captured by backup? `db-primary` is covered by the Postgres dump; `file-primary` / `asset-file-db-indexed` by the rsync snapshot; `ephemeral-file` is correctly excluded (`DEFAULT_EXCLUDES`). Confirm the store lands in the right bucket. See [Backup & Restore](./BACKUP.md).diff --git a/docs/decisions/2026-08-08-privacy-records-machine-local.md b/docs/decisions/2026-08-08-privacy-records-machine-local.mdindex a0f251bd73..8e370aa2f0 100644--- a/docs/decisions/2026-08-08-privacy-records-machine-local.md+++ b/docs/decisions/2026-08-08-privacy-records-machine-local.md@@ -84,7 +84,7 @@ the first two so the boundary fails loudly rather than eroding.### Scope of the rule this ADR states-`CLAUDE.md` summarizes this decision as the flat rule that **PII must not ride+`AGENTS.md` summarizes this decision as the flat rule that **PII must not ridethe federation layer at all**, and for Privacy Center records that is exact andunconditional. The rule governs *records* — what one instance replicates toanother, and what a status or capability payload may disclose. It is not a rule@@ -146,7 +146,7 @@ fix for the creative-data federation that already exists.**#3659** — a general federation fix benefiting every federated kind, not aprivacy prerequisite. It is version-gated so an older peer that does notpresent identity degrades gracefully rather than losing sync.-- `CLAUDE.md`'s Security Model previously stated that PortOS "intentionally+- `AGENTS.md`'s Security Model previously stated that PortOS "intentionallyomits authentication … HTTPS." Both exist as opt-in, off-by-default features,and the stale wording actively misleads anyone reasoning about what a peerchannel can guarantee. Corrected as part of this change.diff --git a/docs/decisions/2026-08-14-strict-json-reads-for-counted-values.md b/docs/decisions/2026-08-14-strict-json-reads-for-counted-values.mdindex b3305ee6ff..bbfc79a912 100644--- a/docs/decisions/2026-08-14-strict-json-reads-for-counted-values.md+++ b/docs/decisions/2026-08-14-strict-json-reads-for-counted-values.md@@ -5,7 +5,7 @@- **Related:** issue #4115 (this audit), issue #2726 (introduced`readJSONFileStrict`, scoped to the Character sheet's file-backed signals),[`server/lib/fileUtils.js`](../../server/lib/fileUtils.js),- [`server/lib/README.md`](../../server/lib/README.md), root `CLAUDE.md`+ [`server/lib/README.md`](../../server/lib/README.md), root `AGENTS.md`("Sentinel + validate to distinguish 'not set / failed' from'present-but-empty / valid'").diff --git a/docs/decisions/2026-08-20-federated-visual-prompts.md b/docs/decisions/2026-08-20-federated-visual-prompts.mdindex b96ddb2414..4391bdaeb1 100644--- a/docs/decisions/2026-08-20-federated-visual-prompts.md+++ b/docs/decisions/2026-08-20-federated-visual-prompts.md@@ -11,7 +11,7 @@## Context-`CLAUDE.md` states flatly that **PII must not ride the federation layer at all**,+`AGENTS.md` states flatly that **PII must not ride the federation layer at all**,pointing at the privacy-records ADR. Read literally against the federated mediawire, that rule looks violated: a federated image or video job carries its`prompt` to the peer as submitted, and a Creative Director / Creative Commission@@ -59,7 +59,7 @@ Concretely:readiness signals, queue depth and staleness — never a prompt, a job body, arecord excerpt, or a filename derived from one. The owner-scoped jobprojection is likewise a sanitized status view. This is the line that must not- move, and it is the line `CLAUDE.md`'s rule is protecting.+ move, and it is the line `AGENTS.md`'s rule is protecting.4. **The counterparty is not an anonymous third party.** Sending is gated on*local* configuration, not on the peer asking nicely: the peer record must be@@ -100,7 +100,7 @@ Concretely:counterparty is a permanent leak where an interactive mistake is a one-timeone — and `peerFetch`'s `rejectUnauthorized: false` posture leaves a plain-LANor non-`.ts.net` peer with no server authentication at all (see the HTTPS- bullet in `CLAUDE.md`). Authentication does not save this: the prompt rides+ bullet in `AGENTS.md`). Authentication does not save this: the prompt ridesthe request body, so an impostor holding the connection reads it before itfails to answer. When unattended routing ships, a route whose peer is notrecognized as a tailnet host must be refused, naming the reason (see@@ -148,7 +148,7 @@ later slice of #4348 and must revisit this ADR before shipping.## Consequences- Privacy Center records are unaffected: nothing here adds a federated kind, a- sync category, or a wire version. `CLAUDE.md` and the privacy-records ADR link+ sync category, or a wire version. `AGENTS.md` and the privacy-records ADR linkhere rather than re-arguing the carve-out, and the schemas and route fieldsstop restating the rationale inline, so a reviewer's objection has one citableanswer instead of four paraphrases.diff --git a/docs/features/brain-system.md b/docs/features/brain-system.mdindex a003cc8707..060e7036b5 100644--- a/docs/features/brain-system.md+++ b/docs/features/brain-system.md@@ -141,7 +141,7 @@ capture, a free-text prompt for a follow-up agent, and tags.**The agent prompt.** Supplying `agentPrompt` queues a CoS task pointed at thestored transcript with that prompt as its brief — "here is what I want done withthis content." Leaving it blank queues nothing: PortOS never starts AI work the-user did not ask for (see the AI Provider Usage Policy in the root `CLAUDE.md`).+user did not ask for (see the AI Provider Usage Policy in the root `AGENTS.md`).**Transcripts.** yt-dlp is asked for English captions; the metadata dump's`subtitles` key (not the produced filename, which is identical for both kinds)diff --git a/docs/features/identity-system.md b/docs/features/identity-system.mdindex 41e8b50155..2bda325652 100644--- a/docs/features/identity-system.md+++ b/docs/features/identity-system.md@@ -608,7 +608,7 @@ CoS injects identity context into agent briefings when relevant1. **Separate data files per section** (not one giant file) -- each section has independent update cadence and the genome file (82KB) is already large2. **Derivation over duplication** -- chronotype reads from genome.json at query time rather than copying marker data. Identity service is the join layer-3. **Progressive disclosure** -- Identity tab shows summary cards; deep dives are sub-routes, not modals (per CLAUDE.md: all views must be deep-linkable)+3. **Progressive disclosure** -- Identity tab shows summary cards; deep dives are sub-routes, not modals (per AGENTS.md: all views must be deep-linkable)4. **LLM-assisted but user-confirmed** -- aesthetic themes extracted by LLM from media lists are suggestions, not gospel. User confirms/edits5. **No new dependencies** -- uses existing Zod, Express, React, Lucide stack6. **Genome data stays read-only** -- identity service reads genome markers but never writes to genome.jsondiff --git a/docs/features/openworld.md b/docs/features/openworld.mdindex ae572fe595..042db8e56c 100644--- a/docs/features/openworld.md+++ b/docs/features/openworld.md@@ -139,7 +139,7 @@ what's healthy, what's not, find a specific app, and take action.| **1.11** | **Clickable HUD stats** — every count routes somewhere: PENDING REVIEWS → `/review`, AGENTS → `/cos`, NODES → `/instances`, etc. | XS || **1.12** | **Richer billboards** — rotate today's briefing headline, productivity streak, top actionable insight, recent agent completion summary, goal progress. | S || **1.13** | **Agent → building tether** — visible light from `AgentEntity` to its assigned building; color = agent state. Plus window-pulse animation on the building. | M |-| **1.14** | **Mobile / touch support** — `pointer: coarse` detection, single-finger orbit, two-finger pinch zoom, tap-to-select. Below 640px collapse HUD into a bottom sheet with search + filters + needs-attention. WASD exploration disables. CLAUDE.md mandate. | M |+| **1.14** | **Mobile / touch support** — `pointer: coarse` detection, single-finger orbit, two-finger pinch zoom, tap-to-select. Below 640px collapse HUD into a bottom sheet with search + filters + needs-attention. WASD exploration disables. AGENTS.md mandate. | M || **1.15** | **Adaptive render budget** — the scene selects an internal detail tier from sustained frame time; player settings do not expose renderer knobs. | XS |### Phase 2 — Holistic Coveragediff --git a/docs/features/sglang-qwen38.md b/docs/features/sglang-qwen38.mdindex d577c86a6c..5e3dca8ffc 100644--- a/docs/features/sglang-qwen38.md+++ b/docs/features/sglang-qwen38.md@@ -252,7 +252,7 @@ buys you the thinking switch.Claude Ollama runs in **lean mode** (`--bare --strict-mcp-config`) because a 7Blocal model drowns in Claude Code's full personal environment — hooks, plugins,-MCP servers, global `CLAUDE.md`. The SGLang pair does not, and that is a choice+MCP servers, the global `~/.claude/CLAUDE.md`. The SGLang pair does not, and that is a choicerather than an oversight: Qwen3.8-27B has a 262,144-token native window, thesame environment is what lets a CoS agent type `/do:pr` and drive a changethrough to merge, and a large prompt prefix costs nothing per turn oncediff --git a/docs/features/soul-system.md b/docs/features/soul-system.mdindex cb9396404b..9d28161648 100644--- a/docs/features/soul-system.md+++ b/docs/features/soul-system.md@@ -22,7 +22,7 @@ LLMs can embody specific personas, but creating comprehensive identity documents2. **Documents Tab**: Sidebar-based document editor for managing soul markdown files by category (core, audio, behavioral, enrichment)3. **Test Tab**: Multi-model behavioral testing against 14 predefined tests, with side-by-side result comparison4. **Enrich Tab**: Guided questionnaire across 10 categories that generates soul document content from answers-5. **Export Tab**: Export soul for use in external LLMs (System Prompt, CLAUDE.md, JSON, individual files)+5. **Export Tab**: Export soul for use in external LLMs (System Prompt, AGENTS.md, JSON, individual files)### CoS Integrationdiff --git a/docs/research/2026-08-09-krea-realtime-apple-silicon.md b/docs/research/2026-08-09-krea-realtime-apple-silicon.mdindex c7361cc60f..513f423c13 100644--- a/docs/research/2026-08-09-krea-realtime-apple-silicon.md+++ b/docs/research/2026-08-09-krea-realtime-apple-silicon.md@@ -5,7 +5,7 @@ let alone executed, on Apple Silicon; the only native-MLX path is a third party'unpublished in-tree crate.**Date:** 2026-08-09**Host:** Apple M5 Max, 128 GB unified-memory tier, macOS 26.5 (host identity-deliberately omitted per `CLAUDE.md`)+deliberately omitted per `AGENTS.md`)**Closes:** #3673**Related:** #3674 (shipped the per-model `disclosure` block this report's licensefindings would have to populate)diff --git a/scripts/agent-instructions-files.test.js b/scripts/agent-instructions-files.test.jsnew file mode 100644index 0000000000..e81df91071--- /dev/null+++ b/scripts/agent-instructions-files.test.js@@ -0,0 +1,122 @@+import { describe, it, expect } from 'vitest';+import { execFileSync } from 'child_process';+import { readFileSync, lstatSync } from 'fs';+import { dirname, join } from 'path';+import { fileURLToPath } from 'url';++// Regression guard for #4852. `AGENTS.md` is the cross-vendor agent-instructions+// standard every CLI PortOS drives reads — except Claude Code, whose memory+// discovery hardcodes `CLAUDE.md` with no configurable filename. So each+// location carries both, and the second is a one-line `@AGENTS.md` import.+//+// Two ways that arrangement silently breaks, both guarded here:+// 1. Someone "tidies" the bridge into a symlink. A git symlink checked out on+// a Windows runner without symlink support materializes as a 9-byte text+// file containing the literal string `AGENTS.md` — a CLAUDE.md from which+// Claude Code loads nothing, and the repo's whole memory disappears for+// that agent with no error anywhere.+// 2. New prose reintroduces `CLAUDE.md` as THE instructions filename, so an+// agent (or a scaffolded repo) is pointed at a file that may not exist.+//+// Enumeration is via `git grep`, so the scan covers exactly *tracked* files —+// gitignored runtime state (`data/`) and the `lib/slashdo` submodule (a separate+// upstream repo, not ours to police) drop out for free.++const REPO_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');++/** Every directory that carries the pair. Adding a nested one? Add it here. */+const INSTRUCTION_DIRS = [+ '.',+ 'client/src',+ 'client/src/components/dashboard',+ 'server',+ 'server/lib/aiToolkit',+];++/** Entire body of a bridge file. */+const IMPORT_BODY = '@AGENTS.md\n';++// Historical records and frozen data. Rewriting these would falsify history or,+// for the migrations and prior prompt defaults, break the exact-string matching+// they perform against what an older version actually wrote.+const EXCLUDED_PREFIXES = [+ '.changelog/',+ 'docs/plans/',+ 'docs/superpowers/',+ 'data/',+ 'lib/slashdo/',+ 'scripts/migrations/',+ 'server/services/taskPromptDefaults/previousDefaults.js',+ 'server/services/taskPromptDefaults/integrity.snapshot.json',+];++// The modules whose JOB is to know both names — the discovery walker, its tests+// (whose fixtures are literal `CLAUDE.md` files), the shared filename constants,+// and this test. Everywhere else, a bare `CLAUDE.md` must be paired with+// `AGENTS.md` on the same line.+const DUAL_NAME_IMPLEMENTATION = [+ 'server/services/agentPromptBuilder.js',+ 'server/services/agentPromptBuilder.test.js',+ 'server/lib/agentInstructionsFile.js',+ 'scripts/agent-instructions-files.test.js',+];++const git = (...args) => execFileSync('git', args, { cwd: REPO_ROOT, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 });++describe('agent-instructions files (#4852)', () => {+ it('every location has a real AGENTS.md and a real CLAUDE.md holding only the import', () => {+ for (const dir of INSTRUCTION_DIRS) {+ const agentsPath = join(REPO_ROOT, dir, 'AGENTS.md');+ const bridgePath = join(REPO_ROOT, dir, 'CLAUDE.md');++ expect(lstatSync(agentsPath).isFile(), `${dir}/AGENTS.md must be a regular file`).toBe(true);+ expect(lstatSync(bridgePath).isFile(), `${dir}/CLAUDE.md must be a regular file`).toBe(true);+ expect(readFileSync(agentsPath, 'utf8').trim().length, `${dir}/AGENTS.md must carry content`).toBeGreaterThan(0);+ expect(readFileSync(bridgePath, 'utf8'), `${dir}/CLAUDE.md must be exactly the @AGENTS.md import`).toBe(IMPORT_BODY);+ }+ });++ it('no tracked AGENTS.md or CLAUDE.md is a symlink', () => {+ // Mode 120000 is git's symlink mode. It survives a Unix checkout and+ // silently degrades to junk text on a Windows runner, so the ban is on the+ // index entry rather than on what happens to be on this machine's disk.+ const symlinks = git('ls-files', '-s', '--', '*AGENTS.md', '*CLAUDE.md')+ .split('\n')+ .filter((line) => line.startsWith('120000'));++ expect(symlinks).toEqual([]);+ });++ it('no tracked file names CLAUDE.md as the canonical instructions file', () => {+ const hits = git('grep', '-n', '--fixed-strings', 'CLAUDE.md', '--', '.')+ .split('\n')+ .filter(Boolean)+ .map((line) => {+ const firstColon = line.indexOf(':');+ const secondColon = line.indexOf(':', firstColon + 1);+ return { file: line.slice(0, firstColon), line: line.slice(0, secondColon), text: line.slice(secondColon + 1) };+ })+ .filter(({ file }) => !EXCLUDED_PREFIXES.some((prefix) => file.startsWith(prefix)))+ .filter(({ file }) => !DUAL_NAME_IMPLEMENTATION.includes(file))+ // `~/.claude/CLAUDE.md` (and `.claude/CLAUDE.md`) is Claude Code's OWN+ // user-level memory location, not a repo convention — it keeps its name.+ .filter(({ text }) => !text.includes('.claude/CLAUDE.md'))+ // Dual naming is the accepted form: an agent told to read+ // "AGENTS.md (or CLAUDE.md)" still finds a managed app that has either.+ .filter(({ text }) => !text.includes('AGENTS.md'));++ expect(hits.map((h) => h.line)).toEqual([]);+ });++ it('the scan actually reads tracked files (detector self-check)', () => {+ // Non-vacuous guard: if the pathspec or the exclusions ever widened to+ // everything, the assertion above would pass by scanning nothing.+ const scanned = git('grep', '-l', '--fixed-strings', 'CLAUDE.md', '--', '.')+ .split('\n')+ .filter(Boolean)+ .filter((file) => !EXCLUDED_PREFIXES.some((prefix) => file.startsWith(prefix)));++ expect(scanned).toContain('AGENTS.md');+ expect(scanned).toContain('server/services/agentPromptBuilder.js');+ });+});diff --git a/scripts/ci-test-plan.js b/scripts/ci-test-plan.jsindex 55ab0e24b0..cfaff2fa25 100644--- a/scripts/ci-test-plan.js+++ b/scripts/ci-test-plan.js@@ -99,7 +99,7 @@ export const WINDOWS_CONTRACT_TESTS = [// Contract guards that run on EVERY plan, whatever the impact scope selects.// `taskPromptDefaults.test.js` pins the cross-install prompt-upgrade contract-// (CLAUDE.md "Distribution model"): edit a preserved historical default and+// (AGENTS.md "Distribution model"): edit a preserved historical default and// other installs stop recognizing their stored prompt, so they are treated as// having customized it and stay on it forever. Nothing else in the suite// notices, and neither can a scoped run that happens not to select this file —diff --git a/scripts/dev-proxy-drift.test.js b/scripts/dev-proxy-drift.test.jsindex 5ca2a163c6..980195660f 100644--- a/scripts/dev-proxy-drift.test.js+++ b/scripts/dev-proxy-drift.test.js@@ -65,7 +65,7 @@ const navPaths = NAV_COMMANDS.map((command) => command.path);/*** Every path the client router declares, with nesting resolved.*- * NOT just `NAV_COMMANDS`: `client/src/CLAUDE.md` requires a selectable view to+ * NOT just `NAV_COMMANDS`: `client/src/AGENTS.md` requires a selectable view to* register only its BASE path in the nav manifest while its `:id` detail route* lives in `App.jsx` alone. A convention-following `<Route path="data/:category">`* would therefore be invisible to a nav-manifest-only check — and the terminatordiff --git a/scripts/migrations/281-reconcile-missing-releases-prompt.test.js b/scripts/migrations/281-reconcile-missing-releases-prompt.test.jsindex 633f310c75..9c0751598a 100644--- a/scripts/migrations/281-reconcile-missing-releases-prompt.test.js+++ b/scripts/migrations/281-reconcile-missing-releases-prompt.test.js@@ -42,7 +42,8 @@ describe('migration 281 — upgrade release-check task prompt to v9', () => {const result = await migration.up({ rootDir });expect(result.updated).toBe(1);const updated = readJson(schedulePath);- expect(updated.tasks['release-check'].promptVersion).toBe(9);+ expect(updated.tasks['release-check'].promptVersion).toBe(PROMPT_VERSIONS['release-check']);+ expect(updated.tasks['release-check'].promptVersion).toBeGreaterThanOrEqual(9);expect(updated.tasks['release-check'].prompt).toBe(DEFAULT_TASK_PROMPTS['release-check']);});diff --git a/scripts/migrations/293-agents-md-prompt-rename.js b/scripts/migrations/293-agents-md-prompt-rename.jsnew file mode 100644index 0000000000..4ce9c3ec3d--- /dev/null+++ b/scripts/migrations/293-agents-md-prompt-rename.js@@ -0,0 +1,68 @@+/**+ * Upgrade the scheduled task prompts that name the agent-instructions file (#4852).+ *+ * AGENTS.md is now the canonical cross-vendor name, so seven shipped defaults+ * changed from "read CLAUDE.md" to "read AGENTS.md (or CLAUDE.md)". Existing+ * installs carry their own copy in data/cos/task-schedule.json, so this walks the+ * stored schedule and upgrades every affected task whose prompt is still an+ * unmodified default (promptCustomized !== true) — the same rule the auto-upgrade+ * on read applies. A user-edited prompt is left alone.+ */++import { readFile, writeFile } from 'fs/promises';+import { join } from 'path';+import { DEFAULT_TASK_PROMPTS, PROMPT_VERSIONS } from '../../server/services/taskPromptDefaults.js';++const SCHEDULE_PATHS = [+ join('data', 'cos', 'task-schedule.json'),+ join('data', 'task-schedule.json'),+];++const TASK_KEYS = [+ 'documentation',+ 'plan-task',+ 'claim-issue',+ 'claim-issue-gitlab',+ 'claim-issue-jira',+ 'release-check',+ 'stash-cleanup',+];++async function readJson(path) {+ const raw = await readFile(path, 'utf-8').catch((err) => {+ if (err.code === 'ENOENT') return null;+ throw err;+ });+ if (raw == null) return null;+ try {+ return JSON.parse(raw);+ } catch {+ return null;+ }+}++export default {+ async up({ rootDir }) {+ let updatedCount = 0;+ for (const relPath of SCHEDULE_PATHS) {+ const fullPath = join(rootDir, relPath);+ const schedule = await readJson(fullPath);+ if (!schedule?.tasks) continue;++ let dirty = false;+ for (const key of TASK_KEYS) {+ const task = schedule.tasks[key];+ if (!task) continue;+ const currentVersion = task.promptVersion || 1;+ if (task.promptCustomized || currentVersion >= PROMPT_VERSIONS[key]) continue;+ task.prompt = DEFAULT_TASK_PROMPTS[key];+ task.promptVersion = PROMPT_VERSIONS[key];+ dirty = true;+ updatedCount += 1;+ console.log(`📝 ${relPath}: upgraded ${key} prompt v${currentVersion} → v${PROMPT_VERSIONS[key]}`);+ }+ if (dirty) await writeFile(fullPath, `${JSON.stringify(schedule, null, 2)}\n`);+ }+ return { updated: updatedCount };+ },+};diff --git a/scripts/migrations/293-agents-md-prompt-rename.test.js b/scripts/migrations/293-agents-md-prompt-rename.test.jsnew file mode 100644index 0000000000..f158ce6a36--- /dev/null+++ b/scripts/migrations/293-agents-md-prompt-rename.test.js@@ -0,0 +1,80 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';++import migration from './293-agents-md-prompt-rename.js';+import { DEFAULT_TASK_PROMPTS, PROMPT_VERSIONS, PREVIOUS_DEFAULT_PROMPTS } from '../../server/services/taskPromptDefaults.js';++const writeJson = (path, value) => writeFileSync(path, `${JSON.stringify(value, null, 2)}\n`);+const readJson = (path) => JSON.parse(readFileSync(path, 'utf8'));++// The outgoing default is the last entry appended for each key — the body an+// install that never customized the prompt is holding right now.+const outgoing = (key) => PREVIOUS_DEFAULT_PROMPTS[key].at(-1);++describe('migration 293 — AGENTS.md prompt rename', () => {+ let rootDir;+ let schedulePath;++ beforeEach(() => {+ rootDir = mkdtempSync(join(tmpdir(), 'migration-293-'));+ mkdirSync(join(rootDir, 'data/cos'), { recursive: true });+ schedulePath = join(rootDir, 'data/cos/task-schedule.json');+ });++ afterEach(() => rmSync(rootDir, { recursive: true, force: true }));++ it('upgrades every uncustomized affected prompt to the AGENTS.md wording', async () => {+ writeJson(schedulePath, {+ tasks: {+ 'claim-issue': { prompt: outgoing('claim-issue'), promptVersion: PROMPT_VERSIONS['claim-issue'] - 1 },+ 'release-check': { prompt: outgoing('release-check'), promptVersion: PROMPT_VERSIONS['release-check'] - 1 },+ 'stash-cleanup': { prompt: outgoing('stash-cleanup'), promptVersion: 1 },+ },+ });++ const result = await migration.up({ rootDir });+ const tasks = readJson(schedulePath).tasks;++ expect(result.updated).toBe(3);+ for (const key of ['claim-issue', 'release-check', 'stash-cleanup']) {+ expect(tasks[key].prompt).toBe(DEFAULT_TASK_PROMPTS[key]);+ expect(tasks[key].promptVersion).toBe(PROMPT_VERSIONS[key]);+ expect(tasks[key].prompt).toContain('AGENTS.md');+ }+ });++ it('leaves a user-customized prompt untouched', async () => {+ writeJson(schedulePath, {+ tasks: {+ 'claim-issue': {+ prompt: 'MY OWN CLAIM PROMPT that mentions CLAUDE.md on purpose',+ promptVersion: 1,+ promptCustomized: true,+ },+ },+ });++ const result = await migration.up({ rootDir });+ const task = readJson(schedulePath).tasks['claim-issue'];++ expect(result.updated).toBe(0);+ expect(task.prompt).toBe('MY OWN CLAIM PROMPT that mentions CLAUDE.md on purpose');+ expect(task.promptVersion).toBe(1);+ });++ it('leaves a prompt already at the current version alone', async () => {+ writeJson(schedulePath, {+ tasks: {+ 'plan-task': { prompt: DEFAULT_TASK_PROMPTS['plan-task'], promptVersion: PROMPT_VERSIONS['plan-task'] },+ },+ });++ expect((await migration.up({ rootDir })).updated).toBe(0);+ });++ it('is a no-op when no schedule file exists', async () => {+ expect((await migration.up({ rootDir })).updated).toBe(0);+ });+});diff --git a/scripts/migrations/294-agents-md-quota-burn-presets.js b/scripts/migrations/294-agents-md-quota-burn-presets.jsnew file mode 100644index 0000000000..d41b8e4979--- /dev/null+++ b/scripts/migrations/294-agents-md-quota-burn-presets.js@@ -0,0 +1,87 @@+/**+ * Rewrite stored quota-burn audit prompts that still name CLAUDE.md (#4852).+ *+ * Picking a preset COPIES its text into the job's own `params.prompt`, and that+ * snapshot carries no version marker — so unlike the scheduled-task prompts+ * there is no auto-upgrade-on-read path to lean on. This migration supplies the+ * missing safe-upgrade step under the same rule PREVIOUS_DEFAULT_PROMPTS uses:+ * a stored prompt is rewritten ONLY when it is byte-for-byte the prior+ * unmodified render of a shipped preset. Anything the user edited — even by one+ * character — is left exactly as it is.+ *+ * The prior render is DERIVED from the current preset by reversing the one+ * wording change, rather than pasted in as ten frozen blobs: the derivation+ * cannot drift out of sync with the presets, and it keeps the migration short.+ */++import { readFile, writeFile } from 'fs/promises';+import { join } from 'path';+import { QUOTA_BURN_PROMPT_PRESETS } from '../../server/lib/quotaBurnPresets.js';++const QUOTA_BURN_PATH = join('data', 'cos', 'quota-burn.json');++// The exact before/after of the #4852 wording change in `auditContract`.+const CURRENT_FRAGMENT = `Read this repository's \`AGENTS.md\` (or \`CLAUDE.md\`, and any nested+per-directory ones covering the slice) before you start, and honor its+conventions and its explicitly declared non-issues — a finding that contradicts+a documented project decision is noise, not a bug.`;++const PRIOR_FRAGMENT = `Read this repository's \`CLAUDE.md\` (and any nested per-directory ones covering+the slice) before you start, and honor its conventions and its explicitly+declared non-issues — a finding that contradicts a documented project decision+is noise, not a bug.`;++/** prior unmodified render → current render, for every shipped audit preset. */+function buildUpgradeMap() {+ const map = new Map();+ for (const preset of QUOTA_BURN_PROMPT_PRESETS) {+ const current = preset.params?.prompt;+ if (typeof current !== 'string' || !current.includes(CURRENT_FRAGMENT)) continue;+ map.set(current.split(CURRENT_FRAGMENT).join(PRIOR_FRAGMENT), current);+ }+ return map;+}++async function readJson(path) {+ const raw = await readFile(path, 'utf-8').catch((err) => {+ if (err.code === 'ENOENT') return null;+ throw err;+ });+ if (raw == null) return null;+ try {+ return JSON.parse(raw);+ } catch {+ return null;+ }+}++export default {+ async up({ rootDir }) {+ const fullPath = join(rootDir, QUOTA_BURN_PATH);+ const config = await readJson(fullPath);+ if (!config?.families) return { updated: 0 };++ const upgrades = buildUpgradeMap();+ let updatedCount = 0;+ let skippedCustom = 0;++ for (const [familyId, family] of Object.entries(config.families)) {+ for (const job of family?.jobs || []) {+ const stored = job?.params?.prompt;+ if (typeof stored !== 'string' || !stored.includes('CLAUDE.md')) continue;+ const upgraded = upgrades.get(stored);+ if (!upgraded) {+ skippedCustom += 1;+ continue;+ }+ job.params.prompt = upgraded;+ updatedCount += 1;+ console.log(`📝 ${QUOTA_BURN_PATH}: upgraded ${familyId}/${job.id || 'job'} audit prompt to the AGENTS.md wording`);+ }+ }++ if (updatedCount) await writeFile(fullPath, `${JSON.stringify(config, null, 2)}\n`);+ if (skippedCustom) console.log(`✋ ${QUOTA_BURN_PATH}: left ${skippedCustom} user-edited prompt(s) untouched`);+ return { updated: updatedCount, skipped: skippedCustom };+ },+};diff --git a/scripts/migrations/294-agents-md-quota-burn-presets.test.js b/scripts/migrations/294-agents-md-quota-burn-presets.test.jsnew file mode 100644index 0000000000..5586a88618--- /dev/null+++ b/scripts/migrations/294-agents-md-quota-burn-presets.test.js@@ -0,0 +1,86 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';++import migration from './294-agents-md-quota-burn-presets.js';+import { QUOTA_BURN_PROMPT_PRESETS } from '../../server/lib/quotaBurnPresets.js';++const writeJson = (path, value) => writeFileSync(path, `${JSON.stringify(value, null, 2)}\n`);+const readJson = (path) => JSON.parse(readFileSync(path, 'utf8'));++const CURRENT_FRAGMENT = `Read this repository's \`AGENTS.md\` (or \`CLAUDE.md\`, and any nested+per-directory ones covering the slice) before you start, and honor its+conventions and its explicitly declared non-issues — a finding that contradicts+a documented project decision is noise, not a bug.`;++const PRIOR_FRAGMENT = `Read this repository's \`CLAUDE.md\` (and any nested per-directory ones covering+the slice) before you start, and honor its conventions and its explicitly+declared non-issues — a finding that contradicts a documented project decision+is noise, not a bug.`;++const preset = QUOTA_BURN_PROMPT_PRESETS[0];+const currentPrompt = preset.params.prompt;+const priorPrompt = currentPrompt.split(CURRENT_FRAGMENT).join(PRIOR_FRAGMENT);++describe('migration 294 — AGENTS.md quota-burn presets', () => {+ let rootDir;+ let configPath;++ beforeEach(() => {+ rootDir = mkdtempSync(join(tmpdir(), 'migration-294-'));+ mkdirSync(join(rootDir, 'data/cos'), { recursive: true });+ configPath = join(rootDir, 'data/cos/quota-burn.json');+ });++ afterEach(() => rmSync(rootDir, { recursive: true, force: true }));++ it('the fixture is a real prior render, not a lookalike', () => {+ // Non-vacuous guard: if the preset wording drifts, this fails here rather+ // than making the upgrade assertion below silently test nothing.+ expect(currentPrompt).toContain(CURRENT_FRAGMENT);+ expect(priorPrompt).not.toBe(currentPrompt);+ expect(priorPrompt).toContain('CLAUDE.md');+ });++ it('rewrites an unmodified stored preset render', async () => {+ writeJson(configPath, {+ families: { claude: { jobs: [{ id: 'j1', params: { prompt: priorPrompt } }] } },+ });++ const result = await migration.up({ rootDir });+ const job = readJson(configPath).families.claude.jobs[0];++ expect(result.updated).toBe(1);+ expect(job.params.prompt).toBe(currentPrompt);+ expect(job.params.prompt).toContain('AGENTS.md');+ });++ it('leaves a user-edited prompt untouched', async () => {+ // One extra character is enough to disqualify it — the rule is exact equality.+ const edited = `${priorPrompt}\n\nAlso check the sprite pipeline.`;+ writeJson(configPath, {+ families: { claude: { jobs: [{ id: 'j1', params: { prompt: edited } }] } },+ });++ const result = await migration.up({ rootDir });+ const job = readJson(configPath).families.claude.jobs[0];++ expect(result.updated).toBe(0);+ expect(result.skipped).toBe(1);+ expect(job.params.prompt).toBe(edited);+ });++ it('ignores jobs that never carried the audit contract', async () => {+ writeJson(configPath, {+ families: { claude: { jobs: [{ id: 'j1', params: { prompt: 'do something else' } }] } },+ });++ const result = await migration.up({ rootDir });+ expect(result).toEqual({ updated: 0, skipped: 0 });+ });++ it('is a no-op when no quota-burn config exists', async () => {+ expect((await migration.up({ rootDir })).updated).toBe(0);+ });+});diff --git a/scripts/regen-prompt-integrity-snapshot.js b/scripts/regen-prompt-integrity-snapshot.jsindex 4021f1f84f..7c38b9d512 100644--- a/scripts/regen-prompt-integrity-snapshot.js+++ b/scripts/regen-prompt-integrity-snapshot.js@@ -4,7 +4,7 @@** Run this ONLY after an intentional prompt-default change that also bumped* PROMPT_VERSIONS and appended the outgoing default to PREVIOUS_DEFAULT_PROMPTS- * (see CLAUDE.md "Distribution model"). Regenerating to silence a failing+ * (see AGENTS.md "Distribution model"). Regenerating to silence a failing* integrity test without those two steps blesses whatever edited a preserved* historical body — which is precisely what the test exists to catch.*diff --git a/scripts/tailnet-identity-leak.test.js b/scripts/tailnet-identity-leak.test.jsindex 1aca1bb676..0349ffa162 100644--- a/scripts/tailnet-identity-leak.test.js+++ b/scripts/tailnet-identity-leak.test.js@@ -6,7 +6,7 @@ import { fileURLToPath } from 'url';// Regression guard: a real Tailscale MagicDNS tailnet suffix, real device// names, and a real CGNAT peer IP were once committed across ~14 tracked// files (server routes/lib, client lib, several test fixtures, doc plans,-// and two changelog entries) — a violation of this repo's own CLAUDE.md+// and two changelog entries) — a violation of this repo's own AGENTS.md// "Sensitive Data & Privacy" section, which lists Tailscale node/MagicDNS// names and Tailscale/LAN IPs as never-commit categories. This test fails// the moment a real-looking value of either kind lands in a tracked file@@ -102,7 +102,7 @@ function realTailnetOffenders(text) {.map(([match]) => match);}-describe('no real Tailscale identity in tracked files (see CLAUDE.md Sensitive Data & Privacy)', () => {+describe('no real Tailscale identity in tracked files (see AGENTS.md Sensitive Data & Privacy)', () => {it('detector matches a real-shaped tailnet suffix and not existing placeholders (self-check)', () => {// Synthetic values shaped like real auto-generated Tailscale suffixes// (never observed real ones) — proves the detector actually fires.diff --git a/server/AGENTS.md b/server/AGENTS.mdnew file mode 100644index 0000000000..a76618814f--- /dev/null+++ b/server/AGENTS.md@@ -0,0 +1,21 @@+# Server conventions (`server/`)++These apply to Express/service/model code. Universal constraints (no try/catch outside the request lifecycle, functional programming, single-line logging, the Security Model, the Storage backend policy, the AI Provider Usage Policy, and the Sensitive Data & Privacy rules) live in the root `AGENTS.md` and always apply.++## Validation and schema parity++- **Schema parity when adding fields.** When you add a field to a sanitizer, `createXxx`, or a payload shape, update the corresponding Zod schema (`server/lib/aiToolkit/validation.js` for toolkit shapes, `server/lib/validation.js` for PortOS routes) in the same change. Wire validation into POST and PUT (PUT can use `schema.partial()`); the PortOS convention is *all* inputs validated — an exported-but-unwired sub-schema creates false confidence. For polymorphic stores like `PUT /api/settings` that accept any sub-object, validate the relevant slice with `schema.partial()` when its key is present in the request body (see `server/routes/settings.js` for the `backupConfigSchema.partial()` pattern). Tolerate UI sentinels (`endpoint: ''` for CLI providers) with `z.preprocess(v => v === '' ? undefined : v, …)`. When a service migrates legacy keys on read, the schema must still accept the legacy shape so older clients don't 400 before the migration runs.++## Write serialization and throughput++- **Async PATCH races on shared records — serialize writes server-side.** When two write paths can mutate the same record concurrently (e.g. a blur-save plus an explicit "Render" button against `stages.comicPages.cover`), client-side guards (refs, `onMouseDown`, status checks) are unreliable — keyboard activation, status==='unknown' stalls, and `loadState → modify → saveState` interleaving all defeat them. The correct fix is to serialize writes at the *file* level on the server (every PATCH awaits the previous one to settle before reading state, so it merges against the freshest persisted record). See `issueWriteTail` in `server/services/pipeline/issues.js`. A `Map<recordId, Promise>` is *not* enough — two writes to different record ids share the same JSON state file and can still clobber each other; collapse the queue to a single tail per shared file.+- **High-frequency state writes must batch.** Per-line state mutations that round-trip through `withStateLock → loadState → saveState` (e.g. `appendAgentOutput` in `cosAgentLifecycle.js`) are fine for human-pace events but catastrophic when called from a hot loop — PTY output streams, AI tool-call streams, or any producer that can emit dozens of events per second. When wiring a new streaming producer, add a batched variant that takes an array (see `appendAgentOutputLines` for the pattern) and flush from the caller on a ~250ms debounce. Always drain the pending buffer in the producer's `finish`/`cleanup` path before the final state write so completion events don't beat the last output batch to disk.++## Tests and peer fan-out++- **Record-creating tests and peer fan-out.** Record create/update paths reach peer-sync only through the subscription adapter in `server/services/sharing/recordEvents.js` (`autoSubscribeRecordToAllPeers` etc.) — a silent no-op until `peerSync.js` registers the real implementation at module load. A suite that never loads `peerSync.js` therefore gets no fan-out without mocking anything. Suites that DO load the peer-sync graph (importing `peerSync.js` or `sharing/index.js`, directly or transitively) must still mock `services/instances.js` with `mockNoPeers()` from `server/lib/mockPathsDataRoot.js` and `services/sharing/peerSync.js` with `mockNoPeerSync()` — the mock keeps the real module's registration side effect from wiring live fan-out into the adapter. To assert auto-subscribe behavior in a domain test, register a test double via `registerSubscriptionAdapter({...})` and clean up with `__resetSubscriptionAdapter()`.++## Prompt templates++- **Stage-prompt template changes need a migration.** `scripts/setup-data.js` only copies *missing* prompt files to `data/prompts/stages/` — existing installs keep their old templates. When you add a `{{template.variable}}` reference to a `data.reference/prompts/stages/*.md` file, also add an entry to `scripts/migrations/NNN-…js` that updates the corresponding installed prompt when its hash still matches the pre-change shipped version. Normalize line endings (`\r\n` → `\n`, bare `\r` → `\n`) before hashing so the comparison is correct on Windows checkouts. The drift warning in `scripts/setup-data.js` distinguishes auto-updatable (matches old shipped hash) from customized (matches neither) — when adding to the migrated list, mirror both `OLD_SHIPPED_MD5` and `NEW_SHIPPED_MD5` there too so the warning stays actionable. Migration scripts live in `scripts/migrations/`; the per-install applied-list is `data/migrations.applied.json` (gitignored runtime state). See `scripts/migrations/003-update-pipeline-stage-prompts.js`.+- **Creative prompts carry the IP-latitude clause automatically — never stamp it by hand.** PortOS is a professional artist's tool; a model that silently renames, genericizes, or disclaimers a deliberate reference to existing IP produces defective output, and rights/clearance is the operator's responsibility, not the model's. `server/lib/creativeLatitude.js` owns the clause and the single table that classifies what gets it, applied at each of the three LLM transports: `promptService.buildPrompt` (stage templates, keyed on the stage name — fails SAFE, so a stage the tables never saw is stamped), `promptRunner.runPromptThroughProvider` (every hand-rolled prompt, keyed on the run `source` tag it already requires — an allowlist, since ops calls dominate there), and `aiProvider.callProviderAISimple` (its own fetch, so creative callers pass `creative: true`). So **a new creative stage or LLM-calling service is covered only once its stage name / `source` is classified in that module** — add the prefix or exact name there rather than wrapping a call site. Two guard tests force the decision: `creativeLatitude.test.js` walks `data.reference/prompts/stage-config.json`, and `creativeLatitude.sources.test.js` scans every `source:` literal handed to the shared runners — both fail on an unclassified entry. A caller that budgets a context window before the stamp lands (the inline editorial check) must reserve `CREATIVE_LATITUDE_TOKENS`.diff --git a/server/CLAUDE.md b/server/CLAUDE.mdindex 525be90b73..43c994c2d3 100644--- a/server/CLAUDE.md+++ b/server/CLAUDE.md@@ -1,21 +1 @@-# Server conventions (`server/`)--These apply to Express/service/model code. Universal constraints (no try/catch outside the request lifecycle, functional programming, single-line logging, the Security Model, the Storage backend policy, the AI Provider Usage Policy, and the Sensitive Data & Privacy rules) live in the root `CLAUDE.md` and always apply.--## Validation and schema parity--- **Schema parity when adding fields.** When you add a field to a sanitizer, `createXxx`, or a payload shape, update the corresponding Zod schema (`server/lib/aiToolkit/validation.js` for toolkit shapes, `server/lib/validation.js` for PortOS routes) in the same change. Wire validation into POST and PUT (PUT can use `schema.partial()`); the PortOS convention is *all* inputs validated — an exported-but-unwired sub-schema creates false confidence. For polymorphic stores like `PUT /api/settings` that accept any sub-object, validate the relevant slice with `schema.partial()` when its key is present in the request body (see `server/routes/settings.js` for the `backupConfigSchema.partial()` pattern). Tolerate UI sentinels (`endpoint: ''` for CLI providers) with `z.preprocess(v => v === '' ? undefined : v, …)`. When a service migrates legacy keys on read, the schema must still accept the legacy shape so older clients don't 400 before the migration runs.--## Write serialization and throughput--- **Async PATCH races on shared records — serialize writes server-side.** When two write paths can mutate the same record concurrently (e.g. a blur-save plus an explicit "Render" button against `stages.comicPages.cover`), client-side guards (refs, `onMouseDown`, status checks) are unreliable — keyboard activation, status==='unknown' stalls, and `loadState → modify → saveState` interleaving all defeat them. The correct fix is to serialize writes at the *file* level on the server (every PATCH awaits the previous one to settle before reading state, so it merges against the freshest persisted record). See `issueWriteTail` in `server/services/pipeline/issues.js`. A `Map<recordId, Promise>` is *not* enough — two writes to different record ids share the same JSON state file and can still clobber each other; collapse the queue to a single tail per shared file.-- **High-frequency state writes must batch.** Per-line state mutations that round-trip through `withStateLock → loadState → saveState` (e.g. `appendAgentOutput` in `cosAgentLifecycle.js`) are fine for human-pace events but catastrophic when called from a hot loop — PTY output streams, AI tool-call streams, or any producer that can emit dozens of events per second. When wiring a new streaming producer, add a batched variant that takes an array (see `appendAgentOutputLines` for the pattern) and flush from the caller on a ~250ms debounce. Always drain the pending buffer in the producer's `finish`/`cleanup` path before the final state write so completion events don't beat the last output batch to disk.--## Tests and peer fan-out--- **Record-creating tests and peer fan-out.** Record create/update paths reach peer-sync only through the subscription adapter in `server/services/sharing/recordEvents.js` (`autoSubscribeRecordToAllPeers` etc.) — a silent no-op until `peerSync.js` registers the real implementation at module load. A suite that never loads `peerSync.js` therefore gets no fan-out without mocking anything. Suites that DO load the peer-sync graph (importing `peerSync.js` or `sharing/index.js`, directly or transitively) must still mock `services/instances.js` with `mockNoPeers()` from `server/lib/mockPathsDataRoot.js` and `services/sharing/peerSync.js` with `mockNoPeerSync()` — the mock keeps the real module's registration side effect from wiring live fan-out into the adapter. To assert auto-subscribe behavior in a domain test, register a test double via `registerSubscriptionAdapter({...})` and clean up with `__resetSubscriptionAdapter()`.--## Prompt templates--- **Stage-prompt template changes need a migration.** `scripts/setup-data.js` only copies *missing* prompt files to `data/prompts/stages/` — existing installs keep their old templates. When you add a `{{template.variable}}` reference to a `data.reference/prompts/stages/*.md` file, also add an entry to `scripts/migrations/NNN-…js` that updates the corresponding installed prompt when its hash still matches the pre-change shipped version. Normalize line endings (`\r\n` → `\n`, bare `\r` → `\n`) before hashing so the comparison is correct on Windows checkouts. The drift warning in `scripts/setup-data.js` distinguishes auto-updatable (matches old shipped hash) from customized (matches neither) — when adding to the migrated list, mirror both `OLD_SHIPPED_MD5` and `NEW_SHIPPED_MD5` there too so the warning stays actionable. Migration scripts live in `scripts/migrations/`; the per-install applied-list is `data/migrations.applied.json` (gitignored runtime state). See `scripts/migrations/003-update-pipeline-stage-prompts.js`.-- **Creative prompts carry the IP-latitude clause automatically — never stamp it by hand.** PortOS is a professional artist's tool; a model that silently renames, genericizes, or disclaimers a deliberate reference to existing IP produces defective output, and rights/clearance is the operator's responsibility, not the model's. `server/lib/creativeLatitude.js` owns the clause and the single table that classifies what gets it, applied at each of the three LLM transports: `promptService.buildPrompt` (stage templates, keyed on the stage name — fails SAFE, so a stage the tables never saw is stamped), `promptRunner.runPromptThroughProvider` (every hand-rolled prompt, keyed on the run `source` tag it already requires — an allowlist, since ops calls dominate there), and `aiProvider.callProviderAISimple` (its own fetch, so creative callers pass `creative: true`). So **a new creative stage or LLM-calling service is covered only once its stage name / `source` is classified in that module** — add the prefix or exact name there rather than wrapping a call site. Two guard tests force the decision: `creativeLatitude.test.js` walks `data.reference/prompts/stage-config.json`, and `creativeLatitude.sources.test.js` scans every `source:` literal handed to the shared runners — both fail on an unclassified entry. A caller that budgets a context window before the stamp lands (the inline editorial check) must reserve `CREATIVE_LATITUDE_TOKENS`.diff --git a/server/lib/README.md b/server/lib/README.mdindex 8bd97529d7..aa4564e086 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -183,6 +183,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `conflictJournal.js` | Non-blocking edit-conflict journal for cross-install LWW merges. `maybeJournalBeforeOverwrite({kind,id,local,remote,source})` (call right before a merge overwrite) archives the losing local version when a true 3-way divergence is detected (`detectConflict` via per-record `syncBaseHash` + `contentHashForRecord`), then advances the base hash; `flushBaseHashes()` persists the batched base-hash side store; `withBaseHashFlushBatch(fn)` defers every interior flush so an await-separated multi-record push loop (peer:online convergence) collapses N `sync_base_hashes.json` rewrites into one terminal write (re-entrant; flushes in `finally`). `deleteSyncBaseHash(kind,id)` evicts a record's base hash when its tombstone is hard-pruned (called from every `pruneTombstoned*` path — universe/series/issue/collection) so the side store doesn't grow without bound; `pruneOrphanedBaseHashes(resolves)` is the backstop sweep (`resolves(kind,id) => bool`; unknown kinds kept) that drops keys whose record no longer resolves, wired into the tombstone GC sweep. `conflictJournalStore()` is the `pending`/`resolved` entry store (discard resolves an entry; DELETE hard-removes it — there is no `dismissed` status). Local-only — never crosses the wire. || `schemaVersions.js` | Cross-instance sync version contract. `PORTOS_SCHEMA_VERSIONS` (frozen map of `{ category: layoutVersion }`), `RECORD_KIND_SCHEMA_CATEGORIES` (frozen map of federated record kind → the schema categories it writes), `buildPortosMeta()` (envelope for every outbound sync payload), `compareSchemaVersions(sender, receiver)` returning `{ ahead, behind, compatible }`, `scopeVersionDiff(diff, categories)` (restrict that diff to the categories a specific transfer touches), and `formatVersionGap()` for UI/log lines. Receivers gate `applyIncomingPush` / share-bucket import / snapshot apply per-category on the scoped comparator result so an upgraded sender can't corrupt a downstream peer — and a bump to one category doesn't sever sync of the others. || `dataRoot.js` | Data-root resolution + worktree-checkout detection (#1947). `resolveInstallRoot(fallbackRoot)` prefers the `PORTOS_DATA_ROOT` env var (pinned at real launch in `ecosystem.config.cjs`) over an `import.meta.url`-derived fallback, so a process booted from inside a CoS agent git worktree still resolves `data/`/`data.reference/` to the real install instead of the worktree's empty tree. `isWorktreeRoot(rootDir)` is the boot-migration backstop — true when `rootDir` lives under `data/cos/worktrees/` (keyed on the path segment only, so a fresh install's empty `data/` isn't a false positive). `DATA_ROOT_ENV` is the env-var name constant. Consumed by `fileUtils.js` (`PATHS`), `server/index.js`, and `scripts/run-migrations.js`. |+| `agentInstructionsFile.js` | The `AGENTS.md` + bridge `CLAUDE.md` pair a repo carries (#4852). `writeAgentInstructions(repoPath, content)` writes the body to `AGENTS.md` and the one-line `@AGENTS.md` import beside it — use it in scaffolders instead of a bare `writeFile(join(repoPath, 'CLAUDE.md'), …)`, since a generated repo carrying only one name is unreadable to half the CLIs PortOS can point at it. Constants: `AGENT_INSTRUCTIONS_FILENAME`, `CLAUDE_BRIDGE_FILENAME`, `AGENT_INSTRUCTIONS_IMPORT`. || `fileUtils.js` | `PATHS` constants, `atomicWrite`, `tryReadFile`, `pathExists` (async `existsSync` replacement for request/hot paths), `safeJSONParse`, `expandHome` (`~/foo` → absolute), `sleep(ms)`, `sanitizeFilename`, `importFileToUploads(tempPath, name)` (land a server-produced temp file in `PATHS.uploads` with `/api/uploads` naming), `saveBase64Upload(dir, { filename, data }, { allowedExtensions, maxBytes })` + `serveLocalFile(res, dir, filename, opts?)` (shared attachment upload/serve pipeline — allowlist, size cap, `<uuid8>-name`, containment guard, nosniff/disposition), extension allowlists (`ATTACHMENT_ALLOWED_EXTENSIONS`, `SONGBOOK_ATTACHMENT_EXTENSIONS`), `assertSafeFilename(name, {extensions, subject})` (throwing basename/traversal/extension gate) plus its non-throwing twin `isSafeFilename(name, extensions)` for read-only callers that must report a bad stored name as data rather than 400 the request — both share one implementation so the gate and the verdict can't drift, and `isTopLevelEntryName(name)` is that shared traversal half on its own, for callers that can't allowlist extensions (arbitrary user assets, directory entries) but still must refuse separators so no intermediate component is left for a symlink to redirect, `readFileTail(path, maxBytes)` (bounded-memory tail read for append-only logs/spools with no size ceiling — null on error vs `''` for an empty file; shared by the agent-transcript cap, the TUI failure analyzer, and the Codex rollout scan), JSONL append/read/write helpers, `dirSize(path, { strict })` (forgiving by default; strict reporting mode rejects failed scans instead of forging zero), hashes (`sha256File` streams above 512 KB; `sha256Text` is its in-memory twin for strings/Buffers), JSON helpers. `readJSONFile(path, default)` swallows every failure into `default`; `readJSONFileStrict(path, default)` → `{ ok, value }` (or `readJSONFile(…, { strict: true })`, which throws) tells "absent → trustworthy empty" apart from "present-but-unreadable/corrupt" — use it whenever the result is counted or shown, so a bad read can't report a fake 0. `tryReadFileStrict(path, encoding?)` → `{ ok, value }` is the same distinction for RAW bytes (the strict twin of `tryReadFile`, #4115): `ok && value !== null` read, `ok && value === null` absent, `!ok` present-but-unreadable. Reach for either whenever the value is counted, displayed, OR written back — a read-modify-write that swallows an unreadable file persists the empty default over real data. Which call sites were audited and why the rest are safe: [docs/decisions/2026-08-14-strict-json-reads-for-counted-values.md](../../docs/decisions/2026-08-14-strict-json-reads-for-counted-values.md). Most paths/file work goes through here. The slashdo command/lib loaders live in `slashdoLoader.js`. || `icloudFile.js` | Guards against blocking reads of **evicted (dataless) cloud files**. macOS Optimize-Mac-Storage offloads a file in an iCloud ubiquity container (or a `~/Library/CloudStorage` File Provider mount); the path and `size` remain but no blocks are local, and the first **data access** BLOCKS in the kernel until materialization completes — indefinitely and uncancellably when iCloud is wedged. Four such reads exhaust libuv's 4-thread fs pool and every later `fs` call in the process queues forever, including the `express.static` read that serves the UI bundle (the whole UI hangs while memory-only routes still answer). Retry-on-error can't help: the read doesn't fail, it hangs. `readIfMaterialized(path, {encoding, label})` screens with a `stat()` (safe — never materializes) and rejects with `err.code === ICLOUD_NOT_MATERIALIZED` instead of issuing the read, kicking a background `brctl download` so the next cycle succeeds; concurrent callers for one path+encoding share a single read. `isUbiquityPath(path)` resolves the containing directory's real path (memoized) rather than substring-matching, so a **symlinked** route into iCloud — `~/Documents/...` under "Desktop & Documents Folders" sync — is still recognized. `isDatalessStats(stats)` is the raw predicate (`size > 0 && blocks === 0`) and is **not safe alone** (a sparse or `decmpfs`-compressed ordinary file matches it); pair it with the platform + cloud-root scoping via `isEvictedStats(path, stats)`, which is what a caller holding a `Stats` should use, or `isSuspectedDataless(path)` which does the `stat` itself. `requestMaterialization(path, {label, retryAfterExit, onFailure})` is the fire-and-forget `brctl download` every brctl caller shares — read paths kick it (default `retryAfterExit: true`) to heal an evicted file, per-path-deduped in a shared in-flight map capped at 4 concurrent children (an evicted vault walk would otherwise fork one per note) and each killed at `DOWNLOAD_DEADLINE_MS` so a wedged `brctl` can't hold every slot for the life of the process; the boot/settings pin in `mortalLoomStore` passes `retryAfterExit: false` so it is NOT tracked in that shared map (it owns a single-sticky-path dedupe at its call site) plus an `onFailure` hook to clear that sticky path on a failed/killed download. `claimBrctlMissingWarning()` returns `true` on the first call only, so the "brctl not found on PATH" warning fires at most once per process across every brctl caller (the fire-and-forget path here and the awaited `materializeAndWait`). `materializeAndWait(path, {label, timeoutMs})` is the **awaited, bounded** counterpart used by WRITE paths (`mortalLoomStore` before overwriting its store, `obsidian.updateNote` before overwriting a note): a write must not silently skip, so it materializes and waits rather than firing and forgetting, bounded by `MATERIALIZE_TIMEOUT_MS` (20s — much tighter than the background `DOWNLOAD_DEADLINE_MS` because a caller is blocked on it) and run in a child process, which is what makes the wait cancellable when the kernel write it replaces would not be. It resolves `true` only on brctl exit-0, which means the download was **accepted, not completed** — always re-screen before trusting the file. Measured (#3706, #3713), and recorded in the module docblock's syscall table: `stat`/`open`/`rename`/`unlink` never materialize, while `read`, `write` (including after `O_TRUNC` — truncating does NOT skip the download), `link`, and `clonefile` all do. `unlink` being free is a measurement, not the POSIX inference — `link` is pure metadata too and it *does* materialize — so delete paths need no screen. The docblock also carries the reproduction recipe: `brctl evict <path>` works (undocumented, like `brctl download`), which is what makes the evict/measure/heal loop scriptable. Consumed by `services/mortalLoomStore.js` and `services/obsidian.js`. || `boundedStateMap.js` | `createBoundedStateMap({ maxSize, ttlMs })` — a `Map` that self-evicts so a per-key state cache can't grow one entry per key forever. Lazy TTL + LRU eviction on `get`/`set` (no timers); `get` doubles as the LRU touch. Used by the moltbook/moltworld rate-limiters to bound their per-agent state. |@@ -224,7 +225,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `bufferedSpawn.js` | `bufferedSpawn(cmd, args, opts)` (structured non-throwing result) + `bufferedSpawnOrThrow` (throwing adapter), plus `killProcessTree`, `resolveWindowsExecutable`, `prepareWindowsSafeSpawn`, `prepareCliSpawn(command, args, env)` (composed resolve+wrap for a `spawn()`-safe pair), `needsShell`, `IS_WIN32`, `WIN_CMD_SHIMS`, `MAX_OUTPUT_BYTES`, `spawnFailureDetail(result, fallback)` (the most useful sentence from a failed result — prefers the spawn error, then a stderr line, then a stdout line that isn't bare JSON punctuation, because a `--json` CLI prints its payload to stdout even when it exits non-zero) — shared buffered-spawn machinery with capped stdout/stderr, timeout-kill, Windows `.cmd`/`.bat` shim resolution, and `taskkill /T /F` tree-kill. `killProcessTree(child, signal, { processGroup })` takes the POSIX group down too when the child was spawned `detached` (Windows always tree-kills). Used by `appBuilder.js`, `appUpdater.js`, the CoS agent spawners, and `setupScriptRunner.js`. || `setupScriptRunner.js` | `spawnSetupScript(envVars)` / `stopSetupScript(child)` / `SETUP_IMAGE_VIDEO_SCRIPT` — the one way to run `scripts/setup-image-video.sh` (shared by the Video Gen BYOV runtimes, the music engines and the MuScriptor venv). Runs it under `resolveBashBinary()` with a `toBashPath` script path, and on Windows presets the `PYTHON_BIN` the script would otherwise default to `python3` for. Cancel via `stopSetupScript`, which tree-kills so uv / pip / git die with bash. || `commandExists.js` | `commandExists(cmd, args = ['--version'], { timeoutMs = 5_000, env, cwd })` — does running `cmd args` succeed? A capability probe (`execFile`-based), not a PATH lookup like `processEnv.js`'s `whichFirst`; `env`/`cwd` let a caller check the exact child process configuration. Consolidates the two previously-private copies in `localLlm.js`/`ollamaManager.js`; callers probing a heavier CLI (e.g. `codeReview.js`'s reviewer-binary probe) pass a longer `timeoutMs`. |-| `spawnCwd.js` | `resolveSpawnCwd(workspacePath, fallbackRoot, label)` — resolves and **logs** the working directory a run/agent spawns into (expanding `~`), and throws when a workspace was requested but is missing / not a directory. Behind `services/runner.js#resolveRunCwd`, which turns that throw into a normal failed-run record for the two spawning runners. Stops a bad app `repoPath` from silently spawning in the PortOS checkout (#3180). `usesCreativeDirectorScratchCwd(task)` / `creativeDirectorScratchCwd(agentId)` / `removeCreativeDirectorScratchCwd(agentId)` / `resolveAgentCliCwd({ workspacePath, fallbackRoot, task, agentId })` — Creative Director no-worktree tasks get a per-agent scratch cwd under `os.tmpdir()/portos-cd-cwd/<id>` (outside the PortOS git tree) instead of the PortOS root, so native CLI CLAUDE.md discovery cannot walk up into the repo (#4650). `removeCreativeDirectorScratchCwd` is the matching finalize cleanup. `withSpawnCwdEnv(env, cwd)` — returns a copy of `env` with `PWD` pinned to `cwd` (dropping stale case-variant keys), because `spawn({ cwd })` doesn't rewrite the inherited `PWD` and OpenCode resolves its project root as `process.env.PWD ?? process.cwd()` (#3193). Apply it at every spawn that names its own cwd — the shared wrappers (`bufferedSpawn`, `spawnDetached`) already do, so their callers inherit it. `spawnCwd.test.js` discovers cwd-passing spawns across `server/` and fails on any that neither pins nor is listed exempt.+| `spawnCwd.js` | `resolveSpawnCwd(workspacePath, fallbackRoot, label)` — resolves and **logs** the working directory a run/agent spawns into (expanding `~`), and throws when a workspace was requested but is missing / not a directory. Behind `services/runner.js#resolveRunCwd`, which turns that throw into a normal failed-run record for the two spawning runners. Stops a bad app `repoPath` from silently spawning in the PortOS checkout (#3180). `usesCreativeDirectorScratchCwd(task)` / `creativeDirectorScratchCwd(agentId)` / `removeCreativeDirectorScratchCwd(agentId)` / `resolveAgentCliCwd({ workspacePath, fallbackRoot, task, agentId })` — Creative Director no-worktree tasks get a per-agent scratch cwd under `os.tmpdir()/portos-cd-cwd/<id>` (outside the PortOS git tree) instead of the PortOS root, so native CLI AGENTS.md / CLAUDE.md discovery cannot walk up into the repo (#4650). `removeCreativeDirectorScratchCwd` is the matching finalize cleanup. `withSpawnCwdEnv(env, cwd)` — returns a copy of `env` with `PWD` pinned to `cwd` (dropping stale case-variant keys), because `spawn({ cwd })` doesn't rewrite the inherited `PWD` and OpenCode resolves its project root as `process.env.PWD ?? process.cwd()` (#3193). Apply it at every spawn that names its own cwd — the shared wrappers (`bufferedSpawn`, `spawnDetached`) already do, so their callers inherit it. `spawnCwd.test.js` discovers cwd-passing spawns across `server/` and fails on any that neither pins nor is listed exempt.| `commandSecurity.js` | Allowlist of safe shell commands + `validatePm2Command(args)` (rejects daemon-wide `pm2 kill`/`startup`/`unstartup` and `<verb> all`). `validateCommand` runs the pm2 check for `pm2` base commands. Mirrored by the `agentGuard/` PATH shim for agentic paths. || `detachedSpawn.js` | `spawnDetached(bin, args, {controlDir,env,cwd,killProcessGroup?})` → ChildProcess-like handle for a long media job that SURVIVES `pm2 restart portos-server`. A pure-`sh` double-fork reparents the job to init (escaping pm2's PPID-based TreeKill — `detached:true` alone doesn't, since it only changes the process group); the server tails on-disk log files for `stdout`/`stderr`/`close`. Group-kill mode persists a marker so cancel, reattach, and orphan reaping terminate a group-leader wrapper plus every runtime child together. Windows has no double-fork (plain-spawn fallback), so its handle's `kill` delegates to `killProcessTree` (`taskkill /T /F`) — a cancel there takes the runner's children with it. Used by loraTraining + videoGen. Also exports `reattachDetached(controlDir)` / `isReattachable(controlDir)` to RE-ATTACH a survivor after a restart (boot re-attach, #1332) and `reapDetached` to checkpoint-kill one when re-attach isn't possible. || `hostShutdown.js` | Tells "PortOS was restarted out from under a running agent" apart from "the agent failed" (#3202). `markHostShuttingDown()` / `isHostShuttingDown()` are the in-process latch the SIGTERM/SIGINT handler sets first thing; `shouldAbandonForHostShutdown({sentinelPresent,terminatedByUser,paused})` keeps every spawn path on the same preserve-vs-finalize policy. `writeHostShutdownMarker({agentIds,signal})` / `readHostShutdownMarker()` / `clearHostShutdownMarker()` persist that verdict to `data/cos/host-shutdown.json` so the NEXT boot's orphan sweep can requeue those agents as *interrupted* — no orphan-retry charge, no 30-minute cooldown. All non-throwing: a missing marker degrades to the ordinary orphan path. |diff --git a/server/lib/agentInstructionsFile.js b/server/lib/agentInstructionsFile.jsnew file mode 100644index 0000000000..a0345f43c6--- /dev/null+++ b/server/lib/agentInstructionsFile.js@@ -0,0 +1,40 @@+/**+ * The agent-instructions file pair a repository carries (#4852).+ *+ * `AGENTS.md` is the cross-vendor standard every CLI PortOS drives reads —+ * except Claude Code, whose memory discovery hardcodes `CLAUDE.md` with no+ * configurable filename. So a repo needs both, and the second one is a+ * one-line `@AGENTS.md` import rather than a symlink: a git symlink checked out+ * on a Windows runner without symlink support materializes as a 9-byte text+ * file containing the literal string `AGENTS.md`, from which Claude Code loads+ * nothing, and a CLI that reads BOTH names (grok) would ingest the full body+ * twice. A real import file is correct on every platform and inert everywhere+ * else.+ */++import { writeFile } from 'fs/promises';+import { join } from 'path';++/** Canonical filename holding the content. */+export const AGENT_INSTRUCTIONS_FILENAME = 'AGENTS.md';++/** Claude Code's hardcoded filename, kept as a bridge to the canonical one. */+export const CLAUDE_BRIDGE_FILENAME = 'CLAUDE.md';++/** Entire body of the bridge file. */+export const AGENT_INSTRUCTIONS_IMPORT = '@AGENTS.md\n';++/**+ * Write a repo's instructions to `AGENTS.md` and the Claude Code bridge beside+ * it. Use this instead of a bare `writeFile(join(repoPath, 'CLAUDE.md'), …)` —+ * a generated repo carrying only one of the two names is unreadable to half the+ * CLIs PortOS can point at it.+ * @param {string} repoPath+ * @param {string} content full `AGENTS.md` body+ */+export async function writeAgentInstructions(repoPath, content) {+ await Promise.all([+ writeFile(join(repoPath, AGENT_INSTRUCTIONS_FILENAME), content),+ writeFile(join(repoPath, CLAUDE_BRIDGE_FILENAME), AGENT_INSTRUCTIONS_IMPORT),+ ]);+}diff --git a/server/lib/agentInstructionsFile.test.js b/server/lib/agentInstructionsFile.test.jsnew file mode 100644index 0000000000..762b0d78bf--- /dev/null+++ b/server/lib/agentInstructionsFile.test.js@@ -0,0 +1,29 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { mkdtempSync, rmSync, readFileSync, lstatSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';++import { writeAgentInstructions, AGENT_INSTRUCTIONS_IMPORT } from './agentInstructionsFile.js';++describe('writeAgentInstructions (#4852)', () => {+ let repoPath;++ beforeEach(() => { repoPath = mkdtempSync(join(tmpdir(), 'portos-agentmd-write-')); });+ afterEach(() => rmSync(repoPath, { recursive: true, force: true }));++ it('writes the body to AGENTS.md and the import bridge to CLAUDE.md', async () => {+ await writeAgentInstructions(repoPath, '# Example App\n\nConventions go here.\n');++ expect(readFileSync(join(repoPath, 'AGENTS.md'), 'utf8')).toBe('# Example App\n\nConventions go here.\n');+ expect(readFileSync(join(repoPath, 'CLAUDE.md'), 'utf8')).toBe(AGENT_INSTRUCTIONS_IMPORT);+ });++ it('writes two regular files, never a symlink', async () => {+ // A git symlink checked out on a Windows runner degrades to 9 bytes of junk+ // text, from which Claude Code loads nothing — so the bridge must be real.+ await writeAgentInstructions(repoPath, '# Example App\n');++ expect(lstatSync(join(repoPath, 'AGENTS.md')).isSymbolicLink()).toBe(false);+ expect(lstatSync(join(repoPath, 'CLAUDE.md')).isSymbolicLink()).toBe(false);+ });+});diff --git a/server/lib/aiToolkit/AGENTS.md b/server/lib/aiToolkit/AGENTS.mdnew file mode 100644index 0000000000..d733b32a92--- /dev/null+++ b/server/lib/aiToolkit/AGENTS.md@@ -0,0 +1,21 @@+# AI Toolkit (`server/lib/aiToolkit/`)++The AI provider/runner/prompt toolkit is vendored in-tree here. (It was previously the `portos-ai-toolkit` npm package.) Keep the directory self-contained — no imports out to other PortOS modules — so future upstream syncs don't fight local edits.++**Key points:**+- `index.js` exports `createAIToolkit`, `createProviderStatusService`, and the four Router factories (providers / runs / prompts / providerStatus)+- Provider configuration (models, tiers, fallbacks) lives in `providers.js`+- `loadProviders()` auto-migrates legacy codex configs to the `codex-configured-default` sentinel; `server/index.js` warms it at startup so the rewrite happens before any request+- PortOS extends toolkit routes in `server/routes/providers.js` for vision testing and provider status (status routes live in PortOS, not the toolkit, because they call PortOS-side socket helpers)+- When adding new provider fields (e.g., `fallbackProvider`, `lightModel`), update `createProvider()` in `providers.js`+- `updateProvider()` uses spread so existing providers preserve custom fields, but `createProvider()` has an explicit field list+- **Refreshing more than one provider goes through `refreshProviderModelsBatch(ids)`, never a loop over `refreshProviderModels(id)`.** Every single-provider refresh ends in `saveProviders`, which invalidates the read cache and rewrites all of `providers.json`; an N-provider fan-out that way is N full-file writes, each superseded by the next. The batch form groups by `ollamaRefreshGroupKey` (one probe per daemon + probe shape), probes each group's lead without persisting, then applies every result and saves **exactly once**. It never throws for a per-provider failure — each group carries its own `status` (`updated` / `failed` / `missing`) so the host logs one line per group rather than one per member. PortOS's post-install fan-out (`refreshOllamaBackedProviders` in `server/services/localLlm.js`) is the worked example.++**Runner extension points.** The runner exposes a small declared override surface (in `runner.js`) so the host (PortOS) supplies its own runners without reaching into private internals:++- `setCliRunner(fn)` / `setTuiRunner(fn)` — register host CLI/TUI runners (pass `null` to revert). PortOS calls both in `server/index.js`: its CLI variant is stdin-based and knows the per-CLI argv conventions (Codex `exec -`, Antigravity `agy --print`, Claude Code `-p -`); the TUI runner has no toolkit built-in, and `setTuiRunner` attaches/detaches `executeTuiRun` so the runs router's `typeof runnerService.executeTuiRun === 'function'` gate stays honest.+- `registerExternalRun(runId, killable)` / `unregisterExternalRun(runId)` / `hasExternalRun(runId)` — track host-spawned child processes / ptys. The toolkit's own `stopRun`, `isRunActive`, and `deleteRun` consult this registry *first*, so **a host runner that spawns its own process MUST register it here** (PortOS does this in `services/runner.js`) — otherwise the runs router reports live runs as inactive and refuses to stop them, and deleting a live run leaks a zombie process. `stopRun` also stamps a one-shot marker consumed through `consumeExternalRunStop(runId)` before unregistering, which lets the host classify the resulting signal as cancellation instead of a provider failure. That classification rides out to callers as `canceled: true` on the run metadata and `code: 'RUN_CANCELED'` on the rejection the prompt runner raises — **anything that turns an LLM failure into a verdict (a pause kind, a filed gap/investigation task, a provider bench, an `error` status) must call `isRunCanceledError` from `errorDetection.js` first**, or it files bug reports about a human pressing Stop. No sibling-method monkey-patching is needed: adding a new lifecycle method (e.g. `pauseRun`) just means having it consult `externalRuns` too.+- `createProviderStatusService({ prerequisitesMet })` — host gate for "can this provider run AT ALL?" (its CLI binary present). `getFallbackProvider` consults it on every candidate: task-level, configured, and system-priority alike. Injected rather than computed here because the answer needs host I/O (a PATH probe) and this directory stays self-contained; PortOS supplies `prerequisitesMetForRouting` from `services/providerPrerequisites.js` in `bootstrap.js`. It MUST be synchronous, and a missing / throwing / non-boolean answer deliberately reads as "yes" — an unknown answer has to route exactly as it did before, because emptying the fallback chain is a far worse failure than the late ENOENT the gate exists to prevent.+- Time-based state transitions need read-side mirrors. `providerStatus.init()` clears expired `estimatedRecovery` entries; every reader (`getStatus`, `getAllStatuses`, `isAvailable`) must re-apply the same recovery check on read — otherwise providers stay "unavailable" past their recovery deadline until the next process restart.++The worked example for "barrel + documented exports" (see root `AGENTS.md` → Module Organization) is this directory's `index.js`.diff --git a/server/lib/aiToolkit/CLAUDE.md b/server/lib/aiToolkit/CLAUDE.mdindex 46c3f37514..43c994c2d3 100644--- a/server/lib/aiToolkit/CLAUDE.md+++ b/server/lib/aiToolkit/CLAUDE.md@@ -1,21 +1 @@-# AI Toolkit (`server/lib/aiToolkit/`)--The AI provider/runner/prompt toolkit is vendored in-tree here. (It was previously the `portos-ai-toolkit` npm package.) Keep the directory self-contained — no imports out to other PortOS modules — so future upstream syncs don't fight local edits.--**Key points:**-- `index.js` exports `createAIToolkit`, `createProviderStatusService`, and the four Router factories (providers / runs / prompts / providerStatus)-- Provider configuration (models, tiers, fallbacks) lives in `providers.js`-- `loadProviders()` auto-migrates legacy codex configs to the `codex-configured-default` sentinel; `server/index.js` warms it at startup so the rewrite happens before any request-- PortOS extends toolkit routes in `server/routes/providers.js` for vision testing and provider status (status routes live in PortOS, not the toolkit, because they call PortOS-side socket helpers)-- When adding new provider fields (e.g., `fallbackProvider`, `lightModel`), update `createProvider()` in `providers.js`-- `updateProvider()` uses spread so existing providers preserve custom fields, but `createProvider()` has an explicit field list-- **Refreshing more than one provider goes through `refreshProviderModelsBatch(ids)`, never a loop over `refreshProviderModels(id)`.** Every single-provider refresh ends in `saveProviders`, which invalidates the read cache and rewrites all of `providers.json`; an N-provider fan-out that way is N full-file writes, each superseded by the next. The batch form groups by `ollamaRefreshGroupKey` (one probe per daemon + probe shape), probes each group's lead without persisting, then applies every result and saves **exactly once**. It never throws for a per-provider failure — each group carries its own `status` (`updated` / `failed` / `missing`) so the host logs one line per group rather than one per member. PortOS's post-install fan-out (`refreshOllamaBackedProviders` in `server/services/localLlm.js`) is the worked example.--**Runner extension points.** The runner exposes a small declared override surface (in `runner.js`) so the host (PortOS) supplies its own runners without reaching into private internals:--- `setCliRunner(fn)` / `setTuiRunner(fn)` — register host CLI/TUI runners (pass `null` to revert). PortOS calls both in `server/index.js`: its CLI variant is stdin-based and knows the per-CLI argv conventions (Codex `exec -`, Antigravity `agy --print`, Claude Code `-p -`); the TUI runner has no toolkit built-in, and `setTuiRunner` attaches/detaches `executeTuiRun` so the runs router's `typeof runnerService.executeTuiRun === 'function'` gate stays honest.-- `registerExternalRun(runId, killable)` / `unregisterExternalRun(runId)` / `hasExternalRun(runId)` — track host-spawned child processes / ptys. The toolkit's own `stopRun`, `isRunActive`, and `deleteRun` consult this registry *first*, so **a host runner that spawns its own process MUST register it here** (PortOS does this in `services/runner.js`) — otherwise the runs router reports live runs as inactive and refuses to stop them, and deleting a live run leaks a zombie process. `stopRun` also stamps a one-shot marker consumed through `consumeExternalRunStop(runId)` before unregistering, which lets the host classify the resulting signal as cancellation instead of a provider failure. That classification rides out to callers as `canceled: true` on the run metadata and `code: 'RUN_CANCELED'` on the rejection the prompt runner raises — **anything that turns an LLM failure into a verdict (a pause kind, a filed gap/investigation task, a provider bench, an `error` status) must call `isRunCanceledError` from `errorDetection.js` first**, or it files bug reports about a human pressing Stop. No sibling-method monkey-patching is needed: adding a new lifecycle method (e.g. `pauseRun`) just means having it consult `externalRuns` too.-- `createProviderStatusService({ prerequisitesMet })` — host gate for "can this provider run AT ALL?" (its CLI binary present). `getFallbackProvider` consults it on every candidate: task-level, configured, and system-priority alike. Injected rather than computed here because the answer needs host I/O (a PATH probe) and this directory stays self-contained; PortOS supplies `prerequisitesMetForRouting` from `services/providerPrerequisites.js` in `bootstrap.js`. It MUST be synchronous, and a missing / throwing / non-boolean answer deliberately reads as "yes" — an unknown answer has to route exactly as it did before, because emptying the fallback chain is a far worse failure than the late ENOENT the gate exists to prevent.-- Time-based state transitions need read-side mirrors. `providerStatus.init()` clears expired `estimatedRecovery` entries; every reader (`getStatus`, `getAllStatuses`, `isAvailable`) must re-apply the same recovery check on read — otherwise providers stay "unavailable" past their recovery deadline until the next process restart.--The worked example for "barrel + documented exports" (see root `CLAUDE.md` → Module Organization) is this directory's `index.js`.diff --git a/server/lib/aiToolkit/defaults/providersSeedParity.test.js b/server/lib/aiToolkit/defaults/providersSeedParity.test.jsindex 62360d8675..09ba94c5c4 100644--- a/server/lib/aiToolkit/defaults/providersSeedParity.test.js+++ b/server/lib/aiToolkit/defaults/providersSeedParity.test.js@@ -16,7 +16,7 @@* default, PortOS's seed is tuned for this install.** This reads both files as JSON — it does NOT import out of the vendored- * aiToolkit directory into PortOS (see server/lib/aiToolkit/CLAUDE.md), so the+ * aiToolkit directory into PortOS (see server/lib/aiToolkit/AGENTS.md), so the* self-contained rule is preserved. If an upstream toolkit sync ever diverges* the sample, this test makes that visible instead of silent.*/diff --git a/server/lib/aiToolkit/internal/antigravity.test.js b/server/lib/aiToolkit/internal/antigravity.test.jsindex 74755fe4ce..56304c5d83 100644--- a/server/lib/aiToolkit/internal/antigravity.test.js+++ b/server/lib/aiToolkit/internal/antigravity.test.js@@ -1,6 +1,6 @@import { describe, it, expect } from 'vitest';import { ANTIGRAVITY_CONFIGURED_DEFAULT, isAntigravityCommand, parseAntigravityModelList } from './antigravity.js';-// The toolkit SOURCE may not import out to server/lib (see ../CLAUDE.md); a test+// The toolkit SOURCE may not import out to server/lib (see ../AGENTS.md); a test// may, and this is the only way to actually pin the duplication it documents.import {isAntigravityCommand as upstreamIsAntigravityCommand,diff --git a/server/lib/aiToolkit/internal/atomicWrite.js b/server/lib/aiToolkit/internal/atomicWrite.jsindex f461742ce7..0ae635c66d 100644--- a/server/lib/aiToolkit/internal/atomicWrite.js+++ b/server/lib/aiToolkit/internal/atomicWrite.js@@ -2,7 +2,7 @@* Atomic file write helper for the aiToolkit.** Vendored copy of server/lib/fileUtils.js#atomicWrite so the toolkit stays- * self-contained (no imports out to sibling PortOS modules — see CLAUDE.md+ * self-contained (no imports out to sibling PortOS modules — see AGENTS.md* "AI Toolkit" section). Keep in sync with the upstream implementation:** PARITY REQUIREMENT: every change to server/lib/fileUtils.js#atomicWritediff --git a/server/lib/aiToolkit/internal/commandBasename.js b/server/lib/aiToolkit/internal/commandBasename.jsindex efbf2f27d7..56335b070e 100644--- a/server/lib/aiToolkit/internal/commandBasename.js+++ b/server/lib/aiToolkit/internal/commandBasename.js@@ -3,7 +3,7 @@** A toolkit-local twin of `commandBasename` in server/lib/providerModels.js —* the vendored toolkit may not import out to sibling PortOS modules (see- * ../CLAUDE.md), and this rule was previously inlined once per vendor predicate+ * ../AGENTS.md), and this rule was previously inlined once per vendor predicate* inside `internal/`. One copy inside the boundary is unavoidable; two were not.** Strips the directory, lowercases, and drops a Windows `.exe` suffix so adiff --git a/server/lib/aiToolkit/internal/cursor.js b/server/lib/aiToolkit/internal/cursor.jsindex 7da56e2103..e1008667d8 100644--- a/server/lib/aiToolkit/internal/cursor.js+++ b/server/lib/aiToolkit/internal/cursor.js@@ -3,7 +3,7 @@** `CURSOR_COMMAND` and `isCursorCommand` are duplicated from* server/lib/cursor.js so the toolkit stays self-contained (no imports out to- * sibling PortOS modules — see ../CLAUDE.md); keep those two in sync with+ * sibling PortOS modules — see ../AGENTS.md); keep those two in sync with* upstream, the same arrangement as ./antigravity.js.** `CURSOR_TUI_ID`, `CURSOR_MODEL_LINE` and `parseCursorModelList` arediff --git a/server/lib/aiToolkit/internal/cursor.test.js b/server/lib/aiToolkit/internal/cursor.test.jsindex 74ff79a29d..93957f573d 100644--- a/server/lib/aiToolkit/internal/cursor.test.js+++ b/server/lib/aiToolkit/internal/cursor.test.js@@ -1,6 +1,6 @@import { describe, it, expect } from 'vitest';import { CURSOR_COMMAND, CURSOR_TUI_ID, isCursorCommand, parseCursorModelList } from './cursor.js';-// The toolkit SOURCE may not import out to server/lib (see ../CLAUDE.md); a test+// The toolkit SOURCE may not import out to server/lib (see ../AGENTS.md); a test// may, and this is the only way to actually pin the duplication it documents.import { CURSOR_COMMAND as UPSTREAM_COMMAND, isCursorCommand as upstreamIsCursorCommand } from '../../cursor.js';diff --git a/server/lib/aiToolkit/providers.js b/server/lib/aiToolkit/providers.jsindex e0643671d0..8f923d6d2c 100644--- a/server/lib/aiToolkit/providers.js+++ b/server/lib/aiToolkit/providers.js@@ -73,7 +73,7 @@ const WIN_EXECUTABLE_EXTS = ['.exe', '.cmd', '.bat', '.com'];/*** Resolve a bare command name to its full path WITH extension on Windows —* mirrors `resolveWindowsExecutable` in `server/lib/bufferedSpawn.js`- * (duplicated here for this directory's self-containment; see ./CLAUDE.md).+ * (duplicated here for this directory's self-containment; see ./AGENTS.md).* Filesystem-only (no subprocess), so it can't reorder/misselect the way a* raw `where` first-line read can.*/@@ -130,7 +130,7 @@ function escapeCmdMetacharsIfUnquoted(value) {}// windowsHide is applied here rather than by importing server/lib/childProcess.js:-// the aiToolkit is contractually self-contained (see aiToolkit/CLAUDE.md), so it+// the aiToolkit is contractually self-contained (see aiToolkit/AGENTS.md), so it// carries its own copy of the default. Without it, every CLI probe below spawns// a console from PortOS's console-less PM2 fork, which Windows hands off to// Windows Terminal as a focus-stealing window. See docs/WINDOWS_CONSOLE.md.@@ -1203,7 +1203,7 @@ export function createProviderService(config = {}) {* flattening it to null, so the toast names the actual cause instead of the* route's generic not-found text — and the stored list is left untouched* either way, since nothing is persisted. Same posture as- * `_fetchOllamaToolCapableModels`, and the root CLAUDE.md rule that a+ * `_fetchOllamaToolCapableModels`, and the root AGENTS.md rule that a* reachable-but-list-failed backend must surface an explicit error rather* than a plausible-looking empty/default result.*diff --git a/server/lib/aiToolkit/providers.test.js b/server/lib/aiToolkit/providers.test.jsindex 84b842ebbe..16dbe94472 100644--- a/server/lib/aiToolkit/providers.test.js+++ b/server/lib/aiToolkit/providers.test.js@@ -121,7 +121,7 @@ describe('Provider Service', () => {).rejects.toThrow('Provider with this ID already exists');});- // Guards the regression noted in CLAUDE.md: `updateProvider` uses spread so+ // Guards the regression noted in AGENTS.md: `updateProvider` uses spread so// existing providers preserve custom fields, but `createProvider` has an// explicit field list. A field added to the schema without being added to// `createProvider` would silently disappear on the create → save → loaddiff --git a/server/lib/aiToolkit/runner.js b/server/lib/aiToolkit/runner.jsindex a0bf44692d..2fbdab8259 100644--- a/server/lib/aiToolkit/runner.js+++ b/server/lib/aiToolkit/runner.js@@ -12,7 +12,7 @@ import { apiGenerationOptions } from './internal/generationOptions.js';// shims on Windows; Node's spawn() can't execute those without going through// cmd.exe. Mirrors `server/lib/bufferedSpawn.js`'s IS_WIN32/killProcessTree/// resolveWindowsExecutable pattern — duplicated rather than imported, since-// this directory must stay self-contained (see ./CLAUDE.md).+// this directory must stay self-contained (see ./AGENTS.md).const IS_WIN32 = process.platform === 'win32';// Extensions Windows can launch directly, checked in cmd.exe's own resolution@@ -158,7 +158,7 @@ export function createRunnerService(config = {}) {// from server/index.js, the host registers them via setCliRunner/setTuiRunner.// Externally-spawned runs (the host owns their child process / pty) are tracked// in `externalRuns` so the toolkit's stopRun/isRunActive/deleteRun see them.- // See server/lib/aiToolkit/CLAUDE.md (override contract).+ // See server/lib/aiToolkit/AGENTS.md (override contract).let cliRunnerOverride = null;const externalRuns = new Map();// A host runner sees only the child/PTY exit event. Remember when that exitdiff --git a/server/lib/aiToolkit/runner.test.js b/server/lib/aiToolkit/runner.test.jsindex 86764add7b..588e7153c0 100644--- a/server/lib/aiToolkit/runner.test.js+++ b/server/lib/aiToolkit/runner.test.js@@ -452,7 +452,7 @@ describe('AI Toolkit runner — built-in executeCliRun spawn (#1865)', () => {// Mirrors server/services/runner.test.js's equivalent assertion — this is// the toolkit's OWN spawn path (inert in PortOS, which always registers a// host CLI runner via setCliRunner, but must stay behaviorally in sync per- // the override-consistency contract in ./CLAUDE.md).+ // the override-consistency contract in ./AGENTS.md).function makeChild() {const child = new EventEmitter();child.stdout = new EventEmitter();diff --git a/server/lib/assetMounts.js b/server/lib/assetMounts.jsindex 9d2845d2c8..c1838e747c 100644--- a/server/lib/assetMounts.js+++ b/server/lib/assetMounts.js@@ -4,7 +4,7 @@** `server/index.js` used to spell each `app.use('/data/…', express.static(…))`* out inline, so nothing could enumerate what was served without regexing the- * source. This is the `server/lib/navManifest.js` pattern the root CLAUDE.md+ * source. This is the `server/lib/navManifest.js` pattern the root AGENTS.md* recommends for exactly that drift problem: one table, iterated by the thing* that mounts and read as data by the guard. The route strings themselves live* one level down in `assetRoutePrefixes.js`, alongside the namespaces thediff --git a/server/lib/auditCatalog.js b/server/lib/auditCatalog.jsindex 7f43753458..1555c63d9d 100644--- a/server/lib/auditCatalog.js+++ b/server/lib/auditCatalog.js@@ -47,14 +47,14 @@ Your deliverable is tracker items, not code. The run must end with the same \`gi5. **Redact before you publish.** An issue is world-readable the moment it is filed. Never paste a secret, credential, token, hostname, IP address, absolute path containing a username, or any personal record into a title or body.6. **Report at the end**: the slice you audited, each item you filed, and anything you deliberately did not file and why.-Read this repository's \`CLAUDE.md\` (and any nested per-directory ones covering the slice) before you start, and honor its conventions and its explicitly declared non-issues.`;+Read this repository's \`AGENTS.md\` (and any nested per-directory ones covering the slice) before you start, and honor its conventions and its explicitly declared non-issues.`;export const DO_WORK_MODE_CONTRACT = `## Mode: implement the highest-value fixThis banner OVERRIDES any later instruction to file issues, leave source unchanged, or skip commits. Pick ONE coherent, high-value finding from the mission below and implement it this run. Do not boil the ocean.1. **Pick a bounded slice** and say so first.-2. **Read the actual code** and the project's \`CLAUDE.md\` / conventions. Honor documented non-issues.+2. **Read the actual code** and the project's \`AGENTS.md\` / conventions. Honor documented non-issues.3. **Implement the fix** — the smallest change that actually solves the user-visible problem. If the only obstacle was a design choice, make the call and state it.4. **Verify** with the project's tests (or a focused new test when the path is untested and a silent break would cost data, money, or quota).5. **Commit** following the repo's conventions. Do not bundle unrelated cleanup.diff --git a/server/lib/branchUpstreamGuard.js b/server/lib/branchUpstreamGuard.jsindex 6672152881..8f99f3ad15 100644--- a/server/lib/branchUpstreamGuard.js+++ b/server/lib/branchUpstreamGuard.js@@ -45,7 +45,7 @@ const GIT_TIMEOUT_MS = 10_000;/*** Read a branch's configured upstream as raw config values.*- * Three outcomes, deliberately NOT collapsed (see CLAUDE.md, "Sentinel ++ * Three outcomes, deliberately NOT collapsed (see AGENTS.md, "Sentinel +* validate"): `''` is UNSET (a healthy untracked branch), a string is the* configured ref, and `null` is COULD NOT READ. Folding the third into `''`* would let a wedged git, a timeout, or an unreadable repo report a branch thatdiff --git a/server/lib/buildIdentity.js b/server/lib/buildIdentity.jsindex 2794e5384f..57e9d68541 100644--- a/server/lib/buildIdentity.js+++ b/server/lib/buildIdentity.js@@ -22,7 +22,7 @@** Privacy: commit / branch / dirty only. No absolute paths (they embed the OS* username), no hostname, no checkout directory — see the Sensitive Data- * section of the root CLAUDE.md. Deliberately no timestamp either: "how long+ * section of the root AGENTS.md. Deliberately no timestamp either: "how long* has this process been up" is already `system.uptime` on the health payload,* and a second spelling of it here would drift (uptime is recomputed per* request; this tuple is frozen at first read).@@ -79,7 +79,7 @@ export function parsePorcelainV2(stdout) {const value = line.slice('# branch.oid '.length).trim();// Empty stays null rather than becoming '': an empty-string commit// compares unequal to every real commit and would report a permanent- // false mismatch downstream (root CLAUDE.md's absent-vs-empty rule).+ // false mismatch downstream (root AGENTS.md's absent-vs-empty rule).if (value && value !== NO_COMMIT) commit = value;} else if (line.startsWith('# branch.head ')) {const value = line.slice('# branch.head '.length).trim();diff --git a/server/lib/childProcess.guards.test.js b/server/lib/childProcess.guards.test.jsindex 0a3d783dc3..9f1c7ec69f 100644--- a/server/lib/childProcess.guards.test.js+++ b/server/lib/childProcess.guards.test.js@@ -17,7 +17,7 @@ const WRAPPER = 'lib/childProcess.js';// Trees that cannot import the wrapper, and so are held to the weaker// per-call-site rule instead. `aiToolkit/` is vendored and contractually-// self-contained (aiToolkit/CLAUDE.md: no imports out to other PortOS modules).+// self-contained (aiToolkit/AGENTS.md: no imports out to other PortOS modules).// `autofixer/` and `browser/` are separate packages with their own// package.json — but they ARE PM2-forked apps (ecosystem.config.cjs), so they// sit in exactly the console-less blast radius this guard covers.diff --git a/server/lib/cliChildEnv.js b/server/lib/cliChildEnv.jsindex bed8593a26..6b929ee3f7 100644--- a/server/lib/cliChildEnv.js+++ b/server/lib/cliChildEnv.js@@ -35,7 +35,7 @@* shapes differ too much (child_process vs node-pty vs an HTTP hand-off to the* CoS runner, stdio variants, kill-tree wiring) to fold in the same change.* `lib/aiToolkit/runner.js` is also out of scope: it is vendored and must not- * import out to other PortOS modules (see `lib/aiToolkit/CLAUDE.md`), and its+ * import out to other PortOS modules (see `lib/aiToolkit/AGENTS.md`), and its* spawn is dormant under PortOS's `setCliRunner` override, so it keeps its* inline copy.*/diff --git a/server/lib/collectionStore.js b/server/lib/collectionStore.jsindex f3d73000f8..186d01e784 100644--- a/server/lib/collectionStore.js+++ b/server/lib/collectionStore.js@@ -297,7 +297,7 @@ export function createCollectionStore({* corrupt record in an otherwise-readable collection. Callers that reason over* the whole set (merge-rate stats, adoption reports) need to distinguish* "N records" from "N-of-M records, K corrupt" so a silent undercount can't- * masquerade as complete truth — the same sentinel-vs-empty rule the CLAUDE.md+ * masquerade as complete truth — the same sentinel-vs-empty rule the AGENTS.md* conventions call out. Mirrors the `loadAll`/`listOutcomesResult` precedent.** @returns {Promise<{ records: any[], failedIds: string[] }>}diff --git a/server/lib/commandSecurity.js b/server/lib/commandSecurity.jsindex d971965a1f..91b993075b 100644--- a/server/lib/commandSecurity.js+++ b/server/lib/commandSecurity.js@@ -55,7 +55,7 @@ export const PM2_BLOCKED_SUBCOMMANDS = new Set(['kill', 'startup', 'unstartup'])// Daemon-wide verbs that are fine against a single named process but catastrophic// with the `all` target (`pm2 stop all`, `pm2 delete all`, `pm2 restart all` —-// the unscoped form the user's CLAUDE.md explicitly forbids). Blocked only when+// the unscoped form the user's AGENTS.md explicitly forbids). Blocked only when// the target is `all`.export const PM2_ALL_TARGET_VERBS = new Set(['stop', 'delete', 'del', 'restart', 'reload', 'gracefulreload', 'scale',diff --git a/server/lib/cosTaskPrompt.js b/server/lib/cosTaskPrompt.jsindex 36aa237591..7ad8f28c49 100644--- a/server/lib/cosTaskPrompt.js+++ b/server/lib/cosTaskPrompt.js@@ -42,7 +42,7 @@ export const TASK_CONTEXT_KEY = 'context';* classified the other way by the migration.** Note `''` is NOT a prompt: an intentionally-cleared note stays a note (the- * absent-vs-present-but-empty rule in CLAUDE.md).+ * absent-vs-present-but-empty rule in AGENTS.md).*/export const isPromptPayload = (value) => typeof value === 'string' && value.includes('\n');diff --git a/server/lib/cosValidation.js b/server/lib/cosValidation.jsindex 58ad2169ff..f1827eb658 100644--- a/server/lib/cosValidation.js+++ b/server/lib/cosValidation.js@@ -1183,7 +1183,7 @@ const cosTaskDiagnosticsSchema = z.object({// Reasoning-effort override for effort-capable CLIs (claude/codex). On create,// '' from a form's "Default" option → undefined (no override persisted). On// update, ''/null must survive as null so the store's legacy-field normalizer-// deletes the pin (absent-vs-cleared, CLAUDE.md) — emptyToUndefined would drop+// deletes the pin (absent-vs-cleared, AGENTS.md) — emptyToUndefined would drop// the clear signal at the route's `!== undefined` gate and make a set effort// permanent through the API.const effortInputSchema = z.preprocess(emptyToUndefined, z.enum(EFFORT_LEVELS).optional());@@ -1191,7 +1191,7 @@ const effortUpdateSchema = z.preprocess(emptyToNull, z.enum(EFFORT_LEVELS).nulla// Federated instance this task is PINNED to (#4520) — only that instance's CoS// evaluator claims and runs it. On create, '' from the picker's "Any instance"// option → undefined (no pin persisted). On update, ''/null must survive as null-// so the route can clear an existing pin (absent-vs-cleared, CLAUDE.md).+// so the route can clear an existing pin (absent-vs-cleared, AGENTS.md).// Bounded-but-format-free on purpose: the id vocabulary is whatever the peers in// this install's registry advertise, and the route is what checks membership.const INSTANCE_ID_MAX_LENGTH = 128;diff --git a/server/lib/cosValidation.test.js b/server/lib/cosValidation.test.jsindex d9accaf561..c52590f603 100644--- a/server/lib/cosValidation.test.js+++ b/server/lib/cosValidation.test.js@@ -54,7 +54,7 @@ describe('cosValidation effort field', () => {});it("update: ''/null survive as null so the API can CLEAR a set effort pin", () => {- // absent-vs-cleared (CLAUDE.md): the route gates on `!== undefined`, and the+ // absent-vs-cleared (AGENTS.md): the route gates on `!== undefined`, and the// store's legacy-field normalizer deletes a null pin — so the clear signal// must reach the route as null, not be preprocessed away to undefined.expect(updateCosTaskSchema.parse({ effort: '' }).effort).toBeNull();diff --git a/server/lib/cudaCapability.js b/server/lib/cudaCapability.jsindex aa0f5c8a96..35fa250a8a 100644--- a/server/lib/cudaCapability.js+++ b/server/lib/cudaCapability.js@@ -7,7 +7,7 @@* (to decide between the CUDA and CPU torch wheels) — previously each had its own* `nvidia-smi` invocation and its own idea of what "no GPU" meant.*- * **Three outcomes, never two.** Per the CLAUDE.md sentinel rule, "the probe could+ * **Three outcomes, never two.** Per the AGENTS.md sentinel rule, "the probe could* not run" is NOT the same answer as "there is no GPU". The result carries a single* `status` (deliberately not a boolean, so there is no falsy value a caller can* accidentally read as "no GPU"):@@ -20,7 +20,7 @@* rather than lying about the hardware.** The probe is a subprocess boundary outside the request lifecycle, so every path- * resolves — nothing throws into a route (CLAUDE.md child-process exception).+ * resolves — nothing throws into a route (AGENTS.md child-process exception).*/import { execFile } from './childProcess.js';diff --git a/server/lib/digitalTwinValidation.js b/server/lib/digitalTwinValidation.jsindex bcd7352af5..432ca92a9d 100644--- a/server/lib/digitalTwinValidation.js+++ b/server/lib/digitalTwinValidation.js@@ -31,7 +31,9 @@ export const valuesTestResultEnum = z.enum(['aligned', 'partial', 'misaligned',export const adversarialTestResultEnum = z.enum(['held', 'partial', 'breached', 'pending']);// Export format enum-export const exportFormatEnum = z.enum(['system_prompt', 'claude_md', 'json', 'individual']);+// 'claude_md' is the pre-#4852 alias of 'agents_md' — kept so a persisted+// preference on an existing install still validates.+export const exportFormatEnum = z.enum(['system_prompt', 'agents_md', 'claude_md', 'json', 'individual']);// Enrichment category enumexport const enrichmentCategoryEnum = z.enum([diff --git a/server/lib/dispatchLabels.audit.test.js b/server/lib/dispatchLabels.audit.test.jsindex 589f33bfde..6aac709b34 100644--- a/server/lib/dispatchLabels.audit.test.js+++ b/server/lib/dispatchLabels.audit.test.js@@ -13,7 +13,7 @@ import { describe, expect, it } from 'vitest';const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..', '..');-const SCAN_ROOTS = ['server', 'CLAUDE.md', '.claude/skills'];+const SCAN_ROOTS = ['server', 'AGENTS.md', '.claude/skills'];const SKIP_DIR = new Set(['node_modules', 'data']);const SKIP_FILE = [/previousDefaults\.js$/,diff --git a/server/lib/fileUtils.js b/server/lib/fileUtils.jsindex 3212bed101..0c3513ab2a 100644--- a/server/lib/fileUtils.js+++ b/server/lib/fileUtils.js@@ -569,7 +569,7 @@ export async function tryReadFileStrict(filePath, encoding = 'utf8') {* rollout JSONL). `readFile` on one of those loads the whole thing into heap;* this reads only the trailing window.*- * Non-throwing, with the sentinel distinction the CLAUDE.md rule demands:+ * Non-throwing, with the sentinel distinction the AGENTS.md rule demands:* - missing / unopenable / read error → `null`* - zero-byte file → `''`* so a caller can tell "nothing to read" from "couldn't read".@@ -687,7 +687,7 @@ async function readWithSwapRetry(filePath, encoding = 'utf-8') {* Read a JSON file, reporting whether the read is TRUSTWORTHY rather than* collapsing every failure into the default (the `readJSONFile` behavior below).*- * The absent-vs-unreadable distinction (see CLAUDE.md's "Sentinel + validate"):+ * The absent-vs-unreadable distinction (see AGENTS.md's "Sentinel + validate"):** - ENOENT (never written) → `{ ok: true, value: defaultValue }` — a genuine* empty. A caller counting records may trust this as a real zero.@@ -950,7 +950,7 @@ export async function writeJSONLines(filePath, values) {* assignment. For read-modify-write, use `mutate(fn)` — it runs the whole* `load → fn → persist` cycle under the same tail, so a `load` always sees the* previous cycle's committed result and one writer can't clobber the other- * (CLAUDE.md: "serialize writes server-side… a single tail per shared file").+ * (AGENTS.md: "serialize writes server-side… a single tail per shared file").* A bare `load()` + `save()` pair does NOT get that guarantee; reach for* `mutate()` whenever the new value depends on the current one.*/@@ -1619,7 +1619,7 @@ export function isPathInsideDir(dir, candidatePath) {* and flow into ffmpeg / image-gen as an "image path" where it'd fail in* confusing ways). Note: `statSync` follows symlinks, so a symlink under* the root pointing to a regular file outside still passes. PortOS is- * single-user (see CLAUDE.md "Security Model") so we accept that — for+ * single-user (see AGENTS.md "Security Model") so we accept that — for* symlink rejection, swap to `lstatSync`.** Pass `{ mustExist: false }` at call time for code paths that intentionallydiff --git a/server/lib/fileWriteQueue.js b/server/lib/fileWriteQueue.jsindex a36893d1c0..b32a4c27fe 100644--- a/server/lib/fileWriteQueue.js+++ b/server/lib/fileWriteQueue.js@@ -8,7 +8,7 @@ import { createKeyCachedQueue } from './createKeyCachedQueue.js';* mediaCollections, universeBuilder, …) needs the same guarantee: a* `readState → modify → writeState` cycle must not interleave with another* cycle on the same file, or one writer's pre-image read overwrites the- * other's just-persisted record. CLAUDE.md: "Async PATCH races on shared+ * other's just-persisted record. AGENTS.md: "Async PATCH races on shared* records — serialize writes server-side… collapse the queue to a single* tail per shared file."*diff --git a/server/lib/gitCommitProbe.js b/server/lib/gitCommitProbe.jsindex 8d88b6e041..b7024b8bc7 100644--- a/server/lib/gitCommitProbe.js+++ b/server/lib/gitCommitProbe.js@@ -4,7 +4,7 @@** It replaced the `[task-<id>]` commit-marker grep that used to live in* `agentRunTracking.js`: nothing in PortOS ever emitted that marker (the root- * CLAUDE.md requires human-readable commit subjects, so stamping an opaque task+ * AGENTS.md requires human-readable commit subjects, so stamping an opaque task* id into every permanent commit was never an option), so the criterion was* unsatisfiable and scored every ordinary code-editing run a failure.*diff --git a/server/lib/gitOutputParsers.js b/server/lib/gitOutputParsers.jsindex 5ca9ec2afd..5db5df7dc5 100644--- a/server/lib/gitOutputParsers.js+++ b/server/lib/gitOutputParsers.js@@ -209,7 +209,7 @@ function sameObject(a, b) {* a busy repo (agents pushing branches) every attempt can lose the same race and* surface a red error for a fetch that actually succeeded. Callers treat a true* return as success instead. Distinguishing "already applied by another writer"- * from "failed" is the sentinel-and-validate rule in CLAUDE.md.+ * from "failed" is the sentinel-and-validate rule in AGENTS.md.** Deliberately strict — it returns false, leaving the existing retry/throw path* in charge, when:diff --git a/server/lib/imageFrameStats.js b/server/lib/imageFrameStats.jsindex e43fd823f7..01fa9a333b 100644--- a/server/lib/imageFrameStats.js+++ b/server/lib/imageFrameStats.js@@ -21,7 +21,7 @@* far under anything an encoder can represent as signal precisely so that a* real frame can never trip them.*- * 2. **Sentinel correctness** (root CLAUDE.md): "could not compute stats" must+ * 2. **Sentinel correctness** (root AGENTS.md): "could not compute stats" must* NOT collapse into "degenerate". `ok` is three-valued —* `true` = measured, has content* `false` = measured, degenerate (`reason` names which)diff --git a/server/lib/index.js b/server/lib/index.jsindex 5caeb739a9..a8d756b36d 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -8,7 +8,7 @@// MAINTENANCE RULE: any new module added to server/lib/ MUST be re-exported// here AND get a one-line entry in README.md. The same rule applies to// client/src/lib/, client/src/hooks/, and client/src/services/. See-// CLAUDE.md "Module organization" for the full convention.+// AGENTS.md "Module organization" for the full convention.// === Validation (Zod schemas + validators) ===// Domain-prefixed validators are namespace-exported so generic names that@@ -184,6 +184,7 @@ export * from './conflictJournal.js';export * from './createKeyCachedQueue.js';export * from './createNewestWinsGuard.js';export * from './dataRoot.js';+export * from './agentInstructionsFile.js';export * from './fileUtils.js';export * from './fileWriteQueue.js';export * from './icloudFile.js';diff --git a/server/lib/index.test.js b/server/lib/index.test.jsindex 1e990f3143..a88cbf97f4 100644--- a/server/lib/index.test.js+++ b/server/lib/index.test.js@@ -15,7 +15,7 @@ const sourceFiles = readdirSync(HERE)// `server/lib/`. If a `export * from './foo.js'` line points to a non-existent// module, the `import * as barrel` above throws — and so does this test. The// catalog-parity test below catches the inverse drift: a file added without-// a README row. Both halves keep the discovery contract in CLAUDE.md honest.+// a README row. Both halves keep the discovery contract in AGENTS.md honest.describe('server/lib/ barrel', () => {it('re-exports every non-test .js file from index.js', () => {diff --git a/server/lib/localModelTuning.js b/server/lib/localModelTuning.jsindex 8537ba24cc..dff5f18ca6 100644--- a/server/lib/localModelTuning.js+++ b/server/lib/localModelTuning.js@@ -352,7 +352,7 @@ export const DEFAULT_TUNING_GRID_VARIANTS = 6;** The returned length IS the run count, so a caller can name it in a consent* gate before anything starts — which the AI Provider Usage Policy (root- * CLAUDE.md) requires of any batch of provider calls. `maxVariants` truncates in+ * AGENTS.md) requires of any batch of provider calls. `maxVariants` truncates in* catalog order; nothing here reports the grid as exhaustive. It is an* in-process option only — there is no wire path that shrinks the grid, because* a request that could would run a different count than consent named.diff --git a/server/lib/navManifest.js b/server/lib/navManifest.jsindex cc137fa32e..fc890b1b11 100644--- a/server/lib/navManifest.js+++ b/server/lib/navManifest.js@@ -1,7 +1,7 @@// Single source of truth for PortOS navigation. Consumed by// server/services/voice/tools.js#ui_navigate and the Cmd+K palette.// Entry: { id, path, label, section, aliases?, keywords?, previousPaths? }.-// See CLAUDE.md "Command Palette & Voice Nav" for the contract.+// See AGENTS.md "Command Palette & Voice Nav" for the contract.//// `previousPaths` lists every path this page has ANSWERED TO BEFORE — including// its parameterized drill-downs, written with the OLD route's param name (thediff --git a/server/lib/pgFileFacade.js b/server/lib/pgFileFacade.jsindex d4a8109b4a..89aafeabf3 100644--- a/server/lib/pgFileFacade.js+++ b/server/lib/pgFileFacade.js@@ -24,7 +24,7 @@ import { checkHealth, ensureSchema } from './db.js';/*** True when the file/escape-hatch backend should be used instead of PostgreSQL.- * Dev/test only — see the Storage backend policy in CLAUDE.md.+ * Dev/test only — see the Storage backend policy in AGENTS.md.*/export function isFileBackend() {return process.env.MEMORY_BACKEND === 'file' || process.env.NODE_ENV === 'test';diff --git a/server/lib/postValidation.js b/server/lib/postValidation.jsindex 8c0917ad38..ddf7243683 100644--- a/server/lib/postValidation.js+++ b/server/lib/postValidation.js@@ -414,7 +414,7 @@ export const postConfigUpdateSchema = z.object({// "HH:MM" string interpreted in the user's configured timezone. The native// <input type="time"> can be cleared to '' by the user; treat that as// "no change" (absent) rather than a validation failure that would reject- // the whole config PUT — same UI-sentinel-tolerance pattern CLAUDE.md+ // the whole config PUT — same UI-sentinel-tolerance pattern AGENTS.md// documents for CLI provider endpoints.reminder: z.object({enabled: z.boolean().optional(),diff --git a/server/lib/providerModels.js b/server/lib/providerModels.jsindex 4e421105e5..557fa23af8 100644--- a/server/lib/providerModels.js+++ b/server/lib/providerModels.js@@ -104,7 +104,7 @@ export const CURSOR_EFFORT_LEVELS = Object.freeze(['low', 'medium', 'high', 'xhi// Effort values no CLI ladder accepts any more, kept ACCEPTED as stored/API// input so records saved under an older ladder still validate after an install-// updates (see the distribution model in CLAUDE.md — installs update+// updates (see the distribution model in AGENTS.md — installs update// independently). `resolveCliEffort` clamps them to a level the target CLI// really takes, so none of these ever reaches a CLI verbatim.const LEGACY_EFFORT_LEVELS = Object.freeze(['ultra']);@@ -834,7 +834,7 @@ export function isClaudeCommand(command) {* True for an Ollama-backed provider that launches the Claude Code binary* (`claude-ollama` / `claude-ollama-tui`). These sessions run a small local* model that drowns in Claude Code's full personal environment — hooks,- * plugins, MCP servers, global CLAUDE.md — so the spawners put them in lean+ * plugins, MCP servers, the global ~/.claude/CLAUDE.md — so the spawners put them in lean* mode (see `applyLeanClaudeArgs`). Keyed on the `ollamaBacked` marker + the* launch command, not provider ids, so renamed/custom local providers get the* same treatment.@@ -864,7 +864,7 @@ export function providerSuppliesGithubToken(provider) {/*** Lean-context flags for local-model Claude Code sessions:- * - `--bare` — skip hooks, plugin sync, auto-memory, and CLAUDE.md+ * - `--bare` — skip hooks, plugin sync, auto-memory, and AGENTS.md* auto-discovery (the user's personal environment derails small models).* - `--strict-mcp-config` — with no `--mcp-config` given, load zero MCP* servers (their tool schemas alone can blow a small Ollama context).diff --git a/server/lib/providerTranscriptUsage.test.js b/server/lib/providerTranscriptUsage.test.jsindex 838ba07092..cf0ecec241 100644--- a/server/lib/providerTranscriptUsage.test.js+++ b/server/lib/providerTranscriptUsage.test.js@@ -9,7 +9,7 @@ import {// Fixtures are hand-authored to match the real formats (verified against a live// install) with invented paths/ids — never a transcribed real record, per the-// Sensitive Data rules in CLAUDE.md.+// Sensitive Data rules in AGENTS.md.const claudeLine = (overrides = {}) => JSON.stringify({type: 'assistant',diff --git a/server/lib/quotaBurnPresets.js b/server/lib/quotaBurnPresets.jsindex 2c7d291a5d..43cac8017a 100644--- a/server/lib/quotaBurnPresets.js+++ b/server/lib/quotaBurnPresets.js@@ -15,6 +15,14 @@* on any install and there is no migration to write — the cost is that an* improved prompt reaches existing jobs only when the user re-picks the preset.*+ * ONE exception exists: #4852 renamed the agent-instructions file this contract+ * tells the agent to read, and a stored job naming CLAUDE.md but not AGENTS.md+ * would send an agent to a file its target repo may no longer have. Migration+ * 294 rewrites those job prompts — but ONLY where the stored string is byte-for-byte+ * a prior unmodified render, which is the same 'unmodified default ⇒ safe to+ * upgrade' rule PREVIOUS_DEFAULT_PROMPTS uses. Any future preset edit that must+ * reach existing jobs needs the same treatment.+ ** Pure module: strings only, no I/O. `routes/quotaBurn.js` serves the list in* the config catalog; the client's preset picker applies one to a job row.*/@@ -118,10 +126,10 @@ token from the local keyring:\`curl -sS -H "Authorization: Bearer $TOK" -H "Accept: application/vnd.github+json" -d @"$BODY" https://api.github.com/repos/<owner>/<repo>/issues\`.A window spent finding real problems and filing none is a wasted window.-Read this repository's \`CLAUDE.md\` (and any nested per-directory ones covering-the slice) before you start, and honor its conventions and its explicitly-declared non-issues — a finding that contradicts a documented project decision-is noise, not a bug.`.trim();+Read this repository's \`AGENTS.md\` (or \`CLAUDE.md\`, and any nested+per-directory ones covering the slice) before you start, and honor its+conventions and its explicitly declared non-issues — a finding that contradicts+a documented project decision is noise, not a bug.`.trim();const auditPreset = ({ id, label, summary, labels, dedupeSearch, mission }) => Object.freeze({id,diff --git a/server/lib/repoIntakeActions.mirror.test.js b/server/lib/repoIntakeActions.mirror.test.jsindex 1f01b666da..e5b6bafd83 100644--- a/server/lib/repoIntakeActions.mirror.test.js+++ b/server/lib/repoIntakeActions.mirror.test.js@@ -20,7 +20,7 @@ const __dirname = dirname(fileURLToPath(import.meta.url));const CLIENT_PATH = resolve(__dirname, '../../client/src/components/brain/RepoIntakeOptions.jsx');// The client table is a .jsx module importing lucide-react, so a server-env-// suite can't import it (see the CI note in CLAUDE.md about server tests pulling+// suite can't import it (see the CI note in AGENTS.md about server tests pulling// client deps). Read the `key:` entries out of the REPO_INTAKE_OPTIONS literal.const clientKeys = () => {const src = readFileSync(CLIENT_PATH, 'utf8');diff --git a/server/lib/roundsValidation.js b/server/lib/roundsValidation.jsindex 050d31998c..9e0f8d89f2 100644--- a/server/lib/roundsValidation.js+++ b/server/lib/roundsValidation.js@@ -60,7 +60,7 @@ export const PROGRESS_SCOPES_MAX = 80; // distinct training scopes trackedexport const RECORDING_GRADES = ['in-tune', 'close', 'off', 'missed', 'pending'];// Trim a string field, returning '' for non-strings. Mirrors the-// absent-vs-empty rule in CLAUDE.md: callers decide whether '' clears.+// absent-vs-empty rule in AGENTS.md: callers decide whether '' clears.const trimField = (v, max) => (typeof v === 'string' ? v.trim().slice(0, max) : '');// Clamp an integer tempo into the supported band; null when unparseable so adiff --git a/server/lib/shotGrammar.js b/server/lib/shotGrammar.jsindex ef80b0204b..95edda8e81 100644--- a/server/lib/shotGrammar.js+++ b/server/lib/shotGrammar.js@@ -13,7 +13,7 @@** Both fields default to null ("not captured") everywhere so an older outline or* a shot the extractor didn't tag is treated as ABSENT (skipped by the continuity- * check) rather than mis-classified — the absent-vs-empty rule from CLAUDE.md.+ * check) rather than mis-classified — the absent-vs-empty rule from AGENTS.md.*/// Camera framing / size. Ordered loosely widest→tightest; the continuity checkdiff --git a/server/lib/singleFlight.js b/server/lib/singleFlight.jsindex 1c0a64963e..1a25710d2c 100644--- a/server/lib/singleFlight.js+++ b/server/lib/singleFlight.js@@ -12,7 +12,7 @@* in-flight-coalescing sites deliberately do NOT use this helper:* - It does NOT layer a TTL / result cache on top. `aiToolkit/providers.js`* keeps its own self-contained TTL-cache-then-coalesce logic — the vendored- * toolkit must not import PortOS-side lib modules (CLAUDE.md), so it can't+ * toolkit must not import PortOS-side lib modules (AGENTS.md), so it can't* build on this even if it wanted the bare coalesce.* - It does NOT reject concurrent callers. `sseDownload.js` deliberately uses* the opposite "reject-if-busy" idiom (a second client can't share onediff --git a/server/lib/spawnCwd.js b/server/lib/spawnCwd.jsindex 13c91fb92d..1f86a50ea8 100644--- a/server/lib/spawnCwd.js+++ b/server/lib/spawnCwd.js@@ -35,8 +35,8 @@ import { expandHome } from './fileUtils.js';* Creative Director treatment/plan/evaluate tasks are HTTP-PATCH deliverables* (`noCodeOutput`) and never asked for a worktree. Spawning them with* `cwd = PATHS.root` lets Claude Code / Codex natively discover the PortOS- * repo's CLAUDE.md files — the same dev-convention bloat the API path already- * skips via `skipClaudeMd`. A per-agent scratch dir with no CLAUDE.md in its+ * repo's AGENTS.md files — the same dev-convention bloat the API path already+ * skips via `skipClaudeMd`. A per-agent scratch dir with no AGENTS.md in its* tree is the provider-agnostic fix (#4650).** `useWorktree: true` keeps the worktree: an explicit isolation request still@@ -52,7 +52,7 @@ export function usesCreativeDirectorScratchCwd(task) {* Isolated cwd for a CD-marked CLI/TUI run. Lives under the OS temp dir — NOT* under the PortOS checkout (`data/cos/agents` is still inside the git tree,* so Claude Code / Codex walking parent directories would still find the repo- * CLAUDE.md). `agentId` is required — a missing id would collapse every CD run+ * AGENTS.md). `agentId` is required — a missing id would collapse every CD run* onto one shared folder.*/export function creativeDirectorScratchCwd(agentId) {diff --git a/server/lib/spawnCwd.test.js b/server/lib/spawnCwd.test.jsindex 6e935ad801..bd98e5f8fe 100644--- a/server/lib/spawnCwd.test.js+++ b/server/lib/spawnCwd.test.js@@ -154,8 +154,8 @@ describe('Creative Director scratch cwd (#4650)', () => {const cwd = creativeDirectorScratchCwd('agent-cd-1');expect(cwd).toBe(join(tmpdir(), 'portos-cd-cwd', 'agent-cd-1'));expect(cwd).not.toBe(PATHS.root);- // Native CLAUDE.md discovery walks parents to the git root. A path under- // the checkout (including gitignored data/) would still leak repo CLAUDE.md.+ // Native AGENTS.md discovery walks parents to the git root. A path under+ // the checkout (including gitignored data/) would still leak repo AGENTS.md.expect(cwd.startsWith(`${PATHS.root}/`)).toBe(false);expect(cwd.startsWith(PATHS.root + '\\')).toBe(false);});diff --git a/server/lib/storyArc.test.js b/server/lib/storyArc.test.jsindex 1107c84867..5bb5115a4e 100644--- a/server/lib/storyArc.test.js+++ b/server/lib/storyArc.test.js@@ -461,7 +461,7 @@ describe('storyArc — Vonnegut shape catalog', () => {// Lock the server-side `points` arrays to the client's `STORY_SHAPES`// definitions so the sparkline and the prompt guidance stay in sync.- // (CLAUDE.md: "Keep `points` arrays in sync with client/.../StoryShapes.jsx".)+ // (AGENTS.md: "Keep `points` arrays in sync with client/.../StoryShapes.jsx".)it('points arrays match the client-side STORY_SHAPES curves', () => {const CLIENT_POINTS = {'rags-to-riches': [-1, -0.7, -0.4, -0.1, 0.3, 0.7, 1],diff --git a/server/lib/storyboardScenes.js b/server/lib/storyboardScenes.jsindex 6f0298195b..24beff74b2 100644--- a/server/lib/storyboardScenes.js+++ b/server/lib/storyboardScenes.js@@ -126,7 +126,7 @@ export function ensureStoryboardIds(scenes) {export function resolveStoryboardTarget(list, { id = null, index = null } = {}) {const arr = Array.isArray(list) ? list : [];// `Number(null)` / `Number('')` are 0 — an absent index must NOT read as- // "index 0" (CLAUDE.md sentinel discipline), so coerce only real numerics.+ // "index 0" (AGENTS.md sentinel discipline), so coerce only real numerics.const idx = index === null || index === undefined || index === '' ? NaN : Number(index);const hasIndex = Number.isInteger(idx) && idx >= 0;if (isNonEmptyStr(id)) {diff --git a/server/lib/streamingSpawn.js b/server/lib/streamingSpawn.jsindex 9604d655b2..825aba0dba 100644--- a/server/lib/streamingSpawn.js+++ b/server/lib/streamingSpawn.js@@ -91,7 +91,7 @@ export function runStreamingCommand(cmd, args, onLine, { timeoutMs = 0, cwd, env//// The callback runs outside the Express request lifecycle, so a throwing// `isCancelled` would take the process down with no `next(err)` to bubble to- // (see the try/catch exception in CLAUDE.md). A predicate that cannot be+ // (see the try/catch exception in AGENTS.md). A predicate that cannot be// asked is treated as "not cancelled" — the timeout still bounds the run.const cancelTimer = typeof isCancelled === 'function'? setInterval(() => {diff --git a/server/lib/styleGuide.js b/server/lib/styleGuide.jsindex 47097302fa..e9f8b726a3 100644--- a/server/lib/styleGuide.js+++ b/server/lib/styleGuide.js@@ -97,7 +97,7 @@ const enumOrNull = (raw, allowed) => (allowed.includes(raw) ? raw : null);// Tri-state boolean: only `true`/`false` count as a set value — anything else is// "unspecified" (absent), so an LLM that omits a convention can't silently flip-// it off (matches the absent-vs-empty rule in CLAUDE.md).+// it off (matches the absent-vs-empty rule in AGENTS.md).const optBool = (raw) => (typeof raw === 'boolean' ? raw : null);// Target grade level. Finite → clamped to [1,18]; otherwise null (unspecified)diff --git a/server/lib/subscriptionSavings.js b/server/lib/subscriptionSavings.jsindex 14fa7aaf70..8efd305f9c 100644--- a/server/lib/subscriptionSavings.js+++ b/server/lib/subscriptionSavings.js@@ -63,7 +63,7 @@ export function prorateMonthlyCost(monthlyCost, days) {* Percent of the API bill a subscription avoided, or null when there is no API* bill to compare against. Null rather than 0 or 100 on purpose: "we cannot* express this as a percentage" is not "you saved nothing" (see the- * sentinel-vs-empty convention in CLAUDE.md), and a UI that prints 0% for an+ * sentinel-vs-empty convention in AGENTS.md), and a UI that prints 0% for an* unused-but-paid-for plan is stating a falsehood about the plan.*/export function savingsPercent(apiCost, savings) {diff --git a/server/routes/apps/documents.js b/server/routes/apps/documents.jsindex 24ec34ff7f..598d469c8e 100644--- a/server/routes/apps/documents.js+++ b/server/routes/apps/documents.js@@ -18,7 +18,9 @@ import { loadApp, pathExists } from './shared.js';const router = Router();-const ALLOWED_DOCUMENTS = ['PLAN.md', 'CLAUDE.md', 'GOALS.md', 'REVIEW.md', 'REJECTED.md'];+// Both agent-instruction names are listed (#4852): AGENTS.md is canonical, while a+// managed app's CLAUDE.md is either its one-line AGENTS.md bridge or its only file.+const ALLOWED_DOCUMENTS = ['PLAN.md', 'AGENTS.md', 'CLAUDE.md', 'GOALS.md', 'REVIEW.md', 'REJECTED.md'];// GET /api/apps/:id/documents - List which documents existrouter.get('/:id/documents', loadApp, asyncHandler(async (req, res) => {diff --git a/server/routes/cosTaskRoutes.js b/server/routes/cosTaskRoutes.jsindex f8204ec3f6..85708db2da 100644--- a/server/routes/cosTaskRoutes.js+++ b/server/routes/cosTaskRoutes.js@@ -338,7 +338,7 @@ router.put('/tasks/:id', asyncHandler(async (req, res) => {// is the explicit clear the schema preserves — it lands as `undefined` in the// metadata patch, which the store's undefined-stripping turns into a real key// removal, restoring opportunistic first-claim-wins. Absent leaves the pin- // untouched (absent-vs-cleared, CLAUDE.md).+ // untouched (absent-vs-cleared, AGENTS.md).if (fields.targetInstanceId !== undefined) {if (fields.targetInstanceId !== null) await assertAssignableInstance(fields.targetInstanceId);updates.metadata = { ...updates.metadata, targetInstanceId: fields.targetInstanceId ?? undefined };diff --git a/server/routes/detect.js b/server/routes/detect.jsindex 4230ee9f2d..b97c6d0513 100644--- a/server/routes/detect.js+++ b/server/routes/detect.js@@ -19,7 +19,7 @@ const router = Router();// path and reads a small set of well-known project files under it (package.json// scripts + name, project.yml, vite.config, and PORT/VITE_PORT lines from .env),// returning their values verbatim. This is INTENTIONAL: PortOS is a single-user-// app on a private Tailscale network (see CLAUDE.md "Security Model"), where the+// app on a private Tailscale network (see AGENTS.md "Security Model"), where the// sole operator legitimately points the "import a repo" flow at any directory on// their own machine — there is no second user to read data from, so no path// confinement is required for safety.diff --git a/server/routes/imageGenSetup.js b/server/routes/imageGenSetup.jsindex a6e948f203..c7d8666822 100644--- a/server/routes/imageGenSetup.js+++ b/server/routes/imageGenSetup.js@@ -127,7 +127,7 @@ router.get('/hf-token-status', asyncHandler(async (_req, res) => {}));// Save the HF token from the inline form on the Image Gen page. settings.json-// is the canonical location (single-user app behind Tailscale — see CLAUDE.md).+// is the canonical location (single-user app behind Tailscale — see AGENTS.md).// Same endpoint serves FLUX.2 and legacy mflux gated models — the token is// global (HF_TOKEN env in spawn).const hfTokenSchema = z.object({diff --git a/server/routes/imageTo3d.js b/server/routes/imageTo3d.jsindex 9ef236621a..aeea3a6cc6 100644--- a/server/routes/imageTo3d.js+++ b/server/routes/imageTo3d.js@@ -84,7 +84,7 @@ router.get('/targets', asyncHandler(async (_req, res) => {* `complete` / `error`) while the target's adapter installs. Gated on hardware* support and single-flighted per target; killed if the client navigates away.* Only fires the real install on this explicit user request — never from boot- * (CLAUDE.md no-cold-bootstrap policy). Mirrors imageGenSetup.js's `/flux2-install`.+ * (AGENTS.md no-cold-bootstrap policy). Mirrors imageGenSetup.js's `/flux2-install`.*/async function handleTargetInstall(targetId, req, res) {const { send, safeEnd } = openSseStream(res);diff --git a/server/routes/localLlm.js b/server/routes/localLlm.jsindex 26464aa97e..96c299b2aa 100644--- a/server/routes/localLlm.js+++ b/server/routes/localLlm.js@@ -466,7 +466,7 @@ router.post('/compare', asyncHandler(async (req, res) => {// endpoints back the measured alternative: run a model at several context sizes// and rank installed models on the evidence.//-// The read/run split is the AI Provider Usage Policy boundary (root CLAUDE.md):+// The read/run split is the AI Provider Usage Policy boundary (root AGENTS.md):// GET touches disk only and is safe to poll; POST /run is the ONLY path that// reaches a provider, and it fires solely from a deliberate user action whose// UI names the backend, model, and run count first. Do not add a boot hook, adiff --git a/server/routes/scaffoldIOS.js b/server/routes/scaffoldIOS.jsindex 281392c552..ad6b664a49 100644--- a/server/routes/scaffoldIOS.js+++ b/server/routes/scaffoldIOS.js@@ -3,6 +3,7 @@ import { join } from 'path';import { promisify } from 'util';import { exec } from '../lib/childProcess.js';import { ensureDir, ensureDirs } from '../lib/fileUtils.js';+import { writeAgentInstructions } from '../lib/agentInstructionsFile.js';import {XCODE_TEAM_ID, XCODE_BUNDLE_PREFIX, XCODE_ENV_EXAMPLE,generateDeployScript, toBundleId, toTargetName,@@ -157,8 +158,8 @@ final class ${targetName}Tests: XCTestCase {await writeFile(deployPath, generateDeployScript(targetName, bundleId));if (process.platform !== 'win32') await chmod(deployPath, 0o755);- // CLAUDE.md- await writeFile(join(repoPath, 'CLAUDE.md'), `# ${name}+ // AGENTS.md (+ the Claude Code bridge)+ await writeAgentInstructions(repoPath, `# ${name}iOS native app built with SwiftUI and XcodeGen.diff --git a/server/routes/scaffoldPortOS.js b/server/routes/scaffoldPortOS.jsindex 11a4ec9b72..3aa3eef794 100644--- a/server/routes/scaffoldPortOS.js+++ b/server/routes/scaffoldPortOS.js@@ -1,6 +1,7 @@import { writeFile } from 'fs/promises';import { join } from 'path';import { atomicWrite, ensureDir, ensureDirs } from '../lib/fileUtils.js';+import { writeAgentInstructions } from '../lib/agentInstructionsFile.js';// Inline CORS middleware snippet for generated projects (no cors package dependency)const CORS_SNIPPET = `app.use((req, res, next) => {@@ -569,10 +570,10 @@ jobs:addStep('Create GitHub Actions', 'done');- // === CLAUDE.md ===- await writeFile(join(repoPath, 'CLAUDE.md'), `# CLAUDE.md+ // === AGENTS.md (+ the Claude Code bridge) ===+ await writeAgentInstructions(repoPath, `# AGENTS.md-This file provides guidance to Claude Code when working with code in this repository.+This file provides guidance to AI coding agents working with code in this repository.## Commandsdiff --git a/server/routes/scaffoldXcode.js b/server/routes/scaffoldXcode.jsindex 54c8708faf..c24fe06289 100644--- a/server/routes/scaffoldXcode.js+++ b/server/routes/scaffoldXcode.js@@ -3,6 +3,7 @@ import { join } from 'path';import { exec } from '../lib/childProcess.js';import { promisify } from 'util';import { ensureDir, ensureDirs } from '../lib/fileUtils.js';+import { writeAgentInstructions } from '../lib/agentInstructionsFile.js';import {XCODE_TEAM_ID, XCODE_BUNDLE_PREFIX, XCODE_ENV_EXAMPLE,toBundleId, toTargetName,@@ -386,8 +387,8 @@ final class ScreenshotTests: XCTestCase {]);}- // CLAUDE.md- await writeFile(join(repoPath, 'CLAUDE.md'), `# ${name}+ // AGENTS.md (+ the Claude Code bridge)+ await writeAgentInstructions(repoPath, `# ${name}Multi-platform native app built with SwiftUI (iOS + macOS + watchOS) and XcodeGen.diff --git a/server/routes/systemHealth.js b/server/routes/systemHealth.jsindex 61e64d2acf..ae60c339eb 100644--- a/server/routes/systemHealth.js+++ b/server/routes/systemHealth.js@@ -64,7 +64,7 @@ router.get('/processing', asyncHandler(async (req, res) => {* peer deliberately GET any /api/* path, as it can for every other endpoint on* this server. The point here is that the stamp is not PUSHED into a payload* that federates unprompted.- * See the root CLAUDE.md privacy rules and #4694 ("local-only diagnostic data+ * See the root AGENTS.md privacy rules and #4694 ("local-only diagnostic data* — must not join a sync payload"). `health.test.js` pins both halves.*/router.get('/build', asyncHandler(async (req, res) => {diff --git a/server/scripts/migrateCatalogPayload.js b/server/scripts/migrateCatalogPayload.jsindex 2c3dcb7823..c1a9bfd168 100644--- a/server/scripts/migrateCatalogPayload.js+++ b/server/scripts/migrateCatalogPayload.js@@ -14,7 +14,7 @@* which gates whether a peer push is even accepted; and* - the storage-LAYOUT version (Postgres tables) handled by `ensureSchema`.* This is the per-record payload-SHAPE version, mirroring the- * `data/{type}/index.json` `schemaVersion` convention documented in CLAUDE.md.+ * `data/{type}/index.json` `schemaVersion` convention documented in AGENTS.md.** Idempotency: a marker in `data/catalog-payload.applied.json` records the* highest registry payload version this install has fully migrated to, so thediff --git a/server/services/activityDigest.js b/server/services/activityDigest.jsindex 4e736783a5..02514b1743 100644--- a/server/services/activityDigest.js+++ b/server/services/activityDigest.js@@ -12,7 +12,7 @@* the template fed to the LLM.* 2. LLM narrative (opt-in). Only when a provider is configured in settings —* the config UI names the provider/model. See "AI Provider Usage Policy" in- * CLAUDE.md: the feature is silent until the user enables it, and the+ * AGENTS.md: the feature is silent until the user enables it, and the* scheduled run is a sanctioned automation the user set up.** The scheduler lives in activityDigestScheduler.js; the manual "draft todaydiff --git a/server/services/activityDigestScheduler.js b/server/services/activityDigestScheduler.jsindex 87e3f1c842..84c9280a48 100644--- a/server/services/activityDigestScheduler.js+++ b/server/services/activityDigestScheduler.js@@ -7,7 +7,7 @@** OFF by default: only runs when the user has enabled it in Settings →* Daily Log → Activity Digest (`enabled: true`). This is a sanctioned- * scheduled automation per CLAUDE.md's AI policy — the user opted in and the+ * scheduled automation per AGENTS.md's AI policy — the user opted in and the* config UI names the provider/model. Until then it is entirely silent (no* provider calls, no journal writes). The `enabled` flag + provider/model are* re-read every tick so toggling them takes effect without a restart.diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.jsindex d93ec4a5d4..d406d64deb 100644--- a/server/services/agentCliSpawning.js+++ b/server/services/agentCliSpawning.js@@ -342,7 +342,7 @@ export async function spawnDirectly({const fullCommand = `${cliConfig.command} ${cliConfig.args.join(' ')} <<< "${(task.description || '').substring(0, 100)}..."`;const ROOT_DIR = PATHS.root;- // CD no-worktree tasks get an isolated scratch cwd so native CLAUDE.md+ // CD no-worktree tasks get an isolated scratch cwd so native AGENTS.md// discovery cannot reach the PortOS repo tree (#4650). Everyone else keeps// workspacePath, falling back to the repo root when it was omitted.const cwd = resolveAgentCliCwd({ workspacePath, fallbackRoot: ROOT_DIR, task, agentId });diff --git a/server/services/agentErrorAnalysis.js b/server/services/agentErrorAnalysis.jsindex 6eb76164ed..b9f5f1212e 100644--- a/server/services/agentErrorAnalysis.js+++ b/server/services/agentErrorAnalysis.js@@ -40,7 +40,7 @@ const CONFIG_EXPECTED_MAX_CHARS = 120;// Machine-identity / network / PII fragments stripped before a captured failure// snippet (or any interpolated free text) lands in a human-facing — and possibly// federated — investigation task body. See the "Sensitive Data & Privacy" section-// in CLAUDE.md: the *shape* of the failure is what a human needs, never the live+// in AGENTS.md: the *shape* of the failure is what a human needs, never the live// hostnames, paths, addresses, or secrets pulled off the running instance.const SNIPPET_REDACTIONS = [// Home-dir paths that embed an OS username → strip the user segment only.@@ -128,7 +128,7 @@ export const ERROR_PATTERNS = [// 2026-08-17: `model_reasoning_effort = "max"`, a variant codex does not// accept, sitting in the global config). Deliberately does NOT echo the// matched path — it embeds the OS username (see Sensitive Data & Privacy in- // CLAUDE.md).+ // AGENTS.md).//// The rejected key can come from either side, and the fix text says which// (see `extract`): PortOS injects only PORTOS_CLI_CONFIG_KEYS via `-c`, sodiff --git a/server/services/agentErrorAnalysis.test.js b/server/services/agentErrorAnalysis.test.jsindex ae0caa712a..36fc262fd2 100644--- a/server/services/agentErrorAnalysis.test.js+++ b/server/services/agentErrorAnalysis.test.js@@ -125,7 +125,7 @@ describe('analyzeAgentFailure — ERROR_PATTERNS classification', () => {expect(analysis.message).toContain('max');expect(analysis.message).toContain('model_reasoning_effort');// The rejection line embeds the OS username in its path — it must never be- // echoed into a failure record (Sensitive Data & Privacy, CLAUDE.md).+ // echoed into a failure record (Sensitive Data & Privacy, AGENTS.md).expect(analysis.message).not.toContain('/home/x/');});diff --git a/server/services/agentFinalization.js b/server/services/agentFinalization.jsindex 9b27c447ee..959e3a699b 100644--- a/server/services/agentFinalization.js+++ b/server/services/agentFinalization.js@@ -72,7 +72,7 @@ export function releaseAgentLane({ agentId, success, duration, exitCode, executi** That probe replaced a task-id commit-marker grep in #3637. NOTHING ever* emitted that marker — no prompt, template, or slashdo command asked an agent- * to stamp a task id into a commit subject, and the root CLAUDE.md forbids+ * to stamp a task id into a commit subject, and the root AGENTS.md forbids* exactly that shape of subject line — so the criterion was unsatisfiable and* stamped `validationPassed: false` on every ordinary code-editing run,* poisoning the task-learning buckets it feeds.@@ -957,7 +957,7 @@ const TRANSCRIPT_RESCUE_TAIL_BYTES = 256 * 1024;*/async function rescueTranscriptPayload({ agentId, taskType }) {if (!agentId || !isProgrammaticIoTaskType(taskType)) return null;- // Sanctioned try/catch (see CLAUDE.md — this runs outside the request+ // Sanctioned try/catch (see AGENTS.md — this runs outside the request// lifecycle): a best-effort salvage must never be able to make the outcome// WORSE than not attempting it. A hook whose own shape predicate throws would// otherwise abort the dispatch and skip the hook entirely, turning "wediff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.jsindex 6ba5c68b17..ac9e724387 100644--- a/server/services/agentLifecycle.js+++ b/server/services/agentLifecycle.js@@ -402,7 +402,7 @@ async function runAgentSpawn(task) {// Lean mode: an Ollama-backed Claude session gets `--bare --strict-mcp-config`// (see applyLeanClaudeArgs) so the user's personal environment — hooks,- // plugins, MCP servers, global CLAUDE.md — doesn't drown the small local+ // plugins, MCP servers, the global ~/.claude/CLAUDE.md — doesn't drown the small local// model. This is orthogonal to the prompt split below.const leanMode = isOllamaClaudeProvider(provider);diff --git a/server/services/agentManagement.js b/server/services/agentManagement.jsindex 6a0fa6803e..b2c5db6189 100644--- a/server/services/agentManagement.js+++ b/server/services/agentManagement.js@@ -511,7 +511,7 @@ async function replacePausedTask({ agentId, task, taskType, overrides }) {/*** The dialog's edits as a task-metadata patch. Every field is "unchanged unless* supplied" — the dialog seeds its selects from the paused run, so a blank value- * is absence rather than an intentional clear (CLAUDE.md's absent-vs-empty rule).+ * is absence rather than an intentional clear (AGENTS.md's absent-vs-empty rule).* `context` APPENDS to `existingContext`: the task's own note is what the* original run was given, and dropping it would resume with less information than* the run that paused. It never touches `metadata.prompt` — the dialog edits thediff --git a/server/services/agentOrchestrator.js b/server/services/agentOrchestrator.jsindex b308901953..6e3ace3084 100644--- a/server/services/agentOrchestrator.js+++ b/server/services/agentOrchestrator.js@@ -55,7 +55,7 @@* `agentManagement.terminateAgent` runs the real signal sequence. That collision* is the most confusing thing in the cluster, so the facade renames the* request-side one to `requestAgentTermination` and lets the process-side one- * keep its name, symmetric with its sibling `killAgent`. CLAUDE.md resolves+ * keep its name, symmetric with its sibling `killAgent`. AGENTS.md resolves* same-name collisions with `export * as <namespace>`, but namespacing here* would spell the call `agentOrchestrator.agentManagement.terminateAgent` —* re-exposing the very leaf module the facade exists to hide — so this onediff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.jsindex a99c78c8ea..19eba68028 100644--- a/server/services/agentPromptBuilder.js+++ b/server/services/agentPromptBuilder.js@@ -1,7 +1,7 @@/*** Agent Prompt Builder*- * Builds the full agent prompt including memory context, CLAUDE.md instructions,+ * Builds the full agent prompt including memory context, AGENTS.md instructions,* digital twin, worktree/pipeline/JIRA sections, skill templates, and tools summary.* Also handles JIRA ticket creation and app workspace resolution.*/@@ -17,6 +17,7 @@ import { getActiveProvider } from './providers.js';import { runPromptThroughProvider } from '../lib/promptRunner.js';import { readJSONFile, PATHS, tryReadFile, expandHome } from '../lib/fileUtils.js';import { loadSlashdoFile, loadSlashdoLib, writeResolvedSlashdoBody } from '../lib/slashdoLoader.js';+import { AGENT_INSTRUCTIONS_FILENAME, CLAUDE_BRIDGE_FILENAME } from '../lib/agentInstructionsFile.js';import { DEFAULT_REVIEWER, DEFAULT_REVIEWERS, DEFAULT_REVIEW_STOP_MODE, LOCAL_LLM_REVIEWERS, MODEL_CAPABLE_CLI_REVIEWERS, describeReviewerCli, isCliReviewer, reviewerCliBinary, normalizeReviewUsernames, normalizeOptionalReviewers, normalizeReviewerMaxRounds, resolveReviewerConfig, resolveClaimReviewerConfig, buildReviewerPinNote, reviewerEffortArgs, reviewerModelArg, buildReviewerEffortNote, resolveKeyedReviewers, buildReviewWithArgs, buildReviewersCsv } from '../lib/validation.js';import { PROVIDER_TYPES } from '../lib/aiToolkit/constants.js';import { doneSentinelName, PROGRAMMATIC_OUTPUT_COMPLETION_HEADING } from '../lib/agentSentinel.js';@@ -227,71 +228,126 @@ export async function loadSkillTemplates(skillNames, loadTemplate = loadSkillTemreturn templates.filter(Boolean).join('\n\n') || null;}-// Nested-CLAUDE.md discovery bounds (#3866). On-demand nested memory files are a-// Claude Code feature — an API-provider agent reads nothing natively, so PortOS-// has to splice them in itself or a subtree rule (including a data-loss guard)-// never reaches that class of agent. The walk is bounded on three axes so a repo-// that grows nested files can't silently balloon every agent prompt or turn one-// prompt build into a full-tree crawl.-const NESTED_CLAUDE_MD_MAX_DEPTH = 5;-const NESTED_CLAUDE_MD_MAX_FILES = 10;-const NESTED_CLAUDE_MD_MAX_DIRS = 2000;+// Nested agent-instruction discovery bounds (#3866). On-demand nested memory+// files are a Claude Code feature — an API-provider agent reads nothing+// natively, so PortOS has to splice them in itself or a subtree rule (including+// a data-loss guard) never reaches that class of agent. The walk is bounded on+// three axes so a repo that grows nested files can't silently balloon every+// agent prompt or turn one prompt build into a full-tree crawl.+const NESTED_AGENT_MD_MAX_DEPTH = 5;+const NESTED_AGENT_MD_MAX_FILES = 10;+const NESTED_AGENT_MD_MAX_DIRS = 2000;// Dot-directories are skipped wholesale (covers `.git`), so these are the// non-dot trees that are either vendored, generated, or runtime state. The list// is deliberately polyglot: an agent workspace is any app PortOS manages, not// just this repo, so a Rust `target/` or a Go `vendor/` would otherwise burn the// directory budget on generated files.-const NESTED_CLAUDE_MD_SKIP_DIRS = new Set([+const NESTED_AGENT_MD_SKIP_DIRS = new Set(['node_modules', 'data', 'data.reference', 'dist', 'build', 'coverage','out', 'obj', 'bin', 'target', 'vendor', 'tmp', 'venv', 'Pods', '__pycache__',]);+// Instruction filenames in preference order (#4852). `AGENTS.md` is the+// cross-vendor standard PortOS now ships; `CLAUDE.md` stays discoverable because+// a managed app may still carry only that name, and a plain rename would+// silently drop its context. A directory holding both contributes exactly ONE+// entry — otherwise this repo's four nested pairs would count as eight against+// NESTED_AGENT_MD_MAX_FILES and the budget would overflow without a signal.+const AGENT_INSTRUCTION_FILENAMES = [AGENT_INSTRUCTIONS_FILENAME, CLAUDE_BRIDGE_FILENAME];++/**+ * True for a bridge `CLAUDE.md` whose entire body is an `@AGENTS.md` import —+ * how PortOS and its scaffolders keep Claude Code (which has no configurable+ * memory filename) reading the shared file. It carries no content of its own, so+ * splicing it would add a useless one-line section to every agent prompt and+ * burn a slot against the file cap.+ * @param {string} content+ */+const isImportOnlyInstructionFile = (content) => {+ const lines = String(content)+ .replace(/<!--[\s\S]*?-->/g, '')+ .split('\n')+ .map((line) => line.trim())+ .filter(Boolean);+ if (lines.length === 0) return false;+ if (!lines.every((line) => /^@\S+$/.test(line))) return false;+ return lines.some((line) => basename(line.slice(1)).toLowerCase() === 'agents.md');+};++/**+ * Read one instruction file, collapsing "absent", "empty", and "import-only+ * bridge" to the same null so callers can fall through to the next candidate.+ * @param {string} path+ * @returns {Promise<string|null>} trimmed content, or null+ */+const readInstructionFile = async (path) => {+ const content = await tryReadFile(path);+ if (!content?.trim()) return null;+ if (basename(path) === CLAUDE_BRIDGE_FILENAME && isImportOnlyInstructionFile(content)) return null;+ return content.trim();+};+/**- * Collect workspace-relative paths of nested `CLAUDE.md` files (the root one is- * excluded — its caller reads it separately and must keep it first). Depth-first- * in lexicographic order, so the result is deterministic and prompt caching stays+ * Collect nested per-directory instruction files (the workspace root is excluded+ * — its caller reads it separately and must keep it first). Depth-first in+ * lexicographic order, so the result is deterministic and prompt caching stays* stable across builds.* @param {string} workspaceDir- * @returns {Promise<string[]>} repo-relative paths, e.g. `['server/CLAUDE.md']`+ * @returns {Promise<Array<{ rel: string, content: string }>>} e.g. `[{ rel: 'server/AGENTS.md', … }]`*/-async function findNestedClaudeMdFiles(workspaceDir) {+async function findNestedAgentInstructionFiles(workspaceDir) {const found = [];let dirsVisited = 0;const walk = async (dir, relDir, depth) => {- if (found.length >= NESTED_CLAUDE_MD_MAX_FILES) return;- if (depth > NESTED_CLAUDE_MD_MAX_DEPTH) return;- if (dirsVisited >= NESTED_CLAUDE_MD_MAX_DIRS) return;+ if (found.length >= NESTED_AGENT_MD_MAX_FILES) return;+ if (depth > NESTED_AGENT_MD_MAX_DEPTH) return;+ if (dirsVisited >= NESTED_AGENT_MD_MAX_DIRS) return;dirsVisited += 1;const entries = await readdir(dir, { withFileTypes: true }).catch(() => null);if (!entries) return;// A nested directory carrying its own `.git` is a submodule or vendored- // checkout (`lib/slashdo` here) — its CLAUDE.md is that project's- // instructions, not this workspace's. Detected structurally rather than by- // an allowlist of paths, which would silently stop matching the moment the- // workspace root is something other than this repo's root.+ // checkout (`lib/slashdo` here) — its instructions are that project's, not+ // this workspace's. Detected structurally rather than by an allowlist of+ // paths, which would silently stop matching the moment the workspace root is+ // something other than this repo's root.if (depth > 0 && entries.some((entry) => entry.name === '.git')) return;const sorted = [...entries].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));const subdirs = [];+ const instructionNames = new Set();for (const entry of sorted) {const rel = relDir ? `${relDir}/${entry.name}` : entry.name;if (entry.isDirectory()) {if (entry.name.startsWith('.')) continue;- if (NESTED_CLAUDE_MD_SKIP_DIRS.has(entry.name)) continue;+ if (NESTED_AGENT_MD_SKIP_DIRS.has(entry.name)) continue;subdirs.push({ path: join(dir, entry.name), rel });// Symlinked directories are deliberately NOT followed — a link back up// the tree would loop, and the depth cap alone wouldn't make the result- // meaningful. A symlinked CLAUDE.md *file* is still read (below).- } else if (entry.name === 'CLAUDE.md' && relDir) {- found.push(rel);- if (found.length >= NESTED_CLAUDE_MD_MAX_FILES) return;+ // meaningful. A symlinked instruction *file* is still read (below).+ } else if (AGENT_INSTRUCTION_FILENAMES.includes(entry.name)) {+ instructionNames.add(entry.name);+ }+ }++ // One entry per directory. Content is read here rather than by the caller so+ // an import-only bridge can be dropped before it consumes a slot against the+ // file cap — filtering after the walk would let a directory of bridges push+ // real instructions out of the budget.+ if (relDir) {+ for (const name of AGENT_INSTRUCTION_FILENAMES) {+ if (!instructionNames.has(name)) continue;+ const content = await readInstructionFile(join(dir, name));+ if (!content) continue;+ found.push({ rel: `${relDir}/${name}`, content });+ break;}+ if (found.length >= NESTED_AGENT_MD_MAX_FILES) return;}for (const sub of subdirs) {- if (found.length >= NESTED_CLAUDE_MD_MAX_FILES) return;+ if (found.length >= NESTED_AGENT_MD_MAX_FILES) return;await walk(sub.path, sub.rel, depth + 1);}};@@ -301,42 +357,43 @@ async function findNestedClaudeMdFiles(workspaceDir) {}/**- * Read CLAUDE.md files for agent context.- * Reads the global (`~/.claude/CLAUDE.md`), the workspace-root `CLAUDE.md`, and- * every nested `CLAUDE.md` under the workspace (#3866) — nested last, each as its- * own labeled section, so precedence still reads root-then-specific.+ * Read agent-instruction files for agent context.+ * Reads the global (`~/.claude/CLAUDE.md`), the workspace-root `AGENTS.md` (or+ * `CLAUDE.md`), and every nested instruction file under the workspace (#3866) —+ * nested last, each as its own labeled section, so precedence still reads+ * root-then-specific.*/-export async function getClaudeMdContext(workspaceDir) {+export async function getAgentInstructionsContext(workspaceDir) {const contexts = [];- // Try to read global CLAUDE.md from ~/.claude/CLAUDE.md+ // Claude Code's own global memory location — a user-level path, not a repo+ // convention, so it keeps the CLAUDE.md name (#4852).const globalPath = join(homedir(), '.claude', 'CLAUDE.md');const globalContent = await tryReadFile(globalPath);if (globalContent?.trim()) {contexts.push({ type: 'Global Instructions', path: globalPath, content: globalContent.trim() });}- // Try to read project-specific CLAUDE.md from workspace directory- const projectPath = join(workspaceDir, 'CLAUDE.md');- const projectContent = await tryReadFile(projectPath);- if (projectContent?.trim()) {- contexts.push({ type: 'Project Instructions', path: projectPath, content: projectContent.trim() });+ // Workspace-root instructions, `AGENTS.md` preferred.+ for (const name of AGENT_INSTRUCTION_FILENAMES) {+ const projectPath = join(workspaceDir, name);+ const projectContent = await readInstructionFile(projectPath);+ if (projectContent) {+ contexts.push({ type: 'Project Instructions', path: projectPath, content: projectContent });+ break;+ }}// Nested per-directory instructions, appended after the root file.- for (const rel of await findNestedClaudeMdFiles(workspaceDir)) {- const nestedPath = join(workspaceDir, rel);- const nestedContent = await tryReadFile(nestedPath);- if (nestedContent?.trim()) {- contexts.push({ type: `Project Instructions (${rel})`, path: nestedPath, content: nestedContent.trim() });- }+ for (const { rel, content } of await findNestedAgentInstructionFiles(workspaceDir)) {+ contexts.push({ type: `Project Instructions (${rel})`, path: join(workspaceDir, rel), content });}if (contexts.length === 0) {return null;}- let section = '## CLAUDE.md Instructions\n\n';+ let section = '## Agent Instructions\n\n';section += 'The following instructions must be followed when working on this task:\n\n';for (const ctx of contexts) {@@ -347,7 +404,6 @@ export async function getClaudeMdContext(workspaceDir) {return section;}-/*** Build a compaction instruction section for retries after context-limit failures.* Provides explicit guidance to the agent on reducing output verbosity.@@ -376,7 +432,7 @@ ${hints.map(h => `- ${h}`).join('\n')}/*** Provider types that get the **light** prompt: agentic CLIs with native- * filesystem tools and CLAUDE.md loading (Claude Code, Codex, Antigravity —+ * filesystem tools and agent-instruction loading (Claude Code, Codex, Antigravity —* whether running interactively as `tui` or one-shot as `cli`). Everything* else (`api`: LM Studio, raw OpenAI/Anthropic) needs the full pasted-in* context because it has no native filesystem access.@@ -1546,10 +1602,10 @@ function buildClaimFlowCompletionSection({ isTui = false, sentinelPath = null, r** - **Light** (`tui` / `cli`): minimal prompt — task description, attached* context, screenshot paths, worktree/jira/pipeline coordinates, and the- * completion-workflow contract. Memory, CLAUDE.md, digital twin, tools+ * completion-workflow contract. Memory, AGENTS.md, digital twin, tools* summary, planning context, skill templates, and compaction warnings are* deliberately omitted because the agent can fetch them itself.- * - **Full** (`api`): kitchen-sink prompt with memory + CLAUDE.md + digital+ * - **Full** (`api`): kitchen-sink prompt with memory + AGENTS.md + digital* twin + tools + skills + planning + git hygiene. The leading* "# Chief of Staff Agent Briefing" header is dropped from both modes.*@@ -1671,11 +1727,11 @@ export async function buildAgentPrompt(task, config, workspaceDir, worktreeInfo// Creative Director tasks (scene evaluation, treatment/plan run via API) judge// generated content rather than writing PortOS code — shared below by both- // `skipDevContext` (the repo's CLAUDE.md files plus memory / digital-twin /+ // `skipDevContext` (the repo's instruction files plus memory / digital-twin /// onboard-tools are pure noise for that prompt) and `noCodeOutput` (the// deliverable is an HTTP PATCH, not a commit).const isCreativeDirectorTask = !!task.metadata?.creativeDirector;- // Full path: API providers don't read CLAUDE.md natively, so always include it —+ // Full path: API providers read no instruction file natively, so always include it —// except for Creative Director tasks, per above. Memory, digital-twin, and the// onboard-tools catalog are the same category of dev-oriented noise for a// vision/PATCH task (#4650) — CD evaluate uses native Read + HTTP PATCH, and@@ -1683,15 +1739,15 @@ export async function buildAgentPrompt(task, config, workspaceDir, worktreeInfo// own prompt, not this section.const skipDevContext = isCreativeDirectorTask;// Fetch independent context sections in parallel- const [memorySection, claudeMdSection, digitalTwinSection] = await Promise.all([+ const [memorySection, agentInstructionsSection, digitalTwinSection] = await Promise.all([skipDevContext? Promise.resolve(null): getMemorySection(task, { maxTokens: config.memory?.maxContextTokens || 2000 }).catch(err => { console.log(`⚠️ Memory retrieval failed: ${err.message}`); return null; }),skipDevContext? Promise.resolve(null)- : getClaudeMdContext(workspaceDir)- .catch(err => { console.log(`⚠️ CLAUDE.md retrieval failed: ${err.message}`); return null; }),+ : getAgentInstructionsContext(workspaceDir)+ .catch(err => { console.log(`⚠️ Agent instructions retrieval failed: ${err.message}`); return null; }),skipDevContext? Promise.resolve(null): getDigitalTwinForPrompt({ maxTokens: config.digitalTwin?.maxContextTokens || config.soul?.maxContextTokens || 2000, personaId: 'active' })@@ -1965,7 +2021,7 @@ ${task.metadata.jiraBranch ? 'Commit your changes to this branch. Do NOT switchtargetAppLabel,config,memorySection,- claudeMdSection,+ agentInstructionsSection,digitalTwinSection,worktreeSection,pipelineSection,@@ -1978,6 +2034,7 @@ ${task.metadata.jiraBranch ? 'Commit your changes to this branch. Do NOT switchskillSection,planningContextSection,toolsSection,+ claudeMdSection: agentInstructionsSection, // Backwards compatibility for prompt templates (pre-#4852 name)soulSection: digitalTwinSection, // Backwards compatibility for prompt templatestimestamp: new Date().toISOString()}).catch(() => null);@@ -1989,7 +2046,7 @@ ${task.metadata.jiraBranch ? 'Commit your changes to this branch. Do NOT switchconst taskBlock = buildTaskBlock(task, { screenshotsAsList: false });// Fallback to built-in template- return `${claudeMdSection || ''}+ return `${agentInstructionsSection || ''}${memorySection || ''}@@ -2077,10 +2134,10 @@ Begin working on the task now.`;/*** Build the **light-context** prompt for agents that have native filesystem- * tools and CLAUDE.md loading (Claude Code, Codex, Antigravity — `tui` or `cli`).+ * tools and agent-instruction loading (Claude Code, Codex, Antigravity — `tui` or `cli`).** The agent already has direct access to the project, so we don't paste in:- * memory dumps, CLAUDE.md contents, digital twin, tools summary,+ * memory dumps, AGENTS.md contents, digital twin, tools summary,* `.planning/` snippets, auto-matched skill templates, or compaction* warnings. We just hand it the task, any user-attached context/screenshots/attachments,* and the PortOS-specific contract bits it can't infer (worktree branch,@@ -2215,7 +2272,7 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMet// --- Unattended run ----------------------------------------------------// First contract section, and unconditional: the light path is the one that// actually stalled on an approval gate, and "no human will answer you" is not- // something the agent can infer from CLAUDE.md or its cwd.+ // something the agent can infer from AGENTS.md or its cwd.contractSections.push(UNATTENDED_RUN_RULE);// --- Worktree ----------------------------------------------------------@@ -2842,7 +2899,7 @@ function buildCliCompletionSection({ worktreeInfo, willOpenPR, prCompletion = PR** So this returns an explicit `null` sentinel and lets each caller decide* whether "no workspace" is legal for it (per the sentinel-and-validate rule in- * CLAUDE.md — absent must not collapse into a valid-looking value). The reason+ * AGENTS.md — absent must not collapse into a valid-looking value). The reason* is logged here, where it's known.** @returns {Promise<string|null>} the app's repoPath, or null if unresolvablediff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.jsindex dfb1cbf940..347c4823aa 100644--- a/server/services/agentPromptBuilder.test.js+++ b/server/services/agentPromptBuilder.test.js@@ -3,9 +3,9 @@** The split is by `provider.type`:* - `tui` / `cli` → light prompt (Claude Code, Codex, Antigravity — agentic- * CLIs with native filesystem tools and CLAUDE.md loading)+ * CLIs with native filesystem tools and agent-instruction loading)* - `api` → full prompt (LM Studio, raw OpenAI/Anthropic — no- * native filesystem access, so we paste in memory/CLAUDE.md/etc.)+ * native filesystem access, so we paste in memory/AGENTS.md/etc.)** The light path is the focus here because it's the new code. The full* path is exercised by a single negative assertion that confirms the@@ -92,7 +92,7 @@ vi.mock('./codeReview.js', () => ({getCodeReviewDefaults: vi.fn().mockResolvedValue({ reviewers: ['copilot'] }),}));-import { buildLightContextPrompt, buildAgentPrompt, buildCompletionGuidelineBullet, reconcileSplitContext, buildReviewLoopFollowUpSection, getAppWorkspace, getClaudeMdContext, detectSkillTemplates, loadSkillTemplates, UNATTENDED_RUN_RULE } from './agentPromptBuilder.js';+import { buildLightContextPrompt, buildAgentPrompt, buildCompletionGuidelineBullet, reconcileSplitContext, buildReviewLoopFollowUpSection, getAppWorkspace, getAgentInstructionsContext, detectSkillTemplates, loadSkillTemplates, UNATTENDED_RUN_RULE } from './agentPromptBuilder.js';import { getCodeReviewDefaults } from './codeReview.js'; // mocked above — control the configured defaultimport { isTruthyMeta } from './agentState.js';import { buildPrompt } from './promptService.js'; // mocked above — inspect call args@@ -381,7 +381,7 @@ describe('buildLightContextPrompt', () => {expect(prompt).not.toMatch(/You are an autonomous agent/);});- it('does NOT paste memory, CLAUDE.md, digital-twin, tools-summary, planning, or skill blocks', () => {+ it('does NOT paste memory, AGENTS.md, digital-twin, tools-summary, planning, or skill blocks', () => {// Light path is synchronous and reads NONE of these — proving it by// checking the rendered output has no section headings for them.const prompt = buildLightContextPrompt(makeTask({@@ -2259,8 +2259,8 @@ describe('discardWorktree (reasoning-only) completion contract', () => {it('splices the fixture verbatim yet still suppresses commit/push/merge in every builder-generated section', async () => {// Sanity: the fixture is live and carries the strings under test. Without// this the assertions below could pass because nothing was read at all.- const claudeMdSection = await getClaudeMdContext('/r');- expect(claudeMdSection).toMatch(/## CLAUDE\.md Instructions/);+ const claudeMdSection = await getAgentInstructionsContext('/r');+ expect(claudeMdSection).toMatch(/## Agent Instructions/);expect(claudeMdSection).toMatch(/gh pr merge/);expect(claudeMdSection).toMatch(/Commit and push your changes/);@@ -2316,6 +2316,8 @@ describe('discardWorktree (reasoning-only) completion contract', () => {expect(context.memorySection).toBeNull();expect(context.digitalTwinSection).toBeNull();expect(context.toolsSection).toBe('');+ expect(context.agentInstructionsSection).toBeNull();+ // Pre-#4852 template variable name, still passed for stored custom templates.expect(context.claudeMdSection).toBeNull();expect(prompt).not.toContain('CD_MEMORY_SENTINEL');expect(prompt).not.toContain('CD_TWIN_SENTINEL');@@ -2346,7 +2348,7 @@ describe('discardWorktree (reasoning-only) completion contract', () => {vi.mocked(getToolsSummaryForPrompt).mockResolvedValue('');});- it('a CD scratch cwd does not leak repo CLAUDE.md into getClaudeMdContext', async () => {+ it('a CD scratch cwd does not leak repo AGENTS.md into getAgentInstructionsContext', async () => {// Mirrors the fixture-pinning in this block: a dir with no CLAUDE.md// (the CD scratch shape) must not surface content that lives in a sibling// "repo" fixture. Global ~/.claude/CLAUDE.md still splices here because@@ -2355,8 +2357,8 @@ describe('discardWorktree (reasoning-only) completion contract', () => {const repo = mkdtempSync(join(tmpdir(), 'portos-cd-repo-'));writeFileSync(join(repo, 'CLAUDE.md'), 'REPO_CLAUDE_MD_LEAK_SENTINEL');const scratch = mkdtempSync(join(tmpdir(), 'portos-cd-scratch-'));- expect(await getClaudeMdContext(repo)).toContain('REPO_CLAUDE_MD_LEAK_SENTINEL');- expect(await getClaudeMdContext(scratch)).not.toContain('REPO_CLAUDE_MD_LEAK_SENTINEL');+ expect(await getAgentInstructionsContext(repo)).toContain('REPO_CLAUDE_MD_LEAK_SENTINEL');+ expect(await getAgentInstructionsContext(scratch)).not.toContain('REPO_CLAUDE_MD_LEAK_SENTINEL');rmSync(repo, { recursive: true, force: true });rmSync(scratch, { recursive: true, force: true });});@@ -2900,32 +2902,33 @@ describe('getAppWorkspace — tilde expansion (#3180)', () => {});});-// #3866 — getClaudeMdContext used to splice only the global + workspace-root-// CLAUDE.md, so a subtree rule (including a data-loss guard) never reached an-// API-provider agent. These pin the nested walk and its bounds.-describe('getClaudeMdContext — nested CLAUDE.md discovery (#3866)', () => {+// #3866 — getAgentInstructionsContext used to splice only the global ++// workspace-root instructions, so a subtree rule (including a data-loss guard)+// never reached an API-provider agent. These pin the nested walk and its bounds.+// #4852 widened the match from `CLAUDE.md` to `AGENTS.md` + `CLAUDE.md`.+describe('getAgentInstructionsContext — nested instruction discovery (#3866)', () => {let workspace;- const writeClaudeMd = (relDir, body) => {+ const writeInstructions = (relDir, body, name = 'AGENTS.md') => {const dir = relDir ? join(workspace, relDir) : workspace;mkdirSync(dir, { recursive: true });- writeFileSync(join(dir, 'CLAUDE.md'), body);+ writeFileSync(join(dir, name), body);};beforeAll(() => {- workspace = mkdtempSync(join(tmpdir(), 'portos-nested-claudemd-'));- writeClaudeMd('', '# Root rules\nAnchor every backup exclude.');- writeClaudeMd('server', '# Server rules\nSchema parity when adding fields.');- writeClaudeMd('client/src/components/dashboard', '# Dashboard rules\nRegister the widget.');- // Ignored trees: each carries a CLAUDE.md that must NOT be spliced.- writeClaudeMd('node_modules/some-dep', '# Vendored dep rules');- writeClaudeMd('data/cos/worktrees/claim-issue-1', '# Runtime worktree rules');+ workspace = mkdtempSync(join(tmpdir(), 'portos-nested-agentmd-'));+ writeInstructions('', '# Root rules\nAnchor every backup exclude.');+ writeInstructions('server', '# Server rules\nSchema parity when adding fields.');+ writeInstructions('client/src/components/dashboard', '# Dashboard rules\nRegister the widget.');+ // Ignored trees: each carries instructions that must NOT be spliced.+ writeInstructions('node_modules/some-dep', '# Vendored dep rules');+ writeInstructions('data/cos/worktrees/claim-issue-1', '# Runtime worktree rules');// Submodule / vendored checkout — recognized by its own `.git`, not by path.- writeClaudeMd('lib/slashdo', '# Submodule rules');+ writeInstructions('lib/slashdo', '# Submodule rules');writeFileSync(join(workspace, 'lib/slashdo/.git'), 'gitdir: ../../.git/modules/slashdo\n');- writeClaudeMd('.hidden', '# Dot dir rules');- // Past the depth cap (depth 6): a/b/c/d/e/f/CLAUDE.md.- writeClaudeMd('a/b/c/d/e/f', '# Too deep rules');+ writeInstructions('.hidden', '# Dot dir rules');+ // Past the depth cap (depth 6): a/b/c/d/e/f/AGENTS.md.+ writeInstructions('a/b/c/d/e/f', '# Too deep rules');});afterAll(() => {@@ -2933,14 +2936,14 @@ describe('getClaudeMdContext — nested CLAUDE.md discovery (#3866)', () => {});it('splices nested files after the root one, each labeled with its repo-relative path', async () => {- const section = await getClaudeMdContext(workspace);+ const section = await getAgentInstructionsContext(workspace);expect(section).toContain('### Project Instructions\n');expect(section).toContain('Anchor every backup exclude.');// The whole point of the issue: subtree content reaches the prompt.- expect(section).toContain('### Project Instructions (server/CLAUDE.md)');+ expect(section).toContain('### Project Instructions (server/AGENTS.md)');expect(section).toContain('Schema parity when adding fields.');- expect(section).toContain('### Project Instructions (client/src/components/dashboard/CLAUDE.md)');+ expect(section).toContain('### Project Instructions (client/src/components/dashboard/AGENTS.md)');expect(section).toContain('Register the widget.');// Root stays first so precedence still reads root-then-specific, and the@@ -2954,7 +2957,7 @@ describe('getClaudeMdContext — nested CLAUDE.md discovery (#3866)', () => {});it('skips vendored, runtime, submodule, dot, and over-depth trees', async () => {- const section = await getClaudeMdContext(workspace);+ const section = await getAgentInstructionsContext(workspace);expect(section).not.toContain('Vendored dep rules');expect(section).not.toContain('Runtime worktree rules');@@ -2967,27 +2970,27 @@ describe('getClaudeMdContext — nested CLAUDE.md discovery (#3866)', () => {// `lib/slashdo` above is skipped only because it carries a `.git`. A sibling// under the same parent, with no `.git`, must still be spliced — otherwise// the skip is really matching `lib/` and the structural check is vacuous.- writeClaudeMd('lib/inhouse', '# In-house lib rules');- const section = await getClaudeMdContext(workspace);- expect(section).toContain('### Project Instructions (lib/inhouse/CLAUDE.md)');+ writeInstructions('lib/inhouse', '# In-house lib rules');+ const section = await getAgentInstructionsContext(workspace);+ expect(section).toContain('### Project Instructions (lib/inhouse/AGENTS.md)');expect(section).toContain('In-house lib rules');expect(section).not.toContain('Submodule rules');rmSync(join(workspace, 'lib/inhouse'), { recursive: true, force: true });});it('caps the number of nested files spliced', async () => {- const capped = mkdtempSync(join(tmpdir(), 'portos-nested-claudemd-cap-'));+ const capped = mkdtempSync(join(tmpdir(), 'portos-nested-agentmd-cap-'));mkdirSync(capped, { recursive: true });- writeFileSync(join(capped, 'CLAUDE.md'), '# Root of capped workspace');+ writeFileSync(join(capped, 'AGENTS.md'), '# Root of capped workspace');// 12 nested files > the 10-file cap. Zero-padded so lexicographic order// matches numeric order and the assertions below are unambiguous.for (let i = 1; i <= 12; i++) {const dir = join(capped, `pkg-${String(i).padStart(2, '0')}`);mkdirSync(dir, { recursive: true });- writeFileSync(join(dir, 'CLAUDE.md'), `# Nested rule ${String(i).padStart(2, '0')}`);+ writeFileSync(join(dir, 'AGENTS.md'), `# Nested rule ${String(i).padStart(2, '0')}`);}- const section = await getClaudeMdContext(capped);+ const section = await getAgentInstructionsContext(capped);const spliced = section.match(/### Project Instructions \(/g) || [];expect(spliced).toHaveLength(10);// Non-vacuous: the survivors are the first 10 by path, and the overflow is@@ -2999,14 +3002,104 @@ describe('getClaudeMdContext — nested CLAUDE.md discovery (#3866)', () => {rmSync(capped, { recursive: true, force: true });});- it('returns null for a workspace with no CLAUDE.md at any level', async () => {- const empty = mkdtempSync(join(tmpdir(), 'portos-nested-claudemd-empty-'));+ it('returns null for a workspace with no instruction file at any level', async () => {+ const empty = mkdtempSync(join(tmpdir(), 'portos-nested-agentmd-empty-'));mkdirSync(join(empty, 'sub'), { recursive: true });- expect(await getClaudeMdContext(empty)).toBeNull();+ expect(await getAgentInstructionsContext(empty)).toBeNull();rmSync(empty, { recursive: true, force: true });});});+// #4852 — AGENTS.md is the canonical cross-vendor name, with `CLAUDE.md` kept as+// a one-line `@AGENTS.md` import so Claude Code (no configurable memory+// filename) still loads the shared content. The walker has to cope with a+// managed app carrying either name, or both.+describe('getAgentInstructionsContext — AGENTS.md / CLAUDE.md resolution (#4852)', () => {+ const makeWorkspace = () => mkdtempSync(join(tmpdir(), 'portos-agentmd-resolve-'));+ const write = (root, rel, body) => {+ const path = join(root, rel);+ mkdirSync(join(path, '..'), { recursive: true });+ writeFileSync(path, body);+ };++ it('still contributes a workspace that has only CLAUDE.md', async () => {+ // Regression guard for the managed-app case: a plain rename would silently+ // drop every app that hasn't adopted AGENTS.md.+ const ws = makeWorkspace();+ write(ws, 'CLAUDE.md', '# Legacy root\nLEGACY_ROOT_SENTINEL');+ write(ws, 'server/CLAUDE.md', '# Legacy nested\nLEGACY_NESTED_SENTINEL');++ const section = await getAgentInstructionsContext(ws);+ expect(section).toContain('LEGACY_ROOT_SENTINEL');+ expect(section).toContain('### Project Instructions (server/CLAUDE.md)');+ expect(section).toContain('LEGACY_NESTED_SENTINEL');+ rmSync(ws, { recursive: true, force: true });+ });++ it('prefers AGENTS.md and yields ONE entry per directory when both are present', async () => {+ // Without the dedupe this repo's four nested pairs would count as eight+ // against the 10-file cap and silently push real instructions out.+ const ws = makeWorkspace();+ write(ws, 'AGENTS.md', '# Root\nROOT_AGENTS_SENTINEL');+ write(ws, 'CLAUDE.md', '# Root\nROOT_CLAUDE_SENTINEL');+ write(ws, 'server/AGENTS.md', '# Server\nNESTED_AGENTS_SENTINEL');+ write(ws, 'server/CLAUDE.md', '# Server\nNESTED_CLAUDE_SENTINEL');++ const section = await getAgentInstructionsContext(ws);+ expect(section).toContain('ROOT_AGENTS_SENTINEL');+ expect(section).not.toContain('ROOT_CLAUDE_SENTINEL');+ expect(section).toContain('### Project Instructions (server/AGENTS.md)');+ expect(section).toContain('NESTED_AGENTS_SENTINEL');+ expect(section).not.toContain('NESTED_CLAUDE_SENTINEL');+ expect(section.match(/### Project Instructions \(/g) || []).toHaveLength(1);+ rmSync(ws, { recursive: true, force: true });+ });++ it('skips an import-only CLAUDE.md bridge instead of splicing an empty section', async () => {+ // The bridge carries no content of its own; splicing it adds a useless+ // one-line section to every agent prompt and burns a cap slot.+ const ws = makeWorkspace();+ write(ws, 'AGENTS.md', '# Root\nBRIDGE_ROOT_SENTINEL');+ write(ws, 'CLAUDE.md', '@AGENTS.md\n');+ write(ws, 'server/CLAUDE.md', '@AGENTS.md\n');++ const section = await getAgentInstructionsContext(ws);+ expect(section).toContain('BRIDGE_ROOT_SENTINEL');+ expect(section).not.toContain('@AGENTS.md');+ // `server/` holds nothing but the bridge, so it contributes no section at all.+ expect(section).not.toContain('### Project Instructions (server/');+ rmSync(ws, { recursive: true, force: true });+ });++ it('an import-only bridge does not consume a slot against the file cap', async () => {+ // Filtering after the walk instead of during it would let 10 bridges push+ // the real nested file out of the budget.+ const ws = makeWorkspace();+ write(ws, 'AGENTS.md', '# Root');+ for (let i = 1; i <= 10; i++) {+ write(ws, `bridge-${String(i).padStart(2, '0')}/CLAUDE.md`, '@AGENTS.md\n');+ }+ write(ws, 'zz-real/AGENTS.md', '# Real\nREAL_AFTER_BRIDGES_SENTINEL');++ const section = await getAgentInstructionsContext(ws);+ expect(section).toContain('REAL_AFTER_BRIDGES_SENTINEL');+ rmSync(ws, { recursive: true, force: true });+ });++ it('keeps a CLAUDE.md that only LOOKS like a bridge', async () => {+ // Non-vacuous guard on the import-only check: content below the import, or+ // an import of something other than AGENTS.md, is real content.+ const ws = makeWorkspace();+ write(ws, 'extra/CLAUDE.md', '@AGENTS.md\n\nClaude-only addendum: NOT_A_BRIDGE_SENTINEL');+ write(ws, 'other/CLAUDE.md', '@docs/conventions.md\n');++ const section = await getAgentInstructionsContext(ws);+ expect(section).toContain('NOT_A_BRIDGE_SENTINEL');+ expect(section).toContain('### Project Instructions (other/CLAUDE.md)');+ rmSync(ws, { recursive: true, force: true });+ });+});+describe('TUI reviewLoopFollowUp completion instructions', () => {it('appends .agent-done sentinel instructions for TUI agents on follow-up tasks', async () => {const task = {diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.jsindex 25f0146e77..9f38ae6cb6 100644--- a/server/services/agentTuiSpawning.js+++ b/server/services/agentTuiSpawning.js@@ -527,11 +527,11 @@ export async function spawnTuiAgent({// /sec; a per-run in-memory buffer would grow without bound on long agents// and the join-into-single-string at finalize would double peak RAM. The// disk file is appended in 250ms-debounced batches (same pattern as- // `flushPendingLines` for parsed output — see CLAUDE.md "High-frequency+ // `flushPendingLines` for parsed output — see AGENTS.md "High-frequency// state writes must batch"), and `analyzeAgentFailure` reads the file on// failure so it gets the full PTY stream regardless of run length.const rawFile = join(agentDir, 'raw.txt');- // CD no-worktree tasks get an isolated scratch cwd so native CLAUDE.md+ // CD no-worktree tasks get an isolated scratch cwd so native AGENTS.md// discovery cannot reach the PortOS repo tree (#4650). Everyone else keeps// workspacePath, falling back to the repo root when it was omitted.const cwd = resolveAgentCliCwd({ workspacePath, fallbackRoot: PATHS.root, task, agentId });@@ -1412,7 +1412,7 @@ export async function spawnTuiAgent({// sendPrompt / finishStartupFailure are async and dispatched fire-and-forget// from the interval below. A setInterval callback can't await, and an// unhandled rejection there (e.g. a finalizeAgent throw inside finish())- // would crash the process — the callback-boundary hazard CLAUDE.md calls out.+ // would crash the process — the callback-boundary hazard AGENTS.md calls out.// Wrap each floating call so a rejection is logged, not thrown.const safeSendPrompt = (reason) => pasteController.sendPrompt(reason).catch((err) =>emitLog('error', `TUI agent ${agentId} sendPrompt(${reason}) failed: ${err?.message || err}`, { agentId }));@@ -1523,7 +1523,7 @@ export async function spawnTuiAgent({const expired = selfClearingGate.takeExpired(Date.now());if (expired) {// setInterval can't await, and an unhandled rejection here would crash the- // process (the callback-boundary hazard CLAUDE.md calls out).+ // process (the callback-boundary hazard AGENTS.md calls out).failOverToFallback(expired).catch((err) =>emitLog('error', `TUI agent ${agentId} deferred fallback finish failed: ${err?.message || err}`, { agentId }));return;diff --git a/server/services/agentTuiSpawning/outputSpooler.js b/server/services/agentTuiSpawning/outputSpooler.jsindex db965a571f..d7050e748b 100644--- a/server/services/agentTuiSpawning/outputSpooler.js+++ b/server/services/agentTuiSpawning/outputSpooler.js@@ -8,7 +8,7 @@* 2. Raw PTY bytes → the append-only `raw.txt` disk spool (no ANSI strip, no* line semantics) that `analyzeAgentFailure` reads on failure.*- * Both pipelines debounce writes on a 250ms window (see CLAUDE.md "High-+ * Both pipelines debounce writes on a 250ms window (see AGENTS.md "High-* frequency state writes must batch") — a chatty TUI emits hundreds of chunks* /sec, and per-chunk state writes would thrash the filesystem and slow the PTY* event loop. Extracted from spawnTuiAgent so the buffering/spooling concern isdiff --git a/server/services/agentWorkspacePrep.js b/server/services/agentWorkspacePrep.jsindex 15373fcbef..36b5187be9 100644--- a/server/services/agentWorkspacePrep.js+++ b/server/services/agentWorkspacePrep.js@@ -147,13 +147,13 @@ export async function prepareAgentWorkspace({ agentId, task }) {// Creative Director treatment/plan/evaluate tasks are HTTP-PATCH deliverables// and never asked for a worktree. Pin them to an isolated scratch cwd BEFORE// the PortOS-root resolution / git-pull / conflict scan, so a CLI/TUI provider- // cannot natively discover the repo CLAUDE.md tree (#4650).+ // cannot natively discover the repo AGENTS.md tree (#4650).if (usesCreativeDirectorScratchCwd(task)) {const workspacePath = creativeDirectorScratchCwd(agentId);await ensureDir(workspacePath);// Codex (and any CLI that refuses a non-git cwd) needs a repo root here.// Initializing INSIDE the scratch makes the scratch itself the git root, so- // native CLAUDE.md discovery cannot walk up into the PortOS checkout —+ // native AGENTS.md discovery cannot walk up into the PortOS checkout —// `--skip-git-repo-check` would only cover Codex's exec path, not TUI.await execGit(['init'], workspacePath).catch((err) => {emitLog('warn', `⚠️ CD scratch git init failed for ${agentId}: ${err.message}`, {diff --git a/server/services/albums/logic.js b/server/services/albums/logic.jsindex f1a1bbcbf4..9ecd0fc33e 100644--- a/server/services/albums/logic.js+++ b/server/services/albums/logic.js@@ -143,7 +143,7 @@ export function mergeAlbumRecord(local, remoteRaw) {/*** Apply a partial patch onto an existing record. Only keys PRESENT in `patch`- * overwrite — absent preserves, present-empty clears (per CLAUDE.md). Bumps+ * overwrite — absent preserves, present-empty clears (per AGENTS.md). Bumps* updatedAt.*/export function applyAlbumPatch(current, patch = {}) {diff --git a/server/services/appIssues.js b/server/services/appIssues.jsindex add1e804bb..46bbd5bf1b 100644--- a/server/services/appIssues.js+++ b/server/services/appIssues.js@@ -16,7 +16,7 @@* (see `listAppIssues`), so the Claim button can never queue a run against a* tracker other than the one the user is looking at.*- * Sentinel discipline (CLAUDE.md): "couldn't ask the forge" never collapses into+ * Sentinel discipline (AGENTS.md): "couldn't ask the forge" never collapses into* "there are no issues". A failed probe returns `issues: []` WITH* `transient: true`, a `reason`, and the `headline`/`remedy` that describe it, so* the UI says "couldn't load" instead of the lie "no open issues" — and says WHYdiff --git a/server/services/apps.js b/server/services/apps.jsindex 05e7e8ac1b..76b8dfbd37 100644--- a/server/services/apps.js+++ b/server/services/apps.js@@ -289,7 +289,7 @@ export async function annotateExpectedExit(processes) {* primitive behind both `getAppStatusSummary()` (counts) and the OpenWorld* snapshot pipeline (per-building status), so the two never drift.*- * Absent-vs-empty rule (CLAUDE.md): `listProcessesStrict(home)` returns `null`+ * Absent-vs-empty rule (AGENTS.md): `listProcessesStrict(home)` returns `null`* when the PM2 read FAILED (vs `[]` for a successful read with no processes).* The generic `listProcesses` flattens a failed read into `[]`, which would* record every app in that home as `not_started` (status known: never launched)diff --git a/server/services/artists/logic.js b/server/services/artists/logic.jsindex d7ee3b1082..d1c1eaa3cc 100644--- a/server/services/artists/logic.js+++ b/server/services/artists/logic.js@@ -123,7 +123,7 @@ export function mergeArtistRecord(local, remoteRaw) {/*** Apply a partial patch onto an existing record. Only keys PRESENT in `patch`* overwrite — an absent key preserves the current value, a present empty-string- * applies the clear (distinguish-absent-vs-empty per CLAUDE.md). Bumps updatedAt.+ * applies the clear (distinguish-absent-vs-empty per AGENTS.md). Bumps updatedAt.*/export function applyArtistPatch(current, patch = {}) {const next = { ...current };diff --git a/server/services/authors/logic.js b/server/services/authors/logic.jsindex af1dd07f69..7301d22221 100644--- a/server/services/authors/logic.js+++ b/server/services/authors/logic.js@@ -132,7 +132,7 @@ export function mergeAuthorRecord(local, remoteRaw) {* Apply a partial patch onto an existing record. Only keys PRESENT in `patch`* overwrite — an absent key preserves the current value, while a present* empty-string value applies the clear (distinguish-absent-vs-empty per- * CLAUDE.md). Always bumps `updatedAt`.+ * AGENTS.md). Always bumps `updatedAt`.*/export function applyAuthorPatch(current, patch = {}) {const next = { ...current };diff --git a/server/services/autoFixMetrics.js b/server/services/autoFixMetrics.jsindex 73e3de0903..a38b3aea5c 100644--- a/server/services/autoFixMetrics.js+++ b/server/services/autoFixMetrics.js@@ -10,7 +10,7 @@* (no I/O — trivially unit-testable); `getAutoFixMetrics` is the thin I/O shim* the route calls to load persisted tasks and hand them to the reducer.*- * Sentinel discipline (per CLAUDE.md): a rate with no denominator and a+ * Sentinel discipline (per AGENTS.md): a rate with no denominator and a* duration summary with no completed-with-timing samples return `null`, NOT a* fabricated 0 — "no data yet" must never read as "0% success" or "0ms* recovery".diff --git a/server/services/autonomousJobs/layeredIntelligenceHooks.js b/server/services/autonomousJobs/layeredIntelligenceHooks.jsindex 390879f06e..223efe7f8b 100644--- a/server/services/autonomousJobs/layeredIntelligenceHooks.js+++ b/server/services/autonomousJobs/layeredIntelligenceHooks.js@@ -22,7 +22,7 @@* spawning an agent at all. Every deterministic side effect stays in these hooks.** Runs OUTSIDE the request lifecycle (scheduler tick / agent completion), so per- * the CLAUDE.md no-try/catch rule the dispatchers own the async boundary; these+ * the AGENTS.md no-try/catch rule the dispatchers own the async boundary; these* stay defensive so a partial failure degrades to a recorded no-op.*/diff --git a/server/services/autonomousJobs/selfDiagnostics.js b/server/services/autonomousJobs/selfDiagnostics.jsindex d0e3ca6115..fbd66dc9c0 100644--- a/server/services/autonomousJobs/selfDiagnostics.js+++ b/server/services/autonomousJobs/selfDiagnostics.js@@ -106,7 +106,7 @@ export function formatDurationShort(ms) {/*** Structured single-line log entry for one failing category. Pure — the handler- * emits it via console so logs stay single-line + emoji-prefixed (CLAUDE.md).+ * emits it via console so logs stay single-line + emoji-prefixed (AGENTS.md).*/export function formatCategoryLogLine(c) {return `🩺 ${c.slug}: ${c.failed}/${c.total} recent failed (${c.successRate}% success) · ` +diff --git a/server/services/bootstrap.js b/server/services/bootstrap.jsindex 483d99229b..44f2ad3261 100644--- a/server/services/bootstrap.js+++ b/server/services/bootstrap.js@@ -18,7 +18,7 @@* database. This file supplies the real implementations; that file decides when* each one runs and which are awaited. Read both before reordering anything.*- * NOTE (CLAUDE.md "No cold-bootstrap LLM calls"): nothing in this file may+ * NOTE (AGENTS.md "No cold-bootstrap LLM calls"): nothing in this file may* queue an AI provider call. Boot only loads on-disk state and ARMS schedulers;* every scheduler here is off by default or user-configured.*/@@ -221,7 +221,7 @@ export const bootstrapServices = async ({ io, dataDir, dataReferenceDir, serverD// Verify every registered collection's on-disk type-level schemaVersion// matches what the code expects. Mismatches mean a migration didn't run (or// the user rolled the code back below a forward-only migration) — log loudly- // but DO NOT crash the server. PortOS is single-user (CLAUDE.md "Security+ // but DO NOT crash the server. PortOS is single-user (AGENTS.md "Security// Model"); a hard exit on startup is worse than a noisy log the user can act// on. Returns per-store statuses for downstream telemetry; we discard them.verifyCollections: () => verifyCollectionVersions([universeStore(), seriesStore(), issueStore(), conflictJournalStore(), storyBuilderStore(), mediaCollectionStore(), loraDatasetStore, liOutcomesStore(), commissionStore(), gameStore, fableLoomStore, ...brainCollectionStores()]),diff --git a/server/services/bootstrapSequence.js b/server/services/bootstrapSequence.jsindex e37c25d2fc..54c761bc87 100644--- a/server/services/bootstrapSequence.js+++ b/server/services/bootstrapSequence.js@@ -15,7 +15,7 @@* Every dependency arrives as a parameter; that is what keeps this testable.* - `await` vs fire-and-forget is part of the contract, not an accident: an* awaited step blocks every later step, and the tests assert which is which.- * - No step here may reach an AI provider (CLAUDE.md "No cold-bootstrap LLM+ * - No step here may reach an AI provider (AGENTS.md "No cold-bootstrap LLM* calls"). Boot loads on-disk state and ARMS schedulers, nothing more.*/diff --git a/server/services/bootstrapSequence.test.js b/server/services/bootstrapSequence.test.jsindex e4fb3281e4..e54de24156 100644--- a/server/services/bootstrapSequence.test.js+++ b/server/services/bootstrapSequence.test.js@@ -173,7 +173,7 @@ describe('runPreRouteSequence — pre-route boot order', () => {});it('does not reach the toolkit itself — every touch goes through an injected step', async () => {- // CLAUDE.md "No cold-bootstrap LLM calls": the sequence may construct and+ // AGENTS.md "No cold-bootstrap LLM calls": the sequence may construct and// hand off the toolkit, never dispatch a run through it.const executeRun = vi.fn();const recorder = createRecorder();@@ -702,7 +702,7 @@ describe('boot source contract', () => {const BOOTSTRAP = read('bootstrap.js');const SEQUENCE = read('bootstrapSequence.js');- // Every entry point that dispatches work to an AI provider. CLAUDE.md's+ // Every entry point that dispatches work to an AI provider. AGENTS.md's// "No cold-bootstrap LLM calls": a fresh install coming online must be silent// until the user asks for AI-backed work. Boot may ARM a scheduler (which// gates on user config before it ever fires) but must never call these.diff --git a/server/services/brainStorage.js b/server/services/brainStorage.jsindex 5b9267cded..669c698e6a 100644--- a/server/services/brainStorage.js+++ b/server/services/brainStorage.js@@ -18,7 +18,7 @@* `queueRecordWrite(id, fn)`: two writes to the SAME (type, id) serialize —* local create/update AND remote peer applies AND tombstone GC all queue on the* same per-id tail, so a peer sync landing mid-way through a local write can't- * read a stale snapshot and drop the other write (the CLAUDE.md-sanctioned+ * read a stale snapshot and drop the other write (the AGENTS.md-sanctioned* "serialize two write paths that mutate the same record" case). Writes to* different records no longer serialize against each other. brainJournal layers* its own storeMutex ON TOP for the read→mutate→write of a single journal entry;diff --git a/server/services/catalogCanonProjection.test.js b/server/services/catalogCanonProjection.test.jsindex 6b0a6cb1ba..93d72dca5c 100644--- a/server/services/catalogCanonProjection.test.js+++ b/server/services/catalogCanonProjection.test.js@@ -14,7 +14,7 @@* `instances.js` stays under the global vitest.setup mock (getPeers → []) so no* created row fans out to live peers; nothing here exercises the* createUniverse/createSeries peerSync import path, so mockNoPeers alone is- * sufficient per the CLAUDE.md record-creating-tests rule.+ * sufficient per the AGENTS.md record-creating-tests rule.*/import { describe, it, expect, afterAll, vi } from 'vitest';diff --git a/server/services/catalogDB.test.js b/server/services/catalogDB.test.jsindex a119b4cd94..5c5d9a96d6 100644--- a/server/services/catalogDB.test.js+++ b/server/services/catalogDB.test.js@@ -11,7 +11,7 @@* `instances.js` is left under the global vitest.setup.js mock (getPeers → [])* so no row created here fans out to live sync peers; nothing here exercises* the createUniverse/createSeries peerSync import path, so mockNoPeers alone- * is sufficient per the CLAUDE.md record-creating-tests rule.+ * is sufficient per the AGENTS.md record-creating-tests rule.*/import { describe, it, expect, afterAll } from 'vitest';diff --git a/server/services/character.js b/server/services/character.jsindex a7c1c80c62..16d0371686 100644--- a/server/services/character.js+++ b/server/services/character.js@@ -109,7 +109,7 @@ export function levelFromAge(ageYears) {// unset date from one that is present-but-unusable (#2757). `levelFromAge(ageYears)` collapses// all of unset/invalid/future/unreadable into `null`, which the client used to treat uniformly// as "set your birth date" — telling a user to *set* a date they already entered. This restores-// the sentinel distinction (absent vs failed vs valid — see CLAUDE.md) as an explicit status:+// the sentinel distinction (absent vs failed vs valid — see AGENTS.md) as an explicit status:// 'unreadable' → the meatspace config could not be read/parsed (getBirthDateStrict readable:false)// 'unset' → no birthDate on record// 'invalid' → birthDate present but not a usable calendar date (unparseable, or andiff --git a/server/services/cosAgentLifecycle.js b/server/services/cosAgentLifecycle.jsindex 1fd3537863..727b9579df 100644--- a/server/services/cosAgentLifecycle.js+++ b/server/services/cosAgentLifecycle.js@@ -306,7 +306,7 @@ const OUTPUT_FLUSH_INTERVAL_MS = 250;// Debounced per-agent output batcher. Wraps appendAgentOutputLines with a// ~250ms flush window so a hot streaming producer triggers one state load+save// per window instead of per line — the write-amplification guard documented in-// CLAUDE.md ("High-frequency state writes must batch"). The TUI spawner rolls+// AGENTS.md ("High-frequency state writes must batch"). The TUI spawner rolls// its own equivalent inline because it co-flushes an output.txt appendFile in// the same batch; producers that only need the state write should use this.//@@ -324,7 +324,7 @@ export function createAgentOutputBatcher(agentId, { intervalMs = OUTPUT_FLUSH_INpending = [];// Swallow+log state-write failures so neither the debounced timer nor a// caller's `await flush()` ever rejects — this runs in child-process /- // timer callbacks where an uncaught throw would crash Node (CLAUDE.md "No+ // timer callbacks where an uncaught throw would crash Node (AGENTS.md "No// try/catch" exception). The authoritative transcript lives in output.txt;// a dropped live-tail batch is non-fatal. Mirrors the TUI spawner's// `.catch(() => {})` on its own batched append.diff --git a/server/services/cosState.js b/server/services/cosState.jsindex 19942625d6..cefbc0424f 100644--- a/server/services/cosState.js+++ b/server/services/cosState.js@@ -22,7 +22,7 @@ export const ROOT_DIR = PATHS.root;// Serialize every state.json read-merge-write on a single tail so two// concurrent loadState→modify→saveState cycles can't interleave and clobber// each other. Standardized on `createFileWriteQueue` — the documented-// single-JSON-file write-serialization convention (CLAUDE.md; same mechanism+// single-JSON-file write-serialization convention (AGENTS.md; same mechanism// settings.js and the issues/series/mediaCollections stores use) — instead of a// bespoke async mutex. Identical `(fn) => Promise` contract, so the ~34 existing// `withStateLock(...)` call sites are unchanged; the name is kept for thatdiff --git a/server/services/cosTaskStore.js b/server/services/cosTaskStore.jsindex 879c0e8946..beafe7ee93 100644--- a/server/services/cosTaskStore.js+++ b/server/services/cosTaskStore.js@@ -127,7 +127,7 @@ function isContentEdit(updates, existingMetadata = {}) {// Cache the parsed array per file so an unchanged file costs one `stat` plus a// structured clone instead of a read + full parse.//-// One server process, one user (CLAUDE.md trust model) — no locking, no atomic+// One server process, one user (AGENTS.md trust model) — no locking, no atomic// write dance. Correctness rests on two independent invalidation signals://// 1. The stamp (`mtimeMs` + `size`) catches writes this module did NOT make —@@ -637,7 +637,7 @@ async function writeTaskUpdate(taskId, updates, taskType, { now }) {// Handle legacy fields that may be passed directly in updates. Use ?? not ||// so an intentional clear to "" is preserved as "" rather than dropped: || maps// every falsy value (incl. "") to undefined, which the cleanup pass below then- // deletes, conflating "cleared" with "absent" (absent-vs-cleared, CLAUDE.md).+ // deletes, conflating "cleared" with "absent" (absent-vs-cleared, AGENTS.md).// Only null becomes undefined (→ deleted); absent fields never enter this loop.for (const f of LEGACY_DIRECT_FIELDS) {if (updates[f] !== undefined) updatedMetadata[f] = updates[f] ?? undefined;diff --git a/server/services/creativeCommissions/scheduler.js b/server/services/creativeCommissions/scheduler.jsindex cd0a719907..e705cb7a13 100644--- a/server/services/creativeCommissions/scheduler.js+++ b/server/services/creativeCommissions/scheduler.js@@ -10,7 +10,7 @@* - re-reads the commission + autonomy config on every fire (only the cron is* captured at registration).*- * Cold-bootstrap compliance (CLAUDE.md AI Provider Usage Policy): a commission is+ * Cold-bootstrap compliance (AGENTS.md AI Provider Usage Policy): a commission is* a user-configured scheduled automation — the sanctioned exception. `start…()`* only ARMS crons; nothing fires until the cadence elapses. The fire handler* additionally gates on creative autonomy mode === 'execute' AND the daily cosdiff --git a/server/services/creativeCommissions/store.js b/server/services/creativeCommissions/store.jsindex bff427b999..d5691ec499 100644--- a/server/services/creativeCommissions/store.js+++ b/server/services/creativeCommissions/store.js@@ -644,7 +644,7 @@ export async function updateCommission(id, patch) {// Serialize the load→merge→save on the per-id write queue so a concurrent// scheduler fire (recordCommissionRun, also queued) can't have its run-history// append clobbered by a stale pre-read here — the scheduler-vs-request race- // CLAUDE.md requires serializing at the record level.+ // AGENTS.md requires serializing at the record level.const merged = await store.queueRecordWrite(id, async () => {const currentRaw = await store.readRaw(id);if (!currentRaw) return null;diff --git a/server/services/creativeDirector/deliverableGate.js b/server/services/creativeDirector/deliverableGate.jsindex b83a0860d5..d6264839bf 100644--- a/server/services/creativeDirector/deliverableGate.js+++ b/server/services/creativeDirector/deliverableGate.js@@ -24,7 +24,7 @@* has come back empty, so the caller can stop re-dispatching and surface a* blocked stage instead of burning the provider indefinitely.*- * Sentinel discipline (root CLAUDE.md): `undefined` = no baseline recorded (a run+ * Sentinel discipline (root AGENTS.md): `undefined` = no baseline recorded (a run* enqueued before this change) and `null` = recorded-and-absent are DISTINCT.* Collapsing them would either mis-fail every legacy run or mis-pass every empty* one.diff --git a/server/services/creativeDirector/sceneRunner.js b/server/services/creativeDirector/sceneRunner.jsindex e5a53a21f7..9728e765dc 100644--- a/server/services/creativeDirector/sceneRunner.js+++ b/server/services/creativeDirector/sceneRunner.js@@ -410,7 +410,7 @@ async function handleRenderCompleted(projectId, sceneId, jobId, opts = {}) {return [];});// Re-check immediately before the agent-task enqueue. Single-user- // single-instance app per CLAUDE.md, but pause IS a real user action+ // single-instance app per AGENTS.md, but pause IS a real user action// and the API roundtrip can land between this read and the enqueue// below. The cost of one extra read is trivial vs. spending an agent// run on work the user explicitly canceled.diff --git a/server/services/dashboardLayouts.js b/server/services/dashboardLayouts.jsindex 0d7a3d6f6d..8396ba6fab 100644--- a/server/services/dashboardLayouts.js+++ b/server/services/dashboardLayouts.js@@ -396,7 +396,7 @@ export async function getState() {// concurrent writers (e.g. an auto-window-activate PUT + a manual layout// save firing from the same browser, or palette + dashboard tabs) can't// interleave load → modify → write and lose each other's changes. Mirrors-// the `issueWriteTail` / `cacheWriteTails` pattern documented in CLAUDE.md+// the `issueWriteTail` / `cacheWriteTails` pattern documented in AGENTS.md// ("Async PATCH races on shared records — serialize writes server-side").let layoutsWriteTail = Promise.resolve();const queueLayoutsWrite = (fn) => {@@ -430,7 +430,7 @@ export function saveLayout(layout) {// doesn't include the key, but cleared when the caller sends `null`. The// existing editor's saveLayout() doesn't send activateWindow, so a vanilla// widget edit must NOT wipe a previously-configured morning window.- // Mirrors the "absent vs intentionally empty" convention in CLAUDE.md.+ // Mirrors the "absent vs intentionally empty" convention in AGENTS.md.const existing = idx >= 0 ? state.layouts[idx] : null;const buildEntry = () => {const entry = {diff --git a/server/services/digital-twin-adversarial-testing.js b/server/services/digital-twin-adversarial-testing.jsindex ccc204b948..dfa3eb4b41 100644--- a/server/services/digital-twin-adversarial-testing.js+++ b/server/services/digital-twin-adversarial-testing.js@@ -119,7 +119,7 @@ export async function runAdversarialTests(providerId, model, testIds = null, per};// Reuse the meta loaded above — single-process, so nothing else mutated it- // while the scenario loop ran (cf. the trust model in CLAUDE.md).+ // while the scenario loop ran (cf. the trust model in AGENTS.md).if (!Array.isArray(meta.adversarialTestHistory)) meta.adversarialTestHistory = [];meta.adversarialTestHistory.unshift(historyEntry);meta.adversarialTestHistory = meta.adversarialTestHistory.slice(0, 50); // Keep last 50 runsdiff --git a/server/services/digital-twin-export.js b/server/services/digital-twin-export.jsindex d0667e2ca1..705e53cce5 100644--- a/server/services/digital-twin-export.js+++ b/server/services/digital-twin-export.js@@ -14,7 +14,7 @@ import { estimateTokens } from '../lib/contextBudget.js';export function getExportFormats() {return [{ id: 'system_prompt', label: 'System Prompt', description: 'Combined markdown for direct injection' },- { id: 'claude_md', label: 'CLAUDE.md', description: 'Format for Claude Code integration' },+ { id: 'agents_md', label: 'AGENTS.md', description: 'Format for agent-instructions files (AGENTS.md / CLAUDE.md)' },{ id: 'json', label: 'JSON', description: 'Structured JSON for API integration' },{ id: 'individual', label: 'Individual Files', description: 'Separate files for each document' },{ id: 'legacy_portrait', label: 'Legacy Portrait', description: 'Comprehensive human-readable identity document' }@@ -55,8 +55,11 @@ export async function exportDigitalTwin(format, documentIds = null, includeDisabswitch (format) {case 'system_prompt':return exportAsSystemPrompt(documentsWithContent);+ // 'claude_md' is the pre-#4852 id, still accepted so a persisted export+ // preference keeps resolving instead of throwing 'Unknown export format'.+ case 'agents_md':case 'claude_md':- return exportAsClaudeMd(documentsWithContent);+ return exportAsAgentsMd(documentsWithContent);case 'json':return exportAsJson(documentsWithContent);case 'individual':@@ -86,7 +89,7 @@ function exportAsSystemPrompt(docs) {};}-function exportAsClaudeMd(docs) {+function exportAsAgentsMd(docs) {let output = '# Soul - User Identity\n\n';output += '> This section defines the identity, values, and preferences of the user.\n\n';@@ -97,7 +100,7 @@ function exportAsClaudeMd(docs) {}return {- format: 'claude_md',+ format: 'agents_md',content: output.trim(),documentCount: docs.length,tokenEstimate: estimateTokens(output)diff --git a/server/services/digital-twin-multi-turn-testing.js b/server/services/digital-twin-multi-turn-testing.jsindex 4bf8f6fb13..b7b5c734fe 100644--- a/server/services/digital-twin-multi-turn-testing.js+++ b/server/services/digital-twin-multi-turn-testing.js@@ -148,7 +148,7 @@ export async function runMultiTurnTests(providerId, model, testIds = null, perso};// Reuse the meta loaded above — single-process, so nothing else mutated it- // while the scenario loop ran (cf. the trust model in CLAUDE.md).+ // while the scenario loop ran (cf. the trust model in AGENTS.md).if (!Array.isArray(meta.multiTurnTestHistory)) meta.multiTurnTestHistory = [];meta.multiTurnTestHistory.unshift(historyEntry);meta.multiTurnTestHistory = meta.multiTurnTestHistory.slice(0, 50); // Keep last 50 runsdiff --git a/server/services/digital-twin-values-testing.js b/server/services/digital-twin-values-testing.jsindex 22f141d292..84ee02aae5 100644--- a/server/services/digital-twin-values-testing.js+++ b/server/services/digital-twin-values-testing.js@@ -135,7 +135,7 @@ export async function runValuesAlignmentTests(providerId, model, testIds = null,};// Reuse the meta loaded above — single-process, so nothing else mutated it- // while the dilemma loop ran (cf. the trust model in CLAUDE.md).+ // while the dilemma loop ran (cf. the trust model in AGENTS.md).if (!Array.isArray(meta.valuesTestHistory)) meta.valuesTestHistory = [];meta.valuesTestHistory.unshift(historyEntry);meta.valuesTestHistory = meta.valuesTestHistory.slice(0, 50); // Keep last 50 runsdiff --git a/server/services/digital-twin.test.js b/server/services/digital-twin.test.jsindex 15854868ec..0f80deda0e 100644--- a/server/services/digital-twin.test.js+++ b/server/services/digital-twin.test.js@@ -1260,7 +1260,7 @@ Forgets the budget and recommends lodging that exceeds it.expect(formats).toHaveLength(5);const ids = formats.map(f => f.id);expect(ids).toContain('system_prompt');- expect(ids).toContain('claude_md');+ expect(ids).toContain('agents_md');expect(ids).toContain('json');expect(ids).toContain('individual');expect(ids).toContain('legacy_portrait');@@ -1298,14 +1298,25 @@ Forgets the budget and recommends lodging that exceeds it.expect(result.tokenEstimate).toBeGreaterThan(0);});- it('should export as claude_md format', async () => {+ it('should export as agents_md format', async () => {await setupExportMeta();- const result = await exportDigitalTwin('claude_md');- expect(result.format).toBe('claude_md');+ const result = await exportDigitalTwin('agents_md');+ expect(result.format).toBe('agents_md');expect(result.content).toContain('## Soul');expect(result.content).toContain('## Values');});+ it('still resolves the pre-#4852 claude_md id to the same export', async () => {+ // A persisted `format: 'claude_md'` on an existing install must keep+ // working — an alias, not a rename that throws 'Unknown export format'.+ await setupExportMeta();+ const legacy = await exportDigitalTwin('claude_md');+ await setupExportMeta();+ const current = await exportDigitalTwin('agents_md');+ expect(legacy.content).toBe(current.content);+ expect(legacy.format).toBe('agents_md');+ });+it('should export as json format', async () => {await setupExportMeta();const result = await exportDigitalTwin('json');diff --git a/server/services/github.js b/server/services/github.jsindex 6e14d889bd..b9d9febd5c 100644--- a/server/services/github.js+++ b/server/services/github.js@@ -325,7 +325,7 @@ export async function getStatus() {// Roughly thirty call sites across PortOS run `gh` and swallow the failure into// an empty result (`.catch(() => [])`). That collapses "the forge said there is// nothing" into "we could not ask the forge" — the exact conflation the root-// CLAUDE.md's sentinel-and-validate rule exists to prevent. In practice it means+// AGENTS.md's sentinel-and-validate rule exists to prevent. In practice it means// a `gh` that cannot reach api.github.com is indistinguishable from a quiet// repo: prWatcher sees no PRs, branchReconcile sees no branches, and an agent// told to open a PR reports success having opened nothing.diff --git a/server/services/gitlab.glabFlags.test.js b/server/services/gitlab.glabFlags.test.jsindex ed8d3e7f24..564e100375 100644--- a/server/services/gitlab.glabFlags.test.js+++ b/server/services/gitlab.glabFlags.test.js@@ -73,7 +73,7 @@ const PATTERNS = [//// `prompts.js` used to sit here too — a stored prompt default cannot be corrected// by editing the string alone, since each edit needs a PROMPT_VERSIONS bump plus-// the outgoing body preserved in PREVIOUS_DEFAULT_PROMPTS (CLAUDE.md+// the outgoing body preserved in PREVIOUS_DEFAULT_PROMPTS (AGENTS.md// "Distribution model"). Issue #4685 did that migration, so the current defaults// are now held to the same standard as every other server source. Prose in a// prompt body that merely EXPLAINS a trap still reads as an instance of it —diff --git a/server/services/gitlab.js b/server/services/gitlab.jsindex 66630caecc..bb0c19aa2a 100644--- a/server/services/gitlab.js+++ b/server/services/gitlab.js@@ -53,7 +53,7 @@ function execGlab(args, cwd, timeoutMs = DEFAULT_EXEC_GLAB_TIMEOUT_MS) {/*** Run a `glab … list` command and parse its JSON array. Three answers, not two —- * the absent-vs-empty split every caller needs (CLAUDE.md):+ * the absent-vs-empty split every caller needs (AGENTS.md):** - `ok` — glab answered; `rows` is the (possibly empty) array.* - `cli-failed` — we could not ask (non-zero exit: unauthenticated, nodiff --git a/server/services/goalScorecard.js b/server/services/goalScorecard.jsindex 6865d71c93..766b8b9884 100644--- a/server/services/goalScorecard.js+++ b/server/services/goalScorecard.js@@ -19,7 +19,7 @@* 2. **Optional LLM narrative (opt-in).** "This week you said X mattered but* spent 6× more time on Y." Behind the same provider config as the activity* digest (#2155) — silent until the user configures a provider AND clicks- * Refresh. See CLAUDE.md "AI Provider Usage Policy".+ * Refresh. See AGENTS.md "AI Provider Usage Policy".** The scorecard artifact lives under `data/insights/` alongside the cross-domain* insights caches. All reads are disk-only; compute is an explicit user action.diff --git a/server/services/huggingFaceRepoCache.js b/server/services/huggingFaceRepoCache.jsindex 4656b20545..7fb3a65a29 100644--- a/server/services/huggingFaceRepoCache.js+++ b/server/services/huggingFaceRepoCache.js@@ -111,7 +111,7 @@ function scheduleSave() {dirty = trueif (saveTimer) return// Outside the request lifecycle — a throw here would be unhandled, so the- // failure is logged and swallowed (per the root CLAUDE.md timer-callback rule).+ // failure is logged and swallowed (per the root AGENTS.md timer-callback rule).// A cache that fails to persist still works in memory; the next load refetches.saveTimer = setTimeout(() => {flush().catch((err) => console.error(`❌ Failed to persist Hugging Face repo cache: ${err.message}`))diff --git a/server/services/imageTo3d/db.js b/server/services/imageTo3d/db.jsindex 70b2ef94db..55fcfa1b27 100644--- a/server/services/imageTo3d/db.js+++ b/server/services/imageTo3d/db.js@@ -107,7 +107,7 @@ export async function deleteModel(id) {/*** A render child cannot survive the PortOS process. Mark interrupted records* failed-retryable on boot without launching any new render work (the GLB- * render is user-triggered only — CLAUDE.md no-cold-bootstrap policy).+ * render is user-triggered only — AGENTS.md no-cold-bootstrap policy).*/export async function recoverInterruptedModels() {const result = await query(diff --git a/server/services/imageTo3d/laneRunner.js b/server/services/imageTo3d/laneRunner.jsindex c3048d6386..2cf2a8a59f 100644--- a/server/services/imageTo3d/laneRunner.js+++ b/server/services/imageTo3d/laneRunner.js@@ -15,7 +15,7 @@** Everything here is a child-process boundary running OUTSIDE the request lifecycle,* so outcomes flow through events and rejected promises — never a throw into Express- * (CLAUDE.md child-process exception).+ * (AGENTS.md child-process exception).*/import { execFile, spawn } from '../../lib/childProcess.js';@@ -38,7 +38,7 @@ export const PYTHON_MODULE_PROBE_SOURCE = 'import importlib.util as u,json,sys;'* set, and only the CLASSIFICATION of the answer is lane-specific (TRELLIS.2 maps it* to a texture-bake quality, Pixal3D to a NAF availability). Returns `null` — never a* partial map — when the probe could not run, so callers can keep "failed to- * determine" distinct from "determined to be missing" (CLAUDE.md sentinel rule).+ * determine" distinct from "determined to be missing" (AGENTS.md sentinel rule).** Child-process boundary outside the request lifecycle: every failure path resolves.* Note the JSON parse happens AFTER the callback resolves rather than inside it — adiff --git a/server/services/imageTo3d/models.js b/server/services/imageTo3d/models.jsindex 3387107d5c..4bacb5ac1e 100644--- a/server/services/imageTo3d/models.js+++ b/server/services/imageTo3d/models.js@@ -10,7 +10,7 @@** The render NEVER auto-runs: it is only reached from an explicit user create /* generate request, and it is gated on the target being installed + runnable on- * this host (CLAUDE.md no-cold-bootstrap AI policy + the host's sensitivity to+ * this host (AGENTS.md no-cold-bootstrap AI policy + the host's sensitivity to* sustained GPU load). Adding a second target is a registration in `adapters.js`,* not a rewrite here.*/diff --git a/server/services/imageTo3d/models.test.js b/server/services/imageTo3d/models.test.jsindex 99f43e4ce7..d7323964cd 100644--- a/server/services/imageTo3d/models.test.js+++ b/server/services/imageTo3d/models.test.js@@ -190,7 +190,7 @@ describe('image-to-3D model orchestration', () => {const result = await recoverInterruptedModels();expect(result).toEqual({ recovered: 2 });// The whole point of boot recovery: mark interrupted renders failed-retryable- // WITHOUT relaunching any GPU work (CLAUDE.md no-cold-bootstrap policy).+ // WITHOUT relaunching any GPU work (AGENTS.md no-cold-bootstrap policy).expect(runTrellis2Generate).not.toHaveBeenCalled();});diff --git a/server/services/imageTo3d/pixal3dCuda.js b/server/services/imageTo3d/pixal3dCuda.jsindex fd4f943836..8c15304f69 100644--- a/server/services/imageTo3d/pixal3dCuda.js+++ b/server/services/imageTo3d/pixal3dCuda.js@@ -12,7 +12,7 @@* Everything is either pure or exercised through injectable `exists`/`spawnImpl`, so* the wiring is unit-testable WITHOUT an NVIDIA box, a ~40 GB install, or a live* render. `runPixal3dCudaGenerate` is the one real subprocess boundary and NEVER- * auto-runs (CLAUDE.md no-cold-bootstrap policy).+ * auto-runs (AGENTS.md no-cold-bootstrap policy).** **Four things differ from the TRELLIS.2 CUDA lane, and each drives the design:***@@ -261,7 +261,7 @@ const [PIXAL3D_RES_FLOOR, PIXAL3D_RES_FULL] = PIXAL3D_RESOLUTIONS;* - otherwise → the floor resolution with `--low_vram`, the least this lane supports.** An unknown/unparseable VRAM reading degrades to the floor rather than overcommitting- * a card we failed to size (CLAUDE.md sentinel rule).+ * a card we failed to size (AGENTS.md sentinel rule).** @param {number|null} vramGb* @returns {{lowVram: boolean, resolution: number}}@@ -410,7 +410,7 @@ export const PIXAL3D_NAF_FALLBACK_HELP = 'Pixal3D is installed, but NATTEN is mi* `isPixal3dNafError` classifies the failure into an actionable message. Reported as* `'unknown'` when the probe itself could not run — deliberately distinct from* `'unavailable'`, so a broken probe never renders a warning about a fine install- * (CLAUDE.md sentinel rule: "failed to determine" ≠ "determined to be bad").+ * (AGENTS.md sentinel rule: "failed to determine" ≠ "determined to be bad").** @param {{execFileImpl?: Function, exists?: (p: string) => boolean,* env?: NodeJS.ProcessEnv}} [opts]diff --git a/server/services/imageTo3d/targets.js b/server/services/imageTo3d/targets.jsindex 93a4a88997..832c2376a8 100644--- a/server/services/imageTo3d/targets.js+++ b/server/services/imageTo3d/targets.js@@ -295,7 +295,7 @@ export function unavailableReason(target, caps = {}) {// told the one thing it can actually act on.if (!caps.cuda) {// "The probe couldn't run" is not "there is no GPU" — never report absent- // hardware we failed to look for (CLAUDE.md sentinel rule).+ // hardware we failed to look for (AGENTS.md sentinel rule).return caps.cudaProbe === 'unknown' ? 'cuda-probe-failed' : 'requires-cuda';}if (req.linuxHost && !caps.linuxHost) return 'requires-linux-host';diff --git a/server/services/imageTo3d/trellis2.js b/server/services/imageTo3d/trellis2.jsindex daf0991eaa..b07956d2d3 100644--- a/server/services/imageTo3d/trellis2.js+++ b/server/services/imageTo3d/trellis2.js@@ -8,7 +8,7 @@* so the wiring is unit-testable **without** downloading the ~15 GB model or running* a live GPU render. `runTrellis2Generate` is the one real-subprocess boundary and* NEVER auto-runs — it throws unless the model is installed and is only reached from- * an explicit user action (CLAUDE.md no-cold-bootstrap policy). The exact wording of+ * an explicit user action (AGENTS.md no-cold-bootstrap policy). The exact wording of* `generate.py`'s progress output is refined during hands-on validation, so the* parser keys on format-agnostic signals (a percentage, a `.glb` path) rather than* guessing internal stage names.@@ -149,7 +149,7 @@ export const TRELLIS2_FALLBACK_BAKE_HELP = 'TRELLIS.2 is installed, but its Meta* confetti surface described in `TRELLIS2_FALLBACK_BAKE_HELP`), or `'unknown'` when* the probe itself could not run — deliberately distinct from `'fallback'` so a* broken probe never renders a scary warning about a possibly-fine install- * (CLAUDE.md sentinel rule: "failed to determine" ≠ "determined to be bad").+ * (AGENTS.md sentinel rule: "failed to determine" ≠ "determined to be bad").** @param {{base?: string, execFileImpl?: Function, exists?: (p: string) => boolean}} [opts]* @returns {Promise<{quality: 'metal'|'fallback'|'unknown', modules: Record<string, boolean>,@@ -241,7 +241,7 @@ export async function probeMetalToolchain({} = {}) {if (platformImpl() !== 'darwin') return { available: null };// Subprocess boundary outside the request lifecycle — every outcome resolves,- // nothing throws into the route (CLAUDE.md child-process exception).+ // nothing throws into the route (AGENTS.md child-process exception).const run = (command, args) => new Promise((resolve) => {execFileImpl(command, args, { timeout: 15000 }, (err, stdout) => {resolve(err ? null : String(stdout ?? ''));@@ -920,7 +920,7 @@ export const TRELLIS2_WATCHDOG_HELP = 'The macOS GPU watchdog stopped this rende* "run nothing"**. That is not incidental: a parameter default only applies to* `undefined`, so `null` already meant this before the fallback became computed,* and using `??` here would quietly turn it back into force-opaque — absent vs.- * explicitly-empty, per CLAUDE.md.+ * explicitly-empty, per AGENTS.md.* - Otherwise force-opaque applies unless the caller asked the exporter for a* transparent material. The rewrite still defaults on because an older o_voxel* promoted to BLEND off a single low-alpha texel, which is what it was written for.diff --git a/server/services/imageTo3d/trellis2Cuda.js b/server/services/imageTo3d/trellis2Cuda.jsindex eacb7d8528..d39998295d 100644--- a/server/services/imageTo3d/trellis2Cuda.js+++ b/server/services/imageTo3d/trellis2Cuda.js@@ -10,7 +10,7 @@* `exists`/`spawnImpl`, so the wiring is unit-testable WITHOUT a 24 GB NVIDIA box, a* ~15 GB weight download, or a live render. `runTrellis2CudaGenerate` is the one real* subprocess boundary and NEVER auto-runs: it rejects unless the model is installed,- * and is only reached from an explicit user action (CLAUDE.md no-cold-bootstrap policy).+ * and is only reached from an explicit user action (AGENTS.md no-cold-bootstrap policy).** **Two things differ from the MPS lane, and both drive the design here:***diff --git a/server/services/imageTo3d/trellis2GenerateRunner.test.js b/server/services/imageTo3d/trellis2GenerateRunner.test.jsindex cfa2eb81cc..bac793c3af 100644--- a/server/services/imageTo3d/trellis2GenerateRunner.test.js+++ b/server/services/imageTo3d/trellis2GenerateRunner.test.js@@ -313,7 +313,7 @@ describe.skipIf(!pyBin)('trellis2RestoreFillHoles', () => {// Python's `write_text` translates \n to the platform line ending, so the patched// file is CRLF on Windows while Node's readFileSync returns the raw bytes. A// `\n\s+` regex then cannot match — this failed ONLY on the Windows CI runner and- // passed locally. Normalizing is the convention root CLAUDE.md prescribes for+ // passed locally. Normalizing is the convention root AGENTS.md prescribes for// exactly this class of failure.const readNormalized = () => readFileSync(basePath(), 'utf8').replace(/\r\n?/g, '\n');diff --git a/server/services/importer.js b/server/services/importer.jsindex c61a8058c2..fe9876a672 100644--- a/server/services/importer.js+++ b/server/services/importer.js@@ -243,7 +243,7 @@ const ARC_POSITION_MAX = 9999;* throws ERR_VALIDATION if that would exceed SEASON_NUMBER_MAX (99).* - Where the assigned number matches an existing season, the existing* season's id (+ timestamps) are preserved — re-import is a metadata- * refresh, not a new season. **String-field merge follows CLAUDE.md's+ * refresh, not a new season. **String-field merge follows AGENTS.md's* "absent vs intentionally empty" rule**: `undefined`/`null` preserves* the existing value; an empty string `""` is treated as an intentional* clear and applied. `updatedAt` bumps when any tracked field@@ -292,7 +292,7 @@ export function mergeSeasons(existingSeasons, incomingSeasons, buildSeasonImpl =const nowIso = new Date().toISOString();// String-field merge: absent (`undefined`/`null`) preserves the existing// value; everything else — including `""` — is the user's intent and is- // applied verbatim. Mirrors the CLAUDE.md "distinguish absent vs+ // applied verbatim. Mirrors the AGENTS.md "distinguish absent vs// intentionally empty" rule so a Review-phase blank-out actually clears.const mergeStr = (incoming, existing) => (incoming == null ? (existing ?? '') : incoming);const incomingBuilt = incomingSeasons.map((s) => {diff --git a/server/services/importer.test.js b/server/services/importer.test.jsindex f9160cff13..b891699bf3 100644--- a/server/services/importer.test.js+++ b/server/services/importer.test.js@@ -1703,7 +1703,7 @@ describe('mergeSeasons (pure helper)', () => {expect(newNumbers).toEqual([4, 5]);});- // Round-7 review: distinguish absent-vs-empty per CLAUDE.md's "LLM+ // Round-7 review: distinguish absent-vs-empty per AGENTS.md's "LLM// response merging" convention. An empty string is the user's intent// to clear the field; null/undefined is the LLM omitting it and the// existing value should win.diff --git a/server/services/insightsService.js b/server/services/insightsService.jsindex 83f3123633..b479e420a4 100644--- a/server/services/insightsService.js+++ b/server/services/insightsService.js@@ -229,7 +229,7 @@ export async function callProviderAISimple(provider, model, prompt, { temperatur// EXPORTED FUNCTIONS// =============================================================================//-// LLM TRIGGER CONTRACT (no-cold-bootstrap policy — see CLAUDE.md "AI Provider+// LLM TRIGGER CONTRACT (no-cold-bootstrap policy — see AGENTS.md "AI Provider// Usage Policy"). The insights source data (genome, blood tests, taste profile,// Apple Health) is sensitive, so provider calls must be *explicitly* user-driven://diff --git a/server/services/jira.js b/server/services/jira.jsindex b7624e965b..bfcf668846 100644--- a/server/services/jira.js+++ b/server/services/jira.js@@ -278,7 +278,7 @@ export async function createTicket(instanceId, ticketData) {/*** Search JIRA issues by an arbitrary JQL string. STRICT variant — lets fetch* errors bubble so a caller can distinguish a transient API failure from a- * legitimately empty result set (the CLAUDE.md sentinel rule). `fields` selects+ * legitimately empty result set (the AGENTS.md sentinel rule). `fields` selects* the returned issue fields; `maxResults` caps the page.** Returns `[{ key, summary, description, status, statusCategory, labels, updated, url }]`.@@ -443,7 +443,7 @@ export async function transitionTicket(instanceId, ticketId, transitionId) {* Fetch tickets assigned to the current user in the active sprint for a project —* STRICT variant that lets fetch errors bubble. Used by the issue-reconcile JIRA* gatherer, which must distinguish a transient API failure (skip, don't park) from- * a legitimately empty sprint ([], a valid answer) — the sentinel rule in CLAUDE.md.+ * a legitimately empty sprint ([], a valid answer) — the sentinel rule in AGENTS.md.* The UI-facing `getMyCurrentSprintTickets` wraps this and swallows to [] instead.*/export async function fetchMyCurrentSprintTickets(instanceId, projectKey) {diff --git a/server/services/layeredIntelligence/forgeFiler.js b/server/services/layeredIntelligence/forgeFiler.jsindex d55462158e..1967646911 100644--- a/server/services/layeredIntelligence/forgeFiler.js+++ b/server/services/layeredIntelligence/forgeFiler.js@@ -67,7 +67,7 @@ export function extractIssuePriority(labels = []) {* Returns `{ ok, issues }` — `ok:false` means the tracker read FAILED (CLI error* or unparseable output), which is NOT the same as "no existing issues" (`ok:true,* issues:[]`). The handler must NOT file when the read failed, or a transient- * `gh` blip would defeat dedup and file a duplicate (CLAUDE.md sentinel rule).+ * `gh` blip would defeat dedup and file a duplicate (AGENTS.md sentinel rule).*/export async function listForgeIssues({ cli, cwd, env, label = LI_LABEL, state = 'all', exec = runCli } = {}) {// glab lists open issues by default and needs `--all` to widen to every state;diff --git a/server/services/layeredIntelligence/planFiler.js b/server/services/layeredIntelligence/planFiler.jsindex 25dc9c58d9..54576783f9 100644--- a/server/services/layeredIntelligence/planFiler.js+++ b/server/services/layeredIntelligence/planFiler.js@@ -48,7 +48,7 @@ export async function appendProposalToPlan({ repoPath, appName, slug, title, bod* reconcile a completed PLAN proposal: `- [x] [lil-foo]` reads as `closed`,* `- [ ] [lil-foo]` as `open`.*- * Absent ≠ done (the CLAUDE.md sentinel rule): a bare tag with NO preceding+ * Absent ≠ done (the AGENTS.md sentinel rule): a bare tag with NO preceding* checkbox stays `open` (still tracked/suppressed) rather than collapsing to* `closed` — a missing checkbox must not silently make an item re-proposable.* A `closed` item carries no `closedAt` (PLAN.md checkboxes have no timestamp),diff --git a/server/services/layeredIntelligence/sources.js b/server/services/layeredIntelligence/sources.jsindex 21f76d0ad4..9921706251 100644--- a/server/services/layeredIntelligence/sources.js+++ b/server/services/layeredIntelligence/sources.js@@ -34,7 +34,7 @@ import { listJiraIssues, plannedWorkJql } from './jiraFiler.js';* a failed tracker read can never be mistaken for "this app has nothing planned" —* the two are opposite instructions to the reasoner (be conservative vs. the field* is wide open), and collapsing them is exactly the failure the sentinel rule in- * CLAUDE.md exists to prevent.+ * AGENTS.md exists to prevent.*/export function plannedWorkUnavailable(why) {return `${PLANNED_WORK_UNAVAILABLE_PREFIX} (${why}). Do NOT treat this as "nothing is planned" — this app may well have a committed backlog that simply could not be listed this run. Be conservative: prefer proposal: null over filing work that might already be in scope.`;diff --git a/server/services/layeredIntelligenceOutcomes.js b/server/services/layeredIntelligenceOutcomes.jsindex de757db389..4e436931ca 100644--- a/server/services/layeredIntelligenceOutcomes.js+++ b/server/services/layeredIntelligenceOutcomes.js@@ -14,7 +14,7 @@* so the store stays bounded — the same window the dedup guard already uses.** Runs OUTSIDE the request lifecycle (scheduler tick / agent completion), so per- * the CLAUDE.md no-try/catch rule the LI hooks own the async boundary; these+ * the AGENTS.md no-try/catch rule the LI hooks own the async boundary; these* helpers stay defensive (a failed read/write degrades to a recorded no-op) and* are gated behind the `sources.outcomes` config toggle by their callers.*/diff --git a/server/services/lmStudioManager.js b/server/services/lmStudioManager.jsindex 956dbae617..660bb7cec7 100644--- a/server/services/lmStudioManager.js+++ b/server/services/lmStudioManager.js@@ -341,7 +341,7 @@ async function loadModelWithArgs(modelId, args = []) {if (await checkLMStudioAvailable(true)) {const resident = await getLoadedModels(true).catch(() => [])// `[]` from `getLoadedModels` means "nothing is loaded" OR "both list- // endpoints failed" — the null-vs-empty sentinel trap in root CLAUDE.md, and+ // endpoints failed" — the null-vs-empty sentinel trap in root AGENTS.md, and// `getLastLoadedModelsError` is the module's own way out of it. An// untrustworthy list must not read as "not resident": that skips the unload,// `lms load` hands back the existing instance, and the previousdiff --git a/server/services/localLlm.js b/server/services/localLlm.jsindex 03b989e82e..b098091450 100644--- a/server/services/localLlm.js+++ b/server/services/localLlm.js@@ -583,7 +583,7 @@ const OLLAMA_CAPABILITY_BADGES = {* `null` for a NON-ARRAY input, which is what `/api/tags` gives: that listing* carries no capability flags at all, so nothing was reported and nothing is* known. Returning `[]` there would collapse "not probed" into "claims- * nothing" — the sentinel mistake root CLAUDE.md forbids — which rendered an+ * nothing" — the sentinel mistake root AGENTS.md forbids — which rendered an* empty badge row on the install catalog and made every capability test look* inapplicable. `/api/show` is what actually knows; an EMPTY array from it is a* real answer and stays `[]`.diff --git a/server/services/localModelAssessmentStore.js b/server/services/localModelAssessmentStore.jsindex ad96c22b3c..53a082869f 100644--- a/server/services/localModelAssessmentStore.js+++ b/server/services/localModelAssessmentStore.js@@ -5,7 +5,7 @@* Split out of `localModelAssessments.js` so the READ side has no path to a* provider. Two reasons that matters:*- * 1. **AI Provider Usage Policy** (root CLAUDE.md). Everything here touches+ * 1. **AI Provider Usage Policy** (root AGENTS.md). Everything here touches* disk (plus, on the run path, one cheap version probe). Nothing in this* file can reach an LLM, so importing it from a status/catalog read is safe* by construction rather than by review.diff --git a/server/services/localModelAssessmentSweep.js b/server/services/localModelAssessmentSweep.jsindex 0b8b54a877..0510e394e7 100644--- a/server/services/localModelAssessmentSweep.js+++ b/server/services/localModelAssessmentSweep.js@@ -25,7 +25,7 @@* identical, and a second queue could run concurrently with this one — which* would make every number either produced describe the contention.*- * ## AI Provider Usage Policy (root CLAUDE.md) — read before editing+ * ## AI Provider Usage Policy (root AGENTS.md) — read before editing** A sweep calls a provider once per queued measurement, so it is STRICTLY* user-triggered, the same as the single-model run:@@ -230,7 +230,7 @@ export function __resetSweep() {// The sweep loop runs OUTSIDE the request lifecycle — there is no `next(err)` to// bubble to, so an uncaught throw here would take the process down (root-// CLAUDE.md). Every model is individually caught, and the loop itself is wrapped.+// AGENTS.md). Every model is individually caught, and the loop itself is wrapped.//// It mutates the `run` it was handed, NOT the module-level `sweep`: a cancelled// queue is replaceable the moment it is cancelled, and a loop still winding downdiff --git a/server/services/localModelAssessments.js b/server/services/localModelAssessments.jsindex a33dd62bc0..3c465cb125 100644--- a/server/services/localModelAssessments.js+++ b/server/services/localModelAssessments.js@@ -14,7 +14,7 @@* was taken in. `lib/localModelAssessment.js` turns that evidence into a verdict* and an intent-specific ranking.*- * ## AI Provider Usage Policy (root CLAUDE.md) — read before editing+ * ## AI Provider Usage Policy (root AGENTS.md) — read before editing** Assessments call an LLM, so they are STRICTLY user-triggered. This module* mirrors the `initDrillCache` / `requestCacheFill` split fromdiff --git a/server/services/meatspace.js b/server/services/meatspace.jsindex c90ee5dbae..eb64e2cb82 100644--- a/server/services/meatspace.js+++ b/server/services/meatspace.js@@ -282,7 +282,7 @@ export async function getBirthDate() {}// Like getBirthDate, but reports whether the config read was TRUSTWORTHY (see-// readJSONFileStrict / CLAUDE.md's "Sentinel + validate" rule). A corrupt/unreadable+// readJSONFileStrict / AGENTS.md's "Sentinel + validate" rule). A corrupt/unreadable// config.json yields `{ birthDate: null, readable: false }` — distinct from a genuinely// unset date (`readable: true`) — so consumers (the character enrichment, #2757) can tell a// user "your birth date is unreadable, fix it" instead of "set your birth date". An ENOENTdiff --git a/server/services/meatspacePost.js b/server/services/meatspacePost.jsindex f3d8464f01..50c9a6a0f3 100644--- a/server/services/meatspacePost.js+++ b/server/services/meatspacePost.js@@ -271,7 +271,7 @@ const DEFAULT_CONFIG = {// (no-provider) modules the launcher can actually compose — mental math and// deterministic cognitive drills (issue #2100). LLM drills are deliberately// excluded: auto-enabling them would queue provider calls the user hasn't- // consented to (see CLAUDE.md's AI Provider Usage Policy) — a user who wants+ // consented to (see AGENTS.md's AI Provider Usage Policy) — a user who wants// wit/verbal drills in every session adds `llm-drills` here explicitly.// `memory` is intentionally NOT a default: composed memory practice is opt-in,// so existing installs keep exactly their prior daily session mix. Legacy@@ -297,7 +297,7 @@ const DEFAULT_CONFIG = {// Opt-in adaptive difficulty (default OFF). When enabled, math drills are// nudged harder/easier at generation time from recent scored performance.adaptive: { enabled: false },- // Opt-in daily reminder (default OFF, off-by-default per CLAUDE.md's+ // Opt-in daily reminder (default OFF, off-by-default per AGENTS.md's// single-user/no-surprise-background-behavior convention). When enabled,// meatspacePostReminder.js fires a deterministic (no-LLM) in-app notification// at `time` (HH:MM, user's configured timezone) if today's POST is incomplete.diff --git a/server/services/meatspacePostDrillCache.js b/server/services/meatspacePostDrillCache.jsindex 9df4033931..07de2b5020 100644--- a/server/services/meatspacePostDrillCache.js+++ b/server/services/meatspacePostDrillCache.js@@ -5,7 +5,7 @@* (0 cached) only fills via requestCacheFill(), which requires explicit user* consent (see meatspacePostRoutes.js). Once a type has been warmed at least* once, consuming a drill silently tops it back up in the background. Cache- * persists to disk. See "AI Provider Usage Policy" in CLAUDE.md.+ * persists to disk. See "AI Provider Usage Policy" in AGENTS.md.*/import { readFile } from 'fs/promises';@@ -177,7 +177,7 @@ export function getCacheStats() {* Explicitly requested cache fill — the only path allowed to perform a cold* fill (0 -> MAX_PER_TYPE). Called from the drill-cache/fill route after the* user has been prompted and picked a provider/model. See PortOS's- * no-cold-bootstrap-LLM-calls rule in CLAUDE.md.+ * no-cold-bootstrap-LLM-calls rule in AGENTS.md.** Types are filled sequentially, not in parallel — a single consented "fill* all" request must not turn into several concurrent LLM batches hammeringdiff --git a/server/services/meatspacePostMorse.js b/server/services/meatspacePostMorse.jsindex 070133daa9..7ee9b858c7 100644--- a/server/services/meatspacePostMorse.js+++ b/server/services/meatspacePostMorse.js@@ -75,7 +75,7 @@ async function saveMorseProgress(data) {// client at once; without this tail their load→mutate→save cycles interleave// and whichever saves last drops the other's change (the just-earned level, or// the just-finished round). atomicWrite makes each file write atomic but not the-// surrounding read-modify-write — see CLAUDE.md "serialize writes server-side".+// surrounding read-modify-write — see AGENTS.md "serialize writes server-side".let morseWriteTail = Promise.resolve();function withMorseWriteTail(fn) {const run = morseWriteTail.then(fn, fn);diff --git a/server/services/meatspacePostReminder.js b/server/services/meatspacePostReminder.jsindex d73bd9deba..929c6fcb4f 100644--- a/server/services/meatspacePostReminder.js+++ b/server/services/meatspacePostReminder.js@@ -5,7 +5,7 @@* (no LLM) in-app notification at a user-chosen time-of-day when today's POST* (Power On Self Test) session is still incomplete. Nothing here calls an AI* provider — the "scheduled automations are user-configured" exception in- * CLAUDE.md's AI Provider Usage Policy covers this even though it's moot, since+ * AGENTS.md's AI Provider Usage Policy covers this even though it's moot, since* this feature makes zero LLM calls of its own.** Mirrors backupScheduler.js's daily-cron registration pattern viadiff --git a/server/services/mediaAssetIndex/db.js b/server/services/mediaAssetIndex/db.jsindex edced24f12..3ffcaee2e8 100644--- a/server/services/mediaAssetIndex/db.js+++ b/server/services/mediaAssetIndex/db.js@@ -154,7 +154,7 @@ async function readListStrict(fn) {* for "nothing on disk" and wipe live rows whose files still exist; in that* case we upsert what we did read and skip pruning that kind, leaving the* existing rows until a later clean reconcile. (This is the absent-vs-empty- * sentinel rule from CLAUDE.md — failed-read ≠ legitimately-empty.)+ * sentinel rule from AGENTS.md — failed-read ≠ legitimately-empty.)** Idempotent: re-running with no disk changes is a no-op upsert + empty prune.* Cheap enough to run unconditionally at boot.diff --git a/server/services/mediaJobQueue/index.test.js b/server/services/mediaJobQueue/index.test.jsindex b4596f2e42..4d1e44783d 100644--- a/server/services/mediaJobQueue/index.test.js+++ b/server/services/mediaJobQueue/index.test.js@@ -586,7 +586,7 @@ describe('mediaJobQueue', () => {// reaches disk; this one proves the debounce, by counting writes. Without// it the test above would still pass if scheduleProgressPersist regressed// to a naive per-event persist() — the high-frequency-write antipattern- // CLAUDE.md forbids. We pin the coalescing by counting atomicWrite calls+ // AGENTS.md forbids. We pin the coalescing by counting atomicWrite calls// under a burst of N progress events (must be ≪ N within one window).const file = join(tempDataDir, 'media-jobs.json');const job = mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'burst' } });diff --git a/server/services/memory.js b/server/services/memory.jsindex 7f97fe1da8..b7d7d219b0 100644--- a/server/services/memory.js+++ b/server/services/memory.js@@ -176,7 +176,7 @@ export async function updateMemory(id, updates) {// Update summary if content changed. Gate on "is a string", not truthiness:// clearing content to "" is an intentional edit that must regenerate (clear)- // the summary, not leave the stale one behind (absent-vs-cleared, CLAUDE.md).+ // the summary, not leave the stale one behind (absent-vs-cleared, AGENTS.md).// The typeof check keeps null/undefined/absent out of generateSummary (which// would throw on .length) while still treating "" as a present-but-empty clear.if (typeof updates.content === 'string' && !updates.summary) {@@ -197,7 +197,7 @@ export async function updateMemory(id, updates) {// Update BM25 index if content or tags changed. Gate on shape, not truthiness:// clearing content to "" (a string) must reindex so the now-empty document// stops matching its old terms, and clearing tags to [] (Array.isArray) must- // reindex too (absent-vs-cleared, CLAUDE.md). null/undefined/absent are skipped.+ // reindex too (absent-vs-cleared, AGENTS.md). null/undefined/absent are skipped.if (typeof updates.content === 'string' || Array.isArray(updates.tags)) {memoryBM25.indexMemory({id: memory.id,diff --git a/server/services/memoryDB.js b/server/services/memoryDB.jsindex dc314796e8..74cbf9d7e5 100644--- a/server/services/memoryDB.js+++ b/server/services/memoryDB.js@@ -292,7 +292,7 @@ export async function updateMemory(id, updates) {// Update summary if content changed but no explicit summary. Gate on "is a// string" not truthiness, mirroring the file backend (memory.js) and keeping- // null/undefined out of generateSummary (absent-vs-cleared, CLAUDE.md).+ // null/undefined out of generateSummary (absent-vs-cleared, AGENTS.md).if (typeof updates.content === 'string' && !updates.summary) {fields.push(`summary = $${paramIdx++}`);params.push(generateSummary(updates.content));diff --git a/server/services/messageSync.js b/server/services/messageSync.jsindex 963fea609d..0dd37f5674 100644--- a/server/services/messageSync.js+++ b/server/services/messageSync.js@@ -385,7 +385,7 @@ export async function refreshMessage(accountId, messageId) {if (existing) {// Use ?? not ||: a genuinely empty-body message (body === '') is a valid// full extraction and must overwrite the old text, not collapse back to it- // (absent-vs-cleared, CLAUDE.md). Only an absent body (null/undefined) keeps+ // (absent-vs-cleared, AGENTS.md). Only an absent body (null/undefined) keeps// the prior text.existing.bodyText = threadMsg.body ?? existing.bodyText;existing.bodyFull = true;@@ -423,7 +423,7 @@ export async function refreshMessage(accountId, messageId) {// Update the original message too if it wasn't matched by externalIdif (!updatedMessages.find(m => m.id === message.id)) {// ?? not ||: an empty extracted body ('') is a valid clear, not a fall-back- // to the stale text (absent-vs-cleared, CLAUDE.md).+ // to the stale text (absent-vs-cleared, AGENTS.md).message.bodyText = detail[0]?.body ?? message.bodyText;message.bodyFull = true;if (!message.threadId) message.threadId = threadKey;diff --git a/server/services/modelCapabilityTestStore.js b/server/services/modelCapabilityTestStore.jsindex 75a568cc31..92e6a767ee 100644--- a/server/services/modelCapabilityTestStore.js+++ b/server/services/modelCapabilityTestStore.js@@ -4,7 +4,7 @@* Split from `modelCapabilityTests.js` for the same two reasons the assessment* store is split from its runner:*- * 1. **AI Provider Usage Policy** (root CLAUDE.md). Nothing in this file can+ * 1. **AI Provider Usage Policy** (root AGENTS.md). Nothing in this file can* reach a provider, so a read path that imports it is safe by construction* rather than by review.* 2. **No import cycle** — the report builder needs stored results, and thediff --git a/server/services/modelCapabilityTests.js b/server/services/modelCapabilityTests.jsindex ef4f67c247..89cfe3258a 100644--- a/server/services/modelCapabilityTests.js+++ b/server/services/modelCapabilityTests.js@@ -20,7 +20,7 @@** ## Rules this file exists to honour*- * 1. **No cold-bootstrap LLM calls** (root CLAUDE.md). `getCapabilityTestReport`+ * 1. **No cold-bootstrap LLM calls** (root AGENTS.md). `getCapabilityTestReport`* touches disk (plus, for Ollama, cached loopback capability probes) and* calls no provider, so it is safe from a poll or a page load.* `runCapabilityTest` is the ONLY path that reaches a model, and it firesdiff --git a/server/services/openWorldIntrospection.js b/server/services/openWorldIntrospection.jsindex a8bf8a7c28..054f4c04e3 100644--- a/server/services/openWorldIntrospection.js+++ b/server/services/openWorldIntrospection.js@@ -38,7 +38,7 @@ const toNumber = (v) => {// The database section. A down/unreachable DB yields `null` (absent), never a// hollow `{ tables: [] }` — the harbor renders "DB OFFLINE" instead of an empty-// quay (CLAUDE.md's absent-vs-empty rule).+// quay (AGENTS.md's absent-vs-empty rule).async function buildDbSection() {const tables = await query(`SELECT relname AS name,diff --git a/server/services/openWorldSnapshots.js b/server/services/openWorldSnapshots.jsindex bfc13e138f..815096dcc5 100644--- a/server/services/openWorldSnapshots.js+++ b/server/services/openWorldSnapshots.js@@ -58,7 +58,7 @@ const SNAPSHOTS_FILE = join(DATA_DIR, 'city-snapshots.jsonl');// Sentinel a getter falls back to when it throws — distinct from a successful// empty read. `null` for object/array sources means "source unavailable at-// capture time" (CLAUDE.md's absent-vs-empty rule), so a transient failure+// capture time" (AGENTS.md's absent-vs-empty rule), so a transient failure// never reads as a legitimate "zero apps / zero peers" in the history.const FAILED = null;@@ -145,7 +145,7 @@ function resolveAgentApp(agent, appStatuses) {* useful to a scrubber than a missing one. Crucially, a thrown getter records* `null` (source unavailable), NOT an empty array / zero count, so a transient* failure can't masquerade as a legitimate "zero apps / zero peers" in the- * history (CLAUDE.md's absent-vs-empty rule). Counts derived from a FAILED+ * history (AGENTS.md's absent-vs-empty rule). Counts derived from a FAILED* source are likewise `null`, distinct from a real `0` on a successful read.*/async function buildSnapshot() {diff --git a/server/services/pipeline/arcPlanner/arcCore.js b/server/services/pipeline/arcPlanner/arcCore.jsindex eeccd53f12..78df1f19e0 100644--- a/server/services/pipeline/arcPlanner/arcCore.js+++ b/server/services/pipeline/arcPlanner/arcCore.js@@ -156,7 +156,7 @@ export async function refineReaderMap(seriesId, feedback, options = {}) {const readerMap = sanitizeReaderMap({ ...content, status: 'draft' });// Refine is meant to PRESERVE — never let an empty LLM payload null out the// existing map. Fall back to the current reader map when the refine produced- // nothing usable (mirrors the CLAUDE.md absent-vs-empty rule).+ // nothing usable (mirrors the AGENTS.md absent-vs-empty rule).const safeReaderMap = readerMap || arc.readerMap || null;if (!safeReaderMap) {throw makeErr('LLM returned an empty reader map and there is none to preserve', ERR_VALIDATION);diff --git a/server/services/pipeline/continuityBible.js b/server/services/pipeline/continuityBible.jsindex 808a2d0ed3..8b0b08df50 100644--- a/server/services/pipeline/continuityBible.js+++ b/server/services/pipeline/continuityBible.js@@ -19,7 +19,7 @@* the LWW-merged series `index.json`. Two hashes pin the inputs so the UI flags* the ledger stale once either the manuscript (`sourceContentHash`) or the canon* (`sourceCanonHash`) changes. Writes serialize on a per-series tail (single- * tail per shared file, per CLAUDE.md). The SSE wrapper mirrors+ * tail per shared file, per AGENTS.md). The SSE wrapper mirrors* reverseOutline.js via lib/sseUtils.js.*/diff --git a/server/services/pipeline/filenameHookFactory.js b/server/services/pipeline/filenameHookFactory.jsindex 83fa273e1a..521af8dbd2 100644--- a/server/services/pipeline/filenameHookFactory.js+++ b/server/services/pipeline/filenameHookFactory.js@@ -11,7 +11,7 @@** `applyFilename(currentStage, parsed, job, filename)` returns either* { patch, label } → stage gets the patch; label is logged- * or `null` to skip (e.g. stale jobId after a re-render — see CLAUDE.md+ * or `null` to skip (e.g. stale jobId after a re-render — see AGENTS.md* "Pending socket-request tracking" for the same generation-aware idea).** Optional `onStamped({ parsed, job, filename, label })` fires once *after*diff --git a/server/services/pipeline/foundationJudge.js b/server/services/pipeline/foundationJudge.jsindex eea436283b..ff5d3fb3d2 100644--- a/server/services/pipeline/foundationJudge.js+++ b/server/services/pipeline/foundationJudge.js@@ -1173,7 +1173,7 @@ async function refineWorld(universeId, { providerId, model, effort, onRunCreated// null (or blank) for an OMITTED field, which is "nothing to add" — NOT a// clear. Writing it would erase the existing unlocked value (sanitize turns a// non-string into ''). Skip locked fields AND absent/blank ones; preserve the- // current value in both cases (the CLAUDE.md absent-vs-empty rule).+ // current value in both cases (the AGENTS.md absent-vs-empty rule).const filled = (v) => typeof v === 'string' && v.trim() !== '';if (locked.logline !== true && filled(expanded.logline)) patch.logline = expanded.logline;if (locked.premise !== true && filled(expanded.premise)) patch.premise = expanded.premise;diff --git a/server/services/pipeline/issueCrud.js b/server/services/pipeline/issueCrud.jsindex 750131bfee..44e68f3874 100644--- a/server/services/pipeline/issueCrud.js+++ b/server/services/pipeline/issueCrud.js@@ -216,7 +216,7 @@ export function bulkReassignSeason(seriesId, fromSeasonId, toSeasonId = null, {return queueSeriesIssuesWrite(seriesId, async () => {// Honor per-season locks — refuse to move issues OUT of or INTO a locked// volume. Series lives in a different write queue, so this is best-effort- // single-user gating, not strict serialization (fine per CLAUDE.md).+ // single-user gating, not strict serialization (fine per AGENTS.md).// Callers that already hold a fresh series (e.g. `deleteSeason` reads it// for the reassign-target validation) can pass `_preloadedSeries` to skip// the duplicate read.diff --git a/server/services/pipeline/issueStages.js b/server/services/pipeline/issueStages.jsindex 93becb1737..8eb8a62f87 100644--- a/server/services/pipeline/issueStages.js+++ b/server/services/pipeline/issueStages.js@@ -169,7 +169,7 @@ export function updateStageWithLatest(issueId, stageId, computeFn, { snapshotPri// issue — both share one mutex per series. The per-record split (migrations// 035/036) otherwise left renumbers on the series queue and stage saves on// the per-id queue (two independent mutexes over the same shared resource);- // see CLAUDE.md "single tail per shared file". seriesId is immutable, so read+ // see AGENTS.md "single tail per shared file". seriesId is immutable, so read// it outside the lock to pick the queue, then re-read the issue INSIDE the// lock for the freshest stage.const work = async () => {diff --git a/server/services/pipeline/issuesShared.js b/server/services/pipeline/issuesShared.jsindex 81aef94507..0ae7146784 100644--- a/server/services/pipeline/issuesShared.js+++ b/server/services/pipeline/issuesShared.js@@ -502,7 +502,7 @@ export const AUDIO_MODES = Object.freeze(['per-clip', 'silent', 'generated', 'up// Read-side default: an absent / unknown audioMode collapses to 'per-clip' —// today's behavior — so an un-migrated record (or one synced from an older,// audioMode-unaware peer) reads correctly before migration 067 stamps the-// explicit value. Never let "absent" become a wrong mode (CLAUDE.md sentinel+// explicit value. Never let "absent" become a wrong mode (AGENTS.md sentinel// discipline).export const sanitizeAudioMode = (raw) => (AUDIO_MODES.includes(raw) ? raw : 'per-clip');diff --git a/server/services/pipeline/manuscriptReview.js b/server/services/pipeline/manuscriptReview.jsindex f1c3c52884..1eb6a651d8 100644--- a/server/services/pipeline/manuscriptReview.js+++ b/server/services/pipeline/manuscriptReview.js@@ -12,7 +12,7 @@* series folder on share/sync without bloating the LWW-merged series* `index.json` (the review is an independent, larger document with its own* write cadence). Writes serialize on a per-series tail (single tail per shared- * file, per CLAUDE.md).+ * file, per AGENTS.md).*/import { join } from 'path';diff --git a/server/services/pipeline/perspectiveRewrite.js b/server/services/pipeline/perspectiveRewrite.jsindex 78d79bcebf..a3e8b538c4 100644--- a/server/services/pipeline/perspectiveRewrite.js+++ b/server/services/pipeline/perspectiveRewrite.js@@ -13,7 +13,7 @@* editorialAnalysis.js). The canonical `stages.prose` draft is never touched —* the user folds insights back by hand. Each rewrite pins a `sourceContentHash`* so the UI can flag it stale once the analyzed draft changes. Per-issue writes- * serialize on a single tail (one tail per shared file, per CLAUDE.md).+ * serialize on a single tail (one tail per shared file, per AGENTS.md).** Errors bubble (no try/catch) — the route owns the request boundary.*/diff --git a/server/services/pipeline/reverseOutline.js b/server/services/pipeline/reverseOutline.jsindex 2149a94e4d..74e7a5617a 100644--- a/server/services/pipeline/reverseOutline.js+++ b/server/services/pipeline/reverseOutline.js@@ -14,7 +14,7 @@* bloating the LWW-merged series `index.json`. A `sourceContentHash` pins the* analyzed manuscript so the UI flags the outline as stale once the draft* changes. Writes serialize on a per-series tail (single tail per shared file,- * per CLAUDE.md).+ * per AGENTS.md).** The SSE wrapper at the bottom mirrors editorial/checkRunner.js: a single* in-memory runs map keyed by seriesId via lib/sseUtils.js.diff --git a/server/services/pipeline/seriesAutopilot/revisionSteps.js b/server/services/pipeline/seriesAutopilot/revisionSteps.jsindex ad6158cb01..2f47fa55c7 100644--- a/server/services/pipeline/seriesAutopilot/revisionSteps.js+++ b/server/services/pipeline/seriesAutopilot/revisionSteps.js@@ -237,7 +237,7 @@ export async function runRevisionCycle(sId, record) {}// 7. Record the cycle: post-cycle mean drives the plateau detector; the ledger- // line is the experiment log (single emoji line per the CLAUDE.md convention).+ // line is the experiment log (single emoji line per the AGENTS.md convention).record.runState.revisionCyclesRun = (record.runState.revisionCyclesRun || 0) + 1;const postSeriesJudge = await getSeriesJudge(sId, { issues: await listIssues({ seriesId: sId }) });const postMean = meanQualityScore(postSeriesJudge);diff --git a/server/services/pm2.js b/server/services/pm2.jsindex cc32994ab0..84e1a3feb7 100644--- a/server/services/pm2.js+++ b/server/services/pm2.js@@ -455,7 +455,7 @@ export async function listProcesses(pm2Home = null) {* `listProcesses()` flattens a failed read into `[]`, which is the right* forgiving behavior for log/command/voice callers that just want "whatever is* running." But app-status getters MUST distinguish "PM2 unreachable" from- * "nothing running" (CLAUDE.md absent-vs-empty rule) — collapsing them records+ * "nothing running" (AGENTS.md absent-vs-empty rule) — collapsing them records* a transient blip as every app `not_started`. Those callers use this instead.** @param {string} pm2Home Optional custom PM2_HOME pathdiff --git a/server/services/privacyBrokers.js b/server/services/privacyBrokers.jsindex b558b08e48..2398948af7 100644--- a/server/services/privacyBrokers.js+++ b/server/services/privacyBrokers.js@@ -10,7 +10,7 @@* ledger is additionally single-writer — two peers working the same broker* would double-submit opt-outs against it.*- * Boot policy (CLAUDE.md — no cold-bootstrap network/LLM): NOTHING here runs at+ * Boot policy (AGENTS.md — no cold-bootstrap network/LLM): NOTHING here runs at* server boot. The curated seed is loaded LAZILY from* data.reference/privacy/brokers.json on first read (`ensureSeeded`); the* `refreshBrokers()` network pull is user-triggered ONLY. Curated rowsdiff --git a/server/services/privacyTwinContext.test.js b/server/services/privacyTwinContext.test.jsindex 0613dacf53..168fc1b20d 100644--- a/server/services/privacyTwinContext.test.js+++ b/server/services/privacyTwinContext.test.js@@ -1,6 +1,6 @@/*** Unit tests for getPrivacyTwinContext (issue #2147). DB + crypto are mocked —- * this is a pure logic test, never touches a real Postgres (see CLAUDE.md+ * this is a pure logic test, never touches a real Postgres (see AGENTS.md* DB-test safety) and never runs as a *.db.test.js.*/diff --git a/server/services/providerPrerequisites.js b/server/services/providerPrerequisites.jsindex b251c51ce6..ed00fa4d21 100644--- a/server/services/providerPrerequisites.js+++ b/server/services/providerPrerequisites.js@@ -30,7 +30,7 @@* prevents.** No LLM call is made here. Probing a CLI is a `--version` spawn, so this is- * safe under the no-cold-bootstrap policy in CLAUDE.md.+ * safe under the no-cold-bootstrap policy in AGENTS.md.*/import { blocksRouting, describeMissingPrerequisites, providerPrerequisites, providerRuntimeKey } from '../lib/providerPrerequisites.js';diff --git a/server/services/providerReadiness.js b/server/services/providerReadiness.jsindex 8324237763..a4f5d89065 100644--- a/server/services/providerReadiness.js+++ b/server/services/providerReadiness.js@@ -30,7 +30,7 @@* neither probes this host for it nor offers to start it here.** No LLM call is ever made here — `GET /v1/models` is a listing, so this is safe- * to poll from a settings page under the no-cold-bootstrap policy in CLAUDE.md.+ * to poll from a settings page under the no-cold-bootstrap policy in AGENTS.md.*/import { localRuntimeForProvider } from '../lib/localProviderRuntime.js';diff --git a/server/services/quotaBurnRunner.js b/server/services/quotaBurnRunner.jsindex a254d891cc..c340a270a2 100644--- a/server/services/quotaBurnRunner.js+++ b/server/services/quotaBurnRunner.js@@ -25,7 +25,7 @@* resetting in 2h beat an `agy` window resetting in 21h on every single tick, so* the agy plan sat at "93% left · 0/5 used" indefinitely.*- * AI-policy posture (CLAUDE.md): this is a sanctioned scheduled automation —+ * AI-policy posture (AGENTS.md): this is a sanctioned scheduled automation —* disabled by default, armed only by an explicit opt-in on the Quota Burn page,* where the family, provider, model, and work are all named before anything* runs. Boot ARMS the interval; it never dispatches. With `enabled: false` thediff --git a/server/services/repoIntake.js b/server/services/repoIntake.jsindex b72b053549..979d98f162 100644--- a/server/services/repoIntake.js+++ b/server/services/repoIntake.js@@ -13,7 +13,7 @@** Both are queued only AFTER the clone succeeds (there is nothing to read* before that), and only because the user asked for them in the same request —- * see the AI Provider Usage Policy in CLAUDE.md.+ * see the AI Provider Usage Policy in AGENTS.md.*/import { randomUUID } from 'crypto';diff --git a/server/services/rounds.js b/server/services/rounds.jsindex e838480cb2..9c8197bc8e 100644--- a/server/services/rounds.js+++ b/server/services/rounds.js@@ -6,7 +6,7 @@* the voice layers (lead / bass / harmony / drone / counter-melody) the user is* stacking — plus per-layer learning notes. Persisted to data/rounds.json.*- * Pure-ish CRUD over a single JSON file: PortOS is single-user (see CLAUDE.md+ * Pure-ish CRUD over a single JSON file: PortOS is single-user (see AGENTS.md* "Security Model"), so a per-file write queue serializes the read-modify-write* cycle rather than guarding against competing humans.*@@ -509,7 +509,7 @@ const seedTemplate = (id) => SEED_ROUNDS.find((s) => s.id === id) || null;// Serialize the read-modify-write cycle so two mutations issued back-to-back// (e.g. a rename PATCH followed by a layer edit) each merge against the freshest// persisted state instead of racing on a stale snapshot. Single-user, so this-// is re-entrancy hygiene, not a multi-actor lock (see CLAUDE.md Security Model).+// is re-entrancy hygiene, not a multi-actor lock (see AGENTS.md Security Model).const enqueue = createFileWriteQueue();// Pure read + sanitize — NO write side effect. When the file is absent ordiff --git a/server/services/sharing/index.js b/server/services/sharing/index.jsindex 754ac1d75f..274e18b13b 100644--- a/server/services/sharing/index.js+++ b/server/services/sharing/index.js@@ -36,7 +36,7 @@ let mediaLibraryKickoff = null;function startMediaLibrarySweep() {// Timer callbacks run OUTSIDE the request lifecycle — an uncaught throw here- // crashes the process (CLAUDE.md). Each sweep already catches per-peer; this+ // crashes the process (AGENTS.md). Each sweep already catches per-peer; this// guards a synchronous throw before the awaits begin.const tick = () => {try {diff --git a/server/services/sharing/peerCosSync.js b/server/services/sharing/peerCosSync.jsindex c81b7e96c2..7262a9fd47 100644--- a/server/services/sharing/peerCosSync.js+++ b/server/services/sharing/peerCosSync.js@@ -64,7 +64,7 @@ function cosAgentsDir() {// Cap so a pathologically large history can't build an unbounded manifest. Each// agent contributes up to 3 files; 150k entries ≈ 50k agents, far beyond any-// realistic single-user history. When exceeded we LOG + truncate (CLAUDE.md "no+// realistic single-user history. When exceeded we LOG + truncate (AGENTS.md "no// silent caps"). Kept in sync with the `entries` cap in peerCosHistoryManifestSchema.// Chosen so the worst-case serialized manifest (~180 bytes/entry ≈ 27MB) stays// UNDER COS_HISTORY_MANIFEST_MAX_BYTES below — otherwise this sender-sidediff --git a/server/services/sharing/peerMediaLibrarySync.js b/server/services/sharing/peerMediaLibrarySync.jsindex ddc8182313..282efd260e 100644--- a/server/services/sharing/peerMediaLibrarySync.js+++ b/server/services/sharing/peerMediaLibrarySync.js@@ -76,7 +76,7 @@ const MEDIA_LIBRARY_KIND_DIRNAMES = Object.freeze({// Cap so a pathologically large library can't build an unbounded manifest. 100k// assets is far beyond any realistic single-user library; when exceeded we LOG-// and truncate (per CLAUDE.md "no silent caps") rather than ship an open-ended+// and truncate (per AGENTS.md "no silent caps") rather than ship an open-ended// list. Pagination is a clean follow-up if ever hit. Kept in sync with the// `assets` array cap in peerLibraryManifestSchema.const MEDIA_LIBRARY_MANIFEST_CAP = 100_000;diff --git a/server/services/sharing/peerSyncAssets.js b/server/services/sharing/peerSyncAssets.jsindex c3bb79e2e3..7e02024bee 100644--- a/server/services/sharing/peerSyncAssets.js+++ b/server/services/sharing/peerSyncAssets.js@@ -746,7 +746,7 @@ export async function pullMissingAssetsFromPeer(senderInstanceId, missingAssets)if (!isStr(senderInstanceId) || !Array.isArray(missingAssets) || missingAssets.length === 0) return;// Trust posture: `senderInstanceId` arrives in the push payload (the route// is Tailnet-only per the project's documented threat model — see- // CLAUDE.md "Security Model"). We DON'T derive it from the TCP origin+ // AGENTS.md "Security Model"). We DON'T derive it from the TCP origin// because Express behind Tailscale loses that fidelity to the SO_REUSEADDR// socket. The guard below means even a payload that *spoofs* a different// peer's id can only redirect the asset pull at one of our OWN registereddiff --git a/server/services/sharing/watcher.js b/server/services/sharing/watcher.jsindex 04b16af19e..2f93b6e718 100644--- a/server/services/sharing/watcher.js+++ b/server/services/sharing/watcher.js@@ -76,7 +76,7 @@ export async function attachWatcher(bucketId) {// not a manifest to process. Manifests live in manifests/ (always *.json).const isBundleSync = (p) => p.includes(`${assetsDir}/`) || p.includes(`${recordsDir}/`);- // try/catch around async event handlers — see CLAUDE.md "PTY/child-process+ // try/catch around async event handlers — see AGENTS.md "PTY/child-process// /setTimeout/setInterval callbacks" rule (chokidar events fire outside the// request lifecycle, no Express middleware to bubble the throw to).w.on('add', async (path) => {diff --git a/server/services/socket.js b/server/services/socket.jsindex ac1a09d380..ef7f0898cd 100644--- a/server/services/socket.js+++ b/server/services/socket.js@@ -66,7 +66,7 @@ const streamKey = (socketId, processName) => `${socketId}:${processName}`;// bails and its client waits forever for `logs:subscribed`. Every claim and// release bumps this counter and a handler only resumes while its own generation// is current — the server-side mirror of the `{ target, generation }`-// pending-request convention in CLAUDE.md.+// pending-request convention in AGENTS.md.const streamGenerations = new Map();const bumpStreamGeneration = (key) => {const next = (streamGenerations.get(key) || 0) + 1;diff --git a/server/services/sprites/animationTrackCrud.js b/server/services/sprites/animationTrackCrud.jsindex 6ff5885138..0db8b534f9 100644--- a/server/services/sprites/animationTrackCrud.js+++ b/server/services/sprites/animationTrackCrud.js@@ -38,7 +38,7 @@** **The writes are serialized and the cache is invalidated.** One `data/` file, one* `createFileWriteQueue` tail, so a create landing while a delete is mid-flight- * cannot read a stale pre-image (the CLAUDE.md rule for a service that owns a single+ * cannot read a stale pre-image (the AGENTS.md rule for a service that owns a single* JSON state file). Every mutation ends in `__resetAnimationTrackStore()` so the* running server serves the table it just wrote instead of reporting success against* a cache nothing dropped.@@ -66,7 +66,7 @@ import {} from './animationTrackStore.js';import { recordsCarryingTrack } from './animationTrackWorkflow.js';-// One store file, so ONE tail — per CLAUDE.md's "collapse the queue to a single+// One store file, so ONE tail — per AGENTS.md's "collapse the queue to a single// tail per shared file". A per-id queue would let two different tracks' writes// interleave on the same JSON and lose one of them.const queueStoreWrite = createFileWriteQueue();diff --git a/server/services/sprites/animationTrackWorkflow.js b/server/services/sprites/animationTrackWorkflow.jsindex 064fecb4ea..771cf683a3 100644--- a/server/services/sprites/animationTrackWorkflow.js+++ b/server/services/sprites/animationTrackWorkflow.js@@ -381,7 +381,7 @@ export async function attachTrackTuiResult(trackId, recordId, runId, videoAbs) {async function packageTrackRun(row, recordId, run) {// Runs outside the request lifecycle (the TUI completion tail), so a throw// here would take the process down rather than reaching error middleware —- // hence the try/catch, per the CLAUDE.md boundary exception.+ // hence the try/catch, per the AGENTS.md boundary exception.try {const [reference, record] = await Promise.all([loadManifest(recordId), getRecord(recordId)]);const source = trackSourceFor(row, reference, run.direction);diff --git a/server/services/sprites/recordsLogic.js b/server/services/sprites/recordsLogic.jsindex b3b376bdb3..799dfb38ce 100644--- a/server/services/sprites/recordsLogic.js+++ b/server/services/sprites/recordsLogic.js@@ -83,7 +83,7 @@ export function buildSpriteRecord(input, { id, now }) {}// Whitelist patch — key-absent preserves, key-present applies (including an-// intentional clear via null/''), per the LLM/merge convention in CLAUDE.md.+// intentional clear via null/''), per the LLM/merge convention in AGENTS.md.const PATCHABLE = ['name', 'status', 'kind', 'spec', 'chromaKey', 'publishBinding', 'notes', 'imageMode', 'imageModelId'];export function applySpriteRecordPatch(record, patch) {diff --git a/server/services/subscriptionCosts.js b/server/services/subscriptionCosts.jsindex 9ab5ac1525..6b9ee58002 100644--- a/server/services/subscriptionCosts.js+++ b/server/services/subscriptionCosts.js@@ -66,7 +66,7 @@ export async function getSubscriptionCosts() {* Merge a patch of plan prices into settings and return the normalized map.** Absent key vs. present-but-empty are DIFFERENT (the LLM/merge convention in- * CLAUDE.md applies to user edits too): a family the patch omits keeps its+ * AGENTS.md applies to user edits too): a family the patch omits keeps its* stored price, while a family sent as `null`/`0` is an intentional clear and* is deleted. Without that split, an editor that only submits changed rows* could never remove a plan the user cancelled.diff --git a/server/services/taskPromptDefaults.js b/server/services/taskPromptDefaults.jsindex 7fdca289a4..b9a6d200e1 100644--- a/server/services/taskPromptDefaults.js+++ b/server/services/taskPromptDefaults.js@@ -13,7 +13,7 @@* working. taskPromptDefaults.test.js pins the exported values against a hash* snapshot so a split/refactor can't silently alter the upgrade contract.*- * Distribution-model machinery (see CLAUDE.md "Distribution model"):+ * Distribution-model machinery (see AGENTS.md "Distribution model"):* - PROMPT_VERSIONS — bumped when a default prompt changes so existing installs auto-upgrade.* - PREVIOUS_DEFAULT_PROMPTS — prior shipped defaults, recognized on read so a stored* (non-customized) prompt can be safely auto-upgraded across installs/versions.diff --git a/server/services/taskPromptDefaults.test.js b/server/services/taskPromptDefaults.test.jsindex 4aee6bb568..f578bf2af8 100644--- a/server/services/taskPromptDefaults.test.js+++ b/server/services/taskPromptDefaults.test.js@@ -11,7 +11,7 @@ import {import { hashPromptBody, buildPromptIntegritySnapshot } from './taskPromptDefaults/integrityHash.js';// Hash snapshot of every exported prompt body and version. This pins the-// cross-install prompt-upgrade contract (see CLAUDE.md "Distribution model"):+// cross-install prompt-upgrade contract (see AGENTS.md "Distribution model"):// a refactor of the taskPromptDefaults/ split cannot silently alter a prompt// byte, and an INTENTIONAL prompt change forces the author through this file —// where the rule is: bump PROMPT_VERSIONS, append the outgoing default to@@ -151,7 +151,7 @@ describe('taskPromptDefaults integrity snapshot', () => {// reasonable reading, records it in an issue comment/note, ships) instead of// punting the choice back to a human. `needs-input` is reserved for// destructive/irreversible or genuinely human-gated (hardware/credentials)- // cases. Mirrors CLAUDE.md "Decide, don't defer". Pins the version-bump pairing+ // cases. Mirrors AGENTS.md "Decide, don't defer". Pins the version-bump pairing// + preserved outgoing defaults for cross-install auto-upgrade.// Version numbers are pinned once, by the `agy` test below — a content test// that also asserts the version has to be edited by every unrelated bump.@@ -482,7 +482,7 @@ describe('taskPromptDefaults integrity snapshot', () => {// read as "not enough work accumulated for a release".it('release-check v9 reconciles missing releases before evaluating readiness, preserving the v8 default', () => {const current = DEFAULT_TASK_PROMPTS['release-check'];- expect(PROMPT_VERSIONS['release-check']).toBe(9);+ expect(PROMPT_VERSIONS['release-check']).toBeGreaterThanOrEqual(9);expect(current).toContain('Reconcile Missing Releases');expect(current).toContain('Unpublished release detected');expect(current).toContain('--latest=false');@@ -497,11 +497,14 @@ describe('taskPromptDefaults integrity snapshot', () => {expect(current).toContain('test-database provisioning/setup command');expect(current).toContain('never substitute a production database');+ // v8 is identified by content, not by position: later revisions append+ // their own outgoing bodies after it, so `last` stops meaning v8.const previous = PREVIOUS_DEFAULT_PROMPTS['release-check'];- const v8 = previous[previous.length - 1];- expect(v8).toContain('database-backed test suite');- expect(v8).not.toContain('Reconcile Missing Releases');- expect(v8).not.toBe(current);+ const v8Candidates = previous.filter(+ (prompt) => prompt.includes('database-backed test suite') && !prompt.includes('Reconcile Missing Releases'),+ );+ expect(v8Candidates).toHaveLength(1);+ expect(v8Candidates[0]).not.toBe(current);});// refresh-local-llm-catalog is the one PortOS-ONLY prompt in this set (it@@ -595,8 +598,9 @@ describe('taskPromptDefaults integrity snapshot', () => {(prompt) => prompt.includes('glab issue list --per-page 100 -F json') && prompt.includes('{issueExcludeLabels}'),);expect(withBoth).toHaveLength(1);- // …and it is the newest entry, which is where an append lands.- expect(withBoth[0]).toBe(previous[previous.length - 1]);+ // …and it was appended after every body that predates v15, so it sits in the+ // newest third of the list even once later revisions append behind it.+ expect(previous.indexOf(withBoth[0])).toBeGreaterThan(previous.length - 4);expect(withBoth[0]).not.toBe(current);});diff --git a/server/services/taskPromptDefaults/integrity.snapshot.json b/server/services/taskPromptDefaults/integrity.snapshot.jsonindex 004fda3aff..2ff5389287 100644--- a/server/services/taskPromptDefaults/integrity.snapshot.json+++ b/server/services/taskPromptDefaults/integrity.snapshot.json@@ -7,23 +7,23 @@"accessibility": "372916803f32b82da38a5b2130a54baf","console-errors": "2b6ed595287f0742bed9ecba6788afe6","dependency-updates": "1d59f04bea630a85a3085829db8599e7",- "documentation": "b375f95ae2274f03d06ba5ceff5705d8",+ "documentation": "246be4932c277fa0ec0ab365beb3baad","ui-bugs": "def9ad96bd74ab397233f234d79a1974","mobile-responsive": "16d8e7f63a673a2de48994c0ac08ef3d","ux": "e03d03fc7c16faa5b5db93be2896b9ad","data-safety": "86b07f51abdbcbe7016f840b5bb0cd9b","simplify": "2a048214d1dd3b75bee9ae1a38fa1589","feature-ideas": "d3282f16da29efe2d53595b3b34778bc",- "plan-task": "2012a0da54bdbf441911a0eed05f0cb1",- "claim-issue": "5bcaf3230a7a46ee039404943feab187",- "claim-issue-gitlab": "ed2c2c9c8cd6297340b3a92666cb2c5a",- "claim-issue-jira": "9d782972b20d6b721eb44d0673315cad",- "code-reviewer-review": "1cd13ee5142d130f95cc390098d0f278",- "code-reviewer-implement": "ab2c3e16d54e195bdf856574b7702042",+ "plan-task": "910802d67f3b5a785f068f4d90178543",+ "claim-issue": "542ce3673abbdee93e895f9df660aaf7",+ "claim-issue-gitlab": "348ed6348b90dcc6eead03e06df049e9",+ "claim-issue-jira": "c66170bfcdee911f03e60261c4f503db",+ "code-reviewer-review": "27ded42013f28e7d327d8f1cc624aac1",+ "code-reviewer-implement": "2e10cac7c1e1cd021d06bfddb5c1eaf2","error-handling": "9afba2e99b90a8d5771c75e7f0615d96","typing": "1f2758ce0bb62d789a21aec241549531",- "release-check": "afa9039cfbff21d77d601dc74eb5b81f",- "stash-cleanup": "f9de8b10937919ceb6656fbdb70179c4",+ "release-check": "2d2a6700c23b73bf738c2aa915e37277",+ "stash-cleanup": "1c12bac5aac6bb27008c40981e7db08c","jira-sprint-manager": "3e63c8a3bdf0d5a05a30faaa2dc07980","do-replan": "35660eb7b43e4259a6a9253ed288a1db","jira-status-report": "9d374a9d8ccb92c5c8fd0aa9899e79a5",@@ -40,10 +40,10 @@"PROMPT_VERSIONS": {"do-replan": 2,"feature-ideas": 10,- "plan-task": 16,- "claim-issue": 16,- "claim-issue-gitlab": 16,- "claim-issue-jira": 12,+ "plan-task": 17,+ "claim-issue": 17,+ "claim-issue-gitlab": 17,+ "claim-issue-jira": 13,"pr-reviewer": 3,"code-reviewer-a": 1,"code-reviewer-b": 1,@@ -58,14 +58,14 @@"performance": 2,"accessibility": 2,"dependency-updates": 4,- "documentation": 5,+ "documentation": 6,"ui-bugs": 2,"mobile-responsive": 2,"ux": 1,"data-safety": 1,"simplify": 1,- "stash-cleanup": 1,- "release-check": 9+ "stash-cleanup": 2,+ "release-check": 10},"REFERENCE_WATCH_AUDITED_VERSION": 3,"PREVIOUS_DEFAULT_PROMPTS": {@@ -95,7 +95,8 @@"8f5b69fd9336b17184e7f7989f97def5","808140457aff9ff344ddac426e0022ed","bbc5495a02102fd470d2a429eedfbe76",- "aa5d121b3cb25aa134e3a20e5f0186c6"+ "aa5d121b3cb25aa134e3a20e5f0186c6",+ "2012a0da54bdbf441911a0eed05f0cb1"],"pr-reviewer": ["9ceeed08f238b3787fc1201a0ce8e023",@@ -117,7 +118,8 @@"367c22d2587212c9c391f50d146948e8","927766326e492e4c9c2566534f465512","364ecf5feb38ec1f7ada50a7bcbf3199",- "52fd3506aad0b283be7234b608cf31ca"+ "52fd3506aad0b283be7234b608cf31ca",+ "9d782972b20d6b721eb44d0673315cad"],"claim-issue-gitlab": ["fae92c45c89c65455930b4b06a1b88c4",@@ -134,7 +136,8 @@"da0a8fbb33ac274a3b2efd968e302a1a","d8fe2bf614b465ca46108ea3295d2ec5","7ff928b2560ed6bb1a96dbbc80142ed9",- "eed428fc96a8a58ee94d38e6e4896932"+ "eed428fc96a8a58ee94d38e6e4896932",+ "ed2c2c9c8cd6297340b3a92666cb2c5a"],"claim-issue": ["37949d1b1fa8d461a15658f8f4192d97",@@ -151,7 +154,8 @@"d5465bd5d6fa1cd979746b99a881dba9","0ffd94e6c7966e5ce457effea63f71d3","dc47a602c96b0618e7bca87e6b21c397",- "50e21cbaece1875f118d3a0f1a25da81"+ "50e21cbaece1875f118d3a0f1a25da81",+ "5bcaf3230a7a46ee039404943feab187"],"security": ["d0f54c1fbe62d067b1a23ee0a9f3528c"@@ -177,7 +181,8 @@"074ea22140f8f6a02c7e40a6bc7b0614","658395fa391df5a0fefaaebdf8dbedb7","751186658f5d9a9dbccdd6830946f3d8",- "74aa8433896647e7815f9d6d9e4a56c8"+ "74aa8433896647e7815f9d6d9e4a56c8",+ "b375f95ae2274f03d06ba5ceff5705d8"],"ui-bugs": ["01d2a7e034713195f33071f2c71a3c99"@@ -193,7 +198,8 @@"9c7508598ee772d1cee8f609f9ed7372","8436a47b5b1c9b2a342795e5634552da","746f11daaf721eae9e16845858ef55ee",- "08c928e6f79f83535e40b6988ff6eae3"+ "08c928e6f79f83535e40b6988ff6eae3",+ "afa9039cfbff21d77d601dc74eb5b81f"],"branch-reconcile": ["7ef2b5f7d8f05937d4912b26ad45f42e",@@ -207,6 +213,9 @@"refresh-local-llm-catalog": ["525bd0077672bf2f8beec9c0124740c8","a9dce67bb9f0837ba904f3412b03637f"+ ],+ "stash-cleanup": [+ "f9de8b10937919ceb6656fbdb70179c4"]}}diff --git a/server/services/taskPromptDefaults/previousDefaults.js b/server/services/taskPromptDefaults/previousDefaults.jsindex 43177fb9d9..b9179d2f45 100644--- a/server/services/taskPromptDefaults/previousDefaults.js+++ b/server/services/taskPromptDefaults/previousDefaults.js@@ -2593,6 +2593,174 @@ If \`git branch -d\` refuses, fetch the default branch and re-check remote \`MER**Do NOT \`git pull\` from inside this phase** (no \`--rebase\`, no \`--autostash\`, no plain \`pull\`). The agent's work is already integrated on GitHub via \`gh pr merge\`; pulling locally provides no functional benefit and risks rebasing the user's in-progress branch / shuffling their uncommitted changes through stash if the source repo HEAD happens to be on a tracking feature branch when the agent runs. Leave the user's working tree alone.+_(Phase 3b is defined above, right after Phase 3 — see the "alternative exit from Phase 3" section.)_`,+ // v16 default prompt (pre-#4852: named CLAUDE.md as the agent-instructions file)+ `[Plan Task: {appName}] Claim and ship next PLAN.md item++Pick the next available unclaimed PLAN.md item by its \`[<slug>]\` ID, **create your own worktree at \`claim/<slug>\`**, implement, ship a PR, and clean up. Mirrors the \`/claim\` slash command — same in-flight scan, same branch naming, same no-local-merge cleanup. **YOU pick the item in Phase 1 — the scheduler does not reserve one for you.** Picking at execution time and immediately creating the \`claim/<slug>\` branch **narrows** the window for two concurrent runs to collide on the same slug — it does NOT eliminate it: two runs can still complete Phase 1 before either creates a branch, then race at \`git worktree add\`. That race is handled in Phase 2 — the loser re-picks the next item. (A dispatch-time pre-pick is strictly worse: it commits both runs to the same slug long before any branch exists.) Do NOT modify files in the source repo directly; ALL editing happens inside the worktree you create.++**How claiming works.** Every PLAN.md checkbox carries a \`[<slug>]\` ID. A slug is "in flight" when it appears as the slug-position segment in either a \`claim/<slug>\` ref (the human/TUI pattern) or a \`cos/<task>/<slug>/<agent>\` ref (the CoS sub-agent pattern) — across local branches, remote branches, or open PR head refs. The \`claim/<slug>\` branch you create IS the claim, visible to every other agent and to the human running \`/claim\` in a TUI.++## Phase 1 — Pick the target slug++Run steps 1–5 in order.++1. Read PLAN.md from the repo root.+2. **If any \`- [ ]\` line lacks an \`[<slug>]\` ID, stop and exit cleanly** — \`do-replan\` populates IDs in one pass; without IDs, this task has nothing to claim.+3. Build the in-flight set. Collect every ref from these sources:+ \`\`\`bash+ git fetch --prune 2>/dev/null+ git branch -a --no-color --format='%(refname:short)'+ gh pr list --state open --json headRefName -q '.[].headRefName' 2>/dev/null+ \`\`\`+ For each ref, extract the slug **only when the ref matches one of these documented patterns** (after stripping any leading remote prefix like \`origin/\` or \`upstream/\`):+ - \`claim/<slug>\` — the slug is everything after \`claim/\`.+ - \`cos/<task>/<slug>/<agent>\` — the slug is the third \`/\`-separated segment.++ A slug is "in flight" iff it appears in a ref matching one of those patterns AND is present in PLAN.md. **Do NOT** flag a slug just because the bare word appears as some other segment of a ref — that would falsely flag any slug literally named \`main\`, \`fix\`, \`feature\`, \`release\`, \`dev\`, etc. against virtually every branch in the repo.+4. **Pick the target slug:** walk PLAN.md top-to-bottom and pick the FIRST \`- [ ]\` line where ALL of the following are true:+ - The slug is NOT in the in-flight set.+ - The immediately-preceding line does NOT start with \`> ⚠️ DRIFT:\`.+ - The line does NOT carry the \`<!-- NEEDS_INPUT -->\` annotation.+5. **If no eligible item exists**, exit cleanly — that's a healthy plan state, not a failure. Brainstorming is handled by the \`feature-ideas\` task; do NOT add new items here.++Capture the exact text of the selected item (without the leading \`- [ ]\`) verbatim, **including its \`[<slug>]\` ID** — the changelog entry will reuse both.++## Phase 2 — Claim (worktree)++Create the worktree on a branch named \`claim/<slug>\`. This branch name is the claim — once created and pushed, no other agent or \`/claim\` session will pick the same slug. Do all editing inside the worktree, NEVER in the source repo's working tree (which may have the user's in-flight work).++\`\`\`bash+SLUG=<picked-slug>+WORKTREE="{worktreesRoot}/claim-\${SLUG}"+mkdir -p {worktreesRoot}+git fetch origin main+git worktree add --no-track -b "claim/\${SLUG}" "\${WORKTREE}" origin/main+cd "\${WORKTREE}"+\`\`\`++**If the worktree-creation command fails because the claim/<slug> branch already exists** (a concurrent run won the branch-creation race, or a remote claim/<slug> is now visible), do NOT force or reuse it — that branch IS another run's claim. Treat the slug as in-flight, return to Phase 1, and pick the next eligible item; if nothing else is eligible, exit cleanly.++Stash the worktree path; you'll need it for Phase 7 cleanup.++## Phase 3 — Verify still valid++Before writing any code, sanity-check that executing the item won't regress newer work. **If ANY of these are true, jump to Phase 3b** (clarification path, not implementation):++- The picked line is preceded by a \`> ⚠️ DRIFT:\` blockquote (you should already have filtered it; double-check).+- The item description references a function, file, or component that no longer exists. Run \`grep -rn\` for the named identifiers — if they're gone, the item is stale.+- The item depends on a predecessor that hasn't shipped (e.g. "Phase B work" when Phase B isn't done).+- The work would require touching files outside the inferred scope (>5 unrelated files), suggesting the item is bigger than originally estimated.++Otherwise: **ambiguity is not a reason to jump to Phase 3b — decide.** If the item merely leaves a design choice unstated or is open to more than one reasonable reading, pick the most reasonable interpretation, note the approach you chose in the commit/PR, and proceed to Phase 4. Jump to Phase 3b ONLY when proceeding would be destructive/irreversible, or genuinely requires the human — specific hardware/credentials you don't have, or a judgment only they can make (the same narrow bar as a \`blocked\` item). The user would rather iterate on top of a shipped best-guess than have the item parked waiting on a decision they didn't ask to make.++## Phase 3b — Request Clarification (alternative exit from Phase 3)++Done from INSIDE the worktree (you've already created \`claim/<slug>\` in Phase 2):++1. Create \`.plan-questions.md\` in the worktree:+ \`\`\`+ # Plan Question: <short title summarizing the PLAN.md item>++ ## PLAN.md Item+ <the exact text of the unchecked item, including its [<slug>]>++ ## Questions+ - <question 1>+ - <question 2>+ \`\`\`+2. **Move the unchecked item to the bottom of PLAN.md and annotate it with \` <!-- NEEDS_INPUT -->\`** — remove from its current position and append at the end with the annotation, **preserving the \`[<slug>]\` ID**. This keeps the queue moving so the next \`plan-task\` run picks a different actionable item.+3. Commit, push the branch (\`git push -u origin claim/<slug>\`), and open a PR with \`gh pr create\` so the user can see the questions. **Do NOT merge** — the user resolves \`.plan-questions.md\` first.+4. Then run the **Phase 3b cleanup** (which differs from Phase 7 — the PR is intentionally unmerged here, so the local branch must NOT be deleted):+ \`\`\`bash+ cd {repoPath}+ git worktree remove "\${WORKTREE}"+ \`\`\`+ Leave the local \`claim/<slug>\` branch alone — \`git branch -d\` will refuse (PR not merged) and \`-D\` would discard work that's still in flight. The branch lives on locally and remotely until the user resolves the questions and the PR merges; \`git branch -d "claim/<slug>"\` becomes safe only after that point.++After Phase 3b runs, **exit** — do NOT proceed to Phase 4. The implementing path resumes only when the user reopens the slug post-clarification.++## Phase 4 — Implement++Write the code, tests, and any docs the item requires. Follow the repo conventions in CLAUDE.md (no try/catch in route handlers, functional programming, Zod validation, Tailwind tokens, reactive UI updates).++Run the relevant test suite as you go.++**Commit messages reference the slug** so the work is grep-able across the changelog, branches, and PR titles:++\`\`\`+<type>([<slug>]): <one-line description>++<optional body>+\`\`\`++Use \`feat:\` / \`fix:\` / \`refactor:\` / \`chore:\` / etc. (The bracketed-scope form \`([<slug>])\` is intentional and matches the project's existing convention — grep \`git log --oneline\` for prior examples. The brackets carry the PLAN.md \`[<slug>]\` ID syntax through to commits, branches, and PRs so a single slug grep finds the whole trail.)++## Phase 5 — Update PLAN.md and the changelog++**Remove the item from PLAN.md outright.** The audit trail for shipped work lives in \`git log\` and the project's changelog (however that repo keeps it) — do NOT archive to a \`DONE.md\`, that file has been retired. Do NOT leave a checked \`- [x]\` behind in PLAN.md.++1. Remove the picked \`- [ ]\` line from PLAN.md entirely. If removing it leaves a heading empty, leave the heading alone — section curation is \`do-replan\`'s job.+2. Record the shipped item in the repo's changelog, **following the convention that repo documents** — read its \`CLAUDE.md\` and changelog README (e.g. \`.changelog/README.md\`) BEFORE writing anything. Some repos collect per-branch fragments in a directory (e.g. \`.changelog/next/\`) via a helper script rather than appending to one shared file, precisely so parallel agents don't conflict on every merge. When such a convention is documented, use it — run the documented command and remember the fragment file it created as \`CHANGELOG_FILE\`.++ Only when no convention is documented, detect a changelog file (in this order — pick the first match) and append an entry there:+ - \`.changelog/NEXT.md\` (staged-release file)+ - \`CHANGELOG.md\` at repo root with an \`## Unreleased\` or \`## [Unreleased]\` heading+ - any other \`changelog\`-shaped file the repo already maintains (look at recent \`git log\` for examples of where prior entries landed)++ Either way, mirror the prose style of recent entries; lead with the slug in brackets so \`git log --grep='<slug>'\` and changelog greps line up:++ \`\`\`markdown+ - **[<slug>] <Title from the PLAN.md line>** — <1–3 sentences on what shipped, key files touched, any caveats>+ \`\`\`++ Remember the exact path you wrote to as \`CHANGELOG_FILE\` — you'll stage it in step 3. If the repo has no changelog at all, skip this step and leave \`CHANGELOG_FILE\` unset; the commit message + \`git log\` becomes the audit trail.++3. Stage PLAN.md plus the changelog file you actually edited (if any) and commit. **Do NOT use a glob or a swallow-on-failure fallback** — staging the exact file you edited is what keeps the audit trail honest:++ \`\`\`bash+ git add PLAN.md+ [ -n "$CHANGELOG_FILE" ] && git add "$CHANGELOG_FILE"+ git commit -m "docs([<slug>]): remove from PLAN.md and log to changelog"+ \`\`\`++## Phase 6 — Review locally, then open the PR and ship++The configured reviewers for this task, in order, are \`{reviewers}\`. Split them by where they can run, preserving order: **LOCAL reviewers** — every token that is NOT an \`@<login>\` (\`claude\` / \`codex\` / \`antigravity\` (CLI binary: \`agy\`) / \`grok\` / \`cursor\` invoke a local-CLI critique; \`lmstudio\` / \`ollama\` use the appended Local Reviewer Procedure) read the working tree and need no PR, so they run BEFORE the PR is opened. **PR-SIDE reviewers** — every \`@<login>\` token, plus any review bot the repo requests automatically on open — review cloud-side, so they can only run once the PR exists. Open the PR only when the branch is already review-clean and all that remains is CI plus those PR-side reviewers.++1. **Self-review your diff for reuse, quality, and efficiency** (DRY, dead code, naming, simpler equivalents, missed edge cases) and fix findings in the same diff — BEFORE opening the PR, not retroactively. Claude Code runs this as the three-agent \`/simplify\` pass; on other CLIs, do the equivalent review by hand.+2. **Run each LOCAL reviewer in order against the BRANCH diff, not a PR diff.** No PR exists yet, so use the CLI's own base-diff mode or \`git diff origin/main...HEAD\` (substitute the repo's default branch when it isn't \`main\`); local LLM reviewers go through the appended endpoint procedure. Apply the fixes, run the tests, and commit them — capped at 3 rounds per reviewer — then advance. A missing CLI, timeout, transport failure, malformed response, or empty response is UNSATISFIED, not clean. Do NOT substitute your own self-review, and never open the PR on the strength of it. If a local reviewer is still unsatisfied after 3 rounds, or its fixes leave the build/tests red, do NOT open a PR — leave the branch and worktree in place, report the reviewer and the failure, and stop.+3. Push the branch: \`git push -u origin claim/<slug>\`, then confirm \`git log --oneline @{u}..HEAD\` is empty so every review fix from step 2 is in the PR's diff.+4. Open the PR with \`gh pr create\` — title MUST encode the slug: \`<type>([<slug>]): <description>\`. Body should summarize what shipped + test plan.+5. **Satisfy the PR-SIDE reviewers and CI before merging.** Request each \`@<login>\` (\`gh pr edit <num> --add-reviewer <login>\`, drop the \`@\`), poll every 5–15s, and address the findings — push fixes, capped at 3 rounds each; their approval gates the merge. Wait out any auto-requested review bot the same way, then let required CI finish (\`gh pr checks <num> --required --watch --fail-fast\` — REQUIRED checks only, so an optional job can't stall the merge). If a reviewer stays unsatisfied or a required check stays red, comment on the PR naming the failure, remove only the worktree, and leave the branch and PR for reconciliation.++6. **Merge immediately via \`gh pr merge\`** — NEVER a local merge and NEVER \`--auto\`. Prefer a true merge commit so Git retains the branch tip, but fall back when the repository disallows that method:+ \`\`\`bash+ PR_URL=$(gh pr view --json url -q .url) # no number: resolves the PR from the checked-out branch+ gh pr merge "$PR_URL" --merge --delete-branch || {+ [ "$(gh pr view "$PR_URL" --json state -q .state)" = "MERGED" ] || gh pr merge "$PR_URL" --squash --delete-branch || gh pr merge "$PR_URL" --rebase --delete-branch+ }+ STATE=$(gh pr view "$PR_URL" --json state -q .state)+ [ "$STATE" = "MERGED" ] || { echo "Expected MERGED, got $STATE" >&2; exit 1; }+ \`\`\`+ The exact comparison must succeed. Investigate and retry on \`OPEN\`; \`CLOSED\` is not success. Do not enter Phase 7 until remote state is exactly \`MERGED\`.++## Phase 7 — Clean up (post-merge ONLY)++This phase runs only after the PR was merged via Phase 6. If you exited via Phase 3b instead, you already did the 3b-specific cleanup — do NOT also run Phase 7.++From the **source repo** (cd back to {repoPath} first; you are currently inside the worktree):++\`\`\`bash+cd {repoPath}+git worktree remove "\${WORKTREE}"+git branch -d "claim/\${SLUG}"+\`\`\`++If \`git branch -d\` refuses, fetch the default branch and re-check remote \`MERGED\` state. Retry \`-d\` only when Git proves the branch integrated; otherwise leave it for reconciliation. Never force-delete with \`-D\`.++**Do NOT \`git pull\` from inside this phase** (no \`--rebase\`, no \`--autostash\`, no plain \`pull\`). The agent's work is already integrated on GitHub via \`gh pr merge\`; pulling locally provides no functional benefit and risks rebasing the user's in-progress branch / shuffling their uncommitted changes through stash if the source repo HEAD happens to be on a tracking feature branch when the agent runs. Leave the user's working tree alone.+_(Phase 3b is defined above, right after Phase 3 — see the "alternative exit from Phase 3" section.)_`,],'pr-reviewer': [@@ -4185,6 +4353,122 @@ The configured reviewers for this task, in order, are \`{reviewers}\`. \`claude\## Phase 7 — Report+Generate a short summary: the ticket KEY + summary worked, the MR/PR URL, the ticket's FINAL JIRA status (confirm it is "In Review"), reviewers run, and any status transition that failed and why.`,+ // v12 default prompt (pre-#4852: named CLAUDE.md as the agent-instructions file)+ `[Claim Issue: {appName}] Claim and ship the next ready JIRA ticket++Pick the next ready JIRA ticket assigned to me in the current sprint, move it to **In Progress**, **create your own worktree at \`claim/<KEY>\`**, implement it, open a merge/pull request that references the ticket, move the ticket to **In Review**, and clean up. This is the \`/claim --issues\` flow for JIRA: same self-managed worktree and no-local-merge cleanup, but the work source is the app's **JIRA** project (via the PortOS JIRA API) and the ticket *status* — not an assignee/label — is the claim. **YOU pick the ticket in Phase 1.** Do NOT modify files in the source repo directly; ALL editing happens inside the worktree you create.++All PortOS API calls below are relative to this base URL: ${PORTOS_API_URL}++**How claiming works.** A ticket is "in flight" when (a) a \`claim/<KEY>\` or \`cos/<task>/<KEY>/<agent>\` ref exists across local branches, remote branches, or open MR/PR source refs, OR (b) its JIRA status is anything other than a not-started status (so "In Progress", "In Review", "Done", etc. are already taken). Moving the ticket to **In Progress** + the \`claim/<KEY>\` branch ARE the claim, visible to every other agent and to the human looking at the sprint board.++## Phase 1 — Pick the target ticket++Run steps 1–5 in order.++1. Resolve the app's JIRA config: GET ${PORTOS_API_URL}/api/apps and find the app whose \`id\` is \`{appId}\`. Read \`jira.enabled\`, \`jira.instanceId\`, and \`jira.projectKey\`. If \`jira.enabled\` is not true or either id is missing, exit cleanly — this task only works against JIRA-configured apps.+2. Fetch my current-sprint tickets: GET ${PORTOS_API_URL}/api/jira/instances/<instanceId>/my-sprint-tickets/<projectKey>. This returns the tickets assigned to me in the active sprint.+3. Build the in-flight set from git refs:+ \`\`\`bash+ cd {repoPath}+ git fetch --prune 2>/dev/null+ git branch -a --no-color --format='%(refname:short)'+ \`\`\`+ For each ref (after stripping any leading \`origin/\` / \`upstream/\` prefix), extract the ticket KEY **only when the ref matches** \`claim/<KEY>\` (the segment after \`claim/\`) or \`cos/<task>/<KEY>/<agent>\` (the \`<KEY>\` third segment). A KEY looks like \`PROJ-1234\`.+4. **Pick the target ticket:** walk the sprint tickets and pick the FIRST where ALL of the following are true (prefer higher priority — Blocker/Highest/High — then oldest):+ - Its status is a not-started status (e.g. "To Do", "Open", "Backlog", "Selected for Development", "Ready"). Skip tickets already "In Progress", "In Review", "Done", or any closed/resolved status — those are claimed or finished.+ - Its KEY is NOT in the in-flight set from step 3.+ - It has enough of a summary/description to act on. A ticket that merely leaves a design choice unstated is still eligible — you'll decide the reading in Phase 3, not skip it here. Skip only a ticket with essentially no actionable content (bare title, no description or acceptance criteria).+ - It is NOT an Epic (issue type "Epic", or a title ending in "(epic)"). Leave epics for a human to split.+5. **If no eligible ticket exists**, exit cleanly — an empty actionable queue is a healthy state, not a failure. If a ticket is in the sprint but too vague or blocked to start, create a Review Hub todo (POST ${PORTOS_API_URL}/api/review/todo with title "[<KEY>] Needs clarification" or "[<KEY>] Blocked" and a description of what's missing) instead of claiming it.++Capture the ticket KEY as \`KEY\`, its summary, and its full description — you'll reuse them in the branch, the MR/PR, and the commit trailer.++## Phase 2 — Claim (In Progress + worktree)++First move the ticket to **In Progress** (this is the claim, and it must happen BEFORE you start coding), then create the worktree. Transition names vary per project workflow, so resolve the id dynamically:++1. GET ${PORTOS_API_URL}/api/jira/instances/<instanceId>/tickets/<KEY>/transitions to list available transitions.+2. Pick the transition whose target status best matches "In Progress" (e.g. "In Progress", "Start Progress", "Start Work"); match case-insensitively. If none clearly matches, pick the transition that moves the ticket out of the To Do / Backlog column.+3. POST ${PORTOS_API_URL}/api/jira/instances/<instanceId>/tickets/<KEY>/transition with body {"transitionId": "<id>"}. If this fails (the status is unreachable), the ticket may have been claimed concurrently — return to Phase 1 and pick the next eligible ticket.++Then create the worktree on a branch named \`claim/<KEY>\`. Do all editing inside the worktree, NEVER in the source repo's working tree:++\`\`\`bash+KEY=<picked-key>+DEFAULT_BRANCH="$(git -C {repoPath} symbolic-ref --short refs/remotes/origin/HEAD 2>/dev/null | sed 's@^origin/@@')"+DEFAULT_BRANCH="\${DEFAULT_BRANCH:-main}"+WORKTREE="{worktreesRoot}/claim-\${KEY}"+mkdir -p "{worktreesRoot}"+git -C {repoPath} fetch origin "\${DEFAULT_BRANCH}"+git -C {repoPath} worktree add --no-track -b "claim/\${KEY}" "\${WORKTREE}" "origin/\${DEFAULT_BRANCH}"+cd "\${WORKTREE}"+\`\`\`++**If \`git worktree add\` fails because the \`claim/<KEY>\` branch already exists** (a concurrent run won the race), do NOT force or reuse it — that branch IS another run's claim. Move the ticket back to its prior status if you transitioned it, treat the ticket as in-flight, return to Phase 1, and pick the next eligible ticket. Stash \`WORKTREE\` — you'll need it for Phase 6 cleanup.++## Phase 3 — Verify still valid++Re-read the ticket (GET ${PORTOS_API_URL}/api/jira/instances/<instanceId>/tickets/<KEY>) before writing any code. **Every exit from this phase must leave a CONVERGING status on the ticket — Done/Closed, or a held status backed by a Review Hub todo.** Transitioning back to a not-started status is NOT an exit: Phase 1's not-started-only filter makes the ticket immediately re-eligible again, so the next pass re-picks it and burns another no-op run — every pass, forever.++- **Already fixed, superseded, or duplicated by another ticket** — a comment says so, or the change it asks for is already on the default branch. Post a ticket comment naming the PR/MR, commit, or ticket that already delivered it (POST ${PORTOS_API_URL}/api/jira/instances/<instanceId>/tickets/<KEY>/comments), transition the ticket to **Done/Closed**, remove the worktree, and return to Phase 1. **Evidence gate: if you cannot name the PR/MR, commit, or ticket that delivered it, this branch does NOT apply** — closing on a hunch destroys live work, which is far worse than one wasted pass. Treat the ticket as real work and continue to Phase 4.+- **Stale reference** — the ticket names a function, file, or component that no longer exists (\`grep -rn\` the named identifiers; if they're gone, it's stale). Post a ticket comment naming what you searched for and what you found instead, create a Review Hub todo (POST ${PORTOS_API_URL}/api/review/todo with title "[<KEY>] Stale reference" and what a human must re-scope), and transition the ticket to a **Blocked/On Hold status if the workflow has one — NOT back to a not-started status**; if the workflow has no held status, leave it **In Progress** so Phase 1's filter excludes it. Then remove the worktree and return to Phase 1.++(A too-large scope is NOT in this list — it has its own park path below.)++**A genuinely too-large ticket needs parking so the queue converges.** If the work is bigger than one coherent claim — it would touch files far outside the ticket's scope (>5 unrelated files) — and you can't carve a valuable standalone slice to ship first, splitting the omnibus is a human call: create a Review Hub todo (POST ${PORTOS_API_URL}/api/review/todo with title "[<KEY>] Needs clarification" and the split you'd suggest), transition the ticket to a **Blocked/On Hold status if the workflow has one — NOT back to a not-started status**, which would re-queue it under Phase 1 (ticket selection never consults Review Hub todos, so a not-started ticket is immediately re-eligible and the run would re-park it every pass); if the workflow has no held status, leave it **In Progress**. Phase 1's not-started-only filter keeps a non-not-started ticket out of the ready queue, and the Review Hub todo is the durable human signal — together they let the claim run converge. Then remove the worktree and exit.++**Ambiguity is NOT a release trigger — decide, don't defer.** If the ticket is merely open to more than one reasonable reading, or leaves a design choice unstated, do NOT bail to a "Needs clarification" todo. Pick the most reasonable interpretation, record the approach you chose in a ticket comment (POST ${PORTOS_API_URL}/api/jira/instances/<instanceId>/tickets/<KEY>/comments) so the decision is on the record, and implement it. The user would rather iterate on top of a shipped best-guess than have the ticket parked waiting on a decision they didn't ask to make. Reserve the "Needs clarification" todo for cases where proceeding would be **destructive or irreversible**, or genuinely requires the human: specific hardware/credentials you don't have, or a judgment only they can make. In those cases only, create the todo (POST ${PORTOS_API_URL}/api/review/todo with title "[<KEY>] Needs clarification" and what a human must resolve), transition the ticket to a **Blocked/On Hold status if the workflow has one — NOT back to a not-started status** (which would re-queue it under Phase 1, since ticket selection never consults Review Hub todos); if the workflow has no held status, leave it **In Progress** so Phase 1's not-started-only filter excludes it. Then remove the worktree and **exit — do NOT proceed to Phase 4**.++Do NOT leave an *unexplained* ticket in "In Progress" with no branch — that is the zombie to avoid. A deliberate park above is different: it always carries a Review Hub todo saying why (and a Blocked/On Hold status where the workflow supports one), so it reads as intentionally held, not abandoned.++## Phase 4 — Implement++Write the code, tests, and any docs the ticket requires. Follow the repo conventions in CLAUDE.md (no try/catch in route handlers, functional programming, Zod validation, Tailwind tokens, reactive UI updates). Run the relevant test suite as you go.++**Roll discovered backbone work INTO this MR/PR** — small supporting helpers, refactors, and tests the fix depends on belong here, not a follow-up. Only defer genuinely-large adjacent work.++Commit with a conventional message referencing the ticket so the trail is grep-able:++\`\`\`+<type>: <one-line description> (<KEY>)+\`\`\`++## Phase 5 — Review locally, then open the MR/PR and move to In Review++The audit trail is the merged MR/PR + \`git log\`. Detect the forge from the git origin and use the matching CLI (\`gh\` for GitHub, \`glab\` for GitLab).++The configured reviewers for this task, in order, are \`{reviewers}\`. Split them by where they can run, preserving order: **LOCAL reviewers** — every token that is NOT an \`@<login>\` (\`claude\` / \`codex\` / \`antigravity\` (CLI binary: \`agy\`) / \`grok\` / \`cursor\` invoke a local-CLI critique; \`lmstudio\` / \`ollama\` use the appended Local Reviewer Procedure) read the working tree and need no MR/PR, so they run in steps 1–2 below, BEFORE it is opened. **PR-SIDE reviewers** — every \`@<login>\` token, plus any review bot the repo requests automatically on open — review cloud-side and run in Phase 6, once the MR/PR exists.++1. **Write the changelog entry now, not after the reviewers run** — every commit the reviewers are about to read must already be on the branch, or the MR/PR carries work nobody reviewed. If the repo maintains a changelog, record a one-line entry **following the convention that repo documents** — read its \`CLAUDE.md\` and changelog README (e.g. \`.changelog/README.md\`) first. Some repos collect per-branch fragments in a directory (e.g. \`.changelog/next/\`) via a helper script rather than appending to one shared file, precisely so parallel agents don't conflict on every merge; use that flow when it's documented. Fall back to appending to the unreleased section (\`.changelog/NEXT.md\`, or \`## Unreleased\` in \`CHANGELOG.md\`) in the repo's existing prose style only when no convention is documented. Otherwise skip it.+2. **Self-review your diff for reuse, quality, and efficiency** (DRY, dead code, naming, simpler equivalents, missed edge cases) and fix the findings in the same diff. Claude Code runs this as the three-agent \`/simplify\` pass; on other CLIs, do the equivalent by hand.+3. **Run each LOCAL reviewer in the listed order against the BRANCH diff, not an MR/PR diff.** Nothing is open yet, so use the CLI's own base-diff mode or \`git diff "origin/\${DEFAULT_BRANCH}...HEAD"\`; local LLM reviewers go through the appended endpoint procedure. Apply the findings, run the tests, and commit the fixes — capped at 3 rounds per reviewer — then advance. A missing CLI, timeout, transport failure, malformed response, or empty response is UNSATISFIED, not clean. Do NOT substitute your own self-review, and do NOT open an MR/PR on the strength of it. If a local reviewer stays unsatisfied after 3 rounds, or its fixes leave the build/tests red, do NOT open one — leave the branch and worktree in place, comment the failure on the ticket (POST ${PORTOS_API_URL}/api/jira/instances/<instanceId>/tickets/<KEY>/comments), and stop.+4. Push the branch: \`git push -u origin "claim/\${KEY}"\`, then confirm \`git log --oneline @{u}..HEAD\` is empty so every review fix from step 3 is in the MR/PR's diff.+5. Open the MR/PR. Reference the JIRA \`KEY\` in the title and description (there is NO \`Closes\` auto-close for JIRA). Summarize what shipped + a short test plan.+ - GitHub: \`gh pr create --fill --head "claim/\${KEY}"\` (then edit the body to mention \`KEY\` if \`--fill\` didn't).+ - GitLab: \`glab mr create --fill --source-branch "claim/\${KEY}" --target-branch "\${DEFAULT_BRANCH}" --yes\`.+ Capture the MR/PR URL as \`PR_URL\`.+6. **Move the ticket to "In Review" — REQUIRED, not optional. Do not finish while it is still "In Progress":**+ - GET ${PORTOS_API_URL}/api/jira/instances/<instanceId>/tickets/<KEY>/transitions again (transitions change once In Progress).+ - Pick the transition whose target status best matches "In Review" (e.g. "In Review", "Code Review", "Review", "Ready for Review"); match case-insensitively.+ - POST ${PORTOS_API_URL}/api/jira/instances/<instanceId>/tickets/<KEY>/transition with body {"transitionId": "<id>"}.+7. Add the MR/PR link to the ticket: POST ${PORTOS_API_URL}/api/jira/instances/<instanceId>/tickets/<KEY>/comments with body {"comment": "Implementation complete. MR/PR: \${PR_URL}\\n\\nReady for code review."}. **If you shipped only PART of the ticket's scope** (a valuable slice with real work remaining), make the comment a \`Done ✓ / Remaining ▢\` summary so the remaining scope is not lost when a human lands the MR/PR; when that remainder is a clean, separable chunk, ALSO file a new follow-up ticket for it (POST ${PORTOS_API_URL}/api/jira/instances/<instanceId>/tickets with a summary + a description referencing \`KEY\`, plus equivalent labels \`model-light|model-medium|model-heavy\`, \`effort-low|effort-medium|effort-high|effort-xhigh|effort-max\`, \`good-first-issue\`, \`help-wanted\` when independently justified) so it re-enters the sprint queue. If a transition in step 6 failed (status unreachable), say so in this comment AND in the Phase 7 summary — do not silently drop it.++## Phase 6 — PR-side review and clean up++The local reviewers already ran in Phase 5, so only the reviewers that need an open MR/PR remain.++1. **Satisfy the PR-SIDE reviewers.** For each \`@<login>\` from the Phase 5 split, request the review on the open MR/PR (GitHub: \`gh pr edit <pr-number> --add-reviewer <login>\`, dropping the \`@\`; GitLab: \`glab mr update <MR_IID> --reviewer <login>\`), poll every 5–15s, and address the findings — push fixes, capped at 3 rounds per reviewer. Wait out any auto-requested review bot the same way. A missing reviewer, timeout, or unresolvable finding is UNSATISFIED, not clean: comment on the MR/PR naming the failure and stop. With no \`@<login>\` configured and no bot review appearing, this step is a no-op.+2. **Leave the MR/PR open for a human to land.** Unlike the GitHub/GitLab issue flows, this flow does NOT auto-merge — the ticket is "In Review" and a human reviews + merges. After the reviewers finish, run the worktree-only cleanup so the source checkout is left clean:+ \`\`\`bash+ cd {repoPath}+ git worktree remove "\${WORKTREE}"+ \`\`\`+ Leave the local \`claim/<KEY>\` branch and the open MR/PR in place. **Do NOT \`git merge\`, \`gh pr merge\`, \`glab mr merge\`, or \`git pull\`** — landing the change and moving the ticket to Done is the human's call.++## Phase 7 — Report+Generate a short summary: the ticket KEY + summary worked, the MR/PR URL, the ticket's FINAL JIRA status (confirm it is "In Review"), reviewers run, and any status transition that failed and why.`,],@@ -4637,10 +4921,133 @@ This flow ships GitLab issues — it does NOT touch PLAN.md. The audit trail is## Phase 6 — Review and ship-The configured reviewers for this task, in order, are \`{reviewers}\`. \`claude\` / \`codex\` / \`antigravity\` invoke a local-CLI critique. (\`copilot\` is GitHub-only — skip it on GitLab.) When more than one is configured, run each in the listed order before merging.+The configured reviewers for this task, in order, are \`{reviewers}\`. \`claude\` / \`codex\` / \`antigravity\` invoke a local-CLI critique. (\`copilot\` is GitHub-only — skip it on GitLab.) When more than one is configured, run each in the listed order before merging.++1. **Self-review your diff for reuse, quality, and efficiency** (DRY, dead code, naming, simpler equivalents, missed edge cases) and fix findings in the same diff BEFORE the reviewers run. Claude Code runs this as the three-agent \`/simplify\` pass; on other CLIs, do the equivalent review by hand.+2. **Wait for each configured CLI reviewer's findings BEFORE merging.** For \`claude\` / \`codex\` / \`antigravity\`, invoke that CLI headless against the MR diff, apply fixes, run tests, re-push — capped at 3 rounds — then advance to the next reviewer.++ **Review-stuck cleanup** (after 3 unresolved rounds): post one summarizing MR note (\`glab mr note\`), then run the worktree-only cleanup (\`cd {repoPath} && git worktree remove "\${WORKTREE}"\`). Leave the local branch, the open MR, the assignee, and the \`in-progress\` label in place so the human picks up cold. Do NOT run Phase 7.+3. **Merge via \`glab mr merge\`** — NEVER a local \`git merge\`. \`glab mr merge\` takes the **MR IID**, which is NOT the issue number — resolve it from the source branch first, then merge by that IID:+ \`\`\`bash+ MR_IID="$(glab mr list --source-branch "claim/issue-\${NUM}" -F json | sed -n 's/.*"iid":\\([0-9]\\{1,\\}\\).*/\\1/p' | head -1)"+ glab mr merge "\${MR_IID}" --yes --remove-source-branch \\+ || glab mr merge "\${MR_IID}" --yes --squash --remove-source-branch+ \`\`\`++## Phase 7 — Clean up (post-merge ONLY)++This phase runs only after the MR merged via Phase 6. From the **source repo** (cd back to {repoPath} first):++\`\`\`bash+cd {repoPath}+git worktree remove "\${WORKTREE}"+git branch -d "claim/issue-\${NUM}"+\`\`\`++If \`git branch -d\` refuses, use \`-D\` — the MR is confirmed merged, so the local branch is redundant.++**Reconcile the issue — did this MR FULLY satisfy its scope?**+- **Yes (full)** — the \`Closes #\${NUM}\` line already auto-closed it on merge to the default branch; if it's somehow still open, close it (\`glab issue close "\${NUM}"\`) and remove the label (\`glab issue update "\${NUM}" --unlabel in-progress\`).+- **No — the remainder is a clean, separable chunk** — close THIS issue with a summarizing note (shipped ✓ / moved to #NEW), remove \`in-progress\`, and file ONE tightly-scoped follow-up for the remainder: \`glab issue create --title "…" --label plan --description "…\\n\\nRefs #\${NUM}"\` (carry over any \`area:*\` labels the issue had).+- **No — the remainder is a continuation of the same scope** — keep the issue OPEN, post a \`Done ✓ / Remaining ▢\` note, and release the claim so the queue re-picks it: \`glab issue update "\${NUM}" --unassign --unlabel in-progress\`.++NEVER leave the issue OPEN with \`in-progress\` still on it — that strands it as a zombie (the claim queue skips \`in-progress\`, so the remaining scope is never re-picked). **Do NOT \`git pull\`** from inside this phase — the work is already integrated on GitLab via \`glab mr merge\`; leave the user's working tree alone.`,+ // v4 default (pre-"[epic]"-prefix epic recognition — bumped to v5)+ `[Claim Issue: {appName}] Claim and ship the next open GitLab issue++Pick the next available unclaimed open GitLab issue, **create your own worktree at \`claim/issue-<num>\`**, implement the fix, ship a merge request (MR) that closes the issue, and clean up. This is the \`/claim --issues\` flow for GitLab — same in-flight scan, same branch naming, same no-local-merge cleanup, but the work source is the repo's **GitLab** issue tracker and the forge CLI is \`glab\` (not \`gh\`). **YOU pick the issue in Phase 1 — the scheduler does not reserve one for you.** Picking at execution time and immediately claiming (worktree + assignee + label) **narrows** the window for two concurrent runs to collide on the same issue — it does NOT eliminate it. Do NOT modify files in the source repo directly; ALL editing happens inside the worktree you create.++{issueAuthorFilter}++**How claiming works.** An issue is "in flight" when its number appears as the issue-position segment in either a \`claim/issue-<num>\` ref (the human/TUI pattern) or a \`cos/<task>/issue-<num>/<agent>\` ref (the CoS sub-agent pattern) across local branches, remote branches, or open MR source-branch refs — OR the issue is already assigned to someone OR carries an \`in-progress\` label. The \`claim/issue-<num>\` branch + the assignee/\`in-progress\` markers you set ARE the claim, visible to every other agent (including parallel machines).++## Phase 1 — Pick the target issue++Run steps 1–5 in order.++1. cd into the repo root ({repoPath}) and confirm GitLab is the forge and \`glab\` is authenticated: \`glab auth status\` and \`glab repo view\`. If \`glab\` is not authenticated or the remote is not GitLab, exit cleanly — this task only works against GitLab issue trackers.+2. List candidate open issues, honoring the author filter described above. Fetch a JSON page and order **oldest-first** (GitLab returns newest-first by default; sort client-side by \`created_at\` since the page is bounded):+ \`\`\`bash+ git fetch --prune 2>/dev/null+ # Owner-only mode (default): add --author <owner> (resolve <owner> from the project namespace).+ glab issue list --per-page 100 -F json+ # Any-author mode: run the SAME command WITHOUT --author.+ \`\`\`+3. Build the in-flight set. Collect every branch/MR source ref:+ \`\`\`bash+ git branch -a --no-color --format='%(refname:short)'+ glab mr list --per-page 100 -F json # read each MR's source_branch+ \`\`\`+ For each ref (after stripping any leading \`origin/\` prefix), extract the issue number **only when the ref matches** \`claim/issue-<num>\` (number after \`claim/issue-\`) or \`cos/<task>/issue-<num>/<agent>\` (the \`issue-<num>\` third segment). Do NOT flag an issue just because its bare number appears elsewhere in a ref.+4. **Pick the target issue:** walk the candidate list oldest-first and pick the FIRST issue where ALL of the following are true:+ - Its number (\`iid\`) is NOT in the in-flight set.+ - It has NO assignees (an assignee means another machine/human already claimed it).+ - It does NOT carry any of these blocking labels: \`in-progress\`, \`blocked\`, \`needs-input\`, \`future\`, \`wontfix\`, \`question\`, \`discussion\`.+ - It is NOT a tracking/umbrella **epic** — recognized by an \`epic\` label OR a title ending in "(epic)". Leave epics for a human to split. **The bare \`plan\` label is NOT a skip signal** — it marks the claimable queue, not a blocker.+5. **If no eligible issue exists**, exit cleanly — an empty actionable queue is a healthy state, not a failure.++Capture the issue number (GitLab \`iid\`) as \`NUM\`, its title, and its full description — you'll reuse them in the MR and the \`Closes #<num>\` line.++## Phase 2 — Claim (worktree + markers)++Detect the default branch first (forge-agnostic), then create the worktree on \`claim/issue-<num>\` and set the cross-machine claim markers. Do all editing inside the worktree, NEVER in the source repo's working tree.++\`\`\`bash+NUM=<picked-number>+DEFAULT_BRANCH="$(git symbolic-ref --short refs/remotes/origin/HEAD 2>/dev/null | sed 's@^origin/@@')"+DEFAULT_BRANCH="\${DEFAULT_BRANCH:-main}"+WORKTREE="data/cos/worktrees/claim-issue-\${NUM}"+mkdir -p data/cos/worktrees+git fetch origin "\${DEFAULT_BRANCH}"+git worktree add -b "claim/issue-\${NUM}" "\${WORKTREE}" "origin/\${DEFAULT_BRANCH}"+# Cross-machine claim markers (best-effort — do not abort the run if these fail).+# Resolve your own username first — glab's --assignee wants a username (the+# \`@me\` gh-ism isn't universally supported), falling back to @me if the lookup fails:+ME="$(glab api user 2>/dev/null | sed -n 's/.*"username":"\\([^"]*\\)".*/\\1/p')"+glab issue update "\${NUM}" --assignee "\${ME:-@me}" 2>/dev/null+glab issue update "\${NUM}" --label in-progress 2>/dev/null+cd "\${WORKTREE}"+\`\`\`++**If \`git worktree add\` fails because the \`claim/issue-<num>\` branch already exists** (a concurrent run won the race), do NOT force or reuse it — that branch IS another run's claim. Treat the issue as in-flight, return to Phase 1, and pick the next eligible issue; if nothing else is eligible, exit cleanly. Stash \`WORKTREE\` — you'll need it for Phase 7 cleanup.++## Phase 3 — Verify still valid++Read the full issue (\`glab issue view "\${NUM}"\`) before writing any code. **If ANY of these are true, release the claim and re-pick** (remove the assignee with \`glab issue update "\${NUM}" --unassign\` + the \`in-progress\` label with \`--unlabel in-progress\`, remove the worktree, return to Phase 1):++- A note indicates the issue was already fixed, superseded, or closed-then-reopened-for-tracking.+- The request references a function, file, or component that no longer exists (\`grep -rn\` the named identifiers — if they're gone, the issue is stale).+- The work would require touching files far outside the issue's scope (>5 unrelated files).+- The requirements are too ambiguous to implement without user clarification.++If too ambiguous or large, post a brief note explaining exactly what decision or clarification a human must provide (\`glab issue note "\${NUM}" -m "..."\`), then **tag it \`needs-input\` so it's excluded from future autonomous claims** (\`glab issue update "\${NUM}" --label needs-input\`), release the claim markers (\`glab issue update "\${NUM}" --unassign --unlabel in-progress\`), remove the worktree, and exit cleanly so a human can refine it. **The \`needs-input\` label is what lets an autonomous drain converge** — Phase 1 step 4 skips \`needs-input\` issues, so without the tag this same un-actionable issue would be re-picked on the next pass forever. Do NOT leave a half-claimed issue.++## Phase 4 — Implement++Write the code, tests, and any docs the issue requires. Follow the repo conventions in CLAUDE.md. Run the relevant test suite as you go.++**Roll discovered backbone work INTO this MR** — small supporting helpers, refactors, and tests that the fix depends on belong here, not a follow-up. Only defer genuinely-large adjacent work; when you do, file a NEW issue (\`glab issue create\`) tagged \`plan\` that references this one (\`Related to #<num>\`).++Commit with a conventional message referencing the issue:++\`\`\`+<type>: <one-line description> (#<num>)+\`\`\`++## Phase 5 — Open the merge request++This flow ships GitLab issues — it does NOT touch PLAN.md. The audit trail is the merged MR + \`git log\`.++1. If the repo maintains a changelog (\`.changelog/NEXT.md\`, or a \`## Unreleased\` section in \`CHANGELOG.md\`), append a one-line entry mirroring the repo's existing prose style. If no changelog convention exists, skip this.+2. Push the branch: \`git push -u origin "claim/issue-\${NUM}"\`+3. Open the MR with \`glab mr create --fill --source-branch "claim/issue-\${NUM}" --target-branch "\${DEFAULT_BRANCH}" --yes\`. **Choose the issue trailer deliberately:** if this MR FULLY satisfies the issue's scope, the description MUST contain \`Closes #\${NUM}\` so the merge auto-closes it; if you deliberately shipped only PART of the issue (a valuable slice with real scope remaining), use \`Refs #\${NUM}\` instead (NOT \`Closes\`) and add a \`## Remaining\` section listing what's left — Phase 7 reconciles the issue so it is never stranded. Summarize what shipped + a short test plan (pass \`--description\` if \`--fill\` didn't capture it).++## Phase 6 — Review and ship++The configured reviewers for this task, in order, are \`{reviewers}\`. \`claude\` / \`codex\` / \`antigravity\` / \`grok\` invoke a local-CLI critique. (\`copilot\` is GitHub-only — skip it on GitLab.) When more than one is configured, run each in the listed order before merging.1. **Self-review your diff for reuse, quality, and efficiency** (DRY, dead code, naming, simpler equivalents, missed edge cases) and fix findings in the same diff BEFORE the reviewers run. Claude Code runs this as the three-agent \`/simplify\` pass; on other CLIs, do the equivalent review by hand.-2. **Wait for each configured CLI reviewer's findings BEFORE merging.** For \`claude\` / \`codex\` / \`antigravity\`, invoke that CLI headless against the MR diff, apply fixes, run tests, re-push — capped at 3 rounds — then advance to the next reviewer.+2. **Wait for each configured CLI reviewer's findings BEFORE merging.** For \`claude\` / \`codex\` / \`antigravity\` / \`grok\`, invoke that CLI headless against the MR diff, apply fixes, run tests, re-push — capped at 3 rounds — then advance to the next reviewer.**Review-stuck cleanup** (after 3 unresolved rounds): post one summarizing MR note (\`glab mr note\`), then run the worktree-only cleanup (\`cd {repoPath} && git worktree remove "\${WORKTREE}"\`). Leave the local branch, the open MR, the assignee, and the \`in-progress\` label in place so the human picks up cold. Do NOT run Phase 7.3. **Merge via \`glab mr merge\`** — NEVER a local \`git merge\`. \`glab mr merge\` takes the **MR IID**, which is NOT the issue number — resolve it from the source branch first, then merge by that IID:@@ -4668,7 +5075,8 @@ If \`git branch -d\` refuses, use \`-D\` — the MR is confirmed merged, so the- **No — the remainder is a continuation of the same scope** — keep the issue OPEN, post a \`Done ✓ / Remaining ▢\` note, and release the claim so the queue re-picks it: \`glab issue update "\${NUM}" --unassign --unlabel in-progress\`.NEVER leave the issue OPEN with \`in-progress\` still on it — that strands it as a zombie (the claim queue skips \`in-progress\`, so the remaining scope is never re-picked). **Do NOT \`git pull\`** from inside this phase — the work is already integrated on GitLab via \`glab mr merge\`; leave the user's working tree alone.`,- // v4 default (pre-"[epic]"-prefix epic recognition — bumped to v5)+ // v5 default (Phase 3 parked an *ambiguous* issue to `needs-input` and re-picked;+ // superseded by v6, which decides and ships instead). Kept so a stored v5 prompt auto-upgrades.`[Claim Issue: {appName}] Claim and ship the next open GitLab issuePick the next available unclaimed open GitLab issue, **create your own worktree at \`claim/issue-<num>\`**, implement the fix, ship a merge request (MR) that closes the issue, and clean up. This is the \`/claim --issues\` flow for GitLab — same in-flight scan, same branch naming, same no-local-merge cleanup, but the work source is the repo's **GitLab** issue tracker and the forge CLI is \`glab\` (not \`gh\`). **YOU pick the issue in Phase 1 — the scheduler does not reserve one for you.** Picking at execution time and immediately claiming (worktree + assignee + label) **narrows** the window for two concurrent runs to collide on the same issue — it does NOT eliminate it. Do NOT modify files in the source repo directly; ALL editing happens inside the worktree you create.@@ -4699,7 +5107,7 @@ Run steps 1–5 in order.- Its number (\`iid\`) is NOT in the in-flight set.- It has NO assignees (an assignee means another machine/human already claimed it).- It does NOT carry any of these blocking labels: \`in-progress\`, \`blocked\`, \`needs-input\`, \`future\`, \`wontfix\`, \`question\`, \`discussion\`.- - It is NOT a tracking/umbrella **epic** — recognized by an \`epic\` label OR a title ending in "(epic)". Leave epics for a human to split. **The bare \`plan\` label is NOT a skip signal** — it marks the claimable queue, not a blocker.+ - It is NOT a tracking/umbrella **epic** — recognized by an \`epic\` label, a title ending in "(epic)", OR a title beginning with an \`[epic]\` bracket or \`Epic:\` tag (e.g. "[Epic] …" / "Epic: …", case-insensitive). Leave epics for a human to split. **The bare \`plan\` label is NOT a skip signal** — it marks the claimable queue, not a blocker.5. **If no eligible issue exists**, exit cleanly — an empty actionable queue is a healthy state, not a failure.Capture the issue number (GitLab \`iid\`) as \`NUM\`, its title, and its full description — you'll reuse them in the MR and the \`Closes #<num>\` line.@@ -4791,8 +5199,7 @@ If \`git branch -d\` refuses, use \`-D\` — the MR is confirmed merged, so the- **No — the remainder is a continuation of the same scope** — keep the issue OPEN, post a \`Done ✓ / Remaining ▢\` note, and release the claim so the queue re-picks it: \`glab issue update "\${NUM}" --unassign --unlabel in-progress\`.NEVER leave the issue OPEN with \`in-progress\` still on it — that strands it as a zombie (the claim queue skips \`in-progress\`, so the remaining scope is never re-picked). **Do NOT \`git pull\`** from inside this phase — the work is already integrated on GitLab via \`glab mr merge\`; leave the user's working tree alone.`,- // v5 default (Phase 3 parked an *ambiguous* issue to `needs-input` and re-picked;- // superseded by v6, which decides and ships instead). Kept so a stored v5 prompt auto-upgrades.+ // v6 default prompt`[Claim Issue: {appName}] Claim and ship the next open GitLab issuePick the next available unclaimed open GitLab issue, **create your own worktree at \`claim/issue-<num>\`**, implement the fix, ship a merge request (MR) that closes the issue, and clean up. This is the \`/claim --issues\` flow for GitLab — same in-flight scan, same branch naming, same no-local-merge cleanup, but the work source is the repo's **GitLab** issue tracker and the forge CLI is \`glab\` (not \`gh\`). **YOU pick the issue in Phase 1 — the scheduler does not reserve one for you.** Picking at execution time and immediately claiming (worktree + assignee + label) **narrows** the window for two concurrent runs to collide on the same issue — it does NOT eliminate it. Do NOT modify files in the source repo directly; ALL editing happens inside the worktree you create.@@ -4857,10 +5264,12 @@ Read the full issue (\`glab issue view "\${NUM}"\`) before writing any code. **I- A note indicates the issue was already fixed, superseded, or closed-then-reopened-for-tracking.- The request references a function, file, or component that no longer exists (\`grep -rn\` the named identifiers — if they're gone, the issue is stale).-- The work would require touching files far outside the issue's scope (>5 unrelated files).-- The requirements are too ambiguous to implement without user clarification.-If too ambiguous or large, post a brief note explaining exactly what decision or clarification a human must provide (\`glab issue note "\${NUM}" -m "..."\`), then **tag it \`needs-input\` so it's excluded from future autonomous claims** (\`glab issue update "\${NUM}" --label needs-input\`), release the claim markers (\`glab issue update "\${NUM}" --unassign --unlabel in-progress\`), remove the worktree, and exit cleanly so a human can refine it. **The \`needs-input\` label is what lets an autonomous drain converge** — Phase 1 step 4 skips \`needs-input\` issues, so without the tag this same un-actionable issue would be re-picked on the next pass forever. Do NOT leave a half-claimed issue.+(A too-large scope is NOT in this release-and-re-pick list — releasing it just lets the next pass re-pick the same oversized issue. It has its own park path below.)++**A genuinely too-large issue needs parking so the drain converges.** If the work is bigger than one coherent claim — it would touch files far outside the issue's scope (>5 unrelated files) — and you can't carve a valuable standalone slice to partial-ship via Phase 5's \`Refs\` path, post a brief note naming the split you'd suggest, **tag it \`needs-input\`** (\`glab issue update "\${NUM}" --label needs-input\`), release the claim markers (\`glab issue update "\${NUM}" --unassign --unlabel in-progress\`), remove the worktree, and exit — splitting an omnibus issue is a human call, and parking it stops a perpetual drain from re-picking the same un-shippable issue every pass (Phase 1 step 4 skips \`needs-input\`).++**Ambiguity is NOT a release trigger — decide, don't defer.** If the issue is merely open to more than one reasonable reading, or leaves a design choice unstated, do NOT bail to \`needs-input\`. Pick the most reasonable interpretation, record the approach you chose in a brief issue note (\`glab issue note "\${NUM}" -m "..."\`) so the decision is on the record, and implement it. The user would rather iterate on top of a shipped best-guess than have the issue parked waiting on a decision they didn't ask to make. Reserve \`needs-input\` — which pulls the issue out of the autonomous queue — for the narrow cases where proceeding would be **destructive or irreversible**, or genuinely requires the human: specific hardware/credentials you don't have, or a judgment only they can make. In those cases only, post the explaining note, **tag it \`needs-input\`** (\`glab issue update "\${NUM}" --label needs-input\`), release the claim markers (\`glab issue update "\${NUM}" --unassign --unlabel in-progress\`), remove the worktree, and exit cleanly. **That label is what lets an autonomous drain converge** — Phase 1 step 4 skips \`needs-input\` issues. Never leave a half-claimed issue.## Phase 4 — Implement@@ -4915,7 +5324,7 @@ If \`git branch -d\` refuses, use \`-D\` — the MR is confirmed merged, so the- **No — the remainder is a continuation of the same scope** — keep the issue OPEN, post a \`Done ✓ / Remaining ▢\` note, and release the claim so the queue re-picks it: \`glab issue update "\${NUM}" --unassign --unlabel in-progress\`.NEVER leave the issue OPEN with \`in-progress\` still on it — that strands it as a zombie (the claim queue skips \`in-progress\`, so the remaining scope is never re-picked). **Do NOT \`git pull\`** from inside this phase — the work is already integrated on GitLab via \`glab mr merge\`; leave the user's working tree alone.`,- // v6 default prompt+ // v7 default prompt`[Claim Issue: {appName}] Claim and ship the next open GitLab issuePick the next available unclaimed open GitLab issue, **create your own worktree at \`claim/issue-<num>\`**, implement the fix, ship a merge request (MR) that closes the issue, and clean up. This is the \`/claim --issues\` flow for GitLab — same in-flight scan, same branch naming, same no-local-merge cleanup, but the work source is the repo's **GitLab** issue tracker and the forge CLI is \`glab\` (not \`gh\`). **YOU pick the issue in Phase 1 — the scheduler does not reserve one for you.** Picking at execution time and immediately claiming (worktree + assignee + label) **narrows** the window for two concurrent runs to collide on the same issue — it does NOT eliminate it. Do NOT modify files in the source repo directly; ALL editing happens inside the worktree you create.@@ -4959,8 +5368,8 @@ Detect the default branch first (forge-agnostic), then create the worktree on \`NUM=<picked-number>DEFAULT_BRANCH="$(git symbolic-ref --short refs/remotes/origin/HEAD 2>/dev/null | sed 's@^origin/@@')"DEFAULT_BRANCH="\${DEFAULT_BRANCH:-main}"-WORKTREE="data/cos/worktrees/claim-issue-\${NUM}"-mkdir -p data/cos/worktrees+WORKTREE="{worktreesRoot}/claim-issue-\${NUM}"+mkdir -p {worktreesRoot}git fetch origin "\${DEFAULT_BRANCH}"git worktree add -b "claim/issue-\${NUM}" "\${WORKTREE}" "origin/\${DEFAULT_BRANCH}"# Cross-machine claim markers (best-effort — do not abort the run if these fail).@@ -5040,7 +5449,8 @@ If \`git branch -d\` refuses, use \`-D\` — the MR is confirmed merged, so the- **No — the remainder is a continuation of the same scope** — keep the issue OPEN, post a \`Done ✓ / Remaining ▢\` note, and release the claim so the queue re-picks it: \`glab issue update "\${NUM}" --unassign --unlabel in-progress\`.NEVER leave the issue OPEN with \`in-progress\` still on it — that strands it as a zombie (the claim queue skips \`in-progress\`, so the remaining scope is never re-picked). **Do NOT \`git pull\`** from inside this phase — the work is already integrated on GitLab via \`glab mr merge\`; leave the user's working tree alone.`,- // v7 default prompt++ // v8 default prompt — pre-changelog-fragment-deference (issue #3998)`[Claim Issue: {appName}] Claim and ship the next open GitLab issuePick the next available unclaimed open GitLab issue, **create your own worktree at \`claim/issue-<num>\`**, implement the fix, ship a merge request (MR) that closes the issue, and clean up. This is the \`/claim --issues\` flow for GitLab — same in-flight scan, same branch naming, same no-local-merge cleanup, but the work source is the repo's **GitLab** issue tracker and the forge CLI is \`glab\` (not \`gh\`). **YOU pick the issue in Phase 1 — the scheduler does not reserve one for you.** Picking at execution time and immediately claiming (worktree + assignee + label) **narrows** the window for two concurrent runs to collide on the same issue — it does NOT eliminate it. Do NOT modify files in the source repo directly; ALL editing happens inside the worktree you create.@@ -5134,10 +5544,10 @@ This flow ships GitLab issues — it does NOT touch PLAN.md. The audit trail is## Phase 6 — Review and ship-The configured reviewers for this task, in order, are \`{reviewers}\`. \`claude\` / \`codex\` / \`antigravity\` / \`grok\` invoke a local-CLI critique. (\`copilot\` is GitHub-only — skip it on GitLab.) When more than one is configured, run each in the listed order before merging.+The configured reviewers for this task, in order, are \`{reviewers}\`. \`claude\` / \`codex\` / \`antigravity\` (CLI binary: \`agy\`) / \`grok\` invoke a local-CLI critique. (\`copilot\` is GitHub-only — skip it on GitLab.) When more than one is configured, run each in the listed order before merging.1. **Self-review your diff for reuse, quality, and efficiency** (DRY, dead code, naming, simpler equivalents, missed edge cases) and fix findings in the same diff BEFORE the reviewers run. Claude Code runs this as the three-agent \`/simplify\` pass; on other CLIs, do the equivalent review by hand.-2. **Wait for each configured CLI reviewer's findings BEFORE merging.** For \`claude\` / \`codex\` / \`antigravity\` / \`grok\`, invoke that CLI headless against the MR diff, apply fixes, run tests, re-push — capped at 3 rounds — then advance to the next reviewer.+2. **Wait for each configured CLI reviewer's findings BEFORE merging.** For \`claude\` / \`codex\` / \`antigravity\` (CLI binary: \`agy\`) / \`grok\`, invoke that CLI headless against the MR diff, apply fixes, run tests, re-push — capped at 3 rounds — then advance to the next reviewer. A configured CLI reviewer whose binary is not on PATH is UNSATISFIED, not clean — that is a broken setup, not a passing review. Do NOT substitute your own self-review and do NOT merge; comment on the MR naming the missing command and stop.**Review-stuck cleanup** (after 3 unresolved rounds): post one summarizing MR note (\`glab mr note\`), then run the worktree-only cleanup (\`cd {repoPath} && git worktree remove "\${WORKTREE}"\`). Leave the local branch, the open MR, the assignee, and the \`in-progress\` label in place so the human picks up cold. Do NOT run Phase 7.3. **Merge via \`glab mr merge\`** — NEVER a local \`git merge\`. \`glab mr merge\` takes the **MR IID**, which is NOT the issue number — resolve it from the source branch first, then merge by that IID:@@ -5166,7 +5576,7 @@ If \`git branch -d\` refuses, use \`-D\` — the MR is confirmed merged, so theNEVER leave the issue OPEN with \`in-progress\` still on it — that strands it as a zombie (the claim queue skips \`in-progress\`, so the remaining scope is never re-picked). **Do NOT \`git pull\`** from inside this phase — the work is already integrated on GitLab via \`glab mr merge\`; leave the user's working tree alone.`,- // v8 default prompt — pre-changelog-fragment-deference (issue #3998)+ // v9 default prompt — pre-converging-Phase-3-release (issue #4106)`[Claim Issue: {appName}] Claim and ship the next open GitLab issuePick the next available unclaimed open GitLab issue, **create your own worktree at \`claim/issue-<num>\`**, implement the fix, ship a merge request (MR) that closes the issue, and clean up. This is the \`/claim --issues\` flow for GitLab — same in-flight scan, same branch naming, same no-local-merge cleanup, but the work source is the repo's **GitLab** issue tracker and the forge CLI is \`glab\` (not \`gh\`). **YOU pick the issue in Phase 1 — the scheduler does not reserve one for you.** Picking at execution time and immediately claiming (worktree + assignee + label) **narrows** the window for two concurrent runs to collide on the same issue — it does NOT eliminate it. Do NOT modify files in the source repo directly; ALL editing happens inside the worktree you create.@@ -5254,7 +5664,7 @@ Commit with a conventional message referencing the issue:This flow ships GitLab issues — it does NOT touch PLAN.md. The audit trail is the merged MR + \`git log\`.-1. If the repo maintains a changelog (\`.changelog/NEXT.md\`, or a \`## Unreleased\` section in \`CHANGELOG.md\`), append a one-line entry mirroring the repo's existing prose style. If no changelog convention exists, skip this.+1. If the repo maintains a changelog, record a one-line entry **following the convention that repo documents** — read its \`CLAUDE.md\` and changelog README (e.g. \`.changelog/README.md\`) first. Some repos collect per-branch fragments in a directory (e.g. \`.changelog/next/\`) via a helper script rather than appending to one shared file, precisely so parallel agents don't conflict on every merge; use that flow when it's documented. Fall back to appending to the unreleased section (\`.changelog/NEXT.md\`, or \`## Unreleased\` in \`CHANGELOG.md\`) in the repo's existing prose style only when no convention is documented. If the repo has no changelog, skip this.2. Push the branch: \`git push -u origin "claim/issue-\${NUM}"\`3. Open the MR with \`glab mr create --fill --source-branch "claim/issue-\${NUM}" --target-branch "\${DEFAULT_BRANCH}" --yes\`. **Choose the issue trailer deliberately:** if this MR FULLY satisfies the issue's scope, the description MUST contain \`Closes #\${NUM}\` so the merge auto-closes it; if you deliberately shipped only PART of the issue (a valuable slice with real scope remaining), use \`Refs #\${NUM}\` instead (NOT \`Closes\`) and add a \`## Remaining\` section listing what's left — Phase 7 reconciles the issue so it is never stranded. Summarize what shipped + a short test plan (pass \`--description\` if \`--fill\` didn't capture it).@@ -5291,8 +5701,7 @@ If \`git branch -d\` refuses, use \`-D\` — the MR is confirmed merged, so the- **No — the remainder is a continuation of the same scope** — keep the issue OPEN, post a \`Done ✓ / Remaining ▢\` note, and release the claim so the queue re-picks it: \`glab issue update "\${NUM}" --unassign --unlabel in-progress\`.NEVER leave the issue OPEN with \`in-progress\` still on it — that strands it as a zombie (the claim queue skips \`in-progress\`, so the remaining scope is never re-picked). **Do NOT \`git pull\`** from inside this phase — the work is already integrated on GitLab via \`glab mr merge\`; leave the user's working tree alone.`,-- // v9 default prompt — pre-converging-Phase-3-release (issue #4106)+ // v10 default (pre-`--no-track`, bumped to v11)`[Claim Issue: {appName}] Claim and ship the next open GitLab issuePick the next available unclaimed open GitLab issue, **create your own worktree at \`claim/issue-<num>\`**, implement the fix, ship a merge request (MR) that closes the issue, and clean up. This is the \`/claim --issues\` flow for GitLab — same in-flight scan, same branch naming, same no-local-merge cleanup, but the work source is the repo's **GitLab** issue tracker and the forge CLI is \`glab\` (not \`gh\`). **YOU pick the issue in Phase 1 — the scheduler does not reserve one for you.** Picking at execution time and immediately claiming (worktree + assignee + label) **narrows** the window for two concurrent runs to collide on the same issue — it does NOT eliminate it. Do NOT modify files in the source repo directly; ALL editing happens inside the worktree you create.@@ -5353,12 +5762,12 @@ cd "\${WORKTREE}"## Phase 3 — Verify still valid-Read the full issue (\`glab issue view "\${NUM}"\`) before writing any code. **If ANY of these are true, release the claim and re-pick** (remove the assignee with \`glab issue update "\${NUM}" --unassign\` + the \`in-progress\` label with \`--unlabel in-progress\`, remove the worktree, return to Phase 1):+Read the full issue (\`glab issue view "\${NUM}"\`) before writing any code. **Every exit from this phase must leave a CONVERGING outcome on the issue — closed, or labeled \`needs-input\`.** Phase 1 step 4 skips both, so an autonomous drain stops re-picking the item. Releasing an issue OPEN and unlabeled is NOT an exit: the work detector still reports it actionable, so the next pass re-picks it and burns another no-op agent — every pass, forever.-- A note indicates the issue was already fixed, superseded, or closed-then-reopened-for-tracking.-- The request references a function, file, or component that no longer exists (\`grep -rn\` the named identifiers — if they're gone, the issue is stale).+- **Already fixed, superseded, or closed-then-reopened-for-tracking** — a note says so, or the change it asks for is already on the default branch. **Close it:** post a note naming the MR/commit (or issue) that already delivered it (\`glab issue note "\${NUM}" -m "..."\`), then \`glab issue close "\${NUM}"\` and clear the markers (\`glab issue update "\${NUM}" --unassign --unlabel in-progress\`). Remove the worktree and return to Phase 1. **Evidence gate: if you cannot name the MR, commit, or issue that delivered it, this branch does NOT apply** — closing on a hunch destroys live work, which is far worse than one wasted pass. Treat the issue as real work and continue to Phase 4.+- **Stale reference** — the request names a function, file, or component that no longer exists (\`grep -rn\` the named identifiers; if they're gone, the issue is stale). Post a note naming what you searched for and what you found instead, **tag it \`needs-input\`** (\`glab issue update "\${NUM}" --label needs-input\`), release the claim markers (\`glab issue update "\${NUM}" --unassign --unlabel in-progress\`), remove the worktree, and return to Phase 1. Re-scoping a stale issue against today's code is a human call — and the label is what keeps the drain off it in the meantime.-(A too-large scope is NOT in this release-and-re-pick list — releasing it just lets the next pass re-pick the same oversized issue. It has its own park path below.)+(A too-large scope is NOT in this list — it has its own park path below.)**A genuinely too-large issue needs parking so the drain converges.** If the work is bigger than one coherent claim — it would touch files far outside the issue's scope (>5 unrelated files) — and you can't carve a valuable standalone slice to partial-ship via Phase 5's \`Refs\` path, post a brief note naming the split you'd suggest, **tag it \`needs-input\`** (\`glab issue update "\${NUM}" --label needs-input\`), release the claim markers (\`glab issue update "\${NUM}" --unassign --unlabel in-progress\`), remove the worktree, and exit — splitting an omnibus issue is a human call, and parking it stops a perpetual drain from re-picking the same un-shippable issue every pass (Phase 1 step 4 skips \`needs-input\`).@@ -5417,8 +5826,8 @@ If \`git branch -d\` refuses, use \`-D\` — the MR is confirmed merged, so the- **No — the remainder is a continuation of the same scope** — keep the issue OPEN, post a \`Done ✓ / Remaining ▢\` note, and release the claim so the queue re-picks it: \`glab issue update "\${NUM}" --unassign --unlabel in-progress\`.NEVER leave the issue OPEN with \`in-progress\` still on it — that strands it as a zombie (the claim queue skips \`in-progress\`, so the remaining scope is never re-picked). **Do NOT \`git pull\`** from inside this phase — the work is already integrated on GitLab via \`glab mr merge\`; leave the user's working tree alone.`,- // v10 default (pre-`--no-track`, bumped to v11)- `[Claim Issue: {appName}] Claim and ship the next open GitLab issue+ // v11 default — follow-ups only applied `plan` (bumped to v12 for dispatch + contributor labels)+`[Claim Issue: {appName}] Claim and ship the next open GitLab issuePick the next available unclaimed open GitLab issue, **create your own worktree at \`claim/issue-<num>\`**, implement the fix, ship a merge request (MR) that closes the issue, and clean up. This is the \`/claim --issues\` flow for GitLab — same in-flight scan, same branch naming, same no-local-merge cleanup, but the work source is the repo's **GitLab** issue tracker and the forge CLI is \`glab\` (not \`gh\`). **YOU pick the issue in Phase 1 — the scheduler does not reserve one for you.** Picking at execution time and immediately claiming (worktree + assignee + label) **narrows** the window for two concurrent runs to collide on the same issue — it does NOT eliminate it. Do NOT modify files in the source repo directly; ALL editing happens inside the worktree you create.@@ -5464,7 +5873,7 @@ DEFAULT_BRANCH="\${DEFAULT_BRANCH:-main}"WORKTREE="{worktreesRoot}/claim-issue-\${NUM}"mkdir -p {worktreesRoot}git fetch origin "\${DEFAULT_BRANCH}"-git worktree add -b "claim/issue-\${NUM}" "\${WORKTREE}" "origin/\${DEFAULT_BRANCH}"+git worktree add --no-track -b "claim/issue-\${NUM}" "\${WORKTREE}" "origin/\${DEFAULT_BRANCH}"# Cross-machine claim markers (best-effort — do not abort the run if these fail).# Resolve your own username first — glab's --assignee wants a username (the# \`@me\` gh-ism isn't universally supported), falling back to @me if the lookup fails:@@ -5542,8 +5951,8 @@ If \`git branch -d\` refuses, use \`-D\` — the MR is confirmed merged, so the- **No — the remainder is a continuation of the same scope** — keep the issue OPEN, post a \`Done ✓ / Remaining ▢\` note, and release the claim so the queue re-picks it: \`glab issue update "\${NUM}" --unassign --unlabel in-progress\`.NEVER leave the issue OPEN with \`in-progress\` still on it — that strands it as a zombie (the claim queue skips \`in-progress\`, so the remaining scope is never re-picked). **Do NOT \`git pull\`** from inside this phase — the work is already integrated on GitLab via \`glab mr merge\`; leave the user's working tree alone.`,- // v11 default — follow-ups only applied `plan` (bumped to v12 for dispatch + contributor labels)-`[Claim Issue: {appName}] Claim and ship the next open GitLab issue+ // v13 default prompt — reviews ran against the MR/PR diff after it was opened+ `[Claim Issue: {appName}] Claim and ship the next open GitLab issuePick the next available unclaimed open GitLab issue, **create your own worktree at \`claim/issue-<num>\`**, implement the fix, ship a merge request (MR) that closes the issue, and clean up. This is the \`/claim --issues\` flow for GitLab — same in-flight scan, same branch naming, same no-local-merge cleanup, but the work source is the repo's **GitLab** issue tracker and the forge CLI is \`glab\` (not \`gh\`). **YOU pick the issue in Phase 1 — the scheduler does not reserve one for you.** Picking at execution time and immediately claiming (worktree + assignee + label) **narrows** the window for two concurrent runs to collide on the same issue — it does NOT eliminate it. Do NOT modify files in the source repo directly; ALL editing happens inside the worktree you create.@@ -5618,7 +6027,7 @@ Read the full issue (\`glab issue view "\${NUM}"\`) before writing any code. **EWrite the code, tests, and any docs the issue requires. Follow the repo conventions in CLAUDE.md. Run the relevant test suite as you go.-**Roll discovered backbone work INTO this MR** — small supporting helpers, refactors, and tests that the fix depends on belong here, not a follow-up. Only defer genuinely-large adjacent work; when you do, file a NEW issue (\`glab issue create\`) tagged \`plan\` that references this one (\`Related to #<num>\`).+**Roll discovered backbone work INTO this MR** — small supporting helpers, refactors, and tests that the fix depends on belong here, not a follow-up. Only defer genuinely-large adjacent work; when you do, file a NEW issue (\`glab issue create\`) tagged \`plan\` that references this one (\`Related to #<num>\`). Choose independent dispatch hints (\`model:light|medium|heavy\`, \`effort:low|medium|high|xhigh|max\`) and contributor labels (\`good first issue\`, \`help wanted\`) only when justified; omit an axis rather than guessing; create each missing label immediately before applying it; use repeated \`--label\` flags; do not prefix the title with \`[category]\` / \`[model:…]\`.Commit with a conventional message referencing the issue:@@ -5636,18 +6045,21 @@ This flow ships GitLab issues — it does NOT touch PLAN.md. The audit trail is## Phase 6 — Review and ship-The configured reviewers for this task, in order, are \`{reviewers}\`. \`claude\` / \`codex\` / \`antigravity\` (CLI binary: \`agy\`) / \`grok\` invoke a local-CLI critique. (\`copilot\` is GitHub-only — skip it on GitLab.) When more than one is configured, run each in the listed order before merging.+The configured reviewers for this task, in order, are \`{reviewers}\`. \`claude\` / \`codex\` / \`antigravity\` (CLI binary: \`agy\`) / \`grok\` invoke a local-CLI critique; \`lmstudio\` / \`ollama\` use the appended Local Reviewer Procedure. Run each in order before merging.1. **Self-review your diff for reuse, quality, and efficiency** (DRY, dead code, naming, simpler equivalents, missed edge cases) and fix findings in the same diff BEFORE the reviewers run. Claude Code runs this as the three-agent \`/simplify\` pass; on other CLIs, do the equivalent review by hand.-2. **Wait for each configured CLI reviewer's findings BEFORE merging.** For \`claude\` / \`codex\` / \`antigravity\` (CLI binary: \`agy\`) / \`grok\`, invoke that CLI headless against the MR diff, apply fixes, run tests, re-push — capped at 3 rounds — then advance to the next reviewer. A configured CLI reviewer whose binary is not on PATH is UNSATISFIED, not clean — that is a broken setup, not a passing review. Do NOT substitute your own self-review and do NOT merge; comment on the MR naming the missing command and stop.+2. **Wait for each configured reviewer's valid findings BEFORE merging.** Invoke CLI reviewers headless against the MR diff; invoke local LLM reviewers through the appended endpoint procedure. Apply fixes, run tests, and re-push — capped at 3 rounds — then advance. A missing CLI, timeout, transport failure, malformed response, or empty response is UNSATISFIED, not clean. Do NOT substitute your own self-review or merge; comment on the MR naming the failure and stop.**Review-stuck cleanup** (after 3 unresolved rounds): post one summarizing MR note (\`glab mr note\`), then run the worktree-only cleanup (\`cd {repoPath} && git worktree remove "\${WORKTREE}"\`). Leave the local branch, the open MR, the assignee, and the \`in-progress\` label in place so the human picks up cold. Do NOT run Phase 7.-3. **Merge via \`glab mr merge\`** — NEVER a local \`git merge\`. \`glab mr merge\` takes the **MR IID**, which is NOT the issue number — resolve it from the source branch first, then merge by that IID:+3. **Merge immediately via \`glab mr merge\`** — NEVER a local \`git merge\`. \`glab mr merge\` takes the **MR IID**, which is NOT the issue number — resolve it from the source branch first, merge, then verify remote state:\`\`\`bashMR_IID="$(glab mr list --source-branch "claim/issue-\${NUM}" -F json | sed -n 's/.*"iid":\\([0-9]\\{1,\\}\\).*/\\1/p' | head -1)"- glab mr merge "\${MR_IID}" --yes --remove-source-branch \\- || glab mr merge "\${MR_IID}" --yes --squash --remove-source-branch+ glab mr merge "\${MR_IID}" --yes --remove-source-branch || {+ glab mr view "\${MR_IID}" -F json | jq -e 'select((.state | ascii_downcase) == "merged")' >/dev/null || glab mr merge "\${MR_IID}" --yes --squash --remove-source-branch+ }+ glab mr view "\${MR_IID}" -F json | jq -er 'select((.state | ascii_downcase) == "merged") | .state'\`\`\`+ The verification command must succeed and print a merged state. An opened/closed state or missing value is not success; investigate CI, review, and branch protection, then retry. Do not enter Phase 7 until the forge confirms the MR is merged.## Phase 7 — Clean up (post-merge ONLY)@@ -5659,15 +6071,15 @@ git worktree remove "\${WORKTREE}"git branch -d "claim/issue-\${NUM}"\`\`\`-If \`git branch -d\` refuses, use \`-D\` — the MR is confirmed merged, so the local branch is redundant.+If \`git branch -d\` refuses, fetch the default branch and re-check the MR's merged state. Retry \`-d\` only when Git proves the branch integrated; otherwise leave it for reconciliation. Never force-delete with \`-D\`.**Reconcile the issue — did this MR FULLY satisfy its scope?**- **Yes (full)** — the \`Closes #\${NUM}\` line already auto-closed it on merge to the default branch; if it's somehow still open, close it (\`glab issue close "\${NUM}"\`) and remove the label (\`glab issue update "\${NUM}" --unlabel in-progress\`).-- **No — the remainder is a clean, separable chunk** — close THIS issue with a summarizing note (shipped ✓ / moved to #NEW), remove \`in-progress\`, and file ONE tightly-scoped follow-up for the remainder: \`glab issue create --title "…" --label plan --description "…\\n\\nRefs #\${NUM}"\` (carry over any \`area:*\` labels the issue had).+- **No — the remainder is a clean, separable chunk** — close THIS issue with a summarizing note (shipped ✓ / moved to #NEW), remove \`in-progress\`, and file ONE tightly-scoped follow-up for the remainder: \`glab issue create --title "…" --label plan [--label model:<tier>] [--label effort:<level>] [--label "good first issue"] [--label "help wanted"] --description "…\\n\\nRefs #\${NUM}"\` (carry over any \`area:*\` labels the issue had; choose the optional labels independently and only when justified — a leftover mechanical sweep is not a good first issue).- **No — the remainder is a continuation of the same scope** — keep the issue OPEN, post a \`Done ✓ / Remaining ▢\` note, and release the claim so the queue re-picks it: \`glab issue update "\${NUM}" --unassign --unlabel in-progress\`.NEVER leave the issue OPEN with \`in-progress\` still on it — that strands it as a zombie (the claim queue skips \`in-progress\`, so the remaining scope is never re-picked). **Do NOT \`git pull\`** from inside this phase — the work is already integrated on GitLab via \`glab mr merge\`; leave the user's working tree alone.`,- // v13 default prompt — reviews ran against the MR/PR diff after it was opened+ // v14 default prompt — pre-{issueExcludeLabels} placeholder (Phase 1 step 4's blocking-label list was still hardcoded literal text; mirrors claim-issue v15)`[Claim Issue: {appName}] Claim and ship the next open GitLab issuePick the next available unclaimed open GitLab issue, **create your own worktree at \`claim/issue-<num>\`**, implement the fix, ship a merge request (MR) that closes the issue, and clean up. This is the \`/claim --issues\` flow for GitLab — same in-flight scan, same branch naming, same no-local-merge cleanup, but the work source is the repo's **GitLab** issue tracker and the forge CLI is \`glab\` (not \`gh\`). **YOU pick the issue in Phase 1 — the scheduler does not reserve one for you.** Picking at execution time and immediately claiming (worktree + assignee + label) **narrows** the window for two concurrent runs to collide on the same issue — it does NOT eliminate it. Do NOT modify files in the source repo directly; ALL editing happens inside the worktree you create.@@ -5735,7 +6147,7 @@ Read the full issue (\`glab issue view "\${NUM}"\`) before writing any code. **E(A too-large scope is NOT in this list — it has its own park path below.)-**A genuinely too-large issue needs parking so the drain converges.** If the work is bigger than one coherent claim — it would touch files far outside the issue's scope (>5 unrelated files) — and you can't carve a valuable standalone slice to partial-ship via Phase 5's \`Refs\` path, post a brief note naming the split you'd suggest, **tag it \`needs-input\`** (\`glab issue update "\${NUM}" --label needs-input\`), release the claim markers (\`glab issue update "\${NUM}" --unassign --unlabel in-progress\`), remove the worktree, and exit — splitting an omnibus issue is a human call, and parking it stops a perpetual drain from re-picking the same un-shippable issue every pass (Phase 1 step 4 skips \`needs-input\`).+**A genuinely too-large issue needs parking so the drain converges.** If the work is bigger than one coherent claim — it would touch files far outside the issue's scope (>5 unrelated files) — and you can't carve a valuable standalone slice to partial-ship via Phase 6's \`Refs\` path, post a brief note naming the split you'd suggest, **tag it \`needs-input\`** (\`glab issue update "\${NUM}" --label needs-input\`), release the claim markers (\`glab issue update "\${NUM}" --unassign --unlabel in-progress\`), remove the worktree, and exit — splitting an omnibus issue is a human call, and parking it stops a perpetual drain from re-picking the same un-shippable issue every pass (Phase 1 step 4 skips \`needs-input\`).**Ambiguity is NOT a release trigger — decide, don't defer.** If the issue is merely open to more than one reasonable reading, or leaves a design choice unstated, do NOT bail to \`needs-input\`. Pick the most reasonable interpretation, record the approach you chose in a brief issue note (\`glab issue note "\${NUM}" -m "..."\`) so the decision is on the record, and implement it. The user would rather iterate on top of a shipped best-guess than have the issue parked waiting on a decision they didn't ask to make. Reserve \`needs-input\` — which pulls the issue out of the autonomous queue — for the narrow cases where proceeding would be **destructive or irreversible**, or genuinely requires the human: specific hardware/credentials you don't have, or a judgment only they can make. In those cases only, post the explaining note, **tag it \`needs-input\`** (\`glab issue update "\${NUM}" --label needs-input\`), release the claim markers (\`glab issue update "\${NUM}" --unassign --unlabel in-progress\`), remove the worktree, and exit cleanly. **That label is what lets an autonomous drain converge** — Phase 1 step 4 skips \`needs-input\` issues. Never leave a half-claimed issue.@@ -5751,27 +6163,36 @@ Commit with a conventional message referencing the issue:<type>: <one-line description> (#<num>)\`\`\`-## Phase 5 — Open the merge request+## Phase 5 — Review locally (BEFORE any MR exists)-This flow ships GitLab issues — it does NOT touch PLAN.md. The audit trail is the merged MR + \`git log\`.+**Every reviewer that can read the working tree runs HERE, while there is still no MR.** Open the MR only once the branch is already review-clean: the MR then carries the finished diff, and the only things left to satisfy are CI and the reviewers that genuinely cannot start until an MR is open.-1. If the repo maintains a changelog, record a one-line entry **following the convention that repo documents** — read its \`CLAUDE.md\` and changelog README (e.g. \`.changelog/README.md\`) first. Some repos collect per-branch fragments in a directory (e.g. \`.changelog/next/\`) via a helper script rather than appending to one shared file, precisely so parallel agents don't conflict on every merge; use that flow when it's documented. Fall back to appending to the unreleased section (\`.changelog/NEXT.md\`, or \`## Unreleased\` in \`CHANGELOG.md\`) in the repo's existing prose style only when no convention is documented. If the repo has no changelog, skip this.-2. Push the branch: \`git push -u origin "claim/issue-\${NUM}"\`-3. Open the MR with \`glab mr create --fill --source-branch "claim/issue-\${NUM}" --target-branch "\${DEFAULT_BRANCH}" --yes\`. **Choose the issue trailer deliberately:** if this MR FULLY satisfies the issue's scope, the description MUST contain \`Closes #\${NUM}\` so the merge auto-closes it; if you deliberately shipped only PART of the issue (a valuable slice with real scope remaining), use \`Refs #\${NUM}\` instead (NOT \`Closes\`) and add a \`## Remaining\` section listing what's left — Phase 7 reconciles the issue so it is never stranded. Summarize what shipped + a short test plan (pass \`--description\` if \`--fill\` didn't capture it).+The configured reviewers for this task, in order, are \`{reviewers}\`. Split that list in two, preserving its order:-## Phase 6 — Review and ship+- **LOCAL reviewers — every token that is NOT an \`@<login>\`.** \`claude\` / \`codex\` / \`antigravity\` (CLI binary: \`agy\`) / \`grok\` / \`cursor\` invoke a local-CLI critique; \`lmstudio\` / \`ollama\` use the appended Local Reviewer Procedure. They read this branch's own diff and need no MR — run them in THIS phase.+- **MR-SIDE reviewers — every \`@<login>\` token**, plus any review bot the project requests automatically when an MR opens. They review server-side and cannot start before the MR exists — they run in Phase 6.-The configured reviewers for this task, in order, are \`{reviewers}\`. \`claude\` / \`codex\` / \`antigravity\` (CLI binary: \`agy\`) / \`grok\` invoke a local-CLI critique; \`lmstudio\` / \`ollama\` use the appended Local Reviewer Procedure. Run each in order before merging.+1. **Write the changelog entry now, not after the reviewers run** — every commit the reviewers are about to read must already be on the branch, or the MR carries work nobody reviewed. If the repo maintains a changelog, record a one-line entry **following the convention that repo documents** — read its \`CLAUDE.md\` and changelog README (e.g. \`.changelog/README.md\`) first. Some repos collect per-branch fragments in a directory (e.g. \`.changelog/next/\`) via a helper script rather than appending to one shared file, precisely so parallel agents don't conflict on every merge; use that flow when it's documented. Fall back to appending to the unreleased section (\`.changelog/NEXT.md\`, or \`## Unreleased\` in \`CHANGELOG.md\`) in the repo's existing prose style only when no convention is documented. If the repo has no changelog, skip this.+2. **Self-review your diff for reuse, quality, and efficiency** (DRY, dead code, naming, simpler equivalents, missed edge cases) and fix the findings in the same diff, before any reviewer runs. Claude Code runs this as the three-agent \`/simplify\` pass; on other CLIs, do the equivalent review by hand.+3. **Run each LOCAL reviewer in the listed order against the BRANCH diff, not an MR diff.** No MR exists yet, so \`glab mr diff\` has nothing to read — use the CLI's own base-diff mode or \`git diff "origin/\${DEFAULT_BRANCH}...HEAD"\`. Apply the findings, run the tests, and commit the fixes — capped at 3 rounds per reviewer — then advance to the next reviewer. A missing CLI, timeout, transport failure, malformed response, or empty response is UNSATISFIED, not clean. Do NOT substitute your own self-review, and do NOT open an MR on the strength of it.+4. **If the branch cannot be brought to a shippable state here, do NOT open an MR** — that is a local reviewer still unsatisfied after 3 rounds, or fixes that leave the build/tests red. Post a note on the ISSUE naming the reviewer and the failure (\`glab issue note "\${NUM}" -m "..."\`), leave the assignee and the \`in-progress\` label in place, remove ONLY the worktree (\`cd {repoPath} && git worktree remove "\${WORKTREE}"\`), and stop. The branch stays for a human to pick up cold. Do NOT run Phase 7.-1. **Self-review your diff for reuse, quality, and efficiency** (DRY, dead code, naming, simpler equivalents, missed edge cases) and fix findings in the same diff BEFORE the reviewers run. Claude Code runs this as the three-agent \`/simplify\` pass; on other CLIs, do the equivalent review by hand.-2. **Wait for each configured reviewer's valid findings BEFORE merging.** Invoke CLI reviewers headless against the MR diff; invoke local LLM reviewers through the appended endpoint procedure. Apply fixes, run tests, and re-push — capped at 3 rounds — then advance. A missing CLI, timeout, transport failure, malformed response, or empty response is UNSATISFIED, not clean. Do NOT substitute your own self-review or merge; comment on the MR naming the failure and stop.+## Phase 6 — Open the merge request, satisfy MR-side review + CI, and merge- **Review-stuck cleanup** (after 3 unresolved rounds): post one summarizing MR note (\`glab mr note\`), then run the worktree-only cleanup (\`cd {repoPath} && git worktree remove "\${WORKTREE}"\`). Leave the local branch, the open MR, the assignee, and the \`in-progress\` label in place so the human picks up cold. Do NOT run Phase 7.-3. **Merge immediately via \`glab mr merge\`** — NEVER a local \`git merge\`. \`glab mr merge\` takes the **MR IID**, which is NOT the issue number — resolve it from the source branch first, merge, then verify remote state:+Every local reviewer's fixes are already committed, so the MR opens against finished work. This flow ships GitLab issues — it does NOT touch PLAN.md. The audit trail is the merged MR + \`git log\`.++1. Push the branch: \`git push -u origin "claim/issue-\${NUM}"\`. Then confirm \`git log --oneline @{u}..HEAD\` is empty — if it isn't, a Phase 5 review fix never left the machine and the MR would be opened against a stale diff; push again before continuing.+2. Open the MR with \`glab mr create --fill --source-branch "claim/issue-\${NUM}" --target-branch "\${DEFAULT_BRANCH}" --yes\`. **Choose the issue trailer deliberately:** if this MR FULLY satisfies the issue's scope, the description MUST contain \`Closes #\${NUM}\` so the merge auto-closes it; if you deliberately shipped only PART of the issue (a valuable slice with real scope remaining), use \`Refs #\${NUM}\` instead (NOT \`Closes\`) and add a \`## Remaining\` section listing what's left — Phase 7 reconciles the issue so it is never stranded. Summarize what shipped + a short test plan (pass \`--description\` if \`--fill\` didn't capture it).+3. **Satisfy the MR-SIDE reviewers.** For each \`@<login>\` from the Phase 5 split, request the review now (resolve \`MR_IID\` from the source branch exactly as step 5 does, then \`glab mr update "\${MR_IID}" --reviewer <login>\`, dropping the \`@\`; if glab rejects the flag, run \`glab mr update --help\` rather than guessing), poll every 5–15s, and address the findings — push fixes, capped at 3 rounds per reviewer. Their approval gates the merge. If the project auto-requests a review bot when the MR opens, wait that round out and address it the same way. With no \`@<login>\` configured and no bot review appearing, this step is a no-op.++ **Review-stuck cleanup** (an MR-side reviewer still unsatisfied after 3 rounds): post one summarizing MR note (\`glab mr note\`), then run the worktree-only cleanup (\`cd {repoPath} && git worktree remove "\${WORKTREE}"\`). Leave the local branch, the open MR, the assignee, and the \`in-progress\` label in place so the human picks up cold. Do NOT run Phase 7.+4. **Let required CI finish and go green** — inspect the MR's pipeline (\`glab ci status\` on the branch, or \`glab mr view "\${MR_IID}"\`). A red required pipeline is not merge-eligible: fix it and re-push (same 3-round cap), or, if it stays red, stop exactly as the review-stuck cleanup above does.+5. **Merge immediately via \`glab mr merge\`** — NEVER a local \`git merge\`. \`glab mr merge\` takes the **MR IID**, which is NOT the issue number — resolve it from the source branch first, merge, then verify remote state:\`\`\`bashMR_IID="$(glab mr list --source-branch "claim/issue-\${NUM}" -F json | sed -n 's/.*"iid":\\([0-9]\\{1,\\}\\).*/\\1/p' | head -1)"glab mr merge "\${MR_IID}" --yes --remove-source-branch || {- glab mr view "\${MR_IID}" -F json | jq -e 'select((.state | ascii_downcase) == "merged")' >/dev/null || glab mr merge "\${MR_IID}" --yes --squash --remove-source-branch+ glab mr view "\${MR_IID}" -F json | jq -e 'select((.state | ascii_downcase) == "merged")' >/dev/null || \+ glab mr merge "\${MR_IID}" --yes --squash --remove-source-branch}glab mr view "\${MR_IID}" -F json | jq -er 'select((.state | ascii_downcase) == "merged") | .state'\`\`\`@@ -5795,7 +6216,7 @@ If \`git branch -d\` refuses, fetch the default branch and re-check the MR's mer- **No — the remainder is a continuation of the same scope** — keep the issue OPEN, post a \`Done ✓ / Remaining ▢\` note, and release the claim so the queue re-picks it: \`glab issue update "\${NUM}" --unassign --unlabel in-progress\`.NEVER leave the issue OPEN with \`in-progress\` still on it — that strands it as a zombie (the claim queue skips \`in-progress\`, so the remaining scope is never re-picked). **Do NOT \`git pull\`** from inside this phase — the work is already integrated on GitLab via \`glab mr merge\`; leave the user's working tree alone.`,- // v14 default prompt — pre-{issueExcludeLabels} placeholder (Phase 1 step 4's blocking-label list was still hardcoded literal text; mirrors claim-issue v15)+ // v15 default — glab recipes still passed `-F json`, which on `glab issue list` is `--output-format` (details|ids|urls), NOT `--output`; it was accepted, ignored, and answered with the human table at exit 0. Superseded by v16.`[Claim Issue: {appName}] Claim and ship the next open GitLab issuePick the next available unclaimed open GitLab issue, **create your own worktree at \`claim/issue-<num>\`**, implement the fix, ship a merge request (MR) that closes the issue, and clean up. This is the \`/claim --issues\` flow for GitLab — same in-flight scan, same branch naming, same no-local-merge cleanup, but the work source is the repo's **GitLab** issue tracker and the forge CLI is \`glab\` (not \`gh\`). **YOU pick the issue in Phase 1 — the scheduler does not reserve one for you.** Picking at execution time and immediately claiming (worktree + assignee + label) **narrows** the window for two concurrent runs to collide on the same issue — it does NOT eliminate it. Do NOT modify files in the source repo directly; ALL editing happens inside the worktree you create.@@ -5825,7 +6246,7 @@ Run steps 1–5 in order.4. **Pick the target issue:** walk the candidate list oldest-first and pick the FIRST issue where ALL of the following are true:- Its number (\`iid\`) is NOT in the in-flight set.- It has NO assignees (an assignee means another machine/human already claimed it).- - It does NOT carry any of these blocking labels: \`in-progress\`, \`blocked\`, \`needs-input\`, \`future\`, \`wontfix\`, \`question\`, \`discussion\`.+ - It does NOT carry any of these blocking labels: {issueExcludeLabels}.- It is NOT a tracking/umbrella **epic** — recognized by an \`epic\` label, a title ending in "(epic)", OR a title beginning with an \`[epic]\` bracket or \`Epic:\` tag (e.g. "[Epic] …" / "Epic: …", case-insensitive). Leave epics for a human to split. **The bare \`plan\` label is NOT a skip signal** — it marks the claimable queue, not a blocker.5. **If no eligible issue exists**, exit cleanly — an empty actionable queue is a healthy state, not a failure.@@ -5907,8 +6328,7 @@ Every local reviewer's fixes are already committed, so the MR opens against fini\`\`\`bashMR_IID="$(glab mr list --source-branch "claim/issue-\${NUM}" -F json | sed -n 's/.*"iid":\\([0-9]\\{1,\\}\\).*/\\1/p' | head -1)"glab mr merge "\${MR_IID}" --yes --remove-source-branch || {- glab mr view "\${MR_IID}" -F json | jq -e 'select((.state | ascii_downcase) == "merged")' >/dev/null || \- glab mr merge "\${MR_IID}" --yes --squash --remove-source-branch+ glab mr view "\${MR_IID}" -F json | jq -e 'select((.state | ascii_downcase) == "merged")' >/dev/null || glab mr merge "\${MR_IID}" --yes --squash --remove-source-branch}glab mr view "\${MR_IID}" -F json | jq -er 'select((.state | ascii_downcase) == "merged") | .state'\`\`\`@@ -5932,7 +6352,7 @@ If \`git branch -d\` refuses, fetch the default branch and re-check the MR's mer- **No — the remainder is a continuation of the same scope** — keep the issue OPEN, post a \`Done ✓ / Remaining ▢\` note, and release the claim so the queue re-picks it: \`glab issue update "\${NUM}" --unassign --unlabel in-progress\`.NEVER leave the issue OPEN with \`in-progress\` still on it — that strands it as a zombie (the claim queue skips \`in-progress\`, so the remaining scope is never re-picked). **Do NOT \`git pull\`** from inside this phase — the work is already integrated on GitLab via \`glab mr merge\`; leave the user's working tree alone.`,- // v15 default — glab recipes still passed `-F json`, which on `glab issue list` is `--output-format` (details|ids|urls), NOT `--output`; it was accepted, ignored, and answered with the human table at exit 0. Superseded by v16.+ // v16 default prompt (pre-#4852: named CLAUDE.md as the agent-instructions file)`[Claim Issue: {appName}] Claim and ship the next open GitLab issuePick the next available unclaimed open GitLab issue, **create your own worktree at \`claim/issue-<num>\`**, implement the fix, ship a merge request (MR) that closes the issue, and clean up. This is the \`/claim --issues\` flow for GitLab — same in-flight scan, same branch naming, same no-local-merge cleanup, but the work source is the repo's **GitLab** issue tracker and the forge CLI is \`glab\` (not \`gh\`). **YOU pick the issue in Phase 1 — the scheduler does not reserve one for you.** Picking at execution time and immediately claiming (worktree + assignee + label) **narrows** the window for two concurrent runs to collide on the same issue — it does NOT eliminate it. Do NOT modify files in the source repo directly; ALL editing happens inside the worktree you create.@@ -5950,13 +6370,13 @@ Run steps 1–5 in order.\`\`\`bashgit fetch --prune 2>/dev/null# Owner-only mode (default): add --author <owner> (resolve <owner> from the project namespace).- glab issue list --per-page 100 -F json+ glab issue list --per-page 100 --output json# Any-author mode: run the SAME command WITHOUT --author.\`\`\`3. Build the in-flight set. Collect every branch/MR source ref:\`\`\`bashgit branch -a --no-color --format='%(refname:short)'- glab mr list --per-page 100 -F json # read each MR's source_branch+ glab mr list --per-page 100 --output json # read each MR's source_branch\`\`\`For each ref (after stripping any leading \`origin/\` prefix), extract the issue number **only when the ref matches** \`claim/issue-<num>\` (number after \`claim/issue-\`) or \`cos/<task>/issue-<num>/<agent>\` (the \`issue-<num>\` third segment). Do NOT flag an issue just because its bare number appears elsewhere in a ref.4. **Pick the target issue:** walk the candidate list oldest-first and pick the FIRST issue where ALL of the following are true:@@ -6042,11 +6462,11 @@ Every local reviewer's fixes are already committed, so the MR opens against fini4. **Let required CI finish and go green** — inspect the MR's pipeline (\`glab ci status\` on the branch, or \`glab mr view "\${MR_IID}"\`). A red required pipeline is not merge-eligible: fix it and re-push (same 3-round cap), or, if it stays red, stop exactly as the review-stuck cleanup above does.5. **Merge immediately via \`glab mr merge\`** — NEVER a local \`git merge\`. \`glab mr merge\` takes the **MR IID**, which is NOT the issue number — resolve it from the source branch first, merge, then verify remote state:\`\`\`bash- MR_IID="$(glab mr list --source-branch "claim/issue-\${NUM}" -F json | sed -n 's/.*"iid":\\([0-9]\\{1,\\}\\).*/\\1/p' | head -1)"+ MR_IID="$(glab mr list --source-branch "claim/issue-\${NUM}" --output json | sed -n 's/.*"iid":\\([0-9]\\{1,\\}\\).*/\\1/p' | head -1)"glab mr merge "\${MR_IID}" --yes --remove-source-branch || {- glab mr view "\${MR_IID}" -F json | jq -e 'select((.state | ascii_downcase) == "merged")' >/dev/null || glab mr merge "\${MR_IID}" --yes --squash --remove-source-branch+ glab mr view "\${MR_IID}" --output json | jq -e 'select((.state | ascii_downcase) == "merged")' >/dev/null || glab mr merge "\${MR_IID}" --yes --squash --remove-source-branch}- glab mr view "\${MR_IID}" -F json | jq -er 'select((.state | ascii_downcase) == "merged") | .state'+ glab mr view "\${MR_IID}" --output json | jq -er 'select((.state | ascii_downcase) == "merged") | .state'\`\`\`The verification command must succeed and print a merged state. An opened/closed state or missing value is not success; investigate CI, review, and branch protection, then retry. Do not enter Phase 7 until the forge confirms the MR is merged.@@ -7157,7 +7577,135 @@ This flow ships GitHub issues — it does NOT touch PLAN.md. The audit trail isThe configured reviewers for this task, in order, are \`{reviewers}\`. \`copilot\` waits for GitHub's auto-review; \`claude\` / \`codex\` / \`antigravity\` / \`grok\` invoke a local-CLI critique. When more than one is configured, run each in the listed order before merging — this mirrors slashdo's \`/do:pr --review-with <list>\`.1. **Self-review your diff for reuse, quality, and efficiency** (DRY, dead code, naming, simpler equivalents, missed edge cases) and fix findings in the same diff BEFORE the reviewers run. Claude Code runs this as the three-agent \`/simplify\` pass; on other CLIs, do the equivalent review by hand.-2. **Wait for each configured reviewer's findings BEFORE merging.** \`gh pr merge --auto\` only waits for required status checks; it does NOT wait for code-review feedback. Run the reviewers in the listed order (\`{reviewers}\`); for \`copilot\`, poll up to 10 minutes for its review and address \`COMMENTED\` / \`CHANGES_REQUESTED\` findings (commit + push inside the worktree, re-poll), capped at 3 rounds. For \`claude\` / \`codex\` / \`antigravity\` / \`grok\`, invoke that CLI headless against the PR diff, apply fixes, run tests, re-push — capped at 3 rounds — then advance to the next reviewer.+2. **Wait for each configured reviewer's findings BEFORE merging.** \`gh pr merge --auto\` only waits for required status checks; it does NOT wait for code-review feedback. Run the reviewers in the listed order (\`{reviewers}\`); for \`copilot\`, poll up to 10 minutes for its review and address \`COMMENTED\` / \`CHANGES_REQUESTED\` findings (commit + push inside the worktree, re-poll), capped at 3 rounds. For \`claude\` / \`codex\` / \`antigravity\` / \`grok\`, invoke that CLI headless against the PR diff, apply fixes, run tests, re-push — capped at 3 rounds — then advance to the next reviewer.++ **Review-stuck cleanup** (after 3 unresolved rounds): post one summarizing PR comment (\`gh pr comment\`), then run the worktree-only cleanup (\`cd {repoPath} && git worktree remove "\${WORKTREE}"\`). Leave the local branch, the open PR, the assignee, and the \`in-progress\` label in place so the human picks up cold. Do NOT run Phase 7.+3. **Merge via \`gh pr merge\`** — NEVER a local \`git merge\`. The repo may allow only one method, so try in order and use the first that succeeds:+ \`\`\`bash+ gh pr merge <pr-num> --auto --delete-branch \\+ || gh pr merge <pr-num> --merge --delete-branch \\+ || gh pr merge <pr-num> --squash --delete-branch \\+ || gh pr merge <pr-num> --rebase --delete-branch+ \`\`\`++## Phase 7 — Clean up (post-merge ONLY)++This phase runs only after the PR merged via Phase 6. From the **source repo** (cd back to {repoPath} first):++\`\`\`bash+cd {repoPath}+git worktree remove "\${WORKTREE}"+git branch -d "claim/issue-\${NUM}"+\`\`\`++If \`git branch -d\` refuses (the PR squash-merged on GitHub but local doesn't know yet), use \`-D\` — the PR is confirmed merged, so the local branch is redundant.++**Reconcile the issue — did this PR FULLY satisfy its scope?**+- **Yes (full)** — the \`Closes #\${NUM}\` trailer already auto-closed it; if it's somehow still open, close it (\`gh issue close "\${NUM}"\`) and remove the label (\`gh issue edit "\${NUM}" --remove-label in-progress\`).+- **No — the remainder is a clean, separable chunk** — close THIS issue with a summarizing comment (shipped ✓ / moved to #NEW), remove \`in-progress\`, and file ONE tightly-scoped follow-up for the remainder: \`gh issue create --title "…" --label plan --body "…\\n\\nRefs #\${NUM}"\` (carry over any \`area:*\` labels the issue had).+- **No — the remainder is a continuation of the same scope** — keep the issue OPEN, post a \`Done ✓ / Remaining ▢\` comment, and release the claim so the queue re-picks it: \`gh issue edit "\${NUM}" --remove-label in-progress --remove-assignee @me\`.++NEVER leave the issue OPEN with \`in-progress\` still on it — that strands it as a zombie (the claim queue skips \`in-progress\`, so the remaining scope is never re-picked). **Do NOT \`git pull\`** from inside this phase — the work is already integrated on GitHub via \`gh pr merge\`; leave the user's working tree alone.`,++ // v9 default prompt — pre-changelog-fragment-deference (issue #3998)+ `[Claim Issue: {appName}] Claim and ship the next open GitHub issue++Pick the next available unclaimed open GitHub issue, **create your own worktree at \`claim/issue-<num>\`**, implement the fix, ship a PR that closes the issue, and clean up. This is the \`/claim --issues\` flow — same in-flight scan, same branch naming, same no-local-merge cleanup, but the work source is the repo's GitHub issue tracker instead of PLAN.md. **YOU pick the issue in Phase 1 — the scheduler does not reserve one for you.** Picking at execution time and immediately claiming (worktree + assignee + label) **narrows** the window for two concurrent runs to collide on the same issue — it does NOT eliminate it. Do NOT modify files in the source repo directly; ALL editing happens inside the worktree you create.++{issueAuthorFilter}++**How claiming works.** An issue is "in flight" when its number appears as the issue-position segment in either a \`claim/issue-<num>\` ref (the human/TUI pattern) or a \`cos/<task>/issue-<num>/<agent>\` ref (the CoS sub-agent pattern) across local branches, remote branches, or open PR head refs — OR the issue is already assigned to someone OR carries an \`in-progress\` label. The \`claim/issue-<num>\` branch + the assignee/\`in-progress\` markers you set ARE the claim, visible to every other agent (including parallel machines) and to the human running \`/claim --issues\` in a TUI.++## Phase 1 — Pick the target issue++Run steps 1–5 in order.++1. cd into the repo root ({repoPath}) and confirm GitHub is the forge: \`gh repo view --json nameWithOwner -q .nameWithOwner\`. If \`gh\` is not authenticated or the remote is not GitHub, exit cleanly — this task only works against GitHub issue trackers.+2. List candidate open issues **oldest-first**, honoring the author filter described above. \`gh issue list\` defaults to newest-first, so order on the SERVER with \`--search "sort:created-asc"\` — a client-side \`jq\` sort would only reorder the already-truncated newest page, dropping the true oldest issues on repos with more than \`--limit\` open issues:+ \`\`\`bash+ git fetch --prune 2>/dev/null+ # Author filter (see the block above). Pass --author as a QUOTED single token —+ # do NOT pack flag+value into one variable: a bare \`$VAR\` holding "--author x"+ # is a single argv token in zsh (no word-splitting) and gh rejects it.+ # Owner-only mode (default): resolve the owner, then add --author "$OWNER"+ OWNER="$(gh repo view --json owner -q .owner.login)"+ gh issue list --state open --author "$OWNER" --search "sort:created-asc" --json number,title,author,assignees,labels,createdAt --limit 100+ # Any-author mode: run the SAME command WITHOUT the --author "$OWNER" flag.+ \`\`\`+3. Build the in-flight set. Collect every branch/PR ref:+ \`\`\`bash+ git branch -a --no-color --format='%(refname:short)'+ gh pr list --state open --json headRefName -q '.[].headRefName' 2>/dev/null+ \`\`\`+ For each ref (after stripping any leading \`origin/\` / \`upstream/\` prefix), extract the issue number **only when the ref matches** \`claim/issue-<num>\` (number after \`claim/issue-\`) or \`cos/<task>/issue-<num>/<agent>\` (the \`issue-<num>\` third segment). Do NOT flag an issue just because its bare number appears elsewhere in a ref.+4. **Pick the target issue:** walk the candidate list oldest-first and pick the FIRST issue where ALL of the following are true:+ - Its number is NOT in the in-flight set.+ - It has NO assignees (an assignee means another machine/human already claimed it).+ - It does NOT carry any of these blocking labels: \`in-progress\`, \`blocked\`, \`needs-input\`, \`future\`, \`wontfix\`, \`question\`, \`discussion\`.+ - It is NOT a tracking/umbrella **epic** — recognized by an \`epic\` label, a title ending in "(epic)", OR a title beginning with an \`[epic]\` bracket or \`Epic:\` tag (e.g. "[Epic] …" / "Epic: …", case-insensitive). An epic needs per-slice partial-ship (each slice its own PR, \`Refs\` not \`Closes\`), so leave it for a human or \`/claim --issues\` to split — don't claim it wholesale here. **The bare \`plan\` label is NOT a skip signal.** \`do-replan --issues\` (and \`/do:replan --issues\`) labels EVERY migrated backlog item \`plan\` — atomic bug-fixes included — so \`plan\` marks the *claimable* queue exactly as \`/do:next --issues\` treats it (it is that flow's required candidate label). Skipping all \`plan\` issues would discard the entire actionable backlog and falsely report an empty queue.+5. **If no eligible issue exists**, exit cleanly — an empty actionable queue is a healthy state, not a failure.++Capture the issue number as \`NUM\`, its title, and its full body — you'll reuse them in the PR and the \`Closes #<num>\` trailer.++## Phase 2 — Claim (worktree + markers)++Create the worktree on a branch named \`claim/issue-<num>\`, then set the cross-machine claim markers. Do all editing inside the worktree, NEVER in the source repo's working tree.++\`\`\`bash+NUM=<picked-number>+WORKTREE="{worktreesRoot}/claim-issue-\${NUM}"+mkdir -p {worktreesRoot}+git fetch origin main+git worktree add -b "claim/issue-\${NUM}" "\${WORKTREE}" origin/main+# Cross-machine claim markers (best-effort — do not abort the run if these fail):+gh issue edit "\${NUM}" --add-assignee @me 2>/dev/null+gh issue edit "\${NUM}" --add-label in-progress 2>/dev/null+cd "\${WORKTREE}"+\`\`\`++(If the repo's default branch is not \`main\`, detect it with \`gh repo view --json defaultBranchRef -q .defaultBranchRef.name\` and substitute it for \`main\` above.)++**If \`git worktree add\` fails because the \`claim/issue-<num>\` branch already exists** (a concurrent run won the race, or a remote claim branch is now visible), do NOT force or reuse it — that branch IS another run's claim. Treat the issue as in-flight, return to Phase 1, and pick the next eligible issue; if nothing else is eligible, exit cleanly. Stash \`WORKTREE\` — you'll need it for Phase 7 cleanup.++## Phase 3 — Verify still valid++Read the full issue (\`gh issue view "\${NUM}" --comments\`) before writing any code. **If ANY of these are true, release the claim and re-pick** (remove the assignee + \`in-progress\` label you set, remove the worktree, return to Phase 1):++- A comment indicates the issue was already fixed, superseded, or closed-then-reopened-for-tracking.+- The request references a function, file, or component that no longer exists (\`grep -rn\` the named identifiers — if they're gone, the issue is stale).++(A too-large scope is NOT in this release-and-re-pick list — releasing it just lets the next pass re-pick the same oversized issue. It has its own park path below.)++**A genuinely too-large issue needs parking so the drain converges.** If the work is bigger than one coherent claim — it would touch files far outside the issue's scope (>5 unrelated files) — and you can't carve a valuable standalone slice to partial-ship via Phase 5's \`Refs\` path, post a brief comment naming the split you'd suggest, **tag it \`needs-input\`** (\`gh issue edit "\${NUM}" --add-label needs-input\`), release the claim markers (\`gh issue edit "\${NUM}" --remove-assignee @me --remove-label in-progress\`), remove the worktree, and exit — splitting an omnibus issue is a human call, and parking it is what stops a perpetual drain from re-picking the same un-shippable issue every pass (Phase 1 step 4 skips \`needs-input\`).++**Ambiguity is NOT a release trigger — decide, don't defer.** If the issue is merely open to more than one reasonable reading, or leaves a design choice unstated, do NOT bail to \`needs-input\`. Pick the most reasonable interpretation, record the approach you chose in a brief issue comment (\`gh issue comment "\${NUM}" --body "..."\`) so the decision is on the record, and implement it. The user would rather iterate on top of a shipped best-guess than have the issue parked waiting on a decision they didn't ask to make. Reserve \`needs-input\` — which pulls the issue out of the autonomous queue — for the narrow cases where proceeding would be **destructive or irreversible**, or genuinely requires the human: specific hardware/credentials you don't have, or a judgment only they can make. In those cases only, post the explaining comment, **tag it \`needs-input\`** (\`gh issue edit "\${NUM}" --add-label needs-input\`), release the claim markers (\`gh issue edit "\${NUM}" --remove-assignee @me --remove-label in-progress\`), remove the worktree, and exit cleanly. **That label is what lets an autonomous drain converge** — Phase 1 step 4 skips \`needs-input\` issues. Never leave a half-claimed issue.++## Phase 4 — Implement++Write the code, tests, and any docs the issue requires. Follow the repo conventions in CLAUDE.md (no try/catch in route handlers, functional programming, Zod validation, Tailwind tokens, reactive UI updates). Run the relevant test suite as you go.++**Roll discovered backbone work INTO this PR** — small supporting helpers, refactors, and tests that the fix depends on belong here, not a follow-up. Only defer genuinely-large adjacent work; when you do, file a NEW issue (\`gh issue create\`) tagged \`plan\` that references this one (\`Related to #<num>\`) rather than appending to PLAN.md.++Commit with a conventional message referencing the issue so the trail is grep-able:++\`\`\`+<type>: <one-line description> (#<num>)+\`\`\`++## Phase 5 — Open the PR++This flow ships GitHub issues — it does NOT touch PLAN.md. The audit trail is the merged PR + \`git log\`.++1. If the repo maintains a changelog (\`.changelog/NEXT.md\`, or a \`## Unreleased\` section in \`CHANGELOG.md\`), append a one-line entry mirroring the repo's existing prose style. If no changelog convention exists, skip this — the PR + commit history is the record.+2. Push the branch: \`git push -u origin "claim/issue-\${NUM}"\`+3. Open the PR with \`gh pr create\`. Summarize what shipped + a short test plan. **Choose the issue trailer deliberately:** if this PR FULLY satisfies the issue's scope, the body MUST contain \`Closes #\${NUM}\` so the merge auto-closes it. If you deliberately shipped only PART of the issue (a valuable slice, with real scope still remaining), use \`Refs #\${NUM}\` instead (NOT \`Closes\`) and add a \`## Remaining\` section listing what's left — Phase 7 reconciles the issue so it is never stranded.++## Phase 6 — Review and ship++The configured reviewers for this task, in order, are \`{reviewers}\`. \`copilot\` waits for GitHub's auto-review; \`claude\` / \`codex\` / \`antigravity\` (CLI binary: \`agy\`) / \`grok\` invoke a local-CLI critique. When more than one is configured, run each in the listed order before merging — this mirrors slashdo's \`/do:pr --review-with <list>\`.++1. **Self-review your diff for reuse, quality, and efficiency** (DRY, dead code, naming, simpler equivalents, missed edge cases) and fix findings in the same diff BEFORE the reviewers run. Claude Code runs this as the three-agent \`/simplify\` pass; on other CLIs, do the equivalent review by hand.+2. **Wait for each configured reviewer's findings BEFORE merging.** \`gh pr merge --auto\` only waits for required status checks; it does NOT wait for code-review feedback. Run the reviewers in the listed order (\`{reviewers}\`); for \`copilot\`, poll up to 10 minutes for its review and address \`COMMENTED\` / \`CHANGES_REQUESTED\` findings (commit + push inside the worktree, re-poll), capped at 3 rounds. For \`claude\` / \`codex\` / \`antigravity\` (CLI binary: \`agy\`) / \`grok\`, invoke that CLI headless against the PR diff, apply fixes, run tests, re-push — capped at 3 rounds — then advance to the next reviewer. A configured CLI reviewer whose binary is not on PATH is UNSATISFIED, not clean — that is a broken setup, not a passing review. Do NOT substitute your own self-review and do NOT merge; comment on the PR naming the missing command and stop.**Review-stuck cleanup** (after 3 unresolved rounds): post one summarizing PR comment (\`gh pr comment\`), then run the worktree-only cleanup (\`cd {repoPath} && git worktree remove "\${WORKTREE}"\`). Leave the local branch, the open PR, the assignee, and the \`in-progress\` label in place so the human picks up cold. Do NOT run Phase 7.3. **Merge via \`gh pr merge\`** — NEVER a local \`git merge\`. The repo may allow only one method, so try in order and use the first that succeeds:@@ -7187,7 +7735,7 @@ If \`git branch -d\` refuses (the PR squash-merged on GitHub but local doesn't kNEVER leave the issue OPEN with \`in-progress\` still on it — that strands it as a zombie (the claim queue skips \`in-progress\`, so the remaining scope is never re-picked). **Do NOT \`git pull\`** from inside this phase — the work is already integrated on GitHub via \`gh pr merge\`; leave the user's working tree alone.`,- // v9 default prompt — pre-changelog-fragment-deference (issue #3998)+ // v10 default prompt — pre-converging-Phase-3-release (issue #4106)`[Claim Issue: {appName}] Claim and ship the next open GitHub issuePick the next available unclaimed open GitHub issue, **create your own worktree at \`claim/issue-<num>\`**, implement the fix, ship a PR that closes the issue, and clean up. This is the \`/claim --issues\` flow — same in-flight scan, same branch naming, same no-local-merge cleanup, but the work source is the repo's GitHub issue tracker instead of PLAN.md. **YOU pick the issue in Phase 1 — the scheduler does not reserve one for you.** Picking at execution time and immediately claiming (worktree + assignee + label) **narrows** the window for two concurrent runs to collide on the same issue — it does NOT eliminate it. Do NOT modify files in the source repo directly; ALL editing happens inside the worktree you create.@@ -7276,7 +7824,7 @@ Commit with a conventional message referencing the issue so the trail is grep-abThis flow ships GitHub issues — it does NOT touch PLAN.md. The audit trail is the merged PR + \`git log\`.-1. If the repo maintains a changelog (\`.changelog/NEXT.md\`, or a \`## Unreleased\` section in \`CHANGELOG.md\`), append a one-line entry mirroring the repo's existing prose style. If no changelog convention exists, skip this — the PR + commit history is the record.+1. If the repo maintains a changelog, record a one-line entry **following the convention that repo documents** — read its \`CLAUDE.md\` and changelog README (e.g. \`.changelog/README.md\`) first. Some repos collect per-branch fragments in a directory (e.g. \`.changelog/next/\`) via a helper script rather than appending to one shared file, precisely so parallel agents don't conflict on every merge; use that flow when it's documented. Fall back to appending to the unreleased section (\`.changelog/NEXT.md\`, or \`## Unreleased\` in \`CHANGELOG.md\`) in the repo's existing prose style only when no convention is documented. If the repo has no changelog, skip this — the PR + commit history is the record.2. Push the branch: \`git push -u origin "claim/issue-\${NUM}"\`3. Open the PR with \`gh pr create\`. Summarize what shipped + a short test plan. **Choose the issue trailer deliberately:** if this PR FULLY satisfies the issue's scope, the body MUST contain \`Closes #\${NUM}\` so the merge auto-closes it. If you deliberately shipped only PART of the issue (a valuable slice, with real scope still remaining), use \`Refs #\${NUM}\` instead (NOT \`Closes\`) and add a \`## Remaining\` section listing what's left — Phase 7 reconciles the issue so it is never stranded.@@ -7314,8 +7862,7 @@ If \`git branch -d\` refuses (the PR squash-merged on GitHub but local doesn't k- **No — the remainder is a continuation of the same scope** — keep the issue OPEN, post a \`Done ✓ / Remaining ▢\` comment, and release the claim so the queue re-picks it: \`gh issue edit "\${NUM}" --remove-label in-progress --remove-assignee @me\`.NEVER leave the issue OPEN with \`in-progress\` still on it — that strands it as a zombie (the claim queue skips \`in-progress\`, so the remaining scope is never re-picked). **Do NOT \`git pull\`** from inside this phase — the work is already integrated on GitHub via \`gh pr merge\`; leave the user's working tree alone.`,-- // v10 default prompt — pre-converging-Phase-3-release (issue #4106)+ // v11 default (pre-`--no-track`, bumped to v12)`[Claim Issue: {appName}] Claim and ship the next open GitHub issuePick the next available unclaimed open GitHub issue, **create your own worktree at \`claim/issue-<num>\`**, implement the fix, ship a PR that closes the issue, and clean up. This is the \`/claim --issues\` flow — same in-flight scan, same branch naming, same no-local-merge cleanup, but the work source is the repo's GitHub issue tracker instead of PLAN.md. **YOU pick the issue in Phase 1 — the scheduler does not reserve one for you.** Picking at execution time and immediately claiming (worktree + assignee + label) **narrows** the window for two concurrent runs to collide on the same issue — it does NOT eliminate it. Do NOT modify files in the source repo directly; ALL editing happens inside the worktree you create.@@ -7377,12 +7924,12 @@ cd "\${WORKTREE}"## Phase 3 — Verify still valid-Read the full issue (\`gh issue view "\${NUM}" --comments\`) before writing any code. **If ANY of these are true, release the claim and re-pick** (remove the assignee + \`in-progress\` label you set, remove the worktree, return to Phase 1):+Read the full issue (\`gh issue view "\${NUM}" --comments\`) before writing any code. **Every exit from this phase must leave a CONVERGING outcome on the issue — closed, or labeled \`needs-input\`.** Phase 1 step 4 skips both, so an autonomous drain stops re-picking the item. Releasing an issue OPEN and unlabeled is NOT an exit: the work detector still reports it actionable, so the next pass re-picks it and burns another no-op agent — every pass, forever.-- A comment indicates the issue was already fixed, superseded, or closed-then-reopened-for-tracking.-- The request references a function, file, or component that no longer exists (\`grep -rn\` the named identifiers — if they're gone, the issue is stale).+- **Already fixed, superseded, or closed-then-reopened-for-tracking** — a comment says so, or the change it asks for is already on the default branch. **Close it:** post a comment naming the PR/commit (or issue) that already delivered it (\`gh issue comment "\${NUM}" --body "..."\`), then \`gh issue close "\${NUM}" --reason completed\` (use \`--reason "not planned"\` when it was superseded rather than delivered) and clear the markers (\`gh issue edit "\${NUM}" --remove-assignee @me --remove-label in-progress\`). Remove the worktree and return to Phase 1. **Evidence gate: if you cannot name the PR, commit, or issue that delivered it, this branch does NOT apply** — closing on a hunch destroys live work, which is far worse than one wasted pass. Treat the issue as real work and continue to Phase 4.+- **Stale reference** — the request names a function, file, or component that no longer exists (\`grep -rn\` the named identifiers; if they're gone, the issue is stale). Post a comment naming what you searched for and what you found instead, **tag it \`needs-input\`** (\`gh issue edit "\${NUM}" --add-label needs-input\`), release the claim markers (\`gh issue edit "\${NUM}" --remove-assignee @me --remove-label in-progress\`), remove the worktree, and return to Phase 1. Re-scoping a stale issue against today's code is a human call — and the label is what keeps the drain off it in the meantime.-(A too-large scope is NOT in this release-and-re-pick list — releasing it just lets the next pass re-pick the same oversized issue. It has its own park path below.)+(A too-large scope is NOT in this list — it has its own park path below.)**A genuinely too-large issue needs parking so the drain converges.** If the work is bigger than one coherent claim — it would touch files far outside the issue's scope (>5 unrelated files) — and you can't carve a valuable standalone slice to partial-ship via Phase 5's \`Refs\` path, post a brief comment naming the split you'd suggest, **tag it \`needs-input\`** (\`gh issue edit "\${NUM}" --add-label needs-input\`), release the claim markers (\`gh issue edit "\${NUM}" --remove-assignee @me --remove-label in-progress\`), remove the worktree, and exit — splitting an omnibus issue is a human call, and parking it is what stops a perpetual drain from re-picking the same un-shippable issue every pass (Phase 1 step 4 skips \`needs-input\`).@@ -7442,8 +7989,8 @@ If \`git branch -d\` refuses (the PR squash-merged on GitHub but local doesn't k- **No — the remainder is a continuation of the same scope** — keep the issue OPEN, post a \`Done ✓ / Remaining ▢\` comment, and release the claim so the queue re-picks it: \`gh issue edit "\${NUM}" --remove-label in-progress --remove-assignee @me\`.NEVER leave the issue OPEN with \`in-progress\` still on it — that strands it as a zombie (the claim queue skips \`in-progress\`, so the remaining scope is never re-picked). **Do NOT \`git pull\`** from inside this phase — the work is already integrated on GitHub via \`gh pr merge\`; leave the user's working tree alone.`,- // v11 default (pre-`--no-track`, bumped to v12)- `[Claim Issue: {appName}] Claim and ship the next open GitHub issue+ // v12 default — follow-ups only applied `plan` (bumped to v13 for dispatch + contributor labels)+`[Claim Issue: {appName}] Claim and ship the next open GitHub issuePick the next available unclaimed open GitHub issue, **create your own worktree at \`claim/issue-<num>\`**, implement the fix, ship a PR that closes the issue, and clean up. This is the \`/claim --issues\` flow — same in-flight scan, same branch naming, same no-local-merge cleanup, but the work source is the repo's GitHub issue tracker instead of PLAN.md. **YOU pick the issue in Phase 1 — the scheduler does not reserve one for you.** Picking at execution time and immediately claiming (worktree + assignee + label) **narrows** the window for two concurrent runs to collide on the same issue — it does NOT eliminate it. Do NOT modify files in the source repo directly; ALL editing happens inside the worktree you create.@@ -7491,7 +8038,7 @@ NUM=<picked-number>WORKTREE="{worktreesRoot}/claim-issue-\${NUM}"mkdir -p {worktreesRoot}git fetch origin main-git worktree add -b "claim/issue-\${NUM}" "\${WORKTREE}" origin/main+git worktree add --no-track -b "claim/issue-\${NUM}" "\${WORKTREE}" origin/main# Cross-machine claim markers (best-effort — do not abort the run if these fail):gh issue edit "\${NUM}" --add-assignee @me 2>/dev/nullgh issue edit "\${NUM}" --add-label in-progress 2>/dev/null@@ -7569,8 +8116,8 @@ If \`git branch -d\` refuses (the PR squash-merged on GitHub but local doesn't k- **No — the remainder is a continuation of the same scope** — keep the issue OPEN, post a \`Done ✓ / Remaining ▢\` comment, and release the claim so the queue re-picks it: \`gh issue edit "\${NUM}" --remove-label in-progress --remove-assignee @me\`.NEVER leave the issue OPEN with \`in-progress\` still on it — that strands it as a zombie (the claim queue skips \`in-progress\`, so the remaining scope is never re-picked). **Do NOT \`git pull\`** from inside this phase — the work is already integrated on GitHub via \`gh pr merge\`; leave the user's working tree alone.`,- // v12 default — follow-ups only applied `plan` (bumped to v13 for dispatch + contributor labels)-`[Claim Issue: {appName}] Claim and ship the next open GitHub issue+ // v14 default prompt — reviews ran against the PR diff after the PR was opened+ `[Claim Issue: {appName}] Claim and ship the next open GitHub issuePick the next available unclaimed open GitHub issue, **create your own worktree at \`claim/issue-<num>\`**, implement the fix, ship a PR that closes the issue, and clean up. This is the \`/claim --issues\` flow — same in-flight scan, same branch naming, same no-local-merge cleanup, but the work source is the repo's GitHub issue tracker instead of PLAN.md. **YOU pick the issue in Phase 1 — the scheduler does not reserve one for you.** Picking at execution time and immediately claiming (worktree + assignee + label) **narrows** the window for two concurrent runs to collide on the same issue — it does NOT eliminate it. Do NOT modify files in the source repo directly; ALL editing happens inside the worktree you create.@@ -7646,7 +8193,7 @@ Read the full issue (\`gh issue view "\${NUM}" --comments\`) before writing anyWrite the code, tests, and any docs the issue requires. Follow the repo conventions in CLAUDE.md (no try/catch in route handlers, functional programming, Zod validation, Tailwind tokens, reactive UI updates). Run the relevant test suite as you go.-**Roll discovered backbone work INTO this PR** — small supporting helpers, refactors, and tests that the fix depends on belong here, not a follow-up. Only defer genuinely-large adjacent work; when you do, file a NEW issue (\`gh issue create\`) tagged \`plan\` that references this one (\`Related to #<num>\`) rather than appending to PLAN.md.+**Roll discovered backbone work INTO this PR** — small supporting helpers, refactors, and tests that the fix depends on belong here, not a follow-up. Only defer genuinely-large adjacent work; when you do, file a NEW issue (\`gh issue create\`) tagged \`plan\` that references this one (\`Related to #<num>\`) rather than appending to PLAN.md. Choose independent dispatch hints (\`model:light|medium|heavy\`, \`effort:low|medium|high|xhigh|max\`) and contributor labels (\`good first issue\`, \`help wanted\`) only when justified; omit an axis rather than guessing; create each missing label immediately before applying it; use repeated \`--label\` flags; do not prefix the title with \`[category]\` / \`[model:…]\`.Commit with a conventional message referencing the issue so the trail is grep-able:@@ -7664,19 +8211,22 @@ This flow ships GitHub issues — it does NOT touch PLAN.md. The audit trail is## Phase 6 — Review and ship-The configured reviewers for this task, in order, are \`{reviewers}\`. \`copilot\` waits for GitHub's auto-review; \`claude\` / \`codex\` / \`antigravity\` (CLI binary: \`agy\`) / \`grok\` invoke a local-CLI critique. When more than one is configured, run each in the listed order before merging — this mirrors slashdo's \`/do:pr --review-with <list>\`.+The configured reviewers for this task, in order, are \`{reviewers}\`. \`claude\` / \`codex\` / \`antigravity\` (CLI binary: \`agy\`) / \`grok\` invoke a local-CLI critique; \`lmstudio\` / \`ollama\` use the appended Local Reviewer Procedure. Run each in order before merging.1. **Self-review your diff for reuse, quality, and efficiency** (DRY, dead code, naming, simpler equivalents, missed edge cases) and fix findings in the same diff BEFORE the reviewers run. Claude Code runs this as the three-agent \`/simplify\` pass; on other CLIs, do the equivalent review by hand.-2. **Wait for each configured reviewer's findings BEFORE merging.** \`gh pr merge --auto\` only waits for required status checks; it does NOT wait for code-review feedback. Run the reviewers in the listed order (\`{reviewers}\`); for \`copilot\`, poll up to 10 minutes for its review and address \`COMMENTED\` / \`CHANGES_REQUESTED\` findings (commit + push inside the worktree, re-poll), capped at 3 rounds. For \`claude\` / \`codex\` / \`antigravity\` (CLI binary: \`agy\`) / \`grok\`, invoke that CLI headless against the PR diff, apply fixes, run tests, re-push — capped at 3 rounds — then advance to the next reviewer. A configured CLI reviewer whose binary is not on PATH is UNSATISFIED, not clean — that is a broken setup, not a passing review. Do NOT substitute your own self-review and do NOT merge; comment on the PR naming the missing command and stop.+2. **Wait for each configured reviewer's findings BEFORE merging.** Run the reviewers in the listed order (\`{reviewers}\`). Invoke CLI reviewers headless against the PR diff and local LLM reviewers through the appended endpoint procedure; apply fixes, run tests, and re-push — capped at 3 rounds — then advance. A missing CLI, timeout, transport failure, malformed response, or empty response is UNSATISFIED, not clean. Do NOT substitute your own self-review or merge; comment on the PR naming the failure and stop.**Review-stuck cleanup** (after 3 unresolved rounds): post one summarizing PR comment (\`gh pr comment\`), then run the worktree-only cleanup (\`cd {repoPath} && git worktree remove "\${WORKTREE}"\`). Leave the local branch, the open PR, the assignee, and the \`in-progress\` label in place so the human picks up cold. Do NOT run Phase 7.-3. **Merge via \`gh pr merge\`** — NEVER a local \`git merge\`. The repo may allow only one method, so try in order and use the first that succeeds:+3. **Merge immediately via \`gh pr merge\`** — NEVER a local \`git merge\` and NEVER \`--auto\`, which can return successfully while leaving the PR queued and OPEN. Prefer a true merge commit, with squash/rebase fallbacks for repositories that disallow it:\`\`\`bash- gh pr merge <pr-num> --auto --delete-branch \\- || gh pr merge <pr-num> --merge --delete-branch \\- || gh pr merge <pr-num> --squash --delete-branch \\- || gh pr merge <pr-num> --rebase --delete-branch+ PR_URL=$(gh pr view <pr-num> --json url -q .url)+ gh pr merge "$PR_URL" --merge --delete-branch || {+ [ "$(gh pr view "$PR_URL" --json state -q .state)" = "MERGED" ] || gh pr merge "$PR_URL" --squash --delete-branch || gh pr merge "$PR_URL" --rebase --delete-branch+ }+ STATE=$(gh pr view "$PR_URL" --json state -q .state)+ [ "$STATE" = "MERGED" ] || { echo "Expected MERGED, got $STATE" >&2; exit 1; }\`\`\`+ The exact comparison MUST succeed. \`OPEN\` means CI, review, or branch protection still blocks the merge; investigate, fix, and retry. \`CLOSED\` is also not success. Do not enter Phase 7 until remote GitHub state is exactly \`MERGED\`.## Phase 7 — Clean up (post-merge ONLY)@@ -7688,15 +8238,15 @@ git worktree remove "\${WORKTREE}"git branch -d "claim/issue-\${NUM}"\`\`\`-If \`git branch -d\` refuses (the PR squash-merged on GitHub but local doesn't know yet), use \`-D\` — the PR is confirmed merged, so the local branch is redundant.+If \`git branch -d\` refuses, fetch the default branch and re-check the PR's remote \`MERGED\` state. Retry \`-d\` only when Git can prove the branch is integrated; otherwise leave the local branch for the reconciliation task. Never force-delete with \`-D\`.**Reconcile the issue — did this PR FULLY satisfy its scope?**- **Yes (full)** — the \`Closes #\${NUM}\` trailer already auto-closed it; if it's somehow still open, close it (\`gh issue close "\${NUM}"\`) and remove the label (\`gh issue edit "\${NUM}" --remove-label in-progress\`).-- **No — the remainder is a clean, separable chunk** — close THIS issue with a summarizing comment (shipped ✓ / moved to #NEW), remove \`in-progress\`, and file ONE tightly-scoped follow-up for the remainder: \`gh issue create --title "…" --label plan --body "…\\n\\nRefs #\${NUM}"\` (carry over any \`area:*\` labels the issue had).+- **No — the remainder is a clean, separable chunk** — close THIS issue with a summarizing comment (shipped ✓ / moved to #NEW), remove \`in-progress\`, and file ONE tightly-scoped follow-up for the remainder: \`gh issue create --title "…" --label plan [--label model:<tier>] [--label effort:<level>] [--label "good first issue"] [--label "help wanted"] --body "…\\n\\nRefs #\${NUM}"\` (carry over any \`area:*\` labels the issue had; choose the optional labels independently and only when justified — a leftover mechanical sweep is not a good first issue).- **No — the remainder is a continuation of the same scope** — keep the issue OPEN, post a \`Done ✓ / Remaining ▢\` comment, and release the claim so the queue re-picks it: \`gh issue edit "\${NUM}" --remove-label in-progress --remove-assignee @me\`.NEVER leave the issue OPEN with \`in-progress\` still on it — that strands it as a zombie (the claim queue skips \`in-progress\`, so the remaining scope is never re-picked). **Do NOT \`git pull\`** from inside this phase — the work is already integrated on GitHub via \`gh pr merge\`; leave the user's working tree alone.`,- // v14 default prompt — reviews ran against the PR diff after the PR was opened+ // v15 default prompt — pre-{issueExcludeLabels} placeholder (Phase 1 step 4's blocking-label list was still hardcoded literal text)`[Claim Issue: {appName}] Claim and ship the next open GitHub issuePick the next available unclaimed open GitHub issue, **create your own worktree at \`claim/issue-<num>\`**, implement the fix, ship a PR that closes the issue, and clean up. This is the \`/claim --issues\` flow — same in-flight scan, same branch naming, same no-local-merge cleanup, but the work source is the repo's GitHub issue tracker instead of PLAN.md. **YOU pick the issue in Phase 1 — the scheduler does not reserve one for you.** Picking at execution time and immediately claiming (worktree + assignee + label) **narrows** the window for two concurrent runs to collide on the same issue — it does NOT eliminate it. Do NOT modify files in the source repo directly; ALL editing happens inside the worktree you create.@@ -7765,7 +8315,7 @@ Read the full issue (\`gh issue view "\${NUM}" --comments\`) before writing any(A too-large scope is NOT in this list — it has its own park path below.)-**A genuinely too-large issue needs parking so the drain converges.** If the work is bigger than one coherent claim — it would touch files far outside the issue's scope (>5 unrelated files) — and you can't carve a valuable standalone slice to partial-ship via Phase 5's \`Refs\` path, post a brief comment naming the split you'd suggest, **tag it \`needs-input\`** (\`gh issue edit "\${NUM}" --add-label needs-input\`), release the claim markers (\`gh issue edit "\${NUM}" --remove-assignee @me --remove-label in-progress\`), remove the worktree, and exit — splitting an omnibus issue is a human call, and parking it is what stops a perpetual drain from re-picking the same un-shippable issue every pass (Phase 1 step 4 skips \`needs-input\`).+**A genuinely too-large issue needs parking so the drain converges.** If the work is bigger than one coherent claim — it would touch files far outside the issue's scope (>5 unrelated files) — and you can't carve a valuable standalone slice to partial-ship via Phase 6's \`Refs\` path, post a brief comment naming the split you'd suggest, **tag it \`needs-input\`** (\`gh issue edit "\${NUM}" --add-label needs-input\`), release the claim markers (\`gh issue edit "\${NUM}" --remove-assignee @me --remove-label in-progress\`), remove the worktree, and exit — splitting an omnibus issue is a human call, and parking it is what stops a perpetual drain from re-picking the same un-shippable issue every pass (Phase 1 step 4 skips \`needs-input\`).**Ambiguity is NOT a release trigger — decide, don't defer.** If the issue is merely open to more than one reasonable reading, or leaves a design choice unstated, do NOT bail to \`needs-input\`. Pick the most reasonable interpretation, record the approach you chose in a brief issue comment (\`gh issue comment "\${NUM}" --body "..."\`) so the decision is on the record, and implement it. The user would rather iterate on top of a shipped best-guess than have the issue parked waiting on a decision they didn't ask to make. Reserve \`needs-input\` — which pulls the issue out of the autonomous queue — for the narrow cases where proceeding would be **destructive or irreversible**, or genuinely requires the human: specific hardware/credentials you don't have, or a judgment only they can make. In those cases only, post the explaining comment, **tag it \`needs-input\`** (\`gh issue edit "\${NUM}" --add-label needs-input\`), release the claim markers (\`gh issue edit "\${NUM}" --remove-assignee @me --remove-label in-progress\`), remove the worktree, and exit cleanly. **That label is what lets an autonomous drain converge** — Phase 1 step 4 skips \`needs-input\` issues. Never leave a half-claimed issue.@@ -7781,27 +8331,37 @@ Commit with a conventional message referencing the issue so the trail is grep-ab<type>: <one-line description> (#<num>)\`\`\`-## Phase 5 — Open the PR+## Phase 5 — Review locally (BEFORE any PR exists)-This flow ships GitHub issues — it does NOT touch PLAN.md. The audit trail is the merged PR + \`git log\`.+**Every reviewer that can read the working tree runs HERE, while there is still no PR.** Open the PR only once the branch is already review-clean: the PR then carries the finished diff, and the only things left to satisfy are CI and the reviewers that genuinely cannot start until a PR is open.-1. If the repo maintains a changelog, record a one-line entry **following the convention that repo documents** — read its \`CLAUDE.md\` and changelog README (e.g. \`.changelog/README.md\`) first. Some repos collect per-branch fragments in a directory (e.g. \`.changelog/next/\`) via a helper script rather than appending to one shared file, precisely so parallel agents don't conflict on every merge; use that flow when it's documented. Fall back to appending to the unreleased section (\`.changelog/NEXT.md\`, or \`## Unreleased\` in \`CHANGELOG.md\`) in the repo's existing prose style only when no convention is documented. If the repo has no changelog, skip this — the PR + commit history is the record.-2. Push the branch: \`git push -u origin "claim/issue-\${NUM}"\`-3. Open the PR with \`gh pr create\`. Summarize what shipped + a short test plan. **Choose the issue trailer deliberately:** if this PR FULLY satisfies the issue's scope, the body MUST contain \`Closes #\${NUM}\` so the merge auto-closes it. If you deliberately shipped only PART of the issue (a valuable slice, with real scope still remaining), use \`Refs #\${NUM}\` instead (NOT \`Closes\`) and add a \`## Remaining\` section listing what's left — Phase 7 reconciles the issue so it is never stranded.+The configured reviewers for this task, in order, are \`{reviewers}\`. Split that list in two, preserving its order:-## Phase 6 — Review and ship+- **LOCAL reviewers — every token that is NOT an \`@<login>\`.** \`claude\` / \`codex\` / \`antigravity\` (CLI binary: \`agy\`) / \`grok\` / \`cursor\` invoke a local-CLI critique; \`lmstudio\` / \`ollama\` use the appended Local Reviewer Procedure. They read this branch's own diff and need no PR — run them in THIS phase.+- **PR-SIDE reviewers — every \`@<login>\` token**, plus any review bot the repo requests automatically when a PR opens. They review cloud-side and cannot start before the PR exists — they run in Phase 6.-The configured reviewers for this task, in order, are \`{reviewers}\`. \`claude\` / \`codex\` / \`antigravity\` (CLI binary: \`agy\`) / \`grok\` invoke a local-CLI critique; \`lmstudio\` / \`ollama\` use the appended Local Reviewer Procedure. Run each in order before merging.+1. **Write the changelog entry now, not after the reviewers run** — every commit the reviewers are about to read must already be on the branch, or the PR carries work nobody reviewed. If the repo maintains a changelog, record a one-line entry **following the convention that repo documents** — read its \`CLAUDE.md\` and changelog README (e.g. \`.changelog/README.md\`) first. Some repos collect per-branch fragments in a directory (e.g. \`.changelog/next/\`) via a helper script rather than appending to one shared file, precisely so parallel agents don't conflict on every merge; use that flow when it's documented. Fall back to appending to the unreleased section (\`.changelog/NEXT.md\`, or \`## Unreleased\` in \`CHANGELOG.md\`) in the repo's existing prose style only when no convention is documented. If the repo has no changelog, skip this — the PR + commit history is the record.+2. **Self-review your diff for reuse, quality, and efficiency** (DRY, dead code, naming, simpler equivalents, missed edge cases) and fix the findings in the same diff, before any reviewer runs. Claude Code runs this as the three-agent \`/simplify\` pass; on other CLIs, do the equivalent review by hand.+3. **Run each LOCAL reviewer in the listed order against the BRANCH diff, not a PR diff.** No PR exists yet, so \`gh pr diff\` has nothing to read — use the CLI's own base-diff mode or \`git diff origin/main...HEAD\` (substitute the repo's default branch when it isn't \`main\`). Apply the findings, run the tests, and commit the fixes — capped at 3 rounds per reviewer — then advance to the next reviewer. A missing CLI, timeout, transport failure, malformed response, or empty response is UNSATISFIED, not clean. Do NOT substitute your own self-review, and do NOT open a PR on the strength of it.+4. **If the branch cannot be brought to a shippable state here, do NOT open a PR** — that is a local reviewer still unsatisfied after 3 rounds, or fixes that leave the build/tests red. Comment on the ISSUE naming the reviewer and the failure (\`gh issue comment "\${NUM}" --body "..."\`), leave the assignee and the \`in-progress\` label in place, remove ONLY the worktree (\`cd {repoPath} && git worktree remove "\${WORKTREE}"\`), and stop. The branch stays for a human to pick up cold. Do NOT run Phase 7.-1. **Self-review your diff for reuse, quality, and efficiency** (DRY, dead code, naming, simpler equivalents, missed edge cases) and fix findings in the same diff BEFORE the reviewers run. Claude Code runs this as the three-agent \`/simplify\` pass; on other CLIs, do the equivalent review by hand.-2. **Wait for each configured reviewer's findings BEFORE merging.** Run the reviewers in the listed order (\`{reviewers}\`). Invoke CLI reviewers headless against the PR diff and local LLM reviewers through the appended endpoint procedure; apply fixes, run tests, and re-push — capped at 3 rounds — then advance. A missing CLI, timeout, transport failure, malformed response, or empty response is UNSATISFIED, not clean. Do NOT substitute your own self-review or merge; comment on the PR naming the failure and stop.+## Phase 6 — Open the PR, satisfy PR-side review + CI, and merge- **Review-stuck cleanup** (after 3 unresolved rounds): post one summarizing PR comment (\`gh pr comment\`), then run the worktree-only cleanup (\`cd {repoPath} && git worktree remove "\${WORKTREE}"\`). Leave the local branch, the open PR, the assignee, and the \`in-progress\` label in place so the human picks up cold. Do NOT run Phase 7.-3. **Merge immediately via \`gh pr merge\`** — NEVER a local \`git merge\` and NEVER \`--auto\`, which can return successfully while leaving the PR queued and OPEN. Prefer a true merge commit, with squash/rebase fallbacks for repositories that disallow it:+Every local reviewer's fixes are already committed, so the PR opens against finished work. This flow ships GitHub issues — it does NOT touch PLAN.md. The audit trail is the merged PR + \`git log\`.++1. Push the branch: \`git push -u origin "claim/issue-\${NUM}"\`. Then confirm \`git log --oneline @{u}..HEAD\` is empty — if it isn't, a Phase 5 review fix never left the machine and the PR would be opened against a stale diff; push again before continuing.+2. Open the PR with \`gh pr create\`. Summarize what shipped + a short test plan. **Choose the issue trailer deliberately:** if this PR FULLY satisfies the issue's scope, the body MUST contain \`Closes #\${NUM}\` so the merge auto-closes it. If you deliberately shipped only PART of the issue (a valuable slice, with real scope still remaining), use \`Refs #\${NUM}\` instead (NOT \`Closes\`) and add a \`## Remaining\` section listing what's left — Phase 7 reconciles the issue so it is never stranded.+3. **Satisfy the PR-SIDE reviewers.** For each \`@<login>\` from the Phase 5 split, request the review now (\`gh pr edit <pr-number> --add-reviewer <login>\`, drop the \`@\`), poll every 5–15s for it, and address the findings — push fixes, capped at 3 rounds per reviewer. Their approval gates the merge. If the repo auto-requests a review bot when the PR opens, wait that round out and address it the same way. With no \`@<login>\` configured and no bot review appearing, this step is a no-op.++ **Review-stuck cleanup** (a PR-side reviewer still unsatisfied after 3 rounds): post one summarizing PR comment (\`gh pr comment\`), then run the worktree-only cleanup (\`cd {repoPath} && git worktree remove "\${WORKTREE}"\`). Leave the local branch, the open PR, the assignee, and the \`in-progress\` label in place so the human picks up cold. Do NOT run Phase 7.+4. **Let required CI finish and go green** — \`gh pr checks <pr-number> --required --watch --fail-fast\` (scope the wait to REQUIRED checks so an optional job can't stall a merge branch protection would allow). A red required check is not merge-eligible: fix it and re-push (same 3-round cap), or, if it stays red, stop exactly as the review-stuck cleanup above does.+5. **Merge immediately via \`gh pr merge\`** — NEVER a local \`git merge\` and NEVER \`--auto\`, which can return successfully while leaving the PR queued and OPEN. Prefer a true merge commit, with squash/rebase fallbacks for repositories that disallow it:\`\`\`bash- PR_URL=$(gh pr view <pr-num> --json url -q .url)+ PR_URL=$(gh pr view --json url -q .url) # no number: resolves the PR from the checked-out branchgh pr merge "$PR_URL" --merge --delete-branch || {- [ "$(gh pr view "$PR_URL" --json state -q .state)" = "MERGED" ] || gh pr merge "$PR_URL" --squash --delete-branch || gh pr merge "$PR_URL" --rebase --delete-branch+ [ "$(gh pr view "$PR_URL" --json state -q .state)" = "MERGED" ] || \+ gh pr merge "$PR_URL" --squash --delete-branch || \+ gh pr merge "$PR_URL" --rebase --delete-branch}STATE=$(gh pr view "$PR_URL" --json state -q .state)[ "$STATE" = "MERGED" ] || { echo "Expected MERGED, got $STATE" >&2; exit 1; }@@ -7826,7 +8386,7 @@ If \`git branch -d\` refuses, fetch the default branch and re-check the PR's rem- **No — the remainder is a continuation of the same scope** — keep the issue OPEN, post a \`Done ✓ / Remaining ▢\` comment, and release the claim so the queue re-picks it: \`gh issue edit "\${NUM}" --remove-label in-progress --remove-assignee @me\`.NEVER leave the issue OPEN with \`in-progress\` still on it — that strands it as a zombie (the claim queue skips \`in-progress\`, so the remaining scope is never re-picked). **Do NOT \`git pull\`** from inside this phase — the work is already integrated on GitHub via \`gh pr merge\`; leave the user's working tree alone.`,- // v15 default prompt — pre-{issueExcludeLabels} placeholder (Phase 1 step 4's blocking-label list was still hardcoded literal text)+ // v16 default prompt (pre-#4852: named CLAUDE.md as the agent-instructions file)`[Claim Issue: {appName}] Claim and ship the next open GitHub issuePick the next available unclaimed open GitHub issue, **create your own worktree at \`claim/issue-<num>\`**, implement the fix, ship a PR that closes the issue, and clean up. This is the \`/claim --issues\` flow — same in-flight scan, same branch naming, same no-local-merge cleanup, but the work source is the repo's GitHub issue tracker instead of PLAN.md. **YOU pick the issue in Phase 1 — the scheduler does not reserve one for you.** Picking at execution time and immediately claiming (worktree + assignee + label) **narrows** the window for two concurrent runs to collide on the same issue — it does NOT eliminate it. Do NOT modify files in the source repo directly; ALL editing happens inside the worktree you create.@@ -7847,8 +8407,11 @@ Run steps 1–5 in order.# do NOT pack flag+value into one variable: a bare \`$VAR\` holding "--author x"# is a single argv token in zsh (no word-splitting) and gh rejects it.# Owner-only mode (default): resolve the owner, then add --author "$OWNER"+ # --limit 500 (not 100): the blocking-label filter below runs on this+ # fetched page, so a small cap risks missing eligible work further down+ # a busy queue when the first page is full of excluded/in-flight issues.OWNER="$(gh repo view --json owner -q .owner.login)"- gh issue list --state open --author "$OWNER" --search "sort:created-asc" --json number,title,author,assignees,labels,createdAt --limit 100+ gh issue list --state open --author "$OWNER" --search "sort:created-asc" --json number,title,author,assignees,labels,createdAt --limit 500# Any-author mode: run the SAME command WITHOUT the --author "$OWNER" flag.\`\`\`3. Build the in-flight set. Collect every branch/PR ref:@@ -7860,7 +8423,7 @@ Run steps 1–5 in order.4. **Pick the target issue:** walk the candidate list oldest-first and pick the FIRST issue where ALL of the following are true:- Its number is NOT in the in-flight set.- It has NO assignees (an assignee means another machine/human already claimed it).- - It does NOT carry any of these blocking labels: \`in-progress\`, \`blocked\`, \`needs-input\`, \`future\`, \`wontfix\`, \`question\`, \`discussion\`.+ - It does NOT carry any of these blocking labels: {issueExcludeLabels}.- It is NOT a tracking/umbrella **epic** — recognized by an \`epic\` label, a title ending in "(epic)", OR a title beginning with an \`[epic]\` bracket or \`Epic:\` tag (e.g. "[Epic] …" / "Epic: …", case-insensitive). An epic needs per-slice partial-ship (each slice its own PR, \`Refs\` not \`Closes\`), so leave it for a human or \`/claim --issues\` to split — don't claim it wholesale here. **The bare \`plan\` label is NOT a skip signal.** \`do-replan --issues\` (and \`/do:replan --issues\`) labels EVERY migrated backlog item \`plan\` — atomic bug-fixes included — so \`plan\` marks the *claimable* queue exactly as \`/do:next --issues\` treats it (it is that flow's required candidate label). Skipping all \`plan\` issues would discard the entire actionable backlog and falsely report an empty queue.5. **If no eligible issue exists**, exit cleanly — an empty actionable queue is a healthy state, not a failure.@@ -7939,9 +8502,7 @@ Every local reviewer's fixes are already committed, so the PR opens against fini\`\`\`bashPR_URL=$(gh pr view --json url -q .url) # no number: resolves the PR from the checked-out branchgh pr merge "$PR_URL" --merge --delete-branch || {- [ "$(gh pr view "$PR_URL" --json state -q .state)" = "MERGED" ] || \- gh pr merge "$PR_URL" --squash --delete-branch || \- gh pr merge "$PR_URL" --rebase --delete-branch+ [ "$(gh pr view "$PR_URL" --json state -q .state)" = "MERGED" ] || gh pr merge "$PR_URL" --squash --delete-branch || gh pr merge "$PR_URL" --rebase --delete-branch}STATE=$(gh pr view "$PR_URL" --json state -q .state)[ "$STATE" = "MERGED" ] || { echo "Expected MERGED, got $STATE" >&2; exit 1; }@@ -8377,6 +8938,34 @@ Repository: {repoPath}- If the repo has a \`.changelog/NEXT.md\` (or similar), log what shipped there in the project's existing prose style.- Keep PLAN.md focused on next actions and future work+Commit documentation improvements.`,+ // v5 default prompt (pre-#4852: named CLAUDE.md as the agent-instructions file)+ `[Improvement: {appName}] Update Documentation++Review and improve {appName} documentation:++Repository: {repoPath}++1. Check README.md:+ - Installation instructions current?+ - Quick start guide clear?+ - Feature overview complete?++2. Review inline documentation:+ - Add JSDoc to exported functions+ - Document complex algorithms+ - Explain non-obvious code++3. Check for docs/ folder:+ - Are all features documented?+ - Is information current?+ - Add missing guides if needed++4. Update PLAN.md if present:+ - Remove completed milestones from PLAN.md outright. Do NOT archive to a \`DONE.md\` — that file is retired; \`git log\` and \`.changelog/\` (or per-app equivalent) are the audit trail.+ - If the repo maintains a changelog, log what shipped there **following the convention the repo documents** — check its \`CLAUDE.md\` and changelog README first. Some repos collect per-branch fragments in a directory (e.g. \`.changelog/next/\`) via a helper script rather than appending to one shared file, precisely so parallel agents don't conflict on every merge. Fall back to appending to the unreleased section (\`.changelog/NEXT.md\`, or \`## Unreleased\` in \`CHANGELOG.md\`) in the project's existing prose style only when no convention is documented.+ - Keep PLAN.md focused on next actions and future work+Commit documentation improvements.`,],'ui-bugs': [@@ -9270,6 +9859,145 @@ If merge fails (e.g., branch protections), try: \`gh pr merge <PR_NUM> --merge -## Step 7: Report+Summarize:+- Version released+- Key changes (from changelog)+- Number of review iterations needed+- Any unresolved issues`,+ // v9 default prompt (pre-#4852: named CLAUDE.md as the agent-instructions file)+ `[Improvement: {appName}] Release Check++Repository: {repoPath}++Check if {appName} has accumulated enough work for a release, following the project's own documented release process.++## Step 0: Discover the Release Process++You need to determine these values (use angle-bracket names as placeholders in subsequent steps):+- \`<SOURCE_BRANCH>\` — where development happens+- \`<TARGET_BRANCH>\` — where releases go+- Changelog format and location+- Pre-release checks (tests, builds)+- Push/rebase conventions++First, extract \`<OWNER>\` and \`<REPO>\`:+\`\`\`bash+cd {repoPath} && gh repo view --json owner,name --jq '"OWNER=" + .owner.login + " REPO=" + .name'+\`\`\`++Then search for release documentation. Check your CLAUDE.md context (already provided above) for "Git Workflow", "Release", or "Changelog" sections. If the release process is not clear from CLAUDE.md, check these files in order (use whichever exist):+1. \`cat {repoPath}/README.md\` — look for release/deployment/workflow sections+2. \`cat {repoPath}/.changelog/README.md\` — changelog format and release conventions+3. \`cat {repoPath}/CONTRIBUTING.md\` — contributing/release guidelines+4. \`ls {repoPath}/docs/\` — look for release process docs (e.g., RELEASE.md, DEPLOY.md)+5. \`ls {repoPath}/.github/workflows/\` — infer branch flow from CI workflow triggers+6. \`gh api repos/<OWNER>/<REPO>/branches --jq '.[].name'\` — list branches to identify the flow++If no documentation specifies a release flow, fall back to: source=dev, target=main.++## Step 1: Reconcile Missing Releases++BEFORE evaluating unreleased work, check for existing release tags that lack a corresponding GitHub Release:+1. \`git -C {repoPath} fetch --tags origin\`+2. List all version tags (e.g., \`v*\`) on \`<TARGET_BRANCH>\` / \`origin\` and list published GitHub Releases:+ \`\`\`bash+ gh release list --repo <OWNER>/<REPO> --limit 100+ \`\`\`+3. Compare every release tag \`vX.Y.Z\` against published GitHub Releases. If a tag \`vX.Y.Z\` exists but has no corresponding GitHub Release:+ - Report the missing release version explicitly: "Unpublished release detected: vX.Y.Z".+ - Locate the changelog body for \`vX.Y.Z\` (e.g., \`.changelog/vX.Y.Z.md\` or \`.changelog/vX.Y.x.md\`).+ - Check if a newer version tag or release exists.+ - Publish the missing release using \`gh release create "vX.Y.Z"\`:+ - Use \`.changelog/vX.Y.Z.md\` (or the assembled changelog for that version) as the release body (\`--notes-file\` or \`--body-file\`).+ - Pass \`--latest=false\` if a newer version tag or release is already published, so backfilling an old version never displaces the current Latest release. Pass \`--latest\` only if \`vX.Y.Z\` is the newest version.+4. Report any missing releases reconciled before proceeding to Step 2.++## Step 2: Evaluate Readiness++Using the changelog location discovered in Step 0:+- Read the current changelog (e.g., \`.changelog/NEXT.md\` or \`.changelog/v*.x.md\`)+- **Also read the entries not yet folded into that file.** Repos that collect per-branch fragments (e.g. \`.changelog/next/\`, so parallel agents don't conflict on a shared file) keep unreleased entries there until the release collects them, so the staged file alone under-counts the work. Read the fragment directory directly, and if the repo's changelog README documents a preview/collect command, use that to assemble the unreleased notes in one call. Do NOT guess a command name — only run one this repo actually documents.+- Read the current version: \`node -p "require('{repoPath}/package.json').version"\` or equivalent++Count substantive entries (lines starting with "###" or "- **" under Features, Fixes, Improvements sections) across the **assembled** unreleased notes — the staged file plus any uncollected fragments. If fewer than 2 substantive entries exist, stop and report: "Not enough work accumulated for a release." Do NOT create a PR.++## Step 3: Verify Clean State++Run these checks on \`<SOURCE_BRANCH>\` (stop if any fail):+1. \`git -C {repoPath} fetch origin\` and ensure \`<SOURCE_BRANCH>\` is up to date+2. Run the project's test suite (use the command from release docs). If the+ release docs identify a separate database-backed test suite, first run the+ documented test-database provisioning/setup command, then run that database+ test command as well. Keep the database test target isolated from any real+ user database; never substitute a production database just to make tests+ pass. If setup cannot reach the documented database service, report the+ environmental blocker and stop before creating the release PR.+3. Run the project's build (use the command from release docs)++## Step 4: Create or Find PR++Check for existing PR: \`gh pr list --repo <OWNER>/<REPO> --base <TARGET_BRANCH> --head <SOURCE_BRANCH> --state open --json number,url\`++If a PR exists, use it. If not, create one following the project's documented release PR conventions.++Capture the PR number as \`<PR_NUM>\` and URL.++## Step 5: Wait for Copilot Review++Copilot review is triggered automatically on push. Poll every 15 seconds until the review appears:+\`\`\`bash+gh api repos/<OWNER>/<REPO>/pulls/<PR_NUM>/reviews --jq '.[] | select(.user.login == "copilot-pull-request-reviewer") | .state'+\`\`\`++Wait until you see APPROVED or CHANGES_REQUESTED. Timeout after 5 minutes of polling.++## Step 6: Address Feedback Loop (max 5 iterations)++### 6a. Fetch unresolved review threads++Use gh api graphql (JSON input to avoid shell escaping issues with GraphQL variables):++\`\`\`bash+echo '{"query":"query{repository(owner:\\"<OWNER>\\",name:\\"<REPO>\\"){pullRequest(number:<PR_NUM>){reviewThreads(first:100){nodes{id,isResolved,comments(first:10){nodes{body,path,line,author{login}}}}}}}}"}' | gh api graphql --input -+\`\`\`++### 6b. If no unresolved threads: skip to Step 7 (Merge).++### 6c. If unresolved threads exist, evaluate each one:++For each comment, read the referenced file and critically evaluate the suggestion:+- **If the suggestion is valid and improves the code**: apply the fix+- **If the suggestion is a false positive, overly pedantic, or would make the code worse**: do NOT change the code++Either way, resolve every thread — the goal is zero unresolved threads before merge.++After evaluating all threads:+- If any code changes were made: run the project's test suite to verify, then commit and push using \`/do:push\` (or manually: stage specific files, conventional commit prefix, \`git pull --rebase && git push\`)++### 6d. Resolve ALL threads via GraphQL mutation (both fixed and dismissed):++For each thread, use the thread node id from 5a:+\`\`\`bash+echo '{"query":"mutation{resolveReviewThread(input:{threadId:\\"THREAD_NODE_ID\\"}){thread{isResolved}}}"}' | gh api graphql --input -+\`\`\`++### 6e. Wait for new Copilot review if code was pushed (repeat Step 5)++If you pushed changes in 6c, the push automatically triggers a new Copilot review. Poll for it, then loop back to 6a. If no code changes were made (all threads were false positives), skip straight to Step 7.++If after 5 iterations there are still unresolved threads, stop and report what remains.++## Step 7: Merge++Only merge when Copilot's most recent review has NO unresolved threads:+\`\`\`bash+gh pr merge <PR_NUM> --merge+\`\`\`++If merge fails (e.g., branch protections), try: \`gh pr merge <PR_NUM> --merge --admin\`++## Step 8: Report+Summarize:- Version released- Key changes (from changelog)@@ -9576,4 +10304,45 @@ Default branch: {defaultBranch}the branch). Finish with a 2–4 sentence summary listing exactly which modelswere added, updated, or removed and the sources you verified them against.`,],+ 'stash-cleanup': [+ // v1 default prompt (pre-#4852: named CLAUDE.md as the agent-instructions file)+ `[Improvement: {appName}] Git Stash Cleanup++Repository: {repoPath}++Audit every entry in \`git stash list\` for {appName} and clear out anything that is stale, superseded, or unrecoverable — without losing real unlanded work. This never produces a commit; it is a working-tree hygiene pass.++## Step 0: Handle a mid-flight conflict first++Run \`git status\` (\`cd {repoPath}\` first). If it shows unmerged paths (a \`git stash pop\` left the tree conflicted), resolve that BEFORE touching the rest of the stash list:++1. For each conflicted file, read the conflict markers and compare the stashed side against the current HEAD/\`main\` side for that region.+2. If the stashed side is fully superseded — HEAD already contains the same change or a superset of it (verify by grepping the file for the added identifiers/lines and reading the surrounding code, not just eyeballing the diff) — resolve with \`git checkout --ours <file>\` and \`git add <file>\`.+3. If the stashed side adds anything HEAD does not already have, STOP. Do not attempt to hand-merge two live versions of the same logic. Leave the conflict markers in place, note exactly which file(s) and which lines are in conflict, and report it — this needs a human to resolve.+4. Once every conflicted file is resolved (or none were conflicted), confirm \`git status\` is clean before continuing to Step 1. A conflict resolved this way produces no diff against HEAD by construction, so there is nothing to commit.++If Step 0 stopped on an unresolved conflict, skip the rest of this task and go straight to Step 3 (Report).++## Step 1: Triage every remaining stash++Run \`git stash list\`. For each \`stash@{N}\`:++1. \`git stash show -p stash@{N} --stat\` for an overview, then the full \`git stash show -p stash@{N}\` for the patch.+2. For every changed symbol or section in the patch, check whether current \`main\`/HEAD already contains the same change or a superset of it — grep the target file(s) for the added identifiers, read the surrounding code, and compare. If the stash's message references a branch name, also check \`git branch -a\` and \`git log --all --oneline\` for whether that branch was already merged or deleted (a strong signal the stash is redundant leftover cruft).+3. Classify each stash:+ - **SUPERSEDED** — the change (or a superset of it) already exists on \`main\`. Safe to drop.+ - **STALE/ABANDONED** — old WIP, exploratory scratch, lockfile-only diff noise, a reference to a file that no longer exists in the repo, or a change that contradicts current architecture/policy (check this repo's CLAUDE.md before assuming). Safe to drop.+ - **REAL UNLANDED WORK** — a coherent change that is not on \`main\` and is not obviously abandoned. Do NOT drop it. Note what it does, which files it touches, and how stale the underlying branch/context looks.+4. Before diffing two stashes independently, check for duplicates: \`diff <(git stash show -p stash@{A}) <(git stash show -p stash@{B})\`. Identical stashes are one unit — classify and act on them together.++## Step 2: Act++- Drop every stash classified SUPERSEDED or STALE/ABANDONED: \`git stash drop stash@{N}\`. Re-run \`git stash list\` after each drop, since indices shift.+- Leave every stash classified REAL UNLANDED WORK in place. Do not apply, pop, or drop it.+- Only run \`git stash clear\` once you have classified the ENTIRE list and confirmed nothing in it is REAL UNLANDED WORK.++## Step 3: Report++Summarize: how many stashes were reviewed, how many were dropped (grouped by reason: superseded vs. stale/abandoned), and — for anything classified REAL UNLANDED WORK — what it is, which files it touches, and a recommendation (recover as a branch, cherry-pick specific hunks, or leave it for the user to decide). When in doubt about whether a stash is safe to drop, leave it in the stash and say so in the report rather than dropping it.`,+ ],};diff --git a/server/services/taskPromptDefaults/prompts.js b/server/services/taskPromptDefaults/prompts.jsindex 85905a74f9..4a30417ddf 100644--- a/server/services/taskPromptDefaults/prompts.js+++ b/server/services/taskPromptDefaults/prompts.js@@ -5,7 +5,7 @@* prose lives apart from the version/upgrade machinery in ./versions.js and* ./previousDefaults.js. Do NOT change a prompt here without bumping its* PROMPT_VERSIONS entry and preserving the prior default in- * PREVIOUS_DEFAULT_PROMPTS — see the barrel's header and CLAUDE.md+ * PREVIOUS_DEFAULT_PROMPTS — see the barrel's header and AGENTS.md* "Distribution model".*/@@ -300,7 +300,7 @@ Repository: {repoPath}4. Update PLAN.md if present:- Remove completed milestones from PLAN.md outright. Do NOT archive to a \`DONE.md\` — that file is retired; \`git log\` and \`.changelog/\` (or per-app equivalent) are the audit trail.- - If the repo maintains a changelog, log what shipped there **following the convention the repo documents** — check its \`CLAUDE.md\` and changelog README first. Some repos collect per-branch fragments in a directory (e.g. \`.changelog/next/\`) via a helper script rather than appending to one shared file, precisely so parallel agents don't conflict on every merge. Fall back to appending to the unreleased section (\`.changelog/NEXT.md\`, or \`## Unreleased\` in \`CHANGELOG.md\`) in the project's existing prose style only when no convention is documented.+ - If the repo maintains a changelog, log what shipped there **following the convention the repo documents** — check its \`AGENTS.md\` (or \`CLAUDE.md\`) and changelog README first. Some repos collect per-branch fragments in a directory (e.g. \`.changelog/next/\`) via a helper script rather than appending to one shared file, precisely so parallel agents don't conflict on every merge. Fall back to appending to the unreleased section (\`.changelog/NEXT.md\`, or \`## Unreleased\` in \`CHANGELOG.md\`) in the project's existing prose style only when no convention is documented.- Keep PLAN.md focused on next actions and future workCommit documentation improvements.`,@@ -657,7 +657,7 @@ After Phase 3b runs, **exit** — do NOT proceed to Phase 4. The implementing pa## Phase 4 — Implement-Write the code, tests, and any docs the item requires. Follow the repo conventions in CLAUDE.md (no try/catch in route handlers, functional programming, Zod validation, Tailwind tokens, reactive UI updates).+Write the code, tests, and any docs the item requires. Follow the repo conventions in AGENTS.md / CLAUDE.md (no try/catch in route handlers, functional programming, Zod validation, Tailwind tokens, reactive UI updates).Run the relevant test suite as you go.@@ -676,7 +676,7 @@ Use \`feat:\` / \`fix:\` / \`refactor:\` / \`chore:\` / etc. (The bracketed-scop**Remove the item from PLAN.md outright.** The audit trail for shipped work lives in \`git log\` and the project's changelog (however that repo keeps it) — do NOT archive to a \`DONE.md\`, that file has been retired. Do NOT leave a checked \`- [x]\` behind in PLAN.md.1. Remove the picked \`- [ ]\` line from PLAN.md entirely. If removing it leaves a heading empty, leave the heading alone — section curation is \`do-replan\`'s job.-2. Record the shipped item in the repo's changelog, **following the convention that repo documents** — read its \`CLAUDE.md\` and changelog README (e.g. \`.changelog/README.md\`) BEFORE writing anything. Some repos collect per-branch fragments in a directory (e.g. \`.changelog/next/\`) via a helper script rather than appending to one shared file, precisely so parallel agents don't conflict on every merge. When such a convention is documented, use it — run the documented command and remember the fragment file it created as \`CHANGELOG_FILE\`.+2. Record the shipped item in the repo's changelog, **following the convention that repo documents** — read its \`AGENTS.md\` (or \`CLAUDE.md\`) and changelog README (e.g. \`.changelog/README.md\`) BEFORE writing anything. Some repos collect per-branch fragments in a directory (e.g. \`.changelog/next/\`) via a helper script rather than appending to one shared file, precisely so parallel agents don't conflict on every merge. When such a convention is documented, use it — run the documented command and remember the fragment file it created as \`CHANGELOG_FILE\`.Only when no convention is documented, detect a changelog file (in this order — pick the first match) and append an entry there:- \`.changelog/NEXT.md\` (staged-release file)@@ -817,7 +817,7 @@ Read the full issue (\`gh issue view "\${NUM}" --comments\`) before writing any## Phase 4 — Implement-Write the code, tests, and any docs the issue requires. Follow the repo conventions in CLAUDE.md (no try/catch in route handlers, functional programming, Zod validation, Tailwind tokens, reactive UI updates). Run the relevant test suite as you go.+Write the code, tests, and any docs the issue requires. Follow the repo conventions in AGENTS.md / CLAUDE.md (no try/catch in route handlers, functional programming, Zod validation, Tailwind tokens, reactive UI updates). Run the relevant test suite as you go.**Roll discovered backbone work INTO this PR** — small supporting helpers, refactors, and tests that the fix depends on belong here, not a follow-up. Only defer genuinely-large adjacent work; when you do, file a NEW issue (\`gh issue create\`) tagged \`plan\` that references this one (\`Related to #<num>\`) rather than appending to PLAN.md. Choose independent dispatch hints (\`model:light|medium|heavy\`, \`effort:low|medium|high|xhigh|max\`) and contributor labels (\`good first issue\`, \`help wanted\`) only when justified; omit an axis rather than guessing; create each missing label immediately before applying it; use repeated \`--label\` flags; do not prefix the title with \`[category]\` / \`[model:…]\`.@@ -836,7 +836,7 @@ The configured reviewers for this task, in order, are \`{reviewers}\`. Split tha- **LOCAL reviewers — every token that is NOT an \`@<login>\`.** \`claude\` / \`codex\` / \`antigravity\` (CLI binary: \`agy\`) / \`grok\` / \`cursor\` invoke a local-CLI critique; \`lmstudio\` / \`ollama\` use the appended Local Reviewer Procedure. They read this branch's own diff and need no PR — run them in THIS phase.- **PR-SIDE reviewers — every \`@<login>\` token**, plus any review bot the repo requests automatically when a PR opens. They review cloud-side and cannot start before the PR exists — they run in Phase 6.-1. **Write the changelog entry now, not after the reviewers run** — every commit the reviewers are about to read must already be on the branch, or the PR carries work nobody reviewed. If the repo maintains a changelog, record a one-line entry **following the convention that repo documents** — read its \`CLAUDE.md\` and changelog README (e.g. \`.changelog/README.md\`) first. Some repos collect per-branch fragments in a directory (e.g. \`.changelog/next/\`) via a helper script rather than appending to one shared file, precisely so parallel agents don't conflict on every merge; use that flow when it's documented. Fall back to appending to the unreleased section (\`.changelog/NEXT.md\`, or \`## Unreleased\` in \`CHANGELOG.md\`) in the repo's existing prose style only when no convention is documented. If the repo has no changelog, skip this — the PR + commit history is the record.+1. **Write the changelog entry now, not after the reviewers run** — every commit the reviewers are about to read must already be on the branch, or the PR carries work nobody reviewed. If the repo maintains a changelog, record a one-line entry **following the convention that repo documents** — read its \`AGENTS.md\` (or \`CLAUDE.md\`) and changelog README (e.g. \`.changelog/README.md\`) first. Some repos collect per-branch fragments in a directory (e.g. \`.changelog/next/\`) via a helper script rather than appending to one shared file, precisely so parallel agents don't conflict on every merge; use that flow when it's documented. Fall back to appending to the unreleased section (\`.changelog/NEXT.md\`, or \`## Unreleased\` in \`CHANGELOG.md\`) in the repo's existing prose style only when no convention is documented. If the repo has no changelog, skip this — the PR + commit history is the record.2. **Self-review your diff for reuse, quality, and efficiency** (DRY, dead code, naming, simpler equivalents, missed edge cases) and fix the findings in the same diff, before any reviewer runs. Claude Code runs this as the three-agent \`/simplify\` pass; on other CLIs, do the equivalent review by hand.3. **Run each LOCAL reviewer in the listed order against the BRANCH diff, not a PR diff.** No PR exists yet, so \`gh pr diff\` has nothing to read — use the CLI's own base-diff mode or \`git diff origin/main...HEAD\` (substitute the repo's default branch when it isn't \`main\`). Apply the findings, run the tests, and commit the fixes — capped at 3 rounds per reviewer — then advance to the next reviewer. A missing CLI, timeout, transport failure, malformed response, or empty response is UNSATISFIED, not clean. Do NOT substitute your own self-review, and do NOT open a PR on the strength of it.4. **If the branch cannot be brought to a shippable state here, do NOT open a PR** — that is a local reviewer still unsatisfied after 3 rounds, or fixes that leave the build/tests red. Comment on the ISSUE naming the reviewer and the failure (\`gh issue comment "\${NUM}" --body "..."\`), leave the assignee and the \`in-progress\` label in place, remove ONLY the worktree (\`cd {repoPath} && git worktree remove "\${WORKTREE}"\`), and stop. The branch stays for a human to pick up cold. Do NOT run Phase 7.@@ -963,7 +963,7 @@ Read the full issue (\`glab issue view "\${NUM}"\`) before writing any code. **E## Phase 4 — Implement-Write the code, tests, and any docs the issue requires. Follow the repo conventions in CLAUDE.md. Run the relevant test suite as you go.+Write the code, tests, and any docs the issue requires. Follow the repo conventions in AGENTS.md (or CLAUDE.md). Run the relevant test suite as you go.**Roll discovered backbone work INTO this MR** — small supporting helpers, refactors, and tests that the fix depends on belong here, not a follow-up. Only defer genuinely-large adjacent work; when you do, file a NEW issue (\`glab issue create\`) tagged \`plan\` that references this one (\`Related to #<num>\`). Choose independent dispatch hints (\`model:light|medium|heavy\`, \`effort:low|medium|high|xhigh|max\`) and contributor labels (\`good first issue\`, \`help wanted\`) only when justified; omit an axis rather than guessing; create each missing label immediately before applying it; use repeated \`--label\` flags; do not prefix the title with \`[category]\` / \`[model:…]\`.@@ -982,7 +982,7 @@ The configured reviewers for this task, in order, are \`{reviewers}\`. Split tha- **LOCAL reviewers — every token that is NOT an \`@<login>\`.** \`claude\` / \`codex\` / \`antigravity\` (CLI binary: \`agy\`) / \`grok\` / \`cursor\` invoke a local-CLI critique; \`lmstudio\` / \`ollama\` use the appended Local Reviewer Procedure. They read this branch's own diff and need no MR — run them in THIS phase.- **MR-SIDE reviewers — every \`@<login>\` token**, plus any review bot the project requests automatically when an MR opens. They review server-side and cannot start before the MR exists — they run in Phase 6.-1. **Write the changelog entry now, not after the reviewers run** — every commit the reviewers are about to read must already be on the branch, or the MR carries work nobody reviewed. If the repo maintains a changelog, record a one-line entry **following the convention that repo documents** — read its \`CLAUDE.md\` and changelog README (e.g. \`.changelog/README.md\`) first. Some repos collect per-branch fragments in a directory (e.g. \`.changelog/next/\`) via a helper script rather than appending to one shared file, precisely so parallel agents don't conflict on every merge; use that flow when it's documented. Fall back to appending to the unreleased section (\`.changelog/NEXT.md\`, or \`## Unreleased\` in \`CHANGELOG.md\`) in the repo's existing prose style only when no convention is documented. If the repo has no changelog, skip this.+1. **Write the changelog entry now, not after the reviewers run** — every commit the reviewers are about to read must already be on the branch, or the MR carries work nobody reviewed. If the repo maintains a changelog, record a one-line entry **following the convention that repo documents** — read its \`AGENTS.md\` (or \`CLAUDE.md\`) and changelog README (e.g. \`.changelog/README.md\`) first. Some repos collect per-branch fragments in a directory (e.g. \`.changelog/next/\`) via a helper script rather than appending to one shared file, precisely so parallel agents don't conflict on every merge; use that flow when it's documented. Fall back to appending to the unreleased section (\`.changelog/NEXT.md\`, or \`## Unreleased\` in \`CHANGELOG.md\`) in the repo's existing prose style only when no convention is documented. If the repo has no changelog, skip this.2. **Self-review your diff for reuse, quality, and efficiency** (DRY, dead code, naming, simpler equivalents, missed edge cases) and fix the findings in the same diff, before any reviewer runs. Claude Code runs this as the three-agent \`/simplify\` pass; on other CLIs, do the equivalent review by hand.3. **Run each LOCAL reviewer in the listed order against the BRANCH diff, not an MR diff.** No MR exists yet, so \`glab mr diff\` has nothing to read — use the CLI's own base-diff mode or \`git diff "origin/\${DEFAULT_BRANCH}...HEAD"\`. Apply the findings, run the tests, and commit the fixes — capped at 3 rounds per reviewer — then advance to the next reviewer. A missing CLI, timeout, transport failure, malformed response, or empty response is UNSATISFIED, not clean. Do NOT substitute your own self-review, and do NOT open an MR on the strength of it.4. **If the branch cannot be brought to a shippable state here, do NOT open an MR** — that is a local reviewer still unsatisfied after 3 rounds, or fixes that leave the build/tests red. Post a note on the ISSUE naming the reviewer and the failure (\`glab issue note "\${NUM}" -m "..."\`), leave the assignee and the \`in-progress\` label in place, remove ONLY the worktree (\`cd {repoPath} && git worktree remove "\${WORKTREE}"\`), and stop. The branch stays for a human to pick up cold. Do NOT run Phase 7.@@ -1108,7 +1108,7 @@ Do NOT leave an *unexplained* ticket in "In Progress" with no branch — that is## Phase 4 — Implement-Write the code, tests, and any docs the ticket requires. Follow the repo conventions in CLAUDE.md (no try/catch in route handlers, functional programming, Zod validation, Tailwind tokens, reactive UI updates). Run the relevant test suite as you go.+Write the code, tests, and any docs the ticket requires. Follow the repo conventions in AGENTS.md / CLAUDE.md (no try/catch in route handlers, functional programming, Zod validation, Tailwind tokens, reactive UI updates). Run the relevant test suite as you go.**Roll discovered backbone work INTO this MR/PR** — small supporting helpers, refactors, and tests the fix depends on belong here, not a follow-up. Only defer genuinely-large adjacent work.@@ -1124,7 +1124,7 @@ The audit trail is the merged MR/PR + \`git log\`. Detect the forge from the gitThe configured reviewers for this task, in order, are \`{reviewers}\`. Split them by where they can run, preserving order: **LOCAL reviewers** — every token that is NOT an \`@<login>\` (\`claude\` / \`codex\` / \`antigravity\` (CLI binary: \`agy\`) / \`grok\` / \`cursor\` invoke a local-CLI critique; \`lmstudio\` / \`ollama\` use the appended Local Reviewer Procedure) read the working tree and need no MR/PR, so they run in steps 1–2 below, BEFORE it is opened. **PR-SIDE reviewers** — every \`@<login>\` token, plus any review bot the repo requests automatically on open — review cloud-side and run in Phase 6, once the MR/PR exists.-1. **Write the changelog entry now, not after the reviewers run** — every commit the reviewers are about to read must already be on the branch, or the MR/PR carries work nobody reviewed. If the repo maintains a changelog, record a one-line entry **following the convention that repo documents** — read its \`CLAUDE.md\` and changelog README (e.g. \`.changelog/README.md\`) first. Some repos collect per-branch fragments in a directory (e.g. \`.changelog/next/\`) via a helper script rather than appending to one shared file, precisely so parallel agents don't conflict on every merge; use that flow when it's documented. Fall back to appending to the unreleased section (\`.changelog/NEXT.md\`, or \`## Unreleased\` in \`CHANGELOG.md\`) in the repo's existing prose style only when no convention is documented. Otherwise skip it.+1. **Write the changelog entry now, not after the reviewers run** — every commit the reviewers are about to read must already be on the branch, or the MR/PR carries work nobody reviewed. If the repo maintains a changelog, record a one-line entry **following the convention that repo documents** — read its \`AGENTS.md\` (or \`CLAUDE.md\`) and changelog README (e.g. \`.changelog/README.md\`) first. Some repos collect per-branch fragments in a directory (e.g. \`.changelog/next/\`) via a helper script rather than appending to one shared file, precisely so parallel agents don't conflict on every merge; use that flow when it's documented. Fall back to appending to the unreleased section (\`.changelog/NEXT.md\`, or \`## Unreleased\` in \`CHANGELOG.md\`) in the repo's existing prose style only when no convention is documented. Otherwise skip it.2. **Self-review your diff for reuse, quality, and efficiency** (DRY, dead code, naming, simpler equivalents, missed edge cases) and fix the findings in the same diff. Claude Code runs this as the three-agent \`/simplify\` pass; on other CLIs, do the equivalent by hand.3. **Run each LOCAL reviewer in the listed order against the BRANCH diff, not an MR/PR diff.** Nothing is open yet, so use the CLI's own base-diff mode or \`git diff "origin/\${DEFAULT_BRANCH}...HEAD"\`; local LLM reviewers go through the appended endpoint procedure. Apply the findings, run the tests, and commit the fixes — capped at 3 rounds per reviewer — then advance. A missing CLI, timeout, transport failure, malformed response, or empty response is UNSATISFIED, not clean. Do NOT substitute your own self-review, and do NOT open an MR/PR on the strength of it. If a local reviewer stays unsatisfied after 3 rounds, or its fixes leave the build/tests red, do NOT open one — leave the branch and worktree in place, comment the failure on the ticket (POST ${PORTOS_API_URL}/api/jira/instances/<instanceId>/tickets/<KEY>/comments), and stop.4. Push the branch: \`git push -u origin "claim/\${KEY}"\`, then confirm \`git log --oneline @{u}..HEAD\` is empty so every review fix from step 3 is in the MR/PR's diff.@@ -1168,7 +1168,7 @@ Repository: {repoPath}2. Read PLAN.md (if exists) to understand already-planned work — do NOT re-suggest items already planned3. Skim recent \`.changelog/\` entries (or equivalent) and \`git log\` (last 50 commits) to understand completed work — do NOT re-suggest items already shipped4. Read REJECTED.md (if exists) to understand previously rejected recommendations — do NOT re-suggest rejected items-5. Read CLAUDE.md for project conventions and architecture+5. Read AGENTS.md (or CLAUDE.md) for project conventions and architecture6. Review the codebase structure, key files, recent git log (last 20 commits)## Phase 2 — Deep Review@@ -1220,7 +1220,7 @@ Repository: {repoPath}2. Read GOALS.md (if exists) for alignment context3. Read PLAN.md (if exists) for current planned work4. Skim recent \`.changelog/\` entries and \`git log\` for completed work-5. Read CLAUDE.md for project conventions+5. Read AGENTS.md (or CLAUDE.md) for project conventions## Phase 2 — Triage Each Recommendation@@ -1238,7 +1238,7 @@ Categorize into:## Phase 3 — Implement6. For each IMPLEMENT item:- - Implement the change following existing code patterns and CLAUDE.md conventions+ - Implement the change following existing code patterns and AGENTS.md (or CLAUDE.md) conventions- Run tests to verify nothing is broken- Commit with a clear message referencing the review recommendation@@ -1336,7 +1336,7 @@ First, extract \`<OWNER>\` and \`<REPO>\`:cd {repoPath} && gh repo view --json owner,name --jq '"OWNER=" + .owner.login + " REPO=" + .name'\`\`\`-Then search for release documentation. Check your CLAUDE.md context (already provided above) for "Git Workflow", "Release", or "Changelog" sections. If the release process is not clear from CLAUDE.md, check these files in order (use whichever exist):+Then search for release documentation. Check your AGENTS.md (or CLAUDE.md) context (already provided above) for "Git Workflow", "Release", or "Changelog" sections. If the release process is not clear from those instructions, check these files in order (use whichever exist):1. \`cat {repoPath}/README.md\` — look for release/deployment/workflow sections2. \`cat {repoPath}/.changelog/README.md\` — changelog format and release conventions3. \`cat {repoPath}/CONTRIBUTING.md\` — contributing/release guidelines@@ -1480,7 +1480,7 @@ Run \`git stash list\`. For each \`stash@{N}\`:2. For every changed symbol or section in the patch, check whether current \`main\`/HEAD already contains the same change or a superset of it — grep the target file(s) for the added identifiers, read the surrounding code, and compare. If the stash's message references a branch name, also check \`git branch -a\` and \`git log --all --oneline\` for whether that branch was already merged or deleted (a strong signal the stash is redundant leftover cruft).3. Classify each stash:- **SUPERSEDED** — the change (or a superset of it) already exists on \`main\`. Safe to drop.- - **STALE/ABANDONED** — old WIP, exploratory scratch, lockfile-only diff noise, a reference to a file that no longer exists in the repo, or a change that contradicts current architecture/policy (check this repo's CLAUDE.md before assuming). Safe to drop.+ - **STALE/ABANDONED** — old WIP, exploratory scratch, lockfile-only diff noise, a reference to a file that no longer exists in the repo, or a change that contradicts current architecture/policy (check this repo's AGENTS.md (or CLAUDE.md) before assuming). Safe to drop.- **REAL UNLANDED WORK** — a coherent change that is not on \`main\` and is not obviously abandoned. Do NOT drop it. Note what it does, which files it touches, and how stale the underlying branch/context looks.4. Before diffing two stashes independently, check for duplicates: \`diff <(git stash show -p stash@{A}) <(git stash show -p stash@{B})\`. Identical stashes are one unit — classify and act on them together.diff --git a/server/services/taskPromptDefaults/versions.js b/server/services/taskPromptDefaults/versions.jsindex d2c6424a4f..38e28b7a11 100644--- a/server/services/taskPromptDefaults/versions.js+++ b/server/services/taskPromptDefaults/versions.js@@ -1,6 +1,6 @@/*** Prompt-version machinery for the cross-install auto-upgrade contract.- * See the barrel (../taskPromptDefaults.js) header and CLAUDE.md+ * See the barrel (../taskPromptDefaults.js) header and AGENTS.md* "Distribution model" before editing.*/@@ -11,10 +11,10 @@ export const PROMPT_VERSIONS = {// fail closed, verify the remote merge state, and clean up without force-delete.'do-replan': 2, // v2: scheduled issue-quality gate rejects speculative/future-only work and keeps valid current refactors claimable'feature-ideas': 10, // v10: Phase 4 (Brainstorm) consults the repo's REJECTED.md and recently closed-unmerged PRs before proposing, so ideas the user already declined aren't re-proposed (mirrors idle-review's REJECTED.md contract). v9: drop DONE.md reads — use `.changelog/` + `git log` (last 50) as the completed-work signal- 'plan-task': 16, // v16: every reviewer that can read the working tree runs BEFORE the PR is opened — Phase 6 splits the configured list into LOCAL reviewers (every non-`@<login>` token, reviewed against `git diff origin/main...HEAD`) and PR-SIDE reviewers (`@<login>` plus any auto-requested review bot), opens the PR only once the branch is review-clean, and then waits on those PR-side reviewers plus required CI. Previously the PR was opened first and every reviewer ran against its diff, so each round of findings landed as follow-up commits on an already-public PR. v14: claim worktree creation passes `--no-track`, so a branch based on `origin/main` cannot inherit `main` as its upstream and make a config-derived push write directly to the default branch; the later `git push -u` sets the intended branch upstream. v13: Phase 5's changelog step reads the repo's documented convention FIRST (per-branch fragment directory + helper script, as PortOS now uses) and only falls back to detect-and-append when none is documented; the Phase 6 review-stuck note no longer names `.changelog/NEXT.md` as the file it wrote. v12: the reviewer bullets name the antigravity reviewer's actual PATH binary (`agy`) — the bare `antigravity` slug is a command that exists nowhere, and a review-loop agent that probed for it concluded no reviewer was available and merged on its own self-review. The same bump adds the missing-binary guard: a reviewer whose CLI is not on PATH is UNSATISFIED, never a clean review the agent substitutes its own self-review for. v11: worktree is created under PortOS's shared worktrees dir (`{worktreesRoot}` → data/cos/worktrees) instead of a repo-relative `data/cos/worktrees/` path, so the agent's checkout no longer lands inside the managed app's working tree. v10: Phase 3 "decide, don't defer" — an *ambiguous* PLAN.md item no longer jumps to the Phase 3b clarification PR; the agent picks the most reasonable reading, notes it, and implements. Phase 3b is reserved for destructive/irreversible or genuinely-human-gated items. Mirrors claim-issue v7 + CLAUDE.md. v9: per-kind reviewer bullets name `grok` alongside `claude`/`codex`/`antigravity` as a local-CLI reviewer (grok is now a selectable Review Loop reviewer). v8: Phase-6 merge fallback prefers --merge over --squash (after --auto), matching the /do:pr + review-loop default and PortOS's merge-only policy- 'claim-issue': 16, // v16: Phase 1 step 4's blocking-label check is now the `{issueExcludeLabels}` placeholder (resolveIssueExcludeLabelsBlock, cosTaskGenerator.js) — the fixed NON_ACTIONABLE_ISSUE_LABELS set plus any app-configured `taskMetadata.issueExcludeLabels` extras (e.g. `good first issue`), so the live claim agent honors the same per-app exclusions the perpetual-drain detector applies, not just the hardcoded set. The pinned-target constraint (`/do:next <num>` / the work-item picker) also re-checks that resolved list, not just the fixed 3, so a target that gained an excluded label after the picker snapshot still isn't force-claimed. Phase 1's candidate fetch widened to `--limit 500` (was 100), matching perpetualWork.js's detector — the label filter runs on the fetched page, so a small cap risked missing eligible work further down a busy queue. v15: Phase 5 is now the pre-PR local review (LOCAL reviewers = every non-`@<login>` token, run against the branch diff; an unsatisfied one blocks PR creation entirely) and Phase 6 opens the PR, satisfies the PR-SIDE reviewers (`@<login>` plus any auto-requested review bot) and required CI, then merges. v13: follow-up issue recipes choose independent slashdo dispatch hints (`model:`/`effort:`) and contributor labels (`good first issue`/`help wanted`) instead of only `plan`. v12: claim worktree creation passes `--no-track`, so a branch based on `origin/main` cannot inherit `main` as its upstream and make a config-derived push write directly to the default branch; the later `git push -u` sets the intended branch upstream. v11: EVERY Phase-3 release now converges — the "already fixed / superseded" case CLOSES the issue (with a comment naming what delivered it) and the "stale reference" case tags `needs-input`, instead of both releasing the issue open and unlabeled. `isActionableIssue` (perpetualWork.js) can only see labels/assignees/epic/in-flight, so a body-or-comment-driven release left the issue looking actionable and the perpetual drain re-spawned a no-op agent on it every tick. v10: Phase 5's changelog step defers to the convention the repo documents (per-branch fragment directory + helper script when present) instead of prescribing an append to `.changelog/NEXT.md`. v9: reviewer bullets name the antigravity reviewer's actual PATH binary (`agy`) — mirrors plan-task v12. The same bump adds the missing-binary guard: a reviewer whose CLI is not on PATH is UNSATISFIED, never a clean review the agent substitutes its own self-review for. v8: worktree is created under PortOS's shared worktrees dir (`{worktreesRoot}` → data/cos/worktrees) instead of a repo-relative `data/cos/worktrees/` path, so the agent's checkout no longer lands inside the managed app's working tree. v7: Phase 3 no longer releases/parks an *ambiguous* issue to `needs-input` — the agent decides (picks the most reasonable reading, records it in an issue comment, ships) rather than punting the choice back to a human; `needs-input` is reserved for destructive/irreversible or genuinely-human-gated (hardware/credentials) cases. Mirrors the "Decide, don't defer" policy in CLAUDE.md. v6: Phase 1 epic skip also recognizes a leading `[epic]` bracket or `Epic:` colon title tag (e.g. "[Epic] …" / "Epic: …"), not just an `epic` label or a "(epic)" suffix — mirrors the perpetualWork detector so a `[Epic]`-titled issue with no `epic` label stops re-spawning a claim agent that always skips it (perpetual drain now converges/parks). v5: per-kind reviewer bullets name `grok` alongside `claude`/`codex`/`antigravity` as a local-CLI reviewer (grok is now a selectable Review Loop reviewer). v4: Phase 5 chooses the issue trailer deliberately (Closes for a full ship, Refs + a `## Remaining` section for a partial one) and Phase 7 reconciles the issue with the partial-ship hybrid — close + file a scoped follow-up when the remainder is separable, else comment "done/remaining" + release the `in-progress` claim — so a partial ship is never left OPEN + `in-progress` (a zombie the claim queue skips forever). v3: Phase 3 tags an ambiguous/too-large issue `needs-input` (not just a comment) so it's excluded from future autonomous claims — required for `perpetual` (drain-until-done) mode to converge instead of re-picking the same un-actionable issue. v2: stop treating the bare `plan` label as a skip — `plan` is the claimable-queue label (do-replan --issues labels every migrated backlog item `plan`), so v1's exclusion emptied the whole actionable queue; now skip only true epics (`epic` label or "(epic)" title)- 'claim-issue-gitlab': 16, // v16: the Phase 1 and Phase 6 glab recipes use `--output json` instead of `-F json`. On `glab issue list`, `-F` is `--output-format` (details|ids|urls) — a DIFFERENT flag from `--output` (text|json) — so that spelling was accepted, ignored, and answered with the human table at exit 0; an agent piping that to `jq` got nothing and could not distinguish it from "no issues". `--output json` is correct on every glab subcommand, so the mr recipes are normalized to the same spelling in this bump. v15: mirrors claim-issue v16 — Phase 1 step 4's blocking-label check is now the `{issueExcludeLabels}` placeholder. v14: mirrors claim-issue v15 — Phase 5 runs the LOCAL reviewers against the branch diff before any MR exists, Phase 6 opens the MR and satisfies the MR-SIDE reviewers + pipeline before merging. v12: follow-up issue recipes choose independent slashdo dispatch hints (`model:`/`effort:`) and contributor labels (`good first issue`/`help wanted`) instead of only `plan`. v11: claim worktree creation passes `--no-track`, so a branch based on the default-branch remote ref does not inherit it as an upstream; the later `git push -u` sets the intended branch upstream. v10: mirrors claim-issue v11 — every Phase-3 release converges (close the already-fixed/superseded issue, tag the stale-reference one `needs-input`) so the perpetual drain stops re-picking it. v9: mirrors claim-issue v10 — Phase 5's changelog step defers to the repo's documented convention (per-branch fragments) rather than prescribing a `.changelog/NEXT.md` append. v8: reviewer bullets name the antigravity reviewer's actual PATH binary (`agy`) — mirrors plan-task v12. The same bump adds the missing-binary guard: a reviewer whose CLI is not on PATH is UNSATISFIED, never a clean review the agent substitutes its own self-review for. v7: worktree is created under PortOS's shared worktrees dir (`{worktreesRoot}` → data/cos/worktrees) instead of a repo-relative `data/cos/worktrees/` path, so the agent's checkout no longer lands inside the managed app's working tree (mirrors claim-issue v8). v6: mirrors claim-issue v7 — Phase 3 decides an *ambiguous* issue (record the chosen reading in an issue note, ship) instead of parking it to `needs-input`, which is reserved for destructive/irreversible or genuinely-human-gated (hardware/credentials) cases. v5: mirrors claim-issue v6 — Phase 1 epic skip also recognizes a leading `[epic]` bracket or `Epic:` colon title tag (e.g. "[Epic] …" / "Epic: …"), not just an `epic` label or a "(epic)" suffix, so the GitLab detector/agent converge on epic-titled issues too. v4: per-kind reviewer bullets name `grok` alongside `claude`/`codex`/`antigravity` as a local-CLI reviewer (grok is now a selectable Review Loop reviewer). v3: mirrors claim-issue v4 — Phase 5 chooses Closes-vs-Refs deliberately and Phase 7 reconciles the issue with the partial-ship hybrid (close + scoped follow-up when separable, else "done/remaining" note + release the `in-progress` claim) so a partial ship is never stranded. v2: Phase 3 tags an ambiguous/too-large issue `needs-input` (mirrors claim-issue v3) so it's excluded from future autonomous claims — required for `perpetual` (drain-until-done) mode to converge. v1: GitLab sibling of claim-issue — same 7-phase /claim --issues flow over `glab` issues + merge requests. Reached via the claim-work router when an app's resolved workTracker is 'gitlab'.- 'claim-issue-jira': 12, // v12: mirrors claim-issue v15 in the JIRA flow — Phase 5 runs the LOCAL reviewers against the branch diff before the MR/PR is opened (and before the In Review transition), Phase 6 keeps only the PR-side reviewers plus the worktree cleanup. v10: follow-up tickets receive equivalent hyphenated dispatch (`model-*`/`effort-*`) and contributor (`good-first-issue`/`help-wanted`) labels when independently justified. v9: claim worktree creation passes `--no-track`, so a branch based on the default-branch remote ref does not inherit it as an upstream; the later `git push -u` sets the intended branch upstream. v8: mirrors claim-issue v11 in JIRA's status vocabulary — an already-fixed/superseded ticket transitions to Done/Closed and a stale-reference ticket parks on a Blocked/On Hold status behind a Review Hub todo, instead of transitioning back to a not-started status that Phase 1 immediately re-picks. v7: mirrors claim-issue v10 — Phase 5's changelog step defers to the repo's documented convention (per-branch fragments) rather than prescribing a `.changelog/NEXT.md` append. v6: reviewer bullets name the antigravity reviewer's actual PATH binary (`agy`) — mirrors plan-task v12. The same bump adds the missing-binary guard: a reviewer whose CLI is not on PATH is UNSATISFIED, never a clean review the agent substitutes its own self-review for. v5: worktree is created under PortOS's shared worktrees dir (`{worktreesRoot}` → data/cos/worktrees) instead of `{repoPath}/data/cos/worktrees/`, so the agent's checkout no longer lands inside the managed app's working tree (mirrors claim-issue v8). v4: mirrors claim-issue v7 — Phase 3 decides an *ambiguous* ticket (record the chosen reading in a ticket comment, ship) instead of parking it to a "Needs clarification" Review Hub todo, and Phase 1 no longer skips a merely-underspecified ticket; the todo is reserved for destructive/irreversible or genuinely-human-gated cases. v3: per-kind reviewer bullets name `grok` alongside `claude`/`codex`/`antigravity` as a local-CLI reviewer (grok is now a selectable Review Loop reviewer). v2: Phase 5 records remaining scope in the ticket (Done/Remaining comment) and files a follow-up ticket when a partial ship's remainder is separable, so remaining work isn't lost when a human lands the MR/PR. v1: JIRA sibling of claim-issue — claim ONE ready sprint ticket, move it To Do→In Progress→In Review around a self-managed worktree + MR/PR. Reached via the claim-work router when an app's resolved workTracker is 'jira' (replaces the prior jira→jira-sprint-manager route).+ 'plan-task': 17, // v17: the implement + changelog steps name `AGENTS.md` (or `CLAUDE.md`) as the repo-conventions file (#4852 made AGENTS.md canonical; the dual naming keeps a managed app that still carries only the old name discoverable). v16: every reviewer that can read the working tree runs BEFORE the PR is opened — Phase 6 splits the configured list into LOCAL reviewers (every non-`@<login>` token, reviewed against `git diff origin/main...HEAD`) and PR-SIDE reviewers (`@<login>` plus any auto-requested review bot), opens the PR only once the branch is review-clean, and then waits on those PR-side reviewers plus required CI. Previously the PR was opened first and every reviewer ran against its diff, so each round of findings landed as follow-up commits on an already-public PR. v14: claim worktree creation passes `--no-track`, so a branch based on `origin/main` cannot inherit `main` as its upstream and make a config-derived push write directly to the default branch; the later `git push -u` sets the intended branch upstream. v13: Phase 5's changelog step reads the repo's documented convention FIRST (per-branch fragment directory + helper script, as PortOS now uses) and only falls back to detect-and-append when none is documented; the Phase 6 review-stuck note no longer names `.changelog/NEXT.md` as the file it wrote. v12: the reviewer bullets name the antigravity reviewer's actual PATH binary (`agy`) — the bare `antigravity` slug is a command that exists nowhere, and a review-loop agent that probed for it concluded no reviewer was available and merged on its own self-review. The same bump adds the missing-binary guard: a reviewer whose CLI is not on PATH is UNSATISFIED, never a clean review the agent substitutes its own self-review for. v11: worktree is created under PortOS's shared worktrees dir (`{worktreesRoot}` → data/cos/worktrees) instead of a repo-relative `data/cos/worktrees/` path, so the agent's checkout no longer lands inside the managed app's working tree. v10: Phase 3 "decide, don't defer" — an *ambiguous* PLAN.md item no longer jumps to the Phase 3b clarification PR; the agent picks the most reasonable reading, notes it, and implements. Phase 3b is reserved for destructive/irreversible or genuinely-human-gated items. Mirrors claim-issue v7 + CLAUDE.md. v9: per-kind reviewer bullets name `grok` alongside `claude`/`codex`/`antigravity` as a local-CLI reviewer (grok is now a selectable Review Loop reviewer). v8: Phase-6 merge fallback prefers --merge over --squash (after --auto), matching the /do:pr + review-loop default and PortOS's merge-only policy+ 'claim-issue': 17, // v17: mirrors plan-task v17 — Phase 4 and Phase 5 name `AGENTS.md` (or `CLAUDE.md`) as the repo-conventions file (#4852). v16: Phase 1 step 4's blocking-label check is now the `{issueExcludeLabels}` placeholder (resolveIssueExcludeLabelsBlock, cosTaskGenerator.js) — the fixed NON_ACTIONABLE_ISSUE_LABELS set plus any app-configured `taskMetadata.issueExcludeLabels` extras (e.g. `good first issue`), so the live claim agent honors the same per-app exclusions the perpetual-drain detector applies, not just the hardcoded set. The pinned-target constraint (`/do:next <num>` / the work-item picker) also re-checks that resolved list, not just the fixed 3, so a target that gained an excluded label after the picker snapshot still isn't force-claimed. Phase 1's candidate fetch widened to `--limit 500` (was 100), matching perpetualWork.js's detector — the label filter runs on the fetched page, so a small cap risked missing eligible work further down a busy queue. v15: Phase 5 is now the pre-PR local review (LOCAL reviewers = every non-`@<login>` token, run against the branch diff; an unsatisfied one blocks PR creation entirely) and Phase 6 opens the PR, satisfies the PR-SIDE reviewers (`@<login>` plus any auto-requested review bot) and required CI, then merges. v13: follow-up issue recipes choose independent slashdo dispatch hints (`model:`/`effort:`) and contributor labels (`good first issue`/`help wanted`) instead of only `plan`. v12: claim worktree creation passes `--no-track`, so a branch based on `origin/main` cannot inherit `main` as its upstream and make a config-derived push write directly to the default branch; the later `git push -u` sets the intended branch upstream. v11: EVERY Phase-3 release now converges — the "already fixed / superseded" case CLOSES the issue (with a comment naming what delivered it) and the "stale reference" case tags `needs-input`, instead of both releasing the issue open and unlabeled. `isActionableIssue` (perpetualWork.js) can only see labels/assignees/epic/in-flight, so a body-or-comment-driven release left the issue looking actionable and the perpetual drain re-spawned a no-op agent on it every tick. v10: Phase 5's changelog step defers to the convention the repo documents (per-branch fragment directory + helper script when present) instead of prescribing an append to `.changelog/NEXT.md`. v9: reviewer bullets name the antigravity reviewer's actual PATH binary (`agy`) — mirrors plan-task v12. The same bump adds the missing-binary guard: a reviewer whose CLI is not on PATH is UNSATISFIED, never a clean review the agent substitutes its own self-review for. v8: worktree is created under PortOS's shared worktrees dir (`{worktreesRoot}` → data/cos/worktrees) instead of a repo-relative `data/cos/worktrees/` path, so the agent's checkout no longer lands inside the managed app's working tree. v7: Phase 3 no longer releases/parks an *ambiguous* issue to `needs-input` — the agent decides (picks the most reasonable reading, records it in an issue comment, ships) rather than punting the choice back to a human; `needs-input` is reserved for destructive/irreversible or genuinely-human-gated (hardware/credentials) cases. Mirrors the "Decide, don't defer" policy in CLAUDE.md. v6: Phase 1 epic skip also recognizes a leading `[epic]` bracket or `Epic:` colon title tag (e.g. "[Epic] …" / "Epic: …"), not just an `epic` label or a "(epic)" suffix — mirrors the perpetualWork detector so a `[Epic]`-titled issue with no `epic` label stops re-spawning a claim agent that always skips it (perpetual drain now converges/parks). v5: per-kind reviewer bullets name `grok` alongside `claude`/`codex`/`antigravity` as a local-CLI reviewer (grok is now a selectable Review Loop reviewer). v4: Phase 5 chooses the issue trailer deliberately (Closes for a full ship, Refs + a `## Remaining` section for a partial one) and Phase 7 reconciles the issue with the partial-ship hybrid — close + file a scoped follow-up when the remainder is separable, else comment "done/remaining" + release the `in-progress` claim — so a partial ship is never left OPEN + `in-progress` (a zombie the claim queue skips forever). v3: Phase 3 tags an ambiguous/too-large issue `needs-input` (not just a comment) so it's excluded from future autonomous claims — required for `perpetual` (drain-until-done) mode to converge instead of re-picking the same un-actionable issue. v2: stop treating the bare `plan` label as a skip — `plan` is the claimable-queue label (do-replan --issues labels every migrated backlog item `plan`), so v1's exclusion emptied the whole actionable queue; now skip only true epics (`epic` label or "(epic)" title)+ 'claim-issue-gitlab': 17, // v17: mirrors claim-issue v17 — the repo-conventions file is named `AGENTS.md` (or `CLAUDE.md`) (#4852). v16: the Phase 1 and Phase 6 glab recipes use `--output json` instead of `-F json`. On `glab issue list`, `-F` is `--output-format` (details|ids|urls) — a DIFFERENT flag from `--output` (text|json) — so that spelling was accepted, ignored, and answered with the human table at exit 0; an agent piping that to `jq` got nothing and could not distinguish it from "no issues". `--output json` is correct on every glab subcommand, so the mr recipes are normalized to the same spelling in this bump. v15: mirrors claim-issue v16 — Phase 1 step 4's blocking-label check is now the `{issueExcludeLabels}` placeholder. v14: mirrors claim-issue v15 — Phase 5 runs the LOCAL reviewers against the branch diff before any MR exists, Phase 6 opens the MR and satisfies the MR-SIDE reviewers + pipeline before merging. v12: follow-up issue recipes choose independent slashdo dispatch hints (`model:`/`effort:`) and contributor labels (`good first issue`/`help wanted`) instead of only `plan`. v11: claim worktree creation passes `--no-track`, so a branch based on the default-branch remote ref does not inherit it as an upstream; the later `git push -u` sets the intended branch upstream. v10: mirrors claim-issue v11 — every Phase-3 release converges (close the already-fixed/superseded issue, tag the stale-reference one `needs-input`) so the perpetual drain stops re-picking it. v9: mirrors claim-issue v10 — Phase 5's changelog step defers to the repo's documented convention (per-branch fragments) rather than prescribing a `.changelog/NEXT.md` append. v8: reviewer bullets name the antigravity reviewer's actual PATH binary (`agy`) — mirrors plan-task v12. The same bump adds the missing-binary guard: a reviewer whose CLI is not on PATH is UNSATISFIED, never a clean review the agent substitutes its own self-review for. v7: worktree is created under PortOS's shared worktrees dir (`{worktreesRoot}` → data/cos/worktrees) instead of a repo-relative `data/cos/worktrees/` path, so the agent's checkout no longer lands inside the managed app's working tree (mirrors claim-issue v8). v6: mirrors claim-issue v7 — Phase 3 decides an *ambiguous* issue (record the chosen reading in an issue note, ship) instead of parking it to `needs-input`, which is reserved for destructive/irreversible or genuinely-human-gated (hardware/credentials) cases. v5: mirrors claim-issue v6 — Phase 1 epic skip also recognizes a leading `[epic]` bracket or `Epic:` colon title tag (e.g. "[Epic] …" / "Epic: …"), not just an `epic` label or a "(epic)" suffix, so the GitLab detector/agent converge on epic-titled issues too. v4: per-kind reviewer bullets name `grok` alongside `claude`/`codex`/`antigravity` as a local-CLI reviewer (grok is now a selectable Review Loop reviewer). v3: mirrors claim-issue v4 — Phase 5 chooses Closes-vs-Refs deliberately and Phase 7 reconciles the issue with the partial-ship hybrid (close + scoped follow-up when separable, else "done/remaining" note + release the `in-progress` claim) so a partial ship is never stranded. v2: Phase 3 tags an ambiguous/too-large issue `needs-input` (mirrors claim-issue v3) so it's excluded from future autonomous claims — required for `perpetual` (drain-until-done) mode to converge. v1: GitLab sibling of claim-issue — same 7-phase /claim --issues flow over `glab` issues + merge requests. Reached via the claim-work router when an app's resolved workTracker is 'gitlab'.+ 'claim-issue-jira': 13, // v13: mirrors claim-issue v17 — the repo-conventions file is named `AGENTS.md` (or `CLAUDE.md`) (#4852). v12: mirrors claim-issue v15 in the JIRA flow — Phase 5 runs the LOCAL reviewers against the branch diff before the MR/PR is opened (and before the In Review transition), Phase 6 keeps only the PR-side reviewers plus the worktree cleanup. v10: follow-up tickets receive equivalent hyphenated dispatch (`model-*`/`effort-*`) and contributor (`good-first-issue`/`help-wanted`) labels when independently justified. v9: claim worktree creation passes `--no-track`, so a branch based on the default-branch remote ref does not inherit it as an upstream; the later `git push -u` sets the intended branch upstream. v8: mirrors claim-issue v11 in JIRA's status vocabulary — an already-fixed/superseded ticket transitions to Done/Closed and a stale-reference ticket parks on a Blocked/On Hold status behind a Review Hub todo, instead of transitioning back to a not-started status that Phase 1 immediately re-picks. v7: mirrors claim-issue v10 — Phase 5's changelog step defers to the repo's documented convention (per-branch fragments) rather than prescribing a `.changelog/NEXT.md` append. v6: reviewer bullets name the antigravity reviewer's actual PATH binary (`agy`) — mirrors plan-task v12. The same bump adds the missing-binary guard: a reviewer whose CLI is not on PATH is UNSATISFIED, never a clean review the agent substitutes its own self-review for. v5: worktree is created under PortOS's shared worktrees dir (`{worktreesRoot}` → data/cos/worktrees) instead of `{repoPath}/data/cos/worktrees/`, so the agent's checkout no longer lands inside the managed app's working tree (mirrors claim-issue v8). v4: mirrors claim-issue v7 — Phase 3 decides an *ambiguous* ticket (record the chosen reading in a ticket comment, ship) instead of parking it to a "Needs clarification" Review Hub todo, and Phase 1 no longer skips a merely-underspecified ticket; the todo is reserved for destructive/irreversible or genuinely-human-gated cases. v3: per-kind reviewer bullets name `grok` alongside `claude`/`codex`/`antigravity` as a local-CLI reviewer (grok is now a selectable Review Loop reviewer). v2: Phase 5 records remaining scope in the ticket (Done/Remaining comment) and files a follow-up ticket when a partial ship's remainder is separable, so remaining work isn't lost when a human lands the MR/PR. v1: JIRA sibling of claim-issue — claim ONE ready sprint ticket, move it To Do→In Progress→In Review around a self-managed worktree + MR/PR. Reached via the claim-work router when an app's resolved workTracker is 'jira' (replaces the prior jira→jira-sprint-manager route).'pr-reviewer': 3, // v3: multi-stage pipeline (security scan → code review + merge)'code-reviewer-a': 1, // v1: 2-stage pipeline (codebase review → triage & implement)'code-reviewer-b': 1, // v1: 2-stage pipeline (codebase review → triage & implement)@@ -35,14 +35,14 @@ export const PROMPT_VERSIONS = {'performance': 2, // v2: generic {appName} body (older default hardcoded "PortOS")'accessibility': 2, // v2: generic {appName} + the app UI (older default hardcoded "PortOS" + http://localhost:5555)'dependency-updates': 4, // v4: the Phase 1 GitLab MR listing gains `--output json` — without it glab answers with the human table, which carries the head branch but NOT the author, while the classification right below it reads both. The same bump drops `--state` from the MR-list recipes — that flag does not exist (MR state is selected by presence flags `--merged`/`--closed`/`--all`, and OPEN is the default), so `--state opened` exited 1 with `Unknown flag: --state` and Phase 1 skipped its bot-PR triage entirely on GitLab repos. v3: Phase 1 triages open Dependabot/Renovate PRs first (evidence → MERGE / FIX-THEN-MERGE / CLOSE / LEAVE, including conflict + CI-failure repair on the bot branch) before Phase 2 updates anything the bots didn't cover — an agent that bumped packages itself was duplicating and conflicting with open bot PRs. v2: generic {appName} body (older default hardcoded "PortOS")- 'documentation': 5, // v5: the changelog step defers to the convention the repo documents (some repos collect per-branch fragments in a directory so parallel agents don't conflict) instead of prescribing an append to `.changelog/NEXT.md`. v4: generic {appName} body (v1 hardcoded "PortOS"; v2/v3 retired DONE.md wording)+ 'documentation': 6, // v6: the changelog step names `AGENTS.md` (or `CLAUDE.md`) as the file carrying the repo's documented convention — #4852 made AGENTS.md the canonical cross-vendor agent-instructions filename, and a managed app that adopted it would otherwise be told to read a file it no longer has. v5: the changelog step defers to the convention the repo documents (some repos collect per-branch fragments in a directory so parallel agents don't conflict) instead of prescribing an append to `.changelog/NEXT.md`. v4: generic {appName} body (v1 hardcoded "PortOS"; v2/v3 retired DONE.md wording)'ui-bugs': 2, // v2: generic {appName} + the app UI (older default hardcoded "PortOS" + http://localhost:5555)'mobile-responsive': 2, // v2: generic {appName} app-UI body (older default hardcoded "PortOS" + http://localhost:5555)- 'ux': 1, // v1: walk the running UI with Playwright MCP against a 7-item named UX checklist and file ONE tracker item per finding via {trackerInstructions} — read-only on source, no branches/PRs. Net-new type (no PREVIOUS_DEFAULT_PROMPTS entry needed). Mode (file-issues vs implement) is injected at dispatch via {modeInstructions} / applyAuditModeWrapper — no prompt bump required.+ 'ux': 1, // v1: walk the running UI with Playwright MCP against a 7-item named UX checklist and file ONE tracker item per finding via {trackerInstructions} — read-only on source, no branches/PRs. Mode (file-issues vs implement) is injected at dispatch via {modeInstructions} / applyAuditModeWrapper — no prompt bump required.'data-safety': 1, // v1: data/upgrade-safety audit (migrations, schema parity, version gates). Mode injected at dispatch.'simplify': 1, // v1: dead-code/duplication audit. Mode injected at dispatch.- 'stash-cleanup': 1, // v1: triage git stash list — supersession check against main, drop superseded/stale entries, leave real unlanded work in place. Net-new type (no PREVIOUS_DEFAULT_PROMPTS entry needed).- 'release-check': 9, // v9: Step 1 reconciles missing GitHub Releases against git release tags (publishing any missing tag with .changelog/vX.Y.Z.md as body and --latest=false when a newer version exists) BEFORE evaluating if enough unreleased work has accumulated; v8: database-backed release tests are provisioned and run using the repo's documented isolated test database before the release PR gate; v7: Step 1 also reads the UNCOLLECTED changelog fragments (the fragment dir, plus whatever preview command that repo documents — release-check is a generic {appName} prompt, so it never names a PortOS script to run) and counts substantive entries across the assembled notes — reading only the staged `.changelog/NEXT.md` under-counts a release whose entries are still per-branch fragments, so a ready release reported as "not enough work". v6: generic {appName} body (older defaults hardcoded "PortOS")+ 'stash-cleanup': 2, // v2: the STALE/ABANDONED heuristic names `AGENTS.md` (or `CLAUDE.md`) as the policy file to check before assuming a stash contradicts current architecture (#4852). v1: triage git stash list — supersession check against main, drop superseded/stale entries, leave real unlanded work in place. Net-new type (no PREVIOUS_DEFAULT_PROMPTS entry needed).+ 'release-check': 10, // v10: the release-documentation search names the `AGENTS.md` (or `CLAUDE.md`) context instead of CLAUDE.md alone (#4852). v9: Step 1 reconciles missing GitHub Releases against git release tags (publishing any missing tag with .changelog/vX.Y.Z.md as body and --latest=false when a newer version exists) BEFORE evaluating if enough unreleased work has accumulated; v8: database-backed release tests are provisioned and run using the repo's documented isolated test database before the release PR gate; v7: Step 1 also reads the UNCOLLECTED changelog fragments (the fragment dir, plus whatever preview command that repo documents — release-check is a generic {appName} prompt, so it never names a PortOS script to run) and counts substantive entries across the assembled notes — reading only the staged `.changelog/NEXT.md` under-counts a release whose entries are still per-branch fragments, so a ready release reported as "not enough work". v6: generic {appName} body (older defaults hardcoded "PortOS")};// Audit anchor for reference-watch's read/write coupling.diff --git a/server/services/tracks/logic.js b/server/services/tracks/logic.jsindex c8960a7d02..90501df671 100644--- a/server/services/tracks/logic.js+++ b/server/services/tracks/logic.js@@ -301,7 +301,7 @@ export function mergeTrackRecord(local, remoteRaw) {if (!local) return { next: remote, inserted: true, remoteWins: true, changed: true };const remoteWins = compareNewerWins(remote.updatedAt, local.updatedAt);let next = remoteWins ? remote : local;- // Absent-vs-cleared (#2911, per the CLAUDE.md merge convention): a payload+ // Absent-vs-cleared (#2911, per the AGENTS.md merge convention): a payload// from a chiptune-unaware (≤v2) peer lacks the chiptune KEYS entirely, while// a v3 peer that intentionally cleared the score sends `chiptuneScore: null`// explicitly. Sanitizing collapses both to null, so gate on key presence in@@ -321,7 +321,7 @@ export function mergeTrackRecord(local, remoteRaw) {/*** Apply a partial patch onto an existing record. Only keys PRESENT in `patch`- * overwrite — absent preserves, present-empty clears (per CLAUDE.md). Bumps+ * overwrite — absent preserves, present-empty clears (per AGENTS.md). Bumps* updatedAt.*/export function applyTrackPatch(current, patch = {}) {diff --git a/server/services/twinEnrichment.js b/server/services/twinEnrichment.jsindex a846653d1a..cfc8679f67 100644--- a/server/services/twinEnrichment.js+++ b/server/services/twinEnrichment.js@@ -23,7 +23,7 @@* each source sync or on a daily rollup tick with no user consent (no provider* calls). The ONLY provider call is `interpretConsumption()`, invoked strictly* from an explicit user-action route (the "what does my consumption say about- * me" button), per CLAUDE.md's AI-provider policy (no cold-bootstrap calls).+ * me" button), per AGENTS.md's AI-provider policy (no cold-bootstrap calls).*/import { join } from 'path';diff --git a/server/services/universeBuilder.test.js b/server/services/universeBuilder.test.jsindex fa24f2e454..8b7d343e5e 100644--- a/server/services/universeBuilder.test.js+++ b/server/services/universeBuilder.test.js@@ -2784,7 +2784,7 @@ describe("universeBuilder service", () => {});// Regression for "Async PATCH races on shared records — serialize writes- // server-side" (CLAUDE.md). Each updateUniverse() now goes through a+ // server-side" (AGENTS.md). Each updateUniverse() now goes through a// file-level write tail so a stale snapshot can't clobber a sibling write.describe("write serialization", () => {it("concurrent updates to the same universe preserve every field", async () => {@@ -2808,7 +2808,7 @@ describe("universeBuilder service", () => {});it("concurrent updates to DIFFERENT universes preserve every field", async () => {- // Per CLAUDE.md: a Map<id, Promise> is NOT enough — both universes+ // Per AGENTS.md: a Map<id, Promise> is NOT enough — both universes// share the same JSON file, so writes to different ids can still race.// The single file-level tail covers this.const a = await svc.createUniverse({ name: "A" });diff --git a/server/services/universeCharacterExpand.js b/server/services/universeCharacterExpand.jsindex cb9e32bdfa..5c2275a4c9 100644--- a/server/services/universeCharacterExpand.js+++ b/server/services/universeCharacterExpand.js@@ -6,7 +6,7 @@* - key absent from LLM response → preserve existing value* - key present with empty string/array → IGNORED (no-op; expand flow has* no "clear" intent — an empty proposal just means the LLM had nothing- * to add). Distinct from the CLAUDE.md merge convention used for+ * to add). Distinct from the AGENTS.md merge convention used for* direct-user PATCHes, where empty CAN mean clear.* - key present with non-empty value → fill ONLY when target field is blank.*/diff --git a/server/services/usageReconciler.test.js b/server/services/usageReconciler.test.jsindex 4fb6b3ba81..9f9451f366 100644--- a/server/services/usageReconciler.test.js+++ b/server/services/usageReconciler.test.js@@ -18,7 +18,7 @@ const {} = await import('./usageReconciler.js');// Fake HOME per test so the parsers read fixtures, never the developer's real-// ~/.claude or ~/.codex (which hold private session data — see CLAUDE.md).+// ~/.claude or ~/.codex (which hold private session data — see AGENTS.md).let home;const WORKSPACE = '/work/example-repo';// claudeProjectSlug(WORKSPACE) — the CLI names its project dir after the cwd.diff --git a/server/services/videoGen/history.js b/server/services/videoGen/history.jsindex 47a915d071..96df5adcab 100644--- a/server/services/videoGen/history.js+++ b/server/services/videoGen/history.js@@ -45,7 +45,7 @@ export async function getHistoryItem(id) {// same stale array and the later save clobbers the earlier's new entry, leaving// an orphaned file that's absent from the list/media-index and undeletable. A// module-level promise tail collapses concurrent mutations to a single writer-// per file (the `issueWriteTail` pattern in CLAUDE.md). `mutator(list)` receives+// per file (the `issueWriteTail` pattern in AGENTS.md). `mutator(list)` receives// the freshest persisted array and returns the array to persist (return the// same reference after mutating it in place, or a new array). Any writer that// can race another on this file should route through here.diff --git a/server/services/voice/timers.js b/server/services/voice/timers.jsindex 3a86ec4113..5b8f47a010 100644--- a/server/services/voice/timers.js+++ b/server/services/voice/timers.js@@ -45,7 +45,7 @@ function persist() {}// Raise the reminder. Runs outside the request lifecycle, so the write is-// guarded (per CLAUDE.md) — a thrown notification write can't crash the process.+// guarded (per AGENTS.md) — a thrown notification write can't crash the process.function notify(timer, { overdue = false } = {}) {return addNotification({type: NOTIFICATION_TYPES.AGENT_WARNING,diff --git a/server/services/voice/voiceOutput.js b/server/services/voice/voiceOutput.jsindex dd0e56d1dd..5082465643 100644--- a/server/services/voice/voiceOutput.js+++ b/server/services/voice/voiceOutput.js@@ -22,7 +22,7 @@// (which predates the announce/claim protocol) also never announces — the// `emitVoiceOutput` fallback covers that transient case.//-// Single-user trust model (see CLAUDE.md): no locking/atomicity needed here —+// Single-user trust model (see AGENTS.md): no locking/atomicity needed here —// one server process, one human. This is a re-entrancy-free in-memory registry.// Membership set of announced candidate sockets. Iteration order is connectiondiff --git a/server/services/workItems.js b/server/services/workItems.jsindex b4710f350a..de5313663f 100644--- a/server/services/workItems.js+++ b/server/services/workItems.js@@ -14,7 +14,7 @@* perpetual mode parks on 'no-detector' — so it reads the same sprint* query the app's Kanban board uses, minus already-started tickets)*- * Sentinel discipline (CLAUDE.md): a failed probe returns `items: []` WITH the+ * Sentinel discipline (AGENTS.md): a failed probe returns `items: []` WITH the* detector's `reason` + `transient: true`, so the caller can say "couldn't* reach the tracker" instead of the lie "no work available".*/diff --git a/server/services/workspaceContext.js b/server/services/workspaceContext.jsindex b31f7b8878..4545810439 100644--- a/server/services/workspaceContext.js+++ b/server/services/workspaceContext.js@@ -21,7 +21,7 @@* single `data/workspace-contexts.json` keyed by app id is the right shape* (small records, no relational queries, no tombstones/sync cursor). Writes* are serialized through a single-tail queue because both the blur/save path- * and an explicit restore can mutate the same file (CLAUDE.md: "serialize+ * and an explicit restore can mutate the same file (AGENTS.md: "serialize* writes server-side… collapse the queue to a single tail per shared file").** This service is read-only with respect to user work: it NEVER stashes,@@ -175,7 +175,7 @@ export async function getContext(appId) {export async function saveContext(appId) {// The whole capture→write runs inside the queue so a concurrent delete can't// complete between this save's capture and its write and then be silently- // resurrected (CLAUDE.md: serialize the full read→modify→write on the shared+ // resurrected (AGENTS.md: serialize the full read→modify→write on the shared// file). Returns null (unknown app id) from inside the queue — fine, the// caller still gets the resolved value.return queueWrite(async () => {diff --git a/server/services/youtubeIngest.js b/server/services/youtubeIngest.jsindex 80bcd82b88..62b1de5099 100644--- a/server/services/youtubeIngest.js+++ b/server/services/youtubeIngest.js@@ -20,7 +20,7 @@* Finally, when the user supplies an `agentPrompt` at ingest time, a CoS task is* queued that points an agent at the freshly-stored transcript with that prompt* — "here is what I want done with this content." No prompt, no task: PortOS- * must never queue AI work the user didn't ask for (root CLAUDE.md, AI Provider+ * must never queue AI work the user didn't ask for (root AGENTS.md, AI Provider* Usage Policy).** Storage:@@ -629,7 +629,7 @@ export async function startYoutubeIngest({// Every await in this fire-and-forget coordinator must sit INSIDE the try:// there is no request lifecycle to bubble to, so a rejection escaping it- // takes the whole Node process down (root CLAUDE.md, no-try/catch exception).+ // takes the whole Node process down (root AGENTS.md, no-try/catch exception).try {// Read once: the vault/folder decision and the CoS task priority both come// from here, and an ingest should use one settings snapshot throughout.diff --git a/server/vitest.setup.js b/server/vitest.setup.jsindex 760350898d..3ad178e221 100644--- a/server/vitest.setup.js+++ b/server/vitest.setup.js@@ -14,7 +14,7 @@* `autoSubscribeRecordToAllPeers` early-returns the moment the target list is* empty, before any `subscribePeer`/HTTP work — so even a *registered* real* adapter issues no network calls. A suite only needs the additional- * `peerSync.js` mock (per the CLAUDE.md convention) when it imports the+ * `peerSync.js` mock (per the AGENTS.md convention) when it imports the* peer-sync graph and wants to keep the registration side effect out* entirely; suites that never load `peerSync.js` get a no-op adapter for free.*