@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
@@ -15,6 +15,9 @@
15
15
  record_attempt() { # record_attempt <plan> <id>
16
16
  local tdir="$1/tasks/$2" cls=""
17
17
  [ "$(task_status "$1" "$2")" = BLOCKED ] && return 0 # never started: nothing to audit
18
+ # Implemented, awaiting its group's review (#140): no review judged this attempt yet. The row is
19
+ # written when the group verdict judges it (record_judged_attempt).
20
+ [ "$(task_status "$1" "$2")" = IMPLEMENTED ] && return 0
18
21
  [ "$(task_status "$1" "$2")" = INFRA ] && cls="$(sed -n 's/^class=//p' "$tdir/infra.txt" 2>/dev/null | head -1)"
19
22
  # A send-back that no reviewer judged keeps the task status FAIL; attempts.tsv names its kind.
20
23
  local st; st="$(task_status "$1" "$2")"
@@ -24,6 +27,96 @@ record_attempt() { # record_attempt <plan> <id>
24
27
  "$st" "$cls" "$(field "$1/tasks.tsv" "$2" dwarf)" >> "$tdir/attempts.tsv"
25
28
  }
26
29
 
30
+ # The row a group verdict writes for a member's attempt (#140), in record_attempt's format, with the
31
+ # status the verdict gave it and the attempt the member is on now.
32
+ record_judged_attempt() { # record_judged_attempt <plan> <id> <status>
33
+ local tdir="$1/tasks/$2"
34
+ printf '%s\t%s\t%s\t%s\t%s\n' "$(date +%s)" "$(cat "$tdir/attempt" 2>/dev/null || echo 0)" \
35
+ "$3" "" "$(field "$1/tasks.tsv" "$2" dwarf)" >> "$tdir/attempts.tsv"
36
+ }
37
+
38
+ # What follows every attempt that was judged: the escalation check, then the decision a FAIL may stop
39
+ # for. do_task runs it after its own attempt, and a group verdict runs it after judging a member's.
40
+ # An IMPLEMENTED or STALE attempt was not judged, so neither step runs for it.
41
+ post_attempt() { # post_attempt <plan> <id>
42
+ local crc=0 stop_before
43
+ [ "$(task_status "$1" "$2")" = IMPLEMENTED ] && return 0
44
+ # A STALE attempt (its prompt changed while it ran, #150) was not judged and spends nothing.
45
+ [ "$(task_status "$1" "$2")" = STALE ] && return 0
46
+ # A FAIL whose every blocking finding needs a file this task does not declare is the plan's fault (#149):
47
+ # stop for a decision now, before the escalation check can write a marker for a model that cannot help.
48
+ if outside_stop_check "$1" "$2"; then
49
+ python3 "$SKILL_DIR/scripts/forge-ledger.py" append "$1" "$2" >/dev/null 2>&1 \
50
+ || note "$2: could not add this review to the findings ledger"
51
+ # A write that fails leaves the task FAIL. Continuing would append this review to the
52
+ # ledger again and let the escalation check mark a model that cannot fix the plan.
53
+ stop_for_decision "$1" "$2" plan || return 1
54
+ return 0
55
+ else
56
+ rm -f "$1/tasks/$2/outside.json"
57
+ fi
58
+ # The retry policy's state (escalation.next or escalation.stop), decided now rather than
59
+ # at the next retry so a spent retry budget still reports it and the scheduler sees it.
60
+ stop_before="$(cat "$1/tasks/$2/escalation.stop" 2>/dev/null)"
61
+ python3 "$SKILL_DIR/scripts/forge-route.py" escalation --plan "$1" --task "$2" --check \
62
+ --qa-only-next "$(qa_only_next_flag "$1" "$2")" >/dev/null 2>&1 || crc=$?
63
+ # A FAIL that does not converge, or that the policy could not move to a stronger model, waits
64
+ # for a person (NEEDS_DECISION). attempts.tsv was written above and keeps FAIL.
65
+ decision_after_attempt "$1" "$2" "$stop_before" "$crc"
66
+ }
67
+
68
+ # Whether the last review's every blocking finding needs a file outside the task (#149). 0 only when the
69
+ # task is FAIL on a real review, at least one finding blocks at the task's threshold, each of those carries
70
+ # {outside=...}, and no path it names is declared by the task itself. Writes tasks/<id>/outside.json:
71
+ # [{path, owner, owners, owner_status}], owner_status being the owner's task_status (null for no owner).
72
+ # Any tool error returns non-zero and writes nothing.
73
+ outside_stop_check() { # outside_stop_check <plan> <id>
74
+ local PLAN="$1" id="$2" tdir="$1/tasks/$2" thr rep paths owned tmp="$1/tasks/$2/.outside.json.tmp" p
75
+ local -a plist=()
76
+ [ "$(task_status "$PLAN" "$id")" = FAIL ] || return 1
77
+ [ -s "$tdir/qa.last" ] || return 1
78
+ case "$(forge_verdict "$tdir/qa.last" 2>/dev/null)" in PASS|FAIL) ;; *) return 1 ;; esac
79
+ thr="$(qa_threshold_for "$PLAN" "$id")" || return 1
80
+ rep="$(python3 "$SKILL_DIR/scripts/forge-contract.py" outside --qa-last "$tdir/qa.last" --threshold "$thr" 2>/dev/null)" || return 1
81
+ paths="$(printf '%s' "$rep" | python3 -c '
82
+ import json, sys
83
+ rows = json.load(sys.stdin)
84
+ blocking = [r for r in rows if r.get("blocking")]
85
+ if not blocking or any(not r.get("outside") for r in blocking):
86
+ sys.exit(1)
87
+ seen = []
88
+ for r in blocking:
89
+ for p in r["outside"]:
90
+ if p not in seen:
91
+ seen.append(p)
92
+ print("\n".join(seen))
93
+ ' 2>/dev/null)" || return 1
94
+ [ -n "$paths" ] || return 1
95
+ while IFS= read -r p; do plist+=("$p"); done <<< "$paths"
96
+ owned="$(python3 "$SKILL_DIR/scripts/forge_owner.py" "$PLAN" "${plist[@]}" --task "$id" 2>/dev/null)" || return 1
97
+ printf '%s' "$owned" | python3 -c '
98
+ import json, os, sys
99
+ plan = sys.argv[1]
100
+ items = json.load(sys.stdin)["paths"]
101
+ if not items or any(i["outside"] is not True for i in items):
102
+ sys.exit(1)
103
+ def status(task):
104
+ base = os.path.join(plan, "tasks", task)
105
+ if os.path.exists(os.path.join(base, "merged")):
106
+ return "MERGED"
107
+ try:
108
+ with open(os.path.join(base, "status"), encoding="utf-8") as f:
109
+ return f.read().strip()
110
+ except OSError:
111
+ return "PENDING"
112
+ out = [{"path": i["path"], "owner": i["owner"], "owners": i["owners"],
113
+ "owner_status": status(i["owner"]) if i["owner"] else None} for i in items]
114
+ json.dump(out, sys.stdout, indent=1)
115
+ sys.stdout.write("\n")
116
+ ' "$PLAN" > "$tmp" 2>/dev/null && mv "$tmp" "$tdir/outside.json" || { rm -f "${tmp:?}"; return 1; }
117
+ return 0
118
+ }
119
+
27
120
  # --- infrastructure stops -------------------------------------------------------
