@giamme/forge 0.14.0 → 0.14.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.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,15 @@ All notable changes to this project are documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
6
  and versions follow the format `{major}.{minor}[.{patch}]` ([...] parts appear only when non-zero).
7
7
 
8
+ ## [0.14.1] - 2026-11-03
9
+
10
+ Two fixes from run 1's follow-ups: a lateral move after an infrastructure stop stays in the tier the task was last assigned, and a claude or openclaude dispatch that already gave its final result is no longer lost to a timeout while a background task keeps it open.
11
+
12
+ ### Fixed
13
+
14
+ - A claude or openclaude implementer or reviewer that gave its final result but stayed open on a background task is no longer killed as a timeout. forge ends it after 30 minutes of silence (`FORGE_RESULT_GRACE`, `0` turns it off), or at the watchdog, and its result goes to review; a turn the session starts after a result is never cut short (#110).
15
+ - An infrastructure stop moves a task only within the tier it was last assigned. A re-plan that picks the row's model again, explored or not, now replaces the tier an older escalation or pin recorded, so a task re-planned onto a cheaper tier can no longer move sideways to a stronger tier's model (#106).
16
+
8
17
  ## [0.14] - 2026-11-02
9
18
 
10
19
  Infrastructure stops now carry a cause and recover on their own where they can, moving sideways to a model of the same tier; forge watch, forge pr and forge runs rerun/compare follow, describe and compare runs; and a run now pays for the full test suite once, after the merge, instead of on every attempt.
package/VERSION CHANGED
@@ -1 +1 @@
1
- 0.14
1
+ 0.14.1
package/docs/artifacts.md CHANGED
@@ -18,6 +18,7 @@ as if the dwarf had written it.
18
18
  <role>.last the final message — read this first
19
19
  <role>.infra only after an infrastructure failure: class, retry_after, detail, harness, model
20
20
  <role>.orphans only when processes were left running after the harness exited
21
+ <role>.settled only when claude/openclaude stayed up on a background task after its final result and forge ended it: ended_by=grace|timeout, backend_exit=; the result stands (not a timeout)
21
22
  <role>.session session id reported by claude, openclaude or codex; absent when the dispatch published none
22
23
  <role>.continue only when the dispatch was asked to continue a session (a reviewer's, or an implementer's): requested=, mode=continued|failed, reason=
23
24
  changes.diff the dwarf's real diff, which is qa's input
@@ -61,7 +62,7 @@ A decomposed run adds:
61
62
  tasks/<id>/<role>.harness only while a guarded dispatch runs: its harness's pid and start time, for forge-guard.py stop
62
63
  tasks/<id>/qa_threshold optional per-task blocking threshold: P0-P3, or none (P3; exempt from a looser plan threshold)
63
64
  tasks/<id>/escalations.tsv epoch, attempt, from-spec, to-spec, source (policy|retry|pin|fallback); older rows have 4 columns
64
- tasks/<id>/running.tier tier<TAB>spec: the tier the last escalations.tsv row moved the task to; ignored once the task runs another spec
65
+ tasks/<id>/running.tier tier<TAB>spec<TAB>epoch: the tier the task runs in, written at each assignment (plan, escalation, pin, retry --dwarf, lateral move); the newer of it and route.jsonl's last pick counts, and neither once the task runs another spec
65
66
  tasks/<id>/escalation.pin a human's one-shot model for the next full retry: one dwarf spec on one line
66
67
  tasks/<id>/escalation.pin.applying the pin while a retry has claimed it; removed once the retry is recorded
67
68
  tasks/<id>/retry_findings.commit commit the carried review judged
package/docs/commands.md CHANGED
@@ -355,7 +355,8 @@ whole ladder. It never dispatches and spends no quota. The retry policy's effort
355
355
  | `--timeout <s>` | kill this dispatch after `<s>` seconds; `0` disables. See the precedence below |
356
356
 
357
357
  **Exit codes:** `0` ok · `2` spec or usage error · `3` harness missing or unusable ·
358
- `4` the backend ran and failed · `7` the backend hit its timeout and was killed ·
358
+ `4` the backend ran and failed · `7` the backend hit its timeout and was killed (unless it had
359
+ already given its final result, below) ·
359
360
  `8` an **infrastructure failure** (quota or usage limit, auth, rate limit, network, or an
360
361
  empty answer) — nothing about the work was judged, so callers pause instead of counting a
361
362
  failure. On `8`, `<run-dir>/<role>.infra` holds `class=`, `retry_after=`, `detail=`, `rc=`,
@@ -377,6 +378,17 @@ silently stalled the others. The default is deliberately generous: this is a bac
377
378
  a wedged process, not a budget. A role killed by it has usually left a partial edit behind, so
378
379
  `7` is worth reporting as such rather than as a clean failure.
379
380
 
381
+ **A final result the CLI stays open after.** claude and openclaude stay up while a background
382
+ task their session started is still open, even after the model's final result. When the log
383
+ ends in that result (only background-task events after it) and has been silent for
384
+ `FORGE_RESULT_GRACE` seconds (default 1800; `0` turns it off), forge ends the harness and the
385
+ result stands: the role finished, its exit is the one the CLI gives for that result, and
386
+ `<role>.settled` says `ended_by=grace`. The same holds when the watchdog is what ended it
387
+ (`ended_by=timeout`), so the work goes to review instead of counting as a timeout. A result is
388
+ not always the end: a background task that completes wakes the session for another turn, and a
389
+ turn under way is never ended by the grace, however long it is silent. The grace is long
390
+ because that wake-up can come many minutes later. `<role>.resolved` records `result_grace=`.
391
+
380
392
  On `3` or `4`, forge shows you the actual error rather than substituting a different model —
381
393
  quietly swapping backends hides the fact that the one you picked is broken.
382
394
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@giamme/forge",
3
- "version": "0.14.0",
3
+ "version": "0.14.1",
4
4
  "description": "Multi-model coding with a reviewer that reads the code: plan, build in parallel worktrees, review every real diff, merge only what passes.",
5
5
  "keywords": ["claude-code", "codex", "opencode", "agent-skill", "code-review", "multi-model"],
6
6
  "license": "MIT",
@@ -862,9 +862,11 @@ clear by itself.
862
862
  the next infrastructure stop. It runs at the dwarf stage and at the QA stage, and not on a Fractal
863
863
  plan:
864
864
 
865
- - a **dwarf-stage** stop takes the next healthy model of the tier the task is running in (the tier
866
- recorded with its last escalation or exploration, otherwise its difficulty). A pinned implementer
867
- is not moved. No attempt is spent.
865
+ - a **dwarf-stage** stop takes the next healthy model of the tier the task is running in: the tier
866
+ recorded at its newest assignment (the plan's pick, explored or not, an escalation, a pin, a
867
+ `retry --dwarf`, an earlier move), as long as it still runs that model; otherwise its difficulty.
868
+ A re-plan that keeps a row's model keeps its tier. A pinned implementer is not moved. No attempt
869
+ is spent.
868
870
  - a **QA-stage** stop takes a reviewer of the same strength from `qa-routing.json`: the next member
869
871
  of the task's difficulty pool, then of `any`, on a pair nobody paused. Never the stopped
870
872
  reviewer's model, and never the implementer's. The attempt and the `resume` marker stay, so the
@@ -43,7 +43,10 @@ way to distinguish stuck from slow. `forge-dispatch.sh` therefore runs every bac
43
43
  background and kills it after its timeout: `--timeout`, else `FORGE_TIMEOUT` (an explicit `0`
44
44
  disables), else the optional `timeout` column of the model's registry row, else 2700 s — scaled
45
45
  ×4/3 for `xhigh` and ×2 for `max`/`ultra` effort when not explicit (`<role>.resolved` records
46
- `timeout=` and `timeout_source=`). A killed dispatch exits `7`.
46
+ `timeout=` and `timeout_source=`). A killed dispatch exits `7`, unless claude or openclaude had
47
+ already given its final result and only an open background task kept it up: that result stands,
48
+ whether the watchdog or `FORGE_RESULT_GRACE` (default 1800 s of silence after it; `0` = off) ended
49
+ it, and `<role>.settled` records which (see [commands](../docs/commands.md)).
47
50
 
48
51
  **Infrastructure failures exit `8`.** After the backend exits, `forge-runtime.py classify` reads
49
52
  the dispatch log (never `<role>.last`, which is only created afterwards): claude/openclaude/grok
@@ -33,9 +33,15 @@
33
33
  # Environment: FORGE_REGISTRY alternate registry file (default: <skill>/registry.tsv)
34
34
  # FORGE_ORPHAN_GUARD off = do not run the harness in its own process group
35
35
  # (default on; also skipped under FORGE_FRACTAL_RUN)
36
+ # FORGE_RESULT_GRACE claude/openclaude: seconds a log that ends in the model's final
37
+ # result may stay silent before forge ends the harness (an open
38
+ # background task keeps it up); default 1800, 0 = off. Either way
39
+ # a dispatch killed after that result is not a timeout.
36
40
  #
37
41
  # Exit codes: 0 ok | 2 usage/resolution error | 3 harness missing or unusable
38
42
  # 4 backend ran but failed | 7 backend exceeded --timeout and was killed
43
+ # (not when its log ended in a final result and only background tasks kept it up:
44
+ # that result stands, as after FORGE_RESULT_GRACE; $ROLE.settled says which)
39
45
  # 8 infrastructure failure (auth, usage_limit, budget, capacity, rate_limit,
40
46
  # provider_down, network, or an empty answer; forge_infra.py says what each
41
47
  # means): the model never got to do its work. $ROLE.infra says which.
@@ -371,6 +377,15 @@ if [ "$LIMIT_SOURCE" = registry ] || [ "$LIMIT_SOURCE" = default ]; then
371
377
  fi
372
378
  fi
373
379
 
380
+ # --- the grace after a final result (#110) --------------------------------------
381
+ # claude and openclaude stay up while a background task of the session is open, even after the
382
+ # model's final result. Once the log ends in that result and stays silent this long, forge ends
383
+ # the harness and the result stands. Long on purpose: a background test run can wake the session
384
+ # for another turn many minutes later.
385
+ RESULT_GRACE="${FORGE_RESULT_GRACE:-1800}"
386
+ case "$RESULT_GRACE" in ''|*[!0-9]*) die "FORGE_RESULT_GRACE must be a nonnegative integer" ;; esac
387
+ [ "${#RESULT_GRACE}" -gt 9 ] || RESULT_GRACE=$((10#$RESULT_GRACE))
388
+
374
389
  # --- run dir & prompt ---------------------------------------------------------
375
390
  [ -d "$REPO" ] || die "--repo '$REPO' is not a directory"
376
391
  REPO="$(cd "$REPO" && pwd)"
@@ -388,7 +403,7 @@ write_continue() { :; } # redefined below once there is an attempt to archive
388
403
  ATTEMPT=""
389
404
  if [ "$PREFLIGHT" != 1 ] && [ "$DRY" != 1 ]; then
390
405
  ATTEMPT="$(python3 "$RUNTIME" begin "$RUN_DIR" "$ROLE")" || exit 3
391
- rm -f "$RUN_DIR/$ROLE.last" "$RUN_DIR/$ROLE.log" "$RUN_DIR/$ROLE.clock" "$RUN_DIR/$ROLE.resolved" "$RUN_DIR/$ROLE.cmd" "$RUN_DIR/$ROLE.timedout" "$RUN_DIR/$ROLE.infra" "$RUN_DIR/$ROLE.orphans" "$RUN_DIR/$ROLE.session" "$RUN_DIR/$ROLE.continue" "$RUN_DIR/$ROLE.harness"
406
+ rm -f "$RUN_DIR/$ROLE.last" "$RUN_DIR/$ROLE.log" "$RUN_DIR/$ROLE.clock" "$RUN_DIR/$ROLE.resolved" "$RUN_DIR/$ROLE.cmd" "$RUN_DIR/$ROLE.timedout" "$RUN_DIR/$ROLE.settled" "$RUN_DIR/$ROLE.infra" "$RUN_DIR/$ROLE.orphans" "$RUN_DIR/$ROLE.session" "$RUN_DIR/$ROLE.continue" "$RUN_DIR/$ROLE.harness"
392
407
  trap 'exit 143' TERM
393
408
  trap 'exit 130' INT
394
409
  # GUARD_ON is 1 only when the harness was started in its own process group (see the
@@ -404,7 +419,7 @@ if [ "$PREFLIGHT" != 1 ] && [ "$DRY" != 1 ]; then
404
419
  # Interrupted after the harness exited but before the normal reap.
405
420
  python3 "$GUARD" reap "$hpid" "$RUN_DIR/$ROLE.orphans" >/dev/null 2>&1
406
421
  fi
407
- if [ -n "${wpid:-}" ]; then pkill -P "$wpid" 2>/dev/null; kill "$wpid" 2>/dev/null; fi
422
+ for watcher in ${wpid:-} ${spid:-}; do pkill -P "$watcher" 2>/dev/null; kill "$watcher" 2>/dev/null; done
408
423
  [ -z "${cpid:-}" ] || kill "$cpid" 2>/dev/null
409
424
  rm -f "$RUN_DIR/$ROLE.harness"
410
425
  }
@@ -705,6 +720,7 @@ if [ "$DRY" != 1 ] || [ "$PREFLIGHT" = 1 ]; then preflight_command; fi
705
720
  [ -n "$CLAMPED" ] && echo "clamped=$CLAMPED"
706
721
  echo "timeout=$LIMIT"
707
722
  echo "timeout_source=$LIMIT_SOURCE"
723
+ case "$HARNESS" in claude|openclaude) echo "result_grace=$RESULT_GRACE" ;; esac
708
724
  # Native review ignores the assembled prompt, so whether it reached the model is a fact
