@giamme/forge 0.12.1 → 0.13.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 (107) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/README.md +1 -1
  3. package/SKILL.md +29 -12
  4. package/VERSION +1 -1
  5. package/docs/add-ons.md +11 -6
  6. package/docs/artifacts.md +12 -6
  7. package/docs/commands.md +179 -17
  8. package/docs/decomposed-runs.md +13 -5
  9. package/docs/forge-ui.md +7 -3
  10. package/docs/memory.md +2 -1
  11. package/docs/models.md +4 -2
  12. package/docs/reviews.md +49 -20
  13. package/docs/troubleshooting.md +3 -1
  14. package/forge +17 -1
  15. package/package.json +1 -1
  16. package/references/dataset.md +39 -13
  17. package/references/decision-models.md +759 -0
  18. package/references/decompose.md +166 -29
  19. package/references/harnesses.md +10 -3
  20. package/references/planning.md +8 -0
  21. package/references/solo.md +13 -3
  22. package/scripts/forge-artifact.sh +30 -4
  23. package/scripts/forge-config.py +238 -29
  24. package/scripts/forge-contract.py +95 -56
  25. package/scripts/forge-control.py +40 -9
  26. package/scripts/forge-decide.py +6 -0
  27. package/scripts/forge-dispatch.sh +38 -16
  28. package/scripts/forge-fail-first.py +2 -2
  29. package/scripts/forge-gate-addressed.sh +40 -0
  30. package/scripts/forge-gate-message.sh +64 -0
  31. package/scripts/forge-issues.py +321 -33
  32. package/scripts/forge-jev-options.sh +269 -42
  33. package/scripts/forge-lib-attribute.sh +447 -0
  34. package/scripts/forge-lib-gates.sh +32 -0
  35. package/scripts/forge-lib-plans.sh +17 -6
  36. package/scripts/forge-lib-review.sh +22 -17
  37. package/scripts/forge-lib-task.sh +217 -38
  38. package/scripts/forge-lib-verify.sh +45 -8
  39. package/scripts/forge-memory.sh +3 -3
  40. package/scripts/forge-parallel-options.sh +18 -5
  41. package/scripts/forge-parallel.sh +455 -303
  42. package/scripts/forge-plan-check.py +35 -1
  43. package/scripts/forge-pre-review.py +437 -0
  44. package/scripts/forge-prompt.py +25 -5
  45. package/scripts/forge-route.py +2 -2
  46. package/scripts/forge-runtime.py +10 -4
  47. package/scripts/forge-schedule.py +21 -5
  48. package/scripts/forge-shadow.py +2 -2
  49. package/scripts/forge-solo.sh +38 -9
  50. package/scripts/forge-submodules.py +389 -0
  51. package/scripts/forge_dataset/cli.py +12 -6
  52. package/scripts/forge_dataset/export.py +55 -45
  53. package/scripts/forge_dataset/harvest.py +33 -5
  54. package/scripts/{forge_jev/outcome.py → forge_dataset/states.py} +21 -7
  55. package/scripts/forge_decide/__init__.py +141 -0
  56. package/scripts/forge_decide/budget.py +149 -0
  57. package/scripts/forge_decide/cache.py +66 -0
  58. package/scripts/forge_decide/cli.py +953 -0
  59. package/scripts/forge_decide/doctor.py +221 -0
  60. package/scripts/forge_decide/label_addressed.py +75 -0
  61. package/scripts/forge_decide/label_attribution.py +62 -0
  62. package/scripts/forge_decide/label_coverage.py +81 -0
  63. package/scripts/forge_decide/label_message.py +38 -0
  64. package/scripts/forge_decide/label_prompt.py +139 -0
  65. package/scripts/forge_decide/labels.py +328 -0
  66. package/scripts/forge_decide/metrics.py +125 -0
  67. package/scripts/forge_decide/migrate.py +226 -0
  68. package/scripts/forge_decide/providers.py +292 -0
  69. package/scripts/forge_decide/replay.py +350 -0
  70. package/scripts/forge_decide/report.py +382 -0
  71. package/scripts/forge_decide/resolve.py +397 -0
  72. package/scripts/forge_decide/sites.py +377 -0
  73. package/scripts/forge_jev/__init__.py +202 -104
  74. package/scripts/forge_jev/addressed.py +171 -0
  75. package/scripts/forge_jev/attribution.py +198 -0
  76. package/scripts/forge_jev/cli.py +460 -382
  77. package/scripts/forge_jev/client.py +155 -77
  78. package/scripts/forge_jev/coupling.py +19 -87
  79. package/scripts/forge_jev/coverage.py +303 -0
  80. package/scripts/forge_jev/findings.py +219 -0
  81. package/scripts/forge_jev/gates.py +225 -27
  82. package/scripts/forge_jev/memory.py +65 -4
  83. package/scripts/forge_jev/message.py +134 -0
  84. package/scripts/forge_jev/plan_gates.py +294 -0
  85. package/scripts/forge_jev/questions.py +173 -313
  86. package/scripts/forge_jev/verify.py +130 -104
  87. package/ui/README.md +2 -2
  88. package/ui/docs/api.md +60 -32
  89. package/ui/forge_ui/control.py +60 -11
  90. package/ui/forge_ui/export.py +2 -1
  91. package/ui/forge_ui/models.py +1 -0
  92. package/ui/forge_ui/reader.py +87 -14
  93. package/ui/forge_ui/static/app.js +2 -2
  94. package/ui/forge_ui/static/controls.js +20 -13
  95. package/ui/forge_ui/static/panel.js +63 -17
  96. package/ui/forge_ui/static/runmodel.js +23 -1
  97. package/ui/forge_ui/static/scene3d.js +2 -15
  98. package/ui/forge_ui/static/settings.js +336 -41
  99. package/ui/forge_ui/static/style.css +19 -7
  100. package/references/jev.md +0 -865
  101. package/scripts/forge_jev/backtest.py +0 -322
  102. package/scripts/forge_jev/corpus.py +0 -156
  103. package/scripts/forge_jev/features.py +0 -24
  104. package/scripts/forge_jev/predict.py +0 -204
  105. package/scripts/forge_jev/review.py +0 -73
  106. package/scripts/forge_jev/routing.py +0 -271
  107. package/scripts/forge_jev/subset.py +0 -123
