harn-stdlib 0.10.194

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
import {
  PATTERN_NAMESPACE,
  PATTERN_SCHEMA,
  pl_short_hash,
  pl_slugify,
  pl_text,
} from "std/agent/pattern_knowledge_values"
// Shared persistence boundary for cross-session pattern learning. This module
// owns state paths, memory projections, and observation normalization; callers
// retain policy such as curation thresholds and review decisions.
import { memory_forget, memory_store, memory_summarize } from "std/memory"
import { redact } from "std/oauth/redaction"
import { runtime_state_paths_under } from "std/runtime"

// These filenames belong only to the legacy session-store import path used by
// `pattern_learning_ensure_migrated`. Current pattern memory has Harn-owned
// paths. Keep this compatibility reader until that migration contract is
// deliberately removed; new hosts must not write these names.
pub fn pl_project_root(fs: HarnessFs, options: any = nil) -> string {
  return pl_text(options?.project_root ?? fs.project_root() ?? fs.cwd() ?? ".")
}

pub fn pl_state_root(fs: HarnessFs, options: any = nil) -> string {
  const explicit_project_root = pl_text(options?.project_root)
  if explicit_project_root != "" {
    return runtime_state_paths_under(explicit_project_root).state_root
  }
  return fs.runtime_paths().state_root
}

pub fn pl_memory_root(fs: HarnessFs, options: any = nil) -> string {
  const explicit = pl_text(options?.memory_root ?? options?.root)
  if explicit != "" {
    return explicit
  }
  return path_join(pl_state_root(fs, options), "memory")
}

pub fn pl_namespace(options: any = nil) -> string {
  const explicit = pl_text(options?.namespace)
  return explicit == "" ? PATTERN_NAMESPACE : explicit
}

pub fn pl_memory_options(fs: HarnessFs, options: any = nil) -> dict {
  return (options ?? {}) + {root: pl_memory_root(fs, options)}
}

pub fn pl_now(clock: HarnessClock, options: any = nil) -> string {
  const explicit = pl_text(options?.now)
  return explicit == "" ? clock.date_iso() : explicit
}

pub fn pl_observation_file(fs: HarnessFs, options: any = nil) -> string {
  return path_join(
    pl_state_root(fs, options),
    "session-store",
    "burin.agent_context.pattern_learning.observations.jsonl",
  )
}

pub fn pl_pending_file(fs: HarnessFs, options: any = nil) -> string {
  return path_join(
    pl_state_root(fs, options),
    "session-store",
    "burin.agent_context.pattern_learning.pending.jsonl",
  )
}

pub fn pl_state_file(fs: HarnessFs, options: any = nil) -> string {
  return path_join(
    pl_state_root(fs, options),
    "session-store",
    "burin.agent_context.pattern_learning.state.jsonl",
  )
}

pub fn pl_migration_marker(fs: HarnessFs, options: any = nil) -> string {
  return path_join(
    pl_memory_root(fs, options),
    pl_namespace(options),
    ".burin-session-store-migrated-v1.json",
  )
}

pub fn pl_read_jsonl_payloads(fs: HarnessFs, path: string) -> list {
  if !path || !fs.exists(path) {
    return []
  }
  let out = []
  for raw_line in (fs.read_text(path) ?? "").split("\n") {
    const line = pl_text(raw_line)
    if line == "" {
      continue
    }
    const parsed = try {
      json_parse(line)
    }
    if is_ok(parsed) {
      out = out + [unwrap(parsed)?.payload ?? {}]
    }
  }
  return out
}

pub fn pl_project_collection(mutations: list) -> list {
  let records = {}
  let order = []
  for mutation in mutations ?? [] {
    const op = pl_text(mutation?.operation)
    if op == "upsert" {
      const record = mutation?.record ?? {}
      const id = pl_text(record?.id)
      if id == "" {
        continue
      }
      if records[id] == nil {
        order = order + [id]
      }
      records = records + {[id]: record}
    } else if op == "delete" {
      const id = pl_text(mutation?.id)
      records = records + {[id]: nil}
      order = order.filter({ existing -> existing != id })
    } else if op == "replace" {
      records = {}
      order = []
      for record in mutation?.records ?? [] {
        const id = pl_text(record?.id)
        if id == "" {
          continue
        }
        if records[id] == nil {
          order = order + [id]
        }
        records = records + {[id]: record}
      }
    } else if op == "clear" {
      records = {}
      order = []
    }
  }
  return order.map({ id -> records[id] }).filter({ record -> record != nil }).to_list()
}

pub fn pl_project_value(mutations: list, fallback: dict) -> dict {
  let value = fallback
  for mutation in mutations ?? [] {
    const op = pl_text(mutation?.operation)
    if op == "replace" && mutation?.value != nil {
      value = mutation.value
    } else if op == "clear" {
      value = fallback
    }
  }
  return value
}

pub fn pl_tags(kind: string, extra: list? = nil) -> list {
  let tags = ["pattern_learning", "pattern_learning:" + kind, "schema:" + PATTERN_SCHEMA]
  for raw in extra ?? [] {
    const tag = pl_text(raw)
    if tag != "" && !tags.contains(tag) {
      tags = tags + [tag]
    }
  }
  return tags
}

pub fn pl_store_record(
  harness: Harness,
  kind: string,
  key: string,
  value: dict,
  options: any = nil,
) -> dict {
  const opts = pl_memory_options(harness.fs, options)
  const now = pl_now(harness.clock, options)
  const id = pl_text(options?.id)
  return memory_store(
    harness.memory,
    pl_namespace(options),
    key,
    value + {schema: PATTERN_SCHEMA, record_kind: kind},
    pl_tags(kind, options?.tags),
    opts
      + {
        id: id == "" ? key.replace(":", "_") : id,
        now: now,
        provenance: options?.provenance ?? {source: "harn.pattern_learning"},
      },
  )
}

pub fn pl_memory_records(
  fs: HarnessFs,
  memory: HarnessMemory,
  kind: string = "",
  options: any = nil,
) -> list {
  const window = if kind == "" {
    {limit: options?.record_limit ?? 2000}
  } else {
    {limit: options?.record_limit ?? 2000, tag: "pattern_learning:" + kind}
  }
  return memory_summarize(memory, pl_namespace(options), window, pl_memory_options(fs, options))
    ?.records
    ?? []
}

pub fn pl_record_values(
  fs: HarnessFs,
  memory: HarnessMemory,
  kind: string,
  options: any = nil,
) -> list {
  return pl_memory_records(fs, memory, kind, options).map({ record -> record?.value ?? {} }).filter(
    { value -> value?.schema == PATTERN_SCHEMA && (value?.record_kind ?? value?.kind) == kind },
  )
    .to_list()
}

pub fn pl_replace_state(harness: Harness, state: dict, options: any = nil) -> dict {
  memory_forget(
    harness.memory,
    pl_namespace(options),
    {key: "state"},
    pl_memory_options(harness.fs, options),
  )
  return pl_store_record(
    harness,
    "state",
    "state",
    {
      enabled: state?.enabled ?? true,
      suppressed_until: state?.suppressed_until ?? state?.suppressedUntil ?? {},
      updated_at: pl_now(harness.clock, options),
    },
    options + {id: pl_unique_record_id(harness.clock, harness.random, "state", options)},
  )?.value
}

pub fn pl_unique_record_id(
  clock: HarnessClock,
  random: HarnessRandom,
  prefix: string,
  options: any = nil,
) -> string {
  return prefix + "_" + pl_short_hash(pl_now(clock, options) + ":" + random.uuid())
}

pub fn pl_sanitize_tool_sequence(sequence: list) -> list {
  let out = []
  for raw in sequence ?? [] {
    const clean = pl_slugify(raw)
    if clean != "" && clean != "load-skill" {
      out = out + [clean]
    }
  }
  return out
}

/**
 * A secret's whole shell word, including adjacent quoted, bare and escaped
 * segments. Unterminated quotes run to the end. An unescaped dollar or backtick
 * outside single quotes may introduce nested shell syntax: suppress the rest
 * instead of guessing where that value ends.
 */
const PL_SECRET_VALUE: string =
  r"(?:\x22(?:[^\x22\\$`]|\\(?:[\s\S]|$))*(?:\x22|$|[$`][\s\S]*)|'[^']*(?:'|$)|\\(?:[\s\S]|$)|[^\s\x22'\\$`]|[$`][\s\S]*)+"

pub fn pl_redact_sensitive(text: string) -> string {
  const no_private = regex_replace(
    r"-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----",
    "<redacted-private-key>",
    text ?? "",
  )
    ?? (text ?? "")
  return regex_replace(
    r"(?i)\b(api[_-]?key|token|secret|password|credential)\b\s*[:=]\s*" + PL_SECRET_VALUE,
    "$1=<redacted>",
    no_private,
  )
    ?? no_private
}

const COMMAND_LEDGER_LIMIT: int = 16

const COMMAND_TEXT_LIMIT: int = 240

/**
 * Scrub a captured command line. Besides the prompt rules, environment
 * assignments whose name looks like a credential (`OPENAI_API_KEY=...`,
 * `DB_PASSWORD=...`) lose their whole value, quoted or not (a double-quoted
 * value may contain escaped quotes, and an unterminated quote runs to the end),
 * and the token-pattern policy runs last. Redact before clipping: a token cut
 * in half no longer matches its pattern.
 *
 * @effects: []
 * @errors: []
 * @api_stability: internal
 */
pub fn pl_redact_command(text: string) -> string {
  const assignments = regex_replace(
    r"(?i)\b([A-Za-z_][A-Za-z0-9_]*(?:key|token|secret|password|passwd|credential|auth)[A-Za-z0-9_]*)="
      + PL_SECRET_VALUE,
    "$1=<redacted>",
    text ?? "",
  )
    ?? (text ?? "")
  return to_string(redact(pl_redact_sensitive(assignments)))
}

/**
 * Normalize a run's command ledger at the observation boundary: at most the
 * last COMMAND_LEDGER_LIMIT entries, each `{tool, command, exit_code, ok}` with
 * a redacted, length-bounded command. Entries without a command are dropped.
 *
 * @effects: []
 * @errors: []
 * @api_stability: internal
 */
pub fn pl_sanitize_command_ledger(ledger: list) -> list {
  let out = []
  for raw in ledger ?? [] {
    const command = pl_redact_command(to_string(raw?.command ?? ""))
    if command == "" {
      continue
    }
    const exit_code = raw?.exit_code
    const code = type_of(exit_code) == "int" ? exit_code : nil
    out = out
      + [
        {
          tool: pl_slugify(raw?.tool ?? ""),
          command: command[0:min(len(command), COMMAND_TEXT_LIMIT)],
          exit_code: code,
          ok: code == nil ? (raw?.ok ?? false) == true : code == 0,
        },
      ]
  }
  const start = max(0, len(out) - COMMAND_LEDGER_LIMIT)
  return out[start:len(out)]
}

/**
 * The run's assessed goal outcome, reduced to its kind and reason. Absent when
 * nothing assessed the run, so an unassessed session never reads as a success.
 */
fn pl_goal_outcome(outcome: any) -> dict? {
  const kind = pl_text(outcome?.kind)
  if kind == "" {
    return nil
  }
  return {kind: kind, reason: pl_text(outcome?.reason)}
}

pub fn pl_observation_from_input(
  clock: HarnessClock,
  random: HarnessRandom,
  input: dict,
  options: any = nil,
) -> dict {
  const prompt = pl_redact_sensitive(pl_text(input?.prompt ?? input?.message))
  if prompt == "" {
    throw "HARN-PATTERN-001: prompt is required"
  }
  const id = pl_text(input?.id)
  return {
    id: id == "" ? random.uuid() : id,
    source_id: pl_text(input?.source_id ?? input?.sourceId),
    session_id: pl_text(input?.session_id ?? input?.sessionID),
    run_id: pl_text(input?.run_id ?? input?.runId),
    evidence_kind: pl_text(input?.evidence_kind ?? input?.evidenceKind),
    prompt: prompt,
    tool_sequence: pl_sanitize_tool_sequence(input?.tool_sequence ?? input?.toolSequence ?? []),
    command_ledger: pl_sanitize_command_ledger(input?.command_ledger ?? []),
    outcome: pl_goal_outcome(input?.outcome),
    observed_at: pl_text(input?.observed_at ?? input?.observedAt ?? pl_now(clock, options)),
  }
}

pub fn pl_observation_from_legacy(
  clock: HarnessClock,
  random: HarnessRandom,
  record: dict,
  options: any = nil,
) -> dict {
  return pl_observation_from_input(
    clock,
    random,
    {
      id: record?.id,
      session_id: record?.sessionID ?? record?.session_id,
      prompt: record?.prompt,
      tool_sequence: record?.toolSequence ?? record?.tool_sequence ?? [],
      observed_at: record?.observedAt ?? record?.observed_at ?? pl_now(clock, options),
    },
    options,
  )
}

pub fn pl_store_observation(harness: Harness, record: dict, options: any = nil) -> dict {
  return pl_store_record(
    harness,
    "observation",
    "observation:" + record.id,
    record,
    options + {id: record.id},
  )?.value
}