diff --git a/CHANGELOG.md b/CHANGELOG.md
index 046c8c9..a25d28c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,18 @@
# Changelog
+## Unreleased
+
+### Added
+
+- `scripts/aap_workspace.py`: `missing` (nodes without a checkout, with the `git clone` for `locator.repo`; clones only with `--clone`), `siblings` (git repos next to the hub that are not nodes) and `suggest` (prints a nodes skeleton; never writes). Cookbook: `workspace-tools.md`.
+- `aap_workspace.py state` and `doctor`; cookbook `node-state.md` (optional active/parked profile via `layout.state` + `profiles.enabled`, no schema change), `capability-index.md`, `new-machine.md`.
+- `examples/personal-hub/`: a synthetic personal hub (map, overlay template, state file, reuse index).
+- Cookbook `home-repo.md`: the hub as the agent's launch point, with auto-clone, worktree and child-map recipes.
+
+### Changed
+
+- README shortened to a one-screen pitch with a diagram; detail lives in the cookbook and `docs/`. The schema is unchanged.
+
## 0.3.0 — 2026-10-28
First release with an agent entry point and an installable skill. The Map v2 schema and its semantics are unchanged from 0.2.0. The "-prototype" suffix is dropped from the version: the project is still experimental, and the README Status section says so in one place.
diff --git a/README.md b/README.md
index 692c805..9188ba0 100644
--- a/README.md
+++ b/README.md
@@ -1,115 +1,70 @@
# Agent Artifact Protocol (AAP)
-A small map checked into your repository that tells coding agents where things live, so they can open the right place without loading everything first.
-
-## Install the skill
+**A short map in your repo that tells coding agents where things live, so they open the right place instead of loading everything.**
+
+```mermaid
+flowchart LR
+ A([Agent starts]) -->|L0: read only this| M[".aap/map.yaml
layout + nodes"]
+ M -->|L1: one hop| P["one layout path
or one node"]
+ P -->|L3: usual tools| C[(code)]
+ subgraph Hub ["Hub repo (optional)"]
+ M
+ L[".aap/map.local.yaml
gitignored: machine paths"] -.->|where each node is checked out| M
+ end
+ M -.->|nodes| R1[repo-a]
+ M -.->|nodes| R2[repo-b]
+```
-The `aap-map` skill looks at your repository and writes the map for you. It is one text file with no dependencies.
+The map is plain YAML and a convention, not a tool. Your normal search (grep, LSP, MCP) still does the finding.
-With the [`skills`](https://skills.sh) installer, which works for Claude Code, Codex, Cursor and many other agents:
+## Quick start
```bash
npx skills add gitpash/agent-artifact-protocol
```
-In Claude Code, from the plugin marketplace:
+Claude Code plugin: `/plugin marketplace add gitpash/agent-artifact-protocol`, then `/plugin install aap@agent-artifact-protocol`.
-```text
-/plugin marketplace add gitpash/agent-artifact-protocol
-/plugin install aap@agent-artifact-protocol
-```
-
-Then say this to your agent, inside the repository you want to map:
+Then, inside the repository you want to map, tell your agent:
> Use the aap-map skill to add an AAP map to this repo.
-The agent reads the repository, writes `.aap/map.yaml`, marks anything it guessed with a `# REVIEW:` comment and tells you what to check. It does not interview you and it never overwrites an existing map.
-
-## Quick start
-
-1. **Install the skill** with one of the commands above.
-2. **Ask your agent to add the map**, as shown above, and read the `# REVIEW:` lines it left. Fix or delete them, or answer "ok".
-3. **Commit `.aap/map.yaml`** and tell the agent to read the map first in future sessions. A line in `AGENTS.md` or `CLAUDE.md` is enough.
-
-If you would rather not install anything, give your LLM this link and ask it to explain AAP or to work in a repository that has a map. The file is written for an agent to read and points to the spec only when it is needed:
-
-```text
-https://raw.githubusercontent.com/gitpash/agent-artifact-protocol/main/llms.txt
-```
+It writes `.aap/map.yaml` and marks guesses with `# REVIEW:`. Fix or delete those, commit the file, and add one line to `AGENTS.md` or `CLAUDE.md` saying to read the map first. It never overwrites an existing map.
-## What AAP is
-
-AAP is a filesystem convention. The map is a short YAML file with the name of the workspace, the folders an agent will want (`code`, `tests`, `docs` and so on) and, for multi-repository setups, a few direct hops to neighbouring repositories. Agents read that file and nothing else at the start of a session, then open one path as the task requires.
-
-The convention comes with a JSON Schema, so any tool can check a map, but the skill itself needs no tool to write one.
-
-## What AAP is not
-
-- Not a context engine or retrieval system. Your normal tools (grep, an LSP, an index, MCP) still do the searching.
-- Not an agent framework or a multi-agent runtime.
-- Not a security boundary. The `access` field is a note between humans and agents, and real enforcement stays with Git permissions, protected branches and sandboxes.
-- Not a replacement for `AGENTS.md` or `CLAUDE.md`. Those say how to work, the map says where things are, and the two sit side by side.
+No install? Give your LLM [`llms.txt`](https://raw.githubusercontent.com/gitpash/agent-artifact-protocol/main/llms.txt) and ask it to work in a repo that has a map.
## A minimal map
```yaml
version: 2
-workspace:
- id: my-app
- description: "What this repository is, one line."
-self:
- id: my-app
- kind: repository
- path: .
+workspace: { id: my-app, description: "What this repository is, one line." }
+self: { id: my-app, kind: repository, path: . }
layout:
code: src/
tests: tests/
- artifacts:
- - path: docs/decisions/
- access: read-write
nodes:
- id: orders-api
kind: repository
description: "Owns the orders contract this app consumes."
- path: services/orders
+ locator: { repo: example/orders-api }
access: read-only
```
-- `layout` maps an intent to a path in this checkout. A plain string means read-write, and the object form adds `access: read-only` for folders that are frozen, generated or vendored. When a key lists several paths, the first one that is not read-only is where durable notes go.
-- `nodes` are direct hops to other repositories you would plausibly open during a normal change here. Most standalone repositories use `nodes: []`.
-- Paths are relative to the repository root, never absolute and never containing `..`.
-
-Examples for a single repository, a hub with several repositories and path references with `access` are in [`examples/`](./examples/). The starter file is [`templates/minimal-map.yaml`](./templates/minimal-map.yaml).
-
-## How an agent uses it
-
-AAP asks for progressive disclosure in four levels, and only the first is required.
-
-| Level | What the agent reads | When |
-|-------|----------------------|------|
-| L0 | The map only | Start of a session |
-| L1 | One layout path or one node | After choosing a key or node for the task |
-| L2 | One durable note | Only if the task needs durable memory |
-| L3 | Code, with the usual tools | Implementation |
-
-Linked maps are hops taken on purpose and are never preloaded recursively. Until you enable writes, an agent should prefer reading and orienting only.
-
-## Beyond the basics
+`layout` maps an intent to a path here. `nodes` are direct hops to other repositories (most repos use `nodes: []`). Machine paths for nodes go in the gitignored `.aap/map.local.yaml`, never in the shared map. More: [`examples/`](./examples/), [`templates/minimal-map.yaml`](./templates/minimal-map.yaml).
-- [`SPEC.md`](./SPEC.md): the short normative specification.
-- [`schemas/`](./schemas/): the JSON Schema for the map and for the optional artifact envelope.
-- [`cookbook/`](./cookbook/): optional profiles such as a hub map for several repositories, schema pinning, CI validation, stream packs and a done bar. None of them is needed for the basic map.
-- [`docs/motivation.md`](./docs/motivation.md) explains why the map exists, and [`docs/skill-tests.md`](./docs/skill-tests.md) describes how the skill was tested.
-- [`CONTRIBUTING.md`](./CONTRIBUTING.md) and [`CHANGELOG.md`](./CHANGELOG.md).
+## What it is not
-To check maps in CI, see [`cookbook/ci-validation.md`](./cookbook/ci-validation.md). This is optional and the skill does not depend on it. This repository keeps its own map in [`.aap/map.yaml`](./.aap/map.yaml), written by the skill.
+Not a retrieval engine, not an agent framework, not a security boundary (`access` is a note, enforcement stays with Git permissions and sandboxes), and not a replacement for `AGENTS.md`: those say how to work, the map says where things are.
-## Status
+## Going further
-AAP is at version 0.3.0 and is experimental. The Map v2 schema has not changed since 0.2.0, but the convention has been used on a small number of repositories, mostly by its author, and it has not been measured against alternatives. Expect small changes before 1.0, and treat the tag you pin as the version you are using. The thesis, that a sparse map beats a bigger prompt, is unproven here, and [`cookbook/measuring.md`](./cookbook/measuring.md) describes how to test it on your own work. If a map does not help, shrink it before adding anything.
+- [`SPEC.md`](./SPEC.md) and [`schemas/`](./schemas/): the normative spec and JSON Schema.
+- [`cookbook/`](./cookbook/): optional recipes. For a hub of many repos: [home repo](./cookbook/home-repo.md), [workspace tools](./cookbook/workspace-tools.md) and [node state](./cookbook/node-state.md). Worked example: [`examples/personal-hub/`](./examples/personal-hub/).
+- [`docs/motivation.md`](./docs/motivation.md), [`docs/skill-tests.md`](./docs/skill-tests.md), [`CONTRIBUTING.md`](./CONTRIBUTING.md), [`CHANGELOG.md`](./CHANGELOG.md).
+- This repo's own map: [`.aap/map.yaml`](./.aap/map.yaml). Optional CI check: [`cookbook/ci-validation.md`](./cookbook/ci-validation.md).
-Feedback is welcome as issues: map size, how fine layout keys should be, and whether the skill guesses well on repositories unlike the three it was tested on.
+## Status, honestly
-## License
+Version 0.3.0, experimental. The Map v2 schema has not changed since 0.2.0, but the convention has been used on few repositories, mostly by its author. The thesis that a sparse map beats a bigger prompt is unproven here; [`cookbook/measuring.md`](./cookbook/measuring.md) shows how to test it on your own work. If a map does not help, shrink it before adding anything. You do not need AAP for a small repo with a good README. Feedback as issues is welcome.
-MIT. See [`LICENSE`](./LICENSE).
+MIT, see [`LICENSE`](./LICENSE).
diff --git a/cookbook/README.md b/cookbook/README.md
index d9503c1..1c723c6 100644
--- a/cookbook/README.md
+++ b/cookbook/README.md
@@ -6,6 +6,11 @@ Optional profiles and how-to pages. None of them is part of the mandatory first
|------|----------------|
| [brownfield-init](./brownfield-init.md) | Add a map to an existing repository without touching its docs system |
| [hub-umbrella](./hub-umbrella.md) | A hub map for several repositories, with nodes as navigation hops |
+| [home-repo](./home-repo.md) | The hub-as-launch-point idea: auto-clone, worktrees, child maps for many repos |
+| [workspace-tools](./workspace-tools.md) | Scripts that report missing checkouts and missing nodes |
+| [node-state](./node-state.md) | Mark nodes active or parked with a next step, without a schema change |
+| [capability-index](./capability-index.md) | A capability -> project table for "I already built this" |
+| [new-machine](./new-machine.md) | Rebuild a hub's checkouts on a fresh machine |
| [schema-pinning](./schema-pinning.md) | Pin the schema by tag or commit instead of following the branch tip |
| [ci-validation](./ci-validation.md) | Check maps against the pinned schema in CI (optional) |
| [measuring](./measuring.md) | How to run an honest A/B of map versus no map |
diff --git a/cookbook/capability-index.md b/cookbook/capability-index.md
new file mode 100644
index 0000000..b17e0f0
--- /dev/null
+++ b/cookbook/capability-index.md
@@ -0,0 +1,18 @@
+# Cookbook: capability index
+
+When a task smells like "I already built this somewhere", the map is the wrong tool: it lists repositories, not things worth borrowing. Keep a one-table index beside it and point to it from the map:
+
+```yaml
+layout:
+ reuse: reuse.md
+```
+
+```markdown
+| Capability | Project | Where |
+|---|---|---|
+| Feature-flag wrapper for gradual rollouts | web-app | src/flags/ |
+```
+
+`Project` is a node id; `Where` is a path inside it. Add a line when you notice a second use, not before. It is not a dependency graph and the agent opens it only when a task asks for reuse (L1, not L0).
+
+Example: [`examples/personal-hub/reuse.md`](../examples/personal-hub/reuse.md).
diff --git a/cookbook/home-repo.md b/cookbook/home-repo.md
new file mode 100644
index 0000000..37b82cd
--- /dev/null
+++ b/cookbook/home-repo.md
@@ -0,0 +1,43 @@
+# Cookbook: home repo
+
+A "home repo" (the idea Matt Pocock describes in his *Home Repo* video) is one repository you always launch your agent from. It holds the routing table: which projects exist, what each is for, where to go for what. An AAP hub map is that routing table in machine-readable form: `nodes` are the rows, `layout` is the hub's own folders, `map.local.yaml` says where each row lives on this machine. The map says where things are; what the agent should *do* (the next two recipes) belongs in `AGENTS.md` or `CLAUDE.md`.
+
+Worked example: [`examples/personal-hub/`](../examples/personal-hub/). Map shape: [`hub-umbrella`](./hub-umbrella.md). Checks: [`workspace-tools`](./workspace-tools.md). Status per node: [`node-state`](./node-state.md). Reuse: [`capability-index`](./capability-index.md).
+
+## Auto-clone a missing node
+
+The map names the repo (`locator.repo`) and the overlay names the path, so a missing checkout is recoverable without asking you. In the hub's `AGENTS.md`:
+
+```markdown
+If a node's checkout is missing, clone `locator.repo` to its overlay path
+(`python scripts/aap_workspace.py missing` prints the command) before working.
+No `locator.repo` means ask the owner.
+```
+
+Cloning is behaviour, so it is an instruction to the agent, not something the map does.
+
+## Worktrees for parallel sessions
+
+When two sessions might touch the same node, tell the agent to work in a `git worktree` of the target repo, not in the shared checkout. Also an `AGENTS.md` line:
+
+```markdown
+Before editing a node, create a worktree of it (`git -C worktree add ...`)
+and work there. Never edit the shared checkout while another session may use it.
+```
+
+The map only resolves which repo; the worktree is the agent's choice for that task. `access: read-only` on a node still means "do not change it from here", worktree or not.
+
+## 30+ repos: progressive disclosure
+
+Do not list everything in one map. Keep the hub's `nodes` to the repos you really open, and give each group its own map reached through `map.path`:
+
+```yaml
+nodes:
+ - id: platform
+ kind: repository
+ description: "Platform services; open its map for the individual repos."
+ locator: { repo: example/platform }
+ map: { path: .aap/map.yaml }
+```
+
+The agent reads the hub map (L0), hops to one child map only when the task needs it, and never preloads children recursively. Leaves stay out of the hub until you open them often.
diff --git a/cookbook/new-machine.md b/cookbook/new-machine.md
new file mode 100644
index 0000000..8bf5170
--- /dev/null
+++ b/cookbook/new-machine.md
@@ -0,0 +1,14 @@
+# Cookbook: set up a new machine
+
+The hub is committed, the machine paths are not. On a fresh machine:
+
+1. Clone the hub and open it.
+2. Copy your overlay template to `.aap/map.local.yaml` and set the paths (see [`examples/personal-hub/map.local.yaml.example`](../examples/personal-hub/map.local.yaml.example)). Nodes that do not need to exist locally can be left out.
+3. Check, then clone what is missing:
+
+```bash
+python scripts/aap_workspace.py doctor # map schema, node state, and a report of missing checkouts
+python scripts/aap_workspace.py missing --clone
+```
+
+`doctor` is read-only. Only the second command, with `--clone`, writes anything, and only clones of `locator.repo` into the overlay paths. Details: [`workspace-tools`](./workspace-tools.md).
diff --git a/cookbook/node-state.md b/cookbook/node-state.md
new file mode 100644
index 0000000..62abbb7
--- /dev/null
+++ b/cookbook/node-state.md
@@ -0,0 +1,39 @@
+# Cookbook: node state (active / parked)
+
+An optional profile for a hub: which projects are live, what the next step is, and when a parked one should wake up. It changes nothing in Core.
+
+## Shape
+
+The map points at a state file with a layout key, and lists the profile as a hint:
+
+```yaml
+layout:
+ state: projects.yaml
+profiles:
+ enabled: [node-state]
+```
+
+```yaml
+# projects.yaml: one row per node id
+projects:
+ - id: web-app
+ status: active # active | parked
+ next: Ship the login rework behind a flag.
+ resume_when: "" # for parked rows: the condition that wakes it
+```
+
+Topology stays in the map, status in the state file, joined by `id`. Nothing is copied between them. A hub that already keeps a registry like this only needs the `layout.state` line.
+
+## Why not a `status` field on nodes
+
+Node objects in the Core schema are closed (`additionalProperties: false`), so `status` on a node would fail validation until the schema changes. The profile avoids that: no schema change, old validators keep working. The cost is a second file and a join by `id`. If the profile proves itself, adding optional `status`, `next` and `resume_when` to the node schema is a candidate for a later Map version; it is not proposed here.
+
+## Check
+
+```bash
+python scripts/aap_workspace.py state
+```
+
+Prints one line per node and flags nodes without a row, rows without a node, and a status other than `active` or `parked`. Keep the active list short; a cap (say three) is a rule for your `AGENTS.md`, not for the map.
+
+Example: [`examples/personal-hub/`](../examples/personal-hub/).
diff --git a/cookbook/workspace-tools.md b/cookbook/workspace-tools.md
new file mode 100644
index 0000000..66adad2
--- /dev/null
+++ b/cookbook/workspace-tools.md
@@ -0,0 +1,41 @@
+# Cookbook: workspace tools
+
+Small checks for a hub map, in [`scripts/aap_workspace.py`](../scripts/aap_workspace.py). They need Python, PyYAML (already needed by `validate.py`) and `git`. They read the map and `.aap/map.local.yaml` and change nothing, except `--clone`, which you must pass yourself. Nothing is copied between files: the map stays the single source.
+
+Run from inside the hub; the map is found by searching upward, or pass `--map PATH`.
+
+## Missing checkouts
+
+```bash
+python scripts/aap_workspace.py missing # report + the git clone line
+python scripts/aap_workspace.py missing --clone # actually clone what is missing
+```
+
+For each node the checkout path is the overlay in `map.local.yaml` (`overlays.nodes` or `local_paths`), else the node's own `path`. If it does not exist, the script prints `git clone `. Nodes with no `locator.repo` are reported with "ask the owner". A node with no path anywhere is reported with a hint to add an overlay. `--strict` exits 1 if anything is missing (for scripts).
+
+## Missing nodes
+
+```bash
+python scripts/aap_workspace.py siblings [--root ~/code]
+```
+
+Lists git repositories in the folder next to the hub (or `--root`) that are neither a node's checkout nor a node's `locator.repo`. This is a report: some repos should not be nodes, and that is your call.
+
+## Nodes skeleton
+
+```bash
+python scripts/aap_workspace.py suggest ~/code
+```
+
+Prints a `nodes:` block (id, `locator.repo` from `origin`, `access: read-only`, a `# REVIEW` description) and the matching `overlays` block for `map.local.yaml`. Paste what you want; the script never writes or overwrites a map. Descriptions are yours to write: a node is worth having only if you can say in one line when to open it.
+
+## State and doctor
+
+```bash
+python scripts/aap_workspace.py state # per-node status, see node-state
+python scripts/aap_workspace.py doctor # map schema (if jsonschema is installed) + state, and a missing-checkouts report
+```
+
+`doctor` is the one command to run before a session or in CI; add `alias aap='python scripts/aap_workspace.py'` if you want it shorter. It exits 1 on a schema or state problem. Missing checkouts are only reported (a fresh machine or a partial checkout is normal); use `missing --strict` to fail on them.
+
+See also: [`home-repo`](./home-repo.md), [`hub-umbrella`](./hub-umbrella.md), [`local-bootstrap`](./local-bootstrap.md).
diff --git a/examples/personal-hub/README.md b/examples/personal-hub/README.md
new file mode 100644
index 0000000..5a83988
--- /dev/null
+++ b/examples/personal-hub/README.md
@@ -0,0 +1,12 @@
+# Example: personal hub (synthetic)
+
+The "home repo" shape: one repository you always start the agent in. Generic names only.
+
+| File | Role |
+|------|------|
+| `map.yaml` | Topology: the nodes, plus pointers to the state file and reuse index |
+| `map.local.yaml.example` | Template for the gitignored `.aap/map.local.yaml` (machine paths) |
+| `projects.yaml` | Status per node: active or parked, next step, resume condition |
+| `reuse.md` | Capability index: what to borrow, from which project |
+
+Recipes: [`home-repo`](../../cookbook/home-repo.md), [`node-state`](../../cookbook/node-state.md), [`capability-index`](../../cookbook/capability-index.md), [`workspace-tools`](../../cookbook/workspace-tools.md).
diff --git a/examples/personal-hub/map.local.yaml.example b/examples/personal-hub/map.local.yaml.example
new file mode 100644
index 0000000..2571b2a
--- /dev/null
+++ b/examples/personal-hub/map.local.yaml.example
@@ -0,0 +1,7 @@
+# Copy to .aap/map.local.yaml (gitignored). Navigation only, never grants write access.
+overlays:
+ nodes:
+ web-app: { path: ~/code/web-app }
+ sensor-firmware: { path: ~/code/sensor-firmware }
+ research-notes: { path: ~/code/research-notes }
+ scratch-tools: { path: ~/code/scratch-tools }
diff --git a/examples/personal-hub/map.yaml b/examples/personal-hub/map.yaml
new file mode 100644
index 0000000..2cda5f3
--- /dev/null
+++ b/examples/personal-hub/map.yaml
@@ -0,0 +1,39 @@
+# yaml-language-server: $schema=../../schemas/map.schema.json
+# Synthetic personal hub: the repository you always launch the agent from.
+# Topology lives here; status lives in projects.yaml (node-state profile);
+# machine paths live in the gitignored .aap/map.local.yaml (see map.local.yaml.example).
+version: 2
+workspace:
+ id: personal-hub
+ description: "Thin hub over my own projects: registry, inbox, reuse index."
+self:
+ id: personal-hub
+ kind: repository
+ path: .
+layout:
+ state: projects.yaml
+ reuse: reuse.md
+ daily: daily/
+nodes:
+ - id: web-app
+ kind: repository
+ description: "Customer-facing web app; open for UI and API client work."
+ locator: { repo: example/web-app }
+ access: read-only
+ - id: sensor-firmware
+ kind: repository
+ description: "Firmware for the motion sensor; open for hardware and sampling questions."
+ locator: { repo: example/sensor-firmware }
+ access: read-only
+ - id: research-notes
+ kind: repository
+ description: "Experiments and write-ups; status in its docs/STATE.md."
+ locator: { repo: example/research-notes }
+ access: read-only
+ - id: scratch-tools
+ kind: repository
+ description: "Local-only helper scripts; no remote."
+ access: read-only
+profiles:
+ enabled:
+ - node-state
diff --git a/examples/personal-hub/projects.yaml b/examples/personal-hub/projects.yaml
new file mode 100644
index 0000000..e3ccd26
--- /dev/null
+++ b/examples/personal-hub/projects.yaml
@@ -0,0 +1,18 @@
+# node-state profile: one row per node id. Keep it short: status, next step, resume condition.
+projects:
+ - id: web-app
+ status: active
+ next: Ship the login rework behind a flag.
+ resume_when: ""
+ - id: sensor-firmware
+ status: active
+ next: Re-run the sampling-rate test after the board arrives.
+ resume_when: ""
+ - id: research-notes
+ status: parked
+ next: Write up the second experiment.
+ resume_when: web-app login rework is shipped
+ - id: scratch-tools
+ status: parked
+ next: Nothing planned.
+ resume_when: a task needs a one-off helper script
diff --git a/examples/personal-hub/reuse.md b/examples/personal-hub/reuse.md
new file mode 100644
index 0000000..66f6aa3
--- /dev/null
+++ b/examples/personal-hub/reuse.md
@@ -0,0 +1,9 @@
+# Reuse index: capability -> project
+
+Read when a task smells like "I already did this somewhere". One line per capability; not a dependency graph.
+
+| Capability | Project | Where |
+|---|---|---|
+| Motion features from an IMU on a microcontroller | sensor-firmware | firmware/imu |
+| Offline classification from windowed features | research-notes | docs/experiments/ |
+| Feature-flag wrapper for gradual rollouts | web-app | src/flags/ |
diff --git a/scripts/aap_workspace.py b/scripts/aap_workspace.py
new file mode 100644
index 0000000..4a35fec
--- /dev/null
+++ b/scripts/aap_workspace.py
@@ -0,0 +1,268 @@
+#!/usr/bin/env python3
+"""Workspace helpers for an AAP hub map. Read-only unless --clone is given.
+
+ missing nodes whose checkout is absent, with the `git clone` for locator.repo
+ siblings git repos next to the map's repo that are not in the map's nodes
+ suggest print a nodes skeleton for the git repos in a folder (never writes)
+ state per-node status from the file layout.state points to (node-state profile)
+ doctor schema check (if jsonschema is installed) + state; exit 1 on those; missing checkouts are only reported
+
+Needs only PyYAML (the same dependency as validate.py) and git.
+"""
+from __future__ import annotations
+import argparse
+import json
+import subprocess
+import sys
+from pathlib import Path
+
+try:
+ import yaml # type: ignore
+except ImportError:
+ sys.exit("ERROR: PyYAML required: pip install pyyaml")
+
+
+def load_yaml(path: Path) -> dict:
+ try:
+ data = yaml.safe_load(path.read_text(encoding="utf-8")) or {}
+ except (yaml.YAMLError, OSError, UnicodeDecodeError) as error:
+ sys.exit(f"ERROR: cannot read {path}: {error}")
+ return data if isinstance(data, dict) else {}
+
+
+def get_nodes(data: dict) -> list[dict]:
+ """Node objects that have a string id; anything else is skipped (the schema check reports it)."""
+ nodes = data.get("nodes")
+ return [n for n in nodes if isinstance(n, dict) and isinstance(n.get("id"), str)] if isinstance(nodes, list) else []
+
+
+def as_dict(value: object) -> dict:
+ return value if isinstance(value, dict) else {}
+
+
+def find_map(start: Path) -> Path:
+ for base in [start, *start.parents]:
+ candidate = base / ".aap" / "map.yaml"
+ if candidate.is_file():
+ return candidate
+ sys.exit("ERROR: no .aap/map.yaml found; pass --map")
+
+
+def root_of(map_path: Path) -> Path:
+ """Repo root: parent of .aap/, or the map's own folder for example maps."""
+ return map_path.parent.parent if map_path.parent.name == ".aap" else map_path.parent
+
+
+def overlay_paths(map_path: Path) -> dict[str, str]:
+ """Machine-local checkout paths from the gitignored map.local.yaml (or overlays in the map)."""
+ found: dict[str, str] = {}
+ sources = [load_yaml(map_path), *(load_yaml(p) for p in (map_path.with_name("map.local.yaml"),) if p.is_file())]
+ for data in sources: # the local file comes last and wins
+ overlays = as_dict(data.get("overlays"))
+ for node_id, entry in as_dict(overlays.get("nodes")).items():
+ if isinstance(entry, dict) and entry.get("path"):
+ found[node_id] = entry["path"]
+ for node_id, path in as_dict(overlays.get("local_paths")).items():
+ if isinstance(path, str):
+ found[node_id] = path
+ return found
+
+
+def resolve(node: dict, overlays: dict[str, str], repo_root: Path) -> Path | None:
+ raw = overlays.get(node["id"]) or node.get("path")
+ if not raw or not isinstance(raw, str):
+ return None
+ path = Path(raw).expanduser()
+ return (path if path.is_absolute() else repo_root / path).resolve()
+
+
+def clone_url(repo: str) -> str:
+ if not isinstance(repo, str) or repo.startswith("-") or any(c.isspace() for c in repo):
+ sys.exit(f"ERROR: refusing odd locator.repo {repo!r}")
+ return repo if ("://" in repo or "@" in repo) else f"https://github.com/{repo}.git"
+
+
+def git_remote(path: Path) -> str | None:
+ result = subprocess.run(["git", "-C", str(path), "remote", "get-url", "origin"],
+ capture_output=True, text=True)
+ return result.stdout.strip() if result.returncode == 0 and result.stdout.strip() else None
+
+
+def repo_slug(remote: str | None) -> str | None:
+ """owner/name from a GitHub-style remote URL, else None."""
+ if not remote:
+ return None
+ tail = remote.removesuffix(".git").replace(":", "/").split("/")
+ return "/".join(tail[-2:]) if len(tail) >= 2 else None
+
+
+def git_repos(root: Path) -> list[Path]:
+ if not root.is_dir():
+ sys.exit(f"ERROR: not a folder: {root}")
+ return sorted(p for p in root.iterdir() if p.is_dir() and (p / ".git").exists())
+
+
+def cmd_missing(args: argparse.Namespace) -> int:
+ map_path = Path(args.map).resolve() if args.map else find_map(Path.cwd())
+ repo_root = root_of(map_path)
+ overlays = overlay_paths(map_path)
+ missing = 0
+ for node in get_nodes(load_yaml(map_path)):
+ path = resolve(node, overlays, repo_root)
+ repo = as_dict(node.get("locator")).get("repo")
+ if path and path.exists():
+ print(f"ok {node['id']}: {path}")
+ continue
+ missing += 1
+ if not path:
+ print(f"MISSING {node['id']}: no checkout path (add it to map.local.yaml under overlays.nodes)")
+ if repo:
+ print(f" git clone {clone_url(repo)} ")
+ continue
+ print(f"MISSING {node['id']}: {path}")
+ if not repo:
+ print(" no locator.repo, so nothing to clone; ask the owner")
+ continue
+ print(f" git clone {clone_url(repo)} {path}")
+ if args.clone:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ subprocess.run(["git", "clone", "--", clone_url(repo), str(path)], check=False)
+ print(f"{missing} missing")
+ return 1 if (missing and args.strict) else 0
+
+
+def cmd_siblings(args: argparse.Namespace) -> int:
+ map_path = Path(args.map).resolve() if args.map else find_map(Path.cwd())
+ repo_root = root_of(map_path)
+ root = Path(args.root).expanduser().resolve() if args.root else repo_root.parent
+ data = load_yaml(map_path)
+ overlays = overlay_paths(map_path)
+ known_paths = {repo_root}
+ known_repos: set[str] = set()
+ for node in get_nodes(data):
+ path = resolve(node, overlays, repo_root)
+ if path:
+ known_paths.add(path)
+ repo = as_dict(node.get("locator")).get("repo")
+ if repo:
+ known_repos.add(repo_slug(repo) or repo)
+ extra = 0
+ for repo in git_repos(root):
+ slug = repo_slug(git_remote(repo))
+ if repo.resolve() in known_paths or (slug and slug in known_repos):
+ continue
+ extra += 1
+ print(f"not in map: {repo.name}" + (f" ({slug})" if slug else " (no remote)"))
+ print(f"{extra} repo(s) in {root} are not nodes of {map_path}")
+ return 1 if (extra and args.strict) else 0
+
+
+def cmd_suggest(args: argparse.Namespace) -> int:
+ root = Path(args.root).expanduser().resolve()
+ print(f"# Suggested nodes for the git repos in {root}. Review, trim, then paste into .aap/map.yaml.")
+ print("# Machine paths go in the gitignored .aap/map.local.yaml, not here.")
+ print("nodes:")
+ for repo in git_repos(root):
+ slug = repo_slug(git_remote(repo))
+ node_id = "".join(c if c.isalnum() else "-" for c in repo.name.lower()).strip("-")
+ if not node_id or not node_id[0].isalpha():
+ node_id = f"repo-{node_id}"
+ print(f" - id: {node_id}")
+ print(" kind: repository")
+ print(' description: "REVIEW: one line on when to open this repository."')
+ if slug:
+ print(f" locator:\n repo: {slug}")
+ print(" access: read-only")
+ print("\n# overlays for .aap/map.local.yaml (gitignored):")
+ print("overlays:\n nodes:")
+ for repo in git_repos(root):
+ node_id = "".join(c if c.isalnum() else "-" for c in repo.name.lower()).strip("-")
+ print(f" {node_id}: {{ path: {json.dumps(str(repo))} }}")
+ return 0
+
+
+def cmd_state(args: argparse.Namespace) -> int:
+ map_path = Path(args.map).resolve() if args.map else find_map(Path.cwd())
+ data = load_yaml(map_path)
+ ref = as_dict(data.get("layout")).get("state")
+ ref = ref.get("path") if isinstance(ref, dict) else ref
+ if not isinstance(ref, str):
+ print("no layout.state in the map; nothing to report (node-state profile not used)")
+ return 0
+ if ref.startswith("/") or ".." in Path(ref).parts:
+ print(f"PROBLEM layout.state must be a relative path without '..': {ref}")
+ return 1
+ state_file = root_of(map_path) / ref
+ if not state_file.is_file():
+ print(f"PROBLEM layout.state points to {ref}, which does not exist")
+ return 1
+ projects = load_yaml(state_file).get("projects")
+ rows = {r["id"]: r for r in (projects if isinstance(projects, list) else []) if isinstance(r, dict) and isinstance(r.get("id"), str)}
+ node_ids = [n["id"] for n in get_nodes(data)]
+ problems = 0
+ for node_id in node_ids:
+ row = rows.get(node_id)
+ if not row:
+ problems += 1
+ print(f"NO STATE {node_id}")
+ continue
+ status = str(row.get("status", "?"))
+ if status not in ("active", "parked"):
+ problems += 1
+ status += " (expected active or parked)"
+ line = f"{status:7} {node_id}: {row.get('next', '')}"
+ if row.get("status") == "parked" and row.get("resume_when"):
+ line += f" [resume when: {row['resume_when']}]"
+ print(line)
+ for unknown in sorted(set(rows) - set(node_ids), key=str):
+ problems += 1
+ print(f"UNKNOWN {unknown}: in {ref} but not a node")
+ return 1 if (problems and args.strict) else 0
+
+
+def cmd_doctor(args: argparse.Namespace) -> int:
+ map_path = Path(args.map).resolve() if args.map else find_map(Path.cwd())
+ print(f"== map: {map_path}")
+ schema = Path(__file__).resolve().parents[1] / "schemas" / "map.schema.json"
+ try:
+ import jsonschema # type: ignore
+ errors = list(jsonschema.Draft7Validator(json.loads(schema.read_text())).iter_errors(load_yaml(map_path)))
+ print("schema: ok" if not errors else "schema: FAILED\n " + "\n ".join(e.message for e in errors))
+ failed = bool(errors)
+ except ImportError:
+ print("schema: skipped (pip install jsonschema)")
+ failed = False
+ print("== missing checkouts")
+ # Missing checkouts are reported, not failed: a fresh machine or a partial checkout is normal.
+ cmd_missing(argparse.Namespace(map=str(map_path), clone=False, strict=False))
+ print("== state")
+ failed |= cmd_state(argparse.Namespace(map=str(map_path), strict=True)) != 0
+ return 1 if failed else 0
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ sub = parser.add_subparsers(dest="cmd", required=True)
+ for name, func in (("missing", cmd_missing), ("siblings", cmd_siblings)):
+ p = sub.add_parser(name)
+ p.add_argument("--map", help="path to .aap/map.yaml (default: search upward from cwd)")
+ p.add_argument("--strict", action="store_true", help="exit 1 when something is reported")
+ if name == "missing":
+ p.add_argument("--clone", action="store_true", help="actually run git clone for missing nodes")
+ else:
+ p.add_argument("--root", help="folder to scan (default: parent of the map's repository)")
+ p.set_defaults(func=func)
+ for name, func in (("state", cmd_state), ("doctor", cmd_doctor)):
+ p = sub.add_parser(name)
+ p.add_argument("--map", help="path to .aap/map.yaml (default: search upward from cwd)")
+ p.add_argument("--strict", action="store_true", help="exit 1 when something is reported")
+ p.set_defaults(func=func)
+ p = sub.add_parser("suggest")
+ p.add_argument("root", help="folder that holds the repositories")
+ p.set_defaults(func=cmd_suggest)
+ args = parser.parse_args()
+ return args.func(args)
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())