harn-stdlib 0.10.133

Embedded Harn standard library source catalog
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
import { CompletionClaim } from "std/agent/completion_claim"
import {
  COMPLETION_VERIFICATION_EVIDENCE_INDEX,
  CompletionEvidenceProjection,
  CompletionEvidenceProjectionStats,
  CompletionEvidenceSnapshot,
  completion_evidence_id,
  completion_requirement_evidence_packet,
} from "std/agent/completion_evidence"
import {
  CompletionRequirementBoundary,
  CompletionRequirementEvidencePacket,
  CompletionRequirementReport,
  completion_requirement_assessments_schema,
  completion_requirement_boundary_report,
  completion_requirement_contract,
  completion_requirement_contract_prompt,
  completion_requirement_ledger_empty,
  completion_requirement_ledger_unassessed,
  completion_requirement_pending_feedback,
  completion_requirement_report,
  completion_requirement_report_omitted,
  completion_requirement_unassessed_feedback,
} from "std/agent/completion_requirements"
pub import {
  COMPLETION_JUDGE_DEFAULT_CAP,
  CompletionReview,
  agent_completion_review,
  agent_completion_review_should_skip_llm,
  agent_verify_completion_judge_cap,
} from "std/agent/completion_review"
import { agent_feedback_emit } from "std/agent/feedback"
pub import {
  CompletionJudgeInvocations,
  CompletionPolicyEvaluation,
  CompletionStageVerdict,
  __completion_arbitrate_contradiction,
  __completion_arbitrate_verification,
} from "std/agent/judge_arbitration"
import { __judge_settle_reply } from "std/agent/judge_contradiction"
import { __judge_evidence_projection_from_lifecycle } from "std/agent/judge_evidence"
import {
  COMPLETION_JUDGE_GAP_CLASSES,
  COMPLETION_VERIFIED_AFTER_WRITE_REASON,
  CompletionJudgeAdmission,
  CompletionJudgeGapClass,
  CompletionVerificationState,
  __completion_judge_gap_class,
  __completion_typed_green_terminal,
  __completion_verification_state_read,
  __judge_checkpoint_unavailable,
  __judge_emit_decision,
  __judge_emit_started,
  __judge_run_checkpoint_bounded,
} from "std/agent/judge_internals"
import { __judge_resolve_itemization } from "std/agent/judge_itemization"
pub import {
  CompletionJudgeGapItem,
  CompletionJudgeVerdict,
  __judge_clamp_completion_detail,
  __judge_completion_verdict_contradicts_itself,
  __judge_completion_verdict_read,
  __judge_completion_verdict_refuses_without_a_gap,
  __judge_completion_verdict_schema,
  __judge_contradiction_feedback,
  __judge_gaps_unattributed_count,
  __judge_ungrounded_gap_quotes,
} from "std/agent/judge_verdict"
import {
  agent_completion_obligations,
  completion_obligations_digest,
  completion_obligations_prompt,
} from "std/agent/obligations"
import { __normalize_judge_config } from "std/agent/options_formats"
import { JudgeConfig } from "std/agent/options_types"
import { __with_prompt_fragment } from "std/agent/preflight"
import { completion_judge_user_prompt } from "std/agent/prompts"
import { agent_emit_event, agent_session_messages } from "std/agent/state"
import {
  AgentTranscriptToolLifecycleReport,
  agent_transcript_tool_lifecycle_report,
} from "std/agent/transcript"
pub import { agent_turn_end_judge_cap } from "std/agent/turn_end"

/** Action the completion-judge model is allowed to return. */
pub type CompletionJudgeAction = "accept" | "continue"

/**
 * Runtime completion decision after deadline and policy enforcement.
 *
 * The two stop actions differ on ONE question: had the deterministic verifier
 * oracle already answered when the loop ran out of judge invocations?
 * `stop_verified` means it had, and it passed; the judge's dissent is kept on
 * the receipt rather than deciding the run. `stop_unverified` is every other
 * stop, including a cap reached over a `failed` or `not_run` oracle.
 */
pub type CompletionDirectiveAction = CompletionJudgeAction | "stop_unverified" | "stop_verified"

pub type CompletionFeedbackDelivery = "none" | "deferred" | "delivered"

pub type CompletionDirectiveReceipt = {
  schema: "harn.completion_directive_receipt.v1",
  evidence_id: string,
  action: CompletionDirectiveAction,
  trigger: string,
  source: string,
  outcome: string,
  reason: string,
  invoked: CompletionJudgeInvocations,
  feedback_delivery: CompletionFeedbackDelivery,
  projection: CompletionEvidenceProjectionStats,
  pending_tool_batch_effect_count: int,
  // The gap the model judge named, and — when an adjudication was overruled —
  // WHAT overruled it. `trigger` names whichever adjudicator ANSWERED, not the
  // boundary that asked, so a reader counting conversions must count
  // `converted_from` and never filter by `trigger`. The completion gate also
  // writes `converted_from`, but only ever a bare ladder reason
  // (`failed_verification`), never an arbitration name, so the two never alias.
  converted_from?: string?,
  gap_class?: string?,
  verification?: CompletionVerificationState?,
  admission?: CompletionJudgeAdmission?,
  checkpoint?: dict?,
  requirements?: CompletionRequirementReport?,
  completion_claim?: CompletionClaim,
}

pub type CompletionDirective = {
  action: CompletionDirectiveAction,
  evidence_id: string,
  feedback?: string?,
  repair?: string?,
  receipt: CompletionDirectiveReceipt,
  feedback_history: dict,
  knowledge_state: string,
}

/**
 * Normalized result from either a deterministic or model completion check.
 * Stable identity for the two model-judge positions in the completion plan.
 */
enum CompletionJudgeSlot {
  Verification
  Completion
}

