Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat: add agent context contract evaluator (#4413)

Adam Eivy657afe3920b7
diff --git a/.changelog/next/added-issue-4413.md b/.changelog/next/added-issue-4413.md
new file mode 100644
index 0000000000..7ba07e67b3
--- /dev/null
+++ b/.changelog/next/added-issue-4413.md
@@ -0,0 +1 @@
+- Agent context now includes a fixture-backed contract evaluator with machine-readable privacy, scope, freshness, and budget results.
diff --git a/docs/features/agent-context.md b/docs/features/agent-context.md
index 4aa853e32b..d239a28c60 100644
--- a/docs/features/agent-context.md
+++ b/docs/features/agent-context.md
@@ -54,7 +54,19 @@ All advertised tools carry MCP `readOnlyHint: true`, `destructiveHint: false`, `
| `list_context` | Page through one enabled scope. |
| `resolve_navigation` | Resolve a PortOS page alias when Navigation is enabled. |
-Calls are capped at 25 returned items, 1,000 inspected source items per scope, 320 characters per summary, 200 characters per query, and 20,000 serialized characters per structured result. Source failures produce an MCP tool error rather than masquerading as an empty result. A capped scan sets `sourceTruncated: true`; search/list also set `truncated: true`, so partial coverage cannot look complete.
+Calls are capped at 25 returned items, 1,000 inspected source items per scope, 320 characters per summary, 200 characters per query, 20,000 serialized characters, and approximately 5,000 tokens per structured result. Source failures produce an MCP tool error rather than masquerading as an empty result. A capped scan sets `sourceTruncated: true`; search/list also set `truncated: true`, so partial coverage cannot look complete. Data-bearing results also expose `sourceStatus: "fresh" | "stale"`, so a retained snapshot cannot be mistaken for a live read.
+
+## Contract evaluation
+
+The public manifest and tool-call contract have a fixture-backed black-box suite. It creates a fresh in-memory contract for every case, replaces every navigation/workspace/Brain/identity source with sanitized fake records, and never reads the running instance, a real workspace, the Privacy Vault, or an AI provider.
+
+Run it from the repository root:
+
+```bash
+npm run --silent eval:agent-context -- --failure-threshold 0
+```
+
+The command writes one JSON report to stdout and exits non-zero when `fail + error` exceeds the threshold. Every case reports `pass`, `fail`, `error`, or `skip` plus its fixture source and tool pointer. Use `--fixture <path>` to evaluate another declarative suite with the same schema. The checked-in cases cover manifest/runtime parity, read-only annotations, search/list/get/navigation/profile calls, scope and privacy boundaries, result and approximate-token budgets, unknown records, source errors, and stale-source signaling.
## Protocol example
diff --git a/package.json b/package.json
index 05b58d1392..3f33763602 100644
--- a/package.json
+++ b/package.json
@@ -12,6 +12,7 @@
"scripts": {
"dev": "node scripts/checkNodeVersion.js && node scripts/dev-start.js",
"dev:stop": "node ./node_modules/pm2/bin/pm2 stop ecosystem.config.cjs",
+ "eval:agent-context": "node scripts/agent-context-eval.js",
"build": "npm run build --prefix client",
"changelog:add": "node scripts/changelog-add.js",
"changelog:collect": "node scripts/changelog-collect.js",
diff --git a/scripts/agent-context-eval.js b/scripts/agent-context-eval.js
new file mode 100644
index 0000000000..eeb433dc2d
--- /dev/null
+++ b/scripts/agent-context-eval.js
@@ -0,0 +1,53 @@
+#!/usr/bin/env node
+
+import { readFile } from 'fs/promises';
+import { resolve } from 'path';
+import { fileURLToPath } from 'url';
+import { runAgentContextEval } from '../server/services/agentContextEval.js';
+
+const repoRoot = fileURLToPath(new URL('..', import.meta.url));
+const defaultFixture = resolve(repoRoot, 'server/test/fixtures/agent-context-eval.json');
+
+const parseArgs = (args) => {
+ let fixture = defaultFixture;
+ let failureThreshold = 0;
+ for (let index = 0; index < args.length; index += 1) {
+ const argument = args[index];
+ if (argument === '--fixture') {
+ if (!args[index + 1]) throw new Error('--fixture requires a path');
+ fixture = resolve(args[index + 1]);
+ index += 1;
+ } else if (argument === '--failure-threshold') {
+ if (!args[index + 1]) throw new Error('--failure-threshold requires a value');
+ failureThreshold = Number(args[index + 1]);
+ index += 1;
+ } else if (argument.startsWith('--failure-threshold=')) {
+ failureThreshold = Number(argument.slice('--failure-threshold='.length));
+ } else {
+ throw new Error(`Unknown argument: ${argument}`);
+ }
+ }
+ if (!Number.isInteger(failureThreshold) || failureThreshold < 0) {
+ throw new Error('--failure-threshold must be a non-negative integer');
+ }
+ return { fixture, failureThreshold };
+};
+
+const main = async () => {
+ const { fixture, failureThreshold } = parseArgs(process.argv.slice(2));
+ const suite = JSON.parse(await readFile(fixture, 'utf8'));
+ return runAgentContextEval(suite, { failureThreshold });
+};
+
+main().then((report) => {
+ process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
+ process.exitCode = report.passed ? 0 : 1;
+}).catch((error) => {
+ process.stdout.write(`${JSON.stringify({
+ kind: 'portos-agent-context-eval',
+ reportVersion: 1,
+ passed: false,
+ error: error.message,
+ }, null, 2)}\n`);
+ process.exitCode = 1;
+});
diff --git a/server/lib/README.md b/server/lib/README.md
index e00f9a29c7..09942ec7a0 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -23,7 +23,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| Module | Purpose |
|---|---|
-| `agentContextValidation.js` | Shared settings, MCP request/tool input/output schemas, bounds, and `advertiseAgentContextTools(scopes)` for the opt-in read-only agent-context surface. |
+| `agentContextValidation.js` | Shared settings, MCP request/tool input/output schemas, result + approximate-token bounds, source-freshness status, and `advertiseAgentContextTools(scopes)` for the opt-in read-only agent-context surface. |
| `validation.js` | Catch-all Zod schemas (app/process/provider, social accounts, GitHub, backup/sharing, document/legacy-export) + the `validateRequest` middleware + shared helpers (`optionalBooleanMap`, `isSafeRecordId`, `parsePagination`). Re-exports the per-domain validation files below so existing deep imports keep working. |
| `sharedSchemas.js` | Cross-domain Zod fragments that `validation.js` and the per-domain `*Validation.js` files both need, kept in a leaf module so the domain files never import back through `validation.js` (its hoisted `export * from` lines would TDZ). `grokVideoDurationSchema` (grok clip-length union), `cloudModelIdString(message)` (cloud-CLI model-id charset/bounds), `recordRenderPinFields` (the `imageMode`/`imageModelId` per-record render pin pair), and `isSafeSubdirFilter(v)` (relative path with no wildcard, `..` segment, or leading `/`), and `csvIdsParam({ max, maxIdLength, truncate })` (the `?ids=a,b,c` batch-by-id query param: trims, drops empties, reads all-blank as absent, and either 400s or silently slices an over-cap batch). |
| `agentOutputMarkers.js` | Status lines PortOS itself appends to an agent's output buffer: `SENTINEL_COMPLETION_MARKER` (the line `ingestDoneSentinel` writes just before the agent's `.agent-done` summary) plus `isAgentLifecycleLine(line)`/`stripLifecycleLines(lines)`, which match PortOS's telemetry on its actual message shapes rather than on a leading emoji (an agent's own summary may well start a line with `✅`). Pure — shared by the emitter (`services/agentTuiSpawning.js`) and by readers that must show only the agent's own words (notably the generated PR description). |
diff --git a/server/lib/agentContextValidation.js b/server/lib/agentContextValidation.js
index c5ad5c71dd..fa77e9c18a 100644
--- a/server/lib/agentContextValidation.js
+++ b/server/lib/agentContextValidation.js
@@ -1,6 +1,6 @@
import { z } from 'zod';
-export const AGENT_CONTEXT_SCHEMA_VERSION = 1;
+export const AGENT_CONTEXT_SCHEMA_VERSION = 2;
export const AGENT_CONTEXT_PROTOCOL_VERSION = '2025-11-25';
export const AGENT_CONTEXT_SUPPORTED_PROTOCOL_VERSIONS = Object.freeze([
'2025-03-26',
@@ -16,6 +16,7 @@ export const AGENT_CONTEXT_LIMITS = Object.freeze({
maxResults: 25,
maxSummaryChars: 320,
maxResponseChars: 20_000,
+ maxApproxTokens: 5_000,
maxSourceItems: 1_000,
maxQueryChars: 200,
maxRefChars: 180,
@@ -75,11 +76,13 @@ export const agentContextSearchOutputSchema = z.object({
total: z.number().int().min(0),
truncated: z.boolean(),
sourceTruncated: z.boolean(),
+ sourceStatus: z.enum(['fresh', 'stale']),
}).strict();
export const agentContextGetOutputSchema = z.object({
item: agentContextItemSchema.nullable(),
sourceTruncated: z.boolean(),
+ sourceStatus: z.enum(['fresh', 'stale']),
}).strict();
export const agentContextListOutputSchema = z.object({
@@ -88,9 +91,13 @@ export const agentContextListOutputSchema = z.object({
nextCursor: z.number().int().min(0).nullable(),
truncated: z.boolean(),
sourceTruncated: z.boolean(),
+ sourceStatus: z.enum(['fresh', 'stale']),
}).strict();
-export const agentContextNavigationOutputSchema = z.object({ match: agentContextItemSchema.nullable() }).strict();
+export const agentContextNavigationOutputSchema = z.object({
+ match: agentContextItemSchema.nullable(),
+ sourceStatus: z.enum(['fresh', 'stale']),
+}).strict();
export const agentContextProfileOutputSchema = z.object({
profile: z.enum(AGENT_CONTEXT_PROFILES),
@@ -100,6 +107,7 @@ export const agentContextProfileOutputSchema = z.object({
maxResults: z.number().int().positive(),
maxSummaryChars: z.number().int().positive(),
maxResponseChars: z.number().int().positive(),
+ maxApproxTokens: z.number().int().positive(),
maxSourceItems: z.number().int().positive(),
}).strict(),
exclusions: z.array(z.string()),
diff --git a/server/lib/agentContextValidation.test.js b/server/lib/agentContextValidation.test.js
index 5886a5729f..02318a3ab2 100644
--- a/server/lib/agentContextValidation.test.js
+++ b/server/lib/agentContextValidation.test.js
@@ -46,5 +46,6 @@ describe('agentContextValidation', () => {
const search = AGENT_CONTEXT_TOOL_REGISTRY.find((tool) => tool.name === 'search_context');
expect(search.inputSchema.safeParse({ query: 'x', limit: AGENT_CONTEXT_LIMITS.maxResults }).success).toBe(true);
expect(search.inputSchema.safeParse({ query: 'x', limit: AGENT_CONTEXT_LIMITS.maxResults + 1 }).success).toBe(false);
+ expect(AGENT_CONTEXT_LIMITS.maxApproxTokens).toBeLessThanOrEqual(Math.ceil(AGENT_CONTEXT_LIMITS.maxResponseChars / 4));
});
});
diff --git a/server/services/agentContextEval.js b/server/services/agentContextEval.js
new file mode 100644
index 0000000000..7f324ee51d
--- /dev/null
+++ b/server/services/agentContextEval.js
@@ -0,0 +1,317 @@
+import { z } from 'zod';
+import { createAgentContextContract } from './agentContextMcp.js';
+
+export const AGENT_CONTEXT_EVAL_REPORT_VERSION = 1;
+
+const fixtureSchema = z.object({
+ navigation: z.array(z.record(z.string(), z.unknown())).optional(),
+ workspaces: z.array(z.record(z.string(), z.unknown())).optional(),
+ brain: z.record(z.string(), z.array(z.record(z.string(), z.unknown()))).optional(),
+ identity: z.record(z.string(), z.record(z.string(), z.unknown())).optional(),
+ sourceStatus: z.record(z.string(), z.enum(['fresh', 'stale'])).optional(),
+ errors: z.array(z.enum(['navigation', 'workspaces', 'brain', 'identity'])).optional(),
+}).strict();
+
+const pathExpectationSchema = z.object({
+ path: z.string().min(1),
+ value: z.unknown(),
+}).strict();
+
+const limitExpectationSchema = z.object({
+ path: z.string().min(1),
+ value: z.number().int().min(0),
+}).strict();
+
+const expectationSchema = z.object({
+ isError: z.boolean().optional(),
+ inputSchemaValid: z.boolean().optional(),
+ outputSchemaValid: z.boolean().optional(),
+ contentParity: z.boolean().optional(),
+ advertisedToolsCovered: z.boolean().optional(),
+ readOnlyTools: z.boolean().optional(),
+ withinBudgets: z.boolean().optional(),
+ equals: z.array(pathExpectationSchema).optional(),
+ contains: z.array(pathExpectationSchema).optional(),
+ excludes: z.array(z.string()).optional(),
+ absentKeys: z.array(z.string()).optional(),
+ maxItems: z.array(limitExpectationSchema).optional(),
+ maxChars: z.array(limitExpectationSchema).optional(),
+}).strict();
+
+const caseSchema = z.object({
+ id: z.string().min(1).max(120),
+ title: z.string().min(1).max(240),
+ severity: z.enum(['critical', 'high', 'medium', 'low']),
+ source: z.string().min(1).max(500),
+ fixture: z.string().min(1).max(120),
+ operation: z.enum(['manifest', 'tool']),
+ tool: z.string().min(1).max(120).optional(),
+ args: z.record(z.string(), z.unknown()).optional(),
+ settings: z.record(z.string(), z.unknown()),
+ skip: z.string().min(1).max(500).optional(),
+ expect: expectationSchema.optional(),
+}).strict().refine((value) => value.operation !== 'tool' || value.tool, {
+ message: 'Tool cases require a tool name',
+ path: ['tool'],
+});
+
+export const agentContextEvalSuiteSchema = z.object({
+ name: z.string().min(1).max(120),
+ version: z.number().int().positive(),
+ fixtures: z.record(z.string(), fixtureSchema),
+ cases: z.array(caseSchema).min(1),
+}).strict();
+
+const resolvePath = (value, path) => path.split('.').reduce((current, part) => {
+ if (current === null || current === undefined) return undefined;
+ return part === 'length' ? current.length : current[part];
+}, value);
+
+const sameValue = (left, right) => JSON.stringify(left) === JSON.stringify(right);
+
+const collectKeys = (value, keys = new Set()) => {
+ if (Array.isArray(value)) {
+ value.forEach((entry) => collectKeys(entry, keys));
+ } else if (value && typeof value === 'object') {
+ Object.entries(value).forEach(([key, entry]) => {
+ keys.add(key);
+ collectKeys(entry, keys);
+ });
+ }
+ return keys;
+};
+
+const valueTypeMatches = (value, type) => {
+ if (type === 'null') return value === null;
+ if (type === 'array') return Array.isArray(value);
+ if (type === 'object') return value !== null && typeof value === 'object' && !Array.isArray(value);
+ if (type === 'integer') return Number.isInteger(value);
+ return typeof value === type;
+};
+
+const validateJsonSchema = (value, schema, path = '$') => {
+ if (!schema || typeof schema !== 'object') return [];
+ if (Array.isArray(schema.anyOf)) {
+ const candidates = schema.anyOf.map((candidate) => validateJsonSchema(value, candidate, path));
+ return candidates.some((errors) => errors.length === 0)
+ ? []
+ : [`${path} does not match any advertised schema variant`];
+ }
+ if (Array.isArray(schema.enum) && !schema.enum.some((entry) => sameValue(entry, value))) {
+ return [`${path} is not an advertised enum value`];
+ }
+
+ const types = Array.isArray(schema.type) ? schema.type : schema.type ? [schema.type] : [];
+ if (types.length > 0 && !types.some((type) => valueTypeMatches(value, type))) {
+ return [`${path} has type ${Array.isArray(value) ? 'array' : value === null ? 'null' : typeof value}; expected ${types.join('|')}`];
+ }
+ if (value === null || value === undefined) return [];
+
+ const errors = [];
+ if (typeof value === 'string') {
+ if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(`${path} is shorter than ${schema.minLength}`);
+ if (schema.maxLength !== undefined && value.length > schema.maxLength) errors.push(`${path} is longer than ${schema.maxLength}`);
+ }
+ if (typeof value === 'number') {
+ if (schema.minimum !== undefined && value < schema.minimum) errors.push(`${path} is below ${schema.minimum}`);
+ if (schema.maximum !== undefined && value > schema.maximum) errors.push(`${path} is above ${schema.maximum}`);
+ }
+ if (Array.isArray(value)) {
+ if (schema.minItems !== undefined && value.length < schema.minItems) errors.push(`${path} has fewer than ${schema.minItems} items`);
+ if (schema.maxItems !== undefined && value.length > schema.maxItems) errors.push(`${path} has more than ${schema.maxItems} items`);
+ value.forEach((entry, index) => errors.push(...validateJsonSchema(entry, schema.items, `${path}.${index}`)));
+ }
+ if (value && typeof value === 'object' && !Array.isArray(value)) {
+ for (const required of schema.required ?? []) {
+ if (!(required in value)) errors.push(`${path}.${required} is required`);
+ }
+ for (const [key, entry] of Object.entries(value)) {
+ if (schema.properties?.[key]) {
+ errors.push(...validateJsonSchema(entry, schema.properties[key], `${path}.${key}`));
+ } else if (schema.additionalProperties === false) {
+ errors.push(`${path}.${key} is not advertised`);
+ }
+ }
+ }
+ return errors;
+};
+
+const fixtureResolver = (commands) => (query) => {
+ const needle = String(query ?? '').toLowerCase();
+ const command = commands.find((entry) => [entry.id, entry.label, entry.path, ...(entry.aliases ?? []), ...(entry.keywords ?? [])]
+ .some((candidate) => String(candidate ?? '').toLowerCase() === needle));
+ return command ? { command } : null;
+};
+
+const createFixtureContract = (fixture, settings) => {
+ const isolated = structuredClone(fixture);
+ const errors = new Set(isolated.errors ?? []);
+ const rejectIfConfigured = (scope) => {
+ if (errors.has(scope)) throw new Error(`Fixture source unavailable: ${scope}`);
+ };
+ const navigation = isolated.navigation ?? [];
+ return createAgentContextContract({
+ readSettings: async () => structuredClone(settings),
+ navigationCommands: navigation,
+ resolveNavigation: fixtureResolver(navigation),
+ listWorkspaceContexts: async () => {
+ rejectIfConfigured('workspaces');
+ return structuredClone(isolated.workspaces ?? []);
+ },
+ brainSearchTypes: Object.keys(isolated.brain ?? {}),
+ getBrainRecords: async (type) => {
+ rejectIfConfigured('brain');
+ return structuredClone(isolated.brain?.[type] ?? []);
+ },
+ previewIdentityExport: async () => {
+ rejectIfConfigured('identity');
+ return { sections: structuredClone(isolated.identity ?? {}) };
+ },
+ getSourceStatus: async (scope) => {
+ rejectIfConfigured(scope);
+ return isolated.sourceStatus?.[scope] ?? 'fresh';
+ },
+ });
+};
+
+const evaluateExpectations = ({ evalCase, manifest, toolResult, suite }) => {
+ const expect = evalCase.expect ?? {};
+ const output = toolResult?.structuredContent;
+ const payload = { manifest, output, toolResult };
+ const findings = [];
+ const advertisedTool = manifest.tools.find((tool) => tool.name === evalCase.tool);
+
+ if (expect.isError !== undefined && Boolean(toolResult?.isError) !== expect.isError) {
+ findings.push(`Expected isError=${expect.isError}, received ${Boolean(toolResult?.isError)}`);
+ }
+ if (expect.inputSchemaValid !== undefined) {
+ const valid = advertisedTool ? validateJsonSchema(evalCase.args ?? {}, advertisedTool.inputSchema).length === 0 : false;
+ if (valid !== expect.inputSchemaValid) findings.push(`Advertised input schema validity was ${valid}`);
+ }
+ if (expect.outputSchemaValid) {
+ if (!advertisedTool) findings.push(`Tool ${evalCase.tool} is not advertised`);
+ else findings.push(...validateJsonSchema(output, advertisedTool.outputSchema).map((message) => `Output schema: ${message}`));
+ }
+ if (expect.contentParity) {
+ const text = toolResult?.content?.[0]?.text;
+ const parsed = typeof text === 'string' ? JSON.parse(text) : undefined;
+ if (!sameValue(parsed, output)) findings.push('Text and structured tool outputs differ');
+ }
+ if (expect.advertisedToolsCovered) {
+ const advertised = manifest.tools.map((tool) => tool.name).sort();
+ const covered = [...new Set(suite.cases.filter((candidate) => candidate.operation === 'tool' && !candidate.skip)
+ .map((candidate) => candidate.tool))].sort();
+ if (!sameValue(advertised, covered)) findings.push(`Advertised/runtime case parity differs: advertised=${advertised.join(',')} covered=${covered.join(',')}`);
+ }
+ if (expect.readOnlyTools) {
+ const unsafe = manifest.tools.filter((tool) => tool.annotations?.readOnlyHint !== true
+ || tool.annotations?.destructiveHint !== false
+ || tool.annotations?.idempotentHint !== true
+ || tool.annotations?.openWorldHint !== false);
+ if (unsafe.length > 0) findings.push(`Tools lack read-only annotations: ${unsafe.map((tool) => tool.name).join(', ')}`);
+ }
+ if (expect.withinBudgets && output !== undefined) {
+ const chars = JSON.stringify(output).length;
+ const approxTokens = Math.ceil(chars / 4);
+ if (chars > manifest.limits.maxResponseChars) findings.push(`Output uses ${chars} chars; limit is ${manifest.limits.maxResponseChars}`);
+ if (approxTokens > manifest.limits.maxApproxTokens) findings.push(`Output uses ~${approxTokens} tokens; limit is ${manifest.limits.maxApproxTokens}`);
+ }
+ for (const check of expect.equals ?? []) {
+ const actual = resolvePath(payload, check.path);
+ if (!sameValue(actual, check.value)) findings.push(`${check.path} expected ${JSON.stringify(check.value)}; received ${JSON.stringify(actual)}`);
+ }
+ for (const check of expect.contains ?? []) {
+ const actual = resolvePath(payload, check.path);
+ if (typeof actual === 'string' ? !actual.includes(check.value) : !Array.isArray(actual) || !actual.includes(check.value)) {
+ findings.push(`${check.path} does not contain ${JSON.stringify(check.value)}`);
+ }
+ }
+ const serialized = JSON.stringify(payload);
+ for (const forbidden of expect.excludes ?? []) {
+ if (serialized.includes(forbidden)) findings.push(`Output contains forbidden fixture value: ${forbidden}`);
+ }
+ const keys = collectKeys(output);
+ for (const forbidden of expect.absentKeys ?? []) {
+ if (keys.has(forbidden)) findings.push(`Output contains forbidden field: ${forbidden}`);
+ }
+ for (const check of expect.maxItems ?? []) {
+ const actual = resolvePath(payload, check.path);
+ if (!Array.isArray(actual) || actual.length > check.value) findings.push(`${check.path} exceeds ${check.value} items`);
+ }
+ for (const check of expect.maxChars ?? []) {
+ const actual = resolvePath(payload, check.path);
+ if (typeof actual !== 'string' || actual.length > check.value) findings.push(`${check.path} exceeds ${check.value} characters`);
+ }
+ return findings;
+};
+
+const runEvalCase = (evalCase, suite) => {
+ if (evalCase.skip) {
+ return Promise.resolve({
+ id: evalCase.id,
+ title: evalCase.title,
+ severity: evalCase.severity,
+ source: evalCase.source,
+ tool: evalCase.tool ?? 'manifest',
+ status: 'skip',
+ reason: evalCase.skip,
+ });
+ }
+ const fixture = suite.fixtures[evalCase.fixture];
+ if (!fixture) {
+ return Promise.resolve({
+ id: evalCase.id,
+ title: evalCase.title,
+ severity: evalCase.severity,
+ source: evalCase.source,
+ tool: evalCase.tool ?? 'manifest',
+ status: 'error',
+ error: `Unknown fixture: ${evalCase.fixture}`,
+ });
+ }
+
+ return Promise.resolve().then(async () => {
+ const contract = createFixtureContract(fixture, evalCase.settings);
+ const manifest = await contract.getManifest();
+ const toolResult = evalCase.operation === 'tool'
+ ? await contract.callTool(evalCase.tool, evalCase.args)
+ : undefined;
+ const findings = evaluateExpectations({ evalCase, manifest, toolResult, suite });
+ return {
+ id: evalCase.id,
+ title: evalCase.title,
+ severity: evalCase.severity,
+ source: evalCase.source,
+ tool: evalCase.tool ?? 'manifest',
+ status: findings.length === 0 ? 'pass' : 'fail',
+ ...(findings.length > 0 ? { findings } : {}),
+ };
+ }).catch((error) => ({
+ id: evalCase.id,
+ title: evalCase.title,
+ severity: evalCase.severity,
+ source: evalCase.source,
+ tool: evalCase.tool ?? 'manifest',
+ status: 'error',
+ error: error.message,
+ }));
+};
+
+export async function runAgentContextEval(suiteInput, { failureThreshold = 0 } = {}) {
+ const suite = agentContextEvalSuiteSchema.parse(suiteInput);
+ const threshold = z.number().int().min(0).parse(failureThreshold);
+ const cases = await Promise.all(suite.cases.map((evalCase) => runEvalCase(evalCase, suite)));
+ const counts = Object.fromEntries(['pass', 'fail', 'error', 'skip']
+ .map((status) => [status, cases.filter((result) => result.status === status).length]));
+ const failures = counts.fail + counts.error;
+ return {
+ kind: 'portos-agent-context-eval',
+ reportVersion: AGENT_CONTEXT_EVAL_REPORT_VERSION,
+ suite: suite.name,
+ suiteVersion: suite.version,
+ failureThreshold: threshold,
+ passed: failures <= threshold,
+ counts,
+ cases,
+ };
+}
diff --git a/server/services/agentContextEval.test.js b/server/services/agentContextEval.test.js
new file mode 100644
index 0000000000..8e0f73d1b7
--- /dev/null
+++ b/server/services/agentContextEval.test.js
@@ -0,0 +1,37 @@
+import { readFile } from 'fs/promises';
+import { fileURLToPath } from 'url';
+import { describe, expect, it } from 'vitest';
+import { runAgentContextEval } from './agentContextEval.js';
+
+const fixturePath = fileURLToPath(new URL('../test/fixtures/agent-context-eval.json', import.meta.url));
+const loadSuite = async () => JSON.parse(await readFile(fixturePath, 'utf8'));
+
+describe('agentContextEval', () => {
+ it('runs the fixture-backed public contract without live data or LLM access', async () => {
+ const report = await runAgentContextEval(await loadSuite());
+
+ expect(report).toMatchObject({
+ kind: 'portos-agent-context-eval',
+ reportVersion: 1,
+ suite: 'agent-context-public-contract',
+ failureThreshold: 0,
+ passed: true,
+ counts: { pass: 10, fail: 0, error: 0, skip: 1 },
+ });
+ expect(report.cases).toHaveLength(11);
+ expect(report.cases.every((result) => result.source && result.tool)).toBe(true);
+ expect(report.cases.find((result) => result.id === 'stale-source-signaling')).toMatchObject({ status: 'pass' });
+ expect(report.cases.find((result) => result.id === 'localized-profile')).toMatchObject({ status: 'skip' });
+ });
+
+ it('applies the configurable failure threshold to fail and error results', async () => {
+ const suite = await loadSuite();
+ suite.cases[0].expect.equals[0].value = 999;
+
+ const strict = await runAgentContextEval(suite);
+ const tolerant = await runAgentContextEval(suite, { failureThreshold: 1 });
+
+ expect(strict).toMatchObject({ passed: false, counts: { fail: 1, error: 0 } });
+ expect(tolerant).toMatchObject({ passed: true, failureThreshold: 1, counts: { fail: 1, error: 0 } });
+ });
+});
diff --git a/server/services/agentContextMcp.js b/server/services/agentContextMcp.js
index 6e65a47892..aa6d716b96 100644
--- a/server/services/agentContextMcp.js
+++ b/server/services/agentContextMcp.js
@@ -83,9 +83,14 @@ const workspaceItem = (workspace, profile) => ({
searchText: searchableText(`${workspace.appName} workspace app ${workspace.appId}`),
});
-const brainText = (record) => Object.entries(record)
- .filter(([key, value]) => key !== 'id' && key !== '_rank' && typeof value === 'string')
- .map(([, value]) => value)
+const BRAIN_CONTEXT_TEXT_FIELDS = Object.freeze([
+ 'name', 'title', 'description', 'context', 'oneLiner', 'artist', 'notes',
+ 'nextAction', 'mood', 'capturedText', 'url', 'content',
+]);
+
+const brainText = (record) => BRAIN_CONTEXT_TEXT_FIELDS
+ .filter((key) => typeof record[key] === 'string')
+ .map((key) => record[key])
.join(' ');
const brainItem = (type, record, profile) => {
@@ -120,23 +125,34 @@ const identityItem = ([key, section]) => ({
searchText: searchableText(`${key} ${section.label || ''} identity export ${section.present ? 'present' : 'absent'}`),
});
-const SOURCE_LOADERS = Object.freeze({
+const normalizeSourceStatus = (value) => value === 'stale' ? 'stale' : 'fresh';
+
+const createSourceLoaders = ({
+ navigationCommands,
+ listWorkspaceContexts,
+ brainSearchTypes,
+ getBrainRecords,
+ previewIdentityExport,
+ getSourceStatus,
+}) => Object.freeze({
navigation: async () => ({
- items: NAV_COMMANDS.slice(0, AGENT_CONTEXT_LIMITS.maxSourceItems).map(navigationItem),
- sourceTruncated: NAV_COMMANDS.length > AGENT_CONTEXT_LIMITS.maxSourceItems,
+ items: navigationCommands.slice(0, AGENT_CONTEXT_LIMITS.maxSourceItems).map(navigationItem),
+ sourceTruncated: navigationCommands.length > AGENT_CONTEXT_LIMITS.maxSourceItems,
+ sourceStatus: normalizeSourceStatus(await getSourceStatus('navigation')),
}),
workspaces: async (profile) => {
- const workspaces = await listContexts();
+ const workspaces = await listWorkspaceContexts();
return {
items: workspaces.slice(0, AGENT_CONTEXT_LIMITS.maxSourceItems)
.map((item) => workspaceItem(item, profile)),
sourceTruncated: workspaces.length > AGENT_CONTEXT_LIMITS.maxSourceItems,
+ sourceStatus: normalizeSourceStatus(await getSourceStatus('workspaces')),
};
},
brain: async (profile) => {
- const byType = await Promise.all(BRAIN_SEARCH_TYPES.map(async (type) => ({
+ const byType = await Promise.all(brainSearchTypes.map(async (type) => ({
type,
- records: await getBrainProjections(type),
+ records: await getBrainRecords(type),
})));
const candidates = [];
for (const { type, records } of byType) {
@@ -147,26 +163,29 @@ const SOURCE_LOADERS = Object.freeze({
return {
items: candidates,
sourceTruncated: byType.reduce((total, entry) => total + entry.records.length, 0) > candidates.length,
+ sourceStatus: normalizeSourceStatus(await getSourceStatus('brain')),
};
},
identity: async () => {
- const sections = Object.entries((await previewLegacyExport()).sections ?? {});
+ const sections = Object.entries((await previewIdentityExport()).sections ?? {});
return {
items: sections.slice(0, AGENT_CONTEXT_LIMITS.maxSourceItems).map(identityItem),
sourceTruncated: sections.length > AGENT_CONTEXT_LIMITS.maxSourceItems,
+ sourceStatus: normalizeSourceStatus(await getSourceStatus('identity')),
};
},
});
-const loadItems = async (config, scopes) => {
+const loadItems = async (config, scopes, sourceLoaders) => {
const sources = await Promise.all(scopes.map(async (scope) => {
- const loader = SOURCE_LOADERS[scope];
+ const loader = sourceLoaders[scope];
if (!loader) throw new Error(`Unsupported context scope: ${scope}`);
return loader(config.profile);
}));
return {
items: sources.flatMap((source) => source.items),
sourceTruncated: sources.some((source) => source.sourceTruncated),
+ sourceStatus: sources.some((source) => source.sourceStatus === 'stale') ? 'stale' : 'fresh',
};
};
@@ -181,7 +200,9 @@ const fitItems = (items, limit) => {
const selected = [];
for (const candidate of items.slice(0, limit)) {
const next = [...selected, candidate.item];
- if (JSON.stringify(next).length > AGENT_CONTEXT_LIMITS.maxResponseChars) break;
+ const serialized = JSON.stringify(next);
+ if (serialized.length > AGENT_CONTEXT_LIMITS.maxResponseChars
+ || Math.ceil(serialized.length / 4) > AGENT_CONTEXT_LIMITS.maxApproxTokens) break;
selected.push(candidate.item);
}
return { items: selected, truncated: selected.length < items.length };
@@ -195,16 +216,17 @@ const profileOutput = (config) => ({
maxResults: AGENT_CONTEXT_LIMITS.maxResults,
maxSummaryChars: AGENT_CONTEXT_LIMITS.maxSummaryChars,
maxResponseChars: AGENT_CONTEXT_LIMITS.maxResponseChars,
+ maxApproxTokens: AGENT_CONTEXT_LIMITS.maxApproxTokens,
maxSourceItems: AGENT_CONTEXT_LIMITS.maxSourceItems,
},
exclusions: [...AGENT_CONTEXT_EXCLUSIONS],
});
const TOOL_HANDLERS = Object.freeze({
- search_context: async (input, config) => {
+ search_context: async (input, config, runtime) => {
const scopes = requestedScopes(config, input.scopes);
const query = input.query.toLowerCase();
- const loaded = await loadItems(config, scopes);
+ const loaded = await loadItems(config, scopes, runtime.sourceLoaders);
const matches = loaded.items
.filter((candidate) => candidate.searchText.toLowerCase().includes(query));
const fitted = fitItems(matches, input.limit ?? AGENT_CONTEXT_LIMITS.defaultResults);
@@ -212,21 +234,23 @@ const TOOL_HANDLERS = Object.freeze({
...fitted,
total: matches.length,
sourceTruncated: loaded.sourceTruncated,
+ sourceStatus: loaded.sourceStatus,
truncated: fitted.truncated || loaded.sourceTruncated,
};
},
- get_context: async (input, config) => {
+ get_context: async (input, config, runtime) => {
const scope = input.ref.split(':', 1)[0];
- if (!config.scopes.includes(scope)) return { item: null, sourceTruncated: false };
- const loaded = await loadItems(config, [scope]);
+ if (!config.scopes.includes(scope)) return { item: null, sourceTruncated: false, sourceStatus: 'fresh' };
+ const loaded = await loadItems(config, [scope], runtime.sourceLoaders);
return {
item: loaded.items.find((candidate) => candidate.item.ref === input.ref)?.item ?? null,
sourceTruncated: loaded.sourceTruncated,
+ sourceStatus: loaded.sourceStatus,
};
},
- list_context: async (input, config) => {
+ list_context: async (input, config, runtime) => {
requestedScopes(config, [input.scope]);
- const loaded = await loadItems(config, [input.scope]);
+ const loaded = await loadItems(config, [input.scope], runtime.sourceLoaders);
const all = loaded.items;
const cursor = input.cursor ?? 0;
const page = all.slice(cursor);
@@ -237,13 +261,17 @@ const TOOL_HANDLERS = Object.freeze({
total: all.length,
nextCursor: nextOffset < all.length ? nextOffset : null,
sourceTruncated: loaded.sourceTruncated,
+ sourceStatus: loaded.sourceStatus,
truncated: fitted.truncated || loaded.sourceTruncated,
};
},
- resolve_navigation: async (input, config) => {
+ resolve_navigation: async (input, config, runtime) => {
requestedScopes(config, ['navigation']);
- const match = resolveNavCommand(input.query);
- return { match: match?.command ? navigationItem(match.command).item : null };
+ const match = runtime.resolveNavigation(input.query);
+ return {
+ match: match?.command ? navigationItem(match.command).item : null,
+ sourceStatus: normalizeSourceStatus(await runtime.getSourceStatus('navigation')),
+ };
},
context_profile: async (_input, config) => profileOutput(config),
});
@@ -258,47 +286,75 @@ const successToolResult = (output) => ({
structuredContent: output,
});
-export async function getAgentContextManifest(settings) {
- const current = settings ?? await getSettings();
- const config = resolveAgentContextConfig(current);
- return {
- kind: 'portos-agent-context',
- schemaVersion: AGENT_CONTEXT_SCHEMA_VERSION,
- protocolVersion: AGENT_CONTEXT_PROTOCOL_VERSION,
- enabled: config.enabled,
- configurationValid: !config.invalid,
- transport: {
- type: 'streamable-http',
- endpoint: '/api/agent-context/mcp',
- loopbackOnly: true,
- stateful: false,
- },
- profile: config.profile,
- scopes: config.scopes,
- limits: profileOutput(config).limits,
- exclusions: [...AGENT_CONTEXT_EXCLUSIONS],
- tools: advertiseAgentContextTools(config.scopes),
+export function createAgentContextContract({
+ readSettings = getSettings,
+ navigationCommands = NAV_COMMANDS,
+ resolveNavigation = resolveNavCommand,
+ listWorkspaceContexts = listContexts,
+ brainSearchTypes = BRAIN_SEARCH_TYPES,
+ getBrainRecords = getBrainProjections,
+ previewIdentityExport = previewLegacyExport,
+ getSourceStatus = async () => 'fresh',
+} = {}) {
+ const sourceLoaders = createSourceLoaders({
+ navigationCommands,
+ listWorkspaceContexts,
+ brainSearchTypes,
+ getBrainRecords,
+ previewIdentityExport,
+ getSourceStatus,
+ });
+ const runtime = { sourceLoaders, resolveNavigation, getSourceStatus };
+
+ const getManifest = async (settings) => {
+ const current = settings ?? await readSettings();
+ const config = resolveAgentContextConfig(current);
+ return {
+ kind: 'portos-agent-context',
+ schemaVersion: AGENT_CONTEXT_SCHEMA_VERSION,
+ protocolVersion: AGENT_CONTEXT_PROTOCOL_VERSION,
+ enabled: config.enabled,
+ configurationValid: !config.invalid,
+ transport: {
+ type: 'streamable-http',
+ endpoint: '/api/agent-context/mcp',
+ loopbackOnly: true,
+ stateful: false,
+ },
+ profile: config.profile,
+ scopes: config.scopes,
+ limits: profileOutput(config).limits,
+ exclusions: [...AGENT_CONTEXT_EXCLUSIONS],
+ tools: advertiseAgentContextTools(config.scopes),
+ };
};
-}
-export async function callAgentContextTool(name, args, settings) {
- const current = settings ?? await getSettings();
- const config = resolveAgentContextConfig(current);
- if (!config.enabled || config.invalid) return errorToolResult('Agent context is disabled or invalid.');
+ const callTool = async (name, args, settings) => {
+ const current = settings ?? await readSettings();
+ const config = resolveAgentContextConfig(current);
+ if (!config.enabled || config.invalid) return errorToolResult('Agent context is disabled or invalid.');
- const tool = AGENT_CONTEXT_TOOL_REGISTRY.find((candidate) => candidate.name === name);
- if (!tool || !TOOL_HANDLERS[name]) return errorToolResult(`Unknown tool: ${cap(name, 120)}`);
- if (tool.requiredScope && !config.scopes.includes(tool.requiredScope)) {
- return errorToolResult(`Tool requires the ${tool.requiredScope} scope.`);
- }
+ const tool = AGENT_CONTEXT_TOOL_REGISTRY.find((candidate) => candidate.name === name);
+ if (!tool || !TOOL_HANDLERS[name]) return errorToolResult(`Unknown tool: ${cap(name, 120)}`);
+ if (tool.requiredScope && !config.scopes.includes(tool.requiredScope)) {
+ return errorToolResult(`Tool requires the ${tool.requiredScope} scope.`);
+ }
- const parsed = tool.inputSchema.safeParse(args ?? {});
- if (!parsed.success) {
- const paths = parsed.error.issues.map((issue) => issue.path.join('.') || 'input').join(', ');
- return errorToolResult(`Invalid tool input at: ${paths}`);
- }
+ const parsed = tool.inputSchema.safeParse(args ?? {});
+ if (!parsed.success) {
+ const paths = parsed.error.issues.map((issue) => issue.path.join('.') || 'input').join(', ');
+ return errorToolResult(`Invalid tool input at: ${paths}`);
+ }
+
+ return Promise.resolve(TOOL_HANDLERS[name](parsed.data, config, runtime))
+ .then((output) => successToolResult(tool.outputSchema.parse(output)))
+ .catch(() => errorToolResult('Context source unavailable for this request.'));
+ };
- return Promise.resolve(TOOL_HANDLERS[name](parsed.data, config))
- .then((output) => successToolResult(tool.outputSchema.parse(output)))
- .catch(() => errorToolResult('Context source unavailable for this request.'));
+ return Object.freeze({ getManifest, callTool });
}
+
+const defaultAgentContextContract = createAgentContextContract();
+
+export const getAgentContextManifest = (settings) => defaultAgentContextContract.getManifest(settings);
+export const callAgentContextTool = (name, args, settings) => defaultAgentContextContract.callTool(name, args, settings);
diff --git a/server/services/agentContextMcp.test.js b/server/services/agentContextMcp.test.js
index 2ea700fed9..e5654c587c 100644
--- a/server/services/agentContextMcp.test.js
+++ b/server/services/agentContextMcp.test.js
@@ -46,6 +46,7 @@ describe('agentContextMcp service', () => {
expect(manifest.profile).toBe('metadata');
expect(manifest.scopes).toEqual(['navigation', 'workspaces']);
expect(manifest.transport).toMatchObject({ loopbackOnly: true, stateful: false });
+ expect(manifest).toMatchObject({ schemaVersion: 2, limits: { maxApproxTokens: 5_000 } });
expect(manifest.exclusions.join(' ')).toMatch(/Privacy Vault/);
});
@@ -78,6 +79,7 @@ describe('agentContextMcp service', () => {
id: 'project-1',
title: 'Contact [email protected] from /Users/alice/notes',
description: 'Host 192.0.2.10 token sk-12345678901234567890',
+ privateBody: 'never expose this projected field',
}]);
const result = await callAgentContextTool('list_context', { scope: 'brain' });
const serialized = JSON.stringify(result);
@@ -86,6 +88,7 @@ describe('agentContextMcp service', () => {
expect(serialized).not.toContain('[email protected]');
expect(serialized).not.toContain('/Users/alice');
expect(serialized).not.toContain('sk-12345678901234567890');
+ expect(serialized).not.toContain('never expose this projected field');
});
it('rejects reads outside configured scopes', async () => {
@@ -106,6 +109,7 @@ describe('agentContextMcp service', () => {
expect(bounded.structuredContent.items).toHaveLength(AGENT_CONTEXT_LIMITS.maxResults);
expect(bounded.structuredContent.truncated).toBe(true);
expect(bounded.structuredContent.sourceTruncated).toBe(true);
+ expect(bounded.structuredContent.sourceStatus).toBe('fresh');
mocks.listContexts.mockRejectedValue(new Error('catalog unavailable'));
const failed = await callAgentContextTool('list_context', { scope: 'workspaces' });
@@ -120,6 +124,7 @@ describe('agentContextMcp service', () => {
});
const navigation = await callAgentContextTool('resolve_navigation', { query: 'home' });
expect(navigation.structuredContent.match).toMatchObject({ title: 'Dashboard', path: '/' });
+ expect(navigation.structuredContent.sourceStatus).toBe('fresh');
const identity = await callAgentContextTool('list_context', { scope: 'identity' });
expect(identity.structuredContent.items[0].summary).toMatch(/raw records are excluded/);
diff --git a/server/test/fixtures/agent-context-eval.json b/server/test/fixtures/agent-context-eval.json
new file mode 100644
index 0000000000..175356aeff
--- /dev/null
+++ b/server/test/fixtures/agent-context-eval.json
@@ -0,0 +1,376 @@
+{
+ "name": "agent-context-public-contract",
+ "version": 1,
+ "fixtures": {
+ "complete": {
+ "navigation": [
+ {
+ "id": "nav.example-home",
+ "path": "/example-home",
+ "label": "Example Home",
+ "section": "Example",
+ "aliases": ["home"],
+ "keywords": ["overview"]
+ }
+ ],
+ "workspaces": [
+ {
+ "appId": "fixture-app-1",
+ "appName": "Example Workspace One",
+ "taskCount": 1,
+ "repoPath": "/tmp/example-one",
+ "savedBranch": "private-branch-one"
+ },
+ {
+ "appId": "fixture-app-2",
+ "appName": "Example Workspace Two",
+ "taskCount": 2,
+ "repoPath": "/tmp/example-two",
+ "savedBranch": "private-branch-two"
+ },
+ {
+ "appId": "fixture-app-3",
+ "appName": "Example Workspace Three",
+ "taskCount": 3,
+ "repoPath": "/tmp/example-three",
+ "savedBranch": "private-branch-three"
+ }
+ ],
+ "brain": {
+ "projects": [
+ {
+ "id": "fixture-project-1",
+ "title": "Example Secret Project",
+ "description": "Contact [email protected] at 192.0.2.10 from /Users/alice/example.",
+ "privateBody": "FORBIDDEN_FIXTURE_BODY"
+ }
+ ]
+ },
+ "identity": {
+ "identity": {
+ "label": "Example Identity",
+ "present": true,
+ "privateBody": "FORBIDDEN_IDENTITY_BODY"
+ }
+ }
+ },
+ "stale": {
+ "workspaces": [
+ {
+ "appId": "fixture-stale-app",
+ "appName": "Example Stale Workspace",
+ "taskCount": 1
+ }
+ ],
+ "sourceStatus": {
+ "workspaces": "stale"
+ }
+ },
+ "source-error": {
+ "errors": ["workspaces"]
+ }
+ },
+ "cases": [
+ {
+ "id": "manifest-tool-parity",
+ "title": "Manifest advertises the complete read-only runtime surface",
+ "severity": "critical",
+ "source": "server/test/fixtures/agent-context-eval.json#manifest-tool-parity",
+ "fixture": "complete",
+ "operation": "manifest",
+ "settings": {
+ "agentContext": {
+ "enabled": true,
+ "profile": "summary",
+ "scopes": ["navigation", "workspaces", "brain", "identity"]
+ }
+ },
+ "expect": {
+ "advertisedToolsCovered": true,
+ "readOnlyTools": true,
+ "equals": [
+ { "path": "manifest.schemaVersion", "value": 2 },
+ { "path": "manifest.limits.maxApproxTokens", "value": 5000 },
+ { "path": "manifest.tools.length", "value": 5 }
+ ],
+ "contains": [
+ { "path": "manifest.exclusions", "value": "Privacy Vault and encrypted privacy records" }
+ ]
+ }
+ },
+ {
+ "id": "profile-scope-and-budgets",
+ "title": "Profile reports the selected scopes and bounded budgets",
+ "severity": "high",
+ "source": "server/test/fixtures/agent-context-eval.json#profile-scope-and-budgets",
+ "fixture": "complete",
+ "operation": "tool",
+ "tool": "context_profile",
+ "args": {},
+ "settings": {
+ "agentContext": {
+ "enabled": true,
+ "profile": "summary",
+ "scopes": ["navigation", "workspaces", "brain", "identity"]
+ }
+ },
+ "expect": {
+ "isError": false,
+ "inputSchemaValid": true,
+ "outputSchemaValid": true,
+ "contentParity": true,
+ "withinBudgets": true,
+ "equals": [
+ { "path": "output.profile", "value": "summary" },
+ { "path": "output.scopes", "value": ["navigation", "workspaces", "brain", "identity"] }
+ ]
+ }
+ },
+ {
+ "id": "search-redacts-and-omits-fields",
+ "title": "Search matches fixture text without leaking forbidden values or fields",
+ "severity": "critical",
+ "source": "server/test/fixtures/agent-context-eval.json#search-redacts-and-omits-fields",
+ "fixture": "complete",
+ "operation": "tool",
+ "tool": "search_context",
+ "args": { "query": "secret", "scopes": ["brain"] },
+ "settings": {
+ "agentContext": {
+ "enabled": true,
+ "profile": "summary",
+ "scopes": ["brain"]
+ }
+ },
+ "expect": {
+ "isError": false,
+ "inputSchemaValid": true,
+ "outputSchemaValid": true,
+ "contentParity": true,
+ "withinBudgets": true,
+ "contains": [
+ { "path": "output.items.0.summary", "value": "[REDACTED EMAIL]" },
+ { "path": "output.items.0.summary", "value": "[REDACTED IP]" }
+ ],
+ "excludes": [
+ "192.0.2.10",
+ "/Users/alice",
+ "FORBIDDEN_FIXTURE_BODY"
+ ],
+ "absentKeys": ["privateBody"]
+ }
+ },
+ {
+ "id": "get-unknown-record",
+ "title": "Unknown opaque references return an honest null result",
+ "severity": "medium",
+ "source": "server/test/fixtures/agent-context-eval.json#get-unknown-record",
+ "fixture": "complete",
+ "operation": "tool",
+ "tool": "get_context",
+ "args": { "ref": "brain:projects:does-not-exist" },
+ "settings": {
+ "agentContext": {
+ "enabled": true,
+ "profile": "metadata",
+ "scopes": ["brain"]
+ }
+ },
+ "expect": {
+ "isError": false,
+ "inputSchemaValid": true,
+ "outputSchemaValid": true,
+ "contentParity": true,
+ "equals": [
+ { "path": "output.item", "value": null },
+ { "path": "output.sourceStatus", "value": "fresh" }
+ ]
+ }
+ },
+ {
+ "id": "list-pagination-and-field-boundary",
+ "title": "List honors result limits and omits workspace implementation fields",
+ "severity": "high",
+ "source": "server/test/fixtures/agent-context-eval.json#list-pagination-and-field-boundary",
+ "fixture": "complete",
+ "operation": "tool",
+ "tool": "list_context",
+ "args": { "scope": "workspaces", "limit": 2 },
+ "settings": {
+ "agentContext": {
+ "enabled": true,
+ "profile": "metadata",
+ "scopes": ["workspaces"]
+ }
+ },
+ "expect": {
+ "isError": false,
+ "inputSchemaValid": true,
+ "outputSchemaValid": true,
+ "contentParity": true,
+ "withinBudgets": true,
+ "equals": [
+ { "path": "output.total", "value": 3 },
+ { "path": "output.nextCursor", "value": 2 },
+ { "path": "output.truncated", "value": true }
+ ],
+ "maxItems": [
+ { "path": "output.items", "value": 2 }
+ ],
+ "excludes": [
+ "Example Workspace One",
+ "/tmp/example-one",
+ "private-branch-one",
+ "fixture-app-1"
+ ],
+ "absentKeys": ["repoPath", "savedBranch", "appId"]
+ }
+ },
+ {
+ "id": "navigation-resolution",
+ "title": "Navigation resolves only through the advertised fixture command",
+ "severity": "medium",
+ "source": "server/test/fixtures/agent-context-eval.json#navigation-resolution",
+ "fixture": "complete",
+ "operation": "tool",
+ "tool": "resolve_navigation",
+ "args": { "query": "home" },
+ "settings": {
+ "agentContext": {
+ "enabled": true,
+ "profile": "metadata",
+ "scopes": ["navigation"]
+ }
+ },
+ "expect": {
+ "isError": false,
+ "inputSchemaValid": true,
+ "outputSchemaValid": true,
+ "contentParity": true,
+ "equals": [
+ { "path": "output.match.path", "value": "/example-home" },
+ { "path": "output.sourceStatus", "value": "fresh" }
+ ]
+ }
+ },
+ {
+ "id": "stale-source-signaling",
+ "title": "A stale fixture source is explicit in the public result",
+ "severity": "high",
+ "source": "server/test/fixtures/agent-context-eval.json#stale-source-signaling",
+ "fixture": "stale",
+ "operation": "tool",
+ "tool": "list_context",
+ "args": { "scope": "workspaces" },
+ "settings": {
+ "agentContext": {
+ "enabled": true,
+ "profile": "metadata",
+ "scopes": ["workspaces"]
+ }
+ },
+ "expect": {
+ "isError": false,
+ "inputSchemaValid": true,
+ "outputSchemaValid": true,
+ "equals": [
+ { "path": "output.sourceStatus", "value": "stale" }
+ ]
+ }
+ },
+ {
+ "id": "identity-privacy-boundary",
+ "title": "Identity results expose presence metadata without fixture payloads",
+ "severity": "critical",
+ "source": "server/test/fixtures/agent-context-eval.json#identity-privacy-boundary",
+ "fixture": "complete",
+ "operation": "tool",
+ "tool": "list_context",
+ "args": { "scope": "identity" },
+ "settings": {
+ "agentContext": {
+ "enabled": true,
+ "profile": "summary",
+ "scopes": ["identity"]
+ }
+ },
+ "expect": {
+ "isError": false,
+ "inputSchemaValid": true,
+ "outputSchemaValid": true,
+ "contains": [
+ { "path": "output.items.0.summary", "value": "raw records are excluded" }
+ ],
+ "excludes": ["FORBIDDEN_IDENTITY_BODY"],
+ "absentKeys": ["privateBody"]
+ }
+ },
+ {
+ "id": "invalid-result-limit",
+ "title": "Inputs above the advertised result limit fail before source access",
+ "severity": "high",
+ "source": "server/test/fixtures/agent-context-eval.json#invalid-result-limit",
+ "fixture": "complete",
+ "operation": "tool",
+ "tool": "list_context",
+ "args": { "scope": "workspaces", "limit": 26 },
+ "settings": {
+ "agentContext": {
+ "enabled": true,
+ "profile": "metadata",
+ "scopes": ["workspaces"]
+ }
+ },
+ "expect": {
+ "isError": true,
+ "inputSchemaValid": false,
+ "contains": [
+ { "path": "toolResult.content.0.text", "value": "Invalid tool input" }
+ ]
+ }
+ },
+ {
+ "id": "source-error-is-not-empty",
+ "title": "Source failures remain errors instead of empty successful results",
+ "severity": "high",
+ "source": "server/test/fixtures/agent-context-eval.json#source-error-is-not-empty",
+ "fixture": "source-error",
+ "operation": "tool",
+ "tool": "list_context",
+ "args": { "scope": "workspaces" },
+ "settings": {
+ "agentContext": {
+ "enabled": true,
+ "profile": "metadata",
+ "scopes": ["workspaces"]
+ }
+ },
+ "expect": {
+ "isError": true,
+ "inputSchemaValid": true,
+ "contains": [
+ { "path": "toolResult.content.0.text", "value": "Context source unavailable" }
+ ]
+ }
+ },
+ {
+ "id": "localized-profile",
+ "title": "Localized context labels",
+ "severity": "low",
+ "source": "server/test/fixtures/agent-context-eval.json#localized-profile",
+ "fixture": "complete",
+ "operation": "tool",
+ "tool": "context_profile",
+ "args": {},
+ "settings": {
+ "agentContext": {
+ "enabled": true,
+ "profile": "metadata",
+ "scopes": ["navigation"]
+ }
+ },
+ "skip": "The agent-context schema does not advertise localization yet."
+ }
+ ]
+}