709
725
  # worth recording rather than inferring from the role and harness later.
710
726
  echo "delivery=$([ "$NATIVE_REVIEW" = 1 ] && echo native_review || echo custom)"
@@ -744,7 +760,7 @@ fi
744
760
  # when a stale $LAST is already there. That is harmless when each run gets a fresh
745
761
  # run-dir, and silently wrong for `forge-parallel.sh retry`, which reuses the task
746
762
  # directory — it would read the first attempt's result and never notice.
747
- rm -f "$LAST" "$LOG" "$RUN_DIR/$ROLE.clock" "$RUN_DIR/$ROLE.clock.stop" "$RUN_DIR/$ROLE.timedout" "$RUN_DIR/$ROLE.infra" "$RUN_DIR/$ROLE.orphans" "$RUN_DIR/$ROLE.harness"
763
+ rm -f "$LAST" "$LOG" "$RUN_DIR/$ROLE.clock" "$RUN_DIR/$ROLE.clock.stop" "$RUN_DIR/$ROLE.timedout" "$RUN_DIR/$ROLE.settled" "$RUN_DIR/$ROLE.infra" "$RUN_DIR/$ROLE.orphans" "$RUN_DIR/$ROLE.harness"
748
764
  python3 "$RUNTIME" phase "$ATTEMPT" model