/** Ordered checks evaluated at one completion boundary. */
enum CompletionPolicyStage {
  Deterministic(check: any)
  ModelJudge(
    slot: CompletionJudgeSlot,
    config: JudgeConfig,
    trigger: string?,
    prior_invocations: int,
    max_invocations: int?,
  )
}

fn __unique_names(names: any) -> list<string> {
  let unique = []
  for name in names {
    if name != "" && !contains(unique, name) {
      unique = unique.appending(name)
    }
  }
  return unique
}

fn __session_tool_names(lifecycle: AgentTranscriptToolLifecycleReport) -> list<string> {
  let names = []
  for call in lifecycle.calls {
    names = names.appending(call.name)
  }
  return __unique_names(names)
}

fn __session_successful_tool_names(lifecycle: AgentTranscriptToolLifecycleReport) -> list<string> {
  let names: list<string> = []
  for call in lifecycle.calls {
    if call.status == "completed" && call.result?.outcome == "ok" {
      names = names + [call.name]
    }
  }
  return __unique_names(names)
}

pub fn __judge_evidence_projection(
  messages: string | bytes | list | dict | set | range | nil,
  opts: dict,
  raw_transcript_digest: any = nil,
) -> CompletionEvidenceProjection {
  return __judge_evidence_projection_from_lifecycle(
    messages,
    agent_transcript_tool_lifecycle_report(messages),
    opts,
    raw_transcript_digest,
  )
}

fn __judge_knowledge_state(lifecycle: AgentTranscriptToolLifecycleReport, text: string) -> string {
  let tool_evidence = []
  for call in lifecycle.calls {
    tool_evidence = tool_evidence.appending(
      {
        name: call.name,
        tool_call_id: call.tool_call_id,
        status: call.status,
        results: call.results.map(
          { result -> {outcome: result.outcome, text: result.text, data: result.data} },
        )
          .to_list(),
      },
    )
  }
  return "sha256:" + sha256(json_stringify({latest_text: text, tool_evidence: tool_evidence}))
}

fn __judge_payload(
  agent: HarnessAgent,
  session: dict,
  opts: dict,
  stop_reason: string,
  text: string,
  iteration: int,
  raw_text: string = "",
) -> CompletionEvidenceSnapshot {
  const messages = agent_session_messages(agent, session.session_id)
  const lifecycle = agent_transcript_tool_lifecycle_report(messages)
  const tool_names = __session_tool_names(lifecycle)
  const successful_tool_names = __session_successful_tool_names(lifecycle)
  const transcript = json_stringify(messages)
  const projected = __judge_evidence_projection_from_lifecycle(
    messages,
    lifecycle,
    opts,
    "sha256:" + sha256(transcript),
  )
  const evidence_packet = completion_requirement_evidence_packet(projected.packet, text)
  const evidence_serialized = json_stringify(evidence_packet)
  const evidence_stats = projected.stats + {serialized_chars: len(evidence_serialized)}
  const pending_tool_batch_effect_count = len(
    opts?._tool_batch_dependency_state?.deferred_signatures ?? [],
  )
  // Read from the session's control records, not from `messages`: an accepted
  // stop delivers no user message, so the transcript in hand cannot show one.
  const obligations = agent_completion_obligations(agent, session.session_id, session?.task ?? "")
  const evidence_id = completion_evidence_id(
    session?.task ?? "",
    stop_reason,
    text,
    evidence_packet,
    pending_tool_batch_effect_count,
    nil,
    completion_obligations_digest(obligations),
  )
  let payload = {
    schema: "harn.completion_evidence_snapshot.v1",
    evidence_id: evidence_id,
    session_id: session.session_id,
    task: session?.task ?? "",
    obligations: obligations,
    stop_reason: stop_reason,
    text: text,
    visible_text: text,
    last_text: text,
    raw_text: raw_text == "" ? text : raw_text,
    transcript: transcript,
    judge_evidence: evidence_serialized,
    judge_evidence_packet: evidence_packet,
    judge_evidence_projection: evidence_stats,
    all_tools_used: join(tool_names, ", "),
    successful_tools_used: join(successful_tool_names, ", "),
    iteration: iteration,
    knowledge_state: __judge_knowledge_state(lifecycle, text),
    pending_tool_batch_effect_count: pending_tool_batch_effect_count,
    verification: nil,
  }
  if opts?._completion_claim != nil {
    payload = payload + {completion_claim: opts._completion_claim}
  }
  return payload
}

/** Bind a gate reading onto the snapshot the remaining stages will be shown. */
fn __judge_payload_with_verification(
  payload: CompletionEvidenceSnapshot,
  state: CompletionVerificationState?,
) -> CompletionEvidenceSnapshot {
  if state == nil {
    return payload
  }
  const verification = state
    + {observed_at_evidence_index: COMPLETION_VERIFICATION_EVIDENCE_INDEX}
  const evidence_packet = completion_requirement_evidence_packet(
    payload.judge_evidence_packet,
    payload.last_text,
    verification,
  )
  const evidence_serialized = json_stringify(evidence_packet)
  return payload
    + {
      evidence_id: completion_evidence_id(
        payload.task,
        payload.stop_reason,
        payload.last_text,
        evidence_packet,
        payload.pending_tool_batch_effect_count,
        verification,
        completion_obligations_digest(payload?.obligations),
      ),
      judge_evidence: evidence_serialized,
      judge_evidence_packet: evidence_packet,
      judge_evidence_projection: payload.judge_evidence_projection
        + {serialized_chars: len(evidence_serialized)},
      verification: verification,
    }
}

