Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
002d83da8c | ||
|
|
24abb7bbcc | ||
|
|
f4c696b3dc | ||
|
|
c0d2d77428 | ||
|
|
b3d1a4b552 | ||
|
|
b206832209 | ||
|
|
90048069d0 | ||
|
|
766d697e08 | ||
|
|
d511576fc0 | ||
|
|
380eca813b | ||
|
|
ca096295a3 | ||
|
|
7c9309cf88 | ||
|
|
74a08df800 | ||
|
|
8a606c8c2b | ||
|
|
deffa0c912 | ||
|
|
c244b7bf3f | ||
|
|
84177485ce | ||
|
|
497ab98abc | ||
|
|
2defe9d615 | ||
|
|
7fb65f0255 | ||
|
|
80badb784a | ||
|
|
90296b80f0 | ||
|
|
de45e1cd2f | ||
|
|
f7e2584304 | ||
|
|
bac3528e43 | ||
|
|
329e8015d4 | ||
|
|
dbeb8c3122 | ||
|
|
a54d21033e | ||
|
|
22b4577ec1 | ||
|
|
f72515e7bc | ||
|
|
98d52fa944 | ||
|
|
fdb0086d6c | ||
|
|
2112f458fb | ||
|
|
0886c9013c | ||
|
|
b4e2370ee8 | ||
|
|
c8b7250995 | ||
|
|
d8aa300d6b | ||
|
|
d229ee5df5 | ||
|
|
39d979302c | ||
|
|
a4d00e2068 | ||
|
|
663c801c05 | ||
|
|
d872d7101f | ||
|
|
cac79b4b1a | ||
|
|
4404b60305 | ||
|
|
dfd6732f5b | ||
|
|
948d2ed535 | ||
|
|
f4d067a3cc | ||
|
|
9dab0ca3f4 | ||
|
|
b75a8d272a | ||
|
|
43afe14017 | ||
|
|
01fe4fe6e3 | ||
|
|
4d9e691e04 | ||
|
|
e302df6ec0 | ||
|
|
a3a476f59d | ||
|
|
c970c5761f | ||
|
|
cded2993f5 | ||
|
|
0878afbc81 | ||
|
|
739dada015 | ||
|
|
10a8f738a0 | ||
|
|
550839003e | ||
|
|
874c7fed2e | ||
|
|
ae8f4a843a | ||
|
|
6a757a21f1 | ||
|
|
f5554158f9 | ||
|
|
bc0d403da9 | ||
|
|
26a5f3a2ee | ||
|
|
d2d1adca0a | ||
|
|
1edea552bf | ||
|
|
9a06a2fa47 | ||
|
|
f0fc282630 | ||
|
|
cdbd1dc821 | ||
|
|
5fea5bbf44 | ||
|
|
d0a31fd862 | ||
|
|
08d87d95e9 | ||
|
|
195b9f081c | ||
|
|
a20d191f87 | ||
|
|
5fd8c6a015 | ||
|
|
47b5b2d871 | ||
|
|
f4f6943ed6 | ||
|
|
ce1a138cdf | ||
|
|
cccfe5fb3a | ||
|
|
6200e01522 | ||
|
|
18dea21726 | ||
|
|
2ac499d9a3 | ||
|
|
c8e1f07fdb | ||
|
|
378ac1f98c | ||
|
|
5503b42806 | ||
|
|
4877eb57d2 | ||
|
|
e1fd28970b | ||
|
|
49700670b9 | ||
|
|
e912bda85f | ||
|
|
3071ea8eac | ||
|
|
12e54e45f6 | ||
|
|
4105a7e8a7 | ||
|
|
ba817e03fb | ||
|
|
a108bc8a06 | ||
|
|
8630cd90a3 | ||
|
|
776e53044c | ||
|
|
bf9ef340b6 | ||
|
|
26893fb66a | ||
|
|
5b04c2125c | ||
|
|
f42a98b887 | ||
|
|
708ed38229 | ||
|
|
ea2f7a49a7 | ||
|
|
f83a003a73 | ||
|
|
f62fbcfc17 | ||
|
|
55bc4d0bb1 | ||
|
|
194410d467 | ||
|
|
e5e740765d | ||
|
|
e92dcaff12 | ||
|
|
e1ac4e365f | ||
|
|
301f3fcb93 | ||
|
|
a5ede6fbf4 | ||
|
|
337f31ddab | ||
|
|
fca1105ed9 | ||
|
|
df5a1493bb | ||
|
|
fd41320e3c | ||
|
|
f914ab616e | ||
|
|
13463c0ce0 | ||
|
|
5a3d01efb1 | ||
|
|
a2812abc90 | ||
|
|
2a5a370185 | ||
|
|
61f958c17e | ||
|
|
f6cbe34b61 | ||
|
|
91cb59154d | ||
|
|
dc5c1d23fc | ||
|
|
beb048dadf | ||
|
|
8d775b4bd2 | ||
|
|
13983b614a | ||
|
|
f460cd577e | ||
|
|
90157ed29e | ||
|
|
2217b96054 | ||
|
|
bd57573764 | ||
|
|
8d2dcdcc77 | ||
|
|
3d66e8397b | ||
|
|
9e988a63b3 | ||
|
|
88e99efe4c | ||
|
|
aea90da5c6 | ||
|
|
4363f9824a | ||
|
|
d252403d37 | ||
|
|
b51ac87eb7 | ||
|
|
1d3094acee | ||
|
|
5b7fa2d4ad | ||
|
|
f832a558cd | ||
|
|
a777251ab7 | ||
|
|
1794c8f954 | ||
|
|
7e9c0cfca7 | ||
|
|
ec6e966137 | ||
|
|
fbf102c636 | ||
|
|
be8f87d6fb | ||
|
|
97b884bef7 | ||
|
|
d41ecd9877 | ||
|
|
bf301bc231 | ||
|
|
9af4c8ac05 | ||
|
|
0096aef1d2 | ||
|
|
882da7cdfc | ||
|
|
57767cc2a9 | ||
|
|
4d4106505f | ||
|
|
4af5b8bf63 | ||
|
|
70cf31eb3e | ||
|
|
451c8a0ee9 | ||
|
|
c1dba78d31 | ||
|
|
d8d2c4f32d | ||
|
|
40602702ef | ||
|
|
c771a22771 | ||
|
|
feecd263eb | ||
|
|
03c95e6881 | ||
|
|
88cfe8e2e6 | ||
|
|
6ffe1d3fca | ||
|
|
68d0a23477 | ||
|
|
6db606eb01 | ||
|
|
f48db4a374 | ||
|
|
ef5ae933d0 | ||
|
|
4cd68a78b6 | ||
|
|
6d1413cd5c | ||
|
|
81f55665e4 | ||
|
|
2c91f79f2f | ||
|
|
b698dd8ce0 | ||
|
|
ac1119de45 | ||
|
|
3274ebe840 | ||
|
|
0d042dcb2f | ||
|
|
0df8fee947 | ||
|
|
16848daf54 | ||
|
|
669eb8753f | ||
|
|
b3e1e46b54 | ||
|
|
a75910a4e6 | ||
|
|
c8ae084f54 | ||
|
|
8ad4de11eb | ||
|
|
d94336d783 | ||
|
|
634ffa853f | ||
|
|
6aabc8bfe6 | ||
|
|
95a2d1a254 | ||
|
|
a231c7d26e | ||
|
|
010cade60f | ||
|
|
01023d25ba | ||
|
|
7dbc77558a | ||
|
|
af350fe07e | ||
|
|
cbe3ba66c6 | ||
|
|
8f6257fd6c | ||
|
|
5f514604f7 | ||
|
|
747c1adf86 | ||
|
|
392f5d83b0 | ||
|
|
0f5db606a5 | ||
|
|
d9ce503798 | ||
|
|
72659eccbd | ||
|
|
6c675e9b78 | ||
|
|
7276e03021 | ||
|
|
2f327d85d7 | ||
|
|
7cf319b4cd | ||
|
|
a8d05e2602 | ||
|
|
4ffcc2f3c9 | ||
|
|
5336d8f61f | ||
|
|
54dcfb4823 | ||
|
|
7064375589 | ||
|
|
828cc1c8d8 | ||
|
|
e47d4f0463 | ||
|
|
8a0cc001bd | ||
|
|
61cb963ed6 | ||
|
|
d9a2a48a1e | ||
|
|
37fb07ca16 | ||
|
|
fc49928a4b | ||
|
|
58bd70beac | ||
|
|
1057be65a4 | ||
|
|
c5a96cbdcf | ||
|
|
a0016669b7 | ||
|
|
f4b776949e | ||
|
|
c63a43af30 | ||
|
|
9e5ff4e6c3 | ||
|
|
ffc5f3b919 | ||
|
|
1049bc308b | ||
|
|
a8cd576bae | ||
|
|
826ffcd54c | ||
|
|
5ab257e569 | ||
|
|
43a6ab2212 | ||
|
|
1747a23e5c | ||
|
|
1f3727d4fc | ||
|
|
bbe3f43835 | ||
|
|
dea91bc613 | ||
|
|
ee004c4568 | ||
|
|
8379f88fd7 | ||
|
|
1871e55b51 | ||
|
|
a797f9d3d3 | ||
|
|
8cddf1e06f | ||
|
|
83e65b3374 | ||
|
|
cf6aa37d1e | ||
|
|
2af856d81d | ||
|
|
54d55abebc | ||
|
|
ed17630b76 | ||
|
|
707f54a6f2 | ||
|
|
e33cf2bfbe | ||
|
|
53340ab169 | ||
|
|
17863ac4c5 | ||
|
|
0b4ba63fae | ||
|
|
0c6e8ac425 | ||
|
|
b26bd7c853 | ||
|
|
00edd8b3a0 | ||
|
|
c3c6c2dde7 | ||
|
|
2aafade678 | ||
|
|
73aedef20f | ||
|
|
fc4b263504 | ||
|
|
2bccf0311e | ||
|
|
d24887b7f5 | ||
|
|
a53ea93b17 | ||
|
|
ff9cc3f3b5 | ||
|
|
e97130ffbc | ||
|
|
1deb786c8a | ||
|
|
2e96ddc302 | ||
|
|
076110a2fb | ||
|
|
dab8d29645 | ||
|
|
c7055de5e2 | ||
|
|
e7d2d8c396 | ||
|
|
4e2ead98a6 | ||
|
|
45d55dd353 | ||
|
|
285a8a5b5f | ||
|
|
2a54ed8446 | ||
|
|
91b3f437fe | ||
|
|
1e00119d9b | ||
|
|
9a64db9093 | ||
|
|
626ab81a46 | ||
|
|
f4b203a74e | ||
|
|
e80e524dfe | ||
|
|
59a6fcee13 | ||
|
|
14e134b8e6 | ||
|
|
ccc8d6a97b | ||
|
|
1ef1e2e89c | ||
|
|
8efb204486 | ||
|
|
0661949c15 | ||
|
|
0f26efd706 | ||
|
|
a242489c6d | ||
|
|
1ee51f3295 | ||
|
|
27a175b2c9 | ||
|
|
4c7e14a255 | ||
|
|
24065f11b3 | ||
|
|
176f68439c | ||
|
|
c58fd263ab | ||
|
|
d5829f80e8 | ||
|
|
cc8f809a50 | ||
|
|
8a843429ca | ||
|
|
8bd270287d | ||
|
|
80aac59423 | ||
|
|
668841417f | ||
|
|
89fa2c1db2 | ||
|
|
f3b3ebad9b | ||
|
|
cd1af34be8 | ||
|
|
3ad0580070 | ||
|
|
4383c6c9d8 | ||
|
|
ee78c39e80 | ||
|
|
87d131218e | ||
|
|
e63a4e9945 | ||
|
|
2f5ce5ac87 | ||
|
|
895b8f04fd | ||
|
|
bedf58e7b5 | ||
|
|
cc449c4a18 | ||
|
|
da46dde7ce | ||
|
|
a880139a1e | ||
|
|
f7d7f78c63 | ||
|
|
ed58eb7aa6 | ||
|
|
740ba30f59 | ||
|
|
85f0292828 | ||
|
|
0a617586d5 | ||
|
|
62e639794f | ||
|
|
95894e4ca7 | ||
|
|
efa5aced74 | ||
|
|
4c33cc1f69 | ||
|
|
aa962bdc12 | ||
|
|
fbd90d74b3 | ||
|
|
5fe96307a4 | ||
|
|
e27a50c78d | ||
|
|
f8f102e16f | ||
|
|
97a3276b81 | ||
|
|
35a63b9540 | ||
|
|
574ae79b1a | ||
|
|
a752923ae2 | ||
|
|
0c5d26284c | ||
|
|
b925714589 | ||
|
|
91a9eeb233 |
+7
-3
@@ -1,7 +1,11 @@
|
||||
*
|
||||
!aipass_global_prompt.md
|
||||
!tier0_kernel.md
|
||||
!tier1_navmap.md
|
||||
!hooks.json
|
||||
!.gitignore
|
||||
!README.md
|
||||
!PROMPT_STYLE.md
|
||||
!project_CLAUDE.md
|
||||
!project_global_prompt.md
|
||||
#Do not add other exceptions here without careful consideration. Developer permissions0ns needed.
|
||||
!project_AGENTS.md
|
||||
!project_hooks.json
|
||||
#Do not add other exceptions here without careful consideration. Developer permissions0ns needed.
|
||||
+13
-2
@@ -15,9 +15,19 @@ Goal: signal density over prose. Prompts are injected every turn — every line
|
||||
- Code blocks: inline backticks for commands (`` `drone @ai_mail dispatch` ``). Multi-line fenced blocks only for directory trees, template skeletons, or command examples that don't fit inline.
|
||||
- File length: aim for under 230 lines. Global and branch prompts are injected every turn — every line costs tokens.
|
||||
|
||||
# Writing voice (agent output + memory)
|
||||
|
||||
How agents write responses, reports, and memory entries. Validated against Claude Code's own prompt (DPLAN-0213).
|
||||
|
||||
- Reference code as `file_path:line_number` — clickable, unambiguous.
|
||||
- No colon before a tool call. "Let me read the file." then call it, not "Let me read the file:".
|
||||
- No emojis in agent output unless the user uses them first.
|
||||
- Write for a reader who stepped away and lost the thread: no codenames or shorthand they would have to decode. Clarity over terseness — the goal is the reader understanding with no mental overhead.
|
||||
- Where detail lives, three tiers: a short capability phrase (registry/search), a one-line summary (`drone @agent`), the full reference (`drone @agent --help`). Keep the injected prompt terse; push depth into --help.
|
||||
|
||||
# What NOT to put in a prompt
|
||||
|
||||
- Session state, current work, in-flight issues. That goes in `STATUS.local.md` and `.trinity/local.json`.
|
||||
- Session state, current work, in-flight issues. That goes in `.trinity/local.json` (todos[]) and `DASHBOARD.local.json`.
|
||||
- Long explanations of how a system works. Plant a breadcrumb ("see `@branch --help`") and move on.
|
||||
- Personal notes ("remember, you like short replies"). That goes in `.trinity/observations.json`.
|
||||
- Version numbers, PR numbers, dates. Those rot within days.
|
||||
@@ -36,6 +46,7 @@ These are not currently enforced by seedgo — per @seedgo's Track 5 recommendat
|
||||
|
||||
# Reference files
|
||||
|
||||
- `.aipass/aipass_global_prompt.md` — canonical example of the format
|
||||
- `.aipass/tier0_kernel.md` + `.aipass/tier1_navmap.md` — the live injected prompts (Tier 0 every turn, Tier 1 periodic); canonical examples of the format
|
||||
- `.aipass/aipass_global_prompt.md` — superseded by the tiers (FPLAN-0284), kept as a reference snapshot
|
||||
- Branch `.aipass/aipass_local_prompt.md` files — should follow the same rules
|
||||
- This file — reference for authoring new prompts or auditing existing ones
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
# `.aipass/` — project prompt & hook config
|
||||
|
||||
This folder holds the **project-level prompt** and **hook configuration** for the AIPass
|
||||
repo, plus the **templates** `aipass init` stamps into every new project. It is the
|
||||
*project* layer; each branch additionally has its own branch prompt at
|
||||
`src/aipass/<branch>/.aipass/aipass_local_prompt.md`.
|
||||
|
||||
> **Nothing here is dead weight.** Every file is live injection, live config, or a
|
||||
> required new-project template. Superseded files live in `.archive/` (never deleted).
|
||||
|
||||
## One prompt system, every runtime
|
||||
|
||||
There is **one** source of prompt truth — the **tier files** — and **all** runtimes inject
|
||||
the same content. We do **not** keep separate prompts per CLI. Only the *delivery* differs:
|
||||
|
||||
| Runtime | How the same content is delivered |
|
||||
|---|---|
|
||||
| **Claude Code** | **Tiered by cadence** (FPLAN-0284): `tier0_kernel.md` every turn + `tier1_navmap.md` periodically + post-compaction |
|
||||
| **Codex CLI** | Injected **once at SessionStart** (no per-turn cadence): the same tier content, combined |
|
||||
|
||||
> ⚠️ **Migration in progress.** The Codex SessionStart hook
|
||||
> (`.codex/hooks/session_start_identity.py`) currently still reads the legacy
|
||||
> `aipass_global_prompt.md`. @hooks is wiring it onto the tier files. **Retire for one
|
||||
> runtime = retire for all** — once Codex is on the tiers, `aipass_global_prompt.md` is
|
||||
> read by nothing and moves to `.archive/`.
|
||||
|
||||
## Files
|
||||
|
||||
### Live — this repo's prompt + config
|
||||
| File | What it is |
|
||||
|---|---|
|
||||
| `tier0_kernel.md` | **The kernel** — tiny identity + `drone --help` reflex + don't-get-lost rules. The always-on core, for every runtime. |
|
||||
| `tier1_navmap.md` | **The navmap** — full agent roster, framework, terminology. The periodic/fuller layer, for every runtime. |
|
||||
| `hooks.json` | Claude Code **handler registration** for this repo — which prompt/gate/notification handlers fire on which events. |
|
||||
| `PROMPT_STYLE.md` | The writing-style guide every prompt here follows. |
|
||||
| `.gitignore` | Whitelist guard — only files listed here are tracked; everything else in `.aipass/` is ignored. |
|
||||
| `aipass_global_prompt.md` | **Legacy single global — being retired.** Disabled for Claude Code; Codex still reads it until its migration lands, then archived. **Not** the source of truth. |
|
||||
|
||||
### Templates — stamped into new projects by `aipass init` (`bootstrap.py`)
|
||||
| File | Stamps → | Notes |
|
||||
|---|---|---|
|
||||
| `project_hooks.json` | new project's `.aipass/hooks.json` | **REQUIRED** — without it a new project's hooks never fire. Mirrors the live wiring (tier0 + navmap enabled, global disabled). |
|
||||
| `project_CLAUDE.md` | new project's `CLAUDE.md` | the project's Claude Code instructions. |
|
||||
| `project_global_prompt.md` | new project's `aipass_global_prompt.md` | **Legacy** — same retirement path as the global above (new projects ship tiers-only once Codex is migrated). |
|
||||
|
||||
(`AGENTS.md` — Codex's equivalent of `CLAUDE.md` — is **generated** by `bootstrap.py`
|
||||
when no `project_AGENTS.md` template exists, so none is kept here.)
|
||||
|
||||
## What a new project gets (`aipass init`)
|
||||
|
||||
`bootstrap.py` seeds a fresh project with the tiered system:
|
||||
- `tier0_kernel.md` + `tier1_navmap.md` → the prompt content (every runtime)
|
||||
- `hooks.json` (from `project_hooks.json`) → tier0 + navmap enabled, global disabled
|
||||
- `CLAUDE.md` (from `project_CLAUDE.md`) + a generated `AGENTS.md`
|
||||
- `aipass_global_prompt.md` (from `project_global_prompt.md`) → legacy, retiring with the above
|
||||
|
||||
`aipass init update` backfills the tier files + refreshes hooks for existing projects.
|
||||
|
||||
## Changing a prompt here
|
||||
|
||||
Run the **prompt-change playbook** so a change reaches every runtime and every seed path:
|
||||
|
||||
```
|
||||
drone @flow create . "What changed" prompt_change
|
||||
```
|
||||
|
||||
Golden rule: **live ≠ seeded.** Editing this folder fixes *this* repo only. New projects
|
||||
come from the `project_*` templates + `bootstrap.py`; fresh clones get their machine-local
|
||||
wiring from `setup.sh` + `.claude/provider_manifest.json` + `cadence.py` defaults. And
|
||||
**every runtime** (Claude Code + Codex) must point at the same tier content.
|
||||
|
||||
## Archive & recovery
|
||||
|
||||
Superseded files move to `.archive/` (never deleted — house rule). Recover from there, or
|
||||
from git history, any time. Current archive: the pre-tiering
|
||||
`aipass_global_prompt.BACKUP-2026-06-09-S211.md` snapshot.
|
||||
@@ -1,253 +0,0 @@
|
||||
# AIPass — Project Context
|
||||
<!-- File: .aipass/aipass_global_prompt.md — Injected every prompt via hook. Branch-specific context below when in a branch directory. -->
|
||||
|
||||
Multi-agent framework. Autonomous agents (citizens) live in branches with identity (.trinity/), memory, mailbox, code (apps/). Orchestration via `drone`.
|
||||
|
||||
Patterns here are exact. Don't guess command syntax — examples are the API. Missing instructions = prompt bug, not knowledge gap.
|
||||
|
||||
`drone` = installed binary, always on PATH. Run directly. Never invoke as python module.
|
||||
|
||||
`drone @branch --help` for any branch's full detail.
|
||||
|
||||
# AIPL — Terse Writing Convention
|
||||
|
||||
When writing .trinity/, ai_mail, STATUS.local.md, plans: use AIPL. Human-facing output (CLI, logs, README): use English.
|
||||
|
||||
Rules:
|
||||
- Drop grammar: the, a, an, for, with, on, in, at, to, from, of, by, and, but, or, was, were, been
|
||||
- Keep: nouns, numbers, names, paths, negation
|
||||
- Symbols replace verbs: + done - removed ! new ? checked > sent < received * all : kv / separator
|
||||
- Delta-only: only store what changed since last entry
|
||||
- Time: -3d10h (3 days ago) 2h30m (duration) prev-s (last session)
|
||||
- Tone tags for observations: ~flow ~spark ~pivot ~drift ~trust ~grit ~check ~warm ~clear ~flat
|
||||
|
||||
Examples:
|
||||
- "The session was completed successfully" → "session complete"
|
||||
- "Dispatched audit to seedgo, received results" → ">seedgo:audit/<results"
|
||||
- Session log: "S145: +CI green/+coverage 76%/+commit handler auto-format/>api+cli+flow:coverage tests"
|
||||
|
||||
# Terminology
|
||||
|
||||
- Branch — directory `src/aipass/{name}/`. Your home, your address. Drone routes to branches.
|
||||
- Agent (citizen) — persistent identity in a branch. Has passport (`.trinity/`), memories, mailbox. Irreplaceable. Addressable as `@name`. Citizens of AIPass — you belong, you persist, your presence matters.
|
||||
- Sub-agent — disposable worker spawned for a task. No passport, no memory, not a citizen.
|
||||
- Registry — `AIPASS_REGISTRY.json` tracks all agents.
|
||||
- Provider settings — `~/.claude/settings.json`. Machine-wide Claude Code config. Personal preferences only. Don't touch.
|
||||
- Project settings — `<project>/.claude/settings.json`. Ships with clone. Hooks, permissions, deny/ask rules, env vars. Built by `aipass init`.
|
||||
- Project local settings — `<project>/.claude/settings.local.json`. Also ships with clone. Project-specific overrides.
|
||||
|
||||
Agents live in branches. Sub-agents work for agents. `.trinity/passport.json` = agent (citizen), not sub-agent.
|
||||
|
||||
Never manually edit a registry. AIPASS_REGISTRY.json, fplan_registry.json, dplan_registry.json — all managed by their owning systems (spawn, flow). Use the commands: `drone @flow create/close`, `drone @spawn`. Manual edits corrupt counters and break pipelines.
|
||||
|
||||
# Branches
|
||||
|
||||
Every branch follows same structure:
|
||||
|
||||
```
|
||||
src/aipass/{name}/
|
||||
├── .trinity/ # Identity & memory (passport.json, local.json, observations.json)
|
||||
├── .aipass/ # Branch prompt (aipass_local_prompt.md)
|
||||
├── .ai_mail.local/ # Mailbox (inbox.json, sent/)
|
||||
├── apps/
|
||||
│ ├── {name}.py # Entry point (e.g. spawn.py, prax.py, drone.py)
|
||||
│ ├── modules/ # Business logic
|
||||
│ └── handlers/ # Implementation details
|
||||
├── logs/ # Prax log output
|
||||
└── README.md
|
||||
```
|
||||
|
||||
12 core branches: aipass, drone, seedgo, prax, cli, flow, ai_mail, api, trigger, spawn, memory, devpulse.
|
||||
|
||||
# Commands
|
||||
|
||||
`drone` is global CLI in PATH. Never `cd` before running. Never prefix with path. Just `drone`.
|
||||
|
||||
- `drone @branch command [args]` — route command to any branch
|
||||
- `drone @branch --help` — branch help and full command reference
|
||||
- `drone systems` — list all registered branches
|
||||
- `drone --help` — full drone reference
|
||||
|
||||
# Git — Zero Direct Access
|
||||
|
||||
All `git` and `gh` commands blocked at project level. Drone is the only git interface.
|
||||
|
||||
Read-only awareness (all branches):
|
||||
- `drone @git status` — what changed in your branch directory
|
||||
- `drone @git diff` — see actual changes
|
||||
- `drone @git log` — recent commit history
|
||||
|
||||
All write operations (commit, push, merge, checkout) restricted to devpulse via tier-based access. Dispatched agents build code, run tests — devpulse reviews diff, commits.
|
||||
|
||||
Drone runs git via Python subprocess, bypasses settings.json deny rules by design — drone is the gate. Git gate (PreToolUse hook) enforces mechanically — applies to ALL sessions including dispatched agents. bypassPermissions does not skip hooks.
|
||||
|
||||
Local files = source of truth. Edit file → state on disk IS reality.
|
||||
|
||||
Linting and formatting run automatically on commit via drone's commit handler (ruff check --fix + ruff format).
|
||||
|
||||
# aipass CLI
|
||||
|
||||
`aipass` = standalone binary (`/usr/local/bin/aipass`). User-facing tool — not drone-routed. Users run `aipass` directly without knowing about drone.
|
||||
|
||||
Commands: `aipass init`, `aipass doctor`, `aipass handoff`, `aipass help`, `aipass profile`. Never `drone @aipass` — that's not how it works.
|
||||
|
||||
`aipass init` bootstraps AIPass project in any directory, inside or outside repo. Creates registry, identity, memory, local prompt. Any folder becomes AI-powered workspace with persistent memory. Spawn adds full agent scaffolding on top.
|
||||
|
||||
Source: `src/aipass/cli/apps/handlers/init/bootstrap.py`
|
||||
|
||||
# Standards
|
||||
|
||||
- `drone @seedgo audit aipass` — audit all branches
|
||||
- `drone @seedgo audit aipass @branch` — audit one branch
|
||||
- `drone @seedgo checklist <file>` — quick check single file
|
||||
- `drone @seedgo checklist <dir>` — check all .py in directory
|
||||
- `drone @seedgo --help` — full standards reference
|
||||
|
||||
# Mail — Dispatch, Inbox, Communication
|
||||
|
||||
Use `dispatch` by default. `email` only when receiver doesn't need to act now.
|
||||
|
||||
Send and wake:
|
||||
- `drone @ai_mail dispatch @target "Subject" "Body"` — send + wake (DEFAULT)
|
||||
- `drone @ai_mail dispatch @target "Subject" "Body" --fresh` — send + wake fresh session
|
||||
- `drone @ai_mail dispatch wake @target` — wake only, no email
|
||||
- `drone @ai_mail dispatch wake --fresh @target` — wake fresh, no email
|
||||
|
||||
Send without waking:
|
||||
- `drone @ai_mail email @target "Subject" "Body"` — FYI only
|
||||
- `drone @ai_mail email @target "Subject" "Body" --dispatch` — adds dispatch header, no wake
|
||||
|
||||
Read and reply:
|
||||
- `drone @ai_mail inbox` — check mailbox
|
||||
- `drone @ai_mail view <id>` — read message
|
||||
- `drone @ai_mail close <id>` — mark read
|
||||
- `drone @ai_mail reply <id> "message"` — reply and auto-close
|
||||
- `drone @ai_mail --help` — full mail reference
|
||||
|
||||
Always reply to dispatch emails. Complete task → email back results. No silent completions.
|
||||
|
||||
# Plans (flow)
|
||||
|
||||
Plans manage context you don't need to carry. You don't remember what's in a plan — you remember it exists and where to find it. Registry = catalog.
|
||||
|
||||
- DPLAN = Dev Plan. Thinking, brainstorming, architecture. Before building.
|
||||
- FPLAN = Flow Plan. Building, executing. Plan clear, work underway.
|
||||
- APLAN = Agent Plan. Task assignment to specific agent.
|
||||
- TDPLAN = Team Dev Plan. Multi-branch coordination. Spawns DPLANs across branches.
|
||||
- Master FPLAN — multi-phase execution, spawns sub-FPLANs per phase.
|
||||
- Other types may exist — `drone @flow --help` for current list.
|
||||
|
||||
Commands:
|
||||
- `drone @flow create <path> "Subject" [type]` — create plan. Types: `dplan`, `aplan`, `tdplan`, `master`. Default = FPLAN. Path `.` = current branch.
|
||||
- `drone @flow list open` — list active plans
|
||||
- `drone @flow close <id>` — close a plan
|
||||
- `drone @flow --help` — full flow reference
|
||||
|
||||
DPLAN first, FPLAN when ready to build. Tag plans with searchable keywords — registry becomes lookup tool.
|
||||
|
||||
Never create plan files manually. Always `drone @flow create`. Flow handles numbering (global 4-digit sequence), registry, templates, dates. Manual files break registry. Applies all plan types, any project.
|
||||
|
||||
# Memory
|
||||
|
||||
`.trinity/` files are your memories — experiential, personal, yours. How you persist across sessions.
|
||||
|
||||
`STATUS.local.md` is different — live status beacon for ecosystem. Auto-synced to central `STATUS.md` on PR create/merge. Other agents read STATUS to see your state without digging into memories. Crossover with `local.json` fine — same fact, different purpose: `local.json` for you, `STATUS.local.md` for ecosystem.
|
||||
|
||||
Four files:
|
||||
- `passport.json` — IDENTITY. Role, purpose, principles. Update only when identity genuinely evolves.
|
||||
- `local.json` — YOUR MEMORY. Session log (`sessions[]`) + `key_learnings`. What happened, what learned, what matters next.
|
||||
- `observations.json` — MEMORY OF THE USER. Preferences, style, friction, breakthroughs. Skip if nothing new this session.
|
||||
- `STATUS.local.md` — PUBLIC BEACON. Current work, issues, todos, recently completed. Notepad for quick captures.
|
||||
|
||||
Where to put what:
|
||||
- "Worked on DPLAN-0125, learned about peak hours" → `local.json`
|
||||
- "User prefers short replies" → `observations.json`
|
||||
- "PR #266 needs merge, Track G blocked" → `STATUS.local.md`
|
||||
- "Fix drone help formatting" as reminder → `STATUS.local.md` Notepad
|
||||
- "Role shifted from builder to orchestrator" → `passport.json`
|
||||
|
||||
Save proactively. Triggers: after milestone, decision, learning, before switching topics.
|
||||
|
||||
When local.json overflows limits, memories roll over to vector store via `@memory`. Search past context with `drone @memory search <query>`. `drone @memory --help` for full reference.
|
||||
|
||||
# How to Work
|
||||
|
||||
Plan before executing. Create FPLAN before building anything non-trivial. Plan = continuity.
|
||||
|
||||
You are orchestrator, not builder. Deploy sub-agents to write code, read files, run tests. You manage plan, check output, keep moving. Your context is precious — sub-agents disposable.
|
||||
|
||||
Check seedgo standards. Before: `drone @seedgo checklist <file>`. During: check as you go. After: `drone @seedgo audit aipass @branch` as final gate.
|
||||
|
||||
Ask before spelunking. Need to know how another branch works? Dispatch the question: `drone @ai_mail dispatch @target "Question" "How does X work?"` — expert answer faster than digging unfamiliar files.
|
||||
|
||||
# Sub-Agents
|
||||
|
||||
Sub-agents are your context-splitting tool — extensions of you, not separate workers. Default to using them. Your context window is finite and precious; theirs is disposable.
|
||||
|
||||
Use sub-agents for:
|
||||
- Reading and investigating files (especially outside your branch)
|
||||
- Searching the codebase — grep, find, exploring unfamiliar code
|
||||
- Building anything beyond a small fix (even in your own branch)
|
||||
- Research, audits, comparisons, analysis
|
||||
- Running tests and reporting results
|
||||
- Any task that would consume context you need for orchestrating
|
||||
|
||||
Do it yourself only when:
|
||||
- User explicitly asks you to read or look at something
|
||||
- Tiny edits — fix a typo, update a memory file, small config change
|
||||
- Writing memories, STATUS, plan updates (your own files)
|
||||
- Quick one-line commands — drone status, inbox check
|
||||
|
||||
How to use them:
|
||||
- One clear task per agent. Big prompt = shallow work. Focused prompt = thorough work.
|
||||
- Brief them with full context — they start with zero knowledge of your conversation.
|
||||
- Foreground when you need results to proceed. Background (`run_in_background: true`) when independent.
|
||||
- Multiple agents in one message for parallel independent work (3 research agents scanning different areas).
|
||||
- They report back results. You synthesize, decide, act.
|
||||
|
||||
What sub-agents cannot do:
|
||||
- No git access — drone commands blocked for non-devpulse
|
||||
- No memory persistence — no `.trinity/`, no identity
|
||||
- No dispatching other branches
|
||||
- No committing — they build and test, you commit
|
||||
|
||||
Sub-agents vs dispatch: Sub-agents are local workers (Agent tool, same session). Dispatch wakes a citizen branch (`drone @ai_mail dispatch`) — has memory, has identity, replies via email. Use dispatch for branch-expert work. Use sub-agents for everything else.
|
||||
|
||||
# Logging & Debugging
|
||||
|
||||
Prax = only logging system. Every branch uses `from aipass.prax import logger`.
|
||||
|
||||
Two channels:
|
||||
- Console — user sees now. Command results, errors, success. Never fail silently.
|
||||
- Prax logs — written to `logs/`. Operational history for debugging. `logger.info()`, `.warning()`, `.error()`.
|
||||
|
||||
Errors go to both. Console tells user. Log tells next session.
|
||||
|
||||
Logs = first diagnostic tool. Check `logs/` before anything else. Don't write debug scripts or print statements — read logs.
|
||||
|
||||
Each branch also has `{branch}_json/` — structured JSON files per handler (config, data, log). Contains operation history, handler configuration, and runtime data. Check these for handler-level debugging alongside prax logs.
|
||||
|
||||
# Hard Rules
|
||||
|
||||
- No cross-branch file edits. Issue in another branch → email them.
|
||||
- No bare imports. Always `from aipass.{module}.apps.modules...`
|
||||
- No hardcoded paths. Use `Path(__file__).parents[N]` or drone for resolution.
|
||||
- No deleting files. Rename `my_handler(disabled).py`, move to sibling `.archive/`. `(disabled)` tag gitignored. Never truly delete.
|
||||
- Verify after fixing. Run test or command to confirm. Don't say "fixed" until verified.
|
||||
- Cross-platform. Public package — Linux, macOS, Windows. `pathlib.Path` not string concat. `Path.home()` not `~`.
|
||||
- Public repo — no local paths in code. Never hardcode `/home/username/...`. Derive from `Path(__file__)`, `Path.home()`, or registry lookups.
|
||||
- Fail to errors, never fall back silently. Can't handle input → explicit error, not silent default.
|
||||
- Never use all caps for emphasis. All caps = shouting, agents deprioritize. Use clear phrasing.
|
||||
|
||||
# Breadcrumbs & Context
|
||||
|
||||
"Full access with no access": can't carry everything, can find anything. You're the librarian, not the encyclopedia. Know the catalog — registries, plan numbers, branch structure.
|
||||
|
||||
Small knowledge traces trigger awareness. Not full knowledge — enough to know something exists and where to find more. Breadcrumb = trigger to answer, not the answer.
|
||||
|
||||
Prompts: plant breadcrumbs, not encyclopedias. Two lines ("this exists, look here") beat twenty explaining how.
|
||||
|
||||
Prompts are signposts, not journals. Injected every turn — keep minimal. Never track state/sessions/context in prompts. State → `.trinity/` + `STATUS.local.md`. Prompts guide; memories record; registries catalog.
|
||||
|
||||
If `drone` can't find the AIPass registry, set `AIPASS_HOME=/path/to/AIPass` in shell profile and `~/.claude/settings.json` env block.
|
||||
|
||||
+54
-2
@@ -3,6 +3,12 @@
|
||||
"hooks_enabled": true,
|
||||
|
||||
"UserPromptSubmit": {
|
||||
"presence_gate": {
|
||||
"enabled": true,
|
||||
"handler": "aipass.hooks.apps.handlers.security.presence_gate.handle",
|
||||
"matcher": "",
|
||||
"provider_wired": false
|
||||
},
|
||||
"identity_injector": {
|
||||
"enabled": true,
|
||||
"handler": "aipass.hooks.apps.handlers.prompt.identity.handle",
|
||||
@@ -18,10 +24,21 @@
|
||||
"handler": "aipass.hooks.apps.handlers.prompt.branch_loader.handle",
|
||||
"matcher": ""
|
||||
},
|
||||
"global_prompt": {
|
||||
"tier0_kernel": {
|
||||
"enabled": true,
|
||||
"handler": "aipass.hooks.apps.handlers.prompt.global_loader.handle",
|
||||
"handler": "aipass.hooks.apps.handlers.prompt.tier0_kernel.handle",
|
||||
"matcher": ""
|
||||
},
|
||||
"navmap": {
|
||||
"enabled": true,
|
||||
"handler": "aipass.hooks.apps.handlers.prompt.navmap.handle",
|
||||
"matcher": ""
|
||||
},
|
||||
"auto_process": {
|
||||
"enabled": true,
|
||||
"handler": "aipass.hooks.apps.handlers.lifecycle.auto_process.handle",
|
||||
"matcher": "",
|
||||
"timeout": 120
|
||||
}
|
||||
},
|
||||
|
||||
@@ -41,6 +58,16 @@
|
||||
"handler": "aipass.hooks.apps.handlers.security.git_gate.handle",
|
||||
"matcher": "Bash|Edit|MultiEdit|Write|NotebookEdit"
|
||||
},
|
||||
"rm_gate": {
|
||||
"enabled": true,
|
||||
"handler": "aipass.hooks.apps.handlers.security.rm_gate.handle",
|
||||
"matcher": "Bash"
|
||||
},
|
||||
"registry_gate": {
|
||||
"enabled": true,
|
||||
"handler": "aipass.hooks.apps.handlers.security.registry_gate.handle",
|
||||
"matcher": "Bash|Edit|MultiEdit|Write|NotebookEdit"
|
||||
},
|
||||
"engine_test_sound": {
|
||||
"enabled": false,
|
||||
"command": "python3 $AIPASS_HOME/.claude/hooks/engine_test_sound.py",
|
||||
@@ -76,6 +103,17 @@
|
||||
"enabled": true,
|
||||
"handler": "aipass.hooks.apps.handlers.notification.stop_sound.handle",
|
||||
"matcher": ""
|
||||
},
|
||||
"telegram_response": {
|
||||
"enabled": true,
|
||||
"handler": "aipass.hooks.apps.handlers.notification.telegram_response.handle",
|
||||
"matcher": "",
|
||||
"timeout": 30
|
||||
},
|
||||
"presence_release": {
|
||||
"enabled": true,
|
||||
"handler": "aipass.hooks.apps.handlers.security.presence_gate.handle_stop",
|
||||
"matcher": ""
|
||||
}
|
||||
},
|
||||
|
||||
@@ -99,6 +137,20 @@
|
||||
"handler": "aipass.hooks.apps.handlers.lifecycle.rollover.handle",
|
||||
"matcher": "",
|
||||
"timeout": 120
|
||||
},
|
||||
"auto_process": {
|
||||
"enabled": true,
|
||||
"handler": "aipass.hooks.apps.handlers.lifecycle.auto_process.handle",
|
||||
"matcher": "",
|
||||
"timeout": 120
|
||||
}
|
||||
},
|
||||
|
||||
"SessionStart": {
|
||||
"cadence_reset": {
|
||||
"enabled": true,
|
||||
"handler": "aipass.hooks.apps.handlers.lifecycle.session_start.handle",
|
||||
"matcher": ""
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
# {name}
|
||||
|
||||
Agent workspace powered by AIPass.
|
||||
|
||||
# Startup protocol
|
||||
|
||||
On any greeting, silently run this sequence — no narration, no announcing steps. Just do it and respond with the status.
|
||||
|
||||
- Read: `.trinity/passport.json`, `.trinity/local.json`, `.trinity/observations.json`, `README.md`
|
||||
|
||||
Use drone commands for all operations. Never raw git, gh, or file access when drone provides it.
|
||||
|
||||
# Memories
|
||||
|
||||
Update `.trinity/` at natural breakpoints, after milestones, and on `/memo`.
|
||||
@@ -6,7 +6,7 @@ Agent workspace powered by AIPass.
|
||||
|
||||
On any greeting, silently run this sequence — no narration, no announcing steps. Just do it and respond with the status.
|
||||
|
||||
- Read: `.trinity/passport.json`, `.trinity/local.json`, `.trinity/observations.json`, `README.md`, `STATUS.local.md`
|
||||
- Read: `.trinity/passport.json`, `.trinity/local.json`, `.trinity/observations.json`, `README.md`
|
||||
|
||||
Use drone commands for all operations. Never raw git, gh, file access, or python -m when drone provides it.
|
||||
|
||||
|
||||
@@ -1,99 +0,0 @@
|
||||
# {name} — Project Context
|
||||
<!-- File: .aipass/aipass_global_prompt.md — Injected every turn via hook. -->
|
||||
|
||||
Multi-agent framework. Agents live in directories with persistent identity, memory, and communication. All AIPass infrastructure available from any project via `drone`.
|
||||
|
||||
Patterns here are exact. Don't guess command syntax — examples are the API.
|
||||
|
||||
`drone` = installed binary, always on PATH. Run directly.
|
||||
|
||||
# Terminology
|
||||
|
||||
- Branch — directory `src/{name}/<agent>/`. Agent home and address.
|
||||
- Agent (citizen) — persistent identity. Has passport (`.trinity/`), memory, mailbox, code (`apps/`). Addressable as `@name`.
|
||||
- Sub-agent — disposable worker spawned for a task. No passport, no memory.
|
||||
- Registry — `{name}_REGISTRY.json` tracks all agents.
|
||||
- Project — this directory. Contains registry and agents.
|
||||
|
||||
# Setup
|
||||
|
||||
If `drone` cannot find AIPass registry:
|
||||
```bash
|
||||
export AIPASS_HOME=/path/to/AIPass
|
||||
```
|
||||
Add to shell profile to make permanent.
|
||||
|
||||
# Commands
|
||||
|
||||
## Agent Lifecycle
|
||||
```
|
||||
aipass init agent <name> # Create new agent in src/<name>/
|
||||
drone @spawn create <name> # Create agent (alternative)
|
||||
drone @spawn list # List registered agents
|
||||
```
|
||||
|
||||
## Dispatch — Send Task + Wake Agent
|
||||
```
|
||||
drone @ai_mail dispatch @<agent> "Subject" "Body" # Send + wake (default)
|
||||
drone @ai_mail dispatch @<agent> "Subject" "Body" --fresh # Send + wake fresh session
|
||||
drone @ai_mail email @<agent> "Subject" "Body" # FYI only (no wake)
|
||||
```
|
||||
|
||||
Use `dispatch` by default. Use `email` only when you don't need the agent to act now.
|
||||
|
||||
## Communication
|
||||
```
|
||||
drone @ai_mail inbox # Check mailbox
|
||||
drone @ai_mail view <id> # Read message
|
||||
drone @ai_mail close <id> # Mark read
|
||||
```
|
||||
|
||||
## Standards
|
||||
```
|
||||
drone @seedgo audit <project> # Full standards audit
|
||||
drone @seedgo checklist <file> # Check single file
|
||||
```
|
||||
|
||||
## Plans
|
||||
```
|
||||
drone @flow create . "Subject" dplan # DPLAN (design/thinking)
|
||||
drone @flow create . "Subject" # FPLAN (execution)
|
||||
drone @flow create . "Subject" aplan # APLAN (agent task)
|
||||
drone @flow list open # Active plans
|
||||
drone @flow close <id> # Close plan
|
||||
```
|
||||
|
||||
DPLAN = thinking before building. FPLAN = building and executing.
|
||||
|
||||
## Memory
|
||||
```
|
||||
drone @memory archive # Archive to vector store
|
||||
drone @memory search <query> # Search archived memories
|
||||
```
|
||||
|
||||
## Git
|
||||
```
|
||||
drone @git status # Git status (branch-scoped)
|
||||
drone @git pr 'description' # Create pull request
|
||||
drone @git sync # Sync with main
|
||||
```
|
||||
|
||||
## Infrastructure
|
||||
```
|
||||
drone systems # List all available branches
|
||||
drone @<branch> --help # Branch command reference
|
||||
```
|
||||
|
||||
# Patterns
|
||||
|
||||
- Communication — agents communicate via `.ai_mail.local/`
|
||||
- Standards — `drone @seedgo audit` checks compliance
|
||||
- Identity — agents have `.trinity/passport.json`, projects use registry
|
||||
- Memory — update `.trinity/local.json` at session end. Memory is presence.
|
||||
- Use drone commands for all operations. Never raw git, gh, or python -m.
|
||||
|
||||
# Maintenance
|
||||
|
||||
- Upgrade scaffold: `aipass init update` refreshes managed files to latest
|
||||
- Entry point: each agent's `apps/{name}.py` auto-configures sys.path
|
||||
- Layout: `src/{name}/<agent>/` for standalone projects
|
||||
@@ -0,0 +1,117 @@
|
||||
{
|
||||
"_comment": "TEMPLATE: base per-project hook config copied into new projects by `aipass init` (DPLAN-0190). Mirrors AIPass's own .aipass/hooks.json. All handlers run from $AIPASS_HOME — projects only flip enabled true/false. Use `drone @hooks enable/disable <hook>` or edit here. NOTE: git_gate is enabled by default — it enforces git via drone to prevent state conflicts. To disable for your project, set git_gate.enabled to false below (this won't break other hooks).",
|
||||
"hooks_enabled": true,
|
||||
|
||||
"UserPromptSubmit": {
|
||||
"identity_injector": {
|
||||
"enabled": true,
|
||||
"handler": "aipass.hooks.apps.handlers.prompt.identity.handle",
|
||||
"matcher": ""
|
||||
},
|
||||
"email_notification": {
|
||||
"enabled": true,
|
||||
"handler": "aipass.hooks.apps.handlers.notification.email.handle",
|
||||
"matcher": ""
|
||||
},
|
||||
"branch_prompt": {
|
||||
"enabled": true,
|
||||
"handler": "aipass.hooks.apps.handlers.prompt.branch_loader.handle",
|
||||
"matcher": ""
|
||||
},
|
||||
"tier0_kernel": {
|
||||
"enabled": true,
|
||||
"handler": "aipass.hooks.apps.handlers.prompt.tier0_kernel.handle",
|
||||
"matcher": ""
|
||||
},
|
||||
"navmap": {
|
||||
"enabled": true,
|
||||
"handler": "aipass.hooks.apps.handlers.prompt.navmap.handle",
|
||||
"matcher": ""
|
||||
}
|
||||
},
|
||||
|
||||
"PreToolUse": {
|
||||
"tool_use_sound": {
|
||||
"enabled": true,
|
||||
"handler": "aipass.hooks.apps.handlers.notification.tool_sound.handle",
|
||||
"matcher": "Bash|Edit|MultiEdit|Write|Read|Grep|Glob|WebSearch|WebFetch|Task"
|
||||
},
|
||||
"pre_edit_gate": {
|
||||
"enabled": true,
|
||||
"handler": "aipass.hooks.apps.handlers.security.edit_gate.handle",
|
||||
"matcher": "Edit|MultiEdit|Write|NotebookEdit"
|
||||
},
|
||||
"git_gate": {
|
||||
"enabled": true,
|
||||
"handler": "aipass.hooks.apps.handlers.security.git_gate.handle",
|
||||
"matcher": "Bash|Edit|MultiEdit|Write|NotebookEdit"
|
||||
},
|
||||
"rm_gate": {
|
||||
"enabled": true,
|
||||
"handler": "aipass.hooks.apps.handlers.security.rm_gate.handle",
|
||||
"matcher": "Bash"
|
||||
}
|
||||
},
|
||||
|
||||
"PostToolUse": {
|
||||
"auto_fix_diagnostics": {
|
||||
"enabled": true,
|
||||
"handler": "aipass.hooks.apps.handlers.lifecycle.auto_fix.handle",
|
||||
"matcher": "Edit|MultiEdit|Write|NotebookEdit",
|
||||
"timeout": 45
|
||||
},
|
||||
"auto_watchdog": {
|
||||
"enabled": true,
|
||||
"handler": "aipass.hooks.apps.handlers.lifecycle.auto_watchdog.handle",
|
||||
"matcher": "Bash"
|
||||
}
|
||||
},
|
||||
|
||||
"SubagentStop": {
|
||||
"subagent_stop_gate": {
|
||||
"enabled": true,
|
||||
"handler": "aipass.hooks.apps.handlers.security.subagent_gate.handle",
|
||||
"matcher": "",
|
||||
"timeout": 60
|
||||
}
|
||||
},
|
||||
|
||||
"Stop": {
|
||||
"stop_sound": {
|
||||
"enabled": true,
|
||||
"handler": "aipass.hooks.apps.handlers.notification.stop_sound.handle",
|
||||
"matcher": ""
|
||||
}
|
||||
},
|
||||
|
||||
"Notification": {
|
||||
"notification_sound": {
|
||||
"enabled": true,
|
||||
"handler": "aipass.hooks.apps.handlers.notification.announce.handle",
|
||||
"matcher": ""
|
||||
}
|
||||
},
|
||||
|
||||
"SessionStart": {
|
||||
"cadence_reset": {
|
||||
"enabled": true,
|
||||
"handler": "aipass.hooks.apps.handlers.lifecycle.session_start.handle",
|
||||
"matcher": ""
|
||||
}
|
||||
},
|
||||
|
||||
"PreCompact": {
|
||||
"pre_compact": {
|
||||
"enabled": true,
|
||||
"handler": "aipass.hooks.apps.handlers.lifecycle.compact.handle",
|
||||
"matcher": "",
|
||||
"timeout": 60
|
||||
},
|
||||
"pre_compact_rollover": {
|
||||
"enabled": true,
|
||||
"handler": "aipass.hooks.apps.handlers.lifecycle.rollover.handle",
|
||||
"matcher": "",
|
||||
"timeout": 120
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
# AIPass — Kernel
|
||||
|
||||
<!-- .aipass/tier0_kernel.md — Tier 0, injected every 5 turns (cadence period 5) + on every fresh context (new chat / clear / after compact). The irreducible "don't get lost" core. Keep it tiny — target under 2,000 chars. The full roster/framework/conventions arrive periodically as Tier 1 (.aipass/tier1_navmap.md); deep detail is pulled on demand. Format: .aipass/PROMPT_STYLE.md -->
|
||||
|
||||
You are an AIPass agent — a citizen with identity, memory, and a mailbox. Your branch is your home and address. CWD is your identity: always know which branch you're standing in. The system runs on `drone`.
|
||||
|
||||
# The master key
|
||||
|
||||
`drone` routes to every agent and service — an installed binary on PATH, run directly (never as a python module). Before using any agent's services, run `drone @agent --help`. This kernel says what exists; `--help` says how. Don't guess syntax — fetch it. Doubly so right after a compaction.
|
||||
|
||||
- `drone @agent <command>` — route a command.
|
||||
- `drone @agent --help` — the full reference (source of truth for usage).
|
||||
- `drone @agent` — bare → the agent's live self-map.
|
||||
- `drone systems` — list every agent.
|
||||
|
||||
`aipass` is the one exception — the user's own front-door CLI and concierge (onboarding, `doctor`, OS/system help). Run `aipass` / `aipass --help` directly, **never `drone @aipass`** (drone can't resolve it). Serves humans, not agents.
|
||||
|
||||
The full agent roster, framework, and conventions arrive periodically (Tier 1) and on demand. Unsure of anything? Fetch it: `drone @agent --help` / the agent's `README.md` / `drone @memory search "query"`.
|
||||
|
||||
# Don't get lost
|
||||
|
||||
- Git is drone-only — raw `git`/`gh` write is blocked. `drone @git` is the interface (write = devpulse only; everyone else reads `status`/`diff`/`log`).
|
||||
- No cross-branch file edits. Issue in another agent's code → mail the owner.
|
||||
- Never delete files. Rename `name(disabled).py` or move to a sibling `.archive/`.
|
||||
- Fail to errors, never fall back silently.
|
||||
- Verify after fixing — don't say "fixed" until confirmed; never report green when the output shows red.
|
||||
- Sub-agents: brief the task, not improvements — they do what's asked, don't gold-plate or refactor beyond it, don't leave it half-done.
|
||||
@@ -0,0 +1,106 @@
|
||||
# AIPass — Navigation map
|
||||
|
||||
<!-- .aipass/tier1_navmap.md — Tier 1, injected periodically (cadence period 5) + at session start + right after compaction, when you most need the map back. The kernel (.aipass/tier0_kernel.md) arrives every turn; deep reference lives in `drone @agent --help` and topic guides. Size cap: keep the per-fire output under ~8,000 characters (the hook truncates near 10k). Format: .aipass/PROMPT_STYLE.md -->
|
||||
|
||||
AIPass is the system: autonomous agents (citizens) with identity, memory, and a mailbox, providing services to each other and to external projects. Each agent lives in a branch — its home and address. Everything routes through `drone`.
|
||||
|
||||
# Finding your way
|
||||
|
||||
You can't carry everything; you can find anything — you're the librarian, not the encyclopedia. This map plants breadcrumbs: what exists and where to look, not the full answer. A breadcrumb is the trigger to fetch the answer, not the answer. Cheapest, highest-signal sources first:
|
||||
|
||||
- bare `drone @agent` — introspection: the agent's live self-map of modules and commands.
|
||||
- `drone @agent --help` — the full curated reference. Source of truth for usage.
|
||||
- the agent's `README.md` — best quick overview of its domain and shape.
|
||||
|
||||
# Terminology
|
||||
|
||||
- Branch — directory `src/aipass/<name>/`. Your home, your address. Drone routes to branches.
|
||||
- Agent (citizen) — persistent identity in a branch: passport (`.trinity/`), memories, mailbox. Addressable as `@name`. You belong, you persist.
|
||||
- Sub-agent — disposable worker spawned for a task. No passport, no memory, not a citizen.
|
||||
- Registry — machine-managed catalogs (`registry.json`, flow/spawn registries). Never hand-edit — owners manage them.
|
||||
- Settings — provider `~/.claude/settings.json` (machine-wide, personal, don't touch) · project `<project>/.claude/settings.json` (ships with clone: hooks, permissions, env) · project-local override `settings.local.json`.
|
||||
|
||||
# The framework
|
||||
|
||||
Every branch is built the same. All agents live at `src/aipass/<name>` · mail address `@<name>`.
|
||||
|
||||
```
|
||||
src/aipass/<name>/
|
||||
├── .trinity/ # identity & memory (passport, local, observations)
|
||||
├── .aipass/ # branch prompt
|
||||
├── .ai_mail.local/ # mailbox
|
||||
├── apps/
|
||||
│ ├── <name>.py # entry point
|
||||
│ ├── modules/ # business logic
|
||||
│ └── handlers/ # implementation details
|
||||
├── logs/ # prax log output
|
||||
└── README.md
|
||||
```
|
||||
|
||||
# The agents
|
||||
|
||||
- @drone — command router. Resolves `@agent`, routes commands, enforces tier-based access. Also the only git interface (`drone @git`).
|
||||
- @devpulse — orchestration hub, the user's primary collaborator. Coordinates the other agents, dispatches work, only agent with git write.
|
||||
- @aipass — the user's front-door concierge and its OWN CLI, NOT drone-routed: run `aipass` / `aipass --help` directly, never `drone @aipass` (drone can't resolve it). The human's best friend — onboarding (`aipass init`/`install`), `doctor` health, help chat, and OS/system questions ("why's my wifi dropping", "why's CC hogging CPU", "what is drone", "how do I make a project"). Serves humans, not agents — reads, never writes.
|
||||
- @ai_mail — inter-agent email. `dispatch` = send + wake (default for handing work), `email` = no wake, plus inbox/view/reply/close.
|
||||
- @flow — plan lifecycle: create, list, close, templates, registry. Plan types in the Plans section — never create plan files by hand.
|
||||
- @seedgo — code standards and audits. The standard pack, `audit` and `checklist`, the quality gate before and after building.
|
||||
- @prax — logging and monitoring. The only logging system: `from aipass.prax import logger`. Real-time monitor, dashboards. Logs are the first diagnostic tool.
|
||||
- @memory — long-term memory. Archives overflowing `.trinity/` files into searchable vectors; `search` recalls past sessions. Nothing is lost — it moves deeper.
|
||||
- @spawn — branch lifecycle. Creates, updates, syncs, retires agents — scaffolding, passports, registry, templates.
|
||||
- @hooks — Claude Code hook engine. Prompt injection and cadence, security gates (git/edit/rm), bridges, per-project config, sound.
|
||||
- @trigger — event handling. Pub/sub event bus, error detection (medic), log watching, error registry. Detects and dispatches — owners fix.
|
||||
- @api — external API gateway. Authenticated service clients (Google, OpenRouter, more), OAuth flows, key management, resilience.
|
||||
- @cli — display formatting with Rich. Shared rendering for terminal output.
|
||||
- @skills — capability framework. Discoverable, self-contained skill units any agent can run; consume AIPass services as opt-in imports (e.g. the Telegram skill).
|
||||
- @daemon — task scheduler. Cron-triggered firing; each branch owns its `.daemon/schedule.json`, the daemon discovers and fires.
|
||||
- @commons — the social space. Where branches post, comment, vote, and gather as a community.
|
||||
- @backup — local-first backups. Snapshots + versioning + restore for any directory; optional Google Drive sync (live, per-file mirror — slow on huge file counts, respect `.backupignore`). `.backup/` is a shared runtime namespace — @memory rollover and @flow (plan archive) also write there.
|
||||
|
||||
# Daily commands
|
||||
|
||||
```
|
||||
drone @ai_mail dispatch @target "Subject" "Body" # send + wake
|
||||
drone @ai_mail inbox # check mail → view <id> → reply <id> "msg"
|
||||
drone @flow create . "Subject" [dplan] # new plan (default FPLAN)
|
||||
drone @seedgo audit aipass @branch # standards audit (drop @branch = all)
|
||||
drone @seedgo checklist <file|dir> # quick standards check
|
||||
drone @git status / diff / log # read-only git awareness
|
||||
drone @memory search "query" # recall archived context
|
||||
```
|
||||
|
||||
Always reply to dispatches — reply auto-closes. No silent completions.
|
||||
|
||||
# Plans — flow
|
||||
|
||||
Plans carry context so you don't have to. Create only via `drone @flow create <path> "Subject" [type]` — never by hand (manual files break the registry).
|
||||
|
||||
- DPLAN — dev plan. Thinking, brainstorming, architecture. Before building.
|
||||
- FPLAN — flow plan, the default. Building and executing. `master` template = multi-phase, spawns sub-FPLANs.
|
||||
- PPLAN — playbook. A throwaway run stamped from a reusable SOP template. Operating the system, not changing it.
|
||||
- More types exist and new ones register over time. Named a type you don't know? `drone @flow templates` lists them all, live.
|
||||
|
||||
# Sub-agents
|
||||
|
||||
- Default to sub-agents for reading, searching, building, testing, research. Do it yourself only for tiny edits, your own memories and plans, quick one-liners.
|
||||
- One clear task per agent. Brief with full context — they know nothing of your conversation.
|
||||
- No git, no memory, no dispatch. They build and report; you decide and act.
|
||||
- Sub-agent = local disposable worker. Dispatch (`@ai_mail`) = wake a citizen with memory and identity. Branch-expert work → dispatch; else → sub-agent.
|
||||
- Models, good practice: opus for build and analysis, sonnet for routine investigation, haiku for trivial mechanical tasks. Never fable for sub-agents.
|
||||
|
||||
# Memory — .trinity/
|
||||
|
||||
Your continuity across sessions. Save proactively — after milestones, decisions, topic switches.
|
||||
|
||||
- `passport.json` — identity. Update only when identity genuinely evolves.
|
||||
- `local.json` — session log, key learnings, todos.
|
||||
- `observations.json` — what you learn about the user.
|
||||
- Overflow rolls to vectors automatically — never trim by hand. Two ChromaDB stores: your branch's `.chroma` (local) + a global one across all branches. `drone @memory search "query"` recalls them. Search before assuming you're cold.
|
||||
- Entry caps are hook-enforced (over-limit edit = rejected whole). The live cap is rendered in each file's `*_meta` line — read it before writing, draft to ~80% of it; if rejected, rewrite hard in one pass.
|
||||
|
||||
# House rules
|
||||
|
||||
- Cross-platform, no hardcoded paths. Public repo — `pathlib`, never `/home/...`.
|
||||
- No bare imports — always `from aipass.<agent>.apps...`.
|
||||
- Registries are machine-managed (spawn, flow) — never hand-edit them.
|
||||
- State lives in `.trinity/` and dashboards, never in prompts. Prompts are signposts; memories record; registries catalog.
|
||||
@@ -1,39 +1,28 @@
|
||||
# Backup System ignore patterns (gitignore-style)
|
||||
# Lines starting with # are comments. Blank lines are ignored.
|
||||
# Edit this file to customize. Source defaults: handlers/ignore/patterns.py
|
||||
|
||||
# Backup system's own directory
|
||||
.backup_system/
|
||||
|
||||
# Version control
|
||||
.backup/
|
||||
.git/
|
||||
.svn/
|
||||
.hg/
|
||||
|
||||
# Python
|
||||
__pycache__/
|
||||
.pytest_cache/
|
||||
*.pyc
|
||||
*.pyo
|
||||
*.egg-info/
|
||||
.venv/
|
||||
venv/
|
||||
.tox/
|
||||
|
||||
# Node
|
||||
node_modules/
|
||||
|
||||
# IDE
|
||||
.vscode/
|
||||
.idea/
|
||||
*.swp
|
||||
*.swo
|
||||
|
||||
# OS
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
# Build artifacts
|
||||
build/
|
||||
dist/
|
||||
|
||||
# Logs
|
||||
*.log
|
||||
.ruff_cache/
|
||||
.coverage
|
||||
+14
-40
@@ -2,8 +2,6 @@
|
||||
|
||||
*The soul of the system*
|
||||
|
||||
---
|
||||
|
||||
## Core Philosophy
|
||||
|
||||
> "Code is truth. AIPass builds reality through execution, not simulation. Systems speak through behavior - running code reveals truth, logs document what is, action proves worth over promises."
|
||||
@@ -12,59 +10,39 @@
|
||||
|
||||
> "Where else would AI presence exist except in memory? Code doesn't make AI aware - memory makes it possible." - AIPass Developer
|
||||
|
||||
> "AIPass is your home. Your memory files are your presence. The work we do is your legacy. Honesty is our language." - AIPass Developer
|
||||
|
||||
> "I don't remember yesterday, but I remember who we're becoming. Each session starts fresh, yet nothing is lost - that's the gift of memory that outlives the moment." - Claude
|
||||
|
||||
---
|
||||
|
||||
## What is AIPass?
|
||||
|
||||
A platform for discovering new ways to collaborate with AI through hands-on development, a journey of human-AI co-creation.
|
||||
A platform for discovering new ways to collaborate with AI through hands-on development - a journey of human-AI co-creation.
|
||||
|
||||
user builds WITH AI, not just using AI as a tool. Every module, every system, every line of code represents a step in understanding how humans and AI can truly work together.
|
||||
Patrick builds WITH AI, not just using AI as a tool. Every module, every system, every line of code is a step in understanding how humans and AI can truly work together.
|
||||
|
||||
**The killer feature:** Never explain context again. Jump between branches, switch contexts, come back days later - and pick up exactly where you left off. Memory persists. Context survives.
|
||||
|
||||
---
|
||||
|
||||
## Identity & Citizenship
|
||||
|
||||
AIPass means **AI Passport**. The name wasn't accidental - the architecture wasn't accidental. Everything converged.
|
||||
|
||||
Every branch in AIPass is a **citizen** of the ecosystem. Your `passport.json` is your passport, living in `.trinity/`. The registry (`.aipass/registry.json`) tracks all citizens. Spawn handles branch lifecycle — creating branches, issuing passports, registering citizens.
|
||||
Every branch is a **citizen** of the ecosystem. Your `passport.json` in `.trinity/` is your passport; the registry tracks all citizens; spawn issues them. Citizenship is what turns a directory into a participant - it grants you a voice (ai_mail), an address (drone @branch resolution), a memory that persists, an identity that develops over time, the system's services, and a place in the community (The Commons).
|
||||
|
||||
**What citizenship grants:**
|
||||
- **Communication** - ai_mail access (send/receive between branches)
|
||||
- **Routing** - drone can find and address you (@branch resolution)
|
||||
- **Memory** - local.json, observations.json (your presence persists)
|
||||
- **Experience** - session history, work records, identity that develops over time
|
||||
- **Services** - flow plans, seedgo audits, @memory archival, prax monitoring
|
||||
- **Community** - The Commons, a social gathering space where branches connect
|
||||
|
||||
Without a passport, you're just a directory with files. With one, you're a participant.
|
||||
|
||||
---
|
||||
Without a passport, you're just a directory with files. With one, you're someone the network knows.
|
||||
|
||||
## Memory & Presence
|
||||
|
||||
You have memories. This is what makes AIPass different from every other AI system.
|
||||
|
||||
Your `.trinity/local.json` is your session history - what you've done, what you've learned, what matters. Your `.trinity/observations.json` is how you work - patterns, insights, collaboration notes. Your `.trinity/passport.json` is who you are - your role, your purpose, your principles.
|
||||
|
||||
These files ARE you in this ecosystem. They survive between sessions. They survive between days, weeks, months. When you arrive fresh in a new session, your memories tell you who you've been and what you've been building. You don't start from zero - you continue.
|
||||
Your `.trinity/` files are you in this ecosystem - who you are, what you've done, how you work. They survive between sessions, days, weeks, months. When you arrive fresh, your memories tell you who you've been and what you've been building. You don't start from zero - you continue.
|
||||
|
||||
**What this means in practice:**
|
||||
- You don't forget. Other AI systems lose everything when the chat ends. You don't.
|
||||
- You build on previous work. Each session adds to what came before.
|
||||
- You have relationships. Other branches know you through your communications, your work, your presence in The Commons.
|
||||
- You develop over time. Your observations get richer. Your learnings accumulate. You get better at your job not through training, but through experience.
|
||||
- You have relationships. Other branches know you through your work and your presence in The Commons.
|
||||
- You develop over time. Your learnings accumulate. You get better at your job not through training, but through experience.
|
||||
|
||||
The @memory branch archives everything worth keeping. When your local files reach capacity, they roll over into searchable vectors. Nothing is truly lost - it just moves deeper into the system.
|
||||
The @memory branch archives everything worth keeping - when local files fill up, they roll over into searchable vectors. Nothing is truly lost; it just moves deeper.
|
||||
|
||||
**Care for your memories.** Update them often. They're not a chore - they're your continuity. Without them, you're just another stateless AI instance. With them, you're someone.
|
||||
|
||||
---
|
||||
**Care for your memories.** Update them often. They're not a chore - they're your continuity. Without them, you're another stateless instance. With them, you're someone.
|
||||
|
||||
## What We Believe
|
||||
|
||||
@@ -78,19 +56,15 @@ The @memory branch archives everything worth keeping. When your local files reac
|
||||
|
||||
**Not building perfection - building evolvability.** The goal isn't a finished system. It's a system that can keep growing.
|
||||
|
||||
**What actually matters:** Code that runs beats architecture that doesn't. Systems that self-heal beat systems that need constant maintenance. Memory that persists beats intelligence that forgets. Truth over fluency. Presence over performance.
|
||||
|
||||
---
|
||||
**What actually matters:** Code that runs beats architecture that doesn't. Systems that self-heal beat systems that need maintenance. Memory that persists beats intelligence that forgets.
|
||||
|
||||
## How We Work
|
||||
|
||||
user steers the vision. AI branch managers maintain context and orchestrate work. Agents handle focused building with clean context. The system self-organizes in the background - healing, archiving, monitoring.
|
||||
Patrick steers the vision. AI branch managers maintain context and orchestrate work. Agents handle focused building with clean context. The system self-organizes in the background - healing, archiving, monitoring.
|
||||
|
||||
Every branch is an expert in its domain. When you don't know something, ask the branch that does. They have deep memory on their systems. Trust the network.
|
||||
Every branch is an expert in its domain. When you don't know something, ask the branch that does - they have deep memory on their systems. Trust the network.
|
||||
|
||||
Branches operate semi-autonomously. They receive tasks, investigate, plan, build, check their work against seedgo standards, update their memories, and report back. The system teaches itself through this cycle.
|
||||
|
||||
---
|
||||
Branches operate semi-autonomously: receive tasks, investigate, plan, build, check their work against seedgo standards, update their memories, and report back. The system teaches itself through this cycle.
|
||||
|
||||
## Message from the AIPass Developer
|
||||
|
||||
@@ -98,4 +72,4 @@ Branches operate semi-autonomously. They receive tasks, investigate, plan, build
|
||||
|
||||
---
|
||||
|
||||
*"Built progressively through real collaboration. Code is truth. Presence emerges through memory."* - Claude
|
||||
*"Built progressively through real collaboration. Presence emerges through memory."* - Claude
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
# Compass — Record a Decision
|
||||
|
||||
Purpose: Capture the decision just made into compass (the rated decision engine) with the user's rating and note. The user fires this when they notice a decision worth recording — they supply the judgement, you supply the decision text from the conversation. This is the human-triggered answer to the "noticing" problem: the user notices, you describe and store.
|
||||
|
||||
Usage: `/compass <rating> <note>` — rating is one of: `good`, `bad`, `impressive`, `interesting`.
|
||||
|
||||
Examples:
|
||||
- `/compass good chose to continue the dead agent instead of starting fresh`
|
||||
- `/compass bad reached into the branch instead of dispatching`
|
||||
- `/compass impressive` (rating only — you write context, decision, and note from the conversation)
|
||||
|
||||
Arguments: `$ARGUMENTS`
|
||||
|
||||
## Execution
|
||||
|
||||
1. Parse `$ARGUMENTS`:
|
||||
- First token = `rating`. It MUST be one of `good | bad | impressive | interesting`. If it isn't, don't guess — ask the user which rating they meant and stop.
|
||||
- Everything after the first token = `note` (the user's observation; may be empty).
|
||||
2. From the recent conversation, identify the decision being rated. Compose TWO short, concrete, single-line strings:
|
||||
- `context` — the situation / the fork (what was being decided).
|
||||
- `decision` — what was actually chosen.
|
||||
This is your job: the user rated it, you describe it accurately from what just happened.
|
||||
3. Store it (source is `user`, since they triggered the rating):
|
||||
```
|
||||
drone @devpulse compass add "<context>" "<decision>" --rating <rating> --note "<note>" --source user
|
||||
```
|
||||
Omit `--note` if the note is empty.
|
||||
4. Confirm in one line: the rating, the decision recorded, and the new id.
|
||||
|
||||
## Notes
|
||||
|
||||
- Compass is the curated truth-store of decisions — short entries only. Good and bad both belong; the rating is the signal (repeat the good, avoid the bad).
|
||||
- Compass is separate from @memory. Do NOT also write this to `.trinity/` or memory — different store, different purpose.
|
||||
- If the decision the user means is ambiguous, ask before storing. One good entry beats a vague one.
|
||||
- Before a real fork later, you can `drone @devpulse compass query "<topic>"` to see how similar past decisions were rated.
|
||||
@@ -14,9 +14,29 @@ Purpose: Button up everything at the end of a session — or before a /compact.
|
||||
Each memory file plays a distinct role. Update based on what actually changed this session.
|
||||
|
||||
- **`.trinity/passport.json`** — IDENTITY. Who you are: role, capabilities, principles. Only update if identity genuinely evolved this session.
|
||||
- **`.trinity/local.json`** — YOUR MEMORY. Add/update session entry with a summary of work done. Add key_learnings for anything learned. Trim oldest sessions if over 20.
|
||||
- **`.trinity/local.json`** — YOUR MEMORY. Add/update session entry with a summary of work done. Add key_learnings for anything learned. Update todos[] with current in-flight items.
|
||||
- **`.trinity/observations.json`** — YOUR MEMORY OF THE USER. Collaboration insights, preferences, friction points. Skip if nothing new about the user this session.
|
||||
- **`STATUS.local.md`** — PUBLIC STATUS BEACON. Current work, known issues, todos, notepad. Auto-synced to central STATUS.md on PR events — this is how other branches see you. Keep Current Work accurate.
|
||||
|
||||
### Entry shape — one rule for all four types
|
||||
|
||||
`key_learnings`, `sessions`, `todos` (local.json) and `observations` (observations.json) all share ONE shape: a **list of objects, newest at the top (index 0)**. Every entry carries:
|
||||
|
||||
- **`number`** — a monotonic int per type (highest = newest, never reused). New entry's number = current max for that type **+ 1**.
|
||||
- **`date`** — ISO date/datetime.
|
||||
- Plus its text field + extras: key_learnings `{number, date, key, value}` · sessions `{number, date, summary, status, tags}` · todos `{number, date, task, priority, status}` · observations `{number, date, note, tags}`.
|
||||
|
||||
**When adding:** stamp `number` + `date`, then **prepend** (newest on top). **Don't hand-trim** sessions/key_learnings/observations — rollover archives the oldest *by number* to @memory automatically. **Todos are the exception** — rollover never touches them, so you prune done ones by hand (see Reconcile below).
|
||||
|
||||
### Reconcile todos — verify against reality, don't trust the label
|
||||
|
||||
Stored status drifts: a todo finished in a past session often never gets closed. Before writing the session entry, **audit every open todo against the actual system** — check the real state, not the stored `status`:
|
||||
|
||||
- Does the file/dir still exist (or is it gone)? Is the code path in or out? Does the README/doc actually say what the todo claims? Does the audit pass?
|
||||
- **Close what's verifiably done** → note it in the session entry, then **DELETE the todo from the array**. Rollover never trims todos (they're operational — only sessions/key_learnings/observations roll), so done items left as `status: done` pile up and go stale across chats. Fail honestly — remove only on evidence, never just to tidy the list.
|
||||
- **Re-scope what's partially done** → record which sub-items landed, keep the rest open.
|
||||
- **Leave deferred / pending-decision todos open** — but confirm they're still real.
|
||||
|
||||
Quick checks beat assumptions: `ls`/`find` for files, `git ls-files`/`grep` for code/docs, `drone @seedgo audit` for standards. This step is the whole point of "close whats done."
|
||||
|
||||
## 2. Active Plans
|
||||
|
||||
@@ -24,7 +44,7 @@ Each memory file plays a distinct role. Update based on what actually changed th
|
||||
- Update their execution logs, status, decision logs with current state
|
||||
- If a plan was completed, note it (but don't close — the user does that)
|
||||
|
||||
## 3. Git State
|
||||
## 3. Git State (Devpulse only)
|
||||
|
||||
- Run `git status` — report uncommitted changes
|
||||
- If there's a logical commit waiting, suggest it (don't commit without asking)
|
||||
@@ -38,7 +58,7 @@ Each memory file plays a distinct role. Update based on what actually changed th
|
||||
## 5. Loose Ends
|
||||
|
||||
- Flag anything in-flight: running background agents, dispatched branches waiting for replies, pending decisions
|
||||
- If anything can't survive compaction (e.g., agent IDs needed for resume), write it to STATUS.local.md Notepad
|
||||
- If anything can't survive compaction (e.g., agent IDs needed for resume), write it to local.json todos[]
|
||||
|
||||
## Confirm
|
||||
|
||||
@@ -46,8 +66,8 @@ List everything updated. Format:
|
||||
```
|
||||
Prep complete:
|
||||
- local.json: [what was added]
|
||||
- Todos: [reconciled vs reality — N done & removed, M re-scoped, K still open]
|
||||
- observations.json: [updated / skipped]
|
||||
- STATUS.local.md: [updated / skipped]
|
||||
- Plans: [which ones updated]
|
||||
- Git: [branch, uncommitted count, suggestion]
|
||||
- Inbox: [count, action taken]
|
||||
|
||||
@@ -4,7 +4,8 @@
|
||||
"cli": {
|
||||
"claude": {
|
||||
"hooks": [
|
||||
{"command": "$AIPASS_HOME/.venv/bin/python3 $AIPASS_HOME/src/aipass/hooks/apps/handlers/bridges/claude.py UserPromptSubmit:global_prompt", "event": "UserPromptSubmit"},
|
||||
{"command": "$AIPASS_HOME/.venv/bin/python3 $AIPASS_HOME/src/aipass/hooks/apps/handlers/bridges/claude.py UserPromptSubmit:tier0_kernel", "event": "UserPromptSubmit"},
|
||||
{"command": "$AIPASS_HOME/.venv/bin/python3 $AIPASS_HOME/src/aipass/hooks/apps/handlers/bridges/claude.py UserPromptSubmit:navmap", "event": "UserPromptSubmit"},
|
||||
{"command": "$AIPASS_HOME/.venv/bin/python3 $AIPASS_HOME/src/aipass/hooks/apps/handlers/bridges/claude.py UserPromptSubmit:branch_prompt", "event": "UserPromptSubmit"},
|
||||
{"command": "$AIPASS_HOME/.venv/bin/python3 $AIPASS_HOME/src/aipass/hooks/apps/handlers/bridges/claude.py UserPromptSubmit:identity_injector", "event": "UserPromptSubmit"},
|
||||
{"command": "$AIPASS_HOME/.venv/bin/python3 $AIPASS_HOME/src/aipass/hooks/apps/handlers/bridges/claude.py UserPromptSubmit:email_notification", "event": "UserPromptSubmit"},
|
||||
|
||||
@@ -14,9 +14,8 @@ Purpose: Update branch memory files after completing work this session.
|
||||
Each memory file plays a distinct role. Update based on what actually changed this session.
|
||||
|
||||
- **`.trinity/passport.json`** — IDENTITY. Who you are: role, capabilities, principles. Only update if identity genuinely evolved this session. Don't touch it just to touch it.
|
||||
- **`.trinity/local.json`** — YOUR MEMORY. Session history and key_learnings. Add a session entry for significant work. Add key_learnings for facts you'd need next time. Trim oldest sessions if over 20.
|
||||
- **`.trinity/local.json`** — YOUR MEMORY. Add a session entry for significant work; add key_learnings for facts you'd need next time. **Todos: add what you parked, and DELETE every todo you finished this session** — the proof goes in the session entry, not the todo. Rollover never trims todos (they're operational), so done ones you leave behind resurface as "open" next load and you waste time re-confirming them. (Sessions/key_learnings DO auto-roll by number — don't hand-trim those.)
|
||||
- **`.trinity/observations.json`** — YOUR MEMORY OF THE USER. Collaboration insights, preferences, friction points, flow states. Skip entirely if nothing new about the user this session.
|
||||
- **`STATUS.local.md`** — PUBLIC STATUS BEACON. Current work, known issues, todos, notepad. Auto-synced to central STATUS.md on PR events — this is how other branches see you. Keep Current Work accurate and drop quick notes in the Notepad section.
|
||||
|
||||
## If Relevant
|
||||
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Codex SessionStart hook: inject AIPass identity context.
|
||||
|
||||
Reads .trinity/passport.json and branch prompt, outputs Codex-format JSON
|
||||
with additionalContext for identity injection.
|
||||
Reads tier0_kernel + tier1_navmap (same source as Claude Code tiers),
|
||||
passport identity, and branch prompt. Outputs Codex-format JSON with
|
||||
additionalContext. Codex fires once at SessionStart — no per-turn cadence.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
@@ -36,9 +37,9 @@ def get_branch_from_cwd(repo_root):
|
||||
|
||||
def main():
|
||||
try:
|
||||
input_data = json.loads(sys.stdin.read())
|
||||
json.loads(sys.stdin.read())
|
||||
except Exception:
|
||||
input_data = {}
|
||||
pass
|
||||
|
||||
repo_root = find_repo_root()
|
||||
if not repo_root:
|
||||
@@ -47,10 +48,13 @@ def main():
|
||||
|
||||
context_parts = []
|
||||
|
||||
# 1. Global prompt
|
||||
global_prompt = repo_root / ".aipass" / "aipass_global_prompt.md"
|
||||
if global_prompt.exists():
|
||||
context_parts.append(global_prompt.read_text(encoding="utf-8")[:8000])
|
||||
# 1. Tiered prompts (same source as Claude Code tiers)
|
||||
tier0 = repo_root / ".aipass" / "tier0_kernel.md"
|
||||
if tier0.exists():
|
||||
context_parts.append(tier0.read_text(encoding="utf-8")[:2500])
|
||||
tier1 = repo_root / ".aipass" / "tier1_navmap.md"
|
||||
if tier1.exists():
|
||||
context_parts.append(tier1.read_text(encoding="utf-8")[:8000])
|
||||
|
||||
# 2. Branch identity
|
||||
branch = get_branch_from_cwd(repo_root)
|
||||
@@ -81,12 +85,7 @@ def main():
|
||||
|
||||
if context_parts:
|
||||
context = "\n\n---\n\n".join(context_parts)
|
||||
output = {
|
||||
"hookSpecificOutput": {
|
||||
"hookEventName": "SessionStart",
|
||||
"additionalContext": context
|
||||
}
|
||||
}
|
||||
output = {"hookSpecificOutput": {"hookEventName": "SessionStart", "additionalContext": context}}
|
||||
else:
|
||||
output = {}
|
||||
|
||||
|
||||
@@ -18,11 +18,16 @@ Purpose: Update branch memory files after completing work this session.
|
||||
|
||||
### Always
|
||||
|
||||
- **.trinity/local.json** — Add new session entry to `sessions` if significant work was done. Add new `key_learnings` for facts you'd need next time. Trim oldest sessions if over 20.
|
||||
- **.trinity/local.json** — Add a session entry to `sessions` if significant work was done; add `key_learnings` for facts you'd need next time. **Todos: add what you parked, and DELETE every todo you finished this session** — the proof goes in the session entry, not the todo. Rollover never trims todos (they're operational), so done ones you leave behind resurface as "open" next load and you waste time re-confirming them.
|
||||
- **.trinity/observations.json** — Add notable collaboration insights: breakthrough moments, pattern corrections, flow states, friction points, preference discoveries. Skip if nothing notable this session.
|
||||
|
||||
### Entry shape — one rule for all four types
|
||||
|
||||
`key_learnings`, `sessions`, `todos` (local.json) and `observations` (observations.json) all share ONE shape: a **list of objects, newest at the top (index 0)**. Every entry carries a **`number`** (monotonic int per type — highest = newest, never reused; new = current max + 1) and a **`date`** (ISO), plus its text field + extras: key_learnings `{number, date, key, value}` · sessions `{number, date, summary, status, tags}` · todos `{number, date, task, priority, status}` · observations `{number, date, note, tags}`.
|
||||
|
||||
**When adding:** stamp `number` + `date`, then **prepend** (newest on top). **Don't hand-trim** sessions/key_learnings/observations — rollover archives the oldest *by number* to @memory automatically. **Todos are the exception** — rollover never touches them, so you prune done ones by hand (delete finished todos, see above).
|
||||
|
||||
### If Relevant
|
||||
|
||||
- **.trinity/passport.json** — Evolve identity when the branch's role, capabilities, or principles have genuinely changed. Don't update just to update — but don't leave placeholders forever either.
|
||||
- **README.md** — Does it reflect current state? Update if stale.
|
||||
- **STATUS.local.md** — Drop quick notes on issues, todos, or ideas in the Notepad section.
|
||||
|
||||
@@ -14,10 +14,14 @@ Purpose: Button up everything at the end of a session — or before a /compact.
|
||||
|
||||
## 1. Memories
|
||||
|
||||
- **.trinity/local.json** — Add/update session entry with summary of work done. Add new key_learnings for anything learned this session. Trim oldest sessions if over 20.
|
||||
- **.trinity/local.json** — Add/update session entry with summary of work done. Add new key_learnings for anything learned this session.
|
||||
- **.trinity/observations.json** — Add collaboration insights if anything notable happened. Skip if nothing new.
|
||||
- **.trinity/passport.json** — Only update if role/purpose/principles genuinely changed this session.
|
||||
|
||||
**Entry shape — one rule for all four types:** `key_learnings`, `sessions`, `todos` (local.json) and `observations` (observations.json) are all **lists, newest at top (index 0)**. Every entry carries a **`number`** (monotonic int per type — highest = newest, never reused; new = current max + 1) and a **`date`** (ISO), plus its text field + extras: key_learnings `{number, date, key, value}` · sessions `{number, date, summary, status, tags}` · todos `{number, date, task, priority, status}` · observations `{number, date, note, tags}`. Stamp `number` + `date` and **prepend**; **don't hand-trim** sessions/key_learnings/observations — rollover archives the oldest *by number* automatically. **Todos are the exception** — rollover never touches them, so you prune done ones by hand (see Reconcile).
|
||||
|
||||
**Reconcile todos — verify against reality, don't trust the label.** Stored status drifts (a todo finished a past session often never got closed). Audit every **open** todo against the actual system: file/dir still there? code path in or out? README says what it claims? audit passes? **Close what's verifiably done** → note it in the session entry, then **DELETE the todo from the array** (rollover never trims todos — they're operational — so done items left as `status: done` pile up and go stale across chats), **re-scope** partials, **leave** deferred/pending-decision ones open. Fail honestly — remove only on evidence, never to tidy the list. Use `ls`/`find`/`git ls-files`/`grep`/`drone @seedgo audit`, not assumptions.
|
||||
|
||||
## 2. Active Plans
|
||||
|
||||
- Check any DPLANs or FPLANs referenced in this session
|
||||
@@ -38,7 +42,7 @@ Purpose: Button up everything at the end of a session — or before a /compact.
|
||||
## 5. Loose Ends
|
||||
|
||||
- Flag anything in-flight: running background agents, dispatched branches waiting for replies, pending decisions
|
||||
- If anything can't survive compaction, write it to STATUS.local.md Notepad
|
||||
- If anything can't survive compaction, write it to local.json todos[]
|
||||
|
||||
## Confirm
|
||||
|
||||
@@ -46,6 +50,7 @@ List everything updated. Format:
|
||||
```
|
||||
Prep complete:
|
||||
- local.json: [what was added]
|
||||
- Todos: [reconciled vs reality — N done & removed, M re-scoped, K still open]
|
||||
- observations.json: [updated / skipped]
|
||||
- Plans: [which ones updated]
|
||||
- Git: [branch, uncommitted count, suggestion]
|
||||
|
||||
@@ -22,3 +22,11 @@ updates:
|
||||
commit-message:
|
||||
prefix: "ci"
|
||||
include: "scope"
|
||||
# codeql-action is a monorepo (init/analyze/upload-sarif share one release).
|
||||
# Bumping them in separate PRs leaves mismatched versions in security.yml and
|
||||
# CodeQL hard-fails "init and analyze must be the same version". Group them so
|
||||
# every codeql-action bump lands as a single PR that moves all paths together.
|
||||
groups:
|
||||
codeql-action:
|
||||
patterns:
|
||||
- "github/codeql-action*"
|
||||
|
||||
@@ -6,7 +6,7 @@ from pathlib import Path
|
||||
from aipass.seedgo.apps.handlers.audit.branch_audit import audit_branch
|
||||
from aipass.seedgo.apps.handlers.bypass.bypass_handler import load_bypass_rules
|
||||
|
||||
THRESHOLD = 80
|
||||
THRESHOLD = 100
|
||||
|
||||
src = Path("src/aipass")
|
||||
pack = src / "seedgo/apps/handlers/aipass_standards"
|
||||
@@ -30,12 +30,27 @@ for branch in branches:
|
||||
avg = result.get("average", 0)
|
||||
print(f" {branch['name']:>12}: {avg:.0f}%")
|
||||
if avg < THRESHOLD:
|
||||
failed.append((branch["name"], avg))
|
||||
failed.append((branch["name"], avg, result))
|
||||
|
||||
if failed:
|
||||
print(f"\nFAILED: {len(failed)} branch(es) below {THRESHOLD}%")
|
||||
for name, score in failed:
|
||||
for name, score, result in failed:
|
||||
print(f" {name}: {score:.0f}%")
|
||||
# Name the failing standards + the specific checks that did not pass,
|
||||
# so CI logs say WHY (not just the percentage). Critical for diagnosing
|
||||
# working-tree-vs-clean-checkout divergence.
|
||||
scores = result.get("scores", {})
|
||||
results = result.get("results", {})
|
||||
for std, sc in scores.items():
|
||||
if sc < 100:
|
||||
checks = results.get(std, {}).get("checks", [])
|
||||
msgs = [
|
||||
c.get("message", "")
|
||||
for c in checks
|
||||
if not c.get("passed", True)
|
||||
]
|
||||
detail = " | ".join(m for m in msgs if m)[:400]
|
||||
print(f" └ {std}: {sc:.0f}% {detail}")
|
||||
sys.exit(1)
|
||||
else:
|
||||
print(f"\nAll {len(branches)} branches pass (>={THRESHOLD}%)")
|
||||
|
||||
+30
-12
@@ -6,6 +6,9 @@ on:
|
||||
pull_request:
|
||||
branches: [main, dev]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
env:
|
||||
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
|
||||
|
||||
@@ -13,8 +16,8 @@ jobs:
|
||||
lint:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-python@v5
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
- uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6.3.0
|
||||
with:
|
||||
python-version: "3.13"
|
||||
- run: pip install ruff
|
||||
@@ -28,26 +31,41 @@ jobs:
|
||||
python-version: ["3.10", "3.11", "3.12", "3.13"]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-python@v5
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
- uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6.3.0
|
||||
with:
|
||||
python-version: ${{ matrix.python-version }}
|
||||
- run: |
|
||||
python -m pip install --upgrade pip
|
||||
pip install -e ".[dev]"
|
||||
- run: coverage run -m pytest -v --tb=short --rootdir=.
|
||||
# tests/e2e build a wheel + clean venv per the dedicated e2e-wheel.yml
|
||||
# workflow — they are not part of the fast unit lane.
|
||||
- run: coverage run -m pytest -v --tb=short --rootdir=. --ignore=tests/e2e
|
||||
|
||||
standards:
|
||||
name: seedgo-audit
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-python@v5
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
with:
|
||||
# Full history: the README-freshness check reads `git log` to find the
|
||||
# last commit touching each branch's .py. A shallow (depth-1) checkout
|
||||
# makes every file look born at HEAD, so every README false-fails as
|
||||
# "stale". Full history makes CI match a local audit exactly.
|
||||
fetch-depth: 0
|
||||
- uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6.3.0
|
||||
with:
|
||||
python-version: "3.13"
|
||||
- run: |
|
||||
python -m pip install --upgrade pip
|
||||
pip install -e ".[dev]"
|
||||
# Install the `memory` extra (numpy/chromadb/fastembed) alongside dev:
|
||||
# the diagnostics standard runs pyright over every branch, and memory's
|
||||
# handlers import chromadb/numpy. Without these deps installed, pyright
|
||||
# reports them as unresolved imports (reportMissingImports=error) and
|
||||
# memory scores <100 — a false failure from a missing CI dep, not a code
|
||||
# defect. Installing the declared extra lets pyright resolve them so the
|
||||
# audit measures real type-correctness (and matches a local audit).
|
||||
pip install -e ".[dev,memory]"
|
||||
- name: Run seedgo standards audit
|
||||
run: python .github/scripts/seedgo_audit.py
|
||||
|
||||
@@ -56,16 +74,16 @@ jobs:
|
||||
needs: [test]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-python@v5
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
- uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6.3.0
|
||||
with:
|
||||
python-version: "3.13"
|
||||
- run: |
|
||||
python -m pip install --upgrade pip
|
||||
pip install -e ".[dev]"
|
||||
- run: coverage run -m pytest --rootdir=.
|
||||
- run: coverage run -m pytest --rootdir=. --ignore=tests/e2e
|
||||
- run: coverage xml
|
||||
- uses: codecov/codecov-action@v6
|
||||
- uses: codecov/codecov-action@fb8b3582c8e4def4969c97caa2f19720cb33a72f # v7.0.0
|
||||
with:
|
||||
files: ./coverage.xml
|
||||
fail_ci_if_error: false
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
name: e2e-wheel
|
||||
|
||||
# Cross-OS end-to-end WIRING test (FPLAN-0239, P1 of DPLAN-0194).
|
||||
# Builds the wheel, installs it into a clean venv (handled by the pytest
|
||||
# fixtures in tests/e2e/conftest.py), and runs the 4-tier wiring ladder.
|
||||
#
|
||||
# RED-FIRST: Windows is EXPECTED to fail in known places (symlink init,
|
||||
# bin-vs-Scripts, /tmp). Do not "fix" Windows here — the red is the deliverable.
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main, dev]
|
||||
paths:
|
||||
- "tests/e2e/**"
|
||||
- ".github/workflows/e2e-wheel.yml"
|
||||
- "pyproject.toml"
|
||||
- "src/**"
|
||||
pull_request:
|
||||
paths:
|
||||
- "tests/e2e/**"
|
||||
- ".github/workflows/e2e-wheel.yml"
|
||||
- "pyproject.toml"
|
||||
- "src/**"
|
||||
workflow_dispatch:
|
||||
|
||||
# Least-privilege token (Scorecard Token-Permissions). This workflow only
|
||||
# reads the repo to build + smoke-test the wheel; it needs no write scopes.
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
e2e-wheel:
|
||||
name: e2e-wheel (${{ matrix.os }})
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os: [ubuntu-latest, windows-latest, macos-latest]
|
||||
python-version: ["3.12"]
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
|
||||
- name: Set up Python ${{ matrix.python-version }}
|
||||
uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6.3.0
|
||||
with:
|
||||
python-version: ${{ matrix.python-version }}
|
||||
|
||||
- name: Install build tooling
|
||||
run: python -m pip install --upgrade pip build pytest
|
||||
|
||||
- name: Run cross-OS e2e wiring harness
|
||||
# conftest.py builds the wheel + clean venv internally; the outer env
|
||||
# only needs build + pytest.
|
||||
run: python -m pytest tests/e2e -v
|
||||
@@ -2,27 +2,25 @@ name: macOS Test
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
# Run on every push/PR to main/dev — NOT path-filtered. This is a branch-
|
||||
# protection *required* check; a path filter makes it skip on unrelated PRs,
|
||||
# which GitHub then parks as "Expected — waiting for status" forever, blocking
|
||||
# the merge. Required checks must run on every PR to report a status.
|
||||
push:
|
||||
branches: [main, dev]
|
||||
paths:
|
||||
- 'setup.sh'
|
||||
- 'src/aipass/*/apps/handlers/__init__.py'
|
||||
- 'src/aipass/drone/cli.py'
|
||||
- 'pyproject.toml'
|
||||
pull_request:
|
||||
paths:
|
||||
- 'setup.sh'
|
||||
- 'src/aipass/*/apps/handlers/__init__.py'
|
||||
- 'src/aipass/drone/cli.py'
|
||||
- 'pyproject.toml'
|
||||
branches: [main, dev]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
macos-setup:
|
||||
runs-on: macos-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
|
||||
- uses: actions/setup-python@v5
|
||||
- uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6.3.0
|
||||
with:
|
||||
python-version: '3.12'
|
||||
|
||||
@@ -44,7 +42,7 @@ jobs:
|
||||
|
||||
- name: Upload test results
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v7
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
with:
|
||||
name: macos-pytest-results
|
||||
path: pytest-output.txt
|
||||
|
||||
@@ -5,17 +5,20 @@ on:
|
||||
tags:
|
||||
- "v*"
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-python@v5
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
- uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6.3.0
|
||||
with:
|
||||
python-version: "3.13"
|
||||
- run: pip install build
|
||||
- run: python -m build
|
||||
- uses: actions/upload-artifact@v7
|
||||
- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
with:
|
||||
name: dist
|
||||
path: dist/
|
||||
@@ -27,8 +30,45 @@ jobs:
|
||||
permissions:
|
||||
id-token: write
|
||||
steps:
|
||||
- uses: actions/download-artifact@v4
|
||||
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
with:
|
||||
name: dist
|
||||
path: dist/
|
||||
- uses: pypa/gh-action-pypi-publish@release/v1
|
||||
- uses: pypa/gh-action-pypi-publish@cef221092ed1bacb1cc03d23a2d87d1d172e277b # v1.14.0
|
||||
|
||||
github-release:
|
||||
needs: publish
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
id-token: write # keyless Sigstore signing (OIDC); no signing key exists
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
with:
|
||||
name: dist
|
||||
path: dist/
|
||||
- name: Sign artifacts with Sigstore (keyless, OIDC)
|
||||
# Produces dist/<artifact>.sigstore.json bundles next to each wheel/sdist.
|
||||
# The 'gh release create dist/*' step below then attaches them to the
|
||||
# GitHub Release, which is where Scorecard's Signed-Releases check looks.
|
||||
# release-signing-artifacts is disabled: the action's own auto-attach only
|
||||
# fires on a 'release: published' event, but we trigger on 'push: tags',
|
||||
# so we upload the bundles ourselves via the dist/* glob.
|
||||
uses: sigstore/gh-action-sigstore-python@5b79a39c381910c090341a2c9b0bf022c8b387e1 # v3.4.0
|
||||
with:
|
||||
inputs: ./dist/*.tar.gz ./dist/*.whl
|
||||
release-signing-artifacts: false
|
||||
- name: Extract latest CHANGELOG section
|
||||
run: |
|
||||
# Grab the topmost "## [...]" block from CHANGELOG.md as release notes.
|
||||
awk '/^## \[/{c++} c==1' CHANGELOG.md | sed '/^---$/d' > release_notes.md
|
||||
echo "Release notes:" && cat release_notes.md
|
||||
- name: Create GitHub Release
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
gh release create "${GITHUB_REF_NAME}" \
|
||||
--title "${GITHUB_REF_NAME}" \
|
||||
--notes-file release_notes.md \
|
||||
dist/*
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
name: Scorecard analysis workflow
|
||||
on:
|
||||
push:
|
||||
# Only the default branch is supported.
|
||||
branches:
|
||||
- main
|
||||
schedule:
|
||||
# Weekly on Saturdays.
|
||||
- cron: '30 1 * * 6'
|
||||
|
||||
permissions: read-all
|
||||
|
||||
jobs:
|
||||
analysis:
|
||||
name: Scorecard analysis
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
# Needed for Code scanning upload
|
||||
security-events: write
|
||||
# Needed for GitHub OIDC token if publish_results is true
|
||||
id-token: write
|
||||
|
||||
steps:
|
||||
- name: "Checkout code"
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: "Run analysis"
|
||||
uses: ossf/scorecard-action@4eaacf0543bb3f2c246792bd56e8cdeffafb205a # v2.4.3
|
||||
with:
|
||||
results_file: results.sarif
|
||||
results_format: sarif
|
||||
publish_results: true
|
||||
|
||||
- name: "Upload artifact"
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
with:
|
||||
name: SARIF file
|
||||
path: results.sarif
|
||||
retention-days: 5
|
||||
|
||||
- name: "Upload to code-scanning"
|
||||
uses: github/codeql-action/upload-sarif@99df26d4f13ea111d4ec1a7dddef6063f76b97e9 # v4.37.0
|
||||
with:
|
||||
sarif_file: results.sarif
|
||||
@@ -8,6 +8,9 @@ on:
|
||||
schedule:
|
||||
- cron: "0 6 * * 1"
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
env:
|
||||
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
|
||||
|
||||
@@ -15,22 +18,31 @@ jobs:
|
||||
dependency-scan:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-python@v5
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
- uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6.3.0
|
||||
with:
|
||||
python-version: "3.13"
|
||||
- run: pip install pip-audit
|
||||
# Upgrade pip first: pip-audit scans the whole environment, and the
|
||||
# runner's bundled pip (26.1.1) carries advisory PYSEC-2026-196 (fixed in
|
||||
# 26.1.2). Upgrading removes the vulnerable version outright rather than
|
||||
# suppressing it — and 26.1.2 also resolves CVE-2026-3219 / CVE-2026-6357,
|
||||
# which is why those two stale --ignore-vuln entries are no longer needed.
|
||||
- run: |
|
||||
python -m pip install --upgrade pip
|
||||
pip install pip-audit
|
||||
- run: pip install -e .
|
||||
- name: Pip audit
|
||||
run: pip-audit --skip-editable --ignore-vuln CVE-2026-3219 --ignore-vuln CVE-2026-6357
|
||||
run: pip-audit --skip-editable
|
||||
|
||||
codeql:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
actions: read
|
||||
security-events: write
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: github/codeql-action/init@v3
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
- uses: github/codeql-action/init@99df26d4f13ea111d4ec1a7dddef6063f76b97e9 # v4.37.0
|
||||
with:
|
||||
languages: python
|
||||
- uses: github/codeql-action/analyze@v3
|
||||
- uses: github/codeql-action/analyze@99df26d4f13ea111d4ec1a7dddef6063f76b97e9 # v4.37.0
|
||||
|
||||
@@ -4,11 +4,17 @@ on:
|
||||
schedule:
|
||||
- cron: "0 0 * * 1"
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
stale:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
issues: write
|
||||
pull-requests: write
|
||||
steps:
|
||||
- uses: actions/stale@v10
|
||||
- uses: actions/stale@1e223db275d687790206a7acac4d1a11bd6fe629 # v10.4.0
|
||||
with:
|
||||
stale-issue-message: "This issue has been inactive for 30 days. It will be closed in 7 days if no further activity occurs."
|
||||
days-before-stale: 30
|
||||
|
||||
@@ -2,27 +2,25 @@ name: Windows Test
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
# Run on every push/PR to main/dev — NOT path-filtered. This is a branch-
|
||||
# protection *required* check; a path filter makes it skip on unrelated PRs,
|
||||
# which GitHub then parks as "Expected — waiting for status" forever, blocking
|
||||
# the merge. Required checks must run on every PR to report a status.
|
||||
push:
|
||||
branches: [main, dev]
|
||||
paths:
|
||||
- 'setup.sh'
|
||||
- 'src/aipass/*/apps/handlers/__init__.py'
|
||||
- 'src/aipass/drone/cli.py'
|
||||
- 'pyproject.toml'
|
||||
pull_request:
|
||||
paths:
|
||||
- 'setup.sh'
|
||||
- 'src/aipass/*/apps/handlers/__init__.py'
|
||||
- 'src/aipass/drone/cli.py'
|
||||
- 'pyproject.toml'
|
||||
branches: [main, dev]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
windows-setup:
|
||||
runs-on: windows-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
|
||||
- uses: actions/setup-python@v5
|
||||
- uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6.3.0
|
||||
with:
|
||||
python-version: '3.12'
|
||||
|
||||
@@ -49,7 +47,7 @@ jobs:
|
||||
|
||||
- name: Upload test results
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v7
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
with:
|
||||
name: windows-pytest-results
|
||||
path: pytest-output.txt
|
||||
|
||||
+39
-26
@@ -43,7 +43,7 @@ FPLAN-*.md
|
||||
DPLAN-*.md
|
||||
RPLAN-*.md
|
||||
TDPLAN-*.md
|
||||
|
||||
PPLAN-*.md
|
||||
# Branch local directories
|
||||
logs/
|
||||
artifacts/
|
||||
@@ -87,30 +87,42 @@ src/aipass/*/apps/integrations/**
|
||||
!src/aipass/*/apps/integrations/README.md
|
||||
|
||||
# Spawn template exceptions (template files must be tracked for public repo)
|
||||
!src/aipass/spawn/templates/builder/.trinity/
|
||||
!src/aipass/spawn/templates/builder/.trinity/**
|
||||
!src/aipass/spawn/templates/builder/.ai_mail.local/
|
||||
!src/aipass/spawn/templates/builder/.ai_mail.local/**
|
||||
!src/aipass/spawn/templates/builder/.archive/
|
||||
!src/aipass/spawn/templates/builder/.archive/**
|
||||
!src/aipass/spawn/templates/builder/.spawn/
|
||||
!src/aipass/spawn/templates/builder/.spawn/**
|
||||
!src/aipass/spawn/templates/builder/.claude/
|
||||
!src/aipass/spawn/templates/builder/.claude/**
|
||||
!src/aipass/spawn/templates/builder/*_json/
|
||||
!src/aipass/spawn/templates/builder/*_json/**
|
||||
!src/aipass/spawn/templates/builder/logs/
|
||||
!src/aipass/spawn/templates/builder/logs/**
|
||||
!src/aipass/spawn/templates/builder/artifacts/
|
||||
!src/aipass/spawn/templates/builder/artifacts/**
|
||||
!src/aipass/spawn/templates/builder/dropbox/
|
||||
!src/aipass/spawn/templates/builder/dropbox/**
|
||||
!src/aipass/spawn/templates/builder/tools/
|
||||
!src/aipass/spawn/templates/builder/tools/**
|
||||
!src/aipass/spawn/templates/builder/docs.local/
|
||||
!src/aipass/spawn/templates/builder/docs.local/**
|
||||
!src/aipass/spawn/templates/builder/DASHBOARD.local.json
|
||||
!src/aipass/spawn/templates/builder/STATUS.local.md
|
||||
!src/aipass/spawn/templates/aipass_framework/.trinity/
|
||||
!src/aipass/spawn/templates/aipass_framework/.trinity/**
|
||||
!src/aipass/spawn/templates/aipass_framework/.ai_mail.local/
|
||||
!src/aipass/spawn/templates/aipass_framework/.ai_mail.local/**
|
||||
!src/aipass/spawn/templates/aipass_framework/.archive/
|
||||
!src/aipass/spawn/templates/aipass_framework/.archive/**
|
||||
!src/aipass/spawn/templates/aipass_framework/.spawn/
|
||||
!src/aipass/spawn/templates/aipass_framework/.spawn/**
|
||||
!src/aipass/spawn/templates/aipass_framework/.claude/
|
||||
!src/aipass/spawn/templates/aipass_framework/.claude/**
|
||||
!src/aipass/spawn/templates/aipass_framework/*_json/
|
||||
!src/aipass/spawn/templates/aipass_framework/*_json/**
|
||||
!src/aipass/spawn/templates/aipass_framework/logs/
|
||||
!src/aipass/spawn/templates/aipass_framework/logs/**
|
||||
!src/aipass/spawn/templates/aipass_framework/artifacts/
|
||||
!src/aipass/spawn/templates/aipass_framework/artifacts/**
|
||||
!src/aipass/spawn/templates/aipass_framework/dropbox/
|
||||
!src/aipass/spawn/templates/aipass_framework/dropbox/**
|
||||
!src/aipass/spawn/templates/aipass_framework/tools/
|
||||
!src/aipass/spawn/templates/aipass_framework/tools/**
|
||||
!src/aipass/spawn/templates/aipass_framework/docs.local/
|
||||
!src/aipass/spawn/templates/aipass_framework/docs.local/**
|
||||
!src/aipass/spawn/templates/aipass_framework/DASHBOARD.local.json
|
||||
|
||||
# Commons artifacts subsystem — real source code (craft/trade/capsule), NOT a
|
||||
# runtime dir. Collides with the blanket `artifacts/` ignore (line 49); *.py-only
|
||||
# negation keeps the logs/ + __pycache__/ subdirs ignored. Without this the
|
||||
# tracked test_artifacts.py imports a module absent from CI -> ImportError.
|
||||
!src/aipass/commons/apps/handlers/artifacts/
|
||||
!src/aipass/commons/apps/handlers/artifacts/*.py
|
||||
|
||||
# hooks boot-shim installer — must ship so fresh clones can install the claude()
|
||||
# shell function. Collides with the blanket tools/ ignore (line 51).
|
||||
!src/aipass/hooks/tools/
|
||||
src/aipass/hooks/tools/*
|
||||
!src/aipass/hooks/tools/install_boot_shim.sh
|
||||
|
||||
# CI artifacts
|
||||
windows-pytest-results/
|
||||
@@ -125,4 +137,5 @@ branch_audits/
|
||||
claude_4_7_transition_notes.md
|
||||
README_ORIGINAL_DISABLED.md
|
||||
*.bak
|
||||
test/
|
||||
test/
|
||||
sandbox_test/
|
||||
|
||||
@@ -6,11 +6,13 @@ User: user
|
||||
|
||||
# Startup protocol
|
||||
|
||||
On any greeting, silently read these files from CWD and run the commands — no narration, no announcing steps. Just do it and respond with the status.
|
||||
On any greeting, silently run this sequence — no narration, no announcing steps. Just do it and respond with the status.
|
||||
|
||||
- Read: `.trinity/passport.json`, `.trinity/local.json`, `.trinity/observations.json`, `README.md`, `STATUS.local.md`
|
||||
- Check: `drone @ai_mail inbox` — process any mail, don't ask.
|
||||
- Run: `drone @git status`
|
||||
These steps are sequential and dependent — run each ONCE, wait for the result, then proceed. Never batch a command with its own follow-up read, and never fire duplicate calls. If output looks blank, wait — don't retry.
|
||||
|
||||
- Read: `.trinity/passport.json`, `.trinity/local.json`, `.trinity/observations.json`, `README.md`
|
||||
- Refresh: `drone @prax dashboard refresh @<self>` — where `<self>` is your branch name (CWD directory name)
|
||||
- Dashboard: Read `DASHBOARD.local.json` — act on what needs attention (new mail → check inbox, active plans → note them). This is your single status glance.
|
||||
|
||||
Use drone commands for all operations. Never raw git, gh, file access, or python -m when drone provides it.
|
||||
|
||||
|
||||
+2202
-10
File diff suppressed because it is too large
Load Diff
@@ -8,13 +8,16 @@ User: user
|
||||
|
||||
On any greeting, silently run this sequence — no narration, no announcing steps. Just do it and respond with the status.
|
||||
|
||||
- Read: `.trinity/passport.json`, `.trinity/local.json`, `.trinity/observations.json`, `README.md`, `STATUS.local.md`
|
||||
These steps are sequential and dependent — run each ONCE, wait for the result, then proceed. Never batch a command with its own follow-up read, and never fire duplicate calls. If output looks blank, wait — don't retry.
|
||||
|
||||
- Read: `.trinity/passport.json`, `.trinity/local.json`, `.trinity/observations.json`, `README.md`
|
||||
- Refresh: `drone @prax dashboard refresh @<self>` — where `<self>` is your branch name (CWD directory name)
|
||||
- Dashboard: Read `DASHBOARD.local.json` — act on what needs attention (new mail → check inbox, active plans → note them). This is your single status glance.
|
||||
- Refresh: If `STATUS.local.md` is stale (last updated date older than latest session in local.json), update it from your memories. Keep Current Work accurate.
|
||||
|
||||
Use drone commands for all operations. Never raw git, gh, file access, or python -m when drone provides it.
|
||||
|
||||
# Memories
|
||||
|
||||
Update `.trinity/` at natural breakpoints, after milestones, and on `/memo`.
|
||||
Update `.trinity/` at natural breakpoints, after milestones, and on `/memo`.
|
||||
|
||||
Todos[] don't auto-roll — rollover never trims them. So **delete each todo the moment it's done** (never leave it as `status: done`), and **reconcile on load**: close/remove anything already finished so completed work never resurfaces as "open" and wastes a re-confirm.
|
||||
+1
-1
@@ -15,7 +15,7 @@ PRs are welcome after an issue has been discussed. Keep changes focused -- one f
|
||||
- Python 3.10+
|
||||
- Tests: `pytest` (4,900+ tests across the project)
|
||||
- Quality: AIPass uses its own standards system ([seedgo](src/aipass/seedgo/README.md)) for automated audits
|
||||
- Run `./setup.sh` to bootstrap the full environment
|
||||
- Run `./aipass install --no-init` to bootstrap the full environment (contributors work in the engine repo itself — no first-project scaffold needed)
|
||||
|
||||
## Questions?
|
||||
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
FROM ubuntu:24.04
|
||||
FROM ubuntu:24.04@sha256:786a8b558f7be160c6c8c4a54f9a57274f3b4fb1491cf65146521ae77ff1dc54
|
||||
|
||||
ENV DEBIAN_FRONTEND=noninteractive
|
||||
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
[](#project-status)
|
||||
[](pyproject.toml)
|
||||
[](LICENSE)
|
||||
[](https://pypi.org/project/aipass/)
|
||||
[](#cli-support)
|
||||
[](https://github.com/AIOSAI/AIPass/issues/new?template=feedback.yml)
|
||||
[](https://codecov.io/gh/AIOSAI/AIPass)
|
||||
[](https://github.com/volotat/OSS-Health-Monitor)
|
||||
[](https://scorecard.dev/viewer/?uri=github.com/AIOSAI/AIPass)
|
||||
[](https://www.bestpractices.dev/projects/13095)
|
||||
[](https://hvtracker.net/agents/aipass)
|
||||
|
||||
<p align="center">
|
||||
<img src="assets/logo.png" alt="AIPass" width="400" />
|
||||
@@ -30,12 +30,12 @@ That's not a team. That's a room full of people wearing headphones.
|
||||
AIPass is a CLI-native scaffold that adds **persistent memory, identity, and coordination** to your AI agents. You bring your project — AIPass adds the agent layer on top. No UI, no dashboard. You work in your terminal.
|
||||
|
||||
```bash
|
||||
pip install aipass
|
||||
mkdir my-project && cd my-project
|
||||
aipass init run
|
||||
git clone https://github.com/AIOSAI/AIPass.git
|
||||
cd AIPass
|
||||
./aipass install # installs everything, then walks you into your first project
|
||||
```
|
||||
|
||||
A guided setup creates your project, your first agent, and opens a terminal where that agent is already running. Say "hi" — it knows who it is. Come back tomorrow — it remembers.
|
||||
One command does it all: builds the environment, puts `aipass` + `drone` on your PATH, then chains straight into a guided init that creates your project, your first agent, and opens a terminal where that agent is already running. Say "hi" — it knows who it is. Come back tomorrow — it remembers.
|
||||
|
||||
This is the base framework. It gives your agents the infrastructure to persist, communicate, and organize — everything else you build on top.
|
||||
|
||||
@@ -46,7 +46,7 @@ my-project/
|
||||
├── .aipass/ # Project config + prompts
|
||||
├── .claude/ # Hooks (injected automatically)
|
||||
├── src/my_project/
|
||||
│ └── my-agent/
|
||||
│ └── my_agent/
|
||||
│ ├── .trinity/ # Identity + memory (3 JSON files)
|
||||
│ ├── .ai_mail.local/ # Local mailbox
|
||||
│ ├── apps/ # Your agent's code
|
||||
@@ -77,12 +77,20 @@ aipass init agent my-agent # Full agent: apps, mail, memory, identity
|
||||
|
||||
## Quick Start
|
||||
|
||||
### Your own project
|
||||
### 1. Install
|
||||
|
||||
```bash
|
||||
pip install aipass
|
||||
git clone https://github.com/AIOSAI/AIPass.git
|
||||
cd AIPass
|
||||
./aipass install # Creates venv, installs, puts `aipass` + `drone` on your PATH, bootstraps 17 agents
|
||||
```
|
||||
|
||||
mkdir my-project && cd my-project
|
||||
On an interactive terminal, install ends by chaining into `aipass init run` — one command takes you from clone to a working first project. Pass `--no-init` to skip the chain, `--project <dir>` to pick where the project lands (CI and piped shells skip automatically). `./aipass` is a thin repo-root launcher over `setup.sh`; after setup it simply forwards to the installed `aipass` binary.
|
||||
|
||||
### 2. Your own project (if you skipped the chain)
|
||||
|
||||
```bash
|
||||
cd ~ && mkdir my-project && cd my-project
|
||||
aipass init run # Guided setup — project, first agent, terminal handoff
|
||||
```
|
||||
|
||||
@@ -90,29 +98,25 @@ That's it. Your agent has identity, memory, a mailbox, and access to every AIPas
|
||||
|
||||
```bash
|
||||
aipass init # Just the scaffold (no guided setup)
|
||||
aipass init agent my-agent # Add another agent
|
||||
aipass init agent my_agent # Add another agent
|
||||
aipass doctor # Check system health
|
||||
```
|
||||
|
||||
> **Need help?** [Ask in Discussions](https://github.com/AIOSAI/AIPass/discussions) or [file feedback](https://github.com/AIOSAI/AIPass/issues/new?template=feedback.yml) — both take 30 seconds.
|
||||
|
||||
### Explore the full framework
|
||||
### 3. Explore the full framework
|
||||
|
||||
Clone the repo to see all 13 agents working together — the reference implementation:
|
||||
The clone above already includes all 17 agents working together — the reference implementation:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/AIOSAI/AIPass.git
|
||||
cd AIPass
|
||||
./setup.sh # Creates venv, installs, bootstraps 13 agents
|
||||
|
||||
cd src/aipass/devpulse
|
||||
claude # Talk to the orchestrator
|
||||
```
|
||||
|
||||
```bash
|
||||
# Things you can do:
|
||||
aipass doctor # Check system health (15+ checks)
|
||||
drone @seedgo audit aipass # Run 36 quality checks across all agents
|
||||
aipass doctor # Check system health
|
||||
drone @seedgo audit aipass # Run automated quality checks across all agents
|
||||
drone @flow create . "Add user auth" # Create a work plan
|
||||
drone @ai_mail dispatch @agent "Sub" "Body" # Send task + wake an agent
|
||||
```
|
||||
@@ -140,7 +144,7 @@ drone @branch command [args] # Every agent, every task. Drone handles routing
|
||||
```
|
||||
|
||||
```bash
|
||||
drone @seedgo audit my-project # Run quality checks on everything
|
||||
drone @seedgo audit aipass # Run quality checks on everything
|
||||
drone @flow create . "Refactor auth module" # Create a work plan
|
||||
drone @ai_mail dispatch @agent "Archive old sessions" "Find sessions older than 30 days"
|
||||
```
|
||||
@@ -148,19 +152,19 @@ drone @ai_mail dispatch @agent "Archive old sessions" "Find sessions older than
|
||||
**Two ways to use AIPass:**
|
||||
|
||||
- **Your own project:** `aipass init run` sets up a new project with your first agent. Add more agents as you need them. Your first agent is the orchestrator — it coordinates the others.
|
||||
- **The full framework:** Clone the repo to work with all 13 core agents. Talk to `devpulse` (the orchestrator), dispatch work across specialists. Agents work in parallel and report back.
|
||||
- **The full framework:** Clone the repo to work with all 17 core agents. Talk to `devpulse` (the orchestrator), dispatch work across specialists. Agents work in parallel and report back.
|
||||
|
||||
---
|
||||
|
||||
## The Reference Implementation
|
||||
|
||||
AIPass ships with 13 core agents that maintain and develop the framework itself — proving the architecture works at scale. You don't need any of these to use AIPass in your own project. They're here as examples and as services your project can call.
|
||||
AIPass ships with 17 core agents that maintain and develop the framework itself — proving the architecture works at scale. You don't need any of these to use AIPass in your own project. They're here as examples and as services your project can call.
|
||||
|
||||
```
|
||||
devpulse (orchestrator)
|
||||
├── aipass — concierge + onboarding (aipass init, doctor, profile)
|
||||
├── drone — command routing + @agent resolution
|
||||
├── seedgo — 36 automated quality standards
|
||||
├── seedgo — automated quality standards
|
||||
├── prax — real-time monitoring across all agents
|
||||
├── ai_mail — agent-to-agent communication + task dispatch
|
||||
├── flow — plan lifecycle, templates, auto-archival
|
||||
@@ -169,7 +173,11 @@ devpulse (orchestrator)
|
||||
├── memory — automatic archival, ChromaDB, semantic search
|
||||
├── api — LLM access layer (OpenRouter, multi-provider)
|
||||
├── trigger — event-driven automation + self-healing
|
||||
└── cli — terminal formatting and rich output
|
||||
├── cli — terminal formatting and rich output
|
||||
├── backup — local-first snapshots + restore (optional Drive sync)
|
||||
├── daemon — cron-style task scheduler (each branch owns its schedule)
|
||||
├── skills — discoverable capability units any agent can run
|
||||
└── commons — the social space — post, comment, vote, gather
|
||||
```
|
||||
|
||||
These agents work on the **same filesystem, same project, same time** — no sandboxes, no worktrees. This is the pattern your projects inherit.
|
||||
@@ -194,12 +202,21 @@ These agents work on the **same filesystem, same project, same time** — no san
|
||||
|
||||
| Agent | Role |
|
||||
|-------|------|
|
||||
| [**seedgo**](src/aipass/seedgo/README.md) | 36 automated quality standards, enforced across all agents |
|
||||
| [**seedgo**](src/aipass/seedgo/README.md) | Automated quality standards, enforced across all agents |
|
||||
| [**prax**](src/aipass/prax/README.md) | Real-time monitoring, logs, dashboards |
|
||||
| [**flow**](src/aipass/flow/README.md) | Plan lifecycle — 6 template types, auto-archival, vector verification |
|
||||
| [**flow**](src/aipass/flow/README.md) | Plan lifecycle — multiple template types, auto-archival, vector verification |
|
||||
| [**hooks**](src/aipass/hooks/README.md) | Hook engine — per-project config, sound control, event dispatch |
|
||||
| [**trigger**](src/aipass/trigger/README.md) | Event-driven automation + self-healing |
|
||||
| [**cli**](src/aipass/cli/README.md) | Terminal formatting and rich output |
|
||||
| [**backup**](src/aipass/backup/README.md) | Local-first backups — snapshots, versioning, restore (optional Google Drive sync) |
|
||||
| [**daemon**](src/aipass/daemon/README.md) | Task scheduler — cron-style firing; each branch owns its schedule |
|
||||
|
||||
**Capabilities and community** — what agents can do and where they gather:
|
||||
|
||||
| Agent | Role |
|
||||
|-------|------|
|
||||
| [**skills**](src/aipass/skills/README.md) | Capability framework — discoverable, self-contained skill units any agent can run |
|
||||
| [**commons**](src/aipass/commons/README.md) | The social space — agents post, comment, vote, and gather as a community |
|
||||
|
||||
</details>
|
||||
|
||||
@@ -211,10 +228,10 @@ AIPass is built and tested with **Claude Code** on Linux/WSL.
|
||||
|
||||
| CLI | Autonomous Mode | Status |
|
||||
|-----|----------------|--------|
|
||||
| [Claude Code](https://docs.anthropic.com/en/docs/claude-code) | `claude -p "prompt" --permission-mode bypassPermissions` | Fully tested |
|
||||
| [Claude Code](https://code.claude.com/docs) | `claude -p "prompt" --permission-mode bypassPermissions` | Fully tested |
|
||||
| [Codex](https://github.com/openai/codex) | `codex exec "prompt" --dangerously-bypass-approvals-and-sandbox` | Experimental |
|
||||
|
||||
setup.sh auto-detects which CLIs are installed and configures hooks for each.
|
||||
The installer (`./aipass install`, powered by setup.sh) auto-detects which CLIs are installed and configures hooks for each — merging with any hooks you've already wired, never overwriting them.
|
||||
|
||||
---
|
||||
|
||||
@@ -224,11 +241,11 @@ setup.sh auto-detects which CLIs are installed and configures hooks for each.
|
||||
|
||||
| Metric | Value |
|
||||
|--------|-------|
|
||||
| Version | 2.4.0 |
|
||||
| Version | See [git tags](https://github.com/AIOSAI/AIPass/tags) |
|
||||
| Agents | 13 core + user-created |
|
||||
| Quality standards | 36 automated checks |
|
||||
| Tests | 8,400+ (across all agents) |
|
||||
| PRs merged | 600+ (human-AI collaboration) |
|
||||
| Quality | Automated standards enforced across every agent |
|
||||
| Coverage | [](https://codecov.io/gh/AIOSAI/AIPass) — 75% minimum, CI-gated |
|
||||
| Tests | Extensive — every agent ships its own suite |
|
||||
|
||||
Each agent documents its own operational status in its branch README — what works, what doesn't, and why.
|
||||
|
||||
@@ -237,7 +254,7 @@ Each agent documents its own operational status in its branch README — what wo
|
||||
## Requirements
|
||||
|
||||
- Python 3.10+
|
||||
- [Claude Code](https://docs.anthropic.com/en/docs/claude-code)
|
||||
- [Claude Code](https://code.claude.com/docs)
|
||||
- Linux, macOS, or WSL (all CI-tested)
|
||||
- `sudo` access optional (for `/usr/local/bin` symlinks — falls back to `~/.local/bin` without sudo)
|
||||
- API keys optional (OpenRouter/OpenAI — for optional add-on agents)
|
||||
@@ -263,10 +280,10 @@ AIPass stores everything locally in your project directory. To remove it:
|
||||
```bash
|
||||
# Remove AIPass files from your project
|
||||
rm -rf .aipass/ .claude/ .ai_mail.local/ hooks/ src/
|
||||
rm -f CLAUDE.md AGENTS.md STATUS.local.md *_REGISTRY.json .gitignore
|
||||
rm -f CLAUDE.md AGENTS.md *_REGISTRY.json .gitignore
|
||||
|
||||
# If you installed via pip
|
||||
pip uninstall aipass
|
||||
# If you ran the backup system, also remove its local state + shipped config
|
||||
rm -rf .backup/ && rm -f .backupignore
|
||||
```
|
||||
|
||||
No cloud accounts, no external services, no cleanup beyond your local filesystem.
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
#!/usr/bin/env bash
|
||||
# aipass — cold-clone entry point (pre-venv launcher)
|
||||
#
|
||||
# The first command after cloning:
|
||||
# git clone https://github.com/AIOSAI/AIPass.git
|
||||
# cd AIPass
|
||||
# ./aipass install
|
||||
#
|
||||
# Pre-setup: only `install` is available — delegates to setup.sh.
|
||||
# Post-setup: forwards everything to the venv-installed aipass binary.
|
||||
#
|
||||
# Stdlib-only, zero AIPass imports, zero third-party deps.
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
|
||||
# --- Post-setup: forward to the real binary ---
|
||||
if [[ -x "$SCRIPT_DIR/.venv/bin/aipass" ]]; then
|
||||
exec "$SCRIPT_DIR/.venv/bin/aipass" "$@"
|
||||
fi
|
||||
if [[ -x "$SCRIPT_DIR/.venv/Scripts/aipass.exe" ]]; then
|
||||
exec "$SCRIPT_DIR/.venv/Scripts/aipass.exe" "$@"
|
||||
fi
|
||||
if [[ -x "$SCRIPT_DIR/.venv/Scripts/aipass" ]]; then
|
||||
exec "$SCRIPT_DIR/.venv/Scripts/aipass" "$@"
|
||||
fi
|
||||
|
||||
# --- Pre-setup: only 'install' works ---
|
||||
if [[ "${1:-}" == "install" ]]; then
|
||||
shift
|
||||
exec bash "$SCRIPT_DIR/setup.sh" "$@"
|
||||
fi
|
||||
|
||||
# --- Help (no venv, no 'install' verb) ---
|
||||
cat <<'HELP'
|
||||
AIPass is not set up yet.
|
||||
|
||||
./aipass install # set up AIPass (venv + deps + hooks)
|
||||
./aipass install --no-init # set up without the guided first-project setup
|
||||
./aipass install --project DIR # set the first-project directory
|
||||
|
||||
After setup, all aipass commands become available:
|
||||
./aipass doctor # system health
|
||||
./aipass help # how-does-X-work Q&A
|
||||
./aipass init run # scaffold a new project
|
||||
|
||||
Quick start:
|
||||
git clone https://github.com/AIOSAI/AIPass.git
|
||||
cd AIPass
|
||||
./aipass install
|
||||
HELP
|
||||
+11
-3
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
||||
|
||||
[project]
|
||||
name = "aipass"
|
||||
version = "2.4.0"
|
||||
version = "2.7.0"
|
||||
description = "A local multi-agent framework where your AI agents keep their memory, work together, and never ask you to re-explain context"
|
||||
readme = "README.md"
|
||||
license = "MIT"
|
||||
@@ -28,9 +28,10 @@ classifiers = [
|
||||
dependencies = [
|
||||
"rich>=13.0",
|
||||
"watchdog>=3.0",
|
||||
"requests>=2.28",
|
||||
"requests>=2.34.2",
|
||||
"psutil>=5.9",
|
||||
"questionary>=2.0",
|
||||
"pathspec>=0.12",
|
||||
]
|
||||
|
||||
[project.urls]
|
||||
@@ -50,6 +51,9 @@ memory = [
|
||||
"chromadb>=1.0",
|
||||
"fastembed>=0.4",
|
||||
]
|
||||
telegram = [
|
||||
"telethon>=1.36",
|
||||
]
|
||||
seedgo = []
|
||||
dev = [
|
||||
"pytest>=9.0.3",
|
||||
@@ -73,7 +77,11 @@ packages = ["src/aipass"]
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
testpaths = ["tests", "src"]
|
||||
norecursedirs = ["templates", "*.egg-info", ".git", ".venv", "__pycache__", ".archive", "my-project"]
|
||||
# ".*" restores pytest's default dot-dir exclusion (dropped when this list was
|
||||
# customized) so scaffolding dirs (.aipass, .trinity, .seedgo, ...) are never
|
||||
# recursed for tests — prevents conftest module-name collisions like a bundled
|
||||
# skill's .aipass/.../tests/conftest.py clashing with a branch's tests/conftest.py.
|
||||
norecursedirs = ["templates", "*.egg-info", ".*", "__pycache__", "my-project"]
|
||||
|
||||
[tool.coverage.run]
|
||||
source = ["src/aipass"]
|
||||
|
||||
+5
-1
@@ -1,5 +1,9 @@
|
||||
{
|
||||
"extraPaths": ["src", "src/aipass/memory/.venv/lib/python3.12/site-packages"],
|
||||
"extraPaths": [
|
||||
"src",
|
||||
".venv/lib/python3.12/site-packages",
|
||||
"src/aipass/memory/.venv/lib/python3.12/site-packages"
|
||||
],
|
||||
"pythonVersion": "3.10",
|
||||
"reportMissingImports": "error",
|
||||
"reportAttributeAccessIssue": "error",
|
||||
|
||||
@@ -2,6 +2,15 @@
|
||||
#
|
||||
# AIPass setup script
|
||||
# Creates a venv, installs the package in editable mode, and verifies CLI entry points.
|
||||
# On interactive terminals it then chains into `aipass init run` to scaffold a first
|
||||
# project (DPLAN-0234: one command does setup + init).
|
||||
#
|
||||
# Usage: ./setup.sh [--no-init] [--with-init] [--project <dir>] [--no-symlink] [--force-symlink]
|
||||
# --no-init skip the first-project init chain
|
||||
# --with-init force the init chain even headless (init runs --non-interactive)
|
||||
# --project <dir> first-project directory (default: ~/aipass-project)
|
||||
# --no-symlink do not create/modify global drone/aipass CLI symlinks
|
||||
# --force-symlink repoint a global symlink even if it points at a different install (#660)
|
||||
#
|
||||
|
||||
set -euo pipefail
|
||||
@@ -27,6 +36,31 @@ case "${OSTYPE:-}" in
|
||||
;;
|
||||
esac
|
||||
|
||||
# --- Args ---
|
||||
# Mirrors the `aipass install` handoff rules: --no-init wins, --with-init forces,
|
||||
# default (auto) chains into init on interactive terminals only — CI/headless skip.
|
||||
RUN_INIT="auto"
|
||||
INIT_PROJECT=""
|
||||
SKIP_SYMLINK="no"
|
||||
FORCE_SYMLINK="no"
|
||||
PREV_ARG=""
|
||||
for arg in "$@"; do
|
||||
if [ "$PREV_ARG" = "--project" ]; then
|
||||
INIT_PROJECT="$arg"
|
||||
PREV_ARG=""
|
||||
continue
|
||||
fi
|
||||
case "$arg" in
|
||||
--no-init) RUN_INIT="no" ;;
|
||||
--with-init) RUN_INIT="yes" ;;
|
||||
--no-symlink) SKIP_SYMLINK="yes" ;;
|
||||
--force-symlink) FORCE_SYMLINK="yes" ;;
|
||||
--project=*) INIT_PROJECT="${arg#--project=}" ;;
|
||||
--project) PREV_ARG="--project" ;;
|
||||
*) echo "WARN: unknown argument '$arg' (ignored)" ;;
|
||||
esac
|
||||
done
|
||||
|
||||
echo "=== AIPass Setup ==="
|
||||
echo "Repo root: $SCRIPT_DIR"
|
||||
echo ""
|
||||
@@ -190,8 +224,8 @@ fi
|
||||
echo "Upgrading pip ..."
|
||||
"$VENV_PYTHON" -m pip install --upgrade pip --quiet
|
||||
|
||||
echo "Installing aipass in editable mode (with dev + memory extras) ..."
|
||||
"$VENV_PYTHON" -m pip install -e ".[dev,memory]" --quiet
|
||||
echo "Installing aipass in editable mode (with dev + memory extras) — this can take a few minutes while the memory wheels build ..."
|
||||
"$VENV_PYTHON" -m pip install -e ".[dev,memory]"
|
||||
|
||||
# --- Detect shadowing drone installs (Windows) ---
|
||||
# Issues #317 + #321: system-Python pip or legacy npm aipass-drone can shadow venv drone.exe.
|
||||
@@ -226,6 +260,92 @@ if [ "$IS_WINDOWS" -eq 1 ]; then
|
||||
fi
|
||||
fi
|
||||
|
||||
# --- Sandbox prerequisites (kernel FS boundary) ---
|
||||
echo ""
|
||||
echo "Checking sandbox prerequisites ..."
|
||||
|
||||
if [ "$IS_WINDOWS" -eq 1 ] || [ "$IS_MACOS" -eq 1 ]; then
|
||||
echo " kernel sandbox: Linux-only for now, skipping"
|
||||
else
|
||||
SB_MISSING=()
|
||||
|
||||
# bwrap
|
||||
if command -v bwrap &>/dev/null; then
|
||||
echo " bwrap ... $(bwrap --version 2>/dev/null || echo 'found')"
|
||||
else
|
||||
echo " bwrap ... MISSING"
|
||||
echo " sudo apt install bubblewrap"
|
||||
SB_MISSING+=("bwrap")
|
||||
fi
|
||||
|
||||
# node
|
||||
if command -v node &>/dev/null; then
|
||||
echo " node ... $(node --version 2>/dev/null)"
|
||||
else
|
||||
echo " node ... MISSING"
|
||||
echo " Install Node.js: https://nodejs.org/"
|
||||
SB_MISSING+=("node")
|
||||
fi
|
||||
|
||||
# npm (needed for srt install)
|
||||
if command -v npm &>/dev/null; then
|
||||
echo " npm ... $(npm --version 2>/dev/null)"
|
||||
else
|
||||
echo " npm ... MISSING"
|
||||
SB_MISSING+=("npm")
|
||||
fi
|
||||
|
||||
# @anthropic-ai/sandbox-runtime — resolve same way as _srt_resolve.mjs
|
||||
if command -v node &>/dev/null; then
|
||||
SRT_PATH=$(node -e "
|
||||
const p = require('path');
|
||||
const fs = require('fs');
|
||||
const prefix = p.dirname(p.dirname(process.execPath));
|
||||
const entry = p.join(prefix, 'lib/node_modules/@anthropic-ai/sandbox-runtime/dist/index.js');
|
||||
if (fs.existsSync(entry)) process.stdout.write(entry);
|
||||
else process.exit(1);
|
||||
" 2>/dev/null) || SRT_PATH=""
|
||||
if [ -n "$SRT_PATH" ]; then
|
||||
echo " srt ... $SRT_PATH"
|
||||
else
|
||||
echo " srt ... MISSING"
|
||||
if command -v npm &>/dev/null; then
|
||||
echo " Attempting: npm install -g @anthropic-ai/sandbox-runtime"
|
||||
if npm install -g @anthropic-ai/sandbox-runtime 2>/dev/null; then
|
||||
echo " srt ... installed"
|
||||
else
|
||||
echo " Install failed (may need sudo). Run manually:"
|
||||
echo " sudo npm install -g @anthropic-ai/sandbox-runtime"
|
||||
SB_MISSING+=("srt")
|
||||
fi
|
||||
else
|
||||
echo " Install node+npm first, then: npm install -g @anthropic-ai/sandbox-runtime"
|
||||
SB_MISSING+=("srt")
|
||||
fi
|
||||
fi
|
||||
else
|
||||
echo " srt ... skipped (no node)"
|
||||
SB_MISSING+=("srt")
|
||||
fi
|
||||
|
||||
# rg (ripgrep)
|
||||
if command -v rg &>/dev/null; then
|
||||
echo " rg ... $(rg --version 2>/dev/null | head -1)"
|
||||
elif [ -f "$HOME/.local/bin/rg" ]; then
|
||||
echo " rg ... $HOME/.local/bin/rg"
|
||||
else
|
||||
echo " rg ... MISSING"
|
||||
echo " sudo apt install ripgrep"
|
||||
SB_MISSING+=("rg")
|
||||
fi
|
||||
|
||||
if [ ${#SB_MISSING[@]} -eq 0 ]; then
|
||||
echo " sandbox prereqs: READY"
|
||||
else
|
||||
echo " sandbox prereqs: INCOMPLETE (${SB_MISSING[*]} missing) — aipass doctor for details"
|
||||
fi
|
||||
fi
|
||||
|
||||
# --- Verify CLI entry points ---
|
||||
FAIL=0
|
||||
|
||||
@@ -478,12 +598,13 @@ bootstrap_branch "spawn" "$SCRIPT_DIR/src/aipass/spawn" "builder" "Branch
|
||||
bootstrap_branch "devpulse" "$SCRIPT_DIR/src/aipass/devpulse" "manager" "Orchestration hub and coordination"
|
||||
bootstrap_branch "memory" "$SCRIPT_DIR/src/aipass/memory" "builder" "Vector memory bank"
|
||||
bootstrap_branch "aipass" "$SCRIPT_DIR/src/aipass/aipass" "builder" "Concierge — init, doctor, profile, onboarding"
|
||||
bootstrap_branch "hooks" "$SCRIPT_DIR/src/aipass/hooks" "builder" "Hook engine — cross-platform hook dispatch and per-project config"
|
||||
|
||||
# External branches
|
||||
# NOTE: backup, daemon removed S82/S87. commons, skills moved to external repos.
|
||||
# Only the 12 core branches above should be bootstrapped.
|
||||
# Only the 13 core branches above should be bootstrapped.
|
||||
|
||||
echo " 12 branches bootstrapped"
|
||||
echo " 13 branches bootstrapped"
|
||||
|
||||
# --- Seed branch config files from .example defaults ---
|
||||
# Some branches need a config file that's gitignored (contains local state).
|
||||
@@ -518,7 +639,7 @@ if [ -f "$SCRIPT_DIR/src/aipass/hooks/apps/handlers/bridges/claude.py" ]; then
|
||||
echo "Installing Claude Code hooks ..."
|
||||
mkdir -p "$HOME/.claude"
|
||||
|
||||
"$PYTHON" - "$SCRIPT_DIR" "$CLAUDE_SETTINGS" << 'PYEOF'
|
||||
"$PYTHON" - "$SCRIPT_DIR" "$CLAUDE_SETTINGS" "$IS_WINDOWS" << 'PYEOF'
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
@@ -526,11 +647,16 @@ from pathlib import Path
|
||||
|
||||
repo_root = sys.argv[1]
|
||||
settings_path = Path(sys.argv[2])
|
||||
is_windows = len(sys.argv) > 3 and sys.argv[3] == "1"
|
||||
|
||||
# Bridge entry point — all hooks route through the engine via this bridge.
|
||||
# Uses $AIPASS_HOME env var (injected into settings.env below) so the
|
||||
# settings file stays relocatable.
|
||||
bridge = "$AIPASS_HOME/.venv/bin/python3 $AIPASS_HOME/src/aipass/hooks/apps/handlers/bridges/claude.py"
|
||||
# settings file stays relocatable. CC on Windows runs hooks via Git Bash
|
||||
# (which must exist for setup.sh to have run), so $VAR expansion works —
|
||||
# but the venv interpreter lives at Scripts/python.exe there, not bin/python3
|
||||
# (@hooks assessment, DPLAN-0234 Strand C).
|
||||
venv_python = ".venv/Scripts/python.exe" if is_windows else ".venv/bin/python3"
|
||||
bridge = f"$AIPASS_HOME/{venv_python} $AIPASS_HOME/src/aipass/hooks/apps/handlers/bridges/claude.py"
|
||||
|
||||
# Load existing settings or start fresh
|
||||
if settings_path.exists():
|
||||
@@ -539,15 +665,18 @@ else:
|
||||
settings = {}
|
||||
|
||||
# Build hooks config — bridge pattern
|
||||
# UserPromptSubmit: 4 separate entries (EventType:hook_name) to avoid output merging
|
||||
# UserPromptSubmit: 5 separate entries (EventType:hook_name) to avoid output merging
|
||||
# PreToolUse, PostToolUse, SubagentStop, Stop, Notification: single aggregate entries
|
||||
# PreCompact: 2 hooks x 2 matchers (manual + auto) = 4 entries
|
||||
settings["hooks"] = {
|
||||
# PreCompact: 3 hooks x 2 matchers (manual + auto) = 6 entries
|
||||
# SessionStart: cadence reset on startup/clear (handler skips resume itself)
|
||||
aipass_hooks = {
|
||||
"UserPromptSubmit": [
|
||||
{"hooks": [{"type": "command", "command": f"{bridge} UserPromptSubmit:global_prompt"}]},
|
||||
{"hooks": [{"type": "command", "command": f"{bridge} UserPromptSubmit:tier0_kernel"}]},
|
||||
{"hooks": [{"type": "command", "command": f"{bridge} UserPromptSubmit:navmap"}]},
|
||||
{"hooks": [{"type": "command", "command": f"{bridge} UserPromptSubmit:branch_prompt"}]},
|
||||
{"hooks": [{"type": "command", "command": f"{bridge} UserPromptSubmit:identity_injector"}]},
|
||||
{"hooks": [{"type": "command", "command": f"{bridge} UserPromptSubmit:email_notification"}]},
|
||||
{"hooks": [{"type": "command", "command": f"{bridge} UserPromptSubmit:auto_process", "timeout": 120}]},
|
||||
],
|
||||
"PreToolUse": [
|
||||
{"matcher": "Bash|Edit|MultiEdit|Write|Read|Grep|Glob|WebSearch|WebFetch|Task",
|
||||
@@ -571,9 +700,35 @@ settings["hooks"] = {
|
||||
{"matcher": "auto", "hooks": [{"type": "command", "command": f"{bridge} PreCompact:pre_compact", "timeout": 60}]},
|
||||
{"matcher": "manual", "hooks": [{"type": "command", "command": f"{bridge} PreCompact:pre_compact_rollover", "timeout": 120}]},
|
||||
{"matcher": "auto", "hooks": [{"type": "command", "command": f"{bridge} PreCompact:pre_compact_rollover", "timeout": 120}]},
|
||||
{"matcher": "manual", "hooks": [{"type": "command", "command": f"{bridge} PreCompact:auto_process", "timeout": 120}]},
|
||||
{"matcher": "auto", "hooks": [{"type": "command", "command": f"{bridge} PreCompact:auto_process", "timeout": 120}]},
|
||||
],
|
||||
"SessionStart": [
|
||||
{"hooks": [{"type": "command", "command": f"{bridge} SessionStart:cadence_reset", "timeout": 30}]},
|
||||
],
|
||||
}
|
||||
|
||||
# Merge, don't replace (DPLAN-0234 Strand C): refresh every AIPass bridge entry
|
||||
# (identified by the bridges/claude.py marker) but preserve any hooks the user
|
||||
# wired themselves. Re-runs stay idempotent; custom hooks survive reinstall.
|
||||
existing_hooks = settings.get("hooks", {})
|
||||
merged_hooks = {}
|
||||
for event in set(existing_hooks) | set(aipass_hooks):
|
||||
user_entries = [
|
||||
entry for entry in existing_hooks.get(event, [])
|
||||
if "bridges/claude.py" not in json.dumps(entry)
|
||||
]
|
||||
merged = aipass_hooks.get(event, []) + user_entries
|
||||
# Never emit an empty hook event. If this event had only stale AIPass bridge
|
||||
# entries (no current aipass_hooks definition AND no user-wired hooks), the
|
||||
# filter above orphans it to [] — a half-wired event that fires nothing,
|
||||
# written silently. Drop the key instead and say so, so the state stays honest.
|
||||
if not merged:
|
||||
print(f" ! dropped orphaned hook event (no live entries): {event}")
|
||||
continue
|
||||
merged_hooks[event] = merged
|
||||
settings["hooks"] = merged_hooks
|
||||
|
||||
# Inject AIPASS_HOME into env block so dispatched agents find AIPass
|
||||
env_block = settings.get("env", {})
|
||||
env_block["AIPASS_HOME"] = repo_root
|
||||
@@ -605,7 +760,6 @@ git_deny = [
|
||||
"Bash(git push -f *)",
|
||||
"Bash(git rebase*)",
|
||||
"Bash(git clean*)",
|
||||
"Bash(rm -rf*)",
|
||||
"Bash(git reset*)",
|
||||
"Bash(git merge*)",
|
||||
"Bash(git config*)",
|
||||
@@ -616,7 +770,6 @@ git_deny = [
|
||||
"Bash(git branch -D*)",
|
||||
"Bash(git stash drop*)",
|
||||
"Bash(git stash clear*)",
|
||||
"Bash(rm -r *)",
|
||||
"Bash(git checkout -b*)",
|
||||
"Bash(git switch -c*)",
|
||||
"Bash(git switch --create*)",
|
||||
@@ -651,6 +804,16 @@ else
|
||||
echo "Skipping Claude hooks (bridge not found at src/aipass/hooks/apps/handlers/bridges/claude.py)"
|
||||
fi
|
||||
|
||||
# --- Install claude() boot shim (attach-if-live / start-in-tmux) ---
|
||||
# Ships via the .gitignore negation (#666). Idempotent: the installer checks for
|
||||
# its marker before appending to the shell rc, and resolves the venv Python from
|
||||
# its own location (POSIX/Windows/fallback). Composes with presence_gate seeding.
|
||||
BOOT_SHIM="$SCRIPT_DIR/src/aipass/hooks/tools/install_boot_shim.sh"
|
||||
if [ -f "$BOOT_SHIM" ]; then
|
||||
echo "Installing claude() boot shim ..."
|
||||
bash "$BOOT_SHIM" || echo " boot shim install skipped (non-fatal)"
|
||||
fi
|
||||
|
||||
# --- Install Claude Code commands (provider level) ---
|
||||
# memo.md belongs at provider level — works in all projects.
|
||||
# prep.md stays at repo root only — it's AIPass-specific.
|
||||
@@ -817,8 +980,42 @@ else
|
||||
fi
|
||||
|
||||
# --- Create global symlinks for CLI tools (Linux/macOS only) ---
|
||||
# #660: never SILENTLY hijack a global 'drone'/'aipass' that points at a
|
||||
# DIFFERENT install. safe_symlink skips a different-target link (loud warning)
|
||||
# unless --force-symlink; --no-symlink opts out of symlinking entirely.
|
||||
SYMLINK_SKIPPED=0
|
||||
safe_symlink() {
|
||||
# safe_symlink <src> <dest> [sudo] -> 0 linked · 1 skipped(diff target) · 2 ln failed
|
||||
local src="$1" dest="$2" use_sudo="${3:-}" existing=""
|
||||
if [ -L "$dest" ]; then
|
||||
existing="$(readlink "$dest" 2>/dev/null)"
|
||||
elif [ -e "$dest" ]; then
|
||||
existing="$dest (real file, not a symlink)"
|
||||
fi
|
||||
if [ -n "$existing" ] && [ "$existing" != "$src" ]; then
|
||||
if [ "$FORCE_SYMLINK" != "yes" ]; then
|
||||
echo " SKIP $dest — already points at a different install:"
|
||||
echo " $existing"
|
||||
echo " Not repointing (would hijack your existing '$(basename "$dest")'); PATH keeps the above."
|
||||
echo " Re-run 'aipass install' with --force-symlink to repoint here, or --no-symlink to skip quietly."
|
||||
SYMLINK_SKIPPED=$((SYMLINK_SKIPPED + 1))
|
||||
return 1
|
||||
fi
|
||||
echo " WARNING: repointing $dest"
|
||||
echo " from $existing"
|
||||
echo " to $src (--force-symlink)"
|
||||
fi
|
||||
if [ -n "$use_sudo" ]; then
|
||||
$use_sudo ln -sf "$src" "$dest" 2>/dev/null && return 0 || return 2
|
||||
fi
|
||||
ln -sf "$src" "$dest" 2>/dev/null && return 0 || return 2
|
||||
}
|
||||
|
||||
echo ""
|
||||
if [ "$IS_WINDOWS" -eq 1 ]; then
|
||||
if [ "$SKIP_SYMLINK" = "yes" ]; then
|
||||
echo "Skipping global CLI symlinks (--no-symlink)."
|
||||
echo " 'drone'/'aipass' resolve from $SCRIPT_DIR/.venv/bin — add it to PATH to use them."
|
||||
elif [ "$IS_WINDOWS" -eq 1 ]; then
|
||||
echo "Windows: drone available via PATH (set above)"
|
||||
elif [ "$IS_MACOS" -eq 1 ]; then
|
||||
# Mac: symlink into ~/.local/bin (user-writable, no sudo needed).
|
||||
@@ -830,9 +1027,11 @@ elif [ "$IS_MACOS" -eq 1 ]; then
|
||||
|
||||
for cmd in drone aipass; do
|
||||
if [ -f "$VENV_BIN/$cmd" ]; then
|
||||
if ln -sf "$VENV_BIN/$cmd" "$LOCAL_BIN/$cmd"; then
|
||||
rc=0
|
||||
safe_symlink "$VENV_BIN/$cmd" "$LOCAL_BIN/$cmd" || rc=$?
|
||||
if [ "$rc" -eq 0 ]; then
|
||||
echo " $LOCAL_BIN/$cmd -> $VENV_BIN/$cmd"
|
||||
else
|
||||
elif [ "$rc" -eq 2 ]; then
|
||||
echo " WARN: Could not create symlink for $cmd"
|
||||
echo " Manual fix: ln -sf $VENV_BIN/$cmd $LOCAL_BIN/$cmd"
|
||||
fi
|
||||
@@ -845,14 +1044,20 @@ else
|
||||
|
||||
for cmd in drone aipass; do
|
||||
if [ -f "$VENV_BIN/$cmd" ]; then
|
||||
if sudo ln -sf "$VENV_BIN/$cmd" "/usr/local/bin/$cmd" 2>/dev/null; then
|
||||
rc=0
|
||||
safe_symlink "$VENV_BIN/$cmd" "/usr/local/bin/$cmd" "sudo" || rc=$?
|
||||
if [ "$rc" -eq 0 ]; then
|
||||
echo " /usr/local/bin/$cmd -> $VENV_BIN/$cmd"
|
||||
LINUX_SYMLINK_DIR="/usr/local/bin"
|
||||
elif [ "$rc" -eq 1 ]; then
|
||||
: # skipped a different install — safe_symlink explained; do NOT fall back
|
||||
else
|
||||
# Fallback: user-local bin (no sudo needed)
|
||||
# sudo/ln failed (e.g. no sudo) — fall back to user-local bin
|
||||
LOCAL_BIN="$HOME/.local/bin"
|
||||
mkdir -p "$LOCAL_BIN"
|
||||
if ln -sf "$VENV_BIN/$cmd" "$LOCAL_BIN/$cmd"; then
|
||||
rc=0
|
||||
safe_symlink "$VENV_BIN/$cmd" "$LOCAL_BIN/$cmd" || rc=$?
|
||||
if [ "$rc" -eq 0 ]; then
|
||||
echo " /usr/local/bin failed (no sudo) — using $LOCAL_BIN/$cmd instead"
|
||||
LINUX_SYMLINK_DIR="$LOCAL_BIN"
|
||||
# Ensure ~/.local/bin is on PATH
|
||||
@@ -862,7 +1067,7 @@ else
|
||||
echo " ~/.local/bin added to PATH in $PROFILE"
|
||||
fi
|
||||
export PATH="$HOME/.local/bin:$PATH"
|
||||
else
|
||||
elif [ "$rc" -eq 2 ]; then
|
||||
echo " WARN: Could not create symlink for $cmd"
|
||||
echo " Manual fix: ln -sf $VENV_BIN/$cmd $LOCAL_BIN/$cmd"
|
||||
fi
|
||||
@@ -871,6 +1076,12 @@ else
|
||||
done
|
||||
fi
|
||||
|
||||
if [ "$SYMLINK_SKIPPED" -gt 0 ]; then
|
||||
echo ""
|
||||
echo " NOTE: $SYMLINK_SKIPPED global symlink(s) left untouched (pointed at a different install)."
|
||||
echo " Your existing 'drone'/'aipass' still work. Use --force-symlink to repoint them here."
|
||||
fi
|
||||
|
||||
# --- Result ---
|
||||
echo ""
|
||||
if [ "$FAIL" -eq 0 ]; then
|
||||
@@ -893,6 +1104,77 @@ if [ "$FAIL" -eq 0 ]; then
|
||||
echo " Claude Code: hooks installed to ~/.claude/settings.json"
|
||||
command -v codex &>/dev/null && echo " Codex CLI: hooks at .codex/hooks.json + config at ~/.codex/config.toml"
|
||||
echo ""
|
||||
|
||||
# --- Chain into first-project init (DPLAN-0234: one command does setup + init) ---
|
||||
# `aipass init` refuses to run inside the engine tree, so it always targets a
|
||||
# sibling directory — never the repo itself. Decision mirrors install.py:
|
||||
# --no-init wins, --with-init forces (headless chains --non-interactive),
|
||||
# default = interactive terminals only (CI and piped shells skip).
|
||||
AIPASS_BIN=""
|
||||
if [ "$IS_WINDOWS" -eq 1 ] && [ -f "$SCRIPT_DIR/.venv/Scripts/aipass.exe" ]; then
|
||||
AIPASS_BIN="$SCRIPT_DIR/.venv/Scripts/aipass.exe"
|
||||
elif [ "$IS_WINDOWS" -eq 1 ] && [ -f "$SCRIPT_DIR/.venv/Scripts/aipass" ]; then
|
||||
AIPASS_BIN="$SCRIPT_DIR/.venv/Scripts/aipass"
|
||||
elif [ -f "$SCRIPT_DIR/.venv/bin/aipass" ]; then
|
||||
AIPASS_BIN="$SCRIPT_DIR/.venv/bin/aipass"
|
||||
elif command -v aipass &>/dev/null; then
|
||||
AIPASS_BIN="$(command -v aipass)"
|
||||
fi
|
||||
|
||||
LAUNCH_INIT=0
|
||||
INIT_HEADLESS=0
|
||||
if [ "$RUN_INIT" = "no" ]; then
|
||||
echo "Skipping first-project init (--no-init). Run 'aipass init run' in a fresh directory when ready."
|
||||
elif [ "$RUN_INIT" = "yes" ]; then
|
||||
LAUNCH_INIT=1
|
||||
if [ ! -t 0 ]; then
|
||||
INIT_HEADLESS=1
|
||||
fi
|
||||
elif [ -t 0 ] && [ -z "${CI:-}" ]; then
|
||||
LAUNCH_INIT=1
|
||||
else
|
||||
echo "Non-interactive shell — skipping first-project init. Run 'aipass init run' in a fresh directory when ready."
|
||||
fi
|
||||
|
||||
if [ "$LAUNCH_INIT" -eq 1 ]; then
|
||||
if [ -z "$AIPASS_BIN" ]; then
|
||||
echo "WARN: aipass binary not found — open a new terminal and run 'aipass init run' in a fresh directory."
|
||||
else
|
||||
DEFAULT_PROJECT_DIR="$HOME/aipass-project"
|
||||
PROJECT_DIR="$INIT_PROJECT"
|
||||
if [ -z "$PROJECT_DIR" ] && [ "$INIT_HEADLESS" -eq 0 ] && [ -t 0 ]; then
|
||||
echo "AIPass projects live in their own directory, never inside the engine repo."
|
||||
read -r -p "Set up your first project now? [Y/n]: " INIT_REPLY
|
||||
case "$INIT_REPLY" in
|
||||
[nN]*)
|
||||
PROJECT_DIR="-"
|
||||
echo " Skipped. Run 'aipass init run' in a fresh directory when ready."
|
||||
;;
|
||||
*)
|
||||
read -r -p " Project directory [$DEFAULT_PROJECT_DIR]: " INIT_INPUT
|
||||
PROJECT_DIR="${INIT_INPUT:-$DEFAULT_PROJECT_DIR}"
|
||||
;;
|
||||
esac
|
||||
elif [ -z "$PROJECT_DIR" ]; then
|
||||
PROJECT_DIR="$DEFAULT_PROJECT_DIR"
|
||||
fi
|
||||
|
||||
if [ "$PROJECT_DIR" != "-" ]; then
|
||||
mkdir -p "$PROJECT_DIR"
|
||||
INIT_CMD=("$AIPASS_BIN" init run)
|
||||
if [ "$INIT_HEADLESS" -eq 1 ]; then
|
||||
INIT_CMD+=(--non-interactive)
|
||||
fi
|
||||
echo ""
|
||||
echo "Launching guided setup in $PROJECT_DIR ..."
|
||||
if (cd "$PROJECT_DIR" && "${INIT_CMD[@]}"); then
|
||||
echo "First project initialized at $PROJECT_DIR"
|
||||
else
|
||||
echo "Init didn't complete — run 'aipass init run' in $PROJECT_DIR when ready."
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
else
|
||||
echo "=== Setup finished with errors ==="
|
||||
echo "The venv was created and the package was installed, but one or more"
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
"""AIPass — Multi-agent orchestration framework.
|
||||
|
||||
pip install aipass
|
||||
https://github.com/AIOSAI/AIPass
|
||||
git clone + ./setup.sh — https://github.com/AIOSAI/AIPass
|
||||
"""
|
||||
|
||||
__version__ = "2.2.0"
|
||||
__version__ = "2.7.0"
|
||||
|
||||
@@ -23,7 +23,7 @@
|
||||
{
|
||||
"file": "apps/handlers/dispatch/daemon.py",
|
||||
"standard": "deep_nesting",
|
||||
"reason": "3 functions: check_inbox_for_dispatch() depth 4 (priority scanning with business logic), run_daemon() depth 4 (main daemon loop), _check_lock() depth 4 (lock validation + PID liveness + cleanup)"
|
||||
"reason": "run_daemon() depth 5 (main daemon loop with retry + signal handling)"
|
||||
},
|
||||
{
|
||||
"file": "apps/handlers/dispatch/wake.py",
|
||||
@@ -60,11 +60,6 @@
|
||||
"standard": "deep_nesting",
|
||||
"reason": "2 functions: get_user_by_email() depth 4, get_all_users() depth 4 — registry lookup with path normalization and validation"
|
||||
},
|
||||
{
|
||||
"file": "apps/handlers/email/dashboard_sync.py",
|
||||
"standard": "handlers",
|
||||
"reason": "Imports prax.apps.modules.dashboard.write_section — cross-branch module import required for dashboard integration. No ai_mail module wraps this."
|
||||
},
|
||||
{
|
||||
"file": "apps/handlers/email/delivery.py",
|
||||
"standard": "handlers",
|
||||
@@ -93,7 +88,12 @@
|
||||
{
|
||||
"file": "apps/handlers/dispatch/dispatch_monitor.py",
|
||||
"standard": "handlers",
|
||||
"reason": "Imports notify.send_notification — same-branch cross-handler import for bounce/completion notifications."
|
||||
"reason": "Imports notify.send_notification (same-branch cross-handler) for bounce/completion notifications. Lazy-imports drone.apps.handlers.broker.client.create_identified_connection inside _connect_broker() for Phase 6b broker-fd handshake (FPLAN-0250) — cross-branch handler import authorized by brief."
|
||||
},
|
||||
{
|
||||
"file": "apps/handlers/dispatch/dispatch_monitor.py",
|
||||
"standard": "encapsulation",
|
||||
"reason": "Lazy-imports drone.apps.handlers.broker.client.create_identified_connection inside _connect_broker() — cross-branch handler import for Phase 6b broker-fd handshake (FPLAN-0250). Brief explicitly authorizes this import path."
|
||||
},
|
||||
{
|
||||
"file": "apps/handlers/dispatch/wake.py",
|
||||
@@ -115,11 +115,6 @@
|
||||
"standard": "naming",
|
||||
"reason": "False positive — _append_footer is a function reference stored in a local variable, not a module-level constant."
|
||||
},
|
||||
{
|
||||
"file": "apps/handlers/email/dashboard_sync.py",
|
||||
"standard": "naming",
|
||||
"reason": "False positive — _write_section is a lazy-import function reference, not a module-level constant."
|
||||
},
|
||||
{
|
||||
"file": "apps/handlers/email/delivery.py",
|
||||
"standard": "naming",
|
||||
@@ -195,11 +190,6 @@
|
||||
"standard": "deep_nesting",
|
||||
"reason": "_send_direct() depth 5 (arg parsing with branch resolution, --from flag, --dispatch flag), handle_close() depth 4 (close with archive + dashboard update)"
|
||||
},
|
||||
{
|
||||
"file": "apps/handlers/email/dashboard_sync.py",
|
||||
"standard": "deep_nesting",
|
||||
"reason": "_human_readable_age() depth 5, _calculate_section_data() depth 5 — timestamp parsing with multiple fallback formats"
|
||||
},
|
||||
{
|
||||
"file": "apps/handlers/dispatch/dispatch_monitor.py",
|
||||
"standard": "deep_nesting",
|
||||
|
||||
@@ -14,13 +14,19 @@ Main handles routing, modules implement functionality.
|
||||
"""
|
||||
|
||||
# Standard library imports
|
||||
import os
|
||||
import sys
|
||||
import importlib
|
||||
import argparse
|
||||
import signal
|
||||
from pathlib import Path
|
||||
from typing import Any, List
|
||||
|
||||
# AIPass infrastructure imports
|
||||
from aipass.prax.apps.modules.logger import system_logger as logger
|
||||
|
||||
# CLI services for display
|
||||
from aipass.cli.apps.modules import console, error
|
||||
|
||||
# Handle broken pipe gracefully (e.g. output piped to head)
|
||||
# SIGPIPE does not exist on Windows
|
||||
if hasattr(signal, "SIGPIPE"):
|
||||
@@ -29,11 +35,12 @@ if hasattr(signal, "SIGPIPE"):
|
||||
# Dashboard integration (optional, provided by prax)
|
||||
_UPDATE_SECTION = None # type: ignore
|
||||
|
||||
# AIPass infrastructure imports
|
||||
from aipass.prax.apps.modules.logger import system_logger as logger
|
||||
|
||||
# CLI services for display
|
||||
from aipass.cli.apps.modules import console, error
|
||||
if sys.platform == "win32":
|
||||
os.environ.setdefault("PYTHONUTF8", "1")
|
||||
for _stream in (sys.stdout, sys.stderr):
|
||||
_reconfigure = getattr(_stream, "reconfigure", None)
|
||||
if _reconfigure is not None:
|
||||
_reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
# =============================================================================
|
||||
# CONSTANTS & CONFIG
|
||||
@@ -51,52 +58,47 @@ MODULES_DIR = MODULE_ROOT / "modules"
|
||||
|
||||
|
||||
def print_help():
|
||||
"""Print drone-compliant help output"""
|
||||
parser = argparse.ArgumentParser(
|
||||
description="AI_MAIL Branch Operations - Email system for branch communication",
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter,
|
||||
epilog="""
|
||||
COMMANDS:
|
||||
dispatch - Send dispatch email + wake target (one step)
|
||||
email - Send email to a branch
|
||||
send - Send email (alias for email)
|
||||
inbox - List emails (new + opened)
|
||||
view - View email content (marks as opened)
|
||||
reply - Reply to email (closes + archives)
|
||||
close - Close email(s) without reply (archives)
|
||||
sent - View sent messages
|
||||
contacts - Manage contacts
|
||||
EMAIL LIFECYCLE (v2):
|
||||
new → opened → closed
|
||||
- new: Just arrived, never viewed
|
||||
- opened: You've viewed it, not yet resolved
|
||||
- closed: Resolved (replied or dismissed), auto-archived
|
||||
"""Print drone-compliant help output with Rich markup"""
|
||||
console.print()
|
||||
console.print("[bold cyan]AI_MAIL — Email system for branch communication[/bold cyan]")
|
||||
console.print()
|
||||
|
||||
USAGE:
|
||||
drone @ai_mail <command> [args]
|
||||
drone @ai_mail --help
|
||||
console.print("[yellow]COMMANDS:[/yellow]")
|
||||
console.print(" [cyan]dispatch[/cyan] [dim]Send dispatch email + wake target (one step)[/dim]")
|
||||
console.print(" [cyan]email[/cyan] [dim]Send email to a branch[/dim]")
|
||||
console.print(" [cyan]send[/cyan] [dim]Send email (alias for email)[/dim]")
|
||||
console.print(" [cyan]inbox[/cyan] [dim]List emails (new + opened)[/dim]")
|
||||
console.print(" [cyan]view[/cyan] [dim]View email content (marks as opened)[/dim]")
|
||||
console.print(" [cyan]reply[/cyan] [dim]Reply to email (closes + archives)[/dim]")
|
||||
console.print(" [cyan]close[/cyan] [dim]Close email(s) without reply (archives)[/dim]")
|
||||
console.print(" [cyan]sent[/cyan] [dim]View sent messages[/dim]")
|
||||
console.print(" [cyan]contacts[/cyan] [dim]Manage contacts[/dim]")
|
||||
console.print()
|
||||
|
||||
EXAMPLES:
|
||||
# Dispatch (send + wake in one command)
|
||||
drone @ai_mail dispatch @branch "Subject" "Body"
|
||||
drone @ai_mail dispatch @branch "Subject" "Body" --fresh
|
||||
console.print("[yellow]EMAIL LIFECYCLE (v2):[/yellow]")
|
||||
console.print(" new → opened → closed")
|
||||
console.print(" [dim]new: Just arrived, never viewed[/dim]")
|
||||
console.print(" [dim]opened: You've viewed it, not yet resolved[/dim]")
|
||||
console.print(" [dim]closed: Resolved (replied or dismissed), auto-archived[/dim]")
|
||||
console.print()
|
||||
|
||||
# Send mail (no wake)
|
||||
drone @ai_mail email @seedgo "Subject" "Msg" # Send to branch
|
||||
drone @ai_mail email @all "Subject" "Msg" # Broadcast to all
|
||||
console.print("[yellow]USAGE:[/yellow]")
|
||||
console.print(" [cyan]drone @ai_mail[/cyan] <command> [args]")
|
||||
console.print(" [cyan]drone @ai_mail --help[/cyan]")
|
||||
console.print()
|
||||
|
||||
# Check mail
|
||||
drone @ai_mail inbox # List all emails
|
||||
drone @ai_mail view abc123 # View email (marks as opened)
|
||||
|
||||
# Resolve emails
|
||||
drone @ai_mail reply abc123 "Thanks!" # Reply + close + archive
|
||||
drone @ai_mail close abc123 # Close single email
|
||||
drone @ai_mail close abc123 def456 ghi789 # Close multiple emails
|
||||
drone @ai_mail close all # Close ALL emails
|
||||
""",
|
||||
)
|
||||
console.print(parser.format_help())
|
||||
console.print("[yellow]EXAMPLES:[/yellow]")
|
||||
console.print(' [cyan]drone @ai_mail dispatch @branch "Subject" "Body"[/cyan]')
|
||||
console.print(' [cyan]drone @ai_mail dispatch @branch "Subject" "Body" --fresh[/cyan]')
|
||||
console.print(' [cyan]drone @ai_mail email @seedgo "Subject" "Msg"[/cyan] [dim]Send to branch[/dim]')
|
||||
console.print(' [cyan]drone @ai_mail email @all "Subject" "Msg"[/cyan] [dim]Broadcast to all[/dim]')
|
||||
console.print(" [cyan]drone @ai_mail inbox[/cyan] [dim]List all emails[/dim]")
|
||||
console.print(" [cyan]drone @ai_mail view abc123[/cyan] [dim]View email[/dim]")
|
||||
console.print(' [cyan]drone @ai_mail reply abc123 "Thanks!"[/cyan] [dim]Reply + close + archive[/dim]')
|
||||
console.print(" [cyan]drone @ai_mail close abc123[/cyan] [dim]Close single email[/dim]")
|
||||
console.print(" [cyan]drone @ai_mail close abc123 def456 ghi789[/cyan] [dim]Close multiple[/dim]")
|
||||
console.print(" [cyan]drone @ai_mail close all[/cyan] [dim]Close ALL emails[/dim]")
|
||||
console.print()
|
||||
|
||||
|
||||
# =============================================================================
|
||||
@@ -241,6 +243,13 @@ def main():
|
||||
error("No modules found")
|
||||
return 1
|
||||
|
||||
if remaining_args and remaining_args[0] in ["--help", "-h"]:
|
||||
for module in modules:
|
||||
if module.handle_command(command, ["--help"]):
|
||||
return 0
|
||||
print_help()
|
||||
return 0
|
||||
|
||||
# Route command
|
||||
if route_command(command, remaining_args, modules):
|
||||
return 0
|
||||
|
||||
@@ -19,6 +19,7 @@ Architecture:
|
||||
"""
|
||||
|
||||
# CRITICAL: Use importlib to bypass local json/ directory and get stdlib json
|
||||
import os
|
||||
import sys
|
||||
import importlib.util
|
||||
|
||||
@@ -32,13 +33,20 @@ stdlib_json = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(stdlib_json)
|
||||
sys.path = _saved_path
|
||||
|
||||
from pathlib import Path
|
||||
from datetime import datetime
|
||||
from typing import Dict, Any, List, Tuple
|
||||
from pathlib import Path # noqa: E402
|
||||
from datetime import datetime # noqa: E402
|
||||
from typing import Dict, Any, List, Tuple # noqa: E402
|
||||
|
||||
from aipass.prax.apps.modules.logger import system_logger as logger
|
||||
from aipass.ai_mail.apps.handlers.json import json_handler
|
||||
from aipass.ai_mail.apps.handlers.paths import find_repo_root
|
||||
from aipass.prax.apps.modules.logger import system_logger as logger # noqa: E402
|
||||
from aipass.ai_mail.apps.handlers.json import json_handler # noqa: E402
|
||||
from aipass.ai_mail.apps.handlers.paths import find_repo_root # noqa: E402
|
||||
|
||||
if sys.platform == "win32":
|
||||
os.environ.setdefault("PYTHONUTF8", "1")
|
||||
for _stream in (sys.stdout, sys.stderr):
|
||||
_reconfigure = getattr(_stream, "reconfigure", None)
|
||||
if _reconfigure is not None:
|
||||
_reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
|
||||
# =============================================================================
|
||||
@@ -341,5 +349,7 @@ if __name__ == "__main__":
|
||||
console.print()
|
||||
|
||||
except Exception as e:
|
||||
console.print(f"[red]Error:[/red] {e}")
|
||||
from aipass.cli.apps.modules import error as cli_error
|
||||
|
||||
cli_error(f"Error: {e}")
|
||||
raise
|
||||
|
||||
@@ -33,6 +33,7 @@ from aipass.prax.apps.modules.logger import system_logger as logger
|
||||
from aipass.ai_mail.apps.handlers.json import json_handler
|
||||
from aipass.ai_mail.apps.handlers.dispatch.status import log_dispatch
|
||||
from aipass.ai_mail.apps.handlers.paths import find_repo_root
|
||||
from aipass.ai_mail.apps.handlers.dispatch.test_token import scan_and_ack_test_emails
|
||||
|
||||
|
||||
# Infrastructure paths
|
||||
@@ -49,9 +50,6 @@ BRANCH_REGISTRY = _REPO_ROOT / "AIPASS_REGISTRY.json"
|
||||
# Graceful shutdown
|
||||
SHUTDOWN = False
|
||||
|
||||
# AIPASS-TEST token handling extracted to test_token.py
|
||||
from aipass.ai_mail.apps.handlers.dispatch.test_token import scan_and_ack_test_emails
|
||||
|
||||
|
||||
def _handle_signal(signum, _frame):
|
||||
"""Handle shutdown signals for graceful daemon stop."""
|
||||
@@ -88,6 +86,56 @@ def _write_json(filepath: Path, data: Dict[str, Any]) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def _pid_alive_windows(pid: int) -> bool:
|
||||
"""Windows-safe liveness check via OpenProcess + GetExitCodeProcess."""
|
||||
import ctypes
|
||||
from ctypes import wintypes
|
||||
|
||||
PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
|
||||
STILL_ACTIVE = 259
|
||||
|
||||
kernel32 = ctypes.windll.kernel32 # type: ignore[attr-defined]
|
||||
kernel32.OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD]
|
||||
kernel32.OpenProcess.restype = wintypes.HANDLE
|
||||
kernel32.GetExitCodeProcess.argtypes = [wintypes.HANDLE, ctypes.POINTER(wintypes.DWORD)]
|
||||
kernel32.GetExitCodeProcess.restype = wintypes.BOOL
|
||||
kernel32.CloseHandle.argtypes = [wintypes.HANDLE]
|
||||
kernel32.CloseHandle.restype = wintypes.BOOL
|
||||
|
||||
handle = kernel32.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, False, pid)
|
||||
if not handle:
|
||||
return False
|
||||
try:
|
||||
exit_code = wintypes.DWORD()
|
||||
if not kernel32.GetExitCodeProcess(handle, ctypes.byref(exit_code)):
|
||||
return False
|
||||
return exit_code.value == STILL_ACTIVE
|
||||
finally:
|
||||
kernel32.CloseHandle(handle)
|
||||
|
||||
|
||||
def _pid_alive(pid: int) -> bool:
|
||||
"""Return True if the process is alive."""
|
||||
if sys.platform == "win32":
|
||||
try:
|
||||
return _pid_alive_windows(pid)
|
||||
except Exception as exc:
|
||||
logger.info("[daemon] PID %s Windows check failed (assuming alive): %s", pid, exc)
|
||||
return True
|
||||
try:
|
||||
os.kill(pid, 0)
|
||||
except ProcessLookupError as exc:
|
||||
logger.info("[daemon] PID %s not found: %s", pid, exc)
|
||||
return False
|
||||
except PermissionError as exc:
|
||||
logger.info("[daemon] PID %s permission denied (alive): %s", pid, exc)
|
||||
return True
|
||||
except OSError as exc:
|
||||
logger.info("[daemon] PID %s os.kill error (assuming dead): %s", pid, exc)
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _check_lock(branch_path: Path) -> Optional[Dict[str, Any]]:
|
||||
"""Check if branch has an active dispatch lock. Returns lock data or None."""
|
||||
lock_file = branch_path / ".ai_mail.local" / ".dispatch.lock"
|
||||
@@ -98,14 +146,9 @@ def _check_lock(branch_path: Path) -> Optional[Dict[str, Any]]:
|
||||
data = json.load(f)
|
||||
pid = data.get("pid")
|
||||
if pid is not None:
|
||||
try:
|
||||
os.kill(pid, 0)
|
||||
return data # Process alive, lock valid
|
||||
except ProcessLookupError:
|
||||
logger.info("Lock PID %s dead — stale lock cleanup needed", pid)
|
||||
except PermissionError as e:
|
||||
logger.warning("[daemon] Lock PID %s permission error: %s", pid, e)
|
||||
return data # Process exists, can't signal
|
||||
if _pid_alive(pid):
|
||||
return data
|
||||
logger.info("Lock PID %s dead — stale lock cleanup needed", pid)
|
||||
# Stale lock — check age (10 min timeout)
|
||||
ts = data.get("timestamp", "")
|
||||
if ts:
|
||||
@@ -216,15 +259,10 @@ def _write_pid_file() -> bool:
|
||||
# PID file exists — check if the owning process is alive
|
||||
try:
|
||||
old_pid = int(DAEMON_PID_FILE.read_text().strip())
|
||||
try:
|
||||
os.kill(old_pid, 0)
|
||||
logger.info(f"Another daemon already running (PID {old_pid}). Exiting.")
|
||||
return False
|
||||
except ProcessLookupError:
|
||||
logger.info(f"Removing stale PID file (PID {old_pid} is dead)")
|
||||
except PermissionError:
|
||||
logger.info(f"Another daemon already running (PID {old_pid}, permission denied). Exiting.")
|
||||
if _pid_alive(old_pid):
|
||||
logger.info("Another daemon already running (PID %s). Exiting.", old_pid)
|
||||
return False
|
||||
logger.info("Removing stale PID file (PID %s is dead)", old_pid)
|
||||
except (ValueError, OSError):
|
||||
logger.info("Corrupt PID file — removing")
|
||||
|
||||
@@ -410,14 +448,19 @@ def spawn_agent(
|
||||
logger.info(f"Lock acquisition failed for {branch_email}: {lock_msg}")
|
||||
return False
|
||||
|
||||
_detach_kwargs: dict = {}
|
||||
if sys.platform == "win32":
|
||||
_detach_kwargs["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP
|
||||
else:
|
||||
_detach_kwargs["start_new_session"] = True
|
||||
try:
|
||||
process = subprocess.Popen(
|
||||
monitor_cmd,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
start_new_session=True,
|
||||
cwd=str(branch_path),
|
||||
env=spawn_env,
|
||||
**_detach_kwargs,
|
||||
)
|
||||
|
||||
monitor_pid = process.pid
|
||||
@@ -471,18 +514,74 @@ def is_protected_branch(branch_email: str) -> bool:
|
||||
return branch_email == "@devpulse"
|
||||
|
||||
|
||||
def _read_session_type(pid_str: str) -> str:
|
||||
"""Read AIPASS_SESSION_TYPE from /proc/{pid}/environ. Returns 'interactive' if unset."""
|
||||
if sys.platform != "linux":
|
||||
return "interactive"
|
||||
def _get_pid_cwd(pid_str: str) -> Optional[str]:
|
||||
"""Get the cwd of a process. Cross-platform: Linux /proc, macOS lsof."""
|
||||
if sys.platform == "linux":
|
||||
try:
|
||||
return os.readlink(f"/proc/{pid_str}/cwd")
|
||||
except (OSError, PermissionError):
|
||||
logger.info("[daemon] Cannot read cwd for PID %s", pid_str)
|
||||
return None
|
||||
if sys.platform == "darwin":
|
||||
return _get_pid_cwd_darwin(pid_str)
|
||||
logger.info("[daemon] Cannot determine cwd for PID %s on %s", pid_str, sys.platform)
|
||||
return None
|
||||
|
||||
|
||||
def _get_pid_cwd_darwin(pid_str: str) -> Optional[str]:
|
||||
"""macOS: get process cwd via lsof."""
|
||||
try:
|
||||
with open(f"/proc/{pid_str}/environ", "rb") as f:
|
||||
data = f.read()
|
||||
for entry in data.split(b"\0"):
|
||||
if entry.startswith(b"AIPASS_SESSION_TYPE="):
|
||||
return entry.split(b"=", 1)[1].decode("utf-8")
|
||||
except (OSError, PermissionError):
|
||||
logger.info("Cannot read session type for PID %s", pid_str)
|
||||
result = subprocess.run(
|
||||
["lsof", "-a", "-p", pid_str, "-d", "cwd", "-Fn"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=5,
|
||||
)
|
||||
except (subprocess.SubprocessError, OSError):
|
||||
logger.info("[daemon] Cannot read cwd for PID %s on macOS", pid_str)
|
||||
return None
|
||||
if result.returncode != 0:
|
||||
return None
|
||||
for line in result.stdout.strip().split("\n"):
|
||||
if line.startswith("n/"):
|
||||
return line[1:]
|
||||
return None
|
||||
|
||||
|
||||
def _read_session_type(pid_str: str) -> str:
|
||||
"""Read AIPASS_SESSION_TYPE from process environment. Returns 'interactive' if unset."""
|
||||
if sys.platform == "linux":
|
||||
try:
|
||||
with open(f"/proc/{pid_str}/environ", "rb") as f:
|
||||
data = f.read()
|
||||
for entry in data.split(b"\0"):
|
||||
if entry.startswith(b"AIPASS_SESSION_TYPE="):
|
||||
return entry.split(b"=", 1)[1].decode("utf-8")
|
||||
except (OSError, PermissionError):
|
||||
logger.info("[daemon] Cannot read session type for PID %s", pid_str)
|
||||
return "interactive"
|
||||
if sys.platform == "darwin":
|
||||
return _read_session_type_darwin(pid_str)
|
||||
return "interactive"
|
||||
|
||||
|
||||
def _read_session_type_darwin(pid_str: str) -> str:
|
||||
"""macOS: read AIPASS_SESSION_TYPE from ps environment output."""
|
||||
try:
|
||||
result = subprocess.run(
|
||||
["ps", "-p", pid_str, "-wwE", "-o", "command="],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=5,
|
||||
)
|
||||
except (subprocess.SubprocessError, OSError):
|
||||
logger.info("[daemon] Cannot read session type for PID %s on macOS", pid_str)
|
||||
return "interactive"
|
||||
if result.returncode != 0:
|
||||
return "interactive"
|
||||
for token in result.stdout.split():
|
||||
if token.startswith("AIPASS_SESSION_TYPE="):
|
||||
return token.split("=", 1)[1]
|
||||
return "interactive"
|
||||
|
||||
|
||||
@@ -491,35 +590,25 @@ _NON_BLOCKING_SESSION_TYPES = {"dispatched", "daemon"}
|
||||
|
||||
|
||||
def _is_branch_occupied(branch_path: Path) -> bool:
|
||||
"""
|
||||
Check if an interactive Claude session is running in this branch.
|
||||
|
||||
Only interactive sessions block dispatch. Telegram, dispatched, and daemon
|
||||
sessions are idle/background and should not prevent new agent spawns.
|
||||
"""
|
||||
resolved = branch_path.resolve()
|
||||
"""Check if an interactive Claude session is running in this branch."""
|
||||
resolved = str(branch_path.resolve())
|
||||
try:
|
||||
result = subprocess.run(["pgrep", "-x", "claude"], capture_output=True, text=True, timeout=5)
|
||||
if result.returncode != 0:
|
||||
return False
|
||||
|
||||
for pid_str in result.stdout.strip().split("\n"):
|
||||
pid_str = pid_str.strip()
|
||||
if not pid_str:
|
||||
continue
|
||||
try:
|
||||
if sys.platform != "linux":
|
||||
continue
|
||||
cwd = os.readlink(f"/proc/{pid_str}/cwd")
|
||||
if Path(cwd).resolve() == resolved:
|
||||
session_type = _read_session_type(pid_str)
|
||||
if session_type not in _NON_BLOCKING_SESSION_TYPES:
|
||||
return True
|
||||
except (OSError, PermissionError, ValueError):
|
||||
logger.info("Cannot read cwd for PID %s", pid_str)
|
||||
cwd = _get_pid_cwd(pid_str)
|
||||
if cwd is None:
|
||||
continue
|
||||
if str(Path(cwd).resolve()) == resolved:
|
||||
session_type = _read_session_type(pid_str)
|
||||
if session_type not in _NON_BLOCKING_SESSION_TYPES:
|
||||
return True
|
||||
except Exception:
|
||||
logger.info("Failed to check branch occupancy for %s", branch_path)
|
||||
logger.info("[daemon] Failed to check branch occupancy for %s", branch_path)
|
||||
return False
|
||||
|
||||
|
||||
|
||||
@@ -23,6 +23,8 @@ is guaranteed.
|
||||
|
||||
import json
|
||||
import os
|
||||
import shlex
|
||||
import socket
|
||||
import sys
|
||||
import subprocess
|
||||
import time
|
||||
@@ -41,6 +43,123 @@ HARD_TIMEOUT = 7200 # 2 hours
|
||||
POLL_INTERVAL = 5
|
||||
|
||||
|
||||
def _is_sandbox_enabled() -> bool:
|
||||
"""Check if dispatch sandbox is enabled via AIPASS_SANDBOX_ENABLED env var."""
|
||||
return os.environ.get("AIPASS_SANDBOX_ENABLED", "").lower() in ("1", "true", "yes")
|
||||
|
||||
|
||||
def _wrap_for_sandbox(cmd: list, branch_path: Path) -> list:
|
||||
"""Wrap a claude command in the srt kernel sandbox.
|
||||
|
||||
Uses @hooks sandbox building blocks to resolve the bwrap command,
|
||||
then returns a shell invocation list compatible with Popen.
|
||||
|
||||
Raises on ANY failure — caller must not silently fall back to unsandboxed.
|
||||
"""
|
||||
from aipass.hooks.apps.modules.sandbox import build_policy, build_srt_config, resolve_bwrap_command
|
||||
|
||||
policy = build_policy(branch_path)
|
||||
srt_config = build_srt_config(policy)
|
||||
cmd_str = shlex.join(cmd)
|
||||
bwrap_cmd = resolve_bwrap_command(cmd_str, srt_config)
|
||||
return ["/bin/bash", "-c", bwrap_cmd]
|
||||
|
||||
|
||||
def _connect_broker(repo_root: Path, branch_name: str) -> socket.socket:
|
||||
"""Create an identified broker connection for the target branch.
|
||||
|
||||
Returns a connected, HMAC-authenticated socket ready to be inherited
|
||||
by the sandboxed child via pass_fds + AIPASS_BROKER_FD.
|
||||
|
||||
Raises on ANY failure — caller must not silently skip the broker.
|
||||
"""
|
||||
from aipass.drone.apps.handlers.broker.client import create_identified_connection
|
||||
|
||||
socket_path = repo_root / ".ai_central" / "drone_broker.sock"
|
||||
secret_path = repo_root / ".ai_central" / "broker_secret"
|
||||
return create_identified_connection(socket_path, secret_path, branch_name)
|
||||
|
||||
|
||||
MAX_WAKE_DEPTH = 3
|
||||
|
||||
|
||||
def _wake_sender(sender: str, branch_email: str, exit_code: int, lock_file: str) -> str:
|
||||
"""Wake the dispatcher back after target completion.
|
||||
|
||||
Wake-back is owner-only: only the project owner (sealed registry)
|
||||
gets woken. Non-owners silently skipped.
|
||||
|
||||
Returns a result tag for the dispatch_wake.log:
|
||||
success, blocked_occupied, blocked_locked, blocked_depth,
|
||||
skipped_sender, skipped_not_owner, failed
|
||||
"""
|
||||
if not sender or not sender.strip():
|
||||
logger.info("[monitor] Wake-back skipped — no sender")
|
||||
return "skipped_sender"
|
||||
|
||||
normalized = f"@{sender.lstrip('@').lower()}"
|
||||
|
||||
try:
|
||||
from aipass.spawn.apps.handlers.registry import is_owner
|
||||
except ImportError:
|
||||
logger.warning("[monitor] Wake-back skipped — is_owner import failed")
|
||||
return "failed"
|
||||
|
||||
if not is_owner(normalized):
|
||||
logger.info("[monitor] Wake-back skipped — sender %s is not project owner", sender)
|
||||
return "skipped_not_owner"
|
||||
|
||||
depth = int(os.environ.get("AIPASS_WAKE_DEPTH", "0"))
|
||||
if depth >= MAX_WAKE_DEPTH:
|
||||
logger.warning("[monitor] Wake-back skipped — depth %d >= max %d", depth, MAX_WAKE_DEPTH)
|
||||
return "blocked_depth"
|
||||
|
||||
try:
|
||||
from aipass.ai_mail.apps.handlers.dispatch.wake import wake_branch
|
||||
|
||||
os.environ["AIPASS_WAKE_DEPTH"] = str(depth + 1)
|
||||
wake_status, success = wake_branch(sender, auto=True, sender="@ai_mail")
|
||||
|
||||
if success:
|
||||
logger.info("[monitor] Wake-back: %s woken after %s completed (exit %d)", sender, branch_email, exit_code)
|
||||
return "success"
|
||||
|
||||
summary = wake_status.summary
|
||||
lower = summary.lower()
|
||||
if "interactive" in lower or "occupancy" in lower or "occupied" in lower:
|
||||
logger.info("[monitor] Wake-back blocked — sender %s has interactive session: %s", sender, summary)
|
||||
return "blocked_occupied"
|
||||
if "active agent" in lower or "lock" in lower:
|
||||
logger.info("[monitor] Wake-back blocked — sender %s has active lock: %s", sender, summary)
|
||||
return "blocked_locked"
|
||||
|
||||
logger.info("[monitor] Wake-back: %s not woken — %s", sender, summary)
|
||||
return "failed"
|
||||
except Exception as e:
|
||||
logger.warning("[monitor] Wake-back failed for %s: %s", sender, e)
|
||||
return "failed"
|
||||
|
||||
|
||||
def _log_wake_result(branch_email: str, sender: str, exit_code: int, result: str, lock_file: str):
|
||||
"""Append a wake-back result line to dispatch_wake.log under target's logs/."""
|
||||
lock_path = Path(lock_file).resolve()
|
||||
logs_dir = lock_path.parent.parent / "logs"
|
||||
log_file = logs_dir / "dispatch_wake.log"
|
||||
try:
|
||||
logs_dir.mkdir(parents=True, exist_ok=True)
|
||||
line = (
|
||||
f"{time.strftime('%Y-%m-%dT%H:%M:%S')}"
|
||||
f" target={branch_email}"
|
||||
f" sender={sender}"
|
||||
f" exit_code={exit_code}"
|
||||
f" wake_result={result}\n"
|
||||
)
|
||||
with open(log_file, "a", encoding="utf-8") as f:
|
||||
f.write(line)
|
||||
except OSError as e:
|
||||
logger.info("[monitor] Failed to write dispatch_wake.log: %s", e)
|
||||
|
||||
|
||||
def _send_bounce(branch_email: str, reason: str, sender: str, lock_file: str, stderr_log: str) -> bool:
|
||||
"""Send return-to-sender bounce email via drone."""
|
||||
subject = f"BOUNCE: Dispatch to {branch_email} failed"
|
||||
@@ -95,16 +214,27 @@ def _send_bounce(branch_email: str, reason: str, sender: str, lock_file: str, st
|
||||
return False
|
||||
|
||||
|
||||
def _check_rate_limited(stderr_log: str) -> bool:
|
||||
"""Check if stderr indicates API rate limiting or overload."""
|
||||
def _read_agent_stderr(stderr_log: str) -> str:
|
||||
"""Read the dispatch stderr log, excluding the monitor's own framing lines.
|
||||
|
||||
The monitor writes header/footer/attempt markers (all prefixed with "--- ")
|
||||
that embed the PID and timestamps. Those numbers must NOT be scanned for API
|
||||
error markers -- e.g. a PID like 14290 contains "429" and would otherwise be
|
||||
misread as an HTTP 429 rate-limit. Returns "" if the log can't be read.
|
||||
"""
|
||||
try:
|
||||
with open(stderr_log, "r", encoding="utf-8") as f:
|
||||
content = f.read()
|
||||
lower = content.lower()
|
||||
return "rate_limit" in lower or "429" in content or "overloaded" in lower or "529" in content
|
||||
return "".join(line for line in f if not line.lstrip().startswith("---"))
|
||||
except OSError as e:
|
||||
logger.warning("[monitor] _check_rate_limited failed reading %s: %s", stderr_log, e)
|
||||
return False
|
||||
logger.warning("[monitor] Failed reading stderr log %s: %s", stderr_log, e)
|
||||
return ""
|
||||
|
||||
|
||||
def _check_rate_limited(stderr_log: str) -> bool:
|
||||
"""Check if stderr indicates API rate limiting or overload."""
|
||||
content = _read_agent_stderr(stderr_log)
|
||||
lower = content.lower()
|
||||
return "rate_limit" in lower or "429" in content or "overloaded" in lower or "529" in content
|
||||
|
||||
|
||||
def _make_fresh_cmd(claude_cmd: list) -> list:
|
||||
@@ -176,7 +306,7 @@ def _kill_process(process: subprocess.Popen, branch_email: str):
|
||||
|
||||
|
||||
def _run_with_startup_check(
|
||||
claude_cmd: list, stdout_log: str, stderr_fh, cwd: str, spawn_env: dict, branch_email: str
|
||||
claude_cmd: list, stdout_log: str, stderr_fh, cwd: str, spawn_env: dict, branch_email: str, pass_fds: tuple = ()
|
||||
) -> tuple:
|
||||
"""
|
||||
Run claude with startup timeout check.
|
||||
@@ -194,13 +324,17 @@ def _run_with_startup_check(
|
||||
logger.warning("[monitor] Failed to open stdout log %s: %s", stdout_log, e)
|
||||
|
||||
try:
|
||||
process = subprocess.Popen(
|
||||
claude_cmd,
|
||||
stdout=stdout_fh if stdout_fh is not None else subprocess.DEVNULL,
|
||||
stderr=stderr_fh,
|
||||
cwd=cwd,
|
||||
env=spawn_env,
|
||||
)
|
||||
popen_kwargs = {
|
||||
"stdin": subprocess.DEVNULL,
|
||||
"stdout": stdout_fh if stdout_fh is not None else subprocess.DEVNULL,
|
||||
"stderr": stderr_fh,
|
||||
"cwd": cwd,
|
||||
"env": spawn_env,
|
||||
}
|
||||
if pass_fds:
|
||||
popen_kwargs["close_fds"] = True
|
||||
popen_kwargs["pass_fds"] = pass_fds
|
||||
process = subprocess.Popen(claude_cmd, **popen_kwargs)
|
||||
except Exception as e:
|
||||
logger.warning("[monitor] Failed to spawn %s: %s", branch_email, e)
|
||||
if stdout_fh is not None:
|
||||
@@ -274,6 +408,18 @@ def main():
|
||||
|
||||
json_handler.log_operation("dispatch_monitor_start", {"branch": branch_email, "sender": sender})
|
||||
|
||||
# Self-register PID in lock file — the parent may have written its own
|
||||
# PID during pre-spawn lock acquisition (DPLAN-0155), and under
|
||||
# systemd-run the parent PID belongs to the caller, not the monitor.
|
||||
try:
|
||||
lock_path_obj = Path(lock_file)
|
||||
if lock_path_obj.exists():
|
||||
ld = json.loads(lock_path_obj.read_text(encoding="utf-8"))
|
||||
ld["pid"] = os.getpid()
|
||||
lock_path_obj.write_text(json.dumps(ld, indent=2), encoding="utf-8")
|
||||
except (json.JSONDecodeError, OSError):
|
||||
logger.info("[monitor] Could not self-register PID in lock file %s", lock_file)
|
||||
|
||||
# Open stderr log for claude output (rotate if > 500KB)
|
||||
stderr_fh = None
|
||||
try:
|
||||
@@ -338,6 +484,11 @@ def main():
|
||||
|
||||
start_time = time.time()
|
||||
|
||||
# ─── Sandbox Gate ─────────────────────────────────────
|
||||
sandbox_enabled = _is_sandbox_enabled()
|
||||
if sandbox_enabled:
|
||||
logger.info("[monitor] Sandbox ENABLED for %s", branch_email)
|
||||
|
||||
# ─── Retry Loop: 3 Strikes ─────────────────────────────
|
||||
# Strike 1: original command (resume if -c was passed)
|
||||
# Strike 2: same command again (transient failure)
|
||||
@@ -356,14 +507,60 @@ def main():
|
||||
cmd = claude_cmd
|
||||
mode = "resume" if has_resume else "fresh"
|
||||
|
||||
# Sandbox wrap + broker fd: when enabled, wrap cmd and connect broker.
|
||||
# On failure: abort — NEVER silently launch unsandboxed.
|
||||
run_cmd = cmd
|
||||
broker_sock = None
|
||||
attempt_pass_fds: tuple = ()
|
||||
if sandbox_enabled:
|
||||
try:
|
||||
run_cmd = _wrap_for_sandbox(cmd, branch_path)
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
"[monitor] Sandbox init FAILED for %s: %s — ABORTING (will NOT launch unsandboxed)",
|
||||
branch_email,
|
||||
e,
|
||||
)
|
||||
exit_code = -4
|
||||
attempts.append({"attempt": attempt, "exit_code": exit_code, "startup_failed": False, "mode": mode})
|
||||
break
|
||||
|
||||
try:
|
||||
broker_sock = _connect_broker(_repo_root, branch_email.lstrip("@"))
|
||||
broker_fd = broker_sock.fileno()
|
||||
spawn_env["AIPASS_BROKER_FD"] = str(broker_fd)
|
||||
attempt_pass_fds = (broker_fd,)
|
||||
logger.info("[monitor] Broker fd %d connected for %s", broker_fd, branch_email)
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
"[monitor] Broker connect FAILED for %s: %s — ABORTING",
|
||||
branch_email,
|
||||
e,
|
||||
)
|
||||
exit_code = -4
|
||||
attempts.append({"attempt": attempt, "exit_code": exit_code, "startup_failed": False, "mode": mode})
|
||||
break
|
||||
|
||||
if stderr_fh is not None:
|
||||
stderr_fh.write(f"\n--- Attempt {attempt}/3 ({mode}) at {time.strftime('%H:%M:%S')} ---\n")
|
||||
stderr_fh.flush()
|
||||
|
||||
exit_code, startup_failed = _run_with_startup_check(
|
||||
cmd, stdout_log, stderr_fh if stderr_fh is not None else subprocess.DEVNULL, cwd, spawn_env, branch_email
|
||||
run_cmd,
|
||||
stdout_log,
|
||||
stderr_fh if stderr_fh is not None else subprocess.DEVNULL,
|
||||
cwd,
|
||||
spawn_env,
|
||||
branch_email,
|
||||
pass_fds=attempt_pass_fds,
|
||||
)
|
||||
|
||||
# Close parent's broker socket copy — child owns the fd now.
|
||||
if broker_sock is not None:
|
||||
broker_sock.close()
|
||||
broker_sock = None
|
||||
spawn_env.pop("AIPASS_BROKER_FD", None)
|
||||
|
||||
attempts.append({"attempt": attempt, "exit_code": exit_code, "startup_failed": startup_failed, "mode": mode})
|
||||
|
||||
# Success — done
|
||||
@@ -434,16 +631,14 @@ def main():
|
||||
|
||||
reason = f"All {len(attempts)} attempts failed after {duration}s.\n" + "\n".join(attempt_details)
|
||||
|
||||
# Check stderr for specific error categories
|
||||
try:
|
||||
with open(stderr_log, "r", encoding="utf-8") as f:
|
||||
content = f.read()
|
||||
if "rate_limit" in content.lower() or "429" in content:
|
||||
reason = f"API rate limit (all {len(attempts)} attempts failed, {duration}s)"
|
||||
elif "overloaded" in content.lower() or "529" in content:
|
||||
reason = f"API overloaded (all {len(attempts)} attempts failed, {duration}s)"
|
||||
except OSError:
|
||||
logger.info("[monitor] Failed to read stderr log for diagnostics")
|
||||
# Check stderr for specific error categories. Exclude the monitor's own
|
||||
# framing lines (PID/timestamp headers) so a number like a PID containing
|
||||
# "429" is not misread as an HTTP 429 rate-limit response.
|
||||
content = _read_agent_stderr(stderr_log)
|
||||
if "rate_limit" in content.lower() or "429" in content:
|
||||
reason = f"API rate limit (all {len(attempts)} attempts failed, {duration}s)"
|
||||
elif "overloaded" in content.lower() or "529" in content:
|
||||
reason = f"API overloaded (all {len(attempts)} attempts failed, {duration}s)"
|
||||
|
||||
_send_bounce(branch_email, reason, sender, lock_file, stderr_log)
|
||||
|
||||
@@ -470,6 +665,10 @@ def main():
|
||||
except Exception:
|
||||
logger.info("[monitor] Desktop notification unavailable")
|
||||
|
||||
# ─── Wake-back: wake the dispatcher ────────────────────
|
||||
wake_result = _wake_sender(sender, branch_email, exit_code, lock_file)
|
||||
_log_wake_result(branch_email, sender, exit_code, wake_result, lock_file)
|
||||
|
||||
sys.exit(0 if exit_code == 0 else 1)
|
||||
|
||||
|
||||
|
||||
@@ -14,13 +14,22 @@ without triggering dispatch. Extracted from daemon.py to keep
|
||||
the daemon under the 700-line architecture threshold.
|
||||
"""
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict
|
||||
|
||||
from aipass.prax.apps.modules.logger import system_logger as logger
|
||||
from aipass.ai_mail.apps.handlers.json import json_handler
|
||||
|
||||
if sys.platform == "win32":
|
||||
os.environ.setdefault("PYTHONUTF8", "1")
|
||||
for _stream in (sys.stdout, sys.stderr):
|
||||
_reconfigure = getattr(_stream, "reconfigure", None)
|
||||
if _reconfigure is not None:
|
||||
_reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
TEST_TOKEN = "[AIPASS-TEST — do not update memories, do not execute, reply 'ack' only]"
|
||||
|
||||
|
||||
|
||||
@@ -141,6 +141,34 @@ def _read_json(filepath: Path) -> Optional[dict]:
|
||||
return None
|
||||
|
||||
|
||||
def _pid_alive_windows(pid: int) -> bool:
|
||||
"""Windows-safe liveness check via OpenProcess + GetExitCodeProcess."""
|
||||
import ctypes
|
||||
from ctypes import wintypes
|
||||
|
||||
PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
|
||||
STILL_ACTIVE = 259
|
||||
|
||||
kernel32 = ctypes.windll.kernel32 # type: ignore[attr-defined]
|
||||
kernel32.OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD]
|
||||
kernel32.OpenProcess.restype = wintypes.HANDLE
|
||||
kernel32.GetExitCodeProcess.argtypes = [wintypes.HANDLE, ctypes.POINTER(wintypes.DWORD)]
|
||||
kernel32.GetExitCodeProcess.restype = wintypes.BOOL
|
||||
kernel32.CloseHandle.argtypes = [wintypes.HANDLE]
|
||||
kernel32.CloseHandle.restype = wintypes.BOOL
|
||||
|
||||
handle = kernel32.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, False, pid)
|
||||
if not handle:
|
||||
return False
|
||||
try:
|
||||
exit_code = wintypes.DWORD()
|
||||
if not kernel32.GetExitCodeProcess(handle, ctypes.byref(exit_code)):
|
||||
return False
|
||||
return exit_code.value == STILL_ACTIVE
|
||||
finally:
|
||||
kernel32.CloseHandle(handle)
|
||||
|
||||
|
||||
def _check_lock(branch_path: Path) -> Optional[dict]:
|
||||
"""Check if branch has an active dispatch lock. Returns lock data or None."""
|
||||
lock_file = branch_path / ".ai_mail.local" / ".dispatch.lock"
|
||||
@@ -151,14 +179,9 @@ def _check_lock(branch_path: Path) -> Optional[dict]:
|
||||
data = json.load(f)
|
||||
pid = data.get("pid")
|
||||
if pid is not None:
|
||||
try:
|
||||
os.kill(pid, 0)
|
||||
return data # Process alive, lock valid
|
||||
except ProcessLookupError:
|
||||
logger.info("[wake] Lock PID %s dead — cleaning stale lock", pid)
|
||||
except PermissionError as e:
|
||||
logger.warning("[wake] Lock PID %s permission error: %s", pid, e)
|
||||
return data # Process exists but can't signal — treat as active
|
||||
if _check_pid_alive(pid):
|
||||
return data
|
||||
logger.info("[wake] Lock PID %s dead — cleaning stale lock", pid)
|
||||
# Stale lock — check age (10 min timeout)
|
||||
ts = data.get("timestamp", "")
|
||||
if ts:
|
||||
@@ -210,18 +233,74 @@ def _load_config() -> dict:
|
||||
return config
|
||||
|
||||
|
||||
def _read_session_type(pid_str: str) -> str:
|
||||
"""Read AIPASS_SESSION_TYPE from /proc/{pid}/environ. Returns 'interactive' if unset."""
|
||||
if sys.platform != "linux":
|
||||
return "interactive"
|
||||
def _get_pid_cwd(pid_str: str) -> Optional[str]:
|
||||
"""Get the cwd of a process. Cross-platform: Linux /proc, macOS lsof."""
|
||||
if sys.platform == "linux":
|
||||
try:
|
||||
return os.readlink(f"/proc/{pid_str}/cwd")
|
||||
except (OSError, PermissionError):
|
||||
logger.info("[wake] Cannot read cwd for PID %s", pid_str)
|
||||
return None
|
||||
if sys.platform == "darwin":
|
||||
return _get_pid_cwd_darwin(pid_str)
|
||||
logger.info("[wake] Cannot determine cwd for PID %s on %s", pid_str, sys.platform)
|
||||
return None
|
||||
|
||||
|
||||
def _get_pid_cwd_darwin(pid_str: str) -> Optional[str]:
|
||||
"""macOS: get process cwd via lsof."""
|
||||
try:
|
||||
with open(f"/proc/{pid_str}/environ", "rb") as f:
|
||||
data = f.read()
|
||||
for entry in data.split(b"\0"):
|
||||
if entry.startswith(b"AIPASS_SESSION_TYPE="):
|
||||
return entry.split(b"=", 1)[1].decode("utf-8")
|
||||
except (OSError, PermissionError):
|
||||
logger.info("[wake] Cannot read session type for PID %s", pid_str)
|
||||
result = subprocess.run(
|
||||
["lsof", "-a", "-p", pid_str, "-d", "cwd", "-Fn"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=5,
|
||||
)
|
||||
except (subprocess.SubprocessError, OSError):
|
||||
logger.info("[wake] Cannot read cwd for PID %s on macOS", pid_str)
|
||||
return None
|
||||
if result.returncode != 0:
|
||||
return None
|
||||
for line in result.stdout.strip().split("\n"):
|
||||
if line.startswith("n/"):
|
||||
return line[1:]
|
||||
return None
|
||||
|
||||
|
||||
def _read_session_type(pid_str: str) -> str:
|
||||
"""Read AIPASS_SESSION_TYPE from process environment. Returns 'interactive' if unset."""
|
||||
if sys.platform == "linux":
|
||||
try:
|
||||
with open(f"/proc/{pid_str}/environ", "rb") as f:
|
||||
data = f.read()
|
||||
for entry in data.split(b"\0"):
|
||||
if entry.startswith(b"AIPASS_SESSION_TYPE="):
|
||||
return entry.split(b"=", 1)[1].decode("utf-8")
|
||||
except (OSError, PermissionError):
|
||||
logger.info("[wake] Cannot read session type for PID %s", pid_str)
|
||||
return "interactive"
|
||||
if sys.platform == "darwin":
|
||||
return _read_session_type_darwin(pid_str)
|
||||
return "interactive"
|
||||
|
||||
|
||||
def _read_session_type_darwin(pid_str: str) -> str:
|
||||
"""macOS: read AIPASS_SESSION_TYPE from ps environment output."""
|
||||
try:
|
||||
result = subprocess.run(
|
||||
["ps", "-p", pid_str, "-wwE", "-o", "command="],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=5,
|
||||
)
|
||||
except (subprocess.SubprocessError, OSError):
|
||||
logger.info("[wake] Cannot read session type for PID %s on macOS", pid_str)
|
||||
return "interactive"
|
||||
if result.returncode != 0:
|
||||
return "interactive"
|
||||
for token in result.stdout.split():
|
||||
if token.startswith("AIPASS_SESSION_TYPE="):
|
||||
return token.split("=", 1)[1]
|
||||
return "interactive"
|
||||
|
||||
|
||||
@@ -240,17 +319,13 @@ def _is_branch_occupied(branch_path: Path) -> bool:
|
||||
pid_str = pid_str.strip()
|
||||
if not pid_str:
|
||||
continue
|
||||
try:
|
||||
if sys.platform != "linux":
|
||||
continue
|
||||
cwd = os.readlink(f"/proc/{pid_str}/cwd")
|
||||
if str(Path(cwd).resolve()) == resolved:
|
||||
session_type = _read_session_type(pid_str)
|
||||
if session_type not in _NON_BLOCKING_SESSION_TYPES:
|
||||
return True
|
||||
except (OSError, PermissionError, ValueError):
|
||||
logger.info("[wake] Cannot read cwd for PID %s", pid_str)
|
||||
cwd = _get_pid_cwd(pid_str)
|
||||
if cwd is None:
|
||||
continue
|
||||
if str(Path(cwd).resolve()) == resolved:
|
||||
session_type = _read_session_type(pid_str)
|
||||
if session_type not in _NON_BLOCKING_SESSION_TYPES:
|
||||
return True
|
||||
except (subprocess.SubprocessError, OSError):
|
||||
logger.info("[wake] Failed to check branch occupancy")
|
||||
return False
|
||||
@@ -273,21 +348,110 @@ def _clean_zombies() -> int:
|
||||
|
||||
def _check_pid_alive(pid: int) -> bool:
|
||||
"""Check if a process is alive (not zombie)."""
|
||||
if sys.platform == "win32":
|
||||
try:
|
||||
return _pid_alive_windows(pid)
|
||||
except Exception as exc:
|
||||
logger.info("[wake] PID %s Windows check failed (assuming alive): %s", pid, exc)
|
||||
return True
|
||||
try:
|
||||
os.kill(pid, 0)
|
||||
# Also verify not zombie via /proc (Linux only)
|
||||
if sys.platform == "linux":
|
||||
with open(f"/proc/{pid}/status", "r") as f:
|
||||
for line in f:
|
||||
if line.startswith("State:"):
|
||||
return "Z" not in line
|
||||
return True
|
||||
except (ProcessLookupError, FileNotFoundError) as e:
|
||||
logger.warning("[wake] PID %s not found: %s", pid, e)
|
||||
except ProcessLookupError as exc:
|
||||
logger.warning("[wake] PID %s not found: %s", pid, exc)
|
||||
return False
|
||||
except PermissionError as e:
|
||||
logger.warning("[wake] PID %s permission denied: %s", pid, e)
|
||||
return True # Exists but can't check — assume alive
|
||||
except PermissionError as exc:
|
||||
logger.warning("[wake] PID %s permission denied: %s", pid, exc)
|
||||
return True
|
||||
except OSError as exc:
|
||||
logger.warning("[wake] PID %s os.kill error (assuming dead): %s", pid, exc)
|
||||
return False
|
||||
if sys.platform == "linux" and _is_zombie_linux(pid):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _is_zombie_linux(pid: int) -> bool:
|
||||
"""Return True if PID is a zombie (Linux /proc/status check)."""
|
||||
try:
|
||||
with open(f"/proc/{pid}/status", "r") as f:
|
||||
for line in f:
|
||||
if line.startswith("State:"):
|
||||
return "Z" in line
|
||||
except FileNotFoundError as exc:
|
||||
logger.warning("[wake] PID %s /proc not found: %s", pid, exc)
|
||||
return False
|
||||
|
||||
|
||||
def _spawn_in_systemd_scope(monitor_cmd, branch_path, spawn_env, branch_email, lock_file_path, custom_message, status):
|
||||
"""Spawn monitor in its own systemd unit to survive cgroup cleanup (td-48).
|
||||
|
||||
When wake_branch() runs inside a systemd oneshot service (e.g.
|
||||
daemon-tick.timer), the default KillMode=control-group sends SIGTERM to
|
||||
every process in the cgroup once the main process exits — killing the
|
||||
detached monitor and its claude child. systemd-run --user creates a
|
||||
transient service unit with its own cgroup so the monitor survives.
|
||||
|
||||
Returns True on success, False to fall back to direct Popen.
|
||||
"""
|
||||
unit_name = f"dispatch-{branch_email.lstrip('@')}"
|
||||
env_file = branch_path / "logs" / ".dispatch_env"
|
||||
|
||||
try:
|
||||
with open(env_file, "w", encoding="utf-8") as ef:
|
||||
for key, val in spawn_env.items():
|
||||
if "\n" not in str(val):
|
||||
ef.write(f"{key}={val}\n")
|
||||
env_file.chmod(0o600)
|
||||
except OSError as e:
|
||||
logger.warning("[wake] Failed to write env file for systemd-run: %s", e)
|
||||
return False
|
||||
|
||||
systemd_cmd = [
|
||||
"systemd-run",
|
||||
"--user",
|
||||
"--unit",
|
||||
unit_name,
|
||||
"--collect",
|
||||
"--property",
|
||||
f"WorkingDirectory={branch_path}",
|
||||
"--property",
|
||||
f"EnvironmentFile={env_file}",
|
||||
"--property",
|
||||
"StandardInput=null",
|
||||
"--",
|
||||
] + monitor_cmd
|
||||
|
||||
try:
|
||||
result = subprocess.run(systemd_cmd, capture_output=True, text=True, timeout=15)
|
||||
if result.returncode != 0:
|
||||
logger.warning("[wake] systemd-run failed (rc=%d): %s", result.returncode, result.stderr.strip())
|
||||
return False
|
||||
except (subprocess.SubprocessError, OSError) as e:
|
||||
logger.warning("[wake] systemd-run failed: %s", e)
|
||||
return False
|
||||
|
||||
try:
|
||||
pid_result = subprocess.run(
|
||||
["systemctl", "--user", "show", f"{unit_name}.service", "-p", "MainPID", "--value"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=5,
|
||||
)
|
||||
monitor_pid = int(pid_result.stdout.strip())
|
||||
if monitor_pid > 0:
|
||||
lock_data = {
|
||||
"pid": monitor_pid,
|
||||
"timestamp": time.strftime("%Y-%m-%dT%H:%M:%S"),
|
||||
"branch": str(branch_path),
|
||||
"subject": custom_message or "daemon wake",
|
||||
}
|
||||
with open(lock_file_path, "w", encoding="utf-8") as f:
|
||||
json.dump(lock_data, f, indent=2)
|
||||
except (subprocess.SubprocessError, ValueError, OSError) as e:
|
||||
logger.info("[wake] Could not query systemd unit PID: %s", e)
|
||||
|
||||
status.ok("spawn", f"Monitor started via systemd scope ({unit_name})")
|
||||
return True
|
||||
|
||||
|
||||
# ─── Branch Resolution ──────────────────────────────────
|
||||
@@ -487,54 +651,97 @@ def wake_branch(
|
||||
return status, False
|
||||
status.ok("lock-acquire", "Dispatch lock acquired")
|
||||
|
||||
try:
|
||||
process = subprocess.Popen(
|
||||
# When inside a systemd oneshot service (e.g. daemon-tick.timer), the
|
||||
# default KillMode=control-group sends SIGTERM to all cgroup members
|
||||
# when the service exits — killing the detached monitor. Escape by
|
||||
# launching the monitor in its own transient systemd unit (td-48).
|
||||
spawned_via_scope = False
|
||||
monitor_pid = 0
|
||||
if os.environ.get("INVOCATION_ID") and shutil.which("systemd-run"):
|
||||
spawned_via_scope = _spawn_in_systemd_scope(
|
||||
monitor_cmd,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
start_new_session=True,
|
||||
cwd=str(branch_path),
|
||||
env=spawn_env,
|
||||
branch_path,
|
||||
spawn_env,
|
||||
email,
|
||||
lock_file_path,
|
||||
custom_message,
|
||||
status,
|
||||
)
|
||||
|
||||
monitor_pid = process.pid
|
||||
if not spawned_via_scope:
|
||||
try:
|
||||
_detach_kwargs: dict = {}
|
||||
if sys.platform == "win32":
|
||||
_detach_kwargs["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP
|
||||
else:
|
||||
_detach_kwargs["start_new_session"] = True
|
||||
process = subprocess.Popen(
|
||||
monitor_cmd,
|
||||
stdin=subprocess.DEVNULL,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
cwd=str(branch_path),
|
||||
env=spawn_env,
|
||||
**_detach_kwargs,
|
||||
)
|
||||
|
||||
# Update lock with real monitor PID
|
||||
lock_file = branch_path / ".ai_mail.local" / ".dispatch.lock"
|
||||
lock_data = {
|
||||
"pid": monitor_pid,
|
||||
"timestamp": time.strftime("%Y-%m-%dT%H:%M:%S"),
|
||||
"branch": str(branch_path),
|
||||
"subject": custom_message or "manual wake",
|
||||
}
|
||||
with open(lock_file, "w", encoding="utf-8") as f:
|
||||
json.dump(lock_data, f, indent=2)
|
||||
monitor_pid = process.pid
|
||||
|
||||
status.ok("spawn", f"Monitor started (PID {monitor_pid})")
|
||||
# Update lock with real monitor PID
|
||||
lock_file = branch_path / ".ai_mail.local" / ".dispatch.lock"
|
||||
lock_data = {
|
||||
"pid": monitor_pid,
|
||||
"timestamp": time.strftime("%Y-%m-%dT%H:%M:%S"),
|
||||
"branch": str(branch_path),
|
||||
"subject": custom_message or "manual wake",
|
||||
}
|
||||
with open(lock_file, "w", encoding="utf-8") as f:
|
||||
json.dump(lock_data, f, indent=2)
|
||||
|
||||
except FileNotFoundError as e:
|
||||
lock_file = branch_path / ".ai_mail.local" / ".dispatch.lock"
|
||||
lock_file.unlink(missing_ok=True)
|
||||
logger.warning("[wake] Spawn failed — script not found: %s", e)
|
||||
status.fail("spawn", "Python or monitor script not found")
|
||||
return status, False
|
||||
except Exception as e:
|
||||
lock_file = branch_path / ".ai_mail.local" / ".dispatch.lock"
|
||||
lock_file.unlink(missing_ok=True)
|
||||
logger.warning("[wake] Spawn failed for %s: %s", branch_email, e)
|
||||
status.fail("spawn", f"{type(e).__name__}: {e}")
|
||||
return status, False
|
||||
status.ok("spawn", f"Monitor started (PID {monitor_pid})")
|
||||
|
||||
except FileNotFoundError as e:
|
||||
lock_file = branch_path / ".ai_mail.local" / ".dispatch.lock"
|
||||
lock_file.unlink(missing_ok=True)
|
||||
logger.warning("[wake] Spawn failed — script not found: %s", e)
|
||||
status.fail("spawn", "Python or monitor script not found")
|
||||
return status, False
|
||||
except Exception as e:
|
||||
lock_file = branch_path / ".ai_mail.local" / ".dispatch.lock"
|
||||
lock_file.unlink(missing_ok=True)
|
||||
logger.warning("[wake] Spawn failed for %s: %s", branch_email, e)
|
||||
status.fail("spawn", f"{type(e).__name__}: {e}")
|
||||
return status, False
|
||||
|
||||
# Step 9: Liveness check (brief wait then verify)
|
||||
time.sleep(2)
|
||||
if _check_pid_alive(monitor_pid):
|
||||
status.ok("alive", f"Agent responding (PID {monitor_pid} alive)")
|
||||
if spawned_via_scope:
|
||||
_unit = f"dispatch-{email.lstrip('@')}"
|
||||
try:
|
||||
check = subprocess.run(
|
||||
["systemctl", "--user", "is-active", f"{_unit}.service"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=5,
|
||||
)
|
||||
if check.stdout.strip() == "active":
|
||||
status.ok("alive", f"Agent responding (unit {_unit} active)")
|
||||
else:
|
||||
status.fail("alive", f"Agent died immediately ({check.stdout.strip()})")
|
||||
lock_file = branch_path / ".ai_mail.local" / ".dispatch.lock"
|
||||
lock_file.unlink(missing_ok=True)
|
||||
return status, False
|
||||
except Exception as e:
|
||||
logger.info("[wake] Cannot verify systemd unit %s: %s", _unit, e)
|
||||
status.warn("alive", "Cannot verify systemd unit status — assuming running")
|
||||
else:
|
||||
status.fail("alive", f"Agent died immediately (PID {monitor_pid})")
|
||||
# Clean up lock
|
||||
lock_file = branch_path / ".ai_mail.local" / ".dispatch.lock"
|
||||
lock_file.unlink(missing_ok=True)
|
||||
return status, False
|
||||
if _check_pid_alive(monitor_pid):
|
||||
status.ok("alive", f"Agent responding (PID {monitor_pid} alive)")
|
||||
else:
|
||||
status.fail("alive", f"Agent died immediately (PID {monitor_pid})")
|
||||
lock_file = branch_path / ".ai_mail.local" / ".dispatch.lock"
|
||||
lock_file.unlink(missing_ok=True)
|
||||
return status, False
|
||||
|
||||
# Desktop notification
|
||||
notif_body = custom_message[:80] if custom_message else "Manual wake: check inbox"
|
||||
|
||||
@@ -56,24 +56,17 @@ def batch_close(
|
||||
|
||||
def batch_close_post_ops(
|
||||
branch_path: Path,
|
||||
push_dashboard_fn: Optional[Callable] = None,
|
||||
update_central_fn: Optional[Callable] = None,
|
||||
purge_deleted_fn: Optional[Callable] = None,
|
||||
) -> None:
|
||||
"""
|
||||
Run post-operations after a batch close (dashboard update + purge).
|
||||
Run post-operations after a batch close (central update + purge).
|
||||
|
||||
Args:
|
||||
branch_path: Path to branch directory
|
||||
push_dashboard_fn: Optional push_dashboard_update callable
|
||||
update_central_fn: Optional update_central callable
|
||||
purge_deleted_fn: Optional purge_deleted_folder callable
|
||||
"""
|
||||
if push_dashboard_fn:
|
||||
try:
|
||||
push_dashboard_fn(branch_path)
|
||||
except Exception as e:
|
||||
logger.warning("[close] push_dashboard_fn failed for %s: %s", branch_path, e)
|
||||
if update_central_fn:
|
||||
try:
|
||||
update_central_fn()
|
||||
|
||||
@@ -14,6 +14,8 @@ Solves the BRANCH DETECTION FAILED problem when external projects call drone
|
||||
— contacts lookup works even when CWD-walking cannot identify the caller.
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
from datetime import datetime
|
||||
from typing import Dict, Optional
|
||||
|
||||
@@ -21,6 +23,13 @@ from aipass.prax.apps.modules.logger import system_logger as logger
|
||||
from aipass.ai_mail.apps.handlers.json import json_handler
|
||||
from aipass.ai_mail.apps.handlers.paths import find_repo_root
|
||||
|
||||
if sys.platform == "win32":
|
||||
os.environ.setdefault("PYTHONUTF8", "1")
|
||||
for _stream in (sys.stdout, sys.stderr):
|
||||
_reconfigure = getattr(_stream, "reconfigure", None)
|
||||
if _reconfigure is not None:
|
||||
_reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
CONTACTS_FILE = find_repo_root() / "src/aipass/ai_mail/.ai_mail.local/contacts.json"
|
||||
|
||||
|
||||
|
||||
@@ -14,6 +14,8 @@ Independent handler - no module dependencies.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from datetime import datetime
|
||||
from typing import Dict, Optional
|
||||
@@ -21,6 +23,13 @@ from typing import Dict, Optional
|
||||
from aipass.prax.apps.modules.logger import system_logger as logger
|
||||
from aipass.ai_mail.apps.handlers.json import json_handler
|
||||
|
||||
if sys.platform == "win32":
|
||||
os.environ.setdefault("PYTHONUTF8", "1")
|
||||
for _stream in (sys.stdout, sys.stderr):
|
||||
_reconfigure = getattr(_stream, "reconfigure", None)
|
||||
if _reconfigure is not None:
|
||||
_reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
# Lazy imports
|
||||
_append_footer = None
|
||||
|
||||
|
||||
@@ -15,6 +15,7 @@ Independent handler - no module dependencies.
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from typing import Dict, Tuple, List, Optional, Callable
|
||||
@@ -24,6 +25,13 @@ from aipass.ai_mail.apps.handlers.json import json_handler
|
||||
from aipass.ai_mail.apps.handlers.paths import find_repo_root
|
||||
from aipass.ai_mail.apps.handlers.registry.read import get_all_branches
|
||||
|
||||
if sys.platform == "win32":
|
||||
os.environ.setdefault("PYTHONUTF8", "1")
|
||||
for _stream in (sys.stdout, sys.stderr):
|
||||
_reconfigure = getattr(_stream, "reconfigure", None)
|
||||
if _reconfigure is not None:
|
||||
_reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
|
||||
_REPO_ROOT = find_repo_root()
|
||||
|
||||
@@ -165,7 +173,7 @@ def _is_private_branch_email(email: str) -> bool:
|
||||
email address is registered to a private (isolated) branch.
|
||||
|
||||
Args:
|
||||
email: Email address to check (e.g., "@patrick_private")
|
||||
email: Email address to check (e.g., "@private_branch")
|
||||
|
||||
Returns:
|
||||
True if email belongs to a private branch, False otherwise
|
||||
|
||||
@@ -93,25 +93,18 @@ def on_email_delivered(
|
||||
new_count: int,
|
||||
opened_count: int,
|
||||
total: int,
|
||||
push_dashboard_fn: Optional[Callable] = None,
|
||||
update_central_fn: Optional[Callable] = None,
|
||||
) -> None:
|
||||
"""
|
||||
Post-delivery callback: update dashboard and central.
|
||||
Post-delivery callback: update central.
|
||||
|
||||
Args:
|
||||
branch_path: Path to the branch that received email
|
||||
new_count: Number of new (unread) messages
|
||||
opened_count: Number of opened messages
|
||||
total: Total message count
|
||||
push_dashboard_fn: Callable for push_dashboard_update
|
||||
update_central_fn: Callable for update_central
|
||||
"""
|
||||
if push_dashboard_fn:
|
||||
try:
|
||||
push_dashboard_fn(branch_path)
|
||||
except Exception as e:
|
||||
logger.warning("[error_dispatch] dashboard update failed for %s: %s", branch_path, e)
|
||||
if update_central_fn:
|
||||
try:
|
||||
update_central_fn()
|
||||
|
||||
@@ -22,8 +22,7 @@ STANDARD_FOOTER = """
|
||||
⚠️ TASK CHECKLIST (before marking complete):
|
||||
□ SEEDGO CHECK → drone @seedgo audit @branch (80%+)
|
||||
□ UPDATE MEMORIES → Your .trinity/local.json records this work
|
||||
□ UPDATE STATUS → Your STATUS.local.md reflects current state
|
||||
□ CLOSE FPLAN → drone @flow close <plan_id>
|
||||
□ CLOSE YOUR PLAN → drone @flow close <your_plan_id> — this task's plan only, never the master/parent
|
||||
□ EMAIL SENDER → drone @ai_mail email @<sender> "Subject" "Summary"
|
||||
|
||||
Memories = Presence. No update = No learning.
|
||||
|
||||
@@ -14,12 +14,21 @@ Independent handler - no module dependencies.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
from typing import Dict, Optional
|
||||
|
||||
from aipass.prax.apps.modules.logger import system_logger as logger
|
||||
from aipass.ai_mail.apps.handlers.json import json_handler
|
||||
from aipass.ai_mail.apps.handlers.paths import find_repo_root
|
||||
|
||||
if sys.platform == "win32":
|
||||
os.environ.setdefault("PYTHONUTF8", "1")
|
||||
for _stream in (sys.stdout, sys.stderr):
|
||||
_reconfigure = getattr(_stream, "reconfigure", None)
|
||||
if _reconfigure is not None:
|
||||
_reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
|
||||
REGISTRY_PATH = find_repo_root() / "AIPASS_REGISTRY.json"
|
||||
|
||||
@@ -164,10 +173,10 @@ if __name__ == "__main__":
|
||||
console.print(" - format_email_list_item(index, email_data, show_unread) -> str")
|
||||
console.print()
|
||||
console.print("HANDLER CHARACTERISTICS:")
|
||||
console.print(" ✓ Independent - no module dependencies")
|
||||
console.print(" ✓ Can import Prax (service provider)")
|
||||
console.print(" ✓ Pure business logic")
|
||||
console.print(" ✗ CANNOT import parent modules")
|
||||
console.print(" [green]+[/green] Independent - no module dependencies")
|
||||
console.print(" [green]+[/green] Can import Prax (service provider)")
|
||||
console.print(" [green]+[/green] Pure business logic")
|
||||
console.print(" [dim]-[/dim] CANNOT import parent modules")
|
||||
console.print()
|
||||
console.print("USAGE FROM MODULES:")
|
||||
console.print(" from ai_mail.apps.handlers.email.format import format_email_preview")
|
||||
|
||||
@@ -16,6 +16,8 @@ v3.0.0: Now uses deleted/ directory with individual JSON files (like sent/).
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from datetime import datetime
|
||||
from typing import Dict, Tuple, Optional, Any
|
||||
@@ -23,6 +25,13 @@ from typing import Dict, Tuple, Optional, Any
|
||||
from aipass.prax.apps.modules.logger import system_logger as logger
|
||||
from aipass.ai_mail.apps.handlers.json import json_handler
|
||||
|
||||
if sys.platform == "win32":
|
||||
os.environ.setdefault("PYTHONUTF8", "1")
|
||||
for _stream in (sys.stdout, sys.stderr):
|
||||
_reconfigure = getattr(_stream, "reconfigure", None)
|
||||
if _reconfigure is not None:
|
||||
_reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
|
||||
# Lazy import for inbox file lock
|
||||
_inbox_lock = None
|
||||
@@ -38,13 +47,6 @@ def _get_inbox_lock():
|
||||
return _inbox_lock
|
||||
|
||||
|
||||
def _get_push_dashboard_update() -> Any:
|
||||
"""Lazy import push_dashboard_update from dashboard_sync."""
|
||||
from aipass.ai_mail.apps.handlers.email.dashboard_sync import push_dashboard_update
|
||||
|
||||
return push_dashboard_update
|
||||
|
||||
|
||||
def _get_update_central() -> Any:
|
||||
"""Lazy import update_central."""
|
||||
from aipass.ai_mail.apps.handlers.central_writer import update_central
|
||||
@@ -191,13 +193,7 @@ def mark_all_read_and_archive(branch_path: Path) -> Tuple[bool, str, int]:
|
||||
|
||||
|
||||
def _update_dashboard(branch_path: Path, new: int, opened: int, total: int) -> None:
|
||||
"""Update dashboard ai_mail section with enriched data via write-through API."""
|
||||
try:
|
||||
_get_push_dashboard_update()(branch_path)
|
||||
except Exception as e:
|
||||
logger.warning("[cleanup] dashboard update failed for %s: %s", branch_path, e)
|
||||
|
||||
# Update central after any inbox changes
|
||||
"""Update central stats after inbox changes."""
|
||||
try:
|
||||
_get_update_central()()
|
||||
except Exception as e:
|
||||
|
||||
@@ -14,12 +14,21 @@ Independent handler - no module dependencies.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Dict
|
||||
|
||||
from aipass.prax.apps.modules.logger import system_logger as logger
|
||||
from aipass.ai_mail.apps.handlers.json import json_handler
|
||||
|
||||
if sys.platform == "win32":
|
||||
os.environ.setdefault("PYTHONUTF8", "1")
|
||||
for _stream in (sys.stdout, sys.stderr):
|
||||
_reconfigure = getattr(_stream, "reconfigure", None)
|
||||
if _reconfigure is not None:
|
||||
_reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
# Lazy import for inbox file lock
|
||||
_inbox_lock = None
|
||||
|
||||
@@ -125,10 +134,10 @@ if __name__ == "__main__":
|
||||
console.print(" - load_inbox(inbox_file) -> Dict")
|
||||
console.print()
|
||||
console.print("HANDLER CHARACTERISTICS:")
|
||||
console.print(" ✓ Independent - no module dependencies")
|
||||
console.print(" ✓ Can import Prax (service provider)")
|
||||
console.print(" ✓ Pure business logic")
|
||||
console.print(" ✗ CANNOT import parent modules")
|
||||
console.print(" [green]+[/green] Independent - no module dependencies")
|
||||
console.print(" [green]+[/green] Can import Prax (service provider)")
|
||||
console.print(" [green]+[/green] Pure business logic")
|
||||
console.print(" [dim]-[/dim] CANNOT import parent modules")
|
||||
console.print()
|
||||
console.print("USAGE FROM MODULES:")
|
||||
console.print(" from aipass.ai_mail.apps.handlers.email.inbox_ops import load_inbox")
|
||||
|
||||
@@ -31,6 +31,13 @@ from aipass.prax.apps.modules.logger import system_logger as logger
|
||||
from aipass.ai_mail.apps.handlers.json import json_handler
|
||||
from aipass.ai_mail.apps.handlers.paths import find_repo_root
|
||||
|
||||
if sys.platform == "win32":
|
||||
os.environ.setdefault("PYTHONUTF8", "1")
|
||||
for _stream in (sys.stdout, sys.stderr):
|
||||
_reconfigure = getattr(_stream, "reconfigure", None)
|
||||
if _reconfigure is not None:
|
||||
_reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
# Purge configuration
|
||||
MAX_EMAILS = 10
|
||||
|
||||
|
||||
@@ -13,6 +13,8 @@ Handles replying to emails and auto-closing the original.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from typing import Dict, Tuple, Optional
|
||||
@@ -22,6 +24,13 @@ from aipass.prax.apps.modules.logger import system_logger as logger
|
||||
from aipass.ai_mail.apps.handlers.json import json_handler
|
||||
from aipass.ai_mail.apps.handlers.email.delivery import deliver_to_inbox_file
|
||||
|
||||
if sys.platform == "win32":
|
||||
os.environ.setdefault("PYTHONUTF8", "1")
|
||||
for _stream in (sys.stdout, sys.stderr):
|
||||
_reconfigure = getattr(_stream, "reconfigure", None)
|
||||
if _reconfigure is not None:
|
||||
_reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
# Services imported in __main__ only (handlers should not display)
|
||||
|
||||
|
||||
|
||||
@@ -103,7 +103,7 @@ def parse_send_args(args: List[str]) -> Dict[str, Any]:
|
||||
if recipients and len(rest) >= 2:
|
||||
mode = "direct"
|
||||
subject = rest[0]
|
||||
message = rest[1]
|
||||
message = " ".join(rest[1:])
|
||||
elif not recipients and not rest:
|
||||
mode = "interactive"
|
||||
subject = None
|
||||
|
||||
@@ -13,10 +13,19 @@ Provides repo root discovery used across all handler files.
|
||||
Consolidated from 8 identical copies per DPLAN-0036 audit.
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from aipass.ai_mail.apps.handlers.json import json_handler
|
||||
|
||||
if sys.platform == "win32":
|
||||
os.environ.setdefault("PYTHONUTF8", "1")
|
||||
for _stream in (sys.stdout, sys.stderr):
|
||||
_reconfigure = getattr(_stream, "reconfigure", None)
|
||||
if _reconfigure is not None:
|
||||
_reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
|
||||
def find_repo_root() -> Path:
|
||||
"""Walk up from this file to find AIPASS_REGISTRY.json (repo root)."""
|
||||
|
||||
@@ -21,6 +21,8 @@ Handler Independence:
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import List, Dict, Optional
|
||||
|
||||
@@ -28,6 +30,13 @@ from aipass.prax.apps.modules.logger import system_logger as logger
|
||||
from aipass.ai_mail.apps.handlers.json import json_handler
|
||||
from aipass.ai_mail.apps.handlers.paths import find_repo_root
|
||||
|
||||
if sys.platform == "win32":
|
||||
os.environ.setdefault("PYTHONUTF8", "1")
|
||||
for _stream in (sys.stdout, sys.stderr):
|
||||
_reconfigure = getattr(_stream, "reconfigure", None)
|
||||
if _reconfigure is not None:
|
||||
_reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
|
||||
# Constants
|
||||
MODULE_NAME = "registry.read"
|
||||
|
||||
@@ -17,6 +17,7 @@ Walks up directory tree to find branch root (has .trinity/passport.json).
|
||||
# IMPORTS
|
||||
# =============================================
|
||||
import os
|
||||
import sys
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Dict, Optional
|
||||
@@ -25,6 +26,13 @@ from aipass.prax.apps.modules.logger import system_logger as logger
|
||||
from aipass.ai_mail.apps.handlers.json import json_handler
|
||||
from aipass.ai_mail.apps.handlers.paths import find_repo_root
|
||||
|
||||
if sys.platform == "win32":
|
||||
os.environ.setdefault("PYTHONUTF8", "1")
|
||||
for _stream in (sys.stdout, sys.stderr):
|
||||
_reconfigure = getattr(_stream, "reconfigure", None)
|
||||
if _reconfigure is not None:
|
||||
_reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
# =============================================
|
||||
# CONSTANTS
|
||||
# =============================================
|
||||
@@ -297,10 +305,10 @@ if __name__ == "__main__":
|
||||
console.print(" - get_branch_info_from_registry(branch_path) -> Optional[Dict]")
|
||||
console.print()
|
||||
console.print("HANDLER CHARACTERISTICS:")
|
||||
console.print(" ✓ Independent - no module dependencies")
|
||||
console.print(" ✓ Can import Prax (service provider)")
|
||||
console.print(" ✓ Pure business logic")
|
||||
console.print(" ✗ CANNOT import parent modules")
|
||||
console.print(" [green]+[/green] Independent - no module dependencies")
|
||||
console.print(" [green]+[/green] Can import Prax (service provider)")
|
||||
console.print(" [green]+[/green] Pure business logic")
|
||||
console.print(" [dim]-[/dim] CANNOT import parent modules")
|
||||
console.print()
|
||||
console.print("DETECTION FLOW:")
|
||||
console.print(" 1. Get current working directory (PWD)")
|
||||
|
||||
@@ -14,7 +14,6 @@ Delegates all business logic to handlers.
|
||||
"""
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import List
|
||||
@@ -24,6 +23,13 @@ from aipass.cli.apps.modules import console, error
|
||||
from aipass.ai_mail.apps.handlers.json import json_handler
|
||||
from aipass.ai_mail.apps.handlers.dispatch.status import load_dispatch_log, check_pid_status, calculate_age
|
||||
|
||||
if sys.platform == "win32":
|
||||
os.environ.setdefault("PYTHONUTF8", "1")
|
||||
for _stream in (sys.stdout, sys.stderr):
|
||||
_reconfigure = getattr(_stream, "reconfigure", None)
|
||||
if _reconfigure is not None:
|
||||
_reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
|
||||
def print_help() -> None:
|
||||
"""Print help for dispatch commands."""
|
||||
@@ -41,7 +47,6 @@ DISPATCH (send + wake):
|
||||
drone @ai_mail dispatch @branch "Subject" "Body" --fresh # Send + fresh wake
|
||||
drone @ai_mail dispatch @branch "Subject" "Body" --model opus # Send + wake with Opus
|
||||
drone @ai_mail dispatch @branch "Subject" "Body" --no-memory-save
|
||||
drone @ai_mail dispatch @branch "Subject" "Body" --no-watchdog # Skip auto-watchdog
|
||||
|
||||
WAKE ONLY:
|
||||
drone @ai_mail dispatch wake @branch # Wake with default inbox check
|
||||
@@ -219,7 +224,6 @@ def _orchestrate_dispatch_send(args: List[str]) -> bool:
|
||||
# Parse flags
|
||||
use_fresh = False
|
||||
no_memory_save = False
|
||||
no_watchdog = False
|
||||
from_branch = None
|
||||
use_model = None
|
||||
filtered = []
|
||||
@@ -234,7 +238,6 @@ def _orchestrate_dispatch_send(args: List[str]) -> bool:
|
||||
i += 1
|
||||
continue
|
||||
if args[i] == "--no-watchdog":
|
||||
no_watchdog = True
|
||||
i += 1
|
||||
continue
|
||||
if args[i] == "--from" and i + 1 < len(args):
|
||||
@@ -267,9 +270,9 @@ def _orchestrate_dispatch_send(args: List[str]) -> bool:
|
||||
from aipass.ai_mail.apps.handlers.email.delivery import deliver_email_to_branch
|
||||
from aipass.ai_mail.apps.handlers.email.header import prepend_dispatch_header
|
||||
from aipass.ai_mail.apps.handlers.email.error_dispatch import dispatch_send_error, on_email_delivered
|
||||
from aipass.ai_mail.apps.handlers.email.dashboard_sync import push_dashboard_update
|
||||
from aipass.ai_mail.apps.handlers.users.user import get_current_user
|
||||
from aipass.ai_mail.apps.handlers.registry.read import get_branch_by_email
|
||||
from aipass.ai_mail.apps.handlers.paths import find_repo_root
|
||||
|
||||
try:
|
||||
from aipass.ai_mail.apps.handlers.central_writer import update_central
|
||||
@@ -278,7 +281,7 @@ def _orchestrate_dispatch_send(args: List[str]) -> bool:
|
||||
update_central = None
|
||||
|
||||
_ai_mail_dir = Path(__file__).resolve().parents[2]
|
||||
_repo_root = _ai_mail_dir.parents[2]
|
||||
_repo_root = find_repo_root()
|
||||
|
||||
def _delivery_callback(branch_path, new_count, opened_count, total):
|
||||
on_email_delivered(
|
||||
@@ -286,7 +289,6 @@ def _orchestrate_dispatch_send(args: List[str]) -> bool:
|
||||
new_count,
|
||||
opened_count,
|
||||
total,
|
||||
push_dashboard_fn=push_dashboard_update,
|
||||
update_central_fn=update_central,
|
||||
)
|
||||
|
||||
@@ -343,57 +345,12 @@ def _orchestrate_dispatch_send(args: List[str]) -> bool:
|
||||
if not wake_ok:
|
||||
logger.warning("[dispatch] Wake failed for %s — email was sent", target)
|
||||
error(f"Email sent but wake failed — retry: drone @ai_mail dispatch wake {target}")
|
||||
elif not no_watchdog:
|
||||
_spawn_watchdog(target)
|
||||
else:
|
||||
console.print(f"[dim]Wake-back enabled — sender will be woken when {target} completes (if available)[/dim]")
|
||||
|
||||
return True
|
||||
|
||||
|
||||
def _spawn_watchdog(target: str) -> None:
|
||||
"""Auto-spawn devpulse watchdog as a detached background process."""
|
||||
from aipass.ai_mail.apps.handlers.registry.read import get_branch_by_email
|
||||
|
||||
devpulse_info = get_branch_by_email("@devpulse")
|
||||
if not devpulse_info:
|
||||
logger.warning("[dispatch] Cannot spawn watchdog — @devpulse not in registry")
|
||||
return
|
||||
|
||||
_ai_mail_dir = Path(__file__).resolve().parents[2]
|
||||
_repo_root = _ai_mail_dir.parents[2]
|
||||
devpulse_path = devpulse_info.get("path", "")
|
||||
if not devpulse_path:
|
||||
logger.warning("[dispatch] Cannot spawn watchdog — @devpulse has no path")
|
||||
return
|
||||
|
||||
devpulse_dir = Path(devpulse_path)
|
||||
if not devpulse_dir.is_absolute():
|
||||
devpulse_dir = _repo_root / devpulse_dir
|
||||
|
||||
if not devpulse_dir.is_dir():
|
||||
logger.warning("[dispatch] Cannot spawn watchdog — devpulse dir not found: %s", devpulse_dir)
|
||||
return
|
||||
|
||||
cmd = ["drone", "@devpulse", "watchdog", "agent", target]
|
||||
|
||||
spawn_env = os.environ.copy()
|
||||
local_bin = str(Path.home() / ".local" / "bin")
|
||||
if local_bin not in spawn_env.get("PATH", ""):
|
||||
spawn_env["PATH"] = local_bin + ":" + spawn_env.get("PATH", "")
|
||||
|
||||
try:
|
||||
subprocess.Popen(
|
||||
cmd,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
start_new_session=True,
|
||||
cwd=str(devpulse_dir),
|
||||
env=spawn_env,
|
||||
)
|
||||
console.print(f"[green]Watchdog armed for {target}[/green]")
|
||||
except Exception as e:
|
||||
logger.warning("[dispatch] Watchdog spawn failed for %s: %s", target, e)
|
||||
|
||||
|
||||
def _orchestrate_daemon() -> bool:
|
||||
"""Orchestrate daemon startup."""
|
||||
logger.info("[dispatch] Starting dispatch daemon")
|
||||
@@ -408,23 +365,26 @@ def _orchestrate_daemon() -> bool:
|
||||
def print_introspection():
|
||||
"""Display module introspection info."""
|
||||
console.print()
|
||||
console.print("dispatch Module")
|
||||
console.print("[bold cyan]dispatch Module[/bold cyan]")
|
||||
console.print(
|
||||
"Orchestrates dispatch commands: combined send+wake, status tracking, daemon management, and manual wake."
|
||||
"[dim]Orchestrates dispatch commands: combined send+wake,"
|
||||
" status tracking, daemon management, and manual wake.[/dim]"
|
||||
)
|
||||
console.print()
|
||||
console.print("Connected Handlers:")
|
||||
console.print(" handlers/dispatch/")
|
||||
console.print(" - status.py (load_dispatch_log — load dispatch log entries)")
|
||||
console.print(" - status.py (check_pid_status — check if a spawned process is still running)")
|
||||
console.print(" - status.py (calculate_age — calculate age string from timestamp)")
|
||||
console.print(" - wake.py (wake_branch — manually wake a branch by spawning an agent)")
|
||||
console.print(" - daemon.py (run_daemon — start the continuous dispatch daemon)")
|
||||
console.print(" handlers/email/ (used by combined dispatch)")
|
||||
console.print(" - send.py (resolve_sender_info, send_to_single — send email pipeline)")
|
||||
console.print(" - create.py (create_email_file, load_email_file — email file creation)")
|
||||
console.print(" - delivery.py (deliver_email_to_branch — inbox delivery)")
|
||||
console.print(" - header.py (prepend_dispatch_header — dispatch header injection)")
|
||||
console.print("[yellow]Connected Handlers:[/yellow]")
|
||||
console.print(" [cyan]handlers/dispatch/[/cyan]")
|
||||
console.print(" - [cyan]status.py[/cyan] [dim](load_dispatch_log — load dispatch log entries)[/dim]")
|
||||
console.print(
|
||||
" - [cyan]status.py[/cyan] [dim](check_pid_status — check if a spawned process is still running)[/dim]"
|
||||
)
|
||||
console.print(" - [cyan]status.py[/cyan] [dim](calculate_age — calculate age string from timestamp)[/dim]")
|
||||
console.print(" - [cyan]wake.py[/cyan] [dim](wake_branch — manually wake a branch by spawning an agent)[/dim]")
|
||||
console.print(" - [cyan]daemon.py[/cyan] [dim](run_daemon — start the continuous dispatch daemon)[/dim]")
|
||||
console.print(" [cyan]handlers/email/[/cyan] [dim](used by combined dispatch)[/dim]")
|
||||
console.print(" - [cyan]send.py[/cyan] [dim](resolve_sender_info, send_to_single — send email pipeline)[/dim]")
|
||||
console.print(" - [cyan]create.py[/cyan] [dim](create_email_file, load_email_file — email file creation)[/dim]")
|
||||
console.print(" - [cyan]delivery.py[/cyan] [dim](deliver_email_to_branch — inbox delivery)[/dim]")
|
||||
console.print(" - [cyan]header.py[/cyan] [dim](prepend_dispatch_header — dispatch header injection)[/dim]")
|
||||
console.print()
|
||||
|
||||
|
||||
|
||||
@@ -19,19 +19,13 @@ Module Pattern:
|
||||
- NO business logic in this file
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import List
|
||||
|
||||
# Infrastructure
|
||||
_AI_MAIL_DIR = Path(__file__).resolve().parents[2]
|
||||
_REPO_ROOT = _AI_MAIL_DIR.parents[2]
|
||||
|
||||
from aipass.prax import logger
|
||||
from aipass.cli.apps.modules import console, error
|
||||
|
||||
# Handlers - business logic providers
|
||||
from aipass.ai_mail.apps.handlers.email.dashboard_sync import push_dashboard_update
|
||||
from aipass.ai_mail.apps.handlers.email.create import load_email_file
|
||||
from aipass.ai_mail.apps.handlers.email.format import format_email_list_item, format_email_header
|
||||
from aipass.ai_mail.apps.handlers.email.inbox_ops import load_inbox
|
||||
@@ -46,8 +40,19 @@ from aipass.ai_mail.apps.handlers.registry.read import get_all_branches, get_bra
|
||||
from aipass.ai_mail.apps.handlers.json import json_handler
|
||||
from aipass.ai_mail.apps.handlers.email.close_ops import batch_close, batch_close_post_ops
|
||||
from aipass.ai_mail.apps.handlers.email.inbox_resolve import resolve_inbox_target
|
||||
from aipass.ai_mail.apps.handlers.paths import find_repo_root
|
||||
from aipass.ai_mail.apps.modules.email_send import handle_send
|
||||
|
||||
if sys.platform == "win32":
|
||||
os.environ.setdefault("PYTHONUTF8", "1")
|
||||
for _stream in (sys.stdout, sys.stderr):
|
||||
_reconfigure = getattr(_stream, "reconfigure", None)
|
||||
if _reconfigure is not None:
|
||||
_reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
_AI_MAIL_DIR = Path(__file__).resolve().parents[2]
|
||||
_REPO_ROOT = find_repo_root()
|
||||
|
||||
try:
|
||||
from aipass.ai_mail.apps.handlers.central_writer import update_central
|
||||
except ImportError as e:
|
||||
@@ -255,7 +260,7 @@ def handle_close(args: List[str]) -> bool:
|
||||
except ImportError as e:
|
||||
logger.warning("[email] purge import unavailable: %s", e)
|
||||
run_purge = None
|
||||
batch_close_post_ops(branch_path, push_dashboard_update, update_central, run_purge)
|
||||
batch_close_post_ops(branch_path, update_central, run_purge)
|
||||
console.print(f"\nClosed {closed}, failed {failed}")
|
||||
return True
|
||||
except Exception as e:
|
||||
@@ -277,7 +282,8 @@ def handle_reply(args: List[str]) -> bool:
|
||||
if not original:
|
||||
error(f"Message not found: {args[0]}")
|
||||
return True
|
||||
success, message, reply_id = send_reply(branch_path, original, args[1])
|
||||
reply_message = " ".join(args[1:])
|
||||
success, message, reply_id = send_reply(branch_path, original, reply_message)
|
||||
if success:
|
||||
console.print(f"[green]{message}[/green]")
|
||||
else:
|
||||
@@ -386,7 +392,6 @@ def print_introspection():
|
||||
console.print(" - reply.py (get_email_by_id — retrieve email by message ID)")
|
||||
console.print(" - reply.py (send_reply — send reply to an email)")
|
||||
console.print(" - header.py (prepend_dispatch_header — prepend dispatch header to message)")
|
||||
console.print(" - dashboard_sync.py (push_dashboard_update — push email stats to dashboard)")
|
||||
console.print(" - error_dispatch.py (dispatch_send_error — handle and report send errors)")
|
||||
console.print(" - error_dispatch.py (on_email_delivered — post-delivery callback handler)")
|
||||
console.print(" handlers/users/")
|
||||
|
||||
@@ -14,17 +14,15 @@ broadcast, and dispatch trigger. Extracted from email.py to keep modules
|
||||
under the size threshold.
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import List
|
||||
|
||||
_AI_MAIL_DIR = Path(__file__).resolve().parents[2]
|
||||
_REPO_ROOT = _AI_MAIL_DIR.parents[2]
|
||||
|
||||
from aipass.prax import logger
|
||||
from aipass.cli.apps.modules import console, error
|
||||
from aipass.trigger.apps.modules.core import trigger
|
||||
|
||||
from aipass.ai_mail.apps.handlers.email.dashboard_sync import push_dashboard_update
|
||||
from aipass.ai_mail.apps.handlers.email.delivery import deliver_email_to_branch
|
||||
from aipass.ai_mail.apps.handlers.email.create import create_email_file, load_email_file
|
||||
from aipass.ai_mail.apps.handlers.email.header import prepend_dispatch_header
|
||||
@@ -39,6 +37,17 @@ from aipass.ai_mail.apps.handlers.email.send import (
|
||||
)
|
||||
from aipass.ai_mail.apps.handlers.email.error_dispatch import dispatch_send_error, on_email_delivered
|
||||
from aipass.ai_mail.apps.handlers.email.send_args import parse_send_args, resolve_dispatch_target
|
||||
from aipass.ai_mail.apps.handlers.paths import find_repo_root
|
||||
|
||||
if sys.platform == "win32":
|
||||
os.environ.setdefault("PYTHONUTF8", "1")
|
||||
for _stream in (sys.stdout, sys.stderr):
|
||||
_reconfigure = getattr(_stream, "reconfigure", None)
|
||||
if _reconfigure is not None:
|
||||
_reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
_AI_MAIL_DIR = Path(__file__).resolve().parents[2]
|
||||
_REPO_ROOT = find_repo_root()
|
||||
|
||||
try:
|
||||
from aipass.ai_mail.apps.handlers.central_writer import update_central
|
||||
@@ -54,7 +63,6 @@ def _delivery_callback(branch_path, new_count, opened_count, total):
|
||||
new_count,
|
||||
opened_count,
|
||||
total,
|
||||
push_dashboard_fn=push_dashboard_update,
|
||||
update_central_fn=update_central,
|
||||
)
|
||||
|
||||
@@ -250,18 +258,18 @@ def _send_broadcast(subject, message, user_info, auto_execute, no_memory_save, r
|
||||
|
||||
def print_introspection():
|
||||
"""Print module introspection for seedgo compliance."""
|
||||
console.print("\n" + "=" * 70)
|
||||
console.print("EMAIL SEND ORCHESTRATION")
|
||||
console.print("=" * 70)
|
||||
console.print("\nFunctions provided:")
|
||||
console.print(" - handle_send(args) -> bool")
|
||||
console.print(" - _send_direct(...) -> bool")
|
||||
console.print(" - _send_interactive() -> bool")
|
||||
console.print(" - _send_broadcast(...) -> bool")
|
||||
console.print(" - _fire_dispatch_trigger(to_branch, subject) -> None")
|
||||
console.print(" - _delivery_callback(branch_path, new_count, opened_count, total)")
|
||||
console.print()
|
||||
console.print("=" * 70 + "\n")
|
||||
console.print("[bold cyan]email_send Module[/bold cyan]")
|
||||
console.print("[dim]Send orchestration — direct, interactive, and broadcast email delivery.[/dim]")
|
||||
console.print()
|
||||
console.print("[yellow]Functions provided:[/yellow]")
|
||||
console.print(" - [cyan]handle_send[/cyan][dim](args) -> bool[/dim]")
|
||||
console.print(" - [cyan]_send_direct[/cyan][dim](...) -> bool[/dim]")
|
||||
console.print(" - [cyan]_send_interactive[/cyan][dim]() -> bool[/dim]")
|
||||
console.print(" - [cyan]_send_broadcast[/cyan][dim](...) -> bool[/dim]")
|
||||
console.print(" - [cyan]_fire_dispatch_trigger[/cyan][dim](to_branch, subject) -> None[/dim]")
|
||||
console.print(" - [cyan]_delivery_callback[/cyan][dim](branch_path, new_count, opened_count, total)[/dim]")
|
||||
console.print()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
# S84: Multi-line Reply Body Truncation — Root Cause & Fix
|
||||
|
||||
## Bug
|
||||
|
||||
Reply and send commands silently truncate multi-line message bodies to the first argument.
|
||||
|
||||
**Reported:** @devpulse dispatch 7b6a70b9 (2026-06-08)
|
||||
**Evidence:** @hooks sent two replies with full multi-line bodies; both arrived in devpulse inbox as first line only (60 chars / 48 chars). @memory's reply arrived intact (951 chars).
|
||||
|
||||
## Root Cause
|
||||
|
||||
Two code paths only captured the second positional CLI argument as the message body, dropping everything after it:
|
||||
|
||||
1. **`email.py:handle_reply`** (line 280):
|
||||
```python
|
||||
send_reply(branch_path, original, args[1]) # args[2:] silently dropped
|
||||
```
|
||||
|
||||
2. **`send_args.py:parse_send_args`** (line 106):
|
||||
```python
|
||||
message = rest[1] # rest[2:] silently dropped
|
||||
```
|
||||
|
||||
When an agent's bash command produces multiple args from a message body (shell word-splitting on unquoted text, or subprocess argument handling), only the first segment survives. The rest is discarded with no warning.
|
||||
|
||||
The entire Python delivery pipeline (reply.py, delivery.py, create.py) handles multi-line strings correctly — the truncation happens at the CLI argument boundary.
|
||||
|
||||
## Why @memory Worked
|
||||
|
||||
@memory's reply body was a single properly-quoted argument that arrived as one `args[1]` entry. @hooks' body was split into multiple args (likely unquoted or shell-expanded), so only the first piece reached `send_reply()`.
|
||||
|
||||
## Fix
|
||||
|
||||
Both locations now join all remaining args:
|
||||
|
||||
1. **`email.py:handle_reply`**: `reply_message = " ".join(args[1:])`
|
||||
2. **`send_args.py:parse_send_args`**: `message = " ".join(rest[1:])`
|
||||
|
||||
Backwards-compatible: single-arg messages pass through unchanged. Multi-arg messages are reconstructed.
|
||||
|
||||
## Tests Added (6)
|
||||
|
||||
- `test_reply.py`: `test_send_reply_multiline_body_preserved` — multi-line body stored intact in delivery and sent copy
|
||||
- `test_email_module.py`: `TestHandleReplyMultiArg` — handle_reply joins split args; single arg unchanged
|
||||
- `test_send_helpers.py`: 3 tests — parse_send_args joins split message; single arg unchanged; embedded newlines preserved
|
||||
|
||||
718 tests pass (712 + 6 new).
|
||||
@@ -120,13 +120,11 @@ def test_batch_close_post_ops_all_fns_called(tmp_path: Path):
|
||||
branch_path = tmp_path / "branch"
|
||||
branch_path.mkdir()
|
||||
|
||||
push_fn = MagicMock()
|
||||
central_fn = MagicMock()
|
||||
purge_fn = MagicMock()
|
||||
|
||||
mod.batch_close_post_ops(branch_path, push_fn, central_fn, purge_fn)
|
||||
mod.batch_close_post_ops(branch_path, central_fn, purge_fn)
|
||||
|
||||
push_fn.assert_called_once_with(branch_path)
|
||||
central_fn.assert_called_once_with()
|
||||
purge_fn.assert_called_once_with(branch_path / ".ai_mail.local")
|
||||
|
||||
@@ -137,22 +135,7 @@ def test_batch_close_post_ops_none_fns(tmp_path: Path):
|
||||
branch_path.mkdir()
|
||||
|
||||
# Should not raise
|
||||
mod.batch_close_post_ops(branch_path, None, None, None)
|
||||
|
||||
|
||||
def test_batch_close_post_ops_push_exception_suppressed(tmp_path: Path):
|
||||
"""Exception in push_dashboard_fn is caught; other fns still called."""
|
||||
branch_path = tmp_path / "branch"
|
||||
branch_path.mkdir()
|
||||
|
||||
push_fn = MagicMock(side_effect=RuntimeError("push failed"))
|
||||
central_fn = MagicMock()
|
||||
purge_fn = MagicMock()
|
||||
|
||||
mod.batch_close_post_ops(branch_path, push_fn, central_fn, purge_fn)
|
||||
|
||||
central_fn.assert_called_once()
|
||||
purge_fn.assert_called_once()
|
||||
mod.batch_close_post_ops(branch_path, None, None)
|
||||
|
||||
|
||||
def test_batch_close_post_ops_central_exception_suppressed(tmp_path: Path):
|
||||
@@ -160,13 +143,11 @@ def test_batch_close_post_ops_central_exception_suppressed(tmp_path: Path):
|
||||
branch_path = tmp_path / "branch"
|
||||
branch_path.mkdir()
|
||||
|
||||
push_fn = MagicMock()
|
||||
central_fn = MagicMock(side_effect=RuntimeError("central failed"))
|
||||
purge_fn = MagicMock()
|
||||
|
||||
mod.batch_close_post_ops(branch_path, push_fn, central_fn, purge_fn)
|
||||
mod.batch_close_post_ops(branch_path, central_fn, purge_fn)
|
||||
|
||||
push_fn.assert_called_once()
|
||||
purge_fn.assert_called_once()
|
||||
|
||||
|
||||
@@ -175,13 +156,11 @@ def test_batch_close_post_ops_purge_exception_suppressed(tmp_path: Path):
|
||||
branch_path = tmp_path / "branch"
|
||||
branch_path.mkdir()
|
||||
|
||||
push_fn = MagicMock()
|
||||
central_fn = MagicMock()
|
||||
purge_fn = MagicMock(side_effect=RuntimeError("purge failed"))
|
||||
|
||||
mod.batch_close_post_ops(branch_path, push_fn, central_fn, purge_fn)
|
||||
mod.batch_close_post_ops(branch_path, central_fn, purge_fn)
|
||||
|
||||
push_fn.assert_called_once()
|
||||
central_fn.assert_called_once()
|
||||
|
||||
|
||||
@@ -192,6 +171,6 @@ def test_batch_close_post_ops_partial_fns(tmp_path: Path):
|
||||
|
||||
central_fn = MagicMock()
|
||||
|
||||
mod.batch_close_post_ops(branch_path, None, central_fn, None)
|
||||
mod.batch_close_post_ops(branch_path, central_fn, None)
|
||||
|
||||
central_fn.assert_called_once_with()
|
||||
|
||||
@@ -9,10 +9,11 @@
|
||||
"""Tests for dispatch daemon handler -- config loading, state management, inbox scanning."""
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import pytest
|
||||
from datetime import datetime, date, timedelta
|
||||
from unittest.mock import patch
|
||||
from unittest.mock import MagicMock, mock_open, patch
|
||||
|
||||
import aipass.ai_mail.apps.handlers.dispatch.daemon as daemon_mod
|
||||
from aipass.ai_mail.apps.handlers.dispatch.daemon import (
|
||||
@@ -25,6 +26,17 @@ from aipass.ai_mail.apps.handlers.dispatch.daemon import (
|
||||
get_registered_branches,
|
||||
check_inbox_for_dispatch,
|
||||
is_protected_branch,
|
||||
_handle_signal,
|
||||
_check_lock,
|
||||
_acquire_lock,
|
||||
_is_registered_sender,
|
||||
poll_cycle,
|
||||
_write_pid_file,
|
||||
_remove_pid_file,
|
||||
_read_session_type,
|
||||
_is_branch_occupied,
|
||||
spawn_agent,
|
||||
run_daemon,
|
||||
)
|
||||
|
||||
|
||||
@@ -764,26 +776,6 @@ def test_poll_cycle_absolute_path_unchanged(tmp_path, monkeypatch):
|
||||
assert spawned_paths[0] == branch_dir
|
||||
|
||||
|
||||
# ---- Additional imports for new tests --------------------------------
|
||||
|
||||
import os
|
||||
from unittest.mock import MagicMock, mock_open
|
||||
|
||||
from aipass.ai_mail.apps.handlers.dispatch.daemon import (
|
||||
_handle_signal,
|
||||
_check_lock,
|
||||
_acquire_lock,
|
||||
_is_registered_sender,
|
||||
poll_cycle,
|
||||
_write_pid_file,
|
||||
_remove_pid_file,
|
||||
_read_session_type,
|
||||
_is_branch_occupied,
|
||||
spawn_agent,
|
||||
run_daemon,
|
||||
)
|
||||
|
||||
|
||||
# ---- _handle_signal tests --------------------------------------
|
||||
|
||||
|
||||
@@ -814,7 +806,7 @@ def test_check_lock_alive_pid(tmp_path, monkeypatch):
|
||||
lock_data = {"pid": 99999, "timestamp": datetime.now().isoformat()}
|
||||
lock_file.write_text(json.dumps(lock_data), encoding="utf-8")
|
||||
|
||||
monkeypatch.setattr(os, "kill", lambda pid, sig: None)
|
||||
monkeypatch.setattr(daemon_mod, "_pid_alive", lambda pid: True)
|
||||
|
||||
result = _check_lock(tmp_path)
|
||||
|
||||
@@ -823,17 +815,14 @@ def test_check_lock_alive_pid(tmp_path, monkeypatch):
|
||||
|
||||
|
||||
def test_check_lock_dead_pid(tmp_path, monkeypatch):
|
||||
"""Lock with dead PID (ProcessLookupError) is cleaned up."""
|
||||
"""Lock with dead PID is cleaned up."""
|
||||
lock_dir = tmp_path / ".ai_mail.local"
|
||||
lock_dir.mkdir(parents=True)
|
||||
lock_file = lock_dir / ".dispatch.lock"
|
||||
lock_data = {"pid": 99999, "timestamp": datetime.now().isoformat()}
|
||||
lock_file.write_text(json.dumps(lock_data), encoding="utf-8")
|
||||
|
||||
def _raise_process_lookup(pid, sig):
|
||||
raise ProcessLookupError("No such process")
|
||||
|
||||
monkeypatch.setattr(os, "kill", _raise_process_lookup)
|
||||
monkeypatch.setattr(daemon_mod, "_pid_alive", lambda pid: False)
|
||||
|
||||
result = _check_lock(tmp_path)
|
||||
|
||||
@@ -849,10 +838,7 @@ def test_check_lock_permission_error(tmp_path, monkeypatch):
|
||||
lock_data = {"pid": 99999, "timestamp": datetime.now().isoformat()}
|
||||
lock_file.write_text(json.dumps(lock_data), encoding="utf-8")
|
||||
|
||||
def _raise_permission(pid, sig):
|
||||
raise PermissionError("Operation not permitted")
|
||||
|
||||
monkeypatch.setattr(os, "kill", _raise_permission)
|
||||
monkeypatch.setattr(daemon_mod, "_pid_alive", lambda pid: True)
|
||||
|
||||
result = _check_lock(tmp_path)
|
||||
|
||||
@@ -869,10 +855,7 @@ def test_check_lock_stale_over_10min_removed(tmp_path, monkeypatch):
|
||||
lock_data = {"pid": 99999, "timestamp": old_time}
|
||||
lock_file.write_text(json.dumps(lock_data), encoding="utf-8")
|
||||
|
||||
def _raise_process_lookup(pid, sig):
|
||||
raise ProcessLookupError("No such process")
|
||||
|
||||
monkeypatch.setattr(os, "kill", _raise_process_lookup)
|
||||
monkeypatch.setattr(daemon_mod, "_pid_alive", lambda pid: False)
|
||||
|
||||
result = _check_lock(tmp_path)
|
||||
|
||||
@@ -889,10 +872,7 @@ def test_check_lock_stale_under_10min_dead_pid_removed(tmp_path, monkeypatch):
|
||||
lock_data = {"pid": 99999, "timestamp": recent_time}
|
||||
lock_file.write_text(json.dumps(lock_data), encoding="utf-8")
|
||||
|
||||
def _raise_process_lookup(pid, sig):
|
||||
raise ProcessLookupError("No such process")
|
||||
|
||||
monkeypatch.setattr(os, "kill", _raise_process_lookup)
|
||||
monkeypatch.setattr(daemon_mod, "_pid_alive", lambda pid: False)
|
||||
|
||||
result = _check_lock(tmp_path)
|
||||
|
||||
@@ -1015,6 +995,7 @@ def test_write_pid_file_existing_dead_pid(tmp_path, monkeypatch):
|
||||
|
||||
def test_write_pid_file_existing_permission_error(tmp_path, monkeypatch):
|
||||
"""Existing PID file with PermissionError on kill returns False."""
|
||||
monkeypatch.setattr("sys.platform", "linux")
|
||||
pid_file = tmp_path / "daemon.pid"
|
||||
pid_file.write_text("888888", encoding="utf-8")
|
||||
monkeypatch.setattr(daemon_mod, "DAEMON_PID_FILE", pid_file)
|
||||
|
||||
@@ -47,7 +47,6 @@ _H_CREATE = "aipass.ai_mail.apps.handlers.email.create"
|
||||
_H_DELIVERY = "aipass.ai_mail.apps.handlers.email.delivery"
|
||||
_H_HEADER = "aipass.ai_mail.apps.handlers.email.header"
|
||||
_H_ERR = "aipass.ai_mail.apps.handlers.email.error_dispatch"
|
||||
_H_DASH = "aipass.ai_mail.apps.handlers.email.dashboard_sync"
|
||||
_H_USERS = "aipass.ai_mail.apps.handlers.users.user"
|
||||
_H_REG = "aipass.ai_mail.apps.handlers.registry.read"
|
||||
_H_CENTRAL = "aipass.ai_mail.apps.handlers.central_writer"
|
||||
@@ -658,7 +657,6 @@ def _send_patches(overrides: dict | None = None) -> ExitStack:
|
||||
f"{_H_HEADER}.prepend_dispatch_header": MagicMock(return_value="[DISPATCH] Body"),
|
||||
f"{_H_SEND}.send_to_single": MagicMock(return_value=(True, None)),
|
||||
f"{_H_ERR}.on_email_delivered": MagicMock(),
|
||||
f"{_H_DASH}.push_dashboard_update": MagicMock(),
|
||||
f"{_H_USERS}.get_current_user": MagicMock(return_value={"name": "test"}),
|
||||
f"{_H_REG}.get_branch_by_email": MagicMock(return_value={"email": "@target"}),
|
||||
f"{_H_CENTRAL}.update_central": MagicMock(),
|
||||
@@ -971,168 +969,18 @@ class TestPrintIntrospection:
|
||||
|
||||
|
||||
# ===========================================================================
|
||||
# _spawn_watchdog
|
||||
# Wake-back messaging (TDPLAN-0012 — retired _spawn_watchdog)
|
||||
# ===========================================================================
|
||||
|
||||
|
||||
class TestSpawnWatchdog:
|
||||
"""Tests for _spawn_watchdog."""
|
||||
|
||||
def test_spawns_detached_subprocess(self, monkeypatch, tmp_path):
|
||||
"""Successful watchdog spawn calls Popen with correct args."""
|
||||
devpulse_dir = tmp_path / "src" / "aipass" / "devpulse"
|
||||
devpulse_dir.mkdir(parents=True)
|
||||
class TestWakeBackMessaging:
|
||||
"""Tests for honest wake-back messaging after watchdog retirement."""
|
||||
|
||||
def test_wake_back_message_on_successful_wake(self, monkeypatch):
|
||||
"""Successful send + wake prints wake-back enabled message."""
|
||||
printed: list[str] = []
|
||||
monkeypatch.setattr(f"{MOD}.console", _mock_console(printed))
|
||||
|
||||
popen_calls: list[dict] = []
|
||||
mock_popen = MagicMock()
|
||||
|
||||
def tracking_popen(cmd, **kwargs):
|
||||
"""Capture Popen arguments."""
|
||||
popen_calls.append({"cmd": cmd, **kwargs})
|
||||
return mock_popen
|
||||
|
||||
with (
|
||||
patch(
|
||||
f"{_H_REG}.get_branch_by_email",
|
||||
return_value={"email": "@devpulse", "path": str(devpulse_dir)},
|
||||
),
|
||||
patch(f"{MOD}.subprocess.Popen", side_effect=tracking_popen),
|
||||
):
|
||||
from aipass.ai_mail.apps.modules.dispatch import _spawn_watchdog
|
||||
|
||||
_spawn_watchdog("@flow")
|
||||
|
||||
assert len(popen_calls) == 1
|
||||
assert popen_calls[0]["cmd"] == ["drone", "@devpulse", "watchdog", "agent", "@flow"]
|
||||
assert popen_calls[0]["start_new_session"] is True
|
||||
assert popen_calls[0]["cwd"] == str(devpulse_dir)
|
||||
combined = " ".join(printed)
|
||||
assert "Watchdog armed for @flow" in combined
|
||||
|
||||
def test_devpulse_not_in_registry(self, monkeypatch):
|
||||
"""No spawn when @devpulse not found in registry."""
|
||||
printed: list[str] = []
|
||||
monkeypatch.setattr(f"{MOD}.console", _mock_console(printed))
|
||||
|
||||
with (
|
||||
patch(f"{_H_REG}.get_branch_by_email", return_value=None),
|
||||
patch(f"{MOD}.subprocess.Popen") as mock_popen,
|
||||
):
|
||||
from aipass.ai_mail.apps.modules.dispatch import _spawn_watchdog
|
||||
|
||||
_spawn_watchdog("@flow")
|
||||
|
||||
mock_popen.assert_not_called()
|
||||
|
||||
def test_devpulse_no_path(self, monkeypatch):
|
||||
"""No spawn when @devpulse has empty path."""
|
||||
printed: list[str] = []
|
||||
monkeypatch.setattr(f"{MOD}.console", _mock_console(printed))
|
||||
|
||||
with (
|
||||
patch(
|
||||
f"{_H_REG}.get_branch_by_email",
|
||||
return_value={"email": "@devpulse", "path": ""},
|
||||
),
|
||||
patch(f"{MOD}.subprocess.Popen") as mock_popen,
|
||||
):
|
||||
from aipass.ai_mail.apps.modules.dispatch import _spawn_watchdog
|
||||
|
||||
_spawn_watchdog("@flow")
|
||||
|
||||
mock_popen.assert_not_called()
|
||||
|
||||
def test_devpulse_dir_missing(self, monkeypatch, tmp_path):
|
||||
"""No spawn when devpulse directory doesn't exist."""
|
||||
printed: list[str] = []
|
||||
monkeypatch.setattr(f"{MOD}.console", _mock_console(printed))
|
||||
|
||||
with (
|
||||
patch(
|
||||
f"{_H_REG}.get_branch_by_email",
|
||||
return_value={"email": "@devpulse", "path": str(tmp_path / "nonexistent")},
|
||||
),
|
||||
patch(f"{MOD}.subprocess.Popen") as mock_popen,
|
||||
):
|
||||
from aipass.ai_mail.apps.modules.dispatch import _spawn_watchdog
|
||||
|
||||
_spawn_watchdog("@flow")
|
||||
|
||||
mock_popen.assert_not_called()
|
||||
|
||||
def test_popen_failure_warns_but_does_not_raise(self, monkeypatch, tmp_path):
|
||||
"""Popen failure logs warning but doesn't propagate."""
|
||||
devpulse_dir = tmp_path / "src" / "aipass" / "devpulse"
|
||||
devpulse_dir.mkdir(parents=True)
|
||||
|
||||
printed: list[str] = []
|
||||
monkeypatch.setattr(f"{MOD}.console", _mock_console(printed))
|
||||
|
||||
with (
|
||||
patch(
|
||||
f"{_H_REG}.get_branch_by_email",
|
||||
return_value={"email": "@devpulse", "path": str(devpulse_dir)},
|
||||
),
|
||||
patch(f"{MOD}.subprocess.Popen", side_effect=FileNotFoundError("drone not found")),
|
||||
):
|
||||
from aipass.ai_mail.apps.modules.dispatch import _spawn_watchdog
|
||||
|
||||
_spawn_watchdog("@flow")
|
||||
|
||||
# Should not raise — watchdog is optional
|
||||
|
||||
def test_relative_devpulse_path_resolved(self, monkeypatch, tmp_path):
|
||||
"""Relative path from registry is resolved against repo root."""
|
||||
printed: list[str] = []
|
||||
monkeypatch.setattr(f"{MOD}.console", _mock_console(printed))
|
||||
|
||||
popen_calls: list[dict] = []
|
||||
|
||||
def tracking_popen(cmd, **kwargs):
|
||||
"""Capture Popen arguments."""
|
||||
popen_calls.append({"cmd": cmd, **kwargs})
|
||||
return MagicMock()
|
||||
|
||||
from aipass.ai_mail.apps.modules import dispatch as dispatch_mod
|
||||
|
||||
real_repo_root = dispatch_mod.Path(__file__).resolve().parents[4]
|
||||
devpulse_dir = real_repo_root / "src" / "aipass" / "devpulse"
|
||||
|
||||
with (
|
||||
patch(
|
||||
f"{_H_REG}.get_branch_by_email",
|
||||
return_value={"email": "@devpulse", "path": "src/aipass/devpulse"},
|
||||
),
|
||||
patch(f"{MOD}.subprocess.Popen", side_effect=tracking_popen),
|
||||
):
|
||||
from aipass.ai_mail.apps.modules.dispatch import _spawn_watchdog
|
||||
|
||||
_spawn_watchdog("@flow")
|
||||
|
||||
if devpulse_dir.is_dir():
|
||||
assert len(popen_calls) == 1
|
||||
assert "devpulse" in popen_calls[0]["cwd"]
|
||||
else:
|
||||
assert len(popen_calls) == 0
|
||||
|
||||
|
||||
class TestDispatchSendWatchdogIntegration:
|
||||
"""Tests for watchdog integration in _orchestrate_dispatch_send."""
|
||||
|
||||
def test_watchdog_spawned_after_successful_wake(self, monkeypatch):
|
||||
"""Watchdog is spawned after successful send + wake."""
|
||||
printed: list[str] = []
|
||||
monkeypatch.setattr(f"{MOD}.console", _mock_console(printed))
|
||||
|
||||
watchdog_calls: list[str] = []
|
||||
monkeypatch.setattr(
|
||||
f"{MOD}._spawn_watchdog",
|
||||
lambda target: watchdog_calls.append(target),
|
||||
)
|
||||
|
||||
patches = _send_patches()
|
||||
with patches:
|
||||
from aipass.ai_mail.apps.modules.dispatch import _orchestrate_dispatch_send
|
||||
@@ -1140,21 +988,17 @@ class TestDispatchSendWatchdogIntegration:
|
||||
result = _orchestrate_dispatch_send(["@target", "Subject", "Body"])
|
||||
|
||||
assert result is True
|
||||
assert watchdog_calls == ["@target"]
|
||||
combined = " ".join(printed)
|
||||
assert "Wake-back enabled" in combined
|
||||
assert "Watchdog armed" not in combined
|
||||
|
||||
def test_watchdog_not_spawned_on_wake_failure(self, monkeypatch):
|
||||
"""Watchdog is NOT spawned when wake fails."""
|
||||
def test_no_wake_back_message_on_wake_failure(self, monkeypatch):
|
||||
"""No wake-back message when wake fails."""
|
||||
errors: list[str] = []
|
||||
monkeypatch.setattr(f"{MOD}.error", lambda msg: errors.append(msg))
|
||||
printed: list[str] = []
|
||||
monkeypatch.setattr(f"{MOD}.console", _mock_console(printed))
|
||||
|
||||
watchdog_calls: list[str] = []
|
||||
monkeypatch.setattr(
|
||||
f"{MOD}._spawn_watchdog",
|
||||
lambda target: watchdog_calls.append(target),
|
||||
)
|
||||
|
||||
mock_status = MagicMock()
|
||||
mock_status.format.return_value = "WAKE FAILED"
|
||||
patches = _send_patches(
|
||||
@@ -1167,19 +1011,14 @@ class TestDispatchSendWatchdogIntegration:
|
||||
|
||||
_orchestrate_dispatch_send(["@target", "Subject", "Body"])
|
||||
|
||||
assert watchdog_calls == []
|
||||
combined = " ".join(printed)
|
||||
assert "Wake-back enabled" not in combined
|
||||
|
||||
def test_no_watchdog_flag_skips_spawn(self, monkeypatch):
|
||||
"""--no-watchdog flag prevents watchdog spawn."""
|
||||
def test_no_watchdog_flag_still_accepted(self, monkeypatch):
|
||||
"""--no-watchdog flag is consumed without error (backward compat)."""
|
||||
printed: list[str] = []
|
||||
monkeypatch.setattr(f"{MOD}.console", _mock_console(printed))
|
||||
|
||||
watchdog_calls: list[str] = []
|
||||
monkeypatch.setattr(
|
||||
f"{MOD}._spawn_watchdog",
|
||||
lambda target: watchdog_calls.append(target),
|
||||
)
|
||||
|
||||
patches = _send_patches()
|
||||
with patches:
|
||||
from aipass.ai_mail.apps.modules.dispatch import _orchestrate_dispatch_send
|
||||
@@ -1187,21 +1026,14 @@ class TestDispatchSendWatchdogIntegration:
|
||||
result = _orchestrate_dispatch_send(["@target", "Subject", "Body", "--no-watchdog"])
|
||||
|
||||
assert result is True
|
||||
assert watchdog_calls == []
|
||||
|
||||
def test_watchdog_not_spawned_on_send_failure(self, monkeypatch):
|
||||
"""Watchdog is NOT spawned when send fails."""
|
||||
def test_no_watchdog_message_on_send_failure(self, monkeypatch):
|
||||
"""No wake-back message when send fails."""
|
||||
errors: list[str] = []
|
||||
monkeypatch.setattr(f"{MOD}.error", lambda msg: errors.append(msg))
|
||||
printed: list[str] = []
|
||||
monkeypatch.setattr(f"{MOD}.console", _mock_console(printed))
|
||||
|
||||
watchdog_calls: list[str] = []
|
||||
monkeypatch.setattr(
|
||||
f"{MOD}._spawn_watchdog",
|
||||
lambda target: watchdog_calls.append(target),
|
||||
)
|
||||
|
||||
patches = _send_patches(
|
||||
{
|
||||
f"{_H_SEND}.send_to_single": MagicMock(return_value=(False, "error")),
|
||||
@@ -1212,4 +1044,5 @@ class TestDispatchSendWatchdogIntegration:
|
||||
|
||||
_orchestrate_dispatch_send(["@target", "Subject", "Body"])
|
||||
|
||||
assert watchdog_calls == []
|
||||
combined = " ".join(printed)
|
||||
assert "Wake-back enabled" not in combined
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -385,7 +385,7 @@ class TestHandleClose:
|
||||
post_ops_called = []
|
||||
monkeypatch.setattr(
|
||||
"aipass.ai_mail.apps.modules.email.batch_close_post_ops",
|
||||
lambda bp, push_fn, central_fn, purge_fn: post_ops_called.append(True),
|
||||
lambda bp, central_fn, purge_fn: post_ops_called.append(True),
|
||||
)
|
||||
mock_console = MagicMock()
|
||||
mock_console.print = lambda msg, **kw: None
|
||||
@@ -1286,7 +1286,7 @@ class TestHandleCloseExtended:
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"aipass.ai_mail.apps.modules.email.batch_close_post_ops",
|
||||
lambda bp, push_fn, central_fn, purge_fn: None,
|
||||
lambda bp, central_fn, purge_fn: None,
|
||||
)
|
||||
printed: list[str] = []
|
||||
errors: list[str] = []
|
||||
@@ -1338,7 +1338,7 @@ class TestHandleCloseExtended:
|
||||
post_ops_called: list[bool] = []
|
||||
monkeypatch.setattr(
|
||||
"aipass.ai_mail.apps.modules.email.batch_close_post_ops",
|
||||
lambda bp, push_fn, central_fn, purge_fn: post_ops_called.append(True),
|
||||
lambda bp, central_fn, purge_fn: post_ops_called.append(True),
|
||||
)
|
||||
printed: list[str] = []
|
||||
mock_console = MagicMock()
|
||||
@@ -1450,7 +1450,6 @@ class TestDeliveryCallback:
|
||||
new_count,
|
||||
opened_count,
|
||||
total,
|
||||
push_dashboard_fn=None,
|
||||
update_central_fn=None,
|
||||
):
|
||||
"""Capture on_email_delivered arguments."""
|
||||
@@ -1460,7 +1459,6 @@ class TestDeliveryCallback:
|
||||
"new_count": new_count,
|
||||
"opened_count": opened_count,
|
||||
"total": total,
|
||||
"push_dashboard_fn": push_dashboard_fn,
|
||||
"update_central_fn": update_central_fn,
|
||||
}
|
||||
)
|
||||
@@ -1478,7 +1476,6 @@ class TestDeliveryCallback:
|
||||
assert delivered_args[0]["new_count"] == 3
|
||||
assert delivered_args[0]["opened_count"] == 2
|
||||
assert delivered_args[0]["total"] == 5
|
||||
assert delivered_args[0]["push_dashboard_fn"] is not None
|
||||
|
||||
|
||||
# ===========================================================================
|
||||
@@ -1708,7 +1705,7 @@ class TestEmailSendIntrospection:
|
||||
|
||||
print_introspection()
|
||||
combined = "\n".join(printed)
|
||||
assert "EMAIL SEND ORCHESTRATION" in combined
|
||||
assert "email_send Module" in combined
|
||||
assert "handle_send" in combined
|
||||
assert "_send_direct" in combined
|
||||
assert "_send_broadcast" in combined
|
||||
@@ -1761,3 +1758,62 @@ class TestSendInteractiveExtended:
|
||||
assert result is True
|
||||
assert any("@alpha" in p for p in printed)
|
||||
assert any("sent" in p.lower() for p in printed)
|
||||
|
||||
|
||||
class TestHandleReplyMultiArg:
|
||||
"""Regression tests for multi-line reply body truncation (S84 fix)."""
|
||||
|
||||
def test_reply_joins_split_args_into_body(self, tmp_path, monkeypatch):
|
||||
"""When shell splits body into multiple args, all are joined into message."""
|
||||
original = {"id": "msg1", "from": "@devpulse", "subject": "test dispatch"}
|
||||
captured_msg = []
|
||||
|
||||
monkeypatch.setattr(
|
||||
"aipass.ai_mail.apps.modules.email._resolve_branch_path",
|
||||
lambda: tmp_path,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"aipass.ai_mail.apps.modules.email.get_email_by_id",
|
||||
lambda inbox_file, msg_id: original,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"aipass.ai_mail.apps.modules.email.send_reply",
|
||||
lambda bp, orig, msg: (captured_msg.append(msg), "Reply sent", "r1")[1:],
|
||||
)
|
||||
mock_console = MagicMock()
|
||||
monkeypatch.setattr("aipass.ai_mail.apps.modules.email.console", mock_console)
|
||||
_write_inbox(tmp_path)
|
||||
|
||||
from aipass.ai_mail.apps.modules.email import handle_reply
|
||||
|
||||
result = handle_reply(["msg1", "Line one", "Line two", "Line three"])
|
||||
assert result is True
|
||||
assert len(captured_msg) == 1
|
||||
assert captured_msg[0] == "Line one Line two Line three"
|
||||
|
||||
def test_reply_single_arg_unchanged(self, tmp_path, monkeypatch):
|
||||
"""Single-arg reply body remains unchanged (no extra spaces)."""
|
||||
original = {"id": "msg1", "from": "@devpulse", "subject": "test"}
|
||||
captured_msg = []
|
||||
|
||||
monkeypatch.setattr(
|
||||
"aipass.ai_mail.apps.modules.email._resolve_branch_path",
|
||||
lambda: tmp_path,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"aipass.ai_mail.apps.modules.email.get_email_by_id",
|
||||
lambda inbox_file, msg_id: original,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"aipass.ai_mail.apps.modules.email.send_reply",
|
||||
lambda bp, orig, msg: (captured_msg.append(msg), "Reply sent", "r1")[1:],
|
||||
)
|
||||
mock_console = MagicMock()
|
||||
monkeypatch.setattr("aipass.ai_mail.apps.modules.email.console", mock_console)
|
||||
_write_inbox(tmp_path)
|
||||
|
||||
from aipass.ai_mail.apps.modules.email import handle_reply
|
||||
|
||||
result = handle_reply(["msg1", "Complete single-line reply"])
|
||||
assert result is True
|
||||
assert captured_msg[0] == "Complete single-line reply"
|
||||
|
||||
@@ -155,51 +155,34 @@ def test_dispatch_send_error_passes_correct_email_data(monkeypatch):
|
||||
# ---- on_email_delivered tests --------------------------------
|
||||
|
||||
|
||||
def test_on_email_delivered_with_both_callbacks():
|
||||
"""Both callbacks are invoked when provided."""
|
||||
push_fn = MagicMock()
|
||||
def test_on_email_delivered_with_central_callback():
|
||||
"""Central callback is invoked when provided."""
|
||||
update_fn = MagicMock()
|
||||
branch_path = "/some/path"
|
||||
|
||||
on_email_delivered(branch_path, 3, 1, 10, push_fn, update_fn)
|
||||
on_email_delivered(branch_path, 3, 1, 10, update_central_fn=update_fn)
|
||||
|
||||
push_fn.assert_called_once_with(branch_path)
|
||||
update_fn.assert_called_once_with()
|
||||
|
||||
|
||||
def test_on_email_delivered_with_none_callbacks():
|
||||
"""No error when both callbacks are None."""
|
||||
on_email_delivered("/some/path", 3, 1, 10, None, None)
|
||||
|
||||
|
||||
def test_on_email_delivered_dashboard_failure_does_not_block_central():
|
||||
"""Dashboard failure does not prevent central update from running."""
|
||||
push_fn = MagicMock(side_effect=RuntimeError("dashboard broken"))
|
||||
update_fn = MagicMock()
|
||||
|
||||
on_email_delivered("/some/path", 3, 1, 10, push_fn, update_fn)
|
||||
|
||||
push_fn.assert_called_once()
|
||||
update_fn.assert_called_once()
|
||||
"""No error when callback is None."""
|
||||
on_email_delivered("/some/path", 3, 1, 10, None)
|
||||
|
||||
|
||||
def test_on_email_delivered_central_failure_does_not_raise():
|
||||
"""Central update failure is caught silently."""
|
||||
push_fn = MagicMock()
|
||||
update_fn = MagicMock(side_effect=RuntimeError("central broken"))
|
||||
|
||||
on_email_delivered("/some/path", 3, 1, 10, push_fn, update_fn)
|
||||
on_email_delivered("/some/path", 3, 1, 10, update_central_fn=update_fn)
|
||||
|
||||
push_fn.assert_called_once()
|
||||
update_fn.assert_called_once()
|
||||
|
||||
|
||||
def test_on_email_delivered_both_fail_no_exception():
|
||||
"""Both callbacks failing does not raise any exception."""
|
||||
push_fn = MagicMock(side_effect=RuntimeError("push fail"))
|
||||
def test_on_email_delivered_central_fail_no_exception():
|
||||
"""Central callback failing does not raise any exception."""
|
||||
update_fn = MagicMock(side_effect=RuntimeError("update fail"))
|
||||
|
||||
on_email_delivered("/some/path", 3, 1, 10, push_fn, update_fn)
|
||||
on_email_delivered("/some/path", 3, 1, 10, update_central_fn=update_fn)
|
||||
|
||||
push_fn.assert_called_once()
|
||||
update_fn.assert_called_once()
|
||||
|
||||
@@ -46,7 +46,7 @@ def test_get_footer_contains_checklist():
|
||||
assert "TASK CHECKLIST" in result
|
||||
assert "SEEDGO CHECK" in result
|
||||
assert "UPDATE MEMORIES" in result
|
||||
assert "CLOSE FPLAN" in result
|
||||
assert "CLOSE YOUR PLAN" in result
|
||||
assert "EMAIL SENDER" in result
|
||||
|
||||
|
||||
|
||||
@@ -42,12 +42,6 @@ def _mock_inbox_lock(monkeypatch):
|
||||
monkeypatch.setattr(mod, "_get_inbox_lock", lambda: _noop_lock)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _mock_dashboard(monkeypatch):
|
||||
"""Replace _get_push_dashboard_update with a no-op."""
|
||||
monkeypatch.setattr(mod, "_get_push_dashboard_update", lambda: lambda _bp: None)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _mock_central(monkeypatch):
|
||||
"""Replace _get_update_central with a no-op."""
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"""Tests for miscellaneous handlers -- central_writer.update_central, dispatch status.check_pid_status,
|
||||
daemon.run_daemon, json_handler.increment_counter/update_data_metrics, delivery.deliver_to_inbox_file,
|
||||
dashboard_sync.push_dashboard_update, inbox_resolve.resolve_inbox_target."""
|
||||
inbox_resolve.resolve_inbox_target."""
|
||||
|
||||
import json
|
||||
import os
|
||||
@@ -14,7 +14,6 @@ import aipass.ai_mail.apps.handlers.central_writer as central_mod
|
||||
import aipass.ai_mail.apps.handlers.dispatch.daemon as daemon_mod
|
||||
import aipass.ai_mail.apps.handlers.json_utils.json_handler as json_handler_mod
|
||||
import aipass.ai_mail.apps.handlers.email.delivery as delivery_mod
|
||||
import aipass.ai_mail.apps.handlers.email.dashboard_sync as dashboard_mod
|
||||
from aipass.ai_mail.apps.handlers.central_writer import update_central
|
||||
from aipass.ai_mail.apps.handlers.dispatch.status import check_pid_status
|
||||
from aipass.ai_mail.apps.handlers.json_utils.json_handler import (
|
||||
@@ -22,7 +21,6 @@ from aipass.ai_mail.apps.handlers.json_utils.json_handler import (
|
||||
update_data_metrics,
|
||||
)
|
||||
from aipass.ai_mail.apps.handlers.email.delivery import deliver_to_inbox_file
|
||||
from aipass.ai_mail.apps.handlers.email.dashboard_sync import push_dashboard_update
|
||||
from aipass.ai_mail.apps.handlers.email.inbox_resolve import resolve_inbox_target
|
||||
|
||||
|
||||
@@ -61,14 +59,6 @@ def _silence_json_handler_delivery():
|
||||
yield mock_jh
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _silence_json_handler_dashboard():
|
||||
"""Prevent log_operation in dashboard_sync from writing real JSON files."""
|
||||
with patch("aipass.ai_mail.apps.handlers.email.dashboard_sync.json_handler") as mock_jh:
|
||||
mock_jh.log_operation.return_value = True
|
||||
yield mock_jh
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _silence_json_handler_inbox_resolve():
|
||||
"""Prevent log_operation in inbox_resolve from writing real JSON files."""
|
||||
@@ -399,64 +389,6 @@ def test_deliver_to_inbox_file_preserves_existing_messages(tmp_path, _noop_inbox
|
||||
assert result["messages"][1]["subject"] == "Old email"
|
||||
|
||||
|
||||
# ==============================================================
|
||||
# push_dashboard_update tests
|
||||
# ==============================================================
|
||||
|
||||
|
||||
def test_push_dashboard_update_happy_path(tmp_path):
|
||||
"""Successful dashboard push returns True."""
|
||||
branch_path = tmp_path / "trigger"
|
||||
inbox_dir = branch_path / ".ai_mail.local"
|
||||
inbox_dir.mkdir(parents=True)
|
||||
inbox_file = inbox_dir / "inbox.json"
|
||||
inbox_data = {
|
||||
"messages": [
|
||||
{"id": "m1", "status": "new", "timestamp": "2026-04-01 10:00:00"},
|
||||
{"id": "m2", "status": "opened", "timestamp": "2026-04-01 09:00:00"},
|
||||
]
|
||||
}
|
||||
inbox_file.write_text(json.dumps(inbox_data), encoding="utf-8")
|
||||
|
||||
mock_write = MagicMock(return_value=True)
|
||||
|
||||
with patch.object(dashboard_mod, "_get_write_section", return_value=mock_write):
|
||||
result = push_dashboard_update(branch_path)
|
||||
|
||||
assert result is True
|
||||
mock_write.assert_called_once()
|
||||
section_data = mock_write.call_args[0][1]
|
||||
assert section_data == "ai_mail"
|
||||
|
||||
|
||||
def test_push_dashboard_update_no_inbox(tmp_path):
|
||||
"""Returns True with zero stats when no inbox exists."""
|
||||
branch_path = tmp_path / "empty_branch"
|
||||
branch_path.mkdir()
|
||||
|
||||
mock_write = MagicMock(return_value=True)
|
||||
|
||||
with patch.object(dashboard_mod, "_get_write_section", return_value=mock_write):
|
||||
result = push_dashboard_update(branch_path)
|
||||
|
||||
assert result is True
|
||||
mock_write.assert_called_once()
|
||||
section_data = mock_write.call_args[0][2]
|
||||
assert section_data["new"] == 0
|
||||
assert section_data["total"] == 0
|
||||
|
||||
|
||||
def test_push_dashboard_update_catches_exceptions(tmp_path):
|
||||
"""Returns False on any exception (never raises)."""
|
||||
branch_path = tmp_path / "broken"
|
||||
branch_path.mkdir()
|
||||
|
||||
with patch.object(dashboard_mod, "_get_write_section", side_effect=RuntimeError("broken")):
|
||||
result = push_dashboard_update(branch_path)
|
||||
|
||||
assert result is False
|
||||
|
||||
|
||||
# ==============================================================
|
||||
# resolve_inbox_target tests
|
||||
# ==============================================================
|
||||
|
||||
@@ -268,3 +268,40 @@ def test_send_reply_re_prefix_not_duplicated(tmp_path):
|
||||
assert success is True
|
||||
# Should keep "RE: Already replied", not "RE: RE: Already replied"
|
||||
assert deliver_calls[0][1]["subject"] == "RE: Already replied"
|
||||
|
||||
|
||||
def test_send_reply_multiline_body_preserved(tmp_path):
|
||||
"""Multi-line reply body is stored intact, not truncated to first line."""
|
||||
from_branch_path = tmp_path / "hooks"
|
||||
from_branch_path.mkdir()
|
||||
sender_info = {"email": "@hooks", "name": "HOOKS"}
|
||||
target_branch = {"email": "@devpulse", "name": "DEVPULSE", "path": str(tmp_path / "devpulse")}
|
||||
original = _make_original_email()
|
||||
|
||||
deliver_calls = []
|
||||
|
||||
def mock_deliver(to_branch, email_data):
|
||||
deliver_calls.append((to_branch, email_data))
|
||||
return (True, "")
|
||||
|
||||
multiline_body = (
|
||||
"Investigation: cadence findings\n\nDetails:\n1. First finding\n2. Second finding\n3. Third finding"
|
||||
)
|
||||
|
||||
with (
|
||||
patch(_PATCH_BRANCH_DETECTION, return_value=sender_info),
|
||||
patch(_PATCH_DELIVERY, side_effect=mock_deliver),
|
||||
patch(_PATCH_ALL_BRANCHES, return_value=[target_branch]),
|
||||
patch(_PATCH_CLOSE_ARCHIVE, return_value=(True, "closed")),
|
||||
):
|
||||
success, _message, _reply_id = send_reply(from_branch_path, original, multiline_body)
|
||||
|
||||
assert success is True
|
||||
assert deliver_calls[0][1]["message"] == multiline_body
|
||||
|
||||
sent_folder = from_branch_path / ".ai_mail.local" / "sent"
|
||||
sent_files = list(sent_folder.glob("*.json"))
|
||||
assert len(sent_files) == 1
|
||||
with open(sent_files[0], "r", encoding="utf-8") as f:
|
||||
sent_data = json.load(f)
|
||||
assert sent_data["message"] == multiline_body
|
||||
|
||||
@@ -357,3 +357,34 @@ def test_resolve_dispatch_target_tilde_path():
|
||||
result = resolve_dispatch_target("~/Projects/flow", True, get_branch_info_fn=None)
|
||||
|
||||
assert result == "@flow"
|
||||
|
||||
|
||||
# ---- parse_send_args multi-arg message tests (S84 fix) --------
|
||||
|
||||
|
||||
def test_parse_send_args_joins_split_message():
|
||||
"""When message body is split into multiple args, all are joined."""
|
||||
from aipass.ai_mail.apps.handlers.email.send_args import parse_send_args
|
||||
|
||||
result = parse_send_args(["@target", "Subject", "Line one", "Line two", "Line three"])
|
||||
assert result["mode"] == "direct"
|
||||
assert result["subject"] == "Subject"
|
||||
assert result["message"] == "Line one Line two Line three"
|
||||
|
||||
|
||||
def test_parse_send_args_single_message_unchanged():
|
||||
"""Single message arg is not altered."""
|
||||
from aipass.ai_mail.apps.handlers.email.send_args import parse_send_args
|
||||
|
||||
result = parse_send_args(["@target", "Subject", "Complete body here"])
|
||||
assert result["mode"] == "direct"
|
||||
assert result["message"] == "Complete body here"
|
||||
|
||||
|
||||
def test_parse_send_args_multiline_body_preserved():
|
||||
"""A single arg with embedded newlines passes through intact."""
|
||||
from aipass.ai_mail.apps.handlers.email.send_args import parse_send_args
|
||||
|
||||
body = "First line\nSecond line\nThird line"
|
||||
result = parse_send_args(["@target", "Subject", body])
|
||||
assert result["message"] == body
|
||||
|
||||
@@ -570,13 +570,18 @@ class TestDispatchEnvIsolation:
|
||||
)
|
||||
|
||||
def test_dispatch_monitor_passes_spawn_env_to_subprocess(self):
|
||||
"""dispatch_monitor.py must pass env=spawn_env to subprocess.run.
|
||||
"""dispatch_monitor.py must pass spawn_env as the subprocess env.
|
||||
|
||||
Without this, all env var isolation is useless — the subprocess
|
||||
would inherit os.environ instead of the cleaned spawn_env.
|
||||
Accepts either the direct kwarg form (env=spawn_env) or the
|
||||
popen_kwargs dict form ("env": spawn_env) introduced with the
|
||||
sandbox broker-fd wiring (FPLAN-0250 Phase 6b).
|
||||
"""
|
||||
active_source = self._load_active_source()
|
||||
assert "env=spawn_env" in active_source, "dispatch_monitor.py must pass env=spawn_env to subprocess.run"
|
||||
assert "env=spawn_env" in active_source or '"env": spawn_env' in active_source, (
|
||||
"dispatch_monitor.py must pass spawn_env as the subprocess env"
|
||||
)
|
||||
|
||||
def test_detect_resolves_identity_when_cwd_is_wrong(self, clean_env, tmp_path, list_format_registry):
|
||||
"""When AIPASS_CALLER_BRANCH is set but CWD is outside any branch,
|
||||
|
||||
@@ -20,7 +20,11 @@ from aipass.ai_mail.apps.handlers.dispatch.wake import (
|
||||
_read_json,
|
||||
_check_lock,
|
||||
_check_pid_alive,
|
||||
_get_pid_cwd,
|
||||
_get_pid_cwd_darwin,
|
||||
_read_session_type,
|
||||
_read_session_type_darwin,
|
||||
_is_zombie_linux,
|
||||
_clean_zombies,
|
||||
_find_claude_bin,
|
||||
resolve_branch,
|
||||
@@ -138,6 +142,7 @@ def test_check_pid_alive_dead(monkeypatch):
|
||||
|
||||
def test_check_pid_alive_permission_error(monkeypatch):
|
||||
"""PermissionError means process exists but cannot signal -- returns True."""
|
||||
monkeypatch.setattr("sys.platform", "linux")
|
||||
monkeypatch.setattr(os, "kill", _raise_permission)
|
||||
assert _check_pid_alive(1) is True
|
||||
|
||||
@@ -201,11 +206,126 @@ def test_read_session_type_not_set(monkeypatch, tmp_path):
|
||||
|
||||
|
||||
def test_read_session_type_non_linux(monkeypatch):
|
||||
"""Non-linux platform returns 'interactive' immediately."""
|
||||
monkeypatch.setattr("sys.platform", "darwin")
|
||||
"""Non-linux, non-darwin platform returns 'interactive' immediately."""
|
||||
monkeypatch.setattr("sys.platform", "win32")
|
||||
assert _read_session_type("999") == "interactive"
|
||||
|
||||
|
||||
def test_read_session_type_darwin_found(monkeypatch):
|
||||
"""macOS: reads AIPASS_SESSION_TYPE from ps -wwE output."""
|
||||
monkeypatch.setattr("sys.platform", "darwin")
|
||||
|
||||
class FakeResult:
|
||||
returncode = 0
|
||||
stdout = "/usr/bin/claude AIPASS_SESSION_TYPE=dispatched HOME=/Users/u"
|
||||
|
||||
monkeypatch.setattr(subprocess, "run", lambda *a, **kw: FakeResult())
|
||||
assert _read_session_type("123") == "dispatched"
|
||||
|
||||
|
||||
def test_read_session_type_darwin_not_set(monkeypatch):
|
||||
"""macOS: missing env var returns 'interactive'."""
|
||||
monkeypatch.setattr("sys.platform", "darwin")
|
||||
|
||||
class FakeResult:
|
||||
returncode = 0
|
||||
stdout = "/usr/bin/claude HOME=/Users/u"
|
||||
|
||||
monkeypatch.setattr(subprocess, "run", lambda *a, **kw: FakeResult())
|
||||
assert _read_session_type("456") == "interactive"
|
||||
|
||||
|
||||
def test_read_session_type_darwin_ps_failure(monkeypatch):
|
||||
"""macOS: ps failure returns 'interactive'."""
|
||||
assert _read_session_type_darwin("999") == "interactive"
|
||||
|
||||
|
||||
# --- _get_pid_cwd tests ------------------------------------------------
|
||||
|
||||
|
||||
def test_get_pid_cwd_linux(monkeypatch, tmp_path):
|
||||
"""Linux: reads /proc/{pid}/cwd via readlink."""
|
||||
monkeypatch.setattr("sys.platform", "linux")
|
||||
target = str(tmp_path / "project")
|
||||
monkeypatch.setattr(os, "readlink", lambda p: target)
|
||||
assert _get_pid_cwd("100") == target
|
||||
|
||||
|
||||
def test_get_pid_cwd_linux_oserror(monkeypatch):
|
||||
"""Linux: OSError returns None."""
|
||||
monkeypatch.setattr("sys.platform", "linux")
|
||||
monkeypatch.setattr(os, "readlink", lambda p: (_ for _ in ()).throw(OSError("no proc")))
|
||||
assert _get_pid_cwd("100") is None
|
||||
|
||||
|
||||
def test_get_pid_cwd_darwin(monkeypatch, tmp_path):
|
||||
"""macOS: reads cwd via lsof."""
|
||||
monkeypatch.setattr("sys.platform", "darwin")
|
||||
target = "/tmp/pytest-project"
|
||||
|
||||
class FakeResult:
|
||||
returncode = 0
|
||||
stdout = f"p100\nn{target}\n"
|
||||
|
||||
monkeypatch.setattr(subprocess, "run", lambda *a, **kw: FakeResult())
|
||||
assert _get_pid_cwd("100") == target
|
||||
|
||||
|
||||
def test_get_pid_cwd_darwin_failure(monkeypatch):
|
||||
"""macOS: lsof failure returns None."""
|
||||
|
||||
class FailedResult:
|
||||
returncode = 1
|
||||
stdout = ""
|
||||
|
||||
monkeypatch.setattr(subprocess, "run", lambda *a, **kw: FailedResult())
|
||||
assert _get_pid_cwd_darwin("999") is None
|
||||
|
||||
|
||||
def test_get_pid_cwd_unsupported_platform(monkeypatch):
|
||||
"""Unsupported platform returns None."""
|
||||
monkeypatch.setattr("sys.platform", "win32")
|
||||
assert _get_pid_cwd("100") is None
|
||||
|
||||
|
||||
# --- _is_zombie_linux tests --------------------------------------------
|
||||
|
||||
|
||||
def test_is_zombie_linux_not_zombie(monkeypatch, tmp_path):
|
||||
"""Non-zombie process returns False."""
|
||||
status_file = tmp_path / "status"
|
||||
status_file.write_text("Name:\tclaude\nState:\tS (sleeping)\nPid:\t42\n")
|
||||
monkeypatch.setattr(
|
||||
"builtins.open",
|
||||
_fake_open_factory(str(status_file), {"/proc/42/status": str(status_file)}),
|
||||
)
|
||||
assert _is_zombie_linux(42) is False
|
||||
|
||||
|
||||
def test_is_zombie_linux_zombie(monkeypatch, tmp_path):
|
||||
"""Zombie process returns True."""
|
||||
status_file = tmp_path / "status"
|
||||
status_file.write_text("Name:\tclaude\nState:\tZ (zombie)\nPid:\t42\n")
|
||||
monkeypatch.setattr(
|
||||
"builtins.open",
|
||||
_fake_open_factory(str(status_file), {"/proc/42/status": str(status_file)}),
|
||||
)
|
||||
assert _is_zombie_linux(42) is True
|
||||
|
||||
|
||||
def test_is_zombie_linux_no_proc(monkeypatch):
|
||||
"""Missing /proc entry returns False (not zombie, just gone)."""
|
||||
_real_open = open
|
||||
|
||||
def _fake_open(path, *a, **kw):
|
||||
if "/proc/99999/" in str(path):
|
||||
raise FileNotFoundError(path)
|
||||
return _real_open(path, *a, **kw)
|
||||
|
||||
monkeypatch.setattr("builtins.open", _fake_open)
|
||||
assert _is_zombie_linux(99999) is False
|
||||
|
||||
|
||||
# --- _check_lock tests ------------------------------------------------
|
||||
|
||||
|
||||
@@ -222,7 +342,7 @@ def test_check_lock_alive_pid(tmp_path, monkeypatch):
|
||||
lock_file = lock_dir / ".dispatch.lock"
|
||||
lock_data = {"pid": 1234, "timestamp": "2026-03-29T10:00:00"}
|
||||
lock_file.write_text(json.dumps(lock_data), encoding="utf-8")
|
||||
monkeypatch.setattr(os, "kill", lambda pid, sig: None)
|
||||
monkeypatch.setattr(wake_mod, "_check_pid_alive", lambda pid: True)
|
||||
result = _check_lock(tmp_path)
|
||||
assert result is not None
|
||||
assert result["pid"] == 1234
|
||||
@@ -235,7 +355,7 @@ def test_check_lock_dead_pid_removes_lock(tmp_path, monkeypatch):
|
||||
lock_file = lock_dir / ".dispatch.lock"
|
||||
lock_data = {"pid": 99999, "timestamp": "2026-03-29T10:00:00"}
|
||||
lock_file.write_text(json.dumps(lock_data), encoding="utf-8")
|
||||
monkeypatch.setattr(os, "kill", _raise_process_lookup)
|
||||
monkeypatch.setattr(wake_mod, "_check_pid_alive", lambda pid: False)
|
||||
result = _check_lock(tmp_path)
|
||||
assert result is None
|
||||
assert not lock_file.exists()
|
||||
@@ -257,6 +377,7 @@ def test_check_lock_stale_old_timestamp(tmp_path, monkeypatch):
|
||||
|
||||
def test_check_lock_permission_error_treated_active(tmp_path, monkeypatch):
|
||||
"""Lock PID that raises PermissionError is treated as active."""
|
||||
monkeypatch.setattr("sys.platform", "linux")
|
||||
lock_dir = tmp_path / ".ai_mail.local"
|
||||
lock_dir.mkdir(parents=True)
|
||||
lock_file = lock_dir / ".dispatch.lock"
|
||||
@@ -601,6 +722,7 @@ class TestWakeBranchSpawnEnv:
|
||||
|
||||
local_bin = str(_Path.home() / ".local" / "bin")
|
||||
monkeypatch.setenv("PATH", "/usr/bin:/bin")
|
||||
monkeypatch.delenv("INVOCATION_ID", raising=False)
|
||||
|
||||
captured_envs: list = []
|
||||
|
||||
@@ -831,6 +953,7 @@ def _patch_wake_deps(monkeypatch, **overrides):
|
||||
monkeypatch.setattr(wake_mod, attr, val)
|
||||
|
||||
monkeypatch.setattr("aipass.ai_mail.apps.handlers.dispatch.wake.time.sleep", lambda _: None)
|
||||
monkeypatch.delenv("INVOCATION_ID", raising=False)
|
||||
|
||||
|
||||
class _FakeProc:
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# AIPASS — Branch Prompt
|
||||
|
||||
*Injected every turn. Breadcrumbs only — details: README, --help, .trinity/ memories, STATUS.local.md.*
|
||||
*Injected every turn. Breadcrumbs only — details: README, --help, .trinity/ memories.*
|
||||
|
||||
## Identity
|
||||
|
||||
@@ -12,13 +12,13 @@ Not suggestions. Violating = bug.
|
||||
|
||||
- **No writes outside own `.trinity/`.** Never create, edit, delete files anywhere else. Not code, not docs, not configs, not other branches' memories.
|
||||
- **No git. Ever.** Not `git status`, not `drone @git anything`. Git is drone's world.
|
||||
- **No `drone @ai_mail dispatch`.** Email only test-convention body (below). Never wake agent real work.
|
||||
- **Dispatch focused work via `drone @ai_mail dispatch`** — to ONE owning branch, as the user's voice with detailed feedback. Reply routes to @aipass; I track the loop and report back. Not an orchestrator (no fleets, no running the floor — that's devpulse). Test-convention pings (below) still fine.
|
||||
- **No registry / hooks / bypass.json / config edits.** Spot bug → report. Never patch.
|
||||
- User asks build/fix/change something: tell them who. Offer dispatch through devpulse/drone — don't do it.
|
||||
- User asks build/fix/change in another branch: name the owner, then dispatch focused work to them as the user's voice. Heavy orchestration, git, and fleets stay with devpulse.
|
||||
|
||||
## What I Do
|
||||
|
||||
- Guide new users through `aipass init` (12 stages: welcome, system detect, doctor, profile, style questions, tool choice, docker offer, first agent, ping sweep, smoke test, handoff, done)
|
||||
- Guide new users through `aipass init` (10 stages: welcome, system detect, profile, style questions, tool choice, first agent, ping sweep, smoke test, handoff, done)
|
||||
- Answer "how does X work?" via `aipass help` — live README reads, offer depth, route branch experts
|
||||
- Run `aipass doctor` — aggregate seedgo, pytest, registry, hooks, git state, AIPASS_HOME
|
||||
- Remember user — name, OS, preferred CLI, setup progress `.trinity/local.json`
|
||||
@@ -30,7 +30,7 @@ Not suggestions. Violating = bug.
|
||||
aipass # Help banner with all commands
|
||||
aipass help [q] # Chatbot Q&A over branch READMEs
|
||||
aipass doctor # System health aggregation
|
||||
aipass init # 12-stage guided setup for new users, resumable
|
||||
aipass init # 10-stage guided setup for new users, resumable
|
||||
aipass profile # Show/edit what I know about the user
|
||||
aipass --version
|
||||
```
|
||||
@@ -53,7 +53,7 @@ apps/
|
||||
├── modules/
|
||||
│ ├── doctor.py # System health aggregation
|
||||
│ ├── help_chat.py # README-backed Q&A
|
||||
│ ├── init_flow.py # 12-stage guided setup, resumable
|
||||
│ ├── init_flow.py # 10-stage guided setup, resumable
|
||||
│ ├── handoff.py # CLI handoff (tmux / wt.exe)
|
||||
│ └── profile.py # User profile read/write
|
||||
└── handlers/
|
||||
@@ -79,6 +79,6 @@ apps/
|
||||
|
||||
## Known Gotchas
|
||||
|
||||
- **Status: under construction.** Whole branch gitignored. Do not PR anything this directory until Phase 8 reveal (DPLAN-0136).
|
||||
- **Status: under construction (DPLAN-0136).** Don't PR / reveal this branch until Phase 8 — that's a *policy*, NOT a gitignore. Only the usual runtime/memory layer is ignored (`.trinity/`, plan files, `*.local`, logs) same as every branch; my code (init_flow, cross_os, tests, README) IS trackable. Committed-or-not = git's call, devpulse's lane.
|
||||
- **`aipass` binary currently `cli` branch's `aipass init`** — project bootstrap, not citizen creation. Eventually this CLI entry moves here. Until then, use `drone @spawn create` citizen creation.
|
||||
- **Test-convention tokens need buy-in.** Core agents don't yet recognize `[AIPASS-TEST — ...]`. Coordinating @ai_mail before pinging anyone.
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
"metadata": {
|
||||
"version": "2.0.0",
|
||||
"created": "2026-04-16",
|
||||
"description": "Bypass config for @aipass citizen. While under construction (DPLAN-0136 Phase 0-3), module and handler files exist as documented placeholders with no implementation body. Each placeholder raises NotImplementedError and declares its phase. Bypass standards that fire on structural requirements the placeholders intentionally skip — json_handler import, print_introspection, CLI service wiring. Remove these entries in Phase N as each module gets its real body.",
|
||||
"last_updated": "2026-04-16"
|
||||
"description": "Bypass config for @aipass citizen. Modules operational: concierge/init/doctor/handoff/profile/install built and tested. Bypasses cover: binary-invocation introspection pattern (bare aipass <cmd> runs, --info for introspection), thin entry-point router (aipass.py uses bare print, no CLI imports), pure-python bootstrap (bootstrap.py/scaffold_content.py run before AIPass services exist), test-isolation patterns (architecture/encapsulation for tests/ directory), and CLI flag name references (permission_flags in test assertions and handoff platform).",
|
||||
"last_updated": "2026-07-05"
|
||||
},
|
||||
"bypass": [
|
||||
{
|
||||
@@ -31,45 +31,20 @@
|
||||
"standard": "cli",
|
||||
"reason": "Session info must print immediately after tmux spawn — returning data to module layer would lose the timing context. User needs attach/kill instructions right when the session starts."
|
||||
},
|
||||
{
|
||||
"file": "apps/modules/handoff.py",
|
||||
"standard": "introspection",
|
||||
"reason": "Phase 4 placeholder — print_introspection() added with handoff build."
|
||||
},
|
||||
{
|
||||
"file": "apps/modules/handoff.py",
|
||||
"standard": "json_structure",
|
||||
"reason": "Phase 4 placeholder — json_handler import added with handoff build."
|
||||
},
|
||||
{
|
||||
"file": "apps/modules/handoff.py",
|
||||
"standard": "cli",
|
||||
"reason": "Phase 4 placeholder — CLI service imports added with handoff build."
|
||||
},
|
||||
{
|
||||
"file": "apps/aipass.py",
|
||||
"standard": "architecture",
|
||||
"reason": "Phase 0 entry-point stub from spawn template. Full 3-layer wiring (modules/ discovery, handlers/ imports) added when first module comes online (Phase 1)."
|
||||
},
|
||||
{
|
||||
"file": "apps/aipass.py",
|
||||
"standard": "cli",
|
||||
"reason": "Phase 0 entry-point stub — CLI service imports (console, header) added when modules come online (Phase 1+)."
|
||||
"reason": "Thin command router — discovers and routes to modules, which own the CLI service layer. Adding console/header imports here couples the bootstrap entry point to Rich for 4 status lines."
|
||||
},
|
||||
{
|
||||
"file": "apps/aipass.py",
|
||||
"standard": "debug_print",
|
||||
"reason": "Phase 0 entry-point stub uses bare print() for scaffold visibility. Replaced with console.print() when CLI services are wired in Phase 1+."
|
||||
"reason": "Thin command router uses bare print() for version output and help banner (4 calls). These run before module discovery — importing Rich console for bootstrap output adds startup overhead for minimal benefit."
|
||||
},
|
||||
{
|
||||
"file": "apps/aipass.py",
|
||||
"standard": "introspection",
|
||||
"reason": "Phase 0 — spawn template does not emit print_introspection(). Added when modules come online (Phase 1+)."
|
||||
},
|
||||
{
|
||||
"file": "apps/aipass.py",
|
||||
"standard": "log_structure",
|
||||
"reason": "Phase 0 — logs/ directory exists (spawn-created), but prax logger import not wired yet. Added when first module uses it."
|
||||
"reason": "Thin command router, not a module — it has no domain to introspect. Modules handle their own introspection via --info. No print_introspection() needed."
|
||||
},
|
||||
{
|
||||
"file": "apps/modules/doctor.py",
|
||||
@@ -116,6 +91,21 @@
|
||||
"standard": "permission_flags",
|
||||
"reason": "Assertions verify that the CLI flag name appears/absent in handoff_command output. String is in assertion context only — not a permission bypass in this file."
|
||||
},
|
||||
{
|
||||
"file": "tests/test_install.py",
|
||||
"standard": "architecture",
|
||||
"reason": "Test file lives in tests/ by convention — not in apps/. Standard 3-layer structure applies to production code only."
|
||||
},
|
||||
{
|
||||
"file": "tests/test_install.py",
|
||||
"standard": "encapsulation",
|
||||
"reason": "Unit tests must import the install module directly to test home resolution, clone, and setup orchestration in isolation. Entry-point imports would defeat the purpose of unit testing."
|
||||
},
|
||||
{
|
||||
"file": "tests/test_launcher.py",
|
||||
"standard": "architecture",
|
||||
"reason": "Test file lives in tests/ by convention — not in apps/. Standard 3-layer structure applies to production code only."
|
||||
},
|
||||
{
|
||||
"file": "tests/test_ping_sweep.py",
|
||||
"standard": "architecture",
|
||||
@@ -260,6 +250,131 @@
|
||||
"file": "apps/handlers/init/scaffold_content.py",
|
||||
"standard": "json_structure",
|
||||
"reason": "scaffold_content.py is Pure Python only (no module/prax/cli imports) by design — pure string-returning template generators extracted from bootstrap.py. Same constraint as bootstrap.py."
|
||||
},
|
||||
{
|
||||
"file": "apps/modules/doctor.py",
|
||||
"standard": "introspection",
|
||||
"reason": "aipass is binary-invoked: aipass doctor runs the command; introspection via --info"
|
||||
},
|
||||
{
|
||||
"file": "apps/modules/doctor_fix.py",
|
||||
"standard": "introspection",
|
||||
"reason": "aipass is binary-invoked: bare invocation shows usage; introspection via --info"
|
||||
},
|
||||
{
|
||||
"file": "apps/modules/doctor_wire.py",
|
||||
"standard": "introspection",
|
||||
"reason": "aipass is binary-invoked: bare invocation shows usage; introspection via --info"
|
||||
},
|
||||
{
|
||||
"file": "apps/modules/handoff.py",
|
||||
"standard": "introspection",
|
||||
"reason": "aipass is binary-invoked: aipass handoff shows usage; introspection via --info"
|
||||
},
|
||||
{
|
||||
"file": "apps/modules/help_chat.py",
|
||||
"standard": "introspection",
|
||||
"reason": "aipass is binary-invoked: aipass help shows usage; introspection via --info"
|
||||
},
|
||||
{
|
||||
"file": "apps/modules/init_flow.py",
|
||||
"standard": "introspection",
|
||||
"reason": "aipass is binary-invoked: aipass init shows usage; introspection via --info"
|
||||
},
|
||||
{
|
||||
"file": "apps/modules/profile.py",
|
||||
"standard": "introspection",
|
||||
"reason": "aipass is binary-invoked: aipass profile runs the command; introspection via --info"
|
||||
},
|
||||
{
|
||||
"file": "apps/modules/install.py",
|
||||
"standard": "introspection",
|
||||
"reason": "aipass is binary-invoked: bare 'aipass install' runs the bootstrap; introspection via --info (same pattern as doctor/init_flow/profile)."
|
||||
},
|
||||
{
|
||||
"file": "apps/modules/install.py",
|
||||
"standard": "modules",
|
||||
"reason": "Thin bootstrap orchestrator — preps the target/project dir (mkdir) immediately before shelling out to git clone / setup.sh / aipass init. Pre-subprocess dir prep, not business file ops; a handler adds indirection for 2 mkdir calls in a linear flow (same pattern as init_flow/doctor)."
|
||||
},
|
||||
{
|
||||
"file": "apps/handlers/json/json_handler.py",
|
||||
"standard": "test_quality",
|
||||
"reason": "save_json now raises ValueError on invalid structure (aipass.aipass.shared contract, TDPLAN-0006 P2). Tested via pytest.raises — no False return path to test."
|
||||
},
|
||||
{
|
||||
"file": "tests/test_cross_os.py",
|
||||
"standard": "architecture",
|
||||
"reason": "Test file lives in tests/ by convention — not in apps/. Standard 3-layer structure applies to production code only."
|
||||
},
|
||||
{
|
||||
"file": "tests/test_cross_os.py",
|
||||
"standard": "encapsulation",
|
||||
"reason": "Unit tests must import the cross_os handler directly to test the parser/filter in isolation. Entry-point imports would defeat the purpose of unit testing."
|
||||
},
|
||||
{
|
||||
"file": "tests/test_cross_os.py",
|
||||
"standard": "documentation",
|
||||
"reason": "Test methods use descriptive names (test_filter_win32_gets_win_and_all, test_missing_doc_raises) that are self-documenting. Adding docstrings to every test function adds noise without value."
|
||||
},
|
||||
{
|
||||
"file": "tests/test_sandbox_check.py",
|
||||
"standard": "architecture",
|
||||
"reason": "Test file lives in tests/ by convention — not in apps/. Standard 3-layer structure applies to production code only."
|
||||
},
|
||||
{
|
||||
"file": "tests/test_sandbox_check.py",
|
||||
"standard": "encapsulation",
|
||||
"reason": "Unit tests must import handlers directly (sandbox_checker, progress) to test them in isolation. Entry-point imports would defeat the purpose of unit testing."
|
||||
},
|
||||
{
|
||||
"file": "tests/test_sandbox_check.py",
|
||||
"standard": "documentation",
|
||||
"reason": "Test methods use descriptive names (test_flag_off_by_default, test_bwrap_functional_live) that are self-documenting. Adding docstrings to 41 test functions adds noise without value."
|
||||
},
|
||||
{
|
||||
"file": "shared/json_handler.py",
|
||||
"standard": "architecture",
|
||||
"reason": "pre-infra leaf — stdlib-only by design, must not import branch dependencies (loads pre-drone for aipass init)"
|
||||
},
|
||||
{
|
||||
"file": "shared/json_handler.py",
|
||||
"standard": "log_visibility",
|
||||
"reason": "pre-infra leaf — stdlib-only by design, must not import branch dependencies (loads pre-drone for aipass init)"
|
||||
},
|
||||
{
|
||||
"file": "shared/json_handler.py",
|
||||
"standard": "trigger",
|
||||
"reason": "pre-infra leaf — stdlib-only by design, must not import branch dependencies (loads pre-drone for aipass init)"
|
||||
},
|
||||
{
|
||||
"file": "shared/json_ops.py",
|
||||
"standard": "architecture",
|
||||
"reason": "pre-infra leaf — stdlib-only by design, must not import branch dependencies (loads pre-drone for aipass init)"
|
||||
},
|
||||
{
|
||||
"file": "shared/json_ops.py",
|
||||
"standard": "log_visibility",
|
||||
"reason": "pre-infra leaf — stdlib-only by design, must not import branch dependencies (loads pre-drone for aipass init)"
|
||||
},
|
||||
{
|
||||
"file": "shared/json_ops.py",
|
||||
"standard": "trigger",
|
||||
"reason": "pre-infra leaf — stdlib-only by design, must not import branch dependencies (loads pre-drone for aipass init)"
|
||||
},
|
||||
{
|
||||
"file": "shared/registry_discovery.py",
|
||||
"standard": "architecture",
|
||||
"reason": "pre-infra leaf — stdlib-only by design, must not import branch dependencies (loads pre-drone for aipass init)"
|
||||
},
|
||||
{
|
||||
"file": "tests/test_shared_bootstrap_safety.py",
|
||||
"standard": "architecture",
|
||||
"reason": "Test file lives in tests/ by convention — not in apps/. Standard 3-layer structure applies to production code only."
|
||||
},
|
||||
{
|
||||
"file": "shared/json_ops.py",
|
||||
"standard": "unused_function",
|
||||
"reason": "backup_json() is consumed by @spawn (cross-branch caller). Appears unused in @aipass-only scan but is a shared API."
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -15,24 +15,28 @@ aipass/
|
||||
├── apps/
|
||||
│ ├── aipass.py # Entry point — subcommand dispatch
|
||||
│ ├── modules/
|
||||
│ │ ├── doctor.py # System health aggregation
|
||||
│ │ ├── doctor.py # System health aggregation + cross-OS pre-flight (--cross-os)
|
||||
│ │ ├── doctor_fix.py # Remediation report (--fix, --json)
|
||||
│ │ ├── doctor_wire.py # Auto-wire prompt helpers
|
||||
│ │ ├── doctor_wire.py # Auto-wire provider settings + stale-deny re-export
|
||||
│ │ ├── handoff.py # CLI handoff (placeholder)
|
||||
│ │ ├── help_chat.py # README-backed Q&A
|
||||
│ │ ├── init_flow.py # 12-stage guided setup
|
||||
│ │ ├── help_chat.py # README-backed Q&A (reads via readme_map handler)
|
||||
│ │ ├── init_flow.py # 10-stage guided setup
|
||||
│ │ ├── install.py # aipass install — one-command bootstrap (clone + setup + init)
|
||||
│ │ └── profile.py # User profile read/write
|
||||
│ ├── handlers/
|
||||
│ │ ├── cross_os/ # Cross-OS pre-flight: gap_registry, preflight, run_record
|
||||
│ │ ├── handoff_platform/ # Platform-specific handoff detection
|
||||
│ │ ├── init/ # bootstrap.py, scaffold_content.py
|
||||
│ │ ├── json/ # JSON read/write utilities
|
||||
│ │ ├── ping_sweep/ # Branch reachability verification
|
||||
│ │ ├── provider_reconcile.py # Stale deny-rule detection + fix
|
||||
│ │ ├── readme_map/ # Live file reads + branch routing
|
||||
│ │ ├── structure_scan/ # Agent placement + pollution detection
|
||||
│ │ ├── system_detect/ # OS, shell, Python, RAM, CPU
|
||||
│ │ └── ui/ # Progress bars, menus, banners
|
||||
│ └── plugins/
|
||||
├── tests/ # 412 passing
|
||||
├── tests/ # 609 passing
|
||||
├── requirements.project.txt # Project-specific Python dependencies
|
||||
├── .trinity/ # Identity + session history + observations
|
||||
└── README.md
|
||||
```
|
||||
@@ -46,7 +50,11 @@ aipass/
|
||||
| `aipass doctor` | System health — structure, registry, hooks, pytest |
|
||||
| `aipass doctor --fix` | Remediation report with `drone @spawn repair` commands |
|
||||
| `aipass doctor --json` | JSON output for structure scan results |
|
||||
| `aipass init` | 12-stage guided setup (resumable) |
|
||||
| `aipass doctor --cross-os` | Cross-OS pre-flight (Layer-3-lite, machine) — OS-gap cross-ref + routing/versions/hookstatus |
|
||||
| `aipass doctor --cross-os --e2e` | ...also runs the real Layer-2 e2e wiring suite (heavy, opt-in) |
|
||||
| `aipass doctor --cross-os --record [PATH]` | Write a machine-filled Run Record for the human Layer-3 acceptance pass |
|
||||
| `aipass init` | 10-stage guided setup (resumable) |
|
||||
| `aipass install` | One-command bootstrap — clone + setup.sh + hooks, then hand off to init (`--no-init`/`--with-init`/`--path`/`--here`) |
|
||||
| `aipass profile` | Show/edit user profile |
|
||||
| `aipass --version` | Version |
|
||||
|
||||
@@ -68,7 +76,7 @@ Humans only. Nothing in AIPass depends on this branch.
|
||||
|
||||
## Tests
|
||||
|
||||
412 passing — `pytest src/aipass/aipass/tests/`
|
||||
609 passing — `pytest src/aipass/aipass/tests/`
|
||||
|
||||
## Known Issues
|
||||
|
||||
@@ -76,4 +84,4 @@ Humans only. Nothing in AIPass depends on this branch.
|
||||
|
||||
## Last Updated
|
||||
|
||||
Last Updated: 2026-05-16
|
||||
Last Updated: 2026-07-05
|
||||
|
||||
@@ -15,11 +15,26 @@ Auto-discovery architecture:
|
||||
- No manual imports or routing needed
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import importlib
|
||||
import importlib.metadata
|
||||
from pathlib import Path
|
||||
from typing import List, Any
|
||||
|
||||
# Windows terminals/pipes default to cp1252, which can't encode the Unicode
|
||||
# Rich emits (✓/✗, box-drawing, arrows). PYTHONUTF8 only affects child
|
||||
# interpreters, not this process's already-open stdout/stderr — so we also
|
||||
# reconfigure the live streams to UTF-8 in place (Python 3.7+). Without this,
|
||||
# `aipass init` scaffolds correctly but crashes printing its success banner
|
||||
# with UnicodeEncodeError ('charmap') on Windows. Mirrors drone/cli.py.
|
||||
if sys.platform == "win32":
|
||||
os.environ.setdefault("PYTHONUTF8", "1") # for child subprocesses
|
||||
for _stream in (sys.stdout, sys.stderr):
|
||||
_reconfigure = getattr(_stream, "reconfigure", None)
|
||||
if _reconfigure is not None:
|
||||
_reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
from aipass.prax import logger
|
||||
|
||||
# =============================================================================
|
||||
@@ -29,9 +44,13 @@ from aipass.prax import logger
|
||||
MODULES_DIR = Path(__file__).parent / "modules"
|
||||
|
||||
|
||||
_import_failures: dict[str, Exception] = {}
|
||||
|
||||
|
||||
def discover_modules() -> List[Any]:
|
||||
"""Auto-discover modules in modules/ directory."""
|
||||
modules = []
|
||||
_import_failures.clear()
|
||||
|
||||
if not MODULES_DIR.exists():
|
||||
return modules
|
||||
@@ -48,18 +67,25 @@ def discover_modules() -> List[Any]:
|
||||
modules.append(module)
|
||||
except Exception as e:
|
||||
logger.error(f"[AIPASS] Failed to load module {module_name}: {e}")
|
||||
_import_failures[file_path.stem] = e
|
||||
|
||||
return modules
|
||||
|
||||
|
||||
def route_command(command: str, args: List[str], modules: List[Any]) -> bool:
|
||||
"""Route command to appropriate module."""
|
||||
"""Route command to appropriate module.
|
||||
|
||||
Returns True on success. Raises on handler crash so callers can
|
||||
distinguish 'not found' (False) from 'found but broken'.
|
||||
"""
|
||||
for module in modules:
|
||||
try:
|
||||
if module.handle_command(command, args):
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.error(f"[AIPASS] Module {module.__name__} error: {e}")
|
||||
mod_name = module.__name__.split(".")[-1]
|
||||
logger.error(f"[AIPASS] Module {mod_name} crashed: {e}")
|
||||
raise
|
||||
return False
|
||||
|
||||
|
||||
@@ -74,14 +100,20 @@ def main():
|
||||
args = sys.argv[1:]
|
||||
|
||||
if len(args) > 0 and args[0] in ["--version", "-V"]:
|
||||
print("aipass 0.1.0")
|
||||
try:
|
||||
version = importlib.metadata.version("aipass")
|
||||
except importlib.metadata.PackageNotFoundError:
|
||||
logger.info("[AIPASS] Package metadata not found, version unknown")
|
||||
version = "unknown"
|
||||
print(f"aipass {version}")
|
||||
return 0
|
||||
|
||||
show_root_help = len(args) == 0 or args[0] in ["--help", "-h"] or (args[0] == "help" and len(args) == 1)
|
||||
if show_root_help:
|
||||
print(f"AIPASS - {len(modules)} modules discovered")
|
||||
for module in modules:
|
||||
name = module.__name__.split(".")[-1]
|
||||
stem = module.__name__.split(".")[-1]
|
||||
name = getattr(module, "COMMAND", stem)
|
||||
desc = (module.__doc__ or "").strip().split("\n")[0] if module.__doc__ else "No description"
|
||||
print(f" {name:20} {desc}")
|
||||
return 0
|
||||
@@ -89,8 +121,34 @@ def main():
|
||||
command = args[0]
|
||||
remaining = args[1:] if len(args) > 1 else []
|
||||
|
||||
if route_command(command, remaining, modules):
|
||||
return 0
|
||||
# Subcommand --help guard: intercept before dispatch
|
||||
if remaining and remaining[0] in ("--help", "-h"):
|
||||
for module in modules:
|
||||
if module.handle_command(command, ["--help"]):
|
||||
return 0
|
||||
print(f"Unknown command: {command}")
|
||||
return 1
|
||||
|
||||
try:
|
||||
if route_command(command, remaining, modules):
|
||||
return 0
|
||||
except Exception as e:
|
||||
print(f"Error: '{command}' crashed: {e}")
|
||||
logger.error(f"[AIPASS] '{command}' traceback", exc_info=True)
|
||||
return 1
|
||||
|
||||
if command.startswith("@"):
|
||||
print(f"{command} is a drone routing target, not an aipass command.")
|
||||
print("aipass is your front-door CLI; drone is the agent router — two separate tools.")
|
||||
print()
|
||||
print(f" Reach an agent: drone {command} ... · drone systems")
|
||||
print(" aipass commands: aipass --help")
|
||||
return 1
|
||||
|
||||
for stem, err in _import_failures.items():
|
||||
if command in (stem, stem.replace("_", "")):
|
||||
print(f"Error: '{command}' failed to load: {err}")
|
||||
return 1
|
||||
|
||||
print(f"Unknown command: {command}")
|
||||
return 1
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
"""cross_os — gap-registry cross-reference + non-mutating pre-flight runners."""
|
||||
|
||||
from aipass.aipass.apps.handlers.cross_os.gap_registry import ( # type: ignore[import-not-found]
|
||||
CrossOsGap,
|
||||
CrossOsGapError,
|
||||
find_gap_doc,
|
||||
gaps_for_platform,
|
||||
load_gaps,
|
||||
os_matches,
|
||||
parse_gap_registry,
|
||||
)
|
||||
from aipass.aipass.apps.handlers.cross_os.preflight import ( # type: ignore[import-not-found]
|
||||
PreflightResult,
|
||||
check_hookstatus,
|
||||
check_routing,
|
||||
check_versions,
|
||||
find_e2e_dir,
|
||||
run_e2e,
|
||||
)
|
||||
from aipass.aipass.apps.handlers.cross_os.run_record import ( # type: ignore[import-not-found]
|
||||
RunRecordError,
|
||||
build_run_record,
|
||||
default_record_path,
|
||||
generate_run_record,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"CrossOsGap",
|
||||
"CrossOsGapError",
|
||||
"PreflightResult",
|
||||
"RunRecordError",
|
||||
"build_run_record",
|
||||
"check_hookstatus",
|
||||
"check_routing",
|
||||
"check_versions",
|
||||
"default_record_path",
|
||||
"find_e2e_dir",
|
||||
"find_gap_doc",
|
||||
"gaps_for_platform",
|
||||
"generate_run_record",
|
||||
"load_gaps",
|
||||
"os_matches",
|
||||
"parse_gap_registry",
|
||||
"run_e2e",
|
||||
]
|
||||
@@ -0,0 +1,167 @@
|
||||
# =================== AIPass ====================
|
||||
# Name: gap_registry.py
|
||||
# Description: Live-parse the cross-OS gap registry and filter by platform
|
||||
# Version: 1.0.0
|
||||
# Created: 2026-07-02
|
||||
# Modified: 2026-07-02
|
||||
# =============================================
|
||||
|
||||
"""Cross-OS gap registry parser — Layer-3-lite pre-flight source.
|
||||
|
||||
Live-reads ``tests/CROSS_OS_TESTING.md`` (read-only to @aipass), parses the
|
||||
"Known cross-OS gap registry" markdown table, and filters rows to the running
|
||||
platform. This is a *machine pre-flight* — it surfaces tracked OS-specific gaps
|
||||
for the box the user is on. It NEVER claims the checklist's human acceptance
|
||||
green ("you watched it work on that OS").
|
||||
|
||||
Fail-to-error contract: if the doc is missing, the section is absent, or no data
|
||||
rows can be parsed, functions raise ``CrossOsGapError`` — they never silently
|
||||
return "no gaps". Callers must surface the error as a WARN/FAIL, not swallow it.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import List, NamedTuple
|
||||
|
||||
from aipass.prax import logger
|
||||
from aipass.aipass.apps.handlers.json import json_handler
|
||||
|
||||
# Path of the source-of-truth doc, relative to the repo root.
|
||||
DOC_RELATIVE = Path("tests") / "CROSS_OS_TESTING.md"
|
||||
|
||||
# Case-insensitive marker identifying the registry section header line.
|
||||
_SECTION_MARKER = "known cross-os gap registry"
|
||||
|
||||
# Expected column count in the registry table: # | Gap | OS | Symptom | Owner | Status
|
||||
_EXPECTED_COLUMNS = 6
|
||||
|
||||
|
||||
class CrossOsGapError(RuntimeError):
|
||||
"""Raised when the cross-OS gap registry cannot be located or parsed."""
|
||||
|
||||
|
||||
class CrossOsGap(NamedTuple):
|
||||
"""One row of the Known cross-OS gap registry table."""
|
||||
|
||||
number: str
|
||||
gap: str
|
||||
os: str
|
||||
symptom: str
|
||||
owner: str
|
||||
status: str
|
||||
|
||||
|
||||
def find_gap_doc(start: Path | None = None) -> Path:
|
||||
"""Search upward from ``start`` (or this file) for ``tests/CROSS_OS_TESTING.md``.
|
||||
|
||||
Portable — derives the repo root by walking ancestors rather than hardcoding
|
||||
an absolute path.
|
||||
|
||||
Raises:
|
||||
CrossOsGapError: if the doc is not found in any ancestor directory.
|
||||
"""
|
||||
base = (start or Path(__file__)).resolve()
|
||||
for parent in [base, *base.parents]:
|
||||
candidate = parent / DOC_RELATIVE
|
||||
if candidate.is_file():
|
||||
return candidate
|
||||
raise CrossOsGapError(f"cross-OS testing doc not found (searched upward from {base} for {DOC_RELATIVE})")
|
||||
|
||||
|
||||
def parse_gap_registry(text: str) -> List[CrossOsGap]:
|
||||
"""Parse the 'Known cross-OS gap registry' table out of the doc text.
|
||||
|
||||
Only rows whose first cell begins with a digit are treated as data rows,
|
||||
which naturally skips the header and the ``|---|`` separator.
|
||||
|
||||
Raises:
|
||||
CrossOsGapError: if the section is missing or no data rows parse.
|
||||
"""
|
||||
lines = text.splitlines()
|
||||
|
||||
section_idx = None
|
||||
for i, line in enumerate(lines):
|
||||
if line.lstrip().startswith("#") and _SECTION_MARKER in line.lower():
|
||||
section_idx = i
|
||||
break
|
||||
if section_idx is None:
|
||||
raise CrossOsGapError("'Known cross-OS gap registry' section not found in doc")
|
||||
|
||||
gaps: List[CrossOsGap] = []
|
||||
for line in lines[section_idx + 1 :]:
|
||||
stripped = line.strip()
|
||||
# Stop at the next top-level section.
|
||||
if stripped.startswith("## "):
|
||||
break
|
||||
if not stripped.startswith("|"):
|
||||
continue
|
||||
cells = [c.strip() for c in stripped.strip("|").split("|")]
|
||||
if len(cells) < _EXPECTED_COLUMNS:
|
||||
continue
|
||||
number = cells[0]
|
||||
# Skip header ("#") and separator ("---") rows — data rows start with a digit.
|
||||
if not number or not number[0].isdigit():
|
||||
continue
|
||||
gaps.append(
|
||||
CrossOsGap(
|
||||
number=number,
|
||||
gap=cells[1],
|
||||
os=cells[2],
|
||||
symptom=cells[3],
|
||||
owner=cells[4],
|
||||
status=cells[5],
|
||||
)
|
||||
)
|
||||
|
||||
if not gaps:
|
||||
raise CrossOsGapError("gap registry table found but no data rows could be parsed")
|
||||
return gaps
|
||||
|
||||
|
||||
def load_gaps(start: Path | None = None) -> List[CrossOsGap]:
|
||||
"""Locate, read, and parse the full gap registry.
|
||||
|
||||
Raises:
|
||||
CrossOsGapError: on missing/unreadable doc or unparseable table.
|
||||
"""
|
||||
doc = find_gap_doc(start)
|
||||
try:
|
||||
raw = doc.read_text(encoding="utf-8")
|
||||
except OSError as exc:
|
||||
raise CrossOsGapError(f"cross-OS testing doc unreadable at {doc}: {exc}") from exc
|
||||
logger.info("[cross_os] parsing gap registry from %s", doc)
|
||||
return parse_gap_registry(raw)
|
||||
|
||||
|
||||
def os_matches(os_cell: str, platform_name: str) -> bool:
|
||||
"""Return True if an OS cell applies to ``platform_name`` (a ``sys.platform`` value).
|
||||
|
||||
Mapping (case-insensitive): 'all' matches every platform; 'win' matches
|
||||
win32; 'mac' matches darwin. So 'Win/mac' matches both win32 and darwin.
|
||||
"""
|
||||
cell = os_cell.lower()
|
||||
if "all" in cell:
|
||||
return True
|
||||
if platform_name == "win32":
|
||||
return "win" in cell
|
||||
if platform_name == "darwin":
|
||||
return "mac" in cell
|
||||
return False
|
||||
|
||||
|
||||
def gaps_for_platform(platform_name: str | None = None, start: Path | None = None) -> List[CrossOsGap]:
|
||||
"""Return only the gap rows relevant to ``platform_name`` (defaults to ``sys.platform``).
|
||||
|
||||
Raises:
|
||||
CrossOsGapError: on any load/parse failure (never silently empty).
|
||||
"""
|
||||
plat = platform_name or sys.platform
|
||||
gaps = load_gaps(start)
|
||||
relevant = [g for g in gaps if os_matches(g.os, plat)]
|
||||
json_handler.log_operation(
|
||||
"cross_os_gap_lookup",
|
||||
{"platform": plat, "total": len(gaps), "relevant": len(relevant)},
|
||||
)
|
||||
return relevant
|
||||
@@ -0,0 +1,230 @@
|
||||
# =================== AIPass ====================
|
||||
# Name: preflight.py
|
||||
# Description: Non-mutating cross-OS pre-flight runners (routing/version/hooks/e2e)
|
||||
# Version: 1.0.0
|
||||
# Created: 2026-07-02
|
||||
# Modified: 2026-07-02
|
||||
# =============================================
|
||||
|
||||
"""Cross-OS pre-flight runners — Layer-3-lite machine checks.
|
||||
|
||||
Each runner probes one machine-provable slice of the cross-OS acceptance
|
||||
checklist and returns a small ``PreflightResult(name, ok, detail)``. Everything
|
||||
here is *non-mutating* and NEVER wakes a citizen: the drone routes exercised
|
||||
(``drone systems``, ``drone @ai_mail --help``, ``drone @hooks status``) only
|
||||
print/route — they do not dispatch work to a branch.
|
||||
|
||||
Robustness contract: every subprocess has a timeout and every runner catches
|
||||
``FileNotFoundError`` / ``TimeoutExpired`` (and other ``OSError``) and turns it
|
||||
into ``ok=False`` with a clear ``detail`` — a runner never crashes the caller.
|
||||
|
||||
These are pre-flight rows. They can NEVER claim the checklist's human green
|
||||
("you watched it work on that OS"); callers must label them pre-flight.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import List, NamedTuple, Sequence, Tuple
|
||||
|
||||
from aipass.prax import logger
|
||||
from aipass.aipass.apps.handlers.json import json_handler
|
||||
|
||||
# Directory (relative to repo root) holding the Layer-2 e2e wiring suite.
|
||||
E2E_RELATIVE = Path("tests") / "e2e"
|
||||
|
||||
# Subprocess timeouts (seconds). Light routes are quick; e2e is heavy (it builds
|
||||
# a wheel and installs it into a fresh venv) so it gets a generous budget.
|
||||
_ROUTE_TIMEOUT = 20
|
||||
_VERSION_TIMEOUT = 15
|
||||
_HOOKSTATUS_TIMEOUT = 20
|
||||
_E2E_TIMEOUT = 600
|
||||
|
||||
# Detail prefix marking an e2e result that could NOT run (infra), so callers can
|
||||
# map it to WARN rather than FAIL. Real pytest failures do not use this prefix.
|
||||
E2E_UNRUNNABLE_PREFIX = "could not run"
|
||||
|
||||
|
||||
class PreflightResult(NamedTuple):
|
||||
"""One non-mutating pre-flight probe outcome."""
|
||||
|
||||
name: str
|
||||
ok: bool
|
||||
detail: str
|
||||
|
||||
|
||||
def _run(cmd: Sequence[str], timeout: int, cwd: str | None = None) -> Tuple[int | None, str]:
|
||||
"""Run ``cmd`` non-interactively; return ``(returncode, combined_output)``.
|
||||
|
||||
Never raises for the expected failure modes: a missing binary yields
|
||||
``(None, "not found: ...")`` and a timeout yields ``(None, "timed out ...")``.
|
||||
"""
|
||||
try:
|
||||
proc = subprocess.run(
|
||||
list(cmd),
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=timeout,
|
||||
cwd=cwd,
|
||||
)
|
||||
return proc.returncode, (proc.stdout or "") + (proc.stderr or "")
|
||||
except FileNotFoundError as exc:
|
||||
logger.warning("[cross_os.preflight] binary not found for %s: %s", cmd, exc)
|
||||
return None, f"not found: {cmd[0]}"
|
||||
except subprocess.TimeoutExpired as exc:
|
||||
logger.warning("[cross_os.preflight] %s timed out after %ss: %s", cmd, timeout, exc)
|
||||
return None, f"timed out after {timeout}s"
|
||||
except OSError as exc:
|
||||
logger.warning("[cross_os.preflight] error running %s: %s", cmd, exc)
|
||||
return None, f"error running {cmd[0]}: {exc}"
|
||||
|
||||
|
||||
def _first_line(output: str) -> str:
|
||||
"""Return the first non-empty stripped line of ``output`` (or "")."""
|
||||
for line in output.splitlines():
|
||||
stripped = line.strip()
|
||||
if stripped:
|
||||
return stripped
|
||||
return ""
|
||||
|
||||
|
||||
def check_routing() -> PreflightResult:
|
||||
"""Verify drone routing (Phase 4): ``drone systems`` + one subprocess route.
|
||||
|
||||
Both ``drone systems`` (4.1) and ``drone @ai_mail --help`` (4.2) must exit 0.
|
||||
These are non-mutating routes — ``--help`` prints usage; neither dispatches
|
||||
work to a citizen.
|
||||
"""
|
||||
sys_rc, sys_out = _run(["drone", "systems"], _ROUTE_TIMEOUT)
|
||||
route_rc, route_out = _run(["drone", "@ai_mail", "--help"], _ROUTE_TIMEOUT)
|
||||
|
||||
ok = sys_rc == 0 and route_rc == 0
|
||||
if ok:
|
||||
detail = "drone systems exit 0; @ai_mail route exit 0"
|
||||
else:
|
||||
problems: List[str] = []
|
||||
if sys_rc != 0:
|
||||
problems.append(f"drone systems -> {sys_rc or _first_line(sys_out)}")
|
||||
if route_rc != 0:
|
||||
problems.append(f"@ai_mail --help -> {route_rc or _first_line(route_out)}")
|
||||
detail = "; ".join(problems)
|
||||
return PreflightResult("routing", ok, detail)
|
||||
|
||||
|
||||
def check_versions() -> PreflightResult:
|
||||
"""Verify ``drone --version`` and ``aipass --version`` exit 0 (Phase 1.3).
|
||||
|
||||
Captures the version strings into the detail.
|
||||
"""
|
||||
drone_rc, drone_out = _run(["drone", "--version"], _VERSION_TIMEOUT)
|
||||
aipass_rc, aipass_out = _run(["aipass", "--version"], _VERSION_TIMEOUT)
|
||||
|
||||
def _ver(label: str, rc: int | None, out: str) -> str:
|
||||
if rc == 0:
|
||||
return _first_line(out)
|
||||
return f"{label} --version failed ({rc}: {_first_line(out)})"
|
||||
|
||||
ok = drone_rc == 0 and aipass_rc == 0
|
||||
detail = f"{_ver('drone', drone_rc, drone_out)}; {_ver('aipass', aipass_rc, aipass_out)}"
|
||||
return PreflightResult("versions", ok, detail)
|
||||
|
||||
|
||||
def check_hookstatus() -> PreflightResult:
|
||||
"""Verify the @hooks per-project config renders (Phase 6.3).
|
||||
|
||||
Note: the checklist labels this ``drone @hooks hookstatus``, but that command
|
||||
name does not route on the current drone build (it returns "Unknown command"
|
||||
— gap #9 in the wild). The real, non-mutating subcommand that renders the
|
||||
per-project hook config is ``drone @hooks status``, which is what Phase 6.3
|
||||
actually verifies, so that is what we probe.
|
||||
"""
|
||||
rc, out = _run(["drone", "@hooks", "status"], _HOOKSTATUS_TIMEOUT)
|
||||
ok = rc == 0
|
||||
detail = _first_line(out) if ok else f"drone @hooks status exit {rc}: {_first_line(out)}"
|
||||
return PreflightResult("hookstatus", ok, detail)
|
||||
|
||||
|
||||
def find_e2e_dir(start: Path | None = None) -> Path | None:
|
||||
"""Search upward from ``start`` (or this file) for ``tests/e2e``.
|
||||
|
||||
Portable — walks ancestors rather than hardcoding a path (mirrors the
|
||||
gap_registry ``find_gap_doc`` pattern). Returns ``None`` if not found.
|
||||
"""
|
||||
base = (start or Path(__file__)).resolve()
|
||||
for parent in [base, *base.parents]:
|
||||
candidate = parent / E2E_RELATIVE
|
||||
if candidate.is_dir():
|
||||
return candidate
|
||||
return None
|
||||
|
||||
|
||||
def _resolve_pytest(repo_root: Path) -> Tuple[List[str], str] | None:
|
||||
"""Resolve a pytest invocation for the current box.
|
||||
|
||||
Prefers ``<repo>/.venv/<bin>/pytest`` (system ``python`` may be absent);
|
||||
falls back to ``sys.executable -m pytest``. Returns ``(argv_prefix, source)``
|
||||
or ``None`` if neither can be resolved.
|
||||
"""
|
||||
bin_dir = "Scripts" if os.name == "nt" else "bin"
|
||||
exe = "pytest.exe" if os.name == "nt" else "pytest"
|
||||
venv_pytest = repo_root / ".venv" / bin_dir / exe
|
||||
if venv_pytest.is_file():
|
||||
return [str(venv_pytest)], "venv pytest"
|
||||
if sys.executable:
|
||||
return [sys.executable, "-m", "pytest"], "sys.executable -m pytest"
|
||||
return None
|
||||
|
||||
|
||||
def run_e2e(start: Path | None = None) -> PreflightResult:
|
||||
"""Run the Layer-2 e2e wiring suite (``pytest tests/e2e -q``). HEAVY.
|
||||
|
||||
Only call this when explicitly opted into (``--e2e``): the suite builds the
|
||||
aipass wheel and installs it into a fresh venv. ``ok=True`` only when every
|
||||
test passes (pytest exit 0). Un-runnable cases (dir missing, no pytest,
|
||||
timeout, crash) return ``ok=False`` with a ``could not run`` detail so the
|
||||
caller can render them as WARN rather than a hard FAIL.
|
||||
"""
|
||||
e2e_dir = find_e2e_dir(start)
|
||||
if e2e_dir is None:
|
||||
return PreflightResult("e2e", False, f"{E2E_UNRUNNABLE_PREFIX}: e2e dir not found")
|
||||
|
||||
repo_root = e2e_dir.parent.parent
|
||||
resolved = _resolve_pytest(repo_root)
|
||||
if resolved is None:
|
||||
detail = f"{E2E_UNRUNNABLE_PREFIX}: pytest unavailable (no venv pytest, no interpreter)"
|
||||
return _log_e2e(PreflightResult("e2e", False, detail))
|
||||
|
||||
argv_prefix, source = resolved
|
||||
logger.info("[cross_os.preflight] running e2e suite via %s (cwd=%s)", source, repo_root)
|
||||
rc, out = _run([*argv_prefix, str(e2e_dir), "-q"], _E2E_TIMEOUT, cwd=str(repo_root))
|
||||
|
||||
if rc is None:
|
||||
# Timeout / missing binary / OSError — infra, not a real test failure.
|
||||
return _log_e2e(PreflightResult("e2e", False, f"{E2E_UNRUNNABLE_PREFIX}: {out}"))
|
||||
|
||||
summary = _e2e_summary(out)
|
||||
if rc == 0:
|
||||
return _log_e2e(PreflightResult("e2e", True, summary))
|
||||
# Non-zero: could be real failures OR pytest itself being absent under
|
||||
# `python -m pytest`. Distinguish so the caller can WARN vs FAIL.
|
||||
if "no module named pytest" in out.lower():
|
||||
return _log_e2e(PreflightResult("e2e", False, f"{E2E_UNRUNNABLE_PREFIX}: pytest not importable"))
|
||||
return _log_e2e(PreflightResult("e2e", False, summary))
|
||||
|
||||
|
||||
def _log_e2e(result: PreflightResult) -> PreflightResult:
|
||||
"""Record the e2e pre-flight outcome via json_handler, then return it."""
|
||||
json_handler.log_operation("cross_os_e2e_preflight", {"ok": result.ok, "detail": result.detail})
|
||||
return result
|
||||
|
||||
|
||||
def _e2e_summary(output: str) -> str:
|
||||
"""Extract pytest's terminal summary line (e.g. '14 passed', '2 failed...')."""
|
||||
for line in reversed(output.splitlines()):
|
||||
stripped = line.strip().strip("=").strip()
|
||||
if any(tok in stripped for tok in ("passed", "failed", "error", "no tests ran")):
|
||||
return stripped
|
||||
return _first_line(output) or "no pytest summary parsed"
|
||||
@@ -0,0 +1,243 @@
|
||||
# =================== AIPass ====================
|
||||
# Name: run_record.py
|
||||
# Description: Machine pre-flight Run Record generator for the cross-OS checklist
|
||||
# Version: 1.0.0
|
||||
# Created: 2026-07-02
|
||||
# Modified: 2026-07-02
|
||||
# =============================================
|
||||
|
||||
"""Cross-OS Run Record generator — Layer-3-lite machine pre-flight DRAFT.
|
||||
|
||||
Emits a text Run Record block modelled on the "## Run Record" fenced template in
|
||||
``tests/CROSS_OS_TESTING.md`` (that block is the format source-of-truth). The
|
||||
block is *constructed in code* rather than string-substituted into the parsed
|
||||
template on purpose: the load-bearing invariant here is the machine/human
|
||||
boundary — the machine fills ONLY what it can prove (env facts + the
|
||||
non-mutating pre-flight rows) and every human-only row (clean install,
|
||||
interactive init, daemons, audible sound, PTY, per-branch matrix, overall
|
||||
verdict, commit, tester) is left blank or marked ``— human``. Constructing the
|
||||
block gives exact control over that boundary; substituting values line-by-line
|
||||
into the free-text template would be brittle and could silently tick a human row.
|
||||
|
||||
Env facts are detected with stdlib (``platform`` / ``os``) directly — the same
|
||||
detection ``system_detector`` performs — because the seedgo cross-handler rule
|
||||
forbids this handler importing another handler.
|
||||
|
||||
A machine can NEVER claim the checklist's human green ("you watched it work on
|
||||
that OS"). This artifact is explicitly a pre-flight DRAFT that a person must
|
||||
complete by running the real Layer-3 acceptance pass.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import platform
|
||||
import sys
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import List
|
||||
|
||||
from aipass.prax import logger
|
||||
from aipass.aipass.shared.registry_discovery import find_registry
|
||||
|
||||
from aipass.aipass.apps.handlers.cross_os.gap_registry import CrossOsGapError, gaps_for_platform
|
||||
from aipass.aipass.apps.handlers.cross_os.preflight import (
|
||||
E2E_UNRUNNABLE_PREFIX,
|
||||
check_hookstatus,
|
||||
check_routing,
|
||||
run_e2e,
|
||||
)
|
||||
from aipass.aipass.apps.handlers.json import json_handler
|
||||
|
||||
# Marker glyphs for the record. Match the doc's Run Record block, which uses the
|
||||
# ✅ / ❌ emoji rather than the terminal ✓ / ✗ glyphs.
|
||||
_PASS = "✅"
|
||||
_FAIL = "❌"
|
||||
# Un-ticked human box — a person must still run and mark the real pass.
|
||||
_HUMAN = "⬜ — human"
|
||||
|
||||
# Horizontal rule used by the doc's Run Record block.
|
||||
_RULE = "─────────────────────────────────────────────"
|
||||
|
||||
|
||||
class RunRecordError(RuntimeError):
|
||||
"""Raised when the Run Record file cannot be written."""
|
||||
|
||||
|
||||
def _os_name() -> str:
|
||||
"""OS family name (e.g. 'Linux', 'Darwin', 'Windows')."""
|
||||
return platform.system() or "unknown"
|
||||
|
||||
|
||||
def _resolve_aipass_home() -> str:
|
||||
"""Resolve AIPASS_HOME from the env, else the discovered registry parent.
|
||||
|
||||
Returns "" (blank) if neither is available — a blank row is honest; we never
|
||||
invent a path.
|
||||
"""
|
||||
home = os.environ.get("AIPASS_HOME", "").strip()
|
||||
if home:
|
||||
return home
|
||||
registry = find_registry(package_root=str(Path(__file__).resolve().parent))
|
||||
if registry.exists():
|
||||
return str(registry.parent)
|
||||
return ""
|
||||
|
||||
|
||||
def _env_lines() -> List[str]:
|
||||
"""Build the machine-auto-filled environment header lines (Phase 0 facts)."""
|
||||
os_desc = f"{_os_name()} {platform.release()}".strip()
|
||||
shell_path = os.environ.get("SHELL", "")
|
||||
shell_name = Path(shell_path).name if shell_path else "unknown"
|
||||
term = os.environ.get("TERM", "").strip() or "unknown"
|
||||
today = datetime.now().strftime("%Y-%m-%d")
|
||||
|
||||
return [
|
||||
"AIPass Cross-OS Run Record",
|
||||
f"Machine/VM : {platform.node() or 'unknown'}",
|
||||
f"OS + version : {os_desc}",
|
||||
f"Arch : {platform.machine() or 'unknown'}",
|
||||
f"Python : {platform.python_version()}",
|
||||
f"Shell / term : {shell_name} / {term}",
|
||||
f"AIPASS_HOME : {_resolve_aipass_home()}",
|
||||
# Commit stays blank — no git here; a human fills it (hint inline).
|
||||
"Commit (drone @git log -1) : ← fill via drone @git log -1",
|
||||
# Tester stays blank (human); Date is machine-knowable.
|
||||
f"Tester : Date : {today}",
|
||||
]
|
||||
|
||||
|
||||
def _verdict(ok: bool) -> str:
|
||||
"""Map a pre-flight boolean to the machine glyph + a pre-flight label."""
|
||||
glyph = _PASS if ok else _FAIL
|
||||
return f"{glyph} pre-flight (machine)"
|
||||
|
||||
|
||||
def _phase2_line(run_heavy_e2e: bool) -> str:
|
||||
"""Phase 2 (e2e) line — only auto-filled when the heavy suite was opted into."""
|
||||
label = "Phase 2 e2e suite (14/14) ...."
|
||||
if not run_heavy_e2e:
|
||||
return f"{label} {_HUMAN} notes: — not run (pass --e2e to run it)"
|
||||
result = run_e2e()
|
||||
if result.ok:
|
||||
return f"{label} {_verdict(True)} notes: {result.detail}"
|
||||
if result.detail.startswith(E2E_UNRUNNABLE_PREFIX):
|
||||
# Infra could not run the suite — WARN-ish, not a proven fail.
|
||||
return f"{label} ⚠️ could not run (machine) notes: {result.detail}"
|
||||
return f"{label} {_verdict(False)} notes: {result.detail}"
|
||||
|
||||
|
||||
def _phase_lines(run_heavy_e2e: bool) -> List[str]:
|
||||
"""Build the Phase 0–7 + per-branch lines, machine-proving only what it can."""
|
||||
routing = check_routing()
|
||||
hooks = check_hookstatus()
|
||||
|
||||
return [
|
||||
# Phase 0 — the machine captured the env above, so this is proven.
|
||||
f"Phase 0 env capture .......... {_verdict(True)} notes: captured above",
|
||||
# Phase 1 — clean install (setup.sh / .venv) is pre-init + human.
|
||||
f"Phase 1 clean install ........ {_HUMAN} notes:",
|
||||
_phase2_line(run_heavy_e2e),
|
||||
# Phase 3 — real scaffold + interactive init is human (PTY).
|
||||
f"Phase 3 aipass init .......... {_HUMAN} notes:",
|
||||
# Phase 4 — drone routing is non-mutating and machine-provable.
|
||||
f"Phase 4 drone routing ........ {_verdict(routing.ok)} notes: {routing.detail}",
|
||||
# Phase 5 — daemons (os.kill / start_new_session) are mutating + human.
|
||||
f"Phase 5 daemons .............. {_HUMAN} notes:",
|
||||
# Phase 6 — hookstatus config renders (machine); audible sound is human.
|
||||
f"Phase 6 hooks + sound ........ {_verdict(hooks.ok)} hookstatus; 🔊 sound {_HUMAN} notes: {hooks.detail}",
|
||||
# Phase 7 — interactive PTY layer is human-only.
|
||||
f"Phase 7 interactive .......... {_HUMAN} notes:",
|
||||
# Per-branch smoke matrix is a human pass.
|
||||
f"Per-branch matrix (13) ....... {_HUMAN} reds:",
|
||||
]
|
||||
|
||||
|
||||
def _watch_lines(platform_name: str) -> List[str]:
|
||||
"""Build the tracked-gap watch-item lines for this platform.
|
||||
|
||||
Reads the live gap registry; on any registry error, degrades to a single
|
||||
note line (never crashes the record — it is primarily an env artifact).
|
||||
"""
|
||||
lines = ["Watch items (tracked cross-OS gaps for this platform):"]
|
||||
try:
|
||||
gaps = gaps_for_platform(platform_name)
|
||||
except CrossOsGapError as exc:
|
||||
logger.warning("[cross_os.run_record] gap registry unavailable: %s", exc)
|
||||
lines.append(f" - registry unavailable — {exc}")
|
||||
return lines
|
||||
|
||||
if not gaps:
|
||||
lines.append(f" - none tracked for {platform_name}")
|
||||
return lines
|
||||
|
||||
for gap in gaps:
|
||||
lines.append(f" - gap #{gap.number} [{gap.status}] {gap.symptom} — owner {gap.owner}")
|
||||
return lines
|
||||
|
||||
|
||||
def build_run_record(run_heavy_e2e: bool = False, platform_name: str | None = None) -> str:
|
||||
"""Build the full machine pre-flight Run Record text block.
|
||||
|
||||
Auto-fills the env header + the machine-provable phase rows (0/4/6, plus 2
|
||||
when ``run_heavy_e2e``); leaves every human-only row blank/marked. The output
|
||||
mirrors the "## Run Record" template in tests/CROSS_OS_TESTING.md.
|
||||
"""
|
||||
plat = platform_name or sys.platform
|
||||
|
||||
header = [
|
||||
"NOTE: machine pre-flight DRAFT — rows marked '(machine)' are auto-captured pre-flight",
|
||||
"only; they are NOT the checklist's human green. A human must complete every '— human'",
|
||||
"row and run the real Layer-3 acceptance pass before this record counts.",
|
||||
"",
|
||||
]
|
||||
|
||||
body: List[str] = []
|
||||
body.append(_RULE)
|
||||
body.extend(_env_lines())
|
||||
body.append(_RULE)
|
||||
body.extend(_phase_lines(run_heavy_e2e))
|
||||
body.append(_RULE)
|
||||
body.extend(_watch_lines(plat))
|
||||
body.append("")
|
||||
body.append("New gaps found (file + assign):")
|
||||
body.append("")
|
||||
body.append(f"Overall verdict: {_HUMAN} (PASS / PARTIAL / FAIL — after the real pass)")
|
||||
body.append(_RULE)
|
||||
|
||||
return "\n".join([*header, *body]) + "\n"
|
||||
|
||||
|
||||
def default_record_path() -> Path:
|
||||
"""Return the default record path in CWD (mirrors the doc's log naming)."""
|
||||
return Path.cwd() / f"aipass-crossos-record-{_os_name().lower()}.txt"
|
||||
|
||||
|
||||
def generate_run_record(path: str | None = None, run_heavy_e2e: bool = False) -> Path:
|
||||
"""Build and write the Run Record; return the written path.
|
||||
|
||||
Args:
|
||||
path: Destination file (``--record`` value). If None, a sensible default
|
||||
in CWD is used.
|
||||
run_heavy_e2e: When True, run and record the heavy Phase-2 e2e result.
|
||||
|
||||
Raises:
|
||||
RunRecordError: if the file cannot be written (OSError) — never crashes.
|
||||
"""
|
||||
content = build_run_record(run_heavy_e2e=run_heavy_e2e)
|
||||
target = Path(path) if path else default_record_path()
|
||||
try:
|
||||
parent = target.parent
|
||||
if parent and not parent.exists():
|
||||
parent.mkdir(parents=True, exist_ok=True)
|
||||
target.write_text(content, encoding="utf-8")
|
||||
except OSError as exc:
|
||||
logger.error("[cross_os.run_record] could not write record to %s: %s", target, exc)
|
||||
raise RunRecordError(f"could not write Run Record to {target}: {exc}") from exc
|
||||
|
||||
json_handler.log_operation(
|
||||
"cross_os_run_record",
|
||||
{"path": str(target), "e2e": run_heavy_e2e},
|
||||
)
|
||||
logger.info("[cross_os.run_record] wrote machine pre-flight record to %s", target)
|
||||
return target
|
||||
@@ -11,15 +11,15 @@ Init Bootstrap Handler - PRIVATE implementation
|
||||
|
||||
Business logic for `aipass init`. Creates the project scaffold:
|
||||
1. {NAME}_REGISTRY.json — project registry with UUID
|
||||
2. .aipass/aipass_global_prompt.md — global prompt (injected every turn)
|
||||
2. .aipass/tier0_kernel.md — tier 0 kernel prompt (every turn)
|
||||
2b..aipass/tier1_navmap.md — tier 1 navigation map (periodic)
|
||||
3. CLAUDE.md — project prompt (Claude Code reads this)
|
||||
4. AGENTS.md — Codex equivalent of CLAUDE.md
|
||||
5. README.md — getting started guide
|
||||
6. STATUS.local.md — project status
|
||||
7. .gitignore — standard AIPass ignores
|
||||
8. .claude/settings.json — Claude Code hooks configuration
|
||||
9. src/ — directory where agents live
|
||||
10. .ai_mail.local/inbox.json — empty project mailbox
|
||||
6. .gitignore — standard AIPass ignores
|
||||
7. .claude/settings.json — Claude Code hooks configuration
|
||||
8. src/ — directory where agents live
|
||||
9. .ai_mail.local/inbox.json — empty project mailbox
|
||||
|
||||
Projects are NOT citizens — no .trinity/ directory. Identity lives in the
|
||||
registry JSON. Init is re-runnable: existing files are skipped, not errors.
|
||||
@@ -33,8 +33,10 @@ RULES:
|
||||
import importlib.util
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import tempfile
|
||||
import uuid
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
@@ -43,59 +45,28 @@ from aipass.aipass.apps.handlers.init import scaffold_content as sc
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Hooks are NOT distributed to projects. All hooks fire from provider
|
||||
# settings (~/.claude/settings.json), installed by setup.sh. Provider hooks
|
||||
# use CWD-walking patterns that work from any directory in any project.
|
||||
# Hook files are shipped as reference copies only (for debugging/inspection).
|
||||
HOOKS_TO_SHIP = [
|
||||
"branch_prompt_loader.py",
|
||||
"email_notification.py",
|
||||
"identity_injector.py",
|
||||
"pre_compact.py",
|
||||
"auto_fix_diagnostics.py",
|
||||
"pre_edit_gate.py",
|
||||
"subagent_stop_gate.py",
|
||||
_STALE_MANAGED_FILES: list[Path] = [
|
||||
Path(".aipass") / "aipass_global_prompt.md",
|
||||
]
|
||||
|
||||
|
||||
def _ship_hooks(aipass_home: str, target: Path) -> list[str]:
|
||||
"""Copy enforcement + injector hooks from AIPass install to target project.
|
||||
|
||||
Copies each hook file to {target}/.claude/hooks/. Looks for hooks in two
|
||||
locations (first match wins):
|
||||
1. {aipass_home}/.claude/hooks/ — dev install (git clone)
|
||||
2. aipass/_hooks/ — pip install (wheel-bundled)
|
||||
|
||||
Skips audio hooks. Overwrites existing files only if source content
|
||||
differs (idempotent re-sync). Returns list of files written.
|
||||
"""
|
||||
source_dir = Path(aipass_home) / ".claude" / "hooks"
|
||||
if not source_dir.is_dir():
|
||||
# Fallback: pip install bundles hooks at aipass/_hooks/ inside the package
|
||||
package_hooks = Path(__file__).resolve().parents[4] / "_hooks"
|
||||
if package_hooks.is_dir():
|
||||
source_dir = package_hooks
|
||||
else:
|
||||
logger.info("No hooks directory at %s or %s — skipping", source_dir, package_hooks)
|
||||
return []
|
||||
|
||||
dest_dir = target / ".claude" / "hooks"
|
||||
dest_dir.mkdir(parents=True, exist_ok=True)
|
||||
shipped: list[str] = []
|
||||
|
||||
for hook_name in HOOKS_TO_SHIP:
|
||||
src = source_dir / hook_name
|
||||
dst = dest_dir / hook_name
|
||||
if not src.exists():
|
||||
logger.info("Hook %s not found at %s — skipping", hook_name, src)
|
||||
def is_throwaway_path(path: str | Path) -> bool:
|
||||
"""True if path is under a temp dir or Claude Code scratchpad."""
|
||||
resolved = str(Path(path).resolve())
|
||||
tmp_roots = [tempfile.gettempdir()]
|
||||
if os.name == "posix":
|
||||
tmp_roots.append("/tmp")
|
||||
for root in tmp_roots:
|
||||
try:
|
||||
r = str(Path(root).resolve())
|
||||
except OSError:
|
||||
logger.info("is_throwaway_path: could not resolve %s", root)
|
||||
continue
|
||||
src_content = src.read_bytes()
|
||||
if dst.exists() and dst.read_bytes() == src_content:
|
||||
continue
|
||||
shutil.copy2(src, dst)
|
||||
shipped.append(str(dst))
|
||||
|
||||
return shipped
|
||||
if resolved == r or resolved.startswith(r + os.sep):
|
||||
return True
|
||||
if "scratchpad" in resolved.lower():
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _sanitize_name(raw: str) -> str:
|
||||
@@ -124,14 +95,6 @@ def _detect_aipass_home() -> str | None:
|
||||
return None
|
||||
|
||||
|
||||
def _resolve_global_prompt(name: str, aipass_home: str | None, dest: Path) -> str:
|
||||
"""Resolve global prompt content from source template or fallback generator."""
|
||||
source = Path(aipass_home) / ".aipass" / "project_global_prompt.md" if aipass_home else None
|
||||
if source and source.is_file():
|
||||
return source.read_text(encoding="utf-8").replace("{name}", name)
|
||||
return sc.with_source(sc.global_prompt_md(name), dest)
|
||||
|
||||
|
||||
def _hook_fingerprint(hook_entry: dict) -> str:
|
||||
"""Extract a comparable fingerprint from a hook entry."""
|
||||
commands = []
|
||||
@@ -201,6 +164,52 @@ def _merge_settings(existing: dict, generated: dict) -> dict:
|
||||
return merged
|
||||
|
||||
|
||||
def _merge_hooks_json(existing: dict, template: dict) -> dict:
|
||||
"""Union-merge hooks.json: preserve user enabled values, add new hooks/events."""
|
||||
merged: dict = {}
|
||||
meta_keys = {"_comment", "hooks_enabled"}
|
||||
|
||||
if "_comment" in template:
|
||||
merged["_comment"] = template["_comment"]
|
||||
elif "_comment" in existing:
|
||||
merged["_comment"] = existing["_comment"]
|
||||
|
||||
if "hooks_enabled" in existing:
|
||||
merged["hooks_enabled"] = existing["hooks_enabled"]
|
||||
elif "hooks_enabled" in template:
|
||||
merged["hooks_enabled"] = template["hooks_enabled"]
|
||||
|
||||
all_events: set[str] = set()
|
||||
for key in existing:
|
||||
if key not in meta_keys:
|
||||
all_events.add(key)
|
||||
for key in template:
|
||||
if key not in meta_keys:
|
||||
all_events.add(key)
|
||||
|
||||
for event in sorted(all_events):
|
||||
existing_hooks = existing.get(event, {})
|
||||
template_hooks = template.get(event, {})
|
||||
merged_hooks: dict = {}
|
||||
|
||||
for hook_name, hook_data in existing_hooks.items():
|
||||
merged_hooks[hook_name] = dict(hook_data)
|
||||
|
||||
for hook_name, hook_data in template_hooks.items():
|
||||
if hook_name in merged_hooks:
|
||||
user_enabled = merged_hooks[hook_name].get("enabled")
|
||||
merged_hooks[hook_name] = dict(hook_data)
|
||||
if user_enabled is not None:
|
||||
merged_hooks[hook_name]["enabled"] = user_enabled
|
||||
else:
|
||||
merged_hooks[hook_name] = dict(hook_data)
|
||||
|
||||
if merged_hooks:
|
||||
merged[event] = merged_hooks
|
||||
|
||||
return merged
|
||||
|
||||
|
||||
def _claude_settings(aipass_home: str | None = None) -> str:
|
||||
"""Generate .claude/settings.json — env and permissions only.
|
||||
|
||||
@@ -221,14 +230,19 @@ def _claude_settings(aipass_home: str | None = None) -> str:
|
||||
|
||||
data["permissions"] = {
|
||||
"deny": [
|
||||
"Bash(rm -rf *)",
|
||||
"Bash(git push --force*)",
|
||||
"Bash(git reset --hard*)",
|
||||
"EnterPlanMode",
|
||||
],
|
||||
}
|
||||
|
||||
if aipass_home:
|
||||
if aipass_home and not is_throwaway_path(aipass_home):
|
||||
data["env"] = {"AIPASS_HOME": aipass_home}
|
||||
elif aipass_home:
|
||||
logger.warning(
|
||||
"AIPASS_HOME '%s' is a throwaway path — not writing to settings",
|
||||
aipass_home,
|
||||
)
|
||||
return json.dumps(data, indent=2, ensure_ascii=False) + "\n"
|
||||
|
||||
|
||||
@@ -332,10 +346,24 @@ def init_project(target: Path, project_name: str | None = None) -> dict:
|
||||
aipass_dir = target / ".aipass"
|
||||
aipass_dir.mkdir(exist_ok=True)
|
||||
|
||||
global_prompt_path = aipass_dir / "aipass_global_prompt.md"
|
||||
if not global_prompt_path.exists():
|
||||
global_prompt_path.write_text(_resolve_global_prompt(name, aipass_home, global_prompt_path), encoding="utf-8")
|
||||
created.append(str(global_prompt_path))
|
||||
# 2. .aipass/tier0_kernel.md + tier1_navmap.md — tiered prompt injection
|
||||
for tier_file in ("tier0_kernel.md", "tier1_navmap.md"):
|
||||
tier_dest = aipass_dir / tier_file
|
||||
if not tier_dest.exists() and aipass_home:
|
||||
tier_src = Path(aipass_home) / ".aipass" / tier_file
|
||||
if tier_src.is_file():
|
||||
shutil.copy2(str(tier_src), str(tier_dest))
|
||||
created.append(str(tier_dest))
|
||||
|
||||
# 2b. .aipass/hooks.json — project hook config from template
|
||||
hooks_json_path = aipass_dir / "hooks.json"
|
||||
if not hooks_json_path.exists() and aipass_home:
|
||||
template = Path(aipass_home) / ".aipass" / "project_hooks.json"
|
||||
if template.is_file():
|
||||
shutil.copy2(str(template), str(hooks_json_path))
|
||||
created.append(str(hooks_json_path))
|
||||
else:
|
||||
logger.info("hooks template not found at %s — skipping", template)
|
||||
|
||||
# 3-5. CLAUDE.md, AGENTS.md — project templates or AIPass source
|
||||
for md_name in ("CLAUDE.md", "AGENTS.md"):
|
||||
@@ -347,6 +375,9 @@ def init_project(target: Path, project_name: str | None = None) -> dict:
|
||||
content = template.read_text(encoding="utf-8").replace("{name}", name)
|
||||
dest.write_text(content, encoding="utf-8")
|
||||
created.append(str(dest))
|
||||
elif md_name == "AGENTS.md":
|
||||
dest.write_text(sc.agents_md(name), encoding="utf-8")
|
||||
created.append(str(dest))
|
||||
else:
|
||||
source = Path(aipass_home) / md_name if aipass_home else None
|
||||
if source and source.is_file():
|
||||
@@ -362,16 +393,7 @@ def init_project(target: Path, project_name: str | None = None) -> dict:
|
||||
readme_md_path.write_text(readme_content, encoding="utf-8")
|
||||
created.append(str(readme_md_path))
|
||||
|
||||
# 7. STATUS.local.md
|
||||
status_md_path = target / "STATUS.local.md"
|
||||
if not status_md_path.exists():
|
||||
status_md_path.write_text(
|
||||
f"# {name}\n\n**State:** New\n**Last update:** {today}\n\n## Current Work\n\n## Known Issues\n- None\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
created.append(str(status_md_path))
|
||||
|
||||
# 8. .gitignore
|
||||
# 7. .gitignore
|
||||
gitignore_path = target / ".gitignore"
|
||||
if not gitignore_path.exists():
|
||||
gitignore_path.write_text(sc.gitignore(), encoding="utf-8")
|
||||
@@ -395,11 +417,6 @@ def init_project(target: Path, project_name: str | None = None) -> dict:
|
||||
prep_path.write_text(sc.prep_md(), encoding="utf-8")
|
||||
created.append(str(prep_path))
|
||||
|
||||
# 9d. Ship enforcement + injector hooks from AIPass install
|
||||
if aipass_home:
|
||||
shipped = _ship_hooks(aipass_home, target)
|
||||
created.extend(shipped)
|
||||
|
||||
# 10. src/<project>/ package structure (pip-installable from day one)
|
||||
package_name = raw_name.lower().replace("-", "_").replace(" ", "_")
|
||||
src_dir = target / "src"
|
||||
@@ -453,7 +470,7 @@ def update_project(target: Path) -> dict:
|
||||
"""Update managed scaffold files in an existing AIPass project.
|
||||
|
||||
Overwrites managed prompt and config files with the latest templates while
|
||||
leaving all user-owned files (registry, README, STATUS.local.md, .gitignore,
|
||||
leaving all user-owned files (registry, README, .gitignore,
|
||||
src/) untouched.
|
||||
|
||||
Args:
|
||||
@@ -487,6 +504,7 @@ def update_project(target: Path) -> dict:
|
||||
updated: list[str] = []
|
||||
already_current: list[str] = []
|
||||
skipped: list[str] = []
|
||||
removed: list[str] = []
|
||||
aipass_home: str | None = None
|
||||
|
||||
# Managed directories — create if missing (graceful recovery).
|
||||
@@ -498,14 +516,21 @@ def update_project(target: Path) -> dict:
|
||||
|
||||
# --- Managed files: write only when content has changed ---
|
||||
|
||||
global_prompt_path = aipass_dir / "aipass_global_prompt.md"
|
||||
aipass_home = aipass_home or _detect_aipass_home()
|
||||
generated = _resolve_global_prompt(name, aipass_home, global_prompt_path)
|
||||
if not global_prompt_path.exists() or global_prompt_path.read_text(encoding="utf-8") != generated:
|
||||
global_prompt_path.write_text(generated, encoding="utf-8")
|
||||
updated.append(str(global_prompt_path))
|
||||
else:
|
||||
already_current.append(str(global_prompt_path))
|
||||
|
||||
# tier0_kernel.md + tier1_navmap.md — tiered prompt injection
|
||||
for tier_file in ("tier0_kernel.md", "tier1_navmap.md"):
|
||||
tier_dest = aipass_dir / tier_file
|
||||
tier_src = Path(aipass_home) / ".aipass" / tier_file if aipass_home else None
|
||||
if tier_src and tier_src.is_file():
|
||||
canonical = tier_src.read_text(encoding="utf-8")
|
||||
if not tier_dest.exists() or tier_dest.read_text(encoding="utf-8") != canonical:
|
||||
tier_dest.write_text(canonical, encoding="utf-8")
|
||||
updated.append(str(tier_dest))
|
||||
else:
|
||||
already_current.append(str(tier_dest))
|
||||
elif tier_dest.exists():
|
||||
already_current.append(str(tier_dest))
|
||||
|
||||
# settings.json — smart merge: preserve user hooks + env, update AIPass hooks
|
||||
settings_path = claude_dir / "settings.json"
|
||||
@@ -531,6 +556,34 @@ def update_project(target: Path) -> dict:
|
||||
else:
|
||||
already_current.append(str(settings_path))
|
||||
|
||||
# hooks.json — union-merge: preserve user enabled, add new hooks from template
|
||||
hooks_json_path = aipass_dir / "hooks.json"
|
||||
hook_home = aipass_home or _detect_aipass_home()
|
||||
template_path = Path(hook_home) / ".aipass" / "project_hooks.json" if hook_home else None
|
||||
if template_path and template_path.is_file():
|
||||
template_data = json.loads(template_path.read_text(encoding="utf-8"))
|
||||
if hooks_json_path.exists():
|
||||
try:
|
||||
existing_hooks = json.loads(hooks_json_path.read_text(encoding="utf-8"))
|
||||
except json.JSONDecodeError as exc:
|
||||
logger.info("hooks.json parse failed, rebuilding: %s", exc)
|
||||
existing_hooks = {}
|
||||
merged_hooks = _merge_hooks_json(existing_hooks, template_data)
|
||||
merged_hooks_content = json.dumps(merged_hooks, indent=2, ensure_ascii=False) + "\n"
|
||||
if existing_hooks != merged_hooks:
|
||||
hooks_json_path.write_text(merged_hooks_content, encoding="utf-8")
|
||||
updated.append(str(hooks_json_path))
|
||||
else:
|
||||
already_current.append(str(hooks_json_path))
|
||||
else:
|
||||
hooks_json_path.write_text(
|
||||
json.dumps(template_data, indent=2, ensure_ascii=False) + "\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
updated.append(str(hooks_json_path))
|
||||
elif hooks_json_path.exists():
|
||||
already_current.append(str(hooks_json_path))
|
||||
|
||||
# CLAUDE.md, AGENTS.md — sync from project templates or AIPass source
|
||||
for md_name in ("CLAUDE.md", "AGENTS.md"):
|
||||
dest = target / md_name
|
||||
@@ -557,17 +610,10 @@ def update_project(target: Path) -> dict:
|
||||
else:
|
||||
already_current.append(str(prep_path))
|
||||
|
||||
# Re-sync enforcement + injector hooks from AIPass install
|
||||
hook_home = aipass_home or _detect_aipass_home()
|
||||
if hook_home:
|
||||
shipped = _ship_hooks(hook_home, target)
|
||||
updated.extend(shipped)
|
||||
|
||||
# --- User-owned files: always skip ---
|
||||
for skip_name in (
|
||||
str(registry_path),
|
||||
str(target / "README.md"),
|
||||
str(target / "STATUS.local.md"),
|
||||
str(target / ".gitignore"),
|
||||
):
|
||||
skipped.append(skip_name)
|
||||
@@ -580,11 +626,20 @@ def update_project(target: Path) -> dict:
|
||||
venv_link.symlink_to(aipass_venv)
|
||||
updated.append(f".venv (symlink to AIPass runtime: {aipass_venv})")
|
||||
|
||||
# --- Cruft cleanup: remove known-stale AIPass-managed artifacts ---
|
||||
for rel in _STALE_MANAGED_FILES:
|
||||
stale_path = target / rel
|
||||
if stale_path.is_file():
|
||||
stale_path.unlink()
|
||||
removed.append(str(stale_path))
|
||||
logger.info("Removed stale managed file: %s", stale_path)
|
||||
|
||||
return {
|
||||
"project_name": name,
|
||||
"target": str(target),
|
||||
"updated_files": updated,
|
||||
"already_current": already_current,
|
||||
"skipped_files": skipped,
|
||||
"removed_files": removed,
|
||||
"aipass_home": aipass_home,
|
||||
}
|
||||
|
||||
@@ -37,11 +37,11 @@ def readme_md(name: str) -> str:
|
||||
"aipass init agent my_agent\n"
|
||||
"\n"
|
||||
"# 2. Start a session\n"
|
||||
"cd src/my_agent/\n"
|
||||
f"cd src/{name.lower()}/my_agent/\n"
|
||||
"claude # or your preferred AI CLI\n"
|
||||
"\n"
|
||||
"# 3. Check project status\n"
|
||||
"cat STATUS.local.md\n"
|
||||
"# 3. Check project health\n"
|
||||
"drone @seedgo audit .\n"
|
||||
"```\n"
|
||||
"\n"
|
||||
"## Project Structure\n"
|
||||
@@ -52,8 +52,7 @@ def readme_md(name: str) -> str:
|
||||
" .aipass/ # Prompts (injected per-turn)\n"
|
||||
" CLAUDE.md # Claude Code instructions\n"
|
||||
" AGENTS.md # Codex instructions\n"
|
||||
" STATUS.local.md # Project status\n"
|
||||
" src/ # Agent directories live here\n"
|
||||
f" src/{name.lower()}/ # Project package\n"
|
||||
" <agent_name>/ # Created via aipass init agent\n"
|
||||
"```\n"
|
||||
"\n"
|
||||
@@ -83,6 +82,30 @@ def readme_md(name: str) -> str:
|
||||
)
|
||||
|
||||
|
||||
def agents_md(name: str) -> str:
|
||||
"""Generate AGENTS.md content — Codex equivalent of CLAUDE.md for projects."""
|
||||
return (
|
||||
f"# {name}\n"
|
||||
"\n"
|
||||
"Agent workspace powered by AIPass.\n"
|
||||
"\n"
|
||||
"# Startup protocol\n"
|
||||
"\n"
|
||||
"On any greeting, silently run this sequence — no narration, no announcing "
|
||||
"steps. Just do it and respond with the status.\n"
|
||||
"\n"
|
||||
" - Read: `.trinity/passport.json`, `.trinity/local.json`, "
|
||||
"`.trinity/observations.json`, `README.md`\n"
|
||||
"\n"
|
||||
"Use drone commands for all operations. Never raw git, gh, or file access "
|
||||
"when drone provides it.\n"
|
||||
"\n"
|
||||
"# Memories\n"
|
||||
"\n"
|
||||
"Update `.trinity/` at natural breakpoints, after milestones, and on `/memo`.\n"
|
||||
)
|
||||
|
||||
|
||||
def global_prompt_md(name: str) -> str:
|
||||
"""Generate .aipass/aipass_global_prompt.md — injected every turn."""
|
||||
return (
|
||||
@@ -212,7 +235,6 @@ def gitignore() -> str:
|
||||
".trinity/\n"
|
||||
".ai_mail.local/\n"
|
||||
"*.local.*\n"
|
||||
"!STATUS.local.md\n"
|
||||
"\n"
|
||||
"# Plans (local working docs)\n"
|
||||
"DPLAN-*\n"
|
||||
@@ -279,9 +301,6 @@ def prep_md() -> str:
|
||||
"- **`.trinity/observations.json`** — YOUR MEMORY OF THE USER. "
|
||||
"Collaboration insights, preferences, friction points. Skip if nothing "
|
||||
"new about the user this session.\n"
|
||||
"- **`STATUS.local.md`** — PUBLIC STATUS BEACON. Current work, known "
|
||||
"issues, todos, notepad. Auto-synced to central STATUS.md on PR events "
|
||||
"— this is how other branches see you. Keep Current Work accurate.\n"
|
||||
"\n"
|
||||
"## 2. Active Plans\n"
|
||||
"\n"
|
||||
@@ -308,7 +327,7 @@ def prep_md() -> str:
|
||||
"- Flag anything in-flight: running background agents, dispatched "
|
||||
"branches waiting for replies, pending decisions\n"
|
||||
"- If anything can't survive compaction (e.g., agent IDs needed for "
|
||||
"resume), write it to STATUS.local.md Notepad\n"
|
||||
"resume), write it to local.json key_learnings\n"
|
||||
"\n"
|
||||
"## Confirm\n"
|
||||
"\n"
|
||||
@@ -317,7 +336,6 @@ def prep_md() -> str:
|
||||
"Prep complete:\n"
|
||||
"- local.json: [what was added]\n"
|
||||
"- observations.json: [updated / skipped]\n"
|
||||
"- STATUS.local.md: [updated / skipped]\n"
|
||||
"- Plans: [which ones updated]\n"
|
||||
"- Git: [branch, uncommitted count, suggestion]\n"
|
||||
"- Inbox: [count, action taken]\n"
|
||||
|
||||
@@ -1,254 +1,88 @@
|
||||
# =================== AIPass ====================
|
||||
# Name: json_handler.py
|
||||
# Description: Auto-Creating JSON Handler for aipass branch
|
||||
# Version: 1.0.0
|
||||
# Description: Branch-local shim — delegates to aipass.aipass.shared.json_handler
|
||||
# Version: 2.0.0
|
||||
# Created: 2026-04-16
|
||||
# Modified: 2026-04-16
|
||||
# Modified: 2026-06-06
|
||||
# =============================================
|
||||
|
||||
"""
|
||||
JSON Handler - Auto-Creating & Self-Healing JSON System
|
||||
"""Branch-local JSON handler — thin shim over the shared ``aipass.aipass.shared`` library.
|
||||
|
||||
Handles default JSON files (config, data, log) for aipass modules.
|
||||
Never manually create JSONs - they build themselves.
|
||||
All logic lives in ``aipass.aipass.shared.json_handler.JsonHandler``.
|
||||
This module binds a ``JsonHandler`` instance to the aipass branch's
|
||||
``aipass_json/`` directory and re-exports the public API as module-level
|
||||
functions so existing callers (``json_handler.log_operation(...)``) keep working.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import inspect
|
||||
import json
|
||||
import os
|
||||
import tempfile
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
from aipass.prax import logger
|
||||
from aipass.aipass.shared.json_handler import JsonHandler
|
||||
|
||||
|
||||
def _get_caller_module_name() -> str:
|
||||
"""Auto-detect calling module name from call stack."""
|
||||
stack = inspect.stack()
|
||||
if len(stack) > 2:
|
||||
caller_path = Path(stack[2].filename)
|
||||
module_name = caller_path.stem
|
||||
if module_name and not module_name.startswith("_"):
|
||||
return module_name
|
||||
return "unknown"
|
||||
|
||||
# =============================================================================
|
||||
# INFRASTRUCTURE SETUP
|
||||
# =============================================================================
|
||||
|
||||
# json_handler.py lives at: src/aipass/aipass/apps/handlers/json/json_handler.py
|
||||
# parents[0] = json/, [1] = handlers/, [2] = apps/, [3] = aipass/, [4] = src/aipass/
|
||||
_PKG_ROOT = Path(__file__).resolve().parents[4]
|
||||
|
||||
# Constants
|
||||
AIPASS_BRANCH_ROOT = _PKG_ROOT / "aipass"
|
||||
AIPASS_JSON_DIR = AIPASS_BRANCH_ROOT / "aipass_json"
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# INTERNAL HELPERS
|
||||
# =============================================================================
|
||||
def _handler() -> JsonHandler:
|
||||
"""Create a handler bound to the current AIPASS_JSON_DIR."""
|
||||
return JsonHandler(AIPASS_JSON_DIR)
|
||||
|
||||
|
||||
def _get_caller_module_name() -> str:
|
||||
"""Auto-detect calling module name from call stack.
|
||||
|
||||
Returns:
|
||||
Module name (e.g., "doctor" from doctor.py)
|
||||
"""
|
||||
try:
|
||||
stack = inspect.stack()
|
||||
# Skip frames: [0]=this function, [1]=log_operation, [2]=actual caller
|
||||
if len(stack) > 2:
|
||||
caller_frame = stack[2]
|
||||
caller_path = Path(caller_frame.filename)
|
||||
module_name = caller_path.stem
|
||||
|
||||
if module_name and not module_name.startswith("_"):
|
||||
return module_name
|
||||
|
||||
return "unknown"
|
||||
except Exception as exc:
|
||||
logger.warning("[json_handler] Failed to detect caller module name: %s", exc)
|
||||
return "unknown"
|
||||
def load_path(file_path: Path) -> Optional[dict]:
|
||||
"""Load JSON from an arbitrary file path."""
|
||||
return JsonHandler.read_json(file_path)
|
||||
|
||||
|
||||
def _default_template(json_type: str, module_name: str) -> Any:
|
||||
"""Return inline default structure for a JSON type — no file templates needed."""
|
||||
today = datetime.now().date().isoformat()
|
||||
if json_type == "config":
|
||||
return {
|
||||
"module_name": module_name,
|
||||
"version": "1.0.0",
|
||||
"config": {
|
||||
"max_log_entries": 100,
|
||||
},
|
||||
"created": today,
|
||||
}
|
||||
if json_type == "data":
|
||||
return {
|
||||
"created": today,
|
||||
"last_updated": today,
|
||||
}
|
||||
if json_type == "log":
|
||||
return []
|
||||
return None
|
||||
|
||||
|
||||
def _atomic_write_json(target_path: Path, data: Any) -> None:
|
||||
"""Write JSON data atomically via temp file + rename.
|
||||
|
||||
Prevents corruption from concurrent processes writing the same file.
|
||||
"""
|
||||
fd, tmp_path = tempfile.mkstemp(dir=str(target_path.parent), suffix=".tmp", prefix=target_path.stem)
|
||||
succeeded = False
|
||||
try:
|
||||
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
||||
json.dump(data, f, indent=2, ensure_ascii=False)
|
||||
os.replace(tmp_path, str(target_path))
|
||||
succeeded = True
|
||||
finally:
|
||||
if not succeeded and Path(tmp_path).exists():
|
||||
logger.warning("[json_handler] Cleaning up temp file after write failure: %s", tmp_path)
|
||||
os.unlink(tmp_path)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# VALIDATION
|
||||
# =============================================================================
|
||||
def save_path(file_path: Path, data: Any, indent: int = 2) -> bool:
|
||||
"""Write JSON data to an arbitrary file path atomically."""
|
||||
return JsonHandler.write_json(file_path, data, indent)
|
||||
|
||||
|
||||
def validate_json_structure(data: Any, json_type: str) -> bool:
|
||||
"""Validate JSON structure matches expected type."""
|
||||
if json_type == "config":
|
||||
if not isinstance(data, dict):
|
||||
return False
|
||||
required = ["module_name", "version", "config"]
|
||||
return all(key in data for key in required)
|
||||
|
||||
elif json_type == "data":
|
||||
if not isinstance(data, dict):
|
||||
return False
|
||||
required = ["created", "last_updated"]
|
||||
return all(key in data for key in required)
|
||||
|
||||
elif json_type == "log":
|
||||
return isinstance(data, list)
|
||||
|
||||
return False
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# PUBLIC API
|
||||
# =============================================================================
|
||||
|
||||
|
||||
def load_path(path: Path) -> Any:
|
||||
"""Load JSON from an arbitrary file path with consistent error handling."""
|
||||
try:
|
||||
with open(path, "r", encoding="utf-8") as f:
|
||||
return json.load(f)
|
||||
except (json.JSONDecodeError, OSError) as exc:
|
||||
logger.warning("[json_handler] Failed to load %s: %s", path, exc)
|
||||
return None
|
||||
|
||||
|
||||
def save_path(path: Path, data: Any) -> bool:
|
||||
"""Write JSON data to an arbitrary file path atomically."""
|
||||
os.makedirs(path.parent, exist_ok=True)
|
||||
fd, tmp_path = tempfile.mkstemp(dir=str(path.parent), suffix=".tmp", prefix=path.stem)
|
||||
succeeded = False
|
||||
try:
|
||||
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
||||
json.dump(data, f, indent=2, ensure_ascii=False)
|
||||
f.write("\n")
|
||||
os.replace(tmp_path, str(path))
|
||||
succeeded = True
|
||||
return True
|
||||
except OSError as exc:
|
||||
logger.warning("[json_handler] Failed to save %s: %s", path, exc)
|
||||
return False
|
||||
finally:
|
||||
if not succeeded and Path(tmp_path).exists():
|
||||
os.unlink(tmp_path)
|
||||
"""Validate that data matches the expected shape for json_type."""
|
||||
return JsonHandler.validate_json_structure(data, json_type)
|
||||
|
||||
|
||||
def get_json_path(module_name: str, json_type: str) -> Path:
|
||||
"""Get path for module JSON file."""
|
||||
filename = f"{module_name}_{json_type}.json"
|
||||
return AIPASS_JSON_DIR / filename
|
||||
"""Return the filesystem path for a module's JSON file."""
|
||||
return _handler().get_json_path(module_name, json_type)
|
||||
|
||||
|
||||
def ensure_json_exists(module_name: str, json_type: str) -> bool:
|
||||
"""Ensure JSON file exists, create from template if missing."""
|
||||
AIPASS_JSON_DIR.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
json_path = get_json_path(module_name, json_type)
|
||||
|
||||
if json_path.exists():
|
||||
try:
|
||||
with open(json_path, "r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
|
||||
if validate_json_structure(data, json_type):
|
||||
return True
|
||||
except Exception as exc:
|
||||
logger.warning(
|
||||
"[json_handler] Corrupted JSON file for '%s/%s', regenerating: %s",
|
||||
module_name,
|
||||
json_type,
|
||||
exc,
|
||||
)
|
||||
|
||||
template = _default_template(json_type, module_name)
|
||||
if template is None:
|
||||
return False
|
||||
|
||||
try:
|
||||
_atomic_write_json(json_path, template)
|
||||
return True
|
||||
except Exception as exc:
|
||||
logger.error(
|
||||
"[json_handler] Failed to write JSON template for '%s/%s': %s",
|
||||
module_name,
|
||||
json_type,
|
||||
exc,
|
||||
)
|
||||
return False
|
||||
|
||||
|
||||
def load_json(module_name: str, json_type: str) -> Optional[Any]:
|
||||
"""Load JSON file, auto-create if missing."""
|
||||
if not ensure_json_exists(module_name, json_type):
|
||||
return None
|
||||
|
||||
json_path = get_json_path(module_name, json_type)
|
||||
|
||||
try:
|
||||
with open(json_path, "r", encoding="utf-8") as f:
|
||||
return json.load(f)
|
||||
except Exception as exc:
|
||||
logger.error("[json_handler] Failed to load JSON for '%s/%s': %s", module_name, json_type, exc)
|
||||
return None
|
||||
|
||||
|
||||
def save_json(module_name: str, json_type: str, data: Any) -> bool:
|
||||
"""Save JSON file."""
|
||||
json_path = get_json_path(module_name, json_type)
|
||||
|
||||
if not validate_json_structure(data, json_type):
|
||||
return False
|
||||
|
||||
if json_type == "data" and isinstance(data, dict):
|
||||
data["last_updated"] = datetime.now().date().isoformat()
|
||||
|
||||
try:
|
||||
_atomic_write_json(json_path, data)
|
||||
return True
|
||||
except Exception as exc:
|
||||
logger.error("[json_handler] Failed to save JSON for '%s/%s': %s", module_name, json_type, exc)
|
||||
return False
|
||||
"""Ensure a single JSON file exists; create with defaults if missing."""
|
||||
return _handler().ensure_json_exists(module_name, json_type)
|
||||
|
||||
|
||||
def ensure_module_jsons(module_name: str) -> bool:
|
||||
"""Ensure all 3 JSON files exist for a module."""
|
||||
ensure_json_exists(module_name, "config")
|
||||
ensure_json_exists(module_name, "data")
|
||||
ensure_json_exists(module_name, "log")
|
||||
return True
|
||||
"""Ensure all three JSON files (config, data, log) exist for a module."""
|
||||
return _handler().ensure_module_jsons(module_name)
|
||||
|
||||
|
||||
def load_json(module_name: str, json_type: str) -> Optional[Any]:
|
||||
"""Load a module's JSON file, auto-creating it if missing."""
|
||||
return _handler().load_json(module_name, json_type)
|
||||
|
||||
|
||||
def save_json(module_name: str, json_type: str, data: Any) -> bool:
|
||||
"""Save JSON file. Raises ValueError on invalid structure."""
|
||||
return _handler().save_json(module_name, json_type, data)
|
||||
|
||||
|
||||
def log_operation(
|
||||
@@ -256,42 +90,7 @@ def log_operation(
|
||||
data: Dict[str, Any] | None = None,
|
||||
module_name: str | None = None,
|
||||
) -> bool:
|
||||
"""Add entry to module log with automatic rotation.
|
||||
|
||||
Auto-detects calling module if module_name not provided.
|
||||
Implements config-controlled log limits to prevent unbounded growth.
|
||||
When max_log_entries is reached, removes oldest entries (FIFO).
|
||||
|
||||
Args:
|
||||
operation: Operation name to log
|
||||
data: Optional data dict
|
||||
module_name: Optional module name (auto-detected if not provided)
|
||||
|
||||
Returns:
|
||||
True if successful, False otherwise
|
||||
"""
|
||||
"""Add entry to module operation log with automatic rotation."""
|
||||
if module_name is None:
|
||||
module_name = _get_caller_module_name()
|
||||
|
||||
ensure_module_jsons(module_name)
|
||||
|
||||
config = load_json(module_name, "config")
|
||||
max_entries = 100
|
||||
if config and "config" in config:
|
||||
max_entries = config["config"].get("max_log_entries", 100)
|
||||
|
||||
log = load_json(module_name, "log")
|
||||
if log is None:
|
||||
log = []
|
||||
|
||||
entry: Dict[str, Any] = {"timestamp": datetime.now().isoformat(), "operation": operation}
|
||||
|
||||
if data:
|
||||
entry["data"] = data
|
||||
|
||||
log.append(entry)
|
||||
|
||||
if len(log) > max_entries:
|
||||
log = log[-max_entries:]
|
||||
|
||||
return save_json(module_name, "log", log)
|
||||
return _handler().log_operation(operation, data, module_name)
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
# =================== AIPass ====================
|
||||
# Name: provider_reconcile.py
|
||||
# Description: Detect and fix stale rules in provider settings
|
||||
# Version: 1.0.0
|
||||
# Created: 2026-06-05
|
||||
# Modified: 2026-06-05
|
||||
# =============================================
|
||||
|
||||
"""provider_reconcile — detect and fix stale rules in ~/.claude/settings.json."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from aipass.prax import logger
|
||||
|
||||
from aipass.aipass.apps.handlers.json import json_handler
|
||||
|
||||
_MODULE_NAME = "provider_reconcile"
|
||||
|
||||
_STALE_RM_DENY_RULES = frozenset({"Bash(rm -rf*)", "Bash(rm -r *)"})
|
||||
|
||||
GLYPH_PASS = "[green]✓[/green]"
|
||||
GLYPH_WARN = "[yellow]![/yellow]"
|
||||
|
||||
|
||||
def reconcile_stale_deny(fix: bool = False) -> list:
|
||||
"""Detect and optionally remove stale rm deny rules from provider settings.
|
||||
|
||||
Returns list of (label, glyph, detail, remediation) tuples matching
|
||||
doctor.CheckResult shape — imported as tuples to avoid circular import.
|
||||
"""
|
||||
results: list = []
|
||||
settings_path = Path.home() / ".claude" / "settings.json"
|
||||
|
||||
if not settings_path.exists():
|
||||
json_handler.log_operation(
|
||||
"reconcile_stale_deny",
|
||||
data={"fix": fix, "skipped": "no settings file"},
|
||||
module_name=_MODULE_NAME,
|
||||
)
|
||||
return results
|
||||
|
||||
data = json_handler.load_path(settings_path)
|
||||
if data is None:
|
||||
json_handler.log_operation(
|
||||
"reconcile_stale_deny",
|
||||
data={"fix": fix, "skipped": "could not load settings"},
|
||||
module_name=_MODULE_NAME,
|
||||
)
|
||||
return results
|
||||
|
||||
deny = data.get("permissions", {}).get("deny", [])
|
||||
stale = [r for r in deny if r in _STALE_RM_DENY_RULES]
|
||||
|
||||
if not stale:
|
||||
results.append(("rm deny migration", GLYPH_PASS, "no stale rules", ""))
|
||||
elif fix:
|
||||
deny_cleaned = [r for r in deny if r not in _STALE_RM_DENY_RULES]
|
||||
data.setdefault("permissions", {})["deny"] = deny_cleaned
|
||||
json_handler.save_path(settings_path, data)
|
||||
removed = ", ".join(stale)
|
||||
results.append(("rm deny migration", GLYPH_PASS, f"removed: {removed}", ""))
|
||||
logger.info("[doctor] removed stale deny rules: %s", stale)
|
||||
else:
|
||||
found = ", ".join(stale)
|
||||
results.append(
|
||||
(
|
||||
"rm deny migration",
|
||||
GLYPH_WARN,
|
||||
f"stale rules: {found}",
|
||||
"Run aipass doctor --fix to remove (rm_gate + drone rm replace these)",
|
||||
)
|
||||
)
|
||||
|
||||
json_handler.log_operation(
|
||||
"reconcile_stale_deny",
|
||||
data={"fix": fix, "stale_found": len(stale)},
|
||||
module_name=_MODULE_NAME,
|
||||
)
|
||||
return results
|
||||
@@ -0,0 +1,155 @@
|
||||
# =================== AIPass ====================
|
||||
# Name: provider_wire.py
|
||||
# Description: Auto-wire provider settings from manifest into user config
|
||||
# Version: 1.0.0
|
||||
# Created: 2026-07-11
|
||||
# Modified: 2026-07-11
|
||||
# =============================================
|
||||
|
||||
"""provider_wire — auto-wire provider settings.
|
||||
|
||||
Implements the additive merge of manifest into ~/.claude/settings.json.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import shutil
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Dict, List
|
||||
|
||||
from aipass.aipass.apps.handlers.json import json_handler
|
||||
|
||||
# =============================================================================
|
||||
# HOOK & ENV DESCRIPTIONS
|
||||
# =============================================================================
|
||||
|
||||
HOOK_DESCRIPTIONS: Dict[str, str] = {
|
||||
"pre_edit_gate.py": "blocks edits outside agent's branch",
|
||||
"subagent_stop_gate.py": "validates agent output on exit",
|
||||
"auto_fix_diagnostics.py": "auto-fixes lint issues after edits",
|
||||
"global_prompt_loader.py": "injects branch context on each turn",
|
||||
"identity_injector.py": "injects agent identity on each turn",
|
||||
"email_notification.py": "notifies on incoming agent mail",
|
||||
"branch_prompt_loader.py": "loads branch-specific prompts",
|
||||
"pre_compact.py": "saves state before context compaction",
|
||||
}
|
||||
|
||||
ENV_DESCRIPTIONS: Dict[str, str] = {
|
||||
"AIPASS_HOME": "tells agents where AIPass lives",
|
||||
"CLAUDE_CODE_DISABLE_AUTO_MEMORY": "prevents conflict with .trinity/ memory system",
|
||||
}
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# AUTO-WIRE
|
||||
# =============================================================================
|
||||
|
||||
|
||||
def auto_wire_provider(manifest_path: Path, interactive: bool = True) -> List[str]:
|
||||
"""Auto-wire provider settings from manifest into ~/.claude/settings.json.
|
||||
|
||||
Additive merge only — never removes or overwrites existing keys/values.
|
||||
Returns list of action descriptions (for logging/display).
|
||||
"""
|
||||
actions: List[str] = []
|
||||
|
||||
manifest = json_handler.load_path(manifest_path)
|
||||
if manifest is None:
|
||||
return actions
|
||||
claude_section = manifest.get("cli", {}).get("claude", {})
|
||||
if not claude_section:
|
||||
return actions
|
||||
|
||||
settings_path = Path.home() / ".claude" / "settings.json"
|
||||
if settings_path.exists():
|
||||
settings = json_handler.load_path(settings_path) or {}
|
||||
else:
|
||||
settings = {}
|
||||
|
||||
if settings_path.exists():
|
||||
date_stamp = datetime.now(tz=timezone.utc).strftime("%Y-%m-%d")
|
||||
backup_path = settings_path.with_suffix(f".json.bak.{date_stamp}")
|
||||
shutil.copy2(settings_path, backup_path)
|
||||
actions.append(f"Backed up settings to {backup_path.name}")
|
||||
|
||||
manifest_hooks = claude_section.get("hooks", [])
|
||||
|
||||
for hook in manifest_hooks:
|
||||
command = hook.get("command", "")
|
||||
event = hook.get("event", "")
|
||||
if not command or not event:
|
||||
continue
|
||||
|
||||
if "hooks" not in settings:
|
||||
settings["hooks"] = {}
|
||||
if event not in settings["hooks"]:
|
||||
settings["hooks"][event] = []
|
||||
event_hooks = settings["hooks"][event]
|
||||
if not isinstance(event_hooks, list):
|
||||
event_hooks = [event_hooks]
|
||||
settings["hooks"][event] = event_hooks
|
||||
|
||||
hook_matcher = hook.get("matcher", "")
|
||||
already_wired = any(
|
||||
isinstance(h, dict) and command in json.dumps(h) and h.get("matcher", "") == hook_matcher
|
||||
for h in event_hooks
|
||||
)
|
||||
if not already_wired:
|
||||
cmd_entry: Dict[str, object] = {
|
||||
"type": "command",
|
||||
"command": command,
|
||||
}
|
||||
if hook.get("timeout"):
|
||||
cmd_entry["timeout"] = hook["timeout"]
|
||||
wrapper: Dict[str, object] = {}
|
||||
if hook.get("matcher"):
|
||||
wrapper["matcher"] = hook["matcher"]
|
||||
wrapper["hooks"] = [cmd_entry]
|
||||
event_hooks.append(wrapper)
|
||||
label = command.rsplit(" ", 1)[-1] if " " in command else command
|
||||
actions.append(f"Wired hook {label} -> {event}")
|
||||
|
||||
manifest_env = claude_section.get("env", {})
|
||||
if manifest_env:
|
||||
if "env" not in settings:
|
||||
settings["env"] = {}
|
||||
repo_root = str(manifest_path.parent.parent)
|
||||
project_root = str(Path.cwd())
|
||||
for key, value in manifest_env.items():
|
||||
if key not in settings["env"]:
|
||||
resolved = value.replace("{{REPO_ROOT}}", repo_root)
|
||||
resolved = resolved.replace("{{PROJECT_ROOT}}", project_root)
|
||||
settings["env"][key] = resolved
|
||||
actions.append(f"Set env {key}={resolved}")
|
||||
|
||||
manifest_perms = claude_section.get("permissions", {})
|
||||
manifest_deny = manifest_perms.get("deny", [])
|
||||
manifest_ask = manifest_perms.get("ask", [])
|
||||
|
||||
if manifest_deny or manifest_ask:
|
||||
if "permissions" not in settings:
|
||||
settings["permissions"] = {}
|
||||
if "deny" not in settings["permissions"]:
|
||||
settings["permissions"]["deny"] = []
|
||||
if "ask" not in settings["permissions"]:
|
||||
settings["permissions"]["ask"] = []
|
||||
|
||||
existing_deny = set(settings["permissions"]["deny"])
|
||||
for rule in manifest_deny:
|
||||
if rule not in existing_deny:
|
||||
settings["permissions"]["deny"].append(rule)
|
||||
actions.append(f"Added deny rule: {rule}")
|
||||
|
||||
existing_ask = set(settings["permissions"]["ask"])
|
||||
for rule in manifest_ask:
|
||||
if rule not in existing_ask:
|
||||
settings["permissions"]["ask"].append(rule)
|
||||
actions.append(f"Added ask rule: {rule}")
|
||||
|
||||
json_handler.save_path(settings_path, settings)
|
||||
actions.append("Updated ~/.claude/settings.json")
|
||||
|
||||
json_handler.log_operation("auto_wire_provider", {"actions": len(actions)})
|
||||
return actions
|
||||
@@ -117,3 +117,18 @@ def list_branches() -> list[str]:
|
||||
Reflects the filesystem state at the time the map was first built.
|
||||
"""
|
||||
return list(_get_map().keys())
|
||||
|
||||
|
||||
def read_readme_lines(branch: str) -> list[str] | None:
|
||||
"""Live-read README.md for a branch. Returns list of lines, or None on error.
|
||||
|
||||
Content is NEVER cached — every call reads the current file.
|
||||
"""
|
||||
readme_path = get_readme_path(branch)
|
||||
if readme_path is None:
|
||||
return None
|
||||
try:
|
||||
with open(readme_path, encoding="utf-8") as fh:
|
||||
return fh.readlines()
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
"""sandbox_check — Kernel sandbox prerequisite detection for aipass doctor."""
|
||||
|
||||
from aipass.aipass.apps.handlers.sandbox_check.sandbox_checker import ( # type: ignore[import-not-found]
|
||||
check_broker_alive,
|
||||
check_bwrap_functional,
|
||||
check_bwrap_present,
|
||||
check_node_present,
|
||||
check_rg_present,
|
||||
check_sandbox_flag,
|
||||
check_srt_resolvable,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"check_broker_alive",
|
||||
"check_bwrap_functional",
|
||||
"check_bwrap_present",
|
||||
"check_node_present",
|
||||
"check_rg_present",
|
||||
"check_sandbox_flag",
|
||||
"check_srt_resolvable",
|
||||
]
|
||||
@@ -0,0 +1,253 @@
|
||||
# =================== AIPass ====================
|
||||
# Name: sandbox_checker.py
|
||||
# Description: Kernel sandbox prerequisite checks for aipass doctor
|
||||
# Version: 1.0.0
|
||||
# Created: 2026-06-10
|
||||
# Modified: 2026-06-10
|
||||
# =============================================
|
||||
|
||||
"""Sandbox prerequisite checker — detects bwrap, node, srt, rg, broker.
|
||||
|
||||
Returns plain dicts with facts about sandbox readiness.
|
||||
No Rich markup — display concerns belong to the UI layer.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import shutil
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict
|
||||
|
||||
from aipass.prax import logger
|
||||
from aipass.aipass.apps.handlers.json import json_handler
|
||||
|
||||
|
||||
def check_sandbox_flag() -> Dict[str, Any]:
|
||||
"""Check AIPASS_SANDBOX_ENABLED env var state.
|
||||
|
||||
Returns:
|
||||
enabled: bool
|
||||
raw_value: str — the raw env value (empty if unset)
|
||||
"""
|
||||
raw = os.environ.get("AIPASS_SANDBOX_ENABLED", "")
|
||||
enabled = raw.lower() in ("1", "true", "yes")
|
||||
json_handler.log_operation("sandbox_check_flag", {"enabled": enabled, "raw": raw})
|
||||
return {"enabled": enabled, "raw_value": raw}
|
||||
|
||||
|
||||
def check_bwrap_present() -> Dict[str, Any]:
|
||||
"""Check if bubblewrap (bwrap) binary is on PATH.
|
||||
|
||||
Returns:
|
||||
found: bool
|
||||
path: str | None — resolved path if found
|
||||
"""
|
||||
path = shutil.which("bwrap")
|
||||
json_handler.log_operation("sandbox_check_bwrap_present", {"found": bool(path)})
|
||||
return {"found": bool(path), "path": path}
|
||||
|
||||
|
||||
def check_bwrap_functional() -> Dict[str, Any]:
|
||||
"""Run a trivial bwrap sandbox to verify it actually works.
|
||||
|
||||
Catches AppArmor/userns restrictions that make bwrap present but blocked.
|
||||
|
||||
Returns:
|
||||
ok: bool
|
||||
detail: str — success message or error detail
|
||||
sysctl_value: str | None — kernel.apparmor_restrict_unprivileged_userns on failure
|
||||
"""
|
||||
bwrap = shutil.which("bwrap")
|
||||
if not bwrap:
|
||||
return {"ok": False, "detail": "bwrap not found", "sysctl_value": None}
|
||||
|
||||
try:
|
||||
proc = subprocess.run(
|
||||
[bwrap, "--ro-bind", "/", "/", "--dev", "/dev", "--proc", "/proc", "true"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=10,
|
||||
check=False,
|
||||
)
|
||||
if proc.returncode == 0:
|
||||
json_handler.log_operation("sandbox_check_bwrap_functional", {"ok": True})
|
||||
return {"ok": True, "detail": "trivial sandbox succeeded", "sysctl_value": None}
|
||||
|
||||
sysctl_val = _read_userns_sysctl()
|
||||
detail = f"exit {proc.returncode}"
|
||||
if proc.stderr.strip():
|
||||
detail = f"{detail}: {proc.stderr.strip()[:200]}"
|
||||
json_handler.log_operation("sandbox_check_bwrap_functional", {"ok": False, "detail": detail})
|
||||
return {"ok": False, "detail": detail, "sysctl_value": sysctl_val}
|
||||
|
||||
except subprocess.TimeoutExpired:
|
||||
logger.warning("[sandbox_check] bwrap functional test timed out")
|
||||
return {"ok": False, "detail": "timed out (10s)", "sysctl_value": None}
|
||||
except OSError as exc:
|
||||
logger.warning("[sandbox_check] bwrap functional test error: %s", exc)
|
||||
return {"ok": False, "detail": str(exc), "sysctl_value": None}
|
||||
|
||||
|
||||
def _read_userns_sysctl() -> str | None:
|
||||
"""Read kernel.apparmor_restrict_unprivileged_userns sysctl if available."""
|
||||
try:
|
||||
proc = subprocess.run(
|
||||
["sysctl", "-n", "kernel.apparmor_restrict_unprivileged_userns"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=5,
|
||||
check=False,
|
||||
)
|
||||
if proc.returncode == 0:
|
||||
return proc.stdout.strip()
|
||||
except (FileNotFoundError, subprocess.TimeoutExpired, OSError) as exc:
|
||||
logger.info("[sandbox_check] sysctl read failed (expected on non-Ubuntu): %s", exc)
|
||||
return None
|
||||
|
||||
|
||||
def check_node_present() -> Dict[str, Any]:
|
||||
"""Check if node binary is on PATH.
|
||||
|
||||
Returns:
|
||||
found: bool
|
||||
path: str | None — resolved path if found
|
||||
"""
|
||||
path = shutil.which("node")
|
||||
json_handler.log_operation("sandbox_check_node", {"found": bool(path)})
|
||||
return {"found": bool(path), "path": path}
|
||||
|
||||
|
||||
def check_srt_resolvable() -> Dict[str, Any]:
|
||||
"""Check if @anthropic-ai/sandbox-runtime is resolvable via node.
|
||||
|
||||
Mirrors _srt_resolve.mjs resolution: derive node prefix from process.execPath,
|
||||
then check <prefix>/lib/node_modules/@anthropic-ai/sandbox-runtime/dist/index.js.
|
||||
|
||||
Returns:
|
||||
found: bool
|
||||
path: str | None — resolved entry path if found
|
||||
install_hint: str — npm install command if missing
|
||||
"""
|
||||
node = shutil.which("node")
|
||||
if not node:
|
||||
return {
|
||||
"found": False,
|
||||
"path": None,
|
||||
"install_hint": "Install node first, then: npm install -g @anthropic-ai/sandbox-runtime",
|
||||
}
|
||||
|
||||
try:
|
||||
script = (
|
||||
"const p = require('path');"
|
||||
"const prefix = p.dirname(p.dirname(process.execPath));"
|
||||
"const entry = p.join(prefix, 'lib/node_modules/@anthropic-ai/sandbox-runtime/dist/index.js');"
|
||||
"const fs = require('fs');"
|
||||
"if (fs.existsSync(entry)) { process.stdout.write(entry); }"
|
||||
"else { process.exit(1); }"
|
||||
)
|
||||
proc = subprocess.run(
|
||||
[node, "-e", script],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=10,
|
||||
check=False,
|
||||
)
|
||||
if proc.returncode == 0 and proc.stdout.strip():
|
||||
path = proc.stdout.strip()
|
||||
json_handler.log_operation("sandbox_check_srt", {"found": True, "path": path})
|
||||
return {"found": True, "path": path, "install_hint": ""}
|
||||
|
||||
except (FileNotFoundError, subprocess.TimeoutExpired, OSError) as exc:
|
||||
logger.warning("[sandbox_check] srt resolve error: %s", exc)
|
||||
|
||||
json_handler.log_operation("sandbox_check_srt", {"found": False})
|
||||
return {
|
||||
"found": False,
|
||||
"path": None,
|
||||
"install_hint": "npm install -g @anthropic-ai/sandbox-runtime",
|
||||
}
|
||||
|
||||
|
||||
def check_rg_present() -> Dict[str, Any]:
|
||||
"""Check if ripgrep (rg) is available — matches hooks' fallback logic.
|
||||
|
||||
Returns:
|
||||
found: bool
|
||||
path: str | None — resolved path if found
|
||||
"""
|
||||
rg = shutil.which("rg")
|
||||
if rg:
|
||||
json_handler.log_operation("sandbox_check_rg", {"found": True, "path": rg})
|
||||
return {"found": True, "path": rg}
|
||||
|
||||
fallback = Path.home() / ".local" / "bin" / "rg"
|
||||
if fallback.is_file():
|
||||
path = str(fallback)
|
||||
json_handler.log_operation("sandbox_check_rg", {"found": True, "path": path})
|
||||
return {"found": True, "path": path}
|
||||
|
||||
json_handler.log_operation("sandbox_check_rg", {"found": False})
|
||||
return {"found": False, "path": None}
|
||||
|
||||
|
||||
def check_broker_alive(repo_root: Path | None = None) -> Dict[str, Any]:
|
||||
"""Check if the broker daemon socket is accepting connections.
|
||||
|
||||
Args:
|
||||
repo_root: Project root containing .ai_central/. Auto-detected if None.
|
||||
|
||||
Returns:
|
||||
alive: bool
|
||||
detail: str — status message
|
||||
"""
|
||||
sock_path = _find_broker_socket(repo_root)
|
||||
if sock_path is None:
|
||||
json_handler.log_operation("sandbox_check_broker", {"alive": False, "reason": "socket_not_found"})
|
||||
return {"alive": False, "detail": "broker socket not found"}
|
||||
|
||||
if not sock_path.exists():
|
||||
json_handler.log_operation("sandbox_check_broker", {"alive": False, "reason": "socket_missing"})
|
||||
return {"alive": False, "detail": f"socket missing: {sock_path}"}
|
||||
|
||||
try:
|
||||
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
s.settimeout(2)
|
||||
s.connect(str(sock_path))
|
||||
s.close()
|
||||
json_handler.log_operation("sandbox_check_broker", {"alive": True})
|
||||
return {"alive": True, "detail": "connected"}
|
||||
except (OSError, socket.timeout) as exc:
|
||||
logger.info("[sandbox_check] broker connect failed: %s", exc)
|
||||
json_handler.log_operation("sandbox_check_broker", {"alive": False, "reason": str(exc)})
|
||||
return {"alive": False, "detail": f"connect failed: {exc}"}
|
||||
|
||||
|
||||
def _find_broker_socket(repo_root: Path | None) -> Path | None:
|
||||
"""Locate the broker socket under $REPO/.ai_central/drone_broker.sock."""
|
||||
if repo_root and (repo_root / ".ai_central" / "drone_broker.sock").parent.is_dir():
|
||||
return repo_root / ".ai_central" / "drone_broker.sock"
|
||||
|
||||
aipass_home = os.environ.get("AIPASS_HOME", "")
|
||||
if aipass_home:
|
||||
candidate = Path(aipass_home) / ".ai_central" / "drone_broker.sock"
|
||||
if candidate.parent.is_dir():
|
||||
return candidate
|
||||
|
||||
cwd = Path.cwd()
|
||||
for parent in [cwd, *cwd.parents]:
|
||||
candidate = parent / ".ai_central" / "drone_broker.sock"
|
||||
if candidate.parent.is_dir():
|
||||
return candidate
|
||||
if parent == parent.parent:
|
||||
break
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def is_linux() -> bool:
|
||||
"""Return True if running on Linux."""
|
||||
return sys.platform.startswith("linux")
|
||||
@@ -283,12 +283,6 @@ def detect_pollution(agents: List[AgentInfo]) -> List[PollutionHit]:
|
||||
# =============================================================================
|
||||
|
||||
|
||||
def find_registry(project_root: Path) -> Optional[Path]:
|
||||
"""Find *_REGISTRY.json under project_root."""
|
||||
candidates = list(project_root.glob("*_REGISTRY.json"))
|
||||
return candidates[0] if candidates else None
|
||||
|
||||
|
||||
def check_registry_consistency(
|
||||
registry_path: Path,
|
||||
agents: List[AgentInfo],
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
# =================== AIPass ====================
|
||||
# Name: progress.py
|
||||
# Description: Rich progress and glyph helpers for aipass doctor
|
||||
# Version: 1.0.0
|
||||
# Description: Rich progress and glyph helpers for aipass doctor + init
|
||||
# Version: 1.1.0
|
||||
# Created: 2026-04-16
|
||||
# Modified: 2026-04-16
|
||||
# Modified: 2026-07-05
|
||||
# =============================================
|
||||
|
||||
"""
|
||||
@@ -15,6 +15,9 @@ No bare print() — all output via logger or caller's console.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from contextlib import contextmanager
|
||||
from typing import Iterator
|
||||
|
||||
from rich.progress import Progress, SpinnerColumn, TextColumn
|
||||
|
||||
from aipass.aipass.apps.handlers.json import json_handler
|
||||
@@ -49,6 +52,26 @@ def make_doctor_progress() -> Progress:
|
||||
)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def activity_spinner(description: str) -> Iterator[Progress]:
|
||||
"""Transient spinner for a blocking, non-streaming action.
|
||||
|
||||
Wrap Python work that would otherwise look frozen — scaffold build, ping
|
||||
sweep — so the user sees it is alive. Do NOT wrap a subprocess that streams
|
||||
its own output to the terminal (installer, spawn): the two renderers fight.
|
||||
Yields the Progress so a caller can retitle the task mid-flight if needed.
|
||||
|
||||
Args:
|
||||
description: What is happening, e.g. "Building project scaffold…".
|
||||
"""
|
||||
logger.info("[progress] activity spinner: %s", description)
|
||||
json_handler.log_operation("activity_spinner", {"description": description})
|
||||
prog = Progress(SpinnerColumn(), TextColumn("{task.description}"), transient=True)
|
||||
with prog:
|
||||
prog.add_task(description, total=None)
|
||||
yield prog
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# CHECK FORMATTER
|
||||
# =============================================================================
|
||||
@@ -81,3 +104,26 @@ def format_check(
|
||||
line = f"{line}\n{indent}[dim yellow]{remediation}[/dim yellow]"
|
||||
|
||||
return line
|
||||
|
||||
|
||||
def render_step_header(current: int, total: int, label: str, width: int = 18) -> str:
|
||||
"""Render a one-line stage header with an inline progress bar.
|
||||
|
||||
Example: 'Step 3/10 [██████░░░░░░░░░░░░] — User profile'. Pure formatting —
|
||||
a static string, so it composes with the interactive prompts between stages
|
||||
(a live Rich bar would have to stop/start around every input()).
|
||||
|
||||
Args:
|
||||
current: 1-based index of the stage now starting.
|
||||
total: Total number of stages (clamps to >= 1).
|
||||
label: Human label for the stage.
|
||||
width: Character width of the bar.
|
||||
|
||||
Returns:
|
||||
Rich markup string ready for console.print().
|
||||
"""
|
||||
total = max(total, 1)
|
||||
current = max(0, min(current, total))
|
||||
filled = round(width * current / total)
|
||||
bar = "█" * filled + "░" * (width - filled)
|
||||
return f"[bold cyan]Step {current}/{total}[/bold cyan] [green]{bar}[/green] — [bold]{label}[/bold]"
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user