28
121
  # A dispatch that failed because of quota, auth, a rate limit, the network or empty
29
122
  # output says nothing about the work. The task is marked INFRA and the attempt is not
@@ -389,6 +482,29 @@ carry_implementer_session() { # carry_implementer_session <tdir>
389
482
  }
390
483
 
391
484
  # --- reviewer-session continuation (plan --reviewer-session, an opt-in experiment) ------------
485
+ # reviewer_session_pick <plan> <rate>: the task ids whose reviews continue under
486
+ # --reviewer-session-rate, one per line. Within each difficulty, round(rate x n) tasks with the
487
+ # lowest sha256 of "<run id>/<task id>", so the halves are balanced by difficulty and stable.
488
+ reviewer_session_pick() {
489
+ python3 - "$1/tasks.tsv" "$(cat "$1/run_id" 2>/dev/null || basename "$1")" "$2" <<'PY'
490
+ import hashlib, sys
491
+ from collections import defaultdict
492
+ rows = [line.split('\t') for line in open(sys.argv[1], encoding='utf-8').read().splitlines()
493
+ if line and not line.startswith('#')]
494
+ run, rate = sys.argv[2], float(sys.argv[3])
495
+ tiers = defaultdict(list)
496
+ for row in rows:
497
+ tiers[row[2] if len(row) > 2 else ''].append(row[0])
498
+ keep = set()
499
+ for ids in tiers.values():
500
+ ids.sort(key=lambda i: hashlib.sha256(('%s/%s' % (run, i)).encode()).hexdigest())
501
+ keep.update(ids[:int(rate * len(ids) + 0.5)])
502
+ for row in rows:
503
+ if row[0] in keep:
504
+ print(row[0])
505
+ PY
506
+ }
507
+
392
508
  # review_session_decide <session-file> <resolved-file> <resolution-file> [harnesses]: whether this
393
509
  # round continues the earlier session. Prints `mode<TAB>reason<TAB>session`; the session is the
394
510
  # id to continue, and empty for every fresh answer.
@@ -502,6 +618,7 @@ decision_reason_text() { # decision_reason_text <reason>: what a reason in decis
502
618
  case "$1" in
503
619
  converging) echo "the last reviews failed one after another, most of their findings were new, and the worst severity did not improve: more attempts keep finding new problems instead of closing the old ones" ;;
504
620
  split) echo "the retry policy found no stronger model to escalate to after repeated failures on one: another attempt on the same model rarely passes" ;;
621
+ plan) echo "every blocking finding of the last review needs a change in a file this task does not declare: the plan, not the implementer, has to change" ;;
505
622
  cap) echo "the attempts spent across runs reach the task's cap (max_attempts, plus each retry=N a person granted): another attempt needs a person's retry=N" ;;
