Merge t3/close-rebuild-seam-gaps: grouped help carries workers note/only; routing adjustments, notes, limits, host-native and with_commit all kept. done / next: fix 1 (rule map)
This commit is contained in:
commit
6cff3a0667
42 files changed
+777
-420
No files matched your search
+10
-14
@@ -30,9 +30,8 @@ with a weaker check or a smaller result.
|
||||
|
||||
Time to delivery is measured, not guessed. Each time the end-of-turn gate lets a turn end it records one
|
||||
delivery row: the time since the last message the human actually typed (hook feedback and tool results do not
|
||||
count), how many times the gate sent the agent back, and how long the checks ran. `sisi status` shows the median
|
||||
and 90th percentile for the last 7 days against the 7 days before, the share spent in checks, and the five
|
||||
slowest checks; `sisi status` shows the 7-day median.
|
||||
count), how many times the gate sent the agent back, and how long the checks ran. `sisi status` shows the
|
||||
median and 90th percentile by project, risk profile, model and policy version.
|
||||
|
||||
A learned change that speeds things up but fails a check is rejected. A learned change that keeps every check
|
||||
passing but makes median delivery slower is flagged for reversal. (Built: `sisi cycle status` flags a cycle
|
||||
@@ -126,12 +125,10 @@ runs alone. Results are reported in contract order either way.
|
||||
|
||||
**Enforcement.** The tool's end-of-turn hook calls `sisi verify`. If a contract exists and a check fails or was
|
||||
not run, the agent is sent back with the failures and cannot report the work as done. If no contract exists and
|
||||
the change is larger than a small threshold, the agent is sent back to write one; a change that size
|
||||
with a contract whose design section is missing or fails validation is sent back to fill it. Small
|
||||
the change is larger than its risk profile allows without one, the agent is sent back to write one. Small
|
||||
edits and subagents pass untouched, and the same send-back budget bounds every send-back, so no
|
||||
session is trapped. Request-time delivery hands the standing principles and the design instruction
|
||||
over when a request reads as design or build work, and `sisi design` prints them before a contract
|
||||
exists.
|
||||
session is trapped. Request-time delivery hands the standing principles over when a request reads as
|
||||
design or build work.
|
||||
Claude Code supports a blocking stop hook. The equivalent in OpenCode, Codex and Muse is not verified; where it
|
||||
does not exist, verification is meant to run at the next session start and failures to be reported then (that
|
||||
fallback is a design intention, not built).
|
||||
@@ -316,18 +313,17 @@ Built and covered by tests:
|
||||
- The rulebook (`canon/core.md`), the risk table, the verifier library and the recipes.
|
||||
- Retrospectives and lessons (`sisi retro`, `sisi lessons`), `sisi learn` live at once, time to delivery
|
||||
(`sisi status`).
|
||||
- Choosing the approach as a checked step: the contract design section, `sisi design`, the gate's
|
||||
design send-back on large changes, and request-time delivery of the standing principles for design
|
||||
or build requests. The rulebook's first rule states it and `sisi rule` reports its enforcement.
|
||||
- Choosing the approach as a checked step: the contract's `approach` and the request-time delivery of the
|
||||
standing principles for design or build requests. `sisi rule` reports the rulebook's enforcement.
|
||||
- Patterns: each retro names the general failure of thinking behind the incident; patterns are
|
||||
first-class, merged in rounds, and promoted into the rulebook as strategic behaviours past a
|
||||
threshold; the digest and `sisi improve` show them first. Three tiers (`core`, `user`, `project`)
|
||||
threshold; `sisi status --learning` shows them first. Three tiers (`core`, `user`, `project`)
|
||||
replace the two-way scope, with older universal items tiered by the next round, and `sisi promote`
|
||||
listing, writing (from the clone) or exporting core items.
|
||||
- The lesson loop: immediate effects in the overlay (field notes, draft recipes, learned notes, `sisi backlog`),
|
||||
- The lesson loop: immediate effects in the overlay (field notes, draft recipes, learned notes),
|
||||
moment-of-use delivery with recorded showings, per-lesson measurement, the strength ladder with enforced
|
||||
checks, `sisi cycle` (due counter, brief, validated apply under lock and base version, exact revert, status
|
||||
with worse-cycle flagging) and `sisi improve`.
|
||||
with worse-cycle flagging).
|
||||
- Personal data, the overlay, update, export and import, releases and rollback, promotion of a personal item
|
||||
into the product.
|
||||
- The data layer for learning: harvest of Claude Code transcripts, task set, ground truth, escape candidates,
|
||||
|
||||
@@ -173,6 +173,5 @@ learnings in scope that target that entry.
|
||||
- `cycle.risk_patterns(cwd)` — the learned risk patterns that apply in a project (`risk.load_patterns`).
|
||||
- `cycle.routing_adjustments(project)` — the learned routing adjustments that apply in a project.
|
||||
- `cycle.due_notice()` — the session-start lines (cycle due, decision waiting).
|
||||
- `retro.satisfied(repo, since, fp)` and `retro.TEMPLATE` — what the gate asks.
|
||||
- `learning.delivery_text(project, query, targets=())` — what the prompt hook may add.
|
||||
- `evaluate.validate_command(repo, before, after, cmd)` — the replay.
|
||||
@@ -11,6 +11,8 @@ applies_to: A new capability in a product that already exists and already has us
|
||||
- Each requirement has an acceptance check, and the checks for the core logic are strong (property, differential or fuzz checks where the input space is broad).
|
||||
- Empty, large, invalid and repeated use of the new capability behave sensibly, and existing data, settings and workflows still work with it.
|
||||
- The capability is discoverable and usable in the product's own terms (labels, help, errors), with loading, empty and error states where it has a surface.
|
||||
- The first usable increment is named, the work is ordered to reach it early, and every status update gives its estimated time, labelled as an estimate.
|
||||
- Where the design depends on a heuristic, classifier or matcher being right most of the time, a throwaway version was first scored on labels a different worker wrote, and the measured ceiling and what stands behind the heuristic are in the design.
|
||||
|
||||
## Checks
|
||||
- Requirements: `requirement-to-check-map` (completeness), `acceptance-examples` (intent), rung 3; every requirement maps to a check or a recorded deferral.
|
||||
@@ -18,6 +20,7 @@ applies_to: A new capability in a product that already exists and already has us
|
||||
- Nothing else broke: `baseline-before-change`, `characterization-tests` (regression), rung 3; invariants from before the first edit.
|
||||
- Real surface: `e2e-playwright` (real-world) for a web capability, `cli-transcript-tests` for a command, rung 3.
|
||||
- Hostile and odd input: `hostile-input-from-schema` (many-inputs), rung 2, for any new parser, import or boundary.
|
||||
- Tests are stable: `repeat-under-parallel-load` (test-quality), rung 3, for each new test module.
|
||||
- Finished cleanly: `no-stubs-scan`, `single-gate-command` (completeness), rung 3.
|
||||
|
||||
## Common false finishes
|
||||
|
||||
@@ -12,11 +12,14 @@ applies_to: Turning a one-line or short description (an app, a service, a tool)
|
||||
- It is safe: dependencies audited, secrets handled, trust boundaries modelled, data stored survives crashes and upgrades.
|
||||
- One command defines done; documentation says how to run and verify it; a release path exists.
|
||||
- The owner walked it and accepted it, and what was assumed is reported.
|
||||
- The first usable increment is named, the work is ordered to reach it early, and every status update gives its estimated time, labelled as an estimate.
|
||||
- Where the design depends on a heuristic, classifier or matcher being right most of the time, a throwaway version was first scored on labels a different worker wrote, and the measured ceiling and what stands behind the heuristic are in the design.
|
||||
|
||||
## Checks
|
||||
- What to build: `acceptance-examples`, `requirement-to-check-map` (completeness), `spec-traceability`; design: `tlaplus` or `quint` for state machines (design).
|
||||
- Logic: `lean4-proofs`, `kani` or `proptest` (prove, many-inputs), rung 1 to 2; `stateful-model-test`, `differential-reference`, `round-trip`.
|
||||
- Tests are real: `cargo-mutants` or the language's mutation tool, `vacuity-check`, `assertion-strength-review` (test-quality).
|
||||
- Tests are stable: `repeat-under-parallel-load` (test-quality), rung 3.
|
||||
- Real world: `e2e-playwright` or `cli-transcript-tests`, `clean-clone-build`, `packaging-install-upgrade`, `cross-platform-matrix`.
|
||||
- Safety: `rust-lints-strict`, `dependency-audit-rust`, `secret-scanning`, `threat-model-checklist`, `licence-notices`.
|
||||
- Done: `single-gate-command`, `no-stubs-scan`, `check-tiering`, `release-gate`; the human: `owner-acceptance-runbook` (intent), rung 6.
|
||||
|
||||
+1
-5
@@ -7,7 +7,7 @@ whose config folder does not exist is skipped and reported, never an error. Only
|
||||
from the tool's own documentation, `--help`, installed files or a local spike are wired here (see
|
||||
docs/harnesses.md); anything unconfirmed is reported in doctor, not guessed into a config.
|
||||
"""
|
||||
import copy, difflib, hashlib, json, os, shlex
|
||||
import difflib, hashlib, json, os
|
||||
|
||||
from . import hookjson, paths, store, wiring
|
||||
|
||||
@@ -515,10 +515,6 @@ class Adapter:
|
||||
"detail": "not wired", "action": None}
|
||||
|
||||
|
||||
def _st(a, rulebook, tick, wired, detail, action=None):
|
||||
return {"tool": a.name, "detected": True, "rulebook": rulebook, "tick": tick,
|
||||
"enforcement": a.enforcement, "via": a.via, "wired": wired, "detail": detail, "action": action}
|
||||
|
||||
|
||||
class Codex(Adapter):
|
||||
name, enforcement, via = "codex", "blocks", "Stop"
|
||||
|
||||
+16
-3
@@ -103,6 +103,11 @@ def missing(profile, c, project, results=None, errors=None, deep_state=None, now
|
||||
absent = True
|
||||
else:
|
||||
absent = False
|
||||
rk = c.get("risk") if isinstance(c.get("risk"), dict) else {}
|
||||
if not absent and rk.get("profile") not in C.RISK_PROFILES:
|
||||
out.append(("a declared risk profile (your own judgement of the change)",
|
||||
'"risk": {"profile": %s}; `sisi risk` shows the floor' % "|".join(C.RISK_PROFILES)))
|
||||
errors = [e for e in errors or [] if "risk.profile" not in e and not e.startswith("risk must be")]
|
||||
if errors:
|
||||
shown = "; ".join(errors[:3]) + ("; and %d more" % (len(errors) - 3) if len(errors) > 3 else "")
|
||||
out.append(("a valid contract: %s" % shown, "fix it, then `sisi contract check`"))
|
||||
@@ -160,16 +165,24 @@ def fit(lines, limit=MAX_LINES):
|
||||
% (len(flat) - limit + 1)])
|
||||
|
||||
|
||||
def shown_lines(r, evidence_lines, tail_lines):
|
||||
"""The lines to show for one result: the evidence that identifies the failure first, then the last
|
||||
lines of its output that the evidence did not already include."""
|
||||
ev = [ln for ln in str(r.get("evidence") or "").splitlines() if ln.strip()][:evidence_lines]
|
||||
tail = [ln for ln in str(r.get("tail") or "").splitlines() if ln.strip() and ln not in ev][-tail_lines:]
|
||||
return ev + tail
|
||||
|
||||
|
||||
def failure_lines(results, per_check=4, checks=4):
|
||||
"""A short report of the blocking results: id, status, and the last lines of what they printed."""
|
||||
"""A short report of the blocking results: id, status, the lines that identify each failure, then
|
||||
the last lines of what it printed."""
|
||||
from . import verify as V
|
||||
out = []
|
||||
bad = V.blocking(results)
|
||||
for r in bad[:checks]:
|
||||
head = "- %s [%s%s]" % (r["id"], r["status"], (": " + r["reason"]) if r.get("reason") else "")
|
||||
out.append(head)
|
||||
tail = [ln for ln in str(r.get("tail") or "").splitlines() if ln.strip()][-per_check:]
|
||||
out += [" " + ln[:200] for ln in tail]
|
||||
out += [" " + ln[:200] for ln in shown_lines(r, per_check, 1)]
|
||||
if len(bad) > checks:
|
||||
out.append("- and %d more failing" % (len(bad) - checks))
|
||||
return out
|
||||
@@ -37,15 +37,21 @@ def template():
|
||||
"",
|
||||
"## Acceptance",
|
||||
"[How the result will be judged: the check that decides accepted or rejected.]",
|
||||
"[Every size, speed or brevity requirement is a number with the command that measures it.]",
|
||||
"[If the worker writes data for another module to read, name that reader and require one end-to-end test that shows the reader's behaviour changes.]",
|
||||
"[If you ask for a classifier, matcher or heuristic and a labelled set, the labels come from a different worker, or a held-out part is written first.]",
|
||||
"",
|
||||
"## Deliverables and report format",
|
||||
"[What to send back, and in what shape: a short report, what changed, the check run.]",
|
||||
"[For numbered items: a commit after each, with a one-line \"done / next\" note in the message.]",
|
||||
"",
|
||||
"## Files you may change",
|
||||
"[The files or folders the worker may change; everything else is read-only.]",
|
||||
"",
|
||||
"## Verification",
|
||||
"[The check the worker must run before reporting, and what output to include.]",
|
||||
"[For an approval gate, trust check or validation step, list the abuse cases the tests must cover: omit the field that triggers the gate, forge the field that marks trust, make the failing-before step fail for an unrelated reason.]",
|
||||
"[New test modules are run about 30 times, with copies in parallel, before the report.]",
|
||||
"",
|
||||
"## Budget and escalation",
|
||||
"[Time or cost budget; when to stop and escalate instead of guessing.]",
|
||||
@@ -114,3 +120,54 @@ def missing_required(text):
|
||||
found = sections(text)
|
||||
return [title for key, title, _n, _r in PARTS
|
||||
if key in _REQUIRED and (key not in found or not _filled(found[key]))]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- advice (never blocks)
|
||||
|
||||
_VAGUE = re.compile(r"\b(short|fast|small|brief|concise|quick)\b", re.I)
|
||||
_GATE = re.compile(r"\b(approv\w*|trust\w*|validat\w*|untrusted)\b", re.I)
|
||||
_ABUSE = re.compile(r"\b(abuse|misuse)\b", re.I)
|
||||
_TESTS = re.compile(r"\btests?\b", re.I)
|
||||
_REPEAT = re.compile(r"\brepeat|\b\d+ times\b|in parallel", re.I)
|
||||
_FOR_OTHERS = re.compile(r"(for|that) (other|another|downstream) modules? (to|will|that)? ?(read|consume|use)|"
|
||||
r"(other|another) modules? (reads?|will read|consumes?)", re.I)
|
||||
_READER = re.compile(r"\b(read by|reader is|reader:|the reader|consumer is|consumer:)\s+[`\w./]+", re.I)
|
||||
_HEURISTIC = re.compile(r"\b(classifier|matcher|heuristic)\b", re.I)
|
||||
_LABELS = re.compile(r"\blabell?ed\b|\blabels\b|ground truth", re.I)
|
||||
_LABELS_INDEPENDENT = re.compile(r"different worker|another worker|other worker|held[- ]?out|blind", re.I)
|
||||
_NUMBERED = re.compile(r"^\s*(\d+[.)]|item \d+)\s", re.I | re.M)
|
||||
_COMMIT_PER_ITEM = re.compile(r"commit (after|per|for) each|done ?/ ?next", re.I)
|
||||
|
||||
|
||||
def _written(text):
|
||||
"""The lines the brief's author wrote: the template's bracketed guidance does not count."""
|
||||
return [ln for ln in (text or "").splitlines()
|
||||
if not (ln.strip().startswith("[") and ln.strip().endswith("]"))]
|
||||
|
||||
|
||||
def advice(text):
|
||||
"""Short pieces of advice about a brief, each with its reason. Advice never blocks a delegation."""
|
||||
lines = _written(text)
|
||||
body = "\n".join(lines)
|
||||
acceptance = sections("\n".join(lines)).get("acceptance", [])
|
||||
out = []
|
||||
vague = sorted({m.group(1).lower() for ln in acceptance if not re.search(r"\d", ln) for m in _VAGUE.finditer(ln)})
|
||||
if vague:
|
||||
out.append("Acceptance says %s with no number: state each size, speed or brevity limit as a number "
|
||||
"and the command that measures it." % "/".join(vague))
|
||||
if _GATE.search(body) and not _ABUSE.search(body):
|
||||
out.append("It mentions approval, trust or validation but lists no abuse cases: name them (omit the "
|
||||
"trigger field, forge the trust mark, fail the before-step for an unrelated reason).")
|
||||
if _TESTS.search(body) and not _REPEAT.search(body):
|
||||
out.append("It asks for tests but not a repeat run: run new test modules about 30 times, with copies "
|
||||
"in parallel, before reporting (exposes time and order dependence).")
|
||||
if _FOR_OTHERS.search(body) and not _READER.search(body):
|
||||
out.append("The worker writes data for other modules to read, but no reader is named: name it and ask "
|
||||
"for one end-to-end test showing its behaviour changes.")
|
||||
if _HEURISTIC.search(body) and _LABELS.search(body) and not _LABELS_INDEPENDENT.search(body):
|
||||
out.append("It asks for a classifier, matcher or heuristic and a labelled set from the same worker: the "
|
||||
"labels should come from a different worker, or a held-out part be written first.")
|
||||
if len(_NUMBERED.findall(body)) >= 2 and not _COMMIT_PER_ITEM.search(body):
|
||||
out.append("It has numbered items but no commit per item: ask for a commit after each, with a "
|
||||
"\"done / next\" note, so an interruption loses at most one.")
|
||||
return out
|
||||
+29
-120
@@ -1,109 +1,6 @@
|
||||
"""Command dispatch. Heavy modules are imported lazily so hooks (tick, gate) stay fast."""
|
||||
import json, os, sys
|
||||
|
||||
HELP = """sisi is still improving
|
||||
|
||||
A shared rulebook and enforced definitions of done for every AI coding CLI.
|
||||
|
||||
sisi contract init [--goal TEXT] start a work unit: create .sisi/contract.json here (refuses while one is open)
|
||||
sisi contract check validate the contract (vacuous checks are refused)
|
||||
sisi contract waive [--check ID] "<reason>"
|
||||
record a deviation: a waived check does not pass; the unit closes as a deviation and the report must say so
|
||||
sisi contract trust | untrust allow / stop allowing this project's contract to run commands
|
||||
sisi unit close [--abandon "<reason>"]
|
||||
archive the unit to .sisi/units/<id>.json with its scorecard; --abandon records why it stopped
|
||||
sisi unit pause "<what it waits for>"
|
||||
record a wait; the turn may end with no demands
|
||||
sisi unit show [ID] | list print the open unit or an archived record; list this project's units
|
||||
sisi verify [--json] run the selected fast checks (five statuses; nothing unrun passes); exit 0 ok, 1 failure, 2 no contract, 3 untrusted
|
||||
sisi verify --deep [--background] run the deep (long) checks; --background detaches and returns at once
|
||||
sisi verify --all | --state run every check in both tiers; print only the deep-check state (with --json)
|
||||
sisi gate [--tool NAME] end-of-turn hook (reads hook JSON on stdin; NAME selects the tool's hook shape)
|
||||
sisi tick [--tool NAME] session-start hook
|
||||
sisi prompt [--tool NAME] prompt-submission hook: prints the matching recipe and lessons for the human's request as added context (silent when nothing strictly matches); `sisi prompt "<request>"` tries it by hand
|
||||
sisi rule [N|ID] the effective rules and how each is enforced; with N or ID: one rule in full (reasons, history, lessons behind it, how it is enforced)
|
||||
sisi watch [--before|--after] before/after shell-tool hook: measures whether the command changed the project
|
||||
sisi install [--dry-run] | uninstall | doctor
|
||||
wire sisi into the tools (by reference), undo, inspect; --dry-run only prints what would change
|
||||
sisi release [--deep] run the source's checks, then make the stable copy the tools run (see docs/developing.md)
|
||||
sisi rollback switch the stable copy back to the previous release
|
||||
sisi promote [ID|L-NNNN] [--apply] | --export [PATH]
|
||||
no ID: list items not yet in the product (learnings that change
|
||||
sisi itself, or earned organization scope); an ID scrubs a
|
||||
personal overlay item into the source folder and drops the
|
||||
personal copy once the product contains it (dry run unless
|
||||
--apply); L-NNNN promotes the rule or recipe a learning was
|
||||
folded into, from the clone; --export writes a contribution file
|
||||
(universal text only; nothing is sent anywhere)
|
||||
sisi update fast-forward the product clone, then back up, migrate and rebuild personal data
|
||||
sisi export [PATH] | import PATH one tar.gz of personal data, results and session records; restore it
|
||||
sisi overlay list|diff|add-rule|replace-rule|disable-rule|enable-rule|add-verifier|...|revert COMMIT
|
||||
learned changes to rules, verifiers and recipes; each one a commit in your personal repo
|
||||
sisi retro print the unit's record and what stands out in it
|
||||
sisi retro --finding F --cause C --impact value|correctness|time|cost|attention --disposition promote|record|drop [--same-as ID | --new] [--target ID]
|
||||
record one finding; promote also needs --change, --mechanism,
|
||||
--expect and --validate; record needs --limits; drop needs --why-not;
|
||||
a match in scope is printed and attached as a recurrence (--new records
|
||||
a learning of its own); --target names the rule or recipe it concerns
|
||||
sisi retro --adopt ID a parent adopts a subagent's candidate learning, by id
|
||||
sisi lessons [--json] | show ID the learning records and their statuses
|
||||
sisi cycle [due|apply FILE|check FILE|revert [ID]|help]
|
||||
turn proposed learnings into mechanisms (no scheduler:
|
||||
due-ness is a counter); apply validates and replays before
|
||||
promoting; help prints the cycle file format
|
||||
sisi approve [ID --yes|--no] list, in full, the consequential changes waiting for the owner; decide one
|
||||
(in a terminal: an agent's --yes without one is refused)
|
||||
sisi learn [--scope user|project] TEXT
|
||||
record an owner statement; it takes effect at once and
|
||||
`sisi oracle` prints it. Scope for other learnings is
|
||||
earned by evidence, never claimed
|
||||
sisi learn --withdraw ID --reason WHY
|
||||
take a statement recorded by mistake out of delivery (kept in history)
|
||||
sisi risk [--json] risk floor for the working-tree change, with reasons and
|
||||
what that profile requires
|
||||
sisi handover [--all] | done ID --where PATH [--quote FRAGMENT]
|
||||
project-scope learnings waiting to be filed in this project's own docs or
|
||||
work list; done confirms one is filed (the named file must contain
|
||||
its key text) and removes it from the list
|
||||
sisi oracle print what the human wants: the standing principles from
|
||||
`sisi learn`, live at once (project-scoped ones only in their project)
|
||||
sisi status [--json] [--learning] recent units with their scorecards, then trends by project, risk profile, model and policy version (median and p95; no single score)
|
||||
sisi verifiers [WORDS] [--lang L] [--kind K] [--rung N] [--section S] [--installed] [--json]
|
||||
list ways to know work is correct, by section
|
||||
sisi verifiers show ID [--trace] one entry in full, and whether its tool is installed here; --trace also prints where each folded lesson lives in it
|
||||
sisi verifiers for "<claim>" best-matching verifiers for a claim or piece of work
|
||||
sisi verifiers doctor | lint which tools are installed; validate the library
|
||||
sisi done [ID] [--trace] recipes: which checks make a kind of work done; --trace also prints where each folded lesson lives in the recipe
|
||||
sisi done for "<work>" best-matching recipe
|
||||
sisi workers [--refresh] the agent tools and models found here, what is usable now and why not, allowance and price where known, delegations waiting for a judgement, and the judged record as three tables
|
||||
sisi workers fact W --price N|--score N --source S record a price (per million tokens) or benchmark standing (0-100), with its source and date
|
||||
sisi workers avoid|prefer PATTERN --why TEXT your own routing constraints, honoured by `sisi route`
|
||||
sisi workers only PROVIDER PATTERN... --why TEXT | --remove make only the matching models of that provider routable
|
||||
sisi workers note PATTERN "TEXT" --why SOURCE | --remove a standing fact about workers matching PATTERN, shown with route results
|
||||
sisi workers down W --reason limit|auth|missing|error [--until DATE] | up W mark a worker unavailable / available again
|
||||
sisi workers import FILE merge another ledger file into the delegation ledger (row counts printed; safe to repeat)
|
||||
sisi route --kind K --difficulty N [--review-of W] [--explain]
|
||||
the most affordable usable worker for this kind and difficulty, and the mechanism to start it with (host subagents, host cross-provider delegation, or sisi delegate); --explain says why
|
||||
sisi delegate brief | check FILE | guide the delegation-contract template (eight parts); which parts a brief lacks; the orchestration playbook
|
||||
sisi delegate --kind K --difficulty N --brief FILE [--worker W] [--review-of W] [--cwd DIR]
|
||||
run one brief on the chosen worker unattended; prints only its final report, the transcript path, and the judge command; a brief without outcome, acceptance or files it may change is refused
|
||||
sisi delegate judge ID --outcome accepted|rejected --check none|diffstat|tests|read|review [--minutes N]
|
||||
record your judgement of a delegation run, so the next choice learns from it; judge work run any other way with --worker W --type K --difficulty N instead of ID
|
||||
sisi delegate amend ID | recent [-n N] [--project P] mark a judged delegation that later proved wrong; list recent judgements to find an id
|
||||
sisi eval list|add|run|compare|shadow|judge|status|import
|
||||
the evaluation harness: benchmark cases from real work, isolated
|
||||
replay, policy comparison and independent judging (see docs/evaluation.md);
|
||||
`sisi eval` alone prints status; run without --tasks replays check cases only
|
||||
sisi version | --version print the product version (the VERSION file in the product folder)
|
||||
sisi help this text
|
||||
|
||||
Three places: the product (this clone, never written at run time), your personal data
|
||||
(~/.local/share/sisi, its own git repository), and scratch (~/.local/state/sisi).
|
||||
Environment: SISI_HOME (stands in for the home directory), SISI_DATA (personal data folder),
|
||||
SISI_STATE (scratch dir), SISI_LIB (where stable releases live, default ~/.local/lib/sisi), SISI_TOOL (name recorded with results), SISI_VERIFIERS and SISI_DONE
|
||||
(library directories, default verifiers/ and done/ in the product).
|
||||
"""
|
||||
|
||||
|
||||
def _pop_opt(args, name):
|
||||
"""Remove `name VALUE` from args, return value or None."""
|
||||
@@ -145,7 +42,7 @@ def cmd_contract(args):
|
||||
except Exception as e:
|
||||
store.log_error("contract-init-archive", e)
|
||||
os.makedirs(os.path.dirname(p), exist_ok=True)
|
||||
skel = C.skeleton(goal)
|
||||
skel = C.skeleton(goal, project)
|
||||
from . import unit as _U
|
||||
skel["id"] = _U.fresh_id(skel["id"], project)
|
||||
skel["base_head"] = gitutil.head(project)
|
||||
@@ -287,12 +184,29 @@ def cmd_personal(cmd, args):
|
||||
return 64
|
||||
|
||||
|
||||
def cmd_help(args):
|
||||
"""`sisi help` (four groups, one line per command) or `sisi help COMMAND` (that command in full)."""
|
||||
from . import helptext
|
||||
if not args:
|
||||
print(helptext.short(), end="")
|
||||
return 0
|
||||
text = helptext.long(args[0])
|
||||
if text is None:
|
||||
print("sisi: no command %r (try `sisi help`)" % args[0], file=sys.stderr)
|
||||
return 64
|
||||
print(text, end="" if text.endswith("\n") else "\n")
|
||||
return 0
|
||||
|
||||
|
||||
def main(argv):
|
||||
args = list(argv)
|
||||
t = _pop_opt(args, "--tool")
|
||||
if t:
|
||||
os.environ["SISI_TOOL"] = t
|
||||
cmd = args.pop(0) if args else "help"
|
||||
if args[:1] in (["--help"], ["-h"]) and cmd not in ("help", "-h", "--help"):
|
||||
args = [cmd]
|
||||
cmd = "help"
|
||||
if cmd == "gate":
|
||||
if t and t != "claude-code":
|
||||
from . import hookio
|
||||
@@ -334,8 +248,7 @@ def main(argv):
|
||||
return 1
|
||||
return 0
|
||||
if cmd in ("help", "-h", "--help"):
|
||||
print(HELP, end="")
|
||||
return 0
|
||||
return cmd_help(args)
|
||||
if cmd == "contract":
|
||||
return cmd_contract(args)
|
||||
if cmd == "verify":
|
||||
@@ -411,17 +324,13 @@ def main(argv):
|
||||
|
||||
|
||||
def _learn_cli(cmd, args):
|
||||
"""Data-layer commands (harvest, tasks, ...) live in learn_cli. The CLI works without it, even if it is broken."""
|
||||
try:
|
||||
import argparse
|
||||
from . import learn_cli
|
||||
ap = argparse.ArgumentParser(prog="sisi")
|
||||
sub = ap.add_subparsers(dest="cmd")
|
||||
learn_cli.register(sub)
|
||||
if cmd not in sub.choices:
|
||||
return None
|
||||
ns = ap.parse_args([cmd] + args)
|
||||
return ns.func(ns)
|
||||
except (ImportError, AttributeError, TypeError) as e:
|
||||
print("sisi: the %r command is unavailable (%s)" % (cmd, e), file=sys.stderr)
|
||||
return 70
|
||||
"""Data-layer commands (harvest, tasks, ...) live in learn_cli; None when `cmd` is not one of them."""
|
||||
import argparse
|
||||
from . import learn_cli
|
||||
ap = argparse.ArgumentParser(prog="sisi")
|
||||
sub = ap.add_subparsers(dest="cmd")
|
||||
learn_cli.register(sub)
|
||||
if cmd not in sub.choices:
|
||||
return None
|
||||
ns = ap.parse_args([cmd] + args)
|
||||
return ns.func(ns)
|
||||
+17
-14
@@ -39,19 +39,24 @@ def is_unedited_skeleton(c):
|
||||
REQ_KINDS = ("explicit", "implied", "contextual", "anticipated", "experiential")
|
||||
REQ_DECISIONS = ("now", "architect", "defer", "ignore")
|
||||
RISK_PROFILES = ("trivial", "isolated", "logic", "integration", "data", "critical", "release")
|
||||
RISK_HINT = ("one of %s, your own judgement of the change; `sisi risk` shows the floor worked out from paths"
|
||||
% ", ".join(RISK_PROFILES))
|
||||
UNIT_STATUSES = ("open", "paused", "closed")
|
||||
|
||||
|
||||
def skeleton(goal=None, cwd=None):
|
||||
name = re.sub(r"[^a-z0-9]+", "-", os.path.basename(os.path.abspath(cwd or os.getcwd())).lower()).strip("-")
|
||||
from . import store as _store
|
||||
"""A new contract. `risk.profile` starts at the floor of the current change; the agent judges it from there."""
|
||||
cwd = cwd or os.getcwd()
|
||||
name = re.sub(r"[^a-z0-9]+", "-", os.path.basename(os.path.abspath(cwd)).lower()).strip("-")
|
||||
from . import store as _store, risk as _risk
|
||||
floor = _risk.floor_for_working_tree(cwd)[0]
|
||||
return {
|
||||
"id": name or "work",
|
||||
"parent": None,
|
||||
"goal": goal or "TODO: one sentence describing the outcome",
|
||||
"scope": {"in": [], "out": []},
|
||||
"requirements": [],
|
||||
"risk": {},
|
||||
"risk": {"profile": floor},
|
||||
"checks": [{
|
||||
"id": "c1",
|
||||
"claim": "PLACEHOLDER (fast tier, runs at the end of every turn, 60 s at most): replace with what this check shows to be true",
|
||||
@@ -185,7 +190,6 @@ _PRINT_WORDS = {"echo", "printf"}
|
||||
_SHELLS = {"sh", "bash", "dash", "zsh", "/bin/sh", "/bin/bash", "/usr/bin/env"}
|
||||
_WRAPPERS = {"env", "command", "exec", "time", "nohup", "builtin"}
|
||||
_TESTERS = {"test", "["}
|
||||
_OPS = {"&&", "||", ";", "|", "&"}
|
||||
|
||||
|
||||
def _lex(s):
|
||||
@@ -337,16 +341,15 @@ def _validate_new_top(c, ids, errs):
|
||||
errs.append("%s: check %r is not a check or invariant id" % (w, r["check"]))
|
||||
if "added" in r and not _str(r["added"]):
|
||||
errs.append(w + ": added must be a non-empty string")
|
||||
if "risk" in c:
|
||||
rk = c["risk"]
|
||||
if not isinstance(rk, dict):
|
||||
errs.append("risk must be an object")
|
||||
else:
|
||||
if "profile" in rk and rk["profile"] not in RISK_PROFILES:
|
||||
errs.append("risk.profile must be one of %s" % ", ".join(RISK_PROFILES))
|
||||
for k in ("why", "blast_radius", "rollback"):
|
||||
if k in rk and not _str(rk[k]):
|
||||
errs.append("risk.%s must be a non-empty string" % k)
|
||||
rk = c.get("risk")
|
||||
if not isinstance(rk, dict):
|
||||
errs.append("risk must be an object that states its profile: " + RISK_HINT)
|
||||
else:
|
||||
if rk.get("profile") not in RISK_PROFILES:
|
||||
errs.append("risk.profile is required: " + RISK_HINT)
|
||||
for k in ("why", "blast_radius", "rollback"):
|
||||
if k in rk and not _str(rk[k]):
|
||||
errs.append("risk.%s must be a non-empty string" % k)
|
||||
if "deferred" in c:
|
||||
df = c["deferred"]
|
||||
if not isinstance(df, list):
|
||||
|
||||
+2
-6
@@ -134,10 +134,6 @@ def routing_adjustments(project):
|
||||
|
||||
# ---- enforced checks (verify.py seam) ----------------------------------------------
|
||||
|
||||
def enforced_path():
|
||||
return paths.overlay_dir("enforced.json")
|
||||
|
||||
|
||||
def load_enforced(project=None):
|
||||
"""Enforced checks; with a project, only those that apply in it."""
|
||||
checks = [c for c in _overlay_json("enforced.json", "checks").get("checks", []) if isinstance(c, dict)]
|
||||
@@ -183,8 +179,8 @@ def enforced_results(c, project, deadline=None, default_timeout=60):
|
||||
to = float(e.get("timeout_s") or default_timeout)
|
||||
if deadline is not None:
|
||||
to = min(to, deadline - time.time())
|
||||
st, dur, tail = V.run_cmd(e["cmd"], project, to, e.get("expect") or {"exit": 0})
|
||||
out.append(dict(base, status=st, duration_s=round(dur, 3), tail=tail,
|
||||
st, dur, tail, ev = V.run_cmd(e["cmd"], project, to, e.get("expect") or {"exit": 0})
|
||||
out.append(dict(base, status=st, duration_s=round(dur, 3), tail=tail, evidence=ev,
|
||||
claim="enforced learning %s: %s" % (lid, e["cmd"])))
|
||||
return out
|
||||
|
||||
|
||||
+2
-1
@@ -90,7 +90,8 @@ def release(project):
|
||||
|
||||
|
||||
def save_state(project, contract_id, fp, results, deep_ids):
|
||||
items = [{"id": r["id"], "status": r["status"], "tail": (r.get("tail") or "")[-1500:]}
|
||||
items = [{"id": r["id"], "status": r["status"], "tail": (r.get("tail") or "")[-1500:],
|
||||
"evidence": r.get("evidence") or ""}
|
||||
for r in results if r.get("tier") == "deep"]
|
||||
st = {"contract": contract_id, "fp": fp, "epoch": time.time(), "ids": sorted(deep_ids),
|
||||
"ok": all(i["status"] in ("passed", "skipped", "not-applicable") for i in items), "items": items}
|
||||
|
||||
+2
-1
@@ -374,7 +374,8 @@ def _decide(payload):
|
||||
store.log_error("gate-deep", e)
|
||||
failing = V.blocking(results)
|
||||
if ds and ds["state"] == "failed" and ds["fresh"]:
|
||||
failing = failing + [{"id": i["id"], "status": "failed", "reason": "deep", "tail": i["tail"]} for i in ds["failed"]]
|
||||
failing = failing + [{"id": i["id"], "status": "failed", "reason": "deep", "tail": i["tail"],
|
||||
"evidence": i.get("evidence") or ""} for i in ds["failed"]]
|
||||
miss = assure.missing(profile, c, project, results, errs, ds["state"] if ds else None)
|
||||
|
||||
if miss or failing:
|
||||
|
||||
+1
-1
@@ -37,7 +37,7 @@ sub-agents is not machine-written.
|
||||
Pasted content does not count towards length (it is a human attachment). The heuristic errs towards
|
||||
calling things machine-written: a false "machine" only removes a session from the human task set.
|
||||
"""
|
||||
import json, os, re, sys, time
|
||||
import json, os, re
|
||||
from collections import namedtuple
|
||||
|
||||
from . import paths
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
"""Help text for `sisi help`: four groups of commands, one line each, and the long text per command.
|
||||
|
||||
`sisi help` must fit 60 lines of 110 characters (tests/test_public.py checks it); the long explanation of a
|
||||
command is printed by `sisi help COMMAND` and `sisi COMMAND --help`.
|
||||
"""
|
||||
|
||||
LONG = {
|
||||
'contract': ' sisi contract init [--goal TEXT] start a work unit: create .sisi/contract.json here (refuses while one is open)\n sisi contract check validate the contract (vacuous checks are refused)\n sisi contract waive [--check ID] "<reason>"\n record a deviation: a waived check does not pass; the unit closes as a deviation and the report must say so\n sisi contract trust | untrust allow / stop allowing this project\'s contract to run commands',
|
||||
'unit': ' sisi unit close [--abandon "<reason>"]\n archive the unit to .sisi/units/<id>.json with its scorecard; --abandon records why it stopped\n sisi unit pause "<what it waits for>"\n record a wait; the turn may end with no demands\n sisi unit show [ID] | list print the open unit or an archived record; list this project\'s units',
|
||||
'verify': ' sisi verify [--json] run the selected fast checks (five statuses; nothing unrun passes); exit 0 ok, 1 failure, 2 no contract, 3 untrusted\n sisi verify --deep [--background] run the deep (long) checks; --background detaches and returns at once\n sisi verify --all | --state run every check in both tiers; print only the deep-check state (with --json)',
|
||||
'gate': " sisi gate [--tool NAME] end-of-turn hook (reads hook JSON on stdin; NAME selects the tool's hook shape)",
|
||||
'tick': ' sisi tick [--tool NAME] session-start hook',
|
||||
'prompt': ' sisi prompt [--tool NAME] prompt-submission hook: prints the matching recipe and lessons for the human\'s request as added context (silent when nothing strictly matches); `sisi prompt "<request>"` tries it by hand',
|
||||
'rule': ' sisi rule [N|ID] the effective rules and how each is enforced; with N or ID: one rule in full (reasons, history, lessons behind it, how it is enforced)',
|
||||
'watch': ' sisi watch [--before|--after] before/after shell-tool hook: measures whether the command changed the project',
|
||||
'install': ' sisi install [--dry-run] | uninstall | doctor\n wire sisi into the tools (by reference), undo, inspect; --dry-run only prints what would change',
|
||||
'release': " sisi release [--deep] run the source's checks, then make the stable copy the tools run (see docs/developing.md)",
|
||||
'rollback': ' sisi rollback switch the stable copy back to the previous release',
|
||||
'promote': ' sisi promote [ID|L-NNNN] [--apply] | --export [PATH]\n no ID: list items not yet in the product (learnings that change\n sisi itself, or earned organization scope); an ID scrubs a\n personal overlay item into the source folder and drops the\n personal copy once the product contains it (dry run unless\n --apply); L-NNNN promotes the rule or recipe a learning was\n folded into, from the clone; --export writes a contribution file\n (universal text only; nothing is sent anywhere)',
|
||||
'update': ' sisi update fast-forward the product clone, then back up, migrate and rebuild personal data',
|
||||
'export': ' sisi export [PATH] | import PATH one tar.gz of personal data, results and session records; restore it',
|
||||
'overlay': ' sisi overlay list|diff|add-rule|replace-rule|disable-rule|enable-rule|add-verifier|...|revert COMMIT\n learned changes to rules, verifiers and recipes; each one a commit in your personal repo',
|
||||
'retro': " sisi retro print the unit's record and what stands out in it\n sisi retro --finding F --cause C --impact value|correctness|time|cost|attention --disposition promote|record|drop [--same-as ID | --new] [--target ID]\n record one finding; promote also needs --change, --mechanism,\n --expect and --validate; record needs --limits; drop needs --why-not;\n a match in scope is printed and attached as a recurrence (--new records\n a learning of its own); --target names the rule or recipe it concerns\n sisi retro --adopt ID a parent adopts a subagent's candidate learning, by id",
|
||||
'lessons': ' sisi lessons [--json] | show ID the learning records and their statuses',
|
||||
'cycle': ' sisi cycle [due|apply FILE|check FILE|revert [ID]|help]\n turn proposed learnings into mechanisms (no scheduler:\n due-ness is a counter); apply validates and replays before\n promoting; help prints the cycle file format',
|
||||
'approve': " sisi approve [ID --yes|--no] list, in full, the consequential changes waiting for the owner; decide one\n (in a terminal: an agent's --yes without one is refused)",
|
||||
'learn': ' sisi learn [--scope user|project] TEXT\n record an owner statement; it takes effect at once and\n `sisi oracle` prints it. Scope for other learnings is\n earned by evidence, never claimed\n sisi learn --withdraw ID --reason WHY\n take a statement recorded by mistake out of delivery (kept in history)',
|
||||
'risk': ' sisi risk [--json] risk floor for the working-tree change, with reasons and\n what that profile requires',
|
||||
'handover': " sisi handover [--all] | done ID --where PATH [--quote FRAGMENT]\n project-scope learnings waiting to be filed in this project's own docs or\n work list; done confirms one is filed (the named file must contain\n its key text) and removes it from the list",
|
||||
'oracle': ' sisi oracle print what the human wants: the standing principles from\n `sisi learn`, live at once (project-scoped ones only in their project)',
|
||||
'status': ' sisi status [--json] [--learning] recent units with their scorecards, then trends by project, risk profile, model and policy version (median and p95; no single score)',
|
||||
'verifiers': ' sisi verifiers [WORDS] [--lang L] [--kind K] [--rung N] [--section S] [--installed] [--json]\n list ways to know work is correct, by section\n sisi verifiers show ID [--trace] one entry in full, and whether its tool is installed here; --trace also prints where each folded lesson lives in it\n sisi verifiers for "<claim>" best-matching verifiers for a claim or piece of work\n sisi verifiers doctor | lint which tools are installed; validate the library',
|
||||
'done': ' sisi done [ID] [--trace] recipes: which checks make a kind of work done; --trace also prints where each folded lesson lives in the recipe\n sisi done for "<work>" best-matching recipe',
|
||||
'workers': ' sisi workers [--refresh] the agent tools and models found here, what is usable now and why not, allowance and price where known, delegations waiting for a judgement, and the judged record as three tables\n sisi workers fact W --price N|--score N --source S record a price (per million tokens) or benchmark standing (0-100), with its source and date\n sisi workers avoid|prefer PATTERN --why TEXT your own routing constraints, honoured by `sisi route`\n sisi workers only PROVIDER PATTERN... --why TEXT | --remove make only the matching models of that provider routable\n sisi workers note PATTERN \"TEXT\" --why SOURCE | --remove a standing fact about workers matching PATTERN, shown with route results\n sisi workers down W --reason limit|auth|missing|error [--until DATE] | up W mark a worker unavailable / available again\n sisi workers import FILE merge another ledger file into the delegation ledger (row counts printed; safe to repeat)',
|
||||
'route': ' sisi route --kind K --difficulty N [--review-of W] [--explain]\n the most affordable usable worker for this kind and difficulty, and the mechanism to start it with (host subagents, host cross-provider delegation, or sisi delegate); --explain says why',
|
||||
'delegate': ' sisi delegate brief | check FILE | guide the delegation-contract template (eight parts); which parts a brief lacks; the orchestration playbook\n sisi delegate --kind K --difficulty N --brief FILE [--worker W] [--review-of W] [--cwd DIR]\n run one brief on the chosen worker unattended; prints only its final report, the transcript path, and the judge command; a brief without outcome, acceptance or files it may change is refused\n sisi delegate judge ID --outcome accepted|rejected --check none|diffstat|tests|read|review [--minutes N]\n record your judgement of a delegation run, so the next choice learns from it; judge work run any other way with --worker W --type K --difficulty N instead of ID\n sisi delegate amend ID | recent [-n N] [--project P] mark a judged delegation that later proved wrong; list recent judgements to find an id',
|
||||
'eval': ' sisi eval list|add|run|compare|shadow|judge|status|import\n the evaluation harness: benchmark cases from real work, isolated\n replay, policy comparison and independent judging (see docs/evaluation.md);\n `sisi eval` alone prints status; run without --tasks replays check cases only',
|
||||
'version': ' sisi version | --version print the product version (the VERSION file in the product folder)',
|
||||
'help': ' sisi help this text',
|
||||
}
|
||||
|
||||
ENV = (
|
||||
"Three places: the product (this clone, read-only at run time), your personal data (~/.local/share/sisi,\n"
|
||||
"its own git repository), and scratch (~/.local/state/sisi). Environment: SISI_HOME, SISI_DATA, SISI_STATE,\n"
|
||||
"SISI_LIB, SISI_TOOL, SISI_VERIFIERS, SISI_DONE (what each means: `sisi help help`).\n")
|
||||
|
||||
# (heading, [(command names, usage shown, one line)]) in reading order. Every command the dispatcher
|
||||
# accepts is named in exactly one row.
|
||||
GROUPS = (
|
||||
("For the person", (
|
||||
(("install", "uninstall", "doctor"), "install [--dry-run] | uninstall | doctor", "wire sisi into your tools, undo it, check it"),
|
||||
(("update",), "update", "update the product; back up, migrate, rebuild your data"),
|
||||
(("status",), "status [--json] [--learning]", "recent units with scorecards, then trends"),
|
||||
(("rollback",), "rollback", "switch the stable copy back to the previous release"),
|
||||
(("approve",), "approve [ID --yes|--no]", "list what waits for you; decide one (terminal only)"),
|
||||
(("oracle",), "oracle", "what you want: the principles recorded by `sisi learn`"),
|
||||
(("export", "import"), "export [PATH] | import PATH", "one tar.gz of personal data and results; restore it"),
|
||||
)),
|
||||
("For the agent at work", (
|
||||
(("contract",), "contract init|check|waive|trust|untrust", "start, validate and bend the unit's contract"),
|
||||
(("unit",), "unit close|pause|show|list", "close a unit with its scorecard, record a wait, look back"),
|
||||
(("risk",), "risk [--json]", "the risk floor of the working-tree change; what it requires"),
|
||||
(("verify",), "verify [--deep|--all|--state] [--json]", "run the contract's checks; nothing unrun passes"),
|
||||
(("retro",), "retro [--finding F ...|--adopt ID]", "the unit's record; record a finding, with its cause and fix"),
|
||||
(("learn",), "learn [--scope S] TEXT | --withdraw ID", "record what the owner said; take a mistaken one back"),
|
||||
(("route",), "route --kind K --difficulty N [--explain]", "the most affordable usable worker for a task"),
|
||||
(("delegate",), "delegate brief|check|guide|judge|amend", "write, check, run and judge a brief for a worker"),
|
||||
(("workers",), "workers [fact|avoid|prefer|only|note|down|up]", "workers found here, what each costs, the judged record"),
|
||||
(("verifiers",), "verifiers show|for|doctor|lint|WORDS", "ways to know work is correct"),
|
||||
(("done",), "done [ID|for \"<work>\"]", "the recipe saying what makes a kind of work done"),
|
||||
(("rule",), "rule [N|ID]", "the rules and how each is enforced"),
|
||||
(("handover",), "handover [--all] | done ID --where PATH", "learnings waiting to be filed in this project's docs"),
|
||||
(("lessons",), "lessons [--json] | show ID", "the learning records and their statuses"),
|
||||
(("eval",), "eval list|add|run|compare|shadow|status", "the evaluation harness: cases, replay, comparison"),
|
||||
)),
|
||||
("Hooks (the tools call these)", (
|
||||
(("tick",), "tick [--tool NAME]", "session start"),
|
||||
(("prompt",), "prompt [--tool NAME]", "each request: the matching recipe and lessons as context"),
|
||||
(("gate",), "gate [--tool NAME]", "end of turn: sends the agent back if the work is not ready"),
|
||||
(("watch",), "watch [--before|--after]", "around shell commands: did the project change?"),
|
||||
)),
|
||||
("Maintaining sisi", (
|
||||
(("release",), "release [--deep]", "check the source, then make the stable copy the tools run"),
|
||||
(("promote",), "promote [ID|L-NNNN] [--apply] | --export", "move a personal item or learning into the product"),
|
||||
(("cycle",), "cycle [due|apply|check|revert|help]", "turn proposed learnings into mechanisms"),
|
||||
(("overlay",), "overlay list|diff|add-rule|...|revert", "your learned changes to rules, verifiers, recipes"),
|
||||
(("harvest", "tasks", "escapes", "checks"), "harvest | tasks | escapes | checks", "the data layer behind `sisi eval`"),
|
||||
(("version",), "version", "print the product version"),
|
||||
(("help",), "help [COMMAND]", "this text, or one command in full"),
|
||||
)),
|
||||
)
|
||||
|
||||
|
||||
LONG["help"] = (
|
||||
" sisi help [COMMAND] this text, or one command in full (also `sisi COMMAND --help`)\n"
|
||||
" Environment: SISI_HOME (stands in for the home directory), SISI_DATA (personal data folder),\n"
|
||||
" SISI_STATE (scratch dir), SISI_LIB (where stable releases live, default ~/.local/lib/sisi),\n"
|
||||
" SISI_TOOL (name recorded with results), SISI_VERIFIERS and SISI_DONE (library directories,\n"
|
||||
" default verifiers/ and done/ in the product).\n")
|
||||
|
||||
|
||||
def names():
|
||||
"""Every command named in GROUPS."""
|
||||
return [n for _h, rows in GROUPS for row in rows for n in row[0]]
|
||||
|
||||
|
||||
def short():
|
||||
out = ["sisi: a shared rulebook and enforced definitions of done for every AI coding CLI.",
|
||||
"`sisi help COMMAND` or `sisi COMMAND --help` explains one command in full."]
|
||||
for heading, rows in GROUPS:
|
||||
out += ["", heading]
|
||||
out += [" sisi %-41s %s" % (usage, text) for _names, usage, text in rows]
|
||||
out += ["", ENV.rstrip("\n")]
|
||||
return "\n".join(out) + "\n"
|
||||
|
||||
|
||||
def long(cmd):
|
||||
"""The full text for one command, or None when `cmd` is not a command."""
|
||||
for _h, rows in GROUPS:
|
||||
for names_, usage, text in rows:
|
||||
if cmd in names_:
|
||||
return LONG.get(cmd) or " sisi %s %s\n" % (usage, text)
|
||||
return None
|
||||
@@ -234,18 +234,6 @@ def replace_node(text, node, new_text):
|
||||
return text[:node.start] + new_text + text[node.end:]
|
||||
|
||||
|
||||
def get_path(text, root, keys):
|
||||
node = root
|
||||
for k in keys:
|
||||
if node.kind == "lit" and node.value == "null":
|
||||
return node
|
||||
found = member(node, k)
|
||||
if found is None:
|
||||
return None
|
||||
node = found[1]
|
||||
return node
|
||||
|
||||
|
||||
def _dump(v):
|
||||
return json.dumps(v, ensure_ascii=False)
|
||||
|
||||
|
||||
@@ -9,11 +9,6 @@ import argparse, json, sys, time
|
||||
from . import store
|
||||
|
||||
|
||||
def _con():
|
||||
from . import harvest
|
||||
return harvest.connect()
|
||||
|
||||
|
||||
def cmd_harvest(args):
|
||||
from . import groundtruth, harvest
|
||||
t = time.time()
|
||||
|
||||
+1
-1
@@ -583,7 +583,7 @@ def statement_origin(statement):
|
||||
text = harvest.typed_text(d)[0]
|
||||
if text and want in _norm_words(text):
|
||||
return "typed by the owner"
|
||||
except (OSError, ImportError):
|
||||
except OSError:
|
||||
pass
|
||||
return "relayed by an agent"
|
||||
|
||||
|
||||
@@ -98,30 +98,6 @@ def personal_config():
|
||||
return {}
|
||||
|
||||
|
||||
def set_personal_config(keys, value, msg):
|
||||
"""Set (or with None remove) a nested key in the personal config.json; one commit in the personal repository."""
|
||||
import json
|
||||
from . import pdata
|
||||
cfg = personal_config()
|
||||
d = cfg
|
||||
for k in keys[:-1]:
|
||||
d = d.setdefault(k, {}) if isinstance(d.get(k, {}), dict) else d.setdefault(k, {})
|
||||
if value is None:
|
||||
d.pop(keys[-1], None)
|
||||
if not d and len(keys) > 1:
|
||||
cfg.pop(keys[0], None)
|
||||
else:
|
||||
d[keys[-1]] = value
|
||||
os.makedirs(data(), exist_ok=True)
|
||||
p = data_file("config.json")
|
||||
tmp = p + ".sisi-tmp"
|
||||
with open(tmp, "w", encoding="utf-8") as f:
|
||||
json.dump(cfg, f, indent=2, sort_keys=True)
|
||||
f.write("\n")
|
||||
os.replace(tmp, p)
|
||||
pdata.commit(msg, ["config.json"])
|
||||
|
||||
|
||||
def state_file(name):
|
||||
return os.path.join(state(), name)
|
||||
|
||||
|
||||
+4
-55
@@ -4,28 +4,11 @@ No arguments: print the unit's record and what stands out. With --finding: recor
|
||||
finding with a disposition. Only the fields the disposition needs are asked for; search
|
||||
terms, topics and short lines are derived by the tool. A finding that resembles an
|
||||
existing learning is attached to it as a recurrence candidate, never refused in a loop.
|
||||
|
||||
Gate compatibility (gate.py calls these; its control flow is unchanged): TEMPLATE,
|
||||
satisfied(), repo_of(), lessons_block().
|
||||
"""
|
||||
import hashlib, json, os, subprocess, sys
|
||||
|
||||
from . import learning as L, paths
|
||||
|
||||
TEMPLATE = (
|
||||
"Before this turn ends, record the retro for this unit ({n}).\n"
|
||||
"Run `sisi retro` first: it prints the unit's record. Then record at least one finding:\n"
|
||||
" sisi retro --finding \"<what happened, with the evidence>\" --cause \"<root cause>\" "
|
||||
"--impact value|correctness|time|cost|attention --disposition promote|record|drop\n"
|
||||
" promote also needs: --change \"<exact improvement>\" --mechanism policy|orchestration|skill|tool|"
|
||||
"infrastructure|verification|knowledge|benchmark --expect \"<observable effect>\" --validate \"<how it will be tested>\"\n"
|
||||
" record also needs: --limits \"<where it applies and where it does not>\"\n"
|
||||
" drop also needs: --why-not \"<why it is not worth promoting>\"\n"
|
||||
"Generic findings are refused. A finding that resembles a learning in scope here is attached to it as\n"
|
||||
"a recurrence (--new records it as its own); --same-as ID names the learning it repeats.\n"
|
||||
"A parent adopts a subagent's candidate by id: sisi retro --adopt ID."
|
||||
)
|
||||
|
||||
|
||||
def repo_of(cwd):
|
||||
return L.project_key(cwd)
|
||||
@@ -40,39 +23,12 @@ def _git_head(cwd):
|
||||
return None
|
||||
|
||||
|
||||
def satisfied(repo, since, fp):
|
||||
"""Gate seam: was a retro recorded for the current unit of this project?"""
|
||||
try:
|
||||
uid = L.unit_id(repo)
|
||||
if L.findings_for_unit(repo, uid):
|
||||
return True
|
||||
# A finding recorded in this project since the request started also counts:
|
||||
# the gate passes `since` from its own session bookkeeping.
|
||||
pk = L.project_key(repo)
|
||||
return any(f.get("project") == pk and (since is None or str(f.get("ts", "")) >= str(since))
|
||||
for f in L.load_findings()) if since else False
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def lessons_block(query, place, session=None, limit=3, max_chars=600, extra=""):
|
||||
"""Gate seam: learnings in scope as background information. Nothing is recorded as shown."""
|
||||
try:
|
||||
text = L.delivery_text(os.getcwd(), str(query))
|
||||
return text[:max_chars] if text else ""
|
||||
except Exception:
|
||||
return ""
|
||||
|
||||
|
||||
def unit_summary(project):
|
||||
"""What `sisi retro` with no arguments prints: the unit's record and what stands out."""
|
||||
try:
|
||||
from . import unit as _unit # work-unit worker's module, when merged
|
||||
text = _unit.summary_for_retro(project)
|
||||
if text:
|
||||
return text
|
||||
except Exception:
|
||||
pass
|
||||
from . import unit as _unit
|
||||
text = _unit.summary_for_retro(project)
|
||||
if text:
|
||||
return text
|
||||
lines = []
|
||||
try:
|
||||
with open(os.path.join(project, ".sisi", "contract.json"), encoding="utf-8") as f:
|
||||
@@ -91,13 +47,6 @@ def unit_summary(project):
|
||||
lines.append("recent verification: %d result(s) on record, %d failed" % (len(rows), len(fails)))
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
try:
|
||||
from . import delivery
|
||||
d = delivery.current(project) if hasattr(delivery, "current") else None
|
||||
if d:
|
||||
lines.append("delivery: %s" % d)
|
||||
except Exception:
|
||||
pass
|
||||
head = _git_head(project)
|
||||
if head:
|
||||
lines.append("project HEAD: %s" % head[:12])
|
||||
|
||||
@@ -38,7 +38,6 @@ import fnmatch, json, os, re, subprocess
|
||||
|
||||
PROFILES = ["trivial", "isolated", "logic", "integration", "data", "critical", "release"]
|
||||
_ORDER = {name: i for i, name in enumerate(PROFILES)}
|
||||
_TRIVIAL_PROFILES = {"trivial"}
|
||||
_DEFAULT_REASON = "ordinary source file: one module's behaviour"
|
||||
_CONTAINERS = {"src", "lib", "app", "packages", "apps", "services", "crates", "modules", "libs",
|
||||
"cmd", "internal", "pkg"}
|
||||
|
||||
+4
-6
@@ -18,10 +18,6 @@ def project_label(pid):
|
||||
return os.path.basename(str(pid).rstrip("/")) if pid else "(unknown project)"
|
||||
|
||||
|
||||
def visible_in(rec, cwd):
|
||||
return L.in_scope(rec, cwd)
|
||||
|
||||
|
||||
USAGE = ("usage: sisi learn [--scope user|project] \"<what you want>\"\n"
|
||||
" sisi learn --withdraw ID --reason \"<why it was recorded by mistake>\"")
|
||||
|
||||
@@ -69,6 +65,8 @@ def cmd_learn(argv):
|
||||
os.getcwd(), L.unit_id(), change=statement, mechanism="knowledge",
|
||||
scope=scope, expect="the agent acts on this statement",
|
||||
owner_statement=True, entered_via="learn", origin=origin)
|
||||
print("recorded owner statement %s (%s; printed by `sisi oracle`; withdraw a mistake with "
|
||||
"`sisi learn --withdraw %s --reason ...`)" % (rec["id"], origin, rec["id"]))
|
||||
print("recorded owner statement %s (%s)" % (rec["id"], origin))
|
||||
print(" stored: %s" % rec["observation"]["evidence"])
|
||||
print(" scope: %s; it takes effect at once and `sisi oracle` prints it" % rec["proposed"]["scope"])
|
||||
print(" to take it back: sisi learn --withdraw %s --reason \"<why it was recorded by mistake>\"" % rec["id"])
|
||||
return 0
|
||||
@@ -24,7 +24,6 @@ Split: sha256(task id) mod 100 < 70 is `dev`, else `holdout`. It depends on the
|
||||
"""
|
||||
import hashlib, json, os, time
|
||||
|
||||
from . import harvest, paths
|
||||
|
||||
DEV_PERCENT = 70
|
||||
MATCH_SLACK_S = 1200
|
||||
|
||||
+1
-4
@@ -1,12 +1,9 @@
|
||||
"""Session-start hook. Records the session baseline, checks wiring, prints at most one line. Must be fast."""
|
||||
import json, os, sys, time
|
||||
import json, os, sys
|
||||
|
||||
from . import store
|
||||
|
||||
|
||||
MAX_AGE_S = 30 * 86400
|
||||
|
||||
|
||||
def _prune(now=None, sid=None):
|
||||
"""Delete old per-session state files, bounded and on a counter (see store.prune_sessions)."""
|
||||
return store.prune_sessions(now=now, active_ids=(sid,) if sid else ())
|
||||
|
||||
+1
-13
@@ -124,18 +124,6 @@ def delegations(project, t0, t1):
|
||||
return None
|
||||
|
||||
|
||||
def _row_epoch(r):
|
||||
for k in ("ts", "t", "started", "ended", "time"):
|
||||
v = r.get(k)
|
||||
if isinstance(v, (int, float)) and not isinstance(v, bool):
|
||||
return float(v)
|
||||
if isinstance(v, str):
|
||||
t = harvest.epoch(v)
|
||||
if t is not None:
|
||||
return t
|
||||
return None
|
||||
|
||||
|
||||
def policy_version(project, c):
|
||||
"""Hash of the policies in force: the effective rulebook, the risk tables,
|
||||
the enforced checks, and the gate/verify config."""
|
||||
@@ -412,7 +400,7 @@ def latest_results(c, rows):
|
||||
ever_failed.add(cid)
|
||||
latest[cid] = {"item": r["item"], "id": cid, "status": st, "reason": r.get("reason"),
|
||||
"duration_s": r.get("duration_s", 0.0), "mandatory": r.get("mandatory", True),
|
||||
"tier": r.get("tier", "fast"), "ts": r.get("ts")}
|
||||
"tier": r.get("tier", "fast"), "ts": r.get("ts"), "evidence": r.get("evidence") or ""}
|
||||
for x in (c.get("checks") or []) + (c.get("invariants") or []):
|
||||
if isinstance(x, dict) and x.get("id") and x["id"] not in latest:
|
||||
latest[x["id"]] = {"item": "check", "id": x["id"], "status": "not-run",
|
||||
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
"""The verifier library and the recipes for "done": parse, list, show, choose, doctor, lint. No model calls."""
|
||||
import concurrent.futures as cf, json, os, re, subprocess, sys
|
||||
import concurrent.futures as cf, json, os, re, subprocess
|
||||
|
||||
from . import contract as C, paths
|
||||
|
||||
|
||||
+68
-16
@@ -6,7 +6,7 @@ change selection is skipped (not affected by this change), or not-applicable whe
|
||||
file it watches exists; an identical-inputs pass is skipped (reused: passed at <time>).
|
||||
Nothing that did not run is ever reported as passed, on any path.
|
||||
"""
|
||||
import hashlib, json, os, signal, subprocess, time
|
||||
import hashlib, json, os, re, signal, subprocess, time
|
||||
from fnmatch import fnmatch
|
||||
from pathlib import PurePosixPath
|
||||
|
||||
@@ -21,16 +21,65 @@ def _tail(s):
|
||||
return s[-TAIL:] if len(s) > TAIL else s
|
||||
|
||||
|
||||
EVIDENCE_LINES = 60 # at most this many lines of evidence per failed check
|
||||
EVIDENCE_CHARS = 3000
|
||||
EVIDENCE_LINE = 300 # and each line is cut here
|
||||
EDGE = 30 # unknown output: this many lines from the start and from the end
|
||||
|
||||
# What names a failure in each known runner's output. A line that matches is kept, with the few lines
|
||||
# after it that carry the assertion or the panic message.
|
||||
_RUNNERS = (
|
||||
("unittest", re.compile(r"^(FAIL|ERROR): \S+ \(.+\)"), re.compile(r"^\s*(\w+\.)*\w*(Error|Exception|Failure)\b.*|^\s+self\.assert\w+\(.*")),
|
||||
("pytest", re.compile(r"^(FAILED|ERROR) \S+|^_{3,} .+ _{3,}$"), re.compile(r"^E\s+.*|^\S+:\d+: \w+")),
|
||||
("cargo test", re.compile(r"^test \S+ \.\.\. FAILED$|^---- \S+ stdout ----$"), re.compile(r"^thread '.*' panicked at.*|^\s+(left|right):.*|^assertion .*")),
|
||||
("go test", re.compile(r"^\s*--- FAIL: \S+"), re.compile(r"^\s+\S+\.go:\d+:.*|^\s+(expected|actual|got|want).*|^panic: .*")),
|
||||
("jest", re.compile(r"^\s*● .+ › .+|^FAIL \S+"), re.compile(r"^\s*(expect\(|Expected|Received).*|^\s*(\w*Error):? .*")),
|
||||
)
|
||||
|
||||
|
||||
def _clip(lines):
|
||||
out, chars = [], 0
|
||||
for ln in lines:
|
||||
ln = ln.rstrip()[:EVIDENCE_LINE]
|
||||
chars += len(ln) + 1
|
||||
if len(out) >= EVIDENCE_LINES or chars > EVIDENCE_CHARS:
|
||||
break
|
||||
out.append(ln)
|
||||
return out
|
||||
|
||||
|
||||
def evidence(text):
|
||||
"""The lines that identify a failure, scrubbed of secrets and bounded in size. For output of a known
|
||||
test runner (unittest, pytest, cargo test, go test, jest): each failing test's name line and the
|
||||
assertion lines after it. Otherwise the first and the last 30 lines. A runner prints its summary last,
|
||||
so the tail alone loses the failing test; these lines are what the agent needs first."""
|
||||
lines = [ln for ln in str(text or "").splitlines() if ln.strip()]
|
||||
picked = []
|
||||
for _name, head, detail in _RUNNERS:
|
||||
if not any(head.match(ln) for ln in lines):
|
||||
continue
|
||||
for i, ln in enumerate(lines):
|
||||
if head.match(ln):
|
||||
picked.append(ln)
|
||||
picked += [d for d in lines[i + 1:i + 40] if detail.match(d) and not head.match(d)][:3]
|
||||
break
|
||||
if not picked:
|
||||
picked = lines if len(lines) <= 2 * EDGE else lines[:EDGE] + ["... (%d lines not shown)" % (len(lines) - 2 * EDGE)] + lines[-EDGE:]
|
||||
from . import learning
|
||||
return "\n".join(learning.scrub_secrets(ln) for ln in _clip(dict.fromkeys(picked)))
|
||||
|
||||
|
||||
def run_cmd(cmd, cwd, timeout, expect):
|
||||
"""Return (status, duration, tail). status: passed/failed/not-run (a timeout never ran to a verdict)."""
|
||||
"""Return (status, duration, tail, evidence). status: passed/failed/not-run (a timeout never ran to a
|
||||
verdict). `evidence` is empty unless the check failed or timed out."""
|
||||
t0 = time.time()
|
||||
if timeout <= 0:
|
||||
return "not-run", 0.0, "not run: time budget exhausted"
|
||||
return "not-run", 0.0, "not run: time budget exhausted", ""
|
||||
try:
|
||||
p = subprocess.Popen(cmd, shell=True, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
||||
stdin=subprocess.DEVNULL, start_new_session=True)
|
||||
except OSError as e:
|
||||
return "failed", 0.0, "could not start: %s" % e
|
||||
return "failed", 0.0, "could not start: %s" % e, "could not start: %s" % e
|
||||
try:
|
||||
out, err = p.communicate(timeout=timeout)
|
||||
except subprocess.TimeoutExpired:
|
||||
@@ -39,20 +88,21 @@ def run_cmd(cmd, cwd, timeout, expect):
|
||||
except OSError:
|
||||
pass
|
||||
try:
|
||||
p.communicate(timeout=5)
|
||||
out, err = p.communicate(timeout=5)
|
||||
except Exception:
|
||||
pass
|
||||
return "not-run", time.time() - t0, "timed out after %gs" % timeout
|
||||
out = err = b""
|
||||
seen = (out or b"").decode("utf-8", "replace") + "\n" + (err or b"").decode("utf-8", "replace")
|
||||
return "not-run", time.time() - t0, "timed out after %gs" % timeout, evidence(seen)
|
||||
dur = time.time() - t0
|
||||
o, e = out.decode("utf-8", "replace"), err.decode("utf-8", "replace")
|
||||
tail = _tail(o + ("\n" if o and e else "") + e)
|
||||
want = expect.get("exit", 0)
|
||||
if p.returncode != want:
|
||||
return "failed", dur, "exit %d, expected %d\n%s" % (p.returncode, want, tail)
|
||||
return "failed", dur, "exit %d, expected %d\n%s" % (p.returncode, want, tail), evidence(o + "\n" + e)
|
||||
sc = expect.get("stdout_contains")
|
||||
if sc is not None and sc not in o:
|
||||
return "failed", dur, "stdout does not contain %r\n%s" % (sc, tail)
|
||||
return "passed", dur, tail
|
||||
return "failed", dur, "stdout does not contain %r\n%s" % (sc, tail), evidence(o + "\n" + e)
|
||||
return "passed", dur, tail, ""
|
||||
|
||||
|
||||
def tree_fp(project, contract_path):
|
||||
@@ -200,16 +250,16 @@ def _run_item(item, x, tier, project, deadline, default_timeout):
|
||||
"tier": tier, "mandatory": x.get("mandatory", True), "independent": bool(x.get("independent", False)),
|
||||
"covers": x.get("covers"), "reason": None, "saved_s": 0.0}
|
||||
if x.get("rung") in (5, 6):
|
||||
r.update(status="not-run", reason="needs human", duration_s=0.0, tail="")
|
||||
r.update(status="not-run", reason="needs human", duration_s=0.0, tail="", evidence="")
|
||||
else:
|
||||
to = float(x.get("timeout_s", default_timeout))
|
||||
if deadline is not None:
|
||||
to = min(to, deadline - time.time())
|
||||
st, dur, tail = run_cmd(x["cmd"], project, to, x.get("expect", {"exit": 0}))
|
||||
st, dur, tail, ev = run_cmd(x["cmd"], project, to, x.get("expect", {"exit": 0}))
|
||||
reason = None
|
||||
if st == "not-run":
|
||||
reason = "timed out" if tail.startswith("timed out") else tail.removeprefix("not run: ")
|
||||
r.update(status=st, reason=reason, duration_s=round(dur, 3), tail=tail)
|
||||
r.update(status=st, reason=reason, duration_s=round(dur, 3), tail=tail, evidence=ev)
|
||||
return r
|
||||
|
||||
|
||||
@@ -217,7 +267,7 @@ def _not_run_result(base_item, x, tier, status, reason, saved=0.0):
|
||||
return {"item": base_item, "id": x["id"], "kind": x.get("kind"), "rung": x.get("rung"),
|
||||
"claim": x.get("claim"), "tier": tier, "mandatory": x.get("mandatory", True),
|
||||
"independent": bool(x.get("independent", False)), "covers": x.get("covers"),
|
||||
"status": status, "reason": reason, "duration_s": 0.0, "tail": "", "saved_s": round(saved, 3)}
|
||||
"status": status, "reason": reason, "duration_s": 0.0, "tail": "", "evidence": "", "saved_s": round(saved, 3)}
|
||||
|
||||
|
||||
def run(c, project, deadline=None, default_timeout=60, tiers=("fast",), changed=None, reuse=True,
|
||||
@@ -326,7 +376,7 @@ def record(c, project, results, fp=None):
|
||||
"seen_failing": bool(r.get("seen_failing")), "mandatory": r.get("mandatory", True),
|
||||
"independent": bool(r.get("independent", False)), "covers": r.get("covers"),
|
||||
"tool": store.tool(), "session": store.session_id(), "run": run_id,
|
||||
"tier": r.get("tier", "fast"), "fp": fp})
|
||||
"tier": r.get("tier", "fast"), "fp": fp, "evidence": r.get("evidence") or ""})
|
||||
return run_id
|
||||
|
||||
|
||||
@@ -340,13 +390,15 @@ def format_table(results):
|
||||
|
||||
|
||||
def failure_report(results, limit=4000):
|
||||
"""What failed and why: the lines that identify each failure first, then the last lines of the output."""
|
||||
from . import assure
|
||||
parts = []
|
||||
bad = {id(r) for r in blocking(results)} | {id(r) for r in results if r["status"] == "failed"}
|
||||
for r in results:
|
||||
if id(r) in bad:
|
||||
label = r["status"] + ((": " + r["reason"]) if r.get("reason") else "")
|
||||
parts.append("- %s %s [%s]: %s\n%s" % (r["item"], r["id"], label, r.get("claim") or "",
|
||||
"\n".join(" " + l for l in (r["tail"] or "").splitlines()[-15:])))
|
||||
"\n".join(" " + l for l in assure.shown_lines(r, 20, 5))))
|
||||
s = "\n".join(parts)
|
||||
return s if len(s) <= limit else s[:limit] + "\n... (truncated)"
|
||||
|
||||
|
||||
+1
-31
@@ -1,7 +1,7 @@
|
||||
"""install / uninstall / doctor. Wiring by reference (import line, symlink, hook entry); never copies canon text.
|
||||
The tools load the generated rulebook in the personal data folder (base rules with the overlay applied), not the
|
||||
product's canon/core.md. Every modified file is backed up into <personal>/install/ first; uninstall restores it exactly."""
|
||||
import copy, hashlib, json, os, re, shlex, shutil, stat as _stat
|
||||
import copy, hashlib, json, os, re, stat as _stat
|
||||
|
||||
from . import hookjson, paths, store
|
||||
|
||||
@@ -321,36 +321,6 @@ def add_hooks(obj):
|
||||
return changed
|
||||
|
||||
|
||||
def remove_hooks(obj):
|
||||
changed = False
|
||||
hooks = obj.get("hooks")
|
||||
if not isinstance(hooks, dict):
|
||||
return False
|
||||
for ev, sub in (("SessionStart", "tick"), ("UserPromptSubmit", "prompt"), ("Stop", "gate"), ("SubagentStop", "gate"),
|
||||
("PreToolUse", "watch"), ("PostToolUse", "watch")):
|
||||
groups = hooks.get(ev)
|
||||
if not isinstance(groups, list):
|
||||
continue
|
||||
keep, ev_changed = [], False
|
||||
for g in groups:
|
||||
hs = g.get("hooks") if isinstance(g, dict) else None
|
||||
if isinstance(hs, list) and any(_is_ours(h, sub) for h in hs):
|
||||
changed = ev_changed = True
|
||||
rest = [h for h in hs if not _is_ours(h, sub)]
|
||||
if rest:
|
||||
g = dict(g, hooks=rest)
|
||||
else:
|
||||
continue
|
||||
keep.append(g)
|
||||
if keep:
|
||||
hooks[ev] = keep
|
||||
elif ev_changed:
|
||||
del hooks[ev]
|
||||
if changed and not hooks:
|
||||
del obj["hooks"]
|
||||
return changed
|
||||
|
||||
|
||||
def _hooks_wired(obj):
|
||||
hooks = obj.get("hooks") if isinstance(obj, dict) else None
|
||||
out = {}
|
||||
|
||||
+29
-43
@@ -474,36 +474,6 @@ def import_ledger(src, now=None):
|
||||
return before, before + added, added
|
||||
|
||||
|
||||
def ensure_imported(now=None):
|
||||
"""Import the previously hand-kept ledger once, losslessly. Returns the row count, or None
|
||||
when there was nothing (more) to import. The original file is only read."""
|
||||
now = time.time() if now is None else now
|
||||
marker = _data_file("delegations-import.json")
|
||||
if os.path.exists(marker):
|
||||
return None
|
||||
try:
|
||||
from . import taskset
|
||||
src = taskset.ledger_path()
|
||||
except Exception:
|
||||
src = None
|
||||
if not src or not os.path.isfile(src):
|
||||
return None
|
||||
if os.path.realpath(src) == os.path.realpath(ledger_path()):
|
||||
return None
|
||||
_before, _after, count = import_ledger(src, now=now)
|
||||
# Merge the availability file that sat beside the old ledger, so nothing is forgotten.
|
||||
sibling = os.path.join(os.path.dirname(src), "availability.json")
|
||||
if os.path.isfile(sibling):
|
||||
avail = read_availability()
|
||||
for k, v in read_json(sibling).items():
|
||||
if isinstance(v, dict):
|
||||
avail[str(k).lower()] = v
|
||||
if avail:
|
||||
write_json(availability_path(), avail)
|
||||
write_json(marker, {"source": src, "rows": count, "ts": now})
|
||||
return count
|
||||
|
||||
|
||||
def unjudged_runs(records=None):
|
||||
records = read_records() if records is None else records
|
||||
judged = {r.get("run_id") for r in records if r.get("kind") == "attempt" and r.get("run_id")}
|
||||
@@ -762,6 +732,21 @@ def with_commit(fn, args, label):
|
||||
pdata.commit("sisi %s%s: worker data changed" % (label, (" " + sub) if sub else ""), list(DATA_FILES))
|
||||
|
||||
|
||||
def effective_prefs(kind, difficulty, project):
|
||||
"""The user's avoid/prefer patterns plus the routing adjustments a learning cycle wrote that apply in
|
||||
this project for this kind (and difficulty, when the adjustment names one). A learned entry carries
|
||||
its learning id as its reason, so `sisi route --explain` shows where it came from."""
|
||||
from . import cycle
|
||||
prefs = load_prefs()
|
||||
for a in cycle.routing_adjustments(project):
|
||||
if a.get("kind") != kind or a.get("difficulty") not in (None, difficulty):
|
||||
continue
|
||||
for key in ("avoid", "prefer"):
|
||||
if a.get(key):
|
||||
prefs[key].append({"pattern": str(a[key]), "why": "learning %s" % a.get("learning")})
|
||||
return prefs
|
||||
|
||||
|
||||
def _fact_dates():
|
||||
dates = []
|
||||
prices = load_prices()
|
||||
@@ -1102,7 +1087,7 @@ def run_delegation(candidates, kind, difficulty, prompt, cwd, explicit=None, rev
|
||||
timeout = DEFAULT_RUN_TIMEOUT_S
|
||||
tried = []
|
||||
cand = explicit
|
||||
prefs = load_prefs()
|
||||
prefs = effective_prefs(kind, difficulty, cwd)
|
||||
if cand is not None and cand.get("host_native"):
|
||||
notes.append("sisi: %s is a host-native worker; start it with the host's own subagent tool "
|
||||
"(`sisi delegate` runs only command-line tools)" % cand["worker"])
|
||||
@@ -1110,6 +1095,7 @@ def run_delegation(candidates, kind, difficulty, prompt, cwd, explicit=None, rev
|
||||
candidates = [c for c in apply_limits(candidates, prefs)[0] if not c.get("host_native")]
|
||||
while True:
|
||||
if cand is None:
|
||||
prefs = effective_prefs(kind, difficulty, cwd)
|
||||
result = routing.choose(candidates, read_records(), read_availability(), kind, difficulty,
|
||||
review_of=review_of, now=time.time(), exclude=tried,
|
||||
avoid=prefs["avoid"], prefer=prefs["prefer"])
|
||||
@@ -1333,7 +1319,6 @@ def cmd_workers(args=()):
|
||||
return _cmd_up(args[1:])
|
||||
if args[:1] == ["import"]:
|
||||
return _cmd_import(args[1:])
|
||||
imported = ensure_imported()
|
||||
disc = discover(force="--refresh" in args)
|
||||
records = read_records()
|
||||
avail = read_availability()
|
||||
@@ -1377,9 +1362,6 @@ def cmd_workers(args=()):
|
||||
continue
|
||||
print("Unavailable: %s - %s, next try %s%s" % (k, v.get("reason") or "down", _when(v.get("retry_at")),
|
||||
(" (%s)" % v["note"]) if v.get("note") else ""))
|
||||
if imported is not None:
|
||||
print("Imported the existing delegation ledger: imported %d rows, once, without changing the original."
|
||||
% imported)
|
||||
waiting = unjudged_runs(records)
|
||||
if waiting:
|
||||
print("%d delegation%s waiting for a judgement (%s). Judge with `sisi delegate judge ID "
|
||||
@@ -1420,7 +1402,6 @@ def _down_lines(down, limit=3):
|
||||
|
||||
|
||||
def _route_setup(args):
|
||||
ensure_imported()
|
||||
kind = _opt(args, "--kind")
|
||||
difficulty = _opt(args, "--difficulty")
|
||||
if not kind or difficulty is None:
|
||||
@@ -1442,7 +1423,7 @@ def cmd_route(args=()):
|
||||
kind, difficulty = setup
|
||||
records = read_records()
|
||||
candidates, cold, excluded = routable_candidates(build_candidates(), records)
|
||||
prefs = load_prefs()
|
||||
prefs = effective_prefs(kind, difficulty, os.getcwd())
|
||||
everyone = candidates
|
||||
candidates, limited = apply_limits(candidates, prefs)
|
||||
result = routing.choose(candidates, records, read_availability(), kind, difficulty,
|
||||
@@ -1736,12 +1717,17 @@ def _cmd_brief_check(args):
|
||||
missing = brief_contract.missing_parts(text)
|
||||
if not missing:
|
||||
print("brief ok: all %d parts present" % len(brief_contract.PARTS))
|
||||
return 0
|
||||
print("brief lacks:")
|
||||
for title in missing:
|
||||
print(" - %s" % title)
|
||||
print("`sisi delegate brief` prints the template.")
|
||||
return 1
|
||||
else:
|
||||
print("brief lacks:")
|
||||
for title in missing:
|
||||
print(" - %s" % title)
|
||||
print("`sisi delegate brief` prints the template.")
|
||||
advice = brief_contract.advice(text)
|
||||
if advice:
|
||||
print("advice (does not block):")
|
||||
for line in advice:
|
||||
print(" - %s" % line)
|
||||
return 1 if missing else 0
|
||||
|
||||
|
||||
def _cmd_down(args):
|
||||
|
||||
+2
-2
@@ -126,8 +126,8 @@ def human(id, rung=5, kind="general"):
|
||||
|
||||
|
||||
def contract(checks, invariants=()):
|
||||
return {"id": "t", "goal": "g", "checks": list(checks), "invariants": list(invariants),
|
||||
"assumptions": [], "questions": []}
|
||||
return {"id": "t", "goal": "g", "risk": {"profile": "isolated"}, "checks": list(checks),
|
||||
"invariants": list(invariants), "assumptions": [], "questions": []}
|
||||
|
||||
|
||||
def skip_timing_if_busy(case):
|
||||
|
||||
@@ -4,6 +4,39 @@ from sisi import contract as C
|
||||
|
||||
|
||||
class ContractTests(SisiCase):
|
||||
def test_the_contract_must_state_its_risk_profile(self):
|
||||
"""R-5.3-1: `risk.profile` is the agent's own judgement and is required; init writes the floor as its start."""
|
||||
good = contract([check("a", "true")])
|
||||
for name, risk in (("missing", None), ("empty object", {}), ("unknown", {"profile": "huge"})):
|
||||
with self.subTest(name):
|
||||
c = dict(good)
|
||||
c.pop("risk")
|
||||
if risk is not None:
|
||||
c["risk"] = risk
|
||||
errs = C.validate(c)
|
||||
self.assertTrue(any("risk" in e and "sisi risk" in e and "integration" in e and "release" in e
|
||||
for e in errs), errs)
|
||||
self.assertEqual(C.validate(good), [])
|
||||
self.git_init()
|
||||
self.assertEqual(self.sisi("contract", "init").returncode, 0)
|
||||
c = C.load(os.path.join(self.proj, ".sisi", "contract.json"))
|
||||
self.assertIn(c["risk"]["profile"], C.RISK_PROFILES)
|
||||
with open(os.path.join(self.proj, "migrations_001.sql"), "w") as f:
|
||||
f.write("alter table t add column c int;\n")
|
||||
os.remove(os.path.join(self.proj, ".sisi", "contract.json"))
|
||||
self.assertEqual(self.sisi("contract", "init").returncode, 0)
|
||||
floor = self.sisi("risk", "--json")
|
||||
import json as _j
|
||||
self.assertEqual(C.load(os.path.join(self.proj, ".sisi", "contract.json"))["risk"]["profile"],
|
||||
_j.loads(floor.stdout)["floor"])
|
||||
self.assertNotEqual(_j.loads(floor.stdout)["floor"], "trivial")
|
||||
c = C.load(os.path.join(self.proj, ".sisi", "contract.json"))
|
||||
c["risk"] = {}
|
||||
C.save(os.path.join(self.proj, ".sisi", "contract.json"), c)
|
||||
r = self.sisi("contract", "check")
|
||||
self.assertEqual(r.returncode, 1)
|
||||
self.assertIn("risk.profile", r.stdout)
|
||||
|
||||
def test_skeleton_is_valid_but_fails(self):
|
||||
c = C.skeleton("goal")
|
||||
self.assertEqual(C.validate(c), [])
|
||||
|
||||
+1
-1
@@ -132,7 +132,7 @@ class EndToEnd(SisiCase):
|
||||
"covers": "the migration is deleted"}]
|
||||
c["invariants"] = [{"id": "readme", "claim": "the readme stays", "cmd": "test -f README.md", "expect": {"exit": 0}}]
|
||||
c["requirements"] = [{"id": "r1", "kind": "explicit", "text": "a users table exists", "decision": "now"}]
|
||||
c["risk"] = {"blast_radius": "one new table; nothing reads it yet", "rollback": "drop the table"}
|
||||
c["risk"] = {"profile": "data", "blast_radius": "one new table; nothing reads it yet", "rollback": "drop the table"}
|
||||
c["approach"] = {"chosen": "a plain SQL migration", "why": "the project already uses them",
|
||||
"alternatives": ["an ORM auto-migration: hides the schema"]}
|
||||
self.agent_writes(os.path.join(".sisi", "contract.json"), json.dumps(c))
|
||||
|
||||
+22
-2
@@ -25,7 +25,7 @@ def full(**over):
|
||||
[dict(check("keeps", "test -f README.md"), covers="the readme is deleted")])
|
||||
c.update(id="t", goal="make the feature work",
|
||||
requirements=[{"id": "r1", "kind": "explicit", "text": "ok.txt exists when the feature is done", "decision": "now"}],
|
||||
risk={"blast_radius": "only the feature file; nothing else reads it", "rollback": "git revert the commit"},
|
||||
risk={"profile": "isolated", "blast_radius": "only the feature file; nothing else reads it", "rollback": "git revert the commit"},
|
||||
approach={"chosen": "write the file directly", "why": "the simplest thing that works",
|
||||
"alternatives": ["generate it from a template: more moving parts"]},
|
||||
started=store.now(), status="open", pauses=[], deviations=[])
|
||||
@@ -174,6 +174,16 @@ class RequirementTests(GateBase):
|
||||
self.assertIn("sisi contract init", miss[0][1])
|
||||
self.assertEqual(assure.missing("isolated", contract([check("a", "false")]), self.proj), [])
|
||||
|
||||
def test_a_contract_without_a_risk_profile_is_missing_one_in_the_gates_list(self):
|
||||
"""R-5.3-1: the declared profile is on the "what is missing" list, once, with the field that supplies it."""
|
||||
c = full()
|
||||
c["risk"] = {"blast_radius": "x" * 20, "rollback": "git revert"}
|
||||
miss = assure.missing("isolated", c, self.proj, errors=C.validate(c))
|
||||
self.assertEqual(len(miss), 1, miss)
|
||||
self.assertIn("risk profile", miss[0][0])
|
||||
self.assertIn('"profile"', miss[0][1])
|
||||
self.assertEqual(assure.missing("isolated", full(), self.proj, errors=C.validate(full())), [])
|
||||
|
||||
def test_logic_needs_covers_on_every_check(self):
|
||||
"""R-5.3-6."""
|
||||
c = contract([check("a", "false"), dict(check("b", "false"), covers="the parser drops a line")])
|
||||
@@ -185,7 +195,7 @@ class RequirementTests(GateBase):
|
||||
|
||||
def test_integration_needs_invariants_requirements_a_risk_note_and_an_approach(self):
|
||||
"""R-5.3-7: each missing piece is named, with the field that supplies it."""
|
||||
c = full(invariants=[], requirements=[], risk={}, approach=None)
|
||||
c = full(invariants=[], requirements=[], risk={"profile": "isolated"}, approach=None)
|
||||
text = " | ".join("%s -> %s" % m for m in assure.missing("integration", c, self.proj))
|
||||
for field in ('"invariants"', '"requirements"', '"risk"', '"approach"'):
|
||||
self.assertIn(field, text)
|
||||
@@ -518,6 +528,16 @@ class FlowTests(GateBase):
|
||||
self.assertEqual(a, "block")
|
||||
self.assertIn("bad", msg)
|
||||
|
||||
def test_the_send_back_shows_the_failing_test_not_only_the_end_of_the_output(self):
|
||||
"""R-5.6-1, R-5.6-4: the failure printed 300 lines above the end of the output is in the gate's message."""
|
||||
cmd = ("echo 'FAIL: test_needle (mod.T.test_needle)'; echo 'AssertionError: needle missing'; "
|
||||
"for i in $(seq 1 300); do echo \"summary $i\"; done; exit 1")
|
||||
self.write_contract(contract([check("t", cmd)]) | {"risk": {"profile": "isolated"}})
|
||||
a, msg = self.call()
|
||||
self.assertEqual(a, "block")
|
||||
self.assertIn("FAIL: test_needle (mod.T.test_needle)", msg)
|
||||
self.assertIn("AssertionError: needle missing", msg)
|
||||
|
||||
def test_a_check_over_the_budget_is_reported_not_passed(self):
|
||||
"""R-15-5: a check that cannot finish in time is not-run, never passed."""
|
||||
with open(os.path.join(self.tmp, "cfg"), "w"):
|
||||
|
||||
@@ -542,6 +542,34 @@ class Mechanisms(Base):
|
||||
self.assertEqual(len(cycle.routing_adjustments(self.proj)), 1)
|
||||
self.assertEqual(cycle.routing_adjustments(self.other_project()), [])
|
||||
|
||||
def test_a_promoted_routing_adjustment_changes_sisi_route_for_its_project_only(self):
|
||||
"""R-11.1-7, R-7.1-1: the reader of routing-adjustments.json is `sisi route`: a cycle's avoid entry
|
||||
moves the choice in its own project, names its learning in --explain, and leaves another project alone."""
|
||||
bindir = os.path.join(self.tmp, "bin")
|
||||
os.makedirs(bindir)
|
||||
tool = os.path.join(bindir, "muse")
|
||||
with open(tool, "w") as f:
|
||||
f.write('#!/bin/sh\nif [ "$1 $2" = "exec --list-models" ]; then echo beta-1; echo beta-2; fi\nexit 0\n')
|
||||
os.chmod(tool, 0o755)
|
||||
env = {"PATH": bindir}
|
||||
for m, price in (("beta-1", "1"), ("beta-2", "2")):
|
||||
r = self.sisi("workers", "fact", "muse/" + m, "--price", price, "--source", "fixture", env=env)
|
||||
self.assertEqual(r.returncode, 0, r.stderr)
|
||||
other = self.other_project()
|
||||
route = ("route", "--kind", "impl", "--difficulty", "2", "--explain")
|
||||
before, before_other = self.sisi(*route, env=env), self.sisi(*route, cwd=other, env=env)
|
||||
self.assertEqual(before.stdout.splitlines()[0], "muse/beta-1", before.stdout)
|
||||
self.assertEqual(before_other.stdout, before.stdout)
|
||||
self.propose()
|
||||
self.assertEqual(self.apply([{"action": "promote", "learning": "L-0001", "mechanism_kind": "routing",
|
||||
"kind": "impl", "avoid": "beta-1"}]).returncode, 0)
|
||||
after, after_other = self.sisi(*route, env=env), self.sisi(*route, cwd=other, env=env)
|
||||
self.assertEqual(after.stdout.splitlines()[0], "muse/beta-2", after.stdout)
|
||||
self.assertIn("learning L-0001", after.stdout)
|
||||
self.assertEqual(after_other.stdout, before_other.stdout)
|
||||
unrelated = self.sisi("route", "--kind", "review", "--difficulty", "2", env=env)
|
||||
self.assertEqual(unrelated.stdout.splitlines()[0], "muse/beta-1")
|
||||
|
||||
def test_earned_scope_widens_what_a_cycle_may_apply(self):
|
||||
"""R-11.6-2: once a learning has earned scope (two units, two projects) its risk adjustment
|
||||
reaches both projects and a rule it motivates needs no approval for reach alone."""
|
||||
@@ -929,6 +957,21 @@ class Store(Base):
|
||||
self.assertIn("prefer short plain reports", r.stdout)
|
||||
self.assertEqual(len(L.owner_statements()), 1)
|
||||
|
||||
def test_learn_says_what_it_stored_and_how_to_take_it_back(self):
|
||||
"""R-12-1: the receipt shows the stored text (secrets scrubbed), id, scope and a withdraw command that works."""
|
||||
out = self.sisi("learn", "--scope", "project", "prefer short plain reports, password=hunter2hunter2").stdout
|
||||
row = self.rows()[0]
|
||||
self.assertIn(row["id"], out)
|
||||
self.assertIn("scope: project", out)
|
||||
self.assertIn(row["observation"]["evidence"], out)
|
||||
self.assertNotIn("hunter2", out)
|
||||
cmd = [l for l in out.splitlines() if "sisi learn --withdraw" in l][0].split("sisi learn ", 1)[1]
|
||||
self.assertIn("--withdraw %s " % row["id"], cmd)
|
||||
import shlex
|
||||
r = self.sisi("learn", *shlex.split(cmd.replace("<why it was recorded by mistake>", "test")))
|
||||
self.assertEqual(r.returncode, 0, r.stderr)
|
||||
self.assertEqual(L.owner_statements(), [])
|
||||
|
||||
def test_learn_records_whether_the_owner_typed_it(self):
|
||||
"""A statement quoted from a human-typed message of the session transcript is `typed by the
|
||||
owner`; a relayed one, or none to check, is `relayed by an agent`. Never blocked."""
|
||||
@@ -976,7 +1019,7 @@ class Store(Base):
|
||||
root = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
|
||||
bad = []
|
||||
for n in sorted(os.listdir(os.path.join(root, "sisi"))):
|
||||
if not n.endswith(".py") or n == "gate.py": # gate.py's retro.lessons_block is the live gate seam
|
||||
if not n.endswith(".py"):
|
||||
continue
|
||||
with open(os.path.join(root, "sisi", n)) as f:
|
||||
for i, line in enumerate(f, 1):
|
||||
@@ -985,6 +1028,23 @@ class Store(Base):
|
||||
bad.append("%s:%d" % (n, i))
|
||||
self.assertEqual(bad, [])
|
||||
|
||||
def test_no_guarded_seams_between_modules_that_always_exist(self):
|
||||
"""Item 4: no `except ImportError` or `hasattr(module, ...)` probe stands in for a module of this
|
||||
package, and nothing names a removed seam. The one platform probe (fcntl, absent on Windows, in pdata) stays."""
|
||||
import re
|
||||
root = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
|
||||
bad = []
|
||||
for n in sorted(os.listdir(os.path.join(root, "sisi"))):
|
||||
if not n.endswith(".py"):
|
||||
continue
|
||||
with open(os.path.join(root, "sisi", n)) as f:
|
||||
for i, line in enumerate(f, 1):
|
||||
if n != "pdata.py" and re.search(r"except \(?ImportError|hasattr\((delivery|unit|gate|retro|learning|cycle)\b", line):
|
||||
bad.append("%s:%d" % (n, i))
|
||||
if re.search(r"retro\.(TEMPLATE|satisfied|lessons_block)|ensure_imported", line):
|
||||
bad.append("%s:%d" % (n, i))
|
||||
self.assertEqual(bad, [])
|
||||
|
||||
def test_no_resource_warnings_from_the_learning_commands(self):
|
||||
"""Item 13: file handles are closed; every learning command runs clean under -W always."""
|
||||
_contract(self)
|
||||
|
||||
@@ -80,6 +80,67 @@ class BriefTests(OrchCase):
|
||||
self.assertIn("Acceptance", r.stdout)
|
||||
self.assertIn("Files you may change", r.stdout)
|
||||
|
||||
def brief_with(self, **parts):
|
||||
"""valid_brief() with the text of some parts replaced; keys are the heading words."""
|
||||
text = valid_brief()
|
||||
heads = {"acceptance": "Acceptance", "verification": "Verification", "outcome": "Outcome and scope",
|
||||
"deliverables": "Deliverables and report format"}
|
||||
for key, body in parts.items():
|
||||
h = heads[key]
|
||||
start = text.index("## " + h)
|
||||
end = text.find("\n\n##", start)
|
||||
end = len(text) if end < 0 else end
|
||||
text = text[:start] + "## %s\n%s" % (h, body) + text[end:]
|
||||
return text
|
||||
|
||||
def advice(self, text):
|
||||
p = os.path.join(self.proj, "b.md")
|
||||
open(p, "w").write(text)
|
||||
r = self.sisi("delegate", "check", p, env=self.env())
|
||||
self.assertEqual(r.returncode, 0, r.stdout) # advice never blocks
|
||||
self.assertLessEqual(len(r.stdout.splitlines()), 20)
|
||||
return r.stdout
|
||||
|
||||
def test_brief_template_carries_what_the_rebuild_learned(self):
|
||||
"""R-7.5-1: the template's guidance names the six cases, and an unfilled template is still unfilled."""
|
||||
t = self.sisi("delegate", "brief", env=self.env()).stdout
|
||||
for phrase in ("a number with the command that measures it", "name that reader", "different worker",
|
||||
"held-out", "abuse cases", "forge the field that marks trust", "unrelated reason",
|
||||
"30 times", "in parallel", "done / next"):
|
||||
self.assertIn(phrase, t)
|
||||
p = os.path.join(self.proj, "t.md")
|
||||
open(p, "w").write(t)
|
||||
r = self.sisi("delegate", "check", p, env=self.env())
|
||||
self.assertNotEqual(r.returncode, 0)
|
||||
self.assertNotIn("advice", r.stdout) # the template's own guidance is not the author's words
|
||||
|
||||
def test_check_flags_each_case_and_stays_quiet_on_a_clean_brief(self):
|
||||
"""R-7.5-1, abuse: each flag has a brief that trips it and a near-identical one that does not."""
|
||||
self.assertNotIn("advice", self.advice(valid_brief()))
|
||||
cases = {
|
||||
"acceptance": (dict(acceptance="Keep the report short and fast."), "Acceptance says"),
|
||||
"gate": (dict(outcome="Add an approval gate for deploys."), "abuse cases"),
|
||||
"tests": (dict(verification="Write tests for the parser."), "repeat run"),
|
||||
"reader": (dict(outcome="Write the index file for other modules to read."), "no reader is named"),
|
||||
"labels": (dict(outcome="Build a matcher and a labelled set of examples."), "different worker"),
|
||||
"commits": (dict(deliverables="1. the parser\n2. the writer"), "commit per item"),
|
||||
}
|
||||
for name, (parts, flag) in cases.items():
|
||||
with self.subTest(name):
|
||||
self.assertIn(flag, self.advice(self.brief_with(**parts)))
|
||||
fixed = {
|
||||
"acceptance": dict(acceptance="The report is under 40 lines (`wc -l report.md`) and the check runs in 5 s."),
|
||||
"gate": dict(outcome="Add an approval gate for deploys.", verification="Abuse cases: omit the trigger field."),
|
||||
"tests": dict(verification="Write tests; run the new module 30 times in parallel."),
|
||||
"reader": dict(outcome="Write the index for other modules to read; the reader is `sisi/search.py`."),
|
||||
"labels": dict(outcome="Build a matcher; the labelled set comes from a different worker."),
|
||||
"commits": dict(deliverables="1. the parser\n2. the writer\nCommit after each item with a done / next note."),
|
||||
}
|
||||
for name, parts in fixed.items():
|
||||
with self.subTest("fixed " + name):
|
||||
self.assertNotIn("advice", self.advice(self.brief_with(**parts)))
|
||||
self.assertLessEqual(len(self.advice(self.brief_with(**{k: v for c in cases.values() for k, v in c[0].items()})).splitlines()), 20)
|
||||
|
||||
def test_check_passes_a_full_brief(self):
|
||||
p = os.path.join(self.proj, "full.md")
|
||||
open(p, "w").write(valid_brief())
|
||||
|
||||
@@ -103,6 +103,54 @@ class PublishableTree(unittest.TestCase):
|
||||
self.assertFalse(os.path.exists(os.path.join(REPO, "docs", "superpowers")))
|
||||
|
||||
|
||||
class HelpIsGrouped(SisiCase):
|
||||
"""`sisi help` is for its readers: four headings, one line per command, short enough to read at a glance."""
|
||||
|
||||
HEADINGS = ["For the person", "For the agent at work", "Hooks (the tools call these)", "Maintaining sisi"]
|
||||
|
||||
def dispatched(self):
|
||||
"""Every command name the dispatcher in cli.main compares `cmd` to, plus the data-layer subcommands."""
|
||||
import ast, argparse
|
||||
from sisi import cli, learn_cli
|
||||
tree = ast.parse(open(cli.__file__, encoding="utf-8").read())
|
||||
main = next(n for n in tree.body if isinstance(n, ast.FunctionDef) and n.name == "main")
|
||||
found = set()
|
||||
for n in ast.walk(main):
|
||||
if isinstance(n, ast.Compare) and isinstance(n.left, ast.Name) and n.left.id == "cmd":
|
||||
for c in n.comparators:
|
||||
for k in (c.elts if isinstance(c, ast.Tuple) else [c]):
|
||||
if isinstance(k, ast.Constant) and isinstance(k.value, str) and not k.value.startswith("-"):
|
||||
found.add(k.value)
|
||||
ap = argparse.ArgumentParser()
|
||||
sub = ap.add_subparsers()
|
||||
learn_cli.register(sub)
|
||||
return found | set(sub.choices)
|
||||
|
||||
def test_the_whole_help_fits_60_lines_of_110_characters_under_four_headings(self):
|
||||
out = self.sisi("help").stdout
|
||||
lines = out.splitlines()
|
||||
self.assertLessEqual(len(lines), 60)
|
||||
self.assertLessEqual(max(map(len, lines)), 110)
|
||||
at = [lines.index(h) for h in self.HEADINGS]
|
||||
self.assertEqual(at, sorted(at))
|
||||
|
||||
def test_every_command_the_dispatcher_accepts_is_listed_once_and_nothing_else(self):
|
||||
from sisi import helptext
|
||||
listed = helptext.names()
|
||||
self.assertEqual(len(listed), len(set(listed)), "a command is listed twice")
|
||||
self.assertEqual(set(listed), self.dispatched())
|
||||
text = self.sisi("help").stdout
|
||||
for name in listed:
|
||||
self.assertTrue(re.search(r"(^ sisi |\| |, )%s\b" % re.escape(name), text, re.M), name)
|
||||
|
||||
def test_the_long_explanation_is_one_help_away(self):
|
||||
a, b = self.sisi("help", "retro"), self.sisi("retro", "--help")
|
||||
self.assertEqual((a.returncode, b.returncode), (0, 0))
|
||||
self.assertEqual(a.stdout, b.stdout)
|
||||
self.assertIn("--disposition promote|record|drop", a.stdout)
|
||||
self.assertEqual(self.sisi("help", "nonesuch").returncode, 64)
|
||||
|
||||
|
||||
NOT_BUILT = {"build", "inbox"} # designed in docs/design.md, named in the README as not built
|
||||
|
||||
|
||||
|
||||
+2
-1
@@ -515,8 +515,9 @@ class StatusTests(UnitCase):
|
||||
helptext = self.sisi("help").stdout
|
||||
for gone in ("sisi time", "sisi scoreboard", "sisi improve", "sisi backlog"):
|
||||
self.assertNotIn(gone, helptext)
|
||||
for kept in ("sisi unit close", "sisi unit pause", "sisi unit show", "sisi status"):
|
||||
for kept in ("sisi unit close|pause|show|list", "sisi status"):
|
||||
self.assertIn(kept, helptext)
|
||||
self.assertIn("sisi unit pause", self.sisi("help", "unit").stdout)
|
||||
for cmd in ("time", "scoreboard"):
|
||||
self.assertNotEqual(self.sisi(cmd).returncode, 0, cmd)
|
||||
|
||||
|
||||
@@ -264,7 +264,7 @@ class NothingUnrunIsEverPassedTests(SisiCase):
|
||||
if wc:
|
||||
x["when_changed"] = wc
|
||||
return x
|
||||
c = {"id": "t", "goal": "g", "assumptions": [], "questions": [], "invariants": [],
|
||||
c = {"id": "t", "goal": "g", "risk": {"profile": "isolated"}, "assumptions": [], "questions": [], "invariants": [],
|
||||
"checks": [mk("a", "f_a", None, True), mk("b", "f_b", ["f_b*"], True),
|
||||
mk("c", "f_c", ["nothing/**"], True), mk("d", "f_d", None, False)]}
|
||||
self.write_contract(c, d)
|
||||
|
||||
+34
-1
@@ -301,9 +301,42 @@ class LintCrossCheckTests(LibCase):
|
||||
self.assertIn("warning(s)", r.stdout)
|
||||
|
||||
|
||||
class RepeatUnderLoadTests(SisiCase):
|
||||
"""R-5.6-1: the library has an entry for repeating a test under parallel load, its command works with the
|
||||
standard library alone, and the two recipes say what this rebuild learned."""
|
||||
|
||||
def test_the_entry_is_in_the_library_and_its_command_separates_stable_from_order_dependent_tests(self):
|
||||
import subprocess
|
||||
r = self.sisi("verifiers", "show", "repeat-under-parallel-load")
|
||||
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
|
||||
self.assertIn("xargs -P 8", r.stdout)
|
||||
d = os.path.join(self.tmp, "rp")
|
||||
os.makedirs(d)
|
||||
with open(os.path.join(d, "test_mod.py"), "w") as f:
|
||||
f.write("import os, time, unittest\n"
|
||||
"class Stable(unittest.TestCase):\n def test_ok(self):\n self.assertEqual(1 + 1, 2)\n"
|
||||
"class Shared(unittest.TestCase):\n def test_shared_path(self):\n"
|
||||
" p = os.path.join(os.path.dirname(__file__), 'shared.txt')\n"
|
||||
" open(p, 'w').write(str(os.getpid())); time.sleep(0.05)\n"
|
||||
" self.assertEqual(open(p).read(), str(os.getpid()))\n")
|
||||
cmd = "seq 30 | xargs -P 8 -I{} python3 -m unittest -q test_mod.%s"
|
||||
run = lambda name: subprocess.run(cmd % name, shell=True, cwd=d, capture_output=True).returncode
|
||||
self.assertEqual(run("Stable"), 0)
|
||||
self.assertNotEqual(run("Shared"), 0)
|
||||
|
||||
def test_the_recipes_name_the_first_increment_and_the_scored_heuristic(self):
|
||||
root = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
|
||||
for name in ("feature", "new-product"):
|
||||
text = open(os.path.join(root, "done", name + ".md"), encoding="utf-8").read()
|
||||
self.assertIn("first usable increment", text, name)
|
||||
self.assertIn("labelled as an estimate", text, name)
|
||||
self.assertIn("labels a different worker wrote", text, name)
|
||||
self.assertIn("repeat-under-parallel-load", text, name)
|
||||
|
||||
|
||||
class CoreMdTests(SisiCase):
|
||||
def test_help_lists_new_commands(self):
|
||||
out = self.sisi("help").stdout
|
||||
out = self.sisi("help").stdout + self.sisi("help", "verifiers").stdout + self.sisi("help", "done").stdout
|
||||
for w in ("verifiers show", "verifiers for", "verifiers doctor | lint", "sisi done", "done for"):
|
||||
self.assertIn(w, out)
|
||||
|
||||
|
||||
@@ -2,6 +2,64 @@ import json, unittest
|
||||
from support import *
|
||||
|
||||
|
||||
class EvidenceTests(SisiCase):
|
||||
"""R-5.6-1, R-5.6-4: a failed check keeps the lines that identify the failure, not only the tail of its output."""
|
||||
|
||||
NOISE = "for i in $(seq 1 300); do echo \"summary noise $i\"; done"
|
||||
|
||||
def test_a_failure_300_lines_above_the_end_is_in_the_stored_result_and_the_report(self):
|
||||
cmd = "echo 'FAIL: test_alpha (mod.T.test_alpha)'; echo 'AssertionError: 1 != 2'; %s; exit 1" % self.NOISE
|
||||
r = self.sisi("verify") if self.write_contract(contract([check("t", cmd)])) is None else None
|
||||
self.assertEqual(r.returncode, 1)
|
||||
row = [x for x in self.results() if x["check"] == "t"][0]
|
||||
self.assertEqual(row["status"], "failed")
|
||||
self.assertIn("FAIL: test_alpha (mod.T.test_alpha)", row["evidence"])
|
||||
self.assertIn("AssertionError: 1 != 2", row["evidence"])
|
||||
self.assertLess(len(row["evidence"]), 3100)
|
||||
shown = r.stdout[r.stdout.index("FAILED:"):]
|
||||
self.assertIn("test_alpha", shown)
|
||||
self.assertLess(shown.index("test_alpha"), shown.index("summary noise 300"))
|
||||
|
||||
def test_each_known_runner_keeps_its_failing_test_names(self):
|
||||
from sisi import verify as V
|
||||
outputs = {
|
||||
"unittest": ("FAIL: test_a (m.T.test_a)\n----\nTraceback\nAssertionError: x\n" + "ok\n" * 200 + "FAILED (failures=1)", "test_a (m.T.test_a)"),
|
||||
"pytest": ("_____ test_b _____\nE assert 1 == 2\n" + "x\n" * 200 + "FAILED tests/t.py::test_b - assert 1 == 2", "tests/t.py::test_b"),
|
||||
"cargo": ("test tests::c ... FAILED\n---- tests::c stdout ----\nthread 'tests::c' panicked at src/l.rs:1:1:\n" + "x\n" * 200 + "test result: FAILED", "tests::c"),
|
||||
"go": ("--- FAIL: TestD (0.00s)\n d_test.go:9: want 1 got 2\n" + "x\n" * 200 + "FAIL\tpkg", "TestD"),
|
||||
"jest": (" ● suite › case e\n Expected: 1\n Received: 2\n" + "x\n" * 200 + "Tests: 1 failed", "case e"),
|
||||
}
|
||||
for name, (text, want) in outputs.items():
|
||||
with self.subTest(name):
|
||||
ev = V.evidence(text)
|
||||
self.assertIn(want, ev)
|
||||
self.assertNotIn("\nx\nx\nx", ev)
|
||||
|
||||
def test_unknown_output_keeps_the_first_and_last_30_lines_bounded_and_scrubbed(self):
|
||||
from sisi import verify as V
|
||||
text = "\n".join(["line %d" % i for i in range(1, 401)] + ["password=hunter2hunter2"])
|
||||
ev = V.evidence(text)
|
||||
self.assertIn("line 1\n", ev + "\n")
|
||||
self.assertIn("line 30\n", ev + "\n")
|
||||
self.assertNotIn("line 31\n", ev + "\n")
|
||||
self.assertIn("line 400", ev)
|
||||
self.assertNotIn("hunter2", ev)
|
||||
self.assertLessEqual(len(V.evidence("y" * 100000)), V.EVIDENCE_CHARS)
|
||||
|
||||
def test_a_timeout_keeps_what_it_had_printed(self):
|
||||
c = contract([check("slow", "echo 'FAIL: test_slow (m.T.test_slow)'; sleep 5", timeout_s=0.5)])
|
||||
self.write_contract(c)
|
||||
self.sisi("verify")
|
||||
row = [x for x in self.results() if x["check"] == "slow"][0]
|
||||
self.assertEqual(row["status"], "not-run")
|
||||
self.assertIn("test_slow", row["evidence"])
|
||||
|
||||
def test_a_passing_check_stores_no_evidence(self):
|
||||
self.write_contract(contract([check("ok", "echo fine; test -d .")]))
|
||||
self.sisi("verify")
|
||||
self.assertEqual([x["evidence"] for x in self.results() if x["check"] == "ok"], [""])
|
||||
|
||||
|
||||
class VerifyTests(SisiCase):
|
||||
def run_verify(self, c, *extra):
|
||||
self.write_contract(c)
|
||||
|
||||
+32
-1
@@ -19,6 +19,37 @@ def snapshot(root):
|
||||
return snap
|
||||
|
||||
|
||||
def remove_hooks(obj):
|
||||
"""Test oracle: strip our hook groups from a settings object (the product removes them structurally)."""
|
||||
changed = False
|
||||
hooks = obj.get("hooks")
|
||||
if not isinstance(hooks, dict):
|
||||
return False
|
||||
for ev, sub in (("SessionStart", "tick"), ("UserPromptSubmit", "prompt"), ("Stop", "gate"), ("SubagentStop", "gate"),
|
||||
("PreToolUse", "watch"), ("PostToolUse", "watch")):
|
||||
groups = hooks.get(ev)
|
||||
if not isinstance(groups, list):
|
||||
continue
|
||||
keep, ev_changed = [], False
|
||||
for g in groups:
|
||||
hs = g.get("hooks") if isinstance(g, dict) else None
|
||||
if isinstance(hs, list) and any(wiring._is_ours(h, sub) for h in hs):
|
||||
changed = ev_changed = True
|
||||
rest = [h for h in hs if not wiring._is_ours(h, sub)]
|
||||
if rest:
|
||||
g = dict(g, hooks=rest)
|
||||
else:
|
||||
continue
|
||||
keep.append(g)
|
||||
if keep:
|
||||
hooks[ev] = keep
|
||||
elif ev_changed:
|
||||
del hooks[ev]
|
||||
if changed and not hooks:
|
||||
del obj["hooks"]
|
||||
return changed
|
||||
|
||||
|
||||
class WiringBase(SisiCase):
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
@@ -127,7 +158,7 @@ class WiringPropertyTests(WiringBase):
|
||||
if st is not None and st.strip():
|
||||
orig = json.loads(st)
|
||||
now = json.loads(self.path(".claude/settings.json") and open(self.path(".claude/settings.json"), "rb").read())
|
||||
wiring.remove_hooks(now)
|
||||
remove_hooks(now)
|
||||
|
||||
def norm(d): # empty hook lists/objects may legitimately disappear in the structural path
|
||||
h = d.get("hooks")
|
||||
|
||||
@@ -88,37 +88,6 @@ class DiscoveryTests(WorkerCase):
|
||||
self.assertFalse(tools["cursor-agent"]["usable"])
|
||||
|
||||
|
||||
class LedgerImportTests(WorkerCase):
|
||||
def test_existing_ledger_imported_once_losslessly(self):
|
||||
src = os.path.join(self.tmp, "orch-log.jsonl")
|
||||
rows = [
|
||||
{"kind": "attempt", "id": "abc123", "ts": 1700000000, "project": "p", "type": "impl",
|
||||
"difficulty": 2, "worker": "beta-1", "outcome": "accepted", "check": "tests",
|
||||
"minutes": 3, "tokens": None, "retry_of": None, "note": "keep me", "extra": [1, 2]},
|
||||
{"kind": "attempt", "id": "def456", "ts": 1700000100, "project": "p", "type": "impl",
|
||||
"difficulty": 2, "worker": "beta-1", "outcome": "rejected", "check": "read",
|
||||
"minutes": 4, "tokens": 9, "retry_of": "abc123", "note": None},
|
||||
{"kind": "amend", "id": "abc123", "ts": 1700000200, "note": "later wrong"},
|
||||
]
|
||||
with open(src, "w") as f:
|
||||
for row in rows:
|
||||
f.write(json.dumps(row) + "\n")
|
||||
before = open(src).read()
|
||||
r = self.sisi("workers", env=self.env(SISI_LEDGER=src))
|
||||
self.assertEqual(r.returncode, 0, r.stderr)
|
||||
self.assertIn("imported 3 rows", r.stdout)
|
||||
self.assertEqual(open(src).read(), before, "the original ledger must not be modified")
|
||||
got = [json.loads(l) for l in open(os.path.join(self.data, "delegations.jsonl"))]
|
||||
self.assertEqual(len(got), 3)
|
||||
for want, have in zip(rows, got):
|
||||
for k, v in want.items():
|
||||
self.assertEqual(have.get(k), v, k)
|
||||
# a second run imports nothing more
|
||||
self.sisi("workers", env=self.env(SISI_LEDGER=src))
|
||||
got2 = [json.loads(l) for l in open(os.path.join(self.data, "delegations.jsonl"))]
|
||||
self.assertEqual(len(got2), 3)
|
||||
|
||||
|
||||
class RouteTests(WorkerCase):
|
||||
def test_route_explains_and_skips_contributor_and_logged_out(self):
|
||||
r = self.sisi("route", "--kind", "impl", "--difficulty", "2", "--explain", env=self.env())
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
---
|
||||
id: repeat-under-parallel-load
|
||||
title: Repeat a test about 30 times with copies running in parallel
|
||||
answers: Does this test still pass when copies of it run at the same time and the machine is busy?
|
||||
rung: 3
|
||||
section: test-quality
|
||||
languages: any
|
||||
kinds: general, concurrency
|
||||
cost: low
|
||||
detect: xargs --version
|
||||
ran_here: yes
|
||||
verified: ran
|
||||
---
|
||||
|
||||
## Use when
|
||||
- You wrote a new test module and are about to report it as passing.
|
||||
- A test passes alone and fails in the full suite, or fails once and passes on rerun.
|
||||
- The test uses time, a fixed path or port, a shared directory, the current directory, or random data.
|
||||
|
||||
## Do not use when
|
||||
- The failure is deterministic. Fix it; do not repeat it.
|
||||
- You need to find a race in the code itself. Repetition only samples; use a model checker or a stress tool built for that.
|
||||
|
||||
## Set up
|
||||
- Nothing beyond `xargs` (GNU or BSD) and `seq`, and the standard test runner of the language. The tests must be hermetic: each copy gets its own temporary directory, state and ports.
|
||||
|
||||
## Minimal example
|
||||
Python's standard library, a module `test_mod.py`:
|
||||
|
||||
python3 -m unittest -q test_mod
|
||||
|
||||
## Run
|
||||
Thirty runs, eight at a time. `xargs` exits 123 if any run exits non-zero:
|
||||
|
||||
seq 30 | xargs -P 8 -I{} python3 -m unittest -q test_mod
|
||||
|
||||
Passing looks like: exit status 0 and no output from unittest. Failure shows as exit 123 with the failing copy's output above it. Reproduce one failure alone, then under load again. Use `-P` near the number of processors, or higher, to make timing worse; run the whole suite as one of the parallel copies when order matters.
|
||||
|
||||
## As a contract check
|
||||
{"id": "repeat-parallel", "claim": "The new test module passes 30 runs, 8 at a time", "kind": "general", "rung": 3, "cmd": "seq 30 | xargs -P 8 -I{} python3 -m unittest -q test_mod", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 900}
|
||||
|
||||
## What a pass does not prove
|
||||
- Thirty passes bound a flake rate only roughly: a 1-in-20 flake can still pass thirty runs. Raise the count for anything that matters.
|
||||
- Copies that already isolate their state cannot show a shared-state bug between them; check that the test really shares something (a path, a port) when you suspect it.
|
||||
- Check that the module name matched tests (Python 3.12 and later exit 5 when a module has no tests; older versions exit 0, so check with `-v` once).
|
||||
- A pass says nothing about the code under test being correct, only that the test is stable.
|
||||
Reference in new issue
Block a user