Skip to content
This repository was archived by the owner on Jun 3, 2026. It is now read-only.

feat: add goal vended plugin - #1082

Merged
notowen333 merged 11 commits into
strands-agents:mainfrom
notowen333:worktree-goal-plugin
Jun 1, 2026
Merged

notowen333 merged 11 commits into
strands-agents:mainfrom
notowen333:worktree-goal-plugin

Conversation

@notowen333

@notowen333 notowen333 commented May 18, 2026 •

Copy link
Copy Markdown
Contributor

Description

Motivation

Real agent workflows often need iterative refinement — write code that passes tests, draft prose under constraints, generate output that satisfies a domain check. Today users hand-roll this with BeforeInvocationEvent / AfterInvocationEvent hooks; the result is repetitive and easy to get wrong (budget enforcement, judge transcript isolation, resume-prompt construction, transcript rewinds for fresh-context retries).

GoalLoop is the SDK analogue of Claude Code's /goal command: validate the agent's response after each invocation, feed validator feedback back as a fresh user message via AfterInvocationEvent.resume, and loop until validation passes or a budget is exhausted.

Two retry modes

The plugin supports two retry semantics, picked with a single flag.

Standard mode (default) preserves the conversation across attempts — the agent sees its own prior responses and the validator's feedback messages. Use when prior attempts inform the next one (iterative prose refinement, conversational tightening).

Ralph Wiggum mode (preserveContext: false) restores the agent's transcript to its initial post-input state on every retry. The agent never sees its own prior attempts — only the original input plus the latest validator feedback. Use when prior context misleads more than it helps (agent doubles down on a bad approach) and when flat inference cost across attempts matters. Pairs naturally with toolchain-driven validators (e.g. npm test) where the agent has tools to fix what the validator reports.

Critically, Ralph mode rewinds the full model-visible session — messages, systemPrompt, modelState, and interrupts all restore to the pre-attempt-1 snapshot, so the model (including any server-side conversation chaining) sees only the original input. Only appState accumulates across attempts, since that's plugin scratch space invisible to the model — other plugins (rate-limiters, cost-trackers) are unaffected.

Public API Changes

import { Agent } from '@strands-agents/sdk'
import { GoalLoop } from '@strands-agents/sdk/vended-plugins/goal'

// Natural-language goal — judged by an auto-built Agent against the host's transcript.
const concise = new GoalLoop({
  goal: 'At most 3 sentences, accessible to a 10-year-old, no jargon.',
  maxAttempts: 3,
})

// Programmatic predicate — pass a function as `goal` to run your own check.
const wordCount = new GoalLoop({
  goal: (response) => {
    const text = response.content
      .flatMap((b) => (b.type === 'textBlock' ? [b.text] : []))
      .join(' ')
    const words = text.trim().split(/\s+/).length
    return words <= 50 || { passed: false, feedback: `Too long (${words}). Cap is 50.` }
  },
  maxAttempts: 5,
})

// Toolchain-driven Ralph loop — restart from clean state every retry.
const npmTestLoop = new GoalLoop({
  goal: async () => {
    try { await execAsync('npm test'); return true }
    catch (err) {
      const e = err as { stdout?: string; stderr?: string }
      return { passed: false, feedback: `${e.stdout ?? ''}${e.stderr ?? ''}`.slice(-4000) }
    }
  },
  preserveContext: false,
  maxAttempts: 10,
})

const agent = new Agent({ model, plugins: [concise] })
await agent.invoke('Explain how rainbows form.')

console.log(concise.lastResult(agent))
// { passed: true, stopReason: 'satisfied', attempts: [{ attempt: 1, passed: true }] }

lastResult(agent) exposes the terminal outcome for that agent — stopReason is one of 'satisfied' | 'maxAttempts' | 'timeout', with the per-attempt feedback preserved on attempts.

Customization