fn __judge_stable_prefix(
  judge_cfg: any,
  opts: dict,
  payload: CompletionEvidenceSnapshot,
  system: string,
  schema: any,
) -> string {
  const rubric = trim(to_string(judge_cfg?.rubric ?? opts?.rubric ?? ""))
  const rubric_block = if rubric == "" {
    ""
  } else {
    "\n\nCompletion rubric:\n" + rubric
  }
  const requirement_block = completion_requirement_contract_prompt(
    completion_requirement_contract(judge_cfg?.requirement_contract),
  )
  // The steering block sits AFTER the goal, rubric, and requirement rows so its
  // supersession clause reads over all of them. It renders empty for an
  // unsteered run, which keeps that run's prefix byte-identical (and cacheable).
  return system
    + "\n\nStable completion goal:\n"
    + payload.task
    + rubric_block
    + requirement_block
    + completion_obligations_prompt(payload?.obligations)
    + "\n\nRequired verdict schema:\n"
    + json_stringify(schema)
}

fn __judge_invoke_closure(
  verify_completion: unknown,
  payload: CompletionEvidenceSnapshot,
) -> CompletionStageVerdict {
  const result = verify_completion(payload)
  if result == nil || result == "" {
    return {vetoed: false, confirm: true, source: "deterministic", trigger: "verify_completion"}
  }
  if type_of(result) == "bool" {
    return {vetoed: !result, confirm: result, source: "deterministic", trigger: "verify_completion"}
  }
  if type_of(result) == "string" {
    return {
      vetoed: true,
      feedback: result,
      confirm: false,
      source: "deterministic",
      trigger: "verify_completion",
    }
  }
  if type_of(result) == "dict" {
    const confirm = result?.confirm == true
    const message = to_string(result?.message ?? result?.feedback ?? "")
    return {
      vetoed: !confirm,
      feedback: message,
      confirm: confirm,
      verification: __completion_verification_state_read(result?.verification),
      requirement_report: result?.requirement_report,
      source: "deterministic",
      reason: if result?.reason == nil {
        nil
      } else {
        to_string(result.reason)
      },
      converted_from: if result?.converted_from == nil {
        nil
      } else {
        to_string(result.converted_from)
      },
      escalation_recommended: if result?.escalation_recommended == nil {
        nil
      } else {
        result.escalation_recommended
      },
      escalation_target: if result?.escalation_target == nil {
        nil
      } else {
        to_string(result.escalation_target)
      },
      trigger: to_string(result?.trigger ?? "verify_completion"),
    }
  }
  return {
    vetoed: false,
    confirm: false,
    source: "deterministic",
    trigger: "verify_completion",
    reason: "completion_verifier_invalid_result",
    terminal_judge_reason: "completion_verifier_invalid_result",
    terminal_evidence_preserved: true,
  }
}