749
765
  t0="$(date +%s)"
750
766
  # Process-group guard. A dwarf that starts `npm test &` and ends its turn leaves that
@@ -785,6 +801,19 @@ if [ "$GUARD_ON" = 1 ]; then
785
801
  fi
786
802
  fi
787
803
 
804
+ # Ends the harness: the whole process group first when the harness has its own (GUARD_ON),
805
+ # then children, then the process itself, then SIGKILL for a CLI that traps TERM and takes
806
+ # its time. Without the guard there is no group to signal as a unit.
807
+ stop_harness() {
808
+ [ "$GUARD_ON" != 1 ] || kill -s TERM -- "-$hpid" 2>/dev/null
809
+ pkill -TERM -P "$hpid" 2>/dev/null
810
+ kill -TERM "$hpid" 2>/dev/null
811
+ sleep 5
812
+ [ "$GUARD_ON" != 1 ] || kill -s KILL -- "-$hpid" 2>/dev/null
813
+ pkill -KILL -P "$hpid" 2>/dev/null
814
+ kill -KILL "$hpid" 2>/dev/null
815
+ }
816
+
788
817
  # Watchdog. Only antigravity has a time bound of its own, and `timeout` is not
789
818
  # present on stock macOS, so without this a hung backend blocks forever — and under
