// std/agent/pattern_knowledge_sessions.harn
//
// Session-store readings for pattern learning: run grouping, the prompt, tool
// and command evidence a run produced, and the curator's bounded transcript
// drill-down. The canonical session store owns the events; this module only
// projects them, redacting before it bounds.
import {
pl_redact_command,
pl_sanitize_tool_sequence,
} from "std/agent/pattern_knowledge_persistence"
import { pl_text } from "std/agent/pattern_knowledge_values"
import { shell_command_from_argv } from "std/command"
import {
SessionStoreListOptions,
SessionStoreOptions,
SessionStoreRead,
session_store_events,
} from "std/session-store"
pub fn pl_session_store_options(options: any = nil) -> SessionStoreOptions {
const root = pl_text(options?.session_store_root)
return root == "" ? {} : {root: root}
}
pub fn pl_session_store_list_options(limit: int, options: any = nil) -> SessionStoreListOptions {
const root = pl_text(options?.session_store_root)
return root == "" ? {limit: limit, sort_by: "updated_at", order: "descending"} : {
root: root,
limit: limit,
sort_by: "updated_at",
order: "descending",
}
}
pub fn pl_session_store_values<T>(read: SessionStoreRead<list<T>>) -> list<T> {
if read.state == "absent" {
return []
}
return read.value
}
fn pl_session_event_kind(event: dict) -> string {
return pl_text(event?.kind?.type ?? event?.kind?.kind)
}
fn pl_session_transcript_event(event: dict) -> dict {
return event?.payload?.transcript_event ?? {}
}
pub fn pl_session_prompt(events: list) -> string {
for event in events ?? [] {
const transcript_event = pl_session_transcript_event(event)
if pl_text(transcript_event?.kind) != "message"
|| pl_text(transcript_event?.role) != "user"
|| pl_text(transcript_event?.visibility) != "public" {
continue
}
const prompt = pl_text(transcript_event?.text)
if prompt != "" {
return prompt
}
}
return ""
}
pub fn pl_session_tool_sequence(events: list) -> list {
let out = []
for event in events ?? [] {
const transcript_event = pl_session_transcript_event(event)
if pl_session_event_kind(event) != "tool_call"
&& pl_text(transcript_event?.kind) != "tool_call" {
continue
}
const name = pl_text(transcript_event?.metadata?.tool_name)
if name != "" {
out = out + [name]
}
}
return pl_sanitize_tool_sequence(out)
}
fn pl_command_from_input(input: any) -> string {
const command = input?.command
if type_of(command) == "string" {
return to_string(command)
}
const argv = input?.argv ?? command
if type_of(argv) == "list" {
return shell_command_from_argv(argv)
}
return ""
}
/** The command a host reports it ran, from the result's command outcome. */
fn pl_command_from_result(raw_output: any) -> string {
const outcome = raw_output?.data?.run_outcome ?? raw_output?.run_outcome
return type_of(outcome?.command) == "string" ? to_string(outcome.command) : ""
}
/**
* The commands a run executed, in order, with how each exited. A tool call
* names its command in `raw_input` (`command` or `argv`); a host-chosen
* command (a verifier the model invoked without arguments) is named by the
* result's command outcome instead. The exit code is `health.command_exit_code`;
* a command that went to the background (exit still unknown, `command_id`
* set) takes its exit from the later update that reports the same
* `command_id`, such as a wait. A known exit code decides `ok`, because a
* tool call completes normally even when its command fails. A check the host ran
* itself, with no tool call, is a typed checkpoint naming `command` and a `status`
* of `passed` or `failed`. This is what lets a curator see a workflow the agent
* had to discover the hard way, which a tool-name sequence (`run, verify, run`)
* hides.
*
* @effects: []
* @errors: []
* @api_stability: internal
*/
pub fn pl_session_command_ledger(events: list) -> list {
let order = []
let commands = {}
let outcomes = {}
let background = {}
for event in events ?? [] {
const transcript_event = pl_session_transcript_event(event)
const kind = pl_text(transcript_event?.kind)
const metadata = transcript_event?.metadata ?? {}
if kind == "typed_checkpoint" {
const verdict = pl_text(metadata?.status)
const checked = pl_text(metadata?.command)
if checked != "" && (verdict == "passed" || verdict == "failed") {
const host_check = "host-check-" + to_string(len(order))
commands = commands + {[host_check]: {tool: pl_text(metadata?.kind), command: checked}}
outcomes = outcomes + {[host_check]: {exit_code: nil, ok: verdict == "passed"}}
order = order + [host_check]
}
continue
}
const call_id = pl_text(metadata?.tool_call_id)
if call_id == "" || (kind != "tool_call" && kind != "tool_call_update") {
continue
}
const health = metadata?.health ?? {}
const command_id = pl_text(health?.command_id)
const exit_code = health?.command_exit_code
const owner = background[command_id]
if owner != nil && owner != call_id {
// A later update (a wait or poll) settles a backgrounded command.
if exit_code != nil {
outcomes = outcomes + {[owner]: {exit_code: exit_code, ok: exit_code == 0}}
background = background + {[command_id]: nil}
}
continue
}
let command = pl_command_from_input(metadata?.raw_input)
if command == "" && kind == "tool_call_update" {
command = pl_command_from_result(metadata?.raw_output)
}
if command != "" && commands[call_id] == nil {
commands = commands + {[call_id]: {tool: pl_text(metadata?.tool_name), command: command}}
order = order + [call_id]
}
const status = pl_text(metadata?.status)
if kind == "tool_call_update" && (status == "completed" || status == "failed") {
if exit_code == nil && command_id != "" {
background = background + {[command_id]: call_id}
} else {
const ok = exit_code != nil ? exit_code == 0 : status == "completed"
outcomes = outcomes + {[call_id]: {exit_code: exit_code, ok: ok}}
}
}
}
return order.filter({ id -> outcomes[id] != nil }).map({ id -> commands[id] + outcomes[id] })
.to_list()
}
fn pl_session_run_id(event: dict) -> string {
return pl_text(event?.headers?.run_id)
}
pub fn pl_session_run_key(session_id: string, run_id: string) -> string {
return session_id + "::" + run_id
}
pub fn pl_session_runs(events: list) -> list {
let ids = []
let grouped = {}
for event in events ?? [] {
const run_id = pl_session_run_id(event)
if run_id == "" {
continue
}
if !ids.contains(run_id) {
ids = ids + [run_id]
}
grouped = grouped + {[run_id]: (grouped[run_id] ?? []) + [event]}
}
return ids.map({ run_id -> {run_id: run_id, events: grouped[run_id] ?? []} }).to_list()
}
pub fn pl_run_has_eligible_natural_terminal(events: list) -> bool {
for event in events ?? [] {
const transcript_event = pl_session_transcript_event(event)
const headers = event?.headers ?? {}
if pl_session_event_kind(event) != "agent_run_terminal"
&& pl_text(transcript_event?.kind)
!= "agent_run_terminal" {
continue
}
if pl_text(transcript_event?.metadata?.terminal?.kind) == "natural"
&& pl_text(headers["harn.workflow_learning.eligibility"])
== "eligible" {
return true
}
}
return false
}
/**
* The completion owner's goal assessment recorded on the run's natural terminal.
*
* @effects: []
* @errors: []
* @api_stability: internal
*/
pub fn pl_run_goal_outcome(events: list) -> any {
for event in events ?? [] {
const transcript_event = pl_session_transcript_event(event)
if pl_session_event_kind(event) != "agent_run_terminal"
&& pl_text(transcript_event?.kind)
!= "agent_run_terminal" {
continue
}
if pl_text(transcript_event?.metadata?.terminal?.kind) == "natural" {
return transcript_event?.metadata?.goal_outcome
}
}
return nil
}
pub fn pl_run_observed_at(events: list, fallback: string) -> string {
if len(events) == 0 {
return fallback
}
const observed_at = pl_text(events[len(events) - 1]?.ts)
return observed_at == "" ? fallback : observed_at
}
const TRANSCRIPT_ENTRY_LIMIT: int = 80
const TRANSCRIPT_TEXT_LIMIT: int = 600
pub type SessionTranscriptQuery = {start_entry?: int, entry_limit?: int, text_limit?: int}
pub type SessionTranscriptEntryMeta = {
entry_index: int,
content_chars: int,
content_truncated: bool,
}
type SessionTranscriptEntryValue = {kind: "message", role: string, text: string} \
| {kind: "tool_call", tool: string, input: string} \
| {kind: "tool_result", text: string}
pub type SessionTranscriptEntry = SessionTranscriptEntryMeta & SessionTranscriptEntryValue
pub type SessionTranscriptPage = {
session_id: string,
state: "present" | "absent",
entry_count: int,
returned_count: int,
start_entry: int,
next_entry: int?,
truncated: bool,
entries: list<SessionTranscriptEntry>,
}
/** Redact, then bound: clipping first could cut a token below its pattern. */
fn pl_transcript_excerpt(
text: string,
limit: int,
) -> {content: string, content_chars: int, content_truncated: bool} {
const clean = pl_redact_command(pl_text(text))
return {
content: len(clean) <= limit ? clean : clean[0:limit] + "…",
content_chars: len(clean),
content_truncated: len(clean) > limit,
}
}
/** Redact every string inside a tool input before it is serialized. */
fn pl_redact_value(value: any) -> any {
const kind = type_of(value)
if kind == "string" {
return pl_redact_command(value)
}
if kind == "list" {
return value.map({ item -> pl_redact_value(item) }).to_list()
}
if kind == "dict" {
let out = {}
for key in keys(value) {
out = out + {[key]: pl_redact_value(value[key])}
}
return out
}
return value
}
/**
* A bounded, redacted reading of one session from the canonical session
* store: public user and assistant messages, each tool call with its input,
* and the head of each tool result. This is the curator's drill-down when a
* card's command ledger is not enough; it reads the durable store directly,
* so it works for sessions that ended in earlier processes.
*
* @effects: [store.read, fs.read]
* @errors: []
* @api_stability: experimental
*/
pub fn pattern_learning_session_transcript(
agent: HarnessAgent,
session_id: string,
options: any = nil,
query: SessionTranscriptQuery = {},
) -> SessionTranscriptPage {
const entry_limit = query.entry_limit ?? TRANSCRIPT_ENTRY_LIMIT
const text_limit = query.text_limit ?? TRANSCRIPT_TEXT_LIMIT
require entry_limit >= 1 && entry_limit <= TRANSCRIPT_ENTRY_LIMIT,
"session transcript entry_limit must be in [1, 80]"
require text_limit >= 128 && text_limit <= 12000,
"session transcript text_limit must be in [128, 12000]"
require entry_limit * text_limit <= TRANSCRIPT_ENTRY_LIMIT * TRANSCRIPT_TEXT_LIMIT,
"narrow entry_limit before requesting larger transcript entries"
require query.start_entry == nil || query.start_entry >= 0,
"session transcript start_entry must be nonnegative"
const read = session_store_events(agent, session_id, pl_session_store_options(options))
const events = pl_session_store_values(read)
const visible = events.map(pl_session_transcript_event).filter(
{ event: dict ->
const kind = pl_text(event?.kind)
const metadata = event?.metadata ?? {}
return (kind == "message" && pl_text(event?.visibility) == "public")
|| (kind == "tool_call" && pl_text(metadata?.tool_name) != "")
|| kind == "tool_result"
},
)
.to_list()
const start = min(len(visible), query.start_entry ?? max(0, len(visible) - entry_limit))
const end = min(len(visible), start + entry_limit)
let entries: list<SessionTranscriptEntry> = []
for transcript_event in visible[start:end] {
const kind = pl_text(transcript_event?.kind)
const metadata = transcript_event?.metadata ?? {}
if kind == "message" && pl_text(transcript_event?.visibility) == "public" {
const excerpt = pl_transcript_excerpt(pl_text(transcript_event?.text), text_limit)
entries = entries
+ [
{
kind: "message",
role: pl_text(transcript_event?.role),
text: excerpt.content,
entry_index: start + len(entries),
}
+ pick(excerpt, ["content_chars", "content_truncated"]),
]
} else if kind == "tool_call" && pl_text(metadata?.tool_name) != "" {
const excerpt = pl_transcript_excerpt(
json_stringify(pl_redact_value(metadata?.raw_input ?? {})),
text_limit,
)
entries = entries
+ [
{
kind: "tool_call",
tool: pl_text(metadata?.tool_name),
input: excerpt.content,
entry_index: start + len(entries),
}
+ pick(excerpt, ["content_chars", "content_truncated"]),
]
} else if kind == "tool_result" {
const excerpt = pl_transcript_excerpt(pl_text(transcript_event?.text), text_limit)
entries = entries
+ [
{kind: "tool_result", text: excerpt.content, entry_index: start + len(entries)}
+ pick(excerpt, ["content_chars", "content_truncated"]),
]
}
}
return {
session_id: session_id,
state: read.state,
entry_count: len(visible),
returned_count: len(entries),
start_entry: start,
next_entry: end < len(visible) ? end : nil,
truncated: start > 0 || end < len(visible)
|| entries.any({ entry -> entry.content_truncated }),
entries: entries,
}
}