Skip to content

feat(agents): add proactive lifecycle hooks to base Agent (#1484) - #1797

Closed
zycaskevin wants to merge 4 commits into
amd:mainfrom
zycaskevin:feat/proactive-lifecycle-hooks
Closed

zycaskevin wants to merge 4 commits into
amd:mainfrom
zycaskevin:feat/proactive-lifecycle-hooks

Conversation

@zycaskevin

Copy link
Copy Markdown

feat(agents): add proactive lifecycle hooks to base Agent (#1484)

Every Hub agent needs a proactive contract (on_first_run/on_heartbeat) — but the base Agent was purely reactive. This PR adds the lifecycle hooks, a unified Proposal schema, and GoalStore.propose() integration so every agent gets first-run discovery and heartbeat propose-with-approval for free.

Before: on_first_run/on_heartbeat/propose don't exist. process_query() duplicated _agent_context binding inline. No mechanism for agents to surface proposals for user approval.

After: Base Agent defines default no-op hooks (backwards-compatible). propose() persists proposals to GoalStore with risk-tier auto-approval (low=risk→queued, medium/high→pending_approval). Shared _agent_identity_context() factors out the grant-binding so both process_query and future heartbeat code reuse the same contextvar path.

Test plan

  • pytest tests/unit/test_goal_store.py::TestPropose -v — 5 propose tests
  • pytest tests/unit/test_proactive_hooks.py -v — 12 hook/propose/regression tests
  • pytest tests/unit/test_goal_store.py -v — all 45 tests still pass
  • pytest tests/test_sdk.py::TestAgentBaseClass -v — unchanged (pre-existing break in test_agent_process_query_interface not caused by this change)

Related

Every Hub agent needs a proactive contract (`on_first_run`/`on_heartbeat`) — but the base `Agent` was purely reactive. This PR adds the lifecycle hooks, a unified `Proposal` schema, and `GoalStore.propose()` integration so every agent gets first-run discovery and heartbeat propose-with-approval for free.

**Before:** `on_first_run`/`on_heartbeat`/`propose` don't exist. `process_query()` duplicated `_agent_context` binding inline. No mechanism for agents to surface proposals for user approval.

**After:** Base `Agent` defines default no-op hooks (backwards-compatible). `propose()` persists proposals to `GoalStore` with risk-tier auto-approval (low=risk→queued, medium/high→pending_approval). Shared `_agent_identity_context()` factors out the grant-binding so both `process_query` and future heartbeat code reuse the same contextvar path.

### Test plan
- `pytest tests/unit/test_goal_store.py::TestPropose -v` — 5 propose tests
- `pytest tests/unit/test_proactive_hooks.py -v` — 12 hook/propose/regression tests
- `pytest tests/unit/test_goal_store.py -v` — all 45 tests still pass
- `pytest tests/test_sdk.py::TestAgentBaseClass -v` — unchanged (pre-existing break in test_agent_process_query_interface not caused by this change)

### Related
- Unblocks amd#1508 (proactive agents eval harness)
- Depends on amd#1484 D4 decisions: unified Proposal schema, GoalStore for pending_approval, shared `_agent_context` binding
@github-actions github-actions Bot added tests Test changes agents labels Jun 21, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Review: proactive lifecycle hooks for base Agent (#1484)

Solid, backwards-compatible scaffolding — the no-op default hooks, the risk-tier auto-approval, and the behavior-preserving identity refactor are all done well. One change is blocking: Agent.propose() swallows every exception and returns None, which is the exact "no silent fallbacks" pattern CLAUDE.md prohibits. The refactor also dropped a security-rationale comment worth restoring. The rest are small consistency nits.

I verified the GoalStore.propose() logic empirically against a temp-file DB (low→queued/approved, medium/high/critical→pending_approval, pending count and actionable count correct, metadata persisted to progress_notes). I could not run the agent.py test suite in this environment (full dependency chain unavailable), so the agent-side tests are reviewed by reading, not by execution.

Issues

🟡 Agent.propose() silently swallows errors and returns None (src/gaia/agents/base/agent.py:2587)

CLAUDE.md "No Silent Fallbacks — Fail Loudly" explicitly bans try: ... except: return None. A persistence failure here would vanish into a debug log and the caller gets None indistinguishable from "no proposal made". logger.exception is not enough — the rule is to re-raise with context (or let it propagate). GoalStore.propose() already raises naturally on DB error, so the wrapper just needs to get out of the way:

        from gaia.agents.base.goal_store import GoalStore

        store = GoalStore()
        return store.propose(proposal)

If you want a contextual message instead of a bare propagation, raise RuntimeError(f"failed to submit proposal {proposal.action!r}: {e}") from e is the allowed form — but don't return None.

🟡 Security rationale comment dropped in the identity refactor (src/gaia/agents/base/agent.py:2596)

The old inline block at the _agent_context import explained why it's imported via the private path — "intentionally PRIVATE … so a malicious tool body cannot import it from the public gaia.connectors API to forge an agent identity (plan amendment A9, issue #915)". The private import is preserved in _agent_identity_context, but that non-obvious security WHY is now gone. This is exactly the kind of invariant comment CLAUDE.md says to keep. Please restore a one-liner on the import inside _agent_identity_context, e.g.:

        # `_agent_context` is intentionally imported via the PRIVATE path so a
        # tool body can't forge an agent identity through the public API (#915).
        from gaia.connectors.context import _agent_context

🟢 Redundant self-import of _now_iso (src/gaia/agents/base/goal_store.py:545)

_now_iso is defined in this same module; every other method (e.g. create_goal) just calls _now_iso() directly. The from gaia.agents.base.goal_store import _now_iso line is unnecessary and inconsistent — drop it and call _now_iso() like the neighbors.

        now = _now_iso()

🟢 source_label branch is dead-equivalent to source (src/gaia/agents/base/goal_store.py:559-564)

source is typed GoalSource (only user / agent_inferred / agent_scheduled), so the if/elif/else just reproduces its input. The description line already uses source directly. Collapse to:

        source_label = source

🟢 GoalStore.propose() docstring overstates the None path (src/gaia/agents/base/goal_store.py, docstring) — it says "Returns the created Goal, or None on DB error," but the method never catches DB errors (they propagate); None can only come from a get_goal race. Minor wording fix.

🟢 -> Optional[Goal] is unquoted and Goal isn't imported in agent.py (src/gaia/agents/base/agent.py:2576). It works at runtime thanks to from __future__ import annotations, but typing.get_type_hints() would fail, and it's inconsistent with the quoted "Proposal" two lines up. Quote it (-> Optional["Goal"]) or import Goal for symmetry.

🟢 New public surface is undocumented. on_first_run / on_heartbeat / propose / Proposal are new base-Agent API. CLAUDE.md asks every feature to be documented; a mention in docs/sdk/core/agent-system.mdx would close it. Acceptable to defer to #1508 since the hooks aren't invoked by any runtime loop yet — but call that out so it isn't lost.

Strengths

  • Test coverage is the right shape. Real-DB GoalStore.propose tests exercise the actual contract, agent-side tests mock the store, and there's an explicit regression test asserting process_query does not fire the hooks — that last one is easy to forget and genuinely valuable.
  • The identity refactor is behavior-preserving. _namespaced_agent_id() + _agent_identity_context() reproduce the prior _gaia_namespaced_agent_id or AGENT_ID resolution and the None-skips-binding path exactly, while removing the duplication — verified line by line.
  • Risk-tier auto-approval mirrors create_goal's existing agent_inferred semantics, so the new path is consistent with the established state machine rather than inventing a parallel one.

Verdict

Request changes — the blocking item is the propose() swallow-and-return-None (clear CLAUDE.md violation); restoring the security comment is the other ask. Everything else is a one-click suggestion. Nice, well-tested contribution overall.

itomek
itomek previously approved these changes Jun 22, 2026
@itomek
itomek added this pull request to the merge queue Jun 23, 2026
@itomek
itomek removed this pull request from the merge queue due to a manual request Jun 23, 2026

@kovtcharov kovtcharov 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.

Thanks @zycaskevin — the scaffolding (no-op defaults, risk-tier auto-approval, behavior-preserving identity refactor) is genuinely solid and the test coverage is the right shape. Before this can merge, a few things from the earlier review are still open, plus two additions we need:

Blocking

  1. Agent.propose() still swallows exceptions and returns None (agent.py) — this is the "No Silent Fallbacks" pattern CLAUDE.md prohibits. GoalStore.propose() already raises on DB error, so let the wrapper get out of the way: store = GoalStore(); return store.propose(proposal) (or raise RuntimeError(...) from e if you want context). Don't return None.
  2. CI "Run Code Quality Checks" is failing — python util/lint.py --all --fix, then push.
  3. Example agent + user guide. The hooks aren't exercised by anything yet. Please add a small example agent that overrides on_first_run/on_heartbeat and calls propose(), plus a short guide in docs/sdk/core/agent-system.mdx (or a new guide page wired into docs/docs.json) walking through it. This both documents the new public API and proves the feature works end-to-end.

Cleanups (quick)
4. Restore the one-line #915 security WHY on the private _agent_context import inside _agent_identity_context.
5. Drop the redundant from ...goal_store import _now_iso self-import; call _now_iso() directly.
6. Collapse the source_label if/elif/else to source_label = source.
7. Fix the GoalStore.propose() docstring ("or None on DB error" — DB errors propagate).
8. Quote the return type (-> Optional["Goal"]) or import Goal in agent.py.

Knock these out and we're good to merge. Really appreciate the contribution! 🎉

Resolve the CHANGES_REQUESTED items on amd#1797:

- Agent.propose() no longer swallows exceptions and returns None — it
  delegates to GoalStore.propose() and lets DB errors propagate (CLAUDE.md
  no-silent-fallbacks). Return type quoted as Optional["Goal"], and Goal/
  Proposal imported under TYPE_CHECKING so pyflakes resolves the forward
  refs (fixes the F821s that were failing Code Quality).
- Restore the amd#915 WHY comment on the private _agent_context import.
- Drop the redundant goal_store self-import of _now_iso; collapse the
  source_label if/elif/else to `source_label = source`; fix the propose()
  docstring (DB errors propagate, not "None on DB error").
- Remove unused test imports (pytest, AgentConsole) — the other half of
  the flake8 failure.
- Document the proactive lifecycle hooks in docs/sdk/core/agent-system.mdx
  with a runnable WorkspaceAgent example, and add an end-to-end test that
  drives that example through a real GoalStore (override -> propose ->
  persisted goal), proving the feature works, not just the mocks.

flake8 (CI config) clean; 58 tests pass in test_proactive_hooks.py +
test_goal_store.py.
@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

Pushed a commit (db9e492) addressing the open CHANGES_REQUESTED items directly on this branch (maintainer push):

Blocking

  1. ✅ Agent.propose() no longer swallows exceptions/returns None — it delegates to GoalStore.propose() and lets DB errors propagate. Return type quoted Optional["Goal"], and Goal/Proposal imported under TYPE_CHECKING so pyflakes resolves the forward refs (this was also causing the F821s in Code Quality).
  2. ✅ Code Quality green — the flake8 failure was F821 (undefined Goal/Proposal annotations) plus F401 (unused pytest/AgentConsole in the test); both fixed. flake8 with the repo's CI config now passes on the touched files.
  3. ✅ Example + guide — added a "Proactive Lifecycle Hooks" section to docs/sdk/core/agent-system.mdx with a runnable WorkspaceAgent (overrides on_first_run/on_heartbeat, calls propose()), plus an end-to-end test that drives that example through a real GoalStore (override → propose() → persisted goal), so the feature is proven, not just mocked.

Cleanups — ✅ restored the #915 WHY comment on the private _agent_context import; dropped the redundant _now_iso self-import; collapsed source_label to source_label = source; fixed the propose() docstring.

Local: flake8 (CI config) clean; 58 tests pass across test_proactive_hooks.py + test_goal_store.py. Thanks again @zycaskevin — nice feature. Leaving final approval to a re-review once CI is green.

@github-actions github-actions Bot added the documentation Documentation changes label Jul 8, 2026
@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

@claude perform a deep code review. identify any gaps or issues including a comprehensive documentation review.

@github-actions

github-actions Bot commented Jul 8, 2026

Copy link
Copy Markdown
Contributor

Deep review done. The earlier round's blockers are all fixed in the current diff — propose() no longer swallows exceptions, the #915 security comment is restored, the _now_iso self-import and unquoted Goal are gone. Nice cleanup.

One thing needs a decision before merge, and it's both a security/trust question and a documentation contradiction:

🟡 Low-risk agent proposals now auto-execute, which contradicts the committed spec. A risk="low" proposal from on_first_run/on_heartbeat is stored as agent_inferred but comes out queued + approved_for_auto=True — so the agent loop runs it with no user approval. The autonomous-agent spec says the opposite: every agent_inferred goal must sit in pending_approval until the user accepts. So the package would ship code and a spec that disagree on the core safety gate. Worse, risk is a plain field the proposing agent sets on itself with no validation — an agent that labels an impactful action "low" auto-runs it. That's a real trust-model change, not just a doc nit.

@kovtcharov-amd — this is an architecture/security call: is auto-approving self-assessed low-risk agent-inferred proposals the intended trust model? If yes, the spec's approval table + state machine need updating in this PR; if no, low-risk should still land in pending_approval (or route through agent_scheduled).

The rest are minor and non-blocking.

🔍 Technical details

🟡 Trust/doc divergence — src/gaia/agents/base/goal_store.py:532 (propose) sets status="queued", approved="True" for risk=="low" while defaulting source="agent_inferred". get_actionable_goals() (goal_store.py:589) then serves it to the loop (approved_for_auto=1 AND status IN ('queued','in_progress')). This contradicts:

  • docs/spec/autonomous-agent-mode.md:445 — | agent_inferred | pending_approval | False | User must explicitly approve |
  • docs/spec/autonomous-agent-mode.md:426 — state machine shows agent_inferred ──► pending_approval as the only entry path.

The risk value is unvalidated (it's a Literal hint, not enforced), and it's supplied by the agent proposing the action. Either update §6.5/§6.3 to add the risk dimension and document the auto-approve carve-out, or keep low-risk agent-inferred proposals in pending_approval. tests/unit/test_goal_store.py::test_propose_low_risk_auto_approves encodes the current behavior, so whichever way it goes, spec + test should agree.

🟢 Dead proposer param — goal_store.py:535 accepts proposer: str = "agent" but nothing in the method body (or Proposal.to_dict(), or the goals table) uses it, so proposer identity is silently dropped. Given the #915 identity work, either persist it in progress_notes/a column or drop the param.

🟢 Proposal not re-exported — src/gaia/agents/base/__init__.py:8 re-exports Goal, GoalStore, Task but not Proposal, which is now public API (used in the documented example). Add it for symmetry; the doc's full-path import works but is inconsistent with how Goal/Task are surfaced.

🟢 propose() duplicates create_goal()'s INSERT (goal_store.py:561 vs goal_store.py:343) — same 11-column INSERT written twice; a future goals-table column change has to be made in both. The status/approval logic genuinely differs, but the SQL could share a private helper.

🟢 Doc/docstring precision:

  • docs/sdk/core/agent-system.mdx:19 table says propose() returns Goal; the signature is Optional["Goal"] (can be None on a get_goal race).
  • goal_store.py:539 docstring first line ("as pending approval") overstates — low-risk goes to queued.
  • goal_store.py:557 source_label = source is a redundant alias; use source directly in the INSERT.

Verified: _namespaced_agent_id() exists (agent.py:2556) and the _agent_identity_context refactor is behavior-preserving; Action/Risk literals and the goals schema line up with the INSERT; the low-risk→actionable path is real (not just stored). I did not run the suite here — agent-side tests reviewed by reading.

Black-format test_goal_store.py and mark the intentionally-unused
interface arguments (on_first_run/on_heartbeat context, GoalStore.propose
proposer) with pylint disable=unused-argument, matching the console.py
convention. Fixes the Run Code Quality Checks failure.
pull Bot pushed a commit to bhardwajRahul/gaia that referenced this pull request Jul 18, 2026
…amd#1484) (amd#2187)

Before this, the base `Agent` was purely reactive — it could only act
when a user typed a prompt, with no way to surface useful work it
discovered on its own. This adds opt-in `on_first_run` / `on_heartbeat`
lifecycle hooks plus `propose()`, where **every agent-inferred proposal
lands in `pending_approval` and waits for explicit user approval**
before anything runs — matching the committed autonomous-agent spec
(`docs/spec/autonomous-agent-mode.md` §6.3/§6.5). Risk tier is kept as
prioritization signal for the approving user but never gates execution.

Supersedes closed amd#1797 and resolves its trust-model blocker per
maintainer decision: the low-risk auto-approve carve-out is removed (all
proposals are approval-gated), and the dead `proposer` param is now
persisted into proposal metadata. All other review items from amd#1797
(no-silent-fallback `propose()`, amd#915 security comment, docs section)
were already addressed on the branch.

Resolves amd#1484.

## Test plan

- [x] `python -m pytest tests/unit/test_goal_store.py
tests/unit/test_proactive_hooks.py -v` — 60 passed, incl. new tests:
every risk tier → `pending_approval`, `proposer` persisted
- [x] `python util/lint.py --all` — clean (mypy warnings pre-existing,
unrelated files)
- [x] Branch merged with latest `origin/main`, tests re-run post-merge
- [ ] Docs: verify the "Proactive Lifecycle Hooks" section renders on
the docs site preview

---------

Co-authored-by: Nancy AI <[email protected]>
Co-authored-by: Kalin Ovtcharov <[email protected]>
Co-authored-by: kovtcharov-amd <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents documentation Documentation changes tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants