harn-stdlib 0.10.2

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
// std/fs - file-system convenience helpers built on the host fs primitives.
import { pretty, safe_parse } from "std/json"
import { parse_json_typed_report } from "std/schema"

type WriteDataOptions = {pretty?: bool, trailing_newline?: bool, ensure_parent?: bool}

fn __fs_norm(path) -> string {
  return replace(path ?? "", "\\", "/")
}

fn __fs_parent(path) -> string {
  return dirname(path ?? "")
}

fn __fs_with_newline(text, trailing_newline) {
  if !(trailing_newline ?? true) || ends_with(text, "\n") {
    return text
  }
  return text + "\n"
}

/**
 * Create the parent directory for `path` when it is not `.` or empty.
 *
 * @effects: []
 * @errors: []
 */
pub fn ensure_parent_dir(path: string) {
  const parent = __fs_parent(path)
  if parent != "" && parent != "." {
    const status = harness.fs.path_status(parent, "write")
    if !(status?.exists ?? false) {
      harness.fs.mkdir(parent)
    }
  }
}

/**
 * Read and parse a JSON file, returning `fallback` for missing or invalid files.
 *
 * @effects: []
 * @errors: []
 */
pub fn read_json(path: string, fallback = nil) {
  if !harness.fs.exists(path) {
    return fallback
  }
  const parsed = safe_parse(harness.fs.read_text(path))
  if parsed == nil {
    return fallback
  }
  return parsed
}

/**
 * Read and parse a JSON file, returning `{ok, value?, error?}`.
 *
 * @effects: []
 * @errors: []
 */
pub fn read_json_result(path: string) -> dict {
  if !harness.fs.exists(path) {
    return {ok: false, error: "file not found: " + path}
  }
  const parsed = try {
    json_parse(harness.fs.read_text(path))
  }
  if is_ok(parsed) {
    return {ok: true, value: unwrap(parsed)}
  }
  return {ok: false, error: to_string(parsed)}
}

/**
 * Read, parse, and validate a JSON file in one step.
 * Returns `{ok, message, errors, issues, value?, stage, path}`.
 *
 * @effects: []
 * @errors: []
 */
pub fn read_json_typed_report<T>(path: string, schema: Schema<T>, apply_defaults = false) -> dict {
  if !harness.fs.exists(path) {
    const message = "file not found: " + path
    return {ok: false, message: message, errors: [message], issues: [], stage: "read", path: path}
  }
  const raw = try {
    harness.fs.read_text(path)
  }
  if !is_ok(raw) {
    const message = to_string(unwrap_err(raw))
    return {ok: false, message: message, errors: [message], issues: [], stage: "read", path: path}
  }
  return parse_json_typed_report(unwrap(raw), schema, apply_defaults) + {path: path}
}

/**
 * Read, parse, and validate a JSON file, returning `fallback` when missing,
 * malformed, or schema-invalid.
 *
 * @effects: []
 * @errors: []
 */
pub fn read_json_typed<T>(
  path: string,
  schema: Schema<T>,
  fallback: T = nil,
  apply_defaults = false,
) -> T {
  const report = read_json_typed_report(path, schema, apply_defaults)
  if report.ok {
    return report.value
  }
  return fallback
}

/**
 * Write a JSON file with optional pretty formatting and parent-dir creation.
 *
 * @effects: []
 * @errors: []
 */
pub fn write_json(path: string, value, options: WriteDataOptions = {}) {
  const opts = options ?? {}
  if opts.ensure_parent ?? true {
    ensure_parent_dir(path)
  }
  const body = if opts.pretty ?? false {
    pretty(value)
  } else {
    json_stringify(value)
  }
  harness.fs.write_text(path, __fs_with_newline(body, opts.trailing_newline ?? true))
}

/**
 * Read and parse a YAML file, returning `fallback` for missing or invalid files.
 *
 * @effects: []
 * @errors: []
 */
pub fn read_yaml(path: string, fallback = nil) {
  if !harness.fs.exists(path) {
    return fallback
  }
  const parsed = try {
    yaml_parse(harness.fs.read_text(path))
  }
  if is_ok(parsed) {
    return unwrap(parsed)
  }
  return fallback
}

/**
 * Write a YAML file.
 *
 * @effects: []
 * @errors: []
 */
pub fn write_yaml(path: string, value, options: WriteDataOptions = {}) {
  const opts = options ?? {}
  if opts.ensure_parent ?? true {
    ensure_parent_dir(path)
  }
  harness.fs
    .write_text(path, __fs_with_newline(yaml_stringify(value), opts.trailing_newline ?? true))
}

/**
 * Read and parse a TOML file, returning `fallback` for missing or invalid files.
 *
 * @effects: []
 * @errors: []
 */
pub fn read_toml(path: string, fallback = nil) {
  if !harness.fs.exists(path) {
    return fallback
  }
  const parsed = try {
    toml_parse(harness.fs.read_text(path))
  }
  if is_ok(parsed) {
    return unwrap(parsed)
  }
  return fallback
}

/**
 * Write a TOML file.
 *
 * @effects: []
 * @errors: []
 */
pub fn write_toml(path: string, value, options: WriteDataOptions = {}) {
  const opts = options ?? {}
  if opts.ensure_parent ?? true {
    ensure_parent_dir(path)
  }
  harness.fs
    .write_text(path, __fs_with_newline(toml_stringify(value), opts.trailing_newline ?? true))
}

/**
 * Write a list of lines as a text file.
 *
 * @effects: []
 * @errors: []
 */
pub fn write_lines(path: string, lines: list<string>, options: WriteDataOptions = {}) {
  const opts = options ?? {}
  if opts.ensure_parent ?? true {
    ensure_parent_dir(path)
  }
  harness.fs
    .write_text(path, __fs_with_newline(join(lines ?? [], "\n"), opts.trailing_newline ?? true))
}

/**
 * Append one line to a text file.
 *
 * @effects: []
 * @errors: []
 */
pub fn append_line(path: string, line: string) {
  const text = line ?? ""
  harness.fs.append(path, text + "\n")
}

/**
 * Create a file if missing and update it to empty content only on first creation.
 *
 * @effects: []
 * @errors: []
 */
pub fn touch(path: string) {
  if !harness.fs.exists(path) {
    ensure_parent_dir(path)
    harness.fs.write_text(path, "")
  }
}

/**
 * Return files matching `pattern` below `root`, using the host glob implementation.
 *
 * @effects: []
 * @errors: []
 */
pub fn find_files(root: string, pattern: string, options = {}) -> list<string> {
  const matches = harness.fs.glob(pattern, {base: root, long_running: options?.long_running ?? false})
  if options?.relative ?? false {
    return matches.map({ path -> relative_path(root, path) }).to_list()
  }
  return matches
}

/**
 * Return `path` relative to `root` when it is inside that root.
 *
 * @effects: []
 * @errors: []
 */
pub fn relative_path(root: string, path: string) -> string {
  const base_raw = __fs_norm(root)
  const target = __fs_norm(path)
  const base = if ends_with(base_raw, "/") {
    base_raw
  } else {
    base_raw + "/"
  }
  if starts_with(target, base) {
    return substring(target, len(base))
  }
  return target
}

/**
 * Return whether `path` exists and is a regular file.
 *
 * @effects: []
 * @errors: []
 */
pub fn is_file(path: string) -> bool {
  const info = try {
    harness.fs.stat(path)
  }
  if !is_ok(info) {
    return false
  }
  return unwrap(info)?.is_file ?? false
}

/**
 * Return whether `path` exists and is a directory.
 *
 * @effects: []
 * @errors: []
 */
pub fn is_dir(path: string) -> bool {
  const info = try {
    harness.fs.stat(path)
  }
  if !is_ok(info) {
    return false
  }
  return unwrap(info)?.is_dir ?? false
}

/**
 * Return a file size in bytes, or nil when the path cannot be statted.
 *
 * @effects: []
 * @errors: []
 */
pub fn file_size(path: string) {
  const info = try {
    harness.fs.stat(path)
  }
  if is_ok(info) {
    return unwrap(info)?.size
  }
  return nil
}

/**
 * Workspace snapshots — thin pipeline-facing wrappers over the host
 * `hostlib_fs_*` snapshot builtins (crates/harn-hostlib/src/fs_snapshot.rs).
 * They capture the pre-image of explicit paths so a pipeline can checkpoint
 * the workspace and roll it back between independent retry attempts — the
 * substrate for a verify-gated best-of-N agent loop.
 *
 * Snapshots are session-scoped: the session id defaults to the active agent
 * session (`agent_session_current_id()`), so each conversation's snapshots
 * stay isolated and are cleaned up when the host closes the session. Callers
 * outside an agent session must pass an explicit `session_id`. This helper
 * resolves and validates that session id.
 *
 * @effects: [host]
 * @errors: []
 */
fn __fs_snapshot_session(opts) -> string {
  const session = opts?.session_id ?? agent_session_current_id()
  if session == nil || session == "" {
    throw "fs_snapshot: no active agent session; pass an explicit `session_id`"
  }
  return session
}

/**
 * Capture a workspace snapshot of `paths`, returning `{snapshot_id,
 * captured_paths, byte_count}`.
 *
 * `opts.session_id` defaults to the active agent session. `opts.snapshot_id`
 * defaults to a fresh `snapshot-<uuid>` id so independent attempts never
 * collide. `paths` are captured immediately; restoring later reinstates
 * their pre-image (including deleting paths that were absent at capture).
 *
 * @effects: [host, fs]
 * @errors: [backend]
 * @api_stability: experimental
 * @example: let snap = fs_snapshot(["src/lib.rs"]); fs_restore(snap.snapshot_id)
 */
pub fn fs_snapshot(paths: list<string> = [], opts = {}) -> dict {
  const session = __fs_snapshot_session(opts)
  const scope = opts?.snapshot_id ?? ("snapshot-" + uuid_v7())
  return hostlib_fs_snapshot({session_id: session, scope_id: scope, paths: paths ?? [], root: opts?.root})
}

/**
 * Restore a previously-captured snapshot, returning `{snapshot_id,
 * restored_paths, skipped_paths_with_reasons}`. With an empty `paths` every
 * captured path is restored; otherwise only the listed subset.
 *
 * @effects: [host, fs]
 * @errors: [backend]
 * @api_stability: experimental
 * @example: fs_restore(snap.snapshot_id)
 */
pub fn fs_restore(snapshot_id: string, paths: list<string> = [], opts = {}) -> dict {
  const session = __fs_snapshot_session(opts)
  return hostlib_fs_restore({session_id: session, snapshot_id: snapshot_id, paths: paths ?? []})
}

/**
 * List the snapshots registered for the session, oldest first. Each entry is
 * `{snapshot_id, scope_id, taken_at_ms, captured_paths, byte_count}`.
 *
 * @effects: [host]
 * @errors: [backend]
 * @api_stability: experimental
 * @example: for snap in fs_list_snapshots() { log(snap.snapshot_id) }
 */
pub fn fs_list_snapshots(opts = {}) -> list<dict> {
  const session = __fs_snapshot_session(opts)
  const result = hostlib_fs_list_snapshots({session_id: session})
  return result?.snapshots ?? []
}

/**
 * Drop a snapshot's in-memory and on-disk state, returning `{snapshot_id,
 * dropped}`. Idempotent: dropping an unknown id reports `dropped: false`.
 * The best-of-N loop calls this to release each attempt's checkpoint.
 *
 * @effects: [host, fs]
 * @errors: [backend]
 * @api_stability: experimental
 * @example: fs_drop_snapshot(snap.snapshot_id)
 */
pub fn fs_drop_snapshot(snapshot_id: string, opts = {}) -> dict {
  const session = __fs_snapshot_session(opts)
  return hostlib_fs_drop_snapshot({session_id: session, snapshot_id: snapshot_id})
}