@@ -434,7 +434,12 @@ def stop_harnesses(plan: object, names: object) -> None:
434
434
  # is left after it withdraws liveness, under the same lock, so no request outlives its run.
435
435
  REQUESTS = 'control.requests'
436
436
  REQUEST_MAX = 64 * 1024
437
- RETRYABLE = ('FAIL', 'UNKNOWN', 'TIMEOUT', 'ERROR', 'INTERRUPTED', 'BLOCKED')
437
+ # NEEDS_INPUT is in neither: a task stopped for the user's answer resumes only through
438
+ # `retry <plan> <id> --answer`, whose preparation refuses without one.
439
+ RETRYABLE = ('FAIL', 'UNKNOWN', 'TIMEOUT', 'ERROR', 'INTERRUPTED', 'BLOCKED', 'INVALIDATED')
440
+ # What --retry-failed retries on its own. INVALIDATED only for a review voided while the committed
441
+ # work stayed as it was (tasks/<id>/invalidated.reason is `review`): that retry is a fresh review.
442
+ AUTO_RETRY = ('FAIL', 'UNKNOWN', 'INVALIDATED')
438
443
 
439
444
 
440
445
  def list_requests(plan: object) -> list:
@@ -606,10 +611,18 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
606
611
  value = _read_budget(plan, 'infra_budget')
607
612
  return infra_retries if value is None else value
608
613
 
614
+ def review_voided(name: str) -> bool:
615
+ file = plan / 'tasks' / name / 'invalidated.reason'
616
+ try:
617
+ return file.read_text().strip() == 'review'
618
+ except OSError:
619
+ return False
620
+
609
621
  def retryable(name: str) -> bool:
610
622
  root = plan / 'tasks' / name
