Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

fix(ai): preserve uncertain investigation conclusions

rcourtman668af3fe6b93
diff --git a/docs/qualification/PATROL_ASSISTANT_CUSTOMER_JOURNEY.md b/docs/qualification/PATROL_ASSISTANT_CUSTOMER_JOURNEY.md
index 29c6f571f1..09bdea9534 100644
--- a/docs/qualification/PATROL_ASSISTANT_CUSTOMER_JOURNEY.md
+++ b/docs/qualification/PATROL_ASSISTANT_CUSTOMER_JOURNEY.md
@@ -63,7 +63,7 @@ reproduction evidence, not a representative customer success rate.
|---|---|---|---|
| 1. Product contract and baseline | Map the current loop and sources of judgment. Record telemetry populations and gaps. | Every identified decision has an owner. Activity is not labelled usefulness. | Complete for this redesign scope. Contract, ownership decisions and baseline limits are recorded. |
| 2. Shared evidence | Preserve canonical risk reasons and SMART counters, source/time semantics and history across tools/turns. | Regression tests preserve unknown versus zero and all canonical evidence. Real responses can inspect the same facts as the product. | Implemented and qualified for the named shared-evidence defects. Canonical disk detail, risk and cadence pass real data-path proof. Full affected package, concurrency and retained-query performance checks pass. Real-model interpretation failures remain tracked in step 5. |
-| 3. Diagnostic orchestration | Correct proposal-as-proof. Audit triage budgets, unmatched-signal evaluation, assessment completion and investigation cutoffs. | No code-written causal conclusion. No quality inferred from tool, flag or finding counts. Each retained pass has an objective reason. Safety boundaries and incomplete outcomes remain explicit. | Proposal promotion and capture inference removed in the working change. Targeted tool, loop and full-service regressions pass. Remaining orchestration audit and live qualification are open. |
+| 3. Diagnostic orchestration | Correct proposal-as-proof. Audit triage budgets, unmatched-signal evaluation, assessment completion and investigation cutoffs. | No code-written causal conclusion. No quality inferred from tool, flag or finding counts. Each retained pass has an objective reason. Safety boundaries and incomplete outcomes remain explicit. | Proposal promotion and capture inference were removed in c5d2f56dda. The current slice removes investigation success-call floors, checkpoint instructions and generic call-count wrap-up rules. Full chat regressions pass. Detection passes and live qualification remain open. |
| 4. Issue through verified outcome | Follow existing issue/investigation/action records into Assistant, approval, execution and independent readback. | Accepted proposal is visibly distinct from execution and verification. Rejected or unsupported actions do not become success. Uncertainty can survive an action proposal. | Existing foundation, full journey qualification pending. |
| 5. Ground-truth qualification and landing | Extend existing qualification tooling only where necessary. Exercise healthy/unhealthy, dependency, missing-access, storage/backup and approved/rejected action cases. Inspect the final browser journey at desktop and narrow widths. | Record exact source/model/permissions, evidence, decisions, faults/misses, latency and verification. Fix in-scope failures, pass appropriate proofs and land scoped commits. | Pending. |
@@ -82,7 +82,8 @@ scoring to make the model pass.
| Flag-count turn ladder | `computeTriageMaxTurns` grants 5 + 3 turns per flag, bounded to 8–40, with a separate quick limit. | Replace quality/urgency proxies with explicit execution resource limits. More flags must not imply a better investigation budget. |
| Unmatched-signal evaluation | `runAIAnalysisState` detects signals from tool output and triage, then starts a second model pass when they lack matching findings. | Audit for removal in favour of complete initial evidence and model-owned decisions. Preserve negative-control and missed-fault qualification rather than force reports. |
| Missing-finding assessment sweep | A bounded continuation requests missing explicit present/resolved/uncertain verdicts for known findings. | Retain only the mechanical completeness obligation, with sufficient original evidence and no fabricated resolution or requirement to discover new issues. |
-| Investigation evidence-call floor | Completion is rejected unless at least one successful structured evidence call occurred. | Audit seed evidence and action freshness separately. A tool count does not prove grounding or quality. Preserve explicit failed/unavailable evidence. |
+| Investigation evidence-call floor | Removed in the current slice. Seed-only and failed-read conclusions survive without forced extra calls. | Completion is not diagnostic correctness. Preserve explicit limits, failed/unavailable evidence and independent action freshness checks. |
+| Generic wrap-up counters | Removed the 12/18-call tool-result instructions and four silent-turn cutoff. | Explicit run limits bound work. Counts and silence do not establish evidential sufficiency. A twenty-read regression preserves available tools, observations and the model conclusion. |
| Authority and execution boundaries | Tenant identity, capability schemas, approvals, invocation IDs, parameter redaction and independent readback. | Keep and prove unchanged when diagnostic policy is simplified. These enforce objective invariants. |
This is an audited change list, not a claim that the changes are already made.
@@ -138,6 +139,7 @@ executes infrastructure actions. Authentication stays in browser memory.
|---|---|
| `/patrol`, 1440, 900 and 390 pixels wide | Start review, expand evidence, focus and activate Explain with Enter, inspect issue title and response, verify selected evidence/resource and one request |
| Assistant drawer | Draft preserved across close/reopen, no inference on ordinary open, no competing workflow starters, normal failed-request display and retry, reload without resubmission |
+| `/patrol` Activity, 1440, 900 and 390 pixels wide | Ordinary and mirrored-alert findings, keyboard review, completed-but-unresolved investigation, failed read and nested transcript, collapse, same linked finding and uncertainty in Assistant |
| `/alerts`, desktop and narrow | Open secondary action menu, dismiss with Escape and outside click, reopen, choose explanation, verify selected alert context and no Patrol trigger |
| Initialization regression tests | Newer context cannot be cleared by an earlier send, rejected send retains context, preparation failure reports error, organisation switch cancels old evidence |
@@ -713,3 +715,34 @@ Subsequent full and focused race runs passed, including the final implementation
The original fault has no established root cause and is not labelled harmless
or explained by the successful reruns. Its private worker log is
`paired-metrics-local-20260905T235637/full-metrics-final.log`.
+
+### Diagnostic orchestration slice, 2026-09-06
+
+The investigation loop no longer rejects a conclusion for having no successful
+read or forces extra tool calls when seed context or unavailable access supports
+an honest unknown conclusion. Evidence attempts still consume the configured
+limit, which remains visible as a system fact. Removed completion checkpoints
+and the Assistant/Watch 12/18-call wrap-up instructions from tool results, along
+with the four silent-tool-turn cutoff. Overall turns, advertised capability
+boundaries, configured budgets and repeated-call/error recovery remain bounded.
+
+Full worker chat and AI packages pass against the exact changed runtime source.
+The longer-read regression executes twenty distinct reads over five silent tool
+turns, retains unchanged observations, and preserves the model's conclusion.
+Seed-only and failed/policy-blocked read cases retain uncertainty. These are
+contract tests, not proof of real diagnosis.
+
+Browser qualification reproduced a linked-issue defect: a finding folded under
+an existing alert could not stay selected because selection searched only the
+non-mirrored display groups. Selection now resolves the canonical filtered
+findings, preserving the existing interactive inline surface. The final
+Playwright matrix opens ordinary and mirrored findings at 1440/900/390 widths,
+opens the nested failed-read transcript, collapses the review and
+passes the same finding, unknown conclusion and access limit to Assistant.
+Scripted inference and blocked writes make this a presentation/context proof.
+
+PR #1920's initial worker proof passed against local source 5288b64d, but its CI
+comparison against the actual base 4f9de86e failed nine benchmark comparisons,
+including small single-resource retained reads. Landing is blocked while the
+exact base/candidate comparison is reproduced and corrected. Do not treat the
+previous narrower performance pass as complete CI qualification.
diff --git a/docs/release-control/v6/internal/status.json b/docs/release-control/v6/internal/status.json
index a44d8bd1cc..2544cce99c 100644
--- a/docs/release-control/v6/internal/status.json
+++ b/docs/release-control/v6/internal/status.json
@@ -10201,7 +10201,7 @@
},
{
"id": "patrol-assistant-customer-outcome-qualification",
- "summary": "The maintainer requested a whole-design assessment and an explicit completion goal for Patrol and Assistant. The ordered plan and source-bound evidence are in docs/qualification/PATROL_ASSISTANT_CUSTOMER_JOURNEY.md. The contract separates observations, model conclusions, proposals, execution and independently verified outcomes. Assistant continues the same issue and governed action records. The explicit explanation handoff is an implemented frontend foundation, not outcome qualification. The recorded 2026-09-05 latest-report, monitoring-active, multi-ping review excluded development and deployment proof and contained 127 paid installs, 71 with Patrol enabled and 23 with Assistant calls. Fourteen reported verified resolutions came from one install. Paid includes all non-free tiers. Activity cooccurrence does not establish a successful linked task, and schema 17 outcome/provider/cost fields had no adoption in that review. Real read-only homelab testing with Claude Opus 5 exposed missing canonical evidence, history target/tier gaps, premature context loss, unsupported causal claims and multi-minute responses. Prior history and handoff changes are recorded in the plan. The current working slice removes proposal rationale promotion into Root Cause and duplicate causal inference, preserves disk SMART/risk/source freshness and explicit remaining life, supports canonical disk get/health, and corrects collector cadence and status recovery. Targeted regressions and the live disk data path pass. Affected full worker package suites pass. The single-metric downsample regression and an adjacent bounded chart regression are corrected. Compiled presence statements are reused within a bounded set, but every query reads current data in one snapshot. The chart comparison shows no significant slowdown. Final metrics/database suites, focused concurrency race checks and the existing benchmark guard pass. Single-metric downsampling remains close to the performance threshold. Final landing checks remain pending. One earlier SQLite native binding fault has no established root cause, although subsequent final full and focused race proofs pass. The latest live answers still infer collector startup from timestamp coincidence, claim continuous coverage from retained spacing and infer backup recovery from an online datastore. They fail diagnostic qualification. A serialized routing-envelope leak prompted a subscription transport correction with targeted regression proof, verified without routing prose in a completed real Assistant answer. A narrow answer-table overflow defect is corrected in the shared sanitized renderer with desktop, intermediate and mobile browser proof. The selected subscription provider explicitly refused autonomous Patrol readiness. The runtime and API preserve that refusal and prevent execution. Ordinary Assistant success is not autonomous proof. Required healthy/unhealthy, dependency, missing-access, backup/capacity and approved/rejected action qualification remains incomplete. Independent volunteered Pro environments are required before claiming repeatable customer value or wider readiness.",
+ "summary": "The maintainer requested a whole-design assessment and an explicit completion goal for Patrol and Assistant. The ordered plan and source-bound evidence are in docs/qualification/PATROL_ASSISTANT_CUSTOMER_JOURNEY.md. The contract separates observations, model conclusions, proposals, execution and independently verified outcomes. Assistant continues the same issue and governed action records. The explicit explanation handoff is an implemented frontend foundation, not outcome qualification. The recorded 2026-09-05 latest-report, monitoring-active, multi-ping review excluded development and deployment proof and contained 127 paid installs, 71 with Patrol enabled and 23 with Assistant calls. Fourteen reported verified resolutions came from one install. Paid includes all non-free tiers. Activity cooccurrence does not establish a successful linked task, and schema 17 outcome/provider/cost fields had no adoption in that review. Real read-only homelab testing with Claude Opus 5 exposed missing canonical evidence, history target/tier gaps, premature context loss, unsupported causal claims and multi-minute responses. Prior history and handoff changes are recorded in the plan. The current working slice removes proposal rationale promotion into Root Cause and duplicate causal inference, preserves disk SMART/risk/source freshness and explicit remaining life, supports canonical disk get/health, and corrects collector cadence and status recovery. Targeted regressions and the live disk data path pass. Affected full worker package suites pass. The single-metric downsample regression and an adjacent bounded chart regression are corrected. Compiled presence statements are reused within a bounded set, but every query reads current data in one snapshot. The chart comparison shows no significant slowdown. Final metrics/database suites, focused concurrency race checks and the existing benchmark guard pass. Single-metric downsampling remains close to the performance threshold. PR #1920 CI subsequently failed nine benchmark comparisons against the actual base 4f9de86e, including small retained reads. The prior worker comparison used local source 5288b64d and does not establish final CI performance. Landing remains blocked pending exact-base reproduction and correction. One earlier SQLite native binding fault has no established root cause, although subsequent final full and focused race proofs pass. The latest live answers still infer collector startup from timestamp coincidence, claim continuous coverage from retained spacing and infer backup recovery from an online datastore. They fail diagnostic qualification. A serialized routing-envelope leak prompted a subscription transport correction with targeted regression proof, verified without routing prose in a completed real Assistant answer. A narrow answer-table overflow defect is corrected in the shared sanitized renderer with desktop, intermediate and mobile browser proof. The selected subscription provider explicitly refused autonomous Patrol readiness. The runtime and API preserve that refusal and prevent execution. Ordinary Assistant success is not autonomous proof. Required healthy/unhealthy, dependency, missing-access, backup/capacity and approved/rejected action qualification remains incomplete. Independent volunteered Pro environments are required before claiming repeatable customer value or wider readiness. The next diagnostic slice removes successful-read completion floors, evidence checkpoint instructions and generic call-count/silent-turn wrap-up policy. Full worker chat and AI suites pass. Browser qualification exposed and corrected mirrored-alert finding selection in the shared review lookup. Ordinary/mirrored records and linked uncertainty/failed-read context pass Playwright at 1440/900/390 widths. Detection orchestration and real-model/action outcome qualification remain open.",
"owner": "project-owner",
"status": "planned",
"recorded_at": "2026-09-05",
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index 91344d70b4..7dca94d57a 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -178,32 +178,23 @@ The proposal remains an attributed model decision. Core preserves final model
prose unchanged in the response, stream and transcript, including uncertainty
or a correction of the earlier rationale. Neither structural validation nor
proposal acceptance establishes a root cause or authorizes execution.
-An investigation cannot complete or submit a typed action proposal before the
-model has received at least one successful structured result from an advertised
-evidence tool. Until then, core withholds proposal authority while leaving
-evidence-tool selection model-owned. Failed, policy-blocked, loop-blocked, and
-otherwise rejected calls still consume the bounded evidence-attempt budget but
-cannot satisfy grounding. Transport success alone is insufficient: the result
-must contain non-empty evidence content and must not carry the shared legacy or
-structured policy-block/approval markers. If that budget is exhausted without
-a successful result, the run fails closed before proposal or
-completed-investigation persistence. An unset attempt ceiling does not weaken
-that rule: reaching the
-independent model-turn limit with no successful result fails closed before the
-generic final-summary fallback. The side-effect-free action-capability lookup is planning
-metadata, not infrastructure evidence: it neither consumes the evidence budget
-nor satisfies this grounding gate. The shared
-`agentcapabilities.IsPatrolInfrastructureEvidenceToolName` vocabulary admits
-only canonical query, discovery, metrics, storage, Docker, Kubernetes, deep-read,
-and PMG observations. Alert/finding state, retained knowledge, and generated
-summaries may help interpret evidence but cannot consume the evidence budget,
-satisfy grounding, or unlock proposal authority by themselves. If the provider
-returns prose without a tool call, core
-must discard that prose as a durable conclusion and allow one bounded repair
-turn that requires a successful structured result from the same advertised evidence
-manifest. The repair is generic and carries no platform-, incident-, or
-model-specific diagnosis. A second tool-free response fails the investigation
-closed instead of recording narrated or simulated tool use as completed work.
+Investigation completion and proposal availability do not depend on successful
+evidence-call counts. The model may conclude from supplied observations or
+report that missing access prevents diagnosis. Failed reads remain failed in
+the model context and retained transcript. Completion means the run ended,
+not that its diagnosis is correct, an issue is resolved or an action executed.
+Capability schemas, permissions, correlation and invocation integrity still
+govern proposals and execution independently.
+
+The configured evidence-attempt ceiling remains a resource limit. Attempted
+calls consume it whether they succeed or fail. The request reports the remaining
+allowance as a system fact and removes those tools when it reaches zero.
+It does not prescribe an investigation priority, demand a causal peer, or inject
+checkpoint instructions into tool results. The existing classification of
+infrastructure evidence calls remains only the scope of this resource limit.
+Planning and retained-context tools remain subject to the overall model-turn
+limit. Output-limit recovery stays bounded and uses existing context.
+
Provider-returned function names must also match the exact tool manifest sent
on that turn before read/write classification or execution. A name invented
from an action or operation enum is rejected as `TOOL_NOT_ADVERTISED`, receives
@@ -4475,12 +4466,12 @@ model responses, model-selected tool calls, and evidence-tool calls. The
operator-facing investigation budget limits evidence calls; core derives a
separate model-response ceiling with reserved completion capacity, and the
terminal `patrol_propose_action` call does not consume evidence budget. The
-default budget is ten evidence calls: enough for model-led diagnosis while
-making the shipped qualification ceiling the ordinary product posture instead
-of a lab-only override. Operators may still choose the bounded 5–30 range. The
-investigation execution profile injects an evidence-completion checkpoint,
-then structurally removes evidence tools at exhaustion while retaining only the
-typed proposal route and final prose. This remains model-led: Pulse defines the
+default budget is ten evidence calls. This is a resource limit, not a claim of
+diagnostic sufficiency. Operators may choose the bounded 5–30 range. The
+investigation execution profile reports the remaining limit in system context
+and structurally removes evidence tools at exhaustion while retaining only the
+typed proposal route and final prose. Tool results contain observations, without
+appended completion instructions. This remains model-led: Pulse defines the
four completion questions (symptom, root cause or uncertainty, affected scope,
safe next action), not a prescribed diagnostic tool sequence. Structured run
completion also preserves the action handoff implied by the model's own
@@ -5850,9 +5841,11 @@ pulse_question from the manifest AND runtime-block it in the agentic
loop before the interactive-call-set special case - a fabricated
question call returns a non-interactive error without emitting a
waiting event and sibling tool calls from the same provider turn keep
-processing; approval waits never block (they queue), and the
-tool-only-turn wrap-up guardrail is interactive-profile-owned rather
-than keyed on autonomy. Interactive runs additionally enforce a
+processing; approval waits never block (they queue). Assistant and Watch
+do not infer diagnostic sufficiency from tool-call totals or silent tool turns.
+Configured run limits and repeated identical-call/error recovery still bound
+execution. Tool results never receive count-based wrap-up instructions.
+Interactive runs additionally enforce a
look-before-asking gate: a `pulse_question` issued before the run has
attempted any real tool call is refused with an error tool result that
steers the model to read-only enumeration (the resolve-before-asking
@@ -7834,15 +7827,13 @@ Qualification may therefore require positive input/output usage for a
tool-free real-model all-clear without falsely rejecting Codex subscription
runs whose analysis and healthy outcome were durably persisted.
-Investigation evidence checkpoints keep the finding resource as an anchor,
-not a fence. When a cross-resource cause remains plausible, empty logs or a
-policy-blocked deep-read attempt cannot justify an unknown-root-cause
-conclusion or remediation proposal on the symptom alone; the remaining
-read-only budget must prioritize canonical query, discovery, or topology
-evidence for at least one plausible causal peer or dependency. Later
-topology/query/discovery resource entries take precedence over an earlier
-empty Docker Swarm-service result when determining whether a container peer is
-implicated.
+The finding resource anchors investigation context without restricting which
+canonical resources the model can inspect. The model decides whether further
+peer or dependency evidence is needed and whether missing access prevents a
+causal conclusion. Neither a successful read count nor a submitted proposal
+establishes that cause. Failed reads and explicit uncertainty remain in the
+transcript and final conclusion. Canonical topology/query/discovery tools retain
+the current evidence required for cross-resource diagnosis.
Resource-scoped investigation health evidence uses the canonical resource
projection. `pulse_query` with `action=health` and a non-empty `resource_id`
diff --git a/docs/release-control/v6/internal/subsystems/patrol-intelligence.md b/docs/release-control/v6/internal/subsystems/patrol-intelligence.md
index 4091672ce7..75a40a85f4 100644
--- a/docs/release-control/v6/internal/subsystems/patrol-intelligence.md
+++ b/docs/release-control/v6/internal/subsystems/patrol-intelligence.md
@@ -2539,7 +2539,14 @@ transitions`. `FindingsPanel.tsx` shows the same label on findings and demotes
active findings that mirror an active alert (`isAlertMirroredFinding` in
`frontend-modern/src/utils/findingAlertIdentity.ts`) into a collapsed `N
findings mirror an active alert` group below the list, where their finding
-options remain available; dismissed and resolved views keep them in place.
+options and investigation review remain available; dismissed and resolved views
+keep them in place. Review selection resolves the canonical filtered findings,
+including mirrors, independently of visual grouping. A completed investigation
+with an uncertain diagnosis remains unresolved and keeps failed access evidence
+visible in its transcript and the linked Assistant context. The rendered
+selection regression lives in `FindingsPanel.links.test.tsx`; the desktop,
+intermediate and narrow linked journey is exercised by
+`scripts/check-patrol-assistant-journey.mjs`.
`PatrolAttentionWorkbench.test.tsx` pins the four decisions and their copy, the
rule reason requirement, the remembered-decision path, the alert-only
guidance, and the flapping collapse.
diff --git a/docs/release-control/v6/internal/subsystems/registry.json b/docs/release-control/v6/internal/subsystems/registry.json
index c1d0dfdfe5..3a884800a6 100644
--- a/docs/release-control/v6/internal/subsystems/registry.json
+++ b/docs/release-control/v6/internal/subsystems/registry.json
@@ -6770,6 +6770,7 @@
"allow_same_subsystem_tests": false,
"test_prefixes": [],
"exact_files": [
+ "frontend-modern/src/components/AI/__tests__/FindingsPanel.links.test.tsx",
"frontend-modern/src/components/AI/__tests__/FindingsPanel.test.ts",
"frontend-modern/src/components/patrol/__tests__/ApprovalSection.test.tsx",
"frontend-modern/src/components/patrol/__tests__/InvestigationSection.test.tsx",
diff --git a/frontend-modern/browser-verification.json b/frontend-modern/browser-verification.json
index a5fa18a8a2..4d0c8bddfc 100644
--- a/frontend-modern/browser-verification.json
+++ b/frontend-modern/browser-verification.json
@@ -1,16 +1,17 @@
{
"version": 1,
- "base_sha": "3a189f31d44789a642b68a915d3d4a683ab81104",
- "verified_at": "2026-09-06T00:41:42.025224Z",
+ "base_sha": "c5d2f56dda42946ebafe09266c8e2e52319ba24b",
+ "verified_at": "2026-09-06T01:21:13.188Z",
"result": "passed",
"changed_paths": [
- "frontend-modern/src/components/AI/aiChatUtils.ts"
+ "frontend-modern/src/components/AI/FindingsPanel.tsx"
],
"content_sha256": {
- "frontend-modern/src/components/AI/aiChatUtils.ts": "c65a0f95d3e32da3e8f590de1d40067b5568e5d7d5573652024541e8f8709fb8"
+ "frontend-modern/src/components/AI/FindingsPanel.tsx": "aead071f9431e5c2284014cd8e4af8fc5cde69951f3f850821808dcf885c5226"
},
"routes": [
- "/patrol"
+ "/patrol",
+ "/alerts"
],
"viewports": [
{
@@ -27,13 +28,12 @@
}
],
"states": [
- "Assistant persisted real retained-performance answer with a six-column table. Browser-only short-table and streaming-table fixtures use the current shared renderer and DOM morph implementation.",
- "Wide table overflow belongs to its focusable region. Conversation and surrounding prose do not scroll horizontally. All columns remain reachable.",
- "Saved subscription provider refusal remains visible. No provider probe, model request or infrastructure mutation was made for this rendering verification."
+ "Ordinary and alert-mirrored findings retain the same review selection. Completed investigation remains Needs attention with unknown cause and failed access evidence.",
+ "Original failed read and uncertain conclusion remain visible in the nested investigation transcript and linked Assistant request. Scripted responses establish presentation and context preservation, not diagnostic competence."
],
"interactions": [
- "Open Assistant, select retained session, keyboard-focus table, ArrowRight scrolling, scroll to last column, vertical message scrolling, inspect start/end pixels at desktop and narrow widths.",
- "Append a table row through the current renderer and DOM morph. Verify region identity, keyboard focus and horizontal scroll position are preserved. Inspect short and streaming table pixels at 1440, 900 and 390 widths.",
- "Escape, reload, reopen Assistant and retained session. Private proof: tmp/patrol-outcome-telemetry/homelab/markdown-table-final. This is renderer qualification, not a passing diagnostic outcome."
+ "Activity, Finding options and history, mirrored disclosure, keyboard Review, investigation thread expansion/collapse, review close at 1440/900/390 widths. Inspect final pixels for readable content and reachable controls.",
+ "Inbox selected issue, evidence expansion, keyboard Explain, same canonical finding with failed-read evidence and uncertainty in Assistant handoff, Escape, draft preservation, reload without resubmission.",
+ "Existing adjacent alert menu Escape/outside dismissal and provider failure/retry checked. No infrastructure mutations or autonomous provider calls. Private source-bound proof: tmp/patrol-assistant-journey/result.json."
]
}
diff --git a/frontend-modern/src/components/AI/FindingsPanel.tsx b/frontend-modern/src/components/AI/FindingsPanel.tsx
index afeb230144..7c939f4ec6 100644
--- a/frontend-modern/src/components/AI/FindingsPanel.tsx
+++ b/frontend-modern/src/components/AI/FindingsPanel.tsx
@@ -507,9 +507,12 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {
);
});
const selectedPatrolFinding = createMemo(() => {
+ if (!isPatrolFindingsSource()) return undefined;
const selectedId = expandedId();
if (!selectedId) return undefined;
- return selectedPatrolGroup()?.findings.find((finding) => finding.id === selectedId);
+ // Alert mirrors have their own disclosure instead of a display group, but
+ // share the same review surface and selection as every visible finding.
+ return filteredFindings().find((finding) => finding.id === selectedId);
});
createEffect(() => {
if (isPatrolFindingsSource() && expandedId() && !selectedPatrolFinding()) {
diff --git a/frontend-modern/src/components/AI/__tests__/FindingsPanel.links.test.tsx b/frontend-modern/src/components/AI/__tests__/FindingsPanel.links.test.tsx
index 1ef405b867..f97849bbb8 100644
--- a/frontend-modern/src/components/AI/__tests__/FindingsPanel.links.test.tsx
+++ b/frontend-modern/src/components/AI/__tests__/FindingsPanel.links.test.tsx
@@ -189,6 +189,40 @@ vi.mock('@/stores/aiIntelligence', () => ({
}));
describe('FindingsPanel resource links', () => {
+ it('keeps an alert-mirrored finding selected in the shared Patrol review panel', async () => {
+ const title = 'Disk pressure with unknown cause';
+ mockState.patrolFindings = [
+ {
+ ...mockState.initialPatrolFindings[0],
+ id: 'mirrored-finding',
+ title,
+ mirrorsAlertId: 'alert-1',
+ mirrorsAlertType: 'disk',
+ description: 'The disk is full. Its cause remains unknown.',
+ investigationStatus: 'completed',
+ investigationOutcome: 'needs_attention',
+ },
+ ];
+ render(() => <FindingsPanel findingsSource="patrol" />);
+ fireEvent.click(screen.getByText('1 finding mirrors an active alert'));
+ const review = screen.getByRole('button', { name: `Review issue for ${title}` });
+ fireEvent.click(review);
+ const panel = await screen.findByRole('complementary', { name: `Review ${title}` });
+ expect(panel).toHaveTextContent('The disk is full. Its cause remains unknown.');
+ expect(screen.getByRole('button', { name: `Close review for ${title}` })).toHaveAttribute(
+ 'aria-expanded',
+ 'true',
+ );
+ fireEvent.click(screen.getByRole('button', { name: `Close review panel for ${title}` }));
+ await waitFor(() =>
+ expect(screen.queryByRole('complementary', { name: `Review ${title}` })).toBeNull(),
+ );
+ expect(screen.getByRole('button', { name: `Review issue for ${title}` })).toHaveAttribute(
+ 'aria-expanded',
+ 'false',
+ );
+ });
+
const expectCollapsedFinding = (title: string) => {
expect(screen.getByRole('button', { name: `Review issue for ${title}` })).toBeInTheDocument();
};
diff --git a/internal/ai/chat/agentic.go b/internal/ai/chat/agentic.go
index f8f03f29a8..90ec789aa1 100644
--- a/internal/ai/chat/agentic.go
+++ b/internal/ai/chat/agentic.go
@@ -801,12 +801,11 @@ type AgenticLoop struct {
modelName string
// Token accumulation across all turns
- totalInputTokens int
- totalOutputTokens int
- totalToolCalls int
- totalModelTurns int
- totalEvidenceCalls int
- successfulEvidenceCalls int
+ totalInputTokens int
+ totalOutputTokens int
+ totalToolCalls int
+ totalModelTurns int
+ totalEvidenceCalls int
// State for ongoing executions
mu sync.Mutex
@@ -950,8 +949,6 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, me
patrolOutputLimitRecoveryAttempted := false
investigationOutputLimitRecoveryPending := false // A truncated investigation conclusion needs one evidence-only retry
investigationOutputLimitRecoveryAttempted := false
- investigationEvidenceStartRepairPending := false // A tool-free investigation start gets one structured evidence retry
- investigationEvidenceStartRepairAttempted := false
toolBlockedLastTurn := false // When true, request final text after budget/loop block
investigationProposalCompleted := false
acceptedFindingReports := 0
@@ -982,17 +979,6 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, me
// limit check below owns compaction when the request actually needs it.
currentTurnStartIndex := len(providerMessages)
- // Generic Assistant/Watch wrap-up nudge. Patrol investigation has a
- // separate evidence budget and completion checkpoint below.
- const wrapUpNudgeAfterCalls = 12
- const wrapUpEscalateAfterCalls = 18
- const maxConsecutiveToolOnlyTurns = 4
- totalToolCalls := 0
- wrapUpNudgeFired := false
- wrapUpEscalateFired := false
- investigationCheckpointFired := false
- investigationBudgetWarningFired := false
- consecutiveToolOnlyTurns := 0
consecutiveAllErrorTurns := 0
patrolContinuationProviderFailed := false
@@ -1000,8 +986,7 @@ agenticLoop:
for turn < maxTurns ||
(patrolFindingRepairPending && !patrolFindingRepairAttempted) ||
(patrolOutputLimitRecoveryPending && !patrolOutputLimitRecoveryAttempted) ||
- (investigationOutputLimitRecoveryPending && !investigationOutputLimitRecoveryAttempted) ||
- (investigationEvidenceStartRepairPending && !investigationEvidenceStartRepairAttempted) {
+ (investigationOutputLimitRecoveryPending && !investigationOutputLimitRecoveryAttempted) {
// Check if aborted
a.mu.Lock()
if a.aborted[sessionID] {
@@ -1082,7 +1067,6 @@ agenticLoop:
patrolFindingContinuationTurn := false
patrolOutputLimitRecoveryTurn := false
investigationOutputLimitRecoveryTurn := false
- investigationEvidenceStartRepairTurn := false
if patrolFindingRepairPending && !patrolFindingRepairAttempted {
if applyPatrolFindingLifecycleRepairRequest(&req, a.currentExecutionProfile(), tools) {
patrolFindingRepairTurn = true
@@ -1131,18 +1115,6 @@ agenticLoop:
Str("session_id", sessionID).
Msg("[AgenticLoop] Investigation output limit reached — retrying one evidence-only conclusion turn")
}
- if !patrolFindingRepairTurn && !patrolOutputLimitRecoveryTurn && !investigationOutputLimitRecoveryTurn && investigationEvidenceStartRepairPending && !investigationEvidenceStartRepairAttempted {
- if !applyInvestigationEvidenceStartRepairRequest(&req, a.currentExecutionProfile(), tools) {
- return resultMessages, fmt.Errorf("Patrol investigation requires grounded evidence, but no evidence tools are available")
- }
- investigationEvidenceStartRepairTurn = true
- investigationEvidenceStartRepairPending = false
- investigationEvidenceStartRepairAttempted = true
- log.Warn().
- Int("turn", turn).
- Str("session_id", sessionID).
- Msg("[AgenticLoop] Investigation returned prose before evidence — requiring one structured evidence call")
- }
if !patrolFindingRepairTurn && !patrolOutputLimitRecoveryTurn && shouldOfferPatrolFindingLifecycleContinuation(patrolFindingContinuationPending, writeCompletedLastTurn, toolBlockedLastTurn) {
if applyPatrolFindingLifecycleContinuationRequest(&req, a.currentExecutionProfile(), tools) {
patrolFindingContinuationTurn = true
@@ -1155,7 +1127,7 @@ agenticLoop:
patrolFindingContinuationPending = false
}
}
- if !patrolFindingRepairTurn && !patrolOutputLimitRecoveryTurn && !patrolFindingContinuationTurn && !investigationEvidenceStartRepairTurn && shouldOfferFinalPatrolFindingDecision(turn, maxTurns, patrolFindingSummaryPending, writeCompletedLastTurn, toolBlockedLastTurn) {
+ if !patrolFindingRepairTurn && !patrolOutputLimitRecoveryTurn && !patrolFindingContinuationTurn && shouldOfferFinalPatrolFindingDecision(turn, maxTurns, patrolFindingSummaryPending, writeCompletedLastTurn, toolBlockedLastTurn) {
// Watch detection gives the model one final, tightly scoped chance to
// persist the conclusion it reached from earlier evidence. Other
// profiles keep the historical tool-free final response.
@@ -1204,25 +1176,18 @@ agenticLoop:
Str("session_id", sessionID).
Msg("[AgenticLoop] Tool calls blocked last turn — omitting tools for final response")
}
- if isPatrolInvestigationExecution(a.currentExecutionProfile()) && !investigationOutputLimitRecoveryTurn && !investigationEvidenceStartRepairTurn {
+ if isPatrolInvestigationExecution(a.currentExecutionProfile()) && !investigationOutputLimitRecoveryTurn {
+ if a.maxEvidenceCalls > 0 && !investigationProposalCompleted {
+ req.System += fmt.Sprintf("\nEvidence-tool calls remaining within this run's configured limit: %d.", max(0, a.maxEvidenceCalls-a.totalEvidenceCalls))
+ }
switch {
case investigationProposalCompleted:
req.Tools = nil
textOnlySafetyBrake = true
req.System += investigationProposalCompletionSystemPrompt
case a.maxEvidenceCalls > 0 && a.totalEvidenceCalls >= a.maxEvidenceCalls:
- if a.successfulEvidenceCalls > 0 {
- req.Tools = investigationTerminalTools(tools)
- } else {
- req.Tools = nil
- }
+ req.Tools = investigationTerminalTools(tools)
textOnlySafetyBrake = len(req.Tools) == 0
- req.System += investigationEvidenceBudgetExhaustedSystemPrompt
- case a.successfulEvidenceCalls == 0:
- // A proposal cannot be grounded before any evidence capability has
- // returned a successful result. Failed and policy-blocked attempts still
- // consume budget, but cannot unlock proposal authority.
- req.Tools = investigationEvidenceTools(tools)
}
}
applyExecutionInferenceAllowance(&req, a.currentExecutionProfile(), patrolSummaryOnlyTurn, a.totalOutputTokens)
@@ -1688,14 +1653,6 @@ agenticLoop:
}
providerMessages = append(providerMessages, providerAssistant)
- // Track turns where the model emitted tool calls but no user-facing text.
- // In chat mode this can otherwise spiral into long tool-only chains.
- if len(toolCalls) > 0 && strings.TrimSpace(assistantMsg.Content) == "" {
- consecutiveToolOnlyTurns++
- } else {
- consecutiveToolOnlyTurns = 0
- }
-
// If no tool calls, we're done - but first check FSM and phantom execution
if len(toolCalls) == 0 {
// No tool calls breaks the "consecutive all-error tool turns" streak.
@@ -1742,24 +1699,6 @@ agenticLoop:
continue
}
- if isPatrolInvestigationExecution(a.currentExecutionProfile()) && a.successfulEvidenceCalls == 0 {
- // Prose about intended tool use is not evidence. Preserve it only in
- // provider context for one bounded correction turn, never as the
- // durable investigation conclusion.
- if len(resultMessages) > 0 {
- resultMessages[len(resultMessages)-1].Content = ""
- }
- if a.maxEvidenceCalls > 0 && a.totalEvidenceCalls >= a.maxEvidenceCalls {
- return resultMessages, fmt.Errorf("Patrol investigation exhausted its evidence-call budget without a successful structured evidence result")
- }
- if investigationEvidenceStartRepairAttempted {
- return resultMessages, fmt.Errorf("Patrol investigation completed twice without a successful structured evidence result")
- }
- investigationEvidenceStartRepairPending = true
- turn++
- continue
- }
-
// === ADVERTISED-ACTION GATE: an action request ends in pulse_control, not prose ===
// The field failure this pins: the operator asks to reboot N guests,
// the model resolves them, then writes a report with "next steps"
@@ -2447,8 +2386,6 @@ agenticLoop:
if firstToolResultText == "" {
firstToolResultText = resultText
}
- successfulInvestigationEvidence := isPatrolInvestigationExecution(a.currentExecutionProfile()) &&
- isSuccessfulInvestigationEvidenceResult(tc.Name, resultText, isError)
// Track pending recovery for strict resolution blocks
// (FSM blocks are tracked above; strict resolution blocks come from the executor)
@@ -2563,9 +2500,6 @@ agenticLoop:
if !isError {
anyToolSucceededThisTurn = true
- if successfulInvestigationEvidence {
- a.successfulEvidenceCalls++
- }
if isPatrolDetectionExecution(a.currentExecutionProfile()) && tc.Name == agentcapabilities.PatrolGetFindingsToolName {
patrolFindingsReadCompleted = true
}
@@ -2681,24 +2615,6 @@ agenticLoop:
})
}
- if isPatrolInvestigationExecution(a.currentExecutionProfile()) && a.maxEvidenceCalls > 0 {
- remaining := a.maxEvidenceCalls - a.totalEvidenceCalls
- checkpoint := investigationEvidenceCheckpoint(a.maxEvidenceCalls)
- if !investigationCheckpointFired && a.totalEvidenceCalls >= checkpoint {
- if maybeInjectInvestigationEvidenceCheckpoint(providerMessages, a.totalEvidenceCalls, remaining) {
- investigationCheckpointFired = true
- }
- }
- if !investigationBudgetWarningFired && remaining <= 2 {
- if maybeInjectInvestigationEvidenceBudgetWarning(providerMessages, a.totalEvidenceCalls, remaining) {
- investigationBudgetWarningFired = true
- }
- }
- if a.totalEvidenceCalls >= a.maxEvidenceCalls && a.successfulEvidenceCalls == 0 {
- return resultMessages, fmt.Errorf("Patrol investigation exhausted its evidence-call budget without a successful structured evidence result")
- }
- }
-
if patrolFindingLifecycleCompletedThisTurn < patrolFindingLifecycleCallsThisTurn {
patrolFindingLifecycleFailedThisTurn = true
}
@@ -2747,36 +2663,6 @@ agenticLoop:
Msg("[AgenticLoop] Tool calls blocked this turn — next turn omits tools")
}
- // Guardrail: in interactive chat mode, force wrap-up after repeated
- // tool-only turns to avoid long no-answer chains. Profile-owned:
- // non-interactive Patrol runs are tool-only by design, so the
- // guardrail applies only to the interactive Assistant profile
- // (and, within it, keeps the historical autonomous exemption).
- a.mu.Lock()
- autonomousMode := a.autonomousMode
- interactiveProfile := !a.executionProfile.NonInteractive()
- a.mu.Unlock()
- if interactiveProfile && !autonomousMode && consecutiveToolOnlyTurns >= maxConsecutiveToolOnlyTurns {
- toolBlockedLastTurn = true
- log.Warn().
- Int("consecutive_tool_only_turns", consecutiveToolOnlyTurns).
- Int("turn", turn).
- Str("session_id", sessionID).
- Msg("[AgenticLoop] Consecutive tool-only turns exceeded threshold — next turn omits tools")
- }
-
- // Track cumulative tool calls and inject the generic wrap-up
- // nudge/escalation outside Patrol investigation, whose evidence budget
- // has its own earlier completion contract.
- totalToolCalls += len(toolCalls)
- if !isPatrolInvestigationExecution(a.currentExecutionProfile()) && !wrapUpNudgeFired && totalToolCalls >= wrapUpNudgeAfterCalls {
- maybeInjectWrapUpNudge(providerMessages, totalToolCalls, maxTurns, turn, wrapUpNudgeAfterCalls)
- wrapUpNudgeFired = true
- } else if !isPatrolInvestigationExecution(a.currentExecutionProfile()) && wrapUpNudgeFired && !wrapUpEscalateFired && totalToolCalls >= wrapUpEscalateAfterCalls {
- maybeInjectWrapUpEscalation(providerMessages, totalToolCalls)
- wrapUpEscalateFired = true
- }
-
// Mark the start of the next turn's messages for compaction tracking
currentTurnStartIndex = len(providerMessages)
turn++
@@ -2785,9 +2671,6 @@ agenticLoop:
if !patrolContinuationProviderFailed {
log.Warn().Int("max_turns", maxTurns).Str("session_id", sessionID).Msg("agentic loop hit max turns limit")
}
- if isPatrolInvestigationExecution(a.currentExecutionProfile()) && a.successfulEvidenceCalls == 0 {
- return resultMessages, fmt.Errorf("Patrol investigation reached its model-turn limit without a successful structured evidence result")
- }
if patrolFindingSummaryPending {
resultMessages = a.ensureFinalTextResponseWithSystemPrompt(ctx, sessionID, resultMessages, providerMessages, callback, patrolFindingLifecycleSummarySystemPrompt)
} else {
diff --git a/internal/ai/chat/agentic_additional_test.go b/internal/ai/chat/agentic_additional_test.go
index 53e86ba86d..2eb9ccf0fa 100644
--- a/internal/ai/chat/agentic_additional_test.go
+++ b/internal/ai/chat/agentic_additional_test.go
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"errors"
+ "fmt"
"strings"
"sync"
"testing"
@@ -163,187 +164,7 @@ func TestInvestigationEvidenceBudgetHelpers(t *testing.T) {
t.Fatalf("derived context tool %q must not count as infrastructure evidence", name)
}
}
- if got := investigationEvidenceCheckpoint(15); got != 8 {
- t.Fatalf("checkpoint(15) = %d, want 8", got)
- }
- evidenceOnly := investigationEvidenceTools(available)
- if len(evidenceOnly) != 1 || evidenceOnly[0].Name != agentcapabilities.PulseQueryToolName {
- t.Fatalf("evidence tools = %+v, want only infrastructure evidence", evidenceOnly)
- }
-}
-
-func TestSuccessfulInvestigationEvidenceResultRejectsEmptyAndBlockedOutcomes(t *testing.T) {
- policyResponse := agentcapabilities.NewToolJSONResultWithIsError(agentcapabilities.NewToolBlockedError(
- agentcapabilities.ErrCodePolicyBlocked,
- "blocked by policy",
- nil,
- ), false)
- tests := []struct {
- name string
- tool string
- content string
- isError bool
- want bool
- }{
- {name: "canonical evidence", tool: agentcapabilities.PulseQueryToolName, content: `{"items":[]}`, want: true},
- {name: "non evidence tool", tool: agentcapabilities.PulseAlertsToolName, content: `{"alerts":[]}`},
- {name: "error result", tool: agentcapabilities.PulseQueryToolName, content: "query failed", isError: true},
- {name: "empty result", tool: agentcapabilities.PulseQueryToolName},
- {name: "whitespace result", tool: agentcapabilities.PulseQueryToolName, content: " \n\t "},
- {name: "legacy policy block", tool: agentcapabilities.PulseQueryToolName, content: " \n" + agentcapabilities.PolicyBlockedToolMarker("query", "blocked by policy")},
- {name: "structured policy block", tool: agentcapabilities.PulseQueryToolName, content: agentcapabilities.ToolResultText(policyResponse)},
- {name: "approval request", tool: agentcapabilities.PulseQueryToolName, content: agentcapabilities.ApprovalRequiredToolMarker("query", "call-1", "approval required", "approval-1", "Approve it.")},
- }
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- if got := isSuccessfulInvestigationEvidenceResult(tt.tool, tt.content, tt.isError); got != tt.want {
- t.Fatalf("isSuccessfulInvestigationEvidenceResult(%q, %q, %v) = %v, want %v", tt.tool, tt.content, tt.isError, got, tt.want)
- }
- })
- }
-}
-
-func TestAgenticLoopPatrolInvestigationPolicyBlockedEvidenceDoesNotUnlockProposal(t *testing.T) {
- t.Setenv("PULSE_STRICT_RESOLUTION", "false")
- provider := &stubStreamingProvider{}
- providerCalls := 0
- provider.chatStream = func(_ context.Context, req providers.ChatRequest, callback providers.StreamCallback) error {
- providerCalls++
- if providerToolIsAdvertised(req.Tools, agentcapabilities.PatrolProposeActionToolName) {
- t.Fatalf("proposal authority exposed before grounded evidence: %+v", req.Tools)
- }
- callback(providers.StreamEvent{Type: "done", Data: providers.DoneEvent{ToolCalls: []providers.ToolCall{{
- ID: "policy-blocked-evidence", Name: agentcapabilities.PulseReadToolName,
- Input: map[string]interface{}{"action": "exec", "command": "uptime", "target_host": "host-1"},
- }}}})
- return nil
- }
-
- executor := tools.NewPulseToolExecutor(tools.ExecutorConfig{AgentServer: policyBlockedEvidenceAgentServer{}})
- executor.ApplyExecutionProfile(tools.ProfilePatrolInvestigation)
- loop := NewAgenticLoop(provider, executor, "system")
- loop.SetExecutionProfile(tools.ProfilePatrolInvestigation)
- loop.SetMaxEvidenceCalls(1)
- loop.SetMaxTurns(3)
-
- result, err := loop.ExecuteWithTools(
- context.Background(),
- "policy-blocked-evidence",
- []Message{{Role: "user", Content: "investigate"}},
- []providers.Tool{{Name: agentcapabilities.PulseReadToolName}, {Name: agentcapabilities.PatrolProposeActionToolName}},
- func(StreamEvent) {},
- )
- if err == nil || !strings.Contains(err.Error(), "without a successful structured evidence result") {
- t.Fatalf("ExecuteWithTools error = %v, want fail-closed grounding error", err)
- }
- if providerCalls != 1 || loop.GetTotalEvidenceCalls() != 1 || loop.successfulEvidenceCalls != 0 {
- t.Fatalf("provider/evidence counts = %d/%d/%d, want 1/1/0", providerCalls, loop.GetTotalEvidenceCalls(), loop.successfulEvidenceCalls)
- }
- if len(result) == 0 || result[len(result)-1].ToolResult == nil {
- t.Fatalf("policy-blocked evidence result missing from transcript: %+v", result)
- }
- blocked := result[len(result)-1].ToolResult
- if blocked.IsError || !agentcapabilities.HasPolicyBlockedToolMarker(blocked.Content) {
- t.Fatalf("test requires a transport-success policy block, got %+v", blocked)
- }
-}
-
-func TestAgenticLoopPatrolInvestigationRepairsToolFreeStart(t *testing.T) {
- provider := &stubStreamingProvider{}
- var requests []providers.ChatRequest
- turn := 0
- provider.chatStream = func(_ context.Context, req providers.ChatRequest, callback providers.StreamCallback) error {
- requests = append(requests, req)
- turn++
- switch turn {
- case 1:
- callback(providers.StreamEvent{Type: "content", Data: providers.ContentEvent{Text: "I will now call a made-up tool in prose."}})
- callback(providers.StreamEvent{Type: "done", Data: providers.DoneEvent{}})
- case 2:
- callback(providers.StreamEvent{Type: "done", Data: providers.DoneEvent{ToolCalls: []providers.ToolCall{{ID: "evidence", Name: agentcapabilities.PulseQueryToolName, Input: map[string]interface{}{"action": "search", "query": "containers"}}}}})
- default:
- callback(providers.StreamEvent{Type: "content", Data: providers.ContentEvent{Text: "grounded conclusion"}})
- callback(providers.StreamEvent{Type: "done", Data: providers.DoneEvent{}})
- }
- return nil
- }
-
- executor := tools.NewPulseToolExecutor(tools.ExecutorConfig{StateProvider: &mockStateProvider{}})
- executor.ApplyExecutionProfile(tools.ProfilePatrolInvestigation)
- loop := NewAgenticLoop(provider, executor, "system")
- loop.SetExecutionProfile(tools.ProfilePatrolInvestigation)
- loop.SetMaxTurns(3)
-
- available := []providers.Tool{
- {Name: agentcapabilities.PulseQueryToolName},
- {Name: agentcapabilities.PatrolActionCapabilitiesToolName},
- {Name: agentcapabilities.PatrolProposeActionToolName},
- }
- result, err := loop.ExecuteWithTools(context.Background(), "grounding-repair", []Message{{Role: "user", Content: "investigate"}}, available, func(StreamEvent) {})
- if err != nil {
- t.Fatalf("ExecuteWithTools: %v", err)
- }
- if len(requests) != 3 {
- t.Fatalf("provider requests = %d, want 3", len(requests))
- }
- for i, req := range requests {
- if req.MinContextTokens != PatrolProviderMinContextTokens {
- t.Fatalf("request %d MinContextTokens = %d, want %d", i, req.MinContextTokens, PatrolProviderMinContextTokens)
- }
- }
- for _, requestIndex := range []int{0, 1} {
- for _, tool := range requests[requestIndex].Tools {
- if tool.Name == agentcapabilities.PatrolProposeActionToolName {
- t.Fatalf("request %d offered an ungrounded proposal: %+v", requestIndex, requests[requestIndex].Tools)
- }
- }
- }
- if requests[1].ToolChoice == nil || requests[1].ToolChoice.Type != providers.ToolChoiceRequired {
- t.Fatalf("repair tool choice = %+v, want required", requests[1].ToolChoice)
- }
- if !strings.Contains(requests[1].System, "cannot accept a completed investigation") {
- t.Fatalf("repair system prompt missing grounding contract: %q", requests[1].System)
- }
- if loop.GetTotalEvidenceCalls() != 1 {
- t.Fatalf("evidence calls = %d, want 1", loop.GetTotalEvidenceCalls())
- }
- if len(result) == 0 || result[0].Content != "" || result[len(result)-1].Content != "grounded conclusion" {
- t.Fatalf("durable result retained ungrounded prose or lost conclusion: %+v", result)
- }
-}
-
-func TestAgenticLoopPatrolInvestigationFailsClosedAfterToolFreeRepair(t *testing.T) {
- provider := &stubStreamingProvider{}
- var requests []providers.ChatRequest
- provider.chatStream = func(_ context.Context, req providers.ChatRequest, callback providers.StreamCallback) error {
- requests = append(requests, req)
- callback(providers.StreamEvent{Type: "content", Data: providers.ContentEvent{Text: "I would inspect this later."}})
- callback(providers.StreamEvent{Type: "done", Data: providers.DoneEvent{}})
- return nil
- }
-
- executor := tools.NewPulseToolExecutor(tools.ExecutorConfig{})
- executor.ApplyExecutionProfile(tools.ProfilePatrolInvestigation)
- loop := NewAgenticLoop(provider, executor, "system")
- loop.SetExecutionProfile(tools.ProfilePatrolInvestigation)
- loop.SetMaxTurns(1)
-
- result, err := loop.ExecuteWithTools(context.Background(), "grounding-fail-closed", []Message{{Role: "user", Content: "investigate"}}, []providers.Tool{{Name: agentcapabilities.PulseQueryToolName}}, func(StreamEvent) {})
- if err == nil || !strings.Contains(err.Error(), "completed twice without a successful structured evidence result") {
- t.Fatalf("ExecuteWithTools error = %v, want fail-closed grounding error", err)
- }
- if len(requests) != 2 {
- t.Fatalf("provider requests = %d, want one bounded repair", len(requests))
- }
- if requests[1].ToolChoice == nil || requests[1].ToolChoice.Type != providers.ToolChoiceRequired {
- t.Fatalf("repair tool choice = %+v, want required", requests[1].ToolChoice)
- }
- for _, msg := range result {
- if strings.TrimSpace(msg.Content) != "" {
- t.Fatalf("ungrounded prose escaped into durable result: %+v", result)
- }
- }
}
func TestAgenticLoopPatrolInvestigationRejectsUnadvertisedToolBeforeFSM(t *testing.T) {
@@ -394,7 +215,7 @@ func TestAgenticLoopPatrolInvestigationRejectsUnadvertisedToolBeforeFSM(t *testi
if rejected.Success || !strings.Contains(rejected.Output, "TOOL_NOT_ADVERTISED") || strings.Contains(rejected.Output, "FSM blocked") {
t.Fatalf("unknown tool result = %+v, want exact-manifest rejection before FSM", rejected)
}
- if !strings.Contains(rejected.Output, agentcapabilities.PulseQueryToolName) || strings.Contains(rejected.Output, agentcapabilities.PatrolProposeActionToolName) {
+ if !strings.Contains(rejected.Output, agentcapabilities.PulseQueryToolName) || !strings.Contains(rejected.Output, agentcapabilities.PatrolProposeActionToolName) {
t.Fatalf("unknown tool correction did not use exact turn manifest: %q", rejected.Output)
}
if loop.GetTotalEvidenceCalls() != 1 {
@@ -455,7 +276,7 @@ func TestAgenticLoopPatrolInvestigationEnforcesEvidenceBudget(t *testing.T) {
if len(requests[2].Tools) != 1 || requests[2].Tools[0].Name != agentcapabilities.PatrolProposeActionToolName {
t.Fatalf("post-budget tools = %+v, want only patrol_propose_action", requests[2].Tools)
}
- if !strings.Contains(requests[2].System, "evidence-call budget is exhausted") {
+ if !strings.Contains(requests[2].System, "Evidence-tool calls remaining within this run's configured limit: 0.") {
t.Fatalf("post-budget system prompt missing completion contract: %q", requests[2].System)
}
if len(result) == 0 || !strings.Contains(result[len(result)-1].Content, "final investigation summary") {
@@ -463,139 +284,6 @@ func TestAgenticLoopPatrolInvestigationEnforcesEvidenceBudget(t *testing.T) {
}
}
-func TestAgenticLoopPatrolInvestigationFailedEvidenceDoesNotUnlockProposal(t *testing.T) {
- provider := &stubStreamingProvider{}
- var requests []providers.ChatRequest
- turn := 0
- provider.chatStream = func(_ context.Context, req providers.ChatRequest, callback providers.StreamCallback) error {
- requests = append(requests, req)
- turn++
- switch turn {
- case 1:
- callback(providers.StreamEvent{Type: "done", Data: providers.DoneEvent{ToolCalls: []providers.ToolCall{{
- ID: "failed-evidence", Name: agentcapabilities.PulseQueryToolName,
- Input: map[string]interface{}{"action": "unsupported"},
- }}}})
- case 2:
- callback(providers.StreamEvent{Type: "done", Data: providers.DoneEvent{ToolCalls: []providers.ToolCall{{
- ID: "successful-evidence", Name: agentcapabilities.PulseQueryToolName,
- Input: map[string]interface{}{"action": "search", "query": "containers"},
- }}}})
- default:
- callback(providers.StreamEvent{Type: "content", Data: providers.ContentEvent{Text: "grounded conclusion"}})
- callback(providers.StreamEvent{Type: "done", Data: providers.DoneEvent{}})
- }
- return nil
- }
-
- executor := tools.NewPulseToolExecutor(tools.ExecutorConfig{StateProvider: &mockStateProvider{}})
- executor.ApplyExecutionProfile(tools.ProfilePatrolInvestigation)
- loop := NewAgenticLoop(provider, executor, "system")
- loop.SetExecutionProfile(tools.ProfilePatrolInvestigation)
- loop.SetMaxEvidenceCalls(3)
- loop.SetMaxTurns(4)
-
- available := []providers.Tool{
- {Name: agentcapabilities.PulseQueryToolName},
- {Name: agentcapabilities.PatrolProposeActionToolName},
- }
- result, err := loop.ExecuteWithTools(context.Background(), "failed-evidence-repair", []Message{{Role: "user", Content: "investigate"}}, available, func(StreamEvent) {})
- if err != nil {
- t.Fatalf("ExecuteWithTools: %v", err)
- }
- if len(requests) != 3 {
- t.Fatalf("provider requests = %d, want 3", len(requests))
- }
- for _, requestIndex := range []int{0, 1} {
- if names := advertisedProviderToolNames(requests[requestIndex].Tools); len(names) != 1 || names[0] != agentcapabilities.PulseQueryToolName {
- t.Fatalf("request %d tools = %v, want evidence only", requestIndex, names)
- }
- }
- if !providerToolIsAdvertised(requests[2].Tools, agentcapabilities.PatrolProposeActionToolName) {
- t.Fatalf("successful evidence did not unlock proposal authority: %+v", requests[2].Tools)
- }
- if loop.GetTotalEvidenceCalls() != 2 || loop.successfulEvidenceCalls != 1 {
- t.Fatalf("evidence attempts=%d successes=%d, want 2/1", loop.GetTotalEvidenceCalls(), loop.successfulEvidenceCalls)
- }
- if len(result) == 0 || result[len(result)-1].Content != "grounded conclusion" {
- t.Fatalf("result = %+v, want grounded conclusion", result)
- }
-}
-
-func TestAgenticLoopPatrolInvestigationFailsClosedWhenEvidenceBudgetHasNoSuccess(t *testing.T) {
- provider := &stubStreamingProvider{}
- providerCalls := 0
- provider.chatStream = func(_ context.Context, req providers.ChatRequest, callback providers.StreamCallback) error {
- providerCalls++
- if providerToolIsAdvertised(req.Tools, agentcapabilities.PatrolProposeActionToolName) {
- t.Fatalf("proposal authority exposed before successful evidence: %+v", req.Tools)
- }
- callback(providers.StreamEvent{Type: "done", Data: providers.DoneEvent{ToolCalls: []providers.ToolCall{{
- ID: "failed-evidence", Name: agentcapabilities.PulseQueryToolName,
- Input: map[string]interface{}{"action": "unsupported"},
- }}}})
- return nil
- }
-
- executor := tools.NewPulseToolExecutor(tools.ExecutorConfig{StateProvider: &mockStateProvider{}})
- executor.ApplyExecutionProfile(tools.ProfilePatrolInvestigation)
- loop := NewAgenticLoop(provider, executor, "system")
- loop.SetExecutionProfile(tools.ProfilePatrolInvestigation)
- loop.SetMaxEvidenceCalls(1)
- loop.SetMaxTurns(3)
-
- result, err := loop.ExecuteWithTools(
- context.Background(),
- "failed-evidence-budget",
- []Message{{Role: "user", Content: "investigate"}},
- []providers.Tool{{Name: agentcapabilities.PulseQueryToolName}, {Name: agentcapabilities.PatrolProposeActionToolName}},
- func(StreamEvent) {},
- )
- if err == nil || !strings.Contains(err.Error(), "exhausted its evidence-call budget without a successful structured evidence result") {
- t.Fatalf("ExecuteWithTools error = %v, want failed-grounding budget error", err)
- }
- if providerCalls != 1 {
- t.Fatalf("provider calls = %d, want fail closed immediately after exhausted attempt", providerCalls)
- }
- if loop.GetTotalEvidenceCalls() != 1 || loop.successfulEvidenceCalls != 0 {
- t.Fatalf("evidence attempts=%d successes=%d, want 1/0", loop.GetTotalEvidenceCalls(), loop.successfulEvidenceCalls)
- }
- if len(result) == 0 || result[len(result)-1].ToolResult == nil || !result[len(result)-1].ToolResult.IsError {
- t.Fatalf("failed evidence result was not preserved: %+v", result)
- }
-}
-
-func TestAgenticLoopPatrolInvestigationTurnLimitCannotBypassSuccessfulEvidence(t *testing.T) {
- provider := &stubStreamingProvider{}
- provider.chatStream = func(_ context.Context, _ providers.ChatRequest, callback providers.StreamCallback) error {
- callback(providers.StreamEvent{Type: "done", Data: providers.DoneEvent{ToolCalls: []providers.ToolCall{{
- ID: "failed-evidence", Name: agentcapabilities.PulseQueryToolName,
- Input: map[string]interface{}{"action": "unsupported"},
- }}}})
- return nil
- }
-
- executor := tools.NewPulseToolExecutor(tools.ExecutorConfig{StateProvider: &mockStateProvider{}})
- executor.ApplyExecutionProfile(tools.ProfilePatrolInvestigation)
- loop := NewAgenticLoop(provider, executor, "system")
- loop.SetExecutionProfile(tools.ProfilePatrolInvestigation)
- loop.SetMaxTurns(1)
-
- result, err := loop.ExecuteWithTools(
- context.Background(),
- "failed-evidence-turn-limit",
- []Message{{Role: "user", Content: "investigate"}},
- []providers.Tool{{Name: agentcapabilities.PulseQueryToolName}},
- func(StreamEvent) {},
- )
- if err == nil || !strings.Contains(err.Error(), "reached its model-turn limit without a successful structured evidence result") {
- t.Fatalf("ExecuteWithTools error = %v, want failed-grounding turn-limit error", err)
- }
- if len(result) == 0 || result[len(result)-1].ToolResult == nil || !result[len(result)-1].ToolResult.IsError {
- t.Fatalf("failed evidence result was not preserved: %+v", result)
- }
-}
-
func TestIsPatrolFindingLifecycleWrite(t *testing.T) {
for _, toolName := range []string{
agentcapabilities.PatrolReportFindingToolName,
@@ -2611,7 +2299,6 @@ func TestAgenticLoop_RecoversTruncatedInvestigationConclusionFromExistingEvidenc
loop.SetExecutionProfile(tools.ProfilePatrolInvestigation)
loop.SetMaxTurns(1)
loop.totalEvidenceCalls = 1
- loop.successfulEvidenceCalls = 1
providerCalls := 0
var recoveryRequest providers.ChatRequest
@@ -3104,3 +2791,178 @@ func TestAgenticLoop_CancelsUnavailableCurrentResourcePendingToolCall(t *testing
t.Fatalf("expected assistant to ask for target, got %q", results[0].Content)
}
}
+
+// The model can interpret seed observations or explicitly report an access
+// limit without a successful tool-call count certifying that interpretation.
+func TestPatrolInvestigationCanConcludeFromSeedContext(t *testing.T) {
+ for _, seed := range []string{
+ "Current observation: the service endpoint is unreachable. No host agent is connected. The cause is unknown.",
+ "Collection is unavailable. No current service or host observation is supplied. The cause is unknown.",
+ } {
+ t.Run(seed, func(t *testing.T) {
+ const conclusion = "The cause is unknown. Host access is unavailable, and no action was performed."
+ calls := 0
+ provider := &stubStreamingProvider{}
+ provider.chatStream = func(_ context.Context, req providers.ChatRequest, callback providers.StreamCallback) error {
+ calls++
+ if req.ToolChoice != nil && req.ToolChoice.Type == providers.ToolChoiceRequired {
+ t.Fatal("a tool call was forced despite the supplied context")
+ }
+ if len(req.Messages) == 0 || req.Messages[0].Content != seed {
+ t.Fatalf("seed context changed: %+v", req.Messages)
+ }
+ callback(providers.StreamEvent{Type: "content", Data: providers.ContentEvent{Text: conclusion}})
+ callback(providers.StreamEvent{Type: "done", Data: providers.DoneEvent{}})
+ return nil
+ }
+ executor := tools.NewPulseToolExecutor(tools.ExecutorConfig{})
+ executor.ApplyExecutionProfile(tools.ProfilePatrolInvestigation)
+ loop := NewAgenticLoop(provider, executor, "Investigate the supplied issue.")
+ loop.SetExecutionProfile(tools.ProfilePatrolInvestigation)
+ loop.SetMaxTurns(3)
+ result, err := loop.ExecuteWithTools(context.Background(), "seed-context", []Message{{Role: "user", Content: seed}}, []providers.Tool{{Name: agentcapabilities.PulseQueryToolName}}, func(StreamEvent) {})
+ if err != nil || calls != 1 || loop.GetTotalEvidenceCalls() != 0 {
+ t.Fatalf("unexpected forced investigation: calls=%d evidence=%d error=%v", calls, loop.GetTotalEvidenceCalls(), err)
+ }
+ if len(result) != 1 || result[0].Content != conclusion {
+ t.Fatalf("uncertainty was discarded: %+v", result)
+ }
+ })
+ }
+}
+
+func TestPatrolInvestigationPreservesFailedReadsAndUncertainty(t *testing.T) {
+ t.Setenv("PULSE_STRICT_RESOLUTION", "false")
+ for _, policyBlocked := range []bool{false, true} {
+ t.Run(fmt.Sprintf("policyBlocked_%v", policyBlocked), func(t *testing.T) {
+ const conclusion = "The requested evidence could not be collected. The cause remains unknown. No action was performed."
+ cfg := tools.ExecutorConfig{StateProvider: &mockStateProvider{}}
+ call := providers.ToolCall{ID: "unavailable-evidence", Name: agentcapabilities.PulseQueryToolName, Input: map[string]interface{}{"action": "unsupported"}}
+ if policyBlocked {
+ cfg.AgentServer = policyBlockedEvidenceAgentServer{}
+ call.Name = agentcapabilities.PulseReadToolName
+ call.Input = map[string]interface{}{"action": "exec", "command": "uptime", "target_host": "host-1"}
+ }
+ provider := &stubStreamingProvider{}
+ calls := 0
+ var observed string
+ provider.chatStream = func(_ context.Context, req providers.ChatRequest, callback providers.StreamCallback) error {
+ calls++
+ if calls == 1 {
+ callback(providers.StreamEvent{Type: "done", Data: providers.DoneEvent{ToolCalls: []providers.ToolCall{call}}})
+ return nil
+ }
+ if calls != 2 {
+ t.Fatalf("unexpected forced follow-up turn %d", calls)
+ }
+ if providerToolIsAdvertised(req.Tools, call.Name) {
+ t.Fatal("exhausted evidence capability remained available")
+ }
+ for _, msg := range req.Messages {
+ if msg.ToolResult != nil && msg.ToolResult.ToolUseID == call.ID {
+ observed = msg.ToolResult.Content
+ if policyBlocked {
+ if !agentcapabilities.HasPolicyBlockedToolMarker(observed) {
+ t.Fatalf("policy boundary lost: %q", observed)
+ }
+ } else if !msg.ToolResult.IsError {
+ t.Fatal("failed read became successful evidence")
+ }
+ }
+ }
+ if observed == "" || strings.Contains(observed, "Patrol evidence checkpoint") || strings.Contains(observed, "Patrol evidence budget") {
+ t.Fatalf("result missing or altered by diagnostic policy: %q", observed)
+ }
+ callback(providers.StreamEvent{Type: "content", Data: providers.ContentEvent{Text: conclusion}})
+ callback(providers.StreamEvent{Type: "done", Data: providers.DoneEvent{}})
+ return nil
+ }
+ executor := tools.NewPulseToolExecutor(cfg)
+ executor.ApplyExecutionProfile(tools.ProfilePatrolInvestigation)
+ loop := NewAgenticLoop(provider, executor, "Investigate the supplied issue.")
+ loop.SetExecutionProfile(tools.ProfilePatrolInvestigation)
+ loop.SetMaxEvidenceCalls(1)
+ loop.SetMaxTurns(3)
+ result, err := loop.ExecuteWithTools(context.Background(), "missing-access", []Message{{Role: "user", Content: "Investigate. No current host observation is available."}}, []providers.Tool{{Name: call.Name}, {Name: agentcapabilities.PatrolProposeActionToolName}}, func(StreamEvent) {})
+ if err != nil || calls != 2 || loop.GetTotalEvidenceCalls() != 1 {
+ t.Fatalf("failed read prevented an honest conclusion: calls=%d evidence=%d error=%v", calls, loop.GetTotalEvidenceCalls(), err)
+ }
+ if len(result) == 0 || result[len(result)-1].Content != conclusion {
+ t.Fatalf("uncertain conclusion lost: %+v", result)
+ }
+ found := false
+ for _, msg := range result {
+ if msg.ToolResult != nil && msg.ToolResult.ToolUseID == call.ID {
+ found = true
+ if msg.ToolResult.Content != observed {
+ t.Fatalf("persisted result differs from model evidence: %q != %q", msg.ToolResult.Content, observed)
+ }
+ }
+ }
+ if !found {
+ t.Fatal("failed read missing from retained transcript")
+ }
+ })
+ }
+}
+
+// A multi-resource investigation may need several tool-only turns. Call counts
+// must neither alter observations nor stand in for the model's conclusion.
+func TestAgenticLoopPreservesEvidenceThroughLongReadSequence(t *testing.T) {
+ for _, profile := range []tools.ExecutionProfile{tools.ProfileInteractiveAssistant, tools.ProfilePatrolDetection} {
+ t.Run(fmt.Sprint(profile), func(t *testing.T) {
+ const conclusion = "No matching resources were found. The requested diagnosis remains unknown."
+ provider := &stubStreamingProvider{}
+ calls := 0
+ observations := make(map[string]string)
+ provider.chatStream = func(_ context.Context, req providers.ChatRequest, callback providers.StreamCallback) error {
+ calls++
+ for _, msg := range req.Messages {
+ if msg.ToolResult == nil {
+ continue
+ }
+ result := msg.ToolResult
+ if result.IsError || strings.Contains(result.Content, "[System:") {
+ t.Fatalf("read result failed or contains injected policy: %+v", result)
+ }
+ if prior, found := observations[result.ToolUseID]; found && prior != result.Content {
+ t.Fatalf("observation changed between provider turns: %q != %q", prior, result.Content)
+ }
+ observations[result.ToolUseID] = result.Content
+ }
+ if !providerToolIsAdvertised(req.Tools, agentcapabilities.PulseQueryToolName) {
+ t.Fatalf("read capability withdrawn before configured run limit on turn %d", calls)
+ }
+ if calls <= 5 {
+ var batch []providers.ToolCall
+ for resource := 0; resource < 4; resource++ {
+ id := fmt.Sprintf("resource-%d-%d", calls, resource)
+ batch = append(batch, providers.ToolCall{ID: id, Name: agentcapabilities.PulseQueryToolName, Input: map[string]interface{}{"action": "search", "query": id}})
+ }
+ callback(providers.StreamEvent{Type: "done", Data: providers.DoneEvent{ToolCalls: batch}})
+ } else {
+ callback(providers.StreamEvent{Type: "content", Data: providers.ContentEvent{Text: conclusion}})
+ callback(providers.StreamEvent{Type: "done", Data: providers.DoneEvent{}})
+ }
+ return nil
+ }
+ executor := tools.NewPulseToolExecutor(tools.ExecutorConfig{StateProvider: &mockStateProvider{}})
+ executor.ApplyExecutionProfile(profile)
+ loop := NewAgenticLoop(provider, executor, "Investigate the requested resources.")
+ loop.SetExecutionProfile(profile)
+ loop.SetMaxTurns(8)
+ result, err := loop.ExecuteWithTools(context.Background(), "long-read-sequence", []Message{{Role: "user", Content: "Check these twenty resources."}}, []providers.Tool{{Name: agentcapabilities.PulseQueryToolName}}, func(StreamEvent) {})
+ if err != nil || calls != 6 || len(observations) != 20 {
+ t.Fatalf("read sequence was curtailed: calls=%d observations=%d error=%v", calls, len(observations), err)
+ }
+ if len(result) == 0 || result[len(result)-1].Content != conclusion {
+ t.Fatalf("model conclusion lost: %+v", result)
+ }
+ for _, msg := range result {
+ if msg.ToolResult != nil && observations[msg.ToolResult.ToolUseID] != msg.ToolResult.Content {
+ t.Fatalf("durable evidence differs from provider observation: %+v", msg.ToolResult)
+ }
+ }
+ })
+ }
+}
diff --git a/internal/ai/chat/agentic_control.go b/internal/ai/chat/agentic_control.go
index abbdd3cb9c..09de5c0aff 100644
--- a/internal/ai/chat/agentic_control.go
+++ b/internal/ai/chat/agentic_control.go
@@ -84,8 +84,8 @@ func (a *AgenticLoop) SetAutonomousMode(enabled bool) {
}
// SetExecutionProfile applies the core-owned execution profile for this
-// loop. The profile owns non-interactive behavior (question handling,
-// tool-only-turn wrap-up) and the prompt's execution-mode description;
+// loop. The profile owns non-interactive question handling, provider
+// stream allowance, and the prompt's execution-mode description;
// it is deliberately separate from autonomous mode, which only affects
// approval waiting and grants no mutation authority.
func (a *AgenticLoop) SetExecutionProfile(profile tools.ExecutionProfile) {
diff --git a/internal/ai/chat/agentic_investigation_budget.go b/internal/ai/chat/agentic_investigation_budget.go
index 8ef7f7fb8f..e3f6714f7d 100644
--- a/internal/ai/chat/agentic_investigation_budget.go
+++ b/internal/ai/chat/agentic_investigation_budget.go
@@ -1,13 +1,9 @@
package chat
import (
- "fmt"
- "strings"
-
"github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities"
"github.com/rcourtman/pulse-go-rewrite/internal/ai/providers"
aitools "github.com/rcourtman/pulse-go-rewrite/internal/ai/tools"
- "github.com/rs/zerolog/log"
)
func isPatrolInvestigationExecution(profile aitools.ExecutionProfile) bool {
@@ -20,14 +16,6 @@ const investigationProposalCompletionSystemPrompt = `
INVESTIGATION COMPLETION: An action proposal has been recorded for this run. Do not call more tools. Summarize the evidence collected and any uncertainty. The proposal is pending governed policy or operator handling and has not executed. Proposal acceptance validates the action contract, not the rationale or root cause.`
-const investigationEvidenceStartRepairSystemPrompt = `
-
-INVESTIGATION GROUNDING: Pulse cannot accept a completed investigation until at least one structured call to an advertised evidence tool succeeds. Choose the most relevant available tool and arguments from the exact finding and resource identity already supplied. Call the tool now through the structured tool interface. Do not narrate, simulate, or place a hypothetical tool call in prose. A failed or policy-blocked call is not evidence.`
-
-const investigationEvidenceBudgetExhaustedSystemPrompt = `
-
-INVESTIGATION COMPLETION: The evidence-call budget is exhausted. No more evidence tools are available. Use the evidence already collected. If it supports a safe advertised remediation and no proposal has been submitted, you must call patrol_propose_action once before the final summary; never leave that remediation only as prose. Otherwise produce the required final summary and state any remaining uncertainty.`
-
const investigationOutputLimitRecoverySystemPrompt = `You are Pulse Patrol completing an investigation after the previous final response exhausted its output budget. Do not call tools, repeat the investigation, or narrate your reasoning. Synthesize only the evidence already present in the conversation into the required five sections: Investigation Summary, Root Cause, Affected Resources, Recommendation, and Conclusion. Name causal and affected resources with their exact observed canonical name or ID. If the evidence does not establish root cause, say exactly what remains uncertain. Never invent evidence, actions, verification, or remediation.`
const investigationOutputLimitRecoveryAllowance = 4_096
@@ -48,47 +36,6 @@ func isInvestigationEvidenceTool(name string) bool {
return agentcapabilities.IsPatrolInfrastructureEvidenceToolName(name)
}
-func isSuccessfulInvestigationEvidenceResult(name, content string, isError bool) bool {
- content = strings.TrimSpace(content)
- if !isInvestigationEvidenceTool(name) || isError || content == "" {
- return false
- }
- if agentcapabilities.HasPolicyBlockedToolMarker(content) || agentcapabilities.HasApprovalRequiredToolMarker(content) {
- return false
- }
- if code, ok := agentcapabilities.ToolResultErrorCode(content); ok {
- switch code {
- case agentcapabilities.ErrCodePolicyBlocked, agentcapabilities.ErrCodeApprovalRequired:
- return false
- }
- }
- return true
-}
-
-func investigationEvidenceTools(available []providers.Tool) []providers.Tool {
- filtered := make([]providers.Tool, 0, len(available))
- for _, tool := range available {
- if isInvestigationEvidenceTool(tool.Name) {
- filtered = append(filtered, tool)
- }
- }
- return filtered
-}
-
-func applyInvestigationEvidenceStartRepairRequest(req *providers.ChatRequest, profile aitools.ExecutionProfile, available []providers.Tool) bool {
- if req == nil || !isPatrolInvestigationExecution(profile) {
- return false
- }
- evidenceTools := investigationEvidenceTools(available)
- if len(evidenceTools) == 0 {
- return false
- }
- req.Tools = evidenceTools
- req.ToolChoice = &providers.ToolChoice{Type: providers.ToolChoiceRequired}
- req.System += investigationEvidenceStartRepairSystemPrompt
- return true
-}
-
func investigationTerminalTools(available []providers.Tool) []providers.Tool {
for _, tool := range available {
if tool.Name == agentcapabilities.PatrolProposeActionToolName {
@@ -97,40 +44,3 @@ func investigationTerminalTools(available []providers.Tool) []providers.Tool {
}
return nil
}
-
-func investigationEvidenceCheckpoint(maxEvidenceCalls int) int {
- checkpoint := (maxEvidenceCalls + 1) / 2
- if checkpoint < 3 {
- return 3
- }
- return checkpoint
-}
-
-func maybeInjectInvestigationEvidenceCheckpoint(messages []providers.Message, used, remaining int) bool {
- return appendInvestigationBudgetMessage(messages, fmt.Sprintf(
- "[Patrol evidence checkpoint: %d evidence calls used, %d remain. Decide whether the evidence now supports all four completion questions: current symptom, most likely root cause or explicit uncertainty, affected scope, and a safe next action. Before concluding that root cause is unknown or proposing remediation on the symptom resource, use available canonical query, discovery, or topology evidence to test at least one plausible causal peer or dependency whenever a cross-resource cause remains plausible. Empty logs or a blocked deep-read path do not close that evidence gap. If the four questions are supported, conclude now; when the safe next action is an advertised remediation, submit it through patrol_propose_action before the final summary instead of leaving it only as prose. Otherwise spend only targeted calls on a named evidence gap.]",
- used, remaining,
- ), "checkpoint")
-}
-
-func maybeInjectInvestigationEvidenceBudgetWarning(messages []providers.Message, used, remaining int) bool {
- return appendInvestigationBudgetMessage(messages, fmt.Sprintf(
- "[Patrol evidence budget: %d evidence calls used, %d remain. Stop exploratory investigation. Use at most the remaining targeted calls. If a cross-resource cause is still plausible and no causal peer or dependency has been tested with canonical query, discovery, or topology evidence, make that the remaining evidence priority; empty logs or a blocked deep-read path are not a root-cause conclusion. If the evidence supports a safe advertised remediation, submit one typed proposal before the final summary; never leave it only as prose. Otherwise conclude with the required summary and explicit uncertainty.]",
- used, remaining,
- ), "warning")
-}
-
-func appendInvestigationBudgetMessage(messages []providers.Message, message, phase string) bool {
- for i := len(messages) - 1; i >= 0; i-- {
- if messages[i].ToolResult == nil || messages[i].ToolResult.IsError {
- continue
- }
- messages[i].ToolResult.Content += "\n\n" + message
- log.Info().
- Str("phase", phase).
- Int("message_index", i).
- Msg("[InvestigationEvidenceBudget] Injected evidence-completion guidance")
- return true
- }
- return false
-}
diff --git a/internal/ai/chat/agentic_investigation_budget_w0716_coverage_test.go b/internal/ai/chat/agentic_investigation_budget_w0716_coverage_test.go
index 0a2cb244b3..c396f64ffa 100644
--- a/internal/ai/chat/agentic_investigation_budget_w0716_coverage_test.go
+++ b/internal/ai/chat/agentic_investigation_budget_w0716_coverage_test.go
@@ -1,7 +1,6 @@
package chat
import (
- "strings"
"testing"
"github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities"
@@ -9,15 +8,6 @@ import (
"github.com/rcourtman/pulse-go-rewrite/internal/ai/tools"
)
-// msgWithResult builds a providers.Message carrying a non-nil tool result so
-// appendInvestigationBudgetMessage has something to mutate.
-func msgWithResult(id, content string, isError bool) providers.Message {
- return providers.Message{
- Role: "user",
- ToolResult: &providers.ToolResult{ToolUseID: id, Content: content, IsError: isError},
- }
-}
-
func Test_w0716_budget_IsPatrolInvestigationExecution(t *testing.T) {
tests := []struct {
name string
@@ -38,17 +28,6 @@ func Test_w0716_budget_IsPatrolInvestigationExecution(t *testing.T) {
}
}
-func TestInvestigationCompletionRequiresSupportedProposalBeforeProse(t *testing.T) {
- for name, prompt := range map[string]string{
- "budget exhausted": investigationEvidenceBudgetExhaustedSystemPrompt,
- } {
- if !strings.Contains(prompt, "must call patrol_propose_action once") ||
- !strings.Contains(prompt, "never leave that remediation only as prose") {
- t.Fatalf("%s prompt must require the governed handoff for a supported remediation: %q", name, prompt)
- }
- }
-}
-
func Test_w0716_budget_IsInvestigationEvidenceTool(t *testing.T) {
tests := []struct {
name string
@@ -108,184 +87,3 @@ func Test_w0716_budget_InvestigationTerminalTools(t *testing.T) {
})
}
}
-
-func Test_w0716_budget_InvestigationEvidenceCheckpoint(t *testing.T) {
- tests := []struct {
- name string
- max int
- want int
- }{
- {name: "zero max clamps to floor", max: 0, want: 3},
- {name: "negative max clamps to floor", max: -5, want: 3},
- {name: "max 1 clamps to floor", max: 1, want: 3},
- {name: "max 4 half-rounded-down still clamps", max: 4, want: 3},
- {name: "max 5 hits floor via normal path", max: 5, want: 3},
- {name: "max 6 still at floor", max: 6, want: 3},
- {name: "max 7 exceeds floor", max: 7, want: 4},
- {name: "max 15 halves up", max: 15, want: 8},
- {name: "large budget halves", max: 100, want: 50},
- }
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- if got := investigationEvidenceCheckpoint(tt.max); got != tt.want {
- t.Fatalf("investigationEvidenceCheckpoint(%d) = %d, want %d", tt.max, got, tt.want)
- }
- })
- }
-}
-
-func Test_w0716_budget_AppendInvestigationBudgetMessage(t *testing.T) {
- const guidance = "[budget note]"
-
- t.Run("empty messages returns false and mutates nothing", func(t *testing.T) {
- var msgs []providers.Message
- if appendInvestigationBudgetMessage(msgs, guidance, "phase") {
- t.Fatal("expected false on empty messages")
- }
- })
-
- t.Run("only nil tool results returns false", func(t *testing.T) {
- msgs := []providers.Message{
- {Role: "user", Content: "plain"},
- {Role: "assistant", Content: "prose"},
- }
- if appendInvestigationBudgetMessage(msgs, guidance, "phase") {
- t.Fatal("expected false when no message carries a tool result")
- }
- if msgs[0].Content != "plain" || msgs[1].Content != "prose" {
- t.Fatalf("non-result content was mutated: %+v", msgs)
- }
- })
-
- t.Run("only error tool results returns false", func(t *testing.T) {
- msgs := []providers.Message{msgWithResult("err-1", "boom", true)}
- if appendInvestigationBudgetMessage(msgs, guidance, "phase") {
- t.Fatal("expected false when the only result is an error")
- }
- if msgs[0].ToolResult.Content != "boom" {
- t.Fatalf("error result content was mutated: %q", msgs[0].ToolResult.Content)
- }
- })
-
- t.Run("appends guidance to the most recent non-error result only", func(t *testing.T) {
- msgs := []providers.Message{
- msgWithResult("ok-early", "early-ok", false),
- msgWithResult("err-mid", "mid-err", true),
- msgWithResult("ok-late", "late-ok", false),
- }
- if !appendInvestigationBudgetMessage(msgs, guidance, "phase") {
- t.Fatal("expected true when a non-error result exists")
- }
- wantEarly := "early-ok"
- wantLate := "late-ok" + "\n\n" + guidance
- if msgs[0].ToolResult.Content != wantEarly {
- t.Fatalf("earlier non-error result was mutated: got %q, want %q", msgs[0].ToolResult.Content, wantEarly)
- }
- if msgs[2].ToolResult.Content != wantLate {
- t.Fatalf("latest non-error result = %q, want %q", msgs[2].ToolResult.Content, wantLate)
- }
- if msgs[1].ToolResult.Content != "mid-err" {
- t.Fatalf("error result content was mutated: %q", msgs[1].ToolResult.Content)
- }
- })
-
- t.Run("skips trailing error to mutate earlier non-error result", func(t *testing.T) {
- msgs := []providers.Message{
- msgWithResult("ok-0", "first-ok", false),
- msgWithResult("err-1", "trailing-err", true),
- }
- if !appendInvestigationBudgetMessage(msgs, guidance, "phase") {
- t.Fatal("expected true when an earlier non-error result exists")
- }
- if want := "first-ok" + "\n\n" + guidance; msgs[0].ToolResult.Content != want {
- t.Fatalf("earlier result = %q, want %q", msgs[0].ToolResult.Content, want)
- }
- if msgs[1].ToolResult.Content != "trailing-err" {
- t.Fatalf("trailing error result was mutated: %q", msgs[1].ToolResult.Content)
- }
- })
-
- t.Run("mutates exactly one result when several qualify", func(t *testing.T) {
- msgs := []providers.Message{
- msgWithResult("ok-a", "a-ok", false),
- msgWithResult("ok-b", "b-ok", false),
- }
- if !appendInvestigationBudgetMessage(msgs, guidance, "phase") {
- t.Fatal("expected true")
- }
- if msgs[0].ToolResult.Content != "a-ok" {
- t.Fatalf("first qualifying result should be untouched: %q", msgs[0].ToolResult.Content)
- }
- if want := "b-ok" + "\n\n" + guidance; msgs[1].ToolResult.Content != want {
- t.Fatalf("only the last qualifying result should be mutated: got %q, want %q", msgs[1].ToolResult.Content, want)
- }
- })
-}
-
-func Test_w0716_budget_MaybeInjectInvestigationEvidenceCheckpoint(t *testing.T) {
- t.Run("injects checkpoint guidance with used and remaining counts", func(t *testing.T) {
- msgs := []providers.Message{msgWithResult("evidence-1", "raw-evidence", false)}
- if !maybeInjectInvestigationEvidenceCheckpoint(msgs, 4, 3) {
- t.Fatal("expected checkpoint injection to return true")
- }
- got := msgs[0].ToolResult.Content
- if !strings.Contains(got, "raw-evidence") {
- t.Fatalf("original content must be preserved, got %q", got)
- }
- for _, want := range []string{"4 evidence calls used", "3 remain", "checkpoint", "completion questions", "plausible causal peer or dependency", "Empty logs or a blocked deep-read path"} {
- if !strings.Contains(got, want) {
- t.Fatalf("checkpoint content missing %q: %q", want, got)
- }
- }
- if !strings.HasPrefix(got, "raw-evidence\n\n") {
- t.Fatalf("guidance must be appended after a blank line, got %q", got)
- }
- })
-
- t.Run("returns false when no injectable result exists", func(t *testing.T) {
- msgs := []providers.Message{
- {Role: "user", Content: "no result here"},
- msgWithResult("err", "boom", true),
- }
- if maybeInjectInvestigationEvidenceCheckpoint(msgs, 1, 0) {
- t.Fatal("expected false when no non-error tool result is present")
- }
- if msgs[1].ToolResult.Content != "boom" {
- t.Fatalf("error result must not be mutated: %q", msgs[1].ToolResult.Content)
- }
- })
-}
-
-func Test_w0716_budget_MaybeInjectInvestigationEvidenceBudgetWarning(t *testing.T) {
- t.Run("injects budget warning with used and remaining counts", func(t *testing.T) {
- msgs := []providers.Message{
- msgWithResult("evidence-early", "first", false),
- msgWithResult("evidence-late", "second", false),
- }
- if !maybeInjectInvestigationEvidenceBudgetWarning(msgs, 9, 1) {
- t.Fatal("expected warning injection to return true")
- }
- if msgs[0].ToolResult.Content != "first" {
- t.Fatalf("earlier result must be untouched, got %q", msgs[0].ToolResult.Content)
- }
- got := msgs[1].ToolResult.Content
- for _, want := range []string{"9 evidence calls used", "1 remain", "budget", "Stop exploratory investigation", "causal peer or dependency", "typed proposal"} {
- if !strings.Contains(got, want) {
- t.Fatalf("warning content missing %q: %q", want, got)
- }
- }
- })
-
- t.Run("returns false on empty messages", func(t *testing.T) {
- if maybeInjectInvestigationEvidenceBudgetWarning(nil, 5, 0) {
- t.Fatal("expected false on empty messages")
- }
- })
-
- t.Run("returns false when all results are errors", func(t *testing.T) {
- msgs := []providers.Message{msgWithResult("e1", "err1", true), msgWithResult("e2", "err2", true)}
- if maybeInjectInvestigationEvidenceBudgetWarning(msgs, 5, 0) {
- t.Fatal("expected false when every result is an error")
- }
- })
-}
diff --git a/internal/ai/chat/agentic_wrapup.go b/internal/ai/chat/agentic_wrapup.go
deleted file mode 100644
index 9068d9067d..0000000000
--- a/internal/ai/chat/agentic_wrapup.go
+++ /dev/null
@@ -1,56 +0,0 @@
-package chat
-
-import (
- "fmt"
-
- "github.com/rcourtman/pulse-go-rewrite/internal/ai/providers"
- "github.com/rs/zerolog/log"
-)
-
-// maybeInjectWrapUpNudge appends a system hint to the last non-error tool result in
-// providerMessages when totalCalls exceeds the threshold. This nudges the model to
-// start wrapping up without forcing text-only mode.
-// Returns true if a nudge was injected.
-func maybeInjectWrapUpNudge(messages []providers.Message, totalCalls, maxTurns, currentTurn, threshold int) bool {
- if totalCalls < threshold {
- return false
- }
-
- turnsRemaining := maxTurns - currentTurn - 1
- nudge := fmt.Sprintf("\n\n[System: You have made %d tool calls (%d turns remaining). You likely have enough data to answer. Start forming your response. You may make 1-2 more targeted calls if critical information is missing, but avoid exploratory calls.]",
- totalCalls, turnsRemaining)
-
- // Find the last non-error tool result in messages and append the nudge
- for i := len(messages) - 1; i >= 0; i-- {
- if messages[i].ToolResult != nil && !messages[i].ToolResult.IsError {
- messages[i].ToolResult.Content += nudge
- log.Info().
- Int("total_calls", totalCalls).
- Int("turns_remaining", turnsRemaining).
- Int("message_index", i).
- Msg("[WrapUpNudge] Injected wrap-up nudge into tool result")
- return true
- }
- }
- return false
-}
-
-// maybeInjectWrapUpEscalation appends a strong wrap-up directive to the last non-error
-// tool result. Called once when the model ignores the initial nudge and reaches 18+ calls.
-// Returns true if an escalation was injected.
-func maybeInjectWrapUpEscalation(messages []providers.Message, totalCalls int) bool {
- escalation := fmt.Sprintf("\n\n[System: WRAP UP NOW. You have made %d tool calls — well past the recommended limit. You MUST respond with your findings on this turn. Do NOT make any more tool calls.]",
- totalCalls)
-
- for i := len(messages) - 1; i >= 0; i-- {
- if messages[i].ToolResult != nil && !messages[i].ToolResult.IsError {
- messages[i].ToolResult.Content += escalation
- log.Info().
- Int("total_calls", totalCalls).
- Int("message_index", i).
- Msg("[WrapUpEscalation] Injected wrap-up escalation into tool result")
- return true
- }
- }
- return false
-}
diff --git a/internal/ai/chat/compaction_test.go b/internal/ai/chat/compaction_test.go
index 13f13baa8e..728966816d 100644
--- a/internal/ai/chat/compaction_test.go
+++ b/internal/ai/chat/compaction_test.go
@@ -408,103 +408,6 @@ func TestCompactOldToolResults_WithKAFacts(t *testing.T) {
assert.Contains(t, msgs[2].ToolResult.Content, "80% used")
}
-func TestMaybeInjectWrapUpNudge(t *testing.T) {
- msgs := []providers.Message{
- {Role: "user", Content: "check everything"},
- makeAssistantMessageWithToolCalls("",
- providers.ToolCall{ID: "tc1", Name: "pulse_query", Input: map[string]interface{}{"type": "topology"}},
- ),
- makeToolResultMessage("tc1", "some result data", false),
- }
-
- // Above threshold: should inject nudge
- injected := maybeInjectWrapUpNudge(msgs, 13, 20, 5, 12)
- assert.True(t, injected)
- assert.Contains(t, msgs[2].ToolResult.Content, "[System: You have made 13 tool calls")
- assert.Contains(t, msgs[2].ToolResult.Content, "14 turns remaining")
- assert.Contains(t, msgs[2].ToolResult.Content, "Start forming your response")
-}
-
-func TestMaybeInjectWrapUpNudge_NotInjectedBelowThreshold(t *testing.T) {
- msgs := []providers.Message{
- {Role: "user", Content: "check something"},
- makeAssistantMessageWithToolCalls("",
- providers.ToolCall{ID: "tc1", Name: "pulse_query", Input: map[string]interface{}{}},
- ),
- makeToolResultMessage("tc1", "result", false),
- }
-
- originalContent := msgs[2].ToolResult.Content
- injected := maybeInjectWrapUpNudge(msgs, 5, 20, 2, 12)
- assert.False(t, injected)
- assert.Equal(t, originalContent, msgs[2].ToolResult.Content, "content should not be modified below threshold")
-}
-
-func TestMaybeInjectWrapUpNudge_SkipsErrorResults(t *testing.T) {
- msgs := []providers.Message{
- makeToolResultMessage("tc1", "good result", false),
- makeToolResultMessage("tc2", "error result", true), // Last result is an error
- }
-
- injected := maybeInjectWrapUpNudge(msgs, 15, 20, 5, 12)
- assert.True(t, injected)
- // Should inject into tc1 (the last non-error result), not tc2
- assert.Contains(t, msgs[0].ToolResult.Content, "[System:")
- assert.NotContains(t, msgs[1].ToolResult.Content, "[System:")
-}
-
-func TestWrapUpNudge_FiresOnce(t *testing.T) {
- // Simulate calling maybeInjectWrapUpNudge twice above threshold.
- // Only the first call should inject text (caller gates with wrapUpNudgeFired).
- msgs := []providers.Message{
- makeToolResultMessage("tc1", "result data", false),
- }
-
- // First call: should inject
- injected := maybeInjectWrapUpNudge(msgs, 13, 20, 5, 12)
- assert.True(t, injected)
- assert.Contains(t, msgs[0].ToolResult.Content, "[System: You have made 13 tool calls")
-
- // Record content after first injection
- contentAfterFirst := msgs[0].ToolResult.Content
-
- // Second call: the function itself always injects if above threshold,
- // but the agentic loop gates it with wrapUpNudgeFired. Verify that
- // calling it again would add a second nudge (showing why the gate matters).
- injected2 := maybeInjectWrapUpNudge(msgs, 15, 20, 7, 12)
- assert.True(t, injected2)
- // Content changed — this proves the agentic loop gate is necessary
- assert.NotEqual(t, contentAfterFirst, msgs[0].ToolResult.Content)
-}
-
-func TestWrapUpNudge_Escalation(t *testing.T) {
- // Verify escalation fires at 18+ calls with stronger text.
- msgs := []providers.Message{
- makeToolResultMessage("tc1", "some data", false),
- }
-
- // Escalation should NOT fire below 18 (it's gated in the loop, but test the function)
- injected := maybeInjectWrapUpEscalation(msgs, 18)
- assert.True(t, injected)
- assert.Contains(t, msgs[0].ToolResult.Content, "WRAP UP NOW")
- assert.Contains(t, msgs[0].ToolResult.Content, "18 tool calls")
- assert.Contains(t, msgs[0].ToolResult.Content, "MUST respond")
- assert.Contains(t, msgs[0].ToolResult.Content, "Do NOT make any more tool calls")
-}
-
-func TestWrapUpEscalation_SkipsErrorResults(t *testing.T) {
- msgs := []providers.Message{
- makeToolResultMessage("tc1", "good result", false),
- makeToolResultMessage("tc2", "error result", true),
- }
-
- injected := maybeInjectWrapUpEscalation(msgs, 20)
- assert.True(t, injected)
- // Should inject into tc1 (last non-error), not tc2
- assert.Contains(t, msgs[0].ToolResult.Content, "WRAP UP NOW")
- assert.NotContains(t, msgs[1].ToolResult.Content, "WRAP UP NOW")
-}
-
func TestTruncateToolResultForModel_ReducedLimit(t *testing.T) {
// Verify the limit is now 16000
assert.Equal(t, 16000, MaxToolResultCharsLimit, "MaxToolResultCharsLimit should be 16000")
diff --git a/internal/ai/chat/service_tooling_test.go b/internal/ai/chat/service_tooling_test.go
index d834d25ebc..6b263b4c24 100644
--- a/internal/ai/chat/service_tooling_test.go
+++ b/internal/ai/chat/service_tooling_test.go
@@ -1236,8 +1236,6 @@ func TestInvestigationLoopRedactsProposalParamsEverywhereDurable(t *testing.T) {
loop := NewAgenticLoop(provider, exec, "base prompt")
loop.SetExecutionProfile(tools.ProfilePatrolInvestigation)
- loop.totalEvidenceCalls = 1
- loop.successfulEvidenceCalls = 1
var streamedRawParam bool
var streamedConclusion strings.Builder
diff --git a/scripts/check-patrol-assistant-journey.mjs b/scripts/check-patrol-assistant-journey.mjs
index 73bc0ab6cd..df417be86e 100644
--- a/scripts/check-patrol-assistant-journey.mjs
+++ b/scripts/check-patrol-assistant-journey.mjs
@@ -4,7 +4,8 @@ import {
chromium,
expect,
} from "../tests/integration/node_modules/@playwright/test/index.mjs";
-import { mkdir, writeFile } from "node:fs/promises";
+import { mkdir, readFile, writeFile } from "node:fs/promises";
+import { createHash } from "node:crypto";
const base = process.env.PLAYWRIGHT_BASE_URL || "http://127.0.0.1:5173";
const output = new URL("../tmp/patrol-assistant-journey/", import.meta.url);
await mkdir(output, { recursive: true });
@@ -70,6 +71,67 @@ const detail = (item) => ({
},
],
});
+// Completed execution is deliberately paired with an unresolved diagnosis.
+const uncertainConclusion =
+ "The cause remains unknown. Host access is unavailable. No action was performed.";
+const failedRead =
+ "Host agent unavailable. The requested logs could not be collected.";
+let investigationFixture = false;
+const investigation = {
+ id: "investigation-proof",
+ finding_id: "finding-proof",
+ session_id: "investigation-session",
+ status: "completed",
+ outcome: "needs_attention",
+ started_at: now,
+ completed_at: now,
+ turn_count: 2,
+ summary: uncertainConclusion,
+ tools_used: ["pulse_read"],
+};
+const finding = {
+ id: "finding-proof",
+ resource_id: resourceId,
+ resource_name: "Database VM",
+ resource_type: "vm",
+ severity: "warning",
+ category: "capacity",
+ title: "Disk pressure with unknown cause",
+ description: "The disk is 95 percent full. The source of growth is unknown.",
+ evidence: "Disk usage is 95 percent.",
+ recommendation: "Restore read access before deciding on a change.",
+ detected_at: now,
+ last_seen_at: now,
+ auto_resolved: false,
+ times_raised: 1,
+ suppressed: false,
+ mirrors_alert_id: "alert-proof",
+ mirrors_alert_type: "disk",
+ investigation_status: "completed",
+ investigation_outcome: "needs_attention",
+ investigation_session_id: investigation.session_id,
+ investigation_attempts: 1,
+ investigation_record: {
+ id: investigation.id,
+ finding_id: "finding-proof",
+ status: "completed",
+ outcome: "needs_attention",
+ subject: {
+ resource_id: resourceId,
+ resource_name: "Database VM",
+ resource_type: "vm",
+ },
+ trigger: { title: "Disk pressure with unknown cause", detected_at: now },
+ confidence: "low",
+ conclusion: uncertainConclusion,
+ evidence: [{ kind: "tool_error", summary: failedRead }],
+ tools_used: ["pulse_read"],
+ started_at: now,
+ completed_at: now,
+ verification: [],
+ rollback: [],
+ },
+};
const browser = await chromium.launch({ headless: true });
const context = await browser.newContext();
const page = await context.newPage();
@@ -93,7 +155,9 @@ const reply = async (route, failure = false) =>
{ type: "session", data: { id: "explanation-proof" } },
{
type: "content",
- data: "The database disk is 95 percent full. Check the recent growth before choosing a change. No changes were made.",
+ data: investigationFixture
+ ? uncertainConclusion
+ : "The database disk is 95 percent full. Check the recent growth before choosing a change. No changes were made.",
},
{ type: "done", data: { session_id: "explanation-proof" } },
]
@@ -130,6 +194,55 @@ try {
json: { error: "Writes disabled in journey proof" },
});
}
+ if (investigationFixture) {
+ if (path === "/api/ai/patrol/findings")
+ return route.fulfill({ json: [finding] });
+ if (path === "/api/ai/unified/findings")
+ return route.fulfill({ json: { findings: [] } });
+ if (path === `/api/ai/findings/${finding.id}/investigation`)
+ return route.fulfill({ json: investigation });
+ if (path === `/api/ai/findings/${finding.id}/investigation/messages`)
+ return route.fulfill({
+ json: {
+ investigation_id: investigation.id,
+ session_id: investigation.session_id,
+ messages: [
+ {
+ id: "read",
+ role: "assistant",
+ content: "",
+ timestamp: now,
+ tool_calls: [
+ {
+ id: "read-1",
+ name: "pulse_read",
+ input: {
+ command: "journalctl --no-pager",
+ target_host: "Database VM",
+ },
+ },
+ ],
+ },
+ {
+ id: "read-result",
+ role: "user",
+ timestamp: now,
+ tool_result: {
+ tool_use_id: "read-1",
+ content: failedRead,
+ is_error: true,
+ },
+ },
+ {
+ id: "conclusion",
+ role: "assistant",
+ content: uncertainConclusion,
+ timestamp: now,
+ },
+ ],
+ },
+ });
+ }
if (path === "/api/ai/status")
return route.fulfill({ json: { running: true } });
if (path === "/api/ai/settings")
@@ -251,11 +364,15 @@ try {
for (const width of [1440, 390]) {
await page.setViewportSize({ width, height: 1000 });
await page.goto(`${base}/alerts`, { waitUntil: "domcontentloaded" });
- const menu = page.getByRole("button", { name: "More alert actions", exact: true }).first();
+ const menu = page
+ .getByRole("button", { name: "More alert actions", exact: true })
+ .first();
await expect(menu).toBeVisible({ timeout: 20000 });
await menu.click();
await expect(page.getByRole("menuitem")).toBeVisible();
- await page.screenshot({ path: new URL(`alert-menu-${width}.png`, output).pathname });
+ await page.screenshot({
+ path: new URL(`alert-menu-${width}.png`, output).pathname,
+ });
await page.keyboard.press("Escape");
await expect(page.getByRole("menuitem")).toHaveCount(0);
await menu.click();
@@ -265,13 +382,119 @@ try {
const before = requests.length;
await page.getByRole("menuitem").click();
await expect.poll(() => requests.length).toBe(before + 1);
- expect(requests.at(-1).handoff_context).toContain("Source: Pulse Alerts active alert");
+ expect(requests.at(-1).handoff_context).toContain(
+ "Source: Pulse Alerts active alert",
+ );
expect(requests.at(-1).handoff_resources.length).toBeGreaterThan(0);
expect(requests.at(-1).autonomous_mode).toBe(false);
- await expect(page.getByText("No changes were made.", { exact: false })).toBeVisible();
+ await expect(
+ page.getByText("No changes were made.", { exact: false }),
+ ).toBeVisible();
await expect(page.getByRole("menuitem")).toHaveCount(0);
- await page.screenshot({ path: new URL(`alert-explanation-${width}.png`, output).pathname });
- results.push({ width, state: "alert menu, Escape, outside click, selected alert explanation" });
+ await page.screenshot({
+ path: new URL(`alert-explanation-${width}.png`, output).pathname,
+ });
+ results.push({
+ width,
+ state: "alert menu, Escape, outside click, selected alert explanation",
+ });
+ }
+ investigationFixture = true;
+ for (const mirrored of [false, true]) {
+ finding.mirrors_alert_id = mirrored ? "alert-proof" : undefined;
+ finding.mirrors_alert_type = mirrored ? "disk" : undefined;
+ for (const width of [1440, 900, 390]) {
+ await page.setViewportSize({ width, height: 1000 });
+ await page.goto(`${base}/patrol`, { waitUntil: "domcontentloaded" });
+ await page.getByRole("tab", { name: "Activity", exact: true }).click();
+ await page
+ .getByRole("button", { name: /Finding options and history/ })
+ .click();
+ if (mirrored)
+ await page
+ .getByText("1 finding mirrors an active alert", { exact: true })
+ .click();
+ const review = page.getByRole("button", {
+ name: `Review issue for ${finding.title}`,
+ exact: true,
+ });
+ await review.scrollIntoViewIfNeeded();
+ await review.focus();
+ await review.press("Enter");
+ const panel = page.locator(`#finding-${finding.id}-details`);
+ await expect(
+ panel.getByText(uncertainConclusion, { exact: true }).first(),
+ ).toBeVisible();
+ await expect(panel.getByText(failedRead, { exact: true })).toBeVisible();
+ await expect(panel.getByText("Resolved", { exact: true })).toHaveCount(0);
+ const thread = page.getByRole("button", {
+ name: "Show investigation thread",
+ exact: true,
+ });
+ await thread.scrollIntoViewIfNeeded();
+ await thread.focus();
+ await thread.press("Enter");
+ await expect(panel.getByText("Error", { exact: true })).toBeVisible();
+ await expect(
+ panel.getByText(failedRead, { exact: true }).last(),
+ ).toBeVisible();
+ await panel
+ .getByText(uncertainConclusion, { exact: true })
+ .last()
+ .scrollIntoViewIfNeeded();
+ await page.screenshot({
+ path: new URL(
+ `investigation-unknown-${mirrored ? "mirrored" : "ordinary"}-${width}.png`,
+ output,
+ ).pathname,
+ });
+ await page
+ .getByRole("button", { name: "Hide investigation thread", exact: true })
+ .click();
+ await expect(panel.getByText("Error", { exact: true })).toHaveCount(0);
+ await page
+ .getByRole("button", {
+ name: `Close review for ${finding.title}`,
+ exact: true,
+ })
+ .click();
+ await expect(panel).toHaveCount(0);
+ if (mirrored) {
+ await page.getByRole("tab", { name: "Inbox", exact: true }).click();
+ await page
+ .getByRole("button", { name: "Start review", exact: true })
+ .click();
+ const explain = page.getByRole("button", {
+ name: "Explain with Assistant",
+ exact: true,
+ });
+ const before = requests.length;
+ await explain.scrollIntoViewIfNeeded();
+ await explain.focus();
+ await explain.press("Enter");
+ await expect.poll(() => requests.length).toBe(before + 1);
+ expect(requests.at(-1).handoff_context).toContain(finding.id);
+ expect(requests.at(-1).handoff_context).toContain(uncertainConclusion);
+ expect(requests.at(-1).handoff_context).toContain(failedRead);
+ expect(requests.at(-1).autonomous_mode).toBe(false);
+ await expect(
+ page
+ .getByTestId("assistant-message-list")
+ .getByText(uncertainConclusion, { exact: true }),
+ ).toBeVisible();
+ await page.screenshot({
+ path: new URL(`investigation-handoff-${width}.png`, output).pathname,
+ });
+ await page.keyboard.press("Escape");
+ }
+ results.push({
+ width,
+ mirrored,
+ state:
+ "Activity finding, keyboard review, completed but unresolved record, failed read, investigation transcript, collapse",
+ linkedAssistantHandoff: mirrored,
+ });
+ }
}
// No background inference after a reload or context-only drawer open.
const beforeReload = requests.length;
@@ -280,11 +503,26 @@ try {
expect(requests.length).toBe(beforeReload);
expect(mutations).toEqual([]);
expect(errors).toEqual([]);
+ const sourceHashes = {};
+ for (const path of [
+ "internal/ai/chat/agentic.go",
+ "internal/ai/chat/agentic_investigation_budget.go",
+ "scripts/check-patrol-assistant-journey.mjs",
+ "frontend-modern/src/components/AI/FindingsPanel.tsx",
+ "frontend-modern/src/components/patrol/InvestigationSection.tsx",
+ "frontend-modern/src/components/patrol/InvestigationMessages.tsx",
+ ]) {
+ sourceHashes[path] = createHash("sha256")
+ .update(await readFile(new URL(`../${path}`, import.meta.url)))
+ .digest("hex");
+ }
await writeFile(
new URL("result.json", output),
JSON.stringify(
{
passed: true,
+ at: new Date().toISOString(),
+ sourceHashes,
base,
results,
requestCount: requests.length,
diff --git a/scripts/release_control/canonical_completion_guard_test.py b/scripts/release_control/canonical_completion_guard_test.py
index 3695de37ca..08bfcc31d6 100644
--- a/scripts/release_control/canonical_completion_guard_test.py
+++ b/scripts/release_control/canonical_completion_guard_test.py
@@ -2698,6 +2698,7 @@ None yet.
"allow_same_subsystem_tests": False,
"test_prefixes": [],
"exact_files": [
+ "frontend-modern/src/components/AI/__tests__/FindingsPanel.links.test.tsx",
"frontend-modern/src/components/AI/__tests__/FindingsPanel.test.ts",
"frontend-modern/src/components/patrol/__tests__/ApprovalSection.test.tsx",
"frontend-modern/src/components/patrol/__tests__/InvestigationSection.test.tsx",
diff --git a/scripts/release_control/subsystem_lookup_test.py b/scripts/release_control/subsystem_lookup_test.py
index 20edc6c425..5823d4d787 100644
--- a/scripts/release_control/subsystem_lookup_test.py
+++ b/scripts/release_control/subsystem_lookup_test.py
@@ -3334,6 +3334,7 @@ class SubsystemLookupTest(unittest.TestCase):
self.assertEqual(
match["verification_requirement"]["exact_files"],
[
+ "frontend-modern/src/components/AI/__tests__/FindingsPanel.links.test.tsx",
"frontend-modern/src/components/AI/__tests__/FindingsPanel.test.ts",
"frontend-modern/src/components/patrol/__tests__/ApprovalSection.test.tsx",
"frontend-modern/src/components/patrol/__tests__/InvestigationSection.test.tsx",
@@ -3365,6 +3366,7 @@ class SubsystemLookupTest(unittest.TestCase):
self.assertEqual(
match["verification_requirement"]["exact_files"],
[
+ "frontend-modern/src/components/AI/__tests__/FindingsPanel.links.test.tsx",
"frontend-modern/src/components/AI/__tests__/FindingsPanel.test.ts",
"frontend-modern/src/components/patrol/__tests__/ApprovalSection.test.tsx",
"frontend-modern/src/components/patrol/__tests__/InvestigationSection.test.tsx",