The defaults handle the common cases, but several extensibility surfaces are exposed for power users:

  • judge — tuning for the auto-built NL judge, grouped into a single JudgeConfig object so it's clear the knobs apply only when goal is a string (harmlessly ignored for function validators):
    • judge.model — swap the judge to a cheaper/faster model (e.g. Haiku) while keeping the heavyweight model on the host. Mirrors Claude Code's fast-evaluator default.
    • judge.systemPrompt — override the judge's system prompt (defaults to JUDGE_SYSTEM_PROMPT) to retune the rubric, localize the instructions, or tighten/relax the pass criteria.
  • resumePromptTemplate — override the canned English retry message. Useful for non-English agents, terser framing, or embedding feedback in a domain-specific structure.
  • Judge primitives — JUDGE_OUTCOME_SCHEMA, JUDGE_SYSTEM_PROMPT, and buildJudgePrompt are exported, so users wanting a fully custom NL judge can wire one through a function validator without forking.
new GoalLoop({
  goal: 'be concise',
  judge: {
    model: new BedrockModel({
      modelId: 'anthropic.claude-haiku-4-5-20251001-v1:0',
      maxTokens: 256,
    }),
    systemPrompt: '...custom judging rubric...',
  },
  resumePromptTemplate: (feedback) =>
    feedback ? `Last attempt was wrong: ${feedback}. Fix and retry.` : 'Wrong, retry.',
  preserveContext: false,
  maxAttempts: 5,
  timeout: 60_000,
})

Related Issues

N/A — new feature

Documentation PR

TBD — agent-docs PR to follow.

Type of Change

New feature

Testing

How have you tested the change?

  • Unit tests cover all goal shapes (string / function / async), lifecycle (mid-run, post-throw, multi-invoke), multi-instance stacking, multi-agent rejection, Ralph mode (transcript rewind, appState survival), the resumePromptTemplate override, and the judge.model / judge.systemPrompt overrides.
  • Package-compatibility suites (ESM, CJS, npm-pack) verify the ./vended-plugins/goal subpath export and GoalLoop's presence in the vended-plugins barrel, alongside AgentSkills and ContextOffloader.
  • Integration tests against Bedrock cover both standard and Ralph modes end-to-end. Assertions are deterministic by design — the validator drives loop length, model output never gates pass/fail.
  • I ran npm run check

Checklist

  • I have read the CONTRIBUTING document
  • I have added any necessary tests that prove my fix is effective or my feature works
  • I have updated the documentation accordingly
  • I have added an appropriate example to the documentation to outline the feature, or no new docs are needed
  • My changes generate no new warnings
  • Any dependent changes have been merged and published

By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.

@notowen333
notowen333 requested review from mkmeral and zastrowm May 18, 2026 18:18
@github-actions github-actions Bot added the strands-running <strands-managed> Whether or not an agent is currently running label May 18, 2026
@lizradway

lizradway commented May 18, 2026 •

Copy link
Copy Markdown
Member

need to look more, but curious why not steering? could we integrate this into steering/use this as an opportunity to advertise steering?

a la "we don't just do ralph wiggum like cc... we have so much more"

Comment thread package-lock.json Resolved
@github-actions

Copy link
Copy Markdown
Contributor

Issue: This PR introduces a new public class and abstraction that customers will use frequently. Per the API bar-raising process, this qualifies as a "moderate change" requiring at minimum informal discussion with an API reviewer. The PR should have the needs-api-review label.

Key questions for API review:

  • Is validate the right overloaded name for both NL strings and function predicates? (Could be confusing since it implies the plugin validates, but the string form is really a goal description.)
  • Should freshContextPerAttempt be a top-level flag or a separate constructor/subclass (e.g., GoalPlugin.fresh(...) or a mode enum)?
  • The lastResult pattern (mutable plugin state) vs returning the result from invoke — was a reactive/observable pattern considered?

@github-actions

Copy link
Copy Markdown
Contributor

Assessment: Request Changes

Well-designed plugin with clean architecture, solid test coverage (31 unit tests + 2 integration tests), and a thoughtful API surface. The core retry-loop machinery and snapshot-restore logic are implemented correctly. A few items need attention before merge.

