@rlynjb/aptkit-core 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (132) hide show
  1. package/README.md +19 -0
  2. package/dist/src/index.d.ts +12 -0
  3. package/dist/src/index.js +9 -0
  4. package/node_modules/@aptkit/agent-anomaly-monitoring/README.md +13 -0
  5. package/node_modules/@aptkit/agent-anomaly-monitoring/dist/src/categories.d.ts +11 -0
  6. package/node_modules/@aptkit/agent-anomaly-monitoring/dist/src/categories.js +100 -0
  7. package/node_modules/@aptkit/agent-anomaly-monitoring/dist/src/fixture-provider.d.ts +10 -0
  8. package/node_modules/@aptkit/agent-anomaly-monitoring/dist/src/fixture-provider.js +18 -0
  9. package/node_modules/@aptkit/agent-anomaly-monitoring/dist/src/index.d.ts +6 -0
  10. package/node_modules/@aptkit/agent-anomaly-monitoring/dist/src/index.js +6 -0
  11. package/node_modules/@aptkit/agent-anomaly-monitoring/dist/src/monitoring-agent.d.ts +32 -0
  12. package/node_modules/@aptkit/agent-anomaly-monitoring/dist/src/monitoring-agent.js +88 -0
  13. package/node_modules/@aptkit/agent-anomaly-monitoring/dist/src/schema-summary.d.ts +2 -0
  14. package/node_modules/@aptkit/agent-anomaly-monitoring/dist/src/schema-summary.js +7 -0
  15. package/node_modules/@aptkit/agent-anomaly-monitoring/dist/src/types.d.ts +32 -0
  16. package/node_modules/@aptkit/agent-anomaly-monitoring/dist/src/types.js +1 -0
  17. package/node_modules/@aptkit/agent-anomaly-monitoring/dist/src/validate.d.ts +9 -0
  18. package/node_modules/@aptkit/agent-anomaly-monitoring/dist/src/validate.js +34 -0
  19. package/node_modules/@aptkit/agent-anomaly-monitoring/fixtures/promoted/sp-revenue-monitoring-fixture-promoted-2026-06-18-18-37-26.json +229 -0
  20. package/node_modules/@aptkit/agent-anomaly-monitoring/fixtures/sp-revenue-monitoring.json +136 -0
  21. package/node_modules/@aptkit/agent-anomaly-monitoring/package.json +33 -0
  22. package/node_modules/@aptkit/agent-diagnostic-investigation/README.md +11 -0
  23. package/node_modules/@aptkit/agent-diagnostic-investigation/dist/src/diagnostic-agent.d.ts +27 -0
  24. package/node_modules/@aptkit/agent-diagnostic-investigation/dist/src/diagnostic-agent.js +95 -0
  25. package/node_modules/@aptkit/agent-diagnostic-investigation/dist/src/fixture-provider.d.ts +10 -0
  26. package/node_modules/@aptkit/agent-diagnostic-investigation/dist/src/fixture-provider.js +18 -0
  27. package/node_modules/@aptkit/agent-diagnostic-investigation/dist/src/index.d.ts +5 -0
  28. package/node_modules/@aptkit/agent-diagnostic-investigation/dist/src/index.js +5 -0
  29. package/node_modules/@aptkit/agent-diagnostic-investigation/dist/src/schema-summary.d.ts +1 -0
  30. package/node_modules/@aptkit/agent-diagnostic-investigation/dist/src/schema-summary.js +1 -0
  31. package/node_modules/@aptkit/agent-diagnostic-investigation/dist/src/types.d.ts +37 -0
  32. package/node_modules/@aptkit/agent-diagnostic-investigation/dist/src/types.js +1 -0
  33. package/node_modules/@aptkit/agent-diagnostic-investigation/dist/src/validate.d.ts +10 -0
  34. package/node_modules/@aptkit/agent-diagnostic-investigation/dist/src/validate.js +49 -0
  35. package/node_modules/@aptkit/agent-diagnostic-investigation/fixtures/promoted/sp-revenue-diagnostic-fixture-promoted-2026-06-18-19-04-28.json +230 -0
  36. package/node_modules/@aptkit/agent-diagnostic-investigation/fixtures/sp-revenue-diagnostic.json +148 -0
  37. package/node_modules/@aptkit/agent-diagnostic-investigation/package.json +33 -0
  38. package/node_modules/@aptkit/agent-query/README.md +11 -0
  39. package/node_modules/@aptkit/agent-query/dist/src/fixture-provider.d.ts +10 -0
  40. package/node_modules/@aptkit/agent-query/dist/src/fixture-provider.js +18 -0
  41. package/node_modules/@aptkit/agent-query/dist/src/index.d.ts +6 -0
  42. package/node_modules/@aptkit/agent-query/dist/src/index.js +6 -0
  43. package/node_modules/@aptkit/agent-query/dist/src/intent.d.ts +6 -0
  44. package/node_modules/@aptkit/agent-query/dist/src/intent.js +23 -0
  45. package/node_modules/@aptkit/agent-query/dist/src/query-agent.d.ts +27 -0
  46. package/node_modules/@aptkit/agent-query/dist/src/query-agent.js +81 -0
  47. package/node_modules/@aptkit/agent-query/dist/src/schema-summary.d.ts +1 -0
  48. package/node_modules/@aptkit/agent-query/dist/src/schema-summary.js +1 -0
  49. package/node_modules/@aptkit/agent-query/dist/src/types.d.ts +5 -0
  50. package/node_modules/@aptkit/agent-query/dist/src/types.js +1 -0
  51. package/node_modules/@aptkit/agent-query/dist/src/validate.d.ts +7 -0
  52. package/node_modules/@aptkit/agent-query/dist/src/validate.js +9 -0
  53. package/node_modules/@aptkit/agent-query/fixtures/promoted/revenue-by-state-query-fixture-promoted-2026-06-18-19-29-11.json +138 -0
  54. package/node_modules/@aptkit/agent-query/fixtures/revenue-by-state-query.json +79 -0
  55. package/node_modules/@aptkit/agent-query/package.json +33 -0
  56. package/node_modules/@aptkit/agent-recommendation/README.md +109 -0
  57. package/node_modules/@aptkit/agent-recommendation/dist/src/fixture-provider.d.ts +10 -0
  58. package/node_modules/@aptkit/agent-recommendation/dist/src/fixture-provider.js +18 -0
  59. package/node_modules/@aptkit/agent-recommendation/dist/src/index.d.ts +4 -0
  60. package/node_modules/@aptkit/agent-recommendation/dist/src/index.js +4 -0
  61. package/node_modules/@aptkit/agent-recommendation/dist/src/recommendation-agent.d.ts +30 -0
  62. package/node_modules/@aptkit/agent-recommendation/dist/src/recommendation-agent.js +85 -0
  63. package/node_modules/@aptkit/agent-recommendation/dist/src/schema-summary.d.ts +1 -0
  64. package/node_modules/@aptkit/agent-recommendation/dist/src/schema-summary.js +1 -0
  65. package/node_modules/@aptkit/agent-recommendation/dist/src/types.d.ts +68 -0
  66. package/node_modules/@aptkit/agent-recommendation/dist/src/types.js +3 -0
  67. package/node_modules/@aptkit/agent-recommendation/dist/src/validate.d.ts +3 -0
  68. package/node_modules/@aptkit/agent-recommendation/dist/src/validate.js +54 -0
  69. package/node_modules/@aptkit/agent-recommendation/fixtures/electronics-spike.json +84 -0
  70. package/node_modules/@aptkit/agent-recommendation/fixtures/promoted/voucher-dropoff-w10-on-openai-promoted-2026-06-18-16-53-02.json +166 -0
  71. package/node_modules/@aptkit/agent-recommendation/fixtures/promoted/voucher-dropoff-w10-on-openai-promoted-2026-06-18-17-20-55.json +157 -0
  72. package/node_modules/@aptkit/agent-recommendation/fixtures/sp-revenue-drop.json +83 -0
  73. package/node_modules/@aptkit/agent-recommendation/fixtures/voucher-dropoff.json +84 -0
  74. package/node_modules/@aptkit/agent-recommendation/package.json +34 -0
  75. package/node_modules/@aptkit/context/README.md +15 -0
  76. package/node_modules/@aptkit/context/dist/src/index.d.ts +2 -0
  77. package/node_modules/@aptkit/context/dist/src/index.js +2 -0
  78. package/node_modules/@aptkit/context/dist/src/workspace-descriptor.d.ts +25 -0
  79. package/node_modules/@aptkit/context/dist/src/workspace-descriptor.js +1 -0
  80. package/node_modules/@aptkit/context/dist/src/workspace-summary.d.ts +9 -0
  81. package/node_modules/@aptkit/context/dist/src/workspace-summary.js +38 -0
  82. package/node_modules/@aptkit/context/package.json +24 -0
  83. package/node_modules/@aptkit/evals/dist/src/assertions.d.ts +13 -0
  84. package/node_modules/@aptkit/evals/dist/src/assertions.js +351 -0
  85. package/node_modules/@aptkit/evals/dist/src/detection-scorer.d.ts +25 -0
  86. package/node_modules/@aptkit/evals/dist/src/detection-scorer.js +72 -0
  87. package/node_modules/@aptkit/evals/dist/src/index.d.ts +3 -0
  88. package/node_modules/@aptkit/evals/dist/src/index.js +3 -0
  89. package/node_modules/@aptkit/evals/dist/src/replay-runner.d.ts +29 -0
  90. package/node_modules/@aptkit/evals/dist/src/replay-runner.js +72 -0
  91. package/node_modules/@aptkit/evals/dist/src/structural-diff.d.ts +50 -0
  92. package/node_modules/@aptkit/evals/dist/src/structural-diff.js +143 -0
  93. package/node_modules/@aptkit/evals/package.json +27 -0
  94. package/node_modules/@aptkit/prompts/README.md +7 -0
  95. package/node_modules/@aptkit/prompts/dist/src/diagnostic.d.ts +3 -0
  96. package/node_modules/@aptkit/prompts/dist/src/diagnostic.js +85 -0
  97. package/node_modules/@aptkit/prompts/dist/src/index.d.ts +5 -0
  98. package/node_modules/@aptkit/prompts/dist/src/index.js +5 -0
  99. package/node_modules/@aptkit/prompts/dist/src/monitoring.d.ts +3 -0
  100. package/node_modules/@aptkit/prompts/dist/src/monitoring.js +57 -0
  101. package/node_modules/@aptkit/prompts/dist/src/query.d.ts +3 -0
  102. package/node_modules/@aptkit/prompts/dist/src/query.js +86 -0
  103. package/node_modules/@aptkit/prompts/dist/src/recommendation.d.ts +3 -0
  104. package/node_modules/@aptkit/prompts/dist/src/recommendation.js +110 -0
  105. package/node_modules/@aptkit/prompts/dist/src/types.d.ts +21 -0
  106. package/node_modules/@aptkit/prompts/dist/src/types.js +6 -0
  107. package/node_modules/@aptkit/prompts/package.json +24 -0
  108. package/node_modules/@aptkit/runtime/dist/src/events.d.ts +44 -0
  109. package/node_modules/@aptkit/runtime/dist/src/events.js +3 -0
  110. package/node_modules/@aptkit/runtime/dist/src/index.d.ts +6 -0
  111. package/node_modules/@aptkit/runtime/dist/src/index.js +6 -0
  112. package/node_modules/@aptkit/runtime/dist/src/json-output.d.ts +10 -0
  113. package/node_modules/@aptkit/runtime/dist/src/json-output.js +32 -0
  114. package/node_modules/@aptkit/runtime/dist/src/model-provider.d.ts +49 -0
  115. package/node_modules/@aptkit/runtime/dist/src/model-provider.js +1 -0
  116. package/node_modules/@aptkit/runtime/dist/src/ndjson-stream.d.ts +43 -0
  117. package/node_modules/@aptkit/runtime/dist/src/ndjson-stream.js +128 -0
  118. package/node_modules/@aptkit/runtime/dist/src/run-agent-loop.d.ts +42 -0
  119. package/node_modules/@aptkit/runtime/dist/src/run-agent-loop.js +138 -0
  120. package/node_modules/@aptkit/runtime/dist/src/usage-ledger.d.ts +29 -0
  121. package/node_modules/@aptkit/runtime/dist/src/usage-ledger.js +61 -0
  122. package/node_modules/@aptkit/runtime/package.json +23 -0
  123. package/node_modules/@aptkit/tools/dist/src/coverage-gate.d.ts +32 -0
  124. package/node_modules/@aptkit/tools/dist/src/coverage-gate.js +43 -0
  125. package/node_modules/@aptkit/tools/dist/src/index.d.ts +3 -0
  126. package/node_modules/@aptkit/tools/dist/src/index.js +3 -0
  127. package/node_modules/@aptkit/tools/dist/src/tool-policy.d.ts +9 -0
  128. package/node_modules/@aptkit/tools/dist/src/tool-policy.js +11 -0
  129. package/node_modules/@aptkit/tools/dist/src/tool-registry.d.ts +27 -0
  130. package/node_modules/@aptkit/tools/dist/src/tool-registry.js +25 -0
  131. package/node_modules/@aptkit/tools/package.json +26 -0
  132. package/package.json +53 -0
