toon-memory 2.5.2 → 2.8.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,262 @@
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
+ // v3/v4 entries have an extra 4-byte extended entry field after the standard 62 bytes
93
+ let nameOffset = 62
94
+ if (version >= 3) {
95
+ nameOffset += 4
96
+ }
97
+
98
+ // Name starts at entryStart + nameOffset, null-terminated, padded to 8-byte alignment
99
+ const nameLen = flags & 0x0fff
100
+ const nameStart = entryStart + nameOffset
101
+ let name: string
102
+ if (nameLen > 0 && nameStart + nameLen <= buf.length) {
103
+ name = buf.toString("utf-8", nameStart, nameStart + nameLen)
104
+ } else {
105
+ const end = buf.indexOf(0, nameStart)
106
+ name = end >= 0 ? buf.toString("utf-8", nameStart, end) : buf.toString("utf-8", nameStart)
107
+ }
108
+
109
+ // Compute total entry size: base bytes + name length, padded to 8-byte boundary
110
+ const rawLen = nameOffset + name.length
111
+ const paddedLen = Math.ceil(rawLen / 8) * 8
112
+ offset = entryStart + paddedLen
113
+
114
+ entries.push({ mtimeSec, mtimeNsec, dev, ino, mode, uid, gid, size, sha, flags, name })
115
+ }
116
+
117
+ return entries
118
+ }
119
+
120
+ /**
121
+ * Parse .gitignore patterns into a set of ignored paths.
122
+ * Simplified: handles exact filenames and directory names.
123
+ */
124
+ function parseGitignore(dir: string): Set<string> {
125
+ const ignored = new Set<string>()
126
+ const gitignorePath = join(dir, "..", ".gitignore")
127
+ if (!existsSync(gitignorePath)) return ignored
128
+
129
+ const lines = readFileSync(gitignorePath, "utf-8").split("\n")
130
+ for (const raw of lines) {
131
+ const line = raw.trim()
132
+ if (!line || line.startsWith("#")) continue
133
+ // Strip leading slash (root-only pattern)
134
+ const pattern = line.replace(/^\//, "")
135
+ // Simple: just track the pattern as-is
136
+ if (pattern) ignored.add(pattern)
137
+ }
138
+ return ignored
139
+ }
140
+
141
+ /**
142
+ * Read the git index and return the list of tracked file paths.
143
+ * These are the files git knows about (staged or tracked).
144
+ * @param cwd Working directory (default: process.cwd())
145
+ */
146
+ export function readGitIndex(cwd?: string): string[] {
147
+ const dir = gitDir(cwd)
148
+ if (!dir) return []
149
+ return parseIndex(dir).map((e) => e.name)
150
+ }
151
+
152
+ /**
153
+ * Parse a raw git object (decompressed with zlib).
154
+ * Returns the object type and content.
155
+ */
156
+ function readObject(sha: string, cwd?: string): { type: string; content: string } | null {
157
+ const dir = gitDir(cwd)
158
+ if (!dir) return null
159
+ const objPath = join(dir, "objects", sha.slice(0, 2), sha.slice(2))
160
+ if (!existsSync(objPath)) return null
161
+
162
+ try {
163
+ const compressed = readFileSync(objPath)
164
+ const decompressed = inflateSync(compressed)
165
+ const str = decompressed.toString("utf-8")
166
+ const nullIdx = str.indexOf("\0")
167
+ if (nullIdx < 0) return null
168
+ const header = str.slice(0, nullIdx)
169
+ const type = header.split(" ")[0]
170
+ const content = str.slice(nullIdx + 1)
171
+ return { type, content }
172
+ } catch {
173
+ return null
174
+ }
175
+ }
176
+
177
+ export interface GitCommit {
178
+ hash: string
179
+ shortHash: string
180
+ subject: string
181
+ author: string
182
+ date: string
183
+ }
184
+
185
+ /**
186
+ * Read the n most recent commits by walking the commit chain from HEAD.
187
+ * @param cwd Working directory (default: process.cwd())
188
+ */
189
+ export function readRecentCommits(count: number = 10, cwd?: string): GitCommit[] {
190
+ const sha = resolveHead(cwd)
191
+ if (!sha) return []
192
+
193
+ const commits: GitCommit[] = []
194
+ const visited = new Set<string>()
195
+ let current = sha
196
+
197
+ while (commits.length < count && current && !visited.has(current)) {
198
+ visited.add(current)
199
+ const obj = readObject(current, cwd)
200
+ if (!obj || obj.type !== "commit") break
201
+
202
+ const lines = obj.content.split("\n")
203
+ let subject = ""
204
+ let author = ""
205
+ let date = ""
206
+ let parent: string | null = null
207
+ let pastHeaders = false
208
+
209
+ for (const line of lines) {
210
+ if (line.startsWith("author ")) {
211
+ const match = line.match(/^author\s+(.+?)\s+<[^>]+>\s+(\d+)/)
212
+ if (match) {
213
+ author = match[1]
214
+ const ts = parseInt(match[2])
215
+ date = new Date(ts * 1000).toISOString().split("T")[0]
216
+ }
217
+ } else if (line.startsWith("parent ")) {
218
+ parent = line.slice(7).trim()
219
+ } else if (line.startsWith("tree ")) {
220
+ // skip
221
+ } else if (line.startsWith("committer ")) {
222
+ pastHeaders = true
223
+ } else if (pastHeaders && !subject && line.trim()) {
224
+ subject = line.trim()
225
+ }
226
+ }
227
+
228
+ commits.push({
229
+ hash: current,
230
+ shortHash: current.slice(0, 7),
231
+ subject,
232
+ author,
233
+ date,
234
+ })
235
+
236
+ current = parent || ""
237
+ }
238
+
239
+ return commits
240
+ }
241
+
242
+ /**
243
+ * Get a summary of the current git status.
244
+ * @param cwd Working directory (default: process.cwd())
245
+ */
246
+ export function gitStatusSummary(cwd?: string): {
247
+ branch: string
248
+ head: string | null
249
+ trackedFiles: number
250
+ recentCommits: GitCommit[]
251
+ hasGitignore: boolean
252
+ } {
253
+ const branch = currentBranch()
254
+ const head = resolveHead(cwd)
255
+ const trackedFiles = readGitIndex(cwd).length
256
+ const recentCommits = readRecentCommits(5, cwd)
257
+ const hasGitignore = existsSync(join(cwd || process.cwd(), ".gitignore"))
258
+
259
+ return { branch, head, trackedFiles, recentCommits, hasGitignore }
260
+ }
261
+
262
+
package/src/lib/graph.ts CHANGED
@@ -14,6 +14,8 @@
14
14
  * without mutating the stored `.toon` file.
15
15
  */
16
16
 
17
+ import { normalize, isExpiredLocal, tokenize, importance } from "./utils"
18
+
17
19
  export interface GraphEntry {
18
20
  id: string
19
21
  category: string
@@ -35,15 +37,6 @@ export interface MemoryGraph {
35
37
  byKey: Map<string, GraphEntry>
36
38
  }
37
39
 
38
- const isExpiredLocal = (ttl: string): boolean => {
39
- if (!ttl) return false
40
- const today = new Date().toISOString().split("T")[0]
41
- return ttl <= today
42
- }
43
-
44
- const normalize = (s: string): string =>
45
- s.toLowerCase().replace(/[-_]/g, " ").replace(/\s+/g, " ").trim()
46
-
47
40
  const entryLines = (data: string): string[] =>
48
41
  data
49
42
  .split("\n")
@@ -125,17 +118,6 @@ export interface GraphRecallOpts {
125
118
  limit?: number
126
119
  }
127
120
 
128
- const importance = (e: GraphEntry): number => {
129
- const today = new Date().toISOString().split("T")[0]
130
- const days =
131
- (Date.now() - new Date(`${e.date || today}T00:00:00`).getTime()) / 86400000
132
- const recency = Math.max(0, 30 - days) / 30
133
- const freq = Math.min(1, e.accessed / 5)
134
- return recency * 0.6 + freq * 0.4
135
- }
136
-
137
- const tokenize = (s: string): string[] => normalize(s).split(" ").filter(Boolean)
138
-
139
121
  /**
140
122
  * BM25 relevance of each entry for the query. Deterministic and offline.
141
123
  * Returns a map key -> score (0 when the entry shares no query token).
@@ -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
+ }
@@ -8,26 +8,7 @@
8
8
  */
9
9
 
10
10
  import { parseEntries, buildGraph, bm25Scores, centrality, renderCompact, type GraphEntry } from "./graph"
11
-
12
- const normalize = (s: string): string =>
13
- s.toLowerCase().replace(/[-_]/g, " ").replace(/\s+/g, " ").trim()
14
-
15
- const tokenize = (s: string): string[] => normalize(s).split(" ").filter(Boolean)
16
-
17
- const isExpiredLocal = (ttl: string): boolean => {
18
- if (!ttl) return false
19
- const today = new Date().toISOString().split("T")[0]
20
- return ttl <= today
21
- }
22
-
23
- const importance = (e: GraphEntry): number => {
24
- const today = new Date().toISOString().split("T")[0]
25
- const days =
26
- (Date.now() - new Date(`${e.date || today}T00:00:00`).getTime()) / 86400000
27
- const recency = Math.max(0, 30 - days) / 30
28
- const freq = Math.min(1, e.accessed / 5)
29
- return recency * 0.6 + freq * 0.4
30
- }
11
+ import { normalize, isExpiredLocal, tokenize, importance } from "./utils"
31
12
 
32
13
  /**
33
14
  * Quality score for an entry (0..1). Pure heuristics, no LLM.
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Shared helper functions used across lib/ modules.
3
+ * Eliminates copy-paste duplication of normalize, isExpiredLocal, importance, tokenize.
4
+ */
5
+
6
+ export const normalize = (s: string): string =>
7
+ s.toLowerCase().replace(/[-_]/g, " ").replace(/\s+/g, " ").trim()
8
+
9
+ export const isExpiredLocal = (ttl: string): boolean => {
10
+ if (!ttl) return false
11
+ const today = new Date().toISOString().split("T")[0]
12
+ return ttl <= today
13
+ }
14
+
15
+ /** Lightweight importance score: recency (60%) + frequency (40%). */
16
+ export function importance(e: { date: string; accessed: number }): number {
17
+ const today = new Date().toISOString().split("T")[0]
18
+ const days =
19
+ (Date.now() - new Date(`${e.date || today}T00:00:00`).getTime()) / 86400000
20
+ const recency = Math.max(0, 30 - days) / 30
21
+ const freq = Math.min(1, e.accessed / 5)
22
+ return recency * 0.6 + freq * 0.4
23
+ }
24
+
25
+ export const tokenize = (s: string): string[] => normalize(s).split(" ").filter(Boolean)