@fabersep/spec 0.0.0-stage → 0.2.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/.claude-plugin/plugin.json +10 -0
- package/LICENSE +202 -0
- package/README.md +277 -2
- package/package.json +52 -4
- package/plugin.json +18 -0
- package/rules/documentation-rules.md +75 -0
- package/skills/faber-discuss/SKILL.md +147 -0
- package/skills/faber-discuss/discuss_log.py +286 -0
- package/skills/faber-discuss/discuss_round.py +379 -0
- package/skills/faber-extract-features/SKILL.md +46 -0
- package/skills/faber-init-arch/SKILL.md +44 -0
- package/skills/faber-init-prd/SKILL.md +38 -0
- package/skills/faber-new-feature/SKILL.md +51 -0
- package/src/cli.mjs +288 -0
- package/src/installer.mjs +387 -0
- package/src/prompt.mjs +114 -0
- package/templates/architecture.md +93 -0
- package/templates/feature-bdd.md +54 -0
- package/templates/feature-prd.md +80 -0
- package/templates/master-prd.md +114 -0
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: faber-discuss
|
|
3
|
+
description: Cross-model second-opinion design and spec review loop, started only when the user explicitly requests it ("faber-discuss", "discuss", /faber-discuss). The active agent (author) briefs an external read-only reviewer CLI (reviewer), loops on numbered findings until they close, drafts the PRD and BDD using FaberSEP templates and rules, has them reviewed in the same reviewer conversation, and finishes with a key-point summary and owner questions.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# faber-discuss — Cross-Model Design & Spec Review
|
|
7
|
+
|
|
8
|
+
Run a structured, read-only second-opinion loop with an external reviewer CLI (`agy` or `claude`) before writing code.
|
|
9
|
+
|
|
10
|
+
**Hard guardrails:**
|
|
11
|
+
- Start **only** when the user explicitly asks to run `faber-discuss` / `discuss` (never on your own initiative).
|
|
12
|
+
- Respond to the user in the user's language; write every ledger file, brief, prompt, and spec in English (quoting the user's own constraints verbatim with an English gloss).
|
|
13
|
+
- Never let the reviewer edit files, run shell commands, or launch subagents/workflows.
|
|
14
|
+
- Never approve a spec, commit, push, or move project board cards inside this skill.
|
|
15
|
+
- **Testing the skill itself:** always pass `--test` to `discuss_round.py` so only the cheapest test model is used (`gemini-3.8-flash-low` for `agy`, `haiku` for `claude`).
|
|
16
|
+
|
|
17
|
+
---
|
|
18
|
+
|
|
19
|
+
## Step 1: Load Governance Rules and Templates
|
|
20
|
+
|
|
21
|
+
Locate the plugin root relative to this `SKILL.md` (`../..`, or `~/.faber/spec/` when installed as a standalone skill in Codex/Cursor), and keep these paths ready for Phase 2 (`spec`):
|
|
22
|
+
1. `../../rules/documentation-rules.md` (fallback: `~/.faber/spec/rules/documentation-rules.md`)
|
|
23
|
+
2. `../../templates/feature-prd.md` (fallback: `~/.faber/spec/templates/feature-prd.md`)
|
|
24
|
+
3. `../../templates/feature-bdd.md` (fallback: `~/.faber/spec/templates/feature-bdd.md`)
|
|
25
|
+
|
|
26
|
+
The helper scripts `discuss_round.py` and `discuss_log.py` live directly alongside this `SKILL.md` (and at `~/.faber/spec/skills/faber-discuss/`).
|
|
27
|
+
|
|
28
|
+
Check the active repository's entry file (`AGENTS.md` or `CLAUDE.md`) and `docs/` layout so generated specs follow project conventions.
|
|
29
|
+
|
|
30
|
+
---
|
|
31
|
+
|
|
32
|
+
## Step 2: Parse Arguments and Defaults
|
|
33
|
+
|
|
34
|
+
The user may give arguments in any order or as natural language (for example: `"claude opus, 3 rounds, 300K, phase=discuss"` or `"neon medium, 4 tur"`). Before Round 1, confirm in one short line what you understood (`reviewer cli/model, rounds, budget, phase1 cap, phase, topic`); ask only if a value is unclear.
|
|
35
|
+
|
|
36
|
+
| Argument | Default | Rule |
|
|
37
|
+
| :--- | :--- | :--- |
|
|
38
|
+
| `cli` | Cross-vendor opposite of `author` (`claude` if author is Antigravity; `agy` if author is Claude) | Supported: `agy`, `claude` |
|
|
39
|
+
| `model` | `opus` (if `cli=claude`) / `gemini-4-neon-medium` (if `cli=agy`) | With `--test`: cheapest only (`haiku` / `gemini-3.8-flash-low`) |
|
|
40
|
+
| `rounds` | `5` per phase | Hard cap per phase |
|
|
41
|
+
| `budget` | `500000` uncached tokens total | `input + output` (including cache write); cache reads logged separately |
|
|
42
|
+
| `phase1` | Half of `budget` | Remaining budget goes to Phase 2 |
|
|
43
|
+
| `phase` | `both` | `discuss` stops after Phase 1; `spec` skips Phase 1 (requires an earlier `decisions.md`) |
|
|
44
|
+
| `topic` | Short slug from current subject | Used for the ledger directory name |
|
|
45
|
+
| `ledger` | `records/external-reviews/YYYY-MM-DD-<reviewer>-<topic>/` if `records/external-reviews/` exists, else `docs/reviews/YYYY-MM-DD-<reviewer>-<topic>/` | Append `-2`, `-3` if the folder already exists |
|
|
46
|
+
|
|
47
|
+
Create `<ledger>/README.md` first (arguments, start time, author and reviewer pair).
|
|
48
|
+
|
|
49
|
+
Initialize the run record before Round 1:
|
|
50
|
+
```bash
|
|
51
|
+
python3 <plugin_dir>/skills/faber-discuss/discuss_log.py init <ledger> \
|
|
52
|
+
--topic <topic> --scenario <topic> \
|
|
53
|
+
--author-model <author-model> --author-effort <effort> \
|
|
54
|
+
--reviewer-cli <cli> --reviewer-model <model> \
|
|
55
|
+
--budget <N> --rounds <N> --phase <phase> --repo <repo-path>
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
---
|
|
59
|
+
|
|
60
|
+
## Step 3: Running Each Round
|
|
61
|
+
|
|
62
|
+
1. Write the exact prompt to `<ledger>/p<phase>-r<n>-prompt.md`.
|
|
63
|
+
2. Execute `discuss_round.py` from the repository root (allow up to 600s command timeout):
|
|
64
|
+
```bash
|
|
65
|
+
python3 <plugin_dir>/skills/faber-discuss/discuss_round.py <ledger> p<phase>-r<n> \
|
|
66
|
+
--cli <cli> --model <model> [--conversation <id>] [--add-dir <path>] [--timeout 540] [--test]
|
|
67
|
+
```
|
|
68
|
+
3. Handle exit codes:
|
|
69
|
+
- `0`: Read `<ledger>/p<phase>-r<n>-reply.md` in full. Check token totals against the phase budget and round cap.
|
|
70
|
+
- `2` (quota/auth error): Stop immediately and jump to Step 6 (**End**).
|
|
71
|
+
- `5` (reviewer failed to resume `--conversation` and opened a new ID): Inform the user immediately (old ID vs new ID, history lost), switch to the **Cold / New Conversation** packet built from `decisions.md` + open items, and record the new ID in `<ledger>/README.md`.
|
|
72
|
+
- `3` or `4` (timeout or missing findings/`VERDICT`): Retry once (for `4`, remind the reviewer of the exact answer format). A second failure ends the run and hands open items to the user.
|
|
73
|
+
|
|
74
|
+
### Cache and Cost Discipline
|
|
75
|
+
- Prompt caches expire quickly (observed ~7 minutes warm window on `agy`). Rule findings quickly using targeted reads (`grep` or line ranges) instead of re-reading entire files, and send the next round within 7 minutes.
|
|
76
|
+
- If >7 minutes passed and previous input exceeded 30K tokens (cold cache or `continue`), start a fresh reviewer conversation (omit `--conversation`) with a compact packet: role, decision table, open IDs, and only the excerpts needed for those open IDs.
|
|
77
|
+
- Estimate each round's cost before sending it (warm: prompt + reply; cold resume: last input; fresh packet: system overhead + packet) and skip the round if it would exceed remaining budget.
|
|
78
|
+
|
|
79
|
+
---
|
|
80
|
+
|
|
81
|
+
## Step 4: Phase 1 — Design Discussion (`discuss`)
|
|
82
|
+
|
|
83
|
+
**Round 1 prompt (`p1-r1-prompt.md`) structure (do NOT paste raw chat transcript):**
|
|
84
|
+
1. **Role:** `"You are the second reviewer in a design discussion. Find what is wrong, missing, or unclear; do not agree to be polite. Read files from disk; do not edit files, run commands, or use subagents, workflows, schedules, or web search."`
|
|
85
|
+
2. **Goal:** What we are designing and why (a few sentences).
|
|
86
|
+
3. **Decided so far:** Numbered list.
|
|
87
|
+
4. **Ruled out:** Option, who ruled it out, why.
|
|
88
|
+
5. **Owner constraints:** User's exact words verbatim (plus English gloss if not English).
|
|
89
|
+
6. **Open points:** Unresolved questions or trade-offs.
|
|
90
|
+
7. **Files worth reading:** Specific absolute paths and relevant line ranges (never "read the whole repo").
|
|
91
|
+
8. **Owner-decision boundary:** Money/billing, store/console, user-visible product changes, scope, and data deletion belong to the project owner — list them under `## Owner questions` (`OQ-n`), never decide them.
|
|
92
|
+
9. **Answer format:**
|
|
93
|
+
- Findings as `F-n [BLOCKER|MAJOR|MINOR] [OPEN|CLOSED]` with **Claim**, **Evidence** (quote or `path:line`), and **Proposed change** (at most 12 per round).
|
|
94
|
+
- Separate `## Owner questions` (`OQ-n`) section.
|
|
95
|
+
- Final line: `VERDICT: CONTINUE | DONE` (limit ~800 words).
|
|
96
|
+
|
|
97
|
+
**Author Rulings & Round N > 1:**
|
|
98
|
+
- Verify each finding against the actual files on disk before ruling.
|
|
99
|
+
- Record every ruling via `discuss_log.py rule <ledger> <round-tag> F-n --ruling ACCEPT|REJECT|PARTIAL|OWNER|SETTLED --reason valid|wrong-claim|out-of-scope|already-covered|owner-decides --note "<one line>"`. (Use `--by owner` when the user rules directly.)
|
|
100
|
+
- Round `N > 1` prompt opens with the ruling table (`ID | ruling | reason or change`) plus any verbatim owner answers, then instructs: `"Reply only on rulings you contest and on new BLOCKER or MAJOR items. Mark accepted IDs CLOSED. Do not reopen OWNER items. New MINOR items only in round 1 of a phase. Before outputting DONE with no findings, confirm you checked edge cases, failure modes, the project entry file (AGENTS.md / CLAUDE.md), and owner constraints."`
|
|
101
|
+
|
|
102
|
+
**Phase 1 Stop Rules:**
|
|
103
|
+
- Stop when `VERDICT: DONE` and zero `BLOCKER`/`MAJOR` findings remain `OPEN`, or at the round cap / Phase 1 budget.
|
|
104
|
+
- **Stalemate:** Any finding still `OPEN` after the author's second `REJECT` becomes `STALEMATE` and moves to the owner list.
|
|
105
|
+
- Write `<ledger>/decisions.md` (decision table of closed IDs, owner questions, stalemates).
|
|
106
|
+
- If any `BLOCKER` sits in `OWNER` or `STALEMATE`, stop here, jump to **End**, and instruct the user to rerun with `phase=spec` after deciding.
|
|
107
|
+
|
|
108
|
+
---
|
|
109
|
+
|
|
110
|
+
## Step 5: Phase 2 — Spec Review (`spec`)
|
|
111
|
+
|
|
112
|
+
1. Write `docs/features/<NN>-<slug>/prd.md` and `acceptance_criteria.md` (`status: draft`) following `../../rules/documentation-rules.md`, `../../templates/feature-prd.md`, `../../templates/feature-bdd.md`, and any target-repo spec rules. Update `docs/features/README.md`.
|
|
113
|
+
2. Before each Phase 2 round, snapshot both files to `<ledger>/snapshots/p2-r<n>-prd.md` and `<ledger>/snapshots/p2-r<n>-acceptance_criteria.md`.
|
|
114
|
+
3. **Round 1 prompt** (continuing the same `--conversation` when warm): give exact paths to PRD, BDD, governance rules, and `<ledger>/decisions.md`; instruct `"Read the files from disk, not from your memory of the discussion"`; check:
|
|
115
|
+
- (a) **Traceability:** every Phase 1 decision is in the PRD, every `FR-XX` maps to `AC-XX` scenarios.
|
|
116
|
+
- (b) **Testability:** atomic, observable `GIVEN / WHEN / THEN` with zero code identifiers or placeholders.
|
|
117
|
+
- (c) **Consistency:** PRD, BDD, and project rules agree.
|
|
118
|
+
- (d) **Boundaries:** non-goals and failure modes are explicit.
|
|
119
|
+
Continue finding numbering (`F-n`).
|
|
120
|
+
4. **Rounds 2+:** send the ruling table plus `diff -u` against the previous snapshot (`snapshots/p2-r<n-1>-*`).
|
|
121
|
+
5. Apply the same stop rules against remaining budget.
|
|
122
|
+
|
|
123
|
+
---
|
|
124
|
+
|
|
125
|
+
## Step 6: End of Run
|
|
126
|
+
|
|
127
|
+
1. Close the log and generate stats/transcript:
|
|
128
|
+
```bash
|
|
129
|
+
python3 <plugin_dir>/skills/faber-discuss/discuss_log.py end <ledger> --reason done|cap|budget|error|stalemate
|
|
130
|
+
python3 <plugin_dir>/skills/faber-discuss/discuss_log.py stats <ledger>
|
|
131
|
+
```
|
|
132
|
+
2. Write `<ledger>/summary.md` (English).
|
|
133
|
+
3. Present to the user (in the user's language):
|
|
134
|
+
- A short key-point summary of the design and spec for a simple `yes` / `no` approval.
|
|
135
|
+
- Numbered owner questions (`OQ-n`) with recommended defaults.
|
|
136
|
+
- Open `MINOR` items.
|
|
137
|
+
- The stats table from `discuss_log.py stats`, the latest `conversation_id`, and how the run ended.
|
|
138
|
+
|
|
139
|
+
---
|
|
140
|
+
|
|
141
|
+
## Step 7: Continue (`/faber-discuss continue`)
|
|
142
|
+
|
|
143
|
+
Syntax: `continue [rounds=2] [budget=100K] [phase=last] [topic] [note]`
|
|
144
|
+
- In a new session without `topic`, list recent ledger folders and ask which one to resume — never resume silently.
|
|
145
|
+
- Read `<ledger>/decisions.md` and the latest `conversation_id`.
|
|
146
|
+
- Quote the user's note verbatim, state which `OQ` or decision it updates, reset stalemate counts for touched IDs, and instruct the reviewer to re-read PRD and BDD from disk.
|
|
147
|
+
- Follow the warm/cold rule (>7 min + >30K input -> fresh packet conversation) and finish with Step 6 (**End**).
|
|
@@ -0,0 +1,286 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Run records for faber-discuss so runs across different author/reviewer pairs can be compared.
|
|
3
|
+
|
|
4
|
+
discuss_log.py init <ledger> --topic T --scenario S --author-model M --author-effort E
|
|
5
|
+
--reviewer-cli CLI --reviewer-model R [--budget N] [--rounds N]
|
|
6
|
+
[--phase both|discuss|spec] [--repo PATH ...]
|
|
7
|
+
discuss_log.py rule <ledger> <round-tag> F-n --ruling ACCEPT|REJECT|PARTIAL|OWNER|SETTLED
|
|
8
|
+
[--reason wrong-claim|out-of-scope|already-covered|owner-decides|valid] [--note TEXT]
|
|
9
|
+
discuss_log.py end <ledger> --reason done|cap|budget|error|stalemate [--author-tokens N]
|
|
10
|
+
[--author-context N] [--plan-5h PCT]
|
|
11
|
+
discuss_log.py outcome <ledger> F-n --was right|wrong [--note TEXT]
|
|
12
|
+
discuss_log.py stats <ledger>
|
|
13
|
+
|
|
14
|
+
Files in the ledger: run.json, rounds.jsonl, rulings.jsonl, outcomes.jsonl, stats.md, transcript.md,
|
|
15
|
+
and per-round p<phase>-r<n>-prompt.md / -reply.json / -reply.md."""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import argparse
|
|
20
|
+
import json
|
|
21
|
+
import re
|
|
22
|
+
import subprocess
|
|
23
|
+
import sys
|
|
24
|
+
import time
|
|
25
|
+
from collections import Counter
|
|
26
|
+
from pathlib import Path
|
|
27
|
+
|
|
28
|
+
RULINGS = ("ACCEPT", "REJECT", "PARTIAL", "OWNER", "SETTLED")
|
|
29
|
+
REASONS = ("valid", "wrong-claim", "out-of-scope", "already-covered", "owner-decides")
|
|
30
|
+
FINDING = re.compile(r"\b(F-\d+)\b\W{0,6}\[?(BLOCKER|MAJOR|MINOR)\]?\W{0,6}\[?(OPEN|CLOSED)?\]?")
|
|
31
|
+
OWNER_Q = re.compile(r"\bOQ-\d+\b")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def parse_findings(text: str) -> list[dict]:
|
|
35
|
+
"""Findings as the reviewer wrote them: first mention of each ID with its severity and status."""
|
|
36
|
+
seen: dict[str, dict] = {}
|
|
37
|
+
for match in FINDING.finditer(text):
|
|
38
|
+
fid, severity, status = match.groups()
|
|
39
|
+
if fid not in seen:
|
|
40
|
+
seen[fid] = {"id": fid, "severity": severity, "status": status or ""}
|
|
41
|
+
return list(seen.values())
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _round_key(tag: str) -> tuple[int, int]:
|
|
45
|
+
phase, rnd = tag.split("-")[:2]
|
|
46
|
+
return int(phase[1:]), int(rnd[1:])
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _jsonl(path: Path) -> list[dict]:
|
|
50
|
+
if not path.exists():
|
|
51
|
+
return []
|
|
52
|
+
return [json.loads(line) for line in path.read_text().splitlines() if line.strip()]
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _append(path: Path, row: dict) -> None:
|
|
56
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
57
|
+
with path.open("a") as handle:
|
|
58
|
+
handle.write(json.dumps(row, ensure_ascii=False) + "\n")
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _commit(path: str) -> str:
|
|
62
|
+
done = subprocess.run(["git", "-C", path, "rev-parse", "HEAD"], capture_output=True, text=True, check=False)
|
|
63
|
+
return done.stdout.strip()
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def cmd_init(args: argparse.Namespace) -> int:
|
|
67
|
+
ledger = Path(args.ledger)
|
|
68
|
+
ledger.mkdir(parents=True, exist_ok=True)
|
|
69
|
+
run = {
|
|
70
|
+
"topic": args.topic,
|
|
71
|
+
"scenario": args.scenario,
|
|
72
|
+
"started_at": time.time(),
|
|
73
|
+
"author": {"model": args.author_model, "effort": args.author_effort},
|
|
74
|
+
"reviewer": {"cli": args.reviewer_cli, "model": args.reviewer_model},
|
|
75
|
+
"budget": args.budget,
|
|
76
|
+
"rounds_per_phase": args.rounds,
|
|
77
|
+
"phase": args.phase,
|
|
78
|
+
"repos": {repo: _commit(repo) for repo in args.repo},
|
|
79
|
+
}
|
|
80
|
+
if args.author_context is not None:
|
|
81
|
+
run["author"]["context_start"] = args.author_context
|
|
82
|
+
if args.plan_5h is not None:
|
|
83
|
+
run["author"]["plan_5h_start"] = args.plan_5h
|
|
84
|
+
(ledger / "run.json").write_text(json.dumps(run, indent=2, ensure_ascii=False))
|
|
85
|
+
print(f"run.json written: {ledger / 'run.json'}")
|
|
86
|
+
return 0
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def cmd_rule(args: argparse.Namespace) -> int:
|
|
90
|
+
ledger = Path(args.ledger)
|
|
91
|
+
row = {
|
|
92
|
+
"at": time.time(),
|
|
93
|
+
"round": args.round,
|
|
94
|
+
"id": args.id,
|
|
95
|
+
"by": args.by,
|
|
96
|
+
"ruling": args.ruling,
|
|
97
|
+
"reason": args.reason or ("owner-decides" if args.ruling == "OWNER" else ""),
|
|
98
|
+
"note": args.note,
|
|
99
|
+
}
|
|
100
|
+
_append(ledger / "rulings.jsonl", row)
|
|
101
|
+
print(f"{args.id}: {args.ruling} {row['reason']}")
|
|
102
|
+
return 0
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def cmd_end(args: argparse.Namespace) -> int:
|
|
106
|
+
path = Path(args.ledger) / "run.json"
|
|
107
|
+
run = json.loads(path.read_text()) if path.exists() else {}
|
|
108
|
+
run["ended_at"] = time.time()
|
|
109
|
+
run["end_reason"] = args.reason
|
|
110
|
+
author = run.setdefault("author", {})
|
|
111
|
+
if args.author_tokens is not None:
|
|
112
|
+
author["tokens"] = args.author_tokens
|
|
113
|
+
if args.author_context is not None:
|
|
114
|
+
author["context_end"] = args.author_context
|
|
115
|
+
if args.plan_5h is not None:
|
|
116
|
+
author["plan_5h_end"] = args.plan_5h
|
|
117
|
+
path.write_text(json.dumps(run, indent=2, ensure_ascii=False))
|
|
118
|
+
print(f"run ended: {args.reason}")
|
|
119
|
+
return 0
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def cmd_outcome(args: argparse.Namespace) -> int:
|
|
123
|
+
_append(
|
|
124
|
+
Path(args.ledger) / "outcomes.jsonl",
|
|
125
|
+
{"at": time.time(), "id": args.id, "was": args.was, "note": args.note},
|
|
126
|
+
)
|
|
127
|
+
print(f"{args.id}: was {args.was}")
|
|
128
|
+
return 0
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def stats(ledger: Path) -> str:
|
|
132
|
+
run = json.loads((ledger / "run.json").read_text()) if (ledger / "run.json").exists() else {}
|
|
133
|
+
rounds = sorted(_jsonl(ledger / "rounds.jsonl"), key=lambda r: _round_key(r["tag"]))
|
|
134
|
+
rulings = _jsonl(ledger / "rulings.jsonl")
|
|
135
|
+
lines = [f"# Stats: {run.get('topic', ledger.name)}", ""]
|
|
136
|
+
author, reviewer = run.get("author", {}), run.get("reviewer", {})
|
|
137
|
+
reviewer_label = reviewer.get("model", "?")
|
|
138
|
+
if reviewer.get("cli"):
|
|
139
|
+
reviewer_label = f"{reviewer['cli']}/{reviewer_label}"
|
|
140
|
+
lines.append(
|
|
141
|
+
f"- Pair: author {author.get('model', '?')} ({author.get('effort', '?')}), "
|
|
142
|
+
f"reviewer {reviewer_label}; scenario {run.get('scenario', '?')}"
|
|
143
|
+
)
|
|
144
|
+
if run.get("started_at") and run.get("ended_at"):
|
|
145
|
+
lines.append(
|
|
146
|
+
f"- Wall time: {round((run['ended_at'] - run['started_at']) / 60, 1)} min; "
|
|
147
|
+
f"ended: {run.get('end_reason', '?')}"
|
|
148
|
+
)
|
|
149
|
+
if "tokens" in author:
|
|
150
|
+
lines.append(f"- Author tokens: {author['tokens']}")
|
|
151
|
+
if "context_start" in author and "context_end" in author:
|
|
152
|
+
lines.append(
|
|
153
|
+
f"- Author context: {author['context_start']} -> {author['context_end']} "
|
|
154
|
+
f"(+{author['context_end'] - author['context_start']})"
|
|
155
|
+
)
|
|
156
|
+
if "plan_5h_start" in author and "plan_5h_end" in author:
|
|
157
|
+
lines.append(f"- Plan 5-hour use: {author['plan_5h_start']}% -> {author['plan_5h_end']}%")
|
|
158
|
+
lines += [
|
|
159
|
+
"",
|
|
160
|
+
"| Round | CLI | Model | Gap min | Input | Cache read | Output | Uncached | New findings | Verdict |",
|
|
161
|
+
"| :--- | :--- | :--- | ---: | ---: | ---: | ---: | ---: | ---: | :--- |",
|
|
162
|
+
]
|
|
163
|
+
totals: Counter = Counter()
|
|
164
|
+
raised: dict[str, dict] = {}
|
|
165
|
+
for row in rounds:
|
|
166
|
+
usage = row.get("usage", {})
|
|
167
|
+
new = [f for f in row.get("findings", []) if f["id"] not in raised]
|
|
168
|
+
for finding in new:
|
|
169
|
+
raised[finding["id"]] = {**finding, "round": row["tag"]}
|
|
170
|
+
for key in ("input_tokens", "cache_read_tokens", "output_tokens", "total_tokens"):
|
|
171
|
+
totals[key] += usage.get(key, 0)
|
|
172
|
+
gap_str = row.get("gap_minutes") if row.get("gap_minutes") is not None else "-"
|
|
173
|
+
lines.append(
|
|
174
|
+
f"| {row['tag']} | {row.get('cli', '')} | {row.get('model', '')} | {gap_str} | "
|
|
175
|
+
f"{usage.get('input_tokens', 0)} | {usage.get('cache_read_tokens', 0)} | "
|
|
176
|
+
f"{usage.get('output_tokens', 0)} | {usage.get('total_tokens', 0)} | {len(new)} | "
|
|
177
|
+
f"{row.get('verdict', '')} |"
|
|
178
|
+
)
|
|
179
|
+
seen_input = totals["input_tokens"] + totals["cache_read_tokens"]
|
|
180
|
+
ratio = f"{round(100 * totals['cache_read_tokens'] / seen_input)}%" if seen_input else "-"
|
|
181
|
+
lines.append(
|
|
182
|
+
f"| **Total** | | | | {totals['input_tokens']} | {totals['cache_read_tokens']} | "
|
|
183
|
+
f"{totals['output_tokens']} | {totals['total_tokens']} | {len(raised)} | cache {ratio} |"
|
|
184
|
+
)
|
|
185
|
+
last: dict[str, dict] = {}
|
|
186
|
+
for row in rulings:
|
|
187
|
+
if last.get(row["id"], {}).get("by") == "owner" and row.get("by", "author") != "owner":
|
|
188
|
+
continue
|
|
189
|
+
last[row["id"]] = row
|
|
190
|
+
by_owner = sum(1 for r in last.values() if r.get("by") == "owner")
|
|
191
|
+
outcomes = {row["id"]: row["was"] for row in _jsonl(ledger / "outcomes.jsonl")}
|
|
192
|
+
severity = Counter(f["severity"] for f in raised.values())
|
|
193
|
+
ruling = Counter(r["ruling"] for r in last.values())
|
|
194
|
+
reason = Counter(r["reason"] for r in last.values() if r["reason"])
|
|
195
|
+
unruled = sorted(set(raised) - set(last), key=lambda i: int(i[2:]))
|
|
196
|
+
owner_qs: set[str] = set()
|
|
197
|
+
for path in ledger.glob("p*-r*-reply.md"):
|
|
198
|
+
owner_qs |= set(OWNER_Q.findall(path.read_text()))
|
|
199
|
+
lines += [
|
|
200
|
+
"",
|
|
201
|
+
f"- Findings: {len(raised)} ({', '.join(f'{k} {v}' for k, v in sorted(severity.items())) or 'none'})",
|
|
202
|
+
f"- Rulings (last per finding): {', '.join(f'{k} {v}' for k, v in sorted(ruling.items())) or 'none'}",
|
|
203
|
+
f"- Reasons: {', '.join(f'{k} {v}' for k, v in sorted(reason.items())) or 'none'}",
|
|
204
|
+
f"- Rulings set by the owner: {by_owner}",
|
|
205
|
+
f"- Later outcomes: right {sum(1 for v in outcomes.values() if v == 'right')}, "
|
|
206
|
+
f"wrong {sum(1 for v in outcomes.values() if v == 'wrong')}",
|
|
207
|
+
f"- Owner questions raised: {len(owner_qs)}",
|
|
208
|
+
f"- Findings with no ruling: {', '.join(unruled) or 'none'}",
|
|
209
|
+
]
|
|
210
|
+
return "\n".join(lines) + "\n"
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def transcript(ledger: Path) -> str:
|
|
214
|
+
tags = sorted({p.name.split("-prompt")[0] for p in ledger.glob("p*-r*-prompt.md")}, key=_round_key)
|
|
215
|
+
parts = []
|
|
216
|
+
for tag in tags:
|
|
217
|
+
parts.append(f"# {tag}: author -> reviewer\n\n" + (ledger / f"{tag}-prompt.md").read_text())
|
|
218
|
+
reply = ledger / f"{tag}-reply.md"
|
|
219
|
+
if reply.exists():
|
|
220
|
+
parts.append(f"# {tag}: reviewer -> author\n\n" + reply.read_text())
|
|
221
|
+
return "\n\n---\n\n".join(parts) + "\n"
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def cmd_stats(args: argparse.Namespace) -> int:
|
|
225
|
+
ledger = Path(args.ledger)
|
|
226
|
+
text = stats(ledger)
|
|
227
|
+
(ledger / "stats.md").write_text(text)
|
|
228
|
+
(ledger / "transcript.md").write_text(transcript(ledger))
|
|
229
|
+
print(text)
|
|
230
|
+
return 0
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def main() -> int:
|
|
234
|
+
parser = argparse.ArgumentParser()
|
|
235
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
236
|
+
init = sub.add_parser("init")
|
|
237
|
+
init.add_argument("ledger")
|
|
238
|
+
init.add_argument("--topic", required=True)
|
|
239
|
+
init.add_argument("--scenario", default="")
|
|
240
|
+
init.add_argument("--author-model", required=True)
|
|
241
|
+
init.add_argument("--author-effort", default="")
|
|
242
|
+
init.add_argument("--reviewer-cli", default="")
|
|
243
|
+
init.add_argument("--reviewer-model", required=True)
|
|
244
|
+
init.add_argument("--budget", type=int, default=500_000)
|
|
245
|
+
init.add_argument("--rounds", type=int, default=5)
|
|
246
|
+
init.add_argument("--phase", default="both", choices=("both", "discuss", "spec"))
|
|
247
|
+
init.add_argument("--repo", action="append", default=[])
|
|
248
|
+
init.add_argument("--author-context", type=int, help="the author session's context tokens at the start")
|
|
249
|
+
init.add_argument("--plan-5h", type=int, help="the plan's 5-hour use in percent at the start")
|
|
250
|
+
init.set_defaults(func=cmd_init)
|
|
251
|
+
|
|
252
|
+
rule = sub.add_parser("rule")
|
|
253
|
+
rule.add_argument("ledger")
|
|
254
|
+
rule.add_argument("round")
|
|
255
|
+
rule.add_argument("id")
|
|
256
|
+
rule.add_argument("--ruling", required=True, choices=RULINGS)
|
|
257
|
+
rule.add_argument("--reason", choices=REASONS)
|
|
258
|
+
rule.add_argument("--note", default="")
|
|
259
|
+
rule.add_argument("--by", default="author", choices=("author", "owner"))
|
|
260
|
+
rule.set_defaults(func=cmd_rule)
|
|
261
|
+
|
|
262
|
+
end = sub.add_parser("end")
|
|
263
|
+
end.add_argument("ledger")
|
|
264
|
+
end.add_argument("--reason", required=True, choices=("done", "cap", "budget", "error", "stalemate"))
|
|
265
|
+
end.add_argument("--author-tokens", type=int, help="the author's tokens when known (a subagent's total)")
|
|
266
|
+
end.add_argument("--author-context", type=int, help="the author session's context tokens at the end")
|
|
267
|
+
end.add_argument("--plan-5h", type=int)
|
|
268
|
+
end.set_defaults(func=cmd_end)
|
|
269
|
+
|
|
270
|
+
out = sub.add_parser("outcome")
|
|
271
|
+
out.add_argument("ledger")
|
|
272
|
+
out.add_argument("id")
|
|
273
|
+
out.add_argument("--was", required=True, choices=("right", "wrong"))
|
|
274
|
+
out.add_argument("--note", default="")
|
|
275
|
+
out.set_defaults(func=cmd_outcome)
|
|
276
|
+
|
|
277
|
+
stat = sub.add_parser("stats")
|
|
278
|
+
stat.add_argument("ledger")
|
|
279
|
+
stat.set_defaults(func=cmd_stats)
|
|
280
|
+
|
|
281
|
+
args = parser.parse_args()
|
|
282
|
+
return args.func(args)
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
if __name__ == "__main__":
|
|
286
|
+
sys.exit(main())
|