Multiplayer agent harness for work.
Stabilize unordered prompt inventories for cache reuse (#1690)
Regan Bell3b1e3cf4c7d7
diff --git a/src/core/attachments.ts b/src/core/attachments.tsindex 92c7bcc71..634942232 100644--- a/src/core/attachments.ts+++ b/src/core/attachments.ts@@ -277,7 +277,7 @@ export function sharedManifest(handles: readonly GrantedHandle[]): string {}if (!lines.length) return "";const total = lines.length;- const shown = lines.slice(0, MAX_SHARED_FILES_LISTED);+ const shown = lines.sort().slice(0, MAX_SHARED_FILES_LISTED);const omitted = total - shown.length;if (omitted > 0) {shown.push(`…and ${omitted} more (read shared/<name> to fetch)`);diff --git a/src/core/environment-facts.ts b/src/core/environment-facts.tsindex 003478210..3d86f6bb9 100644--- a/src/core/environment-facts.ts+++ b/src/core/environment-facts.ts@@ -17,10 +17,10 @@ export function renderComputerBlock(spec: AgentComputerSpec | undefined, layout:if (spec.diskGb) size.push(`${spec.diskGb} GB disk`);const head = [spec.os, size.join(" / ")].filter(Boolean).join(" · ");if (head) lines.push(`${head}.`);- if (spec.runtimes?.length) lines.push(`Runtimes: ${spec.runtimes.join(", ")}.`);- if (spec.tools?.length) lines.push(`Installed CLIs: ${spec.tools.join(", ")}.`);+ if (spec.runtimes?.length) lines.push(`Runtimes: ${spec.runtimes.toSorted().join(", ")}.`);+ if (spec.tools?.length) lines.push(`Installed CLIs: ${spec.tools.toSorted().join(", ")}.`);if (spec.notInstalled?.length) {- lines.push(`NOT installed (install on demand if a task needs one): ${spec.notInstalled.join(", ")}.`);+ lines.push(`NOT installed (install on demand if a task needs one): ${spec.notInstalled.toSorted().join(", ")}.`);}const cwd = spec.workdir ?? ".";@@ -51,7 +51,7 @@ export function renderResidentLoginsBlock("Logins survive machine replacement automatically: the platform keeps an encrypted copy core-side and restores it onto a fresh machine; they are never written into workspace backups.","To (re)log in, start the login command as a background process using the available process controls. A device-flow login prints a URL/code then waits for the person to approve. Relay the URL/code, then watch or poll the process until it exits; never kill it mid-flight. Capture into your keychain is automatic.",];- for (const c of present) {+ for (const c of present.sort((a, b) => a.id.localeCompare(b.id))) {if (record.connectors[c.id] === "active") {lines.push(`- ${c.label} — ✓ signed in`);} else {diff --git a/src/core/gateway-context.ts b/src/core/gateway-context.tsindex ff7dfac81..0d86ec250 100644--- a/src/core/gateway-context.ts+++ b/src/core/gateway-context.ts@@ -5,7 +5,8 @@ export function renderGatewayContext(surface: string | undefined, ctx?: GatewayCconst location = ctx?.location?.trim();const details = Object.entries(ctx?.details ?? {}).map(([k, v]) => [k.trim(), String(v).trim()] as const)- .filter(([k, v]) => k && v);+ .filter(([k, v]) => k && v)+ .sort(([a, av], [b, bv]) => a.localeCompare(b) || av.localeCompare(bv));const instructions = ctx?.instructions?.trim();if (!gateway && !location && details.length === 0 && !instructions) return "";diff --git a/src/core/orchestrator.ts b/src/core/orchestrator.tsindex 540be1a4b..ce56bb996 100644--- a/src/core/orchestrator.ts+++ b/src/core/orchestrator.ts@@ -1709,8 +1709,10 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {if (slugs.length > 0) {const usable = records.filter((r) => slugs.includes(r.slug));const lines = usable.map((r) => {- const methods = r.allowedMethods?.length ? r.allowedMethods.join("/") : "GET";- const paths = r.allowedPathPrefixes?.length ? `paths ${r.allowedPathPrefixes.join(", ")}` : "any path";+ const methods = r.allowedMethods?.length ? r.allowedMethods.toSorted().join("/") : "GET";+ const paths = r.allowedPathPrefixes?.length+ ? `paths ${r.allowedPathPrefixes.toSorted().join(", ")}`+ : "any path";return `- \`${r.slug}\` (${r.name}; shared org credential) → ${r.host} (${methods}; ${paths})`;});sharedCredsBlock =@@ -1737,7 +1739,7 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {"If the intended account is unclear before a write, clarify it rather than silently switching accounts. " +"A non-2xx `status` is the UPSTREAM service's own answer (e.g. a bad query or its auth), not a broker " +"error. Use ONLY these (slug → host; allowed methods; allowed paths):\n" +- lines.join("\n");+ lines.sort().join("\n");}}}@@ -2250,7 +2252,7 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {if (credentialDescriptions.length)systemPrompt +="\n\n## Execution credentials\nRequest exact handles in execute.credentials:\n" +- credentialDescriptions.join("\n");+ credentialDescriptions.sort().join("\n");systemPrompt += sharedCredsBlock;if (actorIsOrgAdmin) {systemPrompt +=diff --git a/src/core/orchestrator/prompt-blocks.ts b/src/core/orchestrator/prompt-blocks.tsindex 394b182ec..6f71d4e73 100644--- a/src/core/orchestrator/prompt-blocks.ts+++ b/src/core/orchestrator/prompt-blocks.ts@@ -2,10 +2,12 @@ import type { CandidateDestination, Cron, Monitor, Webhook } from "../../types.timport type { DirectoryChannel, DirectoryMember } from "../../directory/directory-store.ts";export function deliveryMenu(candidates: CandidateDestination[], defaultKey: string | undefined): string {- const lines = candidates.map(- (c) =>- `- ${c.label}${c.key === defaultKey ? " (default — where we're talking now)" : ""}: destinationKey \`${c.key}\``,- );+ const lines = candidates+ .toSorted((a, b) => a.key.localeCompare(b.key))+ .map(+ (c) =>+ `- ${c.label}${c.key === defaultKey ? " (default — where we're talking now)" : ""}: destinationKey \`${c.key}\``,+ );return ["## Where scheduled tasks post","When you schedule a cron here, it delivers to the default below unless you pass a different",@@ -42,13 +44,20 @@ export function renderStandingObligations(crons: Cron[], webhooks: Webhook[], moconst snippet = (s: string) => (s.length > 100 ? `${s.slice(0, 97)}…` : s).replace(/\s+/g, " ");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.slice(0, OBLIGATIONS_CAP).map((w) => `- webhook \`${w.id}\` (owner ${w.owner}): ${snippet(w.action)}`),- ...monitors.slice(0, OBLIGATIONS_CAP).map((m) => `- job watch on \`${m.processId}\`: ${snippet(m.command)}`),+ ...webhooks+ .toSorted((a, b) => a.id.localeCompare(b.id))+ .slice(0, OBLIGATIONS_CAP)+ .map((w) => `- webhook \`${w.id}\` (owner ${w.owner}): ${snippet(w.action)}`),+ ...monitors+ .toSorted((a, b) => a.id.localeCompare(b.id))+ .slice(0, OBLIGATIONS_CAP)+ .map((m) => `- job watch on \`${m.processId}\`: ${snippet(m.command)}`),];return ["## Already scheduled here",@@ -67,6 +76,7 @@ const REACH_ROSTER_CAP = 30;export function renderReachRoster(channels: DirectoryChannel[], displayName: string): string | null {if (channels.length === 0) return null;const shown = channels+ .toSorted((a, b) => a.channelId.localeCompare(b.channelId)).slice(0, REACH_ROSTER_CAP).map((c) => `#${c.name}`).join(", ");@@ -84,7 +94,7 @@ export function renderReachRoster(channels: DirectoryChannel[], displayName: strconst ROSTER_CAP = 20;export function renderConversationRoster(members: DirectoryMember[]): string | null {if (members.length === 0) return null;- const shown = members.slice(0, ROSTER_CAP);+ const shown = members.toSorted((a, b) => a.principalId.localeCompare(b.principalId)).slice(0, ROSTER_CAP);const lines = shown.map((m) => `- ${m.displayName} (${m.principalId})`);const more = members.length > ROSTER_CAP ? `\n…and ${members.length - ROSTER_CAP} more in this conversation.` : "";return (diff --git a/src/credentials/keychain.ts b/src/credentials/keychain.tsindex 04ea90f03..570c32222 100644--- a/src/credentials/keychain.ts+++ b/src/credentials/keychain.ts@@ -1693,9 +1693,14 @@ function credLine(const who = owner.displayName ? `${owner.displayName} (${owner.id})` : owner.id;if (isBackendCredential(c))return `- ${who}: Composio backend access — use the composio skill and /v1/composio; this key cannot be loaded into a computer`;- let slot = `files ${(c.targets ?? [c.target]).filter(Boolean).join(", ")}`;+ let slot = `files ${(c.targets ?? [c.target]).filter(Boolean).sort().join(", ")}`;if (c.kind === "env") {- slot = c.fields ? c.fields.map((f) => `\`${f.envKey}\``).join(" + ") : `\`${c.envKey}\``;+ slot = c.fields+ ? c.fields+ .map((f) => `\`${f.envKey}\``)+ .sort()+ .join(" + ")+ : `\`${c.envKey}\``;}const label = c.accountLabel ? `, account ${c.accountLabel}` : "";return `- ${who}: ${c.service} (${slot}${label}${expiryNote(c, now, own)}) — credential id \`${c.id}\` — ${grantNote}`;@@ -1757,7 +1762,9 @@ export function renderKeychainManifest(input: KeychainManifestInput, now: numberconst services = (input.detectedByOwner?.get(member.id) ?? []).filter((s) => !registered.has(s.toLowerCase()));if (!services.length) continue;const who = member.displayName ? `${member.displayName} (${member.id})` : member.id;- detectedLines.push(`- ${who}: ${services.join(", ")} — signed in on their own computer, not in the keychain`);+ detectedLines.push(+ `- ${who}: ${services.sort().join(", ")} — signed in on their own computer, not in the keychain`,+ );}const inDm = input.conversationKind === "dm";@@ -1776,7 +1783,7 @@ export function renderKeychainManifest(input: KeychainManifestInput, now: number"A connector grant works exactly like any other: ask the owner, they approve on their own turn, then `use` it.",);if (memberLines.length) {- lines.push("", "In this conversation:", ...memberLines);+ lines.push("", "In this conversation:", ...memberLines.sort());} else {lines.push("", "No keychain credentials registered yet for the people here.");}@@ -1800,7 +1807,7 @@ export function renderKeychainManifest(input: KeychainManifestInput, now: numberlines.push("","Detected but NOT registered (not grantable yet):",- ...detectedLines,+ ...detectedLines.sort(),"To make one usable here, its owner must first register it in their keychain from their own DM with you " +'(they can say "register my logins" there). A login living on someone\'s computer is not a grant — never claim access to it.',);@@ -1810,12 +1817,15 @@ export function renderKeychainManifest(input: KeychainManifestInput, now: numberlines.push("","Available command credentials:",- ...input.injected.map(- (m) =>- `- \`${credentialHandle(m.credentialId)}\` — ${m.service}, owner ${m.ownerId}, provides ${m.env- .map((e) => `\`${e.key}\``)- .join(" + ")}${m.purpose ? `, purpose: "${m.purpose}"` : ""}.`,- ),+ ...input.injected+ .toSorted((a, b) => a.credentialId.localeCompare(b.credentialId))+ .map(+ (m) =>+ `- \`${credentialHandle(m.credentialId)}\` — ${m.service}, owner ${m.ownerId}, provides ${m.env+ .map((e) => `\`${e.key}\``)+ .sort()+ .join(" + ")}${m.purpose ? `, purpose: "${m.purpose}"` : ""}.`,+ ),"Pass these exact handles in the execute tool's credentials field. Core exposes them only to that command.",);}@@ -1834,7 +1844,7 @@ export function renderKeychainManifest(input: KeychainManifestInput, now: number}}if (askLines.length) {- lines.push("", "Asks sent from this conversation:", ...askLines);+ lines.push("", "Asks sent from this conversation:", ...askLines.sort());}lines.push(@@ -1874,14 +1884,16 @@ export function renderKeychainManifest(input: KeychainManifestInput, now: numberlines.push("","### Asks waiting on you",- ...waiting.map((a) => {- const cred = myCreds.get(a.credentialId);- const what = cred- ? `${cred.service}${cred.accountLabel ? ` (${cred.accountLabel})` : ""}`- : `credential \`${a.credentialId}\``;- const hint = a.requestedMode === "standing" ? ", asked as standing" : "";- return `- ask \`${a.id}\`: ${a.requesterId} wants to use your ${what} in ${a.requesterScopeId}${hint}, for: "${a.purpose}" — expires at ${new Date(a.expiresAt).toISOString()}`;- }),+ ...waiting+ .sort((a, b) => a.id.localeCompare(b.id))+ .map((a) => {+ const cred = myCreds.get(a.credentialId);+ const what = cred+ ? `${cred.service}${cred.accountLabel ? ` (${cred.accountLabel})` : ""}`+ : `credential \`${a.credentialId}\``;+ const hint = a.requestedMode === "standing" ? ", asked as standing" : "";+ return `- ask \`${a.id}\`: ${a.requesterId} wants to use your ${what} in ${a.requesterScopeId}${hint}, for: "${a.purpose}" — expires at ${new Date(a.expiresAt).toISOString()}`;+ }),'When this person answers (their own words are the consent — "sure"/"just this once" means `once`; "keep it for that channel" means `standing`; default to `once`):','- Approve: `curl -fsS -X POST "$AGENT_API_URL/v1/keychain/grants" ' +CAPABILITY_CURL_AUTH +diff --git a/src/resolution/sharing-posture.ts b/src/resolution/sharing-posture.tsindex b55283f4c..64598cf5a 100644--- a/src/resolution/sharing-posture.ts+++ b/src/resolution/sharing-posture.ts@@ -23,5 +23,5 @@ export function composeSharingPostures(export function renderSharingPosturePrompt(actor: Principal, sourceScopes: readonly ScopeId[]): string {if (sourceScopes.length === 0) return "";const actorLabel = actor.displayName?.trim() || actor.id;- return `## Sharing posture: Open\nThis live request can read ${actorLabel}'s personally entitled resources from outside this conversation. Those sources are labelled by origin: ${sourceScopes.join(", ")}. Open access can reveal private information in a shared reply. Use only what this request needs, do not volunteer or repeat unrelated private information, and prefer this conversation's own sources when they are sufficient. File discovery is limited to 200 files and 25 shared contexts from the 100 most recent sessions. Files not listed, and binary files, require an explicit share. Carried context is read-only. In Open shared conversations the authenticated live speaker can use their own keychain on a separate disposable computer; other people's credentials and background jobs remain grant-gated. Writes, message history, approvals, security screening, and egress remain scoped normally.`;+ return `## Sharing posture: Open\nThis live request can read ${actorLabel}'s personally entitled resources from outside this conversation. Those sources are labelled by origin: ${sourceScopes.toSorted().join(", ")}. Open access can reveal private information in a shared reply. Use only what this request needs, do not volunteer or repeat unrelated private information, and prefer this conversation's own sources when they are sufficient. File discovery is limited to 200 files and 25 shared contexts from the 100 most recent sessions. Files not listed, and binary files, require an explicit share. Carried context is read-only. In Open shared conversations the authenticated live speaker can use their own keychain on a separate disposable computer; other people's credentials and background jobs remain grant-gated. Writes, message history, approvals, security screening, and egress remain scoped normally.`;}diff --git a/test/file-sharing.test.ts b/test/file-sharing.test.tsindex 823dd2957..637651959 100644--- a/test/file-sharing.test.ts+++ b/test/file-sharing.test.ts@@ -220,7 +220,12 @@ test("sharedManifest caps the listing at MAX_SHARED_FILES_LISTED with a '…andassert.equal((m.match(/^- shared\//gm) ?? []).length, MAX_SHARED_FILES_LISTED, "only the cap is listed");assert.match(m, /…and 7 more \(read shared\/<name> to fetch\)/);assert.match(m, new RegExp(`^${total} files shared with you`));- assert.doesNotMatch(m, new RegExp(`shared/file-${total - 1}\\.txt`));+ const sortedPaths = handles.map((h) => h.handlePath).sort();+ assert.deepEqual(+ m.split("\n").filter((line) => line.startsWith("- ")),+ sortedPaths.slice(0, MAX_SHARED_FILES_LISTED).map((path) => `- ${path}`),+ );+ assert.equal(sharedManifest(handles.toReversed()), m);});test("sharedManifest at exactly the cap lists every file with no '…and N more' tail", () => {diff --git a/test/keychain.test.ts b/test/keychain.test.tsindex 155bba11f..44e1d5281 100644--- a/test/keychain.test.ts+++ b/test/keychain.test.ts@@ -910,7 +910,7 @@ test("manifest: explains itself in a bare channel, lists credentials + protocoldetectedByOwner: new Map([["U1", ["GitHub", "AWS SSO"]]]),});assert.match(detected, /Detected but NOT registered/);- assert.match(detected, /Alice \(U1\): GitHub, AWS SSO — signed in on their own computer/);+ assert.match(detected, /Alice \(U1\): AWS SSO, GitHub — signed in on their own computer/);const k = kc();const cred = await k.save(GH);@@ -1837,3 +1837,83 @@ test("manifest timestamps stay stable until credentials and pending asks actuall(e: KeychainError) => e.status === 410,);});++test("manifest inventories are canonical across discovery order without mutating inputs", async () => {+ const k = kc();+ for (const ownerId of ["U2", "U1"]) {+ await k.save({ ...GH, ownerId });+ await k.save({+ ownerId,+ service: "files",+ files: [+ { path: ".config/z", contentBase64: "eg==" },+ { path: ".config/a", contentBase64: "YQ==" },+ ],+ });+ await k.save({+ ownerId,+ service: "custom",+ fields: [+ { envKey: "Z_KEY", value: "z" },+ { envKey: "A_KEY", value: "a" },+ ],+ });+ await k.setConnectorToken("github.com", ownerId, { accessToken: "token" });+ await k.setConnectorToken("gmail.googleapis.com", ownerId, { accessToken: "token" });+ }+ for (const credential of await k.listByOwner("U1")) {+ await k.createAsk({+ credentialId: credential.id,+ requesterId: "U2",+ requesterScopeId: "channel:C1",+ purpose: "access",+ });+ }+ const input: Parameters<typeof renderKeychainManifest>[0] = {+ scopeId: "personal:U1",+ conversationKind: "dm",+ actorId: "U1",+ members: [{ id: "U2" }, { id: "U1" }],+ entriesByOwner: await k.listByOwners(["U2", "U1"]),+ connectorsByOwner: await k.listConnectorsByOwners(["U2", "U1"]),+ scopeGrants: [],+ injected: ["z", "a"].map((id) => ({+ credentialId: id,+ ownerId: "U1",+ service: id,+ env: [+ { key: "Z", value: "z" },+ { key: "A", value: "a" },+ ],+ })),+ detectedByOwner: new Map([+ ["U1", ["zsh", "aws"]],+ ["U2", ["gcloud", "aws"]],+ ]),+ scopeAsks: await k.listAsks({ requesterScopeId: "channel:C1" }),+ ownerAsks: await k.listAsks({ ownerId: "U1" }),+ };+ const before = structuredClone(input);+ const first = renderKeychainManifest(input, 1000);+ const reversed = structuredClone(input);+ reversed.members.reverse();+ reversed.injected.reverse();+ for (const entry of reversed.injected) entry.env.reverse();+ for (const entries of reversed.entriesByOwner.values()) {+ entries.reverse();+ for (const entry of entries) {+ entry.fields?.reverse();+ entry.targets?.reverse();+ }+ }+ for (const entries of reversed.connectorsByOwner!.values()) entries.reverse();+ for (const entries of reversed.detectedByOwner!.values()) entries.reverse();+ reversed.scopeAsks!.reverse();+ reversed.ownerAsks!.reverse();+ assert.equal(renderKeychainManifest(reversed, 1000), first);+ assert.deepEqual(input, before);+ assert.match(first, /PENDING/);+ assert.match(first, /Asks waiting on you/);+ reversed.connectorsByOwner!.get("U1")![0]!.needsReconnect = true;+ assert.notEqual(renderKeychainManifest(reversed, 1000), first);+});diff --git a/test/prompt-inventory-order.test.ts b/test/prompt-inventory-order.test.tsnew file mode 100644index 000000000..5477d7ab7--- /dev/null+++ b/test/prompt-inventory-order.test.ts@@ -0,0 +1,99 @@+import { test } from "node:test";+import assert from "node:assert/strict";+import { renderComputerBlock, renderResidentLoginsBlock } from "../src/core/environment-facts.ts";+import { renderGatewayContext } from "../src/core/gateway-context.ts";+import { sharedManifest } from "../src/core/attachments.ts";+import { renderSharingPosturePrompt } from "../src/resolution/sharing-posture.ts";+import {+ deliveryMenu,+ renderConversationRoster,+ renderReachRoster,+ renderStandingObligations,+} from "../src/core/orchestrator/prompt-blocks.ts";+import { RESIDENT_AUTH_CONNECTORS } from "../src/credentials/resident-auth.ts";+import type { Cron, Webhook, Monitor, GrantedHandle, CandidateDestination } from "../src/types.ts";+import type { DirectoryMember, DirectoryChannel } from "../src/directory/directory-store.ts";++function checkOrder<T>(items: T[], render: (items: T[]) => string | null): void {+ const before = structuredClone(items);+ const expected = render(items);+ assert.equal(render(items.toReversed()), expected);+ assert.equal(render([...items.slice(3), ...items.slice(0, 3)]), expected);+ assert.deepEqual(items, before);+}++test("prompt inventories keep identical bytes across permutations, including capped subsets", () => {+ const ids = Array.from({ length: 105 }, (_, i) => `id-${String(i).padStart(3, "0")}`);+ checkOrder<DirectoryMember>(+ ids.map((id) => ({ principalId: id, displayName: "Same name", type: "internal" })),+ renderConversationRoster,+ );+ checkOrder<DirectoryChannel>(+ ids.map((id) => ({ channelId: id, name: id })),+ (items) => renderReachRoster(items, "Alex"),+ );+ checkOrder<CandidateDestination>(+ ids.map((id) => ({ key: id, label: id, type: "slack", target: id })),+ (items) => deliveryMenu(items, ids[5]),+ );+ checkOrder<GrantedHandle>(+ ids.map((id) => ({+ handlePath: `shared/${id}`,+ ownerScopeId: "personal:U1",+ ownerPath: `${id}.txt`,+ permission: "read",+ })),+ sharedManifest,+ );+ const base = ids.map((id) => ({+ id,+ ownerScopeId: "personal:U1" as const,+ owner: "U1",+ createdBy: "U1",+ createdAt: 1,+ enabled: true,+ }));+ checkOrder<Cron>(+ base.map((b) => ({ ...b, schedule: { everyMs: 60_000 }, action: b.id })),+ (items) => renderStandingObligations(items, [], []),+ );+ checkOrder<Webhook>(+ base.map((b) => ({ ...b, action: b.id, verification: { scheme: "github" } })),+ (items) => renderStandingObligations([], items, []),+ );+ checkOrder<Monitor>(+ base.map((b) => ({ ...b, processId: b.id, command: b.id, threadRef: "t", cursor: 0, expiresAt: 100 })),+ (items) => renderStandingObligations([], [], items),+ );+ assert.match(deliveryMenu([{ key: "x", label: "X", type: "slack", target: "x" }], "x"), /X \(default/);+});++test("environment and location facts are independent of discovery order", () => {+ checkOrder(["python", "node", "ruby", "bash"], (items) =>+ renderComputerBlock(+ { os: "Linux", runtimes: items, tools: items, notInstalled: items },+ { hasGlobal: false, teamCount: 0 },+ ),+ );+ checkOrder([...RESIDENT_AUTH_CONNECTORS], (items) =>+ renderResidentLoginsBlock(+ {+ scopeId: "personal:U1",+ checkedAt: 1,+ connectors: Object.fromEntries(items.map((c) => [c.id, "active" as const])),+ },+ items,+ ),+ );+ checkOrder(["channel:C2" as const, "team:T1" as const, "personal:U1" as const, "channel:C1" as const], (items) =>+ renderSharingPosturePrompt({ id: "U1", type: "internal" }, items),+ );+ checkOrder(+ [+ ["thread", "t"],+ ["channel", "c"],+ ["team", "t"],+ ],+ (items) => renderGatewayContext("slack", { details: Object.fromEntries(items) }),+ );+});diff --git a/test/service-credential-route.test.ts b/test/service-credential-route.test.tsindex 6a3c2aed4..34411ffe6 100644--- a/test/service-credential-route.test.ts+++ b/test/service-credential-route.test.ts@@ -1345,3 +1345,39 @@ test("usage summaries authorize before reads and include only the requested scopassert.deepEqual(summarize.mock.calls[0]!.arguments, [["summary"]]);assert.doesNotMatch(JSON.stringify(body), /private|unlisted|U2/);});++test("credential prompt blocks are byte-identical across inventory and policy ordering", async () => {+ const { built } = buildWithCapture();+ for (const slug of ["z-service", "a-service"]) {+ await built.serviceCreds.setServiceCredential("org:default-org", {+ slug,+ name: slug,+ secret: "s",+ host: "api.example.com",+ allowedMethods: ["POST", "GET"],+ allowedPathPrefixes: ["/z", "/a"],+ });+ await built.acl.grant({+ ownerScopeId: "org:default-org",+ ref: `service-cred:${slug}`,+ granteeScopeId: "org:default-org",+ permission: "read",+ grantedBy: "admin",+ });+ }+ const first = await built.app.turn(dm("!sysprompt"));+ assert.equal(first.status, "ok");+ assert.match(first.reply ?? "", /service_z-service/);+ assert.match(first.reply ?? "", /service_a-service/);+ assert.match(first.reply ?? "", /Shared org credentials available to you/);+ const list = built.serviceCreds.listServiceCredentials.bind(built.serviceCreds);+ built.serviceCreds.listServiceCredentials = async (...args) =>+ (await list(...args)).reverse().map((record) => ({+ ...record,+ allowedMethods: record.allowedMethods?.toReversed(),+ allowedPathPrefixes: record.allowedPathPrefixes?.toReversed(),+ }));+ const second = await built.app.turn(dm("!sysprompt"));+ assert.equal(second.status, "ok");+ assert.equal(second.reply, first.reply);+});