fn __judge_invoke_structured(
  harness: Harness,
  judge_cfg: JudgeConfig,
  opts: dict,
  payload: CompletionEvidenceSnapshot,
) -> CompletionStageVerdict {
  const system = judge_cfg.system ?? ""
  const contract = completion_requirement_contract(judge_cfg.requirement_contract)
  const schema = __judge_completion_verdict_schema(contract)
  agent_emit_event(
    harness.agent,
    payload.session_id,
    "typed_checkpoint",
    payload.judge_evidence_projection,
  )
  const stable_prefix = __judge_stable_prefix(judge_cfg, opts, payload, system, schema)
  const user = completion_judge_user_prompt(harness.fs, payload)
  const ran = __judge_run_checkpoint_bounded(
    harness,
    {
      judge_cfg: judge_cfg,
      opts: opts,
      payload: payload,
      checkpoint_name: "agent.completion_judge",
      system: stable_prefix,
      user: user,
      schema: schema,
    },
  )
  const checkpoint = ran.checkpoint
  const duration_ms = ran.duration_ms
  if !checkpoint.ok {
    const unavailable = __judge_checkpoint_unavailable(checkpoint)
    if unavailable {
      const judge_outcome = if checkpoint?.status == "admission_refused" {
        "admission_refused"
      } else if checkpoint?.status == "model_unconfigured" {
        // Its own outcome, not a timeout. A misconfiguration reported as a
        // deadline sends the reader to look at latency for a setting that was
        // never set, which is how this class of defect stays open.
        "model_unconfigured"
      } else {
        "timeout"
      }
      const terminal_reason = if judge_outcome == "admission_refused" {
        "completion_judge_deadline_admission_refused"
      } else if judge_outcome == "model_unconfigured" {
        "completion_judge_model_unconfigured"
      } else {
        "completion_judge_deadline_timeout"
      }
      return {
        vetoed: false,
        confirm: false,
        verdict: "unavailable",
        reasoning: to_string(checkpoint.error),
        next_step: "",
        judge_duration_ms: duration_ms,
        source: "llm",
        judge_outcome: judge_outcome,
        reason: terminal_reason,
        terminal_judge_reason: terminal_reason,
        terminal_evidence_preserved: true,
        admission: ran.admission,
        typed_checkpoint: checkpoint,
      }
    }
    // A completion judge is an authority gate, not an advisory reviewer. If it
    // cannot decide, the claim remains unverified.
    //
    // The reply was retried to its bound and still could not be read, so this
    // authority is spent. It terminates on its own reason rather than vetoing:
    // a `continue` here is a veto no turn can answer, which leaves the run to
    // die on an unrelated budget with an unrelated reason. `terminal_judge_reason`
    // is the same field the deadline path above already sets, so both exit
    // authorities read this stop through the vocabulary they already share.
    return {
      vetoed: false,
      confirm: false,
      feedback: to_string(checkpoint.error),
      verdict: "unavailable",
      reasoning: to_string(checkpoint.error),
      next_step: "",
      judge_duration_ms: duration_ms,
      source: "llm",
      judge_outcome: "error",
      reason: "completion_judge_error",
      terminal_judge_reason: "completion_judge_error",
      terminal_evidence_preserved: true,
      admission: ran.admission,
      typed_checkpoint: checkpoint,
    }
  }
  const reask_request = {
    judge_cfg: judge_cfg,
    opts: opts,
    payload: payload,
    checkpoint_name: "agent.completion_judge",
    system: stable_prefix,
    user: user,
    schema: schema,
  }
  // A judge that answered `done` without itemizing has assessed nothing. Re-ask
  // the JUDGE once, rather than sending the actor feedback it cannot act on.
  const resolved = __judge_resolve_itemization(
    harness,
    reask_request,
    contract,
    checkpoint.data,
    __judge_completion_verdict_read(checkpoint.data).verdict == "done",
  )
  const itemized_decoded = __judge_completion_verdict_read(
    resolved.data,
    contract,
    payload.judge_evidence_packet,
  )
  // Both re-ask reasons, in order, owned by the module that owns re-asks: a
  // `done` that also names a gap (harn#8060), then a refusal quoting evidence
  // it was never shown (#8100). The sequencing lives there so this function
  // does not grow a second copy of "re-ask, then re-decode, then remember which
  // reply is now of record".
  const settled = __judge_settle_reply(
    harness,
    reask_request,
    contract,
    payload,
    resolved.data,
    itemized_decoded,
  )
  const decoded = settled.decoded
  const reply_of_record = settled.reply_of_record
  const requirement_report = decoded.requirement_report
  const unassessed = resolved.omitted && requirement_report != nil
  // A judge that REFUSED and itemized nothing has assessed nothing either, but
  // unlike the approval path there is nothing to fail closed against: a
  // `continue` closes no ledger. Charging it as pending would hand the actor a
  // complaint about rows nobody looked at, naming evidence kinds the actor does
  // not supply, in place of the reason the judge actually gave.
  const declined_unassessed = requirement_report != nil
    && !resolved.omitted
    && completion_requirement_report_omitted(contract, reply_of_record?.requirement_report)
  const requirements_pending = requirement_report != nil
    && !requirement_report.complete
    && !declined_unassessed
  // A judge that accepts while naming ANY gap — one of the four named classes
  // or a bare `other` — has contradicted itself inside one object, and the
  // contradiction is readable without a model. Taking the verdict and
  // dropping the gap is how a run that was blocked from doing its work
  // reaches a host as `done`, `natural`, with no stop reason. `other` is not
  // exempted: it is the value a compliant `done` reply leaves the field unset
  // for, so a `done` that populates it anyway — even with `other` — is the
  // same self-contradiction wearing the one label this check used to let
  // through (harn#7910). The gap is the half backed by evidence, so it wins.
  const gap_contradicts_done = __judge_completion_verdict_contradicts_itself(decoded)
  // The converse shape — a `continue` that itemizes nothing, newly reachable
  // now that the reply schema no longer carries a one-item minimum on `gaps` —
  // is deliberately NOT named here. `reason` falls through to the judge's own
  // words when the gate has nothing to say, and the actor needs those words: a
  // refusal that hands back a policy code instead of the condition it found
  // unmet cannot be acted on. The receipt already carries `gap_count`, so a
  // `continue` with zero is legible as the malformed reply it is, in a field
  // that costs the actor nothing. See
  // `__judge_completion_verdict_refuses_without_a_gap` for the typed rule.
  const verdict = requirements_pending || gap_contradicts_done ? "continue" : decoded.verdict
  const detail = if unassessed {
    completion_requirement_unassessed_feedback(requirement_report)
  } else if requirements_pending {
    completion_requirement_pending_feedback(requirement_report)
  } else if gap_contradicts_done {
    // The branch that used to fall through to `decoded.detail`, which on this
    // path is the judge's own rationale for DONE. Handing that back as the
    // reason a run may not stop tells the actor its work is complete, so the
    // veto reads as an approval and the actor correctly does nothing. Measured
    // on three read-only review cells: five conversions in a row, the same
    // sentence re-injected each time, one tool call across seven iterations,
    // and the run ended at the judge cap. A veto has to name the condition it
    // found unmet, or it cannot advance the loop it just refused to end.
    __judge_contradiction_feedback(decoded)
  } else {
    decoded.detail
  }
  const feedback_default = judge_cfg.feedback_fallback ?? ""
  const feedback = if detail == "" {
    feedback_default
  } else {
    detail
  }
  return {
    vetoed: verdict == "continue",
    verdict: verdict,
    gap_class: decoded.gap_class,
    // Whether the self-contradiction was already pointed out to the judge and
    // came back anyway. The arbitration below reads it so a FIRST contradiction
    // is never overruled — only one that survived its resolution.
    contradiction_reasked: settled.contradiction_reasked,
    reason: if unassessed {
      "completion_judge_report_omitted"
    } else if requirements_pending {
      "completion_requirements_pending"
    } else if gap_contradicts_done {
      "completion_judge_gap_contradicts_done"
    } else {
      nil
    },
    feedback: if verdict == "continue" {
      feedback
    } else {
      nil
    },
    reasoning: detail,
    next_step: if verdict == "continue" {
      detail
    } else {
      ""
    },
    judge_duration_ms: duration_ms,
    // The judge's OWN answer, kept whether or not it survived. `verdict` above
    // is the answer of record and may be an override's; without this field a
    // reader cannot tell the two apart, and a record that reports an override
    // under the judge's name is not a record of what happened.
    judge_verdict: decoded.verdict,
    // The party that produced `judge_verdict`. STABLE across an override, so
    // downstream arbitration can still ask "was this a model judge's refusal"
    // without reading `source`, whose meaning changes below.
    judge_source: "llm",
    // `source` names the party whose answer `verdict` IS, not the slot the
    // decision came through. It read "llm" unconditionally, so every override
    // above was published as the model's own word.
    source: if verdict == decoded.verdict {
      "llm"
    } else {
      "gate"
    },
    // Typed, so a consumer reads the overriding party and the rule applied
    // rather than pattern-matching prose. Absent when nothing was overridden.
    override: if verdict == decoded.verdict {
      nil
    } else {
      {
        party: "gate",
        rule: if requirements_pending {
          "completion_requirements_pending"
        } else {
          "completion_judge_gap_contradicts_done"
        },
        judge_verdict: decoded.verdict,
      }
    },
    admission: ran.admission,
    typed_checkpoint: checkpoint,
    requirement_report: requirement_report,
  }
}