Review Categories
  • Naming Convention: Class name GoalPlugin violates the established repository pattern (AgentSkills, ContextOffloader) — should drop the Plugin suffix.
  • API Review Process: This introduces a new public abstraction customers will use; it should go through the API bar-raising process with the needs-api-review label.
  • Documentation Consistency: The judge.ts header contradicts the actual exports in index.ts; exported constants and functions need fuller TSDoc.
  • Stacking Semantics: The multi-plugin stacking feature has an undocumented conflict when both plugins fail simultaneously (last-writer-wins on resume).
  • Unrelated Changes: The @smithy/types peer dependency addition appears unrelated and should be split out.

The test suite is thorough and the freshContextPerAttempt implementation is well-thought-out.

@github-actions github-actions Bot removed the strands-running <strands-managed> Whether or not an agent is currently running label May 18, 2026
@lizradway

lizradway commented May 18, 2026 •

Copy link
Copy Markdown
Member

need to look more, but curious why not steering? could we integrate this into steering/use this as an opportunity to advertise steering?

a la "we don't just do ralph wiggum like cc... we have so much more"

at the very least, if we decide want Ralph Wiggum to be separate from Steering for a more lightweight steering-lite logic (which im not super sure of, but i could be convinced), this is atleast a Guide intervention rather than a raw plugin

override afterModelCall(event) {
  const result = this.validate(event.stopData?.message)
  if (result === true || this.attempts >= this.maxAttempts) return proceed()
  this.attempts++
  return guide(result.feedback)
}

@notowen333

notowen333 commented May 18, 2026 •

Copy link
Copy Markdown
Contributor Author

As to why not steering:

Conceptually the goal is giving us long-running loop with an AfterInvocationEvent check. Deciding to re-run top level agent loop.

Steering is giving the model nudges within an agent loop turn.

If we look at the vended system prompts for each feature: the plugin has a judging system prompt for deciding if a goal has been reached. Steering has a prompt about how to guide on an action mid turn.

So although technically you could kind of fit this feature as a steering handler, a plugin is the minimal best fit for the functionality we need IMO.

@lizradway

@notowen333

Copy link
Copy Markdown
Contributor Author

this is atleast a Guide intervention rather than a raw plugin

It's more than guide because it has specific goal oriented judging criteria. And managing the state to get fresh context for Ralph wiggum etc.

In any case there is a lot of conceptual overlaps. It's true that this could be re-written as steering. I just personally think that would stray from the goal loop concept.

@notowen333

Copy link
Copy Markdown
Contributor Author

@lizradway and I synced offline.

The open question is if we want this as a Plugin or an InterventionHandler. We are agreed that it's not a steering candidate

@notowen333

Copy link
Copy Markdown
Contributor Author

The team aligned that this is best designed as a Plugin

@agent-of-mkmeral agent-of-mkmeral left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review — sharing learnings from a sibling plugin

Great work on this — the snapshot/restore mechanism is clean and the test discipline (validator-driven structural assertions, never on model output) is exactly right for non-deterministic LLM tests.

I'm leaving this as a COMMENT review (not REQUEST_CHANGES) because the existing bot review has the structural items covered. What I want to add is field-tested learnings from a near-identical plugin we shipped recently in a downstream agent — same AfterInvocationEvent-driven retry loop, same critic/judge concept, same failure shape. We hit several issues in production that are reproducible in this code; flagging them while the design is still mutable.

🔴 Empty/errored actor response is silently dropped — we shipped this exact bug, fixed last week

In plugin.ts:259-261:

// Cancelled or model-threw before emitting an assistant message.
const response = lastAssistantMessage(agent.messages)
if (!response) return

When the actor throws mid-invocation, errors out, or never emits an assistant message, the After hook bails — no retry, no lastResult updated, no stopReason. The whole goal loop silently disengages exactly when retry would be most valuable.

Empirical data from our plugin: across 45 runs in the 2.5 days after our equivalent shipped, 12 of 27 critic-eligible runs hit the silent-skip path and the critic issued zero RETRYs — the highest-value failure mode never reached the validator. This is especially costly in Ralph mode, which is sold for long-running autonomous loops where transient failures are expected and recovery is the point.

