Skip to content

Commit 1909582

Browse files
anandgupta42claude
andcommitted
fix(learn): person actions end automatic ownership for good
Manual `learn promote`, `rollback`, `pin` and `unpin` now clear the auto-promote marks under the learn lock before their first write, and fail without changing anything if that cannot be recorded. Marks therefore cannot revive when the approved set later returns to the same bytes (for example a rollback to the auto-published set). The approved-set hash still voids marks for changes made outside learn. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
1 parent 4347d6d commit 1909582

4 files changed

Lines changed: 110 additions & 8 deletions

File tree

‎docs/docs/configure/learn.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -139,7 +139,7 @@ It runs only after automatic reflection (end of `run`, threshold, idle, startup
139139
| Validation | It fails the checks `learn promote` runs: lint, hidden characters, coexistence, and overlaps. |
140140
| Feedback | No signal from a person or an external check is behind the reflection: it needs at least one correction (`user_correction`, including `learn signal add --kind user`), `review` or `ci` signal. Repeated tool failures (`tool_retry`) are captured automatically, so on their own they only stage a candidate. Also held when the feedback was flagged as an instruction to the model. |
141141
| Verification flags | A lesson it adds or changes mentions skipping or disabling verification. Those always need a person. |
142-
| Your approvals | It would edit or remove a lesson a person approved. A lesson counts as automatic only while the approved set is exactly what the last automatic promotion published and the lesson is not pinned. Any `learn promote`, `rollback`, `pin` or `unpin`, or a change to `approved.json` from a pull, makes every approved lesson person-approved. Lessons from another checkout count as person-approved. |
142+
| Your approvals | It would edit or remove a lesson a person approved. A lesson counts as automatic only while the approved set is exactly what the last automatic promotion published and the lesson is not pinned. Any `learn promote`, `rollback`, `pin` or `unpin` makes every approved lesson person-approved for good, even if the set later returns to the same contents; if that cannot be recorded, the command fails and changes nothing. A change to `approved.json` from outside learn, such as a pull, also makes them person-approved. Lessons from another checkout count as person-approved. |
143143
| Size | It adds, edits, or removes more than `learn.auto_promote_max_changes` lessons (default 3), or changes only counters. |
144144
| Rate | The store already had `learn.auto_promote_daily` automatic promotions (default 5) in the last 24 hours. |
145145

‎packages/opencode/src/altimate/learn/auto-promote.ts‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,29 @@ async function writeState(root: string, name: string, state: AutoPromoteState) {
9797
await Store.writeAtomic(root, file, JSON.stringify(state, null, 2) + "\n", 0o600)
9898
}
9999

100+
/**
101+
* Person actions on the approved set (`learn promote`, `rollback`, `pin`, `unpin`) end automatic ownership
102+
* for good, even if the set later returns to the same bytes. Called under the learn lock before the
103+
* action's first write. A failed write aborts the action (fail closed): the error says nothing changed.
104+
* An unreadable state file trusts no marks already (automatic promotion refuses to run), so it is left alone.
105+
*/
106+
export async function voidAutoOwnership(root: string, name: string): Promise<void> {
107+
let state: AutoPromoteState
108+
try {
109+
state = await readAutoPromoteState(root, name)
110+
} catch {
111+
return
112+
}
113+
if (Object.keys(state.auto).length === 0 && state.approvedHash === undefined) return
114+
const { approvedHash: _voided, ...rest } = state
115+
try {
116+
await writeState(root, name, { ...rest, auto: {} })
117+
} catch (error) {
118+
throw new Error(`Cannot record that lessons are no longer automatic in ${autoPromoteStateFile(root, name)} ` +
119+
`(${redactSecrets(errText(error))}); nothing was changed. Fix the file's permissions or delete it, then retry.`)
120+
}
121+
}
122+
100123
/** The latest promotion whose publish completed; reservations are not promotions. */
101124
export function lastCompletedPromotion(state: AutoPromoteState): AutoPromotion | undefined {
102125
return state.promotions.findLast((promotion) => !promotion.pending)

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

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -215,18 +215,24 @@ export async function setPinned(root: string, name: string, id: string, pinned:
215215
const updated = new Date().toISOString()
216216
Object.assign(lesson, { pinned, updated })
217217
const p = paths(root, name)
218+
// A person acted on the approved set: no lesson in it is automatic any more (auto-promote.ts).
219+
await voidAutoOwnership(root, name)
218220
await writeAtomic(root, p.approved, Lessons.canonical(approved))
219221
// A candidate already in progress must not undo this pin on the next curation or promotion.
220222
if (staged) {
221223
Object.assign(staged, { pinned, updated })
222224
await writeAtomic(root, p.candidate, Lessons.canonical(candidate))
223225
}
224-
// Rewriting approved.json also voids automatic ownership (auto-promote.ts binds it to the approved set).
225226
await appendHistory(root, name, { action: pinned ? "pin" : "unpin", id })
226227
return lesson
227228
})
228229
}
229230