/**
 * agent_judge_config.
 *
 * Normalize a `turn_end_condition` or `verify_completion_judge` option. Returns nil when
 * no judge can run — absent, `false`, or a value of a type the judge seam
 * cannot invoke — and the configuration dict otherwise. `true` normalizes to an
 * empty dict, meaning "a judge with default settings".
 *
 * @effects: []
 * @errors: []
 * @api_stability: experimental
 * @example: agent_judge_config(opts?.turn_end_condition)
 */
pub fn agent_judge_config(judge_cfg: JudgeConfig?) -> JudgeConfig? {
  return __normalize_judge_config(judge_cfg)
}

fn __done_contract_primary_prompt(opts: dict) {
  const marker = to_string(opts?.done_sentinel ?? "the configured done sentinel")
  return join(
    [
      "Before yielding as done, state a concise Done claim immediately before " + marker + ".",
      "The claim must cover: requested work, evidence observed, files or artifacts changed, and anything deliberately not done.",
      "Do not claim completion from a green self-authored check alone; connect the evidence back to the user's visible request.",
    ],
    "\n",
  )
}

pub fn __done_contract_judge_system(opts: dict) -> string {
  const extra = trim(to_string(opts?.rubric ?? ""))
  let lines = [
    "You are a strict done-contract judge for an autonomous agent.",
    "Decide whether the latest completion claim is justified by the task, transcript, tool results, and changed artifacts.",
    "Return `done` only when the claim covers the visible request and names adequate evidence.",
    "Return `continue` when evidence is missing, self-authored tests are too weak, or visible requirements are unaddressed.",
    "Judge the substance of the claim, never its wire format. Response markers, sentinels, and layout are enforced elsewhere, and their absence is never a reason to continue.",
    "On `done`, use `detail` for the strongest evidence that every requirement is met, and set no gap fields.",
    // The old instruction here was "use `detail` for the single most important
    // gap". A judge holding three objections could not state them, so it named
    // one, the actor fixed it, and the next invocation named the next. The
    // default cap is three. See #8100.
    "On `continue`, list in `gaps` EVERY gap you currently hold — not the most important one.",
    "The actor can only converge on a set it is shown in full, and you may not add a criterion later that you could have named now.",
    "Give each gap the `criterion` from the task it is against, and the substantive next action that closes it, never a restatement or formatting instruction.",
    // #8091: the refusals read like a judge restating its previous position
    // rather than re-reading the current state. The packet labels the current
    // file view; nothing told the judge it outranks what it said last round.
    "Where the evidence shows a labelled current-state view of a file, that view is the file's state NOW.",
    "It supersedes anything you or the actor said about that file in an earlier round, including your own previous verdict.",
    "When a gap is about the content of a file shown in the evidence above, copy the line that proves it into `evidence_quote`, verbatim.",
    "A quote that does not appear in that evidence is refused and sent back to you, so quote what is there rather than what you expect to be there.",
    "Keep `detail` as the one-line summary of the whole refusal.",
  ]
  if extra != "" {
    lines = lines.appending("Additional rubric:\n" + extra)
  }
  return join(lines, "\n")
}

/**
 * agent_done_contract.
 *
 * Build an agent_loop option bundle for a bidirectional done contract:
 * the primary agent must state a concise completion claim before yielding, and
 * the turn-end judge must return one bounded evidence detail on approval or one
 * bounded gap-and-action detail on veto. The helper rides the existing `turn_end_condition`
 * seam and context-profile prompt-fragment channel; it does not add a new loop
 * hook. Compose it with base options:
 *
 * ```harn,ignore
 * agent_loop(harness, task, nil, base_opts + agent_done_contract({max_invocations: 3}))
 * ```
 *
 * @effects: []
 * @errors: [runtime]
 * @api_stability: experimental
 */
pub fn agent_done_contract(options: dict = {}) -> dict {
  const opts = if type_of(options) == "dict" {
    options
  } else {
    {}
  }
  const judge = if type_of(opts?.judge) == "dict" {
    opts.judge
  } else {
    {}
  }
  const max_invocations = opts?.max_invocations ?? judge?.max_invocations ?? 3
  const bundle = {
    turn_end_condition: judge
      + {
        feedback_fallback: opts?.feedback_fallback
          ?? judge?.feedback_fallback
          ?? "The done claim is not yet justified; address the specific gaps before finishing.",
        max_invocations: max_invocations,
        model: opts?.model ?? judge?.model,
        provider: opts?.provider ?? judge?.provider,
        system: opts?.system ?? judge?.system ?? __done_contract_judge_system(opts),
      },
    loop_until_done: opts?.loop_until_done ?? true,
  }
  return __with_prompt_fragment(
    bundle,
    {body: __done_contract_primary_prompt(opts), id: "done_contract", source: "std/agent/judge"},
  )
}

