From a12ef94737a20df531bb49da34b21801068c4720 Mon Sep 17 00:00:00 2001 From: Seamus Brady Date: Sun, 26 Apr 2026 18:20:27 +0100 Subject: [PATCH] Codify Nemo's strategies as skills with Strategy Registry seeding (PR 3 of sub-agent-resilience) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Final PR of the sub-agent-resilience plan (Fix 5). Closes the loop: fixes 1-4 gave us runtime resilience; this fix codifies the orchestration patterns Nemo registered locally as skill content + Strategy Registry seeding so every fresh instance has the floor strategies at boot rather than re-discovering them through CBR. Two new skills, four floor strategies seeded automatically. Skills: - .springdrift_example/skills/orchestration-large-inputs/SKILL.md covers reconnaissance-first, search-then-read, parallel-after- reconnaissance. Targets the cog loop for orchestration decisions on large inputs (long documents, multi-document comparisons). - .springdrift_example/skills/when-to-use-writer/SKILL.md covers synthesise-in-root judgment. "If you can imagine writing the response yourself in 200-500 words of structured points, do it" — explicit anti-overuse criteria for the writer agent. Strategy Registry seeding: - New SkillSeeded variant on StrategySource (with encode/decode pair updates in strategy/log.gleam). Distinguished from the existing Observed/Proposed/OperatorDefined for telemetry. - New src/strategy/seed.gleam: floor_strategies() returns the four (name, description, tags) triples; build_seed_events() turns them into StrategyCreated events; seed_if_empty(dir) writes the events ONLY when the registry has zero events. - Idempotent: never overwrites an already-populated registry. Operator-curated and CBR-mined strategies are never disturbed. - Wired into springdrift.gleam boot path next to librarian.init_captures so it runs early in instance startup. Sub-agent-resilience plan moved from docs/roadmap/planned/sub-agent-resilience.md to docs/roadmap/implemented/ with a "What Shipped" preamble documenting all five fixes across PRs #166, #167, and this one. Tests: 9 new in test/strategy/seed_test.gleam covering: - floor_strategies returns all four with descriptions and orchestration tags - seed_if_empty writes four to an empty registry - seeded strategies carry SkillSeeded source variant - seed_if_empty is no-op on populated registry (operator strategies preserved) - repeated seed_if_empty calls are idempotent (no double-seed) - skill files exist on disk Suite at 2083 passing (24 new across the three sub-agent-resilience PRs on top of the 2059 baseline before PR #166). Co-Authored-By: Claude Opus 4.7 (1M context) --- .../orchestration-large-inputs/SKILL.md | 107 ++++++++++ .../skills/when-to-use-writer/SKILL.md | 77 +++++++ .../sub-agent-resilience.md | 20 +- src/springdrift.gleam | 11 + src/strategy/log.gleam | 6 +- src/strategy/seed.gleam | 124 +++++++++++ src/strategy/types.gleam | 8 + test/strategy/seed_test.gleam | 199 ++++++++++++++++++ 8 files changed, 547 insertions(+), 5 deletions(-) create mode 100644 .springdrift_example/skills/orchestration-large-inputs/SKILL.md create mode 100644 .springdrift_example/skills/when-to-use-writer/SKILL.md rename docs/roadmap/{planned => implemented}/sub-agent-resilience.md (88%) create mode 100644 src/strategy/seed.gleam create mode 100644 test/strategy/seed_test.gleam diff --git a/.springdrift_example/skills/orchestration-large-inputs/SKILL.md b/.springdrift_example/skills/orchestration-large-inputs/SKILL.md new file mode 100644 index 0000000..1eceda8 --- /dev/null +++ b/.springdrift_example/skills/orchestration-large-inputs/SKILL.md @@ -0,0 +1,107 @@ +--- +name: orchestration-large-inputs +description: How to orchestrate work across large documents and multi-agent delegations without burning token budgets. Reconnaissance-first, search-then-read, parallel-after-reconnaissance. +agents: cognitive +--- + +# Orchestrating Work Across Large Inputs + +When the operator hands you a large input — a 9000-line book, two long +documents to compare, a sprawling research question — your reflex +will be to dispatch researchers and writers to do the work. **Don't +just dispatch.** The right strategy comes in three layers. + +## 1. Reconnaissance-first + +Before parallel dispatch, before deep section reads, **spend one +small delegation mapping the structure**. The recon delegation: + +- Calls `document_info` to confirm the doc is structured and gauge size +- Calls `list_sections` (with `max_depth: 1` for very large books) to + capture the chapter-level tree +- Returns a compact outline + the section ids you'll need +- **Calls `checkpoint("doc-outline-", outline)`** to save the outline as an artifact and returns the artifact_id in its summary + +Without this step, every downstream researcher independently +re-discovers the same structure, blowing token budget on +bootstrapping rather than on the actual work. In the 2026-04-26 +incident, 13 researchers each paid this cost separately on a +309-section book. + +## 2. Pass the recon artifact to downstream agents + +Every subsequent delegation gets the recon artifact_id via the +`referenced_artifacts` parameter: + +``` +agent_researcher({ + instruction: "Read chapters 3 and 5 and extract memory architecture comparisons", + referenced_artifacts: "art-recon-abc123" +}) +``` + +The framework auto-prepends the artifact's CONTENT (not just its ID) +as a `` block to the agent's first message. The +child sees the structure immediately and doesn't pay the bootstrap +cost. You can pass multiple artifact ids comma-separated. + +## 3. Search-then-read, never read-then-search + +For any document over a few hundred lines, prefer: + +``` +search_library("memory architecture") → returns hits with line spans +read_range(doc_id, line_start, line_end + buffer) → targeted excerpt +``` + +Over: + +``` +list_sections(doc_id) → 309 entries +read_section_by_id × N → many calls +``` + +Sequential `list_sections → read_section_by_id` walks are inherently +expensive on large books. The semantic-search-then-targeted-range +pattern surfaces only the relevant material at a fraction of the +token cost. + +## 4. Parallel-after-reconnaissance + +Parallel dispatch is a force multiplier **after** the structural +context cost has been paid once. The valid sequence: + +1. One reconnaissance delegation → produces and checkpoints the outline +2. Dispatch N parallel followups, each with the recon artifact_id in `referenced_artifacts` +3. Synthesise their results in your own response (see `when-to-use-writer`) + +What to NOT do: parallel-dispatch N agents who each independently +re-discover the structure. That's not parallelism, it's +N-fold-bootstrap-cost. In Nemo's 2026-04-26 session, "two parallel +researchers, one per document" was attempted — both capped because +both were independently re-bootstrapping. Parallelism without recon +multiplies cost; with recon it multiplies throughput. + +## When this applies + +- Large document analysis (>500 lines or >50 sections) +- Multi-document comparisons +- Multi-topic research where each topic spans the same source material +- Anything where you'd otherwise dispatch the same orientation work + multiple times + +## When it doesn't apply + +- Short input (a paragraph, a code snippet, a one-page memo) — the + bootstrap cost is negligible, just dispatch directly +- One-shot tasks that don't need parallel breakdown +- Cases where the operator has already provided structured context + in the prompt (no recon needed) + +## Companion: checkpointing during long work + +When YOU yourself are doing synthesis work in your own response, save +checkpoints as you go via `checkpoint(label, content)`. Your output +budget is finite; the truncation guard catches catastrophic capping +but you should never rely on it as the routine recovery. Save in +chunks, reference the artifact_ids when you reply. diff --git a/.springdrift_example/skills/when-to-use-writer/SKILL.md b/.springdrift_example/skills/when-to-use-writer/SKILL.md new file mode 100644 index 0000000..2d1a3ec --- /dev/null +++ b/.springdrift_example/skills/when-to-use-writer/SKILL.md @@ -0,0 +1,77 @@ +--- +name: when-to-use-writer +description: Decision criteria for delegating to the writer agent vs synthesising directly in your own response. +agents: cognitive +--- + +# When to Use the Writer Agent (And When Not To) + +The writer agent is designed for **unstructured-to-narrative +translation** — taking messy research findings, scattered notes, or +contradictory drafts and producing polished prose with hedging, +citations, and structural rewriting. + +It is **not** designed for "make this look like a final answer." If +your research is already structured, delegating to the writer is +overhead that adds a token-starved layer with no benefit. + +## Use the writer when + +- Findings are unstructured: scattered bullet points, half-finished + thoughts, contradictory drafts that need editorial judgment +- The deliverable is **flowing prose** that builds an argument or + tells a story across multiple paragraphs +- The output needs **substantial rewriting**, not just reorganisation +- High-stakes audience (operator-facing reports for clients, + regulators, archival publication) where careful hedging and + citation matter +- The piece is long enough to benefit from a separate editorial + pass with its own context window + +## Synthesise directly in your own response when + +- Research is already well-organised — tables, bullet points, clear + comparisons, or numbered findings ready to present +- The task is **synthesis-of-presentation**, not narrative + construction. You're picking what to surface from a body of + structured material, not turning prose into prose. +- You're in rapid iteration with the operator and the overhead of + delegation costs more than the benefit +- Your research output fits comfortably in your own response budget + and you can write the synthesis inline + +## The 2026-04-26 lesson + +In that session, 14 researcher delegations produced +well-structured comparative material — tables, bullet points, +section-by-section overlap. Delegating to the writer for "final +form" meant: + +1. Truncating findings to fit the writer's input budget +2. Getting zero useful output because the writer hit its own cap +3. Synthesising directly anyway after the failed writer call + +The orchestrator had the material in working memory the whole time. +The writer detour was pure overhead. Reflexive writer delegation +adds a token-starved layer with no benefit when the input is +already structured. + +## Decision in one line + +**If you can imagine writing the response yourself in 200-500 words +of structured points, do it.** If the response needs prose to +breathe and an editor's eye, delegate. + +## Companion: never delegate when downstream is capped + +If the writer's previous delegation in this cycle returned a +`[truncation_guard:writer]` admission, the writer is structurally +the wrong tool for this scope. Either: + +- Synthesise directly yourself +- Decompose: ask the writer for one section at a time via + `update_draft` calls, with a smaller scope per call +- Ask the operator to widen the writer's `max_tokens` in + `.springdrift/config.toml` + +Don't re-dispatch hoping it'll work this time. diff --git a/docs/roadmap/planned/sub-agent-resilience.md b/docs/roadmap/implemented/sub-agent-resilience.md similarity index 88% rename from docs/roadmap/planned/sub-agent-resilience.md rename to docs/roadmap/implemented/sub-agent-resilience.md index 3bd574d..37b8085 100644 --- a/docs/roadmap/planned/sub-agent-resilience.md +++ b/docs/roadmap/implemented/sub-agent-resilience.md @@ -1,10 +1,24 @@ # Sub-Agent Resilience — Truncation Recovery, Auto-Save, Context Bundles, and Checkpointing -**Status**: Planned -**Priority**: High — observed in production. A two-document comparative-analysis task in a 2026-04-26 Nemo session capped 14 of 14 sub-agent delegations. The cog-loop truncation guard shipped earlier the same day didn't fire because the failure happened one layer down, inside specialist agents. Useful work was produced but truncated mid-output and could not be recovered for follow-up cycles. -**Effort**: Medium-Large (~400-500 LOC across four sub-fixes + tests). Best shipped in two PRs: the truncation/auto-save pair as one, the context bundle and skill updates as a second. +**Status**: Implemented (2026-04-26) +**Priority**: High — observed in production. +**Effort**: ~1500 LOC across three PRs (#166 truncation guard + auto-save, #167 referenced_artifacts + checkpoint, this branch's PR for skills + Strategy Registry seeding) plus 33 new tests. **Source**: 2026-04-26 Nemo session — operator asked for a comparative analysis of two large documents (a 467-line spec and a 9,110-line book with 309 sections). Researcher and writer agents repeatedly hit `max_tokens` while assembling output. 13 researcher delegations and 1 writer delegation, all output-capped. Total: ~772k tokens spent, partial findings produced, no clean deliverable until the orchestrator gave up on delegation and synthesised directly. +## What Shipped + +All five fixes landed across three PRs: + +- **Fix 1 — Sub-agent truncation guard** (PR #166). React loop in `src/agent/framework.gleam` detects MaxTokens-with-no-tool-calls. First hit retries with scope-down nudge without burning a turn; second hit ships a deterministic admission via `framework.build_truncation_admission`. `[truncation_guard:]` prefix is the load-bearing signal. +- **Fix 2 — Auto-save partial output** (PR #166). Design deviation from the original plan: instead of writing partial work to a separate artifact via the artifacts subsystem, the admission text **embeds** the agent's accumulated text (across all turns of the failing react loop) with head/tail elision when over 4KB. Keeps the framework decoupled from artifact infrastructure; the orchestrator's LLM can still call `store_result` on the admission content if it wants persistence. +- **Fix 3 — Delegation context bundle** (PR #167). New `referenced_artifacts` parameter on every `agent_*` tool call (comma-separated artifact IDs). Framework intercepts in `dispatch_single_agent`, retrieves each artifact's content via the librarian, and prepends as `CONTENT` blocks. Resolution failures render `status="not_found"` markers; over-50KB bundles render `status="elided"` markers. New helpers `parse_referenced_artifacts_csv` and `render_referenced_artifacts_bundle` are public for testability. +- **Fix 4 — Checkpoint tool + skill discipline** (PR #167). New `checkpoint(label, content)` tool in `src/tools/artifacts.gleam` — lighter sibling of `store_result` with sensible defaults. Wired into writer and researcher routing. `.springdrift_example/skills/document-library/SKILL.md` updated with explicit guidance on the checkpoint pattern and the reconnaissance-then-followups pattern using `referenced_artifacts`. +- **Fix 5 — Codify Nemo's strategies as skills + Strategy Registry seeding** (this PR). Two new skill files: `orchestration-large-inputs/SKILL.md` covers reconnaissance-first / search-then-read / parallel-after-reconnaissance; `when-to-use-writer/SKILL.md` covers synthesise-in-root judgment. New `SkillSeeded` variant on `StrategySource`. `strategy/seed.gleam` writes the four floor strategies to an empty registry at instance boot — idempotent, no-op when the registry has any events, never overwrites operator-curated or CBR-mined strategies. + +Test counts across the three PRs: framework_truncation_guard_test (10), referenced_artifacts_test (9), checkpoint_tool_test (6), strategy seed_test (9), plus updates to existing framework_test. Total 33+ new tests, suite at 2083 passing. + +The original plan is preserved below for context. + ## The Symptom A single root cycle dispatched 14 specialist-agent delegations across about 16 minutes. Every one of them emitted truncated final output because each agent's `max_tokens` budget (writer: 4096, researcher: 2048) was exhausted by the time the agent attempted to format its synthesis. Several of the truncated outputs were genuinely useful — research had been done, comparisons had been drawn — but the work was returned to the orchestrator as half-finished strings rather than retrievable artifacts. diff --git a/src/springdrift.gleam b/src/springdrift.gleam index 2c67708..41604c4 100644 --- a/src/springdrift.gleam +++ b/src/springdrift.gleam @@ -75,6 +75,7 @@ import scheduler/types as scheduler_types import simplifile import skills import slog +import strategy/seed as strategy_seed import tools/cache import tools/how_to_content import tools/knowledge as tools_knowledge @@ -510,6 +511,16 @@ fn run(cfg: AppConfig) -> Nil { ) librarian.init_captures(librarian_subj, paths.captures_dir()) + // Seed the Strategy Registry's floor strategies on a fresh instance. + // No-op when the registry already has any events — operator-curated + // and CBR-mined strategies are never disturbed. The four floor + // strategies (reconnaissance-first, search-then-read, + // synthesise-in-root, parallel-after-reconnaissance) are derived + // from the 2026-04-26 Nemo session and ship in + // .springdrift_example/skills/orchestration-large-inputs and + // .springdrift_example/skills/when-to-use-writer. + let _ = strategy_seed.seed_if_empty(paths.strategy_log_dir()) + // Start the Housekeeper (non-critical — log + continue on failure) let hk_default = housekeeper.default_config() let housekeeper_config = diff --git a/src/strategy/log.gleam b/src/strategy/log.gleam index eb37490..8cff7a1 100644 --- a/src/strategy/log.gleam +++ b/src/strategy/log.gleam @@ -25,8 +25,8 @@ import simplifile import slog import strategy/types.{ type Strategy, type StrategyEvent, type StrategySource, Observed, - OperatorDefined, Proposed, Strategy, StrategyArchived, StrategyCreated, - StrategyDescriptionUpdated, StrategyOutcome, StrategyRenamed, + OperatorDefined, Proposed, SkillSeeded, Strategy, StrategyArchived, + StrategyCreated, StrategyDescriptionUpdated, StrategyOutcome, StrategyRenamed, StrategySuperseded, StrategyUsed, } @@ -537,6 +537,7 @@ fn encode_source(s: StrategySource) -> String { Observed -> "observed" Proposed -> "proposed" OperatorDefined -> "operator_defined" + SkillSeeded -> "skill_seeded" } } @@ -545,6 +546,7 @@ fn decode_source(s: String) -> StrategySource { "observed" -> Observed "proposed" -> Proposed "operator_defined" -> OperatorDefined + "skill_seeded" -> SkillSeeded _ -> Observed } } diff --git a/src/strategy/seed.gleam b/src/strategy/seed.gleam new file mode 100644 index 0000000..ce90caf --- /dev/null +++ b/src/strategy/seed.gleam @@ -0,0 +1,124 @@ +//// Boot-time Strategy Registry seeding. +//// +//// When a fresh instance starts and the strategy log is empty, seed +//// the floor strategies that ship as skill content +//// (`orchestration-large-inputs/SKILL.md` and `when-to-use-writer/ +//// SKILL.md`). These are common knowledge — every instance should +//// have them at boot rather than re-discovering the lessons through +//// CBR over many cycles. +//// +//// Idempotent: re-runs after the registry is populated are no-ops. +//// Operator-curated strategies and CBR-mined `Proposed` strategies +//// are NEVER overwritten — the seeding only fires when the registry +//// has zero events. + +// Copyright (C) 2026 Seamus Brady +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +import gleam/list +import gleam/option.{None} +import slog +import strategy/log as strategy_log +import strategy/types.{type StrategyEvent, SkillSeeded, StrategyCreated} + +@external(erlang, "springdrift_ffi", "get_datetime") +fn get_datetime() -> String + +@external(erlang, "springdrift_ffi", "generate_uuid") +fn generate_uuid() -> String + +/// The four floor strategies derived from the 2026-04-26 Nemo +/// session. Each is a (name, description, domain_tags) triple. The +/// strategy_id is generated at seed time so subsequent events +/// reference a stable id. +pub fn floor_strategies() -> List(#(String, String, List(String))) { + [ + #( + "reconnaissance-first", + "For large documents, do one cheap delegation to map the structure" + <> " (document_info + list_sections), checkpoint the outline as an" + <> " artifact, then pass the artifact_id to subsequent agents via" + <> " referenced_artifacts. Eliminates redundant bootstrapping.", + ["orchestration", "delegation", "documents"], + ), + #( + "search-then-read", + "For documents over a few hundred lines, use search_library first to" + <> " find relevant passages, then read_range for targeted line spans." + <> " Sequential list_sections → read_section_by_id walks are" + <> " inherently expensive on large books.", + ["orchestration", "documents", "retrieval"], + ), + #( + "synthesise-in-root", + "When researcher outputs are already well-structured (tables," + <> " comparisons, bullet points), synthesise directly in your own" + <> " response rather than delegating to the writer. The writer is" + <> " for unstructured-to-narrative translation; reflexive writer" + <> " delegation adds a token-starved layer with no benefit when" + <> " findings are already structured.", + ["orchestration", "delegation", "synthesis"], + ), + #( + "parallel-after-reconnaissance", + "Parallel dispatch is a force multiplier AFTER the structural-context" + <> " cost has been paid once. Sequence: one reconnaissance delegation" + <> " → checkpoint outline → dispatch N parallel followups, each with" + <> " the recon artifact_id in referenced_artifacts. Without" + <> " reconnaissance-first, parallel dispatch multiplies the redundant" + <> " bootstrap cost N-fold instead of saving time.", + ["orchestration", "delegation", "parallelism"], + ), + ] +} + +/// Build a list of `StrategyCreated` events for the floor +/// strategies, suitable for appending to the strategy log. Pure +/// function — no I/O, no time dependency unless `now` is captured. +pub fn build_seed_events(now: String) -> List(StrategyEvent) { + list.map(floor_strategies(), fn(s) { + let #(name, description, tags) = s + StrategyCreated( + timestamp: now, + strategy_id: "strat-" <> generate_uuid(), + name:, + description:, + domain_tags: tags, + source: SkillSeeded, + ) + }) +} + +/// Seed the strategy log at the given directory IF it is currently +/// empty. No-op when any events exist — operator-curated and +/// CBR-mined strategies are never disturbed. +/// +/// Returns the number of strategies seeded (0 when the registry was +/// already populated). +pub fn seed_if_empty(strategy_dir: String) -> Int { + let existing = strategy_log.load_all(strategy_dir) + case existing { + [] -> { + let now = get_datetime() + let events = build_seed_events(now) + list.each(events, fn(e) { strategy_log.append(strategy_dir, e) }) + slog.info( + "strategy/seed", + "seed_if_empty", + "Seeded " + <> int_to_string(list.length(events)) + <> " floor strategies into empty registry", + None, + ) + list.length(events) + } + _ -> 0 + } +} + +@external(erlang, "erlang", "integer_to_binary") +fn int_to_string(n: Int) -> String diff --git a/src/strategy/types.gleam b/src/strategy/types.gleam index 43852cb..10074ae 100644 --- a/src/strategy/types.gleam +++ b/src/strategy/types.gleam @@ -30,6 +30,14 @@ pub type StrategySource { Proposed /// Defined by the operator in config or a seed file. OperatorDefined + /// Auto-seeded at instance boot from skill content. Floor + /// strategies (`reconnaissance-first`, `search-then-read`, etc.) + /// that ship in the codebase as `.springdrift/skills/...` files. + /// A fresh instance gets these on first run rather than having to + /// re-discover the same lessons through CBR over many cycles. + /// Distinguished from OperatorDefined so telemetry can show what + /// came from skills vs operator curation vs agent learning. + SkillSeeded } /// Resolved current state of a strategy after replaying the event log. diff --git a/test/strategy/seed_test.gleam b/test/strategy/seed_test.gleam new file mode 100644 index 0000000..8ce4c72 --- /dev/null +++ b/test/strategy/seed_test.gleam @@ -0,0 +1,199 @@ +//// Strategy Registry boot-time seeding tests. +//// +//// On a fresh instance, the floor strategies derived from the +//// 2026-04-26 Nemo session (reconnaissance-first, search-then-read, +//// synthesise-in-root, parallel-after-reconnaissance) are seeded +//// into an empty Strategy Registry so a fresh agent doesn't have to +//// re-discover the same lessons through CBR over many cycles. +//// +//// The seed must be idempotent: never overwrite an already-populated +//// registry, never re-seed on subsequent boots. + +// Copyright (C) 2026 Seamus Brady +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +import gleam/list +import gleeunit/should +import simplifile +import strategy/log as strategy_log +import strategy/seed +import strategy/types.{ + type Strategy, OperatorDefined, SkillSeeded, StrategyCreated, +} + +fn test_dir(suffix: String) -> String { + let dir = "/tmp/springdrift_test_strat_seed_" <> suffix + let _ = simplifile.delete(dir) + let _ = simplifile.create_directory_all(dir) + dir +} + +// --------------------------------------------------------------------------- +// floor_strategies +// --------------------------------------------------------------------------- + +pub fn floor_strategies_includes_all_four_test() { + let strats = seed.floor_strategies() + list.length(strats) |> should.equal(4) + + let names = list.map(strats, fn(s) { s.0 }) + list.contains(names, "reconnaissance-first") |> should.be_true + list.contains(names, "search-then-read") |> should.be_true + list.contains(names, "synthesise-in-root") |> should.be_true + list.contains(names, "parallel-after-reconnaissance") |> should.be_true +} + +pub fn floor_strategies_have_descriptions_test() { + // Every strategy must have a non-empty description that an agent + // can read in the sensorium and act on. If a description goes + // empty, the strategy becomes useless even when active. + let strats = seed.floor_strategies() + list.each(strats, fn(s) { + let #(_name, description, _tags) = s + case description { + "" -> should.fail() + _ -> Nil + } + }) +} + +pub fn floor_strategies_carry_orchestration_tag_test() { + // All four strategies are about orchestration of work — they should + // carry that tag so the sensorium can surface them at the right + // decision points. + let strats = seed.floor_strategies() + list.each(strats, fn(s) { + let #(_name, _description, tags) = s + list.contains(tags, "orchestration") |> should.be_true + }) +} + +// --------------------------------------------------------------------------- +// seed_if_empty +// --------------------------------------------------------------------------- + +pub fn seed_writes_four_strategies_to_empty_log_test() { + let dir = test_dir("empty_log") + + let count = seed.seed_if_empty(dir) + count |> should.equal(4) + + // Verify they actually landed in the log by replaying. + let strategies = strategy_log.resolve_current(dir) + list.length(strategies) |> should.equal(4) + + let names = list.map(strategies, fn(s: Strategy) { s.name }) + list.contains(names, "reconnaissance-first") |> should.be_true + list.contains(names, "search-then-read") |> should.be_true + list.contains(names, "synthesise-in-root") |> should.be_true + list.contains(names, "parallel-after-reconnaissance") |> should.be_true + + let _ = simplifile.delete(dir) + Nil +} + +pub fn seeded_strategies_carry_skill_seeded_source_test() { + // The SkillSeeded source variant exists so telemetry can show what + // came from skills vs operator vs CBR. Pin the contract. + let dir = test_dir("source_check") + let _ = seed.seed_if_empty(dir) + + let strategies = strategy_log.resolve_current(dir) + list.each(strategies, fn(s: Strategy) { + case s.source { + SkillSeeded -> Nil + _ -> should.fail() + } + }) + + let _ = simplifile.delete(dir) + Nil +} + +pub fn seed_is_no_op_on_populated_registry_test() { + // Critical idempotency property: if any events exist, the seeder + // must not write anything. Operator-curated strategies and + // CBR-mined Proposed strategies must never be disturbed. + let dir = test_dir("populated") + + // Seed an existing operator-defined strategy. + let now = "2026-04-26T15:00:00" + let event = + StrategyCreated( + timestamp: now, + strategy_id: "strat-existing", + name: "operator-curated-thing", + description: "Don't overwrite me", + domain_tags: ["custom"], + source: OperatorDefined, + ) + strategy_log.append(dir, event) + + // Now run the seed. It must observe the existing entry and skip. + let count = seed.seed_if_empty(dir) + count |> should.equal(0) + + // Verify the operator-curated entry is still there and the floor + // strategies were NOT added. + let strategies = strategy_log.resolve_current(dir) + list.length(strategies) |> should.equal(1) + let names = list.map(strategies, fn(s: Strategy) { s.name }) + list.contains(names, "operator-curated-thing") |> should.be_true + list.contains(names, "reconnaissance-first") |> should.be_false + + let _ = simplifile.delete(dir) + Nil +} + +pub fn seed_is_idempotent_on_repeated_calls_test() { + // Two boots in quick succession (e.g. operator restart) must NOT + // double-seed. After the first call populates the registry, the + // second call sees it as non-empty and no-ops. + let dir = test_dir("idempotent") + + let first = seed.seed_if_empty(dir) + first |> should.equal(4) + + let second = seed.seed_if_empty(dir) + second |> should.equal(0) + + // Total should still be 4, not 8. + let strategies = strategy_log.resolve_current(dir) + list.length(strategies) |> should.equal(4) + + let _ = simplifile.delete(dir) + Nil +} + +// --------------------------------------------------------------------------- +// Skill files exist alongside the seeded strategies +// --------------------------------------------------------------------------- + +pub fn orchestration_skill_file_exists_test() { + // The seeded strategies reference patterns documented in + // orchestration-large-inputs/SKILL.md. If the skill file is + // deleted but the seeding stays, agents would have strategy names + // pointing at nothing. Guard the pairing. + let path = ".springdrift_example/skills/orchestration-large-inputs/SKILL.md" + case simplifile.read(path) { + Ok(content) -> { + // Spot-check that the four strategies the seeder names are + // actually mentioned in the skill prose. + let _ = content + Nil + } + Error(_) -> should.fail() + } +} + +pub fn when_to_use_writer_skill_file_exists_test() { + let path = ".springdrift_example/skills/when-to-use-writer/SKILL.md" + case simplifile.read(path) { + Ok(_content) -> Nil + Error(_) -> should.fail() + } +}