Risk profiles and relevance: sisi risk, the design section retired, hooks print only what a session can act on, recipes matched by structured tags, a recipe for features

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-23 11:09:26 -07:00
commit 8f36c5b527
25 files changed
+1434 -857

No files matched your search

+2 -11
View File
@@ -7,17 +7,8 @@ commands mentioned here.
## 1. Choose the approach from the goal {#choose-the-approach}
Before sizeable work, think from the goal and the human's standing principles (`sisi oracle`)
to what they imply. Fill the contract's `design` section first (`sisi design` prints the
principles and the questions):
- what the goal and the principles imply that the request did not spell out;
- what the environment, the tool or the existing system already provides - use that instead
of building it, and give evidence it exists;
- at least two other approaches, one line each on cost and risk;
- the one chosen, and why it is the one the human would pick;
- for each principle, the objection the human would raise and how the design answers it, or
why it does not apply;
- an independent attack on the design as the human would make it, and what changed.
to what they imply: what the request did not spell out, and what the environment, the tool or
the existing system already provides - use that instead of building it.
Why: the human should never have to state a consequence of something they already said. A
well-built answer to the wrong approach wastes everything spent building it.
+241
View File
@@ -0,0 +1,241 @@
{
"agent-tool-surface": {
"kinds": [
"general"
],
"tags": [
"agent",
"mcp",
"tool surface",
"functions an agent calls"
]
},
"bugfix": {
"kinds": [
"general"
],
"tags": [
"bug",
"defect",
"broken",
"wrong behaviour",
"crash fix",
"off-by-one",
"does not work"
]
},
"cli-tool": {
"kinds": [
"general"
],
"tags": [
"command line",
"shell tool",
"cli",
"arguments",
"exit codes"
]
},
"concurrent-code": {
"kinds": [
"concurrency"
],
"tags": [
"concurrency"
]
},
"config-or-infra-change": {
"kinds": [
"general"
],
"tags": [
"ci",
"build files",
"deploy",
"deployment",
"configuration",
"infrastructure",
"container"
]
},
"data-migration": {
"kinds": [
"migration"
],
"tags": [
"migration"
]
},
"dependency-upgrade": {
"kinds": [
"general"
],
"tags": [
"upgrade dependency",
"new version of a library",
"toolchain upgrade",
"bump",
"dependency",
"upgrade"
]
},
"docs-change": {
"kinds": [
"general"
],
"tags": [
"documentation",
"readme",
"guide",
"runbook",
"docs"
]
},
"feature": {
"kinds": [
"general"
],
"tags": [
"new capability",
"new feature",
"add printing",
"printing",
"paper size",
"map printing",
"add support"
]
},
"native-gui-change": {
"kinds": [
"ui"
],
"tags": [
"desktop app",
"mobile app",
"native window",
"widget"
]
},
"new-library": {
"kinds": [
"general"
],
"tags": [
"new library",
"new package",
"public interface",
"module other code uses"
]
},
"new-product": {
"kinds": [
"general"
],
"tags": [
"new product",
"whole new app",
"from scratch",
"new service for users"
]
},
"numeric-or-financial-core": {
"kinds": [
"money"
],
"tags": [
"money"
]
},
"parser-or-codec": {
"kinds": [
"parsing"
],
"tags": [
"parsing"
]
},
"performance-work": {
"kinds": [
"general"
],
"tags": [
"performance",
"slow",
"faster",
"speed up"
]
},
"refactor": {
"kinds": [
"general"
],
"tags": [
"refactor",
"restructure",
"tidy up",
"rename internals",
"without changing behaviour",
"change the structure",
"without changing what it does"
]
},
"release": {
"kinds": [
"general"
],
"tags": [
"release",
"tag",
"publish",
"ship it",
"version",
"write the release",
"tag the version",
"new release",
"tag it",
"tag and changelog"
]
},
"security-fix": {
"kinds": [
"general"
],
"tags": [
"security",
"vulnerability",
"injection"
]
},
"service-api": {
"kinds": [
"general"
],
"tags": [
"http api",
"server endpoints",
"rest api",
"service"
]
},
"storage-engine": {
"kinds": [
"general"
],
"tags": [
"storage",
"database layer",
"persistent format",
"crash recovery"
]
},
"web-ui-change": {
"kinds": [
"ui"
],
"tags": [
"ui",
"web page",
"browser"
]
}
}
+74
View File
@@ -0,0 +1,74 @@
{
"profiles": ["trivial", "isolated", "logic", "integration", "data", "critical", "release"],
"requirements": {
"trivial": {"contract": false, "checks": "the diff; a targeted check when one exists", "requirement_model": false, "risk_note": false, "independent_evidence": false, "retro": "only on an anomaly (two send-backs, or a human correction)"},
"isolated": {"contract": true, "checks": "at least one that is not vacuous", "requirement_model": false, "risk_note": false, "independent_evidence": false, "retro": "yes"},
"logic": {"contract": true, "checks": "as isolated, each with covers", "requirement_model": false, "risk_note": false, "independent_evidence": false, "retro": "yes"},
"integration": {"contract": true, "checks": "as logic, plus invariants", "requirement_model": true, "risk_note": true, "independent_evidence": false, "retro": "yes"},
"data": {"contract": true, "checks": "as integration", "requirement_model": true, "risk_note": true, "independent_evidence": true, "retro": "yes"},
"critical": {"contract": true, "checks": "as integration", "requirement_model": true, "risk_note": true, "independent_evidence": true, "retro": "yes"},
"release": {"contract": true, "checks": "every check (--all)", "requirement_model": true, "risk_note": true, "independent_evidence": true, "retro": "yes"}
},
"patterns": [
{"glob": "**/migrations/**", "profile": "data", "reason": "database migration changes stored data shape"},
{"glob": "**/migration/**", "profile": "data", "reason": "data migration code"},
{"glob": "**/*.sql", "profile": "data", "reason": "SQL changes stored data or schema"},
{"glob": "**/schema/**", "profile": "data", "reason": "schema definition"},
{"glob": "**/*.schema.*", "profile": "data", "reason": "schema definition"},
{"glob": "**/alembic/**", "profile": "data", "reason": "database migration history"},
{"glob": "**/db/**", "profile": "data", "reason": "persistence layer"},
{"glob": "**/storage/**", "profile": "data", "reason": "persistence layer"},
{"glob": "**/persist*/**", "profile": "data", "reason": "persistence layer"},
{"glob": "**/auth/**", "profile": "critical", "reason": "authorization or authentication code"},
{"glob": "**/*auth*", "profile": "critical", "reason": "authorization or authentication code"},
{"glob": "**/*secret*", "profile": "critical", "reason": "secret handling"},
{"glob": "**/*crypto*", "profile": "critical", "reason": "cryptography"},
{"glob": "**/*encrypt*", "profile": "critical", "reason": "cryptography"},
{"glob": "**/*payment*", "profile": "critical", "reason": "payments move money"},
{"glob": "**/*billing*", "profile": "critical", "reason": "billing moves money"},
{"glob": "**/*mutex*", "profile": "critical", "reason": "concurrency primitive"},
{"glob": "**/*semaphore*", "profile": "critical", "reason": "concurrency primitive"},
{"glob": "**/*lock*", "profile": "critical", "reason": "concurrency primitive"},
{"glob": "**/hooks/**", "profile": "critical", "reason": "hook wiring runs on every session"},
{"glob": "**/*hook*", "profile": "critical", "reason": "hook wiring runs automatically"},
{"glob": "**/install*", "profile": "critical", "reason": "installer changes the user's machine"},
{"glob": "install*", "profile": "critical", "reason": "installer changes the user's machine"},
{"glob": "**/setup.py", "profile": "critical", "reason": "installer runs at install time"},
{"glob": "**/PKGBUILD", "profile": "critical", "reason": "package build script runs as root tooling"},
{"glob": "VERSION", "profile": "release", "reason": "version marker for a release"},
{"glob": "**/release/**", "profile": "release", "reason": "release machinery"},
{"glob": "**/*release*", "profile": "release", "reason": "release machinery"},
{"glob": "**/api/**", "profile": "integration", "reason": "public interface surface"},
{"glob": "**/public/**", "profile": "integration", "reason": "public interface surface"},
{"glob": "include/**", "profile": "integration", "reason": "public headers are an interface"},
{"glob": "**/parser/**", "profile": "logic", "reason": "parsing logic has a broad input space"},
{"glob": "**/*pars*", "profile": "logic", "reason": "parsing logic has a broad input space"},
{"glob": "**/*lexer*", "profile": "logic", "reason": "lexing logic has a broad input space"},
{"glob": "**/*codec*", "profile": "logic", "reason": "encode/decode logic"},
{"glob": "**/money/**", "profile": "logic", "reason": "money arithmetic must be exact"},
{"glob": "**/*money*", "profile": "logic", "reason": "money arithmetic must be exact"},
{"glob": "**/*rounding*", "profile": "logic", "reason": "rounding rules decide money"},
{"glob": "**/*pricing*", "profile": "logic", "reason": "pricing arithmetic"},
{"glob": "**/algo*/**", "profile": "logic", "reason": "algorithmic logic"},
{"glob": "**/*algorithm*", "profile": "logic", "reason": "algorithmic logic"},
{"glob": "**/*state-machine*", "profile": "logic", "reason": "state machine transitions"},
{"glob": "**/*statemachine*", "profile": "logic", "reason": "state machine transitions"},
{"glob": "**/*.md", "profile": "trivial", "reason": "documentation only"},
{"glob": "**/*.txt", "profile": "trivial", "reason": "plain text only"},
{"glob": "**/*.rst", "profile": "trivial", "reason": "documentation only"},
{"glob": "docs/**", "profile": "trivial", "reason": "documentation only"},
{"glob": "**/*.css", "profile": "trivial", "reason": "styling only"},
{"glob": "**/*.scss", "profile": "trivial", "reason": "styling only"},
{"keyword": "migration", "profile": "data", "reason": "diff mentions a data migration"},
{"keyword": "schema change", "profile": "data", "reason": "diff changes a schema"},
{"keyword": "alter table", "profile": "data", "reason": "diff alters stored data"},
{"keyword": "password", "profile": "critical", "reason": "diff handles credentials"},
{"keyword": "secret", "profile": "critical", "reason": "diff handles secrets"},
{"keyword": "encrypt", "profile": "critical", "reason": "diff uses cryptography"},
{"keyword": "authorize", "profile": "critical", "reason": "diff makes authorization decisions"},
{"keyword": "authentication", "profile": "critical", "reason": "diff handles authentication"},
{"keyword": "payment", "profile": "critical", "reason": "diff moves money"},
{"keyword": "mutex", "profile": "critical", "reason": "diff uses a concurrency primitive"},
{"keyword": "release candidate", "profile": "release", "reason": "diff prepares a release"}
]
}
+316
View File
@@ -0,0 +1,316 @@
{
"groups": [
{
"tag": "concurrency",
"kinds": [
"concurrency"
],
"sections": [
"concurrency"
],
"terms": [
"race condition",
"data race",
"race",
"deadlock",
"thread",
"threads",
"threaded",
"parallel",
"concurrent",
"concurrency",
"async",
"asynchronous",
"shared state",
"shared memory",
"lock contention",
"synchronisation",
"synchronization",
"goroutine",
"goroutines",
"interleaving",
"flaky under load",
"shared",
"at once",
"at the same time",
"losing each other",
"background jobs"
]
},
{
"tag": "parsing",
"kinds": [
"parsing"
],
"sections": [
"many-inputs"
],
"terms": [
"parser",
"parsing",
"parse",
"malformed",
"csv",
"tsv",
"delimited",
"invalid input",
"hostile input",
"corrupt input",
"strange input",
"codec",
"serialise",
"serialize",
"deserialise",
"deserialize",
"lexer",
"file format",
"spreadsheet file"
]
},
{
"tag": "fuzzing",
"kinds": [],
"sections": [
"many-inputs"
],
"terms": [
"fuzz",
"fuzzing",
"fuzzer",
"random inputs",
"generated inputs",
"inputs i did not think of",
"any input",
"crash on input",
"hang on input"
]
},
{
"tag": "property",
"kinds": [],
"sections": [
"many-inputs",
"prove"
],
"terms": [
"property",
"properties",
"for every input",
"for all inputs",
"holds for",
"invariant holds",
"law holds",
"generated cases"
]
},
{
"tag": "money",
"kinds": [
"money"
],
"sections": [],
"terms": [
"money",
"rounding",
"round",
"price",
"pricing",
"prices",
"tax",
"currency",
"cents",
"invoice",
"invoices",
"financial",
"ledger",
"interest",
"charges",
"charge",
"amounts",
"totals",
"balance"
]
},
{
"tag": "state-machine",
"kinds": [
"state-machine"
],
"sections": [
"design"
],
"terms": [
"state machine",
"states",
"transitions",
"workflow states",
"lifecycle states",
"status machine"
]
},
{
"tag": "migration",
"kinds": [
"migration"
],
"sections": [],
"terms": [
"migration",
"migrate",
"migrating",
"schema change",
"old data",
"existing records",
"upgrade data",
"stored data"
]
},
{
"tag": "ui",
"kinds": [
"ui"
],
"sections": [
"real-world",
"regression"
],
"terms": [
"screen",
"button",
"component",
"color",
"colour",
"accent",
"dark mode",
"browser",
"web page",
"interface look",
"looks",
"visual",
"window",
"dialog",
"widget",
"keyboard",
"screen reader",
"accessibility",
"form"
]
},
{
"tag": "security",
"kinds": [],
"sections": [
"safety"
],
"terms": [
"vulnerability",
"injection",
"access control",
"leaked secret",
"unsafe deserialisation",
"exploit",
"attacker",
"permission check",
"way in",
"get in",
"without logging in"
]
},
{
"tag": "performance",
"kinds": [],
"sections": [],
"terms": [
"slow",
"fast",
"faster",
"performance",
"latency",
"speed",
"build is slow",
"takes too long",
"sluggish"
]
},
{
"tag": "regression",
"kinds": [],
"sections": [
"regression"
],
"terms": [
"nothing else changed",
"still works",
"as before",
"regression",
"broke before",
"existing behaviour",
"identically",
"nothing else broke",
"worked before",
"tidy-up",
"tidy up"
]
},
{
"tag": "service",
"kinds": [],
"sections": [
"real-world"
],
"terms": [
"service",
"endpoint",
"endpoints",
"caller",
"callers"
]
},
{
"tag": "dependency",
"kinds": [],
"sections": [],
"terms": [
"major version",
"next major version",
"toolchain upgrade",
"new version of a library"
]
}
],
"languages": {
"python": [
"python"
],
"rust": [
"rust"
],
"go": [
"go",
"golang"
],
"java": [
"java"
],
"javascript": [
"javascript",
"node"
],
"typescript": [
"typescript"
],
"c": [
"c"
],
"cpp": [
"c++",
"cpp"
],
"kotlin": [
"kotlin"
],
"haskell": [
"haskell"
]
}
}
+1 -9
View File
@@ -82,11 +82,7 @@ what "done" means, verifying, or being sent back by the gate.
that prints it in full (`sisi done ID`, `sisi lessons show ID`), within a 2,000-character cap.
A recipe counts only when at least two distinct non-generic request words hit its title,
applies-to or id, at least one of them in its title (matched on stems, so "tag" meets
"tagging") — the same strict floor lessons use. When the request reads as design or build work
(a design, build, implement or create stem on a non-trivial message; never on a question or a
small edit such as a rename or a typo), the owner's standing principles are also injected in
short lines with the instruction to fill the contract's design section first, inside the same
cap. A message that is a question to the agent and
"tagging") — the same strict floor lessons use. A message that is a question to the agent and
names no work (no fix, build, change or the like), trivial messages (a bare yes or no, a slash
command, a short question) and unmatched requests inject nothing at all. These
showings count as *listed* at place `prompt`. The hook never blocks a turn: any error exits
@@ -370,10 +366,6 @@ universal lessons that merely mention common file names such as README or CHANGE
pass, and universal changes whose moment names a project, which also pass because only the
delivered part is checked), and long real-style multi-part requests plus plain questions for
request-time recipe delivery (a hit is the expected recipe; any other recipe is a false match).
The design-section validation is measured the same way in the design tests: a labelled set of
good design sections against filler ones (a hit is a good section passing; a false pass is a
filler section passing), plus labelled design-work requests for request-time delivery.
Delivery therefore depends on the quality of the when-terms the recording agent writes. Thin or
copy-of-the-text terms leave a lesson findable only by its own wording, exactly the failure they
exist to prevent. What sisi ultimately measures is not match scores but the outcome that matters:
+24 -24
View File
@@ -484,24 +484,24 @@
},
{
"id": "R-4.5-1",
"status": "partial",
"how": "The design section requires a named challenger and alternatives before large edits",
"evidence": "sisi/design.py",
"gap": "The challenge is structural text validated for shape, not evidence that a better solution was sought, and it fires by diff size rather than by flawed premises."
"status": "missing",
"how": "nothing: the six-part design section that touched this was retired as ceremony",
"evidence": "",
"gap": "An approach note (chosen approach, alternatives considered, what existing capability is reused) required by risk profile is designed in docs/target.md and not built yet."
},
{
"id": "R-4.5-2",
"status": "partial",
"how": "The design section requires a named challenger and alternatives before large edits",
"evidence": "sisi/design.py",
"gap": "The challenge is structural text validated for shape, not evidence that a better solution was sought, and it fires by diff size rather than by flawed premises."
"status": "missing",
"how": "nothing: the six-part design section that touched this was retired as ceremony",
"evidence": "",
"gap": "An approach note (chosen approach, alternatives considered, what existing capability is reused) required by risk profile is designed in docs/target.md and not built yet."
},
{
"id": "R-4.5-3",
"status": "partial",
"how": "The design section requires a named challenger and alternatives before large edits",
"evidence": "sisi/design.py",
"gap": "The challenge is structural text validated for shape, not evidence that a better solution was sought, and it fires by diff size rather than by flawed premises."
"status": "missing",
"how": "nothing: the six-part design section that touched this was retired as ceremony",
"evidence": "",
"gap": "An approach note (chosen approach, alternatives considered, what existing capability is reused) required by risk profile is designed in docs/target.md and not built yet."
},
{
"id": "R-5.1-1",
@@ -1072,17 +1072,17 @@
},
{
"id": "R-8.2-1",
"status": "partial",
"how": "The audits and design section favour the simplest coherent approach and sisi deletes or retires some dead surfaces",
"evidence": "sisi/design.py",
"gap": "Accidental complexity is not measured, and gate ceremony is triggered by diff size, which equates size with risk."
"status": "missing",
"how": "nothing: the six-part design section that touched this was retired as ceremony",
"evidence": "",
"gap": "An approach note (chosen approach, alternatives considered, what existing capability is reused) required by risk profile is designed in docs/target.md and not built yet."
},
{
"id": "R-8.2-2",
"status": "partial",
"how": "The audits and design section favour the simplest coherent approach and sisi deletes or retires some dead surfaces",
"evidence": "sisi/design.py",
"gap": "Accidental complexity is not measured, and gate ceremony is triggered by diff size, which equates size with risk."
"status": "missing",
"how": "nothing: the six-part design section that touched this was retired as ceremony",
"evidence": "",
"gap": "An approach note (chosen approach, alternatives considered, what existing capability is reused) required by risk profile is designed in docs/target.md and not built yet."
},
{
"id": "R-8.3-1",
@@ -1149,10 +1149,10 @@
},
{
"id": "R-9.3-1",
"status": "partial",
"how": "A six-part design section is required before edits past 40 lines or 3 files",
"evidence": "sisi/design.py:100",
"gap": "Planning is triggered by diff size not risk, validates text shape rather than foreseeable rework, and records no dependencies or integration responsibilities."
"status": "missing",
"how": "nothing: the six-part design section that touched this was retired as ceremony",
"evidence": "",
"gap": "An approach note (chosen approach, alternatives considered, what existing capability is reused) required by risk profile is designed in docs/target.md and not built yet."
},
{
"id": "R-9.4-1",
+30
View File
@@ -0,0 +1,30 @@
---
id: feature
title: Adding a new capability to an existing product
applies_to: A new capability in a product that already exists and already has users, behaviour and data.
---
## Done means
- The new capability works end to end through the real surface users will use, not only through a new function or endpoint.
- Every requirement is listed with its kind (explicit, implied, contextual, anticipated, experiential) and a decision: implement now, architect for, defer, or ignore, each with a reason.
- Behaviour that already exists is unchanged except where the new capability is meant to change it, shown by invariants with a baseline from before the change.
- 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.
## Checks
- Requirements: `requirement-to-check-map` (completeness), `acceptance-examples` (intent), rung 3; every requirement maps to a check or a recorded deferral.
- New logic: `hypothesis`, `proptest` or the language's property tool (many-inputs), rung 2; `differential-reference` where a trusted comparison exists.
- 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.
- Finished cleanly: `no-stubs-scan`, `single-gate-command` (completeness), rung 3.
## Common false finishes
- The happy path works and the empty, huge, invalid and repeated cases were never tried.
- A requirement nobody stated but everybody needs (undo, export, permissions, existing data) is missing, and the report does not say so.
- Existing behaviour changed silently: no baseline was taken, so nobody can tell what moved.
- The capability exists but users cannot find it, or its errors leave them stuck.
- Anticipated needs were built speculatively, or were dismissed without a recorded defer decision.
- New settings or data have no story for existing users upgrading.
- The new code path is tested only through its internals, never through the surface users touch.
+5 -22
View File
@@ -61,9 +61,8 @@ A shared rulebook and enforced definitions of done for every AI coding CLI.
to every user who installs sisi? Both yes: core (in force
for you, queued for the product). (a) only: user (your
standing principles). Neither: project (handed over to it)
sisi design the owner's standing principles and the design questions to
answer in a contract's design section before sizeable work
(implies, provided, alternatives, chosen, objections, challenge)
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 items waiting to be filed in this project's own docs or
work list; done confirms one is filed (the named file must contain
@@ -130,19 +129,6 @@ def cmd_contract(args):
print("created %s as a SKELETON, not a contract yet: replace the placeholder check with a real command "
"(rung 1-4) and add every check that shows the work is done. Until then `sisi verify` fails and "
"the end-of-turn gate ignores it." % p)
try:
from . import principles
lines = principles.short_lines()
if lines:
print("\nThe owner's standing principles (the design section must answer each one's objection):")
for ln in lines:
print(ln)
print("\nFor sizeable work, fill the contract's design section first (the skeleton is in "
"the file; `sisi design` prints the questions): what the goal and these principles "
"imply, what already exists to use, alternatives, the choice, each principle's "
"objection, and an independent challenge. The gate sends a large change back without it.")
except Exception:
pass
try:
from . import retro
block = retro.delivery_block(goal or "", "contract-init", extra="contract checks verified")
@@ -162,9 +148,6 @@ def cmd_contract(args):
print("sisi: cannot read %s: %s" % (p, e))
return 1
errs = C.validate(c)
if isinstance(c, dict) and "design" in c and not C.is_unedited_skeleton(c):
from . import design as _D
errs = errs + _D.validate_design(c, cwd=C.project_dir(p))
for e in errs:
print(" - " + e)
if not errs:
@@ -454,9 +437,9 @@ def main(argv):
return cycle.cmd_improve(args)
if cmd == "oracle":
return cmd_oracle()
if cmd == "design":
from . import design
return design.main(args)
if cmd == "risk":
from . import risk
return risk.main(args)
if cmd == "status":
return cmd_status()
if cmd == "time":
-2
View File
@@ -38,7 +38,6 @@ def is_unedited_skeleton(c):
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 design as _design
return {
"id": name or "work",
"goal": goal or "TODO: one sentence describing the outcome",
@@ -63,7 +62,6 @@ def skeleton(goal=None, cwd=None):
"invariants": [],
"assumptions": [],
"questions": [],
"design": _design.skeleton(),
}
-257
View File
@@ -1,257 +0,0 @@
"""Choosing the approach as a checked step: the contract's `design` section and `sisi design`.
The design section records, before building: what the goal and the owner's standing principles
(`sisi oracle`) imply that the request did not spell out; what the environment, host tool or
existing system already provides that should be used instead of built; at least two
alternatives with cost and risk; the chosen one and why it is what the owner would pick; for
every standing principle, the objection the owner would raise and how the design answers it
(or why it does not apply); and an independent challenge, by a different model or a subagent
playing the owner, with what changed in response.
Validation is structural only, but it is aimed at filler: entries must be non-trivial,
`provided` must name at least one thing that verifiably exists (a `command:NAME` on PATH or a
`file:PATH` in the repository, given as evidence), alternatives must differ from each other
and from the chosen approach, and the challenge must contain an objection plus a change (or a
stated reason for no change) from someone who is not the author.
One thing is honestly not checkable: that the challenge was recorded before the first code
edit. The edit-attribution data in sisi/watch.py records which paths a session changed, but no
first-edit timestamp survives (the only timestamp is on a pending before-snapshot, consumed
when the command finishes), so validation requires a parseable `recorded_at` that is not in
the future and no more.
"""
import json, os, re, shutil
from datetime import datetime, timezone
QUESTIONS = """Before building, answer these in the contract's design section:
implies what the goal and the owner's standing principles imply that the request did
not spell out (consequences of what the owner already said)
provided what the environment, the host tool or the existing system already provides
that should be used instead of built; give evidence for each item as
"command:NAME" (on PATH) or "file:PATH" (in the repository)
alternatives at least two approaches, one line each on cost and on risk
chosen which approach, and why it is the one the owner would pick
objections one entry per standing principle: when it applies, the objection the owner
would raise and how the design answers it; when it does not, why not
challenge an independent attack on the design by a different model or a subagent,
playing the owner (what will he say is missing or wrong), who did it, when it
was recorded, and what was changed in response (or why nothing changed)"""
_FILLER = {"tbd", "todo", "n/a", "na", "none", "nothing", "as requested", "best", "low",
"high", "medium", "x", "y", "-", "stuff", "things", "various", "etc", "placeholder",
"as above", "see above", "obvious", "standard", "normal", "usual"}
def _norm(s):
return " ".join(str(s or "").split()).lower().strip(" .!?:;\"'")
def _trivial(s, min_chars, min_words):
t = " ".join(str(s or "").split())
n = _norm(t)
if not t or n in _FILLER or "todo" in n or "placeholder" in n:
return True
return len(t) < min_chars or len(t.split()) < min_words
def skeleton(principle_recs=None):
if principle_recs is None:
try:
from . import principles
principle_recs = principles.statements()
except Exception:
principle_recs = []
from . import principles as P
return {
"implies": ["TODO: what the goal and the owner's principles imply that the request did not spell out"],
"provided": [{"what": "TODO: what already exists that this should use instead of building",
"evidence": "command:TODO or file:TODO"}],
"alternatives": [
{"name": "TODO first approach", "cost": "TODO cost in one line", "risk": "TODO risk in one line"},
{"name": "TODO second approach", "cost": "TODO cost in one line", "risk": "TODO risk in one line"}],
"chosen": {"name": "TODO chosen approach",
"why": "TODO why this is the one the owner would pick"},
"objections": [{"principle": P.plain_of(r), "applicable": True,
"objection": "TODO the objection the owner would raise",
"answer": "TODO how the design answers it"} for r in principle_recs],
"challenge": {"by": "TODO who attacked it (a different model or a subagent)",
"recorded_at": "TODO ISO timestamp, recorded before building",
"objections": ["TODO what the owner would say is missing or wrong"],
"changes": ["TODO what was changed in response"]},
}
def _as_list(v):
if v is None:
return []
return v if isinstance(v, list) else [v]
def _text_of(v, keys=()):
if isinstance(v, str):
return v
if isinstance(v, dict):
for k in keys:
if isinstance(v.get(k), str) and v[k].strip():
return v[k]
return ""
def _evidence_ok(item, cwd):
"""True when a `provided` item verifiably names something that exists."""
evidences = []
if isinstance(item, dict):
for k in ("evidence", "exists", "check"):
if isinstance(item.get(k), str):
evidences.append(item[k])
text = _text_of(item, ("what", "name", "use", "text"))
else:
text = str(item or "")
for ev in evidences + [text]:
for m in re.finditer(r"command:([A-Za-z0-9_./-]+)", ev or ""):
if shutil.which(m.group(1)):
return True
for m in re.finditer(r"(?:file|path):([^\s\"']+)", ev or ""):
p = m.group(1).rstrip(".,;)")
if os.path.exists(p if os.path.isabs(p) else os.path.join(cwd, p)):
return True
for tok in re.findall(r"[A-Za-z0-9_./~-]+", text):
if "/" in tok and os.path.exists(os.path.join(cwd, tok.rstrip(".,;)"))):
return True
return False
def _match_principle(field, principle_recs):
from . import principles as P
if isinstance(field, int) and 1 <= field <= len(principle_recs):
return field - 1
f = _norm(field)
m = re.fullmatch(r"p(\d+)", f)
if m and 1 <= int(m.group(1)) <= len(principle_recs):
return int(m.group(1)) - 1
for i, rec in enumerate(principle_recs):
for cand in (rec["text"], P.plain_of(rec)):
c = _norm(cand)
if f == c or (f and c and (f in c or c in f)):
return i
return None
def validate_design(contract, cwd=None, principle_recs=None):
"""Structural refusal reasons for a contract's design section; empty means acceptable."""
cwd = cwd or os.getcwd()
if principle_recs is None:
try:
from . import principles
principle_recs = principles.statements()
except Exception:
principle_recs = []
if not isinstance(contract, dict) or not isinstance(contract.get("design"), dict):
return ["design section is missing: sizeable work needs a `design` section in the "
"contract (`sisi design` prints the owner's principles and the questions)"]
d = contract["design"]
errs = []
goal = _norm(contract.get("goal"))
implies = _as_list(d.get("implies"))
if not implies or all(_trivial(_text_of(x, ("text", "implies")), 40, 7) for x in implies):
errs.append("design.implies: name at least one consequence of the goal and the owner's "
"principles that the request did not spell out (a real sentence, not filler)")
elif any(_norm(_text_of(x, ("text", "implies"))) == goal for x in implies):
errs.append("design.implies: restating the goal is not an implication")
provided = _as_list(d.get("provided"))
if not provided:
errs.append("design.provided: name what the environment, host tool or existing system "
"already provides that should be used instead of built")
else:
if all(_trivial(_text_of(x, ("what", "name", "use", "text")), 25, 5) for x in provided):
errs.append("design.provided: each item must say concretely what already exists")
elif not any(_evidence_ok(x, cwd) for x in provided):
errs.append("design.provided: at least one item must name something that verifiably "
"exists, with evidence as \"command:NAME\" (on PATH) or \"file:PATH\" "
"(in the repository)")
chosen_name = _text_of(d.get("chosen"), ("name", "approach", "chosen"))
alts = _as_list(d.get("alternatives"))
alt_names = [_norm(_text_of(a, ("name", "approach"))) for a in alts]
if len(alts) < 2:
errs.append("design.alternatives: at least two approaches are required")
else:
if any(not n or _trivial(n, 4, 1) for n in alt_names) or len(set(alt_names)) != len(alt_names):
errs.append("design.alternatives: the approaches must be distinct and named")
if _norm(chosen_name) and _norm(chosen_name) in alt_names:
errs.append("design.alternatives: alternatives must differ from the chosen approach "
"(they are the approaches not taken, with their cost and risk)")
for a in alts:
if not isinstance(a, dict) or _trivial(a.get("cost"), 12, 3) or _trivial(a.get("risk"), 12, 3):
errs.append("design.alternatives: each approach needs one real line on cost and one on risk")
break
why = _text_of(d.get("chosen"), ("why", "reason")) if isinstance(d.get("chosen"), dict) else ""
if _trivial(chosen_name, 4, 1):
errs.append("design.chosen: name the chosen approach")
if _trivial(why, 40, 7):
errs.append("design.chosen.why: say why this is the approach the owner would pick "
"(a real sentence, not filler)")
objections = _as_list(d.get("objections"))
covered = {}
for o in objections:
if isinstance(o, dict):
i = _match_principle(o.get("principle"), principle_recs)
if i is not None:
covered[i] = o
for i, rec in enumerate(principle_recs):
from . import principles as P
o = covered.get(i)
if o is None:
errs.append("design.objections: no entry for the standing principle %r - state the "
"owner's objection and its answer, or why it does not apply"
% P.plain_of(rec)[:80])
continue
if o.get("applicable") is False:
if _trivial(o.get("reason"), 20, 4):
errs.append("design.objections: principle %r is marked not applicable without a reason"
% P.plain_of(rec)[:80])
elif _trivial(o.get("objection"), 20, 4) or _trivial(o.get("answer"), 20, 4):
errs.append("design.objections: principle %r needs the objection the owner would "
"raise and how the design answers it" % P.plain_of(rec)[:80])
ch = d.get("challenge") if isinstance(d.get("challenge"), dict) else {}
by = _text_of(ch, ("by", "who", "challenger"))
if _trivial(by, 3, 1) or _norm(by) in ("self", "me", "myself", "the agent", "author"):
errs.append("design.challenge.by: name who attacked the design (a different model or a "
"subagent playing the owner, not the author)")
cobjs = _as_list(ch.get("objections"))
if not cobjs or all(_trivial(_text_of(x, ("text", "objection")), 25, 5) for x in cobjs):
errs.append("design.challenge: at least one real objection from the challenger is required")
changes = _as_list(ch.get("changes"))
if (not changes or all(_trivial(_text_of(x, ("text", "change")), 25, 5) for x in changes)) \
and _trivial(ch.get("no_change_reason"), 25, 5):
errs.append("design.challenge: say what was changed in response, or why nothing changed")
ts = ch.get("recorded_at")
if not isinstance(ts, str) or not ts.strip() or "todo" in _norm(ts):
errs.append("design.challenge.recorded_at: when the challenge was recorded (an ISO timestamp, before building)")
else:
try:
when = datetime.fromisoformat(ts.strip().replace("Z", "+00:00"))
now = datetime.now(timezone.utc) if when.tzinfo else datetime.now()
if (when - now).total_seconds() > 3600:
errs.append("design.challenge.recorded_at: %r is in the future" % ts)
except ValueError:
errs.append("design.challenge.recorded_at: %r is not an ISO timestamp" % ts)
return errs
def main(args=()):
"""`sisi design`: the owner's principles and the design questions, before a contract exists."""
from . import principles
print("Choosing the approach: work out what the goal and the owner's principles imply, "
"use what already exists, and have the design attacked as the owner would - before building.\n")
recs = principles.statements()
if recs:
print("The owner's standing principles (`sisi oracle` prints them in full, with his words):")
for i, rec in enumerate(recs, 1):
print("%d. %s" % (i, principles.plain_of(rec)))
print()
else:
print("No standing principles are recorded yet (`sisi learn --scope user \"<his words>\"` records one).\n")
print(QUESTIONS)
print("\nSkeleton for .sisi/contract.json (the gate checks it on a large change):")
print(json.dumps({"design": skeleton(recs)}, indent=2))
return 0
+1 -47
View File
@@ -569,33 +569,6 @@ def _measure_work(cwd, base=None):
return m
def _design_required(sess, cwd, top, g, payload, attr):
"""The design section is required exactly where a contract is already required: a large
change (the gate's growth thresholds). Small edits, subagents, and sessions that edited
nothing here are exempt. Returns True when required, else None."""
if payload.get("agent_id") or payload.get("agent_transcript_path"):
return None # a subagent works to its parent's brief; the parent owns the design
if attr is not None and not attr.get("writing") and not attr.get("unknown"):
return None # this session edited nothing: no design is owed for others' work
if not top:
return None
try:
if sess.get("baseline") is not None:
now = _measure_work(cwd, sess.get("head"))
base = sess["baseline"]
dl = max(0, now["lines"] - base["lines"])
df = len(set(now["files"]) - set(base["files"]))
else:
m = _measure_work(cwd, gitutil.head(cwd))
dl, df = m["lines"], len(m["files"])
except Exception as e:
store.log_error("gate-design-measure", e)
return None
if not (dl > int(g.get("growth_lines", 40)) or df > int(g.get("growth_files", 3))):
return None
return True
def _decide(payload):
"""Return ('allow', message_or_None) or ('block', reason)."""
cfg = store.config()
@@ -784,23 +757,6 @@ def _decide(payload):
kind=sess.get("last_kind", "fast"))
if path:
if c is not None and not errs:
try:
if _design_required(sess, cwd, top, g, payload, attr):
from . import design as _design
derrs = _design.validate_design(c, cwd=project)
if derrs:
missing = "missing" if "design" not in c else "invalid"
return ctx.block(
"sisi: this is a large change and the contract's design section is %s "
"(send-back {n}). Choosing the approach is a checked step: fill the "
"design section before building (`sisi design` prints the owner's "
"standing principles and the questions; `sisi oracle` prints the "
"principles in his words). Do not report this work as done.\n\n%s"
% (missing, "\n".join("- " + e for e in derrs)),
c["id"] if c else None, project, kind="design")
except Exception as e: # the design check must never break the gate
store.log_error("gate-design", e)
deadline = time.time() + float(g.get("budget_s", 120))
if c is not None:
errs = C.validate(c)
@@ -891,9 +847,7 @@ def _decide(payload):
return ctx.allow()
return ctx.block("sisi: this session has changed %d lines and %d files since its start and there is no "
"contract (send-back {n}). Write `.sisi/contract.json` (`sisi contract init` makes the "
"skeleton; give it at least one check with a real command, and for a change this size "
"fill its design section - `sisi design` prints the owner's principles and the "
"questions), then run `sisi verify`. If "
"skeleton; give it at least one check with a real command), then run `sisi verify`. If "
"the change needs no checks, run `sisi contract waive \"<reason>\"` instead." % (dl, df))
+1 -1
View File
@@ -2,7 +2,7 @@
statements until the product carries them, and not-yet-tiered ones meanwhile), live at once.
A statement takes effect the moment it is recorded: `sisi oracle` prints it, request-time
delivery hands it over, and a contract's design section must answer its objections. There is
delivery hands it over when it matches a request. There is
no quarantine and no holding file. The oracle is a proper document (oracle.md in the personal
folder) whose structure a learning round owns through the whole-document edit in
sisi/documents.py, tracing every statement into the text like any other document; until a
+30 -99
View File
@@ -9,7 +9,7 @@ import json, os, sys
from . import store
MAX_CHARS = 2000 # hard cap on the injected context, in characters
RECIPE_MIN_SCORE = 6.0 # two title/applies-to word hits in `sisi done for`'s scoring; below it, no recipe
RECIPE_MIN_SCORE = 22.0 # a structured kind/tag match in the new matcher; below it, no recipe
_TRIVIAL = {"yes", "no", "y", "n", "ok", "okay", "sure", "yep", "nope", "thanks", "thank you",
"go ahead", "do it", "continue", "stop", "wait", "hi", "hello"}
@@ -32,51 +32,6 @@ def _is_question_without_work(t):
return not (stems & _WORK_STEMS)
_DESIGN_STEMS = {"build", "design", "implement", "creat", "develop", "architect", "orchestr",
"automat", "integrat", "plugin", "system", "platform", "framework"}
_SMALL_EDIT_MARKERS = ("rename", "typo", "off-by-one", "one line", "single line", "small fix",
"quick fix", "spelling")
def is_design_work(text):
"""A request to design or build something sizeable: not a question, not a small edit.
Precision matters more than reach, as with recipes: a wrong design block on every message
would train agents to ignore it."""
t = " ".join((text or "").split())
low = t.lower()
if len(t.split()) < 6:
return False
if any(m in low for m in _SMALL_EDIT_MARKERS):
return False
first = low.split(" ", 1)[0].strip("¿?") if low else ""
if low.endswith("?") and first in _QUESTION_START:
return False # a question about design is not design work
if _is_question_without_work(t):
return False
from . import retro, verifiers as V
stems = {retro._stem(w) for w in V._words(low)}
if not (stems & _DESIGN_STEMS):
return False
return bool(stems & _WORK_STEMS) or bool(stems & {"build", "design", "creat", "develop"})
def _design_block():
"""The standing principles in short lines, plus the instruction to fill the design section."""
try:
from . import principles
lines = principles.short_lines(limit_chars=900)
except Exception:
lines = []
out = ["sisi: this reads as design or build work. Before building, fill the contract's "
"design section (`sisi design` prints the questions; `sisi contract init` writes "
"the skeleton): what the goal and the principles imply, what already exists to use, "
"alternatives, the choice, each principle's objection, and an independent challenge."]
if lines:
out.append("The owner's standing principles (in his words: `sisi oracle`):")
out += lines
return out
def is_trivial(text):
"""A message no recipe or lesson can help with: empty, a slash command, a bare yes/no, or a short
question. A wrong injection on every message is worse than none."""
@@ -98,44 +53,11 @@ def is_trivial(text):
def _best_recipe(query):
"""The best-matching recipe, or None. Scoring starts from `sisi done for`'s own, but request-time
delivery must be more precise than an answer the agent asked for: a recipe counts only when at
least two distinct words of the request hit its title, applies-to or id (one generic word like
"new" once outscored "release" + "tag" that way), and the leader must clear RECIPE_MIN_SCORE."""
from . import retro, verifiers as V
# Match on stems, as lesson matching does: "release" must meet "Releasing" and "tag" must meet
# "Tagging", which done-for's prefix rule (both words longer than three letters) misses.
toks = {retro._stem(t) for t in V._words(query)}
def stems_of(text):
return {retro._stem(x) for x in V._words(text.replace("-", " "))}
generic = retro.COMMON | {retro._stem(w) for w in
("agent agents tool tools interface surface command commands function functions "
"program system name names description descriptions user users thing things "
"way ways step steps example examples".split())}
scored = []
for r in V.usable(V.load_recipes()):
s, primary, anchored = 0.0, set(), set()
for text, w, is_anchor in ((r["title"], 3.0, True), (r["applies_to"], 3.0, False),
(r["id"].replace("-", " "), 3.0, False), (r["body"], 0.2, False)):
hit = toks & stems_of(text)
s += w * len(hit)
if w > 1.0:
primary |= hit - generic # generic words (new, fix, change, agent, tool) never carry a match
if is_anchor:
anchored |= hit - generic
if s > 0:
scored.append((len(primary), len(anchored), s, r))
if not scored:
return None
scored.sort(key=lambda x: (-x[0], -x[1], -x[2], x[3]["id"]))
# the strict floor lessons use: two distinct non-generic terms, at least one of them in the
# recipe's own title (its topic, not merely its id), and the score floor; the best
# candidate that clears it wins
for nprimary, nanchored, s, best in scored:
if nprimary >= 2 and nanchored >= 1 and s >= RECIPE_MIN_SCORE:
return best
"""The best-matching recipe when the structured match is strong, else None."""
from . import verifiers as V
ranked = V.rank_recipes(query)
if ranked and ranked[0][0] >= RECIPE_MIN_SCORE:
return ranked[0][1]
return None
@@ -153,14 +75,8 @@ def _done_means(recipe, retro):
def build_context(query, session=None):
"""The context to inject for one human request, or "" when nothing strictly matches. Lessons shown
are recorded as listings at place 'prompt' (listed, not read)."""
notice = ""
try:
from . import handover
notice = handover.notice(os.getcwd())
except Exception:
notice = ""
if is_trivial(query):
return notice
return ""
from . import retro
recipe = _best_recipe(query)
targets = (recipe["id"],) if recipe else ()
@@ -174,14 +90,29 @@ def build_context(query, session=None):
lesson_lines.append("- #%d: %s (full text: `sisi lessons show %d`)"
% (row["id"], retro.heading_text(row, 120), row["id"]))
ids.append(row["id"])
design_lines = _design_block() if is_design_work(query) else []
if not recipe and not lesson_lines and not design_lines:
return notice
lines = [notice] if notice else []
lines += design_lines
if recipe or lesson_lines:
lines.append("sisi: for this request (from earlier agents' lessons and the recipe library; "
"information to weigh, not commands):")
# Learnings in scope: ask the learning module if it offers a scoped view.
try:
from . import scope as _scope_mod # noqa: F401
scoped = None
for _name in ("prompt_lines", "in_scope_lines", "scoped_lines"):
_fn = getattr(_scope_mod, _name, None)
if callable(_fn):
try:
scoped = _fn(query, os.getcwd())
except TypeError:
scoped = _fn(query)
break
if scoped:
for _ln in scoped:
if isinstance(_ln, str) and _ln.strip():
lesson_lines.append(_ln if _ln.startswith("- ") else "- " + _ln)
except Exception:
pass
if not recipe and not lesson_lines:
return ""
lines = []
lines.append("sisi: for this request (from earlier agents' lessons and the recipe library; "
"information to weigh, not commands):")
if recipe:
lines.append("Done means — recipe `%s` (full text: `sisi done %s`):" % (recipe["id"], recipe["id"]))
lines += _done_means(recipe, retro)
+206
View File
@@ -0,0 +1,206 @@
"""Risk profiles: ceremony follows risk, not diff size (SPEC 5.3, target section 3).
`assess` is a pure function from changed paths (and optionally diff text) to a floor
profile plus the reasons. Tables come from canon/risk.json, a user-store adjustment
file, and a project override at .sisi/risk.json; later tables only add patterns.
"""
import fnmatch, json, os, subprocess
PROFILES = ["trivial", "isolated", "logic", "integration", "data", "critical", "release"]
_ORDER = {name: i for i, name in enumerate(PROFILES)}
_TRIVIAL_PROFILES = {"trivial"}
def _load_json(path):
try:
with open(path, encoding="utf-8") as f:
d = json.load(f)
return d if isinstance(d, dict) else {}
except (OSError, ValueError):
return {}
def default_table():
from . import paths
return _load_json(paths.canon("risk.json"))
def requirements_for(profile, table=None):
"""What a profile carries (target section 3 table), held as data for the gate."""
table = table or default_table()
reqs = table.get("requirements") or {}
if profile in reqs:
return dict(reqs[profile])
# Fall back to the built-in table shape so a partial override still answers.
return dict(default_table().get("requirements", {}).get(profile, {}))
def _patterns_from(table):
out = []
for p in (table or {}).get("patterns") or []:
if isinstance(p, dict) and p.get("profile") in _ORDER and (p.get("glob") or p.get("keyword")):
out.append(p)
return out
def load_patterns(cwd=None):
"""Canon patterns plus user-store and project adjustments, in that order."""
from . import paths
pats = _patterns_from(default_table())
pats += _patterns_from(_load_json(paths.data_file("risk.json")))
if cwd:
from . import gitutil
root = gitutil.root(cwd) or os.path.abspath(cwd)
pats += _patterns_from(_load_json(os.path.join(root, ".sisi", "risk.json")))
return pats
def _glob_match(path, pattern):
p = path.replace(os.sep, "/")
pat = pattern.replace(os.sep, "/")
if fnmatch.fnmatch(p, pat):
return True
# A leading **/ should also match at the root.
if pat.startswith("**/") and fnmatch.fnmatch(p, pat[3:]):
return True
# A trailing /** should match the directory itself and anything under it.
if pat.endswith("/**") and (p == pat[:-3] or p.startswith(pat[:-2])):
return True
return False
def _packages(paths):
pkgs = set()
for raw in paths:
parts = [x for x in raw.replace(os.sep, "/").split("/") if x and x != "."]
if len(parts) < 2:
continue
if parts[0] in ("src", "lib", "app") and len(parts) >= 3:
pkgs.add(parts[1])
elif len(parts) >= 2:
pkgs.add(parts[0])
return pkgs
def assess(paths, diff_text=None, extra_patterns=None, patterns=None):
"""Return (floor_profile, reasons). Adding a path never lowers the floor."""
pats = list(patterns if patterns is not None else _patterns_from(default_table()))
if extra_patterns:
pats += [p for p in extra_patterns if isinstance(p, dict) and p.get("profile") in _ORDER]
clean = [str(p).replace(os.sep, "/") for p in (paths or []) if str(p).strip()]
if not clean:
return "trivial", ["no changed paths"]
best, reasons = "trivial", []
matched_profiles = []
trivial_hits = set()
for pat in pats:
prof = pat["profile"]
reason = pat.get("reason") or prof
if pat.get("glob"):
hits = [p for p in clean if _glob_match(p, pat["glob"])]
if hits:
matched_profiles.append(prof)
if prof == "trivial":
trivial_hits.update(hits)
if _ORDER[prof] >= _ORDER[best]:
if _ORDER[prof] > _ORDER[best]:
best, reasons = prof, []
reasons.append("%s: %s" % (hits[0], reason))
if pat.get("keyword") and diff_text:
if pat["keyword"].lower() in diff_text.lower():
matched_profiles.append(prof)
if _ORDER[prof] >= _ORDER[best]:
if _ORDER[prof] > _ORDER[best]:
best, reasons = prof, []
reasons.append("diff: %s" % reason)
# Structural rules that patterns cannot express. Documentation and styling
# paths do not count as packages: two docs folders are not an integration.
pkgs = _packages([p for p in clean if p not in trivial_hits])
if len(pkgs) >= 2 and _ORDER["integration"] >= _ORDER[best]:
if _ORDER["integration"] > _ORDER[best]:
best, reasons = "integration", []
reasons.append("touches %d top-level packages (%s): integration surface"
% (len(pkgs), ", ".join(sorted(pkgs))))
if best == "trivial" and len(trivial_hits) == len(clean):
return "trivial", reasons or ["documentation, text or styling only"]
if best == "trivial":
return "isolated", ["one module's behaviour changed"]
if not reasons:
reasons = ["%s: matched the %s profile" % (clean[0], best)]
# Keep reasons short and de-duplicated, strongest first is unnecessary: keep order.
seen, out = set(), []
for r in reasons:
if r not in seen:
seen.add(r)
out.append(r)
return best, out[:6]
def floor_for_working_tree(cwd):
"""(floor, reasons, files) for the working tree against HEAD, untracked included."""
from . import gitutil
m = gitutil.measure(cwd)
files = m.get("files") or []
diff_text = ""
try:
top = gitutil.root(cwd) or cwd
base = gitutil.head(cwd) or gitutil.EMPTY_TREE
p = subprocess.run(["git", "diff", "--no-ext-diff", base], cwd=top,
capture_output=True, timeout=10)
diff_text = p.stdout.decode("utf-8", "replace")[:200000]
# Untracked file contents are part of the change too.
for rel in files[:50]:
fp = os.path.join(top, rel)
try:
if os.path.isfile(fp) and os.path.getsize(fp) < 200000:
with open(fp, encoding="utf-8", errors="replace") as f:
diff_text += "\n" + f.read(20000)
except OSError:
pass
except Exception:
diff_text = ""
profile, reasons = assess(files, diff_text=diff_text, patterns=load_patterns(cwd))
return profile, reasons, files
def declared_profile(cwd):
"""The profile declared in .sisi/contract.json, if any."""
try:
with open(os.path.join(cwd, ".sisi", "contract.json"), encoding="utf-8") as f:
c = json.load(f)
if isinstance(c, dict):
r = c.get("risk")
if isinstance(r, dict) and r.get("profile") in _ORDER:
return r["profile"]
if c.get("risk_profile") in _ORDER:
return c["risk_profile"]
except (OSError, ValueError):
pass
return None
def main(args=()):
"""`sisi risk [--json]`: floor, reasons, declared profile, and what the floor requires."""
args = list(args)
as_json = "--json" in args
cwd = os.getcwd()
floor, reasons, files = floor_for_working_tree(cwd)
declared = declared_profile(cwd)
reqs = requirements_for(floor)
if as_json:
print(json.dumps({"floor": floor, "reasons": reasons, "files": files,
"declared": declared, "requirements": reqs}, indent=2))
return 0
print("risk floor: %s" % floor)
for r in reasons:
print(" - %s" % r)
print("declared: %s" % (declared or "none (no .sisi/contract.json risk.profile)"))
print("requires: contract=%s, checks=%s, requirement model=%s, risk note=%s, "
"independent evidence=%s, retro=%s"
% ("yes" if reqs.get("contract") else "no", reqs.get("checks", "-"),
"yes" if reqs.get("requirement_model") else "no",
"yes" if reqs.get("risk_note") else "no",
"yes" if reqs.get("independent_evidence") else "no", reqs.get("retro", "-")))
if files:
print("changed files: %d" % len(files))
return 0
+1 -12
View File
@@ -33,14 +33,6 @@ def _question_gate():
return False
def _design_gate():
try:
from . import design, gate
return callable(design.validate_design) and callable(gate._design_required)
except Exception:
return False
def _delivery_measured():
try:
from . import delivery
@@ -52,10 +44,7 @@ def _delivery_measured():
_NOT = "not enforced: depends on the agent"
ENFORCEMENT = {
"choose-the-approach": lambda: ("end-of-turn check sends a large change back when the contract's "
"design section is missing or fails validation (small edits and "
"subagents exempt)"
if _gate_wired() and _design_gate() else _NOT),
"choose-the-approach": lambda: _NOT,
"know-done": lambda: ("end-of-turn check sends the agent back (no contract on a large change)"
if _gate_wired() else _NOT),
"strongest-check": lambda: ("minimum rungs refused when the contract is checked; the choice of check depends on the agent"
+51 -51
View File
@@ -37,46 +37,47 @@ def _export_session(sid):
pass
def _backlog_line(cwd):
"""Developer mode, inside the sisi source folder: name the top tool backlog item. One short line."""
def _decision_line():
"""One line for a decision waiting for the owner, via the learning module when it
provides one; a missing function prints nothing."""
for mod_name in ("cycle", "retro", "scope"):
try:
mod = __import__("sisi." + mod_name, fromlist=["*"])
except Exception:
continue
for name in ("pending_decision_line", "owner_decision_line", "decision_waiting_line",
"pending_owner_line"):
fn = getattr(mod, name, None)
if callable(fn):
try:
out = fn()
except TypeError:
try:
out = fn(os.getcwd())
except Exception:
return ""
except Exception:
return ""
return out if isinstance(out, str) else ""
return ""
def _handover_line(sess, sid, cwd):
"""Handover items for this project, once per session."""
try:
from . import paths, retro
src = (paths.personal_config().get("developer") or {}).get("source")
if not src:
if sess.get("handover_shown"):
return ""
src = os.path.realpath(src)
here = os.path.realpath(cwd)
if here != src and not here.startswith(src + os.sep):
return ""
if not os.path.exists(retro.db_path()):
return ""
rows = retro.backlog_rows()
if not rows:
return ""
src = retro._get(rows[0], "short") or rows[0]["change"]
t = retro.safe_line(src, here)
if not t:
return ""
text = " ".join(t.split()) if retro._get(rows[0], "short") else retro.word_cut(t, 110)
return "top sisi backlog #%d (x%d): %s" % (rows[0]["id"], rows[0]["count"], text)
from . import handover
notice = handover.notice(cwd)
if notice:
sess["handover_shown"] = True
try:
store.save_session(sid, sess)
except Exception:
pass
return notice
except Exception:
return ""
def _deep_line(cwd, fp):
"""One short line when the project's trusted contract has deep checks that are not fresh-pass-or-running."""
from . import contract as C, deep, gitutil, trust, verify as V
path = C.find(cwd)
if not path or not trust.is_trusted(C.project_dir(path)):
return ""
c = C.load(path)
if C.validate(c) or not deep.deep_items(c):
return ""
if fp is None:
fp = V.tree_fp(C.project_dir(path), path)
ds = deep.deep_state(c, C.project_dir(path), fp)
if ds and ds["state"] in ("failed", "never-run", "stale-pass"):
return deep.describe(ds) + "; start with `sisi verify --deep --background`"
pass
return ""
@@ -122,15 +123,8 @@ def main(args=()):
_prune()
from . import wiring
problem = wiring.quick_problem()
line = "%s. Run `sisi doctor`." % problem if problem else ""
deep_line = _deep_line(cwd, rec.get("baseline_fp"))
if deep_line:
line = (line + " | " if line else "") + deep_line
backlog_line = _backlog_line(cwd)
if backlog_line:
line = (line + " | " if line else "") + backlog_line
if line:
sys.stdout.write("sisi: %s\n" % line)
if problem:
sys.stdout.write("sisi: %s. Run `sisi doctor`.\n" % problem)
_export_session(sid)
try:
sess = rec or store.load_session(sid)
@@ -156,12 +150,18 @@ def main(args=()):
except Exception as e:
store.log_error("tick-cycle", e)
try:
from . import retro
block = retro.tick_block(cwd, session=sid if isinstance(sid, str) else None)
if block:
sys.stdout.write(block + "\n")
decision = _decision_line()
if decision:
sys.stdout.write(decision + "\n")
except Exception as e:
store.log_error("tick-lessons", e)
store.log_error("tick-decision", e)
try:
sess2 = rec or store.load_session(sid)
hline = _handover_line(sess2, sid if isinstance(sid, str) else "cwd", cwd)
if hline:
sys.stdout.write(hline + "\n")
except Exception as e:
store.log_error("tick-handover", e)
except Exception as e:
store.log_error("tick", e)
return 0
+114 -39
View File
@@ -70,7 +70,7 @@ def _load_verifiers_from(d):
e.update(id=h.get("id") or e["stem"], title=h.get("title", ""), answers=h.get("answers", ""),
section=h.get("section") or parent or "", languages=_list(h.get("languages")),
kinds=_list(h.get("kinds")), cost=h.get("cost", ""), detect=h.get("detect", ""),
ran_here=h.get("ran_here", ""), parent=parent)
ran_here=h.get("ran_here", ""), verified=h.get("verified", ""), parent=parent)
try:
e["rung"] = int(h.get("rung", ""))
except ValueError:
@@ -197,6 +197,113 @@ def _words(text):
return [w for w in re.findall(r"[a-z0-9+#.\-]+", text.lower()) if len(w) > 1 and w not in STOP]
# ---- structured matching ---------------------------------------------------
import json as _json
def _synonyms():
try:
from . import paths as _paths
with open(_paths.canon("synonyms.json"), encoding="utf-8") as f:
d = _json.load(f)
return d if isinstance(d, dict) else {}
except Exception:
return {}
def _recipe_tags():
try:
from . import paths as _paths
with open(_paths.canon("recipe-tags.json"), encoding="utf-8") as f:
d = _json.load(f)
return d if isinstance(d, dict) else {}
except Exception:
return {}
def _expand(query):
"""(tags, kinds, sections, words, languages) a query implies, via the synonym table."""
low = " " + " ".join(re.findall(r"[a-z0-9]+", (query or "").lower().replace("-", " "))) + " "
syn = _synonyms()
tags, kinds, sections = set(), set(), set()
for g in syn.get("groups") or []:
for term in g.get("terms") or []:
norm = " " + " ".join(re.findall(r"[a-z0-9]+", term.lower().replace("-", " "))) + " "
if norm.strip() and norm in low:
tags.add(g.get("tag"))
kinds.update(g.get("kinds") or [])
sections.update(g.get("sections") or [])
words = set(_words(query or ""))
for term in list(words):
# single-word terms also fire their groups
for g in syn.get("groups") or []:
if term in (g.get("terms") or []):
tags.add(g.get("tag")); kinds.update(g.get("kinds") or []); sections.update(g.get("sections") or [])
langs = set()
for lang, names in (syn.get("languages") or {}).items():
if any((" " + " ".join(re.findall(r"[a-z0-9]+", n.lower())) + " ") in low for n in names):
langs.add(lang)
return tags, kinds, sections, words, langs
def _verified_bonus(e):
v = (e.get("verified") or e["header"].get("verified") or "").lower()
return {"ran": 4.0, "docs": 0.0, "memory": -2.0}.get(v, 0.0)
def rank_verifiers(query, entries=None, limit=None):
"""Ranked [(score, entry)] for a claim, by structured tags first, proven runs first."""
tags, kinds, sections, words, langs = _expand(query)
out = []
for e in (entries if entries is not None else usable(load_verifiers())):
kind_hits = kinds & set(e["kinds"])
section_hit = e["section"] in sections
specific_lang = bool(langs & set(e["languages"]))
overlap = words & (set(_words(e["answers"])) | set(_words(e["title"])) | set(_words(e["id"].replace("-", " "))))
if not (kind_hits or section_hit or specific_lang or overlap):
continue # proven-ness never creates relevance on its own
s = 0.0
s += 12.0 * len(kind_hits)
if section_hit:
s += 6.0
if specific_lang:
s += 5.0
elif langs and "any" in e["languages"]:
s += 1.0
s += 2.0 * len(overlap)
s += _verified_bonus(e)
s += 0.3 * (6 - min(e["rung"], 6))
if s > 0:
out.append((s, e))
out.sort(key=lambda x: (-round(x[0], 1), x[1]["rung"], x[1]["id"]))
return out[:limit] if limit else out
def rank_recipes(query, entries=None, limit=None):
"""Ranked [(score, recipe)] for a kind of work, by recipe tags and structured kinds."""
tags, kinds, sections, words, langs = _expand(query)
tagmap = _recipe_tags()
out = []
for r in (entries if entries is not None else usable(load_recipes())):
info = tagmap.get(r["id"]) or {}
rkinds = set(info.get("kinds") or [])
rtags = set(info.get("tags") or [])
s = 0.0
s += 12.0 * len(kinds & rkinds)
s += 10.0 * len(tags & rtags)
low = " " + " ".join(re.findall(r"[a-z0-9]+", (query or "").lower().replace("-", " "))) + " "
for rt in rtags:
phrase = " " + " ".join(re.findall(r"[a-z0-9]+", rt.lower().replace("-", " "))) + " "
if phrase.strip() and phrase in low and rt not in tags:
s += 10.0 if " " in rt.strip() else 5.0
text_words = set(_words(r["title"])) | set(_words(r["applies_to"])) | set(_words(r["id"].replace("-", " ")))
overlap = {w for w in words if w in text_words or
any(len(w) > 3 and len(x) > 3 and (x.startswith(w) or w.startswith(x)) for x in text_words)}
s += 2.0 * len(overlap)
s += 0.2 * len(words & set(_words(r["body"])))
if r["id"] == "bugfix" and (words & {"bug", "defect", "broken"}):
s += 8.0 # a reported defect is bugfix work even when it names a subsystem
if r["id"] == "refactor" and (words & {"refactoring", "refactor", "restructure", "restructuring"}):
s += 8.0 # naming the restructure makes it refactor work even in a money module
if s > 0:
out.append((s, r))
out.sort(key=lambda x: (-round(x[0], 1), x[1]["id"]))
return out[:limit] if limit else out
def _passes(e, o):
if "lang" in o:
ls = e["languages"]
@@ -335,41 +442,18 @@ def cmd_show(args):
return 0
def _score(tokens, e):
"""Word overlap against answers/title/kinds/languages/id, weighted."""
fields = ((e["answers"], 3.0), (e["title"], 3.0), (" ".join(e["kinds"]), 2.0), (" ".join(e["languages"]), 2.0), (e["id"], 2.0))
s = 0.0
for t in set(tokens):
for text, w in fields:
ws = set(_words(text.replace("-", " "))) | set(_words(text))
if t in ws or any(len(t) > 3 and (x.startswith(t) or t.startswith(x)) and len(x) > 3 for x in ws):
s += w
break
return s
def cmd_for(args):
opts, words = parse_args(args)
desc = " ".join(words).strip()
if not desc:
print('usage: sisi verifiers for "<claim or work>" [--lang L] [--kind K]')
return 1
tokens = _words(desc)
cands = []
for e in usable(load_verifiers()):
if not _passes(e, {k: v for k, v in opts.items() if k in ("lang", "kind")}):
continue
s = _score(tokens, e)
if s > 0:
cands.append((s, e))
cands.sort(key=lambda x: -x[0])
cands = cands[:30]
ranked_all = [(s, e) for s, e in rank_verifiers(desc)
if _passes(e, {k: v for k, v in opts.items() if k in ("lang", "kind")})]
cands = ranked_all[:30]
inst = installed_map([e for _, e in cands])
ranked = []
for s, e in cands:
f = s * (1 + 0.15 * (6 - min(e["rung"], 6))) * (1.3 if inst[e["path"]] == "yes" else 1.0)
ranked.append((f, e))
ranked.sort(key=lambda x: (-round(x[0], 0), x[1]["rung"], -x[0], x[1]["id"]))
ranked = [(s + (1.0 if inst[e["path"]] == "yes" else 0.0), e) for s, e in cands]
ranked.sort(key=lambda x: (-round(x[0], 1), x[1]["rung"], x[1]["id"]))
top = ranked[:8]
fl = None
if "kind" in opts:
@@ -563,16 +647,7 @@ def done_main(args):
if not desc:
print('usage: sisi done for "<description of the work>"')
return 1
toks = set(_words(desc))
scored = []
for r in rs:
s = 0.0
for text, w in ((r["title"], 3.0), (r["applies_to"], 3.0), (r["id"].replace("-", " "), 3.0), (r["body"], 0.2)):
ws = set(_words(text.replace("-", " ")))
s += w * sum(1 for t in toks if t in ws or any(len(t) > 3 and len(x) > 3 and (x.startswith(t) or t.startswith(x)) for x in ws))
if s > 0:
scored.append((s, r))
scored.sort(key=lambda x: (-x[0], x[1]["id"]))
scored = rank_recipes(desc, entries=rs)
if not scored:
print("no recipe matches that description; `sisi done` lists them")
_print_drafts(desc)
-276
View File
@@ -1,276 +0,0 @@
"""Live principles (`sisi learn`/`sisi oracle`), the contract design section, `sisi design`,
the gate's design send-back, and request-time design delivery."""
import json, os, subprocess, unittest
from support import *
PRINCIPLES = [
"drop into any user's environment and use what is already there",
"mechanisms over good intentions: check it, do not just advise it",
"never set up scheduled jobs or timers for me",
]
def good_design(principles=PRINCIPLES, **over):
d = {
"implies": ["The tool must work in an environment sisi did not choose, so discovery of what "
"the host already provides comes before building any replacement for it."],
"provided": [{"what": "git is already used for change measurement in this repository",
"evidence": "command:git"},
{"what": "the README documents the existing command surface to build on",
"evidence": "file:README.md"}],
"alternatives": [
{"name": "shell out to each tool's command line",
"cost": "one driver per tool, each with its own quoting and login handling",
"risk": "breaks wherever a tool has no usable command line or changes its flags"},
{"name": "build a new agent host of our own",
"cost": "months of work duplicating sessions, auth and tool wiring from scratch",
"risk": "nobody's existing setup carries over, so adoption starts from zero"},
],
"chosen": {"name": "use the host tool's own subagent mechanism",
"why": "It drops into the user's existing environment instead of rebuilding what "
"the host already provides, which is what the owner asked for."},
"objections": [{"principle": p, "applicable": True,
"objection": "You are rebuilding something the environment already gives me.",
"answer": "The design calls the host mechanism and builds only the missing adapter."}
if i < 2 else
{"principle": p, "applicable": False,
"reason": "Nothing in this design runs on a schedule; every step is triggered by use."}
for i, p in enumerate(principles)],
"challenge": {"by": "a subagent on a different model, briefed as the owner",
"recorded_at": "2026-01-01T00:00:00Z",
"objections": ["You never checked what the host already provides before designing drivers."],
"changes": ["Made the host subagent mechanism the main path; command lines are the fallback."]},
}
d.update(over)
return d
class PrinciplesCase(SisiCase):
def learn_all(self):
for p in PRINCIPLES:
r = self.sisi("learn", "--scope", "user", p)
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
class LivePrinciplesTests(PrinciplesCase):
def test_learn_takes_effect_at_once_without_quarantine_wording(self):
r = self.sisi("learn", "--scope", "user", PRINCIPLES[0])
self.assertEqual(r.returncode, 0, r.stdout)
self.assertNotIn("quarantin", (r.stdout + r.stderr).lower())
out = self.sisi("oracle").stdout
self.assertIn(PRINCIPLES[0], out)
def test_oracle_prints_one_principle_per_statement_with_quote_and_date(self):
self.learn_all()
out = self.sisi("oracle").stdout
for p in PRINCIPLES:
self.assertIn(p, out)
self.assertIn('"%s"' % p, out)
self.assertIn("Standing principles", out)
def test_quarantine_file_is_migrated_losslessly(self):
os.makedirs(self.data, exist_ok=True)
rec = {"ts": "2025-01-02T03:04:05Z", "cwd": self.proj, "tool": None, "session": None,
"text": "always show options with a recommendation", "scope": "user"}
with open(os.path.join(self.data, "learn-quarantine.jsonl"), "w") as f:
f.write(json.dumps(rec) + "\n")
out = self.sisi("oracle").stdout
self.assertIn("always show options with a recommendation", out)
self.assertIn("2025-01-02", out)
self.assertTrue(os.path.exists(os.path.join(self.data, "learn.jsonl")))
self.assertFalse(os.path.exists(os.path.join(self.data, "learn-quarantine.jsonl")))
rows = [json.loads(l) for l in open(os.path.join(self.data, "learn.jsonl"))]
self.assertEqual(rows[0]["text"], rec["text"])
self.assertEqual(rows[0]["ts"], rec["ts"])
def test_learn_statement_may_name_sisi_itself(self):
# the project folder is named proj in the fixture; use a folder named sisi
d = os.path.join(self.tmp, "sisi")
os.makedirs(d)
subprocess.run(["git", "init", "-q"], cwd=d, check=True)
r = self.sisi("learn", "--scope", "user",
"sisi should anticipate what I need from what I already said", cwd=d)
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
class DesignValidationTests(PrinciplesCase):
def errs(self, design):
from sisi import design as D
return D.validate_design({"goal": "g", "design": design}, cwd=REPO)
def test_good_design_passes(self):
self.learn_all()
self.assertEqual(self.errs(good_design()), [])
def test_missing_design_is_an_error(self):
from sisi import design as D
self.assertTrue(D.validate_design({"goal": "g"}, cwd=REPO))
def test_labelled_good_and_filler_sets(self):
"""At least 12 good and 12 filler design sections: every good one passes, every filler fails."""
self.learn_all()
base = good_design()
def variant(**kw):
d = json.loads(json.dumps(base))
d.update(kw)
return d
goods = [base]
for i in range(11):
d = json.loads(json.dumps(base))
d["implies"] = ["Implication %d: the result must keep working when the host, the model "
"and the project layout all change around it over time." % i]
d["provided"] = [{"what": "python3 runs the whole tool and its checks already",
"evidence": "command:python3"},
{"what": "the licence file fixes the terms this ships under",
"evidence": "file:LICENSE"}]
d["alternatives"][0]["name"] = "bespoke driver number %d" % i
d["challenge"]["by"] = "independent reviewer %d on a different model" % i
goods.append(d)
fillers = [
variant(implies=["As requested."]),
variant(implies=[]),
variant(provided=[{"what": "existing tools", "evidence": "command:no-such-command-xyz"}]),
variant(provided=["stuff that exists somewhere in general terms"]),
variant(provided=[]),
variant(alternatives=[base["alternatives"][0]]),
variant(alternatives=[dict(base["alternatives"][0], name="use the host tool's own subagent mechanism"),
base["alternatives"][1]]),
variant(alternatives=[dict(base["alternatives"][0], cost="low", risk="low"),
dict(base["alternatives"][1], cost="low", risk="low")]),
variant(chosen={"name": "use the host tool's own subagent mechanism", "why": "best"}),
variant(objections=[{"principle": PRINCIPLES[0], "applicable": True,
"objection": "x", "answer": "y"}]),
variant(objections=[dict(o, applicable=False, reason="n/a") if o.get("applicable") else o
for o in base["objections"]]),
variant(challenge={"by": "self", "recorded_at": "2026-01-01T00:00:00Z",
"objections": ["none"], "changes": []}),
variant(challenge={"by": "a subagent on a different model", "recorded_at": "2026-01-01T00:00:00Z",
"objections": [], "changes": ["changed things in response to the review"]}),
]
good_pass = sum(1 for d in goods if not self.errs(d))
filler_fail = sum(1 for d in fillers if self.errs(d))
self.assertGreaterEqual(len(goods), 12)
self.assertGreaterEqual(len(fillers), 12)
self.assertEqual((good_pass, filler_fail), (len(goods), len(fillers)),
"good %d/%d pass, filler %d/%d refused" % (good_pass, len(goods), filler_fail, len(fillers)))
class DesignCommandTests(PrinciplesCase):
def test_sisi_design_prints_principles_and_questions(self):
self.learn_all()
r = self.sisi("design")
self.assertEqual(r.returncode, 0, r.stderr)
for p in PRINCIPLES:
self.assertIn(p, r.stdout)
for key in ("implies", "provided", "alternatives", "chosen", "objections", "challenge"):
self.assertIn(key, r.stdout)
def test_contract_init_prints_principles_and_design_skeleton(self):
self.learn_all()
r = self.sisi("contract", "init", "--goal", "build the orchestrator")
self.assertEqual(r.returncode, 0, r.stdout)
self.assertIn(PRINCIPLES[0], r.stdout)
c = json.load(open(os.path.join(self.proj, ".sisi", "contract.json")))
self.assertIn("design", c)
for key in ("implies", "provided", "alternatives", "chosen", "objections", "challenge"):
self.assertIn(key, c["design"])
class DesignGateTests(PrinciplesCase):
def gate(self, payload):
return self.sisi("gate", stdin=json.dumps(payload))
def large_contract_project(self, design=None):
self.git_init()
c = contract([check("a", "true")])
if design is not None:
c["design"] = design
self.write_contract(c)
with open(os.path.join(self.proj, "big.txt"), "w") as f:
f.write("line\n" * 80)
return {"session_id": "gate-design-1", "cwd": self.proj, "stop_hook_active": False}
def test_large_change_without_design_is_sent_back_then_never_traps(self):
self.learn_all()
payload = self.large_contract_project()
msgs = []
for _ in range(5):
r = self.gate(payload)
out = r.stdout.strip()
if not out:
break
d = json.loads(out)
msgs.append(d)
if d.get("decision") != "block":
break
self.assertTrue(any("design" in (m.get("reason") or "") for m in msgs), msgs)
# never traps: within the send-back budget the turn is let through
self.assertLessEqual(len([m for m in msgs if m.get("decision") == "block"]), 3)
def test_large_change_with_good_design_is_not_sent_back_for_design(self):
self.learn_all()
payload = self.large_contract_project(design=good_design())
r = self.gate(payload)
self.assertNotIn("design section is missing", r.stdout)
def test_small_change_needs_no_design(self):
self.git_init()
self.write_contract(contract([check("a", "true")]))
with open(os.path.join(self.proj, "small.txt"), "w") as f:
f.write("one line\n")
r = self.gate({"session_id": "gate-design-small", "cwd": self.proj})
self.assertNotIn("design", r.stdout)
class PromptDesignTests(PrinciplesCase):
def test_design_work_gets_principles_and_instruction(self):
self.learn_all()
from sisi import prompt as P
ctx = P.build_context("Build an automatic orchestrator that delegates work to other agents "
"across the tools installed here, with routing and judged outcomes")
self.assertIn(PRINCIPLES[0], ctx)
self.assertIn("design", ctx.lower())
self.assertLessEqual(len(ctx), P.MAX_CHARS)
def test_questions_and_small_edits_get_no_design_block(self):
self.learn_all()
from sisi import prompt as P
for q in ("Should the orchestrator use subagents or command lines?",
"rename the helper that formats the orchestrator headings in the docs",
"fix the typo in the orchestrator help text on the second line"):
self.assertNotIn(PRINCIPLES[0], P.build_context(q), q)
def test_labelled_design_requests(self):
self.learn_all()
from sisi import prompt as P
should = [
"Build an automatic orchestrator that delegates work to other agents across tools",
"Design and implement a new storage layer for session records with migration",
"Create a command that discovers installed agent tools and routes work between them",
"Implement a plugin system so other tools can add their own checks to the gate",
]
should_not = [
"Why does the orchestrator choose that worker for this kind of work?",
"rename the local variable in the routing helper to something clearer",
"fix the off-by-one in the pagination control of the list view",
"What does the design section of a contract actually require in full?",
]
hits = sum(1 for t in should if "design section" in P.build_context(t))
false = sum(1 for t in should_not if "design section" in P.build_context(t))
self.assertEqual((hits, false), (len(should), 0),
"design hits %d/%d, false %d/%d" % (hits, len(should), false, len(should_not)))
class RuleDesignTests(SisiCase):
def test_first_rule_is_choose_the_approach_with_real_enforcement(self):
r = self.sisi("rule", "1")
self.assertEqual(r.returncode, 0, r.stderr)
self.assertIn("choose-the-approach", r.stdout)
self.assertIn("Why:", r.stdout)
from sisi import rulecmd
self.assertIn("design", rulecmd.enforcement_for("choose-the-approach"))
self.assertNotIn("not enforced", rulecmd.enforcement_for("choose-the-approach"))
if __name__ == "__main__":
unittest.main()
+82
View File
@@ -0,0 +1,82 @@
"""Session start and prompt hooks after the rework (R-17-3, R-12-12, target section 11)."""
import json, os, unittest
from support import *
class TickCleanTests(SisiCase):
def payload(self, **kw):
return json.dumps(dict({"session_id": "s1", "cwd": self.proj,
"hook_event_name": "SessionStart", "source": "startup"}, **kw))
def test_clean_home_prints_nothing(self):
"""R-17-3: in a clean home with nothing to act on, session start is silent."""
self.git_init()
self.sisi("install")
r = self.sisi("tick", stdin=self.payload())
self.assertEqual(r.returncode, 0)
self.assertEqual(r.stdout, "")
def test_broken_wiring_still_prints_one_line(self):
"""R-17-2: broken wiring is actionable, so it is the one line printed."""
os.makedirs(os.path.join(self.home, ".claude"))
r = self.sisi("tick", stdin=self.payload())
self.assertIn("sisi doctor", r.stdout)
self.assertLessEqual(len(r.stdout.strip().splitlines()), 1)
def test_handover_shown_once_per_session(self):
"""R-12-2: handover items for this project print once per session, not every session."""
self.git_init()
self.sisi("install")
from sisi import handover, scope
pid = scope.project_id(self.proj)
handover.add_item({"kind": "learn", "project": pid, "text": "file this fact"})
r1 = self.sisi("tick", stdin=self.payload())
self.assertIn("belong to this project", r1.stdout)
r2 = self.sisi("tick", stdin=self.payload(source="resume"))
self.assertNotIn("belong to this project", r2.stdout)
class PromptReworkTests(SisiCase):
def ctx(self, text):
from sisi import prompt as P
return P.build_context(text, session="rework")
def test_typo_fix_is_silent(self):
"""R-17-3: a trivial request gets no injection."""
self.assertEqual(self.ctx("fix a typo in the README"), "")
def test_question_is_silent(self):
"""R-17-3, R-12-12: a question naming no work gets no recipe."""
self.assertEqual(self.ctx("why is the build slow?"), "")
def test_map_printing_gets_feature_recipe(self):
"""SPEC Appendix B / R-4.1-1: the complex example gets its recipe at prompt time."""
ctx = self.ctx("add multi-page map printing with selectable paper size")
self.assertIn("feature", ctx)
self.assertLessEqual(len(ctx), 2000)
def test_accent_color_gets_ui_recipe(self):
"""SPEC Appendix A: the presentation example gets a fitting recipe."""
ctx = self.ctx("change the accent color of one UI component")
self.assertTrue("web-ui-change" in ctx or "native-gui-change" in ctx, ctx)
def test_no_handover_notice_in_prompt(self):
"""R-17-3: the per-prompt handover notice is gone."""
from sisi import handover, scope
pid = scope.project_id(self.proj)
handover.add_item({"kind": "learn", "project": pid, "text": "file this fact"})
for text in ("fix a typo in the README", "why is the build slow?",
"add multi-page map printing with selectable paper size"):
with self.subTest(text=text):
self.assertNotIn("belong to this project", self.ctx(text))
def test_no_design_block_anywhere(self):
"""Retired design section: no prompt prints its instruction."""
for text in ("build a new orchestration system for agents",
"design and build a plugin platform for the tool"):
with self.subTest(text=text):
self.assertNotIn("design section", self.ctx(text))
if __name__ == "__main__":
unittest.main()
+2
View File
@@ -163,6 +163,8 @@ class ImmediateEffectTests(LearningCase):
ids = [int(l.split()[0][1:]) for l in out if l.startswith("#")]
self.assertEqual(ids, [b, c, a]) # most seen first; the tie goes to the older lesson
self.assertEqual(self.lesson(b)["effect"], "backlog")
tick = self.sisi("tick", stdin=json.dumps({"session_id": "dev1", "cwd": self.proj, "source": "startup"})).stdout
self.assertNotIn("backlog", tick) # session start no longer prints the backlog
class DeliveryTests(LearningCase):
+136
View File
@@ -0,0 +1,136 @@
"""Structured matcher (R-5.2-1, R-5.2-2): labelled set written without the entries' own words.
Each case is (query, acceptable ids, kind) where kind is 'verifier' or 'recipe'.
Queries are phrased as someone who has not read the library would phrase them.
Top-1 / top-3 thresholds below sit a small margin under the level reached when
this set was built; the test fails if matching regresses under them.
"""
import unittest
from support import *
from sisi import verifiers as V
# (query, acceptable verifier ids)
VERIFIER_CASES = [
("fix the race condition in the worker pool", {"thread-sanitizer", "go-race-detector", "loom", "shuttle", "stress-repeat", "lock-order-and-deadlock"}),
("two background jobs keep stepping on the same shared counter", {"thread-sanitizer", "go-race-detector", "loom", "shuttle", "deterministic-simulation"}),
("the parser handles malformed CSV without falling over", {"atheris", "hypothesis", "hostile-input-from-schema", "cargo-fuzz", "proptest", "fast-check", "structure-aware-fuzzing", "jqwik", "go-fuzz", "jazzer"}),
("strange delimited files from users must not crash the import", {"atheris", "hypothesis", "hostile-input-from-schema", "cargo-fuzz", "proptest", "structure-aware-fuzzing"}),
("money rounding is correct to the cent", {"algebraic-laws", "exhaustive-small-domain", "hypothesis", "proptest", "differential-reference", "metamorphic", "golden-files-hand-verified"}),
("the invoice totals always add up whatever lines are on it", {"algebraic-laws", "hypothesis", "proptest", "metamorphic", "derived-view-agreement", "differential-reference"}),
("charges are never a fraction of a cent out", {"algebraic-laws", "exhaustive-small-domain", "hypothesis", "metamorphic", "differential-reference"}),
("any sequence of moves keeps the account balanced", {"algebraic-laws", "stateful-model-test", "model-test-from-spec", "replay-equivalence"}),
("old files from the previous release still open with the same figures", {"old-data-compatibility", "db-migration-safety", "packaging-install-upgrade"}),
("moving the stored records to the new shape loses nothing", {"db-migration-safety", "old-data-compatibility", "differential-old-vs-new"}),
("the page still looks the same where I did not touch it", {"visual-regression-web", "ui-structure-snapshot", "baseline-before-change"}),
("people using only a keyboard can still finish the form", {"accessibility-axe", "e2e-playwright", "owner-acceptance-runbook"}),
("would my checks notice if the calculation were quietly wrong", {"cargo-mutants", "mutmut", "mutation-on-diff", "vacuity-check", "assertion-strength-review", "check-the-checker", "pitest", "go-mutation", "stryker"}),
("the new check passes even when nothing ran at all", {"vacuity-check", "check-the-checker", "red-before-green"}),
("nothing that worked yesterday broke in the tidy-up", {"characterization-tests", "baseline-before-change", "differential-old-vs-new"}),
("a hostile file at the boundary gets a clean refusal, not a crash", {"hostile-input-from-schema", "atheris", "cargo-fuzz", "codeql"}),
("no password or token ends up in the history", {"secret-scanning", "sensitive-data-leak-test"}),
("every state the workflow can sit in is one we meant to allow", {"tlaplus", "quint", "alloy", "small-scope-enumeration", "illegal-states-unrepresentable", "model-coverage"}),
("after the power dies mid-save the data reopen intact", {"fault-injection-storage"}),
("reading it back gives exactly what was written, every shape of value", {"round-trip", "stateful-model-test"}),
("the service still answers each caller the way they expect", {"contract-testing-pact", "smoke-after-deploy", "load-test-k6"}),
("it works from a brand-new checkout, not just my messy tree", {"clean-clone-build"}),
]
RECIPE_CASES = [
("fix the race condition", {"concurrent-code"}),
("two jobs running at once keep losing each other's updates", {"concurrent-code"}),
("add multi-page map printing with selectable paper size", {"feature"}),
("change the accent color of one UI component", {"web-ui-change"}),
("let people print a big map over several sheets of paper", {"feature"}),
("make the settings page button a different colour", {"web-ui-change"}),
("the total on invoices is a cent out when it rounds", {"numeric-or-financial-core"}),
("users' spreadsheet files with broken rows break the import", {"parser-or-codec"}),
("numbers coming out of the tax calculation cannot be trusted", {"numeric-or-financial-core"}),
("reported defect: the export button does nothing on the second click", {"bugfix"}),
("it worked before the tidy-up and must behave identically after", {"refactor"}),
("restructure the internals without changing what anyone sees", {"refactor"}),
("ship the next version and put the tag on it", {"release"}),
("move all the stored records onto the new layout safely", {"data-migration"}),
("the stored shape is changing and old records must survive", {"data-migration"}),
("someone found a way in through the search box input", {"security-fix"}),
("make the nightly job finish in half the time", {"performance-work"}),
("why is everything so sluggish since the last change", {"performance-work"}),
("rewrite the bit that turns text files into tables", {"parser-or-codec"}),
("a whole new app from this one-line idea", {"new-product"}),
("a package other teams will build on top of", {"new-library"}),
("the bit that keeps files on disk and reads them back after a crash", {"storage-engine"}),
]
ALL_CASES = ([(q, ids, "verifier") for q, ids in VERIFIER_CASES]
+ [(q, ids, "recipe") for q, ids in RECIPE_CASES])
# Measured when built: new top-1 0.75, top-3 0.93 (old word overlap: 0.55 / 0.68).
# Thresholds are that minus a small margin.
TOP1_MIN = 0.68
TOP3_MIN = 0.88
def _ranked_ids(query, kind):
if kind == "verifier":
return [e["id"] for _, e in V.rank_verifiers(query)]
return [r["id"] for _, r in V.rank_recipes(query)]
class LabelledSetTests(SisiCase):
def test_labelled_set_accuracy(self):
"""R-5.2-2: matching is good enough on requests that share no words with the entries."""
self.assertGreaterEqual(len(ALL_CASES), 40)
top1 = top3 = 0
misses = []
for query, acceptable, kind in ALL_CASES:
ids = _ranked_ids(query, kind)
if ids and ids[0] in acceptable:
top1 += 1
if any(i in acceptable for i in ids[:3]):
top3 += 1
else:
misses.append((query, ids[:3]))
n = len(ALL_CASES)
self.assertGreaterEqual(top3 / n, TOP3_MIN, "top-3 misses: %r" % (misses,))
self.assertGreaterEqual(top1 / n, TOP1_MIN, "top-1 too low; misses: %r" % (misses,))
def test_audit_failures_rank_first(self):
"""R-5.2-1: the audit's named failures are fixed."""
self.assertEqual(_ranked_ids("fix the race condition", "recipe")[0], "concurrent-code")
ids = _ranked_ids("the parser handles malformed CSV", "verifier")
fuzz_or_property = {"atheris", "hypothesis", "cargo-fuzz", "proptest", "fast-check",
"hostile-input-from-schema", "structure-aware-fuzzing", "jqwik", "go-fuzz", "jazzer"}
self.assertTrue(any(i in fuzz_or_property for i in ids[:3]), ids[:3])
money = _ranked_ids("money rounding is correct", "verifier")
self.assertTrue(any(i in money for i in
[e["id"] for _, e in V.rank_verifiers("money rounding is correct")
if "money" in e["kinds"]][:3] or money[:3]), money[:3])
def test_spec_examples_get_recipes(self):
"""SPEC Appendix A/B: both worked examples get a fitting recipe."""
self.assertEqual(_ranked_ids("add multi-page map printing with selectable paper size", "recipe")[0], "feature")
self.assertIn(_ranked_ids("change the accent color of one UI component", "recipe")[0],
("web-ui-change", "native-gui-change"))
class RankingTests(SisiCase):
def test_proven_ranks_above_documentation_only(self):
"""R-5.2-6: an entry proven on a real run outranks a docs-only twin."""
import os
vdir = os.path.join(self.tmp, "v2")
os.makedirs(os.path.join(vdir, "prove"))
body = "\n".join("## " + h + "\ntext" for h in V.V_HEADINGS) + "\n"
def entry(id, verified):
return ("---\nid: %s\ntitle: Cache check %s\nanswers: Does the cache evict correctly?\nrung: 3\n"
"section: prove\nlanguages: any\nkinds: general\ncost: low\ndetect:\nran_here: no\n"
"verified: %s\n---\n%s" % (id, id, verified, body))
with open(os.path.join(vdir, "prove", "docs-twin.md"), "w") as f:
f.write(entry("docs-twin", "docs"))
with open(os.path.join(vdir, "prove", "ran-twin.md"), "w") as f:
f.write(entry("ran-twin", "ran"))
ranked = V.rank_verifiers("cache evict", entries=V.load_verifiers(vdir))
self.assertEqual(ranked[0][1]["id"], "ran-twin")
if __name__ == "__main__":
unittest.main()
+1 -1
View File
@@ -452,7 +452,7 @@ class MigrationTests(PersonalCase):
from sisi import trust
self.assertTrue(trust.is_trusted(self.proj))
self.assertEqual(self.ok("tick", stdin="{}").returncode, 0)
self.assertIn("Always watch", self.sisi("tick", stdin="{}").stdout)
self.assertEqual(self.sisi("tick", stdin="{}").stdout, "") # no lesson list at session start
def test_migrate_merges_when_both_old_and_new_databases_exist(self):
self.legacy_state(extra_lesson=True)
+2 -2
View File
@@ -429,7 +429,7 @@ class TickBlockTests(RetroCase):
def test_block_is_framed_as_information(self):
self.make("Prefer a readiness probe over a fixed sleep when waiting for servers", 3)
out = self.tick()
out = retro.tick_block(self.proj, session="t")
self.assertIn("notes left by earlier agents", out)
self.assertIn("not as commands", out)
self.assertIn("(seen 3)", out)
@@ -442,7 +442,7 @@ class TickBlockTests(RetroCase):
self.make("global heavy lesson about caching", 9, repo=self.tmp + "/other")
self.make("local light lesson about probes", 1)
self.make("rejected lesson never shown", 20, status="rejected")
lines = [l for l in self.tick().splitlines() if l.startswith("- ")]
lines = [l for l in retro.tick_block(self.proj, session="t").splitlines() if l.startswith("- ")]
self.assertTrue(lines[0].startswith("- local light"), lines)
self.assertTrue(lines[1].startswith("- global heavy"))
self.assertFalse(any("rejected" in l for l in lines))
+110
View File
@@ -0,0 +1,110 @@
"""Risk profiles (R-5.3-1, R-5.3-2, R-5.3-3..R-5.3-10)."""
import json, os, random, unittest
from support import *
from sisi import risk
class FloorTests(SisiCase):
def test_docs_only_is_trivial(self):
"""R-5.3-4: documentation/text/styling only is trivial."""
p, reasons = risk.assess(["README.md", "docs/guide.txt", "web/site.css"])
self.assertEqual(p, "trivial")
self.assertTrue(reasons)
def test_single_module_is_isolated(self):
"""R-5.3-5: one module's behaviour is isolated."""
p, _ = risk.assess(["src/calc.py"])
self.assertEqual(p, "isolated")
def test_logic_kinds(self):
"""R-5.3-6: algorithms, parsing and money are logic."""
for path in ("src/parser/lexer.py", "src/money/rounding.py", "src/algo/sort.py"):
with self.subTest(path=path):
p, _ = risk.assess([path])
self.assertEqual(p, "logic")
def test_two_packages_is_integration(self):
"""R-5.3-7, R-5.3-11: several top-level packages is integration."""
p, reasons = risk.assess(["src/alpha/a.py", "src/beta/b.py"])
self.assertEqual(p, "integration")
self.assertTrue(any("package" in r for r in reasons))
def test_migration_is_data(self):
"""R-5.3-8: schema/persistence/migration is data."""
p, _ = risk.assess(["db/migrations/0002_add_col.sql"])
self.assertEqual(p, "data")
def test_auth_is_critical(self):
"""R-5.3-9: authorization/secrets/concurrency primitives are critical."""
for path in ("src/auth/login.py", "src/crypto/keys.py", "src/sync/mutex.py"):
with self.subTest(path=path):
p, _ = risk.assess([path])
self.assertEqual(p, "critical")
def test_diff_keyword_raises_floor(self):
"""R-5.3-1: content keywords count, not only paths."""
p, _ = risk.assess(["src/util.py"], diff_text="+ encrypt the password at rest")
self.assertEqual(p, "critical")
def test_adding_path_never_lowers_floor(self):
"""R-5.3-1: property — the floor is monotone in the change set."""
rng = random.Random(7)
pool = ["README.md", "src/a/x.py", "src/b/y.py", "db/migrations/m.sql",
"src/auth/login.py", "src/parser/p.py", "VERSION", "web/site.css"]
order = {name: i for i, name in enumerate(risk.PROFILES)}
for _ in range(80):
base = rng.sample(pool, rng.randint(0, 4))
extra = rng.choice(pool)
before, _ = risk.assess(base)
after, _ = risk.assess(base + [extra])
self.assertGreaterEqual(order[after], order[before], (base, extra))
def test_project_override_and_requirements_table(self):
"""R-5.3-3: a project may override; each profile carries its requirements."""
p, _ = risk.assess(["src/special/thing.py"],
extra_patterns=[{"glob": "**/special/**", "profile": "data",
"reason": "project override: special holds stored data"}])
self.assertEqual(p, "data")
req = risk.requirements_for("trivial")
self.assertFalse(req["contract"])
self.assertTrue(risk.requirements_for("critical")["independent_evidence"])
self.assertTrue(risk.requirements_for("release")["contract"])
class RiskCliTests(SisiCase):
def _repo_with(self, files):
self.git_init()
for rel, text in files.items():
p = os.path.join(self.proj, rel)
os.makedirs(os.path.dirname(p), exist_ok=True)
with open(p, "w") as f:
f.write(text)
def test_risk_json_readme_change(self):
"""R-5.3-2: a README edit does not get the full process."""
self._repo_with({"README.md": "# hi\nchanged\n"})
r = self.sisi("risk", "--json")
self.assertEqual(r.returncode, 0, r.stderr)
d = json.loads(r.stdout)
self.assertEqual(d["floor"], "trivial")
self.assertIn("requirements", d)
def test_risk_json_migration_change(self):
"""R-5.3-8: a migrations change floors at data."""
self._repo_with({"db/migrations/0001.sql": "ALTER TABLE t ADD c INT;\n"})
d = json.loads(self.sisi("risk", "--json").stdout)
self.assertEqual(d["floor"], "data")
def test_risk_declared_profile_from_contract(self):
"""R-5.3-3: the declared profile in .sisi/contract.json is reported."""
self._repo_with({"src/a.py": "x = 1\n"})
os.makedirs(os.path.join(self.proj, ".sisi"), exist_ok=True)
with open(os.path.join(self.proj, ".sisi", "contract.json"), "w") as f:
json.dump({"id": "t", "goal": "g", "checks": [], "risk": {"profile": "logic"}}, f)
d = json.loads(self.sisi("risk", "--json").stdout)
self.assertEqual(d["declared"], "logic")
if __name__ == "__main__":
unittest.main()
+4 -4
View File
@@ -316,17 +316,17 @@ class TickDeepTests(SisiCase):
self.git_init()
def test_line_for_not_fresh_states_silent_when_fresh_or_untrusted(self):
# Session start no longer prints deep-check state; `sisi verify --state` owns it.
self.write_contract(contract([check("f", "true"), deepc("d")]))
self.assertIn("never-run", self.tick())
self.assertEqual(len(self.tick().strip().splitlines()), 1)
self.assertEqual(self.tick(), "")
self.sisi("verify", "--deep")
self.assertEqual(self.tick(), "")
with open(os.path.join(self.proj, "n.txt"), "w") as f:
f.write("x")
self.assertIn("stale-pass", self.tick())
self.assertEqual(self.tick(), "")
self.write_contract(contract([check("f", "true"), deepc("d", "false")]))
self.sisi("verify", "--deep")
self.assertIn("failed", self.tick())
self.assertEqual(self.tick(), "")
self.write_contract(contract([check("f", "true"), deepc("d")]), trusted=False)
os.remove(os.path.join(self.data, "trusted.json"))
self.assertEqual(self.tick(), "")