fn __judge_directive(
  verdict: dict,
  payload: dict,
  invoked: any,
  completion_judge_cap_reached: any,
  turn_end_judge_cap_reached: any,
  feedback_composition: any,
  feedback_history: dict,
  defer_feedback: bool,
  ledger: CompletionRequirementReport,
) -> CompletionDirective {
  const terminal_reason = trim(to_string(verdict?.terminal_judge_reason ?? ""))
  // A cap is a statement about the JUDGE running out of turns, not about the
  // work. When the deterministic oracle already ran and passed, the run has a
  // stronger answer than the judge was being asked for, so the cap stops it as
  // verified and the dissent stays on the receipt (`outcome`, `gap_class`,
  // `reason`) for whoever grades it later. `observed` is a positive reading
  // ONLY on "passed": `not_run` also covers "the gate could not read facts",
  // and treating that as verified would convert a genuine non-convergence into
  // a clean stop, which is the worse defect. An explicit
  // `terminal_judge_reason` is untouched — that is the judge naming a terminal,
  // not the loop running out of room.
  //
  // The ledger is the second half of that reading, and for the same reason the
  // typed-green skip needs it: the verifier answers "did the declared command
  // pass", never "was each thing the task asked for delivered". A cap reached
  // over outstanding acceptance rows has a judge that spent its budget SAYING
  // SO, so converting it to a verified stop seals a done its own transcript
  // refuses. See harn#8110.
  const cap_reached = completion_judge_cap_reached || turn_end_judge_cap_reached
  const verified_at_cap = cap_reached
    && terminal_reason == ""
    && to_string(payload?.verification?.observed ?? "") == "passed"
    && ledger.pending_count == 0
  const action = if verified_at_cap {
    "stop_verified"
  } else if terminal_reason != "" || cap_reached {
    "stop_unverified"
  } else if verdict.vetoed {
    "continue"
  } else {
    "accept"
  }
  // A cap over a passed oracle gets its OWN wire reason. Reusing the cap label
  // would leave a run that finished and one that never converged sharing a
  // single value, which is what #8058 is about. Which cap it was is not lost:
  // `invoked` on the same receipt names the judge that ran.
  const reason = if verified_at_cap {
    "judge_cap_reached_over_verified_pass"
  } else if terminal_reason != "" {
    terminal_reason
  } else if completion_judge_cap_reached {
    "completion_judge_cap_reached"
  } else if turn_end_judge_cap_reached {
    "turn_end_judge_cap_reached"
  } else {
    to_string(verdict?.reason ?? verdict?.reasoning ?? "")
  }
  const has_feedback = verdict.vetoed
    && trim(to_string(verdict?.feedback ?? "")) != ""
  const feedback_delivery = if len(feedback_composition?.messages ?? []) > 0 {
    "delivered"
  } else if has_feedback && defer_feedback {
    "deferred"
  } else {
    "none"
  }
  const receipt = {
    schema: "harn.completion_directive_receipt.v1",
    evidence_id: payload.evidence_id,
    action: action,
    trigger: verdict?.trigger ?? payload.stop_reason,
    source: verdict?.source ?? "policy",
    outcome: verdict?.judge_outcome ?? verdict?.verdict ?? action,
    reason: reason,
    invoked: invoked,
    feedback_delivery: feedback_delivery,
    projection: payload.judge_evidence_projection,
    pending_tool_batch_effect_count: payload.pending_tool_batch_effect_count,
    converted_from: verdict?.converted_from,
    gap_class: verdict?.gap_class,
    // Attribution coverage for this refusal, so a set of gaps that names no
    // acceptance row is visible instead of silently absent. A non-zero count
    // means either the ledger does not cover what the judge objected to, or the
    // judge objected outside the contract (#8104).
    gap_count: len(verdict?.gaps ?? []),
    gaps_unattributed: __judge_gaps_unattributed_count(verdict?.gaps ?? []),
    verification: payload.verification,
    admission: verdict?.admission,
    checkpoint: verdict?.typed_checkpoint,
    // A receipt describes the whole boundary, not only the last adjudicator.
    // Explicit emptiness on a done distinguishes no declarations from lost data.
    requirements: if ledger.required_count > 0 || ledger.pending_count > 0
      || action == "accept"
      || action == "stop_verified" {
      ledger
    } else {
      nil
    },
    completion_claim: payload?.completion_claim,
  }
  return {
    action: action,
    evidence_id: payload.evidence_id,
    feedback: verdict?.feedback,
    repair: verdict?.next_step,
    receipt: receipt,
    feedback_history: feedback_history,
    // A caller that owns delivery needs the same composition context the
    // inline emit above would have used, or its feedback is deduplicated
    // against a knowledge state it cannot see.
    knowledge_state: payload.knowledge_state,
  }
}

fn __completion_judge_applies(stop_reason: string, due: bool) -> bool {
  if !due {
    return false
  }
  return contains(["sentinel", "natural", "stalled", "explicit_completion_claim"], stop_reason)
}

/** Build the one ordered plan for a completion boundary. */
fn __completion_policy_plan(
  opts: dict,
  stop_reason: string,
  review: CompletionReview = {scrutiny: "standard"},
) -> list<CompletionPolicyStage> {
  let stages: list<CompletionPolicyStage> = []
  if opts?.verify_completion != nil {
    stages = stages + [CompletionPolicyStage.Deterministic(opts.verify_completion)]
  }
  const verification_config = agent_judge_config(opts?.verify_completion_judge)
  if verification_config != nil {
    stages = stages
      + [
        CompletionPolicyStage.ModelJudge(
          CompletionJudgeSlot.Verification(),
          verification_config,
          opts?._verify_completion_judge_trigger,
          opts?._verify_completion_judge_invocations ?? 0,
          agent_verify_completion_judge_cap(verification_config, review),
        ),
      ]
  }
  const completion_config = agent_judge_config(opts?.turn_end_condition)
  if completion_config != nil
    && __completion_judge_applies(stop_reason, opts?._turn_end_judge_due ?? true) {
    stages = stages
      + [
        CompletionPolicyStage.ModelJudge(
          CompletionJudgeSlot.Completion(),
          completion_config,
          opts?._turn_end_judge_trigger,
          opts?._turn_end_judge_invocations ?? 0,
          agent_turn_end_judge_cap(completion_config),
        ),
      ]
  }
  return stages
}

