@giamme/forge 0.12.1 → 0.13.1

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 (111) hide show
  1. package/CHANGELOG.md +66 -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 +14 -4
  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 +763 -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 +22 -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 +457 -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 +39 -9
  50. package/scripts/forge-submodules.py +389 -0
  51. package/scripts/forge-ui-options.sh +25 -0
  52. package/scripts/forge_dataset/cli.py +12 -6
  53. package/scripts/forge_dataset/export.py +140 -84
  54. package/scripts/forge_dataset/harvest.py +33 -5
  55. package/scripts/{forge_jev/outcome.py → forge_dataset/states.py} +21 -7
  56. package/scripts/forge_decide/__init__.py +141 -0
  57. package/scripts/forge_decide/budget.py +180 -0
  58. package/scripts/forge_decide/cache.py +66 -0
  59. package/scripts/forge_decide/cli.py +953 -0
  60. package/scripts/forge_decide/doctor.py +270 -0
  61. package/scripts/forge_decide/label_addressed.py +75 -0
  62. package/scripts/forge_decide/label_attribution.py +62 -0
  63. package/scripts/forge_decide/label_coverage.py +81 -0
  64. package/scripts/forge_decide/label_message.py +38 -0
  65. package/scripts/forge_decide/label_prompt.py +139 -0
  66. package/scripts/forge_decide/labels.py +328 -0
  67. package/scripts/forge_decide/metrics.py +125 -0
  68. package/scripts/forge_decide/migrate.py +226 -0
  69. package/scripts/forge_decide/providers.py +292 -0
  70. package/scripts/forge_decide/replay.py +350 -0
  71. package/scripts/forge_decide/report.py +382 -0
  72. package/scripts/forge_decide/resolve.py +397 -0
  73. package/scripts/forge_decide/sites.py +377 -0
  74. package/scripts/forge_jev/__init__.py +202 -104
  75. package/scripts/forge_jev/addressed.py +171 -0
  76. package/scripts/forge_jev/attribution.py +198 -0
  77. package/scripts/forge_jev/cli.py +460 -382
  78. package/scripts/forge_jev/client.py +155 -77
  79. package/scripts/forge_jev/coupling.py +19 -87
  80. package/scripts/forge_jev/coverage.py +303 -0
  81. package/scripts/forge_jev/findings.py +219 -0
  82. package/scripts/forge_jev/gates.py +225 -27
  83. package/scripts/forge_jev/memory.py +65 -4
  84. package/scripts/forge_jev/message.py +134 -0
  85. package/scripts/forge_jev/plan_gates.py +294 -0
  86. package/scripts/forge_jev/questions.py +173 -313
  87. package/scripts/forge_jev/verify.py +130 -104
  88. package/ui/README.md +2 -2
  89. package/ui/docs/api.md +92 -39
  90. package/ui/forge_ui/control.py +71 -14
  91. package/ui/forge_ui/export.py +2 -1
  92. package/ui/forge_ui/models.py +17 -16
  93. package/ui/forge_ui/reader.py +132 -21
  94. package/ui/forge_ui/repos.py +428 -0
  95. package/ui/forge_ui/static/app.js +24 -5
  96. package/ui/forge_ui/static/cloudmodel.js +8 -5
  97. package/ui/forge_ui/static/controls.js +20 -13
  98. package/ui/forge_ui/static/modelstats.js +12 -8
  99. package/ui/forge_ui/static/panel.js +63 -17
  100. package/ui/forge_ui/static/runmodel.js +48 -7
  101. package/ui/forge_ui/static/scene3d.js +2 -15
  102. package/ui/forge_ui/static/settings.js +481 -68
  103. package/ui/forge_ui/static/style.css +56 -9
  104. package/references/jev.md +0 -865
  105. package/scripts/forge_jev/backtest.py +0 -322
  106. package/scripts/forge_jev/corpus.py +0 -156
  107. package/scripts/forge_jev/features.py +0 -24
  108. package/scripts/forge_jev/predict.py +0 -204
  109. package/scripts/forge_jev/review.py +0 -73
  110. package/scripts/forge_jev/routing.py +0 -271
  111. 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
@@ -192,6 +200,7 @@ fi
192
200
 
193
201
  # The dispatches see a review snapshot, not the repo, so the run dir names it for the dataset.
