Skip to content

Commit 10337a5

Browse files
authored
feat(plugin): inject project rules and show both rule stores clearly (#35)
* 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. * fix(plugin): make rule reads workspace-aware and restore test env correctly - Removed the process-global rule cache: one opencode process can serve several projects, so a cached list could inject another project's rules. Rules are now always read from disk for the calling workspace. - recordLearning dedupes and refreshes recency from the files. - Tests restore USERPROFILE by deleting it when it was unset, instead of assigning the string 'undefined'. * fix(plugin): move a re-recorded rule to the front; test via tmpdir fixture - Re-recording an existing rule now rewrites it at the head of the store, so recency puts it back inside the injection window (the window slices array order, not timestamp). - Rule-visibility tests use the repo tmpdir fixture and cover the re-record ordering.
1 parent d96803c commit 10337a5

3 files changed

Lines changed: 153 additions & 132 deletions

File tree

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

Lines changed: 66 additions & 76 deletions
Original file line numberDiff line numberDiff line change
@@ -277,37 +277,19 @@ class SessionObserverManager {
277277
} catch {}
278278
}
279279

280-
private sessionLearnings: SessionLearning[] = []
281-
282280
public async recordLearning(
283281
learning: Omit<SessionLearning, "id" | "timestamp">,
284282
workspaceDir?: string,
285283
): Promise<SessionLearning> {
286284
const normalizedText = learning.lesson.trim().toLowerCase()
287-
const existingIndex = this.sessionLearnings.findIndex(
288-
(l) => l.lesson.trim().toLowerCase() === normalizedText,
289-
)
290-
if (existingIndex !== -1) {
291-
// Update existing entry timestamp and return without duplicating
292-
const existing = this.sessionLearnings[existingIndex]
293-
existing.timestamp = new Date().toISOString()
294-
return existing
295-
}
296-
285+
const paths = learningStorePaths(workspaceDir)
286+
const files = [paths.global, paths.project].filter((file): file is string => Boolean(file))
297287
const entry: SessionLearning = {
298288
id: `learn_${Date.now()}_${Math.random().toString(36).slice(2, 7)}`,
299289
timestamp: new Date().toISOString(),
300290
...learning,
301291
}
302-
this.sessionLearnings.unshift(entry)
303-
if (this.sessionLearnings.length > 100) this.sessionLearnings.pop()
304-
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))
292+
let stored = entry
311293
await this.mutate(async () => {
312294
for (const file of files) {
313295
try {
@@ -317,50 +299,56 @@ class SessionObserverManager {
317299
const parsed = JSON.parse(await fs.readFile(file, "utf8"))
318300
if (Array.isArray(parsed)) existing = parsed
319301
} catch {}
320-
if (!existing.some((e) => e.lesson.trim().toLowerCase() === normalizedText)) {
321-
await writeJsonAtomic(file, [entry, ...existing].slice(0, 100))
302+
const found = existing.find((e) => e.lesson.trim().toLowerCase() === normalizedText)
303+
if (found) {
304+
// Re-recording refreshes recency AND moves the rule to the front, so it
305+
// re-enters the injection window; it never duplicates.
306+
found.timestamp = new Date().toISOString()
307+
stored = found
308+
await writeJsonAtomic(file, [found, ...existing.filter((e) => e !== found)].slice(0, 100))
309+
continue
322310
}
311+
await writeJsonAtomic(file, [entry, ...existing].slice(0, 100))
323312
} catch {}
324313
}
325314
})
326-
return entry
315+
return stored
327316
}
328317

