Metadata-Version: 2.4
Name: agentlaw
Version: 0.1.3
Summary: Law-first governance kit for AI coding agents: installable scaffold + memory MCP server that lets agents read project rules before they write code.
Author-email: paranmir <yhntgb444@gmail.com>
Maintainer-email: paranmir <yhntgb444@gmail.com>
License-Expression: MIT
Project-URL: Homepage, https://github.com/paranmir/agentlaw
Project-URL: Repository, https://github.com/paranmir/agentlaw
Project-URL: Issues, https://github.com/paranmir/agentlaw/issues
Keywords: llm,agents,memory,mcp,harness,governance
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Software Development
Classifier: Topic :: Software Development :: Libraries
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: typer<1,>=0.12
Requires-Dist: mcp<2,>=1.0
Requires-Dist: sqlite-vec<0.2,>=0.1.6
Requires-Dist: PyYAML<7,>=6.0
Provides-Extra: embeddings
Requires-Dist: sentence-transformers<6,>=5.4; extra == "embeddings"
Requires-Dist: huggingface_hub<2,>=1.11; extra == "embeddings"
Provides-Extra: dev
Requires-Dist: build>=1.2; extra == "dev"
Requires-Dist: pytest>=8; extra == "dev"
Provides-Extra: test
Requires-Dist: pytest>=8; extra == "test"
Requires-Dist: mutmut~=2.4; extra == "test"
Requires-Dist: hypothesis<7,>=6.100; extra == "test"
Dynamic: license-file

# agentlaw

A law-first governance kit for AI coding agents — install governance structure before writing code.

`agentlaw` gives any repository a governed starting structure that AI coding agents can read, follow, and maintain. It works for brand-new repositories and already-existing codebases alike. Drop it in, run the bootstrap, and the agent knows what the rules are before it writes a single line.

