@giamme/forge 0.17.0 → 0.19.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.
Files changed (110) hide show
  1. package/CHANGELOG.md +57 -0
  2. package/README.md +1 -0
  3. package/SKILL.md +32 -5
  4. package/VERSION +1 -1
  5. package/docs/artifacts.md +33 -1
  6. package/docs/commands.md +147 -16
  7. package/docs/dataset.md +5 -0
  8. package/docs/decomposed-runs.md +122 -1
  9. package/docs/development.md +2 -1
  10. package/docs/forge-ui.md +98 -8
  11. package/docs/memory.md +27 -4
  12. package/docs/models.md +8 -0
  13. package/docs/reviews.md +122 -0
  14. package/docs/safety.md +8 -0
  15. package/forge +44 -4
  16. package/package.json +2 -1
  17. package/references/dataset.md +39 -1
  18. package/references/decompose.md +737 -16
  19. package/references/harnesses.md +18 -3
  20. package/references/planning.md +43 -14
  21. package/references/solo.md +2 -1
  22. package/references/ui.md +56 -6
  23. package/registry.tsv +8 -3
  24. package/scripts/forge-artifact.sh +14 -0
  25. package/scripts/forge-brief.py +217 -0
  26. package/scripts/forge-compare.py +13 -2
  27. package/scripts/forge-config.py +176 -9
  28. package/scripts/forge-contract.py +246 -28
  29. package/scripts/forge-control.py +200 -15
  30. package/scripts/forge-dispatch.sh +48 -15
  31. package/scripts/forge-du.py +167 -0
  32. package/scripts/forge-group.py +496 -0
  33. package/scripts/forge-groups.py +89 -0
  34. package/scripts/forge-handoff.py +1128 -0
  35. package/scripts/forge-lib-adopt.sh +1 -0
  36. package/scripts/forge-lib-group.sh +641 -0
  37. package/scripts/forge-lib-plans.sh +343 -4
  38. package/scripts/forge-lib-review.sh +29 -1
  39. package/scripts/forge-lib-task.sh +197 -4
  40. package/scripts/forge-memory.sh +245 -3
  41. package/scripts/forge-metrics.sh +7 -3
  42. package/scripts/forge-parallel-options.sh +4 -0
  43. package/scripts/forge-parallel.sh +1216 -41
  44. package/scripts/forge-planner.py +104 -8
  45. package/scripts/forge-prompt.py +120 -0
  46. package/scripts/forge-retro.py +115 -0
  47. package/scripts/forge-route.py +190 -12
  48. package/scripts/forge-runs-compact.py +443 -0
  49. package/scripts/forge-runs-rm.py +2 -0
  50. package/scripts/forge-runs.py +27 -8
  51. package/scripts/forge-schedule.py +633 -49
  52. package/scripts/forge-shadow.py +7 -1
  53. package/scripts/forge-solo.sh +4 -0
  54. package/scripts/forge-summarize.py +698 -0
  55. package/scripts/forge-ui-options.sh +10 -0
  56. package/scripts/forge-worktrees.py +243 -0
  57. package/scripts/forge_brief/__init__.py +831 -0
  58. package/scripts/forge_brief/answers.py +506 -0
  59. package/scripts/forge_brief/proposals.py +1630 -0
  60. package/scripts/forge_dataset/__init__.py +10 -0
  61. package/scripts/forge_dataset/efforts.py +4 -3
  62. package/scripts/forge_dataset/export.py +36 -10
  63. package/scripts/forge_dataset/facts.py +8 -4
  64. package/scripts/forge_dataset/forecast.py +8 -18
  65. package/scripts/forge_dataset/harvest.py +241 -12
  66. package/scripts/forge_dataset/history.py +13 -6
  67. package/scripts/forge_dataset/importer.py +65 -1
  68. package/scripts/forge_dataset/names.py +66 -0
  69. package/scripts/forge_dataset/reviewers.py +5 -2
  70. package/scripts/forge_dataset/risk.py +6 -3
  71. package/scripts/forge_dataset/routing.py +6 -1
  72. package/scripts/forge_decide/__init__.py +11 -1
  73. package/scripts/forge_groups/__init__.py +308 -0
  74. package/scripts/forge_groups/attribute.py +289 -0
  75. package/scripts/forge_groups/review.py +286 -0
  76. package/scripts/forge_locations.py +366 -0
  77. package/scripts/forge_owner.py +152 -0
  78. package/scripts/forge_registry.py +19 -0
  79. package/scripts/forge_retro/__init__.py +417 -0
  80. package/scripts/forge_retro/issues.py +1193 -0
  81. package/scripts/forge_retro/report.py +671 -0
  82. package/scripts/forge_side/__init__.py +482 -0
  83. package/scripts/forge_storage.py +515 -0
  84. package/ui/README.md +68 -8
  85. package/ui/docs/api.md +375 -31
  86. package/ui/forge_ui/control.py +451 -11
  87. package/ui/forge_ui/executions.py +8 -1
  88. package/ui/forge_ui/export.py +53 -7
  89. package/ui/forge_ui/groups.py +264 -0
  90. package/ui/forge_ui/links.py +337 -0
  91. package/ui/forge_ui/models.py +125 -10
  92. package/ui/forge_ui/projects.py +4 -1
  93. package/ui/forge_ui/reader.py +919 -45
  94. package/ui/forge_ui/server.py +4 -0
  95. package/ui/forge_ui/static/app.js +173 -11
  96. package/ui/forge_ui/static/briefview.js +605 -0
  97. package/ui/forge_ui/static/checksview.js +6 -2
  98. package/ui/forge_ui/static/controls.js +5 -0
  99. package/ui/forge_ui/static/diffview.js +86 -1
  100. package/ui/forge_ui/static/groupsview.js +332 -0
  101. package/ui/forge_ui/static/index.html +4 -0
  102. package/ui/forge_ui/static/panel.js +394 -8
  103. package/ui/forge_ui/static/projectsview.js +189 -10
  104. package/ui/forge_ui/static/runmodel.js +27 -4
  105. package/ui/forge_ui/static/storageview.js +352 -0
  106. package/ui/forge_ui/static/style.css +176 -6
  107. package/ui/forge_ui/static/worktreesview.js +235 -14
  108. package/ui/forge_ui/storage.py +150 -0
  109. package/ui/forge_ui/transcripts.py +35 -10
  110. package/ui/forge_ui/worktrees.py +154 -13