329318
/**
330319
* The rules actually selected for injection, in the same order the prompt
331320
* builder uses. Shared so the listed `injected` flag cannot drift from reality.
332321
*/
333-
private async selectInjected(limit: number): Promise<SessionLearning[]> {
334-
if (this.sessionLearnings.length > 0) {
335-
return this.sessionLearnings.slice(0, limit)
336-
}
337-
// Read through the mutation queue: a read that starts while a forget is still
338-
// writing must not reload the store it is about to forget from.
339-
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[]
322+
private async selectInjected(limit: number, workspaceDir?: string): Promise<SessionLearning[]> {
323+
// Always read from disk, from the right stores for THIS workspace. One process
324+
// can serve several projects, so no cached list may be reused across them.
325+
return this.mutate(async () => {
326+
const read = async (file?: string): Promise<SessionLearning[]> => {
327+
if (!file) return []
328+
try {
329+
const parsed = JSON.parse(await fs.readFile(file, "utf8"))
330+
return Array.isArray(parsed) ? (parsed as SessionLearning[]) : []
331+
} catch {
332+
return []
333+
}
348334
}
335+
const paths = learningStorePaths(workspaceDir)
336+
// Project rules first: a committed, reviewed repo rule outranks an ad-hoc
337+
// global note (AIMETH-008 - shared repo facts win). One entry per rule text.
338+
const seen = new Set<string>()
339+
const merged: SessionLearning[] = []
340+
for (const rule of [...(await read(paths.project)), ...(await read(paths.global))]) {
341+
const key = learningKey(rule)
342+
if (seen.has(key)) continue
343+
seen.add(key)
344+
merged.push(rule)
345+
}
346+
return merged.slice(0, limit)
349347
})
350-
if (loaded.length > 0) {
351-
// Merge, never clobber: a rule recorded while the read was pending must not
352-
// be dropped from the cache by the older file contents.
353-
const seen = new Set(loaded.map(learningKey))
354-
this.sessionLearnings = [
355-
...this.sessionLearnings.filter((l) => !seen.has(learningKey(l))),
356-
...loaded,
357-
]
358-
}
359-
return this.sessionLearnings.slice(0, limit)
360348
}
361349

362-
public async getRecentLearnings(limit = 5): Promise<SessionLearning[]> {
363-
return this.selectInjected(limit)
350+
public async getRecentLearnings(limit = 5, workspaceDir?: string): Promise<SessionLearning[]> {
351+
return this.selectInjected(limit, workspaceDir)
364352
}
365353

366354
private mutation: Promise<unknown> = Promise.resolve()
@@ -373,37 +361,34 @@ class SessionObserverManager {
373361
}
374362

375363
/**
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`.
364+
* Every persisted rule, tagged with which store it lives in (`global` = whole
365+
* machine, `project` = this repo) and whether it is actually injected into a
366+
* session's system prompt. This is the honest answer to "what rules is the
367+
* agent using?" - a rule outside the injection window is shown as stored.
380368
*/
381369
public async listLearnings(
382370
workspaceDir?: string,
383-
): Promise<Array<SessionLearning & { origin: "central" | "workspace"; injected: boolean }>> {
384-
const read = async (file: string): Promise<SessionLearning[]> => {
371+
): Promise<Array<SessionLearning & { origin: "global" | "project"; injected: boolean }>> {
372+
const read = async (file?: string): Promise<SessionLearning[]> => {
373+
if (!file) return []
385374
try {
386375
const parsed = JSON.parse(await fs.readFile(file, "utf8"))
387376
return Array.isArray(parsed) ? (parsed as SessionLearning[]) : []
388377
} catch {
389378
return []
390379
}
391380
}
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()))
381+
const paths = learningStorePaths(workspaceDir)
382+
const global = await read(paths.global)
383+
const project = await read(paths.project)
384+
const globalKeys = new Set(global.map(learningKey))
400385
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 })),
386+
...global.map((l) => ({ ...l, origin: "global" as const })),
387+
...project
388+
.filter((l) => !globalKeys.has(learningKey(l)))
389+
.map((l) => ({ ...l, origin: "project" as const })),
405390
].sort((a, b) => (a.timestamp < b.timestamp ? 1 : -1))
406-
const injectedKeys = new Set((await this.selectInjected(INJECTED_LEARNINGS_LIMIT)).map(learningKey))
391+
const injectedKeys = new Set((await this.selectInjected(INJECTED_LEARNINGS_LIMIT, workspaceDir)).map(learningKey))
407392
return merged.map((l) => ({ ...l, injected: injectedKeys.has(learningKey(l)) }))
408393
}
409394

@@ -416,12 +401,8 @@ class SessionObserverManager {
416401
const needle = lessonText.trim().toLowerCase()
417402
if (!needle) return 0
418403
const matches = (l: SessionLearning) => String(l.lesson ?? "").toLowerCase().includes(needle)
419-
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))
404+
const paths = learningStorePaths(workspaceDir)
405+
const files = [paths.global, paths.project].filter((file): file is string => Boolean(file))
425406
const removed = new Set<string>()
426407
for (const file of files) {
427408
for (const key of await this.dropRules(file, matches)) removed.add(key)
@@ -469,6 +450,15 @@ class SessionObserverManager {
469450
/** How many of the most-recent rules are injected into a session system prompt. */
470451
export const INJECTED_LEARNINGS_LIMIT = 5
471452

453+
/** The two on-disk rule stores: global (whole machine) and this project. */
454+
export function learningStorePaths(workspaceDir?: string): { global?: string; project?: string } {
455+
const homeDir = process.env.USERPROFILE || process.env.HOME || ""
456+
return {
457+
global: homeDir ? path.join(homeDir, ".local", "share", "opencode", "learnings.json") : undefined,
458+
project: workspaceDir ? path.join(workspaceDir, ".system_generated", "logs", "learnings.json") : undefined,
459+
}
460+
}
461+
472462
const learningKey = (l: SessionLearning) => String(l.lesson ?? "").trim().toLowerCase()
473463

474464
/** 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
}),

0 commit comments

Comments
 (0)