611
623
  return (
612
- status(name) in ('FAIL', 'UNKNOWN')
624
+ status(name) in AUTO_RETRY
625
+ and (status(name) != 'INVALIDATED' or review_voided(name))
613
626
  and retries.get(name, 0) < budget(name)
614
627
  # A task that produced no new work (empty diff, byte-identical retry) would
615
628
  # only repeat itself; its marker says so and it is left for a human.
@@ -832,6 +845,9 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
832
845
  return 'refused', 'the task is merged'
833
846
  if state == 'INFRA':
834
847
  return 'refused', 'an infrastructure stop is resumed by the scheduler itself'
848
+ if state == 'NEEDS_INPUT':
849
+ return 'refused', (name + ' is waiting for an answer: forge-parallel.sh retry ' + str(plan)
850
+ + ' ' + name + ' --answer \u2026')
835
851
  if state not in RETRYABLE:
836
852
  return 'refused', 'a ' + state + ' task is not retried'
837
853
  command = ['/bin/bash', script, '_prepare_retry', str(plan), name] + (['--dwarf', dwarf] if dwarf else [])
@@ -965,7 +981,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
965
981
  elif state == 'INFRA':
966
982
  infra_stopped(name)
967
983
  elif allow_requeue and not interrupted and not graceful \
968
- and state in ('FAIL', 'UNKNOWN') and retryable(name):
984
+ and state in AUTO_RETRY and retryable(name):
969
985
  requeue(name)
970
986
  if not reaped:
971
987
  return
@@ -991,7 +1007,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
991
1007
  merge(name)
992
1008
  if state == 'RUNNING':
993
1009
  mark(name, 'INTERRUPTED')
994
- if state in ('FAIL', 'UNKNOWN') and not interrupted and retryable(name):
1010
+ if state in AUTO_RETRY and not interrupted and retryable(name):
995
1011
  requeue(name)
996
1012
  if state == 'INFRA' and not interrupted and not resume(name):
997
1013
  pending.remove(name)
@@ -1022,7 +1038,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1022
1038
  for name in tasks:
1023
1039
  if name in pending or name in active or name in ended:
1024
1040
  continue
1025
- if not interrupted and not graceful and status(name) in ('FAIL', 'UNKNOWN') \
1041
+ if not interrupted and not graceful and status(name) in AUTO_RETRY \
1026
1042
  and retryable(name) and refused.get(name) != budget(name):
1027
1043
  requeue(name)
1028
1044
  if paused and not active and infra_seen and not graceful and infra_cycles < infra_budget():
@@ -197,7 +197,7 @@ def run(args) -> int:
197
197
  if bash('forge_review_snapshot', args.worktree, args.base, args.reviewed, str(review)).returncode:
198
198
  status = 'error'
199
199
  return 0
200
- before = bash('forge_fingerprint', str(review)).stdout.strip()
200
+ before = bash('forge_fingerprint', str(review), '--tracked').stdout.strip()
201
201
  shutil.copyfile(Path(args.tdir) / 'qa.input', out / 'qa.input')
202
202
  env = dict(os.environ, FORGE_SHADOW='1', FORGE_SHADOW_ATTEMPT=args.attempt,
203
203
  FORGE_SHADOW_REVIEWED=args.reviewed, FORGE_SHADOW_FROM=args.qa)
@@ -211,7 +211,7 @@ def run(args) -> int:
211
211
  STATE['child'] = subprocess.Popen(argv, stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT,
212
212
  env=env, close_fds=True)
213
213
  status = watch(STATE['child'], parent)
214
- after = bash('forge_fingerprint', str(review)).stdout.strip()
214
+ after = bash('forge_fingerprint', str(review), '--tracked').stdout.strip()
215
215
  if status == 'done' and (not before or after != before):
216
216
  status = 'invalid' # the reviewer changed its snapshot: its verdict counts for nothing
217
217
  except Stopped:
@@ -19,14 +19,16 @@
19
19
  # forge-solo.sh <run-dir> --repo <dir> --dwarf <spec> [--qa <spec>]
20
20
  # [--approach <file>] [--yolo-dwarf] [--yolo-qa]
21
21
  # [--native-review] [--no-memory] [--timeout <s>] [--dry-run] [--ui]
22
- # [--fail-first]
22
+ # [--fail-first] [--qa-threshold P0|P1|P2|P3|none]
23
23
  #
24
24
  # Reads <run-dir>/prompt.md the implementation instruction (required)
25
25
  # <run-dir>/goal.txt one line, what the user asked for (optional)
26
26
  # Writes <run-dir>/dwarf.{input,last,log,resolved}
27
27
  # <run-dir>/changes.diff
28
28
  # <run-dir>/qa.{input,last,log,resolved}
29
- # <run-dir>/verdict PASS | FAIL | UNKNOWN, when qa emitted one
29
+ # <run-dir>/verdict PASS | FAIL | UNKNOWN, when qa emitted one (after the severity gate)
30
+ # <run-dir>/qa.gate, known_issues.md the gate's decision and the tolerated findings
31
+ # <run-dir>/qa_threshold with --qa-threshold: the blocking level (default P2)
30
32
  # <run-dir>/failfirst.json with --fail-first: do the change's tests fail without it?
31
33
  # <run-dir>/status RUNNING, then this invocation's outcome
32
34
  # <run-dir>/dwarf.spec, qa.spec and attempts.tsv
@@ -93,7 +95,7 @@ forge_metric_on_exit() {
93
95
  }
94
96
 
95
97
  if [ "${1:-}" = --help ] || [ "${1:-}" = -h ]; then
96
- sed -n '18,33s/^# *//p' "$0"
98
+ sed -n '18,39s/^# *//p' "$0"
97
99
  forge_fractal_help
98
100
  echo 'Explicit Fractal retry: repeat the original command with --retry.'
99
101
  exit 0
@@ -103,7 +105,7 @@ case "$RUN" in -*) die "first argument must be the run directory, got '$RUN'" ;;
103
105
  shift
104
106
 
105
107
  OUTPUT=summary
106
- REPO="$PWD"; DWARF=""; QA="opus"; APPROACH=""; YD=""; YQ=""; NATIVE=""; TIMEOUT=""; DRY=0; FAIL_FIRST=0
108
+ REPO="$PWD"; DWARF=""; QA="opus"; APPROACH=""; YD=""; YQ=""; NATIVE=""; TIMEOUT=""; DRY=0; FAIL_FIRST=0; QA_THR=
107
109
  while [ $# -gt 0 ]; do
108
110
  case "$1" in
109
111
  --fractal) forge_fractal_flag on || exit $?; shift ;;
@@ -124,11 +126,15 @@ while [ $# -gt 0 ]; do
124
126
  --timeout) TIMEOUT="${2:?--timeout needs seconds}"; shift 2 ;;
125
127
  --dry-run) DRY=1; shift ;;
126
128
  --fail-first) FAIL_FIRST=1; shift ;;
129
+ --qa-threshold)
130
+ QA_THR="$(printf '%s' "${2:?--qa-threshold needs P0, P1, P2, P3 or none}" | tr 'a-z' 'A-Z')"
131
+ case "$QA_THR" in P0|P1|P2|P3) ;; NONE) QA_THR=none ;; *) die "--qa-threshold must be P0, P1, P2, P3 or none, got '$2'" 2 ;; esac
132
+ shift 2 ;;
127
133
  --ui|--no-ui) forge_ui_flag "$1"; shift ;;
128
134
  *)
129
135
  # `case` is not a loop, so `continue` here belongs to the enclosing while.
130
136
  if [ "$JEV_OPTS" = 1 ]; then
131
- forge_jev_flag "$1"; jev_rc=$?
137
+ forge_jev_flag "$@"; jev_rc=$?
132
138
  case "$jev_rc" in
133
139
  0) shift "$JEV_SHIFT"; continue ;;
134
140
  2) exit 2 ;;
@@ -163,6 +169,8 @@ RUN="$(cd "$RUN" && pwd)"
163
169
  # same run dir restores it rather than re-reading whatever flags are passed then.
164
170
  [ "$JEV_OPTS" = 1 ] && { forge_jev_restore "$RUN" || true; forge_jev_record "$RUN"; }
165
171
  REPO="$(cd "$REPO" && pwd)"