/**
 * Whether this run declares anything that could adjudicate a completion at
 * `stop_reason`.
 *
 * A caller that is about to end the run and wants the turn adjudicated first
 * needs to know whether asking is worth a provider call — and, more importantly,
 * whether an answer it gets back means anything. An evaluation with no stages is
 * not vetoed, so the directive seals `accept`: silence read as approval. Ask
 * this before evaluating, and treat a false as "nobody was asked".
 *
 * The plan is the single owner of what counts as an adjudicator; this only
 * reports whether it produced any stages.
 *
 * @effects: []
 * @errors: []
 * @api_stability: experimental
 * @example: agent_completion_adjudicator_declared(opts, "stalled")
 */
pub fn agent_completion_adjudicator_declared(opts: dict, stop_reason: string) -> bool {
  return len(__completion_policy_plan(opts, stop_reason)) > 0
}

fn __completion_policy_initial_evaluation(
  payload: CompletionEvidenceSnapshot,
  boundary: CompletionRequirementBoundary,
) -> CompletionPolicyEvaluation {
  return {
    verdict: {vetoed: false},
    invoked: {deterministic: false, verify_completion_judge: false, turn_end_condition: false},
    verification_judge_cap_reached: false,
    completion_judge_cap_reached: false,
    payload: payload,
    deterministic_reason: "",
    requirement_boundary: boundary,
    ledger: completion_requirement_boundary_report(boundary),
  }
}

/** Declarations stay pending until their owning adjudicator assesses them. */
fn __completion_boundary_requirements(opts: dict) -> CompletionRequirementBoundary {
  return {
    gate: completion_requirement_ledger_empty(),
    verification: completion_requirement_ledger_unassessed(
      completion_requirement_contract(opts?.verify_completion_judge?.requirement_contract),
    ),
    completion: completion_requirement_ledger_unassessed(
      completion_requirement_contract(opts?.turn_end_condition?.requirement_contract),
    ),
  }
}

fn __completion_policy_can_advance(evaluation: CompletionPolicyEvaluation) -> bool {
  return !evaluation.verdict.vetoed
    && trim(to_string(evaluation.verdict.terminal_judge_reason ?? ""))
      == ""
    && !evaluation.verification_judge_cap_reached
    && !evaluation.completion_judge_cap_reached
}

fn __completion_policy_mark_cap(
  evaluation: CompletionPolicyEvaluation,
  slot: CompletionJudgeSlot,
) -> CompletionPolicyEvaluation {
  match slot {
    Verification() -> { return evaluation + {verification_judge_cap_reached: true} }
    Completion() -> { return evaluation + {completion_judge_cap_reached: true} }
  }
}

fn __completion_policy_mark_model_invoked(
  evaluation: CompletionPolicyEvaluation,
  slot: CompletionJudgeSlot,
  invoked: bool,
) -> CompletionPolicyEvaluation {
  const prior = evaluation.invoked
  match slot {
    Verification() -> { return evaluation
      + {invoked: prior + {verify_completion_judge: invoked}} }
    Completion() -> { return evaluation + {invoked: prior + {turn_end_condition: invoked}} }
  }
}

fn __completion_policy_run_stage(
  harness: Harness,
  opts: dict,
  iteration: int,
  evaluation: CompletionPolicyEvaluation,
  stage: CompletionPolicyStage,
) -> CompletionPolicyEvaluation {
  const payload = evaluation.payload
  match stage {
    Deterministic(check) -> {
      const verdict = __judge_invoke_closure(check, payload)
      const boundary = evaluation.requirement_boundary
        + {gate: verdict.requirement_report ?? completion_requirement_ledger_empty()}
      __judge_emit_decision(harness.agent, payload.session_id, iteration, verdict)
      return evaluation
        + {
          verdict: verdict,
          invoked: evaluation.invoked + {deterministic: true},
          payload: __judge_payload_with_verification(payload, verdict.verification),
          deterministic_reason: to_string(verdict.reason ?? ""),
          requirement_boundary: boundary,
          ledger: completion_requirement_boundary_report(boundary),
        }
    }
    ModelJudge(slot, config, trigger, prior_invocations, max_invocations) -> {
      if max_invocations != nil && prior_invocations >= max_invocations {
        return __completion_policy_mark_cap(evaluation, slot)
      }
      // Decide whether the LLM confirmation is needed BEFORE announcing that a
      // judge started. A skipped judge never ran, so emitting a started event
      // for it would put a call in the timeline that no decision ever answers.
      //
      // THE VERIFICATION DECIDES FIRST, for BOTH slots. The deterministic oracle
      // already answered this boundary's question: the declared verifier passed
      // over a source write and the turn is the sealed final answer. A model call
      // here can only agree, disagree with the runtime's own reading, or fail to
      // return before the headless wall — and all three have been observed. One
      // predicate, read by both callers, so the rule cannot be half-applied.
      // See harn#8110.
      //
      // The acceptance ledger is read here too, BEFORE the judge, because the
      // pending-requirements check that turns a done into a continue lives
      // inside the structured invocation. A skip blind to it would take the
      // ledger with the judge. Every stage reads the same combined report, so
      // this skip, the catalog skip, and the cap conversion cannot disagree.
      const ledger = evaluation.ledger
      if __completion_typed_green_terminal(
        {
          deterministic_invoked: evaluation.invoked.deterministic,
          deterministic_reason: evaluation.deterministic_reason,
          oracle_expected: payload.verification?.oracle_expected ?? false,
          observed: to_string(payload.verification?.observed ?? "not_run"),
          stop_reason: payload.stop_reason,
          final_text: payload.text,
          pending_tool_batch_effect_count: payload.pending_tool_batch_effect_count,
          ledger_pending_count: ledger.pending_count,
        },
      ) {
        const verified_terminal = {
          vetoed: false,
          verdict: "done",
          source: "gate",
          judge_outcome: "skipped_verified_after_write",
          reason: COMPLETION_VERIFIED_AFTER_WRITE_REASON,
          judge_duration_ms: 0,
          trigger: trigger,
          // Preserve the gate's supporting rows when the model is skipped.
          requirement_report: ledger,
        }
        __judge_emit_decision(harness.agent, payload.session_id, iteration, verified_terminal)
        return evaluation + {verdict: verified_terminal}
      }
      match slot {
        Verification() -> {
          // SUBORDINATE to the reading above, deliberately. This rule is
          // catalog-declared: a model row opts into `light` scrutiny and the
          // judge is skipped on a sentinel the gate accepted. It never reads the
          // verification at all, so on a typed green terminal it was deciding —
          // by a model's catalog row — a question the oracle had answered. It now
          // only decides what the verification did not, and its own receipt
          // (`source: "catalog"`) still says which rule fired.
          //
          // The ledger clause applies to this skip for the same reason it
          // applies above: a skipped judge is a skipped pending-requirements
          // check, whichever rule did the skipping.
          if ledger.pending_count == 0
            && agent_completion_review_should_skip_llm(
              agent_completion_review(harness.llm, opts),
              evaluation,
              payload,
            ) {
            const skipped = {
              vetoed: false,
              verdict: "done",
              source: "catalog",
              judge_outcome: "skipped_light_scrutiny",
              judge_duration_ms: 0,
              trigger: trigger,
              requirement_report: ledger,
            }
            __judge_emit_decision(harness.agent, payload.session_id, iteration, skipped)
            return evaluation + {verdict: skipped}
          }
        }
        Completion() -> {
          // No catalog rule reaches this slot; the reading above is the whole
          // skip decision for it.
        }
      }
      __judge_emit_started(harness.agent, payload.session_id, iteration, trigger)
      let verdict = __judge_invoke_structured(harness, config, opts, payload)
      verdict = __completion_arbitrate_contradiction(
        __completion_arbitrate_verification(verdict, evaluation),
        evaluation,
      )
        + {trigger: trigger}
      __judge_emit_decision(harness.agent, payload.session_id, iteration, verdict)
      const report = verdict.requirement_report
      let boundary = evaluation.requirement_boundary
      if report != nil {
        match slot {
          Verification() -> { boundary = boundary + {verification: report} }
          Completion() -> { boundary = boundary + {completion: report} }
        }
      }
      const next = evaluation
        + {
          verdict: verdict,
          requirement_boundary: boundary,
          ledger: completion_requirement_boundary_report(boundary),
        }
      return __completion_policy_mark_model_invoked(
        next,
        slot,
        verdict.judge_outcome != "admission_refused",
      )
    }
  }
}

