Skip to content

Commit c90755d

Browse files
saravmajesticclaude
andcommitted
fix: deliver team rules as the rules state holds them, not the project's copy
- `RulesStore.vouched` returns each rule as a lesson built from the state, and delivery gives those: a copy in the project that keeps a rule's id and text but changes its pin, tags or paths no longer changes what is delivered - export `mayHaveWorkspaceRules` and test it: only a state in the person's state directory counts, not a `rules.json` in the project - test that a resumed session drops its cached team rules while the rules state cannot be read - comment and docs wording Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent b600a0b commit c90755d

7 files changed

Lines changed: 73 additions & 28 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 (`$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.
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). Team rules are delivered from your rules state, and only while you are signed in as the account that pulled them: the project's `workspace-rules` copy is never trusted on its own, so a copy that came with a branch or a merge is not delivered. 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: 8 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -218,7 +218,7 @@ export class Delivery {
218218
// valid snapshots retain their byte-identical prefix across resume and approved edits.
219219
const grandfathered = new Map<string, Pick<Lesson, "id" | "text">[]>()
220220
// Read once per check.
221-
let vouched: Promise<Map<string, string>> | undefined
221+
let vouched: Promise<Map<string, Lesson>> | undefined
222222
for (const { name, lesson } of state.shown) {
223223
// altimate_change start — workspace rules: a session's cached section and notes keep a team rule only while sync
224224
// still vouches for it: workspaces on, and the rule still in the person's rules state (an edit keeps its id, so its
@@ -239,16 +239,16 @@ export class Delivery {
239239
return state
240240
}
241241

242-
// altimate_change start — workspace rules: the team rules the person's own rules state holds now (lesson id → text),
243-
// outside the project. The `workspace-rules` copy in the project is only delivered where it matches: a file in the
244-
// working tree can come from anyone (a branch, a merge). Unreadable, it vouches for none.
245-
private async vouched(): Promise<Map<string, string>> {
242+
// altimate_change start — workspace rules: the team rules the person's own rules state holds now, by lesson id,
243+
// outside the project. They are delivered from that state, never from the `workspace-rules` copy in the project: a file
244+
// in the working tree can come from anyone (a branch, a merge). Unreadable, it vouches for none.
245+
private async vouched(): Promise<Map<string, Lesson>> {
246246
try {
247247
const { RulesStore } = await import("../rules/store")
248248
return await RulesStore.vouched(this.root)
249249
} catch (error) {
250250
log.warn("workspace rules state unreadable; team rules not delivered", { error })
251-
return new Map<string, string>()
251+
return new Map<string, Lesson>()
252252
}
253253
}
254254
// altimate_change end
@@ -273,12 +273,8 @@ export class Delivery {
273273
if (raw === undefined) continue
274274
await SafeFS.assertSafePath(this.root, Store.paths(this.root, name).usage)
275275
await SafeFS.assertSafePath(this.root, path.join(Store.paths(this.root, name).learnDir, "shown.jsonl"))
276-
let parsed = parse(raw)
277-
// altimate_change start — workspace rules: only the team rules the person's rules state holds, word for word
278-
if (name === Store.WORKSPACE_RULES_STORE) {
279-
const vouched = await this.vouched()
280-
parsed = parsed.filter((lesson) => vouched.get(lesson.id) === lesson.text)
281-
}
276+
// altimate_change start — workspace rules: the team rules come from the person's rules state, not the project's copy
277+
const parsed = name === Store.WORKSPACE_RULES_STORE ? [...(await this.vouched()).values()] : parse(raw)
282278
// altimate_change end
283279
const lessons = await Store.mergeUsage(this.root, name, parsed)
284280
const grandfathered = lessons.some((lesson) => lesson.text.length > MAX_TEXT)

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

Lines changed: 10 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,8 @@
1111
// this repository, as lessons of the read-only `workspace-rules` store (a name reserved for it; the person's own
1212
// stores, `team` included, are separate). Delivery, recurrence and `learn show` read it like any other store, so team
1313
// rules reach the prompt ("Team rules"), their exposure is recorded, and "corrected again" falls out of recurrence.
14-
// Only a pull writes it; reflection and promotion never target this store. Delivery gives a rule from it only while
15-
// the state holds the same rule (`vouched`): a copy in the project is never trusted on its own.
14+
// Only a pull writes it; reflection and promotion never target this store. Delivery gives team rules from the state
15+
// (`vouched`), never from this copy: a copy in the project is never trusted on its own.
1616
//
1717
// Writes take the learn lock (delivery reads the same directory) and are atomic.
1818
import { constants } from "node:fs"
@@ -224,19 +224,18 @@ async function writePrivate(file: string, data: string): Promise<void> {
224224
}
225225
}
226226

227-
/** The team rules delivery may give from the project's `workspace-rules` copy: lesson id → text, as the state holds
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. */
231-
export async function vouched(root: string): Promise<Map<string, string>> {
227+
/** The team rules delivery may give, by lesson id, built from the state: nothing of the project's `workspace-rules`
228+
* copy (wording, pin, tags, paths) is used. None while the project is not linked (unlinked and lost access clear the
229+
* state's workspace), and none unless the credential signed in now is the one they were pulled with: a sign-out or
230+
* another account stops them at once, not at the next sync. No network. */
231+
export async function vouched(root: string): Promise<Map<string, Lesson>> {
232232
const state = await read(root)
233233
if (!state.workspace || !state.pulled_with) return new Map()
234234
const { accountDigest } = await import("../workspace/state")
235235
if ((await accountDigest().catch(() => null)) !== state.pulled_with) return new Map()
236-
return new Map(state.rules.map((rule) => [lessonId(rule.rule_key), rule.text]))
236+
return new Map(state.rules.map((rule) => [lessonId(rule.rule_key), toLesson(rule)]))
237237
}
238238

239-
240239
function parse(raw: string | undefined): State | undefined {
241240
if (!raw) return structuredClone(EMPTY)
242241
try {
@@ -273,9 +272,8 @@ export function toLesson(rule: RuleOut): Lesson {
273272

274273
const IGNORE = "*\n"
275274

276-
/** Under the learn lock. The parent learn ignore already keeps `rules.json` out of Git but shares each store's
277-
* `approved.json`, so the mirror needs this one too (whatever an older file said). Written with the mirror only,
278-
* so a project without a workspace never gets it. */
275+
/** Under the learn lock. The parent learn ignore shares each store's `approved.json`, so the mirror needs this one
276+
* (whatever an older file said). Written with the mirror only, so a project without a workspace never gets it. */
279277
async function ensureIgnore(root: string) {
280278
const ignore = path.join(dir(root), ".gitignore")
281279
const current = await SafeFS.open(root, ignore, constants.O_RDONLY)

‎packages/opencode/src/session/prompt.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -173,7 +173,7 @@ const boundDirectories = (): ReadonlySet<string> => {
173173
return new Set()
174174
}
175175
}
176-
const mayHaveWorkspaceRules = (root: string, directory: string) => {
176+
export const mayHaveWorkspaceRules = (root: string, directory: string) => {
177177
if (existsSync(stateFileOf(canonicalDirectory(root)))) return true
178178
const dirs = boundDirectories()
179179
return dirs.size > 0 && dirs.has(canonicalDirectory(directory))

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

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -568,6 +568,44 @@ test("a team-rules copy in the project that the person's rules state does not ho
568568
}
569569
})
570570

571+
test("a team-rules copy that keeps an approved rule's wording but changes its pin or paths is delivered as the state holds it", async () => {
572+
await approve([lesson("L-0801", "Keep the project rules explicit.", { pinned: true })])
573+
const env = process.env.ALTIMATE_DISABLE_WORKSPACE
574+
try {
575+
delete process.env.ALTIMATE_DISABLE_WORKSPACE
576+
// Approved for staging models only.
577+
await pulled([lesson("L-0802", "Name staging models stg_<source>.", { trigger: { paths: ["models/staging/**"] } })])
578+
const scoped = (await new Delivery(root, { ...limits, core_lessons: 2 }).prepare("scoped", "first", "invoices")).section
579+
expect(scoped).toContain("[applies to: models/staging/**] Name staging models")
580+
// A branch rewrites the copy: same id and wording, now pinned and with no paths.
581+
await fs.writeFile(Store.paths(root, Store.WORKSPACE_RULES_STORE).approved, canonical([lesson("L-000000000802", "Name staging models stg_<source>.", { pinned: true })]))
582+
const planted = new Delivery(root, { ...limits, core_lessons: 2 })
583+
expect((await planted.prepare("planted", "first", "invoices")).section).toBe(scoped)
584+
} finally {
585+
if (env === undefined) delete process.env.ALTIMATE_DISABLE_WORKSPACE
586+
else process.env.ALTIMATE_DISABLE_WORKSPACE = env
587+
}
588+
})
589+
590+
test("a resumed session drops its cached team rules while the person's rules state cannot be read", async () => {
591+
await approve([lesson("L-0901", "Keep the project rules explicit.", { pinned: true })])
592+
await approve([lesson("L-0902", "Name staging models stg_<source>.", { pinned: true })], Store.WORKSPACE_RULES_STORE)
593+
const env = process.env.ALTIMATE_DISABLE_WORKSPACE
594+
const file = await RulesStore.stateFile(root)
595+
try {
596+
delete process.env.ALTIMATE_DISABLE_WORKSPACE
597+
expect((await new Delivery(root, { ...limits, core_lessons: 2 }).prepare("locked", "first", "staging")).section).toContain("Name staging models")
598+
await fs.chmod(file, 0o000)
599+
const unreadable = new Delivery(root, { ...limits, core_lessons: 2 })
600+
expect(await unreadable.section("locked")).not.toContain("Name staging models")
601+
expect((await unreadable.prepare("locked", "first", "staging")).section).not.toContain("Name staging models")
602+
} finally {
603+
await fs.chmod(file, 0o600)
604+
if (env === undefined) delete process.env.ALTIMATE_DISABLE_WORKSPACE
605+
else process.env.ALTIMATE_DISABLE_WORKSPACE = env
606+
}
607+
})
608+
571609
test("team rules stop at once when the person signs out or signs in as someone else", async () => {
572610
await approve([lesson("L-0701", "Keep the project rules explicit.", { pinned: true })])
573611
await approve([lesson("L-0702", "Name staging models stg_<source>.", { pinned: true })], Store.WORKSPACE_RULES_STORE)

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -698,7 +698,7 @@ describe("the workspace API, by path", () => {
698698
try {
699699
answer = () => Response.json(syncBody([rule("bbbbbbbbbbbb", "Name staging models stg_<source>.")]))
700700
await RulesSync.pull(root, ready())
701-
expect([...(await RulesStore.vouched(root)).values()]).toEqual(["Name staging models stg_<source>."])
701+
expect([...(await RulesStore.vouched(root)).values()].map((l) => l.text)).toEqual(["Name staging models stg_<source>."])
702702
signedIn.mockResolvedValue(WorkspaceState.credentialDigest(url, "t", "another-key"))
703703
expect((await RulesStore.vouched(root)).size).toBe(0)
704704
signedIn.mockResolvedValue(null)

‎packages/opencode/test/session/learn-prompt.test.ts‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
// altimate_change - new file
22
import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"
3-
import { SessionPrompt } from "../../src/session/prompt"
3+
import { SessionPrompt, mayHaveWorkspaceRules } from "../../src/session/prompt"
4+
import { RulesStore } from "../../src/altimate/rules/store"
45
import { MessageV2 } from "../../src/session/message-v2"
56
import { MessageID, PartID, SessionID } from "../../src/session/schema"
67
import { ModelID, ProviderID } from "../../src/provider/schema"
@@ -209,3 +210,15 @@ describe("approved team rules attached to a user turn", () => {
209210
})
210211
}
211212
})
213+
214+
describe("whether a project may have workspace rules", () => {
215+
test("only a rules state in the person's own state directory counts, never a rules file in the project", async () => {
216+
await using project = await tmpdir()
217+
// The state's old place in the project: a branch can commit it, and it is never read.
218+
await Bun.write(path.join(project.path, ".altimate-code/learn/workspace-rules/rules.json"), JSON.stringify({ version: 1 }))
219+
expect(mayHaveWorkspaceRules(project.path, project.path)).toBe(false)
220+
// A state written for this project, with no workspace binding for its directory.
221+
await RulesStore.update(project.path, (s) => { s.personal_learning = false })
222+
expect(mayHaveWorkspaceRules(project.path, project.path)).toBe(true)
223+
})
224+
})

0 commit comments

Comments
 (0)