ghostkeep 0.7.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- ghostkeep/__init__.py +2 -0
- ghostkeep/__main__.py +3 -0
- ghostkeep/check.py +207 -0
- ghostkeep/cli.py +345 -0
- ghostkeep/decisions.py +49 -0
- ghostkeep/gitio.py +129 -0
- ghostkeep/handoff.py +173 -0
- ghostkeep/health.py +170 -0
- ghostkeep/ledger.py +196 -0
- ghostkeep/setup.py +253 -0
- ghostkeep/sources.py +543 -0
- ghostkeep/state.py +287 -0
- ghostkeep/sync.py +69 -0
- ghostkeep/verify.py +146 -0
- ghostkeep-0.7.0.dist-info/METADATA +222 -0
- ghostkeep-0.7.0.dist-info/RECORD +19 -0
- ghostkeep-0.7.0.dist-info/WHEEL +4 -0
- ghostkeep-0.7.0.dist-info/entry_points.txt +2 -0
- ghostkeep-0.7.0.dist-info/licenses/LICENSE +21 -0
ghostkeep/__init__.py
ADDED
ghostkeep/__main__.py
ADDED
ghostkeep/check.py
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
"""Deterministic checker: compares what agents claimed with what git shows. No LLM."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from dataclasses import dataclass, field
|
|
5
|
+
from datetime import datetime
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from . import gitio, ledger, sources
|
|
9
|
+
from .ledger import LEDGER_DIR, Claim, new_id, now
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclass
|
|
13
|
+
class Finding:
|
|
14
|
+
path: str
|
|
15
|
+
code: str
|
|
16
|
+
expected: str | None = None
|
|
17
|
+
actual: str | None = None
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass
|
|
21
|
+
class Result:
|
|
22
|
+
entry: str | None
|
|
23
|
+
status: str
|
|
24
|
+
findings: list[Finding] = field(default_factory=list)
|
|
25
|
+
claim: Claim | None = None
|
|
26
|
+
|
|
27
|
+
def record(self, head: str | None) -> dict:
|
|
28
|
+
return {
|
|
29
|
+
"v": ledger.SCHEMA_VERSION, "kind": "check", "id": new_id("c"), "ts": now(),
|
|
30
|
+
"head": head, "entry": self.entry, "status": self.status,
|
|
31
|
+
"findings": [f.__dict__ for f in self.findings],
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _fmt(added: int | None, removed: int | None) -> str:
|
|
36
|
+
if added is None and removed is None:
|
|
37
|
+
return "binary"
|
|
38
|
+
return f"+{added} -{removed}"
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _content_delta(root: Path, base: str | None, path: str) -> tuple[int, int] | None:
|
|
42
|
+
"""Line counts measured the way claims are measured (splitlines), so a missing newline at the end
|
|
43
|
+
of a file or CRLF vs LF doesn't read as an extra changed line."""
|
|
44
|
+
old = gitio.show(root, base, path) or ""
|
|
45
|
+
try:
|
|
46
|
+
new = (root / path).read_text(encoding="utf-8", errors="replace")
|
|
47
|
+
except OSError:
|
|
48
|
+
new = ""
|
|
49
|
+
if old == new:
|
|
50
|
+
return None
|
|
51
|
+
return sources.line_delta(old, new)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _recreated_after(root: Path, claim: Claim, path: str) -> bool:
|
|
55
|
+
"""A deleted file that is back: committed after the session's base, or written after the session ended."""
|
|
56
|
+
last = gitio.last_commit_touching(root, path)
|
|
57
|
+
if last and claim.base and not gitio.is_ancestor(root, last, claim.base):
|
|
58
|
+
return True
|
|
59
|
+
try:
|
|
60
|
+
ended = datetime.fromisoformat(claim.ts.replace("Z", "+00:00")).timestamp()
|
|
61
|
+
return (root / path).stat().st_mtime > ended + 60
|
|
62
|
+
except (ValueError, OSError, AttributeError):
|
|
63
|
+
return False
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _matches(actual: tuple, options: list[tuple]) -> bool:
|
|
67
|
+
a, r = actual
|
|
68
|
+
return any((ea is None or ea == a) and (er is None or er == r) for ea, er in options)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def check_claim(root: Path, claim: Claim, newest_for: dict[str, str], dirty: dict[str, str],
|
|
72
|
+
chain: dict[str, tuple[int, int]] | None = None) -> Result:
|
|
73
|
+
findings: list[Finding] = []
|
|
74
|
+
any_uncommitted = False
|
|
75
|
+
strict_files = [f for f in claim.files if newest_for.get(f.path) == claim.id]
|
|
76
|
+
if not claim.files:
|
|
77
|
+
return Result(claim.id, "no_files", claim=claim) # interrupted before changing anything
|
|
78
|
+
if not strict_files:
|
|
79
|
+
return Result(claim.id, "superseded", claim=claim)
|
|
80
|
+
|
|
81
|
+
for f in strict_files:
|
|
82
|
+
if gitio.outside_git(root, f.path):
|
|
83
|
+
# git can't see this file (.git/hooks, ignored files), so "no change in git" proves nothing.
|
|
84
|
+
# Only say what the disk shows; never call it missing when it's there.
|
|
85
|
+
if (root / f.path).exists():
|
|
86
|
+
findings.append(Finding(f.path, "outside_git", f.expected(), "on disk, git doesn't track it"))
|
|
87
|
+
else:
|
|
88
|
+
findings.append(Finding(f.path, "claimed_not_found", f.expected(), "not on disk"))
|
|
89
|
+
continue
|
|
90
|
+
if f.added == 0 and f.removed is None: # the session deleted this file
|
|
91
|
+
if (root / f.path).exists():
|
|
92
|
+
if _recreated_after(root, claim, f.path):
|
|
93
|
+
findings.append(Finding(f.path, "changed_later", "deleted", "re-created after this session"))
|
|
94
|
+
else:
|
|
95
|
+
findings.append(Finding(f.path, "claimed_not_found", "deleted", "still on disk"))
|
|
96
|
+
elif f.path in dirty:
|
|
97
|
+
any_uncommitted = True
|
|
98
|
+
findings.append(Finding(f.path, "not_committed", "deleted", "deleted"))
|
|
99
|
+
continue
|
|
100
|
+
actual = gitio.numstat(root, claim.base, f.path)
|
|
101
|
+
if actual is None:
|
|
102
|
+
findings.append(Finding(f.path, "claimed_not_found", f.expected(), "no change"))
|
|
103
|
+
continue
|
|
104
|
+
a, r = actual
|
|
105
|
+
# What the file should show: this session's own counts, or, when earlier sessions edited the
|
|
106
|
+
# same uncommitted file from the same commit, the sum of every session's counts.
|
|
107
|
+
options = [(f.added, f.removed)]
|
|
108
|
+
if chain and f.path in chain:
|
|
109
|
+
options.append(chain[f.path])
|
|
110
|
+
if a is not None and not _matches(actual, options):
|
|
111
|
+
alt = _content_delta(root, claim.base, f.path)
|
|
112
|
+
if alt is not None and _matches(alt, options):
|
|
113
|
+
actual, (a, r) = alt, alt
|
|
114
|
+
else:
|
|
115
|
+
findings.append(Finding(f.path, "count_mismatch", f.expected(), _fmt(a, r)))
|
|
116
|
+
continue
|
|
117
|
+
if f.path in dirty:
|
|
118
|
+
any_uncommitted = True
|
|
119
|
+
code = "untracked" if dirty[f.path] == "??" else "not_committed"
|
|
120
|
+
findings.append(Finding(f.path, code, f.expected(), _fmt(a, r)))
|
|
121
|
+
|
|
122
|
+
if any(fd.code in ("claimed_not_found", "count_mismatch") for fd in findings):
|
|
123
|
+
status = "mismatch"
|
|
124
|
+
elif any_uncommitted:
|
|
125
|
+
status = "uncommitted"
|
|
126
|
+
else:
|
|
127
|
+
status = "verified"
|
|
128
|
+
return Result(claim.id, status, findings, claim)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _chains(all_claims: list[Claim], newest_for: dict[str, str]) -> dict[str, dict[str, tuple[int, int]]]:
|
|
132
|
+
"""For the newest claim on each file: the summed counts of every claim on that file made from the
|
|
133
|
+
same base commit, when there is more than one and all of them reported counts."""
|
|
134
|
+
by_id = {c.id: c for c in all_claims}
|
|
135
|
+
out: dict[str, dict[str, tuple[int, int]]] = {}
|
|
136
|
+
for path, newest_id in newest_for.items():
|
|
137
|
+
newest = by_id[newest_id]
|
|
138
|
+
same = [fc for c in all_claims if c.base == newest.base for fc in c.files if fc.path == path]
|
|
139
|
+
if len(same) > 1 and all(fc.added is not None and fc.removed is not None for fc in same):
|
|
140
|
+
out.setdefault(newest_id, {})[path] = (sum(fc.added for fc in same), sum(fc.removed for fc in same))
|
|
141
|
+
return out
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def covering_claims(root: Path, claims: list[Claim], results: list[Result],
|
|
145
|
+
paths) -> dict[str, list[Claim]]:
|
|
146
|
+
"""Which claims account for each changed file, newest first.
|
|
147
|
+
|
|
148
|
+
A claim accounts for a change when it names the file, its edit is actually on disk, and nobody has
|
|
149
|
+
committed that file since the claim's base commit (so the change on disk is still the one it made).
|
|
150
|
+
"""
|
|
151
|
+
gone = {(r.entry, f.path) for r in results for f in r.findings if f.code == "claimed_not_found"}
|
|
152
|
+
out: dict[str, list[Claim]] = {}
|
|
153
|
+
for path in paths:
|
|
154
|
+
last = gitio.last_commit_touching(root, path)
|
|
155
|
+
for c in claims:
|
|
156
|
+
if path not in {f.path for f in c.files} or (c.id, path) in gone:
|
|
157
|
+
continue
|
|
158
|
+
if last is None or c.base is None or gitio.is_ancestor(root, last, c.base):
|
|
159
|
+
out.setdefault(path, []).append(c)
|
|
160
|
+
if path in out:
|
|
161
|
+
out[path].reverse()
|
|
162
|
+
return out
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def run(root: Path, write: bool = True) -> list[Result]:
|
|
166
|
+
records = ledger.read(root)
|
|
167
|
+
all_claims = ledger.claims(records)
|
|
168
|
+
head = gitio.head(root)
|
|
169
|
+
dirty = {p: c for p, c in gitio.changed_paths(root).items()
|
|
170
|
+
if not p.startswith(LEDGER_DIR + "/")}
|
|
171
|
+
|
|
172
|
+
# Newest claim per file is the one checked strictly.
|
|
173
|
+
newest_for: dict[str, str] = {}
|
|
174
|
+
for c in all_claims:
|
|
175
|
+
for f in c.files:
|
|
176
|
+
newest_for[f.path] = c.id
|
|
177
|
+
chains = _chains(all_claims, newest_for)
|
|
178
|
+
|
|
179
|
+
results = [check_claim(root, c, newest_for, dirty, chains.get(c.id)) for c in all_claims]
|
|
180
|
+
|
|
181
|
+
# Orphans: changed files that no claim accounts for.
|
|
182
|
+
covered = covering_claims(root, all_claims, results, dirty)
|
|
183
|
+
orphans = sorted(p for p in dirty if p not in covered)
|
|
184
|
+
if orphans:
|
|
185
|
+
results.append(Result(None, "orphan", [
|
|
186
|
+
Finding(p, "no_claim", None, "untracked" if dirty[p] == "??" else "modified")
|
|
187
|
+
for p in orphans
|
|
188
|
+
]))
|
|
189
|
+
|
|
190
|
+
corrupt = [r for r in records if r.get("kind") == "corrupt"]
|
|
191
|
+
for r in corrupt:
|
|
192
|
+
results.append(Result(None, "corrupt", [Finding(f"ledger line {r['line']}", "bad_json", None, r["error"])]))
|
|
193
|
+
|
|
194
|
+
if write:
|
|
195
|
+
# Append-only, but don't repeat a check whose outcome hasn't changed.
|
|
196
|
+
last = ledger.latest_status(records)
|
|
197
|
+
last_orphan = next((r for r in reversed(records)
|
|
198
|
+
if r.get("kind") == "check" and r.get("status") == "orphan"), None)
|
|
199
|
+
for res in results:
|
|
200
|
+
if res.status == "corrupt":
|
|
201
|
+
continue
|
|
202
|
+
prev = last.get(res.entry) if res.entry else last_orphan
|
|
203
|
+
same = prev is not None and prev.get("status") == res.status and \
|
|
204
|
+
prev.get("findings") == [f.__dict__ for f in res.findings] and prev.get("head") == head
|
|
205
|
+
if not same:
|
|
206
|
+
ledger.append(root, res.record(head))
|
|
207
|
+
return results
|
ghostkeep/cli.py
ADDED
|
@@ -0,0 +1,345 @@
|
|
|
1
|
+
"""ghostkeep: verified handoffs between free AI tools."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import json
|
|
6
|
+
import sys
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from . import __version__, check, gitio, handoff, ledger, sync, state, health, setup, verify
|
|
10
|
+
|
|
11
|
+
PROBLEM = {"mismatch", "orphan", "corrupt"}
|
|
12
|
+
MARK = {"verified": "OK ", "uncommitted": "UNC", "mismatch": "BAD", "superseded": "OLD",
|
|
13
|
+
"orphan": "???", "unverified": "...", "corrupt": "ERR"}
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _root() -> Path:
|
|
17
|
+
try:
|
|
18
|
+
return gitio.repo_root(Path.cwd())
|
|
19
|
+
except gitio.GitError:
|
|
20
|
+
sys.exit("ghostkeep: not inside a git repository")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def cmd_init(_: argparse.Namespace) -> int:
|
|
24
|
+
root = _root()
|
|
25
|
+
p = ledger.init(root)
|
|
26
|
+
print(f"Ledger ready: {p.relative_to(root)}")
|
|
27
|
+
print("Tip: commit it to share the history, or add .ghostkeep/ to .gitignore to keep it private.")
|
|
28
|
+
return 0
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def cmd_log(a: argparse.Namespace) -> int:
|
|
32
|
+
root = _root()
|
|
33
|
+
if a.tool not in ledger.TOOLS:
|
|
34
|
+
print(f"ghostkeep: unknown tool '{a.tool}'. Use one of: {', '.join(sorted(ledger.TOOLS))}",
|
|
35
|
+
file=sys.stderr)
|
|
36
|
+
return 2
|
|
37
|
+
claim = ledger.Claim(
|
|
38
|
+
tool=a.tool, asked=a.asked, claimed=a.claimed,
|
|
39
|
+
files=[ledger.FileClaim.parse(s) for s in a.file], open=a.open or [],
|
|
40
|
+
model=a.model, session=a.session, source=a.source, base=gitio.head(root),
|
|
41
|
+
)
|
|
42
|
+
ledger.append(root, claim.to_json())
|
|
43
|
+
print(f"Logged {claim.id} ({claim.tool}, {len(claim.files)} file(s)). Status: unverified")
|
|
44
|
+
return 0
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def cmd_check(a: argparse.Namespace) -> int:
|
|
48
|
+
root = _root()
|
|
49
|
+
results = check.run(root, write=not a.dry_run)
|
|
50
|
+
if a.json:
|
|
51
|
+
print(json.dumps([{
|
|
52
|
+
"entry": r.entry, "status": r.status,
|
|
53
|
+
"tool": r.claim.tool if r.claim else None,
|
|
54
|
+
"findings": [f.__dict__ for f in r.findings],
|
|
55
|
+
} for r in results], indent=2, ensure_ascii=False))
|
|
56
|
+
else:
|
|
57
|
+
if not results:
|
|
58
|
+
print("Nothing to check: no claims and no uncommitted changes.")
|
|
59
|
+
for r in results:
|
|
60
|
+
who = f"{r.entry} {r.claim.tool}" if r.claim else "no claim"
|
|
61
|
+
print(f"[{MARK.get(r.status, r.status)}] {r.status:<11} {who}")
|
|
62
|
+
if r.claim:
|
|
63
|
+
print(f" asked: {r.claim.asked[:100]}")
|
|
64
|
+
for f in r.findings:
|
|
65
|
+
detail = f"expected {f.expected}, actual {f.actual}" if f.expected else f.actual
|
|
66
|
+
print(f" {f.code:<17} {f.path} ({detail})")
|
|
67
|
+
return 1 if any(r.status in PROBLEM for r in results) else 0
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def cmd_sync(a: argparse.Namespace) -> int:
|
|
71
|
+
root = _root()
|
|
72
|
+
if not ledger.ledger_path(root).exists():
|
|
73
|
+
ledger.init(root)
|
|
74
|
+
rep, new = sync.run(root, days=a.days, write=not a.dry_run)
|
|
75
|
+
print(f"Sessions touching this repo (last {a.days:g} days): {rep.sessions_seen}")
|
|
76
|
+
print(f" new claims: {rep.claims_added} decisions/preferences: {rep.decisions_added} "
|
|
77
|
+
f"unchanged: {rep.skipped_unchanged} no file edits: {rep.skipped_no_edits}")
|
|
78
|
+
for r in new:
|
|
79
|
+
if r["kind"] == "claim":
|
|
80
|
+
files = ", ".join(f["path"] for f in r["files"])[:90]
|
|
81
|
+
flag = " [interrupted]" if r.get("interrupted") else ""
|
|
82
|
+
print(f" + {r['tool']:<16} {r['ts'][:16]} {files}{flag}")
|
|
83
|
+
return 0
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _handoff(root: Path, a: argparse.Namespace) -> str:
|
|
87
|
+
if not ledger.ledger_path(root).exists():
|
|
88
|
+
ledger.init(root)
|
|
89
|
+
if not a.no_sync:
|
|
90
|
+
sync.run(root, days=a.days)
|
|
91
|
+
results = check.run(root)
|
|
92
|
+
if not a.hook: # the session-start hook must stay quick: it shows the last test result instead
|
|
93
|
+
verify.run(root)
|
|
94
|
+
text = handoff.build(root, results, days=a.days)
|
|
95
|
+
handoff.write(root, text)
|
|
96
|
+
state.write(root, state.build(ledger.read(root), {r.entry: r.status for r in results if r.entry}))
|
|
97
|
+
return text
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def cmd_handoff(a: argparse.Namespace) -> int:
|
|
101
|
+
if a.hook:
|
|
102
|
+
return _hook(a)
|
|
103
|
+
root = _root()
|
|
104
|
+
text = _handoff(root, a)
|
|
105
|
+
print(text)
|
|
106
|
+
print(f"(written to {ledger.LEDGER_DIR}/HANDOFF.md)", file=sys.stderr)
|
|
107
|
+
return 0
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _stdin_json() -> dict:
|
|
111
|
+
"""The JSON a tool passes its hook on stdin (ignored when run by hand)."""
|
|
112
|
+
if sys.stdin is None or sys.stdin.isatty():
|
|
113
|
+
return {}
|
|
114
|
+
try:
|
|
115
|
+
data = json.loads(sys.stdin.read(1_000_000) or "{}")
|
|
116
|
+
except (ValueError, OSError):
|
|
117
|
+
return {}
|
|
118
|
+
return data if isinstance(data, dict) else {}
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _hook(a: argparse.Namespace) -> int:
|
|
122
|
+
"""Run by a tool's session-start hook. Never breaks the session: always exits 0, prints only what that
|
|
123
|
+
tool expects on stdout, and records how it went in .ghostkeep/hook.json so `doctor` can prove it ran."""
|
|
124
|
+
tool = a.format or "claude-code"
|
|
125
|
+
rec = {"last_run": ledger.now(), "ok": True, "error": None}
|
|
126
|
+
root = None
|
|
127
|
+
out = setup.empty_output(tool)
|
|
128
|
+
try:
|
|
129
|
+
where = setup.root_from_stdin(_stdin_json())
|
|
130
|
+
root = gitio.repo_root(Path(where) if where else Path.cwd())
|
|
131
|
+
out = setup.render_hook(tool, _handoff(root, a))
|
|
132
|
+
except Exception as exc: # noqa: BLE001 - the session must start whatever happens here
|
|
133
|
+
rec.update(ok=False, error=f"{type(exc).__name__}: {exc}"[:300])
|
|
134
|
+
print(out)
|
|
135
|
+
if root is not None:
|
|
136
|
+
try:
|
|
137
|
+
setup.record_run(root, tool, rec)
|
|
138
|
+
except OSError:
|
|
139
|
+
pass
|
|
140
|
+
return 0
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def cmd_setup(a: argparse.Namespace) -> int:
|
|
144
|
+
root = _root()
|
|
145
|
+
if a.remove:
|
|
146
|
+
lines = setup.remove(root)
|
|
147
|
+
else:
|
|
148
|
+
ledger.init(root)
|
|
149
|
+
tools = None if a.tools is None else [t.strip() for t in a.tools.split(",") if t.strip()]
|
|
150
|
+
bad = [t for t in tools or [] if t not in setup.TOOLS]
|
|
151
|
+
if bad:
|
|
152
|
+
print(f"unknown tool(s): {', '.join(bad)}. Choose from {', '.join(setup.TOOLS)}", file=sys.stderr)
|
|
153
|
+
return 2
|
|
154
|
+
lines = setup.install(root, tools=tools, agents_md=not a.no_agents_md)
|
|
155
|
+
for ln in lines:
|
|
156
|
+
print(f"- {ln}")
|
|
157
|
+
if not a.remove:
|
|
158
|
+
print("Check it any time with `ghostkeep doctor`.")
|
|
159
|
+
return 0
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def cmd_stats(a: argparse.Namespace) -> int:
|
|
163
|
+
root = _root()
|
|
164
|
+
n = state.stats(ledger.read(root))
|
|
165
|
+
if a.json:
|
|
166
|
+
print(json.dumps(n, indent=2))
|
|
167
|
+
else:
|
|
168
|
+
print(f"ghostkeep stats ({root})")
|
|
169
|
+
print("\n".join(state.render_stats(n)))
|
|
170
|
+
return 0
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def cmd_pin_test(a: argparse.Namespace) -> int:
|
|
174
|
+
root = _root()
|
|
175
|
+
ledger.init(root)
|
|
176
|
+
if a.clear:
|
|
177
|
+
verify.pin(root, None)
|
|
178
|
+
print("unpinned: 'tests pass' claims will show as not checked")
|
|
179
|
+
return 0
|
|
180
|
+
if not a.command:
|
|
181
|
+
cmd = verify.load_config(root).get("test_command")
|
|
182
|
+
print(f"pinned: {cmd}" if cmd else "nothing pinned. Example: ghostkeep pin-test \"python -m pytest -q\"")
|
|
183
|
+
return 0
|
|
184
|
+
verify.pin(root, a.command, a.timeout)
|
|
185
|
+
print(f"pinned: {a.command} (timeout {a.timeout}s)")
|
|
186
|
+
print("It runs only from `ghostkeep handoff`, only when an agent says tests pass, and only this command.")
|
|
187
|
+
return 0
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def cmd_ack_ledger(a: argparse.Namespace) -> int:
|
|
191
|
+
root = _root()
|
|
192
|
+
breaks = ledger.chain_breaks(root)
|
|
193
|
+
if not breaks:
|
|
194
|
+
print("the ledger's hash chain is intact: nothing to acknowledge")
|
|
195
|
+
return 0
|
|
196
|
+
ledger.append(root, {"v": ledger.SCHEMA_VERSION, "kind": "ack", "id": ledger.new_id("a"), "ts": ledger.now(),
|
|
197
|
+
"lines": breaks, "reason": a.reason})
|
|
198
|
+
print(f"acknowledged break(s) at line(s) {', '.join(map(str, breaks))}: {a.reason}")
|
|
199
|
+
return 0
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def cmd_doctor(a: argparse.Namespace) -> int:
|
|
203
|
+
root = _root()
|
|
204
|
+
lines = health.check(root, days=a.days)
|
|
205
|
+
print(health.render(root, lines))
|
|
206
|
+
return 1 if any(ln.level == health.WARN for ln in lines) else 0
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def _state(root: Path) -> state.State:
|
|
210
|
+
results = check.run(root, write=False)
|
|
211
|
+
return state.build(ledger.read(root), {r.entry: r.status for r in results if r.entry})
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def cmd_state(_: argparse.Namespace) -> int:
|
|
215
|
+
root = _root()
|
|
216
|
+
st = _state(root)
|
|
217
|
+
p = state.write(root, st)
|
|
218
|
+
print(state.render(st))
|
|
219
|
+
print(f"(written to {p.relative_to(root)})", file=sys.stderr)
|
|
220
|
+
return 0
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def cmd_change(a: argparse.Namespace) -> int:
|
|
224
|
+
"""retire / supersede / done / reopen: the user's own corrections, appended to the ledger."""
|
|
225
|
+
root = _root()
|
|
226
|
+
st = _state(root)
|
|
227
|
+
it = st.find(a.id)
|
|
228
|
+
if it is None:
|
|
229
|
+
print(f"no decision or thread with id {a.id!r}. See `ghostkeep state`.", file=sys.stderr)
|
|
230
|
+
return 2
|
|
231
|
+
by = None
|
|
232
|
+
if a.op == "supersede":
|
|
233
|
+
new = st.find(a.new)
|
|
234
|
+
if new is None or new.kind == "thread":
|
|
235
|
+
print(f"no decision with id {a.new!r}", file=sys.stderr)
|
|
236
|
+
return 2
|
|
237
|
+
by = new.id
|
|
238
|
+
if a.op in ("retire", "supersede", "confirm") and it.kind == "thread" or a.op == "done" and it.kind != "thread":
|
|
239
|
+
print(f"`{a.op}` doesn't apply to a {it.kind}", file=sys.stderr)
|
|
240
|
+
return 2
|
|
241
|
+
state.record(root, a.op, it.id, by=by, note=a.note)
|
|
242
|
+
state.write(root, _state(root))
|
|
243
|
+
print(f"{a.op}: {it.id} {it.text[:80]!r}")
|
|
244
|
+
return 0
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def cmd_show(a: argparse.Namespace) -> int:
|
|
248
|
+
root = _root()
|
|
249
|
+
records = ledger.read(root)
|
|
250
|
+
status = ledger.latest_status(records)
|
|
251
|
+
for c in ledger.claims(records)[-a.n:]:
|
|
252
|
+
s = status.get(c.id, {}).get("status", "unverified")
|
|
253
|
+
print(f"[{MARK.get(s, s)}] {c.ts} {c.tool:<16} {s}")
|
|
254
|
+
print(f" asked: {c.asked[:100]}")
|
|
255
|
+
print(f" claimed: {c.claimed[:100]}")
|
|
256
|
+
for f in c.files:
|
|
257
|
+
print(f" file: {f.path} {f.expected()}")
|
|
258
|
+
for o in c.open:
|
|
259
|
+
print(f" open: {o}")
|
|
260
|
+
return 0
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def main(argv: list[str] | None = None) -> int:
|
|
264
|
+
p = argparse.ArgumentParser(prog="ghostkeep", description=__doc__)
|
|
265
|
+
p.add_argument("--version", action="version", version=f"ghostkeep {__version__}")
|
|
266
|
+
sub = p.add_subparsers(dest="cmd", required=True)
|
|
267
|
+
|
|
268
|
+
sub.add_parser("init", help="create .ghostkeep/ledger.jsonl").set_defaults(fn=cmd_init)
|
|
269
|
+
|
|
270
|
+
lg = sub.add_parser("log", help="record what an agent claims it did")
|
|
271
|
+
lg.add_argument("--tool", required=True)
|
|
272
|
+
lg.add_argument("--asked", required=True, help="the user's request, verbatim")
|
|
273
|
+
lg.add_argument("--claimed", required=True, help="what the agent says it did")
|
|
274
|
+
lg.add_argument("--file", action="append", default=[],
|
|
275
|
+
help="claimed file, optionally with counts: path:+3-1 (repeatable)")
|
|
276
|
+
lg.add_argument("--open", action="append", help="something still left to do (repeatable)")
|
|
277
|
+
lg.add_argument("--model")
|
|
278
|
+
lg.add_argument("--session")
|
|
279
|
+
lg.add_argument("--source")
|
|
280
|
+
lg.set_defaults(fn=cmd_log)
|
|
281
|
+
|
|
282
|
+
ck = sub.add_parser("check", help="verify claims against git (no LLM)")
|
|
283
|
+
ck.add_argument("--json", action="store_true")
|
|
284
|
+
ck.add_argument("--dry-run", action="store_true", help="don't write check records")
|
|
285
|
+
ck.set_defaults(fn=cmd_check)
|
|
286
|
+
|
|
287
|
+
sy = sub.add_parser("sync", help="read Claude Code / Antigravity session logs into the ledger")
|
|
288
|
+
sy.add_argument("--days", type=float, default=14)
|
|
289
|
+
sy.add_argument("--dry-run", action="store_true")
|
|
290
|
+
sy.set_defaults(fn=cmd_sync)
|
|
291
|
+
|
|
292
|
+
ho = sub.add_parser("handoff", help="sync, check, and write .ghostkeep/HANDOFF.md for the next agent")
|
|
293
|
+
ho.add_argument("--days", type=float, default=14)
|
|
294
|
+
ho.add_argument("--no-sync", action="store_true")
|
|
295
|
+
ho.add_argument("--hook", action="store_true", help=argparse.SUPPRESS) # used by session-start hooks
|
|
296
|
+
ho.add_argument("--format", choices=["antigravity", "gemini-cli", "claude-code"], help=argparse.SUPPRESS)
|
|
297
|
+
ho.set_defaults(fn=cmd_handoff)
|
|
298
|
+
|
|
299
|
+
su = sub.add_parser("setup", help="load the handoff automatically at session start in every tool")
|
|
300
|
+
su.add_argument("--remove", action="store_true", help="undo setup")
|
|
301
|
+
su.add_argument("--tools", help="comma list: antigravity,gemini-cli,claude-code (default: the ones installed)")
|
|
302
|
+
su.add_argument("--no-agents-md", action="store_true", help="don't touch AGENTS.md")
|
|
303
|
+
su.set_defaults(fn=cmd_setup)
|
|
304
|
+
|
|
305
|
+
stt = sub.add_parser("stats", help="what the checks have flagged so far in this project")
|
|
306
|
+
stt.add_argument("--json", action="store_true")
|
|
307
|
+
stt.set_defaults(fn=cmd_stats)
|
|
308
|
+
|
|
309
|
+
pt = sub.add_parser("pin-test", help="pin the test command used to check 'tests pass' claims")
|
|
310
|
+
pt.add_argument("command", nargs="?", help='e.g. "python -m pytest -q" (quote it)')
|
|
311
|
+
pt.add_argument("--timeout", type=int, default=verify.DEFAULT_TIMEOUT, help="seconds (default 300)")
|
|
312
|
+
pt.add_argument("--clear", action="store_true", help="unpin")
|
|
313
|
+
pt.set_defaults(fn=cmd_pin_test)
|
|
314
|
+
|
|
315
|
+
ak = sub.add_parser("ack-ledger", help="accept a break in the ledger's hash chain you made on purpose")
|
|
316
|
+
ak.add_argument("--reason", required=True)
|
|
317
|
+
ak.set_defaults(fn=cmd_ack_ledger)
|
|
318
|
+
|
|
319
|
+
dr = sub.add_parser("doctor", help="check that every tool's logs are being read and the hook runs")
|
|
320
|
+
dr.add_argument("--days", type=float, default=14)
|
|
321
|
+
dr.set_defaults(fn=cmd_doctor)
|
|
322
|
+
|
|
323
|
+
sub.add_parser("state", help="decisions in force and open threads; writes .ghostkeep/STATE.md") \
|
|
324
|
+
.set_defaults(fn=cmd_state)
|
|
325
|
+
for op, hlp in (("retire", "a decision or preference no longer holds"),
|
|
326
|
+
("supersede", "a decision was replaced by a newer one"),
|
|
327
|
+
("done", "an open thread is finished"), ("reopen", "undo retire/supersede/done"),
|
|
328
|
+
("confirm", "a decision is still true (resets its shelf life)")):
|
|
329
|
+
c = sub.add_parser(op, help=hlp)
|
|
330
|
+
c.add_argument("id", help="id from `ghostkeep state` (a unique prefix is enough)")
|
|
331
|
+
if op == "supersede":
|
|
332
|
+
c.add_argument("new", help="id of the decision that replaces it")
|
|
333
|
+
c.add_argument("--note")
|
|
334
|
+
c.set_defaults(fn=cmd_change, op=op, new=None)
|
|
335
|
+
|
|
336
|
+
sh = sub.add_parser("show", help="recent claims with their latest status")
|
|
337
|
+
sh.add_argument("-n", type=int, default=10)
|
|
338
|
+
sh.set_defaults(fn=cmd_show)
|
|
339
|
+
|
|
340
|
+
a = p.parse_args(argv)
|
|
341
|
+
return a.fn(a)
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
if __name__ == "__main__":
|
|
345
|
+
raise SystemExit(main())
|
ghostkeep/decisions.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""Find decisions and preferences in the USER's own words. Rule-based, no LLM.
|
|
2
|
+
|
|
3
|
+
Patterns ported from the legacy watcher (v2.1), plus the forms seen in the Day 1
|
|
4
|
+
baseline ("Go with Option 1", "Option 2 is rejected because ...").
|
|
5
|
+
Only user messages are scanned, never the agent's: an agent's suggestion is not a decision.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import re
|
|
10
|
+
|
|
11
|
+
DECISION = [
|
|
12
|
+
r"\blet'?s\s+(?:use|go\s+with|keep|drop|stick\s+with)\b",
|
|
13
|
+
r"\bgo\s+with\b",
|
|
14
|
+
r"\bwe\s+(?:will|'ll|should)\s+use\b",
|
|
15
|
+
r"\bdecided\b",
|
|
16
|
+
r"\binstead\s+of\b",
|
|
17
|
+
r"\bdon'?t\s+(?:use|build|add)\b",
|
|
18
|
+
r"\bdo\s+not\s+(?:use|invent|change|add)\b",
|
|
19
|
+
r"\brejected?\b",
|
|
20
|
+
r"\b(?:let'?s|we(?:'ll|\s+will|\s+should)?)\s+switch\s+to\b", # "switch to the logs tab" is a request, not a choice
|
|
21
|
+
r"\bchose\b|\bchoose\b",
|
|
22
|
+
r"\bsupersedes\b",
|
|
23
|
+
]
|
|
24
|
+
# A preference is an instruction about how to work, not a description. "Always run the evals" is one;
|
|
25
|
+
# "the tests always fail" and "never mind" are not, so always/never only count as a command at the
|
|
26
|
+
# start of a sentence, or after I/we with a working verb.
|
|
27
|
+
PREFERENCE = [
|
|
28
|
+
r"^(?:please\s+|and\s+)?(?:always|never)\s+(?!mind\b)[a-z]",
|
|
29
|
+
r"\b(?:i|we)\s+(?:always|never)\s+(?:use|want|run|write|commit|push|keep|test|deploy|add|put)\b",
|
|
30
|
+
r"\bi\s+prefer\b|\bwe\s+prefer\b|\bprefer\s+(?:to|using)\b",
|
|
31
|
+
r"\bfrom\s+now\s+on\b",
|
|
32
|
+
]
|
|
33
|
+
_D = [re.compile(p, re.I) for p in DECISION]
|
|
34
|
+
_P = [re.compile(p, re.I) for p in PREFERENCE]
|
|
35
|
+
_SPLIT = re.compile(r"(?<=[.!?])\s+|\n+")
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def find(text: str) -> list[tuple[str, str]]:
|
|
39
|
+
"""[(kind, sentence)] with kind 'decision' or 'preference'. Sentences are verbatim."""
|
|
40
|
+
out = []
|
|
41
|
+
for raw in _SPLIT.split(text or ""):
|
|
42
|
+
s = raw.strip(" -*\t")
|
|
43
|
+
if len(s) < 8 or len(s) > 400 or s.endswith("?"):
|
|
44
|
+
continue # questions are not decisions
|
|
45
|
+
if any(r.search(s) for r in _D):
|
|
46
|
+
out.append(("decision", s))
|
|
47
|
+
elif any(r.search(s) for r in _P):
|
|
48
|
+
out.append(("preference", s))
|
|
49
|
+
return out
|