@@ -0,0 +1,366 @@
1
+ """Where forge has put things on this machine: every run dir and every worktree it created.
2
+
3
+ forge's index of its own footprint, so `forge du`, `forge runs compact`, forge-ui's Disk and Worktrees
4
+ screens and `forge runs rm` know where to look without guessing from the run registry, the dataset and
5
+ scans of `.forge-worktrees` folders. It records what forge did, never what is there now: every reader
6
+ still asks the disk and git, and marks an entry's path that is gone. It is housekeeping like the run
7
+ registry, so it is written whatever FORGE_DATASET says; FORGE_RUN_REGISTRY=off turns both off.
8
+
9
+ The file is `<config home>/forge/locations.jsonl` (beside the `runs` registry), append-only, one JSON
10
+ object per line:
11
+
12
+ {"v": 1, "at": <unix time>, "op": "add" | "gone", "kind": "run" | "worktree", "path": <real path>,
13
+ "git": <the repository's common git dir>, "root": <its main working tree>, "checkout": <the checkout
14
+ forge ran in>, "run_id", "run_dir", "task", "branch", "wt_kind": task | integration | candidate |
15
+ attribute, "by": <what wrote it>}
16
+
17
+ `git` and `root` name the repository itself, so a checkout deleted by hand, or reached through a
18
+ symlink, hides nothing: git answers for a repository from its main working tree or any worktree.
19
+ `load()` folds the lines by (kind, path): the last `add` wins and a later `gone` marks it gone (with its
20
+ time) until another `add`. A line that is not one of these objects is skipped.
21
+
22
+ Writing never fails or slows a run: the lock is tried briefly and the line is appended without it when
23
+ it stays busy (one write per call, so lines do not interleave); every error is swallowed. The first
24
+ `ensure_imported()` (from `forge du`, `forge runs compact` and the background check at run start) fills
25
+ the file from the run registry and the worktree folders already on disk, once.
26
+
27
+ CLI, for the runners (always exits 0, prints nothing unless asked):
28
+ forge_locations.py run <run dir> a run dir, its repository read from <run dir>/repo
29
+ forge_locations.py worktree created|removed <run dir> <checkout> <path> <branch|-> <kind> [task]
30
+ forge_locations.py list [--json] [--all] what it holds (--all: gone entries too)
31
+ forge_locations.py import [--force] the one-time import, again with --force
32
+ """
33
+ from __future__ import annotations
34
+
35
+ import contextlib
36
+ import errno
37
+ import fcntl
38
+ import json
39
+ import os
40
+ from pathlib import Path
41
+ import subprocess
42
+ import sys
43
+ import time
44
+
45
+ VERSION = 1
46
+ LOCK_WAIT_S = 0.5
47
+ READ_MAX = 64 << 20
48
+ KINDS = ('run', 'worktree')
49
+ WT_KINDS = ('task', 'integration', 'candidate', 'attribute')
50
+ _GIT_TIMEOUT = 10
51
+ _IDENTITY: dict = {}
52
+
53
+
54
+ def config_dir() -> Path:
55
+ """`<config home>/forge`, resolved as the run registry resolves it."""
56
+ value = os.environ.get('XDG_CONFIG_HOME') or ''
57
+ base = Path(value).expanduser() if value else None
58
+ if base is None or not base.is_absolute():
59
+ base = Path.home() / '.config'
60
+ return base / 'forge'
61
+
62
+
63
+ def file_path() -> Path:
64
+ return config_dir() / 'locations.jsonl'
65
+
66
+
67
+ def enabled() -> bool:
68
+ return os.environ.get('FORGE_RUN_REGISTRY', '').strip().lower() != 'off' and config_dir().is_absolute()
69
+
70
+
71
+ def _real(path) -> str:
72
+ try:
73
+ return os.path.realpath(os.fspath(path))
74
+ except (OSError, ValueError, TypeError):
75
+ return os.fspath(path)
76
+
77
+
78
+ def _git(cwd, *args):
79
+ try:
80
+ done = subprocess.run(['git', '--no-optional-locks', '-C', os.fspath(cwd), *args], capture_output=True, text=True,
81
+ stdin=subprocess.DEVNULL, timeout=_GIT_TIMEOUT, errors='replace',
82
+ env={k: v for k, v in os.environ.items() if not k.startswith('GIT_') or k in ('GIT_CONFIG_GLOBAL', 'GIT_CONFIG_NOSYSTEM')})
83
+ except (OSError, ValueError, subprocess.SubprocessError):
84
+ return None, ''
85
+ return done.returncode, done.stdout
86
+
87
+
88
+ def repository(checkout) -> tuple[str | None, str | None]:
89
+ """(the common git dir, the main working tree) of the repository `checkout` belongs to; (None, None) when
90
+ git cannot say. Cached per checkout for the process."""
91
+ if not checkout or not os.path.isdir(checkout):
92
+ return None, None
93
+ key = _real(checkout)
94
+ if key in _IDENTITY:
95
+ return _IDENTITY[key]
96
+ found = (None, None)
97
+ code, out = _git(checkout, 'rev-parse', '--git-common-dir')
98
+ if code == 0 and out.strip():
99
+ common = out.strip()
100
+ common = _real(common if os.path.isabs(common) else os.path.join(checkout, common))
101
+ root = None
102
+ code, listed = _git(checkout, 'worktree', 'list', '--porcelain')
103
+ if code == 0:
104
+ first = next((line[len('worktree '):] for line in listed.splitlines() if line.startswith('worktree ')), None)
105
+ root = _real(first) if first else None
106
+ found = (common, root)
107
+ _IDENTITY[key] = found
108
+ return found
109
+
110
+
111
+ # ---------------------------------------------------------------------------------- writing
112
+
113
+ @contextlib.contextmanager
114
+ def _lock(wait_s):
115
+ """The file's lock, tried for `wait_s`; yields whether it is held. Never raises."""
116
+ fd = None
117
+ try:
118
+ fd = os.open(config_dir() / 'locations.lock', os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o644)
119
+ deadline = time.monotonic() + wait_s
120
+ while True:
121
+ try:
122
+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
123
+ break
124
+ except OSError as error:
125
+ if error.errno not in (errno.EWOULDBLOCK, errno.EAGAIN, errno.EACCES) or time.monotonic() >= deadline:
126
+ raise
127
+ time.sleep(0.01)
128
+ yield True
129
+ except OSError:
130
+ yield False
131
+ finally:
132
+ if fd is not None:
133
+ os.close(fd)
134
+
135
+
136
+ def append(records: list[dict]) -> bool:
137
+ """Appends records in one write. Never raises; False when nothing could be written."""
138
+ if not records or not enabled():
139
+ return False
140
+ try:
141
+ config_dir().mkdir(parents=True, exist_ok=True)
142
+ data = ''.join(json.dumps(dict(r, v=VERSION), sort_keys=True, separators=(',', ':')) + '\n' for r in records).encode()
143
+ with _lock(LOCK_WAIT_S):
144
+ fd = os.open(file_path(), os.O_WRONLY | os.O_APPEND | os.O_CREAT | os.O_NONBLOCK | os.O_NOFOLLOW, 0o644)
145
+ try:
146
+ if not os.path.isfile(file_path()):
147
+ return False
148
+ os.write(fd, data)
149
+ finally:
150
+ os.close(fd)
151
+ return True
152
+ except (OSError, ValueError, TypeError):
153
+ return False
154
+
155
+
156
+ def _repo_fields(checkout) -> dict:
157
+ git, root = repository(checkout)
158
+ return dict(checkout=_real(checkout) if checkout else None, git=git, root=root)
159
+
160
+
161
+ def run_record(run_dir, checkout=None, by='forge') -> dict | None:
162
+ run_dir = _real(run_dir)
163
+ if checkout is None:
164
+ checkout = _first_line(os.path.join(run_dir, 'repo'))
165
+ if not checkout or not os.path.isabs(checkout):
166
+ return None
167
+ run_id = _first_line(os.path.join(run_dir, 'run_id')) or os.path.basename(run_dir)
168
+ return dict(at=time.time(), op='add', kind='run', path=run_dir, run_id=run_id, run_dir=run_dir, by=by,
169
+ **_repo_fields(checkout))
170
+
171
+
172
+ def add_run(run_dir, checkout=None, by='forge') -> bool:
173
+ """Records a run dir; a run already listed, present and with the same repository, is not written again
174
+ (every `run` and `retry` registers its run)."""
175
+ record = run_record(run_dir, checkout, by)
176
+ if record is None or not enabled():
177
+ return False
178
+ known = load().get(('run', record['path']))
179
+ if known and not known['gone'] and all(known.get(k) == record.get(k) for k in ('checkout', 'git', 'root', 'run_id')):
180
+ return True
181
+ return append([record])
182
+
183
+
184
+ def worktree_record(op, path, checkout=None, run_dir=None, run_id=None, branch=None, wt_kind=None, task=None, by='forge') -> dict:
185
+ record = dict(at=time.time(), op='add' if op in ('add', 'created') else 'gone', kind='worktree', path=_real(path),
186
+ run_dir=_real(run_dir) if run_dir else None, run_id=run_id, task=task or None,
187
+ branch=None if branch in (None, '', '-') else branch, wt_kind=wt_kind if wt_kind in WT_KINDS else None, by=by)
188
+ if record['op'] == 'add' or checkout:
189
+ record.update(_repo_fields(checkout))
190
+ if record['run_id'] is None and run_dir:
191
+ record['run_id'] = _first_line(os.path.join(run_dir, 'run_id')) or os.path.basename(_real(run_dir))
192
+ return record
193
+
194
+
195
+ def add_worktree(path, checkout, **fields) -> bool:
196
+ return append([worktree_record('add', path, checkout, **fields)])
197
+
198
+
199
+ def gone(kind, path, by='forge') -> bool:
200
+ if kind not in KINDS:
201
+ return False
202
+ return append([dict(at=time.time(), op='gone', kind=kind, path=_real(path), by=by)])
203
+
204
+
205
+ def _first_line(path) -> str | None:
206
+ try:
207
+ fd = os.open(path, os.O_RDONLY | os.O_NONBLOCK)
208
+ with os.fdopen(fd, 'rb') as stream:
209
+ if not os.path.isfile(path):
210
+ return None
211
+ line = stream.readline(65536).decode('utf-8', 'replace').strip()
212
+ except OSError:
213
+ return None
214
+ return line or None
215
+
216
+
217
+ # ---------------------------------------------------------------------------------- reading
218
+
219
+ def load(path=None) -> dict:
220
+ """{(kind, path): entry} folded from the file: each entry is the merged fields of its adds, with `created`
221
+ (the first add), `updated`, and `gone` (the time of a `gone` after the last add, else None). Read only."""
222
+ target = Path(path) if path is not None else file_path()
223
+ out: dict = {}
224
+ try:
225
+ with open(target, 'rb') as stream:
226
+ data = stream.read(READ_MAX)
227
+ except OSError:
228
+ return out
229
+ for raw in data.splitlines():
230
+ try:
231
+ record = json.loads(raw)
232
+ except ValueError:
233
+ continue
234
+ if not isinstance(record, dict) or record.get('kind') not in KINDS or not isinstance(record.get('path'), str) \
235
+ or not os.path.isabs(record['path']) or record.get('op') not in ('add', 'gone'):
236
+ continue
237
+ at = record.get('at') if isinstance(record.get('at'), (int, float)) else None
238
+ key = (record['kind'], record['path'])
239
+ entry = out.get(key)
240
+ if record['op'] == 'gone':
241
+ if entry is not None:
242
+ entry['gone'] = at or entry.get('updated') or 0
243
+ continue
244
+ if entry is None:
245
+ entry = out[key] = dict(kind=record['kind'], path=record['path'], created=at, updated=at, gone=None)
246
+ for name, value in record.items():
247
+ if name not in ('v', 'op', 'at', 'kind', 'path') and value is not None:
248
+ entry[name] = value
249
+ entry.update(updated=at, gone=None)
250
+ return out
251
+
252
+
253
+ def entries(kind=None, present=True, path=None) -> list[dict]:
254
+ """The folded entries, of one kind when given, only those not marked gone when `present`."""
255
+ return [e for (k, _), e in sorted(load(path).items()) if (kind is None or k == kind) and (not present or not e['gone'])]
256
+
257
+
258
+ def repositories(path=None) -> list[str]:
259
+ """Every repository the file names, as paths git can be asked from: main working trees, then checkouts."""
260
+ seen, out = set(), []
261
+ for e in load(path).values():
262
+ for candidate in (e.get('root'), e.get('checkout')):
263
+ if isinstance(candidate, str) and os.path.isabs(candidate) and candidate not in seen:
264
+ seen.add(candidate)
265
+ out.append(candidate)
266
+ return out
267
+
268
+
269
+ # ---------------------------------------------------------------------------------- the one-time import
270
+
271
+ def marker() -> Path:
272
+ return config_dir() / 'locations.imported'
273
+
274
+
275
+ def ensure_imported(force=False) -> dict | None:
276
+ """Fills the file from the run registry and the worktree folders on disk, once (a marker records it).
277
+ Returns what was added, or None when it had been done already or is off. Never raises."""
278
+ if not enabled() or (marker().exists() and not force):
279
+ return None
280
+ try:
281
+ return _import()
282
+ except Exception: # noqa: BLE001 -- housekeeping never fails its caller
283
+ return None
284
+
285
+
286
+ def _import() -> dict:
287
+ here = str(Path(__file__).resolve().parent)
288
+ if here not in sys.path:
289
+ sys.path.insert(0, here)
290
+ import forge_registry
291
+ import forge_worktrees
292
+ known = load()
293
+ runs, records, seen_repos = [], [], {}
294
+ registry = forge_registry.registry_dir()
295
+ for listing in sorted(registry.glob('*.txt')) if registry.is_dir() else []:
296
+ try:
297
+ lines = listing.read_text(encoding='utf-8', errors='replace').splitlines()
298
+ except OSError:
299
+ continue
300
+ for line in lines:
301
+ line = line.strip()
302
+ if line and not line.startswith('#') and os.path.isabs(line) and os.path.isdir(line):
303
+ runs.append(_real(line))
304
+ for run_dir in dict.fromkeys(runs):
305
+ record = run_record(run_dir, by='import')
306
+ if record is None:
307
+ continue
308
+ if ('run', run_dir) not in known:
309
+ records.append(record)
310
+ checkout = record['checkout']
311
+ if not checkout or not os.path.isdir(checkout) or not forge_worktrees.RUN_ID.fullmatch(record['run_id'] or ''):
312
+ continue
313
+ root = forge_worktrees.wt_root(checkout, record['run_id'])
314
+ if checkout not in seen_repos:
315
+ code, out = _git(checkout, 'worktree', 'list', '--porcelain', '-z')
316
+ seen_repos[checkout] = forge_worktrees.parse_porcelain(out, z=True) if code == 0 else []
317
+ tasks = _tasks(run_dir)
318
+ for wt in seen_repos[checkout]:
319
+ kind = forge_worktrees.owner(wt['path'], wt['branch'], record['run_id'], tasks, root)
320
+ if kind and ('worktree', _real(wt['path'])) not in known:
321
+ branch = (wt['branch'] or '').replace('refs/heads/', '', 1) or None
322
+ records.append(worktree_record('add', wt['path'], checkout, run_dir=run_dir, run_id=record['run_id'],
323
+ branch=branch, wt_kind=kind, task=branch.split('/', 2)[-1] if kind == 'task' and branch else None,
324
+ by='import'))
325
+ append(records)
326
+ config_dir().mkdir(parents=True, exist_ok=True)
327
+ marker().write_text('%d\n' % int(time.time()))
328
+ return dict(runs=sum(1 for r in records if r['kind'] == 'run'), worktrees=sum(1 for r in records if r['kind'] == 'worktree'))
329
+
330
+
331
+ def _tasks(run_dir) -> list[str]:
332
+ try:
333
+ text = Path(run_dir, 'tasks.tsv').read_text(encoding='utf-8', errors='replace')
334
+ except OSError:
335
+ return []
336
+ return [line.split('\t', 1)[0] for line in text.splitlines() if line.strip() and not line.startswith('#')]
337
+
338
+
339
+ # ---------------------------------------------------------------------------------- CLI
340
+
341
+ def main(argv=None) -> int:
342
+ args = list(sys.argv[1:] if argv is None else argv)
343
+ try:
344
+ if args[:1] == ['run'] and len(args) == 2:
345
+ add_run(args[1])
346
+ elif args[:1] == ['worktree'] and len(args) in (7, 8) and args[1] in ('created', 'removed'):
347
+ _, op, run_dir, checkout, path, branch, kind, *task = args
348
+ append([worktree_record(op, path, checkout, run_dir=run_dir, branch=branch, wt_kind=kind,
349
+ task=task[0] if task else None)])
350
+ elif args[:1] == ['list']:
351
+ found = entries(present='--all' not in args)
352
+ if '--json' in args:
353
+ print(json.dumps(found, indent=2))
354
+ else:
355
+ for e in found:
356
+ print('%-8s %s%s' % (e['kind'], e['path'], ' (gone)' if e['gone'] else ''))
357
+ elif args[:1] == ['import']:
358
+ result = ensure_imported(force='--force' in args)
359
+ print(json.dumps(result))
360
+ except Exception: # noqa: BLE001 -- the runners call this: it must never reach a run
361
+ pass
362
+ return 0
363
+
364
+
365
+ if __name__ == '__main__':
366
+ sys.exit(main())
@@ -0,0 +1,152 @@
1
+ #!/usr/bin/env python3
2
+ """Which task of a plan declares a path.
3
+
4
+ `<plan>/tasks.tsv` is tab-separated `id deps difficulty files dwarf qa title`.
5
+ `files` is a comma list of repo-relative paths or directories; `-` declares
6
+ nothing. A later decision asks this module which task owns a path, and whether
7
+ that path sits outside one task, using the same coverage rule the scheduler
8
+ uses to serialise tasks.
9
+
10
+ python3 scripts/forge_owner.py <plan> <path>... [--task ID]
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import argparse
15
+ import json
16
+ import os
17
+ from pathlib import Path
18
+ import posixpath
19
+ import sys
20
+
21
+
22
+ def _rows(plan: str | os.PathLike) -> list[tuple[str, str]]:
23
+ """`(id, files)` from tasks.tsv, in file order.
24
+
25
+ Comment lines, blank lines and rows with fewer than four columns are
26
+ skipped. A missing tasks.tsv raises FileNotFoundError.
27
+ """
28
+ text = (Path(plan) / 'tasks.tsv').read_text(encoding='utf-8').replace('\r', '')
29
+ found = []
30
+ for line in text.splitlines():
31
+ if not line or line.startswith('#'):
32
+ continue
33
+ columns = line.split('\t')
34
+ if len(columns) < 4:
35
+ continue
36
+ found.append((columns[0], columns[3]))
37
+ return found
38
+
39
+
40
+ def _entries(files: str) -> list[str]:
41
+ """Normalised paths in one files cell. Empty tokens and `-` declare nothing."""
42
+ return [posixpath.normpath(part) for part in files.split(',') if part and part != '-']
43
+
44
+
45
+ def declared(plan: str | os.PathLike, task: str) -> list[str]:
46
+ """That task's normalised `files` entries. `[]` for `-` or an unknown task."""
47
+ for ident, files in _rows(plan):
48
+ if ident == task:
49
+ return _entries(files)
50
+ return []
51
+
52
+
53
+ def covers(entry: str, path: str) -> bool:
54
+ """Whether one declared entry covers one path. An entry of `.` covers every path."""
55
+ # forge-schedule.py overlap: posixpath.normpath on each side, then equal or a '/' prefix; '.' covers all.
56
+ def piece(value: str) -> str | None:
57
+ if not value or value == '-':
58
+ return None
59
+ return posixpath.normpath(value)
60
+
61
+ left, right = piece(entry), piece(path)
62
+ if left is None or right is None:
63
+ return False
64
+ return (left == '.' or right == '.' or left == right
65
+ or left.startswith(right + '/') or right.startswith(left + '/'))
66
+
67
+
68
+ def _query(path: str) -> str | None:
69
+ """Repo-relative form of a path, or None when no task can own it.
70
+
71
+ Strip one leading `./`, then posixpath.normpath. An absolute result, or one
72
+ that starts with `..`, is outside the repository.
73
+ """
74
+ text = str(path)
75
+ if text.startswith('./'):
76
+ text = text[2:]
77
+ norm = posixpath.normpath(text)
78
+ if posixpath.isabs(norm) or norm.startswith('..'):
79
+ return None
80
+ return norm
81
+
82
+
83
+ def owners(plan: str | os.PathLike, path: str) -> list[str]:
84
+ """Every task id whose `files` cover `path`, in tasks.tsv order."""
85
+ rows = _rows(plan)
86
+ query = _query(path)
87
+ if query is None:
88
+ return []
89
+ found: list[str] = []
90
+ seen: set[str] = set()
91
+ for ident, files in rows:
92
+ if ident in seen:
93
+ continue
94
+ seen.add(ident) # the first row is the task's declaration, as declared() reads it
95
+ if any(covers(entry, query) for entry in _entries(files)):
96
+ found.append(ident)
97
+ return found
98
+
99
+
100
+ def owner(plan: str | os.PathLike, path: str) -> str | None:
101
+ """The first task in tasks.tsv order whose `files` cover `path`, or None."""
102
+ found = owners(plan, path)
103
+ return found[0] if found else None
104
+
105
+
106
+ def outside(plan: str | os.PathLike, task: str, path: str) -> bool:
107
+ """True when none of `task`'s declared entries covers `path`.
108
+
109
+ A task that declares `.` has nothing outside. A task whose `files` is `-`,
110
+ or an unknown task, has everything outside.
111
+ """
112
+ return not any(covers(entry, path) for entry in declared(plan, task))
113
+
114
+
115
+ def _report(plan: str, paths: list[str], task: str | None) -> dict:
116
+ idents = [ident for ident, _files in _rows(plan)]
117
+ if task is not None and task not in idents:
118
+ raise LookupError(task)
119
+ items = []
120
+ for path in paths:
121
+ found = owners(plan, path)
122
+ items.append({
123
+ 'path': path,
124
+ 'owner': found[0] if found else None,
125
+ 'owners': found,
126
+ 'outside': outside(plan, task, path) if task is not None else None,
127
+ })
128
+ return {'paths': items}
129
+
130
+
131
+ def main(argv: list[str] | None = None) -> int:
132
+ parser = argparse.ArgumentParser(
133
+ prog='forge_owner.py', description='Which task of a plan declares a path.')
134
+ parser.add_argument('plan', help='plan directory containing tasks.tsv')
135
+ parser.add_argument('paths', nargs='+', help='repo-relative paths to look up')
136
+ parser.add_argument('--task', help='also report whether each path is outside this task')
137
+ args = parser.parse_args(argv)
138
+ try:
139
+ report = _report(args.plan, args.paths, args.task)
140
+ except FileNotFoundError:
141
+ print("forge_owner: no tasks.tsv in '%s'" % args.plan, file=sys.stderr)
142
+ return 2
143
+ except LookupError as error:
144
+ print("forge_owner: unknown task '%s'" % error, file=sys.stderr)
145
+ return 2
146
+ json.dump(report, sys.stdout)
147
+ sys.stdout.write('\n')
148
+ return 0
149
+
150
+
151
+ if __name__ == '__main__':
152
+ sys.exit(main())
@@ -112,6 +112,15 @@ def _registry_lock(wait_s: float):
112
112
  os.close(fd)
113
113
 
114
114
 
115
+ def _locations():
116
+ """forge_locations, beside this file: `python3 -I` (how the runners call this) leaves this folder off sys.path."""
117
+ here = os.path.dirname(os.path.abspath(__file__))
118
+ if here not in sys.path:
119
+ sys.path.insert(0, here)
120
+ import forge_locations
121
+ return forge_locations
122
+
123
+
115
124
  def register_run_dir(repo: Path, run_dir: Path) -> None:
116
125
  """Record an absolute run-dir path for this repo, deduplicated.
117
126
 
@@ -121,6 +130,12 @@ def register_run_dir(repo: Path, run_dir: Path) -> None:
121
130
  it (see the module docstring), and appended again if an unregister replaced the file
122
131
  it went to.
123
132
  """
133
+ try:
134
+ # Into forge's location list as well, with the repository's git dir and not only this checkout. Like
135
+ # the registry, it never raises: forge_locations swallows its own errors.
136
+ _locations().add_run(run_dir, str(repo))
137
+ except Exception: # noqa: BLE001 -- an import that fails must not cost the registry line
138
+ pass
124
139
  try:
125
140
  # A relative HOME (registry_dir already ignores a relative XDG_CONFIG_HOME) would resolve
126
141
  # below the current directory -- for a runner, usually the user's repo. Forge does not
@@ -239,6 +254,10 @@ def unregister_run_dir(run_dir) -> list:
239
254
  for path in sorted(directory.glob('*.txt')):
240
255
  if _rewrite_without(path, wanted):
241
256
  changed.append(path)
257
+ try:
258
+ _locations().gone('run', run_dir, by='forge runs rm')
259
+ except Exception: # noqa: BLE001 -- the location list is housekeeping: it never fails a removal
260
+ pass
242
261
  return changed
243
262
 
244
263