fn __completion_policy_evaluate(
  harness: Harness,
  opts: dict,
  payload: CompletionEvidenceSnapshot,
  iteration: int,
  stages: list<CompletionPolicyStage>,
  boundary: CompletionRequirementBoundary,
) -> CompletionPolicyEvaluation {
  let evaluation = __completion_policy_initial_evaluation(payload, boundary)
  for stage in stages {
    if !__completion_policy_can_advance(evaluation) {
      break
    }
    evaluation = __completion_policy_run_stage(harness, opts, iteration, evaluation, stage)
  }
  return evaluation
}

/**
 * Evaluate one verification/completion boundary and return one typed directive.
 *
 * `text` is the projected candidate turn — what a reader should be shown.
 * `raw_text` is that same turn before projection, and is the field a policy
 * must read to decide whether the model declared completion: the parser has
 * already stripped completion markers out of `text`. Callers with the
 * unprojected turn in hand should pass it; omitting it leaves `raw_text`
 * equal to `text`, which preserves the pre-existing behavior.
 *
 * @effects: [agent, host, llm.call]
 * @errors: []
 */
pub fn agent_evaluate_completion(
  harness: Harness,
  session: dict,
  opts: dict,
  stop_reason: string,
  text: string,
  iteration: int = 0,
  raw_text: string = "",
) -> CompletionDirective {
  const payload = __judge_payload(
    harness.agent,
    session,
    opts,
    stop_reason,
    text,
    iteration,
    raw_text,
  )
  const stages = __completion_policy_plan(
    opts,
    stop_reason,
    agent_completion_review(harness.llm, opts),
  )
  const evaluation = __completion_policy_evaluate(
    harness,
    opts,
    payload,
    iteration,
    stages,
    __completion_boundary_requirements(opts),
  )
  let verdict = evaluation.verdict
  if __completion_policy_can_advance(evaluation) && evaluation.ledger.pending_count > 0 {
    verdict = verdict
      + {
        vetoed: true,
        verdict: "continue",
        reason: "completion_requirements_pending",
        feedback: completion_requirement_pending_feedback(evaluation.ledger),
        requirement_report: evaluation.ledger,
      }
  }
  // The evaluated snapshot, not the one built before any stage ran: it is the
  // one carrying whatever the deterministic gate observed.
  const evaluated = evaluation.payload
  let feedback_composition = nil
  if verdict.vetoed
    && verdict.feedback != nil
    && verdict.feedback != ""
    && !(opts?._defer_judge_feedback ?? false) {
    feedback_composition = agent_feedback_emit(
      harness.agent,
      session.session_id,
      [
        {
          kind: "verify_completion",
          content: verdict.feedback,
          source: verdict.trigger ?? "completion_judge",
          reason: "judge_veto",
          action: "continue",
          next_step: verdict.next_step ?? "",
        },
      ],
      {history: opts?._feedback_history ?? {}, knowledge_state: evaluated.knowledge_state},
    )
  }
  const directive = __judge_directive(
    verdict,
    evaluated,
    evaluation.invoked,
    evaluation.verification_judge_cap_reached,
    evaluation.completion_judge_cap_reached,
    feedback_composition,
    feedback_composition?.history ?? opts?._feedback_history ?? {},
    opts?._defer_judge_feedback ?? false,
    evaluation.ledger,
  )
  agent_emit_event(harness.agent, session.session_id, "typed_checkpoint", directive.receipt)
  return directive
}