toon-memory 2.5.2 → 2.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/lib/git.ts ADDED
@@ -0,0 +1,263 @@
1
+ /**
2
+ * Git reading without shell — reads .git/ filesystem directly.
3
+ *
4
+ * Zero child_process usage. Parses binary git index, commit objects,
5
+ * and .gitignore for status summaries. All deterministic, no network.
6
+ */
7
+
8
+ import { existsSync, readFileSync, readdirSync, statSync } from "fs"
9
+ import { join } from "path"
10
+ import { inflateSync } from "zlib"
11
+ import { currentBranch } from "./sessions"
12
+
13
+ function gitDir(cwd?: string): string | null {
14
+ const dotgit = join(cwd || process.cwd(), ".git")
15
+ if (!existsSync(dotgit)) return null
16
+ if (statSync(dotgit).isDirectory()) return dotgit
17
+ // Worktree: .git is a file pointing to the real dir
18
+ const pointer = readFileSync(dotgit, "utf-8").trim()
19
+ if (pointer.startsWith("gitdir:")) {
20
+ const target = pointer.slice(7).trim()
21
+ return target.startsWith("/") ? target : join(process.cwd(), target)
22
+ }
23
+ return null
24
+ }
25
+
26
+ function resolveHead(cwd?: string): string | null {
27
+ const dir = gitDir(cwd)
28
+ if (!dir) return null
29
+ const headPath = join(dir, "HEAD")
30
+ if (!existsSync(headPath)) return null
31
+ const head = readFileSync(headPath, "utf-8").trim()
32
+ if (head.startsWith("ref:")) {
33
+ const refPath = join(dir, head.slice(4).trim())
34
+ if (!existsSync(refPath)) return null
35
+ return readFileSync(refPath, "utf-8").trim()
36
+ }
37
+ // Detached HEAD
38
+ return head || null
39
+ }
40
+
41
+ // ── Git index parsing ────────────────────────────────────────────────
42
+
43
+ interface IndexEntry {
44
+ mtimeSec: number
45
+ mtimeNsec: number
46
+ dev: number
47
+ ino: number
48
+ mode: number
49
+ uid: number
50
+ gid: number
51
+ size: number
52
+ sha: string
53
+ flags: number
54
+ name: string
55
+ }
56
+
57
+ /**
58
+ * Parse the binary .git/index file.
59
+ * Format: 12-byte header + N * (variable) entries.
60
+ * Each entry: 40 bytes fixed + 2 bytes flags + variable name (null-padded to 8).
61
+ */
62
+ function parseIndex(dir: string): IndexEntry[] {
63
+ const indexPath = join(dir, "index")
64
+ if (!existsSync(indexPath)) return []
65
+
66
+ const buf = readFileSync(indexPath)
67
+ if (buf.length < 12) return []
68
+
69
+ const sig = buf.toString("ascii", 0, 4)
70
+ if (sig !== "DIRC") return []
71
+
72
+ const version = buf.readUInt32BE(4)
73
+ const count = buf.readUInt32BE(8)
74
+ if (version < 2 || version > 4) return []
75
+
76
+ const entries: IndexEntry[] = []
77
+ let offset = 12
78
+
79
+ for (let i = 0; i < count && offset + 62 <= buf.length; i++) {
80
+ const entryStart = offset
81
+ const mtimeSec = buf.readUInt32BE(offset)
82
+ const mtimeNsec = buf.readUInt32BE(offset + 4)
83
+ const dev = buf.readUInt32BE(offset + 8)
84
+ const ino = buf.readUInt32BE(offset + 12)
85
+ const mode = buf.readUInt32BE(offset + 16)
86
+ const uid = buf.readUInt32BE(offset + 20)
87
+ const gid = buf.readUInt32BE(offset + 24)
88
+ const size = buf.readUInt32BE(offset + 28)
89
+ const sha = buf.slice(offset + 32, offset + 52).toString("hex")
90
+ const flags = buf.readUInt16BE(offset + 52)
91
+
92
+ // Name starts at offset 62, null-terminated, padded to 8-byte alignment
93
+ const nameLen = flags & 0x0fff
94
+ const nameStart = entryStart + 62
95
+ let name: string
96
+ if (nameLen > 0 && nameStart + nameLen <= buf.length) {
97
+ name = buf.toString("utf-8", nameStart, nameStart + nameLen)
98
+ } else {
99
+ // Read until null byte
100
+ const end = buf.indexOf(0, nameStart)
101
+ name = end >= 0 ? buf.toString("utf-8", nameStart, end) : buf.toString("utf-8", nameStart)
102
+ }
103
+
104
+ // Skip extended data (v3+): 4 extra bytes of padding before the name
105
+ if (version >= 3) {
106
+ // In v3, there's an extra 4-byte field (padding/extended)
107
+ // The name starts at entryStart + 62 regardless in v2-v4
108
+ }
109
+
110
+ // Compute total entry size: 62 bytes + name length, padded to 8-byte boundary
111
+ const rawLen = 62 + name.length
112
+ const paddedLen = Math.ceil(rawLen / 8) * 8
113
+ offset = entryStart + paddedLen
114
+
115
+ entries.push({ mtimeSec, mtimeNsec, dev, ino, mode, uid, gid, size, sha, flags, name })
116
+ }
117
+
118
+ return entries
119
+ }
120
+
121
+ /**
122
+ * Parse .gitignore patterns into a set of ignored paths.
123
+ * Simplified: handles exact filenames and directory names.
124
+ */
125
+ function parseGitignore(dir: string): Set<string> {
126
+ const ignored = new Set<string>()
127
+ const gitignorePath = join(dir, "..", ".gitignore")
128
+ if (!existsSync(gitignorePath)) return ignored
129
+
130
+ const lines = readFileSync(gitignorePath, "utf-8").split("\n")
131
+ for (const raw of lines) {
132
+ const line = raw.trim()
133
+ if (!line || line.startsWith("#")) continue
134
+ // Strip leading slash (root-only pattern)
135
+ const pattern = line.replace(/^\//, "")
136
+ // Simple: just track the pattern as-is
137
+ if (pattern) ignored.add(pattern)
138
+ }
139
+ return ignored
140
+ }
141
+
142
+ /**
143
+ * Read the git index and return the list of tracked file paths.
144
+ * These are the files git knows about (staged or tracked).
145
+ * @param cwd Working directory (default: process.cwd())
146
+ */
147
+ export function readGitIndex(cwd?: string): string[] {
148
+ const dir = gitDir(cwd)
149
+ if (!dir) return []
150
+ return parseIndex(dir).map((e) => e.name)
151
+ }
152
+
153
+ /**
154
+ * Parse a raw git object (decompressed with zlib).
155
+ * Returns the object type and content.
156
+ */
157
+ function readObject(sha: string, cwd?: string): { type: string; content: string } | null {
158
+ const dir = gitDir(cwd)
159
+ if (!dir) return null
160
+ const objPath = join(dir, "objects", sha.slice(0, 2), sha.slice(2))
161
+ if (!existsSync(objPath)) return null
162
+
163
+ try {
164
+ const compressed = readFileSync(objPath)
165
+ const decompressed = inflateSync(compressed)
166
+ const str = decompressed.toString("utf-8")
167
+ const nullIdx = str.indexOf("\0")
168
+ if (nullIdx < 0) return null
169
+ const header = str.slice(0, nullIdx)
170
+ const type = header.split(" ")[0]
171
+ const content = str.slice(nullIdx + 1)
172
+ return { type, content }
173
+ } catch {
174
+ return null
175
+ }
176
+ }
177
+
178
+ export interface GitCommit {
179
+ hash: string
180
+ shortHash: string
181
+ subject: string
182
+ author: string
183
+ date: string
184
+ }
185
+
186
+ /**
187
+ * Read the n most recent commits by walking the commit chain from HEAD.
188
+ * @param cwd Working directory (default: process.cwd())
189
+ */
190
+ export function readRecentCommits(count: number = 10, cwd?: string): GitCommit[] {
191
+ const sha = resolveHead(cwd)
192
+ if (!sha) return []
193
+
194
+ const commits: GitCommit[] = []
195
+ const visited = new Set<string>()
196
+ let current = sha
197
+
198
+ while (commits.length < count && current && !visited.has(current)) {
199
+ visited.add(current)
200
+ const obj = readObject(current, cwd)
201
+ if (!obj || obj.type !== "commit") break
202
+
203
+ const lines = obj.content.split("\n")
204
+ let subject = ""
205
+ let author = ""
206
+ let date = ""
207
+ let parent: string | null = null
208
+ let pastHeaders = false
209
+
210
+ for (const line of lines) {
211
+ if (line.startsWith("author ")) {
212
+ const match = line.match(/^author\s+(.+?)\s+<[^>]+>\s+(\d+)/)
213
+ if (match) {
214
+ author = match[1]
215
+ const ts = parseInt(match[2])
216
+ date = new Date(ts * 1000).toISOString().split("T")[0]
217
+ }
218
+ } else if (line.startsWith("parent ")) {
219
+ parent = line.slice(7).trim()
220
+ } else if (line.startsWith("tree ")) {
221
+ // skip
222
+ } else if (line.startsWith("committer ")) {
223
+ pastHeaders = true
224
+ } else if (pastHeaders && !subject && line.trim()) {
225
+ subject = line.trim()
226
+ }
227
+ }
228
+
229
+ commits.push({
230
+ hash: current,
231
+ shortHash: current.slice(0, 7),
232
+ subject,
233
+ author,
234
+ date,
235
+ })
236
+
237
+ current = parent || ""
238
+ }
239
+
240
+ return commits
241
+ }
242
+
243
+ /**
244
+ * Get a summary of the current git status.
245
+ * @param cwd Working directory (default: process.cwd())
246
+ */
247
+ export function gitStatusSummary(cwd?: string): {
248
+ branch: string
249
+ head: string | null
250
+ trackedFiles: number
251
+ recentCommits: GitCommit[]
252
+ hasGitignore: boolean
253
+ } {
254
+ const branch = currentBranch()
255
+ const head = resolveHead(cwd)
256
+ const trackedFiles = readGitIndex(cwd).length
257
+ const recentCommits = readRecentCommits(5, cwd)
258
+ const hasGitignore = existsSync(join(cwd || process.cwd(), ".gitignore"))
259
+
260
+ return { branch, head, trackedFiles, recentCommits, hasGitignore }
261
+ }
262
+
263
+
@@ -0,0 +1,224 @@
1
+ /**
2
+ * Project structure scanner for toon-memory.
3
+ *
4
+ * Reads the project filesystem (package.json, directory tree, .env.example)
5
+ * to build a compact structural overview. Zero LLM, no network.
6
+ */
7
+
8
+ import { existsSync, readFileSync, readdirSync, statSync } from "fs"
9
+ import { join, extname } from "path"
10
+
11
+ const SKIP_DIRS = new Set([
12
+ "node_modules", ".git", ".toon-memory", "dist", "build",
13
+ ".next", ".nuxt", "coverage", "__pycache__", ".venv",
14
+ "vendor", ".cache", ".turbo",
15
+ ])
16
+
17
+ const MANIFEST_NAMES = [
18
+ "package.json", "Cargo.toml", "requirements.txt",
19
+ "pyproject.toml", "go.mod", "Gemfile", "pom.xml",
20
+ ]
21
+
22
+ export interface ProjectStructure {
23
+ /** Top-level directories (non-skipped). */
24
+ dirs: string[]
25
+ /** Key files at root level. */
26
+ rootFiles: string[]
27
+ /** Source file count (recursive, all extensions). */
28
+ sourceFileCount: number
29
+ /** File extension breakdown: ext → count. */
30
+ extensions: Record<string, number>
31
+ }
32
+
33
+ /**
34
+ * Scan the project directory tree (max depth 2) and return a structural summary.
35
+ */
36
+ export function scanProjectStructure(root: string, maxDepth: number = 2): ProjectStructure {
37
+ const dirs: string[] = []
38
+ const rootFiles: string[] = []
39
+ let sourceFileCount = 0
40
+ const extensions: Record<string, number> = {}
41
+
42
+ function walk(dir: string, depth: number): void {
43
+ if (depth > maxDepth) return
44
+ let entries: string[]
45
+ try {
46
+ entries = readdirSync(dir)
47
+ } catch {
48
+ return
49
+ }
50
+ for (const entry of entries) {
51
+ if (entry.startsWith(".") && depth === 0 && entry !== ".env.example" && entry !== ".env.template") continue
52
+ const fullPath = join(dir, entry)
53
+ let isDir: boolean
54
+ try {
55
+ isDir = statSync(fullPath).isDirectory()
56
+ } catch {
57
+ continue
58
+ }
59
+ if (isDir) {
60
+ if (SKIP_DIRS.has(entry)) continue
61
+ if (depth === 0) dirs.push(entry)
62
+ walk(fullPath, depth + 1)
63
+ } else {
64
+ if (depth === 0) rootFiles.push(entry)
65
+ sourceFileCount++
66
+ const ext = extname(entry) || "(no ext)"
67
+ extensions[ext] = (extensions[ext] || 0) + 1
68
+ }
69
+ }
70
+ }
71
+
72
+ walk(root, 0)
73
+ return { dirs: dirs.sort(), rootFiles: rootFiles.sort(), sourceFileCount, extensions }
74
+ }
75
+
76
+ // ── .env.example parser ──────────────────────────────────────────────
77
+
78
+ export interface EnvVar {
79
+ name: string
80
+ comment: string
81
+ default: string
82
+ }
83
+
84
+ /**
85
+ * Parse .env.example (or .env.template, .env.sample) into structured env vars.
86
+ * Format: VAR_NAME=default # comment
87
+ */
88
+ export function readEnvExample(root: string): EnvVar[] {
89
+ const candidates = [".env.example", ".env.template", ".env.sample"]
90
+ for (const name of candidates) {
91
+ const p = join(root, name)
92
+ if (existsSync(p)) {
93
+ try {
94
+ const content = readFileSync(p, "utf-8")
95
+ return parseEnvContent(content)
96
+ } catch {
97
+ return []
98
+ }
99
+ }
100
+ }
101
+ return []
102
+ }
103
+
104
+ function parseEnvContent(content: string): EnvVar[] {
105
+ const vars: EnvVar[] = []
106
+ for (const raw of content.split("\n")) {
107
+ const line = raw.trim()
108
+ if (!line || line.startsWith("#")) continue
109
+ const eqIdx = line.indexOf("=")
110
+ if (eqIdx < 0) continue
111
+ const name = line.slice(0, eqIdx).trim()
112
+ const rest = line.slice(eqIdx + 1)
113
+ // Split default value from comment
114
+ const hashIdx = rest.indexOf("#")
115
+ const defaultVal = (hashIdx >= 0 ? rest.slice(0, hashIdx) : rest).trim()
116
+ const comment = hashIdx >= 0 ? rest.slice(hashIdx + 1).trim() : ""
117
+ vars.push({ name, comment, default: defaultVal })
118
+ }
119
+ return vars
120
+ }
121
+
122
+ // ── Manifest reader ──────────────────────────────────────────────────
123
+
124
+ export interface ProjectManifest {
125
+ name: string
126
+ version: string
127
+ language: string
128
+ description: string
129
+ scripts: Record<string, string>
130
+ deps: string[]
131
+ devDeps: string[]
132
+ }
133
+
134
+ /**
135
+ * Read project manifest (package.json, Cargo.toml, etc.) and return
136
+ * a unified project info object.
137
+ */
138
+ export function readManifest(root: string): ProjectManifest | null {
139
+ // Try package.json first (most common)
140
+ const pkgPath = join(root, "package.json")
141
+ if (existsSync(pkgPath)) {
142
+ try {
143
+ const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"))
144
+ return {
145
+ name: pkg.name || "",
146
+ version: pkg.version || "",
147
+ language: "javascript",
148
+ description: pkg.description || "",
149
+ scripts: pkg.scripts || {},
150
+ deps: Object.keys(pkg.dependencies || {}),
151
+ devDeps: Object.keys(pkg.devDependencies || {}),
152
+ }
153
+ } catch {
154
+ // fall through
155
+ }
156
+ }
157
+
158
+ // Cargo.toml
159
+ const cargoPath = join(root, "Cargo.toml")
160
+ if (existsSync(cargoPath)) {
161
+ try {
162
+ const txt = readFileSync(cargoPath, "utf-8")
163
+ const nameMatch = txt.match(/^name\s*=\s*"([^"]+)"/m)
164
+ const verMatch = txt.match(/^version\s*=\s*"([^"]+)"/m)
165
+ const depsBlock = txt.match(/\[dependencies\]([\s\S]*?)(?:\[|$)/)?.[1] || ""
166
+ const deps = [...depsBlock.matchAll(/^\s*([A-Za-z0-9_-]+)\s*=/gm)].map((m) => m[1])
167
+ return {
168
+ name: nameMatch?.[1] || "",
169
+ version: verMatch?.[1] || "",
170
+ language: "rust",
171
+ description: "",
172
+ scripts: {},
173
+ deps,
174
+ devDeps: [],
175
+ }
176
+ } catch {
177
+ // fall through
178
+ }
179
+ }
180
+
181
+ // pyproject.toml
182
+ const pyPath = join(root, "pyproject.toml")
183
+ if (existsSync(pyPath)) {
184
+ try {
185
+ const txt = readFileSync(pyPath, "utf-8")
186
+ const nameMatch = txt.match(/^name\s*=\s*"([^"]+)"/m)
187
+ const verMatch = txt.match(/^version\s*=\s*"([^"]+)"/m)
188
+ return {
189
+ name: nameMatch?.[1] || "",
190
+ version: verMatch?.[1] || "",
191
+ language: "python",
192
+ description: "",
193
+ scripts: {},
194
+ deps: [],
195
+ devDeps: [],
196
+ }
197
+ } catch {
198
+ // fall through
199
+ }
200
+ }
201
+
202
+ // go.mod
203
+ const goPath = join(root, "go.mod")
204
+ if (existsSync(goPath)) {
205
+ try {
206
+ const txt = readFileSync(goPath, "utf-8")
207
+ const moduleMatch = txt.match(/^module\s+(.+)$/m)
208
+ const deps = [...txt.matchAll(/^\s*([A-Za-z0-9_./-]+)\s+v[\d.]+/gm)].map((m) => m[1])
209
+ return {
210
+ name: moduleMatch?.[1] || "",
211
+ version: "",
212
+ language: "go",
213
+ description: "",
214
+ scripts: {},
215
+ deps,
216
+ devDeps: [],
217
+ }
218
+ } catch {
219
+ // fall through
220
+ }
221
+ }
222
+
223
+ return null
224
+ }
@@ -0,0 +1,129 @@
1
+ import { readFileSync, existsSync } from "fs"
2
+ import { withLockSync } from "../lib/lock"
3
+ import { readMemory, writeMemory, safeWrite } from "./memory-io"
4
+ import { ensureMemoryFile, MEMORY_FILE, MEMORY_DIR, MAX_ENTRIES, ARCHIVE_DAYS, ARCHIVE_FILE } from "./config"
5
+ import { isExpired } from "./entries"
6
+ import { entryScoreForLine } from "./scoring"
7
+
8
+ /**
9
+ * Archive entries older than ARCHIVE_DAYS or with expired TTL.
10
+ * When `trimToMax` is set, also archive the lowest-importance entries
11
+ * until the active count is at or below MAX_ENTRIES.
12
+ */
13
+ export function archiveOldEntries(opts: { trimToMax?: boolean } = {}): { archived: number; kept: number } {
14
+ const data = readMemory()
15
+ const lines = data.split("\n")
16
+ const headerIdx = lines.findIndex((l) => l.startsWith("entries["))
17
+
18
+ if (headerIdx === -1) return { archived: 0, kept: 0 }
19
+
20
+ const today = new Date()
21
+ const cutoff = new Date(today)
22
+ cutoff.setDate(cutoff.getDate() - ARCHIVE_DAYS)
23
+ const cutoffStr = cutoff.toISOString().split("T")[0]
24
+
25
+ const entryLines = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0)
26
+ const toArchive = new Set<number>()
27
+
28
+ entryLines.forEach((line, idx) => {
29
+ const parts = line.trim().split("|")
30
+ if (parts.length < 7) return
31
+ const date = parts[6]
32
+ const ttl = parts[7] || ""
33
+ if (date < cutoffStr || (ttl && isExpired(ttl))) toArchive.add(idx)
34
+ })
35
+
36
+ if (opts.trimToMax) {
37
+ const remaining = entryLines.length - toArchive.size
38
+ if (remaining > MAX_ENTRIES) {
39
+ const need = remaining - MAX_ENTRIES
40
+ const candidates = entryLines
41
+ .map((line, idx) => ({ idx, score: entryScoreForLine(line) }))
42
+ .filter((c) => !toArchive.has(c.idx))
43
+ .sort((a, b) => a.score - b.score)
44
+ for (let i = 0; i < need && i < candidates.length; i++) toArchive.add(candidates[i].idx)
45
+ }
46
+ }
47
+
48
+ if (toArchive.size === 0) return { archived: 0, kept: entryLines.length }
49
+
50
+ const toArchiveLines = entryLines.filter((_, idx) => toArchive.has(idx)).map((l) => l.trim())
51
+ const toKeepLines = entryLines.filter((_, idx) => !toArchive.has(idx)).map((l) => l.trim())
52
+
53
+ // Write archived entries
54
+ let archiveContent = ""
55
+ if (existsSync(ARCHIVE_FILE)) {
56
+ archiveContent = readFileSync(ARCHIVE_FILE, "utf-8")
57
+ } else {
58
+ archiveContent = `version: 1\narchived:\n`
59
+ }
60
+
61
+ const archiveLines = archiveContent.split("\n")
62
+ let archiveHeaderIdx = archiveLines.findIndex((l) => l.startsWith("archived["))
63
+ if (archiveHeaderIdx === -1) {
64
+ archiveLines.push(`archived[0|]{id|category|key|content|file|tags|date}:`)
65
+ archiveHeaderIdx = archiveLines.length - 1
66
+ }
67
+
68
+ const archiveMatch = archiveLines[archiveHeaderIdx].match(/archived\[(\d+)\|/)
69
+ const archiveCount = archiveMatch ? parseInt(archiveMatch[1]) : 0
70
+
71
+ for (const entry of toArchiveLines) {
72
+ archiveLines.splice(archiveHeaderIdx + 1, 0, ` ${entry}`)
73
+ }
74
+ archiveLines[archiveHeaderIdx] = archiveLines[archiveHeaderIdx].replace(/archived\[\d+\|/, `[${archiveCount + toArchiveLines.length}|`)
75
+
76
+ safeWrite(ARCHIVE_FILE, archiveLines.join("\n"))
77
+
78
+ // Update main file
79
+ lines[headerIdx] = lines[headerIdx].replace(/entries\[\d+\|/, `[${toKeepLines.length}|`)
80
+ const keepSet = new Set(toKeepLines)
81
+ const allEntryLines = lines.slice(headerIdx + 1)
82
+ const newEntryLines = allEntryLines.filter((l) => {
83
+ if (l.trim().length === 0) return false
84
+ return keepSet.has(l.trim())
85
+ })
86
+ lines.splice(headerIdx + 1, allEntryLines.length, ...newEntryLines.map((l) => ` ${l.trim()}`))
87
+ writeMemory(lines.join("\n"))
88
+
89
+ return { archived: toArchiveLines.length, kept: toKeepLines.length }
90
+ }
91
+
92
+ /**
93
+ * Remove entries whose TTL has expired, run at server startup.
94
+ * Distinct from archiveOldEntries: pruning == hard delete of entries that
95
+ * have outlived their TTL. Runs entirely under the memory-file lock so parallel
96
+ * sessions can't corrupt the file mid-prune.
97
+ */
98
+ export function pruneExpiredEntries(): number {
99
+ ensureMemoryFile()
100
+ if (!existsSync(MEMORY_FILE)) return 0
101
+ let pruned = 0
102
+ withLockSync(MEMORY_FILE, () => {
103
+ const data = readMemory()
104
+ const lines = data.split("\n")
105
+ const headerIdx = lines.findIndex((l) => l.startsWith("entries["))
106
+ if (headerIdx === -1) return
107
+
108
+ const entryLines = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0 && !l.startsWith(" summaries:"))
109
+ const kept = entryLines.filter((l) => {
110
+ const parts = l.trim().split("|")
111
+ if (parts.length < 8) return true
112
+ const ttl = parts[7] || ""
113
+ if (ttl && isExpired(ttl)) {
114
+ pruned++
115
+ return false
116
+ }
117
+ return true
118
+ })
119
+ if (pruned === 0) return
120
+
121
+ lines[headerIdx] = lines[headerIdx].replace(/entries\[\d+\|/, `[${kept.length}|`)
122
+ const keepSet = new Set(kept.map((l) => l.trim()))
123
+ const allEntryLines = lines.slice(headerIdx + 1)
124
+ const newLines = allEntryLines.filter((l) => l.trim().length === 0 || keepSet.has(l.trim()))
125
+ lines.splice(headerIdx + 1, allEntryLines.length, ...newLines.map((l) => (l.trim().length ? ` ${l.trim()}` : l)))
126
+ writeMemory(lines.join("\n"))
127
+ })
128
+ return pruned
129
+ }
@@ -0,0 +1,88 @@
1
+ import { readFileSync, writeFileSync, existsSync, mkdirSync } from "fs"
2
+ import { join } from "path"
3
+
4
+ /** Base directory for memory storage */
5
+ export const MEMORY_DIR = join(process.cwd(), ".toon-memory", "memory")
6
+
7
+ /** Main memory data file */
8
+ export const MEMORY_FILE = join(MEMORY_DIR, "data.toon")
9
+
10
+ /** Archive file for old entries */
11
+ export const ARCHIVE_FILE = join(MEMORY_DIR, "archive.toon")
12
+
13
+ /** Observations log written by capture hooks (opt-in, separate from memory) */
14
+ export const OBSERVATIONS_FILE = join(MEMORY_DIR, "observations.toon")
15
+
16
+ /** Configuration file for encryption settings */
17
+ export const CONFIG_FILE = join(MEMORY_DIR, "config.json")
18
+
19
+ /** Maximum active entries before auto-archive */
20
+ export const MAX_ENTRIES = 100
21
+
22
+ /** Days before entries are archived */
23
+ export const ARCHIVE_DAYS = 30
24
+
25
+ /** Encryption algorithm for AES-256-GCM */
26
+ export const ALGORITHM = "aes-256-gcm"
27
+
28
+ /** Memory configuration with encryption settings */
29
+ export interface MemoryConfig {
30
+ /** Whether encryption is enabled */
31
+ encrypted: boolean
32
+ /** Project-specific tag vocabulary discovered from dependencies (Hito 7). */
33
+ vocab?: Record<string, string[]>
34
+ }
35
+
36
+ /**
37
+ * Load memory configuration from config.json.
38
+ */
39
+ export function loadConfig(): MemoryConfig {
40
+ if (!existsSync(CONFIG_FILE)) {
41
+ return { encrypted: false }
42
+ }
43
+ try {
44
+ return JSON.parse(readFileSync(CONFIG_FILE, "utf-8"))
45
+ } catch {
46
+ return { encrypted: false }
47
+ }
48
+ }
49
+
50
+ /**
51
+ * Save memory configuration to config.json.
52
+ */
53
+ export function saveConfig(config: MemoryConfig): void {
54
+ ensureMemoryDir()
55
+ let existing: Partial<MemoryConfig> = {}
56
+ if (existsSync(CONFIG_FILE)) {
57
+ try {
58
+ existing = JSON.parse(readFileSync(CONFIG_FILE, "utf-8"))
59
+ } catch {
60
+ existing = {}
61
+ }
62
+ }
63
+ writeFileSync(CONFIG_FILE, JSON.stringify({ ...existing, ...config }, null, 2))
64
+ }
65
+
66
+ /**
67
+ * Get the encryption key from environment variable.
68
+ */
69
+ export function getKey(): string | undefined {
70
+ return process.env.TOON_MEMORY_KEY
71
+ }
72
+
73
+ /**
74
+ * Ensure memory directory exists, creating it if necessary.
75
+ */
76
+ export function ensureMemoryDir(): void {
77
+ if (!existsSync(MEMORY_DIR)) mkdirSync(MEMORY_DIR, { recursive: true })
78
+ }
79
+
80
+ /**
81
+ * Ensure memory file exists with default structure.
82
+ */
83
+ export function ensureMemoryFile(): void {
84
+ ensureMemoryDir()
85
+ if (!existsSync(MEMORY_FILE)) {
86
+ writeFileSync(MEMORY_FILE, "version: 1\nentries[0|]{id|category|key|content|file|tags|date|ttl|accessed|links|quality|confidence}:\n")
87
+ }
88
+ }