harn-stdlib 0.10.181

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
import {
  AgentToolDispatch,
  __dispatch_results_list,
  __tool_result_ok,
} from "std/agent/loop_result_status"
import {
  AgentEditContentState,
  AgentEditStateVisit,
  AgentStallConfig,
  AgentStallState,
} from "std/agent/stall_types"
import { agent_tool_resolve_workspace_write_name } from "std/agent/tool_annotations"
import { agent_tool_result_data } from "std/agent/tool_lifecycle"
import { VerificationGateInput, verification_gate_input } from "std/verification"

/**
 * Action-stream observation for stall diagnostics.
 *
 * This module owns normalization and recurrence for one dispatched tool call.
 * Consecutive streaks remain consecutive; the separate recurrence map counts
 * exact `(tool, arguments, result)` observations across interleaved calls.
 *
 * @effects: []
 * @errors: []
 */
pub fn __agent_tool_call_name(call: dict) -> string {
  return to_string(call?.name ?? call?.tool_name ?? "")
}

pub fn __agent_tool_call_args(call: dict) -> dict {
  const raw = call?.arguments ?? call?.tool_args
  if type_of(raw) == "dict" {
    return raw
  }
  return {}
}

pub fn __agent_tool_call_signature(call: dict) -> string {
  const args_text = json_stringify(__agent_tool_call_args(call))
  return __agent_tool_call_name(call) + "\n" + args_text
}

pub fn __agent_stall_result_ok(result: dict) -> bool {
  if result?.ok != nil {
    return result.ok ? true : false
  }
  if result?.success != nil {
    return result.success ? true : false
  }
  const status = to_string(result?.status ?? "")
  return status == "ok" || status == "success"
}

pub fn __agent_stall_result_name(result: dict) -> string {
  return to_string(result?.tool_name ?? result?.name ?? "")
}

pub fn __agent_stall_is_context_window_error(text: string) -> bool {
  const lowered = lowercase(text)
  return contains(lowered, "context window")
    || contains(lowered, "context length")
    || contains(lowered, "context_length")
    || contains(lowered, "maximum context")
    || contains(lowered, "token limit")
    || contains(lowered, "too many tokens")
    || contains(lowered, "context_length_exceeded")
    || contains(lowered, "max_tokens")
}

pub fn __agent_stall_delta_signature(current: dict) -> string {
  const signatures = current?.signatures ?? []
  const count = to_int(current?.count) ?? len(signatures)
  return "err:" + sha256(json_stringify({signatures: signatures, count: count}))
}

pub fn __agent_stall_result_error_signature(delta: dict, result: dict) -> string {
  if len(delta.current.signatures) > 0 {
    return __agent_stall_delta_signature(delta.current)
  }
  const fallback = to_string(result?.error ?? result?.message ?? result?.result ?? "")
  return "err:" + sha256(fallback)
}

pub fn __agent_stall_current_hashes(result: dict) -> dict? {
  if type_of(result) != "dict" {
    return nil
  }
  return result?.current_hashes
    ?? result?.currentHashes
    ?? result?.file_hashes
    ?? result?.fileHashes
}

pub fn __agent_stall_gate_input(
  agent: HarnessAgent,
  previous: any,
  result: dict,
) -> VerificationGateInput {
  return verification_gate_input(agent, previous, result, __agent_stall_current_hashes(result))
}

/**
 * Normalize a dispatch result into an outcome kind and stable signature.
 *
 * @effects: []
 * @errors: []
 */
pub fn __agent_stall_result_outcome(agent: HarnessAgent, result: dict) -> dict {
  if __agent_stall_result_ok(result) {
    const payload = json_stringify(result?.result ?? result?.output ?? result?.content)
    return {kind: "ok", signature: "ok:" + sha256(payload)}
  }
  const error_text = to_string(result?.error ?? result?.message ?? result?.result ?? "")
  if __agent_stall_is_context_window_error(error_text) {
    return {kind: "context_window", signature: "ctx"}
  }
  const gate = __agent_stall_gate_input(agent, nil, result)
  if !gate.feedsGates {
    return {kind: "advisory", signature: "advisory:" + sha256(json_stringify(gate.current))}
  }
  return {kind: "error", signature: __agent_stall_result_error_signature(gate.delta, result)}
}

/**
 * Find the dispatch result for the action being folded.
 *
 * @effects: []
 * @errors: []
 */
pub fn __agent_stall_outcome_for(
  agent: HarnessAgent,
  prev_dispatch: AgentToolDispatch,
  tool_name: string,
) -> dict? {
  if prev_dispatch == nil {
    return nil
  }
  const results = __dispatch_results_list(prev_dispatch)
  for result in results {
    if __agent_stall_result_name(result) == tool_name {
      return __agent_stall_result_outcome(agent, result)
    }
  }
  return nil
}

/**
 * Fold one action signature through the strict A/B ping-pong detector.
 *
 * @effects: []
 * @errors: []
 */
pub fn __agent_stall_update_ping_pong(
  state: AgentStallState,
  signature: string,
) -> AgentStallState {
  const a = state.ping_pong_a
  const b = state.ping_pong_b
  if a == "" {
    return state + {ping_pong_a: signature, ping_pong_b: "", ping_pong_alternations: 0}
  }
  if b == "" {
    if a == signature {
      return state + {ping_pong_alternations: 0}
    }
    return state + {ping_pong_b: signature, ping_pong_alternations: 1}
  }
  const expected_next = if state.ping_pong_alternations % 2 == 1 {
    a
  } else {
    b
  }
  if expected_next == signature {
    return state + {ping_pong_alternations: state.ping_pong_alternations + 1}
  }
  if a == signature || b == signature {
    return state + {ping_pong_a: signature, ping_pong_b: "", ping_pong_alternations: 0}
  }
  return state + {ping_pong_a: signature, ping_pong_b: "", ping_pong_alternations: 0}
}

/**
 * Fold one exact successful observation into its session recurrence count.
 *
 * @effects: []
 * @errors: []
 */
pub fn __agent_stall_observation_recurrence(
  state: AgentStallState,
  action_signature: string,
  observation_signature: string,
  outcome_present: bool,
  outcome_kind: string,
) -> dict {
  const counts = state.observation_recurrence_counts ?? {}
  if !outcome_present || outcome_kind != "ok" {
    return {counts: counts, count: 0}
  }
  const key = sha256(action_signature + "\n" + observation_signature)
  const count = (to_int(counts[key] ?? 0) ?? 0) + 1
  return {counts: counts + {[key]: count}, count: count}
}

fn __agent_stall_call_id(call: dict) -> string {
  return to_string(call?.id ?? call?.tool_call_id ?? call?.call_id ?? "")
}

/**
 * Join one originating call to its completed result. Stable call ids own the
 * relation; result order is the compatibility fallback for text-mode calls
 * whose provider did not supply an id.
 *
 * @effects: []
 * @errors: []
 */
pub fn __agent_stall_completed_result(
  dispatch: AgentToolDispatch,
  call: dict,
  index: int,
) -> dict? {
  const results = __dispatch_results_list(dispatch)
  const call_id = __agent_stall_call_id(call)
  if call_id != "" {
    for result in results {
      if to_string(result?.tool_call_id ?? result?.call_id ?? result?.id ?? "") == call_id {
        return result
      }
    }
    return nil
  }
  if index >= 0 && index < len(results) && type_of(results[index]) == "dict" {
    return results[index]
  }
  return nil
}

// A fixed session-checkpoint ceiling, shared across paths, retains only opaque
// keys and counters. Eviction forgets the least recently visited content state.
pub const STALL_EDIT_STATE_VISIT_LIMIT = 256

pub type AgentEditStateObservation = {
  state: AgentStallState,
  path: string,
  count: int,
  iteration_distance: int?,
}

/**
 * Observe a completed agent edit from producer facts only. Never retain a
 * pre-image, rendered output, file content, or ambient filesystem observation.
 * Missing hashes are unavailable evidence, not one shared empty content state.
 *
 * @effects: []
 * @errors: []
 */
pub fn __agent_stall_edit_state(
  state: AgentStallState,
  session_id: string,
  tool_name: string,
  result: dict?,
  iteration: int,
  registry: any,
  policy: any,
) -> AgentEditStateObservation {
  const absent = {state: state, path: "", count: 0, iteration_distance: nil}
  if tool_name == ""
    || result == nil
    || !__tool_result_ok(result)
    || result?.status == "running"
    || (result?.dispatch_receipt?.disposition ?? "executed") != "executed"
    || agent_tool_resolve_workspace_write_name(registry, policy, tool_name) == "" {
    return absent
  }
  const data = agent_tool_result_data(result)
  if type_of(data) != "dict" {
    return absent
  }
  const report = match schema_parse(
    {path: data?.path, after_sha256: data?.after_sha256, mutation_status: data?.mutation_status},
    schema_of(AgentEditContentState),
  ) {
    Ok(value) -> { value }
    Err(_) -> { return absent }
  }
  const path = report.path
  const hash = report.after_sha256
  if trim(path) == "" || trim(hash) == "" {
    return absent
  }
  const key = sha256(json_stringify([session_id, path, hash]))
  let retained: list<AgentEditStateVisit> = []
  let count = 1
  let distance = nil
  for visit in state.edit_state_visits {
    if visit.key == key {
      count = visit.count + 1
      // A resumed loop starts its iteration counter again. The checkpoint
      // owner invalidates old coordinates while preserving content identity.
      if visit.iteration != nil && iteration >= visit.iteration {
        distance = iteration - visit.iteration
      }
    } else {
      retained = retained + [visit]
    }
  }
  retained = retained + [{key: key, iteration: iteration, count: count}]
  if len(retained) > STALL_EDIT_STATE_VISIT_LIMIT {
    retained = retained[1:]
  }
  return {
    state: state + {edit_state_visits: retained},
    path: path,
    count: count,
    iteration_distance: distance,
  }
}

/**
 * Fold one proposed tool call against the prior dispatch for consecutive
 * action diagnostics.
 *
 * Cumulative recurrence is deliberately absent here: a new call cannot be
 * paired to its own result before dispatch. Completed-dispatch recurrence is
 * owned by `agent_stall_observe_completed_dispatch`.
 *
 * @effects: []
 * @errors: []
 */
pub fn __agent_stall_process_call(
  agent: HarnessAgent,
  state: AgentStallState,
  config: AgentStallConfig,
  call: dict,
  tool_name: string,
  prev_dispatch: AgentToolDispatch,
  turn_made_edit: bool,
) -> dict {
  const signature = __agent_tool_call_signature(call)
  const same_action = signature == state.last_signature
  const outcome = __agent_stall_outcome_for(agent, prev_dispatch, tool_name)
  const obs_signature = if outcome != nil {
    outcome.signature
  } else {
    "sig:" + sha256(signature)
  }
  const outcome_kind = if outcome != nil {
    outcome.kind
  } else {
    "ok"
  }
  let next_state = __agent_stall_update_ping_pong(state, signature)
  const streak = if same_action {
    next_state.streak + 1
  } else {
    1
  }
  const repeated = if streak > 1 {
    next_state.repeated_tool_calls + 1
  } else {
    next_state.repeated_tool_calls
  }
  const both_known = outcome != nil && next_state.last_outcome_kind != ""
  const observation_changed = both_known && obs_signature != next_state.last_observation_signature
  const new_same_observation_streak = if !same_action || outcome_kind != "ok" {
    if outcome_kind == "ok" {
      1
    } else {
      0
    }
  } else if observation_changed {
    1
  } else {
    next_state.same_observation_streak + 1
  }
  const new_same_success_streak = if !same_action || outcome_kind != "ok" || turn_made_edit {
    if outcome_kind == "ok" && !turn_made_edit {
      1
    } else {
      0
    }
  } else if !observation_changed {
    1
  } else {
    next_state.same_success_streak + 1
  }
  const new_same_error_streak = if !same_action || outcome_kind != "error" {
    if outcome_kind == "error" {
      1
    } else {
      0
    }
  } else if observation_changed {
    1
  } else {
    next_state.same_error_streak + 1
  }
  const new_context_streak = if outcome_kind == "context_window" {
    next_state.context_window_error_streak + 1
  } else {
    0
  }
  next_state = next_state
    + {
      last_signature: signature,
      streak: streak,
      repeated_tool_calls: repeated,
      last_observation_signature: obs_signature,
      last_outcome_kind: if outcome != nil {
        outcome_kind
      } else {
        ""
      },
      same_observation_streak: new_same_observation_streak,
      same_success_streak: new_same_success_streak,
      same_error_streak: new_same_error_streak,
      context_window_error_streak: new_context_streak,
    }
  const trip = __agent_stall_classify_trip(
    config,
    {
      context_streak: new_context_streak,
      same_error_streak: new_same_error_streak,
      same_observation_streak: new_same_observation_streak,
      same_success_streak: new_same_success_streak,
      outcome_kind: outcome_kind,
      ping_pong_cycles: next_state.ping_pong_alternations / 2,
      outcome_present: outcome != nil,
      streak: streak,
    },
  )
  return {state: next_state, trip: trip}
}

/**
 * Decide which stall condition owns this processed call.
 *
 * @effects: []
 * @errors: []
 */
pub fn __agent_stall_classify_trip(config: AgentStallConfig, s: dict) -> dict? {
  const repair_owns_repeat = config.repair_aware
  if s.context_streak >= config.repeat_context_window_error {
    return {
      pattern: "repeated_context_window_error",
      count: s.context_streak,
      threshold: config.repeat_context_window_error,
    }
  }
  if !repair_owns_repeat && s.same_error_streak >= config.repeat_same_error {
    return {
      pattern: "repeated_error",
      count: s.same_error_streak,
      threshold: config.repeat_same_error,
    }
  }
  if !repair_owns_repeat
    && s.outcome_kind == "ok"
    && s.same_observation_streak >= config.repeat_same_observation {
    return {
      pattern: "repeated_same_observation",
      count: s.same_observation_streak,
      threshold: config.repeat_same_observation,
    }
  }
  if s.outcome_kind == "ok" && s.same_success_streak >= config.repeat_success {
    return {
      pattern: "repeated_success",
      count: s.same_success_streak,
      threshold: config.repeat_success,
    }
  }
  if s.ping_pong_cycles >= config.ping_pong_cycles {
    return {pattern: "ping_pong", count: s.ping_pong_cycles, threshold: config.ping_pong_cycles}
  }
  if !s.outcome_present && s.streak >= config.threshold {
    return {pattern: "repeated_same_signature", count: s.streak, threshold: config.threshold}
  }
  return nil
}