Skip to content

Commit 8a78354

Browse files
sahrizviclaude
andcommitted
fix(workspace): identity review — one owner, bounded resolve, budgeted label
From the Kilo, CodeRabbit and Codex reviews of the identity PR. - The routing directive no longer says "This project is bound to Altimate workspace X": it names the workspace that SERVES the tools ("Altimate workspace X serves the warehouse tools named below"). The snapshot is taken from local state at tool resolution and identity is revalidated against the server later in the turn, so the old sentence could contradict the identity section in one prompt. The ownership test now rejects every "this project is linked|bound|connected|attached to" phrasing instead of one string. - `identity.ts` resolves the binding at most once per 30 s per project (`OUTCOME_MEMO_MS`) and clears the memo on `onBindingChanged`. The resolver deliberately does not memoise an unreachable server, and a cached binding past its validation window re-asks too; on the prompt's critical path that was one `git remote` plus up to two 15-second requests before every generation for the length of an outage. - The label is budgeted on its encoded form (`MAX_LABEL_CHARS`, lone surrogates made well-formed first) so no name can push the section past the cap and clip the instruction; the name is shortened with an ellipsis and the id kept whole. Cap raised to 1,000 as defense in depth. - Tests: hostile-name test now fails without the sanitiser (NEL and the Unicode separators are not JSON-escaped); the trigger test pins the narrowing suffix and that every active instruction sits in the trigger sentence; encoded-label budget covered for surrogates, quotes, backslashes and emoji; memo probe-once and unlink-invalidation covered. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_012Q51zFUmPg1WwtS5CrGJE6
1 parent a37ab7a commit 8a78354

5 files changed

Lines changed: 184 additions & 15 deletions

File tree

‎packages/opencode/src/altimate/workspace/awareness.ts‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -127,7 +127,10 @@ const DISABLED_COPY: Record<NonNullable<Precedence["disabledReason"]>, string> =
127127
}
128128

