k0ntrol-cli 0.1.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.
- k0ntrol/__init__.py +1 -0
- k0ntrol/agents.py +998 -0
- k0ntrol/cli.py +190 -0
- k0ntrol/config.py +330 -0
- k0ntrol/credentials.py +78 -0
- k0ntrol/defaults/config.yaml +23 -0
- k0ntrol/events.py +838 -0
- k0ntrol/frontends/__init__.py +1 -0
- k0ntrol/frontends/ask.py +218 -0
- k0ntrol/frontends/badges.py +228 -0
- k0ntrol/frontends/banner.py +128 -0
- k0ntrol/frontends/diffview.py +174 -0
- k0ntrol/frontends/editor.py +701 -0
- k0ntrol/frontends/klog.html +740 -0
- k0ntrol/frontends/klog.py +403 -0
- k0ntrol/frontends/logo.py +12 -0
- k0ntrol/frontends/mentions.py +29 -0
- k0ntrol/frontends/prompt.py +340 -0
- k0ntrol/frontends/render.py +485 -0
- k0ntrol/frontends/session.py +717 -0
- k0ntrol/frontends/setup.py +442 -0
- k0ntrol/frontends/terminal.py +396 -0
- k0ntrol/frontends/theme.py +24 -0
- k0ntrol/helpers.py +108 -0
- k0ntrol/init_flow.py +362 -0
- k0ntrol/langfuse.py +173 -0
- k0ntrol/memory/__init__.py +0 -0
- k0ntrol/memory/index.py +235 -0
- k0ntrol/memory/layout.py +66 -0
- k0ntrol/memory/python_extract.py +189 -0
- k0ntrol/memory/reflect.py +366 -0
- k0ntrol/memory/refresh.py +21 -0
- k0ntrol/memory/scan.py +538 -0
- k0ntrol/memory/session.py +145 -0
- k0ntrol/otel.py +429 -0
- k0ntrol/pricing.py +29 -0
- k0ntrol/prompts/chatty.md +17 -0
- k0ntrol/prompts/implementer.md +14 -0
- k0ntrol/prompts/planner.md +42 -0
- k0ntrol/prompts/researcher.md +20 -0
- k0ntrol/prompts/reviewer.md +34 -0
- k0ntrol/providers.py +718 -0
- k0ntrol/search.py +133 -0
- k0ntrol/tools/__init__.py +0 -0
- k0ntrol/tools/bulk_read.py +93 -0
- k0ntrol/tools/errors.py +50 -0
- k0ntrol/tools/fetch_url.py +212 -0
- k0ntrol/tools/net.py +317 -0
- k0ntrol/tools/path_guard.py +45 -0
- k0ntrol/tools/read.py +174 -0
- k0ntrol/tools/run_tests.py +66 -0
- k0ntrol/tools/runner.py +177 -0
- k0ntrol/tools/search_memory.py +32 -0
- k0ntrol/tools/slice_guard.py +166 -0
- k0ntrol/tools/slice_journal.py +481 -0
- k0ntrol/tools/tracker.py +115 -0
- k0ntrol/tools/web_search.py +199 -0
- k0ntrol/tools/write.py +123 -0
- k0ntrol/tracker/__init__.py +31 -0
- k0ntrol/tracker/github.py +371 -0
- k0ntrol/tracker/local_files.py +241 -0
- k0ntrol/tracker/protocol.py +210 -0
- k0ntrol/workflow/__init__.py +29 -0
- k0ntrol/workflow/change.py +605 -0
- k0ntrol/workflow/ci_gate.py +96 -0
- k0ntrol/workflow/context.py +137 -0
- k0ntrol/workflow/implement.py +1150 -0
- k0ntrol/workflow/nodes.py +331 -0
- k0ntrol/workflow/plan.py +675 -0
- k0ntrol/workflow/qa.py +98 -0
- k0ntrol/workflow/research.py +533 -0
- k0ntrol/workflow/routers.py +273 -0
- k0ntrol/workflow/run.py +1165 -0
- k0ntrol/workflow/state.py +146 -0
- k0ntrol/workflow/triage.py +269 -0
- k0ntrol_cli-0.1.0.dist-info/METADATA +154 -0
- k0ntrol_cli-0.1.0.dist-info/RECORD +80 -0
- k0ntrol_cli-0.1.0.dist-info/WHEEL +4 -0
- k0ntrol_cli-0.1.0.dist-info/entry_points.txt +2 -0
- k0ntrol_cli-0.1.0.dist-info/licenses/LICENSE +201 -0
|
@@ -0,0 +1,605 @@
|
|
|
1
|
+
"""The ``change`` module: deterministic git side effects for the graphs.
|
|
2
|
+
|
|
3
|
+
#41 needs only reads — the current branch for ``run_start`` and the
|
|
4
|
+
working-tree summary the diff gate shows. #44/#45 add the write side
|
|
5
|
+
(branch, memory commits, commit + push + draft PR)
|
|
6
|
+
as marker-idempotent nodes through this module.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import difflib
|
|
10
|
+
import hashlib
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
import re
|
|
14
|
+
import shutil
|
|
15
|
+
import stat
|
|
16
|
+
import subprocess
|
|
17
|
+
from collections.abc import Iterable
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
|
|
20
|
+
# Cap on the diff text shown at a gate.
|
|
21
|
+
_SUMMARY_MAX_CHARS = 12_000
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def dirty_paths(root: Path, *, ignored_prefix: str = ".k0-mem/") -> list[str]:
|
|
25
|
+
"""Porcelain lines for the working tree, minus ``.k0-mem/`` entries.
|
|
26
|
+
|
|
27
|
+
Local memory is the harness's own scratch space — it never makes the
|
|
28
|
+
tree dirty for a run.
|
|
29
|
+
"""
|
|
30
|
+
return [
|
|
31
|
+
f"{status} {path}" if status else path
|
|
32
|
+
for status, path in _status_entries(_status(root))
|
|
33
|
+
if not _ignored(path, ignored_prefix)
|
|
34
|
+
]
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def reset_scan_output(root: Path) -> None:
|
|
38
|
+
"""Drop local changes to the scanner's output (``Project_context/``).
|
|
39
|
+
|
|
40
|
+
The run-start rescan rewrites the code graph on whatever branch the run
|
|
41
|
+
starts from; left there, it blocks the checkout of the run branch. It is
|
|
42
|
+
derived data the next scan rewrites. ``Mem.md`` and ``Rules.md`` stay.
|
|
43
|
+
"""
|
|
44
|
+
_git(root, "checkout", "--", ".k0-mem/Project_context")
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def changed_paths(root: Path) -> list[str]:
|
|
48
|
+
"""The paths ``dirty_paths`` reports: what the working tree changed."""
|
|
49
|
+
return [
|
|
50
|
+
path
|
|
51
|
+
for _, path in _status_entries(_status(root))
|
|
52
|
+
if not _ignored(path, ".k0-mem/")
|
|
53
|
+
]
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _status_entries(status: str) -> list[tuple[str, str]]:
|
|
57
|
+
"""``(status, path)`` pairs from ``-z`` porcelain — unquoted names and
|
|
58
|
+
rename/copy sources (the bare record after an ``R``/``C`` entry)."""
|
|
59
|
+
entries: list[tuple[str, str]] = []
|
|
60
|
+
source = False
|
|
61
|
+
for record in status.split("\0"):
|
|
62
|
+
if not record:
|
|
63
|
+
continue
|
|
64
|
+
if source:
|
|
65
|
+
entries.append(("", record))
|
|
66
|
+
source = False
|
|
67
|
+
continue
|
|
68
|
+
entries.append((record[:2], record[3:]))
|
|
69
|
+
source = "R" in record[:2] or "C" in record[:2]
|
|
70
|
+
return entries
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _ignored(path: str, prefix: str) -> bool:
|
|
74
|
+
return path == prefix.rstrip("/") or path.startswith(prefix)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def slugify(title: str) -> str:
|
|
78
|
+
"""``k0/<n>-<slug>``'s slug: lowercase alnum runs joined by dashes."""
|
|
79
|
+
slug = re.sub(r"[^a-z0-9]+", "-", title.lower()).strip("-")
|
|
80
|
+
return slug[:48].strip("-") or "work"
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def existing_branch(root: Path, ref: str) -> str | None:
|
|
84
|
+
"""The ``k0/<ref>-*`` branch an earlier run cut, if any.
|
|
85
|
+
|
|
86
|
+
A local branch wins; a branch only on ``origin`` (a fresh clone) counts
|
|
87
|
+
too, named without the remote.
|
|
88
|
+
"""
|
|
89
|
+
local = _branches(root, f"refs/heads/k0/{ref}-*")
|
|
90
|
+
remote = _branches(root, f"refs/remotes/origin/k0/{ref}-*")
|
|
91
|
+
return next(iter(local + [b.removeprefix("origin/") for b in remote]), None)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _branches(root: Path, pattern: str) -> list[str]:
|
|
95
|
+
out = _git(root, "for-each-ref", "--format=%(refname:short)", pattern).stdout
|
|
96
|
+
return out.split()
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def remote_tip(root: Path, branch: str) -> str | None:
|
|
100
|
+
"""The commit ``origin/<branch>`` points at, if the branch was pushed."""
|
|
101
|
+
result = _git(root, "rev-parse", "--verify", "--quiet", f"refs/remotes/origin/{branch}")
|
|
102
|
+
return result.stdout.strip() or None
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def default_base_branch(root: Path) -> str:
|
|
106
|
+
"""origin's default branch, ``main`` when there is no remote."""
|
|
107
|
+
result = _git(
|
|
108
|
+
root, "symbolic-ref", "--quiet", "--short", "refs/remotes/origin/HEAD"
|
|
109
|
+
)
|
|
110
|
+
name = result.stdout.strip()
|
|
111
|
+
if result.returncode == 0 and name:
|
|
112
|
+
return name.removeprefix("origin/")
|
|
113
|
+
return "main"
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def origin_url(root: Path) -> str:
|
|
117
|
+
"""The URL of the ``origin`` remote, empty when there is none."""
|
|
118
|
+
return _git(root, "remote", "get-url", "origin").stdout.strip()
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def decider(root: Path) -> str:
|
|
122
|
+
"""Who is answering the gates: the git user.name, else ``human``."""
|
|
123
|
+
return _git(root, "config", "user.name").stdout.strip() or "human"
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def current_branch(root: Path) -> str | None:
|
|
127
|
+
"""The checkout's branch name, or ``None`` outside a git repo."""
|
|
128
|
+
result = _git(root, "rev-parse", "--abbrev-ref", "HEAD")
|
|
129
|
+
if result.returncode != 0:
|
|
130
|
+
return None
|
|
131
|
+
return result.stdout.strip() or None
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def head_sha(root: Path) -> str:
|
|
135
|
+
"""The commit ``HEAD`` points at, or "" outside a git repo."""
|
|
136
|
+
return _git(root, "rev-parse", "HEAD").stdout.strip()
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def merge_base(root: Path, base: str) -> str:
|
|
140
|
+
"""Where HEAD left ``origin/<base>`` (else local ``<base>``).
|
|
141
|
+
|
|
142
|
+
Falls back to git's empty tree so a diff against it shows everything.
|
|
143
|
+
"""
|
|
144
|
+
for ref in (f"origin/{base}", base):
|
|
145
|
+
found = _git(root, "merge-base", "HEAD", ref).stdout.strip()
|
|
146
|
+
if found:
|
|
147
|
+
return found
|
|
148
|
+
return _empty_tree(root)
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _empty_tree(root: Path) -> str:
|
|
152
|
+
"""The empty tree object (written if missing): diff against it shows all."""
|
|
153
|
+
return _git(root, "hash-object", "-w", "-t", "tree", "/dev/null").stdout.strip()
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
class DiffError(RuntimeError):
|
|
157
|
+
"""``git diff`` failed, so a gate cannot tell what changed."""
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def diff_since(root: Path, since: str, path: str) -> str:
|
|
161
|
+
"""``git diff <since> HEAD -- <path>``, capped like every gate detail.
|
|
162
|
+
|
|
163
|
+
Raises ``DiffError`` when git fails (say ``since`` is missing from the
|
|
164
|
+
repo): a diff that cannot be computed is never an empty diff.
|
|
165
|
+
"""
|
|
166
|
+
proc = _git(root, "diff", since, "HEAD", "--", path)
|
|
167
|
+
if proc.returncode != 0:
|
|
168
|
+
detail = proc.stderr.strip() or f"git diff exited {proc.returncode}"
|
|
169
|
+
raise DiffError(f"cannot diff {path} since {since}: {detail}")
|
|
170
|
+
return _truncate(proc.stdout.rstrip())
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def diff_stat(root: Path) -> str:
|
|
174
|
+
"""``git diff --stat HEAD`` plus untracked paths, for gate details.
|
|
175
|
+
|
|
176
|
+
Agent-written files are untracked and never appear in ``--stat``, so
|
|
177
|
+
they are listed as ``(new)`` lines — otherwise the stat would show
|
|
178
|
+
nothing while the tree is full of new work. ``.k0-mem/`` is runtime
|
|
179
|
+
state, not part of the change, so it is left out.
|
|
180
|
+
"""
|
|
181
|
+
stat = _git(root, "diff", "--stat", "HEAD", "--").stdout.strip()
|
|
182
|
+
lines = [stat] if stat else []
|
|
183
|
+
lines += [f" {path} | (new)" for path in _new_files(root)]
|
|
184
|
+
return "\n".join(lines) or "no changes"
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def _new_files(root: Path) -> list[str]:
|
|
188
|
+
"""Untracked, non-ignored file paths, without ``.k0-mem/``."""
|
|
189
|
+
out = _git(
|
|
190
|
+
root, "ls-files", "-z", "--others", "--exclude-standard"
|
|
191
|
+
).stdout
|
|
192
|
+
return [p for p in out.split("\0") if p and not p.startswith(".k0-mem/")]
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def _status(root: Path) -> str:
|
|
196
|
+
"""``git status --porcelain -z -uall``: unquoted, NUL-separated."""
|
|
197
|
+
return _git(root, "status", "--porcelain", "-z", "-uall").stdout
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def _git(root: Path, *args: str) -> subprocess.CompletedProcess:
|
|
201
|
+
return subprocess.run(
|
|
202
|
+
["git", "-C", str(root), *args],
|
|
203
|
+
capture_output=True,
|
|
204
|
+
text=True,
|
|
205
|
+
check=False,
|
|
206
|
+
)
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
# --- working-tree snapshots (/implement's diff-gate ``n``, #116) ---------------
|
|
210
|
+
|
|
211
|
+
# Backed-up repository files live under this payload subdirectory, apart
|
|
212
|
+
# from the snapshot's own ``manifest.json`` at the root — a repo file of
|
|
213
|
+
# the same name must never be clobbered by the metadata.
|
|
214
|
+
_PAYLOAD = "tree"
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def worktree_snapshot_dir(root: Path, run_id: str) -> Path:
|
|
218
|
+
"""Where run ``run_id``'s pre-run working-tree snapshot lives."""
|
|
219
|
+
return root / ".k0-mem" / "snapshots" / run_id
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def is_git_repo(root: Path) -> bool:
|
|
223
|
+
"""Whether ``root`` sits inside a git work tree.
|
|
224
|
+
|
|
225
|
+
The snapshot is built on ``git ls-files`` — outside a repo it would
|
|
226
|
+
be empty and ``n`` would silently keep every change, so ``/implement``
|
|
227
|
+
refuses such roots up front.
|
|
228
|
+
"""
|
|
229
|
+
result = _git(root, "rev-parse", "--is-inside-work-tree")
|
|
230
|
+
return result.returncode == 0 and result.stdout.strip() == "true"
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def snapshot_worktree(root: Path, dest: Path) -> None:
|
|
234
|
+
"""Copy the working tree's files into ``dest`` for ``restore_worktree``.
|
|
235
|
+
|
|
236
|
+
The set is what git sees — tracked files plus untracked non-ignored
|
|
237
|
+
ones — minus ``.k0-mem/``: agents cannot write protected paths, so
|
|
238
|
+
everything under it is harness bookkeeping, never the change. Files
|
|
239
|
+
land under ``dest / _PAYLOAD`` so the snapshot's own ``manifest.json``
|
|
240
|
+
can never overwrite a backed-up repository file of the same name.
|
|
241
|
+
"""
|
|
242
|
+
_ensure_snapshot_ignored(root)
|
|
243
|
+
dest.mkdir(parents=True, exist_ok=True)
|
|
244
|
+
payload = dest / _PAYLOAD
|
|
245
|
+
manifest: dict[str, str] = {}
|
|
246
|
+
links: dict[str, str] = {}
|
|
247
|
+
dirs: list[str] = []
|
|
248
|
+
for relative in _worktree_files(root):
|
|
249
|
+
source = root / relative
|
|
250
|
+
if source.is_symlink():
|
|
251
|
+
links[relative] = os.readlink(source)
|
|
252
|
+
elif source.is_file():
|
|
253
|
+
target = payload / relative
|
|
254
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
255
|
+
shutil.copy2(source, target)
|
|
256
|
+
manifest[relative] = _sha256(source)
|
|
257
|
+
elif source.is_dir():
|
|
258
|
+
# a gitlink (submodule): recorded so restore leaves it alone
|
|
259
|
+
dirs.append(relative)
|
|
260
|
+
(dest / "manifest.json").write_text(
|
|
261
|
+
json.dumps(
|
|
262
|
+
{"files": manifest, "links": links, "dirs": dirs},
|
|
263
|
+
indent=2,
|
|
264
|
+
sort_keys=True,
|
|
265
|
+
)
|
|
266
|
+
+ "\n",
|
|
267
|
+
encoding="utf-8",
|
|
268
|
+
)
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def restore_worktree(root: Path, snapshot: Path) -> None:
|
|
272
|
+
"""Put the tree back as the snapshot found it.
|
|
273
|
+
|
|
274
|
+
Files the run added are deleted (emptying their dirs), files it
|
|
275
|
+
edited or removed are copied back from the snapshot. ``.k0-mem/`` is
|
|
276
|
+
never in the file set, so events and checkpoints survive.
|
|
277
|
+
"""
|
|
278
|
+
recorded = _snapshot_manifest(snapshot)
|
|
279
|
+
manifest: dict[str, str] = recorded["files"]
|
|
280
|
+
links: dict[str, str] = recorded.get("links", {})
|
|
281
|
+
dirs: list[str] = recorded.get("dirs", [])
|
|
282
|
+
known = set(manifest) | set(links) | set(dirs)
|
|
283
|
+
_remove_new_files(root, known)
|
|
284
|
+
for relative, digest in manifest.items():
|
|
285
|
+
_restore_file(root, snapshot, relative, digest)
|
|
286
|
+
for relative, link_target in links.items():
|
|
287
|
+
_restore_link(root, relative, link_target)
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def _remove_new_files(root: Path, known: set[str]) -> None:
|
|
291
|
+
"""Delete what the run added; empty dirs it leaves are pruned."""
|
|
292
|
+
for relative in _worktree_files(root):
|
|
293
|
+
if relative not in known:
|
|
294
|
+
_remove(root / relative)
|
|
295
|
+
_prune_empty_dirs(root, relative)
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def _restore_file(root: Path, snapshot: Path, relative: str, digest: str) -> None:
|
|
299
|
+
"""Copy one snapshotted file back unless the tree already matches."""
|
|
300
|
+
target = root / relative
|
|
301
|
+
unchanged = (
|
|
302
|
+
not target.is_symlink()
|
|
303
|
+
and target.is_file()
|
|
304
|
+
and _sha256(target) == digest
|
|
305
|
+
)
|
|
306
|
+
if unchanged:
|
|
307
|
+
return
|
|
308
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
309
|
+
_remove(target) # a symlink or dir here must go before copy2 writes
|
|
310
|
+
shutil.copy2(snapshot / _PAYLOAD / relative, target)
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def drop_worktree_snapshot(root: Path, snapshot: Path) -> None:
|
|
314
|
+
"""A finished run keeps no snapshot."""
|
|
315
|
+
shutil.rmtree(snapshot, ignore_errors=True)
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
def _restore_link(root: Path, relative: str, link_target: str) -> None:
|
|
319
|
+
"""Recreate a symlink the run removed or retargeted; leave a correct one."""
|
|
320
|
+
path = root / relative
|
|
321
|
+
if path.is_symlink() and os.readlink(path) == link_target:
|
|
322
|
+
return
|
|
323
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
324
|
+
_remove(path)
|
|
325
|
+
path.symlink_to(link_target)
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def _worktree_files(root: Path) -> list[str]:
|
|
329
|
+
"""Tracked plus untracked-nonignored paths, minus ``.k0-mem/``."""
|
|
330
|
+
seen = dict.fromkeys(
|
|
331
|
+
_git_paths(root, "ls-files", "-z")
|
|
332
|
+
+ _git_paths(root, "ls-files", "--others", "--exclude-standard", "-z")
|
|
333
|
+
)
|
|
334
|
+
return sorted(p for p in seen if p and not p.startswith(".k0-mem/"))
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def _git_paths(root: Path, *args: str) -> list[str]:
|
|
338
|
+
return [p for p in _git(root, *args).stdout.split("\0") if p]
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
def _sha256(path: Path) -> str:
|
|
342
|
+
return hashlib.sha256(path.read_bytes()).hexdigest()
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
def _remove(path: Path) -> None:
|
|
346
|
+
if path.is_dir() and not path.is_symlink():
|
|
347
|
+
shutil.rmtree(path)
|
|
348
|
+
else:
|
|
349
|
+
path.unlink(missing_ok=True)
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
def _prune_empty_dirs(root: Path, relative: str) -> None:
|
|
353
|
+
"""Remove ancestor dirs the run emptied, stopping at the first non-empty."""
|
|
354
|
+
base = root.resolve()
|
|
355
|
+
current = (base / relative).parent
|
|
356
|
+
while current != base:
|
|
357
|
+
try:
|
|
358
|
+
current.rmdir()
|
|
359
|
+
except OSError:
|
|
360
|
+
return
|
|
361
|
+
current = current.parent
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
def _ensure_snapshot_ignored(root: Path) -> None:
|
|
365
|
+
"""Keep ``.k0-mem/snapshots/`` out of ``git status`` like the rest of
|
|
366
|
+
the harness's scratch (same append-only pattern as event rotation)."""
|
|
367
|
+
gitignore = root / ".k0-mem" / ".gitignore"
|
|
368
|
+
text = gitignore.read_text(encoding="utf-8") if gitignore.exists() else ""
|
|
369
|
+
if "snapshots/" in text.splitlines():
|
|
370
|
+
return
|
|
371
|
+
prefix = "" if not text or text.endswith("\n") else "\n"
|
|
372
|
+
with open(gitignore, "a", encoding="utf-8") as fh:
|
|
373
|
+
fh.write(f"{prefix}snapshots/\n")
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
# --- the diff gate's run-change listing (#149) ---------------------------------
|
|
377
|
+
|
|
378
|
+
|
|
379
|
+
def gate_change(root: Path, snapshot: Path) -> tuple[str, str]:
|
|
380
|
+
"""The diff gate's ``(detail, diff)`` against the pre-run snapshot.
|
|
381
|
+
|
|
382
|
+
The baseline is the tree as the run found it, not ``HEAD``: the
|
|
383
|
+
detail lists the pre-run files the run modified or deleted, apart
|
|
384
|
+
from the files it added, so edits to shared code stand out — a file
|
|
385
|
+
already uncommitted before the run and untouched by it matches the
|
|
386
|
+
snapshot and is never listed. The diff is a git-style unified diff
|
|
387
|
+
the frontend draws file by file.
|
|
388
|
+
"""
|
|
389
|
+
recorded = _snapshot_manifest(snapshot)
|
|
390
|
+
changed = _changed_entries(root, snapshot, recorded)
|
|
391
|
+
added = _added_paths(root, recorded)
|
|
392
|
+
detail = _change_lines(changed, added)
|
|
393
|
+
chunks = [_entry_diff(snapshot, root, entry) for entry in changed]
|
|
394
|
+
chunks += [_added_diff(root, path) for path in added]
|
|
395
|
+
return detail, _truncate("\n".join(chunks).rstrip())
|
|
396
|
+
|
|
397
|
+
|
|
398
|
+
def _snapshot_manifest(snapshot: Path) -> dict:
|
|
399
|
+
return json.loads((snapshot / "manifest.json").read_text(encoding="utf-8"))
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
def _changed_entries(
|
|
403
|
+
root: Path, snapshot: Path, recorded: dict
|
|
404
|
+
) -> list[tuple[str, str, str]]:
|
|
405
|
+
"""``(path, mark, kind)`` for each snapshot path the run touched."""
|
|
406
|
+
entries: list[tuple[str, str, str]] = []
|
|
407
|
+
for relative, digest in recorded["files"].items():
|
|
408
|
+
mark = _file_mark(
|
|
409
|
+
root / relative, snapshot / _PAYLOAD / relative, digest
|
|
410
|
+
)
|
|
411
|
+
_note(entries, relative, mark, "file")
|
|
412
|
+
for relative, target in recorded.get("links", {}).items():
|
|
413
|
+
_note(entries, relative, _link_mark(root / relative, target), "link")
|
|
414
|
+
for relative in recorded.get("dirs", []):
|
|
415
|
+
_note(entries, relative, _dir_mark(root / relative), "dir")
|
|
416
|
+
return sorted(entries)
|
|
417
|
+
|
|
418
|
+
|
|
419
|
+
def _note(
|
|
420
|
+
entries: list[tuple[str, str, str]],
|
|
421
|
+
relative: str,
|
|
422
|
+
mark: str | None,
|
|
423
|
+
kind: str,
|
|
424
|
+
) -> None:
|
|
425
|
+
if mark:
|
|
426
|
+
entries.append((relative, mark, kind))
|
|
427
|
+
|
|
428
|
+
|
|
429
|
+
def _file_mark(path: Path, payload: Path, digest: str) -> str | None:
|
|
430
|
+
"""``D`` gone, ``M`` different bytes, kind or mode, ``None`` untouched.
|
|
431
|
+
|
|
432
|
+
The exec bit is compared against the backed-up copy — ``copy2``
|
|
433
|
+
preserves it, so a mode-only change still marks the file.
|
|
434
|
+
"""
|
|
435
|
+
if path.is_symlink() or path.is_dir():
|
|
436
|
+
return "M" # a file became a link or a dir
|
|
437
|
+
if not path.is_file():
|
|
438
|
+
return "D"
|
|
439
|
+
if _sha256(path) != digest or _executable(path) != _executable(payload):
|
|
440
|
+
return "M"
|
|
441
|
+
return None
|
|
442
|
+
|
|
443
|
+
|
|
444
|
+
def _executable(path: Path) -> bool:
|
|
445
|
+
return bool(path.stat().st_mode & stat.S_IXUSR)
|
|
446
|
+
|
|
447
|
+
|
|
448
|
+
def _git_mode(path: Path) -> int:
|
|
449
|
+
"""The ``100644``/``100755`` git reports in a diff's mode lines."""
|
|
450
|
+
return 0o100755 if _executable(path) else 0o100644
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
def _link_mark(path: Path, target: str) -> str | None:
|
|
454
|
+
"""``None`` while the symlink still points at ``target``."""
|
|
455
|
+
if not path.is_symlink():
|
|
456
|
+
return "M" if path.exists() else "D"
|
|
457
|
+
return None if os.readlink(path) == target else "M"
|
|
458
|
+
|
|
459
|
+
|
|
460
|
+
def _dir_mark(path: Path) -> str | None:
|
|
461
|
+
"""A gitlink's checkout: ``None`` while it is still a directory."""
|
|
462
|
+
if path.is_dir():
|
|
463
|
+
return None
|
|
464
|
+
return "M" if path.exists() else "D"
|
|
465
|
+
|
|
466
|
+
|
|
467
|
+
def _added_paths(root: Path, recorded: dict) -> list[str]:
|
|
468
|
+
"""Worktree files the snapshot does not know: what the run added.
|
|
469
|
+
|
|
470
|
+
``git ls-files`` still names a tracked file deleted before the run,
|
|
471
|
+
but its absent bytes never reached the manifest — only paths that
|
|
472
|
+
exist can be run additions.
|
|
473
|
+
"""
|
|
474
|
+
known = (
|
|
475
|
+
set(recorded["files"])
|
|
476
|
+
| set(recorded.get("links", {}))
|
|
477
|
+
| set(recorded.get("dirs", []))
|
|
478
|
+
)
|
|
479
|
+
return [
|
|
480
|
+
p
|
|
481
|
+
for p in _worktree_files(root)
|
|
482
|
+
if p not in known and os.path.lexists(root / p)
|
|
483
|
+
]
|
|
484
|
+
|
|
485
|
+
|
|
486
|
+
def _change_lines(
|
|
487
|
+
changed: list[tuple[str, str, str]], added: list[str]
|
|
488
|
+
) -> str:
|
|
489
|
+
"""Porcelain-style lines: the pre-run files first, then the adds."""
|
|
490
|
+
lines = [f" {mark} {path}" for path, mark, _ in changed]
|
|
491
|
+
lines += [f"?? {path}" for path in added]
|
|
492
|
+
return "\n".join(lines) or "no changes"
|
|
493
|
+
|
|
494
|
+
|
|
495
|
+
def _entry_diff(
|
|
496
|
+
snapshot: Path, root: Path, entry: tuple[str, str, str]
|
|
497
|
+
) -> str:
|
|
498
|
+
"""One ``diff --git`` chunk for a changed pre-run path."""
|
|
499
|
+
relative, mark, kind = entry
|
|
500
|
+
header = f"diff --git a/{relative} b/{relative}\n"
|
|
501
|
+
if kind != "file":
|
|
502
|
+
return header + f"{kind} changed\n"
|
|
503
|
+
old_path = snapshot / _PAYLOAD / relative
|
|
504
|
+
meta = (
|
|
505
|
+
f"deleted file mode {_git_mode(old_path):06o}\n"
|
|
506
|
+
if mark == "D"
|
|
507
|
+
else _mode_lines(old_path, root / relative)
|
|
508
|
+
)
|
|
509
|
+
old = _read_lines(old_path)
|
|
510
|
+
new = [] if mark == "D" else _read_lines(root / relative)
|
|
511
|
+
body = _unified(
|
|
512
|
+
old, new, f"a/{relative}", "/dev/null" if mark == "D" else f"b/{relative}"
|
|
513
|
+
)
|
|
514
|
+
if body is None:
|
|
515
|
+
return header + meta + "binary or unreadable file changed\n"
|
|
516
|
+
return header + meta + body
|
|
517
|
+
|
|
518
|
+
|
|
519
|
+
def _mode_lines(old_path: Path, new_path: Path) -> str:
|
|
520
|
+
"""git's ``old mode``/``new mode`` pair when the exec bit moved."""
|
|
521
|
+
if not new_path.is_file():
|
|
522
|
+
return ""
|
|
523
|
+
old_mode, new_mode = _git_mode(old_path), _git_mode(new_path)
|
|
524
|
+
if old_mode == new_mode:
|
|
525
|
+
return ""
|
|
526
|
+
return f"old mode {old_mode:06o}\nnew mode {new_mode:06o}\n"
|
|
527
|
+
|
|
528
|
+
|
|
529
|
+
def _added_diff(root: Path, relative: str) -> str:
|
|
530
|
+
"""One ``diff --git`` chunk for a file the run added."""
|
|
531
|
+
header = f"diff --git a/{relative} b/{relative}\nnew file\n"
|
|
532
|
+
lines = _read_lines(root / relative)
|
|
533
|
+
if lines is None:
|
|
534
|
+
return header + "binary or unreadable file\n"
|
|
535
|
+
return header + _terminated(
|
|
536
|
+
difflib.unified_diff([], lines, fromfile="/dev/null", tofile=f"b/{relative}")
|
|
537
|
+
)
|
|
538
|
+
|
|
539
|
+
|
|
540
|
+
def _unified(
|
|
541
|
+
old: list[str] | None, new: list[str] | None, fromfile: str, tofile: str
|
|
542
|
+
) -> str | None:
|
|
543
|
+
"""The unified-diff body, ``None`` when either side is unreadable."""
|
|
544
|
+
if old is None or new is None:
|
|
545
|
+
return None
|
|
546
|
+
return _terminated(
|
|
547
|
+
difflib.unified_diff(old, new, fromfile=fromfile, tofile=tofile)
|
|
548
|
+
)
|
|
549
|
+
|
|
550
|
+
|
|
551
|
+
def _terminated(lines: Iterable[str]) -> str:
|
|
552
|
+
"""Join diff lines; an unterminated last line gets git's ``\\ No
|
|
553
|
+
newline`` marker so it never glues onto the next diff line."""
|
|
554
|
+
return "".join(
|
|
555
|
+
line if line.endswith("\n") else f"{line}\n\\n"
|
|
556
|
+
for line in lines
|
|
557
|
+
)
|
|
558
|
+
|
|
559
|
+
|
|
560
|
+
def _read_lines(path: Path) -> list[str] | None:
|
|
561
|
+
try:
|
|
562
|
+
return path.read_text(encoding="utf-8").splitlines(keepends=True)
|
|
563
|
+
except (OSError, UnicodeError):
|
|
564
|
+
return None
|
|
565
|
+
|
|
566
|
+
|
|
567
|
+
def _truncate(text: str) -> str:
|
|
568
|
+
if len(text) > _SUMMARY_MAX_CHARS:
|
|
569
|
+
text = text[:_SUMMARY_MAX_CHARS] + "\n... diff truncated ..."
|
|
570
|
+
return text
|
|
571
|
+
|
|
572
|
+
|
|
573
|
+
GENERATED_ATTRIBUTE = ".k0-mem/Project_context/** linguist-generated=true"
|
|
574
|
+
_GRAPH = ".k0-mem/Project_context/"
|
|
575
|
+
|
|
576
|
+
|
|
577
|
+
def mark_graph_generated(root: Path) -> bool:
|
|
578
|
+
"""Add ``GENERATED_ATTRIBUTE`` to ``.gitattributes``; False when there."""
|
|
579
|
+
path = root / ".gitattributes"
|
|
580
|
+
text = path.read_text(encoding="utf-8") if path.exists() else ""
|
|
581
|
+
if GENERATED_ATTRIBUTE in text.splitlines():
|
|
582
|
+
return False
|
|
583
|
+
gap = "\n" if text and not text.endswith("\n") else ""
|
|
584
|
+
path.write_text(f"{text}{gap}{GENERATED_ATTRIBUTE}\n", encoding="utf-8")
|
|
585
|
+
return True
|
|
586
|
+
|
|
587
|
+
|
|
588
|
+
def branch_paths(root: Path, base: str) -> list[str]:
|
|
589
|
+
"""Every file the commits on ``HEAD`` since ``base`` touch."""
|
|
590
|
+
return _git_paths(root, "diff", "--name-only", "-z", f"{base}...HEAD")
|
|
591
|
+
|
|
592
|
+
|
|
593
|
+
def pushed_file_lines(paths: list[str]) -> list[str]:
|
|
594
|
+
"""The files a push carries, one line each; the knowledge graph as one
|
|
595
|
+
count, so a ``Mem.md`` edit is never lost among them (#204)."""
|
|
596
|
+
graph = [p for p in paths if p.startswith(_GRAPH)]
|
|
597
|
+
lines = [f"- {p}" for p in sorted(paths) if not p.startswith(_GRAPH)]
|
|
598
|
+
if graph:
|
|
599
|
+
lines.append(f"- {len(graph)} knowledge-graph files refreshed")
|
|
600
|
+
return lines
|
|
601
|
+
|
|
602
|
+
|
|
603
|
+
def has_origin(root: Path) -> bool:
|
|
604
|
+
"""Whether the repo has an ``origin`` remote to push to."""
|
|
605
|
+
return _git(root, "remote", "get-url", "origin").returncode == 0
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
"""The CI gate: no push changes ``.github/`` without the human (#47).
|
|
2
|
+
|
|
3
|
+
ADR 0006: ``.github/`` stays writable, so the risk is the push, not the
|
|
4
|
+
write. Every ``/implement #<n>`` push goes through this
|
|
5
|
+
module: ``run_ci_gate`` is
|
|
6
|
+
the node body that decides, ``gated_push`` is the only place the harness
|
|
7
|
+
calls ``tracker.push`` and it refuses to push a HEAD the gate has not
|
|
8
|
+
cleared. The gate looks at the ``.github/`` diff since the last approved
|
|
9
|
+
push (or since the base branch before the first one), so it fires again
|
|
10
|
+
on any later push that changes ``.github/``.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from collections.abc import Callable
|
|
14
|
+
|
|
15
|
+
from langgraph.types import interrupt
|
|
16
|
+
|
|
17
|
+
from k0ntrol.workflow.change import diff_since, head_sha, merge_base
|
|
18
|
+
from k0ntrol.workflow.context import RunContext
|
|
19
|
+
|
|
20
|
+
GITHUB_PATH = ".github/"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class CiGateError(RuntimeError):
|
|
24
|
+
"""A push was attempted without the CI gate clearing HEAD."""
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def ci_diff(ctx: RunContext, state: dict) -> str:
|
|
28
|
+
"""The ``.github/`` diff since the last approved push, "" if none."""
|
|
29
|
+
since = state.get("ci_approved_sha") or merge_base(ctx.root, ctx.base_branch)
|
|
30
|
+
return diff_since(ctx.root, since, GITHUB_PATH)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def run_ci_gate(
|
|
34
|
+
ctx: RunContext, state: dict, *, attempts_key: str = "implementer_attempts"
|
|
35
|
+
) -> dict:
|
|
36
|
+
"""Clear HEAD for a push: pass through, or interrupt on a ``.github/`` diff.
|
|
37
|
+
|
|
38
|
+
``ci_cleared_sha`` names the HEAD the push may use; ``None`` means the
|
|
39
|
+
human rejected and the feedback goes to the building agent, whose
|
|
40
|
+
``attempts_key`` counter the reject resets
|
|
41
|
+
(``implementer_attempts`` on ``/implement``). ``ci_approved``
|
|
42
|
+
is True only when the human approved on this pass (the gate comment is
|
|
43
|
+
due). A run stuck by its event log never interrupts — nobody can be
|
|
44
|
+
asked and the log cannot record the gate — so unapproved changes stay
|
|
45
|
+
local.
|
|
46
|
+
"""
|
|
47
|
+
head = head_sha(ctx.root)
|
|
48
|
+
diff = ci_diff(ctx, state)
|
|
49
|
+
if not diff:
|
|
50
|
+
return {"ci_cleared_sha": head, "ci_approved": False, "ci_feedback": None}
|
|
51
|
+
if state.get("reason") == "event_log":
|
|
52
|
+
return {"ci_cleared_sha": None, "ci_approved": False, "ci_feedback": None}
|
|
53
|
+
decision = interrupt(
|
|
54
|
+
{
|
|
55
|
+
"gate": "ci",
|
|
56
|
+
"question": "approve pushing these .github/ changes?",
|
|
57
|
+
"answers": ["ok", "redo"],
|
|
58
|
+
"detail": diff,
|
|
59
|
+
}
|
|
60
|
+
)
|
|
61
|
+
word, _, feedback = str(decision).strip().partition(" ")
|
|
62
|
+
if word.lower() == "ok":
|
|
63
|
+
return {
|
|
64
|
+
"ci_cleared_sha": head,
|
|
65
|
+
"ci_approved": True,
|
|
66
|
+
"ci_feedback": None,
|
|
67
|
+
"ci_round": state.get("ci_round", 0) + 1,
|
|
68
|
+
}
|
|
69
|
+
return {
|
|
70
|
+
"ci_cleared_sha": None,
|
|
71
|
+
"ci_approved": False,
|
|
72
|
+
attempts_key: 0,
|
|
73
|
+
"refactor": True,
|
|
74
|
+
"ci_feedback": feedback.strip(),
|
|
75
|
+
"ci_rejections": [*state.get("ci_rejections", []), feedback.strip()],
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def make_ci_gate(
|
|
80
|
+
ctx: RunContext, *, attempts_key: str = "implementer_attempts"
|
|
81
|
+
) -> Callable[[dict], dict]:
|
|
82
|
+
"""The ``ci_gate`` graph node."""
|
|
83
|
+
|
|
84
|
+
def node(state: dict) -> dict:
|
|
85
|
+
return run_ci_gate(ctx, state, attempts_key=attempts_key)
|
|
86
|
+
|
|
87
|
+
return node
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def gated_push(ctx: RunContext, state: dict) -> dict:
|
|
91
|
+
"""Push the run's branch, only at a HEAD the CI gate cleared."""
|
|
92
|
+
head = head_sha(ctx.root)
|
|
93
|
+
if state.get("ci_cleared_sha") != head:
|
|
94
|
+
raise CiGateError("push refused: the CI gate has not cleared HEAD")
|
|
95
|
+
ctx.tracker.push(state["branch"])
|
|
96
|
+
return {"ci_approved_sha": head}
|