create-lathe 0.0.0-stage → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +135 -2
- package/bin/create-lathe.js +80 -0
- package/dist/framework.lock +113 -0
- package/dist/package/crates/instrument/Cargo.lock +415 -0
- package/dist/package/crates/instrument/Cargo.toml +27 -0
- package/dist/package/crates/instrument/examples/instrument.rs +73 -0
- package/dist/package/crates/instrument/src/client.rs +128 -0
- package/dist/package/crates/instrument/src/lib.rs +32 -0
- package/dist/package/crates/instrument/src/logging.rs +109 -0
- package/dist/package/crates/instrument/src/protocol.rs +49 -0
- package/dist/package/crates/instrument/src/registry.rs +166 -0
- package/dist/package/crates/instrument/src/selftest.rs +314 -0
- package/dist/package/crates/instrument/src/server.rs +303 -0
- package/dist/package/crates/instrument/tests/command_log.rs +60 -0
- package/dist/package/crates/instrument/tests/round_trip.rs +134 -0
- package/dist/package/crates/instrument/tests/selftest_fail.rs +25 -0
- package/dist/package/crates/instrument/tests/selftest_pass.rs +24 -0
- package/dist/package/crates/instrument/tests/support/mod.rs +38 -0
- package/dist/package/pi/context/journal-de-lot.md +24 -0
- package/dist/package/pi/context/tech-skill.md +19 -0
- package/dist/package/pi/context/ticket-closed.md +18 -0
- package/dist/package/scripts/framework.py +1314 -0
- package/dist/package/scripts/gates.py +1134 -0
- package/dist/package/scripts/setup.py +195 -0
- package/dist/package/skills/bootstrap/SKILL.md +110 -0
- package/dist/package/skills/documentation/SKILL.md +110 -0
- package/dist/package/skills/documentation/references/agents-md.md +70 -0
- package/dist/package/skills/documentation/references/corpus.md +112 -0
- package/dist/package/skills/journal/SKILL.md +81 -0
- package/dist/package/skills/journal/references/entry.md +172 -0
- package/dist/package/skills/lathe/SKILL.md +168 -0
- package/dist/package/skills/lathe/evals/routing.md +196 -0
- package/dist/package/skills/lathe/references/install.md +128 -0
- package/dist/package/skills/lathe/references/invariants.md +31 -0
- package/dist/package/skills/mutants/SKILL.md +85 -0
- package/dist/package/skills/mutants/references/cargo-mutants.md +176 -0
- package/dist/package/skills/mutants/references/triage.md +88 -0
- package/dist/package/skills/optimize/SKILL.md +87 -0
- package/dist/package/skills/optimize/references/codspeed.md +126 -0
- package/dist/package/skills/probe/SKILL.md +82 -0
- package/dist/package/skills/probe/references/wait-and-read.md +53 -0
- package/dist/package/skills/replicate-ui/SKILL.md +64 -0
- package/dist/package/skills/rust/SKILL.md +147 -0
- package/dist/package/skills/rust/references/errors.md +63 -0
- package/dist/package/skills/rust/references/unsafe.md +65 -0
- package/dist/package/skills/scaffold/SKILL.md +78 -0
- package/dist/package/skills/scaffold/profiles/rust-cli/.cargo/config.toml +2 -0
- package/dist/package/skills/scaffold/profiles/rust-cli/AGENTS.md +22 -0
- package/dist/package/skills/scaffold/profiles/rust-cli/Cargo.lock +7 -0
- package/dist/package/skills/scaffold/profiles/rust-cli/Cargo.toml +17 -0
- package/dist/package/skills/scaffold/profiles/rust-cli/README.md +15 -0
- package/dist/package/skills/scaffold/profiles/rust-cli/deny.toml +14 -0
- package/dist/package/skills/scaffold/profiles/rust-cli/rustfmt.toml +2 -0
- package/dist/package/skills/scaffold/profiles/rust-cli/src/main.rs +38 -0
- package/dist/package/skills/scaffold/profiles/rust-cli/tests/cli.rs +27 -0
- package/dist/package/skills/scaffold/profiles/rust-library/.cargo/config.toml +2 -0
- package/dist/package/skills/scaffold/profiles/rust-library/AGENTS.md +21 -0
- package/dist/package/skills/scaffold/profiles/rust-library/Cargo.lock +7 -0
- package/dist/package/skills/scaffold/profiles/rust-library/Cargo.toml +18 -0
- package/dist/package/skills/scaffold/profiles/rust-library/README.md +15 -0
- package/dist/package/skills/scaffold/profiles/rust-library/deny.toml +14 -0
- package/dist/package/skills/scaffold/profiles/rust-library/rustfmt.toml +2 -0
- package/dist/package/skills/scaffold/profiles/rust-library/src/lib.rs +25 -0
- package/dist/package/skills/scaffold/profiles/rust-native-desktop/.cargo/config.toml +2 -0
- package/dist/package/skills/scaffold/profiles/rust-native-desktop/AGENTS.md +23 -0
- package/dist/package/skills/scaffold/profiles/rust-native-desktop/Cargo.lock +9252 -0
- package/dist/package/skills/scaffold/profiles/rust-native-desktop/Cargo.toml +24 -0
- package/dist/package/skills/scaffold/profiles/rust-native-desktop/README.md +15 -0
- package/dist/package/skills/scaffold/profiles/rust-native-desktop/deny.toml +35 -0
- package/dist/package/skills/scaffold/profiles/rust-native-desktop/rustfmt.toml +2 -0
- package/dist/package/skills/scaffold/profiles/rust-native-desktop/src/main.rs +74 -0
- package/dist/package/skills/scaffold/references/gates.md +29 -0
- package/dist/package/skills/scaffold/references/profiles.md +36 -0
- package/dist/package/skills/update/SKILL.md +115 -0
- package/dist/package/skills/verify-visual/SKILL.md +82 -0
- package/dist/package/skills/verify-visual/references/baseline.md +46 -0
- package/dist/package/skills/visual-loop/SKILL.md +72 -0
- package/dist/package/workflows/batch-to-review.md +41 -0
- package/dist/package/workflows/framework-improvement.md +38 -0
- package/dist/package/workflows/hard-bug.md +37 -0
- package/dist/package/workflows/new-rust-cli.md +33 -0
- package/dist/package/workflows/new-rust-desktop-app.md +41 -0
- package/dist/package/workflows/new-rust-library.md +34 -0
- package/dist/package/workflows/performance-work.md +41 -0
- package/dist/package/workflows/ui-change.md +40 -0
- package/package.json +33 -4
|
@@ -0,0 +1,1314 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Install this framework into a project, and prove afterwards that nothing moved.
|
|
3
|
+
|
|
4
|
+
Five commands, one file, standard library only:
|
|
5
|
+
|
|
6
|
+
framework.py build-lock # regenerate framework.lock from package/
|
|
7
|
+
framework.py install --project DIR # copy package/, record what was copied
|
|
8
|
+
framework.py doctor --project DIR # verify the recording still holds
|
|
9
|
+
framework.py update --project DIR # move to the source's lock, delta only
|
|
10
|
+
framework.py bootstrap --project DIR # check the preconditions, then install
|
|
11
|
+
framework.py agents --project DIR [--check] # regenerate the map block of AGENTS.md
|
|
12
|
+
|
|
13
|
+
`package/` is the whole delivery. Everything under it ships; nothing outside it is
|
|
14
|
+
ever copied. `TREES` below is the single statement of where each tree lands, so a
|
|
15
|
+
tree added to `package/` without a destination fails the build instead of silently
|
|
16
|
+
shipping nowhere.
|
|
17
|
+
|
|
18
|
+
The delivery carries its own tooling: `package/scripts/` lands at `.agents/scripts/`,
|
|
19
|
+
so a project can run `gates.py` and `framework.py agents` where they are named. A skill
|
|
20
|
+
that tells a project to run a command it does not have is a broken instruction, and the
|
|
21
|
+
only fix is to ship the command.
|
|
22
|
+
|
|
23
|
+
The lock is the contract. It is deterministic (sorted, no timestamps, no paths
|
|
24
|
+
outside the repository) so that two installs of the same commit produce the same
|
|
25
|
+
bytes, and so that a review of a version bump shows exactly which files changed.
|
|
26
|
+
It carries the three fields that identify an installation without `.git`: `version`,
|
|
27
|
+
the short `commit` that produced the trees, and the `digest` of those trees. It also
|
|
28
|
+
carries `source`, the git URL those trees come from, because `update` without
|
|
29
|
+
`--source` must compare against the recorded source and not against whichever
|
|
30
|
+
checkout this script happens to live in (D-30).
|
|
31
|
+
|
|
32
|
+
Everything installed here belongs to one project. A skill in the machine-wide
|
|
33
|
+
`~/.agents/skills/` serves projects that never asked for it, so `doctor` and
|
|
34
|
+
`bootstrap` fail on it rather than warn: `LATHE_GLOBAL_ROOT` moves that root, which
|
|
35
|
+
is how the tests stay away from a real home directory.
|
|
36
|
+
|
|
37
|
+
Exit codes: 0 clean, 1 drift or refusal, 2 usage error.
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
from __future__ import annotations
|
|
41
|
+
|
|
42
|
+
import argparse
|
|
43
|
+
import contextlib
|
|
44
|
+
import hashlib
|
|
45
|
+
import json
|
|
46
|
+
import os
|
|
47
|
+
import re
|
|
48
|
+
import shlex
|
|
49
|
+
import shutil
|
|
50
|
+
import subprocess
|
|
51
|
+
import sys
|
|
52
|
+
import tempfile
|
|
53
|
+
from collections.abc import Iterator
|
|
54
|
+
from dataclasses import dataclass
|
|
55
|
+
from pathlib import Path
|
|
56
|
+
from typing import Any
|
|
57
|
+
|
|
58
|
+
REPO = Path(__file__).resolve().parent.parent.parent
|
|
59
|
+
PACKAGE = REPO / "package"
|
|
60
|
+
LOCK_NAME = "framework.lock"
|
|
61
|
+
# Where each tree of package/ lands in the target project, relative to its root.
|
|
62
|
+
# A tree with no destination here is a defect the build reports, never a no-op.
|
|
63
|
+
TREES = {
|
|
64
|
+
"skills": ".agents/skills",
|
|
65
|
+
"workflows": ".agents/workflows",
|
|
66
|
+
"crates": "crates",
|
|
67
|
+
"pi": ".pi",
|
|
68
|
+
"scripts": ".agents/scripts",
|
|
69
|
+
}
|
|
70
|
+
# Files a working copy grows that the framework never ships. Without this the lock
|
|
71
|
+
# depends on the machine that generated it and installs junk into every project.
|
|
72
|
+
JUNK = {".DS_Store", ".gitkeep"}
|
|
73
|
+
JUNK_DIRS = {"__pycache__", ".ruff_cache", ".git", "target"}
|
|
74
|
+
STATE_DIR = ".framework"
|
|
75
|
+
STATE_NAME = "installed.json"
|
|
76
|
+
# The lock the upstream skills CLI writes, read by `doctor` to report the commit the
|
|
77
|
+
# project actually holds rather than the one this module pinned.
|
|
78
|
+
SKILLS_LOCK = "skills-lock.json"
|
|
79
|
+
UPSTREAM = {"name": "mattpocock/skills", "commit": "bbadaa6", "skills": 39}
|
|
80
|
+
UPSTREAM_HINT = "npx --yes skills add mattpocock/skills"
|
|
81
|
+
# The 27 names `npx skills add mattpocock/skills` installs, measured 2026-11-28 in
|
|
82
|
+
# .agents/skills/. They are mandatory because the workflows cite them by name.
|
|
83
|
+
MATTPOCOCK_SKILLS = (
|
|
84
|
+
"ask-matt",
|
|
85
|
+
"chief-of-staff",
|
|
86
|
+
"claude-handoff",
|
|
87
|
+
"code-review",
|
|
88
|
+
"codebase-design",
|
|
89
|
+
"diagnosing-bugs",
|
|
90
|
+
"domain-modeling",
|
|
91
|
+
"git-guardrails-claude-code",
|
|
92
|
+
"grill-me",
|
|
93
|
+
"grill-with-docs",
|
|
94
|
+
"grilling",
|
|
95
|
+
"handoff",
|
|
96
|
+
"implement",
|
|
97
|
+
"implement-spec",
|
|
98
|
+
"improve-codebase-architecture",
|
|
99
|
+
"loop-me",
|
|
100
|
+
"migrate-to-shoehorn",
|
|
101
|
+
"pr",
|
|
102
|
+
"prototype",
|
|
103
|
+
"research",
|
|
104
|
+
"retro",
|
|
105
|
+
"scaffold-exercises",
|
|
106
|
+
"setup-matt-pocock-skills",
|
|
107
|
+
"setup-pre-commit",
|
|
108
|
+
"setup-ts-deep-modules",
|
|
109
|
+
"software-factory",
|
|
110
|
+
"tdd",
|
|
111
|
+
"teach",
|
|
112
|
+
"to-questionnaire",
|
|
113
|
+
"to-spec",
|
|
114
|
+
"to-tickets",
|
|
115
|
+
"triage",
|
|
116
|
+
"wait-what",
|
|
117
|
+
"wayfinder",
|
|
118
|
+
"wizard",
|
|
119
|
+
"writing-beats",
|
|
120
|
+
"writing-for-agents",
|
|
121
|
+
"writing-fragments",
|
|
122
|
+
"writing-shape",
|
|
123
|
+
)
|
|
124
|
+
# The second upstream: CodSpeed's three performance skills, measured 2026-11-29 by
|
|
125
|
+
# installing them with their own CLI. `optimize` names them, so install waits for them
|
|
126
|
+
# exactly as it waits for the Matt Pocock set: declared here, installed by the CLI,
|
|
127
|
+
# never copied into this package.
|
|
128
|
+
CODSPEED_SKILLS = ("codspeed-setup-harness", "codspeed-write-benchmarks", "codspeed-optimize")
|
|
129
|
+
CODSPEED = {
|
|
130
|
+
"name": "CodSpeedHQ/codspeed",
|
|
131
|
+
"commit": "ff27652",
|
|
132
|
+
"skills": len(CODSPEED_SKILLS),
|
|
133
|
+
"names": CODSPEED_SKILLS,
|
|
134
|
+
"hint": "npx --yes skills add https://github.com/CodSpeedHQ/codspeed "
|
|
135
|
+
+ " ".join(f"--skill {name}" for name in CODSPEED_SKILLS),
|
|
136
|
+
}
|
|
137
|
+
# Heterogeneous by design (name, commit, count, names, hint); Any keeps the reader on
|
|
138
|
+
# the registry rather than on a TypedDict that exists only to satisfy the checker.
|
|
139
|
+
UPSTREAMS: tuple[dict[str, Any], ...] = (
|
|
140
|
+
dict(UPSTREAM, names=MATTPOCOCK_SKILLS, hint=UPSTREAM_HINT),
|
|
141
|
+
CODSPEED,
|
|
142
|
+
)
|
|
143
|
+
# A declared dependency, not a bonus: the extension injects `.pi/context/*.md`, which
|
|
144
|
+
# is how this framework states a rule at the moment it applies (BACKLOG I-03).
|
|
145
|
+
PI_DEPENDENCY = "no-more-agents-dot-md"
|
|
146
|
+
PI_DEPENDENCY_HINT = "pi install git:github.com/TheophileBaudouin/No-More-Agents-Dot-MD"
|
|
147
|
+
# Technology -> the official skill a project needs before using it. One entry today:
|
|
148
|
+
# `gpui-kit` is the toolkit the rust-native-desktop profile assumes, and Lathe
|
|
149
|
+
# names `gpui-kit-design-guides` as its upstream skill.
|
|
150
|
+
TECHNOLOGIES = {"gpui-kit": "gpui-kit-design-guides"}
|
|
151
|
+
UNKNOWN_COMMIT = "unknown"
|
|
152
|
+
UNKNOWN_SOURCE = "unknown"
|
|
153
|
+
GLOBAL_ROOT_ENV = "LATHE_GLOBAL_ROOT"
|
|
154
|
+
# A remote spelled the way a shell writes it: `git@host:path`, no scheme.
|
|
155
|
+
SCP_LIKE = re.compile(r"^[^@/]+@(?P<host>[^:/]+):(?P<path>.+)$")
|
|
156
|
+
# A remote with a scheme. The userinfo group is matched so that it can be dropped.
|
|
157
|
+
URL_PARTS = re.compile(
|
|
158
|
+
r"^(?P<scheme>[A-Za-z][A-Za-z0-9+.-]*)://(?:[^@/]*@)?(?P<host>[^/:]+)(?::(?P<port>\d+))?(?P<path>/.*)?$"
|
|
159
|
+
)
|
|
160
|
+
# The schemes that reach a repository over ssh rather than over https.
|
|
161
|
+
SSH_SCHEMES = frozenset({"ssh", "git", "git+ssh", "ssh+git"})
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def fail(message: str, code: int = 1) -> int:
|
|
165
|
+
print(f"error: {message}", file=sys.stderr)
|
|
166
|
+
return code
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def digest(path: Path) -> str:
|
|
170
|
+
return hashlib.sha256(path.read_bytes()).hexdigest()
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def load_json(path: Path, hint: str) -> dict:
|
|
174
|
+
"""Read a JSON file, reporting the two ways it usually goes wrong."""
|
|
175
|
+
if not path.is_file():
|
|
176
|
+
raise SystemExit(f"error: {path.name} missing — {hint}")
|
|
177
|
+
try:
|
|
178
|
+
return json.loads(path.read_text(encoding="utf-8"))
|
|
179
|
+
except (OSError, json.JSONDecodeError) as exc:
|
|
180
|
+
raise SystemExit(f"error: {path.name} is unreadable ({exc}) — {hint}") from exc
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def read_lock() -> dict:
|
|
184
|
+
return load_json(REPO / LOCK_NAME, "run build-lock first")
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def walk_tree(root: Path) -> dict[str, str]:
|
|
188
|
+
"""Hash every shippable file under one tree, relative to that tree."""
|
|
189
|
+
files: dict[str, str] = {}
|
|
190
|
+
for file in sorted(root.rglob("*")):
|
|
191
|
+
relative = file.relative_to(root)
|
|
192
|
+
if file.is_file() and file.name not in JUNK and not JUNK_DIRS & set(relative.parts):
|
|
193
|
+
files[relative.as_posix()] = digest(file)
|
|
194
|
+
return files
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def build_lock() -> dict:
|
|
198
|
+
"""Describe every file the framework ships, by tree, sorted."""
|
|
199
|
+
if not PACKAGE.is_dir():
|
|
200
|
+
raise SystemExit(f"error: {PACKAGE} missing — package/ is the whole delivery")
|
|
201
|
+
trees: dict[str, dict[str, str]] = {}
|
|
202
|
+
orphans = []
|
|
203
|
+
for folder in sorted(p for p in PACKAGE.iterdir() if p.is_dir()):
|
|
204
|
+
if folder.name not in TREES:
|
|
205
|
+
orphans.append(folder.name)
|
|
206
|
+
continue
|
|
207
|
+
files = walk_tree(folder)
|
|
208
|
+
if files:
|
|
209
|
+
trees[folder.name] = files
|
|
210
|
+
if orphans:
|
|
211
|
+
raise SystemExit(
|
|
212
|
+
f"error: package/{', package/'.join(orphans)} has no destination in TREES — "
|
|
213
|
+
"add it to the table or move it out of package/, so that what ships stays one list"
|
|
214
|
+
)
|
|
215
|
+
return {
|
|
216
|
+
"framework": "lathe",
|
|
217
|
+
"version": read_version(),
|
|
218
|
+
"commit": read_commit(REPO),
|
|
219
|
+
"digest": tree_digest(trees),
|
|
220
|
+
"source": read_source(REPO),
|
|
221
|
+
"upstream": {
|
|
222
|
+
source["name"]: {k: source[k] for k in ("name", "commit", "skills")}
|
|
223
|
+
for source in UPSTREAMS
|
|
224
|
+
},
|
|
225
|
+
"trees": trees,
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def read_version() -> str:
|
|
230
|
+
return "0.4.0"
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def read_commit(root: Path) -> str:
|
|
234
|
+
"""The short commit that last changed the shipped tree, or `unknown` outside a checkout.
|
|
235
|
+
|
|
236
|
+
A tarball has no `.git`, and it is a valid delivery: a missing git is a value,
|
|
237
|
+
never an error. Without it two installations of the same version are the same
|
|
238
|
+
installation, which is the defect `commit` exists to remove.
|
|
239
|
+
|
|
240
|
+
The commit is scoped to `package/`, not to `HEAD`: a lock that records `HEAD`
|
|
241
|
+
is stale the instant it is committed, because committing the lock moves `HEAD`
|
|
242
|
+
and leaves `package/` untouched. Recording the last commit that touched what
|
|
243
|
+
ships keeps the field meaningful and the check satisfiable.
|
|
244
|
+
"""
|
|
245
|
+
try:
|
|
246
|
+
proc = subprocess.run(
|
|
247
|
+
("git", "log", "-1", "--format=%h", "--", PACKAGE.name),
|
|
248
|
+
cwd=root,
|
|
249
|
+
capture_output=True,
|
|
250
|
+
text=True,
|
|
251
|
+
encoding="utf-8",
|
|
252
|
+
errors="replace",
|
|
253
|
+
)
|
|
254
|
+
except OSError:
|
|
255
|
+
return UNKNOWN_COMMIT
|
|
256
|
+
commit = proc.stdout.strip()
|
|
257
|
+
return commit if proc.returncode == 0 and commit else UNKNOWN_COMMIT
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def read_source(root: Path) -> str:
|
|
261
|
+
"""The git URL those trees come from, or `unknown` without a remote.
|
|
262
|
+
|
|
263
|
+
A URL is the only value that survives a copy: a path would name one machine and
|
|
264
|
+
make the lock depend on where it was built. `unknown` is a value, not an error,
|
|
265
|
+
and `update` refuses it with the one instruction that fixes it.
|
|
266
|
+
|
|
267
|
+
The URL is normalised (`normalized_source`), because the lock's first promise is
|
|
268
|
+
that two installs of one commit produce the same bytes: an ssh clone and an https
|
|
269
|
+
clone of this repository are the same repository, and must not write two locks.
|
|
270
|
+
"""
|
|
271
|
+
try:
|
|
272
|
+
proc = subprocess.run(
|
|
273
|
+
("git", "remote", "get-url", "origin"),
|
|
274
|
+
cwd=root,
|
|
275
|
+
capture_output=True,
|
|
276
|
+
text=True,
|
|
277
|
+
encoding="utf-8",
|
|
278
|
+
errors="replace",
|
|
279
|
+
)
|
|
280
|
+
except OSError:
|
|
281
|
+
return UNKNOWN_SOURCE
|
|
282
|
+
url = proc.stdout.strip()
|
|
283
|
+
return normalized_source(url) if proc.returncode == 0 and url else UNKNOWN_SOURCE
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def normalized_source(url: str) -> str:
|
|
287
|
+
"""One string for one repository, whatever route the checkout used to reach it.
|
|
288
|
+
|
|
289
|
+
`git@host:path` and `ssh://git@host/path` become `https://host/path`, credentials
|
|
290
|
+
are dropped, and the host is lowercased: a token in the remote, or a colleague's
|
|
291
|
+
ssh clone, would otherwise put something machine-specific in a committed lock.
|
|
292
|
+
A spelling this function does not recognise is returned unchanged — a lock that
|
|
293
|
+
records the remote verbatim is wrong only in reproducibility, never in meaning.
|
|
294
|
+
"""
|
|
295
|
+
scp = SCP_LIKE.match(url)
|
|
296
|
+
if scp:
|
|
297
|
+
return f"https://{scp.group('host').lower()}/{scp.group('path').lstrip('/')}"
|
|
298
|
+
parts = URL_PARTS.match(url)
|
|
299
|
+
if not parts:
|
|
300
|
+
return url
|
|
301
|
+
host = parts.group("host").lower()
|
|
302
|
+
path = (parts.group("path") or "").lstrip("/")
|
|
303
|
+
if parts.group("scheme").lower() in SSH_SCHEMES:
|
|
304
|
+
return f"https://{host}/{path}"
|
|
305
|
+
port = parts.group("port")
|
|
306
|
+
return f"{parts.group('scheme').lower()}://{host}{f':{port}' if port else ''}/{path}"
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def tree_digest(trees: dict[str, dict[str, str]]) -> str:
|
|
310
|
+
"""sha256 of the canonical trees map: the content identity of one delivery.
|
|
311
|
+
|
|
312
|
+
`version` alone cannot tell two builds apart. This can: same version, one
|
|
313
|
+
changed file, and the digest differs. `commit` says which history produced it.
|
|
314
|
+
"""
|
|
315
|
+
canonical = json.dumps(trees, sort_keys=True, separators=(",", ":"))
|
|
316
|
+
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def render(lock: dict) -> str:
|
|
320
|
+
return json.dumps(lock, indent=2, sort_keys=True) + "\n"
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def flat(lock: dict) -> dict[tuple[str, str], str]:
|
|
324
|
+
return {
|
|
325
|
+
(tree, rel): digest_
|
|
326
|
+
for tree, files in lock.get("trees", {}).items()
|
|
327
|
+
for rel, digest_ in files.items()
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
def counted(lock: dict) -> str:
|
|
332
|
+
trees = lock.get("trees", {})
|
|
333
|
+
parts = [f"{len(files)} {tree}" for tree, files in sorted(trees.items())]
|
|
334
|
+
return f"{sum(len(f) for f in trees.values())} files ({', '.join(parts)})"
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def usable_source(source: object) -> bool:
|
|
338
|
+
"""Whether a `source` names a repository. `unknown` names none (`read_source`)."""
|
|
339
|
+
return bool(source) and source != UNKNOWN_SOURCE
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
def identity_fields(lock: dict, other: dict, *, compare_commit: bool = True) -> list[str]:
|
|
343
|
+
"""The identity fields two locks disagree on.
|
|
344
|
+
|
|
345
|
+
`commit` is compared only when the two locks are siblings — a project's record
|
|
346
|
+
against a source's lock, which is what `update` decides on. It is not compared by
|
|
347
|
+
the local `--check`, because a lock cannot record the commit that contains it: the
|
|
348
|
+
commit that regenerates the lock also changes the tree, so the comparison is
|
|
349
|
+
unsatisfiable by construction. There, `digest` is the whole integrity claim, and it
|
|
350
|
+
is the one that catches a real drift.
|
|
351
|
+
|
|
352
|
+
`source` is compared only when both sides name a repository. It records where a
|
|
353
|
+
lock was built, not which trees it describes, so `unknown` — a checkout with no
|
|
354
|
+
`origin`, which is how the delivered lock was made — on either side is not a
|
|
355
|
+
disagreement. Comparing it would make the shipped lock permanently stale in every
|
|
356
|
+
clone, and a lock regenerated in a clone would then disagree again with `unknown`.
|
|
357
|
+
"""
|
|
358
|
+
compared = ("version", "commit", "digest", "source")
|
|
359
|
+
return [
|
|
360
|
+
key
|
|
361
|
+
for key in compared
|
|
362
|
+
if lock.get(key) != other.get(key)
|
|
363
|
+
and (key != "source" or usable_source(lock.get(key)) and usable_source(other.get(key)))
|
|
364
|
+
and (key != "commit" or compare_commit)
|
|
365
|
+
]
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
def cmd_build_lock(argv: list[str]) -> int:
|
|
369
|
+
"""Regenerate the lock, or verify it is current with --check.
|
|
370
|
+
|
|
371
|
+
--check exists because a lock you can forget to regenerate is not a lock:
|
|
372
|
+
`install` copies what the lock says, so a stale hash writes a wrong record
|
|
373
|
+
and `doctor` then reports DRIFT on a healthy install.
|
|
374
|
+
"""
|
|
375
|
+
parser = argparse.ArgumentParser(prog="framework.py build-lock")
|
|
376
|
+
parser.add_argument("--check", action="store_true", help="fail if the committed lock is stale")
|
|
377
|
+
args = parser.parse_args(argv)
|
|
378
|
+
|
|
379
|
+
lock = build_lock()
|
|
380
|
+
path = REPO / LOCK_NAME
|
|
381
|
+
|
|
382
|
+
if not args.check:
|
|
383
|
+
path.write_text(render(lock), encoding="utf-8")
|
|
384
|
+
print(f"{LOCK_NAME}: {counted(lock)}")
|
|
385
|
+
return 0
|
|
386
|
+
|
|
387
|
+
if not path.is_file():
|
|
388
|
+
return fail(f"{LOCK_NAME} missing — run build-lock")
|
|
389
|
+
on_disk = load_json(path, "run build-lock")
|
|
390
|
+
fresh, stale = flat(lock), flat(on_disk)
|
|
391
|
+
missing = sorted(set(fresh) - set(stale))
|
|
392
|
+
extra = sorted(set(stale) - set(fresh))
|
|
393
|
+
changed = sorted(key for key in set(fresh) & set(stale) if fresh[key] != stale[key])
|
|
394
|
+
for label, keys in (("not in lock", missing), ("no longer shipped", extra), ("hash differs", changed)):
|
|
395
|
+
for tree, rel in keys:
|
|
396
|
+
print(f" {label}: {tree}/{rel}", file=sys.stderr)
|
|
397
|
+
# The identity fields are compared too: a lock whose `commit` or `digest` lies is
|
|
398
|
+
# exactly the defect they were added to close, and a file diff would not show it.
|
|
399
|
+
identity_diff = identity_fields(lock, on_disk, compare_commit=False)
|
|
400
|
+
for key in identity_diff:
|
|
401
|
+
print(f" {key} differs: lock has {on_disk.get(key)!r}, package/ gives {lock.get(key)!r}", file=sys.stderr)
|
|
402
|
+
if missing or extra or changed or identity_diff:
|
|
403
|
+
return fail(f"{LOCK_NAME} is stale — run build-lock and commit the result")
|
|
404
|
+
print(f"{LOCK_NAME}: up to date ({counted(lock)})")
|
|
405
|
+
return 0
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
def cmd_install(argv: list[str]) -> int:
|
|
409
|
+
args = parse_install_args(argv)
|
|
410
|
+
lock = read_lock()
|
|
411
|
+
project = args.project.resolve()
|
|
412
|
+
if not project.is_dir():
|
|
413
|
+
return fail(f"{project} is not a directory", 2)
|
|
414
|
+
if "trees" not in lock:
|
|
415
|
+
return fail(f"{LOCK_NAME} predates the package/ layout — run build-lock", 2)
|
|
416
|
+
|
|
417
|
+
planned: list[tuple[Path, Path]] = []
|
|
418
|
+
conflicts: list[str] = []
|
|
419
|
+
stale: list[str] = []
|
|
420
|
+
for tree, files in lock["trees"].items():
|
|
421
|
+
if tree not in TREES:
|
|
422
|
+
return fail(f"{LOCK_NAME} names tree {tree!r} with no destination — run build-lock", 2)
|
|
423
|
+
for rel, expected in files.items():
|
|
424
|
+
src = PACKAGE / tree / rel
|
|
425
|
+
# The lock is copied, not scanned: a lock entry whose file is gone or
|
|
426
|
+
# changed would either crash mid-copy or record a hash the install does
|
|
427
|
+
# not produce, and `doctor` would then report DRIFT on a fresh install.
|
|
428
|
+
if not src.is_file() or digest(src) != expected:
|
|
429
|
+
stale.append(f"{tree}/{rel}")
|
|
430
|
+
continue
|
|
431
|
+
dst = project / TREES[tree] / rel
|
|
432
|
+
if dst.exists() and digest(dst) != digest(src):
|
|
433
|
+
conflicts.append(dst.relative_to(project).as_posix())
|
|
434
|
+
planned.append((src, dst))
|
|
435
|
+
|
|
436
|
+
if stale:
|
|
437
|
+
return fail(
|
|
438
|
+
f"package/ does not match {LOCK_NAME} for {len(stale)} file(s) "
|
|
439
|
+
f"(first: {stale[0]}) — run build-lock, then install again",
|
|
440
|
+
1,
|
|
441
|
+
)
|
|
442
|
+
|
|
443
|
+
if conflicts and not args.force:
|
|
444
|
+
print("refusing: these files exist with different content", file=sys.stderr)
|
|
445
|
+
for path in conflicts:
|
|
446
|
+
print(f" {path}", file=sys.stderr)
|
|
447
|
+
print("nothing was written. Re-run with --force to overwrite, or move them aside.", file=sys.stderr)
|
|
448
|
+
return 1
|
|
449
|
+
|
|
450
|
+
if args.dry_run:
|
|
451
|
+
for _, dst in planned:
|
|
452
|
+
print(f"would write {dst.relative_to(project).as_posix()}")
|
|
453
|
+
print(f"{len(planned)} files, {len(conflicts)} conflict(s), dry run")
|
|
454
|
+
return 0
|
|
455
|
+
|
|
456
|
+
for src, dst in planned:
|
|
457
|
+
dst.parent.mkdir(parents=True, exist_ok=True)
|
|
458
|
+
shutil.copyfile(src, dst)
|
|
459
|
+
|
|
460
|
+
state = project / STATE_DIR / STATE_NAME
|
|
461
|
+
state.parent.mkdir(parents=True, exist_ok=True)
|
|
462
|
+
state.write_text(json.dumps(lock, indent=2, sort_keys=True) + "\n", encoding="utf-8")
|
|
463
|
+
|
|
464
|
+
print(f"installed {counted(lock)} into {project}")
|
|
465
|
+
# Reaching here with a conflict means --force was given, so each one was a user
|
|
466
|
+
# file this command just replaced. Naming them is the only record of the loss.
|
|
467
|
+
for path in conflicts:
|
|
468
|
+
print(f" overwritten: {path}")
|
|
469
|
+
for tree in sorted(lock["trees"]):
|
|
470
|
+
print(f" {TREES[tree]}/")
|
|
471
|
+
print("\nupstream pinned:")
|
|
472
|
+
for source in UPSTREAMS:
|
|
473
|
+
print(f" {source['name']} @ {source['commit']} ({source['skills']} skills)")
|
|
474
|
+
print("each is installed by its own CLI, never copied here")
|
|
475
|
+
return 0
|
|
476
|
+
|
|
477
|
+
|
|
478
|
+
def parse_install_args(argv: list[str]) -> argparse.Namespace:
|
|
479
|
+
parser = argparse.ArgumentParser(prog="framework.py install")
|
|
480
|
+
parser.add_argument("--project", required=True, type=Path)
|
|
481
|
+
parser.add_argument("--dry-run", action="store_true")
|
|
482
|
+
parser.add_argument("--force", action="store_true")
|
|
483
|
+
return parser.parse_args(argv)
|
|
484
|
+
|
|
485
|
+
|
|
486
|
+
def lathe_skill_names() -> list[str]:
|
|
487
|
+
"""The skills this delivery ships: one per directory under package/skills.
|
|
488
|
+
|
|
489
|
+
Derived from the package, not from a list: a skill added to `package/` is covered
|
|
490
|
+
by the global check the day it ships, with nothing to keep in sync.
|
|
491
|
+
"""
|
|
492
|
+
skills = PACKAGE / "skills"
|
|
493
|
+
if not skills.is_dir():
|
|
494
|
+
return []
|
|
495
|
+
return sorted(folder.name for folder in skills.iterdir() if folder.is_dir())
|
|
496
|
+
|
|
497
|
+
|
|
498
|
+
def global_root() -> Path:
|
|
499
|
+
"""Where Pi keeps machine-wide state. Overridable so no test writes in a real home."""
|
|
500
|
+
override = os.environ.get(GLOBAL_ROOT_ENV)
|
|
501
|
+
return Path(override).expanduser() if override else Path.home()
|
|
502
|
+
|
|
503
|
+
|
|
504
|
+
def global_skills() -> Path:
|
|
505
|
+
return global_root() / ".agents" / "skills"
|
|
506
|
+
|
|
507
|
+
|
|
508
|
+
def pi_modules() -> Path:
|
|
509
|
+
return global_root() / ".pi" / "agent" / "npm" / "node_modules"
|
|
510
|
+
|
|
511
|
+
|
|
512
|
+
def global_lathe_skills() -> list[str]:
|
|
513
|
+
"""Names of our skills found machine-wide: each one is a project that did not ask."""
|
|
514
|
+
root = global_skills()
|
|
515
|
+
return [name for name in lathe_skill_names() if (root / name).exists()]
|
|
516
|
+
|
|
517
|
+
|
|
518
|
+
def missing_pi_dependency() -> Path | None:
|
|
519
|
+
"""The path the declared Pi extension should occupy, or None when it is there."""
|
|
520
|
+
module = pi_modules() / PI_DEPENDENCY
|
|
521
|
+
return None if module.is_dir() else module
|
|
522
|
+
|
|
523
|
+
|
|
524
|
+
def state_problem(recorded: object) -> str:
|
|
525
|
+
"""Why `.framework/installed.json` cannot be used as a lock, or empty when it can.
|
|
526
|
+
|
|
527
|
+
A file that parses but is not a lock (`[]`, `null`, `"x"`, `{"trees": []}`) is the
|
|
528
|
+
same defect as an unreadable one: every caller would crash on it, so it is named
|
|
529
|
+
here once and answered with the one repair that works. The trees map is checked
|
|
530
|
+
down to its leaves for the same reason: `{"trees": {"skills": []}}` passes an
|
|
531
|
+
`isinstance(..., dict)` test and then raises on the first `.items()`.
|
|
532
|
+
"""
|
|
533
|
+
if not isinstance(recorded, dict):
|
|
534
|
+
return f"is not a JSON object (found {type(recorded).__name__})"
|
|
535
|
+
trees = recorded.get("trees")
|
|
536
|
+
if not isinstance(trees, dict):
|
|
537
|
+
return "has no trees map"
|
|
538
|
+
for tree, files in trees.items():
|
|
539
|
+
if not isinstance(files, dict) or not all(
|
|
540
|
+
isinstance(rel, str) and isinstance(expected, str) for rel, expected in files.items()
|
|
541
|
+
):
|
|
542
|
+
return f"has a tree {tree!r} that is not a map of path to sha256"
|
|
543
|
+
return ""
|
|
544
|
+
|
|
545
|
+
|
|
546
|
+
def project_upstream_commits(project: Path) -> dict[str, str]:
|
|
547
|
+
"""source -> the commit this project's own skills lock names for it.
|
|
548
|
+
|
|
549
|
+
The module constant is what this framework pinned; the project's lock is what it
|
|
550
|
+
holds. Reporting the constant would hide exactly the drift the field exists for.
|
|
551
|
+
"""
|
|
552
|
+
for relative in (Path(".agents") / SKILLS_LOCK, Path(SKILLS_LOCK)):
|
|
553
|
+
path = project / relative
|
|
554
|
+
if not path.is_file():
|
|
555
|
+
continue
|
|
556
|
+
try:
|
|
557
|
+
data = json.loads(path.read_text(encoding="utf-8"))
|
|
558
|
+
except (OSError, json.JSONDecodeError):
|
|
559
|
+
continue
|
|
560
|
+
skills = data.get("skills") if isinstance(data, dict) else None
|
|
561
|
+
if not isinstance(skills, dict):
|
|
562
|
+
continue
|
|
563
|
+
held: dict[str, str] = {}
|
|
564
|
+
for entry in skills.values():
|
|
565
|
+
if not isinstance(entry, dict):
|
|
566
|
+
continue
|
|
567
|
+
source, commit = str(entry.get("source") or ""), str(entry.get("commit") or "")
|
|
568
|
+
if source and commit:
|
|
569
|
+
held[source] = commit
|
|
570
|
+
if held:
|
|
571
|
+
return held
|
|
572
|
+
return {}
|
|
573
|
+
|
|
574
|
+
|
|
575
|
+
def cmd_doctor(argv: list[str]) -> int:
|
|
576
|
+
parser = argparse.ArgumentParser(prog="framework.py doctor")
|
|
577
|
+
parser.add_argument("--project", default=".", type=Path)
|
|
578
|
+
args = parser.parse_args(argv)
|
|
579
|
+
project = args.project.resolve()
|
|
580
|
+
|
|
581
|
+
# Machine-wide state comes first: a global skill or an absent extension spoils
|
|
582
|
+
# every project at once, so it is reported before this project's own files.
|
|
583
|
+
global_lathe = global_lathe_skills()
|
|
584
|
+
if global_lathe:
|
|
585
|
+
print(f"DRIFT — {', '.join(global_lathe)} installed globally in {global_skills()}", file=sys.stderr)
|
|
586
|
+
print("a global skill serves projects that never asked for it; remove it:", file=sys.stderr)
|
|
587
|
+
for name in global_lathe:
|
|
588
|
+
print(f" rm -rf {shlex.quote(str(global_skills() / name))}", file=sys.stderr)
|
|
589
|
+
return 1
|
|
590
|
+
absent_dependency = missing_pi_dependency()
|
|
591
|
+
if absent_dependency is not None:
|
|
592
|
+
return fail(
|
|
593
|
+
f"{PI_DEPENDENCY} is not installed ({absent_dependency}) — it injects the "
|
|
594
|
+
f".pi/context/ rules this framework relies on; install it with: {PI_DEPENDENCY_HINT}",
|
|
595
|
+
1,
|
|
596
|
+
)
|
|
597
|
+
|
|
598
|
+
state = project / STATE_DIR / STATE_NAME
|
|
599
|
+
if not state.is_file():
|
|
600
|
+
return fail(f"no {STATE_DIR}/{STATE_NAME} in {project} — the framework is not installed here")
|
|
601
|
+
|
|
602
|
+
try:
|
|
603
|
+
recorded = json.loads(state.read_text(encoding="utf-8"))
|
|
604
|
+
except (OSError, json.JSONDecodeError) as exc:
|
|
605
|
+
return fail(f"{STATE_DIR}/{STATE_NAME} is unreadable ({exc}) — reinstall to repair")
|
|
606
|
+
|
|
607
|
+
problem = state_problem(recorded)
|
|
608
|
+
if problem:
|
|
609
|
+
return fail(f"{STATE_DIR}/{STATE_NAME} {problem} — reinstall to repair")
|
|
610
|
+
missing, modified, ok = [], [], 0
|
|
611
|
+
unknown = [tree for tree in recorded["trees"] if tree not in TREES]
|
|
612
|
+
if unknown:
|
|
613
|
+
return fail(f"{STATE_DIR}/{STATE_NAME} names unknown trees {unknown} — reinstall to repair")
|
|
614
|
+
for tree, files in recorded["trees"].items():
|
|
615
|
+
for rel, expected in files.items():
|
|
616
|
+
path = project / TREES[tree] / rel
|
|
617
|
+
if not path.is_file():
|
|
618
|
+
missing.append(path.relative_to(project).as_posix())
|
|
619
|
+
elif digest(path) != expected:
|
|
620
|
+
modified.append(path.relative_to(project).as_posix())
|
|
621
|
+
else:
|
|
622
|
+
ok += 1
|
|
623
|
+
|
|
624
|
+
# The identity of the installation, and the upstream commit the project holds.
|
|
625
|
+
# Two installs of one version from two commits are otherwise indistinguishable.
|
|
626
|
+
skills_dir = project / ".agents" / "skills"
|
|
627
|
+
held_commits = project_upstream_commits(project)
|
|
628
|
+
|
|
629
|
+
print(f"checked {ok + len(missing) + len(modified)} files in {project}")
|
|
630
|
+
print(f"installed {identity(recorded)}")
|
|
631
|
+
print(f"global {global_skills()} — no Lathe skill installed globally")
|
|
632
|
+
print(f"pi {PI_DEPENDENCY} present in {pi_modules()}")
|
|
633
|
+
print(f" ok {ok}")
|
|
634
|
+
print(f" missing {len(missing)}")
|
|
635
|
+
print(f" modified {len(modified)}")
|
|
636
|
+
absent_by_source: list[tuple[dict[str, Any], list[str]]] = []
|
|
637
|
+
for source in UPSTREAMS:
|
|
638
|
+
names = tuple(source["names"])
|
|
639
|
+
held = [name for name in names if (skills_dir / name / "SKILL.md").is_file()]
|
|
640
|
+
absent = [name for name in names if name not in set(held)]
|
|
641
|
+
recorded = held_commits.get(str(source["name"])) or f"not recorded in {SKILLS_LOCK}"
|
|
642
|
+
print(f"upstream {source['name']} @ {recorded}: present {len(held)}/{len(names)}")
|
|
643
|
+
if absent:
|
|
644
|
+
absent_by_source.append((source, absent))
|
|
645
|
+
|
|
646
|
+
for label, items in (("missing", missing), ("modified", modified)):
|
|
647
|
+
for item in items:
|
|
648
|
+
print(f" {label}: {item}")
|
|
649
|
+
|
|
650
|
+
drifted = False
|
|
651
|
+
if missing or modified:
|
|
652
|
+
print("\nDRIFT — an agent reading a modified skill is not running this framework.", file=sys.stderr)
|
|
653
|
+
print("Re-run install with --force to restore from the repository of record.", file=sys.stderr)
|
|
654
|
+
drifted = True
|
|
655
|
+
for source, absent in absent_by_source:
|
|
656
|
+
print(
|
|
657
|
+
f"\nDRIFT — {len(absent)} of {source['skills']} {source['name']} skills "
|
|
658
|
+
f"are missing in {skills_dir}: {', '.join(absent)}",
|
|
659
|
+
file=sys.stderr,
|
|
660
|
+
)
|
|
661
|
+
print(f"a step names them; install them with:\n {source['hint']}", file=sys.stderr)
|
|
662
|
+
drifted = True
|
|
663
|
+
if drifted:
|
|
664
|
+
return 1
|
|
665
|
+
print("\nCLEAN")
|
|
666
|
+
return 0
|
|
667
|
+
|
|
668
|
+
|
|
669
|
+
def identity(lock: dict) -> str:
|
|
670
|
+
"""`version (commit, digest8)` — the three fields that tell two installs apart."""
|
|
671
|
+
return f"{lock.get('version', '?')} ({lock.get('commit', UNKNOWN_COMMIT)}, {str(lock.get('digest') or '?')[:8]})"
|
|
672
|
+
|
|
673
|
+
|
|
674
|
+
@dataclass(frozen=True)
|
|
675
|
+
class Source:
|
|
676
|
+
"""A fresh lock, and the package/ tree its hashes describe."""
|
|
677
|
+
|
|
678
|
+
lock: dict
|
|
679
|
+
package: Path
|
|
680
|
+
|
|
681
|
+
|
|
682
|
+
class SourceError(RuntimeError):
|
|
683
|
+
"""The fresh lock could not be obtained. The message says what to do about it.
|
|
684
|
+
|
|
685
|
+
`code` is 2 — usage — for every one of them, including a recorded lock that has no
|
|
686
|
+
usable `source`: that is fixed by `--source PATH|URL`, which is an argument, and 1
|
|
687
|
+
already means "an update is available" for this command. Reporting a missing
|
|
688
|
+
`source` as 1 would make a lock nobody can update read as a lock with news in it.
|
|
689
|
+
"""
|
|
690
|
+
|
|
691
|
+
def __init__(self, message: str, code: int = 2) -> None:
|
|
692
|
+
super().__init__(message)
|
|
693
|
+
self.code = code
|
|
694
|
+
|
|
695
|
+
|
|
696
|
+
def read_lock_file(path: Path) -> dict:
|
|
697
|
+
"""A lock read from somewhere else, with the one field every comparison needs."""
|
|
698
|
+
if not path.is_file():
|
|
699
|
+
raise SourceError(f"{path} missing — point --source at a Lathe checkout, not at a project")
|
|
700
|
+
try:
|
|
701
|
+
lock = json.loads(path.read_text(encoding="utf-8"))
|
|
702
|
+
except (OSError, json.JSONDecodeError) as exc:
|
|
703
|
+
raise SourceError(f"{path} is unreadable ({exc}) — run build-lock in the source checkout") from exc
|
|
704
|
+
# `[]` and `null` parse, and `.get` on them raises AttributeError: a traceback in
|
|
705
|
+
# place of the usage error this command promises, with code 1 read as "news".
|
|
706
|
+
if not isinstance(lock, dict) or not isinstance(lock.get("trees"), dict) or not lock["trees"]:
|
|
707
|
+
raise SourceError(
|
|
708
|
+
f"{path} has no trees map (found {type(lock).__name__}) — run build-lock in the source checkout"
|
|
709
|
+
)
|
|
710
|
+
return lock
|
|
711
|
+
|
|
712
|
+
|
|
713
|
+
def is_url(source: str) -> bool:
|
|
714
|
+
"""A source carrying a scheme, or the scp-like `git@host:path`, is cloned."""
|
|
715
|
+
return "://" in source or source.startswith("git@")
|
|
716
|
+
|
|
717
|
+
|
|
718
|
+
def clone(url: str, checkout: Path) -> None:
|
|
719
|
+
"""Shallow clone: only the lock and the current trees are read, never the history."""
|
|
720
|
+
try:
|
|
721
|
+
proc = subprocess.run(
|
|
722
|
+
("git", "clone", "--depth", "1", "--quiet", url, str(checkout)),
|
|
723
|
+
capture_output=True,
|
|
724
|
+
text=True,
|
|
725
|
+
encoding="utf-8",
|
|
726
|
+
errors="replace",
|
|
727
|
+
)
|
|
728
|
+
except OSError as exc:
|
|
729
|
+
raise SourceError(f"cannot run git ({exc}) — install git, or pass --source PATH") from exc
|
|
730
|
+
if proc.returncode != 0:
|
|
731
|
+
tail = (proc.stderr or proc.stdout).strip().splitlines()[-3:]
|
|
732
|
+
detail = " | ".join(tail) or f"code {proc.returncode}"
|
|
733
|
+
raise SourceError(f"git clone {url} failed ({detail}) — check the URL, or pass --source PATH")
|
|
734
|
+
|
|
735
|
+
|
|
736
|
+
def recorded_source(recorded: dict) -> str:
|
|
737
|
+
"""The `source` of a recorded lock, or a usage refusal naming the one repair.
|
|
738
|
+
|
|
739
|
+
A lock built before the field existed, or built on a checkout with no `origin`,
|
|
740
|
+
carries no usable URL. Comparing against this script's own checkout instead would
|
|
741
|
+
answer the wrong question, so the command stops and says which flag answers it.
|
|
742
|
+
"""
|
|
743
|
+
source = recorded.get("source")
|
|
744
|
+
if not usable_source(source):
|
|
745
|
+
raise SourceError(
|
|
746
|
+
f"no source recorded ({source or 'field absent'}); pass --source PATH|URL",
|
|
747
|
+
2,
|
|
748
|
+
)
|
|
749
|
+
return str(source)
|
|
750
|
+
|
|
751
|
+
|
|
752
|
+
def source_repair(recorded: dict, fresh: dict, provided: str | None) -> bool:
|
|
753
|
+
"""Whether the recorded `source` must be written from the fresh lock.
|
|
754
|
+
|
|
755
|
+
Without `--source` an unusable `source` is a refusal, so the only way back to a
|
|
756
|
+
state that updates on its own is to write the field when the flag supplies what
|
|
757
|
+
the last install could not record. Version, commit and digest can be identical
|
|
758
|
+
here — nothing else would ask for a write — so the repair is its own reason.
|
|
759
|
+
"""
|
|
760
|
+
recordable = usable_source(fresh.get("source"))
|
|
761
|
+
return provided is not None and recordable and not usable_source(recorded.get("source"))
|
|
762
|
+
|
|
763
|
+
|
|
764
|
+
@contextlib.contextmanager
|
|
765
|
+
def source_tree(source: str | None, recorded: dict) -> Iterator[Source]:
|
|
766
|
+
"""The package/ tree to copy from, and the lock that describes it.
|
|
767
|
+
|
|
768
|
+
`--source` wins. Without it the source recorded by the last install is used: the
|
|
769
|
+
git URL of the framework this project holds (D-30), never the checkout this
|
|
770
|
+
script happens to live in — those are two different repositories as soon as
|
|
771
|
+
anyone installs from a fork, a branch or a tag.
|
|
772
|
+
|
|
773
|
+
A URL is cloned into a temporary directory that this context removes on the way
|
|
774
|
+
out, including when the copy fails halfway: a failed update leaves no clone.
|
|
775
|
+
"""
|
|
776
|
+
if source is None:
|
|
777
|
+
source = recorded_source(recorded)
|
|
778
|
+
if is_url(source):
|
|
779
|
+
with tempfile.TemporaryDirectory(prefix="lathe-update-") as tmp:
|
|
780
|
+
checkout = Path(tmp) / "lathe"
|
|
781
|
+
clone(source, checkout)
|
|
782
|
+
yield Source(read_lock_file(checkout / LOCK_NAME), checkout / "package")
|
|
783
|
+
return
|
|
784
|
+
checkout = Path(source).expanduser()
|
|
785
|
+
yield Source(read_lock_file(checkout / LOCK_NAME), checkout / "package")
|
|
786
|
+
|
|
787
|
+
|
|
788
|
+
def unknown_trees(lock: dict) -> list[str]:
|
|
789
|
+
"""Trees the lock names that TREES has no destination for: the lock is newer."""
|
|
790
|
+
return sorted(tree for tree in lock.get("trees", {}) if tree not in TREES)
|
|
791
|
+
|
|
792
|
+
|
|
793
|
+
def plan_update(
|
|
794
|
+
project: Path, recorded: dict, fresh: dict
|
|
795
|
+
) -> tuple[list[tuple[str, str]], list[tuple[str, str]], list[tuple[str, str]]]:
|
|
796
|
+
"""Sort every shipped path into (delta, edited, removed), three hashes at a time.
|
|
797
|
+
|
|
798
|
+
The order of the branches is the contract: a path the user touched is named and
|
|
799
|
+
never written without --force, so a local change survives the update that would
|
|
800
|
+
have erased it.
|
|
801
|
+
"""
|
|
802
|
+
known, wanted = flat(recorded), flat(fresh)
|
|
803
|
+
delta: list[tuple[str, str]] = []
|
|
804
|
+
edited: list[tuple[str, str]] = []
|
|
805
|
+
removed: list[tuple[str, str]] = []
|
|
806
|
+
for key in sorted(set(known) | set(wanted)):
|
|
807
|
+
tree, rel = key
|
|
808
|
+
target = project / TREES[tree] / rel
|
|
809
|
+
on_disk = digest(target) if target.is_file() else None
|
|
810
|
+
if key not in wanted:
|
|
811
|
+
removed.append(key)
|
|
812
|
+
elif key in known and on_disk != known[key]:
|
|
813
|
+
# Disk differs from what was installed: the user edited it, or deleted it.
|
|
814
|
+
edited.append(key)
|
|
815
|
+
elif key not in known and on_disk is not None and on_disk != wanted[key]:
|
|
816
|
+
# An unrecorded file sits where the framework now ships one: also theirs.
|
|
817
|
+
edited.append(key)
|
|
818
|
+
elif on_disk != wanted[key]:
|
|
819
|
+
delta.append(key)
|
|
820
|
+
return delta, edited, removed
|
|
821
|
+
|
|
822
|
+
|
|
823
|
+
def apply_update(project: Path, recorded: dict, source: Source, args: argparse.Namespace) -> int:
|
|
824
|
+
"""Report, or write the delta, then record the fresh lock as the new truth."""
|
|
825
|
+
fresh = source.lock
|
|
826
|
+
# A source lock naming a tree this framework has no destination for is a newer
|
|
827
|
+
# framework, not a usage error: the answer is to update the framework first.
|
|
828
|
+
unknown = unknown_trees(fresh)
|
|
829
|
+
if unknown:
|
|
830
|
+
return fail(
|
|
831
|
+
f"the source lock names trees {unknown} this framework has no destination for — "
|
|
832
|
+
"update the framework itself first",
|
|
833
|
+
1,
|
|
834
|
+
)
|
|
835
|
+
|
|
836
|
+
absent = sorted(
|
|
837
|
+
f"{tree}/{rel}" for tree, rel in flat(fresh) if not (source.package / tree / rel).is_file()
|
|
838
|
+
)
|
|
839
|
+
if absent:
|
|
840
|
+
return fail(
|
|
841
|
+
f"the source lock describes {len(absent)} file(s) its package/ does not have "
|
|
842
|
+
f"(first: {absent[0]}) — run build-lock in the source checkout",
|
|
843
|
+
1,
|
|
844
|
+
)
|
|
845
|
+
|
|
846
|
+
delta, edited, removed = plan_update(project, recorded, fresh)
|
|
847
|
+
# A lock can move without a single file moving: the source bumped its version or
|
|
848
|
+
# moved to another commit over the same tree. The project would stay recorded
|
|
849
|
+
# under a version it no longer holds, so that divergence counts and is written.
|
|
850
|
+
identity_moved = identity(recorded) != identity(fresh)
|
|
851
|
+
# And a record can be repaired without any tree moving: a `source` of `unknown`
|
|
852
|
+
# refuses the next run, so `--source` writes what the last install could not record.
|
|
853
|
+
repaired = source_repair(recorded, fresh, args.source)
|
|
854
|
+
|
|
855
|
+
if args.check:
|
|
856
|
+
print(f"{identity(recorded)} -> {identity(fresh)}")
|
|
857
|
+
for label, keys in (
|
|
858
|
+
("out of date", delta),
|
|
859
|
+
("modified locally", edited),
|
|
860
|
+
("no longer shipped", removed),
|
|
861
|
+
):
|
|
862
|
+
for tree, rel in keys:
|
|
863
|
+
print(f" {label}: {TREES[tree]}/{rel}")
|
|
864
|
+
if identity_moved and not (delta or edited or removed):
|
|
865
|
+
print(f" identity differs: {identity(recorded)} -> {identity(fresh)}, no file moved")
|
|
866
|
+
if repaired:
|
|
867
|
+
print(
|
|
868
|
+
f" source only: {recorded.get('source')!r} -> {fresh.get('source')!r}, no file moved"
|
|
869
|
+
)
|
|
870
|
+
if delta or edited or removed or identity_moved or repaired:
|
|
871
|
+
return 1
|
|
872
|
+
print("up to date — nothing to write")
|
|
873
|
+
return 0
|
|
874
|
+
|
|
875
|
+
if edited and not args.force:
|
|
876
|
+
print("refusing: these files changed locally since the last install", file=sys.stderr)
|
|
877
|
+
for tree, rel in edited:
|
|
878
|
+
print(f" {TREES[tree]}/{rel}", file=sys.stderr)
|
|
879
|
+
print(
|
|
880
|
+
"nothing was written. Keep your version, or re-run with --force to overwrite it.",
|
|
881
|
+
file=sys.stderr,
|
|
882
|
+
)
|
|
883
|
+
return 1
|
|
884
|
+
|
|
885
|
+
writes = delta + (edited if args.force else [])
|
|
886
|
+
if not writes and not removed and not identity_moved and not repaired:
|
|
887
|
+
print(f"{identity(fresh)} — nothing to write")
|
|
888
|
+
return 0
|
|
889
|
+
|
|
890
|
+
for tree, rel in writes:
|
|
891
|
+
destination = project / TREES[tree] / rel
|
|
892
|
+
destination.parent.mkdir(parents=True, exist_ok=True)
|
|
893
|
+
shutil.copyfile(source.package / tree / rel, destination)
|
|
894
|
+
(project / STATE_DIR / STATE_NAME).write_text(render(fresh), encoding="utf-8")
|
|
895
|
+
|
|
896
|
+
print(f"{identity(recorded)} -> {identity(fresh)}")
|
|
897
|
+
if identity_moved and not writes and not removed:
|
|
898
|
+
print(" identity only: no file moved, the recorded lock was rewritten")
|
|
899
|
+
if repaired:
|
|
900
|
+
print(
|
|
901
|
+
f" source only: recorded source written ({recorded.get('source')!r} -> "
|
|
902
|
+
f"{fresh.get('source')!r}), no file moved, so the next run needs no --source"
|
|
903
|
+
)
|
|
904
|
+
for tree, rel in writes:
|
|
905
|
+
print(f" written: {TREES[tree]}/{rel}")
|
|
906
|
+
for tree, rel in removed:
|
|
907
|
+
print(f" no longer shipped, left in place: {TREES[tree]}/{rel}")
|
|
908
|
+
print(f"{len(writes)} file(s) written, {counted(fresh)}")
|
|
909
|
+
return 1
|
|
910
|
+
|
|
911
|
+
|
|
912
|
+
def cmd_update(argv: list[str]) -> int:
|
|
913
|
+
"""Move an installed project to the source's lock, writing only the delta.
|
|
914
|
+
|
|
915
|
+
The source is `--source` when given, and the git source recorded by the last
|
|
916
|
+
install otherwise (D-30): a checkout this script happens to sit in is not the
|
|
917
|
+
repository the project came from.
|
|
918
|
+
|
|
919
|
+
Exit 0 means nothing differed. Exit 1 means something was written — an update that
|
|
920
|
+
was available, or a recorded `source` that `--source` repaired — because the
|
|
921
|
+
contract gives this command no third value and a caller must be able to gate on
|
|
922
|
+
"something moved". Exit 2 means the invocation itself was wrong, including a
|
|
923
|
+
`--source` that cannot be read and a record that names no source at all.
|
|
924
|
+
"""
|
|
925
|
+
parser = argparse.ArgumentParser(prog="framework.py update")
|
|
926
|
+
parser.add_argument("--project", required=True, type=Path)
|
|
927
|
+
parser.add_argument(
|
|
928
|
+
"--source",
|
|
929
|
+
help="a Lathe checkout, or a URL cloned shallowly; default: the source the last install recorded",
|
|
930
|
+
)
|
|
931
|
+
parser.add_argument(
|
|
932
|
+
"--check",
|
|
933
|
+
action="store_true",
|
|
934
|
+
help="report only: writes nothing, exits 1 on any divergence",
|
|
935
|
+
)
|
|
936
|
+
parser.add_argument("--force", action="store_true", help="overwrite files edited locally")
|
|
937
|
+
args = parser.parse_args(argv)
|
|
938
|
+
|
|
939
|
+
project = args.project.resolve()
|
|
940
|
+
if not project.is_dir():
|
|
941
|
+
return fail(f"{project} is not a directory", 2)
|
|
942
|
+
|
|
943
|
+
state = project / STATE_DIR / STATE_NAME
|
|
944
|
+
if not state.is_file():
|
|
945
|
+
return fail(
|
|
946
|
+
f"no {STATE_DIR}/{STATE_NAME} in {project} — nothing is installed here; "
|
|
947
|
+
"run bootstrap or install first",
|
|
948
|
+
1,
|
|
949
|
+
)
|
|
950
|
+
try:
|
|
951
|
+
recorded = json.loads(state.read_text(encoding="utf-8"))
|
|
952
|
+
except (OSError, json.JSONDecodeError) as exc:
|
|
953
|
+
return fail(f"{STATE_DIR}/{STATE_NAME} is unreadable ({exc}) — reinstall to repair", 1)
|
|
954
|
+
problem = state_problem(recorded)
|
|
955
|
+
if problem:
|
|
956
|
+
return fail(f"{STATE_DIR}/{STATE_NAME} {problem} — reinstall to repair", 1)
|
|
957
|
+
# A corrupt record is reported before the source is resolved: otherwise a state
|
|
958
|
+
# defect would clone a repository to learn what a local file already says.
|
|
959
|
+
unknown = unknown_trees(recorded)
|
|
960
|
+
if unknown:
|
|
961
|
+
return fail(
|
|
962
|
+
f"{STATE_DIR}/{STATE_NAME} names trees {unknown} with no destination — reinstall, then update",
|
|
963
|
+
1,
|
|
964
|
+
)
|
|
965
|
+
|
|
966
|
+
try:
|
|
967
|
+
with source_tree(args.source, recorded) as source:
|
|
968
|
+
return apply_update(project, recorded, source, args)
|
|
969
|
+
except SourceError as exc:
|
|
970
|
+
return fail(str(exc), exc.code)
|
|
971
|
+
|
|
972
|
+
|
|
973
|
+
def dependency_pattern(technology: str) -> re.Pattern[str]:
|
|
974
|
+
"""Every shape a Cargo manifest declares one dependency in, one line at a time.
|
|
975
|
+
|
|
976
|
+
Four spellings mean the same thing and each one was missed by a `name =` search:
|
|
977
|
+
`gpui-kit = "0.11"`, `"gpui-kit" = "0.11"`, `gpui-kit.workspace = true`, and the
|
|
978
|
+
table form `[dependencies.gpui-kit]`. A technology the gate cannot see is a skill
|
|
979
|
+
nobody asks for, so the pattern is the guard, not a convenience.
|
|
980
|
+
"""
|
|
981
|
+
name = re.escape(technology)
|
|
982
|
+
key = rf'(?:{name}|"{name}")'
|
|
983
|
+
# `gpui-kit = …`, `"gpui-kit" = …`, `gpui-kit.workspace = true`
|
|
984
|
+
assignment = rf"^\s*{key}(?:\.[A-Za-z0-9_-]+)*\s*="
|
|
985
|
+
# `[dependencies.gpui-kit]`, `[dependencies."gpui-kit"]`, `[target.'cfg(..)'.dependencies.gpui-kit]`
|
|
986
|
+
table = rf"^\s*\[\s*(?:[^\]\n]*\.)?{key}\s*\]"
|
|
987
|
+
# MULTILINE as a flag, not as an inline `(?m)`: Python 3.11 refuses a global flag
|
|
988
|
+
# that is not at the start of the pattern, and this pattern is an alternation.
|
|
989
|
+
return re.compile(f"(?:{assignment})|(?:{table})", re.MULTILINE)
|
|
990
|
+
|
|
991
|
+
|
|
992
|
+
def detected_technologies(project: Path) -> dict[str, str]:
|
|
993
|
+
"""Technologies this project uses, each with the official skill it requires.
|
|
994
|
+
|
|
995
|
+
The manifest is scanned as text, not parsed: `tomllib` arrives in 3.11, and every
|
|
996
|
+
shape a dependency takes on one line is recognised by `dependency_pattern`.
|
|
997
|
+
"""
|
|
998
|
+
manifest = project / "Cargo.toml"
|
|
999
|
+
if not manifest.is_file():
|
|
1000
|
+
return {}
|
|
1001
|
+
text = manifest.read_text(encoding="utf-8", errors="replace")
|
|
1002
|
+
return {
|
|
1003
|
+
technology: skill
|
|
1004
|
+
for technology, skill in TECHNOLOGIES.items()
|
|
1005
|
+
if dependency_pattern(technology).search(text)
|
|
1006
|
+
}
|
|
1007
|
+
|
|
1008
|
+
|
|
1009
|
+
def cmd_bootstrap(argv: list[str]) -> int:
|
|
1010
|
+
"""Prepare a project from zero, refusing while a precondition is unmet.
|
|
1011
|
+
|
|
1012
|
+
The order is the contract. A global Lathe skill makes every project read the
|
|
1013
|
+
wrong copy, so it is refused before anything is written; the upstream skills are
|
|
1014
|
+
mandatory because the workflows cite them by name; the Pi extension is the
|
|
1015
|
+
injection mechanism, not a bonus. Only then is package/ installed.
|
|
1016
|
+
"""
|
|
1017
|
+
parser = argparse.ArgumentParser(prog="framework.py bootstrap")
|
|
1018
|
+
parser.add_argument("--project", required=True, type=Path)
|
|
1019
|
+
parser.add_argument("--force", action="store_true", help="overwrite files that differ")
|
|
1020
|
+
args = parser.parse_args(argv)
|
|
1021
|
+
|
|
1022
|
+
project = args.project.resolve()
|
|
1023
|
+
if not project.is_dir():
|
|
1024
|
+
return fail(f"{project} is not a directory", 2)
|
|
1025
|
+
|
|
1026
|
+
# 1. Nothing of ours may live in the machine-wide skills directory.
|
|
1027
|
+
global_lathe = global_lathe_skills()
|
|
1028
|
+
if global_lathe:
|
|
1029
|
+
print(
|
|
1030
|
+
f"refusing: {', '.join(global_lathe)} installed globally in {global_skills()}",
|
|
1031
|
+
file=sys.stderr,
|
|
1032
|
+
)
|
|
1033
|
+
print("a global skill serves projects that never asked for it; remove it first:", file=sys.stderr)
|
|
1034
|
+
for name in global_lathe:
|
|
1035
|
+
print(f" rm -rf {shlex.quote(str(global_skills() / name))}", file=sys.stderr)
|
|
1036
|
+
return 1
|
|
1037
|
+
|
|
1038
|
+
# 2. Both upstream sources are mandatory: a step names each of their skills.
|
|
1039
|
+
installed = project / ".agents" / "skills"
|
|
1040
|
+
missing_sources = []
|
|
1041
|
+
for source in UPSTREAMS:
|
|
1042
|
+
absent = [
|
|
1043
|
+
name for name in source["names"] if not (installed / name / "SKILL.md").is_file()
|
|
1044
|
+
]
|
|
1045
|
+
if absent:
|
|
1046
|
+
missing_sources.append((source, absent))
|
|
1047
|
+
if missing_sources:
|
|
1048
|
+
for source, absent in missing_sources:
|
|
1049
|
+
print(
|
|
1050
|
+
f"refusing: {len(absent)} of {source['skills']} {source['name']} skills are missing "
|
|
1051
|
+
f"in {installed}",
|
|
1052
|
+
file=sys.stderr,
|
|
1053
|
+
)
|
|
1054
|
+
for name in absent:
|
|
1055
|
+
print(f" {name}", file=sys.stderr)
|
|
1056
|
+
print(f"install them with:\n {source['hint']}", file=sys.stderr)
|
|
1057
|
+
return 1
|
|
1058
|
+
|
|
1059
|
+
# 3. The declared Pi extension is what injects .pi/context/*.md.
|
|
1060
|
+
absent_dependency = missing_pi_dependency()
|
|
1061
|
+
if absent_dependency is not None:
|
|
1062
|
+
print(
|
|
1063
|
+
f"refusing: {PI_DEPENDENCY} is not installed ({absent_dependency})", file=sys.stderr
|
|
1064
|
+
)
|
|
1065
|
+
print(f"install it with:\n {PI_DEPENDENCY_HINT}", file=sys.stderr)
|
|
1066
|
+
return 1
|
|
1067
|
+
|
|
1068
|
+
# 4. Copy the trees and record them; install owns the copy, including --force.
|
|
1069
|
+
code = cmd_install(["--project", str(project)] + (["--force"] if args.force else []))
|
|
1070
|
+
if code != 0:
|
|
1071
|
+
return code
|
|
1072
|
+
|
|
1073
|
+
# 5. Name the official skill each detected technology needs, or say it is there.
|
|
1074
|
+
for technology, skill in sorted(detected_technologies(project).items()):
|
|
1075
|
+
if (installed / skill / "SKILL.md").is_file():
|
|
1076
|
+
print(f"{technology} detected — {skill} present")
|
|
1077
|
+
else:
|
|
1078
|
+
print(
|
|
1079
|
+
f"{technology} detected — install the official skill {skill} in "
|
|
1080
|
+
f"{installed} before using it, or gates.py deps stays red"
|
|
1081
|
+
)
|
|
1082
|
+
print(f"\nready — {project}")
|
|
1083
|
+
return 0
|
|
1084
|
+
|
|
1085
|
+
|
|
1086
|
+
BLOCK_BEGIN = "<!-- lathe:begin"
|
|
1087
|
+
BLOCK_END = "<!-- lathe:end -->"
|
|
1088
|
+
BLOCK_HEAD = (
|
|
1089
|
+
BLOCK_BEGIN
|
|
1090
|
+
+ " — regenerate with `framework.py agents --project .`; edit outside this block -->"
|
|
1091
|
+
)
|
|
1092
|
+
|
|
1093
|
+
|
|
1094
|
+
def workspace_members(project: Path) -> list[str]:
|
|
1095
|
+
"""The crates the root manifest names, in the order it names them."""
|
|
1096
|
+
manifest = project / "Cargo.toml"
|
|
1097
|
+
if not manifest.is_file():
|
|
1098
|
+
return []
|
|
1099
|
+
try:
|
|
1100
|
+
text = manifest.read_text(encoding="utf-8", errors="replace")
|
|
1101
|
+
except OSError:
|
|
1102
|
+
return []
|
|
1103
|
+
match = re.search(r"(?ms)^\s*\[workspace\].*?^\s*members\s*=\s*\[(.*?)\]", text)
|
|
1104
|
+
if match is None:
|
|
1105
|
+
return []
|
|
1106
|
+
return [m.strip().strip('"').strip("'") for m in match.group(1).split(",") if m.strip()]
|
|
1107
|
+
|
|
1108
|
+
|
|
1109
|
+
def agents_map(project: Path) -> list[str]:
|
|
1110
|
+
"""The map a session needs, computed from what exists.
|
|
1111
|
+
|
|
1112
|
+
A path that is gone stops being named, and that is the whole anti-rot mechanism:
|
|
1113
|
+
the block cannot point at a file that no longer exists, because it is derived from
|
|
1114
|
+
the tree rather than remembered. Everything an agent discovers with `ls` is left
|
|
1115
|
+
out; everything a skill already owns is cited by one line, never restated.
|
|
1116
|
+
"""
|
|
1117
|
+
rows: list[str] = []
|
|
1118
|
+
docs = project / "documentation" / "llm"
|
|
1119
|
+
if (docs / "README.md").is_file():
|
|
1120
|
+
count = len(list(docs.glob("*.md")))
|
|
1121
|
+
rows.append(
|
|
1122
|
+
"- Documentation for agents: `documentation/llm/README.md` — read the index, "
|
|
1123
|
+
f"then the one file for the subject ({count} files)."
|
|
1124
|
+
)
|
|
1125
|
+
for filename, label in (
|
|
1126
|
+
("decisions.md", "Decisions"),
|
|
1127
|
+
("decisions", "Decisions"),
|
|
1128
|
+
("pieges.md", "Traps"),
|
|
1129
|
+
("pitfalls.md", "Traps"),
|
|
1130
|
+
("glossaire.md", "Glossary"),
|
|
1131
|
+
("glossary.md", "Glossary"),
|
|
1132
|
+
):
|
|
1133
|
+
candidate = docs / filename
|
|
1134
|
+
if candidate.is_file() or candidate.is_dir():
|
|
1135
|
+
rows.append(f"- {label}: `documentation/llm/{filename}`.")
|
|
1136
|
+
journal = project / "documentation" / "changelog"
|
|
1137
|
+
if journal.is_dir():
|
|
1138
|
+
entries = len(list(journal.glob("*.md")))
|
|
1139
|
+
plural = "entry" if entries == 1 else "entries"
|
|
1140
|
+
rows.append(
|
|
1141
|
+
f"- Lot journal: `documentation/changelog/` — {entries} {plural}, append-only. "
|
|
1142
|
+
"An entry is never rewritten."
|
|
1143
|
+
)
|
|
1144
|
+
if (project / ".scratch").is_dir():
|
|
1145
|
+
rows.append(
|
|
1146
|
+
"- Tickets: `.scratch/<feature>/issues/<NN>-<slug>.md` — a ticked box is a claim "
|
|
1147
|
+
"a command proved, not a task someone finished."
|
|
1148
|
+
)
|
|
1149
|
+
skills = project / ".agents" / "skills"
|
|
1150
|
+
if skills.is_dir():
|
|
1151
|
+
installed = sorted(p.name for p in skills.iterdir() if (p / "SKILL.md").is_file())
|
|
1152
|
+
if installed:
|
|
1153
|
+
rows.append(
|
|
1154
|
+
f"- Skills: `.agents/skills/` — `lathe` names the step ({len(installed)} installed)."
|
|
1155
|
+
)
|
|
1156
|
+
if (project / ".pi" / "context").is_dir():
|
|
1157
|
+
rows.append(
|
|
1158
|
+
"- Conditional rules: `.pi/context/` — they inject themselves at the moment they "
|
|
1159
|
+
"describe; do not restate them here."
|
|
1160
|
+
)
|
|
1161
|
+
members = workspace_members(project)
|
|
1162
|
+
if members:
|
|
1163
|
+
named = ", ".join(f"`{member}`" for member in members)
|
|
1164
|
+
rows.append(f"- Workspace members: {named}.")
|
|
1165
|
+
return rows
|
|
1166
|
+
|
|
1167
|
+
|
|
1168
|
+
def agents_block(project: Path) -> str:
|
|
1169
|
+
"""The block, or an empty string when the project has nothing to map yet."""
|
|
1170
|
+
rows = agents_map(project)
|
|
1171
|
+
if not rows:
|
|
1172
|
+
return ""
|
|
1173
|
+
return "\n".join([BLOCK_HEAD, *rows, BLOCK_END]) + "\n"
|
|
1174
|
+
|
|
1175
|
+
|
|
1176
|
+
def located_block(text: str) -> tuple[int, int] | None:
|
|
1177
|
+
"""Where the block sits in a file, or None. Unbalanced markers are a refusal."""
|
|
1178
|
+
start = text.find(BLOCK_BEGIN)
|
|
1179
|
+
end = text.find(BLOCK_END)
|
|
1180
|
+
if start < 0 and end < 0:
|
|
1181
|
+
return None
|
|
1182
|
+
if start < 0 or end < 0 or end < start:
|
|
1183
|
+
raise SystemExit(
|
|
1184
|
+
"error: AGENTS.md has one Lathe marker and not the other — fix the markers by hand "
|
|
1185
|
+
"before regenerating, so nothing outside the block is lost"
|
|
1186
|
+
)
|
|
1187
|
+
return start, end + len(BLOCK_END)
|
|
1188
|
+
|
|
1189
|
+
|
|
1190
|
+
GITHUB = "https://github.com/"
|
|
1191
|
+
|
|
1192
|
+
|
|
1193
|
+
def remote_head(repository: str) -> str:
|
|
1194
|
+
"""The remote's HEAD commit, or empty when it cannot be reached.
|
|
1195
|
+
|
|
1196
|
+
Empty is not "unchanged": a check that could not run has certified nothing, and
|
|
1197
|
+
the caller reports it as unmeasured rather than green.
|
|
1198
|
+
"""
|
|
1199
|
+
try:
|
|
1200
|
+
proc = subprocess.run(
|
|
1201
|
+
("git", "ls-remote", f"{GITHUB}{repository}", "HEAD"),
|
|
1202
|
+
capture_output=True,
|
|
1203
|
+
text=True,
|
|
1204
|
+
timeout=30,
|
|
1205
|
+
check=False,
|
|
1206
|
+
)
|
|
1207
|
+
except (OSError, subprocess.TimeoutExpired):
|
|
1208
|
+
return ""
|
|
1209
|
+
return proc.stdout.split()[0] if proc.returncode == 0 and proc.stdout.split() else ""
|
|
1210
|
+
|
|
1211
|
+
|
|
1212
|
+
def cmd_upstream(argv: list[str]) -> int:
|
|
1213
|
+
"""What each upstream source is pinned to, and whether the remote has moved.
|
|
1214
|
+
|
|
1215
|
+
This is the session-start question: the package is only as current as its pins,
|
|
1216
|
+
and a pin nobody compares is a dependency nobody updates.
|
|
1217
|
+
"""
|
|
1218
|
+
parser = argparse.ArgumentParser(prog="framework.py upstream")
|
|
1219
|
+
parser.add_argument("--check", action="store_true")
|
|
1220
|
+
parser.add_argument("--project", default=".", type=Path)
|
|
1221
|
+
args = parser.parse_args(argv)
|
|
1222
|
+
check, project = args.check, args.project
|
|
1223
|
+
commits = project_upstream_commits(project)
|
|
1224
|
+
stale = []
|
|
1225
|
+
for source in UPSTREAMS:
|
|
1226
|
+
name = str(source["name"])
|
|
1227
|
+
pinned = commits.get(name, "")
|
|
1228
|
+
if not pinned:
|
|
1229
|
+
print(f"{name}: no commit recorded in {SKILLS_LOCK} — run the install command")
|
|
1230
|
+
stale.append(source)
|
|
1231
|
+
continue
|
|
1232
|
+
if not check:
|
|
1233
|
+
print(f"{name} @ {pinned[:7]} ({source['skills']} skills) — up to date")
|
|
1234
|
+
continue
|
|
1235
|
+
head = remote_head(name)
|
|
1236
|
+
if not head:
|
|
1237
|
+
print(f"{name} @ {pinned[:7]} — UNMEASURED: {GITHUB}{name} unreachable")
|
|
1238
|
+
stale.append(source)
|
|
1239
|
+
elif head.startswith(pinned) or pinned.startswith(head[: len(pinned)]):
|
|
1240
|
+
print(f"{name} @ {pinned[:7]} — up to date")
|
|
1241
|
+
else:
|
|
1242
|
+
print(f"{name} @ {pinned[:7]} — DRIFT: remote HEAD is {head[:7]}")
|
|
1243
|
+
print(f" update: {source['hint']}")
|
|
1244
|
+
stale.append(source)
|
|
1245
|
+
if not check:
|
|
1246
|
+
return 0
|
|
1247
|
+
if stale:
|
|
1248
|
+
print("\nNot current: re-run the install commands above, then build-lock.", file=sys.stderr)
|
|
1249
|
+
return 1
|
|
1250
|
+
print("\nAll upstream sources are current.")
|
|
1251
|
+
return 0
|
|
1252
|
+
|
|
1253
|
+
|
|
1254
|
+
def cmd_agents(argv: list[str]) -> int:
|
|
1255
|
+
parser = argparse.ArgumentParser(prog="framework.py agents")
|
|
1256
|
+
parser.add_argument("--project", default=".", type=Path)
|
|
1257
|
+
parser.add_argument("--check", action="store_true")
|
|
1258
|
+
args = parser.parse_args(argv)
|
|
1259
|
+
project = args.project.resolve()
|
|
1260
|
+
block = agents_block(project)
|
|
1261
|
+
if not block:
|
|
1262
|
+
return fail(
|
|
1263
|
+
f"nothing to map in {project}: no documentation/llm, no changelog, no skills — "
|
|
1264
|
+
"an empty map is worse than no map, so nothing was written",
|
|
1265
|
+
1,
|
|
1266
|
+
)
|
|
1267
|
+
path = project / "AGENTS.md"
|
|
1268
|
+
text = path.read_text(encoding="utf-8") if path.is_file() else ""
|
|
1269
|
+
span = located_block(text)
|
|
1270
|
+
if args.check:
|
|
1271
|
+
if not path.is_file():
|
|
1272
|
+
return fail(f"{path} does not exist — run agents without --check to create it", 1)
|
|
1273
|
+
if span is None:
|
|
1274
|
+
return fail(f"{path} has no Lathe block — run agents without --check to add it", 1)
|
|
1275
|
+
if text[span[0] : span[1]] != block.rstrip("\n"):
|
|
1276
|
+
return fail(
|
|
1277
|
+
"the map block is stale: the tree no longer matches it — run agents without "
|
|
1278
|
+
"--check to regenerate it",
|
|
1279
|
+
1,
|
|
1280
|
+
)
|
|
1281
|
+
print(f"agents: up to date ({len(agents_map(project))} lines mapped)")
|
|
1282
|
+
return 0
|
|
1283
|
+
if span is None:
|
|
1284
|
+
updated = (text.rstrip("\n") + "\n\n" + block) if text.strip() else block
|
|
1285
|
+
verb = "appended to" if text.strip() else "written to"
|
|
1286
|
+
else:
|
|
1287
|
+
updated = text[: span[0]] + block.rstrip("\n") + text[span[1] :]
|
|
1288
|
+
verb = "refreshed in"
|
|
1289
|
+
path.write_text(updated, encoding="utf-8")
|
|
1290
|
+
print(f"agents: {verb} {path} ({len(agents_map(project))} lines mapped)")
|
|
1291
|
+
return 0
|
|
1292
|
+
|
|
1293
|
+
|
|
1294
|
+
def main(argv: list[str]) -> int:
|
|
1295
|
+
if not argv:
|
|
1296
|
+
print(__doc__)
|
|
1297
|
+
return 2
|
|
1298
|
+
command, rest = argv[0], argv[1:]
|
|
1299
|
+
table = {
|
|
1300
|
+
"build-lock": cmd_build_lock,
|
|
1301
|
+
"install": cmd_install,
|
|
1302
|
+
"doctor": cmd_doctor,
|
|
1303
|
+
"update": cmd_update,
|
|
1304
|
+
"bootstrap": cmd_bootstrap,
|
|
1305
|
+
"agents": cmd_agents,
|
|
1306
|
+
"upstream": cmd_upstream,
|
|
1307
|
+
}
|
|
1308
|
+
if command not in table:
|
|
1309
|
+
return fail(f"unknown command {command!r}; expected one of {', '.join(table)}", 2)
|
|
1310
|
+
return table[command](rest)
|
|
1311
|
+
|
|
1312
|
+
|
|
1313
|
+
if __name__ == "__main__":
|
|
1314
|
+
sys.exit(main(sys.argv[1:]))
|