Item 4: remove guarded seams and dead code between the merged pieces. done 4 / next 5 (grouped help)
This commit is contained in:
1 parent
ed018a364c
commit
6787ef0ae9
23 files changed
+82
-261
No files matched your search
+12
-16
@@ -18,7 +18,7 @@ that shows it:
|
|||||||
| Work at a higher level (functions, modules, products) | size of verified work delivered per human message |
|
| Work at a higher level (functions, modules, products) | size of verified work delivered per human message |
|
||||||
| Verifiable outcomes, formal where possible | share of delivered claims backed by a check that ran, by rung |
|
| Verifiable outcomes, formal where possible | share of delivered claims backed by a check that ran, by rung |
|
||||||
| Hands off | human minutes and blocking questions per delivered piece of work |
|
| Hands off | human minutes and blocking questions per delivered piece of work |
|
||||||
| Delivered sooner, with no weaker check | median time from request to verified result (`sisi time`) |
|
| Delivered sooner, with no weaker check | median time from request to verified result (`sisi status`) |
|
||||||
| Improves itself from use, everywhere | the numbers above, as trends, across all tools |
|
| Improves itself from use, everywhere | the numbers above, as trends, across all tools |
|
||||||
|
|
||||||
## The objective
|
## The objective
|
||||||
@@ -30,9 +30,8 @@ with a weaker check or a smaller result.
|
|||||||
|
|
||||||
Time to delivery is measured, not guessed. Each time the end-of-turn gate lets a turn end it records one
|
Time to delivery is measured, not guessed. Each time the end-of-turn gate lets a turn end it records one
|
||||||
delivery row: the time since the last message the human actually typed (hook feedback and tool results do not
|
delivery row: the time since the last message the human actually typed (hook feedback and tool results do not
|
||||||
count), how many times the gate sent the agent back, and how long the checks ran. `sisi time` shows the median
|
count), how many times the gate sent the agent back, and how long the checks ran. `sisi status` shows the
|
||||||
and 90th percentile for the last 7 days against the 7 days before, the share spent in checks, and the five
|
median and 90th percentile by project, risk profile, model and policy version.
|
||||||
slowest checks; `sisi status` shows the 7-day median.
|
|
||||||
|
|
||||||
A learned change that speeds things up but fails a check is rejected. A learned change that keeps every check
|
A learned change that speeds things up but fails a check is rejected. A learned change that keeps every check
|
||||||
passing but makes median delivery slower is flagged for reversal. (Built: `sisi cycle status` flags a cycle
|
passing but makes median delivery slower is flagged for reversal. (Built: `sisi cycle status` flags a cycle
|
||||||
@@ -126,12 +125,10 @@ runs alone. Results are reported in contract order either way.
|
|||||||
|
|
||||||
**Enforcement.** The tool's end-of-turn hook calls `sisi verify`. If a contract exists and a check fails or was
|
**Enforcement.** The tool's end-of-turn hook calls `sisi verify`. If a contract exists and a check fails or was
|
||||||
not run, the agent is sent back with the failures and cannot report the work as done. If no contract exists and
|
not run, the agent is sent back with the failures and cannot report the work as done. If no contract exists and
|
||||||
the change is larger than a small threshold, the agent is sent back to write one; a change that size
|
the change is larger than its risk profile allows without one, the agent is sent back to write one. Small
|
||||||
with a contract whose design section is missing or fails validation is sent back to fill it. Small
|
|
||||||
edits and subagents pass untouched, and the same send-back budget bounds every send-back, so no
|
edits and subagents pass untouched, and the same send-back budget bounds every send-back, so no
|
||||||
session is trapped. Request-time delivery hands the standing principles and the design instruction
|
session is trapped. Request-time delivery hands the standing principles over when a request reads as
|
||||||
over when a request reads as design or build work, and `sisi design` prints them before a contract
|
design or build work.
|
||||||
exists.
|
|
||||||
Claude Code supports a blocking stop hook. The equivalent in OpenCode, Codex and Muse is not verified; where it
|
Claude Code supports a blocking stop hook. The equivalent in OpenCode, Codex and Muse is not verified; where it
|
||||||
does not exist, verification is meant to run at the next session start and failures to be reported then (that
|
does not exist, verification is meant to run at the next session start and failures to be reported then (that
|
||||||
fallback is a design intention, not built).
|
fallback is a design intention, not built).
|
||||||
@@ -315,19 +312,18 @@ Built and covered by tests:
|
|||||||
where nothing blocks.
|
where nothing blocks.
|
||||||
- The rulebook (`canon/core.md`), the risk table, the verifier library and the recipes.
|
- The rulebook (`canon/core.md`), the risk table, the verifier library and the recipes.
|
||||||
- Retrospectives and lessons (`sisi retro`, `sisi lessons`), `sisi learn` live at once, time to delivery
|
- Retrospectives and lessons (`sisi retro`, `sisi lessons`), `sisi learn` live at once, time to delivery
|
||||||
(`sisi time`).
|
(`sisi status`).
|
||||||
- Choosing the approach as a checked step: the contract design section, `sisi design`, the gate's
|
- Choosing the approach as a checked step: the contract's `approach` and the request-time delivery of the
|
||||||
design send-back on large changes, and request-time delivery of the standing principles for design
|
standing principles for design or build requests. `sisi rule` reports the rulebook's enforcement.
|
||||||
or build requests. The rulebook's first rule states it and `sisi rule` reports its enforcement.
|
|
||||||
- Patterns: each retro names the general failure of thinking behind the incident; patterns are
|
- Patterns: each retro names the general failure of thinking behind the incident; patterns are
|
||||||
first-class, merged in rounds, and promoted into the rulebook as strategic behaviours past a
|
first-class, merged in rounds, and promoted into the rulebook as strategic behaviours past a
|
||||||
threshold; the digest and `sisi improve` show them first. Three tiers (`core`, `user`, `project`)
|
threshold; `sisi status --learning` shows them first. Three tiers (`core`, `user`, `project`)
|
||||||
replace the two-way scope, with older universal items tiered by the next round, and `sisi promote`
|
replace the two-way scope, with older universal items tiered by the next round, and `sisi promote`
|
||||||
listing, writing (from the clone) or exporting core items.
|
listing, writing (from the clone) or exporting core items.
|
||||||
- The lesson loop: immediate effects in the overlay (field notes, draft recipes, learned notes, `sisi backlog`),
|
- The lesson loop: immediate effects in the overlay (field notes, draft recipes, learned notes),
|
||||||
moment-of-use delivery with recorded showings, per-lesson measurement, the strength ladder with enforced
|
moment-of-use delivery with recorded showings, per-lesson measurement, the strength ladder with enforced
|
||||||
checks, `sisi cycle` (due counter, brief, validated apply under lock and base version, exact revert, status
|
checks, `sisi cycle` (due counter, brief, validated apply under lock and base version, exact revert, status
|
||||||
with worse-cycle flagging) and `sisi improve`.
|
with worse-cycle flagging).
|
||||||
- Personal data, the overlay, update, export and import, releases and rollback, promotion of a personal item
|
- Personal data, the overlay, update, export and import, releases and rollback, promotion of a personal item
|
||||||
into the product.
|
into the product.
|
||||||
- The data layer for learning: harvest of Claude Code transcripts, task set, ground truth, escape candidates,
|
- The data layer for learning: harvest of Claude Code transcripts, task set, ground truth, escape candidates,
|
||||||
|
|||||||
@@ -173,6 +173,5 @@ learnings in scope that target that entry.
|
|||||||
- `cycle.risk_patterns(cwd)` — the learned risk patterns that apply in a project (`risk.load_patterns`).
|
- `cycle.risk_patterns(cwd)` — the learned risk patterns that apply in a project (`risk.load_patterns`).
|
||||||
- `cycle.routing_adjustments(project)` — the learned routing adjustments that apply in a project.
|
- `cycle.routing_adjustments(project)` — the learned routing adjustments that apply in a project.
|
||||||
- `cycle.due_notice()` — the session-start lines (cycle due, decision waiting).
|
- `cycle.due_notice()` — the session-start lines (cycle due, decision waiting).
|
||||||
- `retro.satisfied(repo, since, fp)` and `retro.TEMPLATE` — what the gate asks.
|
|
||||||
- `learning.delivery_text(project, query, targets=())` — what the prompt hook may add.
|
- `learning.delivery_text(project, query, targets=())` — what the prompt hook may add.
|
||||||
- `evaluate.validate_command(repo, before, after, cmd)` — the replay.
|
- `evaluate.validate_command(repo, before, after, cmd)` — the replay.
|
||||||
+1
-5
@@ -7,7 +7,7 @@ whose config folder does not exist is skipped and reported, never an error. Only
|
|||||||
from the tool's own documentation, `--help`, installed files or a local spike are wired here (see
|
from the tool's own documentation, `--help`, installed files or a local spike are wired here (see
|
||||||
docs/harnesses.md); anything unconfirmed is reported in doctor, not guessed into a config.
|
docs/harnesses.md); anything unconfirmed is reported in doctor, not guessed into a config.
|
||||||
"""
|
"""
|
||||||
import copy, difflib, hashlib, json, os, shlex
|
import difflib, hashlib, json, os
|
||||||
|
|
||||||
from . import hookjson, paths, store, wiring
|
from . import hookjson, paths, store, wiring
|
||||||
|
|
||||||
@@ -515,10 +515,6 @@ class Adapter:
|
|||||||
"detail": "not wired", "action": None}
|
"detail": "not wired", "action": None}
|
||||||
|
|
||||||
|
|
||||||
def _st(a, rulebook, tick, wired, detail, action=None):
|
|
||||||
return {"tool": a.name, "detected": True, "rulebook": rulebook, "tick": tick,
|
|
||||||
"enforcement": a.enforcement, "via": a.via, "wired": wired, "detail": detail, "action": action}
|
|
||||||
|
|
||||||
|
|
||||||
class Codex(Adapter):
|
class Codex(Adapter):
|
||||||
name, enforcement, via = "codex", "blocks", "Stop"
|
name, enforcement, via = "codex", "blocks", "Stop"
|
||||||
|
|||||||
+10
-14
@@ -409,17 +409,13 @@ def main(argv):
|
|||||||
|
|
||||||
|
|
||||||
def _learn_cli(cmd, args):
|
def _learn_cli(cmd, args):
|
||||||
"""Data-layer commands (harvest, tasks, ...) live in learn_cli. The CLI works without it, even if it is broken."""
|
"""Data-layer commands (harvest, tasks, ...) live in learn_cli; None when `cmd` is not one of them."""
|
||||||
try:
|
import argparse
|
||||||
import argparse
|
from . import learn_cli
|
||||||
from . import learn_cli
|
ap = argparse.ArgumentParser(prog="sisi")
|
||||||
ap = argparse.ArgumentParser(prog="sisi")
|
sub = ap.add_subparsers(dest="cmd")
|
||||||
sub = ap.add_subparsers(dest="cmd")
|
learn_cli.register(sub)
|
||||||
learn_cli.register(sub)
|
if cmd not in sub.choices:
|
||||||
if cmd not in sub.choices:
|
return None
|
||||||
return None
|
ns = ap.parse_args([cmd] + args)
|
||||||
ns = ap.parse_args([cmd] + args)
|
return ns.func(ns)
|
||||||
return ns.func(ns)
|
|
||||||
except (ImportError, AttributeError, TypeError) as e:
|
|
||||||
print("sisi: the %r command is unavailable (%s)" % (cmd, e), file=sys.stderr)
|
|
||||||
return 70
|
|
||||||
@@ -190,7 +190,6 @@ _PRINT_WORDS = {"echo", "printf"}
|
|||||||
_SHELLS = {"sh", "bash", "dash", "zsh", "/bin/sh", "/bin/bash", "/usr/bin/env"}
|
_SHELLS = {"sh", "bash", "dash", "zsh", "/bin/sh", "/bin/bash", "/usr/bin/env"}
|
||||||
_WRAPPERS = {"env", "command", "exec", "time", "nohup", "builtin"}
|
_WRAPPERS = {"env", "command", "exec", "time", "nohup", "builtin"}
|
||||||
_TESTERS = {"test", "["}
|
_TESTERS = {"test", "["}
|
||||||
_OPS = {"&&", "||", ";", "|", "&"}
|
|
||||||
|
|
||||||
|
|
||||||
def _lex(s):
|
def _lex(s):
|
||||||
|
|||||||
@@ -134,10 +134,6 @@ def routing_adjustments(project):
|
|||||||
|
|
||||||
# ---- enforced checks (verify.py seam) ----------------------------------------------
|
# ---- enforced checks (verify.py seam) ----------------------------------------------
|
||||||
|
|
||||||
def enforced_path():
|
|
||||||
return paths.overlay_dir("enforced.json")
|
|
||||||
|
|
||||||
|
|
||||||
def load_enforced(project=None):
|
def load_enforced(project=None):
|
||||||
"""Enforced checks; with a project, only those that apply in it."""
|
"""Enforced checks; with a project, only those that apply in it."""
|
||||||
checks = [c for c in _overlay_json("enforced.json", "checks").get("checks", []) if isinstance(c, dict)]
|
checks = [c for c in _overlay_json("enforced.json", "checks").get("checks", []) if isinstance(c, dict)]
|
||||||
|
|||||||
+1
-1
@@ -37,7 +37,7 @@ sub-agents is not machine-written.
|
|||||||
Pasted content does not count towards length (it is a human attachment). The heuristic errs towards
|
Pasted content does not count towards length (it is a human attachment). The heuristic errs towards
|
||||||
calling things machine-written: a false "machine" only removes a session from the human task set.
|
calling things machine-written: a false "machine" only removes a session from the human task set.
|
||||||
"""
|
"""
|
||||||
import json, os, re, sys, time
|
import json, os, re
|
||||||
from collections import namedtuple
|
from collections import namedtuple
|
||||||
|
|
||||||
from . import paths
|
from . import paths
|
||||||
|
|||||||
@@ -234,18 +234,6 @@ def replace_node(text, node, new_text):
|
|||||||
return text[:node.start] + new_text + text[node.end:]
|
return text[:node.start] + new_text + text[node.end:]
|
||||||
|
|
||||||
|
|
||||||
def get_path(text, root, keys):
|
|
||||||
node = root
|
|
||||||
for k in keys:
|
|
||||||
if node.kind == "lit" and node.value == "null":
|
|
||||||
return node
|
|
||||||
found = member(node, k)
|
|
||||||
if found is None:
|
|
||||||
return None
|
|
||||||
node = found[1]
|
|
||||||
return node
|
|
||||||
|
|
||||||
|
|
||||||
def _dump(v):
|
def _dump(v):
|
||||||
return json.dumps(v, ensure_ascii=False)
|
return json.dumps(v, ensure_ascii=False)
|
||||||
|
|
||||||
|
|||||||
@@ -9,11 +9,6 @@ import argparse, json, sys, time
|
|||||||
from . import store
|
from . import store
|
||||||
|
|
||||||
|
|
||||||
def _con():
|
|
||||||
from . import harvest
|
|
||||||
return harvest.connect()
|
|
||||||
|
|
||||||
|
|
||||||
def cmd_harvest(args):
|
def cmd_harvest(args):
|
||||||
from . import groundtruth, harvest
|
from . import groundtruth, harvest
|
||||||
t = time.time()
|
t = time.time()
|
||||||
|
|||||||
+1
-1
@@ -583,7 +583,7 @@ def statement_origin(statement):
|
|||||||
text = harvest.typed_text(d)[0]
|
text = harvest.typed_text(d)[0]
|
||||||
if text and want in _norm_words(text):
|
if text and want in _norm_words(text):
|
||||||
return "typed by the owner"
|
return "typed by the owner"
|
||||||
except (OSError, ImportError):
|
except OSError:
|
||||||
pass
|
pass
|
||||||
return "relayed by an agent"
|
return "relayed by an agent"
|
||||||
|
|
||||||
|
|||||||
@@ -98,30 +98,6 @@ def personal_config():
|
|||||||
return {}
|
return {}
|
||||||
|
|
||||||
|
|
||||||
def set_personal_config(keys, value, msg):
|
|
||||||
"""Set (or with None remove) a nested key in the personal config.json; one commit in the personal repository."""
|
|
||||||
import json
|
|
||||||
from . import pdata
|
|
||||||
cfg = personal_config()
|
|
||||||
d = cfg
|
|
||||||
for k in keys[:-1]:
|
|
||||||
d = d.setdefault(k, {}) if isinstance(d.get(k, {}), dict) else d.setdefault(k, {})
|
|
||||||
if value is None:
|
|
||||||
d.pop(keys[-1], None)
|
|
||||||
if not d and len(keys) > 1:
|
|
||||||
cfg.pop(keys[0], None)
|
|
||||||
else:
|
|
||||||
d[keys[-1]] = value
|
|
||||||
os.makedirs(data(), exist_ok=True)
|
|
||||||
p = data_file("config.json")
|
|
||||||
tmp = p + ".sisi-tmp"
|
|
||||||
with open(tmp, "w", encoding="utf-8") as f:
|
|
||||||
json.dump(cfg, f, indent=2, sort_keys=True)
|
|
||||||
f.write("\n")
|
|
||||||
os.replace(tmp, p)
|
|
||||||
pdata.commit(msg, ["config.json"])
|
|
||||||
|
|
||||||
|
|
||||||
def state_file(name):
|
def state_file(name):
|
||||||
return os.path.join(state(), name)
|
return os.path.join(state(), name)
|
||||||
|
|
||||||
|
|||||||
+4
-55
@@ -4,28 +4,11 @@ No arguments: print the unit's record and what stands out. With --finding: recor
|
|||||||
finding with a disposition. Only the fields the disposition needs are asked for; search
|
finding with a disposition. Only the fields the disposition needs are asked for; search
|
||||||
terms, topics and short lines are derived by the tool. A finding that resembles an
|
terms, topics and short lines are derived by the tool. A finding that resembles an
|
||||||
existing learning is attached to it as a recurrence candidate, never refused in a loop.
|
existing learning is attached to it as a recurrence candidate, never refused in a loop.
|
||||||
|
|
||||||
Gate compatibility (gate.py calls these; its control flow is unchanged): TEMPLATE,
|
|
||||||
satisfied(), repo_of(), lessons_block().
|
|
||||||
"""
|
"""
|
||||||
import hashlib, json, os, subprocess, sys
|
import hashlib, json, os, subprocess, sys
|
||||||
|
|
||||||
from . import learning as L, paths
|
from . import learning as L, paths
|
||||||
|
|
||||||
TEMPLATE = (
|
|
||||||
"Before this turn ends, record the retro for this unit ({n}).\n"
|
|
||||||
"Run `sisi retro` first: it prints the unit's record. Then record at least one finding:\n"
|
|
||||||
" sisi retro --finding \"<what happened, with the evidence>\" --cause \"<root cause>\" "
|
|
||||||
"--impact value|correctness|time|cost|attention --disposition promote|record|drop\n"
|
|
||||||
" promote also needs: --change \"<exact improvement>\" --mechanism policy|orchestration|skill|tool|"
|
|
||||||
"infrastructure|verification|knowledge|benchmark --expect \"<observable effect>\" --validate \"<how it will be tested>\"\n"
|
|
||||||
" record also needs: --limits \"<where it applies and where it does not>\"\n"
|
|
||||||
" drop also needs: --why-not \"<why it is not worth promoting>\"\n"
|
|
||||||
"Generic findings are refused. A finding that resembles a learning in scope here is attached to it as\n"
|
|
||||||
"a recurrence (--new records it as its own); --same-as ID names the learning it repeats.\n"
|
|
||||||
"A parent adopts a subagent's candidate by id: sisi retro --adopt ID."
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def repo_of(cwd):
|
def repo_of(cwd):
|
||||||
return L.project_key(cwd)
|
return L.project_key(cwd)
|
||||||
@@ -40,39 +23,12 @@ def _git_head(cwd):
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
def satisfied(repo, since, fp):
|
|
||||||
"""Gate seam: was a retro recorded for the current unit of this project?"""
|
|
||||||
try:
|
|
||||||
uid = L.unit_id(repo)
|
|
||||||
if L.findings_for_unit(repo, uid):
|
|
||||||
return True
|
|
||||||
# A finding recorded in this project since the request started also counts:
|
|
||||||
# the gate passes `since` from its own session bookkeeping.
|
|
||||||
pk = L.project_key(repo)
|
|
||||||
return any(f.get("project") == pk and (since is None or str(f.get("ts", "")) >= str(since))
|
|
||||||
for f in L.load_findings()) if since else False
|
|
||||||
except Exception:
|
|
||||||
return False
|
|
||||||
|
|
||||||
|
|
||||||
def lessons_block(query, place, session=None, limit=3, max_chars=600, extra=""):
|
|
||||||
"""Gate seam: learnings in scope as background information. Nothing is recorded as shown."""
|
|
||||||
try:
|
|
||||||
text = L.delivery_text(os.getcwd(), str(query))
|
|
||||||
return text[:max_chars] if text else ""
|
|
||||||
except Exception:
|
|
||||||
return ""
|
|
||||||
|
|
||||||
|
|
||||||
def unit_summary(project):
|
def unit_summary(project):
|
||||||
"""What `sisi retro` with no arguments prints: the unit's record and what stands out."""
|
"""What `sisi retro` with no arguments prints: the unit's record and what stands out."""
|
||||||
try:
|
from . import unit as _unit
|
||||||
from . import unit as _unit # work-unit worker's module, when merged
|
text = _unit.summary_for_retro(project)
|
||||||
text = _unit.summary_for_retro(project)
|
if text:
|
||||||
if text:
|
return text
|
||||||
return text
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
lines = []
|
lines = []
|
||||||
try:
|
try:
|
||||||
with open(os.path.join(project, ".sisi", "contract.json"), encoding="utf-8") as f:
|
with open(os.path.join(project, ".sisi", "contract.json"), encoding="utf-8") as f:
|
||||||
@@ -91,13 +47,6 @@ def unit_summary(project):
|
|||||||
lines.append("recent verification: %d result(s) on record, %d failed" % (len(rows), len(fails)))
|
lines.append("recent verification: %d result(s) on record, %d failed" % (len(rows), len(fails)))
|
||||||
except (OSError, ValueError):
|
except (OSError, ValueError):
|
||||||
pass
|
pass
|
||||||
try:
|
|
||||||
from . import delivery
|
|
||||||
d = delivery.current(project) if hasattr(delivery, "current") else None
|
|
||||||
if d:
|
|
||||||
lines.append("delivery: %s" % d)
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
head = _git_head(project)
|
head = _git_head(project)
|
||||||
if head:
|
if head:
|
||||||
lines.append("project HEAD: %s" % head[:12])
|
lines.append("project HEAD: %s" % head[:12])
|
||||||
|
|||||||
@@ -38,7 +38,6 @@ import fnmatch, json, os, re, subprocess
|
|||||||
|
|
||||||
PROFILES = ["trivial", "isolated", "logic", "integration", "data", "critical", "release"]
|
PROFILES = ["trivial", "isolated", "logic", "integration", "data", "critical", "release"]
|
||||||
_ORDER = {name: i for i, name in enumerate(PROFILES)}
|
_ORDER = {name: i for i, name in enumerate(PROFILES)}
|
||||||
_TRIVIAL_PROFILES = {"trivial"}
|
|
||||||
_DEFAULT_REASON = "ordinary source file: one module's behaviour"
|
_DEFAULT_REASON = "ordinary source file: one module's behaviour"
|
||||||
_CONTAINERS = {"src", "lib", "app", "packages", "apps", "services", "crates", "modules", "libs",
|
_CONTAINERS = {"src", "lib", "app", "packages", "apps", "services", "crates", "modules", "libs",
|
||||||
"cmd", "internal", "pkg"}
|
"cmd", "internal", "pkg"}
|
||||||
|
|||||||
@@ -18,10 +18,6 @@ def project_label(pid):
|
|||||||
return os.path.basename(str(pid).rstrip("/")) if pid else "(unknown project)"
|
return os.path.basename(str(pid).rstrip("/")) if pid else "(unknown project)"
|
||||||
|
|
||||||
|
|
||||||
def visible_in(rec, cwd):
|
|
||||||
return L.in_scope(rec, cwd)
|
|
||||||
|
|
||||||
|
|
||||||
USAGE = ("usage: sisi learn [--scope user|project] \"<what you want>\"\n"
|
USAGE = ("usage: sisi learn [--scope user|project] \"<what you want>\"\n"
|
||||||
" sisi learn --withdraw ID --reason \"<why it was recorded by mistake>\"")
|
" sisi learn --withdraw ID --reason \"<why it was recorded by mistake>\"")
|
||||||
|
|
||||||
|
|||||||
@@ -24,7 +24,6 @@ Split: sha256(task id) mod 100 < 70 is `dev`, else `holdout`. It depends on the
|
|||||||
"""
|
"""
|
||||||
import hashlib, json, os, time
|
import hashlib, json, os, time
|
||||||
|
|
||||||
from . import harvest, paths
|
|
||||||
|
|
||||||
DEV_PERCENT = 70
|
DEV_PERCENT = 70
|
||||||
MATCH_SLACK_S = 1200
|
MATCH_SLACK_S = 1200
|
||||||
|
|||||||
+1
-4
@@ -1,12 +1,9 @@
|
|||||||
"""Session-start hook. Records the session baseline, checks wiring, prints at most one line. Must be fast."""
|
"""Session-start hook. Records the session baseline, checks wiring, prints at most one line. Must be fast."""
|
||||||
import json, os, sys, time
|
import json, os, sys
|
||||||
|
|
||||||
from . import store
|
from . import store
|
||||||
|
|
||||||
|
|
||||||
MAX_AGE_S = 30 * 86400
|
|
||||||
|
|
||||||
|
|
||||||
def _prune(now=None, sid=None):
|
def _prune(now=None, sid=None):
|
||||||
"""Delete old per-session state files, bounded and on a counter (see store.prune_sessions)."""
|
"""Delete old per-session state files, bounded and on a counter (see store.prune_sessions)."""
|
||||||
return store.prune_sessions(now=now, active_ids=(sid,) if sid else ())
|
return store.prune_sessions(now=now, active_ids=(sid,) if sid else ())
|
||||||
|
|||||||
@@ -124,18 +124,6 @@ def delegations(project, t0, t1):
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
def _row_epoch(r):
|
|
||||||
for k in ("ts", "t", "started", "ended", "time"):
|
|
||||||
v = r.get(k)
|
|
||||||
if isinstance(v, (int, float)) and not isinstance(v, bool):
|
|
||||||
return float(v)
|
|
||||||
if isinstance(v, str):
|
|
||||||
t = harvest.epoch(v)
|
|
||||||
if t is not None:
|
|
||||||
return t
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def policy_version(project, c):
|
def policy_version(project, c):
|
||||||
"""Hash of the policies in force: the effective rulebook, the risk tables,
|
"""Hash of the policies in force: the effective rulebook, the risk tables,
|
||||||
the enforced checks, and the gate/verify config."""
|
the enforced checks, and the gate/verify config."""
|
||||||
|
|||||||
+1
-1
@@ -1,5 +1,5 @@
|
|||||||
"""The verifier library and the recipes for "done": parse, list, show, choose, doctor, lint. No model calls."""
|
"""The verifier library and the recipes for "done": parse, list, show, choose, doctor, lint. No model calls."""
|
||||||
import concurrent.futures as cf, json, os, re, subprocess, sys
|
import concurrent.futures as cf, json, os, re, subprocess
|
||||||
|
|
||||||
from . import contract as C, paths
|
from . import contract as C, paths
|
||||||
|
|
||||||
|
|||||||
+1
-31
@@ -1,7 +1,7 @@
|
|||||||
"""install / uninstall / doctor. Wiring by reference (import line, symlink, hook entry); never copies canon text.
|
"""install / uninstall / doctor. Wiring by reference (import line, symlink, hook entry); never copies canon text.
|
||||||
The tools load the generated rulebook in the personal data folder (base rules with the overlay applied), not the
|
The tools load the generated rulebook in the personal data folder (base rules with the overlay applied), not the
|
||||||
product's canon/core.md. Every modified file is backed up into <personal>/install/ first; uninstall restores it exactly."""
|
product's canon/core.md. Every modified file is backed up into <personal>/install/ first; uninstall restores it exactly."""
|
||||||
import copy, hashlib, json, os, re, shlex, shutil, stat as _stat
|
import copy, hashlib, json, os, re, stat as _stat
|
||||||
|
|
||||||
from . import hookjson, paths, store
|
from . import hookjson, paths, store
|
||||||
|
|
||||||
@@ -321,36 +321,6 @@ def add_hooks(obj):
|
|||||||
return changed
|
return changed
|
||||||
|
|
||||||
|
|
||||||
def remove_hooks(obj):
|
|
||||||
changed = False
|
|
||||||
hooks = obj.get("hooks")
|
|
||||||
if not isinstance(hooks, dict):
|
|
||||||
return False
|
|
||||||
for ev, sub in (("SessionStart", "tick"), ("UserPromptSubmit", "prompt"), ("Stop", "gate"), ("SubagentStop", "gate"),
|
|
||||||
("PreToolUse", "watch"), ("PostToolUse", "watch")):
|
|
||||||
groups = hooks.get(ev)
|
|
||||||
if not isinstance(groups, list):
|
|
||||||
continue
|
|
||||||
keep, ev_changed = [], False
|
|
||||||
for g in groups:
|
|
||||||
hs = g.get("hooks") if isinstance(g, dict) else None
|
|
||||||
if isinstance(hs, list) and any(_is_ours(h, sub) for h in hs):
|
|
||||||
changed = ev_changed = True
|
|
||||||
rest = [h for h in hs if not _is_ours(h, sub)]
|
|
||||||
if rest:
|
|
||||||
g = dict(g, hooks=rest)
|
|
||||||
else:
|
|
||||||
continue
|
|
||||||
keep.append(g)
|
|
||||||
if keep:
|
|
||||||
hooks[ev] = keep
|
|
||||||
elif ev_changed:
|
|
||||||
del hooks[ev]
|
|
||||||
if changed and not hooks:
|
|
||||||
del obj["hooks"]
|
|
||||||
return changed
|
|
||||||
|
|
||||||
|
|
||||||
def _hooks_wired(obj):
|
def _hooks_wired(obj):
|
||||||
hooks = obj.get("hooks") if isinstance(obj, dict) else None
|
hooks = obj.get("hooks") if isinstance(obj, dict) else None
|
||||||
out = {}
|
out = {}
|
||||||
|
|||||||
@@ -470,36 +470,6 @@ def import_ledger(src, now=None):
|
|||||||
return before, before + added, added
|
return before, before + added, added
|
||||||
|
|
||||||
|
|
||||||
def ensure_imported(now=None):
|
|
||||||
"""Import the previously hand-kept ledger once, losslessly. Returns the row count, or None
|
|
||||||
when there was nothing (more) to import. The original file is only read."""
|
|
||||||
now = time.time() if now is None else now
|
|
||||||
marker = _data_file("delegations-import.json")
|
|
||||||
if os.path.exists(marker):
|
|
||||||
return None
|
|
||||||
try:
|
|
||||||
from . import taskset
|
|
||||||
src = taskset.ledger_path()
|
|
||||||
except Exception:
|
|
||||||
src = None
|
|
||||||
if not src or not os.path.isfile(src):
|
|
||||||
return None
|
|
||||||
if os.path.realpath(src) == os.path.realpath(ledger_path()):
|
|
||||||
return None
|
|
||||||
_before, _after, count = import_ledger(src, now=now)
|
|
||||||
# Merge the availability file that sat beside the old ledger, so nothing is forgotten.
|
|
||||||
sibling = os.path.join(os.path.dirname(src), "availability.json")
|
|
||||||
if os.path.isfile(sibling):
|
|
||||||
avail = read_availability()
|
|
||||||
for k, v in read_json(sibling).items():
|
|
||||||
if isinstance(v, dict):
|
|
||||||
avail[str(k).lower()] = v
|
|
||||||
if avail:
|
|
||||||
write_json(availability_path(), avail)
|
|
||||||
write_json(marker, {"source": src, "rows": count, "ts": now})
|
|
||||||
return count
|
|
||||||
|
|
||||||
|
|
||||||
def unjudged_runs(records=None):
|
def unjudged_runs(records=None):
|
||||||
records = read_records() if records is None else records
|
records = read_records() if records is None else records
|
||||||
judged = {r.get("run_id") for r in records if r.get("kind") == "attempt" and r.get("run_id")}
|
judged = {r.get("run_id") for r in records if r.get("kind") == "attempt" and r.get("run_id")}
|
||||||
@@ -1230,7 +1200,6 @@ def cmd_workers(args=()):
|
|||||||
return _cmd_up(args[1:])
|
return _cmd_up(args[1:])
|
||||||
if args[:1] == ["import"]:
|
if args[:1] == ["import"]:
|
||||||
return _cmd_import(args[1:])
|
return _cmd_import(args[1:])
|
||||||
imported = ensure_imported()
|
|
||||||
disc = discover(force="--refresh" in args)
|
disc = discover(force="--refresh" in args)
|
||||||
records = read_records()
|
records = read_records()
|
||||||
avail = read_availability()
|
avail = read_availability()
|
||||||
@@ -1274,9 +1243,6 @@ def cmd_workers(args=()):
|
|||||||
continue
|
continue
|
||||||
print("Unavailable: %s - %s, next try %s%s" % (k, v.get("reason") or "down", _when(v.get("retry_at")),
|
print("Unavailable: %s - %s, next try %s%s" % (k, v.get("reason") or "down", _when(v.get("retry_at")),
|
||||||
(" (%s)" % v["note"]) if v.get("note") else ""))
|
(" (%s)" % v["note"]) if v.get("note") else ""))
|
||||||
if imported is not None:
|
|
||||||
print("Imported the existing delegation ledger: imported %d rows, once, without changing the original."
|
|
||||||
% imported)
|
|
||||||
waiting = unjudged_runs(records)
|
waiting = unjudged_runs(records)
|
||||||
if waiting:
|
if waiting:
|
||||||
print("%d delegation%s waiting for a judgement (%s). Judge with `sisi delegate judge ID "
|
print("%d delegation%s waiting for a judgement (%s). Judge with `sisi delegate judge ID "
|
||||||
@@ -1296,7 +1262,6 @@ def cmd_workers(args=()):
|
|||||||
|
|
||||||
|
|
||||||
def _route_setup(args):
|
def _route_setup(args):
|
||||||
ensure_imported()
|
|
||||||
kind = _opt(args, "--kind")
|
kind = _opt(args, "--kind")
|
||||||
difficulty = _opt(args, "--difficulty")
|
difficulty = _opt(args, "--difficulty")
|
||||||
if not kind or difficulty is None:
|
if not kind or difficulty is None:
|
||||||
|
|||||||
@@ -983,7 +983,7 @@ class Store(Base):
|
|||||||
root = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
|
root = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
|
||||||
bad = []
|
bad = []
|
||||||
for n in sorted(os.listdir(os.path.join(root, "sisi"))):
|
for n in sorted(os.listdir(os.path.join(root, "sisi"))):
|
||||||
if not n.endswith(".py") or n == "gate.py": # gate.py's retro.lessons_block is the live gate seam
|
if not n.endswith(".py"):
|
||||||
continue
|
continue
|
||||||
with open(os.path.join(root, "sisi", n)) as f:
|
with open(os.path.join(root, "sisi", n)) as f:
|
||||||
for i, line in enumerate(f, 1):
|
for i, line in enumerate(f, 1):
|
||||||
@@ -992,6 +992,23 @@ class Store(Base):
|
|||||||
bad.append("%s:%d" % (n, i))
|
bad.append("%s:%d" % (n, i))
|
||||||
self.assertEqual(bad, [])
|
self.assertEqual(bad, [])
|
||||||
|
|
||||||
|
def test_no_guarded_seams_between_modules_that_always_exist(self):
|
||||||
|
"""Item 4: no `except ImportError` or `hasattr(module, ...)` probe stands in for a module of this
|
||||||
|
package, and nothing names a removed seam. The one platform probe (fcntl, absent on Windows, in pdata) stays."""
|
||||||
|
import re
|
||||||
|
root = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
|
||||||
|
bad = []
|
||||||
|
for n in sorted(os.listdir(os.path.join(root, "sisi"))):
|
||||||
|
if not n.endswith(".py"):
|
||||||
|
continue
|
||||||
|
with open(os.path.join(root, "sisi", n)) as f:
|
||||||
|
for i, line in enumerate(f, 1):
|
||||||
|
if n != "pdata.py" and re.search(r"except \(?ImportError|hasattr\((delivery|unit|gate|retro|learning|cycle)\b", line):
|
||||||
|
bad.append("%s:%d" % (n, i))
|
||||||
|
if re.search(r"retro\.(TEMPLATE|satisfied|lessons_block)|ensure_imported", line):
|
||||||
|
bad.append("%s:%d" % (n, i))
|
||||||
|
self.assertEqual(bad, [])
|
||||||
|
|
||||||
def test_no_resource_warnings_from_the_learning_commands(self):
|
def test_no_resource_warnings_from_the_learning_commands(self):
|
||||||
"""Item 13: file handles are closed; every learning command runs clean under -W always."""
|
"""Item 13: file handles are closed; every learning command runs clean under -W always."""
|
||||||
_contract(self)
|
_contract(self)
|
||||||
|
|||||||
+32
-1
@@ -19,6 +19,37 @@ def snapshot(root):
|
|||||||
return snap
|
return snap
|
||||||
|
|
||||||
|
|
||||||
|
def remove_hooks(obj):
|
||||||
|
"""Test oracle: strip our hook groups from a settings object (the product removes them structurally)."""
|
||||||
|
changed = False
|
||||||
|
hooks = obj.get("hooks")
|
||||||
|
if not isinstance(hooks, dict):
|
||||||
|
return False
|
||||||
|
for ev, sub in (("SessionStart", "tick"), ("UserPromptSubmit", "prompt"), ("Stop", "gate"), ("SubagentStop", "gate"),
|
||||||
|
("PreToolUse", "watch"), ("PostToolUse", "watch")):
|
||||||
|
groups = hooks.get(ev)
|
||||||
|
if not isinstance(groups, list):
|
||||||
|
continue
|
||||||
|
keep, ev_changed = [], False
|
||||||
|
for g in groups:
|
||||||
|
hs = g.get("hooks") if isinstance(g, dict) else None
|
||||||
|
if isinstance(hs, list) and any(wiring._is_ours(h, sub) for h in hs):
|
||||||
|
changed = ev_changed = True
|
||||||
|
rest = [h for h in hs if not wiring._is_ours(h, sub)]
|
||||||
|
if rest:
|
||||||
|
g = dict(g, hooks=rest)
|
||||||
|
else:
|
||||||
|
continue
|
||||||
|
keep.append(g)
|
||||||
|
if keep:
|
||||||
|
hooks[ev] = keep
|
||||||
|
elif ev_changed:
|
||||||
|
del hooks[ev]
|
||||||
|
if changed and not hooks:
|
||||||
|
del obj["hooks"]
|
||||||
|
return changed
|
||||||
|
|
||||||
|
|
||||||
class WiringBase(SisiCase):
|
class WiringBase(SisiCase):
|
||||||
def setUp(self):
|
def setUp(self):
|
||||||
super().setUp()
|
super().setUp()
|
||||||
@@ -127,7 +158,7 @@ class WiringPropertyTests(WiringBase):
|
|||||||
if st is not None and st.strip():
|
if st is not None and st.strip():
|
||||||
orig = json.loads(st)
|
orig = json.loads(st)
|
||||||
now = json.loads(self.path(".claude/settings.json") and open(self.path(".claude/settings.json"), "rb").read())
|
now = json.loads(self.path(".claude/settings.json") and open(self.path(".claude/settings.json"), "rb").read())
|
||||||
wiring.remove_hooks(now)
|
remove_hooks(now)
|
||||||
|
|
||||||
def norm(d): # empty hook lists/objects may legitimately disappear in the structural path
|
def norm(d): # empty hook lists/objects may legitimately disappear in the structural path
|
||||||
h = d.get("hooks")
|
h = d.get("hooks")
|
||||||
|
|||||||
@@ -88,37 +88,6 @@ class DiscoveryTests(WorkerCase):
|
|||||||
self.assertFalse(tools["cursor-agent"]["usable"])
|
self.assertFalse(tools["cursor-agent"]["usable"])
|
||||||
|
|
||||||
|
|
||||||
class LedgerImportTests(WorkerCase):
|
|
||||||
def test_existing_ledger_imported_once_losslessly(self):
|
|
||||||
src = os.path.join(self.tmp, "orch-log.jsonl")
|
|
||||||
rows = [
|
|
||||||
{"kind": "attempt", "id": "abc123", "ts": 1700000000, "project": "p", "type": "impl",
|
|
||||||
"difficulty": 2, "worker": "beta-1", "outcome": "accepted", "check": "tests",
|
|
||||||
"minutes": 3, "tokens": None, "retry_of": None, "note": "keep me", "extra": [1, 2]},
|
|
||||||
{"kind": "attempt", "id": "def456", "ts": 1700000100, "project": "p", "type": "impl",
|
|
||||||
"difficulty": 2, "worker": "beta-1", "outcome": "rejected", "check": "read",
|
|
||||||
"minutes": 4, "tokens": 9, "retry_of": "abc123", "note": None},
|
|
||||||
{"kind": "amend", "id": "abc123", "ts": 1700000200, "note": "later wrong"},
|
|
||||||
]
|
|
||||||
with open(src, "w") as f:
|
|
||||||
for row in rows:
|
|
||||||
f.write(json.dumps(row) + "\n")
|
|
||||||
before = open(src).read()
|
|
||||||
r = self.sisi("workers", env=self.env(SISI_LEDGER=src))
|
|
||||||
self.assertEqual(r.returncode, 0, r.stderr)
|
|
||||||
self.assertIn("imported 3 rows", r.stdout)
|
|
||||||
self.assertEqual(open(src).read(), before, "the original ledger must not be modified")
|
|
||||||
got = [json.loads(l) for l in open(os.path.join(self.data, "delegations.jsonl"))]
|
|
||||||
self.assertEqual(len(got), 3)
|
|
||||||
for want, have in zip(rows, got):
|
|
||||||
for k, v in want.items():
|
|
||||||
self.assertEqual(have.get(k), v, k)
|
|
||||||
# a second run imports nothing more
|
|
||||||
self.sisi("workers", env=self.env(SISI_LEDGER=src))
|
|
||||||
got2 = [json.loads(l) for l in open(os.path.join(self.data, "delegations.jsonl"))]
|
|
||||||
self.assertEqual(len(got2), 3)
|
|
||||||
|
|
||||||
|
|
||||||
class RouteTests(WorkerCase):
|
class RouteTests(WorkerCase):
|
||||||
def test_route_explains_and_skips_contributor_and_logged_out(self):
|
def test_route_explains_and_skips_contributor_and_logged_out(self):
|
||||||
r = self.sisi("route", "--kind", "impl", "--difficulty", "2", "--explain", env=self.env())
|
r = self.sisi("route", "--kind", "impl", "--difficulty", "2", "--explain", env=self.env())
|
||||||
|
|||||||
Reference in new issue
Block a user