@giamme/forge 0.19.0 → 0.21.0
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.
- package/CHANGELOG.md +32 -0
- package/README.md +7 -0
- package/SKILL.md +3 -0
- package/VERSION +1 -1
- package/docs/README.md +1 -0
- package/docs/commands.md +137 -5
- package/docs/development.md +1 -1
- package/docs/forge-ui.md +70 -19
- package/forge +8 -2
- package/package.json +1 -1
- package/references/decompose.md +20 -8
- package/references/memory.md +30 -5
- package/scripts/forge-config.py +10 -9
- package/scripts/forge-control.py +51 -35
- package/scripts/forge-findings.py +675 -0
- package/scripts/forge-group.py +2 -1
- package/scripts/forge-guard.py +71 -33
- package/scripts/forge-handoff.py +14 -17
- package/scripts/forge-issues.py +233 -99
- package/scripts/forge-memory.sh +471 -19
- package/scripts/forge-parallel.sh +24 -14
- package/scripts/forge-planner.py +28 -2
- package/scripts/forge-pre-review.py +11 -4
- package/scripts/forge-ripwire.py +68 -22
- package/scripts/forge-route.py +10 -3
- package/scripts/forge-runs-compact.py +3 -2
- package/scripts/forge-runs-rm.py +14 -14
- package/scripts/forge-runtime.py +36 -19
- package/scripts/forge-schedule.py +135 -62
- package/scripts/forge-shadow.py +16 -9
- package/scripts/forge-summarize.py +7 -3
- package/scripts/forge-sweep.py +206 -46
- package/scripts/forge-ui.py +8 -13
- package/scripts/forge-verify.py +29 -23
- package/scripts/forge_brief/__init__.py +1 -1
- package/scripts/forge_brief/proposals.py +7 -2
- package/scripts/forge_decide/budget.py +6 -1
- package/scripts/forge_decide/replay.py +6 -1
- package/scripts/forge_findings/__init__.py +17 -0
- package/scripts/forge_findings/apply.py +442 -0
- package/scripts/forge_findings/status.py +43 -0
- package/scripts/forge_findings/store.py +595 -0
- package/scripts/forge_findings/tags.py +53 -0
- package/scripts/forge_findings/triage.py +594 -0
- package/scripts/forge_flock.py +87 -0
- package/scripts/forge_fractal/__init__.py +7 -3
- package/scripts/forge_fractal/cli.py +7 -2
- package/scripts/forge_fractal/execution.py +14 -14
- package/scripts/forge_fractal/invocation.py +3 -2
- package/scripts/forge_fractal/pipeline.py +2 -1
- package/scripts/forge_fractal/selection.py +2 -1
- package/scripts/forge_identity.py +328 -0
- package/scripts/forge_locations.py +14 -4
- package/scripts/forge_memory_list.py +7 -3
- package/scripts/forge_posix.py +108 -0
- package/scripts/forge_proc.py +399 -0
- package/scripts/forge_registry.py +15 -6
- package/scripts/forge_retro/__init__.py +8 -2
- package/scripts/forge_retro/issues.py +2 -1
- package/scripts/forge_side/__init__.py +232 -38
- package/scripts/forge_storage.py +11 -1
- package/ui/docs/api.md +130 -12
- package/ui/forge_ui/control.py +693 -17
- package/ui/forge_ui/export.py +1 -1
- package/ui/forge_ui/projects.py +209 -22
- package/ui/forge_ui/reader.py +18 -17
- package/ui/forge_ui/server.py +10 -1
- package/ui/forge_ui/static/findingsactions.js +201 -0
- package/ui/forge_ui/static/index.html +2 -0
- package/ui/forge_ui/static/projectsview.js +600 -45
- package/ui/forge_ui/static/style.css +59 -0
- package/ui/forge_ui/static/triageview.js +423 -0
|
@@ -2,15 +2,19 @@
|
|
|
2
2
|
from __future__ import annotations
|
|
3
3
|
|
|
4
4
|
import contextlib
|
|
5
|
-
import fcntl
|
|
6
5
|
import importlib.util
|
|
7
6
|
import json
|
|
8
7
|
import os
|
|
9
8
|
from pathlib import Path
|
|
10
9
|
import re
|
|
11
10
|
import subprocess
|
|
11
|
+
import sys
|
|
12
12
|
|
|
13
13
|
SCRIPTS = Path(__file__).resolve().parents[1]
|
|
14
|
+
if str(SCRIPTS) not in sys.path:
|
|
15
|
+
sys.path.insert(0, str(SCRIPTS))
|
|
16
|
+
import forge_flock as fcntl # noqa: E402
|
|
17
|
+
import forge_proc # noqa: E402
|
|
14
18
|
REVISION = '18793200c0d7e8cdb2db369ea3abe5647a1e15e4'
|
|
15
19
|
VERSION = '1.2.0'
|
|
16
20
|
ARCHIVE_SHA256 = '3f7714ee0baec05af8d856db2b00d63398026fae2fcf50edbee542671126072c'
|
|
@@ -80,5 +84,5 @@ def command(argv: list, *, cwd: Path | None = None, timeout: float = 120, input:
|
|
|
80
84
|
|
|
81
85
|
|
|
82
86
|
def artifact(verb: str, *args: object) -> str:
|
|
83
|
-
return command(
|
|
84
|
-
|
|
87
|
+
return command(forge_proc.bash_cmd('-c', 'source "$1"; shift; "$@"', 'forge',
|
|
88
|
+
SCRIPTS / 'forge-artifact.sh', verb, *args)).decode().strip()
|
|
@@ -142,11 +142,16 @@ def internal(argv: list[str]) -> int:
|
|
|
142
142
|
remember(managed_run(Path(os.environ['FORGE_FRACTAL_RUN']).name), argv[1:])
|
|
143
143
|
return 0
|
|
144
144
|
if argv[0] == '_lock':
|
|
145
|
-
|
|
145
|
+
_scripts = str(Path(__file__).resolve().parents[1])
|
|
146
|
+
if _scripts not in sys.path:
|
|
147
|
+
sys.path.insert(0, _scripts)
|
|
148
|
+
import forge_flock as fcntl
|
|
149
|
+
import forge_proc
|
|
146
150
|
handle = (Path(argv[1]) / 'pipeline.lock').open('a')
|
|
147
151
|
fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
148
152
|
os.set_inheritable(handle.fileno(), True)
|
|
149
|
-
|
|
153
|
+
forge_proc.exec_or_exit(forge_proc.bash_cmd(*argv[2:]), env=dict(os.environ, FORGE_SOLO_LOCK=argv[1]),
|
|
154
|
+
inherit_fds=True)
|
|
150
155
|
raise ValueError('Unknown internal command')
|
|
151
156
|
|
|
152
157
|
|
|
@@ -22,6 +22,7 @@ import time
|
|
|
22
22
|
import uuid
|
|
23
23
|
|
|
24
24
|
from . import SCRIPTS, artifact, command, identifier, lock, managed_run, read_json, runtime_python, write_json
|
|
25
|
+
import forge_proc
|
|
25
26
|
|
|
26
27
|
PROTOCOL = '''
|
|
27
28
|
Forge owns coordination and independent QA. Implement and run requested checks.
|
|
@@ -64,17 +65,17 @@ def terminate(process: subprocess.Popen) -> None:
|
|
|
64
65
|
# Every managed invocation is its own session; never signal an arbitrary PID.
|
|
65
66
|
if process.poll() is not None:
|
|
66
67
|
return
|
|
67
|
-
|
|
68
|
-
os.killpg(process.pid, signal.SIGTERM)
|
|
68
|
+
forge_proc.kill_tree(process.pid, force=False)
|
|
69
69
|
try:
|
|
70
70
|
process.wait(timeout=2)
|
|
71
71
|
except subprocess.TimeoutExpired:
|
|
72
|
-
|
|
73
|
-
os.killpg(process.pid, signal.SIGKILL)
|
|
72
|
+
forge_proc.kill_tree(process.pid, force=True)
|
|
74
73
|
process.wait(timeout=2)
|
|
75
74
|
|
|
76
75
|
|
|
77
76
|
def process_identity(pid: int) -> str:
|
|
77
|
+
if forge_proc.IS_WINDOWS:
|
|
78
|
+
return forge_proc.process_start_time(pid) or ''
|
|
78
79
|
return subprocess.run(['ps', '-p', str(pid), '-o', 'lstart=,comm='], capture_output=True, text=True).stdout.strip()
|
|
79
80
|
|
|
80
81
|
|
|
@@ -83,8 +84,7 @@ def reap_recorded(task: Path) -> None:
|
|
|
83
84
|
recorded = read_json(path)
|
|
84
85
|
pid = recorded['pid']
|
|
85
86
|
if recorded['identity'] and process_identity(pid) == recorded['identity']:
|
|
86
|
-
|
|
87
|
-
os.killpg(pid, signal.SIGKILL)
|
|
87
|
+
forge_proc.kill_tree(pid, force=True)
|
|
88
88
|
|
|
89
89
|
|
|
90
90
|
@contextlib.contextmanager
|
|
@@ -111,9 +111,9 @@ def bridge(step: Path, prompt: Path, model: str) -> int:
|
|
|
111
111
|
role = config.get('role', 'dwarf')
|
|
112
112
|
if role not in ('dwarf', 'planner'):
|
|
113
113
|
raise ValueError('Unsupported Fractal bridge role')
|
|
114
|
-
argv =
|
|
115
|
-
|
|
116
|
-
|
|
114
|
+
argv = forge_proc.bash_cmd(SCRIPTS / 'forge-dispatch.sh', role, model,
|
|
115
|
+
'--repo', config['workspace'], '--run-dir', str(step), '--prompt-file', str(prompt),
|
|
116
|
+
'--timeout', str(max(1, math.ceil(config['remaining']))), '--output', 'summary')
|
|
117
117
|
if config['yolo'] and role == 'dwarf':
|
|
118
118
|
argv.append('--yolo')
|
|
119
119
|
# Stay in the bridge session so its entire descendant group is reapable.
|
|
@@ -460,7 +460,7 @@ def supervise(run: Path, task: Path) -> int:
|
|
|
460
460
|
limit = read_json(run / 'run.json')['limits']['deadline']
|
|
461
461
|
elapsed = read_json(task / 'state.json').get('elapsed', 0)
|
|
462
462
|
process = subprocess.Popen([str(runtime_python()), str(SCRIPTS / 'forge-fractal.py'),
|
|
463
|
-
'_worker', run.name, task.name],
|
|
463
|
+
'_worker', run.name, task.name], **forge_proc.popen_group_kwargs())
|
|
464
464
|
previous = time.monotonic()
|
|
465
465
|
try:
|
|
466
466
|
while process.poll() is None:
|
|
@@ -575,7 +575,7 @@ def dispatch(argv: list[str]) -> int:
|
|
|
575
575
|
|
|
576
576
|
def limited_dispatch(run: Path, argv: list[str]) -> int:
|
|
577
577
|
if argv[0] == 'doctor':
|
|
578
|
-
return subprocess.call(
|
|
578
|
+
return subprocess.call(forge_proc.bash_cmd(SCRIPTS / 'forge-dispatch.sh', *argv))
|
|
579
579
|
limit = read_json(run / 'run.json')['limits']['deadline']
|
|
580
580
|
output = Path(argv[argv.index('--run-dir') + 1])
|
|
581
581
|
review = Path(argv[argv.index('--repo') + 1])
|
|
@@ -632,13 +632,13 @@ def qa_dispatch(run: Path, task: Path, argv: list[str], limit: int) -> int:
|
|
|
632
632
|
if record.exists():
|
|
633
633
|
old = read_json(record)
|
|
634
634
|
if old['identity'] and process_identity(old['pid']) == old['identity']:
|
|
635
|
-
|
|
636
|
-
os.killpg(old['pid'], signal.SIGKILL)
|
|
635
|
+
forge_proc.kill_tree(old['pid'], force=True)
|
|
637
636
|
while True:
|
|
638
637
|
try:
|
|
639
638
|
with slot(run, check):
|
|
640
639
|
check()
|
|
641
|
-
process = subprocess.Popen(
|
|
640
|
+
process = subprocess.Popen(forge_proc.bash_cmd(SCRIPTS / 'forge-dispatch.sh', *argv),
|
|
641
|
+
**forge_proc.popen_group_kwargs())
|
|
642
642
|
write_json(record, dict(pid=process.pid, identity=process_identity(process.pid)))
|
|
643
643
|
try:
|
|
644
644
|
while process.poll() is None:
|
|
@@ -6,7 +6,8 @@ import threading
|
|
|
6
6
|
import time
|
|
7
7
|
import uuid
|
|
8
8
|
|
|
9
|
-
from . import read_json, write_json
|
|
9
|
+
from . import SCRIPTS, read_json, write_json
|
|
10
|
+
import forge_proc
|
|
10
11
|
|
|
11
12
|
|
|
12
13
|
def _dataset_step(task, node: dict, directory: Path, **values) -> None:
|
|
@@ -54,7 +55,7 @@ def run_step(tree, node: dict, workspace: Path, prompt: str, *, phase: str = 'im
|
|
|
54
55
|
cost = None
|
|
55
56
|
try:
|
|
56
57
|
with output.open('w') as stream:
|
|
57
|
-
process = agent.spawn(invocation,
|
|
58
|
+
process = agent.spawn(invocation, **forge_proc.popen_group_kwargs())
|
|
58
59
|
write_json(directory / 'process.json', dict(pid=process.pid, identity=process_identity(process.pid)))
|
|
59
60
|
def drain():
|
|
60
61
|
for line in process.stdout:
|
|
@@ -8,13 +8,14 @@ import subprocess
|
|
|
8
8
|
import time
|
|
9
9
|
|
|
10
10
|
from . import artifact, lock, read_json, write_json
|
|
11
|
+
import forge_proc
|
|
11
12
|
|
|
12
13
|
|
|
13
14
|
def remember(run: Path, argv: list[str]) -> None:
|
|
14
15
|
with lock(run / 'pipeline-record.lock'):
|
|
15
16
|
config = read_json(run / 'run.json')
|
|
16
17
|
if 'pipeline_argv' not in config:
|
|
17
|
-
config.update(pipeline_argv=
|
|
18
|
+
config.update(pipeline_argv=forge_proc.bash_cmd(*argv), pipeline_cwd=str(Path.cwd()))
|
|
18
19
|
write_json(run / 'run.json', config)
|
|
19
20
|
|
|
20
21
|
|
|
@@ -8,6 +8,7 @@ from pathlib import Path
|
|
|
8
8
|
import sys
|
|
9
9
|
|
|
10
10
|
from . import DEFAULTS, SCRIPTS, command, managed_run, read_json, state_root, write_json
|
|
11
|
+
import forge_proc
|
|
11
12
|
from .install import doctor, install
|
|
12
13
|
|
|
13
14
|
|
|
@@ -17,7 +18,7 @@ def resolve(spec: str, role: str, yolo: bool = False, dry: bool = False) -> dict
|
|
|
17
18
|
root = Path(tmp)
|
|
18
19
|
prompt = root / 'input'
|
|
19
20
|
prompt.write_text('Offline resolution')
|
|
20
|
-
argv =
|
|
21
|
+
argv = forge_proc.bash_cmd(SCRIPTS / 'forge-dispatch.sh')
|
|
21
22
|
if dry:
|
|
22
23
|
argv += [role, spec, '--run-dir', root, '--prompt-file', prompt, '--dry-run']
|
|
23
24
|
else:
|
|
@@ -0,0 +1,328 @@
|
|
|
1
|
+
"""Which repository a checkout or a run belongs to, and every checkout forge has seen of it.
|
|
2
|
+
|
|
3
|
+
The run registry and the dismissal store are keyed by the checkout path, so a run
|
|
4
|
+
started from a linked worktree is filed under that worktree. Once the worktree is
|
|
5
|
+
gone, that path no longer names the repository. This module answers for the
|
|
6
|
+
repository itself: the main working tree, the same identity key `forge_registry`
|
|
7
|
+
uses for that tree, the checkouts forge has recorded and the run dirs registered
|
|
8
|
+
under any of them.
|
|
9
|
+
|
|
10
|
+
It only reads. A missing path, an unreadable file and a git failure are unknown,
|
|
11
|
+
never an exception. `identity` and `checkouts` are cached per process.
|
|
12
|
+
"""
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import hashlib
|
|
16
|
+
import json
|
|
17
|
+
import os
|
|
18
|
+
import re
|
|
19
|
+
import stat
|
|
20
|
+
import subprocess
|
|
21
|
+
|
|
22
|
+
import forge_locations
|
|
23
|
+
import forge_posix
|
|
24
|
+
import forge_registry
|
|
25
|
+
|
|
26
|
+
# A file in <run>/tasks/<id>/ sits three directories under the run dir.
|
|
27
|
+
_RUN_DIR_WALK = 3
|
|
28
|
+
_REPO_READ_MAX = 64 * 1024
|
|
29
|
+
_REGISTRY_READ_MAX = 1 << 20
|
|
30
|
+
_GIT_TIMEOUT = 10
|
|
31
|
+
# Same shape as forge-issues.py github_slug.
|
|
32
|
+
_ORIGIN_SLUG = re.compile(r'github\.com[:/]([^/\s]+)/([^/\s]+?)(?:\.git)?/?$')
|
|
33
|
+
|
|
34
|
+
_identity_cache: dict = {}
|
|
35
|
+
_checkouts_cache: dict = {}
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def identity(path) -> dict | None:
|
|
39
|
+
"""`{"root", "git", "key", "checkout"}` for a checkout, a run dir, or a file inside a run dir.
|
|
40
|
+
|
|
41
|
+
None when `path` is neither an existing directory nor a run dir with a `repo` file.
|
|
42
|
+
"""
|
|
43
|
+
key = _cache_key(path)
|
|
44
|
+
if key is not None and key in _identity_cache:
|
|
45
|
+
return _copy(_identity_cache[key])
|
|
46
|
+
try:
|
|
47
|
+
result = _identity_uncached(path)
|
|
48
|
+
except Exception: # noqa: BLE001 -- a missing path or a git failure is unknown, not an error
|
|
49
|
+
result = _directory_fallback(path)
|
|
50
|
+
if key is not None:
|
|
51
|
+
_identity_cache[key] = result
|
|
52
|
+
return _copy(result)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def checkouts(ident) -> list[str]:
|
|
56
|
+
"""Every checkout of this repository forge has seen, root first, then sorted.
|
|
57
|
+
|
|
58
|
+
The root, the `checkout` and `root` of every locations entry for the same git dir
|
|
59
|
+
or the same root (gone entries included), and the checkout named by the `repo` file
|
|
60
|
+
of every run dir in those checkouts' registry files. Existing or not. Deduplicated
|
|
61
|
+
by realpath.
|
|
62
|
+
"""
|
|
63
|
+
try:
|
|
64
|
+
if not isinstance(ident, dict) or not isinstance(ident.get('root'), str) or not ident['root']:
|
|
65
|
+
return []
|
|
66
|
+
root = ident['root']
|
|
67
|
+
git = ident.get('git') if isinstance(ident.get('git'), str) else None
|
|
68
|
+
cache_key = (_safe_real(root), git)
|
|
69
|
+
if cache_key in _checkouts_cache:
|
|
70
|
+
return list(_checkouts_cache[cache_key])
|
|
71
|
+
result = _checkouts_uncached(root, git)
|
|
72
|
+
_checkouts_cache[cache_key] = result
|
|
73
|
+
return list(result)
|
|
74
|
+
except Exception: # noqa: BLE001 -- an unreadable locations or registry file is unknown
|
|
75
|
+
return []
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def run_dirs(ident) -> list[str]:
|
|
79
|
+
"""Run dirs registered under any checkout of `ident`, existing directories, newest first."""
|
|
80
|
+
try:
|
|
81
|
+
found: dict[str, str] = {}
|
|
82
|
+
for checkout in checkouts(ident):
|
|
83
|
+
for line in _registry_lines(checkout):
|
|
84
|
+
if not os.path.isdir(line):
|
|
85
|
+
continue
|
|
86
|
+
real = _safe_real(line)
|
|
87
|
+
if real not in found and os.path.isdir(real):
|
|
88
|
+
found[real] = real
|
|
89
|
+
paths = list(found)
|
|
90
|
+
paths.sort(key=lambda item: (-_mtime(item), item))
|
|
91
|
+
return paths
|
|
92
|
+
except Exception: # noqa: BLE001 -- a missing registry is an empty list
|
|
93
|
+
return []
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def github_slug(ident) -> str | None:
|
|
97
|
+
"""`owner/repo` from `origin` of the first existing checkout, or None when none answers."""
|
|
98
|
+
try:
|
|
99
|
+
candidates = checkouts(ident)
|
|
100
|
+
except Exception: # noqa: BLE001
|
|
101
|
+
return None
|
|
102
|
+
for checkout in candidates:
|
|
103
|
+
try:
|
|
104
|
+
exists = bool(checkout) and os.path.isdir(checkout)
|
|
105
|
+
except OSError:
|
|
106
|
+
continue
|
|
107
|
+
if not exists:
|
|
108
|
+
continue
|
|
109
|
+
url = _origin(checkout)
|
|
110
|
+
if not url:
|
|
111
|
+
return None
|
|
112
|
+
match = _ORIGIN_SLUG.search(url.strip())
|
|
113
|
+
return f'{match.group(1)}/{match.group(2)}' if match else None
|
|
114
|
+
return None
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _identity_uncached(path) -> dict | None:
|
|
118
|
+
text = os.fspath(path)
|
|
119
|
+
found = _find_run(text)
|
|
120
|
+
if found is not None:
|
|
121
|
+
run_dir, checkout = found
|
|
122
|
+
if os.path.isdir(checkout):
|
|
123
|
+
return _live(checkout)
|
|
124
|
+
return _gone(run_dir, checkout)
|
|
125
|
+
if os.path.isdir(text):
|
|
126
|
+
return _live(text)
|
|
127
|
+
return None
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _directory_fallback(path) -> dict | None:
|
|
131
|
+
try:
|
|
132
|
+
text = os.fspath(path)
|
|
133
|
+
if os.path.isdir(text):
|
|
134
|
+
return _live(text)
|
|
135
|
+
except Exception: # noqa: BLE001
|
|
136
|
+
return None
|
|
137
|
+
return None
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _find_run(path: str) -> tuple[str, str] | None:
|
|
141
|
+
"""`(run dir, checkout path)` when `path` is a run dir, or a file at most three levels inside one."""
|
|
142
|
+
if os.path.isdir(path):
|
|
143
|
+
line = _first_line(os.path.join(path, 'repo'))
|
|
144
|
+
return (path, line) if line else None
|
|
145
|
+
current = os.path.dirname(os.path.abspath(path))
|
|
146
|
+
for _ in range(_RUN_DIR_WALK):
|
|
147
|
+
line = _first_line(os.path.join(current, 'repo'))
|
|
148
|
+
if line:
|
|
149
|
+
return current, line
|
|
150
|
+
parent = os.path.dirname(current)
|
|
151
|
+
if parent == current:
|
|
152
|
+
break
|
|
153
|
+
current = parent
|
|
154
|
+
return None
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _live(checkout: str) -> dict:
|
|
158
|
+
git, root = forge_locations.repository(checkout)
|
|
159
|
+
checkout_real = _safe_real(checkout)
|
|
160
|
+
if not root:
|
|
161
|
+
root = checkout_real
|
|
162
|
+
return {'root': root, 'git': git, 'key': _key(root), 'checkout': checkout_real}
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _gone(run_dir: str, checkout: str) -> dict:
|
|
166
|
+
# The checkout is gone, so git cannot be asked. repo.identity keeps the main
|
|
167
|
+
# working tree; without it the path recorded in `repo` is all forge still has.
|
|
168
|
+
root = _recorded_root(run_dir) or checkout
|
|
169
|
+
return {'root': root, 'git': None, 'key': _key(root), 'checkout': None}
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _checkouts_uncached(root: str, git: str | None) -> list[str]:
|
|
173
|
+
paths = [root]
|
|
174
|
+
for entry in forge_locations.entries(present=False):
|
|
175
|
+
if _matches(entry, git, root):
|
|
176
|
+
for name in ('checkout', 'root'):
|
|
177
|
+
value = entry.get(name)
|
|
178
|
+
if isinstance(value, str) and value:
|
|
179
|
+
paths.append(value)
|
|
180
|
+
# One pass over the checkouts already collected. A checkout that shows up only
|
|
181
|
+
# as a run's `repo` path is not itself scanned for further runs.
|
|
182
|
+
for checkout in list(paths):
|
|
183
|
+
for run_dir in _registry_lines(checkout):
|
|
184
|
+
recorded = _first_line(os.path.join(run_dir, 'repo'))
|
|
185
|
+
if recorded:
|
|
186
|
+
paths.append(recorded)
|
|
187
|
+
return _ordered(root, paths)
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _matches(entry: dict, git: str | None, root: str) -> bool:
|
|
191
|
+
entry_root = entry.get('root')
|
|
192
|
+
if isinstance(entry_root, str) and _same_path(entry_root, root):
|
|
193
|
+
return True
|
|
194
|
+
entry_git = entry.get('git')
|
|
195
|
+
return git is not None and isinstance(entry_git, str) and _same_path(entry_git, git)
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _ordered(root: str, paths: list[str]) -> list[str]:
|
|
199
|
+
seen = {_safe_real(root)}
|
|
200
|
+
extras = []
|
|
201
|
+
for path in paths:
|
|
202
|
+
if not isinstance(path, str) or not path:
|
|
203
|
+
continue
|
|
204
|
+
real = _safe_real(path)
|
|
205
|
+
if real in seen:
|
|
206
|
+
continue
|
|
207
|
+
seen.add(real)
|
|
208
|
+
extras.append(real)
|
|
209
|
+
extras.sort()
|
|
210
|
+
return [root, *extras]
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def _recorded_root(run_dir: str) -> str | None:
|
|
214
|
+
data = _read_bytes(os.path.join(run_dir, 'repo.identity'), _REPO_READ_MAX)
|
|
215
|
+
if not data:
|
|
216
|
+
return None
|
|
217
|
+
try:
|
|
218
|
+
parsed = json.loads(data.decode('utf-8', 'replace'))
|
|
219
|
+
except ValueError:
|
|
220
|
+
return None
|
|
221
|
+
if not isinstance(parsed, dict):
|
|
222
|
+
return None
|
|
223
|
+
recorded = parsed.get('root')
|
|
224
|
+
if not isinstance(recorded, str):
|
|
225
|
+
return None
|
|
226
|
+
return recorded or None
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def _registry_lines(checkout: str) -> list[str]:
|
|
230
|
+
try:
|
|
231
|
+
raw = _read_bytes(forge_registry.runs_registry(checkout), _REGISTRY_READ_MAX)
|
|
232
|
+
except (OSError, ValueError, RuntimeError, TypeError):
|
|
233
|
+
return []
|
|
234
|
+
if not raw:
|
|
235
|
+
return []
|
|
236
|
+
lines = []
|
|
237
|
+
for line in raw.decode('utf-8', 'replace').splitlines():
|
|
238
|
+
line = line.strip()
|
|
239
|
+
if line and not line.startswith('#'):
|
|
240
|
+
lines.append(line)
|
|
241
|
+
return lines
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def _first_line(path: str) -> str | None:
|
|
245
|
+
data = _read_bytes(path, _REPO_READ_MAX)
|
|
246
|
+
if not data:
|
|
247
|
+
return None
|
|
248
|
+
parts = data.splitlines()
|
|
249
|
+
if not parts:
|
|
250
|
+
return None
|
|
251
|
+
line = parts[0].decode('utf-8', 'replace').strip()
|
|
252
|
+
return line or None
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def _read_bytes(path, limit: int) -> bytes | None:
|
|
256
|
+
"""The start of a regular file. A FIFO, a directory or a missing path is unknown, and never blocks."""
|
|
257
|
+
try:
|
|
258
|
+
fd = os.open(os.fspath(path), os.O_RDONLY | forge_posix.O_NONBLOCK)
|
|
259
|
+
except OSError:
|
|
260
|
+
return None
|
|
261
|
+
try:
|
|
262
|
+
if not stat.S_ISREG(os.fstat(fd).st_mode):
|
|
263
|
+
return None
|
|
264
|
+
chunks = []
|
|
265
|
+
left = limit
|
|
266
|
+
while left > 0:
|
|
267
|
+
try:
|
|
268
|
+
block = os.read(fd, left)
|
|
269
|
+
except OSError:
|
|
270
|
+
return None
|
|
271
|
+
if not block:
|
|
272
|
+
break
|
|
273
|
+
chunks.append(block)
|
|
274
|
+
left -= len(block)
|
|
275
|
+
return b''.join(chunks)
|
|
276
|
+
finally:
|
|
277
|
+
os.close(fd)
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def _origin(checkout: str) -> str | None:
|
|
281
|
+
try:
|
|
282
|
+
env = {k: v for k, v in os.environ.items()
|
|
283
|
+
if not k.startswith('GIT_') or k in ('GIT_CONFIG_GLOBAL', 'GIT_CONFIG_NOSYSTEM')}
|
|
284
|
+
done = subprocess.run(
|
|
285
|
+
['git', '--no-optional-locks', '-C', os.fspath(checkout), 'remote', 'get-url', 'origin'],
|
|
286
|
+
capture_output=True, text=True, stdin=subprocess.DEVNULL, timeout=_GIT_TIMEOUT,
|
|
287
|
+
errors='replace', env=env)
|
|
288
|
+
except (OSError, ValueError, subprocess.SubprocessError):
|
|
289
|
+
return None
|
|
290
|
+
if done.returncode != 0:
|
|
291
|
+
return None
|
|
292
|
+
return done.stdout.strip() or None
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
def _key(root: str) -> str:
|
|
296
|
+
try:
|
|
297
|
+
return forge_registry.repo_key(root)
|
|
298
|
+
except (OSError, ValueError, RuntimeError, UnicodeError):
|
|
299
|
+
return hashlib.sha256(_safe_real(root).encode('utf-8', 'replace')).hexdigest()[:16]
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def _cache_key(path) -> str | None:
|
|
303
|
+
try:
|
|
304
|
+
return os.path.realpath(os.fspath(path))
|
|
305
|
+
except (OSError, ValueError, TypeError):
|
|
306
|
+
return None
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def _safe_real(path: str) -> str:
|
|
310
|
+
try:
|
|
311
|
+
return os.path.realpath(path)
|
|
312
|
+
except (OSError, ValueError, TypeError):
|
|
313
|
+
return path
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def _same_path(left: str, right: str) -> bool:
|
|
317
|
+
return left == right or _safe_real(left) == _safe_real(right)
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def _mtime(path: str) -> float:
|
|
321
|
+
try:
|
|
322
|
+
return os.stat(path).st_mtime
|
|
323
|
+
except OSError:
|
|
324
|
+
return 0.0
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
def _copy(result):
|
|
328
|
+
return None if result is None else dict(result)
|
|
@@ -34,7 +34,6 @@ from __future__ import annotations
|
|
|
34
34
|
|
|
35
35
|
import contextlib
|
|
36
36
|
import errno
|
|
37
|
-
import fcntl
|
|
38
37
|
import json
|
|
39
38
|
import os
|
|
40
39
|
from pathlib import Path
|
|
@@ -42,6 +41,12 @@ import subprocess
|
|
|
42
41
|
import sys
|
|
43
42
|
import time
|
|
44
43
|
|
|
44
|
+
_SCRIPTS = str(Path(__file__).resolve().parent)
|
|
45
|
+
if _SCRIPTS not in sys.path:
|
|
46
|
+
sys.path.insert(0, _SCRIPTS)
|
|
47
|
+
import forge_flock as fcntl # noqa: E402
|
|
48
|
+
import forge_posix # noqa: E402
|
|
49
|
+
|
|
45
50
|
VERSION = 1
|
|
46
51
|
LOCK_WAIT_S = 0.5
|
|
47
52
|
READ_MAX = 64 << 20
|
|
@@ -115,7 +120,8 @@ def _lock(wait_s):
|
|
|
115
120
|
"""The file's lock, tried for `wait_s`; yields whether it is held. Never raises."""
|
|
116
121
|
fd = None
|
|
117
122
|
try:
|
|
118
|
-
fd =
|
|
123
|
+
fd = forge_posix.open_nofollow(config_dir() / 'locations.lock',
|
|
124
|
+
os.O_RDWR | os.O_CREAT, 0o644)
|
|
119
125
|
deadline = time.monotonic() + wait_s
|
|
120
126
|
while True:
|
|
121
127
|
try:
|
|
@@ -141,7 +147,11 @@ def append(records: list[dict]) -> bool:
|
|
|
141
147
|
config_dir().mkdir(parents=True, exist_ok=True)
|
|
142
148
|
data = ''.join(json.dumps(dict(r, v=VERSION), sort_keys=True, separators=(',', ':')) + '\n' for r in records).encode()
|
|
143
149
|
with _lock(LOCK_WAIT_S):
|
|
144
|
-
fd =
|
|
150
|
+
fd = forge_posix.open_nofollow(
|
|
151
|
+
file_path(),
|
|
152
|
+
os.O_WRONLY | os.O_APPEND | os.O_CREAT | forge_posix.O_NONBLOCK | forge_posix.O_NOFOLLOW,
|
|
153
|
+
0o644,
|
|
154
|
+
)
|
|
145
155
|
try:
|
|
146
156
|
if not os.path.isfile(file_path()):
|
|
147
157
|
return False
|
|
@@ -204,7 +214,7 @@ def gone(kind, path, by='forge') -> bool:
|
|
|
204
214
|
|
|
205
215
|
def _first_line(path) -> str | None:
|
|
206
216
|
try:
|
|
207
|
-
fd = os.open(path, os.O_RDONLY |
|
|
217
|
+
fd = os.open(path, os.O_RDONLY | forge_posix.O_NONBLOCK)
|
|
208
218
|
with os.fdopen(fd, 'rb') as stream:
|
|
209
219
|
if not os.path.isfile(path):
|
|
210
220
|
return None
|
|
@@ -12,7 +12,8 @@ so the state shown is the one forge's bash decided, never a second implementatio
|
|
|
12
12
|
muted every row of it was marked not injectable (Jev's curation)
|
|
13
13
|
|
|
14
14
|
A learning is a (category, key) group, as rebuild groups the ledger: `count` is the number of distinct runs
|
|
15
|
-
it appeared in, `text` the latest wording. `
|
|
15
|
+
it appeared in, `text` the latest wording. `manual` is true when a person wrote any row of it (role
|
|
16
|
+
`person`); the field is absent otherwise. `memory` is the repo's current .forge/memory.md by section, with
|
|
16
17
|
the roles each section reaches; `rebuilt_differs` says the current file is not what a rebuild makes now (an
|
|
17
18
|
older forge wrote it, or a `prune` asked Jev to drop facts). Stdlib only.
|
|
18
19
|
"""
|
|
@@ -119,8 +120,11 @@ def classify(groups, rebuilt, drops):
|
|
|
119
120
|
else:
|
|
120
121
|
state = 'dropped' # not reached by today's rebuild; kept honest if it changes
|
|
121
122
|
rows = g['rows']
|
|
122
|
-
|
|
123
|
-
|
|
123
|
+
item = dict(category=cat, key=key, text=text, count=count, state=state,
|
|
124
|
+
first=min(r['ts'] for r in rows), last=max(r['ts'] for r in rows), rows=rows)
|
|
125
|
+
if any(r['role'] == 'person' for r in rows):
|
|
126
|
+
item['manual'] = True
|
|
127
|
+
out.append(item)
|
|
124
128
|
out.sort(key=lambda r: (r['last'], r['category'], r['key']), reverse=True)
|
|
125
129
|
return out
|
|
126
130
|
|