Skip to content

Commit b600a0b

Browse files
saravmajesticclaude
andcommitted
fix: deliver team rules only while the account that pulled them is signed in
- A pull stamps the state with the credential it ran with (`pulled_with`), only while that credential is still the one signed in. - `RulesStore.vouched` vouches for nothing unless the credential signed in now matches: a sign-out or another account stops team rules at once, not at the next sync. - `Delivery.vouched` catches a failed dynamic import too. - Docs: the state path follows `$XDG_STATE_HOME`; a project copy is never trusted on its own. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 2f1ee3a commit b600a0b

6 files changed

Lines changed: 70 additions & 6 deletions

File tree

‎docs/docs/configure/learn.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -201,7 +201,7 @@ The card never blocks the input: keep typing, and answer it when you are ready.
201201

202202
**Rule or memory.** A personal preference ("I prefer CTEs") or a fact ("our warehouse is Snowflake") is saved to memory without review. When the agent saved it with `training_save`, a preference goes to your own memory (all your projects) and a fact to this project's memory (outside a linked project, `training_save` saves project training as before). When it saved it with the memory tool, it stays in that tool's project memory. When the wording does not say which, the card asks: Memory, Team rule, or Skip.
203203

204-
**Where they live.** Approved team rules are mirrored into the `workspace-rules` store (`.altimate-code/learn/workspace-rules/`), which is git-ignored and written only by sync: the name is reserved for it, and a store you create needs another `--name`. Everything else sync keeps (proposals waiting to be sent, your review notices, dismissed topics, your learning choice) is your rules state for the project, kept outside it in your own state directory (`~/.local/state/altimate-code/workspace-rules/`, one file per project folder). A rule in the project's `workspace-rules` copy is delivered only while your rules state holds the same rule, so a copy that came with a branch or a merge is never taken for your workspace's rules. Your other stores, including one named `team`, are not touched. Team rules stop being delivered when the project is unlinked, when you sign out, when the workspace refuses access, and while workspaces are turned off (`ALTIMATE_DISABLE_WORKSPACE`); they come back with the next sync.
204+
**Where they live.** Approved team rules are mirrored into the `workspace-rules` store (`.altimate-code/learn/workspace-rules/`), which is git-ignored and written only by sync: the name is reserved for it, and a store you create needs another `--name`. Everything else sync keeps (proposals waiting to be sent, your review notices, dismissed topics, your learning choice) is your rules state for the project, kept outside it in your own state directory (`$XDG_STATE_HOME/altimate-code/workspace-rules/`, usually `~/.local/state/altimate-code/workspace-rules/`, one file per project folder). A rule in the project's `workspace-rules` copy is delivered only while your rules state holds the same rule, pulled with the account you are signed in as now: a copy that came with a branch or a merge is never trusted on its own. Your other stores, including one named `team`, are not touched. Team rules stop being delivered when you sign out or sign in as someone else (at once), when the project is unlinked, when the workspace refuses access, and while workspaces are turned off (`ALTIMATE_DISABLE_WORKSPACE`); they come back with the next sync.
205205

206206
**After review.** Approved rules reach new sessions, and new requests and files in running ones, within a few minutes (a pull at session start and every 5 minutes; `/rules` → Sync now, or `altimate-code learn sync`). A session keeps the wording it was already shown. You see a notice when the owner approves or rejects your rule, with the reason. Usage is reported back to the workspace: how many sessions a rule was applied in, and how often you corrected the agent on its topic after it was shown ("corrected again").
207207