790
819
  # forge-parallel's `xargs -P` one hung task silently stalls its whole wave. The
@@ -796,19 +825,24 @@ if [ "${LIMIT:-0}" != "0" ]; then
796
825
  sleep "$LIMIT"
797
826
  kill -0 "$hpid" 2>/dev/null || exit 0
798
827
  : > "$RUN_DIR/$ROLE.timedout"
799
- # The whole process group first when the harness has its own (GUARD_ON), then
800
- # children, then the process itself, then SIGKILL for a CLI that traps TERM and
801
- # takes its time. Without the guard there is no group to signal as a unit.
802
- [ "$GUARD_ON" != 1 ] || kill -s TERM -- "-$hpid" 2>/dev/null
803
- pkill -TERM -P "$hpid" 2>/dev/null
804
- kill -TERM "$hpid" 2>/dev/null
805
- sleep 5
806
- [ "$GUARD_ON" != 1 ] || kill -s KILL -- "-$hpid" 2>/dev/null
807
- pkill -KILL -P "$hpid" 2>/dev/null
808
- kill -KILL "$hpid" 2>/dev/null
828
+ stop_harness
809
829
  ) >/dev/null 2>&1 &
810
830
  wpid=$!
811
831
  fi
832
+ # A final result the CLI stays open after (#110): once the log ends in it and has been silent for
833
+ # the grace, the harness is ended like a timeout, but the result stands (see below).
834
+ spid=""
835
+ case "$HARNESS" in claude|openclaude)
836
+ if [ "$RESULT_GRACE" != 0 ]; then
837
+ (
838
+ python3 "$RUNTIME" settle "$LOG" "$RESULT_GRACE" "$hpid" </dev/null || exit 0
839
+ kill -0 "$hpid" 2>/dev/null || exit 0
840
+ : > "$RUN_DIR/$ROLE.settled"
841
+ stop_harness
842
+ ) >/dev/null 2>&1 &
843
+ spid=$!
844
+ fi ;;
845
+ esac
812
846
 
813
847
  wait "$hpid"; rc=$?
814
848
  # Its last sample is in before `finish` copies the clock into the attempt. A stop file, not a TERM:
@@ -819,13 +853,13 @@ if [ -n "$cpid" ]; then
819
853
  { : > "$RUN_DIR/$ROLE.clock.stop"; } 2>/dev/null || kill -TERM "$cpid" 2>/dev/null
820
854
  wait "$cpid" 2>/dev/null; cpid=""; rm -f "$RUN_DIR/$ROLE.clock.stop"
821
855
  fi
822
- if [ -n "$wpid" ]; then
823
- # The watchdog is asleep in a child of its own; kill that too or it outlives the
824
- # run as an orphan holding the timer.
825
- pkill -P "$wpid" 2>/dev/null
826
- kill "$wpid" 2>/dev/null
827
- wait "$wpid" 2>/dev/null
828
- fi
856
+ for watcher in $wpid $spid; do
857
+ # The watchdog is asleep in a child of its own, and so is the grace watcher; kill that
858
+ # too or it outlives the run as an orphan holding the timer.
859
+ pkill -P "$watcher" 2>/dev/null
860
+ kill "$watcher" 2>/dev/null
861
+ wait "$watcher" 2>/dev/null
862
+ done
829
863
  # Anything the harness left running in its group is an abandoned background job. Kill it