506
623
  *) echo "$1" ;;
507
624
  esac
@@ -596,6 +713,27 @@ stop_for_decision() { # stop_for_decision <plan> <id> <reason>...
596
713
  read -r used cap <<< "$(attempt_cap_of "$PLAN" "$id")"
597
714
  if [ "$cap" = - ]; then echo "Attempts used so far: $used (no cap)"; else echo "Attempts used so far: $used (attempts $used of $cap)"; fi
598
715
  echo
716
+ case ",${reasons// /}," in *,plan,*)
717
+ if [ -s "$tdir/outside.json" ]; then
718
+ echo "Files outside this task:"
719
+ python3 - "$tdir/outside.json" <<'PYEOF' 2>/dev/null
720
+ import json, sys
721
+ for item in json.load(open(sys.argv[1], encoding="utf-8")):
722
+ if item.get("owner"):
723
+ print(" %s \u2014 declared by %s (%s)" % (item["path"], item["owner"], item.get("owner_status") or "PENDING"))
724
+ else:
725
+ print(" %s \u2014 declared by no task" % item["path"])
726
+ PYEOF
727
+ echo
728
+ echo "Plan choices (this is a change of the plan, edit $PLAN/tasks.tsv):"
729
+ echo " 1. add the path to this task's files"
730
+ echo " 2. make this task depend on the owner (edit its deps)"
731
+ echo " 3. merge the two rows into one task"
732
+ echo " After editing tasks.tsv: forge-parallel.sh plan $PLAN again when no run is live, then"
733
+ echo " forge-parallel.sh retry $PLAN $id --decide retry=1 --reason \"...\" --approved"
734
+ echo
735
+ fi ;;
736
+ esac
599
737
  echo "Choices (each needs your reason; --approved says the decision is yours):"
600
738
  echo " N more attempts: forge-parallel.sh retry $PLAN $id --decide retry=N --reason \"...\" --approved"
601
739
  case ",${reasons// /}," in
@@ -628,7 +766,10 @@ decision_after_attempt() { # decision_after_attempt <plan> <id> <stop-before> <c
628
766
  python3 "$SKILL_DIR/scripts/forge-ledger.py" append "$PLAN" "$id" >/dev/null 2>&1 \
629
767
  || note "$id: could not add this review to the findings ledger"
630
768
  [ "$(task_status "$PLAN" "$id")" = FAIL ] || return 0
631
- if python3 "$SKILL_DIR/scripts/forge-ledger.py" signal "$tdir" >/dev/null 2>&1; then reasons="converging"; fi
769
+ # A scripted task's reviews judge the same command again, not findings a person closes one by one:
770
+ # no convergence count (#142).
771
+ if [ "$(field "$PLAN/tasks.tsv" "$id" dwarf)" != script ] \
772
+ && python3 "$SKILL_DIR/scripts/forge-ledger.py" signal "$tdir" >/dev/null 2>&1; then reasons="converging"; fi
632
773
  stop="$(cat "$tdir/escalation.stop" 2>/dev/null)"
633
774
  if [ -n "$stop" ] && { [ "$crc" = 3 ] || [ "$stop" != "$before" ]; }; then reasons="${reasons:+$reasons }split"; fi
634
775
  read -r used cap <<< "$(attempt_cap_of "$PLAN" "$id")"
@@ -826,7 +967,7 @@ prepare_retry() { # prepare_retry <plan> <id> [new-dwarf [decided]]
826
967
  # (default 3) the next attempt goes a tier up in the user's own pools instead of repeating
827
968
  # the dispatch whose fourth try passes least often, or the task stops with a split
828
969
  # suggestion.
829
- local cur next rc esc_source="" pinned="" has_pin=0
970
+ local cur next rc esc_source="" pinned="" has_pin=0 per_model=""
830
971
  cur="$(field "$T" "$id" dwarf)"
831
972
  [ -f "$tdir/escalation.pin" ] && [ ! -L "$tdir/escalation.pin" ] && has_pin=1
832
973
  if [ -n "$newdwarf" ]; then
@@ -853,7 +994,18 @@ prepare_retry() { # prepare_retry <plan> <id> [new-dwarf [decided]]
853
994
  return 3
854
995
  fi
855
996
  if [ -n "$next" ]; then
856
- note "$id: escalating from $cur to $next after $(cat "$PLAN/escalate_after" 2>/dev/null || echo 3) failed attempts on one model (--escalate-after 0 turns this off)"
997
+ # retry_per_model replaces escalate_after (forge-route.py escalation). The note names the
998
+ # count that moved the task, and does not point at a flag that no longer governs the plan.
999
+ per_model="$(tr -d '[:space:]' < "$PLAN/retry_per_model" 2>/dev/null || true)"
1000
+ case "$per_model" in
1001
+ [1-9]|[1-9][0-9]) ;;
1002
+ *) per_model="" ;;
1003
+ esac
1004
+ if [ -n "$per_model" ]; then
1005
+ note "$id: escalating from $cur to $next after $per_model failed attempts on one model"
1006
+ else
1007
+ note "$id: escalating from $cur to $next after $(cat "$PLAN/escalate_after" 2>/dev/null || echo 3) failed attempts on one model (--escalate-after 0 turns this off)"
1008
+ fi
857
1009
  newdwarf="$next"
858
1010
  esc_source=policy
859
1011
  fi
@@ -1002,12 +1154,53 @@ prepare_fallback() { # prepare_fallback <plan> <id> <excluded harness/model,...>
1002
1154
  fi
1003
1155
  }
1004
1156
 
1157
+ # The next entry of a STALE task (#150): its prompt or approach changed while the attempt ran, so the
1158
+ # attempt was not reviewed and spent nothing. The attempt number is given back (as a dwarf-stage infra
1159
+ # stop does), the implementer is told what changed, and no escalation, decision or attempt-cap gate runs:
1160
+ # nothing was spent. The status is cleared by the caller.
1161
+ prepare_prompt_retry() { # prepare_prompt_retry <plan> <id>
1162
+ local PLAN="$1" id="$2" tdir="$1/tasks/$2" st attempt n
1163
+ st="$(task_status "$PLAN" "$id")"
1164
+ if [ "$st" != STALE ]; then
1165
+ note "$id: is $st, not STALE; --prompt only prepares a task whose prompt changed during its attempt"
1166
+ return 2
1167
+ fi
1168
+ attempt="$(cat "$tdir/attempt" 2>/dev/null)"
1169
+ case "$attempt" in ''|*[!0-9]*) attempt=0 ;; esac
1170
+ [ "$attempt" -gt 0 ] && echo $((attempt - 1)) > "$tdir/attempt"
1171
+ {
1172
+ printf 'The requirements changed while you worked on this task. The full new requirements are above; what changed follows.\n\n'
1173
+ printf 'Bring your committed work in line with the new text, keep what still holds, and explain anything you change.\n\n'
1174
+ printf '```diff\n'
1175
+ cat "$tdir/stale.diff" 2>/dev/null
1176
+ printf '```\n'
1177
+ } > "$tdir/.retry_findings.md.tmp" && mv "$tdir/.retry_findings.md.tmp" "$tdir/retry_findings.md" || return 1
1178
+ printf 'prompt\n' > "$tdir/.retry_findings.source.tmp" && mv "$tdir/.retry_findings.source.tmp" "$tdir/retry_findings.source" || return 1
1179
+ rm -f "$tdir/retry_findings.commit" "$tdir/resume" "$tdir/retry_findings.session" "$tdir/retry_findings.resolved"
1180
+ if [ -f "$PLAN/implementer_session" ]; then
1181
+ carry_implementer_session "$tdir"
1182
+ else
1183
+ for n in session resolved; do rm -f "$tdir/retry_findings.dwarf.$n"; done
1184
+ fi
1185
+ # The stale attempt was never reviewed, and the requirements it worked from are gone. A re-dispatch
1186
+ # that keeps its committed work (a wording fix needs no code change) must be reviewed, not refused as
1187
+ # "identical to the previous attempt": forge-parallel.sh compares the new diff with changes.prev.diff,
1188
+ # which a dwarf stage fills from changes.diff, so neither is left for it to compare. The stale diff of
1189
+ # the prompt (stale.diff) and committed.diff stay as the record.
1190
+ rm -f "$tdir/changes.diff" "$tdir/changes.prev.diff"
1191
+ rm -f "$tdir/status" "$tdir/noretry"
1192
+ }
1193
+
1005
1194
  # The scheduler's `_prepare_retry` target: prepare, then clear the status so the task
1006
1195
  # reads as PENDING again. `retry` clears it itself, after its own preflight. With --resume it
1007
1196
  # prepares an infrastructure stop's resume instead (prepare_resume), and the status stays;
1008
1197
  # with --dwarf <spec> the spec is the explicit new implementer; --fallback <pairs> [--cause <cause> [--role qa]]
1009
1198
  # is prepare_fallback.
1010
- retry_for_scheduler() { # retry_for_scheduler <plan> <id> [--resume | --dwarf <spec> | --fallback <pairs> [--cause <cause> [--role qa]]]
1199
+ retry_for_scheduler() { # retry_for_scheduler <plan> <id> [--resume | --prompt | --dwarf <spec> | --fallback <pairs> [--cause <cause> [--role qa]]]
1200
+ if [ "${3:-}" = --prompt ]; then
1201
+ prepare_prompt_retry "$1" "$2"
1202
+ return $?
1203
+ fi
1011
1204
  if [ "${3:-}" = --resume ]; then
1012
1205
  # An infrastructure stop spends no attempt, but the resume starts one: at the cap it is stopped for a decision.
1013
1206
  attempt_cap_gate "$1" "$2" INFRA "" || return 4
@@ -26,6 +26,7 @@
26
26
  # forge-memory.sh prune <repo>
27
27
  # forge-memory.sh spend <repo> [--run <run-id>]
28
28
  # forge-memory.sh learnings <repo> [--json] every ledger learning and its state, as JSON
29
+ # forge-memory.sh forget <repo> <category:key>... [--dry-run] [--json] [--actor ui|cli]
29
30
  #
30
31
  # Exit codes: 0 ok | 2 usage error
31
32
  set -uo pipefail
@@ -122,12 +123,14 @@ section_title() {
122
123
  # cannot leave memory half-updated — it can only leave the ledger short a row.
123
124
  # With <out>, the memory is written there instead of the repo's .forge/memory.md, and the repo is
124
125
  # only read: `learnings` uses that to say what a rebuild keeps without changing anything.
125
- rebuild() { # rebuild <repo> [<out>] -> prints "kept<TAB>pruned_stale<TAB>pruned_cap"
126
+ # With <ledger>, that file is read instead of the repo's ledger. `forget --dry-run` passes a
127
+ # scratch copy that already has the rows removed, and a scratch <out>, so the repo is not touched.
128
+ rebuild() { # rebuild <repo> [<out> [<ledger>]] -> prints "kept<TAB>pruned_stale<TAB>pruned_cap"
126
129
  local repo="$1" led mem tmp cand jev_loaded=0
127
130
  if [ "${FORGE_MEMORY_DEEP_PRUNE:-0}" = 1 ] && [ -f "$SKILL_DIR/scripts/forge-jev-options.sh" ]; then
128
131
  source "$SKILL_DIR/scripts/forge-jev-options.sh" 2>/dev/null && jev_loaded=1
129
132
  fi
130
- led="$(ledger_for "$repo")"; mem="${2:-$(memory_for "$repo")}"
133
+ led="${3:-$(ledger_for "$repo")}"; mem="${2:-$(memory_for "$repo")}"
131
134
  [ -f "$led" ] || return 0
132
135
  tmp="$mem.tmp.$$"; cand="$mem.cand.$$"
133
136
 
@@ -583,6 +586,242 @@ do_spend() {
583
586
  ' "$led"
584
587
  }
585
588
 
589
+ # --- forget -------------------------------------------------------------------
590
+ # Drop every ledger row of the given category:key learnings and rebuild memory.md.
591
+ # A learning is the (category, key) group `rebuild` and `learnings` use. Rows have no id.
592
+ # FORGE_MEMORY=off stops record, note and inject from writing: those run unasked. show and
593
+ # learnings still read the ledger (learnings only reports memory_off). forget is an explicit
594
+ # edit of that same ledger, so it runs when memory is off too. There is no early return.
595
+ #
596
+ # Sets FORGET_CANON to the ledger's "category:key" form (norm_key on each part), or exits 2.
597
+ parse_forget_key() {
598
+ local raw="$1" cat key
599
+ case "$raw" in
600
+ *:*) ;;
601
+ *) die "forget: KEY must be category:key, got '$raw'" ;;
602
+ esac
603
+ cat="$(norm_key "${raw%%:*}")"
604
+ key="$(norm_key "${raw#*:}")"
605
+ [ -n "$cat" ] && [ -n "$key" ] || die "forget: KEY must be category:key with neither part empty, got '$raw'"
606
+ FORGET_CANON="$cat:$key"
607
+ }
608
+
609
+ # Rewrite the ledger without the requested keys. Kept lines stay byte-identical, including
610
+ # a missing final newline. Prints how many rows matched. Counts are "<key>\t<rows>\t<1|0>".
611
+ forget_filter() { # forget_filter <ledger> <keys-file> <out-ledger> <counts-file>
612
+ python3 - "$@" <<'PY'
613
+ import sys
614
+ ledger_path, keys_path, out_path, counts_path = sys.argv[1:5]
615
+ keys = [line.rstrip('\n') for line in open(keys_path, encoding='utf-8') if line.rstrip('\n')]
616
+ seen = {}
617
+ for key in keys:
618
+ cat, sep, rest = key.partition(':')
619
+ if sep:
620
+ seen.setdefault((cat, rest), 0)
621
+ with open(ledger_path, 'rb') as handle:
622
+ data = handle.read()
623
+ kept = []
624
+ for line in data.splitlines(keepends=True):
625
+ raw = line.rstrip(b'\n').rstrip(b'\r')
626
+ if raw.startswith(b'#') or raw.count(b'\t') < 8:
627
+ kept.append(line)
628
+ continue
629
+ cols = raw.split(b'\t')
630
+ if len(cols) < 9:
631
+ kept.append(line)
632
+ continue
633
+ pair = (cols[6].decode('utf-8', 'surrogateescape'), cols[7].decode('utf-8', 'surrogateescape'))
634
+ if pair in seen:
635
+ seen[pair] += 1
636
+ continue
637
+ kept.append(line)
638
+ with open(out_path, 'wb') as handle:
639
+ handle.write(b''.join(kept))
640
+ with open(counts_path, 'w', encoding='utf-8') as handle:
641
+ for key in keys:
642
+ cat, _, rest = key.partition(':')
643
+ n = seen.get((cat, rest), 0)
644
+ handle.write('%s\t%d\t%s\n' % (key, n, '1' if n else '0'))
645
+ sys.stdout.write('%d\n' % sum(seen.values()))
646
+ PY
647
+ }
648
+
649
+ # Fact lines (`- ...`) present in <before> and absent from <after>, in the before file's
650
+ # order. A section heading disappears with its last fact; it is formatting, and so are the
651
+ # header and blank lines. Callers match on the `- ` lines. A missing file counts as empty.
652
+ forget_removed() { # forget_removed <before> <after> <out>
653
+ python3 - "$@" <<'PY'
654
+ import sys
655
+ from collections import Counter
656
+ before_path, after_path, out_path = sys.argv[1:4]
657
+
658
+ def lines(path):
659
+ try:
660
+ with open(path, encoding='utf-8') as handle:
661
+ return handle.read().splitlines()
662
+ except FileNotFoundError:
663
+ return []
664
+
665
+ have = Counter(lines(after_path))
666
+ removed = []
667
+ for line in lines(before_path):
668
+ if not line.startswith('- '):
669
+ continue
670
+ if have[line]:
671
+ have[line] -= 1
672
+ else:
673
+ removed.append(line)
674
+ with open(out_path, 'w', encoding='utf-8') as handle:
675
+ for line in removed:
676
+ handle.write(line + '\n')
677
+ PY
678
+ }
679
+
680
+ forget_report() { # forget_report <json 0|1> <dry 0|1> <counts> <removed>
681
+ if [ "$1" = 1 ]; then
682
+ python3 - "$2" "$3" "$4" <<'PY'
683
+ import json, sys
684
+ dry, counts_path, removed_path = sys.argv[1:4]
685
+ keys = []
686
+ for line in open(counts_path, encoding='utf-8'):
687
+ line = line.rstrip('\n')
688
+ if not line:
689
+ continue
690
+ key, rows, found = line.split('\t')
691
+ keys.append({"key": key, "rows": int(rows), "found": found == "1"})
692
+ removed = []
693
+ try:
694
+ for line in open(removed_path, encoding='utf-8'):
695
+ line = line.rstrip('\n')
696
+ if line:
697
+ removed.append(line)
698
+ except FileNotFoundError:
699
+ pass
700
+ json.dump({"ok": True, "dry_run": dry == "1", "keys": keys, "memory_lines_removed": removed},
701
+ sys.stdout)
702
+ sys.stdout.write('\n')
703
+ PY
704
+ else
705
+ local key rows found
706
+ while IFS=$'\t' read -r key rows found; do
707
+ [ -n "$key" ] || continue
708
+ if [ "$found" = 1 ]; then
709
+ printf '%s\t%s\n' "$key" "$rows"
710
+ else
711
+ printf '%s\tnot found\n' "$key"
712
+ fi
713
+ done < "$3"
714
+ fi
715
+ }
716
+
717
+ forget_fail() { # forget_fail <scratch> <message>
718
+ [ -n "$1" ] && rm -rf "$1"
719
+ die "$2"
720
+ }
721
+
722
+ do_forget() { # do_forget <repo> <category:key>... [--dry-run] [--json] [--actor ui|cli]
723
+ local repo="" dry=0 as_json=0 actor="cli" raw c keylist="" total=0 status=0 tmp="" scratch="" already=0
724
+ local -a rawkeys=() canon=()
725
+ while [ $# -gt 0 ]; do
726
+ case "$1" in
727
+ -h|--help) memory_usage; exit 0 ;;
728
+ --dry-run) dry=1; shift ;;
729
+ --json) as_json=1; shift ;;
730
+ --actor)
731
+ [ $# -ge 2 ] || die "forget: --actor needs ui or cli"
732
+ actor="$2"; shift 2
733
+ case "$actor" in
734
+ ui|cli) ;;
735
+ *) die "forget: --actor must be ui or cli" ;;
736
+ esac
737
+ ;;
738
+ --) shift
739
+ while [ $# -gt 0 ]; do rawkeys+=("$1"); shift; done
740
+ ;;
741
+ -*) die "forget: unknown option '$1'" ;;
742
+ *)
743
+ if [ -z "$repo" ]; then repo="$1"; else rawkeys+=("$1"); fi
744
+ shift
745
+ ;;
746
+ esac
747
+ done
748
+ [ -n "$repo" ] || die "forget: usage: forget <repo> <category:key>... [--dry-run] [--json] [--actor ui|cli]"
749
+ [ "${#rawkeys[@]}" -ge 1 ] || die "forget: usage: forget <repo> <category:key>... [--dry-run] [--json] [--actor ui|cli]"
750
+ [ -d "$repo" ] || die "forget: '$repo' is not a directory"
751
+ # One learning once. A repeated KEY, or two spellings that norm_key collapses together,
752
+ # is a single entry in the report and in the dataset event's keys list. rows counts
753
+ # ledger rows, so listing the key twice must not count them twice either.
754
+ for raw in "${rawkeys[@]}"; do
755
+ parse_forget_key "$raw"
756
+ already=0
757
+ if [ "${#canon[@]}" -gt 0 ]; then
758
+ for c in "${canon[@]}"; do
759
+ [ "$c" = "$FORGET_CANON" ] && already=1 && break
760
+ done
761
+ fi
762
+ [ "$already" = 1 ] || canon+=("$FORGET_CANON")
763
+ done
764
+ keylist="${canon[0]}"
765
+ if [ "${#canon[@]}" -gt 1 ]; then
766
+ for c in "${canon[@]:1}"; do keylist="$keylist,$c"; done
767
+ fi
768
+
769
+ scratch="$(mktemp -d "${TMPDIR:-/tmp}/forge-memory-forget.XXXXXX")" || die "forget: no scratch dir"
770
+ printf '%s\n' "${canon[@]}" > "$scratch/keys"
771
+ local led mem
772
+ led="$(ledger_for "$repo")"
773
+ mem="$(memory_for "$repo")"
774
+ if [ -f "$led" ]; then
775
+ total="$(forget_filter "$led" "$scratch/keys" "$scratch/ledger.new" "$scratch/counts")" \
776
+ || forget_fail "$scratch" "forget: could not read '$led'"
777
+ else
778
+ total=0
779
+ : > "$scratch/counts"
780
+ for c in "${canon[@]}"; do printf '%s\t0\t0\n' "$c" >> "$scratch/counts"; done
781
+ fi
782
+ case "$total" in
783
+ ''|*[!0-9]*) forget_fail "$scratch" "forget: could not read '$led'" ;;
784
+ esac
785
+
786
+ : > "$scratch/removed"
787
+ if [ "$total" -gt 0 ]; then
788
+ # Lines that leave are the difference between two rebuilds of the ledger, not between
789
+ # whatever memory.md happens to be on disk. A missing file would otherwise report
790
+ # nothing, and a stale or hand-edited one would report edits this forget did not make.
791
+ # The before rebuild reads the full ledger and writes only the scratch <out>.
792
+ rebuild "$repo" "$scratch/before.md" "$led" >/dev/null \
793
+ || forget_fail "$scratch" "forget: could not preview memory"
794
+ if [ "$dry" = 1 ]; then
795
+ # Same rebuild `record` runs, against the reduced ledger, written outside the repo.
796
+ rebuild "$repo" "$scratch/after.md" "$scratch/ledger.new" >/dev/null \
797
+ || forget_fail "$scratch" "forget: could not preview memory"
798
+ forget_removed "$scratch/before.md" "$scratch/after.md" "$scratch/removed" \
799
+ || forget_fail "$scratch" "forget: could not compare memory"
800
+ else
801
+ # do_record appends with >> and takes no lock, so there is none to share. The new
802
+ # ledger is written beside the old one and renamed over it, which is atomic on one
803
+ # filesystem. A concurrent append that lands between this read and that rename is
804
+ # the remaining race: that row is lost.
805
+ tmp="$(mktemp "$(dir_for "$repo")/ledger.tsv.tmp.XXXXXX")" \
806
+ || forget_fail "$scratch" "forget: could not write the ledger"
807
+ # mktemp makes it 0600: cp -p first gives it the ledger's own mode, which the write keeps.
808
+ { cp -p "$led" "$tmp" && cat "$scratch/ledger.new" > "$tmp"; } \
809
+ || { rm -f "$tmp"; forget_fail "$scratch" "forget: could not write the ledger"; }
810
+ mv -f "$tmp" "$led" \
811
+ || { rm -f "$tmp"; forget_fail "$scratch" "forget: could not replace the ledger"; }
812
+ rebuild "$repo" >/dev/null || forget_fail "$scratch" "forget: could not rebuild memory"
813
+ forget_removed "$scratch/before.md" "$mem" "$scratch/removed" \
814
+ || forget_fail "$scratch" "forget: could not compare memory"
815
+ # Only after a rewrite and a rebuild. A miss (rows 0) changes nothing, so it records nothing.
816
+ memory_dataset_event memory_forget "$repo" "" --set "keys=$keylist" --set "rows=$total" --set "actor=$actor"
817
+ fi
818
+ fi
819
+
820
+ forget_report "$as_json" "$dry" "$scratch/counts" "$scratch/removed" || status=$?
821
+ rm -rf "$scratch"
822
+ return "$status"
823
+ }
824
+
586
825
  # --- main ---------------------------------------------------------------------
587
826
  memory_usage() {
588
827
  cat <<'USAGE'
@@ -594,9 +833,11 @@ usage: forge memory <command> <repo> [...] (scripts/forge-memory.sh)
594
833
  prune <repo> re-apply staleness and the cap now, then print what a dwarf is told
595
834
  spend <repo> [--run ID] what forge has cost this repository, from the ledger
596
835
  inject <repo> <role> the block forge prepends to a planner, dwarf or qa prompt
836
+ forget <repo> <cat:key>... remove those learnings from the ledger and rebuild memory.md
837
+ (--dry-run, --json, --actor ui|cli); a missing key is not an error
597
838
  USAGE
598
839
  }
599
- [ $# -ge 1 ] || die "usage: forge-memory.sh <inject|note|record|show|prune|spend|learnings> [repo] [...]"
840
+ [ $# -ge 1 ] || die "usage: forge-memory.sh <inject|note|record|show|prune|spend|learnings|forget> [repo] [...]"
600
841
  CMD="$1"; shift
601
842
  case "$CMD" in
602
843
  -h|--help|help) memory_usage; exit 0 ;;
@@ -608,5 +849,6 @@ case "$CMD" in
608
849
  learnings) [ "${2:-}" = --json ] || [ $# -eq 1 ] || die "learnings: usage: learnings <repo> [--json]"; do_learnings "$1" ;;
609
850
  prune) do_prune "${1:?prune needs a repo}" >/dev/null
610
851
  do_inject "${1}" dwarf ;;
852
+ forget) do_forget "$@" ;;
611
853
  *) die "unknown subcommand '$CMD'" ;;
612
854
  esac
@@ -5,8 +5,9 @@ forge_metric_begin() {
5
5
  FORGE_METRIC="$(python3 "$SKILL_DIR/scripts/forge-runtime.py" begin "$1" "$2")" || return 3
6
6
  # Dispatches started from here name this execution as their parent in the run dataset.
7
7
  export FORGE_DATASET_PARENT="${FORGE_METRIC##*/}"
8
- # The hook, when the caller defines it, records status before finish and Fractal's _outcome.
9
- trap 'metric_rc=$?; ! declare -F forge_metric_on_exit >/dev/null || forge_metric_on_exit "$metric_rc"; python3 "$SKILL_DIR/scripts/forge-runtime.py" finish "$FORGE_METRIC" "$FORGE_METRIC_ROOT" "$FORGE_METRIC_ROLE" pipeline "$metric_rc"; if [ -n "${FORGE_FRACTAL_RUN:-}" ]; then python3 "$SKILL_DIR/scripts/forge-fractal.py" _outcome "$FORGE_METRIC_ROOT" "$metric_rc"; fi; exit "$metric_rc"' EXIT
8
+ # The hook, when the caller defines it, records status before finish and Fractal's _outcome. A review
9
+ # snapshot the runner names in FORGE_REVIEW_SNAPSHOT is removed on every way out (#139).
10
+ trap 'metric_rc=$?; [ -z "${FORGE_REVIEW_SNAPSHOT:-}" ] || ! declare -F forge_drop_snapshot >/dev/null || forge_drop_snapshot "$FORGE_REVIEW_SNAPSHOT"; ! declare -F forge_metric_on_exit >/dev/null || forge_metric_on_exit "$metric_rc"; python3 "$SKILL_DIR/scripts/forge-runtime.py" finish "$FORGE_METRIC" "$FORGE_METRIC_ROOT" "$FORGE_METRIC_ROLE" pipeline "$metric_rc"; if [ -n "${FORGE_FRACTAL_RUN:-}" ]; then python3 "$SKILL_DIR/scripts/forge-fractal.py" _outcome "$FORGE_METRIC_ROOT" "$metric_rc"; fi; exit "$metric_rc"' EXIT
10
11
  }