194
202
  [ "$DRY" = 1 ] || printf '%s\n' "$REPO" > "$RUN/repo"
203
+ [ "$DRY" = 1 ] || forge_repo_identity "$REPO" "$RUN"
195
204
  # Every real run, --ui or not: forge-ui's view of this repo's runs reads the registry.
196
205
  [ "$DRY" = 1 ] || forge_ui_register "$RUN"
197
206
  # Recorded before any dispatch: forge-ui opens this dir immediately, and a re-run
@@ -281,11 +290,18 @@ REVIEW="$RUN/review-$(date +%s)-$$"
281
290
  forge_review_snapshot "$REPO" "$START" "$END" "$REVIEW" || die "cannot create review snapshot" 3
282
291
  SOURCE_FP="$(forge_fingerprint "$REPO")" || exit 3
283
292
  [ "$(forge_tree "$REPO")" = "$END" ] || { echo INVALIDATED > "$RUN/verdict"; die "source changed while preparing QA" 5; }
284
- REVIEW_FP="$(forge_fingerprint "$REVIEW")" || exit 3
293
+ # The review snapshot is a commit; the reviewer's untracked leftovers there do not count (#95).
294
+ # The source keeps them: in a solo run the implementer's new files are untracked.
295
+ REVIEW_FP="$(forge_fingerprint "$REVIEW" --tracked)" || exit 3
285
296
  printf '%s\n' "$SOURCE_FP" > "$RUN/source.fingerprint"
286
297
  printf '%s\n' "$REVIEW_FP" > "$RUN/review.fingerprint"
287
298
  forge_metric_phase preparation
288
299
  # --- qa -----------------------------------------------------------------------
300
+ # The blocking threshold: this invocation's flag (kept in the run dir), else the file, else P2.
301
+ [ -z "$QA_THR" ] || printf '%s\n' "$QA_THR" > "$RUN/qa_threshold"
302
+ THR="$(head -1 "$RUN/qa_threshold" 2>/dev/null | tr -d ' \r' | tr 'a-z' 'A-Z')"
303
+ case "$THR" in P0|P1|P2|P3) ;; NONE) THR=P3 ;; *) THR="$FORGE_QA_THRESHOLD_DEFAULT" ;; esac
304
+ rm -f "$RUN/qa.gate" "$RUN/known_issues.md"
289
305
  rm -f "$RUN/failfirst.json" "$RUN/failfirst.txt"
290
306
  if [ "$FAIL_FIRST" = 1 ]; then
291
307
  # Opt-in and advisory: the reviewer reads the evidence; nothing here changes a verdict.
@@ -298,7 +314,7 @@ fi
298
314
  python3 "$SKILL_DIR/scripts/forge-contract.py" qa --part head --kind solo
299
315
  echo
300
316
  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
317
+ python3 "$SKILL_DIR/scripts/forge-contract.py" qa --part tail --kind solo --threshold "$THR"
302
318
  echo
303
319
  # --irreversible-delete: a deleted file shows as a header, not every line it had (one deleted
304
320
  # data directory once made a 7.1M-character prompt that the reviewer's CLI refused).
@@ -315,7 +331,7 @@ rc=$?
315
331
  forge_metric_phase verification
316
332
  verdict="$(forge_verdict "$RUN/qa.last")"
317
333
  [ -n "$NATIVE" ] && verdict=UNKNOWN
318
- if [ "$(forge_fingerprint "$REPO")" != "$SOURCE_FP" ] || [ "$(forge_fingerprint "$REVIEW")" != "$REVIEW_FP" ]; then
334
+ if [ "$(forge_fingerprint "$REPO")" != "$SOURCE_FP" ] || [ "$(forge_fingerprint "$REVIEW" --tracked)" != "$REVIEW_FP" ]; then
319
335
  echo INVALIDATED > "$RUN/verdict"
320
336
  die "source or review artifact changed during QA; review invalidated" 5
321
337
  fi
@@ -329,11 +345,25 @@ dur_qa="$(sed -n 's/^duration_s=//p' "$RUN/qa.resolved" 2>/dev/null | tail -1)"
329
345
 
330
346
  # --native-review is codex's own reviewer, which refuses a custom prompt alongside
331
347
  # its scope flags — so it never sees the verdict instruction and cannot emit one.
348
+ # Otherwise forge enforces the severity rule itself, as a decomposed task's gate does; a gate
349
+ # that cannot run (no output) keeps the reviewer's verdict.
350
+ gate_note=""
351
+ if [ -z "$NATIVE" ]; then
352
+ gate_line="$(python3 "$SKILL_DIR/scripts/forge-contract.py" gate --verdict "${verdict:-UNKNOWN}" \
353
+ --qa-last "$RUN/qa.last" --threshold "$THR" --known-issues "$RUN/known_issues.md" 2>/dev/null)" || gate_line=""
354
+ if [ -n "$gate_line" ]; then
355
+ printf '%s\t%s\n' "$THR" "$gate_line" > "$RUN/qa.gate"
356
+ case "$(printf '%s' "$gate_line" | awk -F'\t' '{print $1}')" in
357
+ accept) verdict=PASS; gate_note=" (accepted with known issues: $RUN/known_issues.md)" ;;
358
+ fail) verdict=FAIL; gate_note=" (the reviewer said PASS, but listed a CONFIRMED finding at or above the $THR threshold — forge made it FAIL)" ;;
359
+ esac
360
+ fi
361
+ fi
332
362
  echo "${verdict:-UNKNOWN}" > "$RUN/verdict"
333
363
 
334
364
  echo
335
365
  echo "dwarf: $DWARF ${dur_dwarf:-?}s"
336
- echo "qa: $QA ${dur_qa:-?}s verdict: ${verdict:-UNKNOWN}"
366
+ echo "qa: $QA ${dur_qa:-?}s verdict: ${verdict:-UNKNOWN}$gate_note"
337
367
  echo "diff: $RUN/changes.diff"
338
368
  echo "read: $RUN/dwarf.last and $RUN/qa.last"
339
369
  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:]))
@@ -40,3 +40,28 @@ forge_ui_register() {
40
40
  python3 -I "$SKILL_DIR/scripts/forge_registry.py" register "$1" </dev/null >/dev/null 2>&1 || true
41
41
  return 0
42
42
  }
43
+
44
+ # forge_repo_identity CHECKOUT DIR — write DIR/repo.identity, the repository CHECKOUT belongs to:
45
+ # {"root", "worktree", "branch"}. root is the main working tree, the same for the main checkout
46
+ # and every linked worktree; worktree is CHECKOUT's physical path when it differs from root, else
47
+ # null; branch is its branch, null when HEAD is detached. It names the repository after a
48
+ # worktree is removed, which the path in `repo` cannot. Written once, at creation: an existing
49
+ # file stays.
50
+ # Best effort like forge_ui_register: a failure leaves no file, and this always returns 0 and
51
+ # prints nothing. Callers skip it in a --dry-run.
52
+ forge_repo_identity() {
53
+ local checkout="${1:-}" dir="${2:-}" root phys rootphys worktree="" branch tmp
54
+ [ -n "$dir" ] && [ ! -e "$dir/repo.identity" ] || return 0
55
+ root="$(git -C "$checkout" worktree list --porcelain 2>/dev/null | awk '/^worktree /{ sub(/^worktree /, ""); print; exit }')"
56
+ [ -n "$root" ] || return 0
57
+ phys="$(cd "$checkout" 2>/dev/null && pwd -P)" || return 0
58
+ rootphys="$(cd "$root" 2>/dev/null && pwd -P)" || return 0
59
+ [ "$phys" = "$rootphys" ] || worktree="$phys"
60
+ branch="$(git -C "$checkout" symbolic-ref --short -q HEAD 2>/dev/null)"
61
+ tmp="$dir/repo.identity.$$.tmp"
62
+ # The values go in as arguments, never into the code. The redirect and mv sit in the group,
63
+ # so a refused write is silent too.
64
+ { python3 -I -c 'import json, sys; r, w, b = sys.argv[1:4]; print(json.dumps({"root": r, "worktree": w or None, "branch": b or None}, separators=(",", ":")))' "$root" "$worktree" "$branch" > "$tmp" \
65
+ && mv "$tmp" "$dir/repo.identity"; } 2>/dev/null || rm -f "$tmp" 2>/dev/null
66
+ return 0
67
+ }