feat(memory): mod skeleton with off switch and fail-open hooks
This commit is contained in:
1 parent
8e141feeb5
commit
f1d4f9de0a
5 files changed
+248
No files matched your search
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"name": "memory",
|
||||
"version": "0.1.0",
|
||||
"description": "Captures what fails in a session (failed Bash runs, commits, finished branches) and hands it to the memory registries, fail-open, with a per-machine off switch.",
|
||||
"author": {
|
||||
"name": "bchanot"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
{ "modules": ["./register.ts"] }
|
||||
@@ -0,0 +1,108 @@
|
||||
import { test, expect, mock } from 'claude-code/testing'
|
||||
import type { Engine } from 'claude-code/testing'
|
||||
import type { On } from 'claude-code'
|
||||
|
||||
const HOME = '/home/t'
|
||||
const SWITCH = `${HOME}/.claude/memory.json`
|
||||
const ROOT = '/work/app'
|
||||
const BASH_ANSWER = { result: { stdout: 'ok', stderr: '' } }
|
||||
|
||||
type World = {
|
||||
switchText: string | undefined // ~/.claude/memory.json (undefined: absent)
|
||||
rootFails: boolean // session.root rejects
|
||||
logs: string[] // every $.ui.log line
|
||||
sets: string[] // every store key written
|
||||
tools: string[] // every tool name registered
|
||||
}
|
||||
|
||||
/** The bottom hooks the mod reads, over a fake world. */
|
||||
async function boot(
|
||||
$: Engine,
|
||||
on: On,
|
||||
switchText?: string,
|
||||
rootFails = false,
|
||||
): Promise<World> {
|
||||
const w: World = { switchText, rootFails, logs: [], sets: [], tools: [] }
|
||||
mock.clock(on)
|
||||
// not mock.store: the test must see every key written
|
||||
const kv = new Map<string, unknown>()
|
||||
on('store.get', (_a, e) => ({ value: kv.get(e.key) }))
|
||||
on('store.keys', () => ({ value: [...kv.keys()] }))
|
||||
on('store.delete', (_a, e) => ({ value: void kv.delete(e.key) }))
|
||||
on('store.set', (_a, e) => {
|
||||
w.sets.push(e.key)
|
||||
kv.set(e.key, e.value)
|
||||
return { value: undefined }
|
||||
})
|
||||
on('tool.register', (_a, e) => {
|
||||
w.tools.push(e.name)
|
||||
return { value: undefined } as never
|
||||
})
|
||||
on('env.get', () => ({ value: HOME }))
|
||||
on('fs.stat', (_a, e) => {
|
||||
if (e.path !== SWITCH || w.switchText === undefined) {
|
||||
throw new Error('ENOENT')
|
||||
}
|
||||
return { value: {
|
||||
kind: 'file' as const, size: w.switchText.length, mtimeMs: 0,
|
||||
isLink: false,
|
||||
} }
|
||||
})
|
||||
on('fs.read', (_a, e) => {
|
||||
if (e.path !== SWITCH || w.switchText === undefined) {
|
||||
throw new Error('ENOENT')
|
||||
}
|
||||
return { value: w.switchText }
|
||||
})
|
||||
on('session.root', () => {
|
||||
if (w.rootFails) throw new Error('no root')
|
||||
return { value: ROOT }
|
||||
})
|
||||
on('session.id', () => ({ value: 's1' }))
|
||||
on('session.start', (_a, e) => ({ cwd: e.cwd }))
|
||||
on('ui.log', (_a, e) => {
|
||||
w.logs.push(String((e as { text?: unknown }).text))
|
||||
return { value: undefined } as never
|
||||
})
|
||||
on('tool.call', { tool: 'Bash' }, () => BASH_ANSWER as never)
|
||||
await $.session.start({ cwd: '/tmp', surface: null, isInteractive: false })
|
||||
return w
|
||||
}
|
||||
|
||||
const bash = ($: Engine, command: string) =>
|
||||
$.tool.call({ tool: 'Bash', command })
|
||||
|
||||
test('TOFF: enabled false passes a Bash answer through, store empty',
|
||||
async ($, on) => {
|
||||
const w = await boot($, on, '{"enabled": false}')
|
||||
const out = await bash($, 'make test')
|
||||
expect(out).toEqual(BASH_ANSWER)
|
||||
expect(w.sets).toEqual([])
|
||||
})
|
||||
|
||||
test('an absent switch file keeps the mod on', async ($, on) => {
|
||||
const w = await boot($, on)
|
||||
expect(await bash($, 'ls')).toEqual(BASH_ANSWER)
|
||||
expect(w.tools).toEqual(['memory_pending'])
|
||||
})
|
||||
|
||||
test('a malformed switch file keeps the mod on', async ($, on) => {
|
||||
const w = await boot($, on, '{nope')
|
||||
expect(await bash($, 'ls')).toEqual(BASH_ANSWER)
|
||||
expect(w.logs).toEqual([])
|
||||
expect(w.tools).toEqual(['memory_pending'])
|
||||
})
|
||||
|
||||
test('the tool is not registered when the switch is off', async ($, on) => {
|
||||
const w = await boot($, on, '{"enabled": false}')
|
||||
expect(w.tools).toEqual([])
|
||||
})
|
||||
|
||||
test('FAILOPEN: a rejecting session.root still returns the answer',
|
||||
async ($, on) => {
|
||||
const w = await boot($, on, undefined, true)
|
||||
expect(await bash($, 'ls')).toEqual(BASH_ANSWER)
|
||||
expect(await bash($, 'ls')).toEqual(BASH_ANSWER)
|
||||
const warns = w.logs.filter(l => l.startsWith('memory: Bash hook'))
|
||||
expect(warns).toHaveLength(1)
|
||||
})
|
||||
@@ -0,0 +1,130 @@
|
||||
// memory: captures what fails in a session and offers it to the memory
|
||||
// registries. This file is the frame: the off switch, the fail-open hooks
|
||||
// and the per-session state. Every hook reads the session id and root at
|
||||
// the point of use, never from a cache. A hook that fails passes the event
|
||||
// through unchanged: the mod may never break a tool call or a prompt.
|
||||
import type { EngineInterface, On, Register } from 'claude-code'
|
||||
|
||||
type Api = EngineInterface
|
||||
|
||||
type State = {
|
||||
enabled: boolean | null // null: not read yet this session
|
||||
warned: Set<string>
|
||||
pending: string[] // milestones not yet shown in a note
|
||||
writes: Promise<void> // the one chain every store write runs on
|
||||
}
|
||||
|
||||
const SWITCH_FILE = '.claude/memory.json'
|
||||
const MAX_SWITCH_BYTES = 65536
|
||||
const TOOL = 'memory_pending'
|
||||
|
||||
function newState(): State {
|
||||
return {
|
||||
enabled: null,
|
||||
warned: new Set(),
|
||||
pending: [],
|
||||
writes: Promise.resolve(),
|
||||
}
|
||||
}
|
||||
|
||||
/** Logs a hook's fail-open once per session; never throws itself. */
|
||||
function warnOnce(st: State, $: Api, hook: string, kind: string): void {
|
||||
if (st.warned.has(hook)) return
|
||||
st.warned.add(hook)
|
||||
try {
|
||||
$.ui.log(`memory: ${hook} hook failed (${kind}); passed through`)
|
||||
} catch {
|
||||
// a failing log must not break the fail-open itself
|
||||
}
|
||||
}
|
||||
|
||||
/** True unless the user's switch file says `enabled: false`. */
|
||||
async function loadEnabled($: Api): Promise<boolean> {
|
||||
try {
|
||||
const home = await $.env.get('HOME')
|
||||
if (!home) return true
|
||||
const path = `${home}/${SWITCH_FILE}`
|
||||
const info = await $.fs.stat(path)
|
||||
if (info.kind !== 'file' || info.size > MAX_SWITCH_BYTES) return true
|
||||
const data: unknown = JSON.parse(await $.fs.read(path))
|
||||
if (typeof data !== 'object' || data === null) return true
|
||||
return (data as { enabled?: unknown }).enabled !== false
|
||||
} catch {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
/** The tool the model calls to list the pending captures (body: later). */
|
||||
async function registerTool($: Api): Promise<void> {
|
||||
try {
|
||||
await $.tool.register({
|
||||
name: TOOL,
|
||||
description:
|
||||
'List the failures and milestones captured in this project and ' +
|
||||
'not yet written to the memory registries.',
|
||||
inputSchema: { type: 'object', additionalProperties: false },
|
||||
})
|
||||
} catch {
|
||||
$.ui.log('memory: tool not registered')
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the switch on the first event of a session and caches it; each
|
||||
* read of `enabled: true` registers the tool again (a name registered
|
||||
* twice is replaced).
|
||||
*/
|
||||
async function ensureEnabled($: Api, st: State): Promise<boolean> {
|
||||
if (st.enabled !== null) return st.enabled
|
||||
st.enabled = await loadEnabled($)
|
||||
if (st.enabled) await registerTool($)
|
||||
return st.enabled
|
||||
}
|
||||
|
||||
function registerSession(on: On, st: State): void {
|
||||
on('session.start', async ($, e, next) => {
|
||||
await ensureEnabled($, st)
|
||||
return next(e)
|
||||
}).catch(($, e, next) => {
|
||||
warnOnce(st, $, 'session.start', next.error.kind)
|
||||
return next(e)
|
||||
})
|
||||
on('session.end', async ($, e, next) => {
|
||||
st.enabled = null
|
||||
st.pending = []
|
||||
return next(e)
|
||||
}).catch(($, e, next) => {
|
||||
warnOnce(st, $, 'session.end', next.error.kind)
|
||||
return next(e)
|
||||
})
|
||||
}
|
||||
|
||||
function registerBash(on: On, st: State): void {
|
||||
on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
|
||||
if (!(await ensureEnabled($, st))) return next(e)
|
||||
// read before next: a failure here must not run the tool twice
|
||||
const root = await $.session.root()
|
||||
if (root === '') return next(e)
|
||||
return next(e) // capture comes with the store
|
||||
}).catch(($, e, next) => {
|
||||
warnOnce(st, $, 'Bash', next.error.kind)
|
||||
return next(e)
|
||||
})
|
||||
}
|
||||
|
||||
function registerPrompt(on: On, st: State): void {
|
||||
on('prompt.submit', async ($, e, next) => {
|
||||
await ensureEnabled($, st)
|
||||
return next(e)
|
||||
}).catch(($, e, next) => {
|
||||
warnOnce(st, $, 'prompt.submit', next.error.kind)
|
||||
return next(e)
|
||||
})
|
||||
}
|
||||
|
||||
export const register: Register = on => {
|
||||
const st = newState()
|
||||
registerSession(on, st)
|
||||
registerBash(on, st)
|
||||
registerPrompt(on, st)
|
||||
}
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
../mods/memory
|
||||
Reference in new issue
Block a user