pyxis-harness-workspace-changes 0.1.0rc1__tar.gz
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.
- pyxis_harness_workspace_changes-0.1.0rc1/.gitignore +27 -0
- pyxis_harness_workspace_changes-0.1.0rc1/AGENTS.md +70 -0
- pyxis_harness_workspace_changes-0.1.0rc1/LICENSE +21 -0
- pyxis_harness_workspace_changes-0.1.0rc1/PKG-INFO +93 -0
- pyxis_harness_workspace_changes-0.1.0rc1/pyproject.toml +40 -0
- pyxis_harness_workspace_changes-0.1.0rc1/pyxis_harness_workspace_changes/__init__.py +6 -0
- pyxis_harness_workspace_changes-0.1.0rc1/pyxis_harness_workspace_changes/git.py +61 -0
- pyxis_harness_workspace_changes-0.1.0rc1/pyxis_harness_workspace_changes/service.py +251 -0
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
# Python
|
|
2
|
+
__pycache__/
|
|
3
|
+
*.py[cod]
|
|
4
|
+
*.egg-info/
|
|
5
|
+
build/
|
|
6
|
+
dist/
|
|
7
|
+
|
|
8
|
+
# Environments
|
|
9
|
+
.venv/
|
|
10
|
+
.env
|
|
11
|
+
|
|
12
|
+
# Tooling
|
|
13
|
+
.pytest_cache/
|
|
14
|
+
.coverage
|
|
15
|
+
htmlcov/
|
|
16
|
+
.idea/
|
|
17
|
+
.vscode/
|
|
18
|
+
.DS_Store
|
|
19
|
+
|
|
20
|
+
# Local harness state
|
|
21
|
+
.pyharness/
|
|
22
|
+
*.sqlite
|
|
23
|
+
*.sqlite-*
|
|
24
|
+
|
|
25
|
+
# Claude desktop app
|
|
26
|
+
.claude/
|
|
27
|
+
/manual/*.pdf
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
# pyxis-harness-workspace-changes
|
|
2
|
+
|
|
3
|
+
每一轮改动了哪些文件:来自 git 工作树快照。
|
|
4
|
+
|
|
5
|
+
| 项 | 值 |
|
|
6
|
+
|---|---|
|
|
7
|
+
| 条目 | `workspace-changes`(`base` bundle) |
|
|
8
|
+
| 服务 | `WorkspaceChangesService`,`ctx.workspaceChanges` |
|
|
9
|
+
| 注入 | `agents`、`workspace`、`store` |
|
|
10
|
+
| 数据 | 摘要:`ctx.store`;diff:仅在本进程内 |
|
|
11
|
+
|
|
12
|
+
## 文件
|
|
13
|
+
|
|
14
|
+
| 文件 | 内容 |
|
|
15
|
+
|---|---|
|
|
16
|
+
| `__init__.py` | 导出 |
|
|
17
|
+
| `service.py` | `WorkspaceChangesService`、`Config`、store 命名空间:每轮的工作树快照、存储的摘要、diff |
|
|
18
|
+
| `git.py` | `Repo`、`GitError`、`parse_unified` |
|
|
19
|
+
|
|
20
|
+
## 事件
|
|
21
|
+
|
|
22
|
+
| 时机 | 工作 |
|
|
23
|
+
|---|---|
|
|
24
|
+
| `agent/turn-start` | 把会话工作区的工作树快照进私有对象目录(tree id) |
|
|
25
|
+
| `agent/turn-end` | 第二次快照;两者之间 `diff-tree` → 摘要;写入 `turn.extras["changes"]` |
|
|
26
|
+
|
|
27
|
+
## 服务
|
|
28
|
+
|
|
29
|
+
| 成员 | 契约 |
|
|
30
|
+
|---|---|
|
|
31
|
+
| `summaries(session_id)` | 会话中改动过文件的各轮的摘要,从旧到新(已存储) |
|
|
32
|
+
| `summary(session_id, run_id)` | 一份摘要,或 `None` |
|
|
33
|
+
| `diff(session_id, run_id, index)` | 所列文件的 hunk;重启后 `available: False` |
|
|
34
|
+
|
|
35
|
+
`available: False`:记录该 diff 的进程已不存在。
|
|
36
|
+
|
|
37
|
+
## 摘要
|
|
38
|
+
|
|
39
|
+
```
|
|
40
|
+
{run_id, session_id, seq, at, after, workspace, repo,
|
|
41
|
+
files: [{path, display, status, added, deleted, binary}],
|
|
42
|
+
total, added, deleted}
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
| 字段 | 含义 |
|
|
46
|
+
|---|---|
|
|
47
|
+
| `path` | 相对仓库 |
|
|
48
|
+
| `display` | 相对工作区根;在其之上为 `../x` |
|
|
49
|
+
| `after` | 该轮结束时会话的消息数;Web UI 放置卡片的位置 |
|
|
50
|
+
|
|
51
|
+
## 快照
|
|
52
|
+
|
|
53
|
+
| 项 | 契约 |
|
|
54
|
+
|---|---|
|
|
55
|
+
| 仓库 | 不被改动 |
|
|
56
|
+
| tree 的存放 | 仓库 index 的副本 + 私有对象目录(`GIT_OBJECT_DIRECTORY`);仓库的对象作为只读 alternate |
|
|
57
|
+
| index 的副本 | 保留原文件的修改时间:git 据此重读与 index 同一秒内修改的文件 |
|
|
58
|
+
| `.gitignore` | 生效;被忽略的文件不列出 |
|
|
59
|
+
| 工作区不在 git 仓库内 | 无摘要 |
|
|
60
|
+
| 该轮没有改动 | 无摘要 |
|
|
61
|
+
| diff | 仅在本进程运行期间存在 |
|
|
62
|
+
| 摘要 | 持久化在 `ctx.store` |
|
|
63
|
+
|
|
64
|
+
## `git.py`
|
|
65
|
+
|
|
66
|
+
| 名称 | 契约 |
|
|
67
|
+
|---|---|
|
|
68
|
+
| `Repo` | `top`(工作树)、`objects`(对象目录)、`index`(index 文件) |
|
|
69
|
+
| `GitError` | 一条 git 命令失败或超时 |
|
|
70
|
+
| `parse_unified` | unified diff 的 hunk |
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Onenightcarnival
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: pyxis-harness-workspace-changes
|
|
3
|
+
Version: 0.1.0rc1
|
|
4
|
+
Summary: PyxisHarness plugin: files changed per turn, from git work-tree snapshots
|
|
5
|
+
Project-URL: Homepage, https://github.com/Onenightcarnival/pyharness
|
|
6
|
+
Project-URL: Repository, https://github.com/Onenightcarnival/pyharness
|
|
7
|
+
Project-URL: Issues, https://github.com/Onenightcarnival/pyharness/issues
|
|
8
|
+
Project-URL: Documentation, https://github.com/Onenightcarnival/pyharness/tree/main/packages/workspace-changes
|
|
9
|
+
Author: Onenightcarnival
|
|
10
|
+
License-Expression: MIT
|
|
11
|
+
Keywords: agent,deepagents,harness,langgraph,llm,plugin
|
|
12
|
+
Classifier: Development Status :: 3 - Alpha
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
17
|
+
Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
|
|
18
|
+
Requires-Python: >=3.12
|
|
19
|
+
Requires-Dist: pyxis-harness-agent==0.1.0rc1
|
|
20
|
+
Requires-Dist: pyxis-harness-core==0.1.0rc1
|
|
21
|
+
Requires-Dist: pyxis-harness-workspace==0.1.0rc1
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
|
|
24
|
+
# pyxis-harness-workspace-changes
|
|
25
|
+
|
|
26
|
+
每一轮改动了哪些文件:来自 git 工作树快照。
|
|
27
|
+
|
|
28
|
+
| 项 | 值 |
|
|
29
|
+
|---|---|
|
|
30
|
+
| 条目 | `workspace-changes`(`base` bundle) |
|
|
31
|
+
| 服务 | `WorkspaceChangesService`,`ctx.workspaceChanges` |
|
|
32
|
+
| 注入 | `agents`、`workspace`、`store` |
|
|
33
|
+
| 数据 | 摘要:`ctx.store`;diff:仅在本进程内 |
|
|
34
|
+
|
|
35
|
+
## 文件
|
|
36
|
+
|
|
37
|
+
| 文件 | 内容 |
|
|
38
|
+
|---|---|
|
|
39
|
+
| `__init__.py` | 导出 |
|
|
40
|
+
| `service.py` | `WorkspaceChangesService`、`Config`、store 命名空间:每轮的工作树快照、存储的摘要、diff |
|
|
41
|
+
| `git.py` | `Repo`、`GitError`、`parse_unified` |
|
|
42
|
+
|
|
43
|
+
## 事件
|
|
44
|
+
|
|
45
|
+
| 时机 | 工作 |
|
|
46
|
+
|---|---|
|
|
47
|
+
| `agent/turn-start` | 把会话工作区的工作树快照进私有对象目录(tree id) |
|
|
48
|
+
| `agent/turn-end` | 第二次快照;两者之间 `diff-tree` → 摘要;写入 `turn.extras["changes"]` |
|
|
49
|
+
|
|
50
|
+
## 服务
|
|
51
|
+
|
|
52
|
+
| 成员 | 契约 |
|
|
53
|
+
|---|---|
|
|
54
|
+
| `summaries(session_id)` | 会话中改动过文件的各轮的摘要,从旧到新(已存储) |
|
|
55
|
+
| `summary(session_id, run_id)` | 一份摘要,或 `None` |
|
|
56
|
+
| `diff(session_id, run_id, index)` | 所列文件的 hunk;重启后 `available: False` |
|
|
57
|
+
|
|
58
|
+
`available: False`:记录该 diff 的进程已不存在。
|
|
59
|
+
|
|
60
|
+
## 摘要
|
|
61
|
+
|
|
62
|
+
```
|
|
63
|
+
{run_id, session_id, seq, at, after, workspace, repo,
|
|
64
|
+
files: [{path, display, status, added, deleted, binary}],
|
|
65
|
+
total, added, deleted}
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
| 字段 | 含义 |
|
|
69
|
+
|---|---|
|
|
70
|
+
| `path` | 相对仓库 |
|
|
71
|
+
| `display` | 相对工作区根;在其之上为 `../x` |
|
|
72
|
+
| `after` | 该轮结束时会话的消息数;Web UI 放置卡片的位置 |
|
|
73
|
+
|
|
74
|
+
## 快照
|
|
75
|
+
|
|
76
|
+
| 项 | 契约 |
|
|
77
|
+
|---|---|
|
|
78
|
+
| 仓库 | 不被改动 |
|
|
79
|
+
| tree 的存放 | 仓库 index 的副本 + 私有对象目录(`GIT_OBJECT_DIRECTORY`);仓库的对象作为只读 alternate |
|
|
80
|
+
| index 的副本 | 保留原文件的修改时间:git 据此重读与 index 同一秒内修改的文件 |
|
|
81
|
+
| `.gitignore` | 生效;被忽略的文件不列出 |
|
|
82
|
+
| 工作区不在 git 仓库内 | 无摘要 |
|
|
83
|
+
| 该轮没有改动 | 无摘要 |
|
|
84
|
+
| diff | 仅在本进程运行期间存在 |
|
|
85
|
+
| 摘要 | 持久化在 `ctx.store` |
|
|
86
|
+
|
|
87
|
+
## `git.py`
|
|
88
|
+
|
|
89
|
+
| 名称 | 契约 |
|
|
90
|
+
|---|---|
|
|
91
|
+
| `Repo` | `top`(工作树)、`objects`(对象目录)、`index`(index 文件) |
|
|
92
|
+
| `GitError` | 一条 git 命令失败或超时 |
|
|
93
|
+
| `parse_unified` | unified diff 的 hunk |
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "pyxis-harness-workspace-changes"
|
|
3
|
+
version = "0.1.0rc1"
|
|
4
|
+
description = "PyxisHarness plugin: files changed per turn, from git work-tree snapshots"
|
|
5
|
+
license = "MIT"
|
|
6
|
+
requires-python = ">=3.12"
|
|
7
|
+
readme = "AGENTS.md"
|
|
8
|
+
authors = [{ name = "Onenightcarnival" }]
|
|
9
|
+
keywords = ["agent", "llm", "harness", "plugin", "langgraph", "deepagents"]
|
|
10
|
+
classifiers = [
|
|
11
|
+
"Development Status :: 3 - Alpha",
|
|
12
|
+
"Intended Audience :: Developers",
|
|
13
|
+
"Programming Language :: Python :: 3",
|
|
14
|
+
"Programming Language :: Python :: 3.12",
|
|
15
|
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
|
16
|
+
"Topic :: Software Development :: Libraries :: Application Frameworks",
|
|
17
|
+
]
|
|
18
|
+
dependencies = ["pyxis-harness-core==0.1.0rc1", "pyxis-harness-agent==0.1.0rc1", "pyxis-harness-workspace==0.1.0rc1"]
|
|
19
|
+
|
|
20
|
+
[project.entry-points."pyxis_harness.plugins"]
|
|
21
|
+
pyxis-harness-workspace-changes = "pyxis_harness_workspace_changes:WorkspaceChangesService"
|
|
22
|
+
|
|
23
|
+
[project.urls]
|
|
24
|
+
Homepage = "https://github.com/Onenightcarnival/pyharness"
|
|
25
|
+
Repository = "https://github.com/Onenightcarnival/pyharness"
|
|
26
|
+
Issues = "https://github.com/Onenightcarnival/pyharness/issues"
|
|
27
|
+
Documentation = "https://github.com/Onenightcarnival/pyharness/tree/main/packages/workspace-changes"
|
|
28
|
+
|
|
29
|
+
[build-system]
|
|
30
|
+
requires = ["hatchling"]
|
|
31
|
+
build-backend = "hatchling.build"
|
|
32
|
+
|
|
33
|
+
[tool.hatch.build.targets.wheel]
|
|
34
|
+
packages = ["pyxis_harness_workspace_changes"]
|
|
35
|
+
|
|
36
|
+
[tool.hatch.build.targets.wheel.force-include]
|
|
37
|
+
"AGENTS.md" = "pyxis_harness_workspace_changes/AGENTS.md"
|
|
38
|
+
|
|
39
|
+
[tool.hatch.build.targets.sdist.force-include]
|
|
40
|
+
"../../LICENSE" = "LICENSE"
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class GitError(RuntimeError):
|
|
8
|
+
pass
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class Repo:
|
|
12
|
+
def __init__(self, top: Path, objects: Path, index: Path) -> None:
|
|
13
|
+
self.top = top
|
|
14
|
+
self.objects = objects
|
|
15
|
+
self.index = index
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _resolve_git_path(top: Path, value: str) -> Path:
|
|
19
|
+
path = Path(value)
|
|
20
|
+
return path if path.is_absolute() else (top / path).resolve()
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def parse_unified(text: str) -> list[dict[str, Any]]:
|
|
24
|
+
"""
|
|
25
|
+
Hunks of a unified diff: ``{old_start, new_start, header, lines: [{kind, old, new, text}]}``;
|
|
26
|
+
``kind`` is ctx/add/del.
|
|
27
|
+
"""
|
|
28
|
+
hunks: list[dict[str, Any]] = []
|
|
29
|
+
hunk: dict[str, Any] | None = None
|
|
30
|
+
old = new = 0
|
|
31
|
+
rows = text.split("\n")
|
|
32
|
+
if rows and rows[-1] == "":
|
|
33
|
+
rows.pop()
|
|
34
|
+
for line in rows:
|
|
35
|
+
if line.startswith("@@"):
|
|
36
|
+
try:
|
|
37
|
+
ranges = line.split("@@")[1].strip().split(" ")
|
|
38
|
+
old = int(ranges[0].lstrip("-").split(",")[0])
|
|
39
|
+
new = int(ranges[1].lstrip("+").split(",")[0])
|
|
40
|
+
except (IndexError, ValueError):
|
|
41
|
+
old = new = 0
|
|
42
|
+
hunk = {"old_start": old, "new_start": new, "header": line, "lines": []}
|
|
43
|
+
hunks.append(hunk)
|
|
44
|
+
continue
|
|
45
|
+
if hunk is None:
|
|
46
|
+
continue
|
|
47
|
+
if line.startswith("\\"):
|
|
48
|
+
if hunk["lines"]:
|
|
49
|
+
hunk["lines"][-1]["no_newline"] = True
|
|
50
|
+
continue
|
|
51
|
+
if line.startswith("+"):
|
|
52
|
+
hunk["lines"].append({"kind": "add", "old": None, "new": new, "text": line[1:]})
|
|
53
|
+
new += 1
|
|
54
|
+
elif line.startswith("-"):
|
|
55
|
+
hunk["lines"].append({"kind": "del", "old": old, "new": None, "text": line[1:]})
|
|
56
|
+
old += 1
|
|
57
|
+
elif line.startswith(" "):
|
|
58
|
+
hunk["lines"].append({"kind": "ctx", "old": old, "new": new, "text": line[1:]})
|
|
59
|
+
old += 1
|
|
60
|
+
new += 1
|
|
61
|
+
return hunks
|
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import os
|
|
5
|
+
import shutil
|
|
6
|
+
import tempfile
|
|
7
|
+
import time
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any, ClassVar
|
|
10
|
+
|
|
11
|
+
from pydantic import BaseModel, Field
|
|
12
|
+
|
|
13
|
+
from pyxis_harness import Service
|
|
14
|
+
|
|
15
|
+
from .git import GitError, Repo, _resolve_git_path, parse_unified
|
|
16
|
+
|
|
17
|
+
NAMESPACE = ("pyharness", "changes")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class Config(BaseModel):
|
|
21
|
+
timeout_s: float = Field(
|
|
22
|
+
30.0, description="Seconds one git command may run; a slower one abandons the turn's record."
|
|
23
|
+
)
|
|
24
|
+
max_files: int = Field(500, description="Files listed per summary; `total` still counts all of them.")
|
|
25
|
+
context_lines: int = Field(3, description="Context lines around each hunk.")
|
|
26
|
+
max_diff_bytes: int = Field(2_000_000, description="Largest unified diff served for one file.")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class WorkspaceChangesService(Service):
|
|
30
|
+
"""Per-turn changed-file summaries and diffs."""
|
|
31
|
+
|
|
32
|
+
key = "workspaceChanges"
|
|
33
|
+
name = "pyxis-harness-workspace-changes"
|
|
34
|
+
inject: ClassVar[list[str]] = ["agents", "workspace", "store"]
|
|
35
|
+
Config = Config
|
|
36
|
+
|
|
37
|
+
def __init__(self, ctx: Any, config: Config) -> None:
|
|
38
|
+
super().__init__(ctx, config)
|
|
39
|
+
self._repos: dict[str, Repo | None] = {}
|
|
40
|
+
self._dirs: dict[str, Path] = {} # session id -> private git directory
|
|
41
|
+
self._turns: dict[str, dict[str, Any]] = {} # run id -> {repo, base, session}
|
|
42
|
+
self._trees: dict[tuple[str, str], tuple[Repo, str, str]] = {} # (session, run) -> (repo, base, head)
|
|
43
|
+
self._seq: dict[str, int] = {}
|
|
44
|
+
self._locks: dict[str, asyncio.Lock] = {}
|
|
45
|
+
|
|
46
|
+
async def start(self) -> None:
|
|
47
|
+
self.ctx.on("agent/turn-start", self._on_start)
|
|
48
|
+
self.ctx.on("agent/turn-end", self._on_end)
|
|
49
|
+
|
|
50
|
+
async def stop(self) -> None:
|
|
51
|
+
for path in self._dirs.values():
|
|
52
|
+
shutil.rmtree(path, ignore_errors=True)
|
|
53
|
+
self._dirs.clear()
|
|
54
|
+
self._trees.clear()
|
|
55
|
+
|
|
56
|
+
# ------------------------------------------------------------------ queries
|
|
57
|
+
async def summaries(self, session_id: str) -> list[dict[str, Any]]:
|
|
58
|
+
items = await self.ctx.store.asearch((*NAMESPACE, session_id), limit=1000)
|
|
59
|
+
return sorted((dict(i.value) for i in items), key=lambda s: s.get("seq", 0))
|
|
60
|
+
|
|
61
|
+
async def summary(self, session_id: str, run_id: str) -> dict[str, Any] | None:
|
|
62
|
+
item = await self.ctx.store.aget((*NAMESPACE, session_id), run_id)
|
|
63
|
+
return dict(item.value) if item is not None else None
|
|
64
|
+
|
|
65
|
+
async def diff(self, session_id: str, run_id: str, index: int) -> dict[str, Any]:
|
|
66
|
+
summary = await self.summary(session_id, run_id)
|
|
67
|
+
if summary is None:
|
|
68
|
+
raise LookupError(f"no changes recorded for run {run_id!r}")
|
|
69
|
+
if not 0 <= index < len(summary["files"]):
|
|
70
|
+
raise LookupError(f"no file {index} in the summary")
|
|
71
|
+
file = summary["files"][index]
|
|
72
|
+
head = {"path": file["path"], "display": file["display"], "status": file["status"], "binary": file["binary"]}
|
|
73
|
+
trees = self._trees.get((session_id, run_id))
|
|
74
|
+
if trees is None:
|
|
75
|
+
return {**head, "available": False, "hunks": []}
|
|
76
|
+
if file["binary"]:
|
|
77
|
+
return {**head, "available": True, "hunks": []}
|
|
78
|
+
repo, base, after = trees
|
|
79
|
+
out = await self._git(
|
|
80
|
+
repo,
|
|
81
|
+
"diff",
|
|
82
|
+
f"-U{self.config.context_lines}",
|
|
83
|
+
"--no-color",
|
|
84
|
+
"--no-ext-diff",
|
|
85
|
+
"--no-renames",
|
|
86
|
+
base,
|
|
87
|
+
after,
|
|
88
|
+
"--",
|
|
89
|
+
file["path"],
|
|
90
|
+
env=self._env(session_id, repo),
|
|
91
|
+
ok=(0, 1),
|
|
92
|
+
)
|
|
93
|
+
if len(out.encode("utf-8", "replace")) > self.config.max_diff_bytes:
|
|
94
|
+
return {**head, "available": True, "oversized": True, "hunks": []}
|
|
95
|
+
return {**head, "available": True, "hunks": parse_unified(out)}
|
|
96
|
+
|
|
97
|
+
# ------------------------------------------------------------------ turns
|
|
98
|
+
async def _on_start(self, turn: Any) -> None:
|
|
99
|
+
try:
|
|
100
|
+
record = await self.ctx.agents.get_session(turn.session_id)
|
|
101
|
+
repo = await self._repo_for((record or {}).get("workspace"))
|
|
102
|
+
if repo is None:
|
|
103
|
+
return
|
|
104
|
+
async with self._lock(turn.session_id):
|
|
105
|
+
base = await self._snapshot(turn.session_id, repo)
|
|
106
|
+
self._turns[turn.run_id] = {
|
|
107
|
+
"repo": repo,
|
|
108
|
+
"base": base,
|
|
109
|
+
"session": turn.session_id,
|
|
110
|
+
"workspace": self._workspace_root((record or {}).get("workspace")),
|
|
111
|
+
}
|
|
112
|
+
except Exception as exc: # noqa: BLE001 - never break the turn
|
|
113
|
+
self.ctx.logger.warning("workspace changes: baseline skipped for %s: %s", turn.session_id, exc)
|
|
114
|
+
|
|
115
|
+
async def _on_end(self, turn: Any) -> None:
|
|
116
|
+
info = self._turns.pop(turn.run_id, None)
|
|
117
|
+
if info is None:
|
|
118
|
+
return
|
|
119
|
+
try:
|
|
120
|
+
repo: Repo = info["repo"]
|
|
121
|
+
async with self._lock(turn.session_id):
|
|
122
|
+
head = await self._snapshot(turn.session_id, repo)
|
|
123
|
+
if head == info["base"]:
|
|
124
|
+
return
|
|
125
|
+
files = await self._changed_files(turn.session_id, repo, info["base"], head, info["workspace"])
|
|
126
|
+
if not files:
|
|
127
|
+
return
|
|
128
|
+
seq = self._seq.get(turn.session_id, len(await self.summaries(turn.session_id))) + 1
|
|
129
|
+
self._seq[turn.session_id] = seq
|
|
130
|
+
messages = await self.ctx.agents.messages(turn.session_id)
|
|
131
|
+
summary = {
|
|
132
|
+
"run_id": turn.run_id,
|
|
133
|
+
"session_id": turn.session_id,
|
|
134
|
+
"seq": seq,
|
|
135
|
+
"at": time.time(),
|
|
136
|
+
"after": len(messages),
|
|
137
|
+
"workspace": str(info["workspace"]),
|
|
138
|
+
"repo": str(repo.top),
|
|
139
|
+
"files": files[: self.config.max_files],
|
|
140
|
+
"total": len(files),
|
|
141
|
+
"added": sum(f["added"] or 0 for f in files),
|
|
142
|
+
"deleted": sum(f["deleted"] or 0 for f in files),
|
|
143
|
+
}
|
|
144
|
+
self._trees[(turn.session_id, turn.run_id)] = (repo, info["base"], head)
|
|
145
|
+
await self.ctx.store.aput((*NAMESPACE, turn.session_id), turn.run_id, summary)
|
|
146
|
+
turn.extras["changes"] = summary
|
|
147
|
+
except Exception as exc: # noqa: BLE001
|
|
148
|
+
self.ctx.logger.warning("workspace changes: record skipped for %s: %s", turn.session_id, exc)
|
|
149
|
+
|
|
150
|
+
# ------------------------------------------------------------------ git
|
|
151
|
+
def _workspace_root(self, workspace: str | None) -> Path:
|
|
152
|
+
return Path(self.ctx.workspace.open(workspace).root)
|
|
153
|
+
|
|
154
|
+
async def _repo_for(self, workspace: str | None) -> Repo | None:
|
|
155
|
+
root = self._workspace_root(workspace)
|
|
156
|
+
key = str(root)
|
|
157
|
+
if key not in self._repos:
|
|
158
|
+
try:
|
|
159
|
+
out = await self._run(
|
|
160
|
+
["git", "rev-parse", "--show-toplevel", "--git-path", "objects", "--git-path", "index"],
|
|
161
|
+
cwd=root,
|
|
162
|
+
env=self._base_env(),
|
|
163
|
+
)
|
|
164
|
+
top, objects, index = (line.strip() for line in out.strip().splitlines()[:3])
|
|
165
|
+
top_path = Path(top)
|
|
166
|
+
self._repos[key] = Repo(
|
|
167
|
+
top_path, _resolve_git_path(top_path, objects), _resolve_git_path(top_path, index)
|
|
168
|
+
)
|
|
169
|
+
except Exception: # noqa: BLE001 - not a repository, or no git
|
|
170
|
+
self._repos[key] = None
|
|
171
|
+
return self._repos[key]
|
|
172
|
+
|
|
173
|
+
def _lock(self, session_id: str) -> asyncio.Lock:
|
|
174
|
+
return self._locks.setdefault(session_id, asyncio.Lock())
|
|
175
|
+
|
|
176
|
+
def _dir(self, session_id: str) -> Path:
|
|
177
|
+
if session_id not in self._dirs:
|
|
178
|
+
self._dirs[session_id] = Path(tempfile.mkdtemp(prefix="pyh-changes-"))
|
|
179
|
+
(self._dirs[session_id] / "objects").mkdir()
|
|
180
|
+
return self._dirs[session_id]
|
|
181
|
+
|
|
182
|
+
def _base_env(self) -> dict[str, str]:
|
|
183
|
+
env = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")}
|
|
184
|
+
env.update({"GIT_TERMINAL_PROMPT": "0", "GIT_OPTIONAL_LOCKS": "0", "LC_ALL": "C"})
|
|
185
|
+
return env
|
|
186
|
+
|
|
187
|
+
def _env(self, session_id: str, repo: Repo) -> dict[str, str]:
|
|
188
|
+
private = self._dir(session_id)
|
|
189
|
+
return {
|
|
190
|
+
**self._base_env(),
|
|
191
|
+
"GIT_INDEX_FILE": str(private / "index"),
|
|
192
|
+
"GIT_OBJECT_DIRECTORY": str(private / "objects"),
|
|
193
|
+
"GIT_ALTERNATE_OBJECT_DIRECTORIES": str(repo.objects),
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
async def _snapshot(self, session_id: str, repo: Repo) -> str:
|
|
197
|
+
private = self._dir(session_id)
|
|
198
|
+
if repo.index.exists():
|
|
199
|
+
# With its timestamp: git re-reads a file modified in the second its index was written.
|
|
200
|
+
shutil.copy2(repo.index, private / "index")
|
|
201
|
+
else:
|
|
202
|
+
(private / "index").unlink(missing_ok=True)
|
|
203
|
+
env = self._env(session_id, repo)
|
|
204
|
+
await self._git(repo, "add", "--all", "--ignore-errors", env=env, ok=(0, 1))
|
|
205
|
+
return (await self._git(repo, "write-tree", env=env)).strip()
|
|
206
|
+
|
|
207
|
+
async def _changed_files(
|
|
208
|
+
self, session_id: str, repo: Repo, base: str, head: str, workspace: Path
|
|
209
|
+
) -> list[dict[str, Any]]:
|
|
210
|
+
env = self._env(session_id, repo)
|
|
211
|
+
numstat = await self._git(repo, "diff-tree", "-r", "--no-renames", "--numstat", "-z", base, head, env=env)
|
|
212
|
+
status = await self._git(repo, "diff-tree", "-r", "--no-renames", "--name-status", "-z", base, head, env=env)
|
|
213
|
+
statuses: dict[str, str] = {}
|
|
214
|
+
parts = status.split("\0")
|
|
215
|
+
for i in range(0, len(parts) - 1, 2):
|
|
216
|
+
statuses[parts[i + 1]] = parts[i][:1]
|
|
217
|
+
files = []
|
|
218
|
+
for rec in numstat.split("\0"):
|
|
219
|
+
if not rec:
|
|
220
|
+
continue
|
|
221
|
+
added, deleted, path = rec.split("\t", 2)
|
|
222
|
+
binary = added == "-"
|
|
223
|
+
display = os.path.relpath(repo.top / path, workspace)
|
|
224
|
+
files.append(
|
|
225
|
+
{
|
|
226
|
+
"path": path,
|
|
227
|
+
"display": display.replace(os.sep, "/"),
|
|
228
|
+
"status": statuses.get(path, "M"),
|
|
229
|
+
"added": None if binary else int(added),
|
|
230
|
+
"deleted": None if binary else int(deleted),
|
|
231
|
+
"binary": binary,
|
|
232
|
+
}
|
|
233
|
+
)
|
|
234
|
+
files.sort(key=lambda f: f["display"])
|
|
235
|
+
return files
|
|
236
|
+
|
|
237
|
+
async def _git(self, repo: Repo, *args: str, env: dict[str, str], ok: tuple[int, ...] = (0,)) -> str:
|
|
238
|
+
return await self._run(["git", *args], cwd=repo.top, env=env, ok=ok)
|
|
239
|
+
|
|
240
|
+
async def _run(self, argv: list[str], *, cwd: Path, env: dict[str, str], ok: tuple[int, ...] = (0,)) -> str:
|
|
241
|
+
proc = await asyncio.create_subprocess_exec(
|
|
242
|
+
*argv, cwd=str(cwd), env=env, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE
|
|
243
|
+
)
|
|
244
|
+
try:
|
|
245
|
+
out, err = await asyncio.wait_for(proc.communicate(), self.config.timeout_s)
|
|
246
|
+
except TimeoutError:
|
|
247
|
+
proc.kill()
|
|
248
|
+
raise GitError(f"{' '.join(argv[:2])} timed out") from None
|
|
249
|
+
if proc.returncode not in ok:
|
|
250
|
+
raise GitError(err.decode("utf-8", "replace").strip() or f"{argv[1]} failed ({proc.returncode})")
|
|
251
|
+
return out.decode("utf-8", "replace")
|