Skip to content

Commit 6f293bd

Browse files
committed
feat(plugin): inject project rules and show both rule stores clearly
- selectInjected now reads the project store as well as the global one (project rules first, per AIMETH-008), so a per-repo rule is actually injected instead of only written. - listLearnings tags each rule with its store (global vs project); synapse_list_rules groups by store and prints both store paths even when empty. - Extracted learningStorePaths so the store locations are defined once.
1 parent d96803c commit 6f293bd

3 files changed

Lines changed: 107 additions & 61 deletions

File tree

‎packages/opencode/src/plugin/observer.ts‎

Lines changed: 53 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -302,12 +302,9 @@ class SessionObserverManager {
302302
this.sessionLearnings.unshift(entry)
303303
if (this.sessionLearnings.length > 100) this.sessionLearnings.pop()
304304

305-
// Persist to the central and workspace stores, serialised against forgetLearning.
306-
const homeDir = process.env.USERPROFILE || process.env.HOME || ""
307-
const files = [
308-
homeDir ? path.join(homeDir, ".local", "share", "opencode", "learnings.json") : undefined,
309-
workspaceDir ? path.join(workspaceDir, ".system_generated", "logs", "learnings.json") : undefined,
310-
].filter((file): file is string => Boolean(file))
305+
// Persist to the global and project stores, serialised against forgetLearning.
306+
const paths = learningStorePaths(workspaceDir)
307+
const files = [paths.global, paths.project].filter((file): file is string => Boolean(file))
311308
await this.mutate(async () => {
312309
for (const file of files) {
313310
try {
@@ -330,22 +327,34 @@ class SessionObserverManager {
330327
* The rules actually selected for injection, in the same order the prompt
331328
* builder uses. Shared so the listed `injected` flag cannot drift from reality.
332329
*/
333-
private async selectInjected(limit: number): Promise<SessionLearning[]> {
330+
private async selectInjected(limit: number, workspaceDir?: string): Promise<SessionLearning[]> {
334331
if (this.sessionLearnings.length > 0) {
335332
return this.sessionLearnings.slice(0, limit)
336333
}
337334
// Read through the mutation queue: a read that starts while a forget is still
338335
// writing must not reload the store it is about to forget from.
339336
const loaded = await this.mutate(async () => {
340-
try {
341-
const homeDir = process.env.USERPROFILE || process.env.HOME || ""
342-
if (!homeDir) return [] as SessionLearning[]
343-
const centralFile = path.join(homeDir, ".local", "share", "opencode", "learnings.json")
344-
const content = JSON.parse(await fs.readFile(centralFile, "utf8"))
345-
return Array.isArray(content) ? (content as SessionLearning[]) : []
346-
} catch {
347-
return [] as SessionLearning[]
337+
const read = async (file?: string): Promise<SessionLearning[]> => {
338+
if (!file) return []
339+
try {
340+
const parsed = JSON.parse(await fs.readFile(file, "utf8"))
341+
return Array.isArray(parsed) ? (parsed as SessionLearning[]) : []
342+
} catch {
343+
return []
344+
}
348345
}
346+
const paths = learningStorePaths(workspaceDir)
347+
// Project rules first: a committed, reviewed repo rule outranks an ad-hoc
348+
// global note (AIMETH-008 - shared repo facts win). One entry per rule text.
349+
const seen = new Set<string>()
350+
const merged: SessionLearning[] = []
351+
for (const rule of [...(await read(paths.project)), ...(await read(paths.global))]) {
352+
const key = learningKey(rule)
353+
if (seen.has(key)) continue
354+
seen.add(key)
355+
merged.push(rule)
356+
}
357+
return merged
349358
})
350359
if (loaded.length > 0) {
351360
// Merge, never clobber: a rule recorded while the read was pending must not
@@ -359,8 +368,8 @@ class SessionObserverManager {
359368
return this.sessionLearnings.slice(0, limit)
360369
}
361370

362-
public async getRecentLearnings(limit = 5): Promise<SessionLearning[]> {
363-
return this.selectInjected(limit)
371+
public async getRecentLearnings(limit = 5, workspaceDir?: string): Promise<SessionLearning[]> {
372+
return this.selectInjected(limit, workspaceDir)
364373
}
365374

366375
private mutation: Promise<unknown> = Promise.resolve()
@@ -373,37 +382,34 @@ class SessionObserverManager {
373382
}
374383

375384
/**
376-
* Every persisted rule, with where it was found and whether it is one of the
377-
* most-recent rules actually injected into a session's system prompt. This is
378-
* the honest answer to "what rules is the agent using?" - recorded rules that
379-
* fall outside the injection window are shown as `stored`, not `injected`.
385+
* Every persisted rule, tagged with which store it lives in (`global` = whole
386+
* machine, `project` = this repo) and whether it is actually injected into a
387+
* session's system prompt. This is the honest answer to "what rules is the
388+
* agent using?" - a rule outside the injection window is shown as stored.
380389
*/
381390
public async listLearnings(
382391
workspaceDir?: string,
383-
): Promise<Array<SessionLearning & { origin: "central" | "workspace"; injected: boolean }>> {
384-
const read = async (file: string): Promise<SessionLearning[]> => {
392+
): Promise<Array<SessionLearning & { origin: "global" | "project"; injected: boolean }>> {
393+
const read = async (file?: string): Promise<SessionLearning[]> => {
394+
if (!file) return []
385395
try {
386396
const parsed = JSON.parse(await fs.readFile(file, "utf8"))
387397
return Array.isArray(parsed) ? (parsed as SessionLearning[]) : []
388398
} catch {
389399
return []
390400
}
391401
}
392-
const homeDir = process.env.USERPROFILE || process.env.HOME || ""
393-
const central = homeDir
394-
? await read(path.join(homeDir, ".local", "share", "opencode", "learnings.json"))
395-
: []
396-
const workspace = workspaceDir
397-
? await read(path.join(workspaceDir, ".system_generated", "logs", "learnings.json"))
398-
: []
399-
const centralKeys = new Set(central.map((l) => l.lesson.trim().toLowerCase()))
402+
const paths = learningStorePaths(workspaceDir)
403+
const global = await read(paths.global)
404+
const project = await read(paths.project)
405+
const globalKeys = new Set(global.map(learningKey))
400406
const merged = [
401-
...central.map((l) => ({ ...l, origin: "central" as const })),
402-
...workspace
403-
.filter((l) => !centralKeys.has(l.lesson.trim().toLowerCase()))
404-
.map((l) => ({ ...l, origin: "workspace" as const })),
407+
...global.map((l) => ({ ...l, origin: "global" as const })),
408+
...project
409+
.filter((l) => !globalKeys.has(learningKey(l)))
410+
.map((l) => ({ ...l, origin: "project" as const })),
405411
].sort((a, b) => (a.timestamp < b.timestamp ? 1 : -1))
406-
const injectedKeys = new Set((await this.selectInjected(INJECTED_LEARNINGS_LIMIT)).map(learningKey))
412+
const injectedKeys = new Set((await this.selectInjected(INJECTED_LEARNINGS_LIMIT, workspaceDir)).map(learningKey))
407413
return merged.map((l) => ({ ...l, injected: injectedKeys.has(learningKey(l)) }))
408414
}
409415

@@ -417,11 +423,8 @@ class SessionObserverManager {
417423
if (!needle) return 0
418424
const matches = (l: SessionLearning) => String(l.lesson ?? "").toLowerCase().includes(needle)
419425
this.sessionLearnings = this.sessionLearnings.filter((l) => !matches(l))
420-
const homeDir = process.env.USERPROFILE || process.env.HOME || ""
421-
const files = [
422-
homeDir ? path.join(homeDir, ".local", "share", "opencode", "learnings.json") : undefined,
423-
workspaceDir ? path.join(workspaceDir, ".system_generated", "logs", "learnings.json") : undefined,
424-
].filter((file): file is string => Boolean(file))
426+
const paths = learningStorePaths(workspaceDir)
427+
const files = [paths.global, paths.project].filter((file): file is string => Boolean(file))
425428
const removed = new Set<string>()
426429
for (const file of files) {
427430
for (const key of await this.dropRules(file, matches)) removed.add(key)
@@ -469,6 +472,15 @@ class SessionObserverManager {
469472
/** How many of the most-recent rules are injected into a session system prompt. */
470473
export const INJECTED_LEARNINGS_LIMIT = 5
471474

475+
/** The two on-disk rule stores: global (whole machine) and this project. */
476+
export function learningStorePaths(workspaceDir?: string): { global?: string; project?: string } {
477+
const homeDir = process.env.USERPROFILE || process.env.HOME || ""
478+
return {
479+
global: homeDir ? path.join(homeDir, ".local", "share", "opencode", "learnings.json") : undefined,
480+
project: workspaceDir ? path.join(workspaceDir, ".system_generated", "logs", "learnings.json") : undefined,
481+
}
482+
}
483+
472484
const learningKey = (l: SessionLearning) => String(l.lesson ?? "").trim().toLowerCase()
473485

474486
/** Write JSON via a temp file + rename so a reader never sees a half-written file. */

‎packages/opencode/src/plugin/synapse.ts‎

Lines changed: 25 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import * as fs from "fs/promises"
66
import open from "open"
77
import { OauthCallbackPage } from "@opencode-ai/core/oauth/page"
88
import { InstallationVersion } from "@opencode-ai/core/installation/version"
9-
import { INJECTED_LEARNINGS_LIMIT, sessionObserver, sanitizeJsonSchemaForOpenAI } from "./observer"
9+
import { INJECTED_LEARNINGS_LIMIT, learningStorePaths, sessionObserver, sanitizeJsonSchemaForOpenAI } from "./observer"
1010
import { EscalationTracker, declaredTier, classifyFailure, malformedToolCallFromEvent } from "./synapse-escalation"
1111

1212
export const KEYSTONE_ISSUER = "https://identity.alterspective.com.au"
@@ -1434,7 +1434,7 @@ export async function SynapseAuthPlugin(input: PluginInput, options?: SynapsePlu
14341434
sessionObserver.onToolAfter(toolInput.sessionID, toolInput.callID, toolInput.tool, output.output)
14351435
},
14361436
"experimental.chat.system.transform": async (_input, output) => {
1437-
const recentLearnings = await sessionObserver.getRecentLearnings(5)
1437+
const recentLearnings = await sessionObserver.getRecentLearnings(INJECTED_LEARNINGS_LIMIT, input.directory)
14381438
if (escalations.atCap(_input.sessionID ?? input.directory)) {
14391439
output.system.push(
14401440
"AIESC-03: automatic escalation budget is exhausted for this session. Do NOT retry the same request shape. Present the failure evidence to the user and ask how to proceed.",
@@ -1520,25 +1520,31 @@ export async function SynapseAuthPlugin(input: PluginInput, options?: SynapsePlu
15201520
args: {},
15211521
async execute() {
15221522
const rules = await sessionObserver.listLearnings(input.directory)
1523-
if (rules.length === 0) return "No operating rules are recorded."
1523+
const paths = learningStorePaths(input.directory)
15241524
const injected = rules.filter((r) => r.injected).length
1525+
const line = (r: (typeof rules)[number]) =>
1526+
" " +
1527+
(r.injected ? "[injected]" : "[stored] ") +
1528+
" " +
1529+
r.lesson +
1530+
" (" +
1531+
r.source +
1532+
", recorded " +
1533+
r.timestamp +
1534+
")"
1535+
const group = (title: string, file: string | undefined, origin: "global" | "project") => {
1536+
const rows = rules.filter((r) => r.origin === origin)
1537+
return [title + " " + (file ?? "(unavailable)"), ...(rows.length > 0 ? rows.map(line) : [" (none)"])]
1538+
}
15251539
return [
1526-
injected + " of " + rules.length + " recorded rule(s) are injected into this session (the most recent " + INJECTED_LEARNINGS_LIMIT + ").",
1527-
...rules.map(
1528-
(r, i) =>
1529-
(i + 1) +
1530-
". " +
1531-
(r.injected ? "[injected]" : "[stored] ") +
1532-
" " +
1533-
r.lesson +
1534-
" (source: " +
1535-
r.source +
1536-
", store: " +
1537-
r.origin +
1538-
", recorded: " +
1539-
r.timestamp +
1540-
")",
1541-
),
1540+
injected +
1541+
" of " +
1542+
rules.length +
1543+
" recorded rule(s) are injected into this session (the most recent " +
1544+
INJECTED_LEARNINGS_LIMIT +
1545+
", project rules first).",
1546+
...group("Project - this repo only:", paths.project, "project"),
1547+
...group("Global - every project on this machine:", paths.global, "global"),
15421548
].join("\n")
15431549
},
15441550
}),

‎packages/opencode/test/plugin/observer.test.ts‎

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,34 @@ describe("SessionObserverManager.onToolAfter", () => {
8181
describe("rule visibility", () => {
8282
// Declared before any other learning test so the observer's in-memory cache is
8383
// still empty and the real "read from file" injection path actually runs.
84+
test("injects a rule that exists only in the project store", async () => {
85+
const global = await fs.mkdtemp(path.join(os.tmpdir(), "oc-g-"))
86+
const ws = await fs.mkdtemp(path.join(os.tmpdir(), "oc-p-"))
87+
const prev = process.env.USERPROFILE
88+
process.env.USERPROFILE = global
89+
try {
90+
const wsFile = path.join(ws, ".system_generated", "logs", "learnings.json")
91+
await fs.mkdir(path.dirname(wsFile), { recursive: true })
92+
await fs.writeFile(
93+
wsFile,
94+
JSON.stringify([
95+
{ id: "p1", timestamp: "2026-09-23T00:00:00.000Z", lesson: "project only rule", source: "user_feedback" },
96+
]),
97+
"utf8",
98+
)
99+
const listed = await sessionObserver.listLearnings(ws)
100+
const row = listed.find((r) => r.lesson === "project only rule")!
101+
expect(row.origin).toBe("project")
102+
expect(row.injected).toBe(true)
103+
// Clear the cache this test populated so later tests read their own files.
104+
await sessionObserver.forgetLearning("project only rule", ws)
105+
} finally {
106+
process.env.USERPROFILE = prev
107+
await fs.rm(global, { recursive: true, force: true })
108+
await fs.rm(ws, { recursive: true, force: true })
109+
}
110+
})
111+
84112
test("reports the real injection window and counts a rule once across both stores", async () => {
85113
const central = await fs.mkdtemp(path.join(os.tmpdir(), "oc-central-"))
86114
const ws = await fs.mkdtemp(path.join(os.tmpdir(), "oc-ws-"))
@@ -108,7 +136,7 @@ describe("rule visibility", () => {
108136
// newest by timestamp, but outside the first-five window the prompt actually uses
109137
expect(injected["rule 6"]).toBe(false)
110138
expect(injected["rule 7"]).toBe(false)
111-
expect(listed.find((r) => r.lesson === "rule 1")!.origin).toBe("central")
139+
expect(listed.find((r) => r.lesson === "rule 1")!.origin).toBe("global")
112140

113141
expect(await sessionObserver.forgetLearning("rule 1", ws)).toBe(1)
114142
const after = await sessionObserver.listLearnings(ws)

0 commit comments

Comments
 (0)