> This repository is the **authoring workspace** for agentlaw. The public distribution lives at [`paranmir/agentlaw`](https://github.com/paranmir/agentlaw), and the installable Python package will publish to PyPI as `agentlaw`. Most users want the public repo or the PyPI package; this workspace develops the kit using the kit (recursive improvement).

---

## For Humans

### Install

Once published to PyPI:

```bash
pipx install agentlaw
```

The default install is lightweight and keeps the large embedding/model stack
out of the core pipx environment. If you want `agentlaw init` to download the
semantic embedding model, install the optional extra instead:

```bash
pipx install "agentlaw[embeddings]"
```

For an existing pipx install, add the optional stack with:

```bash
pipx inject agentlaw sentence-transformers huggingface_hub
```

While the workspace is still pre-publish, install from this source tree:

```bash
git clone https://github.com/paranmir/agentlaw-workspace
cd agentlaw-workspace
pip install -e .
# Or, with semantic embedding support:
pip install -e ".[embeddings]"
```

### Quick Start

```bash
# 1. Place agentlaw governance into your project
agentlaw init <your-project-dir> --skip-model

# 2. Register the agentlaw-memory MCP server with your AI agent host.
#    The default `--setup-agents prompt` mode emits LLM-actionable
#    instructions — copy them into your agent and let it edit its host
#    config. Restart the host after the edit lands.

# 3. Open a fresh chat with your AI agent on the project and say:
#       Restore the session
#    The agent loads the harness context and you can start work.
```

### Using agentlaw in Your AI Coding Session

Once agentlaw is initialized in a project and the `agentlaw-memory` MCP server is registered with your AI agent host, you drive the harness through natural-language triggers in your conversation. The agent maps each trigger to one of the harness's MCP tools and follows the procedure that the kit ships.

**Triggering session restore** — at the start of any new conversation on the project, say one of:

- "Restore the session" / "세션 복원해봐"
- "Pick up where we left off"
- "지금 어디까지 했어?"

The agent calls `agentlaw_session_restore`, the response packet carries the project's working set, every active plan body, the most recent session_save log entry, framework reminders (memory intent rule, write discipline, consult-before-answer rule), and a step-by-step reminder of the §Canonical Restore Route Mandatory Tier the agent must follow before answering. The first turn of every session is a context-loading turn; substantive work starts on turn two.

**Triggering session save** — when ending a session, before context compaction, or at any milestone, say one of:

- "Save the session" / "세션 저장해줘"
- "Wrap up and save state"
- "Snapshot what we did"

The agent calls `agentlaw_session_save` with the working frame, and the save tool surfaces a post-save verification obligation that you run after.

**When something feels off** — if the agent appears to be answering with stale context or missing rules, ask it to call `agentlaw_session_restore` again, or run `agentlaw mcp-recover --target . --client auto --json` to diagnose MCP connectivity from the shell side.

### Multi-project usage

Install `agentlaw` once with `pipx install agentlaw`, then bootstrap each project independently with `agentlaw init <dir> --skip-model --setup-agents prompt` for the lightweight FTS-only path. Use `pipx install "agentlaw[embeddings]"` or inject the embedding dependencies first if you want `agentlaw init` to download the semantic model. Each initialized project gets its own `<dir>/.harness/index/meta.db`; the memory index is not shared across projects.

Host registration scope differs by agent host:

| Host | Registration scope | Multi-project behavior |
| --- | --- | --- |
| Claude Code | local, per-project and keyed by project path | each project sees only its own `.harness/index/meta.db` |
| Gemini CLI | project-local `.gemini/settings.json` | each project sees only its own `.harness/index/meta.db` |
| Codex | user-level, one global entry | the registration omits `--target`; `agentlaw run-mcp` resolves the target from the cwd where Codex is opened |

`agentlaw verify` checks target scaffold integrity; it does not enforce host MCP scope. Use `agentlaw agent-setup --verify` to check the host registration contract.

### What This Project Is

**The problem.** AI coding agents arrive at a repository without governance. They make plausible-looking changes that violate invariants the team has not written down. The team adds a CLAUDE.md or AGENTS.md to capture rules; the file grows; the agent reads less of it; the rules silently stop applying. The agent and the team need shared structure they can both rely on.

**The kit.** agentlaw installs that structure as governance scaffolding: a constitution, a law layer (memory, artifact, oracle, failure rules), root control tools (init / update / fix), contract documents, a memory subsystem (working set, logs, rules, preferences), and a runtime MCP server that surfaces the rules every session. The agent reads the law before it writes; the kit's verifier mechanically catches drift between the rules and the code.

**Recursive improvement.** This authoring workspace develops agentlaw by using agentlaw on itself. Every plan that lands here goes through `AGENTLAW_INIT_TOOL.md` / `AGENTLAW_UPDATE_TOOL.md` / `AGENTLAW_FIX_TOOL.md` rules; shared law changes are reflected in the bundled package scaffold under `src/agentlaw/scaffold/`; the same `agentlaw verify` that ships to target projects also runs against this repo. The kit's failures and improvements both surface here first.

### Requirements

- **Python** 3.11 or newer (the kit uses `typing.Literal` unpacking and other 3.11-era stdlib features).
- **Operating systems**: developed on Windows; Ubuntu and macOS are exercised through the publish-readiness CI matrix.
- **Disk**: the optional embedding model occupies roughly 500 MB once downloaded (cached under `<your-project>/.harness/models/`).
- **Runtime dependencies** are declared in `pyproject.toml` under `[project] dependencies` (currently `typer`, `mcp`, `sqlite-vec`, `PyYAML`). Optional semantic embedding dependencies live under the `embeddings` extra (`sentence-transformers`, `huggingface_hub`).
- **Dev dependencies** (`pip install -e ".[dev]"`): `build`, `pytest`.

### Repository Layout (this authoring workspace)

```
agentlaw-workspace/
├── AGENTLAW_CONSTITUTION.md         # highest authority
├── AGENTLAW_INIT_TOOL.md            # bootstrap entry
├── AGENTLAW_UPDATE_TOOL.md          # update flow
├── AGENTLAW_FIX_TOOL.md             # gap-fix flow
├── AGENTS.md                       # routing-only entry map
├── README.md                       # this file
├── docs/
│   ├── harness/                    # law layer
│   ├── contracts/                  # contract documents shared with target projects
│   ├── references/                 # local references (binaries gitignored)
│   └── plans/                      # active and completed plans
├── memory/                         # derived continuity (logs, rules, working-set)
├── src/agentlaw/                # Python package (CLI, MCP server, init, verify, scaffold)
├── tests/                          # pytest suite
├── sync_package_data.py            # shared docs → bundled scaffold sync
└── verify_agentlaw.py               # workspace integrity verifier
```

### Links

- **Public seed** (the kit users install): https://github.com/paranmir/agentlaw
- **PyPI** (once published): https://pypi.org/project/agentlaw/
- **This authoring workspace**: https://github.com/paranmir/agentlaw-workspace
- **Issues**: https://github.com/paranmir/agentlaw/issues

---

## For AI Agents

This section is the agent-facing reading order for first-time entry into the kit. If you are reading this README as a new session on a project that has agentlaw installed, follow the §Canonical Restore Route Mandatory Tier in `docs/law/MEMORY_AND_CONTINUITY_RULES.md` instead — that procedure is the binding one. This README is the on-ramp; the law file is the substance.

### Agent Bootstrap (first install)

When the user asks you to set up agentlaw in a project:

1. Install agentlaw from the approved source. Published path (post-release): `pipx install agentlaw`. Use `pipx install "agentlaw[embeddings]"` only when you want local semantic embeddings. Pre-publish source path: `pip install -e .` or `pip install -e ".[embeddings]"` from this workspace.
2. Run `agentlaw init <target-project> --skip-model --setup-agents prompt` in the target for the lightweight path. Omit `--skip-model` only after installing the embedding extra. The `prompt` default emits LLM-actionable instructions for registering the `agentlaw-memory` MCP server in your host config; read those instructions and edit your host config rather than letting init auto-write to user-level config (that requires `--setup-agents auto --yes`).
3. Restart your host after the config edit so the new MCP registration is picked up.
4. On the next agent session, call `agentlaw_session_restore` (MCP) or `agentlaw session-restore --target . --json` (CLI fallback) and follow the §Canonical Restore Route Mandatory Tier in the response.
5. If the MCP server is not visible in a new session despite restart, run `agentlaw mcp-recover --target . --client auto --json` to diagnose runtime + registration state.

### Layer-by-layer map (what each artifact class is for)

- **`AGENTLAW_CONSTITUTION.md`** — highest authority; structural invariants. Rare changes; never violate.
- **Root control tools** (`AGENTLAW_INIT_TOOL.md`, `AGENTLAW_UPDATE_TOOL.md`, `AGENTLAW_FIX_TOOL.md`) — agent-facing procedure documents. Init bootstraps a fresh project, Update incorporates kit upgrades into an existing target, Fix runs the gap-resolution protocol.
- **`docs/law/*` (law layer)** — rules every session reads: memory and continuity, artifact rules, oracle and judgment, code authorship and stewardship, failure taxonomy, mechanical enforcement policy, starter specialization rules, scope, input/output contract.
- **`docs/contracts/*`** — boundary surfaces shared with target projects (MCP tool surface, shared baseline, update workflow). Distributed through the bundled scaffold.
- **`docs/references/*`** — research-and-context references; not authoritative.
- **`memory/*`** — derived continuity (working-set, logs, rules, preferences, lookup rules). Below law in authority.
- **`docs/plans/active/*` and `docs/plans/completed/*`** — work-in-flight and historical work. Active plans are read-on-restore.

### Governing hierarchy

Authority flows top-down:

1. `AGENTLAW_CONSTITUTION.md`
2. Root control tools
3. `docs/law/*` (law)
4. `docs/contracts/*`
5. `docs/references/*` (non-authoritative)
6. `memory/*`
7. `AGENTS.md` (routing only — never a rule store)

When two artifacts seem to conflict, the higher one wins. Memory never overrides law; references never override contracts; AGENTS.md is the entry map, not a source of rules.

### Restore procedure on every session start

§Canonical Restore Route Mandatory Tier (full body in `docs/law/MEMORY_AND_CONTINUITY_RULES.md`) requires 14 steps before composing a substantive response. Summary: confirm runtime integrity, read the working set, read every law file, read every active plan body, read the most recent session_save log entry, scan recent_logs titles, read every active rule's body, read `memory/preferences.md`, read `memory/LOOKUP_RULES.md`, scan the known-facts manifest, run a working-frame `memory_search` over `current_goal + next_actions + open_questions`, inspect governance drift, assemble the packet, surface gaps to the user. The runtime pre-fetches body fields into the restore packet so the substance is in your context without extra `Read` calls; the procedure is binding regardless.

### Critical rules — quick reference

One-line restatements; the binding text lives at the anchors.

- **Memory Intent Rule** — when the user expresses intent to remember, persist, or carry forward, resolve to one of `memory_write` / `promotion_proposal` / `associative_marker` / `explicit_non_save` before final response. Anchor: `docs/law/MEMORY_AND_CONTINUITY_RULES.md` §Memory Intent Rule.
- **Write Discipline** — silence is a valid answer; a write must clear the §Log Write Criterion three-question gate (and the §Item Write Criterion applicability gate for items). Volume is not the target; selectivity is. Anchor: §Write Discipline.
- **Read Routing Criterion** — classify the question (prior judgment / cross-session / current source) before reaching for `memory_search` vs `Grep`/`Read`. Anchor: §Read Routing Criterion.
- **Consult-Before-Answer Rule** — for memory-routed questions, consult memory **before** composing the answer, not after. Anchor: §Consult-Before-Answer Rule.
- **Self-Narration Prohibition** — governed artifact bodies and code comments describe current state only; revision history lives in plans, tracker entries, memory logs, and git, not in the body. Anchor: `docs/law/REPOSITORY_ARTIFACT_RULES.md` §Self-Narration Prohibition (paired with §Reasoning-Critical Inline Comments in `CODE_AUTHORSHIP_AND_STEWARDSHIP_RULES.md`).
- **Promotion Proposal Protocol** — runtime never selects promotion candidates; the agent judges whether durability + future operational relevance + authority gap all hold, then calls `memory_propose_promotion`. Anchor: §Promotion Proposal Protocol.

---

## License

MIT. See `LICENSE`.