231+
/** Lazy: auto-promote.ts imports this module. */
232+
async function voidAutoOwnership(root: string, name: string) {
233+
await (await import("./auto-promote")).voidAutoOwnership(root, name)
234+
}
235+
230236
async function reconcileRetired(root: string, name: string) {
231237
const retired = await loadRetired(root, name)
232238
if (!retired.length) return
@@ -642,6 +648,8 @@ export async function promote(root: string, name: string, opts: PromoteOptions =
642648
const current = await readPromoted(root, name)
643649
if (current !== undefined && Lessons.canonical(Lessons.parse(current)) === publish)
644650
throw new StoreError(`Candidate is identical to the approved lessons; nothing to promote.`)
651+
// A person's promote ends automatic ownership before anything is written; auto-promote's own publish does not.
652+
if (opts.history?.action !== "auto-promote") await voidAutoOwnership(root, name)
645653
let archived: number | undefined
646654
if (current !== undefined) {
647655
// A staged candidate can carry older counters. Keep the approved baseline locally before replacing it.
@@ -691,6 +699,8 @@ export async function rollback(root: string, name: string): Promise<{ restored:
691699
catch { /* Diagnostics must not interrupt the local rollback. */ }
692700
}
693701
}
702+
// Rolling back is a person's choice of lessons: none of the restored set is automatic.
703+
await voidAutoOwnership(root, name)
694704
if (existing !== undefined) {
695705
// Preserve the verified baseline before replacing approved.json, including exports predating receipts.
696706
await writeAtomic(root, p.exportState, Lessons.canonical([sha256(existing)]))

‎packages/opencode/test/altimate/learn/auto-promote.test.ts‎

Lines changed: 75 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -149,10 +149,10 @@ describe("auto-promote success path", () => {
149149
await using dir = await tmpdir({ git: true })
150150
await approve(dir.path, [A])
151151
await autoPromote(input(dir.path, await stage(dir.path, [A, B])))
152-
const before = await fs.readFile(autoPromoteStateFile(dir.path, NAME), "utf8")
153152
await Store.setPinned(dir.path, NAME, B.id, true)
154-
// Pin commits without touching the automatic promotion state, yet the mark no longer applies.
155-
expect(await fs.readFile(autoPromoteStateFile(dir.path, NAME), "utf8")).toBe(before)
153+
// The pin ended automatic ownership in the state file before it was committed.
154+
expect(await readAutoPromoteState(dir.path, NAME)).toMatchObject({ auto: {} })
155+
expect((await readAutoPromoteState(dir.path, NAME)).approvedHash).toBeUndefined()
156156
let state = await readAutoPromoteState(dir.path, NAME)
157157
expect([...autoPromotedIds(state, await Store.loadApproved(dir.path, NAME))]).toEqual([])
158158
expect(await autoPromote(input(dir.path, await stage(dir.path, [A])))).toMatchObject({ status: "held", reason: expect.stringContaining(`person-approved lesson ${B.id}`) })
@@ -176,17 +176,86 @@ describe("auto-promote success path", () => {
176176
expect([...autoPromotedIds({ promotions: [], auto: { [B.id]: Store.sha256(B.text) } }, [lesson()])]).toEqual([])
177177
})
178178

179-
test("a person's promote voids automatic ownership without writing the state file", async () => {
179+
test("a person's promote voids automatic ownership in the state file", async () => {
180180
await using dir = await tmpdir({ git: true })
181181
await approve(dir.path, [A])
182182
await autoPromote(input(dir.path, await stage(dir.path, [A, B])))
183-
const before = await fs.readFile(autoPromoteStateFile(dir.path, NAME), "utf8")
184183
await approve(dir.path, [A, B, C])
185-
expect(await fs.readFile(autoPromoteStateFile(dir.path, NAME), "utf8")).toBe(before)
184+
expect(await readAutoPromoteState(dir.path, NAME)).toMatchObject({ auto: {} })
186185
expect([...autoPromotedIds(await readAutoPromoteState(dir.path, NAME), await Store.loadApproved(dir.path, NAME))]).toEqual([])
187186
expect(await autoPromote(input(dir.path, await stage(dir.path, [A, C])))).toMatchObject({ status: "held", reason: expect.stringContaining(`person-approved lesson ${B.id}`) })
188187
})
189188

189+
test("ABA: auto-promote, a person's promote, then rollback to the exact auto set: no marks revive", async () => {
190+
await using dir = await tmpdir({ git: true })
191+
await approve(dir.path, [A])
192+
await autoPromote(input(dir.path, await stage(dir.path, [A, B])))
193+
const autoSet = await Store.readPromoted(dir.path, NAME)
194+
await approve(dir.path, [A, B, C])
195+
await Store.rollback(dir.path, NAME)
196+
// Same bytes, same hash as the automatic publish.
197+
expect(await Store.readPromoted(dir.path, NAME)).toBe(autoSet)
198+
expect([...autoPromotedIds(await readAutoPromoteState(dir.path, NAME), await Store.loadApproved(dir.path, NAME))]).toEqual([])
199+
expect(await autoPromote(input(dir.path, await stage(dir.path, [A])))).toMatchObject({ status: "held", reason: expect.stringContaining(`person-approved lesson ${B.id}`) })
200+
expect(await approvedIds(dir.path)).toEqual([A.id, B.id])
201+
})
202+
203+
test("ABA: auto-promote, pin, unpin back to identical bytes: no marks revive", async () => {
204+
await using dir = await tmpdir({ git: true })
205+
await approve(dir.path, [A])
206+
await autoPromote(input(dir.path, await stage(dir.path, [A, B])))
207+
const autoSet = (await Store.readPromoted(dir.path, NAME))!
208+
await Store.setPinned(dir.path, NAME, B.id, true)
209+
await Store.setPinned(dir.path, NAME, B.id, false)
210+
// Unpin leaves `pinned: false` and a new timestamp; restore the exact bytes so the hash matches again.
211+
await Store.transaction(dir.path, () => Store.writeAtomic(dir.path, Store.paths(dir.path, NAME).approved, autoSet))
212+
expect([...autoPromotedIds(await readAutoPromoteState(dir.path, NAME), await Store.loadApproved(dir.path, NAME))]).toEqual([])
213+
expect(await autoPromote(input(dir.path, await stage(dir.path, [A])))).toMatchObject({ status: "held", reason: expect.stringContaining(`person-approved lesson ${B.id}`) })
214+
})
215+
216+
test("rolling back the automatic promotion itself restores a set with no automatic lessons", async () => {
217+
await using dir = await tmpdir({ git: true })
218+
await approve(dir.path, [A, C])
219+
await autoPromote(input(dir.path, await stage(dir.path, [A, C, B])))
220+
await Store.rollback(dir.path, NAME)
221+
expect(await approvedIds(dir.path)).toEqual([A.id, C.id])
222+
expect([...autoPromotedIds(await readAutoPromoteState(dir.path, NAME), await Store.loadApproved(dir.path, NAME))]).toEqual([])
223+
expect(await autoPromote(input(dir.path, await stage(dir.path, [A])))).toMatchObject({ status: "held", reason: expect.stringContaining(`person-approved lesson ${C.id}`) })
224+
})
225+
226+
test.each(["promote", "rollback", "pin"])("a person's %s aborts, changing nothing, when automatic ownership cannot be ended", async (action) => {
227+
await using dir = await tmpdir({ git: true })
228+
await approve(dir.path, [A])
229+
await autoPromote(input(dir.path, await stage(dir.path, [A, B])))
230+
if (action === "promote") await stage(dir.path, [A, B, C])
231+
const approvedBefore = await Store.readPromoted(dir.path, NAME)
232+
const stateBefore = await fs.readFile(autoPromoteStateFile(dir.path, NAME), "utf8")
233+
const original = Store.writeAtomic
234+
const write = spyOn(Store, "writeAtomic").mockImplementation(async (...args: Parameters<typeof Store.writeAtomic>) => {
235+
if (args[1].endsWith("auto-promote.json")) throw new Error("EACCES: permission denied")
236+
return original(...args)
237+
})
238+
try {
239+
const run = action === "promote" ? Store.promote(dir.path, NAME)
240+
: action === "rollback" ? Store.rollback(dir.path, NAME)
241+
: Store.setPinned(dir.path, NAME, B.id, true)
242+
await expect(run).rejects.toThrow("nothing was changed")
243+
} finally {
244+
write.mockRestore()
245+
}
246+
expect(await Store.readPromoted(dir.path, NAME)).toBe(approvedBefore)
247+
expect(await fs.readFile(autoPromoteStateFile(dir.path, NAME), "utf8")).toBe(stateBefore)
248+
})
249+
250+
test("a person action on a store that never auto-promoted creates no state file", async () => {
251+
await using dir = await tmpdir({ git: true })
252+
await approve(dir.path, [A])
253+
await approve(dir.path, [A, B])
254+
await Store.setPinned(dir.path, NAME, A.id, true)
255+
await Store.rollback(dir.path, NAME)
256+
expect(await Bun.file(autoPromoteStateFile(dir.path, NAME)).exists()).toBe(false)
257+
})
258+
190259
test("a rollback voids automatic ownership: the restored lessons are a person's choice", async () => {
191260
await using dir = await tmpdir({ git: true })
192261
await approve(dir.path, [A])

0 commit comments

Comments
 (0)