diff --git a/CHANGELOG.md b/CHANGELOG.md index caf68d0..7b49a3c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,12 +10,14 @@ release yet; entries name the pull requests that made them. ### Changed +- `tools/cstack_mcp.py` refuses to start without the durable ledger `cstack init` sets up, and says which command to run; `--allow-memory-ledger` keeps the memory ledger for tests and throwaway development. Tailscale is now optional: the device name comes from `--device`, the name `cstack init` recorded, or the tailnet name. `cryptography` moved from `ci/requirements.txt` to `requirements.txt`. - Re-vendored the four pinned foundations at the commits that merged the 2026-11-09 backfill-review fixes: refrigeration `f78905d`, film `52fa82c`, robotics `d61de96`, template `0dcf469` (template gains one test file, 50 entries). Upstream changed only docs, tests and tools; no bridge or schema changed, so inventory hashes are unchanged. `poodo_skill` moves to `aeba967` (its 45 synced files are byte-identical; the new upstream release-docs test file is listed as deferred). `EXPORT-MANIFEST.json` rebuilt. EndoForge stays pinned until its rounds 8-10 merge. - README and docs index rewritten for a first-time reader: purpose, a real approval run, a top-down diagram and install first; the NASA control documents sit behind one "Engineering records" section. Material moved out of the README went to new how-to guides (approve asks, define bots, use a real model, add a domain, merge train) and an explanation of Foundations and pins. The README's Measured table moved to `docs/verification/measured-2026-11.md`, with every figure tied to a commit on `main` (assurance finding F-7) (#80). ### Added +- `cstack init` (`tools/cstack_init.py`, `adapters/local_setup.py`): one command sets up a private state folder, the device name and a durable witnessed ledger for every bot; safe to run again, with `--check` for a read-only health report. Requirements CS-REQ-084 to CS-REQ-086; guide [Set up Cstack](docs/guides/how-to/set-up.md). - Cstack family documentation standard published in `docs/standards/` (standard, checklist, templates) as the canonical copy for the family. - NASA-organized control documents: software management plan, compliance matrix, test plan and procedures, generated data dictionary, generated test report and version description for the `main` baseline, assurance record, user manual map, limitations page; problem-report and change-request issue templates and a peer-review PR template. - Requirements CS-REQ-036 to CS-REQ-077 for behaviour existing tests already check; every requirement allocated to a design component; full bidirectional trace. diff --git a/EXPORT-MANIFEST.json b/EXPORT-MANIFEST.json index f7a575a..b0570fb 100644 --- a/EXPORT-MANIFEST.json +++ b/EXPORT-MANIFEST.json @@ -27,7 +27,7 @@ "bytes": 1415 }, ".github/workflows/ci.yml": { - "sha256": "7a77c7f271c47d8c89db411c767ce79eab77c9d497961d6abe1fdbd4f3227fea", + "sha256": "e50ae65fffd328ad8b1b3ab7b3561a6f22ddd488cd334159324280d0165e635b", "bytes": 1052 }, ".gitignore": { @@ -51,8 +51,8 @@ "bytes": 4359 }, "CHANGELOG.md": { - "sha256": "4b45ad9f8663e5d4e32a2398d5be78a5eeb21bbf95ad3ec5f520f845524c828e", - "bytes": 7103 + "sha256": "a8f9af483703b39d476ba20124e93e54b6daf83b51f7de6bd506b4c181087c75", + "bytes": 7833 }, "CODE_OF_CONDUCT.md": { "sha256": "6228457a516409a784d807676564c8477f58d979eb7df3a4f690008d8a794442", @@ -71,8 +71,8 @@ "bytes": 1183 }, "README.md": { - "sha256": "f180ee76b42982e1d4b7a83064746a6684ef1704270d0c0d18f7a9c468d5d015", - "bytes": 16333 + "sha256": "75cd2ad52f8185d762610fd51d1c4e9f4130dde437c9c2b332934b44e1aeaa04", + "bytes": 17147 }, "SECURITY.md": { "sha256": "ca32c78d9c9402d31cfac4538c20ddbc9e689f9ce6ecec40fd7535e651edba65", @@ -186,6 +186,10 @@ "sha256": "cd8cabcba2739b2aac95c3798710707605791950a34fceba73eb7ccd28392837", "bytes": 14042 }, + "adapters/foundations_mcp.py": { + "sha256": "18674ac66ffae13f19f97535cde966eccca5ea8fba7ef6313cfa418f550b5402", + "bytes": 7965 + }, "adapters/host_read_models.py": { "sha256": "554a6149db492d1ebdd5ffa7230ab6128518daea208359002eb8c1d3f1646239", "bytes": 21208 @@ -194,6 +198,10 @@ "sha256": "356cf0918fc5fba8752ee11ddd78dee9ce577ef546e80ef319ff2ce074690a3c", "bytes": 23532 }, + "adapters/local_setup.py": { + "sha256": "b1bc30924dc4de0e45a1df589f14168546fabcd9a95bf29ee026862de8f548c8", + "bytes": 16299 + }, "adapters/math_stdio.py": { "sha256": "7332a747fbb96aa2699073ed9f6b6ca7ce88c285b47f7d6fc73cdb07f0ba35e7", "bytes": 11813 @@ -203,8 +211,8 @@ "bytes": 25742 }, "adapters/mcp_stdio_server.py": { - "sha256": "566ed454db6d412209e03db367a0f4a2a2188d9f30012a13e9f1d98f900008cc", - "bytes": 12805 + "sha256": "433e7e59d43e85743c43b6039107fface3a206002c8246f72f754ef54ff06b22", + "bytes": 12830 }, "adapters/memory/README.md": { "sha256": "30dd166af5d401519d2acd28f357c51f2a0fa0b98a0cd445449d4c95963b183e", @@ -379,8 +387,8 @@ "bytes": 1010 }, "bootstrap.py": { - "sha256": "cf066bfe377e5f02d24cfc0d040a1ba2efe5dde7026f11c72d00e8f8b3faf138", - "bytes": 27733 + "sha256": "7c4b19e2e25b70dac12e953339d97bb00e30fbb293841f57c2e27fcfff523daa", + "bytes": 28554 }, "ci/host-only.txt": { "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", @@ -391,8 +399,8 @@ "bytes": 270 }, "ci/requirements.txt": { - "sha256": "1ecce7d0091219627059831f2e48b6c433465defd9702c2c3f741f6f39d58bf7", - "bytes": 372 + "sha256": "c26053f6e77ab2093df22e5fb5227f6f4fe6e5993610d0669930cadd7c76590f", + "bytes": 289 }, "ci/run-local.sh": { "sha256": "477f0eaa0de1b9305f6949ceac603fcc98f4826fd9ffc486364457db6fb0e594", @@ -411,8 +419,8 @@ "bytes": 8349 }, "contracts/ADAPTERS.json": { - "sha256": "f3acd594ab22dc509793f40f6093e742c4abcb7af09d51156e0fe2a86fb3961c", - "bytes": 31508 + "sha256": "82b2a3b5972f64238597702dc5411105f4011f1320e51972e6c30ea42f8301d4", + "bytes": 33684 }, "contracts/CONTRACT.json": { "sha256": "05848bff545d839bdcc9e30f4c8d2352f768e0298129e4bc57cbb68ed9e0c0c5", @@ -439,8 +447,8 @@ "bytes": 2422 }, "contracts/INTERFACES.md": { - "sha256": "34938f9049a848706ff03583eb630e46af43ed33cc070eb1c6d9f3fa5d0ed771", - "bytes": 26705 + "sha256": "78e96fde981a066f2f9a57d8e57c6b04bca08169af7770635e82986e89646fc1", + "bytes": 26900 }, "contracts/RESEARCH.md": { "sha256": "633318d6f72fce2caa8ccfbed7ab34c2f5ff8f1b6e350fe761b27a3a96e8d80d", @@ -471,12 +479,12 @@ "bytes": 684 }, "docs/README.md": { - "sha256": "914f226db4b69a76e5ccbe616005d65c4def91fa8f95427e33359e638a18315e", - "bytes": 7078 + "sha256": "632a972f27d73c770deceb41c3a6f8bed0a43f810b4cf45e2037e36285f8bbe7", + "bytes": 7172 }, "docs/architecture/architecture.md": { - "sha256": "d5a259bcfc07576eac4cea7a74036744a5320dec2d98e74debc53a1df47243c3", - "bytes": 22319 + "sha256": "4a1728ef2188f9380be605eab67f67744f39a1ddc8d8506b7f83300133f948d2", + "bytes": 23113 }, "docs/assurance/assurance-record.md": { "sha256": "71d5308e71aa46f70dd1ac06cd99e19955ae63bafd3cea57355634924b3b8a7f", @@ -511,12 +519,12 @@ "bytes": 4034 }, "docs/guides/explanation/server-and-adapters.md": { - "sha256": "d6eac3103da29a0e668bbcdce7b143e157be312936f795010d1cb14e21029bf7", - "bytes": 7321 + "sha256": "8756fa75134d603696266069d266aaff3d87f658c2b74d4d8b4f14b244399183", + "bytes": 7455 }, "docs/guides/how-to/README.md": { - "sha256": "05a9051fb3b603dadbe67fd2507edd8ca435005abc9f382d97e6602c51f166da", - "bytes": 1048 + "sha256": "6890089d7cad4f4a85591c471e052d42f8648cbead70cadca522718f7a301ac7", + "bytes": 1146 }, "docs/guides/how-to/add-a-domain.md": { "sha256": "2db40dba2a8b8921b41d54c874d1328c2652fbe149614a25309c7edb2b60c429", @@ -527,8 +535,8 @@ "bytes": 4667 }, "docs/guides/how-to/define-bots.md": { - "sha256": "f0657bb1bfee699cf7782714493b70dcfd97e3ed3b8ef7cd8c67ad6dd50df2d5", - "bytes": 2634 + "sha256": "60e71f1ff3ab2d662ff60fe694d3ca6c0bfcb3b9762851e02475e91fec0a2dac", + "bytes": 2797 }, "docs/guides/how-to/merge-train.md": { "sha256": "57f342c9540af29378026196cdd67bd918a0aeff1c35e02d7fef2acdda95350f", @@ -539,8 +547,12 @@ "bytes": 4911 }, "docs/guides/how-to/run-ci-locally.md": { - "sha256": "2cf4d16896f4863d3949be5e6d0a352606d9782ba1ac79717d62c6c148215ce8", - "bytes": 5058 + "sha256": "da1947ec3660e137aa06bf41ffbafde90b17347b1f4d28b875b441e770532fa8", + "bytes": 5100 + }, + "docs/guides/how-to/set-up.md": { + "sha256": "e9b476e56231584c52c62014a6e62b370a20451c27072ec156376eeef1b46e99", + "bytes": 4322 }, "docs/guides/how-to/use-a-real-model.md": { "sha256": "47f525d28f2ef975f511adab6404dce51775eb669ab3c8f113bba968ce2e738d", @@ -551,24 +563,24 @@ "bytes": 1800 }, "docs/guides/reference/commands.md": { - "sha256": "61af7b706324d15cdcd8af87a460d801aaafda861750b40662811f01ca855519", - "bytes": 9258 + "sha256": "822c34c8f9bde3cefcea7c9cc0cdb212e8b623ab3dca489e4903b02bc3702823", + "bytes": 9729 }, "docs/guides/reference/configuration.md": { - "sha256": "edf4f27e425d74117146a5ae2393d793dba08b2cf6911ad5874dc9c23040092c", - "bytes": 4752 + "sha256": "10f87f0f7991cc2957e03c3476df8bcce0ac2b08af58653a48f216e8e5a837ca", + "bytes": 5000 }, "docs/guides/reference/environment.md": { - "sha256": "961b924137b919c0631b962cf8088e881759d146731c48b6b8a81dcc5ab76995", - "bytes": 4218 + "sha256": "dcd6917825219ebb0bdfcba953d2aee1bc8707e9ea59c2c8e2e91ecdce2ae9da", + "bytes": 4244 }, "docs/guides/tutorials/README.md": { "sha256": "e3e7a578ad9a12704e226839c61d88aa2278a64e30c7771228517eee6f06e45b", "bytes": 483 }, "docs/guides/tutorials/first-run.md": { - "sha256": "a0a8da3c25b2c71a7d06db1acacf07e1c4a55a37222f58090ae4f19fe21353d0", - "bytes": 7604 + "sha256": "c8a717d417219b056ad1b049cb1365b7f573b27ba81226fd0e91d5828e715612", + "bytes": 7778 }, "docs/icd/icd-endoforge-pin.md": { "sha256": "7602054207a725e24ef5c28153582ebdf09d3f89df5e82dac286f827f0147c06", @@ -579,8 +591,8 @@ "bytes": 21041 }, "docs/icd/icd-foundations.md": { - "sha256": "bcabb16e735448824c89dcb91ca416b0f80a555e316991252dcc6fe01c67fd03", - "bytes": 12026 + "sha256": "8564330068956d0e8e8d067f8b22902e14191bfce8c04df2f56a3d9727007b45", + "bytes": 15770 }, "docs/icd/icd-poodo.md": { "sha256": "8be48f4f2e7c9917ded4390fbae6cef604be62710cd569623c7e2005cbcc44db", @@ -603,8 +615,8 @@ "bytes": 5760 }, "docs/requirements/requirements.md": { - "sha256": "aa5457afcdd3ae494306a74b75319ccd0fd0725de4c3587832083699a29491a7", - "bytes": 49158 + "sha256": "f8600e4cb1aa3a71a079d2f343d4b7eaedcd62a842b2f152cf582e72cd564651", + "bytes": 52840 }, "docs/rules/no-comments.md": { "sha256": "cd0aac16b8119228bb5b7e79d38e71ddcc430679916a9f7080d7b3bd88fb4a90", @@ -711,8 +723,8 @@ "bytes": 9734 }, "docs/verification/verification-matrix.md": { - "sha256": "36973230602038f7ee2a96fc73ff992c3a37ce7e8c2f89feb8e2aed3a13f2391", - "bytes": 23845 + "sha256": "84cb6209311ad0a6e045ebaa1adba606c64bb3d7e38cbdaef896b248b21f61e6", + "bytes": 24954 }, "docs/verification/wiring-acceptance.md": { "sha256": "a063e0580bf60ca41b37d473f1df7989b12c7e0aa915cecef30b916a4c4720d8", @@ -2059,8 +2071,8 @@ "bytes": 4167 }, "requirements.txt": { - "sha256": "55ff5313a0132d4037cf57d9dc9dd29073aee248a472b0702d2246b37cbd0431", - "bytes": 98 + "sha256": "a4418a02bdf15e406a1286532bebc4c7fe5443efb6da2d7a5f4d2c81161d150e", + "bytes": 119 }, "schemas/engine-v020-tools.json": { "sha256": "500b73fee56fd877649e5e475b8155cd77f7b3a7f002394a5ab909725fc56699", @@ -2246,6 +2258,10 @@ "sha256": "a46ebe47e5ebe01bcb8b2d44dec816fee936b2e3e50bfbb13d723a97af7f0383", "bytes": 7726 }, + "tests/test_cstack_init.py": { + "sha256": "4e51554a33b035389809023718a58eadfa04096f06b2997f66c942b43d1d6c83", + "bytes": 14744 + }, "tests/test_data_dictionary.py": { "sha256": "c07bd1cac36da3d80e39f387207bf754c2bd8eafab98fb80e58ae818315764a1", "bytes": 1157 @@ -2291,8 +2307,8 @@ "bytes": 1942 }, "tests/test_fleet_mail.py": { - "sha256": "195bb022f35b6f9a1a6f06f914c6545124724b6fc87cb9b9d4b80ecd1c1d25f8", - "bytes": 27897 + "sha256": "96dd99a04bc37041069fc6ab752ba66a3b16f23db103c6ba5a79060ff33eb100", + "bytes": 27925 }, "tests/test_fleet_mail_budget.py": { "sha256": "39bac88d15171a8d2f60953ba9a7ea848b6001cbee4d0927c46e5b672e7c1fbd", @@ -2322,6 +2338,10 @@ "sha256": "6450fac6fbef445afd4eeec66f28b78172c57648fbda58ff72e9ea2dfcf79fbd", "bytes": 4156 }, + "tests/test_foundations_mcp.py": { + "sha256": "e8d849e69538cd03d9ba55711ae526c9ea0913094056a75a2b2e8e5aad3fe099", + "bytes": 12003 + }, "tests/test_goal_liveness.py": { "sha256": "75f3b7e05e45b340add1bed493c6ce478ac2c83ee69a135673429fc6b948ee75", "bytes": 5001 @@ -2347,8 +2367,8 @@ "bytes": 5223 }, "tests/test_mcp_driving_adapter.py": { - "sha256": "19475f9c54763aa6b0b838106e441ad4d0969e30ae10f683246688da2b943cdf", - "bytes": 11728 + "sha256": "f1445aac99c7a386c3d353fb8716ef06eb7f7877e33900f1839d710c865b9772", + "bytes": 11778 }, "tests/test_mcp_stdio_client.py": { "sha256": "f4a362be20e12fcc20d05942a7f4cbcd6126a22017f48b20e13effc696bae613", @@ -2479,8 +2499,8 @@ "bytes": 6107 }, "tools/check_readme.py": { - "sha256": "2b829de8aa66f98795878d16b741bea66a8d68d24ccce859db737c3dc9c679f3", - "bytes": 10091 + "sha256": "d04104663cfafbe729f701e489f8a46646b18d8a117e2564b69181a018484b33", + "bytes": 11054 }, "tools/check_trace.py": { "sha256": "621b54f7923fa1cdfb25b3b71f52798befba681f6dffd2df8fea9c60765f8196", @@ -2490,9 +2510,13 @@ "sha256": "368a1f7dda5ab9ecc9c0adaf524707df064e1f5e95b10ffb096ea10eed0bbce5", "bytes": 12521 }, + "tools/cstack_init.py": { + "sha256": "68884a22bba2b8dd34e39b6db6046333962692bda553778618bd47a96490c346", + "bytes": 2690 + }, "tools/cstack_mcp.py": { - "sha256": "25e1de628ee66b3fa4273a4ceaca3c0a4658e789e0c65ab8f970fd4d307bcb38", - "bytes": 2961 + "sha256": "e1205c7ba9f1284b62800cb55262b54e44b5cafe969d9f56a8dadb31aadcfc4c", + "bytes": 3375 }, "tools/e2e_agent.py": { "sha256": "0c3240023a16ea16592131e31117c0c9c97e2cb120f05dd468cd1b937c1505a5", @@ -2502,6 +2526,10 @@ "sha256": "4c49f50eecf4d51140b308d08e5f7192c69c99a647f611d3cc3ea02219b4717f", "bytes": 133 }, + "tools/foundations_mcp.py": { + "sha256": "a05758847bca2689e0003a7372b207e19269a3660f0f8a6c5ef62ca548984193", + "bytes": 1810 + }, "tools/fuzz_ports.py": { "sha256": "1b38686b291fe83230226353dcafb936684e653ac9b820e7b823ecb1c6531a20", "bytes": 9540 diff --git a/README.md b/README.md index dc5b6ab..d234446 100644 --- a/README.md +++ b/README.md @@ -74,10 +74,10 @@ A bot reaches Cstack in one of two ways. `cli.py` runs one JSON file to the end, ```json { "mcpServers": { "cstack-example": { "command": "/path/to/cstack/.venv/bin/python", - "args": ["-B", "/path/to/cstack/tools/cstack_mcp.py", "--aor", "example", "--device", "example-host", "--state-root", "/tmp/cstack-state"] } } } + "args": ["-B", "/path/to/cstack/tools/cstack_mcp.py", "--aor", "example"] } } } ``` -`--device` names the machine, and `--state-root` is where this bot's ledger and your approvals live. The agent then gets six tools: `aor` (who am I), `start_goal`, `advance` (next phase, with its checkpoint), `decide` (record a call and its expected result), `execute` and `ledger`. Their descriptions walk the agent through the phases. +The server finds this bot's ledger, your approvals and the machine's device name in the state folder that `cstack init` set up (see [Install and run](#install-and-run)). If that setup is missing, it refuses to start and tells you the one command to run, rather than keep a record that would be lost. The agent then gets six tools: `aor` (who am I), `start_goal`, `advance` (next phase, with its checkpoint), `decide` (record a call and its expected result), `execute` and `ledger`. Their descriptions walk the agent through the phases. Cstack doesn't start your agents. Each agent connects to its own server; the shared registry, ledgers and approval channel are what make them one team. With `--fleet-mail`, bots can also leave each other messages. Either way, the core walks the goal through the POODO phases and applies each call's effect: `allow` runs it, `ask` waits for you, `deny` refuses it. Which bot may do what is set in `aors/fleet.json`, a file you own. Nothing in a request, a bot's output or a tool's reply can raise its own permissions. @@ -96,7 +96,15 @@ npm ci --prefix adapters/workcell-toolchain --ignore-scripts --no-audit --no-fun cp cstack.config.example.json cstack.config.json ``` -The `npm` step installs the pinned compiler for code-writing runs; the approval example runs without it. `ci/requirements.txt` adds what the test suites need. `cstack.config.json` holds your host settings: where the ledger is written and what a code-writing run may use. Now run the example above. To check your install, run the test suite, then the Python, link and trace checks that CI runs: +The `npm` step installs the pinned compiler for code-writing runs; the approval example runs without it. `ci/requirements.txt` adds what the test suites need. `cstack.config.json` holds your host settings: where the ledger is written and what a code-writing run may use. Now run the example above. + +Before you point an agent at Cstack, set up this machine once: + +```sh +python -B tools/cstack_init.py +``` + +`cstack init` makes a private state folder, a signing key for each bot in `aors/fleet.json` and a durable ledger that survives restarts. Tailscale is optional. Run it again after adding a bot; it keeps what exists and adds what is missing. `--check` reports health without changing anything. [Set up Cstack](docs/guides/how-to/set-up.md) explains each part. To check your install, run the test suite, then the Python, link and trace checks that CI runs: ```sh python -B -m unittest discover -s tests @@ -109,6 +117,7 @@ The [first-run tutorial](docs/guides/tutorials/first-run.md) walks through three | Task | Guide | |---|---| +| Set up a machine so bots keep a durable ledger | [Set up Cstack](docs/guides/how-to/set-up.md) | | Approve calls from a terminal or an answer file | [Approve ask calls](docs/guides/how-to/approve-asks.md) | | Name your bots, what they own and what needs your approval | [Define your bots](docs/guides/how-to/define-bots.md) | | Let a real model write forge code (Claude Code subscription login) | [Use a real model](docs/guides/how-to/use-a-real-model.md) | @@ -143,7 +152,7 @@ It ends with `"assessment": "candidate_passed"` and a receipt naming the compile - Early template. There is no tagged release; `main` is the supported version. - The bundled tools are read-only calculations and checks. Tools with outside effects, such as sending email, are yours to add: as a Foundation, or as an external MCP tool server through `adapters/mcp_stdio_client.py`. - Workcells and Foundations run as child processes with deadlines and output limits. Neither is an OS sandbox for hostile code. -- The ledger is written on one machine. A compromised machine can rewrite its own ledger before anyone else sees it; it is not an independent witness. +- The ledger is written on one machine. A compromised machine can rewrite its own ledger before anyone else sees it; it is not an independent witness. `cstack init`'s two witness keys live on the same machine; see [witnesses](docs/guides/how-to/set-up.md#witnesses). - `tools/scheduled_approvals.py`, the owner's tool for answering a bot's asks, doesn't yet find asks in the per-domain ledger files that MCP sessions write. See [approve ask calls](docs/guides/how-to/approve-asks.md#answer-a-bots-asks). - A forge goal runs one model at a time. EndoForge's parallel coding agents and its caching are not wired in yet. - Results are observations, not engineering, safety or compliance approvals. See [limitations](docs/guides/explanation/limitations.md). diff --git a/adapters/local_setup.py b/adapters/local_setup.py new file mode 100644 index 0000000..c67d6b2 --- /dev/null +++ b/adapters/local_setup.py @@ -0,0 +1,366 @@ +"""One machine's Cstack setup: the private state folder, the device name and a durable witnessed ledger.""" +from dataclasses import dataclass, field +import importlib.util +import json +import os +from pathlib import Path +import re +import shutil +import socket +import stat +import subprocess + +DEVICE_FILE = "device.json" +LEDGER_FILE = "ledger.json" +DEVICE_SCHEMA = "cstack.device/0.1" +LOCAL_WITNESSES = ("local-witness-1", "local-witness-2") +NAME = re.compile(r"[a-z0-9][a-z0-9-]{0,62}") +INIT = "python -B tools/cstack_init.py" + + +class SetupError(Exception): + pass + + +def default_state_root(): + return Path.home() / ".local/state/cstack" + + +def init_command(state_root): + state_root = Path(state_root) + return INIT if state_root == default_state_root() else f"{INIT} --state-root {state_root}" + + +def tailnet_hostname(which=shutil.which, run=subprocess.run): + if which("tailscale") is None: + return None + try: + status = json.loads(run(["tailscale", "status", "--json", "--self"], capture_output=True, text=True, + timeout=10, check=True).stdout) + name = status["Self"]["DNSName"].split(".")[0].lower() + except (OSError, subprocess.SubprocessError, ValueError, KeyError, TypeError, AttributeError): + return None + return name if NAME.fullmatch(name) else None + + +def computer_name(gethostname=socket.gethostname): + label = gethostname().split(".")[0].lower() + return re.sub(r"[^a-z0-9-]+", "-", label).strip("-")[:63] or "local" + + +def recorded_device(state_root): + path = Path(state_root) / DEVICE_FILE + if not path.exists(): + return None + try: + record = json.loads(path.read_text()) + name = record["hostname"] + if record.get("schema") != DEVICE_SCHEMA or type(name) is not str or not NAME.fullmatch(name): + raise ValueError(name) + except (OSError, ValueError, KeyError, TypeError): + raise SetupError(f"{path} is damaged. Run `{init_command(state_root)} --device NAME` to record this " + "machine's device name again.") from None + return name + + +def resolve_device(state_root, tailnet=None): + name = recorded_device(state_root) or (tailnet or tailnet_hostname)() + if name is None: + raise SetupError(f"This machine has no Cstack device name yet. Run `{init_command(state_root)}` once; " + "it records one, with or without Tailscale.") + return name + + +def require_durable(state_root): + if not (Path(state_root) / LEDGER_FILE).is_file(): + raise SetupError( + f"Cstack is not set up in {state_root}: there is no durable ledger, so everything this bot does would " + f"be lost when the server stops. Run `{init_command(state_root)}` once, then start the server again. " + "For a throwaway development session only, add --allow-memory-ledger.") + + +@dataclass +class Report: + state_root: Path + write: bool + lines: list = field(default_factory=list) + device: str | None = None + bots: tuple = () + local_witnesses: bool = False + + def add(self, status, text): + self.lines.append((status, text)) + + @property + def problems(self): + return [text for status, text in self.lines if status == "problem"] + + +def _private_dir(path, report, label): + try: + info = os.lstat(path) + except FileNotFoundError: + if not report.write: + report.add("problem", f"{label} {path} is missing. Run `{init_command(report.state_root)}`.") + return False + os.mkdir(path, 0o700) + os.chmod(path, 0o700) + report.add("created", f"{label} {path}, private to you") + return True + if not stat.S_ISDIR(info.st_mode): + report.add("problem", f"{label} {path} is not a plain folder (it is a link or a file). Move it aside and " + "run init again.") + return False + if info.st_uid != os.getuid(): + report.add("problem", f"{label} {path} belongs to another user. Use a state folder of your own.") + return False + if info.st_mode & 0o077: + if report.write: + os.chmod(path, 0o700) + report.add("fixed", f"{label} {path} was open to other users; it is now private to you") + else: + report.add("problem", f"{label} {path} is open to other users. Run init to make it private.") + return True + + +def _private_file(path, report, label, *, fixable): + info = os.lstat(path) + if not stat.S_ISREG(info.st_mode) or info.st_uid != os.getuid(): + report.add("problem", f"{label} {path} is not a plain file of yours (it is a link, a folder or another " + "user's). Move it aside and run init again.") + return False + if info.st_mode & 0o077: + if fixable and report.write: + os.chmod(path, 0o600) + report.add("fixed", f"{label} {path} was readable by other users; it is now private to you") + elif fixable: + report.add("problem", f"{label} {path} is readable by other users. Run init to make it private.") + else: + report.add("problem", f"{label} {path} is readable by other users, so it may have been copied. Delete " + "it and run init again to make a new one; a new key starts a new ledger writer.") + return False + return True + + +def _write_json(path, value): + temporary = path.with_name(path.name + ".tmp") + descriptor = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o600) + with os.fdopen(descriptor, "w") as handle: + json.dump(value, handle, indent=2, sort_keys=True) + handle.write("\n") + handle.flush() + os.fsync(handle.fileno()) + os.replace(temporary, path) + + +def _read_json(path, report, label): + if not _private_file(path, report, label, fixable=True): + return None + try: + return json.loads(path.read_text()) + except (OSError, ValueError): + report.add("problem", f"{label} {path} is not valid JSON. Move it aside and run init again.") + return None + + +def _key(L, path, report, label): + if os.path.lexists(path): + if not _private_file(path, report, f"Signing key for {label}", fixable=False): + return None + try: + return L.load_key(str(path)) + except (L.LedgerError, OSError, ValueError): + report.add("problem", f"Signing key for {label} {path} is damaged. Move it aside and run init again.") + return None + if not report.write: + report.add("problem", f"Signing key for {label} is missing. Run `{init_command(report.state_root)}`.") + return None + key = L.Ed25519PrivateKey.generate() + L.save_key(key, str(path)) + report.add("created", f"Signing key for {label}, readable only by you") + return key + + +def _device(state_root, fleet, flag, tailnet, gethostname, report): + names = [device.hostname for device in fleet.devices] + try: + recorded = recorded_device(state_root) + except SetupError as error: + report.add("problem", str(error)) + recorded = None + if flag is not None: + if not NAME.fullmatch(flag): + report.add("problem", f"--device {flag!r} is not a device name: use lowercase letters, digits and " + "hyphens.") + return recorded + name, source = flag, "chosen with --device" + elif recorded is not None: + name, source = recorded, "recorded earlier" + else: + detected, source = tailnet(), "this machine's Tailscale name" + if detected is None: + detected, source = computer_name(gethostname), "this computer's name; Tailscale is not in use" + name = detected + if name not in names and len(names) == 1: + name, source = names[0], f"the only device in the bot list; {detected!r} is not listed there" + if name not in names: + report.add("problem", f"This machine is called {name!r}, but the bot list has no device by that name. Add " + f"a devices entry for {name!r} to aors/fleet.json, or run init again with --device " + f"NAME, one of: {', '.join(names) or 'none listed'}.") + return name + if recorded == name: + report.add("ok", f"Device name {name} ({source})") + elif report.write: + _write_json(state_root / DEVICE_FILE, {"schema": DEVICE_SCHEMA, "hostname": name}) + report.add("created", f"Device name {name} ({source})") + else: + report.add("problem", f"This machine's device name is not recorded yet. Run `{init_command(state_root)}`.") + return name + + +def _ledger(state_root, bots, L, report): + config_path = state_root / LEDGER_FILE + config, write = None, report.write + if os.path.lexists(config_path): + config = _read_json(config_path, report, "Ledger settings") + if config is None: + return + if type(config) is not dict or not all(type(config.get(k)) is str for k in ("node", "log", "roster")) \ + or type(config.get("writers")) is not dict: + report.add("problem", f"Ledger settings {config_path} are incomplete. Move the file aside and run init " + "again.") + return + node = config["node"] if config else (report.device if report.device and NAME.fullmatch(report.device) + else "local") + config = config or {"node": node, "log": f"ledger/{node}.jsonl", "roster": "ledger/roster.json", "writers": {}} + config_changed = not config_path.exists() + ledger_dir = state_root / "ledger" + if not _private_dir(ledger_dir, report, "Ledger folder"): + return + roster_path, roster_changed = state_root / config["roster"], False + if os.path.lexists(roster_path): + roster = _read_json(roster_path, report, "Ledger roster") + if roster is None: + return + try: + L.load_roster(str(roster_path)) + if type(roster.get("writers")) is not dict: + raise ValueError("writers") + except (L.LedgerError, OSError, ValueError, KeyError, TypeError, AttributeError): + report.add("problem", f"Ledger roster {roster_path} is damaged. Move the ledger folder aside and run " + "init again to start a new ledger.") + return + else: + if not write: + report.add("problem", f"Ledger roster is missing. Run `{init_command(state_root)}`.") + return + witnesses = {} + if _private_dir(ledger_dir / "witnesses", report, "Witness key folder"): + for name in LOCAL_WITNESSES: + key = _key(L, ledger_dir / "witnesses" / f"{name}.key", report, f"witness {name}") + if key is not None: + witnesses[name] = L.pub_hex(key) + if len(witnesses) < 2: + return + roster, roster_changed = {"quorum": 2, "witnesses": witnesses, "writers": {}}, True + report.local_witnesses = set(roster["witnesses"]) <= set(LOCAL_WITNESSES) + keys_ready = _private_dir(ledger_dir / "keys", report, "Bot key folder") + for slug in bots: + entry = config["writers"].get(slug) + if entry is not None and not (type(entry) is dict and type(entry.get("writer")) is str + and type(entry.get("key")) is str): + report.add("problem", f"Ledger settings list bot {slug} without a usable writer and key.") + continue + if entry is None and not keys_ready: + continue + writer, key_rel = (entry["writer"], entry["key"]) if entry else (slug, f"ledger/keys/{slug}.key") + key = _key(L, state_root / key_rel, report, f"bot {slug}") + if key is None: + continue + bound, want = roster["writers"].get(writer), {"pub": L.pub_hex(key), "node": config["node"]} + bound = {k: bound.get(k) for k in want} if type(bound) is dict else bound + if bound is None: + if not write: + report.add("problem", f"Bot {slug} is not in the ledger roster yet. Run `{init_command(state_root)}`.") + continue + roster["writers"][writer], roster_changed = want, True + elif bound != want: + report.add("problem", f"The signing key for bot {slug} does not match the ledger roster. Init never " + "replaces keys or roster entries: restore the original key, or move the ledger " + "folder and ledger.json aside to start a new ledger.") + continue + if entry is None: + if not write: + report.add("problem", f"Bot {slug} has no ledger writer yet. Run `{init_command(state_root)}`.") + continue + config["writers"][slug], config_changed = {"writer": slug, "key": key_rel}, True + if write and roster_changed: + _write_json(roster_path, roster) + report.add("created", f"Ledger roster {roster_path} (public keys only)") + if write and config_changed: + _write_json(config_path, config) + report.add("created", f"Ledger settings {config_path}") + _verify_log(state_root / config["log"], config["node"], roster, L, report) + + +def _verify_log(log_path, node, roster, L, report): + logs = [path for path in (log_path, *sorted(log_path.with_suffix("").glob("*/*.jsonl"))) if path.is_file()] + if not logs: + report.add("ok", "Ledger is ready; its files are created when a bot first records something") + return + entries = 0 + for path in logs: + try: + entries += len(L.Log(str(path), node, roster).entries) + except (L.LedgerError, OSError, ValueError, KeyError, TypeError) as error: + report.add("problem", f"The ledger file {path} failed verification ({error}). Keep the file: it is the " + "record. Do not run bots until it is explained.") + return + report.add("ok", f"Ledger verified: {len(logs)} file(s), {entries} signed entries, every chain intact") + + +def _bot_state(state_root, slug, report): + folder = state_root / slug + if not _private_dir(folder, report, f"State folder for bot {slug}"): + return + anchors = folder / "anchors.json" + if os.path.lexists(anchors): + value = _read_json(anchors, report, f"Ledger anchors for bot {slug}") + if value is not None and (type(value) is not dict or any(not k.startswith(slug + ".") for k in value)): + report.add("problem", f"Ledger anchors {anchors} do not belong to bot {slug}. Move the file aside.") + elif report.write: + _write_json(anchors, {}) + report.add("created", f"Ledger anchors for bot {slug}") + else: + report.add("problem", f"Ledger anchors for bot {slug} are missing. Run `{init_command(state_root)}`.") + + +def setup(state_root, fleet_path, *, device=None, write=True, tailnet=None, gethostname=None): + from adapters.aor_registry import load_fleet + from poodo_core import ContractError + + state_root = Path(state_root).expanduser() + report = Report(state_root, write) + if write: + state_root.parent.mkdir(parents=True, exist_ok=True) + if not _private_dir(state_root, report, "State folder"): + return report + try: + fleet = load_fleet(fleet_path) + except (OSError, ValueError, ContractError) as error: + report.add("problem", f"The bot list {fleet_path} could not be read: {error}") + return report + report.bots = tuple(bot.slug for bot in fleet.bots) + report.device = _device(state_root, fleet, device, tailnet or tailnet_hostname, + gethostname or socket.gethostname, report) + if write and report.problems: + return report + if importlib.util.find_spec("cryptography") is None: + report.add("problem", "The ledger needs the Python package 'cryptography'. Install it with " + "`pip install -r requirements.txt`, then run init again.") + return report + from adapters.witnessed_ledger import ledger_lib + _ledger(state_root, report.bots, ledger_lib(), report) + for slug in report.bots: + _bot_state(state_root, slug, report) + return report diff --git a/ci/requirements.txt b/ci/requirements.txt index 60efb4c..1f34634 100644 --- a/ci/requirements.txt +++ b/ci/requirements.txt @@ -1,5 +1,4 @@ # CI test dependencies: the repo's own requirements plus what the suites need so they run instead of skipping. -r ../requirements.txt -cryptography==50.0.2 # ADR 004 witnessed-ledger tests (about 70 skip without it) pillow==13.0.0 # hillclimb prove-split pixel diff (forge/endoforge/tools/hillclimb/scripts/pixel-diff.py) numpy==2.5.4 # same pixel diff diff --git a/contracts/ADAPTERS.json b/contracts/ADAPTERS.json index ffc6514..369924b 100644 --- a/contracts/ADAPTERS.json +++ b/contracts/ADAPTERS.json @@ -34,14 +34,14 @@ "lane": "HMIFace", "port": "none", "port_reason": "Host composition entry point: builds an AOR session and serves MCP directly; no core port protocol.", - "vendor": "cstack (in-repo), Tailscale CLI for device identity", + "vendor": "cstack (in-repo); Tailscale CLI optional, for device identity when cstack init recorded none", "kind": "python_module", "path": "tools/cstack_mcp.py", "fake": null, "fake_reason": "Launcher tests use host-supplied fixture configuration; no named HMIFace replaceability fake is registered.", "status": "hard_wired", "strategic_dependency_adr": null, - "notes": "Per-AOR MCP stdio launcher; fixes bot, device, fleet and state at host startup, marks the server process and closes the session on exit." + "notes": "Per-AOR MCP stdio launcher; fixes bot, device, fleet and state at host startup, marks the server process and closes the session on exit. Refuses to start without the durable ledger cstack init sets up, unless --allow-memory-ledger is given." }, { "adapter_id": "foundations-mcp-server", @@ -616,6 +616,16 @@ "role": "host_config", "reason": "Loads this inventory; it attaches nothing." }, + { + "path": "adapters/local_setup.py", + "role": "host_config", + "reason": "Creates and checks host-owned state for cstack init: the private state folder, the recorded device name, and the witnessed ledger's keys, roster and settings. It attaches nothing." + }, + { + "path": "tools/cstack_init.py", + "role": "host_config", + "reason": "The cstack init command: runs adapters/local_setup.py and prints a plain-language report. It attaches nothing." + }, { "path": "adapters/private_sqlite.py", "role": "shared_helper", diff --git a/docs/README.md b/docs/README.md index 7cfccf3..44ba0e2 100644 --- a/docs/README.md +++ b/docs/README.md @@ -12,6 +12,7 @@ Find what you need by what you want to do. New here? Start with the [README](../ | Task | Guide | |---|---| +| Set up a machine so bots keep a durable ledger | [Set up Cstack](guides/how-to/set-up.md) | | Approve calls marked `ask`, on a terminal or from a file | [Approve ask calls](guides/how-to/approve-asks.md) | | Name your bots and what needs your approval | [Define your bots](guides/how-to/define-bots.md) | | Let a real model write forge code | [Use a real model](guides/how-to/use-a-real-model.md) | diff --git a/docs/architecture/architecture.md b/docs/architecture/architecture.md index 8b6d965..9cd1623 100644 --- a/docs/architecture/architecture.md +++ b/docs/architecture/architecture.md @@ -3,10 +3,10 @@ | Field | Value | |---|---| | Document ID | CSTACK-SDD | -| Version | 2.2 | +| Version | 2.3 | | Status | Baselined | | Owner | Akilleez-QA | -| Date | 2026-11-09 | +| Date | 2026-11-16 | | Baseline commit | b7c64b19e3966baaf1aa6793491b454e28f51446 | | Applies to | cstack main at baseline commit | | Classification | Self-assessed Class E analog; not safety-critical (see [SMP §1](../plan/software-management-plan.md#1-software-classification-self-assessed)) | @@ -72,7 +72,7 @@ Each component lists the requirements allocated to it. `python -B tools/check_tr | SDD-C12 | Forge runtime | `extensions/cstack_forge.py`, `adapters/endoforge_workcell.py`, `adapters/workcell/`, `adapters/workcell-toolchain/`, `tools/pin_workcell.py` | One governed EndoForge run per call in `IsolatePool` workcells, registered in `bootstrap.RUNTIMES` | CS-REQ-032, CS-REQ-033, CS-REQ-034, CS-REQ-035, CS-REQ-068, CS-REQ-069 | | SDD-C13 | Local ledgers | `adapters/memory_ledger.py`, `adapters/durable_ledger.py`, `adapters/witnessed_ledger.py`, `adapters/ledger.py` | In-memory, durable JSONL and witnessed node-log implementations of `LedgerPort` | CS-REQ-047, CS-REQ-048 | | SDD-C14 | AOR fleet and sessions | `aors/`, `adapters/aor_registry.py`, `adapters/aor_session.py`, `tools/e2e_agent.py` | Per-bot areas of responsibility, sessions over per-domain cores, end-to-end agent check | CS-REQ-049, CS-REQ-050, CS-REQ-051 | -| SDD-C15 | MCP server and client | `adapters/mcp_stdio_server.py`, `tools/cstack_mcp.py`, `adapters/mcp_stdio_client.py` | Agent-facing MCP server per bot; client for external MCP tool servers | CS-REQ-052, CS-REQ-053 | +| SDD-C15 | MCP server and client | `adapters/mcp_stdio_server.py`, `tools/cstack_mcp.py`, `adapters/mcp_stdio_client.py` | Agent-facing MCP server per bot, which refuses to start without durable state; client for external MCP tool servers | CS-REQ-052, CS-REQ-053, CS-REQ-085 | | SDD-C16 | Fleet mail and relay | `adapters/fleet_mail.py`, `adapters/relay_outbox.py` | Signed bot-to-bot messages on GitHub issues; at-most-once relay outbox | CS-REQ-054, CS-REQ-055 | | SDD-C17 | Memory store | `adapters/memory/` | SQLite/FTS5 store of host-sanitized facts with review, redaction and ingest | CS-REQ-062 | | SDD-C18 | Read models and watchers | `adapters/read_models.py`, `adapters/host_read_models.py`, `tools/read_models.py`, `tools/runtime_watch.py`, `tools/witness_watch.py` | Read-only projections and alarms over ledgers and host state | CS-REQ-057, CS-REQ-058, CS-REQ-059, CS-REQ-060 | @@ -82,6 +82,7 @@ Each component lists the requirements allocated to it. `python -B tools/check_tr | SDD-C22 | Reasoning snapshot | `reasoning/poodo/`, `TODELETE/reasoning/poodo/` | Mirrored POODO skill subset and archived retired paths | CS-REQ-019 | | SDD-C23 | Operator tools without tests | `tools/agent_profiles.py`, `tools/generate_aors.py`, `tools/measure_foundation_routes.py`, `tools/measure_routes_pyodide.mjs`, `tools/tty_approve.py`, `tools/fuzz_ports.py`, `tools/spawncount.py`, `tools/gen_release_docs.py` | Generators, measurement, release-record and test-support scripts; no CS-REQ requirement. `tools/spawncount.py` and `tools/fuzz_ports.py` are used by tests | Infrastructure | | SDD-C24 | Examples and placeholders | `examples/`, `products/`, `workshop/`, `cstack.config.example.json` | Example documents and configuration; empty component areas | Infrastructure | +| SDD-C28 | Local setup (`cstack init`) | `adapters/local_setup.py`, `tools/cstack_init.py` | Creates and checks one machine's private state folder, device name and witnessed-ledger keys, roster and settings; resolves the device name with or without Tailscale | CS-REQ-084, CS-REQ-086 | | SDD-C31 | Foundations MCP server | `adapters/foundations_mcp.py`, `tools/foundations_mcp.py` | Host-launched MCP server exposing the chosen pinned Foundations' tools to one bot, each call decided and executed through its AOR session | CS-REQ-091 | ```mermaid @@ -191,3 +192,4 @@ GPL-3.0-only. Commercial licenses under different terms are available from Refri | 2.0 | 2026-11-08 | 6ae5481fd302439dabb23044d1b715ac8c4a9bec | Family standard format; numbered sections; component table covers every directory with requirement allocation; design decisions, concurrency and quality attributes added | docs/nasa-standard PR | | 2.1 | 2026-11-08 | b7c64b19e3966baaf1aa6793491b454e28f51446 | Engine pin commit updated by the repin | PR #78 | | 2.2 | 2026-11-09 | 6088dd4 | SDD-C1 also allocated CS-REQ-045 (session-end ledger rename) | PR fixing the 2026-11-09 backfill-review findings | +| 2.3 | 2026-11-16 | feat/cstack-init | SDD-C28 local setup added (CS-REQ-084, CS-REQ-086); SDD-C15 also allocated CS-REQ-085 | Draft PR for `cstack init` | diff --git a/docs/guides/explanation/server-and-adapters.md b/docs/guides/explanation/server-and-adapters.md index f5d20af..1a7c3c7 100644 --- a/docs/guides/explanation/server-and-adapters.md +++ b/docs/guides/explanation/server-and-adapters.md @@ -15,17 +15,17 @@ Cstack has two driving adapters. Both build cores through `bootstrap.py`, and ne `tools/cstack_mcp.py` is the long-running way in. A host starts one per bot, from its own MCP client configuration: ```text -python -B tools/cstack_mcp.py --aor example --device example-host --state-root /tmp/cstack-state +python -B tools/cstack_mcp.py --aor example ``` It speaks newline-delimited JSON-RPC 2.0 on stdin and stdout (`adapters/mcp_stdio_server.py`), offering MCP revisions 2025-11-25, 2025-06-18 and 2024-11-05. It has no network listener. What makes it safe to hand to a bot: -- **The bot is fixed at launch.** `--aor` names one entry in `aors/fleet.json`; the device comes from `--device` or the machine's tailnet name. No tool argument can name a bot, device, path, grant or approval. +- **The bot is fixed at launch.** `--aor` names one entry in `aors/fleet.json`; the device comes from `--device`, else the name `cstack init` recorded, else the machine's tailnet name; Tailscale is optional. No tool argument can name a bot, device, path, grant or approval. - **The tool table is closed.** `aor`, `start_goal`, `advance`, `decide`, `execute` and `ledger` map one-to-one to core operations. `--fleet-mail` adds `mail_send`, `mail_inbox`, `mail_reply` and `mail_close`. The host assigns every goal, request and decision id. - **Effects resolve strictest first.** Each effect class (`read`, `execute`, `send` and the rest) is `allow`, `ask` or `deny`, taken from the bot's registry entry, then the device's guest rules when the bot doesn't own the device, then shields-up. An `ask` waits for the owner through the scheduled approval channel (`tools/scheduled_approvals.py`), which refuses to run inside an MCP server. -- **State is the host's.** Ledgers and approvals live under `--state-root` (default `~/.local/state/cstack`). With a `ledger.json` there, the session writes through the witnessed ledger of DECISION-004; without one, it says its ledger is memory only. +- **State is the host's.** Ledgers and approvals live under `--state-root` (default `~/.local/state/cstack`). `cstack init` ([set up Cstack](../how-to/set-up.md)) puts a `ledger.json` there, and the session writes through the witnessed ledger of DECISION-004. Without one the server refuses to start, unless `--allow-memory-ledger` asks for a throwaway memory-only session. An AOR session composes Foundations (`bootstrap.DOMAINS`) only. The forge runtime is in `bootstrap.RUNTIMES`, so being on the registry gives a bot no run authority. diff --git a/docs/guides/how-to/README.md b/docs/guides/how-to/README.md index cdedba6..8d770dc 100644 --- a/docs/guides/how-to/README.md +++ b/docs/guides/how-to/README.md @@ -4,6 +4,7 @@ Task recipes. Each assumes a working clone; the [tutorial](../tutorials/first-ru | Task | Guide | |---|---| +| Set up a machine with one command, so bots keep a durable ledger | [Set up Cstack](set-up.md) | | Approve calls marked `ask`, on a terminal or from a file | [Approve ask calls](approve-asks.md) | | Name your bots, their slices and effects, validate the registry and start a bot's session | [Define your bots](define-bots.md) | | Let a real model write forge code | [Use a real model](use-a-real-model.md) | diff --git a/docs/guides/how-to/define-bots.md b/docs/guides/how-to/define-bots.md index 9394f0c..3cd5103 100644 --- a/docs/guides/how-to/define-bots.md +++ b/docs/guides/how-to/define-bots.md @@ -35,18 +35,19 @@ owner-via-approver This checks the file against `contracts/aor.schema.json`. Loading the registry grants nothing by itself; `bootstrap.py` derives each session's authority from it. -## 3. Start a bot's session +## 3. Set up the machine and start a bot's session ```sh -python -B tools/cstack_mcp.py --aor example --device example-host --state-root /tmp/cstack-state +python -B tools/cstack_init.py +python -B tools/cstack_mcp.py --aor example ``` -This starts an MCP server on stdin and stdout for one bot. Point your agent's MCP client configuration at this command. The host picks the bot (`--aor`) and the device; nothing the bot sends can change them. Asked who it is (the `aor` tool), the session answers with the registry entry (trimmed): +`cstack init` gives every bot in the registry a signing key and a durable ledger, and records this machine's device name; run it again whenever you add a bot. [Set up Cstack](set-up.md) explains each part. The second command starts an MCP server on stdin and stdout for one bot. Point your agent's MCP client configuration at it. The host picks the bot (`--aor`) and the device; nothing the bot sends can change them. Asked who it is (the `aor` tool), the session answers with the registry entry (trimmed): ```text -{"approver": "owner-via-approver", "bot": {"id": "00000001", "name": "Example", "slug": "example"}, "device": "example-host", ..., "ledger": "memory (not durable: no ADR 004 roster configured)", ...} +{"approver": "owner-via-approver", "bot": {"id": "00000001", "name": "Example", "slug": "example"}, "device": "example-host", ..., "ledger": "witnessed", ...} ``` -The ledger is memory only until you configure a witnessed ledger under `--state-root`. [The server, the driver and the adapters](../explanation/server-and-adapters.md) explains the tool table, how effects resolve and where state lives. `tools/agent_profiles.py` generates MCP wiring and one agent profile per bot; see the [command reference](../reference/commands.md). +Without `cstack init` the server refuses to start and names the command to run. [The server, the driver and the adapters](../explanation/server-and-adapters.md) explains the tool table, how effects resolve and where state lives. `tools/agent_profiles.py` generates MCP wiring and one agent profile per bot; see the [command reference](../reference/commands.md). Return to the [how-to guides](README.md). diff --git a/docs/guides/how-to/run-ci-locally.md b/docs/guides/how-to/run-ci-locally.md index 94ec9b2..7000cca 100644 --- a/docs/guides/how-to/run-ci-locally.md +++ b/docs/guides/how-to/run-ci-locally.md @@ -23,7 +23,7 @@ pip install -r requirements.txt -r ci/requirements.txt npm ci --prefix adapters/workcell-toolchain --ignore-scripts --no-audit --no-fund ``` -`ci/requirements.txt` adds `cryptography`, `pillow` and `numpy` to the root requirements. Without `cryptography` about 70 witnessed-ledger tests skip instead of running. +`requirements.txt` includes `cryptography`, which the witnessed ledger and `cstack init` need; without it about 70 witnessed-ledger tests skip instead of running. `ci/requirements.txt` adds `pillow` and `numpy`. ## Run the `test` job diff --git a/docs/guides/how-to/set-up.md b/docs/guides/how-to/set-up.md new file mode 100644 index 0000000..f8c5a73 --- /dev/null +++ b/docs/guides/how-to/set-up.md @@ -0,0 +1,78 @@ +# How to set up Cstack on a machine + +One command sets up a machine so your bots can use Cstack and keep what they do: + +```sh +python -B tools/cstack_init.py +``` + +Run it once after you install, and again whenever you add a bot to `aors/fleet.json`. Running it again is safe: it keeps everything that is already there and adds only what is missing. + +## What it sets up + +Everything goes in one private state folder, `~/.local/state/cstack` unless you pass `--state-root`. Folders are created readable only by you (mode 0700), and files the same way (mode 0600). + +| Item | Where | Why | +|---|---|---| +| Device name | `device.json` | Says which device in `aors/fleet.json` this machine is | +| A signing key per bot | `ledger/keys/.key` | Each bot signs its own ledger entries | +| Two witness keys | `ledger/witnesses/` | The ledger format needs at least two; see [Witnesses](#witnesses) | +| Roster | `/ledger/roster.json` | Public keys only: which key belongs to which bot and witness | +| Ledger settings | `ledger.json` | Where the ledger, roster and keys are; written last | +| Per-bot state | `/anchors.json` | Where each bot's server records the last ledger position it saw | + +With this in place, every bot's MCP server writes to a durable, signed, hash-chained ledger that survives restarts. Without it the server won't start (see [Development without a ledger](#development-without-a-ledger)). + +When it finishes, it prints what it did and what to do next: + +```text +Ready. Bots: example. Device: example-host. Every bot records to a durable, signed ledger that survives restarts. + +Next: + Start a bot's server: python -B tools/cstack_mcp.py --aor example + Check health later: python -B tools/cstack_init.py --check +``` + +## Check health + +```sh +python -B tools/cstack_init.py --check +``` + +This changes nothing. It reports each problem in plain words with the fix, verifies every ledger file's signatures and chain, and exits 1 if anything needs attention, 0 if all is well. + +## Device names and Tailscale + +Each machine needs a device name that `aors/fleet.json` lists. Tailscale is optional. `cstack init` picks the name in this order: + +1. `--device NAME`, if you pass it; +2. the name an earlier `cstack init` recorded; +3. this machine's Tailscale name, if Tailscale is installed and signed in; +4. otherwise this computer's own name, in lowercase. + +If the name it finds isn't in the bot list and the bot list has exactly one device, it uses that device. That is why a fresh clone, with the single `example-host` device, works as is. Otherwise it asks you to add a `devices` entry or pass `--device`. + +The MCP server uses the same name: `--device` if given, else the recorded name, else the Tailscale name. + +## Witnesses + +The ledger format (DECISION-004) expects independent witness machines to co-sign it, so that a compromised machine can't quietly rewrite its own history. `cstack init` makes two witness keys on this machine, so the ledger works from the start. Because they live on the same machine, they don't give that protection: the ledger is durable and signed, but nothing outside the machine vouches for it yet. To get real witnessing, run witnesses on other machines and list their public keys in `/ledger/roster.json`. `cstack init` never replaces a roster that already exists. + +## Fix problems + +- **A key is readable by other users.** It may have been copied, so `cstack init` won't repair it. Delete it and run `cstack init` again to make a new one. +- **A key doesn't match the roster.** `cstack init` never replaces keys or roster entries. Put the original key back, or move `ledger/` and `ledger.json` aside to start a new ledger. +- **A ledger file failed verification.** Keep the file: it is the record. Don't run bots until you know why it changed. +- **A folder or settings file is open to other users.** `cstack init` makes it private again. + +## Development without a ledger + +For a throwaway session, such as a test, the server can run on a memory-only ledger that is lost when it stops. You must ask for it explicitly: + +```text +python -B tools/cstack_mcp.py --aor example --device example-host --allow-memory-ledger +``` + +Bots configured by `tools/agent_profiles.py` never get this flag; `tests/test_cstack_init.py` fails if they do. + +Return to the [how-to guides](README.md). diff --git a/docs/guides/reference/commands.md b/docs/guides/reference/commands.md index 80a9f2c..e2fc54f 100644 --- a/docs/guides/reference/commands.md +++ b/docs/guides/reference/commands.md @@ -61,7 +61,8 @@ All run from the checkout root as `python -B tools/.py`. None reads reques | `pin_endoforge.py` | Rebuilds `vendor/endoforge/` from one EndoForge commit on `origin/main` and records the pin | `--source` (required), `--commit` (required), `--allow-unmerged`. See [repin EndoForge](../how-to/repin-endoforge.md) | | `pin_workcell.py` | Records the hash of every file in `adapters/workcell/` as `workcell_runtime` in `contracts/SOURCE-PINS.json` | None | | `build_export_manifest.py` | Rewrites `EXPORT-MANIFEST.json`: every tracked file with its SHA-256 and size | None | -| `cstack_mcp.py` | Starts the MCP stdio server for one bot's AOR. See [the server](../explanation/server-and-adapters.md) | `--aor` (required), `--state-root` (`~/.local/state/cstack`), `--device` (the tailnet name from `tailscale status`), `--fleet` (`aors/fleet.json`), `--fleet-mail`, `--fleet-mail-repo` (`your-org/cstack`), `--fleet-mail-extra` (repeatable, default `worker`), `--fleet-mail-budget` (20 per hour) | +| `cstack_init.py` | `cstack init`: sets up the state folder, device name and a durable witnessed ledger for every bot; safe to run again. Exits 1 when a problem needs you. See [set up Cstack](../how-to/set-up.md) | `--check` (report only, change nothing), `--state-root` (`~/.local/state/cstack`), `--fleet` (`aors/fleet.json`), `--device` | +| `cstack_mcp.py` | Starts the MCP stdio server for one bot's AOR; refuses, exit 2, without the durable ledger `cstack init` sets up. See [the server](../explanation/server-and-adapters.md) | `--aor` (required), `--state-root` (`~/.local/state/cstack`), `--device` (default: recorded by `cstack init`, else the tailnet name), `--allow-memory-ledger` (development only), `--fleet` (`aors/fleet.json`), `--fleet-mail`, `--fleet-mail-repo` (`your-org/cstack`), `--fleet-mail-extra` (repeatable, default `worker`), `--fleet-mail-budget` (20 per hour) | | `merge_train.py` | Merges open PRs in dependency order. Needs `gh` signed in; exits 2 without it | `--dry-run`, `--policy` (`all` or `low-risk`, default `all`), `--wip`, `--max-passes` (12) | | `claim_gate.py` | Checks a bot's report claims against its POODO ledger | `--report` and `--ledger` (required). `--atoms`, `--atom-refs` and `--consumer` exit 2: no approved-atoms Registry is included | | `scheduled_approvals.py` | Lists asks waiting on the owner and records an answer. Refuses to run inside an MCP server | `--state-root` (required), `--approvals`, `--json`, `--full`; to answer: `DECISION_ID yes\|no --sha256 DIGEST [--ttl 3600] [--bot SLUG]` | diff --git a/docs/guides/reference/configuration.md b/docs/guides/reference/configuration.md index 79c0eed..1f93505 100644 --- a/docs/guides/reference/configuration.md +++ b/docs/guides/reference/configuration.md @@ -61,6 +61,7 @@ The example: | `aors/fleet.json` | `adapters.aor_registry.load_fleet`, `tools/cstack_mcp.py` | The bot registry, validated against `contracts/aor.schema.json` | | `contracts/SOURCE-PINS.json` | Adapters, the workcell runtime, pin tests | Expected hashes of every vendored source. Changed only by a reviewed pin change | | `contracts/ADAPTERS.json` | `bootstrap.check_grants` | Which adapter provides each capability, and on which lane | -| `/ledger.json` | `bootstrap.build_aor_session` | Optional witnessed-ledger setup for AOR sessions (writers, log, roster) | +| `/ledger.json` | `bootstrap.build_aor_session`, `tools/cstack_init.py` | Witnessed-ledger setup for AOR sessions (writers, log, roster), written by `cstack init`; `tools/cstack_mcp.py` refuses to start without it | +| `/device.json` | `tools/cstack_init.py`, `tools/cstack_mcp.py` | This machine's device name in `aors/fleet.json`, recorded by `cstack init` | Return to the [reference index](README.md). diff --git a/docs/guides/reference/environment.md b/docs/guides/reference/environment.md index f7ee4b1..e7ae4ef 100644 --- a/docs/guides/reference/environment.md +++ b/docs/guides/reference/environment.md @@ -28,7 +28,7 @@ The Claude transport passes on only `PATH`, `HOME`, `LANG`, `LC_ALL`, `TERM`, `U |---|---|---|---| | `XDG_STATE_HOME` | `adapters/terminal_approver.py` | `~/.local/state` | Consumed CLI approval markers go in `$XDG_STATE_HOME/cstack/cli-approvals` | -`tools/cstack_mcp.py` keeps AOR state in `~/.local/state/cstack` unless `--state-root` is given; it doesn't read `XDG_STATE_HOME`. +`tools/cstack_mcp.py` and `tools/cstack_init.py` keep AOR state in `~/.local/state/cstack` unless `--state-root` is given; they don't read `XDG_STATE_HOME`. ## AOR sessions and the MCP server diff --git a/docs/guides/tutorials/first-run.md b/docs/guides/tutorials/first-run.md index a1fa947..33f73e5 100644 --- a/docs/guides/tutorials/first-run.md +++ b/docs/guides/tutorials/first-run.md @@ -135,6 +135,7 @@ Keep `cstack.config.json` if you want to carry on. It is ignored by git. ## Where next +- Connect an agent over MCP: run `python -B tools/cstack_init.py` once, as [set up Cstack](../how-to/set-up.md) describes, then [define your bots](../how-to/define-bots.md). - Run the checks CI runs: [run CI checks locally](../how-to/run-ci-locally.md). - Use a real model: set `workcell.transport` to `adapters/workcell/claude-transport.mjs`, as [use a real model](../how-to/use-a-real-model.md) describes. - Understand what you just ran: [how Cstack vendors and runs EndoForge](../explanation/endoforge-vendoring.md). diff --git a/docs/requirements/requirements.md b/docs/requirements/requirements.md index c30fc85..1466f04 100644 --- a/docs/requirements/requirements.md +++ b/docs/requirements/requirements.md @@ -3,10 +3,10 @@ | Field | Value | |---|---| | Document ID | CSTACK-SRS | -| Version | 2.1 | +| Version | 2.2 | | Status | Baselined | | Owner | Akilleez-QA | -| Date | 2026-11-09 | +| Date | 2026-11-16 | | Baseline commit | 6ae5481fd302439dabb23044d1b715ac8c4a9bec | | Applies to | cstack main at baseline commit | | Classification | Self-assessed Class E analog; not safety-critical (see [SMP §1](../plan/software-management-plan.md#1-software-classification-self-assessed)) | @@ -679,6 +679,36 @@ The relay outbox shall send a click retried from several processes once, keep re - Verification: T - Status: Baselined +### CS-REQ-084 — One-command setup + +`tools/cstack_init.py` (`cstack init`) shall create a state folder readable only by its owner (0700 folders, 0600 files), a device record, a signing key per fleet bot, a roster and ledger settings for the DECISION-004 witnessed ledger, writing the settings last. Run again, it shall change nothing when setup is complete, finish a partial setup with the keys already made, add writers for new bots, make loose folders and settings private, and never replace or repair a key that is exposed or does not match the roster. Its `--check` mode shall change nothing, verify every ledger file, and exit 1 when any problem needs the owner. It shall report each result in plain language with the fix. + +- Rationale: without a one-command setup, newcomers ran agent sessions on a memory ledger that was lost when the session ended (critic finding B2). +- Derivation: `adapters/local_setup.py`; `tools/cstack_init.py` +- Allocated to: SDD-C28 +- Verification: T +- Status: Draft + +### CS-REQ-085 — No memory ledger in agent mode + +`tools/cstack_mcp.py` shall refuse to start, with exit 2 and a message naming the `cstack init` command, when its state root has no `ledger.json`, before creating any state, unless the host passes `--allow-memory-ledger`. + +- Rationale: a bot's record must survive the session; a memory ledger is for tests and throwaway development only. +- Derivation: `tools/cstack_mcp.py`; `adapters/local_setup.py` +- Allocated to: SDD-C15 +- Verification: T +- Status: Draft + +### CS-REQ-086 — Device identity without Tailscale + +The device name shall be `--device` when given, else the name `cstack init` recorded, else the tailnet name. `cstack init` shall record, in that order, `--device`, an earlier record, the tailnet name, or the computer's own name; it shall substitute the fleet's only device when the found name is not listed, and otherwise report the unlisted name as a problem without recording it. An absent, failing or signed-out Tailscale shall yield no tailnet name rather than an error. + +- Rationale: requiring Tailscale to start a server blocked people without it (critic finding M9). +- Derivation: `adapters/local_setup.py`; `tools/cstack_mcp.py` +- Allocated to: SDD-C28 +- Verification: T +- Status: Draft + ### 3.8 Memory, read models and watchers ### CS-REQ-062 — Memory store @@ -876,3 +906,4 @@ GPL-3.0-only. Commercial licenses under different terms are available from Refri | 1.x | 2026-10 to 2026-11-08 | various | CS-REQ-001 to CS-REQ-035 added across earlier PRs | See `git log -- docs/requirements/requirements.md` | | 2.0 | 2026-11-08 | 6ae5481fd302439dabb23044d1b715ac8c4a9bec | Family standard format: metadata, record fields, allocation to SDD components; CS-REQ-036 to CS-REQ-077 added from tested behaviour; CS-REQ-027 to CS-REQ-030 restated without repeating the port text | docs/nasa-standard PR | | 2.1 | 2026-11-09 | 6088dd4 | CS-REQ-045 covers a session that ends with an unknown outcome; CS-REQ-047 covers a failed file open | PR fixing the 2026-11-09 backfill-review findings | +| 2.2 | 2026-11-16 | feat/cstack-init | CS-REQ-084 to CS-REQ-086 added: one-command setup, no memory ledger in agent mode, device identity without Tailscale | Draft PR for `cstack init` | diff --git a/docs/verification/verification-matrix.md b/docs/verification/verification-matrix.md index 5597285..b60968c 100644 --- a/docs/verification/verification-matrix.md +++ b/docs/verification/verification-matrix.md @@ -3,10 +3,10 @@ | Field | Value | |---|---| | Document ID | CSTACK-VM | -| Version | 2.1 | +| Version | 2.2 | | Status | Baselined | | Owner | Akilleez-QA | -| Date | 2026-11-09 | +| Date | 2026-11-16 | | Baseline commit | 6ae5481fd302439dabb23044d1b715ac8c4a9bec | | Applies to | cstack main at baseline commit | | Classification | Self-assessed Class E analog; not safety-critical (see [SMP §1](../plan/software-management-plan.md#1-software-classification-self-assessed)) | @@ -84,6 +84,9 @@ The matrix does not embed pass counts. A mapped test shows the requirement is ex | CS-REQ-051 | T | `tests/test_e2e_agent_ledger.py` | Verdict stream and anchor checks | [STR-baseline](reports/STR-baseline.md) | | CS-REQ-052 | T | `tests/test_mcp_driving_adapter.py`; `tests/test_mcp_conformance.py` | Golden tool list; malformed input keeps serving | [STR-baseline](reports/STR-baseline.md) | | CS-REQ-053 | T | `tests/test_mcp_stdio_client.py` | `test_interop_with_official_typescript_sdk_server` skips unless `CSTACK_MCP_SDK_ESM` and `node` are present; a skip is not interop evidence | [STR-baseline](reports/STR-baseline.md) | +| CS-REQ-084 | T | `tests/test_cstack_init.py::InitTests`; `tests/test_cstack_init.py::CommandTests` | Fresh, repeat, partial, permissions, exposed and mismatched keys, linked folder, check-only, tampered ledger, missing `cryptography` | Not yet in a test report; PR check run | +| CS-REQ-085 | T | `tests/test_cstack_init.py::LauncherTests`; `tests/test_mcp_driving_adapter.py` | Refusal names the fix and creates no state; memory ledger only with the flag | Not yet in a test report; PR check run | +| CS-REQ-086 | T | `tests/test_cstack_init.py::DeviceTests`; `tests/test_cstack_init.py::LauncherTests.test_after_init_the_launcher_starts_witnessed_without_tailscale_or_device_flag` | Tailscale absent, failing or present; sole-device fallback; unlisted name; flag validation | Not yet in a test report; PR check run | | CS-REQ-091 | T | `tests/test_foundations_mcp.py` | Every vendored Foundation called once over the real pinned bridges; tampered manifest; stdio launcher | Not yet in a recorded run | | CS-REQ-054 | T | `tests/test_fleet_mail.py`; `tests/test_fleet_mail_budget.py` | Uses a fake `gh`; no network | [STR-baseline](reports/STR-baseline.md) | | CS-REQ-055 | T | `tests/test_relay_outbox.py` | Several processes, torn tails | [STR-baseline](reports/STR-baseline.md) | @@ -158,3 +161,4 @@ GPL-3.0-only. Commercial licenses under different terms are available from Refri | 1.x | 2026-10 to 2026-11-08 | various | Rows for CS-REQ-001 to CS-REQ-035 | See `git log -- docs/verification/verification-matrix.md` | | 2.0 | 2026-11-08 | 6ae5481fd302439dabb23044d1b715ac8c4a9bec | One row per requirement in `file::Class.method` form; rows for CS-REQ-036 to CS-REQ-077; gap table; every test file traced; `tools/check_trace.py` | docs/nasa-standard PR | | 2.1 | 2026-11-09 | 6088dd4 | CS-REQ-045 row adds the session-end and workcell-kill tests; CS-REQ-047 row names a failed file open | PR fixing the 2026-11-09 backfill-review findings | +| 2.2 | 2026-11-16 | feat/cstack-init | Rows for CS-REQ-084 to CS-REQ-086 | Draft PR for `cstack init` | diff --git a/requirements.txt b/requirements.txt index f3594cf..0271467 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,2 +1,3 @@ # Already available in the bound local environment. No installation performed. jsonschema==4.26.0 +cryptography==50.0.2 diff --git a/tests/test_cstack_init.py b/tests/test_cstack_init.py new file mode 100644 index 0000000..f37cc81 --- /dev/null +++ b/tests/test_cstack_init.py @@ -0,0 +1,307 @@ +"""cstack init (tools/cstack_init.py, adapters/local_setup.py) and the launcher's refusal to run without durable state.""" +import contextlib +import importlib.util +import io +import json +import os +from pathlib import Path +import stat +import subprocess +import sys +import tempfile +import unittest +from unittest import mock + +from adapters import local_setup +from adapters.local_setup import SetupError, computer_name, recorded_device, resolve_device, setup, tailnet_hostname +from tests.aor_fixtures import * + +ROOT = Path(__file__).resolve().parent.parent +INIT = ROOT / "tools/cstack_init.py" +MCP = ROOT / "tools/cstack_mcp.py" +NO_TAILSCALE = dict(tailnet=lambda: None, gethostname=lambda: "testbox.local") + + +def two_devices(directory): + path = write_fleet(directory) + fleet = json.loads(path.read_text()) + fleet["devices"].append({**fleet["devices"][0], "hostname": "otherbox"}) + path.write_text(json.dumps(fleet)) + return path + + +def snapshot(root): + return {p.relative_to(root).as_posix(): (stat.S_IMODE(os.lstat(p).st_mode), p.read_bytes() if p.is_file() else None) + for p in sorted(root.rglob("*"))} + + +def mode(path): + return stat.S_IMODE(os.lstat(path).st_mode) + + +class Case(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.dir = Path(tmp.name) + self.state = self.dir / "state" + self.fleet = write_fleet(self.dir) + + def init(self, **kwargs): + return setup(self.state, kwargs.pop("fleet", self.fleet), **{**NO_TAILSCALE, **kwargs}) + + def statuses(self, report): + return {status for status, _ in report.lines} + + +@unittest.skipUnless(HAVE_CRYPTO, NO_CRYPTO) +class InitTests(Case): + def test_fresh_init_creates_private_durable_state(self): + report = self.init() + self.assertEqual(report.problems, []) + self.assertEqual((report.device, report.bots, report.local_witnesses), ("testbox", ("alpha", "beta"), True)) + for folder in (self.state, self.state / "ledger", self.state / "ledger/keys", self.state / "ledger/witnesses", + self.state / "alpha", self.state / "beta"): + self.assertEqual(mode(folder), 0o700, folder) + files = [p for p in self.state.rglob("*") if p.is_file()] + self.assertEqual({mode(p) for p in files}, {0o600}) + config = json.loads((self.state / "ledger.json").read_text()) + roster = json.loads((self.state / config["roster"]).read_text()) + self.assertEqual(set(config["writers"]), {"alpha", "beta"}) + self.assertEqual({w["node"] for w in roster["writers"].values()}, {"testbox"}) + self.assertEqual((roster["quorum"], len(roster["witnesses"])), (2, 2)) + self.assertEqual(recorded_device(self.state), "testbox") + self.assertEqual(json.loads((self.state / "alpha/anchors.json").read_text()), {}) + + def test_a_session_built_on_init_state_is_witnessed(self): + from bootstrap import build_aor_session + self.assertEqual(self.init().problems, []) + session = build_aor_session("alpha", state_root=self.state, hostname=resolve_device(self.state), + fleet_path=self.fleet) + try: + self.assertEqual(session.ledger_label, "witnessed") + finally: + session.close() + + def test_repeat_init_changes_nothing(self): + self.init() + before = snapshot(self.state) + report = self.init() + self.assertEqual((report.problems, self.statuses(report)), ([], {"ok"})) + self.assertEqual(snapshot(self.state), before) + + def test_partial_state_is_completed_with_the_keys_already_made(self): + self.init() + keys = {p: p.read_bytes() for p in self.state.rglob("*.key")} + (self.state / "ledger.json").unlink() + (self.state / "ledger/roster.json").unlink() + (self.state / "beta/anchors.json").unlink() + report = self.init() + self.assertEqual(report.problems, []) + self.assertEqual({p: p.read_bytes() for p in self.state.rglob("*.key")}, keys) + self.assertEqual(self.init(write=False).problems, []) + + def test_a_bot_added_later_gets_a_writer_and_old_keys_are_kept(self): + fleet = json.loads(self.fleet.read_text()) + only_alpha = self.dir / "alpha-only.json" + only_alpha.write_text(json.dumps({**fleet, "bots": fleet["bots"][:1]})) + self.init(fleet=only_alpha) + alpha_key = (self.state / "ledger/keys/alpha.key").read_bytes() + report = self.init() + self.assertEqual(report.problems, []) + self.assertEqual((self.state / "ledger/keys/alpha.key").read_bytes(), alpha_key) + self.assertIn("beta", json.loads((self.state / "ledger.json").read_text())["writers"]) + + def test_loose_folder_and_settings_are_made_private(self): + self.init() + os.chmod(self.state, 0o755) + os.chmod(self.state / "ledger.json", 0o644) + checked = self.init(write=False) + self.assertEqual(len(checked.problems), 2) + self.assertEqual((mode(self.state), mode(self.state / "ledger.json")), (0o755, 0o644)) + report = self.init() + self.assertEqual((report.problems, "fixed" in self.statuses(report)), ([], True)) + self.assertEqual((mode(self.state), mode(self.state / "ledger.json")), (0o700, 0o600)) + + def test_an_exposed_key_is_refused_not_repaired(self): + self.init() + key = self.state / "ledger/keys/alpha.key" + os.chmod(key, 0o644) + report = self.init() + self.assertEqual(len(report.problems), 1) + self.assertIn("may have been copied", report.problems[0]) + self.assertEqual(mode(key), 0o644) + + def test_a_replaced_key_is_refused_and_the_roster_is_kept(self): + from adapters.witnessed_ledger import ledger_lib + L = ledger_lib() + self.init() + roster = (self.state / "ledger/roster.json").read_bytes() + key = self.state / "ledger/keys/alpha.key" + key.unlink() + L.save_key(L.Ed25519PrivateKey.generate(), str(key)) + report = self.init() + self.assertEqual(len(report.problems), 1) + self.assertIn("does not match the ledger roster", report.problems[0]) + self.assertEqual((self.state / "ledger/roster.json").read_bytes(), roster) + + def test_a_linked_state_folder_is_refused(self): + target = self.dir / "elsewhere" + target.mkdir(mode=0o700) + self.state.symlink_to(target) + report = self.init() + self.assertIn("not a plain folder", report.problems[0]) + self.assertEqual(list(target.iterdir()), []) + + def test_check_changes_nothing_on_a_fresh_machine(self): + report = self.init(write=False) + self.assertIn("is missing", report.problems[0]) + self.assertFalse(self.state.exists()) + + def test_check_verifies_recorded_ledger_files_and_reports_tampering(self): + from bootstrap import build_aor_session + self.init() + session = build_aor_session("alpha", state_root=self.state, hostname="testbox", fleet_path=self.fleet, + fleet_mail=None) + try: + session.start_goal(domain=DOMAIN, objective=SAMPLE.objective, acceptance_criteria=["Fixture."]) + finally: + session.close() + log = self.state / f"ledger/testbox/alpha/{DOMAIN}.jsonl" + checked = self.init(write=False) + self.assertEqual(checked.problems, []) + self.assertRegex(" ".join(text for _, text in checked.lines), r"file\(s\), [1-9]\d* signed entries") + log.write_text(log.read_text().replace("Fixture", "Forged", 1)) + report = self.init(write=False) + self.assertEqual(len(report.problems), 1) + self.assertIn("failed verification", report.problems[0]) + + def test_missing_cryptography_is_explained(self): + with mock.patch.object(local_setup.importlib.util, "find_spec", return_value=None): + report = self.init() + self.assertIn("pip install -r requirements.txt", report.problems[-1]) + self.assertFalse((self.state / "ledger.json").exists()) + + +@unittest.skipUnless(HAVE_CRYPTO, NO_CRYPTO) +class DeviceTests(Case): + def test_tailscale_absent_or_signed_out_gives_no_name(self): + self.assertIsNone(tailnet_hostname(which=lambda _: None)) + + def fails(*args, **kwargs): + raise subprocess.CalledProcessError(1, args[0]) + self.assertIsNone(tailnet_hostname(which=lambda _: "/usr/bin/tailscale", run=fails)) + out = mock.Mock(stdout=json.dumps({"Self": {"DNSName": "Box-1.tail1234.ts.net."}})) + self.assertEqual(tailnet_hostname(which=lambda _: "/usr/bin/tailscale", run=lambda *a, **k: out), "box-1") + + def test_computer_name_is_a_valid_device_name(self): + self.assertEqual(computer_name(lambda: "My_Mac.Local"), "my-mac") + self.assertEqual(computer_name(lambda: "___"), "local") + + def test_without_tailscale_the_computer_name_is_recorded(self): + report = self.init(fleet=two_devices(self.dir)) + self.assertEqual((report.problems, recorded_device(self.state)), ([], "testbox")) + + def test_without_tailscale_a_one_device_fleet_supplies_the_name(self): + report = self.init(gethostname=lambda: "laptop") + self.assertEqual((report.problems, recorded_device(self.state)), ([], "testbox")) + self.assertIn("'laptop' is not listed", " ".join(text for _, text in report.lines)) + + def test_tailscale_name_is_used_when_present(self): + report = self.init(fleet=two_devices(self.dir), tailnet=lambda: "otherbox") + self.assertEqual(recorded_device(self.state), "otherbox") + self.assertEqual(report.problems, []) + + def test_an_unlisted_name_is_a_problem_and_is_not_recorded(self): + report = self.init(fleet=two_devices(self.dir), gethostname=lambda: "laptop") + self.assertIn("no device by that name", report.problems[0]) + self.assertIsNone(recorded_device(self.state)) + self.assertFalse((self.state / "ledger.json").exists()) + + def test_device_flag_overrides_and_is_validated(self): + fleet = two_devices(self.dir) + self.init(fleet=fleet) + self.assertEqual(self.init(fleet=fleet, device="otherbox").problems, []) + self.assertEqual(recorded_device(self.state), "otherbox") + self.assertIn("not a device name", self.init(fleet=fleet, device="Bad/Name").problems[0]) + + def test_resolve_prefers_the_recorded_name_then_tailscale(self): + self.state.mkdir() + with self.assertRaisesRegex(SetupError, "cstack_init.py"): + resolve_device(self.state, tailnet=lambda: None) + self.assertEqual(resolve_device(self.state, tailnet=lambda: "tailbox"), "tailbox") + self.init() + self.assertEqual(resolve_device(self.state, tailnet=lambda: "tailbox"), "testbox") + (self.state / "device.json").write_text("{}") + with self.assertRaisesRegex(SetupError, "damaged"): + resolve_device(self.state) + + +class LauncherTests(Case): + def serve(self, *extra, env=None): + frames = ['{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18"}}', + '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"aor","arguments":{}}}'] + return subprocess.run([sys.executable, "-B", str(MCP), "--aor", "alpha", "--state-root", str(self.state), + "--fleet", str(self.fleet), *extra], cwd=ROOT, text=True, capture_output=True, + timeout=120, input="\n".join(frames) + "\n", env=env) + + def test_launcher_refuses_without_durable_state_and_names_the_fix(self): + proc = self.serve("--device", "testbox") + self.assertEqual((proc.returncode, proc.stdout), (2, "")) + self.assertIn("python -B tools/cstack_init.py --state-root", proc.stderr) + self.assertIn("--allow-memory-ledger", proc.stderr) + self.assertFalse(self.state.exists()) + + def test_memory_ledger_needs_the_explicit_development_flag(self): + proc = self.serve("--device", "testbox", "--allow-memory-ledger") + self.assertEqual(proc.returncode, 0, proc.stderr) + aor = json.loads(json.loads(proc.stdout.splitlines()[-1])["result"]["content"][0]["text"]) + self.assertTrue(aor["ledger"].startswith("memory (not durable")) + + @unittest.skipUnless(HAVE_CRYPTO, NO_CRYPTO) + def test_after_init_the_launcher_starts_witnessed_without_tailscale_or_device_flag(self): + self.assertEqual(self.init().problems, []) + env = {**os.environ, "PATH": str(self.dir)} + proc = self.serve(env=env) + self.assertEqual(proc.returncode, 0, proc.stderr) + aor = json.loads(json.loads(proc.stdout.splitlines()[-1])["result"]["content"][0]["text"]) + self.assertEqual((aor["device"], aor["ledger"]), ("testbox", "witnessed")) + + def test_generated_bot_profiles_never_allow_the_memory_ledger(self): + spec = importlib.util.spec_from_file_location("agent_profiles_under_test", ROOT / "tools/agent_profiles.py") + profiles = importlib.util.module_from_spec(spec) + spec.loader.exec_module(profiles) + from adapters.aor_registry import load_fleet + for fleet in (self.fleet, ROOT / "aors/fleet.json"): + files = profiles.build(load_fleet(fleet), ROOT, "/usr/bin/uv", None) + self.assertTrue(files) + for rel, text in files.items(): + self.assertNotIn("--allow-memory-ledger", text, rel) + + +@unittest.skipUnless(HAVE_CRYPTO, NO_CRYPTO) +class CommandTests(Case): + def run_init(self, *extra): + out = io.StringIO() + with contextlib.redirect_stdout(out), mock.patch.object(local_setup, "tailnet_hostname", lambda: None), \ + mock.patch.object(local_setup.socket, "gethostname", lambda: "testbox"): + spec = importlib.util.spec_from_file_location("cstack_init_under_test", INIT) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + code = module.main(["--state-root", str(self.state), "--fleet", str(self.fleet), *extra]) + return code, out.getvalue() + + def test_command_prints_a_plain_summary_and_next_steps(self): + code, out = self.run_init("--check") + self.assertEqual(code, 1) + self.assertIn("Not ready", out) + code, out = self.run_init() + self.assertEqual(code, 0) + self.assertIn("Ready. Bots: alpha, beta. Device: testbox.", out) + self.assertIn(f"python -B tools/cstack_mcp.py --aor alpha --state-root {self.state}", out) + self.assertIn("local keys on this machine", out) + self.assertEqual(self.run_init("--check")[0], 0) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_fleet_mail.py b/tests/test_fleet_mail.py index 25b621e..c377739 100644 --- a/tests/test_fleet_mail.py +++ b/tests/test_fleet_mail.py @@ -515,7 +515,7 @@ def build(*args, **kwargs): ["--aor", "alpha", "--device", "testbox", "--fleet-mail", "--fleet-mail-extra", "agent", "--fleet-mail-budget", "5"]): with self.assertRaises(SystemExit): - launcher.main(argv) + launcher.main([*argv, "--allow-memory-ledger"]) self.assertIsNone(seen[0]) self.assertEqual(seen[1], FleetMailConfig()) self.assertEqual((seen[2].extras, seen[2].budget_per_hour, seen[2].repo), (("agent",), 5, diff --git a/tests/test_foundations_mcp.py b/tests/test_foundations_mcp.py index 4da54b6..01b2e42 100644 --- a/tests/test_foundations_mcp.py +++ b/tests/test_foundations_mcp.py @@ -184,7 +184,7 @@ class LauncherTests(unittest.TestCase): def run_server(self, frames, *foundations): with tempfile.TemporaryDirectory() as directory: argv = [sys.executable, "-B", str(TOOL), "--aor", "alpha", "--state-root", str(Path(directory) / "state"), - "--device", "testbox", "--fleet", str(write_fleet(directory))] + "--device", "testbox", "--allow-memory-ledger", "--fleet", str(write_fleet(directory))] for name in foundations: argv += ["--foundation", name] return subprocess.run(argv, cwd=ROOT, input="".join(json.dumps(f) + "\n" for f in frames), @@ -205,6 +205,15 @@ def test_stdio_lists_and_calls_the_chosen_foundation(self): self.assertEqual(content["receipt"]["result"], {"observation": "synthetic"}) self.assertEqual(content["receipt"]["evidence"][0]["evidence"]["status"], "CHECK") + def test_refuses_to_start_without_a_durable_ledger(self): + with tempfile.TemporaryDirectory() as directory: + argv = [sys.executable, "-B", str(TOOL), "--aor", "alpha", "--state-root", str(Path(directory) / "state"), + "--device", "testbox", "--fleet", str(write_fleet(directory)), "--foundation", "template"] + done = subprocess.run(argv, cwd=ROOT, input="", capture_output=True, text=True, timeout=120) + self.assertEqual(done.returncode, 2, done.stderr) + self.assertIn("cstack_init.py", done.stderr) + self.assertFalse((Path(directory) / "state").exists()) + def test_unregistered_foundation_refuses_to_start(self): done = self.run_server([], "nope") self.assertNotEqual(done.returncode, 0) diff --git a/tests/test_mcp_driving_adapter.py b/tests/test_mcp_driving_adapter.py index ae2b7b0..4c25985 100644 --- a/tests/test_mcp_driving_adapter.py +++ b/tests/test_mcp_driving_adapter.py @@ -24,7 +24,7 @@ def argv(state, fleet, aor="alpha"): return [sys.executable, "-B", str(TOOL), "--aor", aor, "--state-root", str(state), "--device", "testbox", - "--fleet", str(fleet)] + "--fleet", str(fleet), "--allow-memory-ledger"] class Server: @@ -157,7 +157,7 @@ def build(*args, **kwargs): with mock.patch.dict(os.environ, {}, clear=False), mock.patch.object(launcher, "build_aor_session", build): os.environ.pop("CSTACK_MCP_SERVER", None) with self.assertRaises(SystemExit): - launcher.main(["--aor", "alpha", "--device", "testbox"]) + launcher.main(["--aor", "alpha", "--device", "testbox", "--allow-memory-ledger"]) self.assertEqual(seen["marker"], "1") diff --git a/tools/check_readme.py b/tools/check_readme.py index f634598..f4630b1 100644 --- a/tools/check_readme.py +++ b/tools/check_readme.py @@ -90,8 +90,19 @@ def approve_on_tty(check, command): check.record(command, document.get("run_status") == "completed" and outcomes, f"typed approve on a real pty: run_status {document.get('run_status')}, outcomes {outcomes}") +def init_session(check, command): + home = Path(tempfile.mkdtemp(prefix="cstack-home-")) + env = {**check.env, "HOME": str(home)} + first = subprocess.run(command.split(), cwd=check.clone, env=env, capture_output=True, text=True, timeout=120) + again = subprocess.run([*command.split(), "--check"], cwd=check.clone, env=env, capture_output=True, text=True, timeout=120) + ledger = (home / ".local/state/cstack/ledger.json").is_file() + shutil.rmtree(home, ignore_errors=True) + check.record(command, first.returncode == 0 and again.returncode == 0 and ledger, f"exit {first.returncode}, --check exit {again.returncode}, ledger.json {'written' if ledger else 'missing'}; {first.stdout.strip().splitlines()[-1:]}") + + def mcp_session(check, command): state = Path(tempfile.mkdtemp(prefix="cstack-state-")) + subprocess.run(["python", "-B", "tools/cstack_init.py", "--state-root", str(state), "--device", "example-host"], cwd=check.clone, env=check.env, capture_output=True, text=True, timeout=120) argv = command.replace("/tmp/cstack-state", str(state)).split() process = subprocess.Popen(argv, cwd=check.clone, env=check.env, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) frames = [dict(jsonrpc="2.0", id=1, method="initialize", params=dict(protocolVersion="2024-11-05", capabilities={}, clientInfo=dict(name="check", version="1"))), @@ -143,7 +154,8 @@ def main(): check.run_status(REAL_FORGE, "completed", "candidate_passed") config.write_text(config.read_text().replace(CLAUDE_TRANSPORT, STUB_TRANSPORT)) check.plain("python -B -c \"from adapters.aor_registry import load_fleet; print(load_fleet('aors/fleet.json').approver)\"", lambda out: out.strip() == "owner-via-approver") - mcp_session(check, "python -B tools/cstack_mcp.py --aor example --device example-host --state-root /tmp/cstack-state") + init_session(check, "python -B tools/cstack_init.py") + mcp_session(check, "python -B tools/cstack_mcp.py --aor example --state-root /tmp/cstack-state") skipped = gh_unavailable(check.env) for command in NEEDS_GH: if skipped: diff --git a/tools/cstack_init.py b/tools/cstack_init.py new file mode 100644 index 0000000..990c76e --- /dev/null +++ b/tools/cstack_init.py @@ -0,0 +1,54 @@ +"""cstack init: set up this machine so every bot keeps a durable, signed ledger. Safe to run again. + + python -B tools/cstack_init.py set up, or finish a setup that stopped part way + python -B tools/cstack_init.py --check report health; changes nothing +""" +import argparse +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) +from adapters.local_setup import default_state_root, init_command, setup +from bootstrap import DEFAULT_FLEET + +LABELS = {"created": "created", "fixed": "fixed ", "ok": "ok ", "problem": "PROBLEM"} + + +def render(report, check): + root = report.state_root + out = [f"Cstack {'health check' if check else 'setup'}: {root}", ""] + out += [f" {LABELS[status]} {text}" for status, text in report.lines] + out.append("") + if report.problems: + out.append(f"Not ready: {len(report.problems)} problem(s) above. Fix them, then run " + f"`{init_command(root)}{' --check' if check else ''}` again.") + return "\n".join(out) + bots = ", ".join(report.bots) + out.append(f"Ready. Bots: {bots}. Device: {report.device}. Every bot records to a durable, signed ledger " + "that survives restarts.") + if report.local_witnesses: + out.append("The ledger's two witnesses are local keys on this machine, so nothing outside it vouches for " + "the record yet. See docs/guides/how-to/set-up.md#witnesses.") + state = "" if root == default_state_root() else f" --state-root {root}" + first = report.bots[0] if report.bots else "SLUG" + out += ["", "Next:", + f" Start a bot's server: python -B tools/cstack_mcp.py --aor {first}{state}", + f" Check health later: {init_command(root)} --check"] + return "\n".join(out) + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--check", action="store_true", help="report health without changing anything") + parser.add_argument("--state-root", type=Path, default=default_state_root(), help="where state and the ledger live") + parser.add_argument("--fleet", type=Path, default=DEFAULT_FLEET, help="the bot list (aors/fleet.json)") + parser.add_argument("--device", help="this machine's device name in the bot list; default: recorded, else " + "Tailscale, else the computer's name") + args = parser.parse_args(argv) + report = setup(args.state_root, args.fleet, device=args.device, write=not args.check) + print(render(report, args.check)) + return 1 if report.problems else 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/cstack_mcp.py b/tools/cstack_mcp.py index 81b06ef..b3d5069 100644 --- a/tools/cstack_mcp.py +++ b/tools/cstack_mcp.py @@ -3,36 +3,33 @@ A host starts one of these per bot, from its own MCP configuration: python -B tools/cstack_mcp.py --aor example --device example-host The AOR is fixed here, at launch; nothing a bot sends can change it. --fleet-mail adds the mail_* tools -(adapters/fleet_mail.py), sent as this AOR; without it the server is unchanged. The device is this machine's tailnet -name (first label of its DNSName), and state lives in ~/.local/state/cstack/ unless --state-root is given. +(adapters/fleet_mail.py), sent as this AOR; without it the server is unchanged. The device is --device, else the name +`cstack init` recorded, else this machine's tailnet name. State lives in ~/.local/state/cstack/ unless --state-root is +given, and the server refuses to start there without the durable ledger `cstack init` sets up, unless +--allow-memory-ledger is given for a throwaway development session. """ import argparse -import json import os -import subprocess import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) from adapters.mcp_stdio_server import McpServer # noqa: E402 from adapters.fleet_mail import DEFAULT_BUDGET, FleetMailConfig # noqa: E402 +from adapters.local_setup import SetupError, default_state_root, require_durable, resolve_device # noqa: E402 from bootstrap import DEFAULT_FLEET, build_aor_session # noqa: E402 MCP_MARKER = "CSTACK_MCP_SERVER" -def tailnet_hostname(): - status = json.loads(subprocess.run(["tailscale", "status", "--json", "--self"], capture_output=True, - text=True, timeout=10, check=True).stdout) - return status["Self"]["DNSName"].split(".")[0].lower() - - def main(argv=None): parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("--aor", required=True, help="bot slug from aors/fleet.json") - parser.add_argument("--state-root", type=Path, default=Path.home() / ".local/state/cstack") - parser.add_argument("--device", help="override the tailnet device name (tests only)") + parser.add_argument("--state-root", type=Path, default=default_state_root()) + parser.add_argument("--device", help="override the recorded or tailnet device name") + parser.add_argument("--allow-memory-ledger", action="store_true", + help="development only: start without a durable ledger; the record is lost when it stops") parser.add_argument("--fleet", type=Path, default=DEFAULT_FLEET, help="host-owned AOR registry") parser.add_argument("--fleet-mail", action="store_true", help="enable the mail_* tools (off by default)") parser.add_argument("--fleet-mail-repo", default=FleetMailConfig.repo, help="private repo holding fleet mail") @@ -45,7 +42,14 @@ def main(argv=None): # Marks this process (and its children) as a bot's MCP server: host-only tools such as # tools/scheduled_approvals.py refuse to run under it. os.environ[MCP_MARKER] = "1" - session = build_aor_session(args.aor, state_root=args.state_root, hostname=args.device or tailnet_hostname(), + try: + if not args.allow_memory_ledger: + require_durable(args.state_root) + hostname = args.device or resolve_device(args.state_root) + except SetupError as error: + sys.stderr.write(f"cstack: {error}\n") + raise SystemExit(2) from None + session = build_aor_session(args.aor, state_root=args.state_root, hostname=hostname, fleet_path=args.fleet, fleet_mail=mail) try: McpServer(session, name=f"cstack-{args.aor}").serve() diff --git a/tools/foundations_mcp.py b/tools/foundations_mcp.py index fb5052b..318c537 100644 --- a/tools/foundations_mcp.py +++ b/tools/foundations_mcp.py @@ -6,7 +6,8 @@ sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) from adapters.foundations_mcp import FoundationsMcpServer # noqa: E402 from bootstrap import DEFAULT_FLEET, build_aor_session, foundation_inventories # noqa: E402 -from tools.cstack_mcp import MCP_MARKER, tailnet_hostname # noqa: E402 +from adapters.local_setup import SetupError, default_state_root, require_durable, resolve_device # noqa: E402 +from tools.cstack_mcp import MCP_MARKER # noqa: E402 def domain_id(name): @@ -19,14 +20,23 @@ def main(argv=None): parser.add_argument("--aor", required=True, help="bot slug from the fleet registry") parser.add_argument("--foundation", action="append", required=True, metavar="NAME", help="registered Foundation to expose, such as refrigeration; repeatable") - parser.add_argument("--state-root", type=Path, default=Path.home() / ".local/state/cstack") - parser.add_argument("--device", help="override the tailnet device name (tests only)") + parser.add_argument("--state-root", type=Path, default=default_state_root()) + parser.add_argument("--device", help="override the recorded or tailnet device name") + parser.add_argument("--allow-memory-ledger", action="store_true", + help="development only: start without a durable ledger; the record is lost when it stops") parser.add_argument("--fleet", type=Path, default=DEFAULT_FLEET, help="host-owned AOR registry") args = parser.parse_args(argv) foundations = [domain_id(name) for name in args.foundation] os.environ[MCP_MARKER] = "1" + try: + if not args.allow_memory_ledger: + require_durable(args.state_root) + hostname = args.device or resolve_device(args.state_root) + except SetupError as error: + sys.stderr.write(f"cstack: {error}\n") + raise SystemExit(2) from None inventories = foundation_inventories(foundations) - session = build_aor_session(args.aor, state_root=args.state_root, hostname=args.device or tailnet_hostname(), + session = build_aor_session(args.aor, state_root=args.state_root, hostname=hostname, fleet_path=args.fleet, foundations=foundations) try: FoundationsMcpServer(session, inventories, name=f"cstack-foundations-{args.aor}").serve()