[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6993YF9MFV0A9HPWMJVNXZC":3,"skill-same:01M6993YF9MFV0A9HPWMJVNXZC":60},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":8,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":18,"categories":19,"keywords":30,"publishedAt":32,"linkOnly":33,"markdownContent":34,"markdownBody":35,"frontMatter":36,"refName":37,"commitSha":38,"skillDirectory":39,"forksCount":40,"repositoryHtmlUrl":41,"repositoryHomepageUrl":17,"ownerHtmlUrl":42,"ownerBlogUrl":43,"ownerDescription":44,"updatedAt":45,"install":46,"resources":59},"01M6993YF9MFV0A9HPWMJVNXZC","dev-gate","开发门禁命令管理","How capsem-gate works and how to add or change a gate command. Use when touching build, test, or release logic, or when a boundary\u002Fprimitive\u002Frecursion\u002Fpurity guard fails.","介绍 capsem-gate 的工作原理，以及如何添加或修改门禁（gate）命令。当涉及构建、测试或发布逻辑，或当边界（boundary）\u002F原语（primitive）\u002F递归（recursion）\u002F纯度（purity）守卫失败时使用。","google\u002Fcapsem","google","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F1342004?v=4","01M698VYEFDM0VJBZDYYJ2T83S","Google","01M69939YZJTP726NQK4NZNB48",186,"Apache-2.0",null,"https:\u002F\u002Fgithub.com\u002Fgoogle\u002Fcapsem\u002Fblob\u002Fmain\u002Fskills\u002Fdev-gate\u002FSKILL.md",[20,25],{"categoryNo":21,"categoryName":22,"taxonomyType":23,"taxonomyTypeDesc":24},"01M8BQ6TQZN6R52WBJ9H8NRMQM","软件开发工程师","PROFESSION","适用职业",{"categoryNo":26,"categoryName":27,"taxonomyType":28,"taxonomyTypeDesc":29},"01M8BSTR9G4A4GZ0VB2DFN9490","开发环境与工具链管理","SCENARIO","使用场景",[31],"dev gate","2026-11-10 10:12:30",false,"---\nname: dev-gate\ndescription: How capsem-gate works and how to add or change a gate command. Use when touching build, test, or release logic, or when a boundary\u002Fprimitive\u002Frecursion\u002Fpurity guard fails.\n---\n\n# The build and release gate\n\nThe justfile dispatches; `build_system\u002Fbuilder\u002Fgate\u002F` decides. No recipe carries a shell\nbody, none exceeds five lines, and both are contract tests rather than\nconventions.\n\n`just test` is **one process, one machine lock, one workspace, one plan**. Its\ndry run reports the current totals; conditional asset staging makes a literal\nstep\u002Faction count depend on machine state. Its exact-source journal is the\nproof both release commands require by default before they tag or dispatch.\nAn explicit operator-approved release `force` waives that local journal while\nretaining source guards, fresh audits and full hosted qualification. The\nunattended nightly scheduler is also exempt (`[release].unattended_channels` in\n[`config\u002Fgate.toml`](..\u002F..\u002Fconfig\u002Fgate.toml); see\n[`RELEASE.md`](..\u002F..\u002FRELEASE.md) section 8). Proof selection is owned by\n`qualificationflow.decide` and `qualificationevidence.find_release_proof`.\n\n## The rule everything else follows from\n\n**A plan action may never invoke `just` or another `capsem-gate` command.**\n\n`GuardedRunner` refuses it at runtime, seeing through `uv run --project build_system --frozen` and `caffeinate\nenv`. This is not style: the machine lock is not reentrant, so every such call\nwas a child waiting out its 7200-second timeout for the lock its own parent\nheld. Twenty-two of them existed, and each read perfectly at the call site —\n`Run([\"just\", \"_sign\"])` looks like naming a step.\n\nWhen you need another command's work, **compose its fragment**:\n\n```python\ndef fragment(plan: Plan, config: GateConfig, *, after: tuple[Step, ...] = ()) -> Step:\n    \"\"\"Add this module's steps to `plan`; return its terminal step.\"\"\"\n```\n\nGroundwork several fragments share uses `plan.shared(...)`, which makes the\nsecond caller a dependant rather than a duplicate. **Pass `after` to the work,\nnot to the shared step** — sequencing shared groundwork behind one of its\nconsumers is a cycle, and one that only appears once two lanes compose.\n\nA fragment that has more than one leaf returns *all* of them. `static` returned\nonly its last, so the phases after it started while a storage release it owned\nwas still outstanding.\n\n## The interpreter comes first\n\n`capsem-gate` is `capsem.gatelaunch:main`, not `capsem.gate.cli:main`. It\nre-execs under a source-keyed `pycache_prefix` **before importing any of\n`capsem.gate`**, and exports `PYTHONPYCACHEPREFIX` so pytest and every other\nchild inherits it. CPython validates a `.pyc` by mtime and size, so two\nsame-length edits inside one timestamp tick leave stale bytecode that still\nlooks current — which produced 74 false failures during one review, and which\nwould otherwise let a release qualify code that is not in the tree.\n\nThe marker is an exact generation identity, not a boolean. A private\nexact-commit checkout inherits the parent process environment, so the launcher\nmust recompute its source key and re-exec when that marker, the exported\nprefix, or the interpreter's live prefix differs. Its generation remains under\nthe outer checkout's repository cache; never trade source isolation for a\nprefix-local cache that disappears with the worktree.\n\nThe complete gate refuses in `source.record` if `CAPSEM_GATE_PYCACHE` is\nabsent. If you drive a full plan from a test, set it.\n\nNothing in `gatelaunch` may import `capsem.gate` at module scope.\n\n## Release state is one indivisible value\n\n`Qualification.from_environment` is read once in `GateCommand.__init__` and\npassed to `artifacts()`, `functional()` and `glowup()`. Three legal shapes —\nlocal, binary release, runtime release — and every partial combination is\nrefused while the plan is being built. **No module below reads\n`CAPSEM_RELEASE_*` itself.** They each did, from a different variable, and a\ndropped `GITHUB_ENV` line built a plan that verified pulled assets against a\nsource-rebuilt package.\n\nIn a test, hand the command an explicit `qualification=` rather than exporting\na variable.\n\n## `execute()` enforces; you inherit it\n\nNever overridden — a contract test fails if a subclass defines it. In order:\n\n1. `plan()` is built with the machine **sealed** (`planseal.sealed()`). Ambient,\n   not per-runner: `release.py` escaped an instance-scoped seal by constructing\n   its own `Runner` inside `plan()`.\n2. `plan.validate(config)` — cycles, declared exclusives, one owner per\n   artifact. Before the lock, so a bad plan costs nothing.\n3. `--graph` \u002F `--dry-run` answered. **Before** `reexec()`, or asking becomes\n   doing.\n4. `reexec()`, outside the lock.\n5. `RunLog.open` → `GuardedRunner` → `held(*resources)` → `plan.run(context)`.\n6. `RunLog` closes, then every recorded command prints its timing summary; complete gates also enforce the config-owned, evidence-derived slowdown ratchet.\n\n## The host kernel owns the network boundary\n\nDuring implementation, prefer minimal native TDD\u002Fregression checks instead of\nrunning gate plans repeatedly. Qualify the full outcome at major phase\nboundaries and before merge\u002Frelease. Routine bounded commands do not take the\nglobal machine lock; use `--machine-lease` only when deliberately selecting\nisolated machine work. An explicit request covers the complete command,\nincluding Python or shell drivers that launch compilers. Complete gate\u002Frelease\nisolation remains authoritative.\n\nCompiler lifetime is independent: known compiler commands automatically share\nthe compiler cache, and opaque build drivers select `--compiler-cache` without\nserializing their work on the machine lock. Startup uses the short cache-owned\nstartup lock. Reaping and final server shutdown require exclusive cache use,\nso a gate cannot terminate a concurrent focused compiler's server.\n\nCandidate, both release commands, and directly invoked private test modules\nrun under Bubblewrap on Linux or Seatbelt on macOS. Linux receives loopback and\nthe configured UNIX sockets but no external interface; macOS uses the generated\nprofile. Linux `report` mode is deliberately refused because it cannot produce\nthe Seatbelt-style attempted-egress ledger.\n\n`GateCommand` computes its effective typed sandbox mode once and exports it to\nordinary actions through the config-owned environment name. Outside-sandbox\nactions clear it. Host Doctor combines owning-command policy with live kernel\nstate; the machine-lock marker proves only lock ownership, never enforcement.\nCandidate produces the complete local qualification journal required by the\npublic release commands under the policy above. Those commands then dispatch\nindependent hosted qualification. All three accept only `enforce`: explicit\n`off` or `report` is\nrefused before plan construction, re-exec, or resource acquisition. Measure a\nchanging rule through an incomplete module, whose evidence cannot qualify.\n\nA release cannot resolve or publish while trapped in that namespace, so it\nstarts one authenticated helper immediately before re-exec. Only `Run` and\n`Script` actions declared with `outside_sandbox=True` receive that runner. The\nmode-0600 metadata is consumed and deleted before the first plan action, and\nthe helper owns no plan, lock, workspace, or release state. Its commands still\npass through the same `GuardedRunner`, step log, journal, watcher checkpoints,\nand re-entry refusal.\n\nExact guest base-image pulls are not helper egress. They are individually\nrecorded Docker CLI actions that materialize per-platform child manifests\nthrough the already-declared Docker-daemon container-fetch boundary before the\nsealed asset lanes consume them.\n\nThe allowed edges are exact and contract-tested: the shared fast module's\nOSV dependency and strict RustSec actions; binary `channel-source`; both\nbinary `precheck`; `source.remote-main` and `source.publish-ref`; and each final\n`release` step. The advisory authorities\nare mutable security inputs and therefore cannot be replaced by locked package\nprefetch. Never hand the external runner to any other qualification work.\nRelease CI downloads immutable inputs and materializes locked dependencies\nbefore invoking its sandboxed modules.\n\nThe fast graph owns pinned documentation-scanner preparation through its narrow\negress capability before the docs consumer runs. Prove the cold-cache path;\na warm developer cache once hid a download attempted inside Bubblewrap. Sealed\ndocs generation uses retained GitHub evidence, while ordinary publication\nrefreshes it and checks out complete Git history.\n\nNative supervisor restart uses its existing glow-up owner because supervisor\nsetup must precede inherited privilege confinement. Linux then runs the SDK\nworker as the original user with `no_new_privs` in a loopback-only namespace;\nsee `\u002Fdev-testing`'s `..\u002Fdev-testing\u002Freferences\u002Flocal-ci-parity.md`. Never run sudo after\nthat restriction or disable it to make setup work.\n\n## Declaring a command\n\n```python\nclass MyCommand(GateCommand, name=\"my-command\", help=\"one line for --help\"):\n    exclusive = True   # default is False; anything that WRITES needs True\n    records = True     # False only for commands that read runs\n\n    def resources(self):        # acquired in order, released in reverse\n        return (Workspace(self._config),)\n\n    def plan(self) -> Plan:\n        plan = Plan(self.name)\n        fragment(plan, self._config)\n        return plan\n```\n\nAdd the module to `COMMAND_MODULES` in `cli.py`.\n\n**`exclusive` is about cross-process safety.** `[execution.exclusives]` entries\nare `threading.Lock`s: they order steps inside one plan and coordinate nothing\nbetween two `capsem-gate` processes. `just _sign` in one terminal could replace\nthe codesigned binaries a qualification in another was executing.\n\nDirect commands retain finite timeout and process-tree cleanup without a\nglobal lease. An explicit `--machine-lease` selects `boundedlease` for the\nprograms and command prefixes in `[locks.bounded]`, seen through `env` and\nassignments. Inside a gate run it reuses the parent's isolation rather than\nwaiting for its own lock. Routine compilation and focused TDD use the default\nunleased path; phase qualification retains the gate's machine isolation.\n\nThe machine `flock` and holder record are config-owned user-home paths, never\ncheckout-relative paths. Every linked worktree, clone, and detached full-SHA\nprefix shares the service home, Docker\u002FColima daemon, ports, and signing state;\ngiving each tree a lock inode is equivalent to having no machine lock.\n\n## Step or resource?\n\nThe question is *when it must happen*.\n\n| | |\n|---|---|\n| **Step** | Work. Skipped when its dependency fails — which is right: it was written against something that was never produced. |\n| **Resource** | Anything that must happen on **every** path including the aborted one. `held` releases in reverse; `preserve` runs on failure *before* release, because release destroys the evidence. |\n\nThe orphan-process count, the Colima lifecycle and the failure-evidence capture\nare resources. The source-state check is a pair of steps — it must *not* run\nwhen the gate failed, because the failure is the report.\n\n## Everything is data\n\nEvery path, filename, architecture, channel **and environment variable name**\ncomes from `config\u002Fgate.toml`. `build_system\u002Ftests\u002Fgate\u002Ftest_gate_has_no_literal_data.py` catches\nliterals on both sides — a name read *and* a name used as a key in an\nenvironment you hand to a process. Standard conventions (`HOME`, `TMPDIR`,\n`PKG_CONFIG_PATH`, `HOST_UID`) are allowlisted; Capsem rails are not.\n\nReach for the builders rather than assembling dictionaries:\n`config.environment.capsem(home=…, run_dir=…)`,\n`config.environment.content(assets=…)`, and the typed families\nunder `[environment.package]`, `[environment.release_site]`,\n`[environment.install_proof]`.\n\nTreat the runtime assets as one typed `RuntimeContent` root. Pass that value\nthrough composed package\u002Finstall\u002Fglow-up fragments; never rediscover it from\nambient variables or mutable\ncheckout selectors at a Docker\u002FColima boundary.\n\nMachine effects and stable lifecycle labels are closed `StrEnum` vocabularies.\nConstructor seams accept those enum types, not `str`, and reject dynamic raw\nstrings at runtime. Keep a negative Ty fixture proving the wrong string does\nnot type-check; never widen the signature or raise the diagnostic ratchet to\nmake a new call fit. This is a correctness boundary: BuildKit and container\nnetwork modes once shared strings and sent `bridge` to `docker build`.\n\n## Secrets are declared on the invocation\n\nA `Command` that names credentials in `secret_env` cannot render them — not\nthrough `str()`, not in the journal, not in the exception a failure raises. The\nname survives, the value becomes `\u003Credacted>`, and `evidence_argv` scrubs the\nvalue out of argv too. Docker gets `-e NAME` and takes the value from its own\nenvironment, because argv is readable through `ps` and no log filter covers\nthat.\n\n## Every `Call` says why it is one\n\n`Call` renders as prose, so a plan built from them says less. Pass\n`why=Why.SECRETS` (one phase earns this: the package build), `Why.DYNAMIC`\n(argv known only at run time) or `Why.COMPUTATION` — the last is a to-do,\nnot a design, and usually wants to become a named action.\n\n## Stopping a run\n\n`cancellation.check(\"what you are doing\")` at points a partial unit can be\nabandoned from — between files, between chunks, never mid-write. Ctrl-C sets\nthe switch, cancels pending steps, and waits the config-owned grace before naming\nwhat refused to stop. `planrunner` explicitly hands workers the switch. Foreground\ncommands are exact owned process trees; only `Runner.launch` may outlive an action.\n\n## Asking without running\n\n```bash\nuv run --project build_system --frozen capsem-gate \u003Ccommand> --dry-run    # every step, every action, real argv\n```\n```bash\nuv run --project build_system --frozen capsem-gate \u003Ccommand> --graph      # the same graph as mermaid\n```\n```bash\nuv run --project build_system --frozen capsem-gate runs last --failed     # what broke, where, how long\n```\n```bash\nuv run --project build_system --frozen capsem-gate runs digest            # the cross-run state, and what to do\n```\n```bash\nuv run --project build_system --frozen capsem-gate runs trend --step \u003Clabel>   # one step, run by run\n```\n```bash\njust cache stats --offline                                                # every disk cache owner and contract\n```\n\nInspection does not record a gate run: `runs last` used to open a run and\nrepoint `latest` at the question. Read `\u002Fdev-cache` for cache mutation commands.\n\n## The private copy is cloned, not copied\n\nCommands with `private_checkout` work from a copy under `cache\u002Fworktrees\u002F\u003Chash>`. The\nworking tree is copied; the *repository* is cloned with `git clone --local\n--no-checkout`, then `read-tree HEAD` fills the index.\n\nCloned rather than copied because `.git` is a directory in a normal checkout\nand a *file* in a linked worktree, holding an absolute `gitdir:` path back to\nthe original. Carrying that file left the copy attached to live metadata, so a\ncommit in the original moved the supposedly private HEAD -- and the answer used\nto be a flat refusal, which made the gate unrunnable from a worktree. Worktrees\nare how an agent gets an isolated tree, so the isolation machinery was refusing\nto run for exactly the people it exists for.\n\nThe clone costs ~200ms against a 108 MB `.git` and is *faster* than the `cp -R`\nit replaced: `--local` hardlinks the object store. There is no `alternates`\nfile, so a `gc` in the original cannot prune bytes out from under a running\ngate, and the copy owns its HEAD and refs -- which is the property the refusal\nwas protecting.\n\nIf you add something that needs git inside the prefix, it needs the index:\n`git ls-files` and `git check-ignore` read it, and `faults`, `auditfs` and\n`sourcestate` all depend on them.\n\n## The plan is a graph, and it says what it is\n\nEvery step declares `kind`, `needs`, `arch`, `speed` and `concurrency`;\nevery edge declares `Requires`. `workgraph.from_plan` turns a `Plan` into a\ntyped DAG, and the questions get asked there rather than of source text.\n\nAsk the graph, not the file. `uv run --project build_system --frozen capsem-gate runs schedule \u003Ccommand>`\nreports the binding set -- the nodes with no slack, whose cost *is* the run's\ncost, which is not the same as the list of slowest steps.\n\nThree rules when adding a step:\n\n- `needs` is a set, and `NETWORK` must agree with whether any action is\n  `outside_sandbox`. Hermeticity is derived from it over `ARTIFACT` edges, and\n  is never declared: a flag would let a step claim a property its inputs\n  contradict.\n- a capability that must not be shared (`DOCKER`, `VM`, `KVM`) needs a matching\n  `contends`. `static.guest-agents` drove the daemon without claiming it and\n  could have raced `install.materialize`.\n- `speed` is relative to what the lane protects, not a second count. A\n  two-minute step in a four-minute lane guarding a two-hour run is the trade\n  that lane exists to make.\n\n`tests\u002Fcitadel\u002Ftest_work_graph_invariants.py` holds all of it.\n\n## History outlives the run directories\n\n`keep_runs` is twenty, so every longitudinal question -- is this getting\nslower, does that keep failing, did the change help -- used to be answerable\nonly across whatever rotation had not reached. `cache\u002Ftarget\u002Fgate-runs\u002Fledger.jsonl`\nkeeps one distilled row per finished run instead: identity, plan-shape digest,\nand each step's duration and status. A couple of kilobytes, kept for months.\n\n`fast.digest` rebuilds `DIGEST.md` from it at the start of the fast phase, and\n`RunLog.close` rebuilds it again with the finished run included. Close is\nbest-effort on purpose -- it runs on the failure path, where raising would\nreplace the error somebody needs -- and the fast-phase step is the half that is\nallowed to fail.\n\nTwo rules when reading or extending it. Durations are comparable only under\n`runledger.identity` (same command, argv, host class and plan shape), which is\nthe one definition the release ratchet also uses. And a step whose status is\n`skipped` or `carried` records a near-zero duration that is not a measurement:\n`LedgerRow.measured` is how you ask, and taking `duration_ms` directly is how\na median comes to report a build that never ran as the fastest on record.\n\n## The guards that will fail you\n\n| Test | What it holds |\n|---|---|\n| `test_gate_execute_funnel.py` | recursion refused; every subprocess logged; plan construction inert; isolation from acquired resources |\n| `test_gate_no_nested_commands.py` | the same recursion rule statically, plus every named recipe and subcommand resolves |\n| `test_gate_boundary.py` | no shell bodies; ≤5 recipe lines; ≤300 module lines; `ty` strict |\n| `citadel\u002Ftest_shape_boundaries.py` | every `[boundary.*]` source ceiling and its exact debt inventory |\n| `test_gate_primitives_are_the_only_way.py` | only the harness touches the machine; only `planrunner` schedules |\n| `test_gate_has_no_literal_data.py` | no path, architecture or channel spelled in code |\n| `test_gate_hardening.py` | mutation is exclusive; plans are pure; verifications ask the real question |\n| `test_gate_runlog_evidence.py` | attribution under concurrency; run status; non-recording inspection |\n| `test_gate_lifecycle.py` | acquire order, reverse release, preserve first, primary error survives cleanup |\n| `test_gate_qualification.py` | the three legal release states; every partial one refused |\n| `test_gate_secrets.py` | no signing material in argv, journal, summaries or errors |\n| `test_gate_source_identity.py` | the launcher; stale bytecode cannot be qualified |\n| `test_gate_step_output.py` | each step keeps what its commands printed |\n| `test_gate_cancellation.py` | Ctrl-C stops pending, running and waiting work |\n| `test_just_argument_boundary.py` | every recipe parameter crosses one exact argv boundary |\n| `test_gate_candidate.py` | the source state belongs to a run; observing a plan leaves the checkout alone |\n| `test_gate_sandbox.py` | Bubblewrap\u002FSeatbelt policy and the authenticated one-time release egress boundary |\n| `test_gate_release_isolation.py` | only the named release edges may render outside the kernel sandbox |\n\n## Testing a command\n\n`tests\u002Fhelpers\u002Fgate.py` is the one place that knows how to interrogate the\ngate. Assert **edges**, not positions.\n\n`gate_issued()` reads back real argv by *running* the plan against a recording\nrunner. That stubs subprocesses and nothing else, so it passes\n`observing=True` and every primitive that touches the machine honours it. Any\nnew primitive that writes, deletes, links or hashes must check\n`context.observing` first -- otherwise interrogating a plan mutates the\ncheckout a gate may be holding. `RecordSourceState` learned this the expensive\nway: it overwrote the running gate's own state file with the recorder's empty\noutput, and `source.verify` -- the last step of a forty-minute run -- reported\na HEAD change on a tree nobody had touched.\n\nThe same rule applies to any contract that builds a plan from the real config\nand runs it: pass `observing=True`. `tests\u002Fconftest.py` fails the test that\nrewrites `cache\u002Fstate\u002Fgate-source.json`, so the next one to forget finds out\nin seconds rather than at `source.verify`.\n\n| | |\n|---|---|\n| `RecordingRunner` | records what a plan would run, for a test that drives its own plan |\n| `gate_plan(name)` | a built plan; `after_of(label)` is how \"these run in parallel\" is asserted |\n| `gate_labels(name)` | its step labels in graph order, for ordering claims |\n| `gate_issues(name)` | real argv for everything a command would issue -- `None` reads the whole gate |\n\nAll three are cached. Contracts that used to grep the `justfile` for a command\nuse `gate_issues`; contracts about ordering use `gate_labels`. Do not grow a\nlocal copy of these in a test file -- eight files did during the port, and the\ncopies drifted.\n\nTwo lessons paid for here:\n\n**The double is not the thing.** `Resource.environment` is a method;\n`Workspace.environment` was a property. Every funnel test passed because they\nused a recorder written to match the protocol, and the one resource every\nisolated command actually holds raised `TypeError`. Guards should walk the real\nsubclasses.\n\n**A guard built from the current state asserts nothing.** The exclusivity guard\npassed on first write because I listed what was already non-exclusive. Write the\nclaim, watch it fail, then make it true.\n\nBreak every guard once and watch it go red. Clear `__pycache__` between runs.\n\n## Shell is linted on every surface it lives on\n\n`fast.audit.shell` runs ShellCheck over three surfaces, each failing closed:\ntracked `*.sh`, every workflow `run:` body, and every Dockerfile `RUN` body --\nincluding the `.j2` templates, **rendered** through `render_dockerfile` rather\nthan masked, because the rendered output is what builds.\n\n`capsem.gate.shellsurfaces` extracts all three, and the Citadel's shape guard\nmeasures the same bodies, so the linter and the ceiling cannot disagree about\nwhat a body is. Getting that extraction right took five attempts -- flattened\ncontinuations swallowing comments, comments stripped after continuations\ninstead of before, `${{ }}` masked to a literal producing three phantom SC2050\n\"bugs\", Jinja masked instead of rendered, and a dict key that silently dropped\nfive steps into a collision. Add a surface there, not in a second extractor.\n\n`[boundary.shell_bodies]` keeps them simple: 20 executable lines, with an exact\ndebt inventory. The fix for an oversized body is an owned boundary under\n`build_system\u002Fscripts\u002F`, which ShellCheck already lints and a test can call.\n\n## Shell is parsed, not matched\n\n`shelllex` tokenises, `shellparse` builds a tree, `shellnodes` holds the nodes\nand the queries. Ask questions of the tree.\n\nEvery question this repository asks of shell used to be a regular expression,\nand each worked on the case it was written for. `cargo` in a filename, in a\ncomment, on the left of an assignment or inside a quoted argument is not\n`cargo` in command position, and no refinement fixes that -- the distinction is\ngrammatical.\n\n```python\ntree = parse(body, origin=\"check-web-surface.sh\")\ncommands(arm_named(tree, \"release-channel\") or [])   # one case arm, exactly\n[c for c in commands(tree) if c.program == \"cargo\"]  # command position only\nsuppressed(tree)                                     # verdicts thrown away\n```\n\n`Command.program` steps over assignment prefixes and wrappers, so\n`CARGO_TARGET_DIR=\u002Ftmp env cargo build` answers `cargo`. Conjunctions are nodes\nrather than a flattened list, because the operator *is* the meaning: `check`\nand `check || true` differ only in an `AndOr`, and that difference once\nsatisfied a release contract while branch protection was off.\n\n**Pass a shell body, not a container of one.** `parse` sniffs and warns when\nhanded a raw `.j2` template, a whole Dockerfile or a workflow -- each lexes\nwithout error and yields confident nonsense. Use `shellsurfaces` to extract:\nit renders templates and pulls `RUN` and `run:` bodies out. Its own guard read\nraw templates on the first attempt and reported a correctly chained\n`make && ls` as two unguarded statements.\n\nIts suite found four bugs in it before any consumer did. Add cases to\n`build_system\u002Ftests\u002Fscripts\u002Ftest_shell_parse.py` when you extend it.\n\nThis applies to tests too: a workflow is parsed as YAML, its `run:` value is\nthen passed to `shelllex`\u002F`shellparse`, and heredocs come from the lexer's\nmetadata. Do not use regex or indentation slicing as a smaller local parser.\nThat creates a second grammar which eventually disagrees on quoting, `printf`,\nor a moved script and turns the release dispatcher into the first real test.\n\n## An exclusion is exact, hashed, and states why\n\nEvery guard eventually meets something it should not fail on. `exclusions.py`\nis the one shape that carve-out may take. Two wrong shapes were tried first,\nand both look reasonable:\n\n- **A count** -- \"this file has nine\". Fails when somebody adds a harmless\n  tenth; passes when somebody turns one of the nine into something dangerous.\n  The number is orthogonal to the risk.\n- **A program name** -- \"`launchctl` is cleanup\". It is, at three call sites,\n  and a real check at a fourth. Four of the five findings that rule produced\n  were its own misclassification.\n\n`Exclusion` carries `subject` and a `reason` with a minimum length; a reason of\n\"known\" or \"legacy\" is refused by the schema. `HashedExclusion` adds a `digest`\nover the **parsed** form, via `canonical(...)`. Hashing the parse is what makes\nit usable: requote, reflow or move the line and the decision stands; change\nwhat it does and it is a new decision that has to be stated.\n\n`reconcile(found, excused)` is symmetric on purpose. A ledger that only refuses\ngrowth is an exemption list wearing a ratchet's name -- the entry that outlives\nthe thing it excused is exactly the failure these guards exist for, and it is\nthe one that never announces itself.\n\nLedgers today: `[[boundary.discarded_verdicts]]`, `[[boundary.sequenced_runs]]`,\n`[boundary.unclaimed_cargo]`.\n\n## The Citadel runs in the fast phase\n\n`tests\u002Fcitadel\u002F` records architectural mistakes that must not be repeated. It\nis source-level -- no artifact, no VM, no daemon -- so it is scheduled beside\nRuff and the source-syntax audit, not in the broad suite. It was reachable only\nthrough the broad suite's `root` for a while, which meant a DB-boundary\nviolation surfaced after the VMs were up rather than in the first seconds.\n\n`tests\u002Fcitadel` is in `broad_ignores`: one collector, so its failures have one\nowner. `citadel\u002Ftest_guard_scheduling.py` fails if it is moved back behind the\nexpensive work.\n\nEvery guard states its reasoning in a named `*_RATIONALE` appended to the\nassertion, so a violation teaches instead of printing a bare comparison. When\nthe reason is already stated somewhere canonical -- `[boundary]`, AGENTS.md, a\nskill -- the rationale cites it rather than restating it; a second wording is a\nsecond thing to keep in step.\n\n| guard | what it holds |\n|---|---|\n| `test_db_boundary.py` | only `capsem-logger` executes ledger queries |\n| `test_shape_boundaries.py` | every `[boundary.*]` ceiling and debt inventory, files and shell bodies alike |\n| `test_workflow_enforcement.py` | a gating step cannot pass while failing |\n| `test_container_workspace.py` | the guest builder's `\u002Fsrc\u002F*` glob skips dotfiles |\n| `test_skill_context_budget.py` | the skill description budget every session pays |\n| `test_hot_build_contract.py` | hot codecs stay optimized in the dev profile |\n| `test_package_architecture_boundary.py` | package and machine architecture never cross |\n| `test_guard_scheduling.py` | the Citadel itself runs before the expensive work |\n\n## See also\n\n`\u002Fdev-just` for the public surface, `\u002Fdev-testing` for the suites,\n`\u002Frelease-process` for what the release lanes must guarantee.\n","# The build and release gate\n\nThe justfile dispatches; `build_system\u002Fbuilder\u002Fgate\u002F` decides. No recipe carries a shell\nbody, none exceeds five lines, and both are contract tests rather than\nconventions.\n\n`just test` is **one process, one machine lock, one workspace, one plan**. Its\ndry run reports the current totals; conditional asset staging makes a literal\nstep\u002Faction count depend on machine state. Its exact-source journal is the\nproof both release commands require by default before they tag or dispatch.\nAn explicit operator-approved release `force` waives that local journal while\nretaining source guards, fresh audits and full hosted qualification. The\nunattended nightly scheduler is also exempt (`[release].unattended_channels` in\n[`config\u002Fgate.toml`](..\u002F..\u002Fconfig\u002Fgate.toml); see\n[`RELEASE.md`](..\u002F..\u002FRELEASE.md) section 8). Proof selection is owned by\n`qualificationflow.decide` and `qualificationevidence.find_release_proof`.\n\n## The rule everything else follows from\n\n**A plan action may never invoke `just` or another `capsem-gate` command.**\n\n`GuardedRunner` refuses it at runtime, seeing through `uv run --project build_system --frozen` and `caffeinate\nenv`. This is not style: the machine lock is not reentrant, so every such call\nwas a child waiting out its 7200-second timeout for the lock its own parent\nheld. Twenty-two of them existed, and each read perfectly at the call site —\n`Run([\"just\", \"_sign\"])` looks like naming a step.\n\nWhen you need another command's work, **compose its fragment**:\n\n```python\ndef fragment(plan: Plan, config: GateConfig, *, after: tuple[Step, ...] = ()) -> Step:\n    \"\"\"Add this module's steps to `plan`; return its terminal step.\"\"\"\n```\n\nGroundwork several fragments share uses `plan.shared(...)`, which makes the\nsecond caller a dependant rather than a duplicate. **Pass `after` to the work,\nnot to the shared step** — sequencing shared groundwork behind one of its\nconsumers is a cycle, and one that only appears once two lanes compose.\n\nA fragment that has more than one leaf returns *all* of them. `static` returned\nonly its last, so the phases after it started while a storage release it owned\nwas still outstanding.\n\n## The interpreter comes first\n\n`capsem-gate` is `capsem.gatelaunch:main`, not `capsem.gate.cli:main`. It\nre-execs under a source-keyed `pycache_prefix` **before importing any of\n`capsem.gate`**, and exports `PYTHONPYCACHEPREFIX` so pytest and every other\nchild inherits it. CPython validates a `.pyc` by mtime and size, so two\nsame-length edits inside one timestamp tick leave stale bytecode that still\nlooks current — which produced 74 false failures during one review, and which\nwould otherwise let a release qualify code that is not in the tree.\n\nThe marker is an exact generation identity, not a boolean. A private\nexact-commit checkout inherits the parent process environment, so the launcher\nmust recompute its source key and re-exec when that marker, the exported\nprefix, or the interpreter's live prefix differs. Its generation remains under\nthe outer checkout's repository cache; never trade source isolation for a\nprefix-local cache that disappears with the worktree.\n\nThe complete gate refuses in `source.record` if `CAPSEM_GATE_PYCACHE` is\nabsent. If you drive a full plan from a test, set it.\n\nNothing in `gatelaunch` may import `capsem.gate` at module scope.\n\n## Release state is one indivisible value\n\n`Qualification.from_environment` is read once in `GateCommand.__init__` and\npassed to `artifacts()`, `functional()` and `glowup()`. Three legal shapes —\nlocal, binary release, runtime release — and every partial combination is\nrefused while the plan is being built. **No module below reads\n`CAPSEM_RELEASE_*` itself.** They each did, from a different variable, and a\ndropped `GITHUB_ENV` line built a plan that verified pulled assets against a\nsource-rebuilt package.\n\nIn a test, hand the command an explicit `qualification=` rather than exporting\na variable.\n\n## `execute()` enforces; you inherit it\n\nNever overridden — a contract test fails if a subclass defines it. In order:\n\n1. `plan()` is built with the machine **sealed** (`planseal.sealed()`). Ambient,\n   not per-runner: `release.py` escaped an instance-scoped seal by constructing\n   its own `Runner` inside `plan()`.\n2. `plan.validate(config)` — cycles, declared exclusives, one owner per\n   artifact. Before the lock, so a bad plan costs nothing.\n3. `--graph` \u002F `--dry-run` answered. **Before** `reexec()`, or asking becomes\n   doing.\n4. `reexec()`, outside the lock.\n5. `RunLog.open` → `GuardedRunner` → `held(*resources)` → `plan.run(context)`.\n6. `RunLog` closes, then every recorded command prints its timing summary; complete gates also enforce the config-owned, evidence-derived slowdown ratchet.\n\n## The host kernel owns the network boundary\n\nDuring implementation, prefer minimal native TDD\u002Fregression checks instead of\nrunning gate plans repeatedly. Qualify the full outcome at major phase\nboundaries and before merge\u002Frelease. Routine bounded commands do not take the\nglobal machine lock; use `--machine-lease` only when deliberately selecting\nisolated machine work. An explicit request covers the complete command,\nincluding Python or shell drivers that launch compilers. Complete gate\u002Frelease\nisolation remains authoritative.\n\nCompiler lifetime is independent: known compiler commands automatically share\nthe compiler cache, and opaque build drivers select `--compiler-cache` without\nserializing their work on the machine lock. Startup uses the short cache-owned\nstartup lock. Reaping and final server shutdown require exclusive cache use,\nso a gate cannot terminate a concurrent focused compiler's server.\n\nCandidate, both release commands, and directly invoked private test modules\nrun under Bubblewrap on Linux or Seatbelt on macOS. Linux receives loopback and\nthe configured UNIX sockets but no external interface; macOS uses the generated\nprofile. Linux `report` mode is deliberately refused because it cannot produce\nthe Seatbelt-style attempted-egress ledger.\n\n`GateCommand` computes its effective typed sandbox mode once and exports it to\nordinary actions through the config-owned environment name. Outside-sandbox\nactions clear it. Host Doctor combines owning-command policy with live kernel\nstate; the machine-lock marker proves only lock ownership, never enforcement.\nCandidate produces the complete local qualification journal required by the\npublic release commands under the policy above. Those commands then dispatch\nindependent hosted qualification. All three accept only `enforce`: explicit\n`off` or `report` is\nrefused before plan construction, re-exec, or resource acquisition. Measure a\nchanging rule through an incomplete module, whose evidence cannot qualify.\n\nA release cannot resolve or publish while trapped in that namespace, so it\nstarts one authenticated helper immediately before re-exec. Only `Run` and\n`Script` actions declared with `outside_sandbox=True` receive that runner. The\nmode-0600 metadata is consumed and deleted before the first plan action, and\nthe helper owns no plan, lock, workspace, or release state. Its commands still\npass through the same `GuardedRunner`, step log, journal, watcher checkpoints,\nand re-entry refusal.\n\nExact guest base-image pulls are not helper egress. They are individually\nrecorded Docker CLI actions that materialize per-platform child manifests\nthrough the already-declared Docker-daemon container-fetch boundary before the\nsealed asset lanes consume them.\n\nThe allowed edges are exact and contract-tested: the shared fast module's\nOSV dependency and strict RustSec actions; binary `channel-source`; both\nbinary `precheck`; `source.remote-main` and `source.publish-ref`; and each final\n`release` step. The advisory authorities\nare mutable security inputs and therefore cannot be replaced by locked package\nprefetch. Never hand the external runner to any other qualification work.\nRelease CI downloads immutable inputs and materializes locked dependencies\nbefore invoking its sandboxed modules.\n\nThe fast graph owns pinned documentation-scanner preparation through its narrow\negress capability before the docs consumer runs. Prove the cold-cache path;\na warm developer cache once hid a download attempted inside Bubblewrap. Sealed\ndocs generation uses retained GitHub evidence, while ordinary publication\nrefreshes it and checks out complete Git history.\n\nNative supervisor restart uses its existing glow-up owner because supervisor\nsetup must precede inherited privilege confinement. Linux then runs the SDK\nworker as the original user with `no_new_privs` in a loopback-only namespace;\nsee `\u002Fdev-testing`'s `..\u002Fdev-testing\u002Freferences\u002Flocal-ci-parity.md`. Never run sudo after\nthat restriction or disable it to make setup work.\n\n## Declaring a command\n\n```python\nclass MyCommand(GateCommand, name=\"my-command\", help=\"one line for --help\"):\n    exclusive = True   # default is False; anything that WRITES needs True\n    records = True     # False only for commands that read runs\n\n    def resources(self):        # acquired in order, released in reverse\n        return (Workspace(self._config),)\n\n    def plan(self) -> Plan:\n        plan = Plan(self.name)\n        fragment(plan, self._config)\n        return plan\n```\n\nAdd the module to `COMMAND_MODULES` in `cli.py`.\n\n**`exclusive` is about cross-process safety.** `[execution.exclusives]` entries\nare `threading.Lock`s: they order steps inside one plan and coordinate nothing\nbetween two `capsem-gate` processes. `just _sign` in one terminal could replace\nthe codesigned binaries a qualification in another was executing.\n\nDirect commands retain finite timeout and process-tree cleanup without a\nglobal lease. An explicit `--machine-lease` selects `boundedlease` for the\nprograms and command prefixes in `[locks.bounded]`, seen through `env` and\nassignments. Inside a gate run it reuses the parent's isolation rather than\nwaiting for its own lock. Routine compilation and focused TDD use the default\nunleased path; phase qualification retains the gate's machine isolation.\n\nThe machine `flock` and holder record are config-owned user-home paths, never\ncheckout-relative paths. Every linked worktree, clone, and detached full-SHA\nprefix shares the service home, Docker\u002FColima daemon, ports, and signing state;\ngiving each tree a lock inode is equivalent to having no machine lock.\n\n## Step or resource?\n\nThe question is *when it must happen*.\n\n| | |\n|---|---|\n| **Step** | Work. Skipped when its dependency fails — which is right: it was written against something that was never produced. |\n| **Resource** | Anything that must happen on **every** path including the aborted one. `held` releases in reverse; `preserve` runs on failure *before* release, because release destroys the evidence. |\n\nThe orphan-process count, the Colima lifecycle and the failure-evidence capture\nare resources. The source-state check is a pair of steps — it must *not* run\nwhen the gate failed, because the failure is the report.\n\n## Everything is data\n\nEvery path, filename, architecture, channel **and environment variable name**\ncomes from `config\u002Fgate.toml`. `build_system\u002Ftests\u002Fgate\u002Ftest_gate_has_no_literal_data.py` catches\nliterals on both sides — a name read *and* a name used as a key in an\nenvironment you hand to a process. Standard conventions (`HOME`, `TMPDIR`,\n`PKG_CONFIG_PATH`, `HOST_UID`) are allowlisted; Capsem rails are not.\n\nReach for the builders rather than assembling dictionaries:\n`config.environment.capsem(home=…, run_dir=…)`,\n`config.environment.content(assets=…)`, and the typed families\nunder `[environment.package]`, `[environment.release_site]`,\n`[environment.install_proof]`.\n\nTreat the runtime assets as one typed `RuntimeContent` root. Pass that value\nthrough composed package\u002Finstall\u002Fglow-up fragments; never rediscover it from\nambient variables or mutable\ncheckout selectors at a Docker\u002FColima boundary.\n\nMachine effects and stable lifecycle labels are closed `StrEnum` vocabularies.\nConstructor seams accept those enum types, not `str`, and reject dynamic raw\nstrings at runtime. Keep a negative Ty fixture proving the wrong string does\nnot type-check; never widen the signature or raise the diagnostic ratchet to\nmake a new call fit. This is a correctness boundary: BuildKit and container\nnetwork modes once shared strings and sent `bridge` to `docker build`.\n\n## Secrets are declared on the invocation\n\nA `Command` that names credentials in `secret_env` cannot render them — not\nthrough `str()`, not in the journal, not in the exception a failure raises. The\nname survives, the value becomes `\u003Credacted>`, and `evidence_argv` scrubs the\nvalue out of argv too. Docker gets `-e NAME` and takes the value from its own\nenvironment, because argv is readable through `ps` and no log filter covers\nthat.\n\n## Every `Call` says why it is one\n\n`Call` renders as prose, so a plan built from them says less. Pass\n`why=Why.SECRETS` (one phase earns this: the package build), `Why.DYNAMIC`\n(argv known only at run time) or `Why.COMPUTATION` — the last is a to-do,\nnot a design, and usually wants to become a named action.\n\n## Stopping a run\n\n`cancellation.check(\"what you are doing\")` at points a partial unit can be\nabandoned from — between files, between chunks, never mid-write. Ctrl-C sets\nthe switch, cancels pending steps, and waits the config-owned grace before naming\nwhat refused to stop. `planrunner` explicitly hands workers the switch. Foreground\ncommands are exact owned process trees; only `Runner.launch` may outlive an action.\n\n## Asking without running\n\n```bash\nuv run --project build_system --frozen capsem-gate \u003Ccommand> --dry-run    # every step, every action, real argv\n```\n```bash\nuv run --project build_system --frozen capsem-gate \u003Ccommand> --graph      # the same graph as mermaid\n```\n```bash\nuv run --project build_system --frozen capsem-gate runs last --failed     # what broke, where, how long\n```\n```bash\nuv run --project build_system --frozen capsem-gate runs digest            # the cross-run state, and what to do\n```\n```bash\nuv run --project build_system --frozen capsem-gate runs trend --step \u003Clabel>   # one step, run by run\n```\n```bash\njust cache stats --offline                                                # every disk cache owner and contract\n```\n\nInspection does not record a gate run: `runs last` used to open a run and\nrepoint `latest` at the question. Read `\u002Fdev-cache` for cache mutation commands.\n\n## The private copy is cloned, not copied\n\nCommands with `private_checkout` work from a copy under `cache\u002Fworktrees\u002F\u003Chash>`. The\nworking tree is copied; the *repository* is cloned with `git clone --local\n--no-checkout`, then `read-tree HEAD` fills the index.\n\nCloned rather than copied because `.git` is a directory in a normal checkout\nand a *file* in a linked worktree, holding an absolute `gitdir:` path back to\nthe original. Carrying that file left the copy attached to live metadata, so a\ncommit in the original moved the supposedly private HEAD -- and the answer used\nto be a flat refusal, which made the gate unrunnable from a worktree. Worktrees\nare how an agent gets an isolated tree, so the isolation machinery was refusing\nto run for exactly the people it exists for.\n\nThe clone costs ~200ms against a 108 MB `.git` and is *faster* than the `cp -R`\nit replaced: `--local` hardlinks the object store. There is no `alternates`\nfile, so a `gc` in the original cannot prune bytes out from under a running\ngate, and the copy owns its HEAD and refs -- which is the property the refusal\nwas protecting.\n\nIf you add something that needs git inside the prefix, it needs the index:\n`git ls-files` and `git check-ignore` read it, and `faults`, `auditfs` and\n`sourcestate` all depend on them.\n\n## The plan is a graph, and it says what it is\n\nEvery step declares `kind`, `needs`, `arch`, `speed` and `concurrency`;\nevery edge declares `Requires`. `workgraph.from_plan` turns a `Plan` into a\ntyped DAG, and the questions get asked there rather than of source text.\n\nAsk the graph, not the file. `uv run --project build_system --frozen capsem-gate runs schedule \u003Ccommand>`\nreports the binding set -- the nodes with no slack, whose cost *is* the run's\ncost, which is not the same as the list of slowest steps.\n\nThree rules when adding a step:\n\n- `needs` is a set, and `NETWORK` must agree with whether any action is\n  `outside_sandbox`. Hermeticity is derived from it over `ARTIFACT` edges, and\n  is never declared: a flag would let a step claim a property its inputs\n  contradict.\n- a capability that must not be shared (`DOCKER`, `VM`, `KVM`) needs a matching\n  `contends`. `static.guest-agents` drove the daemon without claiming it and\n  could have raced `install.materialize`.\n- `speed` is relative to what the lane protects, not a second count. A\n  two-minute step in a four-minute lane guarding a two-hour run is the trade\n  that lane exists to make.\n\n`tests\u002Fcitadel\u002Ftest_work_graph_invariants.py` holds all of it.\n\n## History outlives the run directories\n\n`keep_runs` is twenty, so every longitudinal question -- is this getting\nslower, does that keep failing, did the change help -- used to be answerable\nonly across whatever rotation had not reached. `cache\u002Ftarget\u002Fgate-runs\u002Fledger.jsonl`\nkeeps one distilled row per finished run instead: identity, plan-shape digest,\nand each step's duration and status. A couple of kilobytes, kept for months.\n\n`fast.digest` rebuilds `DIGEST.md` from it at the start of the fast phase, and\n`RunLog.close` rebuilds it again with the finished run included. Close is\nbest-effort on purpose -- it runs on the failure path, where raising would\nreplace the error somebody needs -- and the fast-phase step is the half that is\nallowed to fail.\n\nTwo rules when reading or extending it. Durations are comparable only under\n`runledger.identity` (same command, argv, host class and plan shape), which is\nthe one definition the release ratchet also uses. And a step whose status is\n`skipped` or `carried` records a near-zero duration that is not a measurement:\n`LedgerRow.measured` is how you ask, and taking `duration_ms` directly is how\na median comes to report a build that never ran as the fastest on record.\n\n## The guards that will fail you\n\n| Test | What it holds |\n|---|---|\n| `test_gate_execute_funnel.py` | recursion refused; every subprocess logged; plan construction inert; isolation from acquired resources |\n| `test_gate_no_nested_commands.py` | the same recursion rule statically, plus every named recipe and subcommand resolves |\n| `test_gate_boundary.py` | no shell bodies; ≤5 recipe lines; ≤300 module lines; `ty` strict |\n| `citadel\u002Ftest_shape_boundaries.py` | every `[boundary.*]` source ceiling and its exact debt inventory |\n| `test_gate_primitives_are_the_only_way.py` | only the harness touches the machine; only `planrunner` schedules |\n| `test_gate_has_no_literal_data.py` | no path, architecture or channel spelled in code |\n| `test_gate_hardening.py` | mutation is exclusive; plans are pure; verifications ask the real question |\n| `test_gate_runlog_evidence.py` | attribution under concurrency; run status; non-recording inspection |\n| `test_gate_lifecycle.py` | acquire order, reverse release, preserve first, primary error survives cleanup |\n| `test_gate_qualification.py` | the three legal release states; every partial one refused |\n| `test_gate_secrets.py` | no signing material in argv, journal, summaries or errors |\n| `test_gate_source_identity.py` | the launcher; stale bytecode cannot be qualified |\n| `test_gate_step_output.py` | each step keeps what its commands printed |\n| `test_gate_cancellation.py` | Ctrl-C stops pending, running and waiting work |\n| `test_just_argument_boundary.py` | every recipe parameter crosses one exact argv boundary |\n| `test_gate_candidate.py` | the source state belongs to a run; observing a plan leaves the checkout alone |\n| `test_gate_sandbox.py` | Bubblewrap\u002FSeatbelt policy and the authenticated one-time release egress boundary |\n| `test_gate_release_isolation.py` | only the named release edges may render outside the kernel sandbox |\n\n## Testing a command\n\n`tests\u002Fhelpers\u002Fgate.py` is the one place that knows how to interrogate the\ngate. Assert **edges**, not positions.\n\n`gate_issued()` reads back real argv by *running* the plan against a recording\nrunner. That stubs subprocesses and nothing else, so it passes\n`observing=True` and every primitive that touches the machine honours it. Any\nnew primitive that writes, deletes, links or hashes must check\n`context.observing` first -- otherwise interrogating a plan mutates the\ncheckout a gate may be holding. `RecordSourceState` learned this the expensive\nway: it overwrote the running gate's own state file with the recorder's empty\noutput, and `source.verify` -- the last step of a forty-minute run -- reported\na HEAD change on a tree nobody had touched.\n\nThe same rule applies to any contract that builds a plan from the real config\nand runs it: pass `observing=True`. `tests\u002Fconftest.py` fails the test that\nrewrites `cache\u002Fstate\u002Fgate-source.json`, so the next one to forget finds out\nin seconds rather than at `source.verify`.\n\n| | |\n|---|---|\n| `RecordingRunner` | records what a plan would run, for a test that drives its own plan |\n| `gate_plan(name)` | a built plan; `after_of(label)` is how \"these run in parallel\" is asserted |\n| `gate_labels(name)` | its step labels in graph order, for ordering claims |\n| `gate_issues(name)` | real argv for everything a command would issue -- `None` reads the whole gate |\n\nAll three are cached. Contracts that used to grep the `justfile` for a command\nuse `gate_issues`; contracts about ordering use `gate_labels`. Do not grow a\nlocal copy of these in a test file -- eight files did during the port, and the\ncopies drifted.\n\nTwo lessons paid for here:\n\n**The double is not the thing.** `Resource.environment` is a method;\n`Workspace.environment` was a property. Every funnel test passed because they\nused a recorder written to match the protocol, and the one resource every\nisolated command actually holds raised `TypeError`. Guards should walk the real\nsubclasses.\n\n**A guard built from the current state asserts nothing.** The exclusivity guard\npassed on first write because I listed what was already non-exclusive. Write the\nclaim, watch it fail, then make it true.\n\nBreak every guard once and watch it go red. Clear `__pycache__` between runs.\n\n## Shell is linted on every surface it lives on\n\n`fast.audit.shell` runs ShellCheck over three surfaces, each failing closed:\ntracked `*.sh`, every workflow `run:` body, and every Dockerfile `RUN` body --\nincluding the `.j2` templates, **rendered** through `render_dockerfile` rather\nthan masked, because the rendered output is what builds.\n\n`capsem.gate.shellsurfaces` extracts all three, and the Citadel's shape guard\nmeasures the same bodies, so the linter and the ceiling cannot disagree about\nwhat a body is. Getting that extraction right took five attempts -- flattened\ncontinuations swallowing comments, comments stripped after continuations\ninstead of before, `${{ }}` masked to a literal producing three phantom SC2050\n\"bugs\", Jinja masked instead of rendered, and a dict key that silently dropped\nfive steps into a collision. Add a surface there, not in a second extractor.\n\n`[boundary.shell_bodies]` keeps them simple: 20 executable lines, with an exact\ndebt inventory. The fix for an oversized body is an owned boundary under\n`build_system\u002Fscripts\u002F`, which ShellCheck already lints and a test can call.\n\n## Shell is parsed, not matched\n\n`shelllex` tokenises, `shellparse` builds a tree, `shellnodes` holds the nodes\nand the queries. Ask questions of the tree.\n\nEvery question this repository asks of shell used to be a regular expression,\nand each worked on the case it was written for. `cargo` in a filename, in a\ncomment, on the left of an assignment or inside a quoted argument is not\n`cargo` in command position, and no refinement fixes that -- the distinction is\ngrammatical.\n\n```python\ntree = parse(body, origin=\"check-web-surface.sh\")\ncommands(arm_named(tree, \"release-channel\") or [])   # one case arm, exactly\n[c for c in commands(tree) if c.program == \"cargo\"]  # command position only\nsuppressed(tree)                                     # verdicts thrown away\n```\n\n`Command.program` steps over assignment prefixes and wrappers, so\n`CARGO_TARGET_DIR=\u002Ftmp env cargo build` answers `cargo`. Conjunctions are nodes\nrather than a flattened list, because the operator *is* the meaning: `check`\nand `check || true` differ only in an `AndOr`, and that difference once\nsatisfied a release contract while branch protection was off.\n\n**Pass a shell body, not a container of one.** `parse` sniffs and warns when\nhanded a raw `.j2` template, a whole Dockerfile or a workflow -- each lexes\nwithout error and yields confident nonsense. Use `shellsurfaces` to extract:\nit renders templates and pulls `RUN` and `run:` bodies out. Its own guard read\nraw templates on the first attempt and reported a correctly chained\n`make && ls` as two unguarded statements.\n\nIts suite found four bugs in it before any consumer did. Add cases to\n`build_system\u002Ftests\u002Fscripts\u002Ftest_shell_parse.py` when you extend it.\n\nThis applies to tests too: a workflow is parsed as YAML, its `run:` value is\nthen passed to `shelllex`\u002F`shellparse`, and heredocs come from the lexer's\nmetadata. Do not use regex or indentation slicing as a smaller local parser.\nThat creates a second grammar which eventually disagrees on quoting, `printf`,\nor a moved script and turns the release dispatcher into the first real test.\n\n## An exclusion is exact, hashed, and states why\n\nEvery guard eventually meets something it should not fail on. `exclusions.py`\nis the one shape that carve-out may take. Two wrong shapes were tried first,\nand both look reasonable:\n\n- **A count** -- \"this file has nine\". Fails when somebody adds a harmless\n  tenth; passes when somebody turns one of the nine into something dangerous.\n  The number is orthogonal to the risk.\n- **A program name** -- \"`launchctl` is cleanup\". It is, at three call sites,\n  and a real check at a fourth. Four of the five findings that rule produced\n  were its own misclassification.\n\n`Exclusion` carries `subject` and a `reason` with a minimum length; a reason of\n\"known\" or \"legacy\" is refused by the schema. `HashedExclusion` adds a `digest`\nover the **parsed** form, via `canonical(...)`. Hashing the parse is what makes\nit usable: requote, reflow or move the line and the decision stands; change\nwhat it does and it is a new decision that has to be stated.\n\n`reconcile(found, excused)` is symmetric on purpose. A ledger that only refuses\ngrowth is an exemption list wearing a ratchet's name -- the entry that outlives\nthe thing it excused is exactly the failure these guards exist for, and it is\nthe one that never announces itself.\n\nLedgers today: `[[boundary.discarded_verdicts]]`, `[[boundary.sequenced_runs]]`,\n`[boundary.unclaimed_cargo]`.\n\n## The Citadel runs in the fast phase\n\n`tests\u002Fcitadel\u002F` records architectural mistakes that must not be repeated. It\nis source-level -- no artifact, no VM, no daemon -- so it is scheduled beside\nRuff and the source-syntax audit, not in the broad suite. It was reachable only\nthrough the broad suite's `root` for a while, which meant a DB-boundary\nviolation surfaced after the VMs were up rather than in the first seconds.\n\n`tests\u002Fcitadel` is in `broad_ignores`: one collector, so its failures have one\nowner. `citadel\u002Ftest_guard_scheduling.py` fails if it is moved back behind the\nexpensive work.\n\nEvery guard states its reasoning in a named `*_RATIONALE` appended to the\nassertion, so a violation teaches instead of printing a bare comparison. When\nthe reason is already stated somewhere canonical -- `[boundary]`, AGENTS.md, a\nskill -- the rationale cites it rather than restating it; a second wording is a\nsecond thing to keep in step.\n\n| guard | what it holds |\n|---|---|\n| `test_db_boundary.py` | only `capsem-logger` executes ledger queries |\n| `test_shape_boundaries.py` | every `[boundary.*]` ceiling and debt inventory, files and shell bodies alike |\n| `test_workflow_enforcement.py` | a gating step cannot pass while failing |\n| `test_container_workspace.py` | the guest builder's `\u002Fsrc\u002F*` glob skips dotfiles |\n| `test_skill_context_budget.py` | the skill description budget every session pays |\n| `test_hot_build_contract.py` | hot codecs stay optimized in the dev profile |\n| `test_package_architecture_boundary.py` | package and machine architecture never cross |\n| `test_guard_scheduling.py` | the Citadel itself runs before the expensive work |\n\n## See also\n\n`\u002Fdev-just` for the public surface, `\u002Fdev-testing` for the suites,\n`\u002Frelease-process` for what the release lanes must guarantee.\n",{"name":5,"description":7},"main","d357170bb677125c80cebed720e62bf47bf083ad","skills\u002Fdev-gate",26,"https:\u002F\u002Fgithub.com\u002Fgoogle\u002Fcapsem","https:\u002F\u002Fgithub.com\u002Fgoogle","https:\u002F\u002Fopensource.google\u002F","Google ❤️ Open Source","2026-11-14 00:49:59",{"source":9,"skillName":5,"commands":47,"prompt":57,"zipAvailable":58},[48,51,54],{"tool":49,"command":50},"npx","npx skills add google\u002Fcapsem --skill dev-gate",{"tool":52,"command":53},"bunx","bunx skills add google\u002Fcapsem --skill dev-gate",{"tool":55,"command":56},"pnpm","pnpm dlx skills add google\u002Fcapsem --skill dev-gate","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fgoogle\u002Fcapsem\u002Fblob\u002Fmain\u002Fskills\u002Fdev-gate\u002FSKILL.md",true,[],[61,78,94,109,122,134],{"skillNo":62,"name":63,"nameZh":64,"description":65,"descriptionZh":66,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":67,"categories":68,"keywords":75,"publishedAt":32},"01M699558T2T4DJMBN08ZCQ79K","use-capsem","Capsem 虚拟机任务执行","Run tasks in Capsem VMs through MCP. Use when an agent needs isolated execution, file analysis, or reports returned to the host.","通过 MCP 在 Capsem 虚拟机中运行任务。在智能体需要隔离执行、文件分析，或将报告返回到主机时使用。","https:\u002F\u002Fgithub.com\u002Fgoogle\u002Fcapsem\u002Fblob\u002Fmain\u002Fskills\u002Fuse-capsem\u002FSKILL.md",[69,72],{"categoryNo":70,"categoryName":71,"taxonomyType":28,"taxonomyTypeDesc":29},"01M8BRN0DBCRG4XGJMB6QQEP11","编码任务委派",{"categoryNo":73,"categoryName":74,"taxonomyType":23,"taxonomyTypeDesc":24},"01M8BRZZF9D7PVFN5MXSPWWD61","AI 工程师",[76,77],"use capsem","MCP",{"skillNo":79,"name":80,"nameZh":81,"description":82,"descriptionZh":83,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":84,"categories":85,"keywords":92,"publishedAt":32},"01M69953Z1CSVQ4N07QX529CZY","site-marketing","营销网站内容维护","The marketing website, capsem.org. Use when editing copy, adding sections, or changing the site theme.","营销网站 capsem.org。在编辑文案、添加板块或更改网站主题时使用。","https:\u002F\u002Fgithub.com\u002Fgoogle\u002Fcapsem\u002Fblob\u002Fmain\u002Fskills\u002Fsite-marketing\u002FSKILL.md",[86,89],{"categoryNo":87,"categoryName":88,"taxonomyType":23,"taxonomyTypeDesc":24},"01M8BQGD6C0J544QTJ9R38Z7ZG","营销专员",{"categoryNo":90,"categoryName":91,"taxonomyType":28,"taxonomyTypeDesc":29},"01M8BQV98WRP4APE9VKKKKJ6FV","社交媒体与内容平台管理",[93],"site marketing",{"skillNo":95,"name":96,"nameZh":97,"description":98,"descriptionZh":99,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":100,"categories":101,"keywords":106,"publishedAt":32},"01M69952B33KBBV37N8QTC4191","site-infra","文档站基础设施维护","The documentation site, docs.capsem.org. Use for user-directed Diátaxis documentation and Astro Starlight changes.","文档站点 docs.capsem.org。用于面向用户的 Diátaxis 文档和 Astro Starlight 相关更改。","https:\u002F\u002Fgithub.com\u002Fgoogle\u002Fcapsem\u002Fblob\u002Fmain\u002Fskills\u002Fsite-infra\u002FSKILL.md",[102,105],{"categoryNo":103,"categoryName":104,"taxonomyType":28,"taxonomyTypeDesc":29},"01M8BQ6TK1MPB82068236GSXDE","文档处理",{"categoryNo":21,"categoryName":22,"taxonomyType":23,"taxonomyTypeDesc":24},[107,108],"site infra","docs",{"skillNo":110,"name":111,"nameZh":112,"description":17,"descriptionZh":113,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":114,"categories":115,"keywords":120,"publishedAt":32},"01M69950YKCZKCDB98JDQNBBRJ","site-architecture","站点架构设计","","https:\u002F\u002Fgithub.com\u002Fgoogle\u002Fcapsem\u002Fblob\u002Fmain\u002Fskills\u002Fsite-architecture\u002FSKILL.md",[116,119],{"categoryNo":117,"categoryName":118,"taxonomyType":28,"taxonomyTypeDesc":29},"01M8BQ6TKQDF2K4KQS863Q79P4","开发参考",{"categoryNo":21,"categoryName":22,"taxonomyType":23,"taxonomyTypeDesc":24},[121],"site architecture",{"skillNo":123,"name":124,"nameZh":125,"description":17,"descriptionZh":113,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":126,"categories":127,"keywords":132,"publishedAt":32},"01M6994Z61JWZ0G2YRJTWFH933","release-process","版本发布流程","https:\u002F\u002Fgithub.com\u002Fgoogle\u002Fcapsem\u002Fblob\u002Fmain\u002Fskills\u002Frelease-process\u002FSKILL.md",[128,129],{"categoryNo":21,"categoryName":22,"taxonomyType":23,"taxonomyTypeDesc":24},{"categoryNo":130,"categoryName":131,"taxonomyType":28,"taxonomyTypeDesc":29},"01M8BQNXPY1AV6BSR5VKHDMWRH","部署与发布管理",[133],"release process",{"skillNo":135,"name":136,"nameZh":137,"description":138,"descriptionZh":139,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":140,"categories":141,"keywords":146,"publishedAt":32},"01M6994XKHADM6FBTYTAPG7FYC","meta-skill-creation","智能体技能创建与优化","Create, improve, and evaluate skills. Use when writing a new skill, editing an existing one, or tuning a description for better triggering.","创建、改进和评估技能。在编写新技能、编辑现有技能或调整 description 以优化触发效果时使用。","https:\u002F\u002Fgithub.com\u002Fgoogle\u002Fcapsem\u002Fblob\u002Fmain\u002Fskills\u002Fmeta-skill-creation\u002FSKILL.md",[142,145],{"categoryNo":143,"categoryName":144,"taxonomyType":28,"taxonomyTypeDesc":29},"01M8BRN0CV1NMDZ5TEJX1GVM29","插件与技能管理",{"categoryNo":73,"categoryName":74,"taxonomyType":23,"taxonomyTypeDesc":24},[147,148],"meta skill creation","writing"]