From f460da47aa1bf57fc92bf8d5156e8a432f7ce9f8 Mon Sep 17 00:00:00 2001
From: SongRenShuo <3064597532@qq.com>
Date: Tue, 17 Nov 2026 23:19:59 +0800
Subject: [PATCH 001/440] docs: add collaboration system distilled from the
sql-visualizer project
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Port the reusable development disciplines from mybatis-plus-sql-visualizer
into this repo:
- AGENTS.md: agent entry points (parallel registry, test tiers, commit rules)
- docs/LESSONS.md: a lessons ledger with the magpie mechanism (evidence +
positive/negative example + Seen counter; entries hitting Seen 3 on
different dates graduate into the standards doc), seeded with 44
cross-stack lessons imported from 80 ledger entries
- docs/规范/: coding & acceptance standards (V/C/M tables), grep-first
editing, doc naming, memory hygiene, popup restraint, collaboration
preferences, git & multi-repo recipes
- docs/开发流程-派活与验收清单.md: dispatch template + acceptance checklist
+ three-tier testing, adapted to cargo/pnpm commands
- docs/经验总结/: methodology digest (verification blindspots, background
dispatch, token governance)
- docs/MEMORY.md: index of the collaboration docs
- .agents/skills/: task-queue (gradle coupling removed) and security-audit
All files are new; no existing file was touched. The popup-restraint
checklist intentionally uses grep patterns instead of file:line anchors,
learning from the source repo where line-number lists rotted after
refactors.
---
.agents/skills/security-audit/AI-AND-LLM.md | 83 ++
.../skills/security-audit/ATTACK-CLASSES.md | 130 +++
.agents/skills/security-audit/CLIENT-SIDE.md | 83 ++
.../security-audit/CLOUD-AND-DEPLOYMENT.md | 86 ++
.../DATA-ISOLATION-AND-LIFECYCLE.md | 84 ++
.../DESKTOP-MOBILE-AND-LOCAL-IPC.md | 89 ++
.agents/skills/security-audit/HUNTING.md | 251 +++++
.../MEMORY-SAFETY-AND-BINARY.md | 101 ++
.../PROTOCOLS-RPC-AND-MESSAGING.md | 81 ++
.../skills/security-audit/RECONNAISSANCE.md | 156 ++++
.../RESOURCE-EXHAUSTION-AND-AVAILABILITY.md | 78 ++
.agents/skills/security-audit/SKILL.md | 192 ++++
.../SUPPLY-CHAIN-AND-RELEASE.md | 73 ++
.../VALIDATION-AND-REPORTING.md | 186 ++++
.../security-audit/WEB-PROTOCOL-AND-AUTH.md | 105 +++
.../skills/security-audit/report-schema.json | 461 +++++++++
.../validate-coverage-ledger.cjs | 872 ++++++++++++++++++
.../validate-coverage-ledger.test.cjs | 740 +++++++++++++++
.../security-audit/validate-findings.cjs | 773 ++++++++++++++++
.../security-audit/validate-findings.test.cjs | 652 +++++++++++++
.agents/skills/task-queue/SKILL.md | 95 ++
.agents/skills/task-queue/scripts/notify.ps1 | 19 +
.agents/skills/task-queue/scripts/watchdog.py | 55 ++
AGENTS.md | 13 +
docs/LESSONS.md | 170 ++++
docs/MEMORY.md | 33 +
...14\346\224\266\346\270\205\345\215\225.md" | 47 +
...17\351\252\214\346\200\273\347\273\223.md" | 48 +
...64\346\230\216\346\226\207\346\241\243.md" | 69 ++
...30\345\205\210\350\257\273\345\217\226.md" | 73 ++
...64\346\230\216\346\226\207\346\241\243.md" | 39 +
...64\346\230\216\346\226\207\346\241\243.md" | 50 +
...14\346\224\266\346\240\207\345\207\206.md" | 32 +
...76\347\256\200\350\247\204\350\214\203.md" | 83 ++
...13\345\210\266\347\272\242\347\272\277.md" | 57 ++
35 files changed, 6159 insertions(+)
create mode 100644 .agents/skills/security-audit/AI-AND-LLM.md
create mode 100644 .agents/skills/security-audit/ATTACK-CLASSES.md
create mode 100644 .agents/skills/security-audit/CLIENT-SIDE.md
create mode 100644 .agents/skills/security-audit/CLOUD-AND-DEPLOYMENT.md
create mode 100644 .agents/skills/security-audit/DATA-ISOLATION-AND-LIFECYCLE.md
create mode 100644 .agents/skills/security-audit/DESKTOP-MOBILE-AND-LOCAL-IPC.md
create mode 100644 .agents/skills/security-audit/HUNTING.md
create mode 100644 .agents/skills/security-audit/MEMORY-SAFETY-AND-BINARY.md
create mode 100644 .agents/skills/security-audit/PROTOCOLS-RPC-AND-MESSAGING.md
create mode 100644 .agents/skills/security-audit/RECONNAISSANCE.md
create mode 100644 .agents/skills/security-audit/RESOURCE-EXHAUSTION-AND-AVAILABILITY.md
create mode 100644 .agents/skills/security-audit/SKILL.md
create mode 100644 .agents/skills/security-audit/SUPPLY-CHAIN-AND-RELEASE.md
create mode 100644 .agents/skills/security-audit/VALIDATION-AND-REPORTING.md
create mode 100644 .agents/skills/security-audit/WEB-PROTOCOL-AND-AUTH.md
create mode 100644 .agents/skills/security-audit/report-schema.json
create mode 100644 .agents/skills/security-audit/validate-coverage-ledger.cjs
create mode 100644 .agents/skills/security-audit/validate-coverage-ledger.test.cjs
create mode 100644 .agents/skills/security-audit/validate-findings.cjs
create mode 100644 .agents/skills/security-audit/validate-findings.test.cjs
create mode 100644 .agents/skills/task-queue/SKILL.md
create mode 100644 .agents/skills/task-queue/scripts/notify.ps1
create mode 100644 .agents/skills/task-queue/scripts/watchdog.py
create mode 100644 AGENTS.md
create mode 100644 docs/LESSONS.md
create mode 100644 docs/MEMORY.md
create mode 100644 "docs/\345\274\200\345\217\221\346\265\201\347\250\213-\346\264\276\346\264\273\344\270\216\351\252\214\346\224\266\346\270\205\345\215\225.md"
create mode 100644 "docs/\347\273\217\351\252\214\346\200\273\347\273\223/20261117-2200-\345\271\266\350\241\214\345\274\200\345\217\221\344\270\216\345\255\220\344\273\243\347\220\206\345\215\217\344\275\234\346\226\271\346\263\225\350\256\272-\347\273\217\351\252\214\346\200\273\347\273\223.md"
create mode 100644 "docs/\350\247\204\350\214\203/git\344\270\216\345\244\232\344\273\223\346\223\215\344\275\234\351\205\215\346\226\271-\350\257\264\346\230\216\346\226\207\346\241\243.md"
create mode 100644 "docs/\350\247\204\350\214\203/\344\273\243\347\240\201\347\274\226\350\276\221\350\247\204\350\214\203-grep\344\274\230\345\205\210\350\257\273\345\217\226.md"
create mode 100644 "docs/\350\247\204\350\214\203/\345\215\217\344\275\234\345\201\217\345\245\275-\350\257\264\346\230\216\346\226\207\346\241\243.md"
create mode 100644 "docs/\350\247\204\350\214\203/\346\226\207\346\241\243\345\221\275\345\220\215\350\247\204\350\214\203-\350\257\264\346\230\216\346\226\207\346\241\243.md"
create mode 100644 "docs/\350\247\204\350\214\203/\347\274\226\347\240\201\344\270\216\351\252\214\346\224\266\346\240\207\345\207\206.md"
create mode 100644 "docs/\350\247\204\350\214\203/\350\256\260\345\277\206\347\262\276\347\256\200\350\247\204\350\214\203.md"
create mode 100644 "docs/\350\247\204\350\214\203/\350\256\276\350\256\241\350\247\204\350\214\203-\345\274\271\347\252\227\345\205\213\345\210\266\347\272\242\347\272\277.md"
diff --git a/.agents/skills/security-audit/AI-AND-LLM.md b/.agents/skills/security-audit/AI-AND-LLM.md
new file mode 100644
index 00000000..02ba9039
--- /dev/null
+++ b/.agents/skills/security-audit/AI-AND-LLM.md
@@ -0,0 +1,83 @@
+# AI, LLM, and Agent Hunting
+
+#### When to use this file
+
+Reach for this file when a language model participates in a trust-sensitive decision: chatbots and assistants, RAG pipelines, persistent agent memory, agent/tool-calling loops, MCP servers and clients, code that builds prompts from untrusted input, or code that consumes model output and acts on it. The important data flow is *untrusted content → model or memory → capability, authority, or sink*.
+
+Use this alongside `ATTACK-CLASSES.md`, not instead of it. Transport, access control, query construction, filesystem use, and output rendering remain ordinary trust boundaries. This file covers the model-specific delegation layer. Split large targets by retrieval, memory, tool dispatch, MCP, and output handling.
+
+## Core discipline (include in every agent prompt for this domain)
+
+```
+- Prompt injection alone is not a finding. Require a code-level boundary failure: content reaches another principal's context, invokes authority the requester lacks, discloses data they cannot read, or drives a sink they cannot reach directly.
+- Model output, memory, tool descriptions, and MCP responses are untrusted inputs. Point to the code that grants authority, trusts output, writes durable state, or feeds a sink.
+- A guardrail prompt is not a security boundary. Count only deterministic checks, resource-scoped authorization, isolation, binding, and constrained credentials.
+- State the attacker, affected principal, effective execution identity, resource, exact action, authority used, and observable impact. An intentional direct request to use the requester's existing authority is not a delegation defect merely because a model executes it.
+- Authorization and action binding are separate controls. Attacker-controlled content that causes an action under an affected principal's valid authority is an action-binding failure when that principal did not intentionally request or approve the exact action.
+- Classify every candidate as `confirmed` only after source evidence and bounded local validation establish the boundary and result. Use `needs_validation` when a required provider, deployment, model, renderer, or identity behavior is not observable locally.
+```
+
+## Context, retrieval, and memory attack classes (subagent_type: `general`)
+
+**Indirect injection through retrieved or ingested content**
+An attacker can write a RAG document, indexed page, file, email, issue body, tool response, or metadata that enters a different principal's model context. Trace who can write each source, how retrieval scopes it, whose session consumes it, and what capability is enabled there. Check isolation, resource authorization, and binding to the consuming principal's intent separately. The defect is a missing deterministic control, not persuasive text by itself.
+
+**Cross-session or cross-tenant context bleed**
+Conversation history, embeddings, retrieval results, or prompt caches are keyed too broadly. Verify tenant and ACL filters in the query itself and every cache key. A tenant field stored on an object is not enforcement if an alternate query, shared cache, or batch path omits it.
+
+**Persistent memory poisoning**
+Attacker-controlled content or model summaries are written into memory that later shapes another task, user, or privileged session. Review who may create, update, merge, and delete memory; its provenance and tenant scope; whether low-trust observations become durable instructions or facts; and whether retrieval distinguishes user preferences from tool policy. Memory intentionally saved by a user and used only for that user's intentional, allowed requests is not a cross-boundary finding.
+
+**Prompt role and provenance confusion**
+Prompt assembly lets untrusted text impersonate a system message, prior turn, tool result, policy, or memory record. Look for string concatenation, untyped history, caller-controlled role fields, and serialization round trips that lose source labels. Confirm that the forged provenance changes a deterministic trust decision or reaches a meaningful capability.
+
+## Tool and action attack classes (subagent_type: `general`)
+
+**Tool-argument injection into a downstream sink**
+Model-produced arguments reach SQL, shell, file, URL-fetch, or privileged APIs without handler-side validation. Treat the tool schema as input parsing, then follow each field from decoded call to sink. Structured output narrows shape; it does not establish authorization, safe paths, safe URLs, or query semantics.
+
+**Excessive agency and confused-deputy authority**
+The agent uses a service identity or broad credential, while the tool handler does not re-check the requesting principal's permission on the named resource. Verify both the effective identity and whether the caller could perform that exact operation through the normal product interface. A shared credential with enforced per-user query scope is not a defect.
+
+**Action-confirmation and approval binding**
+A user approves one described action but execution can use changed arguments, a different resource, a different principal, or a later model turn. An action-binding defect also exists when attacker-controlled content causes a side effect under a victim's valid authority without the victim's intentional request or approval, even if generic authorization permits the victim to perform it. Review whether intent or confirmation binds the normalized tool name, complete argument object, requester, target, amount, expiry, and batch membership. Check retries and resumed sessions: an approval must not authorize a mutated or duplicate side effect.
+
+**Tool-schema and dispatcher disagreement**
+The schema accepts aliases, extra fields, duplicate keys, coercions, nested free-form objects, or out-of-range values that the dispatcher or handler interprets differently. Compare schema validation, canonicalization, generated bindings, and handler defaults. Validate again where values become resource selectors or security-relevant options.
+
+**Unbounded delegated action loops**
+A bounded request can enqueue repeated spend, send, mutation, or external API work without a per-request budget, per-action authorization, cancellation, or idempotency control. Confirm impact on shared cost, quotas, other users, or durable state. Do not test by exhausting a service; use code-level accounting and a locally bounded loop.
+
+## MCP and sub-agent trust classes (subagent_type: `general`)
+
+**Sub-agent and MCP trust inheritance**
+A delegated task receives the full session, credentials, memory, or capabilities rather than the least authority required. Check the principal and tenant carried into each call, capability narrowing, credential audience, and whether delegated results are treated as untrusted on return.
+
+**MCP server and tool identity confusion**
+Calls or results are routed by attacker-influenceable server names, tool names, request IDs, resource URIs, or model-selected aliases rather than the authenticated connection and outstanding request. Check whether two servers can claim the same tool or resource identity, whether reconnect changes the binding, and whether a response from one server can satisfy another server's pending call.
+
+**MCP metadata and schema as policy**
+Tool descriptions, resource metadata, prompts, completion hints, or schemas supplied by an MCP peer are trusted as policy or authorization. These fields can guide the model but cannot grant capability. Find the deterministic allowlist, server identity check, and handler authorization that remain authoritative when metadata conflicts.
+
+## Output and disclosure attack classes (subagent_type: `general`)
+
+**Insecure output rendering**
+Model output reaches an executing HTML, Markdown, template, URL, or command sink without the sink's required encoding and policy. For browser rendering, verify auto-loaded resources and CSP or sanitization in `CLIENT-SIDE.md`; renderer behavior outside the repository makes the candidate `needs_validation`.
+
+**Sensitive context extraction**
+The assembled context contains credentials, another user's data, private source, or policy values that themselves grant access, and user-influenced output exposes them. Read prompt assembly and data-fetch code. Disclosure of generic instructions or behavior that does not cross a data boundary is not a finding.
+
+## Universal moves (apply across the above)
+
+- Draw four maps first: each execution identity, each capability, every writable context or memory source, and each output destination. Then connect the principal at the start to the authority at the end.
+- Start at side-effecting tools and work backward through dispatcher, schema, confirmation, model context, retrieval, and ingestion. Start at durable memory reads and trace every writer.
+- Compare direct, queued, retry, resume, batch, and delegated paths for the same action. The strongest gate must apply after arguments are final and before every side effect.
+
+## Validation rules (apply before reporting ANY finding here)
+
+1. Name the crossed boundary and observable result: attacker, affected principal or shared resource, execution identity, target, and unauthorized or unrequested action or disclosure.
+2. For confused-deputy authority claims, prove the tool lacks requester-and-resource authorization and that the attacker cannot perform the same action normally. For action-binding claims, instead prove attacker-controlled content caused an action under the affected principal's authority that the principal did not intentionally request or approve. Valid generic authorization does not establish that intent.
+3. For memory or retrieval claims, cite both the attacker-controlled write and the later cross-principal read or privileged decision. A shared record without a reachable consumer is not enough.
+4. For action binding, establish the intentional request or normalized approved object, if any, and compare it with the object the handler uses. Confirm a locally observable unrequested action, mutation, duplicate, or authority change without extending the test into harmful execution. For schema disagreement, compare the normalized validated object with the handler's object.
+5. For MCP identity claims, verify the authenticated connection, request correlation, tool namespace, and effective credential. Mark `needs_validation` if external server identity or deployment routing is required.
+6. Return `confirmed` findings only with a complete source trace and meaningful result. Return `needs_validation` for a specific unresolved boundary fact and state the bounded local or owner-observed check needed to resolve it.
diff --git a/.agents/skills/security-audit/ATTACK-CLASSES.md b/.agents/skills/security-audit/ATTACK-CLASSES.md
new file mode 100644
index 00000000..18a2beb4
--- /dev/null
+++ b/.agents/skills/security-audit/ATTACK-CLASSES.md
@@ -0,0 +1,130 @@
+# Attack Classes
+
+#### Attack classes — choose and split based on Phase 1
+
+Select attack classes relevant to the application type. Not every class applies to every codebase. The list below is a starting point; add application-specific classes from Phase 1 and split large codebases per subsystem. Frame work as finding, validating, fixing, and prioritizing vulnerabilities. Keep validation to source review and bounded local fixtures; do not develop payload chains, test availability on live services, or take action in shared environments.
+
+Use `confirmed` only when source evidence and bounded validation establish the full boundary and meaningful result. Use `needs_validation` when a specific deployment, provider, platform, identity, or runtime fact is unavailable; state the missing fact and the safe owner-observed or local check that resolves it.
+
+> **Native / binary / kernel targets** (C/C++/Rust-unsafe, kernel modules, parsers and decoders, FFI, concurrent runtimes, binary loaders, JITs, firmware): use the memory-safety, integer/ABI, concurrency, binary-loader, and privileged-interface classes in [MEMORY-SAFETY-AND-BINARY.md](MEMORY-SAFETY-AND-BINARY.md).
+>
+> **AI / LLM / agent targets** (chatbots, RAG, persistent memory, tool-calling agents, MCP servers/clients, prompt assembly, or model-controlled actions): use the context, memory-poisoning, action-binding, tool-schema, MCP-identity, and output classes in [AI-AND-LLM.md](AI-AND-LLM.md).
+>
+> **HTTP, web, and identity targets** (ordinary web apps, APIs, reverse proxies, CDNs, gateways, custom HTTP parsers, sessions, CSRF, JWT, OAuth/OIDC, SAML, MFA, passkeys, account recovery/linking, API keys, or mTLS): use [WEB-PROTOCOL-AND-AUTH.md](WEB-PROTOCOL-AND-AUTH.md).
+>
+> **Client-side and browser targets** (SPAs, browser extensions, embedded webviews, service workers, browser storage, cross-window messaging, CORS, WebSockets, or DOM rendering): use [CLIENT-SIDE.md](CLIENT-SIDE.md).
+>
+> **Supply-chain and release targets** (dependency resolution, generated inputs, CI, release/signing/promotion, updates, plugins, or extensions): use [SUPPLY-CHAIN-AND-RELEASE.md](SUPPLY-CHAIN-AND-RELEASE.md).
+>
+> **Cloud and deployment targets** (IAM, infrastructure as code, containers/Kubernetes, service mesh, serverless/edge, ingress, provider events, or runtime configuration): use [CLOUD-AND-DEPLOYMENT.md](CLOUD-AND-DEPLOYMENT.md).
+>
+> **Protocol, RPC, and messaging targets** (gRPC, GraphQL transports, Protobuf/Cap'n Proto/Thrift, custom protocols, queues, brokers, pub/sub, webhooks, or streaming RPC): use [PROTOCOLS-RPC-AND-MESSAGING.md](PROTOCOLS-RPC-AND-MESSAGING.md).
+>
+> **Resource-exhaustion and availability targets** (untrusted work can consume shared CPU, memory, disk, connections, workers, queues, quotas, or operator-owned spend): use [RESOURCE-EXHAUSTION-AND-AVAILABILITY.md](RESOURCE-EXHAUSTION-AND-AVAILABILITY.md).
+>
+> **Data-isolation and lifecycle targets** (multi-tenant stores, caches/search, object links, analytics, export/backup, migration, deletion, retention, or restore): use [DATA-ISOLATION-AND-LIFECYCLE.md](DATA-ISOLATION-AND-LIFECYCLE.md).
+>
+> **Desktop, mobile, and local-IPC targets** (native apps, deep links, webview bridges, exported components, privileged helpers, local daemons, Unix sockets/XPC/Binder/D-Bus): use [DESKTOP-MOBILE-AND-LOCAL-IPC.md](DESKTOP-MOBILE-AND-LOCAL-IPC.md).
+
+**Injection** (subagent_type: `general`)
+Trace untrusted input from entry point to dangerous sink. What counts as a "dangerous sink" depends on the application:
+- Web apps: SQL queries, HTML output, shell commands, template engines, file paths, HTTP redirects, deserialization
+- Libraries: any function that processes caller-supplied data without validation — buffer operations, parsers, format strings
+- CLI tools: shell command construction, file path handling, environment variable interpolation
+- Services: query construction, message serialization, log injection, LDAP/XPATH queries
+- Client-side (browser/JS): DOM XSS, prototype pollution, `postMessage`/origin trust, and other browser-side classes — covered by the [CLIENT-SIDE.md](CLIENT-SIDE.md) companion blocks when selected
+
+Do not stop at the obvious direct paths. Look for indirect injection: data stored safely, then retrieved and used in a dangerous context by different code. Look for injection through field names, keys, headers, and metadata — not just values. Look for injection into secondary systems (logs, caches, search indexes, analytics).
+
+**Access control** (subagent_type: `general`)
+Verify that a caller cannot do something outside its authority. Go beyond checking whether permission checks exist — verify they check the *right* permission for the *right* resource via the *right* mechanism:
+- Is there a path to the same state change that checks a different (weaker) permission?
+- Can a field in the request body override what the permission system intended to restrict?
+- Are there endpoints that gate on authentication but forget authorization?
+- Does the same resource have multiple access paths with inconsistent checks?
+- What about bulk/batch/export/import operations — do they enforce per-item permissions?
+
+For complex access models, split into separate agents for auth bypass vs authorization logic.
+
+**Resource and file handling** (subagent_type: `general`)
+- Path traversal (reading/writing outside intended directories) — including through symlinks, encoded sequences, and null bytes
+- SSRF (making the application fetch attacker-controlled URLs) — including through redirects, DNS rebinding, and URL parser differentials
+- Unsafe deserialization, archive extraction (zip slip), temp file handling
+- Memory safety (if applicable): buffer overflows, use-after-free, integer overflow
+- Race conditions on file operations (TOCTOU between check and use)
+
+**Cryptography and secrets** (subagent_type: `general`)
+- Weak randomness for security-critical values (tokens, keys, nonces)
+- Hardcoded secrets, secrets in logs, error messages, URLs, or client-visible responses
+- Broken key derivation, missing HMAC verification, nonce reuse
+- Timing side-channels on secret comparison
+- Misuse of crypto primitives (ECB mode, unauthenticated encryption, static IVs, etc.)
+- What happens when crypto operations fail? Does the error path fall back to no-crypto?
+
+**Business logic** (subagent_type: `general`)
+Hunt logic errors by hand: standard scanners cannot find them, and they yield high-impact findings. For each major workflow:
+- **State machine violations**: Can you skip steps? Go backwards? Reach an invalid state? What happens if you replay a completed flow? What about partial failure — if step 2 of 3 fails, is step 1 rolled back?
+- **Race conditions with business impact**: Concurrent operations that produce invalid states (double-spend, double-approve, lost updates). Focus on operations that check-then-act non-atomically.
+- **Numeric/quantity manipulation**: Negative values, zero values, overflow, precision loss, type coercion between string and number.
+- **Access boundary violations**: Not "does the permission check exist" but "is it the right check for the business rule?" Can input to one operation bypass a restriction enforced on a different operation for the same effect?
+- **Implicit trust assumptions**: Data from storage, config, other components, or plugins assumed safe because "we validated it on the way in." What if a different code path wrote it?
+- **Time-based logic**: Expiry checks, scheduling, rate windows, clock skew. What happens at exact boundary moments? What about timezone differences between components?
+- **Default and fallback behavior**: What is the security posture when config is missing? When a feature flag is off? When a dependency is unavailable? When the system is mid-migration?
+
+**Feature abuse and data leakage** (subagent_type: `general`)
+Legitimate features used for unintended purposes. Look for bugs in the design, not only in the code:
+- **Export/backup as exfiltration**: Can a low-privilege user trigger an export, snapshot, or backup that includes data above their access level? Can they export other users' data? Does the export include deleted/draft/private content? Revision history that was supposed to be pruned?
+- **Import/restore as injection**: Can import overwrite existing data? Can it create records that bypass normal validation? Can it inject content into collections the user has no write access to? Does it respect the same permission model as the UI?
+- **Search/filter/sort as oracle**: Can search queries reveal whether content exists that the user cannot directly access? Do filter parameters let users probe statuses, roles, or fields they should not know about? Does sorting by a hidden field reveal its values through result ordering?
+- **Enumeration through side effects**: Do error messages differ between "does not exist" and "no access"? Do response times differ? Response sizes? HTTP status codes? Can you enumerate users through password reset, invite, or registration flows?
+- **Preview/draft/staging leakage**: Are preview tokens scoped to one item or do they unlock broader access? Can draft content be discovered through search, RSS feeds, sitemaps, or API listing endpoints? Can cache headers cause a CDN to serve private content publicly?
+- **Notification/webhook as SSRF**: Can a user set a notification URL, webhook URL, or callback URL that the server fetches? Is it validated against internal networks? What about after a redirect?
+
+**Chained vulnerabilities and trust boundaries** (subagent_type: `general`)
+Individually allowed or contained behavior can become a vulnerability when another component or lifecycle step relies on a stronger guarantee:
+- **Multi-step boundary failures**: Map what a low-privilege principal may read, write, invoke, and retain, then connect only concrete outputs to later trust decisions. Confirm each prerequisite and do not assume a downstream effect.
+- **Cross-component trust gaps**: Component A validates input and passes it to component B. Compare the exact guarantee A produces with what B assumes, including truncation, type coercion, normalization, tenant scope, and plugin/extension access.
+- **Second-order use**: Data safe when stored may become dangerous in a later context. A field name becomes a JSON path, a slug becomes a file path, escaped text enters raw rendering, or a stored string becomes a URL, regex, template, or policy expression.
+- **Scope and capability growth**: Token, API-key, plugin, OAuth, MCP, or AI capabilities become broader after delegation, refresh, caching, role change, or composition. Name the concrete operation the resulting principal should not have.
+- **Timing and ordering**: Review setup, migration, soft-delete, revoke/cache expiry, check/use, and validate/consume windows. Confirm stale state is accepted before reporting.
+- **Rollback and recovery**: Undelete, restore, revision rollback, and cancellation must apply current ownership, validation, and authorization. Confirm which invalid state is restored.
+
+**Wildcard** (subagent_type: `general`)
+You are not given a category. Find vulnerabilities outside the standard classes already assigned.
+
+Read code that looks boring or disconnected from security. Follow incomplete, experimental, compatibility, and fallback features, but retain the same concrete boundary and validation requirements as every other class.
+
+Use these starting points, but do not limit yourself to them:
+- What is the strangest code in the codebase? Why does it exist? What happens if it is abused?
+- Are there any features that feel half-finished, experimental, or bolted on? Those have the weakest security because they got the least review.
+- What happens if you use the API in a way the frontend never would? The UI constrains users, but the API does not. What API calls are possible but never made by the client?
+- Are there any hidden or undocumented endpoints, parameters, headers, or features? Look at route registrations, middleware, and config for things that are not in the docs.
+- What happens when you mix features that were not designed to work together? Localization + preview + caching. Import + plugins + webhooks. OAuth + impersonation + API keys.
+- Is there anything interesting in the git history? Reverted security fixes, commented-out auth checks, secrets that were committed then removed (still in history).
+- Which valid-account actions affect other users, shared integrity, availability, or operator-owned cost? Verify containment, quotas, authorization, and recovery around those actions.
+- Which operations are irreversible or require elevated confirmation? Bind authorization and approval to the final principal, action, and resource.
+- What assumptions does the code make about the environment? That the database is local, that the clock is accurate, that DNS is trustworthy, that the filesystem is case-sensitive?
+- Look at the test files — what are they **not** testing? Compare the edge cases the developer thought about (tests exist) with the ones they did not (no tests).
+
+Pursue anomalies inside your assigned scope until the invariant is settled. If something looks strange, read it until you can state whether it is safe. If a function has a comment explaining why it is safe, verify the explanation. If a variable is named `temp` or `hack` or `legacy`, read it closely.
+
+**Obvious things** (subagent_type: `general`)
+Other agents hunt subtle bugs. This agent checks the basic exposures that are easy to overlook because everyone assumes someone else already checked them:
+- Are there any hardcoded passwords, API keys, tokens, or secrets in the source? (grep for `password`, `secret`, `apikey`, `token`, `Bearer`, `-----BEGIN`, common default passwords)
+- Are there any TODO/FIXME/HACK/XXX comments that reference security? (`TODO: add auth`, `FIXME: validate input`, `HACK: skip permission check`)
+- Is debug mode / dev mode properly gated? Can it be enabled in production via environment variable, query parameter, or header?
+- Are there test/example/seed credentials that work in production?
+- Is there a `/debug`, `/admin`, `/test`, `/status`, `/health`, `/metrics`, `/env`, `/.env`, `/config` endpoint that is unprotected?
+- Are there any `.env`, `.env.local`, `credentials.json`, `*.pem`, `*.key` files checked into the repo?
+- Does the `.gitignore` actually cover secrets, uploads, and local config?
+- Are dependencies pinned? Are there known CVEs in the dependency tree? (check lockfiles)
+- Are there any `eval()`, `exec()`, `child_process`, `Function()`, `vm.runInContext`, `import()` with dynamic input?
+- Are CORS headers set to `*` or overly permissive? Is `Access-Control-Allow-Credentials` combined with a wildcard origin?
+- Are cookies missing `HttpOnly`, `Secure`, or `SameSite` attributes?
+- Are there any open redirects? (parameters named `redirect`, `return`, `next`, `url`, `goto`, `continue` that feed into redirects without validation)
+- Is TLS enforced? Are there any HTTP-only endpoints?
+- Are error responses in production returning stack traces, internal paths, or SQL errors?
+
+This agent does not need to be creative. It needs to be thorough and literal. Check every item. Report each result.
+
+**Important**: For any finding this agent reports, it must verify the full code path, not just surface appearance. If a cookie is missing `HttpOnly`, check whether the cookie contains security-sensitive data and whether JS needs to read it by design. If an error message contains a field name, check whether the field is ever actually populated with sensitive data. A flag is not a finding — trace the impact before reporting.
diff --git a/.agents/skills/security-audit/CLIENT-SIDE.md b/.agents/skills/security-audit/CLIENT-SIDE.md
new file mode 100644
index 00000000..8ba673e9
--- /dev/null
+++ b/.agents/skills/security-audit/CLIENT-SIDE.md
@@ -0,0 +1,83 @@
+# Client-Side and Browser Hunting
+
+#### When to use this file
+
+Reach for this file when meaningful trust decisions or untrusted rendering happen in a browser: single-page apps, browser extensions, embedded webviews, service workers, offline applications, and code that renders attacker-influenceable content into the DOM, receives cross-window messages, or uses browser storage. These paths include sources the server never sees, such as URL fragments, `window.name`, `postMessage`, and previously cached content.
+
+Use alongside `ATTACK-CLASSES.md`. This file covers browser sources and sinks, origin boundaries, browser persistence, and cross-site state oracles. Use `DESKTOP-MOBILE-AND-LOCAL-IPC.md` for the native side of a webview bridge, and `WEB-PROTOCOL-AND-AUTH.md` for server-side CSRF, sessions, and auth callbacks.
+
+## Core discipline (include in every agent prompt for this domain)
+
+```
+- A client-side candidate needs a controllable source and an executing or disclosing sink. Name both and show attacker-influenced data reaching the sink.
+- The impact must reach a victim's session, another origin, or shared persistence. Self-injection and disclosure of the attacker's own data are not findings.
+- Framework escaping, browser same-origin policy, CSP, COOP/CORP, service-worker scope, and modern noopener defaults are real controls. Verify them before assigning impact.
+- Browser storage and caches are shared by origin and may outlive login state. Identify who writes, who reads, and which account, tenant, or worker lifecycle clears each record.
+- Use `confirmed` only for complete source evidence plus bounded local browser tests. Use `needs_validation` when renderer, extension permission, deployed header, or browser-policy behavior is required but unavailable.
+```
+
+## DOM and object-state attack classes (subagent_type: `general`)
+
+**DOM-based XSS**
+Trace `location` fields, `document.referrer`, `window.name`, message data, storage, and browser-controlled document state into `innerHTML`, `outerHTML`, `document.write`, string-evaluating APIs, executable URLs, jQuery HTML APIs, or framework escape hatches. Interpolation escaped by the framework is not a finding.
+
+**DOM clobbering**
+Attacker-injected `id` or `name` attributes shadow a global, form property, configuration object, or initialization flag later trusted by code. Require both a markup path that preserves the attribute and a security-relevant use of the clobbered value.
+
+**Prototype pollution and gadget chain**
+An attacker-controlled key reaches a recursive write such as deep merge or path assignment and modifies prototype state. Then a reachable gadget consumes the polluted property to change authorization, execution, navigation, or rendering. `JSON.parse`, a shallow copy, or pollution without a gadget is not enough.
+
+## Cross-origin messaging and network attack classes (subagent_type: `general`)
+
+**`postMessage` origin and source trust**
+A handler performs a sensitive action with `event.data` without an exact origin allowlist and, where multiple frames share an origin, the expected `event.source`. On the send side, sensitive data sent to `*` reaches an unintended embedder. Weak substring, prefix, suffix, or unanchored-regex origin matching is not an origin check.
+
+**Cross-site WebSocket request use**
+A WebSocket upgrade accepts ambient cookies from an untrusted origin without an `Origin` check or channel-specific token, allowing the victim's session to read or mutate data. Confirm both the upgrade behavior and a security-relevant message handler.
+
+**Credentialed CORS trust**
+The server reflects or weakly matches `Origin` while allowing credentials and returns sensitive responses. A bare wildcard with credentials is rejected by browsers; report only the actual reflected/allowed origin path and cross-origin data or mutation.
+
+## Service-worker and browser-storage attack classes (subagent_type: `general`)
+
+**Service-worker registration and scope takeover**
+Attacker-influenceable content can become the registered worker script, control a path that receives an over-broad `Service-Worker-Allowed` scope, or alter update imports without integrity control. Verify the final script URL, response MIME type, origin, scope, and who controls every imported script. A normal same-origin worker with intended scope is not a defect.
+
+**Service-worker cache and identity confusion**
+The worker caches personalized responses without including account, tenant, authorization state, or request mode in its policy, then serves them after account switch or logout. Review fetch-event routing, cache names and keys, navigation fallbacks, cache cleanup, and whether error/offline paths return another user's prior response.
+
+**Browser-storage disclosure and stale authorization**
+Tokens, private responses, draft data, or authorization decisions remain in `localStorage`, `sessionStorage`, IndexedDB, Cache Storage, extension storage, or client state and become readable by another account or less-trusted same-origin component. Storage of a token alone is not a finding; require a realistic reader with less authority, or continued use after revocation/logout.
+
+**Cross-context storage and broadcast confusion**
+`storage` events, `BroadcastChannel`, shared workers, or origin-wide caches carry identity or commands between tabs without binding them to the current session. Check account switching, private/public windows, tenant changes, and stale tabs that can overwrite newer auth state.
+
+## Cross-site information leak classes (subagent_type: `general`)
+
+**XS-Leaks and cross-origin state oracles**
+An attacker page can distinguish protected cross-origin state through resource load/error events, frame or window state, redirect behavior, timing, cache state, or response size while the browser attaches victim credentials. Require one concrete secret-bearing predicate such as whether a private object, role, or account exists. Generic timing variance or public-resource availability is not a finding.
+
+**Window and opener state disclosure**
+A cross-origin window's permitted metadata or navigation result reveals protected state, or a retained opener/named-window relationship lets an attacker-controlled page influence a privileged navigation. Check COOP, frame protections, `noopener`, exact origin, and whether the observable state is confidential.
+
+## UI-redress and navigation attack classes (subagent_type: `general`)
+
+**Clickjacking**
+A framed, state-changing action lacks effective `frame-ancestors`, `X-Frame-Options`, or equivalent UI isolation. Require the sensitive action and confirm it can complete in the framed state; missing headers on read-only content are hardening notes.
+
+**Client-side navigation confusion**
+A client source controls redirect or navigation without scheme and destination policy, including executable `javascript:` or `data:` destinations. Reverse tabnabbing applies only where code explicitly keeps `window.opener`, uses `window.open` without isolation, or supports a browser without implicit `noopener`.
+
+## Universal moves (apply across the above)
+
+- Start from DOM, navigation, worker, message, and storage sinks, then trace backward to browser-only and server-controlled sources. Record the browser policy that should stop the path.
+- Test account switch, logout, worker update, offline fallback, and stale-tab state with a local test origin and dummy accounts. Do not use production users, origins, or shared services.
+- For XS-Leaks, list only predicates proved by source and local browser behavior. Then identify the response headers or rendering choice that would remove the oracle.
+
+## Validation rules (apply before reporting ANY finding here)
+
+1. Cite the source, sink, browser policy, affected origin/session, and observable mutation or disclosure.
+2. For prototype pollution, prove the recursive write and a security-relevant gadget. For DOM clobbering, prove the markup survives and the shadowed value is used.
+3. For service workers and storage, prove lifecycle reachability: an attacker-controlled write or cache entry must reach a different account, tenant, or later authorization state.
+4. For messaging, CORS, WebSocket, and XS-Leaks, show exact origin/source validation and the protected state or action exposed. Confirm that CSP, COOP/CORP, cookies, and SameSite policy do not already block it.
+5. Return `confirmed` findings only with a complete client path and bounded local evidence. Return `needs_validation` with the precise deployed header, extension permission, browser version, or renderer behavior an owner must verify.
diff --git a/.agents/skills/security-audit/CLOUD-AND-DEPLOYMENT.md b/.agents/skills/security-audit/CLOUD-AND-DEPLOYMENT.md
new file mode 100644
index 00000000..5569f76c
--- /dev/null
+++ b/.agents/skills/security-audit/CLOUD-AND-DEPLOYMENT.md
@@ -0,0 +1,86 @@
+# Cloud and Deployment Hunting
+
+#### When to use this file
+
+Reach for this file when the repository defines cloud identity, infrastructure, containers, Kubernetes, service mesh, serverless functions, edge workers, ingress, object storage, managed services, or environment-specific configuration. This domain asks whether deployed components receive the intended identity, isolation, network reachability, secrets, and policy. Source often expresses intent rather than live fact, so separate source-confirmed defects from deployment validation needs.
+
+Use `SUPPLY-CHAIN-AND-RELEASE.md` for build and promotion trust, `WEB-PROTOCOL-AND-AUTH.md` for HTTP proxy semantics, and `DATA-ISOLATION-AND-LIFECYCLE.md` for data-store tenant scope.
+
+## Core discipline (include in every agent prompt for this domain)
+
+```
+- Do not infer a live exposure from a manifest alone. Establish which environment consumes it, what defaults or overlays modify it, and whether the source path is active.
+- Map each workload's identity to specific operations and resources. Broad policy is a finding only when lower-trust input can reach an unauthorized action.
+- Ingress, proxies, service mesh, metadata services, and admission policy are real boundaries, but only count a control when its configuration and attachment are visible.
+- Secret references are not secret disclosure. Require a lower-trust reader, output, artifact, log path, or unsafe fallback.
+- Use `confirmed` for active in-repo configurations and local rendering/policy validation. Use `needs_validation` for account policy, network attachment, runtime admission, hosted metadata, or drift that needs owner observation.
+```
+
+## Workload identity and IAM attack classes (subagent_type: `general`)
+
+**Workload identity overreach**
+A workload, pod, function, edge worker, or node identity can act on tenants, accounts, resources, or APIs beyond its role, and untrusted request or job input selects that target. Review cloud policy conditions, resource patterns, service-account attachment, namespace mapping, and fallback credentials.
+
+**Cross-account or cross-tenant role confusion**
+Role assumption, external IDs, token exchange, workload federation, or resource policies accept identity claims not bound to the intended source account, audience, repository, namespace, or workload. Establish both trust policy and caller-controlled claim.
+
+**Application authorization delegated to cloud metadata**
+An app trusts caller-supplied identity headers, tags, labels, account IDs, or resource metadata without verifying they came from the cloud control plane or a trusted proxy. Cloud IAM and application authorization are separate checks.
+
+## Ingress, network, and control-plane attack classes (subagent_type: `general`)
+
+**Unexpected service or management-plane reachability**
+An ingress, service, listener, security group, load-balancer annotation, port mapping, or server bind exposes an admin, debug, metrics, node, control-plane, or internal API to a lower-trust network. Missing network controls alone are `needs_validation`; a repository-controlled public route to a sensitive handler can be `confirmed`.
+
+**Trusted-proxy and mesh identity bypass**
+A backend accepts forwarded identity, mTLS subject, or authorization metadata from peers outside the intended ingress/sidecar, or an alternate port and health/legacy path bypasses the mesh. Verify header stripping, peer reachability, and fail-open behavior when the proxy is absent.
+
+**Metadata and internal-service reachability**
+An untrusted URL, destination, or protocol selection reaches instance/container metadata, control-plane sockets, or internal APIs with workload credentials. Trace URL parsing and redirect handling under `ATTACK-CLASSES.md`; here establish deployed network, metadata-version, and identity boundaries.
+
+## Container and orchestration attack classes (subagent_type: `general`)
+
+**Host or control-plane capability exposure**
+A lower-trust workload can select privileged mode, capabilities, host namespaces, host paths, device mounts, container runtime sockets, or service-account tokens that cross into node/control-plane authority. Bare absence of seccomp or read-only filesystem is hardening unless a reachable operation crosses that boundary.
+
+**Admission and policy path inconsistency**
+One deployment route enforces image identity, namespace, resource, secret, or privilege policy while another controller, job, upgrade, restore, or compatibility path does not. Confirm the alternate route and resulting deployed object.
+
+**Namespace and label trust confusion**
+Network, admission, secret, or workload-identity policy relies on labels, annotations, names, or namespaces that a less-trusted principal can set. Compare who controls selectors with what authority matching grants.
+
+## Configuration and secret lifecycle attack classes (subagent_type: `general`)
+
+**Security-control precedence drift**
+Development values, chart defaults, environment variables, command-line flags, feature gates, sidecar injection, or per-region overlays disable authentication, transport security, tenant scoping, or audit policy in a deployed environment. Render the final configuration for each maintained deployment, not just the base file.
+
+**Secret exposure across workload boundaries**
+Secrets enter logs, crash reports, process arguments, shared environment, broad volumes, build outputs, service discovery, or read APIs accessible to another workload or tenant. Check secret type and authority; a public endpoint or key ID is not a credential.
+
+**Credential renewal and outage fallback**
+Failure to mount, refresh, rotate, or revoke a workload credential causes stale credentials to remain active or an app to accept a less trusted identity mode. Review startup, readiness, reconnect, and cached-client behavior.
+
+## Managed storage, events, and edge attack classes (subagent_type: `general`)
+
+**Object and signed-URL policy confusion**
+Bucket/container policy, object keys, CDN origins, or signed URLs fail to bind principal, operation, object namespace, audience, or expiry. Review list/version operations and write paths as well as reads.
+
+**Event-source identity confusion**
+A function or worker trusts event body fields as source identity without validating provider-signed envelope, subscription/topic, account, region, and replay state. Compare push, pull, retry, and dead-letter paths.
+
+**Edge/runtime boundary mismatch**
+An edge or serverless runtime assumes a secret, API, filesystem, isolation, or tenant policy that differs from the origin runtime, and fallback to origin changes authority or cache behavior. Confirm which configuration selects each path.
+
+## Universal moves (apply across the above)
+
+- Render every maintained environment and make a matrix of external port, workload identity, network peers, mounted secrets, and cloud resources. Differences require an owner or policy explanation.
+- Follow a lower-trust request, object, label, or event into cloud policy. Show which workload credential performs the final operation and what condition should scope it.
+- Diff normal deploy, migration, restore, node maintenance, failover, and local/emulator paths. Review behavior when mesh, admission, identity, secret, or policy service is unavailable.
+
+## Validation rules (apply before reporting ANY finding here)
+
+1. Establish the active source path and effective deployment object; otherwise use `needs_validation` and state which rendered manifest or owner-observed attachment is missing.
+2. Name the lower-trust caller/workload, cloud or application identity, controllable selector, affected resource, and unauthorized operation or disclosure.
+3. Verify provider and orchestrator defaults at the pinned version. Do not assume a public IP, reachable metadata service, permissive firewall, or absent admission attachment.
+4. Local validation may render templates, evaluate policy, inspect container/user namespaces in an isolated fixture, or run an emulator with dummy identities. Do not probe live endpoints or alter shared cloud resources.
+5. Return `confirmed` only with a complete active source trace and concrete boundary result. Return `needs_validation` with the exact deployed policy, identity attachment, overlay, network, or drift observation needed.
diff --git a/.agents/skills/security-audit/DATA-ISOLATION-AND-LIFECYCLE.md b/.agents/skills/security-audit/DATA-ISOLATION-AND-LIFECYCLE.md
new file mode 100644
index 00000000..0cba1fa4
--- /dev/null
+++ b/.agents/skills/security-audit/DATA-ISOLATION-AND-LIFECYCLE.md
@@ -0,0 +1,84 @@
+# Data Isolation and Lifecycle Hunting
+
+#### When to use this file
+
+Reach for this file when the target stores multi-tenant or access-controlled data, derives search/index/cache/analytics copies, issues object links, exports or restores records, migrates schemas, or promises deletion, revocation, and retention behavior. This domain follows one data item through every copy and state transition. Use `ATTACK-CLASSES.md` for endpoint-level access control and `CLOUD-AND-DEPLOYMENT.md` for provider-level storage policy.
+
+Split large targets by primary storage, cache/search, object/blob storage, analytics/logging, export/backup, deletion/revocation, and migration.
+
+## Core discipline (include in every agent prompt for this domain)
+
+```
+- A tenant or owner field on a record is not isolation. Find the query, key, path, policy, or row-level control that enforces it for each read and write path.
+- Trace derived copies. Sanitized primary data can become unsafe in search, cache, analytics, export, previews, logs, replicas, and backups with different ACL and retention rules.
+- Deletion and revocation are lifecycle contracts. Check current, historical, cached, indexed, exported, restored, and queued copies within the product's stated boundary.
+- Privacy or retention preference is not automatically a security vulnerability. Require an explicit data-access boundary or deletion/revocation guarantee and an unauthorized reader or later operation.
+- Use `confirmed` for complete source-visible lineage and bounded dummy-tenant tests. Use `needs_validation` when external storage policy, retention, CDN behavior, replica lag, or backup access is unavailable.
+```
+
+## Tenant and object-isolation attack classes (subagent_type: `general`)
+
+**Missing tenant or owner enforcement**
+A read, update, delete, list, count, or bulk query identifies an object without binding it to the authenticated tenant/owner, or trusts body fields to supply that identity. Compare direct lookup, nested relationship, background, admin, import, and legacy paths.
+
+**Composite-key and namespace collision**
+Cache keys, object paths, database uniqueness, search document IDs, temporary files, or deduplication keys omit tenant or environment. Two principals can overwrite or retrieve the same logical key even though application records carry separate owners.
+
+**Policy and query disagreement**
+Row-level policy, ORM default scopes, authorization filters, and raw/bypass clients apply different predicates. Check joins, aggregates, aliases, views, transactions, `unscoped` or service clients, and error paths where context is missing.
+
+**Blob and signed-reference overreach**
+Object keys, attachment IDs, version IDs, shared links, or signed URLs permit operations or namespaces beyond the issuing principal's access, or remain valid after the underlying ACL changes. Bind operation, exact object/version, audience, expiry, and tenant.
+
+## Derived-data and disclosure attack classes (subagent_type: `general`)
+
+**Search, cache, and index ACL drift**
+A primary record's ACL or lifecycle changes without invalidating a searchable, cached, embedded, thumbnail, RSS, preview, or index copy. Validate filtering at retrieval time as well as document ingestion and invalidation.
+
+**Analytics, logs, traces, and diagnostics as alternate readers**
+Private content or credentials are emitted into systems with broader access, longer retention, or tenant mixing. Confirm the data class and realistic reader; field names, public identifiers, and operator-only content under intended policy are not enough.
+
+**Enumeration and aggregate oracles**
+Counts, filters, ordering, errors, unique constraints, timings, notification behavior, or existence checks disclose protected object or account state. Require a concrete confidential predicate and observable distinction, not general response variance.
+
+## Export, backup, restore, and migration attack classes (subagent_type: `general`)
+
+**Export and backup scope expansion**
+An export, snapshot, portability package, report, or backup includes other tenants, inaccessible object fields, soft-deleted data, secret values, or history above the requester's access. Check per-item authorization after selection and authorization to download the final artifact.
+
+**Import and restore authority expansion**
+Restore/import bypasses owner, schema, ACL, uniqueness, or validation rules, overwrites existing resources, or recreates records in a tenant the requester cannot write. Validate archive contents as untrusted and authorize the resulting operation rather than trusting prior provenance.
+
+**Migration default and ownership confusion**
+Old records lack tenant/ACL/lifecycle fields, incompatible IDs collide, or partial rollout makes new and old readers apply different defaults. Review backfill, dual-read/write, compatibility, rollback, and resumed-migration paths.
+
+**Backup and replication boundary drift**
+Encryption keys, storage accounts, cross-region replicas, restoration environments, or support snapshots have broader identity or tenant scope than primary data. Source can confirm only in-repo policy; hosted access and retention require `needs_validation`.
+
+## Deletion, revocation, and lifecycle attack classes (subagent_type: `general`)
+
+**Soft-delete and tombstone bypass**
+Direct lookup, search, relation traversal, object link, background processor, or restore ignores the lifecycle predicate and returns or acts on a deleted/revoked record. Check whether soft-deleted identifiers can be re-registered before all references are gone.
+
+**Stale authorization and derived copy use**
+Membership removal, ACL update, consent withdrawal, secret revocation, or role downgrade does not invalidate sessions, caches, subscriptions, jobs, or materialized data that continue to authorize future operations.
+
+**Retention and queued-work overrun**
+Deletion completes in primary storage while queued processors, retries, exports, analytics, or generated artifacts recreate or retain the data beyond the promised boundary. Find idempotent deletion and tombstone propagation.
+
+**Restore reintroduces invalid state**
+Backup, undo, undelete, or replica recovery restores data, credentials, memberships, or permissions that current policy no longer allows. Re-authorize restored state and reapply lifecycle changes made after the snapshot.
+
+## Universal moves (apply across the above)
+
+- Pick one protected record and draw primary write, query, cache, index, event, export, backup, deletion, and restore paths. Mark principal and tenant at every edge.
+- Compare two dummy tenants through the same local service methods, then repeat after ACL change, deletion, account switch, and restore. Do not use real user data.
+- Start at bypass clients, background jobs, migrations, global uniqueness, and cache keys. These paths commonly omit request-scoped identity that interactive endpoints carry.
+
+## Validation rules (apply before reporting ANY finding here)
+
+1. Name attacker or lower-trust principal, protected data/state, affected owner/tenant, alternate copy or operation, and unauthorized disclosure or mutation.
+2. Cite both intended source-of-truth policy and the path that omits or disagrees with it. Confirm another layer does not enforce the same tenant/lifecycle condition.
+3. Use local dummy tenants and non-sensitive fixtures to prove cross-scope access or stale lifecycle behavior. Stop at the minimum observable record or operation.
+4. If external cache, object storage, replicas, analytics, backup, or retention policy is required, classify `needs_validation` and state the owner-observed check.
+5. Return `confirmed` only with complete lineage and concrete boundary impact. Return `needs_validation` with the exact unresolved storage, ACL, invalidation, retention, or restore fact.
diff --git a/.agents/skills/security-audit/DESKTOP-MOBILE-AND-LOCAL-IPC.md b/.agents/skills/security-audit/DESKTOP-MOBILE-AND-LOCAL-IPC.md
new file mode 100644
index 00000000..d6230098
--- /dev/null
+++ b/.agents/skills/security-audit/DESKTOP-MOBILE-AND-LOCAL-IPC.md
@@ -0,0 +1,89 @@
+# Desktop, Mobile, and Local IPC Hunting
+
+#### When to use this file
+
+Reach for this file when the target is a desktop or mobile app, privileged helper, updater, local daemon, webview host, deep-link handler, browser native-messaging host, or local IPC client/server. Relevant untrusted actors may be a downloaded document, remote web content, another local app, another OS user, a sandboxed process, or a lower-privilege account. State that starting capability instead of treating all local users as equivalent.
+
+Use `CLIENT-SIDE.md` for browser-side webview behavior, `MEMORY-SAFETY-AND-BINARY.md` for native memory and loader safety, and `SUPPLY-CHAIN-AND-RELEASE.md` for update authenticity.
+
+## Core discipline (include in every agent prompt for this domain)
+
+```
+- Establish the realistic local or remote-content attacker: another app, another OS user, a sandboxed child, an untrusted document, or a remote origin. Self-harm within the same account and authority is not a boundary violation.
+- Paths, process names, bundle/package IDs, and claimed sender fields are not peer authentication. Use OS peer credentials, code identity, capability handles, or protected channel state.
+- The native bridge or helper must authorize each operation and final resource after parsing. A trusted UI or broker does not make attacker-influenceable arguments trusted.
+- OS sandbox, signing, entitlements, permissions, keychain ACLs, exported-component policy, and prompt behavior are real controls when pinned and visible.
+- Use `confirmed` for source evidence plus bounded local/emulator tests. Use `needs_validation` when signing, manifest merge, OS version, device policy, installer ACL, or packaging is required but not observable.
+```
+
+## Deep-link, callback, and navigation attack classes (subagent_type: `general`)
+
+**Custom-scheme and deep-link ambiguity**
+Another app or page can invoke a route that mutates state, imports data, completes authentication, or selects an account without a current-session and one-time callback binding. Review URI normalization, duplicate query fields, scheme/host/path matching, exported activity/handler policy, and stale/replayed links.
+
+**App and account handoff confusion**
+OAuth, SSO, magic-link, invite, device pairing, passwordless, or payment callbacks return to the wrong installed app, profile, tenant, or pending transaction. Bind state to the initiating app identity, current session, account, provider, operation, and expiry.
+
+**File-open and intent authority confusion**
+An associated file, share intent, drag/drop item, pasteboard/clipboard record, notification action, or open-file event triggers a privileged operation without confirming content type, sender trust where applicable, current user intent, and final target.
+
+## Webview and native-bridge attack classes (subagent_type: `general`)
+
+**Navigation-origin to bridge confusion**
+Remote or attacker-controlled frames can reach a JavaScript/native bridge intended only for packaged content. Validate origin at call time and after every navigation, redirect, subframe creation, popup, and error/fallback page. URL-prefix checks and initial-load checks are insufficient.
+
+**Over-broad native bridge capabilities**
+Web content can select arbitrary files, commands, IPC methods, credentials, or system actions through a generic bridge. Check method allowlists, normalized arguments, user/tenant authority, gesture/confirmation requirements, and return-value disclosure.
+
+**Webview file and universal access**
+Remote content can read app-local files, privileged custom schemes, or internal origins because file access, universal access, mixed content, debug interfaces, or custom protocol handlers join origins unexpectedly. Missing a restrictive setting without reachable protected content is hardening.
+
+## Local IPC and exported-component attack classes (subagent_type: `general`)
+
+**IPC peer-authentication gaps**
+Unix sockets, named pipes, XPC, Binder, D-Bus, native messaging, RPC, shared memory, or loopback listeners accept a lower-trust peer without checking OS credentials, code identity, sandbox token, or channel ownership. Require a meaningful method or disclosure behind the channel.
+
+**Claimed principal versus channel identity**
+The authenticated process/channel belongs to one app or user, but request fields select another user, tenant, profile, or capability. Bind each method and resource to the peer credential rather than a caller-declared identifier.
+
+**Exported service, activity, receiver, or provider overreach**
+A mobile component or local automation endpoint is externally invokable and performs an operation intended for the app itself. Review final merged manifests, intent filters, permission/signature level, path grants, and alternate aliases. Manifest status unknown after packaging requires `needs_validation`.
+
+**IPC lifecycle and correlation confusion**
+Predictable request IDs, reused handles, stale channels, inherited descriptors, world-writable socket paths, or restart behavior lets one peer answer, cancel, or reuse another peer's operation. Review creation permissions and cleanup of socket files, locks, ports, and shared mappings.
+
+## Privileged-helper and local-file attack classes (subagent_type: `general`)
+
+**Privileged helper as confused deputy**
+A low-privilege caller can select a privileged command, file, service, user, or system setting without per-operation authorization. Review sudo/polkit/UAC/XPC helper rules and ensure the helper independently validates normalized arguments.
+
+**Install, update, and repair path trust**
+A privileged installer/helper reads manifests, scripts, packages, symlinks, working directories, or repair state writable by a lower-trust actor after authorization. Bind authorization to immutable content and safe destination paths.
+
+**Local file ownership and TOCTOU**
+The app checks a file/path then follows replacement, symlink, mount, or case/normalization changes during a privileged read/write. Use descriptor-relative operations and verify final ownership. Focus `MEMORY-SAFETY-AND-BINARY.md` on parsing after the file is opened.
+
+**Credential-store and local-secret boundary mismatch**
+A keychain/keystore item, token file, backup, log, clipboard, notification preview, or local config is readable by another app/profile/user with less authority. Plaintext readable only by the same intended OS account is not automatically a vulnerability; state the lower-trust reader and credential power.
+
+## Application-state and device-lifecycle attack classes (subagent_type: `general`)
+
+**Account switch, logout, and device restore leakage**
+Cached data, background tasks, widgets, notifications, local databases, webview storage, or biometric approvals survive logout/account change and appear under a later account. Review backup/restore and multi-profile behavior.
+
+**Pending-action and user-presence confusion**
+Notification, widget, shortcut, share sheet, biometric prompt, or deferred operation authorizes a different action than displayed, executes after expiry, or uses another profile's pending state. Bind confirmation to normalized action, resource, account, and current foreground state.
+
+## Universal moves (apply across the above)
+
+- Enumerate every process, app component, local endpoint, URI scheme, file association, webview origin, and helper. Record OS identity, runtime privilege, caller, and callable operation.
+- Read final packaging inputs: merged manifest, entitlements, installer rules, native-messaging registration, protocol handlers, and ACL creation. Source declarations can be overwritten downstream.
+- Validate with dummy profiles and non-sensitive local fixtures on an isolated machine/emulator. Do not interact with other users' apps, credentials, or production services.
+
+## Validation rules (apply before reporting ANY finding here)
+
+1. Name the attacker starting capability, OS/app principal crossed, entry channel, accepted argument or state, and unauthorized operation or disclosure.
+2. Confirm OS sandbox, peer credential, signing, entitlement, permission, user-consent, and installer controls that apply. Unknown packaging/runtime facts require `needs_validation`.
+3. For webview bridges, cite both navigation/origin control and privileged native sink. For IPC, cite peer authentication and per-resource authorization. For helpers, verify final normalized destination.
+4. Keep local tests bounded and use dummy content/accounts. Stop after proving the boundary result; do not extend proof into persistence or broader system modification.
+5. Return `confirmed` only with a complete source and local evidence chain. Return `needs_validation` with the exact OS, manifest, signing, ACL, or device-lifecycle fact required.
diff --git a/.agents/skills/security-audit/HUNTING.md b/.agents/skills/security-audit/HUNTING.md
new file mode 100644
index 00000000..377d4dcf
--- /dev/null
+++ b/.agents/skills/security-audit/HUNTING.md
@@ -0,0 +1,251 @@
+# Vulnerability Hunting
+
+### Phase 2: Run coverage-led hunting waves
+
+The parent assigns `planned` ledger units to `general` agents. Use enough focused hunters to cover the units without combining unrelated boundaries. One hunter may own closely related units in one subsystem; no unit may be silently unassigned because of an agent-count limit — a unit the budget cannot reach is explicitly `deferred` with reason `budget_cannot_reserve_critics_and_validation`.
+
+When a budget or profile caps hunter count, assign units in priority order and record the ordering rationale in the ledger. Rank by: (1) unauthenticated or lowest-trust entry surfaces before authenticated ones; (2) boundaries protecting the most valuable resources (credentials, cross-tenant data, code execution, release authority); (3) prior-run gaps, revalidation targets, and changed source before same-source re-passes; (4) units whose class historically yields confirmed findings for this target type over speculative ones. Ties break lexicographically by `coverage_id` so runs stay deterministic.
+
+Before launch, the parent changes assigned units to `in_progress`, sets a canonical lowercase `agent_id`, and creates that agent's `scratch/` and parent-owned `artifacts/`. Hunters read source and parent-provided context, write only to their unique `scratch/`, and return one structured result through the Task tool. They never write retained artifacts or edit target source, `architecture.md`, `coverage-ledger.json`, `findings.json`, or another agent's files.
+
+## Required hunter prompt
+
+Every hunter prompt contains these parts in this order:
+
+1. A two-sentence role preamble: the hunter's goal is to find source-grounded security invariant failures in its assigned units, and it must return exactly one JSON object matching the structured-result contract at the end of this prompt.
+2. `architecture.md` verbatim.
+3. Assigned coverage IDs, subsystem, boundary, repository-relative starting paths, and each unit's assignment block map from `coverage-ledger.json`.
+4. The exact selected blocks, copied verbatim: each selected ordinary attack-class block from `ATTACK-CLASSES.md`, and from each selected companion its `Core discipline`, each chosen attack-class subsection, `Universal moves`, and `Validation rules`. Ordinary blocks are self-contained and carry no companion-style `Core discipline`, `Universal moves`, or `Validation rules` sections. Do not send block or companion names alone.
+5. Explicit excluded ordinary and companion blocks with a reason for each exclusion.
+6. The core hunting method below, followed by the promotion procedure block.
+7. The core validation rules below.
+8. Carried same-source prior confirmed exclusions, each limited to fingerprint, title, and root cause, plus peer-owned current coverage IDs that this hunter must not duplicate.
+9. The unique scratch/artifact paths, safe agent ID, predeclared promotion allowlist and byte limits, and the structured-result contract, including the Structured hunter result block below and the `confirmed` and `needs_validation` branches of `report-schema.json` copied verbatim.
+
+A prompt may select several companion blocks when the same path crosses several domains. Keep their constraints together. Scope is the hunter's coverage obligation, not permission to duplicate excluded work. If an unexpected different boundary appears, return it under `uncovered` so the parent creates a stable ledger unit and assigns it in the next wave.
+
+#### Core hunting method — include in every hunter prompt
+
+```text
+## Defensive vulnerability-finding method
+
+Your goal is to find source-grounded security invariant failures and the smallest fix,
+not to expand harm beyond the boundary result. Stay within source review and bounded local execution.
+Do not contact deployed endpoints, provider APIs, registries, identity systems,
+message brokers, shared services, or other users. Use local dummy data only.
+
+READ THE CODE AT DEPTH. Follow each assigned input through parsing, identity,
+authorization, normalization, state, derived copies, and the final sink. Read sibling,
+legacy, batch, retry, cancellation, migration, and error paths that produce the same
+effect. Compare sibling controls for equivalence, not only presence, and compare what
+one component guarantees with what the next component assumes.
+
+WORK FROM A CONCRETE INVARIANT:
+1. Name the lower-trust principal and starting capability.
+2. Name the accepted value, action, state transition, or resource selector.
+3. Locate the control that should reject, bind, isolate, limit, or revoke it.
+4. Trace the exact source path after that decision.
+5. Stop at the smallest affected dummy record, wrong return value, process-integrity
+ effect, or locally observable shared-resource effect.
+6. State a source-level change and regression case that enforce the invariant.
+
+DEPTH BOUND: trace only paths that can reach your assigned boundary or whose
+guarantees that boundary relies on. Stop a line of investigation as soon as the
+invariant is settled either way, and record the result in your structured output —
+a covered, candidate, or blocked disposition, or an `uncovered` entry — instead of
+continuing to search.
+
+TEST SAD PATHS AND DISAGREEMENTS. Check absent, empty, zero, negative, maximum,
+over-limit, duplicate, mixed encoding, stale, revoked, reordered, concurrent,
+partially migrated, failed dependency, and rollback state only where the interface
+accepts them. Compare canonicalization and units at every parser or policy handoff.
+For multi-step issues, treat each output as a prerequisite and do not assume a later
+boundary. If any prerequisite is not established, record a blocker.
+
+When a proposed high or critical candidate reveals a reusable root cause, search paths
+owned by the assigned coverage IDs for lexical, structural, and logical variants.
+Consolidate the same root cause, but establish each variant's conditions and impact
+independently. Do not investigate peer-owned units. Return a variant with no current
+coverage unit as `uncovered`.
+
+USE THE NARROWEST LOCAL CHECK THAT SETTLES THE CLAIM. Target-controlled builds,
+tests, processes, browsers, emulators, fuzzers, and fixture processing may run only
+inside the parent-approved OS-enforced sandbox. It must disable external networking,
+start from an empty allowlisted environment, expose target and tools read-only, permit
+writes only to your scratch directory, and apply low CPU, memory, process, file-size,
+disk, and wall-clock limits. Isolated loopback is allowed only for a local fixture.
+If any control is unavailable, do not execute: return needs_validation with that exact
+blocker. Prefer an existing unit test, minimal function harness, dummy-tenant service
+call, small malformed fixture, deterministic race schedule, or locally rendered policy.
+Do not install or fetch tools.
+
+Record the exact input, command, limits, and minimum result. For the environment,
+record only allowlisted variable names and safe non-secret values needed to reproduce
+the check. Never capture the ambient environment, inherited variables, credentials,
+authentication state, or unrelated host paths. The target-controlled process writes
+only in scratch. After the sandbox and all its processes terminate, only trusted
+parent-side code may promote predeclared scratch-relative files, following the
+promotion procedure block included verbatim in this prompt. You and target code never
+write retained artifacts. If promotion is unavailable or fails for decisive evidence,
+return needs_validation with the exact promotion blocker.
+Never stress availability, invoke a live target, use a real credential, publish an
+artifact, or continue past the minimum observed effect.
+
+A deployment, browser, provider, broker, OS, proxy, package, secret, or identity fact
+outside source is not proof either way. If one such fact is decisive, return a
+needs_validation record with the exact missing observation and safe owner-observed check.
+```
+
+#### Promotion procedure — copy this promotion procedure verbatim into every hunter prompt
+
+```text
+Artifact promotion procedure (trusted parent-side code only):
+Reference only for you: the parent performs these steps; you never perform them.
+
+Before execution, the parent opens and retains trusted, non-inheritable directory
+descriptors for the agent's scratch/ and artifacts/ roots, and records an allowlist
+of expected scratch-relative artifact files plus explicit per-file and cumulative
+byte limits. Never pass those descriptors to the agent or sandbox. After the sandbox
+and all its processes terminate, trusted parent-side code promotes each allowlisted
+file separately:
+
+1. Validate the declared relative path: reject absolute, empty, `.`, `..`, or
+ symlinked components.
+2. Walk each parent component from the retained scratch-root descriptor with
+ no-follow directory-relative operations; never reopen by path.
+3. Open the leaf no-follow and nonblocking.
+4. Verify with `fstat` that it is a regular file with link count exactly one and
+ within the recorded per-file and cumulative byte limits.
+5. Enforce those limits again while reading from that descriptor.
+6. Copy exactly the verified size, repeat `fstat`, and reject a changed identity,
+ type, link count, or size.
+7. For the destination, walk every parent component from the retained
+ artifacts-root descriptor with no-follow directory-relative operations; require
+ each existing component to be a real directory, and create any missing directory
+ exclusively before reopening and verifying it no-follow.
+8. Create the leaf exclusively without following links, verify that the opened
+ destination is a regular file with link count exactly one, and copy from the
+ verified source descriptor without reopening either path.
+9. Use equivalent race-safe APIs on non-POSIX systems.
+10. Never recursively copy or glob scratch, extract an archive into artifacts, or
+ open or promote a symlink, FIFO, socket, device, directory, hard-linked file,
+ changing file, or file that exceeds its bound.
+11. If any check is unavailable, cannot be enforced, or fails, discard the scratch
+ entry; if it is decisive evidence, retain `needs_validation` with the exact
+ promotion blocker.
+```
+
+#### Core validation rules — include in every hunter prompt
+
+```text
+## Candidate gate
+
+1. A candidate needs a complete repository-relative source trace and evidence for the
+ claimed root cause, including the strongest source-visible control.
+2. A proposed confirmed record needs a bounded local observed result, meaningful impact
+ across a stated boundary, complete conditions, and no visible preventing layer.
+3. Do not strengthen a crash into code execution, ordinary work into shared availability,
+ or a same-principal action into privilege gain.
+4. If a required fact is not source-visible or locally observable, use
+ needs_validation. Name exact blockers; do not give it severity or speculative completion.
+5. A missing best practice with no affected principal/resource is excluded or hardening,
+ not a finding. A candidate disproved by source is not needs_validation.
+6. Use the same source-derived fingerprint for the same root cause in every state.
+ It must match `^[A-Za-z0-9][A-Za-z0-9._:/@+-]*$` and must not include a line,
+ wave, agent, severity, or verdict.
+7. Return an empty candidate array when nothing survives these gates.
+```
+
+## Local validation boundaries
+
+Local execution is for confirmation, not impact expansion:
+
+- **Allowed only in the required OS sandbox:** offline builds with present dependencies; isolated-loopback processes using dummy state; unit and integration tests; small fixture processing; sanitizers; bounded fuzz/regression tests; deterministic concurrency checks; local browser/emulator tests with dummy accounts; rendered manifests and policy evaluation with dummy identities; mocked external or paid calls.
+- **Disallowed:** live or deployed traffic; requests to services not started for this isolated check; network dependency installation; real accounts or credentials; production data; shared queues, cloud resources, runners, registries, signing or release services; publishing; stress, saturation, or cost generation; any work after the minimum dummy-data boundary result.
+
+The sandbox starts with an empty environment, gives target code no external network or host writable path, and enforces explicit low resource and time limits for every check, not only checks expected to be expensive. Scratch output remains target-controlled after exit. Promote it only with the no-follow, path-confined, regular-file, bounded-size host procedure in `SKILL.md`. Missing any sandbox or promotion capability does not erase a source-grounded candidate; represent the exact blocker in `needs_validation`.
+
+## Structured hunter result
+
+Return exactly one JSON object, with no surrounding prose:
+
+```json
+{
+ "units": [
+ {
+ "coverage_id": "one assigned ID",
+ "disposition": "covered|candidate|blocked",
+ "reviewed_paths": ["repo/relative/path"],
+ "checks": [
+ {
+ "agent_id": "canonical owner of this check",
+ "reviewed_paths": ["repo/relative/path owned by this check"],
+ "invariant": "specific control checked for this unit",
+ "method": "source|local",
+ "result": "what source or the bounded check established",
+ "artifact": "agents//artifacts/file for local, null for source"
+ }
+ ],
+ "candidate_fingerprints": [],
+ "unresolved": []
+ }
+ ],
+ "candidates": [],
+ "hardening": ["concrete non-finding note"],
+ "uncovered": [
+ {
+ "surface": "...",
+ "boundary": "...",
+ "subsystem": "...",
+ "attack_class": "...",
+ "starting_paths": ["repo/relative/path"],
+ "reason": "why this needs its own deterministic coverage unit"
+ }
+ ]
+}
+```
+
+Each `candidates` entry is schema-shaped except that it uses `proposed_verdict` in place of `verdict`:
+
+- `proposed_verdict: "confirmed"`: include every field required by the `confirmed` branch of `report-schema.json` other than `verdict`: `fingerprint`, title, description, `root_cause`, `intended_behavior`, ordered `trace`, `evidence`, `conditions`, target-neutral `execution`, `remediation`, `severity`, and `confidence`. The execution instructions describe only the bounded local check already performed. `payloads` holds the minimum test input, fixture, or native invocation. `observed_result` records actual local output. Overall severity must not exceed observed impact.
+- `proposed_verdict: "needs_validation"`: include every field required by that schema branch other than `verdict`: `fingerprint`, title, description, `claimed_root_cause`, ordered `trace`, `evidence`, nonempty `blockers`, and `validation_plan` with at least one applicable `local` or `deployment` step. Do not invent an inapplicable context. Do not include severity, execution, remediation, reason, or a confirmed `root_cause`. `deployment` is an owner-observed check, not a request to probe a live target.
+
+Every assigned coverage ID appears exactly once in `units`. A `covered` unit needs an owner, nonempty `reviewed_paths` and `checks`, no unresolved fact, and no candidate. A `candidate` unit has the same owned evidence and is the only state that carries linked fingerprints. A `blocked` unit is an owned partial review with nonempty paths, checks, and unresolved facts but no fingerprint. All source paths are repository-relative, never absolute or traversal paths. A trace with several entries begins at `entrypoint`, ends at `sink`, and labels intermediate steps `propagation`. Every check has its own canonical lowercase `agent_id` and nonempty `reviewed_paths`; the unit-level list is exactly the union of those owned paths. A `source` check uses `artifact: null`. A `local` check uses one successfully parent-promoted regular file beneath `agents//artifacts/`; this permits a verifier to add independently owned evidence without taking ownership from the hunter. Never link scratch, an output-root file, or another check owner's artifact.
+
+## Parent consolidation and ledger update
+
+The parent validates each unit result, maps it to exactly one assigned `coverage_id`, and updates only that ledger unit. Reject duplicate or absent IDs, unsafe unit or check agent IDs, source checks with artifacts, and local artifacts that trusted parent-side code did not promote into the check owner's artifacts subtree. Copy the unit's `reviewed_paths`, its `checks` into the unit's `local_checks`, linked artifact paths, candidate fingerprints, and unresolved facts into the ledger. Retain each hunter's `hardening` list in a parent bookkeeping field on the relevant units (outside the semantic fields) so Phase 6 can report it. A failed, malformed, or unsupported conclusion leaves that unit `planned` for reassignment. Untouched budget/profile units become unassigned `deferred` units with empty evidence and a reason; do not hide partial evidence in `deferred`. Run `validate-coverage-ledger.cjs` after the update; an invalid ledger cannot drive another assignment. This per-unit contract allows one hunter to close one unit while returning a candidate or blocker for another.
+
+Consolidate candidate entries by fingerprint and then by root cause. One root cause that exposes several entry paths or effects is one candidate with the strongest complete trace. Related but independent missing controls use separate fingerprints. Record duplicate fingerprints in the relevant ledger unit and do not send duplicate candidates to validation.
+
+## Coverage-critic waves
+
+Immediately after each hunter wave, spend the reserved invocation on one fresh `research` post-wave coverage critic. It receives `architecture.md`, the full coverage ledger including each assignment block map, current candidate fingerprints and states, and the prior-ledger gap summary. It reads source but does not write or run targets. Require exactly this JSON:
+
+```json
+{
+ "missing_units": [
+ {
+ "surface": "...",
+ "boundary": "...",
+ "subsystem": "...",
+ "attack_class": "...",
+ "starting_paths": ["repo/relative/path"],
+ "selected_companion_blocks": ["FILE.md#section"],
+ "excluded_blocks": [{"block": "FILE.md#section", "reason": "..."}],
+ "reason": "source-backed coverage gap"
+ }
+ ],
+ "reassign_ids": ["existing-id-that-did-not-close"],
+ "resolved_prior_leads": ["fingerprint"],
+ "stop": false
+}
+```
+
+The critic checks for unmapped entry points, unchecked parallel paths, missing lifecycle modes, selected companion classes without a unit, unjustified exclusions, units closed without paths/checks, and prior `needs_validation` or changed-source gaps that no unit addresses. It proposes coverage, not findings. `stop` is the critic's own assessment: `true` only when it accepts no `missing_units` and no `reassign_ids`; the parent's loop condition below, not `stop` alone, decides whether another wave runs. For each fingerprint in `resolved_prior_leads`, the parent marks the linked unit or prior-lead entry resolved and records the critic's source-backed reason.
+
+The parent rejects proposed units outside the review scope or source/local boundary, derives canonical IDs for accepted units, and deduplicates them against current units. A prior same-source completed unit may supply evidence; prior `deferred`, `blocked`, `out_of_scope`, or changed-source units become current work and never suppress an accepted unit. Fail rather than merge a canonical ID collision. For each legitimate `reassign_id` with live `blocked`, `covered`, or `candidate` evidence, append that exact terminal record to the unit's `attempts` with the critic's source-backed `reassignment_reason`. Preserve its owner, checks, artifacts, fingerprints, and unresolved facts in that archive. Increment the live `wave`; the next hunter must be a fresh owner and receives an `in_progress` unit with empty live evidence. The hunter's terminal result writes only its new evidence into the live fields. Never copy an archived owner's checks or artifacts into the new live attempt. Sort IDs and validate the ledger before another assignment. In `standard` and `deep`, when the post-wave critic reports no accepted `missing_units` or legitimate `reassign_ids` and no `planned` units remain, spend the separately reserved invocation on a distinct final-clean critic. Complete coverage only when that critic also returns no accepted work. If it finds work, queue it and repeat the wave, post-wave critic, and final-clean process. If time or resources force an early stop, mark every untouched unit `deferred`, preserve the critic's reason, and disclose the gap in the report. Never use a silent wave or agent cap as evidence of complete coverage.
+
+The run profile bounds this loop. A `quick` run has exactly one hunter wave followed by exactly one final critic pass. Add each accepted `missing_unit` to the current ledger and mark it `deferred` with reason `quick_profile_final_critic`. For each legitimate evidence-bearing `reassign_id`, archive the live terminal state in `attempts`, increment `wave`, and set the live state to unassigned `deferred` with empty evidence and reason `quick_profile_final_critic`. Do not launch a second hunter wave or another critic. In a scoped run, the critic still reports out-of-scope gaps it notices, but the parent records them as `out_of_scope` with the critic's reason instead of assigning them. The early-stop rule above is the same mechanism: `quick` is a pre-declared early stop, not evidence of complete coverage.
+
+A budget bounds it the same way. Before assigning each wave, compare remaining budget against its hunter count, the validation reserve, the immediate post-wave critic, and the retained final-clean critic (`quick` reserves only its single final post-wave critic). Shrink the hunter wave to fit, taking units in priority order. If those mandatory reserves do not fit, launch no hunter from that wave and mark its planned units `deferred` with reason `budget_cannot_reserve_critics_and_validation`. Critic-proposed units enter the same ranked queue rather than extending the budget. If surviving candidates exceed the validation reserve, follow the incomplete-run rule in `SKILL.md`: stop hunting, validate in fingerprint order, retain unvalidated units as unresolved candidates, and never present them as findings.
diff --git a/.agents/skills/security-audit/MEMORY-SAFETY-AND-BINARY.md b/.agents/skills/security-audit/MEMORY-SAFETY-AND-BINARY.md
new file mode 100644
index 00000000..86ff4920
--- /dev/null
+++ b/.agents/skills/security-audit/MEMORY-SAFETY-AND-BINARY.md
@@ -0,0 +1,101 @@
+# Memory Safety, Binary, and Kernel Hunting
+
+#### When to use this file
+
+Reach for this file when the target processes untrusted bytes in a memory-unsafe or privileged context: C/C++/Objective-C, Rust `unsafe`, FFI, kernel modules and drivers, parsers and decoders, network daemons, firmware, binary loaders, language runtimes, and JITs. Use `PROTOCOLS-RPC-AND-MESSAGING.md` for protocol authorization and state-machine logic, and this file for process integrity, memory safety, ABI boundaries, and loader behavior.
+
+Pick relevant classes from Phase 1 and split large targets by parser, allocator/lifetime, FFI, concurrency, loader, runtime, or privileged interface.
+
+## Core discipline (include in every agent prompt for this domain)
+
+```
+- Re-derive every bound and lifetime from attacker-controlled inputs and all callers. Validate against the worst accepted case, not a typical test vector.
+- A panic, sanitizer finding, or crash proves a defect only when a realistic untrusted input reaches it. Do not infer memory corruption, code execution, or shared availability impact from a label alone.
+- Validate in a local harness with sanitizers, deterministic concurrency tests, existing fuzz targets, and debugger-assisted fault classification. Stop after proving the violated invariant and observable impact; do not develop post-corruption techniques.
+- Assembly, JIT code, custom allocators, intra-object accesses, and foreign libraries can escape sanitizer coverage. Identify which relevant instructions are instrumented.
+- Classify as `confirmed` only after source evidence and bounded local validation establish the defect and effect. Use `needs_validation` when ABI, allocator, architecture, feature, deployment, or reachability facts remain unknown.
+```
+
+## Bounds, integer, and representation attack classes (subagent_type: `general`)
+
+**Out-of-bounds read or write**
+A length, offset, index, or terminator reaches a fixed or allocated buffer without a correct bound. Recalculate available headroom after prefixes, alignment, padding, and terminators. Check both source and destination capacity, and whether a short input is read before its declared length is trusted.
+
+**Integer overflow, underflow, truncation, and signedness**
+Review attacker-controlled arithmetic before allocation, copy, loop, indexing, and pointer operations. High-hit patterns include `a - b` with `b > a`, `count * element_size`, additions near the type maximum, negative values converted to unsigned, 64-bit lengths narrowed to 32-bit fields, and sentinel values such as `-1` becoming a large size. Confirm which checked representation is later used.
+
+**Unit and pointer-depth confusion**
+Code mixes bytes, elements, code units, pages, words, wire units, or nested pointer element sizes. Compare the unit at parse, validation, allocation, API boundary, and copy. A bounds check using the same wrong unit as the allocation is still wrong.
+
+**Uninitialized or partially initialized data**
+A buffer, padding, struct field, or vector capacity is returned, compared, hashed, serialized, or passed across a trust boundary before initialization. Require an observable consumer and realistic output length; stack allocation by itself is not disclosure.
+
+## Lifetime, type, and concurrency attack classes (subagent_type: `general`)
+
+**Use-after-free, stale view, and double free**
+Owners are released while callbacks, wait queues, timers, iterators, borrowed slices, or cached raw pointers can still use them. Review every error, cancellation, close, and realloc path. For embedded notification anchors, each free path must drain or detach all observers.
+
+**Type confusion and invalid downcast**
+A tag, vtable, union discriminator, object kind, or foreign handle is checked differently from the representation later read. Look for unchecked dynamic casts, stale tags after reuse, and serialized types whose validated element differs from the element consumed. Confirm a wrong-type read or write locally without extending the test beyond the violated invariant.
+
+**Reference-count and ownership races**
+Non-atomic retain/release, a check followed by an unlocked use, or inconsistent ownership across threads can free or mutate an object during access. Compare fast, error, shutdown, and compatibility paths for the same lock and ownership rules.
+
+**Shared-state races and TOCTOU**
+Concurrent parser streams, global caches, lazy initialization, signal handlers, and resource teardown can invalidate bounds, policy, or pointers established earlier. Verify the race with a repeatable local schedule, barrier, or thread sanitizer; a hypothetical interleaving without a security-relevant state transition remains `needs_validation`.
+
+**Lock-order, deadlock, and starvation**
+Externally reachable operations acquire locks in inconsistent order or hold them across callbacks and blocking I/O. Report under availability only when bounded input can stop shared progress; otherwise record it for fixing as a concurrency defect.
+
+## FFI and ABI attack classes (subagent_type: `general`)
+
+**Pointer-length and ownership contract mismatch**
+Caller and callee disagree on who allocates, frees, pins, or mutates a buffer, how long a pointer remains valid, or whether a length is bytes or elements. Trace both sides of every `extern`, CGo/JNI/Python/native binding, and generated wrapper. Check null, zero length, aliasing, and callback retention.
+
+**Layout, alignment, and enum disagreement**
+Foreign code receives a struct, bitfield, packed record, callback signature, integer width, enum, or calling convention that differs by architecture or build flag. Verify `repr`, packing, alignment, endianness, and ABI-specific types. An in-repo declaration mismatch can be confirmed locally; an opaque foreign implementation requires `needs_validation`.
+
+**Unwind, exception, and thread-affinity violations**
+Exceptions or panics cross an ABI that forbids unwinding, callbacks run after teardown, or APIs requiring one runtime thread are invoked elsewhere. Review error conversion and cancellation. Confirm whether the process aborts or state is corrupted before assigning impact.
+
+## Binary loading and runtime attack classes (subagent_type: `general`)
+
+**Library, plugin, and executable search-order trust**
+A privileged process loads a library, plugin, runtime image, or helper from a path writable by a less-trusted principal, or resolves a bare name through an attacker-influenceable working directory or environment. Compare intended installation ownership with each fallback and compatibility search path. A user loading their own plugin into their own process is not a boundary violation.
+
+**Missing artifact identity or signature binding**
+A loader verifies one file or metadata record but maps a different image because path resolution, file replacement, architecture slices, or embedded resources are not bound to the check. Supply-channel authenticity belongs in `SUPPLY-CHAIN-AND-RELEASE.md`; this class covers the local verification-to-map gap.
+
+**Malformed binary metadata and relocation handling**
+Offsets, counts, sections, relocations, symbols, bytecode, or debug metadata are trusted before range, overlap, and representation checks. Test parsers with bounded local fixtures and sanitizers. Separate memory corruption from a safely rejected malformed file.
+
+**JIT and generated-code consistency**
+Validator, interpreter, optimizer, and generated code disagree about types, bounds, side effects, or lifetime. Diff optimized and unoptimized paths using the same local input. Confirm a process-integrity effect; output variance that stays within language semantics is not a finding.
+
+**Unload, reload, and teardown safety**
+Live function pointers, callbacks, worker threads, or data views survive module unload or runtime reset. Review shutdown and failed-load cleanup as closely as startup.
+
+## Kernel and privileged-interface attack classes (subagent_type: `general`)
+
+**User-copy bounds and repeated reads**
+A syscall, ioctl, driver, or kernel parser derives a trusted fact from user memory then reads the same mutable address again. Copy the full request once or revalidate the later copy. Also audit size, direction, and access checks at each user-copy primitive.
+
+**Privileged object lifecycle and dispatch consistency**
+Externally reachable objects have unbalanced retain/release, teardown without observer drain, unchecked selector/table indices, or duplicated compatibility paths that omit a guard. Diff each dispatch and free path side by side.
+
+**Under-authorized powerful interfaces**
+A device node, admin socket, helper, or management API validates shape but not the caller's authority over the resource. Establish actual interface ownership and reachability; permissions or sandbox policy outside the repository make this `needs_validation`.
+
+## Universal moves (apply across the above)
+
+- Audit fixes and duplicated paths for the same source-to-sink shape. A check in one caller, architecture, protocol role, feature flag, or compatibility path does not protect its siblings.
+- Build a table for every parser or FFI boundary: accepted length/type, checked representation, allocation owner, consumer, thread, and teardown. Most native findings are one disagreement in that table.
+- Use existing corpora and small locally generated boundary fixtures. Save exact sanitizer/runtime output and the input property that triggers it; avoid large resource consumption and any live target.
+
+## Validation rules (apply before reporting ANY finding here)
+
+1. Establish a realistic untrusted entry and exact operation that violates a bounds, type, lifetime, ABI, concurrency, loader, or authority invariant.
+2. Classify the observable effect: invalid read, invalid write, stale alias, wrong object, uninitialized output, unauthorized image load, deadlock, or safe process termination. Do not claim a stronger effect than observed.
+3. Run the narrowest local harness, existing test, sanitizer, or fuzzer needed to reproduce the effect. Verify sanitizer coverage of the faulting operation and record architecture/build conditions.
+4. For concurrency, use a deterministic schedule or sanitizer trace. For binary loading, prove the checked identity differs from the mapped identity and name the lower-trust writer.
+5. Return `confirmed` findings only with exact input, source trace, and observed result. Return `needs_validation` for a specific unresolved reachability, ABI, build, deployment, or runtime fact and state the bounded check needed.
diff --git a/.agents/skills/security-audit/PROTOCOLS-RPC-AND-MESSAGING.md b/.agents/skills/security-audit/PROTOCOLS-RPC-AND-MESSAGING.md
new file mode 100644
index 00000000..b04ab88f
--- /dev/null
+++ b/.agents/skills/security-audit/PROTOCOLS-RPC-AND-MESSAGING.md
@@ -0,0 +1,81 @@
+# Protocols, RPC, and Messaging Hunting
+
+#### When to use this file
+
+Reach for this file when the target uses gRPC, GraphQL transports, Cap'n Proto, Thrift, Protobuf, custom binary protocols, streaming RPC, webhooks, brokers, queues, pub/sub, or event buses. It covers peer identity, logical message interpretation, routing, replay, ordering, and delivery semantics. Use `MEMORY-SAFETY-AND-BINARY.md` for parser memory safety, `WEB-PROTOCOL-AND-AUTH.md` for HTTP framing, and `RESOURCE-EXHAUSTION-AND-AVAILABILITY.md` for availability impact.
+
+Split large systems by producer/consumer pair, external/internal peer role, synchronous RPC, streaming, and asynchronous message path.
+
+## Core discipline (include in every agent prompt for this domain)
+
+```
+- "Internal" is not authentication. Name the peer identity at every hop and show how it becomes the application principal used for authorization.
+- Schema validation proves message shape, not provenance, resource authority, ordering, or safe values. Follow decoded fields to policy and side effects.
+- Broker guarantees and application guarantees differ. Write down retry, ordering, acknowledgement, deduplication, and transaction behavior before evaluating state changes.
+- Parser disagreement requires two concrete consumers, schema versions, or wire representations and one security-relevant divergent value.
+- Use `confirmed` for source-complete paths plus bounded local producer/consumer tests. Use `needs_validation` for broker ACL, service-mesh identity, topic attachment, or compatibility behavior outside the repository.
+```
+
+## Framing, schema, and interpretation attack classes (subagent_type: `general`)
+
+**Message boundary and canonicalization disagreement**
+Components disagree on length, compression, duplicate fields, unknown fields, encoding, numeric width, normalization, or envelope/body precedence. Compare generated and custom parsers, gateways, language bindings, and version converters. Confirm which principal, resource, or operation differs after decoding.
+
+**Union, enum, and default confusion**
+Unknown variants, missing discriminators, zero values, default privileges, or compatibility mappings reach code that assumes a validated case. Review exhaustive dispatch, default branches, and how old consumers interpret newly added fields.
+
+**Envelope and payload identity mismatch**
+Authorization uses trusted-looking routing or envelope metadata while the handler acts on a conflicting tenant, account, subject, object, or sender in the body. Identify which source is authoritative and ensure clients cannot override it.
+
+## RPC identity and authorization attack classes (subagent_type: `general`)
+
+**Interceptor and method-path inconsistency**
+An authn/authz interceptor applies to unary methods but not streams, reflection, health, gateway-transcoded paths, compatibility services, or individual stream messages. Compare every registration and route to the same operation.
+
+**Peer identity to application-principal confusion**
+mTLS, workload identity, bearer metadata, forwarded identity, or broker credentials authenticate a channel, but a caller-controlled field selects the user or tenant. The channel identity and claimed principal must be bound by deterministic policy.
+
+**Per-item and streaming authorization gaps**
+A stream, subscription, batch, or bulk message is authorized once, then later items name different resources or continue after role, membership, or token revocation. Re-check where scope can change and bind subscriptions to their original principal.
+
+**Callback and reply-correlation confusion**
+Predictable, reused, or cross-tenant correlation IDs let a response, webhook, cancellation, or acknowledgment satisfy another caller's pending operation. Bind each outstanding request to authenticated peer, tenant, operation, and lifecycle.
+
+## Broker and queue isolation attack classes (subagent_type: `general`)
+
+**Topic, routing-key, and subscription scope gaps**
+A publisher or subscriber can select another tenant's topic, wildcard, consumer group, partition, reply queue, or dead-letter route. Check broker-enforced ACLs where visible and application-side namespace construction. Tenant text inside a payload is not isolation.
+
+**Dead-letter, retry, and diagnostic disclosure**
+Messages routed to dead-letter queues, error topics, tracing, or operator views contain secrets or cross-tenant payloads accessible to a lower-trust consumer. Review policy and redaction at the failure path, not just normal delivery.
+
+**Untrusted producer treated as control plane**
+A message body can declare itself an admin event, provider callback, replication record, or migration instruction without an independently authenticated producer and event type. Verify signatures and source/account/audience binding before privileged handling.
+
+## Replay, ordering, and transaction attack classes (subagent_type: `general`)
+
+**Duplicate delivery and idempotency gaps**
+Retries or redelivery repeat a side effect because deduplication is absent, occurs after mutation, or uses a key that collides across tenants or operations. Confirm the broker's delivery model and the side effect that is not naturally idempotent.
+
+**Out-of-order and stale message acceptance**
+Older state, revoked membership, canceled work, or pre-step-up authorization arrives after newer state and overwrites it. Review sequence/version checks, tombstones, partition changes, and restore/replay workflows.
+
+**Acknowledgment/commit ordering defects**
+Acknowledgment occurs before durable commit and loses security-relevant work, or commit happens before an unreliable acknowledgment and duplicates a mutation. Evaluate transactional outbox/inbox behavior and failure recovery.
+
+**Partial multi-consumer transitions**
+Several consumers jointly implement one authorization or business transition, but retries and partial failure leave only a subset committed. Identify invariants that must become durable atomically or compensate with current authorization.
+
+## Universal moves (apply across the above)
+
+- Draw producer → broker/transport → gateway → consumer → storage for each message family. At each hop record authenticated peer, authoritative tenant/resource fields, validation, and side effect.
+- Feed the same small fixture to every in-repo schema version or language binding. Test duplicate, missing, unknown, boundary, replayed, and reordered messages without producing load.
+- Compare normal, retry, dead-letter, replay, migration, reflection, stream, and gateway-transcoded routes. Security policy must survive transport changes.
+
+## Validation rules (apply before reporting ANY finding here)
+
+1. Name the realistic producer or peer, accepted message, authenticated channel identity, affected principal/resource, and unauthorized mutation or disclosure.
+2. For disagreement claims, cite both parsers/consumers and the divergent decoded value. Safe rejection by either side prevents confirmation.
+3. For replay/order claims, establish actual delivery guarantees and reproduce the invariant failure with a bounded local/in-memory transport.
+4. For authorization and isolation, verify all interceptor, broker ACL, gateway, and consumer layers visible in source. External attachments make the candidate `needs_validation`.
+5. Return `confirmed` only with the complete message lifecycle and observed meaningful result. Return `needs_validation` with the exact broker, service identity, route, or delivery fact required.
diff --git a/.agents/skills/security-audit/RECONNAISSANCE.md b/.agents/skills/security-audit/RECONNAISSANCE.md
new file mode 100644
index 00000000..1a170a93
--- /dev/null
+++ b/.agents/skills/security-audit/RECONNAISSANCE.md
@@ -0,0 +1,156 @@
+# Reconnaissance
+
+### Phase 1: Map the source and plan coverage
+
+The parent initializes `run-metadata.json`, applies the strict pre-reconnaissance budget gate in `SKILL.md`, then creates agent scratch roots and the shared ledger before hunting. If the gate fails, record the incomplete status in metadata and launch no reconnaissance agent. Reconnaissance reads the target and locally available build/configuration state only. It does not contact deployed endpoints, external identity providers, registries, brokers, cloud APIs, or other shared services.
+
+Launch several `research` agents in parallel. They return structured facts to the parent and do not write files.
+
+**Agent 1a: Product, stack, and local operation**
+
+```text
+Read the target at . Do not use network access. Return:
+1. Product type, users, operators, and ordinary trust-sensitive actions.
+2. Languages, frameworks, build system, runtimes, and locally visible deployment models.
+3. Repository-relative entry points and subsystem boundaries.
+4. Exact build and test commands that could run offline with local dependencies, their expected write locations, and the target-controlled inputs they process. Do not run them during reconnaissance.
+5. Comparable software or protocol visible from local documentation and dependencies. If no useful comparison is source-grounded, say so.
+6. Missing local toolchains or runtime facts that limit bounded execution.
+Return only source facts with repository-relative file:line references.
+```
+
+**Agent 1b: Principals, authority, and controls**
+
+```text
+Read all source that establishes identity, authorization, isolation, and privilege. Map:
+1. Each lower-trust principal and the actions it has by design.
+2. Authentication or peer identity at each entry surface.
+3. Per-resource authorization and tenant/owner scope.
+4. Process, browser, workload, CI, plugin, model/tool, device, or local-IPC authority.
+5. Privilege changes, confirmation, revocation, recovery, and fallback paths.
+6. Which controls are source-visible and which depend on an unobserved deployment fact.
+Return trust boundaries and control locations with repository-relative file:line references. Do not infer live reachability.
+```
+
+**Agent 1c: Entry surfaces, copies, and sinks**
+
+```text
+Inventory every source-visible place external or lower-trust input enters:
+- HTTP/browser, RPC/message/protocol, files/archive/document, CLI/env/config, plugins/dependencies/CI, cloud events/IAM selectors, model context/tool arguments, mobile/deep-link/webview, and local IPC.
+For each surface, follow major transformations, stored or derived copies, and security-relevant sinks. Record source-visible limits and parallel paths to the same effect.
+Return repository-relative paths and line numbers. Be complete, but do not execute or send inputs.
+```
+
+**Agent 1d: Local execution and deployment visibility**
+
+```text
+Read tests, build definitions, manifests, packaging, and maintained environment overlays. Return:
+1. Small offline tests or existing fixtures that could validate trust boundaries with dummy data inside the required OS-enforced sandbox.
+2. Processes that could use an isolated loopback network namespace without external or shared dependencies.
+3. Commands that would fetch dependencies, publish artifacts, contact paid/provider APIs, or affect shared state; mark them prohibited for this run.
+4. Deployed controls and attachments that source cannot establish and therefore require needs_validation if decisive.
+5. The final active source path for each deployment mode only where the repository selects it deterministically.
+6. Whether the local platform can enforce an empty allowlisted environment, no external network, read-only target/toolchain mounts, scratch-only writes, and explicit CPU, memory, process, file-size, disk, and wall-clock limits. Missing controls block target-controlled execution.
+7. Whether trusted parent-side code can promote predeclared scratch files with path-confined no-follow descriptor traversal, nonblocking regular-file checks, no-follow traversal of every destination parent, exclusive regular-file destination creation, and explicit per-file and cumulative size bounds. Missing promotion controls block use of scratch files as evidence.
+```
+
+Add focused reconnaissance agents for materially distinct deployment modes or subsystems that these four do not map. Do not silently omit them: if the budget gate in `SKILL.md` blocks a focused agent, launch nothing for it, seed the unmapped area as a `deferred` ledger unit with reason `budget_cannot_reserve_critics_and_validation`, and disclose the gap in the report.
+
+## Prior-run input
+
+Before selecting work, the parent reads every available prior `coverage-ledger.json` and `findings.json` for the same repo:
+
+- Compare the source locations, controls, conditions, and source-derived identity for every prior record and unit against the current source.
+- Carry an unchanged prior `confirmed` record into the current candidate set, with the same fingerprint, only when its relevant source, conditions, and qualifying evidence still apply. Link it to a current `planned` unit with `prior_status: "prior_confirmed_same_source"` and put only that root cause on the hunter exclusion list. The Phase 3 verifier that re-verifies the carried record becomes that unit's assignment owner; its source re-check is the unit's first check and moves the unit to `candidate` with the carried fingerprint.
+- Build a current planned `prior_confirmed_changed_source` revalidation unit when any relevant source or condition changed. Do not exclude that root cause from hunting or assume the prior verdict still applies.
+- Build current work units for every prior `needs_validation`, `deferred`, `blocked`, `out_of_scope`, and changed-source unit. These states are priority input, never deduplication or suppression keys.
+- Carry a still-blocked prior `needs_validation` record with the same fingerprint only after current source supports its trace. Link it to a current `planned` unit with `prior_status: "prior_needs_validation"`; the record keeps the unresolved blocker. The Phase 3 verifier that re-checks the carried record becomes that unit's assignment owner; its re-check is the unit's first check and moves the unit to `candidate` with the carried fingerprint. Include the record in final verification.
+- Treat prior rejected records as stale claims unless current evidence changes the failed trace or missing condition. An unchanged rejection suppresses only that exact claim, not review of the coverage unit.
+- Record missing or incompatible ledgers instead of treating them as empty coverage.
+
+State paths and source refs used in `run-metadata.json`. Summarize only the coverage consequences in `architecture.md`.
+
+## Architecture summary and companion selection
+
+The parent synthesizes `/architecture.md`, with a hard cap of about 1,000 words. Include:
+
+1. Product, principals, normal authority, and protected resources.
+2. The comparable-software baseline from Agent 1a, when one is source-grounded: what security trade-offs the comparable accepts. Use it to calibrate effort and severity, never to dismiss a demonstrated finding; if the comparable shares a defect pattern that has mattered in practice, that strengthens the finding. Omit this line when no meaningful comparable exists.
+3. Tech stack, source-visible deployment paths, and offline build/test limits.
+4. Entry surfaces and the important source-to-sink or lifecycle paths.
+5. Trust boundaries and the strongest source-visible control on each.
+6. Repository-relative starting paths.
+7. Prior coverage gaps, changed-source and blocked revalidation targets, and same-source confirmed exclusions.
+8. A short companion-selection summary derived from [ATTACK-CLASSES.md](ATTACK-CLASSES.md): selected files and the source-visible boundaries that require them.
+
+Keep the assignment-level ordinary block, selected companion blocks, and excluded blocks with reasons in each ledger unit, not in `architecture.md`. This keeps the architecture cap valid for large runs and makes the exact hunter prompt map machine-checkable.
+
+Do not select a companion file merely because the language or dependency name appears. Select it because reconnaissance found the trust-sensitive boundary described by its `When to use this file` section. Do not exclude a visible boundary just because another agent will review a related class.
+
+## Deterministic coverage ledger
+
+The parent writes `/coverage-ledger.json` as a top-level JSON array. Derive one unit for every material combination of entry surface, trust boundary, subsystem, and applicable ordinary or companion attack class at the granularity the run profile sets (`quick` uses one all-in-scope subsystem identity; `deep` adds lifecycle modes). For a scoped run, seed in-scope surfaces for assignment and retain discovered excluded surfaces as `out_of_scope` units so later full runs can turn them into current work.
+
+Each dimension has a human label and a stable source-derived value in `canonical_refs`. Use the same canonical reference for the same source object across runs even if its display label changes. Suitable references include a repository-relative entry path plus exported scope, a route or message identity defined in source, the source control that defines a boundary, a repository package path, and the exact attack-class block reference. A block reference is `FILE.md#` plus the exact class name as written in bold or as a heading in that file — a stable identifier matched against the file text, not a rendered HTML anchor. For companion section blocks, use the heading text before any parenthetical qualifier (for example `Core discipline`). Do not derive references by lowercasing or slugging display labels.
+
+Derive `coverage_id` without lossy slugs:
+
+1. Require every reference to be Unicode NFC with valid scalar values, visible content, no control, format, line/paragraph separator, or default-ignorable code point, and no surrounding whitespace.
+2. Encode its UTF-8 bytes with RFC 3986 percent encoding: leave only `A-Z a-z 0-9 - . _ ~` unescaped and use uppercase `%HH` for every other byte.
+3. Join encoded `surface`, `boundary`, `subsystem`, and `attack_class` references with `::`; append encoded `lifecycle` when present.
+
+Use the fixed canonical value `profile/quick/all-in-scope-subsystems` for the quick profile's coarsened subsystem dimension. Do not include wave number, agent, verdict, severity, or line number in a reference or ID. Sort units lexicographically by `coverage_id` before each assignment. Fail on every duplicate ID. If duplicate IDs have different semantic fields, treat that as a canonical identity collision; never merge or silently overwrite them. The validator also rejects one semantic tuple represented by different canonical references.
+
+Each unit records:
+
+```json
+{
+ "coverage_id": "...",
+ "canonical_refs": {
+ "surface": "src/router.ts#POST /users/:id",
+ "boundary": "src/authz.ts#requireOwner",
+ "subsystem": "packages/api",
+ "attack_class": "ATTACK-CLASSES.md#Access control"
+ },
+ "surface": "...",
+ "boundary": "...",
+ "subsystem": "...",
+ "attack_class": "...",
+ "starting_paths": ["repo/relative/path"],
+ "ordinary_attack_class_block": "ATTACK-CLASSES.md#Access control",
+ "selected_companion_blocks": ["FILE.md#section"],
+ "excluded_blocks": [{"block": "FILE.md#section", "reason": "..."}],
+ "prior_status": "new|prior_confirmed_same_source|prior_confirmed_changed_source|prior_needs_validation|prior_deferred|prior_blocked|prior_out_of_scope|prior_covered_same_source|prior_covered_changed_source|prior_rejected_claim_changed|none",
+ "attempts": [],
+ "wave": 1,
+ "status": "planned",
+ "agent_id": null,
+ "reviewed_paths": [],
+ "local_checks": [],
+ "result_fingerprints": [],
+ "unresolved": []
+}
+```
+
+When `lifecycle` is material, add both `canonical_refs.lifecycle` and a human `lifecycle` field. `ordinary_attack_class_block` is null only when no ordinary block applies. The selected companion list includes each applicable class plus its companion `Core discipline`, `Universal moves`, and `Validation rules`; `excluded_blocks` records every considered but unselected block and the source fact that excludes it.
+
+The parent may add bookkeeping fields but keeps the semantic fields above stable. In `prior_status`, `new` marks a surface first seen in this run when compatible prior ledgers exist; `none` marks a unit seeded when no compatible prior ledger is available. Prior `deferred`, `blocked`, `out_of_scope`, and changed-source units initialize as current `planned` work when now in scope. A prior same-source covered unit remains visible in the current ledger; assign changed source, important lifecycle paths, and exact conflicts first, then use the coverage critic to decide whether it needs another pass.
+
+`attempts` is an append-only archive for evidence-bearing assignments that a coverage critic reopens. Before reassignment, append the prior unit's exact `wave`, `status`, `agent_id`, `reviewed_paths`, `local_checks`, `result_fingerprints`, and `unresolved`, plus the critic's source-backed `reassignment_reason`. Only `blocked`, `covered`, and `candidate` states can be archived. Archived attempts retain the same state and evidence invariants as live units, use strictly increasing waves below the current wave, and retain their producing owners and artifacts. The next assignment increments `wave`, uses a fresh owner, and starts with empty live evidence. If the profile or budget prevents another assignment, increment `wave` and use live `deferred` state with null owner, empty evidence, and the stop reason. Never copy an archived owner's checks or artifacts into the live state. A later live terminal state contains only the new attempt's evidence; the archive remains unchanged.
+
+Enforce this state table exactly:
+
+| Status | Unit `agent_id` | `reviewed_paths` / `local_checks` | `result_fingerprints` | `unresolved` |
+|---|---|---|---|---|
+| `planned` | null | empty | empty | empty |
+| `not_applicable`, `out_of_scope`, `deferred` | null | empty | empty | nonempty reason |
+| `in_progress` | canonical owner | empty | empty | empty |
+| `blocked` | canonical owner | both nonempty owned partial evidence | empty | nonempty blocker |
+| `covered` | canonical owner | both nonempty | empty | empty |
+| `candidate` | canonical owner | both nonempty | nonempty | optional |
+
+Canonical agent IDs match `^[a-z0-9][a-z0-9_-]{0,63}$` and are not Windows device names. Lowercase is mandatory, so one ledger cannot contain case-fold aliases. The unit `agent_id` records the assignment owner. Every check records its own `agent_id` and nonempty `reviewed_paths`; the unit-level `reviewed_paths` is exactly their union. A source-only check uses `artifact: null`. A local check requires a regular file promoted only by trusted parent-side code under exactly `agents//artifacts/`. This lets hunter and verifier checks coexist in one unit. Scratch paths, output-root files, symlinks, special files, and another check owner's artifacts are not evidence.
+
+The ledger is the coverage claim. An architecture summary, agent count, or generic "auth reviewed" sentence is not coverage evidence. Phase 2 closes units only from the paths and checks in a hunter's structured result.
+
+Run `node /validate-coverage-ledger.cjs /coverage-ledger.json` after seeding, after every parent update, and before Phase 6. The validator rejects input beyond 5 MiB, 64 nesting levels, 10,000 units, 1,000 entries in a nested collection, or 500,000 traversed values, and caps reported validation errors at 100. In practice the 5 MiB byte limit holds roughly 2,000-5,000 realistic units, so it binds before the 10,000-unit cap. Fix every error before assigning work or making a coverage claim.
diff --git a/.agents/skills/security-audit/RESOURCE-EXHAUSTION-AND-AVAILABILITY.md b/.agents/skills/security-audit/RESOURCE-EXHAUSTION-AND-AVAILABILITY.md
new file mode 100644
index 00000000..6cbbd1e2
--- /dev/null
+++ b/.agents/skills/security-audit/RESOURCE-EXHAUSTION-AND-AVAILABILITY.md
@@ -0,0 +1,78 @@
+# Resource Exhaustion and Availability Hunting
+
+#### When to use this file
+
+Reach for this file when untrusted requests, messages, files, tenant state, or agent work can consume CPU, memory, disk, connections, worker slots, paid APIs, or queue capacity, or can deadlock/crash a shared service. This domain distinguishes a source-reviewable availability vulnerability from a general performance issue. Never validate by stressing a shared or live service.
+
+Use `MEMORY-SAFETY-AND-BINARY.md` for memory-integrity defects and `PROTOCOLS-RPC-AND-MESSAGING.md` for broker delivery logic. A reachable fatal error belongs here for shared impact even when the underlying parser is covered elsewhere.
+
+## Core discipline (include in every agent prompt for this domain)
+
+```
+- Require an input-to-cost path, a missing effective bound, and impact on another user, shared service, safety function, or operator-owned spend. Self-limiting work in the requester's own process is not a service vulnerability.
+- A missing rate limit is not enough. Check body/message/file caps, concurrency, queues, deadlines, database constraints, upstream gateways, and per-tenant quotas before calling a path unbounded.
+- Do not run stress, saturation, or production tests. Use asymptotic analysis, small boundary fixtures, mocked paid calls, strict local resource limits, and deterministic cancellation tests.
+- State attacker cost, service work, persistence, scope, and recovery. One bounded input with superlinear or persistent shared effect is materially different from sustained volume.
+- Use `confirmed` for source-visible bounds failures demonstrated safely. Use `needs_validation` when upstream caps, deployed topology, autoscaling, paid quota, or recovery behavior is outside the repository.
+```
+
+## Computational amplification attack classes (subagent_type: `general`)
+
+**Superlinear parsing, matching, or evaluation**
+Small accepted input drives catastrophic regex backtracking, nested parsing, recursive validation, symbolic evaluation, graph traversal, template expansion, or adversarial sort/hash behavior. Derive accepted depth/cardinality and complexity, then demonstrate a bounded growth curve locally.
+
+**Decompression and representation amplification**
+Compressed, sparse, nested, aliased, or encoded input expands far beyond the checked transfer or file size. Verify limits after every expansion and across parser stages, including archives, images, fonts, structured documents, and protocol compression tables.
+
+**Database and downstream query amplification**
+A small request creates broad scans, pathological joins, fan-out, unbounded sort/aggregation, or many downstream calls because query depth, filter cardinality, pagination, or expansion fields are not bounded. Confirm authorization does not intentionally permit the same resource scope.
+
+## Resource accumulation attack classes (subagent_type: `general`)
+
+**Unbounded buffering and cardinality**
+Bodies, out-of-order streams, uploads, sessions, unique cache keys, metrics labels, log fields, subscriptions, or pending jobs accumulate without per-item and aggregate limits. Find cleanup and expiration on disconnect, timeout, cancellation, and partial parse.
+
+**File descriptor, handle, and temporary-resource leaks**
+Malformed or canceled work misses cleanup and retains sockets, files, database cursors, timers, subprocesses, temporary files, or object references. Confirm the leak repeats through bounded local iterations and affects a shared pool.
+
+**Detached work after cancellation**
+Client timeout, disconnect, canceled job, or failed authorization returns control but leaves database, model, network, or worker work running. Trace cancellation and deadline propagation through every layer.
+
+## Quota and scheduling attack classes (subagent_type: `general`)
+
+**Pre-authentication work imbalance**
+Expensive parsing, key lookup, cryptography, decompression, or external requests happen before authentication and the earliest size/rate gate. Compare minimal requester effort to shared service cost and check upstream limits.
+
+**Quota-accounting scope and reset gaps**
+Accounting uses attacker-influenceable IP, route, tenant, key prefix, task ID, or other dimension, allowing one principal's work to escape its intended budget or consume another principal's allocation. Review integer overflow, distributed races, retries, reconnects, and account switching.
+
+**Worker, pool, and priority starvation**
+Low-priority or attacker-controlled jobs hold shared locks, workers, database pools, event-loop turns, or scheduler priority needed by unrelated users. Require a path that bypasses queue/concurrency fairness or retains a slot beyond its deadline.
+
+## Failure and recovery attack classes (subagent_type: `general`)
+
+**Reachable fatal error or deadlock**
+An untrusted input reaches `panic`, abort, fatal assertion, unhandled exception, process exit, lock cycle, or infinite loop in a shared process. Confirm supervisor scope and whether one worker or the whole service becomes unavailable. A restarted isolated worker may reduce impact but does not erase the defect.
+
+**Retry storm and fail-open amplification**
+Timeouts, dependency errors, partially processed messages, or health-check failures trigger synchronized or unbounded retries without jitter, ceilings, circuit breaking, or deduplication. Verify one bounded failure source can create persistent aggregate work.
+
+**Poison-record and head-of-line blocking**
+One malformed record or message repeatedly fails at the front of a shared queue, partition, startup scan, migration, or recovery loop. Review skip/quarantine policy, offsets, and whether other tenants share the blocked unit.
+
+**Unsafe recovery and capacity rollback**
+A restart, restore, fallback, or cleanup path rebuilds unbounded state, ignores current quotas, or restores the input that immediately repeats failure. Recovery correctness is part of availability.
+
+## Universal moves (apply across the above)
+
+- Build an input-to-resource table: earliest accepted size/cardinality, work before auth, downstream fan-out, persistence, shared pool, limit and cleanup owner, recovery.
+- Compare aggregate limits with per-object limits. Ten thousand valid one-byte items may evade a per-message cap while exhausting tenant-wide or process-wide state.
+- Validate only in an isolated fixture with strict CPU/memory/time limits and small growth points. Mock external and paid calls and stop once the missing bound or cancellation is observable.
+
+## Validation rules (apply before reporting ANY finding here)
+
+1. Name untrusted input, requester work, service amplification or retained resource, shared blast radius, and recovery. Missing limits without concrete shared impact are hardening.
+2. Confirm no source-visible upstream, parser, queue, tenant, or framework bound prevents the path. Unknown deployed controls require `needs_validation`.
+3. For superlinear behavior, establish the accepted complexity and bounded local growth. For leaks, show repeatable retention after cleanup should occur. For fatal paths, identify process/supervisor isolation.
+4. Prioritize by low requester work, unauthenticated reachability, cross-tenant scope, persistence, and poor recovery; do not validate with availability impact.
+5. Return `confirmed` only with safe local proof and meaningful shared effect. Return `needs_validation` with the exact upstream limit, topology, quota, or recovery observation an owner must check.
diff --git a/.agents/skills/security-audit/SKILL.md b/.agents/skills/security-audit/SKILL.md
new file mode 100644
index 00000000..92178dad
--- /dev/null
+++ b/.agents/skills/security-audit/SKILL.md
@@ -0,0 +1,192 @@
+---
+name: security-audit
+description: Security guidance and vulnerability review for codebases, APIs, services, CLI tools, libraries, and daemons. Use for security questions, focused reviews, vulnerability research, security audits, or pen tests. Run the complete workflow only for explicit codebase audit or pen-test requests, full/comprehensive/end-to-end reviews, or requested report artifacts.
+---
+
+# Security Audit
+
+Find vulnerabilities that violate a real trust boundary, then give owners the source evidence, safe reproduction, priority, and smallest effective fix. This is a defensive, source-first workflow. A candidate without a concrete affected principal, resource, or security outcome is not a confirmed finding.
+
+## Operating modes
+
+This skill is guidance by default. Loading it does not authorize the complete audit workflow or file creation.
+
+- **Guidance mode**: For security questions, focused reviews, methodology, triage, or investigation of specific findings, use only the relevant parts of this skill. Do not automatically run all six phases, create an output directory, or write audit artifacts. You may launch focused agents when useful; they return results to the current task.
+- **Full audit mode**: Use the complete workflow when the user explicitly asks to audit or pen-test a codebase, asks for a full, comprehensive, or end-to-end security review, or requests report artifacts. Run all six phases and write the files defined below.
+
+If the request could mean either mode, ask one focused question before creating files or starting the complete workflow.
+
+## Platform terminology
+
+This skill is agent-neutral:
+
+- **Parent** is the agent that coordinates the run and owns shared state.
+- **Task tool** is the platform's delegation or sub-agent mechanism.
+- **`research` agent** is a delegated agent for focused source exploration and factual verification.
+- **`general` agent** is a delegated agent for broad investigation and bounded local execution.
+- **`subagent_type:`** in a heading names which of these two delegated agent roles runs that work.
+
+Use equivalent platform capabilities while preserving role, write-isolation, prompt, and independence boundaries.
+
+## Universal execution safety
+
+These rules apply in both operating modes. Source inspection is read-only. Run target-controlled builds, tests, processes, browsers, emulators, fuzzers, and fixture processing only inside an OS-enforced sandbox that provides all of these controls:
+
+- no external network; use only an isolated loopback namespace when the check needs local client/server traffic;
+- an empty environment populated from an explicit allowlist with safe values, with scratch-local `HOME`, temporary directories, and caches;
+- a read-only target and toolchain, with the target-controlled process able to write only inside its assigned `scratch/` directory; and
+- explicit low CPU, memory, process, file-size, disk, and wall-clock limits.
+
+The agent, outside the target-controlled process, may make a disposable source copy in an assigned `scratch/` directory when a build must write beside source. In guidance mode, do not retain target-controlled files. In full audit mode, only trusted parent-side code may promote the minimum non-secret result to retained `artifacts/` using the procedure under Write isolation. Never expose a retained output directory (other than the agent's own assigned `scratch/`), another agent's directory, the host home directory, credentials, sockets, or shared services to target code. Do not install dependencies or let builds fetch them. Use only tools and dependencies already available locally. If every control cannot be enforced, do not execute target code: report the missing sandbox capability as a needs-validation blocker and give a safe validation plan.
+
+Use dummy principals, fixtures, and secrets. Do not probe deployed endpoints, external services, shared infrastructure, production identities, other users' data, or live control planes. Do not test availability against a live or shared process, publish artifacts, alter releases, spend paid API quota, or continue beyond the minimum local effect needed to establish a defect. If the decisive fact is outside source or the sandboxed fixture, report it as needing validation.
+
+## Full audit setup
+
+In full audit mode, resolve these values before reconnaissance:
+
+- **Skill directory**: the absolute directory containing this `SKILL.md`.
+- **Target**: the absolute repository root under review.
+- **Repo name**: a stable repository identifier from the directory or local Git remote.
+- **Output directory**: a new writable directory outside the target, defaulting to `~/security-audit-skill//run-`, where `` is the next unused integer. Use a directory inside the target only when the user explicitly selects it and the parent verifies that version control ignores the whole directory. Otherwise stop and request an external path.
+- **Source ref**: the reviewed commit and whether the worktree is dirty. Do not treat unreviewed generated or modified files as another revision.
+
+### Write isolation
+
+The parent creates and is the only writer of shared run files:
+
+- `run-metadata.json`
+- `architecture.md`
+- `coverage-ledger.json`
+- `findings.json`
+- `REPORT.md`
+- `FINDINGS-DETAIL.md`
+- `NEEDS-VALIDATION.md`
+
+Each hunter or verifier receives a unique root under `/agents//`, with separate `scratch/` and `artifacts/` directories. Canonical agent IDs match `^[a-z0-9][a-z0-9_-]{0,63}$` and must not equal a Windows device name such as `con`, `prn`, `aux`, `nul`, `com1` through `com9`, or `lpt1` through `lpt9`. Lowercase IDs prevent case-fold collisions. The agent and every target-controlled process may write only to `scratch/`; retained `artifacts/` is parent-owned, is never exposed to the sandbox, and is writable only by trusted parent-side promotion code. Agents may not change shared files, target source, retained artifacts, or another agent's directory. Do not use `/tmp` or the host home directory as a writable fallback.
+
+Before execution, the parent opens and retains trusted, non-inheritable directory descriptors for the agent's `scratch/` and `artifacts/` roots, and records an allowlist of expected scratch-relative artifact files plus explicit per-file and cumulative byte limits. Never pass those descriptors to the agent or sandbox. After the sandbox and all its processes terminate, trusted parent-side code promotes each allowlisted file separately:
+
+1. Validate the declared relative path: reject absolute, empty, `.`, `..`, or symlinked components.
+2. Walk each parent component from the retained scratch-root descriptor with no-follow directory-relative operations; never reopen by path.
+3. Open the leaf no-follow and nonblocking.
+4. Verify with `fstat` that it is a regular file with link count exactly one and within the recorded per-file and cumulative byte limits.
+5. Enforce those limits again while reading from that descriptor.
+6. Copy exactly the verified size, repeat `fstat`, and reject a changed identity, type, link count, or size.
+7. For the destination, walk every parent component from the retained artifacts-root descriptor with no-follow directory-relative operations; require each existing component to be a real directory, and create any missing directory exclusively before reopening and verifying it no-follow.
+8. Create the leaf exclusively without following links, verify that the opened destination is a regular file with link count exactly one, and copy from the verified source descriptor without reopening either path.
+9. Use equivalent race-safe APIs on non-POSIX systems.
+10. Never recursively copy or glob scratch, extract an archive into artifacts, or open or promote a symlink, FIFO, socket, device, directory, hard-linked file, changing file, or file that exceeds its bound.
+11. If any check is unavailable, cannot be enforced, or fails, discard the scratch entry; if it is decisive evidence, retain `needs_validation` with the exact promotion blocker.
+
+[HUNTING.md](HUNTING.md) and [VALIDATION-AND-REPORTING.md](VALIDATION-AND-REPORTING.md) carry this procedure as one identical fenced block for hunter and verifier prompts; it states the same rules in the same order as this list.
+
+For a reproduced check, record the command, exact test input, sandbox limits, and only the allowlisted environment variable names plus safe non-secret values needed to reproduce it. Never capture or copy the ambient environment, inherited variables, credential values, authentication state, or unrelated host paths. Launch from an empty environment rather than trying to redact one after execution.
+
+Before delegation, the parent writes `run-metadata.json` with at least `run_id`, `repo`, `target`, `source_ref`, `profile`, `scope_paths`, `budget` (null if unset), `execution_policy: "sandboxed-source-and-local-only"`, selected companion files, prior-run paths, shared-file owners, and `run_status: "in_progress"`. Update metadata only when those facts change; candidate state belongs in the coverage ledger and `findings.json`.
+
+## Full audit planning
+
+The coverage, prior-run, profile, and budget requirements in this section apply only in full audit mode.
+
+### Coverage and prior runs
+
+No one pass is complete. Build a deterministic coverage plan before hunting and update it after every agent result. [RECONNAISSANCE.md](RECONNAISSANCE.md) defines the stable coverage units and [HUNTING.md](HUNTING.md) defines coverage-critic waves. The parent alone updates the ledger.
+
+If prior runs exist, read every compatible `coverage-ledger.json` and `findings.json` before planning the current run:
+
+1. Compare the relevant current source with each prior record and unit. A prior source ref alone is not evidence that a path is unchanged.
+2. Carry a prior `confirmed` record into the current candidate set only when its relevant source and conditions are unchanged and its evidence still meets the current contract. Link it to a current ledger unit seeded `planned`, preserve its fingerprint, exclude only that carried root cause from hunters, and send the carried record through the current final verification path; the Phase 3 verifier that re-checks it becomes that unit's assignment owner and moves it to `candidate`.
+3. When relevant source for a prior `confirmed` record changed, create a current planned revalidation unit. Do not put that record on the hunter exclusion list. It remains confirmed only if current independent validation establishes the current path and result.
+4. Make prior `needs_validation`, `deferred`, `blocked`, `out_of_scope`, and any changed-source unit current work. A still-external `needs_validation` record may be carried only after the current source trace is checked and linked by fingerprint to a current `planned` unit whose verifier re-check supplies its owner and evidence; the record keeps the unresolved blocker. These prior states never suppress a current unit.
+5. A prior same-source covered unit may inform priority, but it remains visible in the current ledger. A prior `rejected` record suppresses only the unchanged failed claim, not coverage of its unit; changed evidence creates current work.
+6. Read the prior profile and scope. A prior `quick` or scoped ledger contributes only its recorded evidence and gaps, never an implied "rest is fine."
+
+If no prior ledger exists, say so in the final coverage statement. Never imply that one run exhausts the target.
+
+### Run profiles and scope
+
+During full audit setup, pick a profile from the user's request or propose one from the target's size and stakes. Record it in `run-metadata.json` (`profile`, `scope_paths`) and state it in the report. The default is `standard`.
+
+- **`quick`** — a bounded pass for small targets, re-runs, or a fast first look. Coarsen ledger units to surface × boundary × attack class (subsystem uses the fixed canonical `profile/quick/all-in-scope-subsystems` identifier), run exactly one hunter wave followed by exactly one final coverage-critic pass, and use one fresh verifier per candidate for both candidate validation and final record verification. Do not launch a follow-up hunter wave: record the critic's accepted discoveries and reassignments as `deferred`.
+- **`standard`** — the workflow as written.
+- **`deep`** — for high-stakes or large targets. Split ledger units per subsystem and lifecycle mode, run critic waves to a clean pass, keep candidate validation and final record verification as separate fresh agents, and give `prior_covered_same_source` units an independent second pass.
+
+A **scoped run** audits a subset: named paths, one subsystem, one companion domain, or the diff between two source refs. Seed ledger units only for in-scope surfaces and record everything else as `out_of_scope` — never as `covered`. A scoped or `quick` run must present itself as partial coverage.
+
+Profiles change breadth and redundancy, never the evidence bar. Do not scale away the candidate gate, the source/local execution boundary, `needs_validation` discipline, schema validation, or independent verification of `confirmed` records.
+
+#### Cost budget
+
+The ledger makes spend countable: one unit is roughly one hunter assignment, and one surviving candidate is one or two verifier assignments depending on profile. When the user sets a budget — or the parent proposes one for a large target — record `budget` in `run-metadata.json` as a maximum number of agent invocations across all phases.
+
+Apply the strict budget gate before launching any reconnaissance agent. Reserve the four baseline reconnaissance calls, one final post-wave critic for `quick` or one post-wave plus one distinct final-clean critic for `standard`/`deep`, and at least one verifier call. Add focused reconnaissance only after repeating this gate for each extra call. If the requested budget cannot fund that minimum, launch no agent: ask for a larger budget, narrower scope, or different profile. If the request remains unchanged, set `run_status: "incomplete"` with `incomplete_reason: "budget_cannot_fund_reconnaissance_and_reserves"` and report that no audit pass ran.
+
+Spend it in this order:
+
+1. Count reconnaissance, every post-wave critic, and the separate final-clean critic as agent invocations.
+2. **Reserve critics and validation before hunting.** For `quick`, reserve its one post-wave final critic. Before every `standard` or `deep` hunter wave, reserve one immediate post-wave critic plus one distinct final-clean critic. Also reserve verifier cost from the profile (about 1 or 2 agents per expected candidate; when in doubt reserve 30% of the balance after critic reservation). Never assign hunters into either reserve.
+3. Assign hunters to units in priority order until the hunting allowance is spent. Spend the reserved post-wave critic immediately after that wave; keep the final-clean and validation reserves intact.
+4. Before a later wave, reserve its new post-wave critic again. If the remaining budget cannot cover the required critic calls and validation reserve, launch no hunters from that wave, mark its planned units `deferred` with reason `budget_cannot_reserve_critics_and_validation`, and use the retained final-clean critic to record the resulting gap.
+
+Before wave 1, update the pre-recon estimate with seeded units, implied hunter count, mandatory critic calls, validation reserve, and whether the remaining budget covers the plan. If it clearly cannot, say so and propose either a tighter scope or a coarser profile instead of silently thinning evidence. If later facts consume the required final-critic reserve, launch no hunters, mark all planned work deferred, set the run incomplete with reason `critic_budget_exhausted`, and make no complete-coverage claim.
+
+A strict total-agent budget can still be exceeded by an unexpectedly large candidate set or by a material Phase 5 replacement that needs another independent verifier. If the remaining budget cannot validate every candidate, stop hunting, validate candidates in fingerprint order while the budget permits, and set `run_status: "incomplete"` plus `incomplete_reason: "validation_budget_exhausted"`. Keep each unvalidated fingerprint linked to a `candidate` ledger unit with that unresolved reason. Do not put an unvalidated candidate in `findings.json`, relabel it `needs_validation`, or report the run as complete. Phase 6 may produce a partial report only if its first section states that candidate validation is incomplete and lists the affected fingerprints and units. Never exceed a user-set strict budget silently.
+
+## Core principles
+
+### Require a boundary and result
+
+For every candidate, name the lower-trust principal, accepted input or action, intended control, crossed boundary, affected principal or resource, and concrete observed or owner-observable result. Do not elevate a missing best practice, guessed deployment behavior, generic parser crash, or self-impact into a security finding.
+
+### Use bounded local evidence
+
+Static analysis establishes the source path. Sandboxed local tests resolve behavior when all execution controls are available: a minimal function harness, existing unit test, small parser fixture, dummy-tenant integration test, locally rendered configuration, or bounded isolated-loopback client. Stop at a wrong return value, unauthorized dummy record, sanitizer finding, policy difference, or other minimum effect. Do not extend the local check beyond the minimum boundary result or produce persistence, post-fault, or concealment material.
+
+### Respect source visibility
+
+Deployment controls, proxy behavior, provider settings, browser headers, identity policy, broker ACLs, packaging, and topology are real controls. If they are required and absent from the repository, do not assume either presence or absence. Use `needs_validation` with the exact missing fact and a safe owner-observed or local plan.
+
+### Separate priority from certainty
+
+Only `confirmed` records receive severity. Likelihood and impact must reflect the demonstrated conditions and result; overall severity cannot exceed demonstrated impact. `needs_validation` means a specific source-grounded boundary hypothesis is blocked, not a low-confidence confirmed vulnerability, and it has no severity.
+
+Calibrate overall severity with these anchors:
+
+- **critical** — an unauthenticated actor gains code execution, full data-store access, or takeover of arbitrary accounts.
+- **high** — an actor fully defeats an explicit security control with real consequences: authentication bypass, cross-tenant read or write, stored script execution affecting other users, authenticated code execution, or an unauthenticated remote stop of a shared service.
+- **medium** — a real boundary violation with limited blast radius, uncommon preconditions, or consequences confined to a narrow resource set.
+- **low** — disclosure of non-secret internals, or an effect requiring sustained effort for minimal gain.
+- **informational** — a confirmed but minimal-impact observation, useful mainly as a prerequisite inside a larger finding.
+
+The high/medium discriminator: does the demonstrated result fully defeat an explicit control for an action with real consequences, or only weaken it? If you cannot state the concrete damage, the severity is lower than it feels.
+
+### Recommend the smallest effective source fix
+
+For each confirmed finding, identify the invariant the code must enforce and the narrowest source change that enforces it at the last trusted decision point. Prefer specific repository-relative changes and regression tests over generic hardening advice. The audit describes fixes; it does not modify target source.
+
+## Full audit workflow
+
+In full audit mode, follow all six phases in order:
+
+1. **Reconnaissance** — map the source, trust boundaries, local build paths, companion selections, prior evidence, and initial deterministic coverage ledger with [RECONNAISSANCE.md](RECONNAISSANCE.md).
+2. **Coverage-led hunting waves** — assign isolated hunters from the ledger and collect structured candidate results with [HUNTING.md](HUNTING.md), [ATTACK-CLASSES.md](ATTACK-CLASSES.md), and the selected domain companions.
+3. **Candidate validation** — consolidate fingerprints and give every candidate to a fresh source verifier as defined in [VALIDATION-AND-REPORTING.md](VALIDATION-AND-REPORTING.md).
+4. **Structured output** — write all final `confirmed`, `needs_validation`, and `rejected` records to `findings.json`; validate it with `report-schema.json` and `validate-findings.cjs`, and validate the coverage claim with `validate-coverage-ledger.cjs`.
+5. **Independent record verification** — use fresh agents to verify final source claims and reconcile corrections or state changes.
+6. **Target-neutral report** — derive `REPORT.md`, `FINDINGS-DETAIL.md`, and `NEEDS-VALIDATION.md` from the final records, with no live-probe instructions.
+
+Do not end the run before one of exactly two terminal states: (a) all Phase 6 artifacts are written and both validators pass, or (b) `run_status: "incomplete"` is recorded with its exact reason and the gap is disclosed in the report. Never stop mid-phase.
+
+## Anti-patterns
+
+1. Checklist deviations presented as vulnerabilities.
+2. Defense-in-depth advice with no reachable boundary violation.
+3. Live or shared-environment testing where bounded local evidence is insufficient.
+4. Guessing provider, proxy, browser, identity, or deployment behavior not present in source.
+5. Treating intended same-principal authority or self-impact as a cross-boundary result.
+6. Reporting a parser or runtime effect stronger than the observed effect.
+7. Emitting prose-only hunter results that cannot be deduplicated or verified.
+8. Re-reporting carried same-source prior confirmed records or using them as exemplars that anchor the hunt.
+9. Assigning severity to `needs_validation` records.
+10. Writing the report before independent verification or letting prose and JSON disagree.
diff --git a/.agents/skills/security-audit/SUPPLY-CHAIN-AND-RELEASE.md b/.agents/skills/security-audit/SUPPLY-CHAIN-AND-RELEASE.md
new file mode 100644
index 00000000..bf96aed0
--- /dev/null
+++ b/.agents/skills/security-audit/SUPPLY-CHAIN-AND-RELEASE.md
@@ -0,0 +1,73 @@
+# Supply Chain and Release Hunting
+
+#### When to use this file
+
+Reach for this file when the target resolves dependencies, builds from untrusted contributions, runs CI, creates release artifacts, signs or promotes builds, loads plugins, or updates deployed software. This domain covers trust handoffs from source and dependency to the artifact a user runs. Use `MEMORY-SAFETY-AND-BINARY.md` for flaws inside a local binary loader and `CLOUD-AND-DEPLOYMENT.md` for runtime workload authority.
+
+Split large targets into dependency resolution, CI isolation, artifact provenance, release authorization, and updater/plugin trust.
+
+## Core discipline (include in every agent prompt for this domain)
+
+```
+- A mutable or known-vulnerable dependency is not a finding by itself. Show who can influence resolution, which build consumes it, and what execution or release boundary follows.
+- Follow integrity across every handoff: source identity, resolved inputs, build worker, artifact identity, test result, signature/attestation, promotion, and update consumer.
+- CI configuration is authorization code. Establish which event triggered a workflow, whose code runs, which secrets and tokens exist, and what it may publish or mutate.
+- A checksum fetched from the same untrusted location as the artifact does not establish independent integrity. Identify the trusted root and failure behavior.
+- Use `confirmed` for in-repo control-flow failures with bounded local validation. Use `needs_validation` for branch protection, hosted-runner, registry, signing-service, or production promotion facts that are not observable.
+```
+
+## Dependency and build-input attack classes (subagent_type: `general`)
+
+**Dependency source and namespace confusion**
+Resolver configuration can select an unintended public/private namespace, fallback registry, mirror, repository, or source URL. Review package names, source priority, lockfile and checksum use, alternate build files, platform-specific resolution, and first-install versus update behavior.
+
+**Mutable and unbound build inputs**
+Builds consume branches, tags, unverified submodules, downloaded tools, generated assets, remote includes, floating CI actions, or container tags whose content can change without source review. Require a lower-trust writer and a path into trusted build output; reproducibility by itself does not prove authenticity.
+
+**Generated-source and codegen provenance gaps**
+Schemas, vendored archives, generated clients, localization, documentation examples, or binary blobs produce executable or shipped content without the same review and integrity gate as source. Compare local regeneration with committed output and verify who controls input and generator.
+
+**Build-context inclusion**
+Secrets, local configuration, repository metadata, test fixtures, or developer artifacts enter a package or image because the build context and ignore rules exceed intended release inputs. Confirm that the resulting artifact exposes a real credential, private data, or privileged configuration.
+
+## CI and automation attack classes (subagent_type: `general`)
+
+**Untrusted code in a privileged workflow**
+A pull request, issue comment, fork, dependency update, or external event runs contributor-controlled code with protected secrets, write tokens, deployment authority, or a trusted runner. Compare trigger type, checkout ref, approval gate, environment protection, and permission narrowing. Do not assume repository-host defaults that are not in source.
+
+**Workflow command and expression confusion**
+Attacker-controlled branch names, commit messages, issue fields, artifact names, matrix values, or generated output enter shell commands, template expressions, paths, or privileged workflow inputs without canonical validation.
+
+**Cache, artifact, and workspace trust mixing**
+A lower-trust job can populate a cache, artifact, shared workspace, or output that a higher-trust job later restores and executes or releases. Review cache keys and namespaces, artifact producer identity, digest binding, retention, and whether promotion re-resolves by mutable name.
+
+**Automation identity overreach**
+CI jobs receive permissions beyond the operation, repository, environment, or duration needed, and untrusted job inputs can select the affected resource. Missing least privilege alone is hardening; require a reachable privileged action.
+
+## Release and update attack classes (subagent_type: `general`)
+
+**Build-to-promotion substitution**
+Tests, review, signature, and publication refer to mutable tags, filenames, channels, or artifact IDs rather than the same immutable digest. Check every copy, repack, architecture merge, and provenance step between build and release.
+
+**Release authorization and signing-policy gaps**
+A release or signature is accepted from the wrong workflow, repository, branch, environment, key role, or threshold. Review identity claims inside attestations and verify the consumer validates them, not just a valid signature. Rotation, expiry, and revocation must fail closed where policy requires.
+
+**Update metadata and rollback confusion**
+An updater authenticates payload bytes but not version, product, platform, channel, target path, expiry, or rollback state, or it accepts metadata and payload from different authorized transactions. Verify atomic installation and recovery behavior. A signature API call without policy binding is incomplete.
+
+**Plugin and extension trust expansion**
+An extension package gains host authority beyond its declared scope, a lower-trust publisher can replace another publisher's identity, or install/update hooks run before authenticity and capability checks. Intended installation of arbitrary same-user plugins is not a privilege boundary.
+
+## Universal moves (apply across the above)
+
+- Walk backward from a released digest or installed update to every source, generated input, credential, worker, cache, test result, and authorization decision.
+- Compare untrusted and protected workflow events side by side. Mark each persisted channel crossing between them and require an immutable identity plus producer trust.
+- Review revoked key, failed download, missing attestation, partial platform release, rollback, and registry outage paths. The failure policy is part of release integrity.
+
+## Validation rules (apply before reporting ANY finding here)
+
+1. Name the lower-trust actor, controllable source/cache/artifact/metadata, consuming trusted job or updater, and resulting unauthorized publication, code inclusion, secret disclosure, or privileged execution.
+2. Prove artifact identity across the broken handoff. A different mutable name or unbound digest must reach a real consumer.
+3. Verify built-in package-manager, repository-host, registry, and signing defaults for the pinned version. Unknown hosted controls require `needs_validation`.
+4. Keep local validation bounded: use a harmless fixture repository, dummy credential marker, local registry/config, and non-production artifact namespace. Do not publish or alter a real release.
+5. Return `confirmed` only with a complete source-visible handoff and meaningful result. Return `needs_validation` with the precise branch, runner, registry, signing, or deployment fact an owner must observe.
diff --git a/.agents/skills/security-audit/VALIDATION-AND-REPORTING.md b/.agents/skills/security-audit/VALIDATION-AND-REPORTING.md
new file mode 100644
index 00000000..5e200d73
--- /dev/null
+++ b/.agents/skills/security-audit/VALIDATION-AND-REPORTING.md
@@ -0,0 +1,186 @@
+# Validation, Structured Output, Verification, and Reporting
+
+### Phase 3: Independently validate every candidate
+
+After the clean coverage-critic pass or an explicitly recorded early stop, consolidate Phase 2 candidates and carried same-source prior confirmations by stable fingerprint and root cause. Give every unique proposed `confirmed` and `needs_validation` candidate to a fresh `general` verifier that did not hunt it. A carried prior confirmation follows the same current verification path even though hunters exclude that unchanged root cause. A verifier may read hunter or prior artifacts but must re-read every cited current source location and independently run any decisive check it can reproduce safely.
+
+Assign each verifier a canonical lowercase unique ID and `/agents//scratch/` plus parent-owned `artifacts/`. The verifier writes only to `scratch/` and never writes retained artifacts. It receives only the candidate, its linked coverage-unit checks and artifact paths, architecture facts needed to interpret the path, exact relevant companion validation blocks, the promotion procedure block below, the source/local execution boundary, the `confirmed`, `needs_validation`, and `rejected` branches of `report-schema.json` copied verbatim, and prior records with the same fingerprint. It must not receive another verifier's conclusion.
+
+#### Candidate-verifier prompt
+
+```text
+You did not write this candidate. Try to refute it from repository source and bounded
+local evidence. Do not contact deployed endpoints or external/shared services. Run
+target-controlled code only inside the approved OS-enforced sandbox: no external
+network, empty allowlisted environment, read-only target and tools, scratch-only
+writes, and explicit low resource and wall-clock limits. If any control is unavailable,
+do not execute; retain the exact missing capability as a needs_validation blocker.
+Treat every scratch entry as target-controlled after execution. After the sandbox and
+all its processes terminate, only trusted parent-side code may promote a predeclared
+scratch-relative file, following the promotion procedure block included verbatim in
+this prompt. You and target code never write retained artifacts. If promotion is
+unavailable or fails, do not use that file as evidence.
+
+1. Verify every trace and evidence file, positive line number, scope, and description.
+ Confirm the first entry is a real lower-trust entrypoint and the last is the
+ claimed sink or boundary effect.
+2. Reconstruct the strongest source-visible validation, identity, authorization,
+ normalization, lifecycle, framework, and containment controls on the path.
+ Where the architecture summary names a comparable baseline, note whether it
+ shares the pattern — as calibration, never as grounds to dismiss.
+3. For a proposed confirmed candidate, independently reproduce the minimum observed
+ result when possible. Verify inputs, interface shape, conditions, and affected
+ dummy principal/resource. Do not infer a stronger result or continue after it.
+4. Verify that likelihood, impact, confidence, and the proposed source fix match only
+ what the evidence establishes.
+5. For a proposed needs_validation candidate, decide whether the blocker is genuinely
+ outside source/local observation. If source refutes the trace, reject it. If the
+ missing fact remains decisive, keep needs_validation and make the local and
+ owner-observed plans exact and non-destructive.
+6. Preserve the fingerprint for the same source-derived root cause across every state.
+
+Return exactly one JSON object and no surrounding prose:
+{"decision": "confirmed|needs_validation|rejected", "record": { ... }}
+where record exactly matches the decision's verdict branch of the schema included
+in this prompt. A corrected record replaces the hunter's wording.
+```
+
+Copy this promotion procedure verbatim into every candidate-verifier prompt:
+
+```text
+Artifact promotion procedure (trusted parent-side code only):
+Reference only for you: the parent performs these steps; you never perform them.
+
+Before execution, the parent opens and retains trusted, non-inheritable directory
+descriptors for the agent's scratch/ and artifacts/ roots, and records an allowlist
+of expected scratch-relative artifact files plus explicit per-file and cumulative
+byte limits. Never pass those descriptors to the agent or sandbox. After the sandbox
+and all its processes terminate, trusted parent-side code promotes each allowlisted
+file separately:
+
+1. Validate the declared relative path: reject absolute, empty, `.`, `..`, or
+ symlinked components.
+2. Walk each parent component from the retained scratch-root descriptor with
+ no-follow directory-relative operations; never reopen by path.
+3. Open the leaf no-follow and nonblocking.
+4. Verify with `fstat` that it is a regular file with link count exactly one and
+ within the recorded per-file and cumulative byte limits.
+5. Enforce those limits again while reading from that descriptor.
+6. Copy exactly the verified size, repeat `fstat`, and reject a changed identity,
+ type, link count, or size.
+7. For the destination, walk every parent component from the retained
+ artifacts-root descriptor with no-follow directory-relative operations; require
+ each existing component to be a real directory, and create any missing directory
+ exclusively before reopening and verifying it no-follow.
+8. Create the leaf exclusively without following links, verify that the opened
+ destination is a regular file with link count exactly one, and copy from the
+ verified source descriptor without reopening either path.
+9. Use equivalent race-safe APIs on non-POSIX systems.
+10. Never recursively copy or glob scratch, extract an archive into artifacts, or
+ open or promote a symlink, FIFO, socket, device, directory, hard-linked file,
+ changing file, or file that exceeds its bound.
+11. If any check is unavailable, cannot be enforced, or fails, discard the scratch
+ entry; if it is decisive evidence, retain `needs_validation` with the exact
+ promotion blocker.
+```
+
+A verifier can promote `needs_validation` to `confirmed` only after independently establishing the complete path and bounded observed result. Demote proposed confirmation to `needs_validation` when a specific deployment or runtime fact remains unknown. Use `rejected` when source, local behavior, a visible control, missing meaningful impact, or an impossible prerequisite refutes the claim. `needs_validation` is never a parking place for a speculative idea.
+
+The parent checks that each verifier returned the same fingerprint unless it identified a genuinely different root cause. Merge corrections, record the decision in every linked coverage unit, and ensure there is one final record per fingerprint. Discard a malformed or prose-wrapped verifier result without repairing it; re-run that candidate with a fresh verifier when the budget permits, otherwise it remains an unvalidated ledger candidate under the incomplete-run rule.
+
+When verifier evidence updates a ledger check, set that check's `agent_id` to the verifier's canonical ID and list its nonempty repository-relative `reviewed_paths`. Keep the unit-level `reviewed_paths` equal to the union across checks. Use `method: "source"` with `artifact: null` for source-only review. Use `method: "local"` only with a file successfully promoted by trusted parent-side code below `agents//artifacts/`. The unit retains its original assignment owner, so independently owned hunter and verifier checks can coexist. For a carried prior record's seeded `planned` unit there is no prior owner: the verifier that re-checks it becomes the unit's assignment owner, and its re-check is the unit's first check, moving the unit to `candidate` with the carried fingerprint.
+
+If a strict total-agent budget cannot cover every candidate, set the run status to incomplete and follow the deterministic budget rule in `SKILL.md`. An unvalidated candidate remains only in the ledger. It does not enter `findings.json` under any verdict.
+
+### Phase 4: Write and validate `findings.json`
+
+The parent writes all independently decided records to `/findings.json`, sorted by fingerprint. Include:
+
+- `confirmed`: source-grounded vulnerabilities with complete local execution evidence, conditions, specific remediation, likelihood/impact/overall severity, and confidence.
+- `needs_validation`: source-grounded candidates with an exact unresolved blocker and at least one applicable local or owner-observed deployment plan.
+- `rejected`: source-grounded candidates disproved during validation, retained so future runs do not repeat the unsupported claim without changed evidence.
+
+Read `report-schema.json` immediately before writing. It uses `additionalProperties: false`; do not carry hunter wrapper fields into a record. Keep these verdict contracts distinct:
+
+- A `confirmed` record uses `root_cause`, `intended_behavior`, `conditions`, `execution`, `remediation`, `severity`, and `confidence`. It must not use `claimed_root_cause`, `blockers`, `validation_plan`, or `reason`. `execution` is target-neutral and uses the target's native interface: API/HTTP input, CLI call, library call, message, file fixture, browser action, rendered policy, or local harness as applicable. `observed_result` is nonempty and factual.
+- A `needs_validation` record uses `claimed_root_cause`, `trace`, `evidence`, `blockers`, and at least one nonempty `validation_plan.local` or `validation_plan.deployment` field. Include both only when both contexts can resolve distinct facts. It must not use severity, execution, remediation, reason, or confirmed root cause.
+- A `rejected` record uses `claimed_root_cause`, `trace`, `evidence`, and `reason`. It must not use severity, execution, remediation, blockers, validation plan, or confirmed root cause.
+
+Every record has a stable fingerprint, title, description, and repository-relative source paths. A multi-step trace begins with `entrypoint`, ends with `sink`, and uses `propagation` only between them. One-entry traces use `entrypoint` or `sink`. Overall severity cannot exceed demonstrated impact.
+
+Run:
+
+```sh
+node /validate-findings.cjs /findings.json
+node /validate-coverage-ledger.cjs /coverage-ledger.json
+```
+
+Fix every structural and semantic error before continuing. The findings validator rejects input beyond 5 MiB, 1,000 top-level findings, or 64 nesting levels, and caps reported error output at 100 messages. Validator success proves format and ledger consistency only.
+
+### Phase 5: Verify the final records with fresh eyes
+
+Launch one fresh `research` verifier per final `confirmed` and `needs_validation` record, in parallel. This verifier checks the structured record, not the hunter write-up, and remains inside source/local boundaries.
+
+In a `quick` run, Phase 3 and Phase 5 merge: the Phase 3 verifier also performs these record checks and returns the final schema-shaped record, so each candidate gets one fresh independent reviewer instead of two. Every other profile keeps the two passes separate. Never skip independent review of a `confirmed` record in any profile.
+
+For `confirmed`, require it to check:
+
+1. Every repository-relative trace/evidence path, line, scope, and described operation.
+2. Real entry interface and exact local input shape.
+3. Every condition, parser/policy step, source-visible preventing layer, and observed local result.
+4. Affected principal/resource and demonstrated impact.
+5. Severity separation: realistic likelihood, demonstrated impact, overall no greater than impact.
+6. Remediation strategy and any `code_changes`, including whether the fix enforces the invariant without merely moving trust.
+
+For `needs_validation`, require it to check:
+
+1. The source path is real and supports only the `claimed_root_cause` stated.
+2. Every listed blocker is decisive and not already answerable locally.
+3. The candidate names a boundary and a possible concrete result rather than a generic concern.
+4. At least one validation-plan field is present and exact. `local` uses a bounded fixture; `deployment` asks an owner to observe a configuration, identity, route, policy, or runtime fact. Do not invent a plan for an inapplicable context, and never send audit traffic to a deployment.
+5. The fingerprint matches prior/current records for the same root cause.
+
+Each verifier returns exactly one JSON object: `{"decision":"verified","fingerprint":"..."}` or `{"decision":"replace","reason":"...","record":{...}}`, with no surrounding prose. A replacement record must match its `confirmed`, `needs_validation`, or `rejected` schema branch. Treat a malformed or prose-wrapped Phase 5 result the same way as in Phase 3: discard it without repairing it and re-run with a fresh verifier when the budget permits.
+
+Do not apply a Phase 5 replacement as final when it promotes a record to a stronger verdict, including any promotion to `confirmed`, or materially changes the root cause, trace, execution input or observed result, demonstrated impact, or severity. Give that complete replacement to a new independent verifier that did not hunt, perform Phase 3 validation, or propose the Phase 5 replacement. The new verifier rechecks the current source and independently reproduces any decisive local result under the execution boundary, then returns `verified` or another replacement. Apply a material replacement only after this fresh verification. If another material replacement results, repeat with a fresh verifier. If budget or independence is unavailable, remove the disputed record from `findings.json`, keep its ledger unit as an unresolved candidate, and set `run_status: "incomplete"` with an exact `incomplete_reason`. Non-material wording or repository-line corrections may be applied directly when they do not change meaning or evidence.
+
+After every applied replacement, rerun both validators and update linked ledger decisions. If a final verifier identifies a separate root cause, assign a new fingerprint and send it through independent candidate validation before inclusion. Set `run_status: "complete"` only when every ledger candidate has an independent final disposition and every retained record passes Phase 5.
+
+Do not verify only `confirmed` records. A misleading `needs_validation` handoff wastes owner time and can preserve a false premise.
+
+### Phase 6: Produce target-neutral reports from final records
+
+Only after Phase 5 passes for every record retained in `findings.json`, derive prose from the final records, the ledger, and the hunter `hardening` notes retained in ledger bookkeeping. An incomplete run may report independently verified records, but it must identify each unresolved ledger candidate and must not present it as a finding. The prose files never change a verdict, severity, blocker, or demonstrated impact.
+
+#### `REPORT.md`
+
+Write:
+
+1. Run profile, scope, budget (if set) with agents spent versus planned, source ref, sandboxed source-and-local-only execution statement, prior-run use, and explicit deferred and out-of-scope coverage. Name carried same-source confirmations and changed-source revalidations. A `quick`, scoped, budget-limited, or incomplete run states plainly that it is a partial pass. If candidate validation exhausted a strict budget, state that the run is incomplete and list every unvalidated fingerprint and linked unit; do not describe those candidates as findings. If the budget prevented a mandatory critic, state which critic did not run and make no clean-coverage claim.
+2. One short security posture summary.
+3. A confirmed-findings table: severity, title, affected boundary, and one-line observed result.
+4. Each confirmed finding: repository source location, lower-trust principal, target-native bounded reproduction, conditions, actual result, impact, priority rationale, and smallest source fix.
+5. A separate `NEEDS VALIDATION` table. Give each lead's title, repository trace, exact blocker, bounded local next step, and safe owner-observed deployment check. Do not assign severity or call it a confirmed vulnerability.
+6. Separate hardening notes and positive source patterns.
+7. Coverage summary from the ledger: covered, candidate, blocked, and deferred counts, plus important exclusions and the final critic result.
+
+Do not describe rejected records as findings. Mention their fingerprints only when they explain a prior disagreement or coverage decision.
+
+#### `FINDINGS-DETAIL.md`
+
+For each confirmed `medium`, `high`, or `critical` record, copy the complete source path and target-neutral local reproduction:
+
+- ordered repository-relative trace and evidence;
+- dummy attacker/principal and affected dummy resource;
+- native input, invocation, or fixture and exact bounded instructions;
+- observed output and the security invariant it proves;
+- conditions and containment;
+- source-level remediation and regression case.
+
+#### `NEEDS-VALIDATION.md`
+
+For every unresolved record, copy the source trace, verified evidence, exact blocker, affected boundary, and each applicable bounded local or owner-observed resolution plan. Keep these as prioritized leads without severity. Do not turn them into live test guidance or assume the missing deployment fact.
+
+HTTP is one possible native interface, not the default. A library finding may use a function call, a parser a fixture, a CLI a command, a desktop app an IPC or file action, and infrastructure a locally rendered policy. Do not require an endpoint, external account, or live environment that the target does not have.
+
+Keep the report proportional to the evidence. A clean run may have zero confirmed records. State that result and the remaining coverage/validation limits without inventing LOW findings.
diff --git a/.agents/skills/security-audit/WEB-PROTOCOL-AND-AUTH.md b/.agents/skills/security-audit/WEB-PROTOCOL-AND-AUTH.md
new file mode 100644
index 00000000..1a099fa5
--- /dev/null
+++ b/.agents/skills/security-audit/WEB-PROTOCOL-AND-AUTH.md
@@ -0,0 +1,105 @@
+# HTTP-Protocol and Authentication Hunting
+
+#### When to use this file
+
+Reach for this file when the target speaks HTTP at a parsing, caching, browser-authentication, or identity boundary: web applications, APIs, reverse proxies, CDNs, gateways, custom HTTP servers, and services implementing sessions, JWT, OAuth/OIDC, SAML, password recovery, MFA, passkeys, API keys, or mTLS. Use this with `ATTACK-CLASSES.md`: access-control review asks whether a principal may perform an operation; this file asks whether the HTTP or identity layer can confuse which principal, request, assurance level, or token the operation belongs to.
+
+Pick classes from Phase 1. Split a large target into request framing and cache policy, browser authentication, federated identity, strong authentication and recovery, service credentials, and session lifecycle. A single server behind an unobserved managed proxy has little source-confirmable smuggling surface; a proxy or custom parser has much more.
+
+## Core discipline (include in every agent prompt for this domain)
+
+```
+- Framing and cache findings require two interpretations of the same request, response, or key. Name both components and the exact normalized value on each side.
+- For every credential, find the signature or secret verification and every binding required for its role: issuer, audience, origin, RP, client, session, principal, resource, assurance, expiry, and one-time state.
+- Host, Forwarded, X-Forwarded-*, Origin, Referer, redirect targets, callback state, and request-derived URLs are trust decisions. Trace each to the affected identity or response.
+- A missing header, cookie attribute, MFA prompt, or rate limit is not a finding alone. Require an accepted invalid request, cross-principal impact, assurance downgrade, or credential disclosure.
+- Classify `confirmed` only from complete source evidence and bounded local request/token tests. Use `needs_validation` when proxy, IdP, browser, certificate, secret, or deployed configuration is required but not visible.
+```
+
+## HTTP framing and cache attack classes (subagent_type: `general`)
+
+**Request framing and desynchronization**
+Front end and back end disagree on request length or header normalization. Review multiple `Content-Length` values, `Transfer-Encoding`, HTTP/2 or HTTP/3 downgrade, header-name normalization, forbidden connection headers, and CR/LF conversion. Confirm which bytes one component assigns to a request and which bytes its peer assigns to the next request.
+
+**Web cache poisoning through unkeyed input**
+A request value changes cached content or security-relevant headers but is absent from the cache key. Compare cache key construction with every response variant, including forwarded host/scheme, selected cookies, query normalization, language/device headers, and authorization state.
+
+**Cache deception and private-response caching**
+Cache routing treats a private dynamic path as a public static asset, or caches a response whose identity and authorization inputs are missing from policy. Compare edge cacheability with application route parsing, suffix/path-parameter normalization, and response cache directives.
+
+**Host and forwarded-header trust**
+Untrusted host/proxy metadata determines absolute URLs, tenant routing, callbacks, reset links, cache keys, or the client address used by authorization. Confirm who can supply the header and whether trusted ingress removes client-provided copies.
+
+**Response-header injection**
+Untrusted data reaches `Location`, `Set-Cookie`, CSP, or another response header with unsafe control characters or normalization. Verify framework rejection before reporting and require a security-relevant response change.
+
+## Browser-session attack classes (subagent_type: `general`)
+
+**Ordinary CSRF**
+A browser sends ambient credentials to a state-changing endpoint that accepts a cross-site request without an effective anti-CSRF token, same-site request binding, or strict Origin/Referer validation. Inventory every cookie-authenticated mutation, including form, JSON-like, multipart, method-override, and legacy routes. SameSite is effective only for the cookie and browser contexts actually used; login CSRF and cross-site subresource requests can have different requirements.
+
+**Session fixation and invalidation**
+Session identifiers are not rotated on login, account switch, MFA completion, impersonation, or other privilege changes, or remain valid after logout, password change, revocation, and account disable. Check server sessions, refresh tokens, signed cookies, websocket state, cache copies, and fallback endpoints.
+
+**Cookie scope and transport**
+A sensitive cookie has an over-broad `Domain` or `Path`, can cross an insecure transport, or conflicts with a sibling cookie that another component selects differently. Bare missing flags remain hardening notes unless a realistic less-trusted origin, network position, or browser path can gain or replace the credential.
+
+## Federated-identity attack classes (subagent_type: `general`)
+
+First establish role. Authorization-server controls such as redirect allowlisting and code issuance do not belong to a relying-party client. Verification and binding defects belong to the component consuming the artifact.
+
+**JWT verification and claim binding**
+Check signature verification, server-pinned algorithm and key source, then `exp`, `nbf`, `aud`, and `iss`. Review `kid`, `jku`, and `x5u` as untrusted key selectors, duplicate/header normalization, and decode-without-verify paths. A valid token for another service is invalid here even when signed by a trusted issuer.
+
+**OAuth/OIDC request and callback binding**
+Validate exact `redirect_uri` ownership where the target is the authorization server; session-bound `state`; PKCE and authorization-code binding where applicable; ID-token issuer/audience/signature/nonce; and selected-IdP binding in multi-provider flows. Compare initial callback, retry, mobile/deep-link, and account-link routes.
+
+**SAML signed-object and assertion binding**
+Ensure the element whose signature is validated is the element used as identity. Review unsigned/fallback paths, safe XML parser configuration, canonicalization differences, and freshness/binding fields such as validity windows, audience/recipient, request correlation, and replay state.
+
+## MFA, passkey, and account-transition attack classes (subagent_type: `general`)
+
+**MFA enrollment and assurance downgrade**
+Enrollment, replacement, disablement, recovery-code generation, trusted-device creation, and fallback login require the intended prior assurance. Check that a valid first factor cannot enroll or replace the second factor without policy-required fresh authentication, and that disabled or stale factors stop authorizing sessions.
+
+**Step-up binding and bypass**
+A successful challenge upgrades the wrong session, account, tenant, action, or API request, or an alternate route omits the assurance check. Bind the challenge to principal, current session, assurance target, operation or resource when required, expiry, and one-time completion. Compare UI, API, batch, recovery, and resumed-flow paths.
+
+**WebAuthn and passkey verification**
+At registration, bind challenge, RP ID, expected origin, credential, user/userHandle, algorithm, and policy-required user verification to the initiating session. At authentication, verify challenge, RP/origin, credential membership, signature, and intended user presence/verification. Check account-discovery and linking flows for userHandle or credential-to-account confusion. Signature-counter handling is meaningful only when the product treats regressions as a clone signal.
+
+**Account linking and identity collision**
+Adding an IdP, passkey, email, phone, device, or external account to an existing account must require a current authenticated session, verified ownership of the new identity, policy-required step-up, and callback state bound to the account that initiated linking. Review unlink/relink and invite-acceptance paths for verified-identifier or tenant collisions.
+
+**Password reset and broader recovery**
+Recovery tokens, support/admin recovery, backup codes, device migration, and email or phone change often become the weakest authentication path. Verify token randomness, user/action binding, expiry, one-time state, rate/accounting controls, delivery URL trust, and invalidation of prior tokens and sessions. Different responses that only reveal public account existence are not automatically security findings.
+
+## API-key and mTLS attack classes (subagent_type: `general`)
+
+**API-key scope and resource binding**
+A key authenticates to broader tenants, resources, actions, or environments than its server-side record grants, or request parameters override those bindings. Review key lookup, prefix/full-secret verification, type confusion between publishable and secret keys, scope checks, rotation, revocation caches, and bulk endpoints.
+
+**API-key exposure and unsafe transport**
+Keys appear in client bundles, URLs, redirects, logs, error paths, build artifacts, or responses accessible to a lower-trust principal. A public identifier called a key is not a secret. Confirm key type and the authority gained by disclosure.
+
+**mTLS peer and application-identity confusion**
+A process trusts client-certificate identity headers from any network peer, verifies a chain but maps attacker-influenceable subject text to an account incorrectly, or accepts a certificate for the wrong trust domain, extended usage, audience, or validity policy. Where a trusted proxy terminates mTLS, verify only that proxy can connect, it removes incoming identity headers, and the backend binds the sanitized identity to the request.
+
+**Certificate lifecycle fallback**
+Expired, revoked, missing, or renewal-failed certificates cause silent fallback to bearer-only or anonymous operation, or long-lived pooled connections retain authorization after revocation. Missing deployment revocation data makes the result `needs_validation`; an in-repo fail-open branch is source-confirmable.
+
+## Universal moves (apply across the above)
+
+- Walk issue → store → transmit → consume → refresh → revoke for every credential and challenge. Compare normal, error, retry, migration, legacy, and account-switch paths.
+- Enumerate every door to the same identity and every route to the same sensitive operation. The effective policy is the weakest parallel path, not the most polished UI.
+- Diff parser, proxy, router, cache, and application normalization side by side. For local validation, feed identical bounded request fixtures into each component rather than sending traffic to a live deployment.
+- For recovery and linking, draw the account before/after graph. Each edge must name the current principal, proof of the new identity, required assurance, callback/session binding, and revocation effect.
+
+## Validation rules (apply before reporting ANY finding here)
+
+1. Apply a source-visibility gate. Proxy chains, edge cache keys, IdP policy, certificate trust, browser cookie behavior, secrets, and deployed auth modes may be outside the repository. Record a precise `needs_validation` candidate instead of asserting missing infrastructure behavior.
+2. For framing and cache findings, name both components and the divergent parse/key. Confirm cross-request, cross-user, or private-response impact with bounded local fixtures.
+3. For token, MFA, passkey, account-link, recovery, API-key, and mTLS findings, cite the verification line and missing principal/session/resource/origin/audience/action/assurance binding. Prove the server accepts the invalid transition or credential.
+4. For CSRF, name the ambient credential, state-changing route, accepted cross-site request shape, browser cookie policy, and missing effective check. Read-only actions and routes requiring a non-ambient bearer token do not qualify.
+5. Verify framework and library defaults. If version or configuration is unknown, use `needs_validation`; do not turn an unverified critical claim into a lower-severity confirmed finding.
+6. Return `confirmed` only with a complete source trace and observable unauthorized identity, state, or disclosure. For `needs_validation`, name the missing fact and safe local or owner-observed check that resolves it.
diff --git a/.agents/skills/security-audit/report-schema.json b/.agents/skills/security-audit/report-schema.json
new file mode 100644
index 00000000..55815a36
--- /dev/null
+++ b/.agents/skills/security-audit/report-schema.json
@@ -0,0 +1,461 @@
+{
+ "$comment": "Top-level contract for findings.json. validate-findings.cjs interprets and checks this schema directly.",
+ "type": "array",
+ "items": {
+ "oneOf": [
+ {
+ "type": "object",
+ "description": "A source-grounded vulnerability that was independently demonstrated.",
+ "properties": {
+ "verdict": {
+ "type": "string",
+ "const": "confirmed"
+ },
+ "fingerprint": {
+ "type": "string",
+ "minLength": 1,
+ "pattern": "^[A-Za-z0-9][A-Za-z0-9._:/@+-]*$",
+ "description": "A stable source-derived identifier that does not change between validation states."
+ },
+ "title": {
+ "type": "string",
+ "minLength": 1,
+ "visibleContent": true
+ },
+ "description": {
+ "type": "string",
+ "minLength": 1,
+ "visibleContent": true
+ },
+ "root_cause": {
+ "type": "string",
+ "minLength": 1,
+ "visibleContent": true
+ },
+ "intended_behavior": {
+ "type": "string",
+ "minLength": 1,
+ "visibleContent": true
+ },
+ "trace": {
+ "type": "array",
+ "minItems": 1,
+ "uniqueItems": true,
+ "items": {
+ "type": "object",
+ "properties": {
+ "kind": {
+ "type": "string",
+ "enum": ["entrypoint", "propagation", "sink"]
+ },
+ "file": {
+ "type": "string",
+ "minLength": 1
+ },
+ "line": {
+ "type": "integer",
+ "minimum": 1
+ },
+ "scope": {
+ "type": "string",
+ "minLength": 1,
+ "visibleContent": true
+ },
+ "description": {
+ "type": "string",
+ "minLength": 1,
+ "visibleContent": true
+ }
+ },
+ "required": ["kind", "file", "line", "scope", "description"],
+ "additionalProperties": false
+ }
+ },
+ "evidence": {
+ "type": "array",
+ "minItems": 1,
+ "uniqueItems": true,
+ "items": {
+ "type": "object",
+ "properties": {
+ "file": {
+ "type": "string",
+ "minLength": 1
+ },
+ "line": {
+ "type": "integer",
+ "minimum": 1
+ },
+ "description": {
+ "type": "string",
+ "minLength": 1,
+ "visibleContent": true
+ }
+ },
+ "required": ["file", "line", "description"],
+ "additionalProperties": false
+ }
+ },
+ "conditions": {
+ "type": "array",
+ "uniqueItems": true,
+ "items": {
+ "type": "object",
+ "properties": {
+ "kind": {
+ "type": "string",
+ "enum": ["authentication_level", "authorization_role", "user_interaction", "system_configuration", "network_routing", "environmental_dependency", "data_state", "timing_dependency", "third_party_dependency"]
+ },
+ "description": {
+ "type": "string",
+ "minLength": 1,
+ "visibleContent": true
+ }
+ },
+ "required": ["kind", "description"],
+ "additionalProperties": false
+ }
+ },
+ "execution": {
+ "type": "object",
+ "description": "Target-neutral reproduction in the target's native interface.",
+ "properties": {
+ "attacker_perspective": {
+ "type": "string",
+ "minLength": 1,
+ "visibleContent": true
+ },
+ "payloads": {
+ "type": "array",
+ "minItems": 1,
+ "uniqueItems": true,
+ "items": {
+ "type": "string"
+ }
+ },
+ "instructions": {
+ "type": "array",
+ "minItems": 1,
+ "items": {
+ "type": "string",
+ "minLength": 1,
+ "visibleContent": true
+ }
+ },
+ "observed_result": {
+ "type": "string",
+ "minLength": 1,
+ "visibleContent": true
+ }
+ },
+ "required": ["attacker_perspective", "payloads", "instructions", "observed_result"],
+ "additionalProperties": false
+ },
+ "remediation": {
+ "type": "object",
+ "properties": {
+ "strategy": {
+ "type": "string",
+ "minLength": 1,
+ "visibleContent": true
+ },
+ "code_changes": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "file_name": {
+ "type": "string",
+ "minLength": 1
+ },
+ "fixed_code": {
+ "type": "string"
+ }
+ },
+ "required": ["file_name", "fixed_code"],
+ "additionalProperties": false
+ }
+ }
+ },
+ "required": ["strategy"],
+ "additionalProperties": false
+ },
+ "severity": {
+ "type": "object",
+ "properties": {
+ "likelihood": {
+ "type": "object",
+ "properties": {
+ "score": {
+ "type": "string",
+ "enum": ["informational", "low", "medium", "high", "critical"]
+ },
+ "reason": {
+ "type": "string",
+ "minLength": 1,
+ "visibleContent": true
+ }
+ },
+ "required": ["score", "reason"],
+ "additionalProperties": false
+ },
+ "impact": {
+ "type": "object",
+ "properties": {
+ "score": {
+ "type": "string",
+ "enum": ["informational", "low", "medium", "high", "critical"]
+ },
+ "reason": {
+ "type": "string",
+ "minLength": 1,
+ "visibleContent": true
+ }
+ },
+ "required": ["score", "reason"],
+ "additionalProperties": false
+ },
+ "overall_severity": {
+ "type": "string",
+ "enum": ["informational", "low", "medium", "high", "critical"]
+ }
+ },
+ "required": ["likelihood", "impact", "overall_severity"],
+ "additionalProperties": false
+ },
+ "confidence": {
+ "type": "object",
+ "properties": {
+ "score": {
+ "type": "string",
+ "enum": ["low", "medium", "high"]
+ },
+ "reason": {
+ "type": "string",
+ "minLength": 1,
+ "visibleContent": true
+ }
+ },
+ "required": ["score", "reason"],
+ "additionalProperties": false
+ }
+ },
+ "required": ["verdict", "fingerprint", "title", "description", "root_cause", "intended_behavior", "trace", "evidence", "conditions", "execution", "remediation", "severity", "confidence"],
+ "additionalProperties": false
+ },
+ {
+ "type": "object",
+ "description": "A source-grounded candidate whose decisive validation is blocked.",
+ "properties": {
+ "verdict": {
+ "type": "string",
+ "const": "needs_validation"
+ },
+ "fingerprint": {
+ "type": "string",
+ "minLength": 1,
+ "pattern": "^[A-Za-z0-9][A-Za-z0-9._:/@+-]*$"
+ },
+ "title": {
+ "type": "string",
+ "minLength": 1,
+ "visibleContent": true
+ },
+ "description": {
+ "type": "string",
+ "minLength": 1,
+ "visibleContent": true
+ },
+ "claimed_root_cause": {
+ "type": "string",
+ "minLength": 1,
+ "visibleContent": true
+ },
+ "trace": {
+ "type": "array",
+ "minItems": 1,
+ "uniqueItems": true,
+ "items": {
+ "type": "object",
+ "properties": {
+ "kind": {
+ "type": "string",
+ "enum": ["entrypoint", "propagation", "sink"]
+ },
+ "file": {
+ "type": "string",
+ "minLength": 1
+ },
+ "line": {
+ "type": "integer",
+ "minimum": 1
+ },
+ "scope": {
+ "type": "string",
+ "minLength": 1,
+ "visibleContent": true
+ },
+ "description": {
+ "type": "string",
+ "minLength": 1,
+ "visibleContent": true
+ }
+ },
+ "required": ["kind", "file", "line", "scope", "description"],
+ "additionalProperties": false
+ }
+ },
+ "evidence": {
+ "type": "array",
+ "minItems": 1,
+ "uniqueItems": true,
+ "items": {
+ "type": "object",
+ "properties": {
+ "file": {
+ "type": "string",
+ "minLength": 1
+ },
+ "line": {
+ "type": "integer",
+ "minimum": 1
+ },
+ "description": {
+ "type": "string",
+ "minLength": 1,
+ "visibleContent": true
+ }
+ },
+ "required": ["file", "line", "description"],
+ "additionalProperties": false
+ }
+ },
+ "blockers": {
+ "type": "array",
+ "minItems": 1,
+ "uniqueItems": true,
+ "items": {
+ "type": "string",
+ "minLength": 1,
+ "visibleContent": true
+ }
+ },
+ "validation_plan": {
+ "type": "object",
+ "properties": {
+ "local": {
+ "type": "string",
+ "minLength": 1,
+ "visibleContent": true
+ },
+ "deployment": {
+ "type": "string",
+ "minLength": 1,
+ "visibleContent": true
+ }
+ },
+ "additionalProperties": false
+ }
+ },
+ "required": ["verdict", "fingerprint", "title", "description", "claimed_root_cause", "trace", "evidence", "blockers", "validation_plan"],
+ "additionalProperties": false
+ },
+ {
+ "type": "object",
+ "description": "A source-grounded candidate refuted during validation.",
+ "properties": {
+ "verdict": {
+ "type": "string",
+ "const": "rejected"
+ },
+ "fingerprint": {
+ "type": "string",
+ "minLength": 1,
+ "pattern": "^[A-Za-z0-9][A-Za-z0-9._:/@+-]*$"
+ },
+ "title": {
+ "type": "string",
+ "minLength": 1,
+ "visibleContent": true
+ },
+ "description": {
+ "type": "string",
+ "minLength": 1,
+ "visibleContent": true
+ },
+ "claimed_root_cause": {
+ "type": "string",
+ "minLength": 1,
+ "visibleContent": true
+ },
+ "trace": {
+ "type": "array",
+ "minItems": 1,
+ "uniqueItems": true,
+ "items": {
+ "type": "object",
+ "properties": {
+ "kind": {
+ "type": "string",
+ "enum": ["entrypoint", "propagation", "sink"]
+ },
+ "file": {
+ "type": "string",
+ "minLength": 1
+ },
+ "line": {
+ "type": "integer",
+ "minimum": 1
+ },
+ "scope": {
+ "type": "string",
+ "minLength": 1,
+ "visibleContent": true
+ },
+ "description": {
+ "type": "string",
+ "minLength": 1,
+ "visibleContent": true
+ }
+ },
+ "required": ["kind", "file", "line", "scope", "description"],
+ "additionalProperties": false
+ }
+ },
+ "evidence": {
+ "type": "array",
+ "minItems": 1,
+ "uniqueItems": true,
+ "items": {
+ "type": "object",
+ "properties": {
+ "file": {
+ "type": "string",
+ "minLength": 1
+ },
+ "line": {
+ "type": "integer",
+ "minimum": 1
+ },
+ "description": {
+ "type": "string",
+ "minLength": 1,
+ "visibleContent": true
+ }
+ },
+ "required": ["file", "line", "description"],
+ "additionalProperties": false
+ }
+ },
+ "reason": {
+ "type": "string",
+ "minLength": 1,
+ "visibleContent": true
+ }
+ },
+ "required": ["verdict", "fingerprint", "title", "description", "claimed_root_cause", "trace", "evidence", "reason"],
+ "additionalProperties": false
+ }
+ ]
+ }
+}
diff --git a/.agents/skills/security-audit/validate-coverage-ledger.cjs b/.agents/skills/security-audit/validate-coverage-ledger.cjs
new file mode 100644
index 00000000..0ef58657
--- /dev/null
+++ b/.agents/skills/security-audit/validate-coverage-ledger.cjs
@@ -0,0 +1,872 @@
+#!/usr/bin/env node
+
+/**
+ * Validates coverage-ledger.json and its canonical coverage IDs.
+ * Usage: node validate-coverage-ledger.cjs
+ */
+
+const fs = require("node:fs");
+const path = require("node:path");
+const { TextDecoder } = require("node:util");
+
+// Conservative bounds apply before JSON.parse and again to the parsed document.
+const LIMITS = Object.freeze({
+ inputBytes: 5 * 1024 * 1024,
+ units: 10000,
+ collectionItems: 1000,
+ objectFields: 1000,
+ nestingDepth: 64,
+ preflightValues: 500000,
+ validationErrors: 100,
+});
+const MAX_INPUT_BYTES = LIMITS.inputBytes;
+const MAX_UNITS = LIMITS.units;
+const MAX_LIST_ITEMS = LIMITS.collectionItems;
+const MAX_TEXT_LENGTH = 4096;
+const REQUIRED_FIELDS = [
+ "coverage_id",
+ "canonical_refs",
+ "surface",
+ "boundary",
+ "subsystem",
+ "attack_class",
+ "starting_paths",
+ "ordinary_attack_class_block",
+ "selected_companion_blocks",
+ "excluded_blocks",
+ "prior_status",
+ "attempts",
+ "wave",
+ "status",
+ "agent_id",
+ "reviewed_paths",
+ "local_checks",
+ "result_fingerprints",
+ "unresolved",
+];
+const REF_FIELDS = ["surface", "boundary", "subsystem", "attack_class"];
+const STATUSES = new Set([
+ "planned",
+ "not_applicable",
+ "out_of_scope",
+ "in_progress",
+ "covered",
+ "candidate",
+ "blocked",
+ "deferred",
+]);
+const ATTEMPT_STATUSES = new Set(["covered", "candidate", "blocked"]);
+const ATTEMPT_FIELDS = [
+ "wave",
+ "status",
+ "agent_id",
+ "reviewed_paths",
+ "local_checks",
+ "result_fingerprints",
+ "unresolved",
+ "reassignment_reason",
+];
+const PRIOR_STATUSES = new Set([
+ "new",
+ "prior_confirmed_same_source",
+ "prior_confirmed_changed_source",
+ "prior_needs_validation",
+ "prior_deferred",
+ "prior_blocked",
+ "prior_out_of_scope",
+ "prior_covered_same_source",
+ "prior_covered_changed_source",
+ "prior_rejected_claim_changed",
+ "none",
+]);
+const FINGERPRINT_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:/@+-]*$/;
+const AGENT_ID_PATTERN = /^[a-z0-9][a-z0-9_-]{0,63}$/;
+const WINDOWS_RESERVED_AGENT_ID = /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])$/;
+const VISIBLE_CONTENT = /[^\p{White_Space}\p{Cc}\p{Cf}\p{Default_Ignorable_Code_Point}]/u;
+const PATH_FORBIDDEN_CHARACTER = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}\p{Default_Ignorable_Code_Point}]/u;
+const WINDOWS_RESERVED_COMPONENT = /^(?:con|prn|aux|nul|clock\$|conin\$|conout\$|com[1-9\u00b9\u00b2\u00b3]|lpt[1-9\u00b9\u00b2\u00b3])(?:\.|$)/iu;
+const UTF8_DECODER = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
+const UNSAFE_DIAGNOSTIC_CHARACTER = /[\p{Cc}\p{Cf}\p{Cs}\p{Zl}\p{Zp}\p{Default_Ignorable_Code_Point}]/gu;
+const MAX_DIAGNOSTIC_STRING_LENGTH = 256;
+
+const hasOwn = (value, key) => Object.prototype.hasOwnProperty.call(value, key);
+
+class JsonStructureError extends Error {}
+class SafeInputError extends Error {}
+
+function escapeUnsafeDiagnosticCharacters(value) {
+ return String(value).replace(UNSAFE_DIAGNOSTIC_CHARACTER, (character) => {
+ const codePoint = character.codePointAt(0);
+ return codePoint <= 0xffff
+ ? `\\u${codePoint.toString(16).padStart(4, "0")}`
+ : `\\u{${codePoint.toString(16)}}`;
+ });
+}
+
+function safeQuote(value) {
+ let serialized;
+ if (typeof value === "string") {
+ const clipped = value.length > MAX_DIAGNOSTIC_STRING_LENGTH
+ ? `${value.slice(0, MAX_DIAGNOSTIC_STRING_LENGTH)}...`
+ : value;
+ serialized = JSON.stringify(clipped);
+ } else if (value === null || typeof value === "boolean") {
+ serialized = String(value);
+ } else if (typeof value === "number" && Number.isFinite(value)) {
+ serialized = String(value);
+ } else {
+ serialized = `"<${Array.isArray(value) ? "array" : typeof value}>"`;
+ }
+ return escapeUnsafeDiagnosticCharacters(serialized);
+}
+
+function createErrorList() {
+ const errors = [];
+ Object.defineProperty(errors, "push", {
+ value(...messages) {
+ const remaining = LIMITS.validationErrors - this.length;
+ if (remaining > 0) {
+ Array.prototype.push.apply(this, messages.slice(0, remaining).map(escapeUnsafeDiagnosticCharacters));
+ }
+ return this.length;
+ },
+ });
+ return errors;
+}
+
+function isObject(value) {
+ return value !== null && typeof value === "object" && !Array.isArray(value);
+}
+
+function preflightJsonText(contents) {
+ const containers = [];
+ let rootState = "value";
+ let inString = false;
+ let escaped = false;
+ let totalValues = 0;
+
+ function fail(message) {
+ throw new JsonStructureError(`input ${message}`);
+ }
+
+ function currentContainer() {
+ return containers[containers.length - 1];
+ }
+
+ function countValue() {
+ totalValues++;
+ if (totalValues > LIMITS.preflightValues) {
+ fail(`exceeds ${LIMITS.preflightValues} total value limit`);
+ }
+ }
+
+ function beginValue() {
+ const container = currentContainer();
+ if (!container) {
+ if (rootState !== "value") fail("has malformed JSON structure");
+ rootState = "end";
+ } else if (container.type === "array") {
+ if (container.state !== "firstValueOrEnd" && container.state !== "value") {
+ fail("has malformed JSON array structure");
+ }
+ container.items++;
+ const limit = container.topLevel ? MAX_UNITS : LIMITS.collectionItems;
+ if (container.items > limit) {
+ fail(container.topLevel
+ ? `exceeds ${limit} top-level unit limit`
+ : `exceeds ${limit} item array limit`);
+ }
+ container.state = "commaOrEnd";
+ } else {
+ if (container.state !== "value") fail("has malformed JSON object structure");
+ container.state = "commaOrEnd";
+ }
+ countValue();
+ }
+
+ function beginString() {
+ const container = currentContainer();
+ if (container && container.type === "object" &&
+ (container.state === "firstKeyOrEnd" || container.state === "key")) {
+ container.fields++;
+ if (container.fields > LIMITS.objectFields) {
+ fail(`exceeds ${LIMITS.objectFields} field object limit`);
+ }
+ container.state = "colon";
+ } else {
+ beginValue();
+ }
+ inString = true;
+ }
+
+ function beginContainer(type) {
+ beginValue();
+ if (containers.length >= LIMITS.nestingDepth) {
+ fail(`exceeds nesting depth limit ${LIMITS.nestingDepth}`);
+ }
+ containers.push(type === "array"
+ ? { type, state: "firstValueOrEnd", items: 0, topLevel: containers.length === 0 }
+ : { type, state: "firstKeyOrEnd", fields: 0 });
+ }
+
+ function closeContainer(type) {
+ const container = currentContainer();
+ if (!container || container.type !== type) fail("has mismatched JSON containers");
+ const canClose = type === "array"
+ ? container.state === "firstValueOrEnd" || container.state === "commaOrEnd"
+ : container.state === "firstKeyOrEnd" || container.state === "commaOrEnd";
+ if (!canClose) fail(`has malformed JSON ${type} structure`);
+ containers.pop();
+ }
+
+ function isWhitespace(character) {
+ return character === " " || character === "\t" || character === "\r" || character === "\n";
+ }
+
+ function isTokenDelimiter(character) {
+ return isWhitespace(character) || character === "," || character === ":" ||
+ character === "[" || character === "]" || character === "{" ||
+ character === "}" || character === "\"";
+ }
+
+ for (let index = 0; index < contents.length; index++) {
+ const character = contents[index];
+ if (inString) {
+ if (escaped) {
+ escaped = false;
+ } else if (character === "\\") {
+ escaped = true;
+ } else if (character === "\"") {
+ inString = false;
+ }
+ continue;
+ }
+ if (isWhitespace(character)) continue;
+
+ if (character === "\"") {
+ beginString();
+ } else if (character === "[") {
+ beginContainer("array");
+ } else if (character === "{") {
+ beginContainer("object");
+ } else if (character === "]") {
+ closeContainer("array");
+ } else if (character === "}") {
+ closeContainer("object");
+ } else if (character === ":") {
+ const container = currentContainer();
+ if (!container || container.type !== "object" || container.state !== "colon") {
+ fail("has malformed JSON object structure");
+ }
+ container.state = "value";
+ } else if (character === ",") {
+ const container = currentContainer();
+ if (!container || container.state !== "commaOrEnd") fail("has malformed JSON collection structure");
+ container.state = container.type === "array" ? "value" : "key";
+ } else {
+ beginValue();
+ while (index + 1 < contents.length && !isTokenDelimiter(contents[index + 1])) index++;
+ }
+ }
+
+ if (inString) fail("has an unterminated JSON string");
+ if (containers.length > 0) fail("has truncated JSON structure");
+ if (rootState !== "end") fail("has no JSON value");
+}
+
+function preflightDocument(root) {
+ const errors = createErrorList();
+ const stack = [{ value: root, depth: 0, location: "$" }];
+ let visited = 0;
+
+ while (stack.length > 0) {
+ const { value, depth, location } = stack.pop();
+ visited++;
+ if (visited > LIMITS.preflightValues) {
+ errors.push(`$: exceeds ${LIMITS.preflightValues} total values`);
+ return errors;
+ }
+ if (value === null || typeof value !== "object") continue;
+ if (depth >= LIMITS.nestingDepth) {
+ errors.push(`${location}: exceeds nesting depth limit ${LIMITS.nestingDepth}`);
+ return errors;
+ }
+
+ if (Array.isArray(value)) {
+ const limit = location === "$" ? MAX_UNITS : MAX_LIST_ITEMS;
+ if (value.length > limit) {
+ errors.push(`${location}: exceeds ${limit} entries`);
+ return errors;
+ }
+ for (let index = value.length - 1; index >= 0; index--) {
+ stack.push({ value: value[index], depth: depth + 1, location: `${location}[${index}]` });
+ }
+ continue;
+ }
+
+ const keys = Object.keys(value);
+ if (keys.length > LIMITS.objectFields) {
+ errors.push(`${location}: exceeds ${LIMITS.objectFields} object fields`);
+ return errors;
+ }
+ for (let index = keys.length - 1; index >= 0; index--) {
+ const key = keys[index];
+ stack.push({ value: value[key], depth: depth + 1, location: `${location}{${index}}` });
+ }
+ }
+
+ return errors;
+}
+
+function hasValidUnicodeScalarValues(value) {
+ let index = 0;
+ while (index < value.length) {
+ const first = value.charCodeAt(index++);
+ if (first >= 0xd800 && first <= 0xdbff) {
+ if (index >= value.length) return false;
+ const second = value.charCodeAt(index++);
+ if (second < 0xdc00 || second > 0xdfff) return false;
+ } else if (first >= 0xdc00 && first <= 0xdfff) {
+ return false;
+ }
+ }
+ return true;
+}
+
+function hasVisibleProse(value) {
+ return hasValidUnicodeScalarValues(value) && VISIBLE_CONTENT.test(value);
+}
+
+function isVisibleText(value, maxLength = MAX_TEXT_LENGTH) {
+ return typeof value === "string" &&
+ value.length > 0 &&
+ value.length <= maxLength &&
+ value.trim() === value &&
+ hasVisibleProse(value);
+}
+
+function isCanonicalRef(value) {
+ return isVisibleText(value, 1024) &&
+ !PATH_FORBIDDEN_CHARACTER.test(value) &&
+ value.normalize("NFC") === value;
+}
+
+function encodeCanonicalRef(value) {
+ if (!isCanonicalRef(value)) throw new TypeError("invalid canonical reference");
+ let encoded = "";
+ for (const byte of Buffer.from(value, "utf8")) {
+ const unreserved =
+ (byte >= 0x41 && byte <= 0x5a) ||
+ (byte >= 0x61 && byte <= 0x7a) ||
+ (byte >= 0x30 && byte <= 0x39) ||
+ byte === 0x2d || byte === 0x2e || byte === 0x5f || byte === 0x7e;
+ encoded += unreserved ? String.fromCharCode(byte) : `%${byte.toString(16).toUpperCase().padStart(2, "0")}`;
+ }
+ return encoded;
+}
+
+function canonicalCoverageId(refs) {
+ if (!isObject(refs)) throw new TypeError("canonical_refs must be an object");
+ const fields = hasOwn(refs, "lifecycle") ? [...REF_FIELDS, "lifecycle"] : REF_FIELDS;
+ if (Object.keys(refs).length !== fields.length || fields.some((field) => !hasOwn(refs, field))) {
+ throw new TypeError("canonical_refs has missing or unexpected fields");
+ }
+ return fields.map((field) => encodeCanonicalRef(refs[field])).join("::");
+}
+
+function isSafeRelativePath(value) {
+ if (typeof value !== "string" || value.length === 0 || !hasValidUnicodeScalarValues(value) || value.trim() !== value || PATH_FORBIDDEN_CHARACTER.test(value) || value.includes("\\") || value.includes(":")) return false;
+ if (path.posix.isAbsolute(value) || path.win32.isAbsolute(value) || /^[A-Za-z]:/.test(value) || value.startsWith("~")) return false;
+ return value.split("/").every((segment) =>
+ segment !== "" &&
+ segment !== "." &&
+ segment !== ".." &&
+ !/[ .]$/u.test(segment) &&
+ !WINDOWS_RESERVED_COMPONENT.test(segment));
+}
+
+function isSafeAgentId(value) {
+ return typeof value === "string" &&
+ AGENT_ID_PATTERN.test(value) &&
+ !WINDOWS_RESERVED_AGENT_ID.test(value);
+}
+
+function isOwnedArtifactPath(value, agentId) {
+ if (!isSafeAgentId(agentId) || !isSafeRelativePath(value)) return false;
+ const prefix = `agents/${agentId}/artifacts/`;
+ return value.startsWith(prefix) && value.length > prefix.length;
+}
+
+function validateStringArray(value, location, errors, options = {}) {
+ const { allowEmpty = true, fingerprint = false, pathValue = false } = options;
+ if (!Array.isArray(value)) {
+ errors.push(`${location}: expected array`);
+ return;
+ }
+ if (!allowEmpty && value.length === 0) errors.push(`${location}: must not be empty`);
+ if (value.length > MAX_LIST_ITEMS) errors.push(`${location}: exceeds ${MAX_LIST_ITEMS} entries`);
+ const seen = new Set();
+ value.slice(0, MAX_LIST_ITEMS).forEach((entry, index) => {
+ const entryLocation = `${location}[${index}]`;
+ const valid = pathValue ? isSafeRelativePath(entry) : isVisibleText(entry);
+ if (!valid) errors.push(`${entryLocation}: invalid ${pathValue ? "repository-relative path" : "text"}`);
+ if (fingerprint && typeof entry === "string" && !FINGERPRINT_PATTERN.test(entry)) {
+ errors.push(`${entryLocation}: invalid fingerprint`);
+ }
+ if (typeof entry === "string" && seen.has(entry)) errors.push(`${entryLocation}: duplicate entry`);
+ if (typeof entry === "string") seen.add(entry);
+ });
+}
+
+function validateChecks(value, location, errors) {
+ if (!Array.isArray(value)) {
+ errors.push(`${location}: expected array`);
+ return;
+ }
+ if (value.length > MAX_LIST_ITEMS) errors.push(`${location}: exceeds ${MAX_LIST_ITEMS} entries`);
+ value.slice(0, MAX_LIST_ITEMS).forEach((check, index) => {
+ const base = `${location}[${index}]`;
+ if (!isObject(check)) {
+ errors.push(`${base}: expected object`);
+ return;
+ }
+ for (const field of ["agent_id", "reviewed_paths", "invariant", "method", "result", "artifact"]) {
+ if (!hasOwn(check, field)) errors.push(`${base}: missing required field ${safeQuote(field)}`);
+ }
+ if (!isSafeAgentId(check.agent_id)) errors.push(`${base}.agent_id: expected a canonical lowercase agent ID`);
+ validateStringArray(check.reviewed_paths, `${base}.reviewed_paths`, errors, { allowEmpty: false, pathValue: true });
+ if (!isVisibleText(check.invariant)) errors.push(`${base}.invariant: invalid text`);
+ if (check.method !== "source" && check.method !== "local") errors.push(`${base}.method: expected "source" or "local"`);
+ if (!isVisibleText(check.result)) errors.push(`${base}.result: invalid text`);
+ if (check.method === "source" && check.artifact !== null) {
+ errors.push(`${base}.artifact: source-only check must use null`);
+ } else if (check.method === "local") {
+ if (!isOwnedArtifactPath(check.artifact, check.agent_id)) {
+ errors.push(`${base}.artifact: local check requires an artifact owned by agent ${safeQuote(isSafeAgentId(check.agent_id) ? check.agent_id : "")}`);
+ }
+ } else if (check.method !== "source" && check.method !== "local" && check.artifact !== null && !isSafeRelativePath(check.artifact)) {
+ errors.push(`${base}.artifact: expected null or a safe output-relative path`);
+ }
+ });
+}
+
+function validateReviewedPathOwnership(unit, base, errors) {
+ if (!Array.isArray(unit.reviewed_paths) || !Array.isArray(unit.local_checks)) return;
+ const aggregatePaths = new Set(unit.reviewed_paths.filter((value) => typeof value === "string"));
+ const ownedPaths = new Set();
+ for (const check of unit.local_checks) {
+ if (!isObject(check) || !Array.isArray(check.reviewed_paths)) continue;
+ for (const reviewedPath of check.reviewed_paths) {
+ if (typeof reviewedPath === "string") ownedPaths.add(reviewedPath);
+ }
+ }
+ for (const reviewedPath of aggregatePaths) {
+ if (!ownedPaths.has(reviewedPath)) errors.push(`${base}.reviewed_paths: ${safeQuote(reviewedPath)} has no check owner`);
+ }
+ for (const reviewedPath of ownedPaths) {
+ if (!aggregatePaths.has(reviewedPath)) errors.push(`${base}.local_checks: owned path ${safeQuote(reviewedPath)} is absent from aggregate reviewed_paths`);
+ }
+}
+
+function validateExcludedBlocks(value, location, errors) {
+ if (!Array.isArray(value)) {
+ errors.push(`${location}: expected array`);
+ return;
+ }
+ if (value.length > MAX_LIST_ITEMS) errors.push(`${location}: exceeds ${MAX_LIST_ITEMS} entries`);
+ const seen = new Set();
+ value.slice(0, MAX_LIST_ITEMS).forEach((entry, index) => {
+ const base = `${location}[${index}]`;
+ if (!isObject(entry)) {
+ errors.push(`${base}: expected object`);
+ return;
+ }
+ if (!isVisibleText(entry.block)) errors.push(`${base}.block: invalid text`);
+ if (!isVisibleText(entry.reason)) errors.push(`${base}.reason: invalid text`);
+ if (typeof entry.block === "string" && seen.has(entry.block)) errors.push(`${base}.block: duplicate entry`);
+ if (typeof entry.block === "string") seen.add(entry.block);
+ });
+}
+
+function semanticKey(unit) {
+ return JSON.stringify([
+ unit.surface,
+ unit.boundary,
+ unit.subsystem,
+ unit.attack_class,
+ hasOwn(unit, "lifecycle") ? unit.lifecycle : null,
+ ]);
+}
+
+function hasValidSemanticFields(unit) {
+ return ["surface", "boundary", "subsystem", "attack_class"].every((field) => isVisibleText(unit[field])) &&
+ (!hasOwn(unit, "lifecycle") || isVisibleText(unit.lifecycle));
+}
+
+function requireEmptyArray(unit, field, base, errors) {
+ if (Array.isArray(unit[field]) && unit[field].length > 0) {
+ errors.push(`${base}.${field}: unit with status ${safeQuote(unit.status)} must keep this array empty`);
+ }
+}
+
+function requireNonemptyArray(unit, field, base, errors) {
+ if (!Array.isArray(unit[field]) || unit[field].length === 0) {
+ errors.push(`${base}.${field}: unit with status ${safeQuote(unit.status)} requires entries`);
+ }
+}
+
+function validateStateInvariants(unit, base, errors) {
+ const emptyEvidence = () => {
+ requireEmptyArray(unit, "reviewed_paths", base, errors);
+ requireEmptyArray(unit, "local_checks", base, errors);
+ };
+ const requireOwner = () => {
+ if (!isSafeAgentId(unit.agent_id)) errors.push(`${base}.agent_id: unit with status ${safeQuote(unit.status)} requires a canonical lowercase agent ID`);
+ };
+
+ if (unit.status !== "candidate") requireEmptyArray(unit, "result_fingerprints", base, errors);
+
+ switch (unit.status) {
+ case "planned":
+ if (unit.agent_id !== null) errors.push(`${base}.agent_id: planned unit must be unassigned`);
+ emptyEvidence();
+ requireEmptyArray(unit, "unresolved", base, errors);
+ break;
+ case "not_applicable":
+ case "out_of_scope":
+ case "deferred":
+ if (unit.agent_id !== null) errors.push(`${base}.agent_id: unit with status ${safeQuote(unit.status)} must be unassigned`);
+ emptyEvidence();
+ requireNonemptyArray(unit, "unresolved", base, errors);
+ break;
+ case "in_progress":
+ requireOwner();
+ emptyEvidence();
+ requireEmptyArray(unit, "unresolved", base, errors);
+ break;
+ case "blocked":
+ requireOwner();
+ requireNonemptyArray(unit, "reviewed_paths", base, errors);
+ requireNonemptyArray(unit, "local_checks", base, errors);
+ requireNonemptyArray(unit, "unresolved", base, errors);
+ break;
+ case "covered":
+ requireOwner();
+ requireNonemptyArray(unit, "reviewed_paths", base, errors);
+ requireNonemptyArray(unit, "local_checks", base, errors);
+ requireEmptyArray(unit, "unresolved", base, errors);
+ break;
+ case "candidate":
+ requireOwner();
+ requireNonemptyArray(unit, "reviewed_paths", base, errors);
+ requireNonemptyArray(unit, "local_checks", base, errors);
+ requireNonemptyArray(unit, "result_fingerprints", base, errors);
+ break;
+ }
+}
+
+function validateAttempts(value, unit, base, errors) {
+ if (!Array.isArray(value)) {
+ errors.push(`${base}.attempts: expected array`);
+ return;
+ }
+ if (value.length > MAX_LIST_ITEMS) errors.push(`${base}.attempts: exceeds ${MAX_LIST_ITEMS} entries`);
+
+ const priorOwners = new Set();
+ const priorArtifacts = new Set();
+ let previousWave = 0;
+ value.slice(0, MAX_LIST_ITEMS).forEach((attempt, index) => {
+ const attemptBase = `${base}.attempts[${index}]`;
+ if (!isObject(attempt)) {
+ errors.push(`${attemptBase}: expected object`);
+ return;
+ }
+ for (const field of ATTEMPT_FIELDS) {
+ if (!hasOwn(attempt, field)) errors.push(`${attemptBase}: missing required field ${safeQuote(field)}`);
+ }
+ if (!Number.isInteger(attempt.wave) || attempt.wave < 1) {
+ errors.push(`${attemptBase}.wave: expected a positive integer`);
+ } else {
+ if (attempt.wave <= previousWave) errors.push(`${attemptBase}.wave: archived attempt waves must be strictly increasing`);
+ if (Number.isInteger(unit.wave) && attempt.wave >= unit.wave) {
+ errors.push(`${attemptBase}.wave: archived attempt wave must precede current wave ${safeQuote(unit.wave)}`);
+ }
+ previousWave = attempt.wave;
+ }
+ if (!ATTEMPT_STATUSES.has(attempt.status)) {
+ errors.push(`${attemptBase}.status: expected "covered", "candidate", or "blocked"`);
+ }
+ let hasFreshOwner = false;
+ if (!isSafeAgentId(attempt.agent_id)) {
+ errors.push(`${attemptBase}.agent_id: archived attempt requires a canonical lowercase agent ID`);
+ } else if (priorOwners.has(attempt.agent_id)) {
+ errors.push(`${attemptBase}.agent_id: assignment owner must be fresh for each attempt`);
+ } else {
+ hasFreshOwner = true;
+ }
+ validateStringArray(attempt.reviewed_paths, `${attemptBase}.reviewed_paths`, errors, { pathValue: true });
+ validateChecks(attempt.local_checks, `${attemptBase}.local_checks`, errors);
+ validateReviewedPathOwnership(attempt, attemptBase, errors);
+ validateStringArray(attempt.result_fingerprints, `${attemptBase}.result_fingerprints`, errors, { fingerprint: true });
+ validateStringArray(attempt.unresolved, `${attemptBase}.unresolved`, errors);
+ if (!isVisibleText(attempt.reassignment_reason)) errors.push(`${attemptBase}.reassignment_reason: invalid text`);
+ validateStateInvariants(attempt, attemptBase, errors);
+
+ if (Array.isArray(attempt.local_checks)) {
+ attempt.local_checks.forEach((check, checkIndex) => {
+ if (!isObject(check)) return;
+ if (priorOwners.has(check.agent_id)) {
+ errors.push(`${attemptBase}.local_checks[${checkIndex}].agent_id: prior assignment owner evidence must remain in its earlier attempt`);
+ }
+ if (typeof check.artifact === "string" && priorArtifacts.has(check.artifact)) {
+ errors.push(`${attemptBase}.local_checks[${checkIndex}].artifact: artifact from an earlier attempt cannot be reused`);
+ }
+ if (check.method === "local" && typeof check.artifact === "string") priorArtifacts.add(check.artifact);
+ });
+ }
+ if (hasFreshOwner) priorOwners.add(attempt.agent_id);
+ });
+
+ if (isSafeAgentId(unit.agent_id) && priorOwners.has(unit.agent_id)) {
+ errors.push(`${base}.agent_id: current assignment owner must be fresh after reassignment`);
+ }
+ if (Array.isArray(unit.local_checks)) {
+ unit.local_checks.forEach((check, index) => {
+ if (!isObject(check)) return;
+ if (priorOwners.has(check.agent_id)) {
+ errors.push(`${base}.local_checks[${index}].agent_id: prior assignment owner evidence must remain in its archived attempt`);
+ }
+ if (typeof check.artifact === "string" && priorArtifacts.has(check.artifact)) {
+ errors.push(`${base}.local_checks[${index}].artifact: artifact from an archived attempt cannot be reused`);
+ }
+ });
+ }
+}
+
+function collectUnitErrors(unit, index) {
+ const errors = createErrorList();
+ const base = `$[${index}]`;
+ if (!isObject(unit)) return [`${base}: expected object`];
+
+ for (const field of REQUIRED_FIELDS) {
+ if (!hasOwn(unit, field)) errors.push(`${base}: missing required field ${safeQuote(field)}`);
+ }
+ for (const field of ["surface", "boundary", "subsystem", "attack_class"]) {
+ if (!isVisibleText(unit[field])) errors.push(`${base}.${field}: invalid text`);
+ }
+ if (hasOwn(unit, "lifecycle") && !isVisibleText(unit.lifecycle)) errors.push(`${base}.lifecycle: invalid text`);
+
+ let expectedId = null;
+ if (!isObject(unit.canonical_refs)) {
+ errors.push(`${base}.canonical_refs: expected object`);
+ } else {
+ const expectedFields = hasOwn(unit.canonical_refs, "lifecycle") ? [...REF_FIELDS, "lifecycle"] : REF_FIELDS;
+ for (const field of expectedFields) {
+ if (!hasOwn(unit.canonical_refs, field)) {
+ errors.push(`${base}.canonical_refs: missing required field ${safeQuote(field)}`);
+ } else if (!isCanonicalRef(unit.canonical_refs[field])) {
+ errors.push(`${base}.canonical_refs.${field}: invalid canonical reference`);
+ }
+ }
+ if (Object.keys(unit.canonical_refs).some((field) => !expectedFields.includes(field))) {
+ errors.push(`${base}.canonical_refs: contains unexpected fields`);
+ }
+ if (hasOwn(unit, "lifecycle") !== hasOwn(unit.canonical_refs, "lifecycle")) {
+ errors.push(`${base}: lifecycle and canonical_refs.lifecycle must appear together`);
+ }
+ try {
+ expectedId = canonicalCoverageId(unit.canonical_refs);
+ } catch {
+ // The specific reference errors above are more useful.
+ }
+ }
+ if (!isVisibleText(unit.coverage_id, 65536)) {
+ errors.push(`${base}.coverage_id: invalid text`);
+ } else if (expectedId !== null && unit.coverage_id !== expectedId) {
+ errors.push(`${base}.coverage_id: expected canonical ID ${safeQuote(expectedId)}`);
+ }
+
+ validateStringArray(unit.starting_paths, `${base}.starting_paths`, errors, { allowEmpty: false, pathValue: true });
+ if (unit.ordinary_attack_class_block !== null && !isVisibleText(unit.ordinary_attack_class_block)) {
+ errors.push(`${base}.ordinary_attack_class_block: expected null or non-empty text`);
+ }
+ validateStringArray(unit.selected_companion_blocks, `${base}.selected_companion_blocks`, errors);
+ validateExcludedBlocks(unit.excluded_blocks, `${base}.excluded_blocks`, errors);
+ if (Array.isArray(unit.selected_companion_blocks) && Array.isArray(unit.excluded_blocks)) {
+ const selected = new Set(unit.selected_companion_blocks);
+ unit.excluded_blocks.forEach((entry, blockIndex) => {
+ if (isObject(entry) && selected.has(entry.block)) {
+ errors.push(`${base}.excluded_blocks[${blockIndex}].block: block is also selected`);
+ }
+ });
+ }
+
+ if (!PRIOR_STATUSES.has(unit.prior_status)) errors.push(`${base}.prior_status: invalid value ${safeQuote(unit.prior_status)}`);
+ if (!STATUSES.has(unit.status)) errors.push(`${base}.status: invalid value ${safeQuote(unit.status)}`);
+ if (!Number.isInteger(unit.wave) || unit.wave < 1) errors.push(`${base}.wave: expected a positive integer`);
+ if (unit.agent_id !== null && !isSafeAgentId(unit.agent_id)) errors.push(`${base}.agent_id: expected null or a safe agent ID`);
+
+ validateAttempts(unit.attempts, unit, base, errors);
+ validateStringArray(unit.reviewed_paths, `${base}.reviewed_paths`, errors, { pathValue: true });
+ validateChecks(unit.local_checks, `${base}.local_checks`, errors);
+ validateReviewedPathOwnership(unit, base, errors);
+ validateStringArray(unit.result_fingerprints, `${base}.result_fingerprints`, errors, { fingerprint: true });
+ validateStringArray(unit.unresolved, `${base}.unresolved`, errors);
+
+ validateStateInvariants(unit, base, errors);
+
+ return errors;
+}
+
+function readFileWithinLimit(file) {
+ const noFollow = fs.constants.O_NOFOLLOW;
+ const nonBlock = fs.constants.O_NONBLOCK;
+ if (!Number.isInteger(noFollow) || noFollow === 0 || !Number.isInteger(nonBlock) || nonBlock === 0) {
+ // Node exposes no race-safe fallback on these platforms, so reject all inputs.
+ throw new SafeInputError("OS no-follow and nonblocking input protection is unavailable");
+ }
+
+ let descriptor;
+ try {
+ descriptor = fs.openSync(file, fs.constants.O_RDONLY | noFollow | nonBlock);
+ } catch (error) {
+ if (error && (error.code === "ELOOP" || error.code === "EMLINK")) throw new SafeInputError("input must not be a symlink");
+ throw error;
+ }
+ try {
+ const stat = fs.fstatSync(descriptor);
+ if (!stat.isFile()) throw new SafeInputError("input must be a regular file");
+ if (stat.size > MAX_INPUT_BYTES) throw new SafeInputError(`input exceeds ${MAX_INPUT_BYTES} byte limit`);
+
+ const chunks = [];
+ const buffer = Buffer.allocUnsafe(64 * 1024);
+ let bytesRead = 0;
+ while (true) {
+ const count = fs.readSync(descriptor, buffer, 0, buffer.length, null);
+ if (count === 0) break;
+ bytesRead += count;
+ if (bytesRead > MAX_INPUT_BYTES) throw new SafeInputError(`input exceeds ${MAX_INPUT_BYTES} byte limit`);
+ chunks.push(Buffer.from(buffer.subarray(0, count)));
+ }
+ try {
+ return UTF8_DECODER.decode(Buffer.concat(chunks, bytesRead));
+ } catch {
+ throw new SafeInputError("input is not valid UTF-8");
+ }
+ } finally {
+ fs.closeSync(descriptor);
+ }
+}
+
+function validateDocument(ledger) {
+ const errors = createErrorList();
+ if (!Array.isArray(ledger)) {
+ errors.push("$: expected a top-level array");
+ return errors;
+ }
+ if (ledger.length > MAX_UNITS) {
+ errors.push(`$: exceeds ${MAX_UNITS} coverage units`);
+ return errors;
+ }
+
+ errors.push(...preflightDocument(ledger));
+ if (errors.length > 0) return errors;
+
+ const ids = new Map();
+ const semantics = new Map();
+ let previousId = null;
+ for (let index = 0; index < ledger.length && errors.length < LIMITS.validationErrors; index++) {
+ const unit = ledger[index];
+ errors.push(...collectUnitErrors(unit, index));
+ if (errors.length >= LIMITS.validationErrors) break;
+ if (!isObject(unit) || typeof unit.coverage_id !== "string") continue;
+
+ const key = hasValidSemanticFields(unit) ? semanticKey(unit) : null;
+ if (ids.has(unit.coverage_id)) {
+ const previous = ids.get(unit.coverage_id);
+ const qualifier = key !== null && previous.key !== null && previous.key !== key
+ ? "canonical identity collision with different semantic fields"
+ : "duplicate coverage ID";
+ errors.push(`$[${index}].coverage_id: ${qualifier} at $[${previous.index}]`);
+ } else {
+ ids.set(unit.coverage_id, { index, key });
+ }
+ if (key !== null && semantics.has(key) && semantics.get(key).id !== unit.coverage_id) {
+ const previous = semantics.get(key);
+ errors.push(`$[${index}].canonical_refs: semantic tuple already uses coverage ID ${safeQuote(previous.id)} at $[${previous.index}]`);
+ } else if (key !== null) {
+ semantics.set(key, { id: unit.coverage_id, index });
+ }
+ if (previousId !== null && previousId > unit.coverage_id) {
+ errors.push(`$[${index}].coverage_id: units must be sorted lexicographically`);
+ }
+ previousId = unit.coverage_id;
+ }
+ return errors;
+}
+
+function run(file) {
+ if (!file) {
+ console.error("Usage: node validate-coverage-ledger.cjs ");
+ return 1;
+ }
+
+ let contents;
+ try {
+ contents = readFileWithinLimit(file);
+ } catch (error) {
+ const reason = error instanceof SafeInputError ? error.message : "input could not be opened or read safely";
+ console.error(`Failed to read coverage ledger: ${reason}`);
+ return 1;
+ }
+
+ let ledger;
+ try {
+ preflightJsonText(contents);
+ } catch (error) {
+ const reason = error instanceof JsonStructureError ? error.message : "invalid JSON structure";
+ console.error(`Failed to parse coverage ledger: ${reason}`);
+ return 1;
+ }
+ try {
+ ledger = JSON.parse(contents);
+ } catch {
+ console.error("Failed to parse coverage ledger: invalid JSON syntax");
+ return 1;
+ }
+
+ let errors;
+ try {
+ errors = validateDocument(ledger);
+ } catch {
+ console.error("Failed to validate coverage ledger: unexpected validation error");
+ return 1;
+ }
+ for (const message of errors) console.error("ERROR:", message);
+ if (errors.length > 0) {
+ const cap = errors.length === LIMITS.validationErrors ? `; output capped at ${LIMITS.validationErrors}` : "";
+ console.error(`FAIL: ${errors.length} validation error(s)${cap}`);
+ return 1;
+ }
+ console.log(`PASS: ${ledger.length} coverage units valid`);
+ return 0;
+}
+
+module.exports = {
+ LIMITS,
+ PATH_FORBIDDEN_CHARACTER,
+ UNSAFE_DIAGNOSTIC_CHARACTER,
+ VISIBLE_CONTENT,
+ WINDOWS_RESERVED_COMPONENT,
+ canonicalCoverageId,
+ encodeCanonicalRef,
+ hasVisibleProse,
+ isSafeAgentId,
+ isSafeRelativePath,
+ preflightJsonText,
+ readFileWithinLimit,
+ safeQuote,
+ validateDocument,
+};
+
+if (require.main === module) process.exit(run(process.argv[2]));
diff --git a/.agents/skills/security-audit/validate-coverage-ledger.test.cjs b/.agents/skills/security-audit/validate-coverage-ledger.test.cjs
new file mode 100644
index 00000000..b1444f57
--- /dev/null
+++ b/.agents/skills/security-audit/validate-coverage-ledger.test.cjs
@@ -0,0 +1,740 @@
+const assert = require("node:assert/strict");
+const fs = require("node:fs");
+const os = require("node:os");
+const path = require("node:path");
+const { spawnSync } = require("node:child_process");
+const test = require("node:test");
+const {
+ LIMITS,
+ canonicalCoverageId,
+ encodeCanonicalRef,
+ isSafeAgentId,
+ isSafeRelativePath,
+ preflightJsonText,
+ validateDocument,
+} = require("./validate-coverage-ledger.cjs");
+
+const validatorPath = path.join(__dirname, "validate-coverage-ledger.cjs");
+const CLI_TIMEOUT_MS = 5000;
+const HOSTILE_CLI_TIMEOUT_MS = 15000;
+const HAS_SAFE_INPUT_OPEN = Number.isInteger(fs.constants.O_NOFOLLOW) &&
+ fs.constants.O_NOFOLLOW !== 0 &&
+ Number.isInteger(fs.constants.O_NONBLOCK) &&
+ fs.constants.O_NONBLOCK !== 0;
+
+function unit(overrides = {}) {
+ const canonicalRefs = overrides.canonical_refs || {
+ surface: "src/router.ts#POST /users/:id",
+ boundary: "src/authz.ts#requireOwner",
+ subsystem: "packages/api",
+ attack_class: "ATTACK-CLASSES.md#Access control",
+ };
+ const value = {
+ coverage_id: canonicalCoverageId(canonicalRefs),
+ canonical_refs: canonicalRefs,
+ surface: "Update-user route",
+ boundary: "Object ownership",
+ subsystem: "API",
+ attack_class: "Access control",
+ starting_paths: ["src/router.ts", "src/authz.ts"],
+ ordinary_attack_class_block: "ATTACK-CLASSES.md#Access control",
+ selected_companion_blocks: [],
+ excluded_blocks: [{ block: "WEB-PROTOCOL-AND-AUTH.md#Cache behavior", reason: "The route is not cached." }],
+ prior_status: "new",
+ attempts: [],
+ wave: 1,
+ status: "planned",
+ agent_id: null,
+ reviewed_paths: [],
+ local_checks: [],
+ result_fingerprints: [],
+ unresolved: [],
+ };
+ return Object.assign(value, overrides, { canonical_refs: canonicalRefs });
+}
+
+function errorsFor(value) {
+ return validateDocument(value);
+}
+
+function runCli(contents, options = {}) {
+ const { nodeArgs = [], timeout = CLI_TIMEOUT_MS } = options;
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), "validate-coverage-ledger-"));
+ const ledgerPath = path.join(directory, "coverage-ledger.json");
+ try {
+ fs.writeFileSync(ledgerPath, contents);
+ return spawnSync(process.execPath, [...nodeArgs, validatorPath, ledgerPath], {
+ encoding: "utf8",
+ timeout,
+ });
+ } finally {
+ fs.rmSync(directory, { recursive: true, force: true });
+ }
+}
+
+function cliOutput(result) {
+ return `${result.stdout}${result.stderr}`;
+}
+
+const TERMINAL_CONTROL_PAYLOAD = "\u001b\u0007\u0085\u202e";
+const TERMINAL_CONTROL_BYTES = [
+ Buffer.from([0x1b]),
+ Buffer.from([0x07]),
+ Buffer.from("\u0085"),
+ Buffer.from("\u202e"),
+];
+
+function assertNoInjectedControlBytes(output) {
+ const bytes = Buffer.isBuffer(output) ? output : Buffer.from(output, "utf8");
+ for (const marker of TERMINAL_CONTROL_BYTES) {
+ assert.equal(bytes.indexOf(marker), -1, `found raw control bytes ${marker.toString("hex")}`);
+ }
+}
+
+function sourceCheck(agentId = "hunter-1", overrides = {}) {
+ return {
+ agent_id: agentId,
+ reviewed_paths: ["src/router.ts"],
+ invariant: "The route checks object ownership.",
+ method: "source",
+ result: "The owner check applies before the update.",
+ artifact: null,
+ ...overrides,
+ };
+}
+
+function localCheck(agentId = "hunter-1", overrides = {}) {
+ return sourceCheck(agentId, {
+ method: "local",
+ result: "The bounded fixture accepted the other owner's object.",
+ artifact: `agents/${agentId}/artifacts/result.txt`,
+ ...overrides,
+ });
+}
+
+function archivedAttempt(overrides = {}) {
+ const value = {
+ wave: 1,
+ status: "blocked",
+ agent_id: "hunter-1",
+ reviewed_paths: ["src/router.ts"],
+ local_checks: [sourceCheck()],
+ result_fingerprints: [],
+ unresolved: ["The deployed policy is unavailable."],
+ reassignment_reason: "The critic found an unchecked parallel path.",
+ };
+ return Object.assign(value, overrides);
+}
+
+test("accepts an empty ledger and complete units", () => {
+ assert.deepEqual(errorsFor([]), []);
+ assert.deepEqual(errorsFor([unit()]), []);
+
+ const missingAttempts = unit();
+ delete missingAttempts.attempts;
+ assert(errorsFor([missingAttempts]).some((error) => error.includes('missing required field "attempts"')));
+
+ const covered = unit({
+ status: "covered",
+ agent_id: "hunter-1",
+ reviewed_paths: ["src/router.ts"],
+ local_checks: [sourceCheck()],
+ });
+ assert.deepEqual(errorsFor([covered]), []);
+});
+
+test("accepts a complete ledger through the CLI", { skip: !HAS_SAFE_INPUT_OPEN }, () => {
+ const result = runCli(JSON.stringify([unit()]));
+ assert.equal(result.status, 0, cliOutput(result));
+ assert.match(result.stdout, /PASS: 1 coverage units valid/);
+});
+
+test("text preflight ignores structural characters and escapes inside strings", () => {
+ const value = unit({
+ surface: "Route \\ slash [list] {object}, colon: quoted \"value\"",
+ excluded_blocks: [{
+ block: "COMPANION.md#Literal [brackets] {braces}",
+ reason: "The text contains a backslash \\ before an escaped \"quote\".",
+ }],
+ });
+ const contents = JSON.stringify([value]);
+ assert.doesNotThrow(() => preflightJsonText(contents));
+ assert.deepEqual(JSON.parse(contents), [value]);
+ if (HAS_SAFE_INPUT_OPEN) {
+ const result = runCli(contents);
+ assert.equal(result.status, 0, cliOutput(result));
+ }
+});
+
+test("text preflight enforces structural cardinality limits", () => {
+ const depthLimit = LIMITS.nestingDepth;
+ assert.doesNotThrow(() => preflightJsonText(`${"[".repeat(depthLimit)}0${"]".repeat(depthLimit)}`));
+ assert.throws(
+ () => preflightJsonText(`${"[".repeat(depthLimit + 1)}0${"]".repeat(depthLimit + 1)}`),
+ /exceeds nesting depth limit 64/,
+ );
+
+ const tooManyUnits = `[${"null,".repeat(LIMITS.units)}null]`;
+ assert.throws(() => preflightJsonText(tooManyUnits), /exceeds 10000 top-level unit limit/);
+
+ const tooManyItems = `[[${"null,".repeat(LIMITS.collectionItems)}null]]`;
+ assert.throws(() => preflightJsonText(tooManyItems), /exceeds 1000 item array limit/);
+
+ const objectFields = Array.from(
+ { length: LIMITS.objectFields + 1 },
+ (_, index) => `"field${index}":null`,
+ ).join(",");
+ assert.throws(() => preflightJsonText(`[{${objectFields}}]`), /exceeds 1000 field object limit/);
+
+ const fullArray = `[${"null,".repeat(LIMITS.collectionItems - 1)}null]`;
+ const arraysNeeded = Math.floor(LIMITS.preflightValues / (LIMITS.collectionItems + 1)) + 1;
+ const tooManyValues = `[${Array.from({ length: arraysNeeded }, () => fullArray).join(",")}]`;
+ assert.throws(() => preflightJsonText(tooManyValues), /exceeds 500000 total value limit/);
+});
+
+test("text preflight rejects malformed structural truncation cleanly", () => {
+ assert.throws(() => preflightJsonText("["), /truncated JSON structure/);
+ assert.throws(() => preflightJsonText("[\"unterminated"), /unterminated JSON string/);
+ assert.throws(() => preflightJsonText("[{\"field\":1]"), /mismatched JSON containers/);
+});
+
+test("derives collision-free canonical IDs from exact UTF-8 references", () => {
+ assert.equal(encodeCanonicalRef("route:POST /users"), "route%3APOST%20%2Fusers");
+ assert.notEqual(encodeCanonicalRef("route name"), encodeCanonicalRef("route-name"));
+ assert.equal(
+ canonicalCoverageId({ surface: "a", boundary: "b", subsystem: "c", attack_class: "d", lifecycle: "retry" }),
+ "a::b::c::d::retry",
+ );
+ assert.throws(() => encodeCanonicalRef("e\u0301"), /invalid canonical reference/);
+ assert.throws(() => encodeCanonicalRef("bad\u0000ref"), /invalid canonical reference/);
+ assert.throws(() => encodeCanonicalRef("hidden\u200bref"), /invalid canonical reference/);
+});
+
+test("rejects noncanonical, duplicate, and colliding IDs", () => {
+ const wrong = unit({ coverage_id: "display-label-slug" });
+ assert(errorsFor([wrong]).some((error) => error.includes("expected canonical ID")));
+
+ const duplicate = unit();
+ assert(errorsFor([duplicate, unit()]).some((error) => error.includes("duplicate coverage ID")));
+
+ const collision = unit();
+ const differentMeaning = unit({ surface: "Delete-user route" });
+ assert(errorsFor([collision, differentMeaning]).some((error) => error.includes("canonical identity collision")));
+});
+
+test("requires canonical references to be own properties", () => {
+ const inherited = Object.create(unit().canonical_refs);
+ const value = unit();
+ value.canonical_refs = inherited;
+ assert(errorsFor([value]).some((error) => error.includes("missing required field")));
+});
+
+test("rejects aliases for one semantic tuple", () => {
+ const first = unit();
+ const refs = { ...first.canonical_refs, surface: "src/alias.ts#updateUser" };
+ const alias = unit({ canonical_refs: refs });
+ const ledger = [first, alias].sort((left, right) => left.coverage_id.localeCompare(right.coverage_id));
+ assert(errorsFor(ledger).some((error) => error.includes("semantic tuple already uses coverage ID")));
+});
+
+test("requires lexicographic order", () => {
+ const secondRefs = {
+ surface: "zzz",
+ boundary: "src/authz.ts#requireOwner",
+ subsystem: "packages/api",
+ attack_class: "ATTACK-CLASSES.md#Access control",
+ };
+ assert(errorsFor([unit({ canonical_refs: secondRefs }), unit()])
+ .some((error) => error.includes("sorted lexicographically")));
+});
+
+test("validates assignment block maps", () => {
+ const overlap = unit({
+ selected_companion_blocks: ["AI-AND-LLM.md#Tool calls"],
+ excluded_blocks: [{ block: "AI-AND-LLM.md#Tool calls", reason: "Claimed irrelevant." }],
+ });
+ assert(errorsFor([overlap]).some((error) => error.includes("also selected")));
+
+ const noReason = unit({ excluded_blocks: [{ block: "AI-AND-LLM.md#Tool calls", reason: "" }] });
+ assert(errorsFor([noReason]).some((error) => error.includes("reason")));
+});
+
+test("requires owned artifacts for local checks and null artifacts for source checks", () => {
+ const local = unit({
+ status: "covered",
+ agent_id: "hunter-1",
+ reviewed_paths: ["src/router.ts"],
+ local_checks: [localCheck()],
+ });
+ assert.deepEqual(errorsFor([local]), []);
+
+ const independentlyVerified = unit({
+ status: "covered",
+ agent_id: "hunter-1",
+ reviewed_paths: ["src/router.ts", "src/authz.ts"],
+ local_checks: [sourceCheck(), localCheck("verifier-1", { reviewed_paths: ["src/authz.ts"] })],
+ });
+ assert.deepEqual(errorsFor([independentlyVerified]), []);
+
+ const unownedPath = unit({
+ status: "covered",
+ agent_id: "hunter-1",
+ reviewed_paths: ["src/router.ts", "src/authz.ts"],
+ local_checks: [sourceCheck()],
+ });
+ assert(errorsFor([unownedPath]).some((error) => error.includes("has no check owner")));
+
+ for (const [checkAgentId, artifact] of [
+ [null, "agents/hunter-1/artifacts/result.txt"],
+ ["hunter-1", null],
+ ["hunter-1", "result.txt"],
+ ["hunter-1", "agents/hunter-2/artifacts/result.txt"],
+ ["../hunter", "agents/../hunter/artifacts/result.txt"],
+ ]) {
+ const value = unit({
+ status: "covered",
+ agent_id: "hunter-1",
+ reviewed_paths: ["src/router.ts"],
+ local_checks: [localCheck(checkAgentId, { artifact })],
+ });
+ assert.notEqual(errorsFor([value]).length, 0, `${checkAgentId}: ${artifact}`);
+ }
+
+ const unownedSource = unit({
+ status: "blocked",
+ reviewed_paths: ["src/router.ts"],
+ local_checks: [sourceCheck()],
+ unresolved: ["The boundary behavior is not source-visible."],
+ });
+ assert(errorsFor([unownedSource]).some((error) => error.includes("unit with status \"blocked\" requires a canonical lowercase agent ID")));
+
+ const sourceWithArtifact = unit({
+ status: "covered",
+ agent_id: "hunter-1",
+ reviewed_paths: ["src/router.ts"],
+ local_checks: [sourceCheck("hunter-1", { artifact: "agents/hunter-1/artifacts/source.txt" })],
+ });
+ assert(errorsFor([sourceWithArtifact]).some((error) => error.includes("source-only check must use null")));
+});
+
+test("requires canonical lowercase filesystem-safe agent IDs", () => {
+ for (const value of ["hunter-1", "verifier_2", "a0"]) assert.equal(isSafeAgentId(value), true, value);
+ for (const value of ["Hunter-1", "hunter.1", "hunter-1.", "hunter ", "con", "prn", "aux", "nul", "com1", "lpt9", "../hunter"]) {
+ assert.equal(isSafeAgentId(value), false, value);
+ }
+
+ const caseAlias = unit({ status: "in_progress", agent_id: "Hunter-1" });
+ assert(errorsFor([caseAlias]).some((error) => error.includes("canonical lowercase agent ID")));
+});
+
+test("enforces state evidence", () => {
+ assert(errorsFor([unit({ status: "in_progress" })]).some((error) => error.includes("unit with status \"in_progress\" requires")));
+ assert(errorsFor([unit({ status: "blocked" })]).some((error) => error.includes("unresolved")));
+ assert(errorsFor([unit({ status: "candidate" })]).some((error) => error.includes("reviewed_paths")));
+
+ assert.deepEqual(errorsFor([unit({ status: "in_progress", agent_id: "hunter-1" })]), []);
+ const inProgressEvidence = unit({
+ status: "in_progress",
+ agent_id: "hunter-1",
+ reviewed_paths: ["src/router.ts"],
+ local_checks: [sourceCheck()],
+ });
+ assert(errorsFor([inProgressEvidence]).some((error) => error.includes("must keep this array empty")));
+
+ const assignedPlanned = unit({
+ agent_id: "hunter-1",
+ reviewed_paths: ["src/router.ts"],
+ local_checks: [sourceCheck()],
+ });
+ assert(errorsFor([assignedPlanned]).some((error) => error.includes("planned unit must be unassigned")));
+
+ const candidate = unit({
+ status: "candidate",
+ agent_id: "hunter-1",
+ reviewed_paths: ["src/router.ts"],
+ local_checks: [sourceCheck("hunter-1", { invariant: "Ownership is required.", result: "No check exists." })],
+ result_fingerprints: ["src-router-missing-owner-check"],
+ unresolved: ["validation_budget_exhausted"],
+ });
+ assert.deepEqual(errorsFor([candidate]), []);
+
+ const blocked = unit({
+ status: "blocked",
+ agent_id: "hunter-1",
+ reviewed_paths: ["src/router.ts"],
+ local_checks: [sourceCheck()],
+ unresolved: ["The deployed policy is unavailable."],
+ });
+ assert.deepEqual(errorsFor([blocked]), []);
+ const blockedFingerprint = { ...blocked, result_fingerprints: ["forbidden-fingerprint"] };
+ assert(errorsFor([blockedFingerprint]).some((error) => error.includes("result_fingerprints")));
+
+ for (const status of ["not_applicable", "out_of_scope", "deferred"]) {
+ assert.deepEqual(errorsFor([unit({ status, unresolved: ["Reason recorded."] })]), []);
+ const invalid = unit({
+ status,
+ agent_id: "hunter-1",
+ reviewed_paths: ["src/router.ts"],
+ local_checks: [sourceCheck()],
+ result_fingerprints: ["forbidden-fingerprint"],
+ unresolved: ["Reason recorded."],
+ });
+ const errors = errorsFor([invalid]);
+ assert(errors.some((error) => error.includes("must be unassigned")), status);
+ assert(errors.some((error) => error.includes("reviewed_paths")), status);
+ assert(errors.some((error) => error.includes("result_fingerprints")), status);
+ }
+
+ const coveredFingerprint = unit({
+ status: "covered",
+ agent_id: "hunter-1",
+ reviewed_paths: ["src/router.ts"],
+ local_checks: [sourceCheck()],
+ result_fingerprints: ["forbidden-fingerprint"],
+ });
+ assert(errorsFor([coveredFingerprint]).some((error) => error.includes("result_fingerprints")));
+
+ const coveredUnresolved = unit({
+ status: "covered",
+ agent_id: "hunter-1",
+ reviewed_paths: ["src/router.ts"],
+ local_checks: [sourceCheck()],
+ unresolved: ["Unexpected unresolved claim."],
+ });
+ assert(errorsFor([coveredUnresolved]).some((error) => error.includes("unresolved")));
+});
+
+test("archives prior evidence when a critic assigns a fresh owner", () => {
+ const reassigned = unit({
+ attempts: [archivedAttempt()],
+ wave: 2,
+ status: "in_progress",
+ agent_id: "hunter-2",
+ });
+ assert.deepEqual(errorsFor([reassigned]), []);
+
+ const finalClosure = unit({
+ attempts: [archivedAttempt()],
+ wave: 2,
+ status: "covered",
+ agent_id: "hunter-2",
+ reviewed_paths: ["src/authz.ts"],
+ local_checks: [sourceCheck("hunter-2", { reviewed_paths: ["src/authz.ts"] })],
+ });
+ assert.deepEqual(errorsFor([finalClosure]), []);
+});
+
+test("preserves candidate provenance when reassignment must be deferred", () => {
+ const candidateAttempt = archivedAttempt({
+ status: "candidate",
+ result_fingerprints: ["src-router-missing-owner-check"],
+ unresolved: ["validation_budget_exhausted"],
+ });
+ const deferred = unit({
+ attempts: [candidateAttempt],
+ wave: 2,
+ status: "deferred",
+ unresolved: ["quick_profile_final_critic"],
+ });
+ assert.deepEqual(errorsFor([deferred]), []);
+});
+
+test("rejects reassignment owner reuse and evidence mixing", () => {
+ const reusedOwner = unit({
+ attempts: [archivedAttempt()],
+ wave: 2,
+ status: "in_progress",
+ agent_id: "hunter-1",
+ });
+ assert(errorsFor([reusedOwner]).some((error) => error.includes("current assignment owner must be fresh")));
+
+ const mixedEvidence = unit({
+ attempts: [archivedAttempt({ local_checks: [localCheck()] })],
+ wave: 2,
+ status: "covered",
+ agent_id: "hunter-2",
+ reviewed_paths: ["src/router.ts"],
+ local_checks: [localCheck()],
+ });
+ const errors = errorsFor([mixedEvidence]);
+ assert(errors.some((error) => error.includes("prior assignment owner evidence must remain")));
+ assert(errors.some((error) => error.includes("artifact from an archived attempt cannot be reused")));
+
+ const mixedHistory = unit({
+ attempts: [
+ archivedAttempt({ local_checks: [localCheck()] }),
+ archivedAttempt({
+ wave: 2,
+ agent_id: "hunter-2",
+ local_checks: [localCheck()],
+ }),
+ ],
+ wave: 3,
+ status: "in_progress",
+ agent_id: "hunter-3",
+ });
+ const historyErrors = errorsFor([mixedHistory]);
+ assert(historyErrors.some((error) => error.includes("prior assignment owner evidence must remain in its earlier attempt")));
+ assert(historyErrors.some((error) => error.includes("artifact from an earlier attempt cannot be reused")));
+
+ const unordered = unit({
+ attempts: [archivedAttempt(), archivedAttempt({
+ wave: 1,
+ agent_id: "hunter-2",
+ local_checks: [sourceCheck("hunter-2")],
+ })],
+ wave: 3,
+ status: "in_progress",
+ agent_id: "hunter-3",
+ });
+ assert(errorsFor([unordered]).some((error) => error.includes("strictly increasing")));
+});
+
+test("rejects unsafe paths and malformed fingerprints", () => {
+ for (const value of [
+ "/etc/passwd",
+ "../src/file.js",
+ "src/../file.js",
+ "src/con.txt",
+ "src/PRN",
+ "src/AUX.c",
+ "src/NUL",
+ "src/CLOCK$.txt",
+ "src/conin$.txt",
+ "src/conout$",
+ "src/COM1.log",
+ "src/lpt9",
+ "src/COM\u00b9.log",
+ "src/COM\u00b2.log",
+ "src/COM\u00b3.log",
+ "src/lpt\u00b9",
+ "src/lpt\u00b2",
+ "src/lpt\u00b3",
+ "src/file.js.",
+ "C:/src/file.js",
+ "src/file\n.js",
+ "src/file\u0085.js",
+ "src/file\u2028.js",
+ "src/file\u200b.js",
+ "src/file\u034f.js",
+ "src/file\ufe0f.js",
+ ]) {
+ assert.equal(isSafeRelativePath(value), false, value);
+ }
+ assert.equal(isSafeRelativePath("src/handler.js"), true);
+ assert.equal(isSafeRelativePath("src/caf\u00e9/handler.js"), true);
+ assert(errorsFor([unit({ starting_paths: ["../src/router.ts"] })]).some((error) => error.includes("repository-relative path")));
+ assert(errorsFor([unit({
+ status: "candidate",
+ agent_id: "hunter-1",
+ reviewed_paths: ["src/router.ts"],
+ local_checks: [sourceCheck("hunter-1", { invariant: "Ownership is required.", result: "No check exists." })],
+ result_fingerprints: ["not stable"],
+ })]).some((error) => error.includes("invalid fingerprint")));
+});
+
+test("rejects format, default-ignorable, and invalid-scalar prose", () => {
+ for (const invisible of ["\u200b", "\u034f", "\ufe0f", "\ud800"]) {
+ assert(errorsFor([unit({ surface: invisible })]).some((error) => error.includes("surface")), JSON.stringify(invisible));
+ assert(errorsFor([unit({
+ excluded_blocks: [{ block: "ATTACK-CLASSES.md#Access control", reason: invisible }],
+ })]).some((error) => error.includes("reason")), JSON.stringify(invisible));
+ }
+});
+
+test("quotes input-derived controls in direct validation errors", () => {
+ const invalidStatus = `invalid-${TERMINAL_CONTROL_PAYLOAD}`;
+ const invalidPath = `src/${TERMINAL_CONTROL_PAYLOAD}.js`;
+ const value = unit({
+ status: invalidStatus,
+ agent_id: "hunter-1",
+ reviewed_paths: [invalidPath],
+ local_checks: [sourceCheck()],
+ result_fingerprints: ["force-state-error"],
+ });
+ const output = errorsFor([value]).join("\n");
+
+ assert.match(output, /\$\[0\]\.status/);
+ assert.match(output, /\$\[0\]\.reviewed_paths/);
+ assert.match(output, /\\u001b/);
+ assert.match(output, /\\u0007/);
+ assert.match(output, /\\u0085/);
+ assert.match(output, /\\u202e/);
+ assertNoInjectedControlBytes(output);
+});
+
+test("quotes input-derived controls in CLI validation errors", { skip: !HAS_SAFE_INPUT_OPEN }, () => {
+ const value = unit({
+ status: `invalid-${TERMINAL_CONTROL_PAYLOAD}`,
+ result_fingerprints: ["force-state-error"],
+ });
+ const result = runCli(JSON.stringify([value]));
+
+ assert.equal(result.status, 1, cliOutput(result));
+ assert.match(result.stderr, /\$\[0\]\.status/);
+ assert.match(result.stderr, /\\u001b/);
+ assertNoInjectedControlBytes(result.stderr);
+});
+
+test("returns a generic syntax error without parser-supplied controls", { skip: !HAS_SAFE_INPUT_OPEN }, () => {
+ const malformed = Buffer.concat([
+ Buffer.from("["),
+ Buffer.from(TERMINAL_CONTROL_PAYLOAD),
+ Buffer.from("]"),
+ ]);
+ const result = runCli(malformed);
+
+ assert.equal(result.status, 1, cliOutput(result));
+ assert.equal(result.stderr, "Failed to parse coverage ledger: invalid JSON syntax\n");
+ assertNoInjectedControlBytes(result.stderr);
+});
+
+test("does not reflect controls from a failed CLI input path", () => {
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), "validate-coverage-ledger-path-"));
+ const missingPath = path.join(directory, `missing-${TERMINAL_CONTROL_PAYLOAD}.json`);
+ try {
+ const result = spawnSync(process.execPath, [validatorPath, missingPath], {
+ encoding: "utf8",
+ timeout: CLI_TIMEOUT_MS,
+ });
+ assert.equal(result.status, 1, cliOutput(result));
+ assert.match(result.stderr, /Failed to read coverage ledger:/);
+ assertNoInjectedControlBytes(result.stderr);
+ } finally {
+ fs.rmSync(directory, { recursive: true, force: true });
+ }
+});
+
+test("rejects invalid UTF-8 through the CLI", { skip: !HAS_SAFE_INPUT_OPEN }, () => {
+ const encoded = Buffer.from(JSON.stringify([unit()]));
+ const marker = Buffer.from("Update-user route");
+ const markerOffset = encoded.indexOf(marker);
+ assert.notEqual(markerOffset, -1);
+ const malformed = Buffer.concat([
+ encoded.subarray(0, markerOffset),
+ Buffer.from([0x80]),
+ encoded.subarray(markerOffset + marker.length),
+ ]);
+
+ const result = runCli(malformed);
+ const output = cliOutput(result);
+ assert.equal(result.status, 1, output);
+ assert.match(output, /input is not valid UTF-8/);
+ assert.doesNotMatch(output, /TypeError|stack|at validate-coverage-ledger/i);
+});
+
+test("rejects a FIFO through the CLI without blocking", { skip: process.platform === "win32" || !HAS_SAFE_INPUT_OPEN }, () => {
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), "validate-coverage-ledger-fifo-"));
+ const fifoPath = path.join(directory, "coverage-ledger.json");
+ try {
+ const created = spawnSync("mkfifo", [fifoPath], { encoding: "utf8", timeout: CLI_TIMEOUT_MS });
+ assert.equal(created.status, 0, cliOutput(created));
+
+ const result = spawnSync(process.execPath, [validatorPath, fifoPath], {
+ encoding: "utf8",
+ timeout: CLI_TIMEOUT_MS,
+ });
+ const output = cliOutput(result);
+ assert.notEqual(result.error && result.error.code, "ETIMEDOUT", output);
+ assert.equal(result.status, 1, output);
+ assert.match(output, /input must be a regular file/);
+ assert.doesNotMatch(output, /stack|at validate-coverage-ledger/i);
+ } finally {
+ fs.rmSync(directory, { recursive: true, force: true });
+ }
+});
+
+test("rejects a symlink through the CLI", { skip: process.platform === "win32" || !HAS_SAFE_INPUT_OPEN }, () => {
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), "validate-coverage-ledger-symlink-"));
+ const targetPath = path.join(directory, "target.json");
+ const symlinkPath = path.join(directory, "coverage-ledger.json");
+ try {
+ fs.writeFileSync(targetPath, JSON.stringify([unit()]));
+ fs.symlinkSync(targetPath, symlinkPath);
+ const result = spawnSync(process.execPath, [validatorPath, symlinkPath], {
+ encoding: "utf8",
+ timeout: CLI_TIMEOUT_MS,
+ });
+ const output = cliOutput(result);
+ assert.notEqual(result.error && result.error.code, "ETIMEDOUT", output);
+ assert.equal(result.status, 1, output);
+ assert.match(output, /input must not be a symlink/);
+ assert.doesNotMatch(output, /stack|at validate-coverage-ledger/i);
+ } finally {
+ fs.rmSync(directory, { recursive: true, force: true });
+ }
+});
+
+test("rejects deeply nested input without recursion failure", () => {
+ let nested = 0;
+ for (let depth = 0; depth < 20000; depth++) nested = [nested];
+ assert(errorsFor(nested).some((error) => error.includes("exceeds nesting depth limit 64")));
+ if (!HAS_SAFE_INPUT_OPEN) return;
+
+ const result = runCli(`${"[".repeat(20000)}0${"]".repeat(20000)}`);
+ const output = cliOutput(result);
+ assert.notEqual(result.error && result.error.code, "ETIMEDOUT", output);
+ assert.equal(result.status, 1, output);
+ assert.match(output, /exceeds nesting depth limit 64/);
+ assert.doesNotMatch(output, /RangeError|Maximum call stack|stack|at validate-coverage-ledger/i);
+});
+
+test("rejects multi-megabyte nesting under a constrained Node heap", { skip: !HAS_SAFE_INPUT_OPEN }, () => {
+ const openContainers = "[".repeat(2000000);
+ const cases = [
+ openContainers,
+ `${openContainers}0${"]".repeat(2000000)}`,
+ ];
+ for (const contents of cases) {
+ const result = runCli(contents, {
+ nodeArgs: ["--max-old-space-size=64"],
+ timeout: HOSTILE_CLI_TIMEOUT_MS,
+ });
+ const output = cliOutput(result);
+ assert.notEqual(result.error && result.error.code, "ETIMEDOUT", output);
+ assert.equal(result.status, 1, output);
+ assert.match(output, /exceeds nesting depth limit 64/);
+ assert.doesNotMatch(output, /heap out of memory|allocation failed|RangeError|Maximum call stack|stack|at validate-coverage-ledger/i);
+ }
+});
+
+test("caps malformed 10000-unit validation output", () => {
+ assert.equal(errorsFor(Array.from({ length: LIMITS.units }, () => null)).length, LIMITS.validationErrors);
+ if (!HAS_SAFE_INPUT_OPEN) return;
+
+ const result = runCli(JSON.stringify(Array.from({ length: LIMITS.units }, () => null)));
+ const output = cliOutput(result);
+ assert.notEqual(result.error && result.error.code, "ETIMEDOUT", output);
+ assert.equal(result.status, 1, output);
+ assert.match(output, /output capped at 100/);
+ assert(output.length < 20000, `unexpected output length ${output.length}`);
+ assert.doesNotMatch(output, /RangeError|Maximum call stack|stack|at validate-coverage-ledger/i);
+});
+
+test("rejects malformed top-level data and excessive unit counts", () => {
+ assert.deepEqual(errorsFor({ units: [] }), ["$: expected a top-level array"]);
+ const tooMany = Array.from({ length: 10001 }, () => null);
+ const errors = errorsFor(tooMany);
+ assert.deepEqual(errors, ["$: exceeds 10000 coverage units"]);
+
+ const oversizedCollection = unit({ extra: Array.from({ length: LIMITS.collectionItems + 1 }, () => null) });
+ assert(errorsFor([oversizedCollection]).some((error) => error.includes("exceeds 1000 entries")));
+});
+
+test("accepts a canonical ID derived from near-maximum multibyte references", () => {
+ const canonicalRefs = {
+ surface: "\u6f22".repeat(1024),
+ boundary: "\u00e9".repeat(1024),
+ subsystem: "packages/api",
+ attack_class: "\u6f22".repeat(1023) + "\u00e9",
+ };
+ const value = unit({ canonical_refs: canonicalRefs });
+ assert(value.coverage_id.length > 16384, `coverage_id length ${value.coverage_id.length}`);
+ assert(value.coverage_id.length <= 65536, `coverage_id length ${value.coverage_id.length}`);
+ assert.deepEqual(errorsFor([value]), []);
+
+ if (HAS_SAFE_INPUT_OPEN) {
+ const result = runCli(JSON.stringify([value]));
+ assert.equal(result.status, 0, cliOutput(result));
+ }
+});
diff --git a/.agents/skills/security-audit/validate-findings.cjs b/.agents/skills/security-audit/validate-findings.cjs
new file mode 100644
index 00000000..2843fece
--- /dev/null
+++ b/.agents/skills/security-audit/validate-findings.cjs
@@ -0,0 +1,773 @@
+#!/usr/bin/env node
+
+/**
+ * Validates findings.json against report-schema.json.
+ * Usage: node validate-findings.cjs
+ *
+ * This is a dependency-free interpreter for the JSON Schema keywords used by
+ * report-schema.json, plus finding-specific checks that are clearer in code.
+ */
+
+const fs = require("fs");
+const path = require("path");
+const { TextDecoder } = require("util");
+
+const hasOwn = (value, key) => Object.prototype.hasOwnProperty.call(value, key);
+const SUPPORTED_TYPES = new Set(["object", "array", "string", "integer", "number", "boolean", "null"]);
+const SUPPORTED_KEYWORDS = new Set([
+ "$comment",
+ "additionalProperties",
+ "const",
+ "description",
+ "enum",
+ "items",
+ "minimum",
+ "minItems",
+ "minLength",
+ "oneOf",
+ "pattern",
+ "properties",
+ "required",
+ "type",
+ "uniqueItems",
+ "visibleContent",
+]);
+const SEVERITY_RANK = new Map([
+ ["informational", 0],
+ ["low", 1],
+ ["medium", 2],
+ ["high", 3],
+ ["critical", 4],
+]);
+const LIMITS = Object.freeze({
+ inputBytes: 5 * 1024 * 1024,
+ nestingDepth: 64,
+ arrayItems: 1000,
+ canonicalKeyBytes: 1024 * 1024,
+ uniqueSetBytes: 5 * 1024 * 1024,
+ validationErrors: 100,
+});
+const VISIBLE_CONTENT = /[^\p{White_Space}\p{Cc}\p{Cf}\p{Default_Ignorable_Code_Point}]/u;
+const PATH_FORBIDDEN_CHARACTER = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}\p{Default_Ignorable_Code_Point}]/u;
+const WINDOWS_RESERVED_COMPONENT = /^(?:con|prn|aux|nul|clock\$|conin\$|conout\$|com[1-9\u00b9\u00b2\u00b3]|lpt[1-9\u00b9\u00b2\u00b3])(?:\.|$)/iu;
+const UTF8_DECODER = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
+const UNSAFE_DIAGNOSTIC_CHARACTER = /[\p{Cc}\p{Cf}\p{Cs}\p{Zl}\p{Zp}\p{Default_Ignorable_Code_Point}]/gu;
+const MAX_DIAGNOSTIC_STRING_LENGTH = 256;
+
+class JsonStructureError extends Error {}
+class SafeInputError extends Error {}
+
+function escapeUnsafeDiagnosticCharacters(value) {
+ return String(value).replace(UNSAFE_DIAGNOSTIC_CHARACTER, (character) => {
+ const codePoint = character.codePointAt(0);
+ return codePoint <= 0xffff
+ ? `\\u${codePoint.toString(16).padStart(4, "0")}`
+ : `\\u{${codePoint.toString(16)}}`;
+ });
+}
+
+function safeQuote(value) {
+ let serialized;
+ if (typeof value === "string") {
+ const clipped = value.length > MAX_DIAGNOSTIC_STRING_LENGTH
+ ? `${value.slice(0, MAX_DIAGNOSTIC_STRING_LENGTH)}...`
+ : value;
+ serialized = JSON.stringify(clipped);
+ } else if (value === null || typeof value === "boolean") {
+ serialized = String(value);
+ } else if (typeof value === "number" && Number.isFinite(value)) {
+ serialized = String(value);
+ } else {
+ serialized = `"<${Array.isArray(value) ? "array" : typeof value}>"`;
+ }
+ return escapeUnsafeDiagnosticCharacters(serialized);
+}
+
+function propertyPath(base, key) {
+ return /^[A-Za-z_][A-Za-z0-9_]*$/.test(key)
+ ? `${base}.${key}`
+ : `${base}[${safeQuote(key)}]`;
+}
+
+function createErrorList() {
+ const errors = [];
+ Object.defineProperty(errors, "push", {
+ value(...messages) {
+ const remaining = LIMITS.validationErrors - this.length;
+ if (remaining > 0) {
+ Array.prototype.push.apply(this, messages.slice(0, remaining).map(escapeUnsafeDiagnosticCharacters));
+ }
+ return this.length;
+ },
+ });
+ return errors;
+}
+
+function typeOf(value) {
+ if (Array.isArray(value)) return "array";
+ if (value === null) return "null";
+ return typeof value;
+}
+
+function deepEqual(left, right) {
+ if (left === right) return true;
+ if (typeOf(left) !== typeOf(right)) return false;
+ if (Array.isArray(left)) {
+ return left.length === right.length && left.every((value, index) => deepEqual(value, right[index]));
+ }
+ if (left !== null && typeof left === "object") {
+ const leftKeys = Object.keys(left);
+ const rightKeys = Object.keys(right);
+ return leftKeys.length === rightKeys.length &&
+ leftKeys.every((key) => hasOwn(right, key) && deepEqual(left[key], right[key]));
+ }
+ return false;
+}
+
+function codePointLength(value) {
+ let length = 0;
+ let index = 0;
+ while (index < value.length) {
+ const first = value.charCodeAt(index++);
+ if (first >= 0xd800 && first <= 0xdbff && index < value.length) {
+ const second = value.charCodeAt(index);
+ if (second >= 0xdc00 && second <= 0xdfff) index++;
+ }
+ length++;
+ }
+ return length;
+}
+
+function hasValidUnicodeScalarValues(value) {
+ let index = 0;
+ while (index < value.length) {
+ const first = value.charCodeAt(index++);
+ if (first >= 0xd800 && first <= 0xdbff) {
+ if (index >= value.length) return false;
+ const second = value.charCodeAt(index++);
+ if (second < 0xdc00 || second > 0xdfff) return false;
+ } else if (first >= 0xdc00 && first <= 0xdfff) {
+ return false;
+ }
+ }
+ return true;
+}
+
+function hasVisibleProse(value) {
+ return hasValidUnicodeScalarValues(value) && VISIBLE_CONTENT.test(value);
+}
+
+function canonicalKey(value) {
+ const chunks = [];
+ let bytes = 0;
+
+ function append(chunk) {
+ bytes += Buffer.byteLength(chunk);
+ if (bytes > LIMITS.canonicalKeyBytes) {
+ throw new Error(`canonical key exceeds ${LIMITS.canonicalKeyBytes} byte limit`);
+ }
+ chunks.push(chunk);
+ }
+
+ function encode(item) {
+ const type = typeOf(item);
+ if (type === "null") {
+ append("null");
+ } else if (type === "string") {
+ append(`string:${JSON.stringify(item)}`);
+ } else if (type === "number") {
+ append(`number:${Object.is(item, -0) ? "0" : String(item)}`);
+ } else if (type === "boolean") {
+ append(`boolean:${item ? "true" : "false"}`);
+ } else if (type === "array") {
+ append("array:[");
+ item.forEach((entry, index) => {
+ if (index > 0) append(",");
+ encode(entry);
+ });
+ append("]");
+ } else if (type === "object") {
+ append("object:{");
+ Object.keys(item).sort().forEach((key, index) => {
+ if (index > 0) append(",");
+ append(JSON.stringify(key));
+ append(":");
+ encode(item[key]);
+ });
+ append("}");
+ } else {
+ append(`${type}:${String(item)}`);
+ }
+ }
+
+ encode(value);
+ return { key: chunks.join(""), bytes };
+}
+
+function collectDataLimitErrors(value, location = "$data") {
+ const stack = [{ value, location, depth: value !== null && typeof value === "object" ? 1 : 0 }];
+ const seen = new WeakSet();
+
+ while (stack.length > 0) {
+ const current = stack.pop();
+ if (current.value === null || typeof current.value !== "object") continue;
+ if (current.depth > LIMITS.nestingDepth) {
+ return [escapeUnsafeDiagnosticCharacters(`${current.location}: exceeds ${LIMITS.nestingDepth} level nesting depth limit`)];
+ }
+ if (seen.has(current.value)) {
+ return [escapeUnsafeDiagnosticCharacters(`${current.location}: input must not contain repeated or cyclic object references`)];
+ }
+ seen.add(current.value);
+
+ if (Array.isArray(current.value)) {
+ if (current.value.length > LIMITS.arrayItems) {
+ return [escapeUnsafeDiagnosticCharacters(`${current.location}: exceeds ${LIMITS.arrayItems} item array limit`)];
+ }
+ for (let index = current.value.length - 1; index >= 0; index--) {
+ const child = current.value[index];
+ if (child !== null && typeof child === "object") {
+ stack.push({ value: child, location: `${current.location}[${index}]`, depth: current.depth + 1 });
+ }
+ }
+ } else {
+ const keys = Object.keys(current.value);
+ for (let index = keys.length - 1; index >= 0; index--) {
+ const key = keys[index];
+ const child = current.value[key];
+ if (child !== null && typeof child === "object") {
+ stack.push({ value: child, location: propertyPath(current.location, key), depth: current.depth + 1 });
+ }
+ }
+ }
+ }
+
+ return [];
+}
+
+function collectSchemaErrors(schema, location = "schema") {
+ const errors = createErrorList();
+
+ function check(node, p) {
+ if (node === null || typeof node !== "object" || Array.isArray(node)) {
+ errors.push(`${p}: schema must be an object`);
+ return;
+ }
+
+ for (const key of Object.keys(node)) {
+ if (!SUPPORTED_KEYWORDS.has(key)) errors.push(`${p}: unsupported schema keyword ${safeQuote(key)}`);
+ }
+
+ if (hasOwn(node, "$comment") && typeof node.$comment !== "string") {
+ errors.push(`${p}.$comment: expected string`);
+ }
+ if (hasOwn(node, "description") && typeof node.description !== "string") {
+ errors.push(`${p}.description: expected string`);
+ }
+ if (hasOwn(node, "type") && (!SUPPORTED_TYPES.has(node.type))) {
+ errors.push(`${p}.type: unsupported type ${safeQuote(node.type)}`);
+ }
+ if (hasOwn(node, "properties")) {
+ if (node.properties === null || typeof node.properties !== "object" || Array.isArray(node.properties)) {
+ errors.push(`${p}.properties: expected object`);
+ } else {
+ for (const key of Object.keys(node.properties)) check(node.properties[key], propertyPath(`${p}.properties`, key));
+ }
+ }
+ if (hasOwn(node, "required")) {
+ if (!Array.isArray(node.required) || node.required.some((key) => typeof key !== "string")) {
+ errors.push(`${p}.required: expected an array of strings`);
+ } else if (new Set(node.required).size !== node.required.length) {
+ errors.push(`${p}.required: entries must be unique`);
+ }
+ }
+ if (hasOwn(node, "additionalProperties") && typeof node.additionalProperties !== "boolean") {
+ errors.push(`${p}.additionalProperties: only boolean values are supported`);
+ }
+ if (hasOwn(node, "enum")) {
+ if (!Array.isArray(node.enum) || node.enum.length === 0) {
+ errors.push(`${p}.enum: expected a non-empty array`);
+ } else {
+ const seen = new Set();
+ for (const value of node.enum) {
+ let key;
+ try {
+ key = canonicalKey(value).key;
+ } catch (error) {
+ errors.push(`${p}.enum: ${error.message}`);
+ break;
+ }
+ if (seen.has(key)) {
+ errors.push(`${p}.enum: entries must be unique`);
+ break;
+ }
+ seen.add(key);
+ }
+ }
+ }
+ if (hasOwn(node, "items")) check(node.items, `${p}.items`);
+ for (const keyword of ["minItems", "minLength"]) {
+ if (hasOwn(node, keyword) && (!Number.isInteger(node[keyword]) || node[keyword] < 0)) {
+ errors.push(`${p}.${keyword}: expected a non-negative integer`);
+ }
+ }
+ if (hasOwn(node, "minimum") && (typeof node.minimum !== "number" || !Number.isFinite(node.minimum))) {
+ errors.push(`${p}.minimum: expected a finite number`);
+ }
+ if (hasOwn(node, "pattern")) {
+ if (typeof node.pattern !== "string") {
+ errors.push(`${p}.pattern: expected string`);
+ } else {
+ try {
+ new RegExp(node.pattern);
+ } catch (error) {
+ errors.push(`${p}.pattern: invalid regular expression`);
+ }
+ }
+ }
+ if (hasOwn(node, "uniqueItems") && typeof node.uniqueItems !== "boolean") {
+ errors.push(`${p}.uniqueItems: expected boolean`);
+ }
+ if (hasOwn(node, "visibleContent")) {
+ if (typeof node.visibleContent !== "boolean") {
+ errors.push(`${p}.visibleContent: expected boolean`);
+ } else if (node.visibleContent === true && node.type !== "string") {
+ errors.push(`${p}.visibleContent: requires type "string"`);
+ }
+ }
+ if (hasOwn(node, "oneOf")) {
+ if (!Array.isArray(node.oneOf) || node.oneOf.length === 0) {
+ errors.push(`${p}.oneOf: expected a non-empty array`);
+ } else {
+ node.oneOf.forEach((branch, index) => check(branch, `${p}.oneOf[${index}]`));
+ }
+ }
+ }
+
+ check(schema, location);
+ return errors;
+}
+
+function findDiscriminator(schema) {
+ if (!hasOwn(schema, "properties") || typeof schema.properties !== "object") return null;
+ for (const key of Object.keys(schema.properties)) {
+ const subSchema = schema.properties[key];
+ if (subSchema && typeof subSchema === "object" && hasOwn(subSchema, "const")) {
+ return { key, value: subSchema.const };
+ }
+ }
+ return null;
+}
+
+function validate(value, schema, p, errors) {
+ if (errors.length >= LIMITS.validationErrors) return;
+ if (hasOwn(schema, "oneOf")) {
+ const results = schema.oneOf.map((branch) => collectUnchecked(value, branch, p));
+ const passingIndexes = results
+ .map((branchErrors, index) => branchErrors.length === 0 ? index : -1)
+ .filter((index) => index !== -1);
+
+ if (passingIndexes.length !== 1) {
+ errors.push(`${p}: must match exactly one schema in oneOf; matched ${passingIndexes.length}`);
+ if (passingIndexes.length === 0 && value !== null && typeof value === "object" && !Array.isArray(value)) {
+ const matchingDiscriminators = schema.oneOf
+ .map((branch, index) => ({ discriminator: findDiscriminator(branch), index }))
+ .filter(({ discriminator }) => discriminator && hasOwn(value, discriminator.key) && deepEqual(value[discriminator.key], discriminator.value));
+ if (matchingDiscriminators.length === 1) {
+ errors.push(...results[matchingDiscriminators[0].index]);
+ }
+ }
+ }
+ }
+
+ if (hasOwn(schema, "const") && !deepEqual(value, schema.const)) {
+ errors.push(`${p}: must equal ${safeQuote(schema.const)}, got ${safeQuote(value)}`);
+ }
+ if (hasOwn(schema, "enum") && !schema.enum.some((allowed) => deepEqual(value, allowed))) {
+ const allowed = schema.enum.map(safeQuote).join(", ");
+ errors.push(`${p}: invalid value ${safeQuote(value)} (expected one of ${allowed})`);
+ }
+
+ if (hasOwn(schema, "type") && typeOf(value) !== schema.type && !(schema.type === "integer" && typeOf(value) === "number" && Number.isInteger(value))) {
+ errors.push(`${p}: expected ${schema.type}, got ${typeOf(value)}`);
+ return;
+ }
+
+ if (typeOf(value) === "object") {
+ for (const req of hasOwn(schema, "required") ? schema.required : []) {
+ if (!hasOwn(value, req)) errors.push(`${p}: missing required field ${safeQuote(req)}`);
+ }
+ for (const key of Object.keys(value)) {
+ if (hasOwn(schema, "properties") && hasOwn(schema.properties, key)) {
+ validate(value[key], schema.properties[key], propertyPath(p, key), errors);
+ } else if (hasOwn(schema, "additionalProperties") && schema.additionalProperties === false) {
+ errors.push(`${p}: unexpected field ${safeQuote(key)}`);
+ }
+ }
+ }
+
+ if (Array.isArray(value)) {
+ if (hasOwn(schema, "minItems") && value.length < schema.minItems) {
+ errors.push(`${p}: must have at least ${schema.minItems} item(s), got ${value.length}`);
+ }
+ if (hasOwn(schema, "uniqueItems") && schema.uniqueItems === true) {
+ const seen = new Set();
+ let setBytes = 0;
+ for (let i = 0; i < value.length; i++) {
+ let canonical;
+ try {
+ canonical = canonicalKey(value[i]);
+ } catch (error) {
+ errors.push(`${p}[${i}]: ${error.message}`);
+ break;
+ }
+ if (seen.has(canonical.key)) {
+ errors.push(`${p}: items must be unique; duplicate at index ${i}`);
+ continue;
+ }
+ setBytes += canonical.bytes;
+ if (setBytes > LIMITS.uniqueSetBytes) {
+ errors.push(`${p}: canonical uniqueness set exceeds ${LIMITS.uniqueSetBytes} byte limit`);
+ break;
+ }
+ seen.add(canonical.key);
+ }
+ }
+ if (hasOwn(schema, "items")) {
+ value.forEach((item, index) => validate(item, schema.items, `${p}[${index}]`, errors));
+ }
+ }
+
+ if (typeof value === "string") {
+ if (hasOwn(schema, "minLength") && codePointLength(value) < schema.minLength) {
+ errors.push(`${p}: must have at least ${schema.minLength} character(s)`);
+ }
+ if (schema.visibleContent === true) {
+ if (!hasValidUnicodeScalarValues(value)) {
+ errors.push(`${p}: must contain only valid Unicode scalar values`);
+ } else if (!VISIBLE_CONTENT.test(value)) {
+ errors.push(`${p}: must contain a visible character`);
+ }
+ }
+ if (hasOwn(schema, "pattern") && !(new RegExp(schema.pattern).test(value))) {
+ errors.push(`${p}: must match pattern ${JSON.stringify(schema.pattern)}`);
+ }
+ }
+
+ if (typeof value === "number" && hasOwn(schema, "minimum") && value < schema.minimum) {
+ errors.push(`${p}: must be at least ${schema.minimum}, got ${value}`);
+ }
+}
+
+function collectUnchecked(value, schema, p) {
+ const errors = createErrorList();
+ validate(value, schema, p, errors);
+ return errors;
+}
+
+function collect(value, schema, p = "$data") {
+ const limitErrors = collectDataLimitErrors(value, p);
+ if (limitErrors.length > 0) return limitErrors;
+ return collectUnchecked(value, schema, p);
+}
+
+function isSafeRelativeSourcePath(value) {
+ if (typeof value !== "string" || value.length === 0 || !hasValidUnicodeScalarValues(value) || value.trim() !== value || PATH_FORBIDDEN_CHARACTER.test(value) || value.includes("\\") || value.includes(":")) return false;
+ if (path.posix.isAbsolute(value) || path.win32.isAbsolute(value) || /^[A-Za-z]:/.test(value) || value.startsWith("~")) return false;
+ const segments = value.split("/");
+ return segments.every((segment) =>
+ segment !== "" &&
+ segment !== "." &&
+ segment !== ".." &&
+ !/[ .]$/u.test(segment) &&
+ !WINDOWS_RESERVED_COMPONENT.test(segment));
+}
+
+function collectFindingSemanticErrors(findings) {
+ const errors = createErrorList();
+ if (!Array.isArray(findings)) return errors;
+
+ const fingerprints = new Map();
+ let previousFingerprint = null;
+ findings.forEach((finding, index) => {
+ if (errors.length >= LIMITS.validationErrors) return;
+ if (!finding || typeof finding !== "object" || Array.isArray(finding)) return;
+ const base = `$[${index}]`;
+
+ if (hasOwn(finding, "fingerprint") && typeof finding.fingerprint === "string") {
+ if (fingerprints.has(finding.fingerprint)) {
+ errors.push(`${base}.fingerprint: duplicate of $[${fingerprints.get(finding.fingerprint)}].fingerprint`);
+ } else {
+ fingerprints.set(finding.fingerprint, index);
+ }
+ if (previousFingerprint !== null && previousFingerprint > finding.fingerprint) {
+ errors.push(`${base}.fingerprint: findings must be sorted lexicographically`);
+ }
+ previousFingerprint = finding.fingerprint;
+ }
+
+ for (const field of ["trace", "evidence"]) {
+ if (!hasOwn(finding, field) || !Array.isArray(finding[field])) continue;
+ finding[field].forEach((entry, entryIndex) => {
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) return;
+ if (hasOwn(entry, "line") && (!Number.isInteger(entry.line) || entry.line < 1)) {
+ errors.push(`${base}.${field}[${entryIndex}].line: must be a positive integer`);
+ }
+ if (hasOwn(entry, "file") && !isSafeRelativeSourcePath(entry.file)) {
+ errors.push(`${base}.${field}[${entryIndex}].file: must be a safe repository-relative source path`);
+ }
+ });
+ }
+ if (finding.remediation && Array.isArray(finding.remediation.code_changes)) {
+ finding.remediation.code_changes.forEach((change, changeIndex) => {
+ if (change && hasOwn(change, "file_name") && !isSafeRelativeSourcePath(change.file_name)) {
+ errors.push(`${base}.remediation.code_changes[${changeIndex}].file_name: must be a safe repository-relative source path`);
+ }
+ });
+ }
+
+ if (Array.isArray(finding.trace) && finding.trace.length === 1) {
+ const kind = finding.trace[0] && finding.trace[0].kind;
+ if (kind !== "entrypoint" && kind !== "sink") {
+ errors.push(`${base}.trace[0].kind: a one-line trace must be "entrypoint" or "sink"`);
+ }
+ } else if (Array.isArray(finding.trace) && finding.trace.length > 1) {
+ const last = finding.trace.length - 1;
+ if (finding.trace[0] && finding.trace[0].kind !== "entrypoint") {
+ errors.push(`${base}.trace[0].kind: must be "entrypoint", got ${safeQuote(finding.trace[0].kind)}`);
+ }
+ if (finding.trace[last] && finding.trace[last].kind !== "sink") {
+ errors.push(`${base}.trace[${last}].kind: must be "sink", got ${safeQuote(finding.trace[last].kind)}`);
+ }
+ for (let traceIndex = 1; traceIndex < last; traceIndex++) {
+ if (finding.trace[traceIndex] && finding.trace[traceIndex].kind !== "propagation") {
+ errors.push(`${base}.trace[${traceIndex}].kind: must be "propagation", got ${safeQuote(finding.trace[traceIndex].kind)}`);
+ }
+ }
+ }
+
+ const verdict = finding.verdict;
+ if (verdict === "confirmed") {
+ for (const forbidden of ["claimed_root_cause", "blockers", "validation_plan", "reason"]) {
+ if (hasOwn(finding, forbidden)) errors.push(`${base}: confirmed finding must not contain ${safeQuote(forbidden)}`);
+ }
+ if (!finding.execution || typeof finding.execution !== "object" || typeof finding.execution.observed_result !== "string" || !hasVisibleProse(finding.execution.observed_result)) {
+ errors.push(`${base}: confirmed finding requires a visible execution observed_result`);
+ }
+ if (!finding.remediation || typeof finding.remediation !== "object" || typeof finding.remediation.strategy !== "string" || !hasVisibleProse(finding.remediation.strategy)) {
+ errors.push(`${base}: confirmed finding requires visible remediation`);
+ }
+ const overall = finding.severity && finding.severity.overall_severity;
+ const impact = finding.severity && finding.severity.impact && finding.severity.impact.score;
+ if (SEVERITY_RANK.has(overall) && SEVERITY_RANK.has(impact) && SEVERITY_RANK.get(overall) > SEVERITY_RANK.get(impact)) {
+ errors.push(`${base}.severity.overall_severity: cannot exceed demonstrated impact ${safeQuote(impact)}`);
+ }
+ } else if (verdict === "needs_validation") {
+ if (hasOwn(finding, "severity")) errors.push(`${base}: needs_validation finding must not contain "severity"`);
+ for (const forbidden of ["execution", "remediation", "reason", "root_cause"]) {
+ if (hasOwn(finding, forbidden)) errors.push(`${base}: needs_validation finding must not contain ${safeQuote(forbidden)}`);
+ }
+ const plan = finding.validation_plan;
+ const hasLocalPlan = plan && typeof plan.local === "string" && hasVisibleProse(plan.local);
+ const hasDeploymentPlan = plan && typeof plan.deployment === "string" && hasVisibleProse(plan.deployment);
+ if (!hasLocalPlan && !hasDeploymentPlan) {
+ errors.push(`${base}.validation_plan: requires at least one visible local or deployment plan`);
+ }
+ } else if (verdict === "rejected") {
+ for (const forbidden of ["severity", "execution", "remediation", "blockers", "validation_plan", "root_cause"]) {
+ if (hasOwn(finding, forbidden)) errors.push(`${base}: rejected finding must not contain ${safeQuote(forbidden)}`);
+ }
+ }
+ });
+
+ return errors;
+}
+
+function validateDocument(findings, schema) {
+ const schemaErrors = collectSchemaErrors(schema);
+ if (schemaErrors.length > 0) return schemaErrors;
+ const limitErrors = collectDataLimitErrors(findings, "$");
+ if (limitErrors.length > 0) return limitErrors;
+ const errors = collectUnchecked(findings, schema, "$");
+ if (errors.length < LIMITS.validationErrors) {
+ errors.push(...collectFindingSemanticErrors(findings));
+ }
+ return errors;
+}
+
+function loadSchema(schemaPath) {
+ const schema = JSON.parse(fs.readFileSync(schemaPath, "utf8"));
+ const errors = collectSchemaErrors(schema);
+ if (errors.length > 0) throw new Error(`unsupported or invalid report schema:\n${errors.join("\n")}`);
+ return schema;
+}
+
+function readFileWithinLimit(file) {
+ const noFollow = fs.constants.O_NOFOLLOW;
+ const nonBlock = fs.constants.O_NONBLOCK;
+ if (!Number.isInteger(noFollow) || noFollow === 0 || !Number.isInteger(nonBlock) || nonBlock === 0) {
+ throw new SafeInputError("OS no-follow and nonblocking input protection is unavailable");
+ }
+
+ let descriptor;
+ try {
+ descriptor = fs.openSync(file, fs.constants.O_RDONLY | noFollow | nonBlock);
+ } catch (error) {
+ if (error && (error.code === "ELOOP" || error.code === "EMLINK")) {
+ throw new SafeInputError("input must not be a symlink");
+ }
+ throw error;
+ }
+ try {
+ const stat = fs.fstatSync(descriptor);
+ if (!stat.isFile()) {
+ throw new SafeInputError("input must be a regular file");
+ }
+ if (stat.size > LIMITS.inputBytes) {
+ throw new SafeInputError(`input exceeds ${LIMITS.inputBytes} byte limit`);
+ }
+
+ const chunks = [];
+ const buffer = Buffer.allocUnsafe(64 * 1024);
+ let bytesRead = 0;
+ while (true) {
+ const count = fs.readSync(descriptor, buffer, 0, buffer.length, null);
+ if (count === 0) break;
+ bytesRead += count;
+ if (bytesRead > LIMITS.inputBytes) {
+ throw new SafeInputError(`input exceeds ${LIMITS.inputBytes} byte limit`);
+ }
+ chunks.push(Buffer.from(buffer.subarray(0, count)));
+ }
+ try {
+ return UTF8_DECODER.decode(Buffer.concat(chunks, bytesRead));
+ } catch {
+ throw new SafeInputError("input is not valid UTF-8");
+ }
+ } finally {
+ fs.closeSync(descriptor);
+ }
+}
+
+function enforceJsonTextLimits(contents) {
+ const containers = [];
+ let inString = false;
+ let escaped = false;
+
+ function markArrayItem() {
+ const container = containers[containers.length - 1];
+ if (!container || container.type !== "array" || !container.expectsItem) return;
+ container.expectsItem = false;
+ container.items++;
+ if (container.items > LIMITS.arrayItems) {
+ throw new JsonStructureError(`input exceeds ${LIMITS.arrayItems} item array limit`);
+ }
+ }
+
+ for (let index = 0; index < contents.length; index++) {
+ const character = contents[index];
+ if (inString) {
+ if (escaped) {
+ escaped = false;
+ } else if (character === "\\") {
+ escaped = true;
+ } else if (character === "\"") {
+ inString = false;
+ }
+ continue;
+ }
+
+ if (character === "\"") {
+ markArrayItem();
+ inString = true;
+ } else if (character === "[" || character === "{") {
+ markArrayItem();
+ if (containers.length >= LIMITS.nestingDepth) {
+ throw new JsonStructureError(`input exceeds ${LIMITS.nestingDepth} level nesting depth limit`);
+ }
+ containers.push({
+ type: character === "[" ? "array" : "object",
+ expectsItem: character === "[",
+ items: 0,
+ });
+ } else if (character === "]" || character === "}") {
+ containers.pop();
+ } else if (character === ",") {
+ const container = containers[containers.length - 1];
+ if (container && container.type === "array") container.expectsItem = true;
+ } else if (!/\s/.test(character)) {
+ markArrayItem();
+ }
+ }
+}
+
+function run(file) {
+ if (!file) {
+ console.error("Usage: node validate-findings.cjs ");
+ return 1;
+ }
+
+ let schema;
+ try {
+ schema = loadSchema(path.join(__dirname, "report-schema.json"));
+ } catch (error) {
+ console.error("Failed to load report-schema.json:", error.message);
+ return 1;
+ }
+
+ let contents;
+ try {
+ contents = readFileWithinLimit(file);
+ } catch (error) {
+ const reason = error instanceof SafeInputError ? error.message : "input could not be opened or read safely";
+ console.error(`Failed to read findings JSON: ${reason}`);
+ return 1;
+ }
+
+ try {
+ enforceJsonTextLimits(contents);
+ } catch (error) {
+ const reason = error instanceof JsonStructureError ? error.message : "invalid JSON structure";
+ console.error(`Failed to parse findings JSON: ${reason}`);
+ return 1;
+ }
+
+ let findings;
+ try {
+ findings = JSON.parse(contents);
+ } catch {
+ console.error("Failed to parse findings JSON: invalid JSON syntax");
+ return 1;
+ }
+
+ let errors;
+ try {
+ errors = validateDocument(findings, schema);
+ } catch {
+ console.error("Failed to validate findings JSON: unexpected validation error");
+ return 1;
+ }
+ for (const message of errors) console.error("ERROR:", escapeUnsafeDiagnosticCharacters(message));
+ if (errors.length > 0) {
+ const cap = errors.length === LIMITS.validationErrors ? `; output capped at ${LIMITS.validationErrors}` : "";
+ console.error(`FAIL: ${errors.length} validation error(s)${cap}`);
+ return 1;
+ }
+ console.log(`PASS: ${findings.length} findings valid`);
+ return 0;
+}
+
+module.exports = {
+ LIMITS,
+ PATH_FORBIDDEN_CHARACTER,
+ UNSAFE_DIAGNOSTIC_CHARACTER,
+ VISIBLE_CONTENT,
+ WINDOWS_RESERVED_COMPONENT,
+ collect,
+ collectFindingSemanticErrors,
+ collectSchemaErrors,
+ hasVisibleProse,
+ isSafeRelativeSourcePath,
+ validateDocument,
+};
+
+if (require.main === module) process.exit(run(process.argv[2]));
diff --git a/.agents/skills/security-audit/validate-findings.test.cjs b/.agents/skills/security-audit/validate-findings.test.cjs
new file mode 100644
index 00000000..8d245b22
--- /dev/null
+++ b/.agents/skills/security-audit/validate-findings.test.cjs
@@ -0,0 +1,652 @@
+const assert = require("node:assert/strict");
+const fs = require("node:fs");
+const os = require("node:os");
+const path = require("node:path");
+const { spawnSync } = require("node:child_process");
+const test = require("node:test");
+const schema = require("./report-schema.json");
+const {
+ LIMITS,
+ collect,
+ collectSchemaErrors,
+ validateDocument,
+} = require("./validate-findings.cjs");
+
+const validatorPath = path.join(__dirname, "validate-findings.cjs");
+const CLI_TIMEOUT_MS = 5000;
+const HOSTILE_CLI_TIMEOUT_MS = 15000;
+const HAS_SAFE_INPUT_OPEN = Number.isInteger(fs.constants.O_NOFOLLOW) &&
+ fs.constants.O_NOFOLLOW !== 0 &&
+ Number.isInteger(fs.constants.O_NONBLOCK) &&
+ fs.constants.O_NONBLOCK !== 0;
+const TERMINAL_CONTROL_PAYLOAD = "\u001b\u0007\u0085\u202e\u034f\ufe0f";
+const TERMINAL_CONTROL_BYTES = [
+ Buffer.from([0x1b]),
+ Buffer.from([0x07]),
+ Buffer.from("\u0085"),
+ Buffer.from("\u202e"),
+ Buffer.from("\u034f"),
+ Buffer.from("\ufe0f"),
+];
+
+function source(kind = "entrypoint", file = "src/handler.c", line = 10) {
+ return { kind, file, line, scope: "handle", description: "Attacker data reaches the operation." };
+}
+
+function evidence(file = "src/handler.c", line = 10) {
+ return { file, line, description: "The source performs the operation without the required check." };
+}
+
+function confirmed() {
+ return {
+ verdict: "confirmed",
+ fingerprint: "src-handler-missing-check",
+ title: "Missing ownership check",
+ description: "An attacker can reach an operation without the intended ownership check.",
+ root_cause: "handle omits the ownership check before changing the object.",
+ intended_behavior: "Only the object's owner can change it.",
+ trace: [source("entrypoint"), source("propagation", "src/model.c", 20), source("sink", "src/store.c", 30)],
+ evidence: [evidence()],
+ conditions: [],
+ execution: {
+ attacker_perspective: "An unprivileged remote user with their own account.",
+ payloads: ["An object identifier owned by another user."],
+ instructions: ["Submit the identifier through the public operation."],
+ observed_result: "The other user's object changes.",
+ },
+ remediation: { strategy: "Check ownership before the state change." },
+ severity: {
+ likelihood: { score: "medium", reason: "The operation is directly reachable." },
+ impact: { score: "medium", reason: "The attacker changes one protected object." },
+ overall_severity: "medium",
+ },
+ confidence: { score: "high", reason: "The source path and result were reproduced." },
+ };
+}
+
+function needsValidation() {
+ return {
+ verdict: "needs_validation",
+ fingerprint: "src-parser-size-hypothesis",
+ title: "Unchecked parsed size",
+ description: "A parsed size may reach an allocation without a limit.",
+ claimed_root_cause: "parse_size may pass an unbounded value to allocate.",
+ trace: [source()],
+ evidence: [evidence()],
+ blockers: ["The generated parser source is absent from this checkout."],
+ validation_plan: {
+ local: "Generate the parser and submit the smallest input that exceeds the documented limit.",
+ deployment: "In an approved test deployment, confirm the request reaches the generated parser and record the bounded observable result.",
+ },
+ };
+}
+
+function rejected() {
+ return {
+ verdict: "rejected",
+ fingerprint: "src-router-auth-bypass",
+ title: "Authorization bypass in router",
+ description: "The candidate claimed a route bypassed authorization.",
+ claimed_root_cause: "dispatch was claimed to skip the authorization wrapper.",
+ trace: [source("sink")],
+ evidence: [evidence()],
+ reason: "All routes pass through the authorization wrapper before dispatch.",
+ };
+}
+
+function errorsFor(value) {
+ return validateDocument(value, schema);
+}
+
+function runCli(contents, options = {}) {
+ const { nodeArgs = [], timeout = CLI_TIMEOUT_MS } = options;
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), "validate-findings-"));
+ const findingsPath = path.join(directory, "findings.json");
+ try {
+ fs.writeFileSync(findingsPath, contents);
+ return spawnSync(process.execPath, [...nodeArgs, validatorPath, findingsPath], {
+ encoding: "utf8",
+ timeout,
+ });
+ } finally {
+ fs.rmSync(directory, { recursive: true, force: true });
+ }
+}
+
+function cliOutput(result) {
+ return `${result.stdout}${result.stderr}`;
+}
+
+function assertNoInjectedControlBytes(output) {
+ const bytes = Buffer.isBuffer(output) ? output : Buffer.from(output, "utf8");
+ for (const marker of TERMINAL_CONTROL_BYTES) {
+ assert.equal(bytes.indexOf(marker), -1, `found raw control bytes ${marker.toString("hex")}`);
+ }
+}
+
+function producerShapedFindings() {
+ const demonstrated = confirmed();
+ demonstrated.conditions = [{
+ kind: "authentication_level",
+ description: "The attacker needs a normal account.",
+ }];
+ demonstrated.execution.payloads = ["", " \t\r\n", "\u0000\u001f\u007f", "\u034f", "\ufe0f", "\ud800", "\udc00", "[{,}]\\\""];
+ demonstrated.remediation.code_changes = [{
+ file_name: "src/handler.c",
+ fixed_code: "",
+ }];
+
+ const blocked = needsValidation();
+ delete blocked.validation_plan.deployment;
+
+ return [demonstrated, blocked, rejected()];
+}
+
+function rejectMutation(factory, mutate) {
+ const value = factory();
+ mutate(value);
+ assert.notEqual(errorsFor([value]).length, 0);
+}
+
+test("schema is an actual top-level array with exactly three branches", () => {
+ assert.equal(schema.type, "array");
+ assert.equal(schema.items.oneOf.length, 3);
+ assert.deepEqual(schema.items.oneOf.map((branch) => branch.properties.verdict.const), [
+ "confirmed", "needs_validation", "rejected",
+ ]);
+ const confirmedSchema = schema.items.oneOf[0].properties;
+ assert.equal(confirmedSchema.title.visibleContent, true);
+ assert.equal(confirmedSchema.execution.properties.payloads.items.minLength, undefined);
+ assert.equal(confirmedSchema.execution.properties.payloads.items.visibleContent, undefined);
+ assert.equal(confirmedSchema.remediation.properties.code_changes.items.properties.fixed_code.minLength, undefined);
+});
+
+test("accepts a producer-shaped findings document through the CLI", () => {
+ const result = runCli(JSON.stringify(producerShapedFindings()));
+ assert.equal(result.status, 0, cliOutput(result));
+ assert.match(result.stdout, /PASS: 3 findings valid/);
+});
+
+test("accepts empty output and each complete branch", () => {
+ assert.deepEqual(errorsFor([]), []);
+ assert.deepEqual(errorsFor([confirmed(), needsValidation(), rejected()]), []);
+ const localOnly = needsValidation();
+ delete localOnly.validation_plan.deployment;
+ assert.deepEqual(errorsFor([localOnly]), []);
+ const deploymentOnly = needsValidation();
+ delete deploymentOnly.validation_plan.local;
+ assert.deepEqual(errorsFor([deploymentOnly]), []);
+});
+
+test("allows a one-line finding trace", () => {
+ const finding = confirmed();
+ finding.trace = [source("entrypoint")];
+ assert.deepEqual(errorsFor([finding]), []);
+});
+
+test("rejects empty required content", () => {
+ const cases = [
+ [confirmed, (finding) => { finding.title = ""; }],
+ [confirmed, (finding) => { finding.title = " "; }],
+ [confirmed, (finding) => { finding.evidence = []; }],
+ [confirmed, (finding) => { finding.execution.payloads = []; }],
+ [confirmed, (finding) => { finding.execution.instructions = []; }],
+ [confirmed, (finding) => { finding.execution.observed_result = ""; }],
+ [confirmed, (finding) => { finding.remediation.strategy = ""; }],
+ [needsValidation, (finding) => { finding.blockers = []; }],
+ [needsValidation, (finding) => { finding.validation_plan = {}; }],
+ [needsValidation, (finding) => { finding.validation_plan = { local: " " }; }],
+ [rejected, (finding) => { finding.claimed_root_cause = ""; }],
+ ];
+ for (const [factory, mutate] of cases) rejectMutation(factory, mutate);
+});
+
+test("preserves exact payload and replacement-code strings", () => {
+ const finding = confirmed();
+ const payloads = ["", " \t\r\n", "\u0000\u001f\u007f", "\u034f", "\ufe0f", "\ud800", "\udc00"];
+ const fixedCode = "\u0000 \t\r\n\u001f\u007f\u034f\ufe0f\ud800x\udc00";
+ finding.execution.payloads = payloads.slice();
+ finding.remediation.code_changes = [{ file_name: "src/handler.c", fixed_code: fixedCode }];
+
+ assert.deepEqual(errorsFor([finding]), []);
+ assert.deepEqual(finding.execution.payloads, payloads);
+ assert.equal(finding.remediation.code_changes[0].fixed_code, fixedCode);
+});
+
+test("rejects invalid scalars and whitespace, control, format, or default-ignorable prose", () => {
+ for (const invisible of ["\u0000\t\r\n\u001f\u007f\u200b", "\u034f", "\ufe0f", "\ud800", "\udc00", "visible\ud800"]) {
+ const cases = [
+ [confirmed, (finding) => { finding.title = invisible; }],
+ [confirmed, (finding) => { finding.trace[0].scope = invisible; }],
+ [confirmed, (finding) => { finding.evidence[0].description = invisible; }],
+ [confirmed, (finding) => { finding.execution.instructions = [invisible]; }],
+ [confirmed, (finding) => { finding.remediation.strategy = invisible; }],
+ [confirmed, (finding) => { finding.severity.impact.reason = invisible; }],
+ [confirmed, (finding) => { finding.confidence.reason = invisible; }],
+ [needsValidation, (finding) => { finding.blockers = [invisible]; }],
+ [needsValidation, (finding) => { finding.validation_plan = { local: invisible }; }],
+ [rejected, (finding) => { finding.reason = invisible; }],
+ ];
+ for (const [factory, mutate] of cases) rejectMutation(factory, mutate);
+ }
+});
+
+test("quotes input-derived controls in direct validation values and paths", () => {
+ const finding = confirmed();
+ finding.trace[0].kind = `invalid-${TERMINAL_CONTROL_PAYLOAD}`;
+ finding.execution[`extra-${TERMINAL_CONTROL_PAYLOAD}`] = "value";
+
+ const cyclic = {};
+ cyclic[`path-${TERMINAL_CONTROL_PAYLOAD}`] = cyclic;
+ const output = [
+ ...errorsFor([finding]),
+ ...collect(cyclic, { type: "object" }, "$input"),
+ ].join("\n");
+
+ for (const escaped of ["\\u001b", "\\u0007", "\\u0085", "\\u202e", "\\u034f", "\\ufe0f"]) {
+ assert(output.includes(escaped), `missing escaped diagnostic ${escaped}`);
+ }
+ assertNoInjectedControlBytes(output);
+});
+
+test("rejects line zero", () => {
+ rejectMutation(confirmed, (finding) => { finding.trace[0].line = 0; });
+ rejectMutation(rejected, (finding) => { finding.evidence[0].line = 0; });
+});
+
+test("does not treat inherited or Object-prototype properties as schema properties", () => {
+ rejectMutation(confirmed, (finding) => { finding.constructor = "not allowed"; });
+ const inherited = Object.create({ verdict: "confirmed" });
+ assert(errorsFor([inherited]).some((error) => error.includes("exactly one")));
+ assert(collect(Object.create({ constructor: "inherited" }), {
+ type: "object",
+ properties: { constructor: { type: "string" } },
+ required: ["constructor"],
+ additionalProperties: false,
+ }).some((error) => error.includes("missing required")));
+});
+
+test("oneOf requires exactly one passing branch", () => {
+ assert(collect("value", { oneOf: [{ type: "string" }, { minLength: 1 }] }, "$test")
+ .some((error) => error.includes("matched 2")));
+ assert(collect(7, { oneOf: [{ type: "string" }, { minimum: 10 }] }, "$test")
+ .some((error) => error.includes("matched 0")));
+});
+
+test("rejects duplicate fingerprints and unique array entries", () => {
+ const first = confirmed();
+ const second = rejected();
+ second.fingerprint = first.fingerprint;
+ assert(errorsFor([first, second]).some((error) => error.includes("duplicate of")));
+ rejectMutation(needsValidation, (finding) => { finding.blockers = [finding.blockers[0], finding.blockers[0]]; });
+});
+
+test("uses canonical Set uniqueness for structured entries at the array limit", () => {
+ const entries = Array.from({ length: LIMITS.arrayItems }, (_, id) => ({ id, label: String(id) }));
+ assert.deepEqual(collect(entries, { type: "array", uniqueItems: true }), []);
+
+ const duplicate = entries.slice(0, -1);
+ duplicate.push({ label: "0", id: 0 });
+ assert(collect(duplicate, { type: "array", uniqueItems: true })
+ .some((error) => error.includes(`duplicate at index ${LIMITS.arrayItems - 1}`)));
+});
+
+test("bounds canonical uniqueness keys and Set storage", () => {
+ const oversizedKey = "x".repeat(LIMITS.canonicalKeyBytes + 1);
+ assert(collect([oversizedKey], { type: "array", uniqueItems: true })
+ .some((error) => error.includes("canonical key exceeds")));
+
+ const itemLength = Math.floor(LIMITS.uniqueSetBytes / 6);
+ const largeUniqueItems = Array.from({ length: 6 }, (_, index) => `${index}${"x".repeat(itemLength)}`);
+ assert(collect(largeUniqueItems, { type: "array", uniqueItems: true })
+ .some((error) => error.includes("canonical uniqueness set exceeds")));
+});
+
+test("requires findings to be sorted by fingerprint", () => {
+ const first = confirmed();
+ const second = rejected();
+ assert(errorsFor([second, first]).some((error) => error.includes("sorted lexicographically")));
+});
+
+test("rejects severity above demonstrated impact", () => {
+ rejectMutation(confirmed, (finding) => {
+ finding.severity.overall_severity = "high";
+ finding.severity.impact.score = "medium";
+ });
+});
+
+test("rejects unsafe source paths", () => {
+ const badPaths = [
+ "/etc/passwd",
+ "../src/file.c",
+ "src/../file.c",
+ "src//file.c",
+ "C:\\src\\file.c",
+ "src/file:name.c",
+ "src/file\nname.c",
+ "src/file\u0001name.c",
+ "src/file\u0085name.c",
+ "src/file\u2028name.c",
+ "src/file\u202ename.c",
+ "src/file\u2066name.c",
+ "src/file\u200dname.c",
+ "src/file\u034fname.c",
+ "src/file\ufe0fname.c",
+ "src/file\ud800name.c",
+ "src/file\udc00name.c",
+ "CON",
+ "src/con.txt",
+ "src/PRN",
+ "src/AUX.c",
+ "src/NUL",
+ "src/COM1.log",
+ "src/lpt9",
+ "src/CONIN$",
+ "src/CONOUT$.txt",
+ "src/CLOCK$.txt",
+ "src/COM\u00b9.log",
+ "src/LPT\u00b2.log",
+ "src /file.c",
+ "src./file.c",
+ "src/file.c ",
+ "src/file.c.",
+ ];
+ for (const badPath of badPaths) {
+ rejectMutation(confirmed, (finding) => { finding.trace[0].file = badPath; });
+ }
+ rejectMutation(rejected, (finding) => { finding.evidence[0].file = "NUL.txt"; });
+ rejectMutation(confirmed, (finding) => {
+ finding.remediation.code_changes = [{ file_name: "src/file:name.c", fixed_code: "replacement" }];
+ });
+});
+
+test("accepts legitimate Unicode source paths and prose", () => {
+ const finding = confirmed();
+ finding.title = "Finding \ud83d\ude00 cafe\u0301";
+ finding.trace[0].file = "src/日本語/cafe\u0301-\ud83d\ude00.ts";
+ finding.evidence[0].file = "src/mañana/файл.ts";
+ finding.remediation.code_changes = [{
+ file_name: "src/修正/éxito.ts",
+ fixed_code: "replacement",
+ }];
+ assert.deepEqual(errorsFor([finding]), []);
+});
+
+test("CLI rejects input above the byte limit without an exception trace", () => {
+ const result = runCli(Buffer.alloc(LIMITS.inputBytes + 1, 0x20));
+ const output = cliOutput(result);
+ assert.equal(result.status, 1, output);
+ assert.match(output, new RegExp(`input exceeds ${LIMITS.inputBytes} byte limit`));
+ assert.doesNotMatch(output, /RangeError|Maximum call stack|heap out of memory/i);
+});
+
+test("CLI rejects invalid UTF-8 without replacement or an exception trace", () => {
+ const findings = producerShapedFindings();
+ findings[0].execution.payloads = ["INVALID_UTF8"];
+ const encoded = Buffer.from(JSON.stringify(findings));
+ const marker = Buffer.from("INVALID_UTF8");
+ const markerOffset = encoded.indexOf(marker);
+ assert.notEqual(markerOffset, -1);
+ const malformed = Buffer.concat([
+ encoded.subarray(0, markerOffset),
+ Buffer.from([0x80]),
+ encoded.subarray(markerOffset + marker.length),
+ ]);
+
+ const result = runCli(malformed);
+ const output = cliOutput(result);
+ assert.equal(result.status, 1, output);
+ assert.match(output, /input is not valid UTF-8/);
+ assert.doesNotMatch(output, /TypeError|stack|at validate-findings/i);
+});
+
+test("quotes input-derived controls in CLI validation errors", { skip: !HAS_SAFE_INPUT_OPEN }, () => {
+ const finding = confirmed();
+ finding.trace[0].kind = `invalid-${TERMINAL_CONTROL_PAYLOAD}`;
+ finding.execution[`extra-${TERMINAL_CONTROL_PAYLOAD}`] = "value";
+ const result = runCli(JSON.stringify([finding]));
+
+ assert.equal(result.status, 1, cliOutput(result));
+ assert.match(result.stderr, /\$\[0\]\.trace\[0\]\.kind/);
+ assert.match(result.stderr, /\\u001b/);
+ assert.match(result.stderr, /\\u202e/);
+ assertNoInjectedControlBytes(result.stderr);
+});
+
+test("returns a generic syntax error without parser-supplied controls", { skip: !HAS_SAFE_INPUT_OPEN }, () => {
+ const malformed = Buffer.concat([
+ Buffer.from("["),
+ Buffer.from(TERMINAL_CONTROL_PAYLOAD),
+ Buffer.from("]"),
+ ]);
+ const result = runCli(malformed);
+
+ assert.equal(result.status, 1, cliOutput(result));
+ assert.equal(result.stderr, "Failed to parse findings JSON: invalid JSON syntax\n");
+ assertNoInjectedControlBytes(result.stderr);
+});
+
+test("does not reflect controls from a failed CLI input path", () => {
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), "validate-findings-path-"));
+ const missingPath = path.join(directory, `missing-${TERMINAL_CONTROL_PAYLOAD}.json`);
+ try {
+ const result = spawnSync(process.execPath, [validatorPath, missingPath], {
+ encoding: "utf8",
+ timeout: CLI_TIMEOUT_MS,
+ });
+ assert.equal(result.status, 1, cliOutput(result));
+ assert.match(result.stderr, /Failed to read findings JSON:/);
+ assertNoInjectedControlBytes(result.stderr);
+ } finally {
+ fs.rmSync(directory, { recursive: true, force: true });
+ }
+});
+
+test("CLI rejects lone-surrogate prose without changing payload semantics", () => {
+ const findings = producerShapedFindings();
+ findings[0].title = "\ud800";
+ const result = runCli(JSON.stringify(findings));
+ const output = cliOutput(result);
+ assert.equal(result.status, 1, output);
+ assert.match(output, /must contain only valid Unicode scalar values/);
+ assert.doesNotMatch(output, /stack|at validate-findings/i);
+});
+
+test("CLI rejects Unicode format controls in source paths", () => {
+ const findings = producerShapedFindings();
+ findings[0].trace[0].file = "src/file\u202ename.c";
+ const result = runCli(JSON.stringify(findings));
+ const output = cliOutput(result);
+ assert.equal(result.status, 1, output);
+ assert.match(output, /must be a safe repository-relative source path/);
+ assert.doesNotMatch(output, /stack|at validate-findings/i);
+});
+
+test("CLI rejects a FIFO without blocking", { skip: process.platform === "win32" || !HAS_SAFE_INPUT_OPEN }, () => {
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), "validate-findings-fifo-"));
+ const fifoPath = path.join(directory, "findings.json");
+ try {
+ const created = spawnSync("mkfifo", [fifoPath], { encoding: "utf8", timeout: CLI_TIMEOUT_MS });
+ assert.equal(created.status, 0, cliOutput(created));
+
+ const result = spawnSync(process.execPath, [validatorPath, fifoPath], {
+ encoding: "utf8",
+ timeout: CLI_TIMEOUT_MS,
+ });
+ const output = cliOutput(result);
+ assert.notEqual(result.error && result.error.code, "ETIMEDOUT", output);
+ assert.equal(result.status, 1, output);
+ assert.match(output, /input must be a regular file/);
+ assert.doesNotMatch(output, /stack|at validate-findings/i);
+ } finally {
+ fs.rmSync(directory, { recursive: true, force: true });
+ }
+});
+
+test("CLI rejects a symlink without following it", { skip: process.platform === "win32" || !HAS_SAFE_INPUT_OPEN }, () => {
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), "validate-findings-symlink-"));
+ const targetPath = path.join(directory, "target.json");
+ const symlinkPath = path.join(directory, "findings.json");
+ try {
+ fs.writeFileSync(targetPath, JSON.stringify(producerShapedFindings()));
+ fs.symlinkSync(targetPath, symlinkPath);
+ const result = spawnSync(process.execPath, [validatorPath, symlinkPath], {
+ encoding: "utf8",
+ timeout: CLI_TIMEOUT_MS,
+ });
+ const output = cliOutput(result);
+ assert.notEqual(result.error && result.error.code, "ETIMEDOUT", output);
+ assert.equal(result.status, 1, output);
+ assert.match(output, /input must not be a symlink/);
+ assert.doesNotMatch(output, /stack|at validate-findings/i);
+ } finally {
+ fs.rmSync(directory, { recursive: true, force: true });
+ }
+});
+
+test("CLI rejects input above the nesting-depth limit without an exception trace", () => {
+ const levels = LIMITS.nestingDepth + 1;
+ const result = runCli(`${"[".repeat(levels)}0${"]".repeat(levels)}`);
+ const output = cliOutput(result);
+ assert.equal(result.status, 1, output);
+ assert.match(output, new RegExp(`${LIMITS.nestingDepth} level nesting depth limit`));
+ assert.doesNotMatch(output, /RangeError|Maximum call stack|heap out of memory/i);
+});
+
+test("CLI rejects an oversized array without an exception trace", () => {
+ const result = runCli(JSON.stringify(Array(LIMITS.arrayItems + 1).fill(null)));
+ const output = cliOutput(result);
+ assert.equal(result.status, 1, output);
+ assert.match(output, new RegExp(`${LIMITS.arrayItems} item array limit`));
+ assert.doesNotMatch(output, /RangeError|Maximum call stack|heap out of memory/i);
+});
+
+test("checks pattern and branch invariants", () => {
+ rejectMutation(rejected, (finding) => { finding.fingerprint = "not stable"; });
+ rejectMutation(needsValidation, (finding) => {
+ finding.severity = { impact: { score: "low" }, overall_severity: "low" };
+ });
+});
+
+test("rejects unsupported and malformed schema keywords", () => {
+ assert(collectSchemaErrors({ type: "string", format: "uuid" }).some((error) => error.includes("format")));
+ assert(collectSchemaErrors({ type: "string", pattern: "[" }).some((error) => error.includes("regular expression")));
+ assert(collectSchemaErrors({ type: "string", visibleContent: "yes" }).some((error) => error.includes("expected boolean")));
+ assert(collectSchemaErrors({ type: "array", visibleContent: true }).some((error) => error.includes("requires type")));
+ assert.notEqual(validateDocument([], { type: "array", maxItems: 1 }).length, 0);
+});
+
+test("caps malformed 1000-finding validation output", () => {
+ assert.equal(errorsFor(Array.from({ length: LIMITS.arrayItems }, () => null)).length, LIMITS.validationErrors);
+ if (!HAS_SAFE_INPUT_OPEN) return;
+
+ const result = runCli(JSON.stringify(Array.from({ length: LIMITS.arrayItems }, () => null)));
+ const output = cliOutput(result);
+ assert.notEqual(result.error && result.error.code, "ETIMEDOUT", output);
+ assert.equal(result.status, 1, output);
+ assert.match(output, /output capped at 100/);
+ assert(output.length < 20000, `unexpected output length ${output.length}`);
+ assert.doesNotMatch(output, /RangeError|Maximum call stack|stack|at validate-findings/i);
+});
+
+test("caps amplified in-limit findings output under a constrained Node heap", { skip: !HAS_SAFE_INPUT_OPEN }, () => {
+ const findings = Array.from({ length: 750 }, () => ({
+ verdict: "confirmed",
+ trace: Array.from({ length: LIMITS.arrayItems }, () => 0),
+ evidence: Array.from({ length: LIMITS.arrayItems }, () => 0),
+ }));
+ const contents = JSON.stringify(findings);
+ assert(contents.length > 3 * 1000 * 1000, `hostile input too small: ${contents.length}`);
+ assert(contents.length <= LIMITS.inputBytes, `hostile input over limit: ${contents.length}`);
+
+ const result = runCli(contents, {
+ nodeArgs: ["--max-old-space-size=64"],
+ timeout: HOSTILE_CLI_TIMEOUT_MS,
+ });
+ const output = cliOutput(result);
+ assert.notEqual(result.error && result.error.code, "ETIMEDOUT", output);
+ assert.equal(result.status, 1, output);
+ assert.match(output, /output capped at 100/);
+ assert(output.length < 20000, `unexpected output length ${output.length}`);
+ assert.doesNotMatch(output, /heap out of memory|allocation failed|RangeError|Maximum call stack/i);
+});
+
+test("keeps shared helpers aligned with the coverage-ledger validator", () => {
+ const findingsModule = require("./validate-findings.cjs");
+ const ledgerModule = require("./validate-coverage-ledger.cjs");
+
+ for (const name of [
+ "VISIBLE_CONTENT",
+ "PATH_FORBIDDEN_CHARACTER",
+ "WINDOWS_RESERVED_COMPONENT",
+ "UNSAFE_DIAGNOSTIC_CHARACTER",
+ ]) {
+ assert.equal(findingsModule[name].source, ledgerModule[name].source, `${name} source`);
+ assert.equal(findingsModule[name].flags, ledgerModule[name].flags, `${name} flags`);
+ }
+
+ const sharedLimitKeys = Object.keys(findingsModule.LIMITS)
+ .filter((key) => Object.prototype.hasOwnProperty.call(ledgerModule.LIMITS, key))
+ .sort();
+ assert.deepEqual(sharedLimitKeys, ["inputBytes", "nestingDepth", "validationErrors"]);
+ for (const key of sharedLimitKeys) {
+ assert.equal(findingsModule.LIMITS[key], ledgerModule.LIMITS[key], `LIMITS.${key}`);
+ }
+
+ const pathCorpus = [
+ "src/handler.js",
+ "src/caf\u00e9/handler.js",
+ "src/\u65e5\u672c\u8a9e/\u0444\u0430\u0439\u043b.ts",
+ "src/cloc\u212a$.txt",
+ "src/CLOCK$.txt",
+ "src/con.txt",
+ "CON",
+ "src/COM\u00b9.log",
+ "src/lpt\u00b3",
+ "/etc/passwd",
+ "../src/file.c",
+ "src/../file.c",
+ "src//file.c",
+ "src\\file.c",
+ "src/file:name.c",
+ "~home/file.c",
+ "C:/file.c",
+ "src/file.c ",
+ "src/file.c.",
+ "src/file\u202ename.c",
+ "src/file\u200b.js",
+ "src/file\u034f.js",
+ "src/file\ufe0f.js",
+ "src/file\ud800name.c",
+ "src/file\udc00name.c",
+ ];
+ for (const value of pathCorpus) {
+ assert.equal(
+ findingsModule.isSafeRelativeSourcePath(value),
+ ledgerModule.isSafeRelativePath(value),
+ `path verdict diverges for ${JSON.stringify(value)}`,
+ );
+ }
+ assert.equal(findingsModule.isSafeRelativeSourcePath("src/cloc\u212a$.txt"), false);
+ assert.equal(ledgerModule.isSafeRelativePath("src/cloc\u212a$.txt"), false);
+
+ const proseCorpus = [
+ "Valid prose.",
+ "caf\u00e9",
+ "",
+ " \t\r\n",
+ "\u200b",
+ "\u034f",
+ "\ufe0f",
+ "\ud800",
+ "\udc00",
+ "visible\ud800",
+ ];
+ for (const value of proseCorpus) {
+ assert.equal(
+ findingsModule.hasVisibleProse(value),
+ ledgerModule.hasVisibleProse(value),
+ `prose verdict diverges for ${JSON.stringify(value)}`,
+ );
+ }
+});
diff --git a/.agents/skills/task-queue/SKILL.md b/.agents/skills/task-queue/SKILL.md
new file mode 100644
index 00000000..ec43bf5f
--- /dev/null
+++ b/.agents/skills/task-queue/SKILL.md
@@ -0,0 +1,95 @@
+---
+name: task-queue
+description: 任务目录监视器——把任务 .md 文件丢进 .tasks/pending/,当前会话挂起一个后台守望进程自动发现新任务,唤醒本会话实施并归档,长期循环。当用户说「启动任务监视」「挂起任务监视」「停止任务监视」「任务队列状态」「手动跑一轮任务队列」「暂停任务队列」「任务队列开关」,或询问 .tasks/ 目录协议、queue.state 开关用法、任务文件格式、队列卡住排障时使用。
+---
+
+# task-queue 任务目录监视器(会话挂起模式)
+
+原理:本会话用 run_in_background 挂起守望进程 `scripts/watchdog.py`,它每隔几秒扫 `.tasks/pending/`,发现新任务立即输出一行报告并退出;后台任务退出会自动唤醒本会话,代理按 SOP 认领、实施、归档,然后重新挂起下一个守望进程。如此循环,会话保持挂着不结束,来任务自动干活。
+
+生命周期铁律:
+
+- 守望进程依附当前会话,会话关闭监视即停。向用户交代这一点。
+- 同一时刻只挂一个守望进程;重挂前确认上一个已结束。
+- 唤醒后无论走了哪条分支,只要继续监视就必须重挂守望进程,这是循环的接力棒,忘了挂监视就死了。
+
+## 目录协议
+
+```
+.tasks/
+├── pending/ 新任务入口,.md 文件,文件名即任务名,内容即任务指令
+├── doing/ 实施中
+├── done/ 完成归档
+├── failed/ 失败归档
+├── queue.state 手动开关,一行文本:on / paused / off
+└── journal.log 心跳与动作流水
+```
+
+- 任务文件命名 `YYYYMMDD-HHMM-.md`,内容是给实施会话的完整任务指令,不要求结构化头部。
+- 认领就是原子移动 `pending/x.md → doing/x.md`,同一时刻只有一个守望循环在跑,无并发竞争。
+- 一轮只做一个任务,文件名排序最老优先;做不完的留给下一轮。
+- 失败移入 `failed/`,不自动重试,防止坏任务文件无限烧 token。
+- `doing/` 非空视为上一轮未完(多半是会话中途被杀),journal 告警并提醒用户人工处置,不自动回收。
+
+## queue.state 开关
+
+一行纯文本,三个合法值,用户直接用编辑器手改,守望进程每轮轮询时读取:
+
+- `on` — 正常发现并报告任务。
+- `paused` — 守望进程跳过检测但继续轮询,任务在 pending 堆积,改回 `on` 后自动恢复。
+- `off` — 守望进程立即输出 `TASKQUEUE STATE off` 退出,代理收到后结束监视循环。
+
+启动写 `on`,停止写 `off`,其余值只由用户手改。文件缺失按 `on` 处理并补写。开关语义即时生效:任务实施到一半改 `off`,本轮照常做完,重挂的守望进程读到 `off` 即退出收尾。
+
+## 任务实施规约
+
+以任务文件内容为指令实施。通用约束:
+
+- 跑任何长构建命令(`cargo build/test`、`pnpm check/install`、`tauri build`)前先 `python C:\Users\USER\.zcode\cli\parallel_tasks.py check`,有活跃任务则 register 登记、跑完 done 注销(项目并行铁律,见 `AGENTS.md`)。
+- 任务文件里的「验收标准」「约束」是硬要求,逐条满足;做不到就按失败归档,不要硬凑。
+- 实施会话就是当前会话,AGENTS.md、项目记忆、工具权限全部在场,无需额外注入。
+
+## 启动
+
+1. 创建 `.tasks/` 下四个目录(已存在则跳过),queue.state 写入 `on`(已存在则覆盖,启动即复位开关),journal.log 不存在则建空文件。
+2. 与用户确认轮询间隔(默认 10 秒)与守望超时(默认 30 分钟,超时自动重挂)。
+3. 后台挂起守望进程(run_in_background):
+ ```
+ python \scripts\watchdog.py --dir \.tasks --interval 10 --timeout 1800
+ ```
+4. journal 记 `MONITOR ON`,向用户报告:监视已挂起、参数、queue.state 位置与改 `off` 即停的用法。
+
+## 唤醒处理 SOP(后台任务退出时执行)
+
+读后台输出行,按前缀分支:
+
+1. `TASKQUEUE NEW <文件名>` → 认领实施:
+ - `mv pending/<文件名> doing/`,journal 记 `CLAIM`,notify CLAIM(可选)。
+ - 按任务实施规约执行任务。
+ - 成功 → `mv` 进 `done/`,文件末尾追加「--- 实施记录 ---」:日期、commit hash(若涉及提交)、要点三五行;journal 记 `DONE`;notify DONE。
+ - 失败 → `mv` 进 `failed/`,追加失败原因与已尝试手段;journal 记 `FAIL`;notify FAIL。
+ - 重挂守望进程。
+2. `TASKQUEUE STATE off` → journal 记 `MONITOR OFF (by switch)`,确认 queue.state 为 off,notify STOPPED,向用户报告监视已关闭。不重挂。
+3. `TASKQUEUE TIMEOUT` → 空转超时,journal 记一行心跳,直接重挂守望进程。不发通知。
+
+## 通知
+
+只在有动作的轮次发系统通知(Windows toast),空轮静默。调用:
+
+```
+powershell -NoProfile -ExecutionPolicy Bypass -File \scripts\notify.ps1
+```
+
+TYPE 取 `CLAIM` / `DONE` / `FAIL` / `STOPPED`,MESSAGE 为任务文件名(纯 ASCII)。通知失败只记 journal,不重试不阻塞。
+
+## 停止
+
+杀掉后台守望任务(TaskStop),queue.state 覆写为 `off`,journal 记 `MONITOR OFF (manual)`。`doing/` 有滞留文件时如实告知位置,不代处置。
+
+## 查状态
+
+向用户报告:queue.state 当前值、守望进程是否在跑、pending/doing/done/failed 各自的文件数与文件名、journal.log 尾部 20 行。
+
+## 手动跑一轮
+
+不动后台守望,直接按「唤醒处理 SOP」的认领实施分支跑一轮(挑 pending 里最老的任务)。适合验证链路或补跑,做完守望循环照旧。
diff --git a/.agents/skills/task-queue/scripts/notify.ps1 b/.agents/skills/task-queue/scripts/notify.ps1
new file mode 100644
index 00000000..aa291dad
--- /dev/null
+++ b/.agents/skills/task-queue/scripts/notify.ps1
@@ -0,0 +1,19 @@
+param(
+ [Parameter(Mandatory = $true)][string]$Type,
+ [Parameter(Mandatory = $true)][string]$Message
+)
+
+# Windows toast via WinRT, no third-party modules. AppId pins to the registered
+# PowerShell AUMID so the toast is accepted without installing a package.
+try {
+ [Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] | Out-Null
+ $template = [Windows.UI.Notifications.ToastNotificationManager]::GetTemplateContent([Windows.UI.Notifications.ToastTemplateType]::ToastText02)
+ $texts = $template.GetElementsByTagName("text")
+ $null = $texts.Item(0).AppendChild($template.CreateTextNode("TaskQueue/$Type"))
+ $null = $texts.Item(1).AppendChild($template.CreateTextNode($Message))
+ $toast = [Windows.UI.Notifications.ToastNotification]::new($template)
+ [Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier("{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\WindowsPowerShell\v1.0\powershell.exe").Show($toast)
+ exit 0
+} catch {
+ exit 1
+}
diff --git a/.agents/skills/task-queue/scripts/watchdog.py b/.agents/skills/task-queue/scripts/watchdog.py
new file mode 100644
index 00000000..35d04603
--- /dev/null
+++ b/.agents/skills/task-queue/scripts/watchdog.py
@@ -0,0 +1,55 @@
+#!/usr/bin/env python
+"""task-queue watchdog: poll .tasks/pending for new task files.
+
+Runs in the background of a ZCode session. Prints one machine-readable
+line and exits; the session wakes on process exit and acts on the line.
+
+Lines:
+ TASKQUEUE NEW oldest pending task found, claim and run it
+ TASKQUEUE STATE off queue.state says off, stop the monitor loop
+ TASKQUEUE TIMEOUT nothing found within --timeout, re-arm me
+"""
+
+import argparse
+import sys
+import time
+from pathlib import Path
+
+
+def read_state(root: Path) -> str:
+ f = root / "queue.state"
+ try:
+ return f.read_text(encoding="utf-8", errors="replace").strip().lower()
+ except OSError:
+ return "on"
+
+
+def main() -> int:
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--dir", required=True, help="queue root (.tasks)")
+ ap.add_argument("--interval", type=float, default=10.0)
+ ap.add_argument("--timeout", type=float, default=1800.0)
+ args = ap.parse_args()
+
+ root = Path(args.dir)
+ pending = root / "pending"
+ deadline = time.monotonic() + args.timeout
+
+ while True:
+ state = read_state(root)
+ if state == "off":
+ print("TASKQUEUE STATE off", flush=True)
+ return 0
+ if state != "paused" and pending.is_dir():
+ md = sorted(p for p in pending.glob("*.md") if p.is_file())
+ if md:
+ print(f"TASKQUEUE NEW {md[0].name}", flush=True)
+ return 0
+ if time.monotonic() >= deadline:
+ print("TASKQUEUE TIMEOUT", flush=True)
+ return 0
+ time.sleep(args.interval)
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/AGENTS.md b/AGENTS.md
new file mode 100644
index 00000000..84a70a66
--- /dev/null
+++ b/AGENTS.md
@@ -0,0 +1,13 @@
+# AGENTS.md(7shell 仓库级代理与贡献者指令)
+
+本仓由多会话并行开发(多工作树 + 子代理车道),AI 代理与人类贡献者共用一套流程。开始任何改动前,按顺序读:
+
+1. **改代码前先读 [`docs/LESSONS.md`](docs/LESSONS.md)**——教训账本,每条都是带证据的复发规则;Seen 满 3 天的规则固化进 [`docs/规范/编码与验收标准.md`](docs/规范/编码与验收标准.md),审查与收口逐条对照。
+2. **跑任何长构建命令前先过并行登记**——`cargo build/test`、`pnpm install/check`、`tauri build`、`make app-e2e` 这类吃内存的命令,先 `python C:/Users/USER/.zcode/cli/parallel_tasks.py check` → 有活跃任务先 `register --name <任务名> --sandbox <独立沙盒>`,跑完 `done --name <任务名>`(禁裸 `done`,会注销全部活跃任务)。构建并发上限 2 路,瓶颈是内存提交量不是 CPU。
+3. 定向测试纪律、验收清单(含 not run 条款)、派活模板:[`docs/开发流程-派活与验收清单.md`](docs/开发流程-派活与验收清单.md)。
+4. 架构与不变量:[`docs/architecture.md`](docs/architecture.md) 与 [`docs/security-model.md`](docs/security-model.md)。改契约必须同批更新归属文档;动 security-model 不变量先走 [`docs/pips/`](docs/pips/README.md)。
+5. 文档写现状,提案写进 `docs/pips/`(门槛见其 README);新缺陷/教训在收口后补记 `docs/LESSONS.md`(规则一句话 + hash 证据 + Seen 计数,不写流水账;事件叙事进 `docs/经验总结/`)。
+6. **「提交即回填」**:用户可感改动随提交回填 `CHANGELOG.md` 的 `[Unreleased]` 段(一句一条,带提交哈希)。
+7. **对外动作须用户明确授权**:push 任何远端、建 tag、发 release、外发内容均不得自动执行。
+8. **推送 GitHub 一律走令牌**,禁裸 `git push`(裸推走 credential.helper 指向的 GUI 凭据管理器,弹窗抢焦点且可能常驻不退)。令牌读 `.local/github-token.json`,命令行加 `-c credential.helper=` 置空凭据助手再推;推送脚本仓名写死、回显目标 URL、注释纯 ASCII。
+9. 人类贡献者面向的流程(环境搭建、提交规范、依赖门槛)见 [`CONTRIBUTING.md`](CONTRIBUTING.md);本文件只管代理协作纪律,两者冲突时以更严格者为准。
diff --git a/docs/LESSONS.md b/docs/LESSONS.md
new file mode 100644
index 00000000..f934e7a9
--- /dev/null
+++ b/docs/LESSONS.md
@@ -0,0 +1,170 @@
+# LESSONS(教训账本)
+
+> 本文件是**持续演进、带淘汰压力的规则账本**,机制导入自 mybatis-plus-sql-visualizer 仓(其机制取自 magpie 项目的 LESSONS.md,2026-10-23 引入并经四十余轮实战淬炼)。
+> 每条教训固定四段:**粗体祈使句规则 → 证据(提交号/文档路径/真机日志,hash 级)→ 正例与反例 → `Seen N× (日期…)`**。
+> 同日多次发现只算一天;**Seen 满 3 个不同日期的规则整体搬进 [`规范/编码与验收标准.md`](规范/编码与验收标准.md)**,本文件在升级记录保留指针,后续复发继续记回。
+> 复盘触发点:不搞自动复盘——每次**收口、门禁复跑、真机故障**之后,由当值会话顺手补记一条(有新教训才记,没有不硬凑)。
+> 分工:本文件只收**可执行规则**;事件叙事与完整排查过程写 `docs/经验总结/`,条目用链接引用不复制内容。**改代码前先读本文件。**
+> 导入条目(I 编号)的 Seen 从 0 起算——导入不计数,在本仓复发才记;条目末尾标注源仓出处,细节需要时查源仓原文。
+
+## 导入条目(2026-11-17 建账,源仓 2026-09~11 实战)
+
+### 排障与取证
+
+**I1 排障先挖根因链,别信表层包装的异常**
+`unwrap_or_default`/`runCatching`/`catch` 吞掉后会留下 `None` 调用链假象。逐层 `.source()`(Rust)/`Caused by:`(Java)找根因;把「包装异常: null」当异常本身去修是反例。(源仓 L1)
+
+**I2 判「搜不到/没有」之前先跑对照查询,证明搜索接口本身是好的**
+每个「0」旁边并排给出同接口的已知非零查询读数;源本身不可用时把结论降级为「未取到」并写明原因。「搜了一遍没有」不区分「接口坏了/被限流」与「确实不存在」。(源仓 L14)
+
+**I3 注释里点名的守卫必须真的存在**
+在注释里断言「已由某某守卫保证」,先 `grep` 确认那个守卫类/测试在场,并写清适用版本;没落测试的「已合规」从未被机器验过。(源仓 L16)
+
+**I4 CI 腿「绿」却不产出逐例口径就是空绿**
+凡带「环境不满足就打印 + return」这类显式绿跳的腿,必须在同一 job 内产出一行逐例汇总(files/tests/skipped/failures)。没有这行数字,`exit 0` 什么都不证明。判定顺序固定:腿红先读环境,腿绿先读逐例口径。(源仓 L42)
+
+**I5 构建静默死亡先读崩溃日志与内存提交量,别先怀疑代码或增量缓存**
+「跑到某个 task 就结束、无编译错误也无 FAILED」按进程级死因排查:找当天崩溃日志(`hs_err_pid*.log` / Rust panic 落盘)→ 看内存提交量(commit)不是 CPU → 列本机构建进程的启动日期清孤儿。88% commit 的状态下继续叠构建+测试必然再崩。(源仓 L75)
+
+**I6 判「用户手上那个包有没有这条修复」看产物字节,别信版本号**
+扫安装目录里的类/符号或以行为差异为准。版本号没人动就仍是旧号,「版本号没变」与「代码是旧的」是两件事;每次给包必须同时给 sha256 与「装完确认文件修改时间」的自查方法。(源仓 L35)
+
+### 验证纪律
+
+**I7 反向验证的夹具要先算清「修复点之前还有几道闸门」**
+撤掉修复看是否变红之前,夹具的每个参数都要过一遍沿途其它闸门——缺陷那道门之前若有更早的短路(家族排除、启发式、开关),夹具被截走就红不起来。判定办法:加临时探针打印被测链的实际产出,先证明夹具抵达目标层。夹具值还必须与守卫默认值拉开,两值撞车等于 0 红假绿。(源仓 L80 + L2)
+
+**I8 反向验证前先提交;摘除探针后 grep 自证生效**
+`git checkout -- ` 回退的是整个文件,同文件里未提交改动一起消失——摘之前先提交或只用编辑工具改回。摘除式探针最阴的失败是「探针没落地」:改完立刻 `grep -c` 确认目标语句真的不再执行。(源仓 L32 + L50)
+
+**I9 同回合内改被测文件 ⇒ 已跑的门禁读数作废,必须复跑**
+读数落地后冻结被测面;确要再改,重跑该面定向并更新读数。「顺手改一下,读数应该还绿」是反例。(源仓 L5)
+
+**I10 时序类判据断言「调度值」,不要断言墙钟间隔比值**
+拿时间差值当判据会把一次性预热成本算进第一段,在慢 runner 上必红。给被测对象加睡眠注入缝(生产注入真实睡眠、测试注入记录器),断言「被请求睡多久」的序列——与机器快慢完全无关且更强。(源仓 L18)
+
+**I11 夹具钉定值必须指向「CI 克隆的那个远端」可达的提交**
+钉定值只在已 push 到 CI 拉取的那个远端时才成立。改钉定值前跑 `git ls-remote` + `merge-base --is-ancestor` 两条只读判据;「本地能跑」恰恰因为对象躺在本机克隆里,与远端无关。(源仓 L19)
+
+### 缓存与数据
+
+**I12 校验判据必须对齐真正消费方的解析器与类型**
+判「这份 JSON/配置能不能被加载」,要按真正消费它的那个解析器与类型约束去校验,不是「能否解析成通用树」。宽松解析器会放过裸值,严格消费者会拒绝——判据不一致的后果是「真机损坏形态被判成健康,自愈逻辑全程空转」。(源仓 L61)
+
+**I13 「TTL 内一律命中」是伪缓存:命中条件里时间判据不能覆盖内容判据**
+`TTL 内直接命中 || 内容未变` 的实际语义是「TTL 内无视内容」,同时吃掉「改了不生效」与「同键不同内容串味」。要吸收重建造成的伪失效,用内容型指纹(文本哈希),指纹代价必须远低于被缓存的那次计算。(源仓 L67)
+
+**I14 抗抖动正缓存必须带收回条件,且收回判据只有一个合法来源——「查询成功且确认不存在」**
+「返回值是否为空」不能当判据:它既可能是「确定没有」也可能是「这次没算完」。内部实现显式化三态 `Found / Absent / Unknown`(Found 入缓存 / Unknown 保留 / Absent 才收回),取消与错误永远算「没算完」。(源仓 L76)
+
+**I15 按名字找目标先锚定身份域,禁无语义背书的宽松尾缀匹配**
+先确定名字的身份域(命名空间/模块/包),判定只在该域内精确比较;「任意前缀 + 同名尾段」在单命名空间样例里看似无害,在多命名空间语料里把同名另一条认成同一条。放宽匹配必须能说出引擎侧的等价语义。测试夹具要主动造「多命名空间 + 同名」形态——单命名空间语料永远测不出这类错。(源仓 L79)
+
+**I16 收窄「怎么认一个对象」的契约前,先枚举仓里既有实现暴露的形态**
+只认一个方法名/字段名会把合法条目静默判成「无名」,症状不是报错而是「集合被滤空 → 上游永远收不到结果」。取名/取键这类兼容面一律走候选链,全都取不到才算缺席;「多候选就弃权」的保守降级,先用一条命令量真实数据的歧义度——歧义在真实项目里是常态时,「弃权」等于能力从不生效。(源仓 L41 + L36)
+
+**I17 一次性元数据随载体走(消息/返回值/回调参数),别走共享可变状态**
+跨线程、跨渲染次数传递的小块元数据(失败成因、诊断快照)优先编码进载体本身。只要还留一处「谁清谁写」的约定,就会被重复渲染、并发写方打掉;读方不清空,由下一次写入覆盖。(源仓 L40)
+
+### 协作与提交
+
+**I18 提交信息写 UTF-8 文件 `git commit -F`,禁内联反引号**
+Git Bash 里 `commit -m` 的反引号被命令替换吃掉——报错但提交仍成功、信息静默缺段;`python -c` 双引号串同根更隐蔽。中文一律写文件传递,Bash 命令行直传必乱码;编辑后必回读校验关键内容在场。(源仓 L4)
+
+**I19 跨调用改文件一律用编辑工具,Bash 内 python/heredoc 写文件可能不落盘**
+沙盒拦截下同进程回读成功、跨调用丢失。Bash 内 python 只做只读分析。(源仓 L4)
+
+**I20 每笔提交至少过编译——未编译提交堵死下游车道验证**
+多车道共用主干时,一笔编译不过的提交让所有下游车道无法验证。提交前跑一次增量检查(`cargo check` / `pnpm typecheck`,秒级);「我的改动是纯新增文件,编译肯定没问题」是反例。(源仓 L11)
+
+**I21 修一个点要横向审计同型兄弟,机制替换要覆盖同形态的平行实现**
+修一处缺陷时 grep 同模式调用点/同形状守卫/同谓词分支,本次一并修或明确登记。机制替换(全量扫描→索引、同步→异步、吞错→上抛)落笔前先把「同形态的弟弟们」列全——报障往往下一次落在没被点到的那条平行链上,时间差几天,容易被当成新 bug 从头再查。(源仓 S7 + L74)
+
+**I22 修「某条信息没显示」之前,先枚举这个回调的全部消费点是否都接上了**
+不许只改复现时走的那条调用链——先数同一个回调在文件里有几个调用点,逐个核对。看到「同一功能两个入口,只有其中一个正常」,先 diff 两个入口的接线,不要先怀疑数据或竞态。(源仓 L39)
+
+**I23 共用工作树里别家车道的在途文档别用 `git stash push` 挪开**
+stash 把文件在工作树里回到 HEAD 版本,对方下一次提交会把 pop 出来的冲突标记当成正常内容提交进主干。正路:等对方提交完再动;或 `git apply --cached` 只暂存自己那段。(源仓 L77)
+
+**I24 本机 Windows 红线合集**
+① Git Bash 调带 `/X` 参数的 Windows 工具会被 MSYS 转成路径(robocopy `/E` → `E:/`),一律写 `.ps1` 用 PowerShell 执行,robocopy 退出码 0~7 均为成功;② 无 BOM 的 UTF-8 `.ps1` 里的中文串会被 PowerShell 5.1 按 ANSI 读成乱码语法错——含中文一律用 pwsh 7 或文案纯 ASCII;③ 中文请求体写 UTF-8 文件再 `curl --data-binary`;④ 推送脚本仓名写死、回显目标 URL,别读凭据文件里的 `repo` 字段拼 URL(常是从别的仓拷来的旧值)。(源仓 L4/L6/L13/L47)
+
+**I25 多组并行部署/运维:冲突由主控统一处置,判据落在磁盘字节与实连**
+主控把「作业基准」写成共享文件(唯一事实源),凭据只放权限 600 的文件;组间抢资源/孤儿进程由主控读证据后统一清、定错峰顺序,不叫子代理自己 kill。环境会替换显示串时,别拿显示串改脚本,用逐字节比对或实连自证;别在任务运行中改脚本——在途进程会读到中间态。(源仓 L56)
+
+### 流程与发布
+
+**I26 UI/交互争议方案先给用户看形态,绿灯读数不构成方向依据**
+形态预览/对照稿先行,用户点头再落码。定向全绿 → 落码 → 等真机反馈 → 整案撤除是反例(源仓两轮返工均此形态);「预览点头」也不能替代「按原版逐项核对」。(源仓 L12)
+
+**I27 后台长命令禁用 `2>&1 | tail -N` 收尾——失败正文会被截断吞掉,退出码还会被换成管道末命令的**
+重定向全量到文件 + 紧跟 `echo "EXIT=$?"` 把真退出码打进日志,判读用 grep 提取。tail 要等上游 EOF 才输出,中途读输出文件恒为空,还会误判任务没起来。(源仓 L22)
+
+**I28 CI 需要外部实例时,先问「它能不能由 runner 自给」**
+共享实例会把「别人的机器挂了」变成「我们的门禁红了」,且一个连不上的库能生出十几条业务断言失败,读报的人只看到最后一条。能自给就自给(本仓 `deploy/lab/` 即此思路的落地);确实不能自给的腿,在记录里显式写「环境腿、只能环境侧修」。(源仓 L43)
+
+**I29 运维/部署脚本只放服务器=没备份;口令只放服务器=备份永久失效**
+凡是要靠「机器重装后照单重建」的东西,事实源必须在仓库里,服务器上的副本只是部署产物。备份仓库口令必须离线双份(密码管理器或另一台设备各一份)——AK/SK 丢了还能新建,仓库口令丢了没有任何恢复路径。(源仓 L52)
+
+**I30 CI 提速先量「全局地板」再动刀:单腿变快≠整轮变快**
+动编排前先拉逐 job/逐 step 的起止时间找整轮关键路径与真地板;任何改动用同 workflow、只差一个变量的 A/B 轮验证,对比「整轮结束时刻」。已证伪路线:把最长腿切片并行(固定成本占大头)、把大对象预置进共享缓存(放大条目让所有腿的恢复一起变慢)。负收益立即 revert。(源仓 L72)
+
+**I31 retry 救不了「一次性读完」的下载:先确认有没有续传语义**
+一次 `read()` 拉大文件没有续传——每轮重试把同一个失败从头再演。正解:`Range` 从本地已落字节续拉 + 判据用服务端声明的 digest;连续 N 轮零进展即判链路不可用并把替代通道写进报错。`watch` 类命令的退出码不能当结论,判据取查询接口的最终状态。(源仓 L51)
+
+### 工具与环境(第二批导入)
+
+**I32 `git add -f` 对被忽略目录下的文件静默无效**
+exit 0 无报错但暂存区是空的。绕过配方=`git hash-object -w ` + `git update-index --add --cacheinfo 100644,,`;提交后必回读 `git ls-files` 确认关键文件在场。(源仓 pitfall-git-add-force-silent-noop-ignored-dir)
+
+**I33 本机 Git Bash 的 `grep` 是 ugrep 包装,`-c` 与管道会静默返空**
+0 命中先怀疑工具。同族:`unzip … | grep -q` 假阴性(管道末命令退出码)、`comm` 对含中文/CRLF 清单恒给「零交集」(集合运算改 `grep -F`)、python 不认 `/f/` 路径、`sed -i` 会改行尾、cygpath 转分号分隔清单整串当一个路径。(源仓 pitfall-gitbash-grep-is-ugrep-wrapper / gitbash-toolchain-path-quirks)
+
+**I34 超长单行表格行不能用「行首前缀」做编辑锚点**
+`old_string` 只截行首会把原行残余粘到新行尾;`git diff --stat` 对单行文件恒显示 1 insertion,看不出被改坏。必须整行回读校验关键内容在场。(源仓 pitfall-single-line-table-edit-prefix-match)
+
+**I44 提交身份先核 `user.email`——错邮箱把贡献归到别人账号**
+提交邮箱抄了上游作者或模板值,Gitee/GitHub 的贡献图归到陌生账号;判据看 commits API 的 `author.login`。仓内写死 user.email,发现后 `--reset-author` 修正。(源仓 pitfall-commit-identity-wrong-email-owns-attribution)
+
+### 构建与发行
+
+**I35 发行物必须在干净树上构建——在途未提交改动会被编进包里**
+`inspect`/自检类脚本只验版本与文案,验不出源码状态;跑门禁时树上有别人的在途改动,门禁 PASS 的包也不可发行。打包前 `git status` 无源码改动;实施代理报告须回答「跑门禁时树是否干净」。(源仓 pitfall-buildplugin-zip-tainted-by-inflight-changes)
+
+**I36 嵌了构建时间戳的产物,哈希永不同——哈希不能作「同一份产物」的判据**
+每次构建都唯一的字段(时间戳/随机 salt)让本地包与 CI 包必不同哈希;判内容一致用可复现锚点(版本、字节内标记),别拿哈希相等下「不是同一份」的结论。(源仓 pitfall-mpv-build-timestamp-vs-ci-zip-hash)
+
+### 缓存与重试
+
+**I37 「就绪 → 重算」的闭环可能自激:补不到结果也回调 ⇒ 几秒内多轮重算**
+任何「就绪→重算」闭环都要问一句重算会不会再次触发等待。后台补齐的回调,无论成功失败都要有终止条件——同 key 同缓存代只补一次(缓存失效/调度失败才退回)。(源仓 pitfall-m2-warm-retry-self-exciting-loop)
+
+**I38 预取要有失败记忆;首开慢先分清冷启动固定成本与算法成本**
+解析不到又不写缓存时,每次重绘都会重触发预取,形成自旋。给失败结果也写记忆(带短 TTL);收窄检索范围反而更慢时,先怀疑是冷索引/JIT 这类一次性固定成本——该挪走不该压。(源仓 pitfall-prefetch-needs-failure-memo-and-coldstart-vs-algorithm)
+
+**I42 结果级 memo 必须挂在清单缓存槽自身;负缓存须哨兵**
+memo 挂旁路槽时,旁路命中会跳过下层 TTL/有效性检查,形成「永远不失效」的第二层缓存。负缓存(「查过没有」)不能存 null(并发 Map 不收),用哨兵对象。(源仓 pitfall-cache-memo-shares-listing-slot)
+
+### 验证与归因
+
+**I39 性能归因先分段切再下结论;冷启动固定成本别算到算法头上**
+把链路按段埋点(请求→计算→装配→呈现),逐段对时找断点。首次操作慢常是冷启动编译/索引这类固定成本(同一条第二次就是毫秒级),拿「刚打开第一次点」判算法慢会误判。(源仓 pitfall-preview-open-stage-split)
+
+**I40 测试唯一键禁用时钟尾巴拼接**
+时钟末几位取值空间小(如毫秒末 3 位只有千级),批量造数必撞键。唯一键一律原子序号或 UUID。(源仓 pitfall-test-unique-data-by-clock-tail)
+
+**I41 别急着判「环境受限未验证」,先证明路径真的走不通**
+归因环境之前先做对照:同样输入在最小复现里走不走得通。「环境问题」与「我的判据写错了」在表象上一样。(源仓 pitfall-blame-environment-before-proving-path)
+
+**I43 耗时阈值类断言在慢 runner 上稳定假红**
+「持续 N 秒」「首次完成不超过 N ms」这类判据把机器速度写进了断言——6 核本地一直绿、2 核 CI 稳定红。判据要么断行为(该不该发生),要么注入时钟缝断调度值(见 I10)。(源仓 pitfall-ci-slow-runner-amplifies-time-threshold-tests)
+
+## 活跃规则
+
+(本仓新产生的教训按时间追加在这里,编号从 A1 起;Seen 满 3 升级进规范并在此留指针。)
+
+## 升级记录
+
+| 日期 | 条目 | 去向 |
+|---|---|---|
+| (空) | | |
diff --git a/docs/MEMORY.md b/docs/MEMORY.md
new file mode 100644
index 00000000..7571986b
--- /dev/null
+++ b/docs/MEMORY.md
@@ -0,0 +1,33 @@
+# docs/MEMORY.md(内部协作文档检索索引)
+
+> 唯一的内部协作文档检索入口。面向用户的英文文档(`docs/guide/` 等 VitePress 站点)不在此索引内。
+> 新增/移动内部协作文档时同步更新本文件;命名规则见 [`docs/规范/文档命名规范-说明文档.md`](规范/文档命名规范-说明文档.md)。
+
+## 流程与协作
+
+- [`AGENTS.md`](../AGENTS.md) — 仓库级代理与贡献者指令入口(并行登记、三档测试、提交纪律)
+- [`开发流程-派活与验收清单.md`](开发流程-派活与验收清单.md) — 派活六字段模板、验收五条、测试三档分层、常见坑
+- [`pips/README.md`](pips/README.md) — PIP 提案机制(什么时候写、状态流转)
+
+## 账本与索引
+
+- [`LESSONS.md`](LESSONS.md) — 教训账本(四段格式、Seen 计数、满 3 升级规范;含 44 条导入条目)
+- [`MEMORY.md`](MEMORY.md) — 本文件,文档检索索引
+
+## 规范(docs/规范/)
+
+- [`编码与验收标准.md`](规范/编码与验收标准.md) — 审查与收口逐条对照的两列标准(V/C/M 条目)
+- [`代码编辑规范-grep优先读取.md`](规范/代码编辑规范-grep优先读取.md) — 大文件 grep 定位 + 精确读取的分级操作
+- [`文档命名规范-说明文档.md`](规范/文档命名规范-说明文档.md) — 时间戳命名体系、规范四后缀、与 PIP 的分工
+- [`记忆精简规范.md`](规范/记忆精简规范.md) — 项目记忆三类去向与数量基线
+- [`设计规范-弹窗克制红线.md`](规范/设计规范-弹窗克制红线.md) — 弹窗/通知准入五问、允许/禁止类、触点登记
+- [`协作偏好-说明文档.md`](规范/协作偏好-说明文档.md) — 用户确认的 AI 代理工作口径(立项/验证分工/授权边界/文案/异步)
+- [`git与多仓操作配方-说明文档.md`](规范/git与多仓操作配方-说明文档.md) — git 暂存/工作树/多仓推送/Gitee 建仓配方与本机 Git Bash 工具链坑速查
+
+## 经验总结(docs/经验总结/)
+
+- [`20261117-2200-并行开发与子代理协作方法论-经验总结.md`](经验总结/20261117-2200-并行开发与子代理协作方法论-经验总结.md) — 验证盲区、后台派发、测试分层、token 治理、调度模式五篇汇编
+
+## 记忆归档
+
+- `docs/memory-archive/` — 已交付功能、已解决踩坑的归档(判定标准见记忆精简规范;建仓暂空,首次归档时建 README 索引)
diff --git "a/docs/\345\274\200\345\217\221\346\265\201\347\250\213-\346\264\276\346\264\273\344\270\216\351\252\214\346\224\266\346\270\205\345\215\225.md" "b/docs/\345\274\200\345\217\221\346\265\201\347\250\213-\346\264\276\346\264\273\344\270\216\351\252\214\346\224\266\346\270\205\345\215\225.md"
new file mode 100644
index 00000000..ea7529ff
--- /dev/null
+++ "b/docs/\345\274\200\345\217\221\346\265\201\347\250\213-\346\264\276\346\264\273\344\270\216\351\252\214\346\224\266\346\270\205\345\215\225.md"
@@ -0,0 +1,47 @@
+# 开发流程:派活与验收清单
+
+> 本文是 `AGENTS.md` 第 3 条指向的作业细则:主控怎么派活、子代理怎么交活、收口怎么验收。只写可执行动作,规则来自多轮并行开发的实际返工点(机制与模板导入自 mybatis-plus-sql-visualizer 仓并按本仓命令面适配)。
+
+## 一、派活模板
+
+每条派活必须写死以下六项,缺一项就会在现场临时猜:
+
+1. **工作树与分支**:`git worktree add .worktrees/<名> -b <名> <基线>`;分支用扁平名,不用 `feature/` 前缀(第三方工具曾连坐删除 `feature/` 整目录);本地独有分支尽快 push 留底。
+2. **写集**:列出该车道会碰的文件/目录,并保证与其它车道互斥;`CHANGELOG`、共享文档这类多车道共写的文件提前说明冲突处理方式(禁用 stash 挪别家在途文档——见 LESSONS I23)。
+3. **只跑定向**:Rust 用 `cargo test -p <测试名>`;前端用 `pnpm vitest run <文件>`;守卫用 `pnpm test:guards`。明令**不跑全量**(`pnpm check` / `cargo test --workspace`)、**不 `clean`**、不跑构建校验。全量门禁由收口阶段统一跑一次。
+4. **并行登记**:跑长构建前 `python C:/Users/USER/.zcode/cli/parallel_tasks.py check`;有活跃任务先 `register --name <名> --sandbox <工作树绝对路径>`,跑完 `done --name <名>`(禁裸 `done`,它会注销全部活跃任务)。
+5. **提交纪律**:每完成一件可提交的就立即提交(掉线时未提交的成果全丢);`git add` 具体文件、禁 `-A`;消息写 UTF-8 文件后 `git commit -F`(消息里禁反引号;中文写文件传递,Bash 直传必乱码)。
+6. **报告字段**:改动文件、提交哈希、定向读数(N/失败/错误/skip,逐例口径)、反向验证读数、未完成项与风险。没跑过的读数不许写「全绿」。
+
+红线(每条派活都写):不 push、不合流、不建 tag、不对外发内容;不碰别人的工作树;计划/文档回写只写自己工作树里的副本,主仓副本只读。
+
+## 二、验收清单
+
+1. **读数可复核**:读数要能对上测试输出或 CI 日志,不接受「全绿」两个字;腿绿先读逐例口径(见 LESSONS I4)。
+2. **反向验证**:每条修复至少一条「摘掉必红」探针,贴摘除与还原两次读数;反向前先算清夹具沿途的闸门(LESSONS I7),摘除后 grep 自证生效(LESSONS I8)。守卫/扫描类改动还要证明探针有判别力——合成样本只能证明「规则看得见我造的形态」。
+3. **not run 条款**:没跑的测试、门禁、真机逐项列「没跑 + 为什么」;环境受限只能写「环境受限未验证」,不得拿受限环境读数冒充验证通过。
+4. **合并复核**:冲突按「保留双方」解;合并后在集成分支重跑定向——各支自报读数之和不是权威读数。
+5. **文档三件**:计划/PIP 状态回填、`CHANGELOG.md`(带提交哈希)、归属文档(`docs/architecture.md` / `security-model.md`)改契约同批更新。
+
+## 三、测试三档分层
+
+1. **定向**——每个实施子代理自己跑,随报告交出(见派活模板第 3 项)。
+2. **统一全量门禁**——全部子代理完成后**单派一个只读收口代理**(或主控亲自)跑一次权威全量(`pnpm check` + `cargo test --workspace` + `cargo clippy`);主控同时写文档收尾,并行不空等。收口代理只读;主控并行写文档期间不得碰 `src/`——一旦改了生产代码,那道绿立刻过期,必须复跑。
+3. **构建校验**——`tauri build` / `pnpm app:e2e` 只在大改动或发版前跑(大改动判据:动依赖版本、动 crate 依赖方向、动 descriptors 协议、动 security-model 不变量、引入新平台接口)。
+
+## 四、并行与资源
+
+- 构建并发默认上限 2 路;瓶颈是**内存提交量不是 CPU**(Windows 上用内存 commit 读数判断,别看 CPU);用户显式放开才可突破。
+- 长命令一律后台启动,禁 sleep 轮询;输出全量落盘 + 回显真退出码(LESSONS I27);子代理拿不到锁就记录证据交回主控复跑,不空等。
+- 子代理并发默认 ≤3(账户限流);派活前确认当前车道数;并行紧张时转主控直接实施。
+- **多组并行部署/运维任务**:主控把「作业基准」写成共享文件(唯一事实源),凭据只放权限 600 的文件、基准里只写变量名;组间抢资源/孤儿进程由主控读证据后统一处置,不叫子代理自己 kill;判据落在磁盘字节与实连(LESSONS I25)。
+- **会话粒度 token 治理**:省 token 的主杠杆是会话粒度不是提示词——上下文到 12~15 万就收口、写交接文档、开新会话;一个可提交单元一个会话;探索交给子代理、只回收结论。交接文档字段固定:分支与 tip / 已完成 / 未完成 / 证据读数 / 下一步 / 踩过的坑。方法论见 [`docs/经验总结/20261117-2200-并行开发与子代理协作方法论-经验总结.md`](经验总结/20261117-2200-并行开发与子代理协作方法论-经验总结.md)。
+
+## 五、常见坑
+
+- **工作树的 `.git` 是文件不是目录**:提交消息写临时文件(如 `/tmp/msg.txt`),不要写 `.git/COMMIT_MSG`。
+- **Windows 长路径删不掉**:用 `\\?\` 前缀 + `rd /s /q`,写成 `.ps1` 执行(Git Bash 会把 `/X` 参数当路径转义)。
+- **新增 i18n 键**要所有 locale 双份并过 `pnpm check:i18n`;只加英文不够。
+- **改 descriptors 协议**先跑 `pnpm generate:descriptors` 再提交,`pnpm check:descriptors` 红就是忘了同步生成物。
+- **新增守卫测试**要过架构守卫的登记面;注释里点名「已由某某守卫保证」前先 grep 确认守卫在场(LESSONS I3)。
+- **Rust 依赖新库**走 CONTRIBUTING 的高门槛(cargo-deny 许可清单);引入前先看标准库与既有 crate 能否覆盖。
diff --git "a/docs/\347\273\217\351\252\214\346\200\273\347\273\223/20261117-2200-\345\271\266\350\241\214\345\274\200\345\217\221\344\270\216\345\255\220\344\273\243\347\220\206\345\215\217\344\275\234\346\226\271\346\263\225\350\256\272-\347\273\217\351\252\214\346\200\273\347\273\223.md" "b/docs/\347\273\217\351\252\214\346\200\273\347\273\223/20261117-2200-\345\271\266\350\241\214\345\274\200\345\217\221\344\270\216\345\255\220\344\273\243\347\220\206\345\215\217\344\275\234\346\226\271\346\263\225\350\256\272-\347\273\217\351\252\214\346\200\273\347\273\223.md"
new file mode 100644
index 00000000..9f22efa4
--- /dev/null
+++ "b/docs/\347\273\217\351\252\214\346\200\273\347\273\223/20261117-2200-\345\271\266\350\241\214\345\274\200\345\217\221\344\270\216\345\255\220\344\273\243\347\220\206\345\215\217\344\275\234\346\226\271\346\263\225\350\256\272-\347\273\217\351\252\214\346\200\273\347\273\223.md"
@@ -0,0 +1,48 @@
+# 并行开发与子代理协作方法论汇编
+
+> 本汇编收录自 mybatis-plus-sql-visualizer 仓 `docs/经验总结/` 五篇方法论文章的普适核心(2026-09~10 实战沉淀,与具体技术栈无关),建仓时一次性导入。叙事细节与完整案例查源仓原文。
+> 配套规则见 [`docs/开发流程-派活与验收清单.md`](../开发流程-派活与验收清单.md);本篇只写「为什么」,不重复「怎么做」。
+
+## 一、多路并行开发中的验证盲区(为什么绿灯看不出问题)
+
+四类「绿灯看不出的问题」:
+
+1. **加了防护不等于防护有效**——须有「防护被绕过」的反例(反向验证)。
+2. **加了透传不等于透传到达**——须向上找同函数的外层吞噬点。
+3. **追加字段会挤掉老信息**——断言被挤掉的字段仍可见。
+4. **接线守卫用整文件 contains 会假绿**——必须匹配调用点精确串;整文件子串检查在回退调用后仍然绿。
+
+守卫自证盲区四条方法论:
+
+- 守卫改动必须用真实站点做「删掉修复 → 必红」。
+- 合成样本证明规则不空转,真实站点反向验证证明规则有判别力,**不可互替**。
+- 「仓内 0 违规」在写命中为 0 时是空绿。
+- 守卫绑定面要覆盖仓内主流形态——新规则上线前先 grep 要防的真实站点用哪种写法。
+
+「根治的口径怎么被证伪」:声称根治前先问「我的改动是否触及机制本身」。
+
+## 二、子智能体后台派发与并行调度
+
+- **并行度来自「后台」**,与「一条消息塞几个调用」无关(一条消息多个调用实测只产出一个,一律 run_in_background 逐条派)。
+- **派发前三检查**:①写集显式声明并两两求交——交集非空必须串行,同文件三处改动合成一个 agent;②主任务自留一条不重叠车道,不空等;③prompt 自包含——后台 agent 无法提问,不确定先派只读侦察。
+- **收口协议**:不轮询等通知;读产物不读 agent 输出全文;回报压缩为「状态/产物/证据/是否通过」;写与验分离,另派只读复核;**拿 agent 自述当结论是最常见的坑**。
+
+## 三、测试三档分层与收口时序
+
+- 为什么子代理不该跑全量:并行期读数不可信(别人在途改动让全量成片失败)、墙钟 N 倍、构建校验的判别力不随次数增加。
+- 收口时序「门禁 ∥ 写文档」:全部子代理完成后单派只读收口代理跑全量,主控同时写文档收尾,并行不空等。
+- 长命令一律后台不许 sleep:睡几百秒既解决不了锁又白占并发槽位。
+- 待办清单与实际进度同步:清单是用户看进度的唯一窗口,不许出现「实际做完好几步、清单停在第一步」。
+
+## 四、token 消耗治理(省 token 的主杠杆是会话粒度,不是提示词)
+
+- 一条工具输出进入上下文后每次请求重发:早收口收益是**乘法级**。成本模型——第 k 次请求的一条 5K 输出,若会话还有 100 次请求,实际消耗 500K。
+- **P0 纪律**:上下文到 12~15 万就收口、写交接文档、开新会话;一个可提交单元一个会话;探索交给子代理、只回收 ≤1.5K 结论。
+- **交接文档字段固定**:分支与 tip / 已完成 / 未完成 / 证据读数 / 下一步 / 踩过的坑。
+- 红线:截断只截通过时的噪音;失败必须走结构化失败聚合,不能盲截栈。
+
+## 五、调度模式与决策模式的选用
+
+- 一句话判定:**有执行疑问(怎么分配、并行还是串行)→ 开执行调度层;有方向/因果/分歧疑问(该不该做、为什么、选哪条路)→ 开决策统筹层**。
+- 方向未定就并行,方向错了并行越多错得越多。
+- 组合用法:决策层主持总循环(定位—复盘—转失败),调度层在每轮里战术性并派与复核。
diff --git "a/docs/\350\247\204\350\214\203/git\344\270\216\345\244\232\344\273\223\346\223\215\344\275\234\351\205\215\346\226\271-\350\257\264\346\230\216\346\226\207\346\241\243.md" "b/docs/\350\247\204\350\214\203/git\344\270\216\345\244\232\344\273\223\346\223\215\344\275\234\351\205\215\346\226\271-\350\257\264\346\230\216\346\226\207\346\241\243.md"
new file mode 100644
index 00000000..cf86dcc3
--- /dev/null
+++ "b/docs/\350\247\204\350\214\203/git\344\270\216\345\244\232\344\273\223\346\223\215\344\275\234\351\205\215\346\226\271-\350\257\264\346\230\216\346\226\207\346\241\243.md"
@@ -0,0 +1,69 @@
+# Git 与多仓操作配方
+
+> 从 mybatis-plus-sql-visualizer 仓多会话并行开发实战沉淀的 git 配方,按 7shell 场景整理。教训的一句话版本见 [`LESSONS.md`](../LESSONS.md)(I32/I34/I44 等);本文件写具体操作步骤。
+
+## 一、暂存与提交
+
+### `git add` 对被忽略目录静默无效的绕过(LESSONS I32)
+
+```bash
+# add -f 无效时(exit 0 但暂存区空)
+hash=$(git hash-object -w )
+git update-index --add --cacheinfo 100644,$hash,
+# 提交后必回读确认
+git ls-files | grep
+```
+
+### 提交纪律
+
+- 消息写 UTF-8 文件后 `git commit -F`;中文跨调用一律写文件传递(Bash 直传乱码)。
+- 消息里禁反引号(Git Bash 命令替换:报错但提交仍成功、信息静默缺段)。
+- 提交后 `git show --stat HEAD` 必须只列自己的文件——多车道/并行会话时 `git add` 只点明确路径,**禁 `-A`**(会卷走别的会话在途文件)。
+- 提交身份先核:仓内写死 `user.email`(贡献归属按邮箱映射),错了用 `--reset-author` 修(LESSONS I44)。
+
+### 编辑工具的锚点陷阱(LESSONS I34)
+
+超长单行(表格行、状态行、锁文件)不能用行首前缀当 `old_string`——原行残余会粘到新行尾,且 `git diff --stat` 对单行文件恒显示 1 insertion 掩盖破坏。改完整行回读校验。
+
+## 二、工作树与分支
+
+### 清理作业口径
+
+删工作树/分支前逐个核:`git worktree remove --force`(build 产物会挡);分支删除前必验 tip 可达性——`git merge-base --is-ancestor master`(或 `git tag --contains`),否则唯一提交全库孤立。注意 cherry-pick 过的分支 `--contains` 失灵,判据改用 tree 哈希 + diff 空。
+
+- 远端真值看 `git ls-remote`(本地 remote-tracking 会过期)。
+- 删远端分支须用户点头。
+- Windows 长路径删不掉:`\\?\` 前缀 + `rd /s /q` 写成 `.ps1` 执行。
+
+### 共享工作树的三条禁令
+
+1. 别家在途文档别用 `git stash push` 挪开(LESSONS I23——pop 冲突窗口里对方会把冲突标记提交进主干)。
+2. 合并冲突逐 hunk 裁决;**文档类禁整侧 `--ours/--theirs`**(会静默丢掉另一侧新增行)。裁决前 `git show :2:` / `:3:` 各自落盘 diff,按行取并集再回填。
+3. 长命令后台跑 + 全量落盘(LESSONS I27/I43 相关)。
+
+## 三、多仓推送
+
+- **仓名写死**:不读凭据文件里的 `repo` 字段拼 URL(常是从别的仓拷来的旧值,会把 A 仓提交推给 B 仓)。推送前回显目标 URL(token 打码)。
+- **推送走令牌**:读 `.local/github-token.json`(或对应凭据文件),命令行 `-c credential.helper=` 置空凭据助手、`GIT_TERMINAL_PROMPT=0`——裸推会走 GUI 凭据管理器弹窗抢焦点(AGENTS.md 第 8 条)。
+- **强推用显式 lease**:URL 直推不更新 remote-tracking,裸 `--force-with-lease` 会误报 stale;写全 `--force-with-lease=master:<旧 sha>`,动手前先 `ls-remote` 对齐双远端。
+- **推送脚本纯 ASCII**:PowerShell 5.1 对无 BOM 的 `.ps1` 按 ANSI 解码,中文注释会吃掉下一行变量赋值(URL 变成 `…/owner/.git` 报 403,报错完全不指向「变量为空」)。
+
+### Gitee 建仓三怪癖
+
+1. 建 repo 的 `private:false` 会被忽略(201 仍私有)。
+2. **空仓不能转公开(422)→ 先推内容再 PATCH `private=false`**,判据=匿名 raw 返回 200。
+3. PATCH `/repos` 必须带 `name` 字段。
+
+## 四、本机 Git Bash 工具链坑(速查)
+
+| 坑 | 处置 |
+|---|---|
+| `grep` 是 ugrep 包装,`-c` 与管道静默返空 | 0 命中先怀疑工具;换 `rg` 或原生 grep |
+| `unzip … \| grep -q` 假阴性 | 管道末命令退出码≠工具退出码;分步跑 |
+| `comm` 对含中文/CRLF 清单恒「零交集」 | 集合运算改 `grep -F` |
+| python 不认 `/f/` 风格路径 | 用 Windows 路径或 `cygpath -w` 单路径转换 |
+| `sed -i` 会改行尾 | 改行尾敏感文件前先备份比对 |
+| cygpath 转分号分隔清单整串当一个路径 | 清单原文直接用,不整体 cygpath |
+| Git Bash 直调 `powershell -File` 吞退出码 | `-Command "& '...ps1' ...; exit $LASTEXITCODE"` |
+| 含中文的 `.ps1` 无 BOM 被 PS 5.1 按 ANSI 炸 | 用 pwsh 7,或脚本纯 ASCII |
+| MSYS 把 `/X` 参数转成路径 | 带 `/X` 参数的 Windows 工具一律写 `.ps1` 执行 |
diff --git "a/docs/\350\247\204\350\214\203/\344\273\243\347\240\201\347\274\226\350\276\221\350\247\204\350\214\203-grep\344\274\230\345\205\210\350\257\273\345\217\226.md" "b/docs/\350\247\204\350\214\203/\344\273\243\347\240\201\347\274\226\350\276\221\350\247\204\350\214\203-grep\344\274\230\345\205\210\350\257\273\345\217\226.md"
new file mode 100644
index 00000000..dcc1ebb3
--- /dev/null
+++ "b/docs/\350\247\204\350\214\203/\344\273\243\347\240\201\347\274\226\350\276\221\350\247\204\350\214\203-grep\344\274\230\345\205\210\350\257\273\345\217\226.md"
@@ -0,0 +1,73 @@
+# 代码编辑规范:grep 优先读取
+
+> **用途**:修改大文件(>300 行)时,用 grep 定位行号 + 精确 Read,替代全文读取。机制导入自 mybatis-plus-sql-visualizer 仓同名规范。
+> **触发条件**:修改涉及 >300 行的文件时。
+
+---
+
+## 核心原则
+
+> **先 grep 定位行号,再 Read 精确范围,最后 Edit 修改。绝不 Read 整个大文件。**
+
+## 分级操作
+
+### Level 1:简单修改(改文案 / 改条件 / 改一行)
+
+```bash
+rg -n "目标内容" crates/sevenshell-core/src/lib.rs # 定位行号
+Read 行号-5 ~ 行号+5 # 只看上下文
+```
+
+token 消耗:<100。不需要看全文。
+
+### Level 2:修改方法逻辑(改参数 / 加返回值 / 改条件分支)
+
+```bash
+rg -n "fn connect" crates/sevenshell-ssh/src/session.rs # 找函数体范围
+Read 函数体 # 读完整函数
+rg -n "涉及的字段名/结构体名" crates/ # 找依赖的字段和类型
+Read 字段声明区域 # 确认类型
+```
+
+token 消耗:~400。两轮 grep + 两轮小范围 Read。
+
+### Level 3:重构 / 拆分(大改)
+
+```bash
+rg -n "^(pub )?(async )?fn |^pub struct |^pub enum |^impl " 文件.rs # 列出所有声明
+Read 关键区间(字段区 + 要改的函数 + 相关函数)
+```
+
+TS 侧同理:`rg -n "export (function|const|class|interface)" apps/desktop/src --type ts`。
+
+token 消耗:~2K。先看清结构,再定向读取。
+
+## 什么时候必须读全文
+
+只有一种情况:**你不知道这个文件里有什么,也不知道要改哪里**。这时候需要探索。但探索完之后,后续修改都应该用 grep 定位。
+
+## 会遗漏的场景(必须注意)
+
+修改函数时,grep 只看到函数体,可能**遗漏依赖**:
+
+- **字段声明**:函数里用的字段,声明可能在文件顶部或 `struct` 定义里(类型、可空性)
+- **use / import**:函数里用的类型,导入在文件头
+- **相关函数**:改 `connect()` 可能需要理解 `reconnect()` 的逻辑
+- **trait / 接口契约**:改实现前先看 trait 定义;改 Rust 时注意 `impl` 块可能分散在多处
+
+**应对**:每次修改前,用 grep 先确认涉及的字段和依赖,再定向 Read。不要跳过「找依赖」这一步。
+
+## token 对比
+
+| 场景 | 全文 Read | grep + 精确 Read | 节省 |
+|------|-----------|-------------------|------|
+| 改一行文案 | ~6,000 | <100 | 98% |
+| 改函数逻辑 | ~6,000 | ~400 | 93% |
+| 重构拆分 | ~6,000 | ~2,000 | 68% |
+
+## 注意事项
+
+- grep/rg/find 命令跑在 shell 里,不消耗 token(是工具调用,不是 LLM 读取)
+- 只有 Read 的内容才计入 token
+- grep 输出的行号是 1-based
+- Edit 的 old_string 必须与文件内容**逐字符匹配**,grep 定位后用 Read 确认精确内容再 Edit
diff --git "a/docs/\350\247\204\350\214\203/\345\215\217\344\275\234\345\201\217\345\245\275-\350\257\264\346\230\216\346\226\207\346\241\243.md" "b/docs/\350\247\204\350\214\203/\345\215\217\344\275\234\345\201\217\345\245\275-\350\257\264\346\230\216\346\226\207\346\241\243.md"
new file mode 100644
index 00000000..62d2d3d0
--- /dev/null
+++ "b/docs/\350\247\204\350\214\203/\345\215\217\344\275\234\345\201\217\345\245\275-\350\257\264\346\230\216\346\226\207\346\241\243.md"
@@ -0,0 +1,39 @@
+# 协作偏好(AI 代理工作口径)
+
+> 用户在 mybatis-plus-sql-visualizer 项目多轮协作中确认的工作方式,建仓时沉淀为 7shell 的协作口径。与本仓 [`AGENTS.md`](../../AGENTS.md)、[`开发流程-派活与验收清单.md`](../开发流程-派活与验收清单.md) 冲突时以更严格者为准;本文件写「用户怎么要求做事」,不重复流程细节。
+
+## 立项与实施
+
+- **先立项再开工**:动手前先写计划/提案文档;实施者先证伪计划里的「待验证前提」再落码。大变更走 PIP(见 [`pips/README.md`](../pips/README.md)),任务级实施立时间戳计划文档。
+- **验收清单要能照抄**:每项给操作路径 + 预期值 + 失败时的日志锚点 + 回退开关;「环境受限未验证」如实标注,不冒充通过。
+- **实施计划的所有内容都要做**:「实施计划所有内容」指全部条目,不得自行缩成高优项或只做文档登记。
+- **派发前核实任务状态**:立项/实施前先全分支、全工作树排查这活是否已有人做过或在做,防重复实施;缺陷/任务编号取号前先 grep 查重。
+- **主控的统计结论也要被证伪**:计数类结论(多少处、多少个、覆盖几条)入文档前必须附产生它的命令与口径。
+
+## 验证分工
+
+- **性能问题先非 GUI 自证**:先通过非 GUI 用例验证(注入缝放大「慢」→ 断言新路径不触发同步检索 + 耗时上限),验证没问题再交 GUI 验收。
+- **最终 GUI 验收由用户做**:助手交付编号步骤 + 预期结果 + 失败时该看的日志行 + 判读口径,不代用户点 GUI;用户在用电脑时不占用桌面跑 GUI 自动化。
+- **优化不得收窄兼容面**:收窄候选源/搜索范围类优化必须配「未命中回补链 + 跨形态用例」,不许为了提速把某个平台/协议/形态静默排除——漏掉的形态在测试夹具里往往看不见。
+
+## 授权边界
+
+- **文档、代码、合流、发行、推送是五个独立许可**:一次「允许」只覆盖它明说的那件事;「只更新 md,不用改代码」意味着先前的代码授权作废,新指令与在跑的写操作冲突时先回退再改文档。
+- **清理类任务未授权不得删改任何文件**:分析阶段只读,先出风险分档表等逐组勾选;授权当次逐组有效,未勾的不许顺带清。
+- **对外动作(push/tag/发行/外发内容)须用户明确授权**(AGENTS.md 第 7 条的重申)。
+- **发行物/构建产物判「能不能发」看门禁读数与树的干净状态**,不看自述(LESSONS I35)。
+
+## 文案与界面
+
+- **面向用户的变更日志要简写**:一条一主题、每条短行(≤60~80 字),宁 8 条短不要 4 条长;只写用户可见结果,根因与读数留在内部记录。段序按 Added→Fixed→Changed。
+- **界面文案要教会用户「怎么填」**:行标签显示内部编号时用户会怀疑东西坏了;标签取条件文本、输入区给常驻说明、置灰要说明原因与替代入口。
+- **错误提示写界面真实存在的标签页名 + 当场可核对的一件事**(例:「设置 → 外观 → 字体,这个下拉里应有等宽字体」),不写抽象设置项名,不引导用户改无关文件。
+- **新 UI 交互照抄仓内既有同类实现**:一致性优先于自创。
+- **显示格式严格跟随设置**:空间不够应丢整块信息或截断,不是把字段缩写成另一种格式。
+- **产品描述禁用能力清单替换口号**:摘要给钩子、清单是正文的活;「支持 N 种 X」这类罗列不做标题。
+
+## 异步与并行
+
+- **后台任务禁阻塞等待**:长命令 `run_in_background` 启动 → 主控继续做不依赖读数的事 → 只在完成通知后取数;禁 sleep 轮询、禁阻塞式等待输出(细则见派活清单)。
+- **达标即提交**:给子代理派活写死「每完成一件可提交的就立即提交」;报告给按时间顺序的提交哈希清单。
+- **并行紧张时转主控直接实施**:派活前探余量,子代理失败/被叫停后不原样重派,接手前先审计工作树有无半成品。
diff --git "a/docs/\350\247\204\350\214\203/\346\226\207\346\241\243\345\221\275\345\220\215\350\247\204\350\214\203-\350\257\264\346\230\216\346\226\207\346\241\243.md" "b/docs/\350\247\204\350\214\203/\346\226\207\346\241\243\345\221\275\345\220\215\350\247\204\350\214\203-\350\257\264\346\230\216\346\226\207\346\241\243.md"
new file mode 100644
index 00000000..8cfdac54
--- /dev/null
+++ "b/docs/\350\247\204\350\214\203/\346\226\207\346\241\243\345\221\275\345\220\215\350\247\204\350\214\203-\350\257\264\346\230\216\346\226\207\346\241\243.md"
@@ -0,0 +1,50 @@
+# 文档命名规范(内部协作文档)
+
+> 约束 7shell 仓内部协作文档的命名与组织。机制导入自 mybatis-plus-sql-visualizer 仓同名规范,删去其业务专属节。
+> 分工边界:面向用户的英文文档(`docs/guide/`、`docs/index.md` 等 VitePress 站点)不归本规范管;本规范只管「我们怎么做事」的内部协作文档。与 [`docs/pips/`](../pips/README.md) 的分工见 §三。
+
+## 一、时间戳前缀命名体系
+
+一次性任务文档统一 `{YYYYMMDD}-{HHMM}-{主题}-{文档类型}.md`,按类型归目录:
+
+| 类型 | 目录 | 示例 |
+|---|---|---|
+| 开发计划 | `docs/开发计划/` | `20261117-1430-连接重连策略-开发计划.md` |
+| 调研报告 | `docs/调研报告/` | `20261117-1617-竞品横向对比-调研报告.md` |
+| 验收文档 | `docs/验收文档/` | `20261117-1225-里程碑验收-验收文档.md` |
+| 性能分析 | `docs/性能分析/` | `20261117-0821-启动耗时-性能分析.md` |
+| 经验总结 | `docs/经验总结/` | `20261117-0900-门禁提速-经验总结.md` |
+
+- 日期 YYYYMMDD、时分 HHMM(文档创建时刻)。
+- 验收文档的内容要求:一次交付(合并/里程碑/发行)带来的全部用户可见变更集中验收——新增功能清单、逐项验收步骤(操作路径 + 预期结果)、已知边界、回归基线;自动化已验证项与需手工走查项分开陈述。
+- 经验总结的范围界定:跨任务可复用的踩坑与配方;单任务的实施过程记录写在开发计划文档的实施记录节,不另立经验总结。
+
+## 二、规范类四后缀
+
+`docs/规范/` 目录下,主题**不带日期**(约定长期有效,不按任务归档):
+
+- `{主题}-规范.md`——约定类
+- `{主题}-清单.md`——可勾选验收项
+- `{主题}-红线.md`——禁止项
+- `{主题}-说明文档.md`——长期说明(机制、指南、协议)
+
+确需区分版本时写 `{主题}-{YYYYMMDD}版.md`。一次性任务材料不得放入 `docs/规范/`。
+
+**根级账本例外**:两类文件留 `docs/` 根目录、不进 `规范/`——
+- `docs/LESSONS.md`:活跃教训账本,收口/故障后高频追加,位置服务于写入入口(与 `AGENTS.md` 呼应),不是稳定规范。
+- `docs/MEMORY.md`:文档检索索引,索引入口身份要求路径长期稳定。
+
+判据:**「稳定规则/约定」进 `规范/`;「活跃账本/索引入口/权威总册」留根**。
+
+## 三、与 PIP 的分工
+
+- 大提案(动 security-model 不变量、公开契约、crate 依赖方向、发行承诺)走 [`docs/pips/`](../pips/README.md),命名 `PIP-NNNN-short-title.md`(其 README 的门槛与流程为准)。
+- PIP 管「决策为什么这么做」;时间戳计划文档管「一次实施怎么干活、干到哪了」。两者可并存:PIP-Accepted 后的实施细节立时间戳计划文档,互相链接不复制内容。
+
+## 四、引用与图片规范
+
+- 文档内嵌图一律使用**文件相对路径**(基准=当前文档所在目录)——这是唯一在 GitHub / Gitee / VS Code / IDE 预览中全部正确的写法;禁内嵌外链图片(防盗链 302 会导致站外不可见)。
+- 资源清单类表格里列「路径」时用仓库根相对写法(描述文件位置而非嵌入)。
+- 手工渲染的示意图(非真机截图)在引用处必须**显式标注「设计稿,非实现截图」**,避免被误读为功能已实现。
+- 对外素材(README/官网引用的图)与开发过程设计稿分目录存放,防清理时误删对外图。
+- 功能演示动图不入仓:README 引用官网稳定 URL,仓库内不留副本。
diff --git "a/docs/\350\247\204\350\214\203/\347\274\226\347\240\201\344\270\216\351\252\214\346\224\266\346\240\207\345\207\206.md" "b/docs/\350\247\204\350\214\203/\347\274\226\347\240\201\344\270\216\351\252\214\346\224\266\346\240\207\345\207\206.md"
new file mode 100644
index 00000000..67ad7a54
--- /dev/null
+++ "b/docs/\350\247\204\350\214\203/\347\274\226\347\240\201\344\270\216\351\252\214\346\224\266\346\240\207\345\207\206.md"
@@ -0,0 +1,32 @@
+# 编码与验收标准
+
+> 本文件机制导入自 mybatis-plus-sql-visualizer 仓的《编码与验收标准》(其条目全部来自教训账本 Seen 满 3 个不同日期的复发教训,另有显式标注来源的「机制导入」节)。
+> 格式两列:左列一句话祈使句规则,右列「审查者/复核者具体看什么」。审查定向测试报告、复核收口读数、评审他人提交时逐条对照;不满足的条目要在报告里点名说哪条不满足。
+> 演进规则:V/C 条目只能从 [`LESSONS.md`](../LESSONS.md) 升级进来(Seen ≥ 3),不允许直接在本文件立新规;M 条目只允许整节机制导入(须标注来源)。
+
+## 验证与测试
+
+| 规则 | 复核者看什么 |
+|---|---|
+| **V1 反向验证必须成对且有对照,空绿不算数** | 守卫/扫描类改动:摘掉修复分支必须变红(贴两次读数);合成样本只证「规则看得见我造的形态」,须补真实形态对照;「全仓 0 违规」在写命中为 0 时是空绿;探针夹具值必须与守卫默认值拉开。 |
+| **V2 定向测试以判据数收读数** | 报告必须给每类用例数(`cargo test` 的 `N passed` / vitest 的 tests 数),判据数对不上即视为没跑;过滤器不匹配会静默跑 0 个测试且退出码正常——看到 `0 passed` 就当没跑。改共享类型/守卫脚本后跑整桶而非单文件。 |
+| **V3 收口多步禁用 `&&` 串联** | 多步收口用分号或显式检查每步退出码;合并/门禁的失败会伪装成「进行中」(源仓实测白等半小时)。 |
+| **V4 工作树所有权与并发写隔离** | 接手掉线代理先 `git status` + 搜临时探针/RED PROBE 注释,确认工作树没停在「先红」中间态;并发车道禁同改 `src/`;**提交后 `git show --stat HEAD` 必须只列自己的文件**,读数贴进报告;跑长构建前过 `parallel_tasks.py check` + 登记。 |
+| **V5 证据看产物,不看文档自述** | 判断影响面/用户受影响面以 tag 树、发行物内容、二进制、实测请求为准;CHANGELOG/清单与产物不符即 blocker;「未复现」如实标注 not run,不得写成通过。 |
+| **V6 修 bug 必 grep 同型兄弟** | 修一处缺陷时 grep 同模式调用点/同形状守卫/同谓词分支,本次一并修或明确登记;机制替换要列全「同形态的平行实现」清单(见 LESSONS I21)。 |
+
+## 提交与文档
+
+| 规则 | 复核者看什么 |
+|---|---|
+| **C1 提交信息走 UTF-8 文件 `-F`,body 带验证记录** | 禁 `git commit -m` 内联(Git Bash 反引号陷阱——报错但提交仍成功、信息静默缺段);授权提交的 body 写「跑了什么定向、读数多少」;编辑后回读校验关键内容在场。 |
+| **C2 文档契约与代码同源** | 行为域文档(`docs/architecture.md`、`docs/security-model.md`、`docs/ui-conventions.md`)改契约须同批更新;security-model 不变量变更先走 PIP;链接指源文件与具名符号,不复制实现;一个事实只写一处、他处链接。 |
+| **C3 本机工具红线** | Git Bash 传 `/X` 参数一律 `.ps1` 化;robocopy 0~7 均成功;跨调用写文件用编辑工具(Bash 内 python/heredoc 可能不落盘);中文请求体写 UTF-8 文件再 curl;含中文的 `.ps1` 用 pwsh 7 或纯 ASCII。 |
+
+## 机制导入
+
+| 规则 | 复核者看什么 |
+|---|---|
+| **M1 协议/钩子的失败策略必须显式成契约**(来源:插件仓 M1,其机制取自 magpie) | 新增/评审扩展面(descriptor 协议、MCP 工具、事件回调、sidecar 接口)时:①接口文档显式声明 fail-open(钩子坏了不拦业务,只计数/限流日志)还是 fail-closed(钩子缺失/异常时拒绝服务——安全、凭据、脱敏类属此档);②「每事件一次」与「每会话一次」生命周期的钩子分开,不混在一个接口里;③注册函数一律返回注销句柄 + 内部幂等删除,绝不暴露内部列表;④fail-closed 点位必须有按需刷新路径,不允许重启生效。 |
+| **M2 注释里点名的守卫必须真的存在,且守卫自身有反向验证**(来源:插件仓 L16/L7 实战) | 注释断言「已由某某守卫保证」时 grep 确认守卫在场;守卫类测试入库时配「摘掉被守卫的规则必须变红」的自证;新增守卫/扫描测试文件要登记进守卫清单(若建立),漏登只在 CI 全量时红。 |
+| **M3 记忆与文档三层分工**(来源:插件仓 docs 体系) | 仓库文档写现状(事实源唯一);提案与计划进 `docs/pips/`;教训账本只收可执行规则、事件叙事进 `docs/经验总结/`。改代码前先读账本;收口后顺手补记(有新教训才记,没有不硬凑)。 |
diff --git "a/docs/\350\247\204\350\214\203/\350\256\260\345\277\206\347\262\276\347\256\200\350\247\204\350\214\203.md" "b/docs/\350\247\204\350\214\203/\350\256\260\345\277\206\347\262\276\347\256\200\350\247\204\350\214\203.md"
new file mode 100644
index 00000000..33626fd6
--- /dev/null
+++ "b/docs/\350\247\204\350\214\203/\350\256\260\345\277\206\347\262\276\347\256\200\350\247\204\350\214\203.md"
@@ -0,0 +1,83 @@
+# 记忆精简规范
+
+> 规范本地记忆文件(`~/.zcode/cli/memories/projects/<本项目>/memory/`)的管理,防止无限增长导致上下文膨胀。机制导入自 mybatis-plus-sql-visualizer 仓同名规范。
+> **适用**:每次完成功能开发或修复后,主动判断记忆去向。
+
+---
+
+## 1. 三类记忆与去向
+
+| 类型 | 特征 | 去向 |
+|------|------|------|
+| **核心知识** | 架构、模型、约定、活跃功能(未完成/待实施) | 保留在项目 memory |
+| **已完成记录** | 已交付的功能、已修复的 bug、已解决的踩坑 | 移入 `docs/memory-archive/` |
+| **通用经验** | 平台/框架陷阱、方法论、用户偏好(跨项目复用) | 移入 `~/.zcode/cli/memories/global/` |
+
+### 保留标准(全部满足才保留)
+
+- 下次开发**仍需参考**(如架构决策、协议映射)
+- 处于**活跃状态**(功能待实施、问题未彻底解决)
+- **仅本项目独有**(否则归 global)
+
+### 归档标准(满足任一即归档)
+
+- 功能已交付且发行
+- Bug 已修复且测试全绿
+- 踩坑已解决且不会以相同形态复现
+- 开发计划执行完毕
+
+### 全局标准(满足任一即归 global)
+
+- Rust/Tauri/SSH 领域通用陷阱(非本项目特有)
+- 多智能体协调方法论
+- 用户偏好/环境配置
+
+---
+
+## 2. 归档目录结构
+
+```
+docs/memory-archive/
+├── README.md # 归档索引(导航清单)
+├── bug-fixes/ # 已修复 bug / 已完成功能
+├── pitfalls/ # 已解决踩坑
+└── methodology/ # 智能体方法论(备用)
+```
+
+### 归档索引维护
+
+每次归档新增文件后,同步更新 `README.md` 中对应分类表格:新增一行(文件名 + 一句话摘要)+ 更新底部统计。
+
+---
+
+## 3. 操作流程
+
+### 归档操作(每次完成功能/修复后)
+
+1. **判断**:按 §1 标准确定去向(保留 / 归档 / 全局)
+2. **移动**:`mv` 文件到对应归档子目录
+3. **更新归档索引**:`docs/memory-archive/README.md` 新增条目
+4. **更新项目索引**:从项目 `MEMORY.md` 删除已移出条目
+5. **提交**:`git add` 归档文件 + 索引,`git commit`
+
+### 定期审视(每 2~4 周或记忆增长 20%+ 时)
+
+1. 列出项目 memory 全部文件
+2. 逐文件按 §1 标准重新分类
+3. 批量移动 + 更新索引
+
+---
+
+## 4. 数量基线
+
+| 位置 | 基线 | 预警线 |
+|------|------|--------|
+| 项目 memory(含 MEMORY.md) | ~15 | >25 |
+| 归档 archive | 持续增长(历史记录) | — |
+| 全局 global | ~40 | >60 |
+
+超过预警线时触发定期审视。
+
+---
+
+> **原则**:记忆是开发过程的副产品,不是纪念品。已完成的记录就该归档,让活跃知识保持精简。
diff --git "a/docs/\350\247\204\350\214\203/\350\256\276\350\256\241\350\247\204\350\214\203-\345\274\271\347\252\227\345\205\213\345\210\266\347\272\242\347\272\277.md" "b/docs/\350\247\204\350\214\203/\350\256\276\350\256\241\350\247\204\350\214\203-\345\274\271\347\252\227\345\205\213\345\210\266\347\272\242\347\272\277.md"
new file mode 100644
index 00000000..bc9d20f5
--- /dev/null
+++ "b/docs/\350\247\204\350\214\203/\350\256\276\350\256\241\350\247\204\350\214\203-\345\274\271\347\252\227\345\205\213\345\210\266\347\272\242\347\272\277.md"
@@ -0,0 +1,57 @@
+# 弹窗克制红线
+
+> 本文档固化 7shell 弹窗与通知的设计红线:什么能弹、什么不能弹、新弹窗合入前要过哪几问。机制导入自 mybatis-plus-sql-visualizer 仓同名规范。
+> 立项依据:赛道内最完整的同类工具曾因「平均一小时一次弹窗」被用户打出 1 星并弃用——同类评论三年内出现三次。7shell 的「零打扰」不能只隐含在实现里,要写成约定,防的是未来迭代中「顺手」加一个无门禁弹窗。
+
+**清单与代码漂移的教训已吸取(源仓实测:文件级行号清单随重构大面积漂移失效)**:本规范从第一天就把触点清单写成「grep 模式 + 门禁机制字段」,不写文件:行号。每次触碰弹窗相关代码后重跑一遍:
+
+```bash
+# 前端(Vue3 + Tauri dialog/notification)
+rg -nE "window\.(alert|confirm|prompt)|\\b(ask|confirm|message|open)\\s*\\(|ElMessageBox|MessageBox|notification\\." apps/desktop/src --type ts -g '*.vue'
+# Tauri 后端与 Rust 侧弹窗/通知
+rg -nE "plugin-dialog|tauri-plugin-notification|MessageBox|Notification" crates/ src-tauri/
+```
+
+模式本身随技术栈演进修订;修订模式也是一次登记。
+
+## 登记义务
+
+新增或移除任何弹窗/通知触点,须同步更新本文触点清单;清单与 grep 结果对不上时,以 grep 复核结果为准并修订本文。
+新增「应用主动」类触点除登记外,还须过下方准入五问,任何一问不过不得合入。
+
+## 触点清单
+
+> 基线:待首审。7shell 尚未做过触点审计,首次合入弹窗相关改动时先跑一遍上面的 grep 建立基线行数,再逐点定性登记。
+
+| 触点 | grep 命中模式 | 触发方(用户/应用主动) | 门禁机制(开关/一次性/频率上限) |
+|------|--------------|------------------------|--------------------------------|
+| (待登记) | | | |
+
+## 允许类
+
+默认放行,不需要额外论证,但仍须登记进触点清单。
+
+1. 用户操作反馈:点击按钮后的结果、错误、「未找到」类提示。
+2. 用户操作确认:破坏性操作(删除会话/主机、清空数据等)的确认框、轻量输入框。
+3. 含开关的一次性通知:默认关或可永久忽略,同一触点每会话至多一次。
+
+## 禁止类
+
+一律不做,Code Review 按此驳回。
+
+1. 无开关的应用主动弹窗、导流弹窗。导流只走设置页与 README。
+2. 营销/评分引导弹窗。评分引导只进 README 与更新通知正文链接。
+3. 频率超限的任何主动触点,超出「每会话一次」即违规。
+4. 后台失败转弹窗。连接失败、下载失败等主链失败在面板内报错或静默降级重试,不弹模态框。
+
+边界判断:「用户点击直接引发」是允许类的客观判据。拿不准的触发路径(如异步回调里弹提示)按禁止类处理,宁紧勿松。
+
+## 准入五问
+
+新增主动触点前逐问自检,全部通过才准合入:
+
+1. 是否用户点击直接引发?
+2. 面板内或通知形态是否确实不够用?
+3. 是否带开关或一次性?
+4. 频率上限是多少?
+5. 是否已在本文触点清单登记?
From 5209361736f92a54978953d19e89f2eb8220f7ec Mon Sep 17 00:00:00 2001
From: SongRenShuo <3064597532@qq.com>
Date: Wed, 18 Nov 2026 00:22:10 +0800
Subject: [PATCH 002/440] docs: research and a development plan for the Linux
desktop workbench
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Two background studies feed one decision: cooldesktop (full source) and
the reference product (asar static reverse engineering) both ship a "Linux desktop" that is
a web workbench over SSH-carried data, not a stream of screen pixels, and
most SSH targets are headless servers with no desktop to stream at all.
With the maintainer's call on 2026-11-18 the workbench shape is the whole
feature; a real pixel desktop stays out of scope and its evidence stays on
file.
- docs/调研报告/: the two raw studies, plus the synthesis that fixes the
direction and the naming (protocol linuxDesk, tab workbench)
- docs/开发计划/: the staged plan - descriptor pipeline, the two dispatch
arms in sevenshell-core, the frontend pane, lanes, gates and the premises
to falsify before coding
- docs/architecture.md: a "desktop workbench" section beside the RDP one
- docs/MEMORY.md: index entries for the new documents
---
docs/MEMORY.md | 10 +
docs/architecture.md | 20 ++
...00\345\217\221\350\256\241\345\210\222.md" | 107 ++++++++
...03\347\240\224\346\212\245\345\221\212.md" | 243 ++++++++++++++++++
...03\347\240\224\346\212\245\345\221\212.md" | 64 +++++
5 files changed, 444 insertions(+)
create mode 100644 "docs/\345\274\200\345\217\221\350\256\241\345\210\222/20261118-0019-linux\346\241\214\351\235\242\345\267\245\344\275\234\345\217\260-\345\274\200\345\217\221\350\256\241\345\210\222.md"
create mode 100644 "docs/\350\260\203\347\240\224\346\212\245\345\221\212/20261117-2356-cooldesktop-\350\260\203\347\240\224\346\212\245\345\221\212.md"
create mode 100644 "docs/\350\260\203\347\240\224\346\212\245\345\221\212/20261118-0017-linux\346\241\214\351\235\242\350\277\236\346\216\245-\350\260\203\347\240\224\346\212\245\345\221\212.md"
diff --git a/docs/MEMORY.md b/docs/MEMORY.md
index 7571986b..a8026908 100644
--- a/docs/MEMORY.md
+++ b/docs/MEMORY.md
@@ -28,6 +28,16 @@
- [`20261117-2200-并行开发与子代理协作方法论-经验总结.md`](经验总结/20261117-2200-并行开发与子代理协作方法论-经验总结.md) — 验证盲区、后台派发、测试分层、token 治理、调度模式五篇汇编
+## 调研报告(docs/调研报告/)
+
+- [`20261117-2356-cooldesktop-调研报告.md`](调研报告/20261117-2356-cooldesktop-调研报告.md) — cooldesktop 全量源码调研:Web 桌面壳定性、消息协议组织精华、安全反面教材
+- [`20261118-0007-product-research.md`](调研报告/20261118-0007-product-research.md) — the reference product(the product)asar 静态逆向:Go sidecar SSH 栈、Web 桌面形态、隧道与连接管理模型
+- [`20261118-0017-linux桌面连接-调研报告.md`](调研报告/20261118-0017-linux桌面连接-调研报告.md) — 两项目调研综述与「Linux 桌面」方向决策(只做 Web 桌面工作台)
+
+## 开发计划(docs/开发计划/)
+
+- [`20261118-0019-linux桌面工作台-开发计划.md`](开发计划/20261118-0019-linux桌面工作台-开发计划.md) — linuxDesk 协议管道 + 前端工作台面板:分期任务、派活车道、待验证前提
+
## 记忆归档
- `docs/memory-archive/` — 已交付功能、已解决踩坑的归档(判定标准见记忆精简规范;建仓暂空,首次归档时建 README 索引)
diff --git a/docs/architecture.md b/docs/architecture.md
index 796e2282..21bc0b33 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -78,6 +78,26 @@ full-screen choice and drive mapping are stored per session (`DesktopSettings`),
one machine can differ. Drive mapping is on by default, matching what the reference dialog calls
regular: the remote can read and write the local drives while a session is open.
+## The desktop workbench
+
+The `linuxDesk` protocol is the second answer to "show me that machine", and it is the opposite
+shape: where RDP hands the session to another program, the workbench draws one — and where RDP
+needs a desktop environment on the far side, the workbench needs nothing but the SSH connection
+it is. Most machines an SSH client reaches are headless servers, which is exactly the finding the
+reference study recorded about the two products it examined: their "Linux desktops" are web
+workbenches over management data, not streams of screen pixels
+([the research note](调研报告/20261118-0017-linux桌面连接-调研报告.md) holds the evidence and the decision).
+
+A `linuxDesk` session is an ordinary SSH session in every mechanical sense — same open path, same
+host-key order, same vault fields, no new command on the wire (the dispatch arms in
+`crates/sevenshell-core/src/sessions.rs` are the whole backend difference). What differs is the
+front page: a session whose protocol supports the `workbench` capability mounts a workbench tab
+instead of a terminal tab, and the terminal, the file browser and the monitor pages open from it
+onto the same connection. The workbench itself composes surfaces this document already describes —
+the system mark, the host monitor's sample, the file browser's entries — and adds no new way for
+anything to reach the machine. Personal bits (recent file entries) live in the WebView's own
+storage like the recent-session list: usage memory, not settings.
+
## Opening a session
The order is the security property, so it is worth reading once:
diff --git "a/docs/\345\274\200\345\217\221\350\256\241\345\210\222/20261118-0019-linux\346\241\214\351\235\242\345\267\245\344\275\234\345\217\260-\345\274\200\345\217\221\350\256\241\345\210\222.md" "b/docs/\345\274\200\345\217\221\350\256\241\345\210\222/20261118-0019-linux\346\241\214\351\235\242\345\267\245\344\275\234\345\217\260-\345\274\200\345\217\221\350\256\241\345\210\222.md"
new file mode 100644
index 00000000..c12665ea
--- /dev/null
+++ "b/docs/\345\274\200\345\217\221\350\256\241\345\210\222/20261118-0019-linux\346\241\214\351\235\242\345\267\245\344\275\234\345\217\260-\345\274\200\345\217\221\350\256\241\345\210\222.md"
@@ -0,0 +1,107 @@
+# Linux 桌面工作台(linuxDesk)开发计划
+
+- 日期:2026-11-18(基线:song 分支 f460da4)
+- 状态:待实施。方向已由用户拍板(见[调研报告](../调研报告/20261118-0017-linux桌面连接-调研报告.md)第四节:只做 Web 桌面工作台,真实桌面画面不做)。
+- 决策依据:[cooldesktop-调研报告](../调研报告/20261117-2356-cooldesktop-调研报告.md)、[the reference product-调研报告](../调研报告/20261118-0007-product-research.md)、仓内协议架构盘点。
+
+## 一、目标与非目标
+
+**MVP 交付(一期)**:新增连接类型「Linux 桌面」(协议 id `linuxDesk`)。它是一条普通 SSH 连接,但连接后的默认 tab 是工作台面板:
+
+1. 系统卡:主机名、系统标志(复用 HostSystem 映射)、运行读数(CPU/内存/磁盘,复用 monitor 采样与速率换算)。
+2. 文件快捷区:主目录等入口的图标区,点击打开本会话的文件浏览器 tab(SFTP,共用同一连接);最近访问入口记在 WebView 本地存储(同 recent sessions 的用法记忆口径,不进设置文件)。
+3. 会话卡:连接状态、已验证的主机密钥指纹、加密连接的既得事实展示。
+4. 入口区:打开终端(同 handle 的终端 tab,懒挂载)、打开文件浏览器、打开监控页。
+
+**非目标(写清楚,防止范围爬升)**:
+
+- 真实桌面画面(VNC/RFB/像素流)——用户已拍板不做,将来另立提案(备选证据在调研报告第四节)。
+- 远端任何落盘/部署:无 GA agent 式远端组件,无 sshd_config 改写(the reference product 的两个反面教材)。
+- 应用中心、回收站、磁盘管理、网络挂载、服务器对传、批量命令面板——backlog,见第六节。
+- 新增 Tauri 命令、新增 crate、vault schema 升版——MVP 一概不需要(见待验证前提 5)。
+
+## 二、架构落点
+
+### 后端(足迹刻意极小)
+
+| 落点 | 改动 |
+|---|---|
+| `descriptors/protocols/linuxDesk.yaml` | 新增:schemaVersion 1、order 22(rdp 20 与 rawTcp 45 之间的空档)、id linuxDesk、rustVariant LinuxDesk、labelKey protocol.linuxDesk.label、defaultPort 22、runtime native、transport tcp、supportLevel connect、capabilities 见下 |
+| `descriptors/capabilities.yaml` | 新增能力 `workbench`(group desktop、order 150、labelKey capability.workbench.label),由 linuxDesk 声明 |
+| `pnpm generate:descriptors` | 提交两个生成物:descriptors.manifest.json + apps/desktop/src/types/generated/protocols.ts;`pnpm check:descriptors` 红=忘了同步 |
+| `crates/sevenshell-core/src/sessions.rs:211` | `Protocol::Ssh => {}` 扩为 `Protocol::Ssh | Protocol::LinuxDesk => {}`——linuxDesk 的开启路径与 SSH 完全同一条(主机密钥探测→决策→重验→carrier/terminal) |
+| `crates/sevenshell-core/src/sessions.rs:394-400` | unreachable 守卫的 SSH-like 列表补 LinuxDesk |
+| i18n | en + zh-CN 双份:protocol.linuxDesk.label、capability.workbench.label(workbench.* 前端域键随面板任务加) |
+
+linuxDesk 声明的能力(照抄 ssh.yaml 中工作台兑现的子集):shell、exec、resize、keepalive、hostMetrics、sftp、scp、jumpHost、forwarding、dynamicForwarding、recording、workbench。不声明 agentForwarding。
+
+### 前端(主要工作量)
+
+| 落点 | 改动 |
+|---|---|
+| `apps/desktop/src/stores/terminals.ts:251` | `WorkspaceTab` 联合加 `WorkbenchTab`(kind "workbench",持有 session) |
+| `apps/desktop/src/stores/terminals.ts:822-828` | open outcome 挂默认 tab 处按协议分叉:`protocolSupports(session.protocol, "workbench")` → 挂 workbench tab(不自动挂终端 tab,终端从工作台懒挂载,复用同一 handle) |
+| `apps/desktop/src/components/workspace/WorkbenchPane.vue` | 新组件:三块布局(系统卡 + 文件快捷区 + 会话/入口卡);数据全部走既有 invoke 包装(session_system、monitor_sample、文件列表) |
+| `apps/desktop/src/components/workspace/WorkspaceTabs.vue` | tab 分支、图标、关闭文案(参考归档 c981da4 里 desktop tab 的接线形态) |
+| `apps/desktop/src/components/sessions/SessionDialog.vue:94-99` | PROTOCOL_GROUPS 的 desktop 组加 linuxDesk;平台过滤(:125)不需要动——linuxDesk 全平台可用 |
+| `apps/desktop/src/types/session.ts`、`lib/backend/*` | 若 tab 形态需要 wire 镜像则同步;不新增命令包装 |
+| i18n workbench 域 | en + zh-CN 双份 |
+
+### 已清点的协议匹配面(实施第一项任务要复跑确认)
+
+全仓 `Protocol::Rdp` 仅 4 处(sessions.rs:212/395、desktop.rs:31/248),后两者是 RDP 专属不动;对协议的相等比较(files.rs:353/356、sevenshell-api/local/sessions.rs:125、src-tauri/commands/sessions.rs:46)不命中 LinuxDesk 即自动走 SSH 路径,均为期望行为。实施时先全量重跑 `rg -n "Protocol::" crates src-tauri packages apps/desktop/src` + 编译,确认清单无漂移,再动手。
+
+## 三、待验证前提(实施者先证伪再动手)
+
+1. **默认 tab 分叉点**:terminals.ts:822 的 open outcome 处理是否是唯一挂默认 tab 的位置(浏览器宿主 sevenshell-web 走同一前端代码,应同源;若有第二处挂签点会漏分叉)。验证法:grep `kind: "terminal"` 的构造点。
+2. **编辑器零改动假设**:SessionDialog 对 linuxDesk 只需加 picker 分组,SSH 字段/认证方法渲染完全复用。验证法:加完描述符后真开一次编辑器。
+3. **终端懒挂载兼容性**:terminals.ts 按 session.id 找终端 tab 的逻辑(:454 等)对「有 handle 但暂无终端 tab」的会话是否成立(文件浏览器「rides on a terminal's connection」的查找路径要能找到 handle 而不仅是 tab)。若不成立,最小修法是 linuxDesk 连接后仍挂一个隐藏的或直接挂载的终端 tab,由实测定。
+4. **monitor_sample 与 session_system 对 linuxDesk 会话无协议门槛**:两处按 handle 取连接,不查协议(architecture.md 口径),预期成立,实测确认。
+5. **vault 不升版**:Session 无新字段,LinuxDesk 会话随现有 schema 12 序列化无损。验证法:sevenshell-types/tests/wire.rs 加 LinuxDesk 会话夹具 + sevenshell-vault round-trip 测试(若有会话夹具文件)跑一遍。若 vault 的传输/备份测试按协议枚举遍历,会自动覆盖到。
+6. **policy 分类器不按协议分派**:classification 按命令串,与协议无关(读 policy.rs 确认无 protocol 分支)。
+
+## 四、分期与任务
+
+### P0 协议管道与骨架(车道 A,Rust+描述符,半天量级)
+
+1. 描述符 YAML + 生成物 + i18n 协议键(上文表格)。
+2. sessions.rs 两处分派 + 全仓协议匹配面扫查(含编译器兜底确认)。
+3. 测试:
+ - sevenshell-types wire.rs:LinuxDesk 会话序列化夹具(camelCase 守卫自动覆盖新变体)。
+ - sevenshell-core:linuxDesk 会话走 SSH 开启路径的定向测试(复用既有 SSH 开启测试的 lab,断言 open outcome 同形);流式终端路径对 LinuxDesk 的 unreachable 守卫测试。
+ - 反向验证探针:临时把 sessions.rs:211 的 LinuxDesk 从 SSH 臂摘掉 → 编译失败(非穷尽 match),证明分派点确实在场且被编译器盯住;截图/贴读数后还原。
+4. 写集:descriptors/、crates/sevenshell-types(生成物+测试)、crates/sevenshell-core/src/sessions.rs、apps/desktop/src/i18n/locales/*/protocol.json 与 capability.json、生成的 protocols.ts。
+5. 定向:`cargo test -p sevenshell-types wire`、`cargo test -p sevenshell-core <新增测试名>`、`pnpm check:descriptors`、`pnpm check:i18n`。明令不跑全量、不 clean。
+
+### P1 工作台面板(车道 B,前端,1~2 天量级;依赖 P0 的生成物)
+
+1. WorkbenchTab 类型 + 默认挂签分叉 + WorkspaceTabs 分支。
+2. WorkbenchPane.vue:系统卡(session_system + monitor_sample 数据,null 显示为「—」不是 0,沿用 monitor 面板口径)、文件快捷区(入口图标 + 最近访问)、会话/入口卡(指纹、终端/文件/监控入口)。
+3. 最近访问记 WebView 存储,不进 settings.json(安全模型「两种状态两个家」口径)。
+4. 测试:WorkbenchPane 组件 spec(数据 mock、空态、null 读数画横线);WorkspaceTabs spec 补 workbench 分支;stores/terminals spec 补默认分叉用例。
+5. 写集:apps/desktop/src/{components/workspace,stores,types,lib,i18n}。与车道 A 写集互斥(车道 A 不碰 stores/components)。
+6. 定向:`pnpm vitest run <改动文件>`。不跑全量。
+
+### P2 打磨(可与 P1 收口并行规划,不阻塞 MVP 门禁)
+
+1. 快捷操作区(重启/关机):必须走 policy 分类 + 确认对话 + 审计行(容器动作的既有模式),the reference product 的「输入确认重启」文案口径可借。此项触碰不变量 7 的消费面,落地时单独提交。
+2. 壁纸/主题个性化(the reference product desktopBgType 思路;若做成会话字段则触发 vault schema 升版,届时按迁移链流程走)。
+3. 文件快捷区指向任意路径(FilesTab 支持 initialPath 参数)。
+
+### Backlog(记录,不排期)
+
+真实桌面画面 PIP(证据:调研报告第四节);应用中心/回收站/磁盘管理/挂载(the reference product 功能清单为需求源);转发配置的场景示例文案;连接时自动回读 OS 名(the reference product `/node/updateOSName`——7shell 的 HostSystem 已有等价物,只差写回卡片)。
+
+## 五、派活与收口
+
+- **车道划分**:P0 车道 A 先行落盘(生成物是车道 B 的依赖);P1 车道 B 随后。两车道写集互斥。子代理并发 ≤3、构建并发 ≤2、跑长命令前 parallel_tasks.py check/register/done。
+- **派活六项**(每条派活写死):工作树 `git worktree add .worktrees/<名> -b <名> f460da4`(扁平分支名);写集按上文任务条目;只跑定向(见各任务);并行登记;提交纪律——每完成一件可提交的立即提交、git add 具体文件、消息写 UTF-8 文件 `git commit -F`、禁反引号、每笔提交过编译(`cargo check -p ` / `pnpm typecheck`);报告字段——改动文件、提交哈希、定向读数(逐例口径)、反向验证读数、未完成项与风险、跑门禁时树是否干净。
+- **红线**:不 push、不合流、不建 tag;不碰别人工作树;CHANGELOG 与本计划文档由主控统一回填(车道不写)。
+- **收口**:两车道完成后单派只读收口代理(独立沙盒、写集为空)跑一次权威全量 `pnpm check` + `cargo test --workspace` + `cargo clippy -- -D warnings`;主控并行写文档收尾,收口期间不碰 src/。构建校验(tauri build/app e2e)按「大改动」判据——本改动动 descriptors 协议,触发构建校验一档,发版前跑。
+- **not run 条款**:真机联一台真实 Linux 主机(含无头服务器与带桌面环境各一)的手工验收项,单独列出「没跑 + 为什么」;环境受限的读数不得写成验证通过。
+
+## 六、风险
+
+1. **前端默认 tab 分叉遗漏第二挂签点**(待验证前提 1)——后患是浏览器宿主或重连路径挂错面板,表现为「连上直接进了终端」这类小偏差,收口时以真机点检兜底。
+2. **术语与既有 RDP 文案混淆**:i18n 里 desktop 组现有文案面向 RDP 系统客户端;workbench 域的文案要避免「远程桌面」字样,统一叫「工作台」,防止用户把两者混为一谈。
+3. **能力声明过宽**:linuxDesk 照抄 ssh 能力集的前提是这些能力在 UI 上全部对 linuxDesk 可用(协议能力同时驱动 policy 与将来的 agent 工具面);若发现某能力对 linuxDesk 不该出现(如 recording),当次提交收紧声明,宁可窄不可宽。
diff --git "a/docs/\350\260\203\347\240\224\346\212\245\345\221\212/20261117-2356-cooldesktop-\350\260\203\347\240\224\346\212\245\345\221\212.md" "b/docs/\350\260\203\347\240\224\346\212\245\345\221\212/20261117-2356-cooldesktop-\350\260\203\347\240\224\346\212\245\345\221\212.md"
new file mode 100644
index 00000000..7b97be48
--- /dev/null
+++ "b/docs/\350\260\203\347\240\224\346\212\245\345\221\212/20261117-2356-cooldesktop-\350\260\203\347\240\224\346\212\245\345\221\212.md"
@@ -0,0 +1,243 @@
+# cooldesktop 调研报告
+
+> 调研对象:houxinlin/cooldesktop(F:\code\Java\Github\other\houxinlin\cooldesktop,本地只读检出,未跑构建)
+> 调研目的:为 7shell「Linux 桌面」连接类型提供参考——7shell 要的是通过 SSH 连接/隧道承载、在客户端渲染远程 Linux 主机真实桌面的可视化页面。
+> 调研方法:先读 README / install.sh / cool_sum.txt / 根级构建文件建立全局认知,再按模块深挖源码主线。所有结论带 `文件:行号` 出处(相对 cooldesktop 根目录)。文中标注「推断」处为证据不足、经分析得出的判断。
+
+## 结论速览
+
+1. cooldesktop 不是远程桌面,而是「Web 桌面壳」:在浏览器里画一个仿操作系统的窗口管理器,把文件管理、终端、日志追踪等服务器管理功能做成可开多窗口的 Web 应用,目标是「像操作本地系统一样操作远程 Linux」(README.md:3-31)。
+2. 全仓没有任何真实桌面采集痕迹:grep 不到 X11/Xvfb/Wayland/VNC/xrdp/截屏/java.awt.Robot 任何一处,「桌面」与「远程主机画面」无关。
+3. 部署模型是重型的:目标 Linux 服务器上常驻一个 Spring Boot fat jar(要求 JDK 11+,install.sh 用 root 权限注册 systemd 服务),浏览器直接访问服务端 2556 端口,与 SSH 隧道无关。
+4. desktop-loader 是第三方应用热加载器:按魔数区分 jar 应用与自定义 .webapp 包,用独立类加载器把 @Component 类注册进运行中的 Spring 容器、动态注册带应用 id 前缀的 Controller,支持卸载——这是全项目最有个性的部件。
+5. 传输层是双通道:STOMP over SockJS(广播主题 /desktop-topic/event,服务端推送 12 类事件)+ 终端专用原生 WebSocket(文本帧,ANSI 转义直通,前端 xterm.js 渲染);消息体是 JSON map(subject + action + 任意键值)。
+6. 输入注入不存在:没有任何鼠标键盘事件注入到桌面层的机制;「输入」只有两条路——终端键盘输入写 PTY stdin,其余操作全是标准 HTTP API。
+7. 终端链路用 pty4j 在服务端本地起 /bin/bash,不是 SSH 会话;窗口大小同步协议是「setSize + 四个定长 4 位数字」的字符串(LinuxTerminal.kt:45-52),比较粗糙。
+8. 认证靠魔改版 tomcat-embed-core(内含 TomcatGlobalAuthenticationValve 全局认证阀 + 登录 Servlet + IP 限流),源码不在本仓,密码明文存 ~/cooldesktop-work/password.conf;WebSocket 层本身零鉴权(握手发随机 UUID 当 Principal)。
+9. desktop-file 的分片上传协议(预检目标 → 分片落盘 → 按字节总和判完整 → 锁内合并 → WebSocket 通知刷新)与异步压缩/粘贴的「提交任务即返回 + WS 推结果」模式值得借鉴。
+10. 前端是 Vue SPA,源码在独立仓库 cooldesktop-web(README.md:88),本仓只有构建产物;从产物里可确认 xterm.js、拖拽窗口、iframe 内嵌 Web 应用三种技术。
+11. 单用户模型:无多用户、无权限分级、服务端剪贴板是全局单例,root 进程直接读写全盘——定位是个人服务器管理工具,不是多人协作产品。
+12. 对 7shell 的核心结论:它的「桌面」形态与 7shell 要的真实桌面渲染不匹配,但其 STOMP 主题协议设计、任务异步化 + WS 推送 UX、文件管理器交互、第三方应用加载器思路可以借鉴;SSH 承载与零服务端部署这两条 7shell 底线它都不满足。
+
+## 1. 项目定位与整体架构
+
+### 1.1 它是什么、给谁用
+
+README 开篇一句话定位:「CoolDesktop 是一个 Linux 服务器管理软件,采用全新的操作方式,让您像操作本地系统一样,操作远程 Linux」(README.md:3)。功能清单(README.md:5-31):仿操作系统的多窗口 + 第三方软件加载卸载、文件复制粘贴剪切压缩解压、多终端、文件上传拖放、日志追踪、jar 一键启停、文件分享链接、开发自定义管理软件;软件商店提供图片查看器、文件编辑器、系统监视器、Java 进程管理器(可热替换、GC、在线反编译内存中的 class)。
+
+所以它的用户画像是「个人 Linux 服务器(尤其是 Java 应用服务器)的运维者」,形态是把 Web 版服务器管理面板做成操作系统的样子。它面向的是一台自己有 root 权限的服务器,而不是企业级多人托管场景。
+
+### 1.2 部署形态
+
+install.sh 展示了官方部署路径:root 身份运行,创建 /opt/cooldesktop 目录,从 cool_sum.txt 里取 jar 的 sha1 与下载地址做循环下载校验(install.sh:20-36),生成 systemd 服务文件,`User=root`、`ExecStart= -jar cooldesktop.jar`(install.sh:39-53)。cool_sum.txt 就是一行「sha1 + URL」(cool_sum.txt:1)。README 说明默认端口 2556,浏览器直接访问(README.md:68),首次登录默认密码 `cooldesktop`(README.md:75-80)。
+
+desktop-startup 模块的 Startup.java 是另一个启动入口:定位自身目录下的 `/cooldesktop/CoolDesktop.jar`,JDK 版本低于 11 时改用随包分发的 `/jre`,然后 ProcessBuilder 起子进程并把输出重定向到日志文件(Startup.java:36-49)。配套的 desktop-web/build.gradle.kts 里有一个 `install` 任务,用 jlink 裁剪出精简 JRE 到 bin/jre(desktop-web/build.gradle.kts:20-36),即官方发布物是「启动器 + fat jar + 精简 JRE」三件套。
+
+一个值得注意的约束:Application.kt 的 main 里检查 `os.name`,非 Linux 直接 error 退出(Application.kt:33-41)——它是纯服务端 Linux 程序,Windows 只能用于开发调试。
+
+### 1.3 模块职责与协同
+
+settings.gradle.kts 声明 8 个模块(settings.gradle.kts:1-9)。协同关系很直接:desktop-web 是唯一产出 fat jar 的聚合模块,依赖 desktop-file / desktop-loader / desktop-database / desktop-websocket / desktop-system 五个业务模块(desktop-web/build.gradle.kts:5-9),而所有模块都依赖 desktop-common(根 build.gradle.kts:96-97)。desktop-startup 只是启动器,不进 Spring 世界。
+
+各模块职责按源码归纳:
+
+- desktop-common:常量、Directory(工作目录布局)、日志抽象、通用模型(FileHandlerResult/Page/HttpResponseBody)与 Kotlin 扩展。没有业务。
+- desktop-database:H2 文件库 + JdbcTemplate 薄封装,4 张表(sys_config / app_properties / sys_log / share_file_map,CooldesktopDatabaseTablInitialization.kt:18-27),庘认证都没配(CoolDesktopDatabaseConfig.kt:20)。
+- desktop-file:文件域全部能力(浏览、上传下载、压缩解压、文本编辑、图标缩略图、分享链接、jar 启停、tail 入口),服务接口 IFileService.kt:12-68 一个接口全覆盖。
+- desktop-loader:第三方应用热加载(见第 2 节),依赖 desktop-file 的目录扩展与 desktop-system 的资源注册。
+- desktop-system:系统能力中枢——终端(pty4j)、tail、命令模板、通知与审计 AOP、壁纸、SSH 密钥管理、Spring 动态注册器(bean / RequestMapping / 静态资源)、分享下载 Servlet。
+- desktop-websocket:STOMP 事件通道 + 终端原生 WebSocket 的接线层,业务不多,主要是两个 Configurer 和两个 Action。
+- desktop-web:Spring Boot 主应用,控制器薄层(应用管理 API / 文件 API / 系统 API / 应用静态资源),聚合打包。
+
+### 1.4 两个非常规的构建决策
+
+根 build.gradle.kts 有两处决策影响了对这个项目的理解,值得单独说。
+
+第一,它排除了官方 spring-boot 与 spring-webmvc 依赖,改用作者自编译的 jar(build.gradle.kts:77-81 排除,:105/:108 引入 desktop-lib 下的 spring-boot-2.6.1.jar 与 spring-webmvc-5.3.20-SNAPSHOT.jar),注释说明是为了配合魔改。这属于深度魔改框架的路径,构建强依赖作者本机路径(build.gradle.kts:38-51 的 copyLib 任务从 `/home/HouXinLin/projects/java/...` 拷 jar),换环境不可复现。
+
+第二,`compileOnly("org.apache.tomcat.embed:tomcat-embed-core:9.0.58")` + `runtimeOnly(files("desktop-lib/tomcat-embed-core.jar"))`(build.gradle.kts:101-102),注释明说「tomcat 为二次开发的 jar,主要功能全局拦截,进行登录」。desktop-lib/tomcat-embed-core.jar 里确实有 TomcatGlobalAuthenticationValve、TomcatGlobalAuthenticationHttpServlet(含 IPLimitTask 内部类)、TomcatShareFileHttpServlet 等自研类(unzip -l 实测类清单),源码不在本仓。认证(第 6 节)整个建立在这个闭源 jar 上。
+
+## 2. 桌面/画面从哪来:没有真实桌面,只有 Web 桌面壳
+
+这是本次调研最重要的一条定性结论:**cooldesktop 与真实桌面采集无关**。
+
+取证方式是反向验证:对全仓 .kt/.java/.kts/.properties 用 `xvfb|x11|xdotool|xauth|vnc|xrdp|wayland|java.awt.Robot|screenshot|Xvnc` 大小写不敏感搜索,命中数为 0。后端没有任何截屏、帧采集、显示服务器交互的代码。所谓「桌面」是浏览器里的一个 Vue 单页应用:壁纸、图标、任务栏、可拖拽多窗口都是 DOM,壁纸是用户上传后存在服务器的图片文件(CoolDesktopSystem.kt:66-79 changeWallpaper 上传到 ~/cooldesktop-work/config/wallpaper 并写库),经 /system/resource/wallpaper/** 静态映射返回(SystemResourceMvcConfigurer.kt:12-18)。桌面上的「文件快捷方式」只是把一组路径存进 H2 的 app_properties 表(CoolDesktopSystemController.kt:115-144),图标由服务端按文件类型返回 PNG(FileServiceImpl.kt:252-259,icon 资源就躺在 desktop-file/src/main/resources/static/icon/ 下)。
+
+因此它回答 7shell 的问题很明确:**「远程 Linux 主机的真实桌面画面」在这个项目里根本不存在,不存在可供借鉴的画面采集/编码/传输流水线。**
+
+### 2.1 desktop-loader 是干什么的
+
+desktop-loader 不是画面加载器,而是「第三方应用热加载器」——README 第 0 条「拥有加载、卸载第三方软件能力」的实现。应用分两类(ApplicationManager.kt:23-27):
+
+- **EASY_APP(jar 应用)**:一个普通 jar,内含 app.properties 描述文件(EasyApplicationLoader.kt:76)与若干 @Component 类。加载时用魔数识别(ApplicationTypeDetection.kt:14-16,`PK\x03\x04` 即 ZIP/JAR 魔数),读 app.properties 校验必填项与最低系统版本(EasyApplicationLoader.kt:163-179, 205-213),创建支持「jar 套 jar」的类加载器——复用 Spring Boot loader 的 JarFile/嵌套 URL(EasyApplicationLoader.kt:215-229,ApplicationClassLoader 直接继承 LaunchedURLClassLoader,ApplicationClassLoader.kt:6-8)——然后扫描 @Component 类注册进运行中的 Spring 容器(EasyApplicationLoader.kt:234-265),CoolDesktopBeanRegister 用 defaultListableBeanFactory.registerBeanDefinition 动态注册/销毁(CoolDesktopBeanRegister.kt:30-67),并做了一个类加载器身份校验防两个应用同包名互踩(CoolDesktopBeanRegister.kt:54-58)。Controller 注册由自定义 RequestMappingRegister 完成,它会自动给应用的每个 mapping 加 `/{applicationId}` 前缀并支持动态反注册(RequestMappingRegister.kt:54-68)。卸载时依次调用应用的可选 uninstall 方法、销毁 bean、反注册 Controller、删 jar 文件(EasyApplicationLoader.kt:141-157)。
+- **WEB_MINI_APP(web 应用)**:自定义二进制格式 `.webapp`:4 字节魔数(0x007913E)+ 4 字节 JSON 头长度 + JSON 应用描述 + 静态资源包(FilePackage 表,WebMiniApplicationLoader.kt:40-52),staticResOffset 指向资源区。运行时按路径查资源表、带内存缓存返回(WebMiniApplicationWrapper.kt:14-22),HTTP 入口是 `/desktop/webapplication/{applicationId}/**`(WebApplicationResourceController.kt:35-49),用 Tika 探测 Content-Type。本质上是「前端页面打包成单文件、后端代管静态资源」的最小 Web 应用。
+- **AloneApplicationLoader**:一个空壳,注释「预留」(AloneApplicationLoader.kt:7-16),推断是给独立进程/独立 Tomcat 应用预留的扩展点,未实现。
+
+安装分发走 ApplicationInstallDispatcher:按字节魔数选 loader(ApplicationInstallDispatcher.kt:52-59);在线安装走 ApplicationDownloadManager 的单线程安装队列 + InstallStep 流水线(下载 → 安装 → 通知客户端刷新),每步进度经 STOMP 推到浏览器(ApplicationDownloadManager.kt:63-74, 105-115)。软件商店服务端地址存在 H2 配置里,默认 cool.properties 写死 http://www.houxinlin.com:8081(cool.properties:1)。
+
+应用与主程序的交互面是 desktop-lib 里另一个闭源 jar desktop-application-definition-1.0-SNAPSHOT.jar(Application/EasyApplication/WebMiniApplication/ApplicationLoader 接口定义,unzip 类清单实测)+ cooldesktop-application-event-definition jar(ApplicationInteractive/ApplicationMessagePublish 生命周期与消息接口,EasyApplicationLoader.kt:8-11 import)。客户端打开/关闭应用的事件从 STOMP 进来(CooldesktopMessage.kt:16-20),转发给 jar 应用的 onOpen/onClose(ApplicationManager.kt:45-60)。
+
+## 3. 传输与渲染
+
+### 3.1 双 WebSocket 通道
+
+**STOMP over SockJS(事件与通知)**:端点 /desktop-socket-endpoint,simple broker 前缀 /desktop-topic,客户端发送前缀 /desktop(DesktopWebSocketConfigurer.kt:19-23)。广播主题枚举集中在 Constant.WebSocketSubjectNameConstant,共 12 个:文件夹刷新、安装进度、文件事件、终端消息、壁纸刷新、应用刷新、打开目录、压缩结果、成功/错误通知、应用消息推送、shell 执行结果、分享链接刷新(Constant.kt:43-57)。消息体是 JSON map:`{subject, action, ...任意键值}`(WebSocketMessageBuilder.kt:7-28)。客户端到服务端只有一个 @MessageMapping("/event"),用于开/关应用(CooldesktopMessage.kt:16-20)。订阅/断开事件由 WebSocketEventListener 按 destination 分发给 IStompSubjectAction 实现(WebSocketEventListener.kt:27-57)。
+
+服务端推送统一收敛在 CoolDesktopEventAction.send:无人订阅时进离线队列(上限 5 条,满了直接丢弃)、有订阅者时 convertAndSend 到 /desktop-topic/event;另有一条 DelayQueue 线程做延迟发送;最后一个客户端断开时 TailManager.stopAll() 清理所有日志追踪(CoolDesktopEventAction.kt:32-77)。
+
+**终端专用原生 WebSocket(非 STOMP)**:/ws/websocket/terminal,TextWebSocketHandler,连接建立即创建终端、断开即销毁、消息原文写入 PTY(XterminalWebSocketConfigurer.kt:20-34)。注意它 setAllowedOrigins("*")(XterminalWebSocketConfigurer.kt:34),且用 TextMessage 而非 BinaryMessage 回传(SshMessageListener.kt:8-12)——终端输出(含 ANSI 转义序列)以 UTF-8 文本帧直通前端,前端 xterm.js 渲染。没有压缩、没有帧率控制——文本终端天然不需要。
+
+### 3.2 异步任务与推送的通用模式
+
+长耗时文件操作(粘贴、压缩、解压)的接口设计是「提交即返回 taskId,结果用 WebSocket 推」:FileServiceImpl 的这些方法都挂在 @NotifyWebSocket 注解下,AOP 在方法返回/抛异常后自动把结果转成 JSON 推给客户端(CoolDesktopNotifyWebSocketAspect.kt:39-68,注解用法见 FileServiceImpl.kt:78, 280, 302)。前端拿到 taskId 与主题后做进度刷新。这个模式在这个项目里被反复使用,是最成熟的工程习惯。
+
+### 3.3 前端在哪里、怎么渲染
+
+前端源码在独立仓库 houxinlin/cooldesktop-web(README.md:88-94,`npm run build` 后把 dist 拷进 desktop-web/src/main/resources/static/),本仓只有构建产物:index.html 引 sockjs.js 与两个 ES module bundle(static/index.html)。对产物 bundle 做关键词计数(index.60a4d698.js,634KB):xterm×58、drag×24、Stomp×10、iframe×8、SockJS×1。可以确认前端三件套:xterm.js 渲染终端、Vue 拖拽窗口管理器、Web 类应用用 iframe 内嵌(推断:iframe 标签出现于应用窗口宿主,配合 /desktop/webapplication/ 资源服务)。没有 canvas 绘图、没有视频流、没有像素级渲染——再次印证它是 DOM 桌面。
+
+## 4. 输入与交互
+
+### 4.1 不存在输入注入
+
+与画面采集的结论一致:cooldesktop 没有任何把鼠标键盘事件注入到 Linux 图形层的机制。xdotool/XTest/java.awt.Robot 在仓库里出现次数为零。「输入」只有两条通路:
+
+1. 终端键盘输入:前端 xterm.js 捕获按键 → WebSocket 文本帧 → TerminalSocketAction.onMessage → writeCommand 入队(TerminalSocketAction.kt:30-34)→ 消费线程写 PTY stdin(LinuxTerminal.kt:79-95)。
+2. Web 应用交互:全部是常规 HTTP API(文件操作、系统配置等),每个按钮背后是一个 REST 端点,不存在「模拟桌面事件」。
+
+### 4.2 终端尺寸同步协议
+
+前端窗口变化时通过两条约定消息同步(LinuxTerminal.kt:55-63, 84-86):`INIT_HOME_TERMINAL:` 设定初始目录并放行 PTY 创建(waitInit CountDownLatch,LinuxTerminal.kt:25, 56-59, 66);`setSize` 前缀消息携带 col/row/w/h 四个定长 4 位数字段,服务端按固定下标切割解析后设 WinSize(LinuxTerminal.kt:45-52)。这套协议能用但很脆:列数超过 9999、或某个数字段不足 4 位都会解析错乱;用魔数前缀字符串而不是结构化消息,属于这个项目里比较粗糙的部分。
+
+### 4.3 窗口管理
+
+多窗口、最大化/最小化、拖拽全部在前端 Vue 里实现(产物 bundle 的 drag 关键词与 README.md:5 的功能声明),后端不参与窗口状态管理,推断窗口布局不持久化。后端参与的只有两类「窗口级」数据:桌面快捷方式列表(存 H2,CoolDesktopSystemController.kt:115-144)和每个应用窗口对应的 API 前缀/资源前缀隔离(/{applicationId}/)。文件拖放上传是前端分片调 chunk/upload(README.md:13「上传文件托放既可完成」+ StaticResourceController.kt:186-190)。
+
+### 4.4 服务端文件剪贴板
+
+「复制/剪切/粘贴」是服务端单条目全局单例:ClipboardManager 只记一个 memoryFilePath + 一个 actionCommand(copy/cut/none)(ClipboardManager.kt:10-15),粘贴时 copyRecursively 或 copy 后删源(ClipboardManager.kt:50-74)。没有任何用户/会话维度隔离,两个浏览器标签页会互相覆盖剪贴板。
+
+## 5. 周边能力
+
+### 5.1 desktop-file:文件域全家桶
+
+IFileService.kt:12-68 一个接口定义了全部 22 个操作,REST 入口在 StaticResourceController(/desktop/api/file/**,StaticResourceController.kt:23-332)。几处有设计含量的实现:
+
+- **目录列表并发构建**:listDirector 对目录下每个条目提交线程池任务,CountDownLatch 整体等待 1 分钟上限,文件夹排前、文件排后(FileServiceImpl.kt:173-212)。HTTP 层面一个请求拿全量属性(FileAttribute 含大小/权限/类型),前端不用逐个请求。
+- **分片上传**:chunkUpload 预检目标存在性与读写权限 → 分片按 blobId 落盘到 fileupload/chunk/{chunkId}/ → 用「已落盘分片字节总和 == total」判断是否传完 → fileMergeLockMap + synchronized 保证只有一个线程合并 → 合并后删分片目录并经 WS 推 refresh 事件让前端刷新目录(FileServiceImpl.kt:129-168)。配套 fileMerge 独立接口(FileServiceImpl.kt:101-127)。单请求上限 25MB(application.properties:1-3)。
+- **压缩/解压**:zip/tar/7z 三种,实现在 compress 包(ZipCompress/TarCompress/SEVENZCompress, commons-compress + tukaani xz,根 build.gradle.kts:113-114),异步执行 + @NotifyWebSocket 推结果(FileServiceImpl.kt:280-319)。
+- **文本编辑**:getTextFileContent/setTextFileContent 直接读写(FileServiceImpl.kt:331-351),支撑「文件编辑器」应用。
+- **图标与缩略图**:Tika 探测类型(根 build.gradle.kts:125 引 tika-core),内置 40+ 个扩展名 PNG 图标,图片缩略图用 thumbnailator(FileServiceImpl.kt:217-259)。
+- **jar 一键启停**:runJarFile 先用 Attach API(com.sun.tools.attach.VirtualMachine,JarUtils.kt:6, 12-40)列 Java 进程、按 jar 路径过滤 pid,再 nohup java -jar 后台启动、轮询确认启动成功;stopJar 遇到同路径多进程会拒绝执行(FileServiceImpl.kt:364-386)。依赖 desktop-lib/tools.jar(根 build.gradle.kts:104),这是 JDK8 时代的 tools.jar 路径假设,运行端 JDK11+ 实际靠 jdk.attach 模块(jlink 打包用了 ALL-MODULE-PATH,desktop-web/build.gradle.kts:26-35)。
+- **文件分享链接**:createShareLink 用「路径 hashCode 逐位映射 + 随机字符」生成短 id,冲突则追加随机位,过期时间 1 天/7 天/10 年三档(FileServiceImpl.kt:414-443),下载走 /s/* 由魔改 Tomcat 转发到 CoolDesktopShareHttpServlet 免认证直出文件(SystemConfiguration.kt:41-58, CoolDesktopShareHttpServlet.kt:18-30),每天 12 点定时清理过期链接与 180 天前的审计日志(DatabaseScheduled.kt:18-23)。
+- **日志追踪(tail)**:tailStart 起一个 `bash -c tail -F -n 250 ` 进程逐行回调,输出推到按路径动态拼的主题 `/event/tail/$path`(FileServiceImpl.kt:396-407, Tail.kt:20-29)。
+
+### 5.2 desktop-system:终端、命令模板与横切面
+
+- **终端**:pty4j PtyProcess 起 /bin/bash(desktop-system/build.gradle.kts:10 依赖 pty4j 0.12.10),详见第 4 节。
+- **命令模板**:CommandConstant 枚举集中管理 ssh-keygen、nohup java -jar、kill -9、tail -F、netstat/lsof 查端口六条模板(CommandConstant.kt:5-11),CommandImpl 执行。这类「模板集中一处」的做法比散落各处拼字符串好维护,但模板本身硬编码了 netstat/lsof 等非 POSIX 必备命令。
+- **通知 AOP**:@NotifyWebSocket + CoolDesktopNotifyWebSocketAspect(第 3.2 节)。
+- **审计 AOP**:@LogRecord 注解 + LogRecordAspect @Before 切面,把控制器参数名与值序列化后写入 sys_log 表(LogRecordAspect.kt:37-58),所有敏感操作(删除、上传、重置密码、装软件)都挂了注解(StaticResourceController.kt 全篇、CoolDesktopSystemController.kt:40-137)。配合 getSystemLog 分页查询接口构成操作审计闭环(CoolDesktopSystemController.kt:151-158)。
+- **SSH 密钥管理**:configSecureShell 生成 PEM 密钥对(ssh-keygen -m PEM -b 2048,CommandConstant.kt:6),公钥追加到硬编码的 /root/.ssh/authorized_keys(CoolDesktopSystem.kt:59, 98-143),私钥/公钥/用户名存 H2 且被列为敏感配置不回传客户端(CoolDesktopSystem.kt:52-57)。**仓库内没有任何消费这三项配置的代码**,desktop-system/build.gradle.kts:7 声明的 jsch 依赖也没有任何 import(grep com.jcraft 命中 0 处源码)——推断这组功能是给「浏览器端/第三方应用直连 SSH」准备的半成品,或者消费者在前端闭源仓。README「所用语言及依赖」里列了 jsch(README.md:59),佐证原本规划过 SSH 直连终端。
+
+### 5.3 desktop-database 的角色
+
+就是一个零依赖的 H2 键值仓 + 日志表:无 ORM、无迁移框架、建表用 create table if not exists 的 CommandLineRunner(CooldesktopDatabaseTablInitialization.kt:18-27)、连接串不带认证(CoolDesktopDatabaseConfig.kt:20)。表只有四张(第 1.3 节)。它的价值不在技术含量,而在于示范了「桌面类单机产品用什么存配置/状态/审计」的最小方案。
+
+### 5.4 对 SSH 远程桌面场景的参考价值判断
+
+- 文件域:7shell 的 SSH 场景下传输通道大概率走 SFTP,cooldesktop 的「分片上传/HTTP 下载」协议本身用不上,但**分片校验、失败预检、异步任务 + WS 进度推送、目录并发枚举、图标/缩略图 UX** 都是可平移的交互设计。
+- 终端域:7shell 的终端应走 SSH channel(shell/exec)而非本地 pty4j,但 xterm.js + 文本帧直通 + resize 消息的三段式结构是通用模式;它的定长数字 resize 协议是反面教材,应换成结构化 JSON 或 doOnResize 语义消息。
+- tail 日志追踪:对 7shell 的「日志文件追踪」功能有直接参考价值,但按路径拼主题的做法要改(见坑清单)。
+- jar 进程管理:对「管理远程 Java 应用」的 7shell 用户是潜在功能,Attach API 要求管理进程与目标进程同机同用户,7shell 客户端在本地 Windows 上跑不了对远程主机的 Attach——这条路在 SSH 场景下不可行,只能靠远端脚本(它自己也是 nohup + bash,Attach 只用来查 pid,JarUtils.kt:27-30)。
+
+## 6. 安全模型
+
+### 6.1 认证:闭源魔改 Tomcat 全局阀
+
+认证不在 Spring Security,而是魔改 tomcat-embed-core:jar 内含 TomcatGlobalAuthenticationValve(9.3KB 主类)、TomcatGlobalAuthenticationHttpServlet(登录 Servlet,带 IPLimitTask/IpLimitMessage/IP 限流内部类)、TomcatGlobalAuthenticationPasswordUtils、TomcatShareFileHttpServlet(unzip desktop-lib/tomcat-embed-core.jar 类清单实测)。根 build.gradle.kts:100 注释「主要功能,全局拦截,进行登录」。登录页由 Tomcat 直接伺服(desktop-web/src/main/resources/tomcat/tomcat-index.html),密码框用 jsencrypt 做 RSA 加密提交(tomcat-index.html:5 引 jsencrypt.min.js)。
+
+TomcatCallback 用 MethodHandles 反射调用闭源 jar 的两个静态回调把 Tomcat 世界接回 Spring:登录结果写审计日志(TomcatCallback.kt:50-66)、分享下载 Servlet 注入(TomcatCallback.kt:31-40)。密码存 ~/cooldesktop-work/password.conf 明文(TomcatGlobalAuthenticationPasswordUtils.kt:12-33),重置时强制转大写(CoolDesktopSystem.kt:158-161),README 声明默认密码 cooldesktop(README.md:75-80)。
+
+免认证路径有两个:OpenUrlManager 维护的 URL 白名单(存文件 config/o_urls/config,OpenUrlManager.kt:11-42,应用安装时自动注册 urlExclude,ApplicationManager.kt:72);/s/* 分享下载路径(SystemConfiguration.kt:47 注释「生产环境中由 tomcat 负责转发……免除认证」)。
+
+### 6.2 WebSocket 层零鉴权
+
+STOMP 握手的 determineUser 直接发随机 UUID 当 Principal(DesktopWebSocketConfigurer.kt:28-34),STOMP 消息处理不校验任何身份;终端 WS allowedOrigins("*")。整个 WS 面的安全性完全依赖 HTTP 层的 Tomcat Valve 把没有登录 Cookie 的握手请求拦在门外(推断:Valve 是全局的,SockJS 握手走 HTTP,未登录者连不上;登录后的 WS 会话无二次鉴权,任何已登录页面可以全量订阅所有主题)。没有按用户的主题隔离——广播语义本来也是「单管理员」假设。
+
+### 6.3 会话与权限模型
+
+单用户、单管理员、无角色权限分级。服务进程 root 运行(install.sh:45 User=root),文件 API 可以读写任意路径(只有 canRead/canWrite 检查,FileServiceImpl.kt:261-263),shell 执行接口直接跑任意脚本(StaticResourceController.kt:100-103)。这不是疏忽而是产品定位——它就是给有 root 的人用的管理工具。多用户隔离、容器隔离在这个项目里都不存在;唯一的「隔离」手段是魔改 Valve 的 IP 限流(防止爆破登录)。
+
+值得记录的一个防御性细节:系统配置接口对敏感 key(SSH 私钥/公钥/用户名)做了「不返回、不允许直接写」的双向过滤(CoolDesktopSystem.kt:52-57, 81-85)。
+
+## 7. 与 7shell 需求的匹配度分析
+
+7shell 的需求:通过 SSH 连接到一台 Linux 主机,查看并操作它的**真实桌面**。逐条对照:
+
+**根本不匹配的部分(先说清楚,避免错位借鉴):**
+
+- **画面层零匹配**。7shell 要的是 X11/Wayland 桌面的像素级渲染(截屏轮询或视频流),cooldesktop 对此没有任何实现——它的「桌面」是浏览器 DOM 自绘的应用壳(第 2 节)。想在 7shell 的桌面渲染上从它借鉴编码/传输/渲染技术,是没有东西可拿的。
+- **承载通道不匹配**。cooldesktop 的所有流量(HTTP API + SockJS + WS)都是浏览器直连服务端 TCP 端口,没有 SSH 承载、没有隧道适配、没有对 NAT/防火墙场景的考虑(install.sh 直接在服务器上开 2556 端口)。7shell 若复用其协议,等于要自己补上「把 HTTP/WS 塞进 SSH 通道」的整层。
+- **部署模型不匹配**。目标机要装 JDK 11+、root systemd 常驻 Spring Boot + H2(install.sh:39-53),这套依赖重量级且侵入宿主机。7shell 的 SSH 场景理想状态是零部署或一个轻量远端 agent;把 cooldesktop 整套搬过去显然不成立。它的部分能力(pty4j、thumbnailator、H2)甚至要求目标机有 Java 环境——7shell 的远端不能假设有 Java。
+- **单用户 root 假设**。无多用户、无权限分级、全局单例剪贴板、WS 无鉴权(第 6 节)。7shell 若做多人/多连接管理,这套模型不能沿用。
+
+**可对齐的部分(客观判断,按价值排序):**
+
+1. **消息协议骨架**:STOMP 主题 + JSON 消息体(subject/action/payload 三元组,WebSocketMessageBuilder.kt:7-28)+ 服务端推送收敛点(CoolDesktopEventAction.send 统一入口)+ 离线缓冲(5 条上限)+ 延迟发送 + 全员断开清理(CoolDesktopEventAction.kt:32-77)。7shell 桌面会话的消息路由(画面帧、窗口事件、剪贴板、通知)可以采用同构设计——主题分层、单一发送入口、断线清理钩子,这些和画面流是正交的。
+2. **「提交任务 + WebSocket 推结果」的异步模式**:@NotifyWebSocket AOP 把「异步任务完成通知」做成声明式(CoolDesktopNotifyWebSocketAspect.kt:39-68),接口层提交即返回 taskId(StaticResourceController.kt:176-181)。7shell 的文件传输、压缩、长命令等耗时操作可沿用这个 UX 形态(实现上不用 AOP,7shell 是 Tauri 客户端不是 Web)。
+3. **文件管理器交互设计**:目录一次请求全量属性 + 并发构建(FileServiceImpl.kt:173-212)、类型图标 + 缩略图(FileServiceImpl.kt:217-259)、服务端剪贴板语义(copy/cut/paste 三命令,ClipboardManager.kt)、分片上传的完整性校验与合并锁(FileServiceImpl.kt:129-168)。这些 UX 决策对 7shell 的 SFTP 文件管理界面有直接参考意义,只是传输通道换成 SFTP。
+4. **终端链路结构**:xterm.js(前端渲染)+ 文本帧直通 ANSI(传输)+ PTY(后端)三段式,以及断开即销毁终端的会话生命周期(XterminalWebSocketConfigurer.kt:20-34, TerminalSocketAction.kt:36-40)。7shell 的 SSH 终端等价物是 xterm.js + SSH shell channel,结构同构。
+5. **操作审计**:@LogRecord 声明式审计 + H2 分页查询 + 定期清理(LogRecordAspect.kt:37-58, DatabaseScheduled.kt:18-23)。7shell 若要「连接内操作记录」功能,这是最简参考实现。
+6. **应用加载器思路**(仅在未来 7shell 做插件生态时有参考价值):魔数识别应用类型、类加载器隔离、动态 bean/Controller 注册与反注册、按应用 id 加 URL 前缀隔离(第 2.1 节)。这个子系统复杂度高、闭源 jar 依赖多,7shell 短期不建议碰,但它证明了「单 JVM 内热插拔 Web 应用」在 Spring Boot 上可行。
+
+**总体判断**:cooldesktop 与 7shell「Linux 桌面」需求的关系是「同为 Linux 远程管理工具,交互范式相近,但核心渲染技术线不同」。它验证了「Web 桌面壳 + 应用生态」这条路(值得学习交互与协议组织),不能提供「真实桌面画面传输」的任何经验。7shell 的画面采集/编码/传输需要参考的是 noVNC、xrdp、RustDesk、KasmVNC 这一类项目,cooldesktop 只能贡献外围(文件、终端、协议组织、审计)。
+
+## 8. 精华点与坑/局限清单
+
+### 8.1 精华点(值得学)
+
+1. **统一推送收敛 + 离线缓冲 + 断线清理**:所有服务端推送走 CoolDesktopEventAction.send 单点;无订阅者时最多缓冲 5 条,订阅建立即冲刷;最后一个客户端断开时停掉所有 tail 进程(desktop-websocket/.../CoolDesktopEventAction.kt:32-77)。防推送风暴、防资源泄漏两个问题一起解决。
+2. **声明式 WebSocket 通知**:方法上挂 @NotifyWebSocket(subject=..., action=...),AOP 自动把返回值/异常转成 JSON 推给前端,业务代码零侵入(desktop-system/.../CoolDesktopNotifyWebSocketAspect.kt:39-68;用法示例 desktop-file/.../FileServiceImpl.kt:78)。耗时操作「提交即返回 + 推送收尾」的 UX 全项目一致。
+3. **运行中 Spring 容器的应用热插拔**:自定义类加载器支持嵌套 jar(desktop-loader/.../EasyApplicationLoader.kt:215-229)、@Component 扫描注册进 defaultListableBeanFactory(同文件 234-265)、Controller 动态注册并自动加 /{applicationId} 前缀实现多应用路由隔离(desktop-system/.../RequestMappingRegister.kt:54-68)、卸载链完整(uninstall 方法 → 销毁 bean → 反注册 mapping → 删文件,EasyApplicationLoader.kt:141-157)、类加载器身份校验防同包名冲突(CoolDesktopBeanRegister.kt:54-58)。
+4. **自定义二进制应用分发格式**:4 字节魔数区分类型(webmini 0x007913E / easyapp PK\x03\x04,ApplicationTypeDetection.kt:8-18),.webapp 格式「魔数 + JSON 头长度 + JSON + 资源 FilePackage」单文件分发带偏移定位(WebMiniApplicationLoader.kt:40-52),服务端按需解包 + 内存缓存(WebMiniApplicationWrapper.kt:14-22)。
+5. **分片上传的并发安全合并**:目标存在性预检 → 分片落盘 → 「字节总和 == total」判完整 → ConcurrentHashMap 锁对象 + synchronized 单线程合并 → 合并后即清锁删目录(FileServiceImpl.kt:129-168)。并发上传同一文件时只有一个线程执行合并,其余直接返回。
+6. **审计与通知双 AOP 横切面**:@LogRecord 在方法执行前记录参数到 sys_log(LogRecordAspect.kt:37-58),参数按类型分派转换器(MultipartFile 只记文件名等),配合每天 12 点的过期清理定时任务(DatabaseScheduled.kt:18-23)形成最小审计闭环。
+7. **敏感配置双向过滤**:SSH 密钥等 key 既不返回给客户端也不允许通过配置接口写入(CoolDesktopSystem.kt:52-57, 81-85),接口层显式白名单思维。
+8. **全局认证阀 + 免认证白名单**:认证收敛在 Tomcat Valve 一层,业务代码完全无感;需要免认证的路径走显式白名单注册(OpenUrlManager.kt:11-42、ApplicationManager.kt:72),还带登录 IP 限流(desktop-lib/tomcat-embed-core.jar 内 IPLimitTask 类)。
+
+### 8.2 坑与局限(值得避)
+
+1. **认证核心闭源、构建不可复现**:魔改 Tomcat 与应用定义 jar 都是仓库外预编译产物(desktop-lib/*.jar),copyLib 任务硬编码作者本机路径(build.gradle.kts:38-51),离开作者机器无法完整构建;安全审计只能靠反编译闭源 jar。
+2. **密码明文落盘 + 重置强制大写**:password.conf 明文存储(TomcatGlobalAuthenticationPasswordUtils.kt:27-33),重置入口 uppercase() 静默缩小密码空间且用户不知情(CoolDesktopSystem.kt:158-161);登录页 RSA(jsencrypt)只保护传输不保护存储。
+3. **WebSocket 层零鉴权 + 全开 CORS**:握手 Principal 是随机 UUID(DesktopWebSocketConfigurer.kt:28-34),STOMP/终端 WS 不做任何身份校验,终端端点 allowedOrigins("*")(XterminalWebSocketConfigurer.kt:34),安全性 100% 押在 HTTP Valve 兜底上;WS 一旦换成非 Tomcat 容器或加直连路径就裸奔。
+4. **SQL 字符串拼接**:sys_log 查询的条件构造器把参数直接拼进 SQL(`"$k=$v and "`、`'\'$value\''`,CoolDesktopDatabase.kt:104-143),logType/logLevel 来自请求参数(CoolDesktopSystemController.kt:151-158),存在注入面(H2 本地文件库 + 单管理员场景下危害有限,但模式不可取)。
+5. **终端 resize 协议脆弱**:`setSize` + 四个定长 4 位数字段按固定下标切割(LinuxTerminal.kt:45-52),超过 9999 列/行或字段位数不足即错乱;`INIT_HOME_TERMINAL:` 前缀魔法串与普通命令共用一条通道(LinuxTerminal.kt:55-61),没有转义保护——目录名里含该前缀会被误吞。
+6. **tail 主题直接拼用户路径**:`/event/tail/$path` 把任意文件路径编进 STOMP 主题(FileServiceImpl.kt:396-407),多客户端下主题互相可见且路径信息泄露给所有订阅者;路径变化(软链、重命名)也会让主题失效。
+7. **全局单例剪贴板**:服务端只存一份 (action, path)(ClipboardManager.kt:10-15),多标签页/多会话互相覆盖,且粘贴是异步的、复制状态无过期。
+8. **目录列表 1 分钟整体超时静默丢结果**:listDirector 的 CountDownLatch.await(1, MINUTES) 到点直接返回已收集部分(FileServiceImpl.kt:196-206),大目录(如 /proc 挂载点误入)下用户看到不完整列表却无任何提示。
+9. **环境硬编码**:/bin/bash、netstat/lsof/tail、/root/.ssh/authorized_keys 全部写死(CommandConstant.kt:5-11、CoolDesktopSystem.kt:59),非 glibc 发行版、精简容器镜像、非 root 用户场景直接失效;Application.kt 非 Linux 强制退出(Application.kt:33-41)。
+10. **H2 无认证无迁移**:jdbc:h2: 不带凭据(CoolDesktopDatabaseConfig.kt:20),建表靠 if not exists(CooldesktopDatabaseTablInitialization.kt:18-27),无版本迁移机制——表结构演进只能靠手工兼容。
+11. **SSH 密钥功能疑似半成品**:生成密钥写 authorized_keys、私钥入 H2(CoolDesktopSystem.kt:98-143),但仓库内无任何消费代码,jsch 依赖无 import(desktop-system/build.gradle.kts:7);照着学之前要先确认其设计意图。
+12. **前端闭源在独立仓**:本仓只有打包产物(README.md:88-94),窗口管理器实现细节(拖拽、快捷键、iframe 沙箱策略)无法在仓内核实,本报告第 3.3/4.3 节的前端结论均基于产物 bundle 关键词推断。
+
+## 9. 对 7shell 的可借鉴清单
+
+按「拿协议与思路、不拿代码与部署」的原则:
+
+1. **消息协议组织**:主题分层枚举 + JSON 三元组(subject/action/payload)+ 单一发送收敛点 + 离线缓冲上限 + 最后断开者触发资源清理(CoolDesktopEventAction.kt:32-77)。7shell 的桌面会话协议(画面帧通道、事件通道、控制通道)可以直接套这个骨架,把 STOMP 主题换成 SSH 多路复用 channel 或自定义帧类型。
+2. **耗时操作 UX**:提交即返回任务 id + 完成后推送结果 + 失败也推送(AOP 语义转成显式事件即可)(CoolDesktopNotifyWebSocketAspect.kt:39-68)。适用于 7shell 的文件传输、压缩、远程命令执行。
+3. **文件管理器交互**:目录一次拉全量属性、类型图标内置、图片缩略图服务端生成、copy/cut/paste 服务端状态机、分片完整性校验(FileServiceImpl.kt 各节)。通道换 SFTP 后这些 UX 设计原样成立;分片上传若 7shell 要做大文件断点续传,「字节总和判完整 + 合并锁」仍可参考。
+4. **终端三段式**:xterm.js + 文本帧直通 + 断开销毁的生命周期(XterminalWebSocketConfigurer.kt:20-34)。resize 必须用结构化消息(反向吸取 LinuxTerminal.kt:45-52 的教训),7shell 天然有 SSH pty-req resize 可用,不需要自定义协议。
+5. **审计闭环**:声明式操作日志 + 分页查询 + 定期过期清理(LogRecordAspect.kt:37-58、DatabaseScheduled.kt:18-23)。若 7shell 需要「会话操作记录」,照此最小实现即可。
+6. **安全设计正反面**:正面——认证收敛在单一拦截层、免认证路径显式白名单、敏感配置不回传(OpenUrlManager.kt:11-42、CoolDesktopSystem.kt:52-57);反面——WS 层必须自带鉴权不能押注 HTTP 中间件(DesktopWebSocketConfigurer.kt:28-34 是教训)、密码不能明文落盘(TomcatGlobalAuthenticationPasswordUtils.kt:27-33 是教训)。
+7. **不碰的部分**:真实桌面画面采集/编码/传输(它没有)、Spring 容器热插拔应用(短期不值得)、二开 Tomcat 认证(7shell 不是 Web 服务)、目标机 Java 依赖(7shell 不能假设远端有 JDK)。
+
+---
+
+## 附:取证命令记录
+
+- 全仓桌面采集关键词反查:`grep -rniE "xvfb|x11|xdotool|xauth|vnc|xrdp|wayland|java\.awt\.Robot|screenshot|Xvnc" --include="*.kt" --include="*.java" --include="*.kts" --include="*.properties" .` → 0 命中。
+- 闭源 jar 类清单:`unzip -l desktop-lib/tomcat-embed-core.jar`(命中 TomcatGlobalAuthenticationValve/TomcatGlobalAuthenticationHttpServlet/TomcatShareFileHttpServlet 等)、`unzip -l desktop-lib/desktop-application-definition-1.0-SNAPSHOT.jar`。
+- jsch 消费者反查:`grep -rn "com.jcraft|JSch" --include="*.kt" --include="*.java" .` → 0 命中。
+- 前端产物关键词计数:对 assets/index.60a4d698.js 与 vendor.42559af5.js grep -oiE "xterm|SockJS|stomp|iframe|drag|getContext" 统计(第 3.3 节数据)。
+- 魔数解码:495934 = 0x007913E(webmini 自定义魔数)、1347093252 = 0x504B0304(PK zip 头,ApplicationTypeDetection.kt:8-18)。
diff --git "a/docs/\350\260\203\347\240\224\346\212\245\345\221\212/20261118-0017-linux\346\241\214\351\235\242\350\277\236\346\216\245-\350\260\203\347\240\224\346\212\245\345\221\212.md" "b/docs/\350\260\203\347\240\224\346\212\245\345\221\212/20261118-0017-linux\346\241\214\351\235\242\350\277\236\346\216\245-\350\260\203\347\240\224\346\212\245\345\221\212.md"
new file mode 100644
index 00000000..10e8f863
--- /dev/null
+++ "b/docs/\350\260\203\347\240\224\346\212\245\345\221\212/20261118-0017-linux\346\241\214\351\235\242\350\277\236\346\216\245-\350\260\203\347\240\224\346\212\245\345\221\212.md"
@@ -0,0 +1,64 @@
+# Linux 桌面连接:两项目调研综述与方向决策
+
+> 日期:2026-11-18。输入材料:[20261117-2356-cooldesktop-调研报告.md](20261117-2356-cooldesktop-调研报告.md)、[20261118-0007-product-research.md](20261118-0007-product-research.md)(两份均由子代理独立完成,主控抽查复核过承重结论)、7shell 仓内架构盘点(行号见第四节)。
+> 决策记录:2026-11-18 用户拍板——主线只做 Web 桌面工作台,真实桌面画面(像素流)不做,留待将来另立提案。
+
+## 一、最重要的一致发现
+
+两个参考产品的「Linux 桌面」都不是远程桌面的像素流,这是本次调研最有价值的结论,直接决定了技术路线:
+
+- **the reference product(产品名「the product」)**:桌面是本地 Go 服务(the product service)托管的 Vue3 单页应用,Electron 用 webview 内嵌 `http://127.0.0.1:{gmPort}/newweb/#?...`;壁纸、图标、回收站、应用中心、任务管理器全部是前端画的桌面隐喻,数据经 SSH 到远端 `/.product-agent/` 下的 GA agent 取回。全部产物(JS、833 键语言文件、未 strip 的 Go 二进制)中 VNC/noVNC/X11 抓屏/H264/WebRTC 指纹计数为 0。
+- **cooldesktop**:连远端 agent 都没有——「桌面」就是浏览器里 Vue 自绘的窗口管理器壳(DOM 拖拽窗口 + iframe 内嵌 Web 应用 + xterm.js 终端),与远程主机的真实画面完全无关;全仓 grep 不到任何 X11/Xvfb/Wayland/VNC/截屏/Robot 痕迹(已做对照查询证伪搜索接口失效的可能)。
+
+这背后有一个产品现实:SSH 客户端的连接对象绝大多数是无头服务器,上面根本没有可渲染的桌面。「Linux 桌面」在这类产品里的真实含义是**一台主机的可视化管理工作台**,借用操作系统的隐喻组织文件、监控、终端和应用入口。
+
+## 二、两项目精华与反面教材
+
+按「正面学什么、反面避什么」浓缩(细节与行号证据见两份报告):
+
+| 来源 | 精华(可平移) | 反面教材(要避开) |
+|---|---|---|
+| the reference product | 桌面隐喻的文件/系统面板是「Linux 桌面」需求的低成本解法,比像素流便宜一个数量级,且对无头服务器同样可用;隧道四类型配「场景示例」的解释式 UX(本地 Navicat 连 3306 实际访问服务器 MySQL 这类文案);创建前端口占用预检;连接表单/分组树/跳板链/代理的字段模型;零知识云同步(本地加密后上传);凭据 AES 加密落盘分层 | 远端自动部署 GA agent(UPX 加壳、root 权限、`/.product-agent` 落盘);未开 AllowTcpForwarding 时自动备份并改写远端 sshd_config(即便带回滚也越权);主窗口 nodeIntegration: true;登录通道内嵌可提取的共享 RSA 私钥 |
+| cooldesktop | STOMP 主题分层 + JSON 三元组消息体 + 单一推送收敛点 + 离线缓冲 + 末位断开清理;「提交任务即返回 taskId + 完成后推送结果」的异步 UX;分片上传的完整性校验与合并锁;敏感配置双向过滤(不返回也不允许写) | 认证押在闭源魔改 Tomcat 上(构建不可复现);WS 层零鉴权 + allowedOrigins("*");密码明文落盘且重置强制大写;SQL 字符串拼接;终端 resize 用定长 4 位数字段按下标切割的脆弱协议 |
+
+与 7shell「Linux 桌面」画面采集直接相关的技术(X11 抓屏、帧编码、视频流),两个项目都没有——真实桌面画面若将来要做,参考对象应是 noVNC、xrdp、RustDesk 一类项目,这一点两份报告都已写明。
+
+## 三、与 7shell 架构的匹配分析
+
+7shell 的安全模型明确拒绝 the reference product 式的远端 footprint:不在用户主机上自动部署常驻 agent、不擅自改远端配置、无命令不上机(「commands nobody typed are a constant」)。好消息是,Web 桌面工作台恰好**不需要任何远端部署**:工作台要的每一类数据,7shell 现有面上全都有了,全部 rides 在用户已经打开的那条 SSH 连接上。
+
+现有资产盘点(行号为 2026-11-18 基线 f460da4 实测):
+
+| 工作台需要 | 现有资产 | 出处 |
+|---|---|---|
+| 操作系统标志与身份 | `session_system` 固定只读命令(uname/os-release)+ 前端图标映射 | docs/architecture.md「The system mark beside a session」;`lib/system/icons.ts` |
+| CPU/内存/网络/磁盘读数 | `monitor_sample` 单条固定命令采样 + 前端速率换算 | `crates/sevenshell-core/src/monitor.rs`;`lib/monitor/rates.ts` |
+| 文件浏览/传输 | SFTP 文件工作台 + 传输面板 | `sevenshell-sftp`;`components/files/` |
+| 终端入口 | 同一连接上的终端 tab | `stores/terminals.ts:822`(open outcome 挂终端 tab) |
+| 跳板/端口转发 | 路由逐跳验证 + forwards 随会话拉起 | docs/architecture.md「Routes and forwards」 |
+| 主机密钥信任流 | 探测 → 决策 → 重验,与普通 SSH 完全一致 | docs/security-model.md 不变量 2/3 |
+
+后端足迹因此极小:新增一个协议身份 + 前端一个工作台面板,核心复用。协议匹配点全仓清点过——Rust 侧按协议分派的位置只有 `crates/sevenshell-core/src/sessions.rs:211`(终端开启分派)与 `:395`(流式终端守卫)两处需要接新变体,其余对协议的比较(`files.rs:353/356` 的 WebDAV/FTP 特判、`sevenshell-api` 的 container 特判等)不命中新协议即自动落到 SSH 路径,正是想要的行为。编译器会兜住一切非通配 match;通配 match 与 `==` 比较的扫查已列入开发计划第一项任务。
+
+前端落点同样收敛:`WorkspaceTab` 联合类型在 `stores/terminals.ts:251`,连接后的默认开签在 `:822-828`,协议选择器分组在 `components/sessions/SessionDialog.vue:94-99`(desktop 分组现只有 rdp)。归档提交 c981da4 曾建过嵌入式 RDP 引擎的 `desktop` tab 形态(tab kind + 面板组件 + i18n 域 + Tauri 裸字节帧通道),其骨架结构可作为接线参考——但工作台不画像素,帧通道那套不需要恢复。
+
+## 四、方向决策记录
+
+2026-11-18 用户在三个选项中拍板:**只做 Web 桌面工作台**(与两个参考项目对齐,范围最紧、风险最小),真实桌面画面留待将来另立提案。被放弃的两条路线的证据保留如下,避免将来重复调研:
+
+- **真实桌面画面(VNC/RFB over SSH + canvas 渲染)**:技术上可行——7shell 已有 SSH 通道承载任意 TCP 服务的能力(k8s CONNECT 桥、端口转发),归档引擎 c981da4 证明过进程内 canvas + 批量脏矩形 + 输入回传的完整形态;但仅对装了桌面环境的主机有意义(x11vnc 等),且 RFB 客户端或远端抓屏 helper 都是不小的实现量。将来若立项,从 noVNC/xrdp/RustDesk 与归档引擎两头取材。
+- **混合先行(工作台 + 真桌面分期)**:即「两期都做」,用户未选;如方向变化按本节证据重启即可。
+
+## 五、命名与形态定案
+
+- 协议 id:`linuxDesk`;Rust 变体 `LinuxDesk`;标签 `protocol.linuxDesk.label`=「Linux 桌面」(英文 "Linux desktop")。
+- defaultPort 22(底层就是 SSH 连接)、runtime `native`、transport `tcp`、supportLevel `connect`;能力面先照抄 ssh.yaml 中它真正兑现的子集(shell/exec/resize/keepalive/hostMetrics/sftp/scp/jumpHost/forwarding/dynamicForwarding/recording),另加一个新能力 `workbench`(desktop 组)标记「该协议开工作台面板」,供前端定默认 tab 与将来的 agent 工具面使用。agentForwarding 不声明——工作台用不到,不 honest 的能力不写。
+- 前端:新 tab kind `workbench`,面板组件 `WorkbenchPane.vue`,i18n 域 `workbench.json`(en + zh-CN 双份,`pnpm check:i18n` 把关);linuxDesk 会话连接后默认挂工作台 tab,终端/文件/监控页仍可从工作台进入,共用同一条连接。
+- 会话模型不加新字段:linuxDesk 复用 Session 的 host/port/user/auth/jump/forwards,不需要 vault schema 升版(wire 测试补 LinuxDesk 夹具验证序列化即可)。
+
+## 六、引用
+
+- [20261117-2356-cooldesktop-调研报告.md](20261117-2356-cooldesktop-调研报告.md)(子代理产出,243 行,带文件:行号出处与取证命令附录)
+- [20261118-0007-product-research.md](20261118-0007-product-research.md)(子代理产出,271 行,asar 解包静态逆向,解包副本在 F:\tmp\7shell-research\product-asar)
+- 7shell 侧关键盘点:docs/architecture.md(Remote desktops / Routes and forwards / The host monitor)、docs/security-model.md(不变量表)、crates/sevenshell-core/src/sessions.rs:204-402、apps/desktop/src/stores/terminals.ts:251-848
+- 开发计划:[20261118-0019-linux桌面工作台-开发计划.md](../开发计划/20261118-0019-linux桌面工作台-开发计划.md)
From ecbd407d80fca254c32f228b72648ff7f4d445d0 Mon Sep 17 00:00:00 2001
From: SongRenShuo <3064597532@qq.com>
Date: Wed, 18 Nov 2026 01:50:42 +0800
Subject: [PATCH 003/440] feat(descriptors): the Linux desktop workbench
session
A new protocol, linuxDesk, is an SSH session whose front page is the
desktop workbench. It is the reference study's answer to "show me that
machine": most SSH targets are headless servers with no desktop to stream,
so the feature is a workbench over the surfaces the connection already
carries, not a stream of screen pixels.
- descriptors: the linuxDesk protocol and the `workbench` capability it
claims; generated manifest and TypeScript tables
- sessions: the workbench session opens through the SSH open path unchanged
(credential, host-key probe, decision, re-verify, authenticate); the
stream-terminal path names it among the transports it never sees
- types: WorkbenchSettings (the session's workbench backdrop choice) and
WorkbenchPowerOutcome ride the wire; camelCase guard covers both
- vault: schema 13 - an older build would drop the backdrop on its next
write, so the version moves; every session fixture carries the field
- i18n: protocol and capability labels in both locales
The dispatch point is compiler-guarded: removing linuxDesk from the SSH arm
fails the build with E0004 (probe verified, both readings on file).
---
.../src/i18n/locales/en/capability.json | 3 ++
.../desktop/src/i18n/locales/en/protocol.json | 3 ++
.../src/i18n/locales/zh-CN/capability.json | 3 ++
.../src/i18n/locales/zh-CN/protocol.json | 3 ++
apps/desktop/src/types/generated/protocols.ts | 12 ++++++
crates/sevenshell-core/src/batch.rs | 1 +
crates/sevenshell-core/src/desktop.rs | 1 +
crates/sevenshell-core/src/k8s.rs | 1 +
crates/sevenshell-core/src/sessions.rs | 7 +++-
crates/sevenshell-core/tests/ftp_files.rs | 1 +
crates/sevenshell-core/tests/live_batch.rs | 1 +
.../tests/live_channel_budget.rs | 1 +
.../sevenshell-core/tests/live_connection.rs | 1 +
.../sevenshell-core/tests/live_container.rs | 1 +
.../tests/live_container_files.rs | 1 +
crates/sevenshell-core/tests/live_files.rs | 1 +
crates/sevenshell-core/tests/live_k8s.rs | 1 +
.../sevenshell-core/tests/live_k8s_via_ssh.rs | 1 +
crates/sevenshell-core/tests/live_monitor.rs | 1 +
.../sevenshell-core/tests/live_pod_files.rs | 1 +
crates/sevenshell-core/tests/live_scp.rs | 1 +
crates/sevenshell-core/tests/live_system.rs | 1 +
crates/sevenshell-core/tests/webdav_files.rs | 1 +
crates/sevenshell-sync/src/snippets.rs | 1 +
crates/sevenshell-sync/tests/live_sync.rs | 1 +
crates/sevenshell-sync/tests/round_trip.rs | 1 +
crates/sevenshell-types/src/lib.rs | 2 +-
crates/sevenshell-types/src/session.rs | 40 +++++++++++++++++++
crates/sevenshell-types/tests/wire.rs | 37 +++++++++++++++++
crates/sevenshell-vault/src/document.rs | 10 +++--
crates/sevenshell-vault/src/transfer.rs | 1 +
crates/sevenshell-vault/src/vault.rs | 1 +
descriptors/capabilities.yaml | 9 +++++
descriptors/descriptors.manifest.json | 31 ++++++++++++++
descriptors/protocols/linuxDesk.yaml | 31 ++++++++++++++
src-tauri/src/state.rs | 1 +
36 files changed, 209 insertions(+), 5 deletions(-)
create mode 100644 descriptors/protocols/linuxDesk.yaml
diff --git a/apps/desktop/src/i18n/locales/en/capability.json b/apps/desktop/src/i18n/locales/en/capability.json
index 0981e335..21a9eb0c 100644
--- a/apps/desktop/src/i18n/locales/en/capability.json
+++ b/apps/desktop/src/i18n/locales/en/capability.json
@@ -57,6 +57,9 @@
"systemClient": {
"label": "Opens in the system remote desktop client"
},
+ "workbench": {
+ "label": "Desktop workbench"
+ },
"container": {
"label": "Containers"
},
diff --git a/apps/desktop/src/i18n/locales/en/protocol.json b/apps/desktop/src/i18n/locales/en/protocol.json
index 1d8fdaea..9a3650da 100644
--- a/apps/desktop/src/i18n/locales/en/protocol.json
+++ b/apps/desktop/src/i18n/locales/en/protocol.json
@@ -6,6 +6,9 @@
"rdp": {
"label": "Remote desktop (RDP)"
},
+ "linuxDesk": {
+ "label": "Linux desktop"
+ },
"webdav": {
"label": "WebDAV"
},
diff --git a/apps/desktop/src/i18n/locales/zh-CN/capability.json b/apps/desktop/src/i18n/locales/zh-CN/capability.json
index 9aaf551d..d776caba 100644
--- a/apps/desktop/src/i18n/locales/zh-CN/capability.json
+++ b/apps/desktop/src/i18n/locales/zh-CN/capability.json
@@ -57,6 +57,9 @@
"systemClient": {
"label": "由系统远程桌面客户端打开"
},
+ "workbench": {
+ "label": "桌面工作台"
+ },
"container": {
"label": "容器"
},
diff --git a/apps/desktop/src/i18n/locales/zh-CN/protocol.json b/apps/desktop/src/i18n/locales/zh-CN/protocol.json
index 27d5f374..fc2eee07 100644
--- a/apps/desktop/src/i18n/locales/zh-CN/protocol.json
+++ b/apps/desktop/src/i18n/locales/zh-CN/protocol.json
@@ -6,6 +6,9 @@
"rdp": {
"label": "远程桌面(RDP)"
},
+ "linuxDesk": {
+ "label": "Linux 桌面"
+ },
"webdav": {
"label": "WebDAV"
},
diff --git a/apps/desktop/src/types/generated/protocols.ts b/apps/desktop/src/types/generated/protocols.ts
index 8c640817..19228dc9 100644
--- a/apps/desktop/src/types/generated/protocols.ts
+++ b/apps/desktop/src/types/generated/protocols.ts
@@ -4,6 +4,7 @@
export type ProtocolId =
| "ssh"
| "rdp"
+ | "linuxDesk"
| "webdav"
| "ftp"
| "telnet"
@@ -45,6 +46,7 @@ export type CapabilityKey =
| "keyMaterial"
| "platformAgent"
| "systemClient"
+ | "workbench"
| "container"
| "containerImages"
| "containerLogs"
@@ -105,6 +107,15 @@ export const PROTOCOLS: readonly ProtocolDescriptor[] = [
supportLevel: "connect",
capabilities: ["systemClient"],
},
+ {
+ id: "linuxDesk",
+ labelKey: "protocol.linuxDesk.label",
+ defaultPort: 22,
+ runtime: "native",
+ transport: "tcp",
+ supportLevel: "connect",
+ capabilities: ["shell", "exec", "resize", "keepalive", "hostMetrics", "sftp", "scp", "jumpHost", "forwarding", "dynamicForwarding", "recording", "workbench"],
+ },
{
id: "webdav",
labelKey: "protocol.webdav.label",
@@ -241,6 +252,7 @@ export const CAPABILITIES: readonly CapabilityDescriptor[] = [
{ key: "keyMaterial", group: "auth", labelKey: "capability.keyMaterial.label" },
{ key: "platformAgent", group: "auth", labelKey: "capability.platformAgent.label" },
{ key: "systemClient", group: "desktop", labelKey: "capability.systemClient.label" },
+ { key: "workbench", group: "desktop", labelKey: "capability.workbench.label" },
{ key: "container", group: "container", labelKey: "capability.container.label" },
{ key: "containerImages", group: "container", labelKey: "capability.containerImages.label" },
{ key: "containerLogs", group: "container", labelKey: "capability.containerLogs.label" },
diff --git a/crates/sevenshell-core/src/batch.rs b/crates/sevenshell-core/src/batch.rs
index bd8e9994..ea9eb5d6 100644
--- a/crates/sevenshell-core/src/batch.rs
+++ b/crates/sevenshell-core/src/batch.rs
@@ -468,6 +468,7 @@ mod tests {
auth: SessionAuth::with_password(AuthMethod::Password),
terminal: TerminalSettings::default(),
desktop: sevenshell_types::DesktopSettings::default(),
+ workbench: sevenshell_types::WorkbenchSettings::default(),
telnet: sevenshell_types::TelnetSettings::default(),
serial: sevenshell_types::SerialSettings::default(),
local: sevenshell_types::LocalSettings::default(),
diff --git a/crates/sevenshell-core/src/desktop.rs b/crates/sevenshell-core/src/desktop.rs
index a502a6ac..6c1567dd 100644
--- a/crates/sevenshell-core/src/desktop.rs
+++ b/crates/sevenshell-core/src/desktop.rs
@@ -252,6 +252,7 @@ mod tests {
auth: SessionAuth::with_password(AuthMethod::Password),
terminal: TerminalSettings::default(),
desktop: sevenshell_types::DesktopSettings::default(),
+ workbench: sevenshell_types::WorkbenchSettings::default(),
telnet: sevenshell_types::TelnetSettings::default(),
serial: sevenshell_types::SerialSettings::default(),
local: sevenshell_types::LocalSettings::default(),
diff --git a/crates/sevenshell-core/src/k8s.rs b/crates/sevenshell-core/src/k8s.rs
index a71714dc..ff9b9b24 100644
--- a/crates/sevenshell-core/src/k8s.rs
+++ b/crates/sevenshell-core/src/k8s.rs
@@ -333,6 +333,7 @@ mod tests {
auth: SessionAuth::with_password(AuthMethod::Password),
terminal: TerminalSettings::default(),
desktop: sevenshell_types::DesktopSettings::default(),
+ workbench: sevenshell_types::WorkbenchSettings::default(),
telnet: sevenshell_types::TelnetSettings::default(),
serial: sevenshell_types::SerialSettings::default(),
local: sevenshell_types::LocalSettings::default(),
diff --git a/crates/sevenshell-core/src/sessions.rs b/crates/sevenshell-core/src/sessions.rs
index 021c984f..b30f97e7 100644
--- a/crates/sevenshell-core/src/sessions.rs
+++ b/crates/sevenshell-core/src/sessions.rs
@@ -208,7 +208,10 @@ impl Core {
) -> Result {
let session = self.session(session_id)?;
match session.protocol {
- Protocol::Ssh => {}
+ // The workbench session is an SSH session in every mechanical sense: the open order —
+ // credential, host-key probe, decision, re-verify, authenticate — is the same order,
+ // and the only difference is the tab the interface mounts first.
+ Protocol::Ssh | Protocol::LinuxDesk => {}
Protocol::Rdp => {
return Err(ShellError::app_unsupported(
"this session is a remote desktop, not a terminal",
@@ -392,6 +395,7 @@ impl Core {
until_cancelled(sevenshell_term::open_wsl(spec, size), cancel).await?
}
Protocol::Ssh
+ | Protocol::LinuxDesk
| Protocol::Rdp
| Protocol::WebDav
| Protocol::Ftp
@@ -929,6 +933,7 @@ mod tests {
auth: SessionAuth::with_password(AuthMethod::Password),
terminal: TerminalSettings::default(),
desktop: sevenshell_types::DesktopSettings::default(),
+ workbench: sevenshell_types::WorkbenchSettings::default(),
telnet: sevenshell_types::TelnetSettings::default(),
serial: sevenshell_types::SerialSettings::default(),
local: sevenshell_types::LocalSettings::default(),
diff --git a/crates/sevenshell-core/tests/ftp_files.rs b/crates/sevenshell-core/tests/ftp_files.rs
index 4134fb8f..715f7c86 100644
--- a/crates/sevenshell-core/tests/ftp_files.rs
+++ b/crates/sevenshell-core/tests/ftp_files.rs
@@ -176,6 +176,7 @@ fn ftp_session(port: u16) -> Session {
auth: SessionAuth::with_password(AuthMethod::Password),
terminal: TerminalSettings::default(),
desktop: sevenshell_types::DesktopSettings::default(),
+ workbench: sevenshell_types::WorkbenchSettings::default(),
telnet: sevenshell_types::TelnetSettings::default(),
serial: sevenshell_types::SerialSettings::default(),
local: sevenshell_types::LocalSettings::default(),
diff --git a/crates/sevenshell-core/tests/live_batch.rs b/crates/sevenshell-core/tests/live_batch.rs
index 87ceeaa0..16238cca 100644
--- a/crates/sevenshell-core/tests/live_batch.rs
+++ b/crates/sevenshell-core/tests/live_batch.rs
@@ -58,6 +58,7 @@ fn lab() -> Option {
auth: SessionAuth::with_password(AuthMethod::Password),
terminal: TerminalSettings::default(),
desktop: sevenshell_types::DesktopSettings::default(),
+ workbench: sevenshell_types::WorkbenchSettings::default(),
telnet: sevenshell_types::TelnetSettings::default(),
serial: sevenshell_types::SerialSettings::default(),
local: sevenshell_types::LocalSettings::default(),
diff --git a/crates/sevenshell-core/tests/live_channel_budget.rs b/crates/sevenshell-core/tests/live_channel_budget.rs
index 9270d56e..c2bc98a0 100644
--- a/crates/sevenshell-core/tests/live_channel_budget.rs
+++ b/crates/sevenshell-core/tests/live_channel_budget.rs
@@ -56,6 +56,7 @@ fn lab() -> Option {
auth: SessionAuth::with_password(AuthMethod::Password),
terminal: TerminalSettings::default(),
desktop: sevenshell_types::DesktopSettings::default(),
+ workbench: sevenshell_types::WorkbenchSettings::default(),
telnet: sevenshell_types::TelnetSettings::default(),
serial: sevenshell_types::SerialSettings::default(),
local: sevenshell_types::LocalSettings::default(),
diff --git a/crates/sevenshell-core/tests/live_connection.rs b/crates/sevenshell-core/tests/live_connection.rs
index a71dfee5..214630bf 100644
--- a/crates/sevenshell-core/tests/live_connection.rs
+++ b/crates/sevenshell-core/tests/live_connection.rs
@@ -115,6 +115,7 @@ fn lab_with_session(password_override: Option<&str>) -> Option {
auth: SessionAuth::with_password(AuthMethod::Password),
terminal: TerminalSettings::default(),
desktop: sevenshell_types::DesktopSettings::default(),
+ workbench: sevenshell_types::WorkbenchSettings::default(),
telnet: sevenshell_types::TelnetSettings::default(),
serial: sevenshell_types::SerialSettings::default(),
local: sevenshell_types::LocalSettings::default(),
diff --git a/crates/sevenshell-core/tests/live_container.rs b/crates/sevenshell-core/tests/live_container.rs
index 6a623cb0..c887c782 100644
--- a/crates/sevenshell-core/tests/live_container.rs
+++ b/crates/sevenshell-core/tests/live_container.rs
@@ -47,6 +47,7 @@ fn session(id: &str, name: &str, protocol: Protocol) -> Session {
auth: SessionAuth::with_password(AuthMethod::Password),
terminal: TerminalSettings::default(),
desktop: sevenshell_types::DesktopSettings::default(),
+ workbench: sevenshell_types::WorkbenchSettings::default(),
telnet: sevenshell_types::TelnetSettings::default(),
serial: sevenshell_types::SerialSettings::default(),
local: sevenshell_types::LocalSettings::default(),
diff --git a/crates/sevenshell-core/tests/live_container_files.rs b/crates/sevenshell-core/tests/live_container_files.rs
index e82cd991..a97eefc6 100644
--- a/crates/sevenshell-core/tests/live_container_files.rs
+++ b/crates/sevenshell-core/tests/live_container_files.rs
@@ -75,6 +75,7 @@ fn session(id: &str, name: &str, protocol: Protocol) -> Session {
auth: SessionAuth::with_password(AuthMethod::Password),
terminal: TerminalSettings::default(),
desktop: sevenshell_types::DesktopSettings::default(),
+ workbench: sevenshell_types::WorkbenchSettings::default(),
telnet: sevenshell_types::TelnetSettings::default(),
serial: sevenshell_types::SerialSettings::default(),
local: sevenshell_types::LocalSettings::default(),
diff --git a/crates/sevenshell-core/tests/live_files.rs b/crates/sevenshell-core/tests/live_files.rs
index ec39aaf6..d420ca2a 100644
--- a/crates/sevenshell-core/tests/live_files.rs
+++ b/crates/sevenshell-core/tests/live_files.rs
@@ -55,6 +55,7 @@ fn lab() -> Option {
auth: SessionAuth::with_password(AuthMethod::Password),
terminal: TerminalSettings::default(),
desktop: sevenshell_types::DesktopSettings::default(),
+ workbench: sevenshell_types::WorkbenchSettings::default(),
telnet: sevenshell_types::TelnetSettings::default(),
serial: sevenshell_types::SerialSettings::default(),
local: sevenshell_types::LocalSettings::default(),
diff --git a/crates/sevenshell-core/tests/live_k8s.rs b/crates/sevenshell-core/tests/live_k8s.rs
index 13870421..9fe5d3e1 100644
--- a/crates/sevenshell-core/tests/live_k8s.rs
+++ b/crates/sevenshell-core/tests/live_k8s.rs
@@ -65,6 +65,7 @@ fn cluster() -> Option {
auth: SessionAuth::with_password(AuthMethod::Password),
terminal: TerminalSettings::default(),
desktop: sevenshell_types::DesktopSettings::default(),
+ workbench: sevenshell_types::WorkbenchSettings::default(),
telnet: sevenshell_types::TelnetSettings::default(),
serial: sevenshell_types::SerialSettings::default(),
local: sevenshell_types::LocalSettings::default(),
diff --git a/crates/sevenshell-core/tests/live_k8s_via_ssh.rs b/crates/sevenshell-core/tests/live_k8s_via_ssh.rs
index 8b08f8d2..95c5b417 100644
--- a/crates/sevenshell-core/tests/live_k8s_via_ssh.rs
+++ b/crates/sevenshell-core/tests/live_k8s_via_ssh.rs
@@ -116,6 +116,7 @@ fn session(id: &str, protocol: sevenshell_types::Protocol, host: &str, port: u16
auth: SessionAuth::with_password(AuthMethod::Password),
terminal: TerminalSettings::default(),
desktop: sevenshell_types::DesktopSettings::default(),
+ workbench: sevenshell_types::WorkbenchSettings::default(),
telnet: sevenshell_types::TelnetSettings::default(),
serial: sevenshell_types::SerialSettings::default(),
local: sevenshell_types::LocalSettings::default(),
diff --git a/crates/sevenshell-core/tests/live_monitor.rs b/crates/sevenshell-core/tests/live_monitor.rs
index 44e498d8..dc77687c 100644
--- a/crates/sevenshell-core/tests/live_monitor.rs
+++ b/crates/sevenshell-core/tests/live_monitor.rs
@@ -99,6 +99,7 @@ fn lab() -> Option {
auth: SessionAuth::with_password(AuthMethod::Password),
terminal: TerminalSettings::default(),
desktop: sevenshell_types::DesktopSettings::default(),
+ workbench: sevenshell_types::WorkbenchSettings::default(),
telnet: sevenshell_types::TelnetSettings::default(),
serial: sevenshell_types::SerialSettings::default(),
local: sevenshell_types::LocalSettings::default(),
diff --git a/crates/sevenshell-core/tests/live_pod_files.rs b/crates/sevenshell-core/tests/live_pod_files.rs
index efd0857e..818f31bf 100644
--- a/crates/sevenshell-core/tests/live_pod_files.rs
+++ b/crates/sevenshell-core/tests/live_pod_files.rs
@@ -65,6 +65,7 @@ fn cluster() -> Option {
auth: SessionAuth::with_password(AuthMethod::Password),
terminal: TerminalSettings::default(),
desktop: sevenshell_types::DesktopSettings::default(),
+ workbench: sevenshell_types::WorkbenchSettings::default(),
telnet: sevenshell_types::TelnetSettings::default(),
serial: sevenshell_types::SerialSettings::default(),
local: sevenshell_types::LocalSettings::default(),
diff --git a/crates/sevenshell-core/tests/live_scp.rs b/crates/sevenshell-core/tests/live_scp.rs
index b1b35a1a..81cd5326 100644
--- a/crates/sevenshell-core/tests/live_scp.rs
+++ b/crates/sevenshell-core/tests/live_scp.rs
@@ -38,6 +38,7 @@ fn lab_session() -> Option {
auth: SessionAuth::with_password(AuthMethod::Password),
terminal: TerminalSettings::default(),
desktop: sevenshell_types::DesktopSettings::default(),
+ workbench: sevenshell_types::WorkbenchSettings::default(),
telnet: sevenshell_types::TelnetSettings::default(),
serial: sevenshell_types::SerialSettings::default(),
local: sevenshell_types::LocalSettings::default(),
diff --git a/crates/sevenshell-core/tests/live_system.rs b/crates/sevenshell-core/tests/live_system.rs
index 5151164c..f76d7b2b 100644
--- a/crates/sevenshell-core/tests/live_system.rs
+++ b/crates/sevenshell-core/tests/live_system.rs
@@ -87,6 +87,7 @@ fn lab() -> Option {
auth: SessionAuth::with_password(AuthMethod::Password),
terminal: TerminalSettings::default(),
desktop: sevenshell_types::DesktopSettings::default(),
+ workbench: sevenshell_types::WorkbenchSettings::default(),
telnet: sevenshell_types::TelnetSettings::default(),
serial: sevenshell_types::SerialSettings::default(),
local: sevenshell_types::LocalSettings::default(),
diff --git a/crates/sevenshell-core/tests/webdav_files.rs b/crates/sevenshell-core/tests/webdav_files.rs
index aadcd88d..599f9801 100644
--- a/crates/sevenshell-core/tests/webdav_files.rs
+++ b/crates/sevenshell-core/tests/webdav_files.rs
@@ -177,6 +177,7 @@ fn webdav_session(url: String) -> Session {
auth: SessionAuth::with_password(AuthMethod::Password),
terminal: TerminalSettings::default(),
desktop: sevenshell_types::DesktopSettings::default(),
+ workbench: sevenshell_types::WorkbenchSettings::default(),
telnet: sevenshell_types::TelnetSettings::default(),
serial: sevenshell_types::SerialSettings::default(),
local: sevenshell_types::LocalSettings::default(),
diff --git a/crates/sevenshell-sync/src/snippets.rs b/crates/sevenshell-sync/src/snippets.rs
index b7bc47a0..dcba38ef 100644
--- a/crates/sevenshell-sync/src/snippets.rs
+++ b/crates/sevenshell-sync/src/snippets.rs
@@ -682,6 +682,7 @@ mod tests {
auth: SessionAuth::with_password(AuthMethod::Password),
terminal: TerminalSettings::default(),
desktop: sevenshell_types::DesktopSettings::default(),
+ workbench: sevenshell_types::WorkbenchSettings::default(),
telnet: sevenshell_types::TelnetSettings::default(),
serial: sevenshell_types::SerialSettings::default(),
local: sevenshell_types::LocalSettings::default(),
diff --git a/crates/sevenshell-sync/tests/live_sync.rs b/crates/sevenshell-sync/tests/live_sync.rs
index 10ce892e..ce8522c2 100644
--- a/crates/sevenshell-sync/tests/live_sync.rs
+++ b/crates/sevenshell-sync/tests/live_sync.rs
@@ -111,6 +111,7 @@ fn library(vault: &Vault) {
auth: SessionAuth::with_password(AuthMethod::Password),
terminal: TerminalSettings::default(),
desktop: sevenshell_types::DesktopSettings::default(),
+ workbench: sevenshell_types::WorkbenchSettings::default(),
telnet: sevenshell_types::TelnetSettings::default(),
serial: sevenshell_types::SerialSettings::default(),
local: sevenshell_types::LocalSettings::default(),
diff --git a/crates/sevenshell-sync/tests/round_trip.rs b/crates/sevenshell-sync/tests/round_trip.rs
index 3874bf3d..d1cf0687 100644
--- a/crates/sevenshell-sync/tests/round_trip.rs
+++ b/crates/sevenshell-sync/tests/round_trip.rs
@@ -36,6 +36,7 @@ fn session(id: &str, name: &str) -> Session {
auth: SessionAuth::with_password(AuthMethod::Password),
terminal: TerminalSettings::default(),
desktop: sevenshell_types::DesktopSettings::default(),
+ workbench: sevenshell_types::WorkbenchSettings::default(),
telnet: sevenshell_types::TelnetSettings::default(),
serial: sevenshell_types::SerialSettings::default(),
local: sevenshell_types::LocalSettings::default(),
diff --git a/crates/sevenshell-types/src/lib.rs b/crates/sevenshell-types/src/lib.rs
index c57c0067..ebf4e2ee 100644
--- a/crates/sevenshell-types/src/lib.rs
+++ b/crates/sevenshell-types/src/lib.rs
@@ -81,7 +81,7 @@ pub use session::{
Session, SessionAuth, SessionExportSummary, SessionGroup, SessionImportOutcome, SessionImportSummary, SftpEntry,
SftpListing, SftpOutcome, SftpPasteItem, SftpPasteOutcome, TelnetSettings, TerminalSettings, TransferDirection,
TransferInfo, TransferState, TunnelFailure, UploadAnswer, UploadOutcome, VaultArchive, VaultState, WebDavSettings,
- WslSettings,
+ WorkbenchPowerOutcome, WorkbenchSettings, WslSettings,
};
pub use settings::{
AI_SESSION_RETENTION_DAYS_DEFAULT, AI_SESSION_RETENTION_DAYS_MAX, AI_SESSION_RETENTION_DAYS_MIN, AppLayout,
diff --git a/crates/sevenshell-types/src/session.rs b/crates/sevenshell-types/src/session.rs
index 167c6761..74b2e8d4 100644
--- a/crates/sevenshell-types/src/session.rs
+++ b/crates/sevenshell-types/src/session.rs
@@ -28,6 +28,9 @@ pub struct Session {
/// What a remote desktop asks of the system client. Ignored by SSH sessions.
#[serde(default)]
pub desktop: DesktopSettings,
+ /// How the desktop workbench draws this machine. Only a `linuxDesk` session reads it.
+ #[serde(default, skip_serializing_if = "WorkbenchSettings::is_empty")]
+ pub workbench: WorkbenchSettings,
/// What a Telnet console expects on the wire. Ignored by every other protocol.
#[serde(default)]
pub telnet: TelnetSettings,
@@ -506,6 +509,43 @@ impl Default for DesktopSettings {
}
}
+/// What the desktop workbench draws for this session.
+///
+/// The workbench is the `linuxDesk` protocol's front page, and this carries the personal bits a
+/// person chooses for how *this machine's* workbench looks. They live on the session beside the
+/// rest of what the vault holds rather than in the interface's storage, because a face chosen
+/// for one machine is a setting about that machine, not a habit of the person who chose it — and
+/// it should travel with the session the way every other per-session choice does.
+#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct WorkbenchSettings {
+ /// Which built-in backdrop the workbench draws. `None` is the interface's default, and a
+ /// document written before this field existed has none of it — which is what every older
+ /// document meant.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub wallpaper: Option,
+}
+
+impl WorkbenchSettings {
+ /// Whether nothing has been chosen. An empty setting is left out of the wire document, the
+ /// way the other per-protocol settings that default to nothing are.
+ pub fn is_empty(&self) -> bool {
+ self.wallpaper.is_none()
+ }
+}
+
+/// Whether a power action the workbench asked for reached the machine.
+///
+/// `shutdown` and `reboot` often take the connection down before the command can report an exit
+/// status, so "no status" is the action working rather than failing. An exit status the machine
+/// did report is the machine's own answer, and a non-zero one is this type's only failure path —
+/// which the error envelope carries, not this.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct WorkbenchPowerOutcome {
+ pub issued: bool,
+}
+
/// A folder in the session tree. Groups nest, and are ordered by `order`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
diff --git a/crates/sevenshell-types/tests/wire.rs b/crates/sevenshell-types/tests/wire.rs
index 22497764..9da0f4f7 100644
--- a/crates/sevenshell-types/tests/wire.rs
+++ b/crates/sevenshell-types/tests/wire.rs
@@ -479,6 +479,7 @@ fn a_session_with_a_route_and_forwards_serializes_with_camel_case_fields() {
},
terminal: TerminalSettings::default(),
desktop: sevenshell_types::DesktopSettings::default(),
+ workbench: sevenshell_types::WorkbenchSettings::default(),
telnet: sevenshell_types::TelnetSettings::default(),
serial: sevenshell_types::SerialSettings::default(),
local: sevenshell_types::LocalSettings::default(),
@@ -529,6 +530,42 @@ fn desktop_settings_serialize_with_camel_case_fields() {
assert_eq!(json["redirectDrives"], serde_json::json!(false));
}
+#[test]
+fn a_workbench_session_serializes_with_camel_case_fields() {
+ // The workbench session is an SSH session on the wire: the same fields, with the protocol
+ // naming the machine the interface draws a workbench for. Nothing here is workbench-shaped
+ // yet except the protocol id, which is the point — the descriptor's `workbench` capability,
+ // not a new wire shape, is what tells the interface which pane to mount.
+ let session = Session {
+ id: "workbench-1".to_owned(),
+ name: "lab".to_owned(),
+ group_id: None,
+ protocol: Protocol::LinuxDesk,
+ host: "host.example".to_owned(),
+ port: 22,
+ user: "root".to_owned(),
+ auth: SessionAuth::with_password(AuthMethod::Password),
+ terminal: TerminalSettings::default(),
+ desktop: sevenshell_types::DesktopSettings::default(),
+ workbench: sevenshell_types::WorkbenchSettings::default(),
+ telnet: sevenshell_types::TelnetSettings::default(),
+ serial: sevenshell_types::SerialSettings::default(),
+ local: sevenshell_types::LocalSettings::default(),
+ wsl: sevenshell_types::WslSettings::default(),
+ container: sevenshell_types::ContainerSettings::default(),
+ kubernetes: sevenshell_types::KubernetesSettings::default(),
+ webdav: sevenshell_types::WebDavSettings::default(),
+ ftp: sevenshell_types::FtpSettings::default(),
+ jump: Vec::new(),
+ forwards: Vec::new(),
+ updated_at: 1,
+ };
+
+ let json = check(&session, "Session");
+ assert_eq!(json["protocol"], serde_json::json!("linuxDesk"));
+ assert_eq!(json["host"], serde_json::json!("host.example"));
+}
+
#[test]
fn a_created_key_carries_its_fingerprint_and_one_public_line() {
// The one key-shaped thing that crosses this boundary, and only the half that is meant to be
diff --git a/crates/sevenshell-vault/src/document.rs b/crates/sevenshell-vault/src/document.rs
index 4c73e07f..df392ebe 100644
--- a/crates/sevenshell-vault/src/document.rs
+++ b/crates/sevenshell-vault/src/document.rs
@@ -45,8 +45,10 @@ use crate::credential::{KeyEntry, SecretEntry, SecretKind, ServicePassword};
/// Version 12 added the assistant's stored conversations and the table the secrets of an external
/// MCP server will live in: an older build reading one would parse the document, drop both tables
/// and write it back — every conversation and every server credential gone in the course of
-/// somebody opening the window.
-pub const VAULT_SCHEMA_VERSION: u32 = 12;
+/// somebody opening the window. Version 13 added a workbench session's backdrop choice, which an
+/// older build would drop on its next write — a face the person chose for that machine, gone
+/// without a word.
+pub const VAULT_SCHEMA_VERSION: u32 = 13;
/// How many sent commands are remembered. Enough to cover a working session's worth of "what was
/// that line", and bounded so the vault does not grow with every command ever typed.
@@ -971,7 +973,8 @@ pub(crate) fn migrate(mut document: Document) -> Result {
// meant — so the steps are the version number alone. 9 → 10: a session secret may now be a
// kubeconfig document. 10 → 11: the document may now carry an assistant provider's key. 11 → 12:
// it may now carry the assistant's conversations and an MCP server's credentials, and an older
- // document simply has neither table. The number moves so an older build refuses the whole file as
+ // document simply has neither table. 12 → 13: a session may now carry the workbench's backdrop
+ // choice. The number moves so an older build refuses the whole file as
// too new instead of failing to read one unknown secret variant and calling the vault corrupt, and
// so a build that predates the keys cannot drop them by writing the document back.
document.schema_version = VAULT_SCHEMA_VERSION;
@@ -1016,6 +1019,7 @@ mod tests {
auth: SessionAuth::with_password(AuthMethod::Password),
terminal: TerminalSettings::default(),
desktop: sevenshell_types::DesktopSettings::default(),
+ workbench: sevenshell_types::WorkbenchSettings::default(),
telnet: sevenshell_types::TelnetSettings::default(),
serial: sevenshell_types::SerialSettings::default(),
local: sevenshell_types::LocalSettings::default(),
diff --git a/crates/sevenshell-vault/src/transfer.rs b/crates/sevenshell-vault/src/transfer.rs
index dad6e2bc..9324b7fb 100644
--- a/crates/sevenshell-vault/src/transfer.rs
+++ b/crates/sevenshell-vault/src/transfer.rs
@@ -553,6 +553,7 @@ mod tests {
auth: SessionAuth::with_password(AuthMethod::Password),
terminal: TerminalSettings::default(),
desktop: sevenshell_types::DesktopSettings::default(),
+ workbench: sevenshell_types::WorkbenchSettings::default(),
telnet: sevenshell_types::TelnetSettings::default(),
serial: sevenshell_types::SerialSettings::default(),
local: sevenshell_types::LocalSettings::default(),
diff --git a/crates/sevenshell-vault/src/vault.rs b/crates/sevenshell-vault/src/vault.rs
index b24165ba..90c36646 100644
--- a/crates/sevenshell-vault/src/vault.rs
+++ b/crates/sevenshell-vault/src/vault.rs
@@ -1326,6 +1326,7 @@ mod tests {
auth: SessionAuth::with_password(AuthMethod::Password),
terminal: TerminalSettings::default(),
desktop: sevenshell_types::DesktopSettings::default(),
+ workbench: sevenshell_types::WorkbenchSettings::default(),
telnet: sevenshell_types::TelnetSettings::default(),
serial: sevenshell_types::SerialSettings::default(),
local: sevenshell_types::LocalSettings::default(),
diff --git a/descriptors/capabilities.yaml b/descriptors/capabilities.yaml
index 4faec703..abdccd2c 100644
--- a/descriptors/capabilities.yaml
+++ b/descriptors/capabilities.yaml
@@ -117,6 +117,15 @@ capabilities:
# in-process channels (view, input, resize, clipboard) were removed with the embedded engine in
# c981da4; `systemClient` is the whole promise this build makes about a remote desktop.
+ # The desktop workbench is the other answer, and it is drawn by this process: a front page for a
+ # machine that composes the surfaces its connection already carries (system mark, monitor
+ # sample, file entries) into one view. Only the linuxDesk protocol claims it, and it is what
+ # decides that a session opens onto the workbench instead of a terminal.
+ - key: workbench
+ order: 150
+ group: desktop
+ labelKey: capability.workbench.label
+
# -- Containers ---------------------------------------------------------
# The workbench has panes for all five, and the Docker runtime is covered by live tests; the
# other runtimes use the same command construction, with the environment gap recorded in AGENTS.
diff --git a/descriptors/descriptors.manifest.json b/descriptors/descriptors.manifest.json
index 88180491..5f4cdd0c 100644
--- a/descriptors/descriptors.manifest.json
+++ b/descriptors/descriptors.manifest.json
@@ -135,6 +135,13 @@
"labelKey": "capability.systemClient.label",
"planned": false
},
+ {
+ "key": "workbench",
+ "order": 150,
+ "group": "desktop",
+ "labelKey": "capability.workbench.label",
+ "planned": false
+ },
{
"key": "container",
"order": 190,
@@ -244,6 +251,30 @@
"systemClient"
]
},
+ {
+ "id": "linuxDesk",
+ "rustVariant": "LinuxDesk",
+ "order": 22,
+ "labelKey": "protocol.linuxDesk.label",
+ "defaultPort": 22,
+ "runtime": "native",
+ "transport": "tcp",
+ "supportLevel": "connect",
+ "capabilities": [
+ "shell",
+ "exec",
+ "resize",
+ "keepalive",
+ "hostMetrics",
+ "sftp",
+ "scp",
+ "jumpHost",
+ "forwarding",
+ "dynamicForwarding",
+ "recording",
+ "workbench"
+ ]
+ },
{
"id": "webdav",
"rustVariant": "WebDav",
diff --git a/descriptors/protocols/linuxDesk.yaml b/descriptors/protocols/linuxDesk.yaml
new file mode 100644
index 00000000..95c6bc88
--- /dev/null
+++ b/descriptors/protocols/linuxDesk.yaml
@@ -0,0 +1,31 @@
+schemaVersion: 1
+order: 22
+id: linuxDesk
+rustVariant: LinuxDesk
+labelKey: protocol.linuxDesk.label
+defaultPort: 22
+# A Linux machine reached over SSH, whose front page is the desktop workbench: the session is
+# carried by the same machinery as `ssh` (same open path, same host-key order, same vault
+# fields, no remote footprint), and the only difference is the tab the interface mounts first.
+# The workbench composes surfaces the connection already carries — the system mark, the host
+# monitor's sample, the file browser — rather than opening any new way to reach the machine.
+runtime: native
+transport: tcp
+supportLevel: connect
+# The capabilities this protocol honours are the SSH set the workbench and its terminal actually
+# use, plus `workbench`, which only this protocol claims: it is what tells the interface to mount
+# the workbench tab and what later tells the agent interface which tools a workbench session has.
+# Agent forwarding is left unclaimed on purpose: nothing here uses it yet.
+capabilities:
+ - shell
+ - exec
+ - resize
+ - keepalive
+ - hostMetrics
+ - sftp
+ - scp
+ - jumpHost
+ - forwarding
+ - dynamicForwarding
+ - recording
+ - workbench
diff --git a/src-tauri/src/state.rs b/src-tauri/src/state.rs
index 04c83104..7fe62474 100644
--- a/src-tauri/src/state.rs
+++ b/src-tauri/src/state.rs
@@ -752,6 +752,7 @@ mod tests {
auth: sevenshell_types::SessionAuth::with_password(sevenshell_types::AuthMethod::Password),
terminal: sevenshell_types::TerminalSettings::default(),
desktop: sevenshell_types::DesktopSettings::default(),
+ workbench: sevenshell_types::WorkbenchSettings::default(),
telnet: sevenshell_types::TelnetSettings::default(),
serial: sevenshell_types::SerialSettings::default(),
local: sevenshell_types::LocalSettings::default(),
From 9faa5b02384ec05839a017764cf5723558ecc1bc Mon Sep 17 00:00:00 2001
From: SongRenShuo <3064597532@qq.com>
Date: Wed, 18 Nov 2026 01:50:56 +0800
Subject: [PATCH 004/440] feat(workbench): the power action, behind the same
gate as everything gated
The workbench's one action that reaches the far side is the power action:
reboot and shutdown, two fixed commands nobody typed into, run as the user
the session already authenticated as. The gate is the container gate's with
one gate earlier - an unknown verb is refused before anything is read - and
one layer deeper: a workbench session is a saved session, so its own group,
host and port layers apply, and a Deny on a machine is a workbench that will
not power it off. The decision comes before the handle is looked up, because
a deny is answered before any socket.
- policy: workbench_action grades both verbs Destructive and every unknown
verb Catastrophic
- core: workbench_power, with the "no exit status is the machine going down"
reading written into the outcome type
- error: WORKBENCH-POWER-FAILED, and a workbench subsystem beside rdp
- hosts: one command on the desktop shell, one dispatch arm in the browser
host, one wrapper-shaped the same in both
- i18n: the power failure message and the rule names, both locales
---
apps/desktop/src/i18n/locales/en/errors.json | 3 +
apps/desktop/src/i18n/locales/en/risk.json | 5 +
.../src/i18n/locales/zh-CN/errors.json | 3 +
apps/desktop/src/i18n/locales/zh-CN/risk.json | 5 +
crates/sevenshell-core/src/lib.rs | 1 +
crates/sevenshell-core/src/workbench.rs | 263 ++++++++++++++++++
crates/sevenshell-error/src/code.rs | 4 +
crates/sevenshell-error/src/envelope.rs | 15 +
crates/sevenshell-policy/src/lib.rs | 2 +
.../sevenshell-policy/src/workbench_risk.rs | 57 ++++
crates/sevenshell-web/src/main.rs | 7 +
src-tauri/src/commands/mod.rs | 1 +
src-tauri/src/commands/workbench.rs | 26 ++
src-tauri/src/lib.rs | 1 +
14 files changed, 393 insertions(+)
create mode 100644 crates/sevenshell-core/src/workbench.rs
create mode 100644 crates/sevenshell-policy/src/workbench_risk.rs
create mode 100644 src-tauri/src/commands/workbench.rs
diff --git a/apps/desktop/src/i18n/locales/en/errors.json b/apps/desktop/src/i18n/locales/en/errors.json
index 341f1727..18634d36 100644
--- a/apps/desktop/src/i18n/locales/en/errors.json
+++ b/apps/desktop/src/i18n/locales/en/errors.json
@@ -20,6 +20,9 @@
"rdp": {
"launchFailed": "The Windows Remote Desktop client could not be started."
},
+ "workbench": {
+ "powerFailed": "The machine did not accept the power action. {detail}"
+ },
"terminal": {
"unreachable": "Could not reach {host}:{port}. Nothing answered there, or it is not a Telnet service.",
"serialFailed": "Could not open serial port {port}. Check that the device is connected and no other program holds it.",
diff --git a/apps/desktop/src/i18n/locales/en/risk.json b/apps/desktop/src/i18n/locales/en/risk.json
index 110f3cec..89e4a6ba 100644
--- a/apps/desktop/src/i18n/locales/en/risk.json
+++ b/apps/desktop/src/i18n/locales/en/risk.json
@@ -40,6 +40,11 @@
"namespaceDelete": "Deletes a namespace and everything in it",
"evict": "Evicts a pod from its node",
"unknown": "A cluster request this version does not recognise"
+ },
+ "workbench": {
+ "reboot": "Restarts the machine",
+ "shutdown": "Powers the machine off",
+ "unknown": "A workbench action this version does not recognise"
}
}
}
diff --git a/apps/desktop/src/i18n/locales/zh-CN/errors.json b/apps/desktop/src/i18n/locales/zh-CN/errors.json
index aed6ed2a..a79e4c6a 100644
--- a/apps/desktop/src/i18n/locales/zh-CN/errors.json
+++ b/apps/desktop/src/i18n/locales/zh-CN/errors.json
@@ -20,6 +20,9 @@
"rdp": {
"launchFailed": "无法启动 Windows 远程桌面客户端。"
},
+ "workbench": {
+ "powerFailed": "机器未接受本次电源操作。{detail}"
+ },
"terminal": {
"unreachable": "无法连接 {host}:{port}。该地址没有响应,或不是 Telnet 服务。",
"serialFailed": "无法打开串口 {port}。请确认设备已连接、端口未被其他程序占用。",
diff --git a/apps/desktop/src/i18n/locales/zh-CN/risk.json b/apps/desktop/src/i18n/locales/zh-CN/risk.json
index bca2438d..bd0070b8 100644
--- a/apps/desktop/src/i18n/locales/zh-CN/risk.json
+++ b/apps/desktop/src/i18n/locales/zh-CN/risk.json
@@ -40,6 +40,11 @@
"namespaceDelete": "删除命名空间及其中的全部内容",
"evict": "把 Pod 从节点上驱逐",
"unknown": "当前版本不认识的集群请求"
+ },
+ "workbench": {
+ "reboot": "重启机器",
+ "shutdown": "关闭机器电源",
+ "unknown": "当前版本不认识的工作台操作"
}
}
}
diff --git a/crates/sevenshell-core/src/lib.rs b/crates/sevenshell-core/src/lib.rs
index a2d5f83c..db3d4d7a 100644
--- a/crates/sevenshell-core/src/lib.rs
+++ b/crates/sevenshell-core/src/lib.rs
@@ -20,6 +20,7 @@ mod policy;
mod sessions;
mod snippets;
mod system;
+mod workbench;
pub use archive::{ARCHIVE_TIMEOUT, archive_name, shell_quote};
pub use batch::{BatchEvent, DEFAULT_PARALLEL, MAX_HOST_TIMEOUT, MAX_PARALLEL, MIN_HOST_TIMEOUT, classify_command};
diff --git a/crates/sevenshell-core/src/workbench.rs b/crates/sevenshell-core/src/workbench.rs
new file mode 100644
index 00000000..260fc0d7
--- /dev/null
+++ b/crates/sevenshell-core/src/workbench.rs
@@ -0,0 +1,263 @@
+//! The desktop workbench's one action that reaches the far side.
+//!
+//! Almost everything the workbench shows is a surface the session's connection already carries —
+//! the system mark, the monitor's sample, the file browser. The one thing it can ask the machine
+//! to *do* is the power action, and it is held to the same shape the container workspace uses:
+//! the verbs are fixed, the commands behind them are constants nobody types into, the policy
+//! matrix decides what this installation does about the danger, and every decision leaves one
+//! audit line. Unlike the container paths, a workbench session is a saved session, so its own
+//! group, host and port layers apply — a `Deny` on a machine is a workbench that will not power
+//! it off.
+//!
+//! The commands are deliberately plain: `shutdown -r now` and `shutdown -h now` are the two forms
+//! every mainstream init answers, run as the user the session already authenticated as. Their
+//! rights are the session's rights; nothing here elevates. And an unknown verb is refused before
+//! any of it — there is no command behind a verb this module has not named.
+
+use std::time::Duration;
+
+use sevenshell_error::ShellError;
+use sevenshell_types::{PolicyAction, Protocol, WorkbenchPowerOutcome};
+
+use crate::sessions::Core;
+
+/// How long the machine has to answer a power command. The action that works takes the
+/// connection down with the machine, which ends the wait from the other side.
+const POWER_TIMEOUT: Duration = Duration::from_secs(15);
+
+/// The two commands the workbench can run on a machine, and neither is built from input. See the
+/// module note for why these two forms and no others.
+const REBOOT_COMMAND: &str = "shutdown -r now";
+const SHUTDOWN_COMMAND: &str = "shutdown -h now";
+
+impl Core {
+ /// Runs one workbench power action after the policy verdict for it.
+ ///
+ /// The order is the container gate's, with one gate earlier: the verb itself. An action this
+ /// module has no command for is refused before the session is even read — a refusal that
+ /// cannot be argued into a run by any configuration of the matrix or the interface. And the
+ /// policy decision comes before the handle is looked up, because a `Deny` is answered before
+ /// any socket: the caller names both the session it is acting for and the handle it acts
+ /// through, so the gate can use the session's own layers and still refuse a dead handle
+ /// cheaply.
+ pub async fn workbench_power(
+ &self,
+ session_id: &str,
+ handle: &str,
+ action: &str,
+ acknowledged: bool,
+ ) -> Result {
+ let normalized = action.trim().to_ascii_lowercase();
+ let command = match normalized.as_str() {
+ "reboot" => REBOOT_COMMAND,
+ "shutdown" => SHUTDOWN_COMMAND,
+ _ => return Err(ShellError::app_unsupported("that workbench action does not exist")),
+ };
+
+ let session = self.session(session_id)?;
+ if session.protocol != Protocol::LinuxDesk {
+ return Err(ShellError::app_unsupported(
+ "power actions belong to the desktop workbench",
+ ));
+ }
+
+ let verdict = sevenshell_policy::workbench_action(&normalized);
+ let saved = self.session_policy_target(session_id);
+ let target = saved.as_ref().map(|saved| saved.as_target()).unwrap_or_default();
+ let decision = self.policy_decision(
+ &format!("workbench.{normalized}"),
+ &verdict,
+ target,
+ Some(session_id),
+ Some(&normalized),
+ );
+ match decision.action {
+ PolicyAction::Deny => {
+ return Err(ShellError::policy_denied(&format!("workbench.{normalized}")));
+ }
+ PolicyAction::Ask if !acknowledged => {
+ let rule = verdict
+ .reasons
+ .first()
+ .map(|reason| reason.rule_id.as_str())
+ .unwrap_or("workbench.unknown");
+ return Err(ShellError::policy_approval_required(rule));
+ }
+ _ => {}
+ }
+
+ let remote = self.registry.session_of(handle).await?;
+ let outcome = remote.exec(command, POWER_TIMEOUT).await?;
+ match outcome.exit_code {
+ Some(0) => Ok(WorkbenchPowerOutcome { issued: true }),
+ // A power action that reported no exit status has almost always taken the connection
+ // down with the machine — which is the action working, not failing. An exit status
+ // the machine did report is the machine's own answer.
+ None => Ok(WorkbenchPowerOutcome { issued: true }),
+ Some(_) => {
+ let detail = if outcome.stderr.trim().is_empty() {
+ format!("exit code {:?}", outcome.exit_code)
+ } else {
+ outcome.stderr.trim().to_owned()
+ };
+ Err(ShellError::workbench_power_failed(detail))
+ }
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use std::sync::{Arc, Mutex};
+
+ use sevenshell_policy::{PolicyAuditEvent, PolicyJournal};
+ use sevenshell_types::{AuthMethod, PolicyAction, PolicyMatrix, PolicyRule, SessionAuth, TerminalSettings};
+ use tempfile::{TempDir, tempdir};
+
+ use super::*;
+ use sevenshell_vault::Vault;
+
+ #[derive(Default)]
+ struct RecordingJournal {
+ events: Mutex>,
+ }
+
+ impl RecordingJournal {
+ fn events(&self) -> Vec {
+ self.events.lock().expect("not poisoned").clone()
+ }
+ }
+
+ impl PolicyJournal for RecordingJournal {
+ fn record(&self, event: PolicyAuditEvent) {
+ self.events.lock().expect("not poisoned").push(event);
+ }
+ }
+
+ fn deny_everything() -> PolicyRule {
+ PolicyRule {
+ safe: PolicyAction::Deny,
+ caution: PolicyAction::Deny,
+ destructive: PolicyAction::Deny,
+ catastrophic: PolicyAction::Deny,
+ }
+ }
+
+ fn core_with_policy(rule: PolicyRule) -> (TempDir, Arc, Arc) {
+ let directory = tempdir().expect("temp dir");
+ let vault = Arc::new(Vault::open_at(directory.path().join("vault.json")));
+ vault.create("correct horse battery staple").expect("create");
+
+ let mut session = sample("workbench-1", "a workbench machine");
+ session.protocol = Protocol::LinuxDesk;
+ vault.save_session(session, None).expect("save");
+
+ let (core, _events): (Arc, _) = Core::new(vault);
+ let journal = Arc::new(RecordingJournal::default());
+ core.set_policy(PolicyMatrix { global: rule, ..PolicyMatrix::default() }, Some(Arc::clone(&journal) as Arc));
+ (directory, core, journal)
+ }
+
+ fn sample(id: &str, name: &str) -> sevenshell_types::Session {
+ sevenshell_types::Session {
+ id: id.to_owned(),
+ name: name.to_owned(),
+ group_id: None,
+ protocol: Protocol::Ssh,
+ host: "127.0.0.1".to_owned(),
+ port: 2222,
+ user: "someone".to_owned(),
+ auth: SessionAuth::with_password(AuthMethod::Password),
+ terminal: TerminalSettings::default(),
+ desktop: sevenshell_types::DesktopSettings::default(),
+ workbench: sevenshell_types::WorkbenchSettings::default(),
+ telnet: sevenshell_types::TelnetSettings::default(),
+ serial: sevenshell_types::SerialSettings::default(),
+ local: sevenshell_types::LocalSettings::default(),
+ wsl: sevenshell_types::WslSettings::default(),
+ container: sevenshell_types::ContainerSettings::default(),
+ kubernetes: sevenshell_types::KubernetesSettings::default(),
+ webdav: sevenshell_types::WebDavSettings::default(),
+ ftp: sevenshell_types::FtpSettings::default(),
+ jump: Vec::new(),
+ forwards: Vec::new(),
+ updated_at: 0,
+ }
+ }
+
+ #[tokio::test]
+ async fn an_unknown_verb_is_refused_before_anything_is_read() {
+ // Neither the session nor the handle names anything real, and the verb names nothing the
+ // module has a command for: the refusal must be about the verb, which is the gate that
+ // runs first.
+ let (_directory, core, journal) = core_with_policy(PolicyRule::default());
+ let error = core
+ .workbench_power("session-that-never-existed", "handle-that-never-existed", "format", true)
+ .await
+ .expect_err("an unknown verb is refused");
+
+ assert_eq!(error.code(), sevenshell_error::ErrorCode::AppUnsupported);
+ assert!(journal.events().is_empty(), "nothing was decided, nothing is journaled");
+ }
+
+ #[tokio::test]
+ async fn a_deny_refuses_the_power_action_even_when_acknowledged() {
+ let (_directory, core, journal) = core_with_policy(deny_everything());
+
+ // Acknowledged on purpose: an acknowledgement answers a question, it does not overrule a
+ // deny. And the handle does not exist, so this proves the gate answers before any
+ // connection lookup — the decision is about the machine the session names, not about
+ // whether a channel is open.
+ let error = core
+ .workbench_power("workbench-1", "handle-that-never-existed", "reboot", true)
+ .await
+ .expect_err("a deny refuses the action");
+
+ assert_eq!(error.code(), sevenshell_error::ErrorCode::PolicyDenied);
+ let events = journal.events();
+ assert_eq!(events.len(), 1, "one action, one line");
+ assert_eq!(events[0].action, "workbench.reboot");
+ assert_eq!(events[0].decision, PolicyAction::Deny);
+ assert_eq!(events[0].subject.as_deref(), Some("reboot"));
+ }
+
+ #[tokio::test]
+ async fn a_question_without_an_acknowledgement_names_the_rule() {
+ // The default rule asks about destructive actions and lets everything else run; no layer
+ // is set, so the ask comes from the global floor.
+ let (_directory, core, journal) = core_with_policy(PolicyRule::default());
+
+ let error = core
+ .workbench_power("workbench-1", "handle-that-never-existed", "shutdown", false)
+ .await
+ .expect_err("a question stops the action");
+
+ assert_eq!(error.code(), sevenshell_error::ErrorCode::PolicyApprovalRequired);
+ // An ask is a decision too, and it is on the trail like every other one — what the
+ // absence of an acknowledgement changes is only that nothing ran.
+ let events = journal.events();
+ assert_eq!(events.len(), 1, "one action, one line, asks included");
+ assert_eq!(events[0].decision, PolicyAction::Ask);
+ }
+
+ #[tokio::test]
+ async fn a_session_that_is_not_a_workbench_is_refused_by_the_protocol() {
+ let directory = tempdir().expect("temp dir");
+ let vault = Arc::new(Vault::open_at(directory.path().join("vault.json")));
+ vault.create("correct horse battery staple").expect("create");
+
+ let mut session = sample("plain-ssh-1", "an ordinary SSH session");
+ session.protocol = Protocol::Ssh;
+ vault.save_session(session, None).expect("save");
+
+ let (core, _events): (Arc, _) = Core::new(vault);
+ // The protocol check runs before the policy gate: a plain SSH session named by a
+ // workbench power action is a caller that is confused, not an installation that decided
+ // anything — and the refusal names that, whatever the matrix says.
+ let error = core
+ .workbench_power("plain-ssh-1", "handle-that-never-existed", "reboot", true)
+ .await
+ .expect_err("only a workbench session powers a machine off");
+ assert_eq!(error.code(), sevenshell_error::ErrorCode::AppUnsupported);
+ }
+}
diff --git a/crates/sevenshell-error/src/code.rs b/crates/sevenshell-error/src/code.rs
index ce951507..f9df8499 100644
--- a/crates/sevenshell-error/src/code.rs
+++ b/crates/sevenshell-error/src/code.rs
@@ -69,6 +69,10 @@ error_catalog! {
#[doc = "The system Remote Desktop client could not be started."]
RdpLaunchFailed => "RDP-LAUNCH-FAILED", "errors.rdp.launchFailed";
+ // -- Workbench ---------------------------------------------------------
+ #[doc = "The machine refused a power action, or reported that it failed."]
+ WorkbenchPowerFailed => "WORKBENCH-POWER-FAILED", "errors.workbench.powerFailed";
+
// -- SFTP --------------------------------------------------------------
#[doc = "The remote path does not exist."]
SftpNotFound => "SFTP-NOT-FOUND", "errors.sftp.notFound";
diff --git a/crates/sevenshell-error/src/envelope.rs b/crates/sevenshell-error/src/envelope.rs
index 62ea551d..be814b01 100644
--- a/crates/sevenshell-error/src/envelope.rs
+++ b/crates/sevenshell-error/src/envelope.rs
@@ -30,6 +30,8 @@ pub enum Subsystem {
Container,
/// A Kubernetes API server and the kubeconfig used to reach it.
K8s,
+ /// The desktop workbench a `linuxDesk` session opens onto.
+ Workbench,
Fs,
Store,
Policy,
@@ -45,6 +47,7 @@ impl Subsystem {
Self::Ssh => "ssh",
Self::Sftp => "sftp",
Self::Rdp => "rdp",
+ Self::Workbench => "workbench",
Self::Terminal => "terminal",
Self::Container => "container",
Self::K8s => "k8s",
@@ -382,6 +385,18 @@ impl ShellError {
.with_outcome(OperationOutcome::NotSent)
}
+ // -- Workbench ---------------------------------------------------------
+
+ /// The machine refused a power action the workbench asked for, or reported that it failed.
+ ///
+ /// What the machine said travels as the detail; it is the server's own reply text about a
+ /// command this build chose, so it names a problem on the far side rather than a secret.
+ pub fn workbench_power_failed(detail: impl AsRef) -> Self {
+ Self::new(ErrorCode::WorkbenchPowerFailed, Origin::new(Subsystem::Workbench))
+ .with_detail(detail)
+ .with_outcome(OperationOutcome::Sent)
+ }
+
// -- SFTP --------------------------------------------------------------
pub fn sftp_not_found(remote_path: &str) -> Self {
diff --git a/crates/sevenshell-policy/src/lib.rs b/crates/sevenshell-policy/src/lib.rs
index a0d7a604..cbb00dc2 100644
--- a/crates/sevenshell-policy/src/lib.rs
+++ b/crates/sevenshell-policy/src/lib.rs
@@ -14,10 +14,12 @@
pub mod command_risk;
pub mod container_risk;
pub mod matrix;
+pub mod workbench_risk;
pub use command_risk::classify;
pub use container_risk::{container_action, kubernetes_request};
pub use matrix::{PolicyAuditEvent, PolicyDecision, PolicySource, PolicyTarget, decide};
+pub use workbench_risk::workbench_action;
pub use sevenshell_types::{RiskAssessment, RiskLevel, RiskReason};
/// Where a policy decision goes once it has been made.
diff --git a/crates/sevenshell-policy/src/workbench_risk.rs b/crates/sevenshell-policy/src/workbench_risk.rs
new file mode 100644
index 00000000..c86d60ce
--- /dev/null
+++ b/crates/sevenshell-policy/src/workbench_risk.rs
@@ -0,0 +1,57 @@
+//! What a desktop workbench action could do, before it runs.
+//!
+//! The workbench is a front page, and almost everything on it reads rather than writes — the
+//! sample, the mark, the file entries are surfaces the connection already carries. The one
+//! exception is the power action, and it is the same shape as a container action: a fixed verb
+//! with a fixed command behind it, decided here rather than by the risk classifier, because
+//! there is no command line for anybody to have read.
+//!
+//! A machine losing power is not like a container losing one process: sessions die, writes that
+//! were in flight may not land, and a machine that comes back up is somebody's morning to check.
+//! Both verbs are `Destructive`, so the matrix can never be configured to run them unattended —
+//! the strictest-layer rule raises destructive verdicts to at least a question.
+
+use sevenshell_types::{RiskAssessment, RiskLevel, RiskReason};
+
+/// Classifies one workbench power action.
+///
+/// Unknown verbs are `Catastrophic`, never run: a caller this table has not learned about has no
+/// command behind it worth guessing at, and a gate that guessed would be a gate that ran
+/// something nobody named.
+pub fn workbench_action(action: &str) -> RiskAssessment {
+ let action = action.trim().to_ascii_lowercase();
+ let verdict = match action.as_str() {
+ "reboot" => ("workbench.reboot", "risk.workbench.reboot", RiskLevel::Destructive),
+ "shutdown" => ("workbench.shutdown", "risk.workbench.shutdown", RiskLevel::Destructive),
+ _ => ("workbench.unknown", "risk.workbench.unknown", RiskLevel::Catastrophic),
+ };
+ RiskAssessment::from_reasons(vec![RiskReason::new(verdict.0, verdict.1, verdict.2)])
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use sevenshell_types::RiskLevel;
+
+ #[test]
+ fn both_power_verbs_are_destructive_and_name_their_rule() {
+ for action in ["reboot", "shutdown", "Reboot", " SHUTDOWN "] {
+ let verdict = workbench_action(action);
+ assert_eq!(verdict.level, RiskLevel::Destructive, "{action} is destructive");
+ assert!(verdict.needs_approval(), "{action} always asks a person");
+ }
+ }
+
+ #[test]
+ fn reboot_and_shutdown_are_told_apart() {
+ assert_eq!(workbench_action("reboot").reasons[0].rule_id, "workbench.reboot");
+ assert_eq!(workbench_action("shutdown").reasons[0].rule_id, "workbench.shutdown");
+ }
+
+ #[test]
+ fn an_unknown_verb_is_catastrophic() {
+ let verdict = workbench_action("format");
+ assert_eq!(verdict.level, RiskLevel::Catastrophic);
+ assert!(verdict.needs_approval());
+ }
+}
diff --git a/crates/sevenshell-web/src/main.rs b/crates/sevenshell-web/src/main.rs
index e5e064c6..3b4455f4 100644
--- a/crates/sevenshell-web/src/main.rs
+++ b/crates/sevenshell-web/src/main.rs
@@ -1042,6 +1042,13 @@ async fn dispatch(state: &WebState, cmd: &str, args: Value) -> Result {
+ let session_id: String = from_args(&args, "sessionId")?;
+ let handle: String = from_args(&args, "handle")?;
+ let action: String = from_args(&args, "action")?;
+ let acknowledged: bool = from_args(&args, "acknowledged")?;
+ to_value(state.core.workbench_power(&session_id, &handle, &action, acknowledged).await?)
+ }
"container_connect" => {
let session_id: String = from_args(&args, "sessionId")?;
diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rs
index f41871fb..636231f6 100644
--- a/src-tauri/src/commands/mod.rs
+++ b/src-tauri/src/commands/mod.rs
@@ -31,3 +31,4 @@ pub mod sync;
pub mod terminal;
pub mod update;
pub mod vault;
+pub mod workbench;
diff --git a/src-tauri/src/commands/workbench.rs b/src-tauri/src/commands/workbench.rs
new file mode 100644
index 00000000..7be111b2
--- /dev/null
+++ b/src-tauri/src/commands/workbench.rs
@@ -0,0 +1,26 @@
+//! The desktop workbench's command: the one action on this surface that reaches the far side.
+//!
+//! Everything else the workbench shows arrives through the commands it already has — the system
+//! mark, the monitor sample, the file browser. This module exists so the power action's
+//! acknowledgement travels through the same thin adapter every other gated action does.
+
+use sevenshell_error::ShellError;
+use sevenshell_types::WorkbenchPowerOutcome;
+use tauri::State;
+
+use crate::state::ShellState;
+
+/// Runs one workbench power action after the core's policy gate has decided about it.
+#[tauri::command]
+pub async fn workbench_power(
+ state: State<'_, ShellState>,
+ session_id: String,
+ handle: String,
+ action: String,
+ acknowledged: bool,
+) -> Result {
+ state
+ .core()
+ .workbench_power(&session_id, &handle, &action, acknowledged)
+ .await
+}
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 6902471b..adc961cf 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -237,6 +237,7 @@ pub fn run() {
commands::terminal::tunnels_open,
commands::terminal::tunnel_close,
commands::desktop::desktop_open,
+ commands::workbench::workbench_power,
commands::monitor::monitor_sample,
commands::monitor::monitor_processes,
commands::monitor::monitor_process_detail,
From c54e08c2941b2d106d02eae1d911c943f36bfdfb Mon Sep 17 00:00:00 2001
From: SongRenShuo <3064597532@qq.com>
Date: Wed, 18 Nov 2026 02:03:12 +0800
Subject: [PATCH 005/440] test(container): answer the cursor query a real
terminal would answer
The local pty terminal test typed into cmd and waited for the echo, and on
this Windows build conhost sends a cursor-position query first and waits for
the answer before showing the prompt - so the test sat on a 30-second timeout
seeing nothing but ESC[6n. The product never hits this because xterm.js
answers the query for real. The test now answers it the way a terminal
client does, which makes the test more faithful, not more permissive: it
still asserts the typed bytes come back.
12/12 green locally after the fix; the failure was machine-new (this repo's
tests had never run on this box), not a regression - the diff between the
baseline and the feature work touches nothing in this crate.
---
crates/sevenshell-container/tests/local_runner.rs | 9 +++++++++
1 file changed, 9 insertions(+)
diff --git a/crates/sevenshell-container/tests/local_runner.rs b/crates/sevenshell-container/tests/local_runner.rs
index 41abd83f..3160db93 100644
--- a/crates/sevenshell-container/tests/local_runner.rs
+++ b/crates/sevenshell-container/tests/local_runner.rs
@@ -139,9 +139,18 @@ async fn a_terminal_carries_bytes_in_both_directions() {
terminal.write(line.as_bytes()).await.expect("write should be accepted");
let mut seen = Vec::new();
+ // The other end of this terminal is the test itself, and a real terminal client answers the
+ // cursor-position query a host writes into the stream — xterm.js does it for the actual
+ // interface, which is why the product never sees this. A newer conhost waits on the answer
+ // before it shows the prompt, so the loop below replies once, the way a terminal would.
+ let mut answered_cursor_query = false;
let found = tokio::time::timeout(Duration::from_secs(30), async {
while let Some(chunk) = terminal.next_output().await {
seen.extend_from_slice(&chunk);
+ if !answered_cursor_query && seen.windows(4).any(|w| w == b"\x1b[6n") {
+ answered_cursor_query = true;
+ terminal.write(b"\x1b[1;1R").await.expect("answer should be accepted");
+ }
if String::from_utf8_lossy(&seen).contains("pty-ok") {
return true;
}
From e8b0aca1cfc74c4310a77e87dcbd3b59254c7649 Mon Sep 17 00:00:00 2001
From: SongRenShuo <3064597532@qq.com>
Date: Wed, 18 Nov 2026 02:04:00 +0800
Subject: [PATCH 006/440] feat(workbench): the power call crosses to the
interface side
The workbench surface is mostly readings of a connection the session already
carries; the one command it can send is the power action, and the interface
needs its wrapper, its outcome type and the workbench settings the session
document may carry before anything can be drawn or pressed. The error code
the Rust catalog already names is mirrored here so a refusal renders as a
sentence rather than a code.
---
apps/desktop/src/lib/backend/api.ts | 14 ++++++++++++++
apps/desktop/src/lib/backend/errorCodes.ts | 2 ++
apps/desktop/src/lib/backend/tauri.ts | 16 ++++++++++++++++
apps/desktop/src/types/session.ts | 13 +++++++++++++
4 files changed, 45 insertions(+)
diff --git a/apps/desktop/src/lib/backend/api.ts b/apps/desktop/src/lib/backend/api.ts
index b16544a1..704dcb15 100644
--- a/apps/desktop/src/lib/backend/api.ts
+++ b/apps/desktop/src/lib/backend/api.ts
@@ -100,6 +100,7 @@ import type {
TerminalData,
UploadAnswer,
UploadOutcome,
+ WorkbenchPowerOutcome,
VaultArchive,
VaultState,
ZmodemEvent,
@@ -968,6 +969,19 @@ export const backend = {
open: (sessionId: string): Promise => forward("desktop_open", () => desktop.desktopOpen(sessionId)),
},
+ /**
+ * The desktop workbench's one action that reaches the far side. Everything else it shows is a
+ * reading of the connection the session already carries; this is the one thing somebody can ask
+ * the machine to do, and the acknowledgement it carries is the answer the policy gate acts on.
+ */
+ workbenchPower: (
+ sessionId: string,
+ handle: string,
+ action: string,
+ acknowledged: boolean,
+ ): Promise =>
+ forward("workbench_power", () => desktop.workbenchPower(sessionId, handle, action, acknowledged)),
+
/**
* What the host behind a terminal is doing. Asked for by handle, because a sample rides the
* connection the terminal already has: there is nothing to sample without one.
diff --git a/apps/desktop/src/lib/backend/errorCodes.ts b/apps/desktop/src/lib/backend/errorCodes.ts
index b1be38e9..b6afadc9 100644
--- a/apps/desktop/src/lib/backend/errorCodes.ts
+++ b/apps/desktop/src/lib/backend/errorCodes.ts
@@ -23,6 +23,8 @@ export const ERROR_CATALOG = {
"SSH-KEY-UNSUPPORTED": "errors.ssh.keyUnsupported",
// RDP
"RDP-LAUNCH-FAILED": "errors.rdp.launchFailed",
+ // The desktop workbench
+ "WORKBENCH-POWER-FAILED": "errors.workbench.powerFailed",
// Terminal transports that are not SSH
"TERMINAL-UNREACHABLE": "errors.terminal.unreachable",
"TERMINAL-SERIAL-FAILED": "errors.terminal.serialFailed",
diff --git a/apps/desktop/src/lib/backend/tauri.ts b/apps/desktop/src/lib/backend/tauri.ts
index d80a0a9a..55c4d2c0 100644
--- a/apps/desktop/src/lib/backend/tauri.ts
+++ b/apps/desktop/src/lib/backend/tauri.ts
@@ -102,6 +102,7 @@ import type {
TransferInfo,
UploadAnswer,
UploadOutcome,
+ WorkbenchPowerOutcome,
VaultArchive,
VaultState,
ZmodemEvent,
@@ -931,6 +932,21 @@ export function desktopOpen(sessionId: string): Promise {
return invoke("desktop_open", { sessionId });
}
+/**
+ * Runs one workbench power action for a Linux desktop session.
+ *
+ * The acknowledgement travels with the call rather than being implied: what it says is that a person
+ * answered the question in front of them, which is exactly what the policy gate is allowed to act on.
+ */
+export function workbenchPower(
+ sessionId: string,
+ handle: string,
+ action: string,
+ acknowledged: boolean,
+): Promise {
+ return invoke("workbench_power", { sessionId, handle, action, acknowledged });
+}
+
export function tunnelsOpen(): Promise {
return invoke("tunnels_open");
}
diff --git a/apps/desktop/src/types/session.ts b/apps/desktop/src/types/session.ts
index c1cbdcc7..fb2587d2 100644
--- a/apps/desktop/src/types/session.ts
+++ b/apps/desktop/src/types/session.ts
@@ -102,6 +102,8 @@ export interface Session {
readonly terminal: TerminalSettings;
/** What a remote desktop asks of the system client. Absent on SSH sessions and older exports. */
readonly desktop?: DesktopSettings;
+ /** What the desktop workbench draws. Absent on every other protocol and on older exports. */
+ readonly workbench?: WorkbenchSettings;
/** What a Telnet console expects on the wire. Absent on every other protocol. */
readonly telnet?: TelnetSettings;
/** The serial port and its line parameters. Absent on every other protocol. */
@@ -135,6 +137,12 @@ export interface DesktopSettings {
redirectDrives: boolean;
}
+/** What the desktop workbench draws. Nothing here was typed into a terminal. */
+export interface WorkbenchSettings {
+ /** Which built-in backdrop the workbench draws. Absent asks for the interface's own default. */
+ readonly wallpaper?: string;
+}
+
/** What the Enter key puts on a Telnet wire: the teletype pair, a bare CR, or a bare LF. */
export type EnterMode = "crlf" | "cr" | "lf";
@@ -387,6 +395,11 @@ export type SftpOutcome =
readonly packed: boolean;
};
+/** What a workbench power action answered: the command left, or it did not. */
+export interface WorkbenchPowerOutcome {
+ readonly issued: boolean;
+}
+
export type TransferDirection = "download" | "upload";
export type TransferState =
From fc5046cb76a065eba104ba7f81ad88de49c3768f Mon Sep 17 00:00:00 2001
From: SongRenShuo <3064597532@qq.com>
Date: Wed, 18 Nov 2026 02:05:59 +0800
Subject: [PATCH 007/440] feat(sessions): the editor's draft carries the
workbench backdrop choice
The session editor now holds which built-in wallpaper a linuxDesk session's
workbench draws. The draft reads `session.workbench.wallpaper` when it is
filled and writes it back only on a session whose descriptor claims the
workbench capability, so SSH and every other kind save no workbench block at
all; no choice saves as nothing on the wire, which is what every session
written before the choice existed already means.
- types: Session gains `workbench` mirroring the Rust wire type (the TS
interface was the one place the field had not landed)
- sessionEditor: `workbenchWallpaper` draft state, `isWorkbench` from the
descriptor capability, draft write-back
- editor enablement: the plan's "zero editor changes" premise did not hold -
linuxDesk is added to the endpoint and user questions and to the public-key
rule, since a session with no host field would save unusable
- spec: the saved wallpaper reads back into the draft, no choice and a
non-workbench protocol produce no field, a reopened editor restores the
choice; red-probed (3 failed with write-back removed, 22/22 with it)
---
apps/desktop/src/stores/sessionEditor.spec.ts | 54 +++++++++++++++++++
apps/desktop/src/stores/sessionEditor.ts | 48 +++++++++++++++--
apps/desktop/src/types/session.ts | 14 +++++
3 files changed, 112 insertions(+), 4 deletions(-)
diff --git a/apps/desktop/src/stores/sessionEditor.spec.ts b/apps/desktop/src/stores/sessionEditor.spec.ts
index d9dd60ec..b9585c0d 100644
--- a/apps/desktop/src/stores/sessionEditor.spec.ts
+++ b/apps/desktop/src/stores/sessionEditor.spec.ts
@@ -461,4 +461,58 @@ describe("session editor store", () => {
expect(editor.kubeContextsFailure?.code).toBeTruthy();
expect(editor.kubeContextsBusy).toBe(false);
});
+
+ it("reads a workbench session's saved wallpaper into the draft and saves the choice back", () => {
+ const editor = useSessionEditorStore();
+ editor.fill({
+ ...sample("lab", "lab"),
+ protocol: "linuxDesk",
+ workbench: { wallpaper: "aurora" },
+ });
+
+ expect(editor.isWorkbench).toBe(true);
+ expect(editor.workbenchWallpaper).toBe("aurora");
+ expect(editor.draft().workbench).toEqual({ wallpaper: "aurora" });
+
+ // Another choice saves under its own id, and "no choice" saves as nothing at all: the field
+ // the wire document omits is the one every older session already means by its absence.
+ editor.workbenchWallpaper = "forest";
+ expect(editor.draft().workbench).toEqual({ wallpaper: "forest" });
+ editor.workbenchWallpaper = "";
+ expect(editor.draft().workbench).toBeUndefined();
+ });
+
+ it("carries no workbench block on a protocol the workbench does not apply to", () => {
+ const editor = useSessionEditorStore();
+ editor.fill(sample("ssh-host", "ssh-host"));
+
+ // A value held from a draft that was on a workbench kind is not written onto another kind —
+ // the same rule the container and cluster blocks follow. Switching back brings it out again.
+ editor.workbenchWallpaper = "aurora";
+ expect(editor.isWorkbench).toBe(false);
+ expect(editor.draft().workbench).toBeUndefined();
+
+ editor.setProtocol("linuxDesk");
+ expect(editor.draft().workbench).toEqual({ wallpaper: "aurora" });
+ editor.setProtocol("ssh");
+ expect(editor.draft().workbench).toBeUndefined();
+ });
+
+ it("restores the wallpaper when the editor reopens on the saved session", async () => {
+ const library = useSessionsStore();
+ const editor = useSessionEditorStore();
+ editor.fill({ ...sample("lab", "lab"), protocol: "linuxDesk" });
+ editor.workbenchWallpaper = "dawn";
+
+ await library.save(editor.draft());
+ const saved = sessionSaveMock.mock.calls[0]?.[0];
+ expect(saved?.workbench).toEqual({ wallpaper: "dawn" });
+
+ // A reopening draft starts from nothing and reads the choice back out of the saved session.
+ editor.fill(null);
+ expect(editor.workbenchWallpaper).toBe("");
+ const reopened = library.sessions.find((session) => session.id === "lab");
+ editor.fill(reopened ?? null);
+ expect(editor.workbenchWallpaper).toBe("dawn");
+ });
});
diff --git a/apps/desktop/src/stores/sessionEditor.ts b/apps/desktop/src/stores/sessionEditor.ts
index 9100f14e..0d6e81c8 100644
--- a/apps/desktop/src/stores/sessionEditor.ts
+++ b/apps/desktop/src/stores/sessionEditor.ts
@@ -17,7 +17,13 @@ import { backend } from "@/lib/backend/api";
import { type ShellError, asShellError } from "@/lib/backend/errors";
import { useSessionsStore } from "@/stores/sessions";
import type { ContainerRuntime, ContainerSettings, ContainerTransport } from "@/types/container";
-import { PROTOCOLS, protocolById, type AuthMethodId, type Protocol } from "@/types/generated/protocols";
+import {
+ PROTOCOLS,
+ protocolById,
+ protocolSupports,
+ type AuthMethodId,
+ type Protocol,
+} from "@/types/generated/protocols";
import type { KubeconfigSource, KubeContextInfo, KubernetesSettings } from "@/types/k8s";
import type {
BackspaceMode,
@@ -249,6 +255,16 @@ export const useSessionEditorStore = defineStore("sessionEditor", () => {
const desktopFullscreen = ref(DEFAULT_DESKTOP.fullscreen);
const desktopDrives = ref(DEFAULT_DESKTOP.redirectDrives);
+ /**
+ * Which built-in backdrop the workbench draws for this machine, as the session's choice names it.
+ *
+ * Empty is "no choice", which saves as nothing at all: an absent field is what every session
+ * written before the choice existed carries, and the interface's default is what both of those
+ * mean. The ids are the four the workbench pane draws; anything else the wire may carry is not
+ * offered here, but a session that names one keeps it rather than being quietly rewritten.
+ */
+ const workbenchWallpaper = ref("");
+
/** The Telnet keyboard translation, which is the whole of what a console can be configured with. */
const telnetEnter = ref(DEFAULT_TELNET.enter);
const telnetBackspace = ref(DEFAULT_TELNET.backspace);
@@ -311,18 +327,30 @@ export const useSessionEditorStore = defineStore("sessionEditor", () => {
protocol.value === "rawTcp" ||
protocol.value === "rdp" ||
protocol.value === "webdav" ||
- protocol.value === "ftp",
+ protocol.value === "ftp" ||
+ // A workbench session rides the SSH open path, so it is reached the same way.
+ protocol.value === "linuxDesk",
);
/** Whether this connection has a person to name. Only SSH, RDP, WebDAV and FTP do. */
const needsUser = computed(
() =>
- protocol.value === "ssh" || protocol.value === "rdp" || protocol.value === "webdav" || protocol.value === "ftp",
+ protocol.value === "ssh" ||
+ protocol.value === "rdp" ||
+ protocol.value === "webdav" ||
+ protocol.value === "ftp" ||
+ protocol.value === "linuxDesk",
);
/** Whether SSH's authentication, route and forwarding sections apply. */
const isSsh = computed(() => protocol.value === "ssh");
+ /**
+ * Whether the desktop workbench section applies: the protocol descriptor claims the capability,
+ * so a protocol that gains it later lights the section up without this store learning its name.
+ */
+ const isWorkbench = computed(() => protocolSupports(protocol.value, "workbench"));
+
/** Whether the remote-desktop display section applies. */
const isRdp = computed(() => protocol.value === "rdp");
@@ -375,7 +403,9 @@ export const useSessionEditorStore = defineStore("sessionEditor", () => {
// has to be answered, and even that can be left for an anonymous server.
user: needsUser.value && !isWebDav.value && user.value.trim() === "",
port: needsEndpoint.value && !isWebDav.value && !validPort(port.value, 1),
- key: isSsh.value && method.value === "publicKey" && !attachedKey.value?.keyRef,
+ // A workbench session signs in the way SSH does, so a public-key choice there is as incomplete
+ // without a key as it is on SSH itself.
+ key: (isSsh.value || isWorkbench.value) && method.value === "publicKey" && !attachedKey.value?.keyRef,
serialPort: protocol.value === "serial" && serialPort.value.trim() === "",
serialBaud: protocol.value === "serial" && !validBaud(serialBaud.value),
// An engine on another machine is reached through a saved session; an empty id has no route.
@@ -460,6 +490,10 @@ export const useSessionEditorStore = defineStore("sessionEditor", () => {
desktopHeight.value = String(desktop.height);
desktopFullscreen.value = desktop.fullscreen;
desktopDrives.value = desktop.redirectDrives;
+ // The wallpaper is read whatever the protocol is, and only written back onto a session whose
+ // descriptor claims the workbench: a value held for one kind survives a switch away and back,
+ // the way the SSH-only fields do.
+ workbenchWallpaper.value = session?.workbench?.wallpaper ?? "";
const telnet = session?.telnet ?? DEFAULT_TELNET;
telnetEnter.value = telnet.enter;
telnetBackspace.value = telnet.backspace;
@@ -563,6 +597,10 @@ export const useSessionEditorStore = defineStore("sessionEditor", () => {
fullscreen: desktopFullscreen.value,
redirectDrives: desktopDrives.value,
},
+ // Only a protocol whose descriptor claims the workbench carries a backdrop, and no choice is
+ // no field: an empty workbench block on the wire would be a section the reader must ignore.
+ workbench:
+ isWorkbench.value && workbenchWallpaper.value !== "" ? { wallpaper: workbenchWallpaper.value } : undefined,
telnet: { enter: telnetEnter.value, backspace: telnetBackspace.value },
serial: {
port: serialPort.value.trim(),
@@ -686,6 +724,7 @@ export const useSessionEditorStore = defineStore("sessionEditor", () => {
desktopHeight,
desktopFullscreen,
desktopDrives,
+ workbenchWallpaper,
telnetEnter,
telnetBackspace,
serialPort,
@@ -702,6 +741,7 @@ export const useSessionEditorStore = defineStore("sessionEditor", () => {
needsEndpoint,
needsUser,
isSsh,
+ isWorkbench,
isRdp,
isWebDav,
isFtp,
diff --git a/apps/desktop/src/types/session.ts b/apps/desktop/src/types/session.ts
index c1cbdcc7..f0078f22 100644
--- a/apps/desktop/src/types/session.ts
+++ b/apps/desktop/src/types/session.ts
@@ -102,6 +102,8 @@ export interface Session {
readonly terminal: TerminalSettings;
/** What a remote desktop asks of the system client. Absent on SSH sessions and older exports. */
readonly desktop?: DesktopSettings;
+ /** How the desktop workbench draws this machine. Only a `linuxDesk` session reads it. */
+ readonly workbench?: WorkbenchSettings;
/** What a Telnet console expects on the wire. Absent on every other protocol. */
readonly telnet?: TelnetSettings;
/** The serial port and its line parameters. Absent on every other protocol. */
@@ -125,6 +127,18 @@ export interface Session {
readonly updatedAt: number;
}
+/**
+ * How the desktop workbench draws this machine.
+ *
+ * The ids are a contract shared with the workbench pane: the editor offers them and the pane draws
+ * them, so neither may rename one without the other. The wire type carries a plain string, and an
+ * id a build does not know is that build's default backdrop rather than an error.
+ */
+export interface WorkbenchSettings {
+ /** Which built-in backdrop the workbench draws. Absent means the interface's default. */
+ readonly wallpaper?: string;
+}
+
/** The fields the RDP editor groups under "display" and "mapping". */
export interface DesktopSettings {
/** Window size in pixels; ignored when `fullscreen` is on. */
From 90e8b4cc888b02dd6fb48212817eaf627a590588 Mon Sep 17 00:00:00 2001
From: SongRenShuo <3064597532@qq.com>
Date: Wed, 18 Nov 2026 02:06:04 +0800
Subject: [PATCH 008/440] feat(sessions): the editor shows the workbench
section for linuxDesk
A linuxDesk session now picks its workbench wallpaper in the connection
editor: a select beside the other per-protocol sections, offering the
interface default and the four built-in backdrops (aurora, dawn, forest,
plain) - the id contract the workbench pane draws. The section is gated on
the protocol descriptor claiming the workbench capability, not on a
hard-coded protocol name.
The protocol picker places linuxDesk in the desktop group, whose heading
becomes "Desktop": the group now holds two things that are not both remote
desktops, and the plan's wording rule keeps "remote desktop" reserved for
the RDP system client. The authentication, jump-host and forwarding sections
light up for linuxDesk for the same reason its descriptor claims those
capabilities; agent forwarding stays SSH-only, which is why the descriptor
leaves it unclaimed.
i18n: the section's keys in both locales; no window.confirm/alert involved.
---
.../src/components/sessions/SessionDialog.vue | 46 +++++++++++++++++--
.../desktop/src/i18n/locales/en/sessions.json | 12 ++++-
.../src/i18n/locales/zh-CN/sessions.json | 12 ++++-
3 files changed, 64 insertions(+), 6 deletions(-)
diff --git a/apps/desktop/src/components/sessions/SessionDialog.vue b/apps/desktop/src/components/sessions/SessionDialog.vue
index f438e8c7..7f6001b4 100644
--- a/apps/desktop/src/components/sessions/SessionDialog.vue
+++ b/apps/desktop/src/components/sessions/SessionDialog.vue
@@ -95,7 +95,7 @@ const PROTOCOL_GROUPS: readonly { labelKey: string; protocols: readonly Protocol
{ labelKey: "sessions.editor.protocolGroups.terminal", protocols: ["ssh", "telnet", "rawTcp"] },
{ labelKey: "sessions.editor.protocolGroups.local", protocols: ["local", "wsl", "serial"] },
{ labelKey: "sessions.editor.protocolGroups.files", protocols: ["webdav", "ftp"] },
- { labelKey: "sessions.editor.protocolGroups.desktop", protocols: ["rdp"] },
+ { labelKey: "sessions.editor.protocolGroups.desktop", protocols: ["rdp", "linuxDesk"] },
{ labelKey: "sessions.editor.protocolGroups.containers", protocols: ["container", "kubernetes"] },
];
@@ -183,6 +183,25 @@ function chooseProtocol(value: string): void {
/** The two protocols with a display, a mapping and no terminal on this side. */
const isDesktop = computed(() => editor.protocol === "rdp");
+/**
+ * The built-in backdrops the workbench can draw, in the order somebody meets them.
+ *
+ * The ids are a contract shared with the workbench pane and the session wire type, so they are
+ * spelled here rather than derived from anything: a rename on one side would silently orphan the
+ * choices already saved. The first option is "no choice", which saves as nothing at all.
+ */
+const WORKBENCH_WALLPAPERS: readonly { id: string; labelKey: string }[] = [
+ { id: "aurora", labelKey: "sessions.editor.workbench.wallpaperAurora" },
+ { id: "dawn", labelKey: "sessions.editor.workbench.wallpaperDawn" },
+ { id: "forest", labelKey: "sessions.editor.workbench.wallpaperForest" },
+ { id: "plain", labelKey: "sessions.editor.workbench.wallpaperPlain" },
+];
+
+const workbenchWallpaperOptions = computed(() => [
+ { value: "", label: t("sessions.editor.workbench.wallpaperDefault") },
+ ...WORKBENCH_WALLPAPERS.map((wallpaper) => ({ value: wallpaper.id, label: t(wallpaper.labelKey) })),
+]);
+
/** The sizes the reference dialog offers before somebody types their own. */
const RESOLUTIONS = [
{ width: 1280, height: 1024 },
@@ -592,7 +611,7 @@ async function forgetKey(): Promise {