‎packages/opencode/src/altimate/learn/delivery.ts‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -243,11 +243,13 @@ export class Delivery {
243243
// outside the project. The `workspace-rules` copy in the project is only delivered where it matches: a file in the
244244
// working tree can come from anyone (a branch, a merge). Unreadable, it vouches for none.
245245
private async vouched(): Promise<Map<string, string>> {
246-
const { RulesStore } = await import("../rules/store")
247-
return RulesStore.vouched(this.root).catch((error) => {
246+
try {
247+
const { RulesStore } = await import("../rules/store")
248+
return await RulesStore.vouched(this.root)
249+
} catch (error) {
248250
log.warn("workspace rules state unreadable; team rules not delivered", { error })
249251
return new Map<string, string>()
250-
})
252+
}
251253
}
252254
// altimate_change end
253255

‎packages/opencode/src/altimate/rules/store.ts‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,9 @@ export const State = z.object({
134134
cursor: z.string().optional(),
135135
pending_count: z.number().int().default(0),
136136
pulled_at: z.string().optional(),
137+
/** The credential (`credentialDigest`) the last successful pull was made with: its rules are delivered only while the
138+
* same credential is signed in. */
139+
pulled_with: z.string().optional(),
137140
last_error: z.string().optional(),
138141
/** Queued proposals dropped because the account or workspace changed. Its own field: a later pull's error (or its
139142
* success) does not erase it. Shown for `SCOPE_DROP_NOTICE_MS`. */
@@ -222,10 +225,14 @@ async function writePrivate(file: string, data: string): Promise<void> {
222225
}
223226

224227
/** The team rules delivery may give from the project's `workspace-rules` copy: lesson id → text, as the state holds
225-
* them. None while the project is not linked (unlinked, signed out and lost access clear the state's workspace). */
228+
* them. None while the project is not linked (unlinked and lost access clear the state's workspace), and none unless
229+
* the credential signed in now is the one they were pulled with: a sign-out or another account stops them at once,
230+
* not at the next sync. No network. */
226231
export async function vouched(root: string): Promise<Map<string, string>> {
227232
const state = await read(root)
228-
if (!state.workspace) return new Map()
233+
if (!state.workspace || !state.pulled_with) return new Map()
234+
const { accountDigest } = await import("../workspace/state")
235+
if ((await accountDigest().catch(() => null)) !== state.pulled_with) return new Map()
229236
return new Map(state.rules.map((rule) => [lessonId(rule.rule_key), rule.text]))
230237
}
231238

‎packages/opencode/src/altimate/rules/sync.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,11 @@ export async function pull(root: string, ctx: Ready): Promise<PullResult> {
139139
})
140140
const fresh: State["notices"] = []
141141
let applied = true
142+
// Stamped only while the credential that pulled is still the one signed in: another process may have signed in as
143+
// someone else while this pull ran.
144+
const { accountDigest, credentialDigest } = await import("../workspace/state")
145+
const pulledWith = credentialDigest(ctx.actAs.url, ctx.actAs.instance, ctx.actAs.apiKey)
146+
const current = (await accountDigest().catch(() => null)) === pulledWith
142147
const state = await RulesStore.update(root, (state) => {
143148
// Applied only to the state it was asked for: another process may have adopted another account or workspace, or
144149
// pulled a newer revision, while this answer was on its way.
@@ -152,6 +157,8 @@ export async function pull(root: string, ctx: Ready): Promise<PullResult> {
152157
state.cursor = response.cursor
153158
state.pending_count = response.pending_count
154159
state.pulled_at = new Date().toISOString()
160+
if (current) state.pulled_with = pulledWith
161+
else delete state.pulled_with
155162
state.last_error = response.skipped
156163
? `${response.skipped} team ${response.skipped === 1 ? "rule" : "rules"} could not be read by this version of altimate-code, or did not pass the rule lint (one line, no commands, links or secrets), and ${response.skipped === 1 ? "is" : "are"} not delivered`
157164
: undefined

‎packages/opencode/test/altimate/learn/delivery.test.ts‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import { canonical, type Lesson } from "../../../src/altimate/learn/lesson"
88
import * as Store from "../../../src/altimate/learn/store"
99
import { Telemetry } from "../../../src/altimate/telemetry"
1010
import { RulesStore } from "../../../src/altimate/rules/store"
11+
import * as WorkspaceState from "../../../src/altimate/workspace/state"
1112

1213
let root: string
1314
const NAME = "team-playbook"
@@ -24,11 +25,16 @@ const fixtures = () => [
2425
]
2526
const envKeys = ["ALTIMATE_LEARN_REQUEST_LESSONS", "ALTIMATE_LEARN_FILE_HOOK", "ALTIMATE_LEARN_FILE_LESSONS", "ALTIMATE_LEARN_CAPTURE"] as const
2627
const savedEnv = Object.fromEntries(envKeys.map((key) => [key, process.env[key]]))
28+
/** The credential signed in: team rules are pulled with it. */
29+
const ACCOUNT = "account-a"
30+
let signedIn: ReturnType<typeof spyOn>
2731
beforeEach(async () => {
2832
for (const key of envKeys) delete process.env[key]
2933
root = await fs.mkdtemp(path.join(os.tmpdir(), "learn-delivery-"))
34+
signedIn = spyOn(WorkspaceState, "accountDigest").mockResolvedValue(ACCOUNT)
3035
})
3136
afterEach(async () => {
37+
signedIn.mockRestore()
3238
for (const key of envKeys) {
3339
if (savedEnv[key] === undefined) delete process.env[key]
3440
else process.env[key] = savedEnv[key]
@@ -46,6 +52,7 @@ async function approve(lessons = fixtures(), name = NAME) {
4652
async function pulled(lessons: Lesson[]) {
4753
await RulesStore.update(root, (s) => {
4854
s.workspace = { name: "Team", owner_name: null, is_owner: false }
55+
s.pulled_with = ACCOUNT
4956
s.rules = lessons.map((l) => ({
5057
public_id: `p-${l.id}`, rule_key: `R-${l.id.replace(/\D/g, "").padStart(12, "0")}`, repo_identity: null, text: l.text,
5158
applies_to: l.trigger?.paths ?? [], tags: [], pinned: !!l.pinned, version: 1, updated_at: l.updated,
@@ -561,6 +568,27 @@ test("a team-rules copy in the project that the person's rules state does not ho
561568
}
562569
})
563570

571+
test("team rules stop at once when the person signs out or signs in as someone else", async () => {
572+
await approve([lesson("L-0701", "Keep the project rules explicit.", { pinned: true })])
573+
await approve([lesson("L-0702", "Name staging models stg_<source>.", { pinned: true })], Store.WORKSPACE_RULES_STORE)
574+
const env = process.env.ALTIMATE_DISABLE_WORKSPACE
575+
try {
576+
delete process.env.ALTIMATE_DISABLE_WORKSPACE
577+
const on = await new Delivery(root, { ...limits, core_lessons: 2 }).prepare("switch", "first", "staging")
578+
expect(on.section).toContain("Name staging models")
579+
// Another account, before any sync has seen it: neither the cached section nor a rebuild gives the rule.
580+
signedIn.mockResolvedValue("account-b")
581+
const other = new Delivery(root, { ...limits, core_lessons: 2 })
582+
expect(await other.section("switch")).not.toContain("Name staging models")
583+
expect((await other.prepare("switch", "first", "staging")).section).not.toContain("Name staging models")
584+
signedIn.mockResolvedValue(null)
585+
expect((await new Delivery(root, { ...limits, core_lessons: 2 }).prepare("signed-out", "first", "staging")).section).not.toContain("Name staging models")
586+
} finally {
587+
if (env === undefined) delete process.env.ALTIMATE_DISABLE_WORKSPACE
588+
else process.env.ALTIMATE_DISABLE_WORKSPACE = env
589+
}
590+
})
591+
564592
test("a mirror that cannot be read keeps a resumed session's cached team rules", async () => {
565593
await approve([lesson("L-0401", "Keep the project rules explicit.", { pinned: true })])
566594
await approve([lesson("L-0402", "Name staging models stg_<source>.", { pinned: true })], Store.WORKSPACE_RULES_STORE)

‎packages/opencode/test/altimate/rules/rules.test.ts‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -691,6 +691,26 @@ describe("the workspace API, by path", () => {
691691
expect((await RulesStore.read(root)).outbox).toEqual([])
692692
})
693693

694+
test("pulled rules are vouched for only while the credential that pulled them is signed in", async () => {
695+
const root = await tmp()
696+
const url = `http://127.0.0.1:${server.port}`
697+
const signedIn = spyOn(WorkspaceState, "accountDigest").mockResolvedValue(WorkspaceState.credentialDigest(url, "t", "secret-key"))
698+
try {
699+
answer = () => Response.json(syncBody([rule("bbbbbbbbbbbb", "Name staging models stg_<source>.")]))
700+
await RulesSync.pull(root, ready())
701+
expect([...(await RulesStore.vouched(root)).values()]).toEqual(["Name staging models stg_<source>."])
702+
signedIn.mockResolvedValue(WorkspaceState.credentialDigest(url, "t", "another-key"))
703+
expect((await RulesStore.vouched(root)).size).toBe(0)
704+
signedIn.mockResolvedValue(null)
705+
expect((await RulesStore.vouched(root)).size).toBe(0)
706+
// A pull that finished after someone else signed in is not stamped with its credential.
707+
await RulesSync.pull(root, ready())
708+
expect((await RulesStore.read(root)).pulled_with).toBeUndefined()
709+
} finally {
710+
signedIn.mockRestore()
711+
}
712+
})
713+
694714
test("a dropped usage batch marks its sessions reported, so the same batch is not rebuilt", async () => {
695715
const root = await tmp()
696716
answer = () => Response.json(syncBody([rule("aaaaaaaaaaaa", "Name staging models stg_<source>.")]))

0 commit comments

Comments
 (0)