129129
// Identity — "which Altimate Workspace is this project linked to" — is NOT stated
130-
// here. It lives in `identity.ts`, which renders it every turn from the binding
130+
// here, and the workspace named in the routing intro is the one that SERVES the
131+
// tools (the snapshot's provenance), not a claim about the current link: a
132+
// snapshot is taken from local state at tool resolution, and the link can be
133+
// revalidated against the server later in the same turn. It lives in `identity.ts`, which renders it every turn from the binding
131134
// itself, independent of routing: a project can be linked and route nothing (a
132135
// workspace that materialised no integrations), or be unlinked, or be unverifiable
133136
// this turn, and each of those deserves a definite answer that a routing directive,
@@ -233,7 +236,7 @@ function assembleExtensionsOnly(
233236
return [
234237
HEADING,
235238
"",
236-
`This project is bound to Altimate workspace ${label}. No warehouse capability is routed through it in ` +
239+
`Altimate workspace ${label} serves the extension tools below. No warehouse capability is routed through it in ` +
237240
`this session: every connection uses the local tools (${ALL_LOCAL_TOOLS}).`,
238241
"",
239242
EXTENSION_INTRO,
@@ -292,7 +295,7 @@ function assemble(
292295
return [
293296
HEADING,
294297
"",
295-
`This project is bound to Altimate workspace ${label}. For each connection type below, the ` +
298+
`Altimate workspace ${label} serves the warehouse tools named below. For each connection type below, the ` +
296299
"local tool for a capability that names a workspace tool will NOT execute — it returns a " +
297300
"redirect. Call the named workspace tool directly; capabilities not named for a type stay on " +
298301
"the local tools:",

‎packages/opencode/src/altimate/workspace/identity.ts‎

Lines changed: 50 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -22,16 +22,26 @@
2222
// meant nagging about linking mid-conversation about an unrelated Databricks topic, or
2323
// pedantically re-qualifying every casual mention of one. Neither is this feature's
2424
// job — resolving "this/current/active workspace" is.
25-
import { resolveBindingOutcome, type BindingOutcome } from "./state"
25+
import { onBindingChanged, resolveBindingOutcome, type BindingOutcome } from "./state"
2626
import { inertWorkspaceName } from "./workspace-name"
2727
import { isEnabled } from "./engine-seams"
2828
import { Instance } from "../../project/instance"
2929

3030
/** Independent of `awareness.ts`'s MAX_SECTION_CHARS (2,000) — this section is a short,
3131
* fixed-shape identity statement, not an open-ended list of served integrations, so a
32-
* much smaller ceiling is enough. Exists mainly as a guard against a pathological
33-
* workspace name defeating `inertWorkspaceName`'s own 80-code-point cap. */
34-
export const MAX_SECTION_CHARS = 800
32+
* much smaller ceiling is enough. The label is budgeted separately (`MAX_LABEL_CHARS`)
33+
* so the cap here is defense in depth and never cuts the instruction itself: the fixed
34+
* copy is ~640 characters, and a label at its budget still leaves room. */
35+
export const MAX_SECTION_CHARS = 1_000
36+
37+
/** The rendered label — quoted name plus id — after JSON escaping. `inertWorkspaceName`
38+
* bounds the name to 80 code points, but escaping expands quotes and backslashes to
39+
* two units and a lone surrogate to six; without a budget on the ENCODED form, 80
40+
* lone surrogates pushed the section past the cap and clipped the instruction
41+
* mid-sentence. Lone surrogates are replaced first (U+FFFD), so the worst case is
42+
* 80 escaped quotes (162 units) plus a 16-digit id — just over this budget, where
43+
* the name is shortened with an ellipsis and the id is kept whole. */
44+
export const MAX_LABEL_CHARS = 180
3545

3646
const HEADING = "## Altimate Workspace"
3747

@@ -124,13 +134,40 @@ function renderBody(outcome: BindingOutcome): string {
124134

125135
function workspaceLabel(name: string, id: string): string {
126136
// A name that sanitises to nothing must not erase the identity: the id is the
127-
// stable half, and `""` reads as a bug.
128-
return `${JSON.stringify(inertWorkspaceName(name) || "(unnamed)")} (id ${id})`
137+
// stable half, and `""` reads as a bug. Lone surrogates are made well-formed
138+
// before quoting so they cost one unit, not a six-character escape.
139+
const points = Array.from(inertWorkspaceName(name).toWellFormed())
140+
const suffix = ` (id ${id})`
141+
let label = `${JSON.stringify(points.join("") || "(unnamed)")}${suffix}`
142+
while (label.length > MAX_LABEL_CHARS && points.length > 0) {
143+
points.pop()
144+
label = `${JSON.stringify(points.join("") + "…")}${suffix}`
145+
}
146+
return label
147+
}
148+
149+
/** How long a resolved outcome is reused before the binding is resolved again.
150+
*
151+
* This section renders on every step of the agentic loop. `resolveBindingOutcome`
152+
* is a local read while its 5-minute validation stamp holds, but outside it — no
153+
* cached binding, or a cached one past its window — every ask is a `git remote`
154+
* plus up to two requests with 15-second budgets, and an unreachable server is
155+
* deliberately not memoised there (a blip must not outlive the session as a
156+
* remembered answer). Left on the critical path that meant one probe before
157+
* every generation for as long as an outage lasted. One resolve per window
158+
* bounds it; a link, unlink or rebind in this process clears the memo at once
159+
* (`onBindingChanged`), so the next step sees the change. */
160+
export const OUTCOME_MEMO_MS = 30_000
161+
const memo = new Map<string, { at: number; outcome: BindingOutcome }>()
162+
onBindingChanged(() => memo.clear())
163+
164+
export function resetOutcomeMemoForTests(): void {
165+
memo.clear()
129166
}
130167

131168
/** Called on every step of the agentic loop, same as `awareness.ts`'s section —
132-
* `resolveBindingOutcome` is a cached local read (5-minute revalidation window), so
133-
* this stays cheap. Reads `Instance.directory` ITSELF, inside the same try/catch as
169+
* the binding is resolved at most once per `OUTCOME_MEMO_MS` per project, so this
170+
* stays cheap. Reads `Instance.directory` ITSELF, inside the same try/catch as
134171
* the resolve call — not as a caller-supplied argument evaluated at the call site.
135172
* `Instance.directory` is an `AsyncLocalStorage`-backed getter (`project/instance.ts`)
136173
* that throws `Context.NotFound` outside an established instance context (some test
@@ -147,7 +184,11 @@ export async function systemSection(): Promise<string> {
147184
// every turn that none is linked and how to link one.
148185
if (!isEnabled()) return ""
149186
try {
150-
const outcome = await resolveBindingOutcome(Instance.directory)
187+
const directory = Instance.directory
188+
const hit = memo.get(directory)
189+
if (hit && Date.now() - hit.at < OUTCOME_MEMO_MS) return render(hit.outcome)
190+
const outcome = await resolveBindingOutcome(directory)
191+
memo.set(directory, { at: Date.now(), outcome })
151192
return render(outcome)
152193
} catch {
153194
return render({ status: "unknown" })

‎packages/opencode/test/altimate/workspace/awareness.test.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -420,7 +420,10 @@ describe("the identity line", () => {
420420
// must not state it too, or the two could disagree.
421421
await refresh(SESSION, SNOWFLAKE_TOOLS)
422422
const out = section()
423-
expect(out).not.toContain("This project is linked to")
423+
// Any sentence of the shape "this project is <linked|bound|connected> to" is an
424+
// identity claim; the routing intro may only say which workspace SERVES the tools.
425+
expect(out).not.toMatch(/this project is (linked|bound|connected|attached) to/i)
426+
expect(out).toMatch(/Altimate workspace "analytics" \(id 42\) serves/)
424427
expect(out).toContain("## Workspace integrations")
425428
})
426429

‎packages/opencode/test/altimate/workspace/identity-section.test.ts‎

Lines changed: 62 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,8 +30,10 @@ afterAll(() => {
3030
})
3131

3232
const { AltimateApi } = await import("../../../src/altimate/api/client")
33-
const { systemSection } = await import("../../../src/altimate/workspace/identity")
34-
const { recordApprovedBinding } = await import("../../../src/altimate/workspace/state")
33+
const { systemSection, resetOutcomeMemoForTests, OUTCOME_MEMO_MS } = await import(
34+
"../../../src/altimate/workspace/identity",
35+
)
36+
const { recordApprovedBinding, clearLocalBinding } = await import("../../../src/altimate/workspace/state")
3537
const { Instance } = await import("../../../src/project/instance")
3638

3739
type Creds = Awaited<ReturnType<typeof AltimateApi.getCredentials>>
@@ -50,6 +52,7 @@ let projectDir = ""
5052

5153
beforeEach(() => {
5254
process.env.ALTIMATE_WORKSPACE = "1"
55+
resetOutcomeMemoForTests()
5356
projectDir = mkdtempSync(path.join(SANDBOX, "proj-"))
5457
// Nothing here should need the network; anything that asks gets an empty 200.
5558
globalThis.fetch = (async () =>
@@ -110,6 +113,63 @@ describe("systemSection", () => {
110113
expect(out).not.toContain("linked to Altimate Workspace \"")
111114
})
112115

116+
test("an unreachable server is probed once per window, not once per step", async () => {
117+
// The section renders on every agent step. Without the memo, an outage
118+
// costs a `git remote` plus up to two 15-second requests before every
119+
// generation; with it, one resolve per `OUTCOME_MEMO_MS`.
120+
let attempts = 0
121+
globalThis.fetch = (async () => {
122+
attempts++
123+
throw new Error("offline")
124+
}) as unknown as typeof fetch
125+
expect(await inProject(systemSection)).toContain("could not be verified")
126+
const afterFirst = attempts
127+
expect(afterFirst).toBeGreaterThan(0)
128+
expect(await inProject(systemSection)).toContain("could not be verified")
129+
expect(await inProject(systemSection)).toContain("could not be verified")
130+
expect(attempts).toBe(afterFirst)
131+
// A new window asks again — the blip was never promoted to a remembered answer.
132+
resetOutcomeMemoForTests()
133+
await inProject(systemSection)
134+
expect(attempts).toBeGreaterThan(afterFirst)
135+
expect(OUTCOME_MEMO_MS).toBeLessThanOrEqual(60_000)
136+
})
137+
138+
test("a link or unlink in this process clears the memo, so the next step sees it", async () => {
139+
// Bound, memoised; then the binding is removed the way `/workspace` unlink
140+
// does it. Without the `onBindingChanged` hook the memo would keep naming
141+
// the workspace for up to a window after the user unlinked.
142+
await recordApprovedBinding(projectDir, {
143+
datamateId: 42,
144+
datamateName: "analytics",
145+
repoRemote: null,
146+
projectPath: projectDir,
147+
linkedAt: Date.now(),
148+
})
149+
expect(await inProject(systemSection)).toContain('linked to Altimate Workspace "analytics" (id 42)')
150+
await clearLocalBinding(projectDir, { scope: { tenant: "acme", apiUrl: "https://api.example.com" } })
151+
globalThis.fetch = (async () =>
152+
new Response(JSON.stringify({ detail: "not found" }), {
153+
status: 404,
154+
headers: { "content-type": "application/json" },
155+
})) as unknown as typeof fetch
156+
expect(await inProject(systemSection)).toContain("No Altimate Workspace is linked")
157+
})
158+
159+
test("a bound answer after an outage is seen once the window ends", async () => {
160+
globalThis.fetch = (async () => {
161+
throw new Error("offline")
162+
}) as unknown as typeof fetch
163+
expect(await inProject(systemSection)).toContain("could not be verified")
164+
resetOutcomeMemoForTests()
165+
globalThis.fetch = (async () =>
166+
new Response(JSON.stringify({ detail: "not found" }), {
167+
status: 404,
168+
headers: { "content-type": "application/json" },
169+
})) as unknown as typeof fetch
170+
expect(await inProject(systemSection)).toContain("No Altimate Workspace is linked")
171+
})
172+
113173
test("degrades to the unverified copy outside an instance context rather than throwing", async () => {
114174
// `Instance.directory` throws outside a context; prompt assembly must not.
115175
const out = await systemSection()

‎packages/opencode/test/altimate/workspace/identity.test.ts‎

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,51 @@ describe("bound — a specific Altimate Workspace is linked", () => {
6161
expect(out.split("\n").length).toBeGreaterThan(1) // section itself is multi-line
6262
expect(out).not.toContain('evil"\nname') // raw hostile substring never appears verbatim
6363
expect(out).toContain("id 1")
64+
// JSON quoting alone would escape the newline and quote; it does NOT touch NEL,
65+
// the Unicode line separators or the length. Those are the sanitiser's job, and
66+
// this is what fails when it is skipped.
67+
const separators = "a\u0085b\u2028c\u2029d"
68+
const sep = render({ ...outcome, binding: { ...outcome.binding, datamateName: separators } })
69+
expect(sep).not.toMatch(/[\u0085\u2028\u2029]/)
70+
expect(sep).toContain('"a b c d"')
71+
const long = render({ ...outcome, binding: { ...outcome.binding, datamateName: "y".repeat(500) } })
72+
expect(long).toContain('"' + "y".repeat(79) + '…"')
73+
expect(long).not.toContain("y".repeat(81))
74+
})
75+
76+
test("the label is budgeted on its ENCODED form, so no name can clip the instruction", () => {
77+
// 80 lone surrogates escape to six characters each; 80 quotes to two. Either
78+
// used to push the section past the cap and cut the instruction mid-sentence.
79+
const last = "or footnote every incidental mention of one."
80+
for (const name of ["\uD800".repeat(80), '"'.repeat(80), "\\".repeat(80), "🚀".repeat(80), "x".repeat(80)]) {
81+
const out = render({
82+
status: "bound",
83+
binding: { datamateId: Number.MAX_SAFE_INTEGER, datamateName: name, repoRemote: null, projectPath: "/p", linkedAt: 0 },
84+
})
85+
expect(out.endsWith(last)).toBe(true)
86+
expect(out.length).toBeLessThan(MAX_SECTION_CHARS)
87+
expect(out).toContain(`(id ${Number.MAX_SAFE_INTEGER})`)
88+
expect(out.isWellFormed()).toBe(true)
89+
}
90+
// Past the budget (80 escaped quotes plus a 16-digit id) the NAME is shortened
91+
// with an ellipsis and the id is kept whole, rather than the sentence being cut.
92+
const quoted = render({
93+
status: "bound",
94+
binding: {
95+
datamateId: Number.MAX_SAFE_INTEGER,
96+
datamateName: '"'.repeat(80),
97+
repoRemote: null,
98+
projectPath: "/p",
99+
linkedAt: 0,
100+
},
101+
})
102+
expect(quoted).toMatch(/\\"…" \(id 9007199254740991\)\./)
103+
// Under the budget nothing is shortened.
104+
const plain = render({
105+
status: "bound",
106+
binding: { datamateId: 1, datamateName: '"'.repeat(80), repoRemote: null, projectPath: "/p", linkedAt: 0 },
107+
})
108+
expect(plain).not.toContain("…")
64109
})
65110
})
66111

@@ -134,8 +179,25 @@ test("all three branches scope their active instruction to the same identity-que
134179
] satisfies BindingOutcome[]) {
135180
const out = render(outcome)
136181
expect(out).toContain(trigger)
182+
// The narrowing half of the trigger is what stops a passing mention of some
183+
// other service's workspace from counting; without it the prefix alone
184+
// still reads as "any mention".
185+
expect(out).toContain("used to ask what THIS project is connected to")
137186
expect(out).not.toContain("whenever")
138187
expect(out).not.toMatch(/\balways\b/i)
188+
// "every mention" may appear only inside the exemption ("no need to … every
189+
// incidental mention"), never as a condition for acting.
190+
for (const line of out.split("\n")) {
191+
if (/\b(every|any|each) (incidental )?mention\b/i.test(line)) expect(line).toContain("no need")
192+
}
193+
// Every active instruction — the answer, the link offer, the retry advice —
194+
// sits in the one sentence that opens with the trigger, so nothing can ask
195+
// for it unconditionally elsewhere.
196+
for (const line of out.split("\n")) {
197+
if (/offer to help link|say plainly|say link status|the answer is/.test(line)) {
198+
expect(line.startsWith("When the user's own message asks a workspace-IDENTITY question")).toBe(true)
199+
}
200+
}
139201
}
140202
})
141203

0 commit comments

Comments
 (0)