830
864
  # before reading the tree, and leave the list for the caller. Bounded (~3s) and advisory:
831
865
  # a reaper failure changes nothing about the exit code.
@@ -840,6 +874,28 @@ DURATION=$(( $(date +%s) - t0 ))
840
874
  echo "duration_s=$DURATION" >> "$RUN_DIR/$ROLE.resolved"
841
875
  [ "$OUTPUT" != full ] || cat "$LOG"
842
876
  [ "$OUTPUT" != summary ] || echo "forge: role=$ROLE backend_exit=$rc final=$LAST log=$LOG metrics=$ATTEMPT/metrics.json"
877
+ # Ended by forge after the model's final result, with only background tasks open: the answer was
878
+ # in, so the role finished and its result stands, whether the grace or the watchdog ended it. The
879
+ # exit is the one the CLI gives for that result. A turn that began while forge was ending it is cut
880
+ # off, as by a timeout.
881
+ if [ -f "$RUN_DIR/$ROLE.settled" ] || [ -f "$RUN_DIR/$ROLE.timedout" ]; then
882
+ case "$HARNESS" in claude|openclaude)
883
+ if verdict="$(python3 "$RUNTIME" settled "$LOG" 2>/dev/null)"; then
884
+ # The marker is written before the harness is stopped, so it says the grace came first.
885
+ if [ -f "$RUN_DIR/$ROLE.settled" ]; then after="${RESULT_GRACE}s of silence"; ended_by=grace
886
+ else after="the ${LIMIT}s timeout"; ended_by=timeout; fi
887
+ printf 'ended_by=%s\nbackend_exit=%s\n' "$ended_by" "$rc" > "$RUN_DIR/$ROLE.settled"
888
+ rm -f "$RUN_DIR/$ROLE.timedout"
889
+ if [ "$verdict" = error ]; then rc=1; else rc=0; fi
890
+ note "$HARNESS gave its final result, then stayed open on a background task; forge ended it after $after — the result stands"
891
+ elif [ -f "$RUN_DIR/$ROLE.settled" ]; then
892
+ rm -f "$RUN_DIR/$ROLE.settled"; : > "$RUN_DIR/$ROLE.timedout"
893
+ note "$HARNESS began another turn while forge was ending it after its final result — see $LOG"
894
+ write_continue failed timeout
895
+ exit 7
896
+ fi ;;
897
+ esac
898
+ fi
843
899
  if [ -f "$RUN_DIR/$ROLE.timedout" ]; then
844
900
  note "$HARNESS exceeded the ${LIMIT}s timeout and was killed after ${DURATION}s — see $LOG"
845
901
  write_continue failed timeout
@@ -422,11 +422,13 @@ EOF
422
422
  # Exploration (--explore): now and then the neighbouring tier's model instead, with the
423
423
  # odds recorded, so `forge dataset routing` can compare two models on tasks neither was
424
424
  # routed to by design. The pool's turn above was still taken, so other rows are unchanged.
425
- if [ -n "$EXPLORE" ] && [ "$dw" != UNASSIGNED ]; then
426
- local explored
427
- explored="$(python3 "$SKILL_DIR/scripts/forge-route.py" explore --plan "$PLAN" --task "$id" \
428
- --tier "$diff" --epsilon "$EXPLORE" --default "$dw" --pools "$PLAN/fractal-routing.json" 2>/dev/null)"
429
- [ -z "$explored" ] || dw="$explored"
425
+ # Explored or not, the pick's tier is recorded (running.tier), so an escalation or pin that
426
+ # this re-plan replaces no longer says which tier a lateral move stays in (#106).
427
+ if [ "$dw" != UNASSIGNED ]; then
428
+ local assigned
429
+ assigned="$(python3 "$SKILL_DIR/scripts/forge-route.py" assign --plan "$PLAN" --task "$id" \
430
+ --tier "$diff" --epsilon "${EXPLORE:-0}" --default "$dw" --pools "$PLAN/fractal-routing.json" 2>/dev/null)"
431
+ [ -z "$assigned" ] || dw="$assigned"
430
432
  fi
431
433
  fi
432
434
  # resolve qa: the same grammar as the dwarf, a comma-list round-robins within its tier.
@@ -16,6 +16,12 @@ bias (inverse-propensity weighting needs the probability each choice had).
16
16
  <plan>/tasks/<id>/route.jsonl (never rewritten) and marks a changed pick in tasks/<id>/route.explored for the table. A row
17
17
  with no neighbour is not explored and records nothing.
18
18
 
