@remnic/core 9.3.656 → 9.3.658
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/dist/access-cli.js +12 -12
- package/dist/access-http.js +6 -6
- package/dist/access-mcp.js +5 -5
- package/dist/access-service.js +4 -4
- package/dist/briefing.d.ts +1 -1
- package/dist/briefing.js +2 -2
- package/dist/causal-consolidation.js +3 -3
- package/dist/{chunk-YEZHZCUO.js → chunk-2VCTTEJM.js} +3 -3
- package/dist/{chunk-DR67OK4E.js → chunk-3R6OP33G.js} +3 -3
- package/dist/{chunk-JSVFEHLL.js → chunk-46RXRASB.js} +2 -2
- package/dist/{chunk-NXCK7DO7.js → chunk-4PLOQDBB.js} +54 -18
- package/dist/chunk-4PLOQDBB.js.map +1 -0
- package/dist/{chunk-54XF2FY7.js → chunk-5PFIMBJJ.js} +12 -12
- package/dist/{chunk-4UL7VPTD.js → chunk-6M4LYWA2.js} +4 -4
- package/dist/{chunk-DIBWFCLA.js → chunk-7KSPKZIQ.js} +3 -3
- package/dist/{chunk-RDW5G6DO.js → chunk-7VWDC7AD.js} +10 -11
- package/dist/chunk-7VWDC7AD.js.map +1 -0
- package/dist/{chunk-SWDHVH2P.js → chunk-BKRIAXTU.js} +2 -2
- package/dist/{chunk-WWMHAMAY.js → chunk-BNUAOLDK.js} +2 -2
- package/dist/{chunk-GCYFUTUC.js → chunk-FIS5RT6K.js} +2 -2
- package/dist/{chunk-IOZ5WBWD.js → chunk-G2VVBWFU.js} +7 -5
- package/dist/chunk-G2VVBWFU.js.map +1 -0
- package/dist/{chunk-GSHW5VVD.js → chunk-GGL7R2L2.js} +4 -4
- package/dist/{chunk-WIKMCJUR.js → chunk-JI3LQFJH.js} +2 -2
- package/dist/{chunk-Z6UDTNY6.js → chunk-KI6QM5AV.js} +6 -6
- package/dist/chunk-KI6QM5AV.js.map +1 -0
- package/dist/{chunk-2BD7DG37.js → chunk-MBZAESQ3.js} +2 -2
- package/dist/{chunk-VAEAGTEQ.js → chunk-QFKRE7AU.js} +3 -3
- package/dist/{chunk-AGJKWOKV.js → chunk-RVT6U6PV.js} +2 -2
- package/dist/{chunk-TFFZUFEP.js → chunk-VJYFXDCZ.js} +2 -2
- package/dist/{chunk-QZRKNA5F.js → chunk-ZCMO46YY.js} +2 -2
- package/dist/cli.js +15 -15
- package/dist/compounding/engine.js +2 -2
- package/dist/connectors/codex-materialize-runner.js +2 -2
- package/dist/connectors/index.js +2 -2
- package/dist/entity-retrieval.js +2 -2
- package/dist/index.js +20 -20
- package/dist/maintenance/memory-governance.js +2 -2
- package/dist/maintenance/rebuild-memory-lifecycle-ledger.js +2 -2
- package/dist/maintenance/rebuild-memory-projection.js +3 -3
- package/dist/namespaces/migrate.js +3 -3
- package/dist/namespaces/storage.js +2 -2
- package/dist/operator-toolkit.js +5 -5
- package/dist/orchestrator.js +10 -10
- package/dist/schemas.d.ts +22 -22
- package/dist/semantic-consolidation.js +3 -3
- package/dist/semantic-rule-promotion.js +2 -2
- package/dist/semantic-rule-verifier.js +2 -2
- package/dist/storage.d.ts +27 -5
- package/dist/storage.js +1 -1
- package/dist/transfer/types.d.ts +12 -12
- package/dist/verified-recall.js +2 -2
- package/package.json +1 -1
- package/src/briefing.ts +8 -4
- package/src/entity-retrieval.ts +8 -3
- package/src/orchestrator.ts +1 -2
- package/src/storage.ts +79 -26
- package/dist/chunk-IOZ5WBWD.js.map +0 -1
- package/dist/chunk-NXCK7DO7.js.map +0 -1
- package/dist/chunk-RDW5G6DO.js.map +0 -1
- package/dist/chunk-Z6UDTNY6.js.map +0 -1
- /package/dist/{chunk-YEZHZCUO.js.map → chunk-2VCTTEJM.js.map} +0 -0
- /package/dist/{chunk-DR67OK4E.js.map → chunk-3R6OP33G.js.map} +0 -0
- /package/dist/{chunk-JSVFEHLL.js.map → chunk-46RXRASB.js.map} +0 -0
- /package/dist/{chunk-54XF2FY7.js.map → chunk-5PFIMBJJ.js.map} +0 -0
- /package/dist/{chunk-4UL7VPTD.js.map → chunk-6M4LYWA2.js.map} +0 -0
- /package/dist/{chunk-DIBWFCLA.js.map → chunk-7KSPKZIQ.js.map} +0 -0
- /package/dist/{chunk-SWDHVH2P.js.map → chunk-BKRIAXTU.js.map} +0 -0
- /package/dist/{chunk-WWMHAMAY.js.map → chunk-BNUAOLDK.js.map} +0 -0
- /package/dist/{chunk-GCYFUTUC.js.map → chunk-FIS5RT6K.js.map} +0 -0
- /package/dist/{chunk-GSHW5VVD.js.map → chunk-GGL7R2L2.js.map} +0 -0
- /package/dist/{chunk-WIKMCJUR.js.map → chunk-JI3LQFJH.js.map} +0 -0
- /package/dist/{chunk-2BD7DG37.js.map → chunk-MBZAESQ3.js.map} +0 -0
- /package/dist/{chunk-VAEAGTEQ.js.map → chunk-QFKRE7AU.js.map} +0 -0
- /package/dist/{chunk-AGJKWOKV.js.map → chunk-RVT6U6PV.js.map} +0 -0
- /package/dist/{chunk-TFFZUFEP.js.map → chunk-VJYFXDCZ.js.map} +0 -0
- /package/dist/{chunk-QZRKNA5F.js.map → chunk-ZCMO46YY.js.map} +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
runPostConsolidationMaterialize
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-BNUAOLDK.js";
|
|
4
4
|
import {
|
|
5
5
|
discoverMemoryExtensions,
|
|
6
6
|
renderExtensionsBlock,
|
|
@@ -217,4 +217,4 @@ export {
|
|
|
217
217
|
buildExtensionsBlockForConsolidation,
|
|
218
218
|
materializeAfterSemanticConsolidation
|
|
219
219
|
};
|
|
220
|
-
//# sourceMappingURL=chunk-
|
|
220
|
+
//# sourceMappingURL=chunk-BKRIAXTU.js.map
|
|
@@ -7,7 +7,7 @@ import {
|
|
|
7
7
|
} from "./chunk-3UXOZBHV.js";
|
|
8
8
|
import {
|
|
9
9
|
StorageManager
|
|
10
|
-
} from "./chunk-
|
|
10
|
+
} from "./chunk-4PLOQDBB.js";
|
|
11
11
|
import {
|
|
12
12
|
isSafeRouteNamespace
|
|
13
13
|
} from "./chunk-U3PN77QT.js";
|
|
@@ -118,4 +118,4 @@ export {
|
|
|
118
118
|
runCodexMaterialize,
|
|
119
119
|
runPostConsolidationMaterialize
|
|
120
120
|
};
|
|
121
|
-
//# sourceMappingURL=chunk-
|
|
121
|
+
//# sourceMappingURL=chunk-BNUAOLDK.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
StorageManager
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-4PLOQDBB.js";
|
|
4
4
|
|
|
5
5
|
// src/semantic-rule-promotion.ts
|
|
6
6
|
import { createHash, randomUUID } from "crypto";
|
|
@@ -529,4 +529,4 @@ export {
|
|
|
529
529
|
setSemanticRulePromotionTestHooks,
|
|
530
530
|
promoteSemanticRuleFromMemory
|
|
531
531
|
};
|
|
532
|
-
//# sourceMappingURL=chunk-
|
|
532
|
+
//# sourceMappingURL=chunk-FIS5RT6K.js.map
|
|
@@ -4,7 +4,7 @@ import {
|
|
|
4
4
|
import {
|
|
5
5
|
compareEntityTimestamps,
|
|
6
6
|
normalizeEntityName
|
|
7
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-4PLOQDBB.js";
|
|
8
8
|
import {
|
|
9
9
|
sanitizeMemoryContent
|
|
10
10
|
} from "./chunk-FVQJYWH7.js";
|
|
@@ -336,11 +336,13 @@ async function buildEntityMentionIndex(storage, config, recallNamespaces, namesp
|
|
|
336
336
|
Promise.all(storages.map((scopedStorage) => scopedStorage.readAllMemories())),
|
|
337
337
|
readNativeChunks(config, recallNamespaces)
|
|
338
338
|
]);
|
|
339
|
-
const
|
|
339
|
+
const entityRecords = entityFileSets.flatMap(
|
|
340
|
+
(set, index2) => set.map((entity) => ({ entity, aliases: storages[index2].entityAliases }))
|
|
341
|
+
);
|
|
340
342
|
const memories = memorySets.flat();
|
|
341
343
|
const entities = /* @__PURE__ */ new Map();
|
|
342
|
-
for (const entity of
|
|
343
|
-
const canonicalId = normalizeEntityName(entity.name, entity.type);
|
|
344
|
+
for (const { entity, aliases } of entityRecords) {
|
|
345
|
+
const canonicalId = normalizeEntityName(entity.name, entity.type, aliases);
|
|
344
346
|
const rawStructuredSections = entity.structuredSections ?? [];
|
|
345
347
|
const rawBeliefLedgerFactKeys = beliefLedgerFactKeys(rawStructuredSections);
|
|
346
348
|
const sanitizedFacts = entity.facts.map((fact) => sanitizeEntityFact(fact)).filter(Boolean).filter((fact) => !rawBeliefLedgerFactKeys.has(normalizeEntityText(fact))).map((fact) => compactLine(fact, 180));
|
|
@@ -677,4 +679,4 @@ export {
|
|
|
677
679
|
entityIndexVersion,
|
|
678
680
|
entityRecentTranscriptLookbackHours
|
|
679
681
|
};
|
|
680
|
-
//# sourceMappingURL=chunk-
|
|
682
|
+
//# sourceMappingURL=chunk-G2VVBWFU.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/entity-retrieval.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport { sanitizeMemoryContent } from \"./sanitize.js\";\nimport { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { collectNativeKnowledgeChunks, type NativeKnowledgeChunk } from \"./native-knowledge.js\";\nimport { compareEntityTimestamps, normalizeEntityName, type StorageManager } from \"./storage.js\";\nimport { normalizeEntityText, resolveRequestedEntitySectionKeys } from \"./entity-schema.js\";\nimport type { EntityStructuredSection, MemoryFile, PluginConfig, TranscriptEntry } from \"./types.js\";\n\nconst ENTITY_INDEX_VERSION = 3;\nconst RECENT_TRANSCRIPT_LOOKBACK_HOURS = 24;\nconst INSTRUCTION_LIKE_RE = /\\b(always|never|must|should|remember to|do not|don't|process|workflow|template|checklist|instruction)\\b/i;\nconst METADATA_WRAPPER_RE = /^(source|context|metadata|notes?):/i;\nconst ENTITY_PRONOUN_RE = /\\b(he|him|his|she|her|they|them|their|it|its)\\b/i;\nconst BELIEF_LEDGER_SECTION_KEY = \"belief_ledger\";\nconst BELIEF_LEDGER_FACT_RE = /^claim=([^;]+);\\s*status=([^;]+);\\s*updatedAt=([^;]+);\\s*(.+)$/;\n\ntype EntityQueryMode = \"direct\" | \"timeline\" | \"follow_up\";\n\ntype EntityMentionIndexEntry = {\n canonicalId: string;\n name: string;\n type: string;\n aliases: string[];\n summary?: string;\n facts: string[];\n timelineFacts: string[];\n structuredSections: EntityStructuredSection[];\n timeline: Array<{\n timestamp: string;\n text: string;\n source?: string;\n sessionKey?: string;\n principal?: string;\n }>;\n relationships: Array<{ target: string; label: string }>;\n activity: Array<{ date: string; note: string }>;\n factCount: number;\n memorySnippets: string[];\n nativeChunks: Array<{\n chunkId: string;\n title: string;\n sourceKind: NativeKnowledgeChunk[\"sourceKind\"];\n sourcePath: string;\n snippet: string;\n derivedDate?: string;\n }>;\n};\n\ntype EntityMentionIndex = {\n version: number;\n updatedAt: string;\n entities: EntityMentionIndexEntry[];\n};\n\ntype EntityCandidate = {\n entry: EntityMentionIndexEntry;\n alias: string;\n score: number;\n source: \"query\" | \"recent_turn\";\n};\n\ntype EntityHintSnippet = {\n text: string;\n score: number;\n kind: \"summary\" | \"fact\" | \"section\" | \"relationship\" | \"activity\" | \"memory\" | \"native\";\n};\n\nexport interface BuildEntityRecallSectionOptions {\n config: PluginConfig;\n storage: StorageManager;\n namespaceStorage?: (namespace: string) => Promise<StorageManager>;\n query: string;\n recallNamespaces?: string[];\n recentTurns: number;\n maxHints: number;\n maxSupportingFacts: number;\n maxRelatedEntities: number;\n maxChars: number;\n transcriptEntries: TranscriptEntry[];\n}\n\nfunction tokenize(value: string): string[] {\n return normalizeEntityText(value).split(/\\s+/).filter((token) => token.length >= 2);\n}\n\nfunction uniqueStrings(values: string[]): string[] {\n return [...new Set(values.map((value) => value.trim()).filter((value) => value.length > 0))];\n}\n\nfunction containsPhrase(haystack: string, needle: string): boolean {\n if (!needle) return false;\n const escaped = needle.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n return new RegExp(`(^|\\\\b)${escaped}(\\\\b|$)`, \"i\").test(haystack);\n}\n\nfunction compactLine(value: string, maxLength: number = 220): string {\n const normalized = value.replace(/\\s+/g, \" \").trim();\n if (normalized.length <= maxLength) return normalized;\n return `${normalized.slice(0, Math.max(0, maxLength - 1)).trimEnd()}…`;\n}\n\nfunction dedupeHintSnippetsByText(snippets: EntityHintSnippet[]): EntityHintSnippet[] {\n const seen = new Set<string>();\n const result: EntityHintSnippet[] = [];\n for (const snippet of snippets) {\n const key = normalizeEntityText(snippet.text);\n if (seen.has(key)) continue;\n seen.add(key);\n result.push(snippet);\n }\n return result;\n}\n\nfunction isBeliefLedgerSection(section: Pick<EntityStructuredSection, \"key\">): boolean {\n return normalizeEntityText(section.key).replace(/\\s+/g, \"_\") === BELIEF_LEDGER_SECTION_KEY;\n}\n\nfunction beliefLedgerFactKeys(sections: EntityStructuredSection[]): Set<string> {\n const keys = new Set<string>();\n for (const section of sections) {\n if (!isBeliefLedgerSection(section)) continue;\n for (const fact of section.facts) {\n keys.add(normalizeEntityText(fact));\n }\n }\n return keys;\n}\n\nfunction recallFactsForStructuredSection(section: EntityStructuredSection): string[] {\n if (!isBeliefLedgerSection(section)) return section.facts;\n return currentActiveBeliefLedgerFactTexts(section.facts);\n}\n\nfunction currentActiveBeliefLedgerFactTexts(facts: string[]): string[] {\n const byClaim = new Map<string, { status: string; updatedAtMs: number; texts: string[] }>();\n for (const fact of facts) {\n const match = BELIEF_LEDGER_FACT_RE.exec(fact.trim());\n if (!match) continue;\n const [, claimId, status, updatedAt, text] = match;\n const updatedAtMs = Date.parse(updatedAt);\n if (!claimId?.trim() || !status?.trim() || !Number.isFinite(updatedAtMs) || !text?.trim()) continue;\n const normalizedStatus = status.trim().toLowerCase();\n const normalizedClaimId = claimId.trim();\n const current = byClaim.get(normalizedClaimId);\n const inactiveTieWins =\n current &&\n updatedAtMs === current.updatedAtMs &&\n current.status === \"active\" &&\n normalizedStatus !== \"active\";\n if (!current || updatedAtMs > current.updatedAtMs || inactiveTieWins) {\n byClaim.set(normalizedClaimId, { status: normalizedStatus, updatedAtMs, texts: [text.trim()] });\n continue;\n }\n if (updatedAtMs === current.updatedAtMs && current.status === normalizedStatus) {\n current.texts.push(text.trim());\n }\n }\n const result: string[] = [];\n for (const current of byClaim.values()) {\n if (current.status === \"active\") {\n result.push(...current.texts);\n }\n }\n return result;\n}\n\nfunction relationLine(entry: EntityMentionIndexEntry, relationship: { target: string; label: string }): string {\n const normalizedLabel = relationship.label.replace(/\\s+/g, \" \").trim();\n if (normalizedLabel.length === 0) return `${entry.name} is connected to ${relationship.target}`;\n return `${entry.name} ${normalizedLabel} ${relationship.target}`;\n}\n\nfunction detectEntityQueryMode(query: string): EntityQueryMode | null {\n const normalized = normalizeEntityText(query);\n if (!normalized) return null;\n if (\n /^(what about|and what about|how about|what happened (with|to) (he|him|his|she|her|they|them|their|it|its)|did (he|she|they|it)|is (he|she|they|it)|was (he|she|they|it))\\b/.test(normalized)\n ) {\n return \"follow_up\";\n }\n if (\n /^(who is|who s|what do we know about|what does|tell me about|what can you tell me about|what s new with|what happened with|what happened to|status of|where is|how is)\\b/.test(normalized)\n ) {\n if (/^what does\\b/.test(normalized)) {\n if (/^what does (?:this|that|it|the|a|an|my|our|your|their)\\b/.test(normalized)) {\n return null;\n }\n if (\n /^what does [a-z0-9-]+ (?:error|warning|exception|failure|stack|trace|code|message|log)\\b/.test(normalized)\n && /\\b(mean|means|indicate|indicates|imply|implies)\\b/.test(normalized)\n ) {\n return null;\n }\n }\n return /what happened|what s new|status of|how is|where is/.test(normalized) ? \"timeline\" : \"direct\";\n }\n if (ENTITY_PRONOUN_RE.test(normalized) && normalized.split(/\\s+/).length <= 8) {\n return \"follow_up\";\n }\n return null;\n}\n\nfunction scoreAliasMatch(query: string, alias: string): number {\n const normalizedQuery = normalizeEntityText(query);\n const normalizedAlias = normalizeEntityText(alias);\n if (!normalizedAlias) return 0;\n if (normalizedQuery === normalizedAlias) return 10;\n if (containsPhrase(normalizedQuery, normalizedAlias)) return 8 + Math.min(normalizedAlias.split(/\\s+/).length, 3);\n const queryTokens = new Set(tokenize(normalizedQuery));\n const aliasTokens = tokenize(normalizedAlias);\n if (aliasTokens.length === 0) return 0;\n const overlap = aliasTokens.filter((token) => queryTokens.has(token)).length;\n if (overlap === 0) return 0;\n // Cross-entity contamination guard (#682 PR 2/3 R-2). For multi-token\n // aliases, partial-token overlap that hits ONLY shared common tokens\n // (like \"person\" in \"Person-A1\" / \"Person-B1\") would surface every\n // similarly-prefixed entity for a query that named only one. Require\n // that the overlap include at least one DISTINCTIVE alias token —\n // i.e. a token that does not also appear in any other entity's\n // alias-token vocabulary. Since this function is pure / per-pair, we\n // approximate \"distinctive\" by requiring the overlap to include at\n // least one token that is not a substring-of common identifier\n // affixes. The aliasTokens with length > 1 must contribute at least\n // one non-affix overlap. \"Alice Example\" ([\"alice\", \"example\"])\n // matched by query \"Tell me about Alice\" → overlap = 1 on \"alice\",\n // and \"alice\" is not an affix → score = 1. \"Person-A1\" tokens\n // [\"person\", \"a1\"] matched by query \"Who is Person-B1?\" → overlap =\n // 1 on \"person\", and \"person\" IS an affix → score = 0.\n if (aliasTokens.length > 1) {\n const nonAffixOverlap = aliasTokens.filter(\n (token) => queryTokens.has(token) && !isAliasAffixToken(token),\n ).length;\n if (nonAffixOverlap === 0) return 0;\n }\n return overlap;\n}\n\n/**\n * Tokens that look like type prefixes / generic role identifiers and\n * therefore should not, on their own, count as evidence that a\n * multi-token alias matches a query (#682 PR 2/3 R-2).\n *\n * Kept as a small explicit list rather than a regex so additions are\n * deliberate. The list mirrors the entity types listed in\n * `entity-schema.ts` plus the most common generic role identifiers\n * that frequently appear as the leading token of a display name.\n */\nconst ALIAS_AFFIX_TOKENS = new Set<string>([\n \"person\", \"people\", \"user\", \"users\", \"team\", \"teams\",\n \"project\", \"projects\", \"topic\", \"topics\",\n \"org\", \"orgs\", \"organization\", \"organizations\", \"company\", \"companies\",\n \"place\", \"places\", \"tool\", \"tools\", \"service\", \"services\",\n \"system\", \"systems\", \"agent\", \"agents\", \"bot\", \"bots\",\n]);\n\nfunction isAliasAffixToken(token: string): boolean {\n return ALIAS_AFFIX_TOKENS.has(token);\n}\n\nfunction isLikelyInstructionLike(value: string): boolean {\n return INSTRUCTION_LIKE_RE.test(value) || METADATA_WRAPPER_RE.test(value);\n}\n\nfunction sanitizeEntityFact(fact: string): string {\n const sanitized = sanitizeMemoryContent(fact);\n const clean = sanitized.text.trim();\n if (!clean) return \"\";\n if (INSTRUCTION_LIKE_RE.test(clean) && clean.length > 100) return \"\";\n return clean;\n}\n\nfunction scoreHintSnippet(snippet: EntityHintSnippet, queryTokens: string[]): EntityHintSnippet | null {\n const normalized = normalizeEntityText(snippet.text);\n if (!normalized) return null;\n const scored = { ...snippet };\n if (isLikelyInstructionLike(scored.text) && scored.kind !== \"summary\") {\n scored.score -= 3;\n }\n const overlap = queryTokens.filter((token) => normalized.includes(token)).length;\n scored.score += overlap * 2;\n if (METADATA_WRAPPER_RE.test(scored.text)) scored.score -= 2;\n if (scored.text.length <= 160) scored.score += 1;\n return scored.score > 0 ? scored : null;\n}\n\nfunction sortTimelineEntriesDesc(\n left: EntityMentionIndexEntry[\"timeline\"][number],\n right: EntityMentionIndexEntry[\"timeline\"][number],\n): number {\n const timestampOrder = compareEntityTimestamps(right.timestamp, left.timestamp);\n if (timestampOrder !== 0) {\n return timestampOrder;\n }\n return right.text.localeCompare(left.text);\n}\n\nfunction jaccardSimilarity(a: string, b: string): number {\n const aTokens = new Set(tokenize(a));\n const bTokens = new Set(tokenize(b));\n if (aTokens.size === 0 || bTokens.size === 0) return 0;\n let intersection = 0;\n for (const token of aTokens) {\n if (bTokens.has(token)) intersection += 1;\n }\n const union = new Set([...aTokens, ...bTokens]).size;\n return union === 0 ? 0 : intersection / union;\n}\n\nfunction buildAliasIndex(entries: EntityMentionIndexEntry[]): Map<string, EntityMentionIndexEntry[]> {\n const index = new Map<string, EntityMentionIndexEntry[]>();\n for (const entry of entries) {\n const aliases = uniqueStrings([entry.name, ...entry.aliases]).map(normalizeEntityText).filter(Boolean);\n for (const alias of aliases) {\n const existing = index.get(alias) ?? [];\n existing.push(entry);\n index.set(alias, existing);\n }\n }\n return index;\n}\n\nasync function readNativeChunks(\n config: PluginConfig,\n recallNamespaces?: string[],\n): Promise<NativeKnowledgeChunk[]> {\n if (!config.nativeKnowledge?.enabled) return [];\n return collectNativeKnowledgeChunks({\n workspaceDir: config.workspaceDir,\n memoryDir: config.memoryDir,\n config: config.nativeKnowledge,\n recallNamespaces: config.namespacesEnabled ? recallNamespaces : undefined,\n defaultNamespace: config.defaultNamespace,\n }).catch(() => []);\n}\n\nasync function resolveEntityIndexStorages(\n storage: StorageManager,\n config: PluginConfig,\n recallNamespaces?: string[],\n namespaceStorage?: (namespace: string) => Promise<StorageManager>,\n): Promise<StorageManager[]> {\n if (\n !config.namespacesEnabled ||\n !namespaceStorage ||\n !recallNamespaces ||\n recallNamespaces.length === 0\n ) {\n return [storage];\n }\n\n const storages: StorageManager[] = [];\n const seenDirs = new Set<string>();\n for (const namespace of uniqueStrings(recallNamespaces)) {\n try {\n const scopedStorage = await namespaceStorage(namespace);\n const storageDir = path.resolve(scopedStorage.dir);\n if (seenDirs.has(storageDir)) continue;\n seenDirs.add(storageDir);\n storages.push(scopedStorage);\n } catch {\n continue;\n }\n }\n\n return storages.length > 0 ? storages : [storage];\n}\n\nfunction entityIndexStatePath(storage: StorageManager): string {\n return path.join(storage.dir, \"state\", \"entity-mention-index.json\");\n}\n\nasync function readEntityIndexState(storage: StorageManager): Promise<EntityMentionIndex | null> {\n const raw = await readFile(entityIndexStatePath(storage), \"utf-8\").catch(() => \"\");\n if (!raw) return null;\n try {\n const parsed = JSON.parse(raw) as Partial<EntityMentionIndex>;\n if (parsed.version !== ENTITY_INDEX_VERSION || !Array.isArray(parsed.entities)) return null;\n return parsed as EntityMentionIndex;\n } catch {\n return null;\n }\n}\n\nasync function writeEntityIndexState(storage: StorageManager, index: EntityMentionIndex): Promise<void> {\n const statePath = entityIndexStatePath(storage);\n await mkdir(path.dirname(statePath), { recursive: true });\n const nextContent = JSON.stringify(index, null, 2) + \"\\n\";\n const currentContent = await readFile(statePath, \"utf-8\").catch(() => \"\");\n if (currentContent === nextContent) return;\n await writeFile(statePath, nextContent, \"utf-8\");\n}\n\nfunction nativePseudoCanonicalId(chunk: NativeKnowledgeChunk): string {\n return `native:${createHash(\"sha256\").update(chunk.sourcePath).digest(\"hex\").slice(0, 12)}`;\n}\n\nfunction createPseudoNativeEntry(chunk: NativeKnowledgeChunk): EntityMentionIndexEntry {\n const canonicalId = nativePseudoCanonicalId(chunk);\n return {\n canonicalId,\n name: chunk.title,\n type: chunk.sourceKind,\n aliases: uniqueStrings(chunk.aliases ?? []),\n facts: [],\n structuredSections: [],\n timelineFacts: [],\n timeline: [],\n relationships: [],\n activity: [],\n factCount: 0,\n memorySnippets: [],\n nativeChunks: [\n {\n chunkId: chunk.chunkId,\n title: chunk.title,\n sourceKind: chunk.sourceKind,\n sourcePath: chunk.sourcePath,\n snippet: compactLine(chunk.content, 180),\n derivedDate: chunk.derivedDate,\n },\n ],\n };\n}\n\nfunction mergeNativeChunk(entry: EntityMentionIndexEntry, chunk: NativeKnowledgeChunk): void {\n const existing = entry.nativeChunks.find((item) => item.chunkId === chunk.chunkId);\n if (existing) return;\n entry.nativeChunks.push({\n chunkId: chunk.chunkId,\n title: chunk.title,\n sourceKind: chunk.sourceKind,\n sourcePath: chunk.sourcePath,\n snippet: compactLine(chunk.content, 180),\n derivedDate: chunk.derivedDate,\n });\n entry.aliases = uniqueStrings([...entry.aliases, ...(chunk.aliases ?? [])]);\n}\n\nasync function buildEntityMentionIndex(\n storage: StorageManager,\n config: PluginConfig,\n recallNamespaces?: string[],\n namespaceStorage?: (namespace: string) => Promise<StorageManager>,\n): Promise<EntityMentionIndex> {\n const storages = await resolveEntityIndexStorages(\n storage,\n config,\n recallNamespaces,\n namespaceStorage,\n );\n const shouldPersistIndex =\n storages.length === 1 && path.resolve(storages[0]!.dir) === path.resolve(storage.dir);\n const [previousIndex, entityFileSets, memorySets, nativeChunks] = await Promise.all([\n shouldPersistIndex ? readEntityIndexState(storage) : Promise.resolve(null),\n Promise.all(storages.map((scopedStorage) => scopedStorage.readAllEntityFiles())),\n Promise.all(storages.map((scopedStorage) => scopedStorage.readAllMemories())),\n readNativeChunks(config, recallNamespaces),\n ]);\n // Pair each entity with the alias table of the store it came from (#1534):\n // canonical ids must reflect the owning store's aliases, never another\n // namespace's.\n const entityRecords = entityFileSets.flatMap((set, index) =>\n set.map((entity) => ({ entity, aliases: storages[index]!.entityAliases })),\n );\n const memories = memorySets.flat();\n\n const entities = new Map<string, EntityMentionIndexEntry>();\n for (const { entity, aliases } of entityRecords) {\n const canonicalId = normalizeEntityName(entity.name, entity.type, aliases);\n const rawStructuredSections = entity.structuredSections ?? [];\n const rawBeliefLedgerFactKeys = beliefLedgerFactKeys(rawStructuredSections);\n const sanitizedFacts = entity.facts\n .map((fact) => sanitizeEntityFact(fact))\n .filter(Boolean)\n .filter((fact) => !rawBeliefLedgerFactKeys.has(normalizeEntityText(fact)))\n .map((fact) => compactLine(fact, 180));\n const sanitizedTimelineFacts = entity.timeline\n .map((entry) => sanitizeEntityFact(entry.text))\n .filter(Boolean)\n .map((fact) => compactLine(fact, 180));\n entities.set(canonicalId, {\n canonicalId,\n name: entity.name,\n type: entity.type,\n aliases: uniqueStrings(entity.aliases),\n summary: entity.synthesis?.trim() || entity.summary?.trim() || undefined,\n facts: sanitizedFacts,\n timelineFacts: uniqueStrings(sanitizedTimelineFacts),\n structuredSections: rawStructuredSections.map((section) => ({\n key: section.key,\n title: section.title,\n facts: recallFactsForStructuredSection(section)\n .map((fact) => sanitizeEntityFact(fact))\n .filter(Boolean)\n .map((fact) => compactLine(fact, 180)),\n })).filter((section) => section.facts.length > 0),\n timeline: entity.timeline.map((entry) => ({ ...entry })),\n relationships: entity.relationships.map((relationship) => ({ ...relationship })),\n activity: entity.activity.map((activity) => ({ ...activity })),\n factCount: sanitizedFacts.length,\n memorySnippets: [],\n nativeChunks: [],\n });\n }\n\n for (const memory of memories) {\n const entityRef = typeof memory.frontmatter.entityRef === \"string\" ? memory.frontmatter.entityRef : \"\";\n if (!entityRef) continue;\n const entry = entities.get(entityRef);\n if (!entry) continue;\n const snippet = await readMemorySnippet(memory);\n if (!entry.memorySnippets.includes(snippet)) {\n entry.memorySnippets.push(snippet);\n }\n }\n\n const aliasIndex = buildAliasIndex([...entities.values()]);\n for (const chunk of nativeChunks) {\n const existingPseudo = entities.get(nativePseudoCanonicalId(chunk));\n if (existingPseudo) {\n mergeNativeChunk(existingPseudo, chunk);\n continue;\n }\n const candidateAliases = uniqueStrings([chunk.title, ...(chunk.aliases ?? [])]).map(normalizeEntityText).filter(Boolean);\n let matched = false;\n for (const alias of candidateAliases) {\n for (const entry of aliasIndex.get(alias) ?? []) {\n mergeNativeChunk(entry, chunk);\n matched = true;\n }\n }\n if (matched) continue;\n const pseudoEntry = createPseudoNativeEntry(chunk);\n entities.set(pseudoEntry.canonicalId, pseudoEntry);\n }\n\n const sortedEntities = [...entities.values()].sort((left, right) => left.name.localeCompare(right.name));\n const previousEntities = previousIndex ? JSON.stringify(previousIndex.entities) : \"\";\n const nextEntities = JSON.stringify(sortedEntities);\n const index: EntityMentionIndex = {\n version: ENTITY_INDEX_VERSION,\n updatedAt:\n previousIndex && previousEntities === nextEntities\n ? previousIndex.updatedAt\n : new Date().toISOString(),\n entities: sortedEntities,\n };\n if (shouldPersistIndex) {\n await writeEntityIndexState(storage, index);\n }\n return index;\n}\n\nfunction resolveExplicitCandidates(\n index: EntityMentionIndex,\n query: string,\n): EntityCandidate[] {\n const candidates: EntityCandidate[] = [];\n for (const entry of index.entities) {\n const aliases = uniqueStrings([entry.name, ...entry.aliases]);\n let bestAlias = \"\";\n let bestScore = 0;\n for (const alias of aliases) {\n const score = scoreAliasMatch(query, alias);\n if (score > bestScore) {\n bestAlias = alias;\n bestScore = score;\n }\n }\n if (bestScore <= 0) continue;\n candidates.push({ entry, alias: bestAlias, score: bestScore, source: \"query\" });\n }\n return candidates.sort((left, right) => right.score - left.score);\n}\n\nfunction resolveRecentTurnCandidates(\n index: EntityMentionIndex,\n transcriptEntries: TranscriptEntry[],\n recentTurns: number,\n): EntityCandidate[] {\n if (recentTurns <= 0 || transcriptEntries.length === 0) return [];\n const recentEntries = transcriptEntries.slice(-recentTurns);\n const candidates = new Map<string, EntityCandidate>();\n for (let indexOffset = recentEntries.length - 1; indexOffset >= 0; indexOffset -= 1) {\n const turn = recentEntries[indexOffset];\n const recencyBoost = recentEntries.length - indexOffset;\n const roleWeight = turn.role === \"user\" ? 2 : turn.role === \"assistant\" ? -1 : 0;\n for (const entry of index.entities) {\n const aliases = uniqueStrings([entry.name, ...entry.aliases]);\n for (const alias of aliases) {\n const score = scoreAliasMatch(turn.content, alias);\n if (score <= 0) continue;\n const current = candidates.get(entry.canonicalId);\n const weightedScore = score + Math.max(0, 6 - recencyBoost) + roleWeight;\n if (!current || weightedScore > current.score) {\n candidates.set(entry.canonicalId, {\n entry,\n alias,\n score: weightedScore,\n source: \"recent_turn\",\n });\n }\n }\n }\n }\n return [...candidates.values()].sort((left, right) => right.score - left.score);\n}\n\nasync function readMemorySnippet(memory: MemoryFile): Promise<string> {\n const content = memory.content.replace(/\\s+/g, \" \").trim();\n return compactLine(content, 180);\n}\n\nasync function buildHintSnippets(\n entry: EntityMentionIndexEntry,\n queryTokens: string[],\n mode: EntityQueryMode,\n maxSupportingFacts: number,\n requestedSectionKeys: Set<string>,\n): Promise<EntityHintSnippet[]> {\n const snippets: EntityHintSnippet[] = [];\n const aliasTokens = new Set(tokenize(uniqueStrings([entry.name, ...entry.aliases]).join(\" \")));\n if (entry.summary) {\n snippets.push({ text: compactLine(entry.summary, 180), score: 10, kind: \"summary\" });\n }\n\n if (requestedSectionKeys.size > 0) {\n for (const section of entry.structuredSections) {\n if (!requestedSectionKeys.has(normalizeEntityText(section.key).replace(/\\s+/g, \"_\"))) continue;\n for (const fact of section.facts) {\n snippets.push({ text: fact, score: mode === \"direct\" ? 8 : 9, kind: \"section\" });\n }\n }\n } else {\n for (const fact of entry.timelineFacts) {\n snippets.push({ text: fact, score: mode === \"direct\" ? 6 : 7, kind: \"fact\" });\n }\n for (const section of entry.structuredSections) {\n for (const fact of section.facts) {\n const normalizedFact = normalizeEntityText(fact);\n const hasNonAliasQueryOverlap = queryTokens.some((token) =>\n !aliasTokens.has(token) && normalizedFact.includes(token)\n );\n if (entry.timelineFacts.length > 0 && !hasNonAliasQueryOverlap) {\n continue;\n }\n snippets.push({ text: fact, score: mode === \"direct\" ? 6 : 7, kind: \"fact\" });\n }\n }\n if (entry.timelineFacts.length === 0 && entry.structuredSections.length === 0) {\n for (const fact of entry.facts) {\n if (!fact.trim()) continue;\n snippets.push({ text: fact, score: mode === \"direct\" ? 6 : 7, kind: \"fact\" });\n }\n }\n }\n\n if (requestedSectionKeys.size === 0) {\n for (const relationship of entry.relationships) {\n snippets.push({\n text: compactLine(relationLine(entry, relationship), 180),\n score: mode === \"direct\" && entry.type.toLowerCase() === \"person\" ? 6 : 4,\n kind: \"relationship\",\n });\n }\n\n for (const activity of entry.activity) {\n snippets.push({\n text: compactLine(`${activity.date}: ${activity.note}`, 180),\n score: 4,\n kind: \"activity\",\n });\n }\n\n for (const memorySnippet of entry.memorySnippets.slice(0, Math.min(maxSupportingFacts, 4))) {\n snippets.push({\n text: memorySnippet,\n score: 5,\n kind: \"memory\",\n });\n }\n\n for (const chunk of entry.nativeChunks) {\n snippets.push({\n text: compactLine(chunk.snippet, 180),\n score: 3,\n kind: \"native\",\n });\n }\n }\n\n const deduped = new Map<string, EntityHintSnippet>();\n for (const snippet of snippets) {\n const scored = scoreHintSnippet(snippet, queryTokens);\n if (!scored) continue;\n const normalized = normalizeEntityText(scored.text);\n const existing = deduped.get(normalized);\n if (!existing || scored.score > existing.score) deduped.set(normalized, scored);\n }\n\n return [...deduped.values()]\n .filter((snippet) => snippet.score > 0)\n .sort((left, right) => right.score - left.score)\n .slice(0, maxSupportingFacts);\n}\n\nfunction summarizeUncertainty(snippets: EntityHintSnippet[]): string | null {\n const direct = snippets.filter((snippet) =>\n snippet.kind === \"summary\"\n || snippet.kind === \"fact\"\n || snippet.kind === \"section\"\n || snippet.kind === \"memory\"\n );\n if (direct.length < 2) return null;\n for (let index = 0; index < direct.length; index += 1) {\n for (let compare = index + 1; compare < direct.length; compare += 1) {\n if (jaccardSimilarity(direct[index].text, direct[compare].text) < 0.2) {\n return \"Evidence is mixed across stored facts; treat the hints below as partial and verify before answering definitively.\";\n }\n }\n }\n return null;\n}\n\nfunction formatEntityHintSection(\n candidates: Array<{\n candidate: EntityCandidate;\n snippets: EntityHintSnippet[];\n uncertainty: string | null;\n }>,\n queryTokens: string[],\n mode: EntityQueryMode,\n maxRelatedEntities: number,\n maxChars: number,\n): string | null {\n if (candidates.length === 0) return null;\n const lines: string[] = [\"## entity_answer_hints\", \"\"];\n for (const { candidate, snippets, uncertainty } of candidates) {\n const hasSummary = Boolean(candidate.entry.summary?.trim());\n const preferredTopSnippets = hasSummary\n ? snippets.filter((snippet) => snippet.kind !== \"fact\")\n : snippets;\n let topSnippets = (\n preferredTopSnippets.length > 0 ? preferredTopSnippets : snippets\n ).slice(0, 3);\n const buildTimelineSnippets = (seedExcludedTexts: Set<string>): EntityHintSnippet[] => {\n const explicitTimelinePool = dedupeHintSnippetsByText(\n (candidate.entry.timeline ?? [])\n .slice()\n .sort(sortTimelineEntriesDesc)\n .map((entry) => sanitizeEntityFact(entry.text))\n .filter(Boolean)\n .map((text) => scoreHintSnippet({\n text: compactLine(text, 180),\n score: 7,\n kind: \"activity\" as const,\n }, queryTokens))\n .filter((snippet): snippet is EntityHintSnippet => snippet !== null)\n .filter((snippet) => !seedExcludedTexts.has(normalizeEntityText(snippet.text))),\n ).slice(0, 2);\n const activityTimelinePool = dedupeHintSnippetsByText(\n snippets\n .filter((snippet) => (\n snippet.kind === \"activity\" || snippet.kind === \"memory\"\n ) && !seedExcludedTexts.has(normalizeEntityText(snippet.text))),\n ).slice(0, 2);\n return explicitTimelinePool.length > 0\n ? explicitTimelinePool\n : activityTimelinePool.length > 0\n ? activityTimelinePool\n : dedupeHintSnippetsByText(\n snippets\n .filter((snippet) => (\n snippet.kind === \"fact\" || snippet.kind === \"summary\"\n ) && !seedExcludedTexts.has(normalizeEntityText(snippet.text))),\n ).slice(0, 2);\n };\n const baseTopSnippetTexts = new Set(topSnippets.map((snippet) => normalizeEntityText(snippet.text)));\n const timelinePool = mode !== \"direct\" ? buildTimelineSnippets(baseTopSnippetTexts) : [];\n if (mode !== \"direct\" && hasSummary && topSnippets.length < 2) {\n if (timelinePool.length > 0) {\n topSnippets = [...topSnippets, timelinePool[0]!].slice(0, 3);\n }\n }\n const topSnippetTexts = new Set(topSnippets.map((snippet) => normalizeEntityText(snippet.text)));\n lines.push(`- target: ${candidate.entry.name} (${candidate.entry.type})`);\n if (candidate.source === \"recent_turn\") {\n lines.push(`- resolution: carried forward from recent turns via alias \"${candidate.alias}\"`);\n } else {\n lines.push(`- resolution: matched alias \"${candidate.alias}\" in the query`);\n }\n if (uncertainty) lines.push(`- uncertainty: ${uncertainty}`);\n if (topSnippets.length > 0) {\n lines.push(\"- likely answer:\");\n for (const snippet of topSnippets) {\n lines.push(` - ${snippet.text}`);\n }\n }\n if (mode !== \"direct\") {\n const fallbackTimeline = timelinePool.filter(\n (snippet) => !topSnippetTexts.has(normalizeEntityText(snippet.text)),\n );\n if (fallbackTimeline.length > 0) {\n lines.push(\"- recent timeline:\");\n for (const snippet of fallbackTimeline) {\n lines.push(` - ${snippet.text}`);\n }\n }\n }\n const related = candidate.entry.relationships.slice(0, maxRelatedEntities).map((relationship) => relationship.target);\n if (related.length > 0) {\n lines.push(`- related entities: ${related.join(\", \")}`);\n }\n lines.push(`- support counts: facts=${candidate.entry.factCount}, memories=${candidate.entry.memorySnippets.length}, native=${candidate.entry.nativeChunks.length}`);\n lines.push(\"\");\n }\n\n let result = lines.join(\"\\n\");\n if (result.length > maxChars) {\n result = `${result.slice(0, Math.max(0, maxChars - 15)).trimEnd()}\\n\\n...(trimmed)\\n`;\n }\n return result.trim().length > 0 ? result.trimEnd() : null;\n}\n\nexport async function buildEntityRecallSection(options: BuildEntityRecallSectionOptions): Promise<string | null> {\n const mode = detectEntityQueryMode(options.query);\n if (!mode) return null;\n\n const index = await buildEntityMentionIndex(\n options.storage,\n options.config,\n options.recallNamespaces,\n options.namespaceStorage,\n );\n if (index.entities.length === 0) return null;\n\n const explicitCandidates = resolveExplicitCandidates(index, options.query);\n const candidates = explicitCandidates.length > 0\n ? explicitCandidates\n : resolveRecentTurnCandidates(index, options.transcriptEntries, options.recentTurns);\n\n if (candidates.length === 0) return null;\n\n const queryTokens = tokenize(options.query);\n const candidateLimit = explicitCandidates.length === 0 && mode === \"follow_up\"\n ? 1\n : options.maxHints;\n const rankedCandidates = candidates.slice(0, candidateLimit);\n const enriched = await Promise.all(\n rankedCandidates.map(async (candidate) => {\n const requestedSectionKeys = new Set(\n resolveRequestedEntitySectionKeys(\n options.query,\n candidate.entry.type,\n candidate.entry.structuredSections,\n options.config.entitySchemas,\n ),\n );\n const snippets = await buildHintSnippets(\n candidate.entry,\n queryTokens,\n mode,\n options.maxSupportingFacts,\n requestedSectionKeys,\n );\n return {\n candidate,\n snippets,\n uncertainty: summarizeUncertainty(snippets),\n };\n }),\n );\n\n const section = formatEntityHintSection(enriched, queryTokens, mode, options.maxRelatedEntities, options.maxChars);\n if (!section) return null;\n return section;\n}\n\nexport async function readRecentEntityTranscriptEntries(\n transcriptEntriesPromise: Promise<TranscriptEntry[]>,\n recentTurns: number,\n): Promise<TranscriptEntry[]> {\n if (recentTurns <= 0) return [];\n const transcriptEntries = await transcriptEntriesPromise.catch(() => []);\n if (transcriptEntries.length === 0) return [];\n return transcriptEntries.slice(-Math.max(1, recentTurns * 2));\n}\n\nexport const entityIndexVersion = ENTITY_IND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GAAG,cAAc;AAC3D,QAAM,WAAW,MAAM,QAAQ;AAAA,IAC7B,iBAAiB,IAAI,OAAO,cAAc;AACxC,YAAM,uBAAuB,IAAI;AAAA,QAC/B;AAAA,UACE,QAAQ;AAAA,UACR,UAAU,MAAM;AAAA,UAChB,UAAU,MAAM;AAAA,UAChB,QAAQ,OAAO;AAAA,QACjB;AAAA,MACF;AACA,YAAM,WAAW,MAAM;AAAA,QACrB,UAAU;AAAA,QACV;AAAA,QACA;AAAA,QACA,QAAQ;AAAA,QACR;AAAA,MACF;AACA,aAAO;AAAA,QACL;AAAA,QACA;AAAA,QACA,aAAa,qBAAqB,QAAQ;AAAA,MAC5C;AAAA,IACF,CAAC;AAAA,EACH;AAEA,QAAM,UAAU,wBAAwB,UAAU,aAAa,MAAM,QAAQ,oBAAoB,QAAQ,QAAQ;AACjH,MAAI,CAAC,QAAS,QAAO;AACrB,SAAO;AACT;AAEA,eAAsB,kCACpB,0BACA,aAC4B;AAC5B,MAAI,eAAe,EAAG,QAAO,CAAC;AAC9B,QAAM,oBAAoB,MAAM,yBAAyB,MAAM,MAAM,CAAC,CAAC;AACvE,MAAI,kBAAkB,WAAW,EAAG,QAAO,CAAC;AAC5C,SAAO,kBAAkB,MAAM,CAAC,KAAK,IAAI,GAAG,cAAc,CAAC,CAAC;AAC9D;AAEO,IAAM,qBAAqB;AAC3B,IAAM,sCAAsC;","names":["index"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
listNamespaces
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-QFKRE7AU.js";
|
|
4
4
|
import {
|
|
5
5
|
runConsolidationProvenanceCheck
|
|
6
6
|
} from "./chunk-AL4RAJL5.js";
|
|
@@ -36,13 +36,13 @@ import {
|
|
|
36
36
|
import {
|
|
37
37
|
listMemoryGovernanceRuns,
|
|
38
38
|
readMemoryGovernanceRunArtifact
|
|
39
|
-
} from "./chunk-
|
|
39
|
+
} from "./chunk-ZCMO46YY.js";
|
|
40
40
|
import {
|
|
41
41
|
analyzeGraphHealth
|
|
42
42
|
} from "./chunk-Y56J7CXW.js";
|
|
43
43
|
import {
|
|
44
44
|
StorageManager
|
|
45
|
-
} from "./chunk-
|
|
45
|
+
} from "./chunk-4PLOQDBB.js";
|
|
46
46
|
import {
|
|
47
47
|
lintWorkspaceFiles
|
|
48
48
|
} from "./chunk-DM2T26WE.js";
|
|
@@ -1336,4 +1336,4 @@ export {
|
|
|
1336
1336
|
runBenchmarkRecall,
|
|
1337
1337
|
runOperatorRepair
|
|
1338
1338
|
};
|
|
1339
|
-
//# sourceMappingURL=chunk-
|
|
1339
|
+
//# sourceMappingURL=chunk-GGL7R2L2.js.map
|
|
@@ -5,7 +5,7 @@ import {
|
|
|
5
5
|
import {
|
|
6
6
|
ALL_CATEGORY_DIRS,
|
|
7
7
|
StorageManager
|
|
8
|
-
} from "./chunk-
|
|
8
|
+
} from "./chunk-4PLOQDBB.js";
|
|
9
9
|
import {
|
|
10
10
|
isSafeRouteNamespace
|
|
11
11
|
} from "./chunk-U3PN77QT.js";
|
|
@@ -209,4 +209,4 @@ export {
|
|
|
209
209
|
resolveNamespaceStorageRoot,
|
|
210
210
|
NamespaceStorageRouter
|
|
211
211
|
};
|
|
212
|
-
//# sourceMappingURL=chunk-
|
|
212
|
+
//# sourceMappingURL=chunk-JI3LQFJH.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import {
|
|
2
2
|
StorageManager,
|
|
3
3
|
normalizeEntityName
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-4PLOQDBB.js";
|
|
5
5
|
import {
|
|
6
6
|
extractJsonCandidates
|
|
7
7
|
} from "./chunk-RGMVMVMF.js";
|
|
@@ -77,7 +77,7 @@ function parseBriefingFocus(token) {
|
|
|
77
77
|
}
|
|
78
78
|
return { type: "topic", value: trimmed };
|
|
79
79
|
}
|
|
80
|
-
function focusMatchesMemory(memory, focus) {
|
|
80
|
+
function focusMatchesMemory(memory, focus, entityAliases) {
|
|
81
81
|
const needle = focus.value.toLowerCase();
|
|
82
82
|
const entityRef = (memory.frontmatter.entityRef ?? "").toLowerCase();
|
|
83
83
|
const rawHaystackParts = [
|
|
@@ -90,7 +90,7 @@ function focusMatchesMemory(memory, focus) {
|
|
|
90
90
|
const rawHaystack = rawHaystackParts.join(" ").toLowerCase();
|
|
91
91
|
if (rawHaystack.includes(needle)) return true;
|
|
92
92
|
if (!entityRef) return false;
|
|
93
|
-
const focusCanonical = normalizeEntityName(focus.value, focus.type);
|
|
93
|
+
const focusCanonical = normalizeEntityName(focus.value, focus.type, entityAliases);
|
|
94
94
|
let refForNormalize = entityRef;
|
|
95
95
|
const typeDelimMatch = refForNormalize.match(
|
|
96
96
|
new RegExp(`^${focus.type}[^a-z0-9]+`, "i")
|
|
@@ -98,7 +98,7 @@ function focusMatchesMemory(memory, focus) {
|
|
|
98
98
|
if (typeDelimMatch) {
|
|
99
99
|
refForNormalize = refForNormalize.slice(typeDelimMatch[0].length);
|
|
100
100
|
}
|
|
101
|
-
const refCanonical = normalizeEntityName(refForNormalize, focus.type);
|
|
101
|
+
const refCanonical = normalizeEntityName(refForNormalize, focus.type, entityAliases);
|
|
102
102
|
return refCanonical === focusCanonical;
|
|
103
103
|
}
|
|
104
104
|
function focusMatchesEntity(entity, focus) {
|
|
@@ -426,7 +426,7 @@ async function buildBriefing(options) {
|
|
|
426
426
|
safeReadEntities(options.storage)
|
|
427
427
|
]);
|
|
428
428
|
const memoriesInWindow = filterMemoriesByWindow(allMemories, window);
|
|
429
|
-
const focusedMemories = focus ? memoriesInWindow.filter((m) => focusMatchesMemory(m, focus)) : memoriesInWindow;
|
|
429
|
+
const focusedMemories = focus ? memoriesInWindow.filter((m) => focusMatchesMemory(m, focus, options.storage.entityAliases)) : memoriesInWindow;
|
|
430
430
|
const activeThreads = buildActiveThreads(focusedMemories);
|
|
431
431
|
const recentEntities = buildRecentEntities(allEntities, window, focus);
|
|
432
432
|
const openCommitments = buildOpenCommitments(focusedMemories);
|
|
@@ -870,4 +870,4 @@ export {
|
|
|
870
870
|
resolveBriefingSaveDir,
|
|
871
871
|
briefingFilename
|
|
872
872
|
};
|
|
873
|
-
//# sourceMappingURL=chunk-
|
|
873
|
+
//# sourceMappingURL=chunk-KI6QM5AV.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/briefing.ts"],"sourcesContent":["/**\n * Daily Context Briefing (Issue #370)\n *\n * Produces a focused \"here is what matters right now\" briefing by\n * cross-referencing active entities, recent facts, open commitments,\n * LLM-generated follow-ups, and an optional calendar source.\n *\n * The module exposes:\n * - `parseBriefingWindow(token)` — CLI-friendly window parser.\n * - `buildBriefing(options)` — core builder that returns markdown + JSON.\n * - `FileCalendarSource` — stub CalendarSource implementation that reads\n * a local ICS or JSON file.\n *\n * ALL OpenAI usage in this module goes through the Responses API. Chat\n * Completions is never used.\n */\n\nimport { readFile } from \"node:fs/promises\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport { log } from \"./logger.js\";\nimport { extractJsonCandidates } from \"./json-extract.js\";\nimport { normalizeEntityName, StorageManager } from \"./storage.js\";\nimport { readEnvVar, resolveHomeDir } from \"./runtime/env.js\";\nimport type {\n BriefingActiveThread,\n BriefingCalendarSourceError,\n BriefingFocus,\n BriefingFollowup,\n BriefingOpenCommitment,\n BriefingRecentEntity,\n BriefingResult,\n BriefingSections,\n CalendarEvent,\n CalendarSource,\n EntityFile,\n MemoryFile,\n} from \"./types.js\";\n\n// ──────────────────────────────────────────────────────────────────────────\n// Window parsing\n// ──────────────────────────────────────────────────────────────────────────\n\n/** Allowed values for the briefing format flag/field. */\nexport const BRIEFING_FORMAT_ALLOWED = [\"markdown\", \"json\"] as const;\n\n/**\n * Default model used for the Responses API follow-up generation call.\n * Mirrors the extraction engine default in config.ts — keep in sync.\n */\nexport const BRIEFING_FOLLOWUP_DEFAULT_MODEL = \"gpt-5.5\";\nexport type BriefingFormatValue = typeof BRIEFING_FORMAT_ALLOWED[number];\n\n/**\n * Validate a user-supplied `--format` flag value.\n * Returns `null` when the value is valid (or `undefined`, meaning the flag\n * was not supplied and the caller should fall back to the configured default).\n * Returns an error message string when the value is explicitly invalid.\n */\nexport function validateBriefingFormat(value: string | undefined): string | null {\n if (value === undefined) return null;\n if ((BRIEFING_FORMAT_ALLOWED as readonly string[]).includes(value)) return null;\n return `Invalid --format value: \"${value}\". Accepted: ${BRIEFING_FORMAT_ALLOWED.join(\", \")}.`;\n}\n\n/** Parsed briefing lookback window. */\nexport interface ParsedBriefingWindow {\n /** Start of the window (inclusive). */\n from: Date;\n /** End of the window (exclusive). */\n to: Date;\n /** Human-readable label. */\n label: string;\n}\n\nconst DAY_MS = 24 * 60 * 60 * 1000;\n\n/**\n * Maximum allowed lookback offset in milliseconds (100 years).\n * Anything beyond this is almost certainly a typo or abuse — and would\n * overflow to `Invalid Date` for sufficiently large values anyway.\n */\nconst MAX_WINDOW_MS = 100 * 365 * DAY_MS;\n\n/**\n * Parse a CLI-friendly window token into a concrete date range.\n *\n * Accepted forms (case-insensitive):\n * - `yesterday` — the previous UTC calendar day.\n * - `today` — the current UTC calendar day so far.\n * - `NNh` — last N hours (e.g. `24h`, `48h`).\n * - `NNd` — last N calendar days (e.g. `3d`, `7d`).\n * - `NNw` — last N weeks (e.g. `1w`, `2w`).\n *\n * Returns `null` for invalid tokens so callers can surface a clean error.\n */\nexport function parseBriefingWindow(\n token: string,\n now: Date = new Date(),\n): ParsedBriefingWindow | null {\n const raw = typeof token === \"string\" ? token.trim().toLowerCase() : \"\";\n if (raw.length === 0) return null;\n\n if (raw === \"yesterday\") {\n const startOfToday = startOfUtcDay(now);\n const from = new Date(startOfToday.getTime() - DAY_MS);\n return { from, to: startOfToday, label: \"yesterday\" };\n }\n\n if (raw === \"today\") {\n return { from: startOfUtcDay(now), to: now, label: \"today\" };\n }\n\n const match = raw.match(/^(\\d+)\\s*(h|d|w)$/);\n if (!match) return null;\n const value = parseInt(match[1], 10);\n if (!Number.isFinite(value) || value <= 0) return null;\n const unit = match[2];\n let ms = 0;\n if (unit === \"h\") ms = value * 60 * 60 * 1000;\n else if (unit === \"d\") ms = value * DAY_MS;\n else if (unit === \"w\") ms = value * 7 * DAY_MS;\n if (ms === 0) return null;\n // Reject values that exceed the 100-year cap or would overflow to Invalid Date.\n if (ms > MAX_WINDOW_MS || !Number.isFinite(ms)) return null;\n const from = new Date(now.getTime() - ms);\n if (!Number.isFinite(from.getTime())) return null;\n return {\n from,\n to: now,\n label: `last ${value}${unit}`,\n };\n}\n\nfunction startOfUtcDay(date: Date): Date {\n const d = new Date(date.getTime());\n d.setUTCHours(0, 0, 0, 0);\n return d;\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// Focus filter\n// ──────────────────────────────────────────────────────────────────────────\n\n/**\n * Parse a CLI `--focus` string into a structured focus filter.\n *\n * Accepted forms:\n * - `person:Jane Doe`\n * - `project:remnic-core`\n * - `topic:retrieval`\n *\n * If no prefix is supplied, falls back to `topic:<value>`.\n */\nexport function parseBriefingFocus(token: string | undefined): BriefingFocus | null {\n if (typeof token !== \"string\") return null;\n const trimmed = token.trim();\n if (trimmed.length === 0) return null;\n const [maybeType, ...rest] = trimmed.split(\":\");\n if (rest.length === 0) {\n return { type: \"topic\", value: maybeType };\n }\n const rawType = maybeType.toLowerCase();\n if (rawType === \"person\" || rawType === \"project\" || rawType === \"topic\") {\n const value = rest.join(\":\").trim();\n if (value.length === 0) return null;\n return { type: rawType, value };\n }\n return { type: \"topic\", value: trimmed };\n}\n\n/**\n * Decide whether a memory/entity matches the given focus filter.\n * Purely deterministic — no LLM, case-insensitive substring match across\n * the most useful surfaces.\n *\n * For typed focus (`person:`, `project:`, `entity:`) we attribute via the\n * canonical-id path below to avoid the substring leak fixed in #682 PR 2/3\n * R-10 (`Alice-Test` substring-hitting `person-alice-test-a1`).\n *\n * For untyped (`topic`) focus there is no type to canonicalize against, so\n * we keep `entityRef` in the raw haystack — otherwise memories that link to\n * an entity only via `frontmatter.entityRef` (no body / tag mention) would\n * silently drop out of an untyped focus filter (codex P2 review on #695).\n */\nexport function focusMatchesMemory(\n memory: MemoryFile,\n focus: BriefingFocus,\n entityAliases?: Readonly<Record<string, string>>,\n): boolean {\n const needle = focus.value.toLowerCase();\n const entityRef = (memory.frontmatter.entityRef ?? \"\").toLowerCase();\n\n // Raw substring match across content and tags. For untyped (`topic`)\n // focus, also include the entityRef so memories linked only via the\n // frontmatter ref still match. For typed focus we deliberately\n // exclude entityRef here and route through the canonical-id path\n // below (see comment above).\n const rawHaystackParts = [\n memory.content,\n ...(memory.frontmatter.tags ?? []),\n ];\n if (focus.type === \"topic\" && entityRef) {\n rawHaystackParts.push(entityRef);\n }\n const rawHaystack = rawHaystackParts.join(\" \").toLowerCase();\n if (rawHaystack.includes(needle)) return true;\n\n // Canonical-id match (#682 PR 2/3 R-10). Normalize BOTH sides through\n // `normalizeEntityName` so:\n // - `entityRef === slug` exact comparison no longer fails when the\n // stored ref is in a non-canonical form (e.g. `person:Alice-Test`\n // vs. `person-alice-test`) — both normalize to the same canonical id.\n // - `entityRef.includes(slug)` substring matching is replaced by\n // equality, so similarly-prefixed entities like\n // `person-alice-test-a1` no longer match a focus on\n // `person:Alice-Test`.\n // This also handles the type-prefix-in-name case the cursor reviewer\n // flagged: `normalizeEntityName` strips a duplicate type prefix so\n // `Project-Alpha` of type `project` canonicalizes to `project-alpha`,\n // and a focus on `project:Project-Alpha` does the same.\n if (!entityRef) return false;\n const focusCanonical = normalizeEntityName(focus.value, focus.type, entityAliases);\n // Strip a leading `<type><delimiter>` prefix from a non-canonical\n // entityRef before normalizing — `normalizeEntityName` only strips\n // `<type>-` so other valid verbatim formats (`person:Alice-Test`,\n // `person/alice-test`, `person_alice_test`, `person Alice Test`)\n // would otherwise double up the type prefix and miss the canonical\n // comparison. Codex P2 review on #695: memory writes persist\n // entityRef strings as provided, so any non-alphanumeric delimiter\n // after the type token must be tolerated here.\n let refForNormalize = entityRef;\n const typeDelimMatch = refForNormalize.match(\n new RegExp(`^${focus.type}[^a-z0-9]+`, \"i\"),\n );\n if (typeDelimMatch) {\n refForNormalize = refForNormalize.slice(typeDelimMatch[0].length);\n }\n const refCanonical = normalizeEntityName(refForNormalize, focus.type, entityAliases);\n return refCanonical === focusCanonical;\n}\n\nexport function focusMatchesEntity(entity: EntityFile, focus: BriefingFocus): boolean {\n const needle = focus.value.toLowerCase();\n if (focus.type === \"person\" && entity.type.toLowerCase() !== \"person\") return false;\n if (focus.type === \"project\" && entity.type.toLowerCase() !== \"project\") return false;\n const haystack = [\n entity.name,\n entity.synthesis || entity.summary || \"\",\n ...entity.facts,\n ...(entity.aliases ?? []),\n ...(entity.structuredSections ?? []).flatMap((section) => [section.title, ...section.facts]),\n ]\n .join(\" \")\n .toLowerCase();\n return haystack.includes(needle);\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// Calendar source\n// ──────────────────────────────────────────────────────────────────────────\n\n/**\n * Stub `CalendarSource` backed by a single local file. Supports:\n * - JSON files containing an array of `CalendarEvent` records, OR a wrapper\n * `{ events: CalendarEvent[] }` object.\n * - Minimal ICS (`.ics`) files — extracts `VEVENT` blocks with `SUMMARY`,\n * `DTSTART`, `DTEND`, `LOCATION`, `DESCRIPTION`, `UID`.\n *\n * Real calendar integrations (Google, iCloud, Microsoft) can plug into the\n * same `CalendarSource` interface later.\n */\nexport class FileCalendarSource implements CalendarSource {\n constructor(private readonly filePath: string) {}\n\n async eventsForDate(dateIso: string): Promise<CalendarEvent[]> {\n let raw: string;\n try {\n raw = await readFile(this.filePath, \"utf-8\");\n } catch (err) {\n log.warn(`briefing: calendar source unreadable at ${this.filePath}: ${err}`);\n return [];\n }\n\n const events = this.filePath.toLowerCase().endsWith(\".ics\")\n ? parseIcsEvents(raw)\n : parseJsonEvents(raw);\n\n return events.filter((event) => eventFallsOnDate(event, dateIso));\n }\n}\n\nfunction parseJsonEvents(raw: string): CalendarEvent[] {\n try {\n const parsed = JSON.parse(raw) as unknown;\n const arr = Array.isArray(parsed)\n ? parsed\n : parsed && typeof parsed === \"object\" && Array.isArray((parsed as { events?: unknown }).events)\n ? ((parsed as { events: unknown[] }).events)\n : [];\n const events: CalendarEvent[] = [];\n for (const entry of arr) {\n if (!entry || typeof entry !== \"object\") continue;\n const e = entry as Record<string, unknown>;\n const id = typeof e.id === \"string\" ? e.id : typeof e.uid === \"string\" ? e.uid : cryptoRandomId();\n const title = typeof e.title === \"string\" ? e.title : typeof e.summary === \"string\" ? e.summary : \"\";\n const start = typeof e.start === \"string\" ? e.start : typeof e.dtstart === \"string\" ? e.dtstart : \"\";\n if (!title || !start) continue;\n events.push({\n id,\n title,\n start,\n end: typeof e.end === \"string\" ? e.end : typeof e.dtend === \"string\" ? e.dtend : undefined,\n location: typeof e.location === \"string\" ? e.location : undefined,\n notes: typeof e.notes === \"string\" ? e.notes : typeof e.description === \"string\" ? e.description : undefined,\n });\n }\n return events;\n } catch (err) {\n log.warn(`briefing: calendar JSON parse failed: ${err}`);\n return [];\n }\n}\n\ninterface IcsParsedLine {\n property: string;\n params: Record<string, string>;\n value: string;\n}\n\n/**\n * Parse a single ICS content line into its property, parameters, and value.\n * Returns null if the line is not a well-formed property line.\n *\n * Example:\n * `DTSTART;TZID=America/New_York:20260411T233000`\n * → { property: \"DTSTART\", params: { TZID: \"America/New_York\" }, value: \"20260411T233000\" }\n */\nfunction parseIcsLine(line: string): IcsParsedLine | null {\n // Find the first `:` outside of any parameter value. Per RFC 5545 parameter\n // values may be quoted, but the minimal-parser use case here only needs to\n // handle unquoted TZID values.\n const colonIdx = line.indexOf(\":\");\n if (colonIdx <= 0) return null;\n const head = line.slice(0, colonIdx);\n const value = line.slice(colonIdx + 1).trim();\n // Head is of the form `PROPERTY[;PARAM=val[;PARAM=val]]`.\n const headParts = head.split(\";\");\n const property = headParts[0]!.toUpperCase();\n if (!/^[A-Z0-9-]+$/.test(property)) return null;\n const params: Record<string, string> = {};\n for (let i = 1; i < headParts.length; i++) {\n const segment = headParts[i]!;\n const eqIdx = segment.indexOf(\"=\");\n if (eqIdx <= 0) continue;\n const name = segment.slice(0, eqIdx).toUpperCase();\n let val = segment.slice(eqIdx + 1);\n // Strip surrounding quotes if present (RFC 5545 §3.1).\n if (val.startsWith('\"') && val.endsWith('\"') && val.length >= 2) {\n val = val.slice(1, -1);\n }\n params[name] = val;\n }\n return { property, params, value };\n}\n\ninterface IcsDateField {\n raw: string;\n params: Record<string, string>;\n}\n\n/** @internal — exported for testing only. */\nexport function parseIcsEvents(raw: string): CalendarEvent[] {\n const events: CalendarEvent[] = [];\n // RFC 5545 §3.1 line unfolding: a CRLF (now \\n) followed by a single\n // whitespace character (space or tab) is a fold — remove both characters\n // to join the continuation onto the preceding logical line. This MUST\n // happen after normalising CRLF → \\n and BEFORE splitting on \\n.\n const normalized = raw.replace(/\\r\\n/g, \"\\n\").replace(/\\n[ \\t]/g, \"\");\n const blocks = normalized.split(/BEGIN:VEVENT/i).slice(1);\n for (const block of blocks) {\n const endIdx = block.search(/END:VEVENT/i);\n const body = endIdx === -1 ? block : block.slice(0, endIdx);\n const simpleFields: Record<string, string> = {};\n const dateFields: Record<string, IcsDateField> = {};\n for (const line of body.split(\"\\n\")) {\n const parsed = parseIcsLine(line);\n if (!parsed) continue;\n const { property, params, value } = parsed;\n if (property === \"DTSTART\" || property === \"DTEND\") {\n if (dateFields[property] === undefined) {\n dateFields[property] = { raw: value, params };\n }\n } else if (simpleFields[property] === undefined) {\n simpleFields[property] = value;\n }\n }\n const title = simpleFields.SUMMARY;\n const dtstart = dateFields.DTSTART;\n if (!title || !dtstart) continue;\n const dtend = dateFields.DTEND;\n events.push({\n id: simpleFields.UID ?? cryptoRandomId(),\n title,\n start: normalizeIcsDate(dtstart.raw, dtstart.params),\n end: dtend ? normalizeIcsDate(dtend.raw, dtend.params) : undefined,\n location: simpleFields.LOCATION,\n notes: simpleFields.DESCRIPTION,\n });\n }\n return events;\n}\n\n/**\n * Normalise an ICS date/datetime value (optionally with a `TZID` parameter)\n * into an ISO 8601 string that downstream code can compare unambiguously.\n *\n * Behaviour:\n * - `20260411T150000Z` → `2026-04-11T15:00:00Z`\n * - `20260411` → `2026-04-11T00:00:00Z` (date-only events are day-boundaries)\n * - `20260411T150000` (floating, no Z, no TZID) → `2026-04-11T15:00:00` (floating)\n * - `20260411T233000` with `TZID=America/New_York` → `2026-04-12T03:30:00Z`\n * (applies the zone offset at that wallclock time; DST-aware via Intl)\n * - Unknown TZID falls back to UTC with a logged warning (conservative:\n * the event still appears, but on the UTC date).\n */\nfunction normalizeIcsDate(value: string, params: Record<string, string> = {}): string {\n // Date-time with explicit Z suffix (UTC).\n if (/^\\d{8}T\\d{6}Z$/.test(value)) {\n const y = value.slice(0, 4);\n const m = value.slice(4, 6);\n const d = value.slice(6, 8);\n const hh = value.slice(9, 11);\n const mm = value.slice(11, 13);\n const ss = value.slice(13, 15);\n return `${y}-${m}-${d}T${hh}:${mm}:${ss}Z`;\n }\n // Date-time without Z: may be floating or zoned via TZID.\n if (/^\\d{8}T\\d{6}$/.test(value)) {\n const y = value.slice(0, 4);\n const m = value.slice(4, 6);\n const d = value.slice(6, 8);\n const hh = value.slice(9, 11);\n const mm = value.slice(11, 13);\n const ss = value.slice(13, 15);\n const local = `${y}-${m}-${d}T${hh}:${mm}:${ss}`;\n const tzid = params.TZID;\n if (tzid) {\n const utcIso = icsWallclockToUtc(local, tzid);\n if (utcIso) return utcIso;\n log.warn(\n `briefing: unsupported TZID \"${tzid}\" — treating as UTC for ${local}`,\n );\n return `${local}Z`;\n }\n // No TZID → floating. Downstream compares the date slice directly.\n return local;\n }\n // Date-only (all-day event). Date-only values carry no TZID per RFC 5545.\n if (/^\\d{8}$/.test(value)) {\n return `${value.slice(0, 4)}-${value.slice(4, 6)}-${value.slice(6, 8)}T00:00:00Z`;\n }\n return value;\n}\n\n/**\n * Convert a wallclock local datetime in a named IANA timezone to a UTC ISO\n * string. Returns null if the timezone is unsupported by the runtime.\n *\n * Implementation note: this is the standard \"invert the formatter\" technique.\n * We treat the local wallclock as though it were UTC, ask the runtime what\n * time that instant shows in the target zone, and the delta is the zone's\n * offset at that wallclock moment (DST-aware).\n */\nfunction icsWallclockToUtc(local: string, tzid: string): string | null {\n const match = local.match(/^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})$/);\n if (!match) return null;\n const [, y, mo, d, hh, mm, ss] = match;\n // Treat the wallclock as UTC for the first probe.\n const naiveUtcMs = Date.UTC(\n Number(y),\n Number(mo) - 1,\n Number(d),\n Number(hh),\n Number(mm),\n Number(ss),\n );\n if (!Number.isFinite(naiveUtcMs)) return null;\n\n let formatter: Intl.DateTimeFormat;\n try {\n formatter = new Intl.DateTimeFormat(\"en-US\", {\n timeZone: tzid,\n year: \"numeric\",\n month: \"2-digit\",\n day: \"2-digit\",\n hour: \"2-digit\",\n minute: \"2-digit\",\n second: \"2-digit\",\n hour12: false,\n });\n } catch {\n return null;\n }\n\n const zonedMs = zonedFormatToMs(formatter, new Date(naiveUtcMs));\n if (zonedMs === null) return null;\n // Offset = naiveUtc − zonedAtNaiveUtc (positive for zones east of UTC).\n const offsetMs = naiveUtcMs - zonedMs;\n // Apply the offset once to land on the real UTC instant.\n const realUtcMs = naiveUtcMs + offsetMs;\n // Second pass: offsets can differ when the wallclock crosses a DST boundary.\n const zonedMs2 = zonedFormatToMs(formatter, new Date(realUtcMs));\n if (zonedMs2 !== null) {\n const offsetMs2 = realUtcMs - zonedMs2;\n if (offsetMs2 !== offsetMs) {\n return new Date(naiveUtcMs + offsetMs2).toISOString();\n }\n }\n return new Date(realUtcMs).toISOString();\n}\n\n/**\n * Format a Date in the given timezone and return the absolute ms timestamp\n * of that wallclock time interpreted as if it were UTC. Used only by\n * `icsWallclockToUtc` to compute zone offsets.\n */\nfunction zonedFormatToMs(formatter: Intl.DateTimeFormat, date: Date): number | null {\n const parts = formatter.formatToParts(date);\n const get = (type: string): string | undefined =>\n parts.find((p) => p.type === type)?.value;\n const y = get(\"year\");\n const mo = get(\"month\");\n const d = get(\"day\");\n const hh = get(\"hour\");\n const mm = get(\"minute\");\n const ss = get(\"second\");\n if (!y || !mo || !d || !hh || !mm || !ss) return null;\n // RFC 5545 / Intl edge-case: some runtimes return `hour: \"24\"` for midnight\n // while keeping the same calendar day (instead of returning hour=0 with the\n // next day). Passing 24 straight to Date.UTC would roll the date forward by\n // one day, producing a 24-hour-skewed offset in icsWallclockToUtc and\n // shifting TZID midnight events to the wrong briefing day. Normalise to 0\n // and leave the date component unchanged.\n const normalizedHour = Number(hh) === 24 ? 0 : Number(hh);\n const ms = Date.UTC(Number(y), Number(mo) - 1, Number(d), normalizedHour, Number(mm), Number(ss));\n return Number.isFinite(ms) ? ms : null;\n}\n\n/**\n * Returns true when `isoStr` has an explicit UTC or numeric offset suffix\n * (Z, ±HH:MM, or ±HHMM). Floating datetimes produced by `normalizeIcsDate`\n * have no such suffix.\n */\nfunction isoHasTimezone(isoStr: string): boolean {\n return /(Z|[+-]\\d{2}:?\\d{2})$/.test(isoStr);\n}\n\n/**\n * Parse an ISO datetime string (UTC-aware or floating) to milliseconds since\n * epoch, or `null` if the string is not a valid datetime.\n *\n * - UTC / offset-aware strings are passed directly to `new Date()`.\n * - Floating strings (no timezone suffix) are interpreted as UTC so that\n * interval arithmetic uses the same epoch base as UTC-aware strings.\n * The caller is responsible for using the correct date-boundary constants.\n */\nfunction isoToMs(isoStr: string): number | null {\n if (!isoStr) return null;\n let src = isoStr;\n if (!isoHasTimezone(src)) {\n // Treat floating time as UTC for interval math (append Z).\n src = src + \"Z\";\n }\n const ms = new Date(src).getTime();\n return Number.isFinite(ms) ? ms : null;\n}\n\n/** @internal — exported for testing only. */\nexport function eventFallsOnDate(event: CalendarEvent, dateIso: string): boolean {\n const target = dateIso.slice(0, 10);\n const start = event.start;\n\n // Floating ICS datetime (no Z, no offset): `normalizeIcsDate` produces\n // \"YYYY-MM-DDTHH:MM:SS\" with no timezone. Passing this to `new Date()`\n // causes ECMAScript to parse it as local time, which then round-trips\n // through UTC via `toISOString()` and can shift the calendar date.\n // For floating times we compare date portions directly (no epoch arithmetic).\n const startIsFloating = !isoHasTimezone(start);\n\n if (startIsFloating) {\n // Validate the start timestamp with the same rigour applied to end:\n // 1. Shape check — must match the ISO-8601 date or datetime pattern.\n // 2. Real-date check — round-trip through UTC to reject impossible dates\n // like \"2026-02-30\" that JavaScript silently auto-corrects.\n // 3. Time-component check — reject out-of-range hours/minutes/seconds\n // (e.g. \"2026-04-11T25:99:00\") that JavaScript rolls over to a\n // different day, which would cause the event to be matched against\n // unrelated calendar dates.\n // If start fails any check we skip the event entirely — there is no usable\n // start date to fall back on.\n const startShapeOk =\n typeof start === \"string\" &&\n /^\\d{4}-\\d{2}-\\d{2}(T\\d{2}:\\d{2}(:\\d{2}(\\.\\d+)?)?)?$/.test(start);\n if (!startShapeOk) {\n log.debug(`briefing: skipping calendar event with invalid start value: ${JSON.stringify(start)}`);\n return false;\n }\n const startDateStr = start.slice(0, 10);\n const startDateProbe = new Date(startDateStr + \"T00:00:00Z\");\n if (\n Number.isNaN(startDateProbe.getTime()) ||\n startDateProbe.toISOString().slice(0, 10) !== startDateStr\n ) {\n log.warn(\n `briefing: skipping calendar event \"${event.title}\" with impossible start date ${JSON.stringify(startDateStr)}`,\n );\n return false;\n }\n const startRawTime = start.indexOf(\"T\") !== -1 ? start.slice(start.indexOf(\"T\") + 1) : \"\";\n if (startRawTime !== \"\") {\n const startTimeParts = startRawTime.split(\":\").map(Number);\n const shh = startTimeParts[0] ?? 0;\n const smm = startTimeParts[1] ?? 0;\n const sss = Math.floor(startTimeParts[2] ?? 0);\n if (shh > 23 || smm > 59 || sss > 59) {\n log.warn(\n `briefing: skipping calendar event \"${event.title}\" with out-of-range start time ${JSON.stringify(startRawTime)}`,\n );\n return false;\n }\n }\n\n const startDate = startDateStr;\n const end = event.end;\n\n // Point event (no end) — simple date prefix comparison.\n if (!end) return startDate === target;\n\n // Validate that end is a recognisable ISO-8601 date/datetime string before\n // slicing it for lexicographic comparison. A malformed end (e.g. a JSON\n // feed emitting \"end\": \"invalid\") would otherwise produce a non-date prefix\n // from `end.slice(0, 10)` and cause the event to appear on unrelated days.\n // Fallback: treat the event as a single-day event starting on startDate.\n const endIsValid =\n typeof end === \"string\" &&\n /^\\d{4}-\\d{2}-\\d{2}(T\\d{2}:\\d{2}(:\\d{2}(\\.\\d+)?)?)?$/.test(end);\n if (!endIsValid) {\n log.warn(\n `briefing: event \"${event.title}\" has malformed end timestamp ${JSON.stringify(end)}; treating as single-day event at ${startDate}`,\n );\n // Render the event but only on its start date.\n return startDate === target;\n }\n\n // UhLh: Reject impossible calendar dates that pass the regex (e.g. \"2026-99-99\").\n // The regex only validates the *shape* of the string — it accepts month 99 and\n // day 99. We must additionally verify the date is real by constructing a UTC\n // Date and checking that the ISO round-trip matches the input prefix. If the\n // date is impossible, Date will auto-correct it (e.g. \"2026-01-99\" becomes some\n // later date), so the round-trip will differ. Fall back to single-day semantics.\n const endDate = end.slice(0, 10);\n const endDateProbe = new Date(endDate + \"T00:00:00Z\");\n if (\n Number.isNaN(endDateProbe.getTime()) ||\n endDateProbe.toISOString().slice(0, 10) !== endDate\n ) {\n log.warn(\n `briefing: event \"${event.title}\" has impossible end date ${JSON.stringify(endDate)}; treating as single-day event at ${startDate}`,\n );\n return startDate === target;\n }\n\n // Validate the time components of the end timestamp when present.\n // The regex above only checks the shape (e.g. two digits for hour) but does\n // not enforce numeric ranges. A value like \"2026-04-11T25:99:99\" passes the\n // regex and the date-round-trip check above yet carries an impossible time.\n // JavaScript's Date constructor silently rolls such values over to a later\n // date, which would make the event bleed into unrelated days. Extract the\n // individual time fields and reject anything outside the valid range.\n const rawTime = end.indexOf(\"T\") !== -1 ? end.slice(end.indexOf(\"T\") + 1) : \"\";\n if (rawTime !== \"\") {\n const timeParts = rawTime.split(\":\").map(Number);\n const hh = timeParts[0] ?? 0;\n const mm = timeParts[1] ?? 0;\n // Seconds may carry a fractional component; floor to get the integer part.\n const ss = Math.floor(timeParts[2] ?? 0);\n const timeIsValid = hh <= 23 && mm <= 59 && ss <= 59;\n if (!timeIsValid) {\n log.warn(\n `briefing: event \"${event.title}\" has out-of-range end time ${JSON.stringify(rawTime)}; treating as single-day event at ${startDate}`,\n );\n return startDate === target;\n }\n }\n\n // Span event: include if [start, end) overlaps the target calendar day.\n //\n // We can't use pure YYYY-MM-DD lexicographic comparison because a\n // same-day event (`start=2026-04-11T14:30`, `end=2026-04-11T15:00`)\n // has `startDate === endDate === \"2026-04-11\"`, and a `target < endDate`\n // check would wrongly exclude it. A cross-day event ending at\n // `2026-04-12T00:00:00` (exact midnight) also needs the end day to be\n // treated as exclusive per half-open `[start, end)` semantics.\n //\n // Decide whether the end day is still active on the end date by looking\n // at the time portion: if the end time is strictly after midnight, the\n // event is still running at the start of the end day and should include\n // it; if the end time is exactly midnight, the event ends precisely at\n // the boundary and the end day is excluded. Within-day spans always\n // have a non-zero end time and so correctly include their own date.\n //\n // UhLg: A date-only end value (no \"T\" separator) produces an empty\n // endTime string. The regex above does not match empty string, so\n // endAtExactMidnight would be false and the event would incorrectly\n // appear on the end date. Date-only end values carry [start, end)\n // semantics (the end date is exclusive), so we treat them as midnight.\n const endTime = end.slice(11); // \"HH:MM\", \"HH:MM:SS\", \"HH:MM:SS.mmm\", or \"\" (date-only)\n // Treat any end time that is exactly midnight — or absent (date-only) — as\n // day-exclusive per [start, end) semantics.\n // Cases covered:\n // \"\" — date-only end (UhLg fix: exclusive like midnight)\n // \"00:00\" — HH:MM form (valid floating-time ISO value, no seconds)\n // \"00:00:00\" — HH:MM:SS form\n // \"00:00:00.000...\" — with fractional seconds (any number of trailing zeros)\n // A bare `>` string comparison incorrectly treats \"00:00:00.000\" as > \"00:00:00\"\n // because the fractional suffix makes the string lexicographically longer.\n const endIsDateOnly = endTime === \"\";\n const endAtExactMidnight = endIsDateOnly || /^00(:00){1,2}(\\.0+)?$/.test(endTime);\n const endActiveOnEndDay = !endAtExactMidnight;\n if (endActiveOnEndDay) {\n return startDate <= target && target <= endDate;\n }\n return startDate <= target && target < endDate;\n }\n\n // UTC or offset-aware ISO string: parse and normalise to UTC milliseconds,\n // then check whether the event's [start, end) interval overlaps the target\n // UTC day [dayStart, dayEnd).\n const startMs = isoToMs(start);\n if (startMs === null) {\n log.debug(`briefing: skipping calendar event with invalid start value: ${JSON.stringify(start)}`);\n return false;\n }\n\n // Boundaries of the target UTC day (half-open: [dayStart, dayEnd)).\n const dayStart = Date.UTC(\n Number(target.slice(0, 4)),\n Number(target.slice(5, 7)) - 1,\n Number(target.slice(8, 10)),\n );\n const dayEnd = dayStart + 86_400_000; // +24 h\n\n const end = event.end;\n if (!end) {\n // Point event: included iff start falls within [dayStart, dayEnd).\n return startMs >= dayStart && startMs < dayEnd;\n }\n\n const endMs = isoToMs(end);\n if (endMs === null) {\n // Unparseable end — fall back to point-event semantics.\n return startMs >= dayStart && startMs < dayEnd;\n }\n\n // Interval event: overlaps day iff start < dayEnd AND end > dayStart.\n // Using strict > for end so that an event ending exactly at midnight\n // (dayEnd of previous day) is NOT counted on the next day.\n return startMs < dayEnd && endMs > dayStart;\n}\n\nfunction cryptoRandomId(): string {\n // Keep dependency-free: Math.random is fine for synthetic fixture IDs.\n return `evt-${Math.random().toString(36).slice(2, 10)}`;\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// buildBriefing\n// ──────────────────────────────────────────────────────────────────────────\n\n/** Dependency-injection hook for LLM follow-up generation (used in tests). */\nexport type BriefingFollowupGenerator = (\n prompt: {\n sections: BriefingSections;\n windowLabel: string;\n maxFollowups: number;\n },\n) => Promise<BriefingFollowup[]>;\n\n/** Options accepted by `buildBriefing`. */\nexport interface BuildBriefingOptions {\n /** Workspace-scoped storage. Tests pass a temp dir. */\n storage: StorageManager;\n /** Parsed window. If omitted, a default 1-day window is used. */\n window?: ParsedBriefingWindow;\n /** Optional focus filter. */\n focus?: BriefingFocus | null;\n /** Optional namespace hint for logging. */\n namespace?: string;\n /** Calendar source. Section omitted entirely when undefined. */\n calendarSource?: CalendarSource;\n /** Maximum LLM follow-ups (0 to disable the section). */\n maxFollowups?: number;\n /** Whether the module is allowed to invoke the Responses API. */\n allowLlm?: boolean;\n /** OpenAI API key. If absent the follow-up section is gracefully omitted. */\n openaiApiKey?: string;\n /** OpenAI-compatible base URL (for Azure or proxied endpoints). */\n openaiBaseUrl?: string;\n /** Model id for the Responses call. */\n model?: string;\n /** Injected follow-up generator. Overrides real LLM call (tests). */\n followupGenerator?: BriefingFollowupGenerator;\n /** Injected \"now\" — makes tests deterministic. */\n now?: Date;\n}\n\nconst MAX_ACTIVE_THREADS = 8;\nconst MAX_RECENT_ENTITIES = 8;\nconst MAX_OPEN_COMMITMENTS = 8;\n\n/**\n * Build the daily context briefing.\n *\n * Never throws on LLM failures — the suggested follow-ups section is simply\n * omitted and `followupsUnavailableReason` is set.\n */\nexport async function buildBriefing(options: BuildBriefingOptions): Promise<BriefingResult> {\n const now = options.now ?? new Date();\n const window = options.window ?? defaultWindow(now);\n const maxFollowups = clampFollowups(options.maxFollowups);\n const focus = options.focus ?? null;\n\n const [allMemories, allEntities] = await Promise.all([\n safeReadMemories(options.storage),\n safeReadEntities(options.storage),\n ]);\n\n const memoriesInWindow = filterMemoriesByWindow(allMemories, window);\n const focusedMemories = focus\n ? memoriesInWindow.filter((m) => focusMatchesMemory(m, focus, options.storage.entityAliases))\n : memoriesInWindow;\n\n const activeThreads = buildActiveThreads(focusedMemories);\n const recentEntities = buildRecentEntities(allEntities, window, focus);\n // TODO(#370): openCommitments only covers memories inside the lookback window.\n // Still-open commitments (pending tag, commitment category) that pre-date the\n // window are silently omitted. A separate query over allMemories filtered to\n // open-status entries would surface these. Deferred to avoid scope creep here.\n const openCommitments = buildOpenCommitments(focusedMemories);\n\n const calendarLoadResult = options.calendarSource\n ? await loadTodayCalendar(options.calendarSource, now)\n : undefined;\n\n const calendarSourceErrors: BriefingCalendarSourceError[] =\n calendarLoadResult?.error ? [calendarLoadResult.error] : [];\n\n const sectionsBase: BriefingSections = {\n activeThreads,\n recentEntities,\n openCommitments,\n suggestedFollowups: [],\n todayCalendar: calendarLoadResult?.events,\n };\n\n let followups: BriefingFollowup[] = [];\n let followupsUnavailableReason: string | undefined;\n\n if (maxFollowups === 0 || options.allowLlm === false) {\n followupsUnavailableReason = \"LLM follow-ups disabled by configuration\";\n } else if (!options.openaiApiKey && !options.followupGenerator) {\n followupsUnavailableReason =\n 'no LLM configured for follow-ups (set OPENAI_API_KEY, enable a local LLM, or use modelSource \"gateway\")';\n } else {\n try {\n const generator = options.followupGenerator ?? buildOpenAiFollowupGenerator({\n apiKey: options.openaiApiKey!,\n model: options.model ?? BRIEFING_FOLLOWUP_DEFAULT_MODEL,\n baseURL: options.openaiBaseUrl,\n });\n const generated = await generator({\n sections: sectionsBase,\n windowLabel: window.label,\n maxFollowups,\n });\n followups = generated.slice(0, maxFollowups);\n } catch (err) {\n const errMsg = stringifyError(err);\n const modelName = options.model ?? BRIEFING_FOLLOWUP_DEFAULT_MODEL;\n // Detect \"model not found / invalid\" errors from the Responses API and\n // produce a user-friendly message that surfaces the problematic identifier.\n if (\n /model/i.test(errMsg) &&\n (/not found/i.test(errMsg) || /does not exist/i.test(errMsg) || /invalid/i.test(errMsg))\n ) {\n followupsUnavailableReason =\n `configured follow-up model '${modelName}' is not available in the Responses API`;\n } else {\n followupsUnavailableReason = `LLM follow-ups failed: ${errMsg}`;\n }\n log.warn(`briefing: ${followupsUnavailableReason}`);\n }\n }\n\n const sections: BriefingSections = {\n ...sectionsBase,\n suggestedFollowups: followups,\n };\n\n const windowIso = { from: window.from.toISOString(), to: window.to.toISOString() };\n const markdown = renderBriefingMarkdown({\n sections,\n windowLabel: window.label,\n focus,\n followupsUnavailableReason,\n generatedAt: now,\n namespace: options.namespace,\n });\n\n const json: Record<string, unknown> = {\n generatedAt: now.toISOString(),\n window: windowIso,\n focus,\n namespace: options.namespace ?? null,\n sections,\n followupsUnavailableReason: followupsUnavailableReason ?? null,\n calendarSourceErrors: calendarSourceErrors.length > 0 ? calendarSourceErrors : null,\n };\n\n const result: BriefingResult = {\n markdown,\n json,\n sections,\n followupsUnavailableReason,\n window: windowIso,\n };\n\n if (calendarSourceErrors.length > 0) {\n result.calendarSourceErrors = calendarSourceErrors;\n }\n\n return result;\n}\n\nfunction clampFollowups(value: number | undefined): number {\n if (typeof value !== \"number\" || !Number.isFinite(value)) return 5;\n return Math.max(0, Math.min(10, Math.floor(value)));\n}\n\nfunction defaultWindow(now: Date): ParsedBriefingWindow {\n const parsed = parseBriefingWindow(\"yesterday\", now);\n if (parsed) return parsed;\n return { from: new Date(now.getTime() - DAY_MS), to: now, label: \"yesterday\" };\n}\n\nasync function safeReadMemories(storage: StorageManager): Promise<MemoryFile[]> {\n try {\n return await storage.readAllMemories();\n } catch (err) {\n log.warn(`briefing: readAllMemories failed: ${err}`);\n return [];\n }\n}\n\nasync function safeReadEntities(storage: StorageManager): Promise<EntityFile[]> {\n try {\n return await storage.readAllEntityFiles();\n } catch (err) {\n log.warn(`briefing: readAllEntityFiles failed: ${err}`);\n return [];\n }\n}\n\nfunction memoryTimestamp(memory: MemoryFile): number {\n const raw = memory.frontmatter.updated || memory.frontmatter.created;\n if (!raw) return 0;\n const t = Date.parse(raw);\n return Number.isFinite(t) ? t : 0;\n}\n\n/** @internal — exported for testing only. */\nexport function filterMemoriesByWindow(memories: MemoryFile[], window: ParsedBriefingWindow): MemoryFile[] {\n const fromMs = window.from.getTime();\n const toMs = window.to.getTime();\n return memories.filter((m) => {\n // Exclude explicitly retired statuses so commitments overridden within the\n // window don't appear as open. In addition to `superseded` / `archived`\n // (temporal retirement), also exclude `rejected` and `quarantined`, which\n // come from governance/disposition workflows: those memories have been\n // explicitly marked unsafe or invalid and must NOT flow into active\n // threads, open commitments, or follow-up generation, even if they\n // fall within the briefing window. Surfacing them would reintroduce\n // quarantined content into downstream automation as actionable context.\n //\n // `pending_review` memories are awaiting human review — not invalidated —\n // and must be included so reviewers see them in the briefing.\n const status = m.frontmatter.status;\n if (\n status === \"superseded\" ||\n status === \"archived\" ||\n status === \"rejected\" ||\n status === \"quarantined\" ||\n status === \"forgotten\"\n ) {\n return false;\n }\n const ts = memoryTimestamp(m);\n return ts >= fromMs && ts < toMs;\n });\n}\n\n/** @internal — exported for testing only. */\nexport function buildActiveThreads(memories: MemoryFile[]): BriefingActiveThread[] {\n const buckets = new Map<string, BriefingActiveThread>();\n for (const memory of memories) {\n const threadKey = extractThreadKey(memory);\n const updatedAt = memory.frontmatter.updated || memory.frontmatter.created || \"\";\n const existing = buckets.get(threadKey);\n if (!existing || updatedAt > existing.updatedAt) {\n buckets.set(threadKey, {\n id: threadKey,\n title: summarizeContentTitle(memory),\n updatedAt,\n // Always derive reason from the newest memory so the description\n // reflects the most-recent activity type, not the first memory seen.\n reason: describeReason(memory),\n });\n }\n }\n return Array.from(buckets.values())\n .sort((a, b) => {\n if (a.updatedAt > b.updatedAt) return -1;\n if (a.updatedAt < b.updatedAt) return 1;\n // Tiebreaker: lexicographic order by id ensures a deterministic, stable\n // result when multiple threads share the same updatedAt timestamp (e.g.\n // after a batch extraction run).\n return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;\n })\n .slice(0, MAX_ACTIVE_THREADS);\n}\n\nfunction extractThreadKey(memory: MemoryFile): string {\n const entityRef = memory.frontmatter.entityRef?.trim();\n if (entityRef) return `entity:${entityRef}`;\n const tags = memory.frontmatter.tags ?? [];\n const topicTag = tags.find((t) => t.startsWith(\"topic:\"));\n if (topicTag) return topicTag;\n if (tags.length > 0) return `tag:${tags[0]}`;\n return `memory:${memory.frontmatter.id}`;\n}\n\nfunction summarizeContentTitle(memory: MemoryFile): string {\n const firstLine = (memory.content || \"\").split(\"\\n\").find((line) => line.trim().length > 0) ?? \"\";\n const trimmed = firstLine.trim();\n if (trimmed.length === 0) return memory.frontmatter.id;\n return trimmed.length > 120 ? `${trimmed.slice(0, 117)}...` : trimmed;\n}\n\nfunction describeReason(memory: MemoryFile): string {\n const cat = memory.frontmatter.category;\n if (cat === \"commitment\") return \"open commitment\";\n if (cat === \"decision\") return \"recent decision\";\n if (cat === \"correction\") return \"recent correction\";\n return \"recent activity\";\n}\n\n/** @internal — exported for testing only. */\nexport function buildRecentEntities(\n entities: EntityFile[],\n window: ParsedBriefingWindow,\n focus: BriefingFocus | null,\n): BriefingRecentEntity[] {\n const fromMs = window.from.getTime();\n const scored: BriefingRecentEntity[] = [];\n const now = window.to;\n for (const entity of entities) {\n if (focus && !focusMatchesEntity(entity, focus)) continue;\n const toMs = window.to.getTime();\n const updatedMs = entity.updated ? Date.parse(entity.updated) : 0;\n if (!Number.isFinite(updatedMs) || updatedMs < fromMs || updatedMs >= toMs) continue;\n const score = StorageManager.scoreEntity(entity, now);\n scored.push({\n name: entity.name,\n type: entity.type,\n updatedAt: entity.updated,\n score: Number(score.toFixed(4)),\n summary: entity.synthesis || entity.summary,\n });\n }\n return scored\n .sort((a, b) => {\n const scoreDiff = b.score - a.score;\n if (scoreDiff !== 0) return scoreDiff;\n if (a.updatedAt > b.updatedAt) return -1;\n if (a.updatedAt < b.updatedAt) return 1;\n return 0;\n })\n .slice(0, MAX_RECENT_ENTITIES);\n}\n\nfunction buildOpenCommitments(memories: MemoryFile[]): BriefingOpenCommitment[] {\n const commitments: BriefingOpenCommitment[] = [];\n\n for (const memory of memories) {\n const tags = memory.frontmatter.tags ?? [];\n const isPending = tags.some((t) => t.toLowerCase() === \"pending\");\n const isCommitment = memory.frontmatter.category === \"commitment\";\n const isUnresolvedQuestion = /(?:\\?$|\\bfollow[- ]up\\b|\\btodo\\b)/i.test(memory.content);\n\n if (isPending || isCommitment || isUnresolvedQuestion) {\n const kind: BriefingOpenCommitment[\"kind\"] = isCommitment\n ? \"commitment\"\n : isUnresolvedQuestion\n ? \"question\"\n : \"pending_memory\";\n commitments.push({\n id: memory.frontmatter.id,\n kind,\n text: summarizeContentTitle(memory),\n source: memory.frontmatter.source,\n createdAt: memory.frontmatter.created,\n });\n }\n }\n\n return commitments\n .sort((a, b) => {\n // Missing timestamps sort last (highest comparator value).\n if (!a.createdAt && !b.createdAt) return 0;\n if (!a.createdAt) return 1;\n if (!b.createdAt) return -1;\n if (a.createdAt > b.createdAt) return -1;\n if (a.createdAt < b.createdAt) return 1;\n return 0;\n })\n .slice(0, MAX_OPEN_COMMITMENTS);\n}\n\ninterface CalendarLoadResult {\n events: CalendarEvent[] | undefined;\n error: BriefingCalendarSourceError | undefined;\n}\n\nasync function loadTodayCalendar(\n source: CalendarSource,\n now: Date,\n): Promise<CalendarLoadResult> {\n const sourceLabel = (source as { filePath?: string }).filePath ?? \"calendar\";\n try {\n const dateIso = now.toISOString().slice(0, 10);\n const events = await source.eventsForDate(dateIso);\n // Return the events array (possibly empty for a legitimately empty calendar).\n // An empty array is distinct from `undefined`: empty means \"source responded\n // with no events today\"; undefined means \"source failed\".\n return { events, error: undefined };\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n log.warn(`briefing: calendar source error (${sourceLabel}): ${message}`);\n // Return undefined events (not []) to signal an error so callers can\n // distinguish \"no events today\" from \"the calendar source threw\".\n return {\n events: undefined,\n error: { source: sourceLabel, error: message },\n };\n }\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// Follow-ups (Responses API)\n// ──────────────────────────────────────────────────────────────────────────\n\nfunction buildOpenAiFollowupGenerator(cfg: {\n apiKey: string;\n model: string;\n baseURL?: string;\n}): BriefingFollowupGenerator {\n return async ({ sections, windowLabel, maxFollowups }) => {\n // Lazy import keeps the module dependency-free when LLM path is unused.\n const { OpenAI } = (await import(\"openai\")) as {\n OpenAI: new (opts: { apiKey: string; baseURL?: string }) => unknown;\n };\n const clientOpts: { apiKey: string; baseURL?: string } = { apiKey: cfg.apiKey };\n if (cfg.baseURL) clientOpts.baseURL = cfg.baseURL;\n const client = new OpenAI(clientOpts) as {\n responses: {\n create: (args: {\n model: string;\n instructions: string;\n input: string;\n max_output_tokens?: number;\n }) => Promise<{ output_text?: string }>;\n };\n };\n\n const prompt = buildFollowupPrompt(sections, windowLabel, maxFollowups);\n const response = await client.responses.create({\n model: cfg.model,\n instructions: FOLLOWUP_INSTRUCTIONS,\n input: prompt,\n max_output_tokens: 512,\n });\n\n const text = typeof response.output_text === \"string\" ? response.output_text : \"\";\n return parseFollowupResponse(text, maxFollowups);\n };\n}\n\n/**\n * Minimal chat-completion surface shared by `FallbackLlmClient` (gateway\n * model chain) and `LocalLlmClient` (Ollama / OpenAI-compatible local\n * endpoints). Matches `Orchestrator.fastLlmForRerank` so briefing\n * follow-ups can ride the same routing as other fast-tier operations.\n */\nexport interface BriefingChainLlmClient {\n chatCompletion(\n messages: Array<{ role: \"system\" | \"user\" | \"assistant\"; content: string }>,\n options?: {\n temperature?: number;\n maxTokens?: number;\n timeoutMs?: number;\n operation?: string;\n priority?: \"background\" | \"recall-critical\";\n },\n ): Promise<{ content: string } | null>;\n}\n\n/**\n * Build a follow-up generator backed by the configured LLM chain\n * (gateway model source or local LLM) instead of a direct OpenAI key.\n *\n * Local models frequently wrap JSON in code fences or prose, so the\n * response is run through `extractJsonCandidates` and the first candidate\n * that parses into a valid `{ followups: [...] }` shape wins. Throws when\n * the chain returns nothing or no candidate parses — `buildBriefing`\n * catches and surfaces the message via `followupsUnavailableReason`.\n */\nexport function buildChainFollowupGenerator(\n client: BriefingChainLlmClient,\n): BriefingFollowupGenerator {\n return async ({ sections, windowLabel, maxFollowups }) => {\n const prompt = buildFollowupPrompt(sections, windowLabel, maxFollowups);\n const response = await client.chatCompletion(\n [\n { role: \"system\", content: FOLLOWUP_INSTRUCTIONS },\n { role: \"user\", content: prompt },\n ],\n {\n temperature: 0.2,\n maxTokens: 512,\n operation: \"briefing-followups\",\n priority: \"background\",\n },\n );\n if (!response?.content) {\n throw new Error(\"LLM chain returned no response\");\n }\n const candidates = extractJsonCandidates(response.content);\n let lastError: unknown;\n for (const candidate of candidates) {\n try {\n return parseFollowupResponse(candidate, maxFollowups);\n } catch (err) {\n lastError = err;\n }\n }\n throw new Error(\n `LLM chain response contained no valid followups JSON: ${stringifyError(lastError ?? \"no JSON candidates found\")}`,\n );\n };\n}\n\nconst FOLLOWUP_INSTRUCTIONS = `You suggest short follow-up prompts for a daily context briefing.\nReturn strict JSON of the form { \"followups\": [{ \"text\": \"...\", \"rationale\": \"...\" }] }.\nRules:\n- Never invent facts absent from the input.\n- Keep each \"text\" under 140 characters.\n- Prefer concrete, action-oriented phrasing.\n- Omit duplicates. Avoid filler.`;\n\nfunction buildFollowupPrompt(\n sections: BriefingSections,\n windowLabel: string,\n maxFollowups: number,\n): string {\n const lines: string[] = [];\n lines.push(`Window: ${windowLabel}`);\n lines.push(`Desired follow-ups: ${maxFollowups}`);\n lines.push(\"\");\n lines.push(\"Active threads:\");\n for (const t of sections.activeThreads) lines.push(`- ${t.title} (${t.reason})`);\n lines.push(\"\");\n lines.push(\"Recent entities:\");\n for (const e of sections.recentEntities) lines.push(`- ${e.name} [${e.type}]`);\n lines.push(\"\");\n lines.push(\"Open commitments:\");\n for (const c of sections.openCommitments) lines.push(`- [${c.kind}] ${c.text}`);\n return lines.join(\"\\n\");\n}\n\nfunction parseFollowupResponse(raw: string, max: number): BriefingFollowup[] {\n // JSON.parse throws on invalid JSON — let the caller catch it so the outer\n // try/catch in buildBriefing can set followupsUnavailableReason rather than\n // silently returning an empty array that masks the parse failure.\n const candidates = extractJsonCandidates(raw);\n let lastError: unknown;\n for (const candidate of candidates) {\n try {\n const parsed = JSON.parse(candidate) as unknown;\n if (!parsed || typeof parsed !== \"object\") {\n throw new Error(`LLM returned non-object JSON: ${typeof parsed}`);\n }\n const arr = (parsed as { followups?: unknown }).followups;\n if (!Array.isArray(arr)) {\n throw new Error(`LLM response missing \"followups\" array`);\n }\n const out: BriefingFollowup[] = [];\n for (const entry of arr) {\n if (!entry || typeof entry !== \"object\") continue;\n const text = (entry as Record<string, unknown>).text;\n if (typeof text !== \"string\" || text.trim().length === 0) continue;\n const rationale = (entry as Record<string, unknown>).rationale;\n out.push({\n text: text.trim(),\n rationale: typeof rationale === \"string\" ? rationale.trim() : undefined,\n });\n if (out.length >= max) break;\n }\n return out;\n } catch (err) {\n lastError = err;\n }\n }\n if (lastError) throw lastError;\n throw new Error(\"LLM response contained no JSON candidates\");\n}\n\nfunction stringifyError(err: unknown): string {\n if (err instanceof Error) return err.message;\n return String(err);\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// Markdown rendering\n// ──────────────────────────────────────────────────────────────────────────\n\ninterface RenderContext {\n sections: BriefingSections;\n windowLabel: string;\n focus: BriefingFocus | null;\n followupsUnavailableReason?: string;\n generatedAt: Date;\n namespace?: string;\n}\n\nexport function renderBriefingMarkdown(ctx: RenderContext): string {\n const lines: string[] = [];\n lines.push(`# Daily Context Briefing`);\n lines.push(\"\");\n lines.push(`_Generated ${ctx.generatedAt.toISOString()} (window: ${ctx.windowLabel})_`);\n if (ctx.focus) {\n lines.push(`_Focus: ${ctx.focus.type}:${ctx.focus.value}_`);\n }\n if (ctx.namespace) {\n lines.push(`_Namespace: ${ctx.namespace}_`);\n }\n lines.push(\"\");\n\n lines.push(`## Active threads`);\n if (ctx.sections.activeThreads.length === 0) {\n lines.push(`_No active threads in window._`);\n } else {\n for (const t of ctx.sections.activeThreads) {\n lines.push(`- **${t.title}** — ${t.reason} (updated ${t.updatedAt})`);\n }\n }\n lines.push(\"\");\n\n lines.push(`## Recent entities`);\n if (ctx.sections.recentEntities.length === 0) {\n lines.push(`_No entities updated in window._`);\n } else {\n for (const e of ctx.sections.recentEntities) {\n const summary = e.summary ? ` — ${e.summary}` : \"\";\n lines.push(`- **${e.name}** (${e.type}, score ${e.score})${summary}`);\n }\n }\n lines.push(\"\");\n\n lines.push(`## Open commitments`);\n if (ctx.sections.openCommitments.length === 0) {\n lines.push(`_No open commitments detected._`);\n } else {\n for (const c of ctx.sections.openCommitments) {\n lines.push(`- [${c.kind}] ${c.text}`);\n }\n }\n lines.push(\"\");\n\n lines.push(`## Suggested follow-ups`);\n if (ctx.followupsUnavailableReason) {\n lines.push(`_Unavailable: ${ctx.followupsUnavailableReason}_`);\n } else if (ctx.sections.suggestedFollowups.length === 0) {\n lines.push(`_No follow-ups suggested._`);\n } else {\n for (const f of ctx.sections.suggestedFollowups) {\n const rationale = f.rationale ? ` _(${f.rationale})_` : \"\";\n lines.push(`- ${f.text}${rationale}`);\n }\n }\n lines.push(\"\");\n\n if (ctx.sections.todayCalendar !== undefined) {\n lines.push(`## Today's calendar`);\n if (ctx.sections.todayCalendar.length === 0) {\n lines.push(`_No events on the calendar today._`);\n } else {\n for (const ev of ctx.sections.todayCalendar) {\n const end = ev.end ? ` → ${ev.end}` : \"\";\n const loc = ev.location ? ` @ ${ev.location}` : \"\";\n lines.push(`- **${ev.title}** (${ev.start}${end})${loc}`);\n }\n }\n lines.push(\"\");\n }\n\n return lines.join(\"\\n\").trimEnd() + \"\\n\";\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// Save helpers\n// ──────────────────────────────────────────────────────────────────────────\n\n/**\n * Resolve the directory where `--save` writes dated briefings.\n * Respects the following precedence:\n * 1. explicit `configOverride` argument\n * 2. `$REMNIC_HOME/briefings/`\n * 3. `$HOME/.remnic/briefings/`\n */\nexport function resolveBriefingSaveDir(\n configOverride: string | null | undefined,\n env?: NodeJS.ProcessEnv,\n): string {\n if (typeof configOverride === \"string\" && configOverride.trim().length > 0) {\n return path.resolve(configOverride.trim());\n }\n const remnicHome = (env === undefined ? readEnvVar(\"REMNIC_HOME\") : env.REMNIC_HOME)?.trim();\n if (remnicHome && remnicHome.length > 0) {\n return path.join(remnicHome, \"briefings\");\n }\n const home = env === undefined\n ? resolveHomeDir()\n : env.HOME ?? env.USERPROFILE ?? os.homedir();\n return path.join(home, \".remnic\", \"briefings\");\n}\n\n/** Format the dated filename for a given briefing. */\nexport function briefingFilename(date: Date, format: \"markdown\" | \"json\" = \"markdown\"): string {\n const day = date.toISOString().slice(0, 10);\n return format === \"json\" ? `${day}.json` : `${day}.md`;\n}\n"],"mappings":";;;;;;;;;;;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AAI,cAAc,WAAW,SAAS,GAAG;AACvC,WAAO,KAAK,KAAK,YAAY,WAAW;AAAA,EAC1C;AACA,QAAM,OAAO,QAAQ,SACjB,eAAe,IACf,IAAI,QAAQ,IAAI,eAAe,GAAG,QAAQ;AAC9C,SAAO,KAAK,KAAK,MAAM,WAAW,WAAW;AAC/C;AAGO,SAAS,iBAAiB,MAAY,SAA8B,YAAoB;AAC7F,QAAM,MAAM,KAAK,YAAY,EAAE,MAAM,GAAG,EAAE;AAC1C,SAAO,WAAW,SAAS,GAAG,GAAG,UAAU,GAAG,GAAG;AACnD;","names":["from","end"]}
|
|
@@ -6,7 +6,7 @@ import {
|
|
|
6
6
|
} from "./chunk-SFQ6QNL7.js";
|
|
7
7
|
import {
|
|
8
8
|
StorageManager
|
|
9
|
-
} from "./chunk-
|
|
9
|
+
} from "./chunk-4PLOQDBB.js";
|
|
10
10
|
import {
|
|
11
11
|
buildLifecycleEventsForMemory,
|
|
12
12
|
sortMemoryLifecycleEvents
|
|
@@ -74,4 +74,4 @@ export {
|
|
|
74
74
|
backupExistingLedger,
|
|
75
75
|
rebuildMemoryLifecycleLedger
|
|
76
76
|
};
|
|
77
|
-
//# sourceMappingURL=chunk-
|
|
77
|
+
//# sourceMappingURL=chunk-MBZAESQ3.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
NamespaceStorageRouter
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-JI3LQFJH.js";
|
|
4
4
|
import {
|
|
5
5
|
namespaceCollectionName
|
|
6
6
|
} from "./chunk-EKQMQQ3U.js";
|
|
@@ -10,7 +10,7 @@ import {
|
|
|
10
10
|
} from "./chunk-ZFXCQPNO.js";
|
|
11
11
|
import {
|
|
12
12
|
ALL_CATEGORY_DIRS
|
|
13
|
-
} from "./chunk-
|
|
13
|
+
} from "./chunk-4PLOQDBB.js";
|
|
14
14
|
import {
|
|
15
15
|
isSafeRouteNamespace
|
|
16
16
|
} from "./chunk-U3PN77QT.js";
|
|
@@ -204,4 +204,4 @@ export {
|
|
|
204
204
|
verifyNamespaces,
|
|
205
205
|
runNamespaceMigration
|
|
206
206
|
};
|
|
207
|
-
//# sourceMappingURL=chunk-
|
|
207
|
+
//# sourceMappingURL=chunk-QFKRE7AU.js.map
|
|
@@ -4,7 +4,7 @@ import {
|
|
|
4
4
|
} from "./chunk-DRD2Q7HQ.js";
|
|
5
5
|
import {
|
|
6
6
|
StorageManager
|
|
7
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-4PLOQDBB.js";
|
|
8
8
|
import {
|
|
9
9
|
parseContinuityImprovementLoops
|
|
10
10
|
} from "./chunk-LDXUBPMO.js";
|
|
@@ -1261,4 +1261,4 @@ export {
|
|
|
1261
1261
|
defaultTierMigrationCycleBudget,
|
|
1262
1262
|
CompoundingEngine
|
|
1263
1263
|
};
|
|
1264
|
-
//# sourceMappingURL=chunk-
|
|
1264
|
+
//# sourceMappingURL=chunk-RVT6U6PV.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
StorageManager
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-4PLOQDBB.js";
|
|
4
4
|
import {
|
|
5
5
|
getCachedRuleMemories,
|
|
6
6
|
setCachedRuleMemories
|
|
@@ -117,4 +117,4 @@ export {
|
|
|
117
117
|
compareVerifiedSemanticRuleResults,
|
|
118
118
|
searchVerifiedSemanticRules
|
|
119
119
|
};
|
|
120
|
-
//# sourceMappingURL=chunk-
|
|
120
|
+
//# sourceMappingURL=chunk-VJYFXDCZ.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
StorageManager
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-4PLOQDBB.js";
|
|
4
4
|
import {
|
|
5
5
|
decideLifecycleTransition
|
|
6
6
|
} from "./chunk-TBBDFYXW.js";
|
|
@@ -729,4 +729,4 @@ export {
|
|
|
729
729
|
listMemoryGovernanceRuns,
|
|
730
730
|
readMemoryGovernanceRunArtifact
|
|
731
731
|
};
|
|
732
|
-
//# sourceMappingURL=chunk-
|
|
732
|
+
//# sourceMappingURL=chunk-ZCMO46YY.js.map
|