@edihasaj/recall 0.8.13 → 0.8.15

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.
@@ -2,7 +2,7 @@ import {
2
2
  listEntitiesForMemory,
3
3
  listMemoryIdsForEntity,
4
4
  neighborsOf
5
- } from "./chunk-R4G62MKZ.js";
5
+ } from "./chunk-M7OKBKKU.js";
6
6
  import {
7
7
  getMemory
8
8
  } from "./chunk-TPCWQS6Q.js";
@@ -120,4 +120,4 @@ async function graphQuery(db, query, embeddingConfig, options = {}) {
120
120
  export {
121
121
  graphQuery
122
122
  };
123
- //# sourceMappingURL=chunk-MIRCNPUN.js.map
123
+ //# sourceMappingURL=chunk-A54CLR5Q.js.map
@@ -263,6 +263,11 @@ function countRelations(db) {
263
263
  const row = db.select({ c: sql`count(*)` }).from(entityRelations).get();
264
264
  return Number(row?.c ?? 0);
265
265
  }
266
+ function clearGraph(db) {
267
+ db.delete(memoryEntities).run();
268
+ db.delete(entityRelations).run();
269
+ db.delete(entities).run();
270
+ }
266
271
 
267
272
  export {
268
273
  isPlausibleEntityName,
@@ -277,6 +282,7 @@ export {
277
282
  neighborsOf,
278
283
  listAllRelations,
279
284
  countEntities,
280
- countRelations
285
+ countRelations,
286
+ clearGraph
281
287
  };
282
- //# sourceMappingURL=chunk-R4G62MKZ.js.map
288
+ //# sourceMappingURL=chunk-M7OKBKKU.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/graph/store.ts","../src/graph/normalize.ts"],"sourcesContent":["/**\n * Read/write layer for the knowledge graph tables. Pure DB operations —\n * no LLM calls, no business logic — so they're safe to call from any\n * code path (capture hook, dispatcher, scan, MCP tool).\n */\nimport { randomUUID } from \"node:crypto\";\nimport { and, eq, inArray, like, or, sql } from \"drizzle-orm\";\nimport type { RecallDb } from \"../db/client.js\";\nimport { entities, entityRelations, memoryEntities } from \"../db/schema.js\";\nimport { normalizeName, type EntityKind } from \"./normalize.js\";\n\nexport type RelationType =\n | \"uses\"\n | \"replaces\"\n | \"conflicts_with\"\n | \"tested_by\"\n | \"depends_on\"\n | \"references\"\n | \"part_of\";\n\nexport interface EntityRow {\n id: string;\n kind: EntityKind;\n name: string;\n normalized_name: string;\n repo: string | null;\n description: string | null;\n mention_count: number;\n first_seen_memory_id: string | null;\n created_at: string;\n updated_at: string;\n}\n\nexport interface EntityRelationRow {\n id: string;\n source_entity_id: string;\n target_entity_id: string;\n relation_type: RelationType;\n source_memory_id: string | null;\n confidence: number;\n created_at: string;\n}\n\nexport interface UpsertEntityInput {\n kind: EntityKind;\n name: string;\n repo?: string | null;\n description?: string | null;\n first_seen_memory_id?: string | null;\n}\n\n/**\n * Insert or look up an entity by (kind, normalized_name, repo). Returns the\n * canonical row. Increments mention_count on every call so we can rank\n * entities by how often the codebase mentions them.\n */\nexport function upsertEntity(db: RecallDb, input: UpsertEntityInput): EntityRow {\n const normalized = normalizeName(input.kind, input.name);\n const repo = input.repo ?? null;\n const now = new Date().toISOString();\n\n const existing = findEntityByNormalized(db, input.kind, normalized, repo);\n if (existing) {\n db.update(entities)\n .set({\n mention_count: existing.mention_count + 1,\n updated_at: now,\n // Backfill description / first_seen if not previously set.\n description: existing.description ?? input.description ?? null,\n first_seen_memory_id: existing.first_seen_memory_id ?? input.first_seen_memory_id ?? null,\n })\n .where(eq(entities.id, existing.id))\n .run();\n return {\n ...existing,\n mention_count: existing.mention_count + 1,\n updated_at: now,\n description: existing.description ?? input.description ?? null,\n first_seen_memory_id: existing.first_seen_memory_id ?? input.first_seen_memory_id ?? null,\n };\n }\n\n const id = randomUUID();\n db.insert(entities)\n .values({\n id,\n kind: input.kind,\n name: input.name.trim(),\n normalized_name: normalized,\n repo,\n description: input.description ?? null,\n first_seen_memory_id: input.first_seen_memory_id ?? null,\n mention_count: 1,\n created_at: now,\n updated_at: now,\n })\n .run();\n return {\n id,\n kind: input.kind,\n name: input.name.trim(),\n normalized_name: normalized,\n repo,\n description: input.description ?? null,\n mention_count: 1,\n first_seen_memory_id: input.first_seen_memory_id ?? null,\n created_at: now,\n updated_at: now,\n };\n}\n\nexport function findEntityByNormalized(\n db: RecallDb,\n kind: EntityKind,\n normalized: string,\n repo: string | null,\n): EntityRow | null {\n const row = db\n .select()\n .from(entities)\n .where(\n and(\n eq(entities.kind, kind),\n eq(entities.normalized_name, normalized),\n repo === null\n ? sql`${entities.repo} IS NULL`\n : eq(entities.repo, repo),\n ),\n )\n .get();\n return (row as EntityRow | undefined) ?? null;\n}\n\nexport function getEntity(db: RecallDb, id: string): EntityRow | null {\n const row = db.select().from(entities).where(eq(entities.id, id)).get();\n return (row as EntityRow | undefined) ?? null;\n}\n\nexport interface ListEntitiesOptions {\n repo?: string;\n kind?: EntityKind;\n search?: string;\n limit?: number;\n offset?: number;\n}\n\nexport function listEntities(db: RecallDb, opts: ListEntitiesOptions = {}): EntityRow[] {\n const conditions = [] as Array<ReturnType<typeof eq> | ReturnType<typeof or>>;\n if (opts.repo) conditions.push(eq(entities.repo, opts.repo));\n if (opts.kind) conditions.push(eq(entities.kind, opts.kind));\n if (opts.search) {\n // Push the contains-match into SQL so LIMIT applies post-filter; the\n // previous in-memory filter only saw the top-N by mention_count and\n // missed long-tail matches entirely.\n const needle = `%${opts.search.toLowerCase()}%`;\n conditions.push(\n or(\n like(entities.normalized_name, needle),\n like(sql`lower(${entities.name})`, needle),\n )!,\n );\n }\n const where = conditions.length === 1 ? conditions[0] : conditions.length > 1 ? and(...conditions) : undefined;\n const builder = where\n ? db.select().from(entities).where(where)\n : db.select().from(entities);\n return builder\n .orderBy(sql`${entities.mention_count} DESC`)\n .limit(opts.limit ?? 200)\n .offset(opts.offset ?? 0)\n .all() as EntityRow[];\n}\n\nexport interface LinkMemoryEntityInput {\n memory_id: string;\n entity_id: string;\n source: \"heuristic\" | \"llm\" | \"manual\";\n weight?: number;\n}\n\n/** Idempotent: links a memory to an entity, no-op if the edge already exists. */\nexport function linkMemoryToEntity(db: RecallDb, input: LinkMemoryEntityInput): void {\n const existing = db\n .select({ id: memoryEntities.id })\n .from(memoryEntities)\n .where(\n and(\n eq(memoryEntities.memory_id, input.memory_id),\n eq(memoryEntities.entity_id, input.entity_id),\n ),\n )\n .get();\n if (existing) return;\n db.insert(memoryEntities)\n .values({\n id: randomUUID(),\n memory_id: input.memory_id,\n entity_id: input.entity_id,\n source: input.source,\n weight: input.weight ?? 1,\n created_at: new Date().toISOString(),\n })\n .run();\n}\n\nexport function listEntitiesForMemory(db: RecallDb, memoryId: string): EntityRow[] {\n return db\n .select({\n id: entities.id,\n kind: entities.kind,\n name: entities.name,\n normalized_name: entities.normalized_name,\n repo: entities.repo,\n description: entities.description,\n mention_count: entities.mention_count,\n first_seen_memory_id: entities.first_seen_memory_id,\n created_at: entities.created_at,\n updated_at: entities.updated_at,\n })\n .from(memoryEntities)\n .innerJoin(entities, eq(entities.id, memoryEntities.entity_id))\n .where(eq(memoryEntities.memory_id, memoryId))\n .all() as EntityRow[];\n}\n\nexport function listMemoryIdsForEntity(db: RecallDb, entityId: string): string[] {\n const rows = db\n .select({ memory_id: memoryEntities.memory_id })\n .from(memoryEntities)\n .where(eq(memoryEntities.entity_id, entityId))\n .all();\n return rows.map((r) => r.memory_id);\n}\n\nexport interface UpsertRelationInput {\n source_entity_id: string;\n target_entity_id: string;\n relation_type: RelationType;\n source_memory_id?: string | null;\n confidence?: number;\n}\n\n/** Idempotent on (source, target, relation_type, source_memory_id). */\nexport function upsertRelation(db: RecallDb, input: UpsertRelationInput): EntityRelationRow {\n const sourceMem = input.source_memory_id ?? null;\n const existing = db\n .select()\n .from(entityRelations)\n .where(\n and(\n eq(entityRelations.source_entity_id, input.source_entity_id),\n eq(entityRelations.target_entity_id, input.target_entity_id),\n eq(entityRelations.relation_type, input.relation_type),\n sourceMem === null\n ? sql`${entityRelations.source_memory_id} IS NULL`\n : eq(entityRelations.source_memory_id, sourceMem),\n ),\n )\n .get() as EntityRelationRow | undefined;\n if (existing) {\n if (input.confidence !== undefined && input.confidence > existing.confidence) {\n db.update(entityRelations)\n .set({ confidence: input.confidence })\n .where(eq(entityRelations.id, existing.id))\n .run();\n return { ...existing, confidence: input.confidence };\n }\n return existing;\n }\n const id = randomUUID();\n const now = new Date().toISOString();\n db.insert(entityRelations)\n .values({\n id,\n source_entity_id: input.source_entity_id,\n target_entity_id: input.target_entity_id,\n relation_type: input.relation_type,\n source_memory_id: sourceMem,\n confidence: input.confidence ?? 0.6,\n created_at: now,\n })\n .run();\n return {\n id,\n source_entity_id: input.source_entity_id,\n target_entity_id: input.target_entity_id,\n relation_type: input.relation_type,\n source_memory_id: sourceMem,\n confidence: input.confidence ?? 0.6,\n created_at: now,\n };\n}\n\nexport function neighborsOf(\n db: RecallDb,\n entityId: string,\n options: { hops?: number; relationTypes?: RelationType[] } = {},\n): { entities: EntityRow[]; relations: EntityRelationRow[] } {\n const maxHops = Math.max(1, Math.min(5, options.hops ?? 1));\n const visited = new Set<string>([entityId]);\n let frontier = [entityId];\n const collectedRelations = new Map<string, EntityRelationRow>();\n\n for (let hop = 0; hop < maxHops; hop++) {\n if (frontier.length === 0) break;\n const next: string[] = [];\n const relationFilter = options.relationTypes;\n const outgoing = db\n .select()\n .from(entityRelations)\n .where(\n relationFilter && relationFilter.length > 0\n ? and(\n inArray(entityRelations.source_entity_id, frontier),\n inArray(entityRelations.relation_type, relationFilter),\n )\n : inArray(entityRelations.source_entity_id, frontier),\n )\n .all() as EntityRelationRow[];\n const incoming = db\n .select()\n .from(entityRelations)\n .where(\n relationFilter && relationFilter.length > 0\n ? and(\n inArray(entityRelations.target_entity_id, frontier),\n inArray(entityRelations.relation_type, relationFilter),\n )\n : inArray(entityRelations.target_entity_id, frontier),\n )\n .all() as EntityRelationRow[];\n\n for (const rel of [...outgoing, ...incoming]) {\n collectedRelations.set(rel.id, rel);\n for (const candidate of [rel.source_entity_id, rel.target_entity_id]) {\n if (!visited.has(candidate)) {\n visited.add(candidate);\n next.push(candidate);\n }\n }\n }\n frontier = next;\n }\n\n const entityRows = visited.size === 0\n ? []\n : (db\n .select()\n .from(entities)\n .where(inArray(entities.id, Array.from(visited)))\n .all() as EntityRow[]);\n\n return {\n entities: entityRows,\n relations: Array.from(collectedRelations.values()),\n };\n}\n\n/**\n * List every relation in the graph, optionally restricted to relations\n * whose source AND target entities both belong to the given repo. Used by\n * the WebUI to render the whole graph at once (no seed required).\n */\nexport function listAllRelations(\n db: RecallDb,\n opts: { repo?: string; limit?: number } = {},\n): EntityRelationRow[] {\n const limit = Math.min(Math.max(opts.limit ?? 2000, 1), 10_000);\n if (!opts.repo) {\n return db\n .select()\n .from(entityRelations)\n .limit(limit)\n .all() as EntityRelationRow[];\n }\n // Filter both endpoints to entities in the repo. Two-step: collect ids,\n // then pick relations whose endpoints are both inside that set.\n const repoEntityIds = db\n .select({ id: entities.id })\n .from(entities)\n .where(eq(entities.repo, opts.repo))\n .all()\n .map((r) => r.id);\n if (repoEntityIds.length === 0) return [];\n const idSet = new Set(repoEntityIds);\n const all = db\n .select()\n .from(entityRelations)\n .where(\n and(\n inArray(entityRelations.source_entity_id, repoEntityIds),\n inArray(entityRelations.target_entity_id, repoEntityIds),\n ),\n )\n .limit(limit)\n .all() as EntityRelationRow[];\n return all.filter(\n (r) => idSet.has(r.source_entity_id) && idSet.has(r.target_entity_id),\n );\n}\n\nexport function countEntities(db: RecallDb): number {\n const row = db\n .select({ c: sql<number>`count(*)` })\n .from(entities)\n .get();\n return Number(row?.c ?? 0);\n}\n\nexport function countRelations(db: RecallDb): number {\n const row = db\n .select({ c: sql<number>`count(*)` })\n .from(entityRelations)\n .get();\n return Number(row?.c ?? 0);\n}\n","/**\n * Canonical-form helpers for entity dedup. Two entities with the same\n * (kind, normalizedName, repo) collapse into one node.\n *\n * Normalization rules are conservative on purpose — we'd rather have a\n * duplicate than merge two semantically distinct things. Aggressive\n * merging belongs in a maintenance pass that can be reviewed.\n */\n\nexport type EntityKind =\n | \"file\"\n | \"function\"\n | \"library\"\n | \"tool\"\n | \"concept\"\n | \"repo_path\"\n | \"command\"\n | \"url\";\n\nexport function normalizeName(kind: EntityKind, raw: string): string {\n const trimmed = raw.trim();\n switch (kind) {\n case \"file\":\n case \"repo_path\":\n // Posix-style paths, no leading slash, no trailing slash.\n return trimmed\n .replace(/\\\\/g, \"/\")\n .replace(/^[./]+/, \"\")\n .replace(/\\/+$/, \"\")\n .toLowerCase();\n case \"function\":\n // foo() / Class.method / obj.method — keep the dotted form, drop parens/args.\n return trimmed\n .replace(/\\(.*\\)/, \"\")\n .replace(/\\s+/g, \"\")\n .toLowerCase();\n case \"library\":\n case \"tool\":\n case \"command\":\n // package names / CLI names: lowercase, strip @scope leading-only if present\n // but keep `@scope/name` distinct from `name`.\n return trimmed.toLowerCase();\n case \"url\":\n try {\n const u = new URL(trimmed);\n return `${u.hostname.toLowerCase()}${u.pathname.replace(/\\/+$/, \"\")}`;\n } catch {\n return trimmed.toLowerCase();\n }\n case \"concept\":\n default:\n return trimmed.toLowerCase().replace(/\\s+/g, \" \");\n }\n}\n\nexport function isPlausibleEntityName(kind: EntityKind, name: string): boolean {\n const n = name.trim();\n if (n.length === 0 || n.length > 200) return false;\n // Filter common false positives that look like identifiers but aren't.\n if (/^[0-9]+$/.test(n)) return false;\n if (kind === \"concept\" && n.split(/\\s+/).length > 8) return false;\n // Single-letter \"library\" tokens are almost always noise.\n if ((kind === \"library\" || kind === \"tool\") && n.length < 2) return false;\n return true;\n}\n"],"mappings":";;;;;;;;;;;;;AAKA,SAAS,kBAAkB;;;ACcpB,SAAS,cAAc,MAAkB,KAAqB;AACnE,QAAM,UAAU,IAAI,KAAK;AACzB,UAAQ,MAAM;AAAA,IACZ,KAAK;AAAA,IACL,KAAK;AAEH,aAAO,QACJ,QAAQ,OAAO,GAAG,EAClB,QAAQ,UAAU,EAAE,EACpB,QAAQ,QAAQ,EAAE,EAClB,YAAY;AAAA,IACjB,KAAK;AAEH,aAAO,QACJ,QAAQ,UAAU,EAAE,EACpB,QAAQ,QAAQ,EAAE,EAClB,YAAY;AAAA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T,OAAO,EACP,KAAK,eAAe,EACpB;AAAA,IACC;AAAA,MACE,QAAQ,gBAAgB,kBAAkB,aAAa;AAAA,MACvD,QAAQ,gBAAgB,kBAAkB,aAAa;AAAA,IACzD;AAAA,EACF,EACC,MAAM,KAAK,EACX,IAAI;AACP,SAAO,IAAI;AAAA,IACT,CAAC,MAAM,MAAM,IAAI,EAAE,gBAAgB,KAAK,MAAM,IAAI,EAAE,gBAAgB;AAAA,EACtE;AACF;AAEO,SAAS,cAAc,IAAsB;AAClD,QAAM,MAAM,GACT,OAAO,EAAE,GAAG,cAAsB,CAAC,EACnC,KAAK,QAAQ,EACb,IAAI;AACP,SAAO,OAAO,KAAK,KAAK,CAAC;AAC3B;AAEO,SAAS,eAAe,IAAsB;AACnD,QAAM,MAAM,GACT,OAAO,EAAE,GAAG,cAAsB,CAAC,EACnC,KAAK,eAAe,EACpB,IAAI;AACP,SAAO,OAAO,KAAK,KAAK,CAAC;AAC3B;","names":[]}
1
+ {"version":3,"sources":["../src/graph/store.ts","../src/graph/normalize.ts"],"sourcesContent":["/**\n * Read/write layer for the knowledge graph tables. Pure DB operations —\n * no LLM calls, no business logic — so they're safe to call from any\n * code path (capture hook, dispatcher, scan, MCP tool).\n */\nimport { randomUUID } from \"node:crypto\";\nimport { and, eq, inArray, like, or, sql } from \"drizzle-orm\";\nimport type { RecallDb } from \"../db/client.js\";\nimport { entities, entityRelations, memoryEntities } from \"../db/schema.js\";\nimport { normalizeName, type EntityKind } from \"./normalize.js\";\n\nexport type RelationType =\n | \"uses\"\n | \"replaces\"\n | \"conflicts_with\"\n | \"tested_by\"\n | \"depends_on\"\n | \"references\"\n | \"part_of\";\n\nexport interface EntityRow {\n id: string;\n kind: EntityKind;\n name: string;\n normalized_name: string;\n repo: string | null;\n description: string | null;\n mention_count: number;\n first_seen_memory_id: string | null;\n created_at: string;\n updated_at: string;\n}\n\nexport interface EntityRelationRow {\n id: string;\n source_entity_id: string;\n target_entity_id: string;\n relation_type: RelationType;\n source_memory_id: string | null;\n confidence: number;\n created_at: string;\n}\n\nexport interface UpsertEntityInput {\n kind: EntityKind;\n name: string;\n repo?: string | null;\n description?: string | null;\n first_seen_memory_id?: string | null;\n}\n\n/**\n * Insert or look up an entity by (kind, normalized_name, repo). Returns the\n * canonical row. Increments mention_count on every call so we can rank\n * entities by how often the codebase mentions them.\n */\nexport function upsertEntity(db: RecallDb, input: UpsertEntityInput): EntityRow {\n const normalized = normalizeName(input.kind, input.name);\n const repo = input.repo ?? null;\n const now = new Date().toISOString();\n\n const existing = findEntityByNormalized(db, input.kind, normalized, repo);\n if (existing) {\n db.update(entities)\n .set({\n mention_count: existing.mention_count + 1,\n updated_at: now,\n // Backfill description / first_seen if not previously set.\n description: existing.description ?? input.description ?? null,\n first_seen_memory_id: existing.first_seen_memory_id ?? input.first_seen_memory_id ?? null,\n })\n .where(eq(entities.id, existing.id))\n .run();\n return {\n ...existing,\n mention_count: existing.mention_count + 1,\n updated_at: now,\n description: existing.description ?? input.description ?? null,\n first_seen_memory_id: existing.first_seen_memory_id ?? input.first_seen_memory_id ?? null,\n };\n }\n\n const id = randomUUID();\n db.insert(entities)\n .values({\n id,\n kind: input.kind,\n name: input.name.trim(),\n normalized_name: normalized,\n repo,\n description: input.description ?? null,\n first_seen_memory_id: input.first_seen_memory_id ?? null,\n mention_count: 1,\n created_at: now,\n updated_at: now,\n })\n .run();\n return {\n id,\n kind: input.kind,\n name: input.name.trim(),\n normalized_name: normalized,\n repo,\n description: input.description ?? null,\n mention_count: 1,\n first_seen_memory_id: input.first_seen_memory_id ?? null,\n created_at: now,\n updated_at: now,\n };\n}\n\nexport function findEntityByNormalized(\n db: RecallDb,\n kind: EntityKind,\n normalized: string,\n repo: string | null,\n): EntityRow | null {\n const row = db\n .select()\n .from(entities)\n .where(\n and(\n eq(entities.kind, kind),\n eq(entities.normalized_name, normalized),\n repo === null\n ? sql`${entities.repo} IS NULL`\n : eq(entities.repo, repo),\n ),\n )\n .get();\n return (row as EntityRow | undefined) ?? null;\n}\n\nexport function getEntity(db: RecallDb, id: string): EntityRow | null {\n const row = db.select().from(entities).where(eq(entities.id, id)).get();\n return (row as EntityRow | undefined) ?? null;\n}\n\nexport interface ListEntitiesOptions {\n repo?: string;\n kind?: EntityKind;\n search?: string;\n limit?: number;\n offset?: number;\n}\n\nexport function listEntities(db: RecallDb, opts: ListEntitiesOptions = {}): EntityRow[] {\n const conditions = [] as Array<ReturnType<typeof eq> | ReturnType<typeof or>>;\n if (opts.repo) conditions.push(eq(entities.repo, opts.repo));\n if (opts.kind) conditions.push(eq(entities.kind, opts.kind));\n if (opts.search) {\n // Push the contains-match into SQL so LIMIT applies post-filter; the\n // previous in-memory filter only saw the top-N by mention_count and\n // missed long-tail matches entirely.\n const needle = `%${opts.search.toLowerCase()}%`;\n conditions.push(\n or(\n like(entities.normalized_name, needle),\n like(sql`lower(${entities.name})`, needle),\n )!,\n );\n }\n const where = conditions.length === 1 ? conditions[0] : conditions.length > 1 ? and(...conditions) : undefined;\n const builder = where\n ? db.select().from(entities).where(where)\n : db.select().from(entities);\n return builder\n .orderBy(sql`${entities.mention_count} DESC`)\n .limit(opts.limit ?? 200)\n .offset(opts.offset ?? 0)\n .all() as EntityRow[];\n}\n\nexport interface LinkMemoryEntityInput {\n memory_id: string;\n entity_id: string;\n source: \"heuristic\" | \"llm\" | \"manual\";\n weight?: number;\n}\n\n/** Idempotent: links a memory to an entity, no-op if the edge already exists. */\nexport function linkMemoryToEntity(db: RecallDb, input: LinkMemoryEntityInput): void {\n const existing = db\n .select({ id: memoryEntities.id })\n .from(memoryEntities)\n .where(\n and(\n eq(memoryEntities.memory_id, input.memory_id),\n eq(memoryEntities.entity_id, input.entity_id),\n ),\n )\n .get();\n if (existing) return;\n db.insert(memoryEntities)\n .values({\n id: randomUUID(),\n memory_id: input.memory_id,\n entity_id: input.entity_id,\n source: input.source,\n weight: input.weight ?? 1,\n created_at: new Date().toISOString(),\n })\n .run();\n}\n\nexport function listEntitiesForMemory(db: RecallDb, memoryId: string): EntityRow[] {\n return db\n .select({\n id: entities.id,\n kind: entities.kind,\n name: entities.name,\n normalized_name: entities.normalized_name,\n repo: entities.repo,\n description: entities.description,\n mention_count: entities.mention_count,\n first_seen_memory_id: entities.first_seen_memory_id,\n created_at: entities.created_at,\n updated_at: entities.updated_at,\n })\n .from(memoryEntities)\n .innerJoin(entities, eq(entities.id, memoryEntities.entity_id))\n .where(eq(memoryEntities.memory_id, memoryId))\n .all() as EntityRow[];\n}\n\nexport function listMemoryIdsForEntity(db: RecallDb, entityId: string): string[] {\n const rows = db\n .select({ memory_id: memoryEntities.memory_id })\n .from(memoryEntities)\n .where(eq(memoryEntities.entity_id, entityId))\n .all();\n return rows.map((r) => r.memory_id);\n}\n\nexport interface UpsertRelationInput {\n source_entity_id: string;\n target_entity_id: string;\n relation_type: RelationType;\n source_memory_id?: string | null;\n confidence?: number;\n}\n\n/** Idempotent on (source, target, relation_type, source_memory_id). */\nexport function upsertRelation(db: RecallDb, input: UpsertRelationInput): EntityRelationRow {\n const sourceMem = input.source_memory_id ?? null;\n const existing = db\n .select()\n .from(entityRelations)\n .where(\n and(\n eq(entityRelations.source_entity_id, input.source_entity_id),\n eq(entityRelations.target_entity_id, input.target_entity_id),\n eq(entityRelations.relation_type, input.relation_type),\n sourceMem === null\n ? sql`${entityRelations.source_memory_id} IS NULL`\n : eq(entityRelations.source_memory_id, sourceMem),\n ),\n )\n .get() as EntityRelationRow | undefined;\n if (existing) {\n if (input.confidence !== undefined && input.confidence > existing.confidence) {\n db.update(entityRelations)\n .set({ confidence: input.confidence })\n .where(eq(entityRelations.id, existing.id))\n .run();\n return { ...existing, confidence: input.confidence };\n }\n return existing;\n }\n const id = randomUUID();\n const now = new Date().toISOString();\n db.insert(entityRelations)\n .values({\n id,\n source_entity_id: input.source_entity_id,\n target_entity_id: input.target_entity_id,\n relation_type: input.relation_type,\n source_memory_id: sourceMem,\n confidence: input.confidence ?? 0.6,\n created_at: now,\n })\n .run();\n return {\n id,\n source_entity_id: input.source_entity_id,\n target_entity_id: input.target_entity_id,\n relation_type: input.relation_type,\n source_memory_id: sourceMem,\n confidence: input.confidence ?? 0.6,\n created_at: now,\n };\n}\n\nexport function neighborsOf(\n db: RecallDb,\n entityId: string,\n options: { hops?: number; relationTypes?: RelationType[] } = {},\n): { entities: EntityRow[]; relations: EntityRelationRow[] } {\n const maxHops = Math.max(1, Math.min(5, options.hops ?? 1));\n const visited = new Set<string>([entityId]);\n let frontier = [entityId];\n const collectedRelations = new Map<string, EntityRelationRow>();\n\n for (let hop = 0; hop < maxHops; hop++) {\n if (frontier.length === 0) break;\n const next: string[] = [];\n const relationFilter = options.relationTypes;\n const outgoing = db\n .select()\n .from(entityRelations)\n .where(\n relationFilter && relationFilter.length > 0\n ? and(\n inArray(entityRelations.source_entity_id, frontier),\n inArray(entityRelations.relation_type, relationFilter),\n )\n : inArray(entityRelations.source_entity_id, frontier),\n )\n .all() as EntityRelationRow[];\n const incoming = db\n .select()\n .from(entityRelations)\n .where(\n relationFilter && relationFilter.length > 0\n ? and(\n inArray(entityRelations.target_entity_id, frontier),\n inArray(entityRelations.relation_type, relationFilter),\n )\n : inArray(entityRelations.target_entity_id, frontier),\n )\n .all() as EntityRelationRow[];\n\n for (const rel of [...outgoing, ...incoming]) {\n collectedRelations.set(rel.id, rel);\n for (const candidate of [rel.source_entity_id, rel.target_entity_id]) {\n if (!visited.has(candidate)) {\n visited.add(candidate);\n next.push(candidate);\n }\n }\n }\n frontier = next;\n }\n\n const entityRows = visited.size === 0\n ? []\n : (db\n .select()\n .from(entities)\n .where(inArray(entities.id, Array.from(visited)))\n .all() as EntityRow[]);\n\n return {\n entities: entityRows,\n relations: Array.from(collectedRelations.values()),\n };\n}\n\n/**\n * List every relation in the graph, optionally restricted to relations\n * whose source AND target entities both belong to the given repo. Used by\n * the WebUI to render the whole graph at once (no seed required).\n */\nexport function listAllRelations(\n db: RecallDb,\n opts: { repo?: string; limit?: number } = {},\n): EntityRelationRow[] {\n const limit = Math.min(Math.max(opts.limit ?? 2000, 1), 10_000);\n if (!opts.repo) {\n return db\n .select()\n .from(entityRelations)\n .limit(limit)\n .all() as EntityRelationRow[];\n }\n // Filter both endpoints to entities in the repo. Two-step: collect ids,\n // then pick relations whose endpoints are both inside that set.\n const repoEntityIds = db\n .select({ id: entities.id })\n .from(entities)\n .where(eq(entities.repo, opts.repo))\n .all()\n .map((r) => r.id);\n if (repoEntityIds.length === 0) return [];\n const idSet = new Set(repoEntityIds);\n const all = db\n .select()\n .from(entityRelations)\n .where(\n and(\n inArray(entityRelations.source_entity_id, repoEntityIds),\n inArray(entityRelations.target_entity_id, repoEntityIds),\n ),\n )\n .limit(limit)\n .all() as EntityRelationRow[];\n return all.filter(\n (r) => idSet.has(r.source_entity_id) && idSet.has(r.target_entity_id),\n );\n}\n\nexport function countEntities(db: RecallDb): number {\n const row = db\n .select({ c: sql<number>`count(*)` })\n .from(entities)\n .get();\n return Number(row?.c ?? 0);\n}\n\nexport function countRelations(db: RecallDb): number {\n const row = db\n .select({ c: sql<number>`count(*)` })\n .from(entityRelations)\n .get();\n return Number(row?.c ?? 0);\n}\n\n/**\n * Wipe all graph state (entities, relations, and memory→entity links). Used\n * by `graph backfill --rebuild` to regenerate the graph from scratch under\n * the current extraction rules, dropping entities that older/looser rules\n * produced (e.g. generic `pnpm build` command nodes).\n */\nexport function clearGraph(db: RecallDb): void {\n db.delete(memoryEntities).run();\n db.delete(entityRelations).run();\n db.delete(entities).run();\n}\n","/**\n * Canonical-form helpers for entity dedup. Two entities with the same\n * (kind, normalizedName, repo) collapse into one node.\n *\n * Normalization rules are conservative on purpose — we'd rather have a\n * duplicate than merge two semantically distinct things. Aggressive\n * merging belongs in a maintenance pass that can be reviewed.\n */\n\nexport type EntityKind =\n | \"file\"\n | \"function\"\n | \"library\"\n | \"tool\"\n | \"concept\"\n | \"repo_path\"\n | \"command\"\n | \"url\";\n\nexport function normalizeName(kind: EntityKind, raw: string): string {\n const trimmed = raw.trim();\n switch (kind) {\n case \"file\":\n case \"repo_path\":\n // Posix-style paths, no leading slash, no trailing slash.\n return trimmed\n .replace(/\\\\/g, \"/\")\n .replace(/^[./]+/, \"\")\n .replace(/\\/+$/, \"\")\n .toLowerCase();\n case \"function\":\n // foo() / Class.method / obj.method — keep the dotted form, drop parens/args.\n return trimmed\n .replace(/\\(.*\\)/, \"\")\n .replace(/\\s+/g, \"\")\n .toLowerCase();\n case \"library\":\n case \"tool\":\n case \"command\":\n // package names / CLI names: lowercase, strip @scope leading-only if present\n // but keep `@scope/name` distinct from `name`.\n return trimmed.toLowerCase();\n case \"url\":\n try {\n const u = new URL(trimmed);\n return `${u.hostname.toLowerCase()}${u.pathname.replace(/\\/+$/, \"\")}`;\n } catch {\n return trimmed.toLowerCase();\n }\n case \"concept\":\n default:\n return trimmed.toLowerCase().replace(/\\s+/g, \" \");\n }\n}\n\nexport function isPlausibleEntityName(kind: EntityKind, name: string): boolean {\n const n = name.trim();\n if (n.length === 0 || n.length > 200) return false;\n // Filter common false positives that look like identifiers but aren't.\n if (/^[0-9]+$/.test(n)) return false;\n if (kind === \"concept\" && n.split(/\\s+/).length > 8) return false;\n // Single-letter \"library\" tokens are almost always noise.\n if ((kind === \"library\" || kind === \"tool\") && n.length < 2) return false;\n return true;\n}\n"],"mappings":";;;;;;;;;;;;;AAKA,SAAS,kBAAkB;;;ACcpB,SAAS,cAAc,MAAkB,KAAqB;AACnE,QAAM,UAAU,IAAI,KAAK;AACzB,UAAQ,MAAM;AAAA,IACZ,KAAK;AAAA,IACL,KAAK;AAEH,aAAO,QACJ,QAAQ,OAAO,GAAG,EAClB,QAAQ,UAAU,EAAE,EACpB,QAAQ,QAAQ,EAAE,EAClB,YAAY;AAAA,IACjB,KAAK;AAEH,aAAO,QACJ,QAAQ,UAAU,EAAE,EACpB,QAAQ,QAAQ,EAAE,EAClB,YAAY;AAAA,IACjB,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAGH,aAAO,QAAQ,YAAY;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AkB,aAAa;AAAA,MACvD,QAAQ,gBAAgB,kBAAkB,aAAa;AAAA,IACzD;AAAA,EACF,EACC,MAAM,KAAK,EACX,IAAI;AACP,SAAO,IAAI;AAAA,IACT,CAAC,MAAM,MAAM,IAAI,EAAE,gBAAgB,KAAK,MAAM,IAAI,EAAE,gBAAgB;AAAA,EACtE;AACF;AAEO,SAAS,cAAc,IAAsB;AAClD,QAAM,MAAM,GACT,OAAO,EAAE,GAAG,cAAsB,CAAC,EACnC,KAAK,QAAQ,EACb,IAAI;AACP,SAAO,OAAO,KAAK,KAAK,CAAC;AAC3B;AAEO,SAAS,eAAe,IAAsB;AACnD,QAAM,MAAM,GACT,OAAO,EAAE,GAAG,cAAsB,CAAC,EACnC,KAAK,eAAe,EACpB,IAAI;AACP,SAAO,OAAO,KAAK,KAAK,CAAC;AAC3B;AAQO,SAAS,WAAW,IAAoB;AAC7C,KAAG,OAAO,cAAc,EAAE,IAAI;AAC9B,KAAG,OAAO,eAAe,EAAE,IAAI;AAC/B,KAAG,OAAO,QAAQ,EAAE,IAAI;AAC1B;","names":[]}
@@ -1,12 +1,12 @@
1
1
  import {
2
2
  graphQuery
3
- } from "./chunk-MIRCNPUN.js";
3
+ } from "./chunk-A54CLR5Q.js";
4
4
  import {
5
5
  getEntity,
6
6
  listEntities,
7
7
  listMemoryIdsForEntity,
8
8
  neighborsOf
9
- } from "./chunk-R4G62MKZ.js";
9
+ } from "./chunk-M7OKBKKU.js";
10
10
  import {
11
11
  captureCorrectionFallback,
12
12
  compileContext,
@@ -1197,4 +1197,4 @@ function createRecallMcpServer(db = initDb()) {
1197
1197
  export {
1198
1198
  createRecallMcpServer
1199
1199
  };
1200
- //# sourceMappingURL=chunk-6CSJD45G.js.map
1200
+ //# sourceMappingURL=chunk-OHPGNDSH.js.map
@@ -3,7 +3,7 @@ import {
3
3
  linkMemoryToEntity,
4
4
  upsertEntity,
5
5
  upsertRelation
6
- } from "./chunk-R4G62MKZ.js";
6
+ } from "./chunk-M7OKBKKU.js";
7
7
  import {
8
8
  getMemory
9
9
  } from "./chunk-TPCWQS6Q.js";
@@ -60,9 +60,91 @@ var PACKAGE_STOPWORDS = /* @__PURE__ */ new Set([
60
60
  "info",
61
61
  "error",
62
62
  "ts",
63
- "js"
63
+ "js",
64
+ // Shell / language builtins that look package-shaped in backticks but are
65
+ // not libraries ("echo", "dict", ...).
66
+ "echo",
67
+ "dict",
68
+ "list",
69
+ "set",
70
+ "map",
71
+ "str",
72
+ "int",
73
+ "bool",
74
+ "float",
75
+ "print",
76
+ "println",
77
+ "log",
78
+ "dir",
79
+ "env",
80
+ "tmp",
81
+ "src",
82
+ "lib",
83
+ "bin",
84
+ "out",
85
+ "obj",
86
+ "val",
87
+ "var",
88
+ "let",
89
+ "const",
90
+ "func",
91
+ "def",
92
+ "cls",
93
+ "self",
94
+ "args",
95
+ "kwargs",
96
+ "none",
97
+ "cat",
98
+ "grep",
99
+ "sed",
100
+ "awk",
101
+ "cwd",
102
+ "std"
64
103
  ]);
65
104
  var CLI_RE = /\b(npm|pnpm|yarn|bun|cargo|go|uv|pip|node|deno|claude|codex|cursor|recall|brew|gh|git)\s+([a-z][a-z-]{0,30})\b/g;
105
+ var TOOL_ONLY_CLIS = /* @__PURE__ */ new Set(["npm", "pnpm", "yarn", "bun", "node", "deno"]);
106
+ var CLI_SUBCOMMAND_STOPWORDS = /* @__PURE__ */ new Set([
107
+ "a",
108
+ "an",
109
+ "and",
110
+ "are",
111
+ "as",
112
+ "at",
113
+ "be",
114
+ "by",
115
+ "can",
116
+ "do",
117
+ "does",
118
+ "for",
119
+ "from",
120
+ "has",
121
+ "have",
122
+ "i",
123
+ "if",
124
+ "in",
125
+ "into",
126
+ "is",
127
+ "it",
128
+ "its",
129
+ "no",
130
+ "not",
131
+ "of",
132
+ "on",
133
+ "or",
134
+ "so",
135
+ "that",
136
+ "the",
137
+ "then",
138
+ "this",
139
+ "to",
140
+ "up",
141
+ "via",
142
+ "was",
143
+ "we",
144
+ "will",
145
+ "with",
146
+ "you"
147
+ ]);
66
148
  var URL_RE = /\bhttps?:\/\/[^\s<>"'`)]+/g;
67
149
  var RELATION_CUES = [
68
150
  { rx: /\b(?:replaces?|replaced|supersedes?|superseded|deprecates?|deprecated)\b/i, relation: "replaces" },
@@ -106,8 +188,15 @@ function heuristic(text) {
106
188
  push("library", candidate, 0.7);
107
189
  }
108
190
  for (const m of text.matchAll(CLI_RE)) {
109
- push("tool", m[1]);
110
- push("command", `${m[1]} ${m[2]}`);
191
+ const tool = m[1];
192
+ const sub = m[2];
193
+ if (CLI_SUBCOMMAND_STOPWORDS.has(sub)) {
194
+ push("tool", tool);
195
+ continue;
196
+ }
197
+ push("tool", tool);
198
+ if (TOOL_ONLY_CLIS.has(tool)) continue;
199
+ push("command", `${tool} ${sub}`);
111
200
  }
112
201
  for (const m of text.matchAll(URL_RE)) {
113
202
  push("url", m[0]);
@@ -232,4 +321,4 @@ export {
232
321
  mergeAndIngest,
233
322
  safeIngestMemoryById
234
323
  };
235
- //# sourceMappingURL=chunk-FKZ7IDIY.js.map
324
+ //# sourceMappingURL=chunk-TJGQUY63.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/graph/extractor.ts","../src/graph/ingest.ts"],"sourcesContent":["/**\n * Entity extractor. Pulls entities (files, functions, libraries, tools,\n * concepts, paths, commands, URLs) plus typed relations out of memory text.\n *\n * Two paths:\n * 1. heuristic() — always runs, cheap, regex-based, deterministic.\n * Catches paths, package-like names, identifier-shaped function calls,\n * common CLI tools, URLs. Used on every memory write.\n *\n * 2. llmEnrich() — opt-in; runs when an LLM provider is configured.\n * Reads the memory text + the heuristic seed and returns canonical\n * entity names + relations between them. Drives multi-hop graph walks.\n */\nimport type { RelationType } from \"./store.js\";\nimport type { EntityKind } from \"./normalize.js\";\nimport { isPlausibleEntityName } from \"./normalize.js\";\n\nexport interface ExtractedEntity {\n kind: EntityKind;\n name: string;\n /** 'heuristic' for regex output, 'llm' for model-extracted, 'manual' for user. */\n source: \"heuristic\" | \"llm\" | \"manual\";\n /** Where this mention came from in the source text, if known. */\n weight?: number;\n}\n\nexport interface ExtractedRelation {\n source: { kind: EntityKind; name: string };\n target: { kind: EntityKind; name: string };\n relation: RelationType;\n confidence: number;\n}\n\nexport interface ExtractionResult {\n entities: ExtractedEntity[];\n relations: ExtractedRelation[];\n}\n\n// ---- Heuristic extractor ----------------------------------------------------\n\n// File paths: src/foo/bar.ts, ./scripts/x.sh, docs/README.md\nconst PATH_RE = /(?:^|[\\s`'\"(])((?:\\.{0,2}\\/)?(?:[A-Za-z0-9_.-]+\\/){1,}[A-Za-z0-9_.-]+\\.[A-Za-z0-9]{1,8})/g;\n// Inline-coded short identifiers: `foo()`, `Bar.method()`\nconst FUNC_RE = /`([A-Za-z_][\\w.]{1,}\\(\\))`/g;\n// Package-like names in backticks: `react`, `@scope/pkg`, `drizzle-orm`.\n// Two flavours:\n// - SCOPED_PACKAGE_RE: @scope/name and hyphenated names — high-confidence\n// - SIMPLE_PACKAGE_RE: single lowercase words in backticks — gated by a stop-list\nconst SCOPED_PACKAGE_RE = /`(@[a-z0-9_-]+\\/[a-z0-9_.-]+|[a-z][a-z0-9_-]*(?:-[a-z0-9]+)+)`/g;\nconst SIMPLE_PACKAGE_RE = /`([a-z][a-z0-9_]{2,30})`/g;\n// Common English / generic words that look package-shaped but aren't.\nconst PACKAGE_STOPWORDS = new Set([\n \"the\", \"and\", \"but\", \"for\", \"use\", \"uses\", \"used\", \"with\", \"from\", \"this\",\n \"that\", \"have\", \"has\", \"true\", \"false\", \"null\", \"void\", \"data\", \"code\",\n \"test\", \"tests\", \"build\", \"run\", \"runs\", \"name\", \"type\", \"types\", \"main\",\n \"yes\", \"no\", \"ok\", \"all\", \"any\", \"new\", \"old\", \"more\", \"less\", \"always\",\n \"never\", \"todo\", \"fixme\", \"note\", \"warn\", \"info\", \"error\", \"ts\", \"js\",\n // Shell / language builtins that look package-shaped in backticks but are\n // not libraries (\"echo\", \"dict\", ...).\n \"echo\", \"dict\", \"list\", \"set\", \"map\", \"str\", \"int\", \"bool\", \"float\",\n \"print\", \"println\", \"log\", \"dir\", \"env\", \"tmp\", \"src\", \"lib\", \"bin\",\n \"out\", \"obj\", \"val\", \"var\", \"let\", \"const\", \"func\", \"def\", \"cls\", \"self\",\n \"args\", \"kwargs\", \"none\", \"cat\", \"grep\", \"sed\", \"awk\", \"cwd\", \"std\",\n]);\n// Bare CLI invocation lines: `npm test`, `pnpm i`, `cargo build`\nconst CLI_RE = /\\b(npm|pnpm|yarn|bun|cargo|go|uv|pip|node|deno|claude|codex|cursor|recall|brew|gh|git)\\s+([a-z][a-z-]{0,30})\\b/g;\n// Package managers + runtimes whose `<tool> <word>` pairs are almost always\n// generic build/script noise (\"pnpm build\", \"node dist\", \"npm run\") or English\n// filler grabbed from prose (\"Use pnpm as ...\", \"npm install\" → \"npm in\").\n// For these we record the tool itself but never a `command` entity.\nconst TOOL_ONLY_CLIS = new Set([\"npm\", \"pnpm\", \"yarn\", \"bun\", \"node\", \"deno\"]);\n// Second tokens that are English filler, not real subcommands — reject the\n// whole match so we don't mint entities like \"pnpm as\" or \"git it\".\nconst CLI_SUBCOMMAND_STOPWORDS = new Set([\n \"a\", \"an\", \"and\", \"are\", \"as\", \"at\", \"be\", \"by\", \"can\", \"do\", \"does\", \"for\",\n \"from\", \"has\", \"have\", \"i\", \"if\", \"in\", \"into\", \"is\", \"it\", \"its\", \"no\",\n \"not\", \"of\", \"on\", \"or\", \"so\", \"that\", \"the\", \"then\", \"this\", \"to\", \"up\",\n \"via\", \"was\", \"we\", \"will\", \"with\", \"you\",\n]);\n// URLs\nconst URL_RE = /\\bhttps?:\\/\\/[^\\s<>\"'`)]+/g;\n\n// Relation keyword cues. Order matters — first match wins for a sentence.\nconst RELATION_CUES: Array<{ rx: RegExp; relation: RelationType; flip?: boolean }> = [\n { rx: /\\b(?:replaces?|replaced|supersedes?|superseded|deprecates?|deprecated)\\b/i, relation: \"replaces\" },\n { rx: /\\b(?:conflicts? with|incompatible with|clashes? with)\\b/i, relation: \"conflicts_with\" },\n { rx: /\\b(?:tested by|covered by)\\b/i, relation: \"tested_by\" },\n { rx: /\\b(?:depends on|requires|required by)\\b/i, relation: \"depends_on\" },\n { rx: /\\b(?:uses?|used|relies on|via)\\b/i, relation: \"uses\" },\n { rx: /\\b(?:references?|see also|cf\\.)\\b/i, relation: \"references\" },\n { rx: /\\b(?:part of|inside|under)\\b/i, relation: \"part_of\" },\n];\n\nexport function heuristic(text: string): ExtractionResult {\n const entities = new Map<string, ExtractedEntity>(); // dedupe by (kind|name)\n const relations: ExtractedRelation[] = [];\n\n const push = (kind: EntityKind, name: string, weight = 1) => {\n if (!isPlausibleEntityName(kind, name)) return;\n const key = `${kind}|${name}`;\n const existing = entities.get(key);\n if (existing) {\n existing.weight = (existing.weight ?? 1) + weight;\n } else {\n entities.set(key, { kind, name, source: \"heuristic\", weight });\n }\n };\n\n // Files / paths\n for (const m of text.matchAll(PATH_RE)) {\n const raw = m[1];\n // Discriminate `repo_path` (no extension) vs `file` — both produce graph\n // nodes, but only `file` is treated as a file-system artifact.\n if (raw.includes(\".\") && !raw.endsWith(\"/\")) {\n push(\"file\", raw);\n } else {\n push(\"repo_path\", raw);\n }\n }\n\n // Functions in backticks\n for (const m of text.matchAll(FUNC_RE)) {\n push(\"function\", m[1]);\n }\n\n // Packages in backticks — scoped/hyphenated first (high confidence)\n for (const m of text.matchAll(SCOPED_PACKAGE_RE)) {\n push(\"library\", m[1]);\n }\n // Single-word backticked tokens, filtered by stop-list\n for (const m of text.matchAll(SIMPLE_PACKAGE_RE)) {\n const candidate = m[1];\n if (PACKAGE_STOPWORDS.has(candidate)) continue;\n push(\"library\", candidate, 0.7);\n }\n\n // CLI commands\n for (const m of text.matchAll(CLI_RE)) {\n const tool = m[1];\n const sub = m[2];\n // English filler after the tool (\"pnpm as\", \"npm in\") is not a command.\n if (CLI_SUBCOMMAND_STOPWORDS.has(sub)) {\n push(\"tool\", tool);\n continue;\n }\n push(\"tool\", tool);\n // Package managers / runtimes: the `<tool> <script>` pair is generic\n // tooling noise (\"pnpm build\", \"node dist\"). Keep only the tool node.\n if (TOOL_ONLY_CLIS.has(tool)) continue;\n push(\"command\", `${tool} ${sub}`);\n }\n\n // URLs\n for (const m of text.matchAll(URL_RE)) {\n push(\"url\", m[0]);\n }\n\n // Relations: split into sentences, look for a cue + two entity mentions.\n const sentences = text.split(/(?<=[.!?])\\s+|\\n+/);\n for (const sentence of sentences) {\n const cue = RELATION_CUES.find((c) => c.rx.test(sentence));\n if (!cue) continue;\n const mentioned: Array<{ kind: EntityKind; name: string; idx: number }> = [];\n for (const ent of entities.values()) {\n const idx = sentence.indexOf(ent.name);\n if (idx >= 0) mentioned.push({ kind: ent.kind, name: ent.name, idx });\n }\n if (mentioned.length < 2) continue;\n mentioned.sort((a, b) => a.idx - b.idx);\n relations.push({\n source: { kind: mentioned[0].kind, name: mentioned[0].name },\n target: { kind: mentioned[1].kind, name: mentioned[1].name },\n relation: cue.relation,\n confidence: 0.5,\n });\n }\n\n return { entities: Array.from(entities.values()), relations };\n}\n\n// ---- LLM enrichment --------------------------------------------------------\n\nexport const ENTITY_EXTRACTION_SYSTEM = `You extract code-graph entities and typed relations from short engineering notes (rules, decisions, gotchas).\n\nReturn STRICT JSON only — no prose, no fences. Shape:\n{\n \"entities\": [{\"kind\": \"<one of: file|function|library|tool|concept|repo_path|command|url>\", \"name\": \"<canonical surface form>\"}],\n \"relations\": [{\"source\": {\"kind\": \"...\", \"name\": \"...\"}, \"target\": {\"kind\": \"...\", \"name\": \"...\"}, \"relation\": \"<one of: uses|replaces|conflicts_with|tested_by|depends_on|references|part_of>\", \"confidence\": 0.0-1.0}]\n}\n\nRules:\n- Only include entities the text actually mentions. Do NOT invent.\n- Prefer the most specific kind: a file path is \"file\", a library name is \"library\", a CLI like \"npm install\" is \"command\".\n- \"concept\" is a last resort for domain words (\"authentication\", \"rate limiting\").\n- Skip generic English (pronouns, verbs, adjectives).\n- If the text is purely about user preferences or behaviour with no nameable artifact, return {\"entities\": [], \"relations\": []}.\n- Be conservative on relations — only include one when the text clearly states it.`;\n\nexport interface LlmExtractInput {\n memoryText: string;\n /** Optional seed list from the heuristic pass — saves the LLM a step. */\n seed?: ExtractedEntity[];\n}\n\nexport function buildExtractionPrompt(input: LlmExtractInput): string {\n const seedBlock = input.seed && input.seed.length > 0\n ? `\\n\\nHeuristic seed (use as hints, refine or override):\\n${input.seed\n .slice(0, 20)\n .map((e) => `- ${e.kind}: ${e.name}`)\n .join(\"\\n\")}`\n : \"\";\n return `Memory text:\\n\"\"\"\\n${input.memoryText}\\n\"\"\"${seedBlock}\\n\\nReturn STRICT JSON.`;\n}\n\n/**\n * Parse the LLM response into an ExtractionResult, tolerating fenced code\n * and surrounding prose. Returns null if no valid shape is recognised.\n */\nexport function parseLlmExtraction(raw: string): ExtractionResult | null {\n let text = raw.trim();\n // Strip code fences if present\n const fenceMatch = text.match(/```(?:json)?\\s*([\\s\\S]+?)\\s*```/);\n if (fenceMatch) text = fenceMatch[1].trim();\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n return null;\n }\n if (typeof parsed !== \"object\" || parsed === null) return null;\n const obj = parsed as Record<string, unknown>;\n const entities = sanitiseEntities(obj.entities);\n const relations = sanitiseRelations(obj.relations);\n return { entities, relations };\n}\n\nconst VALID_KINDS: ReadonlySet<EntityKind> = new Set<EntityKind>([\n \"file\", \"function\", \"library\", \"tool\", \"concept\", \"repo_path\", \"command\", \"url\",\n]);\nconst VALID_RELATIONS: ReadonlySet<RelationType> = new Set<RelationType>([\n \"uses\", \"replaces\", \"conflicts_with\", \"tested_by\", \"depends_on\", \"references\", \"part_of\",\n]);\n\nfunction sanitiseEntities(raw: unknown): ExtractedEntity[] {\n if (!Array.isArray(raw)) return [];\n const out: ExtractedEntity[] = [];\n for (const item of raw) {\n if (!item || typeof item !== \"object\") continue;\n const o = item as Record<string, unknown>;\n const kind = String(o.kind ?? \"\");\n const name = String(o.name ?? \"\").trim();\n if (!VALID_KINDS.has(kind as EntityKind)) continue;\n if (!isPlausibleEntityName(kind as EntityKind, name)) continue;\n out.push({ kind: kind as EntityKind, name, source: \"llm\" });\n }\n return out;\n}\n\nfunction sanitiseRelations(raw: unknown): ExtractedRelation[] {\n if (!Array.isArray(raw)) return [];\n const out: ExtractedRelation[] = [];\n for (const item of raw) {\n if (!item || typeof item !== \"object\") continue;\n const o = item as Record<string, unknown>;\n const rel = String(o.relation ?? \"\");\n if (!VALID_RELATIONS.has(rel as RelationType)) continue;\n const source = parseEndpoint(o.source);\n const target = parseEndpoint(o.target);\n if (!source || !target) continue;\n const confidence = typeof o.confidence === \"number\"\n ? Math.max(0, Math.min(1, o.confidence))\n : 0.6;\n out.push({ source, target, relation: rel as RelationType, confidence });\n }\n return out;\n}\n\nfunction parseEndpoint(raw: unknown): { kind: EntityKind; name: string } | null {\n if (!raw || typeof raw !== \"object\") return null;\n const o = raw as Record<string, unknown>;\n const kind = String(o.kind ?? \"\");\n const name = String(o.name ?? \"\").trim();\n if (!VALID_KINDS.has(kind as EntityKind)) return null;\n if (!isPlausibleEntityName(kind as EntityKind, name)) return null;\n return { kind: kind as EntityKind, name };\n}\n\n/**\n * Merge a heuristic pass with an LLM pass. LLM entries override heuristic\n * ones on the same (kind, name) — the model's source tag takes precedence\n * because it's the higher-quality signal.\n */\nexport function mergeExtractions(...passes: ExtractionResult[]): ExtractionResult {\n const entities = new Map<string, ExtractedEntity>();\n for (const pass of passes) {\n for (const ent of pass.entities) {\n const key = `${ent.kind}|${ent.name}`;\n const prev = entities.get(key);\n if (!prev || (prev.source === \"heuristic\" && ent.source === \"llm\")) {\n entities.set(key, ent);\n }\n }\n }\n // Deduplicate relations on (source, target, relation).\n const relations = new Map<string, ExtractedRelation>();\n for (const pass of passes) {\n for (const rel of pass.relations) {\n const key = `${rel.source.kind}|${rel.source.name}->${rel.relation}->${rel.target.kind}|${rel.target.name}`;\n const prev = relations.get(key);\n if (!prev || rel.confidence > prev.confidence) {\n relations.set(key, rel);\n }\n }\n }\n return {\n entities: Array.from(entities.values()),\n relations: Array.from(relations.values()),\n };\n}\n","/**\n * Glue: take a memory row, extract entities, persist them into the graph.\n *\n * The heuristic pass always runs (cheap, deterministic). The LLM enrichment\n * pass is left to the maintenance dispatcher — capture-path latency stays\n * regex-bounded, the graph fills in asynchronously.\n */\nimport type { RecallDb } from \"../db/client.js\";\nimport { getMemory } from \"../models/memory.js\";\nimport {\n heuristic,\n mergeExtractions,\n type ExtractionResult,\n} from \"./extractor.js\";\nimport {\n upsertEntity,\n linkMemoryToEntity,\n upsertRelation,\n type EntityRow,\n type EntityRelationRow,\n} from \"./store.js\";\n\nexport interface IngestSummary {\n memory_id: string;\n entities_created_or_updated: number;\n relations_created_or_updated: number;\n}\n\nexport interface MemoryLike {\n id: string;\n text: string;\n repo: string | null;\n}\n\n/**\n * Run the heuristic extractor on a memory and persist entities + relations.\n * Idempotent: calling twice for the same memory bumps mention counts but\n * does not duplicate rows. Safe to call from capture-path hot code.\n */\nexport function ingestMemoryHeuristic(db: RecallDb, memory: MemoryLike): IngestSummary {\n const extraction = heuristic(memory.text);\n return persistExtraction(db, memory, extraction);\n}\n\n/**\n * Apply a pre-computed ExtractionResult (e.g. from an LLM pass merged with\n * the heuristic pass) for a memory. Used by the maintenance dispatcher.\n */\nexport function ingestMemoryExtraction(\n db: RecallDb,\n memory: MemoryLike,\n extraction: ExtractionResult,\n): IngestSummary {\n return persistExtraction(db, memory, extraction);\n}\n\nexport function mergeAndIngest(\n db: RecallDb,\n memory: MemoryLike,\n passes: ExtractionResult[],\n): IngestSummary {\n return persistExtraction(db, memory, mergeExtractions(...passes));\n}\n\nfunction persistExtraction(\n db: RecallDb,\n memory: MemoryLike,\n extraction: ExtractionResult,\n): IngestSummary {\n const entityIndex = new Map<string, EntityRow>(); // dedupe by (kind|normalized) for relation lookup\n let entitiesTouched = 0;\n for (const ent of extraction.entities) {\n const row = upsertEntity(db, {\n kind: ent.kind,\n name: ent.name,\n repo: memory.repo,\n first_seen_memory_id: memory.id,\n });\n entityIndex.set(`${row.kind}|${row.normalized_name}`, row);\n linkMemoryToEntity(db, {\n memory_id: memory.id,\n entity_id: row.id,\n source: ent.source,\n weight: ent.weight,\n });\n entitiesTouched++;\n }\n\n let relationsTouched = 0;\n const lookupRow = (kind: string, name: string): EntityRow | undefined => {\n // upsertEntity normalizes internally, so we have to mirror that to look up\n // by the index key. Skip if the related entity wasn't in this batch.\n for (const row of entityIndex.values()) {\n if (row.kind === kind && row.name === name) return row;\n }\n return undefined;\n };\n\n for (const rel of extraction.relations) {\n const src = lookupRow(rel.source.kind, rel.source.name)\n ?? upsertEntity(db, { kind: rel.source.kind, name: rel.source.name, repo: memory.repo });\n const tgt = lookupRow(rel.target.kind, rel.target.name)\n ?? upsertEntity(db, { kind: rel.target.kind, name: rel.target.name, repo: memory.repo });\n if (src.id === tgt.id) continue;\n upsertRelation(db, {\n source_entity_id: src.id,\n target_entity_id: tgt.id,\n relation_type: rel.relation,\n source_memory_id: memory.id,\n confidence: rel.confidence,\n });\n relationsTouched++;\n }\n\n return {\n memory_id: memory.id,\n entities_created_or_updated: entitiesTouched,\n relations_created_or_updated: relationsTouched,\n };\n}\n\n/**\n * Best-effort heuristic ingest by memory id. Used by capture-path callers\n * (daemon /correct, /review, /scan) that want graph ingest to be a no-op on\n * failure rather than aborting the originating request.\n *\n * Returns the summary on success, `null` if the memory was not found, or\n * `null` if any error was swallowed.\n */\nexport function safeIngestMemoryById(db: RecallDb, memoryId: string): IngestSummary | null {\n try {\n const mem = getMemory(db, memoryId);\n if (!mem) return null;\n return ingestMemoryHeuristic(db, { id: mem.id, text: mem.text, repo: mem.repo });\n } catch (err) {\n console.error(`[recall] graph ingest failed for ${memoryId}:`, err);\n return null;\n }\n}\n\n// Re-export the row types so callers don't have to know about the\n// store layer's internal naming.\nexport type { EntityRow, EntityRelationRow };\n"],"mappings":";;;;;;;;;;;AAyCA,IAAM,UAAU;AAEhB,IAAM,UA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AM,MAAM,UAAU,IAAI,OAAO,MAAM,IAAI,OAAO,IAAI,KACjD,aAAa,IAAI,EAAE,MAAM,IAAI,OAAO,MAAM,MAAM,IAAI,OAAO,MAAM,MAAM,OAAO,KAAK,CAAC;AACzF,UAAM,MAAM,UAAU,IAAI,OAAO,MAAM,IAAI,OAAO,IAAI,KACjD,aAAa,IAAI,EAAE,MAAM,IAAI,OAAO,MAAM,MAAM,IAAI,OAAO,MAAM,MAAM,OAAO,KAAK,CAAC;AACzF,QAAI,IAAI,OAAO,IAAI,GAAI;AACvB,mBAAe,IAAI;AAAA,MACjB,kBAAkB,IAAI;AAAA,MACtB,kBAAkB,IAAI;AAAA,MACtB,eAAe,IAAI;AAAA,MACnB,kBAAkB,OAAO;AAAA,MACzB,YAAY,IAAI;AAAA,IAClB,CAAC;AACD;AAAA,EACF;AAEA,SAAO;AAAA,IACL,WAAW,OAAO;AAAA,IAClB,6BAA6B;AAAA,IAC7B,8BAA8B;AAAA,EAChC;AACF;AAUO,SAAS,qBAAqB,IAAc,UAAwC;AACzF,MAAI;AACF,UAAM,MAAM,UAAU,IAAI,QAAQ;AAClC,QAAI,CAAC,IAAK,QAAO;AACjB,WAAO,sBAAsB,IAAI,EAAE,IAAI,IAAI,IAAI,MAAM,IAAI,MAAM,MAAM,IAAI,KAAK,CAAC;AAAA,EACjF,SAAS,KAAK;AACZ,YAAQ,MAAM,oCAAoC,QAAQ,KAAK,GAAG;AAClE,WAAO;AAAA,EACT;AACF;","names":[]}
package/dist/cli.js CHANGED
@@ -3538,13 +3538,18 @@ uiCmd.command("status").description("Show WebUI status").option("--daemon-port <
3538
3538
  var graphCmd = program.command("graph").description("Inspect and rebuild the knowledge graph (entities + relations)");
3539
3539
  graphCmd.command("stats").description("Show entity/relation counts").action(async () => {
3540
3540
  const db = initDb();
3541
- const { countEntities, countRelations } = await import("./store-QLWSC7S4.js");
3541
+ const { countEntities, countRelations } = await import("./store-OPRTGS73.js");
3542
3542
  console.log(`entities: ${countEntities(db)}`);
3543
3543
  console.log(`relations: ${countRelations(db)}`);
3544
3544
  });
3545
- graphCmd.command("backfill").description("Run the heuristic extractor over every active memory (idempotent)").option("--repo <repo>", "Limit to a single repo").option("--limit <n>", "Cap rows processed", "10000").action(async (opts) => {
3545
+ graphCmd.command("backfill").description("Run the heuristic extractor over every active memory (idempotent)").option("--repo <repo>", "Limit to a single repo").option("--limit <n>", "Cap rows processed", "10000").option("--rebuild", "Clear all existing entities/relations first, then re-extract").action(async (opts) => {
3546
3546
  const db = initDb();
3547
- const { ingestMemoryHeuristic } = await import("./ingest-55ISNXYX.js");
3547
+ const { ingestMemoryHeuristic } = await import("./ingest-V73EAXSX.js");
3548
+ if (opts.rebuild) {
3549
+ const { clearGraph } = await import("./store-OPRTGS73.js");
3550
+ clearGraph(db);
3551
+ console.log("Cleared existing graph entities and relations.");
3552
+ }
3548
3553
  const rows = queryMemories(db, {
3549
3554
  repo: opts.repo,
3550
3555
  status: "active",
@@ -3563,7 +3568,7 @@ graphCmd.command("backfill").description("Run the heuristic extractor over every
3563
3568
  });
3564
3569
  graphCmd.command("entities").description("List entities").option("--repo <repo>", "Filter by repo").option("--kind <kind>", "Filter by entity kind").option("--search <q>", "Substring filter on name").option("--limit <n>", "Max rows", "50").action(async (opts) => {
3565
3570
  const db = initDb();
3566
- const { listEntities } = await import("./store-QLWSC7S4.js");
3571
+ const { listEntities } = await import("./store-OPRTGS73.js");
3567
3572
  const rows = listEntities(db, {
3568
3573
  repo: opts.repo,
3569
3574
  kind: opts.kind,
@@ -3582,7 +3587,7 @@ graphCmd.command("entities").description("List entities").option("--repo <repo>"
3582
3587
  });
3583
3588
  graphCmd.command("query <query...>").description("Run graph-aware retrieval for a query").option("--repo <repo>", "Restrict to repo").option("--hops <n>", "Graph hops", "2").option("--limit <n>", "Max hits", "10").action(async (queryTokens, opts) => {
3584
3589
  const db = initDb();
3585
- const { graphQuery } = await import("./retrieval-M566ZUK5.js");
3590
+ const { graphQuery } = await import("./retrieval-KOMACG36.js");
3586
3591
  const { loadEmbeddingConfigFromEnv: loadEmbeddingConfigFromEnv2 } = await import("./embeddings-5ARZAEM5.js");
3587
3592
  const embeddingConfig = loadEmbeddingConfigFromEnv2();
3588
3593
  const result = await graphQuery(db, queryTokens.join(" "), embeddingConfig, {