Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
107 changes: 107 additions & 0 deletions .springdrift_example/skills/orchestration-large-inputs/SKILL.md
Original file line number Diff line number Diff line change
@@ -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-<doc_id>", 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 `<reference_artifact>` 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.
77 changes: 77 additions & 0 deletions .springdrift_example/skills/when-to-use-writer/SKILL.md
Original file line number Diff line number Diff line change
@@ -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.
Original file line number Diff line number Diff line change
@@ -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:<agent>]` 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 `<reference_artifact id="...">CONTENT</reference_artifact>` 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.
Expand Down
11 changes: 11 additions & 0 deletions src/springdrift.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 =
Expand Down
6 changes: 4 additions & 2 deletions src/strategy/log.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -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,
}

Expand Down Expand Up @@ -537,6 +537,7 @@ fn encode_source(s: StrategySource) -> String {
Observed -> "observed"
Proposed -> "proposed"
OperatorDefined -> "operator_defined"
SkillSeeded -> "skill_seeded"
}
}

Expand All @@ -545,6 +546,7 @@ fn decode_source(s: String) -> StrategySource {
"observed" -> Observed
"proposed" -> Proposed
"operator_defined" -> OperatorDefined
"skill_seeded" -> SkillSeeded
_ -> Observed
}
}
Expand Down
124 changes: 124 additions & 0 deletions src/strategy/seed.gleam
Original file line number Diff line number Diff line change
@@ -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 <seamus@corvideon.ie>
//
// 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
Loading
Loading