feat(memory): status reader through memory.sh, entries with lessons
This commit is contained in:
1 parent
44e843685f
commit
38afa9325d
3 files changed
+388
-45
No files matched your search
@@ -693,5 +693,20 @@ cp "$FIX/v1h/.claude/memory/blockers.md" v1h.bak
|
||||
printf -- '---\nformat: 2\n---\n' > "$FIX/v1h/.claude/memory/blockers.md"
|
||||
check T13d-banner-flips-off "$(banner "$FIX/v1h")" 0
|
||||
cat v1h.bak > "$FIX/v1h/.claude/memory/blockers.md"
|
||||
# T18 the mod's entriesOf reads the same IDs as memory.sh index on this repo's
|
||||
# registries (parseIndex lists no EVAL row); FAILS when they are absent
|
||||
parity=$(R="$ROOT" OUT="$(bash "$MEM" -C "$ROOT" index 2>/dev/null)" \
|
||||
bun -e '
|
||||
import { readFileSync } from "node:fs"
|
||||
const { entriesOf, parseIndex } =
|
||||
await import(`${process.env.R}/mods/memory/hooks/register.ts`)
|
||||
const read = n => readFileSync(`${process.env.R}/.claude/memory/${n}.md`, "utf8")
|
||||
const a = new Set(["decisions", "learnings", "blockers"]
|
||||
.flatMap(n => entriesOf(read(n)).map(e => e.id)))
|
||||
const b = new Set(parseIndex(process.env.OUT ?? "").keys())
|
||||
const diff = [...a].filter(x => !b.has(x)).concat([...b].filter(x => !a.has(x)))
|
||||
console.log(a.size > 0 && diff.length === 0 ? "same" : `differ ${diff}`)
|
||||
' 2>&1)
|
||||
check T18-entriesOf-vs-index-ids "$parity" same
|
||||
echo "PASS=$pass FAIL=$fail"
|
||||
[ "$fail" -eq 0 ]
|
||||
@@ -3,7 +3,8 @@ import type { Engine, MockClock } from 'claude-code/testing'
|
||||
import type { On } from 'claude-code'
|
||||
import {
|
||||
cap, tail, redact, normalize, failureLine, sessionOf, addFailure,
|
||||
entriesOf, isSuperseded, grams, buildIndex, matchOf,
|
||||
entriesOf, parseIndex, isLive, lessonOf, assembleEntries, grams,
|
||||
buildIndex, matchOf,
|
||||
segments, suiteKeyOf, commitLabel, finishLabel,
|
||||
} from './register'
|
||||
|
||||
@@ -12,6 +13,19 @@ const SWITCH = `${HOME}/.claude/memory.json`
|
||||
const ROOT = '/work/app'
|
||||
const BASH_ANSWER = { result: { stdout: 'ok', stderr: '' } }
|
||||
|
||||
/** What `memory.sh index` prints for the fixture registries below. */
|
||||
const INDEX_OUT = [
|
||||
'.claude/memory/blockers.md', '',
|
||||
'| ID | Date | Title | Status |', '|---|---|---|---|',
|
||||
'| BLK-001 | 2026-01-01 | x | open |', '',
|
||||
'.claude/memory/learnings.md', '',
|
||||
'| ID | Date | Title | Status |', '|---|---|---|---|',
|
||||
'| LRN-002 | 2026-01-01 | y | superseded |', '',
|
||||
].join('\n')
|
||||
|
||||
/** How the process bottom answers: a stdout, or a way to fail. */
|
||||
type Proc = { stdout: string } | 'throw' | 'exit2' | 'hang'
|
||||
|
||||
type World = {
|
||||
switchText: string | undefined // ~/.claude/memory.json (undefined: absent)
|
||||
rootFails: boolean // session.root rejects
|
||||
@@ -28,6 +42,8 @@ type World = {
|
||||
unreadable: Set<string> // paths whose fs.read throws
|
||||
statFails: Set<string> // paths whose fs.stat throws though they exist
|
||||
existsFails: Set<string> // paths whose fs.exists throws
|
||||
proc: Proc // what `memory.sh index` does now
|
||||
runs: string[][] // every process.run argv
|
||||
gets: number // store.get calls
|
||||
getsFail: boolean // store.get throws
|
||||
}
|
||||
@@ -77,6 +93,7 @@ async function boot($: Engine, on: On, o: Opts = {}): Promise<World> {
|
||||
unreadable: new Set(o.unreadable ?? []),
|
||||
statFails: new Set(o.statFails ?? []),
|
||||
existsFails: new Set(o.existsFails ?? []),
|
||||
proc: { stdout: INDEX_OUT }, runs: [],
|
||||
gets: 0, getsFail: false,
|
||||
}
|
||||
handStore(on, w, o.storeFails ?? false)
|
||||
@@ -115,6 +132,15 @@ async function boot($: Engine, on: On, o: Opts = {}): Promise<World> {
|
||||
}
|
||||
return { value: w.switchText }
|
||||
})
|
||||
on('process.run', async (_a, e) => {
|
||||
w.runs.push([...e.argv])
|
||||
if (w.proc === 'throw') throw new Error('spawn failed')
|
||||
if (w.proc === 'hang') await new Promise(() => undefined)
|
||||
const done = w.proc === 'exit2'
|
||||
? { exitCode: 2, stdout: '' } : { exitCode: 0, stdout: w.proc.stdout }
|
||||
return { value: { ...done, stderr: '', isStdoutTruncated: false,
|
||||
isStderrTruncated: false } }
|
||||
})
|
||||
on('session.root', () => {
|
||||
if (w.rootFails) throw new Error('no root')
|
||||
return { value: w.root }
|
||||
@@ -580,6 +606,10 @@ const LEARNINGS = '## LRN-002 \u2014 y\n- **Status**: superseded\n' +
|
||||
const REGS = { [BLK]: BLOCKERS, [LRN]: LEARNINGS }
|
||||
const PENDING = 'mcp__memory__memory_pending'
|
||||
|
||||
/** The error index of one registry text, every entry live (no statuses). */
|
||||
const idxOf = (text: string) =>
|
||||
buildIndex(assembleEntries([text], new Map()), undefined)
|
||||
|
||||
const pending = async ($: Engine): Promise<string> =>
|
||||
String(((await $.tool.call({ tool: PENDING })) as { result: unknown })
|
||||
.result)
|
||||
@@ -652,7 +682,7 @@ test('IDX7: the answer holds no unredacted runtime-built token', async (
|
||||
test('IDX8: the error span is indexed, not the prose between', async () => {
|
||||
const body = '## BLK-009 \u2014 z\n`git rm` and later words ' +
|
||||
'`fatal: unable to access remote host`\n'
|
||||
const index = buildIndex([body])
|
||||
const index = idxOf(body)
|
||||
expect(matchOf(index, normalize('fatal: unable to access remote host')))
|
||||
.toBe('BLK-009')
|
||||
expect(matchOf(index, normalize('and later words fatal unable')))
|
||||
@@ -662,7 +692,7 @@ test('IDX8: the error span is indexed, not the prose between', async () => {
|
||||
test('a key of fewer than 4 words has no gram, so it is NEW', () => {
|
||||
expect(grams('a b c')).toEqual([])
|
||||
expect(grams('a b c d e')).toEqual(['a b c d', 'b c d e'])
|
||||
const index = buildIndex(['## BLK-001 x\n`aaa bbb ccc ddd`\n'])
|
||||
const index = idxOf('## BLK-001 x\n`aaa bbb ccc ddd`\n')
|
||||
expect(matchOf(index, 'aaa bbb ccc')).toBeUndefined()
|
||||
})
|
||||
|
||||
@@ -674,13 +704,13 @@ test('entriesOf slices between headings, heading line included', () => {
|
||||
])
|
||||
})
|
||||
|
||||
test('isSuperseded: the last status wins, else the heading tag', () => {
|
||||
expect(isSuperseded('## LRN-1 a\n- **Status**: open\n- **Statut**: ' +
|
||||
'superseded\n')).toBe(true)
|
||||
expect(isSuperseded('## LRN-1 a\n- **Status**: superseded\n' +
|
||||
'- **Status**: open\n')).toBe(false)
|
||||
expect(isSuperseded('## LRN-1 [superseded] a\nbody\n')).toBe(true)
|
||||
expect(isSuperseded('## LRN-1 [open] a\n')).toBe(false)
|
||||
test('isLive: superseded and deprecated are dead, an absent ID too', () => {
|
||||
const m = parseIndex(INDEX_OUT)
|
||||
expect(isLive(m, 'BLK-001')).toBe(true)
|
||||
expect(isLive(m, 'LRN-002')).toBe(false)
|
||||
expect(isLive(m, 'BLK-999')).toBe(false)
|
||||
expect(isLive(parseIndex('| BDR-001 | d | t | deprecated |\n'), 'BDR-001'))
|
||||
.toBe(false)
|
||||
})
|
||||
|
||||
test('a directory and an over-size file are skipped on the index line', async (
|
||||
@@ -816,7 +846,7 @@ test('TIME1: an index over 80000 newlines builds in under 500 ms', () => {
|
||||
const body = '## BLK-001 x\n' + '\n'.repeat(80000) + '- **Status**: open\n' +
|
||||
'\r\n'.repeat(40000) + '`fatal: unable to access remote`\n'
|
||||
const t0 = now()
|
||||
const index = buildIndex([body])
|
||||
const index = idxOf(body)
|
||||
expect(now() - t0).toBeLessThan(500)
|
||||
expect(index.size).toBe(2)
|
||||
})
|
||||
@@ -867,8 +897,8 @@ test('a registry of exactly 4 MiB is read, one byte more skipped', async (
|
||||
})
|
||||
|
||||
test('a span of 12 chars is indexed, one of 11 is not', () => {
|
||||
const at12 = buildIndex(['## BLK-001 x\n`aa bb cc ddd`\n'])
|
||||
const at11 = buildIndex(['## BLK-001 x\n`aa bb cc dd`\n'])
|
||||
const at12 = idxOf('## BLK-001 x\n`aa bb cc ddd`\n')
|
||||
const at11 = idxOf('## BLK-001 x\n`aa bb cc dd`\n')
|
||||
expect(at12.size).toBe(1)
|
||||
expect(at11.size).toBe(0)
|
||||
})
|
||||
@@ -888,6 +918,7 @@ test('a throwing exists probe names the registry, keeps the other', async (
|
||||
const files = { [BLK]: BLOCKERS, [LRN]: LEARNINGS.replace(
|
||||
'superseded', 'open') }
|
||||
const w = await boot($, on, { files, statFails: [BLK], existsFails: [BLK] })
|
||||
w.proc = { stdout: INDEX_OUT.replace('superseded', 'open') }
|
||||
await failing($, w, EXIT1 + 'error: pathspec did not match anything')
|
||||
const text = await pending($)
|
||||
expect(text).toContain(
|
||||
@@ -1296,7 +1327,7 @@ test('I2: credentials on the command line are redacted', () => {
|
||||
|
||||
test('IDX9: a placeholder-only gram is not indexed nor matched', () => {
|
||||
const span = '`connect 10.0.0.1:5432 refused 12 34`'
|
||||
const index = buildIndex(['## LRN-074 x\n' + span + '\n'])
|
||||
const index = idxOf('## LRN-074 x\n' + span + '\n')
|
||||
const key = normalize('Error at 2026-11-04 12:00:00.123 timeout')
|
||||
expect(matchOf(index, key)).toBeUndefined()
|
||||
expect(grams('# # # # x')).toEqual(['# # # x'])
|
||||
@@ -1450,7 +1481,7 @@ test('TIME1: each 6-bis rule stays fast on 64 KiB adversarial input', () => {
|
||||
test('the registry index caps a 1 MiB span before normalize', () => {
|
||||
const body = '## BLK-001 x\n`' + 'fatal word '.repeat(95326) + '`\n'
|
||||
const t0 = now()
|
||||
const index = buildIndex([body])
|
||||
const index = idxOf(body)
|
||||
expect(now() - t0).toBeLessThan(50)
|
||||
expect(index.size).toBeGreaterThan(0)
|
||||
})
|
||||
@@ -1566,3 +1597,159 @@ test('TIME1: curl prefix shapes stay fast on 64 KiB', () => {
|
||||
expect(now() - t0).toBeLessThan(30)
|
||||
}
|
||||
})
|
||||
|
||||
// ---- Task 1 (phase 4c): statuses from memory.sh, entries with lessons ----
|
||||
|
||||
const SR_LINE = 'fatal: unable to access remote host'
|
||||
|
||||
test('SR1: parseIndex reads ID, lowercased status word and title', () => {
|
||||
const out = [
|
||||
'.claude/memory/decisions.md', '',
|
||||
'| ID | Date | Title | Status |', '|---|---|---|---|',
|
||||
'| BDR-031 | 2026-06-25 | t | superseded |',
|
||||
'| LRN-001 | 2026-01-01 | a | b | Open (2026) |',
|
||||
'| LRN-003 | 2026-01-01 | t | |',
|
||||
].join('\n')
|
||||
expect([...parseIndex(out)]).toEqual([
|
||||
['BDR-031', { status: 'superseded', title: 't' }],
|
||||
['LRN-001', { status: 'open', title: 'a | b' }],
|
||||
['LRN-003', { status: '', title: 't' }],
|
||||
])
|
||||
})
|
||||
|
||||
test('SR2: a superseded entry is not indexed, a live one is known', async (
|
||||
$, on,
|
||||
) => {
|
||||
const w = await boot($, on, { files: REGS })
|
||||
w.proc = { stdout: INDEX_OUT.replace('| open |', '| superseded |') }
|
||||
await failing($, w, EXIT1 + SR_LINE)
|
||||
expect(await pending($)).toContain('- NEW ×1 ' + SR_LINE)
|
||||
w.proc = { stdout: INDEX_OUT.replace('| superseded |', '| open |') }
|
||||
await failing($, w, EXIT1 + 'error: pathspec did not match anything')
|
||||
expect(await pending($)).toContain('- known LRN-002 ×1 error: path')
|
||||
})
|
||||
|
||||
test('SR2b: the process is run once, with the memory.sh argv', async (
|
||||
$, on,
|
||||
) => {
|
||||
const w = await boot($, on, { files: REGS })
|
||||
await pending($)
|
||||
expect(w.runs).toEqual([
|
||||
['bash', '/home/t/.claude/lib/memory.sh', '-C', '/work/app', 'index'],
|
||||
])
|
||||
})
|
||||
|
||||
for (const [name, proc] of [
|
||||
['SR3: process.run throws', 'throw'],
|
||||
['SR4: exit code 2', 'exit2'],
|
||||
['SR6: an empty stdout', { stdout: '' }],
|
||||
] as const) {
|
||||
test(`${name}: advisory known, status reader unavailable`, async (
|
||||
$, on,
|
||||
) => {
|
||||
const w = await boot($, on, { files: REGS })
|
||||
w.proc = proc
|
||||
await failing($, w, EXIT1 + SR_LINE)
|
||||
const text = await pending($)
|
||||
expect(text).toContain(
|
||||
'index: read blockers.md, learnings.md; status reader unavailable')
|
||||
expect(text).toContain('- known BLK-001 ×1 ' + SR_LINE)
|
||||
})
|
||||
}
|
||||
|
||||
test('SR5: process.run never settles, the answer comes at 2500 ms', async (
|
||||
$, on,
|
||||
) => {
|
||||
const w = await boot($, on, { files: REGS })
|
||||
await failing($, w, EXIT1 + SR_LINE)
|
||||
w.proc = 'hang'
|
||||
const answer = pending($)
|
||||
await new Promise(r => setTimeout(r, 20)) // let the call reach its wait
|
||||
await w.clock.advance(2500)
|
||||
const text = await answer
|
||||
expect(text).toContain('read blockers.md, learnings.md; status reader unav')
|
||||
expect(text).toContain('- known BLK-001 ×1 ' + SR_LINE)
|
||||
})
|
||||
|
||||
test('SR7: no registry read, no process run, no unavailable note', async (
|
||||
$, on,
|
||||
) => {
|
||||
const w = await boot($, on)
|
||||
await failing($, w, EXIT1 + SR_LINE)
|
||||
const text = await pending($)
|
||||
expect(w.runs).toEqual([])
|
||||
expect(text).not.toContain('status reader')
|
||||
})
|
||||
|
||||
test('LS1: a BDR Decision reads its first sentence', () => {
|
||||
expect(lessonOf('BDR', '## BDR-1 t\n- **Decision**: Use X. Then Y.\n'))
|
||||
.toBe('Use X.')
|
||||
})
|
||||
|
||||
test('LS2: an LRN takes Apply before Pattern', () => {
|
||||
const body = '## LRN-1 t\n- **Pattern**: p one\n- **Apply**: do it now\n'
|
||||
expect(lessonOf('LRN', body)).toBe('do it now')
|
||||
expect(lessonOf('LRN', '## LRN-1 t\n- **Pattern**: p one\n'))
|
||||
.toBe('p one')
|
||||
})
|
||||
|
||||
test('LS3: a BLK plain label, Solution before Real cause', () => {
|
||||
expect(lessonOf('BLK', '## BLK-1 t\n- Real cause: c\n- Solution: fix z\n'))
|
||||
.toBe('fix z')
|
||||
expect(lessonOf('BLK', '## BLK-1 t\n- **Real cause**: only c\n'))
|
||||
.toBe('only c')
|
||||
expect(lessonOf('BLK', '## BLK-1 t\n- **Friction**: f\n')).toBe('')
|
||||
})
|
||||
|
||||
test('LS4: a 2000-char field is cut at 280 ending with an ellipsis', () => {
|
||||
const text = lessonOf('BDR', '## BDR-1 t\n- **Decision**: ' +
|
||||
'a'.repeat(2000) + '\n')
|
||||
expect(text).toHaveLength(280)
|
||||
expect(text.endsWith('a…')).toBe(true)
|
||||
})
|
||||
|
||||
test('LS5: a 2001-char Decision still yields a lesson cut at 280', () => {
|
||||
const text = lessonOf('BDR', '## BDR-1 t\n- **Decision**: ' +
|
||||
'b'.repeat(2001) + '\nnext line\n')
|
||||
expect(text).toHaveLength(280)
|
||||
expect(text.endsWith('…')).toBe(true)
|
||||
})
|
||||
|
||||
test('LS6: `; ` ends the sentence before a capital only', () => {
|
||||
expect(lessonOf('BDR', '- Decision: a; Then b')).toBe('a;')
|
||||
expect(lessonOf('BDR', '- Decision: a; then b. c')).toBe('a; then b. c')
|
||||
})
|
||||
|
||||
test('EN1: a heading of 320 chars is still an entry; ## Notes is not', () => {
|
||||
const text = '## BDR-007 — ' + 'T'.repeat(320) + '\nbody\n## Notes\nx\n'
|
||||
const parts = entriesOf(text)
|
||||
expect(parts.map(p => p.id)).toEqual(['BDR-007'])
|
||||
expect(parts[0]?.body).toBe(text) // the 4b rule: up to the next entry
|
||||
})
|
||||
|
||||
test('assembleEntries joins kind, memory.sh title, lesson and body', () => {
|
||||
const body = '## LRN-009 — t [open] (2026-01-02)\n- **Apply**: do z. Ok\n'
|
||||
const long = 'W'.repeat(150)
|
||||
const index = parseIndex(
|
||||
`| LRN-009 | 2026-01-02 | ${long} | open |\n`)
|
||||
const [e] = assembleEntries([body], index)
|
||||
expect(e).toEqual({
|
||||
id: 'LRN-009', kind: 'LRN', title: 'W'.repeat(99) + '…',
|
||||
lesson: 'do z.', body,
|
||||
})
|
||||
expect(assembleEntries([body], new Map())[0]?.title).toBe('')
|
||||
})
|
||||
|
||||
test('TIMEentries: entriesOf and lessonOf on 64 KiB fields, under 50 ms', () => {
|
||||
const bodies = [
|
||||
'## BLK-001 x\n- Solution: ' + 'a'.repeat(65536 - 26),
|
||||
'## BLK-001 x\n- Solution: ' + 'a. '.repeat(21000),
|
||||
'## BLK-001 x\n' + ' '.repeat(65536) + '- Solution: y',
|
||||
'## BLK-001 x\n' + '- '.repeat(32768),
|
||||
]
|
||||
for (const text of bodies) {
|
||||
const t0 = now()
|
||||
for (const part of entriesOf(text)) lessonOf('BLK', part.body)
|
||||
expect(now() - t0).toBeLessThan(50)
|
||||
}
|
||||
})
|
||||
+171
-30
@@ -383,17 +383,40 @@ async function sweepStore($: Api, curKey: string, id: string): Promise<void> {
|
||||
}
|
||||
|
||||
// The registry error index: which captured failures a registry knows.
|
||||
const REGISTRIES = ['blockers.md', 'learnings.md']
|
||||
const MAX_REGISTRY = 4194304
|
||||
const MIN_SPAN = 12
|
||||
const GRAM_WORDS = 4
|
||||
const HEADING = /^## ((?:BLK|LRN)-\d+)\b.*$/gm
|
||||
// the ID only: a bounded capture carries no `$`, so a long heading stays one
|
||||
const HEADING = /^## ((?:BDR|LRN|BLK)-\d+)\b/gm
|
||||
const SPAN = /`([^`\n]+)`/g
|
||||
// [ \t] not \s: a multiline regex must not cross newlines (quadratic).
|
||||
const STATUS =
|
||||
/^[ \t]*-[ \t]*\*\*Stat(?:us|ut)[^*\n]*\*\*[ \t]*:?[ \t]*([A-Za-z-]+)/gim
|
||||
const STATUS_WAIT_MS = 2500 // our own race over the process's 2000 ms
|
||||
const STATUS_TIMEOUT_MS = 2000
|
||||
const MAX_INDEX_ROW = 1000
|
||||
const DEAD = new Set(['superseded', 'deprecated'])
|
||||
const INDEX_ROW = new RegExp(
|
||||
'^\\|[ \\t]{0,5}((?:BDR|LRN|BLK)-\\d+)[ \\t]{0,5}\\|[^|]{0,40}\\|' +
|
||||
'(.{0,900})\\|([^|]{0,100})\\|[ \\t]{0,5}$',
|
||||
)
|
||||
const MAX_TITLE = 100
|
||||
const MAX_LESSON = 280
|
||||
const MAX_FIELD = 2000
|
||||
const LESSON_LABELS: Record<Kind, string[]> = {
|
||||
BDR: ['Decision'],
|
||||
LRN: ['Apply', 'Future application', 'Pattern'],
|
||||
BLK: ['Solution', 'Real cause'],
|
||||
}
|
||||
|
||||
type Entry = { id: string; body: string }
|
||||
export type Kind = 'BDR' | 'LRN' | 'BLK'
|
||||
export type Entry = {
|
||||
id: string
|
||||
kind: Kind
|
||||
title: string
|
||||
lesson: string
|
||||
body: string
|
||||
}
|
||||
type Part = { id: string; body: string }
|
||||
type Listed = { status: string; title: string }
|
||||
export type StatusMap = Map<string, Listed>
|
||||
|
||||
type Read = { text: string } | { why: string }
|
||||
|
||||
@@ -423,8 +446,8 @@ async function tryRead($: Api, path: string): Promise<Read> {
|
||||
}
|
||||
}
|
||||
|
||||
/** The BLK/LRN entries; a body runs from its heading to the next one. */
|
||||
export function entriesOf(text: string): Entry[] {
|
||||
/** The entries' ID and body; a body runs from its heading to the next. */
|
||||
export function entriesOf(text: string): Part[] {
|
||||
const heads = [...text.matchAll(HEADING)]
|
||||
return heads.map((m, i) => ({
|
||||
id: m[1] ?? '',
|
||||
@@ -432,14 +455,63 @@ export function entriesOf(text: string): Entry[] {
|
||||
}))
|
||||
}
|
||||
|
||||
// shortcut: a lexical reader, not memory.sh's shared parser (that lives in
|
||||
// shell); upgrade = call the parser once the engine exposes a CLI run in
|
||||
// hooks.
|
||||
/** The last labelled status reads superseded; else the heading `[tag]`. */
|
||||
export function isSuperseded(body: string): boolean {
|
||||
const last = [...body.matchAll(STATUS)].pop()
|
||||
if (last !== undefined) return (last[1] ?? '').toLowerCase() === 'superseded'
|
||||
return /\[superseded\]/i.test(body.split('\n', 1)[0] ?? '')
|
||||
/**
|
||||
* ID -> status word and title, from the rows `memory.sh index` prints
|
||||
* (`| ID | Date | Title | Status |`); the status is its lowercased first
|
||||
* word, `''` when empty.
|
||||
*/
|
||||
export function parseIndex(stdout: string): StatusMap {
|
||||
const rows: StatusMap = new Map()
|
||||
for (const line of stdout.split('\n')) {
|
||||
const m = INDEX_ROW.exec(line.slice(0, MAX_INDEX_ROW))
|
||||
if (m === null) continue
|
||||
const word = (m[3] ?? '').trim().match(/^[A-Za-z-]+/)?.[0] ?? ''
|
||||
const title = (m[2] ?? '').trim()
|
||||
rows.set(m[1] ?? '', { status: word.toLowerCase(), title })
|
||||
}
|
||||
return rows
|
||||
}
|
||||
|
||||
/** False when the ID is superseded or deprecated, or the map lacks it. */
|
||||
export function isLive(status: StatusMap, id: string): boolean {
|
||||
const row = status.get(id)
|
||||
return row !== undefined && !DEAD.has(row.status)
|
||||
}
|
||||
|
||||
/** `text` cut to `n` characters, the last one `…` when it was cut. */
|
||||
function clip(text: string, n: number): string {
|
||||
return text.length > n ? `${text.slice(0, n - 1)}…` : text
|
||||
}
|
||||
|
||||
/** The first sentence: up to `. ` or `; ` before a capital, or the end. */
|
||||
function firstSentence(field: string): string {
|
||||
return /^(.*?[.;])(?:[ \t]+(?=[A-Z])|$)/.exec(field)?.[1] ?? field
|
||||
}
|
||||
|
||||
/**
|
||||
* The one-line lesson of an entry: the first sentence of its first labelled
|
||||
* field, in the order of its kind; `''` when none is there.
|
||||
*/
|
||||
export function lessonOf(kind: Kind, body: string): string {
|
||||
for (const label of LESSON_LABELS[kind]) {
|
||||
const line = new RegExp(
|
||||
`^[ \\t]*-[ \\t]*(?:\\*\\*)?${label}(?:\\*\\*)?[ \\t]*:[ \\t]*` +
|
||||
`(.{0,${MAX_FIELD}})`,
|
||||
'im',
|
||||
).exec(body)
|
||||
const field = (line?.[1] ?? '').trim()
|
||||
if (line !== null) return clip(firstSentence(field), MAX_LESSON)
|
||||
}
|
||||
return ''
|
||||
}
|
||||
|
||||
/** The entries of registry texts, titled by `memory.sh index`'s rows. */
|
||||
export function assembleEntries(texts: string[], index: StatusMap): Entry[] {
|
||||
return texts.flatMap(entriesOf).map(({ id, body }) => {
|
||||
const kind = id.slice(0, 3) as Kind
|
||||
const title = clip(index.get(id)?.title ?? '', MAX_TITLE)
|
||||
return { id, kind, title, lesson: lessonOf(kind, body), body }
|
||||
})
|
||||
}
|
||||
|
||||
const PLACEHOLDERS = new Set(['#', '<path>', '<hex>'])
|
||||
@@ -465,7 +537,6 @@ function spansOf(body: string): string[] {
|
||||
}
|
||||
|
||||
function indexEntry(index: Map<string, string>, entry: Entry): void {
|
||||
if (isSuperseded(entry.body)) return
|
||||
for (const span of spansOf(entry.body)) {
|
||||
for (const gram of grams(normalize(span))) {
|
||||
if (!index.has(gram)) index.set(gram, entry.id)
|
||||
@@ -473,11 +544,19 @@ function indexEntry(index: Map<string, string>, entry: Entry): void {
|
||||
}
|
||||
}
|
||||
|
||||
/** gram -> first ID, over the backticked spans of live entries. */
|
||||
export function buildIndex(texts: string[]): Map<string, string> {
|
||||
/**
|
||||
* gram -> first ID, over the backticked spans of live entries. Without
|
||||
* statuses (`undefined`) every entry is indexed: advisory, never injected.
|
||||
*/
|
||||
export function buildIndex(
|
||||
entries: Entry[],
|
||||
status: StatusMap | undefined,
|
||||
): Map<string, string> {
|
||||
const index = new Map<string, string>()
|
||||
for (const text of texts) {
|
||||
for (const entry of entriesOf(text)) indexEntry(index, entry)
|
||||
for (const entry of entries) {
|
||||
if (status === undefined || isLive(status, entry.id)) {
|
||||
indexEntry(index, entry)
|
||||
}
|
||||
}
|
||||
return index
|
||||
}
|
||||
@@ -494,15 +573,54 @@ export function matchOf(
|
||||
return undefined
|
||||
}
|
||||
|
||||
type Registries = { index: Map<string, string>; note: string }
|
||||
/** The stdout of `argv` on exit 0; `undefined` on any other end or 2.5 s. */
|
||||
async function runWithin($: Api, argv: string[]): Promise<string | undefined> {
|
||||
const stop = new AbortController()
|
||||
const timer = $.clock.sleep(STATUS_WAIT_MS, { signal: stop.signal })
|
||||
.then(() => undefined, () => undefined)
|
||||
const run = $.process.run(argv, { timeoutMs: STATUS_TIMEOUT_MS })
|
||||
.then(r => (r.exitCode === 0 ? r.stdout : undefined), () => undefined)
|
||||
try {
|
||||
return await Promise.race([run, timer])
|
||||
} finally {
|
||||
stop.abort()
|
||||
}
|
||||
}
|
||||
|
||||
async function loadIndex($: Api, root: string): Promise<Registries> {
|
||||
/** The statuses `memory.sh index` prints; `undefined` when unavailable. */
|
||||
async function statusMap($: Api, root: string): Promise<StatusMap | undefined> {
|
||||
try {
|
||||
const home = await $.env.get('HOME')
|
||||
if (!home) return undefined
|
||||
const out = await runWithin(
|
||||
$, ['bash', `${home}/.claude/lib/memory.sh`, '-C', root, 'index'])
|
||||
const rows = out === undefined ? undefined : parseIndex(out)
|
||||
return rows?.size ? rows : undefined
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
type Registries = {
|
||||
entries: Entry[]
|
||||
status: StatusMap | undefined
|
||||
index: Map<string, string>
|
||||
note: string
|
||||
}
|
||||
|
||||
type Loaded = { texts: string[]; note: string }
|
||||
|
||||
/** The texts of the named registries and the first part of the note. */
|
||||
async function readRegistries(
|
||||
$: Api,
|
||||
root: string,
|
||||
names: string[],
|
||||
): Promise<Loaded> {
|
||||
const texts: string[] = []
|
||||
const read: string[] = []
|
||||
const skipped: string[] = []
|
||||
for (const name of REGISTRIES) {
|
||||
const path = `${root}/.claude/memory/${name}`
|
||||
const r = await tryRead($, path)
|
||||
for (const name of names) {
|
||||
const r = await tryRead($, `${root}/.claude/memory/${name}`)
|
||||
if ('why' in r) {
|
||||
skipped.push(`${name} (${r.why})`)
|
||||
continue
|
||||
@@ -514,9 +632,31 @@ async function loadIndex($: Api, root: string): Promise<Registries> {
|
||||
read.length > 0 ? `read ${read.join(', ')}` : '',
|
||||
skipped.length > 0 ? `skipped ${skipped.join(', ')}` : '',
|
||||
]
|
||||
return { texts, note: `index: ${parts.filter(Boolean).join('; ')}` }
|
||||
}
|
||||
|
||||
const FAILURE_FILES = ['blockers.md', 'learnings.md']
|
||||
const FAILURE_KINDS = new Set<Kind>(['BLK', 'LRN'])
|
||||
|
||||
/**
|
||||
* The entries of the named registries with their statuses, and the error
|
||||
* index over the BLK and LRN ones. No registry read: no process run.
|
||||
*/
|
||||
async function loadRegistries(
|
||||
$: Api,
|
||||
root: string,
|
||||
names: string[],
|
||||
): Promise<Registries> {
|
||||
const { texts, note } = await readRegistries($, root, names)
|
||||
const status = texts.length > 0 ? await statusMap($, root) : undefined
|
||||
const entries = assembleEntries(texts, status ?? new Map())
|
||||
const failing = entries.filter(e => FAILURE_KINDS.has(e.kind))
|
||||
const lost = texts.length > 0 && status === undefined
|
||||
return {
|
||||
index: buildIndex(texts),
|
||||
note: `index: ${parts.filter(Boolean).join('; ')}`,
|
||||
entries,
|
||||
status,
|
||||
index: buildIndex(failing, status),
|
||||
note: lost ? `${note}; status reader unavailable` : note,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -797,7 +937,8 @@ async function pendingAnswer($: Api, st: State): Promise<string> {
|
||||
const id = await $.session.id()
|
||||
await st.writes
|
||||
const project = await loadProject($, root)
|
||||
return formatPending(root, project, id, await loadIndex($, root))
|
||||
const rx = await loadRegistries($, root, FAILURE_FILES)
|
||||
return formatPending(root, project, id, rx)
|
||||
}
|
||||
|
||||
function registerPending(on: On, st: State): void {
|
||||
@@ -960,7 +1101,7 @@ function registerBash(on: On, st: State): void {
|
||||
async function newFailureCount($: Api, st: State, at: Where): Promise<number> {
|
||||
await st.writes
|
||||
const p = await loadProject($, at.root)
|
||||
const { index } = await loadIndex($, at.root)
|
||||
const { index } = await loadRegistries($, at.root, FAILURE_FILES)
|
||||
const cur = p.sessions.find(s => s.id === at.id)
|
||||
return (cur?.failures ?? []).filter(isFailure)
|
||||
.filter(f => matchOf(index, f.key) === undefined).length
|
||||
|
||||
Reference in new issue
Block a user