11
12
  forge_metric_phase() {
12
13
  python3 "$SKILL_DIR/scripts/forge-runtime.py" phase "$FORGE_METRIC" "$1"
@@ -25,8 +26,11 @@ forge_dataset_event() { # forge_dataset_event <name> --dir <dir> [--task id] [--
25
26
  }
26
27
  # A worktree forge added or removed (#125): forge-ui's Worktrees screen lists every one, removed ones too.
27
28
  # <kind> is task, integration, candidate or attribute (scripts/forge_worktrees.py); <branch> is - when detached.
28
- # Off with the dataset (FORGE_DATASET=off), as forge_dataset_event is.
29
+ # Always into forge's location list (forge_locations.py, off only with FORGE_RUN_REGISTRY=off), so forge knows
30
+ # where its worktrees are whatever the dataset says; the dataset event is off with FORGE_DATASET=off.
29
31
  forge_worktree_event() { # forge_worktree_event created|removed <run dir> <repo> <path> <branch|-> <kind> [task]
32
+ python3 -I "$SKILL_DIR/scripts/forge_locations.py" worktree "$1" "$2" "$3" "$4" "$5" "$6" ${7:+"$7"} \
33
+ </dev/null >/dev/null 2>&1 || true
30
34
  forge_dataset_event "worktree_$1" --dir "$2" ${7:+--task "$7"} --set repo_path="$3" --set path="$4" \
31
35
  --set branch="$5" --set kind="$6"
32
36
  }
@@ -15,6 +15,10 @@
15
15
  # --infra-retries when `run` or `retry` is not given them; a flag wins. On `retry` they are
16
16
  # the further attempts after this one (while its review fails) and the waits out of an infrastructure stop.
17
17
  #
18
+ # `plan` also writes retro, brief, brief_scope, brief_model, summaries and summaries_model
19
+ # (--retro, --brief, --brief-scope, --brief-model, --summaries, --summaries-model; #132, #133,
20
+ # #135). They are plan-only flags, parsed in do_plan, not here; see forge_features_resolve.
21
+ #
18
22
  # Persisted options become files in the plan dir, like --verify and --setup, so a later
19
23
  # `retry` or the scheduler's task processes see them. Cost-bearing options that change
20
24
  # what a run is allowed to spend (--retry-failed, --infra-retries) are deliberately NOT