pcmcp 1.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pcmcp-1.1.0.dist-info/METADATA +108 -0
- pcmcp-1.1.0.dist-info/RECORD +57 -0
- pcmcp-1.1.0.dist-info/WHEEL +5 -0
- pcmcp-1.1.0.dist-info/entry_points.txt +2 -0
- pcmcp-1.1.0.dist-info/licenses/LICENSE +21 -0
- pcmcp-1.1.0.dist-info/top_level.txt +1 -0
- pcmcp_swarm/__init__.py +6 -0
- pcmcp_swarm/__main__.py +288 -0
- pcmcp_swarm/bots/__init__.py +0 -0
- pcmcp_swarm/bots/bot_a.py +102 -0
- pcmcp_swarm/bots/bot_b.py +130 -0
- pcmcp_swarm/bots/bot_c.py +56 -0
- pcmcp_swarm/bots/bot_e.py +112 -0
- pcmcp_swarm/bots/bot_s.py +48 -0
- pcmcp_swarm/bots/common.py +132 -0
- pcmcp_swarm/checkin/__init__.py +42 -0
- pcmcp_swarm/checkin/handler.py +143 -0
- pcmcp_swarm/checkin/local_inbox.py +65 -0
- pcmcp_swarm/checkin/stubs.py +34 -0
- pcmcp_swarm/config.py +137 -0
- pcmcp_swarm/daemon.py +70 -0
- pcmcp_swarm/doorbell/__init__.py +69 -0
- pcmcp_swarm/doorbell/gmail_imap.py +70 -0
- pcmcp_swarm/doorbell/local.py +87 -0
- pcmcp_swarm/doorbell/stubs.py +13 -0
- pcmcp_swarm/drive/__init__.py +39 -0
- pcmcp_swarm/drive/_testentry.py +41 -0
- pcmcp_swarm/drive/api.py +378 -0
- pcmcp_swarm/drive/browse.py +219 -0
- pcmcp_swarm/drive/cli.py +541 -0
- pcmcp_swarm/drive/compare_icloud.py +78 -0
- pcmcp_swarm/drive/fake.py +329 -0
- pcmcp_swarm/drive/icloud.py +73 -0
- pcmcp_swarm/drive/inventory.py +199 -0
- pcmcp_swarm/drive/language_baseline.py +34 -0
- pcmcp_swarm/drive/language_experiment.py +147 -0
- pcmcp_swarm/drive/owner.py +156 -0
- pcmcp_swarm/drive/planfile.py +379 -0
- pcmcp_swarm/drive/runs.py +152 -0
- pcmcp_swarm/drive/selftest.py +920 -0
- pcmcp_swarm/drive/swarm.py +654 -0
- pcmcp_swarm/drive/tasks.py +68 -0
- pcmcp_swarm/drive/trigger.py +766 -0
- pcmcp_swarm/health.py +123 -0
- pcmcp_swarm/mcp_server.py +411 -0
- pcmcp_swarm/plans.py +112 -0
- pcmcp_swarm/registry.py +130 -0
- pcmcp_swarm/runner.py +190 -0
- pcmcp_swarm/scanner.py +139 -0
- pcmcp_swarm/screenshot/__init__.py +15 -0
- pcmcp_swarm/screenshot/linux.py +24 -0
- pcmcp_swarm/screenshot/macos.py +43 -0
- pcmcp_swarm/screenshot/windows.py +21 -0
- pcmcp_swarm/secret_store.py +37 -0
- pcmcp_swarm/selftest.py +360 -0
- pcmcp_swarm/signing.py +95 -0
- pcmcp_swarm/util.py +119 -0
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pcmcp
|
|
3
|
+
Version: 1.1.0
|
|
4
|
+
Summary: PCMCP: cross-platform instant file-state change bot swarm with a stdlib-only MCP server.
|
|
5
|
+
Author-email: Angela Wilkinson <angie@synhumanitylabs.com>
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://synomize.io
|
|
8
|
+
Project-URL: Repository, https://github.com/Missprincessish/PCMCP
|
|
9
|
+
Project-URL: Issues, https://github.com/Missprincessish/PCMCP/issues
|
|
10
|
+
Keywords: mcp,model-context-protocol,swarm,automation,mac
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Operating System :: MacOS
|
|
13
|
+
Classifier: Operating System :: POSIX
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Topic :: System :: Systems Administration
|
|
16
|
+
Requires-Python: >=3.9
|
|
17
|
+
Description-Content-Type: text/markdown
|
|
18
|
+
License-File: LICENSE
|
|
19
|
+
Dynamic: license-file
|
|
20
|
+
|
|
21
|
+
<img width="512" height="279" alt="PCMCP logo" src="https://github.com/user-attachments/assets/712ad48c-ddf6-422b-ab1f-d522f1aa8c2c" />
|
|
22
|
+
|
|
23
|
+
# PCMCP
|
|
24
|
+
|
|
25
|
+
**Start on Mac. Continue anywhere. Send it back. Nothing gets lost.**
|
|
26
|
+
|
|
27
|
+
PCMCP is two things in one repo:
|
|
28
|
+
|
|
29
|
+
1. **The original WebMCP cross-platform task handoff demo** (browser MCP tools hand a task capsule between machines).
|
|
30
|
+
2. **The PCMCP Deterministic Bot Swarm** — up to 100 deterministic, hash-logged, reversible file bots, plus an iMessage text trigger so a phone can ask a Mac for status, screenshots and more.
|
|
31
|
+
|
|
32
|
+
## What actually works (tested, no hand-waving)
|
|
33
|
+
|
|
34
|
+
| Feature | Status |
|
|
35
|
+
|---|---|
|
|
36
|
+
| WebMCP capsule handoff demo (`send_capsule` / `receive_capsule`) | works; run locally with `npm start` |
|
|
37
|
+
| Swarm selftest (bots, registry, plans, approval, undo, crash-resume, doorbell, signed check-in) | 57/57 on macOS (arm64), Python 3.15 |
|
|
38
|
+
| iMessage text trigger → screenshot, attached back to the chat as `.png` | verified live: attachment confirmed present in the Messages database, not just "sent" |
|
|
39
|
+
| iMessage text trigger → screensaver start | verified live (bounded launch, honest failure reporting) |
|
|
40
|
+
| Text trigger commands: `status`, `live`, `inventory`, `task`, `browse`, `run` | implemented and unit-tested |
|
|
41
|
+
| Trigger parser: a command quoted inside a normal sentence is never executed | 10/10 unit tests; line-anchored full-match parsing |
|
|
42
|
+
| Cross-platform selftest | 57/57 on macOS (arm64) and Linux, verified from a fresh public-repo download; Windows not yet run |
|
|
43
|
+
|
|
44
|
+
## The iMessage text trigger
|
|
45
|
+
|
|
46
|
+
The Mac reads the Messages database read-only. A text from an allowed sender can do:
|
|
47
|
+
|
|
48
|
+
```text
|
|
49
|
+
PCMCP-<secret> status live swarm status
|
|
50
|
+
PCMCP-<secret> live listener health: uptime, poll rate, active jobs, last acted command + age, free disk
|
|
51
|
+
PCMCP-<secret> screensaver start the Mac screensaver (reversible action; verified launch only)
|
|
52
|
+
PCMCP-<secret> screenshot screenshot of the screen, attached back as .png
|
|
53
|
+
PCMCP-<secret> inventory drive read-only Google Drive inventory (attached .txt listing)
|
|
54
|
+
PCMCP-<secret> inventory icloud look-only iCloud Drive listing (names, sizes, downloaded/cloud-only)
|
|
55
|
+
PCMCP-<secret> inventory missing compare iCloud with Documents and Downloads (read-only)
|
|
56
|
+
PCMCP-<secret> task <name> one named read-only task (attached .txt)
|
|
57
|
+
PCMCP-<secret> browse <alias.index> browse approved folders by numbered child directories
|
|
58
|
+
PCMCP-<secret> run <plan-prefix> start a plan the owner already signed with a passphrase
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
Safety rules that matter:
|
|
62
|
+
|
|
63
|
+
- **The secret is a doorbell, not an approval.** There is no text command for approve.
|
|
64
|
+
- One command per line: a command quoted inside a normal sentence is never executed.
|
|
65
|
+
- The Mac stores only the SHA-256 of the secret; replies never contain it; each message acts at most once, only if new, incoming, from an allowed sender, inside the rate limit.
|
|
66
|
+
- Nothing a text can reach writes, moves or deletes — except `run`, which executes only a plan signed with the owner passphrase, one shot per approval, never after her stop or a rollback.
|
|
67
|
+
|
|
68
|
+
See the docstring of `pcmcp_swarm/drive/trigger.py` for the full safety model.
|
|
69
|
+
|
|
70
|
+
## Deterministic bot swarm
|
|
71
|
+
|
|
72
|
+
Up to 100 bots: plain Python, no AI, no randomness. Every action is pre-approved by the owner, logged with SHA-256 hashes, and reversible (deletes and overwrites are staged, never destroyed). Doorbell + HMAC-signed instruction batches: the orchestrator can propose; only the local owner CLI can approve.
|
|
73
|
+
|
|
74
|
+
- Docs: [SWARM_README.md](SWARM_README.md) • Data format: [SPEC.md](SPEC.md) • Task ledger: [SWARM_TASKS.md](SWARM_TASKS.md) • Drive plan format: [DRIVE_PLAN_SPEC.md](DRIVE_PLAN_SPEC.md)
|
|
75
|
+
- Code: [`pcmcp_swarm/`](pcmcp_swarm/) (Python standard library only, no `pip install`)
|
|
76
|
+
- Selftest: `python3 -m pcmcp_swarm.selftest`
|
|
77
|
+
|
|
78
|
+
## MCP server
|
|
79
|
+
|
|
80
|
+
The swarm speaks Model Context Protocol, standard library only, no `pip install`:
|
|
81
|
+
|
|
82
|
+
```bash
|
|
83
|
+
python3 -m pcmcp_swarm mcp
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
Tools: `swarm_status`, `swarm_meter` (fleet health meter: per-bot verdict OK / WARN / STALLED / BROKEN with evidence and repair advice, so the client knows which arm of the swarm is broken), `swarm_plan_list`, `swarm_plan_show`, `swarm_scan` (proposes a plan, changes nothing), `swarm_execute` (dry-run by default), `swarm_undo` (restores), `swarm_approve` (refuses unless the owner sets `mcp.allow_approval: true` in the config), and `swarm_screenshot` (returns a PNG inline as MCP image content so a vision-capable client can see the screen; refuses unless `mcp.allow_screenshots: true`). Real execution additionally requires `mcp.allow_real_execution: true`. All gates default to false: out of the box an MCP client can look, propose and dry-run, never approve, destroy or photograph anything. A repaired bot returns to OK once its failed op is re-run and completed. Every call is logged to `logs/mcp.jsonl`. Also exposes the bot registry key as an MCP resource (`pcmcp://registry`), answers `prompts/list` and `logging/setLevel`, and speaks protocol versions 2024-11-05, 2025-03-26 and 2025-06-18. Conformance-tested against the documented client wire format: handshake, version fallback, notification silence, parse errors and every startup probe a real client sends.
|
|
87
|
+
|
|
88
|
+
## Built around Instinct
|
|
89
|
+
|
|
90
|
+
PCMCP is built for the new texting agents. I use Instinct daily: it texts my Mac a command (over iMessage), the deterministic swarm does the work, and results come back to the chat, screenshot or file attached. The agent never gets a shell, never gets approve rights, and can only propose work for the owner to approve locally. The trigger parser is hardened so a command quoted inside a normal sentence is never executed, and reply delivery is verified against the Messages database instead of trusting AppleScript's word for it.
|
|
91
|
+
|
|
92
|
+
## WebMCP handoff demo (the original PCMCP)
|
|
93
|
+
|
|
94
|
+
A browser exposes real `document.modelContext.registerTool(...)` WebMCP tools that let an agent send and receive a neutral task capsule, so the same task state can move between computers without remote-controlling the other machine.
|
|
95
|
+
|
|
96
|
+
```bash
|
|
97
|
+
npm start
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
Then open `http://localhost:4173` in your browser. (The live demo used a temporary Cloudflare tunnel; those URLs die by design, so run locally for a fresh one.)
|
|
101
|
+
|
|
102
|
+
## License
|
|
103
|
+
|
|
104
|
+
MIT
|
|
105
|
+
|
|
106
|
+
---
|
|
107
|
+
|
|
108
|
+
Built by **Angela Wilkinson** at **SynHumanity Labs** • [synomize.io](https://synomize.io)
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
pcmcp-1.1.0.dist-info/licenses/LICENSE,sha256=8Yz4bZ29gNtQxOYWQJZWzvuIVIy1Jbf9w6t-kiiUOQg,1083
|
|
2
|
+
pcmcp_swarm/__init__.py,sha256=-FvWpsxPoFA2h29XncO6NFxz6KQiCqflhd2nVy8mUmw,215
|
|
3
|
+
pcmcp_swarm/__main__.py,sha256=mAAfj3iRVik4SSGprKNIpBuRdmj3ykk75rycNAbNXB0,13011
|
|
4
|
+
pcmcp_swarm/config.py,sha256=Y8zlWWfS621H-2lGs1K9YpBSwlWvob1BedWz_BGIK1k,7067
|
|
5
|
+
pcmcp_swarm/daemon.py,sha256=wCRjzFjytiMg4drsIZ2wxtWMyrC1Hvn8oM1qhOCoLgk,2996
|
|
6
|
+
pcmcp_swarm/health.py,sha256=0z_U2G-zyZBGGqu4QHDQ_heuhyW9hGSYNQXohTFB3U8,5606
|
|
7
|
+
pcmcp_swarm/mcp_server.py,sha256=wH_pzPPASt0D1r8uWgDADlhOE-0nraNjWSbPlNQeVBg,20432
|
|
8
|
+
pcmcp_swarm/plans.py,sha256=BqXPYv8QBtVqjiIBCxutmW2MqWcTHudFn-amioq_Tlk,4883
|
|
9
|
+
pcmcp_swarm/registry.py,sha256=wCpQqssFwh5TjYOsk9Y_9p3n5q3Cp_70jT_lYfdt-l8,5802
|
|
10
|
+
pcmcp_swarm/runner.py,sha256=vhcUVJCRVJii2BLEvTLW8fOPCBSQI-LiBWIZaXL_UB4,9184
|
|
11
|
+
pcmcp_swarm/scanner.py,sha256=gurFWSRPCQUXNoQoCxB0WqSLlQIwsOdVDMct1HNmIlo,5976
|
|
12
|
+
pcmcp_swarm/secret_store.py,sha256=_U6c9-tjr-8uBUX8022yZ15fPb7ZyjSd06x8NeRlTkI,1474
|
|
13
|
+
pcmcp_swarm/selftest.py,sha256=4IN9pP02UbVFv_YMgg1pLUuBHqz0zpyoq5ZFCpmKSVE,20992
|
|
14
|
+
pcmcp_swarm/signing.py,sha256=SDPDfP1B0KXlzU3p2xjxSoN6Kk6saKRN7B0jCDHhh6E,4220
|
|
15
|
+
pcmcp_swarm/util.py,sha256=lmZrdtkECUQeG0j2RWl_SCx4sMstUiuU8wwYhPXn4l4,3689
|
|
16
|
+
pcmcp_swarm/bots/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
17
|
+
pcmcp_swarm/bots/bot_a.py,sha256=tsYUMn-mV1ktsKAsk-NF72LmnGQp40deQepLV2etzcM,4299
|
|
18
|
+
pcmcp_swarm/bots/bot_b.py,sha256=___PPzHCRPYUxQVh8RdbRoCn8Z8dNpW5T4eIMqf1o3Y,5473
|
|
19
|
+
pcmcp_swarm/bots/bot_c.py,sha256=DLkeIW5VmXF9YMypEGPseD2kx-xZZUJCU44RU2V9U9g,2328
|
|
20
|
+
pcmcp_swarm/bots/bot_e.py,sha256=QPF47h-YX_F0nZUOv78qR3f6hOvwzSXSxGrTFofGQqo,4799
|
|
21
|
+
pcmcp_swarm/bots/bot_s.py,sha256=x2316GRdScKN1gGRRWWKJxTyzx0w_C7Uj0VFyMycUUQ,2079
|
|
22
|
+
pcmcp_swarm/bots/common.py,sha256=5exlx-nILn8VcebkR9tA2xVtf0D815MvbON6OKNlvgc,5533
|
|
23
|
+
pcmcp_swarm/checkin/__init__.py,sha256=Hm-FdxO4xdMzNLqClAqpKBPOoQEi77iHVbqwfEBCDJw,1683
|
|
24
|
+
pcmcp_swarm/checkin/handler.py,sha256=XYxBsJqbWW5amRNw6JXLD2nrHkscNPx5SNZ3cGlO8X4,7738
|
|
25
|
+
pcmcp_swarm/checkin/local_inbox.py,sha256=X6qnt6Gl8HU8WGUsW1MGP2vjY5vyzPykJpcSxtcg8ag,2476
|
|
26
|
+
pcmcp_swarm/checkin/stubs.py,sha256=r5hdS1c74_GlucuI4JMgYaFAaL8Si2mcWjug1ji_XUg,1433
|
|
27
|
+
pcmcp_swarm/doorbell/__init__.py,sha256=SNRuv5-Vzvvwun0GCAIfPEo_IIaFipf5NZgX1BBjB2I,2370
|
|
28
|
+
pcmcp_swarm/doorbell/gmail_imap.py,sha256=A14r2R6QtUGDHy5JoBfm1PI0wyAtd1weagh4RULcHI8,2907
|
|
29
|
+
pcmcp_swarm/doorbell/local.py,sha256=mCtX_70Nqzl63-Li_n7fspuyNSTW2zjcDHe9LtDQ_6s,2864
|
|
30
|
+
pcmcp_swarm/doorbell/stubs.py,sha256=VomEfobi1mhoTRiN2vhzTsImb3qyXwfsx-4zhtoyUns,481
|
|
31
|
+
pcmcp_swarm/drive/__init__.py,sha256=2g7U9hwDK1rCAX7VZIIvGPf4Z6SUR9F74lD223Nzau0,1589
|
|
32
|
+
pcmcp_swarm/drive/_testentry.py,sha256=Qjc2bjejfFlC4vvzsA0nBj952gyoVq2FZW7WQGSrP9A,1570
|
|
33
|
+
pcmcp_swarm/drive/api.py,sha256=eKxNECRlpijXpSev-0_d4YcSse7nZbCq8wtLkffU3Ds,17143
|
|
34
|
+
pcmcp_swarm/drive/browse.py,sha256=H4NJtEMJkDj1RKBEr08Vdf1K7wIoMUYWKRq248ZAakk,11044
|
|
35
|
+
pcmcp_swarm/drive/cli.py,sha256=poenpqdX8DFdBuvdxL8yU2yHXJxjQhd-YzS6h5IhtZo,29469
|
|
36
|
+
pcmcp_swarm/drive/compare_icloud.py,sha256=bWsxwwh74Ma0VOyA8II0fRO16Hpt4cmMabsodAywh5s,3251
|
|
37
|
+
pcmcp_swarm/drive/fake.py,sha256=9Y_-ol8aBhEz5JVQg3r3cRgRT23G980GrYFJHcMeyvU,16434
|
|
38
|
+
pcmcp_swarm/drive/icloud.py,sha256=TrJxceME_nkEwdBf99E06nZvaxiJCy5v1bu-ZAB27no,3492
|
|
39
|
+
pcmcp_swarm/drive/inventory.py,sha256=OFZBAllTF4qGOU7oDatV0ViQazBnRSlCAI0RZrEbzdc,9141
|
|
40
|
+
pcmcp_swarm/drive/language_baseline.py,sha256=ypyPhLrLrLjbM-XFMa1qzcmVli3lSrz3ZPiOnLST-mM,1598
|
|
41
|
+
pcmcp_swarm/drive/language_experiment.py,sha256=D6jnb4kMuXI6VhmpaL_krl2qihF0RFGkjaCp5vqVFic,7029
|
|
42
|
+
pcmcp_swarm/drive/owner.py,sha256=PjFVCJdyjqxwpJZrCfIsUt_uMsFbi-fUkYUe4Wkthp8,7496
|
|
43
|
+
pcmcp_swarm/drive/planfile.py,sha256=MVie-8NnOWYNJPojDGHI0pSMiJaC8DLzD8jDcF2RV_k,18948
|
|
44
|
+
pcmcp_swarm/drive/runs.py,sha256=_iYNRuJpL2ew8stXaapYBDggsOAABWH2g6CGE7KBYQY,5552
|
|
45
|
+
pcmcp_swarm/drive/selftest.py,sha256=lyo5_WNVFyl1WhWctVSJuKLi8qNlP2Ou6DZzYMad5XE,56863
|
|
46
|
+
pcmcp_swarm/drive/swarm.py,sha256=G9fUnG41VIaubS2UdCyHW4dHoCHxjZJP59e2uJNRaXk,32153
|
|
47
|
+
pcmcp_swarm/drive/tasks.py,sha256=KQS6aJZSweMZEV2BWJL-FPY0V67GvqnwxanEQ2AfvbU,3166
|
|
48
|
+
pcmcp_swarm/drive/trigger.py,sha256=fyeKlvMWvnqLanq6ABc81-Z47CMpvNfaQ1bbWLkhI8E,43990
|
|
49
|
+
pcmcp_swarm/screenshot/__init__.py,sha256=bQc9qr3VGU8auKUs-ivxR_cM-gP8989G6eBA0puqLpQ,470
|
|
50
|
+
pcmcp_swarm/screenshot/linux.py,sha256=XGUbYUTQeofkxrwEnetfgBM_IzdFfG8ig59NAPlYyx8,1157
|
|
51
|
+
pcmcp_swarm/screenshot/macos.py,sha256=20Dgwv0BGrVLVaCssyoHeqXHDX3lCmw-2SfsfiNrQpk,1672
|
|
52
|
+
pcmcp_swarm/screenshot/windows.py,sha256=2xsixpfWsOphXuWGrCFYmuXypHbhdmdNBfeLgawAz9w,1062
|
|
53
|
+
pcmcp-1.1.0.dist-info/METADATA,sha256=XjGVnHTJvmIDvMdz9bmlmly-WT3MSutwmxU7W2vh4V8,7230
|
|
54
|
+
pcmcp-1.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
55
|
+
pcmcp-1.1.0.dist-info/entry_points.txt,sha256=BOJFBuh_KXS8nunpnqq3VPzVQYtjjoU19ongaSEKN2c,58
|
|
56
|
+
pcmcp-1.1.0.dist-info/top_level.txt,sha256=LcrbFEMGcPhTuhpBUat7hufQ-I0T7Ma8z_zwghKO740,12
|
|
57
|
+
pcmcp-1.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Angela Christine Wilkinson
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
pcmcp_swarm
|
pcmcp_swarm/__init__.py
ADDED
pcmcp_swarm/__main__.py
ADDED
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
"""PCMCP swarm command line. Run from the repo root: python3 -m pcmcp_swarm <command>
|
|
2
|
+
|
|
3
|
+
Owner-only actions (approve, execute --for-real, undo, pending approve) exist ONLY here, on the local
|
|
4
|
+
machine. No doorbell or check-in channel can reach them.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import argparse
|
|
9
|
+
import json
|
|
10
|
+
import os
|
|
11
|
+
import secrets as py_secrets
|
|
12
|
+
import sys
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
from . import config as config_mod, health, plans as plans_mod, registry as reg_mod, runner, scanner, signing
|
|
16
|
+
from .util import atomic_write_json, now_iso, read_json
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _ctx(args):
|
|
20
|
+
cfg = config_mod.load(args.config)
|
|
21
|
+
return cfg, config_mod.data_paths(cfg)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def cmd_init(args):
|
|
25
|
+
cpath = config_mod.config_path(args.config)
|
|
26
|
+
user_cfg = read_json(cpath, {}) or {}
|
|
27
|
+
if args.data_dir:
|
|
28
|
+
user_cfg["data_dir"] = str(Path(args.data_dir).expanduser().resolve())
|
|
29
|
+
roots = set(user_cfg.get("allowed_roots", []))
|
|
30
|
+
roots.update(str(Path(r).expanduser().resolve()) for r in args.allow_root or [])
|
|
31
|
+
user_cfg["allowed_roots"] = sorted(roots)
|
|
32
|
+
if args.inbox:
|
|
33
|
+
user_cfg.setdefault("checkin", {}).setdefault("local_inbox", {})["inbox_dir"] = str(Path(args.inbox).expanduser())
|
|
34
|
+
if args.outbox:
|
|
35
|
+
user_cfg.setdefault("checkin", {}).setdefault("local_inbox", {})["outbox_dir"] = str(Path(args.outbox).expanduser())
|
|
36
|
+
atomic_write_json(cpath, user_cfg)
|
|
37
|
+
cfg, paths = _ctx(args)
|
|
38
|
+
for k in ("plans", "journal", "health", "quarantine", "screenshots"):
|
|
39
|
+
paths[k].mkdir(parents=True, exist_ok=True)
|
|
40
|
+
reg = reg_mod.build(cfg["fleet"])
|
|
41
|
+
old = read_json(paths["registry"])
|
|
42
|
+
if old and not args.force:
|
|
43
|
+
print(f"registry exists at {paths['registry']} (use --force to rebuild from config.fleet)")
|
|
44
|
+
reg = reg_mod.load(paths["registry"])
|
|
45
|
+
else:
|
|
46
|
+
reg_mod.save(paths["registry"], reg)
|
|
47
|
+
paths["registry_key"].write_text(reg_mod.render_key(reg), encoding="utf-8")
|
|
48
|
+
_keygen(cfg, force=False)
|
|
49
|
+
print(f"config: {cpath}\ndata dir: {paths['root']}\nregistry: {paths['registry']}\nkey: {paths['registry_key']}")
|
|
50
|
+
print(f"allowed roots: {cfg['allowed_roots'] or 'NONE (bots will refuse everything until you add one)'}")
|
|
51
|
+
if cfg["doorbell"]["trigger"].startswith("CHANGE-ME"):
|
|
52
|
+
print("NOTE: set doorbell.trigger in the config file; until then no ring can ever be valid.")
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _keygen(cfg, force):
|
|
56
|
+
spec = cfg["checkin"]["secret"]
|
|
57
|
+
if spec.get("type") != "file":
|
|
58
|
+
return
|
|
59
|
+
p = Path(spec["path"]).expanduser()
|
|
60
|
+
if p.exists() and not force:
|
|
61
|
+
return
|
|
62
|
+
p.parent.mkdir(parents=True, exist_ok=True)
|
|
63
|
+
p.write_text(py_secrets.token_hex(32) + "\n", encoding="utf-8")
|
|
64
|
+
try:
|
|
65
|
+
os.chmod(p, 0o600)
|
|
66
|
+
except OSError:
|
|
67
|
+
pass
|
|
68
|
+
print(f"wrote new check-in secret to {p} (share it with the orchestrator out of band)")
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def cmd_keygen(args):
|
|
72
|
+
cfg, _ = _ctx(args)
|
|
73
|
+
_keygen(cfg, force=args.force)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def cmd_status(args):
|
|
77
|
+
cfg, paths = _ctx(args)
|
|
78
|
+
st = health.status(paths, reg_mod.load(paths["registry"]), cfg)
|
|
79
|
+
print(json.dumps(st, indent=2) if args.json else health.render(st))
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def cmd_scan(args):
|
|
83
|
+
cfg, paths = _ctx(args)
|
|
84
|
+
reg = reg_mod.load(paths["registry"])
|
|
85
|
+
root = os.path.realpath(args.root)
|
|
86
|
+
from .util import is_within
|
|
87
|
+
if not any(is_within(root, r) for r in cfg["allowed_roots"]):
|
|
88
|
+
sys.exit(f"refused: {root} is not inside allowed_roots {cfg['allowed_roots']}")
|
|
89
|
+
plan, classification = scanner.build_plan(root, cfg, reg, {"kind": "local_scan", "by": "owner-cli"})
|
|
90
|
+
plans_mod.save(paths, plan)
|
|
91
|
+
(paths["plans"] / f"{plan['plan_hash']}.txt").write_text(plans_mod.render(plan), encoding="utf-8")
|
|
92
|
+
atomic_write_json(paths["plans"] / f"{plan['plan_hash']}.classification.json", classification)
|
|
93
|
+
res = runner.execute(paths, cfg, reg, plan, dry_run=True, log=lambda *_: None)
|
|
94
|
+
print(plans_mod.render(plan) if not args.quiet else f"plan {plan['plan_hash']}")
|
|
95
|
+
print(f"\nDRY RUN (nothing changed): {res['counts']}")
|
|
96
|
+
print(f"plan hash: {plan['plan_hash']}")
|
|
97
|
+
print(f"approve with: python3 -m pcmcp_swarm approve {plan['plan_hash'][:12]}")
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def cmd_plan(args):
|
|
101
|
+
cfg, paths = _ctx(args)
|
|
102
|
+
if args.action == "list":
|
|
103
|
+
for p in sorted(paths["plans"].glob("*.json")):
|
|
104
|
+
if p.name.endswith(".classification.json"):
|
|
105
|
+
continue
|
|
106
|
+
pl = read_json(p)
|
|
107
|
+
print(f"{pl['plan_hash'][:12]} approved={plans_mod.is_approved(paths, pl['plan_hash'])} "
|
|
108
|
+
f"{pl['body']['summary'].get('total_operations')} ops {pl['body']['root']}")
|
|
109
|
+
else:
|
|
110
|
+
print(plans_mod.render(plans_mod.load(paths, args.ref)))
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def cmd_approve(args):
|
|
114
|
+
"""SAFETY: the owner approval gate. Applies only to the exact plan hash shown."""
|
|
115
|
+
cfg, paths = _ctx(args)
|
|
116
|
+
reg = reg_mod.load(paths["registry"])
|
|
117
|
+
plan = plans_mod.load(paths, args.ref)
|
|
118
|
+
problems = plans_mod.validate(plan, reg, cfg["allowed_roots"])
|
|
119
|
+
if problems:
|
|
120
|
+
sys.exit("refusing to approve an invalid plan: " + "; ".join(problems))
|
|
121
|
+
h = plan["plan_hash"]
|
|
122
|
+
print(f"plan {h}\nsummary: {json.dumps(plan['body']['summary'])}")
|
|
123
|
+
if not args.yes:
|
|
124
|
+
if not sys.stdin.isatty():
|
|
125
|
+
sys.exit("approval needs an interactive terminal (or --yes when you are scripting it yourself)")
|
|
126
|
+
typed = input(f"Type the first 8 characters of the plan hash to approve ({h[:8]}): ").strip()
|
|
127
|
+
if typed != h[:8]:
|
|
128
|
+
sys.exit("not approved")
|
|
129
|
+
rec = plans_mod.record_approval(paths, h)
|
|
130
|
+
print(f"approved {h} at {rec['approved_at']}")
|
|
131
|
+
if args.execute:
|
|
132
|
+
_run_real(cfg, paths, reg, plan)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _run_real(cfg, paths, reg, plan):
|
|
136
|
+
res = runner.execute(paths, cfg, reg, plan, dry_run=False)
|
|
137
|
+
print(f"result: {res['counts']} halted: {res['halted']}")
|
|
138
|
+
rep = runner.report(paths, plan)
|
|
139
|
+
atomic_write_json(paths["root"] / "reports" / f"{plan['plan_hash']}.json", rep)
|
|
140
|
+
print(f"report: {paths['root'] / 'reports' / (plan['plan_hash'] + '.json')}")
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def cmd_execute(args):
|
|
144
|
+
cfg, paths = _ctx(args)
|
|
145
|
+
reg = reg_mod.load(paths["registry"])
|
|
146
|
+
plan = plans_mod.load(paths, args.ref)
|
|
147
|
+
if not args.for_real:
|
|
148
|
+
res = runner.execute(paths, cfg, reg, plan, dry_run=True)
|
|
149
|
+
print(f"DRY RUN (nothing changed): {res['counts']}. Add --for-real to execute an approved plan.")
|
|
150
|
+
return
|
|
151
|
+
try:
|
|
152
|
+
_run_real(cfg, paths, reg, plan)
|
|
153
|
+
except runner.NotApproved as e:
|
|
154
|
+
sys.exit(str(e))
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def cmd_undo(args):
|
|
158
|
+
cfg, paths = _ctx(args)
|
|
159
|
+
reg = reg_mod.load(paths["registry"])
|
|
160
|
+
plan = plans_mod.load(paths, args.ref)
|
|
161
|
+
res = runner.undo(paths, cfg, reg, plan, op_id=args.op)
|
|
162
|
+
print(f"undo receipts: {[(r.get('op_id'), r.get('status')) for r in res['receipts']]}")
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def cmd_report(args):
|
|
166
|
+
cfg, paths = _ctx(args)
|
|
167
|
+
plan = plans_mod.load(paths, args.ref)
|
|
168
|
+
rep = runner.report(paths, plan)
|
|
169
|
+
out = paths["root"] / "reports" / f"{plan['plan_hash']}.json"
|
|
170
|
+
atomic_write_json(out, rep)
|
|
171
|
+
if args.json:
|
|
172
|
+
print(json.dumps(rep, indent=2))
|
|
173
|
+
return
|
|
174
|
+
print(f"REPORT {rep['plan_hash']} approved={rep['approved']}")
|
|
175
|
+
for bot, b in rep["per_bot"].items():
|
|
176
|
+
print(f" {bot:<5} executed={b['executed']:<4} undone={b['undone']:<3} errors={len(b['errors'])} {b['first']} -> {b['last']}")
|
|
177
|
+
print(f" undo events: {len(rep['undo_events'])}\nfull report (all hashes): {out}")
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def cmd_ring(args):
|
|
181
|
+
cfg, _ = _ctx(args)
|
|
182
|
+
from .doorbell.local import spool_ring
|
|
183
|
+
print(f"rang local spool: {spool_ring(cfg, args.text)}")
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def cmd_listen(args):
|
|
187
|
+
cfg, paths = _ctx(args)
|
|
188
|
+
from .daemon import listen
|
|
189
|
+
listen(paths, cfg, once=args.once)
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def cmd_checkin(args):
|
|
193
|
+
cfg, paths = _ctx(args)
|
|
194
|
+
from .checkin.handler import check_in
|
|
195
|
+
print(check_in(paths, cfg, wake_reason="manual"))
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def cmd_sign(args):
|
|
199
|
+
"""Reference signer (for testing, and as the spec for the orchestrator's own signer)."""
|
|
200
|
+
cfg, _ = _ctx(args)
|
|
201
|
+
from .secret_store import get_secret
|
|
202
|
+
batch = read_json(args.file)
|
|
203
|
+
batch.setdefault("schema", signing.BATCH_SCHEMA)
|
|
204
|
+
batch.setdefault("schema_version", 1)
|
|
205
|
+
env = signing.sign(batch, get_secret(cfg["checkin"]["secret"]))
|
|
206
|
+
out = Path(args.out or (cfg["checkin"]["local_inbox"]["inbox_dir"] + f"/{batch['batch_id']}.json")).expanduser()
|
|
207
|
+
atomic_write_json(out, env)
|
|
208
|
+
print(f"signed batch written to {out}")
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def cmd_pending(args):
|
|
212
|
+
cfg, paths = _ctx(args)
|
|
213
|
+
from .checkin import get_channel
|
|
214
|
+
from .checkin.handler import pending, take_screenshot
|
|
215
|
+
items = pending(paths)
|
|
216
|
+
if args.action == "list":
|
|
217
|
+
for p in items:
|
|
218
|
+
print(f"{p['request_id']} {p['kind']} {p['target']} {p['at']}")
|
|
219
|
+
if not items:
|
|
220
|
+
print("no pending requests")
|
|
221
|
+
return
|
|
222
|
+
match = [p for p in items if p["request_id"] == args.id]
|
|
223
|
+
if not match:
|
|
224
|
+
sys.exit(f"no pending request {args.id}")
|
|
225
|
+
receipt, att = take_screenshot(paths, cfg, reg_mod.load(paths["registry"]), match[0]["target"], args.id)
|
|
226
|
+
receipt.update(schema="pcmcp.batch_receipt", schema_version=1, batch_id=args.id, kind="screenshot", at=now_iso())
|
|
227
|
+
print(f"{receipt['status']}: {receipt.get('screenshot')} -> {get_channel(cfg).post_receipts(receipt, att)}")
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def cmd_registry(args):
|
|
231
|
+
cfg, paths = _ctx(args)
|
|
232
|
+
reg = reg_mod.load(paths["registry"])
|
|
233
|
+
print(reg_mod.render_key(reg))
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def main(argv=None):
|
|
237
|
+
ap = argparse.ArgumentParser(prog="python3 -m pcmcp_swarm", description="PCMCP deterministic bot swarm")
|
|
238
|
+
ap.add_argument("--config", help="config file (default $PCMCP_CONFIG or ~/.pcmcp/config.json)")
|
|
239
|
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
|
240
|
+
|
|
241
|
+
s = sub.add_parser("init", help="create config, data dir, registry, key and check-in secret")
|
|
242
|
+
s.add_argument("--allow-root", action="append", help="folder the bots may touch (repeatable)")
|
|
243
|
+
s.add_argument("--data-dir"); s.add_argument("--inbox"); s.add_argument("--outbox")
|
|
244
|
+
s.add_argument("--force", action="store_true", help="rebuild registry from config.fleet")
|
|
245
|
+
s.set_defaults(fn=cmd_init)
|
|
246
|
+
s = sub.add_parser("keygen"); s.add_argument("--force", action="store_true"); s.set_defaults(fn=cmd_keygen)
|
|
247
|
+
s = sub.add_parser("status", help="health dashboard"); s.add_argument("--json", action="store_true"); s.set_defaults(fn=cmd_status)
|
|
248
|
+
s = sub.add_parser("scan", help="dry-run scan a folder and propose a plan (changes nothing)")
|
|
249
|
+
s.add_argument("root"); s.add_argument("--quiet", action="store_true"); s.set_defaults(fn=cmd_scan)
|
|
250
|
+
s = sub.add_parser("plan"); s.add_argument("action", choices=["show", "list"]); s.add_argument("ref", nargs="?", default="latest")
|
|
251
|
+
s.set_defaults(fn=cmd_plan)
|
|
252
|
+
s = sub.add_parser("approve", help="OWNER: approve one exact plan hash")
|
|
253
|
+
s.add_argument("ref"); s.add_argument("--yes", action="store_true"); s.add_argument("--execute", action="store_true")
|
|
254
|
+
s.set_defaults(fn=cmd_approve)
|
|
255
|
+
s = sub.add_parser("execute", help="dry-run a plan; --for-real runs an approved plan")
|
|
256
|
+
s.add_argument("ref"); s.add_argument("--for-real", action="store_true"); s.set_defaults(fn=cmd_execute)
|
|
257
|
+
s = sub.add_parser("undo", help="OWNER: reverse a plan (or one op) from its receipts")
|
|
258
|
+
s.add_argument("ref"); s.add_argument("--op"); s.set_defaults(fn=cmd_undo)
|
|
259
|
+
s = sub.add_parser("report"); s.add_argument("ref"); s.add_argument("--json", action="store_true"); s.set_defaults(fn=cmd_report)
|
|
260
|
+
s = sub.add_parser("ring", help="ring the local doorbell"); s.add_argument("text"); s.set_defaults(fn=cmd_ring)
|
|
261
|
+
s = sub.add_parser("listen", help="run the doorbell listener"); s.add_argument("--once", action="store_true"); s.set_defaults(fn=cmd_listen)
|
|
262
|
+
s = sub.add_parser("checkin", help="check in once now, without a doorbell"); s.set_defaults(fn=cmd_checkin)
|
|
263
|
+
s = sub.add_parser("sign", help="sign a batch JSON with the shared secret (reference signer)")
|
|
264
|
+
s.add_argument("file"); s.add_argument("--out"); s.set_defaults(fn=cmd_sign)
|
|
265
|
+
s = sub.add_parser("pending", help="OWNER: list/approve pending screenshot requests")
|
|
266
|
+
s.add_argument("action", choices=["list", "approve"]); s.add_argument("id", nargs="?"); s.set_defaults(fn=cmd_pending)
|
|
267
|
+
s = sub.add_parser("registry", help="print the registry key"); s.set_defaults(fn=cmd_registry)
|
|
268
|
+
s = sub.add_parser("mcp", help="run the MCP server (stdio) for agent clients: propose-only until the owner enables config gates")
|
|
269
|
+
s.set_defaults(fn=lambda args: (_ for _ in ()).throw(SystemExit(_mcp_main())))
|
|
270
|
+
from .drive import cli as drive_cli
|
|
271
|
+
drive_cli.add_parser(sub)
|
|
272
|
+
args = ap.parse_args(argv)
|
|
273
|
+
if argv is not None:
|
|
274
|
+
args._argv = ["python3", "-m", "pcmcp_swarm", *argv]
|
|
275
|
+
from .drive.api import DriveError, ForbiddenOperation
|
|
276
|
+
try:
|
|
277
|
+
args.fn(args)
|
|
278
|
+
except (FileNotFoundError, ValueError, RuntimeError, PermissionError, DriveError, ForbiddenOperation) as e:
|
|
279
|
+
sys.exit(f"error: {e}")
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def _mcp_main():
|
|
283
|
+
from .mcp_server import serve
|
|
284
|
+
return serve()
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
if __name__ == "__main__":
|
|
288
|
+
main()
|
|
File without changes
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
"""Letter A — create a new file or folder. Deterministic: same order, same result."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import base64
|
|
5
|
+
import os
|
|
6
|
+
|
|
7
|
+
from .common import Refuse, check_path, file_rec, load_intent, qdir, run, save_intent, stage, unstage
|
|
8
|
+
from ..util import sha256_bytes, sha256_file
|
|
9
|
+
|
|
10
|
+
LETTER = "A"
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _content(params) -> bytes:
|
|
14
|
+
if "content_b64" in params:
|
|
15
|
+
return base64.b64decode(params["content_b64"])
|
|
16
|
+
return str(params.get("content", "")).encode("utf-8")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def create_folder(order, mode):
|
|
20
|
+
p = check_path(order, order["params"]["path"])
|
|
21
|
+
intent = load_intent(order)
|
|
22
|
+
if p.exists() and not p.is_dir():
|
|
23
|
+
raise Refuse(f"a file already exists where the folder should be: {p}")
|
|
24
|
+
if mode == "dry_run":
|
|
25
|
+
return {"status": "would_do" if not p.exists() else "already_done", "dst": str(p),
|
|
26
|
+
"note": "folder exists" if p.exists() else "will create folder"}
|
|
27
|
+
if intent is None:
|
|
28
|
+
intent = {"existed_before": p.exists()}
|
|
29
|
+
save_intent(order, intent)
|
|
30
|
+
p.mkdir(parents=True, exist_ok=True)
|
|
31
|
+
return {"status": "done", "dst": str(p),
|
|
32
|
+
"undo": {"kind": "remove_folder_if_created_and_empty", "path": str(p), "created": not intent["existed_before"]}}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def create_file(order, mode):
|
|
36
|
+
params = order["params"]
|
|
37
|
+
p = check_path(order, params["path"])
|
|
38
|
+
data = _content(params)
|
|
39
|
+
want = sha256_bytes(data)
|
|
40
|
+
cur = sha256_file(p)
|
|
41
|
+
intent = load_intent(order)
|
|
42
|
+
if cur is not None and cur != want and intent is None and not params.get("overwrite"):
|
|
43
|
+
raise Refuse(f"file exists and overwrite was not approved: {p}")
|
|
44
|
+
if mode == "dry_run":
|
|
45
|
+
return {"status": "already_done" if cur == want else "would_do", "dst": str(p),
|
|
46
|
+
"files": [file_rec("dst", p, cur, want)]}
|
|
47
|
+
if intent is None:
|
|
48
|
+
intent = {"sha256_before": cur}
|
|
49
|
+
save_intent(order, intent)
|
|
50
|
+
staged_old = None
|
|
51
|
+
if intent["sha256_before"] is not None and intent["sha256_before"] != want:
|
|
52
|
+
staged_old = qdir(order, "overwritten", p.name)
|
|
53
|
+
if p.exists() and sha256_file(p) == intent["sha256_before"]:
|
|
54
|
+
stage(p, staged_old) # overwrite: old content goes to quarantine first
|
|
55
|
+
if sha256_file(p) != want:
|
|
56
|
+
tmp = p.with_name(p.name + ".pcmcp-tmp")
|
|
57
|
+
p.parent.mkdir(parents=True, exist_ok=True)
|
|
58
|
+
with open(tmp, "wb") as f:
|
|
59
|
+
f.write(data)
|
|
60
|
+
f.flush()
|
|
61
|
+
os.fsync(f.fileno())
|
|
62
|
+
os.replace(tmp, p)
|
|
63
|
+
return {"status": "done", "dst": str(p), "files": [file_rec("dst", p, intent["sha256_before"], sha256_file(p))],
|
|
64
|
+
"undo": {"kind": "unstage_created_file", "path": str(p), "sha256": want,
|
|
65
|
+
"restore_overwritten": str(staged_old) if staged_old else None,
|
|
66
|
+
"overwritten_sha256": intent["sha256_before"] if staged_old else None}}
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def undo_create_folder(order, mode):
|
|
70
|
+
u = order["undo"]
|
|
71
|
+
p = check_path(order, u["path"])
|
|
72
|
+
if not u.get("created"):
|
|
73
|
+
return {"status": "done", "note": "folder pre-existed; left in place"}
|
|
74
|
+
if not p.exists():
|
|
75
|
+
return {"status": "already_done"}
|
|
76
|
+
if any(p.iterdir()):
|
|
77
|
+
raise Refuse(f"folder not empty, will not remove: {p}")
|
|
78
|
+
if mode != "dry_run":
|
|
79
|
+
p.rmdir() # empty folder only: nothing can be lost
|
|
80
|
+
return {"status": "done" if mode != "dry_run" else "would_do", "dst": str(p)}
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def undo_create_file(order, mode):
|
|
84
|
+
u = order["undo"]
|
|
85
|
+
p = check_path(order, u["path"])
|
|
86
|
+
dest = qdir(order, "undo", p.name)
|
|
87
|
+
files = []
|
|
88
|
+
if p.exists():
|
|
89
|
+
if sha256_file(p) != u["sha256"]:
|
|
90
|
+
raise Refuse(f"file changed since creation, will not undo: {p}")
|
|
91
|
+
if mode != "dry_run":
|
|
92
|
+
stage(p, dest)
|
|
93
|
+
files.append(file_rec("created_file_staged", p, u["sha256"], None))
|
|
94
|
+
if u.get("restore_overwritten") and mode != "dry_run":
|
|
95
|
+
unstage(qdir(order, "overwritten", p.name), p, u["overwritten_sha256"])
|
|
96
|
+
files.append(file_rec("restored_original", p, None, u["overwritten_sha256"]))
|
|
97
|
+
return {"status": "done" if mode != "dry_run" else "would_do", "files": files}
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
if __name__ == "__main__":
|
|
101
|
+
run(LETTER, {"create_folder": create_folder, "create_file": create_file},
|
|
102
|
+
{"create_folder": undo_create_folder, "create_file": undo_create_file})
|