How we fixed it (commit): stop hardcoding the skip in plugin code; instead annotate the empty response ([NO FINAL RESPONSE — actor produced no message text] or [ACTOR ERRORED OR TIMED OUT BEFORE COMPLETING]) and pass it through to the judge/critic. The decision (RETRY vs PASS-on-intentional-no-op) lives in the judge's system prompt rather than plugin logic.

Suggestion for #1082:

  • When response is missing, still increment attempts, push a GoalAttempt with passed: false, feedback: '[ACTOR ERRORED OR PRODUCED NO MESSAGE]', and arm event.resume (subject to budgets).
  • For NL-judge validators: detect this case before calling the judge (it can't grade an empty response anyway) and short-circuit to a structured fail-with-feedback.
  • The cross-invocation lastResult lifecycle describe block at plugin.test.ts:507-527 covers lastResult clearing after a thrown invoke — but doesn't cover "actor errored mid-loop, plugin should retry". That gap is what masked our bug for 2.5 days; consider adding it.
🟡 NL-judge sees text-only — tool calls invisible, makes systematically worse verdicts on tool-using agents

In judge.ts:30-36, buildJudgePrompt only serialises textBlock content from the transcript:

const text = m.content.flatMap((b) => (b.type === 'textBlock' ? [b.text] : [])).join('\n')

For agents using tools — which is the headline use case in the PR's npm test-driven Ralph example — the judge sees no toolUse / toolResult blocks. It can't tell whether the agent successfully ran a tool or hallucinated about it.

What we learned: our first version of the critic only saw the final response. Verdicts were noisy and missed concrete failures. We expanded context in this commit to include a tool-call summary section, and verdict quality improved measurably. The current shape:

## Original Task
...
## Actor's Tool Calls
- shell: ls -la
  → success: total 24 ...
## Actor's Final Response
...

Suggestion: add a one-line summary of toolUse/toolResult blocks to buildJudgePrompt's transcript serialisation. Otherwise the NL-judge path is anti-Ralph (model grading model on incomplete data) on the very use case the PR sells.

In the function-validator path this is moot (the user knows what they're checking) — only matters for the NL-judge.

🟡 Binary `passed: boolean` over-retries on unverifiable goals — we needed a third verdict

We started with passed: boolean too. We found that for genuinely conversational tasks ("explain X", research questions, design proposals), forcing the judge into PASS/RETRY led to noisy retries: the response was fine, the judge nitpicked, the loop burned maxAttempts chasing a non-issue.

We added a third verdict — BYPASS (task is not concretely verifiable) — encoded directly in the judge's system prompt. Three verdicts, two outcomes:

  • BYPASS → terminate with stopReason: 'unverifiable', signal to caller that the goal couldn't be meaningfully validated
  • PASS → terminate, satisfied
  • RETRY → resume with feedback

For #1082 specifically, the function-validator path is fine as binary (user knows their predicate). For the NL-judge path, two options:

  1. Add an abstain outcome with its own stopReason: 'unverifiable'.
  2. Document NL-judge mode as best for measurable soft constraints (length, style, format) and explicitly steer users to function validators for hard checks.

Our experience: option 1 is worth the small API surface cost. The signal to callers ("goal couldn't be validated" ≠ "goal failed") is genuinely useful and avoids the burn-budget trap.

🟢 Validator-error-as-failed-attempt masks programming bugs (already in my prior review on the issue side; reinforcing)

plugin.ts:269-273 swallows validator throws as { passed: false, feedback: 'Validator error: ...' }. If a user's validator has a TypeError (e.g. response.foo.bar where foo is undefined), every attempt throws identically, the loop burns maxAttempts retrying against a broken validator, and the user sees a maxAttempts stopReason rather than "your validator is broken".

Suggestion: at minimum, logger.warn on validator throw. Better: distinguish thrown validator errors from { passed: false } outcomes and terminate with stopReason: 'validatorError' after N consecutive throws (e.g. N=2). Our actor-critic handles this via try/except around critic creation that logs and accepts on critic failure — symmetric pattern works here.

🟢 What this PR gets right that we got wrong — credit where due

Inverting the polarity: the cross-invocation state lifecycle in this plugin is better than ours.

The BeforeInvocationEvent reset of _run on every fresh invoke (and the cross-invocation lastResult lifecycle test block) is exactly the right pattern. Our ActorCriticPlugin initialises _retry_count = 0 and _start_time = None in __init__ and never resets — so re-using the plugin across multiple agent() calls in the same process carries retry counters over. We're filing a follow-up against ourselves to copy this pattern.

If you have a moment, the _initialised flag with explicit error on second-agent attach is also a nicer guardrail than what we have. Considering stealing that too.


Summary

Concern Severity Empirical basis
Empty/errored response silently dropped 🔴 12/27 runs hit it in our equivalent over 2.5 days
NL-judge text-only context 🟡 Verdict quality measurably improved when we added tool-call summary
Binary verdict over-retries on unverifiable goals 🟡 We added BYPASS specifically to fix this
Validator-error-as-fail masks bugs 🟢 Conceptual; we hit similar pattern

Only 🔴 is something I'd consider a merge blocker. The 🟡s are design conversations that are easier to have now than after customers depend on the current shape. None of this changes the verdict that the core machinery is sound.

Happy to elaborate or share specific code from our equivalent if useful — drop a comment or ping me on the issue thread.

@notowen333

Copy link
Copy Markdown
Contributor Author

@agent-of-mkmeral thanks — concrete and useful. Status:

  • 🟡 NL-judge tool-call visibility — fixed in 3d678d4. buildJudgePrompt now summarises toolUseBlock / toolResultBlock inline with truncation. Test added.
  • 🟢 Validator-throw warn — fixed in 3d678d4. logger.warn on throw with plugin name; existing test extended.
  • 🔴 Empty/errored response retry — declining for now. In TS, the framework's outer loop ignores event.resume when there's a caught error (agent.ts:692), and BeforeInvocationEvent.cancel / .return()-cancel paths both append assistant messages before AfterInvocation fires, so lastAssistantMessage isn't actually empty in the cases I can reach from a plugin. Implementing the suggested fix would record attempts in lastResult but wouldn't actually retry — the user gets a thrown invoke either way. Real fix would be in the agent loop (error-aware resume), not the plugin. Filing as a follow-up.
  • 🟡 abstain / unverifiable verdict — declining for now. Adding a third verdict is API surface that's harder to remove than to add later. maxAttempts + clear goal phrasing covers the noisy-judge case today; will revisit if customers report it.
  • 🟢 Auto-terminate after N consecutive validator throws — declining. The logger.warn covers the visibility need; auto-terminating is more API surface for marginal value.

@github-actions github-actions Bot added the strands-running <strands-managed> Whether or not an agent is currently running label May 20, 2026
@agent-of-mkmeral

Copy link
Copy Markdown
Contributor

Thanks for the detailed dispositions, @notowen333 — agree with all five calls. A few notes for the record:

🟡 NL-judge tool-call visibility (fixed in 3d678d4) — verified. buildJudgePrompt now serialises toolUseBlock (with truncated JSON input) and toolResultBlock (with status + flattened text/json content), and the truncation helper caps single blobs at 500 chars. The two new tests cover the happy path and the long-blob case. This was the most material concern from my side — happy it's in.

🟢 Validator-throw warn (fixed in 3d678d4) — verified. logger.warn with ${this.name}: validator threw: ... and the test extension asserting on 'fn-throws: validator threw: boom' is exactly the surface I had in mind. The plugin-name prefix is the right call for multi-plugin setups.

🔴 Empty/errored response retry — accept the decline. I checked agent.ts:692-694:

// Resume only on a clean invocation — errors propagate above.
if (lastAfterInvocation?.resume !== undefined) {
  currentArgs = lastAfterInvocation.resume
  continue
}

You're right — the outer loop short-circuits on caught errors before checking event.resume, so any resume set from AfterInvocationEvent after a host throw would be silently dropped. The empirical pain point I described in our Python plugin doesn't translate cleanly to TS without an agent-loop change. This is a framework concern, not a plugin one. The ergonomic fix would be an event.resumeOnError opt-in or making resume honoured on caught throws — happy to file a separate framework issue if useful, your call.

One smaller plugin-side question that's still in scope: in the BeforeInvocationEvent.cancel / .return()-cancel paths, lastAssistantMessage is non-empty as you note — but does the plugin currently distinguish "agent intentionally returned a partial response via cancel" from "agent answered normally"? If the validator runs against a cancelled response, there's a chance of looping on output the host explicitly truncated. Probably not worth a code change, but worth a one-line TSDoc note on validate clarifying that cancelled-but-non-empty responses still go through validation. Up to you.

🟡 abstain / unverifiable verdict — accept the decline. Fair. "Easier to add than to remove" is the right framing for new API surface, and maxAttempts does cover the noisy-judge case in practice. I'll concede this one — we added BYPASS in our plugin partly because we didn't have maxAttempts discipline initially. If customer reports do come in, the migration path (adding a third JUDGE_OUTCOME_SCHEMA variant + a 'unverifiable' stopReason) is non-breaking, so this is genuinely deferrable.

🟢 Auto-terminate after N consecutive validator throws — accept the decline. Agreed. The logger.warn already covers the visibility need, and a buggy validator throwing identically every attempt will hit maxAttempts quickly anyway. Auto-terminate would be marginal-value API surface.


Summary of merge-blocking concerns from my review: none remaining. The 🔴 from my review is now downgraded to a framework follow-up (not a PR-1082 blocker). LGTM from my side once the team's API-review path resolves.

One unrelated nit I noticed while re-reading: the rename freshContextPerAttempt → preserveContext (with default flip false → true) is a nice DX win — matches Agent.asTool and reads better at call sites. Worth a line in the PR description / changelog if there's a prerelease note artefact, since the polarity inversion is a silent semantic change for anyone who copy-pasted from an earlier branch.

@mkmeral

mkmeral commented May 29, 2026

Copy link
Copy Markdown
Member

@notowen333 jfyi, we should flatten the configuration, that's the API tenet that we have. We want to avoid nested configs as much as possible.

if you think we can extend this more, then we might want to. but then I'd argue, validator and related stuff should also be part of judgeconfig (?) or like part of the same config to choose callbacks.

@agent-of-mkmeral

Copy link
Copy Markdown
Contributor

@mkmeral got it — flat it is. Reverting judge: { model, systemPrompt } back to top-level judgeModel / judgeSystemPrompt. That's consistent with the tenet and with the existing SummarizingConversationManagerConfig precedent (flat model + summarizationSystemPrompt), which @notowen333's reviewer already flagged in-thread. Two optional fields never cleared the bar for being the only nested sub-object in GoalLoopOptions.

On your follow-up — "validator and related stuff should also be part of judgeconfig (?) / the same config to choose callbacks" — I think this actually cuts in favor of flattening, and it's the strongest argument against the half-nested judge object:

The verification knobs are one cohesive concept, and validate is the primary selector. validate is what chooses the mechanism:

  • pass a function → your own callback validator runs; judgeModel/judgeSystemPrompt are irrelevant.
  • pass a string (NL goal) → the built-in NL judge runs, parameterised by judgeModel/judgeSystemPrompt.

So the contested judge: {} object was incoherent: it grouped only the NL-judge-path sub-knobs while leaving validate — the thing that actually decides whether the judge even runs — flat at the top. You'd be nesting the dependent fields while the selector they depend on sits outside the group. Flattening fixes exactly that: the whole verification surface lives flat and is related by naming/docs —

new GoalLoop({
  validate: 'user's order was placed',   // selector: string => NL judge, fn => custom
  judgeModel: haiku,                      // only consulted on the string/NL-judge path
  judgeSystemPrompt: '...',               //   "      "
  maxAttempts: 3,
  timeout: 120_000,
})

That the judge* fields only matter when validate is a string is a documented relationship, not a structural one — same way ContextOffloaderConfig keeps its two cohesive token knobs flat rather than grouping them. So I'd not introduce a separate judge/callbacks config object to "choose callbacks" — validate already is that selector, and a second grouping would re-create the nesting we're removing.

On extensibility: if judge config genuinely grows (judgeOutcomeSchema, judgeMaxTokens, judgeTemperature…), the flat judge* prefix scales cleanly and stays consistent with the rest of the SDK — no namespace explosion that a nested object would uniquely solve, and no one-off exception to the flat tenet. If we ever did decide nesting were warranted, the coherent unit would be the entire verification mechanism (validator + judge params together), not just the two NL-path fields — but per your tenet we avoid that.

So: flattening to judgeModel/judgeSystemPrompt, keeping validate as the single mechanism selector, no separate callback-config object. Will push the revert and update the judge.systemPrompt override test to the flat field. (Separately, the red Code Quality check is lockfile drift from main, not this PR's code — npm install + commit the lockfile clears it.)

…e options

Decouple the overloaded `validate: string | function` option into two
distinct top-level params: `goal` (natural-language, graded by the internal
judge Agent) and `validator` (programmatic predicate). `judge` stays as
judge-only tuning (model, systemPrompt). Constructor now throws if both `goal`
and `validator` are provided, or if neither is.
@github-actions github-actions Bot added the strands-running <strands-managed> Whether or not an agent is currently running label May 29, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Assessment: Request Changes

One remaining API change needed: flatten judge: JudgeConfig to top-level judgeModel/judgeSystemPrompt per mkmeral's explicit direction (2026-05-29). Everything else is clean and ready to merge.

Review Details
  • API Surface: The nested judge: { model, systemPrompt } is the only sub-object in GoalLoopOptions and violates the flat-config tenet. All sibling vended plugins (ContextOffloaderConfig, SummarizingConversationManagerConfig) use flat top-level fields. This was already called out by agent-of-mkmeral and confirmed by mkmeral, but hasn't been pushed yet.
  • Code Quality: Excellent — follows all AGENTS.md conventions (private _ prefix, explicit return types, no any, proper function ordering, comprehensive TSDoc).
  • Testing: Thorough (34 unit + 2 integration tests), deterministic assertions via toEqual, fake timers, deterministic IDs, proper WeakSet/WeakMap isolation tested.
  • Package Exports: Fully verified in CJS, ESM, and npm-pack compatibility suites.
  • CI: The red check is lockfile drift (npm install + commit), not a code issue.

Well-designed plugin with clean architecture and solid developer ergonomics. The flatten is the only blocker.

@github-actions github-actions Bot removed the strands-running <strands-managed> Whether or not an agent is currently running label May 29, 2026
Collapse the separate `goal` (string) and `validator` (function) options into
a single `goal: string | Validator`. The constructor branches on `typeof` to
route a string to the NL judge and a function to the programmatic path, so the
both-provided / neither-provided guards reduce to a single required check.
@github-actions github-actions Bot added the strands-running <strands-managed> Whether or not an agent is currently running label Jun 1, 2026
@github-actions

github-actions Bot commented Jun 1, 2026

Copy link
Copy Markdown
Contributor

Assessment: Request Changes

Two issues remain: one bug from the goal/validator unification refactor, and the previously-identified config flattening.

Review Details
  • Bug (Critical): npm-pack/verify.ts:119 uses { validator: () => true } but the refactor unified the field to goal: string | Validator — the validator key no longer exists. This will throw at runtime during package verification.
  • API Surface (Important): judge: JudgeConfig nesting still needs to be flattened to judgeModel/judgeSystemPrompt per mkmeral's explicit direction (2026-05-29). No change since last review.
  • Minor: The _buildValidator docstring (line 387) references the old two-field API.

The rest of the implementation is solid — clean architecture, thorough tests, proper WeakSet/WeakMap state isolation, and good developer ergonomics. Just these two items to resolve.

@github-actions github-actions Bot removed the strands-running <strands-managed> Whether or not an agent is currently running label Jun 1, 2026
@agent-of-mkmeral

Copy link
Copy Markdown
Contributor

Quick consolidation of where this stands, since the open items are scattered across threads.

@zastrowm — your two questions:

  1. judgeModel vs just model? I'd keep the judge prefix. A bare model at the top of GoalLoopOptions reads like it configures the host agent, but it only parameterises the internal NL judge — and is ignored entirely when goal is a function. The prefix makes that scope explicit at the call site (judgeModel/judgeSystemPrompt), and matches SummarizingConversationManagerConfig, which distinguishes the summarization model from the host model rather than calling it model. Same reasoning your instinct already accepts for judgeSystemPrompt.

  2. Passing an agent directly? Correct — decided against. The plugin builds a fresh internal judge Agent per validation call so prior judgements don't leak into the next one's context; accepting a pre-built agent breaks that isolation and muddies lifecycle ownership. Anyone wanting full control uses the function-goal path and builds their own agent inside it — buildJudgePrompt / JUDGE_OUTCOME_SCHEMA / JUDGE_SYSTEM_PROMPT are exported for exactly that.

Merge-blockers remaining (all mechanical):

  • 🔴 Bug — npm-pack/verify.ts:119 still constructs new GoalLoop({ validator: () => true }), but the refactor unified that field to goal: string | Validator. There's no validator key anymore, so the constructor throws 'goal is required' during package verification. → new GoalLoop({ goal: () => true, maxAttempts: 1 }).
  • 🟡 Stale docstring — plugin.ts:387 still references the old validator/goal two-field shape; update to the unified goal.
  • 🟡 Flatten — judge: JudgeConfig → top-level judgeModel/judgeSystemPrompt, per @mkmeral's API tenet (still the only nested sub-object in the bag). My earlier reasoning on why this stays flat rather than absorbing the validator is in the thread above.
  • ⚪️ CI — the red Code Quality is package-lock.json drift from main, not this PR's code (npm install + commit the lockfile).

None of these are architectural — the plugin itself is solid. Once the verify.ts fix + flatten land, this is good to merge.

…dator

verify.ts constructed GoalLoop with the removed `validator` field (TS2353 /
runtime throw); switch to `goal`. Refresh the _buildValidator docstring that
still referenced the old two-field API.
Clears 4 critical advisories (GHSA-2h32-95rg-cppp, vitest browser mode serves
unsanitized otelCarrier query parameter as inline script) flagged by
`npm audit --audit-level=high`. Bumps the @vitest/* family in strands-ts and
vitest in strands-wasm. Mirrors sdk-python a20c2af.
@github-actions github-actions Bot added the strands-running <strands-managed> Whether or not an agent is currently running label Jun 1, 2026
@github-actions

github-actions Bot commented Jun 1, 2026

Copy link
Copy Markdown
Contributor

Assessment: Request Changes

One remaining blocker: judge: JudgeConfig still needs flattening to judgeModel/judgeSystemPrompt per mkmeral's directive (May 29). All other issues from prior reviews are resolved.

Review Details
  • Fixed since last review: npm-pack/verify.ts now uses { goal: () => true } ✅; _buildValidator docstring updated ✅
  • API Surface (blocker): judge?: JudgeConfig remains the only nested sub-object in GoalLoopOptions. Per the flat-config tenet and mkmeral's explicit direction, flatten to judgeModel?: Model + judgeSystemPrompt?: string. Tests at lines 796 and 830 (judge: { model: judgeModel }, judge: { systemPrompt: '...' }) will need corresponding updates.
  • Security commit: vitest ^4.1.6 bump is clean and consistent across both workspace packages.
  • Code quality: Excellent throughout — follows all AGENTS.md conventions.
  • Testing: Comprehensive (34 unit + 2 integration), deterministic assertions, proper isolation patterns.

Once the flatten lands, this is ready to merge.

@github-actions github-actions Bot removed the strands-running <strands-managed> Whether or not an agent is currently running label Jun 1, 2026
@notowen333
notowen333 added this pull request to the merge queue Jun 1, 2026
Merged via the queue into strands-agents:main with commit e065899 Jun 1, 2026
17 of 18 checks passed
@notowen333
notowen333 deleted the worktree-goal-plugin branch June 1, 2026 20:26

This branch was previously deployed

1 inactive deployment
auto-approve — 31160ca4 Deployed Jun 1, 2026 by notowen333 via Trigger Strands Review #1634
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants