harn-stdlib 0.10.0

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
// std/prompt_library — reusable prompt fragments and hotspot consolidation.
//
// Import with: import "std/prompt_library"
import { filter_nil } from "std/collections"
import { euclidean_distance, kmeans } from "std/math"

fn __empty_library() {
  return {_type: "prompt_library", fragments: []}
}

fn __require_library(library, name = "prompt_library") {
  require library != nil && library._type == "prompt_library", name + ": expected a prompt library"
  return library.fragments ?? []
}

fn __estimate_tokens_text(text) {
  return to_int(ceil(len(text) * 1.0 / 4.0))
}

fn __fragment_id_from_path(path) {
  const base = basename(path)
  if ends_with(base, ".harn.prompt") {
    return substring(base, 0, len(base) - len(".harn.prompt"))
  }
  const ext = extname(base)
  if ext != "" {
    return substring(base, 0, len(base) - len(ext))
  }
  return base
}

fn __normalize_words(text) {
  const normalized = regex_replace("[^A-Za-z0-9_./:-]+", " ", lowercase(text))
  return split(trim(normalized), " ").filter({ word -> word != "" })
}

fn __token_prefix(text, max_tokens) {
  const words = __normalize_words(text)
  if max_tokens == nil || max_tokens <= 0 || len(words) <= max_tokens {
    return join(words, " ")
  }
  return join(words[:max_tokens], " ")
}

fn __fragment_from_config(harness: Harness, config, base_dir = nil) {
  let body = config?.body ?? config?.prompt ?? config?.text
  let path = config?.path
  if body == nil && path != nil {
    const full_path = if base_dir != nil && !starts_with(path, "/") {
      path_join(base_dir, path)
    } else {
      path
    }
    body = harness.fs.read_text(full_path)
    path = full_path
  }
  require body != nil, "prompt_fragment: fragment requires body, prompt, text, or path"
  const id = config?.id ?? if path != nil {
    __fragment_id_from_path(path)
  } else {
    nil
  }
  require id != nil && id != "", "prompt_fragment: fragment id must be a non-empty string"
  return prompt_fragment(id, body, config + {path: path})
}

fn __front_matter_fragment(harness: Harness, path, text) {
  if !starts_with(text, "---\n") {
    return prompt_fragment(__fragment_id_from_path(path), text, {path: path, source_path: path})
  }
  const rest = substring(text, 4)
  const marker = rest.index_of("\n---\n")
  if marker < 0 {
    return prompt_fragment(__fragment_id_from_path(path), text, {path: path, source_path: path})
  }
  const meta_text = substring(rest, 0, marker)
  const body = substring(rest, marker + len("\n---\n"))
  const meta = toml_parse(meta_text)
  return __fragment_from_config(harness, meta + {body: body, path: path, source_path: path}, dirname(path))
}

fn __load_one(harness: Harness, path) {
  const text = harness.fs.read_text(path)
  const parsed = try {
    toml_parse(text)
  }
  if is_ok(parsed) {
    const data = unwrap(parsed)
    if data?.prompt_fragments != nil {
      const base_dir = dirname(path)
      let library = __empty_library()
      for fragment_config in data.prompt_fragments {
        library = prompt_library_define(library, __fragment_from_config(harness, fragment_config, base_dir))
      }
      return library
    }
  }
  return prompt_library([__front_matter_fragment(harness, path, text)])
}

fn __render_fragment(fragment, bindings = nil) {
  const body = fragment?.body ?? fragment?.prompt ?? fragment?.text
  require body != nil, "prompt_library_inject: fragment has no body"
  const source_path = fragment?.source_path ?? fragment?.path
  if source_path != nil && starts_with(source_path, "std/") {
    return render_prompt(source_path, bindings ?? {})
  }
  return render_string(body, bindings ?? {})
}