@@ -0,0 +1,136 @@
1
+ {
2
+ "id": "sp-revenue-monitoring",
3
+ "description": "Detect a seeded SP revenue drop from a deterministic Olist-style monitoring fixture.",
4
+ "workspace": {
5
+ "projectId": "olist",
6
+ "projectName": "Olist Brazilian ecommerce fixture",
7
+ "events": [
8
+ { "name": "purchase", "properties": ["state", "category", "total_price"], "eventCount": 50000 },
9
+ { "name": "session_start", "properties": ["utm_source"], "eventCount": 80000 },
10
+ { "name": "checkout", "properties": ["state"], "eventCount": 35000 },
11
+ { "name": "view_item", "properties": ["category"], "eventCount": 120000 }
12
+ ],
13
+ "customerProperties": ["state", "city"],
14
+ "catalogs": [],
15
+ "totalCustomers": 125000,
16
+ "totalEvents": 285000,
17
+ "oldestTimestamp": 1764547200000,
18
+ "dataHorizon": { "from": "2025-12-01", "to": "2026-06-01", "durationDays": 182 }
19
+ },
20
+ "tools": [
21
+ {
22
+ "name": "get_metric_timeseries",
23
+ "description": "Return metric timeseries for an optional dimension.",
24
+ "inputSchema": {
25
+ "type": "object",
26
+ "properties": {
27
+ "metric": { "type": "string" },
28
+ "dimension": { "type": "string" },
29
+ "time_range": { "type": "object" },
30
+ "granularity": { "type": "string" }
31
+ },
32
+ "required": ["metric", "time_range"]
33
+ },
34
+ "result": {
35
+ "periodComparison": {
36
+ "metric": "revenue",
37
+ "dimension": "state",
38
+ "segment": "SP",
39
+ "recentWindow": { "from": "2026-05-04", "to": "2026-06-01" },
40
+ "baselineWindow": { "from": "2026-02-09", "to": "2026-05-04" },
41
+ "recentValue": 28550000,
42
+ "baselineAverage": 40800000,
43
+ "pctChange": -0.300245,
44
+ "relatedSegments": [
45
+ { "name": "RJ", "pctChange": -0.02 },
46
+ { "name": "MG", "pctChange": 0.01 }
47
+ ]
48
+ },
49
+ "points": [
50
+ { "ts": "2026-05-04", "segment": "SP", "value": 7400000 },
51
+ { "ts": "2026-05-11", "segment": "SP", "value": 7200000 },
52
+ { "ts": "2026-05-18", "segment": "SP", "value": 7050000 },
53
+ { "ts": "2026-05-25", "segment": "SP", "value": 6900000 },
54
+ { "ts": "2026-05-04", "segment": "RJ", "value": 4300000 },
55
+ { "ts": "2026-05-11", "segment": "RJ", "value": 4350000 }
56
+ ],
57
+ "totalCount": 4200
58
+ }
59
+ },
60
+ {
61
+ "name": "get_anomaly_context",
62
+ "description": "Return context for a selected anomaly window and baseline.",
63
+ "inputSchema": {
64
+ "type": "object",
65
+ "properties": {
66
+ "metric": { "type": "string" },
67
+ "dimension": { "type": "string" },
68
+ "segment": { "type": "string" },
69
+ "anomaly_window": { "type": "object" },
70
+ "baseline_window": { "type": "object" }
71
+ },
72
+ "required": ["metric", "dimension", "segment"]
73
+ },
74
+ "result": {
75
+ "anomaly_summary": {
76
+ "metric": "revenue",
77
+ "segment": "SP",
78
+ "anomaly_value": 28550000,
79
+ "baseline_avg": 40800000,
80
+ "pct_change": -0.300245
81
+ },
82
+ "related_segments": [
83
+ { "name": "RJ", "pct_change": -0.02 },
84
+ { "name": "MG", "pct_change": 0.01 }
85
+ ]
86
+ }
87
+ }
88
+ ],
89
+ "modelResponses": [
90
+ {
91
+ "content": [
92
+ {
93
+ "type": "tool_use",
94
+ "id": "tool-1",
95
+ "name": "get_metric_timeseries",
96
+ "input": {
97
+ "metric": "revenue",
98
+ "dimension": "state",
99
+ "time_range": { "from": "2026-05-04", "to": "2026-06-01" },
100
+ "granularity": "week"
101
+ }
102
+ }
103
+ ],
104
+ "usage": { "inputTokens": 900, "outputTokens": 80 },
105
+ "model": "fixture-model"
106
+ },
107
+ {
108
+ "content": [
109
+ {
110
+ "type": "tool_use",
111
+ "id": "tool-2",
112
+ "name": "get_anomaly_context",
113
+ "input": {
114
+ "metric": "revenue",
115
+ "dimension": "state",
116
+ "segment": "SP",
117
+ "anomaly_window": { "from": "2026-05-04", "to": "2026-06-01" },
118
+ "baseline_window": { "from": "2026-02-09", "to": "2026-05-04" }
119
+ }
120
+ }
121
+ ],
122
+ "usage": { "inputTokens": 760, "outputTokens": 75 },
123
+ "model": "fixture-model"
124
+ },
125
+ {
126
+ "content": [
127
+ {
128
+ "type": "text",
129
+ "text": "```json\n[{\"metric\":\"revenue\",\"category\":\"revenue_drop\",\"scope\":[\"state:SP\"],\"change\":{\"value\":30,\"direction\":\"down\",\"baseline\":\"recent 4w vs prior 12w\"},\"severity\":\"critical\",\"impact\":\"Sao Paulo revenue is down about 30% while nearby states are stable, putting the largest regional topline segment at risk if the trend continues.\",\"evidence\":[{\"tool\":\"get_anomaly_context\",\"result\":{\"segment\":\"SP\",\"pct_change\":-0.300245,\"anomaly_value\":28550000,\"baseline_avg\":40800000}}]}]\n```"
130
+ }
131
+ ],
132
+ "usage": { "inputTokens": 1020, "outputTokens": 210 },
133
+ "model": "fixture-model"
134
+ }
135
+ ]
136
+ }
@@ -0,0 +1,33 @@
1
+ {
2
+ "name": "@aptkit/agent-anomaly-monitoring",
3
+ "version": "0.0.0",
4
+ "type": "module",
5
+ "main": "./dist/src/index.js",
6
+ "types": "./dist/src/index.d.ts",
7
+ "files": [
8
+ "README.md",
9
+ "dist/src",
10
+ "fixtures"
11
+ ],
12
+ "exports": {
13
+ ".": {
14
+ "types": "./dist/src/index.d.ts",
15
+ "import": "./dist/src/index.js"
16
+ }
17
+ },
18
+ "scripts": {
19
+ "build": "tsc -p tsconfig.json",
20
+ "test": "npm run build && node --test dist/test/*.test.js",
21
+ "replay:fixture": "npm run build && node dist/scripts/replay-fixture.js",
22
+ "replay:promoted": "npm run build && node ../../../scripts/replay-promoted-fixtures.mjs --count anomalyCount --empty \"no promoted monitoring fixtures found\""
23
+ },
24
+ "dependencies": {
25
+ "@aptkit/context": "0.0.0",
26
+ "@aptkit/prompts": "0.0.0",
27
+ "@aptkit/runtime": "0.0.0",
28
+ "@aptkit/tools": "0.0.0"
29
+ },
30
+ "devDependencies": {
31
+ "@types/node": "^20.0.0"
32
+ }
33
+ }
@@ -0,0 +1,11 @@
1
+ # Diagnostic Investigation Agent
2
+
3
+ Extracted from the Blooming Insights diagnostic agent as a reusable AptKit capability.
4
+
5
+ This package investigates a single anomaly, tests competing hypotheses through a `ToolRegistry`, and returns a structured diagnosis with evidence and confidence.
6
+
7
+ ```ts
8
+ import { DiagnosticInvestigationAgent } from '@aptkit/agent-diagnostic-investigation';
9
+ ```
10
+
11
+ The first fixture covers a seeded Sao Paulo revenue drop over an Olist-style ecommerce workspace.
@@ -0,0 +1,27 @@
1
+ import { type CapabilityTraceSink, type ModelProvider } from '@aptkit/runtime';
2
+ import { type ToolRegistry } from '@aptkit/tools';
3
+ import type { Anomaly, Diagnosis, WorkspaceDescriptor } from './types.js';
4
+ export declare const DIAGNOSTIC_INVESTIGATION_CAPABILITY_ID = "diagnostic-investigation-agent";
5
+ /** Least-privilege tool grant for evidence-gathering during diagnostic investigation. */
6
+ export declare const diagnosticInvestigationToolPolicy: {
7
+ capabilityId: string;
8
+ allowedTools: readonly ["execute_analytics_eql", "get_event_segmentation", "list_email_campaigns", "list_experiments", "list_scenarios", "list_banners", "list_customers", "get_customer_prediction_score", "get_metric_timeseries", "get_segments", "get_anomaly_context"];
9
+ };
10
+ export type DiagnosticAgentOptions = {
11
+ model: ModelProvider;
12
+ tools: ToolRegistry;
13
+ workspace: WorkspaceDescriptor;
14
+ trace?: CapabilityTraceSink;
15
+ prompt?: string;
16
+ };
17
+ export type DiagnosticRunOptions = {
18
+ signal?: AbortSignal;
19
+ };
20
+ export declare class DiagnosticInvestigationAgent {
21
+ private readonly options;
22
+ private readonly prompt;
23
+ constructor(options: DiagnosticAgentOptions);
24
+ /** Investigates one anomaly and returns a validated diagnosis with evidence and confidence. */
25
+ investigate(anomaly: Anomaly, runOptions?: DiagnosticRunOptions): Promise<Diagnosis>;
26
+ }
27
+ export declare function diagnosisConfidence(diagnosis: Diagnosis): 'high' | 'medium' | 'low';
@@ -0,0 +1,95 @@
1
+ import { diagnosticPromptPackage, renderPromptTemplate } from '@aptkit/prompts';
2
+ import { buildSynthesisInstruction, runAgentLoop } from '@aptkit/runtime';
3
+ import { filterToolsForPolicy } from '@aptkit/tools';
4
+ import { schemaSummary } from './schema-summary.js';
5
+ import { tryParseDiagnosis } from './validate.js';
6
+ export const DIAGNOSTIC_INVESTIGATION_CAPABILITY_ID = 'diagnostic-investigation-agent';
7
+ /** Least-privilege tool grant for evidence-gathering during diagnostic investigation. */
8
+ export const diagnosticInvestigationToolPolicy = {
9
+ capabilityId: DIAGNOSTIC_INVESTIGATION_CAPABILITY_ID,
10
+ allowedTools: [
11
+ 'execute_analytics_eql',
12
+ 'get_event_segmentation',
13
+ 'list_email_campaigns',
14
+ 'list_experiments',
15
+ 'list_scenarios',
16
+ 'list_banners',
17
+ 'list_customers',
18
+ 'get_customer_prediction_score',
19
+ 'get_metric_timeseries',
20
+ 'get_segments',
21
+ 'get_anomaly_context',
22
+ ],
23
+ };
24
+ const FALLBACK_DIAGNOSIS = {
25
+ conclusion: 'Insufficient data to determine a cause for this change.',
26
+ evidence: [],
27
+ hypothesesConsidered: [],
28
+ confidence: 'low',
29
+ };
30
+ export class DiagnosticInvestigationAgent {
31
+ options;
32
+ prompt;
33
+ constructor(options) {
34
+ this.options = options;
35
+ this.prompt = options.prompt ?? diagnosticPromptPackage.system;
36
+ }
37
+ /** Investigates one anomaly and returns a validated diagnosis with evidence and confidence. */
38
+ async investigate(anomaly, runOptions = {}) {
39
+ const allTools = await this.options.tools.listTools();
40
+ const toolSchemas = filterToolsForPolicy(allTools, diagnosticInvestigationToolPolicy);
41
+ const system = renderPromptTemplate(this.prompt, {
42
+ schema: schemaSummary(this.options.workspace),
43
+ project_id: this.options.workspace.projectId,
44
+ anomaly: JSON.stringify(anomaly),
45
+ });
46
+ const { toolCalls, parsed } = await runAgentLoop({
47
+ capabilityId: DIAGNOSTIC_INVESTIGATION_CAPABILITY_ID,
48
+ model: this.options.model,
49
+ tools: this.options.tools,
50
+ system,
51
+ userPrompt: 'Investigate the anomaly and return the diagnosis JSON object.',
52
+ toolSchemas,
53
+ trace: this.options.trace,
54
+ signal: runOptions.signal,
55
+ maxTurns: 8,
56
+ maxToolCalls: 6,
57
+ synthesisInstruction: buildSynthesisInstruction('Stop investigating now and output your final answer. Respond with ONLY a single JSON object in a json fence matching the diagnosis shape: conclusion, evidence, hypothesesConsidered, and any supported optional fields. Base it only on the evidence already gathered.'),
58
+ parseResult: tryParseDiagnosis,
59
+ recoveryPrompt: (calls) => buildRecoveryPrompt(anomaly, calls),
60
+ });
61
+ const diagnosis = parsed ?? FALLBACK_DIAGNOSIS;
62
+ const confidence = diagnosisConfidence(diagnosis);
63
+ const hadErrors = toolCalls.some((call) => call.error);
64
+ return { ...diagnosis, confidence: confidence === 'high' && hadErrors ? 'medium' : confidence };
65
+ }
66
+ }
67
+ export function diagnosisConfidence(diagnosis) {
68
+ if (diagnosis.confidence)
69
+ return diagnosis.confidence;
70
+ const hypotheses = diagnosis.hypothesesConsidered ?? [];
71
+ if (hypotheses.length === 0)
72
+ return 'low';
73
+ const supported = hypotheses.filter((item) => item.supported).length;
74
+ const tested = hypotheses.filter((item) => item.reasoning.trim().length > 0).length;
75
+ if (supported >= 1 && tested === hypotheses.length)
76
+ return 'high';
77
+ if (supported >= 1)
78
+ return 'medium';
79
+ return 'low';
80
+ }
81
+ function buildRecoveryPrompt(anomaly, toolCalls) {
82
+ const evidence = toolCalls
83
+ .map((call, index) => {
84
+ const payload = call.error ? { error: call.error } : call.result;
85
+ return `Query ${index + 1}: ${call.toolName} ${JSON.stringify(call.args).slice(0, 200)}\nResult: ${JSON.stringify(payload).slice(0, 900)}`;
86
+ })
87
+ .join('\n\n') || '(no successful queries were completed)';
88
+ return [
89
+ `Anomaly investigated:\n${JSON.stringify(anomaly)}`,
90
+ `Queries run and their results:\n${evidence}`,
91
+ 'Based ONLY on the evidence above, output your best-supported diagnosis as a single JSON object in a json fence.',
92
+ 'Use this shape: {"conclusion": string, "evidence": string[], "hypothesesConsidered": [{"hypothesis": string, "supported": boolean, "reasoning": string}]}.',
93
+ 'Give a concrete conclusion grounded in observed values. If the data was inconclusive, say what was inconclusive. Do NOT request more queries.',
94
+ ].join('\n\n');
95
+ }
@@ -0,0 +1,10 @@
1
+ import type { ModelProvider, ModelRequest, ModelResponse } from '@aptkit/runtime';
2
+ export declare class FixtureModelProvider implements ModelProvider {
3
+ private readonly responses;
4
+ readonly id = "fixture";
5
+ readonly defaultModel = "fixture-model";
6
+ readonly requests: ModelRequest[];
7
+ private index;
8
+ constructor(responses: ModelResponse[]);
9
+ complete(request: ModelRequest): Promise<ModelResponse>;
10
+ }
@@ -0,0 +1,18 @@
1
+ export class FixtureModelProvider {
2
+ responses;
3
+ id = 'fixture';
4
+ defaultModel = 'fixture-model';
5
+ requests = [];
6
+ index = 0;
7
+ constructor(responses) {
8
+ this.responses = responses;
9
+ }
10
+ async complete(request) {
11
+ this.requests.push(request);
12
+ const response = this.responses[this.index];
13
+ this.index += 1;
14
+ if (!response)
15
+ throw new Error(`fixture model exhausted after ${this.index - 1} responses`);
16
+ return response;
17
+ }
18
+ }
@@ -0,0 +1,5 @@
1
+ export * from './diagnostic-agent.js';
2
+ export * from './fixture-provider.js';
3
+ export * from './schema-summary.js';
4
+ export * from './types.js';
5
+ export * from './validate.js';
@@ -0,0 +1,5 @@
1
+ export * from './diagnostic-agent.js';
2
+ export * from './fixture-provider.js';
3
+ export * from './schema-summary.js';
4
+ export * from './types.js';
5
+ export * from './validate.js';
@@ -0,0 +1 @@
1
+ export { schemaSummary } from '@aptkit/context';
@@ -0,0 +1 @@
1
+ export { schemaSummary } from '@aptkit/context';
@@ -0,0 +1,37 @@
1
+ export type { WorkspaceDescriptor } from '@aptkit/context';
2
+ export type Severity = 'critical' | 'warning' | 'info' | 'positive';
3
+ export type Anomaly = {
4
+ metric: string;
5
+ scope: string[];
6
+ change: {
7
+ value: number;
8
+ direction: 'up' | 'down';
9
+ baseline: string;
10
+ };
11
+ severity: Severity;
12
+ evidence: {
13
+ tool: string;
14
+ result: unknown;
15
+ }[];
16
+ impact?: string;
17
+ history?: number[];
18
+ category?: string;
19
+ };
20
+ export type Diagnosis = {
21
+ conclusion: string;
22
+ evidence: string[];
23
+ hypothesesConsidered: {
24
+ hypothesis: string;
25
+ supported: boolean;
26
+ reasoning: string;
27
+ }[];
28
+ affectedCustomers?: {
29
+ count: number;
30
+ segmentDescription: string;
31
+ };
32
+ confidence?: 'high' | 'medium' | 'low';
33
+ timeSeries?: {
34
+ day: string;
35
+ value: number;
36
+ }[];
37
+ };
@@ -0,0 +1,10 @@
1
+ import type { Diagnosis } from './types.js';
2
+ export declare function isDiagnosis(value: unknown): value is Diagnosis;
3
+ export declare function tryParseDiagnosis(text: string): Diagnosis | null;
4
+ export declare function validateDiagnosis(diagnosis: unknown): {
5
+ ok: true;
6
+ error?: undefined;
7
+ } | {
8
+ ok: false;
9
+ error: string;
10
+ };
@@ -0,0 +1,49 @@
1
+ import { parseAgentJson } from '@aptkit/runtime';
2
+ function isRecord(value) {
3
+ return !!value && typeof value === 'object' && !Array.isArray(value);
4
+ }
5
+ function isHypothesis(value) {
6
+ return (isRecord(value) &&
7
+ typeof value.hypothesis === 'string' &&
8
+ typeof value.supported === 'boolean' &&
9
+ typeof value.reasoning === 'string');
10
+ }
11
+ function isAffectedCustomers(value) {
12
+ return isRecord(value) && typeof value.count === 'number' && typeof value.segmentDescription === 'string';
13
+ }
14
+ function isTimeSeriesPoint(value) {
15
+ return isRecord(value) && typeof value.day === 'string' && typeof value.value === 'number';
16
+ }
17
+ export function isDiagnosis(value) {
18
+ if (!isRecord(value))
19
+ return false;
20
+ if (typeof value.conclusion !== 'string')
21
+ return false;
22
+ if (!Array.isArray(value.evidence) || !value.evidence.every((item) => typeof item === 'string'))
23
+ return false;
24
+ if (!Array.isArray(value.hypothesesConsidered) || !value.hypothesesConsidered.every(isHypothesis)) {
25
+ return false;
26
+ }
27
+ if (value.affectedCustomers !== undefined && !isAffectedCustomers(value.affectedCustomers))
28
+ return false;
29
+ if (value.timeSeries !== undefined && (!Array.isArray(value.timeSeries) || !value.timeSeries.every(isTimeSeriesPoint))) {
30
+ return false;
31
+ }
32
+ if (value.confidence !== undefined && !['high', 'medium', 'low'].includes(String(value.confidence)))
33
+ return false;
34
+ return true;
35
+ }
36
+ export function tryParseDiagnosis(text) {
37
+ try {
38
+ const parsed = parseAgentJson(text);
39
+ return isDiagnosis(parsed) ? parsed : null;
40
+ }
41
+ catch {
42
+ return null;
43
+ }
44
+ }
45
+ export function validateDiagnosis(diagnosis) {
46
+ if (isDiagnosis(diagnosis))
47
+ return { ok: true };
48
+ return { ok: false, error: 'diagnosis must match the expected structured output shape' };
49
+ }