172
+ # Before any decision-model step: the privacy floor and the run budget read these.
173
+ [ "$JEV_OPTS" = 1 ] && forge_decide_env "$REPO" "$RUN"
166
174
  if [ "$DRY" != 1 ] && [ "${FORGE_SOLO_LOCK:-}" != "$RUN" ]; then
167
175
  exec python3 "$SKILL_DIR/scripts/forge-fractal.py" _lock "$RUN" "$0" "${ORIGINAL_ARGS[@]}"
168
176
  fi
@@ -281,11 +289,18 @@ REVIEW="$RUN/review-$(date +%s)-$$"
281
289
  forge_review_snapshot "$REPO" "$START" "$END" "$REVIEW" || die "cannot create review snapshot" 3
282
290
  SOURCE_FP="$(forge_fingerprint "$REPO")" || exit 3
283
291
  [ "$(forge_tree "$REPO")" = "$END" ] || { echo INVALIDATED > "$RUN/verdict"; die "source changed while preparing QA" 5; }
284
- REVIEW_FP="$(forge_fingerprint "$REVIEW")" || exit 3
292
+ # The review snapshot is a commit; the reviewer's untracked leftovers there do not count (#95).
293
+ # The source keeps them: in a solo run the implementer's new files are untracked.
294
+ REVIEW_FP="$(forge_fingerprint "$REVIEW" --tracked)" || exit 3
285
295
  printf '%s\n' "$SOURCE_FP" > "$RUN/source.fingerprint"
286
296
  printf '%s\n' "$REVIEW_FP" > "$RUN/review.fingerprint"
287
297
  forge_metric_phase preparation
288
298
  # --- qa -----------------------------------------------------------------------
299
+ # The blocking threshold: this invocation's flag (kept in the run dir), else the file, else P2.
300
+ [ -z "$QA_THR" ] || printf '%s\n' "$QA_THR" > "$RUN/qa_threshold"
301
+ THR="$(head -1 "$RUN/qa_threshold" 2>/dev/null | tr -d ' \r' | tr 'a-z' 'A-Z')"
302
+ case "$THR" in P0|P1|P2|P3) ;; NONE) THR=P3 ;; *) THR="$FORGE_QA_THRESHOLD_DEFAULT" ;; esac
303
+ rm -f "$RUN/qa.gate" "$RUN/known_issues.md"
289
304
  rm -f "$RUN/failfirst.json" "$RUN/failfirst.txt"
290
305
  if [ "$FAIL_FIRST" = 1 ]; then
291
306
  # Opt-in and advisory: the reviewer reads the evidence; nothing here changes a verdict.
@@ -298,7 +313,7 @@ fi
298
313
  python3 "$SKILL_DIR/scripts/forge-contract.py" qa --part head --kind solo
299
314
  echo
300
315
  if [ -s "$RUN/failfirst.txt" ]; then cat "$RUN/failfirst.txt"; echo; fi
301
- python3 "$SKILL_DIR/scripts/forge-contract.py" qa --part tail --kind solo
316
+ python3 "$SKILL_DIR/scripts/forge-contract.py" qa --part tail --kind solo --threshold "$THR"
302
317
  echo
303
318
  # --irreversible-delete: a deleted file shows as a header, not every line it had (one deleted
304
319
  # data directory once made a 7.1M-character prompt that the reviewer's CLI refused).
@@ -315,7 +330,7 @@ rc=$?
315
330
  forge_metric_phase verification
316
331
  verdict="$(forge_verdict "$RUN/qa.last")"
317
332
  [ -n "$NATIVE" ] && verdict=UNKNOWN
318
- if [ "$(forge_fingerprint "$REPO")" != "$SOURCE_FP" ] || [ "$(forge_fingerprint "$REVIEW")" != "$REVIEW_FP" ]; then
333
+ if [ "$(forge_fingerprint "$REPO")" != "$SOURCE_FP" ] || [ "$(forge_fingerprint "$REVIEW" --tracked)" != "$REVIEW_FP" ]; then
319
334
  echo INVALIDATED > "$RUN/verdict"
320
335
  die "source or review artifact changed during QA; review invalidated" 5
321
336
  fi
@@ -329,11 +344,25 @@ dur_qa="$(sed -n 's/^duration_s=//p' "$RUN/qa.resolved" 2>/dev/null | tail -1)"
329
344
 
330
345
  # --native-review is codex's own reviewer, which refuses a custom prompt alongside
331
346
  # its scope flags — so it never sees the verdict instruction and cannot emit one.
347
+ # Otherwise forge enforces the severity rule itself, as a decomposed task's gate does; a gate
348
+ # that cannot run (no output) keeps the reviewer's verdict.
349
+ gate_note=""
350
+ if [ -z "$NATIVE" ]; then
351
+ gate_line="$(python3 "$SKILL_DIR/scripts/forge-contract.py" gate --verdict "${verdict:-UNKNOWN}" \
352
+ --qa-last "$RUN/qa.last" --threshold "$THR" --known-issues "$RUN/known_issues.md" 2>/dev/null)" || gate_line=""
353
+ if [ -n "$gate_line" ]; then
354
+ printf '%s\t%s\n' "$THR" "$gate_line" > "$RUN/qa.gate"
355
+ case "$(printf '%s' "$gate_line" | awk -F'\t' '{print $1}')" in
356
+ accept) verdict=PASS; gate_note=" (accepted with known issues: $RUN/known_issues.md)" ;;
357
+ fail) verdict=FAIL; gate_note=" (the reviewer said PASS, but listed a CONFIRMED finding at or above the $THR threshold — forge made it FAIL)" ;;
358
+ esac
359
+ fi
360
+ fi
332
361
  echo "${verdict:-UNKNOWN}" > "$RUN/verdict"
333
362
 
334
363
  echo
335
364
  echo "dwarf: $DWARF ${dur_dwarf:-?}s"
336
- echo "qa: $QA ${dur_qa:-?}s verdict: ${verdict:-UNKNOWN}"
365
+ echo "qa: $QA ${dur_qa:-?}s verdict: ${verdict:-UNKNOWN}$gate_note"
337
366
  echo "diff: $RUN/changes.diff"
338
367
  echo "read: $RUN/dwarf.last and $RUN/qa.last"
339
368
  echo
@@ -0,0 +1,389 @@
1
+ #!/usr/bin/env python3
2
+ """forge-submodules.py populate --source <repo> --worktree <wt> --out <file>
3
+
4
+ Give a worktree its submodules' files. `git worktree add` leaves every submodule path (a gitlink,
5
+ mode 160000) an empty directory; this fills each one, offline, from the checkout the worktree was
6
+ made from (<source>), and writes one TSV line per gitlink to <file>:
7
+
8
+ state<TAB>path<TAB>sha<TAB>detail
9
+
10
+ in index order, `sha` being the commit the worktree's index records. The states:
11
+
12
+ exported the source has the submodule's repository (.git/modules/<name>, or an old-style
13
+ <path>/.git) and it holds `sha`: `git archive <sha>` is extracted into the path
14
+ copied otherwise, the source's <path> has files: they are copied from its working tree
15
+ (real copies, never hardlinks; symlinks stay symlinks; any .git is skipped)
16
+ missing neither, or a failure (`detail` says which): the directory stays as it was
17
+ kept the path already holds files (a resumed run): left untouched
18
+
19
+ No `.git` is ever created under a populated path. Files there with no `.git` are invisible to the
20
+ superproject's git: `status` stays clean, `add -A` skips them, `worktree move` and `remove` work,
21
+ so every diff, fingerprint and merge gate forge takes is the same as with the empty directory. A
22
+ real submodule checkout would change all of that.
23
+
24
+ Never uses the network (every git call has protocol.allow=never and no lazy fetch), never runs
25
+ `git submodule`, fetch or clone, never writes any git config. With no gitlink, <file> is not
26
+ written. A failure on one submodule makes it `missing` and the others go on. Exit 0, or 2 on bad
27
+ arguments. Standard library only.
28
+ """
29
+ from __future__ import annotations
30
+
31
+ import argparse
32
+ import os
33
+ import shutil
34
+ import stat
35
+ import subprocess
36
+ import sys
37
+ import tarfile
38
+ import tempfile
39
+
40
+ GIT_TIMEOUT_S = 120
41
+ ARCHIVE_TIMEOUT_S = 600
42
+ GITLINK = '160000'
43
+ # Variables a calling git (a hook, `git rebase --exec`) may have set: they would point every
44
+ # call here at the caller's repository.
45
+ GIT_ENV_DROP = ('GIT_DIR', 'GIT_WORK_TREE', 'GIT_INDEX_FILE', 'GIT_COMMON_DIR', 'GIT_OBJECT_DIRECTORY',
46
+ 'GIT_ALTERNATE_OBJECT_DIRECTORIES', 'GIT_NAMESPACE', 'GIT_PREFIX')
47
+ NO_METADATA = 'source checkout has no submodule metadata; files copied from its working tree'
48
+
49
+
50
+ class Refused(Exception):
51
+ """This submodule cannot be populated; the message is the `detail`."""
52
+
53
+
54
+ class BadArguments(Exception):
55
+ """Exit 2."""
56
+
57
+
58
+ def git_env() -> dict:
59
+ env = {k: v for k, v in os.environ.items() if k not in GIT_ENV_DROP}
60
+ # A partial clone fetches a missing object on demand; nothing here may reach a remote.
61
+ env.update(GIT_NO_LAZY_FETCH='1', GIT_TERMINAL_PROMPT='0')
62
+ return env
63
+
64
+
65
+ def git_cmd(*args: str) -> list:
66
+ return ['git', '-c', 'protocol.allow=never', *args]
67
+
68
+
69
+ def git(*args: str, timeout: int = GIT_TIMEOUT_S) -> subprocess.CompletedProcess:
70
+ return subprocess.run(git_cmd(*args), capture_output=True, env=git_env(), timeout=timeout)
71
+
72
+
73
+ def first_line(data: bytes) -> str:
74
+ lines = data.decode('utf-8', 'replace').strip().splitlines()
75
+ return lines[0] if lines else ''
76
+
77
+
78
+ def is_dot_git(name: str) -> bool:
79
+ # case-folded: on a case-insensitive filesystem `.GIT` is a `.git`
80
+ return name.casefold() == '.git'
81
+
82
+
83
+ # ---- what the worktree has
84
+
85
+ def gitlinks(wt: str) -> list:
86
+ """[(path, sha)] in index order. An unmerged gitlink counts once, at stage 0 or else 2 (ours)."""
87
+ done = git('-C', wt, 'ls-files', '-s', '-z')
88
+ if done.returncode != 0:
89
+ raise BadArguments('--worktree %s is not a git worktree: %s' % (wt, first_line(done.stderr)))
90
+ order, chosen = [], {}
91
+ for entry in done.stdout.split(b'\0'):
92
+ if not entry:
93
+ continue
94
+ meta, _, path = entry.partition(b'\t')
95
+ mode, sha, stage = meta.decode().split(' ')
96
+ if mode != GITLINK:
97
+ continue
98
+ path = os.fsdecode(path)
99
+ if path not in chosen:
100
+ order.append(path)
101
+ chosen[path] = (stage, sha)
102
+ elif stage in ('0', '2') and chosen[path][0] not in ('0', '2'):
103
+ chosen[path] = (stage, sha)
104
+ return [(path, chosen[path][1]) for path in order]
105
+
106
+
107
+ def names(wt: str) -> dict:
108
+ """{path: name} from the worktree's .gitmodules; empty without one."""
109
+ gitmodules = os.path.join(wt, '.gitmodules')
110
+ if not os.path.isfile(gitmodules):
111
+ return {}
112
+ done = git('config', '-f', gitmodules, '-z', '--get-regexp', r'^submodule\..*\.path$')
113
+ found = {}
114
+ for entry in done.stdout.split(b'\0') if done.returncode == 0 else ():
115
+ key, _, value = os.fsdecode(entry).partition('\n')
116
+ if key.startswith('submodule.') and key.endswith('.path') and value:
117
+ found.setdefault(value, key[len('submodule.'):-len('.path')])
118
+ return found
119
+
120
+
121
+ # ---- where the source keeps the submodule's repository
122
+
123
+ def safe_name(name: str) -> bool:
124
+ # git refuses these too: a name is a path under .git/modules and must stay there
125
+ parts = name.replace('\\', '/').split('/')
126
+ return bool(name) and not os.path.isabs(name) and '..' not in parts
127
+
128
+
129
+ def rev_parse(source: str, *args: str) -> str | None:
130
+ done = git('-C', source, 'rev-parse', '--path-format=absolute', *args)
131
+ if done.returncode != 0:
132
+ return None
133
+ return os.fsdecode(done.stdout).strip() or None
134
+
135
+
136
+ def source_gitdir(source: str, path: str, name: str) -> str | None:
137
+ if safe_name(name):
138
+ # A linked worktree keeps the modules it initialized itself under .git/worktrees/<id>/
139
+ # (what --git-path gives); the ones its main worktree initialized are in the common dir.
140
+ candidates = [rev_parse(source, '--git-path', 'modules/' + name)]
141
+ common = rev_parse(source, '--git-common-dir')
142
+ candidates.append(common and os.path.join(common, 'modules', *name.split('/')))
143
+ for candidate in candidates:
144
+ if candidate and os.path.isdir(candidate):
145
+ return candidate
146
+ # old style: the submodule's repository, or a `gitdir:` file, at <source>/<path>/.git
147
+ sub = os.path.join(source, path)
148
+ dotgit = os.path.join(sub, '.git')
149
+ if os.path.isdir(dotgit):
150
+ return dotgit
151
+ if os.path.isfile(dotgit):
152
+ try:
153
+ with open(dotgit, encoding='utf-8', errors='replace') as fh:
154
+ line = fh.readline().strip()
155
+ except OSError:
156
+ return None
157
+ if line.startswith('gitdir:'):
158
+ target = os.path.join(sub, line[len('gitdir:'):].strip())
159
+ if os.path.isdir(target):
160
+ return os.path.normpath(target)
161
+ return None
162
+
163
+
164
+ # ---- filling a destination
165
+
166
+ def inside(path: str, root: str) -> bool:
167
+ return path == root or path.startswith(root.rstrip(os.sep) + os.sep)
168
+
169
+
170
+ def make_writable(path: str) -> None:
171
+ """Give `path` and the directories under it their owner's rwx: copy_tree keeps a source
172
+ directory's mode, and a read-only directory cannot have its entries removed."""
173
+ os.chmod(path, os.stat(path).st_mode | stat.S_IRWXU)
174
+ with os.scandir(path) as it:
175
+ for entry in it:
176
+ if entry.is_dir(follow_symlinks=False):
177
+ make_writable(entry.path)
178
+
179
+
180
+ def clear(dest: str) -> None:
181
+ """Empty `dest` after a failed attempt, so it is left as it was found."""
182
+ for entry in os.scandir(dest):
183
+ if entry.is_dir(follow_symlinks=False):
184
+ make_writable(entry.path)
185
+ shutil.rmtree(entry.path, ignore_errors=True)
186
+ else:
187
+ try:
188
+ os.unlink(entry.path)
189
+ except OSError:
190
+ pass
191
+
192
+
193
+ def member_parts(name: str) -> list:
194
+ if name.startswith('/') or os.path.isabs(name):
195
+ raise Refused('archive member refused: %s (absolute path)' % name)
196
+ parts = [p for p in name.split('/') if p not in ('', '.')]
197
+ if '..' in parts:
198
+ raise Refused('archive member refused: %s (.. component)' % name)
199
+ return parts
200
+
201
+
202
+ def no_link_on_the_way(dest: str, parts: list, name: str) -> None:
203
+ """Refuse to write through a symlink: no tree git makes needs it, and it is how a crafted
204
+ archive (`d -> elsewhere` then `d/x`) writes outside the destination."""
205
+ current = dest
206
+ for part in parts:
207
+ current = os.path.join(current, part)
208
+ if os.path.islink(current):
209
+ raise Refused('archive member refused: %s (path goes through a symlink)' % name)
210
+
211
+
212
+ def extract(archive, dest: str) -> None:
213
+ """Extract an uncompressed tar stream into `dest`, vetting every member."""
214
+ links = []
215
+ with tarfile.open(fileobj=archive, mode='r|') as tar:
216
+ for member in tar:
217
+ parts = member_parts(member.name)
218
+ if not parts or any(is_dot_git(p) for p in parts):
219
+ continue
220
+ target = os.path.join(dest, *parts)
221
+ if member.isdir():
222
+ no_link_on_the_way(dest, parts, member.name)
223
+ os.makedirs(target, exist_ok=True)
224
+ os.chmod(target, (member.mode & 0o777) | 0o700)
225
+ continue
226
+ no_link_on_the_way(dest, parts[:-1], member.name)
227
+ os.makedirs(os.path.dirname(target), exist_ok=True)
228
+ if member.issym():
229
+ linked = member.linkname
230
+ resolved = os.path.normpath(os.path.join(dest, *parts[:-1], linked))
231
+ if not linked or os.path.isabs(linked) or not inside(resolved, dest):
232
+ raise Refused('archive member refused: %s (link to %s, outside the submodule)'
233
+ % (member.name, linked))
234
+ os.symlink(linked, target)
235
+ links.append((member.name, target))
236
+ elif member.isreg():
237
+ fd = os.open(target, os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, 'O_NOFOLLOW', 0), 0o600)
238
+ with os.fdopen(fd, 'wb') as out:
239
+ shutil.copyfileobj(tar.extractfile(member), out)
240
+ os.fchmod(out.fileno(), member.mode & 0o777)
241
+ else:
242
+ raise Refused('archive member refused: %s (not a file, directory or symlink)' % member.name)
243
+ # Each link was checked on its own text; a chain (`b -> .`, `a -> b/..`) can still lead out.
244
+ real = os.path.realpath(dest)
245
+ for name, link in links:
246
+ if not inside(os.path.realpath(link), real):
247
+ raise Refused('archive member refused: %s (link resolves outside the submodule)' % name)
248
+
249
+
250
+ def export(gitdir: str, sha: str, dest: str) -> None:
251
+ with tempfile.TemporaryFile() as err:
252
+ proc = subprocess.Popen(git_cmd('--git-dir=' + gitdir, 'archive', '--format=tar', sha),
253
+ stdout=subprocess.PIPE, stderr=err, env=git_env())
254
+ try:
255
+ extract(proc.stdout, dest)
256
+ except (tarfile.TarError, OSError) as exc:
257
+ raise Refused('extracting git archive failed: %s' % exc) from exc
258
+ finally:
259
+ proc.stdout.close()
260
+ try:
261
+ code = proc.wait(timeout=ARCHIVE_TIMEOUT_S)
262
+ except subprocess.TimeoutExpired:
263
+ proc.kill()
264
+ code = proc.wait()
265
+ if code != 0:
266
+ err.seek(0)
267
+ raise Refused('git archive failed: %s' % (first_line(err.read()) or 'exit %d' % code))
268
+
269
+
270
+ def copy_tree(src: str, dest: str) -> None:
271
+ """Copy src's contents into dest: symlinks as symlinks, files as new files, .git skipped."""
272
+ for entry in os.scandir(src):
273
+ if is_dot_git(entry.name):
274
+ continue
275
+ target = os.path.join(dest, entry.name)
276
+ if entry.is_symlink():
277
+ os.symlink(os.readlink(entry.path), target)
278
+ elif entry.is_dir(follow_symlinks=False):
279
+ os.mkdir(target)
280
+ copy_tree(entry.path, target)
281
+ shutil.copymode(entry.path, target)
282
+ elif entry.is_file(follow_symlinks=False):
283
+ # copyfile writes a new file: never os.link, so the copy can be rewritten in place
284
+ shutil.copyfile(entry.path, target, follow_symlinks=False)
285
+ shutil.copymode(entry.path, target, follow_symlinks=False)
286
+ # sockets, fifos, devices: nothing to build with
287
+
288
+
289
+ def has_files(directory: str) -> bool:
290
+ try:
291
+ with os.scandir(directory) as it:
292
+ return any(not is_dot_git(e.name) for e in it)
293
+ except OSError:
294
+ return False
295
+
296
+
297
+ def populate_one(source: str, wt: str, path: str, sha: str, name: str) -> tuple:
298
+ """(state, detail) for one gitlink."""
299
+ dest = os.path.join(wt, path)
300
+ if os.path.islink(dest) or (os.path.lexists(dest) and not os.path.isdir(dest)):
301
+ return 'missing', 'the worktree has something other than a directory at this path'
302
+ if not inside(os.path.realpath(dest), os.path.realpath(wt)):
303
+ return 'missing', 'the path leads outside the worktree'
304
+ if os.path.isdir(dest) and any(True for _ in os.scandir(dest)):
305
+ return 'kept', ''
306
+ gitdir = source_gitdir(source, path, name)
307
+ fallback = NO_METADATA
308
+ if gitdir:
309
+ if git('--git-dir=' + gitdir, 'cat-file', '-e', sha + '^{commit}').returncode == 0:
310
+ os.makedirs(dest, exist_ok=True)
311
+ try:
312
+ export(gitdir, sha, dest)
313
+ except Exception as exc: # noqa: BLE001 whatever it was, this one is missing and the rest go on
314
+ clear(dest)
315
+ return 'missing', str(exc) if isinstance(exc, Refused) else 'exporting failed: %s' % exc
316
+ return 'exported', ''
317
+ fallback = ("the source's submodule repository does not have the recorded commit; "
318
+ 'files copied from its working tree')
319
+ src = os.path.join(source, path)
320
+ if os.path.isdir(src) and has_files(src):
321
+ os.makedirs(dest, exist_ok=True)
322
+ try:
323
+ copy_tree(src, dest)
324
+ except Exception as exc: # noqa: BLE001
325
+ clear(dest)
326
+ return 'missing', 'copying from the source checkout failed: %s' % exc
327
+ return 'copied', fallback
328
+ if gitdir:
329
+ return 'missing', "the source's submodule repository does not have the recorded commit"
330
+ return 'missing', 'the source checkout has neither the submodule repository nor its files'
331
+
332
+
333
+ def field(text: str) -> str:
334
+ return text.replace('\t', ' ').replace('\n', ' ').replace('\r', ' ')
335
+
336
+
337
+ def write_atomically(out: str, text: str) -> None:
338
+ directory = os.path.dirname(os.path.abspath(out))
339
+ os.makedirs(directory, exist_ok=True)
340
+ fd, tmp = tempfile.mkstemp(dir=directory, prefix='.' + os.path.basename(out) + '.')
341
+ try:
342
+ with os.fdopen(fd, 'w', encoding='utf-8') as fh:
343
+ fh.write(text)
344
+ os.replace(tmp, out)
345
+ except BaseException:
346
+ try:
347
+ os.unlink(tmp)
348
+ except OSError:
349
+ pass
350
+ raise
351
+
352
+
353
+ def populate(source: str, wt: str, out: str) -> int:
354
+ links = gitlinks(wt)
355
+ if not links:
356
+ return 0
357
+ by_path = names(wt)
358
+ lines = []
359
+ for path, sha in links:
360
+ try:
361
+ state, detail = populate_one(source, wt, path, sha, by_path.get(path, path))
362
+ except Exception as exc: # noqa: BLE001
363
+ state, detail = 'missing', 'populating failed: %s' % exc
364
+ lines.append('\t'.join((state, field(path), sha, field(detail))) + '\n')
365
+ write_atomically(out, ''.join(lines))
366
+ return 0
367
+
368
+
369
+ def main(argv: list) -> int:
370
+ parser = argparse.ArgumentParser(prog='forge-submodules.py', description=__doc__.split('\n\n')[1])
371
+ sub = parser.add_subparsers(dest='command', required=True)
372
+ pop = sub.add_parser('populate', help="fill a worktree's submodule paths from the source checkout")
373
+ pop.add_argument('--source', required=True, help='the checkout the worktree was made from')
374
+ pop.add_argument('--worktree', required=True, help='the worktree to populate')
375
+ pop.add_argument('--out', required=True, help='where the TSV outcome is written')
376
+ args = parser.parse_args(argv)
377
+ source, wt = os.path.abspath(args.source), os.path.abspath(args.worktree)
378
+ for label, directory in (('--source', source), ('--worktree', wt)):
379
+ if not os.path.isdir(directory):
380
+ parser.error('%s %s is not a directory' % (label, directory))
381
+ try:
382
+ return populate(source, wt, args.out)
383
+ except BadArguments as exc:
384
+ print('forge-submodules: %s' % exc, file=sys.stderr)
385
+ return 2
386
+
387
+
388
+ if __name__ == '__main__':
389
+ sys.exit(main(sys.argv[1:]))
@@ -29,21 +29,24 @@ def _human(n: int) -> str:
29
29
 
30
30
 
31
31
  def _continued_sessions(db) -> dict:
32
- """How many dispatches asked to continue a reviewer session.
32
+ """How many dispatches asked to continue a session: reviewers' and implementers' apart.
33
33
 
34
34
  Counted from the dispatch events themselves. A shadow review is not required, and a
35
35
  continue that failed still counts: the file was written because continuing was requested.
36
36
  """
37
- continued = failed = 0
37
+ counts = dict(continued_reviews=0, failed_continues=0,
38
+ continued_implementers=0, failed_implementer_continues=0)
38
39
  for (raw,) in db.execute(
39
40
  "SELECT data FROM events WHERE kind = 'dispatch' AND data LIKE ?",
40
41
  ('%"session_continue": "%',)):
41
- value = json.loads(raw).get('session_continue')
42
+ data = json.loads(raw)
43
+ value = data.get('session_continue')
44
+ dwarf = data.get('role') == 'dwarf'
42
45
  if value == 'continued':
43
- continued += 1
46
+ counts['continued_implementers' if dwarf else 'continued_reviews'] += 1
44
47
  elif value == 'failed':
45
- failed += 1
46
- return dict(continued_reviews=continued, failed_continues=failed)
48
+ counts['failed_implementer_continues' if dwarf else 'failed_continues'] += 1
49
+ return counts
47
50
 
48
51
 
49
52
  def status(args) -> int:
@@ -99,6 +102,9 @@ def status(args) -> int:
99
102
  if summary.get('continued_reviews') or summary.get('failed_continues'):
100
103
  print(' continued reviews: %d' % summary['continued_reviews'])
101
104
  print(' failed continues: %d' % summary['failed_continues'])
105
+ if summary.get('continued_implementers') or summary.get('failed_implementer_continues'):
106
+ print(' continued implementers: %d' % summary['continued_implementers'])
107
+ print(' failed implementer continues: %d' % summary['failed_implementer_continues'])
102
108
  if summary['legacy_archives']:
103
109
  print(' legacy: %d archived run dir(s) kept in %s (`forge dataset import %s` re-reads them;'
104
110
  ' events already stored are skipped)' % (summary['legacy_archives'], legacy, legacy))