Template 1.28.2: backport 2.0.1 fixes to the 1.x line
Python 3.8 compatibility, routines.py --mark YAML spacing and comments, OKF --out and Starlight image paths confined to their folders, script counts in AGENTS.md/READMEs/manuals, and the tests/unit/ suite. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
8415004031
commit
cd7ae4dd44
21 changed files with 353 additions and 24 deletions
|
|
@ -104,7 +104,7 @@ def _kb_identity():
|
||||||
name = ENV.get("CKB_MCP_NAME")
|
name = ENV.get("CKB_MCP_NAME")
|
||||||
if not name:
|
if not name:
|
||||||
r = subprocess.run(["git", "-C", str(kb_store.root), "remote", "get-url", "origin"], capture_output=True, text=True)
|
r = subprocess.run(["git", "-C", str(kb_store.root), "remote", "get-url", "origin"], capture_output=True, text=True)
|
||||||
name = Path(r.stdout.strip()).name.removesuffix(".git") if r.returncode == 0 and r.stdout.strip() else kb_store.root.name
|
name = re.sub(r"\.git$", "", Path(r.stdout.strip()).name) if r.returncode == 0 and r.stdout.strip() else kb_store.root.name
|
||||||
desc = ENV.get("CKB_MCP_DESCRIPTION", "")
|
desc = ENV.get("CKB_MCP_DESCRIPTION", "")
|
||||||
for f in (kb_store.root / "ABOUT.md", kb_store.root / "ABOUT.pl.md", kb_store.root / "wiki" / "overview.md"):
|
for f in (kb_store.root / "ABOUT.md", kb_store.root / "ABOUT.pl.md", kb_store.root / "wiki" / "overview.md"):
|
||||||
if desc or not f.is_file():
|
if desc or not f.is_file():
|
||||||
|
|
|
||||||
|
|
@ -93,7 +93,10 @@ def load_edges(root):
|
||||||
except ValueError:
|
except ValueError:
|
||||||
return []
|
return []
|
||||||
edges = data.get("edges", []) if isinstance(data, dict) else data
|
edges = data.get("edges", []) if isinstance(data, dict) else data
|
||||||
norm = lambda v: (lambda s: s if s.endswith(".md") else s + ".md")(str(v).lstrip("/").removeprefix("wiki/"))
|
def norm(v):
|
||||||
|
s = str(v).lstrip("/")
|
||||||
|
s = s[5:] if s.startswith("wiki/") else s # removeprefix is 3.9+
|
||||||
|
return s if s.endswith(".md") else s + ".md"
|
||||||
return [(norm(e.get("from", "")), norm(e.get("to", ""))) for e in edges if isinstance(e, dict)]
|
return [(norm(e.get("from", "")), norm(e.get("to", ""))) for e in edges if isinstance(e, dict)]
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -32,7 +32,9 @@ If no interpreter is found, stop, say so, and point to "Prerequisites" in
|
||||||
print the report, and write nothing to `outputs/`. Use this when the user
|
print the report, and write nothing to `outputs/`. Use this when the user
|
||||||
wants to know whether the wiki *would* export cleanly without touching the
|
wants to know whether the wiki *would* export cleanly without touching the
|
||||||
working tree (e.g. as part of a review, or before a lint pass).
|
working tree (e.g. as part of a review, or before a lint pass).
|
||||||
- `--out DIR` — write somewhere other than `outputs/okf` (rarely needed).
|
- `--out DIR` — write somewhere other than `outputs/okf` (rarely needed). It
|
||||||
|
must be a folder inside `outputs/`, because it is deleted and rebuilt on
|
||||||
|
every export; anything else is refused with exit code 2.
|
||||||
|
|
||||||
The script deletes and rebuilds the output directory on every run, so the
|
The script deletes and rebuilds the output directory on every run, so the
|
||||||
bundle can never accumulate stale files from pages that were since renamed
|
bundle can never accumulate stale files from pages that were since renamed
|
||||||
|
|
|
||||||
|
|
@ -494,7 +494,18 @@ def main():
|
||||||
finally:
|
finally:
|
||||||
shutil.rmtree(tmp, ignore_errors=True)
|
shutil.rmtree(tmp, ignore_errors=True)
|
||||||
else:
|
else:
|
||||||
out_dir = REPO_ROOT / args.out
|
out_dir = (REPO_ROOT / args.out).resolve()
|
||||||
|
outputs = (REPO_ROOT / "outputs").resolve()
|
||||||
|
# build() deletes out_dir first, so it must be a folder of its own
|
||||||
|
# under outputs/ — never the repo, wiki/ or outputs/ itself.
|
||||||
|
try:
|
||||||
|
inside = out_dir != outputs and out_dir.relative_to(outputs)
|
||||||
|
except ValueError:
|
||||||
|
inside = False
|
||||||
|
if not inside:
|
||||||
|
print(f"error: --out must name a folder inside outputs/ (got {args.out!r}); "
|
||||||
|
"it is deleted and rebuilt on every export", file=sys.stderr)
|
||||||
|
return 2
|
||||||
report = build(out_dir)
|
report = build(out_dir)
|
||||||
problems = validate(out_dir)
|
problems = validate(out_dir)
|
||||||
print_report(report, problems, out_dir, checked_only=False)
|
print_report(report, problems, out_dir, checked_only=False)
|
||||||
|
|
|
||||||
|
|
@ -160,6 +160,15 @@ CASCADE_LINK_RE = re.compile(r"\[([^\]]+)\]\((?:linked|libs)/[^)]+\)")
|
||||||
IMAGE_REL_RE = re.compile(r"!\[([^\]]*)\]\(\.\./assets/([^)]+)\)")
|
IMAGE_REL_RE = re.compile(r"!\[([^\]]*)\]\(\.\./assets/([^)]+)\)")
|
||||||
|
|
||||||
|
|
||||||
|
def _within(path, folder):
|
||||||
|
"""True when resolved `path` is inside `folder` (Path.is_relative_to is 3.9+)."""
|
||||||
|
try:
|
||||||
|
path.relative_to(folder.resolve())
|
||||||
|
return True
|
||||||
|
except ValueError:
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
def rewrite_body(body, title_index, unresolved_wikilinks, copied_assets):
|
def rewrite_body(body, title_index, unresolved_wikilinks, copied_assets):
|
||||||
# 1. strip wikilinks that ride alongside a markdown link (either order:
|
# 1. strip wikilinks that ride alongside a markdown link (either order:
|
||||||
# "[text](path) ([[Wikilink]])" or the legacy "[[Wikilink]] / [text](path)")
|
# "[text](path) ([[Wikilink]])" or the legacy "[[Wikilink]] / [text](path)")
|
||||||
|
|
@ -211,9 +220,14 @@ def rewrite_body(body, title_index, unresolved_wikilinks, copied_assets):
|
||||||
# 6. copy relative person/asset images and rewrite to /assets/...
|
# 6. copy relative person/asset images and rewrite to /assets/...
|
||||||
def _image(m):
|
def _image(m):
|
||||||
alt, rel = m.group(1), m.group(2)
|
alt, rel = m.group(1), m.group(2)
|
||||||
src = WIKI / "assets" / rel
|
src = (WIKI / "assets" / rel).resolve()
|
||||||
|
dest = (OUT / "public" / "assets" / rel).resolve()
|
||||||
|
# `rel` comes from page text, which may come from captured pages:
|
||||||
|
# copy only from inside wiki/assets/ to inside the export's assets.
|
||||||
|
if not (_within(src, WIKI / "assets") and _within(dest, OUT / "public" / "assets")):
|
||||||
|
print(f"warning: image path leaves wiki/assets/, not copied: ../assets/{rel}", file=sys.stderr)
|
||||||
|
return m.group(0)
|
||||||
if src.is_file():
|
if src.is_file():
|
||||||
dest = OUT / "public" / "assets" / rel
|
|
||||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||||
shutil.copyfile(src, dest)
|
shutil.copyfile(src, dest)
|
||||||
copied_assets.append(rel)
|
copied_assets.append(rel)
|
||||||
|
|
|
||||||
|
|
@ -142,6 +142,16 @@ def as_date(value):
|
||||||
|
|
||||||
LINK_RE = re.compile(r"\[[^\]]*\]\(([^)]+)\)")
|
LINK_RE = re.compile(r"\[[^\]]*\]\(([^)]+)\)")
|
||||||
WIKILINK_RE = re.compile(r"\[\[([^\]]+)\]\]")
|
WIKILINK_RE = re.compile(r"\[\[([^\]]+)\]\]")
|
||||||
|
def _drop_md(s):
|
||||||
|
"""`s` without a trailing `.md` (str.removesuffix is 3.9+)."""
|
||||||
|
return s[:-3] if s.endswith(".md") else s
|
||||||
|
|
||||||
|
|
||||||
|
def _drop_wiki(s):
|
||||||
|
"""`s` without a leading `wiki/` (str.removeprefix is 3.9+)."""
|
||||||
|
return s[5:] if s.startswith("wiki/") else s
|
||||||
|
|
||||||
|
|
||||||
SOURCE_BULLET_RE = re.compile(r"^\s*[-*]\s+`([^`]+)`(.*)$", re.M)
|
SOURCE_BULLET_RE = re.compile(r"^\s*[-*]\s+`([^`]+)`(.*)$", re.M)
|
||||||
FINGERPRINT_RE = re.compile(r"\b(sha256|etag|mtime):([^\s,)]+)")
|
FINGERPRINT_RE = re.compile(r"\b(sha256|etag|mtime):([^\s,)]+)")
|
||||||
# A Crux block is attributed by an em-dash line under it. Two shapes matter:
|
# A Crux block is attributed by an em-dash line under it. Two shapes matter:
|
||||||
|
|
@ -408,11 +418,11 @@ def check_graph(root, docs):
|
||||||
stripped = value[len("/wiki/"):] if value.startswith("/wiki/") else value.lstrip("/")
|
stripped = value[len("/wiki/"):] if value.startswith("/wiki/") else value.lstrip("/")
|
||||||
candidates = {
|
candidates = {
|
||||||
value,
|
value,
|
||||||
value.removesuffix(".md"),
|
_drop_md(value),
|
||||||
stripped,
|
stripped,
|
||||||
stripped.removesuffix(".md"),
|
_drop_md(stripped),
|
||||||
f"entities/{value}",
|
f"entities/{value}",
|
||||||
f"entities/{value}".removesuffix(".md"),
|
_drop_md(f"entities/{value}"),
|
||||||
}
|
}
|
||||||
if not candidates & known:
|
if not candidates & known:
|
||||||
findings.append(f"graph/edges.json: edge {i} `{side}: {value}` does not resolve to a page")
|
findings.append(f"graph/edges.json: edge {i} `{side}: {value}` does not resolve to a page")
|
||||||
|
|
@ -984,7 +994,7 @@ def cold_pages(today, days):
|
||||||
if when is None or not path:
|
if when is None or not path:
|
||||||
continue
|
continue
|
||||||
first = when if first is None or when < first else first
|
first = when if first is None or when < first else first
|
||||||
key = path.strip().lstrip("/").removeprefix("wiki/")
|
key = _drop_wiki(path.strip().lstrip("/"))
|
||||||
last[key] = max(last.get(key, when), when)
|
last[key] = max(last.get(key, when), when)
|
||||||
if first is None or (today - first).days < days:
|
if first is None or (today - first).days < days:
|
||||||
covered = (today - first).days if first else 0
|
covered = (today - first).days if first else 0
|
||||||
|
|
|
||||||
|
|
@ -144,7 +144,9 @@ def load_edges(root):
|
||||||
|
|
||||||
|
|
||||||
def norm_ref(ref):
|
def norm_ref(ref):
|
||||||
return ref.lstrip("/").removeprefix("wiki/").removesuffix(".md")
|
ref = ref.lstrip("/")
|
||||||
|
ref = ref[5:] if ref.startswith("wiki/") else ref # removeprefix is 3.9+
|
||||||
|
return ref[:-3] if ref.endswith(".md") else ref
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------- signals ---
|
# ---------------------------------------------------------------- signals ---
|
||||||
|
|
|
||||||
|
|
@ -168,7 +168,14 @@ def cmd_mark(path, name, today):
|
||||||
stamp = today.strftime("%Y-%m-%d")
|
stamp = today.strftime("%Y-%m-%d")
|
||||||
if "last_run" in it["fields"]:
|
if "last_run" in it["fields"]:
|
||||||
j = it["fields"]["last_run"][1]
|
j = it["fields"]["last_run"][1]
|
||||||
lines[j] = re.sub(r"(last_run:\s*)\S*", r"\g<1>" + stamp, lines[j], count=1)
|
# Replace only the value: keep `key: value` spacing (a bare `last_run:`
|
||||||
|
# must not become `last_run:2026-…`, which YAML rejects) and keep any
|
||||||
|
# trailing comment as a comment.
|
||||||
|
m = re.match(r"^(\s*(?:-\s+)?last_run:)[ \t]*([^#\s]*)[ \t]*(#.*)?$", lines[j])
|
||||||
|
if m:
|
||||||
|
lines[j] = f"{m.group(1)} {stamp}" + (f" {m.group(3)}" if m.group(3) else "")
|
||||||
|
else:
|
||||||
|
lines[j] = re.sub(r"(last_run:)[ \t]*\S*", r"\g<1> " + stamp, lines[j], count=1)
|
||||||
else:
|
else:
|
||||||
pad = " " * (it["indent"] + 2)
|
pad = " " * (it["indent"] + 2)
|
||||||
lines.insert(it["last"] + 1, f"{pad}last_run: {stamp}")
|
lines.insert(it["last"] + 1, f"{pad}last_run: {stamp}")
|
||||||
|
|
|
||||||
|
|
@ -258,9 +258,9 @@ Disambiguation, only where the table alone is ambiguous:
|
||||||
takes a typed confirmation first, and never touches the template layer or `src/`.
|
takes a typed confirmation first, and never touches the template layer or `src/`.
|
||||||
|
|
||||||
### Scripts and the Python Runtime
|
### Scripts and the Python Runtime
|
||||||
Seven skills ship a deterministic Python script (`ckb-lint`, `ckb-retrieve`,
|
Eight skills ship a deterministic Python script (`ckb-lint`, `ckb-retrieve`,
|
||||||
`ckb-ingest`, `ckb-routine`, `ckb-export-okf`, `ckb-export-starlight`,
|
`ckb-ingest`, `ckb-routine`, `ckb-consolidate`, `ckb-export-okf`,
|
||||||
`ckb-add-conversation`). They need Python 3.8+ and nothing else. Where a
|
`ckb-export-starlight`, `ckb-add-conversation`). They need Python 3.8+ and nothing else. Where a
|
||||||
skill doc writes `<python>`, resolve it once per session: the first of
|
skill doc writes `<python>`, resolve it once per session: the first of
|
||||||
`python3`, `python`, `py -3` that runs `--version` and reports 3.x.
|
`python3`, `python`, `py -3` that runs `--version` and reports 3.x.
|
||||||
Windows normally has `python` or `py`, never `python3`.
|
Windows normally has `python` or `py`, never `python3`.
|
||||||
|
|
|
||||||
|
|
@ -669,7 +669,7 @@ goes into `wiki/query-gaps.md` only on your yes. See
|
||||||
|
|
||||||
## Quick Start
|
## Quick Start
|
||||||
|
|
||||||
0. **Optional: install Python 3.8+.** Five skills run a stdlib-only Python
|
0. **Optional: install Python 3.8+.** Eight skills run a stdlib-only Python
|
||||||
script; without it the session-start check falls back to a bash/PowerShell
|
script; without it the session-start check falls back to a bash/PowerShell
|
||||||
script, lint and retrieval run in a slower manual mode, and the exporters
|
script, lint and retrieval run in a slower manual mode, and the exporters
|
||||||
are unavailable. Per-OS steps: [docs/MANUAL.md → Prerequisites](docs/MANUAL.md#prerequisites).
|
are unavailable. Per-OS steps: [docs/MANUAL.md → Prerequisites](docs/MANUAL.md#prerequisites).
|
||||||
|
|
|
||||||
|
|
@ -733,7 +733,7 @@ tylko po twojej zgodzie. Zobacz `.agents/skills/ckb-feynman/SKILL.md`.
|
||||||
|
|
||||||
## Szybki start
|
## Szybki start
|
||||||
|
|
||||||
0. **Opcjonalnie: zainstaluj Pythona 3.8+.** Pięć skilli uruchamia skrypt
|
0. **Opcjonalnie: zainstaluj Pythona 3.8+.** Osiem skilli uruchamia skrypt
|
||||||
w Pythonie (tylko biblioteka standardowa); bez niego kontrola na starcie
|
w Pythonie (tylko biblioteka standardowa); bez niego kontrola na starcie
|
||||||
sesji przechodzi na zapasowy skrypt bash/PowerShell, lint i wyszukiwanie
|
sesji przechodzi na zapasowy skrypt bash/PowerShell, lint i wyszukiwanie
|
||||||
działają w wolniejszym trybie ręcznym, a eksporty są niedostępne. Kroki
|
działają w wolniejszym trybie ręcznym, a eksporty są niedostępne. Kroki
|
||||||
|
|
|
||||||
2
VERSION
2
VERSION
|
|
@ -1 +1 @@
|
||||||
1.28.1
|
1.28.2
|
||||||
|
|
|
||||||
|
|
@ -340,7 +340,8 @@ docs. Independent of the content schema above.
|
||||||
|
|
||||||
| Version | Date | What landed | Schema |
|
| Version | Date | What landed | Schema |
|
||||||
|---|---|---|---|
|
|---|---|---|---|
|
||||||
| **1.28.1** | 2026-11-11 | Release channel `1.x`: the maintenance branch for the 1.x line once 2.0 ships, fixes only, and the last line with PowerShell support (D-0019). Listed in the channel tables of `ckb-init`, `ckb-upgrade`, `AGENTS.md`, both READMEs and both manuals, and in the `ckb.yaml` comment. `ckb-upgrade` Step 2: a higher **major** version upstream stops the run before Step 4, quotes the breaking part of the upstream changelog row, and offers the new major or a switch to the maintenance branch; never crossed from a routine or batch run | 1.7 |
|
| **1.28.2** | 2026-11-11 | `1.x` backport of the 2.0.1 fixes, no new features: Python 3.8 compatibility (`removeprefix`/`removesuffix` replaced in lint, retrieve, consolidate and the mcp server), `routines.py --mark` writing `last_run:2026-…` and swallowing comments, `export_okf.py --out` confined to `outputs/`, Starlight image copies confined to `wiki/assets/`, script counts in `AGENTS.md`, READMEs and manuals. Same `tests/unit/` suite, run by `smoke.sh` | 1.7 |
|
||||||
|
| 1.28.1 | 2026-11-11 | Release channel `1.x`: the maintenance branch for the 1.x line once 2.0 ships, fixes only, and the last line with PowerShell support (D-0019). Listed in the channel tables of `ckb-init`, `ckb-upgrade`, `AGENTS.md`, both READMEs and both manuals, and in the `ckb.yaml` comment. `ckb-upgrade` Step 2: a higher **major** version upstream stops the run before Step 4, quotes the breaking part of the upstream changelog row, and offers the new major or a switch to the maintenance branch; never crossed from a routine or batch run | 1.7 |
|
||||||
| 1.28.0 | 2026-11-11 | New opt-in `share` module (D-0018): skill `ckb-share` and `share.py` (`join`/`send`/`unshare`/`list`/`receive`/`status`, stdlib + git). A **channel** is a separate git repo per trust group with `CHANNEL.md`, `members.yaml` (kb → owner emails) and one append-only mailbox per KB, `mail/<kb>/`, cloned into `tmp/share/<channel>/`. **Send** packs a self-contained copy of an `outputs/documents/`, `outputs/answers/` or `wiki/` page (`raw/archive/` only with `--raw-ok`): `<private>` spans and `## Notes` dropped, local links as text, Sources/Crux paths marked `<kb>:`; envelope `type: share`, `kind`, `share_id`, `version`, `from`, `to`, `sent_by`, `untrusted: true`; lint's secret patterns block the send (exit 3), a dry run prints the `ABOUT.md` sensitivity section, the user confirms. Re-sending makes the next version. **Receive** copies messages addressed to the KB into `raw/inbox/` with `share_channel`, `share_ref`, `received_on`, `submitted_by` (git author) and `supersedes_source`; a message whose git author is not an owner of its mailbox is UNVERIFIED and taken only with `--accept-unverified`; a retraction becomes `raw/retractions/` requests for every held version. A `received:` ledger in the script-owned `share:` block of `ckb.yaml` keeps handled messages from returning. `dedup_inbox.py` reports `SAME SHARE`; `ckb-ingest` and `ckb-retract` know share files and requests. Smoke test covers two KBs and a bare-repo channel end to end | 1.7 |
|
| 1.28.0 | 2026-11-11 | New opt-in `share` module (D-0018): skill `ckb-share` and `share.py` (`join`/`send`/`unshare`/`list`/`receive`/`status`, stdlib + git). A **channel** is a separate git repo per trust group with `CHANNEL.md`, `members.yaml` (kb → owner emails) and one append-only mailbox per KB, `mail/<kb>/`, cloned into `tmp/share/<channel>/`. **Send** packs a self-contained copy of an `outputs/documents/`, `outputs/answers/` or `wiki/` page (`raw/archive/` only with `--raw-ok`): `<private>` spans and `## Notes` dropped, local links as text, Sources/Crux paths marked `<kb>:`; envelope `type: share`, `kind`, `share_id`, `version`, `from`, `to`, `sent_by`, `untrusted: true`; lint's secret patterns block the send (exit 3), a dry run prints the `ABOUT.md` sensitivity section, the user confirms. Re-sending makes the next version. **Receive** copies messages addressed to the KB into `raw/inbox/` with `share_channel`, `share_ref`, `received_on`, `submitted_by` (git author) and `supersedes_source`; a message whose git author is not an owner of its mailbox is UNVERIFIED and taken only with `--accept-unverified`; a retraction becomes `raw/retractions/` requests for every held version. A `received:` ledger in the script-owned `share:` block of `ckb.yaml` keeps handled messages from returning. `dedup_inbox.py` reports `SAME SHARE`; `ckb-ingest` and `ckb-retract` know share files and requests. Smoke test covers two KBs and a bare-repo channel end to end | 1.7 |
|
||||||
| 1.27.0 | 2026-11-02 | New core skill `ckb-feynman`, adapted from the `feynman` skill in superhero-tech-super-brain: explains one page in plain words with a concrete example and a `→ [[page]] · [Title § Heading](/wiki/…#anchor)` line under each block, then sorts every thin spot into Wiki, Sources or Mine gaps without filling any from model knowledge, asks for an explain-back and ends with numbered next moves. Candidates come from `review: draft`/`needs_update`, single-source, stale or contradicted pages; topic pages are followed to their members; Crux fingerprints are checked as in `ckb-retrieve` Step 6; `<private>` spans are never explained. Sessions go to `outputs/teaching/feynman/YYYY-MM-DD_<slug>.md` (`type: feynman-session`, fingerprinted `## Sources`, gitignored with `outputs/teaching/`, no `wiki/log.md` entry); a Sources gap reaches `wiki/query-gaps.md` only on a yes. `ckb-teach-me` skips the folder; `ckb-init`, `AGENTS.md` routing row, both READMEs and manuals updated; eval case `ckb-feynman/session` with a recorded reference run (6/6). `outputs/teaching/` added to the directory contract; `run_evals.py` matches deleted files with glob semantics (`**` was one segment) | 1.7 |
|
| 1.27.0 | 2026-11-02 | New core skill `ckb-feynman`, adapted from the `feynman` skill in superhero-tech-super-brain: explains one page in plain words with a concrete example and a `→ [[page]] · [Title § Heading](/wiki/…#anchor)` line under each block, then sorts every thin spot into Wiki, Sources or Mine gaps without filling any from model knowledge, asks for an explain-back and ends with numbered next moves. Candidates come from `review: draft`/`needs_update`, single-source, stale or contradicted pages; topic pages are followed to their members; Crux fingerprints are checked as in `ckb-retrieve` Step 6; `<private>` spans are never explained. Sessions go to `outputs/teaching/feynman/YYYY-MM-DD_<slug>.md` (`type: feynman-session`, fingerprinted `## Sources`, gitignored with `outputs/teaching/`, no `wiki/log.md` entry); a Sources gap reaches `wiki/query-gaps.md` only on a yes. `ckb-teach-me` skips the folder; `ckb-init`, `AGENTS.md` routing row, both READMEs and manuals updated; eval case `ckb-feynman/session` with a recorded reference run (6/6). `outputs/teaching/` added to the directory contract; `run_evals.py` matches deleted files with glob semantics (`**` was one segment) | 1.7 |
|
||||||
| 1.26.2 | 2026-11-10 | `ABOUT.pl.md`: the Polish pair of the `ABOUT.md` scaffold, like the other `.pl.md` docs. Agents read both when both are filled in and `ABOUT.md` wins on a conflict (`AGENTS.md`, `ckb-ingest`); `ckb-init` copies both and puts a Polish answer in the Polish file; `ckb-upgrade` creates it once for KBs below 1.26.2 and never recreates a deleted one; `ckb-reset` leaves it alone; the `mcp` server's `kb_overview` includes it and its description falls back to its `tldr`, ignoring either placeholder. `README.pl.md` and `QUICKSTART.pl.md` point to it; both manuals list it | 1.7 |
|
| 1.26.2 | 2026-11-10 | `ABOUT.pl.md`: the Polish pair of the `ABOUT.md` scaffold, like the other `.pl.md` docs. Agents read both when both are filled in and `ABOUT.md` wins on a conflict (`AGENTS.md`, `ckb-ingest`); `ckb-init` copies both and puts a Polish answer in the Polish file; `ckb-upgrade` creates it once for KBs below 1.26.2 and never recreates a deleted one; `ckb-reset` leaves it alone; the `mcp` server's `kb_overview` includes it and its description falls back to its `tldr`, ignoring either placeholder. `README.pl.md` and `QUICKSTART.pl.md` point to it; both manuals list it | 1.7 |
|
||||||
|
|
|
||||||
|
|
@ -348,7 +348,8 @@ Niezależna od schematu treści powyżej.
|
||||||
|
|
||||||
| Wersja | Data | Co weszło | Schemat |
|
| Wersja | Data | Co weszło | Schemat |
|
||||||
|---|---|---|---|
|
|---|---|---|---|
|
||||||
| **1.28.1** | 2026-11-11 | Kanał wydawniczy `1.x`: gałąź utrzymaniowa linii 1.x po wydaniu 2.0, tylko poprawki, ostatnia z obsługą PowerShella (D-0019). Dopisany do tabel kanałów w `ckb-init`, `ckb-upgrade`, `AGENTS.md`, obu README i obu podręcznikach oraz do komentarza w `ckb.yaml`. `ckb-upgrade` krok 2: wyższa wersja **główna** w źródle zatrzymuje przebieg przed krokiem 4, cytuje przełomową część wiersza changeloga i proponuje nową wersję główną albo przejście na gałąź utrzymaniową; nigdy nie przechodzi przez nią z rutyny ani trybu wsadowego | 1.7 |
|
| **1.28.2** | 2026-11-11 | Przeniesienie poprawek 2.0.1 na `1.x`, bez nowych funkcji: zgodność z Pythonem 3.8 (`removeprefix`/`removesuffix` zastąpione w lincie, wyszukiwaniu, konsolidacji i serwerze mcp), `routines.py --mark` zapisujące `last_run:2026-…` i połykające komentarze, `export_okf.py --out` ograniczone do `outputs/`, kopie obrazów w Starlight ograniczone do `wiki/assets/`, liczba skryptów w `AGENTS.md`, README i podręcznikach. Ten sam zestaw `tests/unit/`, uruchamiany przez `smoke.sh` | 1.7 |
|
||||||
|
| 1.28.1 | 2026-11-11 | Kanał wydawniczy `1.x`: gałąź utrzymaniowa linii 1.x po wydaniu 2.0, tylko poprawki, ostatnia z obsługą PowerShella (D-0019). Dopisany do tabel kanałów w `ckb-init`, `ckb-upgrade`, `AGENTS.md`, obu README i obu podręcznikach oraz do komentarza w `ckb.yaml`. `ckb-upgrade` krok 2: wyższa wersja **główna** w źródle zatrzymuje przebieg przed krokiem 4, cytuje przełomową część wiersza changeloga i proponuje nową wersję główną albo przejście na gałąź utrzymaniową; nigdy nie przechodzi przez nią z rutyny ani trybu wsadowego | 1.7 |
|
||||||
| 1.28.0 | 2026-11-11 | Nowy opcjonalny moduł `share` (D-0018): skill `ckb-share` i `share.py` (`join`/`send`/`unshare`/`list`/`receive`/`status`, biblioteka standardowa + git). **Kanał** to osobne repozytorium git na grupę zaufania z `CHANNEL.md`, `members.yaml` (baza → e-maile właścicieli) i jedną skrzynką tylko do dopisywania na bazę, `mail/<baza>/`, klonowane do `tmp/share/<kanał>/`. **Wysyłka** pakuje samodzielną kopię strony z `outputs/documents/`, `outputs/answers/` lub `wiki/` (`raw/archive/` tylko z `--raw-ok`): bez fragmentów `<private>` i `## Notes`, linki lokalne jako tekst, ścieżki w Sources/Crux oznaczone `<baza>:`; koperta `type: share`, `kind`, `share_id`, `version`, `from`, `to`, `sent_by`, `untrusted: true`; wzorce sekretów z lintu blokują wysyłkę (kod 3), próba pokazuje sekcję wrażliwości z `ABOUT.md`, użytkownik potwierdza. Ponowna wysyłka tworzy kolejną wersję. **Odbiór** kopiuje wiadomości do bazy do `raw/inbox/` z `share_channel`, `share_ref`, `received_on`, `submitted_by` (autor w gicie) i `supersedes_source`; wiadomość, której autor nie jest właścicielem skrzynki, jest NIEZWERYFIKOWANA i brana tylko z `--accept-unverified`; wycofanie staje się żądaniami w `raw/retractions/` dla każdej posiadanej wersji. Rejestr `received:` w należącym do skryptu bloku `share:` w `ckb.yaml` nie pozwala obsłużonym wiadomościom wrócić. `dedup_inbox.py` zgłasza `SAME SHARE`; `ckb-ingest` i `ckb-retract` znają pliki i żądania z share. Test dymny obejmuje dwie bazy i kanał na gołym repozytorium od początku do końca | 1.7 |
|
| 1.28.0 | 2026-11-11 | Nowy opcjonalny moduł `share` (D-0018): skill `ckb-share` i `share.py` (`join`/`send`/`unshare`/`list`/`receive`/`status`, biblioteka standardowa + git). **Kanał** to osobne repozytorium git na grupę zaufania z `CHANNEL.md`, `members.yaml` (baza → e-maile właścicieli) i jedną skrzynką tylko do dopisywania na bazę, `mail/<baza>/`, klonowane do `tmp/share/<kanał>/`. **Wysyłka** pakuje samodzielną kopię strony z `outputs/documents/`, `outputs/answers/` lub `wiki/` (`raw/archive/` tylko z `--raw-ok`): bez fragmentów `<private>` i `## Notes`, linki lokalne jako tekst, ścieżki w Sources/Crux oznaczone `<baza>:`; koperta `type: share`, `kind`, `share_id`, `version`, `from`, `to`, `sent_by`, `untrusted: true`; wzorce sekretów z lintu blokują wysyłkę (kod 3), próba pokazuje sekcję wrażliwości z `ABOUT.md`, użytkownik potwierdza. Ponowna wysyłka tworzy kolejną wersję. **Odbiór** kopiuje wiadomości do bazy do `raw/inbox/` z `share_channel`, `share_ref`, `received_on`, `submitted_by` (autor w gicie) i `supersedes_source`; wiadomość, której autor nie jest właścicielem skrzynki, jest NIEZWERYFIKOWANA i brana tylko z `--accept-unverified`; wycofanie staje się żądaniami w `raw/retractions/` dla każdej posiadanej wersji. Rejestr `received:` w należącym do skryptu bloku `share:` w `ckb.yaml` nie pozwala obsłużonym wiadomościom wrócić. `dedup_inbox.py` zgłasza `SAME SHARE`; `ckb-ingest` i `ckb-retract` znają pliki i żądania z share. Test dymny obejmuje dwie bazy i kanał na gołym repozytorium od początku do końca | 1.7 |
|
||||||
| 1.27.0 | 2026-11-02 | Nowy skill bazowy `ckb-feynman`, zaadaptowany ze skilla `feynman` z superhero-tech-super-brain: wyjaśnia jedną stronę prostymi słowami na konkretnym przykładzie, z linią `→ [[page]] · [Tytuł § Nagłówek](/wiki/…#kotwica)` pod każdym fragmentem, potem przypisuje każde rozrzedzone miejsce do luk Wiki, Źródła lub Moje, nie łatając żadnej wiedzą modelu, prosi o wyjaśnienie z powrotem i kończy ponumerowanymi kolejnymi krokami. Kandydaci to strony `review: draft`/`needs_update`, z jednym źródłem, nieaktualne lub ze sprzecznością; strony tematyczne prowadzą do stron członkowskich; odciski Crux sprawdzane jak w kroku 6 `ckb-retrieve`; fragmenty `<private>` nigdy nie są wyjaśniane. Sesje trafiają do `outputs/teaching/feynman/YYYY-MM-DD_<slug>.md` (`type: feynman-session`, `## Sources` z odciskami, ignorowane przez gita razem z `outputs/teaching/`, bez wpisu w `wiki/log.md`); luka w źródłach trafia do `wiki/query-gaps.md` tylko po zgodzie. `ckb-teach-me` pomija ten folder; zaktualizowane `ckb-init`, wiersz routingu w `AGENTS.md`, oba README i oba podręczniki; przypadek eval `ckb-feynman/session` z zapisanym przebiegiem wzorcowym (6/6). `outputs/teaching/` dodane do kontraktu katalogów; `run_evals.py` dopasowuje usunięte pliki semantyką glob (`**` było jednym segmentem) | 1.7 |
|
| 1.27.0 | 2026-11-02 | Nowy skill bazowy `ckb-feynman`, zaadaptowany ze skilla `feynman` z superhero-tech-super-brain: wyjaśnia jedną stronę prostymi słowami na konkretnym przykładzie, z linią `→ [[page]] · [Tytuł § Nagłówek](/wiki/…#kotwica)` pod każdym fragmentem, potem przypisuje każde rozrzedzone miejsce do luk Wiki, Źródła lub Moje, nie łatając żadnej wiedzą modelu, prosi o wyjaśnienie z powrotem i kończy ponumerowanymi kolejnymi krokami. Kandydaci to strony `review: draft`/`needs_update`, z jednym źródłem, nieaktualne lub ze sprzecznością; strony tematyczne prowadzą do stron członkowskich; odciski Crux sprawdzane jak w kroku 6 `ckb-retrieve`; fragmenty `<private>` nigdy nie są wyjaśniane. Sesje trafiają do `outputs/teaching/feynman/YYYY-MM-DD_<slug>.md` (`type: feynman-session`, `## Sources` z odciskami, ignorowane przez gita razem z `outputs/teaching/`, bez wpisu w `wiki/log.md`); luka w źródłach trafia do `wiki/query-gaps.md` tylko po zgodzie. `ckb-teach-me` pomija ten folder; zaktualizowane `ckb-init`, wiersz routingu w `AGENTS.md`, oba README i oba podręczniki; przypadek eval `ckb-feynman/session` z zapisanym przebiegiem wzorcowym (6/6). `outputs/teaching/` dodane do kontraktu katalogów; `run_evals.py` dopasowuje usunięte pliki semantyką glob (`**` było jednym segmentem) | 1.7 |
|
||||||
| 1.26.2 | 2026-11-10 | `ABOUT.pl.md`: polska para szablonu `ABOUT.md`, jak pozostałe dokumenty `.pl.md`. Gdy oba są wypełnione, agent czyta oba, a przy rozbieżności wygrywa `ABOUT.md` (`AGENTS.md`, `ckb-ingest`); `ckb-init` kopiuje oba i wpisuje odpowiedź po polsku do polskiego pliku; `ckb-upgrade` tworzy go raz w KB poniżej 1.26.2 i nigdy nie odtwarza usuniętego; `ckb-reset` go nie rusza; w module `mcp` `kb_overview` go zawiera, a opis serwera bierze jego `tldr`, pomijając oba placeholdery. `README.pl.md` i `QUICKSTART.pl.md` do niego odsyłają; oba podręczniki go wymieniają | 1.7 |
|
| 1.26.2 | 2026-11-10 | `ABOUT.pl.md`: polska para szablonu `ABOUT.md`, jak pozostałe dokumenty `.pl.md`. Gdy oba są wypełnione, agent czyta oba, a przy rozbieżności wygrywa `ABOUT.md` (`AGENTS.md`, `ckb-ingest`); `ckb-init` kopiuje oba i wpisuje odpowiedź po polsku do polskiego pliku; `ckb-upgrade` tworzy go raz w KB poniżej 1.26.2 i nigdy nie odtwarza usuniętego; `ckb-reset` go nie rusza; w module `mcp` `kb_overview` go zawiera, a opis serwera bierze jego `tldr`, pomijając oba placeholdery. `README.pl.md` i `QUICKSTART.pl.md` do niego odsyłają; oba podręczniki go wymieniają | 1.7 |
|
||||||
|
|
|
||||||
|
|
@ -37,10 +37,11 @@ examples, not magic words; the agent matches intent.
|
||||||
|
|
||||||
### Prerequisites
|
### Prerequisites
|
||||||
|
|
||||||
The agent does almost everything by reading and writing Markdown. Five
|
The agent does almost everything by reading and writing Markdown. Eight
|
||||||
skills additionally run a small **Python 3.8+** script (standard library
|
skills additionally run a small **Python 3.8+** script (standard library
|
||||||
only, nothing to `pip install`): lint (including the check the agent runs
|
only, nothing to `pip install`): lint (including the check the agent runs
|
||||||
at every session start), retrieval ranking, inbox duplicate detection, and the two exporters.
|
at every session start), retrieval ranking, inbox duplicate detection,
|
||||||
|
routines, consolidation reports, saving conversations, and the two exporters.
|
||||||
Python is *recommended*, not strictly required:
|
Python is *recommended*, not strictly required:
|
||||||
|
|
||||||
| Without Python | What happens |
|
| Without Python | What happens |
|
||||||
|
|
|
||||||
|
|
@ -39,11 +39,11 @@ intencji.
|
||||||
|
|
||||||
### Wymagania wstępne
|
### Wymagania wstępne
|
||||||
|
|
||||||
Agent robi prawie wszystko, czytając i pisząc Markdown. Pięć skilli
|
Agent robi prawie wszystko, czytając i pisząc Markdown. Osiem skilli
|
||||||
dodatkowo uruchamia mały skrypt w **Pythonie 3.8+** (tylko biblioteka
|
dodatkowo uruchamia mały skrypt w **Pythonie 3.8+** (tylko biblioteka
|
||||||
standardowa, nic do `pip install`): lint (w tym kontrola uruchamiana na
|
standardowa, nic do `pip install`): lint (w tym kontrola uruchamiana na
|
||||||
początku każdej sesji), ranking przy wyszukiwaniu, wykrywanie duplikatów w
|
początku każdej sesji), ranking przy wyszukiwaniu, wykrywanie duplikatów w
|
||||||
skrzynce oraz dwa eksporty.
|
skrzynce, rutyny, raporty konsolidacji, zapis rozmów oraz dwa eksporty.
|
||||||
Python jest *zalecany*, nie bezwzględnie wymagany:
|
Python jest *zalecany*, nie bezwzględnie wymagany:
|
||||||
|
|
||||||
| Bez Pythona | Co się dzieje |
|
| Bez Pythona | Co się dzieje |
|
||||||
|
|
|
||||||
|
|
@ -289,5 +289,6 @@ python3 tests/run_evals.py check ckb-decide/record "$TMP/eval" > "$TMP/eval.txt"
|
||||||
python3 "$LINT" --budget > "$TMP/budget.txt" || { echo "budget: template is over its own always-loaded budget"; head -3 "$TMP/budget.txt"; fail=1; }
|
python3 "$LINT" --budget > "$TMP/budget.txt" || { echo "budget: template is over its own always-loaded budget"; head -3 "$TMP/budget.txt"; fail=1; }
|
||||||
# mcp module: what a remote client may read and write (no MCP SDK needed).
|
# mcp module: what a remote client may read and write (no MCP SDK needed).
|
||||||
python3 tests/mcp_policy.py "$FIX" || fail=1
|
python3 tests/mcp_policy.py "$FIX" || fail=1
|
||||||
|
python3 -m unittest discover -s tests/unit -q 2>"$TMP/unit.txt" || { cat "$TMP/unit.txt"; echo "unit tests failed"; fail=1; }
|
||||||
[[ $fail -eq 0 ]] && echo "smoke: OK"
|
[[ $fail -eq 0 ]] && echo "smoke: OK"
|
||||||
exit $fail
|
exit $fail
|
||||||
|
|
|
||||||
36
tests/unit/test_docs_consistency.py
Normal file
36
tests/unit/test_docs_consistency.py
Normal file
|
|
@ -0,0 +1,36 @@
|
||||||
|
"""AGENTS.md is loaded into every session; what it says about the skills must
|
||||||
|
match what ships."""
|
||||||
|
import re
|
||||||
|
import unittest
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[2]
|
||||||
|
AGENTS = (ROOT / "AGENTS.md").read_text(encoding="utf-8")
|
||||||
|
WORDS = {3: "Three", 4: "Four", 5: "Five", 6: "Six", 7: "Seven", 8: "Eight",
|
||||||
|
9: "Nine", 10: "Ten", 11: "Eleven", 12: "Twelve"}
|
||||||
|
|
||||||
|
|
||||||
|
def core_skills():
|
||||||
|
return sorted(p.name for p in (ROOT / ".agents/skills").iterdir() if (p / "SKILL.md").is_file())
|
||||||
|
|
||||||
|
|
||||||
|
def skills_with_scripts():
|
||||||
|
return sorted(p.name for p in (ROOT / ".agents/skills").iterdir() if list((p / "scripts").glob("*.py")))
|
||||||
|
|
||||||
|
|
||||||
|
class AgentsMd(unittest.TestCase):
|
||||||
|
def test_script_sentence_matches_disk(self):
|
||||||
|
m = re.search(r"(\w+) skills ship a deterministic Python script \(([^)]*)\)", AGENTS)
|
||||||
|
self.assertIsNotNone(m, "the 'N skills ship a deterministic Python script' sentence is missing")
|
||||||
|
named = sorted(re.findall(r"`(ckb-[\w-]+)`", m.group(2)))
|
||||||
|
self.assertEqual(named, skills_with_scripts())
|
||||||
|
self.assertEqual(m.group(1), WORDS.get(len(named)), "count word does not match the list")
|
||||||
|
|
||||||
|
def test_every_core_skill_is_routed(self):
|
||||||
|
routing = AGENTS.split("## 3. SKILL ROUTING", 1)[1].split("### Scripts", 1)[0]
|
||||||
|
missing = [s for s in core_skills() if f"`{s}`" not in routing]
|
||||||
|
self.assertEqual(missing, [], "skills with no routing-table row")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
69
tests/unit/test_exporters.py
Normal file
69
tests/unit/test_exporters.py
Normal file
|
|
@ -0,0 +1,69 @@
|
||||||
|
"""The exporters delete and rewrite their output folder; they must never
|
||||||
|
reach outside it, whatever the page text or the --out flag says."""
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[2]
|
||||||
|
FIX = ROOT / "tests/fixtures/minimal-kb"
|
||||||
|
OKF = ROOT / ".agents/skills/ckb-export-okf/scripts/export_okf.py"
|
||||||
|
STARLIGHT = ROOT / ".agents/skills/ckb-export-starlight/scripts/export_starlight.py"
|
||||||
|
|
||||||
|
|
||||||
|
def run(cwd, script, *args):
|
||||||
|
return subprocess.run([sys.executable, str(script), *args], cwd=str(cwd),
|
||||||
|
capture_output=True, text=True, encoding="utf-8", errors="replace")
|
||||||
|
|
||||||
|
|
||||||
|
class ExportContainment(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.tmp = tempfile.TemporaryDirectory()
|
||||||
|
self.outer = Path(self.tmp.name)
|
||||||
|
self.kb = self.outer / "kb"
|
||||||
|
shutil.copytree(str(FIX), str(self.kb))
|
||||||
|
|
||||||
|
def tearDown(self):
|
||||||
|
self.tmp.cleanup()
|
||||||
|
|
||||||
|
def test_okf_refuses_out_outside_outputs(self):
|
||||||
|
for bad in (".", "wiki", "outputs", "..", str(self.outer)):
|
||||||
|
r = run(self.kb, OKF, "--out", bad)
|
||||||
|
self.assertEqual(r.returncode, 2, f"--out {bad}: {r.stdout}{r.stderr}")
|
||||||
|
self.assertTrue((self.kb / "wiki" / "index.md").is_file(), f"--out {bad} deleted the wiki")
|
||||||
|
self.assertTrue((self.kb / "ckb.yaml").is_file(), f"--out {bad} deleted the KB")
|
||||||
|
|
||||||
|
def test_okf_default_and_nested_out_work(self):
|
||||||
|
self.assertIn(run(self.kb, OKF).returncode, (0, 1))
|
||||||
|
self.assertTrue((self.kb / "outputs/okf").is_dir())
|
||||||
|
self.assertIn(run(self.kb, OKF, "--out", "outputs/okf-test").returncode, (0, 1))
|
||||||
|
self.assertTrue((self.kb / "outputs/okf-test").is_dir())
|
||||||
|
|
||||||
|
def test_okf_check_writes_nothing(self):
|
||||||
|
before = sorted(p.relative_to(self.kb) for p in self.kb.rglob("*"))
|
||||||
|
self.assertIn(run(self.kb, OKF, "--check").returncode, (0, 1))
|
||||||
|
self.assertEqual(sorted(p.relative_to(self.kb) for p in self.kb.rglob("*")), before)
|
||||||
|
|
||||||
|
def test_starlight_image_traversal_is_not_copied(self):
|
||||||
|
(self.outer / "secret.txt").write_text("do not export", encoding="utf-8")
|
||||||
|
assets = self.kb / "wiki" / "assets"
|
||||||
|
assets.mkdir(parents=True, exist_ok=True)
|
||||||
|
(assets / "ok.png").write_bytes(b"\x89PNG")
|
||||||
|
page = self.kb / "wiki" / "entities" / "pic.md"
|
||||||
|
page.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
page.write_text("---\ntype: entity\ntldr: pictures\n---\n\n# Pic\n\n"
|
||||||
|
"\n\n\n"
|
||||||
|
"\n", encoding="utf-8")
|
||||||
|
r = run(self.kb, STARLIGHT, "--mode", "content-only", "--today", "2026-11-11")
|
||||||
|
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
|
||||||
|
out = self.kb / "outputs" / "starlight"
|
||||||
|
self.assertTrue((out / "public/assets/ok.png").is_file(), "a normal asset should still be copied")
|
||||||
|
leaked = [p for p in self.outer.rglob("secret.txt") if p != self.outer / "secret.txt"]
|
||||||
|
self.assertEqual(leaked, [], f"traversal copied the file to {leaked}")
|
||||||
|
self.assertIn("not copied", r.stderr)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
93
tests/unit/test_py38.py
Normal file
93
tests/unit/test_py38.py
Normal file
|
|
@ -0,0 +1,93 @@
|
||||||
|
"""Every script the template ships must run on Python 3.8 (AGENTS.md §3).
|
||||||
|
|
||||||
|
No 3.8 interpreter is needed: this parses each script and rejects syntax and
|
||||||
|
standard-library APIs that arrived later. The mcp server is exempt — its SDK
|
||||||
|
dependency requires 3.10, and it runs in its own container.
|
||||||
|
"""
|
||||||
|
import ast
|
||||||
|
import sys
|
||||||
|
import unittest
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[2]
|
||||||
|
EXEMPT = {Path(".agents/modules/mcp/server")}
|
||||||
|
|
||||||
|
# Methods and functions added after 3.8, by name.
|
||||||
|
LATER_ATTRS = {
|
||||||
|
"removeprefix", "removesuffix", # str/bytes, 3.9
|
||||||
|
"is_relative_to", "with_stem", # pathlib, 3.9
|
||||||
|
"readlink", # Path.readlink, 3.9
|
||||||
|
"lcm", # math, 3.9
|
||||||
|
"bit_count", # int, 3.10
|
||||||
|
"pairwise", # itertools, 3.10
|
||||||
|
"aiter", "anext", # builtins, 3.10
|
||||||
|
"batched", # itertools, 3.12
|
||||||
|
"walk", # Path.walk, 3.12 (os.walk is fine; see below)
|
||||||
|
}
|
||||||
|
LATER_MODULES = {"zoneinfo", "graphlib", "tomllib"}
|
||||||
|
BUILTIN_GENERICS = {"list", "dict", "set", "frozenset", "tuple", "type"}
|
||||||
|
|
||||||
|
|
||||||
|
def scripts():
|
||||||
|
for p in sorted((ROOT / ".agents").rglob("*.py")):
|
||||||
|
rel = p.relative_to(ROOT)
|
||||||
|
if any(rel.is_relative_to(e) if hasattr(rel, "is_relative_to") else str(rel).startswith(str(e)) for e in EXEMPT):
|
||||||
|
continue
|
||||||
|
yield rel, p.read_text(encoding="utf-8")
|
||||||
|
|
||||||
|
|
||||||
|
def problems(rel, text):
|
||||||
|
out = []
|
||||||
|
try:
|
||||||
|
tree = ast.parse(text, filename=str(rel), feature_version=(3, 8))
|
||||||
|
except SyntaxError as e:
|
||||||
|
return [f"{rel}:{e.lineno}: syntax newer than 3.8: {e.msg}"]
|
||||||
|
future_annotations = any(
|
||||||
|
isinstance(n, ast.ImportFrom) and n.module == "__future__"
|
||||||
|
and any(a.name == "annotations" for a in n.names)
|
||||||
|
for n in tree.body)
|
||||||
|
|
||||||
|
def annotation_issue(node):
|
||||||
|
for sub in ast.walk(node):
|
||||||
|
if isinstance(sub, ast.BinOp) and isinstance(sub.op, ast.BitOr):
|
||||||
|
return "`X | Y` annotation (3.10)"
|
||||||
|
if isinstance(sub, ast.Subscript) and isinstance(sub.value, ast.Name) \
|
||||||
|
and sub.value.id in BUILTIN_GENERICS:
|
||||||
|
return f"`{sub.value.id}[...]` annotation (3.9)"
|
||||||
|
return None
|
||||||
|
|
||||||
|
for node in ast.walk(tree):
|
||||||
|
if isinstance(node, ast.Attribute) and node.attr in LATER_ATTRS:
|
||||||
|
# os.walk predates everything; only flag `.walk` on non-`os` objects
|
||||||
|
if node.attr == "walk" and isinstance(node.value, ast.Name) and node.value.id == "os":
|
||||||
|
continue
|
||||||
|
out.append(f"{rel}:{node.lineno}: `.{node.attr}` is newer than 3.8")
|
||||||
|
elif isinstance(node, ast.Import):
|
||||||
|
out += [f"{rel}:{node.lineno}: module `{a.name}` is newer than 3.8"
|
||||||
|
for a in node.names if a.name.split(".")[0] in LATER_MODULES]
|
||||||
|
elif isinstance(node, ast.ImportFrom) and node.module and node.module.split(".")[0] in LATER_MODULES:
|
||||||
|
out.append(f"{rel}:{node.lineno}: module `{node.module}` is newer than 3.8")
|
||||||
|
elif not future_annotations and isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
||||||
|
anns = [a.annotation for a in node.args.args + node.args.kwonlyargs if a.annotation]
|
||||||
|
anns += [node.returns] if node.returns else []
|
||||||
|
for ann in anns:
|
||||||
|
issue = annotation_issue(ann)
|
||||||
|
if issue:
|
||||||
|
out.append(f"{rel}:{ann.lineno}: {issue}")
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
class Py38Compat(unittest.TestCase):
|
||||||
|
def test_scripts_parse_and_use_only_38_apis(self):
|
||||||
|
found = []
|
||||||
|
for rel, text in scripts():
|
||||||
|
found += problems(rel, text)
|
||||||
|
self.assertEqual(found, [], "\n" + "\n".join(found))
|
||||||
|
|
||||||
|
def test_guard_catches_known_bad_code(self):
|
||||||
|
bad = "def f(x: list[str]) -> str | None:\n return x[0].removeprefix('a')\nimport zoneinfo\n"
|
||||||
|
self.assertEqual(len(problems(Path("bad.py"), bad)), 4)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
78
tests/unit/test_routines.py
Normal file
78
tests/unit/test_routines.py
Normal file
|
|
@ -0,0 +1,78 @@
|
||||||
|
"""routines.py edits ckb.yaml in place; every edit must leave valid YAML."""
|
||||||
|
import re
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[2]
|
||||||
|
SCRIPT = ROOT / ".agents/skills/ckb-routine/scripts/routines.py"
|
||||||
|
|
||||||
|
|
||||||
|
def run(root, *args):
|
||||||
|
return subprocess.run([sys.executable, str(SCRIPT), "--root", str(root), "--today", "2026-11-11", *args],
|
||||||
|
capture_output=True, text=True, encoding="utf-8")
|
||||||
|
|
||||||
|
|
||||||
|
def yaml_problems(text):
|
||||||
|
"""A YAML subset check strong enough for ckb.yaml: every mapping line is
|
||||||
|
`key:` or `key: value` (a space after the colon), never `key:value`."""
|
||||||
|
bad = []
|
||||||
|
for n, line in enumerate(text.splitlines(), 1):
|
||||||
|
body = line.split(" #", 1)[0].rstrip()
|
||||||
|
m = re.match(r"^\s*(?:-\s+)?([A-Za-z_][\w-]*):(\S.*)?$", body)
|
||||||
|
if m and m.group(2) and not m.group(2).startswith("//"):
|
||||||
|
bad.append(f"{n}: {line}")
|
||||||
|
return bad
|
||||||
|
|
||||||
|
|
||||||
|
class Mark(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.tmp = tempfile.TemporaryDirectory()
|
||||||
|
self.root = Path(self.tmp.name)
|
||||||
|
|
||||||
|
def tearDown(self):
|
||||||
|
self.tmp.cleanup()
|
||||||
|
|
||||||
|
def write(self, text):
|
||||||
|
(self.root / "ckb.yaml").write_text(text, encoding="utf-8")
|
||||||
|
|
||||||
|
def read(self):
|
||||||
|
return (self.root / "ckb.yaml").read_text(encoding="utf-8")
|
||||||
|
|
||||||
|
def test_add_then_mark_keeps_space_after_colon(self):
|
||||||
|
self.write("template:\n branch: main\n")
|
||||||
|
self.assertEqual(run(self.root, "--add", "--name", "wl", "--do", "Lint", "--every", "7d").returncode, 0)
|
||||||
|
self.assertEqual(run(self.root, "--mark", "wl").returncode, 0)
|
||||||
|
text = self.read()
|
||||||
|
self.assertIn(" last_run: 2026-11-11", text)
|
||||||
|
self.assertEqual(yaml_problems(text), [])
|
||||||
|
|
||||||
|
def test_mark_keeps_trailing_comment(self):
|
||||||
|
self.write("routines:\n - name: wl\n do: Lint\n every: 7d\n last_run: # never ran\n")
|
||||||
|
self.assertEqual(run(self.root, "--mark", "wl").returncode, 0)
|
||||||
|
self.assertIn(" last_run: 2026-11-11 # never ran\n", self.read())
|
||||||
|
due = run(self.root, "--due")
|
||||||
|
self.assertNotIn("unreadable", due.stdout + due.stderr)
|
||||||
|
|
||||||
|
def test_mark_replaces_existing_date_only(self):
|
||||||
|
self.write("routines:\n - name: wl\n do: Lint\n every: 7d\n last_run: 2026-01-01 # weekly\n")
|
||||||
|
run(self.root, "--mark", "wl")
|
||||||
|
self.assertIn(" last_run: 2026-11-11 # weekly\n", self.read())
|
||||||
|
|
||||||
|
def test_mark_unknown_name_leaves_file_unchanged(self):
|
||||||
|
before = "routines:\n - name: wl\n do: Lint\n every: 7d\n last_run:\n"
|
||||||
|
self.write(before)
|
||||||
|
self.assertNotEqual(run(self.root, "--mark", "nope").returncode, 0)
|
||||||
|
self.assertEqual(self.read(), before)
|
||||||
|
|
||||||
|
def test_bad_period_leaves_file_unchanged(self):
|
||||||
|
before = "template:\n branch: main\n"
|
||||||
|
self.write(before)
|
||||||
|
self.assertNotEqual(run(self.root, "--add", "--name", "x", "--do", "Lint", "--every", "3m").returncode, 0)
|
||||||
|
self.assertEqual(self.read(), before)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
Loading…
Add table
Reference in a new issue