19
+ forge-route.py assign --plan P --task ID --tier T --default SPEC --pools FILE [--epsilon E]
20
+ Called by `plan` for each row it resolves (one the user left to forge): `explore` above when E is
21
+ above 0, then tasks/<id>/running.tier for the spec it prints, with the tier of that pick (T, or the
22
+ neighbour's tier an exploration chose). A re-plan that re-resolves a row thus replaces whatever an
23
+ older escalation or pin recorded (#106); a row whose dwarf the plan keeps is never assigned.
24
+
19
25
  forge-route.py escalation --plan P --task ID [--check] [--qa-only-next yes|no]
20
26
  The retry policy: after <plan>/escalate_after (default 3; 0 = off) failed attempts on
21
27
  one spec, the next attempt goes to the next tier up of the user's pools instead of
@@ -42,8 +48,8 @@ bias (inverse-propensity weighting needs the probability each choice had).
42
48
 
43
49
  forge-route.py fallback --plan P --task ID [--exclude harness/model,...]
44
50
  The lateral move of an infrastructure stop: prints the next free model of the pool of the
45
- tier the task runs in (its difficulty, the tier its exploration picked, or the target its last
46
- escalation recorded in running.tier), or exits 1 when there is none. Never a model of another tier.
51
+ tier the task runs in (the newest record of it: see running_tier), or exits 1 when there is none.
52
+ Never a model of another tier.
47
53
  The move is recorded by `lateral` below, not as an escalation.
48
54
 
49
55
  forge-route.py qa-fallback --plan P --task ID [--exclude harness/model,...]
@@ -56,7 +62,7 @@ bias (inverse-propensity weighting needs the probability each choice had).
56
62
  forge-route.py record --plan P --task ID (--probe | --line TEXT)
57
63
  Internal. Probe or append tasks/<id>/escalations.tsv through forge-control.py, which
58
64
  walks from the plan one directory at a time and refuses a symlink at any component.
59
- An appended row also writes tasks/<id>/running.tier: its target tier and spec.
65
+ An appended row also writes tasks/<id>/running.tier: its target tier, spec and time.
60
66
  `--probe` exits 0 when every component below the plan is a real directory and the file
61
67
  is absent or a regular file. `--line` appends one record under those same conditions.
62
68
  A missing parent exits 1 and writes nothing: the walk has no directory descriptor then,
@@ -369,31 +375,46 @@ def escalation_target(source: str, frm: str, to: str, running: str, pools: dict,
369
375
 
370
376
  def running_tier(plan: Path, task: str, current: str = '') -> str:
371
377
  """The tier a task runs in, from what forge recorded when it assigned the model, never from which
372
- pools list the model: one model can sit in several, and a re-plan can change them. While the task
373
- runs the spec of a record, the tier in tasks/<id>/running.tier (written with each escalations.tsv
374
- row), else the tier its exploration picked; with neither, as in an older plan, the difficulty.
375
- `current` is the spec the task runs, read from tasks.tsv when not given. '' when the difficulty
376
- is no tier."""
378
+ pools list the model: one model can sit in several, and a re-plan can change them. Two records
379
+ say it, each with its time: tasks/<id>/running.tier, written at every assignment (the plan's
380
+ resolution of the row, an escalation, a pin, `retry --dwarf`, a lateral move), and the last
381
+ exploration decision in route.jsonl, all an older plan has. The newer one counts, and only while
382
+ the task still runs its spec: an older record never beats a newer pick of the same model (#106).
383
+ With neither, or when the newest is for another spec (the table was edited by hand), the
384
+ difficulty. `current` is the spec the task runs, read from tasks.tsv when not given. '' when the
385
+ difficulty is no tier."""
377
386
  tier = _row_cell(plan, task, 2)
378
387
  if tier not in TIERS:
379
388
  return ''
380
389
  tdir = plan / 'tasks' / task
381
390
  current = current or _dwarf_of(plan, task)
382
- with contextlib.suppress(OSError):
383
- recorded, _, spec = (tdir / 'running.tier').read_text().strip().partition('\t')
384
- if spec == current and recorded in TIERS:
385
- return recorded
386
- with contextlib.suppress(OSError, ValueError, AttributeError): # no usable record: the difficulty
391
+ records = []
392
+ with contextlib.suppress(OSError, ValueError):
393
+ path = tdir / 'running.tier'
394
+ cells = path.read_text().strip().split('\t')
395
+ if len(cells) > 1 and cells[0] in TIERS:
396
+ # Written before records carried their time (forge 0.14): as old as the file.
397
+ records.append((float(cells[2]) if len(cells) > 2 else path.stat().st_mtime, cells[1], cells[0]))
398
+ with contextlib.suppress(OSError, ValueError, AttributeError, TypeError):
387
399
  lines = (tdir / 'route.jsonl').read_text().splitlines()
388
400
  decision = json.loads(lines[-1]) if lines else {}
389
- if decision.get('chosen') == current and decision.get('chosen_tier') in TIERS:
390
- return decision['chosen_tier']
401
+ if decision.get('chosen_tier') in TIERS:
402
+ records.append((float(decision.get('at') or 0), decision.get('chosen'), decision['chosen_tier']))
403
+ if records:
404
+ _, spec, recorded = max(records, key=lambda record: record[0])
405
+ if spec == current:
406
+ return recorded
391
407
  return tier
392
408
 
393
409
 
410
+ def write_running_tier(plan: str, task: str, tier: str, spec: str, control) -> None:
411
+ """tasks/<id>/running.tier: `tier<TAB>spec<TAB>time`, the tier the task runs in while it runs `spec`."""
412
+ control.write_atomic(plan, 'tasks/%s/running.tier' % task, '%s\t%s\t%.6f\n' % (tier, spec, time.time()))
413
+
414
+
394
415
  def record_running_tier(plan: str, task: str, row: str, control) -> None:
395
- """tasks/<id>/running.tier for an escalations.tsv row: `tier<TAB>spec`, the tier the row moved the
396
- task to, decided here with the pools of this moment. A fallback stays in its tier."""
416
+ """tasks/<id>/running.tier for an escalations.tsv row: the tier the row moved the task to, decided
417
+ here with the pools of this moment. A fallback stays in its tier."""
397
418
  cells = row.rstrip('\n').split('\t')
398
419
  frm, to, source = cells[2], cells[3], cells[4] if len(cells) > 4 else 'policy'
399
420
  tier = running_tier(Path(plan), task, frm)
@@ -401,7 +422,7 @@ def record_running_tier(plan: str, task: str, row: str, control) -> None:
401
422
  tier = escalation_target(source, frm, to, tier, load_pools(Path(plan) / 'fractal-routing.json'),
402
423
  registry_models())
403
424
  if tier:
404
- control.write_atomic(plan, 'tasks/%s/running.tier' % task, '%s\t%s\n' % (tier, to))
425
+ write_running_tier(plan, task, tier, to, control)
405
426
 
406
427
 
407
428
  def fallback(args) -> int:
@@ -433,13 +454,14 @@ def qa_fallback(args) -> int:
433
454
 
434
455
  # --- exploration -------------------------------------------------------------------
435
456
 
436
- def explore(args) -> str:
457
+ def explore(args) -> tuple:
458
+ """(spec, tier): the pick and the tier it was picked from."""
437
459
  epsilon = float(args.epsilon)
438
460
  if not 0 < epsilon <= 1:
439
- return args.default
461
+ return args.default, args.tier
440
462
  alternative, alternative_tier = neighbour(args.default, args.tier, load_pools(args.pools), registry_models())
441
463
  if not alternative:
442
- return args.default
464
+ return args.default, args.tier
443
465
  candidates = [args.default, alternative]
444
466
  rng = rng_for(args.task)
445
467
  draw = rng.random()
@@ -460,6 +482,26 @@ def explore(args) -> str:
460
482
  marker.write_text(chosen + '\n')
461
483
  elif marker.exists():
462
484
  marker.unlink()
485
+ return chosen, decision['chosen_tier']
486
+
487
+
488
+ def assign(args) -> str:
489
+ """`plan`'s resolution of a row: the exploration draw, then the record of the tier its pick runs in,
490
+ newer than any record it replaces. A record that cannot be written is removed rather than left to
491
+ speak for the new pick. Prints the pick; any failure prints SPEC, as explore does."""
492
+ chosen, tier = args.default, args.tier
493
+ with contextlib.suppress(Exception):
494
+ chosen, tier = explore(args)
495
+ try:
496
+ control = _load_control()
497
+ plan = os.path.realpath(args.plan)
498
+ try:
499
+ write_running_tier(plan, args.task, tier, chosen, control)
500
+ except Exception as error:
501
+ print('%s: could not record the tier it runs in: %s' % (args.task, error), file=sys.stderr)
502
+ control.remove_safe(plan, 'tasks/%s/running.tier' % args.task)
503
+ except Exception:
504
+ pass
463
505
  return chosen
464
506
 
465
507
 
@@ -968,7 +1010,7 @@ def record_lateral_tier(plan: str, task: str, row: str, control) -> None:
968
1010
  frm, to = cells[3], cells[4]
969
1011
  tier = running_tier(Path(plan), task, frm)
970
1012
  if tier:
971
- control.write_atomic(plan, 'tasks/%s/running.tier' % task, '%s\t%s\n' % (tier, to))
1013
+ write_running_tier(plan, task, tier, to, control)
972
1014
 
973
1015
 
974
1016
  def main(argv=None) -> int:
@@ -977,6 +1019,10 @@ def main(argv=None) -> int:
977
1019
  p = sub.add_parser('explore')
978
1020
  for name in ('plan', 'task', 'tier', 'epsilon', 'default', 'pools'):
979
1021
  p.add_argument('--' + name, required=True)
1022
+ p = sub.add_parser('assign', help="plan's resolution of a row: exploration, then the record of its tier")
1023
+ for name in ('plan', 'task', 'tier', 'default', 'pools'):
1024
+ p.add_argument('--' + name, required=True)
1025
+ p.add_argument('--epsilon', default='0')
980
1026
  p = sub.add_parser('escalation')
981
1027
  p.add_argument('--plan', required=True)
982
1028
  p.add_argument('--task', required=True)
@@ -1004,10 +1050,13 @@ def main(argv=None) -> int:
1004
1050
  args = ap.parse_args(argv)
1005
1051
  if args.command == 'explore':
1006
1052
  try:
1007
- print(explore(args))
1053
+ print(explore(args)[0])
1008
1054
  except Exception:
1009
1055
  print(args.default)
1010
1056
  return 0
1057
+ if args.command == 'assign':
1058
+ print(assign(args))
1059
+ return 0
1011
1060
  if args.command == 'record':
1012
1061
  return record_escalation(args)
1013
1062
  if args.command == 'lateral':
@@ -306,7 +306,7 @@ def _finish(attempt: Path, root: Path, role: str, harness: str, rc: str) -> None
306
306
  session_path.unlink(missing_ok=True)
307
307
  if found is not None:
308
308
  session_path.write_text(found + '\n')
309
- for suffix in ('prompt', 'last', 'log', 'clock', 'resolved', 'cmd', 'timedout', 'infra', 'orphans',
309
+ for suffix in ('prompt', 'last', 'log', 'clock', 'resolved', 'cmd', 'timedout', 'settled', 'infra', 'orphans',
310
310
  'session', 'continue'):
311
311
  if suffix == 'prompt' and not prompt_ready:
312
312
  continue
@@ -655,6 +655,72 @@ def classify(log: str, harness: str, rc: object, last: str = '', role: str = '',
655
655
  return None
656
656
 
657
657
 
658
+ # --- a final result the CLI stays open after (#110) ----------------------------------
659
+ # claude -p (and openclaude) stays up while a background task its session started is still open,
660
+ # even after the model's final result: one dwarf sat 47 minutes on a finished answer until the
661
+ # watchdog killed it as TIMEOUT. A result is not always the end, though: a background task that
662
+ # completes wakes the session for another turn, sometimes after a long wait (an hour and more on a
663
+ # slow suite). A new turn always opens with system/init, and until one does the only events after
664
+ # a result are the background tasks' own.
665
+ BACKGROUND_EVENTS = ('task_updated', 'task_notification', 'background_tasks_changed', 'hook_started', 'hook_response')
666
+ SETTLE_POLL_S = 5.0
667
+
668
+
669
+ def settled_result(text: str) -> dict | None:
670
+ """The last `result` event when only background-task events follow it: the model ended its turn and
671
+ began no other. None when the log has no result, or a turn is under way after it."""
672
+ found = None
673
+ for event in _events(text)[0]:
674
+ if event.get('type') == 'result':
675
+ found = event
676
+ elif not (event.get('type') == 'system' and event.get('subtype') in BACKGROUND_EVENTS):
677
+ found = None
678
+ return found
679
+
680
+
681
+ def settle(log: str, grace: str, pid: str) -> None:
682
+ """Returns once the harness log ends in a settled result (settled_result) and has not grown for `grace`
683
+ seconds of the machine's awake time; exits 1 once process `pid`, the harness, is gone. dispatch then ends
684
+ the harness: its answer is in, and only a background task keeps it open. An idle log whose last turn is
685
+ still under way (a long command) is never ended here; that is the watchdog's."""
686
+ grace_s, target = float(grace), int(pid)
687
+ poll = min(SETTLE_POLL_S, max(grace_s / 4, 0.05))
688
+ size, since, judged = None, time.monotonic(), None
689
+ while True:
690
+ try:
691
+ os.kill(target, 0)
692
+ except ProcessLookupError:
693
+ sys.exit(1)
694
+ except PermissionError:
695
+ pass
696
+ try:
697
+ now = os.stat(log).st_size
698
+ except OSError:
699
+ now = None
700
+ if now != size:
701
+ size, since = now, time.monotonic()
702
+ elif judged != size and time.monotonic() - since >= grace_s:
703
+ judged = size # read once per size: an idle log mid-turn is not read again and again
704
+ try:
705
+ text = Path(log).read_text(errors='replace')
706
+ except OSError:
707
+ text = ''
708
+ if settled_result(text) is not None:
709
+ return
710
+ time.sleep(poll)
711
+
712
+
713
+ def settled_command(log: str) -> None:
714
+ """Prints `ok`, or `error` for an is_error result, when LOG ends in a settled result; exits 1 otherwise."""
715
+ try:
716
+ event = settled_result(Path(log).read_text(errors='replace'))
717
+ except OSError:
718
+ event = None
719
+ if event is None:
720
+ sys.exit(1)
721
+ print('error' if event.get('is_error') is True else 'ok')
722
+
723
+
658
724
  def classify_command(log: str, harness: str, rc: str, last: str = '', role: str = '') -> None:
659
725
  try:
660
726
  hit = classify(log, harness, rc, last, role)
@@ -691,6 +757,10 @@ def main() -> None:
691
757
  classify_command(*args)
692
758
  elif command == 'clock':
693
759
  clock(*args)
760
+ elif command == 'settle':
761
+ settle(*args)
762
+ elif command == 'settled':
763
+ settled_command(*args)
694
764
  else:
695
765
  raise ValueError('unknown runtime command: ' + command)
696
766
  except (OSError, ValueError, RuntimeError) as error: