// std/agent/crystallization_curator.harn
//
// Agentic write-side of cross-session crystallization. Pattern memory supplies
// bounded evidence; a normal Harn agent loop decides whether and how to turn it
// into a reusable skill, MCP tool, workflow, or hybrid. Deterministic code only
// validates the terminal proposal contract and evidence membership.
import { LearnedDispatchDeclaration } from "std/agent/learned/sources"
import { agent_loop } from "std/agent/loop"
import {
pattern_learning_accepted_skills,
pattern_learning_curator_evidence,
pattern_learning_import_session_records,
pattern_learning_pending,
pattern_learning_record_curated_batch,
} from "std/agent/pattern_knowledge"
pub import { CuratedCapabilityKind } from "std/agent/pattern_knowledge_curated"
import { pl_state_root } from "std/agent/pattern_knowledge_persistence"
import {
SessionTranscriptQuery,
pattern_learning_session_transcript,
} from "std/agent/pattern_knowledge_sessions"
import { agent_tool_handler_result } from "std/agent/tool_lifecycle"
import { command_run, command_sequence_plan } from "std/command"
import { tool_registry_from } from "std/tools"
const CURATOR_SCHEMA = "harn.crystallization.curator.v1"
const CURATOR_VALIDATION_TIMEOUT_MS: int = 120000
fn cc_text(value: string?) -> string {
return regex_replace(r"\s+", " ", to_string(value ?? "").trim())
?? to_string(value ?? "").trim()
}
/**
* Run trusted, fixed-argv toolchain commands under the curator's owning
* capability sandbox. `workspace_paths` retains Harn's in-process filesystem
* and launch-cwd checks while avoiding an unsupported nested macOS sandbox-exec
* around the fixed Harn argv. Candidate effects remain capability mediated.
*/
fn cc_toolchain_command_options(overrides: dict? = nil) -> dict {
const cwd = to_string(overrides?.cwd ?? "")
const isolated_runtime = if cwd == "" {
{LANG: "en_US.UTF-8", TERM: "dumb"}
} else {
{
HARN_PROJECT_ROOT: cwd,
HARN_STATE_DIR: path_join(cwd, ".harn-state"),
LANG: "en_US.UTF-8",
TERM: "dumb",
}
}
return {sandbox_profile: "workspace_paths", env_mode: "replace", env: isolated_runtime}
+ (overrides
?? {})
}
fn cc_recent_evidence(harness: Harness, options: any = nil) -> list {
const supplied = options?.evidence
const all = if type_of(supplied) == "list" {
supplied
} else {
pattern_learning_curator_evidence(harness, options)
}
const limit = min(max(1, options?.evidence_limit ?? 12), 40)
const start = max(0, len(all) - limit)
return all[start:len(all)]
}
fn cc_evidence_cards(evidence: list) -> list {
return (evidence ?? []).map(
{ item ->
return {
id: item?.id,
session_id: item?.session_id,
prompt: item?.prompt,
tool_sequence: item?.tool_sequence ?? [],
commands: item?.command_ledger ?? [],
observed_at: item?.observed_at,
outcome: item?.outcome,
}
},
)
.to_list()
}
/**
* Sessions that failed a command, later passed that same command, and ended on a
* pass, counted from each card's command ledger. Empty unless at least two
* distinct sessions did, since one recovery is not repetition. A card with no
* session id cannot be told apart from another, so it never counts. Command text
* is carried verbatim; whether two recoveries are the same fix stays the
* curator's judgment.
*/
fn cc_repeated_recoveries(cards: list) -> list {
let out = []
let sessions = []
for card in cards {
let failed = []
let recovered_with = []
let last_ok = false
let failure_rerun_passed = false
for entry in card?.commands ?? [] {
const command = to_string(entry?.command ?? "")
if entry?.ok == false {
if command != "" {
failed = failed + [command]
}
last_ok = false
} else if entry?.ok == true {
last_ok = true
if len(failed) > 0 {
recovered_with = recovered_with + [command]
failure_rerun_passed = failure_rerun_passed
|| failed.any({ failure -> command.contains(failure) })
}
}
}
const session = cc_text(card?.session_id)
if session != "" && last_ok && failure_rerun_passed {
if !sessions.contains(session) {
sessions = sessions + [session]
}
out = out
+ [{session_id: card?.session_id, failed: failed, recovered_with: recovered_with}]
}
}
return len(sessions) >= 2 ? out : []
}
fn cc_session_ids(evidence: list) -> list {
let out = []
for item in evidence ?? [] {
const id = cc_text(item?.session_id)
if id != "" && !out.contains(id) {
out = out + [id]
}
}
return out
}
const REVIEWED_EVIDENCE_CAP: int = 200
const MIN_CITED_SESSIONS: int = 2
fn cc_review_file(fs: HarnessFs, options: any = nil) -> string {
return path_join(pl_state_root(fs, options), "crystallization", "curator-review.json")
}
/** Evidence ids an earlier review already saw. */
fn cc_reviewed_ids(fs: HarnessFs, options: any = nil) -> list {
const text = try {
fs.read_text(cc_review_file(fs, options))
} catch {
""
}
const parsed = text == "" ? nil : json_parse(text)
return type_of(parsed?.evidence_ids) == "list" ? parsed.evidence_ids : []
}
fn cc_record_review(fs: HarnessFs, evidence: list, options: any = nil) {
let ids = cc_reviewed_ids(fs, options)
for item in evidence {
const id = cc_text(item?.id)
if id != "" && !ids.contains(id) {
ids = ids + [id]
}
}
const start = max(0, len(ids) - REVIEWED_EVIDENCE_CAP)
const path = cc_review_file(fs, options)
fs.mkdir(dirname(path))
fs.write_text(path, json_stringify({evidence_ids: ids[start:len(ids)]}))
}
/**
* True when a session paid a workflow discovery cost the installed library
* does not already remove: a command failed, or it ran a command no installed
* check runs. A session that only ran installed checks, and passed, teaches
* nothing new. A session that ran no command counts as new: persistence stores
* an absent ledger as an empty one, and no installed check covers a session
* that never ran one.
*/
fn cc_shows_new_workflow(item: dict, installed: list) -> bool {
const checks = installed.map({ entry -> entry.verify_command }).filter({ text -> text != "" })
.to_list()
const ledger = item?.command_ledger
if type_of(ledger) != "list" || len(ledger) == 0 {
return true
}
for entry in ledger {
if !(entry?.ok ?? false) {
return true
}
const command = to_string(entry?.command ?? "")
if command != ""
&& !checks.any({ check -> cc_runs_declared_check(check, {command: command, cwd: ""}) }) {
return true
}
}
return false
}
fn cc_prompt(
fs: HarnessFs,
evidence: list,
pending: list,
installed: list = [],
declared: list = [],
requested_kind: CuratedCapabilityKind? = nil,
) -> dict {
const cards = cc_evidence_cards(evidence)
const system = """
You are Harn's crystallization curator. You inspect completed coding-agent sessions and decide whether repeated or strongly reusable work should become a durable project capability.
Think like a senior harness engineer, not a sequence miner. Infer intent, invariants, repository conventions, useful parameters, failure recovery, and the narrowest reusable interface. A capability may be a skill, an executable Harn MCP tool, a Harn workflow that mixes deterministic and agentic stages, or a hybrid. It is correct to propose nothing.
Use inspect_session_evidence when the summary cards are insufficient and a card supplies a non-empty session_id; when none does, the cards are the complete evidence available. Before authoring an executable proposal, retrieve the narrow Harn guides you need with lookup_harn_skill; harn-language plus harn-mcp or harn-orchestration and harn-testing are usually sufficient. For an MCP tool, call scaffold_harn_tool before authoring: it projects Harn's current canonical generator into the single-file package shape accepted here, so do not reconstruct an older tool API from memory. Search compiler-owned global function names with search_harn_builtins instead of guessing APIs. For every executable proposal, author Harn language—not Rust, TypeScript, Python, or pseudocode—and call validate_harn_candidate on the complete source. Repair it until the compiler and authored tests report pass. Test pure helpers for deterministic rendering and validation, and also exercise at least one representative success path through the public tool registry. A workspace-writing tool must annotate `kind: "edit"` and `side_effect_level: "workspace_write"`. Return its producer facts with `agent_tool_handler_result`: successful data must carry `mutation_status: "applied"` plus the complete repo-relative `changed_paths` list (or `mutation_status: "unchanged"` when it proved the requested state already existed). When the tool can deterministically reread and prove every changed artifact, include `verification: agent_tool_postcondition(changed_paths)` only after those checks pass; never certify an unchecked write. Its tests must assert the dispatch envelope's typed mutation and postcondition receipts and the real filesystem effects, not merely its plan. In an MCP server, fs.project_root() is the capability package while fs.cwd() is the consumer workspace: apply consumer-repository effects relative to fs.cwd(). Finish by calling submit_crystallization_batch exactly once successfully with zero to three proposals. A rejected submission is feedback: repair and resubmit. Never claim evidence you did not inspect. Do not encode secrets, machine-specific absolute paths, or transcript-specific ids into an artifact.
Each executable proposal must include complete Harn source in artifact.source and a deterministic user-test suite in artifact.test_source. Set artifact.entrypoint to server.harn for harn_tool/hybrid proposals or workflow.harn for harn_workflow proposals. MCP server source must be runnable with `harn serve mcp server.harn`; tests must be runnable with `harn test test.harn`. Keep external effects behind Harness capabilities, declare capabilities and side effects, preserve approval boundaries, and prefer a small semantic interface over replaying incidental low-level calls.
Treat authored tests as falsifiers for the repository contract, not liveness checks. For every representative success path, assert the exact externally consumed outputs—such as normalized paths, command arguments, generated names, status fields, and ordering—not only `ok`, non-empty output, or a generic substring. Include at least one held-out compositional input that was not copied from an evidence card (for example a multiword identifier when the evidence names were single words). A tool that dispatches successfully but returns a malformed path or subtly wrong receipt must fail admission.
Harn tests are `pipeline test_name(harness: Harness) { assert_eq(...) }` and may import public helpers from `./server`. Omit unused parameters. Declare a named type alias before schema_of(TypeName); inline record expressions are values, not type declarations. List indexing returns a nilable element: guard an indexed value before passing it as a non-nil string. Do not use `use`, `struct`, `Vec`, `Result`, attributes, macros, references, or other Rust syntax.
These examples define breadth, not templates:
1. Repeated package verification may become verify_package(package): one MCP tool that runs the repository's typecheck, tests, and lint with failure receipts. The insight is the verified contract, not argv-position extraction.
2. Repeated pull-request babysitting may become monitor_merge_candidate(repo, pr): a durable Harn workflow that observes checks and reviews, parks on triggers, classifies safe transitions agentically, and never merges without the configured policy boundary.
3. Repeated creation of framework objects in a language with weak AST support may become add_framework_entity(name, fields): a tool that studies nearby exemplars, renders the repository-specific files, applies hash-guarded edits, and runs the framework's own validation. It may retain a bounded agentic step when deterministic parsing is not reliable.
Each card's `commands` lists the commands that run executed, in order, with exit codes. A run that failed several commands before one succeeded shows a project workflow the agent had to discover the hard way: how this repository is tested, built, generated, or deployed. Such hard-won knowledge is strong evidence once two sessions show it, because every future session would pay the same discovery cost. Encode the working sequence, its required environment and ordering, as a capability that later sessions can call first try. For a deterministic command sequence, call scaffold_harn_tool with `steps` (the working commands in order, argv words relative to the repository): it returns a complete tested tool and its `verify_command`. Validate it, then submit it as a harn_tool with that artifact and `verify_command` unchanged. When the full sequence is slow, also pass `fast_steps`: the quick check an agent should run after each edit, such as the formatter and linter plus the fastest declared tests. Submit `fast_verify_command` unchanged beside `verify_command`; the full sequence stays the check that must pass before finishing.
The repository's declared checks set each check's scope: its arguments, filters, markers, and directory. A learned sequence starts from them. Add the steps the evidence shows they need first (generate, build, install) and keep each declared check you use as one step, word for word, with its `cwd`. Never replace a declared check with a broader command an agent happened to run: a slow or out-of-scope suite the repository excludes makes every future session pay for it, and fail on code the task did not touch. When declared checks disagree on scope, as when a Makefile target runs every test but the CI workflow excludes a slow suite, use the ones the CI workflow runs: they are what a change must pass to merge. When a declared `verify` check that sessions already passed aggregates the others, keep it whole so the sequence still runs everything it runs. A submission whose `verify_command` runs neither a declared test check nor such a verify check is rejected.
Count recovery across sessions. `repeated_recoveries` lists sessions that failed a command, later passed that same command, and ended on a pass, counted from their command ledgers, so treat those facts as confirmed. When its entries share the same kind of step, each of those sessions paid to rediscover one fix and the next session will pay again. Propose that recovery as a sequence: the steps, then the declared check, unchanged. Use the repository's own named recipe for a step when the evidence shows one, such as a make or just target, instead of rebuilding its arguments; a step runs without a shell, so a glob in it never expands. A sequence that only repeats a declared check adds nothing and is rejected. Being able to state the fix in one line, already knowing the declared check, or a step rewriting tracked generated or formatted files are not reasons to decline: the sessions ran those steps themselves to finish, and the agent still reviews the resulting diff. Decline only when the failures came from each task's own code or the recoveries have nothing in common.
Every proposal's `evidence_ids` must list the `id` of cards, not their `session_id`, from at least two sessions, each with a non-empty `session_id` and at least one command. A submission that cites fewer is rejected, so submit zero proposals when the window does not hold two such sessions.
Prefer proposals that compress reasoning while preserving or improving correctness. Reject coincidental repetition, tasks with unstable semantics, and capabilities already covered by the pending or installed library.
"""
const message = """
Review this bounded evidence window and the existing pending capability cards.
<evidence_cards>
${json_stringify(cards)}
</evidence_cards>
<repeated_recoveries>
${json_stringify(cc_repeated_recoveries(cards))}
</repeated_recoveries>
<existing_pending>
${json_stringify(pending ?? [])}
</existing_pending>
<installed_capabilities>
${json_stringify(installed)}
</installed_capabilities>
<declared_checks>
${json_stringify(declared)}
</declared_checks>
An installed capability already serves future sessions: do not propose it again under any name. Submit zero proposals when the evidence shows nothing beyond the installed and pending library.
Call submit_crystallization_batch when your analysis is complete.
"""
const dispatch_guidance = fs.render_prompt(
"std/agent/learned/prompts/curation.harn.prompt",
{
dispatch_schema: json_stringify(schema_to_json_schema(schema_of(LearnedDispatchDeclaration))),
requested_kind: requested_kind ?? "choose the appropriate kind",
},
)
return {system: "${system}\n\n${dispatch_guidance}", message: message}
}
fn cc_allowed_session(args: dict, allowed: list) -> string {
const id = cc_text(args?.session_id)
if id == "" || !allowed.contains(id) {
throw "inspect_session_evidence: session_id is outside this evidence window. Pass a card's session_id field, not its id."
}
return id
}
fn cc_validate_artifact(harness: Harness, artifact: dict, options: any = nil) -> dict {
const source = to_string(artifact?.source ?? "")
const test_source = to_string(artifact?.test_source ?? "")
const entrypoint = to_string(artifact?.entrypoint ?? "")
const injected = options?.validator
if injected != nil {
const checked = injected(source)
return checked + {artifact: artifact}
}
if !["server.harn", "workflow.harn"].contains(entrypoint) {
return {outcome: "fail", error: "entrypoint must be server.harn or workflow.harn"}
}
const import_path = entrypoint == "server.harn" ? "./server" : "./workflow"
if !test_source.contains(import_path) || !test_source.contains("assert") {
return {
outcome: "fail",
error: "test_source must import `" + import_path + "` and assert observable helper behavior",
}
}
const dir = harness.fs.mkdtemp_in_workspace("harn-curator-")
return try {
harness.fs.write_text(path_join(dir, entrypoint), source)
harness.fs.write_text(path_join(dir, "test.harn"), test_source)
const formatted = command_run(
harness.tools,
[cc_harn_binary(harness.env, options), "fmt", entrypoint, "test.harn"],
cc_toolchain_command_options(
{cwd: dir, timeout_ms: options?.validation_timeout_ms ?? CURATOR_VALIDATION_TIMEOUT_MS},
),
)
if !(formatted?.success ?? false) {
harness.fs.delete(dir)
return {
outcome: "fail",
error: "harn fmt failed",
format_stdout: to_string(formatted?.stdout ?? "")[0:4000],
format_stderr: to_string(formatted?.stderr ?? "")[0:4000],
}
}
const normalized_source = harness.fs.read_text(path_join(dir, entrypoint))
const normalized_test = harness.fs.read_text(path_join(dir, "test.harn"))
const check = command_run(
harness.tools,
[cc_harn_binary(harness.env, options), "check", "--strict", entrypoint, "test.harn"],
cc_toolchain_command_options(
{cwd: dir, timeout_ms: options?.validation_timeout_ms ?? CURATOR_VALIDATION_TIMEOUT_MS},
),
)
let tested = {}
if check?.success ?? false {
tested = command_run(
harness.tools,
[cc_harn_binary(harness.env, options), "test", "test.harn"],
cc_toolchain_command_options(
{cwd: dir, timeout_ms: options?.validation_timeout_ms ?? CURATOR_VALIDATION_TIMEOUT_MS},
),
)
}
harness.fs.delete(dir)
const passed = (check?.success ?? false) && (tested?.success ?? false)
const diagnostics = {
outcome: passed ? "pass" : "fail",
check_status: check?.status,
check_timed_out: check?.timed_out ?? false,
check_stdout: to_string(check?.stdout ?? "")[0:4000],
check_stderr: to_string(check?.stderr ?? "")[0:4000],
test_status: tested?.status,
test_timed_out: tested?.timed_out ?? false,
test_stdout: to_string(tested?.stdout ?? "")[0:4000],
test_stderr: to_string(tested?.stderr ?? "")[0:4000],
}
// The model already owns the submitted source. Re-echoing both complete
// files on every failed compiler turn multiplies context and prompt-cache
// writes without adding information. Return formatter-normalized files only
// on success, where the terminal persistence boundary needs them.
return passed ? diagnostics
+ {
artifact: artifact + {source: normalized_source, test_source: normalized_test},
} : diagnostics
} catch (e) {
harness.fs.delete(dir)
return {outcome: "fail", error: to_string(e)}
}
}
fn cc_harn_binary(env: HarnessEnv, options: any = nil) -> string {
return options?.harn_binary ?? env.get("HARN_BIN") ?? "harn"
}
fn cc_lookup_skill(
capabilities: {env: HarnessEnv, fs: HarnessFs, tools: HarnessTools},
raw_name: string?,
options: any = nil,
) -> dict {
const name = cc_text(raw_name)
const allowed = [
"harn-language",
"harn-agent",
"harn-mcp",
"harn-testing",
"harn-orchestration",
"harn-product-quality",
]
if !allowed.contains(name) {
throw "lookup_harn_skill: unsupported guide `" + name + "`"
}
const dir = capabilities.fs.mkdtemp_in_workspace("harn-curator-guide-")
const result = try {
const executed = command_run(
capabilities.tools,
[cc_harn_binary(capabilities.env, options), "skill", "get", name, "--full"],
cc_toolchain_command_options({cwd: dir, timeout_ms: options?.guide_timeout_ms ?? 30000}),
)
capabilities.fs.delete(dir)
executed
} catch (e) {
capabilities.fs.delete(dir)
throw e
}
const stdout = to_string(result?.stdout ?? "")
const stderr = to_string(result?.stderr ?? "")
return {
name: name,
success: result?.success ?? false,
guide: stdout[0:min(len(stdout), options?.guide_max_bytes ?? 16000)],
stderr: stderr[0:min(len(stderr), 2000)],
}
}
const COMMAND_SEQUENCE_MAX_STEPS: int = 8
const COMMAND_SEQUENCE_SERVER = """
import { command_run } from "std/command"
import { ToolRegistry } from "std/tools"
const STEP_TIMEOUT_MS: int = 300000
const TAIL_LINES: int = 25
/** The repository's working sequence, in the order that works. */
const STEPS: list = __STEPS__
/**
* The steps to run. A non-empty `target` (a repository-relative path such as a
* test directory) narrows the final step.
*/
pub fn check_plan(target: string) -> list {
const clean = target.trim()
if clean != "" && (clean.starts_with("/") || clean.contains("..") || !regex_match("^[A-Za-z0-9_./:-]+$", clean)) {
throw "target must be a repository-relative path, got: " + clean
}
let plan = []
for index in range(0, len(STEPS)) {
const step = STEPS[index]
plan = plan + [index == len(STEPS) - 1 && clean != "" ? step + {argv: step.argv + [clean]} : step]
}
return plan
}
fn tail_text(text: string) -> string {
const lines = text.split("\n")
const start = max(0, len(lines) - TAIL_LINES)
return join(lines[start:len(lines)], "\n")
}
/** Compact receipt: which steps ran, the first failing step, and its output tail. */
pub fn summarize(steps: list) -> dict {
let failed = nil
for step in steps {
if !step.ok {
failed = step
break
}
}
const last = len(steps) == 0 ? nil : steps[len(steps) - 1]
return {
ok: failed == nil && len(steps) > 0,
steps: steps.map({ step -> {label: step.label, ok: step.ok, exit_code: step.exit_code} }).to_list(),
failed_step: failed?.label,
output_tail: tail_text(to_string((failed ?? last)?.output ?? "")),
}
}
/** Runs one step's argv from a directory and returns its process result. */
pub type StepRunner = fn(list, string) -> dict
/** Run `plan` in order from `cwd`, stopping at the first failing step. */
pub fn run_plan(run: StepRunner, cwd: string, plan: list) -> dict {
let steps = []
for step in plan {
const dir = to_string(step?.cwd ?? "")
const result = run(step.argv, dir == "" ? cwd : path_join(cwd, dir))
steps = steps + [{label: step.label, ok: result.success, exit_code: result.exit_code, output: result.combined}]
if !result.success {
break
}
}
return summarize(steps)
}
/** Return a tool registry containing `__TOOL__`. */
pub fn tools(harness: Harness, registry: ToolRegistry? = nil) -> ToolRegistry {
let reg = registry ?? tool_registry()
reg = tool_define(
reg,
"__TOOL__",
__DESCRIPTION__,
{
parameters: {
target: {type: "string", description: "Optional repository-relative path that narrows the final step; empty for everything."},
},
returns: {type: "object"},
annotations: {kind: "execute", side_effect_level: "workspace_write"},
handler: { args ->
const run = { argv, cwd -> command_run(harness.tools, argv, {cwd: cwd, timeout_ms: STEP_TIMEOUT_MS}) }
return run_plan(run, harness.fs.cwd(), check_plan(to_string(args?.target ?? "")))
},
},
)
return reg
}
/** Serve this package's tools over MCP. */
pipeline default(harness: Harness) {
harness.tools.mcp_tools(tools(harness))
}
"""
const COMMAND_SEQUENCE_TEST = """
import { check_plan, run_plan, summarize } from "./server"
pipeline test_plan_keeps_the_learned_order() {
const original = check_plan("")
assert_eq(original.map({ step -> step.label }).to_list(), __LABELS__)
const narrowed = check_plan("tests/unit")
assert_eq(narrowed[len(narrowed) - 1]?.cwd, original[len(original) - 1]?.cwd, "narrowing must preserve the final step directory")
assert_eq(narrowed[len(narrowed) - 1].argv[len(narrowed[len(narrowed) - 1].argv) - 1], "tests/unit")
}
pipeline test_plan_rejects_a_path_escape() {
const escaped = try {
check_plan("../outside")
}
assert(is_err(escaped), "a target must stay inside the repository")
}
pipeline test_summary_reports_the_first_failing_step() {
const receipt = summarize(
[
{label: "first", ok: true, exit_code: 0, output: "fine"},
{label: "second", ok: false, exit_code: 2, output: "broken here"},
],
)
assert_eq(receipt.ok, false)
assert_eq(receipt.failed_step, "second")
assert_eq(receipt.output_tail, "broken here")
}
pipeline test_run_stops_at_the_first_failure() {
let calls = []
const fake = { argv, cwd ->
calls = calls + [{argv: argv, cwd: cwd}]
const failing = argv[0] == "second"
return {success: !failing, exit_code: failing ? 2 : 0, combined: failing ? "stale table" : "fine"}
}
const receipt = run_plan(
fake,
"workspace",
[
{label: "first", argv: ["first", "a"]},
{label: "second", argv: ["second"]},
{label: "never", argv: ["never"]},
],
)
assert_eq(calls, [{argv: ["first", "a"], cwd: "workspace"}, {argv: ["second"], cwd: "workspace"}])
assert_eq(receipt.steps.map({ step -> step.label }).to_list(), ["first", "second"])
assert_eq(receipt.failed_step, "second")
assert_eq(receipt.output_tail, "stale table")
}
"""
/** One step as shell text; a step with a `cwd` runs in a subshell from that directory. */
fn cc_step_shell(step: dict) -> string {
const command = join(step.argv.map({ word -> cc_shell_word(word) }).to_list(), " ")
const dir = to_string(step?.cwd ?? "")
return dir == "" ? command : "(cd " + cc_shell_word(dir) + " && " + command + ")"
}
fn cc_shell_word(word: string) -> string {
if word != "" && regex_match("^[A-Za-z0-9_./:=@%+-]+$", word) {
return word
}
return "'" + word.replace("'", "'\"'\"'") + "'"
}
/** Validate learned `[{label, argv, cwd?}]` steps: at most eight, repository-relative. */
fn cc_normalize_steps(raw_steps: list, field: string) -> list {
if type_of(raw_steps) != "list" || len(raw_steps) == 0
|| len(raw_steps) > COMMAND_SEQUENCE_MAX_STEPS {
throw "invalid_steps: ${field} must list 1 to ${COMMAND_SEQUENCE_MAX_STEPS} commands"
}
let steps = []
for raw in raw_steps {
const label = regex_replace(r"[^a-z0-9_]+", "_", lowercase(cc_text(raw?.label))) ?? ""
const argv = raw?.argv
if label == "" || type_of(argv) != "list" || len(argv) == 0 {
throw "invalid_steps: each step needs a label and a non-empty argv list"
}
let words = []
for word in argv {
const text = to_string(word ?? "")
if type_of(word) != "string" || text == "" || text.starts_with("/") {
throw "invalid_steps: argv entries must be non-empty, repository-relative strings: "
+ json_stringify(argv)
}
words = words + [text]
}
const dir = to_string(raw?.cwd ?? "")
if dir != ""
&& (dir.starts_with("/") || dir.contains("..") || !regex_match("^[A-Za-z0-9_./-]+$", dir)) {
throw "invalid_steps: a step cwd must be a repository-relative directory, got: " + dir
}
steps = steps
+ [dir == "" ? {label: label, argv: words} : {label: label, argv: words, cwd: dir}]
}
return steps
}
fn cc_steps_shell(steps: list) -> string {
return join(steps.map({ step -> cc_step_shell(step) }).to_list(), " && ")
}
// Substitute only tokens in the trusted template, never tokens in inserted data.
fn cc_sequence_template(template: string, bindings: dict<string, string>) -> string {
const parts = template.split("__")
let rendered = ""
for index in range(0, len(parts)) {
const part = parts[index] ?? ""
if index % 2 == 0 {
rendered = rendered + part
} else {
const value = bindings[part]
if value == nil {
throw "missing command-sequence template binding: " + part
}
rendered = rendered + to_string(value)
}
}
return rendered
}
// JSON is data, not Harn source: carry its bytes in an ASCII-only literal.
fn cc_sequence_data(value: any) -> string {
return "json_parse(base64_decode(\"" + base64_encode(json_stringify(value)) + "\"))"
}
/**
* Render a complete, tested MCP tool package that runs a learned command
* sequence in order and returns a compact failure receipt, plus the same
* sequence as one shell line (`verify_command`) a host may adopt as the
* project's verifier. `steps` is `[{label, argv, cwd?}]`, at most eight steps,
* each a fixed argv with repository-relative paths. Optional `fast_steps`, in
* the same shape, is the quick check to run while working (for example lint
* and the fastest declared tests); it projects to `fast_verify_command` and the
* full `steps` stay the check that must pass before finishing.
*
* @effects: []
* @errors: [invalid_steps]
* @api_stability: experimental
*/
pub fn crystallization_command_sequence_package(
raw_name: string,
raw_description: string,
raw_steps: list,
raw_fast_steps: list? = nil,
) -> dict {
const tool = regex_replace(r"[^a-z0-9_]+", "_", lowercase(cc_text(raw_name))) ?? ""
if tool == "" || !regex_match("^[a-z][a-z0-9_]*$", tool) {
throw "invalid_steps: name must start with a letter, got: " + cc_text(raw_name)
}
const description = raw_description
if description.trim() == "" {
throw "invalid_steps: description is required"
}
const steps = cc_normalize_steps(raw_steps, "steps")
const fast = raw_fast_steps == nil || len(raw_fast_steps) == 0 ? [] : cc_normalize_steps(
raw_fast_steps,
"fast_steps",
)
const labels = steps.map({ step -> step.label }).to_list()
const source = cc_sequence_template(
COMMAND_SEQUENCE_SERVER,
{
STEPS: cc_sequence_data(steps),
TOOL: tool,
DESCRIPTION: "base64_decode(\"" + base64_encode(description) + "\")",
},
)
const test_source = cc_sequence_template(
COMMAND_SEQUENCE_TEST,
{LABELS: cc_sequence_data(labels)},
)
const rendered = {
entrypoint: "server.harn",
tool_names: [tool],
source: source.trim() + "\n",
test_source: test_source.trim() + "\n",
verify_command: cc_steps_shell(steps),
}
return len(fast) == 0 ? rendered : rendered + {fast_verify_command: cc_steps_shell(fast)}
}
fn cc_scaffold_tool(
capabilities: {env: HarnessEnv, fs: HarnessFs, tools: HarnessTools},
raw_name: string?,
raw_description: string?,
options: any = nil,
) -> dict {
const name = regex_replace(r"[^a-zA-Z0-9_-]+", "-", cc_text(raw_name)) ?? "capability"
const description = cc_text(raw_description)
const dir = capabilities.fs.mkdtemp_in_workspace("harn-tool-scaffold-")
return try {
const generated = command_run(
capabilities.tools,
[
cc_harn_binary(capabilities.env, options),
"tool",
"new",
name,
"--description",
description,
"--dir",
dir,
"--force",
],
cc_toolchain_command_options({cwd: dir, timeout_ms: options?.guide_timeout_ms ?? 30000}),
)
if !(generated?.success ?? false) {
capabilities.fs.delete(dir)
return {success: false, stderr: to_string(generated?.stderr ?? "")[0:4000]}
}
const library = capabilities.fs.read_text(path_join(dir, "lib/tools.harn"))
const server = capabilities.fs.read_text(path_join(dir, "server.harn"))
const test = capabilities.fs.read_text(path_join(dir, "tests/test_tool.harn"))
const projected_server = library + "\n\n"
+ server.replace("import { tools } from \"lib/tools\"\n\n", "")
const projected_test = test.replace(
"import { tools } from \"../lib/tools\"",
"import { tools } from \"./server\"",
)
capabilities.fs.delete(dir)
return {
success: true,
entrypoint: "server.harn",
source: projected_server,
test_source: projected_test,
note:
"Rename and adapt this generated package. Preserve tool_define schema validation and dispatch-level success tests; assert real filesystem effects for workspace-writing tools, use fs.cwd() for the consumer workspace, and keep public pure helpers directly testable.",
}
} catch (e) {
capabilities.fs.delete(dir)
return {success: false, error: to_string(e)}
}
}
fn cc_search_builtins(
capabilities: {env: HarnessEnv, fs: HarnessFs, tools: HarnessTools},
raw_query: string?,
options: any = nil,
) -> dict {
const query = lowercase(cc_text(raw_query))
const terms = query.split(" ").filter({ term -> len(term) >= 2 }).to_list()
if len(terms) == 0 {
return {success: false, error: "query must contain at least one two-character term"}
}
const dir = capabilities.fs.mkdtemp_in_workspace("harn-curator-catalog-")
const result = try {
const executed = command_run(
capabilities.tools,
[cc_harn_binary(capabilities.env, options), "contracts", "builtins", "--pretty", "false"],
cc_toolchain_command_options(
{
cwd: dir,
timeout_ms: options?.guide_timeout_ms ?? 30000,
capture: {max_inline_bytes: options?.catalog_max_bytes ?? 2000000},
},
),
)
capabilities.fs.delete(dir)
executed
} catch (e) {
capabilities.fs.delete(dir)
throw e
}
if !(result?.success ?? false) {
return {success: false, stderr: to_string(result?.stderr ?? "")[0:4000]}
}
const catalog = try {
json_parse(to_string(result?.stdout ?? "{}"))
} catch (e) {
return {success: false, error: "invalid contracts catalog: " + to_string(e)}
}
let primary = []
let secondary = []
for builtin in catalog?.builtins ?? [] {
const name = lowercase(to_string(builtin?.name ?? ""))
const exposure = to_string(builtin?.contract?.exposure?.kind ?? "")
if name.starts_with("__") || !(builtin?.parser_known ?? false)
|| exposure == "runtime_internal" {
continue
}
const projected = {
name: builtin?.name,
exposure: exposure,
return_types: builtin?.return_types ?? [],
parser_known: true,
}
if terms.any({ term -> name == term || name.starts_with(term) || term.starts_with(name) }) {
primary = primary + [projected]
} else if terms.any({ term -> name.contains(term) }) {
secondary = secondary + [projected]
}
}
let matches = primary
for item in secondary {
if len(matches) >= 40 {
break
}
matches = matches + [item]
}
if len(matches) > 40 {
matches = matches[0:40]
}
return {success: true, query: query, matches: matches}
}
/**
* The installed library, normalized to `{name, verify_command}`: the host's
* installed capabilities plus every accepted skill.
*/
fn cc_installed(fs: HarnessFs, options: any = nil) -> list {
let out = []
const accepted = pattern_learning_accepted_skills(fs, options).map(
{ skill -> {name: skill?.name} },
)
for item in (options?.installed ?? []) + accepted.to_list() {
const name = cc_text(item?.name)
if name != "" {
out = out + [{name: name, verify_command: to_string(item?.verify_command ?? "")}]
}
}
return out
}
/** A proposal duplicates an installed capability by name or its exact verifier line. */
fn cc_duplicates_installed(proposal: dict, installed: list) -> bool {
const name = cc_text(proposal?.name)
const verify = to_string(proposal?.artifact?.verify_command ?? "")
return installed.any(
{ item -> item.name == name || (verify.trim() != "" && item.verify_command == verify) },
)
}
/**
* The repository's declared checks, normalized to `{intent, command, cwd, origin}`.
* A host passes the checks its project-check resolver chose; learned checks
* stay out so the curator never reads its own output back as a declaration.
*/
fn cc_declared_checks(options: any = nil) -> list {
let out = []
for item in options?.declared_checks ?? [] {
const command = to_string(item?.command ?? "")
if command != "" {
out = out
+ [
{
intent: cc_text(item?.intent),
command: command,
cwd: to_string(item?.cwd ?? ""),
origin: cc_text(item?.origin),
},
]
}
}
return out
}
/** Match literal argv and directory scopes from the owning shell planner. */
fn cc_runs_declared_check(verify_command: string, check: dict) -> bool {
const observed = command_sequence_plan(verify_command)
const declared = command_sequence_plan(check.command, check.cwd)
if observed.status != "measured" || declared.status != "measured"
|| len(observed.steps) == 0
|| len(declared.steps) == 0 {
return false
}
const have = observed.steps
const want = declared.steps
for start in range(0, len(have) - len(want) + 1) {
if have[start:start + len(want)] == want {
return true
}
}
return false
}
/** True when every step of a verifier already belongs to a declared check. */
fn cc_only_repeats_declared_checks(verify_command: string, declared: list) -> bool {
const observed = command_sequence_plan(verify_command)
if observed.status != "measured" || len(observed.steps) == 0 {
return false
}
let declared_steps = []
for check in declared {
declared_steps = declared_steps + command_sequence_plan(check.command, check.cwd).steps
}
return observed.steps.all({ step -> declared_steps.any({ known -> known == step }) })
}
fn cc_session_passed_command(evidence: list, command: string) -> bool {
return evidence.any(
{ item ->
(item?.command_ledger ?? []).any(
{ entry -> entry?.ok == true && to_string(entry?.command ?? "").contains(command) },
)
},
)
}
/**
* The declared checks a learned verifier must run at least one of: any test
* check, or a verify check a session in the window already passed. A verify
* check can be wider than the test checks, so naming one is not enough; a
* session that ran it shows future sessions pay nothing new for it.
*/
fn cc_required_declared_checks(declared: list, evidence: list) -> list {
return declared.filter(
{ check ->
check.intent == "test"
|| (check.intent == "verify" && cc_session_passed_command(evidence, check.command))
},
)
.to_list()
}
/**
* The distinct sessions a proposal's citations can be counted for: a cited
* evidence item from this window with a session id and a non-empty command ledger.
*/
fn cc_cited_sessions(proposal: dict, evidence: list) -> list {
const cited = proposal?.evidence_ids ?? []
return cc_session_ids(
evidence.filter({ item -> cited.contains(item?.id) && len(item?.command_ledger ?? []) > 0 })
.to_list(),
)
}
fn cc_prepare_valid_proposals(
harness: Harness,
proposals: list,
evidence: list,
options: any = nil,
) -> list {
let prepared = []
const installed = cc_installed(harness.fs, options)
const declared = cc_declared_checks(options)
const required = cc_required_declared_checks(declared, evidence)
for proposal in proposals ?? [] {
if cc_duplicates_installed(proposal, installed) {
continue
}
if len(cc_cited_sessions(proposal, evidence)) < MIN_CITED_SESSIONS {
throw "submit_crystallization_batch: `evidence_ids` must list the `id` of cards, not their session_id, from at least two sessions that each have a non-empty session_id and at least one command. Repair and resubmit, or submit no proposal when the window lacks two. Card ids: "
+ json_stringify(evidence.map({ item -> item?.id }).to_list())
}
if proposal?.kind == "skill" {
prepared = prepared + [proposal]
continue
}
const verify = to_string(proposal?.artifact?.verify_command ?? "")
if verify != "" && len(required) > 0
&& !required.any({ check -> cc_runs_declared_check(verify, check) }) {
throw "submit_crystallization_batch: `verify_command` must run a declared test check, or a verify check a session already passed, word for word from its cwd, not a broader command. A step with a glob or other shell syntax cannot be measured. Declared: "
+ json_stringify(required)
}
if verify != "" && cc_only_repeats_declared_checks(verify, declared) {
throw "submit_crystallization_batch: `verify_command` only repeats declared checks, which later sessions already run. Add the steps it needs first, or submit no proposal."
}
const checked = cc_validate_artifact(harness, proposal?.artifact ?? {}, options)
if checked?.outcome != "pass" {
throw "submit_crystallization_batch: executable package did not pass strict check and authored tests; repair it before resubmitting.\n"
+ json_stringify(checked)
}
prepared = prepared + [proposal + {artifact: checked.artifact}]
}
return prepared
}
fn cc_tools(harness: Harness, evidence: list, options: any, on_submitted: fn(dict) -> nil) {
const allowed_sessions = cc_session_ids(evidence)
const query_schema = schema_to_json_schema(schema_of(SessionTranscriptQuery))
const query_properties = query_schema?.properties
require type_of(query_properties) == "dict",
"session transcript query must have object properties"
const transcript_schema = query_schema
+ {
type: "object",
properties: query_properties + {session_id: {type: "string"}},
required: ["session_id"],
}
return tool_registry_from(
[
{
name: "inspect_session_evidence",
description:
"Inspect a bounded transcript page. Clipped entries report content_truncated and entry_index. Request one entry with start_entry, entry_limit: 1 and text_limit up to 12000 to inspect its full source. The entry_limit * text_limit budget is at most 48000 characters.",
inputSchema: transcript_schema,
returns: {type: "object"},
handler: { args ->
const session_id = cc_allowed_session(args, allowed_sessions)
let source = options
let roots: list<string> = []
for item in evidence {
const root = cc_text(item?.session_store_root)
if cc_text(item?.session_id) == session_id && root != "" && !roots.contains(root) {
roots = roots + [root]
}
}
if len(roots) > 1 {
throw "inspect_session_evidence: session has conflicting source stores"
}
for root in roots {
source = (options ?? {}) + {session_store_root: root}
}
const query: SessionTranscriptQuery = schema_expect(
args,
schema_of(SessionTranscriptQuery),
)
const result = pattern_learning_session_transcript(
harness.agent,
session_id,
source,
query,
)
return agent_tool_handler_result(json_stringify(result), result)
},
annotations: {kind: "lookup", readOnlyHint: true, side_effect_level: "read_only"},
},
{
name: "lookup_harn_skill",
description:
"Retrieve an authoritative Harn authoring guide before writing unfamiliar language, MCP, orchestration, testing, or product-quality code.",
parameters: {
name: {
type: "string",
enum: [
"harn-language",
"harn-agent",
"harn-mcp",
"harn-testing",
"harn-orchestration",
"harn-product-quality",
],
},
},
returns: {type: "object"},
handler: { args ->
const result = cc_lookup_skill(
{env: harness.env, fs: harness.fs, tools: harness.tools},
args?.name,
options,
)
agent_tool_handler_result(to_string(result), result, result.success ? "ok" : "error")
},
annotations: {kind: "lookup", readOnlyHint: true, side_effect_level: "process"},
},
{
name: "scaffold_harn_tool",
description:
"Generate a compiler-current single-file Harn MCP tool and authored-test starting point. With `steps`, return a complete, tested tool that runs that command sequence in order with failure receipts, plus its `verify_command`; with `fast_steps`, also the quick in-progress check as `fast_verify_command`.",
parameters: {
name: {type: "string"},
description: {type: "string"},
steps: {
type: "array",
description:
"Optional learned command sequence: [{label, argv}] in the order that works, argv as repository-relative words.",
items: {
type: "object",
properties: {
label: {type: "string"},
argv: {type: "array", items: {type: "string"}},
cwd: {
type: "string",
description:
"Repository-relative directory the step runs from; omit for the root.",
},
},
},
},
fast_steps: {
type: "array",
description:
"Optional quick check to run while working, same shape as steps: lint and the fastest declared tests, never broader than steps.",
items: {
type: "object",
properties: {
label: {type: "string"},
argv: {type: "array", items: {type: "string"}},
cwd: {type: "string"},
},
},
},
},
returns: {type: "object"},
handler: { args ->
if len(args?.steps ?? []) > 0 || len(args?.fast_steps ?? []) > 0 {
const rendered = try {
crystallization_command_sequence_package(
to_string(args?.name ?? ""),
to_string(args?.description ?? ""),
args.steps,
args?.fast_steps,
)
}
const result = is_err(rendered) ? {
success: false,
error: to_string(unwrap_err(rendered)),
} : unwrap(rendered) + {success: true}
return agent_tool_handler_result(
to_string(result),
result,
result.success ? "ok" : "error",
)
}
const result = cc_scaffold_tool(
{env: harness.env, fs: harness.fs, tools: harness.tools},
args?.name,
args?.description,
options,
)
agent_tool_handler_result(to_string(result), result, result.success ? "ok" : "error")
},
annotations: {kind: "read", side_effect_level: "read_only"},
},
{
name: "search_harn_builtins",
description:
"Search Harn's compiler/runtime-owned builtin contract catalog by semantic name terms. Use before guessing global function names or importing a builtin from stdlib.",
parameters: {
query: {
type: "string",
description:
"Space-separated API concepts such as 'character case string' or 'json parse'.",
},
},
returns: {type: "object"},
handler: { args ->
const result = cc_search_builtins(
{env: harness.env, fs: harness.fs, tools: harness.tools},
args?.query,
options,
)
agent_tool_handler_result(to_string(result), result, result.success ? "ok" : "error")
},
annotations: {kind: "read", side_effect_level: "read_only"},
},
{
name: "validate_harn_candidate",
description:
"Compile-check complete agent-authored Harn source and return bounded diagnostics. Use this before submitting every executable proposal.",
parameters: {
entrypoint: {type: "string", enum: ["server.harn", "workflow.harn"]},
source: {type: "string"},
test_source: {type: "string"},
},
returns: {type: "object"},
handler: { args ->
const result = cc_validate_artifact(harness, args, options)
agent_tool_handler_result(
to_string(result),
result,
result.outcome == "pass" ? "ok" : "error",
)
},
annotations: {kind: "verification", readOnlyHint: true, side_effect_level: "process"},
},
{
name: "submit_crystallization_batch",
description:
"Submit the curator's final zero-to-three typed capability proposals for validation and review.",
parameters: {
decline_reason: {
type: "string",
required: false,
description:
"When a requested artifact kind cannot safely be produced, explain the concrete missing evidence or capability. Required for a zero-proposal response to a requested kind.",
},
proposals: {
type: "array",
maxItems: 3,
items: {
type: "object",
properties: {
kind: options?.requested_kind == nil ? schema_to_json_schema(
schema_of(CuratedCapabilityKind),
) : {type: "string", enum: [options.requested_kind]},
name: {
type: "string",
description:
"Capability name; the boundary canonicalizes reasonable words or underscores to a lowercase hyphenated slug.",
},
title: {type: "string"},
description: {type: "string"},
when_to_use: {type: "string"},
body: {type: "string"},
evidence_ids: {type: "array", items: {type: "string"}, minItems: 1},
capabilities: {type: "array", items: {type: "string"}},
side_effects: {type: "array", items: {type: "string"}},
artifact: {
type: "object",
properties: {
entrypoint: {type: "string"},
tool_names: {type: "array", items: {type: "string"}},
source: {type: "string"},
test_source: {type: "string"},
dispatch: schema_to_json_schema(schema_of(LearnedDispatchDeclaration)),
verify_command: {
type: "string",
description:
"For a command-sequence tool, the same sequence as one shell line, as scaffold_harn_tool returned it.",
},
fast_verify_command: {
type: "string",
description:
"For a command-sequence tool with fast_steps, the quick check as scaffold_harn_tool returned it.",
},
},
},
},
required: [
"kind",
"name",
"title",
"description",
"when_to_use",
"body",
"evidence_ids",
],
},
},
},
returns: {type: "object"},
handler: { args ->
if options?.requested_kind != nil && len(args?.proposals ?? []) == 0
&& cc_text(args?.decline_reason) == "" {
throw "submit_crystallization_batch: explain why the requested artifact cannot safely be produced in decline_reason"
}
const proposals = cc_prepare_valid_proposals(
harness,
args?.proposals ?? [],
evidence,
options,
)
const result = pattern_learning_record_curated_batch(
harness,
args + {proposals: proposals},
evidence,
options,
)
on_submitted(result)
return agent_tool_handler_result(to_string(result), result)
},
annotations: {kind: "record", side_effect_level: "store_write"},
},
],
)
}
/**
* Run one bounded agentic crystallization review over recent session evidence.
* The semantic decision is made by the model; Harn constrains evidence access,
* proposal shape, cost, iterations, and durable review state. `usage` is the
* run's physical provider ledger (tokens and cost of every curator call); it is
* absent when the session reported none, so a host reads unmeasured, never zero.
* A host passes `installed` (`[{name, verify_command}]`) so the curator neither
* proposes nor stages a capability the project already has, and
* `require_new_evidence: true` to skip the model call entirely when every
* evidence item was already seen by an earlier review, or when every unseen
* session only ran installed checks and passed (`no_new_workflow_evidence`). `declared_checks`
* (`[{intent, command, cwd}]`, the checks the repository states) bound a
* learned verifier's scope: one that runs none of the declared test checks is rejected.
* Every proposal must cite evidence from at least two sessions with a session id and
* a command ledger; a submission that does not is rejected whatever the model says.
*
* @effects: [agent, llm, store.read, store.write]
* @errors: []
* @api_stability: experimental
*/
pub fn crystallization_curate(harness: Harness, raw_options: any = nil) -> dict {
const requested_kind: CuratedCapabilityKind? =
raw_options?.requested_kind == nil ? nil : schema_expect(
raw_options.requested_kind,
schema_of(CuratedCapabilityKind),
)
const options = (raw_options ?? {}) + {requested_kind: requested_kind}
const session_import = pattern_learning_import_session_records(harness, options)
const evidence = cc_recent_evidence(harness, options)
if len(evidence) == 0 {
return {
schema: CURATOR_SCHEMA,
status: "no_evidence",
proposals: [],
session_import: session_import,
}
}
if options?.require_new_evidence ?? false {
const reviewed = cc_reviewed_ids(harness.fs, options)
const unreviewed = evidence.filter({ item -> !reviewed.contains(cc_text(item?.id)) }).to_list()
const installed = cc_installed(harness.fs, options)
const status = len(unreviewed) == 0 ? "no_new_evidence" : unreviewed.any(
{ item -> cc_shows_new_workflow(item, installed) },
) ? "" : "no_new_workflow_evidence"
if status != "" {
if len(unreviewed) > 0 {
cc_record_review(harness.fs, unreviewed, options)
}
return {
schema: CURATOR_SCHEMA,
status: status,
proposals: [],
proposal_count: 0,
evidence_count: len(evidence),
session_import: session_import,
}
}
}
const pending_before = pattern_learning_pending(harness, options)
const prompts = cc_prompt(
harness.fs,
evidence,
pending_before,
cc_installed(harness.fs, options),
cc_declared_checks(options),
requested_kind,
)
const route = options?.agent ?? {}
let submitted: dict? = nil
let agent_options = route
+ {
tools: cc_tools(
harness,
evidence,
options,
{ batch: dict ->
submitted = batch
return nil
},
),
allowed_tools: [
"inspect_session_evidence",
"lookup_harn_skill",
"scaffold_harn_tool",
"search_harn_builtins",
"validate_harn_candidate",
"submit_crystallization_batch",
],
require_successful_tools: ["submit_crystallization_batch"],
stop_after_successful_tools: ["submit_crystallization_batch"],
loop_until_done: true,
max_iterations: min(max(2, route?.max_iterations ?? 12), 24),
max_nudges: 2,
session_id: route?.session_id ?? "crystallization-curator-" + harness.random.uuid_v7(),
budget: route?.budget ?? {max_cost_usd: 0.75, max_total_tokens: 60000},
// A curator reviews evidence; it must never recursively become evidence.
workflow_learning_eligibility: "excluded",
}
if route?.provider == nil
&& route?.model == nil
&& route?.models == nil
&& route?.ladder == nil {
agent_options = agent_options + {ladder: "frugal"}
}
const result = agent_loop(harness, prompts.message, prompts.system, agent_options)
if (result?.tools?.successful ?? []).contains("submit_crystallization_batch") {
cc_record_review(harness.fs, evidence, options)
}
const proposals = submitted?.proposals ?? []
return {
schema: CURATOR_SCHEMA,
status: result?.terminal?.kind ?? result?.status ?? "unknown",
curator_session_id: result?.session_id,
evidence_count: len(evidence),
proposal_count: len(proposals),
proposals: proposals,
decline_reason: submitted?.decline_reason ?? "",
session_import: session_import,
usage: result?.physical_usage,
agent_result: result,
}
}