fn __matches_filters(fragment, filters) {
  if filters == nil {
    return true
  }
  if filters?.id != nil && fragment.id != filters.id {
    return false
  }
  if filters?.tenant_id != nil && fragment?.tenant_id != filters.tenant_id {
    return false
  }
  if filters?.provenance != nil && fragment?.provenance != filters.provenance {
    return false
  }
  if filters?.status != nil && fragment?.status != filters.status {
    return false
  }
  if filters?.tag != nil && !(fragment?.tags ?? []).contains(filters.tag) {
    return false
  }
  if filters?.tags != nil {
    for tag in filters.tags {
      if !(fragment?.tags ?? []).contains(tag) {
        return false
      }
    }
  }
  return true
}

fn __score_fragment(fragment, ctx) {
  let score = 0
  const tags = fragment?.tags ?? []
  for tag in ctx?.tags ?? [] {
    if tags.contains(tag) {
      score = score + 10
    }
  }
  const query = trim(lowercase(ctx?.query ?? ctx?.text ?? ""))
  if query != "" {
    const fragment_id = fragment?.id ?? ""
    const fragment_title = fragment?.title ?? ""
    const fragment_body = fragment?.body ?? ""
    const haystack = lowercase(fragment_id + " " + fragment_title + " " + fragment_body)
    for word in __normalize_words(query) {
      if contains(haystack, word) {
        score = score + 1
      }
    }
  }
  return score
}

fn __top_scored(scored, limit) {
  let remaining = scored
  let out = []
  while len(remaining) > 0 && (limit == nil || len(out) < limit) {
    let best_index = 0
    let best_score = remaining[0].score
    let idx = 1
    while idx < len(remaining) {
      if remaining[idx].score > best_score {
        best_index = idx
        best_score = remaining[idx].score
      }
      idx = idx + 1
    }
    out = out.push(remaining[best_index].fragment)
    remaining = remaining[:best_index] + remaining[best_index + 1:]
  }
  return out
}

fn __conversation_text(conversation) {
  if type_of(conversation) == "string" {
    return conversation
  }
  return conversation?.prefix
    ?? conversation?.text
    ?? conversation?.prompt
    ?? conversation?.system
    ?? conversation?.content
    ?? json_stringify(conversation)
}

fn __conversation_id(conversation, index) {
  if type_of(conversation) == "dict" && conversation?.id != nil {
    return conversation.id
  }
  return "conversation-" + to_string(index)
}

fn __conversation_embedding(conversation, text) {
  if type_of(conversation) == "dict" && conversation?.embedding != nil {
    return conversation.embedding
  }
  const words = __normalize_words(text)
  const vocab = [
    "system",
    "developer",
    "tool",
    "agent",
    "context",
    "repo",
    "workspace",
    "rust",
    "test",
    "error",
    "fix",
    "issue",
    "github",
    "docs",
    "api",
    "prompt",
  ]
  let vector = []
  for term in vocab {
    let count = 0
    for word in words {
      if word == term {
        count = count + 1
      }
    }
    vector = vector.push(count * 1.0)
  }
  vector = vector.push(len(words) * 1.0)
  return vector
}

fn __avg_distance(point, points) {
  if len(points) == 0 {
    return 0.0
  }
  let total = 0.0
  for other in points {
    total = total + euclidean_distance(point, other)
  }
  return total / (len(points) * 1.0)
}

fn __silhouette(points, assignments, k) {
  if k <= 1 || len(points) <= 1 {
    return 0.0
  }
  let total = 0.0
  let idx = 0
  while idx < len(points) {
    const cluster = assignments[idx]
    let same = []
    let other_clusters = []
    let c = 0
    while c < k {
      other_clusters = other_clusters.push([])
      c = c + 1
    }
    let j = 0
    while j < len(points) {
      if j != idx {
        if assignments[j] == cluster {
          same = same.push(points[j])
        } else {
          const other = assignments[j]
          other_clusters[other] = other_clusters[other].push(points[j])
        }
      }
      j = j + 1
    }
    const a = __avg_distance(points[idx], same)
    let b = nil
    for group in other_clusters {
      if len(group) > 0 {
        const d = __avg_distance(points[idx], group)
        if b == nil || d < b {
          b = d
        }
      }
    }
    if b != nil {
      const denom = if a > b {
        a
      } else {
        b
      }
      if denom > 0 {
        total = total + (b - a) / denom
      }
    }
    idx = idx + 1
  }
  return total / (len(points) * 1.0)
}

fn __choose_kmeans(points, options) {
  const n = len(points)
  const requested = options?.k
  if requested != nil {
    const result = kmeans(points, requested, {max_iterations: options?.max_iterations ?? 100})
    return {k: requested, result: result, silhouette: __silhouette(points, result.assignments, requested)}
  }
  if n < 4 {
    const result = kmeans(points, 1, {max_iterations: options?.max_iterations ?? 100})
    return {k: 1, result: result, silhouette: 0.0}
  }
  const max_k = if options?.max_k != nil && options.max_k < n {
    options.max_k
  } else {
    n
  }
  let k = 2
  let best = nil
  while k <= max_k && k <= 6 {
    const result = kmeans(points, k, {max_iterations: options?.max_iterations ?? 100})
    const score = __silhouette(points, result.assignments, k)
    if best == nil || score > best.silhouette {
      best = {k: k, result: result, silhouette: score}
    }
    k = k + 1
  }
  return best
}

fn __prefix_count(snippets, prefix) {
  let count = 0
  for snippet in snippets {
    if starts_with(snippet, prefix) {
      count = count + 1
    }
  }
  return count
}

fn __shared_prefix(snippets, min_fraction, min_tokens) {
  let best = {text: "", tokens: 0, support: 0}
  for snippet in snippets {
    const words = split(snippet, " ").filter({ word -> word != "" })
    let n = len(words)
    while n >= min_tokens {
      const prefix = join(words[:n], " ")
      const support = __prefix_count(snippets, prefix)
      if support / (len(snippets) * 1.0) >= min_fraction && n > best.tokens {
        best = {text: prefix, tokens: n, support: support}
        break
      }
      n = n - 1
    }
  }
  return best
}

/**
 * Create a prompt library from a fragment list.
 *
 * @effects: []
 * @errors: []
 */
pub fn prompt_library(fragments = nil) {
  let library = __empty_library()
  for fragment in fragments ?? [] {
    library = prompt_library_define(library, fragment)
  }
  return library
}

/**
 * Normalize one prompt fragment.
 *
 * @effects: []
 * @errors: []
 */
pub fn prompt_fragment(id, body, config = nil) {
  require id != nil && id != "", "prompt_fragment: id must be a non-empty string"
  require body != nil, "prompt_fragment: body must not be nil"
  const {provenance = "manual", status = if provenance == "kmeans" {
  "pending_review"
} else {
  "accepted"
}} = config ?? {}
  return filter_nil(
    {
      id: id,
      title: config?.title ?? id,
      tags: config?.tags ?? [],
      token_budget: config?.token_budget ?? __estimate_tokens_text(body),
      cache_ttl: config?.cache_ttl ?? "5m",
      cache_control: config?.cache_control ?? {type: "ephemeral"},
      body: body,
      path: config?.path,
      source_path: config?.source_path,
      provenance: provenance,
      status: status,
      tenant_id: config?.tenant_id,
      score: config?.score,
      members: config?.members,
      support: config?.support,
      tokens_saved: config?.tokens_saved,
      monthly_savings_usd: config?.monthly_savings_usd,
    },
  )
}

/**
 * Add or replace a fragment by id.
 *
 * @effects: []
 * @errors: []
 */
pub fn prompt_library_define(library, fragment) {
  const fragments = __require_library(library, "prompt_library_define")
  require fragment?.id != nil && fragment.id != "", "prompt_library_define: fragment requires id"
  let out = []
  let replaced = false
  for existing in fragments {
    if existing.id == fragment.id {
      out = out.push(fragment)
      replaced = true
    } else {
      out = out.push(existing)
    }
  }
  if !replaced {
    out = out.push(fragment)
  }
  return {_type: "prompt_library", fragments: out}
}

/**
 * Load fragments from a TOML catalog or `.harn.prompt` fragment file.
 *
 * @effects: []
 * @errors: []
 */
pub fn prompt_library_load(path_or_paths) {
  if type_of(path_or_paths) == "list" {
    let library = __empty_library()
    for path in path_or_paths {
      const loaded = prompt_library_load(path)
      for fragment in loaded.fragments {
        library = prompt_library_define(library, fragment)
      }
    }
    return library
  }
  return __load_one(harness, path_or_paths)
}

/**
 * List fragments, optionally filtered by id, tag/tags, tenant, provenance, or status.
 *
 * @effects: []
 * @errors: []
 */
pub fn prompt_library_list(library, filters = nil) {
  const fragments = __require_library(library, "prompt_library_list")
  return fragments.filter({ fragment -> __matches_filters(fragment, filters) })
}

/**
 * Find one fragment by id, returning nil when it is absent.
 *
 * @effects: []
 * @errors: []
 */
pub fn prompt_library_find(library, id) {
  for fragment in __require_library(library, "prompt_library_find") {
    if fragment.id == id {
      return fragment
    }
  }
  return nil
}

/**
 * Render one fragment to text.
 *
 * @effects: []
 * @errors: []
 */
pub fn prompt_library_inject(library, id, bindings = nil) {
  const fragment = prompt_library_find(library, id)
  require fragment != nil, "prompt_library_inject: unknown fragment '" + id + "'"
  return __render_fragment(fragment, bindings)
}

/**
 * Render one fragment with cache metadata for hosts that consume prompt blocks.
 *
 * @effects: []
 * @errors: []
 */
pub fn prompt_library_payload(library, id, bindings = nil) {
  const fragment = prompt_library_find(library, id)
  require fragment != nil, "prompt_library_payload: unknown fragment '" + id + "'"
  return {
    fragment_id: fragment.id,
    text: __render_fragment(fragment, bindings),
    cache_control: fragment?.cache_control ?? {type: "ephemeral"},
    cache_ttl: fragment?.cache_ttl ?? "5m",
    token_budget: fragment?.token_budget,
    provenance: fragment?.provenance,
  }
}

/**
 * Render all matching fragments until `max_tokens` would be exceeded.
 *
 * @effects: []
 * @errors: []
 */
pub fn prompt_library_inject_cluster(library, filters = nil, bindings = nil) {
  const max_tokens = filters?.max_tokens
  let used = 0
  let blocks = []
  for fragment in prompt_library_list(library, filters) {
    const budget = fragment?.token_budget ?? __estimate_tokens_text(fragment?.body ?? "")
    if max_tokens != nil && used + budget > max_tokens {
      continue
    }
    blocks = blocks.push(__render_fragment(fragment, bindings))
    used = used + budget
  }
  return join(blocks, "\n\n")
}

/**
 * Score and return likely useful fragments for a context.
 *
 * @effects: []
 * @errors: []
 */
pub fn prompt_library_suggest(library, ctx = nil) {
  let scored = []
  for fragment in __require_library(library, "prompt_library_suggest") {
    const score = __score_fragment(fragment, ctx ?? {})
    if score > 0 || (ctx?.query == nil && ctx?.tags == nil) {
      scored = scored.push({score: score, fragment: fragment})
    }
  }
  return __top_scored(scored, ctx?.limit ?? ctx?.top_n ?? 5)
}

/**
 * Return a closure-backed namespace for `library.inject(...)` style calls.
 *
 * @effects: []
 * @errors: []
 */
pub fn prompt_library_api(library) {
  return {
    inject: fn(id, bindings = nil) { return prompt_library_inject(library, id, bindings) },
    inject_cluster: fn(filters = nil, bindings = nil) { return prompt_library_inject_cluster(library, filters, bindings) },
    payload: fn(id, bindings = nil) { return prompt_library_payload(library, id, bindings) },
    suggest: fn(ctx = nil) { return prompt_library_suggest(library, ctx) },
    list: fn(filters = nil) { return prompt_library_list(library, filters) },
    find: fn(id) { return prompt_library_find(library, id) },
  }
}

/**
 * Build k-means prompt-hotspot fragment proposals from tenant-scoped conversations.
 *
 * @effects: []
 * @errors: []
 */
pub fn prompt_library_hotspots(conversations, options = nil) {
  const tenant = options?.tenant_id
  const {max_prefix_tokens = 1200, min_fraction = 0.8, min_shared_tokens = 8} = options ?? {}
  const daily_invocations = options?.daily_invocation_count ?? 1
  const dollars_per_token = options?.dollars_per_token ?? 0.0
  const min_monthly_savings = options?.min_monthly_savings_usd ?? 0.0
  let records = []
  let points = []
  let index = 0
  for conversation in conversations {
    if tenant == nil || type_of(conversation) != "dict" || conversation?.tenant_id == tenant {
      const text = __conversation_text(conversation)
      const snippet = __token_prefix(text, max_prefix_tokens)
      records = records
        .push(
        {
          id: __conversation_id(conversation, index),
          tenant_id: if type_of(conversation) == "dict" {
            conversation?.tenant_id
          } else {
            nil
          },
          snippet: snippet,
          embedding: __conversation_embedding(conversation, snippet),
        },
      )
      points = points.push(records[-1].embedding)
    }
    index = index + 1
  }
  if len(records) == 0 {
    return []
  }
  const chosen = __choose_kmeans(points, options ?? {})
  let snippets_by_cluster = []
  let members_by_cluster = []
  let k = 0
  while k < chosen.k {
    snippets_by_cluster = snippets_by_cluster.push([])
    members_by_cluster = members_by_cluster.push([])
    k = k + 1
  }
  let idx = 0
  while idx < len(records) {
    const cluster = chosen.result.assignments[idx]
    snippets_by_cluster[cluster] = snippets_by_cluster[cluster].push(records[idx].snippet)
    members_by_cluster[cluster] = members_by_cluster[cluster].push(records[idx].id)
    idx = idx + 1
  }
  let proposals = []
  let cluster_id = 0
  while cluster_id < len(snippets_by_cluster) {
    const snippets = snippets_by_cluster[cluster_id]
    if len(snippets) > 0 {
      const prefix = __shared_prefix(snippets, min_fraction, min_shared_tokens)
      if prefix.tokens >= min_shared_tokens {
        const tokens_saved = prefix.tokens * (prefix.support - 1)
        const monthly = tokens_saved * daily_invocations * 30.0 * dollars_per_token
        if monthly >= min_monthly_savings {
          const scope = tenant ?? "default"
          const id = "kmeans-" + scope + "-" + substring(sha256(prefix.text), 0, 12)
          proposals = proposals
            .push(
            prompt_fragment(
              id,
              prefix.text,
              {
                title: "K-means hotspot " + to_string(cluster_id),
                tags: options?.tags ?? ["hotspot"],
                token_budget: prefix.tokens,
                provenance: "kmeans",
                tenant_id: tenant,
                status: "pending_review",
                score: chosen.silhouette,
                members: members_by_cluster[cluster_id],
                support: prefix.support,
                tokens_saved: tokens_saved,
                monthly_savings_usd: monthly,
              },
            ),
          )
        }
      }
    }
    cluster_id = cluster_id + 1
  }
  return proposals
}

/**
 * Return pending k-means proposals in the shape expected by review UIs.
 *
 * @effects: []
 * @errors: []
 */
pub fn prompt_library_review_queue(library, filters = nil) {
  let queue = []
  const base_filters = filters ?? {}
  const review_status = filters?.status ?? "pending_review"
  const review_filters = base_filters + {provenance: "kmeans", status: review_status}
  for fragment in prompt_library_list(library, review_filters) {
    queue = queue
      .push(
      {
        id: fragment.id,
        title: fragment.title,
        tenant_id: fragment?.tenant_id,
        text: fragment.body,
        token_budget: fragment?.token_budget,
        support: fragment?.support,
        members: fragment?.members ?? [],
        tokens_saved: fragment?.tokens_saved ?? 0,
        monthly_savings_usd: fragment?.monthly_savings_usd ?? 0.0,
        status: fragment.status,
      },
    )
  }
  return queue
}