Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Send environment inventories once, then only changes (#2209)

Regan Bell5e0ccb410299
diff --git a/package-lock.json b/package-lock.json
index 66cdbbd4a..c7c3cc669 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -33,6 +33,7 @@
"@smithy/signature-v4": "^5.6.6",
"@superserve/sdk": "^0.8.3",
"croner": "^10.0.1",
+ "cronstrue": "3.29.0",
"e2b": "^2.51.0",
"emoji-datasource": "^16.0.0",
"fastify": "^5.12.5",
@@ -5566,6 +5567,15 @@
"node": ">=18.0"
}
},
+ "node_modules/cronstrue": {
+ "version": "3.29.0",
+ "resolved": "https://registry.npmjs.org/cronstrue/-/cronstrue-3.29.0.tgz",
+ "integrity": "sha512-jSs7/VEuy9o449mDY5eZFb7lYMByQ7uZWHnIjzOQE5kfpKnwcqFGtfVvKgxLtDOmZkbD0e37BMFGHdpOvESpdg==",
+ "license": "MIT",
+ "bin": {
+ "cronstrue": "bin/cli.js"
+ }
+ },
"node_modules/cross-spawn": {
"version": "7.0.6",
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
diff --git a/package.json b/package.json
index f69516ff0..3c3843277 100644
--- a/package.json
+++ b/package.json
@@ -92,6 +92,7 @@
"@smithy/signature-v4": "^5.6.6",
"@superserve/sdk": "^0.8.3",
"croner": "^10.0.1",
+ "cronstrue": "3.29.0",
"e2b": "^2.51.0",
"emoji-datasource": "^16.0.0",
"fastify": "^5.12.5",
diff --git a/src/core/environment-facts.ts b/src/core/environment-facts.ts
index 2f24e8a66..1849c432e 100644
--- a/src/core/environment-facts.ts
+++ b/src/core/environment-facts.ts
@@ -1,3 +1,7 @@
+import { createHash } from "node:crypto";
+import { retainedSnapshot } from "../harness/context-snapshot.ts";
+import type { SandboxResources } from "../sandbox/sandbox-resources.ts";
+import type { SessionEntry } from "../types.ts";
import type { AgentComputerSpec } from "../sandbox/sandbox.ts";
import { connectorLabel, type ConnectorStatusRecord } from "../credentials/connector-status.ts";
@@ -73,3 +77,58 @@ export function renderConnectedAppsBlock(
}
return lines.join("\n");
}
+
+interface EnvironmentSnapshot {
+ hashes: Record<string, string>;
+ sessionId: string;
+ anchorSeq?: number;
+}
+
+export function environmentDelta(
+ blocks: Record<string, string>,
+ history: readonly SessionEntry[],
+ sessionId: string,
+): { text: string; record: EnvironmentSnapshot } {
+ const { previous, anchorSeq } = retainedSnapshot(
+ history,
+ (entry) => (entry.payload as { environmentSnapshot?: EnvironmentSnapshot } | null)?.environmentSnapshot,
+ );
+ const current = Object.fromEntries(Object.entries(blocks).filter(([, text]) => text.trim()));
+ const hashes = Object.fromEntries(
+ Object.entries(current).map(([key, text]) => [key, createHash("sha256").update(text).digest("hex")]),
+ );
+ const record = { hashes, sessionId, ...(anchorSeq !== undefined ? { anchorSeq } : {}) };
+ if (!previous) return { text: Object.values(current).join("\n\n"), record };
+ const changed = Object.entries(current).filter(([key]) => previous.hashes[key] !== hashes[key]);
+ const removed = Object.keys(previous.hashes).filter((key) => !(key in current));
+ return {
+ text:
+ changed.length || removed.length
+ ? [
+ "Environment changes: sections below replace their earlier versions; unlisted sections are unchanged. Inventories are not permission grants; access is checked live.",
+ ...changed.map(([, text]) => text),
+ ...removed.map((key) => `No longer included: ${key}. Do not rely on its earlier inventory.`),
+ ].join("\n\n")
+ : "",
+ record,
+ };
+}
+
+export function renderSandboxProfiles(
+ providers: ReturnType<SandboxResources["profiles"]>,
+ layout: WorkspaceLayoutInfo,
+): Record<string, string> {
+ return Object.fromEntries(
+ providers
+ .toSorted((a, b) => a.name.localeCompare(b.name))
+ .map((provider) => [
+ `Sandbox provider ${provider.name}`,
+ [
+ `## Sandbox provider ${provider.name}`,
+ `Available actions: ${provider.actions.toSorted().join(", ")}.`,
+ renderComputerBlock(provider.spec, layout).replace("## Sandbox environment profile\n", "") ||
+ "Environment profile unknown.",
+ ].join("\n"),
+ ]),
+ );
+}
diff --git a/src/core/orchestrator.ts b/src/core/orchestrator.ts
index 1c22f9dff..a84036c65 100644
--- a/src/core/orchestrator.ts
+++ b/src/core/orchestrator.ts
@@ -1,3 +1,4 @@
+import { DEFAULT_CRON_TIMEZONE } from "../cron/schedule.ts";
import { createAdminCall } from "../tools/admin.ts";
import { scopeTeamsToTurn } from "../teams/teams.ts";
import { externalSlackRequestAllowed, currentExternalSlackRun } from "../resolution/external-slack.ts";
@@ -72,7 +73,12 @@ import {
connectorStatusIsStale,
refreshConnectorStatus,
} from "../credentials/connector-status.ts";
-import { renderComputerBlock, renderConnectedAppsBlock } from "./environment-facts.ts";
+import {
+ environmentDelta,
+ renderComputerBlock,
+ renderConnectedAppsBlock,
+ renderSandboxProfiles,
+} from "./environment-facts.ts";
import { PROVIDERS } from "../connectors/oauth.ts";
import { estimateCostUsd } from "../ratelimit/budget.ts";
import {
@@ -1159,7 +1165,7 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
if (external)
systemPrompt +=
"\n\nThis conversation has an external Slack audience. Answer and run code here using only the explicitly provided shared service credentials. Personal memory, files, keychains, connected apps, organization data and administrative tools are unavailable. When personal access is needed, say briefly that you are continuing privately, and include [[continue-private: task]] in your final answer. The continuation goes only to the authenticated requester; never put private results in this channel.";
- const turnContextBlocks: string[] = [];
+ const turnContextBlocks: Record<string, string> = {};
if (input.privateSessionMessage)
systemPrompt +=
"\n\nThis is a private message from another session. You may read context and reply using session.write with the sender session ID. Replies remain private and read-only. Do not open children or interrupt work. Reply only when there is useful information to send; reply chains are bounded.";
@@ -1282,11 +1288,6 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
const turnInboxDir = `${turnFilesDir}/${INBOX_DIR}`;
const turnSharedDir = `${turnFilesDir}/${SHARED_DIR}`;
- const computerBlock = renderComputerBlock(scopeProfile.spec, {
- hasGlobal: resolution.layers.some((l) => l.mountPath === "global"),
- teamCount: resolution.layers.filter((l) => l.mountPath.startsWith("team-")).length,
- });
- turnContextBlocks.push(computerBlock);
if (!external && deps.scratchExec) {
systemPrompt +=
'\n\nSelect a sandbox explicitly or use a stored default. The opt-in scratch box (scope:"scratch") is separate: same OS/tooling, read-only org-global files, this conversation\'s scoped Files/API capabilities, and credentials explicitly requested per execute call. Its local files are wiped after the turn, and resident workspace files and cached CLI logins are not restored. Use it for self-contained commands and API work; publish needed outputs to Files and verify success. Use scoped execution for existing workspace state or work that must continue locally.';
@@ -1294,21 +1295,21 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
if (!external && deps.deploymentLayer?.hints.length) {
systemPrompt += `\n\n## Deployment tool hints\n${deps.deploymentLayer.hints.map((hint) => `- ${hint}`).join("\n")}`;
}
- if (visibleSkills.length) systemPrompt += `\n\n${skillsIndex(visibleSkills, sharingSources)}`;
+ if (visibleSkills.length) turnContextBlocks["Skills"] = skillsIndex(visibleSkills, sharingSources);
const gatewayBlock = renderGatewayContext(input.surface, input.gatewayContext);
- if (gatewayBlock) systemPrompt += `\n\n${gatewayBlock}`;
+ if (gatewayBlock) turnContextBlocks["Where you are"] = gatewayBlock;
const homeChannel =
conversation.kind === "group" && conversation.channelRef
? await deps.managedGroups
?.slackChannel?.(conversation.channelRef)
.catch(swallowAs("orchestrator: project home channel read", undefined))
: undefined;
- if (homeChannel) systemPrompt += `\n\n${renderProjectHomeChannel(homeChannel.channelName)}`;
- systemPrompt += cronBlock;
+ if (homeChannel) turnContextBlocks["Project home channel"] = renderProjectHomeChannel(homeChannel.channelName);
+ turnContextBlocks["Where scheduled tasks post"] = cronBlock;
const sharedFilesBlock = sharedFilesSystemSection(resolution.grantedHandles);
- if (sharedFilesBlock) systemPrompt += `\n\n${sharedFilesBlock}`;
+ if (sharedFilesBlock) turnContextBlocks["Files shared with you"] = sharedFilesBlock;
- const timeBlock = turnTimezone ? currentTimeBlock(turnTimezone, Date.now()) : "";
+ const timeBlock = currentTimeBlock(turnTimezone ?? DEFAULT_CRON_TIMEZONE, Date.now());
let memoryContext = "a channel";
if (conversation.kind === "dm") memoryContext = "a direct message";
else if (conversation.channelName) memoryContext = `#${conversation.channelName}`;
@@ -1971,6 +1972,15 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
)),
})
: deps.sandboxResources;
+ const workspaceLayout = {
+ hasGlobal: resolution.layers.some((l) => l.mountPath === "global"),
+ teamCount: resolution.layers.filter((l) => l.mountPath.startsWith("team-")).length,
+ };
+ if (turnSandboxResources) {
+ Object.assign(turnContextBlocks, renderSandboxProfiles(turnSandboxResources.profiles(), workspaceLayout));
+ } else {
+ turnContextBlocks["Sandbox environment profile"] = renderComputerBlock(scopeProfile.spec, workspaceLayout);
+ }
const {
box,
@@ -2346,13 +2356,13 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
),
hooks.filter((w) => w.enabled && w.ownerScopeId === scopeId),
mons.filter((m) => m.ownerScopeId === scopeId && m.expiresAt > nowMs),
+ turnTimezone,
),
)
.catch(swallowAs("orchestrator: standing-obligations read", null));
- turnContextBlocks.push(
+ turnContextBlocks["Already scheduled here"] =
obligations ??
- "## Already scheduled here\nScheduled-work status is unavailable; check the live inventories before scheduling.",
- );
+ "## Already scheduled here\nScheduled-work status is unavailable; check the live inventories before scheduling.";
}
if (input.origin.kind === "automation" && input.origin.destination && !input.surfaceTools) {
systemPrompt +=
@@ -2367,7 +2377,7 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
await reachableChannelsFor(deps.directory!, actor.id),
actor.displayName ?? "this person",
);
- if (roster) systemPrompt += `\n\n${roster}`;
+ if (roster) turnContextBlocks["Other computers you can reach"] = roster;
}
if (!external && deps.directory) {
const rosterBlock = await (async () => {
@@ -2389,7 +2399,7 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
}
return renderConversationRoster(resolved);
})().catch(swallowAs("orchestrator: conversation roster", null));
- if (rosterBlock) systemPrompt += `\n\n${rosterBlock}`;
+ if (rosterBlock) turnContextBlocks["Who’s in this conversation"] = rosterBlock;
}
if (!strictReadOnly && (deps.keychain || credentialDescriptions.length)) {
const audienceMembers = conversation.audience.filter((p) => p.type === "internal");
@@ -2415,7 +2425,7 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
execution: credentialDescriptions,
scopeAsks,
});
- if (keychainBlock) systemPrompt += `\n\n${keychainBlock}`;
+ if (keychainBlock) turnContextBlocks["Credentials"] = keychainBlock;
}
if (!strictReadOnly && deps.resolveConnectorClient && conversation.kind === "dm") {
let status = null;
@@ -2429,7 +2439,7 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
swallow("orchestrator: connected-app status", e);
}
const connectionsUrl = deps.publicWebUrl ? `${deps.publicWebUrl.replace(/\/$/, "")}/keychain` : undefined;
- systemPrompt += `\n\n${renderConnectedAppsBlock(status, configuredProviders, connectionsUrl)}`;
+ turnContextBlocks["Connected apps"] = renderConnectedAppsBlock(status, configuredProviders, connectionsUrl);
}
const stableSystemBytes = systemPrompt.length;
if (swarmBinding)
@@ -3166,7 +3176,6 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
sender,
unscreenedNote,
input.conversationHeader?.trim(),
- ...turnContextBlocks,
volatileContext,
]
.filter((s) => s && s.trim())
@@ -3444,8 +3453,11 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
},
) => {
const recall = memoryRecallDelta(recalled, continuation?.history ?? history);
+ const snapshot = environmentDelta(turnContextBlocks, continuation?.history ?? history, session.id);
const turnEnvironment = environmentNote(
- [turnEnvironmentContents, recall.text ? `${memoryHeading}${recall.text}` : ""].filter(Boolean).join("\n\n"),
+ [turnEnvironmentContents, snapshot.text, recall.text ? `${memoryHeading}${recall.text}` : ""]
+ .filter(Boolean)
+ .join("\n\n"),
);
const environment = [turnEnvironment, ...documentInputs.notices].filter(Boolean).join("\n");
let recordedRecall = false;
@@ -3481,6 +3493,7 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
if (!recordedRecall && !payload.steered && !payload.overheard) {
recordedRecall = true;
payload.memoryContext = nextContext;
+ payload.environmentSnapshot = snapshot.record;
if (environment) payload.environment = environment;
if (recall.text) payload.memoryRecall = recall.record;
}
@@ -3659,7 +3672,7 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
...(codexTurnAuth ? { codexAuth: codexTurnAuth } : {}),
...(input.runId ? { runId: input.runId } : {}),
cancel: turnAbort.signal,
- ...(continueTurn && !continuation ? { continueTurn: true } : {}),
+ ...(continueTurn && !continuation && !snapshot.text && !recall.text ? { continueTurn: true } : {}),
...(input.shutdown ? { shutdown: input.shutdown } : {}),
input: harnessInput,
...(!partial && messageTs ? { triggerTs: messageTs } : {}),
diff --git a/src/core/orchestrator/prompt-blocks.ts b/src/core/orchestrator/prompt-blocks.ts
index 54b511ef2..4a163194c 100644
--- a/src/core/orchestrator/prompt-blocks.ts
+++ b/src/core/orchestrator/prompt-blocks.ts
@@ -1,3 +1,5 @@
+import cronstrue from "cronstrue";
+import { DEFAULT_CRON_TIMEZONE } from "../../cron/schedule.ts";
import type { CandidateDestination, Cron, Monitor, Webhook } from "../../types.ts";
import type { DirectoryChannel, DirectoryMember } from "../../directory/directory-store.ts";
@@ -29,46 +31,59 @@ export function renderProjectHomeChannel(channelName: string): string {
].join("\n");
}
-const OBLIGATIONS_CAP = 10;
-function cronSchedulePromptLabel(c: Cron): string {
+function localIsoTime(timezone: string, nowMs: number): string {
+ const parts = new Intl.DateTimeFormat("en-CA", {
+ timeZone: timezone,
+ year: "numeric",
+ month: "2-digit",
+ day: "2-digit",
+ hour: "2-digit",
+ minute: "2-digit",
+ second: "2-digit",
+ hourCycle: "h23",
+ timeZoneName: "longOffset",
+ }).formatToParts(nowMs);
+ const fields = Object.fromEntries(parts.map(({ type, value }) => [type, value]));
+ const offset = fields.timeZoneName === "GMT" ? "+00:00" : fields.timeZoneName!.slice(3);
+ return `${fields.year}-${fields.month}-${fields.day}T${fields.hour}:${fields.minute}:${fields.second}${offset}`;
+}
+
+function cronSchedulePromptLabel(c: Cron, timezone: string): string {
const schedule = c.schedule;
- if (schedule.cron) return `cron ${schedule.cron}${schedule.timezone ? ` ${schedule.timezone}` : " default timezone"}`;
- return schedule.everyMs != null
- ? `every ${Math.max(1, Math.round(schedule.everyMs / 60_000))}m`
- : `once at ${new Date(schedule.firstFireAt ?? c.createdAt).toISOString()}`;
+ if (schedule.cron)
+ return `${cronstrue.toString(schedule.cron.replaceAll("#L", "L"))} (${schedule.timezone ?? DEFAULT_CRON_TIMEZONE})`;
+ if (schedule.everyMs != null) {
+ for (const [size, unit] of [
+ [3_600_000, "hours"],
+ [60_000, "minutes"],
+ [1000, "seconds"],
+ ] as const) {
+ if (schedule.everyMs % size === 0) return `every ${schedule.everyMs / size} ${unit}`;
+ }
+ return `every ${schedule.everyMs} milliseconds`;
+ }
+ return `once at ${localIsoTime(timezone, schedule.firstFireAt ?? c.createdAt)}`;
}
-export function renderStandingObligations(crons: Cron[], webhooks: Webhook[], monitors: Monitor[]): string {
- const total = crons.length + webhooks.length + monitors.length;
- if (total === 0) return "## Already scheduled here\nNo active scheduled work was found for this conversation.";
- const snippet = (s: string) => (s.length > 100 ? `${s.slice(0, 97)}…` : s).replace(/\s+/g, " ");
+export function renderStandingObligations(
+ crons: Cron[],
+ webhooks: Webhook[],
+ monitors: Monitor[],
+ timezone = DEFAULT_CRON_TIMEZONE,
+): string {
+ const summary = (text: string) => (text.length > 100 ? `${text.slice(0, 97)}…` : text);
const lines = [
...crons
.toSorted((a, b) => a.id.localeCompare(b.id))
- .slice(0, OBLIGATIONS_CAP)
- .map(
- (c) =>
- `- cron \`${c.id}\`${c.title ? ` "${c.title}"` : ""} (${cronSchedulePromptLabel(c)}, owner ${c.owner}): ${snippet(c.action ?? c.message ?? "")}`,
- ),
- ...webhooks
- .toSorted((a, b) => a.id.localeCompare(b.id))
- .slice(0, OBLIGATIONS_CAP)
- .map((w) => `- webhook \`${w.id}\` (owner ${w.owner}): ${snippet(w.action)}`),
+ .map((c) => `- ${c.title || "Untitled scheduled task"} — ${cronSchedulePromptLabel(c, timezone)}`),
+ ...webhooks.toSorted((a, b) => a.id.localeCompare(b.id)).map((w) => `- Webhook: ${summary(w.action)}`),
...monitors
.toSorted((a, b) => a.id.localeCompare(b.id))
- .slice(0, OBLIGATIONS_CAP)
- .map((m) => `- job watch on \`${m.processId}\`: ${snippet(m.purpose ?? m.command)}`),
+ .map((m) => `- Job watch: ${summary(m.purpose ?? m.command)}`),
];
return [
"## Already scheduled here",
- ...lines,
- ...(total > lines.length
- ? [
- `…and ${total - lines.length} more — \`cron\` action=list${
- webhooks.length > OBLIGATIONS_CAP ? " / `webhook` action=list" : ""
- }.`,
- ]
- : []),
+ ...(lines.length ? lines : ["No active scheduled work was found for this conversation."]),
].join("\n");
}
@@ -107,16 +122,5 @@ export function renderConversationRoster(members: DirectoryMember[]): string | n
}
export function currentTimeBlock(timezone: string, nowMs: number): string {
- let local: string;
- try {
- local = new Intl.DateTimeFormat("en-US", { timeZone: timezone, dateStyle: "full", timeStyle: "short" }).format(
- nowMs,
- );
- } catch {
- return "";
- }
- return [
- "## The user's local time",
- `It is currently ${local} for this user (timezone ${timezone}). Read "today", "tonight", "9am my time" and similar against this timezone unless they say otherwise.`,
- ].join("\n");
+ return `## The user's local time\n${localIsoTime(timezone, nowMs)} (${timezone})`;
}
diff --git a/src/harness/context-snapshot.ts b/src/harness/context-snapshot.ts
new file mode 100644
index 000000000..1b518d2dc
--- /dev/null
+++ b/src/harness/context-snapshot.ts
@@ -0,0 +1,15 @@
+import type { SessionEntry } from "../types.ts";
+
+export function retainedSnapshot<T extends { anchorSeq?: number; sessionId?: string }>(
+ history: readonly SessionEntry[],
+ read: (entry: SessionEntry) => T | undefined,
+): { previous?: T; anchorSeq?: number } {
+ const entry = history.findLast((entry) => entry.type === "user" && read(entry));
+ const previous = entry && read(entry);
+ if (!entry || !previous || (previous.sessionId !== undefined && previous.sessionId !== entry.sessionId)) return {};
+ const anchorSeq = previous.anchorSeq ?? entry.seq;
+ const anchor = history.find((candidate) => candidate.seq === anchorSeq && candidate.type === "user");
+ const baseline = anchor && read(anchor);
+ if (!baseline || baseline.anchorSeq !== undefined) return {};
+ return { previous, anchorSeq };
+}
diff --git a/src/memory/recall-delta.ts b/src/memory/recall-delta.ts
index cb8993a62..28ce77bcd 100644
--- a/src/memory/recall-delta.ts
+++ b/src/memory/recall-delta.ts
@@ -1,3 +1,4 @@
+import { retainedSnapshot } from "../harness/context-snapshot.ts";
import type { SessionEntry } from "../types.ts";
import { isMemoryBookkeeping } from "./notebook.ts";
@@ -58,17 +59,13 @@ export function memoryRecallDelta(
history: readonly SessionEntry[],
authorizedScopes: readonly string[] = [...body.matchAll(/^### ([^\s:]+:[^\n]+)$/gm)].map((match) => match[1]!),
): { text: string; record: RecallRecord } {
- const previousEntry = history.findLast(
- (entry) =>
- entry.type === "user" &&
- typeof (entry.payload as { memoryRecall?: RecallRecord } | null)?.memoryRecall?.body === "string",
+ const { previous, anchorSeq } = retainedSnapshot(
+ history,
+ (entry) => (entry.payload as { memoryRecall?: RecallRecord } | null)?.memoryRecall,
);
- const previous = (previousEntry?.payload as { memoryRecall?: RecallRecord } | undefined)?.memoryRecall;
- const anchorSeq = previous?.anchorSeq ?? previousEntry?.seq;
- const retained = anchorSeq !== undefined && history.some((entry) => entry.seq === anchorSeq);
- const record = { body, ...(retained ? { anchorSeq } : {}) };
+ const record = { body, ...(anchorSeq !== undefined ? { anchorSeq } : {}) };
const newFacts = facts(body);
- if (!retained || !previous) return { text: render(newFacts.values()), record };
+ if (!previous) return { text: render(newFacts.values()), record };
if (previous.body === body) return { text: "", record };
const oldFacts = facts(previous.body);
const added = [...newFacts].filter(([key]) => !oldFacts.has(key)).map(([, fact]) => fact);
diff --git a/src/sandbox/sandbox-resources.ts b/src/sandbox/sandbox-resources.ts
index e267514f5..8f4bc0bda 100644
--- a/src/sandbox/sandbox-resources.ts
+++ b/src/sandbox/sandbox-resources.ts
@@ -37,7 +37,14 @@ export interface SandboxDefault {
sandboxId: string | null;
}
+interface SandboxProviderProfile {
+ name: SandboxBackendName;
+ spec?: AgentComputerSpec;
+ actions: string[];
+}
+
export interface SandboxResources {
+ profiles(): SandboxProviderProfile[];
forTurn(turn: { actorId: string; scopeId: ScopeId; isCurrent: () => Promise<boolean> }): SandboxResources;
initialize(): Promise<void>;
list(
@@ -47,7 +54,7 @@ export interface SandboxResources {
sandboxes: SandboxResource[];
defaultSandboxId: string | null;
defaultMode: "none" | "selected";
- providers: Array<{ name: SandboxBackendName; spec?: AgentComputerSpec; actions: string[] }>;
+ providers: SandboxProviderProfile[];
}>;
create(
actorId: string,
@@ -118,7 +125,16 @@ export function createSandboxResources(opts: {
return action();
});
};
+ const profiles = (): SandboxProviderProfile[] =>
+ (Object.entries(opts.backends) as Array<[SandboxBackendName, Sandbox]>)
+ .filter(([, backend]) => !!backend)
+ .map(([name, backend]) => ({
+ name,
+ ...(backend.profile.spec ? { spec: backend.profile.spec } : {}),
+ actions: actionsFor(backend),
+ }));
return {
+ profiles,
forTurn: (turn) =>
createSandboxResources({
...opts,
@@ -216,18 +232,11 @@ export function createSandboxResources(opts: {
availableActions = (record.cleanupPending || record.error) && backend?.destroyScope ? ["retire"] : [];
sandboxes.push({ ...record, holders: undefined, availableActions });
}
- const providers = (Object.entries(opts.backends) as Array<[SandboxBackendName, Sandbox]>)
- .filter(([, backend]) => !!backend)
- .map(([name, backend]) => ({
- name,
- ...(backend.profile.spec ? { spec: backend.profile.spec } : {}),
- actions: actionsFor(backend),
- }));
return {
sandboxes,
defaultSandboxId: route?.sandboxId ?? null,
defaultMode: route?.sandboxId ? "selected" : "none",
- providers,
+ providers: profiles(),
};
},
async create(actorId, scopeId, backend, name, reservationId) {
diff --git a/src/sessions/session-store.ts b/src/sessions/session-store.ts
index a76cde66a..b79c94455 100644
--- a/src/sessions/session-store.ts
+++ b/src/sessions/session-store.ts
@@ -588,7 +588,7 @@ export type TranscriptEntry = SessionEntry & { truncated?: true };
const PROJECTED_TYPES: ReadonlySet<EntryType> = new Set<EntryType>(["tool_call", "tool_result"]);
const MODEL_ONLY_FIELDS: Partial<Record<EntryType, ReadonlySet<string>>> = {
- user: new Set(["environment", "memoryRecall"]),
+ user: new Set(["environment", "environmentSnapshot", "memoryRecall"]),
thinking: new Set(["thinkingSignature"]),
};
const WALK_DEPTH = 8;
diff --git a/test/cache-observability.test.ts b/test/cache-observability.test.ts
index 1c75c0dc7..299551c9c 100644
--- a/test/cache-observability.test.ts
+++ b/test/cache-observability.test.ts
@@ -113,14 +113,21 @@ test("metrics: the cache aggregate reflects warm turns and flags a stable-prefix
conversation: { kind: "dm", threadRef: "dm:U3:m1" },
text: "!cachemiss",
};
- assert.equal((await s.built.app.turn(warm1)).status, "ok");
- assert.equal((await s.built.app.turn(warm2)).status, "ok");
- assert.equal((await s.built.app.turn(miss)).status, "ok");
+ const turns = [];
+ for (const request of [warm1, warm2, miss]) {
+ const result = await s.built.app.turn(request);
+ assert.equal(result.status, "ok");
+ const calls = await s.built.sessions.listLlmRequests(result.sessionId!);
+ const usage = calls.find((call) => call.model === "mock")!.usage!;
+ turns.push(usage.cacheRead! / (usage.cacheRead! + usage.cacheWrite! + usage.input));
+ }
const m = await getJson(s.base, "/v1/admin/metrics?scope=org:default-org");
assert.ok(m.cache, "the metrics response carries a cache block");
assert.equal(m.cache.samples, 3, "all three turns carried cache telemetry");
- assert.ok(m.cache.avgHitRatio > 0.5 && m.cache.avgHitRatio < 1, "avg hit ratio is the blend of warm + miss turns");
+ assert.ok(turns[0]! > 0 && turns[1]! > 0);
+ assert.equal(turns[2], 0);
+ assert.ok(Math.abs(m.cache.avgHitRatio - turns.reduce((sum, ratio) => sum + ratio, 0) / turns.length) < 1e-9);
assert.ok(
m.cache.pooledHitRatio > 0 && m.cache.pooledHitRatio <= 1,
"pooled (token-weighted) ratio is a real fraction",
@@ -178,7 +185,7 @@ test("history /llm: per-call usage (cacheRead/cacheWrite) is plumbed through to
cacheWrite: req.usage.cacheWrite,
uncachedInput: req.usage.input,
});
- assert.ok(ratio !== null && ratio > 0.5, "the call's hit ratio is high (warm)");
+ assert.ok(ratio !== null && ratio > 0 && ratio < 1, "the call serves cached prefix and uncached new context");
assert.equal(
isStablePrefixMiss({
cacheRead: req.usage.cacheRead,
diff --git a/test/context-compaction.test.ts b/test/context-compaction.test.ts
index fe56e7373..0990433f5 100644
--- a/test/context-compaction.test.ts
+++ b/test/context-compaction.test.ts
@@ -614,11 +614,11 @@ test("a DM follow-up after the background pass reuses the summary — no blockin
compactCalls.push(input);
return "tiny recap";
};
- const keptAfterFirstTurn = ["msg 4", "msg 5", "msg 6", "msg 7", "!histcount", "history:8"];
- const { orch, sessions } = buildOrchestrator(harness, budgetWhoseKeepWindowFits(tokensOf(...keptAfterFirstTurn)));
+ const messages = msgTexts(8).map((text) => `${text} ${"history ".repeat(1000)}`);
+ const { orch, sessions } = buildOrchestrator(harness, budgetBetweenSoftAndHard(tokensOf(...messages)));
const sid = await seed(
sessions,
- msgTexts(8).map((text) => ({ payload: { text } })),
+ messages.map((text) => ({ payload: { text } })),
);
await orch.handleTurn(turn("!histcount"));
@@ -626,10 +626,17 @@ test("a DM follow-up after the background pass reuses the summary — no blockin
assert.equal(compactCalls.length, 1);
await waitForLeaseRelease(sessions, sid);
+ const expectedHistory = forModelContext(await sessions.getEntries(sid));
+ assert.ok(expectedHistory.some((entry) => contextSummaryPayload(entry)));
+ assert.ok(expectedHistory.some((entry) => entry.type === "user"));
delete harness.models.compactHistory;
const res = await orch.handleTurn(turn("!histcount"));
assert.equal(res.status, "ok");
- assert.equal(res.reply, "history:7", "the follow-up starts on [summary, recent…] with no summarizer call");
+ assert.equal(
+ res.reply,
+ `history:${expectedHistory.length}`,
+ "the follow-up starts on [summary, recent…] with no summarizer call",
+ );
});
test("forModelContext strips thinking/text/soul (never laundered into a durable summary)", () => {
@@ -984,10 +991,7 @@ test("the background pass waits out a turn that holds the lock rather than throw
test("a turn landing mid-summarization does not disturb the fold: it covers a prefix, the turn's entries stay", async () => {
const { harness, compactCalls, open } = gatedHarness();
- const paddedTexts = Array.from(
- { length: 15 },
- (_, i) => `msg ${i} with enough padding words that a mid-summarization turn stays under the hard threshold`,
- );
+ const paddedTexts = Array.from({ length: 15 }, (_, i) => `msg ${i} ${"padding ".repeat(1000)}`);
const { orch, sessions } = buildOrchestrator(harness, budgetBetweenSoftAndHard(tokensOf(...paddedTexts)));
const sid = await seed(
sessions,
diff --git a/test/environment-delta.test.ts b/test/environment-delta.test.ts
new file mode 100644
index 000000000..257139b49
--- /dev/null
+++ b/test/environment-delta.test.ts
@@ -0,0 +1,132 @@
+import assert from "node:assert/strict";
+import { test } from "node:test";
+import { environmentDelta, renderSandboxProfiles } from "../src/core/environment-facts.ts";
+import { currentTimeBlock, renderStandingObligations } from "../src/core/orchestrator/prompt-blocks.ts";
+import { forModelContext } from "../src/harness/context-compaction.ts";
+import { reconstructMessagesFromHistory } from "../src/harness/replay.ts";
+import type { Cron, SessionEntry } from "../src/types.ts";
+
+function entry(seq: number, blocks: Record<string, string>, history: SessionEntry[]): SessionEntry {
+ const snapshot = environmentDelta(blocks, history, "s");
+ return {
+ sessionId: "s",
+ seq,
+ parentSeq: seq - 1,
+ type: "user",
+ createdAt: seq,
+ scopeLabel: "personal:U1",
+ payload: { text: "hello", environment: snapshot.text, environmentSnapshot: snapshot.record },
+ };
+}
+
+test("snapshots survive serialized replay and emit only changed or removed inventories", () => {
+ const original = { Credentials: "## Credentials\n- a\n- b", Sandboxes: "## Sandboxes\n- box" };
+ const first = entry(1, original, []);
+ const history: SessionEntry[] = JSON.parse(JSON.stringify([first]));
+ assert.equal(environmentDelta(original, history, "s").text, "");
+ const changed = { Credentials: "## Credentials\n- b\n- c" };
+ const second = entry(2, changed, history);
+ const text = (second.payload as { environment: string }).environment;
+ assert.match(text, /replace their earlier versions/);
+ assert.match(text, /- c/);
+ assert.doesNotMatch(text, /- a|- box/);
+ assert.match(text, /No longer included: Sandboxes/);
+ assert.equal(environmentDelta(changed, [...history, second], "s").text, "");
+ const replay = reconstructMessagesFromHistory([...history, second]);
+ assert.match(JSON.stringify(replay), /No longer included: Sandboxes/);
+});
+
+test("a compacted-away snapshot anchor resets the full baseline even when a later delta remains", () => {
+ const blocks = { Credentials: "## Credentials\n- a", Skills: "## Skills\n- browse" };
+ const first = entry(1, blocks, []);
+ const second = entry(2, { ...blocks, Credentials: "## Credentials\n- b" }, [first]);
+ const retained = forModelContext([second]);
+ const reset = environmentDelta({ ...blocks, Credentials: "## Credentials\n- b" }, retained, "s");
+ assert.match(reset.text, /## Skills/);
+ assert.doesNotMatch(reset.text, /Environment changes/);
+ assert.equal(reset.record.anchorSeq, undefined);
+});
+
+test("unrecorded attempts never advance the baseline; an emitted retry becomes the next baseline", () => {
+ const blocks = { Skills: "## Skills\n- browse" };
+ const first = entry(1, blocks, []);
+ const changed = { Skills: "## Skills\n- search" };
+ const attempt = environmentDelta(changed, [first], "s");
+ assert.equal(environmentDelta(changed, [first], "s").text, attempt.text);
+ const retry = entry(2, changed, [first]);
+ assert.equal(environmentDelta(changed, [first, retry], "s").text, "");
+ assert.match(environmentDelta({}, [first, retry], "s").text, /No longer included: Skills/);
+});
+
+test("local ISO clock follows daylight-saving transitions and non-hour offsets", () => {
+ assert.match(
+ currentTimeBlock("America/Los_Angeles", Date.parse("2026-03-08T09:59:59Z")),
+ /2026-03-08T01:59:59-08:00/,
+ );
+ assert.match(
+ currentTimeBlock("America/Los_Angeles", Date.parse("2026-03-08T10:00:00Z")),
+ /2026-03-08T03:00:00-07:00/,
+ );
+ assert.match(currentTimeBlock("Asia/Kathmandu", 0), /1970-01-01T05:30:00\+05:30/);
+});
+
+test("standing work includes all titles and readable timings, not IDs, owners or task bodies", () => {
+ const crons: Cron[] = Array.from({ length: 15 }, (_, i) => ({
+ id: `cron-${i}`,
+ ownerScopeId: "personal:U1",
+ owner: "private-owner",
+ createdBy: "U1",
+ createdAt: 0,
+ enabled: true,
+ title: `Task ${i}`,
+ action: "private instructions",
+ schedule: { cron: "0 8 * * 1,3,5", timezone: "America/Los_Angeles" },
+ }));
+ const text = renderStandingObligations(crons, [], []);
+ assert.equal(text.split("\n").filter((line) => line.startsWith("- ")).length, 15);
+ assert.match(text, /Task 14/);
+ assert.match(text, /08:00 AM, only on Monday, Wednesday, and Friday/);
+ assert.doesNotMatch(text, /cron-1|private instructions|private-owner|and .* more/);
+ assert.match(
+ renderStandingObligations(
+ [{ ...crons[0]!, schedule: { cron: "0 8 * * FRI#L", timezone: "America/Los_Angeles" } }],
+ [],
+ [],
+ ),
+ /last Friday/,
+ );
+ const once = renderStandingObligations(
+ [{ ...crons[0]!, schedule: { firstFireAt: Date.parse("2026-11-01T10:00:00Z") } }],
+ [],
+ [],
+ );
+ assert.match(once, /2026-11-01T02:00:00-08:00/);
+});
+
+test("live provider profiles represent configured and unknown capabilities without personal resources", () => {
+ const inventory = renderSandboxProfiles(
+ [
+ { name: "modal", actions: ["create"], spec: { os: "Linux", tools: ["node"] } },
+ { name: "sprites", actions: ["create"] },
+ ],
+ { hasGlobal: false, teamCount: 0 },
+ );
+ assert.match(inventory["Sandbox provider modal"]!, /node/);
+ assert.match(inventory["Sandbox provider sprites"]!, /unknown/);
+});
+
+test("forked entries cannot mistake a resequenced row for the original snapshot anchor", () => {
+ const blocks = { Skills: "## Skills\n- browse" };
+ const original = entry(5, blocks, []);
+ const delta = entry(8, blocks, [original]);
+ const fork = [
+ { ...original, sessionId: "fork", seq: 0 },
+ { ...delta, sessionId: "fork", seq: 1 },
+ ];
+ assert.equal(environmentDelta(blocks, fork, "fork").text, blocks.Skills);
+ assert.equal(environmentDelta(blocks, fork.slice(1), "fork").text, blocks.Skills);
+ assert.doesNotMatch(JSON.stringify(delta.payload), /## Skills.*## Skills/);
+ assert.ok(
+ !JSON.stringify((delta.payload as { environmentSnapshot: unknown }).environmentSnapshot).includes("browse"),
+ );
+});
diff --git a/test/keychain-ask.test.ts b/test/keychain-ask.test.ts
index ce2d8eee3..00449cf96 100644
--- a/test/keychain-ask.test.ts
+++ b/test/keychain-ask.test.ts
@@ -583,7 +583,7 @@ describe("/v1/keychain/asks — card approval end to end", async () => {
approvals.decide(askId, { externalId: actorId }, decision);
const resumeTurns = async (sessionId: string, pattern: RegExp) =>
(await built.sessions.getEntries(sessionId)).filter(
- (e) => e.type === "user" && pattern.test(JSON.stringify(e.payload)),
+ (e) => e.type === "user" && pattern.test((e.payload as { text: string }).text),
);
const capFor = (actorId: string, scope = scopeId("personal", actorId), extra: Partial<CapabilityClaims> = {}) =>
@@ -859,8 +859,13 @@ describe("/v1/keychain/asks — card approval end to end", async () => {
const resolution = await waitFor(() => resumeTurns(session!.id, /The credential owner approved access/));
assert.equal(resolution.length, 1, "exactly one resolution turn, in the original thread's session");
- const prompt = JSON.stringify(resolution[0]!.payload);
- assert.ok(!prompt.includes(ask.id) && !prompt.includes(grant.id), "no ids in the resume text");
+ const { text: prompt, environment } = resolution[0]!.payload as { text: string; environment: string };
+ assert.ok(
+ !prompt.includes(ask.id) && !prompt.includes(grant.id) && !prompt.includes(gh.id),
+ "no ids in the resume text",
+ );
+ assert.ok(environment.includes(`github:${gh.id}`), "the credential handle belongs in the inventory");
+ assert.ok(environment.includes(grant.id), "the inventory includes the approved grant");
assert.ok(!prompt.includes("clone acme/payments"), "no purpose text in the resume text");
await waitFor(async () =>
@@ -1187,7 +1192,7 @@ describe("/v1/keychain/asks — card approval end to end", async () => {
await built.scheduler.tick(Date.now());
const resolved = await waitFor(() => resumeTurns(session!.id, /did not answer the access request/));
assert.equal(resolved.length, 1, "exactly one expired-resolution turn in the asking thread");
- assert.ok(!JSON.stringify(resolved[0]!.payload).includes(made.ask.id));
+ assert.ok(!(resolved[0]!.payload as { text: string }).text.includes(made.ask.id));
await built.scheduler.tick(Date.now());
assert.equal(
diff --git a/test/keychain.test.ts b/test/keychain.test.ts
index b9f1c754c..86907c506 100644
--- a/test/keychain.test.ts
+++ b/test/keychain.test.ts
@@ -1288,14 +1288,16 @@ test("turn e2e: prompt lists exact handles and keychain env credentials are neve
mode: "standing",
purpose: "use my gh here for repo work",
});
+ const sys2 = await built.app.turn(channelTurn("!sysprompt", "U_ASKER", audience));
+ assert.match(sys2.reply ?? "", /STANDING grant .*use my gh here for repo work/);
+ assert.match(sys2.reply ?? "", new RegExp(`github:${cred.id}`));
+
mark = fakeSprites.execScripts().length;
assert.equal((await built.app.turn(channelTurn("!run true", "U_ASKER", audience))).status, "ok");
assert.ok(!execScriptsMention("export GITHUB_TOKEN=", mark), "standing grants are not ambient");
assert.ok(!execScriptsMention("ghp_e2e", mark), "an unrequested command never receives the secret");
-
- const sys2 = await built.app.turn(channelTurn("!sysprompt", "U_ASKER", audience));
- assert.match(sys2.reply ?? "", /STANDING grant .*use my gh here for repo work/);
- assert.match(sys2.reply ?? "", new RegExp(`github:${cred.id}`));
+ const unchanged = await built.app.turn(channelTurn("!sysprompt", "U_ASKER", audience));
+ assert.doesNotMatch(unchanged.reply ?? "", /STANDING grant|## Credentials/);
await selectDefaultSandbox(built, "U_OWNER", "personal:U_OWNER");
mark = fakeSprites.execScripts().length;
diff --git a/test/leader-lease.test.ts b/test/leader-lease.test.ts
index c932917ce..f9fdc2bba 100644
--- a/test/leader-lease.test.ts
+++ b/test/leader-lease.test.ts
@@ -147,13 +147,13 @@ test(
const killed = await standbyPool.q(
`WITH k AS (SELECT hashtextextended('leader-lease:failover:key', 0) AS v)
- SELECT pg_terminate_backend(l.pid) AS ok
+ SELECT pg_terminate_backend(l.pid, 5000) AS ok
FROM pg_locks l, k
WHERE l.locktype = 'advisory' AND l.granted
AND l.database = (SELECT oid FROM pg_database WHERE datname = current_database())
AND l.classid::bigint = ((k.v >> 32) & 4294967295) AND l.objid::bigint = (k.v & 4294967295)`,
);
- assert.equal(killed.length, 1, "found and terminated the holder's lock connection");
+ assert.deepEqual(killed, [{ ok: true }], "the holder's lock connection has terminated");
assert.equal(
await standby.hold("failover:key", async () => "second"),
diff --git a/test/orchestrator-documents.test.ts b/test/orchestrator-documents.test.ts
index e5d5f96a1..0197a2d11 100644
--- a/test/orchestrator-documents.test.ts
+++ b/test/orchestrator-documents.test.ts
@@ -84,7 +84,7 @@ test("compaction stops automatic document replay while preserving the original f
});
test("compaction during a turn stops document replay immediately", async () => {
- const built = freshApp(2000);
+ const built = freshApp(20_000);
const blob = await built.blobTransfer.put(Buffer.from("QUARTZ-731"));
const request = {
surface: "test" as const,
@@ -107,7 +107,7 @@ test("compaction during a turn stops document replay immediately", async () => {
for (let i = 0; i < 8; i++) {
await built.sessions.append(lease, {
type: i % 2 === 0 ? "user" : "assistant",
- payload: { text: "Synthetic conversation context. ".repeat(100) },
+ payload: { text: "Synthetic conversation context. ".repeat(2000) },
scopeLabel: entries[0]!.scopeLabel,
});
}
diff --git a/test/orchestrator.test.ts b/test/orchestrator.test.ts
index 911ffe5d9..6ea50462f 100644
--- a/test/orchestrator.test.ts
+++ b/test/orchestrator.test.ts
@@ -1178,7 +1178,7 @@ test("turn timezone rides the prompt and control-plane capability token", async
const prompt = await app.turn(
dm("!sysprompt", { conversation: { kind: "dm", threadRef: "dm:U1:tz-prompt" }, timezone: "America/New_York" }),
);
- assert.match(prompt.reply ?? "", /timezone America\/New_York/);
+ assert.match(prompt.reply ?? "", /\(America\/New_York\)/);
captured = undefined;
const invalid = await app.turn(
@@ -4539,3 +4539,63 @@ for (const [securityPosture, securityScreen] of [
assert.doesNotMatch(prompts, /NOT security-screened/);
});
}
+
+test("environment inventories are incremental across real turns with a durable full-snapshot anchor", async () => {
+ const { app, sessions } = freshApp();
+ const first = await app.turn(dm("first", { timezone: "America/Los_Angeles" }));
+ assert.equal(first.status, "ok");
+ assert.match(first.reply ?? "", /## Sandbox provider/);
+ const second = await app.turn(dm("second", { timezone: "America/Los_Angeles" }));
+ assert.equal(second.status, "ok");
+ assert.doesNotMatch(second.reply ?? "", /## Sandboxes|## Sandbox provider/);
+ assert.match(second.reply ?? "", /## The user's local time/);
+ const entries = await sessions.getEntries(first.sessionId!);
+ const users = entries.filter((entry) => entry.type === "user");
+ const firstSnapshot = (users[0]!.payload as { environmentSnapshot: { hashes: Record<string, string> } })
+ .environmentSnapshot;
+ assert.ok(Object.keys(firstSnapshot.hashes).some((key) => key.startsWith("Sandbox provider")));
+ const secondSnapshot = (users[1]!.payload as { environmentSnapshot: { anchorSeq: number } }).environmentSnapshot;
+ assert.equal(secondSnapshot.anchorSeq, users[0]!.seq);
+});
+
+test("an isolated channel environment does not disclose the actor's private sandbox", async () => {
+ const built = freshApp({ sharingPosture: "isolated" });
+ await built.directory.replace([
+ { principalId: "U1", displayName: "One", type: "internal" },
+ { principalId: "U2", displayName: "Two", type: "internal" },
+ ]);
+ await built.directory.replaceChannels(
+ [{ channelId: "C1", name: "team" }],
+ [
+ { channelId: "C1", principalId: "U1" },
+ { channelId: "C1", principalId: "U2" },
+ ],
+ );
+ const privateName = "PRIVATE-ACQUISITION-REVIEW";
+ const personal = await built.sandboxResources.create("U1", "personal:U1", "sprites", privateName);
+ await selectComputer(built, "U1", "channel:C1");
+ const inventory = await built.sandboxResources.list("U1", "channel:C1");
+ assert.ok(inventory.sandboxes.some((sandbox) => sandbox.id === personal.id));
+
+ const request: TurnRequest = {
+ surface: "test",
+ actor: internalActor,
+ conversation: {
+ kind: "channel",
+ threadRef: "ch:C1:private-sandbox-environment",
+ channelRef: "C1",
+ audience: [{ externalId: "U1" }, { externalId: "U2" }],
+ },
+ text: "hello",
+ };
+ const result = await built.app.turn(request);
+ assert.equal(result.status, "ok");
+ const session = await built.sessions.getByThread(request.conversation.threadRef);
+ const entries = await built.sessions.getEntries(session!.id);
+ const environment = (entries.find((entry) => entry.type === "user")!.payload as { environment: string }).environment;
+ assert.match(environment, /## Sandbox provider sprites/);
+ for (const content of [environment, result.reply ?? ""]) {
+ assert.ok(!content.includes(privateName), "the private sandbox name must not reach the shared turn");
+ assert.ok(!content.includes(personal.id), "the private sandbox ID must not reach the shared turn");
+ }
+});
diff --git a/test/service-credential-route.test.ts b/test/service-credential-route.test.ts
index 64748e7a2..163193a17 100644
--- a/test/service-credential-route.test.ts
+++ b/test/service-credential-route.test.ts
@@ -1346,7 +1346,7 @@ test("usage summaries authorize before reads and include only the requested scop
assert.doesNotMatch(JSON.stringify(body), /private|unlisted|U2/);
});
-test("credential prompt blocks are byte-identical across inventory and policy ordering", async () => {
+test("credential inventory and policy reordering do not resend unchanged credentials", async () => {
const { built } = buildWithCapture();
for (const slug of ["z-service", "a-service"]) {
await built.serviceCreds.setServiceCredential("org:default-org", {
@@ -1379,7 +1379,8 @@ test("credential prompt blocks are byte-identical across inventory and policy or
}));
const second = await built.app.turn(dm("!sysprompt"));
assert.equal(second.status, "ok");
- assert.equal(second.reply, first.reply);
+ assert.match(second.reply ?? "", /<environment>/);
+ assert.doesNotMatch(second.reply ?? "", /## Credentials|No longer included: Credentials|service_[az]-service/);
});
test("broker accepts no-expiry sandbox tokens but still enforces credential disablement", async () => {
diff --git a/test/system-prompt-order.test.ts b/test/system-prompt-order.test.ts
index 8946ca337..1a0fe274c 100644
--- a/test/system-prompt-order.test.ts
+++ b/test/system-prompt-order.test.ts
@@ -187,8 +187,8 @@ test("system prompt is ordered cached-prefix → volatile tail, with memory LAST
"Skills",
"Where you are",
"Where scheduled tasks post",
- "Connected apps",
"Sandbox environment profile",
+ "Connected apps",
"What you remember",
];
assert.doesNotMatch(prompt, /\n## Your logins\n/);
@@ -464,7 +464,15 @@ test("the system prompt is byte-identical across two turns a minute apart; the c
assert.equal(second.status, "ok");
for (const title of ["Skills", "Where you are", "Where scheduled tasks post", "Connected apps"]) {
- assert.ok(systemOf(first.reply ?? "").includes(`\n## ${title}\n`), `expected "## ${title}" in the system prompt`);
+ assert.ok(
+ environmentOf(first.reply ?? "").includes(`\n## ${title}\n`),
+ `expected "## ${title}" in the first environment`,
+ );
+ assert.ok(
+ !environmentOf(second.reply ?? "").includes(`\n## ${title}\n`),
+ `unchanged "## ${title}" must not repeat`,
+ );
+ assert.ok(!systemOf(first.reply ?? "").includes(`\n## ${title}\n`));
}
for (const title of ["Sandbox environment profile", "The user's local time", "What you remember", "Your logins"]) {
assert.ok(
@@ -501,7 +509,11 @@ test("the cached prefix survives skill-store reordering + a recordUse-style meta
assert.equal(second.status, "ok");
const prefixA = prefixOf(first.reply ?? "");
- assert.ok(prefixA.includes("**alpha**") && prefixA.includes("**zeta**"), "skills render in the cached prefix");
+ assert.ok(
+ first.reply!.includes("**alpha**") && first.reply!.includes("**zeta**"),
+ "skills render in the initial environment",
+ );
+ assert.doesNotMatch(second.reply!, /\*\*alpha\*\*|\*\*zeta\*\*/);
assert.equal(
prefixOf(second.reply ?? ""),
prefixA,
@@ -512,8 +524,18 @@ test("the cached prefix survives skill-store reordering + a recordUse-style meta
test("standing obligations: this scope's pending triggers render; other scopes' and immediate one-shots don't", async () => {
const crons = createCronStore();
const base = { owner: actor.id, createdBy: actor.id, ownerScopeId: scopeId("personal", actor.id) };
- await crons.create({ ...base, schedule: { everyMs: 300_000 }, action: "poll the vendor status page" });
- await crons.create({ ...base, schedule: { firstFireAt: Date.now() + 86_400_000 }, action: "follow up with legal" });
+ await crons.create({
+ ...base,
+ schedule: { everyMs: 300_000 },
+ title: "Vendor status",
+ action: "poll the vendor status page",
+ });
+ await crons.create({
+ ...base,
+ schedule: { firstFireAt: Date.now() + 86_400_000 },
+ title: "Legal follow-up",
+ action: "follow up with legal",
+ });
await crons.create({ ...base, schedule: { firstFireAt: Date.now() - 1000 }, message: "hi alice" });
await crons.create({
...base,
@@ -529,8 +551,9 @@ test("standing obligations: this scope's pending triggers render; other scopes'
assert.match(prompt, /schedule the wake-up in the same turn/);
assert.match(prompt, /\n## Already scheduled here\n/);
- assert.match(prompt, /poll the vendor status page/);
- assert.match(prompt, /follow up with legal/);
+ assert.match(prompt, /Vendor status — every 5 minutes/);
+ assert.match(prompt, /Legal follow-up — once at/);
+ assert.doesNotMatch(prompt, /poll the vendor status page|follow up with legal/);
assert.doesNotMatch(prompt, /hi alice/);
assert.doesNotMatch(prompt, /channel-only digest/);
});
@@ -1174,6 +1197,7 @@ test("profile and scheduled-work changes append fresh snapshots without rewritin
createdBy: actor.id,
ownerScopeId: scopeId("personal", actor.id),
schedule: { everyMs: 300_000 },
+ title: "Synthetic status",
action: "check the synthetic status page",
});
sandbox.profile.spec = { os: "Other Linux", cpus: 8, workdir: "/new/workspace", homeDir: "/new/home" };
@@ -1196,17 +1220,17 @@ test("profile and scheduled-work changes append fresh snapshots without rewritin
assert.match(seen[0]!.environment!, /Debian 12/);
assert.match(seen[0]!.environment!, /No active scheduled work/);
assert.match(seen[1]!.environment!, /Other Linux|8 vCPU/);
- assert.match(seen[1]!.environment!, /check the synthetic status page/);
- assert.doesNotMatch(seen[2]!.environment!, /check the synthetic status page/);
+ assert.match(seen[1]!.environment!, /Synthetic status/g);
+ assert.doesNotMatch(seen[2]!.environment!, /Synthetic status/g);
assert.match(seen[2]!.environment!, /No active scheduled work/);
- assert.doesNotMatch(seen[3]!.environment!, /Sandbox environment profile/);
+ assert.match(seen[3]!.environment!, /No longer included: Sandbox environment profile/);
assert.match(seen[3]!.environment!, /Scheduled-work status is unavailable/);
assert.doesNotMatch(seen[3]!.environment!, /Other Linux|synthetic status|No active scheduled work/);
assert.deepEqual(seen[1]!.history, originalHistory);
assert.deepEqual((await sessions.getEntries(first.sessionId!)).slice(0, originalHistory.length), originalHistory);
});
-test("connector revocation still refreshes system-authority permissions", async () => {
+test("connector revocation refreshes the environment without treating historical inventories as authority", async () => {
let revoked = false;
const { orchestrator } = buildOrchestrator({
connectorStatusCache: {
@@ -1222,10 +1246,11 @@ test("connector revocation still refreshes system-authority permissions", async
revoked = true;
const second = await orchestrator.handleTurn(dm("dm:U1:revoked-cache", "!sysprompt"));
const prefix = (reply: string) => reply.split("\n\n<environment>")[0]!;
- assert.match(prefix(first.reply!), /Connected: Google/);
- assert.match(prefix(second.reply!), /Needs reconnect: Google.*Do not use these apps/);
- assert.doesNotMatch(prefix(second.reply!), /Connected: Google/);
- assert.notEqual(prefix(first.reply!), prefix(second.reply!));
+ assert.match(first.reply!, /Connected: Google/);
+ assert.match(second.reply!, /Needs reconnect: Google.*Do not use these apps/);
+ assert.doesNotMatch(second.reply!, /Connected: Google/);
+ assert.equal(prefix(first.reply!), prefix(second.reply!));
+ assert.match(second.reply!, /sections below replace their earlier versions/);
});
for (const mode of ["safe", "blocked", "unavailable", "ordinary", "observe"] as const) {
diff --git a/test/transcript-window.test.ts b/test/transcript-window.test.ts
index 603e91ba5..4d9d8b841 100644
--- a/test/transcript-window.test.ts
+++ b/test/transcript-window.test.ts
@@ -227,8 +227,11 @@ test("GET /v1/sessions/:id honors tailTurns/sinceSeq and reports earlierEntries"
assert.equal((shown.payload as { memoryRecall?: unknown }).memoryRecall, undefined);
assert.equal(typeof (oneBody.entry.payload as { environment?: unknown }).environment, "string");
assert.deepEqual(
- { ...oneBody.entry, payload: { ...(oneBody.entry.payload as object), environment: undefined } },
- { ...shown, payload: { ...(shown.payload as object), environment: undefined } },
+ {
+ ...oneBody.entry,
+ payload: { ...(oneBody.entry.payload as object), environment: undefined, environmentSnapshot: undefined },
+ },
+ { ...shown, payload: { ...(shown.payload as object), environment: undefined, environmentSnapshot: undefined } },
"the whole entry, exactly as stored, is one fetch away",
);
@@ -299,7 +302,12 @@ test("a user entry carrying huge model-only context no longer hides the turns be
for (let turn = 0; turn < 4; turn++) {
log.push({
...entry(turn * 2, "user"),
- payload: { text: `ask ${turn}`, environment: context, memoryRecall: { body: context } },
+ payload: {
+ text: `ask ${turn}`,
+ environment: context,
+ environmentSnapshot: { hashes: { Skills: "abc" }, sessionId: "s" },
+ memoryRecall: { body: context },
+ },
});
log.push(entry(turn * 2 + 1, "assistant"));
}
diff --git a/test/turn-retry-replay.test.ts b/test/turn-retry-replay.test.ts
index 29407bee7..10f51dc7a 100644
--- a/test/turn-retry-replay.test.ts
+++ b/test/turn-retry-replay.test.ts
@@ -50,9 +50,11 @@ function fakeSandbox(): Sandbox {
};
}
-function buildScenario() {
+function buildScenario(interruptAfterToolResult = false) {
const turns: string[] = [];
const continued: Array<boolean | undefined> = [];
+ const environments: Array<string | undefined> = [];
+ const sandbox = fakeSandbox();
const harness = defineHarness(
{
id: "pi",
@@ -65,6 +67,7 @@ function buildScenario() {
async runTurn(turn) {
turns.push(turn.input);
continued.push(turn.continueTurn);
+ environments.push(turn.environment);
const userEntry = await turn.emit({
type: "user",
payload: { text: turn.input },
@@ -73,11 +76,28 @@ function buildScenario() {
await turn.tape?.({
kind: "message",
harness: "pi",
- payload: { role: "user", content: [{ type: "text", text: turn.input }], timestamp: Date.now() },
+ payload: {
+ role: "user",
+ content: [{ type: "text", text: [turn.input, turn.environment].filter(Boolean).join("\n\n") }],
+ timestamp: Date.now(),
+ },
scopeLabel: turn.scopeLabel,
entrySeq: userEntry.seq,
meta: { bareText: turn.input },
});
+ if (interruptAfterToolResult && turns.length === 1) {
+ await turn.emit({
+ type: "tool_call",
+ payload: { tool: "execute", callId: "c1", command: "ls" },
+ scopeLabel: turn.scopeLabel,
+ });
+ await turn.emit({
+ type: "tool_result",
+ payload: { tool: "execute", callId: "c1", result: "a.txt" },
+ scopeLabel: turn.scopeLabel,
+ });
+ throw new Error("interrupted after recording a tool result");
+ }
const reply = "it runs on this conversation's computer";
await turn.tape?.({
kind: "message",
@@ -116,7 +136,7 @@ function buildScenario() {
runs,
workspace,
files: createMemoryFileArtifactStore(createMemoryDurableByteStore()),
- sandbox: fakeSandbox(),
+ sandbox,
modelGateway: createModelGateway(),
auditLog,
rateLimiter: createRateLimiter({ maxPerWindow: 100, windowMs: 60_000 }),
@@ -146,7 +166,7 @@ function buildScenario() {
(e) => e.type === "user" && String((e.payload as { text?: string }).text ?? "").startsWith(ASK),
);
};
- return { orchestrator, sessions, runs, turns, continued, input, asks };
+ return { orchestrator, sessions, runs, turns, continued, environments, sandbox, input, asks };
}
test("a retry replays the answer the previous attempt recorded instead of asking again", async () => {
@@ -288,19 +308,41 @@ test("a turn that recorded no reply replays as silent, not as an empty answer",
});
test("a resume whose recorded work ends at a tool result asks the harness to continue the assistant turn", async () => {
- const { orchestrator, sessions, runs, turns, continued, input, asks } = buildScenario();
+ const { orchestrator, runs, turns, continued, environments, input, asks } = buildScenario(true);
const run = (await runs.enqueue({ sessionId: conversation.threadRef, request: input(ASK) })).run;
- const marker = await seedTurn(sessions, [
- { type: "user", payload: { text: ASK } },
- { type: "tool_call", payload: { tool: "execute", callId: "c1", command: "ls" } },
- { type: "tool_result", payload: { callId: "c1", result: "a.txt" } },
- ]);
- await runs.noteTurnUserSeq(run.id, marker);
+ await assert.rejects(
+ orchestrator.handleTurn(input(ASK, { runId: run.id, attempt: 1 })),
+ /interrupted after recording a tool result/,
+ );
+ const original = (await asks())[0]!;
+ assert.ok((original.payload as { environmentSnapshot?: unknown }).environmentSnapshot);
+ assert.match(environments[0]!, /## Where you are/);
+
+ const retry = await orchestrator.handleTurn(input(ASK, { runId: run.id, attempt: 2 }));
+ assert.equal(retry.status, "ok");
+ assert.deepEqual(continued, [undefined, true], "unchanged inventories preserve assistant continuation");
+ assert.doesNotMatch(environments[1]!, /## Where you are|Environment changes/);
+ assert.match(turns[1]!, /^\(system note:/, "the note still travels as the fallback input");
+ assert.equal((await asks()).length, 1);
+});
+
+test("a changed inventory on retry reaches the model instead of continuing past the update", async () => {
+ const { orchestrator, runs, continued, environments, sandbox, input, asks } = buildScenario(true);
+ sandbox.profile.spec = { os: "Old Linux" };
+ const run = (await runs.enqueue({ sessionId: conversation.threadRef, request: input(ASK) })).run;
+ await assert.rejects(
+ orchestrator.handleTurn(input(ASK, { runId: run.id, attempt: 1 })),
+ /interrupted after recording a tool result/,
+ );
+ assert.match(environments[0]!, /Old Linux/);
+ sandbox.profile.spec = { os: "New Linux" };
const retry = await orchestrator.handleTurn(input(ASK, { runId: run.id, attempt: 2 }));
assert.equal(retry.status, "ok");
- assert.deepEqual(continued, [true], "the harness is told the tape ends at a recorded tool result");
- assert.match(turns[0]!, /^\(system note:/, "the note still travels as the fallback input");
+ assert.deepEqual(continued, [undefined, undefined], "the new user message carries changed inventory");
+ assert.match(environments[1]!, /Environment changes/);
+ assert.match(environments[1]!, /New Linux/);
+ assert.doesNotMatch(environments[1]!, /Old Linux|## Where you are/);
assert.equal((await asks()).length, 1);
});